Newick format

Newick writes a tree with nested parentheses. The reader accepts quoted names, comments in square brackets and NHX annotations; the tree is written back in the same format.

1

Starting code

This is the PHP code used by this example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public function newick(NewickReaderInterface $newickReader)
{
    // The great apes: quoted names, an NHX annotation and a comment are allowed
    $sNewick = "((('Homo sapiens'[&&NHX:S=human],('Pan troglodytes','Pan paniscus')),"
        . "'Gorilla gorilla'),'Pongo abelii')Hominidae; [no branch lengths: topology only]";
 
    $oTree = $newickReader->read($sNewick);
 
    // A malformed tree is refused with the position of the error
    $aErrors = [];
    foreach (["((Human,Chimpanzee),Gorilla;", "((Human,Chimpanzee),Gorilla)", "((Human,),Gorilla);"] as $sBroken) {
        try {
            $newickReader->read($sBroken);
        } catch (InvalidNewickException $e) {
            $aErrors[$sBroken] = $e->getMessage();
        }
    }
 
    return $this->render('default/phylogeneticsNewick.html.twig', [
        'input'   => $sNewick,
        'tree'    => $oTree,
        'leaves'  => $oTree->getLeafNames(),
        'newick'  => $oTree->toNewick(),
        'errors'  => $aErrors,
    ]);
}
2

Result

Result returned by BioPHP for the demonstration data.

The great apes
Newick read((('Homo sapiens'[&&NHX:S=human],('Pan troglodytes','Pan paniscus')),'Gorilla gorilla'),'Pongo abelii')Hominidae; [no branch lengths: topology only]
5 leavesHomo sapiens, Pan troglodytes, Pan paniscus, Gorilla gorilla, Pongo abelii
Written back((('Homo sapiens',('Pan troglodytes','Pan paniscus')),'Gorilla gorilla'),'Pongo abelii')Hominidae;
Hominidae
├── ┐
│   ├── ┐
│   │   ├── Homo sapiens
│   │   └── ┐
│   │       ├── Pan troglodytes
│   │       └── Pan paniscus
│   └── Gorilla gorilla
└── Pongo abelii
Malformed trees are refused
((Human,Chimpanzee),Gorilla;Unbalanced parentheses at position 27.
((Human,Chimpanzee),Gorilla)A Newick string must end with ";".
((Human,),Gorilla);Unnamed leaf at position 8 : every leaf must have a name.

The code above is the one actually executed by this page. Find the other examples in the left-hand column, or the tools in BioTools.