PhyNetPy Documentation

Library for the Development and Use of Phylogenetic Network Methods

MetropolisHastings Module v1.0.0

Metropolis-Hastings MCMC and Hill Climbing search algorithms for phylogenetic inference.

Author:
Mark Kessler
Last Edit:
5/12/26
Source:
MetropolisHastings.py

Exceptions

exception HillClimbException(Exception)

This exception is raised when there is an error running the Hill Climbing algorithm.

exception MetropolisHastingsException(Exception)

This exception is raised when there is an error running the Metropolis Hastings algorithm.

ProposalKernel

class ProposalKernel(ABC)

Abstract class that defines proposal kernel behavior. In general, simply must have a generate method that spits out a move.

Constructor

__init__() -> None

Initialize a proposal kernel

Methods

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

*ABSTRACT METHOD* Generate the next move for a model to apply to the network.

Parameter Type Description
model Optional current model. Subclasses may use it for state-aware sampling (e.g. cap-aware filtering of ``AddReticulation`` when the network is already at ``max_reticulations``). Kernels that don't need state may ignore this parameter.
Returns: Move: Any newly instantiated object that is a subclass of Move.
report_outcome(accepted: bool, delta: float = 0.0) -> None

Report whether the last generated move was accepted or rejected. Subclasses may override this to implement adaptive weight tuning.

Parameter Type Description
accepted True if the move improved the score and was committed.
delta Score change (proposed - current). Positive means the proposal was better (for a maximisation problem).

Infer_MP_Allop_Kernel

class Infer_MP_Allop_Kernel(ProposalKernel)

Proposal kernel for the Infer_MP_Allop_2.0 method.

Constructor

__init__() -> None

Initialize proposal kernel for the Infer_MP_Allop_2.0 method.

Methods

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

Simply return a new SwitchParentage object.

Parameter Type Description
model Unused; accepted for interface compatibility.
Returns: SwitchParentage: A new switch parentage move.

HillClimbing

class HillClimbing

Class that implements the Hill Climbing search method.

Constructor

__init__(pkernel: ProposalKernel, submodel: GTR = None, data: Matrix | None = None, model: Model | None = None, num_iter: int = 500, stochastic: int = -1, enhanced_stop: bool = True) -> None

Initialize a Hill Climb search.

Parameter Type Description
pkernel ProposalKernel Some proposal kernel
submodel GTR, optional A substitution model. Defaults to JC.
data Matrix | None, optional A data matrix. Defaults to None.
model Model | None, optional A Model obj. Defaults to None.
num_iter int, optional Number of iterations. Defaults to 500.
stochastic int, optional Random seed. Defaults to -1.
enhanced_stop bool, optional Early stopping flag. Defaults to True.

Methods

run -> State

Run the hill climbing algorithm.

Returns: State: The final end state of the model.
run_many(count: int) -> list[float]

Runs the hill climbing algorithm 'count' times.

Parameter Type Description
count int the number of times to run.
Returns: list[float]: [mean, median, max, min]

MetropolisHastings

class MetropolisHastings

A special case of Hill Climbing, in which moves are accepted even if the score is not an improvement, based on the Hastings Ratio.

Constructor

__init__(pkernel: ProposalKernel, submodel: GTR = None, data: Matrix | None = None, model: Model | None = None, num_iter: int = 500) -> None

Initialize a Metropolis Hastings search.

Parameter Type Description
pkernel ProposalKernel A proposal kernel.
submodel GTR, optional A substitution model. Defaults to JC.
data Matrix | None, optional The data. Defaults to None.
model Model | None, optional A phylogenetic model. Defaults to None.
num_iter int, optional Number of iterations. Defaults to 500.

Methods

run -> State

Run the Metropolis-Hastings algorithm.

Returns: State: The end state.
run_many_different_start(count: int, format_stats: bool = True) -> list[float]

Runs the MH algorithm 'count' times.

Parameter Type Description
count int The number of times to run.
format_stats bool Flag to print stats.
Returns: list[float]: [mean, median, max, min]

SimulatedAnnealing

class SimulatedAnnealing

Simulated annealing search for phylogenetic network optimization. Temperature follows an exponential schedule from ``t_start`` toward ``t_end`` over (1 - plateau_frac) * num_iter adjustment steps. * ``schedule="cool"`` (default): ``t_start`` should exceed ``t_end`` so T drops (classic SA: explore early, exploit late). * ``schedule="heat"``: ``t_end`` should exceed ``t_start`` so T rises (greedy / hill-climbing when T is tiny, then more uphill acceptance later to escape local maxima). * ``schedule="geometric_reheat"``: Hold T for ``steps_per_temp`` iterations, then multiply by ``cooling_alpha`` (geometric cooling) down to ``t_min``. Reheats (multiply T by ``reheat_factor``, capped at ``t_start * reheat_cap_mult``) trigger when any of these stagnation signals fi...

Constructor

__init__(pkernel: ProposalKernel, model: Model, num_iter: int = 500, t_start: float = 10.0, t_end: float = 0.01, n_restarts: int = 1, seed: int = 42, plateau_frac: float = 0.0, progress_every: int = 0, schedule: Literal['cool', 'heat', 'geometric_reheat'] = 'cool', t_min: Optional[float] = None, cooling_alpha: float = 0.93, steps_per_temp: int = 100, reheat_threshold: int = 1000, reheat_factor: float = 2.0, reheat_window: int = 500, reheat_min_improve: float = 1.0, reheat_on_no_uphill: bool = True, reheat_cap_mult: float = 1.0, reheat_max_consecutive: int = 5) -> None
Parameter Type Description
pkernel Proposal kernel that generates moves.
model Initial Model object (network + scorer).
num_iter Iterations per annealing run.
t_start Initial temperature (T0). For ``geometric_reheat``, also the ceiling when reheating.
t_end For ``cool``/``heat``, target temperature. For ``geometric_reheat`` ignored unless ``t_min`` is omitted, then used as the floor temperature (same role as T_min).
n_restarts Number of independent restarts.
seed RNG seed for reproducibility.
plateau_frac Fraction of iterations to hold at ``t_start`` before beginning exponential cool/heat (0.0-1.0). Ignored for ``geometric_reheat``.
progress_every If > 0, print a progress line every this many iterations (current log score, temperature, best-so-far in run).
schedule ``"cool"`` / ``"heat"`` as above, or ``"geometric_reheat"``.
t_min Floor temperature for ``geometric_reheat`` (default: ``t_end``).
cooling_alpha Geometric factor applied every ``steps_per_temp`` iterations (0 < alpha < 1).
steps_per_temp Iterations at a given T before cooling by alpha.
reheat_threshold Backstop strict-stall trigger. If run-best has not strictly improved in this many iterations, reheat.
reheat_factor Factor applied to T on reheat (> 1).
reheat_window Window (in iterations) used for the rate-based plateau trigger and the frozen-chain uphill counter. Also doubles as the post-reheat grace period.
reheat_min_improve Minimum run-best gain (log-PL units) over ``reheat_window`` iters that still counts as progress. Below this -> reheat. Scale with taxa count / reticulations;
see class:`SimulatedAnnealing` docs.
reheat_on_no_uphill If True, also reheat when the chain accepted zero uphill moves during the last ``reheat_window`` iters AND window gain is below ``3 * reheat_min_improve`` (signals T is effectively 0 relative to typical deltas while progress is weak; healthy strict-descent runs are *not* reheated).
reheat_cap_mult Ceiling on post-reheat T expressed as a multiple of ``t_start``. ``1.0`` keeps the classic cap at ``t_start``; values > 1 allow progressively hotter escapes.
reheat_max_consecutive Cascade guard. Maximum number of reheats that may fire without any strict run-best improvement between them. Once hit, further reheats are suspended until the chain finds a new best score (at which point the counter resets). Set to a very large int to disable the guard.

Methods

run -> State

Run simulated annealing (with optional restarts).

Returns: State holding the best network found across all restarts.

Navigation

Modules

This Page