Library for the Development and Use of Phylogenetic Network Methods
The public inference API: the verbs infer, score, and simulate, the InferenceResult they return, infer_dimple for divide-and-conquer on a tree of blobs, plus the registry, scorers, kernels, result types, and MCMC diagnostics around them.
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``...
One line naming the method, the score and its sense, and the posterior size.
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`).
Whether the final network must contain this one as a subgraph.
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.
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.
The set of allele / sequence labels present in the data.
Explicit species -> allele mapping, or ``None`` if unset.
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``.
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). |
Set the explicit species -> allele mapping (``None`` to clear it).
Return an explicit mapping, falling back to identity.
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.
The set of gene-copy (allele) labels across all trees.
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.
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``.
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. |
DataError: If *trees* is empty or contains a reticulate network.Set the explicit species -> allele mapping, keeping it in step with ``species_gene_mapping``.
Species -> allele mapping, resolved through the naming rule. Defers to the inherited resolution chain: an explicit mapping, then the naming rule, then identity.
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. |
DataError: If the file cannot be read or holds no trees.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. |
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...
The set of sequence labels across all loci.
Number of loci.
Total aligned site count summed across loci.
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``. |
DataError: If no loci are supplied.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__`. |
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.
The set of taxon labels in the marker matrix.
Number of marker sites.
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. |
DataError: If *alignment* is not an ``MSA``.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. |
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...
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. |
ModelSpecError: If the model cannot be applied to *data*.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...
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. |
ModelSpecError: If any rate is non-positive.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.
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`). |
Return the subgenome assignment to use for *data*.
| Parameter | Type | Description |
|---|---|---|
| data | The :class:`~phynetpy.data.Data` being analysed. |
ModelSpecError: If no assignment is available.Check that a subgenome assignment can be resolved.
| Parameter | Type | Description |
|---|---|---|
| data | The data the run will consume. |
ModelSpecError: If no assignment is available.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.
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...
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.
Configure the parsimony criterion.
| Parameter | Type | Description |
|---|---|---|
| weighting | Per-tree weighting scheme (``"bootstrap"``, ``"posterior"``, ...). ``None`` weights every gene tree equally. |
CriterionError: If a weighting scheme is requested.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.
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. |
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.
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. |
CriterionError: If *subsets* is not ``"trinets"``.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...
Data types the wrapped objective is defined on.
Branch-length policy of the wrapped objective.
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). |
CriterionError: If the objective is itself Bayesian, or the chain budget is inconsistent.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...
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...
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``).
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``. |
Transition-probability matrix ``P(t) = exp(Q t)``.
| Parameter | Type | Description |
|---|---|---|
| t | Branch length in expected substitutions per site (``>= 0``). |
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.
Construct the parameter-free JC69 model.
Closed-form JC69 transition matrix (see class docstring).
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``).
Build an HKY85 model.
| Parameter | Type | Description |
|---|---|---|
| kappa | Transition/transversion rate ratio (``> 0``). | |
| pi | Stationary base frequencies (length 4, ``A,C,G,T``). |
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)``.
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``. |
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...
Fraction of proposals the driver accepted.
Build a Tracer-style trace table from the MH samples.
Write a BEAST/Tracer-compatible ``.log`` of the sampled chain.
Write the sampled species networks as a NEXUS ``.trees`` file.
Per-parameter diagnostics (mean, HPD, ESS, ...) for the MH chain.
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).
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...
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.
Build a Tracer-style trace table from the recorded samples.
Write a BEAST/Tracer-compatible ``.log`` of the sampled chain.
| Parameter | Type | Description |
|---|---|---|
| path | Output path (conventionally ``.log``); open it in Tracer. |
Write the sampled species networks as a NEXUS ``.trees`` file.
| Parameter | Type | Description |
|---|---|---|
| path | Output path (conventionally ``.trees``); for DensiTree / TreeAnnotator-style topology summaries. |
Per-parameter diagnostics (mean, HPD, ESS, ...) for the chain.
| Parameter | Type | Description |
|---|---|---|
| hpd_prob | Coverage for the reported HPD interval (default 0.95). |
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.
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.
Representative newick of the most-sampled topology (``None`` if empty).
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.
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.
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).
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.
The chain with the highest MAP log posterior (``None`` if empty).
All chains' post-burn-in samples concatenated.
Posterior P(number of reticulations) pooled across all chains.
Ranked ``(representative_newick, posterior_probability)`` pooled.
Representative newick of the most-sampled topology across chains.
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).
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.
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``, ...). |
Infer a network from *data*.
| Parameter | Type | Description |
|---|---|---|
| data | The observations. |
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. |
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__``.
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. |
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...
| 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``. |
Whether the next :meth:`generate` will change phase. Hill climbing decides to stop before it asks for the next move, and the phase change happens inside that request. When both counters reach the same threshold, the stop wins and the reticulation phase is never sampled. The driver calls this so a switch that is already due still gets one proposal.
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. |
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). |
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).
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.
Lifetime per-move statistics across the search.
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.
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).
Initialise the container.
| Parameter | Type | Description |
|---|---|---|
| triplets | Canonical species triplets. | |
| rho_by_triplet | Mapping ``triplet -> (rho_XY|Z, rho_XZ|Y, rho_YZ|X)``. |
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).
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. |
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).
True if the scorer returns log posterior rather than log likelihood.
Last likelihood value computed (``None`` before first call).
Last posterior value computed (``None`` before first call).
Number of worker processes used by ``score_many`` (1 = serial).
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). |
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.
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 `...
``True`` while the kernel is still adapting sigmas/weights.
Current search phase (``"topology"`` or ``"reticulation"``).
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`. |
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.
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). |
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. |
Return the current effective selection probabilities. Honours phase + adaptive scaler. Useful for diagnostic printing mid-run.
Lifetime per-move statistics across the search.
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.
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.
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. |
Select and apply one operator.
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.
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. |
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). |
Class that sets up and runs the Infer_MP_Allop_2.0 inference method.
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. |
Computes the network with the lowest parsimony score over the set of given gene trees.
Callable scorer that integrates with Model.set_likelihood_calculator(). Computes the MP Allop parsimony score (negated for maximization).
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. |
A Standard MUL tree with methods for calculating the maximum parsimony score for Infer_MP_Allop_2.0.
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. |
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 |
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. |
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. |
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. |
Compute the total parsimony score over a list of gene trees.
| Parameter | Type | Description |
|---|---|---|
| gt_list | list[Network] | a list of gene trees |
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.
Create an empty ``AlleleMap`` with no leaves mapped yet.
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 |
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...
Keyword arguments to construct an :class:`MCMC_SEQ` on this data.
Tracer-style summary statistics for one traced parameter. Attributes mirror the columns Tracer shows in its "Estimates" table.
Whether ESS clears Tracer's poor-mixing threshold (200).
A table of :class:`ParameterSummary` objects for a whole chain.
Smallest ESS across all parameters (the binding diagnostic).
Heuristic: every parameter clears the ESS threshold.
Names of parameters whose ESS is below the threshold.
Plain nested dict (handy for JSON / DataFrame construction).
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=...)``). |
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 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``, ...). |
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)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``, ...). |
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)Infer a network by dividing a tree of blobs and stitching the pieces. The scaffold is partitioned at its polytomies. Each subset is inferred with MSC triplet pseudo-likelihood (:func:`phynetpy.infer.infer`), and the subset networks are merged back onto the scaffold. This is not a criterion and it is not dispatched through the inference registry. Each subset is inferred by simulated annealing: :data:`SUBSET_RUNS` runs of :data:`SUBSET_ITERS` iterations, and the highest log pseudo-likelihood is kept. Extra keyword arguments are forwarded to each subset ``infer`` call and override those defaults (``num_iter``, ``n_runs``, ``method``, ``t_start``). ``seed`` seeds only the partition shuffle. The search seeds are ``0, 1, 2`` unless a ``seed`` keyword is passed in the forwarded arguments.
| Parameter | Type | Description |
|---|---|---|
| gene_trees | GeneTrees | Rooted gene trees on the full taxon set. Individual trees may omit taxa. They are not rerooted, and no outgroup leaf is added to them. |
| tree_of_blobs | Network | Rooted scaffold. A node with more than two children is a blob. |
| start_tree | Network | Binary tree on the same taxa, used as the pseudo-likelihood start on each subset. |
| max_subset_size | int | Largest subset. Default 12, minimum 4. |
| n_divisions | int | Alternative partitions of each blob. Default 15. |
| max_reticulations | int | Cap on each subset search. The merge can still keep every reticulation the subsets returned, so the stitched network can contain more than this many. |
| seed | int | Seed for the partition packings and the enumeration shuffle. The first division of every blob is deterministic. |
| outgroup | str | None | Leaf to drop from the scaffold before partitioning. Not inserted into the gene trees. ``None`` leaves the scaffold unchanged. |
| model_selection | str | None | Choose each subset's reticulation count by ``gain`` (recommended; a step must add more than :data:`SELECTION_GAIN_THRESHOLD`), ``aic``, ``bic``, or ``elbow`` over caps 0 to ``max_reticulations``, each cap warm-started from the one below, and, for ``gain``, ``aic`` and ``bic``, make the merger require the same gain of each reticulation. None keeps the fixed cap and DIMPLE's any-improvement rule. |
| true_network | Network | None | Ground-truth network. When given, each subset's cap is the number of detectable reticulations in the true network restricted to the subset (:func:`true_reticulation_bound`), the protocol of the DIMPLE |
| paper | and ``max_reticulations`` and the subset part of ``model_selection`` are not used. For benchmarks only. | |
| score_final | bool | Score the stitched network (a triplet table on every taxon; seconds to minutes on large data). False leaves ``score`` None. **search: Subset search settings, see :func:`subset_chains`. Defaults are simulated annealing, :data:`SUBSET_ITERS` iterations, |
| and | data:`SUBSET_RUNS` runs. A passed value replaces the default. ``chains=[{"method": "sa", "num_iter": 20000, "n_runs": 5}, {"method": "hc", "num_iter": 20000, "n_runs": 3}]`` runs a portfolio per subset and keeps the best-scoring network. |
DimpleError: If the inputs are illegal or a stitch step cannot place a clade., RuntimeError: If a blob's base tree has a non-finite pseudo-likelihood while reticulations are being placed.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 ``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. |
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. |
ValueError: If the cell is already registered.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. |
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.List every implemented cell of the validity matrix.
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`. |
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. |
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). |
ValueError: If fewer than three species labels are available (triplets require at least three taxa).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). |
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).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. |
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``). |
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. |
Log timed MSNC density log P(g | Psi) via joint-edge AC DP.
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. |
InferAllopError: If the subgenome map cannot label the MUL tips of *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. |
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. |
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. |
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. |
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. |
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).
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). |
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. |
Compute a :class:`ParameterSummary` for one trace.
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). |
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 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. |
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>``. |