PhyNetPy Documentation

Library for the Development and Use of Phylogenetic Network Methods

Network Module v1.0.0

Core phylogenetic network data structures: Node, Edge, Branch, and Network classes.

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

Exceptions

exception NetworkError(Exception)

This exception is raised when a network is malformed, or if a network operation fails.

exception NodeError(Exception)

This exception is raised when a Node operation fails.

exception EdgeError(Exception)

This exception is raised when an Edge operation fails.

Branch

class Branch

A lightweight, detached view of a single branch (edge) of a phylogenetic tree or network. Holds the branch length, inheritance probability, and the label of the parent node. Unlike :class:`Edge`, a ``Branch`` is not wired into a :class:`Network`; it is the value type handed to model nodes and other consumers that need branch parameters without the surrounding topology.

Properties

length -> float property

Get the length of the branch.

Returns: float: The branch length.
inheritance_probability -> float property

Get the inheritance probability (gamma) of the branch.

Returns: float: The inheritance probability.
parent_id -> str property

Get the label of the branch's parent node.

Returns: str: The parent node label.

Constructor

__init__(length: float = None, inheritance_probability: float = None, parent_id: str = None) -> None

Initialize a Branch.

Parameter Type Description
length float, optional Branch length. Defaults to None.
inheritance_probability float, optional Inheritance probability (gamma) for a reticulation branch. Defaults to None.
parent_id str, optional Label of the parent node. Defaults to None.

Methods

__len__ -> float

Get the length of the branch.

Returns: float: The branch length.
length(value: float) -> None

Set the length of the branch. Negative values are rejected with a warning and leave the current value untouched.

Parameter Type Description
value float The new branch length.
inheritance_probability(value: float) -> None

Set the inheritance probability of the branch. Values outside [0, 1] are rejected with a warning and leave the current value untouched.

Parameter Type Description
value float The new inheritance probability.
parent_id(value: str) -> None

Set the label of the branch's parent node.

Parameter Type Description
value str The new parent node label.
__str__ -> str

Return a string representation of the branch.

Returns: str: Human readable description of the branch.
__repr__ -> str

Return a string representation of the branch.

Returns: str: Human readable description of the branch.

Node

class Node

Node class that provides support for managing network constructs like reticulation nodes and other phylogenetic attributes.

Properties

label -> str property

Returns the name of the node

Returns: str: Node label.

Constructor

__init__(name: str, is_reticulation: bool = False, attr: Union[dict[Any, Any], None] = None, seq: Union[DataSequence, None] = None, t: Union[float, None] = None) -> None

Initialize a node with a name, attribute mapping, and a hybrid flag.

Parameter Type Description
name str A Node label.
is_reticulation bool, optional Flag that marks a node as a reticulation node if set to True. Defaults to False.
attr dict[Any, Any], optional Fill a mapping with any other user defined values. Defaults to a new empty dictionary.
seq Union[DataSequence, None], optional A data sequence wrapper.
t Union[float, None], optional A speciation time for this node.

Methods

get_attributes -> dict[Union[str, Any], Any]

Retrieve the attribute mapping.

Returns: dict[Union[str, Any], Any]: A storage of key value pairs that correspond to user defined node attributes. Typically keys are string labels, but they can be anything.
set_attributes(new_attr: dict[Union[str, Any], Any]) -> None

Set a node's attributes to a mapping of key labels to attribute values.

Parameter Type Description
new_attr dict[Union[str, Any], Any] Attribute storage mapping.
get_time -> float

Get the speciation time for this node. Closer to 0 implies a time closer to the origin (the root). A larger time implies a time closer to the present (leaves).

Returns: float: Speciation time, typically in coalescent units.
set_time(new_t: float) -> None

Set the speciation time for this node. The arg 't' must be a non-negative number.

Parameter Type Description
new_t float The new speciation/hybridization time for this node.
Raises: NodeError: If the new time is negative.
__str__ -> str

Create a string representation of a node.

Returns: str: A string representation of the node.
__eq__(other) -> bool

Equality comparison for Node objects. Two nodes are equal if they have the same name (identity). Note: This is based on node identity, not biological distance.

Parameter Type Description
other Another object to compare against
Returns: bool: True if both are Node objects with the same name
__hash__ -> int

Hash function for Node objects. Uses the node name for hashing to maintain consistency with equality.

Returns: int: Hash value based on the node name
to_string -> str

Create a description of a node and summarize its attributes.

Returns: str: A string description of the node.
set_name(new_name: str) -> None

Sets the name of the node to new_name.

Parameter Type Description
new_name str A new string label for this node.
set_is_reticulation(new_is_retic: bool) -> None

Sets whether a node is a reticulation Node (or not).

Parameter Type Description
new_is_retic bool Hybrid flag. True if this node is a reticulation node, false otherwise
is_reticulation -> bool

Retrieves whether a node is a reticulation Node (or not)

Returns: bool: True, if this node is a reticulation. False otherwise.
add_attribute(key: Any, value: Any) -> None

Put a key and value pair into the node attribute dictionary. If the key is already present, it will overwrite the old value.

Parameter Type Description
key Any Attribute key.
value Any Attribute value for the key.
attribute_value(key: Any) -> object

If key is a key in the attributes mapping, then its value will be returned. Otherwise, returns None.

Parameter Type Description
key Any A lookup key.
Returns: object: The value of key, if key is present.
set_seq(new_sequence: DataSequence) -> None

Associate a data sequence with this node, if this node is a leaf in a network.

Parameter Type Description
new_sequence DataSequence A data sequence wrapper. Grab from MSA object upon parsing.
get_seq -> DataSequence

Gets the data sequence associated with this node.

Returns: DataSequence: Data sequence wrapper.
Raises: NodeError: If no sequence record has been associated with this node.
copy -> Node

Duplicate this node by copying all data into a separate Node object. Useful for crafting copies of networks without having to deep copy.

Returns: Node: An equivalent node to this node, with all the same data but technically are not "=="

Edge

class Edge

Class for directed edges. Instead of being a wrapper for a "set" of member nodes, we can now think about an Edge as a wrapper for a tuple of member nodes (a, b), where now the direction is encoded in the ordering (where a is the source, and b the destination).

Properties

src -> Node property

Get the source node of this edge.

Returns: Node: The source node.
dest -> Node property

Get the destination node of this edge.

Returns: Node: The destination node.

Constructor

__init__(source: Node, destination: Node, length: float | None = None, gamma: float | None = None, weight: float | None = None, tag: str | None = None) -> None

An edge has a source (parent) and a destination (child). Edges in a phylogenetic context are *generally* directed. source -----> destination

Parameter Type Description
source Node The parent node.
destination Node The child node.
length float, optional Branch length value. Defaults to None.
gamma float, optional Inheritance Probability, MUST be from [0,1]. Defaults to None.
weight float, optional Edge weight, can be any real number. Defaults to None.
tag str, optional A name tag for identifiability of hybrid edges should each have a gamma of 0.5. Defaults to None.
Raises: ValueError: If @gamma is not a probabilistic value between 0 and 1 (inclusive, but if a hybrid edge pair has 0 and 1 then those hybrid edges may as well not exist)., EdgeError: If @length does not match the difference between @source.get_time() and @destination.get_time().

Methods

set_tag(new_tag: str) -> None

Set the name/identifiability tag of this edge.

Parameter Type Description
new_tag str a unique string identifier.
get_tag -> str

Get the name/identifiability tag for this edge.

Returns: str: The name/identifiabity tag for this edge. High change of being None!
__hash__ -> int

Hash function for Edge objects: a process-independent hash of the endpoint labels fixed at construction. Equality is identity.

Returns: int: The cached hash.
set_gamma(gamma: float) -> None

Set the inheritance probability of this edge. Only applicable to hybrid edges, but no warning will be raised if you attempt to set the probability of a non-hybrid edge.

Parameter Type Description
gamma float A probability (between 0 and 1 inclusive).
Raises: ValueError: If gamma is not between 0 and 1 inclusive.
get_gamma -> float

Gets the inheritance probability for this edge.

Returns: float: A probability (between 0 and 1).
copy(new_src: Node | None = None, new_dest: Node | None = None) -> Edge

Craft an identical edge to this edge object, just in a new object. Useful in building subnetworks of a network that is in hand.

Parameter Type Description
new_src Node | None, optional A new source node for this edge.
new_dest Node | None, optional A new destination node for this edge.
Returns: Edge: An identical edge to this one, with respect to the data they hold.
set_length(branch_length: float, warn_times: bool = False, enforce_times: bool = False) -> None

Set the branch length of this edge. If enforce_times is True, then the branch length must be equivalent to the difference in times of the source and destination nodes. If warn_times is True, then a warning will be raised if the branch length is not equivalent to the difference in times of the source and destination nodes.

Parameter Type Description
branch_length float The new branch length.
warn_times bool, optional If True, raises a warning if the branch length is not equivalent to the difference in times of the source and destination nodes. Defaults to False.
enforce_times bool, optional If True, raises an error if the branch length is not equivalent to the difference in times of the source and destination nodes. Defaults to False.
Raises: EdgeError: If enforce_times is True and the branch length is not equivalent to the difference in times of the source and destination nodes. Warning: If warn_times is True and the branch length is not equivalent to the difference in times of the source and destination nodes.
get_length -> float

Get the branch length of this edge.

Returns: float: The branch length of this edge.
set_weight(new_weight: float) -> None

Set the weight of this edge.

Parameter Type Description
new_weight float The new weight of this edge.
get_weight -> float

Get the weight of this edge.

Returns: float: The weight of this edge.
to_names -> tuple[str, str]

Get the names of the nodes in this edge.

Returns: tuple[str, str]: A tuple of the names of the nodes in this edge.
to_branch -> Branch

Convert this edge to a Branch object for use in phylogenetic computations.

Returns: Branch: A Branch with this edge's length, gamma, and source node label.

Network

class Network

A directed (and potentially acyclic) graph of Nodes joined by Edges. An 'Edge' object is a wrapper class for a tuple of two nodes, (a, b), where a and b are Node objects, and the direction of the edge is from a to b (a is b's parent) -- thus (a, b) is NOT the same as (b, a). Notes and Allowances: 1) You may create cycles -- however we have provided a method to check if this graph object is acyclic. This method is internally called on methods that assume that a network has no cycles, so be mindful of the state of networks that are passed as arguments. 2) You may have multiple roots. Be mindful of whether this graph is connected and what root you wish to operate on. 3) You may end up with floater nodes/edges, ie this may be an unconnected network with multiple connected components. We will p...

Constructor

__init__(edges: Union[EdgeSet, set[Edge], None] = None, nodes: Union[NodeSet, set[Node], None] = None, branch_length_unit: BranchLengthUnit | str | None = None) -> None

Initialize a Network object. You may initialize with any combination of edges/nodes, or provide none at all. If you provide edges and no nodes, each node present in those edges *WILL* be added to the network.

Parameter Type Description
edges EdgeSet | set[Edge], optional The edges of the network. Defaults to no edges.
nodes NodeSet | set[Node], optional The nodes of the network. Defaults to no nodes.
branch_length_unit Explicit unit carried by edge lengths. Graph operations accept ``UNSPECIFIED``; biological calculations require a concrete unit.
Raises: TypeError: If any provided edge is not an Edge object.

Methods

begin_transaction -> None

Start recording every change to this network so it can be undone. While a transaction is open, each node and edge added or removed, each rename, and each change to a node's time or reticulation flag or an edge's length, gamma, weight or tag is journaled with its inverse. :meth:`rollback_transaction` replays the inverses and restores the network exactly, same objects included; :meth:`commit_transaction` discards the journal. Transactions nest: an inner commit folds its journal into the outer one, an inner rollback undoes only the inner changes. This is the general form of "mutate, evaluate, maybe revert". A search move can be undone without cloning the network first, and code that tries a candidate edit in place can roll it back instead of working on a copy. Changes made through ``Node.set_name`` directly, through the attribute dictionaries, or by touching the underlying node and edge sets are not journaled; use :meth:`update_node_name` and the network methods.

in_transaction -> bool

Whether a transaction is open on this network.

Returns: bool: True between :meth:`begin_transaction` and the matching commit or rollback.
commit_transaction -> None

Keep the changes of the innermost open transaction. A no-op when no transaction is open, so a driver can call it on acceptance without knowing whether the move used a transaction.

rollback_transaction -> None

Undo every change of the innermost open transaction. The inverses are replayed newest first with journaling suspended, so the network returns to the state at :meth:`begin_transaction` with the same node and edge objects. A no-op when no transaction is open.

__contains__(obj: Union[Node, Edge]) -> bool

Allows a simple pythonic "n in network" or "e in network" check.

Parameter Type Description
obj Node | Edge A node or edge.
Returns: bool: True if obj is a node or edge in the network.
Raises: TypeError: If @obj is neither a Node nor an Edge.
add_nodes(*nodes: Union[Node, list[Node]]) -> None

Add any amount of nodes to this network. Accepts nodes as separate arguments, as lists, or as a mixture of both.

add_uid_node(node: Union[Node, None] = None) -> Node

Ensure a node has a unique name that hasn't been used before/is not currently in use for this graph. May be used with a node that is or is not yet an element of V. The node will be added to V as a result of this function.

Parameter Type Description
node Node | None Any node object. Defaults to None.
Returns: Node: the added/edited node that has been added to the graph.
uid_count -> int

Return the current value of the unique-id counter used by :meth:`add_uid_node`. Structural copies (see :meth:`Network.copy`) must carry this counter forward so that regenerated ``UID_*`` node names never collide with names already present in the graph.

Returns: int: The next unique id that :meth:`add_uid_node` will use.
get_branch_length_unit -> BranchLengthUnit

Return the unit attached to this network's edge lengths.

set_branch_length_unit(unit: BranchLengthUnit | str) -> None

Tag edge lengths with an explicit unit without rescaling them.

set_uid_count(value: int) -> None

Set the unique-id counter used by :meth:`add_uid_node`.

Parameter Type Description
value int The value to assign to the counter.
V -> list[Node]

Get all nodes in V.

Returns: list[Node]: the set V, in list form.
E -> list[Any]

Get the set E (in list form).

Returns: list[Edge]: The list of all edges in the graph
get_item(key: str) -> object

Access the blob storage with a key. CONSIDER REMOVAL OF THIS FUNCTION...

Parameter Type Description
key str a string key to access the blob storage
Returns: object: the object stored in the blob storage
put_item(key: str, item: Any) -> None

Add an item to the blob storage.

Parameter Type Description
key str a string key to access the blob storage
item Any the object to store in the blob storage
has_node_named(name: str) -> Union[Node, None]

Check whether the graph has a node with a certain name. Strings must be exactly equal (same white space, capitalization, etc.)

Parameter Type Description
name str the name to search for
Returns: Node | None: the node with the given name, or None if there is no such node
in_degree(node: Node) -> int

Get the in-degree of a node.

Parameter Type Description
node Node A node in V
Returns: int: the in degree count
out_degree(node: Node) -> int

Get the out-degree(number of edges where the given node is a parent) of a node in the graph.

Parameter Type Description
node Node a node in V
Returns: int: the out-degree count
in_edges(node: Node) -> list[Any]

Get the in-edges of a node in V. The in-edges are the edges in E, where the given node is the child.

Parameter Type Description
node Node a node in V
Returns: list[Any]: the list of in-edges
out_edges(node: Node) -> list[Any]

Get the out-edges of a node in V. The out-edges are the edges in E, where the given node is the parent.

Parameter Type Description
node Node a node in V
Returns: list[Any]: the list of out-edges
from_newick(newick: str, branch_length_unit: BranchLengthUnit | str | None = None) -> Network @classmethod

Construct a Network object by passing in a newick string and parsing out the topology from there.

Parameter Type Description
newick str An extended newick string.
branch_length_unit Unit represented by parsed branch lengths.
Returns: Network: An initialized network object
add_edges(edges: Union[Edge, list[Edge]]) -> None

If edges is a list of Edges, then add each Edge to the list of edges. If edges is a singleton Edge then just add to the edge array. Note: Each edge that you attempt to add must be between two nodes that exist in the network. Otherwise, an error will be thrown.

Parameter Type Description
edges Edge | list[Edge] a single edge, or multiple.
Raises: NetworkError: if input edge/edges are malformed in any way
remove_nodes(node: Node) -> None

Removes node from the list of nodes. Also prunes all edges from the graph that are connected to the node. Has no effect if node is not in this network.

Parameter Type Description
node Node a Node obj
remove_edge(edge: Union[Edge, list[Node]], gamma: float | None = None) -> None

Removes edge from the list of edges. Does not delete nodes with no edges Has no effect if 'edge' is not in the graph.

Parameter Type Description
edge Edge | list[Node] an edge to remove from the graph
gamma float an inheritance probability from [0,1], if the edge is provided as a list of nodes, and there is an identifiability issue that needs resolving (ie, the edge that needs to be removed is a bubble edge). Optional. Defaults to None.
Raises: NetworkError: If 'edge' is neither an Edge nor a [src, dest] pair.
update_node_name(node: Node, name: str) -> None

Rename a node and update *all* bookkeeping (NodeSet, EdgeSet, leaf/root sets). Node.__hash__ is name-based, so the node must be pulled out of every hash-keyed collection *before* the rename and put back *after*.

Parameter Type Description
node Node a node in the graph
name str the new name for the node.
get_edge(n1: Node, n2: Node, gamma: float | None = None, tag: str | None = None) -> Edge

Note, that in the event of bubbles, 2 edges will exist with the same source and destination. If this is possible, please supply the inheritance probability of the correct branch. If both edges are known to be identical (gamma = 0.5), then one will be chosen at random.

Parameter Type Description
n1 Node parent node
n2 Node child node
gamma float inheritance probability. Optional. Defaults to None
tag str A name/identifiability tag for hybrid edges should both gammas be = .5. Optional. Defaults to None.
Returns: Edge: the edge containing n1 and n2 and has the proper gamma value (if applicable).
root -> Node

Return the root of the Network. Phylogenetic networks only have one root, but for generality and practical use, multiple roots have been allowed. To get all roots, should multiple exist, call the function "roots". This function only returns 1 root.

Returns: Node: The root of the network.
Raises: NetworkError: If there are no roots in the network (cycle, or empty), or if there are multiple roots in the network.
roots -> list[Node]

Return all root(s) of the Network. Phylogenetic networks typically have one root, but for generality and practical use, multiple roots have been allowed. Use ``root()`` to retrieve a single root.

Returns: list[Node]: A list of all root nodes (nodes with in-degree 0 and out-degree > 0).
get_leaves -> list[Node]

Returns the set X (a subset of V), the set of all leaves (nodes with out-degree 0). Only returns the leaves that are connected/reachable from the root.

Returns: list[Node]: the connected elements of X, in list format.
get_parents(node: Node) -> list[Node]

Returns a list of the parents of a node. There is no hard cap on the length of this array.

Parameter Type Description
node Node any node in V.
Returns: list[Node]: the parents of the node.
Raises: NetworkError: If the node is not in the graph.
get_children(node: Node) -> list[Node]

Returns a list of the children of a node. There is no hard cap on the length of this array.

Parameter Type Description
node Node any node in V.
Returns: list[Node]: the children of the node.
Raises: NetworkError: If the node is not in the graph.
get_branches(node: Node) -> dict[str, Any]

Returns a dictionary of branches connected to the node.

Parameter Type Description
node Node a node in the graph.
Returns: dict[str, Any]: a dictionary of branches connected to the node. The keys are "parent_branches" and "child_branches". The values are lists of branches.
clean(options: list[bool] = [True, True, True]) -> None

All the various ways that the graph can be cleaned up and streamlined while not altering topology or results of algorithms. Algorithm Indeces: 0) Remove nodes that have in/out degree of 0 (floater nodes) 1) Remove a spurious root/root edge (root node with only one out edge) 2) Consolidate all chains of nodes with in/out degree of 1 into 1 edge. Default behavior is to run all three. To not run a certain routine, set the options list at the indeces listed above to False. Ie. To run the first and third algo, use [True, False, True].

Parameter Type Description
options list[bool], optional A list of booleans that signal which algorithms to run. Defaults to [True, True, True].
mrca(set_of_nodes: set[Node] | set[str]) -> Node

Computes the Least Common Ancestor of a set of graph nodes.

Parameter Type Description
set_of_nodes set[Node] | set[str] A set of Nodes, or node names.
Returns: Node: The node that is the LCA of the set.
Raises: NetworkError: If any node in the set is not in the graph, or if elements are of an unexpected type.
leaf_descendants(node: Node) -> set[Node]

Compute the set of all leaf nodes that are descendants of the parameter node. Uses DFS to find paths to leaves.

Parameter Type Description
node Node The node for which to compute leaf children.
Returns: set[Node]: The set of all leaves that descend from 'node'.
Raises: NetworkError: If node is not found in the graph.
diff_subtree_edges(rng: np.random.Generator) -> list[Edge]

Returns 2 random edges such that there does not exist a directed path from one edge source node to the other edge source node.

Parameter Type Description
rng np.random.Generator an rng object.
Returns: list[Edge]: a list of 2 edges such that neither edge is reachable from either starting point.
subgenome_count(n: Node) -> int

Given a node in this graph, return the subgenome count.

Parameter Type Description
n Node Any node in the graph. It is an error to input a node that is not in the graph.
Returns: int: subgenome count
Raises: NetworkError: If the input node is not in the graph.
edges_downstream_of_node(n: Node) -> list[Edge]

Returns the set (as a list) of edges that are in the subgraph of a node.

Parameter Type Description
n Node A node in a graph.
Returns: list[Edge]: The set of all edges in the subgraph of n.
Raises: NetworkError: If the input node is not in the graph.
edges_upstream_of_node(n: Node) -> list[Edge]

Returns the set (as a list) of edges that are in all paths from the root to this node. Useful in avoiding the creation of cycles when adding edges.

Parameter Type Description
n Node A node in a graph.
Returns: list[Edge]: The set of all edges on paths from the root to n.
Raises: NetworkError: If the input node is not in the graph.
subgenome_ct_edges(downstream_node: Union[Node, None] = None, delta: float = math.inf, start_node: Union[Node, None] = None) -> dict[Edge, int]

Maps edges to their subgenome counts.

Parameter Type Description
downstream_node Node | None, optional No edges will be included in the map that are in a subgraph of this node. Defaults to None.
delta float, optional Only include edges in the mapping that have subgenome counts <= delta. Defaults to math.inf.
start_node Node | None, optional Provide a node only if you don't want to start at the root. Defaults to None.
Returns: dict[Edge, int]: a map from edges to subgenome counts
Raises: NetworkError: If the graph has more than one root to start.
edges_to_subgenome_count(downstream_node: Union[Node, None] = None, delta: float = math.inf, start_node: Union[Node, None] = None) -> dict[int, list[Edge]]

Maps edges to their subgenome counts.

Parameter Type Description
downstream_node Node | None, optional No edges will be included in the map that are in a subgraph of this node. Defaults to None.
delta float, optional Only include edges in the mapping that have subgenome counts <= delta. Defaults to math.inf.
start_node Node | None, optional Provide a node only if you don't want to start at the root. Defaults to None.
Returns: dict[int, list[Edge]]: a map from edges to subgenome counts
Raises: NetworkError: If the graph has more than one root to start.
leaf_descendants_all -> dict[Node, set[Node]]

Map each node in the graph to its set of leaf descendants

Returns: dict[Node, set[Node]]: map from graph nodes to their leaf descendants
newick(annotate: bool = False) -> str

Generate the newick string of the network.

Parameter Type Description
annotate bool, optional If True, branch lengths (``:len``) and inheritance probabilities (``[&gamma=g]``) are written alongside the topology. Defaults to False.
Returns: str: The newick representation of the network.
is_acyclic -> bool

Checks if each of this graph's connected components is acyclic

Returns: bool: True if acyclic, False if cyclic.
bfs_dfs(start_node: Union[Node, None] = None, dfs: bool = False, is_connected: bool = False, accumulator: Callable[..., None] | None = None, accumulated: Any = None) -> tuple[dict[Node, int], Any]

General bfs-dfs routine, with the added utility of checking whether or not this graph is made up of multiple connected components.

Parameter Type Description
start_node Node | None, optional Give a node to start the search from. Defaults to None, in which case the search will start at the root.
dfs bool, optional Flag that specifies whether to use bfs or dfs. Defaults to False (bfs), if true is passed, will run dfs.
is_connected bool, optional Flag that, if enabled, will check for the connected component status. Defaults to False (won't run).
accumulator Callable[..., None] | None, optional A function that takes the currently searched Node in the graph and does some sort of bookkeeping.
accumulated Any Any type of structure that stores the data given by the accumulator function.
Returns: tuple[dict[Node, int], Any]: Mapping from nodes to their distance from the start node.
subnet(retic_node: Node) -> Network

Make a copy of a subnetwork of this DAG, rooted at 'retic_node', with unique node names.

Parameter Type Description
retic_node Node A node in this network that is a reticulation node
Returns: Network: A subnetwork of the DAG being operated on
copy -> tuple[Network, dict[Node, Node]]

Copy this network into a new network object, also with new node and edge objects.

Returns: tuple[Network, dict[Node, Node]]: A tuple of the copied network and a map from old nodes to new nodes.
graft_subtree(subtree: Network, sibling_of: Node | None = None, under: Node | None = None) -> Node

Copy ``subtree`` into this network and attach it. Internal labels that already occur here are replaced with fresh ones. Leaf labels are kept, and a leaf label that is already present is an error: grafting must not duplicate a taxon. The copy is attached either by splitting the edge above ``sibling_of`` or as a new child of ``under``. If ``sibling_of`` is the root, there is no edge to split. A new root is created with the old root and the grafted subtree as its two children, so the grafted leaves are not dropped.

Parameter Type Description
subtree Network The subtree to copy in. Its own root is the node that becomes the attachment point.
sibling_of Node | None A node of this network. The subtree becomes its sibling.
under Node | None A node of this network. The subtree becomes a new child of it.
Returns: Node: The image, in this network, of ``subtree``'s root.
Raises: NetworkError: If neither or both of ``sibling_of`` and ``under`` are given, if the anchor is not in this network, or if a leaf label of ``subtree`` is already present.
to_networkx -> nx.Graph

Convert this network to a NetworkX graph object.

Returns: nx.Graph: A NetworkX graph object.
is_isomorphic(other: Network) -> bool

Check if this network is topologically isomorphic to another network. Two networks are isomorphic if they have the same topology, regardless of node labels or branch lengths. This method calls the GraphUtils.is_isomorphic function.

Parameter Type Description
other Network The other network to compare against.
Returns: bool: True if the networks are topologically isomorphic, False otherwise.
rooted_triplet_distance(other: Network) -> float

Computes the rooted triplet distance between two networks. This distance measure compares the topological relationships between all triplets of leaves in both networks. For each triplet of leaves {x, y, z}, the pair sharing the deepest MRCA are identified as siblings, producing a canonical encoding. The distance is the normalized symmetric difference of these triplet sets.

Parameter Type Description
other Network The other network to compare against.
Returns: float: The rooted triplet distance (0 = identical, 1 = completely different).
joint_dissimilarity(other: Network, kind: str = 'nakhleh') -> 'JointDissimilarityResult'

The joint reticulation-and-tree dissimilarity between this network and another on the same taxon set: a minimum-cost matching of the reticulation tripartitions (``D_ret``) plus three times the dissimilarity of the two remainders left once every reticulation is removed (``D_tree``). See :mod:`~phynetpy.JointDissimilarity` for the definition; this method calls ``JointDissimilarity.joint_dissimilarity``.

Parameter Type Description
other Network The other network to compare against.
kind str Structure dissimilarity used on blocks and
remainders ``"leaf"``, ``"cluster"`` or ``"nakhleh"`` (default).
Returns: JointDissimilarityResult: ``r1``, ``r2``, ``D_ret``, ``D_tree`` and the derived ``m``, ``D_joint``, ``D_ret_normalized``, ``D_joint_normalized``.
Raises: NetworkError: If either network is not a valid rooted binary- reticulation network, or the taxon sets differ., ValueError: If ``kind`` is unknown.
get_subtree_at(node: Node) -> set[Node]

Collect all nodes in the subtree rooted at the given node.

Parameter Type Description
node Node The root of the subtree.
Returns: set[Node]: A set of nodes in the subtree.
dist_from_root(node: Node) -> int

Get the distance from the root to the given node, measured in edge count (hop count) via BFS.

Parameter Type Description
node Node A node in this network.
Returns: int: The number of edges on the BFS-shortest path from the root to the given node.
topological_order -> list[Node]

Compute a topological order of nodes in an acyclic network.

Returns: list[Node]: Nodes in topological order from roots to leaves.
Raises: NetworkError: If the network contains a directed cycle and no valid topological order exists.
distance_from_root(node: Node, use_time: bool = True) -> float

Compute distance from root to a given node.

Parameter Type Description
node Node The target node
use_time bool If True, use branch lengths/times. If False, use edge count.
Returns: float: Distance from root (time units or edge count)
Raises: NetworkError: If node is not in the network or no path to root exists
set_node_times_from_root -> None

Set time attributes for all nodes based on their distance from root. Uses cumulative branch lengths from root. Useful for enabling biologically meaningful node comparisons. The root node is assigned time 0.0 and each descendant's time is the sum of branch lengths along the BFS path from the root.

Returns: None
set_node_times_by_edge_count -> None

Set time attributes for all nodes based on their edge count from root. This provides biologically meaningful comparison when actual times are not available. Edge counts are converted to time values for comparison purposes. The root node is assigned time 0.0 and each descendant's time equals the number of edges on the BFS path from the root.

Returns: None

MUL

class MUL(Network)

A subclass of a Network, that is a binary tree that results from the transformation of a standard network into a Multilabeled Species Tree.

Constructor

__init__(gene_map: dict[str, list[str]], rng: np.random.Generator) -> None

Initializes a MUL object.

Parameter Type Description
gene_map dict[str, list[str]] A mapping from gene names to a set of gene copy names.
rng np.random.Generator A numpy random number generator.

Methods

to_mul(net: Network) -> Network

Creates a (MU)lti-(L)abeled Species Tree from a network

Parameter Type Description
net Network A Network
Returns: Network: a MUL tree (as a Network obj)
Raises: NetworkError: If the network is malformed with regards to ploidy

Module Functions

stable_hash(text: str) -> int

A hash of ``text`` that is the same in every Python process. Python salts ``hash(str)`` per process, so collections keyed by node names (and anything that iterates them: candidate lists in search moves, the merger's edge scans) came out in a different order on every run, and fixed-seed searches were not reproducible. This is 64-bit FNV-1a: cheap, well spread, and process independent. Node and Edge hashes are computed from it once and cached.

Parameter Type Description
text str The string to hash.
Returns: int: A 64-bit hash.

Navigation

Modules

This Page