dlce-eva / python-newick

python package to read and write the Newick format
Apache License 2.0
47 stars 12 forks source link

python-newick

Build Status PyPI

python package to read and write the Newick format.

Reading Newick

Since Newick specifies a format for a set of trees, all functions to read Newick return a list of newick.Node objects.

Supported Newick dialects

While the set of reserved characters in Newick (;(),:) is relatively small, it's still often seen as too restrictive, in particular when it comes to adding more data to tree nodes. Thus, Newick provides two mechanisms to overcome this restriction:

Quoted node labels

Node labels in Newick may be quoted (i.e. enclosed in single quotes ') to make it possible to add characters which are otherwise reserved. The newick package supports quoted labels.

>>> from newick import loads
>>> print(loads("('A:B','C''D')'E(F)'")[0].ascii_art())
         ┌─'A:B'
──'E(F)'─┤
         └─'C''D'

When creating Newick trees programmatically, names can be quoted (if necessary) automatically:

>>> from newick import Node
>>> print(Node("A(F')", auto_quote=True).name)
'A(F'')'
>>> print(Node("A(F')", auto_quote=True).unquoted_name)
A(F')

Note: newick provides no support to parse structured data from node labels (as it can be found in the trees distributed by the Genome Taxonomy Database).

Additional information in comments

The "Newick specification" states

Comments are enclosed in square brackets and may appear anywhere

This has spawned a host of ad-hoc mechanisms to insert additional data into Newick trees.

The newick package allows to deal with comments in two ways.

Note that square brackets inside quoted labels will not be interpreted as comments or annotations:

>>> newick.loads("('a[label]',b)c;")[0].descendants[0].name
"'a[label]'"
>>> newick.loads("('a[label]',b)c;")[0].newick
"('a[label]',b)c"

Some support for reading key-value data from node comments is available as well. If the comment format follows the NHX spec or the &<key>=<value>,...-format used e.g. by the MrBayes or BEAST software, additional data can be accessed from the dict Node.properties:

>>> newick.loads('(A,B)C[&&NHX:k1=v1:k2=v2];')[0].properties
{'k1': 'v1', 'k2': 'v2'}

Limitations:

Writing Newick

In parallel to the read operations there are three functions to serialize a single Node object or a list of Node objects to Newick format:

A tree may be assembled using the factory methods of the Node class:

Manipulating trees