Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
22cf6be
Test that every state-space type factorizes in block triangular form
Sendrowski Oct 25, 2026
9423546
Compute second moments of spectra in one forward pass over all bins
Sendrowski Oct 25, 2026
63e8f32
Flatten second moments of the SFS onto the lineage-counting space und…
Sendrowski Oct 25, 2026
82bbb31
Reuse one propagator per step on equispaced time grids
Sendrowski Oct 26, 2026
75b57ae
Enumerate states once and assemble each epoch's rate matrix from a fi…
Sendrowski Oct 26, 2026
ce3e346
Choose dense or action exponentials with one cost model across all mo…
Sendrowski Oct 26, 2026
79fa5e5
Use the cost model for tree-height grids and uniformization for mutat…
Sendrowski Oct 26, 2026
9cd4ebf
Replace expm_action_min_dim with Settings.expm_method and pass explic…
Sendrowski Oct 26, 2026
1042d23
Trim per-point grid planning and generator-basis construction overhead
Sendrowski Oct 27, 2026
b4caf61
Fix test isolation, coverage gaps, dependency floors and stale docstr…
Sendrowski Oct 27, 2026
fa7474a
Check both margins of the 2D cosine joint at their quantiles
Sendrowski Oct 27, 2026
186fa49
Reject NaN quantile levels and times, and validate sample counts and …
Sendrowski Oct 27, 2026
f0f07d3
Restore plot_pdf as a deprecated alias
Sendrowski Oct 27, 2026
eeddc1d
Add smoke tests replaying the manuscript code
Sendrowski Oct 27, 2026
12bcbe2
Document that a Coalescent is not thread-safe
Sendrowski Oct 28, 2026
f7ac45a
Stop the COS window warning from recommending de Hoog throughout
Sendrowski Oct 28, 2026
f719cd8
Hold a discretized trajectory's end value from its end time on
Sendrowski Oct 28, 2026
2e6459e
Name the demes migration restriction in to_demes
Sendrowski Oct 28, 2026
7e0c030
Reject unscaled multiple-merger time and invalid replicate counts in …
Sendrowski Oct 28, 2026
e4f421d
Keep the empirical deme and locus covariance a matrix for one deme or…
Sendrowski Oct 28, 2026
a032966
Compare lineage and locus configurations unequal to other types
Sendrowski Oct 28, 2026
155a186
Add moments of every order to RewardDistribution
Sendrowski Oct 28, 2026
878a476
Rerun the runtime benchmarks with migration and more lineages
Sendrowski Oct 29, 2026
7151008
Return the exact bound for log-scale estimates clipped to it
Sendrowski Nov 1, 2026
99c19e3
Release 2.3.0
Sendrowski Oct 29, 2026
62fcc8d
Release 2.3.0
Sendrowski Nov 1, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

import os
import sys

sys.path.append('..')
sys.path.insert(0, os.path.abspath('..'))

from phasegen import __version__

Expand Down
Binary file modified docs/images/execution_times.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/sampling_times.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified docs/images/state_space_sizes.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 11 additions & 1 deletion docs/modules/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@
Changelog
=========

[2.3.0] - 2026-10-29
^^^^^^^^^^^^^^^^^^^^
- Choose between dense matrix exponentials and their action with one cost model, set by :attr:`Settings.expm_method <phasegen.settings.Settings.expm_method>`, which replaces ``Settings.expm_action_min_dim``.
- Compute mutational configurations (:meth:`UnfoldedSFSDistribution.get_mutation_config() <phasegen.distributions.UnfoldedSFSDistribution.get_mutation_config>`) by adaptive uniformization, substantially faster on multi-epoch demographies.
- Speed up the second moments of the spectra and multi-epoch models.
- Add moments of any order with :meth:`RewardDistribution.moment() <phasegen.distributions.RewardDistribution.moment>`.
- Hold the end value of a :class:`~phasegen.demography.DiscretizedRateChange` from its end time on, which changes discretized trajectories with a finite end time.
- Validate inputs more thoroughly and fix several smaller defects.
- :class:`~phasegen.inference.Inference` objects saved with version 2.2.0 cannot be loaded.

[2.2.0] - 2026-10-24
^^^^^^^^^^^^^^^^^^^^
- Differentiate inference losses exactly, at a cost independent of the number of parameters (:attr:`Inference.gradient <phasegen.inference.Inference.gradient>`), and expose the derivatives of moments of any order (:meth:`Coalescent.gradient() <phasegen.distributions.Coalescent.gradient>`, :class:`~phasegen.gradient.Gradient`).
Expand Down Expand Up @@ -50,7 +60,7 @@ Changelog
- Add the two-locus site-frequency spectrum under recombination via :attr:`Coalescent.sfs2 <phasegen.distributions.Coalescent.sfs2>`, with support for multiple-merger coalescents.
- Add summary statistics: Hudson's :attr:`Coalescent.fst <phasegen.distributions.Coalescent.fst>`, Patterson's f-statistics (:meth:`Coalescent.f2() <phasegen.distributions.Coalescent.f2>`, :meth:`Coalescent.f3() <phasegen.distributions.Coalescent.f3>`, :meth:`Coalescent.f4() <phasegen.distributions.Coalescent.f4>`), Tajima's :attr:`UnfoldedSFSDistribution.tajimas_d <phasegen.distributions.UnfoldedSFSDistribution.tajimas_d>` with the :attr:`UnfoldedSFSDistribution.theta_pi <phasegen.distributions.UnfoldedSFSDistribution.theta_pi>` and :attr:`UnfoldedSFSDistribution.theta_w <phasegen.distributions.UnfoldedSFSDistribution.theta_w>` estimators, and cross-locus linkage via the correlation of coalescence times.
- Accelerate state-space construction with `numba <https://numba.pydata.org/>`__, which is now a required dependency.
- Compute moments of large state spaces from the sparse action of the matrix exponential (threaded over epochs), controlled by :attr:`Settings.expm_action_min_dim <phasegen.settings.Settings.expm_action_min_dim>`.
- Compute moments of large state spaces from the sparse action of the matrix exponential (threaded over epochs), controlled by ``Settings.expm_action_min_dim``.
- Validate the new statistics against msprime/tskit ground truth, including within the scenario-comparison workflow (Kingman and multiple-merger models, and beyond the two-lineage case).
- Use the ``spawn`` start method for the worker pool on macOS to avoid fork/numba deadlocks.
- Documentation: add a dedicated *Spectra & summary statistics* reference page and drop the exponentiation-backend page.
Expand Down
6 changes: 3 additions & 3 deletions docs/modules/distributions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ Phase-type distributions. The :class:`~phasegen.distributions.Coalescent` class
.. autoclass:: phasegen.distributions.JointSFSDistribution

.. autoclass:: phasegen.distributions.TwoLocusSFSDistribution
:exclude-members: cdf, pdf, quantile, plot_cdf, bin, loci, demes
:exclude-members: cdf, pdf, quantile, plot_cdf, plot_pdf, bin, loci, demes

.. autoclass:: phasegen.distributions.DemographyGradient

Expand All @@ -75,10 +75,10 @@ Phase-type distributions. The :class:`~phasegen.distributions.Coalescent` class
.. autoclass:: phasegen.distributions.RewardDistribution

.. autoclass:: phasegen.distributions.ConditionalRewardDistribution
:exclude-members: __init__, plot_cdf
:exclude-members: __init__, plot_cdf, plot_pdf

.. autoclass:: phasegen.distributions.JointRewardDistribution
:exclude-members: quantile, plot_cdf
:exclude-members: quantile, plot_cdf, plot_pdf

.. autoclass:: phasegen.distributions.DistributionFunction
:members:
Expand Down
4 changes: 2 additions & 2 deletions docs/reference/performance.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Constructing it (enumerating the states and assembling the rate matrix) is accel

Exact computation
-----------------
The runtime of exact moments is governed by the size of the state space, which enters through linear solves with the transient block of the last epoch, matrix exponentials over finite epochs, and the order of the moment. The evaluation strategies and the settings that select them are described in :meth:`PhaseTypeDistribution.moment() <phasegen.distributions.PhaseTypeDistribution.moment>`. Below we can see the total runtime in seconds for computing the mean tree height, the mean SFS, and the mean two-locus SFS under a 1-epoch standard coalescent over a range of different numbers of lineages and loci.
The runtime of exact moments is governed by the size of the state space, which enters through linear solves with the transient block of the last epoch, matrix exponentials over finite epochs, and the order of the moment. The evaluation strategies and the settings that select them are described in :meth:`PhaseTypeDistribution.moment() <phasegen.distributions.PhaseTypeDistribution.moment>`. Below we can see the total runtime in seconds for computing the mean tree height, the mean SFS, and the mean two-locus SFS under a 1-epoch standard coalescent with migration over a range of numbers of lineages, demes and loci.

.. image:: ../images/execution_times.png
:alt: Execution times
Expand All @@ -25,7 +25,7 @@ The runtime of exact moments is governed by the size of the state space, which e

Empirical estimation
--------------------
Where the exact computation becomes too costly, the statistics can instead be estimated from ``phasegen``'s own vectorised sampler (:meth:`Coalescent.to_empirical() <phasegen.distributions.Coalescent.to_empirical>`). Its cost grows with the number of samples and the number of jumps per trajectory, while the state space is still constructed as for the exact computation (see :meth:`PhaseTypeDistribution.sample() <phasegen.distributions.PhaseTypeDistribution.sample>`). The figure below shows the runtime for drawing 100,000 samples, on the same colour scale as above. Sampling is considerably faster even for the largest case, which is the slowest to compute exactly in the figure above.
Where the exact computation becomes too costly, the statistics can instead be estimated from ``phasegen``'s own vectorised sampler (:meth:`Coalescent.to_empirical() <phasegen.distributions.Coalescent.to_empirical>`). Its cost grows with the number of samples and the number of jumps per trajectory, while the state space is still constructed as for the exact computation (see :meth:`PhaseTypeDistribution.sample() <phasegen.distributions.PhaseTypeDistribution.sample>`). The figure below shows the runtime for drawing 100,000 samples, on the same colour scale as above. Its runtime grows more slowly than that of the exact computation as the scenarios become more complex.

.. image:: ../images/sampling_times.png
:alt: Sampling times
Expand Down
2 changes: 1 addition & 1 deletion phasegen/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
__contact__ = "sendrowski.janek@gmail.com"
__date__ = "2023-04-09"

__version__ = '2.2.0'
__version__ = '2.3.0'

import logging
import os
Expand Down
119 changes: 95 additions & 24 deletions phasegen/demography.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,14 +452,28 @@ def to_demes(self, max_epochs: int = 1000) -> 'demes.Graph':
Convert to a :class:`demes.Graph`, by way of :meth:`Demography.to_msprime()
<phasegen.demography.Demography.to_msprime>`. Sizes and times are taken over unchanged, so
:meth:`Demography.from_demes() <phasegen.demography.Demography.from_demes>` with ``ploidy=1`` recovers the
demography.
demography. A :class:`demes.Graph` takes migration rates as proportions of at most 1, so a demography with a
larger migration rate, or with a split or pulse, which :class:`msprime.Demography` expresses as a window of
fast migration, cannot be converted.

:param max_epochs: Maximum number of epoch changes to use, as for :meth:`Demography.to_msprime()
<phasegen.demography.Demography.to_msprime>`.
:return: The :class:`demes.Graph`.
:raises ImportError: If msprime is not installed.
:raises ValueError: If a migration rate exceeds 1, or the demography has a split or pulse.
"""
return self.to_msprime(max_epochs=max_epochs).to_demes()
demography = self.to_msprime(max_epochs=max_epochs)

import msprime as ms

rate = max([float(np.max(demography.migration_matrix, initial=0))] +
[e.rate for e in demography.events if isinstance(e, ms.MigrationRateChange)])

if rate > 1:
raise ValueError(f"demes takes migration rates of at most 1, and the demography reaches {rate:g}, from a "
f"migration rate or from the migration window of a split or pulse.")

return demography.to_demes()

@property
def _msprime_names(self) -> Dict[str, str]:
Expand Down Expand Up @@ -566,6 +580,11 @@ def _build_epoch(self, prev: 'Epoch | None', i: int) -> 'Epoch':
# drain rate, so that the epoch does not depend on the order of events sharing a start time
splits = [e for e in self.events if isinstance(e, PopulationSplit)]

# a discretized trajectory holds its end value from its end time on, unless an event sets that rate there
for e in self.events:
if isinstance(e, DiscretizedDemographicEvent):
e._hold(epoch)

# a rate set by two events in one epoch keeps the value of the later one in the list, which is sorted by
# start time, so the precedence depends on how the changes are grouped into events
setters = {}
Expand Down Expand Up @@ -1213,8 +1232,11 @@ def __init__(
rates: Dict[float, Dict[Any, float]]
times, rates = self._flatten(pop_sizes | migration_rates)

# the negated comparisons also reject NaN
if np.any(~(np.array(times, dtype=float) >= 0)):
times_arr = np.array(times, dtype=float)
if np.any(np.isnan(times_arr)):
raise ValueError('Times must not be NaN.')

if np.any(times_arr < 0):
raise ValueError('All times must not be negative.')

migration = np.array([rates[k][t] for k in rates for t in migration_rates if t in rates[k]], dtype=float)
Expand Down Expand Up @@ -1653,7 +1675,8 @@ def __init__(
"""
Initialize the discretized change of a population size or migration rate.

:param trajectory: Trajectory function taking the time as argument and returning the rate.
:param trajectory: Trajectory function taking the time as argument and returning the rate, a number or an
array holding one number.
:param start_time: Start time of the event.
:param end_time: End time of the event.
:param pop: Population name or None if no population size changes.
Expand Down Expand Up @@ -1747,41 +1770,79 @@ def _broadcast(self, epoch: Epoch) -> None:

epoch.end_time = min(epoch.end_time, self.start_time + n_steps * self.step_size, self.end_time)

def _rate(self, t: float) -> float:
"""
The value of the trajectory at a time, a number or an array holding one number.

:param t: Time.
:return: The value as a float.
:raises ValueError: If the trajectory does not return a single number.
"""
value = self.trajectory(t)

try:
arr = np.asarray(value, dtype=float)
except (TypeError, ValueError):
arr = None

if arr is None or arr.size != 1:
name = (f'population size trajectory of {self.pop}' if self.pop is not None
else f'migration rate trajectory from {self.source_pop} to {self.dest_pop}')
raise ValueError(f'The {name} must return a single number, got {value!r} at time {t:g}.')

return float(arr.reshape(()))

def _apply(self, epoch: Epoch) -> set:
"""
Apply the demographic event to the given epoch if applicable.
Apply the demographic event to the given epoch if applicable. An epoch contained in the event, up to and
including a trailing partial interval ending at the end time, takes the mean of the trajectory at its ends.

:param epoch: Epoch.
:return: The keys of the rates set.
"""
# if epoch is contained in the event, up to and including a trailing partial interval ending at self.end_time
if self.start_time <= epoch.start_time and epoch.end_time <= self.end_time:
return self._set(epoch, (self._rate(epoch.start_time) + self._rate(epoch.end_time)) / 2)

rate_start = self.trajectory(epoch.start_time)
rate_end = self.trajectory(epoch.end_time)
rate = (rate_start + rate_end) / 2
return set()

if self.pop is None:
if not 0 <= rate < np.inf:
raise ModelError(f'The migration rate trajectory from {self.source_pop} to {self.dest_pop} gives '
f'{rate} on [{epoch.start_time:g}, {epoch.end_time:g}), which is not finite and '
f'non-negative.')
def _hold(self, epoch: Epoch) -> None:
"""
Set the trajectory's value at the end time on the epoch starting there, which later epochs inherit. It runs
before the events are applied, so any event setting the rate at the end time takes precedence.

epoch.migration_rates[(self.source_pop, self.dest_pop)] = rate
:param epoch: Epoch.
"""
if epoch.start_time == self.end_time:
self._set(epoch, self._rate(self.end_time))

return {(self.source_pop, self.dest_pop)}
def _set(self, epoch: Epoch, rate: float) -> set:
"""
Set the population size or migration rate on an epoch.

# a decaying trajectory may underflow to zero far out, which a simulation accepts and the exact
# computation rejects where it reaches that epoch
:param epoch: Epoch.
:param rate: The size or rate.
:return: The keys of the rates set.
:raises ModelError: If the rate is negative or not finite.
"""
if self.pop is None:
if not 0 <= rate < np.inf:
raise ModelError(f'The population size trajectory of {self.pop} gives {rate} on '
f'[{epoch.start_time:g}, {epoch.end_time:g}), which is negative or not finite.')
raise ModelError(f'The migration rate trajectory from {self.source_pop} to {self.dest_pop} gives '
f'{rate} on [{epoch.start_time:g}, {epoch.end_time:g}), which is not finite and '
f'non-negative.')

epoch.pop_sizes[self.pop] = rate
epoch.migration_rates[(self.source_pop, self.dest_pop)] = rate

return {self.pop}
return {(self.source_pop, self.dest_pop)}

return set()
# a decaying trajectory may underflow to zero far out, which a simulation accepts and the exact
# computation rejects where it reaches that epoch
if not 0 <= rate < np.inf:
raise ModelError(f'The population size trajectory of {self.pop} gives {rate} on '
f'[{epoch.start_time:g}, {epoch.end_time:g}), which is negative or not finite.')

epoch.pop_sizes[self.pop] = rate

return {self.pop}


class DiscretizedRateChanges(DiscretizedDemographicEvent):
Expand Down Expand Up @@ -1882,6 +1943,16 @@ def _apply(self, epoch: Epoch) -> set:
"""
return set().union(*(e._apply(epoch) for e in self.events.values()))

def _hold(self, epoch: Epoch) -> None:
"""
Set the value of each trajectory at its end time on the epoch starting there, which later epochs inherit and
any event setting the rate there overrides.

:param epoch: Epoch.
"""
for e in self.events.values():
e._hold(epoch)


class _ExponentialTrajectory:
r"""
Expand Down
21 changes: 21 additions & 0 deletions phasegen/distributions/_common.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Shared helpers for the distributions package."""
import copy
import functools
import numbers

import numpy as np
from typing import Callable, Mapping, Sequence, Tuple
Expand Down Expand Up @@ -117,6 +118,26 @@ def _validate_start_time(start_time: float) -> None:
raise ValueError(f"Start time must be greater than or equal to 0, got {start_time}.")


def _n_samples(n_samples: 'int | float', minimum: int = 0) -> int:
"""
Validate a number of samples.

:param n_samples: The number of samples, of any numeric type with an integral value of at least ``minimum``.
:param minimum: The smallest number of samples allowed.
:return: The number of samples as an integer.
:raises ValueError: if ``n_samples`` is not an integer of at least ``minimum``.
"""
if isinstance(n_samples, np.ndarray) and n_samples.ndim == 0:
n_samples = n_samples.item()

if (isinstance(n_samples, bool) or not isinstance(n_samples, numbers.Real)
or not float(n_samples).is_integer() or n_samples < minimum):
kind = 'a non-negative integer' if minimum == 0 else f'an integer of at least {minimum}'
raise ValueError(f"The number of samples must be {kind}, got {n_samples!r}.")

return int(n_samples)


def _frequency_class(i: 'int | float', n: int) -> int:
"""
Validate a frequency class of a spectrum array.
Expand Down
Loading
Loading