utils¶
Utility functions and helpers.
phylogenetic_trees
¶
Auxiliary functions for phylogentic trees.
Phylogenetic trees are usually defined as trees where every inner node has at least two children.
However, the class Tree does not force this property. Simulated trees are often 'planted', i.e.,
the root has only a single child, and this edge represents the ancestral lineage.
node_to_str(node: TreeNode) -> str
¶
String representation of a node in a phylogenetic tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
TreeNode
|
A TreeNode object representing a node in a phylogenetic tree. The node is expected to have attributes 'label', 'reconc', and 'dist'. |
required |
Returns:
| Type | Description |
|---|---|
str
|
String representation of the node including reconc (if defined) and dist. |
Source code in asymmetree/utils/phylogenetic_trees.py
sorted_nodes(tree: Tree, oldest_to_youngest: bool = True) -> list[TreeNode]
¶
List of nodes sorted by timestamp.
Return a list of all nodes in the tree sorted by time stamp beginning with the oldest (highest
time stamp). Optionally the order can be reversed by setting oldest_to_youngest to False.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
A phylogenetic tree with nodes that have a |
required |
oldest_to_youngest
|
bool
|
If True, the nodes are sorted from oldest to youngest, otherwise from youngest to oldest. |
True
|
Returns:
| Type | Description |
|---|---|
list[TreeNode]
|
Nodes sorted by their timestamp. |
Source code in asymmetree/utils/phylogenetic_trees.py
sorted_edges(tree: Tree) -> list[tuple[TreeNode, TreeNode]]
¶
List of edges (u,v) sorted by timestamp of u.
Return a list of all edges (u,v) sorted by timestamp of u beginning with the oldest (highest time stamp).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
A phylogenetic tree with nodes that have a |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[TreeNode, TreeNode]]
|
Edges sorted by their timestamp. |
Source code in asymmetree/utils/phylogenetic_trees.py
distance_from_timing(tree: Tree) -> None
¶
Adjusts all distances according to the time stamp difference.
The distance of an edge (u,v) is set to the absolute difference of the time stamps of u and v,
i.e., dist = abs(u.tstamp - v.tstamp).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
A phylogenetic tree with nodes that have a |
required |
Source code in asymmetree/utils/phylogenetic_trees.py
delete_and_reconnect(tree: Tree, node: TreeNode, add_distances: bool = True, keep_transferred: bool = True) -> TreeNode | None
¶
Delete a node from the tree and reconnect its parent and children.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
A phylogenetic tree. |
required |
node
|
TreeNode
|
The node in the tree to be deleted. |
required |
add_distances
|
bool
|
When the node v is deleted and its children are reconnected to its parent,
add to the |
True
|
keep_transferred
|
bool
|
When the edge of the deleted node v from its parent u was a transfer edge, make all edges from u to the children of v transfer edges. |
True
|
Returns:
| Type | Description |
|---|---|
TreeNode | None
|
The parent of the node, if it could be deleted, or None, if the node could not be deleted, i.e., it has no parent. |
Source code in asymmetree/utils/phylogenetic_trees.py
add_planted_root(tree: Tree) -> TreeNode
¶
Add a new root that has the original root as its single child.
A tree is called planted if the root has only a single child. This is often the case for simulated trees where the edge from the planted root to its child represents the ancestral lineage. This function adds a planted root to a tree that does not have one yet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
A phylogenetic tree. |
required |
Returns:
| Type | Description |
|---|---|
TreeNode
|
The newly added planted root. |
Source code in asymmetree/utils/phylogenetic_trees.py
reconc_sorted_leaves(tree: Tree, return_list: bool = False) -> dict | tuple[dict, list]
¶
Sort leaves by their reconciliation attribute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
A tree with nodes that have a |
required |
return_list
|
bool
|
If True, also return a list of leaves such that leaves of the same reconciliation appear as a coherent sequence. |
False
|
Returns:
| Type | Description |
|---|---|
dict | tuple[dict, list]
|
A dictionary with reconciliations as keys and a list of corresponding nodes as values. If
|
Source code in asymmetree/utils/phylogenetic_trees.py
distance_matrix(tree: Tree, leaf_order: list[TreeNode] | None = None) -> tuple[list[TreeNode], np.ndarray]
¶
Distance matrix on the leaf set of the phylogenetic tree.
Computes a distance matrix on the set of leaves of the tree where each distances is the sum of
the distances (dist) on the path connecting the pair of leaves.
Additionally a list of leaves corresponding to the indices in the matrix is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
A tree with nodes that have a |
required |
leaf_order
|
list[TreeNode] | None
|
A list of all leaves in the tree defining the indices for the matrix. The default is None, in which case leaves are indexed in sibling order. |
None
|
Returns:
| Type | Description |
|---|---|
list[TreeNode]
|
A list of TreeNode objects representing the order for the lines/columns in the distance matrix. |
ndarray
|
An array representing the distance matrix. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in asymmetree/utils/phylogenetic_trees.py
distances_from_root(tree: Tree) -> dict[TreeNode, float]
¶
The distances of each node to the root of the tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
A tree with nodes that have a |
required |
Returns:
| Type | Description |
|---|---|
dict[TreeNode, float]
|
A dictionary where the keys are TreeNode objects and the values are their distances (sum of
|
Source code in asymmetree/utils/phylogenetic_trees.py
topology_only(tree: Tree, inplace: bool = True) -> Tree
¶
Reset reconciliations, distances, time stamps, transfer status, and inner labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
A tree. |
required |
inplace
|
bool
|
If True, reset the attributes of this tree instance, otherwise make a copy first and modify the copy. |
True
|
Returns:
| Type | Description |
|---|---|
Tree
|
The original or a copy of the tree instance with reset attributes. |
Source code in asymmetree/utils/phylogenetic_trees.py
count_node_types(tree: Tree) -> dict[str, int]
¶
Count speciations, duplication, losses, HGTs and surviving genes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
A tree with nodes that have an |
required |
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
A dictionary with the event counts as values. Keys are 'S' (speciations), 'D' (duplication), 'L' (losses), 'H' (HGTs) and 'extant' (surviving genes). |
Source code in asymmetree/utils/phylogenetic_trees.py
random_colored_tree(n: int, colors: int | list, binary: bool = False, force_all_colors: bool = False) -> Tree
¶
Create a random colored tree.
The number of leaves and the reconciliation labels are specified in the parameters n and colors,
respectively. Each non-leaf node in the resulting tree will have at least two children (property
of phylogenetic trees).
The colors (attribute reconc) are assigned to the leaves at random. If force_all_colors is
True, the resulting tree is guaranteed to have at least one leaf of each reconciliation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
The desired number of leaves. |
required |
colors
|
int | list
|
The list of recociliations, or the desired number in which case the reconciliations {1, ..., colors} are used. |
required |
binary
|
bool
|
If True, forces the tree to be binary (the default is False). |
False
|
force_all_colors
|
bool
|
If True, the resulting tree is guaranteed to have at least one leaf of each reconciliation (the default is False). |
False
|
Returns:
| Type | Description |
|---|---|
Tree
|
A random tree with n leaves to which the |
Raises:
| Type | Description |
|---|---|
TypeError
|
If n is not an integer > 0. |
ValueError
|
If the number of colors is greater than n and |
Source code in asymmetree/utils/phylogenetic_trees.py
random_ultrametric_timing(tree: Tree, inplace: bool = False, adjust_distances: bool = False) -> Tree
¶
Generate a random ultrametric timing for the tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
The tree for which a random timing shall be generated. |
required |
inplace
|
bool
|
If True, the input tree is modified, otherwise a copy is returned. |
False
|
adjust_distances
|
bool
|
If True, also adjust the dist attribute of the tree nodes to match the
differences of the |
False
|
Returns:
| Type | Description |
|---|---|
Tree
|
A random tree whose nodes have |
Source code in asymmetree/utils/phylogenetic_trees.py
phylo_tree_attributes(tree: Tree, inplace: bool = True) -> Tree
¶
Add the attributes for a phylogentic tree if not already set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
The tree for which attributes shall be added. |
required |
inplace
|
bool
|
If True, the input tree is modified, otherwise a copy is returned. |
True
|
Returns:
| Type | Description |
|---|---|
Tree
|
The tree with added attributes. |
Source code in asymmetree/utils/phylogenetic_trees.py
assign_missing_labels(tree: Tree) -> None
¶
Assign integer label to nodes with no or missing label.
Also assign the number_of_species attribute (i.e., the number of leaves) to the tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
A tree with some nodes that have no or missing label. |
required |
Source code in asymmetree/utils/phylogenetic_trees.py
reconstruct_reconc_from_graph(tree: Tree, G: nx.Graph | nx.DiGraph) -> None
¶
Reconstruct the reconciliations from a NetworkX Graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
A tree for which reconciliations shall be reconstructed. |
required |
G
|
Graph | DiGraph
|
The graph from which labels and reconciliations shall be reconstructed. |
required |
Source code in asymmetree/utils/phylogenetic_trees.py
reconstruct_timestamps(tree: Tree) -> None
¶
Reconstruct the timestamps.
Make the time stamps matching with the distance attribute. The root obtains time stamp 1.0, and
all other nodes obtain smaller time stamps such that the difference to the parent's time stamp
is exactly dist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
A tree with nodes that have a |
required |
Source code in asymmetree/utils/phylogenetic_trees.py
delete_losses_and_contract(tree: Tree, inplace: bool = False) -> Tree
¶
Delete all branches leading to loss leaves only.
Nodes that would have only a single child afterwards are suppressed (except possibly the planted root), i.e. their children are recursively reconnected to the parents. Distances are cumulated in this process and the transferred status is kept in the sense that an edge is a transfer edge if at least one edge on the contracted path to which it corresponds was a transfer edge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
The tree in which loss branches shall be removed. |
required |
inplace
|
bool
|
If True, the tree is directly manipulated. The default is False in which case a copy of the tree is created which gets manipulated while the original tree remains untouched. |
False
|
Returns:
| Type | Description |
|---|---|
Tree
|
The tree with all loss branches removed (original instance or a new one depending on the
|
Source code in asymmetree/utils/phylogenetic_trees.py
remove_planted_root(tree: Tree, inplace: bool = True) -> Tree
¶
Remove the planted root of the tree (if existent).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
Tree
|
The tree in which the planted root shall be removed. |
required |
inplace
|
bool
|
If True, the tree is directly manipulated, otherwise a copy is created and the original tree remains untouched. |
True
|
Returns:
| Type | Description |
|---|---|
Tree
|
The tree with the planted root removed (original instance or a new one depending on the
|
Source code in asymmetree/utils/phylogenetic_trees.py
to_newick(tree: Tree, label: bool = True, reconc: bool = True, distance: bool = True, label_inner: bool = True, reconc_inner: bool = False) -> str
¶
Return a Newick representation of the tree.
The Newick string can contain the labels, reconciliations and distances of the nodes. The labels and reconciliations of the inner nodes can optionally be included as well. The reconciliations are included in <...> brackets, and the distances are included in :... notation as usual. By default, labels, reconciliations and distances of all nodes are included with the exception of the reconciliations of the inner nodes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
bool
|
If True, the Newick str contains the labels of the nodes. |
True
|
reconc
|
bool
|
If True, the Newick str contains the reconciliations of the nodes in <[...]> brackets. |
True
|
distance
|
bool
|
If True, the Newick str contains the distances of the nodes in standard :[...] notation. |
True
|
label_inner
|
bool
|
If True, the Newick str also contains the labels of the inner nodes. |
True
|
reconc_inner
|
bool
|
If True, the Newick str contains the reconciliations of the inner nodes. |
False
|
Returns:
| Type | Description |
|---|---|
str
|
A Newick representation of the tree. |
Source code in asymmetree/utils/phylogenetic_trees.py
parse_newick(newick: str) -> Tree
¶
Parses trees in Newick format into object of type Tree.
This function parses trees in Newick format into object of type Tree. The Newick string may
contain labels, reconciliations and distances of the nodes. The reconciliations are expected to
be included in <...> brackets, and the distances are expected to be included in :... notation as
usual. The labels and reconciliations of the inner nodes can optionally be included as well.
Labels and reconciliations that are integer numbers are converted to int. The reconciliations
(if present in <...> in the string) are parsed as strings and need to be converted to integers
afterwards if necessary.
NOTE: Do not use this function for serialization and reloading Tree objects. Use the
serialize() function instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
newick
|
str
|
A tree in Newick format. |
required |
Returns:
| Type | Description |
|---|---|
Tree
|
The parsed tree. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the input is not a string. |
ValueError
|
If the input is not a valid Newick string. |
Source code in asymmetree/utils/phylogenetic_trees.py
distance_calculation
¶
Calculation of sequence distances for various models.
The distance between two sequences is defined as the expected number of substitutions per site that have occurred since the two sequences diverged from their common ancestor. This module provides functions to calculate distances under various substitution models, including the Jukes-Cantor 1969 model, the Kimura 1980 model, and maximum likelihood distances under general substitution models.
References
- Z. Yang. Computational molecular evolution. Oxford series in ecology and evolution. Oxford University Press, 2006. ISBN 978-0-19-856699-1 978-0-19-856702-8.
maximum_likelihood_distance(seq1: str, seq2: str, subst_model: SubstModel = None, model_type: str | None = None, model_name: str | None = None) -> float
¶
Calculate the maximum likelihood distance between two aligned sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seq1
|
str
|
First aligned sequence. |
required |
seq2
|
str
|
Second aligned sequence. |
required |
subst_model
|
SubstModel
|
Substitution model to use for distance calculation. If None, model_type and model_name must be provided to construct a SubstModel instance. |
None
|
model_type
|
str | None
|
Type of substitution model (e.g., "n" for nucleotide, "a" for amino acid). Required if subst_model is None. |
None
|
model_name
|
str | None
|
Name of substitution model (e.g., "JC69", "K80"). Required if subst_model is None. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Estimated distance between the two sequences under the specified substitution model. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If subst_model is None and either model_type or model_name is not provided. |
Source code in asymmetree/utils/distance_calculation.py
p_distance(seq1: str, seq2: str, exclude_gaps: bool = True) -> tuple[float, int]
¶
Calculate the p-distance of two aligned sequences (normalized Hamming distance).
The p-distance is the proportion of sites at which the two sequences differ. It equals the Hamming distance divided by the number of valid columns (i.e., columns without gaps if exclude_gaps is True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seq1
|
str
|
First aligned sequence. |
required |
seq2
|
str
|
Second aligned sequence. |
required |
exclude_gaps
|
bool
|
If True, columns with a gap in one sequence are ignored. Columns with gaps in both sequences are always ignored. |
True
|
Returns:
| Type | Description |
|---|---|
float
|
The p-distance. |
int
|
The number of valid columns used in the calculation. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input sequences have different lengths. |
Source code in asymmetree/utils/distance_calculation.py
JC69_distance(seq1: str, seq2: str, exclude_gaps: bool = True, amino_acid: bool = False, variance: bool = False) -> float | tuple[float, float]
¶
Jukes Cantor 1969 distance.
The Jukes-Cantor 1969 model assumes equal base frequencies and equal substitution rates among all nucleotides.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seq1
|
str
|
First aligned sequence. |
required |
seq2
|
str
|
Second aligned sequence. |
required |
exclude_gaps
|
bool
|
If True, columns with a gap in one sequence are ignored. Columns with gaps in both sequences are always ignored. |
True
|
amino_acid
|
bool
|
If True, the distance is calculated under the Jukes-Cantor model for amino acids, which assumes equal frequencies and substitution rates among all amino acids. |
False
|
variance
|
bool
|
If True, also calculate the variance of the distance estimate. |
False
|
Returns:
| Type | Description |
|---|---|
float | tuple[float, float]
|
If |
Source code in asymmetree/utils/distance_calculation.py
K80_distance(seq1: str, seq2: str, variance: bool = False) -> tuple[float, float] | tuple[float, float, float]
¶
Kimura 1980 distance and transition/transversion ratio.
The Kimura 1980 model distinguishes between transitions (substitutions between purines or pyrimidines) and transversions (substitutions between a purine and a pyrimidine). It assumes equal base frequencies and equal substitution rates among all nucleotides, but allows for different rates between transitions and transversions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seq1
|
str
|
First aligned sequence. |
required |
seq2
|
str
|
Second aligned sequence. |
required |
variance
|
bool
|
If True, also calculate the variance of the distance estimate. |
False
|
Returns:
| Type | Description |
|---|---|
tuple[float, float] | tuple[float, float, float]
|
If |
Source code in asymmetree/utils/distance_calculation.py
sampling
¶
Module for sampling from various distributions.
The Sampler class allows sampling from a variety of distributions, including constant, uniform,
discrete uniform, gamma, exponential, zipf, and negative binomial distributions. The class also
supports specifying minimum and maximum values for the samples, as well as shifting the distribution
along the x-axis.
Sampler
¶
Sampling from a variety of distributions.
Source code in asymmetree/utils/sampling.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | |
__init__(params: int | float | tuple | list, minimum: int | float | None = None, maximum: int | float | None = None, discrete: bool = False, shift: int | float = 0) -> None
¶
Construct a Sampler object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
int | float | tuple | list
|
The distribution and its parameters, see documentation for available options. |
required |
minimum
|
int | float | None
|
Minimum value to be sampled. |
None
|
maximum
|
int | float | None
|
Maximum value to be sampled. |
None
|
discrete
|
bool
|
If True, round sampled values in case of a continuous distribution. |
False
|
shift
|
int | float
|
Shift distribution along x-axis. The default is 0, i.e., the distribution is not shifted. |
0
|
Source code in asymmetree/utils/sampling.py
__call__() -> int | float
¶
Draw a value from the specified distribution.
Returns:
| Type | Description |
|---|---|
int | float
|
A value drawn from the specified distribution, which is an |