ivy 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:
  • node (Node) – Node object
  • node_ages (dict) – Dict mapping nodes to ages
Returns:

mapping of nodes to lengths

Return type:

dict

ivy.ages.min_ages(node, leaf_ages, results={})[source]

Calculate minimum ages given fixed ages in leaf_ages

Parameters:
  • node (Node) – A node object
  • leaf_ages (dict) – A dict mapping leaf nodes to ages
Returns:

mapping of nodes to ages

Return type:

dict

ivy.ages.smooth(node, node_ages, results={})[source]

adjust ages of internal nodes by smoothing

ivy.align module

ivy.align.find(aln, substr)[source]

generator that yields (seqnum, pos) tuples for every position of subseq in aln

ivy.align.find_id(aln, regexp)[source]
ivy.align.gapcols(aln, c=u'-')[source]
ivy.align.muscle(seqs, cmd=None)[source]
ivy.align.musclep(seqs1, seqs2, cmd=u'/usr/bin/muscle')[source]
ivy.align.read(data, format=None, name=None)[source]
ivy.align.write(data, f, format=u'fasta')[source]

ivy.ascii module

class ivy.ascii.AsciiBuffer(width, height)[source]
putstr(r, c, s)[source]
ivy.ascii.render(root, unitlen=3, minwidth=50, maxwidth=None, scaled=False, show_internal_labels=True)[source]

Create an ascii tree to be shown with print()

ivy.ascii.scale_cpos(node, n2c, scalef, root_offset)[source]
ivy.ascii.set_rpos(node, n2c)[source]
ivy.ascii.smooth_cpos(node, n2c)[source]
ivy.ascii.sum_to_root(node, internodes=True, length=False)[source]

Number of branches from node to root.

Parameters:
  • node (Node) – A Node object
  • RR – Do internodes and length do anything in this function? -CZ
Returns:

The number of branches from node to root.

Return type:

int

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.autocollapse.autocollapse_info(node, collapsed, visible=True, info={})[source]

gather information to determine if a node should be collapsed

collapsed is a set containing nodes that are already collapsed

ivy.bipart module

class ivy.bipart.Bipart(elements, subset, node=None, support=None)[source]

Bases: object

A class representing a bipartition.

compute(elements)[source]
iscompatible(other)[source]
class ivy.bipart.TreeSet(root, elements=None)[source]
ivy.bipart.compare(set1, set2, support=None)[source]
ivy.bipart.compare_trees(r1, r2, support=None)[source]
ivy.bipart.conflict(bp1, bp2, support=None)[source]

ivy.birthdeath module

Equations from Magallon and Sanderson 2001

ivy.birthdeath.Alpha(epsilon, r, t)[source]

Calculate Alpha

Parameters:
  • epsilon (float) – Relative extinction rate(d/b)
  • r (float) – Net diversification rate (b-d).
  • t (float) – Elapsed time
Returns:

Alpha

Return type:

Float

ivy.birthdeath.Beta(epsilon, r, t)[source]

Calculate Beta

Parameters:
  • epsilon (float) – Relative extinction rate(d/b)
  • r (float) – Net diversification rate (b-d).
  • t (float) – Elapsed time.
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:
  • i (int) – Number of extant species
  • t (float) – Elapsed time
  • r (float) – Net diversification rate (b-d)
  • epsilon (float) – Relative extinction (d/b)
ivy.birthdeath.Nbar(t, a, r, epsilon)[source]

Mean clade size conditional on survival of the clade

Parameters:
  • t (float) – Elapsed time
  • a (int) – Number of lineages at t=0
  • r (float) – Net diversification rate (b-d)
  • epsilon (float) – Relative extinction (d/b)
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:
  • i (int) – Number of extant species
  • t (float) – Elapsed time
  • r (float) – Net diversification rate (b-d)
  • epsilon (float) – Relative extinction (d/b)
ivy.birthdeath.condPrN(i, t, a, r, epsilon)[source]

Conditional probability of i species after time t, given the probability of survival

Parameters:
  • i (int) – Number of extant species
  • t (float) – Elapsed time
  • a (int) – Number of lineages at t=0
  • r (float) – Net diversification rate (b-d)
  • epsilon (float) – Relative extinction (d/b)
ivy.birthdeath.logLT(t, n, r, epsilon)[source]

Log-likelihood of terminal taxa

Parameters:
  • t – vector of stem ages
  • n – vector of diversities
  • r (float) – net diversification
  • epsilon (float) – Relative extinction
ivy.birthdeath.prN(i, t, a, r, epsilon)[source]

Probability of observing i species after time t

Parameters:
  • i (int) – Number of extant species
  • t (float) – Elapsed time
  • a (int) – Number of lineages at t=0
  • r (float) – Net diversification rate (b-d)
  • epsilon (float) – Relative extinction (d/b)
ivy.birthdeath.r_hat_crown(t, n, epsilon)[source]
ivy.birthdeath.r_hat_stem(t, n, epsilon)[source]

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:
  • node (Node) – A node object
  • data (dict) – Mapping of leaf names to character values
Returns:

Mapping of internal nodes to tuples containing ancestral

state, its variance (error), the contrast, and the contrasts’s variance.

Return type:

dict

TODO: modify to accommodate polytomies.

ivy.data module

class ivy.data.Matrix[source]

Bases: object

get(x, col=None)[source]
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

index_array(array)[source]

ivy.demo module

class ivy.demo.Demo(src, title=u'', arg_str=u'', auto_all=None)[source]

Bases: IPython.lib.demo.ClearIPDemo

show(index=None)[source]

Show a single block on screen

ivy.demo.demo(src, speed=1)[source]
ivy.demo.random() → x in the interval [0, 1).

ivy.examples module

ivy.genbank module

ivy.genbank.ac2gi(ac)[source]
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.blast(query, e=10, n=100, entrez_query=u'')[source]
ivy.genbank.blast_closest(fasta, e=10)[source]
ivy.genbank.create_fastas(data, genes)[source]
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.genbank.extract_gene(seq, gene)[source]

RR: Not sure what format seq should be in -CZ

ivy.genbank.fetch_DNA_seqs(terms, maxn=10000, batchsize=1000)[source]
terms: sequence of search terms, quoted appropriately, with Entrez
specifiers, e.g. [‘“Mus musculus”[organism]’]

maxn: maximum number of sequences to return returns list of SeqRecord objects

ivy.genbank.fetch_aclist(aclist, batchsize=1000)[source]
ivy.genbank.fetch_gilist(gilist, batchsize=1000)[source]
ivy.genbank.fetchseq(gi)[source]
ivy.genbank.fetchtax(taxid)[source]
ivy.genbank.gi2tax(gi)[source]
ivy.genbank.gi2webenv(gilist)[source]
ivy.genbank.merge_fastas(fnames, name=u'merged')[source]
ivy.genbank.organism_id(s)[source]
ivy.genbank.search_taxonomy(q)[source]
ivy.genbank.seqrec_taxid(seqrec)[source]

extract the NCBI taxon id from a sequence record

ivy.genbank.start_codons(seq)[source]
ivy.genbank.trimpos(rec)[source]

return the positions of the first and last ungapped base

ivy.interactive module

Adds to the interactive IPython/pylab environment

ivy.interactive.alnfig(*args, **kwargs)[source]
ivy.interactive.readaln(data, *args, **kwargs)[source]
ivy.interactive.readtree(data, *args, **kwargs)[source]
ivy.interactive.treefig(*args, **kwargs)[source]

ivy.ivy_completers module

ivy.layout module

layout nodes in 2d space

The function of interest is calc_node_positions (aka nodepos)

class ivy.layout.Coordinates(x=0, y=0)[source]

Coordinates class for storing xy coordinates

point()[source]
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:

dict

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:

dict

Notes

Origin is at upper left

ivy.layout.smooth_xpos(node, n2coords)[source]

ivy.layout_polar module

class ivy.layout_polar.Coordinates[source]
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:

dict

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.layout_polar.smooth_xpos(node, n2coords)[source]
ivy.layout_polar.test()[source]

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.ltt.test()[source]
ivy.ltt.traverse(node, t=0, results=None)[source]

Recursively traverse the tree and collect information about when nodes split and how many lineages are added by its splitting.

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.matrix.vcv(root)[source]

Leaf variances and covariances :param root: A node object :type root: Node

Returns:A defaultdict mapping pairs of nodes to variances cov: A defaultdict mapping pairs of nodes to covariances
Return type:var

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.

parse_embedded_comment()[source]
ivy.newick.add_label_chars(chars)[source]
ivy.newick.nexus_iter(infile)[source]
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:

Node

ivy.newick.parse_ampersand_comment(s)[source]
ivy.newick.test_parse_comment()[source]

ivy.nexus module

class ivy.nexus.Newick(parse_results=None, ttable={})[source]

Bases: object

convenience class for storing the results of a newick tree record from a nexus file, as parsed by newick.nexus_iter

parse()[source]
populate(parse_results, ttable={})[source]
ivy.nexus.fetchaln(fname)[source]

Fetch alignment

ivy.nexus.parse_treesblock(infile)[source]
ivy.nexus.split_blocks(infile)[source]

ivy.ordereddict module

class ivy.ordereddict.OrderedDict(*args, **kwds)[source]

Bases: dict, UserDict.DictMixin

clear()[source]
copy()[source]
classmethod fromkeys(iterable, value=None)[source]
items()
iteritems()
iterkeys()
itervalues()
keys()[source]
pop(key, *args)
popitem(last=True)[source]
setdefault(key, default=None)
update(other=None, **kwargs)
values()

ivy.pyperclip module

ivy.pyperclip.copy(text)
ivy.pyperclip.getcb()
ivy.pyperclip.gtkGetClipboard()[source]
ivy.pyperclip.gtkSetClipboard(text)[source]
ivy.pyperclip.macGetClipboard()[source]
ivy.pyperclip.macSetClipboard(text)[source]
ivy.pyperclip.paste()
ivy.pyperclip.qtGetClipboard()[source]
ivy.pyperclip.qtSetClipboard(text)[source]
ivy.pyperclip.setcb(text)
ivy.pyperclip.winGetClipboard()[source]
ivy.pyperclip.winSetClipboard(text)[source]
ivy.pyperclip.xclipGetClipboard()[source]
ivy.pyperclip.xclipSetClipboard(text)[source]
ivy.pyperclip.xselGetClipboard()[source]
ivy.pyperclip.xselSetClipboard(text)[source]

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:
  • eventfile (str) – Path to event data output from BAMM
  • treefile (str) – Path to tree
  • spex (str) – “s”, “e”, or “netdiv”. Whether to get speciation, extinction, or net diversification rates.
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:
  • seq (str) – A sequence
  • pos (int) – Starting position. Defaults to 0.
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:
  • seq (str) – A sequence.
  • substr (str) – A subsequence to search for
  • start (int) – Starting index. Defaults to 0
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:
  • seq (list) – Each element of the list is one character in a sequence.
  • gapchar (str) – The character gaps are coded as. Defaults to ‘-‘
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:

array

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})
copy()[source]

Like dict.copy() but returns a Counter instance instead of a dict.

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.

classmethod fromkeys(iterable, v=None)[source]
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
class ivy.storage.MaxDict[source]

Bases: dict

class ivy.storage.Storage[source]

Bases: dict

A Storage object is like a dictionary except obj.foo can be used in addition to obj[‘foo’].

From web2py/gluon/storage.py by Massimo Di Pierro (www.web2py.com)

ivy.storage.convert(d)[source]

convert a (potentially nested) dict to Storage

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.

ivy.tree.C(leaves, internals)[source]
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
add_child(child, reindex=True)[source]

Mutate function Add child as child of self

Parameters:
  • child (Node) – A node object
  • reindex (bool) – Whether to recalculate index attributes after mutating
ape_node_idx()[source]
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:

str

bgrep(s, ignorecase=True)[source]

Find branches (internal nodes) by regular-expression search of labels

Parameters:
  • s (str) – String to search.
  • ignorecase (bool) – Indicates to ignore case. Defaults to true.
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:
  • 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.
  • reindex (bool) – Whether to recalculate index attributes after mutating
Returns:

A new node.

Return type:

Node

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:
  • add (bool) – Whether or not to add self’s length to children’s length.
  • reindex (bool) – Whether to recalculate index attributes after mutating
Returns:

Parent of self

Return type:

Node

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:

list

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:

Node

get_root()[source]
get_siblings()[source]

Return list of siblings of node

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:
  • s (str) – String to search.
  • ignorecase (bool) – Indicates to ignore case. Defaults to true.
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:
  • tree (Node) – Another tree to compare to
  • verbose (bool) – Whether or not to print a message containing the non-matching properties
Returns:

Whether or not the trees are the same.

Return type:

bool

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
iterleaves()[source]

Yield leaves descendant from self

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.

leafsets(d=None, labels=False)[source]

return a mapping of nodes to leaf sets (nodes or labels)

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:
  • s (str) – String to search.
  • ignorecase (bool) – Indicates to ignore case. Defaults to true.
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

max_tippath(first=True)[source]

Get the maximum length from self to a leaf node

mrca(*nodes)[source]

Find most recent common ancestor of nodes

Parameters:*nodes (Node) – Node objects
Returns:The MRCA of nodes
Return type:Node
ntaxa()[source]

Number of leaves descended from self

order_subtrees_by_size(n2s=None, recurse=False, reverse=False)[source]

Order interal clades by size

postiter(f=None)[source]

Yield nodes in postorder sequence

preiter(f=None)[source]

Yield nodes in preorder sequence

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

remove_child(child, reindex=True)[source]

Mutate function. Remove child from self.

Parameters:
  • child (Node) – A node object that is a child of self
  • reindex (bool) – Whether to recalculate index attributes after mutating
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:

Node

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
set_iternode_cache()[source]

Store iteration order for faster access.

subtree_mapping(labels, clean=False)[source]

Find the set of nodes in ‘labels’, and create a new tree representing the subtree connecting them. Nodes are assumed to be non-nested.

Returns:a mapping of old nodes to new nodes and vice versa.
Return type:dict

TODO: test this, high bug probability

tiplabels()[source]

List of labels of leaves descended from self, in preorder sequence

write(outfile=None, format=u'newick', length_fmt=u':%g', end=True, clobber=False)[source]
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.tree.readmany(data, format=u'newick')[source]

Iterate over trees from a source.

ivy.tree.remove_singletons(root, add=True)[source]

Remove descendant nodes that are the sole child of their parent

ivy.tree.traverse(node)[source]

recursive preorder iterator based solely on .children attribute

ivy.tree.write(node, outfile=None, format=u'newick', length_fmt=u':%g', clobber=False)[source]
ivy.tree.write_newick(node, outfile=None, length_fmt=u':%g', end=False, clobber=False)[source]

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:
  • study_id (str) – The id of the study
  • format (str) – One of [“rdf”, “html”, “nexml”, “nexus”]
Returns:

Str representing a nexus file (if format = “nexus”)

OR

An lxml etree object

ivy.treebase.parse_chars(e, otus)[source]
ivy.treebase.parse_charsets(study_id)[source]
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.treebase.parse_otus(e)[source]

Get OTUs from an etree object

Parameters:e – A nexml document parsed by etree
Returns:A dict mapping keys to OTUs contained in ivy Storage objects
Return type:dict
ivy.treebase.parse_states(e)[source]

e is a characters element

ivy.treebase.parse_trees(e, otus)[source]

Get trees from an etree object

Parameters:
  • e – A nexml document parsed by etree
  • otus – OTUs returned by parse_otus
Returns:

A list of ivy Storage objects each

containing every node of a tree.

Return type:

list

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.