forked from AdmiralenOla/Scoary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
methods.py
1716 lines (1554 loc) · 70.6 KB
/
methods.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Script for associating Roary output with phenotypic trait (+/-)
# Idea and implementation: Ola Brynildsrud ([email protected])
# Null hypothesis: Gene is equally distributed in Trait+ and Trait-
# isolates
import argparse
import sys
import csv
import time
import random
import logging
import re
from multiprocessing import Pool, Value
from scipy import stats as ss
from scipy import spatial
from .citation import citation
from .classes import Matrix
from .classes import QuadTree
from .classes import PhyloTree
from .classes import PimpedFileHandler
from .classes import ScoaryLogger
from .__init__ import __version__
#import scoary
import os
from pkg_resources import resource_string, resource_filename
#SCOARY_VERSION = scoary.__version__
SCOARY_VERSION = __version__
# Python 2/3 annoyances
try:
xrange
except NameError:
xrange = range
# Set up log and message flow
log = ScoaryLogger(logging.getLogger('scoary'))
log.setLevel(logging.DEBUG)
logformat = '%(asctime)s %(message)s'
logdatefmt='%m/%d/%Y %I:%M:%S %p'
formatter = logging.Formatter(fmt=logformat,datefmt=logdatefmt)
def main(**kwargs):
"""
The main function of Scoary.
"""
# If main has been ran from the GUI, then args already exists
if len(kwargs) == 0:
args, cutoffs = ScoaryArgumentParser()
else:
args = kwargs["args"]
cutoffs = kwargs["cutoffs"]
sys.stdout = kwargs["statusbar"]
# If the citation arg has been passed, nothing should be done except
# a call to citation
if args.citation:
sys.exit(citation())
# If the test argument was used, all settings are overrided and
# defaulted
if args.test:
args.correction = ['I','EPW']
args.delimiter = ','
args.genes = os.path.join(
resource_filename(__name__, 'exampledata'),
'Gene_presence_absence.csv')
args.grabcols = [-999]
args.max_hits = None
args.newicktree = None
args.no_pairwise = False
args.outdir = './'
args.permute = 0
args.p_value_cutoff = [0.05,0.05]
args.restrict_to = None
args.start_col = 15
args.threads = 4
args.traits = os.path.join(
resource_filename(__name__, 'exampledata'),
'Tetracycline_resistance.csv')
args.upgma_tree = True
args.write_reduced = False
args.no_time = False
args.collapse = False
cutoffs = {"I": 0.05, "EPW": 0.05}
# Start clock
starttime = time.time()
# currenttime is ONLY used to append to filenames, therefore, it
# is set empty if args.no_time is True
if args.no_time:
currenttime = ""
else:
currenttime = time.strftime("_%d_%m_%Y_%H%M")
# Outdir should end with slash
if not args.outdir.endswith("/"):
args.outdir += "/"
# Initiate console from sys.stdout (which might be a statusbar)
console = logging.StreamHandler(sys.stdout)
console.setFormatter(logging.Formatter('%(message)s'))
console.setLevel(logging.INFO)
log.addHandler(console)
# Create log file
log_filename = os.path.join(args.outdir,
"scoary%s.log" % currenttime)
log_handler = PimpedFileHandler(log_filename, mode='w')
log_handler.setFormatter(formatter)
log.addHandler(log_handler)
log.info("==== Scoary started ====")
log.info("Command: " + " ".join(sys.argv))
# Catch all system exceptions from here on out
try:
# Perform tests to make sure all input is okay
if args.traits is None or args.genes is None:
sys.exit(("The following arguments are required: -t/--traits, "
"-g/--genes"))
if args.threads <= 0:
sys.exit("Number of threads must be positive")
if not os.path.isfile(args.traits):
sys.exit("Could not find the traits file: %s" % args.traits)
if not os.path.isfile(args.genes):
sys.exit("Could not find the gene presence absence file: %s"
% args.genes)
if ((args.newicktree is not None) and
(not os.path.isfile(args.newicktree))):
sys.exit("Could not find the custom tree file: %s"
% args.newicktree)
if not all( [(p <= 1.0 and p > 0.0) for p in args.p_value_cutoff] ):
sys.exit("P must be between 0.0 and 1.0 or exactly 1.0")
if (len(args.delimiter) > 1):
sys.exit("Delimiter must be a single character string. "
"There is no support for tab.")
if ((len(args.p_value_cutoff) != len(args.correction)) and
(len(args.p_value_cutoff) != 1)):
sys.exit("You can not use more p-value cutoffs than correction "
"methods. Either provide a single p-value that will be applied "
"to all correction methods, or provide exactly as many as the "
"number of correction methods and in corresponding sequence. "
"e.g. -c I EPW -p 0.1 0.05 will apply an individual p-value "
"cutoff of 0.1 AND a pairwise comparisons p-value cutoff of "
"0.05.")
if "P" in cutoffs and args.permute == 0:
sys.exit("Cannot use empirical p-values in filtration without "
"performing permutations. Use '--permute X' where X is a "
"number equal to or larger than 10")
if args.permute < 10 and args.permute != 0:
sys.exit("The absolute minimum number of permutations is 10 "
"(or 0 to deactivate)")
elif args.permute > 0:
try:
random.shuffle
except:
sys.exit("Unable to find random.shuffle. Can not proceed "
"with permutations")
if "P" in cutoffs:
if cutoffs["P"] < (1.0/args.permute):
sys.exit("Permutation cutoff too low for this number of "
"permutations")
if args.permute > 10000:
log.info("Note: You have set Scoary to do a high number of "
"permutations. This may take a while.")
if args.no_pairwise:
log.info("Performing no pairwise comparisons. Ignoring all "
"tree related options (user tree, population aware-correction, "
"permutations).")
args.permute = 0
args.newicktree = None
for m in ["PW","EPW","P"]:
cutoffs.pop(m,None)
# Start analysis
with open(args.genes, "rU") as genes, \
open(args.traits, "rU") as traits:
if args.restrict_to is not None:
# Note: Despite being a dictionary, the values of
# allowed_isolates are not currently used, only the keys
allowed_isolates = {isolate : "all"
for line in
open(args.restrict_to,"rU")
for isolate in line.rstrip().split(",")}
else:
# Despite the confusing name
# this actually means all isolates are allowed
# and included in the analysis
allowed_isolates = None
if args.write_reduced:
sys.exit("You cannot use the -w argument without "
"specifying a subset (-r)")
log.info("Reading gene presence absence file")
genedic_and_matrix = \
Csv_to_dic_Roary(genes,
args.delimiter,
args.grabcols,
startcol=int(args.start_col) - 1,
allowed_isolates=allowed_isolates,
writereducedset=args.write_reduced,
time=currenttime,
outdir=args.outdir)
genedic = genedic_and_matrix["Roarydic"]
zeroonesmatrix = genedic_and_matrix["Zero_ones_matrix"]
strains = genedic_and_matrix["Strains"]
extracolstoprint = genedic_and_matrix["Extracols"]
# Create or load tree (No need for tree if --no_pairwise)
if (args.newicktree) is None and not (args.no_pairwise):
log.info("Creating Hamming distance matrix based on gene "
"presence/absence")
TDM = CreateTriangularDistanceMatrix(zeroonesmatrix,
strains)
QT = PopulateQuadTreeWithDistances(TDM)
log.info("Building UPGMA tree from distance matrix")
upgmatree = upgma(QT)
elif (args.no_pairwise):
# Performing --no_pairwise analysis
log.info("Ignoring relatedness among input sample and "
"performing only population structure-naive analysis.")
upgmatree = None
else:
log.info("Reading custom tree file")
from .nwkhandler import ReadTreeFromFile
upgmatree, members = ReadTreeFromFile(args.newicktree)
if (sorted(strains) != sorted(members)):
# There could be two reasons for this. Either (a) that
# the gene presence absence file and the tree file does
# not have the same isolates or (b) that the -r flag has
# been used.
if args.restrict_to is None:
sys.exit("CRITICAL: Please make sure that isolates in "
"your custom tree match those in your gene "
"presence absence file.")
else:
# Verify that the all isolates in strains (from GPA
# file) are in members (from tree), and if so prune
# tree of extraneous isolates. Else, call an error
if (all(i in members for i in strains)):
# Prune tree of the extraneous isolates
log.info("Pruning phylogenetic tree to correspond "
"to set of included isolates")
Prune = [i for i in members if
i not in strains]
upgmatree = PruneForMissing(upgmatree, Prune)
else:
sys.exit("CRITICAL: Your provided tree file did "
"not contain all the isolates in your gene "
"presence absence file.")
log.info("Reading traits file")
traitsdic, Prunedic = Csv_to_dic(traits,
args.delimiter,
allowed_isolates,
strains)
log.info("Finished loading files into memory.\n\n")
log.info("==== Performing statistics ====")
filtopts = filtrationoptions(cutoffs, args.collapse)
for line in filtopts:
log.info(line)
log.info("Tallying genes and performing statistical analyses")
RES_and_GTC = Setup_results(genedic, traitsdic, args.collapse)
RES = RES_and_GTC["Results"]
GTC = RES_and_GTC["Gene_trait_combinations"]
if args.upgma_tree:
StoreUPGMAtreeToFile(upgmatree,
args.outdir,
time=currenttime)
StoreResults(RES,
args.max_hits,
cutoffs,
upgmatree,
GTC,
Prunedic,
args.outdir,
args.permute,
args.threads,
args.no_pairwise,
genedic,
extracolstoprint,
time=currenttime,
delimiter=args.delimiter)
log.info("\n")
log.info("==== Finished ====")
log.info("Checked a total of %d genes for "
"associations to %d trait(s). Total time used: %d "
"seconds." % (len(genedic),
len(traitsdic),
int(time.time()-starttime)))
except SystemExit as e:
exc_type, exc_value, _ = sys.exc_info()
log.exception("CRITICAL:")
log.removeHandler(log_handler)
log.removeHandler(console)
sys.exit(exc_value)
if log.critical.called > 0:
log.info("Scoary finished successfully, but with CRITICAL ERRORS. "
"Please check your log file.")
elif log.error.called > 0:
log.info("Scoary finished successfully, but with ERRORS. Please check "
"your log file.")
elif log.warning.called > 0:
log.info("Scoary finished successfully, but with WARNINGS. Please "
"check your log file.")
else:
log.info("No warnings were recorded.")
log.removeHandler(log_handler)
log.removeHandler(console)
sys.exit(0)
###############################
# FUNCTIONS FOR READING INPUT #
###############################
def Csv_to_dic_Roary(genefile, delimiter, grabcols, startcol=14,
allowed_isolates=None, writereducedset=False, time="",
outdir="./"):
"""
Converts a gene presence/absence file into dictionaries
that are readable by Scoary.
"""
r = {}
if writereducedset:
file = open(ReduceSet(genefile,delimiter, grabcols, startcol,
allowed_isolates,time,outdir),"rU")
csvfile = csv.reader(file, skipinitialspace=True,
delimiter=delimiter)
else:
csvfile = csv.reader(genefile, skipinitialspace=True,
delimiter=delimiter)
header = next(csvfile)
# If include all relevant columns, grabcols == -999
if grabcols == [-999]:
grabcols = list(range(3,len(header)))
try:
header[startcol]
except IndexError:
sys.exit("The startcol (-s) you have specified does not seem to "
"correspond to any column in your gene presence/absence file.")
strains = header[startcol:]
extracolstoprint = [header[c] for c in grabcols]
# Include alternative column spellings
Roarycols = ["Gene", "Non-unique Gene name", "Annotation",
"No. isolates", "No. sequences",
"Avg sequences per isolate", "Genome Fragment",
"Order within Fragment", "Accessory Fragment",
"Accessory Order with Fragment", "QC",
"Min group size nuc", "Max group size nuc",
"Avg group size nuc", "Order within fragment",
"Genome fragment", "Accessory fragment" ]
if header[0:3] == Roarycols[0:3]:
roaryfile = True
else:
roaryfile = False
# Move forwards from startcol to find correct startcol
if strains[0] in Roarycols and roaryfile:
for c in xrange(len(strains)):
if strains[c] not in Roarycols:
correctstartcol = startcol + c
break
log.error("ERROR: Make sure you have set the -s parameter "
"correctly. You are running with -s %s. This correponds to the "
"column %s. If this is not an isolate, Scoary might crash or "
"produce strange results. Scoary thinks you should have run "
"with -s %s instead" % (str(startcol+1),
strains[0],
str(correctstartcol + 1)))
if roaryfile:
# Move backwards from startcol to find correct startcol
Firstcols = header[:startcol][::-1]
minus = 0
Censored_isolates = []
for c in xrange(len(Firstcols)):
if Firstcols[c] not in Roarycols:
minus += 1
Censored_isolates.append(Firstcols[c])
else:
if minus > 0:
correctstartcol = startcol - minus
log.error("ERROR: Make sure you have set the -s "
"parameter correctly. You are running with -s %s. "
"Scoary thinks you should have used %s. This excludes "
"the following, which Scoary thinks are isolates: %s" %
(str(startcol+1),
str(correctstartcol+1),
", ".join(Censored_isolates)))
break
if allowed_isolates is not None:
strain_names_allowed = [val for val in strains
if val in allowed_isolates.keys()]
else:
strain_names_allowed = strains
zero_ones_matrix = []
try:
genecol = header.index("Gene")
nugcol = header.index("Non-unique Gene name")
anncol = header.index("Annotation")
except ValueError:
log.error("ERROR: Could not properly detect the correct names "
"for all columns in the ROARY table.")
genecol = 0
nugcol = 1
anncol = 2
for line in csvfile:
q = line
try:
r[q[genecol]] = ({"Non-unique Gene name": q[nugcol],
"Annotation": q[anncol]}
if roaryfile
else {})
except IndexError:
sys.exit("CRITICAL: Could not read gene presence absence "
"file. Verify that this file is a proper Roary file using "
"the specified delimiter (default is ',').")
# The zero_ones_line variable represents the presence (1) or
# absence (0) of a gene. It is used for calculating distances
# between strains.
zero_ones_line = []
for strain in xrange(len(strains)):
if (allowed_isolates is not None):
if strains[strain] not in allowed_isolates.keys():
continue
if q[startcol + strain] in ["", "0", "-"]:
# If the gene is not present, AND The isolate is allowed
r[q[genecol]][strains[strain]] = 0
zero_ones_line.append(0)
# Add a 0 to indicate non-presence
else:
# Gene is present if any other value than "", "0" or "-"
# is in the cell
r[q[genecol]][strains[strain]] = 1
zero_ones_line.append(1)
# Add a 1 to indicate presence of the current gene in
# this strain
# Add grabcols
for c in grabcols:
r[q[genecol]][header[c]+"_name"] = q[c]
# Since we are only interested in the differences between
# strains, no need to append the zero_ones_line if it is all 1's
# (core gene) or all 0's (not in collection)
if 1 in zero_ones_line and 0 in zero_ones_line:
zero_ones_matrix.append(zero_ones_line)
# Transpose list for distance calculation purposes
if writereducedset:
file.close()
zero_ones_matrix = list(map(list, zip(*zero_ones_matrix)))
return {"Roarydic": r,
"Zero_ones_matrix": zero_ones_matrix,
"Strains": strain_names_allowed,
"Extracols": extracolstoprint}
def ReduceSet(genefile, delimiter, grabcols, startcol=14,
allowed_isolates=None, time="",outdir="./"):
"""
Helper function for csv_to_dic_roary.
Method for writing a reduced gene presence absence file, based only
on isolates allowed by the restrict_to flag. This can speed up
Scoary when analyzing subsets of large (e.g. more than a couple
of hundred) datasets.
"""
csvfile = csv.reader(genefile, skipinitialspace=True,
delimiter=delimiter)
header = next(csvfile)
allowed_indexes = list(range(startcol))
for c in xrange(len(header)):
if header[c] in allowed_isolates.keys():
allowed_indexes.append(c)
log.info("Writing gene presence absence file for the reduced set of "
"isolates")
reducedfilename = \
"%sgene_presence_absence_reduced%s.csv" % (outdir, time)
# Trim grabcols to only include non-restricted isolates
grabcols = [i for i in grabcols if i in allowed_indexes]
with open(reducedfilename, "w") as csvout:
wtr = csv.writer(csvout, delimiter = delimiter)
newheader = [header[a] for a in allowed_indexes]
wtr.writerow(newheader)
for r in csvfile:
wtr.writerow( tuple(r[a] for a in allowed_indexes) )
log.info("Finished writing reduced gene presence absence list to "
"file %s" % str(reducedfilename))
return reducedfilename
def Csv_to_dic(csvfile, delimiter, allowed_isolates, strains):
"""
Converts an input traits file (csv format) to dictionaries readable
by Scoary.
"""
tab = list(zip(*csv.reader(csvfile, delimiter=delimiter)))
r = {}
# Create dictionary over which trees need pruning due to missing
# data
Prunedic = {}
if len(tab) < 2:
sys.exit("Please check that your traits file is formatted "
"properly and contains at least one trait")
for num_trait in xrange(1, len(tab)):
p = dict(zip(tab[0], tab[num_trait]))
if "" in p:
name_trait = p[""]
del p[""]
elif "Name" in p:
name_trait = p["Name"]
del p["Name"]
else:
sys.exit("Make sure the top-left cell in the traits file "
"is either empty or 'Name'. Do not include empty rows")
# Filter so that only allowed isolates are included
if allowed_isolates is not None:
p = {strain: indicator for (strain, indicator) in
list(p.items()) if strain in allowed_isolates.keys()}
# Stop if unknown character found in traits file
allowed_values = ["0","1","NA",".","-"," ",""]
if not all([x in allowed_values for x in p.values()]):
sys.exit("Unrecognized character found in trait file. Allowed "
"values (no commas): %s" % str(",".join(allowed_values)))
# Remove isolates with missing values, but only for the
# trait for which they are missing
if ("NA" in p.values()
or "-" in p.values()
or "." in p.values()
or " " in p.values()
or "" in p.values()):
log.warning("WARNING: Some isolates have missing values for "
"trait %s. Missing-value isolates will not be counted in "
"association analysis towards this trait."
% str(name_trait))
p_filt = {strain: indicator for (strain, indicator) in
p.items() if indicator not in ["NA","-","."," ",""]}
Prunedic[name_trait] = [k for (k,v) in p.items() if
v in ["NA","-","."," ",""]]
#p = p_filt
else:
Prunedic[name_trait] = []
p_filt = p
# Remove isolates that did not have rows in the trait file but
# that were allowed by the GPA file/restrict_to
#if not all(s in p.keys() for s in strains):
if not all(s in p.keys() for s in strains):
log.error("ERROR: Some isolates in your gene presence "
"absence file were not represented in your traits file. "
"These will count as MISSING data and will not be included."
)
Prunedic[name_trait] += [s for s in strains if
s not in p.keys() and
s not in Prunedic[name_trait]]
r[name_trait] = p_filt
Prunedic[name_trait] += [None]
return r, Prunedic
################################
# FUNCTIONS FOR HANDLING TREES #
################################
def CreateTriangularDistanceMatrix(zeroonesmatrix, strainnames):
"""
Converts a raw matrix of 0s and 1s (indicating gene presence and
absence, rows correspond to genes and columns to allowed strains) to
an (upper) triangular matrix of pairwise Hamming distances.
The distance d(i,i) is set to 1 for all i.
"""
try:
hamming_distances = [float(h) for h in list(
spatial.distance.pdist(zeroonesmatrix, 'hamming'))]
except TypeError:
sys.exit("Could not locate scipy.spatial.distance.pdist. "
"Perhaps you have an old version of SciPy installed?")
nstrains = int((1 + (1 + 8*len(hamming_distances))**0.5)/2)
TriangularDistanceMatrix = []
Strain_names = []
for i in xrange(nstrains):
# Adding the maximum relative hamming distance to prevent
# Quadtree algorithm to pick a pair where i = j
add = [1]
add += hamming_distances[:(nstrains-i-1)]
hamming_distances = hamming_distances[(nstrains-i-1):]
TriangularDistanceMatrix.append(add)
Strain_names.append(strainnames[i])
return {"matrix": TriangularDistanceMatrix, "names": Strain_names}
def PopulateQuadTreeWithDistances(TDM):
"""
Takes a triangular distance matrix, creates a quadtree and populates
it with the hamming distances between isolates.
First creates a Quadmatrix, so not really optimized.
"""
Quadmatrix = Matrix(dim=len(TDM["matrix"]))
for i in xrange(Quadmatrix.dim):
for j in xrange(i, Quadmatrix.dim):
try:
Quadmatrix[i][j] = \
Quadmatrix[j][i] = TDM["matrix"][i][(j-i)]
except IndexError:
sys.exit("There was an error trying to populate the "
"Quadtree with pairwise distances. Please "
"report this bug to [email protected]")
PopulatedQuadtree = QuadTree(Quadmatrix.dim, names=TDM["names"])
for i in xrange(Quadmatrix.dim):
PopulatedQuadtree.insert_row(i, Quadmatrix[i])
return PopulatedQuadtree
def upgma(d):
"""
Returns a UPGMA tree from a QuadTree distance matrix d. Heavily
based on original implementation by Christian Storm Pedersen.
"""
n = d.dim
cluster = [x for x in d.names]
size = n * [1]
while n > 1:
# While there are more than a single cluster left, find clusters
# i and j with minimum distance
i, j = d.argmin()
# Build list of distances from the new cluster to all the other
# clusters
new_cluster = [cluster[i], cluster[j]]
new_size = size[i] + size[j]
new_dist = []
for k in xrange(d.dim):
if cluster[k] is None:
new_dist.append(1)
else:
new_dist.append((d.get_elm(i,k)*size[i] +
d.get_elm(j,k)*size[j]) / new_size)
# Insert new row/col in d
new_dist[i] = sys.maxsize
d.insert_row(i, new_dist)
d.insert_col(i, new_dist)
d.insert_row(j, d.dim * [sys.maxsize])
d.insert_col(j, d.dim * [sys.maxsize])
cluster[i] = new_cluster
cluster[j] = None
size[i] = new_size
size[j] = 0
n -= 1
return new_cluster
def PruneForMissing(tree, Prunedic):
"""
Method for pruning isolates with missing values from the upgma tree
and gene-trait combinations objects. This happens for a particular
trait only, and so the full tree and GTC objects are used for traits
without missing values
"""
# Traverse tree and prune missing-data isolates
# Left node is a subtree, go deeper
# Make slice copy to prevent tampering with original
tree = tree[:]
if isinstance(tree[0],list):
tree[0] = PruneForMissing(tree[0], Prunedic)
# Right node is a subtree, go deeper
if isinstance(tree[1], list):
tree[1] = PruneForMissing(tree[1], Prunedic)
# Both isolates have missing data and should be excised
if (tree[0] in Prunedic) and (tree[1] in Prunedic):
return
# Only left node has missing data and should be excised
elif tree[0] in Prunedic:
return tree[1]
# Only right node has missing data and should be excised
elif tree[1] in Prunedic:
return tree[0]
# Neither the left or right nodes have missing data
else:
return [tree[0], tree[1]]
def StoreUPGMAtreeToFile(upgmatree, outdir, time=""):
"""
A method for printing the UPGMA tree that is built internally from
the hamming distances in the gene presence/absence matrix
"""
treefilename = str(outdir + ("Tree%s.nwk" % time))
with open(treefilename, "w") as treefile:
Tree = str(upgmatree)
Tree = Tree.replace("[", "(")
Tree = Tree.replace("]", ")")
treefile.write(Tree + ";")
log.info("Wrote the UPGMA tree to file: %s" % treefilename)
#####################################
# FUNCTIONS FOR CALCULATING RESULTS #
#####################################
def Setup_results(genedic, traitsdic, collapse):
"""
This is the method that actually does all the counting of genes,
calculation of p-values and post-test adjustment of p-values.
The majority of running time is currently spent doing Fisher's exact
test. The running time is somewhat shortened by storing the p-values
of known 2x2 cell distributions, so that identical Fisher's tests
will not have to be run.
"""
# Need to create one results dictionary for each trait
all_traits = {}
gene_trait_combinations = {}
fisher_calculated_values = {}
for trait in traitsdic:
all_traits[trait] = {}
# Also need a list of all p-values to perform stepwise FDR corr
p_value_list = []
log.info("Gene-wise counting and Fisher's exact tests for trait: "
"%s" % str(trait))
# We also need a number of tests variable for each genedic.
# (The number of tests may not be the same, depending on how
# many genes are in 0 or all strains.)
number_of_tests = len(genedic)
# Need initial number of tests for status bar
initial_number_of_tests = number_of_tests
# Additionally, we need a dictionary to, for each gene
# hold the gene-trait status (e.g "AB" or "ab" of each strain)
gene_trait_combinations[trait] = {}
distributions = {}
i = 0 # Progress
for gene in genedic:
# Status:
sys.stdout.write("\r{:.2%}".format(float(i) /
initial_number_of_tests))
sys.stdout.flush()
i += 1 # Progress
stats = Perform_statistics(traitsdic[trait], genedic[gene])
stat_table = stats["statistics"]
num_pos = stat_table["tpgp"] + stat_table["tpgn"]
num_neg = stat_table["tngp"] + stat_table["tngn"]
if (stat_table["tpgp"] + stat_table["tngp"]) == 0:
# No included isolates have the gene
# Remove 1 from the number of tests
number_of_tests -= 1
# proceed to the next gene
continue
if (stat_table["tpgn"] + stat_table["tngn"]) == 0:
# All included isolates have the gene
number_of_tests -= 1
continue
# IF gene_trait_combination exists already, ie the current
# gene is perfectly correlated with another gene, collapse
# the two into a single unit
# Should consider adding a softer correlation required than
# 100%, i.e. genes that are highly co-distributed should
# perhaps be merged earlier?
if stats["hash"] in distributions and collapse:
# Find out which gene is correlated
corr_gene = distributions[stats["hash"]]
# Collapse the two genes
newgenename = corr_gene + "--" + gene
distributions[stats["hash"]] = newgenename
# Remove 1 from the number of tests
number_of_tests -= 1
mergedgenes = True
del(gene_trait_combinations[trait][corr_gene])
gene_trait_combinations[trait][newgenename] = \
stats["gene_trait"]
else:
distributions[stats["hash"]] = gene
mergedgenes = False
gene_trait_combinations[trait][gene] = \
stats["gene_trait"]
obs_table = [[stat_table["tpgp"],
stat_table["tpgn"]],
[stat_table["tngp"],
stat_table["tngn"]]]
obs_tuple = (stat_table["tpgp"],
stat_table["tpgn"],
stat_table["tngp"],
stat_table["tngn"])
if obs_tuple in fisher_calculated_values:
odds_ratio = fisher_calculated_values[obs_tuple][0]
p_value = fisher_calculated_values[obs_tuple][1]
else:
fisher = ss.fisher_exact(obs_table)
p_value = fisher[1]
odds_ratio = fisher[0]
fisher_calculated_values[obs_tuple] = fisher
if not mergedgenes:
all_traits[trait][gene] = {
"NUGN": genedic[gene]["Non-unique Gene name"],
"Annotation": genedic[gene]["Annotation"],
"tpgp": stat_table["tpgp"],
"tngp": stat_table["tngp"],
"tpgn": stat_table["tpgn"],
"tngn": stat_table["tngn"],
"sens": ((float(stat_table["tpgp"]) / num_pos * 100) if
num_pos > 0 else 0.0),
"spes": ((float(stat_table["tngn"]) / num_neg * 100) if
num_neg > 0 else 0.0),
"OR": odds_ratio,
"p_v": p_value}
p_value_list.append((gene, p_value))
else:
temp = all_traits[trait][corr_gene]
del(all_traits[trait][corr_gene])
all_traits[trait][newgenename] = {
"NUGN": temp["NUGN"] + "--" +
genedic[gene]["Non-unique Gene name"],
"Annotation": temp["Annotation"] + "--" +
genedic[gene]["Annotation"],
"tpgp": stat_table["tpgp"],
"tngp": stat_table["tngp"],
"tpgn": stat_table["tpgn"],
"tngn": stat_table["tngn"],
"sens": ((float(stat_table["tpgp"]) / num_pos * 100) if
num_pos > 0 else 0.0),
"spes": ((float(stat_table["tngn"]) / num_neg * 100) if
num_neg > 0 else 0.0),
"OR": odds_ratio,
"p_v": p_value}
p_value_list.append((newgenename, p_value))
sys.stdout.write("\r100.00%")
sys.stdout.flush()
sys.stdout.write("\n")
log.info("Adding p-values adjusted for testing multiple hypotheses")
# Now calculate Benjamini-Hochberg and Bonferroni p-values
# Sorted list of tuples: (gene, p-value)
# s_p_v = abbreviation for sorted_p_values
s_p_v = sorted(p_value_list, key=lambda x: x[1])
# Find out which p-values are ties
# Note: Changed from step-down to step-up
# (from least significant to most significant)
tie = [s_p_v[i-1][1] == s_p_v[i][1] for i in
xrange(1, len(s_p_v))]
# Initialize dics of corrected p values
# bh_c_p_v = abbreviation for bh_corrected_p_values
bh_c_p_v = {}
# The least significant gene is entered into the dic
bh_c_p_v[s_p_v[len(s_p_v)-1][0]] = last_bh = s_p_v[len(s_p_v)-1][1]
for (ind, (gene, p)) in reversed(list(enumerate(s_p_v[:-1]))):
bh_c_p_v[gene] = min([last_bh, p*number_of_tests/(ind+1.0)]\
) if not tie[ind] else last_bh
last_bh = bh_c_p_v[gene]
# Now add values to dictionaries:
for gene in all_traits[trait]:
all_traits[trait][gene]["B_p"] = min(
all_traits[trait][gene]["p_v"] * number_of_tests , 1.0)
all_traits[trait][gene]["BH_p"] = min(bh_c_p_v[gene], 1.0)
return {"Results": all_traits,
"Gene_trait_combinations": gene_trait_combinations}
def Perform_statistics(traits, genes):
"""
Helper function for Setup_results.
The method that adds the presence/absence status for each
trait-status combination.
"""
r = {"tpgp": 0, "tpgn": 0, "tngp": 0, "tngn": 0}
# tpgn = trait positive, gene negative, etc
gene_trait = {}
distribution_hash = ""
for t in traits: # For each strain
# If missing data, continue without including isolate
# Note, this should no longer be invoked, since missing-value
# isolates are not in the traits dic to begin with
if traits[t] in ["NA","-","."]:
gene_trait[t] = "NA"
distribution_hash += str(genes[t])
continue
try:
if int(traits[t]) == 1 and genes[t] == 1:
r["tpgp"] += 1
distribution_hash += "1"
gene_trait[t] = "AB"
elif int(traits[t]) == 1 and genes[t] == 0:
r["tpgn"] += 1
distribution_hash += "0"
gene_trait[t] = "aB"
elif int(traits[t]) == 0 and genes[t] == 1:
r["tngp"] += 1
distribution_hash += "1"
gene_trait[t] = "Ab"
elif int(traits[t]) == 0 and genes[t] == 0:
r["tngn"] += 1
distribution_hash += "0"
gene_trait[t] = "ab"
else:
sys.exit("There was a problem with comparing your "
"traits and gene presence/absence files. Make sure you "
"have formatted the traits file to specification and "
"only use 1s and 0s, as well as NA, - or . for missing "
"data. Also make sure the Roary file contains empty "
"cells for non-present genes and non-empty text cells "
"for present genes.")
except KeyError:
sys.stdout.write("\n")
log.critical("CRITICAL: Could not find %s in the genes "
"file." % str(t) )
#log.warning("CRITICAL: Could not find %s in the genes file" % str(t))
sys.exit("Make sure strains are named the same in your "
"traits file as in your gene presence/absence file")
return {"statistics": r, "hash": int(distribution_hash, 2),
"gene_trait": gene_trait}
#################################
# FUNCTIONS FOR CREATING OUTPUT #
#################################
def StoreResults(Results, max_hits, cutoffs, upgmatree, GTC, Prunedic,
outdir, permutations, num_threads, no_pairwise,
genedic, extracolstoprint, time="", delimiter=","):
"""
A method for storing the results. Calls StoreTraitResult for each
trait column in the input file.
"""
for Trait in Results:
sys.stdout.write("\n")
log.info("Storing results: " + Trait)
StoreTraitResult(Results[Trait], Trait, max_hits, cutoffs,
upgmatree, GTC, Prunedic, outdir, permutations,
num_threads, no_pairwise, genedic,
extracolstoprint, time, delimiter)
def StoreTraitResult(Trait, Traitname, max_hits, cutoffs, upgmatree,
GTC, Prunedic, outdir, permutations, num_threads,
no_pairwise, genedic, extracolstoprint, time="",
delimiter=","):
"""
The method that actually stores the results. Only accepts results
from a single trait at a time
"""
permutations = int(permutations)
if num_threads > 1:
multithreaded = True
else:
multithreaded = False
fname = (outdir + Traitname + time + '.results.csv')
with open(fname, "w") as outfile:
# Sort genes by p-value.
sort_instructions = SortResultsAndSetKey(Trait)
if max_hits is None:
max_hits = len(Trait)
num_results = min(max_hits, len(Trait))
cut_possibilities = {
"I": "p_v",
"B": "B_p",