Back to index

python-biopython  1.60
Classes | Functions | Variables
Bio.Phylo.BaseTree Namespace Reference

Classes

class  TreeElement
class  TreeMixin
class  Tree
class  Clade
class  BranchColor

Functions

def _level_traverse
def _preorder_traverse
def _postorder_traverse
def _sorted_attrs
def _identity_matcher
def _class_matcher
def _string_matcher
def _attribute_matcher
def _function_matcher
def _object_matcher
def _combine_matchers
def _combine_args

Variables

string __docformat__ = "restructuredtext en"

Function Documentation

def Bio.Phylo.BaseTree._attribute_matcher (   kwargs) [private]
Match a node by specified attribute values.

``terminal`` is a special case: True restricts the search to external (leaf)
nodes, False restricts to internal nodes, and None allows all tree elements
to be searched, including phyloXML annotations.

Otherwise, for a tree element to match the specification (i.e. for the
function produced by `_attribute_matcher` to return True when given a tree
element), it must have each of the attributes specified by the keys and
match each of the corresponding values -- think 'and', not 'or', for
multiple keys.

Definition at line 88 of file BaseTree.py.

00088 
00089 def _attribute_matcher(kwargs):
00090     """Match a node by specified attribute values.
00091 
00092     ``terminal`` is a special case: True restricts the search to external (leaf)
00093     nodes, False restricts to internal nodes, and None allows all tree elements
00094     to be searched, including phyloXML annotations.
00095 
00096     Otherwise, for a tree element to match the specification (i.e. for the
00097     function produced by `_attribute_matcher` to return True when given a tree
00098     element), it must have each of the attributes specified by the keys and
00099     match each of the corresponding values -- think 'and', not 'or', for
00100     multiple keys.
00101     """
00102     def match(node):
00103         if 'terminal' in kwargs:
00104             # Special case: restrict to internal/external/any nodes
00105             kwa_copy = kwargs.copy()
00106             pattern = kwa_copy.pop('terminal')
00107             if (pattern is not None and
00108                 (not hasattr(node, 'is_terminal') or
00109                     node.is_terminal() != pattern)):
00110                 return False
00111         else:
00112             kwa_copy = kwargs
00113         for key, pattern in kwa_copy.iteritems():
00114             # Nodes must match all other specified attributes
00115             if not hasattr(node, key):
00116                 return False
00117             target = getattr(node, key)
00118             if isinstance(pattern, basestring):
00119                 return (isinstance(target, basestring) and
00120                         re.match(pattern+'$', target))
00121             if isinstance(pattern, bool):
00122                 return (pattern == bool(target))
00123             if isinstance(pattern, int):
00124                 return (pattern == target)
00125             if pattern is None:
00126                 return (target is None)
00127             raise TypeError('invalid query type: %s' % type(pattern))
00128         return True
00129     return match

Here is the call graph for this function:

Here is the caller graph for this function:

def Bio.Phylo.BaseTree._class_matcher (   target_cls) [private]
Match a node if it's an instance of the given class.

Definition at line 77 of file BaseTree.py.

00077 
00078 def _class_matcher(target_cls):
00079     """Match a node if it's an instance of the given class."""
00080     def match(node):
00081         return isinstance(node, target_cls)
00082     return match

Here is the call graph for this function:

Here is the caller graph for this function:

def Bio.Phylo.BaseTree._combine_args (   first,
  rest 
) [private]
Convert ``[targets]`` or ``*targets`` arguments to a single iterable.

This helps other functions work like the built-in functions `max` and
`min`.

Definition at line 186 of file BaseTree.py.

00186 
00187 def _combine_args(first, *rest):
00188     """Convert ``[targets]`` or ``*targets`` arguments to a single iterable.
00189 
00190     This helps other functions work like the built-in functions `max` and
00191     `min`.
00192     """
00193     # Background: is_monophyletic takes a single list or iterable (like the
00194     # same method in Bio.Nexus.Trees); root_with_outgroup and common_ancestor
00195     # take separate arguments. This mismatch was in the initial release and I
00196     # didn't notice the inconsistency until after Biopython 1.55. I can think
00197     # of cases where either style is more convenient, so let's support both
00198     # (for backward compatibility and consistency between methods).
00199     if hasattr(first, '__iter__') and not (isinstance(first, TreeElement) or
00200             isinstance(first, type) or isinstance(first, basestring) or
00201             isinstance(first, dict)):
00202         # `terminals` is an iterable of targets
00203         if rest:
00204             raise ValueError("Arguments must be either a single list of "
00205                     "targets, or separately specified targets "
00206                     "(e.g. foo(t1, t2, t3)), but not both.")
00207         return first
00208     # `terminals` is a single target -- wrap in a container
00209     return itertools.chain([first], rest)
00210 
00211 
00212 # Class definitions

Here is the caller graph for this function:

def Bio.Phylo.BaseTree._combine_matchers (   target,
  kwargs,
  require_spec 
) [private]
Merge target specifications with keyword arguments.

Dispatch the components to the various matcher functions, then merge into a
single boolean function.

Definition at line 166 of file BaseTree.py.

00166 
00167 def _combine_matchers(target, kwargs, require_spec):
00168     """Merge target specifications with keyword arguments.
00169 
00170     Dispatch the components to the various matcher functions, then merge into a
00171     single boolean function.
00172     """
00173     if not target:
00174         if not kwargs:
00175             if require_spec:
00176                 raise ValueError("you must specify a target object or keyword "
00177                                 "arguments.")
00178             return lambda x: True
00179         return _attribute_matcher(kwargs)
00180     match_obj = _object_matcher(target)
00181     if not kwargs:
00182         return match_obj
00183     match_kwargs = _attribute_matcher(kwargs)
00184     return (lambda x: match_obj(x) and match_kwargs(x))
00185 

Here is the call graph for this function:

Here is the caller graph for this function:

def Bio.Phylo.BaseTree._function_matcher (   matcher_func) [private]
Safer attribute lookup -- returns False instead of raising an error.

Definition at line 130 of file BaseTree.py.

00130 
00131 def _function_matcher(matcher_func):
00132     """Safer attribute lookup -- returns False instead of raising an error."""
00133     def match(node):
00134         try:
00135             return matcher_func(node)
00136         except (LookupError, AttributeError, ValueError, TypeError):
00137             return False
00138     return match

Here is the call graph for this function:

Here is the caller graph for this function:

def Bio.Phylo.BaseTree._identity_matcher (   target) [private]
Match a node to the target object by identity.

Definition at line 71 of file BaseTree.py.

00071 
00072 def _identity_matcher(target):
00073     """Match a node to the target object by identity."""
00074     def match(node):
00075         return (node is target)
00076     return match

Here is the call graph for this function:

Here is the caller graph for this function:

def Bio.Phylo.BaseTree._level_traverse (   root,
  get_children 
) [private]
Traverse a tree in breadth-first (level) order.

Definition at line 23 of file BaseTree.py.

00023 
00024 def _level_traverse(root, get_children):
00025     """Traverse a tree in breadth-first (level) order."""
00026     Q = collections.deque([root])
00027     while Q:
00028         v = Q.popleft()
00029         yield v
00030         Q.extend(get_children(v))

def Bio.Phylo.BaseTree._object_matcher (   obj) [private]
Retrieve a matcher function by passing an arbitrary object.

i.e. 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.

Definition at line 139 of file BaseTree.py.

00139 
00140 def _object_matcher(obj):
00141     """Retrieve a matcher function by passing an arbitrary object.
00142 
00143     i.e. passing a `TreeElement` such as a `Clade` or `Tree` instance returns an
00144     identity matcher, passing a type such as the `PhyloXML.Taxonomy` class
00145     returns a class matcher, and passing a dictionary returns an attribute
00146     matcher.
00147 
00148     The resulting 'match' function returns True when given an object matching
00149     the specification (identity, type or attribute values), otherwise False.
00150     This is useful for writing functions that search the tree, and probably
00151     shouldn't be used directly by the end user.
00152     """
00153     if isinstance(obj, TreeElement):
00154         return _identity_matcher(obj)
00155     if isinstance(obj, type):
00156         return _class_matcher(obj)
00157     if isinstance(obj, basestring):
00158         return _string_matcher(obj)
00159     if isinstance(obj, dict):
00160         return _attribute_matcher(obj)
00161     if callable(obj):
00162         return _function_matcher(obj)
00163     raise ValueError("%s (type %s) is not a valid type for comparison."
00164                      % (obj, type(obj)))
00165 

Here is the call graph for this function:

Here is the caller graph for this function:

def Bio.Phylo.BaseTree._postorder_traverse (   root,
  get_children 
) [private]
Traverse a tree in depth-first post-order (children before parent).

Definition at line 41 of file BaseTree.py.

00041 
00042 def _postorder_traverse(root, get_children):
00043     """Traverse a tree in depth-first post-order (children before parent)."""
00044     def dfs(elem):
00045         for v in get_children(elem):
00046             for u in dfs(v):
00047                 yield u
00048         yield elem
00049     for elem in dfs(root):
00050         yield elem
00051 

def Bio.Phylo.BaseTree._preorder_traverse (   root,
  get_children 
) [private]
Traverse a tree in depth-first pre-order (parent before children).

Definition at line 31 of file BaseTree.py.

00031 
00032 def _preorder_traverse(root, get_children):
00033     """Traverse a tree in depth-first pre-order (parent before children)."""
00034     def dfs(elem):
00035         yield elem
00036         for v in get_children(elem):
00037             for u in dfs(v):
00038                 yield u
00039     for elem in dfs(root):
00040         yield elem

def Bio.Phylo.BaseTree._sorted_attrs (   elem) [private]
Get a flat list of elem's attributes, sorted for consistency.

Definition at line 52 of file BaseTree.py.

00052 
00053 def _sorted_attrs(elem):
00054     """Get a flat list of elem's attributes, sorted for consistency."""
00055     singles = []
00056     lists = []
00057     # Sort attributes for consistent results
00058     for attrname, child in sorted(elem.__dict__.iteritems(),
00059                                   key=lambda kv: kv[0]):
00060         if child is None:
00061             continue
00062         if isinstance(child, list):
00063             lists.extend(child)
00064         else:
00065             singles.append(child)
00066     return (x for x in singles + lists
00067             if isinstance(x, TreeElement))
00068 
00069 
00070 # Factory functions to generalize searching for clades/nodes

def Bio.Phylo.BaseTree._string_matcher (   target) [private]

Definition at line 83 of file BaseTree.py.

00083 
00084 def _string_matcher(target):
00085     def match(node):
00086         return unicode(node) == target
00087     return match

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

string Bio.Phylo.BaseTree.__docformat__ = "restructuredtext en"

Definition at line 11 of file BaseTree.py.