Back to index

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

Classes

class  PhyloXMLError
class  Parser
class  Writer

Functions

def register_namespace
def read
def parse
def write
def _local
def _split_namespace
def _ns
def _get_child_as
def _get_child_text
def _get_children_as
def _get_children_text
def _indent
def _str2bool
def _dict_str2bool
def _int
def _float
def _collapse_wspace
def _replace_wspace
def _serialize
def _clean_attrib
def _handle_complex
def _handle_simple

Variables

string __docformat__ = "restructuredtext en"
dictionary NAMESPACES
 register_namespace = ElementTree.register_namespace

Class Documentation

class Bio::Phylo::PhyloXMLIO::PhyloXMLError
Exception raised when PhyloXML object construction cannot continue.

XML syntax errors will be found and raised by the underlying ElementTree
module; this exception is for valid XML that breaks the phyloXML
specification.

Definition at line 58 of file PhyloXMLIO.py.


Function Documentation

def Bio.Phylo.PhyloXMLIO._clean_attrib (   obj,
  attrs 
) [private]
Create a dictionary from an object's specified, non-None attributes.

Definition at line 609 of file PhyloXMLIO.py.

00609 
00610 def _clean_attrib(obj, attrs):
00611     """Create a dictionary from an object's specified, non-None attributes."""
00612     out = {}
00613     for key in attrs:
00614         val = getattr(obj, key)
00615         if val is not None:
00616             out[key] = _serialize(val)
00617     return out
00618 

Here is the call graph for this function:

Here is the caller graph for this function:

def Bio.Phylo.PhyloXMLIO._collapse_wspace (   text) [private]
Replace all spans of whitespace with a single space character.

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

Definition at line 236 of file PhyloXMLIO.py.

00236 
00237 def _collapse_wspace(text):
00238     """Replace all spans of whitespace with a single space character.
00239 
00240     Also remove leading and trailing whitespace. See "Collapse Whitespace
00241     Policy" in the phyloXML spec glossary:
00242     http://phyloxml.org/documentation/version_100/phyloxml.xsd.html#Glossary
00243     """
00244     if text is not None:
00245         return ' '.join(text.split())
00246 
# NB: Not currently used

Here is the caller graph for this function:

def Bio.Phylo.PhyloXMLIO._dict_str2bool (   dct,
  keys 
) [private]

Definition at line 215 of file PhyloXMLIO.py.

00215 
00216 def _dict_str2bool(dct, keys):
00217     out = dct.copy()
00218     for key in keys:
00219         if key in out:
00220             out[key] = _str2bool(out[key])
00221     return out

Here is the call graph for this function:

Here is the caller graph for this function:

def Bio.Phylo.PhyloXMLIO._float (   text) [private]

Definition at line 229 of file PhyloXMLIO.py.

00229 
00230 def _float(text):
00231     if text is not None:
00232         try:
00233             return float(text)
00234         except Exception:
00235             return None

Here is the caller graph for this function:

def Bio.Phylo.PhyloXMLIO._get_child_as (   parent,
  tag,
  construct 
) [private]
Find a child node by tag, and pass it through a constructor.

Returns None if no matching child is found.

Definition at line 147 of file PhyloXMLIO.py.

00147 
00148 def _get_child_as(parent, tag, construct):
00149     """Find a child node by tag, and pass it through a constructor.
00150 
00151     Returns None if no matching child is found.
00152     """
00153     child = parent.find(_ns(tag))
00154     if child is not None:
00155         return construct(child)

Here is the call graph for this function:

Here is the caller graph for this function:

def Bio.Phylo.PhyloXMLIO._get_child_text (   parent,
  tag,
  construct = unicode 
) [private]
Find a child node by tag; pass its text through a constructor.

Returns None if no matching child is found.

Definition at line 156 of file PhyloXMLIO.py.

00156 
00157 def _get_child_text(parent, tag, construct=unicode):
00158     """Find a child node by tag; pass its text through a constructor.
00159 
00160     Returns None if no matching child is found.
00161     """
00162     child = parent.find(_ns(tag))
00163     if child is not None and child.text:
00164         return construct(child.text)

Here is the call graph for this function:

Here is the caller graph for this function:

def Bio.Phylo.PhyloXMLIO._get_children_as (   parent,
  tag,
  construct 
) [private]
Find child nodes by tag; pass each through a constructor.

Returns an empty list if no matching child is found.

Definition at line 165 of file PhyloXMLIO.py.

00165 
00166 def _get_children_as(parent, tag, construct):
00167     """Find child nodes by tag; pass each through a constructor.
00168 
00169     Returns an empty list if no matching child is found.
00170     """
00171     return [construct(child) for child in 
00172             parent.findall(_ns(tag))]

Here is the call graph for this function:

Here is the caller graph for this function:

def Bio.Phylo.PhyloXMLIO._get_children_text (   parent,
  tag,
  construct = unicode 
) [private]
Find child nodes by tag; pass each node's text through a constructor.

Returns an empty list if no matching child is found.

Definition at line 173 of file PhyloXMLIO.py.

00173 
00174 def _get_children_text(parent, tag, construct=unicode):
00175     """Find child nodes by tag; pass each node's text through a constructor.
00176 
00177     Returns an empty list if no matching child is found.
00178     """
00179     return [construct(child.text) for child in 
00180             parent.findall(_ns(tag))
00181             if child.text]

Here is the call graph for this function:

Here is the caller graph for this function:

def Bio.Phylo.PhyloXMLIO._handle_complex (   tag,
  attribs,
  subnodes,
  has_text = False 
) [private]

Definition at line 619 of file PhyloXMLIO.py.

00619 
00620 def _handle_complex(tag, attribs, subnodes, has_text=False):
00621     def wrapped(self, obj):
00622         elem = ElementTree.Element(tag, _clean_attrib(obj, attribs))
00623         for subn in subnodes:
00624             if isinstance(subn, basestring):
00625                 # singular object: method and attribute names are the same
00626                 if getattr(obj, subn) is not None:
00627                     elem.append(getattr(self, subn)(getattr(obj, subn)))
00628             else:
00629                 # list: singular method, pluralized attribute name
00630                 method, plural = subn
00631                 for item in getattr(obj, plural):
00632                     elem.append(getattr(self, method)(item))
00633         if has_text:
00634             elem.text = _serialize(obj.value)
00635         return elem
00636     wrapped.__doc__ = "Serialize a %s and its subnodes, in order." % tag
00637     return wrapped
00638 

Here is the call graph for this function:

def Bio.Phylo.PhyloXMLIO._handle_simple (   tag) [private]

Definition at line 639 of file PhyloXMLIO.py.

00639 
00640 def _handle_simple(tag):
00641     def wrapped(self, obj):
00642         elem = ElementTree.Element(tag)
00643         elem.text = _serialize(obj)
00644         return elem
00645     wrapped.__doc__ = "Serialize a simple %s node." % tag
00646     return wrapped
00647 

Here is the call graph for this function:

def Bio.Phylo.PhyloXMLIO._indent (   elem,
  level = 0 
) [private]
Add line breaks and indentation to ElementTree in-place.

Sources:

- http://effbot.org/zone/element-lib.htm#prettyprint
- http://infix.se/2007/02/06/gentlemen-indent-your-xml

Definition at line 182 of file PhyloXMLIO.py.

00182 
00183 def _indent(elem, level=0):
00184     """Add line breaks and indentation to ElementTree in-place.
00185 
00186     Sources:
00187 
00188     - http://effbot.org/zone/element-lib.htm#prettyprint
00189     - http://infix.se/2007/02/06/gentlemen-indent-your-xml
00190     """
00191     i = "\n" + level*"  "
00192     if len(elem):
00193         if not elem.text or not elem.text.strip():
00194             elem.text = i + "  "
00195         for e in elem:
00196             _indent(e, level+1)
00197             if not e.tail or not e.tail.strip():
00198                 e.tail = i + "  "
00199         if not e.tail or not e.tail.strip():
00200             e.tail = i
00201     else:
00202         if level and (not elem.tail or not elem.tail.strip()):
00203             elem.tail = i
00204 
00205 # ---------------------------------------------------------
00206 # INPUT
00207 # ---------------------------------------------------------

Here is the caller graph for this function:

def Bio.Phylo.PhyloXMLIO._int (   text) [private]

Definition at line 222 of file PhyloXMLIO.py.

00222 
00223 def _int(text):
00224     if text is not None:
00225         try:
00226             return int(text)
00227         except Exception:
00228             return None

Here is the caller graph for this function:

def Bio.Phylo.PhyloXMLIO._local (   tag) [private]
Extract the local tag from a namespaced tag name.

Definition at line 130 of file PhyloXMLIO.py.

00130 
00131 def _local(tag):
00132     """Extract the local tag from a namespaced tag name."""
00133     if tag[0] == '{':
00134         return tag[tag.index('}')+1:]
00135     return tag

Here is the caller graph for this function:

def Bio.Phylo.PhyloXMLIO._ns (   tag,
  namespace = NAMESPACES['phy'] 
) [private]
Format an XML tag with the given namespace.

Definition at line 143 of file PhyloXMLIO.py.

00143 
00144 def _ns(tag, namespace=NAMESPACES['phy']):
00145     """Format an XML tag with the given namespace."""
00146     return '{%s}%s' % (namespace, tag)

Here is the caller graph for this function:

def Bio.Phylo.PhyloXMLIO._replace_wspace (   text) [private]
Replace tab, LF and CR characters with spaces, but don't collapse.

See "Replace Whitespace Policy" in the phyloXML spec glossary:
http://phyloxml.org/documentation/version_100/phyloxml.xsd.html#Glossary

Definition at line 247 of file PhyloXMLIO.py.

00247 
00248 def _replace_wspace(text):
00249     """Replace tab, LF and CR characters with spaces, but don't collapse.
00250 
00251     See "Replace Whitespace Policy" in the phyloXML spec glossary:
00252     http://phyloxml.org/documentation/version_100/phyloxml.xsd.html#Glossary
00253     """
00254     for char in ('\t', '\n', '\r'):
00255         if char in text:
00256             text = text.replace(char, ' ')
00257     return text
00258 

def Bio.Phylo.PhyloXMLIO._serialize (   value) [private]
Convert a Python primitive to a phyloXML-compatible Unicode string.

Definition at line 600 of file PhyloXMLIO.py.

00600 
00601 def _serialize(value):
00602     """Convert a Python primitive to a phyloXML-compatible Unicode string."""
00603     if isinstance(value, float):
00604         return unicode(value).upper()
00605     elif isinstance(value, bool):
00606         return unicode(value).lower()
00607     return unicode(value)
00608 

Here is the caller graph for this function:

def Bio.Phylo.PhyloXMLIO._split_namespace (   tag) [private]
Split a tag into namespace and local tag strings.

Definition at line 136 of file PhyloXMLIO.py.

00136 
00137 def _split_namespace(tag):
00138     """Split a tag into namespace and local tag strings."""
00139     try:
00140         return tag[1:].split('}', 1)
00141     except:
00142         return ('', tag)

Here is the caller graph for this function:

def Bio.Phylo.PhyloXMLIO._str2bool (   text) [private]

Definition at line 208 of file PhyloXMLIO.py.

00208 
00209 def _str2bool(text):
00210     if text == 'true':
00211         return True
00212     if text == 'false':
00213         return False
00214     raise ValueError('String could not be converted to boolean: ' + text)

Here is the caller graph for this function:

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.

Definition at line 81 of file PhyloXMLIO.py.

00081 
00082 def parse(file):
00083     """Iterate over the phylogenetic trees in a phyloXML file.
00084 
00085     This ignores any additional data stored at the top level, but may be more
00086     memory-efficient than the `read` function.
00087 
00088     :returns: a generator of `Bio.Phylo.PhyloXML.Phylogeny` objects.
00089     """
00090     return Parser(file).parse()

def Bio.Phylo.PhyloXMLIO.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.

Definition at line 71 of file PhyloXMLIO.py.

00071 
00072 def read(file):
00073     """Parse a phyloXML file or stream and build a tree of Biopython objects.
00074 
00075     The children of the root node are phylogenies and possibly other arbitrary
00076     (non-phyloXML) objects.
00077 
00078     :returns: a single `Bio.Phylo.PhyloXML.Phyloxml` object.
00079     """
00080     return Parser(file).read()

def Bio.Phylo.PhyloXMLIO.register_namespace (   prefix,
  uri 
)

Definition at line 51 of file PhyloXMLIO.py.

00051 
00052     def register_namespace(prefix, uri):
00053         ElementTree._namespace_map[uri] = prefix

def Bio.Phylo.PhyloXMLIO.write (   obj,
  file,
  encoding = 'utf-8',
  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.

Definition at line 91 of file PhyloXMLIO.py.

00091 
00092 def write(obj, file, encoding='utf-8', indent=True):
00093     """Write a phyloXML file.
00094 
00095     :Parameters:
00096         obj
00097             an instance of `Phyloxml`, `Phylogeny` or `BaseTree.Tree`, or an
00098             iterable of either of the latter two. The object will be converted
00099             to a Phyloxml object before serialization.
00100         file
00101             either an open handle or a file name.
00102     """
00103     def fix_single(tree):
00104         if isinstance(tree, PX.Phylogeny):
00105             return tree
00106         if isinstance(tree, PX.Clade):
00107             return tree.to_phylogeny()
00108         if isinstance(tree, PX.BaseTree.Tree):
00109             return PX.Phylogeny.from_tree(tree)
00110         if isinstance(tree, PX.BaseTree.Clade):
00111             return PX.Phylogeny.from_tree(PX.BaseTree.Tree(root=tree))
00112         else:
00113             raise ValueError("iterable must contain Tree or Clade types")
00114 
00115     if isinstance(obj, PX.Phyloxml):
00116         pass
00117     elif (isinstance(obj, PX.BaseTree.Tree) or
00118           isinstance(obj, PX.BaseTree.Clade)):
00119         obj = fix_single(obj).to_phyloxml()
00120     elif hasattr(obj, '__iter__'):
00121         obj = PX.Phyloxml({}, phylogenies=(fix_single(t) for t in obj))
00122     else:
00123         raise ValueError("First argument must be a Phyloxml, Phylogeny, "
00124                 "Tree, or iterable of Trees or Phylogenies.")
00125     return Writer(obj).write(file, encoding=encoding, indent=indent)
00126 
00127 
00128 # ---------------------------------------------------------
00129 # Functions I wish ElementTree had


Variable Documentation

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

Definition at line 19 of file PhyloXMLIO.py.

Initial value:
00001 {
00002         'phy':  'http://www.phyloxml.org',
00003         }

Definition at line 39 of file PhyloXMLIO.py.

Bio.Phylo.PhyloXMLIO.register_namespace = ElementTree.register_namespace

Definition at line 44 of file PhyloXMLIO.py.