← Back to PhyNetPy

PhyNetPy Documentation

Library for the Development and Use of Phylogenetic Network Methods

Newick Module v1.0.0

The Newick module provides utilities for handling Newick format strings and generating Nexus files from networks and gene trees.

Author:
Mark Kessler
Last Edit:
3/11/25
Source:
Newick.py

Exceptions

exception NewickParserError(Exception)

Raised when there are errors parsing a Newick string into a Network object.

Helper Functions

def get_labels(newick_str: str) -> set[str]

Extract all unique taxa labels from a Newick string.

Parameter Type Description
newick_str str A Newick format string
Returns: set[str] - Set of unique taxa labels

NexusTemplate Class

class NexusTemplate

Class for generating Nexus files from tree/network data. Automatically manages taxa blocks and can include PhyloNet commands.

Constructor

__init__(self)

Initialize a blank Nexus template.

Methods

add(self, newick_str: str) -> None

Add a network (as Newick string) to the TREES block. Taxa labels are automatically extracted and added to the TAXA block.

Parameter Type Description
newick_str str Network in Newick format
add_phylonet_cmd(self, cmd: str) -> None

Add a PhyloNet command to be included in the PHYLONET block.

Parameter Type Description
cmd str A PhyloNet command string
load_gene_trees(self, filename: str) -> None

Load gene trees from a file and add them to the template.

Parameter Type Description
filename str Path to file containing gene trees
generate(self, loc: Union[Path, str], end_name: str) -> None

Generate a Nexus file at the specified location.

Parameter Type Description
loc Path | str Directory to save the file
end_name str Filename (must include .nex extension)
Raises: NewickParserError - If file already exists

Generated Nexus Format

The NexusTemplate generates files with the following structure:

#NEXUS

BEGIN TAXA;
DIMENSIONS NTAX=n;
TAXALABELS
taxon1
taxon2
...
;
END;

BEGIN TREES;
Tree net1 = (newick_string1);
Tree net2 = (newick_string2);
...
END;

BEGIN PHYLONET;
command1;
command2;
...
END;

Usage Examples

from PhyNetPy.Newick import NexusTemplate, get_labels

# Extract labels from a Newick string
newick = "((A:1,B:1)C:1,(D:1,E:1)F:1)root;"
labels = get_labels(newick)
print(f"Taxa: {labels}")  # {'A', 'B', 'C', 'D', 'E', 'F', 'root'}

# Create a Nexus file from networks
template = NexusTemplate()

# Add networks
template.add("((A:1,B:1):1,(C:1,D:1):1);")
template.add("((A:1,C:1):1,(B:1,D:1):1);")

# Add PhyloNet commands
template.add_phylonet_cmd("InferNetwork_MPL (all) 1;")

# Generate the file
template.generate("/path/to/output", "networks.nex")

# Load gene trees and create Nexus
template2 = NexusTemplate()
template2.load_gene_trees("gene_trees.nex")
template2.add_phylonet_cmd("InferNetwork_ML (all) 2 -bl;")
template2.generate("/path/to/output", "inference_input.nex")

See Also

Navigation

Modules

This Page