PhyNetPy Documentation

Library for the Development and Use of Phylogenetic Network Methods

infer Module v0.6.0

The public inference API: the verbs infer, score, and simulate, the InferenceResult they return, plus the registry, scorers, kernels, result types, and MCMC diagnostics around them.

Author:
Mark Kessler
Source:
infer.py

InferenceResult

class InferenceResult

Uniform return type for :func:`infer`. The return type does not change with the criterion: a point estimate (ML, MDC) and a posterior sample (Bayesian) both arrive here, with ``posterior`` populated only in the latter case. That is what lets a caller swap criteria without rewriting the code that consumes the result. Attributes: best: The best network found. For a Bayesian run this is the maximum a posteriori network. score: The objective value of :attr:`best`. A log likelihood, log pseudo-likelihood, or log posterior for the likelihood-based criteria; an extra-lineage count for :class:`~phynetpy.criteria.MDC`. method: The method that ran, named after the PhyloNet command it corresponds to (e.g. ``"InferNetwork_MPL"``). lower_is_better: Whether :attr:`score` is minimised. ``True``...

Methods

__repr__ -> str

Start

class Start

A starting phylogeny bundled with how the search may use it. The network and its usage mode travel together, because a bare network is ambiguous: "start here" and "the answer must contain this" are different requests that happen to take the same argument. Attributes: network: The starting network (which may be a tree). mode: Whether the search may reshape it (:attr:`StartMode.FREE`, the default) or only add to it (:attr:`StartMode.AUGMENT`).

Properties

augment_only -> bool property

Whether the final network must contain this one as a subgraph.

StartMode

class StartMode(Enum)

How a search may use a user-supplied starting phylogeny. Attributes: FREE: A free starting point. The search may reshape it without restriction; only the initial position is influenced. AUGMENT: A backbone the result must contain. The search may only add to it, never remove or rearrange what is already there. Well-defined because adding reticulations to a network yields a network containing the original as a subgraph, so this is a real constraint on the search space rather than an initialisation hint.

Data

class Data(ABC)

Base class for every input type on the data axis. Subclasses declare *what kind of observation* the user has: :class:`~phynetpy.data.GeneTrees` (gene-tree estimates), :class:`~phynetpy.data.Alignment` (per-locus sequences), or :class:`~phynetpy.data.BiallelicMarkers` (SNPs). A criterion declares which of these it is defined on via ``Criterion.accepts_data``, and the registry keys engines on the concrete class. Every data type carries the species-to-allele mapping alongside the observations, because the mapping describes *the sample*, not the biology or the objective: which gene copies were sequenced from which species is a property of the data set. This is why neither verb takes a separate ``mapping`` argument.

Properties

taxa -> set property abstract

The set of allele / sequence labels present in the data.

mapping -> Optional[Dict[str, List[str]]] property

Explicit species -> allele mapping, or ``None`` if unset.

has_branch_lengths -> bool property

Whether the data carries usable branch lengths. Only meaningful for :class:`~phynetpy.data.GeneTrees`; sequence and marker data have no branch lengths of their own, so the base implementation reports ``False``. Consulted by the registry when a criterion's ``use_branch_lengths`` policy is ``True``.

Constructor

__init__(mapping: Optional[Dict[str, List[str]]] = None) -> None

Initialise the shared mapping slot.

Parameter Type Description
mapping Species -> list of allele / gene-copy labels. ``None`` defers to :meth:`resolved_mapping`, which falls back to an identity mapping (each label is its own species).

Methods

mapping(value: Optional[Dict[str, List[str]]]) -> None

Set the explicit species -> allele mapping (``None`` to clear it).

resolved_mapping -> Dict[str, List[str]]

Return an explicit mapping, falling back to identity.

Returns: dict[str, list[str]]: Species -> allele labels. When no mapping was supplied, every label is treated as its own species, which is the right default for single-copy (one allele per species) data.

GeneTrees

class GeneTrees(Data, _GeneTreeCollection)

Gene-tree estimates: the data axis type for gene trees. Accepted by the MDC, likelihood, pseudo-likelihood, and Bayesian criteria -- gene trees are the only data type all four are defined on. Because this subclasses :class:`phynetpy.GeneTrees.GeneTrees`, every inherited utility (``build_majority_rule_consensus_tree``, ``most_frequent_gene_tree``, ``cluster_support``, ``rf_distance``, ``astral``, ``mp_allop_map``, ...) is available, and the object can be handed straight to the numerical engines, which expect that type. Attributes: trees: Set of gene trees, each a :class:`~phynetpy.Network.Network`. taxa_names: Union of all gene-copy (allele) labels.

Properties

taxa -> set property

The set of gene-copy (allele) labels across all trees.

mapping -> Optional[Dict[str, List[str]]] property

Explicit species -> allele mapping, or ``None`` if unset. Kept in step with the inherited ``species_gene_mapping`` so the numerical engines and the two verbs read the same value.

has_branch_lengths -> bool property

Whether these gene trees carry observed branch lengths. ``False`` means the trees are topologies only. Set at construction (from the source file's text, or from the trees' edges) rather than inferred later, because ``phynetpy.IO`` back-fills missing lengths with ``1``.

Constructor

__init__(trees: Optional[List[Network]] = None, mapping: Optional[Dict[str, List[str]]] = None, naming_rule: Optional[Callable[..., Any]] = None, has_branch_lengths: Optional[bool] = None) -> None

Wrap a set of gene trees as a data-axis object.

Parameter Type Description
trees The gene trees. Each should be a rooted binary :class:`~phynetpy.Network.Network` with no reticulations.
mapping Species -> list of allele labels. Omit for single-copy data, where each label is its own species.
naming_rule ``f : str -> str`` deriving a species key from an allele label; an alternative to an explicit *mapping* (e.g. :func:`phynetpy.GeneTrees.phynetpy_naming`).
has_branch_lengths Override the branch-length flag. ``None`` infers it from the trees' edges.
Raises: DataError: If *trees* is empty or contains a reticulate network.

Methods

mapping(value: Optional[Dict[str, List[str]]]) -> None

Set the explicit species -> allele mapping, keeping it in step with ``species_gene_mapping``.

resolved_mapping -> Dict[str, List[str]]

Species -> allele mapping, resolved through the naming rule. Defers to the inherited resolution chain: an explicit mapping, then the naming rule, then identity.

from_file(path: Union[str, os.PathLike], mapping: Optional[Dict[str, List[str]]] = None, naming_rule: Optional[Callable[..., Any]] = None, format: Optional[str] = None) -> 'GeneTrees' @classmethod

Load gene trees from a NEXUS or Newick file.

Parameter Type Description
path Path to the file.
mapping Species -> list of allele labels.
naming_rule ``f : str -> str`` deriving species from labels.
format ``"nexus"`` or ``"newick"``. ``None`` infers from the file extension, defaulting to NEXUS.
Returns: GeneTrees: The loaded collection, with ``has_branch_lengths`` determined from the file's text.
Raises: DataError: If the file cannot be read or holds no trees.
from_newick(strings: Union[str, Sequence[str]], mapping: Optional[Dict[str, List[str]]] = None, naming_rule: Optional[Callable[..., Any]] = None) -> 'GeneTrees' @classmethod

Build from one or more Newick strings.

Parameter Type Description
strings A single Newick string, or a sequence of them. A single string containing several ``;``-terminated trees is split.
mapping Species -> list of allele labels.
naming_rule ``f : str -> str`` deriving species from labels.
Returns: GeneTrees: The parsed collection.
__repr__ -> str

Alignment

class Alignment(Data)

Multilocus nucleotide sequence alignments. One :class:`Alignment` holds *all* loci for the analysis; each locus is a separate alignment over the same allele labels. Accepted by the Bayesian criterion, which co-estimates the species network and the gene trees (Wen & Nakhleh 2018). PhyNetPy will not estimate gene trees from an alignment, so the MDC and pseudo-likelihood criteria reject this type outright: those are defined over gene-tree topologies. Summarise the alignment externally and pass :class:`~phynetpy.data.GeneTrees` instead. The nucleotide substitution model lives here rather than on the model axis, because it describes how *these sequences* were generated, while the model axis describes how the gene copies are related. Attributes: loci: Per-locus alignments as ``{label: sequen...

Properties

taxa -> set property

The set of sequence labels across all loci.

n_loci -> int property

Number of loci.

n_sites -> int property

Total aligned site count summed across loci.

Constructor

__init__(loci: Union[MSA, Sequence[Any]], mapping: Optional[Dict[str, List[str]]] = None, substitution_model: Optional[Any] = None) -> None

Wrap per-locus alignments as a data-axis object.

Parameter Type Description
loci A single :class:`~phynetpy.MSA.MSA`, or a sequence of per-locus alignments (each an ``MSA`` or a ``{label: sequence}`` dict).
mapping Species -> list of allele labels, where the allele labels are the alignment row names.
substitution_model A :class:`~phynetpy.infer.SubstitutionModel` (``JC69``, ``HKY85``, ``GTR``). ``None`` selects ``JC69``.
Raises: DataError: If no loci are supplied.

Methods

from_file(path: Union[str, os.PathLike, Sequence[Union[str, os.PathLike]]], mapping: Optional[Dict[str, List[str]]] = None, format: Optional[str] = None, substitution_model: Optional[Any] = None) -> 'Alignment' @classmethod

Load one locus per file.

Parameter Type Description
path A single path, or a sequence of paths (one per locus).
mapping Species -> list of allele labels.
format ``"nexus"``, ``"fasta"``, or ``"vcf"``. ``None`` infers from each file's extension.
substitution_model See :meth:`__init__`.
Returns: Alignment: The loaded alignments, one locus per file.
__repr__ -> str

BiallelicMarkers

class BiallelicMarkers(Data)

Unlinked biallelic markers (SNPs). Sites are encoded as per-taxon counts of the "red" allele, so a row of a diploid data set reads ``0``/``1``/``2``. Accepted by the likelihood and Bayesian criteria (Bryant et al. 2012; Zhu et al. 2018). ``samples`` -- how many gene copies were sequenced per taxon -- belongs here rather than on the model axis: it describes the sampling effort, not the biology. The mutation rates ``u``/``v`` and the coalescent rate live on :class:`~phynetpy.models.MSC` instead, since those *are* the generative process. Attributes: alignment: The underlying :class:`~phynetpy.MSA.MSA`. samples: Taxon label -> number of sampled gene copies.

Properties

taxa -> set property

The set of taxon labels in the marker matrix.

n_sites -> int property

Number of marker sites.

Constructor

__init__(alignment: MSA, mapping: Optional[Dict[str, List[str]]] = None, samples: Optional[Dict[str, int]] = None) -> None

Wrap a biallelic marker matrix as a data-axis object.

Parameter Type Description
alignment The marker matrix, as an :class:`~phynetpy.MSA.MSA` whose sequences hold per-site red-allele counts.
mapping Species -> list of taxon labels. Usually the identity for marker data, where each row is its own taxon.
samples Taxon label -> sampled gene-copy count. ``None`` assumes one sampled copy per taxon.
Raises: DataError: If *alignment* is not an ``MSA``.

Methods

from_file(path: Union[str, os.PathLike], mapping: Optional[Dict[str, List[str]]] = None, samples: Optional[Dict[str, int]] = None, format: Optional[str] = None) -> 'BiallelicMarkers' @classmethod

Load markers from a NEXUS or VCF file.

Parameter Type Description
path Path to the file.
mapping Species -> list of taxon labels.
samples Taxon label -> sampled gene-copy count.
format ``"nexus"`` or ``"vcf"``. ``None`` infers from the extension.
Returns: BiallelicMarkers: The loaded marker matrix.
__repr__ -> str

Model

class Model(ABC)

Base class for a generative biological process. A model says what produced the data and therefore how to read the inferred network: under :class:`~phynetpy.models.MSC` a reticulation is a hybridization or introgression event between diploid lineages, while under :class:`~phynetpy.models.Allopolyploid` it is a polyploid formation event and the network is interpreted through its multiple-labelled (MUL) tree. Models are declarative parameter carriers, not engines. They hold the process parameters (population mutation rate, mutation rates, subgenome assignment) and are handed to the engine the registry selects; the numerical work lives in the engines. .. note:: Unrelated to :class:`phynetpy.ModelGraph.Model`, which is the probabilistic graphical model a search mutates. See the :mod:`phynetpy.m...

Methods

validate(data) -> None

Check this model against the data it will be run on. Called by the registry after dispatch succeeds, so a model may assume the (data, model, criterion) triple is legal and only needs to police its own parameters. The default accepts everything.

Parameter Type Description
data The :class:`~phynetpy.data.Data` the run will consume.
Raises: ModelSpecError: If the model cannot be applied to *data*.
__repr__ -> str

MSC

class MSC(Model)

The multispecies network coalescent: diploid lineages with ILS. The default model, and the one nearly every method in the field is built on. Gene copies coalesce within the branches of the species network at a rate set by the population mutation rate; at a reticulation, each lineage passes into one parent with probability given by that edge's inheritance probability (gamma). Incomplete lineage sorting therefore arises from the coalescent, and a reticulation means hybridization or introgression. The process parameters live here because they *are* the biology. The mutation rates ``u`` and ``v`` describe the biallelic transition model. ``theta`` is the population mutation rate ``4*N*mu`` for every MSC data type. Fixed branch-specific values may override it through ``branch_thetas``. Attribute...

Constructor

__init__(theta: Optional[float] = None, u: float = 1.0, v: float = 1.0, branch_thetas: Optional[Mapping[BranchThetaKey, float]] = None) -> None

Configure the multispecies network coalescent.

Parameter Type Description
theta Population mutation rate ``4*N*mu``. ``None`` defers to the engine (which samples it, for the Bayesian criterion).
u Red-to-green mutation rate (biallelic markers only).
v Green-to-red mutation rate (biallelic markers only).
branch_thetas Fixed per-population values. Stable ``(parent_label, child_label)`` keys identify edges; a child label identifies the branch above that node. Use ``("__root__", root_label)`` for the ancestral population.
Raises: ModelSpecError: If any rate is non-positive.

Methods

__repr__ -> str

Allopolyploid

class Allopolyploid(Model)

Allopolyploidy: networks read through their MUL tree. Models polyploid taxa whose subgenomes descend from distinct diploid progenitors (Hejase et al.; MP-Allop / Polyphest). A reticulation is a polyploid formation event, and the network is scored by expanding it into a multiple-labelled (MUL) tree in which each subgenome of a polyploid appears as its own tip. Because subgenome assignment -- which gene copies belong to which subgenome of which taxon -- is a statement about the biology of the taxa, it lives on the model rather than on the data. When omitted, it is derived from the data's own mapping. Attributes: subgenome_map: Subgenome / species -> list of gene-copy labels. ``None`` derives it from the data.

Constructor

__init__(subgenome_map: Optional[Dict[str, List[str]]] = None) -> None

Configure the allopolyploid process.

Parameter Type Description
subgenome_map Subgenome -> list of gene-copy labels. ``None`` derives the assignment from the data's mapping (or, failing
that from :meth:`phynetpy.GeneTrees.GeneTrees.mp_allop_map`).

Methods

resolve_subgenome_map(data) -> Dict[str, List[str]]

Return the subgenome assignment to use for *data*.

Parameter Type Description
data The :class:`~phynetpy.data.Data` being analysed.
Returns: dict[str, list[str]]: Subgenome -> gene-copy labels.
Raises: ModelSpecError: If no assignment is available.
validate(data) -> None

Check that a subgenome assignment can be resolved.

Parameter Type Description
data The data the run will consume.
Raises: ModelSpecError: If no assignment is available.
__repr__ -> str

BranchLengthUnit

class BranchLengthUnit(str, Enum)

Units carried by every biologically interpreted network. ``SUBSTITUTIONS_PER_SITE`` is required by sequence, marker, and timed-MSC calculations. ``COALESCENT_2N`` supports topology/coalescent workflows. ``UNSPECIFIED`` is safe for graph operations but rejected by biological calculations until the network is explicitly tagged or converted.

Criterion

class Criterion(ABC)

Base class for a statistical objective. A criterion says *what number is being optimised*: a parsimony cost, a full likelihood, a pseudo-likelihood, or a posterior. It is independent of both the data type and the biology, which is why it is its own axis. Two class attributes make the legality of a run checkable before any computation starts: * ``accepts_data`` -- the data types the objective is mathematically defined on. Violating it is a :class:`TypeError`, not a missing feature: MDC over a sequence alignment is not unimplemented, it is undefined. * ``scorable`` -- whether the objective can score a single fixed network. ``False`` for :class:`~phynetpy.criteria.Bayesian`, whose value on one network collapses to its wrapped objective. Attributes: use_branch_lengths: Tri-valued branch-length...

Methods

__repr__ -> str

MDC

class MDC(Criterion)

Minimizing deep coalescences: a parsimony criterion. Counts the extra gene lineages needed to reconcile the gene trees with the species network and prefers the network needing fewest. Defined over gene-tree *topologies*, so branch lengths are ignored by construction -- ``use_branch_lengths`` is fixed at ``False`` and cannot be overridden. Lower is better, unlike every other criterion here; the verbs normalise this so that :attr:`~phynetpy.infer.InferenceResult.score` is always reported in the criterion's own natural direction and documented as such.

Constructor

__init__(weighting: Optional[str] = None) -> None

Configure the parsimony criterion.

Parameter Type Description
weighting Per-tree weighting scheme (``"bootstrap"``, ``"posterior"``, ...). ``None`` weights every gene tree equally.
Raises: CriterionError: If a weighting scheme is requested.

Likelihood

class Likelihood(Criterion)

Full likelihood of the data under the model. Integrates over all coalescent histories rather than summarising them, so it is the most statistically efficient of the point-estimate criteria and the most expensive. Defined on all three data types. Attributes: use_branch_lengths: ``True`` requires and uses gene-tree branch lengths, ``False`` scores topologies only, ``None`` uses them when present.

Constructor

__init__(use_branch_lengths: Optional[bool] = None) -> None

Configure the full-likelihood criterion.

Parameter Type Description
use_branch_lengths Branch-length policy. ``None`` (default) uses gene-tree branch lengths when the data carries them.

Methods

__repr__ -> str

PseudoLikelihood

class PseudoLikelihood(Criterion)

Pseudo-likelihood over subsets of the taxa. Replaces the full likelihood with a product of likelihoods over small subsets (by default rooted triples), which is far cheaper and scales to many more taxa at some cost in efficiency (Yu & Nakhleh 2015; Solis-Lemus & Ane 2016). Defined on gene-tree topologies and on biallelic markers, but not on alignments: a pseudo-likelihood over subsets of gene trees needs gene trees, and PhyNetPy does not estimate them from sequences. Attributes: subsets: Which subsets the product runs over. Only ``"trinets"`` (rooted triples) is implemented. use_branch_lengths: Branch-length policy; the triplet method consumes topologies only.

Constructor

__init__(subsets: str = 'trinets', use_branch_lengths: Optional[bool] = None) -> None

Configure the pseudo-likelihood criterion.

Parameter Type Description
subsets Subset family for the product. ``"trinets"`` (3-taxon subnetworks) is the only supported value.
use_branch_lengths Branch-length policy.
Raises: CriterionError: If *subsets* is not ``"trinets"``.

Methods

__repr__ -> str

Bayesian

class Bayesian(Criterion)

Bayesian mode: sample a posterior built on an objective. Not a fourth objective but a *mode layered on one*. The casual user writes ``Bayesian()`` and gets the full likelihood; the power user writes ``Bayesian(objective=PseudoLikelihood())``. Which data types are legal follows from the wrapped objective, so ``accepts_data`` is delegated to it. Scoring a single fixed network under a Bayesian criterion collapses to computing its likelihood or posterior density, so ``scorable`` is ``False`` and :func:`phynetpy.infer.score` refuses it, pointing the caller at ``.objective`` instead. Attributes: objective: The wrapped likelihood (full or pseudo). prior: Prior hyperparameters, or ``None`` for the engine's defaults. chain_length: Total proposed moves. burnin: Iterations discarded before sampling b...

Properties

accepts_data -> tuple property

Data types the wrapped objective is defined on.

use_branch_lengths -> Optional[bool] property

Branch-length policy of the wrapped objective.

Constructor

__init__(objective: Optional[Criterion] = None, prior: Optional[Any] = None, chain_length: int = 1000000, burnin: int = 100000, sample_freq: int = 100, seed: Any = None, temperatures: Optional[list] = None) -> None

Configure the Bayesian mode.

Parameter Type Description
objective The likelihood the posterior is built on. ``None``
selects class:`Likelihood`.
prior Prior hyperparameters (:class:`~phynetpy.infer.MCMC_GTPriors` for gene trees and
markers :class:`~phynetpy.infer.MCMCSeqPriors` for alignments). ``None`` uses the engine's defaults.
chain_length Total proposed moves.
burnin Iterations discarded before sampling.
sample_freq Thinning interval for retained samples.
seed Master RNG seed.
temperatures MC3 temperature ladder (alignments only).
Raises: CriterionError: If the objective is itself Bayesian, or the chain budget is inconsistent.

Methods

__repr__ -> str

MCMC_GTPriors

class MCMC_GTPriors

Composable prior parameters for :func:`log_prior_network`. Defaults follow Wen & Nakhleh (2016). Each component can be disabled by setting its weight to ``0.0`` for a plain-likelihood search (equivalent to HC / SA with method="mh" dropped in). Attributes: branch_length_rate: Rate ``lambda`` of an ``Exp(lambda)`` prior on every finite branch length. Mean branch length under the prior is ``1 / lambda``. Default 1.0 coalescent-unit. gamma_alpha, gamma_beta: Beta(alpha, beta) prior on each reticulation inheritance probability. Default ``(1, 1)`` is uniform. retic_count_mean: Mean of the ``Poisson`` prior on the number of reticulations. Default 1.0 (softly shrinks toward tree-like topologies while still supporting several retics). topology_weight: Coefficient on the topology prior...

MCMCSeqPriors

class MCMCSeqPriors

Prior hyperparameters for :class:`MCMC_SEQ` (PhyloNet defaults). Attributes: poisson_mean: Mean of the Poisson prior on the number of reticulation nodes (PhyloNet ``-pp``; default 1.0). max_reticulations: Hard cap on reticulations (PhyloNet ``-mr``; default 4). max_level: Hard cap on network *level* -- the maximum number of reticulations in any single biconnected component ("blob"). ``1`` restricts the sampler to level-1 (galled) networks, whose displayed-tree count grows linearly rather than combinatorially, so the MSNC ancestral-configuration DP stays cheap. Reticulation-adding / relocating moves that would exceed the cap self-reject *before* the expensive coupled gene-tree re-proposal and scoring, so the constraint also acts as a runtime optimisation. ``None`` (default) disabl...

SubstitutionModel

class SubstitutionModel

Time-reversible 4-state nucleotide substitution model. Subclasses build the (un-normalised) instantaneous rate matrix ``Q`` via :meth:`_build_Q` from their stationary base frequencies ``pi`` and the six exchangeability rates. The base class then normalises ``Q`` so that the expected substitution rate is 1 (``-sum_i pi_i Q_ii = 1``) -- this makes a branch length the expected number of substitutions per site, exactly as in PhyloNet/BEAST -- and computes ``P(t) = exp(Q t)`` via a single eigendecomposition that is reused for every branch length. Attributes: pi: Stationary base frequency vector (length 4, ``A,C,G,T``).

Constructor

__init__(pi: Sequence[float], rates: Sequence[float]) -> None

Build and normalise the model.

Parameter Type Description
pi Stationary base frequencies (length 4; ``A,C,G,T``); must sum to 1.
rates The six exchangeability parameters in the order ``AC, AG, AT, CG, CT, GT``.

Methods

p_matrix(t: float) -> np.ndarray

Transition-probability matrix ``P(t) = exp(Q t)``.

Parameter Type Description
t Branch length in expected substitutions per site (``>= 0``).
Returns: A ``4x4`` row-stochastic matrix; ``P[i,j]`` is the probability of ending in state ``j`` after time ``t`` starting from state ``i``.

JC69

class JC69(SubstitutionModel)

Jukes-Cantor (1969): equal base frequencies, equal rates. PhyloNet's default model. Uses the closed-form transition matrix ``P_ii(t) = 1/4 + 3/4 e^{-4t/3}``, ``P_ij(t) = 1/4 - 1/4 e^{-4t/3}``, bypassing the eigendecomposition entirely for speed and exactness.

Constructor

__init__() -> None

Construct the parameter-free JC69 model.

Methods

p_matrix(t: float) -> np.ndarray

Closed-form JC69 transition matrix (see class docstring).

HKY85

class HKY85(SubstitutionModel)

Hasegawa-Kishino-Yano (1985): free ``pi``, one transition/transversion ratio. Exchangeabilities are ``[1, kappa, 1, 1, kappa, 1]`` in ``AC,AG,AT,CG,CT,GT`` order (transitions ``A<->G`` and ``C<->T`` scaled by ``kappa``).

Constructor

__init__(kappa: float, pi: Sequence[float]) -> None

Build an HKY85 model.

Parameter Type Description
kappa Transition/transversion rate ratio (``> 0``).
pi Stationary base frequencies (length 4, ``A,C,G,T``).

GTR

class GTR(SubstitutionModel)

General time-reversible model: free ``pi`` and all six exchangeabilities. Args mirror PhyloNet's ``-gtr (piA piC piG piT, rAC rAG rAT rCG rCT rGT)``.

Constructor

__init__(pi: Sequence[float], rates: Sequence[float]) -> None

Build a GTR model.

Parameter Type Description
pi Stationary base frequencies (length 4, ``A,C,G,T``).
rates Six exchangeabilities ``AC,AG,AT,CG,CT,GT``.

MCMCGTResult

class MCMCGTResult

Aggregate result from an :class:`MCMC_GT` search. Both Bayesian (``method="mh"``) and likelihood-maximising (``method="hc"`` / ``"sa"``) runs populate this container; fields irrelevant to a given method are left at their defaults. Attributes: method: Which driver produced this result (``"mh"``, ``"hc"``, or ``"sa"``). best_network: Highest-scoring network seen during the search. For MH this is the MAP sample; for HC / SA it's the end-state. best_log_posterior: Score associated with ``best_network`` (posterior for MH; likelihood for HC / SA). samples: Posterior samples collected from the MH chain, in order of draw. Empty for HC / SA. num_iter: Total proposed moves evaluated. num_accepted: Count of moves actually accepted into the c...

Properties

acceptance_rate -> float property

Fraction of proposals the driver accepted.

Methods

trace_table -> tuple[list[int], dict[str, list[float]]]

Build a Tracer-style trace table from the MH samples.

Returns: ``(states, traces)`` with columns ``posterior``, ``likelihood``, ``prior`` (= posterior - likelihood) and ``reticulationCount``. Empty for hill-climbing / simulated-annealing runs (which record no samples).
write_log(path: str) -> None

Write a BEAST/Tracer-compatible ``.log`` of the sampled chain.

write_networks(path: str) -> None

Write the sampled species networks as a NEXUS ``.trees`` file.

summary(hpd_prob: float = 0.95) -> ChainSummary

Per-parameter diagnostics (mean, HPD, ESS, ...) for the MH chain.

MCMCSample

class MCMCSample

A single posterior sample from an :class:`MCMC_GT` MH run. Attributes: iteration: Global iteration index at which the sample was taken (including burn-in). network: Deep copy of the species network at this iteration. Decoupled from the chain's live model so subsequent moves don't mutate the sample. log_posterior: Unnormalised log posterior at the sample (``sum_i log P(g_i | Psi) + log_prior(Psi)``). log_likelihood: Just the MSNC log likelihood part (useful for reporting the MAP estimate independently of the prior).

InferNetworkMLResult

class InferNetworkMLResult

Aggregate result returned by :meth:`InferNetwork_ML.search`. Attributes: best_network: Highest-likelihood species network found across every run. Branch lengths (coalescent units) and reticulation inheritance probabilities are the ML estimates for this topology (always optimised at least once at the end of the search). best_log_likelihood: MSNC log likelihood of ``best_network``. Higher (closer to 0) is better. num_reticulations: Reticulation-node count of ``best_network``. networks: Up to ``num_networks`` distinct top-scoring networks (best first), each paired with its log likelihood. Useful for inspecting near-optimal alternatives / model selection. num_networks_examined: Total number of distinct topologies scored across all runs (the analogue of PhyloNet's ``-m`` budget consumption). nu...

MCMCSeqResult

class MCMCSeqResult

Aggregate result of an :meth:`MCMC_SEQ.search` run. Attributes: map_network: Maximum-a-posteriori species network found. map_log_posterior: Its log posterior. map_theta: ``theta`` at the MAP state. samples: Recorded posterior samples (post burn-in, thinned). acceptance_rate: Fraction of proposals accepted. num_iterations: Total proposals attempted. wall_time_sec: Wall-clock duration.

Methods

trace_table -> tuple[list[int], dict[str, list[float]]]

Build a Tracer-style trace table from the recorded samples.

Returns: ``(states, traces)`` where ``states`` are the per-sample iteration indices and ``traces`` maps column name to per-sample values. Columns: ``posterior``, ``likelihood``, ``prior`` (= posterior - likelihood), ``theta`` and ``reticulationCount`` -- mirroring the quantities PhyloNet's MCMC_SEQ logs.
write_log(path: str) -> None

Write a BEAST/Tracer-compatible ``.log`` of the sampled chain.

Parameter Type Description
path Output path (conventionally ``.log``); open it in Tracer.
write_networks(path: str) -> None

Write the sampled species networks as a NEXUS ``.trees`` file.

Parameter Type Description
path Output path (conventionally ``.trees``); for DensiTree / TreeAnnotator-style topology summaries.
summary(hpd_prob: float = 0.95) -> ChainSummary

Per-parameter diagnostics (mean, HPD, ESS, ...) for the chain.

Parameter Type Description
hpd_prob Coverage for the reported HPD interval (default 0.95).
Returns: A: class:`~phynetpy._chain_analysis.ChainSummary`; ``print`` it for a Tracer-style table, or inspect ``.parameters`` / ``.min_ess``.
reticulation_posterior -> dict[int, float]

Posterior P(number of reticulations) from the sampled chain. This is the *mass*-based estimate to report instead of the MAP reticulation count: the joint MAP can sit on the coalescent ``theta -> 0`` degeneracy and over-count reticulations, whereas this marginal over the discrete dimension is what the chain actually visited.

topology_posterior(top_n: Optional[int] = None) -> list[tuple[str, float]]

Ranked ``(representative_newick, posterior_probability)`` topologies. Topologies are compared ignoring branch lengths / gamma (see :func:`_topology_signature`). The top entry is the posterior-mode ("MAP") *topology* -- a far more trustworthy point estimate than the single highest-density state.

map_topology -> Optional[str]

Representative newick of the most-sampled topology (``None`` if empty).

information_criteria -> Optional[dict[str, float]]

AIC / AICc / BIC of the MAP network. Uses the MAP network's maximised log *likelihood* (not posterior) and its free-parameter count ``k = L + 3r`` (see :func:`_count_free_parameters`); the BIC sample size is the total number of aligned sites. Returns ``None`` when the likelihood was not recorded (e.g. a hand-built result). Lower AIC/BIC is better.

model_selection_by_reticulation -> list[dict[str, float]]

AIC / AICc / BIC per reticulation count, from the sampled chain. Groups the posterior samples by reticulation count, takes the best (highest) log likelihood seen at each count as that model's maximised fit, and scores it with ``k = L + 3r`` parameters over the total site count. Each row also carries ``dAIC`` / ``dBIC`` -- the increase over the best-scoring model -- so you can read off whether an *extra* reticulation earns its ``\Delta k = 3`` penalty or is just the chain exploring higher dimensions (a ``dAIC`` above ~2, or any positive ``dBIC``, means the simpler model is preferred despite its lower likelihood). Sorted by reticulation count.

MCMCSeqSample

class MCMCSeqSample

One recorded posterior sample. Attributes: iteration: Chain iteration at which the sample was taken. log_posterior: Unnormalised log posterior. log_likelihood: Total phylogenetic + coalescent log likelihood. network_newick: Extended-Newick string of the species network. theta: Population mutation rate. num_reticulations: Reticulation count. gamma_major: Largest inheritance probability across the network's reticulations (``None`` for a tree state).

MultiChainResult

class MultiChainResult

Aggregate result of a :func:`run_parallel_chains` run. Attributes: chains: Per-chain :class:`MCMCSeqResult` (partial if stopped early), ordered by chain id. rhat: Final cross-chain R-hat per trace column. n_chains: Number of chains launched. stopped_early: Whether the run was halted (monitor "stop" or Ctrl-C) before all chains finished their iterations. errors: ``chain_id -> traceback`` for any chain that raised. wall_time_sec: Total wall-clock duration.

Methods

best -> Optional[MCMCSeqResult]

The chain with the highest MAP log posterior (``None`` if empty).

pooled_samples -> list[MCMCSeqSample]

All chains' post-burn-in samples concatenated.

reticulation_posterior -> dict[int, float]

Posterior P(number of reticulations) pooled across all chains.

topology_posterior(top_n: Optional[int] = None) -> list[tuple[str, float]]

Ranked ``(representative_newick, posterior_probability)`` pooled.

map_topology -> Optional[str]

Representative newick of the most-sampled topology across chains.

MultiChainStatus

class MultiChainStatus

Live snapshot of a :func:`run_parallel_chains` run. Passed to the ``monitor`` callback every check interval. Attributes: per_chain: ``chain_id -> latest status dict`` with keys ``iteration``, ``num_iter``, ``log_posterior``, ``map_log_posterior``, ``num_reticulations``, ``acceptance_rate`` and ``n_samples``. rhat: ``param -> Gelman-Rubin R-hat`` across chains (``nan`` until at least two chains have >= 2 post-burn-in samples). Values near 1.0 (commonly ``< 1.05``) indicate the chains have mixed. elapsed_sec: Wall-clock seconds since launch. running: Chain ids still sampling. finished: Chain ids that have returned (completed or stopped).

Engine

class Engine(ABC)

Base class for a concrete (data, model, criterion) implementation. An engine is the adapter between the declarative axis objects and the numerical code. Each registered engine implements *both* verbs, which is why scoring is not a separate command: PhyloNet's ``CalGTProb`` and its deep-coalescence count are simply ``score(net, data, MSC(), Likelihood())`` and ``score(net, data, MSC(), MDC())``. Attributes: model: The generative process for this run. criterion: The statistical objective for this run. start: Optional :class:`~phynetpy.infer.Start` describing the starting phylogeny and how the search may use it. search: Generic search controls, forwarded from the verb's ``**search`` kwargs.

Constructor

__init__(model: Model, criterion: Criterion, start: Optional[Any] = None, **search: Any) -> None

Bind the axis objects and the search controls for one run.

Parameter Type Description
model The generative process.
criterion The statistical objective.
start Optional starting phylogeny and usage mode. **search: Generic search controls (``max_reticulations``, ``preset``, ``seed``, ...).

Methods

infer(data: Data) -> Any abstract

Infer a network from *data*.

Parameter Type Description
data The observations.
Returns: InferenceResult: The best network, its score, and any posterior sample or search trace.
score(network, data: Data, optimize: bool = False) -> float abstract

Score a single fixed network.

Parameter Type Description
network The network to score.
data The observations.
optimize When ``True``, optimise the network's continuous parameters (branch lengths and inheritance probabilities) and report the best attainable score for that topology. When ``False``, score the network exactly as given.
Returns: float: The objective value.

MPLScorer

class MPLScorer

Callable likelihood evaluator for use with :class:`Model`. Registered via ``model.set_likelihood_calculator(scorer)``. On each call, rebuilds a fresh :class:`_TripleDPEngine` for the current network (topology moves invalidate the previous engine's cached articulation sets) and returns the log pseudo-likelihood. Gene-tree rho values never change during a search, so they are stored once on the instance. Triplets whose gene-tree rho is identically zero contribute nothing to the score and are pruned at construction time to avoid redundant DP calls. Attributes: _rho: Full triplet -> rho table (kept even for pruned triplets in case the scorer is reused against a network with a different triplet mask). _triplets: Active (non-zero-rho) triplet list used by ``__call__``.

Constructor

__init__(rho: dict[tuple[str, str, str], tuple[float, float, float]], triplets: list[tuple[str, str, str]]) -> None

Initialise the scorer from precomputed gene-tree statistics.

Parameter Type Description
rho Mapping ``triplet -> (rho_XY|Z, rho_XZ|Y, rho_YZ|X)``.
triplets Canonical species triplets to iterate over.

MPLKernel

class MPLKernel(ProposalKernel)

Phase-aware proposal kernel for MPL network search. Cycles between two complementary search phases: **TOPOLOGY** -- Explores tree space via SPR and branch-length adjustments (ChangeNodeHeight), with ChangeInheritanceProb mixed in for gamma tuning. **RETICULATION** -- Searches for hybridization events via Add/Remove/Flip reticulation and source/dest moves, with ChangeInheritanceProb and ChangeNodeHeight for local refinement after reticulation changes. Both phases keep a small bleed of the complementary phase's moves active (~10-15% weight) so the chain stays ergodic across phase flips and the adaptive scaler always has fresh observations for every class. Phase transitions fire after ``phase_patience`` consecutive proposals without accepted improvement. Within each phase, selection weights a...

Constructor

__init__(move_types: list[type[Move]] | None = None, weights: list[float] | None = None, max_reticulations: int | None = None, max_level: int | None = None, adaptive: bool = True, window_size: int = 30, min_weight: float = 0.05, phase_patience: int = 150, warmup: int = 8, stagnation_reset_delta: float = 1.0, rng: np.random.Generator | None = None) -> None
Parameter Type Description
move_types Move classes available to the kernel. When ``None`` the full default set is used.
weights Fixed per-move selection weights. Supplying this disables phased cycling and adaptive tuning.
max_reticulations Cap on reticulation nodes. When the current network is at the cap, ``AddReticulation`` is dropped from the active move set so we don't waste proposals on guaranteed no-ops.
max_level Cap on network level (``max_lvl`` search flag). Passed to every level-raising move (Add / Relocate / ChangeReticSource / ChangeReticDest / Flip) so they self-reject proposals that would exceed the cap. ``None`` disables the per-move check (the accept-path level guard remains authoritative).
adaptive Enable within-phase adaptive weight scaling.
window_size Sliding-window length for acceptance stats.
min_weight Minimum scale factor (fraction of base weight) to prevent any move from being fully starved.
phase_patience Consecutive non-improving proposals before the kernel switches to the next phase. Default 150 keeps phase flips roughly aligned with the SA ``steps_per_temp`` cadence.
warmup Minimum observations per move class before the adaptive scaling activates for that class.
stagnation_reset_delta Minimum strict-improvement magnitude (in log-PL units) that counts as "real progress" for stagnation-reset purposes. Any ``delta > stagnation_reset_delta`` resets the stagnation counter; smaller wiggles are ignored. Default 1.0 filters out the O(0.01-0.1) tweaks that late-stage NH/CIP moves generate, so the counter actually climbs during genuine plateaus. Setting to 0.0 restores the prior "any strict improvement resets" behaviour. Required for phase cycling and adaptive SPR radius to track true plateaus rather than micro-noise.
rng ``numpy.random.Generator`` used to sample the move class. When ``None``, a fresh generator is created from OS entropy; callers that care about reproducibility (e.g. ``MPL.search``) should pass one seeded from the search-wide ``SeedSequence``.

Methods

generate(model: 'Model | None' = None) -> Move

Sample a move from the current phase's weighted distribution.

Parameter Type Description
model Optional current model. Used only for cap-aware filtering (``AddReticulation`` is dropped when the network is already at ``max_reticulations``). Callers from ``SimulatedAnnealing``/``HillClimbing`` pass the live model; the abstract base signature keeps the parameter optional for back-compat.
report_outcome(accepted: bool, delta: float = 0.0) -> None

Record a move outcome and update adaptive state. Called by the search driver (HC / SA) immediately after each ``generate()`` -> propose -> score pair, regardless of accept/reject. Updates: * The rolling per-move history window (fed back to :meth:`_adapt_weights`). * Lifetime accepted/improved counters (for :meth:`format_stats`). * The Robbins-Monro sigma for the last move class when it was a continuous proposal (NH / CIP). * The magnitude-aware stagnation counter driving phase switching and adaptive SPR radius.

Parameter Type Description
accepted True iff the driver committed this move.
delta Score change ``new - old``; positive means strict improvement on the search objective (maximisation).
on_reheat -> None

Notify the kernel that the driver just fired a reheat. Reheats are the SA layer's explicit "we're stuck" signal -- they're computed from rolling improvement over a window, which is a *stronger* plateau signal than anything the kernel's own stagnation counter can see. On notification we: 1. Force ``_stagnation`` up to ``phase_patience`` so the next ``generate()`` call triggers a phase switch (if we aren't in the opposite phase already). This flips to retic-focused moves to try a structurally different escape route. 2. Arm the post-reheat broad-SPR window: the next ``SPR_BROAD_MODE_PROPOSALS`` SPR draws are forced to ``SPR_DECAY_MIN`` (near-flat, large hops) regardless of intervening phase switches or stagnation resets. The broad-SPR window is the critical half: without it, the phase switch from (1) resets ``_stagnation`` to 0 before a single broad SPR fires, reverting the move to local-only mode and cancelling the reheat's entire exploration intent. With it, reheats actually reach the basin-escape topology moves they were fired to attempt. No-ops for the non-phased kernel (custom ``weights`` path).

get_weights -> dict[str, float]

Return the current effective selection probabilities. Honours the active phase (when phased) and the adaptive scaler (when enabled); falls back to the fixed weight list otherwise. Useful for quick introspection or logging.

Returns: ``dict`` mapping move class name to probability in [0, 1] (summing to 1).
get_stats -> dict[str, dict[str, int | float]]

Lifetime per-move statistics across the search.

Returns: Mapping ``move_class_name -> {proposed, accepted, improved, acceptance_rate, improvement_rate}``. ``acceptance_rate`` is accepted / proposed (fraction of draws that were committed to the chain, including uphill-accepted moves). ``improvement_rate`` is improved / proposed (strict log-PL gain). Both rates default to 0 when a move was never sampled.
format_stats -> str

Return a human-readable summary of lifetime kernel statistics. Intended for printing at the end of a search. Includes per-move proposal / accept / improve counts, phase-switch summary, adaptive sigma end-state, SPR radius range, and the post-reheat broad-SPR window activation count.

GeneTreeTripletResult

class GeneTreeTripletResult

Container for precomputed gene-tree triplet frequencies (rho values). Returned by :func:`compute_gene_tree_triplets` and consumed by :func:`score_species_network_triplets` (or stored on :class:`MPL` for repeated scoring against varying species networks). Encodes the "gene-tree side" of the MPL inputs: all rho values are functions of the observed gene trees only and never change during a network search. Attributes: triplets: Canonical ordered species triplets, e.g. ``[('A', 'B', 'C'), ('A', 'B', 'D'), ...]``. rho_by_triplet: For each triplet ``(X, Y, Z)``, the empirical frequencies of the three rooted resolutions as a tuple ``(rho_XY|Z, rho_XZ|Y, rho_YZ|X)``. Values sum to approximately the number of gene trees that covered all three taxa (ties contribute 1/3 to each resolution).

Constructor

__init__(triplets: list[tuple[str, str, str]], rho_by_triplet: dict[tuple[str, str, str], tuple[float, float, float]]) -> None

Initialise the container.

Parameter Type Description
triplets Canonical species triplets.
rho_by_triplet Mapping ``triplet -> (rho_XY|Z, rho_XZ|Y, rho_YZ|X)``.

SpeciesNetworkTripletResult

class SpeciesNetworkTripletResult

Container for species-network triplet probabilities and final score. Returned by :func:`score_species_network_triplets`. Holds the "species-network side" of the scoring call: per-triplet predicted probabilities plus the summed log-pseudo-likelihood. Attributes: triplets: Canonical ordered species triplets (matching the order used during scoring). probs_by_triplet: For each triplet, predicted probabilities ``(P(XY|Z), P(XZ|Y), P(YZ|X))`` under the DP model. log_pseudo_likelihood: Total MPL score (higher is better; always <= 0 since it is a sum of ``rho * log(p)`` terms).

Constructor

__init__(triplets: list[tuple[str, str, str]], probs_by_triplet: dict[tuple[str, str, str], tuple[float, float, float]], log_pseudo_likelihood: float) -> None

Initialise the container.

Parameter Type Description
triplets Canonical species triplets.
probs_by_triplet Mapping ``triplet -> (P(XY|Z), P(XZ|Y), P(YZ|X))`` under the DP model.
log_pseudo_likelihood Final pseudo-likelihood score.

MCMCGTScorer

class MCMCGTScorer

Callable likelihood evaluator for :class:`Model`. Registered via ``model.set_likelihood_calculator(scorer)``. Holds a persistent :class:`_GTLikelihoodEngine` bound to ``model.network``; rebinds automatically when the scorer detects a network-object identity swap (e.g. after a deep-copy undo) or when ``model._dirty_nodes is None`` (topology change). Returns either the log posterior (``posterior=True``, the canonical Bayesian MCMC_GT objective) or the plain log likelihood (``posterior=False``, for ``method="hc"`` / ``"sa"`` where the prior term is irrelevant to the maximisation).

Properties

posterior_mode -> bool property

True if the scorer returns log posterior rather than log likelihood.

last_log_likelihood -> float | None property

Last likelihood value computed (``None`` before first call).

last_log_posterior -> float | None property

Last posterior value computed (``None`` before first call).

n_workers -> int property

Number of worker processes used by ``score_many`` (1 = serial).

Constructor

__init__(gene_trees: Iterable[Network] | GeneTrees, mapping: dict[str, list[str]], priors: Optional[MCMC_GTPriors] = None, posterior: bool = True, n_workers: int = 1) -> None

Initialise from gene trees, mapping, and prior hyperparams.

Parameter Type Description
gene_trees Either a :class:`GeneTrees` collection or any iterable yielding :class:`Network` gene trees.
mapping Species label -> list of gene-copy labels (same convention as :class:`MPL`). Internally flattened to a gene-copy -> species reverse map for the engine.
priors Prior hyperparameters. Default: :class:`MCMC_GTPriors` defaults (Exp(1) branch lengths, Beta(1,1) gammas, Poisson(1) retic count).
posterior When ``True`` (default), return log posterior. When ``False``, return plain log likelihood (priors dropped).
n_workers Number of worker processes for parallel ``score_many``. ``1`` (default) keeps the original serial path. When ``> 1``, a :class:`_ScoreManyPool` is constructed with that many workers; gene trees are broadcast to every worker once at pool startup. Capped at ``len(gene_trees)``. Pool is torn down via :meth:`close` (called automatically from :meth:`MCMC_GT.search` via try/finally).

Methods

close -> None

Tear down the worker pool if one was started. Safe to call multiple times; safe to call when no pool was ever started. :meth:`MCMC_GT.search` calls this from a ``finally`` block so chains terminate cleanly even on exceptions.

MCMCGTKernel

class MCMCGTKernel(ProposalKernel)

Phase-aware, Robbins-Monro-tuned proposal kernel for :class:`MCMC_GT`. Cycles between two complementary search phases (same design as :class:`MPL.MPLKernel`): **TOPOLOGY** -- SPR + branch-length / inheritance-prob tuning; small bleed (~10% aggregate) of reticulation moves. **RETICULATION** -- Add/Remove/Flip/Source/Dest/Relocate + gamma tuning; small bleed (~10%) of SPR + ChangeNodeHeight so local refinements still happen alongside retic restructuring. Phase transitions fire after ``phase_patience`` consecutive proposals without an accepted log-posterior delta exceeding ``stagnation_reset_delta``. Within each phase, ``ChangeNodeHeight`` and ``ChangeInheritanceProb`` adapt their proposal sigmas via Robbins-Monro toward 0.234 acceptance (Roberts/Gelman/Gilks 1997), and ``SPR`` interpolates `...

Properties

adaptive -> bool property

``True`` while the kernel is still adapting sigmas/weights.

phase -> str property

Current search phase (``"topology"`` or ``"reticulation"``).

Constructor

__init__(max_reticulations: Optional[int] = None, weights: Optional[dict[type, float]] = None, rng: Optional[np.random.Generator] = None, move_types: Optional[list[type]] = None, max_level: Optional[int] = None, adaptive: bool = True, window_size: int = 30, min_weight: float = 0.05, phase_patience: int = 150, warmup: int = 8, stagnation_reset_delta: Optional[float] = None) -> None

Configure the kernel.

Parameter Type Description
max_reticulations Upper bound on retic count. When the current network is at or above the cap, :class:`AddReticulation` is filtered out of the candidate pool.
move_types Optional restriction of the move classes the kernel may draw from (``opt_bl`` / ``fix_st`` search flags filter this via :func:`phynetpy._search_flags.resolve_move_types`). When ``None`` the full default set is used.
max_level Cap on network level (``max_lvl`` search flag), passed to every level-raising move so they self-reject proposals that would exceed the cap. ``None`` disables the per-move check (the accept-path guard remains authoritative).
weights When supplied, disables phase cycling and adaptive tuning; the kernel reverts to the v1 fixed-weight behaviour. Useful for unit tests and "I know exactly what I want" callers.
rng NumPy random Generator. When ``None``, a fresh one is created from OS entropy; callers that care about reproducibility should pass one seeded from the chain's :class:`np.random.SeedSequence`.
adaptive Enable within-phase adaptive weight scaling (efficiency-aware) and Robbins-Monro sigma tuning. Ignored when ``weights`` is supplied. Default ``True``.
window_size Sliding-window length for per-move acceptance/improvement statistics.
min_weight Floor on the multiplicative scale factor applied to base weights, to prevent any move from being fully starved.
phase_patience Consecutive non-improving proposals before the kernel switches to the next phase.
warmup Minimum observations per move class before the adaptive scaler activates for that class.
stagnation_reset_delta Minimum strict-improvement magnitude (in log-posterior units) that counts as "real progress" for stagnation-reset purposes. ``None`` -> :attr:`_MCMCGTAdaptiveConfig.STAGNATION_RESET_DELTA`.

Methods

freeze_adaptation -> None

Disable all online adaptation; keep current sigmas/phase fixed. Called by :meth:`MCMC_GT._run_mh` exactly when the burn-in window ends. The post-freeze chain is a proper Bayesian posterior sample (no diminishing-adaptation gymnastics required). Stat counters keep updating so ``format_stats`` still reports honest per-move accept rates over the post-burn-in window.

generate(model: 'Model | None' = None) -> Move

Sample a :class:`Move` from the current effective distribution.

Parameter Type Description
model Optional current model. Used for cap-aware filtering (``AddReticulation`` dropped at the cap).
Returns: Freshly-instantiated: class:`Move`. Continuous moves (``ChangeNodeHeight``, ``ChangeInheritanceProb``) are instantiated with the kernel's current adaptive sigma; ``SPR`` with its current adaptive ``distance_decay``.
report_outcome(accepted: bool, delta: float = 0.0) -> None

Record a move outcome and update adaptive state. Called by the search driver after each ``generate -> propose -> score`` cycle, regardless of accept/reject.

Parameter Type Description
accepted True iff the driver committed the move to the chain.
delta ``log_posterior_proposed - log_posterior_current``. Positive means the proposal landed in a strictly higher-density region of the posterior.
get_weights -> dict[str, float]

Return the current effective selection probabilities. Honours phase + adaptive scaler. Useful for diagnostic printing mid-run.

get_stats -> dict[str, dict[str, float]]

Lifetime per-move statistics across the search.

Returns: Mapping ``move_class_name -> {proposed, accepted, improved, acceptance_rate, improvement_rate}``.
format_stats -> str

Return a human-readable summary of lifetime kernel statistics. Includes per-move counts/rates, phase-switch summary, adaptive sigma end-state, and SPR distance-decay range. Prints sorted by proposal count (descending) for at-a-glance reading of the actually-active moves.

MCMCSeqKernel

class MCMCSeqKernel

Weighted mixture of MCMC_SEQ operators. On each step :meth:`propose` selects an operator by weight and applies it. The default weights split effort across gene-tree moves and species-network moves in roughly the proportions PhyloNet uses (more weight on gene trees when there are few loci, since they carry most of the signal). Attributes: rng: Random generator driving operator selection and proposals.

Constructor

__init__(rng: np.random.Generator, max_reticulations: int = 4, coupled_dimension_moves: bool = False) -> None

Build the kernel.

Parameter Type Description
rng Random generator.
max_reticulations Reticulation cap (disables add when reached).
coupled_dimension_moves When ``True`` the add / delete-reticulation moves re-propose every gene tree at the instant the dimension changes (:func:`op_add_reticulation_coupled` / :func:`op_delete_reticulation_coupled`). When ``False`` (default) they change only the network and let the gene trees migrate gradually via the per-locus moves (:func:`op_add_reticulation_decoupled` / :func:`op_delete_reticulation_decoupled`). The decoupled scheme (PhyloNet's) avoids the trans-dimensional hysteresis the coupled all-at-once re-proposal induces and mixes across reticulation counts far better.

Methods

propose(state: SeqState) -> Optional[tuple[float, Callable]]

Select and apply one operator.

Returns: ``(log_hastings_ratio, undo)`` on success, or ``None`` if the chosen operator was inapplicable / illegal.

FelsensteinCalculator

class FelsensteinCalculator

Per-locus phylogenetic likelihood ``P(S | g)`` via vectorised pruning. On construction the alignment for one locus is compressed to its distinct site patterns (columns), each carrying an integer weight (how many original sites share that pattern). Scoring a gene tree then runs one post-order sweep in which every node's conditional likelihoods are an ``(n_patterns, 4)`` array, so a single ``partials @ P.T`` matrix product propagates all sites across a branch at once. This is the standard BEAGLE-style batching and is the source of the "sequences are very vectorizable" speed-up. Attributes: taxa: Ordered list of leaf labels present in the alignment. n_patterns: Number of distinct site patterns after compression.

Constructor

__init__(alignment: dict[str, str]) -> None

Compress a single-locus alignment.

Parameter Type Description
alignment Map from leaf label to its aligned nucleotide string (all strings the same length). IUPAC ambiguity / gaps are allowed and expand to tip partials.

Methods

log_likelihood(gene_tree: Network, model: SubstitutionModel, site_rate: float = 1.0) -> float

Felsenstein log-likelihood of the alignment on ``gene_tree``.

Parameter Type Description
gene_tree A rooted *tree* (one connected component, no reticulations) whose leaves are labelled with this locus's taxa and whose edges carry branch lengths in substitution units.
model The nucleotide substitution model.
site_rate Optional per-locus relative mutation rate (PhyloNet's ``-murate``); branch lengths are effectively scaled by this. Defaults to 1.0 (rate variation off).
Returns: The summed log-likelihood over all (weighted) site patterns.

InferMPAllop

class InferMPAllop

Class that sets up and runs the Infer_MP_Allop_2.0 inference method.

Constructor

__init__(network: Network, gene_map: dict[str, list[str]], gene_trees: list[Network], iter_ct: int, rng: np.random.Generator) -> None

Initialize the parameters for this method call.

Parameter Type Description
network Network A starting network.
gene_map dict[str, list[str]] A subgenome mapping.
gene_trees list[Network] A set of gene trees.
iter_ct int Number of iterations to run the chain.
rng np.random.Generator random number generator.

Methods

run -> float

Computes the network with the lowest parsimony score over the set of given gene trees.

Returns: float: parsimony score of the most likely Network

MPAllopScorer

class MPAllopScorer

Callable scorer that integrates with Model.set_likelihood_calculator(). Computes the MP Allop parsimony score (negated for maximization).

Constructor

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

Create a new ``MPAllopScorer``.

Parameter Type Description
gene_map Subgenome mapping from species to their gene-copy
labels forwarded to the internal :class:`Allop_MUL`.
gene_trees Gene trees to reconcile against each candidate network's multiple-labelled tree.
rng Random generator used when resolving allele-map ties.

Allop_MUL

class Allop_MUL(MUL)

A Standard MUL tree with methods for calculating the maximum parsimony score for Infer_MP_Allop_2.0.

Methods

extra_lineages(coal_event_map: dict[tuple, str], f: AlleleMap) -> int

Computes the number of extra lineages in a mapping from a gene tree T, into a MUL tree, T'.

Parameter Type Description
coal_event_map dict[tuple[str, str], str] A mapping from edges in T' to a list of nodes of T that have been mapped into that edge.
f AlleleMap An allele map.
Returns: int: number of extra lineages
xl_helper(start_node: Node, edge_xl_map: dict, coal_map: dict[tuple[str, str], str], f: AlleleMap) -> None

Recursive helper that computes lineage counts for extra lineage calculation.

Parameter Type Description
start_node Node Node to process
edge_xl_map dict Mapping from edges to lineage counts [bottom, top]
coal_map dict Mapping from edges to gene tree internal node names
f AlleleMap allele mapping
gene_tree_map(g: Network, leaf_map: AlleleMap, mrca_cache: dict[frozenset[Node], Node]) -> dict[tuple, list[str]]

Maps a gene tree (T) into a MUL tree (T').

Parameter Type Description
g Network The gene tree
leaf_map AlleleMap Allele map from gene tree to MUL tree.
mrca_cache dict A cache for MRCA computations.
Returns: dict[tuple, list[str]]: Mapping from edges in T' to gene tree nodes.
XL(g: Network, mrca_cache: dict[frozenset[Node], Node]) -> int

Computes the minimum number of extra lineages over all possible allele maps for gene tree g mapped into this MUL tree.

Parameter Type Description
g Network A gene tree
mrca_cache dict A cache for MRCA computations.
Returns: int: the minimum number of extra lineages (>= 0)
XL_Allele(g: Network, f: AlleleMap, mrca_cache: dict[frozenset[Node], Node]) -> int

Compute the extra lineages for a specific allele mapping.

Parameter Type Description
g Network A gene tree
f AlleleMap An allele map from leaves of g to leaves of T
mrca_cache dict A cache for MRCA computations.
Returns: int: number of extra lineages
score(gt_list: list[Network]) -> int

Compute the total parsimony score over a list of gene trees.

Parameter Type Description
gt_list list[Network] a list of gene trees
Returns: int: The MUL tree score

AlleleMap

class AlleleMap

Data structure that holds a mapping from gene tree leaf names to MUL tree leaf names. Internally handles the mechanism for making sure gene copies are not mapped to the same subgenome.

Constructor

__init__() -> None

Create an empty ``AlleleMap`` with no leaves mapped yet.

Methods

put(g_leaf: Node, mul_leaf: str) -> int

Map a gene tree leaf to a MUL tree leaf.

Parameter Type Description
g_leaf Node a gene tree leaf
mul_leaf str a MUL tree leaf label
Returns: int: 0 if the mapping was unsuccessful, 1 if it was.

SimulatedData

class SimulatedData

A simulated multilocus data set with its ground truth. The fields under "inputs to inference" are exactly what :class:`phynetpy._mcmc_seq.MCMC_SEQ` consumes; the "ground truth" fields are what a recovery / calibration check compares the posterior against. Attributes: loci: Per-locus alignments (allele label -> aligned sequence string). mapping: Species label -> list of allele (gene-copy) labels sampled. species_of: Allele label -> species label (inverse of ``mapping``). gene_trees: The *true* simulated gene tree for each locus. true_network: The species network the data were generated on. true_theta: The population mutation rate used. true_branch_thetas: Fixed branch-specific population rates used. model: The substitution model used. seq_length: Number of sites...

Methods

to_mcmc_seq_kwargs -> dict[str, Any]

Keyword arguments to construct an :class:`MCMC_SEQ` on this data.

Returns: Constructor keywords for ``MCMC_SEQ``. The true network and gene trees are deliberately *not* passed so recovery starts from an independent UPGMA guess.

ParameterSummary

class ParameterSummary

Tracer-style summary statistics for one traced parameter. Attributes mirror the columns Tracer shows in its "Estimates" table.

Properties

ess_ok -> bool property

Whether ESS clears Tracer's poor-mixing threshold (200).

ChainSummary

class ChainSummary

A table of :class:`ParameterSummary` objects for a whole chain.

Properties

min_ess -> float property

Smallest ESS across all parameters (the binding diagnostic).

converged -> bool property

Heuristic: every parameter clears the ESS threshold.

Methods

__getitem__(name: str) -> ParameterSummary
__iter__
low_ess -> list[str]

Names of parameters whose ESS is below the threshold.

to_dict -> dict[str, dict[str, float]]

Plain nested dict (handy for JSON / DataFrame construction).

__str__ -> str

Module Functions

infer(data: Data, model: Union[Model, str, None] = None, criterion: Union[Criterion, str, None] = None, start: Union[Start, Network, None] = None, **search: Any) -> InferenceResult

Infer a phylogenetic network from data.

Parameter Type Description
data The observations: a :class:`~phynetpy.data.GeneTrees`, :class:`~phynetpy.data.Alignment`, or :class:`~phynetpy.data.BiallelicMarkers`. Carries the species-to-allele mapping.
model The generative process. Defaults to :class:`~phynetpy.models.MSC` (diploid + ILS). A string shortcut such as ``"MSC"`` is accepted.
criterion The statistical objective. Defaults to :class:`~phynetpy.criteria.Likelihood`. A string shortcut such as ``"MPL"`` or ``"MDC"`` is accepted.
start Optional starting phylogeny. A bare :class:`~phynetpy.Network.Network` is treated as ``Start(net)`` -- a free starting point. Wrap it as ``Start(net, mode=StartMode.AUGMENT)`` to require that the result contain it. ``None`` lets the engine build its own seed (usually a majority-rule consensus of the gene trees). **search: Generic search controls, forwarded to the engine: ``max_reticulations``, ``max_lvl``, ``num_iter``, ``preset``, ``seed``, ``n_workers``, ``progress``, and driver-specific extras. Objective-specific settings belong on the criterion instead (``Bayesian(chain_length=...)``, ``PseudoLikelihood(subsets=...)``).
Returns: InferenceResult: The best network, its score, and -- for Bayesian runs -- the retained posterior sample.
Raises: TypeError: If the criterion is not defined on this data type., ValueError: If the criterion needs branch lengths the data lacks., NotImplementedError: If the combination is valid but unimplemented. Examples: Maximum pseudo-likelihood from gene trees:: result = infer(gts, criterion=PseudoLikelihood()) Bayesian sampling on top of a pseudo-likelihood:: result = infer(gts, criterion=Bayesian( objective=PseudoLikelihood(), chain_length=200_000, ))
score(network: Network, data: Data, model: Union[Model, str, None] = None, criterion: Union[Criterion, str, None] = None, optimize: bool = False, **search: Any) -> float

Score a single network against data under some criterion.

Parameter Type Description
network The network to score.
data The observations.
model The generative process. Defaults to :class:`~phynetpy.models.MSC`.
criterion The statistical objective. Defaults to :class:`~phynetpy.criteria.Likelihood`. Must be scorable: :class:`~phynetpy.criteria.Bayesian` is not, because a Bayesian score of one fixed network collapses to its wrapped objective.
optimize ``False`` (default) scores the network exactly as given, using its own branch lengths and inheritance probabilities. ``True`` optimises those continuous parameters and reports the best score attainable for this topology. **search: Controls for the ``optimize=True`` parameter search (``max_rounds``, ``improve_threshold``, ``scope``, ...).
Returns: float: The objective value. A log likelihood, log pseudo-likelihood, or log posterior density for the likelihood-based criteria (higher is better); an extra-lineage count for :class:`~phynetpy.criteria.MDC` (lower is better).
Raises: TypeError: If the criterion is not defined on this data type, or is not scorable on its own., ValueError: If the criterion needs branch lengths the data lacks., NotImplementedError: If the combination is valid but unimplemented. Examples: The deep-coalescence count of a network, PhyloNet's separate parsimony-scoring command:: score(net, gts, model=MSC(), criterion=MDC()) The best likelihood this topology can attain:: score(net, gts, criterion=Likelihood(), optimize=True)
simulate(model: Any = None, network: Optional[Network] = None, n: int = 1, data: str = 'gene_trees', mapping: Optional[Dict[str, List[str]]] = None, seq_length: int = 500, seed: Any = None, taxa: Any = None, birth_rate: float = 1.0, **params: Any) -> Data

Generate data under ``model`` along ``network``.

Parameter Type Description
model The generative process (:class:`~phynetpy.models.MSC`). A string shortcut such as ``"MSC"`` is accepted; ``None`` defaults to ``MSC()``. Process parameters are read off the model: ``theta``/``branch_thetas`` for the coalescent and ``u``/``v`` for markers.
network The species network to simulate along. Needs branch lengths tagged as ``SUBSTITUTIONS_PER_SITE`` and inheritance probabilities on reticulation in-edges. ``None`` draws a species *tree* under a pure-birth process instead, which requires *taxa*.
n How much data to generate. Number of gene trees, number of loci, or number of marker sites, depending on *data*.
data Which data-axis type to return -- ``"gene_trees"``, ``"alignment"``, or ``"markers"``.
mapping Species -> list of allele labels to sample. ``None`` samples one allele per leaf, named after the leaf.
seq_length Sites per locus, for ``data="alignment"``.
seed Random seed for reproducibility.
taxa Tip count, or list of tip labels, for the species tree drawn when *network* is ``None``.
birth_rate Speciation rate for that pure-birth (Yule) process. **params: Extra arguments forwarded to the underlying simulator (``substitution_model``, ``samples``, ...).
Returns: Data: A :class:`~phynetpy.data.GeneTrees`, :class:`~phynetpy.data.Alignment`, or :class:`~phynetpy.data.BiallelicMarkers`, carrying *mapping*, so the result feeds directly into :func:`~phynetpy.infer.infer` and :func:`~phynetpy.infer.score`. The generating network is attached as ``.true_network`` so a recovery check needs nothing else.
Raises: TypeError: If neither *network* nor *taxa* is given., ValueError: If *data* is not a recognised kind, *n* is not positive, or the species-tree parameters are inconsistent., NotImplementedError: If the model has no simulator for this data kind. Examples: A recovery check -- simulate under a known network, then try to get it back:: sim = simulate(MSC(theta=0.02), true_net, n=50, mapping=mapping) result = infer(sim, criterion=PseudoLikelihood()) A null check on a species tree PhyNetPy drew itself:: sim = simulate(MSC(), taxa=6, n=200) result = infer(sim, criterion=PseudoLikelihood()) compare_networks(result.best, sim.true_network)
convert_network_branch_lengths(network: 'Network', target: BranchLengthUnit | str, theta: float, branch_thetas: Optional[Mapping[BranchThetaKey, float]] = None) -> 'Network'

Return a structural copy with branch lengths converted explicitly. Conversion follows ``t_coal = 2*t_sub/theta_branch``. The source unit is read from ``network`` and must already be explicit. Node-time annotations are copied unchanged; biological calculations derive timing from edges.

run_parallel_chains(sampler: 'MCMC_SEQ', n_chains: int = 4, num_iter: int = 1000000, burn_in: int = 100000, sample_freq: int = 100, seed: Any = None, check_every: int = 2000, monitor: Optional[Callable[[MultiChainStatus], Optional[str]]] = None, rhat_params: Sequence[str] = ('posterior', 'theta', 'reticulationCount'), progress: bool = True, poll_interval: float = 0.5, shutdown_grace_sec: float = 30.0, temperatures: Optional[Sequence[float]] = None, swap_interval: int = 1) -> MultiChainResult

Run ``n_chains`` independent MCMC_SEQ chains in parallel processes. Each chain is the same sampler seeded from an independent sub-stream, so the chains are over-dispersed and their cross-chain Gelman-Rubin R-hat (reported live and in the result) is a valid convergence diagnostic. Control: every ``check_every`` iterations each worker reports its state; the parent aggregates them into a :class:`MultiChainStatus` and, if ``monitor`` is given, calls ``monitor(status)``. Return: * ``"continue"`` / ``None`` -- keep sampling (clears any pause); * ``"pause"`` -- block every chain in place (re-polled until the monitor stops returning ``"pause"``); * ``"stop"`` -- halt every chain and return partial results. A ``KeyboardInterrupt`` (Ctrl-C) in the parent also stops gracefully.

Parameter Type Description
sampler A fully constructed :class:`MCMC_SEQ` (must be picklable; it is copied to each worker). Its ``priors.max_reticulations`` is honoured by each chain's default kernel.
n_chains Number of parallel chains / processes.
num_iter Iterations per chain.
burn_in Per-chain burn-in before sampling.
sample_freq Per-chain thinning interval.
seed Master seed; each chain gets an independent spawned sub-seed.
check_every Iterations between control/report checkpoints.
monitor Optional callback driving pause/stop (see above).
rhat_params Trace columns to track for live R-hat. Valid names: ``posterior``, ``likelihood``, ``prior``, ``theta``, ``reticulationCount``.
progress Print a live dashboard when ``True``.
poll_interval Parent queue-poll cadence (seconds).
shutdown_grace_sec How long to wait for workers to return partial results after a stop before terminating them.
temperatures Optional MC3 temperature ladder (e.g. ``[1.0, 2.0, 3.0]``) forwarded to every chain; when given, each of the ``n_chains`` processes runs a full Metropolis-coupled ensemble and contributes its cold chain to the cross-chain R-hat. ``None`` runs plain single chains.
swap_interval MC3 swap cadence (iterations) forwarded to each ensemble.
Returns: A: class:`MultiChainResult` with per-chain results, final R-hat, and any per-chain error tracebacks.
register(data_cls: type, model_cls: type, criterion_cls: type) -> Callable[[Type[Engine]], Type[Engine]]

Register an engine for one cell of the validity matrix. Every implemented method is exactly one registration site, which makes the mapping from PhyloNet commands to PhyNetPy code one-to-one and self-documenting.

Parameter Type Description
data_cls The :class:`~phynetpy.data.Data` subclass.
model_cls The :class:`~phynetpy.models.Model` subclass.
criterion_cls The :class:`~phynetpy.criteria.Criterion` subclass.
Returns: A decorator that registers the engine class and returns it unchanged.
Raises: ValueError: If the cell is already registered.
resolve(data: Data, model: Model, criterion: Criterion) -> Type[Engine]

Resolve a triple to its engine, or explain why it cannot be run. Runs the three checks in order, so the most fundamental objection is always the one reported.

Parameter Type Description
data The observations.
model The generative process.
criterion The statistical objective.
Returns: The: class:`Engine` subclass implementing this cell.
Raises: TypeError: If *criterion* is not defined on this data type, or if an argument is not an axis object at all., ValueError: If the criterion was asked to use branch lengths the data does not carry., NotImplementedError: If the combination is legal in principle but has no engine yet.
registered_cells -> List[Tuple[str, str, str, str]]

List every implemented cell of the validity matrix.

Returns: list[tuple[str, str, str, str]]: ``(data, model, criterion, method)`` tuples, sorted, where ``method`` is the PhyloNet command the engine corresponds to.
validity_matrix(model_cls: Optional[type] = None) -> Dict[str, Dict[str, str]]

Render the validity matrix for one model as nested dicts. Regenerates the design memo's table from the code, so the documentation cannot drift from what is actually registered. Each cell is one of: * the engine's method name -- implemented; * ``"-"`` -- valid in principle, no engine yet (``NotImplementedError``); * ``"x"`` -- illegal in principle (``TypeError``).

Parameter Type Description
model_cls The :class:`~phynetpy.models.Model` subclass to tabulate. ``None`` uses :class:`~phynetpy.models.MSC`.
Returns: dict[str, dict[str, str]]: ``matrix[data_name][criterion_name]``.
optimize_network_parameters(model: Model, scorer: Callable[[Model], float], mapping: dict[str, list[str]], max_rounds: int = _DEFAULT_MAX_ROUNDS, improve_threshold: float = _DEFAULT_IMPROVE_THRESHOLD, min_branch: float = _MIN_BRANCH_LENGTH, max_branch: float = _MAX_BRANCH_LENGTH, branch_iters: int = _BRANCH_LINE_ITERS, scope: str = 'all') -> float

Maximise the score of ``model.network`` over its continuous params. Holds the topology fixed and optimises every identifiable branch length and reticulation inheritance probability *in place* via Brent coordinate ascent, returning the optimised score. The objective is evaluated through ``scorer`` -- any ``Callable[[Model], float]`` (e.g. an ``MCMCGTScorer`` for the full MSNC likelihood or an ``MPLScorer`` for the triplet pseudo-likelihood). Each evaluation flags a single network node dirty, which routes a likelihood engine that supports incremental invalidation (such as :class:`~phynetpy._mcmc_gt._GTLikelihoodEngine`) through its *partial* invalidation path -- the reason per-parameter line searches stay cheap. Scorers without that fast path simply rescore from scratch (still correct, just not as fast).

Parameter Type Description
model Live model whose ``network`` is optimised in place.
scorer A callable bound to ``model`` via ``model.set_likelihood_calculator``.
mapping Species -> allele-label map (used to skip unidentifiable single-allele pendant edges).
max_rounds Maximum coordinate-ascent sweeps over all params.
improve_threshold Stop once a full sweep improves the score by less than this.
min_branch max_branch: Inclusive bounds on each branch length (coalescent units). ``max_branch`` mirrors PhyloNet's ``-l`` default of 6.
branch_iters Brent evaluation cap per parameter per sweep.
scope Which parameters to optimise. ``"all"`` (default) optimises every identifiable edge plus all gammas -- the behaviour used for the one-time final optimisation. ``"reticulation"`` optimises the gammas and the branches incident to reticulation nodes. ``"gamma"`` optimises only the inheritance probabilities (no branch lengths) -- the cheapest per-topology scope, and a no-op for trees (r=0). Both restricted scopes leave the remaining branch lengths to the one-time final optimisation.
Returns: The maximised score.
compute_gene_tree_triplets(gene_trees: GeneTrees, mapping: dict[str, list[str]], species_labels: Optional[list[str]] = None) -> GeneTreeTripletResult

Enumerate triplets and precompute rho from ``gene_trees``. Gene-tree statistics are constant across a network search, so this is called exactly once up front.

Parameter Type Description
gene_trees Collection of gene trees.
mapping Species -> list of allele labels.
species_labels Optional explicit species list; defaults to ``sorted(mapping.keys())``. Provide this when scoring against a reduced taxon set (e.g. sub-sample experiments).
Returns: :class:`GeneTreeTripletResult` carrying triplets and rho.
Raises: ValueError: If fewer than three species labels are available (triplets require at least three taxa).
score_species_network_triplets(species_net: Network, gene_triplet_result: GeneTreeTripletResult) -> SpeciesNetworkTripletResult

Score a species network against precomputed triplet frequencies. Builds a fresh :class:`_TripleDPEngine` bound to ``species_net`` and walks every triplet, computing both predicted probabilities and the MPL log-sum.

Parameter Type Description
species_net Species network to evaluate.
gene_triplet_result Output of :func:`compute_gene_tree_triplets` (same gene-tree set).
Returns: :class:`SpeciesNetworkTripletResult` with per-triplet probabilities and the final log pseudo-likelihood.
Raises: ValueError: If a network triplet isn't present in ``gene_triplet_result`` (which indicates the rho table was built over a different species set than the network's leaves).
format_mpl_reference_comparison(found: Network, reference: Network, rho: dict[tuple[str, str, str], tuple[float, float, float]], triplets: list[tuple[str, str, str]], top_k: int = 25) -> str

Build a text report comparing a found network against a reference. The report covers four sections: 1. Final MPL scores for both networks and the signed gap. 2. Per-network reticulation summary (parent labels, subtree leaves) to eyeball where each reticulation sits. 3. Clade-level Venn counts: shared, only-in-found, only-in-reference. 4. Top ``top_k`` triplets where the reference outperforms the found network, ranked by log-likelihood gap -- useful for diagnosing *why* the found topology under-fits. Uses the same ``rho`` and ``triplets`` passed to :class:`MPL` so the reference is scored against the same observed gene-tree statistics.

Parameter Type Description
found Best network returned by the search.
reference Ground-truth or baseline network.
rho Triplet frequency table (gene-tree side).
triplets Canonical triplets to iterate over.
top_k How many worst-performing triplets to list.
Returns: Multi-line formatted report string (no trailing newline).
save_mpl_network_newick(net: Network, path: str | os.PathLike[str]) -> None

Serialize ``net`` as Newick to ``path`` (UTF-8, newline-terminated). Parent directories are created if they don't exist.

Parameter Type Description
net Network to serialise.
path Output path (str or ``os.PathLike``).
log_prior_network(net: Network, priors: MCMC_GTPriors) -> float

Compose the network prior from its component pieces. Components (all additive in log space): * **Topology**: ``priors.topology_weight * topology_prior_fn(net)`` when the caller supplies a custom topology prior; otherwise zero (uniform over topologies with the observed retic count). * **Branch lengths**: per-edge ``Exp(branch_length_rate)``. Zero-length and ``None`` branches are treated as the ``_LOG_FLOOR`` cap to avoid ``log(0)`` but keep the score finite for partially-annotated networks. * **Gammas**: per-reticulation ``Beta(gamma_alpha, gamma_beta)`` on one of the two parent-edge gammas (the other is ``1 - gamma`` by construction). * **Retic count**: ``Poisson(retic_count_mean)`` on the number of reticulation nodes.

Parameter Type Description
net Species network to score. All branch lengths / gammas read directly off the network's edges; no topology caching is performed here (callers that need caching should memoise at a higher level).
priors :class:`MCMC_GTPriors` hyperparameters.
Returns: Log prior (typically negative; the more "extreme" a network is under the prior, the more negative the value).
gene_tree_msnc_log_density(gene_tree: Network, species_net: Network, species_of: dict[str, str], theta: float = 0.02, branch_thetas: Optional[dict[BranchThetaKey, float]] = None) -> float

Log timed MSNC density log P(g | Psi) via joint-edge AC DP.

allop_parsimony_score(network: Network, gene_trees: list[Network], subgenome_map: dict[str, list[str]], rng: np.random.Generator = None) -> int

Compute the allopolyploid parsimony score of a network. The numerical core of the ``(GeneTrees, Allopolyploid, MDC)`` cell: expands *network* into its multiple-labelled (MUL) tree and counts the extra gene lineages needed to reconcile the gene trees with it. Reached from the public API as ``score(net, gene_trees, model=Allopolyploid(...), criterion=MDC())``.

Parameter Type Description
network Network The species network to score.
gene_trees list[Network] The gene trees to reconcile.
subgenome_map dict[str, list[str]] Subgenome-to-genes mapping.
rng np.random.Generator, optional RNG used when resolving allele maps. Defaults to a fresh generator.
Returns: int: The parsimony score (extra lineage count; lower is better).
Raises: InferAllopError: If the subgenome map cannot label the MUL tips of *network*.
simulate_gene_tree(species_net: Network, alleles_per_species: dict[str, list[str]], theta: float, rng: np.random.Generator, branch_thetas: Optional[dict[BranchThetaKey, float]] = None) -> Network

Simulate one gene tree under the multispecies network coalescent. Performs a backward-in-time, height-ordered sweep of ``species_net``. Sampled alleles enter at the leaves (height 0); lineages coalesce within each branch (:func:`_coalesce_within`); at a reticulation node each surviving lineage independently ascends one of the two parent edges with probability ``gamma`` / ``1 - gamma``; at the root the remaining lineages coalesce to a single MRCA.

Parameter Type Description
species_net Timed species network (ultrametric, substitution units) with reticulation inheritance probabilities on hybrid edges.
alleles_per_species Map species label -> the allele (gene-copy) labels to sample; these become the gene-tree leaf labels. Species absent from the map contribute a single lineage named after the species.
theta Constant population mutation rate (used for every branch unless ``branch_thetas`` overrides it).
rng Random generator.
branch_thetas Optional fixed per-population ``theta`` values.
Returns: A rooted, ultrametric: class:`Network` (a tree) with branch lengths in substitution units and leaves labelled by the sampled alleles.
simulate_sequences(gene_tree: Network, model: SubstitutionModel, n_sites: int, rng: np.random.Generator) -> dict[str, str]

Evolve an alignment of ``n_sites`` down ``gene_tree`` under ``model``. The root sequence is drawn i.i.d. from the model's stationary frequencies; each branch then mutates every site with that branch's transition matrix ``P(t)``.

Parameter Type Description
gene_tree Rooted gene tree with branch lengths in substitution units.
model Nucleotide substitution model.
n_sites Number of sites (alignment columns) to simulate.
rng Random generator.
Returns: Map from leaf label -> simulated nucleotide string (length ``n_sites``, alphabet ``A,C,G,T``).
simulate_multilocus(species_net: Network, mapping: dict[str, list[str]], n_loci: int, seq_length: int, theta: float = 0.02, model: Optional[SubstitutionModel] = None, branch_thetas: Optional[dict[Any, float]] = None, seed: Any = None) -> SimulatedData

Simulate a full multilocus data set on a known species network. For each of ``n_loci`` independent loci a gene tree is drawn under the MSNC (:func:`simulate_gene_tree`) and an alignment is evolved down it (:func:`simulate_sequences`).

Parameter Type Description
species_net The *true* timed species network (with gammas on hybrid edges).
mapping Species label -> list of allele labels to sample at every locus (use one allele per species for the single-individual case, or several to exercise multi-allele coalescence).
n_loci Number of independent loci to simulate.
seq_length Sites per locus.
theta Population mutation rate (constant across branches unless ``branch_thetas`` is given).
model Substitution model (default :class:`JC69`).
branch_thetas Optional fixed per-population ``theta`` values.
seed Seed for all randomness.
Returns: A: class:`SimulatedData` bundle ready for ``MCMC_SEQ(**data.to_mcmc_seq_kwargs())``.
effective_sample_size(values: Sequence[float]) -> float

Effective sample size of a univariate trace. Uses BEAST/Tracer's estimator ``ESS = N * gamma(0) / varStat`` where ``varStat`` is the initial-positive-sequence autocovariance sum. A perfectly independent chain yields ``ESS == N``; heavy autocorrelation drives it toward 1.

Parameter Type Description
values The sampled values of one parameter, in draw order.
Returns: The effective sample size. ``nan`` for a constant trace (no variance, ESS undefined -- Tracer shows a dash) and for fewer than two samples.
autocorrelation_time(values: Sequence[float], step_size: int = 1) -> float

Integrated autocorrelation time (in states).

Parameter Type Description
values The sampled values, in draw order.
step_size Number of MCMC states between consecutive samples (the sampling / thinning interval). Scales the result into state units exactly as Tracer does.
Returns: ``ACT = step_size * varStat / gamma(0)``; ``nan`` for a constant trace.
standard_error_of_mean(values: Sequence[float]) -> float

Monte-Carlo standard error of the mean, ``sqrt(varStat / N)``. This is the autocorrelation-corrected error Tracer reports, *not* the naive ``stdev / sqrt(N)`` (which ignores between-sample dependence).

hpd_interval(values: Sequence[float], prob: float = 0.95) -> tuple[float, float]

Highest-posterior-density (HPD) interval of a trace. The narrowest interval that contains a ``prob`` fraction of the samples -- the same credible interval Tracer displays (e.g. "95% HPD interval").

Parameter Type Description
values The sampled values.
prob Target coverage in ``(0, 1]`` (default 0.95).
Returns: ``(lower, upper)`` bounds. For a single sample both equal that value.
geweke(values: Sequence[float], first: float = 0.1, last: float = 0.5) -> float

Geweke (1992) convergence z-score. Compares the mean of the first ``first`` fraction of the chain to the mean of the last ``last`` fraction, standardised by their (spectral) standard errors. ``|z| < 2`` is consistent with convergence.

Parameter Type Description
values The sampled values, in draw order.
first Fraction of the chain taken from the start.
last Fraction taken from the end.
Returns: The z-score, or ``nan`` if the chain is too short / degenerate.
summarize(name: str, values: Sequence[float], step_size: int = 1, hpd_prob: float = 0.95) -> ParameterSummary

Compute a :class:`ParameterSummary` for one trace.

summarize_traces(traces: Mapping[str, Sequence[float]], step_size: int = 1, hpd_prob: float = 0.95, skip: Iterable[str] = ()) -> ChainSummary

Summarize every column of a trace table.

Parameter Type Description
traces Mapping from parameter name to its per-sample values.
step_size Sampling / thinning interval (states between samples).
hpd_prob Coverage for the reported HPD interval.
skip Column names to exclude (e.g. the ``state`` index column).
Returns: A: class:`ChainSummary`.
write_tracer_log(states: Sequence[int], traces: Mapping[str, Sequence[float]], path: str, comments: Optional[Sequence[str]] = None, state_column: str = 'state') -> None

Write a BEAST/Tracer-compatible tab-delimited ``.log`` file. The first column is the integer chain state; remaining columns are the traced parameters in ``traces`` insertion order. The file opens directly in Tracer.

Parameter Type Description
states Per-sample chain-state (iteration) indices.
traces Mapping from parameter name to per-sample values; every column must have the same length as ``states``.
path Output path (conventionally ending in ``.log``).
comments Optional ``#``-prefixed header lines (e.g. provenance).
state_column Name of the leading index column (Tracer expects ``state``).
read_tracer_log(path: str) -> tuple[list[int], dict[str, list[float]]]

Read a BEAST/Tracer ``.log`` file. Skips ``#`` comment lines, treats the first remaining row as the header and its first column as the integer chain state.

Parameter Type Description
path Path to the ``.log`` file.
Returns: ``(states, traces)`` where ``states`` is the list of state indices and ``traces`` maps each remaining column name to its list of floats.
write_trees_nexus(states: Sequence[int], newicks: Sequence[str], path: str, taxa: Optional[Sequence[str]] = None, prefix: str = 'STATE') -> None

Write sampled networks as a NEXUS ``TREES`` block. Produces a file consumable by DensiTree / TreeAnnotator and other NEXUS readers. Reticulate (extended-Newick) strings are written verbatim, which plain tree viewers may not render but which round-trips losslessly.

Parameter Type Description
states Per-sample chain-state indices (used to name each tree).
newicks Extended-Newick strings, one per sample, aligned with ``states``.
path Output path (conventionally ``.trees`` or ``.nex``).
taxa Optional explicit taxon list for the ``TAXA`` block; if omitted no ``TAXA`` block is written (most readers cope).
prefix Tree-name prefix; tree ``i`` is named ``<prefix>_<state>``.

Navigation

Modules

This Page