response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
Retrieve a matcher function by passing an arbitrary object (PRIVATE). Passing a ``TreeElement`` such as a ``Clade`` or ``Tree`` instance returns an identity matcher, passing a type such as the ``PhyloXML.Taxonomy`` class returns a class matcher, and passing a dictionary returns an attribute matcher. The resulting 'match' function returns True when given an object matching the specification (identity, type or attribute values), otherwise False. This is useful for writing functions that search the tree, and probably shouldn't be used directly by the end user.
def _object_matcher(obj): """Retrieve a matcher function by passing an arbitrary object (PRIVATE). Passing a ``TreeElement`` such as a ``Clade`` or ``Tree`` instance returns an identity matcher, passing a type such as the ``PhyloXML.Taxonomy`` class returns a class matcher, and passing a dictionary returns an attribute matcher. The resulting 'match' function returns True when given an object matching the specification (identity, type or attribute values), otherwise False. This is useful for writing functions that search the tree, and probably shouldn't be used directly by the end user. """ if isinstance(obj, TreeElement): return _identity_matcher(obj) if isinstance(obj, type): return _class_matcher(obj) if isinstance(obj, str): return _string_matcher(obj) if isinstance(obj, dict): return _attribute_matcher(obj) if callable(obj): return _function_matcher(obj) raise ValueError(f"{obj} (type {type(obj)}) is not a valid type for comparison.")
Merge target specifications with keyword arguments (PRIVATE). Dispatch the components to the various matcher functions, then merge into a single boolean function.
def _combine_matchers(target, kwargs, require_spec): """Merge target specifications with keyword arguments (PRIVATE). Dispatch the components to the various matcher functions, then merge into a single boolean function. """ if not target: if not kwargs: if require_spec: raise ValueError( "you must specify a target object or keyword arguments." ) return lambda x: True return _attribute_matcher(kwargs) match_obj = _object_matcher(target) if not kwargs: return match_obj match_kwargs = _attribute_matcher(kwargs) return lambda x: match_obj(x) and match_kwargs(x)
Convert ``[targets]`` or ``*targets`` arguments to a single iterable (PRIVATE). This helps other functions work like the built-in functions ``max`` and ``min``.
def _combine_args(first, *rest): """Convert ``[targets]`` or ``*targets`` arguments to a single iterable (PRIVATE). This helps other functions work like the built-in functions ``max`` and ``min``. """ # Background: is_monophyletic takes a single list or iterable (like the # same method in Bio.Nexus.Trees); root_with_outgroup and common_ancestor # take separate arguments. This mismatch was in the initial release and I # didn't notice the inconsistency until after Biopython 1.55. I can think # of cases where either style is more convenient, so let's support both # (for backward compatibility and consistency between methods). if hasattr(first, "__iter__") and not ( isinstance(first, (TreeElement, dict, str, type)) ): # terminals is an iterable of targets if rest: raise ValueError( "Arguments must be either a single list of " "targets, or separately specified targets " "(e.g. foo(t1, t2, t3)), but not both." ) return first # terminals is a single target -- wrap in a container return itertools.chain([first], rest)
Resolve URI for librdf.
def qUri(x): """Resolve URI for librdf.""" return resolve_uri(x, namespaces=RDF_NAMESPACES)
Format label for librdf.
def format_label(x): """Format label for librdf.""" return x.replace("_", " ")
Iterate over the trees in a CDAO file handle. :returns: generator of Bio.Phylo.CDAO.Tree objects.
def parse(handle, **kwargs): """Iterate over the trees in a CDAO file handle. :returns: generator of Bio.Phylo.CDAO.Tree objects. """ return Parser(handle).parse(**kwargs)
Write a trees in CDAO format to the given file handle. :returns: number of trees written.
def write(trees, handle, plain=False, **kwargs): """Write a trees in CDAO format to the given file handle. :returns: number of trees written. """ return Writer(trees).write(handle, plain=plain, **kwargs)
Search strict consensus tree from multiple trees. :Parameters: trees : iterable iterable of trees to produce consensus tree.
def strict_consensus(trees): """Search strict consensus tree from multiple trees. :Parameters: trees : iterable iterable of trees to produce consensus tree. """ trees_iter = iter(trees) first_tree = next(trees_iter) terms = first_tree.get_terminals() bitstr_counts, tree_count = _count_clades(itertools.chain([first_tree], trees_iter)) # Store bitstrs for strict clades strict_bitstrs = [ bitstr for bitstr, t in bitstr_counts.items() if t[0] == tree_count ] strict_bitstrs.sort(key=lambda bitstr: bitstr.count("1"), reverse=True) # Create root root = BaseTree.Clade() if strict_bitstrs[0].count("1") == len(terms): root.clades.extend(terms) else: raise ValueError("Taxons in provided trees should be consistent") # make a bitstr to clades dict and store root clade bitstr_clades = {strict_bitstrs[0]: root} # create inner clades for bitstr in strict_bitstrs[1:]: clade_terms = [terms[i] for i in bitstr.index_one()] clade = BaseTree.Clade() clade.clades.extend(clade_terms) for bs, c in bitstr_clades.items(): # check if it should be the parent of current clade if bs.contains(bitstr): # remove old bitstring del bitstr_clades[bs] # update clade children c.clades = [child for child in c.clades if child not in clade_terms] # set current clade as child of c c.clades.append(clade) # update bitstring bs = bs ^ bitstr # update clade bitstr_clades[bs] = c break # put new clade bitstr_clades[bitstr] = clade return BaseTree.Tree(root=root)
Search majority rule consensus tree from multiple trees. This is a extend majority rule method, which means the you can set any cutoff between 0 ~ 1 instead of 0.5. The default value of cutoff is 0 to create a relaxed binary consensus tree in any condition (as long as one of the provided trees is a binary tree). The branch length of each consensus clade in the result consensus tree is the average length of all counts for that clade. :Parameters: trees : iterable iterable of trees to produce consensus tree.
def majority_consensus(trees, cutoff=0): """Search majority rule consensus tree from multiple trees. This is a extend majority rule method, which means the you can set any cutoff between 0 ~ 1 instead of 0.5. The default value of cutoff is 0 to create a relaxed binary consensus tree in any condition (as long as one of the provided trees is a binary tree). The branch length of each consensus clade in the result consensus tree is the average length of all counts for that clade. :Parameters: trees : iterable iterable of trees to produce consensus tree. """ tree_iter = iter(trees) first_tree = next(tree_iter) terms = first_tree.get_terminals() bitstr_counts, tree_count = _count_clades(itertools.chain([first_tree], tree_iter)) # Sort bitstrs by descending #occurrences, then #tips, then tip order bitstrs = sorted( bitstr_counts.keys(), key=lambda bitstr: (bitstr_counts[bitstr][0], bitstr.count("1"), str(bitstr)), reverse=True, ) root = BaseTree.Clade() if bitstrs[0].count("1") == len(terms): root.clades.extend(terms) else: raise ValueError("Taxons in provided trees should be consistent") # Make a bitstr-to-clades dict and store root clade bitstr_clades = {bitstrs[0]: root} # create inner clades for bitstr in bitstrs[1:]: # apply majority rule count_in_trees, branch_length_sum = bitstr_counts[bitstr] confidence = 100.0 * count_in_trees / tree_count if confidence < cutoff * 100.0: break clade_terms = [terms[i] for i in bitstr.index_one()] clade = BaseTree.Clade() clade.clades.extend(clade_terms) clade.confidence = confidence clade.branch_length = branch_length_sum / count_in_trees bsckeys = sorted(bitstr_clades, key=lambda bs: bs.count("1"), reverse=True) # check if current clade is compatible with previous clades and # record its possible parent and child clades. compatible = True parent_bitstr = None child_bitstrs = [] # multiple independent children for bs in bsckeys: if not bs.iscompatible(bitstr): compatible = False break # assign the closest ancestor as its parent # as bsckeys is sorted, it should be the last one if bs.contains(bitstr): parent_bitstr = bs # assign the closest descendant as its child # the largest and independent clades if ( bitstr.contains(bs) and bs != bitstr and all(c.independent(bs) for c in child_bitstrs) ): child_bitstrs.append(bs) if not compatible: continue if parent_bitstr: # insert current clade; remove old bitstring parent_clade = bitstr_clades.pop(parent_bitstr) # update parent clade children parent_clade.clades = [ c for c in parent_clade.clades if c not in clade_terms ] # set current clade as child of parent_clade parent_clade.clades.append(clade) # update bitstring # parent = parent ^ bitstr # update clade bitstr_clades[parent_bitstr] = parent_clade if child_bitstrs: remove_list = [] for c in child_bitstrs: remove_list.extend(c.index_one()) child_clade = bitstr_clades[c] parent_clade.clades.remove(child_clade) clade.clades.append(child_clade) remove_terms = [terms[i] for i in remove_list] clade.clades = [c for c in clade.clades if c not in remove_terms] # put new clade bitstr_clades[bitstr] = clade if (len(bitstr_clades) == len(terms) - 1) or ( len(bitstr_clades) == len(terms) - 2 and len(root.clades) == 3 ): break return BaseTree.Tree(root=root)
Search Adam Consensus tree from multiple trees. :Parameters: trees : list list of trees to produce consensus tree.
def adam_consensus(trees): """Search Adam Consensus tree from multiple trees. :Parameters: trees : list list of trees to produce consensus tree. """ clades = [tree.root for tree in trees] return BaseTree.Tree(root=_part(clades), rooted=True)
Recursive function for Adam Consensus algorithm (PRIVATE).
def _part(clades): """Recursive function for Adam Consensus algorithm (PRIVATE).""" new_clade = None terms = clades[0].get_terminals() term_names = [term.name for term in terms] if len(terms) == 1 or len(terms) == 2: new_clade = clades[0] else: bitstrs = {_BitString("1" * len(terms))} for clade in clades: for child in clade.clades: bitstr = _clade_to_bitstr(child, term_names) to_remove = set() to_add = set() for bs in bitstrs: if bs == bitstr: continue elif bs.contains(bitstr): to_add.add(bitstr) to_add.add(bs ^ bitstr) to_remove.add(bs) elif bitstr.contains(bs): to_add.add(bs ^ bitstr) elif not bs.independent(bitstr): to_add.add(bs & bitstr) to_add.add(bs & bitstr ^ bitstr) to_add.add(bs & bitstr ^ bs) to_remove.add(bs) # bitstrs = bitstrs | to_add bitstrs ^= to_remove if to_add: for ta in sorted(to_add, key=lambda bs: bs.count("1")): independent = True for bs in bitstrs: if not ta.independent(bs): independent = False break if independent: bitstrs.add(ta) new_clade = BaseTree.Clade() for bitstr in sorted(bitstrs): indices = bitstr.index_one() if len(indices) == 1: new_clade.clades.append(terms[indices[0]]) elif len(indices) == 2: bifur_clade = BaseTree.Clade() bifur_clade.clades.append(terms[indices[0]]) bifur_clade.clades.append(terms[indices[1]]) new_clade.clades.append(bifur_clade) elif len(indices) > 2: part_names = [term_names[i] for i in indices] next_clades = [] for clade in clades: next_clades.append(_sub_clade(clade, part_names)) # next_clades = [clade.common_ancestor([clade.find_any(name=name) for name in part_names]) for clade in clades] new_clade.clades.append(_part(next_clades)) return new_clade
Extract a compatible subclade that only contains the given terminal names (PRIVATE).
def _sub_clade(clade, term_names): """Extract a compatible subclade that only contains the given terminal names (PRIVATE).""" term_clades = [clade.find_any(name) for name in term_names] sub_clade = clade.common_ancestor(term_clades) if len(term_names) != sub_clade.count_terminals(): temp_clade = BaseTree.Clade() temp_clade.clades.extend(term_clades) for c in sub_clade.find_clades(terminal=False, order="preorder"): if c == sub_clade.root: continue children = set(c.find_clades(terminal=True)) & set(term_clades) if children: for tc in temp_clade.find_clades(terminal=False, order="preorder"): tc_children = set(tc.clades) tc_new_clades = tc_children - children if children.issubset(tc_children) and tc_new_clades: tc.clades = list(tc_new_clades) child_clade = BaseTree.Clade() child_clade.clades.extend(list(children)) tc.clades.append(child_clade) sub_clade = temp_clade return sub_clade
Count distinct clades (different sets of terminal names) in the trees (PRIVATE). Return a tuple first a dict of bitstring (representing clade) and a tuple of its count of occurrences and sum of branch length for that clade, second the number of trees processed. :Parameters: trees : iterable An iterable that returns the trees to count
def _count_clades(trees): """Count distinct clades (different sets of terminal names) in the trees (PRIVATE). Return a tuple first a dict of bitstring (representing clade) and a tuple of its count of occurrences and sum of branch length for that clade, second the number of trees processed. :Parameters: trees : iterable An iterable that returns the trees to count """ bitstrs = {} tree_count = 0 for tree in trees: tree_count += 1 clade_bitstrs = _tree_to_bitstrs(tree) for clade in tree.find_clades(terminal=False): bitstr = clade_bitstrs[clade] if bitstr in bitstrs: count, sum_bl = bitstrs[bitstr] count += 1 sum_bl += clade.branch_length or 0 bitstrs[bitstr] = (count, sum_bl) else: bitstrs[bitstr] = (1, clade.branch_length or 0) return bitstrs, tree_count
Calculate branch support for a target tree given bootstrap replicate trees. :Parameters: target_tree : Tree tree to calculate branch support for. trees : iterable iterable of trees used to calculate branch support. len_trees : int optional count of replicates in trees. len_trees must be provided when len(trees) is not a valid operation.
def get_support(target_tree, trees, len_trees=None): """Calculate branch support for a target tree given bootstrap replicate trees. :Parameters: target_tree : Tree tree to calculate branch support for. trees : iterable iterable of trees used to calculate branch support. len_trees : int optional count of replicates in trees. len_trees must be provided when len(trees) is not a valid operation. """ term_names = sorted(term.name for term in target_tree.find_clades(terminal=True)) bitstrs = {} size = len_trees if size is None: try: size = len(trees) except TypeError: raise TypeError( "Trees does not support len(trees), " "you must provide the number of replicates in trees " "as the optional parameter len_trees." ) from None for clade in target_tree.find_clades(terminal=False): bitstr = _clade_to_bitstr(clade, term_names) bitstrs[bitstr] = (clade, 0) for tree in trees: for clade in tree.find_clades(terminal=False): bitstr = _clade_to_bitstr(clade, term_names) if bitstr in bitstrs: c, t = bitstrs[bitstr] c.confidence = (t + 1) * 100.0 / size bitstrs[bitstr] = (c, t + 1) return target_tree
Generate bootstrap replicates from a multiple sequence alignment (OBSOLETE). :Parameters: msa : MultipleSeqAlignment multiple sequence alignment to generate replicates. times : int number of bootstrap times.
def bootstrap(msa, times): """Generate bootstrap replicates from a multiple sequence alignment (OBSOLETE). :Parameters: msa : MultipleSeqAlignment multiple sequence alignment to generate replicates. times : int number of bootstrap times. """ length = len(msa[0]) i = 0 while i < times: i += 1 item = None for j in range(length): col = random.randint(0, length - 1) if not item: item = msa[:, col : col + 1] else: item += msa[:, col : col + 1] yield item
Generate bootstrap replicate trees from a multiple sequence alignment. :Parameters: alignment : Alignment or MultipleSeqAlignment object multiple sequence alignment to generate replicates. times : int number of bootstrap times. tree_constructor : TreeConstructor tree constructor to be used to build trees.
def bootstrap_trees(alignment, times, tree_constructor): """Generate bootstrap replicate trees from a multiple sequence alignment. :Parameters: alignment : Alignment or MultipleSeqAlignment object multiple sequence alignment to generate replicates. times : int number of bootstrap times. tree_constructor : TreeConstructor tree constructor to be used to build trees. """ if isinstance(alignment, MultipleSeqAlignment): length = len(alignment[0]) for i in range(times): bootstrapped_alignment = None for j in range(length): col = random.randint(0, length - 1) if bootstrapped_alignment is None: bootstrapped_alignment = alignment[:, col : col + 1] else: bootstrapped_alignment += alignment[:, col : col + 1] tree = tree_constructor.build_tree(bootstrapped_alignment) yield tree else: n, m = alignment.shape for i in range(times): cols = [random.randint(0, m - 1) for j in range(m)] tree = tree_constructor.build_tree(alignment[:, cols]) yield tree
Consensus tree of a series of bootstrap trees for a multiple sequence alignment. :Parameters: alignment : Alignment or MultipleSeqAlignment object Multiple sequence alignment to generate replicates. times : int Number of bootstrap times. tree_constructor : TreeConstructor Tree constructor to be used to build trees. consensus : function Consensus method in this module: ``strict_consensus``, ``majority_consensus``, ``adam_consensus``.
def bootstrap_consensus(alignment, times, tree_constructor, consensus): """Consensus tree of a series of bootstrap trees for a multiple sequence alignment. :Parameters: alignment : Alignment or MultipleSeqAlignment object Multiple sequence alignment to generate replicates. times : int Number of bootstrap times. tree_constructor : TreeConstructor Tree constructor to be used to build trees. consensus : function Consensus method in this module: ``strict_consensus``, ``majority_consensus``, ``adam_consensus``. """ trees = bootstrap_trees(alignment, times, tree_constructor) tree = consensus(trees) return tree
Create a BitString representing a clade, given ordered tree taxon names (PRIVATE).
def _clade_to_bitstr(clade, tree_term_names): """Create a BitString representing a clade, given ordered tree taxon names (PRIVATE).""" clade_term_names = {term.name for term in clade.find_clades(terminal=True)} return _BitString.from_bool((name in clade_term_names) for name in tree_term_names)
Create a dict of a tree's clades to corresponding BitStrings (PRIVATE).
def _tree_to_bitstrs(tree): """Create a dict of a tree's clades to corresponding BitStrings (PRIVATE).""" clades_bitstrs = {} term_names = [term.name for term in tree.find_clades(terminal=True)] for clade in tree.find_clades(terminal=False): bitstr = _clade_to_bitstr(clade, term_names) clades_bitstrs[clade] = bitstr return clades_bitstrs
Generate a branch length dict for a tree, keyed by BitStrings (PRIVATE). Create a dict of all clades' BitStrings to the corresponding branch lengths (rounded to 5 decimal places).
def _bitstring_topology(tree): """Generate a branch length dict for a tree, keyed by BitStrings (PRIVATE). Create a dict of all clades' BitStrings to the corresponding branch lengths (rounded to 5 decimal places). """ bitstrs = {} for clade, bitstr in _tree_to_bitstrs(tree).items(): bitstrs[bitstr] = round(clade.branch_length or 0.0, 5) return bitstrs
Are two trees are equal in terms of topology and branch lengths (PRIVATE). (Branch lengths checked to 5 decimal places.)
def _equal_topology(tree1, tree2): """Are two trees are equal in terms of topology and branch lengths (PRIVATE). (Branch lengths checked to 5 decimal places.) """ term_names1 = {term.name for term in tree1.find_clades(terminal=True)} term_names2 = {term.name for term in tree2.find_clades(terminal=True)} return (term_names1 == term_names2) and ( _bitstring_topology(tree1) == _bitstring_topology(tree2) )
Iterate over the trees in a Newick file handle. :returns: generator of Bio.Phylo.Newick.Tree objects.
def parse(handle, **kwargs): """Iterate over the trees in a Newick file handle. :returns: generator of Bio.Phylo.Newick.Tree objects. """ return Parser(handle).parse(**kwargs)
Write a trees in Newick format to the given file handle. :returns: number of trees written.
def write(trees, handle, plain=False, **kwargs): """Write a trees in Newick format to the given file handle. :returns: number of trees written. """ return Writer(trees).write(handle, plain=plain, **kwargs)
Given a prefixed URI, return the full URI.
def qUri(s): """Given a prefixed URI, return the full URI.""" return resolve_uri(s, namespaces=NAMESPACES, xml_style=True)
Optionally converts a CDAO-prefixed URI into an OBO-prefixed URI.
def cdao_to_obo(s): """Optionally converts a CDAO-prefixed URI into an OBO-prefixed URI.""" return f"obo:{cdao_elements[s[len('cdao:'):]]}"
Check for matches in both CDAO and OBO namespaces.
def matches(s): """Check for matches in both CDAO and OBO namespaces.""" if s.startswith("cdao:"): return (s, cdao_to_obo(s)) else: return (s,)
Iterate over the trees in a NeXML file handle. :returns: generator of Bio.Phylo.NeXML.Tree objects.
def parse(handle, **kwargs): """Iterate over the trees in a NeXML file handle. :returns: generator of Bio.Phylo.NeXML.Tree objects. """ return Parser(handle).parse(**kwargs)
Write a trees in NeXML format to the given file handle. :returns: number of trees written.
def write(trees, handle, plain=False, **kwargs): """Write a trees in NeXML format to the given file handle. :returns: number of trees written. """ return Writer(trees).write(handle, plain=plain, **kwargs)
Parse the trees in a Nexus file. Uses the old Nexus.Trees parser to extract the trees, converts them back to plain Newick trees, and feeds those strings through the new Newick parser. This way we don't have to modify the Nexus module yet. (Perhaps we'll eventually change Nexus to use the new NewickIO parser directly.)
def parse(handle): """Parse the trees in a Nexus file. Uses the old Nexus.Trees parser to extract the trees, converts them back to plain Newick trees, and feeds those strings through the new Newick parser. This way we don't have to modify the Nexus module yet. (Perhaps we'll eventually change Nexus to use the new NewickIO parser directly.) """ nex = Nexus.Nexus(handle) # NB: Once Nexus.Trees is modified to use Tree.Newick objects, do this: # return iter(nex.trees) # Until then, convert the Nexus.Trees.Tree object hierarchy: def node2clade(nxtree, node): subclades = [node2clade(nxtree, nxtree.node(n)) for n in node.succ] return Newick.Clade( branch_length=node.data.branchlength, name=node.data.taxon, clades=subclades, confidence=node.data.support, comment=node.data.comment, ) for nxtree in nex.trees: newroot = node2clade(nxtree, nxtree.node(nxtree.root)) yield Newick.Tree( root=newroot, rooted=nxtree.rooted, name=nxtree.name, weight=nxtree.weight )
Write a new Nexus file containing the given trees. Uses a simple Nexus template and the NewickIO writer to serialize just the trees and minimal supporting info needed for a valid Nexus file.
def write(obj, handle, **kwargs): """Write a new Nexus file containing the given trees. Uses a simple Nexus template and the NewickIO writer to serialize just the trees and minimal supporting info needed for a valid Nexus file. """ trees = list(obj) writer = NewickIO.Writer(trees) nexus_trees = [ TREE_TEMPLATE % {"index": idx + 1, "tree": nwk} for idx, nwk in enumerate( writer.to_strings(plain=False, plain_newick=True, **kwargs) ) ] tax_labels = [str(x.name) for x in chain(*(t.get_terminals() for t in trees))] text = NEX_TEMPLATE % { "count": len(tax_labels), "labels": " ".join(tax_labels), "trees": "\n".join(nexus_trees), } handle.write(text) return len(nexus_trees)
Check a string using testfunc, and warn if there's no match (PRIVATE).
def _check_str(text, testfunc): """Check a string using testfunc, and warn if there's no match (PRIVATE).""" if text is not None and not testfunc(text): warnings.warn( f"String {text} doesn't match the given regexp", PhyloXMLWarning, stacklevel=2, )
Parse a phyloXML file or stream and build a tree of Biopython objects. The children of the root node are phylogenies and possibly other arbitrary (non-phyloXML) objects. :returns: a single ``Bio.Phylo.PhyloXML.Phyloxml`` object.
def read(file): """Parse a phyloXML file or stream and build a tree of Biopython objects. The children of the root node are phylogenies and possibly other arbitrary (non-phyloXML) objects. :returns: a single ``Bio.Phylo.PhyloXML.Phyloxml`` object. """ return Parser(file).read()
Iterate over the phylogenetic trees in a phyloXML file. This ignores any additional data stored at the top level, but may be more memory-efficient than the ``read`` function. :returns: a generator of ``Bio.Phylo.PhyloXML.Phylogeny`` objects.
def parse(file): """Iterate over the phylogenetic trees in a phyloXML file. This ignores any additional data stored at the top level, but may be more memory-efficient than the ``read`` function. :returns: a generator of ``Bio.Phylo.PhyloXML.Phylogeny`` objects. """ return Parser(file).parse()
Write a phyloXML file. :Parameters: obj an instance of ``Phyloxml``, ``Phylogeny`` or ``BaseTree.Tree``, or an iterable of either of the latter two. The object will be converted to a Phyloxml object before serialization. file either an open handle or a file name.
def write(obj, file, encoding=DEFAULT_ENCODING, indent=True): """Write a phyloXML file. :Parameters: obj an instance of ``Phyloxml``, ``Phylogeny`` or ``BaseTree.Tree``, or an iterable of either of the latter two. The object will be converted to a Phyloxml object before serialization. file either an open handle or a file name. """ def fix_single(tree): if isinstance(tree, PX.Phylogeny): return tree if isinstance(tree, PX.Clade): return tree.to_phylogeny() if isinstance(tree, PX.BaseTree.Tree): return PX.Phylogeny.from_tree(tree) if isinstance(tree, PX.BaseTree.Clade): return PX.Phylogeny.from_tree(PX.BaseTree.Tree(root=tree)) else: raise ValueError("iterable must contain Tree or Clade types") if isinstance(obj, PX.Phyloxml): pass elif isinstance(obj, (PX.BaseTree.Tree, PX.BaseTree.Clade)): obj = fix_single(obj).to_phyloxml() elif hasattr(obj, "__iter__"): obj = PX.Phyloxml({}, phylogenies=(fix_single(t) for t in obj)) else: raise ValueError( "First argument must be a Phyloxml, Phylogeny, " "Tree, or iterable of Trees or Phylogenies." ) return Writer(obj).write(file, encoding=encoding, indent=indent)
Extract the local tag from a namespaced tag name (PRIVATE).
def _local(tag): """Extract the local tag from a namespaced tag name (PRIVATE).""" if tag[0] == "{": return tag[tag.index("}") + 1 :] return tag
Split a tag into namespace and local tag strings (PRIVATE).
def _split_namespace(tag): """Split a tag into namespace and local tag strings (PRIVATE).""" try: return tag[1:].split("}", 1) except ValueError: return ("", tag)
Format an XML tag with the given namespace (PRIVATE).
def _ns(tag, namespace=NAMESPACES["phy"]): """Format an XML tag with the given namespace (PRIVATE).""" return f"{{{namespace}}}{tag}"
Find a child node by tag, and pass it through a constructor (PRIVATE). Returns None if no matching child is found.
def _get_child_as(parent, tag, construct): """Find a child node by tag, and pass it through a constructor (PRIVATE). Returns None if no matching child is found. """ child = parent.find(_ns(tag)) if child is not None: return construct(child)
Find a child node by tag; pass its text through a constructor (PRIVATE). Returns None if no matching child is found.
def _get_child_text(parent, tag, construct=str): """Find a child node by tag; pass its text through a constructor (PRIVATE). Returns None if no matching child is found. """ child = parent.find(_ns(tag)) if child is not None and child.text: return construct(child.text)
Find child nodes by tag; pass each through a constructor (PRIVATE). Returns an empty list if no matching child is found.
def _get_children_as(parent, tag, construct): """Find child nodes by tag; pass each through a constructor (PRIVATE). Returns an empty list if no matching child is found. """ return [construct(child) for child in parent.findall(_ns(tag))]
Find child nodes by tag; pass each node's text through a constructor (PRIVATE). Returns an empty list if no matching child is found.
def _get_children_text(parent, tag, construct=str): """Find child nodes by tag; pass each node's text through a constructor (PRIVATE). Returns an empty list if no matching child is found. """ return [construct(child.text) for child in parent.findall(_ns(tag)) if child.text]
Add line breaks and indentation to ElementTree in-place (PRIVATE). Sources: - http://effbot.org/zone/element-lib.htm#prettyprint - http://infix.se/2007/02/06/gentlemen-indent-your-xml
def _indent(elem, level=0): """Add line breaks and indentation to ElementTree in-place (PRIVATE). Sources: - http://effbot.org/zone/element-lib.htm#prettyprint - http://infix.se/2007/02/06/gentlemen-indent-your-xml """ i = "\n" + level * " " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " for e in elem: _indent(e, level + 1) if not e.tail or not e.tail.strip(): e.tail = i + " " if not e.tail or not e.tail.strip(): e.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i
Convert string to boolean (PRIVATE).
def _str2bool(text): """Convert string to boolean (PRIVATE).""" if text == "true" or text == "1": return True if text == "false" or text == "0": return False raise ValueError("String could not be converted to boolean: " + text)
Return a new dictionary where string values are replaced with booleans (PRIVATE).
def _dict_str2bool(dct, keys): """Return a new dictionary where string values are replaced with booleans (PRIVATE).""" out = dct.copy() for key in keys: if key in out: out[key] = _str2bool(out[key]) return out
Return text as an integer (PRIVATE).
def _int(text): """Return text as an integer (PRIVATE).""" if text is not None: try: return int(text) except Exception: return None
Return text as a float (PRIVATE).
def _float(text): """Return text as a float (PRIVATE).""" if text is not None: try: return float(text) except Exception: return None
Replace all spans of whitespace with a single space character (PRIVATE). Also remove leading and trailing whitespace. See "Collapse Whitespace Policy" in the phyloXML spec glossary: http://phyloxml.org/documentation/version_100/phyloxml.xsd.html#Glossary
def _collapse_wspace(text): """Replace all spans of whitespace with a single space character (PRIVATE). Also remove leading and trailing whitespace. See "Collapse Whitespace Policy" in the phyloXML spec glossary: http://phyloxml.org/documentation/version_100/phyloxml.xsd.html#Glossary """ if text is not None: return " ".join(text.split())
Replace tab, LF and CR characters with spaces, but don't collapse (PRIVATE). See "Replace Whitespace Policy" in the phyloXML spec glossary: http://phyloxml.org/documentation/version_100/phyloxml.xsd.html#Glossary
def _replace_wspace(text): """Replace tab, LF and CR characters with spaces, but don't collapse (PRIVATE). See "Replace Whitespace Policy" in the phyloXML spec glossary: http://phyloxml.org/documentation/version_100/phyloxml.xsd.html#Glossary """ for char in ("\t", "\n", "\r"): if char in text: text = text.replace(char, " ") return text
Convert a Python primitive to a phyloXML-compatible string (PRIVATE).
def _serialize(value): """Convert a Python primitive to a phyloXML-compatible string (PRIVATE).""" if isinstance(value, float): return str(value).upper() elif isinstance(value, bool): return str(value).lower() return str(value)
Create a dictionary from an object's specified, non-None attributes (PRIVATE).
def _clean_attrib(obj, attrs): """Create a dictionary from an object's specified, non-None attributes (PRIVATE).""" out = {} for key in attrs: val = getattr(obj, key) if val is not None: out[key] = _serialize(val) return out
Handle to serialize nodes with subnodes (PRIVATE).
def _handle_complex(tag, attribs, subnodes, has_text=False): """Handle to serialize nodes with subnodes (PRIVATE).""" def wrapped(self, obj): """Wrap nodes and subnodes as elements.""" elem = ElementTree.Element(tag, _clean_attrib(obj, attribs)) for subn in subnodes: if isinstance(subn, str): # singular object: method and attribute names are the same if getattr(obj, subn) is not None: elem.append(getattr(self, subn)(getattr(obj, subn))) else: # list: singular method, pluralized attribute name method, plural = subn for item in getattr(obj, plural): elem.append(getattr(self, method)(item)) if has_text: elem.text = _serialize(obj.value) return elem wrapped.__doc__ = f"Serialize a {tag} and its subnodes, in order." return wrapped
Handle to serialize simple nodes (PRIVATE).
def _handle_simple(tag): """Handle to serialize simple nodes (PRIVATE).""" def wrapped(self, obj): """Wrap node as element.""" elem = ElementTree.Element(tag) elem.text = _serialize(obj) return elem wrapped.__doc__ = f"Serialize a simple {tag} node." return wrapped
Convert prefixed URIs to full URIs. Optionally, converts CDAO named identifiers to OBO numeric identifiers.
def resolve_uri(s, namespaces=cdao_namespaces, cdao_to_obo=True, xml_style=False): """Convert prefixed URIs to full URIs. Optionally, converts CDAO named identifiers to OBO numeric identifiers. """ if cdao_to_obo and s.startswith("cdao:"): return resolve_uri(f"obo:{cdao_elements[s[5:]]}", namespaces, cdao_to_obo) for prefix in namespaces: if xml_style: s = s.replace(prefix + ":", "{%s}" % namespaces[prefix]) else: s = s.replace(prefix + ":", namespaces[prefix]) return s
Parse a file iteratively, and yield each of the trees it contains. If a file only contains one tree, this still returns an iterable object that contains one element. Examples -------- >>> import Bio.Phylo >>> trees = Bio.Phylo.parse('PhyloXML/apaf.xml', 'phyloxml') >>> for tree in trees: ... print(tree.rooted) True
def parse(file, format, **kwargs): """Parse a file iteratively, and yield each of the trees it contains. If a file only contains one tree, this still returns an iterable object that contains one element. Examples -------- >>> import Bio.Phylo >>> trees = Bio.Phylo.parse('PhyloXML/apaf.xml', 'phyloxml') >>> for tree in trees: ... print(tree.rooted) True """ with File.as_handle(file) as fp: yield from getattr(supported_formats[format], "parse")(fp, **kwargs)
Parse a file in the given format and return a single tree. Raises a ``ValueError`` if there are zero or multiple trees -- if this occurs, use ``parse`` instead to get the complete sequence of trees.
def read(file, format, **kwargs): """Parse a file in the given format and return a single tree. Raises a ``ValueError`` if there are zero or multiple trees -- if this occurs, use ``parse`` instead to get the complete sequence of trees. """ try: tree_gen = parse(file, format, **kwargs) tree = next(tree_gen) except StopIteration: raise ValueError("There are no trees in this file.") from None try: next(tree_gen) except StopIteration: return tree else: raise ValueError("There are multiple trees in this file; use parse() instead.")
Write a sequence of trees to file in the given format.
def write(trees, file, format, **kwargs): """Write a sequence of trees to file in the given format.""" if isinstance(trees, (BaseTree.Tree, BaseTree.Clade)): # Passed a single tree instead of an iterable -- that's OK trees = [trees] with File.as_handle(file, "w+") as fp: n = getattr(supported_formats[format], "write")(trees, fp, **kwargs) return n
Convert between two tree file formats.
def convert(in_file, in_format, out_file, out_format, parse_args=None, **kwargs): """Convert between two tree file formats.""" if parse_args is None: parse_args = {} trees = parse(in_file, in_format, **parse_args) return write(trees, out_file, out_format, **kwargs)
Convert a Tree object to a networkx graph. The result is useful for graph-oriented analysis, and also interactive plotting with pylab, matplotlib or pygraphviz, though the resulting diagram is usually not ideal for displaying a phylogeny. Requires NetworkX version 0.99 or later.
def to_networkx(tree): """Convert a Tree object to a networkx graph. The result is useful for graph-oriented analysis, and also interactive plotting with pylab, matplotlib or pygraphviz, though the resulting diagram is usually not ideal for displaying a phylogeny. Requires NetworkX version 0.99 or later. """ try: import networkx except ImportError: raise MissingPythonDependencyError( "Install NetworkX if you want to use to_networkx." ) from None # NB (1/2010): the networkx API stabilized at v.1.0 # 1.0+: edges accept arbitrary data as kwargs, weights are floats # 0.99: edges accept weight as a string, nothing else # pre-0.99: edges accept no additional data # Ubuntu Lucid LTS uses v0.99, let's support everything if networkx.__version__ >= "1.0": def add_edge(graph, n1, n2): graph.add_edge(n1, n2, weight=n2.branch_length or 1.0) # Copy branch color value as hex, if available if hasattr(n2, "color") and n2.color is not None: graph[n1][n2]["color"] = n2.color.to_hex() elif hasattr(n1, "color") and n1.color is not None: # Cascading color attributes graph[n1][n2]["color"] = n1.color.to_hex() n2.color = n1.color # Copy branch weight value (float) if available if hasattr(n2, "width") and n2.width is not None: graph[n1][n2]["width"] = n2.width elif hasattr(n1, "width") and n1.width is not None: # Cascading width attributes graph[n1][n2]["width"] = n1.width n2.width = n1.width elif networkx.__version__ >= "0.99": def add_edge(graph, n1, n2): graph.add_edge(n1, n2, (n2.branch_length or 1.0)) else: def add_edge(graph, n1, n2): graph.add_edge(n1, n2) def build_subgraph(graph, top): """Walk down the Tree, building graphs, edges and nodes.""" for clade in top: graph.add_node(clade.root) add_edge(graph, top.root, clade.root) build_subgraph(graph, clade) if tree.rooted: G = networkx.DiGraph() else: G = networkx.Graph() G.add_node(tree.root) build_subgraph(G, tree.root) return G
Convert a Tree object to an igraph Graph. The result is useful for graph-oriented analysis and interactive plotting with matplotlib, Cairo, and plotly. Requires python-igraph version 0.10.0 or later. :Parameters: vertex_attributes : sequence of strings A sequence of strings containing the Clade properties that are to be stored as vertex attributes, e.g. "name". edge_attributes : sequence of strings A sequence of strings containing the Clade properties that are to be stored as edge attributes, e.g. "color" and "width". In both cases, if a property is not found it will be ignored.
def to_igraph(tree, vertex_attributes=None, edge_attributes=("color", "width")): """Convert a Tree object to an igraph Graph. The result is useful for graph-oriented analysis and interactive plotting with matplotlib, Cairo, and plotly. Requires python-igraph version 0.10.0 or later. :Parameters: vertex_attributes : sequence of strings A sequence of strings containing the Clade properties that are to be stored as vertex attributes, e.g. "name". edge_attributes : sequence of strings A sequence of strings containing the Clade properties that are to be stored as edge attributes, e.g. "color" and "width". In both cases, if a property is not found it will be ignored. """ try: import igraph as ig except ImportError: raise MissingPythonDependencyError( "Install igraph if you want to use to_igraph." ) from None if ig.__version__ < "0.10": raise MissingPythonDependencyError( "Update igraph to 0.10 or later if you want to use to_igraph." ) # Count the leaves, thereby the total number of nodes in the tree n_nodes = sum(1 for x in tree.find_clades()) # Empty tree if n_nodes == 0: return ig.Graph() # NOTE: In igraph, adding all edges at once is much faster, so we prepare # an edgelist and related attributes def add_subtree(node, n_node, counter, edges, edge_attrs, vertex_attrs): """Add edges from this subtree, breath-first.""" # NOTE: Bio.Phylo stores both vertex and edge attributes in the # same place as "clade" attributes. However, the root node can have # a vertex attribute but no edge attribute, hence the code blocks are # in different places for attrname in vertex_attrs: if hasattr(node, attrname): # Sometimes, only some tree nodes (e.g. leaves) have # a certain attribute, e.g. a name if len(vertex_attrs[attrname]) == 0: vertex_attrs[attrname] = [None] * n_nodes vertex_attrs[attrname][n_node] = getattr(node, attrname) delta_counter = 0 for i, child in enumerate(node): n_child = counter + 1 + i delta_counter += 1 edges.append((n_node, n_child)) # NOTE: The root cannot have an edge attribute, therefore to have # an edge attribute you must be child of some other node. for attrname in edge_attrs: if hasattr(child, attrname): # Sometimes, only some tree edges (i.e. branches) have # a certain attribute, e.g. a name edge_attrs[attrname].append(getattr(child, attrname)) old_counter = counter counter = counter + delta_counter for i, child in enumerate(node): n_child = old_counter + 1 + i counter = add_subtree( child, n_child, counter, edges, edge_attrs, vertex_attrs ) return counter edges = [] if vertex_attributes is None: vertex_attributes = () edge_attrs = {attrname: [] for attrname in edge_attributes} vertex_attrs = {attrname: [] for attrname in vertex_attributes} add_subtree(tree.root, 0, 0, edges, edge_attrs, vertex_attrs) # Remove unused attributes for attrname in vertex_attributes: if len(vertex_attrs[attrname]) == 0: del vertex_attrs[attrname] for attrname in edge_attributes: if len(edge_attrs[attrname]) == 0: del edge_attrs[attrname] graph = ig.Graph( edges=edges, vertex_attrs=vertex_attrs, edge_attrs=edge_attrs, directed=bool(tree.rooted), ) return graph
Draw an ascii-art phylogram of the given tree. The printed result looks like:: _________ Orange ______________| | |______________ Tangerine ______________| | | _________________________ Grapefruit _| |_________| | |______________ Pummelo | |__________________________________ Apple :Parameters: file : file-like object File handle opened for writing the output drawing. (Default: standard output) column_width : int Total number of text columns used by the drawing.
def draw_ascii(tree, file=None, column_width=80): """Draw an ascii-art phylogram of the given tree. The printed result looks like:: _________ Orange ______________| | |______________ Tangerine ______________| | | _________________________ Grapefruit _| |_________| | |______________ Pummelo | |__________________________________ Apple :Parameters: file : file-like object File handle opened for writing the output drawing. (Default: standard output) column_width : int Total number of text columns used by the drawing. """ if file is None: file = sys.stdout taxa = tree.get_terminals() # Some constants for the drawing calculations max_label_width = max(len(str(taxon)) for taxon in taxa) drawing_width = column_width - max_label_width - 1 drawing_height = 2 * len(taxa) - 1 def get_col_positions(tree): """Create a mapping of each clade to its column position.""" depths = tree.depths() # If there are no branch lengths, assume unit branch lengths if max(depths.values()) == 0: depths = tree.depths(unit_branch_lengths=True) # Potential drawing overflow due to rounding -- 1 char per tree layer fudge_margin = int(math.ceil(math.log(len(taxa), 2))) cols_per_branch_unit = (drawing_width - fudge_margin) / max(depths.values()) return { clade: int(blen * cols_per_branch_unit + 1.0) for clade, blen in depths.items() } def get_row_positions(tree): positions = {taxon: 2 * idx for idx, taxon in enumerate(taxa)} def calc_row(clade): for subclade in clade: if subclade not in positions: calc_row(subclade) positions[clade] = ( positions[clade.clades[0]] + positions[clade.clades[-1]] ) // 2 calc_row(tree.root) return positions col_positions = get_col_positions(tree) row_positions = get_row_positions(tree) char_matrix = [[" " for x in range(drawing_width)] for y in range(drawing_height)] def draw_clade(clade, startcol): thiscol = col_positions[clade] thisrow = row_positions[clade] # Draw a horizontal line for col in range(startcol, thiscol): char_matrix[thisrow][col] = "_" if clade.clades: # Draw a vertical line toprow = row_positions[clade.clades[0]] botrow = row_positions[clade.clades[-1]] for row in range(toprow + 1, botrow + 1): char_matrix[row][thiscol] = "|" # NB: Short terminal branches need something to stop rstrip() if (col_positions[clade.clades[0]] - thiscol) < 2: char_matrix[toprow][thiscol] = "," # Draw descendents for child in clade: draw_clade(child, thiscol + 1) draw_clade(tree.root, 0) # Print the complete drawing for idx, row in enumerate(char_matrix): line = "".join(row).rstrip() # Add labels for terminal taxa in the right margin if idx % 2 == 0: line += " " + str(taxa[idx // 2]) file.write(line + "\n") file.write("\n")
Plot the given tree using matplotlib (or pylab). The graphic is a rooted tree, drawn with roughly the same algorithm as draw_ascii. Additional keyword arguments passed into this function are used as pyplot options. The input format should be in the form of: pyplot_option_name=(tuple), pyplot_option_name=(tuple, dict), or pyplot_option_name=(dict). Example using the pyplot options 'axhspan' and 'axvline':: from Bio import Phylo, AlignIO from Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor constructor = DistanceTreeConstructor() aln = AlignIO.read(open('TreeConstruction/msa.phy'), 'phylip') calculator = DistanceCalculator('identity') dm = calculator.get_distance(aln) tree = constructor.upgma(dm) Phylo.draw(tree, axhspan=((0.25, 7.75), {'facecolor':'0.5'}), ... axvline={'x':0, 'ymin':0, 'ymax':1}) Visual aspects of the plot can also be modified using pyplot's own functions and objects (via pylab or matplotlib). In particular, the pyplot.rcParams object can be used to scale the font size (rcParams["font.size"]) and line width (rcParams["lines.linewidth"]). :Parameters: label_func : callable A function to extract a label from a node. By default this is str(), but you can use a different function to select another string associated with each node. If this function returns None for a node, no label will be shown for that node. do_show : bool Whether to show() the plot automatically. show_confidence : bool Whether to display confidence values, if present on the tree. axes : matplotlib/pylab axes If a valid matplotlib.axes.Axes instance, the phylogram is plotted in that Axes. By default (None), a new figure is created. branch_labels : dict or callable A mapping of each clade to the label that will be shown along the branch leading to it. By default this is the confidence value(s) of the clade, taken from the ``confidence`` attribute, and can be easily toggled off with this function's ``show_confidence`` option. But if you would like to alter the formatting of confidence values, or label the branches with something other than confidence, then use this option. label_colors : dict or callable A function or a dictionary specifying the color of the tip label. If the tip label can't be found in the dict or label_colors is None, the label will be shown in black.
def draw( tree, label_func=str, do_show=True, show_confidence=True, # For power users axes=None, branch_labels=None, label_colors=None, *args, **kwargs, ): """Plot the given tree using matplotlib (or pylab). The graphic is a rooted tree, drawn with roughly the same algorithm as draw_ascii. Additional keyword arguments passed into this function are used as pyplot options. The input format should be in the form of: pyplot_option_name=(tuple), pyplot_option_name=(tuple, dict), or pyplot_option_name=(dict). Example using the pyplot options 'axhspan' and 'axvline':: from Bio import Phylo, AlignIO from Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor constructor = DistanceTreeConstructor() aln = AlignIO.read(open('TreeConstruction/msa.phy'), 'phylip') calculator = DistanceCalculator('identity') dm = calculator.get_distance(aln) tree = constructor.upgma(dm) Phylo.draw(tree, axhspan=((0.25, 7.75), {'facecolor':'0.5'}), ... axvline={'x':0, 'ymin':0, 'ymax':1}) Visual aspects of the plot can also be modified using pyplot's own functions and objects (via pylab or matplotlib). In particular, the pyplot.rcParams object can be used to scale the font size (rcParams["font.size"]) and line width (rcParams["lines.linewidth"]). :Parameters: label_func : callable A function to extract a label from a node. By default this is str(), but you can use a different function to select another string associated with each node. If this function returns None for a node, no label will be shown for that node. do_show : bool Whether to show() the plot automatically. show_confidence : bool Whether to display confidence values, if present on the tree. axes : matplotlib/pylab axes If a valid matplotlib.axes.Axes instance, the phylogram is plotted in that Axes. By default (None), a new figure is created. branch_labels : dict or callable A mapping of each clade to the label that will be shown along the branch leading to it. By default this is the confidence value(s) of the clade, taken from the ``confidence`` attribute, and can be easily toggled off with this function's ``show_confidence`` option. But if you would like to alter the formatting of confidence values, or label the branches with something other than confidence, then use this option. label_colors : dict or callable A function or a dictionary specifying the color of the tip label. If the tip label can't be found in the dict or label_colors is None, the label will be shown in black. """ try: import matplotlib.pyplot as plt except ImportError: try: import pylab as plt except ImportError: raise MissingPythonDependencyError( "Install matplotlib or pylab if you want to use draw." ) from None import matplotlib.collections as mpcollections # Arrays that store lines for the plot of clades horizontal_linecollections = [] vertical_linecollections = [] # Options for displaying branch labels / confidence def conf2str(conf): if int(conf) == conf: return str(int(conf)) return str(conf) if not branch_labels: if show_confidence: def format_branch_label(clade): try: confidences = clade.confidences # phyloXML supports multiple confidences except AttributeError: pass else: return "/".join(conf2str(cnf.value) for cnf in confidences) if clade.confidence is not None: return conf2str(clade.confidence) return None else: def format_branch_label(clade): return None elif isinstance(branch_labels, dict): def format_branch_label(clade): return branch_labels.get(clade) else: if not callable(branch_labels): raise TypeError( "branch_labels must be either a dict or a callable (function)" ) format_branch_label = branch_labels # options for displaying label colors. if label_colors: if callable(label_colors): def get_label_color(label): return label_colors(label) else: # label_colors is presumed to be a dict def get_label_color(label): return label_colors.get(label, "black") else: def get_label_color(label): # if label_colors is not specified, use black return "black" # Layout def get_x_positions(tree): """Create a mapping of each clade to its horizontal position. Dict of {clade: x-coord} """ depths = tree.depths() # If there are no branch lengths, assume unit branch lengths if not max(depths.values()): depths = tree.depths(unit_branch_lengths=True) return depths def get_y_positions(tree): """Create a mapping of each clade to its vertical position. Dict of {clade: y-coord}. Coordinates are negative, and integers for tips. """ maxheight = tree.count_terminals() # Rows are defined by the tips heights = { tip: maxheight - i for i, tip in enumerate(reversed(tree.get_terminals())) } # Internal nodes: place at midpoint of children def calc_row(clade): for subclade in clade: if subclade not in heights: calc_row(subclade) # Closure over heights heights[clade] = ( heights[clade.clades[0]] + heights[clade.clades[-1]] ) / 2.0 if tree.root.clades: calc_row(tree.root) return heights x_posns = get_x_positions(tree) y_posns = get_y_positions(tree) # The function draw_clade closes over the axes object if axes is None: fig = plt.figure() axes = fig.add_subplot(1, 1, 1) elif not isinstance(axes, plt.matplotlib.axes.Axes): raise ValueError(f"Invalid argument for axes: {axes}") def draw_clade_lines( use_linecollection=False, orientation="horizontal", y_here=0, x_start=0, x_here=0, y_bot=0, y_top=0, color="black", lw=".1", ): """Create a line with or without a line collection object. Graphical formatting of the lines representing clades in the plot can be customized by altering this function. """ if not use_linecollection and orientation == "horizontal": axes.hlines(y_here, x_start, x_here, color=color, lw=lw) elif use_linecollection and orientation == "horizontal": horizontal_linecollections.append( mpcollections.LineCollection( [[(x_start, y_here), (x_here, y_here)]], color=color, lw=lw ) ) elif not use_linecollection and orientation == "vertical": axes.vlines(x_here, y_bot, y_top, color=color) elif use_linecollection and orientation == "vertical": vertical_linecollections.append( mpcollections.LineCollection( [[(x_here, y_bot), (x_here, y_top)]], color=color, lw=lw ) ) def draw_clade(clade, x_start, color, lw): """Recursively draw a tree, down from the given clade.""" x_here = x_posns[clade] y_here = y_posns[clade] # phyloXML-only graphics annotations if hasattr(clade, "color") and clade.color is not None: color = clade.color.to_hex() if hasattr(clade, "width") and clade.width is not None: lw = clade.width * plt.rcParams["lines.linewidth"] # Draw a horizontal line from start to here draw_clade_lines( use_linecollection=True, orientation="horizontal", y_here=y_here, x_start=x_start, x_here=x_here, color=color, lw=lw, ) # Add node/taxon labels label = label_func(clade) if label not in (None, clade.__class__.__name__): axes.text( x_here, y_here, f" {label}", verticalalignment="center", color=get_label_color(label), ) # Add label above the branch (optional) conf_label = format_branch_label(clade) if conf_label: axes.text( 0.5 * (x_start + x_here), y_here, conf_label, fontsize="small", horizontalalignment="center", ) if clade.clades: # Draw a vertical line connecting all children y_top = y_posns[clade.clades[0]] y_bot = y_posns[clade.clades[-1]] # Only apply widths to horizontal lines, like Archaeopteryx draw_clade_lines( use_linecollection=True, orientation="vertical", x_here=x_here, y_bot=y_bot, y_top=y_top, color=color, lw=lw, ) # Draw descendents for child in clade: draw_clade(child, x_here, color, lw) draw_clade(tree.root, 0, "k", plt.rcParams["lines.linewidth"]) # If line collections were used to create clade lines, here they are added # to the pyplot plot. for i in horizontal_linecollections: axes.add_collection(i) for i in vertical_linecollections: axes.add_collection(i) # Aesthetics try: name = tree.name except AttributeError: pass else: if name: axes.set_title(name) axes.set_xlabel("branch length") axes.set_ylabel("taxa") # Add margins around the tree to prevent overlapping the axes xmax = max(x_posns.values()) axes.set_xlim(-0.05 * xmax, 1.25 * xmax) # Also invert the y-axis (origin at the top) # Add a small vertical margin, but avoid including 0 and N+1 on the y axis axes.set_ylim(max(y_posns.values()) + 0.8, 0.2) # Parse and process key word arguments as pyplot options for key, value in kwargs.items(): try: # Check that the pyplot option input is iterable, as required list(value) except TypeError: raise ValueError( 'Keyword argument "%s=%s" is not in the format ' "pyplot_option_name=(tuple), pyplot_option_name=(tuple, dict)," " or pyplot_option_name=(dict) " % (key, value) ) from None if isinstance(value, dict): getattr(plt, str(key))(**dict(value)) elif not (isinstance(value[0], tuple)): getattr(plt, str(key))(*value) elif isinstance(value[0], tuple): getattr(plt, str(key))(*value[0], **dict(value[1])) if do_show: plt.show()
Test whether the argument can be serialized as an integer (PRIVATE).
def _is_int(x): """Test whether the argument can be serialized as an integer (PRIVATE).""" return isinstance(x, int) or str(x).isdigit()
Test whether the argument can be serialized as a number (PRIVATE).
def _is_numeric(x): """Test whether the argument can be serialized as a number (PRIVATE).""" try: float(str(x)) return True except ValueError: return False
Parse a BASEML results file.
def read(results_file): """Parse a BASEML results file.""" results = {} if not os.path.exists(results_file): raise FileNotFoundError("Results file does not exist.") with open(results_file) as handle: lines = handle.readlines() if not lines: raise ValueError( "Empty results file. Did BASEML exit successfully? " "Run 'Baseml.run()' with 'verbose=True'." ) (results, num_params) = _parse_baseml.parse_basics(lines, results) results = _parse_baseml.parse_parameters(lines, results, num_params) if results.get("version") is None: raise ValueError("Invalid results file") return results
Compute p-value, from distribution function and test statistics.
def cdf_chi2(df, stat): """Compute p-value, from distribution function and test statistics.""" if df < 1: raise ValueError("df must be at least 1") if stat < 0: raise ValueError("The test statistic must be positive") x = 0.5 * stat alpha = df / 2.0 prob = 1 - _incomplete_gamma(x, alpha) return prob
Compute the log of the gamma function for a given alpha (PRIVATE). Comments from Z. Yang: Returns ln(gamma(alpha)) for alpha>0, accurate to 10 decimal places. Stirling's formula is used for the central polynomial part of the procedure. Pike MC & Hill ID (1966) Algorithm 291: Logarithm of the gamma function. Communications of the Association for Computing Machinery, 9:684
def _ln_gamma_function(alpha): """Compute the log of the gamma function for a given alpha (PRIVATE). Comments from Z. Yang: Returns ln(gamma(alpha)) for alpha>0, accurate to 10 decimal places. Stirling's formula is used for the central polynomial part of the procedure. Pike MC & Hill ID (1966) Algorithm 291: Logarithm of the gamma function. Communications of the Association for Computing Machinery, 9:684 """ if alpha <= 0: raise ValueError x = alpha f = 0 if x < 7: f = 1 z = x while z < 7: f *= z z += 1 x = z f = -log(f) z = 1 / (x * x) return ( f + (x - 0.5) * log(x) - x + 0.918938533204673 + ( ((-0.000595238095238 * z + 0.000793650793651) * z - 0.002777777777778) * z + 0.083333333333333 ) / x )
Compute an incomplete gamma ratio (PRIVATE). Comments from Z. Yang:: Returns the incomplete gamma ratio I(x,alpha) where x is the upper limit of the integration and alpha is the shape parameter. returns (-1) if in error ln_gamma_alpha = ln(Gamma(alpha)), is almost redundant. (1) series expansion if alpha>x or x<=1 (2) continued fraction otherwise RATNEST FORTRAN by Bhattacharjee GP (1970) The incomplete gamma integral. Applied Statistics, 19: 285-287 (AS32)
def _incomplete_gamma(x, alpha): """Compute an incomplete gamma ratio (PRIVATE). Comments from Z. Yang:: Returns the incomplete gamma ratio I(x,alpha) where x is the upper limit of the integration and alpha is the shape parameter. returns (-1) if in error ln_gamma_alpha = ln(Gamma(alpha)), is almost redundant. (1) series expansion if alpha>x or x<=1 (2) continued fraction otherwise RATNEST FORTRAN by Bhattacharjee GP (1970) The incomplete gamma integral. Applied Statistics, 19: 285-287 (AS32) """ p = alpha g = _ln_gamma_function(alpha) accurate = 1e-8 overflow = 1e30 gin = 0 rn = 0 a = 0 b = 0 an = 0 dif = 0 term = 0 if x == 0: return 0 if x < 0 or p <= 0: return -1 factor = exp(p * log(x) - x - g) if x > 1 and x >= p: a = 1 - p b = a + x + 1 term = 0 pn = [1, x, x + 1, x * b, None, None] gin = pn[2] / pn[3] else: gin = 1 term = 1 rn = p while term > accurate: rn += 1 term *= x / rn gin += term gin *= factor / p return gin while True: a += 1 b += 2 term += 1 an = a * term for i in range(2): pn[i + 4] = b * pn[i + 2] - an * pn[i] if pn[5] != 0: rn = pn[4] / pn[5] dif = abs(gin - rn) if dif > accurate: gin = rn elif dif <= accurate * rn: break for i in range(4): pn[i] = pn[i + 2] if abs(pn[4]) < overflow: continue for i in range(4): pn[i] /= overflow gin = 1 - factor * gin return gin
Parse a CODEML results file.
def read(results_file): """Parse a CODEML results file.""" results = {} if not os.path.exists(results_file): raise FileNotFoundError("Results file does not exist.") with open(results_file) as handle: lines = handle.readlines() if not lines: raise ValueError( "Empty results file. Did CODEML exit successfully? " "Run 'Codeml.run()' with 'verbose=True'." ) (results, multi_models, multi_genes) = _parse_codeml.parse_basics(lines, results) results = _parse_codeml.parse_nssites(lines, results, multi_models, multi_genes) results = _parse_codeml.parse_pairwise(lines, results) results = _parse_codeml.parse_distances(lines, results) if not results: raise ValueError("Invalid results file") return results
Parse a yn00 results file.
def read(results_file): """Parse a yn00 results file.""" results = {} if not os.path.exists(results_file): raise FileNotFoundError("Results file does not exist.") with open(results_file) as handle: lines = handle.readlines() if not lines: raise ValueError( "Empty results file. Did YN00 exit successfully? " "Run 'Yn00.run()' with 'verbose=True'." ) for line_num, line in enumerate(lines): if "(A) Nei-Gojobori (1986) method" in line: ng86_start = line_num + 1 elif "(B) Yang & Nielsen (2000) method" in line: (results, sequences) = _parse_yn00.parse_ng86( lines[ng86_start:line_num], results ) yn00_start = line_num + 1 elif "(C) LWL85, LPB93 & LWLm methods" in line: results = _parse_yn00.parse_yn00( lines[yn00_start:line_num], results, sequences ) results = _parse_yn00.parse_others( lines[line_num + 1 :], results, sequences ) if not results: raise ValueError("Invalid results file.") return results
Parse the basics that should be present in most baseml results files.
def parse_basics(lines, results): """Parse the basics that should be present in most baseml results files.""" version_re = re.compile(r"BASEML \(in paml version (\d+\.\d+[a-z]*).*") np_re = re.compile(r"lnL\(ntime:\s+\d+\s+np:\s+(\d+)\)") num_params = -1 for line in lines: # Find all floating point numbers in this line line_floats_res = line_floats_re.findall(line) line_floats = [float(val) for val in line_floats_res] # Find the version number # Example match: # "BASEML (in paml version 4.3, August 2009) alignment.phylip" version_res = version_re.match(line) if version_res is not None: results["version"] = version_res.group(1) # Find max lnL # Example match: # ln Lmax (unconstrained) = -316.049385 if "ln Lmax" in line and len(line_floats) == 1: results["lnL max"] = line_floats[0] # Find lnL values. # Example match (lnL = -2021.348300): # "lnL(ntime: 19 np: 22): -2021.348300 +0.000000" elif "lnL(ntime:" in line and line_floats: results["lnL"] = line_floats[0] np_res = np_re.match(line) if np_res is not None: num_params = int(np_res.group(1)) # Find tree lengths. # Example match: "tree length = 1.71931" elif "tree length" in line and len(line_floats) == 1: results["tree length"] = line_floats[0] # Find the estimated tree, only taking the tree if it has # branch lengths elif re.match(r"\(+", line) is not None: if ":" in line: results["tree"] = line.strip() return (results, num_params)
Parse the various parameters from the file.
def parse_parameters(lines, results, num_params): """Parse the various parameters from the file.""" parameters = {} parameters = parse_parameter_list(lines, parameters, num_params) parameters = parse_kappas(lines, parameters) parameters = parse_rates(lines, parameters) parameters = parse_freqs(lines, parameters) results["parameters"] = parameters return results
Parse the parameters list, which is just an unlabeled list of numeric values.
def parse_parameter_list(lines, parameters, num_params): """Parse the parameters list, which is just an unlabeled list of numeric values.""" for line_num in range(len(lines)): line = lines[line_num] # Find all floating point numbers in this line line_floats_res = line_floats_re.findall(line) line_floats = [float(val) for val in line_floats_res] # Get parameter list. This can be useful for specifying starting # parameters in another run by copying the list of parameters # to a file called in.baseml. Since the parameters must be in # a fixed order and format, copying and pasting to the file is # best. For this reason, they are grabbed here just as a long # string and not as individual numbers. if len(line_floats) == num_params: parameters["parameter list"] = line.strip() # Find SEs. The same format as parameters above is maintained # since there is a correspondence between the SE format and # the parameter format. # Example match: # "SEs for parameters: # -1.00000 -1.00000 -1.00000 801727.63247 730462.67590 -1.00000 if "SEs for parameters:" in lines[line_num + 1]: SEs_line = lines[line_num + 2] parameters["SEs"] = SEs_line.strip() break return parameters
Parse out the kappa parameters.
def parse_kappas(lines, parameters): """Parse out the kappa parameters.""" kappa_found = False for line in lines: # Find all floating point numbers in this line line_floats_res = line_floats_re.findall(line) line_floats = [float(val) for val in line_floats_res] # Find kappa parameter (F84, HKY85, T92 model) # Example match: # "Parameters (kappa) in the rate matrix (F84) (Yang 1994 J Mol Evol 39:105-111): # 3.00749" if "Parameters (kappa)" in line: kappa_found = True elif kappa_found and line_floats: branch_res = re.match(r"\s(\d+\.\.\d+)", line) if branch_res is None: if len(line_floats) == 1: parameters["kappa"] = line_floats[0] else: parameters["kappa"] = line_floats kappa_found = False else: if parameters.get("branches") is None: parameters["branches"] = {} branch = branch_res.group(1) if line_floats: parameters["branches"][branch] = { "t": line_floats[0], "kappa": line_floats[1], "TS": line_floats[2], "TV": line_floats[3], } # Find kappa under REV # Example match: # kappa under REV: 999.00000 145.76453 0.00001 0.00001 0.00001 elif "kappa under" in line and line_floats: if len(line_floats) == 1: parameters["kappa"] = line_floats[0] else: parameters["kappa"] = line_floats return parameters
Parse the rate parameters.
def parse_rates(lines, parameters): """Parse the rate parameters.""" Q_mat_found = False trans_probs_found = False for line in lines: # Find all floating point numbers in this line line_floats_res = line_floats_re.findall(line) line_floats = [float(val) for val in line_floats_res] # Find rate parameters # Example match: # "Rate parameters: 999.00000 145.59775 0.00001 0.00001 0.00001" if "Rate parameters:" in line and line_floats: parameters["rate parameters"] = line_floats # Find rates # Example match: # "rate: 0.90121 0.96051 0.99831 1.03711 1.10287" elif "rate: " in line and line_floats: parameters["rates"] = line_floats # Find Rate matrix Q & average kappa (REV model) # Example match: # Rate matrix Q, Average Ts/Tv = 3.0308 # -2.483179 1.865730 0.617449 0.000000 # 2.298662 -2.298662 0.000000 0.000000 # 0.335015 0.000000 -0.338059 0.003044 # 0.000000 0.000000 0.004241 -0.004241 elif "matrix Q" in line: parameters["Q matrix"] = {"matrix": []} if line_floats: parameters["Q matrix"]["average Ts/Tv"] = line_floats[0] Q_mat_found = True elif Q_mat_found and line_floats: parameters["Q matrix"]["matrix"].append(line_floats) if len(parameters["Q matrix"]["matrix"]) == 4: Q_mat_found = False # Find alpha (gamma shape parameter for variable rates) # Example match: "alpha (gamma, K=5) = 192.47918" elif "alpha" in line and line_floats: parameters["alpha"] = line_floats[0] # Find rho for auto-discrete-gamma model elif "rho" in line and line_floats: parameters["rho"] = line_floats[0] elif "transition probabilities" in line: parameters["transition probs."] = [] trans_probs_found = True elif trans_probs_found and line_floats: parameters["transition probs."].append(line_floats) if len(parameters["transition probs."]) == len(parameters["rates"]): trans_probs_found = False return parameters
Parse the basepair frequencies.
def parse_freqs(lines, parameters): """Parse the basepair frequencies.""" root_re = re.compile(r"Note: node (\d+) is root.") branch_freqs_found = False base_freqs_found = False for line in lines: # Find all floating point numbers in this line line_floats_res = line_floats_re.findall(line) line_floats = [float(val) for val in line_floats_res] # Find base frequencies from baseml 4.3 # Example match: # "Base frequencies: 0.20090 0.16306 0.37027 0.26577" if "Base frequencies" in line and line_floats: base_frequencies = {} base_frequencies["T"] = line_floats[0] base_frequencies["C"] = line_floats[1] base_frequencies["A"] = line_floats[2] base_frequencies["G"] = line_floats[3] parameters["base frequencies"] = base_frequencies # Find base frequencies from baseml 4.1: # Example match: # "base frequency parameters # " 0.20317 0.16768 0.36813 0.26102" elif "base frequency parameters" in line: base_freqs_found = True # baseml 4.4 returns to having the base frequencies on the next line # but the heading changed elif "Base frequencies" in line and not line_floats: base_freqs_found = True elif base_freqs_found and line_floats: base_frequencies = {} base_frequencies["T"] = line_floats[0] base_frequencies["C"] = line_floats[1] base_frequencies["A"] = line_floats[2] base_frequencies["G"] = line_floats[3] parameters["base frequencies"] = base_frequencies base_freqs_found = False # Find frequencies # Example match: # "freq: 0.90121 0.96051 0.99831 1.03711 1.10287" elif "freq: " in line and line_floats: parameters["rate frequencies"] = line_floats # Find branch-specific frequency parameters # Example match (note: I think it's possible to have 4 more # values per line, enclosed in brackets, so I'll account for # this): # (frequency parameters for branches) [frequencies at nodes] (see Yang & Roberts 1995 fig 1) # # Node #1 ( 0.25824 0.24176 0.25824 0.24176 ) # Node #2 ( 0.00000 0.50000 0.00000 0.50000 ) elif "(frequency parameters for branches)" in line: parameters["nodes"] = {} branch_freqs_found = True elif branch_freqs_found: if line_floats: node_res = re.match(r"Node \#(\d+)", line) node_num = int(node_res.group(1)) node = {"root": False} node["frequency parameters"] = line_floats[:4] if len(line_floats) > 4: node["base frequencies"] = { "T": line_floats[4], "C": line_floats[5], "A": line_floats[6], "G": line_floats[7], } parameters["nodes"][node_num] = node else: root_res = root_re.match(line) if root_res is not None: root_node = int(root_res.group(1)) parameters["nodes"][root_node]["root"] = True branch_freqs_found = False return parameters
Parse the basic information that should be present in most codeml output files.
def parse_basics(lines, results): """Parse the basic information that should be present in most codeml output files.""" # multi_models is used to designate there being results for more than one # model in the file multi_models = False multi_genes = False version_re = re.compile(r".+ \(in paml version (\d+\.\d+[a-z]*).*") model_re = re.compile(r"Model:\s+(.+)") num_genes_re = re.compile(r"\(([0-9]+) genes: separate data\)") # In codeml 4.1, the codon substitution model is headed by: # "Codon frequencies:" # In codeml 4.3+ it is headed by: # "Codon frequency model:" codon_freq_re = re.compile(r"Codon frequenc[a-z\s]{3,7}:\s+(.+)") siteclass_re = re.compile(r"Site-class models:\s*([^\s]*)") for line in lines: # Find all floating point numbers in this line line_floats_res = line_floats_re.findall(line) line_floats = [float(val) for val in line_floats_res] # Get the program version number version_res = version_re.match(line) if version_res is not None: results["version"] = version_res.group(1) continue # Find the model description at the beginning of the file. model_res = model_re.match(line) if model_res is not None: results["model"] = model_res.group(1) # Find out if more than one genes are analyzed num_genes_res = num_genes_re.search(line) if num_genes_res is not None: results["genes"] = [] num_genes = int(num_genes_res.group(1)) for n in range(num_genes): results["genes"].append({}) multi_genes = True continue # Get the codon substitution model codon_freq_res = codon_freq_re.match(line) if codon_freq_res is not None: results["codon model"] = codon_freq_res.group(1) continue # Find the site-class model name at the beginning of the file. # This exists only if a NSsites class other than 0 is used. # If there's no site class model listed, then there are multiple # models in the results file # Example match: "Site-class models: PositiveSelection" siteclass_res = siteclass_re.match(line) if siteclass_res is not None: siteclass_model = siteclass_res.group(1) if siteclass_model != "": results["site-class model"] = siteclass_model multi_models = False else: multi_models = True # Get the maximum log-likelihood if "ln Lmax" in line and line_floats: results["lnL max"] = line_floats[0] return (results, multi_models, multi_genes)
Determine which NSsites models are present and parse them.
def parse_nssites(lines, results, multi_models, multi_genes): """Determine which NSsites models are present and parse them.""" ns_sites = {} model_re = re.compile(r"Model (\d+):\s+(.+)") gene_re = re.compile(r"Gene\s+([0-9]+)\s+.+") siteclass_model = results.get("site-class model") if not multi_models: # If there's only one model in the results, find out # which one it is and then parse it. if siteclass_model is None: siteclass_model = "one-ratio" current_model = { "one-ratio": 0, "NearlyNeutral": 1, "PositiveSelection": 2, "discrete": 3, "beta": 7, "beta&w>1": 8, "M2a_rel": 22, }[siteclass_model] if multi_genes: genes = results["genes"] current_gene = None gene_start = None model_results = None for line_num, line in enumerate(lines): gene_res = gene_re.match(line) if gene_res: if current_gene is not None: assert model_results is not None parse_model(lines[gene_start:line_num], model_results) genes[current_gene - 1] = model_results gene_start = line_num current_gene = int(gene_res.group(1)) model_results = {"description": siteclass_model} if len(genes[current_gene - 1]) == 0: model_results = parse_model(lines[gene_start:], model_results) genes[current_gene - 1] = model_results else: model_results = {"description": siteclass_model} model_results = parse_model(lines, model_results) ns_sites[current_model] = model_results else: # If there are multiple models in the results, scan through # the file and send each model's text to be parsed individually. current_model = None model_start = None for line_num, line in enumerate(lines): # Find model names. If this is found on a line, # all of the following lines until the next time this matches # contain results for Model X. # Example match: "Model 1: NearlyNeutral (2 categories)" model_res = model_re.match(line) if model_res: if current_model is not None: # We've already been tracking a model, so it's time # to send those lines off for parsing before beginning # a new one. parse_model(lines[model_start:line_num], model_results) ns_sites[current_model] = model_results model_start = line_num current_model = int(model_res.group(1)) model_results = {"description": model_res.group(2)} if ns_sites.get(current_model) is None: # When we reach the end of the file, we'll still have one more # model to parse. model_results = parse_model(lines[model_start:], model_results) ns_sites[current_model] = model_results # Only add the ns_sites dict to the results if we really have results. # Model M0 is added by default in some cases, so if it exists, make sure # it's not empty if len(ns_sites) == 1: m0 = ns_sites.get(0) if not m0 or len(m0) > 1: results["NSsites"] = ns_sites elif len(ns_sites) > 1: results["NSsites"] = ns_sites return results
Parse an individual NSsites model's results.
def parse_model(lines, results): """Parse an individual NSsites model's results.""" parameters = {} SEs_flag = False dS_tree_flag = False dN_tree_flag = False w_tree_flag = False num_params = None tree_re = re.compile(r"^\([\w #:',.()]*\);\s*$") branch_re = re.compile(r"\s+(\d+\.\.\d+)[\s+\d+\.\d+]+") model_params_re = re.compile(r"(?<!\S)([a-z]\d?)\s*=\s+(\d+\.\d+)") for line in lines: # Find all floating point numbers in this line line_floats_res = line_floats_re.findall(line) line_floats = [float(val) for val in line_floats_res] # Check if branch-specific results are in the line branch_res = branch_re.match(line) # Check if additional model parameters are in the line model_params = model_params_re.findall(line) # Find lnL values. # Example match (lnL = -2021.348300): # "lnL(ntime: 19 np: 22): -2021.348300 +0.000000" if "lnL(ntime:" in line and line_floats: results["lnL"] = line_floats[0] np_res = re.match(r"lnL\(ntime:\s+\d+\s+np:\s+(\d+)\)", line) if np_res is not None: num_params = int(np_res.group(1)) # Get parameter list. This can be useful for specifying starting # parameters in another run by copying the list of parameters # to a file called in.codeml. Since the parameters must be in # a fixed order and format, copying and pasting to the file is # best. For this reason, they are grabbed here just as a long # string and not as individual numbers. elif len(line_floats) == num_params and not SEs_flag: parameters["parameter list"] = line.strip() # Find SEs. The same format as parameters above is maintained # since there is a correspondence between the SE format and # the parameter format. # Example match: # "SEs for parameters: # -1.00000 -1.00000 -1.00000 801727.63247 730462.67590 -1.00000 elif "SEs for parameters:" in line: SEs_flag = True elif SEs_flag and len(line_floats) == num_params: parameters["SEs"] = line.strip() SEs_flag = False # Find tree lengths. # Example match: "tree length = 1.71931" elif "tree length =" in line and line_floats: results["tree length"] = line_floats[0] # Find the estimated trees only taking the tree if it has # lengths or rate estimates on the branches elif tree_re.match(line) is not None: if ":" in line or "#" in line: if dS_tree_flag: results["dS tree"] = line.strip() dS_tree_flag = False elif dN_tree_flag: results["dN tree"] = line.strip() dN_tree_flag = False elif w_tree_flag: results["omega tree"] = line.strip() w_tree_flag = False else: results["tree"] = line.strip() elif "dS tree:" in line: dS_tree_flag = True elif "dN tree:" in line: dN_tree_flag = True elif "w ratios as labels for TreeView:" in line: w_tree_flag = True # Find rates for multiple genes # Example match: "rates for 2 genes: 1 2.75551" elif "rates for" in line and line_floats: line_floats.insert(0, 1.0) parameters["rates"] = line_floats # Find kappa values. # Example match: "kappa (ts/tv) = 2.77541" elif "kappa (ts/tv)" in line and line_floats: parameters["kappa"] = line_floats[0] # Find omega values. # Example match: "omega (dN/dS) = 0.25122" elif "omega (dN/dS)" in line and line_floats: parameters["omega"] = line_floats[0] elif "w (dN/dS)" in line and line_floats: parameters["omega"] = line_floats # Find omega and kappa values for multi-gene files # Example match: "gene # 1: kappa = 1.72615 omega = 0.39333" elif "gene # " in line: gene_num = int(re.match(r"gene # (\d+)", line).group(1)) if parameters.get("genes") is None: parameters["genes"] = {} parameters["genes"][gene_num] = { "kappa": line_floats[0], "omega": line_floats[1], } # Find dN values. # Example match: "tree length for dN: 0.2990" elif "tree length for dN" in line and line_floats: parameters["dN"] = line_floats[0] # Find dS values # Example match: "tree length for dS: 1.1901" elif "tree length for dS" in line and line_floats: parameters["dS"] = line_floats[0] # Find site class distributions. # Example match 1 (normal model, 2 site classes): # "p: 0.77615 0.22385" # Example match 2 (branch site A model, 4 site classes): # "proportion 0.00000 0.00000 0.73921 0.26079" elif line[0:2] == "p:" or line[0:10] == "proportion": site_classes = parse_siteclass_proportions(line_floats) parameters["site classes"] = site_classes # Find the omega value corresponding to each site class # Example match (2 site classes): "w: 0.10224 1.00000" elif line[0:2] == "w:": site_classes = parameters.get("site classes") site_classes = parse_siteclass_omegas(line, site_classes) parameters["site classes"] = site_classes # Find the omega values corresponding to a branch type from # the clade model C for each site class # Example match: # "branch type 0: 0.31022 1.00000 0.00000" elif "branch type " in line: branch_type = re.match(r"branch type (\d)", line) if branch_type: site_classes = parameters.get("site classes") branch_type_no = int(branch_type.group(1)) site_classes = parse_clademodelc( branch_type_no, line_floats, site_classes ) parameters["site classes"] = site_classes # Find the omega values of the foreground branch for each site # class in the branch site A model # Example match: # "foreground w 0.07992 1.00000 134.54218 134.54218" elif line[0:12] == "foreground w": site_classes = parameters.get("site classes") site_classes = parse_branch_site_a(True, line_floats, site_classes) parameters["site classes"] = site_classes # Find the omega values of the background for each site # class in the branch site A model # Example match: # "background w 0.07992 1.00000 0.07992 1.00000" elif line[0:12] == "background w": site_classes = parameters.get("site classes") site_classes = parse_branch_site_a(False, line_floats, site_classes) parameters["site classes"] = site_classes # Find dN & dS for each branch, which is organized in a table # The possibility of NaNs forces me to not use the line_floats # method. # Example row (some spaces removed to make it smaller...). # " 6..7 0.000 167.7 54.3 0.0000 0.0000 0.0000 0.0 0.0" elif branch_res is not None and line_floats: branch = branch_res.group(1) if parameters.get("branches") is None: parameters["branches"] = {} params = line.strip().split()[1:] parameters["branches"][branch] = { "t": float(params[0].strip()), "N": float(params[1].strip()), "S": float(params[2].strip()), "omega": float(params[3].strip()), "dN": float(params[4].strip()), "dS": float(params[5].strip()), "N*dN": float(params[6].strip()), "S*dS": float(params[7].strip()), } # Find model parameters, which can be spread across multiple # lines. # Example matches: # " p0= 0.99043 p= 0.36657 q= 1.04445 # " (p1= 0.00957) w= 3.25530" elif model_params: float_model_params = [] for param in model_params: float_model_params.append((param[0], float(param[1]))) parameters.update(dict(float_model_params)) if parameters: results["parameters"] = parameters return results
Find proportion of alignment assigned to each class. For models which have multiple site classes, find the proportion of the alignment assigned to each class.
def parse_siteclass_proportions(line_floats): """Find proportion of alignment assigned to each class. For models which have multiple site classes, find the proportion of the alignment assigned to each class. """ site_classes = {} if line_floats: for n in range(len(line_floats)): site_classes[n] = {"proportion": line_floats[n]} return site_classes
Find omega estimate for each class. For models which have multiple site classes, find the omega estimated for each class.
def parse_siteclass_omegas(line, site_classes): """Find omega estimate for each class. For models which have multiple site classes, find the omega estimated for each class. """ # The omega results are tabular with strictly 9 characters per column # (1 to 3 digits before the decimal point and 5 after). This causes # numbers to sometimes run into each other, so we must use a different # regular expression to account for this. i.e.: # w: 0.00012 1.00000109.87121 line_floats = re.findall(r"\d{1,3}\.\d{5}", line) if not site_classes or len(line_floats) == 0: return for n in range(len(line_floats)): site_classes[n]["omega"] = line_floats[n] return site_classes
Parse results specific to the clade model C.
def parse_clademodelc(branch_type_no, line_floats, site_classes): """Parse results specific to the clade model C.""" if not site_classes or len(line_floats) == 0: return for n in range(len(line_floats)): if site_classes[n].get("branch types") is None: site_classes[n]["branch types"] = {} site_classes[n]["branch types"][branch_type_no] = line_floats[n] return site_classes
Parse results specific to the branch site A model.
def parse_branch_site_a(foreground, line_floats, site_classes): """Parse results specific to the branch site A model.""" if not site_classes or len(line_floats) == 0: return for n in range(len(line_floats)): if site_classes[n].get("branch types") is None: site_classes[n]["branch types"] = {} if foreground: site_classes[n]["branch types"]["foreground"] = line_floats[n] else: site_classes[n]["branch types"]["background"] = line_floats[n] return site_classes
Parse results from pairwise comparisons.
def parse_pairwise(lines, results): """Parse results from pairwise comparisons.""" # Find pairwise comparisons # Example: # 2 (Pan_troglo) ... 1 (Homo_sapie) # lnL = -291.465693 # 0.01262 999.00000 0.00100 # # t= 0.0126 S= 81.4 N= 140.6 dN/dS= 0.0010 dN= 0.0000 dS= 0.0115 pair_re = re.compile(r"\d+ \((.+)\) ... \d+ \((.+)\)") pairwise = {} seq1 = None seq2 = None for line in lines: # Find all floating point numbers in this line line_floats_res = line_floats_re.findall(line) line_floats = [float(val) for val in line_floats_res] pair_res = pair_re.match(line) if pair_res: seq1 = pair_res.group(1) seq2 = pair_res.group(2) if seq1 not in pairwise: pairwise[seq1] = {} if seq2 not in pairwise: pairwise[seq2] = {} if len(line_floats) == 1 and seq1 is not None and seq2 is not None: pairwise[seq1][seq2] = {"lnL": line_floats[0]} pairwise[seq2][seq1] = pairwise[seq1][seq2] elif len(line_floats) == 6 and seq1 is not None and seq2 is not None: pairwise[seq1][seq2].update( { "t": line_floats[0], "S": line_floats[1], "N": line_floats[2], "omega": line_floats[3], "dN": line_floats[4], "dS": line_floats[5], } ) pairwise[seq2][seq1] = pairwise[seq1][seq2] if pairwise: results["pairwise"] = pairwise return results
Parse amino acid sequence distance results.
def parse_distances(lines, results): """Parse amino acid sequence distance results.""" distances = {} sequences = [] raw_aa_distances_flag = False ml_aa_distances_flag = False matrix_row_re = re.compile(r"(.+)\s{5,15}") for line in lines: # Find all floating point numbers in this line line_floats_res = line_floats_re.findall(line) line_floats = [float(val) for val in line_floats_res] if "AA distances" in line: raw_aa_distances_flag = True # In current versions, the raw distances always come # first but I don't trust this to always be true ml_aa_distances_flag = False elif "ML distances of aa seqs." in line: ml_aa_distances_flag = True raw_aa_distances_flag = False # Parse AA distances (raw or ML), in a lower diagonal matrix matrix_row_res = matrix_row_re.match(line) if matrix_row_res and (raw_aa_distances_flag or ml_aa_distances_flag): seq_name = matrix_row_res.group(1).strip() if seq_name not in sequences: sequences.append(seq_name) if raw_aa_distances_flag: if distances.get("raw") is None: distances["raw"] = {} distances["raw"][seq_name] = {} for i in range(len(line_floats)): distances["raw"][seq_name][sequences[i]] = line_floats[i] distances["raw"][sequences[i]][seq_name] = line_floats[i] else: if distances.get("ml") is None: distances["ml"] = {} distances["ml"][seq_name] = {} for i in range(len(line_floats)): distances["ml"][seq_name][sequences[i]] = line_floats[i] distances["ml"][sequences[i]][seq_name] = line_floats[i] if distances: results["distances"] = distances return results
Parse the Nei & Gojobori (1986) section of the results. Nei_Gojobori results are organized in a lower triangular matrix, with the sequence names labeling the rows and statistics in the format: w (dN dS) per column Example row (2 columns): 0.0000 (0.0000 0.0207) 0.0000 (0.0000 0.0421)
def parse_ng86(lines, results): """Parse the Nei & Gojobori (1986) section of the results. Nei_Gojobori results are organized in a lower triangular matrix, with the sequence names labeling the rows and statistics in the format: w (dN dS) per column Example row (2 columns): 0.0000 (0.0000 0.0207) 0.0000 (0.0000 0.0421) """ sequences = [] for line in lines: # The purpose of this complex regex is to parse the NG86 section for # valid lines of data that are mixed in with citations and comments. # The data lines begin with a taxon name, followed by zero or more # fields containing numeric values, sometimes enclosed in parens. # Taxon names are from 1-30 characters and are usually separated from # the numeric portion of the line by space(s). Long taxon names to are # truncated to 30 characters, and may run into the data fields without # any separator., e.g. some_long_name-1.0000 # This regex is an attempt to cover more pathological cases while also # parsing all existing versions of yn00 output with shorter names. matrix_row_res = re.match( r"^([^\s]+?)(\s+-?\d+\.\d+.*$|\s*$|-1.0000\s*\(.*$)", line ) if matrix_row_res is not None: # Find all floating point numbers in this line, accounting # for the fact that the sequence IDs might have bits that # look like floating point values. line_floats_res = re.findall(r"-*\d+\.\d+", matrix_row_res.group(2)) line_floats = [float(val) for val in line_floats_res] seq_name = matrix_row_res.group(1).strip() sequences.append(seq_name) results[seq_name] = {} for i in range(0, len(line_floats), 3): NG86 = {} NG86["omega"] = line_floats[i] NG86["dN"] = line_floats[i + 1] NG86["dS"] = line_floats[i + 2] results[seq_name][sequences[i // 3]] = {"NG86": NG86} results[sequences[i // 3]][seq_name] = {"NG86": NG86} return (results, sequences)
Parse the Yang & Nielsen (2000) part of the results. Yang & Nielsen results are organized in a table with each row comprising one pairwise species comparison. Rows are labeled by sequence number rather than by sequence name.
def parse_yn00(lines, results, sequences): """Parse the Yang & Nielsen (2000) part of the results. Yang & Nielsen results are organized in a table with each row comprising one pairwise species comparison. Rows are labeled by sequence number rather than by sequence name. """ # Example (header row and first table row): # seq. seq. S N t kappa omega dN +- SE dS +- SE # 2 1 67.3 154.7 0.0136 3.6564 0.0000 -0.0000 +- 0.0000 0.0150 # +- 0.0151 for line in lines: # Find all floating point numbers in this line line_floats_res = re.findall(r"-*\d+\.\d+", line) line_floats = [float(val) for val in line_floats_res] row_res = re.match(r"\s+(\d+)\s+(\d+)", line) if row_res is not None: seq1 = int(row_res.group(1)) seq2 = int(row_res.group(2)) seq_name1 = sequences[seq1 - 1] seq_name2 = sequences[seq2 - 1] YN00 = {} YN00["S"] = line_floats[0] YN00["N"] = line_floats[1] YN00["t"] = line_floats[2] YN00["kappa"] = line_floats[3] YN00["omega"] = line_floats[4] YN00["dN"] = line_floats[5] YN00["dN SE"] = line_floats[6] YN00["dS"] = line_floats[7] YN00["dS SE"] = line_floats[8] results[seq_name1][seq_name2]["YN00"] = YN00 results[seq_name2][seq_name1]["YN00"] = YN00 seq_name1 = None seq_name2 = None return results
Parse the results from the other methods. The remaining methods are grouped together. Statistics for all three are listed for each of the pairwise species comparisons, with each method's results on its own line. The stats in this section must be handled differently due to the possible presence of NaN values, which won't get caught by my typical "line_floats" method used above.
def parse_others(lines, results, sequences): """Parse the results from the other methods. The remaining methods are grouped together. Statistics for all three are listed for each of the pairwise species comparisons, with each method's results on its own line. The stats in this section must be handled differently due to the possible presence of NaN values, which won't get caught by my typical "line_floats" method used above. """ # Example: # 2 (Pan_troglo) vs. 1 (Homo_sapie) # L(i): 143.0 51.0 28.0 sum= 222.0 # Ns(i): 0.0000 1.0000 0.0000 sum= 1.0000 # Nv(i): 0.0000 0.0000 0.0000 sum= 0.0000 # A(i): 0.0000 0.0200 0.0000 # B(i): -0.0000 -0.0000 -0.0000 # LWL85: dS = 0.0227 dN = 0.0000 w = 0.0000 S = 45.0 N = 177.0 # LWL85m: dS = -nan dN = -nan w = -nan S = -nan N = -nan (rho = -nan) # LPB93: dS = 0.0129 dN = 0.0000 w = 0.0000 seq_name1 = None seq_name2 = None for line in lines: comp_res = re.match(r"\d+ \((.+)\) vs. \d+ \((.+)\)", line) if comp_res is not None: seq_name1 = comp_res.group(1) seq_name2 = comp_res.group(2) elif seq_name1 is not None and seq_name2 is not None: if "dS =" in line: stats = {} line_stats = line.split(":")[1].strip() # Find all of the xx = ###### values in a row # ie dS = 0.0227 # For dN and dS, the values have 8 characters from the equals # sign, while the rest have 7 characters. On Windows, # NaNs take on weird values like -1.#IND, which might fill the # entire fixed column width. res_matches = re.findall(r"[dSNwrho]{1,3} =.{7,8}?", line_stats) for stat_pair in res_matches: stat = stat_pair.split("=")[0].strip() value = stat_pair.split("=")[1].strip() try: stats[stat] = float(value) except ValueError: stats[stat] = None if "LWL85:" in line: results[seq_name1][seq_name2]["LWL85"] = stats results[seq_name2][seq_name1]["LWL85"] = stats elif "LWL85m" in line: results[seq_name1][seq_name2]["LWL85m"] = stats results[seq_name2][seq_name1]["LWL85m"] = stats elif "LPB93" in line: results[seq_name1][seq_name2]["LPB93"] = stats results[seq_name2][seq_name1]["LPB93"] = stats return results
Get a float from a token, if it fails, returns the string (PRIVATE).
def _gp_float(tok): """Get a float from a token, if it fails, returns the string (PRIVATE).""" try: return float(tok) except ValueError: return str(tok)
Get a int from a token, if it fails, returns the string (PRIVATE).
def _gp_int(tok): """Get a int from a token, if it fails, returns the string (PRIVATE).""" try: return int(tok) except ValueError: return str(tok)
Parse a file containing a GenePop file. fname is a file name that contains a GenePop record.
def read(fname): """Parse a file containing a GenePop file. fname is a file name that contains a GenePop record. """ record = FileRecord(fname) return record
Get individual's data from line.
def get_indiv(line): """Get individual's data from line.""" indiv_name, marker_line = line.split(",") markers = marker_line.replace("\t", " ").split(" ") markers = [marker for marker in markers if marker != ""] if len(markers[0]) in [2, 4]: # 2 digits per allele marker_len = 2 else: marker_len = 3 try: allele_list = [ (int(marker[0:marker_len]), int(marker[marker_len:])) for marker in markers ] except ValueError: # Haploid allele_list = [(int(marker[0:marker_len]),) for marker in markers] return indiv_name, allele_list, marker_len
Parse a handle containing a GenePop file. Arguments: - handle is a file-like object that contains a GenePop record.
def read(handle): """Parse a handle containing a GenePop file. Arguments: - handle is a file-like object that contains a GenePop record. """ record = Record(handle) record.comment_line = next(handle).rstrip() # We can now have one loci per line or all loci in a single line # separated by either space or comma+space... # We will remove all commas on loci... that should not be a problem sample_loci_line = next(handle).rstrip().replace(",", "") all_loci = sample_loci_line.split(" ") record.loci_list.extend(all_loci) line = handle.readline() while line != "": line = line.rstrip() if line.upper() == "POP": record.stack.append("POP") break record.loci_list.append(line) line = handle.readline() next_line = handle.readline().rstrip() indiv_name, allele_list, record.marker_len = get_indiv(next_line) record.stack.append(next_line) return record
Extract the details of the individual information on the line.
def get_indiv(line): """Extract the details of the individual information on the line.""" def int_no_zero(val): """Return integer of val, or None if is zero.""" v = int(val) if v == 0: return None return v indiv_name, marker_line = line.split(",") markers = marker_line.replace("\t", " ").split(" ") markers = [marker for marker in markers if marker != ""] if len(markers[0]) in [2, 4]: # 2 digits per allele marker_len = 2 else: marker_len = 3 try: allele_list = [ (int_no_zero(marker[0:marker_len]), int_no_zero(marker[marker_len:])) for marker in markers ] except ValueError: # Haploid allele_list = [(int_no_zero(marker[0:marker_len]),) for marker in markers] return indiv_name, allele_list, marker_len
Parse a handle containing a GenePop file. handle is a file-like object that contains a GenePop record.
def read(handle): """Parse a handle containing a GenePop file. handle is a file-like object that contains a GenePop record. """ record = Record() record.comment_line = next(handle).rstrip() # We can now have one loci per line or all loci in a single line # separated by either space or comma+space... # We will remove all commas on loci... that should not be a problem sample_loci_line = next(handle).rstrip().replace(",", "") all_loci = sample_loci_line.split(" ") record.loci_list.extend(all_loci) for line in handle: line = line.rstrip() if line.upper() == "POP": break record.loci_list.append(line) else: raise ValueError("No population data found, file probably not GenePop related") record.populations.append([]) for line in handle: line = line.rstrip() if line.upper() == "POP": record.populations.append([]) else: indiv_name, allele_list, record.marker_len = get_indiv(line) record.populations[-1].append((indiv_name, allele_list)) loci = record.loci_list for pop in record.populations: record.pop_list.append(pop[-1][0]) for indiv in pop: for mk_i in range(len(loci)): mk_orig = indiv[1][mk_i] mk_real = [] for al in mk_orig: if al == 0: mk_real.append(None) else: mk_real.append(al) indiv[1][mk_i] = tuple(mk_real) return record
Iterate over a CLA file as Cla records for each line. Arguments: - handle - file-like object.
def parse(handle): """Iterate over a CLA file as Cla records for each line. Arguments: - handle - file-like object. """ for line in handle: if line.startswith("#"): continue yield Record(line)
Iterate over a DES file as a Des record for each line. Arguments: - handle - file-like object
def parse(handle): """Iterate over a DES file as a Des record for each line. Arguments: - handle - file-like object """ for line in handle: if line.startswith("#"): continue yield Record(line)
Iterate over a DOM file as a Dom record for each line. Arguments: - handle -- file-like object.
def parse(handle): """Iterate over a DOM file as a Dom record for each line. Arguments: - handle -- file-like object. """ for line in handle: if line.startswith("#"): continue yield Record(line)
Iterate over a HIE file as Hie records for each line. Arguments: - handle - file-like object.
def parse(handle): """Iterate over a HIE file as Hie records for each line. Arguments: - handle - file-like object. """ for line in handle: if line.startswith("#"): continue yield Record(line)
Convert RAF one-letter amino acid codes into IUPAC standard codes. Letters are uppercased, and "." ("Unknown") is converted to "X".
def normalize_letters(one_letter_code): """Convert RAF one-letter amino acid codes into IUPAC standard codes. Letters are uppercased, and "." ("Unknown") is converted to "X". """ if one_letter_code == ".": return "X" else: return one_letter_code.upper()
Iterate over RAF file, giving a SeqMap object for each line. Arguments: - handle -- file-like object.
def parse(handle): """Iterate over RAF file, giving a SeqMap object for each line. Arguments: - handle -- file-like object. """ for line in handle: yield SeqMap(line)