-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathMAPLEv0.6.12.py
9226 lines (8705 loc) · 350 KB
/
MAPLEv0.6.12.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
import sys
from math import log
import argparse
from time import time
import os.path
from operator import itemgetter
#©EMBL-European Bioinformatics Institute, 2021-2023
#Developd by Nicola De Maio, with contributions from Myrthe Willemsen.
# MAPLE code to estimate a tree by maximum likelihood from a MAPLE format input.
#TODO test HnZ modifier to favour placement onto successful lineages (those with many samples and direct descendants)
#longer-term plans
#TODO parallelization of initial tree search, probably only feasible in C++
#TODO Timed trees
#TODO further detailed substitution models that has a specific rate for each position, from each nucleotide, to each nucleotide (12 times more parameters than position-specific model).
#TODO phylogeography
#TODO codon models, selection
#TODO indels, alignment via alignment-free pair-HMM
#TODO Bayesian implementation in BEAST
#TODO Recombination via pair-HMM based SPR search of second parent
#TODO phylodynamics/selection
#TODO relativistic phylogenetics for arbitrary large trees
#things one could MAYBE also try in the future:
#TODO implement parsimony?
#TODO create an initial stage for sample placement with very low thresholds; then, a second placement stage would use the default thresholds and work
# like the SPR search but starting the placement search from the node found by the first stage; finally, the last stage would be as usual.
# I tried this but it comes at little computational advantage and at large accuracy cost.
parser = argparse.ArgumentParser(description='Estimate a tree from a diff format and using iterative approximate maximum likelihood sample placement.')
#important options
parser.add_argument('--input',default="/Users/demaio/Desktop/GISAID-hCoV-19-phylogeny-2021-03-12/phylogenetic_inference/2021-03-31_unmasked_differences_reduced.txt_consensus-based.txt", help='Input MAPLE file name; should contain first the reference genome and then the difference of all samples with respet to the reference.')
parser.add_argument('--reference',default="", help='Optional input reference file name. By default it assumes instead that the reference is part of the MAPLE format input.')
parser.add_argument("--model", help="Which substitution model should be used. Allowed models so far are JC, GTR (default) or UNREST.", default="GTR")
parser.add_argument('--output',default="/Users/demaio/Desktop/GISAID-hCoV-19-phylogeny-2021-03-12/phylogenetic_inference/MAPLE", help='Output path and identifier to be used for newick output file.')
parser.add_argument('--inputTree',default="", help='Input newick tree file name; this is optional, and is used for online inference (or for Robinson-Foulds distance calculation if option --inputRFtrees is also used).')
parser.add_argument('--inputRates',default="", help='Name of input containing pre-estimated substitution rates and possibly other model parameters; this is optional, and is only used for online inference. The same format as the MAPLE output is expected, and information about all parameters of the selected substitution model is expected.')
parser.add_argument("--largeUpdate", help="When using option --inputTree to do online inference, by default the tree is only updated locally where the new sequences are inserted. Use this option instead to perform a thorough update of the phylogeny.", action="store_true")
parser.add_argument('--inputRFtrees',default="", help='file name with input newick trees to be compared with the input tree in option --inputTree to calculate Robinson-Foulds distances; this option will turn off the normal MAPLE estimation - only RF distances will be calculated. Each newick tree contained in this file will be compared to the single tree specified with option --inputTree .')
parser.add_argument("--overwrite", help="Overwrite previous results if already present.", action="store_true")
parser.add_argument("--fast", help="Set parameters so to run tree inference faster; this will be less accurate in cases of high complexity, for example with recombination, sequencing errors, etc. It will overrule user choices for options --thresholdLogLK , --thresholdLogLKtopology , --allowedFails , --allowedFailsTopology .", action="store_true")
parser.add_argument("--rateVariation", help="Estimate and use rate variation: the model assumes one rate per site, and the rates are assumed independently (no rate categories). This might cause overfitting if the dataset is not large enough, but in any case one would probably only use MAPLE for large enough datasets.", action="store_true")
parser.add_argument("--estimateMAT", help="Estimate mutation events on the final tree, and write them on the nexus tree.", action="store_true")
parser.add_argument("--doNotImproveTopology", help="Do not perform SPR moves, despite searching for them; this is useful if one wants to analyse a tree and calculate branch supports without changing the input tree.", action="store_true")
parser.add_argument("--saveInitialTreeEvery",help="Every these many samples placed (default 50,000) save the current tree to file. This way if there is any problem, the building of the initial tree can be restarted from the last saved tree.", type=int, default=50000)
parser.add_argument("--doNotPlaceNewSamples", help="Given an input tree, skip the placement of samples on the tree (in case the input alignment contained more samples than on the tree), so keep only the samples originally already on the tree.", action="store_true")
parser.add_argument("--doNotReroot", help="Skip rooting optimization.", action="store_true")
parser.add_argument("--noLocalRef", help="Do not use local references (this will usually take longer to run).", action="store_true")
#parallelization options
parser.add_argument("--numCores",help="Maximum number of cores to use if parallelizing. By default (0) use as many cores as available.", type=int, default=1)
#threshold options
parser.add_argument("--minNumNon4",help="Minimum number of mutations threshold to define a subreference in the MAT - smaller values will cause denser references in the MAT.", type=int, default=1)
parser.add_argument("--maxNumDescendantsForMATClade",help="Number of positive-branch-length descendants allowed before triggering mutation list (i.e. local reference) creation in the tree.", type=int, default=50)
parser.add_argument("--noFastTopologyInitialSearch", help="Don't run a first fast short-range topology search (before the extensive one in case the latter is performed).", action="store_true")
parser.add_argument("--thresholdProb",help="relative probability threshold used to ignore possible states with very low probabilities.", type=float, default=0.00000001)
parser.add_argument("--thresholdLogLK",help="logLK difference threshold (in number of mutations) to consider a logLk close to optimal.", type=float, default=18.0)
parser.add_argument("--thresholdLogLKtopology",help="Maximum logLK difference threshold (in number of mutations) to consider a logLk close to optimal when looking for topology improvements.", type=float, default=14.0)
parser.add_argument("--allowedFails",help="Number of times one can go down the tree without increasing placement likelihood before the tree traversal is stopped (only applies to non-0 branch lengths).", type=int, default=5)
parser.add_argument("--allowedFailsTopology",help="Maximum number of times one can crawl along the tree without increasing placement likelihood before the tree traversal is stopped during topology search (only applies to non-0 branch lengths).", type=int, default=4)
parser.add_argument("--numTopologyImprovements",help="Number of times we traverse the tree looking for deep (and slow) topological improvements. Default is 1, select 0 to skip deep topological search. values >1 are not recommended.", type=int, default=1)
parser.add_argument("--thresholdTopologyPlacement",help="Don't try to re-place nodes that have current appending logLK cost above this threshold.", type=float, default=-0.1)
parser.add_argument("--updateSubstMatrixEveryThisSamples",help="How many new samples to place before each update of the substitution rate matrix.", type=int, default=25)
parser.add_argument("--nonStrictStopRules", help="If specified, then during the initial placement stage, a slower, non-strict rule for stopping the placement search is applied: the search is stopped if enough many consencutive LK worsening are observed, AND if LK is below the considered threshold.", action="store_true")
parser.add_argument("--strictTopologyStopRules", help="If specified, then during the topological improvement stage, a faster, strict rule for stopping the SPR search is applied: the search is stopped if enough many consencutive LK worsening are observed, OR if LK is below the considered threshold.", action="store_true")
parser.add_argument("--thresholdDiffForUpdate",help="Consider the probability of a new partial changed if the difference between old and new is above this threshold.", type=float, default=0.00001)
parser.add_argument("--thresholdFoldChangeUpdate",help="Consider the probability of a new partial changed, if the fold difference between old and new if above this threshold.", type=float, default=1.01)
parser.add_argument("--thresholdLogLKconsecutivePlacement",help="logLK difference threshold to consider something as a significant decrease in log-LK when considering consecutive likelihood decreases.", type=float, default=0.01)
parser.add_argument("--thresholdLogLKTopologySubRoundImprovement",help="logLK difference threshold to consider something as a significant decrease in log-LK when considering sub-rounds of SPR moves.", type=float, default=3.0)
parser.add_argument("--minBLenSensitivity",help="Fraction of a mutation to be considered as a precision for branch length estimation (default 0.001, which means branch lengths estimated up to a 1000th of a mutation precision).", type=float, default=0.001)
parser.add_argument("--thresholdLogLKoptimization",help="logLK difference threshold (in number of mutations) to consider a logLk close to optimal when deciding for which possible placements to perform branch length optimization.", type=float, default=1.0)
parser.add_argument("--thresholdLogLKoptimizationTopology",help="logLK difference threshold (in number of mutations) to consider a logLk close to optimal when deciding for which possible placements to perform branch length optimization during the SPR stage.", type=float, default=1.0)
parser.add_argument("--maxReplacements",help="Maximum number of replacements attempts per node per SPR round (prevents loops).", type=int, default=10)
parser.add_argument("--useFixedThresholdLogLKoptimizationTopology", help="Use this option if you want to specify the value in --thresholdLogLKoptimizationTopology instead of estimating it from the data.", action="store_true")
parser.add_argument("--minNumSamplesForRateVar",help="When creating the initial tree, start using the rate variation model only after these many samples have been added (better not to decrease this too much to avoid overfitting).", type=int, default=510000)
parser.add_argument("--minNumSamplesForErrorModel",help="When creating the initial tree, start using the error model only after these many samples have been added (better not to decrease this too much to avoid overfitting).", type=int, default=510000)
#lineage assignment options
parser.add_argument('--assignmentFileCSV',default="", help='give path and name to a .csv file containing reference sample names and their lineage assignment. When using this option, option --inputTree should also be used. Then MAPLE will assign all samples in the tree to a lineage following the reference lineages file. Each sample is assigned a lineage same as its closest reference parent.')
parser.add_argument('--assignmentFile',default="", help='Like --assignmentFileCSV but expects an alignment file in any format (as long as sequence names follow a > character as in Fasta and Maple formats).')
parser.add_argument('--inputNexusTree',default="", help='input nexus tree file name; this is optional, and is used for lineage assignment. The nexus tree is supposed to be the output of MAPLE, so that it has alternativePlacements annotation to represent topological uncertainty.')
parser.add_argument('--reRoot',default="", help='Re-root the input newick tree so that the specified sample/lineage is root. By default, no specified lineage/sample, so no rerooting.')
#rarer options
parser.add_argument("--defaultBLen",help="Default length of branches, for example when the input tree has no branch length information.", type=float, default=0.000033)
parser.add_argument("--normalizeInputBLen",help="For the case the input tree has branch lengths expressed not in a likelihood fashion (that is, expected number of substitutions per site), then multiply the input branch lengths by this factor. Particularly useful when using parsimony-based input trees.", type=float, default=1.0)
parser.add_argument("--multipleInputRFTrees", help="Use this option if the file specified by option --inputRFtrees contains multiple trees - otherwise only read the first tree from that file.", action="store_true")
parser.add_argument("--debugging", help="Test that likelihoods are calculated and updated as expected - time consuming and only meant for small trees for debugging purposes.", action="store_true")
parser.add_argument("--onlyNambiguities", help="Treat all ambiguities as N (total missing information).", action="store_true")
parser.add_argument("--nonBinaryTree", help="Write output tree with multifurcations - by default the tree is written as binary so to avoid problems reading the tree in other software.", action="store_true")
parser.add_argument("--writeTreesToFileEveryTheseSteps", help="By default, don't write intermediate trees to file. If however a positive integer is specified with this option, intermediate trees will be written to file every this many topological changes.", type=int, default=0)
parser.add_argument("--writeLKsToFileEveryTheseSteps", help="By default, don't write likelihoods of intermediate trees to file. If however a positive integer is specified with this option, likelihoods of intermediate trees will be written to file every this many topological changes.", type=int, default=0)
parser.add_argument("--noSubroundTrees", help="Do not write to file subround treees.", action="store_true")
#error model options
parser.add_argument("--estimateErrorRate", help="Estimate a single error rate for the whole genome. Input value is used as starting value", action="store_true")
parser.add_argument("--estimateSiteSpecificErrorRate", help="Estimate a separate error rate for each genome genome. Input value is used as starting value", action="store_true")
parser.add_argument("--errorRateInitial", help="Initial value used for estimating the error rate. The default is the inverse of the reference genome length (one error expected per genome).", type=float, default=0.0)
parser.add_argument("--errorRateFixed", help="Fix the error rate to a given input value", type=float, default=0.0)
parser.add_argument("--errorRateSiteSpecificFile", help="provide a file directory to a file that contains the siteSpecific error rates", type=str, default=None)
parser.add_argument("--estimateErrors", help="Estimate erroneous positions in the input sequences. This option is only allowed if option --estimateSiteSpecificErrorRate or errorRateSiteSpecificFile is also used.", action="store_true")
parser.add_argument("--minErrorProb", help="Minimum error probability to be reported when using option --estimateErrors", type=float, default=0.01)
#SPRTA options
parser.add_argument("--SPRTA", help="Calculate branch support values with a modification of the aBayes approach of Anisimova et al 2011 (De Maio et al 2024, in prep.).", action="store_true")
parser.add_argument("--aBayesPlus", help="Synonim for option --SPRTA.", action="store_true")
parser.add_argument("--networkOutput", help="Include in the output tree the alternative branches with their support (like in a weighted phylogenetic network).", action="store_true")
parser.add_argument("--minBranchSupport", help="Minimum branch support to be considered when using option --networkOutput", type=float, default=0.01)
parser.add_argument("--supportFor0Branches", help="When calculating branch support, also consider supports of branches of length 0, such as samples less informative than other samples which might have multiple placements on the tree.", action="store_true")
parser.add_argument("--minMutProb", help="Minimum mutation probability to be written to output when using option --estimateMAT", type=float, default=0.01)
parser.add_argument("--keepInputIQtreeSupports", help="Assumes the input tree is from IQTREE, reads the support values on the tree branches, and prints the same values in the output nexus tree.", action="store_true")
#TODO HorseNotZebra modifiers option
parser.add_argument("--HnZ", help="By default (0), don't use modifiers. If 1, use the topological HorseNotZebra modifier; if 2, use the abundance HnZ modifier.", type=int, default=0)
args = parser.parse_args()
onlyNambiguities=args.onlyNambiguities
thresholdProb=args.thresholdProb
debugging=args.debugging
inputFile=args.input
outputFile=args.output
refFile=args.reference
allowedFails=args.allowedFails
allowedFailsTopology=args.allowedFailsTopology
model=args.model
thresholdLogLK=args.thresholdLogLK
thresholdLogLKtopology=args.thresholdLogLKtopology
overwrite=args.overwrite
binaryTree=(not args.nonBinaryTree)
numTopologyImprovements=args.numTopologyImprovements
thresholdTopologyPlacement=args.thresholdTopologyPlacement
updateSubstMatrixEveryThisSamples=args.updateSubstMatrixEveryThisSamples
strictStopRules=(not args.nonStrictStopRules)
strictTopologyStopRules=args.strictTopologyStopRules
thresholdDiffForUpdate=args.thresholdDiffForUpdate
thresholdFoldChangeUpdate=args.thresholdFoldChangeUpdate
thresholdLogLKconsecutivePlacement=args.thresholdLogLKconsecutivePlacement
thresholdLogLKTopologySubRoundImprovement=args.thresholdLogLKTopologySubRoundImprovement
calculateLKfinalTree=True
maxNumDescendantsForMATClade=args.maxNumDescendantsForMATClade
minNumNon4=args.minNumNon4
saveInitialTreeEvery=args.saveInitialTreeEvery
doNotPlaceNewSamples=args.doNotPlaceNewSamples
doNotReroot=args.doNotReroot
noSubroundTrees=args.noSubroundTrees
useLocalReference= (not args.noLocalRef)
numCores=args.numCores
parallelize=False
if numCores>1:
parallelize=True
from multiprocessing import Pool
from os import cpu_count
numAvailCores=cpu_count()
print('Number of CPUs available: '+str(numAvailCores))
if numCores>numAvailCores:
numCores=numAvailCores
print('Number of CPUs that will be used: '+str(numCores))
thresholdLogLKoptimization=args.thresholdLogLKoptimization
thresholdLogLKoptimizationTopology=args.thresholdLogLKoptimizationTopology
minBLenSensitivity=args.minBLenSensitivity
example=False
runFast=args.fast
if runFast:
thresholdLogLK=14.0
allowedFails=4
allowedFailsTopology=3
thresholdLogLKtopology=7.0
thresholdTopologyPlacement=-1.0
minBLenSensitivity=0.001
fastTopologyInitialSearch=(not args.noFastTopologyInitialSearch)
strictTopologyStopRulesInitial=True
allowedFailsTopologyInitial=2
thresholdLogLKtopologyInitial=6.0
thresholdTopologyPlacementInitial=-0.1
minNumSamplesForRateVar=args.minNumSamplesForRateVar
minNumSamplesForErrorModel=args.minNumSamplesForErrorModel
defaultBLen=args.defaultBLen
normalizeInputBLen=args.normalizeInputBLen
multipleInputRFTrees=args.multipleInputRFTrees
inputTree=args.inputTree
inputRates=args.inputRates
inputRFtrees=args.inputRFtrees
largeUpdate=args.largeUpdate
assignmentFile=args.assignmentFile
assignmentFileCSV=args.assignmentFileCSV
inputNexusTree=args.inputNexusTree
maxReplacements=args.maxReplacements
writeTreesToFileEveryTheseSteps=args.writeTreesToFileEveryTheseSteps
writeLKsToFileEveryTheseSteps=args.writeLKsToFileEveryTheseSteps
reRoot=args.reRoot
mutMatrixGlobal=None
estimateErrorRate=args.estimateErrorRate
estimateSiteSpecificErrorRate = args.estimateSiteSpecificErrorRate
errorRateInitial = args.errorRateInitial
errorRateFixed = args.errorRateFixed
errorRateSiteSpecificFile = args.errorRateSiteSpecificFile
estimateErrors=args.estimateErrors
if estimateErrors and (not estimateSiteSpecificErrorRate) and (not errorRateSiteSpecificFile):
print("Since option --estimateErrors has been selected, I am switching on --estimateSiteSpecificErrorRate so to allow estimation of site-specific error probabilities.")
estimateSiteSpecificErrorRate=True
minErrorProb=args.minErrorProb
errorRateGlobal=0.0
usingErrorRate=False
errorRateSiteSpecific=False
rateVariation=args.rateVariation
useRateVariation=False
mutMatrices=None
aBayesPlus=args.aBayesPlus
sprta=args.SPRTA
aBayesPlus=aBayesPlus or sprta
networkOutput=args.networkOutput
minBranchSupport=args.minBranchSupport
supportFor0Branches=args.supportFor0Branches
if supportFor0Branches:
supportForIdenticalSequences=True
else:
supportForIdenticalSequences=False
estimateMAT=args.estimateMAT
minMutProb=args.minMutProb
doNotImproveTopology=args.doNotImproveTopology
keepInputIQtreeSupports=args.keepInputIQtreeSupports
aBayesPlusOn=False
if aBayesPlus:
import math
warnedBLen=[False]
warnedTotDiv=[False]
sumChildLKs=[0.0]
numChildLKs=[0]
useFixedThresholdLogLKoptimizationTopology=args.useFixedThresholdLogLKoptimizationTopology
totDivFromRef=[0.0]
#TODO HnZ check and HnZvector definition and update
HnZ=args.HnZ
if HnZ>2 or HnZ<0:
print("Option --HnZ only allows values 0 (no HnZ), 1 (topological HnZ) or 2 (abundance HnZ).")
exit()
if HnZ==1:
HnZvector=[0,0,0]
elif HnZ==2:
HnZvector=[0,0,2*log(2)]
def updateHnZvector(n):
currentN=len(HnZvector)
while currentN<=n:
if HnZ==1:
HnZvector.append(HnZvector[-1]+log( (2*currentN) - 3))
elif HnZ==2:
HnZvector.append(currentN*log(currentN))
currentN+=1
def getHnZ(n):
if n>=len(HnZvector):
updateHnZvector(n)
if n<=0:
print("Requested HnZ score for non-positive nDesc0? "+str(n))
raise Exception("exit")
return HnZvector[n]
class Tree(object):
def __init__(self):
self.dist = []
self.replacements=[]
self.children = []
self.mutations=[]
self.up=[]
self.dirty=[]
self.name=[]
self.minorSequences=[]
self.probVect=[]
self.probVectUpRight=[]
self.probVectUpLeft=[]
self.probVectTotUp=[]
self.nDesc=[]
#TODO number of branches descending from node after collapsing 0-length branches
self.nDesc0=[]
def __repr__(self):
return "Tree object"
def addNode(self,dirtiness=True):
self.up.append(None)
self.children.append([])
self.dirty.append(dirtiness)
self.name.append("")
self.minorSequences.append([])
self.mutations.append([])
self.replacements.append(0)
self.dist.append(0.0)
self.probVect.append(None)
self.probVectUpRight.append(None)
self.probVectUpLeft.append(None)
self.probVectTotUp.append(None)
self.nDesc.append(0)
#TODO make sure this si updated correctly throughout
if HnZ:
self.nDesc0.append(1)
#IMPORTANT definitions of genome list entries structure.
#The first element of a genome list entry represnts its type: 0="A", 1="C", 2="G", 3="T", 4="R", 5="N", 6="O"
# for entries of type 4="R" or 5="N" the second element represents the last position of the stretch of genome that they represent;
# a value of 1 refers to the first position of the genome. In all other cases the second element represents the mutation-annotated tree reference nucleotide
# at the considered position at the considered node.
#For entries of type 6="O" the last element is always a normalized vector of likelihoods (they always have to sum to 1.0).
# For elements of type <5, when considering error probabilities, a last additional flag element informs if the observation comes from a tip
# without minor sequences (in which case we need to account for probabilities of errors), or not.
#If present, another element in third position represents the evolutionary distance since the considered type was observed (this is always missing with type "N"=5);
#If the element is not not present, this distance is assumed to be 0.0.
#If the distance (branch length) value is present, another distance value can also be present for entries of type <5 ;
#this is to account for the fact that the observation might have occurred on the other side of the phylogeny with respect to the root;
#when this additional branch length is also present, for example if the entry is (1, 234, 0.0001, 0.0002) then this means that a "C" was observed at genome position 234, and the observation
#is separated from the root by a distance of 0.0001, while a distance of 0.0002 separates the root from the current node (or position along a branch) considered.
# readNewick() now also reads IQTREE branch supports if keepInputIQtreeSupports==True
# different types of branch support in IQTREE:
# )63:
# )0.650000:
# )/0.125:
# )75.4:
# )/0.999:
# )75.4/67.3:
#function to read input newick string
def readNewick(nwFile,multipleTrees=False,dirtiness=True,createDict=False,inputDictNames=None,keepNames=False):
phyloFile=open(nwFile)
trees=[]
line=phyloFile.readline()
if inputDictNames==None and (not keepNames):
namesInTree=[]
if createDict:
namesInTreeDict={}
sampleNum=0
while line!="":
while line=="\n":
line=phyloFile.readline()
if line=="":
break
tree=Tree()
tree.addNode(dirtiness=dirtiness)
if keepInputIQtreeSupports:
tree.IQsupport=[0.0]
nwString=line.replace("\n","")
index=0
nodeIndex=len(tree.name)-1
name=""
distStr=""
finished=False
while index<len(nwString):
if nwString[index]=="(":
tree.children[nodeIndex].append(len(tree.up))
tree.addNode(dirtiness=dirtiness)
if keepInputIQtreeSupports:
tree.IQsupport.append(None)
tree.up[-1]=nodeIndex
nodeIndex=len(tree.up)-1
index+=1
elif nwString[index]==";":
trees.append((tree,nodeIndex))
finished=True
break
elif nwString[index]=="[":
while nwString[index]!="]":
index+=1
index+=1
elif nwString[index]==":":
index+=1
while nwString[index]!="," and nwString[index]!=")" and nwString[index]!=";":
distStr+=nwString[index]
index+=1
elif nwString[index]==",":
if name!="":
if keepNames:
tree.name[nodeIndex]=name
elif inputDictNames==None:
tree.name[nodeIndex]=sampleNum
if createDict:
namesInTreeDict[name]=sampleNum
sampleNum+=1
namesInTree.append(name)
else:
tree.name[nodeIndex]=inputDictNames[name]
name=""
if distStr!="":
tree.dist[nodeIndex]=float(distStr)*normalizeInputBLen
if tree.dist[nodeIndex]<0.0:
print("Warning: negative branch length in the input tree: "+distStr+" ; converting it to positive.")
tree.dist[nodeIndex]=abs(tree.dist[nodeIndex])
distStr=""
else:
tree.dist[nodeIndex]=defaultBLen
nodeIndex=tree.up[nodeIndex]
tree.children[nodeIndex].append(len(tree.up))
tree.addNode(dirtiness=dirtiness)
if keepInputIQtreeSupports:
tree.IQsupport.append(None)
tree.up[-1]=nodeIndex
nodeIndex=len(tree.up)-1
index+=1
elif nwString[index]==")":
if name!="":
if keepNames:
tree.name[nodeIndex]=name
elif inputDictNames==None:
tree.name[nodeIndex]=sampleNum
if createDict:
namesInTreeDict[name]=sampleNum
sampleNum+=1
namesInTree.append(name)
else:
tree.name[nodeIndex]=inputDictNames[name]
name=""
if distStr!="":
tree.dist[nodeIndex]=float(distStr)*normalizeInputBLen
distStr=""
else:
tree.dist[nodeIndex]=defaultBLen
if keepInputIQtreeSupports:
suppStr=""
index+=1
while nwString[index]!=":" and nwString[index]!=")" and nwString[index]!=";":
suppStr+=nwString[index]
index+=1
if suppStr!="":
suppVal=float(suppStr.split("/")[-1])
if suppVal>1:
suppVal=suppVal/100.0
tree.IQsupport[tree.up[nodeIndex]]=suppVal
else:
index+=1
nodeIndex=tree.up[nodeIndex]
else:
name+=nwString[index]
index+=1
if not finished:
print("Error, final character ; not found in newick string in file "+nwFile+".")
raise Exception("exit")
if not multipleTrees:
break
line=phyloFile.readline()
phyloFile.close()
if keepNames:
return trees
elif createDict:
return trees, namesInTree, namesInTreeDict
elif inputDictNames==None:
return trees, namesInTree
else:
return trees
#assign branch length to a node from a substring of a newick file
def assignNodeBLen(dist,nodeIndex,distStr):
if distStr!="":
dist[nodeIndex]=float(distStr)*normalizeInputBLen
if dist[nodeIndex]<0.0:
print("Warning: negative branch length in the input tree: "+distStr+" ; converting it to positive.")
dist[nodeIndex]=abs(dist[nodeIndex])
distStr=""
else:
dist[nodeIndex]=defaultBLen
#assign node features from a substring of a nexus file
def assignNodeFeatures(featureDicts,nodeIndex,annotationString):
st=annotationString.replace("[","").replace("]","")
features={}
index=0
while index<len(st):
oldIndex=index
while st[index]!="=":
index+=1
featureName=st[oldIndex:index]
featureName=featureName.replace("&","")
index+=1
if st[index]=="{":
oldIndex=index
while st[index]!="}":
index+=1
featureStr=st[oldIndex:index].replace("{","").replace("}","")
featureList=featureStr.split(",")
featureDict={}
for featureElement in featureList:
if featureElement!="":
featureElementList=featureElement.split(":")
if len(featureElementList)==2:
featureDict[featureElementList[0]]=float(featureElementList[1])
else:
featureDict[featureElementList[0]]=None
features[featureName]=featureDict
index+=1
else:
oldIndex=index
while st[index]!="}" and st[index]!=",":
index+=1
featureStr=st[oldIndex:index]
try:
featureValue=float(featureStr)
features[featureName]=featureValue
except ValueError:
features[featureName]=featureStr
if index<len(st) and st[index]==",":
index+=1
featureDicts[nodeIndex]=features
#function to read input nexus file
def readNexus(nxFile,dirtiness=True):
print("Reading Nexus file "+nxFile)
phyloFile=open(nxFile)
line=phyloFile.readline()
while line!="begin trees;\n":
line=phyloFile.readline()
if line=="":
print("Error, no tree found in nexus file "+nxFile+".")
raise Exception("exit")
line=phyloFile.readline()
nwString=line.replace("\n","").split()[4]
index=0
tree=Tree()
featureDicts=[]
tree.addNode(dirtiness=dirtiness)
featureDicts.append(None)
nodeIndex=len(tree.name)-1
name=""
distStr=""
annotationString=""
finished=False
madeUpNameCount=0
while index<len(nwString):
if nwString[index]=="(":
tree.children[nodeIndex].append(len(tree.up))
tree.addNode(dirtiness=dirtiness)
featureDicts.append(None)
tree.up[-1]=nodeIndex
nodeIndex=len(tree.up)-1
index+=1
elif nwString[index]==";":
if name!="":
tree.name[nodeIndex]=name
name=""
else:
madeUpNameCount+=1
tree.name[nodeIndex]="madeUpNodeName"+str(madeUpNameCount)
assignNodeBLen(tree.dist,nodeIndex,distStr)
distStr=""
assignNodeFeatures(featureDicts,nodeIndex,annotationString)
annotationString=""
root=nodeIndex
finished=True
break
elif nwString[index]=="[":
firstInd=index
while nwString[index]!="]":
index+=1
lastInd=index
annotationString=nwString[firstInd:lastInd+1]
index+=1
elif nwString[index]==":":
index+=1
while nwString[index]!="," and nwString[index]!=")" and nwString[index]!=";":
distStr+=nwString[index]
index+=1
elif nwString[index]==",":
if name!="":
tree.name[nodeIndex]=name
name=""
else:
madeUpNameCount+=1
tree.name[nodeIndex]="madeUpNodeName"+str(madeUpNameCount)
assignNodeBLen(tree.dist,nodeIndex,distStr)
distStr=""
assignNodeFeatures(featureDicts,nodeIndex,annotationString)
annotationString=""
nodeIndex=tree.up[nodeIndex]
tree.children[nodeIndex].append(len(tree.up))
tree.addNode(dirtiness=dirtiness)
featureDicts.append(None)
tree.up[-1]=nodeIndex
nodeIndex=len(tree.up)-1
index+=1
elif nwString[index]==")":
if name!="":
tree.name[nodeIndex]=name
name=""
else:
madeUpNameCount+=1
tree.name[nodeIndex]="madeUpNodeName"+str(madeUpNameCount)
assignNodeBLen(tree.dist,nodeIndex,distStr)
distStr=""
assignNodeFeatures(featureDicts,nodeIndex,annotationString)
annotationString=""
index+=1
nodeIndex=tree.up[nodeIndex]
else:
name+=nwString[index]
index+=1
if not finished:
print("Error, final character ; not found in newick string in file "+nxFile+".")
raise Exception("exit")
phyloFile.close()
tree.featureDicts=featureDicts
print("Finished reading Nexus file.")
return tree,root
#function that changes multifurcating tree structure into a binary tree by adding 0-length branches/nodes
def makeTreeBinary(tree,root):
nodesToVisit=[root]
while nodesToVisit:
node=nodesToVisit.pop()
if tree.children[node]:
while len(tree.children[node])>2:
child2=tree.children[node].pop()
child1=tree.children[node].pop()
tree.up[child1]=len(tree.up)
tree.up[child2]=len(tree.up)
tree.addNode()
tree.children[-1].append(child1)
tree.children[-1].append(child2)
tree.up[-1]=node
tree.children[node].append(len(tree.up)-1)
nodesToVisit.append(tree.children[node][0])
nodesToVisit.append(tree.children[node][1])
#given a list of mutation events, create a reverted list to be used for re-rooting (when the direction of branches changes).
def flipMutations(mutationList):
newMutationList=[]
for mut in mutationList:
newMutationList.append((mut[0],mut[2],mut[1]))
return newMutationList
#check inconsistent references between two vectors
def checkInconsistency(probVectP,probVectC):
indexEntry1, indexEntry2, pos = 0, 0, 0
entry1=probVectP[indexEntry1]
entry2=probVectC[indexEntry2]
while True:
if entry1[0]==4 or entry1[0]==5 : # case entry1 is R or N
if entry2[0]==4 or entry2[0]==5:
pos=min(entry1[1],entry2[1])
if pos==lRef:
break
if entry2[1]==pos:
indexEntry2+=1
entry2=probVectC[indexEntry2]
else:
pos+=1
if pos==lRef:
break
indexEntry2+=1
entry2=probVectC[indexEntry2]
if entry1[1]==pos:
indexEntry1+=1
entry1=probVectP[indexEntry1]
else: #entry1 is a non-ref nuc or O
if entry2[0]!=4 and entry2[0]!=5:
if entry1[1]!=entry2[1]:
return True
pos+=1
if pos==lRef:
break
indexEntry1+=1
entry1=probVectP[indexEntry1]
if (entry2[0]!=4 and entry2[0]!=5) or entry2[1]==pos:
indexEntry2+=1
entry2=probVectC[indexEntry2]
return False
#function to merge 2 MAT mutation lists (for example for when removing an internal node from the tree). First list is the top one.
#downward=True is for merging across different sides of the MRCA.
def mergeMutationLists(mutations1,mutations2,downward=False):
ind1, ind2, pos1=0, 0, 0
newMutations=[]
while True:
if ind1<len(mutations1):
pos1=mutations1[ind1][0]
if ind2<len(mutations2):
pos2=mutations2[ind2][0]
if pos1<pos2:
if downward:
newMutations.append((pos1,mutations1[ind1][2],mutations1[ind1][1]))
else:
newMutations.append(mutations1[ind1])
ind1+=1
elif pos2<pos1:
newMutations.append(mutations2[ind2])
ind2+=1
else:
if downward:
sourceNuc=mutations1[ind1][2]
endNuc=mutations1[ind1][1]
else:
sourceNuc=mutations1[ind1][1]
endNuc=mutations1[ind1][2]
if endNuc!=mutations2[ind2][1]:
print("WARNING, inconsistent mutations in the MAT? "+str(ind1)+" "+str(ind2))
print(mutations1)
print(mutations2)
print()
if sourceNuc!=mutations2[ind2][2]:
newMutations.append((pos2,sourceNuc,mutations2[ind2][2]))
ind2+=1
ind1+=1
else:
if downward:
newMutations.append((pos1,mutations1[ind1][2],mutations1[ind1][1]))
else:
newMutations.append(mutations1[ind1])
ind1+=1
else:
if ind2<len(mutations2):
newMutations.append(mutations2[ind2])
ind2+=1
else:
break
return newMutations
#re-root a tree based on a given sample name, making the sample the root.
# if reRootAtInternalNode==True , flip also mutations in the local references. In this case sample represents the internal node whose parent branch to use as new root.
#TODO update also nDesc0 while re-rooting
def reRootTree(tree,root,sample,reRootAtInternalNode=False):
sampleNode=None
up=tree.up
children=tree.children
dist=tree.dist
#TODO
nDesc0=tree.nDesc0
minorSequences=tree.minorSequences
if reRootAtInternalNode:
sampleNode=sample
mutations=tree.mutations
#mutations at the new root, representing differences wrt the reference
rootMuts=mutations[root]
childrenList=[up[sampleNode]]
while up[childrenList[-1]]!=root:
childrenList.append(up[childrenList[-1]])
while childrenList:
newNode=childrenList.pop()
if mutations[newNode]:
rootMuts=mergeMutationLists(rootMuts,mutations[newNode])
else:
#find the node associated to the sample
nodesToVisit=[root]
while nodesToVisit:
node=nodesToVisit.pop()
try:
if tree.name[node]==sample:
sampleNode=node
break
except:
pass
if children[node]:
nodesToVisit.append(children[node][0])
nodesToVisit.append(children[node][1])
if sampleNode==None:
print("Input lineage/sample for rerooting not found, please specify a lineage/sample contained in the tree with option --reRoot.")
return root
#now create new root
if up[sampleNode]!=None:
if up[up[sampleNode]]==None:
if sampleNode==children[up[sampleNode]][0]:
sibling=children[up[sampleNode]][1]
else:
sibling=children[up[sampleNode]][0]
dist[sibling]+=dist[sampleNode]
dist[sampleNode]=False
#TODO
if HnZ:
nDesc0[up[sampleNode]]=nDesc0[sampleNode]
if dist[sibling]>effectivelyNon0BLen:
nDesc0[up[sampleNode]]+=1
else:
nDesc0[up[sampleNode]]+=nDesc0[sibling]
return up[sampleNode]
tree.addNode()
children[-1].append(sampleNode)
children[-1].append(up[sampleNode])
newRoot=len(dist)-1
oldDist=dist[sampleNode]
oldDistUp=dist[up[sampleNode]]
oldUp=up[sampleNode]
oldUpUp=up[up[sampleNode]]
dist[-1]=0.00000001
if reRootAtInternalNode:
dist[oldUp]=dist[sampleNode]/2
dist[sampleNode]=dist[sampleNode]/2
else:
dist[sampleNode]=0.0
dist[oldUp]=oldDist
up[sampleNode]=newRoot
up[oldUp]=newRoot
currentNode=oldUpUp
currentBLen=oldDistUp
currentChild=oldUp
currentChildChild=sampleNode
if reRootAtInternalNode:
oldMutations=mutations[currentChild]
mutations[currentChild]=[]
#now reiteratively flip the direction of branches until one reaches the old root
while up[currentNode]!=None:
if currentChildChild==children[currentChild][0]:
numChildChild=0
else:
numChildChild=1
children[currentChild][numChildChild]=currentNode
if reRootAtInternalNode:
newMutations=flipMutations(oldMutations)
oldMutations=mutations[currentNode]
mutations[currentNode]=newMutations
oldBLen=dist[currentNode]
oldPNode=up[currentNode]
dist[currentNode]=currentBLen
up[currentNode]=currentChild
currentChildChild=currentChild
currentChild=currentNode
currentNode=oldPNode
currentBLen=oldBLen
#Now finalize by removing the old root
if currentChildChild==children[currentChild][0]:
numChildChild=0
else:
numChildChild=1
if currentChild==children[currentNode][0]:
numChild=0
else:
numChild=1
if reRootAtInternalNode:
#deal with mutations at the children of the old root
newMutations=flipMutations(oldMutations)
mutations[children[currentNode][1-numChild]]=mergeMutationLists(newMutations,mutations[children[currentNode][1-numChild]])
mutations[newRoot]=rootMuts
children[currentChild][numChildChild]=children[currentNode][1-numChild]
up[children[currentNode][1-numChild]]=currentChild
dist[children[currentNode][1-numChild]]+=currentBLen
#TODO update nDesc0 of nodes afected by the re-rooting
if HnZ:
node0=currentChild
while node0!=None:
if children[node0]:
if dist[children[node0][0]]>effectivelyNon0BLen:
nDesc0[node0]=1
else:
nDesc0[node0]=nDesc0[children[node0][0]]
if dist[children[node0][1]]>effectivelyNon0BLen:
nDesc0[node0]+=1
else:
nDesc0[node0]+=nDesc0[children[node0][1]]
else:
nDesc0[node0]=1+len(minorSequences[node0])
node0=up[node0]
return newRoot
else:
return sampleNode
#Robinson-Foulds distance (1981) using a simplification of the algorithm from Day 1985.
#this function prepare the data to compare trees to a reference one t1.
#I split in two functions (the second one is RobinsonFouldsWithDay1985() below) so that I don't have to repeat these steps for the reference tree if I compare to the same reference tree multiple times.
def prepareTreeComparison(tree,t1,rooted=False,minimumBLen=0.000006):
"""
Myrthe:
I extended this to calculate the RFL distance (see the Robinson Foulds paper) where they describe this.
Basically, for every branch that is shared among the two trees, add the absolute difference of the two branches to the RFL.
(This is first stored seperately as the KL value first).
For every branch that is only in either of the two trees, add the length to the RFL distance.
For the tree that is 'prepared for comparison', usually the true tree, I will store two hash tables (python dictionaries) together containing all branch lengths.
One contains all leaf-branches. These are indexed by the leaf's name, usually a number (node.name).
The other dictionary contains all inner branches, indexed by the <Left, Right> values of the subtree that is attached by the branch of interest.
(One could improve the implementation by writing one's own hash maps and functions. Given that the indices have certain limits to what values they can become, it would be easy to obtain a perfect hash function)
Furthermore, I calculate the sum of all the inner branch lengths. Whenever in the second function of the Day's algorithm (the comparison with the estimated tree),
a branch is found in both trees, I add the absolute difference between the two branches, and substract the branch length of the true tree.
I don't do this for leaf branches, as we can be sure that a leaf branch exists in both trees (if higher than the minimum length).
(I do this because it is less straight forward to add branch lengths of the true tree when they are not found during the comparison with the estimated tree)
Similar to the normal RF distance function, I do not take into account branches with length smaller than the minimum branch length.
However, cases may occur that a branch exists in both trees, but in one of them it is lower than the minimum branch length, making the RFL less accurate.
:param tree: input tree
:param t1: input root
:param rooted:
:param minimumBLen:
:param addRootRFL: Should the distance from the root node up be taken into account? I think this has usually no significance, and is always set to 1.0.
:return: Various metrics, among which the RFL.
"""
children=tree.children
up=tree.up
dist=tree.dist
name=tree.name
exploredChildren = [0] * len(up)
maxSoFar=[float("-inf")] * len(up)
minSoFar=[float("inf")] * len(up)
nDescendants = [0] * len(up)
tree.exploredChildren=exploredChildren
tree.maxSoFar=maxSoFar
tree.minSoFar=minSoFar
tree.nDescendants=nDescendants
#dictionary of values given to sequence names
leafNameDict={}
#list of sequence names sorted according to value
leafNameDictReverse=[]
#table containing clusters in the tree
nodeTable=[]
#dictionaries with branch lengths
branchLengthDict, leafDistDict = {}, {}
sumBranchLengths = 0 # sum of all branch lengths, except from the leaves
#if comparing as unrooted trees, calculate tot num of leaves (using a postorder traversal), which will become useful later
if not rooted:
nLeaves=0
node=t1
movingFrom=0
while node!=up[t1]:
if movingFrom==0: #0 means reaching node from parent, 1 means coming back from a child
if len(children[node])==0:
nLeaves+=1
nextNode=up[node]
movingFrom=1
nodeTable.append([0,0])
else:
nextNode=children[node][0]
movingFrom=0
else:
nChildren=len(children[node])
exploredChildren[node]+=1
if exploredChildren[node]==nChildren:
nextNode=up[node]
movingFrom=1
else:
nextNode=children[node][exploredChildren[node]]
movingFrom=0
node=nextNode
#implementing a non-recursive postorder traversal to assign values to internal nodes to fill nodeTable
leafCount=0
node=t1
movingFrom=0
lastL=float("inf")
lastR=float("-inf")
lastDesc=0
numBranches=0
while node!=up[t1]:
if movingFrom==0: #0 means reaching node from parent, 1 means coming back from a child
if len(children[node])==0:
name[node]=(name[node]).replace("?","_").replace("&","_")
leafNameDict[name[node]]=leafCount
leafNameDictReverse.append(name[node])
if rooted:
nodeTable.append([0,0])
lastL=leafCount
lastR=leafCount
lastDesc=1
leafCount+=1
nextNode=up[node]
movingFrom=1
leafDistDict[name[node]] = dist[node]
else:
exploredChildren[node]=0
nextNode=children[node][0]
movingFrom=0
else:
nChildren=len(children[node])
exploredChildren[node]+=1
if lastL<minSoFar[node]:
minSoFar[node]=lastL
if lastR>maxSoFar[node]:
maxSoFar[node]=lastR
nDescendants[node]+=lastDesc
if exploredChildren[node]==nChildren:
nextNode=up[node]
movingFrom=1
lastL=minSoFar[node]
lastR=maxSoFar[node]
lastDesc=nDescendants[node]
if node!=t1:
sumBranchLengths += dist[node]
if node==t1:
nodeTable[lastR][0]=lastL
nodeTable[lastR][1]=lastR
else:
if (not rooted) and (up[node]==t1) and (len(children[t1])==2):
if node==children[t1][1]:
currentBL=dist[node]+dist[children[t1][0]]
addBranch=True