| 1 |
# Copyright 2005-2008 by Frank Kauff & Cymon J. Cox. All rights reserved. |
| 2 |
# This code is part of the Biopython distribution and governed by its |
| 3 |
# license. Please see the LICENSE file that should have been included |
| 4 |
# as part of this package. |
| 5 |
|
| 6 |
"""Tree class to handle phylogenetic trees. |
| 7 |
|
| 8 |
Provides a set of methods to read and write newick-format tree descriptions, |
| 9 |
get information about trees (monphyly of taxon sets, congruence between trees, |
| 10 |
common ancestors,...) and to manipulate trees (reroot trees, split terminal |
| 11 |
nodes). |
| 12 |
""" |
| 13 |
# type: ignore |
| 14 |
|
| 15 |
import random |
| 16 |
|
| 17 |
from . import Nodes |
| 18 |
|
| 19 |
PRECISION_BRANCHLENGTH = 6 |
| 20 |
PRECISION_SUPPORT = 6 |
| 21 |
NODECOMMENT_START = "[&" |
| 22 |
NODECOMMENT_END = "]" |
| 23 |
|
| 24 |
|
| 25 |
class TreeError(Exception): |
| 26 |
pass |
| 27 |
|
| 28 |
|
| 29 |
class NodeData(object): |
| 30 |
"""Stores tree-relevant data associated with nodes (e.g. branches or otus).""" |
| 31 |
|
| 32 |
def __init__(self, taxon=None, branchlength=0.0, support=None, comment=None): |
| 33 |
self.taxon = taxon |
| 34 |
self.branchlength = branchlength |
| 35 |
self.support = support |
| 36 |
self.comment = comment |
| 37 |
|
| 38 |
|
| 39 |
class Tree(Nodes.Chain): |
| 40 |
"""Represents a tree using a chain of nodes with on predecessor (=ancestor) |
| 41 |
and multiple successors (=subclades). |
| 42 |
""" |
| 43 |
|
| 44 |
# A newick tree is parsed into nested list and then converted to a node list in two stages |
| 45 |
# mostly due to historical reasons. This could be done in one swoop). Note: parentheses ( ) and |
| 46 |
# colon : are not allowed in taxon names. This is against NEXUS standard, but makes life much |
| 47 |
# easier when parsing trees. |
| 48 |
|
| 49 |
## NOTE: Tree should store its data class in something like self.dataclass=data, |
| 50 |
## so that nodes that are generated have easy access to the data class |
| 51 |
## Some routines use automatically NodeData, this needs to be more concise |
| 52 |
|
| 53 |
def __init__( |
| 54 |
self, |
| 55 |
tree=None, |
| 56 |
weight=1.0, |
| 57 |
rooted=False, |
| 58 |
name="", |
| 59 |
data=NodeData, |
| 60 |
values_are_support=False, |
| 61 |
max_support=1.0, |
| 62 |
): |
| 63 |
"""Ntree(self,tree).""" |
| 64 |
Nodes.Chain.__init__(self) |
| 65 |
self.dataclass = data |
| 66 |
self.__values_are_support = values_are_support |
| 67 |
self.max_support = max_support |
| 68 |
self.weight = weight |
| 69 |
self.rooted = rooted |
| 70 |
self.name = name |
| 71 |
root = Nodes.Node(data()) |
| 72 |
self.root = self.add(root) |
| 73 |
if tree: # use the tree we have |
| 74 |
# if Tree is called from outside Nexus parser, we need to get rid of linebreaks, etc |
| 75 |
tree = tree.strip().replace("\n", "").replace("\r", "") |
| 76 |
# there's discrepancy whether newick allows semicolons et the end |
| 77 |
tree = tree.rstrip(";") |
| 78 |
subtree_info, base_info = self._parse(tree) |
| 79 |
root.data = self._add_nodedata(root.data, [[], base_info]) |
| 80 |
self._add_subtree(parent_id=root.id, tree=subtree_info) |
| 81 |
|
| 82 |
def _parse(self, tree): |
| 83 |
"""Parses (a,b,c...)[[[xx]:]yy] into subcomponents and travels down recursively.""" |
| 84 |
# Remove any leading/trailing white space - want any string starting |
| 85 |
# with " (..." should be recognised as a leaf, "(..." |
| 86 |
tree = tree.strip() |
| 87 |
if tree.count("(") != tree.count(")"): |
| 88 |
raise TreeError("Parentheses do not match in (sub)tree: " + tree) |
| 89 |
if tree.count("(") == 0: # a leaf |
| 90 |
# check if there's a colon, or a special comment, or both after the taxon name |
| 91 |
nodecomment = tree.find(NODECOMMENT_START) |
| 92 |
colon = tree.find(":") |
| 93 |
if colon == -1 and nodecomment == -1: # none |
| 94 |
return [tree, [None]] |
| 95 |
elif colon == -1 and nodecomment > -1: # only special comment |
| 96 |
return [tree[:nodecomment], self._get_values(tree[nodecomment:])] |
| 97 |
elif colon > -1 and nodecomment == -1: # only numerical values |
| 98 |
return [tree[:colon], self._get_values(tree[colon + 1 :])] |
| 99 |
elif ( |
| 100 |
colon < nodecomment |
| 101 |
): # taxon name ends at first colon or with special comment |
| 102 |
return [tree[:colon], self._get_values(tree[colon + 1 :])] |
| 103 |
else: |
| 104 |
return [tree[:nodecomment], self._get_values(tree[nodecomment:])] |
| 105 |
else: |
| 106 |
closing = tree.rfind(")") |
| 107 |
val = self._get_values(tree[closing + 1 :]) |
| 108 |
if not val: |
| 109 |
val = [None] |
| 110 |
subtrees = [] |
| 111 |
plevel = 0 |
| 112 |
prev = 1 |
| 113 |
for p in range(1, closing): |
| 114 |
if tree[p] == "(": |
| 115 |
plevel += 1 |
| 116 |
elif tree[p] == ")": |
| 117 |
plevel -= 1 |
| 118 |
elif tree[p] == "," and plevel == 0: |
| 119 |
subtrees.append(tree[prev:p]) |
| 120 |
prev = p + 1 |
| 121 |
subtrees.append(tree[prev:closing]) |
| 122 |
subclades = [self._parse(subtree) for subtree in subtrees] |
| 123 |
return [subclades, val] |
| 124 |
|
| 125 |
def _add_subtree(self, parent_id=None, tree=None): |
| 126 |
"""Adds leaf or tree (in newick format) to a parent_id.""" |
| 127 |
if parent_id is None: |
| 128 |
raise TreeError("Need node_id to connect to.") |
| 129 |
for st in tree: |
| 130 |
nd = self.dataclass() |
| 131 |
nd = self._add_nodedata(nd, st) |
| 132 |
if isinstance(st[0], list): # it's a subtree |
| 133 |
sn = Nodes.Node(nd) |
| 134 |
self.add(sn, parent_id) |
| 135 |
self._add_subtree(sn.id, st[0]) |
| 136 |
else: # it's a leaf |
| 137 |
nd.taxon = st[0] |
| 138 |
leaf = Nodes.Node(nd) |
| 139 |
self.add(leaf, parent_id) |
| 140 |
|
| 141 |
def _add_nodedata(self, nd, st): |
| 142 |
"""Add data to the node parsed from the comments, taxon and support.""" |
| 143 |
if isinstance(st[1][-1], str) and st[1][-1].startswith(NODECOMMENT_START): |
| 144 |
nd.comment = st[1].pop(-1) |
| 145 |
# if the first element is a string, it's the subtree node taxon |
| 146 |
elif isinstance(st[1][0], str): |
| 147 |
nd.taxon = st[1][0] |
| 148 |
st[1] = st[1][1:] |
| 149 |
if len(st) > 1: |
| 150 |
if ( |
| 151 |
len(st[1]) >= 2 |
| 152 |
): # if there's two values, support comes first. Is that always so? |
| 153 |
nd.support = st[1][0] |
| 154 |
if st[1][1] is not None: |
| 155 |
nd.branchlength = st[1][1] |
| 156 |
elif ( |
| 157 |
len(st[1]) == 1 |
| 158 |
): # otherwise it could be real branchlengths or support as branchlengths |
| 159 |
if not self.__values_are_support: # default |
| 160 |
if st[1][0] is not None: |
| 161 |
nd.branchlength = st[1][0] |
| 162 |
else: |
| 163 |
nd.support = st[1][0] |
| 164 |
return nd |
| 165 |
|
| 166 |
def _get_values(self, text): |
| 167 |
"""Extracts values (support/branchlength) from xx[:yyy], xx.""" |
| 168 |
|
| 169 |
if text == "": |
| 170 |
return None |
| 171 |
nodecomment = None |
| 172 |
if NODECOMMENT_START in text: # if there's a [&....] comment, cut it out |
| 173 |
nc_start = text.find(NODECOMMENT_START) |
| 174 |
nc_end = text.find(NODECOMMENT_END) |
| 175 |
if nc_end == -1: |
| 176 |
raise TreeError( |
| 177 |
"Error in tree description: Found %s without matching %s" |
| 178 |
% (NODECOMMENT_START, NODECOMMENT_END) |
| 179 |
) |
| 180 |
nodecomment = text[nc_start : nc_end + 1] |
| 181 |
text = text[:nc_start] + text[nc_end + 1 :] |
| 182 |
|
| 183 |
# pase out supports and branchlengths, with internal node taxa info |
| 184 |
values = [] |
| 185 |
taxonomy = None |
| 186 |
for part in [t.strip() for t in text.split(":")]: |
| 187 |
if part: |
| 188 |
try: |
| 189 |
values.append(float(part)) |
| 190 |
except ValueError: |
| 191 |
assert taxonomy is None, "Two string taxonomies?" |
| 192 |
taxonomy = part |
| 193 |
if taxonomy: |
| 194 |
values.insert(0, taxonomy) |
| 195 |
if nodecomment: |
| 196 |
values.append(nodecomment) |
| 197 |
return values |
| 198 |
|
| 199 |
def _walk(self, node=None): |
| 200 |
"""Return all node_ids downwards from a node.""" |
| 201 |
|
| 202 |
if node is None: |
| 203 |
node = self.root |
| 204 |
for n in self.node(node).succ: |
| 205 |
yield n |
| 206 |
for sn in self._walk(n): |
| 207 |
yield sn |
| 208 |
|
| 209 |
def node(self, node_id): |
| 210 |
"""Return the instance of node_id. |
| 211 |
|
| 212 |
node = node(self,node_id) |
| 213 |
""" |
| 214 |
if node_id not in self.chain: |
| 215 |
raise TreeError("Unknown node_id: %d" % node_id) |
| 216 |
return self.chain[node_id] |
| 217 |
|
| 218 |
def split(self, parent_id=None, n=2, branchlength=1.0): |
| 219 |
"""Speciation: generates n (default two) descendants of a node. |
| 220 |
|
| 221 |
[new ids] = split(self,parent_id=None,n=2,branchlength=1.0): |
| 222 |
""" |
| 223 |
if parent_id is None: |
| 224 |
raise TreeError("Missing node_id.") |
| 225 |
ids = [] |
| 226 |
parent_data = self.chain[parent_id].data |
| 227 |
for i in range(n): |
| 228 |
node = Nodes.Node() |
| 229 |
if parent_data: |
| 230 |
node.data = self.dataclass() |
| 231 |
# each node has taxon and branchlength attribute |
| 232 |
if parent_data.taxon: |
| 233 |
node.data.taxon = parent_data.taxon + str(i) |
| 234 |
node.data.branchlength = branchlength |
| 235 |
ids.append(self.add(node, parent_id)) |
| 236 |
return ids |
| 237 |
|
| 238 |
def search_taxon(self, taxon): |
| 239 |
"""Returns the first matching taxon in self.data.taxon. Not restricted to terminal nodes. |
| 240 |
|
| 241 |
node_id = search_taxon(self,taxon) |
| 242 |
""" |
| 243 |
for id, node in self.chain.items(): |
| 244 |
if node.data.taxon == taxon: |
| 245 |
return id |
| 246 |
return None |
| 247 |
|
| 248 |
def prune(self, taxon): |
| 249 |
"""Prunes a terminal taxon from the tree. |
| 250 |
|
| 251 |
id_of_previous_node = prune(self,taxon) |
| 252 |
If taxon is from a bifurcation, the connectiong node will be collapsed |
| 253 |
and its branchlength added to remaining terminal node. This might be no |
| 254 |
longer a meaningful value' |
| 255 |
""" |
| 256 |
|
| 257 |
id = self.search_taxon(taxon) |
| 258 |
if id is None: |
| 259 |
raise TreeError("Taxon not found: %s" % taxon) |
| 260 |
elif id not in self.get_terminals(): |
| 261 |
raise TreeError("Not a terminal taxon: %s" % taxon) |
| 262 |
else: |
| 263 |
prev = self.unlink(id) |
| 264 |
self.kill(id) |
| 265 |
if len(self.node(prev).succ) == 1: |
| 266 |
if ( |
| 267 |
prev == self.root |
| 268 |
): # we deleted one branch of a bifurcating root, then we have to move the root upwards |
| 269 |
self.root = self.node(self.root).succ[0] |
| 270 |
self.node(self.root).branchlength = 0.0 |
| 271 |
self.kill(prev) |
| 272 |
else: |
| 273 |
succ = self.node(prev).succ[0] |
| 274 |
new_bl = ( |
| 275 |
self.node(prev).data.branchlength |
| 276 |
+ self.node(succ).data.branchlength |
| 277 |
) |
| 278 |
self.collapse(prev) |
| 279 |
self.node(succ).data.branchlength = new_bl |
| 280 |
return prev |
| 281 |
|
| 282 |
def get_taxa(self, node_id=None): |
| 283 |
"""Return a list of all otus downwards from a node. |
| 284 |
|
| 285 |
nodes = get_taxa(self,node_id=None) |
| 286 |
""" |
| 287 |
|
| 288 |
if node_id is None: |
| 289 |
node_id = self.root |
| 290 |
if node_id not in self.chain: |
| 291 |
raise TreeError("Unknown node_id: %d." % node_id) |
| 292 |
if self.chain[node_id].succ == []: |
| 293 |
if self.chain[node_id].data: |
| 294 |
return [self.chain[node_id].data.taxon] |
| 295 |
else: |
| 296 |
return None |
| 297 |
else: |
| 298 |
list = [] |
| 299 |
for succ in self.chain[node_id].succ: |
| 300 |
list.extend(self.get_taxa(succ)) |
| 301 |
return list |
| 302 |
|
| 303 |
def get_terminals(self): |
| 304 |
"""Return a list of all terminal nodes.""" |
| 305 |
return [i for i in self.all_ids() if self.node(i).succ == []] |
| 306 |
|
| 307 |
def is_terminal(self, node): |
| 308 |
"""Returns True if node is a terminal node.""" |
| 309 |
return self.node(node).succ == [] |
| 310 |
|
| 311 |
def is_internal(self, node): |
| 312 |
"""Returns True if node is an internal node.""" |
| 313 |
return len(self.node(node).succ) > 0 |
| 314 |
|
| 315 |
def is_preterminal(self, node): |
| 316 |
"""Returns True if all successors of a node are terminal ones.""" |
| 317 |
if self.is_terminal(node): |
| 318 |
return False not in [self.is_terminal(n) for n in self.node(node).succ] |
| 319 |
else: |
| 320 |
return False |
| 321 |
|
| 322 |
def count_terminals(self, node=None): |
| 323 |
"""Counts the number of terminal nodes that are attached to a node.""" |
| 324 |
if node is None: |
| 325 |
node = self.root |
| 326 |
return len([n for n in self._walk(node) if self.is_terminal(n)]) |
| 327 |
|
| 328 |
def collapse_genera(self, space_equals_underscore=True): |
| 329 |
"""Collapses all subtrees which belong to the same genus (i.e share the same first word in their taxon name.)""" |
| 330 |
|
| 331 |
while True: |
| 332 |
for n in self._walk(): |
| 333 |
if self.is_terminal(n): |
| 334 |
continue |
| 335 |
taxa = self.get_taxa(n) |
| 336 |
genera = [] |
| 337 |
for t in taxa: |
| 338 |
if space_equals_underscore: |
| 339 |
t = t.replace(" ", "_") |
| 340 |
try: |
| 341 |
genus = t.split("_", 1)[0] |
| 342 |
except: |
| 343 |
genus = "None" |
| 344 |
if genus not in genera: |
| 345 |
genera.append(genus) |
| 346 |
if len(genera) == 1: |
| 347 |
self.node(n).data.taxon = genera[0] + " <collapsed>" |
| 348 |
# now we kill all nodes downstream |
| 349 |
nodes2kill = [kn for kn in self._walk(node=n)] |
| 350 |
for kn in nodes2kill: |
| 351 |
self.kill(kn) |
| 352 |
self.node(n).succ = [] |
| 353 |
break # break out of for loop because node list from _walk will be inconsistent |
| 354 |
else: # for loop exhausted: no genera to collapse left |
| 355 |
break # while |
| 356 |
|
| 357 |
def sum_branchlength(self, root=None, node=None): |
| 358 |
"""Adds up the branchlengths from root (default self.root) to node. |
| 359 |
|
| 360 |
sum = sum_branchlength(self,root=None,node=None) |
| 361 |
""" |
| 362 |
|
| 363 |
if root is None: |
| 364 |
root = self.root |
| 365 |
if node is None: |
| 366 |
raise TreeError("Missing node id.") |
| 367 |
blen = 0.0 |
| 368 |
while node is not None and node is not root: |
| 369 |
blen += self.node(node).data.branchlength |
| 370 |
node = self.node(node).prev |
| 371 |
return blen |
| 372 |
|
| 373 |
def set_subtree(self, node): |
| 374 |
"""Return subtree as a set of nested sets. |
| 375 |
|
| 376 |
sets = set_subtree(self,node) |
| 377 |
""" |
| 378 |
|
| 379 |
if self.node(node).succ == []: |
| 380 |
return self.node(node).data.taxon |
| 381 |
else: |
| 382 |
try: |
| 383 |
return frozenset(self.set_subtree(n) for n in self.node(node).succ) |
| 384 |
except: |
| 385 |
print(node) |
| 386 |
print(self.node(node).succ) |
| 387 |
for n in self.node(node).succ: |
| 388 |
print("%s %s" % (n, self.set_subtree(n))) |
| 389 |
print([self.set_subtree(n) for n in self.node(node).succ]) |
| 390 |
raise |
| 391 |
|
| 392 |
def is_identical(self, tree2): |
| 393 |
"""Compare tree and tree2 for identity. |
| 394 |
|
| 395 |
result = is_identical(self,tree2) |
| 396 |
""" |
| 397 |
return self.set_subtree(self.root) == tree2.set_subtree(tree2.root) |
| 398 |
|
| 399 |
def is_compatible(self, tree2, threshold, strict=True): |
| 400 |
"""Compares branches with support>threshold for compatibility. |
| 401 |
|
| 402 |
result = is_compatible(self,tree2,threshold) |
| 403 |
""" |
| 404 |
|
| 405 |
# check if both trees have the same set of taxa. strict=True enforces this. |
| 406 |
missing2 = set(self.get_taxa()) - set(tree2.get_taxa()) |
| 407 |
missing1 = set(tree2.get_taxa()) - set(self.get_taxa()) |
| 408 |
if strict and (missing1 or missing2): |
| 409 |
if missing1: |
| 410 |
print( |
| 411 |
"Taxon/taxa %s is/are missing in tree %s" |
| 412 |
% (",".join(missing1), self.name) |
| 413 |
) |
| 414 |
if missing2: |
| 415 |
print( |
| 416 |
"Taxon/taxa %s is/are missing in tree %s" |
| 417 |
% (",".join(missing2), tree2.name) |
| 418 |
) |
| 419 |
raise TreeError("Can't compare trees with different taxon compositions.") |
| 420 |
t1 = [ |
| 421 |
(set(self.get_taxa(n)), self.node(n).data.support) |
| 422 |
for n in self.all_ids() |
| 423 |
if self.node(n).succ |
| 424 |
and ( |
| 425 |
self.node(n).data |
| 426 |
and self.node(n).data.support |
| 427 |
and self.node(n).data.support >= threshold |
| 428 |
) |
| 429 |
] |
| 430 |
t2 = [ |
| 431 |
(set(tree2.get_taxa(n)), tree2.node(n).data.support) |
| 432 |
for n in tree2.all_ids() |
| 433 |
if tree2.node(n).succ |
| 434 |
and ( |
| 435 |
tree2.node(n).data |
| 436 |
and tree2.node(n).data.support |
| 437 |
and tree2.node(n).data.support >= threshold |
| 438 |
) |
| 439 |
] |
| 440 |
conflict = [] |
| 441 |
for st1, sup1 in t1: |
| 442 |
for st2, sup2 in t2: |
| 443 |
if not st1.issubset(st2) and not st2.issubset( |
| 444 |
st1 |
| 445 |
): # don't hiccup on upstream nodes |
| 446 |
intersect, notin1, notin2 = ( |
| 447 |
st1 & st2, |
| 448 |
st2 - st1, |
| 449 |
st1 - st2, |
| 450 |
) # all three are non-empty sets |
| 451 |
# if notin1==missing1 or notin2==missing2 <==> st1.issubset(st2) or st2.issubset(st1) ??? |
| 452 |
if intersect and not ( |
| 453 |
notin1.issubset(missing1) or notin2.issubset(missing2) |
| 454 |
): |
| 455 |
# omit conflicts due to missing taxa |
| 456 |
conflict.append( |
| 457 |
(st1, sup1, st2, sup2, intersect, notin1, notin2) |
| 458 |
) |
| 459 |
return conflict |
| 460 |
|
| 461 |
def common_ancestor(self, node1, node2): |
| 462 |
"""Return the common ancestor that connects two nodes. |
| 463 |
|
| 464 |
node_id = common_ancestor(self,node1,node2) |
| 465 |
""" |
| 466 |
|
| 467 |
l1 = [self.root] + self.trace(self.root, node1) |
| 468 |
l2 = [self.root] + self.trace(self.root, node2) |
| 469 |
return [n for n in l1 if n in l2][-1] |
| 470 |
|
| 471 |
def distance(self, node1, node2): |
| 472 |
"""Add and return the sum of the branchlengths between two nodes. |
| 473 |
dist = distance(self,node1,node2) |
| 474 |
""" |
| 475 |
|
| 476 |
ca = self.common_ancestor(node1, node2) |
| 477 |
return self.sum_branchlength(ca, node1) + self.sum_branchlength(ca, node2) |
| 478 |
|
| 479 |
def is_monophyletic(self, taxon_list): |
| 480 |
"""Return node_id of common ancestor if taxon_list is monophyletic, -1 otherwise. |
| 481 |
|
| 482 |
result = is_monophyletic(self,taxon_list) |
| 483 |
""" |
| 484 |
if isinstance(taxon_list, str): |
| 485 |
taxon_set = set([taxon_list]) |
| 486 |
else: |
| 487 |
taxon_set = set(taxon_list) |
| 488 |
node_id = self.root |
| 489 |
while True: |
| 490 |
subclade_taxa = set(self.get_taxa(node_id)) |
| 491 |
if subclade_taxa == taxon_set: # are we there? |
| 492 |
return node_id |
| 493 |
else: # check subnodes |
| 494 |
for subnode in self.chain[node_id].succ: |
| 495 |
if set(self.get_taxa(subnode)).issuperset( |
| 496 |
taxon_set |
| 497 |
): # taxon_set is downstream |
| 498 |
node_id = subnode |
| 499 |
break # out of for loop |
| 500 |
else: |
| 501 |
return -1 # taxon set was not with successors, for loop exhausted |
| 502 |
|
| 503 |
def is_bifurcating(self, node=None): |
| 504 |
"""Return True if tree downstream of node is strictly bifurcating.""" |
| 505 |
if node is None: |
| 506 |
node = self.root |
| 507 |
if ( |
| 508 |
node == self.root and len(self.node(node).succ) == 3 |
| 509 |
): # root can be trifurcating, because it has no ancestor |
| 510 |
return ( |
| 511 |
self.is_bifurcating(self.node(node).succ[0]) |
| 512 |
and self.is_bifurcating(self.node(node).succ[1]) |
| 513 |
and self.is_bifurcating(self.node(node).succ[2]) |
| 514 |
) |
| 515 |
if len(self.node(node).succ) == 2: |
| 516 |
return self.is_bifurcating(self.node(node).succ[0]) and self.is_bifurcating( |
| 517 |
self.node(node).succ[1] |
| 518 |
) |
| 519 |
elif len(self.node(node).succ) == 0: |
| 520 |
return True |
| 521 |
else: |
| 522 |
return False |
| 523 |
|
| 524 |
def branchlength2support(self): |
| 525 |
"""Move values stored in data.branchlength to data.support, and set branchlength to 0.0 |
| 526 |
|
| 527 |
This is necessary when support has been stored as branchlength (e.g. paup), and has thus |
| 528 |
been read in as branchlength. |
| 529 |
""" |
| 530 |
|
| 531 |
for n in self.chain: |
| 532 |
self.node(n).data.support = self.node(n).data.branchlength |
| 533 |
self.node(n).data.branchlength = 0.0 |
| 534 |
|
| 535 |
def convert_absolute_support(self, nrep): |
| 536 |
"""Convert absolute support (clade-count) to rel. frequencies. |
| 537 |
|
| 538 |
Some software (e.g. PHYLIP consense) just calculate how often clades appear, instead of |
| 539 |
calculating relative frequencies.""" |
| 540 |
|
| 541 |
for n in self._walk(): |
| 542 |
if self.node(n).data.support: |
| 543 |
self.node(n).data.support /= float(nrep) |
| 544 |
|
| 545 |
def has_support(self, node=None): |
| 546 |
"""Returns True if any of the nodes has data.support is not None.""" |
| 547 |
for n in self._walk(node): |
| 548 |
if self.node(n).data.support: |
| 549 |
return True |
| 550 |
else: |
| 551 |
return False |
| 552 |
|
| 553 |
def randomize( |
| 554 |
self, |
| 555 |
ntax=None, |
| 556 |
taxon_list=None, |
| 557 |
branchlength=1.0, |
| 558 |
branchlength_sd=None, |
| 559 |
bifurcate=True, |
| 560 |
): |
| 561 |
"""Generates a random tree with ntax taxa and/or taxa from taxlabels. |
| 562 |
|
| 563 |
new_tree = randomize(self,ntax=None,taxon_list=None,branchlength=1.0,branchlength_sd=None,bifurcate=True) |
| 564 |
Trees are bifurcating by default. (Polytomies not yet supported). |
| 565 |
""" |
| 566 |
|
| 567 |
if not ntax and taxon_list: |
| 568 |
ntax = len(taxon_list) |
| 569 |
elif not taxon_list and ntax: |
| 570 |
taxon_list = ["taxon" + str(i + 1) for i in range(ntax)] |
| 571 |
elif not ntax and not taxon_list: |
| 572 |
raise TreeError("Either numer of taxa or list of taxa must be specified.") |
| 573 |
elif ntax != len(taxon_list): |
| 574 |
raise TreeError("Length of taxon list must correspond to ntax.") |
| 575 |
# initiate self with empty root |
| 576 |
self.__init__() |
| 577 |
terminals = self.get_terminals() |
| 578 |
# bifurcate randomly at terminal nodes until ntax is reached |
| 579 |
while len(terminals) < ntax: |
| 580 |
newsplit = random.choice(terminals) |
| 581 |
new_terminals = self.split(parent_id=newsplit, branchlength=branchlength) |
| 582 |
# if desired, give some variation to the branch length |
| 583 |
if branchlength_sd: |
| 584 |
for nt in new_terminals: |
| 585 |
bl = random.gauss(branchlength, branchlength_sd) |
| 586 |
if bl < 0: |
| 587 |
bl = 0 |
| 588 |
self.node(nt).data.branchlength = bl |
| 589 |
terminals.extend(new_terminals) |
| 590 |
terminals.remove(newsplit) |
| 591 |
# distribute taxon labels randomly |
| 592 |
random.shuffle(taxon_list) |
| 593 |
for node, name in zip(terminals, taxon_list): |
| 594 |
self.node(node).data.taxon = name |
| 595 |
|
| 596 |
def display(self): |
| 597 |
"""Quick and dirty lists of all nodes.""" |
| 598 |
table = [ |
| 599 |
("#", "taxon", "prev", "succ", "brlen", "blen (sum)", "support", "comment") |
| 600 |
] |
| 601 |
# Sort this to be consistent across CPython, Jython, etc |
| 602 |
for i in sorted(self.all_ids()): |
| 603 |
n = self.node(i) |
| 604 |
if not n.data: |
| 605 |
table.append( |
| 606 |
(str(i), "-", str(n.prev), str(n.succ), "-", "-", "-", "-") |
| 607 |
) |
| 608 |
else: |
| 609 |
tx = n.data.taxon |
| 610 |
if not tx: |
| 611 |
tx = "-" |
| 612 |
blength = "%0.2f" % n.data.branchlength |
| 613 |
if blength is None: |
| 614 |
blength = "-" |
| 615 |
sum_blength = "-" |
| 616 |
else: |
| 617 |
sum_blength = "%0.2f" % self.sum_branchlength(node=i) |
| 618 |
support = n.data.support |
| 619 |
if support is None: |
| 620 |
support = "-" |
| 621 |
else: |
| 622 |
support = "%0.2f" % support |
| 623 |
comment = n.data.comment |
| 624 |
if comment is None: |
| 625 |
comment = "-" |
| 626 |
table.append( |
| 627 |
( |
| 628 |
str(i), |
| 629 |
tx, |
| 630 |
str(n.prev), |
| 631 |
str(n.succ), |
| 632 |
blength, |
| 633 |
sum_blength, |
| 634 |
support, |
| 635 |
comment, |
| 636 |
) |
| 637 |
) |
| 638 |
print("\n".join("%3s %32s %15s %15s %8s %10s %8s %20s" % l for l in table)) |
| 639 |
print("\nRoot: %s" % self.root) |
| 640 |
|
| 641 |
def to_string( |
| 642 |
self, |
| 643 |
support_as_branchlengths=False, |
| 644 |
branchlengths_only=False, |
| 645 |
plain=True, |
| 646 |
plain_newick=False, |
| 647 |
ladderize=None, |
| 648 |
ignore_comments=True, |
| 649 |
): |
| 650 |
"""Return a paup compatible tree line.""" |
| 651 |
# if there's a conflict in the arguments, we override plain=True |
| 652 |
if support_as_branchlengths or branchlengths_only: |
| 653 |
plain = False |
| 654 |
self.support_as_branchlengths = support_as_branchlengths |
| 655 |
self.branchlengths_only = branchlengths_only |
| 656 |
self.ignore_comments = ignore_comments |
| 657 |
self.plain = plain |
| 658 |
|
| 659 |
def make_info_string(data, terminal=False): |
| 660 |
"""Creates nicely formatted support/branchlengths.""" |
| 661 |
# CHECK FORMATTING |
| 662 |
if self.plain: # plain tree only. That's easy. |
| 663 |
info_string = "" |
| 664 |
elif ( |
| 665 |
self.support_as_branchlengths |
| 666 |
): # support as branchlengths (eg. PAUP), ignore actual branchlengths |
| 667 |
if terminal: # terminal branches have 100% support |
| 668 |
info_string = ":%1.2f" % self.max_support |
| 669 |
elif data.support: |
| 670 |
info_string = ":%1.2f" % (data.support) |
| 671 |
else: |
| 672 |
info_string = ":0.00" |
| 673 |
elif self.branchlengths_only: # write only branchlengths, ignore support |
| 674 |
info_string = ":%1.5f" % (data.branchlength) |
| 675 |
else: # write suport and branchlengths (e.g. .con tree of mrbayes) |
| 676 |
if terminal: |
| 677 |
info_string = ":%1.5f" % (data.branchlength) |
| 678 |
else: |
| 679 |
if ( |
| 680 |
data.branchlength is not None and data.support is not None |
| 681 |
): # we have blen and suppport |
| 682 |
info_string = "%1.2f:%1.5f" % (data.support, data.branchlength) |
| 683 |
elif data.branchlength is not None: # we have only blen |
| 684 |
info_string = "0.00000:%1.5f" % (data.branchlength) |
| 685 |
elif data.support is not None: # we have only support |
| 686 |
info_string = "%1.2f:0.00000" % (data.support) |
| 687 |
else: |
| 688 |
info_string = "0.00:0.00000" |
| 689 |
if not ignore_comments and hasattr(data, "nodecomment"): |
| 690 |
info_string = str(data.nodecomment) + info_string |
| 691 |
return info_string |
| 692 |
|
| 693 |
def ladderize_nodes(nodes, ladderize=None): |
| 694 |
"""Sorts node numbers according to the number of terminal nodes.""" |
| 695 |
if ladderize in ["left", "LEFT", "right", "RIGHT"]: |
| 696 |
succnode_terminals = sorted( |
| 697 |
(self.count_terminals(node=n), n) for n in nodes |
| 698 |
) |
| 699 |
if ladderize == "right" or ladderize == "RIGHT": |
| 700 |
succnode_terminals.reverse() |
| 701 |
if succnode_terminals: |
| 702 |
succnodes = zip(*succnode_terminals)[1] |
| 703 |
else: |
| 704 |
succnodes = [] |
| 705 |
else: |
| 706 |
succnodes = nodes |
| 707 |
return succnodes |
| 708 |
|
| 709 |
def newickize(node, ladderize=None): |
| 710 |
"""Convert a node tree to a newick tree recursively.""" |
| 711 |
|
| 712 |
if not self.node(node).succ: # terminal |
| 713 |
return self.node(node).data.taxon + make_info_string( |
| 714 |
self.node(node).data, terminal=True |
| 715 |
) |
| 716 |
else: |
| 717 |
succnodes = ladderize_nodes(self.node(node).succ, ladderize=ladderize) |
| 718 |
subtrees = [newickize(sn, ladderize=ladderize) for sn in succnodes] |
| 719 |
return "(%s)%s" % ( |
| 720 |
",".join(subtrees), |
| 721 |
make_info_string(self.node(node).data), |
| 722 |
) |
| 723 |
|
| 724 |
treeline = ["tree"] |
| 725 |
if self.name: |
| 726 |
treeline.append(self.name) |
| 727 |
else: |
| 728 |
treeline.append("a_tree") |
| 729 |
treeline.append("=") |
| 730 |
if self.weight != 1: |
| 731 |
treeline.append("[&W%s]" % str(round(float(self.weight), 3))) |
| 732 |
if self.rooted: |
| 733 |
treeline.append("[&R]") |
| 734 |
succnodes = ladderize_nodes(self.node(self.root).succ) |
| 735 |
subtrees = [newickize(sn, ladderize=ladderize) for sn in succnodes] |
| 736 |
treeline.append("(%s)" % ",".join(subtrees)) |
| 737 |
if plain_newick: |
| 738 |
return treeline[-1] |
| 739 |
else: |
| 740 |
return " ".join(treeline) + ";" |
| 741 |
|
| 742 |
def __str__(self): |
| 743 |
"""Short version of to_string(), gives plain tree""" |
| 744 |
return self.to_string(plain=True) |
| 745 |
|
| 746 |
def unroot(self): |
| 747 |
"""Defines a unrooted Tree structure, using data of a rooted Tree.""" |
| 748 |
|
| 749 |
# travel down the rooted tree structure and save all branches and the nodes they connect |
| 750 |
|
| 751 |
def _get_branches(node): |
| 752 |
branches = [] |
| 753 |
for b in self.node(node).succ: |
| 754 |
branches.append( |
| 755 |
[node, b, self.node(b).data.branchlength, self.node(b).data.support] |
| 756 |
) |
| 757 |
branches.extend(_get_branches(b)) |
| 758 |
return branches |
| 759 |
|
| 760 |
self.unrooted = _get_branches(self.root) |
| 761 |
# if root is bifurcating, then it is eliminated |
| 762 |
if len(self.node(self.root).succ) == 2: |
| 763 |
# find the two branches that connect to root |
| 764 |
rootbranches = [b for b in self.unrooted if self.root in b[:2]] |
| 765 |
b1 = self.unrooted.pop(self.unrooted.index(rootbranches[0])) |
| 766 |
b2 = self.unrooted.pop(self.unrooted.index(rootbranches[1])) |
| 767 |
# Connect them two each other. If both have support, it should be identical (or one set to None?). |
| 768 |
# If both have branchlengths, they will be added |
| 769 |
newbranch = [b1[1], b2[1], b1[2] + b2[2]] |
| 770 |
if b1[3] is None: |
| 771 |
newbranch.append( |
| 772 |
b2[3] |
| 773 |
) # either None (both rootbranches are unsupported) or some support |
| 774 |
elif b2[3] is None: |
| 775 |
newbranch.append(b1[3]) # dito |
| 776 |
elif b1[3] == b2[3]: |
| 777 |
newbranch.append(b1[3]) # identical support |
| 778 |
elif b1[3] == 0 or b2[3] == 0: |
| 779 |
newbranch.append(b1[3] + b2[3]) # one is 0, take the other |
| 780 |
else: |
| 781 |
raise TreeError( |
| 782 |
"Support mismatch in bifurcating root: %f, %f" |
| 783 |
% (float(b1[3]), float(b2[3])) |
| 784 |
) |
| 785 |
self.unrooted.append(newbranch) |
| 786 |
|
| 787 |
def root_with_outgroup(self, outgroup=None): |
| 788 |
def _connect_subtree(parent, child): |
| 789 |
"""Hook subtree starting with node child to parent.""" |
| 790 |
for i, branch in enumerate(self.unrooted): |
| 791 |
if parent in branch[:2] and child in branch[:2]: |
| 792 |
branch = self.unrooted.pop(i) |
| 793 |
break |
| 794 |
else: |
| 795 |
raise TreeError( |
| 796 |
"Unable to connect nodes for rooting: nodes %d and %d are not connected" |
| 797 |
% (parent, child) |
| 798 |
) |
| 799 |
self.link(parent, child) |
| 800 |
self.node(child).data.branchlength = branch[2] |
| 801 |
self.node(child).data.support = branch[3] |
| 802 |
# now check if there are more branches connected to the child, and if so, connect them |
| 803 |
child_branches = [b for b in self.unrooted if child in b[:2]] |
| 804 |
for b in child_branches: |
| 805 |
if child == b[0]: |
| 806 |
succ = b[1] |
| 807 |
else: |
| 808 |
succ = b[0] |
| 809 |
_connect_subtree(child, succ) |
| 810 |
|
| 811 |
# check the outgroup we're supposed to root with |
| 812 |
if outgroup is None: |
| 813 |
return self.root |
| 814 |
outgroup_node = self.is_monophyletic(outgroup) |
| 815 |
if outgroup_node == -1: |
| 816 |
return -1 |
| 817 |
# if tree is already rooted with outgroup on a bifurcating root, |
| 818 |
# or the outgroup includes all taxa on the tree, then we're fine |
| 819 |
if ( |
| 820 |
len(self.node(self.root).succ) == 2 |
| 821 |
and outgroup_node in self.node(self.root).succ |
| 822 |
) or outgroup_node == self.root: |
| 823 |
return self.root |
| 824 |
|
| 825 |
self.unroot() |
| 826 |
# now we find the branch that connects outgroup and ingroup |
| 827 |
# print(self.node(outgroup_node).prev) |
| 828 |
for i, b in enumerate(self.unrooted): |
| 829 |
if outgroup_node in b[:2] and self.node(outgroup_node).prev in b[:2]: |
| 830 |
root_branch = self.unrooted.pop(i) |
| 831 |
break |
| 832 |
else: |
| 833 |
raise TreeError("Unrooted and rooted Tree do not match") |
| 834 |
if outgroup_node == root_branch[1]: |
| 835 |
ingroup_node = root_branch[0] |
| 836 |
else: |
| 837 |
ingroup_node = root_branch[1] |
| 838 |
# now we destroy the old tree structure, but keep node data. Nodes will be reconnected according to new outgroup |
| 839 |
for n in self.all_ids(): |
| 840 |
self.node(n).prev = None |
| 841 |
self.node(n).succ = [] |
| 842 |
# now we just add both subtrees (outgroup and ingroup) branch for branch |
| 843 |
root = Nodes.Node(data=NodeData()) # new root |
| 844 |
self.add(root) # add to tree description |
| 845 |
self.root = root.id # set as root |
| 846 |
self.unrooted.append( |
| 847 |
[root.id, ingroup_node, root_branch[2], root_branch[3]] |
| 848 |
) # add branch to ingroup to unrooted tree |
| 849 |
self.unrooted.append( |
| 850 |
[root.id, outgroup_node, 0.0, 0.0] |
| 851 |
) # add branch to outgroup to unrooted tree |
| 852 |
_connect_subtree(root.id, ingroup_node) # add ingroup |
| 853 |
_connect_subtree(root.id, outgroup_node) # add outgroup |
| 854 |
# if theres still a lonely node in self.chain, then it's the old root, and we delete it |
| 855 |
oldroot = [ |
| 856 |
i for i in self.all_ids() if self.node(i).prev is None and i != self.root |
| 857 |
] |
| 858 |
if len(oldroot) > 1: |
| 859 |
raise TreeError( |
| 860 |
"Isolated nodes in tree description: %s" % ",".join(oldroot) |
| 861 |
) |
| 862 |
elif len(oldroot) == 1: |
| 863 |
self.kill(oldroot[0]) |
| 864 |
return self.root |
| 865 |
|
| 866 |
def merge_with_support( |
| 867 |
self, bstrees=None, constree=None, threshold=0.5, outgroup=None |
| 868 |
): |
| 869 |
"""Merges clade support (from consensus or list of bootstrap-trees) with phylogeny. |
| 870 |
|
| 871 |
tree=merge_bootstrap(phylo,bs_tree=<list_of_trees>) |
| 872 |
or |
| 873 |
tree=merge_bootstrap(phylo,consree=consensus_tree with clade support) |
| 874 |
""" |
| 875 |
|
| 876 |
if bstrees and constree: |
| 877 |
raise TreeError( |
| 878 |
"Specify either list of bootstrap trees or consensus tree, not both" |
| 879 |
) |
| 880 |
if not (bstrees or constree): |
| 881 |
raise TreeError("Specify either list of bootstrap trees or consensus tree.") |
| 882 |
# no outgroup specified: use the smallest clade of the root |
| 883 |
if outgroup is None: |
| 884 |
try: |
| 885 |
succnodes = self.node(self.root).succ |
| 886 |
smallest = min((len(self.get_taxa(n)), n) for n in succnodes) |
| 887 |
outgroup = self.get_taxa(smallest[1]) |
| 888 |
except: |
| 889 |
raise TreeError("Error determining outgroup.") |
| 890 |
else: # root with user specified outgroup |
| 891 |
self.root_with_outgroup(outgroup) |
| 892 |
|
| 893 |
if bstrees: # calculate consensus |
| 894 |
constree = consensus(bstrees, threshold=threshold, outgroup=outgroup) |
| 895 |
else: |
| 896 |
if not constree.has_support(): |
| 897 |
constree.branchlength2support() |
| 898 |
constree.root_with_outgroup(outgroup) |
| 899 |
# now we travel all nodes, and add support from consensus, if the clade is present in both |
| 900 |
for pnode in self._walk(): |
| 901 |
cnode = constree.is_monophyletic(self.get_taxa(pnode)) |
| 902 |
if cnode > -1: |
| 903 |
self.node(pnode).data.support = constree.node(cnode).data.support |
| 904 |
|
| 905 |
|
| 906 |
def consensus(trees, threshold=0.5, outgroup=None): |
| 907 |
"""Compute a majority rule consensus tree of all clades with relative frequency>=threshold from a list of trees.""" |
| 908 |
|
| 909 |
total = len(trees) |
| 910 |
if total == 0: |
| 911 |
return None |
| 912 |
# shouldn't we make sure that it's NodeData or subclass?? |
| 913 |
dataclass = trees[0].dataclass |
| 914 |
max_support = trees[0].max_support |
| 915 |
clades = {} |
| 916 |
# countclades={} |
| 917 |
alltaxa = set(trees[0].get_taxa()) |
| 918 |
# calculate calde frequencies |
| 919 |
c = 0 |
| 920 |
for t in trees: |
| 921 |
c += 1 |
| 922 |
# if c % 100 == 0: |
| 923 |
# print(c) |
| 924 |
if alltaxa != set(t.get_taxa()): |
| 925 |
raise TreeError("Trees for consensus must contain the same taxa") |
| 926 |
t.root_with_outgroup(outgroup=outgroup) |
| 927 |
for st_node in t._walk(t.root): |
| 928 |
subclade_taxa = sorted(t.get_taxa(st_node)) |
| 929 |
subclade_taxa = str(subclade_taxa) # lists are not hashable |
| 930 |
if subclade_taxa in clades: |
| 931 |
clades[subclade_taxa] += float(t.weight) / total |
| 932 |
else: |
| 933 |
clades[subclade_taxa] = float(t.weight) / total |
| 934 |
# if subclade_taxa in countclades: |
| 935 |
# countclades[subclade_taxa]+ = t.weight |
| 936 |
# else: |
| 937 |
# countclades[subclade_taxa] = t.weight |
| 938 |
# weed out clades below threshold |
| 939 |
delclades = [ |
| 940 |
c for c, p in clades.items() if round(p, 3) < threshold |
| 941 |
] # round can be necessary |
| 942 |
for c in delclades: |
| 943 |
del clades[c] |
| 944 |
# create a tree with a root node |
| 945 |
consensus = Tree(name="consensus_%2.1f" % float(threshold), data=dataclass) |
| 946 |
# each clade needs a node in the new tree, add them as isolated nodes |
| 947 |
for c, s in clades.items(): |
| 948 |
node = Nodes.Node(data=dataclass()) |
| 949 |
node.data.support = s |
| 950 |
node.data.taxon = set(eval(c)) |
| 951 |
consensus.add(node) |
| 952 |
# set root node data |
| 953 |
consensus.node(consensus.root).data.support = None |
| 954 |
consensus.node(consensus.root).data.taxon = alltaxa |
| 955 |
# we sort the nodes by no. of taxa in the clade, so root will be the last |
| 956 |
consensus_ids = consensus.all_ids() |
| 957 |
consensus_ids.sort( |
| 958 |
lambda x, y: len(consensus.node(x).data.taxon) |
| 959 |
- len(consensus.node(y).data.taxon) |
| 960 |
) |
| 961 |
# now we just have to hook each node to the next smallest node that includes all taxa of the current |
| 962 |
for i, current in enumerate( |
| 963 |
consensus_ids[:-1] |
| 964 |
): # skip the last one which is the root |
| 965 |
# print('----') |
| 966 |
# print('current: %s' % consensus.node(current).data.taxon) |
| 967 |
# search remaining nodes |
| 968 |
for parent in consensus_ids[i + 1 :]: |
| 969 |
# print('parent: %s' % consensus.node(parent).data.taxon) |
| 970 |
if consensus.node(parent).data.taxon.issuperset( |
| 971 |
consensus.node(current).data.taxon |
| 972 |
): |
| 973 |
break |
| 974 |
else: |
| 975 |
raise TreeError("corrupt tree structure?") |
| 976 |
# internal nodes don't have taxa |
| 977 |
if len(consensus.node(current).data.taxon) == 1: |
| 978 |
consensus.node(current).data.taxon = consensus.node( |
| 979 |
current |
| 980 |
).data.taxon.pop() |
| 981 |
# reset the support for terminal nodes to maximum |
| 982 |
# consensus.node(current).data.support=max_support |
| 983 |
else: |
| 984 |
consensus.node(current).data.taxon = None |
| 985 |
consensus.link(parent, current) |
| 986 |
# eliminate root taxon name |
| 987 |
consensus.node(consensus_ids[-1]).data.taxon = None |
| 988 |
if alltaxa != set(consensus.get_taxa()): |
| 989 |
raise TreeError("FATAL ERROR: consensus tree is corrupt") |
| 990 |
return consensus |