-
Notifications
You must be signed in to change notification settings - Fork 54
/
treeanc.py
1681 lines (1380 loc) · 71.2 KB
/
treeanc.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 time, sys
import gc
import numpy as np
from Bio import Phylo
from Bio.Phylo.BaseTree import Clade
from . import config as ttconf
from . import MissingDataError,UnknownMethodError
from .seq_utils import seq2prof, prof2seq, normalize_profile, extend_profile
from .gtr import GTR
from .gtr_site_specific import GTR_site_specific
from .sequence_data import SequenceData
def compressed_sequence(node):
if node.name in node.tt.data.compressed_alignment and (not node.tt.reconstructed_tip_sequences):
return node.tt.data.compressed_alignment[node.name]
elif hasattr(node, '_cseq'):
return node._cseq
elif node.is_terminal(): # node without sequence when tip-reconstruction is off.
return None
elif hasattr(node, '_cseq'):
return node._cseq
else:
raise ValueError('Ancestral sequences are not yet inferred')
def mutations(node):
"""
Get the mutations on a tree branch. Take compressed sequences from both sides
of the branch (attached to the node), compute mutations between them, and
expand these mutations to the positions in the real sequences.
"""
if node.up is None:
return []
elif (not node.tt.reconstructed_tip_sequences) and node.name in node.tt.data.aln:
return node.tt.data.differences(node.up.cseq, node.tt.data.aln[node.name], seq2_compressed=False, mask=node.mask)
elif node.is_terminal() and (node.name not in node.tt.data.aln):
return []
else:
return node.tt.data.differences(node.up.cseq, node.cseq, mask=node.mask)
string_types = [str] if sys.version_info[0]==3 else [str, unicode]
Clade.sequence = property(lambda x: x.tt.sequence(x, as_string=False))
Clade.cseq = property(compressed_sequence)
Clade.mutations = property(mutations)
class TreeAnc(object):
"""
Class defines simple tree object with basic interface methods: reading and
saving from/to files, initializing leaves with sequences from the
alignment, making ancestral state inference
"""
def __init__(self, tree=None, aln=None, gtr=None, fill_overhangs=True,
ref=None, verbose = ttconf.VERBOSE, ignore_gaps=True,
convert_upper=True, seq_multiplicity=None, log=None,
compress=True, seq_len=None, ignore_missing_alns=False,
keep_node_order=False, rng_seed=None, **kwargs):
"""
TreeAnc constructor. It prepares the tree, attaches sequences to the leaf nodes,
and sets some configuration parameters.
Parameters
----------
tree : str, Bio.Phylo.Tree
Phylogenetic tree. String passed is interpreted as a filename with
a tree in a standard format that can be parsed by the Biopython Phylo module.
Branch length should be in units of average number of nucleotide or protein
substitutions per site. Use on trees with longer branches (>4) is not recommended.
aln : str, Bio.Align.MultipleSequenceAlignment, dict
Sequence alignment. If a string passed, it is interpreted as the
filename to read Biopython alignment from. If a dict is given,
this is assumed to be the output of vcf_utils.read_vcf which
specifies for each sequence the differences from a reference
gtr : str, GTR
GTR model object. If string passed, it is interpreted as the type of
the GTR model. A new GTR instance will be created for this type.
fill_overhangs : bool, default True
In some cases, the missing data on both ends of the alignment is
filled with the gap sign('-'). If set to True, the end-gaps are converted to "unknown"
characters ('N' for nucleotides, 'X' for aminoacids). Otherwise, the alignment is treated as-is
ref : None, optional
Reference sequence used in VCF mode
verbose : int, default 3
Verbosity level as number from 0 (lowest) to 10 (highest).
ignore_gaps : bool, default True
Ignore gaps in branch length calculations
convert_upper : bool, default True
Convert all sequences to upper case
seq_multiplicity : dict
If individual nodes in the tree correspond to multiple sampled sequences
(i.e. read count in a deep sequencing experiment), these can be
specified as a dictionary. This currently only affects rooting and
can be used to weigh individual tips by abundance or important during root search.
compress : bool, default True
reduce identical alignment columns to one (not useful when
inferring site specific GTR models).
seq_len : int, optional
length of the sequence. this is inferred from the input alignment or the reference
sequence in most cases but can be specified for other applications.
ignore_missing_alns : bool, default False
**kwargs
Keyword arguments to construct the GTR model
.. Note::
Some GTR types require additional configuration parameters.
If the new GTR is being instantiated, these parameters are expected
to be passed as kwargs. If nothing is passed, the default values are
used, which might cause unexpected results.
Raises
------
AttributeError
If no tree is passed in
"""
if tree is None:
raise TypeError("TreeAnc requires a tree!")
self.t_start = time.time()
self.verbose = verbose
self.log = log
self.ok = False
self.data = None
self.log_messages = set()
self.logger("TreeAnc: set-up",1)
self._internal_node_count = 0
self.use_mutation_length = False
self.ignore_gaps = ignore_gaps
self.reconstructed_tip_sequences = False
self.sequence_reconstruction = None
self.ignore_missing_alns = ignore_missing_alns
self.keep_node_order = keep_node_order
self.rng = np.random.default_rng(seed=rng_seed)
self._tree = None
self.tree = tree
if tree is None:
raise MissingDataError("TreeAnc: tree loading failed! exiting")
# set up GTR model
self._gtr = None
self.set_gtr(gtr or 'JC69', **kwargs)
# set alignment and attach sequences to tree on success.
# otherwise self.data.aln will be None
self.data = SequenceData(aln, ref=ref, logger=self.logger, compress=compress,
convert_upper=convert_upper, fill_overhangs=fill_overhangs, ambiguous=self.gtr.ambiguous,
sequence_length=seq_len)
if self.gtr.is_site_specific and self.data.compress:
raise TypeError("TreeAnc: sequence compression and site specific gtr models are incompatible!" )
if self.data.aln and self.tree:
self._check_alignment_tree_gtr_consistency()
def logger(self, msg, level, warn=False, only_once=False):
"""
Print log message *msg* to stdout.
Parameters
-----------
msg : str
String to print on the screen
level : int
Log-level. Only the messages with a level higher than the
current verbose level will be shown.
warn : bool
Warning flag. If True, the message will be displayed
regardless of its log-level.
"""
if only_once and msg in self.log_messages:
return
self.log_messages.add(msg)
lw=80
if level<self.verbose or (warn and level<=self.verbose):
from textwrap import fill
dt = time.time() - self.t_start
outstr = '\n' if level<2 else ''
initial_indent = format(dt, '4.2f')+'\t' + level*'-'
subsequent_indent = " "*len(format(dt, '4.2f')) + "\t" + " "*level
outstr += fill(msg, width=lw, initial_indent=initial_indent, subsequent_indent=subsequent_indent)
print(outstr, file=sys.stdout)
####################################################################
## SET-UP
####################################################################
@property
def leaves_lookup(self):
"""
The :code:`{leaf-name:leaf-node}` dictionary. It enables fast
search of a tree leaf object by its name.
"""
return self._leaves_lookup
@property
def gtr(self):
"""
:setter: Sets the GTR object passed in
:getter: Returns the current GTR object
"""
return self._gtr
@gtr.setter
def gtr(self, value):
"""
Parameters
-----------
value : GTR
the new GTR object
"""
if not isinstance(value, (GTR, GTR_site_specific)):
raise TypeError("GTR instance expected")
self._gtr = value
def set_gtr(self, in_gtr, **kwargs):
"""
Create new GTR model if needed, and set the model as an attribute of the
TreeAnc class
Parameters
-----------
in_gtr : str, GTR
The gtr model to be assigned. If string is passed,
it is taken as the name of a standard GTR model, and is
attempted to be created through :code:`GTR.standard()` interface. If a
GTR instance is passed, it is set directly .
**kwargs
Keyword arguments to construct the GTR model. If none are passed, defaults
are assumed.
"""
if isinstance(in_gtr, str):
self._gtr = GTR.standard(model=in_gtr, **kwargs)
self._gtr.logger = self.logger
elif isinstance(in_gtr, (GTR, GTR_site_specific)):
self._gtr = in_gtr
self._gtr.logger=self.logger
else:
self.logger("TreeAnc.gtr_setter: can't interpret GTR model", 1, warn=True)
raise TypeError("Cannot set GTR model in TreeAnc class: GTR or "
"string expected")
if self._gtr.ambiguous is None:
self.fill_overhangs=False
@property
def aln(self):
'''
:setter: Sets the alignment
:getter: Returns the alignment
'''
return self.data.aln
@aln.setter
def aln(self,in_aln):
self.data.aln=in_aln
if self.tree:
self._check_alignment_tree_gtr_consistency()
@property
def tree(self):
"""
The phylogenetic tree currently used by the TreeAnc.
:setter: Sets the tree. Directly if passed as Phylo.Tree, or by reading from \
file if passed as a str.
:getter: Returns the tree as a Phylo.Tree object
"""
return self._tree
@tree.setter
def tree(self, in_tree):
'''
assigns a tree to the internal self._tree variable. The tree is either
loaded from file (if in_tree is str) or assigned (if in_tree is a Phylo.tree)
'''
from os.path import isfile
self._tree = None
if isinstance(in_tree, Phylo.BaseTree.Tree):
self._tree = in_tree
elif type(in_tree) in string_types and isfile(in_tree):
try:
self._tree=Phylo.read(in_tree, 'newick')
except:
fmt = in_tree.split('.')[-1]
if fmt in ['nexus', 'nex']:
self._tree=Phylo.read(in_tree, 'nexus')
else:
raise MissingDataError('TreeAnc: could not load tree, format needs to be nexus or newick! input was '+str(in_tree))
else:
raise MissingDataError('TreeAnc: could not load tree! input was '+str(in_tree))
if self._tree.count_terminals()<3:
raise MissingDataError('TreeAnc: tree in %s as only %d tips. Please check your tree!'%(str(in_tree), self._tree.count_terminals()))
# remove all existing sequence attributes
branch_length_warning = False
for node in self._tree.find_clades():
node.branch_length = node.branch_length if node.branch_length else 0.0
if node.branch_length > ttconf.MAX_BRANCH_LENGTH:
branch_length_warning = True
if hasattr(node, "_cseq"):
node.__delattr__("_cseq")
node.original_length = node.branch_length
node.mutation_length = node.branch_length
if branch_length_warning:
self.logger("WARNING: TreeTime has detected branches that are longer than %d. "
"TreeTime requires trees where branch length is in units of average number "
"of nucleotide or protein substitutions per site. "
"Use on trees with longer branches is not recommended for ancestral sequence reconstruction."%(ttconf.MAX_BRANCH_LENGTH), 0, warn=True)
self.prepare_tree()
if self.data:
self._check_alignment_tree_gtr_consistency()
return ttconf.SUCCESS
@property
def one_mutation(self):
"""
Returns
-------
float
inverse of the uncompressed sequence length - length scale for short branches
"""
return 1.0/self.data.full_length if self.data.full_length else np.nan
@one_mutation.setter
def one_mutation(self,om):
self.logger("TreeAnc: one_mutation can't be set",1)
@property
def seq_len(self):
return self.data.full_length
@property
def sequence_length(self):
return self.data.full_length
def _check_alignment_tree_gtr_consistency(self):
'''
For each node of the tree, check whether there is a sequence available
in the alignment and assign this sequence as a character array
'''
if len(self.tree.get_terminals()) != len(self.data.aln):
self.logger(f"**WARNING: Number of tips in tree ({len(self.tree.get_terminals())}) differs from number of sequences in alignment ({len(self.data.aln)})**", 3, warn=True)
failed_leaves= 0
# loop over leaves and assign multiplicities of leaves (e.g. number of identical reads)
for l in self.tree.get_terminals():
if l.name in self.data.seq_multiplicity:
l.count = self.data.seq_multiplicity[l.name]
else:
l.count = 1.0
# loop over tree, and assign sequences
for l in self.tree.find_clades():
if hasattr(l, 'branch_state'): del l.branch_state
if l.name not in self.data.compressed_alignment and l.is_terminal():
self.logger("***WARNING: TreeAnc._check_alignment_tree_gtr_consistency: NO SEQUENCE FOR LEAF: '%s'" % l.name, 0, warn=True)
failed_leaves += 1
if not self.ignore_missing_alns and failed_leaves > self.tree.count_terminals()/3:
raise MissingDataError("TreeAnc._check_alignment_tree_gtr_consistency: At least 30\\% terminal nodes cannot be assigned a sequence!\n"
"Are you sure the alignment belongs to the tree?")
else: # could not assign sequence for internal node - is OK
pass
if failed_leaves:
self.logger("***WARNING: TreeAnc: %d nodes don't have a matching sequence in the alignment."
" POSSIBLE ERROR."%failed_leaves, 0, warn=True)
# extend profile to contain additional unknown characters
extend_profile(self.gtr, [self.data.ref] if self.data.is_sparse
else self.data.aln.values(), logger=self.logger)
self.ok = True
def prepare_tree(self):
"""
Set link to parent and calculate distance to root for all tree nodes.
Should be run once the tree is read and after every rerooting,
topology change or branch length optimizations.
"""
self.sequence_reconstruction = False
self.tree.root.branch_length = 0.001
self.tree.root.mask = None
self.tree.root.mutation_length = self.tree.root.branch_length
if not self.keep_node_order:
self.tree.ladderize()
self._prepare_nodes()
self._leaves_lookup = {node.name:node for node in self.tree.get_terminals()}
def _prepare_nodes(self):
"""
Set auxilliary parameters to every node of the tree.
"""
self.tree.root.up = None
self.tree.root.tt = self
self.tree.root.bad_branch=self.tree.root.bad_branch if hasattr(self.tree.root, 'bad_branch') else False
name_set = {n.name for n in self.tree.find_clades() if n.name}
internal_node_count = 0
for clade in self.tree.get_nonterminals(order='preorder'): # parents first
if clade.name is None:
tmp = "NODE_" + format(internal_node_count, '07d')
while tmp in name_set:
internal_node_count += 1
tmp = "NODE_" + format(internal_node_count, '07d')
clade.name = tmp
name_set.add(clade.name)
internal_node_count+=1
for c in clade.clades:
c.up = clade
c.tt = self
for clade in self.tree.find_clades(order='postorder'): # children first
if clade.is_terminal():
clade.bad_branch = clade.bad_branch if hasattr(clade, 'bad_branch') else False
else:
clade.bad_branch = all([c.bad_branch for c in clade])
if not hasattr(clade, "mask"):
clade.mask = None
self._calc_dist2root()
self._internal_node_count = max(internal_node_count, self._internal_node_count)
def _calc_dist2root(self):
"""
For each node in the tree, set its root-to-node distance as dist2root
attribute
"""
self.tree.root.dist2root = 0.0
for clade in self.tree.get_nonterminals(order='preorder'): # parents first
for c in clade.clades:
c.dist2root = clade.dist2root + c.mutation_length
####################################################################
## END SET-UP
####################################################################
###################################################################
### ancestral reconstruction
###################################################################
def reconstruct_anc(self,*args, **kwargs):
"""Shortcut for :py:meth:`treetime.TreeAnc.infer_ancestral_sequences`
"""
return self.infer_ancestral_sequences(*args,**kwargs)
def infer_ancestral_sequences(self, method='probabilistic', infer_gtr=False,
marginal=False, reconstruct_tip_states=False, **kwargs):
"""Reconstruct ancestral sequences
Parameters
----------
method : str
Method to use. Supported values are "parsimony", "fitch", "probabilistic" and "ml"
infer_gtr : bool
Infer a GTR model before reconstructing the sequences
marginal : bool
Assign sequences that are most likely after averaging over all other nodes
instead of the jointly most likely sequences.
reconstruct_tip_states : bool, optional
Reconstruct sequences of terminal nodes/leaves, thereby replacing ambiguous
characters with the inferred base/state. default: False
**kwargs
additional keyword arguments that are passed down to :py:meth:`TreeAnc.infer_gtr` and :py:meth:`TreeAnc._ml_anc`
Returns
-------
N_diff : int
Number of nucleotides different from the previous
reconstruction. If there were no pre-set sequences, returns N*L
"""
if not self.ok:
raise MissingDataError("TreeAnc.infer_ancestral_sequences: ERROR, sequences or tree are missing")
self.logger("TreeAnc.infer_ancestral_sequences with method: %s, %s"%(method, 'marginal' if marginal else 'joint'), 1)
if method.lower() in ['ml', 'probabilistic']:
if marginal:
_ml_anc = self._ml_anc_marginal
else:
_ml_anc = self._ml_anc_joint
elif method.lower() in ['fitch', 'parsimony']:
_ml_anc = self._fitch_anc
else:
raise UnknownMethodError("Reconstruction method needs to be in ['ml', 'probabilistic', 'fitch', 'parsimony'], got '{}'".format(method))
if infer_gtr:
self.infer_gtr(marginal=marginal, **kwargs)
N_diff = _ml_anc(reconstruct_tip_states=reconstruct_tip_states, **kwargs)
else:
N_diff = _ml_anc(reconstruct_tip_states=reconstruct_tip_states, **kwargs)
return N_diff
###################################################################
### FITCH
###################################################################
def _fitch_anc(self, **kwargs):
"""
Reconstruct ancestral states using Fitch's algorithm. It implements
the iteration from leaves to the root constructing the Fitch profiles for
each character of the sequence, and then by propagating from the root
to the leaves, reconstructs the sequences of the internal nodes.
Keyword Args
------------
Returns
-------
Ndiff : int
Number of the characters that changed since the previous
reconstruction. These changes are determined from the pre-set
sequence attributes of the nodes. If there are no sequences available
(i.e., no reconstruction has been made before), returns the total
number of characters in the tree.
"""
# set fitch profiiles to each terminal node
for l in self.tree.get_terminals():
l.state = [[k] for k in l.cseq]
L = self.data.compressed_length
self.logger("TreeAnc._fitch_anc: Walking up the tree, creating the Fitch profiles",2)
for node in self.tree.get_nonterminals(order='postorder'):
node.state = [self._fitch_state(node, k) for k in range(L)]
ambs = [i for i in range(L) if len(self.tree.root.state[i])>1]
if len(ambs) > 0:
for amb in ambs:
self.logger("Ambiguous state of the root sequence "
"in the position %d: %s, "
"choosing %s" % (amb, str(self.tree.root.state[amb]),
self.tree.root.state[amb][0]), 4)
self.tree.root._cseq = np.array([k[self.rng.integers(len(k)) if len(k)>1 else 0]
for k in self.tree.root.state])
self.logger("TreeAnc._fitch_anc: Walking down the self.tree, generating sequences from the "
"Fitch profiles.", 2)
N_diff = 0
for node in self.tree.get_nonterminals(order='preorder'):
if node.up != None: # not root
sequence = np.array([node.up._cseq[i]
if node.up._cseq[i] in node.state[i]
else node.state[i][0] for i in range(L)])
if self.sequence_reconstruction:
N_diff += (sequence!=node.cseq).sum()
else:
N_diff += L
node._cseq = sequence
del node.state # no need to store Fitch states
self.sequence_reconstruction = 'parsimony'
self.logger("Done ancestral state reconstruction",3)
return N_diff
def _fitch_state(self, node, pos):
"""
Determine the Fitch profile for a single character of the node's sequence.
The profile is essentially the intersection between the children's
profiles or, if the former is empty, the union of the profiles.
Parameters
----------
node : PhyloTree.Clade:
Internal node which the profiles are to be determined
pos : int
Position in the node's sequence which the profiles should
be determinedf for.
Returns
-------
state : numpy.array
Fitch profile for the character at position pos of the given node.
"""
state = self._fitch_intersect([k.state[pos] for k in node.clades])
if len(state) == 0:
state = np.concatenate([k.state[pos] for k in node.clades])
return state
def _fitch_intersect(self, arrays):
"""
Find the intersection of any number of 1D arrays.
Return the sorted, unique values that are in all of the input arrays.
Adapted from numpy.lib.arraysetops.intersect1d
"""
def pairwise_intersect(arr1, arr2):
s2 = set(arr2)
b3 = [val for val in arr1 if val in s2]
return b3
arrays = list(arrays) # allow assignment
N = len(arrays)
while N > 1:
arr1 = arrays.pop()
arr2 = arrays.pop()
arr = pairwise_intersect(arr1, arr2)
arrays.append(arr)
N = len(arrays)
return arrays[0]
###################################################################
### Maximum Likelihood
###################################################################
def sequence_LH(self, pos=None, full_sequence=False):
"""return the likelihood of the observed sequences given the tree
Parameters
----------
pos : int, optional
position in the sequence, if none, the sum over all positions will be returned
full_sequence : bool, optional
does the position refer to the full or compressed sequence, by default compressed sequence is assumed.
Returns
-------
float
likelihood
"""
if not hasattr(self.tree, "total_sequence_LH"):
self.logger("TreeAnc.sequence_LH: you need to run marginal ancestral inference first!", 1)
self.infer_ancestral_sequences(marginal=True)
if pos is not None:
if full_sequence:
compressed_pos = self.data.full_to_compressed_sequence_map[pos]
else:
compressed_pos = pos
return self.tree.sequence_LH[compressed_pos]
else:
return self.tree.total_sequence_LH
def ancestral_likelihood(self):
"""
Calculate the likelihood of the given realization of the sequences in
the tree
Returns
-------
log_lh : float
The tree likelihood given the sequences
"""
log_lh = np.zeros(self.data.multiplicity().shape[0])
for node in self.tree.find_clades(order='postorder'):
if node.up is None: # root node
# 0-1 profile
profile = seq2prof(node.cseq, self.gtr.profile_map)
# get the probabilities to observe each nucleotide
profile *= self.gtr.Pi
profile = profile.sum(axis=1)
log_lh += np.log(profile) # product over all characters
continue
t = node.branch_length
indices = np.array([(self.gtr.state_index[a], self.gtr.state_index[b])
for a, b in zip(node.up.cseq, node.cseq)])
logQt = np.log(self.gtr.expQt(t))
lh = logQt[indices[:, 1], indices[:, 0]]
log_lh += lh
return log_lh
def _branch_length_to_gtr(self, node):
"""
Set branch lengths to either mutation lengths of given branch lengths.
The assigend values are to be used in the following ML analysis.
"""
if self.use_mutation_length:
return max(ttconf.MIN_BRANCH_LENGTH*self.one_mutation, node.mutation_length)
else:
return max(ttconf.MIN_BRANCH_LENGTH*self.one_mutation, node.branch_length)
def _ml_anc_marginal(self, sample_from_profile=False,
reconstruct_tip_states=False, debug=False, **kwargs):
"""
Perform marginal ML reconstruction of the ancestral states. In contrast to
joint reconstructions, this needs to access the probabilities rather than only
log probabilities and is hence handled by a separate function.
Parameters
----------
sample_from_profile : bool or str
assign sequences probabilistically according to the inferred probabilities
of ancestral states instead of to their ML value. This parameter can also
take the value 'root' in which case probabilistic sampling will happen
at the root but at no other node.
reconstruct_tip_states : bool, default False
reconstruct sequence assigned to leaves, will replace ambiguous characters
with the most likely definite character. Note that this will affect the mutations
assigned to branches.
"""
self.logger("TreeAnc._ml_anc_marginal: type of reconstruction: Marginal", 2)
self.postorder_traversal_marginal()
# choose sequence characters from this profile.
# treat root node differently to avoid piling up mutations on the longer branch
if sample_from_profile=='root':
root_sample_from_profile = True
other_sample_from_profile = False
elif isinstance(sample_from_profile, bool):
root_sample_from_profile = sample_from_profile
other_sample_from_profile = sample_from_profile
self.total_LH_and_root_sequence(sample_from_profile=root_sample_from_profile,
assign_sequence=True)
N_diff = self.preorder_traversal_marginal(reconstruct_tip_states=reconstruct_tip_states,
sample_from_profile=other_sample_from_profile,
assign_sequence=True)
self.logger("TreeAnc._ml_anc_marginal: ...done", 3)
self.reconstructed_tip_sequences = reconstruct_tip_states
# do clean-up:
if not debug:
for node in self.tree.find_clades():
try:
del node.marginal_log_Lx
del node.marginal_subtree_LH_prefactor
except:
pass
gc.collect()
self.sequence_reconstruction = 'marginal'
return N_diff
def total_LH_and_root_sequence(self, sample_from_profile=False, assign_sequence=False):
self.logger("Computing root node sequence and total tree likelihood...",3)
# Msg to the root from the distant part (equ frequencies)
if len(self.gtr.Pi.shape)==1:
self.tree.root.marginal_outgroup_LH = np.repeat([self.gtr.Pi], self.data.compressed_length, axis=0)
else:
self.tree.root.marginal_outgroup_LH = np.copy(self.gtr.Pi.T)
self.tree.root.marginal_profile, pre = normalize_profile(self.tree.root.marginal_outgroup_LH*self.tree.root.marginal_subtree_LH)
marginal_LH_prefactor = self.tree.root.marginal_subtree_LH_prefactor + pre
self.tree.sequence_LH = marginal_LH_prefactor
self.tree.total_sequence_LH = (self.tree.sequence_LH*self.data.multiplicity()).sum()
self.tree.sequence_marginal_LH = self.tree.total_sequence_LH
if assign_sequence:
seq, prof_vals, idxs = prof2seq(self.tree.root.marginal_profile,
self.gtr, sample_from_prof=sample_from_profile,
normalize=False, rng=self.rng)
self.tree.root._cseq = seq
def postorder_traversal_marginal(self):
L = self.data.compressed_length
n_states = self.gtr.alphabet.shape[0]
self.logger("Attaching sequence profiles to leafs... ", 3)
# set the leaves profiles. This doesn't ever need to be reassigned for leaves
for leaf in self.tree.get_terminals():
if not hasattr(leaf, "marginal_subtree_LH"):
if leaf.name in self.data.compressed_alignment:
leaf.marginal_subtree_LH = seq2prof(self.data.compressed_alignment[leaf.name], self.gtr.profile_map)
else:
leaf.marginal_subtree_LH = np.ones((L, n_states))
if not hasattr(leaf, "marginal_subtree_LH_prefactor"):
leaf.marginal_subtree_LH_prefactor = np.zeros(L)
self.logger("Postorder: computing likelihoods... ", 3)
# propagate leaves --> root, set the marginal-likelihood messages
for node in self.tree.get_nonterminals(order='postorder'): #leaves -> root
# regardless of what was before, set the profile to ones
tmp_log_subtree_LH = np.zeros((L,n_states), dtype=float)
node.marginal_subtree_LH_prefactor = np.zeros(L, dtype=float)
for ch in node.clades:
if ch.mask is None:
ch.marginal_log_Lx = self.gtr.propagate_profile(ch.marginal_subtree_LH,
self._branch_length_to_gtr(ch), return_log=True) # raw prob to transfer prob up
else:
ch.marginal_log_Lx = (self.gtr.propagate_profile(ch.marginal_subtree_LH,
self._branch_length_to_gtr(ch), return_log=True).T*ch.mask).T # raw prob to transfer prob up
tmp_log_subtree_LH += ch.marginal_log_Lx
node.marginal_subtree_LH_prefactor += ch.marginal_subtree_LH_prefactor
node.marginal_subtree_LH, offset = normalize_profile(tmp_log_subtree_LH, log=True)
node.marginal_subtree_LH_prefactor += offset # and store log-prefactor
def preorder_traversal_marginal(self, reconstruct_tip_states=False, sample_from_profile=False, assign_sequence=False):
self.logger("Preorder: computing marginal profiles...",3)
# propagate root -->> leaves, reconstruct the internal node sequences
# provided the upstream message + the message from the complementary subtree
N_diff = 0
for node in self.tree.find_clades(order='preorder'):
if node.up is None: # skip if node is root
continue
if hasattr(node, 'branch_state'): del node.branch_state
# integrate the information coming from parents with the information
# of all children my multiplying it to the prev computed profile
node.marginal_outgroup_LH, pre = normalize_profile(np.log(np.maximum(ttconf.TINY_NUMBER, node.up.marginal_profile)) - node.marginal_log_Lx,
log=True, return_offset=False)
if node.is_terminal() and (not reconstruct_tip_states): # skip remainder unless leaves are to be reconstructed
continue
tmp_msg_from_parent = self.gtr.evolve(node.marginal_outgroup_LH,
self._branch_length_to_gtr(node), return_log=False)
if node.mask is None:
node.marginal_profile, pre = normalize_profile(node.marginal_subtree_LH * tmp_msg_from_parent, return_offset=False)
else:
node.marginal_profile, pre = normalize_profile(node.marginal_subtree_LH * (node.mask*tmp_msg_from_parent.T + (1.0-node.mask)).T,
return_offset=False)
# choose sequence based maximal marginal LH.
if assign_sequence:
seq, prof_vals, idxs = prof2seq(node.marginal_profile, self.gtr,
sample_from_prof=sample_from_profile,
normalize=False, rng=self.rng)
if self.sequence_reconstruction:
N_diff += (seq!=node.cseq).sum()
else:
N_diff += self.data.compressed_length
#assign new sequence
node._cseq = seq
return N_diff
def _ml_anc_joint(self, sample_from_profile=False,
reconstruct_tip_states=False, debug=False, **kwargs):
"""
Perform joint ML reconstruction of the ancestral states. In contrast to
marginal reconstructions, this only needs to compare and multiply LH and
can hence operate in log space.
Parameters
----------
sample_from_profile : str
This parameter can take the value 'root' in which case probabilistic
sampling will happen at the root. otherwise sequences at ALL nodes are
set to the value that jointly optimized the likelihood.
reconstruct_tip_states : bool, default False
reconstruct sequence assigned to leaves, will replace ambiguous characters
with the most likely definite character. Note that this will affect the mutations
assigned to branches.
"""
N_diff = 0 # number of sites differ from perv reconstruction
L = self.data.compressed_length
n_states = self.gtr.alphabet.shape[0]
self.logger("TreeAnc._ml_anc_joint: type of reconstruction: Joint", 2)
self.logger("TreeAnc._ml_anc_joint: Walking up the tree, computing likelihoods... ", 3)
# for the internal nodes, scan over all states j of this node, maximize the likelihood
for node in self.tree.find_clades(order='postorder'):
if hasattr(node, 'branch_state'): del node.branch_state
if node.up is None:
node.joint_Cx=None # not needed for root
continue
branch_len = self._branch_length_to_gtr(node)
# transition matrix from parent states to the current node states.
# denoted as Pij(i), where j - parent state, i - node state
log_transitions = np.log(np.maximum(ttconf.TINY_NUMBER, self.gtr.expQt(branch_len)))
if node.is_terminal():
if node.name in self.data.compressed_alignment:
tmp_prof = seq2prof(self.data.compressed_alignment[node.name], self.gtr.profile_map)
msg_from_children = np.log(np.maximum(tmp_prof, ttconf.TINY_NUMBER))
else:
msg_from_children = np.zeros((L, n_states))
msg_from_children[np.isnan(msg_from_children) | np.isinf(msg_from_children)] = -ttconf.BIG_NUMBER
else:
# Product (sum-Log) over all child subtree likelihoods.
# this is prod_ch L_x(i)
msg_from_children = np.sum(np.stack([c.joint_Lx for c in node.clades], axis=0), axis=0)
if not debug:
# Now that we have calculated the current node's likelihood
# from its children, clean up likelihood matrices attached
# to children to save memory.
for c in node.clades:
del c.joint_Lx
# for every possible state of the parent node,
# get the best state of the current node
# and compute the likelihood of this state
# preallocate storage
node.joint_Lx = np.zeros((L, n_states)) # likelihood array
node.joint_Cx = np.zeros((L, n_states), dtype=np.uint16) # max LH indices
for char_i, char in enumerate(self.gtr.alphabet):
# Pij(i) * L_ch(i) for given parent state j
# if the node has a mask, P_ij is uniformly 1 at masked positions as no info is propagated
if node.mask is None:
msg_to_parent = (log_transitions[:,char_i].T + msg_from_children)
else:
msg_to_parent = ((log_transitions[:,char_i]*np.repeat([node.mask], self.gtr.n_states, axis=0).T) + msg_from_children)
# For this parent state, choose the best state of the current node
node.joint_Cx[:, char_i] = msg_to_parent.argmax(axis=1)
# and compute the likelihood of the best state of the current node
# given the state of the parent (char_i) -- at masked position, there is no contribution
node.joint_Lx[:, char_i] = msg_to_parent.max(axis=1)
if node.mask is not None:
node.joint_Lx[:, char_i] *= node.mask
# root node profile = likelihood of the total tree
msg_from_children = np.sum(np.stack([c.joint_Lx for c in self.tree.root], axis = 0), axis=0)
# Pi(i) * Prod_ch Lch(i)
self.tree.root.joint_Lx = msg_from_children + np.log(self.gtr.Pi).T
normalized_profile = (self.tree.root.joint_Lx.T - self.tree.root.joint_Lx.max(axis=1)).T
# choose sequence characters from this profile.
# treat root node differently to avoid piling up mutations on the longer branch
if sample_from_profile=='root':
root_sample_from_profile = True
elif isinstance(sample_from_profile, bool):
root_sample_from_profile = sample_from_profile
seq, anc_lh_vals, idxs = prof2seq(np.exp(normalized_profile), self.gtr,
sample_from_prof = root_sample_from_profile,
rng=self.rng)
# compute the likelihood of the most probable root sequence
self.tree.sequence_LH = np.choose(idxs, self.tree.root.joint_Lx.T)
self.tree.sequence_joint_LH = (self.tree.sequence_LH*self.data.multiplicity()).sum()
self.tree.root._cseq = seq
self.tree.root.seq_idx = idxs
self.logger("TreeAnc._ml_anc_joint: Walking down the tree, computing maximum likelihood sequences...",3)
# for each node, resolve the conditioning on the parent node
nodes_to_reconstruct = self.tree.get_nonterminals(order='preorder')
if reconstruct_tip_states:
nodes_to_reconstruct += self.tree.get_terminals()
#TODO: Should we add tips without sequence here?
for node in nodes_to_reconstruct:
# root node has no mutations, everything else has been already set
if node.up is None:
continue
# choose the value of the Cx(i), corresponding to the state of the
# parent node i. This is the state of the current node
node.seq_idx = np.choose(node.up.seq_idx, node.joint_Cx.T)
# reconstruct seq, etc
tmp_sequence = np.choose(node.seq_idx, self.gtr.alphabet)
if self.sequence_reconstruction: