ivy package¶
Subpackages¶
- ivy.chars package- Subpackages
- Submodules
- ivy.chars.bayesian_models module
- ivy.chars.catpars module
- ivy.chars.discrete module
- ivy.chars.evolve module
- ivy.chars.hrm module
- ivy.chars.hrm_bayesian module
- ivy.chars.mk module
- ivy.chars.mk_mr module
- ivy.chars.recon module
- Module contents
 
- ivy.sim package
- ivy.vis package
Submodules¶
ivy.ages module¶
Calculate node ages from branch lengths.
The function of interest is ages2lengths
- 
ivy.ages.ages2lengths(node, node_ages, results={})[source]¶
- Convert node ages to branch lengths - Parameters: - Returns: - mapping of nodes to lengths - Return type: 
ivy.align module¶
ivy.ascii module¶
ivy.autocollapse module¶
For drawing big trees. Calculate which clades can be ‘collapsed’ and displayed with a placeholder.
TODO: test and develop this module further
- 
ivy.autocollapse.autocollapse(root, collapsed=None, keep_visible=None, max_visible=1000)[source]¶
- traverse a tree and find nodes that should be collapsed in order to satify max_visible - collapsed is a set object for storing collapsed nodes - keep_visible is a set object of nodes that should not be placed in collapsed 
ivy.bipart module¶
ivy.birthdeath module¶
Equations from Magallon and Sanderson 2001
- 
ivy.birthdeath.Alpha(epsilon, r, t)[source]¶
- Calculate Alpha - Parameters: - Returns: - Alpha - Return type: - Float 
- 
ivy.birthdeath.Beta(epsilon, r, t)[source]¶
- Calculate Beta - Parameters: - Returns: - Beta - Return type: - Float 
- 
ivy.birthdeath.Kendall1948(i, t, r, epsilon)[source]¶
- Probability of observing i species given single ancestor after time t - Parameters: 
- 
ivy.birthdeath.Nbar(t, a, r, epsilon)[source]¶
- Mean clade size conditional on survival of the clade - Parameters: 
- 
ivy.birthdeath.condKendall1948(i, t, r, epsilon)[source]¶
- Probability of observing i species given a single ancestor after time t conditional on the clade surviving to time t - Parameters: 
- 
ivy.birthdeath.condPrN(i, t, a, r, epsilon)[source]¶
- Conditional probability of i species after time t, given the probability of survival - Parameters: 
ivy.contrasts module¶
Calculate independent contrasts
TODO: include utilities for transforming data, etc.
- 
ivy.contrasts.PIC(node, data, results=None)[source]¶
- Phylogenetic independent contrasts. - Recursively calculate independent contrasts of a bifurcating node given a dictionary of trait values. - Parameters: - Returns: - Mapping of internal nodes to tuples containing ancestral
- state, its variance (error), the contrast, and the contrasts’s variance. 
 - Return type: - TODO: modify to accommodate polytomies. 
ivy.data module¶
- 
class ivy.data.Rows(array=None, k=None, v=None)[source]¶
- Bases: - object- A helper class for associating row-based data with nodes. Implements a dictionary-like interface that allows lookups by, e.g., d[node] or d[‘Pongo’]. - k is a function that returns the key from a row - v is a function that returns the value from a row 
ivy.demo module¶
- 
class ivy.demo.Demo(src, title=u'', arg_str=u'', auto_all=None)[source]¶
- Bases: - IPython.lib.demo.ClearIPDemo
- 
ivy.demo.random() → x in the interval [0, 1).¶
ivy.examples module¶
ivy.genbank module¶
- 
ivy.genbank.batch(iterable, size)[source]¶
- Take an iterable and return it in chunks (sub-iterables) - Parameters: - iterable – Any iterable
- size (int) – Size of chunks
 - Yields: - Chunks of size size 
- 
ivy.genbank.extract_gbac(s)[source]¶
- Extract genbank accession - Parameters: - s (str) – text string of genbank file - Returns: - Accession number(s) - Return type: - list 
ivy.interactive module¶
Adds to the interactive IPython/pylab environment
ivy.ivy_completers module¶
ivy.layout module¶
layout nodes in 2d space
The function of interest is calc_node_positions (aka nodepos)
- 
ivy.layout.calc_node_positions(node, width, height, lpad=0, rpad=0, tpad=0, bpad=0, scaled=True, smooth=True, n2coords=None)[source]¶
- Calculate where nodes should be positioned in 2d space for drawing a tree - Parameters: - node (Node) – A (root) node
- width (float) – The width of the canvas
- height (float) – The height of the canvas
- rpad, tpad, bpad (lpad,) – Padding on the edges of the canvas. Optional, defaults to 0.
- scaled (bool) – Whether or not the tree is scaled. Optional, defaults to True.
- smooth (bool) – Whether or not to smooth the tree. Optional, defaults to True.
 - Returns: - Mapping of nodes to Coordinates object - Return type: - Notes - Origin is at upper left 
- 
ivy.layout.cartesian(node, xscale=1.0, leafspace=None, scaled=True, n2coords=None, smooth=0, array=<built-in function array>, ones=<function ones>, yunit=None)[source]¶
- RR: What is the difference between this function and calc_node_positions?
- Is it being used anywhere? -CZ
 
- 
ivy.layout.depth_length_preorder_traversal(node, n2coords=None, isroot=False)[source]¶
- Calculate node depth (root = depth 0) and length to root - Parameters: - node (Node) – A node object - Returns: - Mapping of nodes to coordinate objects. Coordinate
- objects have attributes “depth” and “length_to_root”
 - Return type: - dict 
- 
ivy.layout.nodepos(node, width, height, lpad=0, rpad=0, tpad=0, bpad=0, scaled=True, smooth=True, n2coords=None)¶
- Calculate where nodes should be positioned in 2d space for drawing a tree - Parameters: - node (Node) – A (root) node
- width (float) – The width of the canvas
- height (float) – The height of the canvas
- rpad, tpad, bpad (lpad,) – Padding on the edges of the canvas. Optional, defaults to 0.
- scaled (bool) – Whether or not the tree is scaled. Optional, defaults to True.
- smooth (bool) – Whether or not to smooth the tree. Optional, defaults to True.
 - Returns: - Mapping of nodes to Coordinates object - Return type: - Notes - Origin is at upper left 
ivy.layout_polar module¶
- 
ivy.layout_polar.calc_node_positions(node, radius=1.0, pole=None, start=0, end=None, direction=1, scaled=False, n2coords=None)[source]¶
- Calculate where nodes should be positioned in 2d space for drawing a polar tree - Parameters: - node (Node) – A (root) node
- radius (float) – The radius of the tree. Optional, defaults to 1
- pole (tuple) – Tuple of floats. The cartesian coordinate of the pole. Optional, defaults to None.
- end (float) – Where the tree ends. For best results, between 0 and 360. Optional, defaults to None.
- direction – CLOCKWISE or COUNTERCLOCKWISE. The direction the tree is drawn. Optional, defaults to COUNTERCLOCKWISE
- scaled (bool) – Whether or not the tree is scaled. Optional, defaults to False.
 - Returns: - Mapping of nodes to Coordinates object - Return type: 
- 
ivy.layout_polar.depth_length_preorder_traversal(node, n2coords=None)[source]¶
- Calculate node depth (root = depth 0) and length to root - Parameters: - node (Node) – A node object. - Returns: - Mapping of nodes to coordinates instances. Coordinate instances have attributes “depth” and “length_to_root” - Return type: - dict 
ivy.ltt module¶
Compute lineages through time
- 
ivy.ltt.ltt(node)[source]¶
- Calculate lineages through time. The tree is assumed to be an ultrametric chronogram (extant leaves, with branch lengths proportional to time). - Parameters: - node (Node) – A node object. All nodes should have branch lengths. - Returns: - (times, diversity) - 1D-arrays containing the results. - Return type: - tuple 
ivy.matrix module¶
Functions for dealing with trees as matrices.
- 
ivy.matrix.readEL(el)[source]¶
- Create a tree from an edge list - Parameters: - el (list) – Edge list where each index is a node and each index’s value is the node’s parent. The root is its own parent. - Returns: - Tree from the edge list - Return type: - Node - Example - el = [1,1,1,3,3] - print readEL(el).ascii() ——————————————–+ 2- 1+
- : ———————-+ 4 ———————3+ ———————-+ 5
 
ivy.newick module¶
Parse newick strings.
The function of interest is parse, which returns the root node of the parsed tree.
- 
class ivy.newick.Tokenizer(infile)[source]¶
- Bases: - shlex.shlex- Provides tokens for parsing newick strings. 
- 
ivy.newick.parse(data, ttable=None, treename=None)[source]¶
- Parse a newick string. - Parameters: - data – Any file-like object that can be coerced into shlex, or a string (converted to StringIO)
- ttable (dict) – Mapping of node labels in the newick string to other values.
 - Returns: - The root node. - Return type: 
ivy.nexus module¶
ivy.ordereddict module¶
ivy.pyperclip module¶
- 
ivy.pyperclip.copy(text)¶
- 
ivy.pyperclip.getcb()¶
- 
ivy.pyperclip.paste()¶
- 
ivy.pyperclip.setcb(text)¶
ivy.r_funcs module¶
Functions that interface with r using rpy2
- 
ivy.r_funcs.phylorate(eventfile, treefile, spex)[source]¶
- Use BAMMtools to get rate data for characters or speciation/extinction rates along the branches of tree - (http://bamm-project.org/introduction.html) - Parameters: - Returns: - Tuple of rates and node indices associated with the rates 
ivy.sequtil module¶
- 
ivy.sequtil.find_stop_codons(seq, pos=0)[source]¶
- Find stop codons within sequence (in reading frame) - Parameters: - Yields: - tuple – The index where the stop codon starts and which stop codon was found. 
- 
ivy.sequtil.finditer(seq, substr, start=0)[source]¶
- Find substrings within a sequence - Parameters: - Yields: - int – Starting indicies of where the substr was found in seq 
- 
ivy.sequtil.gapidx(seq, gapchar=u'-')[source]¶
- For a sequence with gaps, calculate site positions without gaps - Parameters: - Returns: - An array where the first element corresponds to range(number of characters that are not gaps) and the second element is the indicies of all characters that are not gaps. - Return type: 
ivy.storage module¶
- 
class ivy.storage.Counter(iterable=None, **kwds)[source]¶
- Bases: - dict- Dict subclass for counting hashable objects. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. - >>> Counter('zyzygy') Counter({'y': 3, 'z': 2, 'g': 1}) - 
elements()[source]¶
- Iterator over elements repeating each as many times as its count. - >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] - If an element’s count has been set to zero or is a negative number, elements() will ignore it. 
 - 
most_common(n=None)[source]¶
- List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts. - >>> Counter('abracadabra').most_common(3) [('a', 5), ('r', 2), ('b', 2)] 
 - 
update(iterable=None, **kwds)[source]¶
- Like dict.update() but add counts instead of replacing them. - Source can be an iterable, a dictionary, or another Counter instance. - >>> c = Counter('which') >>> c.update('witch') # add elements from another iterable >>> d = Counter('watch') >>> c.update(d) # add elements from another counter >>> c['h'] # four 'h' in which, witch, and watch 4 
 
- 
ivy.tree module¶
The Node class and functions for creating trees from Newick strings, etc.
ivy does not have a Tree class per se, as most functions operate directly on Node objects.
- 
class ivy.tree.Node(**kwargs)[source]¶
- Bases: - object- A basic Node class with attributes and references to child nodes (‘children’, a list) and ‘parent’. - Keyword Arguments: - id – ID of the node. If not provided, is set using builtin id function
- ni (int) – Node index.
- li (int) – Leaf index.
- isroot (bool) – Is the node a root.
- isleaf (bool) – Is the node a leaf.
- label (str) – Node label.
- length (float) – Branch length from node to parent
- support – Bootstrap support values
- age (float) – Age of the node in time units.
- parent (Node) – Parent of the ndoe.
- children (list) – List of node objects. Children of node
- nchildren (int) – Number of children
- left – The “left” node
- treename – Name of tree
- comment – Comments for tree
 - 
ascii(*args, **kwargs)[source]¶
- Create ascii tree. - Keyword Arguments: - unitlen (float) – How long each unit should be rendered as. Defaults to 3.
- minwidth (float) – Minimum width of the plot. Defaults to 50
- maxwidth (float) – Maximum width of the plot. Defaults to None
- scaled (bool) – Whether or not the tree is scaled. Defaults to False
- show_internal_labels (bool) – Whether or not to show labels on internal nodes. Defaults to True.
 - Returns: - Ascii tree to be shown with print(). - Return type: 
 - 
bgrep(s, ignorecase=True)[source]¶
- Find branches (internal nodes) by regular-expression search of labels - Parameters: - Returns: - A list of node objects whose labels were matched by s. - Return type: - lsit 
 - 
bisect_branch(distance=0.5, reindex=True)[source]¶
- Mutate function. Add new node as parent to self in the middle of branch to parent. - Parameters: - Returns: - A new node. - Return type: 
 - 
clades()[source]¶
- Get internal nodes descended from self - Returns: - A list of internal nodes descended from (and not including) self. - Return type: - list 
 - 
collapse(add=False, reindex=True)[source]¶
- Mutate function - Remove self and collapse children to polytomy - Parameters: - Returns: - Parent of self - Return type: 
 - 
copy(recurse=True, _par=None)[source]¶
- Return a shallow copy of self. If recurse = False, do not copy children, parents, or any attribute that is Node. - Parameters: - recurse (bool) – Whether or not to copy children as well as self. - Returns: - A copy of self. - Return type: - Node 
 - 
descendants(order=u'pre', v=None, f=None)[source]¶
- Return a list of nodes descendant from self - but _not_ including self! - Parameters: - order (str) – Indicates wether to return nodes in preorder or postorder sequence. Optional, defaults to “pre”
- f (function) – filtering function that evaluates to True if desired node is called as the first parameter.
 - Returns: - A list of nodes descended from self not including self. - Return type: 
 - 
drop_tip(nodes)[source]¶
- Return a NEW TREE with the given tips dropped from it. Does not affect old tree. - Parameters: - nodes (list) – Leaf nodes or labels of leaf nodes - Returns: - Node – New root node with tips dropped - Return type: - Node 
 - 
excise(reindex=True)[source]¶
- Mutate function For ‘knees’: remove self from between parent and single child - Parameters: - reindex (bool) – Whether to recalculate index attributes after mutating tree. 
 - 
find(f, *args, **kwargs)[source]¶
- Find descendant nodes (generator version) - Parameters: - f – Function or a string. If a string, it is converted to a function for finding f as a substring in node labels. Otherwise, f should evaluate to True if called with a desired node as the first parameter. - Yields: - Node – Found nodes in preorder sequence. 
 - 
findall(f, *args, **kwargs)[source]¶
- Find descendant nodes (list version) - Parameters: - f – Function or a string. If a string, it is converted to a function for finding f as a substring in node labels. Otherwise, f should evaluate to True if called with a desired node as the first parameter. - Yields: - Node – Found nodes in preorder sequence. 
 - 
get(f, *args, **kwargs)[source]¶
- Return the first node found by node.find() - Parameters: - f (function) – A function that evaluates to True if desired node is called as the first parameter.
- **kwargs (*args,) – Additional args called by f 
 - Returns: - The first node found by node.find() - Return type: 
 - 
graft(node, reindex=True)[source]¶
- Mutate function Add node as sister to self. :param node: Node to graft to tree :type node: Node :param reindex: Whether to recalculate index attributes after mutating tree. :type reindex: bool 
 - 
grep(s, ignorecase=True)[source]¶
- Find nodes by regular-expression search of labels - Parameters: - Returns: - A list of node objects whose labels were matched by s. - Return type: - lsit 
 - 
internals(f=None)[source]¶
- Return a list nodes that have children (internal nodes) - Parameters: - f (function) – A function that evaluates to true if called with desired node as the first input - Returns: - A list of internal nodes that are true for f (if f is given) - Return type: - list 
 - 
is_same_tree(tree)[source]¶
- Test if two trees are the same (same topology, characteristics, labels, etc.) Ignores IDs by default. - Parameters: - Returns: - Whether or not the trees are the same. - Return type: 
 - 
ismono(*leaves)[source]¶
- Test if leaf descendants are monophyletic - Parameters: - *leaves (Node) – At least two leaf Node objects or labels - Returns: - Are the leaf descendants monophyletic? - Return type: - bool 
 - 
iternodes(f=None)[source]¶
- List of nodes descendant from self - including self :Yields: Node – - Nodes descended from self (including self) in
- preorder sequence
 
 - 
iternodes_cached(f=None, force=False)[source]¶
- Cached version of iternodes. Faster, but requires that the tree is static and not being changed. 
 - 
keep_tip(nodes)[source]¶
- Return a NEW TREE containing only the given tips. - Parameters: - nodes (list) – Leaf nodes or labels of leaf notes - Returns: - Node – New root node containing only given tips - Return type: - Node 
 - 
labeled()[source]¶
- Return a list of all descendant nodes that are labeled - Returns: - All descendants of self that are labeled (including self) - Return type: - list 
 - 
ladderize(reverse=False, reindex=True)[source]¶
- Mutate function Rotate nodes so tree is ordered by clade size. - WARNING: May cause strange results with functions that rely on
- pre- and post- ordering of nodes
 
 - 
leaf_distances(measure=u'length')[source]¶
- RR: I don’t quite understand the structure of the output. 
 - 
leaves(f=None)[source]¶
- Return a list of leaves. Can be filtered with f. - Parameters: - f (function) – A function that evaluates to True if called with desired node as the first input - Returns: - A list of leaves that are true for f (if f is given) - Return type: - list 
 - 
lgrep(s, ignorecase=True)[source]¶
- Find leaves by regular-expression search of labels - Parameters: - Returns: - A list of node objects whose labels were matched by s. - Return type: - lsit 
 - 
makeroot(shift_labels=False)[source]¶
- shift_labels: flag to shift internal parent-child node labels when internode polarity changes; suitable e.g. if internal node labels indicate unrooted bipartition support 
 - 
mrca(*nodes)[source]¶
- Find most recent common ancestor of nodes - Parameters: - *nodes (Node) – Node objects - Returns: - The MRCA of nodes - Return type: - Node 
 - 
order_subtrees_by_size(n2s=None, recurse=False, reverse=False)[source]¶
- Order interal clades by size 
 - 
prune(reindex=True)[source]¶
- Mutate function Remove self if self is not root. - All descendants of self are also removed - Parameters: - reindex (bool) – Whether to recalculate index attributes after mutating tree. - Returns: - Parent of self. If parent had only two children,
- parent is now a ‘knee’ and can be removed with excise.
 - Return type: - Node 
 - 
reindex(node, n=0, d=0, ni=0, li=0, ii=0, pi=0)[source]¶
- Iteratively attach ‘ni’, ‘ii’, ‘pi’, and ‘li’ attributes to nodes 
 - 
reroot(newroot, distance=0.5)[source]¶
- Reroot the tree between newroot and its parent. By default, the new node is halfway in between newroot and its current parent. Works by unrooting the tree, then rerooting it at the new node. - Returns a NEW tree. Does not affect old tree - Parameters: - newroot – Node or str of node label. Cannot be child of current root.
- distance (float) – What percentage along branch to place new node. Defaults to 0.5 (bisection). Higher numbers set the new node closer to the parent, lower numbers set it closer to child.
 - Returns: - Root node of new rerooted tree. - Return type: 
 - 
rootpath(end=None, stop=None)[source]¶
- Iterate over parent nodes toward the root, or node end if encountered. - Parameters: - end (Node) – A Node object to iterate to (instead of iterating towards root). Optional, defaults to None
- stop (function) – A function that returns True if desired node is called as the first parameter. Optional, defaults to None
 - Yields: - Node – Nodes in path to root (or end). 
 - 
rootpath_length(end=None)[source]¶
- Get length from self to root(if end is None) or length from self to an ancestor node (if end is an ancestor to self) - Parameters: - end (Node) – A node object - Returns: - The length from self to root/end - Return type: - float 
 
- 
ivy.tree.clade_sizes(node, results={})[source]¶
- Map node and descendants to number of descendant tips 
- 
ivy.tree.cls(root)[source]¶
- Get clade sizes of whole tree :param * root: A root node - Returns: - A dict mapping nodes to clade sizes
 
- 
ivy.tree.load_chars(filename, colNames=True, rowNames=False)[source]¶
- Given a filename pointing to a CSV with species names as column one and characters as remaining columns, return a dictionary mapping names to characters 
- 
ivy.tree.read(data, format=None, treename=None, ttable=None)[source]¶
- Read a single tree from data, which can be a Newick string, a file name, or a file-like object with tell and ‘read` methods. treename is an optional string that will be attached to all created nodes. - Parameters: - data – A file or file-like object or newick string - Returns: - The root node. - Return type: - Node 
ivy.treebase module¶
Functions to get trees and character data from treebase
- 
ivy.treebase.fetch_study(study_id, format=u'nexml')[source]¶
- Get a study from treebase in one of various formats - Parameters: - Returns: - Str representing a nexus file (if format = “nexus”) - OR - An lxml etree object 
- 
ivy.treebase.parse_nexml(doc)[source]¶
- Parse an etree ElementTree - Parameters: - doc – An etree ElementTree or a file that can be parsed into an etree ElementTree with etree.parse - Returns: - An ivy Storage object containing all the information from the
- nexml file: Characters, metadata, OTUs, and trees.
 
ivy.treegraph module¶
ivy.treegraph_experimental module¶
ivy.ubio module¶
Module contents¶
ivy - a phylogenetics library and visual shell http://www.reelab.net/ivy
Copyright 2010 Richard Ree <rree@fieldmuseum.org>
Required: ipython, matplotlib, scipy, numpy Useful: dendropy, biopython, etc.