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
|
#! /usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this work or any portion thereof in published work,
## please cite it as:
##
## Sukumaran, J. and M. T. Holder. 2010. DendroPy: a Python library
## for phylogenetic computing. Bioinformatics 26: 1569-1571.
##
##############################################################################
"""
Classes and Methods for working with tree reconciliation, fitting, embedding,
contained/containing etc.
"""
import dendropy
from dendropy.model import coalescent
class ContainingTree(dendropy.Tree):
"""
A "containing tree" is a (usually rooted) tree data structure within which
other trees are "contained". For example, species trees and their contained
gene trees; host trees and their contained parasite trees; biogeographical
"area" trees and their contained species or taxon trees.
"""
def __init__(self,
containing_tree,
contained_taxon_namespace,
contained_to_containing_taxon_map,
contained_trees=None,
fit_containing_edge_lengths=True,
collapse_empty_edges=True,
ultrametricity_precision=False,
ignore_root_deep_coalescences=True,
**kwargs):
"""
__init__ converts ``self`` to ContainingTree class, embedding the trees
given in the list, ``contained_trees.``
Mandatory Arguments:
``containing_tree``
A |Tree| or |Tree|-like object that describes the topological
constraints or conditions of the containing tree (e.g., species,
host, or biogeographical area trees).
``contained_taxon_namespace``
A |TaxonNamespace| object that will be used to manage the taxa of
the contained trees.
``contained_to_containing_taxon_map``
A |TaxonNamespaceMapping| object mapping |Taxon| objects in the
contained |TaxonNamespace| to corresponding |Taxon| objects in the
containing tree.
Optional Arguments:
``contained_trees``
An iterable container of |Tree| or |Tree|-like objects that
will be contained into ``containing_tree``; e.g. gene or
parasite trees.
``fit_containing_edge_lengths``
If |True| [default], then the branch lengths of
``containing_tree`` will be adjusted to fit the contained tree
as they are added. Otherwise, the containing tree edge lengths
will not be changed.
``collapse_empty_edges``
If |True| [default], after edge lengths are adjusted,
zero-length branches will be collapsed.
``ultrametricity_precision``
If |False| [default], then trees will not be checked for
ultrametricity. Otherwise this is the threshold within which
all node to tip distances for sister nodes must be equal.
``ignore_root_deep_coalescences``
If |True| [default], then deep coalescences in the root will
not be counted.
Other Keyword Arguments: Will be passed to Tree().
"""
if "taxon_namespace" not in kwargs:
kwargs["taxon_namespace"] = containing_tree.taxon_namespace
dendropy.Tree.__init__(self,
containing_tree,
taxon_namespace=containing_tree.taxon_namespace)
self.original_tree = containing_tree
for edge in self.postorder_edge_iter():
edge.head_contained_edges = {}
edge.tail_contained_edges = {}
edge.containing_taxa = set()
edge.contained_taxa = set()
self._contained_taxon_namespace = contained_taxon_namespace
self._contained_to_containing_taxon_map = None
self._contained_trees = None
self._set_contained_to_containing_taxon_map(contained_to_containing_taxon_map)
self.fit_containing_edge_lengths = fit_containing_edge_lengths
self.collapse_empty_edges = collapse_empty_edges
self.ultrametricity_precision = ultrametricity_precision
self.ignore_root_deep_coalescences = ignore_root_deep_coalescences
if contained_trees:
self._set_contained_trees(contained_trees)
if self.contained_trees:
self.rebuild(rebuild_taxa=False)
def _set_contained_taxon_namespace(self, taxon_namespace):
self._contained_taxon_namespace = taxon_namespace
def _get_contained_taxon_namespace(self):
if self._contained_taxon_namespace is None:
self._contained_taxon_namespace = dendropy.TaxonNamespace()
return self._contained_taxon_namespace
contained_taxon_namespace = property(_get_contained_taxon_namespace)
def _set_contained_to_containing_taxon_map(self, contained_to_containing_taxon_map):
"""
Sets mapping of |Taxon| objects of the genes/parasite/etc. to that of
the population/species/host/etc.
Creates mapping (e.g., species to genes) and decorates edges of self
with sets of both containing |Taxon| objects and the contained
|Taxon| objects that map to them.
"""
if isinstance(contained_to_containing_taxon_map, dendropy.TaxonNamespaceMapping):
if self._contained_taxon_namespace is not contained_to_containing_taxon_map.domain_taxon_namespace:
raise ValueError("Domain TaxonNamespace of TaxonNamespaceMapping ('domain_taxon_namespace') not the same as 'contained_taxon_namespace' TaxonNamespace")
self._contained_to_containing_taxon_map = contained_to_containing_taxon_map
else:
self._contained_to_containing_taxon_map = dendropy.TaxonNamespaceMapping(
mapping_dict=contained_to_containing_taxon_map,
domain_taxon_namespace=self.contained_taxon_namespace,
range_taxon_namespace=self.taxon_namespace)
self.build_edge_taxa_sets()
def _get_contained_to_containing_taxon_map(self):
return self._contained_to_containing_taxon_map
contained_to_containing_taxon_map = property(_get_contained_to_containing_taxon_map)
def _set_contained_trees(self, trees):
if hasattr(trees, 'taxon_namespace'):
if self._contained_taxon_namespace is None:
self._contained_taxon_namespace = trees.taxon_namespace
elif self._contained_taxon_namespace is not trees.taxon_namespace:
raise ValueError("'contained_taxon_namespace' of ContainingTree is not the same TaxonNamespace object of 'contained_trees'")
self._contained_trees = dendropy.TreeList(trees, taxon_namespace=self._contained_taxon_namespace)
if self._contained_taxon_namespace is None:
self._contained_taxon_namespace = self._contained_trees.taxon_namespace
def _get_contained_trees(self):
if self._contained_trees is None:
self._contained_trees = dendropy.TreeList(taxon_namespace=self._contained_taxon_namespace)
return self._contained_trees
contained_trees = property(_get_contained_trees)
def _get_containing_to_contained_taxa_map(self):
return self._contained_to_containing_taxon_map.reverse
containing_to_contained_taxa_map = property(_get_containing_to_contained_taxa_map)
def clear(self):
"""
Clears all contained trees and mapped edges.
"""
self.contained_trees = dendropy.TreeList(taxon_namespace=self._contained_to_containing_taxon_map.domain_taxa)
self.clear_contained_edges()
def clear_contained_edges(self):
"""
Clears all contained mapped edges.
"""
for edge in self.postorder_edge_iter():
edge.head_contained_edges = {}
edge.tail_contained_edges = {}
def fit_edge_lengths(self, contained_trees):
"""
Recalculate node ages / edge lengths of containing tree to accomodate
contained trees.
"""
# set the ages
for node in self.postorder_node_iter():
if node.is_internal():
disjunct_leaf_set_list_split_bitmasks = []
for i in node.child_nodes():
disjunct_leaf_set_list_split_bitmasks.append(self.taxon_namespace.taxa_bitmask(taxa=i.edge.containing_taxa))
min_age = float('inf')
for et in contained_trees:
min_age = self._find_youngest_intergroup_age(et, disjunct_leaf_set_list_split_bitmasks, min_age)
node.age = max( [min_age] + [cn.age for cn in node.child_nodes()] )
else:
node.age = 0
# set the corresponding edge lengths
self.set_edge_lengths_from_node_ages()
# collapse 0-length branches
if self.collapse_empty_edges:
self.collapse_unweighted_edges()
def rebuild(self, rebuild_taxa=True):
"""
Recalculate edge taxa sets, node ages / edge lengths of containing
tree, and embed edges of contained trees.
"""
if rebuild_taxa:
self.build_edge_taxa_sets()
if self.fit_containing_edge_lengths:
self.fit_edge_lengths(self.contained_trees)
self.clear_contained_edges()
for et in self.contained_trees:
self.embed_tree(et)
def embed_tree(self, contained_tree):
"""
Map edges of contained tree into containing tree (i.e., self).
"""
if self.seed_node.age is None:
self.calc_node_ages(ultrametricity_precision=self.ultrametricity_precision)
if contained_tree not in self.contained_trees:
self.contained_trees.append(contained_tree)
if self.fit_containing_edge_lengths:
self.fit_edge_lengths(self.contained_trees)
if contained_tree.seed_node.age is None:
contained_tree.calc_node_ages(ultrametricity_precision=self.ultrametricity_precision)
contained_leaves = contained_tree.leaf_nodes()
taxon_to_contained = {}
for nd in contained_leaves:
containing_taxon = self.contained_to_containing_taxon_map[nd.taxon]
x = taxon_to_contained.setdefault(containing_taxon, set())
x.add(nd.edge)
for containing_edge in self.postorder_edge_iter():
if containing_edge.is_terminal():
containing_edge.head_contained_edges[contained_tree] = taxon_to_contained[containing_edge.head_node.taxon]
else:
containing_edge.head_contained_edges[contained_tree] = set()
for nd in containing_edge.head_node.child_nodes():
containing_edge.head_contained_edges[contained_tree].update(nd.edge.tail_contained_edges[contained_tree])
if containing_edge.tail_node is None:
if containing_edge.length is not None:
target_age = containing_edge.head_node.age + containing_edge.length
else:
# assume all coalesce?
containing_edge.tail_contained_edges[contained_tree] = set([contained_tree.seed_node.edge])
continue
else:
target_age = containing_edge.tail_node.age
containing_edge.tail_contained_edges[contained_tree] = set()
for contained_edge in containing_edge.head_contained_edges[contained_tree]:
if contained_edge.tail_node is not None:
remaining = target_age - contained_edge.tail_node.age
elif contained_edge.length is not None:
remaining = target_age - (contained_edge.head_node.age + contained_edge.length)
else:
continue
while remaining > 0:
if contained_edge.tail_node is not None:
contained_edge = contained_edge.tail_node.edge
else:
if contained_edge.length is not None and (remaining - contained_edge.length) <= 0:
contained_edge = None
remaining = 0
break
else:
remaining = 0
break
if contained_edge and remaining > 0:
remaining -= contained_edge.length
if contained_edge is not None:
containing_edge.tail_contained_edges[contained_tree].add(contained_edge)
def build_edge_taxa_sets(self):
"""
Rebuilds sets of containing and corresponding contained taxa at each
edge.
"""
for edge in self.postorder_edge_iter():
if edge.is_terminal():
edge.containing_taxa = set([edge.head_node.taxon])
else:
edge.containing_taxa = set()
for i in edge.head_node.child_nodes():
edge.containing_taxa.update(i.edge.containing_taxa)
edge.contained_taxa = set()
for t in edge.containing_taxa:
edge.contained_taxa.update(self.containing_to_contained_taxa_map[t])
def num_deep_coalescences(self):
"""
Returns total number of deep coalescences of the contained trees.
"""
return sum(self.deep_coalescences().values())
def deep_coalescences(self):
"""
Returns dictionary where the contained trees are keys, and the number of
deep coalescences corresponding to the tree are values.
"""
dc = {}
for tree in self.contained_trees:
for edge in self.postorder_edge_iter():
if edge.tail_node is None and self.ignore_root_deep_coalescences:
continue
try:
dc[tree] += len(edge.tail_contained_edges[tree]) - 1
except KeyError:
dc[tree] = len(edge.tail_contained_edges[tree]) - 1
return dc
def embed_contained_kingman(self,
edge_pop_size_attr='pop_size',
default_pop_size=1,
label=None,
rng=None,
use_expected_tmrca=False):
"""
Simulates, *embeds*, and returns a "censored" (Kingman) neutral coalescence tree
conditional on self.
``rng``
Random number generator to use. If |None|, the default will
be used.
``edge_pop_size_attr``
Name of attribute of self's edges that specify the population
size. If this attribute does not exist, then the population
size is taken to be 1.
Note that all edge-associated taxon sets must be up-to-date (otherwise,
``build_edge_taxa_sets()`` should be called).
"""
et = self.simulate_contained_kingman(
edge_pop_size_attr=edge_pop_size_attr,
default_pop_size=default_pop_size,
label=label,
rng=rng,
use_expected_tmrca=use_expected_tmrca)
self.embed_tree(et)
return et
def simulate_contained_kingman(self,
edge_pop_size_attr='pop_size',
default_pop_size=1,
label=None,
rng=None,
use_expected_tmrca=False):
"""
Simulates and returns a "censored" (Kingman) neutral coalescence tree
conditional on self.
``rng``
Random number generator to use. If |None|, the default will
be used.
``edge_pop_size_attr``
Name of attribute of self's edges that specify the population
size. If this attribute does not exist, then the population
size is taken to be 1.
Note that all edge-associated taxon sets must be up-to-date (otherwise,
``build_edge_taxa_sets()`` should be called), and that the tree
is *not* added to the set of contained trees. For the latter, call
``embed_contained_kingman``.
"""
# Dictionary that maps nodes of containing tree to list of
# corresponding nodes on gene tree, initially populated with leaf
# nodes.
contained_nodes = {}
for nd in self.leaf_node_iter():
contained_nodes[nd] = []
for gt in nd.edge.contained_taxa:
gn = dendropy.Node(taxon=gt)
contained_nodes[nd].append(gn)
# Generate the tree structure
for edge in self.postorder_edge_iter():
if edge.head_node.parent_node is None:
# root: run unconstrained coalescence until just one gene node
# remaining
if hasattr(edge, edge_pop_size_attr):
pop_size = getattr(edge, edge_pop_size_attr)
else:
pop_size = default_pop_size
if len(contained_nodes[edge.head_node]) > 1:
final = coalescent.coalesce_nodes(nodes=contained_nodes[edge.head_node],
pop_size=pop_size,
period=None,
rng=rng,
use_expected_tmrca=use_expected_tmrca)
else:
final = contained_nodes[edge.head_node]
else:
# run until next coalescence event, as determined by this edge
# size.
if hasattr(edge, edge_pop_size_attr):
pop_size = getattr(edge, edge_pop_size_attr)
else:
pop_size = default_pop_size
remaining = coalescent.coalesce_nodes(nodes=contained_nodes[edge.head_node],
pop_size=pop_size,
period=edge.length,
rng=rng,
use_expected_tmrca=use_expected_tmrca)
try:
contained_nodes[edge.tail_node].extend(remaining)
except KeyError:
contained_nodes[edge.tail_node] = remaining
# Create and return the full tree
contained_tree = dendropy.Tree(taxon_namespace=self.contained_taxon_namespace, label=label)
contained_tree.seed_node = final[0]
contained_tree.is_rooted = True
return contained_tree
def _find_youngest_intergroup_age(self, contained_tree, disjunct_leaf_set_list_split_bitmasks, starting_min_age=None):
"""
Find the age of the youngest MRCA of disjunct leaf sets.
"""
if starting_min_age is None:
starting_min_age = float('inf')
if contained_tree.seed_node.age is None:
contained_tree.calc_node_ages(ultrametricity_precision=self.ultrametricity_precision)
for nd in contained_tree.ageorder_node_iter(include_leaves=False):
if nd.age > starting_min_age:
break
prev_intersections = False
for bm in disjunct_leaf_set_list_split_bitmasks:
if bm & nd.edge.split_bitmask:
if prev_intersections:
return nd.age
prev_intersections = True
return starting_min_age
def write_as_mesquite(self, out, **kwargs):
"""
For debugging purposes, write out a Mesquite-format file.
"""
from dendropy.dataio import nexuswriter
nw = nexuswriter.NexusWriter(**kwargs)
nw.is_write_block_titles = True
out.write("#NEXUS\n\n")
nw._write_taxa_block(out, self.taxon_namespace)
out.write('\n')
nw._write_taxa_block(out, self.contained_trees.taxon_namespace)
if self.contained_trees.taxon_namespace.label:
domain_title = self.contained_trees.taxon_namespace.label
else:
domain_title = self.contained_trees.taxon_namespace.oid
contained_taxon_namespace = self.contained_trees.taxon_namespace
contained_label = self.contained_trees.label
out.write('\n')
self._contained_to_containing_taxon_map.write_mesquite_association_block(out)
out.write('\n')
nw._write_trees_block(out, dendropy.TreeList([self], taxon_namespace=self.taxon_namespace))
out.write('\n')
nw._write_trees_block(out, dendropy.TreeList(self.contained_trees, taxon_namespace=contained_taxon_namespace, label=contained_label))
out.write('\n')
def reconciliation_discordance(gene_tree, species_tree):
"""
Given two trees (with splits encoded), this returns the number of gene
duplications implied by the gene tree reconciled on the species tree, based
on the algorithm described here:
Goodman, M. J. Czelnusiniak, G. W. Moore, A. E. Romero-Herrera, and
G. Matsuda. 1979. Fitting the gene lineage into its species lineage,
a parsimony strategy illustrated by cladograms constructed from globin
sequences. Syst. Zool. 19: 99-113.
Maddison, W. P. 1997. Gene trees in species trees. Syst. Biol. 46:
523-536.
This function requires that the gene tree and species tree *have the same
leaf set*. Note that for correct results,
(a) trees must be rooted (i.e., is_rooted = True)
(b) split masks must have been added as rooted (i.e., when
encode_splits was called, is_rooted must have been set to True)
"""
taxa_mask = species_tree.taxon_namespace.all_taxa_bitmask()
species_node_gene_nodes = {}
gene_node_species_nodes = {}
for gnd in gene_tree.postorder_node_iter():
gn_children = gnd.child_nodes()
if len(gn_children) > 0:
ssplit = 0
for gn_child in gn_children:
ssplit = ssplit | gene_node_species_nodes[gn_child].edge.leafset_bitmask
sanc = species_tree.mrca(start_node=species_tree.seed_node, leafset_bitmask=ssplit)
gene_node_species_nodes[gnd] = sanc
if sanc not in species_node_gene_nodes:
species_node_gene_nodes[sanc] = []
species_node_gene_nodes[sanc].append(gnd)
else:
gene_node_species_nodes[gnd] = species_tree.find_node(lambda x : x.taxon == gnd.taxon)
contained_gene_lineages = {}
for snd in species_tree.postorder_node_iter():
if snd in species_node_gene_nodes:
for gnd in species_node_gene_nodes[snd]:
for gnd_child in gnd.child_nodes():
sanc = gene_node_species_nodes[gnd_child]
p = sanc
while p is not None and p != snd:
if p.edge not in contained_gene_lineages:
contained_gene_lineages[p.edge] = 0
contained_gene_lineages[p.edge] += 1
p = p.parent_node
dc = 0
for v in contained_gene_lineages.values():
dc += v - 1
return dc
def monophyletic_partition_discordance(tree, taxon_namespace_partition):
"""
Returns the number of deep coalescences on tree ``tree`` that would result
if the taxa in ``tax_sets`` formed K mutually-exclusive monophyletic groups,
where K = len(tax_sets)
``taxon_namespace_partition`` == TaxonNamespacePartition
"""
tax_sets = taxon_namespace_partition.subsets()
# from dendropy.model import parsimony
# taxon_state_sets_map = {}
# assert tree.taxon_namespace is taxon_namespace_partition.taxon_namespace
# for taxon in tree.taxon_namespace:
# taxon_state_sets_map[taxon] = [0 for i in range(len(tax_sets))]
# for idx, ts in enumerate(tax_sets):
# for taxon in ts:
# taxon_state_sets_map[taxon][idx] = 1
# for taxon in tree.taxon_namespace:
# taxon_state_sets_map[taxon] = [set([i]) for i in taxon_state_sets_map[taxon]]
# return parsimony.fitch_down_pass(
# postorder_nodes=tree.postorder_node_iter(),
# taxon_state_sets_map=taxon_state_sets_map
# )
dc_tree = dendropy.Tree()
dc_tree.taxon_namespace = dendropy.TaxonNamespace()
for t in range(len(tax_sets)):
dc_tree.taxon_namespace.add_taxon(dendropy.Taxon(label=str(t)))
def _get_dc_taxon(nd):
for idx, tax_set in enumerate(tax_sets):
if nd.taxon in tax_set:
return dc_tree.taxon_namespace[idx]
assert "taxon not found in partition: '%s'" % nd.taxon.label
src_dc_map = {}
for snd in tree.postorder_node_iter():
nnd = dendropy.Node()
src_dc_map[snd] = nnd
children = snd.child_nodes()
if len(children) == 0:
nnd.taxon = _get_dc_taxon(snd)
else:
taxa_set = []
for cnd in children:
dc_node = src_dc_map[cnd]
if len(dc_node.child_nodes()) > 1:
nnd.add_child(dc_node)
else:
ctax = dc_node.taxon
if ctax is not None and ctax not in taxa_set:
taxa_set.append(ctax)
del src_dc_map[cnd]
if len(taxa_set) > 1:
for t in taxa_set:
cnd = dendropy.Node()
cnd.taxon = t
nnd.add_child(cnd)
else:
if len(nnd.child_nodes()) == 0:
nnd.taxon = taxa_set[0]
elif len(taxa_set) == 1:
cnd = dendropy.Node()
cnd.taxon = taxa_set[0]
nnd.add_child(cnd)
dc_tree.seed_node = nnd
return len(dc_tree.leaf_nodes()) - len(tax_sets)
|