πŸ’» Simulator

Tools for stochastic phylogenetic simulation.

🎲 Hazards

Model time-varying event rates in simulations.

class phyloom.simulator.hazards.ConstantHazard(rate: float)[source]

Bases: Hazard

Hazard with a constant event rate.

Given a positive rate \(r\), the instantaneous event rate at time \(t\) is

\[\lambda(t) = r.\]

For starting time \(t_0\), later time \(t\), and positive threshold \(c\), the cumulative hazard \(H(t_0, t)\) and its inversion are

\[H(t_0,t) = r(t-t_0), \qquad H^{-1}(t_0,c) = t_0 + \frac{c}{r}.\]
Parameters:

rate – The constant event rate \(r\), which must be positive.

invert(t0: float, threshold: float) → float | None[source]

Return the time at which the constant cumulative hazard reaches threshold.

class phyloom.simulator.hazards.DeltaHazard[source]

Bases: Hazard

Degenerate hazard for an event occurring immediately.

This hazard represents a point-mass event at the current time rather than an ordinary, absolutely continuous rate. For starting time \(t_0\) and every positive threshold \(c\), inversion is defined as

\[H^{-1}(t_0,c) = t_0.\]

Thus, the event occurs at \(t_0\) regardless of \(c\). This is useful for events that should fire as soon as they are eligible.

invert(t0: float, threshold: float) → float[source]

Return t0, since the hazard fires immediately.

class phyloom.simulator.hazards.ExponentialHazard(rate: float, decay: float)[source]

Bases: Hazard

Hazard whose rate changes exponentially with time.

Given a positive base rate \(r\) and decay parameter \(d\), this models

\[\lambda(t) = r\,e^{-dt}.\]

Its cumulative hazard is

\[\begin{split}H(t_0,t) = \begin{cases} r(t-t_0), & d=0,\\[4pt] \dfrac{r}{d}\left(e^{-dt_0}-e^{-dt}\right), & d\ne 0. \end{cases}\end{split}\]

Therefore, for \(d\ne 0\) and positive threshold \(c\), inversion is

\[H^{-1}(t_0,c) = -\frac{1}{d}\log\left(e^{-dt_0}-\frac{dc}{r}\right)\]

When \(d>0\), the total future cumulative hazard is

\[\lim_{t\to\infty} H(t_0,t) = \frac{r}{d}e^{-dt_0};\]

thresholds at or above this limit are never reached and inversion returns None. Negative decay values model exponential growth and have no finite upper limit on cumulative hazard.

Parameters:
  • rate – The base rate \(r\), which must be positive.

  • decay – The exponential decay parameter \(d\).

invert(t0: float, threshold: float) → float | None[source]

Invert the exponential cumulative hazard analytically.

class phyloom.simulator.hazards.Hazard[source]

Bases: ABC

Base class for time-dependent event rates.

A hazard is a non-negative instantaneous event rate \(\lambda(t)\), where \(t\) is time. Starting at time \(t_0\), the cumulative hazard \(H(t_0, t)\) at a later time \(t\) is

\[H(t_0, t) = \int_{t_0}^{t} \lambda(s)\,\mathrm{d}s.\]

To schedule an event, the simulator draws a positive threshold \(c\), representing the random amount of event pressure that must accumulate before the event occurs. The inverse cumulative hazard gives the corresponding event time:

\[H^{-1}(t_0, c) = \inf\{t \geq t_0 : H(t_0, t) \geq c\}.\]

A larger hazard accumulates event pressure more quickly and therefore leads to shorter expected waiting times.

The inversion mechanics are delegated to subclasses, which implement invert() for their specific rate function.

abstract invert(t0: float, threshold: float) → float | None[source]

Find the time at which a cumulative-hazard threshold is met.

Parameters:
  • t0 – Non-negative starting time \(t_0\).

  • threshold – Positive cumulative-hazard threshold \(c\).

Returns:

The earliest time \(t \geq t_0\) at which the threshold is met, or None if it is never met.

class phyloom.simulator.hazards.NumericHazard(rate_fn: Callable[[float], float], *, max_bracketing_steps: int = 16, initial_dt: float = 1.0)[source]

Bases: Hazard

Hazard defined by an arbitrary non-negative rate function.

This hazard models \(\lambda(t) = f(t)\) for a generic user-supplied function \(f\) that returns the non-negative event rate at time \(t\). The cumulative hazard is evaluated by numerical quadrature and inversion uses a bracketed root solver. The search begins at \(t_0 + \mathrm{initial\_dt}\) and doubles the search interval at most max_bracketing_steps times. If it cannot find a bracket, inversion returns None; the threshold may be unreachable or the configured search limit may be too small.

Parameters:
  • rate_fn – Function \(f\) that returns the non-negative event rate \(f(t)\) at time \(t\).

  • max_bracketing_steps – Maximum number of times to expand the time interval when searching for a bracket for the root solver.

  • initial_dt – Initial width of the time interval to search for a bracket for the root solver.

invert(t0: float, threshold: float) → float | None[source]

Invert the cumulative hazard by numerical integration and root finding.

class phyloom.simulator.hazards.SkylineHazard(rates: Sequence[float], break_times: Sequence[float])[source]

Bases: Hazard

Hazard with a piecewise-constant rate over time intervals.

Let \(m\) be the number of break times, and let \(b_1 < \dots < b_m\) be those times. With \(b_0 = 0\) and \(b_{m+1} = \infty\), the event rate \(r_i\) applies for each time \(t\) between consecutive break times:

\[\lambda(t) = r_i \quad\text{for}\quad b_i \leq t < b_{i+1}.\]

For starting time \(t_0\) and later time \(t\), the cumulative hazard \(H(t_0, t)\) is the sum of the contributions from each interval:

\[H(t_0,t) = \sum_{i=0}^{m} r_i \left[\min(t,b_{i+1})-\max(t_0,b_i)\right]_+, \qquad [x]_+ = \max(x,0).\]

If the total cumulative hazard after \(t_0\) is less than the threshold \(c\), inversion returns None.

Parameters:
  • rates – Non-negative rates \(r_0,\dots,r_m\), one for each interval.

  • break_times – Positive, strictly increasing interval boundaries \(b_1,\dots,b_m\).

invert(t0: float, threshold: float) → float | None[source]

Invert the piecewise-linear cumulative hazard interval by interval.

🧱 Core

Building blocks for event-driven stochastic simulation models.

class phyloom.simulator.core.EventRule[source]

Bases: Protocol[ModelT_contra]

Defines state transition eligibility and mutation logic for a stochastic event.

An EventRule governs how state changes occur within a model, while its associated hazard governs when the event fires. A single rule manages one or more β€œopportunities”—individual elementary state transitions currently available in the model (e.g., an active lineage eligible for death, a source-recipient pair for infection, or a lineage pair for coalescence). The opportunity count directly scales the per-opportunity hazard to compute the total rate for the event.

Implementations must calculate opportunities without modifying the target model and, upon execution, apply exactly one valid transition (typically by sampling an opportunity uniformly at random and mutating the model state in place).

opportunities(model: ModelT_contra) → int[source]

Calculate the number of elementary state transitions currently available.

A return value of 0 indicates that the event is inactive in the current model state and cannot be selected by the simulator.

apply(model: ModelT_contra)[source]

Select and execute a single eligible transition on the model.

Mutates the target model state according to the event’s rule semantics. The simulator guarantees this method is invoked only when opportunities() returns a positive count for the current model state.

class phyloom.simulator.core.Event(rule: EventRule[ModelT_contra], hazard: Hazard, *, rate_multiplier: Callable[[ModelT_contra], float] | None = None)[source]

Bases: Generic[ModelT_contra]

Represents a discrete stochastic state transition with a sampled firing time.

An Event binds an EventRule (governing state mutations and opportunity counts) to a per-opportunity Hazard (governing time-dependent rates).

To propose a firing time, the event queries the rule’s active opportunity count, samples an exponential waiting threshold, and converts that threshold into an absolute time via the hazard. An optional state-dependent rate multiplier further scales the overall event rate. Higher opportunity counts or larger multipliers increase the total hazard rate, resulting in shorter expected waiting times.

Upon selection by the simulator, the event delegates the actual state mutation back to its underlying rule. This design decouples event scheduling from model mutation logic.

Parameters:
  • rule – Governs eligibility, opportunity counting, and state mutation.

  • hazard – The time-dependent per-opportunity hazard used to sample firing times.

  • rate_multiplier – An optional callable computing a non-negative rate-scaling factor from the model state. Returning zero disables the event.

query_firing_time(model: ModelT_contra) → float | None[source]

Sample the next proposed firing time for this event given the current model state.

Draws a standard exponential random variate, scales it by the active opportunity count and any configured rate multiplier, and passes the resulting integrated hazard threshold to the underlying hazard function to invert into an absolute time.

Parameters:

model – The target simulation model state to evaluate.

Returns:

The absolute proposed firing time, or None if the event is inactive (e.g., zero opportunities or zero rate multiplier).

apply(model: ModelT_contra)[source]

Execute the state mutation associated with this event.

Delegates to the underlying EventRule to select and apply a single eligible transition to model.

class phyloom.simulator.core.Model(events: Iterable[Event[Self]] = (), schedule: Iterable[tuple[float, Callable[[Self], None]]] = ())[source]

Base class for stepwise stochastic discrete-event simulations.

A Model stores a simulated clock, stochastic events, and deterministic actions scheduled at absolute times. Call step() repeatedly to advance the clock and apply transitions. On each call, the model samples proposed firing times for its events, advances to the earliest proposal, scheduled action, or supplied time limit, and applies all transitions due at that time. Transitions due simultaneously are applied in random order.

Concrete subclasses represent the domain state being modeled, such as a population, phylogenetic tree, or epidemiological network. State-transition implementations can use rng, inspect current_time, and add further events or actions with add_event() and add_action(). The model does not reset its clock, events, scheduled actions, or subclass state; callers control the simulation lifecycle.

Parameters:
  • events – Stochastic events governing continuous-time state transitions.

  • schedule – Iterable of (time, action) pairs. An action receives and mutates the model when its time is reached. Actions scheduled for the same time are shuffled before execution.

property rng: Random

Internal pseudo-random number generator.

Use this generator for any stochasticity in state-transition implementations to ensure reproducibility.

property current_time: float

The current simulated clock time of the model.

add_event(event: Event[Self])[source]

Dynamically add a new stochastic event to the model.

add_action(time: float, rule: Callable[[Self], None])[source]

Dynamically schedule a deterministic action at the specified time.

step(max_time: float | None = None) → bool[source]

Advance the simulation clock to the next transition time and apply all due transitions.

The clock advances to the earliest proposed stochastic event, scheduled action, or max_time. All events and actions due at that time are applied in random order. Supplying max_time prevents the clock from advancing beyond that time, but does not prevent events or actions scheduled for that time from being applied.

Parameters:

max_time – Optional inclusive upper limit for the simulated clock.

Returns:

False when no transition is applied, either because none is possible or because the next transition is after max_time; True when a transition is applied, including at max_time.

πŸ”€ Networks

Network simulation model and event rules.

class phyloom.simulator.net.LineageEventRule(state: str | None = None)[source]

Bases: Generic[NetModelT_contra]

Base rule for single-lineage transition events in a network model.

This class serves as an abstract base for stochastic events that target an individual active lineageβ€”such as lineage termination, sampling, state transitions, or speciation. It handles candidate selection by counting eligible lineages and uniformly sampling one when the event executes, delegating the actual state modification to subclasses.

Parameters:

state – Optional state identifier used to restrict event eligibility to a matching subset of active lineages. Defaults to None (all active lineages eligible).

opportunities(model: NetModelT_contra) → int[source]

Count the number of currently eligible lineages.

apply(model: NetModelT_contra)[source]

Uniformly sample an eligible lineage and delegate to apply_to_lineage().

abstract apply_to_lineage(model: NetModelT_contra, lineage: NodeID)[source]

Apply the event transition to the selected lineage.

class phyloom.simulator.net.LineagePairEventRule(states: tuple[str, str] | None = None)[source]

Bases: Generic[NetModelT_contra]

Base rule for pairwise lineage interaction events in a network model.

This class serves as an abstract base for stochastic events that operate on a pair of distinct active lineagesβ€”such as coalescence, reticulation, or gene flow. It provides automated candidate pair enumeration and uniform random sampling over eligible pairs, delegating the domain-specific transition logic to subclasses.

Pair eligibility depends on the pair of state selectors provided during initialization:

  • Unordered within-state pairs (selectors are identical or no state restriction): Pair combinations are calculated without replacement (\(\binom{n}{2} = n(n - 1) / 2\)), ensuring a lineage cannot interact with itself.

  • Ordered cross-state pairs (selectors are distinct values): Combinations are evaluated across the two candidate pools (\(n_1 \times n_2\)).

Parameters:

states – Optional state identifiers for each participant in the interaction. Defaults to None (all active lineages eligible for unordered pairing).

opportunities(model: NetModelT_contra) → int[source]

Count the number of currently eligible lineage pairs.

apply(model: NetModelT_contra)[source]

Uniformly sample an eligible lineage pair and apply the event transition.

Draws a single pair of lineages from the candidate pool defined by the state selectors and delegates the transition to the subclass implementation of apply_to_lineages().

abstract apply_to_lineages(model: NetModelT_contra, lineages: tuple[NodeID, NodeID])[source]

Apply the event transition to the selected lineage pair.

class phyloom.simulator.net.NetModel(events: Iterable[Event[Self]] = (), schedule: Iterable[tuple[float, Callable[[Self], None]]] = ())[source]

Bases: ABC, Model

Base abstraction for simulations that build phylogenetic networks.

A NetModel maintains the network constructed during a run as collections of nodes and directed edges. Nodes are lineage records, and an edge relates a parent lineage to a descendant lineage created from it.

Lineages are organized into states, which can be used to select lineages for events. States are represented by strings, and their biological interpretation is model-defined. A lineage is active while it exists at the current simulation time and can be changed by a subsequent event. get_current_lineages(), count_current_lineages(), and draw_current_lineages() respectively provide access to, count, and draw active lineages.

Subclasses must supply model-specific primitives to evolve active lineages through time, for example by replacing one or more lineages with their descendants and define time_of(), get_root(), and origin to describe the network’s timing and extent. This supports both forward-time models and backward-time models, such as coalescents.

The full history is exposed through history(). A skeleton can be supplied when only the ancestry of selected leaf lineages is needed, for example to obtain the history relevant to observed or sampled data while omitting unobserved parts of the simulation.

Parameters:
  • events – Stochastic events governing continuous-time state transitions.

  • schedule – Iterable of (time, action) pairs. An action receives and mutates the model when its time is reached. Actions scheduled for the same time are shuffled before execution.

property nodes: Mapping[NodeID, Node]

Read-only mapping of lineage node ids to node records.

property edges: Mapping[tuple[NodeID, NodeID], Edge[None]]

Read-only mapping from directed (parent, child) node-id pairs to edge records.

abstract get_root() → NodeID[source]

Root node id of the history built by the run.

property stem: Edge[None]

Stem edge connecting the history root to the origin time above it.

abstract property origin: float

Simulation origin time, preceding the history root.

abstract time_of(lineage: NodeID) → float[source]

Return the model time associated with a lineage node.

history() uses lineage times to set the length of an edge from parent to child to time_of(child) - time_of(parent). The stem length is time_of(get_root()) - origin.

state_of(lineage: NodeID) → str[source]

Return the state assigned to a lineage node.

get_current_lineages(state: str | None = None) → SetView[NodeID][source]

Return active lineages, optionally restricted to a state.

count_current_lineages(state: str | None = None) → int[source]

Return the number of active lineages, optionally restricted to a state.

draw_current_lineages(state: str | None = None, k: int = 1) → list[NodeID][source]

Uniformly draw k active lineage ids without replacement, optionally restricted to a state.

history(skeleton: Iterable[NodeID] | None = None, *, return_as: Literal['tree']) → Tree[float][source]
history(skeleton: Iterable[NodeID] | None = None, *, return_as: Literal['net'] = 'net') → Net[float]

Return the simulated history as a network or tree.

Without a skeleton, the result is the full history of the run: every lineage and relationship produced by the simulation. With a skeleton, the result is the ancestry of the selected leaf lineages, including their shared ancestry but excluding unrelated lineages.

Parameters:
  • skeleton – Leaf lineage ids that define the history to return. The result contains their shared ancestry, rather than lineages unrelated to them. This is useful when the full simulation includes lineages outside the observed or sampled history. If omitted, return the full simulated history.

  • return_as – Whether to return the history as a tree or a network.

Returns:

The full simulated history or the ancestry of the selected leaf lineages.

🌱 BDSH

BDSH (Birth-Death-Sampling-Hybridization) simulation framework.

class phyloom.simulator.bdsh.LDH(parent_states: tuple[str, str] | None = None, hybrid_state: str | None = None)[source]

Bases: LineagePairEventRule[BDSHModel]

Lineage-degenerative hybridization (LDH) event that replaces two active lineages with one hybrid child.

Parameters:
  • parent_states – Optional pair of states restricting the two parent lineages.

  • hybrid_state – Optional state assigned to the hybrid child. If omitted, the parents must share the same state, which the child inherits.

apply_to_lineages(model: BDSHModel, lineages: tuple[NodeID, NodeID])[source]

Replace the selected lineage pair with one hybrid child.

class phyloom.simulator.bdsh.LGH(parent_states: tuple[str, str] | None = None, hybrid_state: str | None = None, new_parent_states: tuple[str | None, str | None] = (None, None))[source]

Bases: LineagePairEventRule[BDSHModel]

Lineage-generative hybridization (LGH) event.

Models a dual-speciation hybridization event where two active parent lineages each give birth to a child lineage, and those two child lineages then hybridize. Both original parent lineages continue as active branches, while their offspring combine into a single hybrid lineage.

Parameters:
  • parent_states – Optional pair of states restricting the two parent lineages.

  • hybrid_state – Optional state assigned to the resulting hybrid lineage. If omitted, the parents must share the same state, which the child inherits.

  • new_parent_states – Optional pair of states assigned to the continuing parent lineages, in the same order as parent_states. A None entry inherits the parent’s state.

apply_to_lineages(model: BDSHModel, lineages: tuple[NodeID, NodeID])[source]

Hybridize one offspring of each selected lineage, keeping both lineages active.

class phyloom.simulator.bdsh.LNH(continuing_parent_state: str | None = None, terminating_parent_state: str | None = None, new_parent_state: str | None = None, hybrid_state: str | None = None)[source]

Bases: LineagePairEventRule[BDSHModel]

Lineage-neutral hybridization (LNH) event.

Models a combined speciation-hybridization event where an active lineage gives birth to an intermediate offspring that immediately hybridizes with a second active lineage. The primary parent lineage continues (with an optional state transition), while its new offspring merges with the secondary parent to form a hybrid lineage.

Parameters:
  • continuing_parent_state – Optional state restricting the primary (birth-giving) parent lineage.

  • terminating_parent_state – Optional state restricting the secondary (hybridizing) parent lineage.

  • new_parent_state – Optional state assigned to the continuing primary (birth-giving) parent lineage. If omitted, the continuing lineage inherits the parent’s state.

  • hybrid_state – Optional state assigned to the resulting hybrid lineage. If omitted, the parents must share the same state, which the child inherits.

apply_to_lineages(model: BDSHModel, lineages: tuple[NodeID, NodeID])[source]

Hybridize an offspring of the first selected lineage with the second selected lineage.

class phyloom.simulator.bdsh.BDSHModel(init_state: str, events: Iterable[Event[Self]] = (), schedule: Iterable[tuple[float, Callable[[Self], None]]] = ())[source]

Bases: NetModel

Birth-death-sampling-hybridization model.

The model evolves a rooted network forward in time from one initial lineage. Alongside the active lineages inherited from NetModel, it records sampled lineages: finalized lineages designated as observations. The sampled set can be used to extract the part of the history ancestral to the observed data.

The model exposes a small set of lineage primitives:

  • birth_from() replaces one active lineage with a continuing lineage and a new child lineage;

  • continue_as() replaces a lineage with one child, optionally in a new state (migration or state change);

  • finalize() ends an active lineage without sampling it (death);

  • sample() ends and records a lineage, or, with removal=False, records a sample while leaving a new active descendant; and

  • hybridize() replaces two active parents with one hybrid child that has two incoming edges.

Parameters:
  • init_state – State of the initial active lineage.

  • events – Stochastic events governing continuous-time state transitions.

  • schedule – Iterable of (time, action) pairs. An action receives and mutates the model when its time is reached. Actions scheduled for the same time are shuffled before execution.

Examples

The following deterministic schedule calls every kind of lineage primitive. Lineage ids are allocated in creation order, which makes the network changes easy to follow. The hybridization creates a reticulation in the full history; only ids 6 and 9 are sampled.

>>> from phyloom.simulator.bdsh import BDSHModel
>>> schedule = [
...     (1, lambda m: m.birth_from(1)),
...     (2, lambda m: m.birth_from(2)),
...     (3, lambda m: m.continue_as(3, "B")),
...     (4, lambda m: m.hybridize((4, 5), hybrid_state="H")),
...     (5, lambda m: m.rho_sample(1.0, "B", removal=True)),
...     (6, lambda m: m.sample(7, removal=False)),
...     (7, lambda m: m.finalize(8)),
... ]
>>> model = BDSHModel(init_state="A", schedule=schedule)
>>> while model.step():
...     pass
>>> list(model.get_current_lineages()), sorted(model.get_sampled_lineages())
([], [6, 9])

The full history contains every lineage, including the unsampled lineages and the unobserved paths between the two sampled leaves:

>>> model.history().pretty_print()
1|A [1.0]
|-- 2|A [1]
|   |-- 4|A [2]
|   |   `-- 7|H [2]
|   |       |-- 8|H [1]
|   |       `-- 9|H [0]
|   `-- 5|A [2]
|       `-- ref 7|H [2]
`-- 3|A [2]
    `-- 6|B [2]

Passing the sampled lineages as a skeleton compresses away unobserved paths and returns the sampled network:

>>> sampled = model.history(model.get_sampled_lineages())
>>> sampled.pretty_print()
1|A [1.0]
|-- 9|H [5]
`-- 6|B [4]
get_root() → NodeID[source]

Return the initial lineage as the root of the history.

time_of(lineage: NodeID) → float[source]

Return the time at which lineage was finalized.

An active lineage is treated as ending at current_time, which allows a history to be materialized before all lineages have been finalized.

property origin: float

Return 0.0, the start of forward simulation time.

finalize(lineage: NodeID)[source]

End an active lineage without sampling it.

This is the primitive used for death or any other unobserved terminal outcome. The lineage remains in the model history but is removed from the active lineage sets.

Parameters:

lineage – Active lineage to end.

sample(lineage: NodeID, *, removal: bool)[source]

Record an active lineage as a sample.

Parameters:
  • lineage – Active lineage to record.

  • removal – Whether to end the sampled lineage. If False, the lineage first branches; one descendant is recorded as the sample at the current time, and the other remains active.

rho_sample(p: float, state: str | None = None, *, removal: bool)[source]

Independently sample eligible active lineages.

Parameters:
  • p – Sampling probability for each eligible lineage.

  • state – Optional state restricting eligible lineages.

  • removal – Whether to end sampled lineages. If False, each sampled lineage first branches; one descendant is recorded as the sample at the current time, and the other remains active.

continue_as(lineage: NodeID, new_state: str | None = None) → NodeID[source]

Replace an active lineage with one continuing child.

Parameters:
  • lineage – Active lineage to continue.

  • new_state – Optional state of the child lineage. If omitted, the child inherits the parent’s state.

Returns:

The new active child lineage id.

birth_from(parent: NodeID, child_states: tuple[str | None, str | None] = (None, None)) → tuple[NodeID, NodeID][source]

Replace one active parent lineage with two active descendant lineages.

Parameters:
  • parent – Active lineage on which the birth occurs.

  • child_states – Optional pair of states assigned to the descendant lineages. A None entry inherits the parent’s state.

Returns:

The pair of new active child lineage ids, in the same order as child_states.

hybridize(parents: tuple[NodeID, NodeID], hybrid_state: str | None = None) → NodeID[source]

Replace two active parent lineages with one hybrid child.

Parameters:
  • parents – Pair of active parent lineage ids.

  • hybrid_state – Optional state of the hybrid child. If omitted, the parents must share the same state, which the child inherits.

Returns:

The new active hybrid lineage id.

get_sampled_lineages(state: str | None = None) → SetView[NodeID][source]

Read-only view of sampled lineage ids, optionally restricted to one state.

count_sampled_lineages(state: str | None = None) → int[source]

Count sampled lineages, optionally restricted to one state.

class phyloom.simulator.bdsh.Birth(parent_state: str | None = None, child_states: tuple[str | None, str | None] = (None, None))[source]

Bases: LineageEventRule[BDSHModel]

Birth event that replaces one active lineage with two descendants.

Parameters:
  • parent_state – Optional state restricting eligible parent lineages.

  • child_states – Optional pair of states assigned to the descendant lineages. A None entry inherits the parent’s state.

apply_to_lineage(model: BDSHModel, lineage: NodeID)[source]

Replace the selected lineage with two descendants.

class phyloom.simulator.bdsh.Death(state: str | None = None)[source]

Bases: LineageEventRule[BDSHModel]

Death event that finalizes one active lineage without sampling it.

Parameters:

state – Optional state restricting eligible lineages.

apply_to_lineage(model: BDSHModel, lineage: NodeID)[source]

Finalize the selected lineage without sampling it.

class phyloom.simulator.bdsh.Migration(source_state: str, target_state: str)[source]

Bases: LineageEventRule[BDSHModel]

State-change event that replaces one active lineage with a continuing child.

Parameters:
  • source_state – State restricting eligible parent lineages.

  • target_state – State assigned to the child lineage.

apply_to_lineage(model: BDSHModel, lineage: NodeID)[source]

Replace the selected lineage with a continuing child in the target state.

class phyloom.simulator.bdsh.Sampling(state: str | None = None, *, removal: bool)[source]

Bases: LineageEventRule[BDSHModel]

Sampling event that records one eligible active lineage.

Parameters:
  • state – Optional state restricting eligible lineages.

  • removal – Whether to end the sampled lineage. If False, the lineage first branches; one descendant is recorded as the sample at the current time, and the other remains active.

apply_to_lineage(model: BDSHModel, lineage: NodeID)[source]

Record the selected lineage as a sample.

πŸ”— Coalescent

Coalescent simulation framework.

class phyloom.simulator.coalescent.Coalesce(current_states: tuple[str, str] | None = None, ancestral_state: str | None = None)[source]

Bases: LineagePairEventRule[CoalescentModel]

Coalescence event that replaces two active lineages with one ancestral parent.

Parameters:
  • current_states – Optional pair of states restricting the child pair.

  • ancestral_state – Optional state assigned to the ancestral parent. If omitted, the child lineages must share the same state, which the parent inherits.

apply_to_lineages(model: CoalescentModel, lineages: tuple[NodeID, NodeID])[source]

Replace the selected lineage pair with one ancestral parent.

class phyloom.simulator.coalescent.CoalescentModel(init_population: Mapping[str, int], events: Iterable[Event[Self]] = (), schedule: Iterable[tuple[float, Callable[[Self], None]]] = ())[source]

Bases: NetModel

Backwards-time genealogy model.

This model evolves a rooted network backwards in time from an initial population of lineages. Simulation advances backwards from the observed lineages toward their ancestors. current_time therefore increases into the past, while lineage times are stored as its negative so that older ancestors have smaller coordinates. The active set represents lineages still being traced backwards.

The model’s primitives are:

  • spawn(), which creates a new active lineage at the current time;

  • retrace(), which replaces one active lineage by an ancestral parent in another state; and

  • coalesce(), which replaces two active lineages by one parent and connects both children to it.

Coalescent histories do not maintain a sampled-lineage set. A complete history can be materialized only after the active lineages have been reduced to one root.

Parameters:
  • init_population – Positive number of initial active lineages for each state.

  • events – Stochastic events governing continuous-time state transitions.

  • schedule – Iterable of (time, action) pairs. An action receives and mutates the model when its time is reached. Actions scheduled for the same time are shuffled before execution.

Examples

This deterministic schedule starts with two A lineages, spawns a third, retraces one through a B ancestor, then coalesces the lineages into an A/B ancestor.

>>> from phyloom.simulator.coalescent import CoalescentModel
>>> schedule = [
...     (1, lambda m: m.spawn("A")),
...     (2, lambda m: m.retrace(1, "B")),
...     (3, lambda m: m.coalesce((2, 3), state="A")),
...     (4, lambda m: m.coalesce((4, 5), state="A/B")),
... ]
>>> model = CoalescentModel(init_population={"A": 2}, schedule=schedule)
>>> while model.step(max_time=5):
...     pass
>>> model.history().pretty_print()
6|A/B [1]
|-- 4|B [2]
|   `-- 1|A [2.0]
`-- 5|A [1]
    |-- 2|A [3.0]
    `-- 3|A [2]
get_root() → NodeID[source]

Return the sole remaining active lineage as the root.

The genealogy must have fully coalesced before this method is called.

time_of(lineage: NodeID) → float[source]

Return the backwards-time coordinate assigned to a lineage.

property origin: float

Return the current simulation origin in backwards-time coordinates.

spawn(state: str) → NodeID[source]

Create a new active lineage in the given state at the current time.

Parameters:

state – State of the new lineage.

Returns:

The new active lineage id.

coalesce(lineages: tuple[NodeID, NodeID], state: str | None = None) → NodeID[source]

Replace two active lineages with one ancestral parent.

Parameters:
  • lineages – Pair of active child lineage ids.

  • state – Optional state assigned to the new parent. If omitted, both children must share a state, which the parent inherits.

Returns:

The new active parent lineage id.

retrace(lineage: NodeID, state: str) → NodeID[source]

Replace one active lineage with an ancestral parent in state.

Parameters:
  • lineage – Active lineage to retrace.

  • state – State assigned to the new ancestral parent.

Returns:

The new active parent lineage id.

class phyloom.simulator.coalescent.Retrace(ancestral_state: str, current_state: str | None = None)[source]

Bases: LineageEventRule[CoalescentModel]

Retrace event that replaces one active lineage with an ancestral parent.

Parameters:
  • ancestral_state – State assigned to the new parent.

  • current_state – Optional state restricting eligible lineages.

apply_to_lineage(model: CoalescentModel, lineage: NodeID)[source]

Replace the selected lineage with an ancestral parent.

🦠 Epidemic

Compartmental epidemic simulation framework.

class phyloom.simulator.epidemic.EpidemicModel(init_state: str, init_pools: Mapping[str, int], events: Iterable[Event[Self]] = (), schedule: Iterable[tuple[float, Callable[[Self], None]]] = ())[source]

Bases: NetModel

Compartmental epidemic model.

The model evolves a rooted network forward in time from one initial infectious lineage. Epidemic dynamics are represented by two complementary components: pools, which stores counts of individuals in named compartments such as S, I, and R, and the transmission network, which stores active lineages and their discrete state labels. The model also records sampled lineages: finalized lineages designated as observations that can be used to extract the portion of the history ancestral to the observed data. Although the pool and network states are maintained independently, events may update both. For example, an infection removes an individual from a recipient pool and replaces one active source lineage with two descendants, whereas a recovery terminates a lineage and returns an individual to a destination pool.

Its lineage and population primitives are:

  • infection() consumes one individual from a recipient pool and replaces an active source lineage with two descendants;

  • recovery() ends a lineage, returns one individual to a destination pool, and optionally records that lineage as sampled;

  • migration() replaces a lineage with one child in the same or a new state (migration or another state change); and

  • flow() moves one individual between pools without changing the lineage network.

Parameters:
  • init_state – State of the initial infectious lineage.

  • init_pools – Initial non-negative counts for each population pool.

  • events – Stochastic events governing continuous-time state transitions.

  • schedule – Iterable of (time, action) pairs. An action receives and mutates the model when its time is reached. Actions scheduled for the same time are shuffled before execution.

Examples

This deterministic SIR-like history exposes infection, recovery with and without sampling, migration, and pool flow. Lineage ids are allocated in creation order, which makes the network changes easy to follow. It starts with one infectious lineage and three susceptible individuals, and ends with four recovered individuals, two of which are sampled.

>>> from phyloom.simulator.epidemic import EpidemicModel
>>> schedule = [
...     (1, lambda m: m.infection(1, "S")),
...     (2, lambda m: m.infection(3, "S")),
...     (3, lambda m: m.recovery(2, "R", sample=True)),
...     (4, lambda m: m.migration(4, "I")),
...     (5, lambda m: m.flow("S", "R")),
...     (6, lambda m: m.recovery(5, "R")),
...     (7, lambda m: m.recovery(6, "R", sample=True)),
... ]
>>> model = EpidemicModel(init_state="I", init_pools={"S": 3}, schedule=schedule)
>>> while model.step():
...     pass
>>> dict(model.pools), list(model.get_current_lineages())
({'S': 0, 'R': 4}, [])
>>> sorted(model.get_sampled_lineages())
[2, 6]

The full history contains every transmission lineage, including the unsampled lineages and the unobserved path between the two sampled leaves:

>>> model.history().pretty_print()
1|I [1.0]
|-- 2|I [2]
`-- 3|I [1]
    |-- 4|I [2]
    |   `-- 6|I [3]
    `-- 5|I [4]

Passing the sampled lineages as a skeleton compresses away unobserved paths and returns the sampled network:

>>> sampled = model.history(model.get_sampled_lineages())
>>> sampled.pretty_print()
1|I [1.0]
|-- 2|I [2]
`-- 6|I [6]
get_root() → NodeID[source]

Return the initial lineage as the root of the history.

time_of(lineage: NodeID) → float[source]

Return the time at which lineage was finalized.

An active lineage is treated as ending at current_time, which allows a history to be materialized before all lineages recover.

property origin: float

Return 0.0, the start of forward simulation time.

property pools: Mapping[str, int]

Read-only mapping of compartment names to current counts.

flow(source: str, destination: str)[source]

Move one individual from source to destination.

Pool flow changes compartment counts only; it does not create, finalize, or sample a lineage.

Parameters:
  • source – Pool to decrement.

  • destination – Pool to increment.

recovery(lineage: NodeID, destination_pool: str, *, sample: bool = False)[source]

End an active lineage, return one individual to a destination pool, and optionally record that lineage as sampled.

Parameters:
  • lineage – Active lineage that recovers.

  • destination_pool – Pool receiving the recovered individual.

  • sample – Whether to record the finalized lineage as a sample.

migration(lineage: NodeID, new_state: str | None = None) → NodeID[source]

Replace an active lineage with one continuing child.

Parameters:
  • lineage – Active lineage to continue.

  • new_state – Optional state assigned to the child. If omitted, the child inherits its parent’s state.

Returns:

The new active child lineage id.

infection(parent: NodeID, recipient_pool: str, child_states: tuple[str | None, str | None] = (None, None)) → tuple[NodeID, NodeID][source]

Replace one active lineage with two descendants and decrement a recipient pool.

Parameters:
  • parent – Active lineage on which the infection occurs.

  • recipient_pool – Pool from which the infected individual is removed.

  • child_states – Optional pair of states assigned to the descendant lineages. A None entry inherits the parent’s state.

Returns:

The pair of new active child lineage ids, in the same order as child_states.

get_sampled_lineages(state: str | None = None) → SetView[NodeID][source]

Read-only view of sampled lineage ids, optionally restricted to one state.

count_sampled_lineages(state: str | None = None) → int[source]

Count sampled lineages, optionally restricted to one state.

class phyloom.simulator.epidemic.Flow(source_pool: str, destination_pool: str)[source]

Pool-flow event that moves one individual from a source pool to a destination pool.

There is one opportunity for every individual in source_pool. Flow does not affect lineages, and only modifies the counts of individuals in the source and destination pools.

Parameters:
  • source_pool – Pool to decrement.

  • destination_pool – Pool to increment.

opportunities(model: EpidemicModel)[source]

Count the number of individuals currently in source_pool.

apply(model: EpidemicModel)[source]

Move one individual from source_pool to destination_pool.

class phyloom.simulator.epidemic.Infection(recipient_pool: str, source_state: str | None = None, child_states: tuple[str | None, str | None] = (None, None))[source]

Infection event that replaces one active lineage with two descendants and decrements a pool.

The number of infection opportunities is the product of the number of eligible source lineages and the number of individuals in recipient_pool. When an opportunity is selected, one eligible source lineage is chosen uniformly, one individual is removed from the recipient pool, and the lineage is replaced by two descendants.

Parameters:
  • recipient_pool – Pool from which the infected individual is removed.

  • source_state – Optional state used to restrict eligible source lineages.

  • child_states – Optional pair of states assigned to the descendant lineages. A None entry inherits the parent’s state.

opportunities(model: EpidemicModel)[source]

Count the number of infection opportunities in the model.

apply(model: EpidemicModel)[source]

Select one infection opportunity and apply it to the model.

class phyloom.simulator.epidemic.Migration(source_state: str, target_state: str)[source]

Bases: LineageEventRule[EpidemicModel]

State-change event that replaces one active lineage with a continuing child.

Parameters:
  • source_state – State restricting eligible parent lineages.

  • target_state – State assigned to the child lineage.

apply_to_lineage(model: EpidemicModel, lineage: NodeID)[source]

Replace the selected lineage with a continuing child in the target state.

class phyloom.simulator.epidemic.Recovery(destination_pool: str, source_state: str | None = None, *, sample: bool = False)[source]

Bases: LineageEventRule[EpidemicModel]

Recovery event that finalizes a lineage and increments a pool.

Parameters:
  • destination_pool – Pool receiving the recovered individual.

  • source_state – Optional state restricting eligible lineages.

  • sample – Whether to record the finalized lineage as a sample.

apply_to_lineage(model: EpidemicModel, lineage: NodeID)[source]

Finalize the selected lineage and increment the destination pool.

πŸ› οΈ Utils

Simulation utilities.

phyloom.simulator.utils.run_simulations(n_samples: int, sim_func: Callable[[SampleID, Seed], Metadata], *, seed: Seed | None = None, n_jobs: int = -1) → pd.DataFrame[source]

Run independent simulations in parallel and collect their metadata.

Parameters:
  • n_samples – Number of simulations to run. Sample IDs are assigned sequentially from 1 to n_samples.

  • sim_func – Function that runs one simulation for a sample ID and random seed, returning that sample’s metadata.

  • seed – Seed used to derive the per-sample seeds. If None, use a non-deterministic seed source.

  • n_jobs – Number of parallel workers passed to joblib.Parallel.

Returns:

A data frame containing one row of metadata per sample, sorted by sample_id.