diff --git a/docs/conf.py b/docs/conf.py index 2a1dd53d..6c96db44 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -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__ diff --git a/docs/images/execution_times.png b/docs/images/execution_times.png index 47b7d232..9f93f28e 100644 Binary files a/docs/images/execution_times.png and b/docs/images/execution_times.png differ diff --git a/docs/images/sampling_times.png b/docs/images/sampling_times.png index b33824af..b7a9bc28 100644 Binary files a/docs/images/sampling_times.png and b/docs/images/sampling_times.png differ diff --git a/docs/images/state_space_sizes.png b/docs/images/state_space_sizes.png index 72bb51b3..36b4d447 100644 Binary files a/docs/images/state_space_sizes.png and b/docs/images/state_space_sizes.png differ diff --git a/docs/modules/changelog.rst b/docs/modules/changelog.rst index 48f7defc..ee906a06 100644 --- a/docs/modules/changelog.rst +++ b/docs/modules/changelog.rst @@ -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 `, which replaces ``Settings.expm_action_min_dim``. +- Compute mutational configurations (:meth:`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() `. +- 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 `), and expose the derivatives of moments of any order (:meth:`Coalescent.gradient() `, :class:`~phasegen.gradient.Gradient`). @@ -50,7 +60,7 @@ Changelog - Add the two-locus site-frequency spectrum under recombination via :attr:`Coalescent.sfs2 `, with support for multiple-merger coalescents. - Add summary statistics: Hudson's :attr:`Coalescent.fst `, Patterson's f-statistics (:meth:`Coalescent.f2() `, :meth:`Coalescent.f3() `, :meth:`Coalescent.f4() `), Tajima's :attr:`UnfoldedSFSDistribution.tajimas_d ` with the :attr:`UnfoldedSFSDistribution.theta_pi ` and :attr:`UnfoldedSFSDistribution.theta_w ` estimators, and cross-locus linkage via the correlation of coalescence times. - Accelerate state-space construction with `numba `__, 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 `. +- 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. diff --git a/docs/modules/distributions.rst b/docs/modules/distributions.rst index ee2745e6..e239bc92 100644 --- a/docs/modules/distributions.rst +++ b/docs/modules/distributions.rst @@ -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 @@ -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: diff --git a/docs/reference/performance.rst b/docs/reference/performance.rst index af2ed750..3b78e143 100644 --- a/docs/reference/performance.rst +++ b/docs/reference/performance.rst @@ -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() `. 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() `. 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 @@ -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() `). 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() `). 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() `). 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() `). 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 diff --git a/phasegen/__init__.py b/phasegen/__init__.py index 121bf193..47c223a7 100644 --- a/phasegen/__init__.py +++ b/phasegen/__init__.py @@ -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 diff --git a/phasegen/demography.py b/phasegen/demography.py index fdfb9891..ed1982e7 100644 --- a/phasegen/demography.py +++ b/phasegen/demography.py @@ -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() `. Sizes and times are taken over unchanged, so :meth:`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() `. :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]: @@ -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 = {} @@ -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) @@ -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. @@ -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): @@ -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""" diff --git a/phasegen/distributions/_common.py b/phasegen/distributions/_common.py index 5432764e..05fb005a 100644 --- a/phasegen/distributions/_common.py +++ b/phasegen/distributions/_common.py @@ -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 @@ -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. diff --git a/phasegen/distributions/_gradient.py b/phasegen/distributions/_gradient.py index 2a36c35e..26667dfa 100644 --- a/phasegen/distributions/_gradient.py +++ b/phasegen/distributions/_gradient.py @@ -28,9 +28,6 @@ #: Number of Taylor terms whose outer products are contracted in one batch of the reverse pass. _CHUNK = 64 -#: Relative tolerance of the reconstruction of a generator from the basis of :class:`_GeneratorBasis`. -_BASIS_RTOL = 1e-10 - #: Largest step of the differences of the generator over a parameter of the coalescent model it is not affine in, #: relative to the magnitude of the parameter (at least 1). _PARAMETER_STEP = 1e-6 @@ -309,68 +306,41 @@ def __init__(self) -> None: self.factor: float = 1.0 -class _GeneratorBasis: +class _GeneratorDerivatives: r""" - The generator as a linear function of the inverse coalescent time scales and the migration rates, - - .. math:: - \mathbf{S} = \mathbf{K} + \sum_d \frac{\mathbf{C}_d}{s(N_d)} + \sum_{a \neq b} m_{ab} \mathbf{M}_{ab}, - - where :math:`s(N)` is the time scale of the coalescent model at population size :math:`N`, :math:`\mathbf{C}_d` - the coalescence part of deme :math:`d` at unit inverse time scale, :math:`\mathbf{M}_{ab}` the migration part - from deme :math:`a` to deme :math:`b` at unit rate and :math:`\mathbf{K}` the part that depends on neither, such - as recombination. + The derivatives of the generator by the population sizes, the migration rates and the parameters of the coalescent + model, from the parts of the ``_GeneratorBasis`` of the state space. """ def __init__(self, state_space: 'StateSpace') -> None: """ - Build the basis from generators of the state space at unit population sizes. + Take the parts of the generator from the basis of the state space. - :param state_space: The state space, returned to its epoch afterwards. + :param state_space: The state space. """ + basis = state_space._basis + self.state_space = state_space - self.pops: List[str] = list(state_space.lineage_config.pop_names) - self.pairs: List[Tuple[str, str]] = [(a, b) for a in self.pops for b in self.pops if a != b] + self.pops: List[str] = basis.pops + self.pairs: List[Tuple[str, str]] = basis.pairs - epoch = state_space.epoch - model = state_space.model + #: Part depending on neither the population sizes nor the migration rates. + self.K: sp.csr_matrix = basis.part(0) - def generator(sizes: Dict[str, float], rates: Dict[Tuple[str, str], float]) -> sp.csr_matrix: - state_space.update_epoch(Epoch(pop_sizes=sizes, migration_rates=rates)) - return sp.csr_matrix(state_space.S, dtype=float, copy=True) + #: Coalescence part of each deme at unit inverse time scale. + self.C: Dict[str, sp.csr_matrix] = {p: basis.part(1 + i) for i, p in enumerate(self.pops)} - try: - unit = {p: 1.0 for p in self.pops} - S0 = generator(unit, {}) - c1, c2 = 1 / model._get_timescale(1.0), 1 / model._get_timescale(2.0) - - #: Coalescence part of each deme at unit inverse time scale. - self.C: Dict[str, sp.csr_matrix] = { - p: ((S0 - generator(unit | {p: 2.0}, {})) / (c1 - c2)).tocsr() for p in self.pops - } - - #: Migration part of each ordered pair at unit rate. - self.M: Dict[Tuple[str, str], sp.csr_matrix] = { - pair: (generator(unit, {pair: 1.0}) - S0).tocsr() for pair in self.pairs - } - - #: Part depending on neither the population sizes nor the migration rates. - self.K: sp.csr_matrix = (S0 - sum((C * c1 for C in self.C.values()), sp.csr_matrix(S0.shape))).tocsr() - - # the generator is affine in the inverse time scales and migration rates for every coalescent model, which - # an epoch away from the unit values checks - sizes = {p: 0.7 + 0.37 * i for i, p in enumerate(self.pops)} - rates = {pair: 0.3 + 0.21 * j for j, pair in enumerate(self.pairs)} - self._check(sizes, rates, generator(sizes, rates)) - finally: - state_space.update_epoch(epoch) + #: Migration part of each ordered pair at unit rate. + self.M: Dict[Tuple[str, str], sp.csr_matrix] = { + pair: basis.part(1 + len(self.pops) + j) for j, pair in enumerate(self.pairs) + } self._transient: Dict[bytes, Tuple[Dict[str, sp.csr_matrix], Dict[Tuple[str, str], sp.csr_matrix], np.ndarray, np.ndarray]] = {} - #: Finite-difference stencils of the generator over the parameters of :func:`_rate_parameters`, as bases with - #: weights, by parameter, ``None`` for a parameter that cannot be varied. - self._stencils: Dict[str, Optional[List[Tuple['_GeneratorBasis', float]]]] = {} + #: Finite-difference stencils of the generator over the parameters of :func:`_rate_parameters`, as derivatives + #: of varied state spaces with weights, by parameter, ``None`` for a parameter that cannot be varied. + self._stencils: Dict[str, Optional[List[Tuple['_GeneratorDerivatives', float]]]] = {} #: The contractions of :meth:`contraction`, by set of states. self._contractions: Dict[bytes, '_Contraction'] = {} @@ -413,26 +383,23 @@ def touch(self, contraction: '_Contraction', key: tuple, keep: int) -> None: def _generator(self, sizes: Dict[str, float], rates: Dict[Tuple[str, str], float]) -> sp.csr_matrix: """ - The generator rebuilt from the basis. + The generator from the basis of the state space. :param sizes: The population sizes by deme. :param rates: The migration rates by ordered pair, zero where absent. :return: The generator. """ - model = self.state_space.model - S = self.K + sum((self.C[p] / model._get_timescale(sizes[p]) for p in self.pops), sp.csr_matrix(self.K.shape)) - for pair in self.pairs: - S = S + rates.get(pair, 0.0) * self.M[pair] + basis = self.state_space._basis - return S.tocsr() + return basis.matrix(basis.coefficients(sizes, rates)) - def _varied(self, name: str, value: float) -> '_GeneratorBasis': + def _varied(self, name: str, value: float) -> '_GeneratorDerivatives': """ - The basis of the state space with one parameter of :func:`_rate_parameters` changed. + The derivatives of the generator of the state space with one parameter of :func:`_rate_parameters` changed. :param name: The parameter. :param value: Its value. - :return: The basis. + :return: The derivatives. :raises ValueError: If the value is invalid. """ ss = self.state_space @@ -441,9 +408,9 @@ def _varied(self, name: str, value: float) -> '_GeneratorBasis': raise ValueError('The recombination rate must not be negative.') locus_config = copy.copy(ss.locus_config) locus_config.recombination_rate = value - return _GeneratorBasis(ss._with(locus_config=locus_config)) + return _GeneratorDerivatives(ss._with(locus_config=locus_config)) - return _GeneratorBasis(ss._with(model=ss.model._with(**{name: value}))) + return _GeneratorDerivatives(ss._with(model=ss.model._with(**{name: value}))) def _valid(self, name: str, value: float) -> bool: """ @@ -463,15 +430,17 @@ def _valid(self, name: str, value: float) -> bool: return True - def _stencil(self, name: str) -> Optional[List[Tuple['_GeneratorBasis', float]]]: + def _stencil(self, name: str) -> Optional[List[Tuple['_GeneratorDerivatives', float]]]: """ - The bases and weights of a difference of the generator over a parameter, memoized. A parameter the generator - is affine in (the recombination rate and the parameters in ``_affine_parameters`` of the model) takes an exact - two-point difference with a large step towards valid values. Any other takes a second-order central - difference where it may vary by a thousand steps either way and a one-sided one towards valid values otherwise. + The varied state spaces and their weights in a difference of the generator over a parameter, memoized. A + parameter the generator is affine in (the recombination rate and the parameters in ``_affine_parameters`` of + the model) takes an exact two-point difference with a large step towards valid values. Any other takes a + second-order central difference where it may vary by a thousand steps either way and a one-sided one towards + valid values otherwise. :param name: The parameter. - :return: The bases with their weights, or ``None`` if the parameter cannot be varied. + :return: The derivatives of the varied state spaces with their weights, or ``None`` if the parameter cannot be + varied. """ if name not in self._stencils: model = self.state_space.model @@ -574,21 +543,6 @@ def coefficients(self, epoch: Epoch) -> Dict[str, float]: return out - def _check(self, sizes: Dict[str, float], rates: Dict[Tuple[str, str], float], S: sp.csr_matrix) -> None: - """ - Raise if the basis does not reproduce a generator. - - :param sizes: The population sizes of the generator. - :param rates: Its migration rates. - :param S: The generator. - :raises ValueError: If the generator is not reproduced. - """ - diff = abs(self._generator(sizes, rates) - S).max() - if diff > _BASIS_RTOL * max(abs(S).max(), 1e-300): - raise ValueError( - f"The generator is not affine in the inverse time scales and migration rates (deviation {diff:.3g})." - ) - class MeanGradient: """ @@ -613,7 +567,6 @@ def compute_columns(self, rewards: np.ndarray) -> Optional[List[Tuple[float, 'De :param rewards: The reward vectors over the states of the state space, one per column. :return: The mean and gradient of each column, or ``None`` where the occupation times are not defined in closed form. - :raises ValueError: If the generator is not affine in the inverse time scales and migration rates. """ from .phase_type import DemographyGradient @@ -625,7 +578,7 @@ def compute_columns(self, rewards: np.ndarray) -> Optional[List[Tuple[float, 'De m, idx_t = occupation nt = len(idx_t) - basis = _generator_basis(dist.state_space) + basis = _generator_derivatives(dist.state_space) con = basis.contraction(idx_t) names = basis.parameter_names @@ -684,7 +637,7 @@ class _Contraction: states that the generators can take. """ - def __init__(self, basis: _GeneratorBasis, idx: np.ndarray) -> None: + def __init__(self, basis: _GeneratorDerivatives, idx: np.ndarray) -> None: """ Restrict the basis to a set of states. @@ -767,7 +720,6 @@ def compute(self, heads: np.ndarray, tail: Sequence[np.ndarray], :param seeds: The weights of the moments of the last ``i`` rewards of the tail, one per column, by ``i``. :return: The weighted moment and its gradient of each column, ``None`` for a column without weight, or ``None`` where absorption is not certain in the last epoch. - :raises ValueError: If the generator is not affine in the inverse time scales and migration rates. """ from math import factorial from ..rewards import CustomReward @@ -781,7 +733,7 @@ def compute(self, heads: np.ndarray, tail: Sequence[np.ndarray], heads = np.asarray(heads, dtype=float) seeds = {i: np.asarray(w, dtype=float) for i, w in (seeds or {}).items()} n = dist.state_space.k - basis = _generator_basis(dist.state_space) + basis = _generator_derivatives(dist.state_space) names = basis.parameter_names full = basis.contraction(np.arange(n)) rows = np.concatenate([j * n + full.rows for j in range(k + 1)]) @@ -961,28 +913,21 @@ def _zero_gradient(distribution: 'PhaseTypeDistribution', k: int) -> 'Demography """ from .phase_type import DemographyGradient - basis = _generator_basis(distribution.state_space) + basis = _generator_derivatives(distribution.state_space) names = basis.parameter_names return DemographyGradient(distribution._get_epochs_until_unbounded(k), basis.pops, basis.pairs, parameters=names) -def _generator_basis(state_space: 'StateSpace') -> _GeneratorBasis: +def _generator_derivatives(state_space: 'StateSpace') -> _GeneratorDerivatives: """ - The generator basis of a state space, kept on the state space, which :class:`~phasegen.inference.Inference` - shares across evaluations, as is the error of a space without one. + The derivatives of the generator of a state space, kept on the state space, which + :class:`~phasegen.inference.Inference` shares across evaluations. :param state_space: The state space. - :return: The basis. - :raises ValueError: If the generator is not affine in the inverse time scales and migration rates. + :return: The derivatives. """ - if state_space._generator_basis is None: - try: - state_space._generator_basis = _GeneratorBasis(state_space) - except ValueError as e: - state_space._generator_basis = e - - if isinstance(state_space._generator_basis, ValueError): - raise state_space._generator_basis + if state_space._generator_derivatives is None: + state_space._generator_derivatives = _GeneratorDerivatives(state_space) - return state_space._generator_basis + return state_space._generator_derivatives diff --git a/phasegen/distributions/_grid.py b/phasegen/distributions/_grid.py new file mode 100644 index 00000000..c9d0251e --- /dev/null +++ b/phasegen/distributions/_grid.py @@ -0,0 +1,100 @@ +"""Runs of equal steps of a time grid and the propagators reused along them.""" +import sys +from math import isfinite +from typing import Callable, Dict, List, Tuple + +import numpy as np + +#: Number of unit roundoffs of a grid time within which its step continues a run of equal steps. +_STEP_ULPS = 4 + +#: Largest number of step lengths whose propagators ``_Propagators`` keeps. +_MAX_PROPAGATORS = 8 + +#: Largest number of steps of a run, bounding the row vectors a run materializes. +_MAX_RUN_STEPS = 2 ** 12 + + +class _StepRuns: + """ + Ascending times of one epoch as runs of equal steps from the time the propagated vector is at. A run of + :math:`c` steps :math:`d` from :math:`x_0` advances the vector to the times :math:`x_0 + j d`, + :math:`j = 1, \\ldots, c`, and holds the times :math:`u_j` it covers when a step exists with + :math:`|u_j - x_0 - j d| \\le \\epsilon |u_j|` for all :math:`j`, where :math:`\\epsilon` is ``_STEP_ULPS`` + unit roundoffs, the rounding of a time grid. Each run is extended while such a step exists, and is then cut into + runs of at most ``_MAX_RUN_STEPS`` steps. Times at or before the time reached take a step of zero. + """ + + @staticmethod + def split(x: float, t: np.ndarray) -> Tuple[List[Tuple[float, int]], float]: + """ + :param x: The time the vector is at. + :param t: Ascending times, at least ``x`` up to rounding. + :return: The runs as pairs of step and number of steps, and the time reached after the last. + """ + tol = _STEP_ULPS * sys.float_info.epsilon + + # the closed runs, and the open one as its start, the bounds on its step, its number of steps and last time + runs: List[Tuple[float, int]] = [] + run = None + + for u in t.tolist(): + if run is not None: + x0, lo, hi, c, last = run + + if isfinite(u) and isfinite(x0): + r = tol * abs(u) + lo_new, hi_new = max(lo, (u - x0 - r) / (c + 1)), min(hi, (u - x0 + r) / (c + 1)) + + if lo_new <= hi_new: + run = (x0, lo_new, hi_new, c + 1, u) + continue + + d = _StepRuns._step(*run) + runs.append((d, c)) + x = x0 + c * d + + d = u - x if u > x else 0.0 + r = tol * abs(u) if isfinite(d) else 0.0 + run = (x, d - r, d + r, 1, u) + + if run is not None: + d = _StepRuns._step(*run) + runs.append((d, run[3])) + x = run[0] + run[3] * d + + return [(d, min(c - s, _MAX_RUN_STEPS)) for d, c in runs for s in range(0, c, _MAX_RUN_STEPS)], x + + @staticmethod + def _step(x0: float, lo: float, hi: float, c: int, last: float) -> float: + """The step of a run, that to its last time where it lies within the bounds.""" + d = (last - x0) / c if last > x0 else 0.0 + + return max(0.0, min(max(d, lo), hi)) + + +class _Propagators: + """ + The propagators of one epoch by step length, computed by ``compute(tau)`` and kept for the ``_MAX_PROPAGATORS`` + step lengths used most recently. + """ + + def __init__(self, compute: Callable[[float], np.ndarray]) -> None: + """ + :param compute: The propagator of a step. + """ + self._compute = compute + self._cache: Dict[float, np.ndarray] = {} + + def __call__(self, tau: float) -> np.ndarray: + """ + :param tau: The step. + :return: The propagator of ``tau``. + """ + P = self._cache.pop(tau) if tau in self._cache else self._compute(tau) + self._cache[tau] = P + + if len(self._cache) > _MAX_PROPAGATORS: + del self._cache[next(iter(self._cache))] + + return P diff --git a/phasegen/distributions/_kingman.py b/phasegen/distributions/_kingman.py new file mode 100644 index 00000000..41fbc0f0 --- /dev/null +++ b/phasegen/distributions/_kingman.py @@ -0,0 +1,84 @@ +""" +Block-size kernel of the Kingman coalescent, which reduces the second moments of the site-frequency spectrum of a +single deme to the times spent with each number of lineages. +""" +import numpy as np +from scipy.special import binom + + +class KingmanBlockKernel: + r""" + Contraction of the ordered level occupation of the lineage-counting state space with the block-size kernel + :math:`W_{ijkl} = \mathbb{E}[B_{k,i} B_{l,j}]`, the expected product of the number :math:`B_{k,i}` of the + :math:`k` lineages that subtend :math:`i` of the :math:`n` samples and the number :math:`B_{l,j}` of the + :math:`l \le k` lineages that subtend :math:`j`. Level :math:`l` is ancestral to level :math:`k`. With + :math:`d` the number of the :math:`k` lineages that descend from a given one of the :math:`l` lineages and + :math:`c(m, p) = \binom{m - 1}{p - 1}` the number of compositions of :math:`m` into :math:`p` positive parts, + + .. math:: + + W_{ijkl} = l \sum_{d} \frac{c(k - d, l - 1)}{c(k, l)} \cdot + \frac{d\, c(j - i, d - 1)\, c(n - j, k - d) + (k - d)\, c(j, d)\, c(n - j - i, k - d - 1)}{c(n, k)}, + + The occupation is contracted over :math:`l` first, without forming the kernel. + """ + + def __init__(self, n: int) -> None: + """ + :param n: The number of samples :math:`n`, at least 2. + """ + self.n = n + + def contract(self, occupation: np.ndarray) -> np.ndarray: + r""" + The ordered cross-moments :math:`X_{ij} = \sum_{k \ge l} M_{kl} W_{ijkl}`, where :math:`M_{kl}` is the expected + measure of the times :math:`s < t` with :math:`k` lineages at :math:`s` and :math:`l` at :math:`t`, so that + :math:`\mathbb{E}[L_i L_j] = X_{ij} + X_{ji}` for the branch length :math:`L_i` subtending :math:`i` samples. + + :param occupation: The ordered occupation over the transient states of the lineage-counting state space, entry + ``[n - k, n - l]`` holding :math:`M_{kl}`, of shape ``(n - 1, n - 1)``. + :return: :math:`X_{ij}` at ``[i - 1, j - 1]`` for :math:`i, j = 1, \dots, n - 1`. + """ + n = self.n + c = self._compositions() + + # the pairs (k, d) of a level k and a number d = 1, ..., k - 1 of its lineages descending from a lineage of a + # level l <= k + k = np.repeat(np.arange(2, n + 1), np.arange(1, n)) + d = np.concatenate([np.arange(1, m) for m in range(2, n + 1)]) + + # weights over l = 2, ..., n of each pair: l c(k - d, l - 1) / c(k, l) M_kl, zero for l > k + l = np.arange(2, n + 1) + valid = l[None, :] <= k[:, None] + share = np.where(valid, l * c[k - d][:, l - 1] / np.where(valid, c[k][:, l], 1.0), 0.0) + levels = np.asarray(occupation)[np.ix_(n - np.arange(2, n + 1), n - l)] + weight = (share * levels[k - 2]).sum(axis=1) / c[n, k] + + # the descendants (first term) and the other lineages (second term) of size i, as products over the pairs of a + # factor in the size j and one in j - i or n - j - i + j = np.arange(1, n)[:, None] + q = np.arange(n)[:, None] + first = (weight * d * c[n - j, k - d]) @ c[q, d - 1].T + second = (weight * (k - d) * c[j, d]) @ c[q, k - d - 1].T + + i = np.arange(1, n) + diff = j - i[None, :] + rest = n - j - i[None, :] + cross = np.where(diff >= 0, np.take_along_axis(first, np.maximum(diff, 0), axis=1), 0.0) + \ + np.where(rest >= 0, np.take_along_axis(second, np.maximum(rest, 0), axis=1), 0.0) + + # entry [j - 1, i - 1] holds X_ij + return cross.T + + def _compositions(self) -> np.ndarray: + r""" + The numbers of compositions :math:`c(m, p)` for :math:`m, p = 0, \dots, n`, with :math:`c(0, 0) = 1`. + + :return: Array of shape ``(n + 1, n + 1)``. + """ + m = np.arange(self.n + 1)[:, None] + p = np.arange(self.n + 1)[None, :] + c = np.where((m >= p) & (p >= 1), binom(np.maximum(m - 1, 0), np.maximum(p - 1, 0)), 0.0) + c[0, 0] = 1.0 + + return c diff --git a/phasegen/distributions/_moments.py b/phasegen/distributions/_moments.py index 4fae1f69..27f270a4 100644 --- a/phasegen/distributions/_moments.py +++ b/phasegen/distributions/_moments.py @@ -8,7 +8,7 @@ from collections import deque from ..caching import cache from math import comb, factorial -from typing import Dict, List, Tuple, Iterable, Optional, Sequence, TYPE_CHECKING +from typing import Dict, List, NamedTuple, Tuple, Iterable, Optional, Sequence, TYPE_CHECKING import numpy as np import scipy.linalg as sla import scipy.sparse as sp @@ -24,7 +24,9 @@ from ..settings import Settings from ..state_space import BlockCountingStateSpace +from ._grid import _Propagators, _StepRuns from ._gradient import _ClosedFormTape, _OccupationStep, _TapedAction, _VanLoanStep +from ._kingman import KingmanBlockKernel from ._common import _make_hashable, _validate_order, _validate_reward_count, _validate_rewards, \ _validate_start_time @@ -51,20 +53,82 @@ #: reward terms below double resolution, and a smaller factor would overflow the rebased extended vector. _MIN_BALANCE = np.finfo(float).eps -#: Summed 1-norm of the steps ``S tau`` per cubed Van Loan dimension above which the closed form takes the dense -#: exponential in its finite epochs and its propagation to the start time, and below which the sparse action. The -#: action takes a number of matrix-vector products proportional to the step norm, the dense exponential a cost cubic -#: in the dimension. Measured crossover about 1e-5 to 1e-4 on block-counting spaces of 297 to 627 states, with the -#: dense exponential 8 to 30 times faster on lineage-counting chains of 260 to 600 states at 2e-4 to 2e-3. -#: ``_occupation_times`` applies it to each epoch on its own, with the dimension of its augmented generator. -_DENSE_EXPM_STEP_NORM = 5e-5 - -#: Fixed cost of one sparse action in units of the step norm, added per exponential to the summed step norm compared -#: against ``_DENSE_EXPM_STEP_NORM``. Fitted on 924 finite-epoch generators of one- and two-deme spaces of 1 to 10 -#: epochs and Van Loan dimensions 35 to 1216, where it brings the total time within 0.1% of always taking the faster -#: of the two exponentials. It sends dimensions below about 74 to the dense exponential. +#: Cost ratio :math:`K` of the dense exponentials against the sparse action of ``_ExpmCost``. With +#: ``_ACTION_STEP_NORM_OFFSET``, ``_TAPED_DENSE_COST`` and ``_MOMENT_COST``, fitted jointly on 3880 passes recorded on +#: each of an arm64 Mac and an x86-64 cluster node (closed-form and windowed moments, occupation times, time grids, +#: the forward pass of the second moments of spectra and gradients, 10 to 490 states), where it brings each kind of +#: pass within 2.5% of always taking the faster side on both machines. +_EXPM_COST_RATIO = 0.17 + +#: Fixed cost :math:`\gamma` of one sparse action in units of the step norm, the work besides the matrix-vector +#: products that the step norm counts. _ACTION_STEP_NORM_OFFSET = 20 +#: Factor on the cost of the dense exponentials of a pass recorded for its gradient, whose backward pass takes the +#: Fréchet derivative of each dense exponential and reverses each action. +_TAPED_DENSE_COST = 4 + +#: Dense size from which ``Settings.expm_method = 'auto'`` takes the action whatever the cost, which bounds the memory +#: of the dense exponentials. +_EXPM_ACTION_MIN_DIM = 1500 + + +class _ExpmCost(NamedTuple): + r""" + A cost profile of the choice between dense exponentials and sparse actions. With :math:`n_a` actions of + :math:`B` stacked vectors under operators of dimension :math:`d_a` and step norms :math:`s_i`, against + :math:`B c` dense exponentials of size :math:`d_d` for each of :math:`n_d` steps, the dense side is cheaper where + + .. math:: + \left(\sum_i s_i + \gamma n_a\right) (B d_a + d_0) > K F F_\mathrm{tape} B c\, n_d\, d_d^3, + + with :math:`\gamma` the ``_ACTION_STEP_NORM_OFFSET``, :math:`K` the ``_EXPM_COST_RATIO``, :math:`F` and + :math:`d_0` the fields of the profile, and :math:`F_\mathrm{tape}` the ``_TAPED_DENSE_COST`` for a pass recorded + for its gradient and 1 otherwise. + """ + #: The factor :math:`F` on the cost of the dense exponentials. + dense: float + + #: The fixed cost :math:`d_0` of a product of the action in units of a row entry. + offset: int + + def bound(self, d_action: int, d_dense: int, count: int, n_actions: int, n_dense: int, batch: int = 1, + taped: bool = False) -> float: + r""" + The summed step norm above which the dense exponentials are cheaper, by :attr:`Settings.expm_method + `: :math:`-\infty` for ``'dense'``, :math:`\infty` for ``'action'`` + and for ``'auto'`` from ``_EXPM_ACTION_MIN_DIM`` in ``d_dense`` on, and the cost model otherwise. + + :param d_action: The dimension :math:`d_a` of the operator of an action. + :param d_dense: The size :math:`d_d` of each dense exponential. + :param count: The number :math:`c` of dense exponentials per step and vector. + :param n_actions: The number :math:`n_a` of actions. + :param n_dense: The number :math:`n_d` of steps with their own dense exponentials. + :param batch: The number :math:`B` of stacked vectors. + :param taped: Whether the pass is recorded for its gradient. + :return: The bound, negative where the dense exponentials are cheaper at any norm. + """ + if Settings.expm_method == 'dense': + return -np.inf + + if Settings.expm_method == 'action' or d_dense >= _EXPM_ACTION_MIN_DIM: + return np.inf + + factor = _EXPM_COST_RATIO * self.dense * (_TAPED_DENSE_COST if taped else 1) + return (factor * batch * count * n_dense * d_dense ** 3 / (batch * d_action + self.offset) - + _ACTION_STEP_NORM_OFFSET * n_actions) + + +#: The cost profile of the moments, distribution functions and occupation times. +_MOMENT_COST = _ExpmCost(dense=1, offset=10000) + +#: The cost profile of a batch of the Laplace transform, propagated as one stacked action of the batched truncated +#: Taylor series and exponentiated as one stack of Pade approximants. Fitted with ``_EXPM_COST_RATIO`` on 6981 batches +#: recorded on an x86-64 cluster node (marginal, joint and conditional transforms on one and two demes, two loci, +#: splits, pulses and out of Africa, 2 to 627 dimensions, 1 to 44 bounded epochs), where it brings each kind of batch +#: within 3% of always taking the faster side. +_TRANSFORM_COST = _ExpmCost(dense=0.36, offset=3000) + #: Smallest dimension from which the dense exponentials of the Van Loan matrices and of the augmented occupation #: generator take ``BlockTriangularExpm``, one matrix at a time, rather than the generic exponential of the stack. #: Over matrices of 2 to 4 diagonal blocks of 8 to 128 states each and step norms 0.1 to 100, it picked an exponential @@ -75,6 +139,9 @@ #: Largest number of entries of a stack of matrices exponentiated at once, about a megabyte, so that it stays in cache. _MAX_STACK_ENTRIES = 2 ** 17 +#: The SciPy backend, whose interval action the occupation grid of spectra takes whichever backend is registered. +_SCIPY_EXPM = SciPyExpmBackend() + #: Largest ratio of the pairwise coalescence and migration rates of an epoch that double precision resolves, see #: ``MomentEvaluator._rate_spread``. _MAX_RATE_SPREAD = 1e16 @@ -99,27 +166,22 @@ class MomentEvaluator: _epochs_cache: Dict[int, Tuple[List[Epoch], bool]] @staticmethod - def _van_loan_matrix(R, S, k: int = 1, sparse: bool = False, heads: int = 1) -> 'sp.spmatrix | np.ndarray': + def _van_loan_matrix(R, S, k: int = 1, sparse: bool = False) -> 'sp.spmatrix | np.ndarray': r""" The Van Loan matrix of ``PhaseTypeDistribution.moment``, assembled directly as sparse CSR when ``sparse``. - With several ``heads`` (sparse only), the first block row and column are repeated once per head, each head - coupled to the shared second block by its own reward. - :param R: List of reward vectors, one per head followed by the rewards 2, ..., k. + :param R: List of length k of reward vectors. :param S: Intensity matrix (dense or sparse, matching ``sparse``). :param k: The order of the moment. :param sparse: Whether to build a sparse matrix. - :param heads: The number of first blocks. - :return: Van Loan matrix of :math:`(k + h) \times (k + h)` blocks for :math:`h` heads. + :return: Van Loan matrix of :math:`(k + 1) \times (k + 1)` blocks. """ if sparse: - blocks = [[None] * (k + heads) for _ in range(k + heads)] - for i in range(k + heads): + blocks = [[None] * (k + 1) for _ in range(k + 1)] + for i in range(k + 1): blocks[i][i] = S - if heads - 1 <= i < k + heads - 1: + if i < k: blocks[i][i + 1] = sp.diags(R[i]) - for a in range(heads - 1): - blocks[a][heads] = sp.diags(R[a]) return sp.bmat(blocks, format='csr') O = np.zeros_like(S) @@ -251,10 +313,8 @@ def _solve_sparse(n_transient: int) -> bool: """ Whether a linear solve over ``n_transient`` transient states takes the sparse path, at and above :attr:`Settings.closed_form_sparse_min_states `. - Distinct from :attr:`Settings.expm_action_min_dim `, which - governs the matrix-exponential action, though ``_accumulate_closed_form`` and ``_occupation_times`` let this - one decide both, their exponentials following the sparsity their factorization already takes, except on the - stiff generators of ``_DENSE_EXPM_STEP_NORM``. + The matrix exponentials are chosen independently, by ``_dense_expm_is_faster`` under + :attr:`Settings.expm_method `. :param n_transient: Number of transient states the solve is over. :return: Whether to take the sparse path. @@ -362,11 +422,9 @@ def moment( .. rubric:: Implementation - - Matrix exponentials are formed densely while :math:`(k + 1)|E|` is below - :attr:`Settings.expm_action_min_dim `, and are otherwise - applied to vectors as sparse actions (Al-Mohy and Higham, 2011). In the closed form below, the finite epochs - take the sparse action at any dimension, except where the rates are stiff enough for the dense exponential - to be faster. + - Matrix exponentials are applied to vectors as sparse actions (Al-Mohy and Higham, 2011) or formed densely + as :attr:`Settings.expm_method ` selects, by default by a cost + comparison, with :math:`(k + 1)|E|` the size of the dense exponential. - :math:`\mathbf{U}` is never formed. A single LU factorization of :math:`-\mathbf{T}` serves all solves. It is sparse from :attr:`Settings.closed_form_sparse_min_states ` transient states on, with the states ordered by @@ -380,11 +438,10 @@ def moment( block of its own, where :math:`\lambda` is the balancing factor of the blocks. - Spectra share one computation across bins. The expected occupation times :math:`\mathbf{m}` of the transient states, which equal :math:`\boldsymbol{\alpha}_T \mathbf{U}` in a single epoch, give every bin - mean as :math:`\mathbf{m}\, \mathbf{r}_j`, and in a single epoch the two-point occupation - :math:`\operatorname{diag}(\mathbf{m})\, \mathbf{U}` gives every covariance at once. For one population - under the :class:`~phasegen.coalescent_models.StandardCoalescent`, the mean SFS is computed on the smaller - lineage-counting state space (:attr:`Settings.flatten_block_counting - `). + mean as :math:`\mathbf{m}\, \mathbf{r}_j`. + - For one population and one locus under the :class:`~phasegen.coalescent_models.StandardCoalescent`, the + first moments and the second moments of the SFS bins are computed on the smaller lineage-counting state + space (:attr:`Settings.flatten_block_counting `). .. rubric:: References @@ -604,22 +661,31 @@ def _action_operator(self, rewards: Sequence[Reward], k: int, i_epoch: int) -> T return (Vt, np.where(reward, 0.0, Vt.data), np.where(reward, Vt.data, 0.0), self._get_regularization_factor(S, scale=scale), scale) - def _advance_action(self, w: np.ndarray, tau: float, lamb: float, op: Tuple, k: int) -> Tuple[np.ndarray, float]: + def _advance_action( + self, + w: np.ndarray, + tau: float, + lamb: float, + op: Tuple, + k: int, + count: int = 1 + ) -> Tuple[np.ndarray, float]: """ - Advance the forward extended vector by ``tau`` within the current epoch by the sparse matrix-exponential - action. Each step is balanced on the factor of the epoch capped at the reward scale times - ``tau / _MIN_SCALED_STEP``, since block ``j`` of the vector gains the ``j``-th power of the scaled step, and - floored at ``_MIN_BALANCE`` times the factor. + Advance the forward extended vector ``count`` times by ``tau`` within the current epoch by the sparse + matrix-exponential action, several steps by one interval action. Each step is balanced on the factor of the + epoch capped at the reward scale times ``tau / _MIN_SCALED_STEP``, since block ``j`` of the vector gains the + ``j``-th power of the scaled step, and floored at ``_MIN_BALANCE`` times the factor. :param w: Extended row vector of ``(k + 1)`` blocks, stored against ``lamb`` and rebased in place. :param tau: The step, non-positive for none. :param lamb: The factor ``w`` is stored against. :param op: The operator of :meth:`_action_operator` for the current epoch. :param k: The order of the moment. - :return: The advanced vector and the factor it is stored against. + :param count: The number of steps. + :return: The vectors after each step, of shape ``(count, len(w))``, and the factor they are stored against. """ if tau <= 0: - return w, lamb + return np.repeat(w[None], count, axis=0), lamb Vt, gen, rew, factor, scale = op if Settings.regularize: @@ -628,7 +694,12 @@ def _advance_action(self, w: np.ndarray, tau: float, lamb: float, op: Tuple, k: A = sp.csr_matrix((tau * gen + (tau / lamb) * rew, Vt.indices, Vt.indptr), shape=Vt.shape) - return Backend.expm_multiply(A, w, blocks=k + 1), lamb + if count == 1: + return Backend.expm_multiply(A, w, blocks=k + 1)[None], lamb + + return Backend.expm_multiply_interval( + A, w, float(count), count, advance=lambda v, s: Backend.expm_multiply(A * s, v, blocks=k + 1) + ), lamb def _rate_spread(self, epoch: 'Epoch', duration: float = np.inf) -> float: r""" @@ -815,7 +886,8 @@ def _powers_apply(self, k: int, rewards: Sequence[Reward], end_times: Sequence[f """ Whether the raw moments up to order ``k`` are read from one closed form by :meth:`_raw_powers`: where the rewards are equal, the end times infinite, :attr:`Settings.closed_form_last_epoch - ` set and absorption certain in the last epoch. + ` set, the moment not flattened and absorption certain in + the last epoch. :param k: The order. :param rewards: The rewards. @@ -826,6 +898,7 @@ def _powers_apply(self, k: int, rewards: Sequence[Reward], end_times: Sequence[f all(r == rewards[0] for r in rewards[1:]) and bool(np.isinf(end_times).all()) and Settings.closed_form_last_epoch and + not self._flattening_applies(k, rewards) and self._absorption_certain_in_last_epoch(k) ) @@ -910,32 +983,35 @@ def _accumulate_flattened( rewards: Sequence[Reward] = None, start_time: float = 0.0 ) -> np.ndarray: - """ - Evaluate the kth (non-central) moment at different end times using the lineage counting state space. + r""" + Evaluate the kth (non-central) moment at different end times using the lineage counting state space. The + second moment of the bin rewards ``a`` and ``b`` collected in this order is + :math:`2 \sum_{i \in a, j \in b} X_{ij}`, see ``KingmanBlockKernel.contract``. - :param k: The order of the moment. + :param k: The order of the moment, 1 or 2. :param end_times: Sequence of end times or end time when to evaluate the moment. :param rewards: Sequence of k rewards. By default, the reward of the underlying distribution. :param start_time: Time from which to start accumulation. :return: The moment accumulated at the specified times or time. - :raises ValueError: If the state space is not a :class:`~phasegen.state_space.BlockCountingStateSpace`, or if - k is not 1, or if there are multiple populations or loci or if the coalescent model is not the standard - coalescent. + :raises ValueError: If the moment is not flattened, see ``_flattening_applies``. """ + rewards = (self.reward,) * k if rewards is None else tuple(rewards) - if not isinstance(self.state_space, BlockCountingStateSpace): - raise ValueError("Flattened accumulation is only supported for BlockCountingStateSpace.") - - if k != 1: - raise ValueError("Flattened accumulation is only supported for k = 1.") + if not self._flattening_applies(k, rewards): + raise ValueError( + "Flattened accumulation is only supported for the first moment and for the second moment of SFS bins " + "on the block-counting state space of a single population and a single locus under the standard " + "coalescent." + ) - if self.lineage_config.n_pops != 1 or self.locus_config.n != 1: - raise ValueError("Flattened accumulation is only supported for a single population and a single locus.") + if k == 2: + n = self.lineage_config.n + a, b = (np.asarray(self._sfs_reward_block_sizes(r, n)) - 1 for r in rewards) + cross = self._tree_height._level_cross_moments(tuple(end_times), float(start_time))[1] - if not isinstance(self.state_space.model, StandardCoalescent): - raise ValueError("Flattened accumulation is only supported for standard coalescent.") + return 2 * cross[:, a][:, :, b].sum(axis=(1, 2)) - weights = self._flattened_weights(rewards[0] if rewards else self.reward) + weights = self._flattened_weights(rewards[0]) # Create a custom reward that returns the weights. weighted_reward = CustomReward(lambda _: weights) @@ -944,6 +1020,38 @@ def _accumulate_flattened( k=k, end_times=end_times, rewards=(weighted_reward,), start_time=start_time ) + @_make_hashable + @cache + def _level_cross_moments(self, end_times: Sequence[float], start_time: float) -> np.ndarray: + r""" + The ordered cross-moments :math:`X_{ij}` of ``KingmanBlockKernel.contract`` of the branch lengths subtending + :math:`i` and :math:`j` samples, from the ordered two-point occupation :math:`M_{ab} = \mathbb{E} + \int\!\!\int_{t_\mathrm{start} < s < u < t} \mathbb{1}\{X_s = a\} \mathbb{1}\{X_u = b\}\, \mathrm{d}s\, + \mathrm{d}u` of the transient states :math:`a, b` of the lineage-counting state space of this distribution, with + :math:`X_s` the state at time :math:`s` and :math:`t` an end time. ``_bin_second_moments`` of the indicator + rewards of the states gives :math:`M + M^\top`, and :math:`M` is upper triangular, the states being ordered by + decreasing number of lineages. + + :param end_times: The end times. + :param start_time: The start time. + :return: The expected occupation of each transient state, of shape ``(len(end_times), n - 1)``, and + :math:`X_{ij}`, of shape ``(len(end_times), n - 1, n - 1)``. + """ + idx_t = np.where(~self.state_space.absorbing)[0] + levels = [CustomReward(lambda space, a=a: (np.arange(space.k) == a).astype(float)) for a in idx_t] + kernel = KingmanBlockKernel(self.lineage_config.n) + + means = np.zeros((len(end_times), len(idx_t))) + cross = np.zeros((len(end_times), len(idx_t), len(idx_t))) + for i, end_time in enumerate(end_times): + if end_time > start_time: + means[i], occupation = self._bin_second_moments(levels, start_time, end_time) + occupation = np.triu(occupation) + occupation[np.diag_indices_from(occupation)] /= 2 + cross[i] = kernel.contract(occupation) + + return means, cross + def _flattened_weights(self, reward: Reward) -> np.ndarray: """ The reward of :meth:`_accumulate_flattened` on the lineage-counting state space, indexed by ``n - k`` for @@ -1056,7 +1164,7 @@ def _accumulate( # flattening takes precedence over the closed form (it shrinks the state space, which dominates the cost) and # re-enters this method on the lineage-counting state space, where the flattened reward is checked - if self._flattening_applies(k): + if self._flattening_applies(k, rewards): self._logger.debug("accumulate (k=%d): flattened block-counting", k) return self._accumulate_flattened(k, end_times, rewards, start_time) @@ -1128,9 +1236,10 @@ def _accumulate_windowed( Raw moment of a single reward ordering over the window ``[start_time, t]`` for each finite ``t`` in ``end_times``: propagates ``alpha`` to ``start_time`` with the plain generator, then threads the row vector holding it in its first block through the epochs by the Van Loan exponential and reads off its product with - ``e`` in the last block at each end time. The exponential is dense below :attr:`Settings.expm_action_min_dim - ` and a sparse action above. For ``k >= 2`` the difference of - two moments accumulated from 0 would omit the cross terms. + ``e`` in the last block at each end time. The exponential is dense or a sparse action as + ``_dense_expm_is_faster`` decides from ``_grid_steps``. Within an epoch, the end times are + taken as runs of equal steps (``_StepRuns``), with one dense exponential per step length or one interval action + per run. For ``k >= 2`` the difference of two moments accumulated from 0 would omit the cross terms. :param k: The order of the moment. :param start_time: The non-negative window start time. @@ -1145,7 +1254,8 @@ def _accumulate_windowed( self.state_space.update_epoch(epoch) n = self.state_space.k - use_action = (k + 1) * n >= Settings.expm_action_min_dim + dim = (k + 1) * n + use_action = not self._dense_expm_is_faster(dim, dim, 1, *self._grid_steps(start_time, t_sorted)) # --- propagate the entry distribution to the window start via the plain generator --- alpha_start = np.asarray(self.state_space.alpha, dtype=float) @@ -1181,44 +1291,60 @@ def _accumulate_windowed( lamb = self._balance(epoch, start_time, t_sorted[-1], scale) op = self._dense_van_loan(R, lamb, k, i_epoch) - def advance(w, tau, lamb) -> Tuple[np.ndarray, float]: + def propagators(op: np.ndarray, lamb: float) -> _Propagators: + """The dense exponentials of the Van Loan matrix ``op`` balanced by ``lamb``, by step.""" + return _Propagators(lambda tau: self._block_expm((op * tau / lamb)[None], n, [False] * (k + 1))[0]) + + expms = None if use_action else propagators(op, lamb) + + def advance(w, tau, lamb, count=1) -> Tuple[np.ndarray, float]: if use_action: - return self._advance_action(w, tau, lamb, op, k) + return self._advance_action(w, tau, lamb, op, k, count) - return w @ self._block_expm((op * tau / lamb)[None], n, [False] * (k + 1))[0], lamb + W = np.empty((count, len(w))) + for c in range(count): + w = W[c] = w @ expms(tau) if tau > 0 else w + + return W, lamb moments = np.zeros_like(t_sorted, dtype=float) + # an empty (or reversed) window accumulates no reward + x, i = start_time, int(np.searchsorted(t_sorted, start_time, side='right')) + # The Van Loan exponential is evaluated over the absorption time, which scales with Ne (the doubling search # in ``_get_absorption_time`` deliberately spans many orders of magnitude). For a large time the dense # ``expm`` can transiently over/underflow inside scipy's scaling-squaring on some BLAS builds, even though # the regularized result (corrected by ``lamb ** k``) is finite. The benign intermediate over/divide/invalid # is silenced here and the *output* is checked for finiteness below, so a genuine blow-up still surfaces. with np.errstate(over='ignore', divide='ignore', invalid='ignore', under='ignore'): - for i, u in enumerate(t_sorted): - if u <= start_time: - # an empty (or reversed) window accumulates no reward - continue + while i < len(t_sorted): + # the end times up to the end of the epoch, as runs of equal steps + j = int(np.searchsorted(t_sorted, epoch.end_time, side='right')) + runs, x_end = _StepRuns.split(x, t_sorted[i:j]) + + for step, count in runs: + W, lamb = advance(w, step, lamb, count) + moments[i:i + count] = factorial(k) * lamb ** k * (W @ e_ext) + w, i = W[-1].copy(), i + count + + if i == len(t_sorted): + break + + # advance to the end of the epoch + w, lamb = advance(w, epoch.end_time - x_end, lamb) + w, x = w[-1], epoch.end_time + i_epoch, epoch = next(epochs) + self.state_space.update_epoch(epoch) - # advance through whole epochs between u_prev and u - while u > epoch.end_time: - w, lamb = advance(w, epoch.end_time - u_prev, lamb) - u_prev = epoch.end_time - i_epoch, epoch = next(epochs) - self.state_space.update_epoch(epoch) - - if use_action: - op = self._action_operator(rewards, k, i_epoch) - else: - # balance each epoch on its own rates (see ``_rebase``) - lamb_new = self._balance(epoch, start_time, t_sorted[-1], scale) - lamb = self._rebase_forward(w, lamb, lamb_new, k, n) - op = self._dense_van_loan(R, lamb, k, i_epoch) - - # remaining time in the current epoch - w, lamb = advance(w, u - u_prev, lamb) - moments[i] = factorial(k) * lamb ** k * float(w @ e_ext) - u_prev = u + if use_action: + op = self._action_operator(rewards, k, i_epoch) + else: + # balance each epoch on its own rates (see ``_rebase``) + lamb_new = self._balance(epoch, start_time, t_sorted[-1], scale) + lamb = self._rebase_forward(w, lamb, lamb_new, k, n) + op = self._dense_van_loan(R, lamb, k, i_epoch) + expms = propagators(op, lamb) # restore the original (unsorted) order moments = moments[np.argsort(np.argsort(end_times))] @@ -1576,7 +1702,6 @@ def _accumulate_closed_form( k: int, rewards: Sequence[Reward], start_time: float = 0.0, - heads: Sequence[Reward] = None, tape: _ClosedFormTape = None, suffixes: bool = False ) -> np.ndarray: @@ -1586,30 +1711,19 @@ def _accumulate_closed_form( finite epochs from ``start_time`` on applied backwards to the extended vector, and last the entry distribution propagated to ``start_time``. - With ``heads``, each head takes the place of the first reward in turn. The blocks of the extended vector after - the first do not depend on the first reward, so one extended vector holds a first block per head and the - remaining blocks once, and a single LU and, on the sparse action, a single action per epoch serve every head. - :param k: The order of the moment, at least 1. :param rewards: Sequence of k rewards (a single ordering). :param start_time: The non-negative start time. - :param heads: Rewards each substituted for the first of ``rewards``. By default, the first of ``rewards``. - :param tape: If given, receives the record that ``CrossMomentGradient`` differentiates, for a single head and a - zero start time. The sparse actions are then applied by ``_TapedAction``. - :param suffixes: Whether to return, for a single head, the raw moments of the trailing rewards ``rewards[k - - i:]`` for ``i = 0, ..., k``, read from the trailing blocks of the extended vector, one for ``i = 0``. - :return: The kth moment accumulated until absorption, one per head, or the moments of the trailing rewards. - :raises ValueError: If ``tape`` is given with several heads or a positive start time, or ``suffixes`` with - several heads. + :param tape: If given, receives the record that ``CrossMomentGradient`` differentiates, for a zero start time. + The sparse actions are then applied by ``_TapedAction``. + :param suffixes: Whether to return the raw moments of the trailing rewards ``rewards[k - i:]`` for ``i = 0, + ..., k``, read from the trailing blocks of the extended vector, one for ``i = 0``. + :return: The kth moment accumulated until absorption, as an array of one entry, or the moments of the trailing + rewards. + :raises ValueError: If ``tape`` is given with a positive start time. """ - heads = tuple(rewards[:1]) if heads is None else tuple(heads) - m = len(heads) - - if tape is not None and (m > 1 or start_time > 0): - raise ValueError("A closed form is recorded for a single head from time zero only.") - - if suffixes and m > 1: - raise ValueError("The moments of the trailing rewards are returned for a single head only.") + if tape is not None and start_time > 0: + raise ValueError("A closed form is recorded from time zero only.") epochs = self._get_epochs_until_unbounded(k) self._check_demography_conditioning(epochs) @@ -1633,14 +1747,10 @@ def _accumulate_closed_form( # finite-epoch Van Loan exponentials take the sparse action except on the stiff generators of # ``_dense_expm_is_faster``, whatever the factorization. sparse = self._solve_sparse(len(idx_t)) - use_action = not self._dense_expm_is_faster(k, epochs, start_time) - - # the dense exponential of the stacked Van Loan matrix grows with the cube of the number of heads, so there each - # head is evaluated on its own - if m > 1 and not use_action: - return np.concatenate([ - self._accumulate_closed_form(k, (h,) + tuple(rewards[1:]), start_time) for h in heads - ]) + dim = (k + 1) * n + use_action = not self._dense_expm_is_faster( + dim, dim, 1, self._closed_form_steps(epochs, start_time), taped=tape is not None + ) if sparse: self._logger.debug( @@ -1655,11 +1765,9 @@ def _accumulate_closed_form( solve = self._last_epoch_solver(id(self.state_space), len(epochs), idx_t.astype(np.intp).tobytes(), sparse) # the j-th block of the extended vector is stored divided by lamb ** (k - j), which balances the Van Loan - # exponentials of the finite epochs, so the moment is multiplied by lamb ** k at the end. The heads share one - # factor, whose reward scale spans every head. + # exponentials of the finite epochs, so the moment is multiplied by lamb ** k at the end r_all = [np.asarray(r._get(self.state_space), dtype=float) for r in rewards] - r_heads = [np.asarray(h._get(self.state_space), dtype=float) for h in heads] - scale = self._reward_scale(r_heads + r_all[1:]) + scale = self._reward_scale(r_all) lamb = self._get_regularization_factor(self.state_space.S, scale=scale) # reward diagonals restricted to the transient states (the off-diagonal Van Loan reward blocks are diagonal) @@ -1670,13 +1778,11 @@ def _accumulate_closed_form( for j in range(k - 1, 0, -1): nu[j] = solve(r_t[j] * nu[j + 1]) / lamb - # the extended vector holds the first block of each head, then the blocks 1, ..., k shared by the heads - z = np.zeros((m + k) * n) - for a, r_h in enumerate(r_heads): - z[a * n + idx_t] = solve(r_h[idx_t] * nu[1]) / lamb + z = np.zeros((k + 1) * n) + z[idx_t] = solve(r_t[0] * nu[1]) / lamb for j in range(1, k + 1): - z[(m - 1 + j) * n + idx_t] = nu[j] - z[(m - 1 + k) * n + idx_a] = e[idx_a] + z[j * n + idx_t] = nu[j] + z[k * n + idx_a] = e[idx_a] if tape is not None: tape.epochs, tape.idx_t, tape.solve, tape.lamb = epochs, idx_t, solve, lamb @@ -1691,7 +1797,7 @@ def _accumulate_closed_form( # steps and Van Loan matrices do not depend on the extended vector, so they are gathered first and the dense # exponentials evaluated in stacks. steps = [] - R = [r._get(self.state_space) for r in heads + tuple(rewards[1:])] + R = [r._get(self.state_space) for r in rewards] for i_epoch, epoch in reversed(list(enumerate(epochs[:-1]))): if epoch.end_time <= start_time: break @@ -1704,7 +1810,7 @@ def _accumulate_closed_form( if use_action: r_vecs = [np.asarray(r, dtype=float) for r in R] - V = self._van_loan_matrix(r_vecs, self._epoch_csr(i_epoch) * lamb_e, k, sparse=True, heads=m) + V = self._van_loan_matrix(r_vecs, self._epoch_csr(i_epoch) * lamb_e, k, sparse=True) steps.append((i_epoch, duration, lamb_e, V * tau)) else: steps.append((i_epoch, duration, lamb_e, (self._dense_rate_matrix() * lamb_e, tau))) @@ -1715,11 +1821,9 @@ def _accumulate_closed_form( ], n, [False] * (k + 1)) for i_epoch, duration, lamb_e, op in steps: - z[:(m - 1) * n] *= (lamb / lamb_e) ** k - if tape is None: - lamb = self._rebase(z[(m - 1) * n:], lamb, lamb_e, k, n) - z = Backend.expm_multiply(op, z, blocks=k + m) if use_action else next(exps) @ z + lamb = self._rebase(z, lamb, lamb_e, k, n) + z = Backend.expm_multiply(op, z, blocks=k + 1) if use_action else next(exps) @ z continue rebase = np.ones_like(z) @@ -1728,7 +1832,7 @@ def _accumulate_closed_form( if use_action: step = _VanLoanStep(i_epoch, epochs[i_epoch], duration, rebase, z.copy(), op.tocsr()) - step.action = _TapedAction(step.A, blocks=k + m) + step.action = _TapedAction(step.A, blocks=k + 1) z, step.checkpoints = step.action.apply(z) else: S, tau = op @@ -1759,58 +1863,127 @@ def _accumulate_closed_form( factorial(i) * lamb ** i * float(alpha_ext[:n] @ z[(k - i) * n:(k - i + 1) * n]) for i in range(1, k + 1) ]) - return factorial(k) * lamb ** k * np.array([ - float(alpha_ext @ np.concatenate([z[a * n:(a + 1) * n], z[m * n:]])) for a in range(m) - ]) + return np.array([factorial(k) * lamb ** k * float(alpha_ext @ z)]) - def _dense_expm_is_faster(self, k: int, epochs: List[Epoch], start_time: float) -> bool: - """ - Whether the dense exponentials of ``_accumulate_closed_form``, those of the finite epochs and of the propagation - to ``start_time``, are cheaper than the sparse action: below :attr:`Settings.expm_action_min_dim - ` in the Van Loan dimension, where the summed 1-norm of the - steps ``S tau``, each increased by ``_ACTION_STEP_NORM_OFFSET``, exceeds ``_DENSE_EXPM_STEP_NORM`` times the - cube of the dimension. Leaves the state space in the last epoch. - - :param k: The order of the moment. - :param epochs: The epochs of ``_get_epochs_until_unbounded``. - :param start_time: The non-negative start time. + def _dense_expm_is_faster( + self, + d_action: int, + d_dense: int, + count: int, + steps: List[Tuple[Epoch, float]], + n_dense: int = None, + taped: bool = False + ) -> bool: + """ + Whether ``count`` dense exponentials of size ``d_dense`` per step are cheaper than one sparse action of an + operator of dimension ``d_action`` per step, over the steps ``(epoch, tau)``, or ``n_dense`` times ``count`` + dense exponentials when they are reused across steps, by ``_MOMENT_COST`` with the step norms of the rate + matrix ``S`` of each epoch. Leaves the state space in the epoch it found. + + :param d_action: The dimension of the operator of the action. + :param d_dense: The size of each dense exponential. + :param count: The number of dense exponentials per step. + :param steps: The epochs and the times of the actions. + :param n_dense: The number of steps with their own dense exponentials, by default all. + :param taped: Whether the pass is recorded for its gradient. :return: Whether to form the dense exponentials. """ - dim = (k + 1) * self.state_space.k - if dim >= Settings.expm_action_min_dim: + steps = [(epoch, tau) for epoch, tau in steps if tau > 0] + if not steps: return False - # the exponentials span the time up to the later of the start time and the start of the last epoch - horizon = max(start_time, epochs[-1].start_time) - steps = [(epoch, min(epoch.end_time, horizon) - epoch.start_time) for epoch in epochs] - steps = [(epoch, tau) for epoch, tau in steps if tau > 0] + bound = _MOMENT_COST.bound(d_action, d_dense, count, len(steps), len(steps) if n_dense is None else n_dense, + taped=taped) + if bound == np.inf: + return False # the fixed costs of the actions alone may exceed the dense exponentials, without reading a generator - norm = _ACTION_STEP_NORM_OFFSET * len(steps) - if norm > _DENSE_EXPM_STEP_NORM * dim ** 3: + if bound < 0: return True + # the summed step norm, reading each epoch's generator once + durations: Dict[Epoch, float] = {} for epoch, tau in steps: + durations[epoch] = durations.get(epoch, 0.0) + tau + + current = self.state_space.epoch + norm = 0.0 + for epoch, duration in durations.items(): self.state_space.update_epoch(epoch) - norm += float(abs(self.state_space.S).sum(axis=0).max()) * tau + norm += float(abs(self.state_space.S).sum(axis=0).max()) * duration + self.state_space.update_epoch(current) - self.state_space.update_epoch(epochs[-1]) + return bool(norm > bound) + + @staticmethod + def _closed_form_steps(epochs: List[Epoch], start_time: float) -> List[Tuple[Epoch, float]]: + """ + The epochs of ``_get_epochs_until_unbounded`` and the times the closed form spends in them under an + exponential, up to the later of ``start_time`` and the start of the last epoch. + + :param epochs: The epochs. + :param start_time: The non-negative start time. + :return: The epochs and the times. + """ + horizon = max(start_time, epochs[-1].start_time) + + return [(epoch, min(epoch.end_time, horizon) - epoch.start_time) for epoch in epochs] + + def _grid_steps(self, start_time: float, end_times: np.ndarray) -> Tuple[List[Tuple[Epoch, float]], int]: + """ + The actions and the number of distinct dense exponentials of a propagation from ``start_time`` through the + sorted finite ``end_times`` after it, as ``_accumulate_windowed`` and ``_mean_occupation_grid`` take them: one + action per step of a run of equal steps (``_StepRuns``) and per remainder to the end of an epoch, and one dense + exponential per epoch and step length. + + :param start_time: The non-negative start time. + :param end_times: The sorted finite end times. + :return: The epochs and the times of the actions, and the number of dense exponentials. + """ + times = end_times[end_times > start_time] + steps, dense, x, i = [], set(), start_time, 0 + for epoch in self.demography.epochs: + if i == len(times): + break + if epoch.end_time <= x: + continue - return norm > _DENSE_EXPM_STEP_NORM * dim ** 3 + j = int(np.searchsorted(times, epoch.end_time, side='right')) + runs, x = _StepRuns.split(x, times[i:j]) + if j < len(times): + runs.append((epoch.end_time - x, 1)) + x = epoch.end_time + steps += [(epoch, step) for step, count in runs if step > 0 for _ in range(count)] + dense.update((epoch.start_time, step) for step, _ in runs if step > 0) + i = j - def _flattening_applies(self, k: int) -> bool: + return steps, len(dense) + + def _flattening_applies(self, k: int, rewards: Sequence[Reward] = None) -> bool: """ Whether the block-counting state space can be flattened onto the lineage-counting state space for this - moment: the first moment of the standard coalescent on a single population and a single locus. Takes - precedence over the closed form and the batched occupation. + moment of the standard coalescent on a single population and a single locus: the first moment of any reward, + and the second moment of two rewards that are each an unfolded or folded SFS bin with polymorphic blocks. + Takes precedence over the closed form and the batched occupation. + + :param k: The order of the moment. + :param rewards: The rewards, required for the second moment. + :return: Whether to flatten. """ - return ( + if not ( Settings.flatten_block_counting and - k == 1 and isinstance(self.state_space, BlockCountingStateSpace) and isinstance(self.state_space.model, StandardCoalescent) and self.lineage_config.n_pops == 1 and self.locus_config.n == 1 + ): + return False + + if k == 1: + return True + + return k == 2 and rewards is not None and len(rewards) == 2 and all( + self._sfs_reward_block_sizes(r, self.lineage_config.n) is not None for r in rewards ) def _transient_block(self, idx_t: np.ndarray, sparse: bool = False) -> 'sp.spmatrix | np.ndarray': @@ -1863,7 +2036,9 @@ def _mean_occupation_grid(self, end_times: Sequence[float], start_time: float = """ Expected time spent in each state of ``E`` over ``[start_time, t]`` for each end time ``t``, threaded across epochs with the augmented generator ``[[S, I], [0, 0]]`` of ``PhaseTypeDistribution.moment``, for the batched - mean accumulation of a spectrum. A positive start time subtracts the occupation up to it. + mean accumulation of a spectrum. Within an epoch, the end times are taken as runs of equal steps + (``_StepRuns``), with one dense exponential per step length or one interval action per run. A positive start + time subtracts the occupation up to it. :param end_times: Times at which to evaluate the occupation. A NaN end time gives a NaN occupation. :param start_time: Time from which to accumulate. By default, the start time of the distribution. @@ -1915,45 +2090,63 @@ def _mean_occupation_grid(self, end_times: Sequence[float], start_time: float = self.state_space.update_epoch(epoch) n = self.state_space.k - # the occupation integral is read off the augmented generator ``[[S, I], [0, 0]]``; for large state spaces - # apply its (transposed) matrix-exponential action instead of forming the dense 2n x 2n exponential - use_action = 2 * n >= Settings.expm_action_min_dim + # the occupation integral is read off the augmented generator ``[[S, I], [0, 0]]``, by its (transposed) + # matrix-exponential action or its dense exponentials + use_action = not self._dense_expm_is_faster(2 * n, 2 * n, 1, *self._grid_steps(0.0, t_sorted)) + + p = np.concatenate([np.asarray(self.state_space.alpha, dtype=float), np.zeros(n)]) + x, i = 0.0, 0 + out = np.zeros((len(t_sorted), n)) - def advance(p, m, tau) -> 'Tuple[np.ndarray, np.ndarray]': - if tau <= 0: - return p, m + while True: + self._check_numerical_stability(self.state_space.S, i_epoch) S = self.state_space.S + if use_action: - aug = sp.bmat([ + augT = sp.bmat([ [sp.csc_matrix(S), sp.identity(n, format='csc')], [None, sp.csc_matrix((n, n))], - ], format='csc') - w = Backend.expm_multiply( - (aug * tau).T.tocsc(), np.concatenate([p, m]), action=spla.expm_multiply, blocks=2 - ) + ], format='csc').T.tocsc() + + def advance(v: np.ndarray, tau: float) -> np.ndarray: + """``v`` advanced by ``tau``.""" + return Backend.expm_multiply(augT * tau, v, action=spla.expm_multiply, blocks=2) else: aug = np.zeros((2 * n, 2 * n)) aug[:n, :n] = np.asarray(S.todense()) if sp.issparse(S) else np.asarray(S) aug[:n, n:] = np.eye(n) - w = np.concatenate([p, m]) @ self._block_expm((aug * tau)[None], n, [False, True])[0] - return w[:n], w[n:] + propagators = _Propagators(lambda tau: self._block_expm((aug * tau)[None], n, [False, True])[0]) + + def advance(v: np.ndarray, tau: float) -> np.ndarray: + """``v`` advanced by ``tau``.""" + return v @ propagators(tau) + + # the end times up to the end of the epoch, as runs of equal steps + j = int(np.searchsorted(t_sorted, epoch.end_time, side='right')) + runs, x_end = _StepRuns.split(x, t_sorted[i:j]) + + for step, count in runs: + if step <= 0: + out[i:i + count] = p[n:] + elif use_action and count > 1: + P = Backend.expm_multiply_interval( + augT, p, step * count, count, interval=_SCIPY_EXPM.compute_action_interval, advance=advance + ) + out[i:i + count], p = P[:, n:], P[-1] + else: + for c in range(i, i + count): + p = advance(p, step) + out[c] = p[n:] + i += count - p = np.asarray(self.state_space.alpha, dtype=float) - m = np.zeros(n) - u_prev = 0.0 - out = np.zeros((len(t_sorted), n)) + if i == len(t_sorted): + break - for idx, u in enumerate(t_sorted): - while u > epoch.end_time: - self._check_numerical_stability(self.state_space.S, i_epoch) - p, m = advance(p, m, epoch.end_time - u_prev) - u_prev = epoch.end_time - i_epoch, epoch = next(epochs) - self.state_space.update_epoch(epoch) - self._check_numerical_stability(self.state_space.S, i_epoch) - p, m = advance(p, m, u - u_prev) - out[idx] = m - u_prev = u + if epoch.end_time > x_end: + p = advance(p, epoch.end_time - x_end) + x = epoch.end_time + i_epoch, epoch = next(epochs) + self.state_space.update_epoch(epoch) return out[np.argsort(order)] @@ -2019,11 +2212,8 @@ def _occupation_times( tau = upper - epoch.start_time - # the dense exponential where the step is stiff enough to be the cheaper one, see ``_DENSE_EXPM_STEP_NORM`` - use_action = not ( - 2 * nt < Settings.expm_action_min_dim and - float(abs(S).sum(axis=0).max()) * tau + _ACTION_STEP_NORM_OFFSET > - _DENSE_EXPM_STEP_NORM * (2 * nt) ** 3 + use_action = not self._dense_expm_is_faster( + 2 * nt, 2 * nt, 1, [(epoch, tau)], taped=tape is not None ) steps.append((epoch, tau, S, use_action)) @@ -2083,57 +2273,213 @@ def augmented(S, tau) -> np.ndarray: return m, idx_t - def _two_point_occupation(self) -> Optional[Tuple[np.ndarray, 'Callable', np.ndarray]]: + @staticmethod + def _forward_operator(S: sp.csr_matrix, R: np.ndarray, rewarded: np.ndarray, cu: float, cw: float) -> sp.csr_matrix: + """ + The transpose of the generator of the forward pass of ``_bin_second_moments`` for the column action, of + ``2 m + 1`` blocks of the size of ``S``: ``S`` on the diagonal blocks of ``p`` and each ``u_a``, ``diag(r_a) / + cu`` from ``p`` to ``u_a`` and ``diag(c) / cw`` from ``u_a`` to ``w_a``, with ``c`` the indicator of the states + where some reward is non-zero, so that the vector is stationary once the rewards are collected. + + :param S: The rate matrix. + :param R: The reward vectors ``r_a`` as columns. + :param rewarded: The indicator ``c``. + :param cu: The factor ``u_a`` is stored against. + :param cw: The factor of ``w_a`` relative to ``u_a``. + :return: The transposed generator. + """ + n, m = R.shape + St = S.T.tocsr() + states = np.arange(n) + rewarded = np.flatnonzero(rewarded) + bins, bins_rewarded = np.repeat(np.arange(m), n), np.repeat(np.arange(m), rewarded.size) + + coupling = sp.csr_matrix(( + np.concatenate([R.T.ravel() / cu, np.full(m * rewarded.size, 1.0 / cw)]), + (np.concatenate([(1 + bins) * n + np.tile(states, m), (1 + m + bins_rewarded) * n + np.tile(rewarded, m)]), + np.concatenate([np.tile(states, m), (1 + bins_rewarded) * n + np.tile(rewarded, m)])) + ), shape=((2 * m + 1) * n,) * 2) + + return (sp.block_diag([St] * (m + 1) + [sp.csr_matrix((m * n, m * n))], format='csr') + coupling).tocsr() + + @staticmethod + def _forward_van_loan(S: np.ndarray, r: np.ndarray, rewarded: np.ndarray, cu: float, cw: float) -> np.ndarray: """ - Factors of the two-point occupation matrix ``K = diag(m) (-T)^{-1}`` of ``PhaseTypeDistribution.moment``, - defined for a single epoch without an accumulation window, so that ``R^T K R = (m * R)^T solve(R)`` for a - stack of reward columns ``R``. ``K`` is never formed, and the LU of ``-T`` is sparse from - :attr:`Settings.closed_form_sparse_min_states ` - transient states on. Other cases return ``None`` and callers evaluate per pair. + The dense generator of the forward pass of ``_bin_second_moments`` restricted to one bin, the blocks of ``p``, + ``u_a`` and ``w_a`` of ``_forward_operator`` untransposed. - :return: ``(m, solve, idx_t)`` with ``m = alpha (-T)^{-1}`` and ``solve`` applying ``(-T)^{-1}``, over the - transient states ``idx_t``, or ``None`` when not applicable (caller falls back). + :param S: The rate matrix. + :param r: The reward vector ``r_a``. + :param rewarded: The indicator ``c`` of ``_forward_operator``. + :param cu: The factor ``u_a`` is stored against. + :param cw: The factor of ``w_a`` relative to ``u_a``. + :return: The matrix of three blocks in each dimension. """ - if not (Settings.closed_form_last_epoch and self._tree_height.end_time is None): - return None + n = S.shape[0] + V = np.zeros((3 * n, 3 * n)) + V[:n, :n] = S + V[n:2 * n, n:2 * n] = S + V[:n, n:2 * n] = np.diag(r / cu) + V[n:2 * n, 2 * n:] = np.diag(rewarded / cw) - if self._tree_height.start_time > 0: - # the two-point occupation is a double integral over ``s < u``; the windowed (start_time > 0) version is - # not the full one minus a box, so the batched covariance cannot subtract it the way the mean does. Fall - # back to the per-pair path, which accumulates each pair over ``[start_time, absorption]`` directly. - self._logger.debug( - "two-point occupation: start_time=%.3g > 0; using per-pair covariance (windowed two-point occupation " - "not batched)", self._tree_height.start_time - ) - return None + return V - epochs = self._get_epochs_until_unbounded(2) + def _bin_second_moments_flattened( + self, + rewards: Sequence[Reward], + start_time: float = None, + end_time: float = None + ) -> Tuple[np.ndarray, np.ndarray]: + """ + The means and the cross-moments of ``_bin_second_moments`` for SFS bin rewards flattened onto the + lineage-counting state space, from the occupation and the cross-moments of ``_level_cross_moments``, the + latter summed over the block sizes of each bin. - # only the single-epoch closed form is used; the multi-epoch ODE is stiffness-fragile (see docstring) - if len(epochs) > 1: - self._logger.debug( - "two-point occupation: %d epochs; using per-pair matrix-exponential (multi-epoch closed form " - "disabled)", len(epochs) - ) - return None + :param rewards: The bin rewards, each flattened as in ``_flattening_applies``. + :param start_time: The start time. By default, that of the distribution. + :param end_time: The end time. By default, that of the distribution, or absorption. + :return: The means and the cross-moments. + """ + n = self.lineage_config.n + start, end = self._resolve_window(start_time, end_time) + self._logger.debug("second moments of %d SFS bins flattened onto the lineage-counting state space", len(rewards)) - if not self._absorption_certain_in_last_epoch(2): - return None + # the block sizes counted by each bin + F = np.zeros((len(rewards), n - 1)) + for a, r in enumerate(rewards): + F[a, np.asarray(self._sfs_reward_block_sizes(r, n)) - 1] = 1.0 - self.state_space.update_epoch(epochs[-1]) - self._check_numerical_stability(self.state_space.S, 0) - absorbing = self.state_space.absorbing - # only the states that can carry mass; see ``_alpha_support`` - idx_t = np.where(~absorbing & self._alpha_support(2))[0] + occupation, cross = (x[0] for x in self._tree_height._level_cross_moments((end,), start)) + mean = occupation @ np.column_stack([self._flattened_weights(r) for r in rewards])[:n - 1] - sparse = self._solve_sparse(len(idx_t)) - neg_t = -self._transient_block(idx_t, sparse=sparse) - solve = self._lu_solver(neg_t, sparse) - m = solve.T(np.asarray(self.state_space.alpha, dtype=float)[idx_t]) + return mean, F @ (cross + cross.T) @ F.T + + @BlasThreadLimit() + def _bin_second_moments( + self, + rewards: Sequence[Reward], + start_time: float = None, + end_time: float = None + ) -> Tuple[np.ndarray, np.ndarray]: + """ + The means ``E[R_a]`` and the second cross-moments ``E[R_a R_b]`` of the rewards over the accumulation window of + the distribution, by the forward pass of ``PhaseTypeDistribution.moment`` shared by all rewards. The finite + epochs take the stacked sparse action, or one dense exponential per reward where ``_dense_expm_is_faster``, and + the unbounded last epoch is closed with one factorization of ``-T``. + + :param rewards: The rewards. + :param start_time: The start time. By default, that of the distribution. + :param end_time: The end time. By default, that of the distribution, or absorption. + :return: The means, of shape ``(m,)``, and the cross-moments, of shape ``(m, m)``, for ``m`` rewards. + :raises ValueError: If a reward is not accumulable, see ``Reward._check_accumulable``. + :raises ModelError: If a moment is not a number. + """ + if rewards and all(self._flattening_applies(2, (r, r)) for r in rewards): + return self._bin_second_moments_flattened(rewards, start_time, end_time) + + ss = self.state_space + start, end = self._resolve_window(start_time, end_time) + closed = bool(np.isinf(end) and Settings.closed_form_last_epoch and self._absorption_certain_in_last_epoch(2)) + + if closed: + epochs = self._get_epochs_until_unbounded(2) + self._check_demography_conditioning(epochs) + finite = list(enumerate(epochs[:-1])) + steps = self._closed_form_steps(epochs, start) + else: + if np.isinf(end): + end = self._get_time_to_absorption() + finite = [] + for i_epoch, epoch in enumerate(self.demography.epochs): + finite.append((i_epoch, epoch)) + if epoch.end_time >= end: + break + ss.update_epoch(finite[0][1]) + steps = [(epoch, min(epoch.end_time, end) - epoch.start_time) for _, epoch in finite] + + n = ss.k + vectors = [np.asarray(r._get(ss), dtype=float) for r in rewards] + Reward._check_accumulable(ss, rewards, vectors) + R = np.column_stack(vectors) + m = R.shape[1] + use_action = not self._dense_expm_is_faster((2 * m + 1) * n, 3 * n, m, steps) + scale = self._reward_scale(list(R.T)) + rewarded = (R != 0).any(axis=1).astype(float) self._logger.debug( - "two-point occupation: single-epoch closed form diag(m)(-T)^-1, %s LU (n_t=%d)", - 'sparse' if sparse else 'dense', len(idx_t) + "second moments of %d rewards over [%.3g, %.3g]: forward pass by the %s, %d finite epoch(s)%s", m, start, + end, "stacked sparse action" if use_action else "dense exponential per reward", len(finite), + ", closed last epoch" if closed else "" ) - return m, solve, idx_t + # x = [p, u_1, ..., u_m, w_1, ..., w_m], with u_a stored divided by cu and w_a by cu * cw + x = np.zeros((2 * m + 1) * n) + x[:n] = ss.alpha + cu = cw = 1.0 + + with np.errstate(over='ignore', divide='ignore', invalid='ignore', under='ignore'): + for i_epoch, epoch in finite: + ss.update_epoch(epoch) + self._check_numerical_stability(ss.S, i_epoch) + t0, t1 = epoch.start_time, epoch.end_time if closed else min(epoch.end_time, end) + + if t0 < start: + x[:n] = self._propagate_plain(x[:n], min(t1, start) - t0, use_action) + t0 = start + + if t1 <= t0: + continue + + # balance each epoch on its own rates, an exact diagonal similarity (see ``_rebase``) + cu_new = self._get_regularization_factor(ss.S, t1 - t0, scale) + cw_new = self._get_regularization_factor(ss.S, t1 - t0) + x[n:(m + 1) * n] *= cu / cu_new + x[(m + 1) * n:] *= cu * cw / (cu_new * cw_new) + cu, cw = cu_new, cw_new + + if use_action: + A = self._forward_operator(sp.csr_matrix(ss.S), R, rewarded, cu, cw) * (t1 - t0) + x = Backend.expm_multiply(A, x, blocks=2 * m + 1, depth=3) + continue + + S = self._dense_rate_matrix() + exps = self._block_expms([ + lambda a=a: self._forward_van_loan(S, R[:, a], rewarded, cu, cw) * (t1 - t0) for a in range(m) + ], n, [False, False, True]) + p, U, W = x[:n], x[n:(m + 1) * n].reshape(m, n), x[(m + 1) * n:].reshape(m, n) + y = np.empty_like(x) + for a, E in enumerate(exps): + if a == 0: + y[:n] = p @ E[:n, :n] + y[(1 + a) * n:(2 + a) * n] = p @ E[:n, n:2 * n] + U[a] @ E[n:2 * n, n:2 * n] + y[(1 + m + a) * n:(2 + m + a) * n] = p @ E[:n, 2 * n:] + U[a] @ E[n:2 * n, 2 * n:] + W[a] + x = y + + p = x[:n] + U = x[n:(m + 1) * n].reshape(m, n) * cu + W = x[(m + 1) * n:].reshape(m, n) * (cu * cw) + mean = U.sum(axis=1) + ordered = W @ R # [a, b]: reward a collected before reward b + + if closed: + # w_a(inf) r_b = w_a(t_L) r_b + (u_a(t_L) + m_L * r_a) (-T)^{-1} r_b with m_L = p(t_L) (-T)^{-1} + last = epochs[-1] + ss.update_epoch(last) + self._check_numerical_stability(ss.S, len(epochs) - 1) + if start > last.start_time: + p = self._propagate_plain(p, start - last.start_time, use_action) + + idx_t = np.where(~ss.absorbing & self._alpha_support(2))[0] + sparse = self._solve_sparse(len(idx_t)) + solve = self._last_epoch_solver(id(ss), len(epochs), idx_t.astype(np.intp).tobytes(), sparse) + R_t = R[idx_t] + m_last = solve.T(p[idx_t]) + mean = mean + m_last @ R_t + ordered = ordered + (U[:, idx_t] + m_last * R_t.T) @ solve(R_t) + + if np.isnan(mean).any() or np.isnan(ordered).any(): + raise ModelError( + "NaN value encountered when computing moment. This is likely due to an ill-conditioned rate matrix." + ) + + return mean, ordered + ordered.T diff --git a/phasegen/distributions/_uniformization.py b/phasegen/distributions/_uniformization.py new file mode 100644 index 00000000..5cbe0e07 --- /dev/null +++ b/phasegen/distributions/_uniformization.py @@ -0,0 +1,180 @@ +"""The exponential of a Metzler generator and its integral, applied to a row vector by uniformization.""" +from functools import cached_property +from typing import Tuple + +import numpy as np +import scipy.sparse as sp +from numba import njit +from scipy.special import gammaln + +#: Largest product of the uniformization rate and the step of one chunk, below which the first Poisson weight stays +#: within the double-precision range. +_MAX_CHUNK = 500.0 + +#: Absolute truncation floor of the Poisson series relative to the 1-norm of the propagated vector. +_FLOOR = 1e-46 + +#: Floor relative to the 1-norm of the propagated vector above which the entries seed the states a step of more than +#: one chunk is taken over. +_SUPPORT_FLOOR = 1e-16 + +#: Factor on the largest exit rate among the states reachable from the entries above ``_SUPPORT_FLOOR``, up to which +#: the nonzero entries below that floor also seed the states a step of more than one chunk is taken over. +_SUPPORT_RATE_RATIO = 10.0 + + +class _Uniformization: + r""" + The row vectors :math:`\mathbf{v} e^{\mathbf{A} \tau}` and :math:`\mathbf{v} \int_0^\tau e^{\mathbf{A} s}\, + \mathrm{d}s` for a sub-generator :math:`\mathbf{A}` with non-negative off-diagonal entries and non-positive row + sums, and a non-negative :math:`\mathbf{v}`. With :math:`\lambda` the largest exit rate :math:`-A_{ii}`, + :math:`\mathbf{P} = \mathbf{I} + \mathbf{A} / \lambda` is non-negative and substochastic, and + + .. math:: + + e^{\mathbf{A} \tau} = \sum_{k \ge 0} w_k \mathbf{P}^k, \qquad + \int_0^\tau e^{\mathbf{A} s}\, \mathrm{d}s = \frac{1}{\lambda} \sum_{k \ge 0} Q_k \mathbf{P}^k, + + with :math:`w_k` the Poisson probabilities of :math:`k` at mean :math:`\lambda \tau` and :math:`Q_k = \sum_{j > k} + w_j` their upper tails. The series is truncated where the remaining Poisson mass falls below ``_FLOOR`` times the + 1-norm of the vector. A step with :math:`\lambda \tau` above ``_MAX_CHUNK`` is taken in equal chunks over the + states ``_support`` returns, at their largest exit rate, and restarted on the remaining states whenever these + shrink (adaptive uniformization). + """ + + def __init__(self, A) -> None: + """ + :param A: The sub-generator, dense or sparse. + """ + #: The sub-generator + self.A: sp.csr_matrix = sp.csr_matrix(A) + + #: The exit rates + self.exits: np.ndarray = np.maximum(-self.A.diagonal(), 0.0) + + #: The uniformization rate + self.lam: float = float(self.exits.max()) if self.A.shape[0] else 0.0 + + @cached_property + def _targets(self) -> sp.csr_matrix: + """ + The transposed sparsity pattern of the sub-generator, whose product with a mask of states marks their targets. + """ + return (self.A != 0).T.tocsr() + + def _support(self, v: np.ndarray) -> np.ndarray: + """ + The states reachable from the entries of ``v`` above ``_SUPPORT_FLOOR`` times its 1-norm, and from the nonzero + ones exiting at most ``_SUPPORT_RATE_RATIO`` times as fast as the states reachable from those. + + :param v: The non-negative, nonzero row vector. + :return: The mask of the states. + """ + def reachable(seeds: np.ndarray) -> np.ndarray: + reach = frontier = seeds + while frontier.any(): + frontier = (self._targets @ frontier) & ~reach + reach = reach | frontier + return reach + + strong = v > _SUPPORT_FLOOR * v.sum() + slow = self.exits <= _SUPPORT_RATE_RATIO * self.exits[reachable(strong)].max() + + return reachable(strong | ((v > 0) & slow)) + + @staticmethod + def _weights(lt: float) -> Tuple[np.ndarray, np.ndarray]: + """ + The Poisson probabilities at mean ``lt`` up to the truncation, normalized to sum to one, and their upper + tails. + + :param lt: The mean. + :return: The probabilities and the upper tails. + """ + # beyond the mean, the tail after k is at most w_{k + 1} / (1 - lt / (k + 2)) + log_floor = np.log(_FLOOR) + k = int(np.ceil(lt)) + 1 + while -lt + (k + 1) * np.log(lt) - gammaln(k + 2) - np.log1p(-lt / (k + 2)) > log_floor: + k += max(1, int(np.sqrt(lt)) // 4) + + ks = np.arange(k + 1) + w = np.exp(-lt + ks * np.log(lt) - gammaln(ks + 1)) + w /= w.sum() + Q = np.append(np.cumsum(w[:0:-1])[::-1], 0.0) + + return w, Q + + def propagate(self, v: np.ndarray, tau: float) -> Tuple[np.ndarray, np.ndarray]: + """ + :param v: The non-negative row vector. + :param tau: The non-negative time. + :return: The vector advanced by ``tau`` and its integral over ``[0, tau]``. + """ + v = np.asarray(v, dtype=float) + + if self.lam == 0 or tau == 0 or not v.any(): + return v.copy(), v * tau + + restrict = self.lam * tau > _MAX_CHUNK + floor = _FLOOR * float(v.sum()) / max(1.0, tau) + u, occ = v.copy(), np.zeros_like(v) + + while tau > 0 and u.any(): + A, lam, keep = self.A, self.lam, slice(None) + if restrict: + keep = np.flatnonzero(self._support(u)) + A, lam = A[keep][:, keep], float(self.exits[keep].max()) + + x, y, u = u[keep], occ[keep], np.zeros_like(v) + if lam == 0: + u[keep], occ[keep] = x, y + x * tau + break + + n = A.shape[0] + chunks = max(1, int(np.ceil(lam * tau / _MAX_CHUNK))) + h = tau / chunks + w, Q = self._weights(lam * h) + Pt = (sp.identity(n, format='csr') + A / lam).T.tocsr() + + for done in range(1, chunks + 1): + x = _series(Pt.indptr, Pt.indices, Pt.data, x, w, Q / lam, floor, y) + u[keep] = x + if not x.any() or restrict and done < chunks and self._support(u).sum() < n: + break + + u[keep], occ[keep] = x, y + tau = (chunks - done) * h + + return u, occ + + +@njit(cache=True) +def _series(indptr, indices, data, v, w, q, floor, occ): + """ + ``sum_k w_k x_k`` with ``x_k = P^k v`` for the CSR matrix ``P``, adding ``sum_k q_k x_k`` to ``occ``, until the + weights end or the 1-norm of ``x_k`` falls to ``floor``. + """ + n = v.size + x, y = v.copy(), np.empty(n) + u = w[0] * v + for i in range(n): + occ[i] += q[0] * v[i] + + for k in range(1, w.size): + total = 0.0 + for i in range(n): + acc = 0.0 + for p in range(indptr[i], indptr[i + 1]): + acc += data[p] * x[indices[p]] + y[i] = acc + total += acc + x, y = y, x + + for i in range(n): + u[i] += w[k] * x[i] + occ[i] += q[k] * x[i] + + if total <= floor: + break + + return u diff --git a/phasegen/distributions/base.py b/phasegen/distributions/base.py index 78259ff8..9813f092 100644 --- a/phasegen/distributions/base.py +++ b/phasegen/distributions/base.py @@ -1,7 +1,6 @@ """Distribution base classes and marginal (per-deme / per-locus) views.""" import logging -import warnings from abc import ABC, abstractmethod from collections.abc import Mapping from ..caching import cached_property @@ -637,8 +636,8 @@ def _warn_if_join_off(self, xs: np.ndarray, cdf: np.ndarray) -> None: d = self._distribution d._logger.warning( "%s: the expansion departs from the de Hoog CDF by %.2e at %.4g (bar %.0e). Its window ends at %.4g " - "and leaves out a mass of %.2e, which it folds back into the body. Settings.dehoog_tail_quantile = 0 " - "evaluates the CDF by the de Hoog inversion throughout.", d._titled('COS CDF (window)'), error, x_cut, + "and leaves out a mass of %.2e, which it folds back into the body, so the CDF, quantiles and density " + "below the cut may be biased.", d._titled('COS CDF (window)'), error, x_cut, self._cos_join_tol, xs[-1], 1.0 - self._cdf_point(float(xs[-1])) ) @@ -848,10 +847,10 @@ def __call__(self, q) -> 'np.ndarray | float': :param q: Probability level or array of levels :math:`q \in [0, 1]`. :return: The quantiles, of the same shape as ``q``. :raises NotImplementedError: If the coalescent has a bounded accumulation window. - :raises ValueError: If any ``q`` lies outside :math:`[0, 1]`. + :raises ValueError: If any ``q`` is NaN or lies outside :math:`[0, 1]`. """ qa = np.atleast_1d(np.asarray(q, dtype=float)) - if np.any((qa < 0) | (qa > 1)): + if not np.all((qa >= 0) & (qa <= 1)): raise ValueError("Quantile must be between 0 and 1.") if Settings.check_inversions and np.any(qa > _QUANTILE_TAIL_LEVEL): @@ -860,11 +859,9 @@ def __call__(self, q) -> 'np.ndarray | float': "approximate.", self._distribution._titled('quantile'), _QUANTILE_TAIL_LEVEL ) - # NaN levels are passed through, the grid taking the others - valid = ~np.isnan(qa) - out = np.full_like(qa, np.nan) - if valid.any(): - out[valid] = self._interp_quantile(qa[valid], *self._cdf_grid(q_max=float(qa[valid].max()))) + out = np.empty_like(qa) + if qa.size: + out[...] = self._interp_quantile(qa.ravel(), *self._cdf_grid(q_max=float(qa.max()))).reshape(qa.shape) return out if np.ndim(q) > 0 else float(out[0]) @@ -1313,6 +1310,18 @@ def quantile(self) -> QuantileFunction: "(a bivariate joint quantile is not well-defined; use a marginal/conditional).") return self._function('quantile', self._quantile_function) + def plot_pdf(self, *args, **kwargs) -> 'plt.Axes': + """ + Plot the PDF curve. + + .. deprecated:: 2.0.0 + Use ``pdf.plot()``. ``plot_pdf`` will be removed in a future release. + """ + logger.getChild(type(self).__name__).warning( + "plot_pdf() is deprecated since 2.0.0 and will be removed in a future release, use .pdf.plot() instead." + ) + return self.pdf.plot(*args, **kwargs) + def plot_cdf(self, *args, **kwargs) -> 'plt.Axes': """ Plot the CDF curve. @@ -1320,8 +1329,9 @@ def plot_cdf(self, *args, **kwargs) -> 'plt.Axes': .. deprecated:: 2.0.0 Use ``cdf.plot()``. ``plot_cdf`` will be removed in a future release. """ - warnings.warn("plot_cdf() is deprecated since 2.0.0 and will be removed in a future release; " - "use .cdf.plot() instead.", DeprecationWarning, stacklevel=2) + logger.getChild(type(self).__name__).warning( + "plot_cdf() is deprecated since 2.0.0 and will be removed in a future release, use .cdf.plot() instead." + ) return self.cdf.plot(*args, **kwargs) def _warn_if_negative(self, values: np.ndarray, label: str, rtol: float = 1e-3) -> np.ndarray: diff --git a/phasegen/distributions/coalescent.py b/phasegen/distributions/coalescent.py index f1a08a98..0c79bcba 100644 --- a/phasegen/distributions/coalescent.py +++ b/phasegen/distributions/coalescent.py @@ -518,7 +518,9 @@ class Coalescent(AbstractCoalescent, Serializable): """ Coalescent process of a sample of lineages under a demography, a coalescent model and a locus configuration. Its tree height, total branch length, site-frequency spectra and any other accumulated reward are phase-type - distributed. + distributed. A :class:`~phasegen.distributions.Coalescent` is not thread-safe: its statistics share state spaces + that switch between epochs, so concurrent threads each need their own + :class:`~phasegen.distributions.Coalescent`, or processes are used. The following example computes the mean tree height and site-frequency spectrum of five lineages in a population whose size drops to 0.2 at time 0.5. @@ -954,8 +956,7 @@ def gradient(self, k: int = 1, rewards: Sequence[Reward] = None, center: bool = :return: The derivatives. :raises NotImplementedError: If the moment is accumulated over a time window. :raises ValueError: If ``k`` is not a positive integer, if the number of rewards differs from ``k``, if a - reward is non-zero on an absorbing state, if absorption is not certain in the last epoch, or if the - generator is not affine in the rates. + reward is non-zero on an absorbing state, or if absorption is not certain in the last epoch. :raises TypeError: If ``k`` is not a number or an entry of ``rewards`` is not a :class:`~phasegen.rewards.Reward`. """ diff --git a/phasegen/distributions/empirical.py b/phasegen/distributions/empirical.py index 998d3e47..0f178e6a 100644 --- a/phasegen/distributions/empirical.py +++ b/phasegen/distributions/empirical.py @@ -28,8 +28,8 @@ JointSFSDistribution, TwoLocusSFSDistribution from .mutation_configs import MutationConfig, MutationLayout, _DefaultLayoutMixin from ._common import ( - _descendant_config, _frequency_class, _make_hashable, _polymorphic_class, _sqrt_spectrum, _validate_order, - _validate_reward, _validate_reward_count, _validate_rewards, _validate_start_time + _descendant_config, _frequency_class, _make_hashable, _n_samples, _polymorphic_class, _sqrt_spectrum, + _validate_order, _validate_reward, _validate_reward_count, _validate_rewards, _validate_start_time ) from .coalescent import AbstractCoalescent, Coalescent from .phase_type import PhaseTypeDistribution @@ -1776,7 +1776,7 @@ def mutation_layout(self, loci: Sequence[int] = (0, 1), folded: bool = False) -> return TwoLocusSFSDistribution._layout_of(lineages, locus_config, loci, folded) cdf = pdf = quantile = property(TwoLocusSFSDistribution._no_univariate_distribution) - plot_cdf = bin = TwoLocusSFSDistribution._no_univariate_distribution + plot_pdf = plot_cdf = bin = TwoLocusSFSDistribution._no_univariate_distribution def _no_marginals(self, *args, **kwargs) -> NoReturn: """ @@ -2153,17 +2153,17 @@ def __init__( with np.errstate(divide='ignore', invalid='ignore'): #: Covariance matrix for the demes, of the per-deme samples summed over loci, ``None`` unless the samples #: resolve the demes - self.pops_cov: np.ndarray | None = np.cov(over_loci, bias=True) if resolves_demes else None + self.pops_cov: np.ndarray | None = np.atleast_2d(np.cov(over_loci, bias=True)) if resolves_demes else None #: Correlation matrix for the demes, of the per-deme samples summed over loci, ``None`` unless the samples #: resolve the demes - self.pops_corr: np.ndarray | None = np.corrcoef(over_loci) if resolves_demes else None + self.pops_corr: np.ndarray | None = np.atleast_2d(np.corrcoef(over_loci)) if resolves_demes else None #: Correlation matrix for the loci - self.loci_corr: np.ndarray = np.corrcoef(over_demes) + self.loci_corr: np.ndarray = np.atleast_2d(np.corrcoef(over_demes)) #: Covariance matrix for the loci - self.loci_cov: np.ndarray = np.cov(over_demes, bias=True) + self.loci_cov: np.ndarray = np.atleast_2d(np.cov(over_demes, bias=True)) def _touch(self, t: np.ndarray) -> None: """ @@ -4386,8 +4386,9 @@ def __init__( require. :param simulate_mutations: Whether to simulate mutations. :param seed: Non-negative integer random seed. ``None`` draws one from fresh entropy. - :raises ValueError: If ``model`` is a Beta coalescent whose alpha exceeds 1.991, the largest that msprime - accepts, or if ``simulate_mutations`` is set without a ``mutation_rate``. + :raises ValueError: If ``model`` is a Beta coalescent with alpha above 1.991 or a Beta or Dirac coalescent + with ``scale_time=False``, neither of which ``msprime`` supports, if ``num_replicates`` is not a + positive integer, or if ``simulate_mutations`` is set without ``mutation_rate``. """ super().__init__( n=n, @@ -4403,6 +4404,12 @@ def __init__( f"msprime accepts Beta coalescents with alpha up to {_MSPRIME_BETA_ALPHA_MAX}, got {self.model.alpha}." ) + if isinstance(self.model, (BetaCoalescent, DiracCoalescent)) and not self.model.scale_time: + raise ValueError(f"msprime simulates {type(self.model).__name__} only on its own time scale, which is that " + f"of scale_time=True.") + + num_replicates = _n_samples(num_replicates, minimum=1) + if simulate_mutations and mutation_rate is None: raise ValueError("Simulating mutations requires a mutation rate.") @@ -5394,7 +5401,7 @@ def __init__( :param n_samples: Number of trajectories to simulate per statistic. :param seed: Non-negative integer seed, or a :class:`numpy.random.Generator` from which one is drawn at construction. ``None`` draws one from fresh entropy. - :raises ValueError: If ``seed`` is a negative integer. + :raises ValueError: If ``seed`` is a negative integer or ``n_samples`` is not a positive integer. """ if seed is None: seed = np.random.default_rng() @@ -5415,7 +5422,7 @@ def __init__( self._coalescent: Optional[Coalescent] = coalescent #: Number of trajectories sampled per statistic. - self.n_samples: int = n_samples + self.n_samples: int = _n_samples(n_samples, minimum=1) #: Random seed, drawn at construction if none is given. self.seed: int = int(seed.integers(2 ** 63)) if isinstance(seed, np.random.Generator) else seed diff --git a/phasegen/distributions/mutation_configs.py b/phasegen/distributions/mutation_configs.py index 7cd0a82c..3371221d 100644 --- a/phasegen/distributions/mutation_configs.py +++ b/phasegen/distributions/mutation_configs.py @@ -12,17 +12,15 @@ import scipy.sparse as sp from ..demography import Demography -from ..expm import Backend from ..initial import InitialDistribution from ..lineage import LineageConfig from ..locus import LocusConfig from ..rewards import CombinedReward, Reward, SumReward, TreeHeightReward, UnitReward from ..settings import Settings from ..state_space import StateSpace +from ._uniformization import _Uniformization from .phase_type import PhaseTypeDistribution, TreeHeightDistribution -expm = Backend.expm - #: Largest number of floats held by the single-epoch lattice memo of one distribution before it is cleared. _LATTICE_MEMO_MAX_FLOATS = 2 ** 25 @@ -608,11 +606,11 @@ def get_mutation_config( - In a single epoch, the resolvent is one dense inverse. It is cached for the most recent layout and :math:`\theta`, with the row vectors :math:`\mathbf{x}_\mathbf{c} \mathbf{U}` of all count vectors evaluated so far, so a configuration costs one vector-matrix product per new count vector. - - Over several epochs, the linear solves use a sparse LU factorization once :math:`L n_T` reaches - :attr:`Settings.closed_form_sparse_min_states `, - and the exponentials become sparse actions once it reaches - :attr:`Settings.expm_action_min_dim `. The probabilities of - all :math:`L` count vectors are cached for the most recent layout and :math:`\theta`. + - Over several epochs, each finite epoch is applied by uniformization, and the last epoch is solved count + vector by count vector with one factorization, sparse from + :attr:`Settings.closed_form_sparse_min_states ` + transient states on. The probabilities of all :math:`L` count vectors are cached for the most recent layout + and :math:`\theta`. - ``get_mutation_configs(order='probability')`` climbs from the empty configuration to a local maximum of the probability, then expands outward with a priority queue. The order is exactly descending if every other configuration has a neighbour, one mutation apart, of at least equal probability. @@ -673,6 +671,19 @@ def _mutation_rewards(self, layout: MutationLayout) -> Tuple[np.ndarray, ...]: return non_absorbing, alpha, R + def _transient_rates(self, non_absorbing: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: + """ + The dense sub-intensity matrix of the current epoch and the absorption rate of each transient state, summed + over the rates into the absorbing states so that it is exactly zero where there are none. + + :param non_absorbing: The mask of the transient states. + :return: ``(S, e)``. + """ + rows = self.state_space.S[non_absorbing, :] + S, out = rows[:, non_absorbing], rows[:, ~non_absorbing] + + return (S.toarray() if sp.issparse(S) else np.asarray(S)), np.asarray(out.sum(axis=1), dtype=float).ravel() + def _get_resolvent(self, layout: MutationLayout, theta: float) -> Tuple: r""" Single-epoch resolvent :math:`\mathbf{U} = (\theta \operatorname{diag}(\bar{\mathbf{r}}) - \mathbf{T}_1)^{-1}`, @@ -693,9 +704,7 @@ def _get_resolvent(self, layout: MutationLayout, theta: float) -> Tuple: non_absorbing, alpha, R = self._mutation_rewards(layout) - S = self.state_space.S[non_absorbing, :][:, non_absorbing] - S = S.toarray() if sp.issparse(S) else np.asarray(S) - e = -S @ np.ones(S.shape[0]) + S, e = self._transient_rates(non_absorbing) r_total = R.sum(axis=0) leaking = self._leaking_states(S, e, r_total) @@ -773,9 +782,7 @@ def _mutation_epoch_data(self, layout: MutationLayout) -> Tuple: epochs = [] for epoch in self._get_epochs_until_unbounded(): self.state_space.update_epoch(epoch) - S = self.state_space.S[non_absorbing, :][:, non_absorbing] - S = S.toarray() if sp.issparse(S) else np.asarray(S) - e = -S @ np.ones(S.shape[0]) + S, e = self._transient_rates(non_absorbing) tau = None if np.isinf(epoch.end_time) else epoch.end_time - epoch.start_time epochs.append((S, e, tau, self._leaking_states(S, e, r_total))) @@ -849,54 +856,46 @@ def _get_mutation_config_inhomogeneous( # the one-mutation shifts of each bin, as (source node, target node) pairs shifts = [[(a, b) for a, b, i in edges if i == j] for j in range(J)] - sparse = self._solve_sparse(nt) - action = nt >= Settings.expm_action_min_dim - - def build_generator(S: np.ndarray) -> 'np.ndarray | sp.spmatrix': - diag = S - theta * np.diag(r_total) - if sparse: - A = sp.kron(sp.identity(L, format='csr'), sp.csr_matrix(diag), format='csr') - for i in range(J): - N = sp.csr_matrix(([1.0] * len(shifts[i]), tuple(zip(*shifts[i])) if shifts[i] else ([], [])), - shape=(L, L)) - A = A + sp.kron(N, sp.diags(theta * R[i]), format='csr') - return A - - A = np.zeros((nt, nt)) - for a in range(L): - A[a * m:(a + 1) * m, a * m:(a + 1) * m] = diag - for a, b, i in edges: - A[a * m:(a + 1) * m, b * m:(b + 1) * m] = np.diag(theta * R[i]) - return A + # the one-mutation shifts into each node, as (source node, bin) pairs, all from earlier nodes + incoming = [[] for _ in range(L)] + for a, b, i in edges: + incoming[b].append((a, i)) - def occupation(M: 'np.ndarray | sp.spmatrix', b: np.ndarray, leaking: Optional[np.ndarray]) -> np.ndarray: - if leaking is None: - return self._lu_solver(M.T, sparse)(b) + def build_generator(S: np.ndarray) -> sp.csr_matrix: + A = sp.kron(sp.identity(L, format='csr'), sp.csr_matrix(S - theta * np.diag(r_total)), format='csr') + for i in range(J): + N = sp.csr_matrix(([1.0] * len(shifts[i]), tuple(zip(*shifts[i])) if shifts[i] else ([], [])), + shape=(L, L)) + A = A + sp.kron(N, sp.diags(theta * R[i]), format='csr') + return A - # the occupation of the closed classes enters no equation of the others and exits nowhere - k = np.tile(leaking, L) - occ = np.zeros(nt) - occ[k] = self._lu_solver(M[k][:, k].T, sparse)(b[k]) - return occ + def occupation(S: np.ndarray, v: np.ndarray, leaking: Optional[np.ndarray]) -> np.ndarray: + """ + The row vector x with x (-A) = v, by substitution in node order: x_b = (v_b + sum_a x_a theta diag(r_i)) + (theta diag(r) - S)^{-1}, every term non-negative. The occupation of the closed classes enters no + equation of the others and exits nowhere. + """ + k = np.arange(m) if leaking is None else np.flatnonzero(leaking) + solve = self._lu_solver((theta * np.diag(r_total) - S)[np.ix_(k, k)].T, self._solve_sparse(k.size)) + x, V = np.zeros((L, m)), v.reshape(L, m) + for b in range(L): + rhs = V[b].copy() + for a, i in incoming[b]: + rhs += x[a] * theta * R[i] + x[b, k] = solve(rhs[k]) + return x v = np.zeros(nt) v[:m] = alpha p = np.zeros(L) for S, e, tau, leaking in epochs: - A = build_generator(S) - if tau is None: - p += occupation(-A, v, leaking).reshape(L, m) @ e + p += occupation(S, v, leaking) @ e break - if action: - u = Backend.expm_multiply(A.T * tau, v) - else: - u = v @ expm((A.toarray() if sparse else A) * tau) - - p += occupation(A, u - v, leaking).reshape(L, m) @ e - v = u + v, occ = _Uniformization(build_generator(S)).propagate(v, tau) + p += occ.reshape(L, m) @ e probs = dict(zip(nodes, p.tolist())) diff --git a/phasegen/distributions/phase_type.py b/phasegen/distributions/phase_type.py index 4131737e..1271e7f9 100644 --- a/phasegen/distributions/phase_type.py +++ b/phasegen/distributions/phase_type.py @@ -13,6 +13,7 @@ from .._blas import BlasThreadLimit from ..demography import Demography, Epoch from ..expm import Backend, _GrowthBound +from ._grid import _Propagators, _StepRuns from ..errors import ModelError from ..lineage import LineageConfig from ..locus import LocusConfig @@ -21,8 +22,8 @@ from ..spectrum import SFS, AbstractSpectrum from ..state_space import LineageCountingStateSpace, StateSpace -from ._common import N_EMPIRICAL_SAMPLES, _validate_order, _validate_reward, _validate_reward_count, _validate_rewards, \ - _validate_start_time, _sqrt_spectrum +from ._common import N_EMPIRICAL_SAMPLES, _n_samples, _validate_order, _validate_reward, _validate_reward_count, \ + _validate_rewards, _validate_start_time, _sqrt_spectrum from .base import CallableDistributionFunctions, DensityAwareDistribution, DistributionFunction, \ MarginalDemeDistributions, MarginalLocusDistributions, MomentAwareDistribution, _LogSurvivalGrid, \ _GridCumulativeDistributionFunction, _GridDensityFunction, _GridQuantileFunction @@ -510,8 +511,8 @@ def gradient(self, k: int = 1, rewards: Sequence[Reward] = None, center: bool = the rates redirects it, and the value of the redirected mass afterwards. Within the integral, the rate change :math:`\mathbf{H}` acts at the fraction :math:`\sigma` of the epoch, with the unperturbed rates acting before and after it. It is computed on the same path as the exponential in the - forward pass, densely or by reversing the Taylor action (see :attr:`Settings.expm_action_min_dim - `). + forward pass, densely or by reversing the Taylor action (see :attr:`Settings.expm_method + `). The entries of the generator :math:`\mathbf{S}_i` of epoch :math:`i`, of which :math:`\mathbf{T}_i` is the transient block, change linearly with the inverse coalescent time scales, the migration rates, the @@ -570,8 +571,7 @@ def gradient(self, k: int = 1, rewards: Sequence[Reward] = None, center: bool = :return: The derivatives. :raises NotImplementedError: If the moment is accumulated over a time window. :raises ValueError: If ``k`` is not a positive integer, if the number of rewards differs from ``k``, if a - reward is non-zero on an absorbing state, if absorption is not certain in the last epoch, or if the - generator is not affine in the rates. + reward is non-zero on an absorbing state, or if absorption is not certain in the last epoch. :raises TypeError: If ``k`` is not a number or an entry of ``rewards`` is not a :class:`~phasegen.rewards.Reward`. """ @@ -926,7 +926,10 @@ def sample(self, n_samples: int, seed: Union[int, np.random.Generator] = None) - :param seed: Integer seed of a :class:`numpy.random.Generator`, or the generator itself. ``None`` draws fresh entropy. :return: The samples, of shape ``(n_samples,)``. + :raises ValueError: If ``n_samples`` is not a non-negative integer. """ + n_samples = _n_samples(n_samples) + return self._sample(n_samples, rng=np.random.default_rng(seed)).reshape(n_samples) @staticmethod @@ -954,11 +957,13 @@ def to_empirical( :param seed: Integer seed of a :class:`numpy.random.Generator`, or the generator itself. ``None`` draws fresh entropy. :return: The empirical distribution. + :raises ValueError: If ``n_samples`` is not a positive integer. .. versionadded:: 2.0 """ from .empirical import EmpiricalPhaseTypeDistribution + n_samples = _n_samples(n_samples, minimum=1) pops = self.lineage_config.pop_names n_loci = self.locus_config.n @@ -1309,6 +1314,13 @@ class _ExpmFunction(_LogSurvivalGrid): #: Largest number of bisections of an epoch. _max_depth: int = 64 + #: Number of advances of the state distribution by which ``_build_cdf_grid`` estimates its cost, over about twice + #: the span of the grid. + _expected_advances: int = 2000 + + #: Number of distinct segment widths per epoch by which ``_build_cdf_grid`` estimates its cost. + _expected_widths: int = 20 + def _cdf_grid(self, x_max: float = 0.0, q_max: float = 0.0) -> tuple: """The grid over ``[0, t_max]``, built once. The arguments are ignored.""" return self._shared('expm_cdf_grid', self._build_cdf_grid) @@ -1331,6 +1343,15 @@ def _build_cdf_grid(self) -> tuple: epochs = itertools.takewhile(lambda ep: ep.start_time < t_max, d.demography.epochs) bounds = [float(ep.start_time) for ep in epochs] + [t_max] + # the dense propagators of the distinct segment widths against one action per advance, as + # ``_dense_expm_is_faster`` weighs them + steps = [] + for a, b in zip(bounds[:-1], bounds[1:]): + count = max(1, round(self._expected_advances * (b - a) / t_max)) + steps += [(d.demography.get_epoch(a), 2 * (b - a) / count)] * count + k = d.state_space.k + dense = d._dense_expm_is_faster(k, k, 1, steps, self._expected_widths * (len(bounds) - 1)) + w = np.asarray(d.state_space.alpha, dtype=float) nodes, log_survival, left, right = [0.0], [float(self._log_survival(d._cum(w)))], [], [] @@ -1342,7 +1363,6 @@ def _build_cdf_grid(self) -> tuple: memo, propagators = {}, {} # the absorbed and the surviving mass and the absorption flux of a row vector, in one product reads = np.column_stack([1 - e, e, d._exit_rates()]) - dense = d.state_space.k < Settings.expm_action_min_dim def advance(v: np.ndarray, tau: float) -> np.ndarray: """ @@ -1350,11 +1370,11 @@ def advance(v: np.ndarray, tau: float) -> np.ndarray: propagator of ``tau / 2`` where that exists. """ if not dense: - return d._propagate(v, tau, memo) + return d._propagate(v, tau, memo, False) if tau not in propagators: half = propagators.get(tau / 2) - propagators[tau] = d._propagate(np.eye(d.state_space.k), tau, memo) if half is None else half @ half + propagators[tau] = d._propagate(np.eye(k), tau, memo, True) if half is None else half @ half return v @ propagators[tau] @@ -1375,7 +1395,7 @@ def point(x: float, v: np.ndarray) -> tuple: # segments from the epoch start of widths h, h, 2h, 4h, ..., with h the longest step of ``_propagate``, # up to the first node where H reaches h_top or to the epoch end, each bisected below - h = d._per_epoch(memo, 'step', d._step_constants)[2] + h = d._per_epoch(memo, 'step', d._step_constants)[1] width = b - a if h is None else h lo = point(a, w) segments = [(0.0, 0, lo)] @@ -1537,13 +1557,13 @@ def __call__(self, q) -> 'np.ndarray | float': :param q: Probability level or array of levels in :math:`[0, 1]`. :return: The quantiles, of the same shape as ``q``. :raises NotImplementedError: If the coalescent has a bounded accumulation window. - :raises ValueError: If any ``q`` lies outside :math:`[0, 1]`. + :raises ValueError: If any ``q`` is NaN or lies outside :math:`[0, 1]`. """ self._distribution._assert_not_windowed() qa = np.atleast_1d(np.asarray(q, dtype=float)) - if np.any((qa < 0) | (qa > 1)): + if not np.all((qa >= 0) & (qa <= 1)): raise ValueError("Specified quantile must be between 0 and 1.") out = self._interp_quantile(qa.ravel(), *self._cdf_grid()).reshape(qa.shape) @@ -1609,9 +1629,8 @@ class TreeHeightDistribution(PhaseTypeDistribution, DensityAwareDistribution): where :math:`\boldsymbol{\alpha}_T e^{\mathbf{T} x}` holds the probabilities of the transient states at time :math:`x` and :math:`\mathbf{q}` their absorption rates (Bladt and Nielsen, 2017). The density is read off the - same vector as the CDF, without differencing. Above :attr:`Settings.expm_action_min_dim - ` states, the density far in the tail is accurate to roundoff - relative to its maximum, not relative to its own value. + same vector as the CDF, without differencing. Where the exponential is applied as a sparse action, the density + far in the tail is accurate to roundoff relative to its maximum, not relative to its own value. .. rubric:: Several epochs @@ -1628,10 +1647,9 @@ class TreeHeightDistribution(PhaseTypeDistribution, DensityAwareDistribution): .. rubric:: Implementation - - The state probabilities are propagated from point to point in ascending order. The exponential is formed - densely by the active matrix-exponential backend below :attr:`Settings.expm_action_min_dim - ` states, and is otherwise applied as a sparse action (Al-Mohy - and Higham, 2011). + - The state probabilities are propagated from point to point in ascending order, with the exponentials evaluated + as :attr:`Settings.expm_method ` selects. Equally spaced points share + one exponential per step length. - The quantile is read from the log-survival grid of :class:`~phasegen.distributions.QuantileFunction` on :math:`[0, t_\mathrm{max}]`, with :math:`t_\mathrm{max}` given by :attr:`TreeHeightDistribution.t_max `. Each node carries the exact negative log-survival @@ -1749,8 +1767,7 @@ def _step_constants(self) -> tuple: """ The quantities of the current epoch that ``_propagate`` reads. - :return: The rate matrix, its dense form below ``Settings.expm_action_min_dim`` states (``None`` at or above), - the longest step whose exponent stays within ``_max_step_norm`` (``None`` for a zero rate matrix) and the + :return: The rate matrix, the longest step whose exponent stays within ``_max_step_norm`` (``None`` for a zero rate matrix) and the slowest mean exit time of a transient state. :raises ModelError: If the rates are not finite. """ @@ -1771,14 +1788,19 @@ def _step_constants(self) -> tuple: exit_rates = exit_rates[exit_rates > 0] t_exit = 1 / exit_rates.min() if exit_rates.size else 0 - dense = self._dense_rate_matrix() if self.state_space.k < Settings.expm_action_min_dim else None - - return S, dense, h, t_exit + return S, h, t_exit - def _propagate(self, w: np.ndarray, tau: float, memo: dict = None) -> np.ndarray: + def _propagate( + self, + w: np.ndarray, + tau: float, + memo: dict = None, + dense: bool = None, + propagators: _Propagators = None + ) -> np.ndarray: """ - Advance the state distribution ``w`` by ``tau`` within the current epoch, by the dense exponential below - ``Settings.expm_action_min_dim`` states and by the sparse action at or above it. A step whose exponent + Advance the state distribution ``w`` by ``tau`` within the current epoch, by the dense exponential or by the + sparse action, as ``_dense_expm_is_faster`` decides for this one step unless ``dense`` is given. A step whose exponent exceeds ``_max_step_norm`` is split into steps of doubling length. On the dense path, propagation ends once a step at least as long as the slowest mean exit time of a transient state leaves the transient entries unchanged. The absorbing states never feed the transient ones, so those entries are then stationary, and the @@ -1789,6 +1811,8 @@ def _propagate(self, w: np.ndarray, tau: float, memo: dict = None) -> np.ndarray :param w: The row vector to advance, or a matrix whose rows are advanced. :param tau: Time to advance by, within the current epoch. :param memo: Per-epoch values of the sweep, see ``_per_epoch``. + :param dense: Whether to take the dense exponential, by default as decided for this step. + :param propagators: The dense exponentials of the current epoch by step, computed afresh if not given. :return: The advanced row vector. """ if tau <= 0: @@ -1797,22 +1821,28 @@ def _propagate(self, w: np.ndarray, tau: float, memo: dict = None) -> np.ndarray if tau == np.inf: return self._limit(w) - S, dense, h, t_exit = self._per_epoch(memo, 'step', self._step_constants) + S, h, t_exit = self._per_epoch(memo, 'step', self._step_constants) h = tau if h is None else h if dense is None: + k = self.state_space.k + dense = self._dense_expm_is_faster(k, k, 1, [(self.state_space.epoch, tau)]) + + if dense: + S_dense = self._per_epoch(memo, 'dense', self._dense_rate_matrix) + else: # ``expm_multiply`` computes ``exp(a) @ b``, so the left action ``w @ exp(S tau)`` is ``exp(S^T tau) @ w`` St, abs_St, growth = self._per_epoch(memo, 'action', self._action_constants) while tau > 0: step = min(tau, h) - if dense is None: + if not dense: w = Backend.expm_multiply(St * step, w) tau, h = tau - step, 2 * h stationary = tau > 0 and Backend._stationary(St, abs_St, w, tau, growth(tau)) else: - v = w @ expm(dense * step) + v = w @ (expm(S_dense * step) if propagators is None else propagators(step)) stationary = step >= t_exit and np.array_equal(v * self._e, w * self._e) w, tau, h = v, tau - step, 2 * h @@ -1941,28 +1971,120 @@ def _sweep(self, t: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: :math:`F = \mathbf{p}\,(\mathbf{1} - \mathbf{h}) / \mathbf{p}\,\mathbf{1}` and :math:`f = \mathbf{p}\,\mathbf{S}_\ell\,(\mathbf{1} - \mathbf{h})` are read off, with :math:`\mathbf{h}` the indicator of the transient states, :math:`\mathbf{1}` the vector of ones and :math:`\mathbf{S}_\ell` the rate - matrix of the epoch :math:`\ell` holding the time. + matrix of the epoch :math:`\ell` holding the time. Within an epoch, the times are taken as runs of equal + steps (``_StepRuns``), each run reusing one dense exponential per step length, or taking one interval action + of :meth:`Backend.expm_multiply_interval() ` on the sparse path, + as ``_dense_expm_is_faster`` decides from ``_sweep_steps``. :param t: Ascending times to evaluate at. :return: The CDF and the density at ``t``. """ w = np.asarray(self.state_space.alpha, dtype=float) - epoch = self.demography.get_epoch(0) - u_prev = 0.0 + k = self.state_space.k + plan = self._sweep_plan(t) + dense = self._dense_expm_is_faster(k, k, 1, *self._sweep_steps(plan)) cdf, pdf = np.zeros(len(t)), np.zeros(len(t)) - memo = {} + memo, i = {}, 0 + absorbed = 1 - self._e - for i, u in enumerate(t): - w = self._sweep_to(w, u_prev, float(u), epoch, memo) - epoch = self.state_space.epoch + for epoch, runs, remainder in plan: + self.state_space.update_epoch(epoch) + self._per_epoch(memo, 'stable', lambda: self._check_numerical_stability(self.state_space.S, epoch.index)) + propagators = _Propagators( + lambda tau: expm(self._per_epoch(memo, 'dense', self._dense_rate_matrix) * tau) + ) if dense else None + exit_rates = self._per_epoch(memo, 'exit', self._exit_rates) - cdf[i] = self._cum(w) - pdf[i] = float(w @ self._per_epoch(memo, 'exit', self._exit_rates)) - u_prev = float(u) + for step, count in runs: + W = self._propagate_run(w, step, count, memo, dense, propagators) + w = W[-1] + cdf[i:i + count] = W @ absorbed / W.sum(axis=1) + pdf[i:i + count] = W @ exit_rates + i += count + + w = self._propagate(w, remainder, memo, dense, propagators) return cdf, pdf + def _sweep_plan(self, t: np.ndarray) -> List[Tuple['Epoch', List[Tuple[float, int]], float]]: + """ + The propagation of ``_sweep`` through the ascending times ``t``: per epoch it reaches, the runs of equal steps + (``_StepRuns``) to its times, a time on a boundary taking the epoch ending there, and the remainder to the epoch + end, zero in the last epoch reached. + + :param t: Ascending times. + :return: The epochs, their runs as pairs of step and number of steps, and their remainders. + """ + epoch = self.demography.get_epoch(0) + plan, x, i = [], 0.0, 0 + + while i < len(t): + j = int(np.searchsorted(t, epoch.end_time, side='right')) + runs, x_end = _StepRuns.split(x, np.asarray(t[i:j], dtype=float)) + i = j + + plan.append((epoch, runs, epoch.end_time - x_end if i < len(t) else 0.0)) + + if i < len(t): + x = epoch.end_time + epoch = self.demography.get_epoch(epoch.end_time) + + return plan + + @staticmethod + def _sweep_steps(plan: List[Tuple['Epoch', List[Tuple[float, int]], float]]) -> Tuple[List[Tuple['Epoch', float]], int]: + """ + The actions and the number of distinct dense exponentials of a ``_sweep_plan``: one interval action per run of + several finite steps and one action per other step and per remainder, and one dense exponential per epoch and + step length. Infinite steps take the limit and neither. + + :param plan: The plan. + :return: The epochs and the times of the actions, and the number of dense exponentials. + """ + steps, dense = [], set() + for epoch, runs, remainder in plan: + for step, count in runs + [(remainder, 1)]: + if 0 < step < np.inf: + steps.append((epoch, step * count)) + dense.add((epoch.index, step)) + + return steps, len(dense) + + def _propagate_run( + self, + w: np.ndarray, + step: float, + count: int, + memo: dict, + dense: bool, + propagators: _Propagators = None + ) -> np.ndarray: + """ + The row vector advanced ``count`` times by ``step`` within the current epoch, by ``_propagate`` per step, or on + the sparse path by one interval action, which itself steps where the run is stiff. + + :param w: The row vector to advance. + :param step: The step. + :param count: The number of steps. + :param memo: Per-epoch values of the sweep, see ``_per_epoch``. + :param dense: Whether to take the dense exponentials. + :param propagators: The dense exponentials of the current epoch by step. + :return: The row vectors after each step, of shape ``(count, len(w))``. + """ + if not dense and count > 1 and 0 < step < np.inf: + St = self._per_epoch(memo, 'action', self._action_constants)[0] + + return Backend.expm_multiply_interval( + St, w, step * count, count, advance=lambda v, tau: self._propagate(v, tau, memo, False) + ) + + W = np.empty((count, len(w))) + for c in range(count): + w = W[c] = self._propagate(w, step, memo, dense, propagators) + + return W + @cached_property def t_max(self) -> float: """ diff --git a/phasegen/distributions/reward.py b/phasegen/distributions/reward.py index 47eba590..c53a75fc 100644 --- a/phasegen/distributions/reward.py +++ b/phasegen/distributions/reward.py @@ -6,7 +6,7 @@ """ import logging from math import comb, factorial -from typing import Any, NoReturn, TYPE_CHECKING, Optional, Sequence, Union +from typing import Any, NoReturn, TYPE_CHECKING, Optional, Sequence, Tuple, Union import numpy as np import scipy.linalg as sla @@ -19,8 +19,8 @@ from .base import CallableDistributionFunctions, JointDensity, JointCDF, \ ConditionalDensity, ConditionalCDF, ConditionalQuantileFunction, \ _LSTCumulativeDistributionFunction, _LSTDensityFunction, _LSTQuantileFunction -from ._common import N_EMPIRICAL_SAMPLES, _validate_order -from ._moments import MomentEvaluator, _AUTO_PERM +from ._common import N_EMPIRICAL_SAMPLES, _n_samples, _validate_order +from ._moments import MomentEvaluator, _AUTO_PERM, _TRANSFORM_COST if TYPE_CHECKING: from .phase_type import PhaseTypeDistribution @@ -31,6 +31,14 @@ #: Mass beyond the window of the 2D cosine expansion of a joint distribution above which a warning is logged. _COS2D_TAIL_WARN = 1e-2 +#: Levels within the continuous part of each marginal, above its atom at 0, at whose quantiles +#: ``JointRewardDistribution._cos2d_wiggle_check`` compares the margins of the 2D cosine expansion with the marginal +#: CDFs. They are densest at low levels, where a steep rise above the atom or a narrow body sits. +_COS2D_CHECK_LEVELS = np.array([0.01, 0.03, 0.06, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.65, 0.8, 0.95]) + +#: Largest gap between a margin of the 2D cosine expansion and the marginal CDF above which a warning is logged. +_COS2D_MARGIN_WARN = 0.03 + #: Error of the Euler inversion of a unit step (``_euler_step_error``) at or below which #: ``JointRewardDistribution._jump_correction`` leaves the jumps out. Steps far below the point of inversion err by #: rounding only, about ``1e-16 * exp(A / 2)``, and steps far above it by less. @@ -251,6 +259,36 @@ def std(self) -> float: """Standard deviation of the accumulated reward.""" return self.var ** 0.5 + def moment(self, k: int, center: bool = True) -> float: + r""" + The moment of order :math:`k` of the accumulated reward, central by default, evaluated by + :meth:`PhaseTypeDistribution.moment() `. + + :param k: Order of the moment. + :param center: Whether to return the central moment. + :return: The moment. + :raises TypeError: If ``k`` is not a number. + :raises ValueError: If ``k`` is not a non-negative integer. + """ + k = _validate_order(k) + + return float(MomentEvaluator.moment(self._host, k=k, rewards=(self.reward,) * k, center=center)) + + @cached_property + def m2(self) -> float: + """Second (non-central) moment.""" + return self.moment(k=2, center=False) + + @cached_property + def m3(self) -> float: + """Third (non-central) moment.""" + return self.moment(k=3, center=False) + + @cached_property + def m4(self) -> float: + """Fourth (non-central) moment.""" + return self.moment(k=4, center=False) + def to_empirical( self, n_samples: int = N_EMPIRICAL_SAMPLES, @@ -265,10 +303,12 @@ def to_empirical( :param seed: Integer seed of a :class:`numpy.random.Generator`, or the generator itself. ``None`` draws fresh entropy. :return: The empirical distribution. + :raises ValueError: If ``n_samples`` is not a positive integer. """ from .empirical import EmpiricalDistribution - samples = self._host._sample(n_samples, rewards=[self.reward], rng=np.random.default_rng(seed)) + samples = self._host._sample(_n_samples(n_samples, minimum=1), rewards=[self.reward], + rng=np.random.default_rng(seed)) dist = EmpiricalDistribution(samples[:, 0]) dist.label = self.label dist._variable = self._variable @@ -324,7 +364,10 @@ def lst(self, s: complex) -> complex: .. rubric:: Implementation - - The exponentials are formed densely. The last-epoch system is solved by a sparse LU factorization from + - The exponentials of the bounded epochs are applied to the batch of arguments by a truncated Taylor series + or formed densely by Pade approximants, as + :attr:`Settings.expm_method ` selects. The + last-epoch system is solved by a sparse LU factorization from :attr:`Settings.closed_form_sparse_min_states ` transient states on, and by a dense one below. - Transient states that the initial vector cannot reach in any epoch carry no mass and are left out. @@ -529,24 +572,26 @@ def _shift_rows(s, r: np.ndarray, tau: float) -> np.ndarray: def _lst_taylor_from_shift(shifts: np.ndarray, deriv: np.ndarray, alpha: np.ndarray, T_epochs, sparse: bool, - perm=_AUTO_PERM, order: int = 2) -> np.ndarray: + perm=_AUTO_PERM, order: int = 2, action: bool = None) -> np.ndarray: """The Taylor coefficients ``[Phi_0, ..., Phi_order]`` of ``_lst_from_shift_batch`` at the shift ``shift + eps * deriv`` for each row ``shift`` of ``shifts``, described at ``JointRewardDistribution.lst_taylor``: bounded epochs propagate the block-bidiagonal matrix over the truncated polynomial ring by - ``_ShiftedGenerator.propagate``, decided and chunked as in ``_lst_from_shift_batch``, and the last epoch - back-substitutes with one LU per row. Returns an array of shape ``(len(shifts), order + 1)``.""" + ``_ShiftedGenerator.propagate``, decided (unless ``action`` is given) and chunked as in ``_lst_from_shift_batch``, + and the last epoch back-substitutes with one LU per row. Returns an array of shape ``(len(shifts), order + 1)``.""" nt, k = len(alpha), order + 1 n_aug = nt + 1 K = len(shifts) - action = k * n_aug >= Settings.expm_action_min_dim + if action is None: + exits = (_exit_rates(T) for T, _, _ in T_epochs[:-1]) + action = _takes_action(k * n_aug, K, len(T_epochs) - 1, _shifted_blocks(T_epochs, exits, shifts, deriv, order)) chunk = max(1, (_LST_VECTOR_ENTRIES // (k * n_aug)) if action else (_LST_MATRIX_ENTRIES // (k * n_aug) ** 2)) if K > chunk: # the Taylor action of a chunk costs as many products as its largest shift needs, so chunk similar shifts by_size = np.argsort(np.abs(shifts).max(axis=1), kind='stable') if action else np.arange(K) out = np.empty((K, k), dtype=complex) out[by_size] = np.concatenate([ - _lst_taylor_from_shift(shifts[by_size[i:i + chunk]], deriv, alpha, T_epochs, sparse, perm, order) + _lst_taylor_from_shift(shifts[by_size[i:i + chunk]], deriv, alpha, T_epochs, sparse, perm, order, action) for i in range(0, K, chunk) ]) return out @@ -875,10 +920,11 @@ def to_empirical( :param seed: Integer seed of a :class:`numpy.random.Generator`, or the generator itself. ``None`` draws fresh entropy. :return: The empirical joint distribution. + :raises ValueError: If ``n_samples`` is not a positive integer. """ from .empirical import EmpiricalJointDistribution - samples = self._host._sample(n_samples, rewards=[self.reward_a, self.reward_b], + samples = self._host._sample(_n_samples(n_samples, minimum=1), rewards=[self.reward_a, self.reward_b], rng=np.random.default_rng(seed)) dist = EmpiricalJointDistribution(samples[:, 0], samples[:, 1], (self.reward_a._variable, self.reward_b._variable)) @@ -1385,34 +1431,42 @@ def _build_cos2d(self) -> dict: @property def _cos2d_wiggle_check(self) -> float: - """The largest near-origin gap between ``F(x, inf)`` of the cosine expansion and the marginal CDF of ``R_a``, - logged as a warning above 0.03. The cosine error concentrates near the axes, so this margin comparison detects - an under-resolved near-origin rise. It reads the coefficients directly, so it does not recurse into - ``_cc_box``.""" + """The largest gap between the margins ``F(x, inf)`` and ``F(inf, y)`` of the cosine expansion and the marginal + CDFs of ``R_a`` and ``R_b``, at quantiles from 1% to 95% of the continuous part of each marginal above its atom + at 0, logged as a warning above 0.03. A gap shows that :attr:`Settings.cos_terms_2d + ` under-resolves the joint distribution. It reads the coefficients + directly, so it does not recurse into ``_cc_box``.""" return self._cos_memo('wiggle', self._build_cos2d_wiggle_check, (Settings.cos_terms, Settings.cos_terms_2d)) def _build_cos2d_wiggle_check(self) -> float: """Build ``_cos2d_wiggle_check``.""" st = self._cos2d - ma = self.marginal('a') - # near-origin points of the continuous part, where the bias concentrates. They lie above the atom at 0, where - # the inversion of the continuous part is defined - a0 = float(self._atoms['a0']) - xs = np.linspace(0.0, float(ma.quantile(a0 + 0.4 * (1.0 - a0))), 5)[1:] - # cosine full CDF F(x, inf) = axis atoms (de Hoog) + the cosine continuous box integrated to the window edge - box = self._cos_antideriv(st['ua'], np.minimum(xs, st['ba'])) @ st['A'] @ self._cos_antideriv(st['ub'], np.array([st['bb']])).T - g_b = ma._invert(lambda s: self.lst_batch(s, np.inf) / s, xs) - cos_cdf = g_b + self._atoms['a0'] - self._atoms['both0'] + box[:, 0] - true_cdf = np.array([float(ma.cdf(float(x))) for x in xs]) - err = float(np.abs(cos_cdf - true_cdf).max()) - if Settings.check_inversions and err > 0.03: + both0 = self._atoms['both0'] + errs = {} + for axis in ('a', 'b'): + marg = self.marginal(axis) + a0 = float(self._atoms[axis + '0']) + xs = np.asarray(marg.quantile(a0 + (1.0 - a0) * _COS2D_CHECK_LEVELS), dtype=float) + # cosine margin = axis atoms (de Hoog) + the cosine continuous box integrated to the other window edge + if axis == 'a': + box = (self._cos_antideriv(st['ua'], np.minimum(xs, st['ba'])) @ st['A'] + @ self._cos_antideriv(st['ub'], np.array([st['bb']])).T)[:, 0] + g = marg._invert(lambda s: self.lst_batch(s, np.inf) / s, xs) + else: + box = (self._cos_antideriv(st['ua'], np.array([st['ba']])) @ st['A'] + @ self._cos_antideriv(st['ub'], np.minimum(xs, st['bb'])).T)[0] + g = marg._invert(lambda s: self.lst_batch(np.inf, s) / s, xs) + cos_cdf = g + self._atoms[axis + '0'] - both0 + box + errs[axis] = float(np.abs(cos_cdf - marg.cdf._cdf_point(xs)).max()) + axis = max(errs, key=errs.get) + if Settings.check_inversions and errs[axis] > _COS2D_MARGIN_WARN: self._logger.warning( - "The 2D Fourier-cosine joint inversion under-resolves near the origin: its CDF deviates from the " - "marginal CDF by up to %.3g there. The joint CDF and density may be biased near the axes, where the " - "cosine series cannot capture a sharp or skewed rise.", err, + "The 2D Fourier-cosine joint inversion under-resolves the joint distribution: its margin deviates from " + "the marginal CDF of R_%s by up to %.3g. The joint CDF and density may be biased. Increase " + "Settings.cos_terms_2d (currently %d) to resolve it.", axis, errs[axis], Settings.cos_terms_2d, ) - return err + return errs[axis] @property def _density_grid(self) -> dict: @@ -2445,9 +2499,8 @@ def __init__(self, diag: np.ndarray, off_norm: np.ndarray): :param diag: The diagonals of the matrices, of shape ``(K, dim)``. :param off_norm: The column 1-norms of their off-diagonal parts, shared by all of them. """ + plain, shifted = self.norms(diag, off_norm) mu = diag.mean(axis=1) - plain = float((off_norm + np.abs(diag)).max(initial=0.0)) - shifted = float((off_norm + np.abs(diag - mu[:, None])).max(initial=0.0)) if not np.isfinite(plain): raise ValueError(f'The matrices of the Taylor action must be finite, got a 1-norm bound of {plain}.') @@ -2468,6 +2521,19 @@ def __init__(self, diag: np.ndarray, off_norm: np.ndarray): if m * steps < cost: cost, self.m, self.s = m * steps, m, steps + @staticmethod + def norms(diag: np.ndarray, off_norm: np.ndarray) -> Tuple[float, float]: + """ + The bounds on the 1-norms of the matrices, unshifted and shifted by their mean diagonals :math:`\\mu_k`, + whose smaller one sets the degree and steps. + + :param diag: The diagonals of the matrices, of shape ``(K, dim)``. + :param off_norm: The column 1-norms of their off-diagonal parts, shared by all of them. + :return: The unshifted and the shifted bound. + """ + return (float((off_norm + np.abs(diag)).max(initial=0.0)), + float((off_norm + np.abs(diag - diag.mean(axis=1)[:, None])).max(initial=0.0))) + def apply(self, W: np.ndarray, product) -> np.ndarray: """ The rows :math:`\\mathbf{w}_k e^{\\mathbf{A}_k}`. @@ -2496,9 +2562,8 @@ def apply(self, W: np.ndarray, product) -> np.ndarray: class _EpochSteps: r""" - The exponentials :math:`e^{\mathbf{M}_e}` of a stack of epoch matrices applied to single vectors, formed densely - by ``_expm_batch`` below :attr:`Settings.expm_action_min_dim - ` and applied by ``_TaylorAction`` at or above it. + The exponentials :math:`e^{\mathbf{M}_e}` of a stack of epoch matrices, each applied to a single vector, formed + densely by ``_expm_batch`` or applied by ``_TaylorAction`` as ``_takes_action`` decides. """ def __init__(self, M: np.ndarray): @@ -2506,7 +2571,8 @@ def __init__(self, M: np.ndarray): :param M: The matrices, of shape ``(E, n, n)``. """ self.M = M - self._dense = _expm_batch(M) if M.shape[-1] < Settings.expm_action_min_dim else None + blocks = (((np.diagonal(m)[None], np.abs(m).sum(axis=0) - np.abs(np.diagonal(m))),) for m in M) + self._dense = None if _takes_action(M.shape[-1], 1, len(M), blocks) else _expm_batch(M) def _action(self, w: np.ndarray, M: np.ndarray) -> np.ndarray: r"""The row :math:`\mathbf{w} e^{\mathbf{M}}` by ``_TaylorAction``.""" @@ -2568,13 +2634,54 @@ def _expm_batch(A: np.ndarray) -> np.ndarray: return R +def _shifted_blocks(T_epochs, exits, shifts: np.ndarray, deriv: np.ndarray = None, order: int = 0): + """Per bounded epoch, the diagonals and off-diagonal column norms of the ``_ShiftedGenerator`` of blocks of the + shift vectors, at most ``_LST_VECTOR_ENTRIES`` diagonal entries each, the input of ``_takes_action``.""" + rows = max(1, _LST_VECTOR_ENTRIES // ((order + 1) * (shifts.shape[1] + 1))) + for (T, t0, t1), q in zip(T_epochs[:-1], exits): + yield ((g.diag, g.off_norm) for g in (_ShiftedGenerator(T, q, t1 - t0, shifts[i:i + rows], deriv, order) + for i in range(0, len(shifts), rows))) + + +def _takes_action(dim: int, batch: int, n_epochs: int, epochs) -> bool: + r""" + Whether a batch of ``batch`` matrices of dimension ``dim`` per epoch is propagated by ``_TaylorAction`` rather + than exponentiated by ``_expm_batch``, by the bound of ``_TRANSFORM_COST`` on the step norms of + ``_TaylorAction.norms`` summed over the epochs, read only where the bound is finite and positive. + + :param dim: The dimension of each matrix. + :param batch: The number of matrices of each epoch. + :param n_epochs: The number of epochs. + :param epochs: Per epoch, an iterable over blocks of its matrices, each given by their diagonals, of shape + ``(b, dim)``, and the column 1-norms of their off-diagonal parts, shared by all of them. + :return: Whether to take the action. + """ + bound = _TRANSFORM_COST.bound(dim, dim, 1, n_epochs, n_epochs, batch=batch) + if bound == np.inf: + return True + + if not n_epochs or bound < 0: + return False + + norm = 0.0 + for blocks in epochs: + plain = shifted = 0.0 + for diag, off_norm in blocks: + p, q = _TaylorAction.norms(diag, off_norm) + plain, shifted = max(plain, p), max(shifted, q) + norm += min(plain, shifted) + + return not norm > bound + + def _lst_from_shift_batch(shifts: np.ndarray, alpha, T_epochs, exits: list, sparse: bool, - perm=_AUTO_PERM) -> np.ndarray: + perm=_AUTO_PERM, action: bool = None) -> np.ndarray: r""" The transform of ``RewardDistribution.lst`` with the diagonal shift :math:`s \mathbf{r}_T` replaced by an arbitrary vector, which is :math:`s_a \mathbf{r}_a + s_b \mathbf{r}_b` for the joint transform, at each row of a stack of - shift vectors ``(k, nt)``. The bounded epochs propagate the batch by ``_ShiftedGenerator.propagate``, in chunks of - at most ``_LST_VECTOR_ENTRIES`` vector or ``_LST_MATRIX_ENTRIES`` matrix entries. A dense last epoch is solved as + shift vectors ``(k, nt)``. The bounded epochs propagate the batch by ``_ShiftedGenerator.propagate``, by the + Taylor action or the dense exponentials as ``_takes_action`` decides for the whole batch, in chunks of at most + ``_LST_VECTOR_ENTRIES`` vector or ``_LST_MATRIX_ENTRIES`` matrix entries. A dense last epoch is solved as one stacked ``np.linalg.solve``, a sparse one by the block-triangular sparse LU of ``MomentEvaluator._lu_solver`` per shift, with ``perm`` the ordering of the last-epoch sub-intensity matrix, which depends only on its sparsity pattern. An infinite shift removes its state, which gives the limit of the shift growing without bound: the rows @@ -2586,6 +2693,7 @@ def _lst_from_shift_batch(shifts: np.ndarray, alpha, T_epochs, exits: list, spar :param exits: The per-epoch exit vectors :math:`-\mathbf{T}\mathbf{e}`. :param sparse: Whether the last-epoch solve is sparse. :param perm: The block-triangular ordering of the last-epoch sub-intensity matrix. + :param action: Whether the bounded epochs take the Taylor action, decided by ``_takes_action`` if ``None``. :return: The transform at each shift vector. """ nt = len(alpha) @@ -2606,14 +2714,15 @@ def _lst_from_shift_batch(shifts: np.ndarray, alpha, T_epochs, exits: list, spar sparse, sub_perm) return out - action = nt + 1 >= Settings.expm_action_min_dim + if action is None: + action = _takes_action(nt + 1, k, len(T_epochs) - 1, _shifted_blocks(T_epochs, exits, shifts)) chunk = max(1, (_LST_VECTOR_ENTRIES // (nt + 1)) if action else (_LST_MATRIX_ENTRIES // (nt + 1) ** 2)) if k > chunk: # the Taylor action of a chunk costs as many products as its largest shift needs, so chunk similar shifts by_size = np.argsort(np.abs(shifts).max(axis=1), kind='stable') if action else np.arange(k) out = np.empty(k, dtype=complex) out[by_size] = np.concatenate([_lst_from_shift_batch(shifts[by_size[i:i + chunk]], alpha, T_epochs, exits, - sparse, perm) for i in range(0, k, chunk)]) + sparse, perm, action) for i in range(0, k, chunk)]) return out diag = np.arange(nt) @@ -3141,12 +3250,12 @@ def __call__(self, q) -> 'np.ndarray | float': """ :param q: Level or array of levels in ``[0, 1]``. :return: The quantiles, of the same shape. - :raises ValueError: If any ``q`` lies outside ``[0, 1]``. + :raises ValueError: If any ``q`` is NaN or lies outside ``[0, 1]``. """ d = self._distribution d._warn_if_line_unresolved() qa = np.atleast_1d(np.asarray(q, dtype=float)) - if np.any((qa < 0) | (qa > 1)): + if not np.all((qa >= 0) & (qa <= 1)): raise ValueError("Quantile must be between 0 and 1.") ys, ps = d._atom_values, d._atom_masses diff --git a/phasegen/distributions/spectra.py b/phasegen/distributions/spectra.py index 2b9ef734..08bf33a7 100644 --- a/phasegen/distributions/spectra.py +++ b/phasegen/distributions/spectra.py @@ -6,7 +6,7 @@ import math from abc import ABC, abstractmethod from ..caching import cached_property, cache -from typing import Dict, List, Mapping, NoReturn, Tuple, Iterable, Optional, Sequence, Union, TYPE_CHECKING +from typing import Dict, List, Mapping, NoReturn, Tuple, Iterable, Sequence, Union, TYPE_CHECKING import numpy as np from .._blas import BlasThreadLimit from ..errors import ModelError @@ -17,8 +17,8 @@ from ..settings import Settings from ..spectrum import SFS, TwoSFS, JointSFS, TwoLocusSFS -from ._common import N_EMPIRICAL_SAMPLES, _descendant_config, _frequency_class, _make_hashable, _polymorphic_class, \ - _validate_order +from ._common import N_EMPIRICAL_SAMPLES, _descendant_config, _frequency_class, _make_hashable, _n_samples, \ + _polymorphic_class, _validate_order from .base import CumulativeDistributionFunction, DensityFunction, QuantileFunction from .phase_type import DemographyGradient, PhaseTypeDistribution from .mutation_configs import MutationLayout, SpectrumDistribution @@ -230,6 +230,18 @@ def _mean_rewards( return host, R, [pos for pos, _ in bins] + @cached_property + def _second_moments(self) -> Tuple[List[Tuple[int, ...]], np.ndarray, np.ndarray]: + """ + The means and the second cross-moments of the polymorphic bins, from one forward pass over all bins, see + ``MomentEvaluator._bin_second_moments``. Cached so that the covariance and the variance share it. + + :return: The positions of the bins, their means and their cross-moments. + """ + bins = self._bins() + + return [pos for pos, _ in bins], *self._bin_second_moments([CombinedReward([self.reward, r]) for _, r in bins]) + def _cov_entries(self) -> List[Tuple[Tuple[int, ...], List[Tuple[float, Tuple[np.ndarray, ...]]], float, float]]: """ The entries of the covariance of the bins, each a central moment of two bin rewards. @@ -547,7 +559,9 @@ def sample(self, n_samples: int, seed: Union[int, np.random.Generator] = None) - :param seed: Integer seed of a :class:`numpy.random.Generator`, or the generator itself. ``None`` draws fresh entropy. :return: Array of shape ``(n_samples, n + 1)``, whose column means estimate :attr:`mean`. + :raises ValueError: If ``n_samples`` is not a non-negative integer. """ + n_samples = _n_samples(n_samples) indices = self._get_indices() rewards = [CombinedReward([self.reward, self._get_sfs_reward(i)]) for i in indices] sampled = self._sample(n_samples, rewards=rewards, rng=np.random.default_rng(seed)) @@ -573,6 +587,7 @@ def to_empirical( :param seed: Integer seed of a :class:`numpy.random.Generator`, or the generator itself. ``None`` draws fresh entropy. :return: The empirical spectrum. + :raises ValueError: If ``n_samples`` is not a positive integer. :raises NotImplementedError: For more than one locus. """ from .empirical import EmpiricalPhaseTypeSFSDistribution @@ -580,6 +595,7 @@ def to_empirical( if self.locus_config.n != 1: raise NotImplementedError("Sampled SFS is only available for single-locus scenarios.") + n_samples = _n_samples(n_samples, minimum=1) pops = self.lineage_config.pop_names n = self.lineage_config.n indices = self._get_indices() @@ -828,51 +844,6 @@ def get_accumulation( return float(accumulation[0]) if scalar else accumulation - @cached_property - def _cov_batched(self) -> Optional[TwoSFS]: - """ - Batched 2-SFS covariance, contracting ``_two_point_occupation`` with the stacked bin rewards as in - ``PhaseTypeDistribution.moment``. - - :return: The covariance, or ``None`` when not applicable, and the caller evaluates per pair. - """ - if not Settings.closed_form_last_epoch: - return None - - two_point = self._two_point_occupation() - if two_point is None: - return None - - m, solve, idx_t = two_point - ss = self.state_space - indices = self._get_indices() - R = np.column_stack([ - np.asarray(CombinedReward([self.reward, self._get_sfs_reward(i)])._get(ss), dtype=float)[idx_t] - for i in indices - ]) - - sfs_matrix = (m[:, None] * R).T @ solve(R) # R^T diag(m) (-T)^{-1} R (one ordering) - self._logger.debug("sfs.cov: centering with the outer product of bin means") - mean = np.asarray(self.mean.data)[indices] - cov = (sfs_matrix + sfs_matrix.T) - np.outer(mean, mean) - - out = np.zeros((self.lineage_config.n + 1, self.lineage_config.n + 1)) - for a, ia in enumerate(indices): - out[ia, indices] = cov[a] - return TwoSFS(out) - - def _cov_stacked(self) -> bool: - """ - Whether :attr:`cov` evaluates the cross-moments of the bin pairs in closed form, stacked over the first bin. - - :return: Whether the stacked closed form applies. - """ - _, end_time = self._resolve_window() - - return bool( - np.isinf(end_time) and Settings.closed_form_last_epoch and self._absorption_certain_in_last_epoch(2) - ) - @cached_property @BlasThreadLimit() def cov(self) -> TwoSFS: @@ -880,50 +851,11 @@ def cov(self) -> TwoSFS: Covariance matrix across site-frequency counts, evaluated as described in :meth:`PhaseTypeDistribution.moment() `. """ - batched = self._cov_batched - if batched is not None: - self._logger.debug("sfs.cov: batched (shared two-point occupation)") - return batched - - indices = self._get_indices() - bin_rewards = [CombinedReward([self.reward, self._get_sfs_reward(i)]) for i in indices] - start_time, _ = self._resolve_window() - - if self._cov_stacked(): - self._logger.debug("sfs.cov: closed form over %d bin pairs, stacked over the first bin", len(indices) ** 2) - Reward._check_accumulable(self.state_space, bin_rewards) - - # the cross-moment of each bin pair, one evaluation per second bin - cross = np.column_stack([ - self._accumulate_closed_form(2, (r, r), start_time, heads=bin_rewards) for r in bin_rewards - ]) - - if np.isnan(cross).any(): - raise ModelError( - "NaN value encountered when computing moment. " - "This is likely due to an ill-conditioned rate matrix." - ) - else: - self._logger.debug("sfs.cov: per-pair matrix exponential over %d bin pairs", len(indices) ** 2) - - # cross-moment of each bin pair (serial) - cross = np.array([ - [ - PhaseTypeDistribution.moment(self, k=2, permute=False, center=False, rewards=(r_i, r_j)) - for r_j in bin_rewards - ] - for r_i in bin_rewards - ]) - - # re-structure the results to a matrix form - sfs = np.zeros((self.lineage_config.n + 1, self.lineage_config.n + 1)) - sfs[np.ix_(indices, indices)] = cross - - # get matrix of marginal moments - m2 = np.outer(self.mean.data, self.mean.data) + positions, mean, cross = self._second_moments + indices = [pos[0] for pos in positions] - # calculate covariances - cov = (sfs + sfs.T) / 2 - m2 + cov = np.zeros((self.lineage_config.n + 1, self.lineage_config.n + 1)) + cov[np.ix_(indices, indices)] = cross - np.outer(mean, mean) return TwoSFS(cov) @@ -934,14 +866,12 @@ def var(self) -> SFS: Variance of the branch length of each frequency class, the diagonal of :attr:`UnfoldedSFSDistribution.cov `. """ - batched = self._cov_batched - if batched is not None: - return SFS(np.diag(np.asarray(batched.data))) + positions, mean, cross = self._second_moments - if 'cov' in self.__dict__ and self._cov_stacked(): - return SFS(np.diag(np.asarray(self.cov.data))) + var = np.zeros(self.lineage_config.n + 1) + var[[pos[0] for pos in positions]] = np.diag(cross) - mean ** 2 - return self.moment(k=2, center=True) + return SFS(var) def get_cov(self, i: int, j: int) -> float: """ @@ -1478,7 +1408,9 @@ def sample(self, n_samples: int, seed: Union[int, np.random.Generator] = None) - :param seed: Integer seed of a :class:`numpy.random.Generator`, or the generator itself. ``None`` draws fresh entropy. :return: Array of shape ``(n_samples, *shape)``, whose means over the first axis estimate :attr:`mean`. + :raises ValueError: If ``n_samples`` is not a non-negative integer. """ + n_samples = _n_samples(n_samples) configs = self._get_configs() rewards = [CombinedReward([self.reward, JointSFSReward(c)]) for c in configs] sampled = self._sample(n_samples, rewards=rewards, rng=np.random.default_rng(seed)) @@ -1503,10 +1435,11 @@ def to_empirical( :param seed: Integer seed of a :class:`numpy.random.Generator`, or the generator itself. ``None`` draws fresh entropy. :return: The empirical joint spectrum. + :raises ValueError: If ``n_samples`` is not a positive integer. """ from .empirical import EmpiricalJointSFSDistribution, MsprimeCoalescent - samples = self.sample(n_samples, seed=seed) # (n_samples, *shape) + samples = self.sample(_n_samples(n_samples, minimum=1), seed=seed) # (n_samples, *shape) # non-central moments of orders 1 .. max (matching the msprime joint-SFS ground truth) max_order = MsprimeCoalescent._jsfs_max_order @@ -1831,15 +1764,13 @@ def var(self) -> JointSFS: Variance of the branch length of each joint site-frequency spectrum bin, the diagonal of :attr:`JointSFSDistribution.cov `. """ - batched = self._cov_batched - if batched is not None: - configs, cov = batched - out = np.zeros(self.shape) - for a, config in enumerate(configs): - out[config] = cov[a, a] - return JointSFS(out, pop_names=self.lineage_config.pop_names) + configs, mean, cross = self._second_moments - return self.moment(k=2, center=True) + out = np.zeros(self.shape) + for a, config in enumerate(configs): + out[config] = cross[a, a] - mean[a] ** 2 + + return JointSFS(out, pop_names=self.lineage_config.pop_names) def get_cov( self, @@ -1864,37 +1795,6 @@ def get_cov( ) ) - @cached_property - def _cov_batched(self) -> Optional[Tuple[List[Tuple[int, ...]], np.ndarray]]: - """ - Batched joint-SFS covariance, contracting ``_two_point_occupation`` with the stacked bin rewards as in - ``PhaseTypeDistribution.moment``. Cached so that ``cov`` and ``var`` share one solve. - - :return: ``(configs, cov)`` with ``cov`` the bins-by-bins covariance over the polymorphic ``configs``, or - ``None`` when not applicable, and callers evaluate per pair. - """ - if not Settings.closed_form_last_epoch: - return None - - two_point = self._two_point_occupation() - if two_point is None: - return None - - m, solve, idx_t = two_point - ss = self.state_space - configs = self._get_configs() - R = np.column_stack([ - np.asarray(CombinedReward([self.reward, JointSFSReward(config)])._get(ss), dtype=float)[idx_t] - for config in configs - ]) - - sfs_matrix = (m[:, None] * R).T @ solve(R) # R^T diag(m) (-T)^{-1} R (one ordering) - self._logger.debug("jsfs.cov: centering with the outer product of bin means") - mean = np.array([self.mean.data[config] for config in configs]) - cov = (sfs_matrix + sfs_matrix.T) - np.outer(mean, mean) - - return configs, cov - @cached_property @BlasThreadLimit() def cov(self) -> np.ndarray: @@ -1904,26 +1804,13 @@ def cov(self) -> np.ndarray: between bins ``(a_0, ..., a_{P-1})`` and ``(b_0, ..., b_{P-1})``. Evaluated as described in :meth:`PhaseTypeDistribution.moment() `. """ - batched = self._cov_batched - if batched is not None: - self._logger.debug("jsfs.cov: batched (shared two-point occupation)") - configs, cov = batched - out = np.zeros(self.shape + self.shape) - for a, config_a in enumerate(configs): - for b, config_b in enumerate(configs): - out[tuple(config_a) + tuple(config_b)] = cov[a, b] - return out - - configs = self._get_configs() - pairs = [(a, b) for a in configs for b in configs] - - self._logger.debug("jsfs.cov: per-pair matrix exponential over %d config pairs", len(pairs)) - - results = [self.get_cov(a, b) for a, b in pairs] + configs, mean, cross = self._second_moments + cov = cross - np.outer(mean, mean) out = np.zeros(self.shape + self.shape) - for (a, b), result in zip(pairs, results): - out[tuple(a) + tuple(b)] = result + for a, config_a in enumerate(configs): + for b, config_b in enumerate(configs): + out[config_a + config_b] = cov[a, b] return out @@ -2066,7 +1953,7 @@ class :math:`i` at locus 0 and class :math:`j` at locus 1, which has no univaria "class, use the single-locus spectrum: pg.Coalescent(...).sfs.cdf / .pdf and their .plot()." ) - plot_cdf = bin = _no_univariate_distribution + plot_pdf = plot_cdf = bin = _no_univariate_distribution cdf = pdf = quantile = property(_no_univariate_distribution) def _unsupported(self, *args, **kwargs) -> NoReturn: @@ -2106,8 +1993,7 @@ def gradient(self, k: int = 1) -> 'DemographyGradient': :return: The derivatives. :raises NotImplementedError: If ``k`` is a positive integer other than one, or the moment is accumulated over a time window. - :raises ValueError: If ``k`` is not a positive integer, if absorption is not certain in the last epoch, or if - the generator is not affine in the rates. + :raises ValueError: If ``k`` is not a positive integer, or if absorption is not certain in the last epoch. :raises TypeError: If ``k`` is not a number. """ k = _validate_order(k) @@ -2330,57 +2216,25 @@ def mean(self) -> TwoLocusSFS: and evaluated as described in :meth:`PhaseTypeDistribution.moment() `. """ - batched = self._mean_batched() - if batched is not None: - return batched - - n = self.lineage_config.n - indices = [(i, j) for i in self._get_indices() for j in self._get_indices()] - - results = [ - PhaseTypeDistribution.moment(self, k=2, permute=False, center=False, rewards=self._bin_rewards(i, j)) - for i, j in indices - ] + indices = self._get_indices() + _, cross = self._second_moments - out = np.zeros((n + 1, n + 1)) - for (i, j), result in zip(indices, results): - out[i, j] = result + out = np.zeros((self.lineage_config.n + 1,) * 2) + out[np.ix_(indices, indices)] = cross[:len(indices), len(indices):] # symmetrize over the two (exchangeable) loci, as for the single-locus SFS covariance return TwoLocusSFS((out + out.T) / 2) - def _mean_batched(self) -> Optional[TwoLocusSFS]: + @cached_property + def _second_moments(self) -> Tuple[np.ndarray, np.ndarray]: """ - Batched mean two-locus SFS, contracting ``_two_point_occupation`` with the stacked per-locus bin rewards as in - ``PhaseTypeDistribution.moment``. + The means and the second cross-moments of the rewards of the polymorphic classes at locus 0 and then at locus + 1, from one forward pass, see ``MomentEvaluator._bin_second_moments``. - :return: The mean two-locus SFS, or ``None`` when not applicable, and the caller evaluates per pair. + :return: The means and the cross-moments. """ - two_point = self._two_point_occupation() - if two_point is None: - return None - - m, solve, idx_t = two_point - ss = self.state_space - indices = self._get_indices() - R0 = np.column_stack([ - np.asarray(CombinedReward([self.reward, TwoLocusSFSReward(0, i)])._get(ss), dtype=float)[idx_t] - for i in indices - ]) - R1 = np.column_stack([ - np.asarray(CombinedReward([self.reward, TwoLocusSFSReward(1, j)])._get(ss), dtype=float)[idx_t] - for j in indices - ]) - - uncentered = (m[:, None] * R0).T @ solve(R1) + solve(R0).T @ (m[:, None] * R1) - - n = self.lineage_config.n - out = np.zeros((n + 1, n + 1)) - for a, ia in enumerate(indices): - out[ia, indices] = uncentered[a] - - # symmetrize over the two (exchangeable) loci, as the per-pair path does - return TwoLocusSFS((out + out.T) / 2) + return self._bin_second_moments([CombinedReward([self.reward, TwoLocusSFSReward(locus, i)]) + for locus in (0, 1) for i in self._get_indices()]) def sample_per_locus(self, n_samples: int, seed: Union[int, np.random.Generator] = None) -> Tuple[np.ndarray, np.ndarray]: r""" @@ -2394,7 +2248,9 @@ def sample_per_locus(self, n_samples: int, seed: Union[int, np.random.Generator] :param seed: Integer seed of a :class:`numpy.random.Generator`, or the generator itself. ``None`` draws fresh entropy. :return: The locus-0 and locus-1 branch lengths, each of shape ``(n_samples, n + 1)``. + :raises ValueError: If ``n_samples`` is not a non-negative integer. """ + n_samples = _n_samples(n_samples) indices = self._get_indices() rewards = ( [CombinedReward([self.reward, TwoLocusSFSReward(0, i)]) for i in indices] + @@ -2423,6 +2279,7 @@ def sample(self, n_samples: int, seed: Union[int, np.random.Generator] = None) - :param seed: Integer seed of a :class:`numpy.random.Generator`, or the generator itself. ``None`` draws fresh entropy. :return: Array of shape ``(n_samples, n + 1, n + 1)``. + :raises ValueError: If ``n_samples`` is not a non-negative integer. """ left, right = self.sample_per_locus(n_samples, seed=seed) @@ -2443,10 +2300,11 @@ def to_empirical( :param seed: Integer seed of a :class:`numpy.random.Generator`, or the generator itself. ``None`` draws fresh entropy. :return: The empirical two-locus spectrum. + :raises ValueError: If ``n_samples`` is not a positive integer. """ from .empirical import EmpiricalTwoLocusSFSDistribution - return EmpiricalTwoLocusSFSDistribution(*self.sample_per_locus(n_samples, seed=seed), + return EmpiricalTwoLocusSFSDistribution(*self.sample_per_locus(_n_samples(n_samples, minimum=1), seed=seed), lineage_config=self._layout_lineages, locus_config=self._layout_loci) @cached_property @@ -2501,11 +2359,8 @@ def _locus_marginals(self) -> Tuple[Dict[int, float], Dict[int, float]]: :return: The means and variances, keyed by bin. """ - indices = self._get_indices() - - def moment(i: int, k: int) -> float: - reward = CombinedReward([self.reward, TwoLocusSFSReward(0, i)]) - return PhaseTypeDistribution.moment(self, k=k, center=k == 2, rewards=(reward,) * k) + mean, cross = self._second_moments - return {i: moment(i, 1) for i in indices}, {i: moment(i, 2) for i in indices} + return ({i: float(mean[a]) for a, i in enumerate(self._get_indices())}, + {i: float(cross[a, a] - mean[a] ** 2) for a, i in enumerate(self._get_indices())}) diff --git a/phasegen/expm.py b/phasegen/expm.py index a14a1112..909bb0e1 100644 --- a/phasegen/expm.py +++ b/phasegen/expm.py @@ -6,16 +6,18 @@ exponentials, for which the default SciPy backend is faster than the TensorFlow, Jax and PyTorch ones, whose per-call overhead dominates at these sizes. -Two operations are exposed: the dense matrix exponential :math:`\\exp(\\mathbf{A})` -(:meth:`ExpmBackend.compute() `) and its action +Three operations are exposed: the dense matrix exponential :math:`\\exp(\\mathbf{A})` +(:meth:`ExpmBackend.compute() `), its action :math:`\\exp(\\mathbf{A})\\mathbf{v}` on a vector or thin matrix -(:meth:`ExpmBackend.compute_action() `). - -A registered backend reaches the Van Loan evaluation of moments, the tree-height distribution functions and the -mutational configurations. The Laplace transform of an accumulated reward always calls SciPy. The occupation times of -spectra call SciPy above :attr:`Settings.closed_form_sparse_min_states -` and :attr:`Settings.expm_action_min_dim -`, and the registered backend below them. +(:meth:`ExpmBackend.compute_action() `), and that action at equally spaced +multiples of :math:`\\mathbf{A}` +(:meth:`ExpmBackend.compute_action_interval() `). + +A registered backend reaches the Van Loan evaluation of moments and the tree-height distribution functions. The +Laplace transform of an accumulated reward always calls SciPy. The occupation times of spectra call SciPy above +:attr:`Settings.closed_form_sparse_min_states ` and where +:attr:`Settings.expm_method ` selects the action, and the registered backend +otherwise. """ import logging from abc import ABC, abstractmethod @@ -46,11 +48,12 @@ class _GrowthBound: A bound :math:`G(f) \ge f^{-1} \int_0^f \|\exp(s \mathbf{A})\|_1\, ds` for :meth:`Backend._stationary() `. With :math:`\mathbf{A} = \mathbf{D} + \mathbf{N}` split into its :math:`L` diagonal blocks :math:`\mathbf{D}` and the strictly block triangular rest - :math:`\mathbf{N}`, the Dyson series of :math:`\exp(s \mathbf{A})` ends after :math:`L` terms, so that + :math:`\mathbf{N}`, the Dyson series of :math:`\exp(s \mathbf{A})` ends after :math:`d` terms, where + :math:`d \le L` is the length of the longest chain of blocks that :math:`\mathbf{N}` couples plus one, so that .. math:: G(f) = \min_{p \in \{1, \infty\}} c_p \Big( \varphi(f m_p) + e^{f m_p} - \sum_{j=1}^{L-1} \frac{(f \beta_p)^j}{(j + 1)!} \Big), + \sum_{j=1}^{d-1} \frac{(f \beta_p)^j}{(j + 1)!} \Big), with :math:`m_p = \max(0, \mu_p(\mathbf{D}))` the positive part of the logarithmic :math:`p`-norm, :math:`\mu_1(\mathbf{D}) = \max_j (d_{jj} + \sum_{i \ne j} |d_{ij}|)` and :math:`\mu_\infty(\mathbf{D}) = @@ -59,11 +62,12 @@ class _GrowthBound: the :math:`\infty`-norm bound to the 1-norm. For a transposed generator and :math:`L = 1`, :math:`G = 1`. """ - def __init__(self, a, abs_a, blocks: int = 1) -> None: + def __init__(self, a, abs_a, blocks: int = 1, depth: int = None) -> None: r""" :param a: Square matrix :math:`\mathbf{A}`. :param abs_a: Its entrywise absolute value. :param blocks: The number :math:`L` of equal diagonal blocks. + :param depth: The number :math:`d` of terms of the Dyson series, by default :math:`L`. """ coo = scipy.sparse.coo_matrix(abs_a) dim = a.shape[0] @@ -73,6 +77,9 @@ def __init__(self, a, abs_a, blocks: int = 1) -> None: #: The number of blocks :math:`L`. self.blocks: int = blocks + #: The number of terms :math:`d` of the Dyson series. + self.depth: int = blocks if depth is None else depth + #: The triples :math:`(c_p, m_p, \beta_p)` for :math:`p = 1, \infty`. self.norms: list = [] for c, axis in ((1.0, coo.col), (float(dim), coo.row)): @@ -85,7 +92,7 @@ def __call__(self, f: float) -> float: :param f: The fraction :math:`f \ge 0`. :return: :math:`G(f)`, possibly infinite. """ - j = np.arange(1, self.blocks) + j = np.arange(1, self.depth) out = np.inf with np.errstate(over='ignore', invalid='ignore'): for c, m, beta in self.norms: @@ -131,6 +138,31 @@ def compute_action(self, a, b: np.ndarray) -> np.ndarray: return self.compute(a_dense) @ b + def compute_action_interval(self, a, b: np.ndarray, stop: float, num: int) -> np.ndarray: + """ + Compute the actions :math:`\\exp(s_j \\mathbf{A})\\mathbf{v}` at :math:`s_j = j\\, s / q` for + :math:`j = 1, \\ldots, q`, with :math:`s` the ``stop`` and :math:`q` the ``num``. + + The default implementation forms the dense exponential of one step via :meth:`compute` and applies it + :math:`q` times. :class:`SciPyExpmBackend` overrides it with the interval algorithm of Al-Mohy and Higham + (2011) in :func:`scipy.sparse.linalg.expm_multiply`. + + :param a: Matrix (typically a sparse matrix). + :param b: Vector or thin matrix. + :param stop: The largest multiple :math:`s`. + :param num: The number of multiples :math:`q`. + :return: The actions, stacked along the first axis. + """ + a_dense = a.toarray() if hasattr(a, 'toarray') else np.asarray(a) + P = self.compute(a_dense * (stop / num)) + + out = [] + for _ in range(num): + b = P @ b + out.append(b) + + return np.stack(out) + class TensorFlowExpmBackend(ExpmBackend): """ @@ -217,6 +249,25 @@ def compute_action(self, a, b: np.ndarray) -> np.ndarray: return expm_multiply(a.astype(self.precision), np.asarray(b, dtype=self.precision)) + def compute_action_interval(self, a, b: np.ndarray, stop: float, num: int) -> np.ndarray: + """ + Compute the actions :math:`\\exp(s_j \\mathbf{A})\\mathbf{v}` at :math:`s_j = j\\, s / q` for + :math:`j = 1, \\ldots, q`, with :math:`s` the ``stop`` and :math:`q` the ``num``, by the interval algorithm of + Al-Mohy and Higham (2011) in :func:`scipy.sparse.linalg.expm_multiply`. + + :param a: Matrix (typically a sparse matrix). + :param b: Vector or thin matrix. + :param stop: The largest multiple :math:`s`. + :param num: The number of multiples :math:`q`. + :return: The actions, stacked along the first axis. + """ + from scipy.sparse.linalg import expm_multiply + + return expm_multiply( + a.astype(self.precision), np.asarray(b, dtype=self.precision), start=0.0, stop=stop, num=num + 1, + endpoint=True + )[1:] + class JaxExpmBackend(ExpmBackend): """ @@ -290,7 +341,14 @@ def expm(cls, m: np.ndarray) -> np.ndarray: return cls._writable(cls.backend.compute(m)) @classmethod - def expm_multiply(cls, a, b: np.ndarray, action: Callable = None, blocks: int = 1) -> np.ndarray: + def expm_multiply( + cls, + a, + b: np.ndarray, + action: Callable = None, + blocks: int = 1, + depth: int = None + ) -> np.ndarray: """ Compute the action of the matrix exponential, :math:`\\exp(\\mathbf{A})\\mathbf{v}` (``exp(a) @ b``), via the active backend, as a writable NumPy array. An argument of 1-norm above ``_ACTION_STEP_NORM`` is applied in steps @@ -301,6 +359,7 @@ def expm_multiply(cls, a, b: np.ndarray, action: Callable = None, blocks: int = :param b: Vector or thin matrix. :param action: The action ``exp(a) @ b`` of one step, by default that of the active backend. :param blocks: The number of equal diagonal blocks of ``a`` outside of which it is strictly block triangular. + :param depth: The length of the longest chain of blocks that ``a`` couples plus one, by default ``blocks``. :return: ``exp(a) @ b``. """ action = cls.backend.compute_action if action is None else action @@ -310,7 +369,7 @@ def expm_multiply(cls, a, b: np.ndarray, action: Callable = None, blocks: int = return cls._writable(action(a, b)) abs_a, v, done = abs(a), b, 0.0 - growth = _GrowthBound(a, abs_a, blocks) + growth = _GrowthBound(a, abs_a, blocks, depth) for f in cls._step_fractions(norm): v = cls._writable(action(a * (f - done), v)) done = f @@ -319,6 +378,45 @@ def expm_multiply(cls, a, b: np.ndarray, action: Callable = None, blocks: int = return v + @classmethod + def expm_multiply_interval( + cls, + a, + b: np.ndarray, + stop: float, + num: int, + interval: Callable = None, + advance: Callable = None + ) -> np.ndarray: + """ + Compute the actions :math:`\\exp(s_j \\mathbf{A})\\mathbf{v}` at :math:`s_j = j\\, s / q` for + :math:`j = 1, \\ldots, q`, with :math:`s` the ``stop`` and :math:`q` the ``num``, via the active backend, as + a writable NumPy array. Where the 1-norm of :math:`s \\mathbf{A}` exceeds the norm above which + :meth:`expm_multiply` steps, the steps are applied one by one by ``advance``. + + :param a: Matrix (typically a sparse matrix). + :param b: Vector or thin matrix. + :param stop: The largest multiple :math:`s`. + :param num: The number of multiples :math:`q`. + :param interval: The actions ``interval(a, b, stop, num)``, by default those of the active backend. + :param advance: The action ``advance(v, tau)`` of :math:`\\exp(\\tau \\mathbf{A})` on ``v``, by default + :meth:`expm_multiply`. + :return: The actions, stacked along the first axis. + """ + interval = cls.backend.compute_action_interval if interval is None else interval + norm = float(abs(a).sum(axis=0).max()) * stop if a.shape[0] else 0.0 + + if np.isfinite(norm) and norm <= _ACTION_STEP_NORM: + return cls._writable(interval(a, b, stop, num)) + + advance = (lambda v, tau: cls.expm_multiply(a * tau, v)) if advance is None else advance + out = [] + for _ in range(num): + b = advance(b, stop / num) + out.append(b) + + return np.stack(out) + @staticmethod def _step_fractions(norm: float) -> np.ndarray: """ diff --git a/phasegen/gradient.py b/phasegen/gradient.py index cbf94d8a..1b9509ae 100644 --- a/phasegen/gradient.py +++ b/phasegen/gradient.py @@ -13,7 +13,7 @@ from ._blas import BlasThreadLimit from .distributions import Coalescent, DemographyGradient from .distributions._common import _sqrt_spectrum, _validate_order -from .distributions._gradient import _generator_basis, _passes, _rate_parameters +from .distributions._gradient import _passes, _rate_parameters from .spectrum import AbstractSpectrum #: The distributions of a :class:`~phasegen.distributions.Coalescent` whose moments the gradient supports. @@ -515,7 +515,7 @@ def value(y: float) -> Any: def supported(self, params: Dict[str, float]) -> bool: """ Whether the statistic has an exact Jacobian at the given parameters. This holds if it reads only the moments - listed in :class:`~phasegen.gradient.Gradient`, of state spaces whose generator is affine in the rates. + listed in :class:`~phasegen.gradient.Gradient`. :param params: The parameters. :return: Whether the Jacobian at these parameters is exact. @@ -534,27 +534,7 @@ def _unsupported_reason(self, params: Dict[str, float]) -> Optional[str]: except Exception: return None - if recorder.rejection is not None: - return recorder.rejection - - try: - for read in recorder.reads: - _generator_basis(self._host(read).state_space) - except ValueError as e: - return str(e) - - return None - - @staticmethod - def _host(read: _Read) -> Any: - """ - The distribution whose state space carries the reward vectors of a read, that of the flattened mean for an SFS - of the standard coalescent. - - :param read: The read. - :return: The distribution. - """ - return read.dist._mean_host() if read.kind == 'mean' else read.dist + return recorder.rejection def _record(self, coal: Coalescent) -> Optional[Tuple[np.ndarray, _CoalescentRecorder]]: """ @@ -595,8 +575,8 @@ def _exact(self, params: Dict[str, float], :param params: The parameters. :param bounds: The bounds of the parameters. :return: The entries and the Jacobian, or ``None`` where the statistic reads an unsupported quantity, a moment - is windowed, an entry is not finite, absorption is not certain in the last epoch, the generator is not affine - in the rates, or the value of the backward pass differs from the moments. + is windowed, an entry is not finite, absorption is not certain in the last epoch, or the value of the backward + pass differs from the moments. """ coal = self.coal(**params) record = self._record(coal) @@ -725,19 +705,13 @@ def _derivatives(self, hosts: Dict[tuple, list], contraction: np.ndarray, :param hosts: The host and its weighted orderings of ``_group_terms``, by key. :param contraction: The weighted values of each column, against which the backward passes are checked. :param magnitude: The sum of the moduli of the weighted values of each column. - :return: The derivatives, or ``None`` where the generator is not affine in the rates, absorption is not certain - in the last epoch, or the value of the backward pass differs from the moments. + :return: The derivatives, or ``None`` where absorption is not certain in the last epoch or the value of the + backward pass differs from the moments. """ n_columns = len(contraction) adjoint = np.zeros(n_columns) derivatives = [] for host, terms in hosts.values(): - try: - _generator_basis(host.state_space) - except ValueError as e: - self._log.info("%s Using finite differences.", e) - return None - outs = _passes(host, terms, n_columns) if outs is None: return None diff --git a/phasegen/inference.py b/phasegen/inference.py index d13c9e00..d2c79c71 100644 --- a/phasegen/inference.py +++ b/phasegen/inference.py @@ -714,10 +714,16 @@ def _optimize( exact, log_scale, penalty) # the optimizer sees the free parameters, with y = log(x) for those on a logarithmic scale, and dL/dy = x dL/dx, - # with x clipped to its bounds + # with x clipped to its bounds and equal to a bound where log(x) is at the logarithm of that bound + y_bounds = [(np.log(lo), np.log(hi)) if is_log else (lo, hi) + for lo, hi, is_log in zip(lower[free], upper[free], log[free])] + y_lower, y_upper = np.array(y_bounds, dtype=float).reshape(-1, 2).T + def to_x(y: np.ndarray) -> np.ndarray: x = start.copy() x[free] = np.where(log[free], np.clip(np.exp(np.where(log[free], y, 0)), lower[free], upper[free]), y) + x[free] = np.where(log[free] & (y <= y_lower), lower[free], + np.where(log[free] & (y >= y_upper), upper[free], x[free])) return x def fun(y: np.ndarray) -> Any: @@ -733,8 +739,7 @@ def fun(y: np.ndarray) -> Any: fun=fun, x0=np.where(log, np.log(np.where(log, start, 1)), start)[free], method=method_mle, - bounds=[(np.log(lo), np.log(hi)) if is_log else (lo, hi) - for lo, hi, is_log in zip(lower[free], upper[free], log[free])], + bounds=y_bounds, jac=smooth or None, options=opts, callback=penalized.update diff --git a/phasegen/lineage.py b/phasegen/lineage.py index 5ca0ad97..4d50b705 100644 --- a/phasegen/lineage.py +++ b/phasegen/lineage.py @@ -116,4 +116,7 @@ def __eq__(self, other) -> bool: :param other: Other lineage configuration :return: Whether the two lineage configurations are equal """ + if not isinstance(other, LineageConfig): + return NotImplemented + return list(self.lineage_dict.items()) == list(other.lineage_dict.items()) diff --git a/phasegen/locus.py b/phasegen/locus.py index 5254fae6..fbe4084f 100644 --- a/phasegen/locus.py +++ b/phasegen/locus.py @@ -103,6 +103,9 @@ def __eq__(self, other) -> bool: :param other: Other locus configuration :return: Whether the two locus configurations are equal """ + if not isinstance(other, LocusConfig): + return NotImplemented + return ( self.n == other.n and self.n_unlinked == other.n_unlinked diff --git a/phasegen/rewards.py b/phasegen/rewards.py index 596fa0eb..a7976892 100644 --- a/phasegen/rewards.py +++ b/phasegen/rewards.py @@ -159,7 +159,11 @@ def support(state_space: Type[StateSpace], rewards: Iterable['Reward']) -> bool: return all([reward.supports(state_space) for reward in rewards]) @staticmethod - def _check_accumulable(state_space: StateSpace, rewards: Iterable['Reward']) -> None: + def _check_accumulable( + state_space: StateSpace, + rewards: Iterable['Reward'], + vectors: Iterable[np.ndarray] = None + ) -> None: r""" Check that the rewards vanish on the absorbing states of the state space. The reward accumulated up to absorption is determined by the transient entries alone, so a reward with mass on an absorbing state is @@ -167,10 +171,13 @@ def _check_accumulable(state_space: StateSpace, rewards: Iterable['Reward']) -> :param state_space: The state space the rewards are resolved against. :param rewards: The rewards to accumulate. + :param vectors: The reward vectors of ``rewards`` on the state space, if already resolved. :raises ValueError: If a reward is not a vector with one entry per state, or is non-zero on an absorbing state. """ - for reward in rewards: - values = np.asarray(reward._get(state_space), dtype=float) + rewards = list(rewards) + vectors = [r._get(state_space) for r in rewards] if vectors is None else vectors + for reward, values in zip(rewards, vectors): + values = np.asarray(values, dtype=float) if values.shape != (state_space.k,): raise ValueError( diff --git a/phasegen/settings.py b/phasegen/settings.py index bf963877..628d25f4 100644 --- a/phasegen/settings.py +++ b/phasegen/settings.py @@ -2,7 +2,7 @@ Settings for the PhaseGen application. """ from contextlib import contextmanager -from typing import Any, Iterator, Optional +from typing import Any, Iterator, Literal, Optional class _SettingsMeta(type): @@ -20,7 +20,12 @@ def __setattr__(cls, name: str, value: Any): :param name: Name of the setting. :param value: Value to assign. :raises AttributeError: If no setting of that name exists. + :raises ValueError: If :attr:`Settings.expm_method` is given a value other than ``'auto'``, ``'dense'`` or + ``'action'``. """ + if name == 'expm_method' and value not in ('auto', 'dense', 'action'): + raise ValueError(f"Settings.expm_method must be 'auto', 'dense' or 'action', got {value!r}.") + if not name.startswith('_') and not hasattr(cls, name): available = ', '.join(sorted(n for n in vars(cls) if not n.startswith('_'))) raise AttributeError( @@ -37,8 +42,8 @@ class Settings(metaclass=_SettingsMeta): The attributes are class-level and read directly (e.g. ``Settings.use_pbar = True``). Assigning a name that is not declared here raises :class:`AttributeError`. """ - #: Whether to evaluate the mean site-frequency spectrum of a single population and locus under the standard - #: coalescent on the lineage-counting state space, see :meth:`PhaseTypeDistribution.moment() + #: Whether to compute the moments of the site-frequency spectrum of a single population and locus under the + #: standard coalescent on the smaller lineage-counting state space, see :meth:`PhaseTypeDistribution.moment() #: `. flatten_block_counting: bool = True @@ -65,10 +70,13 @@ class Settings(metaclass=_SettingsMeta): #: pure-Python construction. use_numba: bool = True - #: Matrix dimension at or above which a matrix exponential is applied to a vector by the action algorithm and not - #: formed densely. It applies to moments, distribution functions, mutational configurations and the Laplace - #: transforms of reward distributions. The result is unchanged. Set to 0 or very large to force either path. - expm_action_min_dim: int = 1500 + #: How matrix exponentials are evaluated for moments, distribution functions and the Laplace transforms of reward + #: distributions. ``'dense'`` forms each exponential, at memory quadratic and cost cubic in its dimension, and + #: suits small state spaces only. ``'action'`` applies each exponential to its vector (Al-Mohy and Higham, 2011). + #: ``'auto'`` takes whichever is cheaper by a cost model in the dimension, the number of exponentials and the 1-norm + #: of the matrix times the step, and the action for large dimensions to bound memory. All three agree up to + #: rounding. + expm_method: Literal['auto', 'dense', 'action'] = 'auto' #: Number of BLAS threads while moments, their gradients and inferences are evaluated, or ``None`` to leave them #: unchanged. More threads gain little on these small matrices, and with the NumPy and SciPy wheels, which each @@ -84,8 +92,8 @@ class Settings(metaclass=_SettingsMeta): #: sparse block-triangular LU factorization and not a dense one. It applies to the closed-form moments (see #: :meth:`PhaseTypeDistribution.moment() `), the last-epoch #: solve of the Laplace transform and the multi-epoch mutational configurations, where it is compared against the - #: number of count vectors times the number of transient states. The result is unchanged. Set to 0 to always use - #: the sparse path, or very large to always use the dense path. + #: number of transient states of the solve shared by all count vectors. The result is unchanged. Set to 0 to always + #: use the sparse path, or very large to always use the dense path. closed_form_sparse_min_states: int = 256 #: State count at or above which the rate matrix is stored sparse. The sparse solves and actions read the sparse diff --git a/phasegen/state_space.py b/phasegen/state_space.py index 75e42c70..c3bd1b8a 100644 --- a/phasegen/state_space.py +++ b/phasegen/state_space.py @@ -33,7 +33,7 @@ from .initial import InitialDistribution from .lineage import LineageConfig from .locus import LocusConfig -from .state_space_numba import build_rate_matrix +from .state_space_numba import build_transitions logger = logging.getLogger('phasegen') @@ -68,6 +68,154 @@ def _numba_model_params(model: CoalescentModel) -> Tuple[int, float, float, floa _WARNED_SIZES: set = set() +class _GeneratorBasis: + r""" + The intensity matrix of a state space as a combination of fixed parts on one sparsity pattern, + + .. math:: + \mathbf{S} = \mathbf{K} + \sum_d \frac{\mathbf{C}_d}{s(N_d)} + \sum_{a \neq b} m_{ab} \mathbf{M}_{ab}, + + where :math:`N_d` is the population size of deme :math:`d`, :math:`s(N)` the time scale of the coalescent model at + size :math:`N`, :math:`m_{ab}` the backward migration rate from deme :math:`a` to deme :math:`b`, + :math:`\mathbf{C}_d` the coalescence part of deme :math:`d` at unit inverse time scale, :math:`\mathbf{M}_{ab}` the + migration part at unit rate, and :math:`\mathbf{K}` the part depending on neither, the recombination of two loci. + Each part has zero row sums. Part 0 is :math:`\mathbf{K}`, parts :math:`1, \dots, D` the coalescence of the + :math:`D` demes, and the remaining parts the migration of the ordered pairs :attr:`pairs`. + """ + + def __init__( + self, + states: List['State'], + src: np.ndarray, + dst: np.ndarray, + rates: np.ndarray, + parts: np.ndarray, + pops: List[str], + model: CoalescentModel + ) -> None: + """ + Fix the sparsity pattern of the transitions and the diagonal. + + :param states: The states. + :param src: The source state of each transition. + :param dst: The target state of each transition. + :param rates: The rate of each transition in its part. + :param parts: The part of each transition. + :param pops: The demes. + :param model: The coalescent model, whose time scale weights the coalescence parts. + """ + n = len(states) + + #: The states, in the row order of the rate matrix. + self.states: List['State'] = states + + #: The demes. + self.pops: List[str] = list(pops) + + #: The ordered pairs of demes of the migration parts. + self.pairs: List[Tuple[str, str]] = [(a, b) for a in self.pops for b in self.pops if a != b] + + #: The coalescent model, whose time scale weights the coalescence parts. + self.model: CoalescentModel = model + + #: The source state, rate in its part and part of each transition. + self.src, self.rates, self.parts = src, rates, parts + + # every transition and diagonal entry lands on one entry of the CSR pattern, duplicates being summed + keys = np.concatenate([src, np.arange(n)]) * n + np.concatenate([dst, np.arange(n)]) + # a stable sort, fast on keys the enumeration lists by ascending source + order = np.argsort(keys, kind='stable') + ordered = keys[order] + first = np.concatenate([[True], ordered[1:] != ordered[:-1]]) + self._entry = np.empty(len(keys), dtype=np.int64) + self._entry[order] = np.cumsum(first) - 1 + self._rows, self._cols = np.divmod(ordered[first], n) + self._diagonal = self._rows == self._cols + + @property + def n_parts(self) -> int: + """ + The number of parts. + """ + return 1 + len(self.pops) + len(self.pairs) + + def coefficients(self, pop_sizes: Dict[str, float], migration_rates: Dict[Tuple[str, str], float]) -> np.ndarray: + """ + The coefficients of the parts, one, the inverse time scales and the migration rates, as numerators (first + row) and denominators (second row), so that a coalescence rate is divided by the time scale. + + :param pop_sizes: The population sizes by deme. + :param migration_rates: The migration rates by ordered pair, zero where absent. + :return: The numerators and denominators. + """ + n_pops = len(self.pops) + + numerators = [1.0] * (1 + n_pops) + [migration_rates.get(pair, 0.0) for pair in self.pairs] + denominators = [1.0] + [self.model._get_timescale(pop_sizes[p]) for p in self.pops] + [1.0] * len(self.pairs) + + return np.array([numerators, denominators]) + + def matrix(self, coefficients: np.ndarray, dense: bool = False) -> 'np.ndarray | sp.csr_matrix': + """ + The combination of the parts. The sparse form leaves out the off-diagonal entries that are zero. + + :param coefficients: The numerators and denominators of the coefficients of the parts. + :param dense: Whether to return a dense array, otherwise a :class:`scipy.sparse.csr_matrix`. + :return: The matrix. + """ + n = len(self.states) + rates = self.rates * coefficients[0][self.parts] / coefficients[1][self.parts] + terms = np.concatenate([rates, -np.bincount(self.src, weights=rates, minlength=n)]) + data = np.bincount(self._entry, weights=terms, minlength=len(self._rows)) + + if dense: + S = np.zeros((n, n)) + S[self._rows, self._cols] = data + return S + + keep = (data != 0) | self._diagonal + indptr = np.concatenate([[0], np.cumsum(np.bincount(self._rows[keep], minlength=n))]) + + return sp.csr_matrix((data[keep], self._cols[keep], indptr), shape=(n, n)) + + def part(self, i: int) -> sp.csr_matrix: + """ + A part on its own. + + :param i: The part. + :return: The part. + """ + return self.matrix(np.stack([np.eye(self.n_parts)[i], np.ones(self.n_parts)])) + + @staticmethod + def _parts(totals: np.ndarray, src: np.ndarray, dst: np.ndarray) -> np.ndarray: + """ + The part of each transition, from the change of the number of lineages per deme: a coalescence reduces the + number in one deme, a migration moves lineages between two demes, and a recombination changes no deme or + adds a lineage. + + :param totals: The number of lineages per state and deme. + :param src: The source state of each transition. + :param dst: The target state of each transition. + :return: The parts. + """ + n_demes = totals.shape[1] + delta = np.take(totals, dst, axis=0) - np.take(totals, src, axis=0) + total = totals.sum(axis=1) + change = total[dst] - total[src] + lose, gain = delta.argmin(axis=1), delta.argmax(axis=1) + + parts = np.zeros(len(src), dtype=np.int64) + coalescence = change < 0 + parts[coalescence] = 1 + lose[coalescence] + # a change summing to zero is a migration unless it is none, where the first deme is both minimum and maximum + migration = (change == 0) & (lose != gain) + parts[migration] = (1 + n_demes + lose[migration] * (n_demes - 1) + gain[migration] - + (gain[migration] > lose[migration])) + + return parts + + class StateSpace(ABC): r""" Abstract base class for coalescent state spaces. @@ -94,11 +242,8 @@ class StateSpace(ABC): #: Initial distribution over locus configurations, ``None`` for the single configuration :attr:`locus_config` locus_distribution: InitialDistribution | None = None - #: Rate matrix of the epoch left last, keyed by that epoch, restored by :meth:`update_epoch` on returning to it - _previous_S: Dict[Epoch, np.ndarray] = {} - - #: The basis of the generator kept for the exact gradients of moments, or the error of a space without one. - _generator_basis: Any = None + #: The derivatives of the generator kept for the exact gradients of moments. + _generator_derivatives: Any = None def __init__( self, @@ -156,43 +301,99 @@ def __init__( #: Epoch self.epoch: Epoch = epoch - #: Transitions and states per epoch of the pure-Python construction - self._cache: Dict[Epoch, Tuple[Dict[Tuple['State', 'State'], Tuple[float, str]], List['State']]] = {} - - # time in seconds to compute original rate matrix + #: Time in seconds taken to enumerate the states and transitions self.time: float | None = None @cached_property def states(self) -> List['State']: """ - The states of the space, in the row order of :attr:`StateSpace.S `. - - :raises ModelError: If a population size of the current epoch is not positive. + The states of the space, in the row order of :attr:`StateSpace.S `. They + do not depend on the epoch. """ - # both constructions evaluate the rates of the current epoch - self._assert_positive_sizes(self.epoch) + return self._basis.states - start = time.time() + @cached_property + def _basis(self) -> _GeneratorBasis: + """ + The basis of the rate matrices of all epochs, from one enumeration of the states and transitions. The states + held by a copy of ``_with`` keep their order. + :raises MemoryError: If the number of states exceeds the cap. + """ # The builder aborts with a MemoryError once the number of states exceeds ``Settings.max_state_space_size``, # for every state-space type and without an a-priori size formula. The cap bounds the number of states, not # the memory, which grows with the width of a state, so the joint block-counting space of several demes can # exhaust memory below it. After a successful build the actual count is warned about (escalating with size), # again for every type. - if self._use_numba(): - states, S = self._construct_numba() - # the states are epoch-independent, but prime the current epoch's rate matrix to avoid rebuilding it - self.__dict__.setdefault('S', S) - else: - transitions, states = self.get_transitions() - self._cache[self.epoch] = (transitions, states) + start = time.time() + states, src, dst, rates = self._enumerate() - # record time to compute rate matrix - self.time = time.time() - start + if 'states' in self.__dict__: + order = {s: i for i, s in enumerate(self.__dict__['states'])} + perm = np.array([order[s] for s in states], dtype=np.int64) + states, src, dst = self.__dict__['states'], perm[src], perm[dst] + + # the number of ancestral lineages per deme, a linked lineage counting once over the loci + lineages = np.array([s.lineages for s in states]) + totals = lineages.sum(axis=(1, 3)) + if lineages.shape[1] > 1: + totals -= (lineages.shape[1] - 1) * np.array([s.linked[0] for s in states]).sum(axis=2) + parts = _GeneratorBasis._parts(totals, src, dst) + + # the pure-Python construction lists coalescence rates at unit population size + if not self._use_numba(): + rates[(parts >= 1) & (parts <= totals.shape[1])] *= self.model._get_timescale(1.0) + + self.time = time.time() - start self._warn_if_large(len(states)) - return states + return _GeneratorBasis(states, src, dst, rates, parts, self.lineage_config.pop_names, self.model) + + def _enumerate(self) -> Tuple[List['State'], np.ndarray, np.ndarray, np.ndarray]: + """ + Enumerate the states and the transitions at unit population sizes and unit migration rates. + + :return: The states, and the source state, target state and rate of each transition. + """ + if self._use_numba(): + init = self._get_initial() + n_blocks = self._numba_n_blocks(init) + model_id, alpha, psi, c = _numba_model_params(self.model) + recomb_rate, recomb0, recomb1 = self._numba_recombination() + + rows, src, dst, rates = build_transitions( + initial=self._numba_initial(init), + kind=self._numba_kind(), + n_demes=init.lineages.shape[1], + n_blocks=n_blocks, + model_id=model_id, + alpha=alpha, + psi=psi, + c=c, + block_vectors=self._numba_block_vectors(n_blocks), + recomb_rate=recomb_rate, + recomb0=recomb0, + recomb1=recomb1, + max_states=Settings.max_state_space_size, + ) + + return [self._numba_to_state(row, init) for row in rows], src, dst, rates + + epoch, pops = self.epoch, self.lineage_config.pop_names + self.epoch = Epoch(pop_sizes={p: 1.0 for p in pops}, + migration_rates={(a, b): 1.0 for a in pops for b in pops if a != b}) + + try: + transitions, states = self.get_transitions() + finally: + self.epoch = epoch + + index = {s: i for i, s in enumerate(states)} + src = np.array([index[a] for a, _ in transitions], dtype=np.int64) + dst = np.array([index[b] for _, b in transitions], dtype=np.int64) + + return states, src, dst, np.array([r for r, _ in transitions.values()], dtype=float) def _warn_if_large(self, n_states: int) -> None: """ @@ -331,11 +532,17 @@ def S(self) -> np.ndarray: the rate of the event taking state :math:`x` to state :math:`y`. The diagonal follows the zero-row-sum convention :math:`s_{xx} = -\sum_{y \ne x} s_{xy}`, so :math:`\mathbf{S}\mathbf{e} = \mathbf{0}`, and the absorption rates are :math:`\mathbf{q} = -\mathbf{T}\mathbf{e}_T` for the transient block :math:`\mathbf{T}`. + It is a dense array below :attr:`Settings.dense_rate_matrix_max_states + ` states and a :class:`scipy.sparse.csr_matrix` from + there on. :raises ModelError: If a population size of the epoch is not positive. """ self._assert_positive_sizes(self.epoch) - return self._get_rate_matrix() + basis = self._basis + + return basis.matrix(basis.coefficients(self.epoch.pop_sizes, self.epoch.migration_rates), + dense=len(basis.states) < Settings.dense_rate_matrix_max_states) def _initial_components(self) -> List[Tuple[float, LineageConfig, LocusConfig]]: """ @@ -426,13 +633,7 @@ def update_epoch(self, epoch: Epoch) -> None: self.S *= self._get_scaling_factor(self.epoch, epoch) else: - # keep the rate matrix of the epoch being left, and restore that of the epoch entered if it was the - # one left last - previous = self._previous_S - self._previous_S = {self.epoch: self.__dict__.pop('S')} if 'S' in self.__dict__ else {} - - if epoch in previous: - self.__dict__['S'] = previous[epoch] + self.drop_S() self.epoch = epoch @@ -470,11 +671,11 @@ def _get_scaling_factor(self, epoch_prev: Epoch, epoch_next: Epoch) -> float: def __getstate__(self) -> dict: """ - The state without the generator basis, which is rebuilt on use. + The state without the derivatives of the generator, which are rebuilt on use. :return: The state. """ - return {k: v for k, v in self.__dict__.items() if k != '_generator_basis'} + return {k: v for k, v in self.__dict__.items() if k != '_generator_derivatives'} def __eq__(self, other) -> bool: """ @@ -497,16 +698,12 @@ def drop_S(self) -> None: """ Drop the current rate matrix. """ - try: - # noinspection all - del self.S - except AttributeError: - pass + self.__dict__.pop('S', None) def _with(self, model: CoalescentModel = None, locus_config: LocusConfig = None) -> 'StateSpace': """ - A copy of the state space with another coalescent model or locus configuration, sharing the states, whose rate - matrices are built anew. + A copy of the state space with another coalescent model or locus configuration, sharing the states in their + order, whose rate matrices are built anew. :param model: The coalescent model, by default that of this space. :param locus_config: The locus configuration, by default that of this space. @@ -526,14 +723,12 @@ def _with(self, model: CoalescentModel = None, locus_config: LocusConfig = None) def drop_cache(self) -> None: """ - Drop the rate matrix cache, the current rate matrix, that of the epoch left last and the generator basis of the - gradients. + Drop the current rate matrix, the basis of the rate matrices and the derivatives of the generator kept for the + gradients. The states are kept. """ self.drop_S() - - self._previous_S = {} - self._cache = {} - self._generator_basis = None + self.__dict__.pop('_basis', None) + self._generator_derivatives = None @abstractmethod def _get_initial(self) -> 'State': @@ -626,102 +821,6 @@ def _numba_to_state(self, row: np.ndarray, init: 'State') -> 'State': """Rebuild a :class:`State` from a kernel row (default: reshape into the lineage array; linkage is static).""" return State((row.reshape(init.lineages.shape).astype(init.lineages.dtype), init.linked.copy())) - def _construct_numba(self) -> Tuple[List['State'], np.ndarray]: - """ - Build the states and rate matrix for the current epoch via the numba kernel. - - :return: The states (in kernel discovery order) and the intensity matrix, a :class:`scipy.sparse.csr_matrix` - from :attr:`Settings.dense_rate_matrix_max_states ` - states on and dense below. - """ - init = self._get_initial() - n_demes = init.lineages.shape[1] - n_blocks = self._numba_n_blocks(init) - pops = self.lineage_config.pop_names - - mig = np.zeros((n_demes, n_demes)) - for i, a in enumerate(pops): - for j, b in enumerate(pops): - if i != j: - mig[i, j] = self.epoch.migration_rates[(a, b)] - - timescales = np.array([self.model._get_timescale(self.epoch.pop_sizes[p]) for p in pops]) - model_id, alpha, psi, c = _numba_model_params(self.model) - recomb_rate, recomb0, recomb1 = self._numba_recombination() - - rows, S = build_rate_matrix( - initial=self._numba_initial(init), - kind=self._numba_kind(), - n_demes=n_demes, - n_blocks=n_blocks, - mig=mig, - timescales=timescales, - model_id=model_id, - alpha=alpha, - psi=psi, - c=c, - block_vectors=self._numba_block_vectors(n_blocks), - recomb_rate=recomb_rate, - recomb0=recomb0, - recomb1=recomb1, - max_states=Settings.max_state_space_size, - dense_max_states=Settings.dense_rate_matrix_max_states, - ) - - states = [self._numba_to_state(row, init) for row in rows] - - return states, S - - def _get_rate_matrix(self) -> np.ndarray: - """ - Get the rate matrix. - - :return: The rate matrix. - """ - if self._use_numba(): - start = time.time() - states, S = self._construct_numba() - # materialising S before .states makes this the first construction: record the time and warn about a large - # space here too, since the states cached_property (which otherwise owns that bookkeeping) will not run. - if 'states' not in self.__dict__: - self.__dict__['states'] = states - self.time = time.time() - start - self._warn_if_large(len(states)) - return S - - if self.epoch not in self._cache: - self._cache[self.epoch] = self.get_transitions() - - transitions, states = self._cache[self.epoch] - - return self._graph_to_matrix(transitions, states) - - @staticmethod - def _graph_to_matrix( - transitions: Dict[Tuple['State', 'State'], Tuple[float, str]], - states: List['State'] - ) -> np.ndarray: - """ - Convert transition graph to rate matrix. - - :param transitions: Transitions. - :param states: States. - :return: Rate matrix. - """ - S = np.zeros((len(states), len(states))) - - # order of original states - ordering = {s: i for i, s in enumerate(states)} - - # fill rate matrix - for (source, target), transition in transitions.items(): - S[ordering[source], ordering[target]] = transition[0] - - # fill diagonal with negative sum of row - S[np.diag_indices_from(S)] = -np.sum(S, axis=1) - - return S - def _get_color_state(self, i: int) -> str: """ Get color of the state indexed by `i`. diff --git a/phasegen/state_space_numba.py b/phasegen/state_space_numba.py index e97f06ab..fbb1b5a5 100644 --- a/phasegen/state_space_numba.py +++ b/phasegen/state_space_numba.py @@ -1,15 +1,15 @@ """ Numba-accelerated kernels for state-space construction. -The kernels operate on integer state rows (the flattened ``lineages`` array of shape ``(n_demes, n_blocks)``) and build the rate matrix directly. Kinds 0 and 1 -build the single-locus lineage- and block-/joint-counting spaces, and kinds 2 and 3 the two-locus block- and -lineage-counting spaces under recombination. +The kernels operate on integer state rows (the flattened ``lineages`` array of shape ``(n_demes, n_blocks)``) and +enumerate the states and their transitions. Kinds 0 and 1 build the single-locus lineage- and block-/joint-counting +spaces, and kinds 2 and 3 the two-locus block- and lineage-counting spaces under recombination. Coalescent rates are reproduced from the model formulae (exact ``comb`` via an integer loop, the Euler beta via ``math.lgamma``, and the binomial pmf via ``comb`` and powers, all three in log space from ``_LOG_SPACE_MIN_LINEAGES`` lineages on, where the float binomial coefficient would overflow), parameterised by a -``model_id`` (0 standard, 1 beta, 2 dirac) plus ``alpha``/``psi``/``c``. Per-deme timescales and the migration-rate -matrix are precomputed in Python and passed in, so no transcendental model code other than the rates lives here. +``model_id`` (0 standard, 1 beta, 2 dirac) plus ``alpha``/``psi``/``c``. The transitions are listed at unit time scales +and unit migration rates, from which the state space assembles the rate matrix of each epoch. States are numbered in discovery order, which differs from the pure-Python enumeration. Parity tests compare the two constructions up to a permutation of the states. @@ -199,16 +199,15 @@ def _find_or_add(rows, chain_next, head, target) -> int: # --------------------------------------------------------------------------------------------------------------------- @njit(cache=True) -def _build(initial, kind, n_demes, n_blocks, mig, timescales, model_id, alpha, psi, c, block_vectors, - recomb_rate, recomb0, recomb1, max_states) -> tuple: +def _build(initial, kind, n_demes, n_blocks, model_id, alpha, psi, c, block_vectors, recomb_rate, recomb0, recomb1, + max_states) -> tuple: """ - Build the state graph by BFS over integer ``lineages`` rows. + Build the state graph by BFS over integer ``lineages`` rows, with coalescence rates at unit time scale and + migration rates at unit rate. :param initial: Flattened initial lineage row (length ``n_demes * n_blocks``). :param kind: 0 lineage-counting, 1 block-/joint-counting, 2 two-locus block-counting (recombination), 3 two-locus lineage-counting (recombination). - :param mig: ``(n_demes, n_demes)`` migration-rate matrix. - :param timescales: per-deme timescale by which coalescence rates are divided. :param block_vectors: ``(n_blocks, vdim)`` block labels (descendant vectors / size classes); the merged block of a merger is the one whose label equals the summed label of the merging blocks (found by linear search). :param recomb_rate: recombination rate (kinds 2 and 3 only). @@ -258,9 +257,7 @@ def _build(initial, kind, n_demes, n_blocks, mig, timescales, model_id, alpha, p carry1 += cnt absorbing = carry0 == 1 and carry1 == 1 - # --- migration: move one lineage of each block between demes, rate scaled by source count --- - # the target states are discovered for every ordered deme pair regardless of the migration rate (matching - # the pure-Python construction, so the state set is epoch-independent); only the edge is rate-gated + # --- migration: move one lineage of each block between demes, at unit rate per lineage --- for d1 in range(n_demes): for d2 in range(n_demes): if d1 == d2: @@ -272,10 +269,9 @@ def _build(initial, kind, n_demes, n_blocks, mig, timescales, model_id, alpha, p target[d1 * n_blocks + blk] -= 1 target[d2 * n_blocks + blk] += 1 tidx = _find_or_add(rows, chain_next, head, target) - if mig[d1, d2] != 0.0: - src.append(np.int64(cur)) - dst.append(np.int64(tidx)) - rate.append(mig[d1, d2] * cnt) + src.append(np.int64(cur)) + dst.append(np.int64(tidx)) + rate.append(float(cnt)) # --- coalescence (only when more than one lineage remains, and not yet absorbed for two loci) --- if total > 1 and not absorbing: @@ -288,8 +284,6 @@ def _build(initial, kind, n_demes, n_blocks, mig, timescales, model_id, alpha, p if deme_total < 2: continue - ts = timescales[deme] - if kind == 0: # lineage-counting: merge k of the deme's lineages into one (count decreases by k - 1) cnt = source[base] @@ -302,7 +296,7 @@ def _build(initial, kind, n_demes, n_blocks, mig, timescales, model_id, alpha, p tidx = _find_or_add(rows, chain_next, head, target) src.append(np.int64(cur)) dst.append(np.int64(tidx)) - rate.append(r / ts) + rate.append(r) continue # block-/joint-counting: enumerate merger combinations over present blocks via an odometer @@ -380,7 +374,7 @@ def _build(initial, kind, n_demes, n_blocks, mig, timescales, model_id, alpha, p tidx = _find_or_add(rows, chain_next, head, target) src.append(np.int64(cur)) dst.append(np.int64(tidx)) - rate.append(r / ts) + rate.append(r) # --- recombination (two-locus): a block ancestral at both loci splits into the two single-locus blocks, per # deme, at rate r per such lineage. Kind 2 (block-counting) splits (a_0, a_1) -> (a_0, 0) + (0, a_1); kind 3 @@ -425,13 +419,11 @@ def _build(initial, kind, n_demes, n_blocks, mig, timescales, model_id, alpha, p return rows_arr, src_arr, dst_arr, rate_arr -def build_rate_matrix( +def build_transitions( initial: np.ndarray, kind: int, n_demes: int, n_blocks: int, - mig: np.ndarray, - timescales: np.ndarray, model_id: int, alpha: float, psi: float, @@ -441,24 +433,18 @@ def build_rate_matrix( recomb0: np.ndarray = None, recomb1: np.ndarray = None, max_states: int = 2 ** 62, - dense_max_states: int = 0, ) -> tuple: """ - Python entry point: build the state rows and the rate matrix via the numba kernel. - - The kernel's BFS is aborted once it discovers more than ``max_states`` states, and a :class:`MemoryError` is - raised. The cap bounds the number of states, not the memory, which grows with the width of a state row. The COO - transitions the kernel returns are assembled, in one place, into either a dense array (below ``dense_max_states`` - states, where dense is cheap and the dense moment paths are faster) or a :class:`scipy.sparse.csr_matrix` (above - it, since the generator is sparse, each state coalescing to only O(n) others, and a dense ``n_states**2`` matrix - would be prohibitive). - - :return: ``(rows, S)`` where ``rows`` is ``(n_states, n_demes * n_blocks)`` integer lineage rows (discovery - order) and ``S`` is the dense or sparse intensity matrix, whose diagonal holds the negative row sums. + Python entry point: enumerate the states and the transitions via the numba kernel, at unit time scales and unit + migration rates, so that every migration transition is listed. The kernel's BFS is aborted once it discovers more + than ``max_states`` states, and a :class:`MemoryError` is raised. The cap bounds the number of states, not the + memory, which grows with the width of a state row. + + :return: ``(rows, src, dst, rate)`` where ``rows`` is ``(n_states, n_demes * n_blocks)`` integer lineage rows + (discovery order) and ``src``, ``dst``, ``rate`` the transitions, a pair of states possibly listed several + times. :raises MemoryError: if the state space exceeds ``max_states``. """ - from scipy.sparse import coo_matrix - # the recombination split maps are only used for the two-locus kernels (kinds 2 and 3), pass dummies otherwise if recomb0 is None: recomb0 = np.zeros(n_blocks, dtype=np.int64) @@ -467,30 +453,17 @@ def build_rate_matrix( rows, src, dst, rate = _build( initial.astype(np.int64), kind, n_demes, n_blocks, - mig.astype(np.float64), timescales.astype(np.float64), model_id, float(alpha), float(psi), float(c), block_vectors.astype(np.int64), float(recomb_rate), recomb0.astype(np.int64), recomb1.astype(np.int64), int(max_states), ) - n = rows.shape[0] - # the BFS aborts once it exceeds the cap, so a returned count over it means the (incomplete) space is too large - if n > max_states: + if rows.shape[0] > max_states: raise MemoryError( f"State space exceeds the maximum of {max_states} states (construction aborted to avoid running out " f"of memory). Increase Settings.max_state_space_size to override, or reduce the sample size." ) - # off-diagonal transitions (a target may be reached by several transitions, e.g. multiple-merger paths, so - # duplicate (src, dst) entries are summed by ``coo_matrix``) plus the diagonal = negative out-rate per row - row_sums = np.bincount(src, weights=rate, minlength=n) - diag = np.arange(n) - data = np.concatenate([rate, -row_sums]) - rows_idx = np.concatenate([src, diag]) - cols_idx = np.concatenate([dst, diag]) - S = coo_matrix((data, (rows_idx, cols_idx)), shape=(n, n)) - - # one place decides the representation: dense where it is cheap and faster, sparse where dense would be too big - return rows, (S.toarray() if n < dense_max_states else S.tocsr()) + return rows, src, dst, rate diff --git a/poetry.lock b/poetry.lock index 4e235a00..ca9eb778 100644 --- a/poetry.lock +++ b/poetry.lock @@ -3489,4 +3489,4 @@ type = ["pytest-mypy (>=1.0.1) ; platform_python_implementation != \"PyPy\""] [metadata] lock-version = "2.1" python-versions = ">=3.11,<3.15" -content-hash = "21f2906f3667e37c277d5f72baa75c9bda631d3f6e959f20e2e4fd229afe8053" +content-hash = "372f93b21142a96c4be7a49985cdf72a5eb0d7b80c5587ae1714e285f929674a" diff --git a/pyproject.toml b/pyproject.toml index bdefc8f7..1ef81119 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "phasegen" -version = "2.2.0" +version = "2.3.0" description = "Computation and inference on exact solutions of coalescent distributions under diverse demographic scenarios." authors = ["Janek Sendrowski "] license = "GPL-3.0-or-later" @@ -9,11 +9,11 @@ readme = "README.md" [tool.poetry.dependencies] python = ">=3.11,<3.15" typing-extensions = "^4.11.0" -matplotlib = "^3.8.4" +matplotlib = "^3.9" seaborn = "^0.13.2" numpy = ">=1.26.4" pandas = ">=2.2.2,<4" -jsonpickle = ">=3.0.4,<5" +jsonpickle = ">=3.4.2,<5" multiprocess = "^0.70.16" dill = ">=0.3.8" pyyaml = "^6.0.1" diff --git a/scripts/plot_heatmap_execution_times.py b/scripts/plot_heatmap_execution_times.py index 0fdcb31e..d616075f 100644 --- a/scripts/plot_heatmap_execution_times.py +++ b/scripts/plot_heatmap_execution_times.py @@ -71,8 +71,15 @@ def plot_heatmap( for (n, d) in itertools.product(N, D): pbar.set_description(f"n={n}, d={d}") + pops = {'pop_0': n} | {f'pop_{i}': 0 for i in range(1, d)} + + # unit migration between all demes, so that every state of the state space is reachable coal = pg.Coalescent( - n=pg.LineageConfig({'pop_0': n} | {f'pop_{i}': 0 for i in range(1, d)}), + n=pg.LineageConfig(pops), + demography=pg.Demography( + pop_sizes={p: 1 for p in pops}, + migration_rates={(a, b): 1.0 for a in pops for b in pops if a != b} + ), loci=locus_config ) @@ -113,7 +120,7 @@ def plot_heatmap( plot_heatmap( ax=ax[0], - N=np.arange(2, 13, 1), + N=np.arange(4, 48, 4), D=np.arange(1, 4), callback=lambda coal: coal.tree_height.mean, title="Mean tree height, one locus" @@ -121,7 +128,7 @@ def plot_heatmap( plot_heatmap( ax=ax[1], - N=np.arange(2, 11, 1), + N=np.arange(2, 20, 2), D=np.arange(1, 4), callback=lambda coal: coal.sfs.mean, title="Mean SFS, one locus" @@ -129,7 +136,7 @@ def plot_heatmap( plot_heatmap( ax=ax[2], - N=np.arange(2, 7, 1), + N=np.arange(3, 13, 2), D=np.arange(1, 3), callback=lambda coal: coal.tree_height.mean, title="Mean tree height, two loci", @@ -139,7 +146,7 @@ def plot_heatmap( # mean two-locus SFS (the recombination-aware 2-SFS); single population plot_heatmap( ax=ax[3], - N=np.arange(2, 7, 1), + N=np.arange(2, 12, 2), D=np.arange(1, 2), callback=lambda coal: coal.sfs2.mean, title="Mean two-locus SFS", diff --git a/scripts/plot_heatmap_sampling_times.py b/scripts/plot_heatmap_sampling_times.py index af2fca42..70525d95 100644 --- a/scripts/plot_heatmap_sampling_times.py +++ b/scripts/plot_heatmap_sampling_times.py @@ -64,8 +64,15 @@ def plot_heatmap( for (n, d) in itertools.product(N, D): pbar.set_description(f"n={n}, d={d}") + pops = {'pop_0': n} | {f'pop_{i}': 0 for i in range(1, d)} + + # unit migration between all demes, so that every state of the state space is reachable coal = pg.Coalescent( - n=pg.LineageConfig({'pop_0': n} | {f'pop_{i}': 0 for i in range(1, d)}), + n=pg.LineageConfig(pops), + demography=pg.Demography( + pop_sizes={p: 1 for p in pops}, + migration_rates={(a, b): 1.0 for a in pops for b in pops if a != b} + ), loci=locus_config ) @@ -102,7 +109,7 @@ def plot_heatmap( plot_heatmap( ax=ax[0], - N=np.arange(2, 13, 1), + N=np.arange(4, 48, 4), D=np.arange(1, 4), callback=lambda coal: coal.tree_height.to_empirical(N_SAMPLES).mean, title="Mean tree height, one locus" @@ -110,7 +117,7 @@ def plot_heatmap( plot_heatmap( ax=ax[1], - N=np.arange(2, 11, 1), + N=np.arange(2, 20, 2), D=np.arange(1, 4), callback=lambda coal: coal.sfs.to_empirical(N_SAMPLES).mean, title="Mean SFS, one locus" @@ -118,7 +125,7 @@ def plot_heatmap( plot_heatmap( ax=ax[2], - N=np.arange(2, 7, 1), + N=np.arange(3, 13, 2), D=np.arange(1, 3), callback=lambda coal: coal.tree_height.to_empirical(N_SAMPLES).mean, title="Mean tree height, two loci", @@ -128,7 +135,7 @@ def plot_heatmap( # mean two-locus SFS (the recombination-aware 2-SFS); single population plot_heatmap( ax=ax[3], - N=np.arange(2, 7, 1), + N=np.arange(2, 12, 2), D=np.arange(1, 2), callback=lambda coal: coal.sfs2.to_empirical(N_SAMPLES).mean, title="Mean two-locus SFS", diff --git a/testing/test_bin_second_moments.py b/testing/test_bin_second_moments.py new file mode 100644 index 00000000..474d3949 --- /dev/null +++ b/testing/test_bin_second_moments.py @@ -0,0 +1,290 @@ +""" +Tests of the second moments of spectra from one forward pass over all bins (``MomentEvaluator._bin_second_moments``): +agreement with the cross-moments of each pair of bins in every regime the pass reaches, values pinned against the +per-pair evaluation, its routing, and the boundaries of its exponential dispatch. +""" +from unittest.mock import patch + +import numpy as np +import pytest +import scipy.sparse as sp + +import phasegen as pg +from phasegen.distributions import PhaseTypeDistribution, _moments +from phasegen.expm import Backend, _GrowthBound +from phasegen.rewards import CombinedReward +from phasegen.settings import Settings + +_THREE = {0: 1.0, 0.4: 0.3, 1.2: 2.0} + + +@pytest.fixture(autouse=True) +def _unflattened(): + """The single-deme spectra of the standard coalescent take the forward pass on the block-counting state space. + The conftest restores the setting.""" + Settings.flatten_block_counting = False + + +def _single(n=5, sizes=None, model=None, start_time=0, end_time=None) -> pg.Coalescent: + """One deme with three epochs by default.""" + return pg.Coalescent(n=n, model=model, demography=pg.Demography(pop_sizes={'pop_0': sizes or _THREE}), + start_time=start_time, end_time=end_time) + + +def _two_demes(n0=2, n1=2, start_time=0, end_time=None) -> pg.Coalescent: + """Two demes with migration and two epochs.""" + return pg.Coalescent(n={'pop_0': n0, 'pop_1': n1}, start_time=start_time, end_time=end_time, + demography=pg.Demography(pop_sizes={'pop_0': {0: 1.0, 0.5: 0.4}, 'pop_1': {0: 1.0}}, + migration_rates={('pop_0', 'pop_1'): 1.0, ('pop_1', 'pop_0'): 0.6})) + + +def _spy(method): + """Patch a method of the moment evaluator with a pass-through spy counting its calls.""" + return patch.object(PhaseTypeDistribution, method, autospec=True, + side_effect=getattr(PhaseTypeDistribution, method)) + + +def _per_pair(dist) -> np.ndarray: + """The covariance of the bins of a spectrum from the cross-moment of each ordered pair of bins.""" + rewards = [CombinedReward([dist.reward, reward]) for _, reward in dist._bins()] + mean = np.array([PhaseTypeDistribution.moment(dist, k=1, rewards=(r,)) for r in rewards]) + ordered = np.array([[PhaseTypeDistribution.moment(dist, k=2, rewards=(a, b), center=False, permute=False) + for b in rewards] for a in rewards]) + + return (ordered + ordered.T) / 2 - np.outer(mean, mean) + + +def _batched(dist) -> np.ndarray: + """The covariance of the bins of a spectrum over its polymorphic bins, in the order of ``_bins``.""" + cov = np.asarray(getattr(dist.cov, 'data', dist.cov)) + positions = [pos for pos, _ in dist._bins()] + + return np.array([[cov[a + b] for b in positions] for a in positions]) + + +_REGIMES = { + 'three epochs': (lambda: _single().sfs, {}), + 'three epochs folded': (lambda: _single().fsfs, {}), + 'one epoch': (lambda: _single(sizes={0: 1.0}).sfs, {}), + 'one bin': (lambda: _single(n=2).sfs, {}), + 'beta three epochs': (lambda: _single(model=pg.BetaCoalescent(alpha=1.5)).sfs, {}), + 'dirac two epochs': (lambda: _single(model=pg.DiracCoalescent(psi=0.5, c=1), sizes={0: 1, 0.7: 0.2}).sfs, {}), + 'stiff sizes': (lambda: _single(sizes={0: 1e-3, 0.01: 1e4, 5e4: 1e-2}).sfs, {}), + 'start in a finite epoch': (lambda: _single(start_time=0.6).sfs, {}), + 'start in the last epoch': (lambda: _single(start_time=1.5).sfs, {}), + 'start in the only epoch': (lambda: _single(sizes={0: 1.0}, start_time=0.5).sfs, {}), + 'finite window': (lambda: _single(start_time=0.6, end_time=2.0).sfs, {}), + 'finite end': (lambda: _single(end_time=1.0).sfs, {}), + 'closed form disabled': (lambda: _single().sfs, {'closed_form_last_epoch': False}), + 'forced action': (lambda: _single().sfs, {'expm_method': 'action'}), + 'forced dense': (lambda: _single().sfs, {'expm_method': 'dense'}), + 'sparse factorization': (lambda: _single().sfs, {'closed_form_sparse_min_states': 0}), + 'two demes sfs': (lambda: _two_demes().sfs, {}), + 'two demes jsfs': (lambda: _two_demes().jsfs, {}), + 'two demes jsfs window': (lambda: _two_demes(start_time=0.3, end_time=1.5).jsfs, {}), + 'two demes jsfs forced action': (lambda: _two_demes().jsfs, {'expm_method': 'action'}), +} + + +@pytest.mark.parametrize('name', list(_REGIMES), ids=list(_REGIMES)) +def test_covariance_matches_the_cross_moments_of_each_pair(name): + """The covariance of the bins equals the cross-moments of each ordered pair of bins, centered by their means.""" + make, settings = _REGIMES[name] + for key, value in settings.items(): + setattr(Settings, key, value) + + batched = _batched(make()) + reference = _per_pair(make()) + + np.testing.assert_allclose(batched, reference, rtol=0, atol=1e-12 * np.abs(reference).max()) + + +@pytest.mark.parametrize('read', [ + lambda: _single().sfs.cov, + lambda: _single().sfs.var, + lambda: _single().sfs.corr, + lambda: _single(sizes={0: 1.0}).sfs.cov, + lambda: _single(start_time=1.5).sfs.var, + lambda: _single(start_time=0.6, end_time=2.0).fsfs.cov, + lambda: _two_demes().jsfs.cov, + lambda: _two_demes().jsfs.var, + lambda: pg.Coalescent(n=4, loci=2, recombination_rate=0.7, + demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.4: 0.5}})).sfs2.mean, + lambda: pg.Coalescent(n=4, loci=2, recombination_rate=0.7, + demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.4: 0.5}})).sfs2.cov, +], ids=['sfs.cov', 'sfs.var', 'sfs.corr', 'sfs.cov one epoch', 'sfs.var start in the last epoch', 'fsfs.cov window', + 'jsfs.cov', 'jsfs.var', 'sfs2.mean', 'sfs2.cov']) +def test_second_moments_of_spectra_take_one_forward_pass(read): + """Each second moment of a spectrum is read from one forward pass, never from per-bin or per-pair moments.""" + with _spy('_bin_second_moments') as forward, _spy('_accumulate_closed_form') as closed, \ + _spy('_accumulate_windowed') as windowed, _spy('_raw_powers') as powers: + read() + + assert forward.call_count == 1 + assert closed.call_count == windowed.call_count == powers.call_count == 0 + + +def test_second_moments_equal_the_per_pair_values(): + """Entries of the second moments, as the per-pair and per-bin evaluations gave them.""" + rtol = 1e-12 + + sfs = _single(n=6).sfs + assert sfs.cov.data[1, 2] == pytest.approx(-0.06609360636277128, rel=rtol) + assert sfs.cov.data[2, 5] == pytest.approx(-0.05453862264194538, rel=rtol) + assert sfs.var.data[3] == pytest.approx(0.9736311013115428, rel=rtol) + assert _single(n=6).fsfs.cov.data[1, 3] == pytest.approx(-0.07235352050915567, rel=rtol) + + windowed = _single(n=6, start_time=0.6, end_time=2.0).sfs + assert windowed.cov.data[1, 2] == pytest.approx(-0.006453006283565935, rel=rtol) + assert windowed.var.data[1] == pytest.approx(0.07666372117516553, rel=rtol) + assert _single(n=6, start_time=1.5).sfs.cov.data[1, 4] == pytest.approx(-0.004419241116600708, rel=rtol) + + jsfs = _two_demes().jsfs + assert np.asarray(jsfs.cov)[1, 0, 0, 1] == pytest.approx(-0.4234888256450624, rel=rtol) + assert jsfs.var.data[1, 1] == pytest.approx(3.552387167079909, rel=rtol) + + sfs2 = pg.Coalescent(n=4, loci=2, recombination_rate=0.7, + demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.4: 0.5}})).sfs2 + assert sfs2.mean.data[1, 2] == pytest.approx(0.8871406096802578, rel=rtol) + assert sfs2.cov.data[1, 1] == pytest.approx(0.4249968182667958, rel=1e-11) + + +@pytest.mark.parametrize('offset, action', [(0, True), (1, False)]) +def test_windowed_pass_takes_the_action_from_the_threshold(offset, action, monkeypatch): + """In a finite window, the pass takes the stacked action from the Van Loan dimension at which + ``Settings.expm_method = 'auto'`` caps the dense exponentials on, and one dense exponential per bin below, with the + same values.""" + reference = _batched(_single(end_time=2.0).sfs) + sfs = _single(end_time=2.0).sfs + monkeypatch.setattr(_moments, '_EXPM_ACTION_MIN_DIM', 3 * sfs.state_space.k + offset) + + with _spy('_block_expms') as dense, patch.object(Backend, 'expm_multiply', side_effect=Backend.expm_multiply) as act: + batched = _batched(sfs) + + stacked = [c for c in act.call_args_list if c.kwargs.get('blocks') == 2 * len(sfs._bins()) + 1] + assert bool(stacked) is action and (dense.call_count > 0) is not action + np.testing.assert_allclose(batched, reference, rtol=0, atol=1e-12 * np.abs(reference).max()) + + +@pytest.mark.parametrize('dense', [True, False]) +@pytest.mark.parametrize('end_time', [None, 2.0], ids=['closed', 'window']) +def test_pass_follows_the_stacked_dense_exponential_rule(dense, end_time): + """The finite epochs take the dense exponentials exactly where ``_dense_expm_is_faster`` holds, with the same + values, until absorption and in a window.""" + reference = _per_pair(_single(end_time=end_time).sfs) + sfs = _single(end_time=end_time).sfs + + with patch.object(PhaseTypeDistribution, '_dense_expm_is_faster', autospec=True, return_value=dense), \ + _spy('_block_expms') as blocks: + batched = _batched(sfs) + + assert (blocks.call_count > 0) is dense + np.testing.assert_allclose(batched, reference, rtol=0, atol=1e-12 * np.abs(reference).max()) + + +def _stacked_dispatch(make) -> bool: + """Whether the second moments of the spectrum made by ``make`` take the stacked action.""" + action = patch.object(Backend, 'expm_multiply', side_effect=Backend.expm_multiply) + with action as act, _spy('_block_expms') as dense: + make().cov + + stacked = any(c.kwargs.get('blocks', 1) > 3 for c in act.call_args_list) + assert stacked is not (dense.call_count > 0) + + return stacked + + +_SHORT = {0: 1.0, 0.1: 0.5, 0.2: 2.0} + + +@pytest.mark.parametrize('make, action', [ + (lambda: _single(n=5).sfs, False), + (lambda: _single(n=10).sfs, True), + (lambda: _single(n=6, model=pg.BetaCoalescent(alpha=1.5)).sfs, False), + (lambda: _single(n=10, model=pg.BetaCoalescent(alpha=1.5)).sfs, True), + (lambda: _single(n=6, model=pg.DiracCoalescent(psi=0.5, c=1)).sfs, False), + (lambda: _single(n=5, end_time=2.0).sfs, False), + (lambda: _two_demes(3, 3, start_time=0.3, end_time=1.5).jsfs, True), + (lambda: _two_demes(2, 2).sfs, False), +], ids=['kingman n=5', 'kingman n=10', 'beta n=6', 'beta n=10', 'dirac n=6', 'window n=5', 'window jsfs 3+3', + 'two demes sfs 2+2']) +def test_stacked_dispatch_on_the_block_counting_space(make, action): + """The forward pass takes the dense exponentials on small block-counting spaces and the stacked action from about + 20 states on, until absorption and in a window.""" + assert _stacked_dispatch(make) is action + + +@pytest.mark.parametrize('n, sizes, action', [(10, _THREE, False), (30, _THREE, False), (30, _SHORT, True)], + ids=['n=10', 'n=30 long epochs', 'n=30 short epochs']) +def test_stacked_dispatch_on_the_lineage_counting_space(n, sizes, action): + """Flattened onto the lineage-counting space, the forward pass over the ``n - 1`` levels takes the dense + exponentials on stiff epochs and the stacked action on short ones.""" + Settings.flatten_block_counting = True + sfs = _single(n=n, sizes=sizes).sfs + + with _spy('_level_cross_moments') as flattened: + assert _stacked_dispatch(lambda: sfs) is action + + assert flattened.call_count == 1 + + +def test_stiff_stacked_action_stops_once_stationary(): + """An epoch whose generator has a 1-norm far above the stepping threshold is applied in norm-doubling steps that + stop once the stacked vector is stationary, and matches the dense exponentials.""" + make = lambda: _single(sizes={0: 1.0, 0.5: 1e-4, 2.0: 1.0}).sfs + Settings.expm_method = 'dense' + reference = _batched(make()) + + Settings.expm_method = 'action' + with patch.object(Backend, '_stationary', side_effect=Backend._stationary) as stationary: + batched = _batched(make()) + + assert stationary.call_count > 0 + np.testing.assert_allclose(batched, reference, rtol=0, atol=1e-11 * np.abs(reference).max()) + + +def test_growth_bound_depth_bounds_the_exponential(): + """The growth bound with the depth of the coupling chain bounds the mean norm of the exponential of a matrix of five + diagonal blocks coupled along chains of three blocks, and is tighter than the bound over all five blocks.""" + rng = np.random.default_rng(0) + n = 4 + S = rng.uniform(0, 1, (n, n)) + np.fill_diagonal(S, 0) + np.fill_diagonal(S, -S.sum(axis=1) - 0.5) + + # blocks p, u_1, u_2, w_1, w_2 of the forward pass, transposed for the column action + A = np.zeros((5 * n, 5 * n)) + for b in range(3): + A[b * n:(b + 1) * n, b * n:(b + 1) * n] = S.T + for a in range(2): + A[(1 + a) * n:(2 + a) * n, :n] = np.diag(rng.uniform(1, 3, n)) + A[(3 + a) * n:(4 + a) * n, (1 + a) * n:(2 + a) * n] = 2.0 * np.eye(n) + A = sp.csr_matrix(A * 3.0) + + import scipy.linalg as sla + for f in (0.5, 1.0, 4.0): + s = np.linspace(0, f, 401) + norms = [np.abs(sla.expm(x * A.toarray())).sum(axis=0).max() for x in s] + mean_norm = float(np.sum((np.array(norms[1:]) + norms[:-1]) / 2 * np.diff(s)) / f) + tight, loose = _GrowthBound(A, abs(A), 5, depth=3)(f), _GrowthBound(A, abs(A), 5)(f) + assert mean_norm <= tight * (1 + 1e-6) and tight < loose + + +def test_jacobian_of_second_moments_is_unchanged(): + """The exact Jacobian of entries of ``sfs.cov``, ``jsfs.var`` and ``jsfs.cov``, read through the forward pass, + equals the one from the per-pair values, and the backward pass agrees with the values read.""" + coal = lambda N1, m: pg.Coalescent(n={'pop_0': 2, 'pop_1': 2}, demography=pg.Demography( + pop_sizes={'pop_0': {0: 1.0, 0.5: N1}, 'pop_1': {0: 1.0}}, + migration_rates={('pop_0', 'pop_1'): m, ('pop_1', 'pop_0'): 0.6})) + gradient = pg.Gradient(coal, lambda c: np.array([c.sfs.cov.data[1, 2], c.jsfs.var.data[1, 1], + np.asarray(c.jsfs.cov)[1, 0, 0, 1]])) + params, bounds = {'N1': 0.4, 'm': 1.0}, {'N1': (0.05, 5), 'm': (0.01, 5)} + + exact = gradient._exact(params, bounds) + assert exact is not None + + value, jacobian = exact + np.testing.assert_allclose(value, [-1.3180612934735434, 3.552387167079909, -0.4234888256450624], rtol=1e-12) + np.testing.assert_allclose(jacobian, [[-1.2468038558119652, 0.7500612562903464], + [4.319325382546423, 0.15202572093266548], + [-0.4638229069345021, 0.1346383190704073]], rtol=1e-11) diff --git a/testing/test_blas_threads.py b/testing/test_blas_threads.py index 6698aa2f..15b51ee9 100644 --- a/testing/test_blas_threads.py +++ b/testing/test_blas_threads.py @@ -125,67 +125,20 @@ def test_batched_jsfs_accumulate_runs_with_the_configured_blas_threads(monkeypat assert seen and all(t == [1] * len(t) for t in seen) -def _threads_in_two_point_occupation(monkeypatch, evaluate) -> list: - """ - The BLAS threads seen by ``MomentEvaluator._two_point_occupation`` and by each call of the solve it returns, under - a caller's limit of four threads. - """ - seen = [] - target = _moments.MomentEvaluator._two_point_occupation - - def spy(self): - seen.append(_blas_threads()) - out = target(self) - if out is None: - return None - m, solve, idx_t = out - - def spied_solve(b): - seen.append(_blas_threads()) - return solve(b) - - return m, spied_solve, idx_t - - monkeypatch.setattr(_moments.MomentEvaluator, '_two_point_occupation', spy) - with threadpoolctl.threadpool_limits(4, user_api='blas'): - evaluate() - - return seen - - @pytest.mark.parametrize('evaluate', [ lambda: pg.Coalescent(n=6).sfs.var, lambda: pg.Coalescent(n=6).sfs.cov, + lambda: pg.Coalescent(n=6, demography=pg.Demography(pop_sizes={'pop_0': {0: 1.0, 0.5: 0.4, 1.5: 2.0}})).fsfs.cov, lambda: _two_demes().jsfs.cov, lambda: pg.Coalescent(n=4, loci=2, recombination_rate=1.0).sfs2.mean, -], ids=['sfs.var', 'sfs.cov', 'jsfs.cov', 'sfs2.mean']) -def test_two_point_occupation_runs_with_the_configured_blas_threads(monkeypatch, evaluate): + lambda: pg.Coalescent(n=4, loci=2, recombination_rate=1.0).sfs2.cov, +], ids=['sfs.var', 'sfs.cov', 'fsfs.cov 3-epoch', 'jsfs.cov', 'sfs2.mean', 'sfs2.cov']) +def test_second_moments_of_spectra_run_with_the_configured_blas_threads(monkeypatch, evaluate): """ - The batched second-order spectra factorize and solve in ``MomentEvaluator._two_point_occupation`` with - ``Settings.blas_threads``. They ran with the caller's threads, as only ``MomentEvaluator.accumulate``, - ``MomentEvaluator._occupation_times`` and ``MomentEvaluator._mean_occupation_grid`` limited them. + The second moments of spectra run ``MomentEvaluator._bin_second_moments`` with ``Settings.blas_threads``, also + where they are read through the marginals of the two-locus covariance. """ - seen = _threads_in_two_point_occupation(monkeypatch, evaluate) - - assert seen and all(t == [1] * len(t) for t in seen) - - -def test_stacked_sfs_cov_runs_with_the_configured_blas_threads(monkeypatch): - """ - The stacked closed form of ``fsfs.cov`` across epochs runs ``MomentEvaluator._accumulate_closed_form`` with - ``Settings.blas_threads``. It ran with the caller's threads, as ``SFSDistribution.cov`` calls it directly. - """ - seen = [] - accumulate = _moments.MomentEvaluator._accumulate_closed_form - - def spy(self, *args, **kwargs): - seen.append(_blas_threads()) - return accumulate(self, *args, **kwargs) - - monkeypatch.setattr(_moments.MomentEvaluator, '_accumulate_closed_form', spy) - coal = pg.Coalescent(n=6, demography=pg.Demography(pop_sizes={'pop_0': {0: 1.0, 0.5: 0.4, 1.5: 2.0}})) - with threadpoolctl.threadpool_limits(4, user_api='blas'): - coal.fsfs.cov + seen = _threads_inside(monkeypatch, '_bin_second_moments', evaluate) assert seen and all(t == [1] * len(t) for t in seen) diff --git a/testing/test_closed_form_last_epoch.py b/testing/test_closed_form_last_epoch.py index 77658ee7..f8bb25c4 100644 --- a/testing/test_closed_form_last_epoch.py +++ b/testing/test_closed_form_last_epoch.py @@ -14,20 +14,25 @@ import phasegen as pg import phasegen.distributions as _pgd +from phasegen.errors import ModelError from phasegen.settings import Settings from testing import TestCase _HI, _LO = 10 ** 12, 0 -# the closed-form / batched dispatch entry points (every one is gated on ``_use_closed_form``) -_CF_ENTRY_POINTS = ("_accumulate_closed_form", "_occupation_times", "_two_point_occupation") +# the closed-form / batched dispatch entry points, and the factorization of the last epoch that the closed forms of +# every order and the second moments of spectra share +_CF_ENTRY_POINTS = ("_accumulate_closed_form", "_occupation_times", "_last_epoch_solver") @contextlib.contextmanager def _count_closed_form_calls(): """Count calls to the closed-form / batched entry points while still executing them normally.""" + cls = _pgd.PhaseTypeDistribution counts = {name: 0 for name in _CF_ENTRY_POINTS} - originals = {name: getattr(_pgd.PhaseTypeDistribution, name) for name in _CF_ENTRY_POINTS} + originals = {name: getattr(cls, name) for name in _CF_ENTRY_POINTS} + # an entry point inherited from a base class is restored by deleting the wrapper from this class + own = {name: vars(cls)[name] for name in _CF_ENTRY_POINTS if name in vars(cls)} def make(name, orig): def wrapper(self, *args, **kwargs): @@ -38,11 +43,14 @@ def wrapper(self, *args, **kwargs): try: for name in _CF_ENTRY_POINTS: - setattr(_pgd.PhaseTypeDistribution, name, make(name, originals[name])) + setattr(cls, name, make(name, originals[name])) yield counts finally: for name in _CF_ENTRY_POINTS: - setattr(_pgd.PhaseTypeDistribution, name, originals[name]) + if name in own: + setattr(cls, name, own[name]) + else: + delattr(cls, name) def _both(fn): @@ -60,18 +68,18 @@ def _four_paths(fn): Evaluate ``fn`` under all four moment solvers, forcing each via the path-selection thresholds: dense/sparse matrix exponential (closed form off) and dense/sparse closed form (closed form on). """ - # (closed_form_last_epoch, expm_action_min_dim, closed_form_sparse_min_states); _HI/_LO force the + # (closed_form_last_epoch, expm_method, closed_form_sparse_min_states); _HI/_LO force the # dense/sparse sub-paths configs = { - "dense-expm": (False, _HI, _HI), - "sparse-expm": (False, _LO, _HI), - "dense-cf": (True, _HI, _HI), - "sparse-cf": (True, _LO, _LO), + "dense-expm": (False, 'dense', _HI), + "sparse-expm": (False, 'action', _HI), + "dense-cf": (True, 'dense', _HI), + "sparse-cf": (True, 'action', _LO), } out = {} - for name, (cf, eamd, cfmin) in configs.items(): + for name, (cf, method, cfmin) in configs.items(): Settings.closed_form_last_epoch = cf - Settings.expm_action_min_dim = eamd + Settings.expm_method = method Settings.closed_form_sparse_min_states = cfmin out[name] = np.asarray(fn(), dtype=float) return out @@ -110,7 +118,7 @@ def _four_paths(fn): "2-deme jsfs.mean": lambda: pg.Coalescent(n={'pop_0': 2, 'pop_1': 2}, demography=_MIG).jsfs.mean.data, "2-epoch 2-deme jsfs.mean": lambda: pg.Coalescent(n={'pop_0': 2, 'pop_1': 2}, demography=_MIG_2EPOCH).jsfs.mean.data, - # joint-SFS second moments, batched through the shared two-point occupation (single and multi epoch) + # joint-SFS second moments, from one forward pass over all bins (single and multi epoch) "2-deme jsfs.cov": lambda: pg.Coalescent(n={'pop_0': 2, 'pop_1': 2}, demography=_MIG).jsfs.cov, "2-deme jsfs.var": lambda: pg.Coalescent(n={'pop_0': 2, 'pop_1': 2}, demography=_MIG).jsfs.var.data, "2-epoch 2-deme jsfs.cov": @@ -163,20 +171,18 @@ def test_disabled_uses_only_matrix_exponential(name): assert sum(counts.values()) == 0, f"{name}: closed-form/batched path used while disabled: {counts}" -# the documented dispatch: which closed-form / batched entry points each moment kind reaches when enabled. -# (covariances also touch ``_occupation_times`` because they subtract the batched mean.) +# the documented dispatch: which closed-form / batched entry points each moment kind reaches when enabled _EXPECTED_PATHS = { - "tree_height.mean": {"_accumulate_closed_form"}, - "tree_height.var": {"_accumulate_closed_form"}, + "tree_height.mean": {"_accumulate_closed_form", "_last_epoch_solver"}, + "tree_height.var": {"_accumulate_closed_form", "_last_epoch_solver"}, # single-population SFS mean flattens (k=1, standard) onto the occupation of the lineage-counting space "sfs.mean": {"_occupation_times"}, - # the cov's mean flattens onto the lineage-counting occupation, and the covariance uses the two-point operator - "sfs.cov 1-epoch": {"_two_point_occupation", "_occupation_times"}, - # multi-epoch covariance: the batched single-epoch operator is declined (returns None) -> stacked closed form - "sfs.cov 3-epoch": {"_two_point_occupation", "_occupation_times", "_accumulate_closed_form"}, + # the covariances take their means and cross-moments from one forward pass closed in the last epoch + "sfs.cov 1-epoch": {"_last_epoch_solver"}, + "sfs.cov 3-epoch": {"_last_epoch_solver"}, # joint SFS is multi-population, so flattening does not apply: mean uses the batched occupation "jsfs.mean": {"_occupation_times"}, - "jsfs.cov": {"_two_point_occupation", "_occupation_times"}, + "jsfs.cov": {"_last_epoch_solver"}, } @@ -259,6 +265,22 @@ def test_absorption_before_last_epoch(self): np.testing.assert_allclose(on, off, rtol=1e-8) +@pytest.mark.parametrize("migration_rates", [ + {}, + {('a', 'b'): {0: 1.0, 1.0: 0.0}, ('b', 'a'): {0: 1.0, 1.0: 0.0}}, +], ids=["no-migration", "migration-before-1"]) +@pytest.mark.parametrize("moment", ["sfs.var", "sfs.cov", "jsfs.cov"]) +def test_second_moments_of_spectra_raise_when_the_demography_does_not_absorb(migration_rates, moment): + """The variances and covariances of the spectra raise on two demes that are disconnected in the last epoch. + Regression: the second moments of the bins closed the last epoch without checking that it absorbs.""" + coal = pg.Coalescent(n={'a': 2, 'b': 2}, demography=pg.Demography( + pop_sizes={'a': 1.0, 'b': 1.0}, migration_rates=migration_rates)) + spectrum, attr = moment.split('.') + + with pytest.raises(ModelError, match="does not absorb"): + _ = getattr(getattr(coal, spectrum), attr) + + @pytest.mark.parametrize("sparse", [False, True], ids=["dense-cf", "sparse-cf"]) def test_closed_form_finite_epochs_exact_at_large_population_size(sparse): """ @@ -269,7 +291,7 @@ def test_closed_form_finite_epochs_exact_at_large_population_size(sparse): """ Settings.closed_form_last_epoch = True Settings.closed_form_sparse_min_states = _LO if sparse else _HI - Settings.expm_action_min_dim = _LO if sparse else _HI + Settings.expm_method = 'action' if sparse else 'dense' def third_moment(N: float, sizes: dict) -> float: demography = pg.Demography(pop_sizes={'pop_0': {t * N: s * N for t, s in sizes.items()}}) diff --git a/testing/test_coalescents.py b/testing/test_coalescents.py index bd659d7a..54d4d6d6 100644 --- a/testing/test_coalescents.py +++ b/testing/test_coalescents.py @@ -11,6 +11,7 @@ import numpy as np import pytest from matplotlib import pyplot as plt +from scipy.integrate import trapezoid import phasegen as pg from phasegen.distributions import MsprimeCoalescent @@ -667,7 +668,7 @@ def test_marginal_view_curves_honour_own_reward(self): deme = sfs.demes['pop_0'] t = np.linspace(0, float(coal.tree_height.quantile(0.9999)), 2000) - mean_from_cdf = np.trapezoid(1 - np.asarray(deme.cdf(t)), t, axis=0) + mean_from_cdf = trapezoid(1 - np.asarray(deme.cdf(t)), t, axis=0) deme_mean = np.asarray(deme.mean.data, dtype=float) full_mean = np.asarray(sfs.mean.data, dtype=float) @@ -1937,7 +1938,7 @@ def test_high_moments_after_a_short_epoch_match_an_extended_precision_reference( assert coal.tree_height.moment(5, center=False) == pytest.approx(0.031670133796944716, rel=1e-12) assert coal.tree_height.moment(5) == pytest.approx(-5.6834198753562267e-10, rel=1e-5, abs=0) - pg.Settings.expm_action_min_dim = 1 + pg.Settings.expm_method = 'action' coal = pg.Coalescent(n=3, demography=pg.Demography(pop_sizes={'pop_0': {0: 1e-3, 1e-4: 1e3}})) raw = coal.moment(5, [pg.rewards.TreeHeightReward()] * 5, center=False, end_time=1.5e-4) @@ -1953,7 +1954,7 @@ def test_high_moments_across_a_very_short_epoch_match_an_extended_precision_refe References from a 100-digit mpmath Van Loan computation.""" if sparse: pg.Settings.closed_form_sparse_min_states = 1 - pg.Settings.expm_action_min_dim = 0 + pg.Settings.expm_method = 'action' two_demes = pg.Coalescent(n=pg.LineageConfig({'a': 2, 'b': 2}), demography=pg.Demography( pop_sizes={'a': {0: 1, 1: 2, 1 + 1e-12: 0.5}, 'b': {0: 1, 1: 3}}, @@ -1989,7 +1990,7 @@ def test_action_path_moments_do_not_depend_on_the_other_end_times(): """On the sparse-action path each step is balanced on its own length, so a moment at one end time is the same whether or not later end times are requested with it. Regression: the factor was taken from the last end time, and the fifth raw moment at t = 1e-3 came out 44% off when evaluated together with t = 10.""" - pg.Settings.expm_action_min_dim = 1 + pg.Settings.expm_method = 'action' reward = (pg.rewards.TreeHeightReward(),) * 5 times = [1.5e-4, 1e-3, 1e-2, 10] @@ -2163,7 +2164,7 @@ def coals(): pop_sizes={'a': 1, 'b': 2}, migration_rates={('a', 'b'): 0.5, ('b', 'a'): 1}))] dense = [(c.tree_height.cdf(np.inf), c.tree_height.cdf(1e6)) for c in coals()] - monkeypatch.setattr(pg.Settings, 'expm_action_min_dim', 2) + monkeypatch.setattr(pg.Settings, 'expm_method', 'action') for c, (cdf_inf, cdf_far) in zip(coals(), dense): assert c.tree_height.cdf(np.inf) == pytest.approx(cdf_inf, rel=1e-12) @@ -2212,7 +2213,7 @@ def acc(): return pg.Coalescent(n=4, model=pg.BetaCoalescent(alpha=1.5)).sfs.accumulate(1, [0.5, np.nan, 2.0]) dense = acc() - monkeypatch.setattr(pg.Settings, 'expm_action_min_dim', 0) + monkeypatch.setattr(pg.Settings, 'expm_method', 'action') action = acc() assert np.isnan(action[1, 1:-1]).all() @@ -2419,7 +2420,7 @@ def moments(): assert dense[0] == pytest.approx(acc[1] - acc[0], rel=1e-10) np.testing.assert_allclose(dense[::2], dense[1::2], rtol=1e-10) - monkeypatch.setattr(pg.Settings, 'expm_action_min_dim', 0) + monkeypatch.setattr(pg.Settings, 'expm_method', 'action') monkeypatch.setattr(pg.Settings, 'closed_form_sparse_min_states', 1) np.testing.assert_allclose(moments(), dense, rtol=1e-8) diff --git a/testing/test_coverage_gaps.py b/testing/test_coverage_gaps.py index 6531bdc9..1b3fa869 100644 --- a/testing/test_coverage_gaps.py +++ b/testing/test_coverage_gaps.py @@ -172,29 +172,29 @@ def test_empirical_sfs_mean_is_sfs_type(self): self.assertEqual(np.asarray(emp.mean).shape, (6,)) self.assertEqual(np.asarray(emp.cov).shape, (6, 6)) - def test_sfs_cov_batched_is_cached(self): - """SFSDistribution._cov_batched is memoized, so accessing sfs.corr (which reads both var and cov, each of - which needs the shared two-point occupation) runs the expensive solve only once, without changing results.""" - import phasegen.distributions.spectra as sp + def test_sfs_second_moments_are_cached(self): + """The second moments of the SFS are memoized, so accessing sfs.corr, which reads the variance and the + covariance, runs the forward pass over the bins once, without changing results.""" + from phasegen.distributions._moments import MomentEvaluator - # reference correlation before instrumenting the solve reference = np.asarray(pg.Coalescent(n=6).sfs.corr.data).copy() calls = {'n': 0} - original = sp.SFSDistribution._two_point_occupation + original = MomentEvaluator._bin_second_moments + sfs = pg.Coalescent(n=6).sfs + + # the pass of the flattened spectrum runs on its tree height, which is not counted def counting(self, *args, **kwargs): - calls['n'] += 1 + calls['n'] += self is sfs return original(self, *args, **kwargs) - sp.SFSDistribution._two_point_occupation = counting + MomentEvaluator._bin_second_moments = counting try: - corr = np.asarray(pg.Coalescent(n=6).sfs.corr.data) + corr = np.asarray(sfs.corr.data) + sfs.var finally: - # the method is inherited from the moment-evaluator mixin, so it is removed rather than assigned back: - # assigning would leave a shadowing entry in ``SFSDistribution.__dict__`` that later patches of the base - # class never reach - del sp.SFSDistribution._two_point_occupation + MomentEvaluator._bin_second_moments = original - self.assertEqual(calls['n'], 1) # a single shared solve, not one per var and cov + self.assertEqual(calls['n'], 1) np.testing.assert_allclose(corr, reference) diff --git a/testing/test_demography.py b/testing/test_demography.py index 38f5eada..46123d64 100644 --- a/testing/test_demography.py +++ b/testing/test_demography.py @@ -1465,3 +1465,87 @@ def test_pulse_agrees_with_msprime_mass_migration_under_every_coalescent_model(m heights = np.array([ts.first().time(ts.first().root) for ts in reps]) assert abs(exact - heights.mean()) < 4 * heights.std() / np.sqrt(len(heights)) + + +def test_nan_time_raises_its_own_error(): + """A NaN epoch time raises a ValueError naming NaN. Regression: it was reported as a negative time.""" + with pytest.raises(ValueError, match='Times must not be NaN'): + pg.DiscreteRateChanges(pop_sizes={'pop_0': {0: 1, np.nan: 2}}) + + with pytest.raises(ValueError, match='Times must not be NaN'): + pg.Demography(pop_sizes={'pop_0': {0: 1, np.nan: 2}}) + + with pytest.raises(ValueError, match='All times must not be negative'): + pg.DiscreteRateChanges(pop_sizes={'pop_0': {0: 1, -1: 2}}) + + +def test_discretized_trajectory_returning_a_size_one_array_is_coerced(): + """A trajectory returning a size-1 array gives the same epochs as one returning the float, and one returning + several values raises a ValueError naming the trajectory. Regression: the array was stored as the rate unconverted + and failed later with an unrelated NumPy shape error.""" + def coalescent(trajectory): + return pg.Coalescent(n=3, demography=pg.Demography(events=[pg.DiscretizedRateChange( + trajectory=trajectory, start_time=0, end_time=1, pop='pop_0', step_size=0.25)])) + + as_float = coalescent(lambda t: 1 + t) + as_array = coalescent(lambda t: np.array([1 + t])) + + sizes = [e.pop_sizes['pop_0'] for e in islice(as_array.demography.epochs, 5)] + assert all(type(s) is float for s in sizes) + assert as_array.tree_height.mean == pytest.approx(as_float.tree_height.mean, rel=1e-14) + + with pytest.raises(ValueError, match='population size trajectory of pop_0 must return a single number'): + list(islice(coalescent(lambda t: np.array([1 + t, 2])).demography.epochs, 3)) + + with pytest.raises(ValueError, match='migration rate trajectory from a to b must return a single number'): + list(islice(pg.Demography(pop_sizes={'a': 1, 'b': 1}, events=[pg.DiscretizedRateChange( + trajectory=lambda t: [0.1, 0.2], start_time=0, end_time=1, source='a', dest='b')]).epochs, 3)) + + +def test_discretized_trajectory_holds_its_end_value_from_end_time_on(caplog): + """From its end time on, a discretized trajectory holds its value at the end time, which an event at that time + overrides without a clash warning. Regression: the epochs from the end time on inherited the mean of the last + step, which put the mean tree height of 10 lineages declining at rate 2 until time 1 at 10.21, against 11.10 from + msprime.""" + def growth(): + return pg.ExponentialPopSizeChanges(initial_size={'pop_0': 1}, growth_rate=-2, start_time=0, end_time=1) + + d = pg.Demography(events=[growth()]) + + assert d.get_epoch(1.0).pop_sizes['pop_0'] == pytest.approx(np.exp(2), rel=1e-14) + assert d.get_epoch(5.0).pop_sizes['pop_0'] == pytest.approx(np.exp(2), rel=1e-14) + assert pg.Coalescent(n=10, demography=d).tree_height.mean == pytest.approx(11.10, rel=0.01) + + with caplog.at_level('WARNING'): + explicit = pg.Demography(events=[growth(), pg.PopSizeChange(pop='pop_0', time=1, size=3)]) + + assert explicit.get_epoch(2.0).pop_sizes['pop_0'] == 3 + + assert not [r for r in caplog.records if 'Several events set' in r.getMessage()] + + +def test_rate_set_at_the_end_of_a_trajectory_takes_precedence(): + """A size or migration rate that an event starting before a trajectory sets at the trajectory's end time applies + from then on, as in msprime. Regression: the end value of the trajectory overwrote it whenever that event sorted + first, such as the pop_sizes and migration_rates dictionaries, which put the mean tree height of a demography + imported from msprime 24 standard errors from msprime.""" + sizes = pg.Demography(pop_sizes={'pop_0': {0: 1, 2: 3}}, events=[pg.ExponentialPopSizeChanges( + initial_size={'pop_0': 1}, growth_rate=-1, start_time=0.5, end_time=2, step_size=0.25)]) + rates = pg.Demography(pop_sizes={'pop_0': 1, 'pop_1': 1}, migration_rates={('pop_0', 'pop_1'): {0: 0.1, 2: 0.5}}, + events=[pg.DiscretizedRateChange(trajectory=lambda t: 0.1 * np.exp(t), start_time=0.5, + end_time=2, source='pop_0', dest='pop_1')]) + + assert sizes.get_epoch(3).pop_sizes['pop_0'] == 3 + assert rates.get_epoch(3).migration_rates[('pop_0', 'pop_1')] == 0.5 + + +def test_to_demes_names_the_migration_restriction(): + """A demography with a split, a pulse or a migration rate above 1 raises a ValueError naming the demes restriction. + Regression: demes raised 'invalid migration' from inside the conversion.""" + split = pg.Demography(pop_sizes={'a': 1, 'b': 1}, + events=[pg.PopulationSplit(time=1, derived='b', ancestral='a')]) + fast = pg.Demography(pop_sizes={'a': 1, 'b': 1}, migration_rates={('a', 'b'): 1.5}) + + for d in (split, fast): + with pytest.raises(ValueError, match='demes takes migration rates of at most 1'): + d.to_demes() diff --git a/testing/test_distributions.py b/testing/test_distributions.py index 15586fbb..9a93e066 100644 --- a/testing/test_distributions.py +++ b/testing/test_distributions.py @@ -106,7 +106,7 @@ def test_propagated_vector_matches_the_dense_transition_matrix(self): def test_matrix_exponential_action_agrees_with_the_dense_path(self): """ The tree-height cdf / pdf / quantile must not depend on which propagation path - :attr:`Settings.expm_action_min_dim` selects: the sparse action and the dense exponential compute the same + :attr:`Settings.expm_method` selects: the sparse action and the dense exponential compute the same thing. This is what a state space too large to densify relies on, and the CDF used to ignore the setting outright and form the dense ``k x k`` propagator regardless. """ @@ -120,12 +120,9 @@ def test_matrix_exponential_action_agrees_with_the_dense_path(self): dense = pg.Coalescent(n=15, demography=demo).tree_height ref = dense.cdf(t), dense.pdf(t), dense.quantile(q) - try: - Settings.expm_action_min_dim = 1 # force every propagation through the sparse action - action = pg.Coalescent(n=15, demography=demo).tree_height - got = action.cdf(t), action.pdf(t), action.quantile(q) - finally: - Settings.expm_action_min_dim = 1500 + Settings.expm_method = 'action' + action = pg.Coalescent(n=15, demography=demo).tree_height + got = action.cdf(t), action.pdf(t), action.quantile(q) for a, b in zip(ref, got): np.testing.assert_allclose(b, a, rtol=1e-8, atol=1e-10) @@ -177,22 +174,17 @@ def test_tree_height_cdf_and_pdf_at_infinity_and_huge_times(self): """ from phasegen.settings import Settings - dim = Settings.expm_action_min_dim + for method in ('dense', 'action'): + Settings.expm_method = method + th = pg.Coalescent(n=5, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 2: 0.5}})).tree_height - try: - for min_dim in (10 ** 9, 1): - Settings.expm_action_min_dim = min_dim - th = pg.Coalescent(n=5, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 2: 0.5}})).tree_height + x = np.array([1.0, 1e300, np.inf]) + cdf, pdf = th.cdf(x), th.pdf(x) - x = np.array([1.0, 1e300, np.inf]) - cdf, pdf = th.cdf(x), th.pdf(x) - - self.assertAlmostEqual(cdf[0], th.cdf(1.0), delta=1e-14) - np.testing.assert_array_equal(cdf[1:], 1.0) - np.testing.assert_allclose(pdf[1:], 0.0, atol=1e-300) - self.assertEqual(th.cdf(np.inf), 1.0) - finally: - Settings.expm_action_min_dim = dim + self.assertAlmostEqual(cdf[0], th.cdf(1.0), delta=1e-14) + np.testing.assert_array_equal(cdf[1:], 1.0) + np.testing.assert_allclose(pdf[1:], 0.0, atol=1e-300) + self.assertEqual(th.cdf(np.inf), 1.0) def test_tree_height_quantile_resolves_the_lower_tail(self): """ diff --git a/testing/test_empirical_parity_ejoint.py b/testing/test_empirical_parity_ejoint.py index 28d932e7..6ef994ab 100644 --- a/testing/test_empirical_parity_ejoint.py +++ b/testing/test_empirical_parity_ejoint.py @@ -162,7 +162,7 @@ def test_empirical_joint_pdf_excludes_the_axes_and_needs_two_points(): jd.pdf(1.0, 1.0) -def test_empirical_joint_plots_as_the_exact_one(one_deme): +def test_empirical_joint_plots_as_the_exact_one(one_deme, caplog): """The joint CDF and density draw heatmaps and surfaces, the density at its cell centres, and plot_cdf works.""" import matplotlib.pyplot as plt @@ -172,8 +172,8 @@ def test_empirical_joint_plots_as_the_exact_one(one_deme): sampled.cdf.plot(show=False) sampled.pdf.plot(show=False) sampled.pdf.plot_surface(show=False) - with pytest.warns(DeprecationWarning): - sampled.plot_cdf(show=False) + sampled.plot_cdf(show=False) + assert any('plot_cdf() is deprecated' in r.getMessage() for r in caplog.records) plt.close('all') cdf, pdf = sampled.cdf._plot_data(n_points=12), sampled.pdf._plot_data(n_points=12) diff --git a/testing/test_expm.py b/testing/test_expm.py index 815490d1..da923be2 100644 --- a/testing/test_expm.py +++ b/testing/test_expm.py @@ -110,3 +110,46 @@ def compute(self, m): pg.Backend.backend = previous assert got == pytest.approx(expected, rel=1e-12) + + +@pytest.mark.parametrize('stiff', [False, True]) +def test_expm_multiply_interval_steps_where_stiff(stiff): + """ + The interval action matches the actions of each multiple. Below the stiff threshold it takes one interval action + of the backend, above it it applies the steps one by one, each stopping once the vector is stationary. + """ + from unittest.mock import patch + import scipy.sparse as sp + from scipy.sparse.linalg import expm_multiply + from phasegen.expm import Backend + + rng = np.random.default_rng(0) + S = sp.random(30, 30, density=0.2, random_state=1).toarray() + S -= np.diag(S.sum(axis=1) + 0.5) + a = sp.csr_matrix(S.T * (1e3 if stiff else 1.0)) + b = rng.uniform(size=30) + stop, num = 2.0, 7 + + with patch.object(Backend.backend, 'compute_action_interval', wraps=Backend.backend.compute_action_interval) as spy: + out = Backend.expm_multiply_interval(a, b, stop, num) + + assert spy.call_count == (0 if stiff else 1) + assert out.shape == (num, 30) + + ref = np.stack([expm_multiply(a * (stop * (j + 1) / num), b) for j in range(num)]) + np.testing.assert_allclose(out, ref, rtol=1e-12, atol=1e-14 * np.abs(ref).max()) + + +def test_default_backend_interval_action(): + """The interval action of a backend without its own repeats the dense exponential of one step.""" + from phasegen.expm import ExpmBackend + + class Dense(ExpmBackend): + def compute(self, m): + return scipy.linalg.expm(m) + + a = np.array([[-1.0, 1.0], [0.0, -2.0]]) + b = np.array([1.0, 2.0]) + out = Dense().compute_action_interval(a, b, 3.0, 3) + + np.testing.assert_allclose(out, [scipy.linalg.expm(a * s) @ b for s in (1, 2, 3)], rtol=1e-13) diff --git a/testing/test_expm_action.py b/testing/test_expm_action.py index d8b5cb2a..c69e3b24 100644 --- a/testing/test_expm_action.py +++ b/testing/test_expm_action.py @@ -12,8 +12,8 @@ from phasegen.settings import Settings #: force the dense / action path respectively -DENSE = 10 ** 9 -ACTION = 0 +DENSE = 'dense' +ACTION = 'action' def _demography(pop_sizes, migration_rate=1.0, two_epoch=False): @@ -31,10 +31,10 @@ def _demography(pop_sizes, migration_rate=1.0, two_epoch=False): def _both_paths(make, get): """Compute the statistic with the dense and the action path.""" - Settings.expm_action_min_dim = DENSE + Settings.expm_method = DENSE dense = np.asarray(get(make())) - Settings.expm_action_min_dim = ACTION + Settings.expm_method = ACTION action = np.asarray(get(make())) return dense, action @@ -153,11 +153,11 @@ def test_tree_height_terms_bounded_by_beta_alpha_close_to_two(): def tree_height(): return pg.Coalescent(n=6, model=pg.BetaCoalescent(alpha=2 - 1e-6)).tree_height - Settings.expm_action_min_dim = DENSE + Settings.expm_method = DENSE th = tree_height() pdf, cdf = th.pdf(t), th.cdf(t) - Settings.expm_action_min_dim = ACTION + Settings.expm_method = ACTION core, terms = _expm_multiply._expm_multiply_simple_core, [0] def counted(A, B, t_, mu, m_star, s, *args, **kwargs): @@ -173,3 +173,53 @@ def counted(A, B, t_, mu, m_star, s, *args, **kwargs): _expm_multiply._expm_multiply_simple_core = core assert 0 < terms[0] < 40000 + + +@pytest.mark.parametrize('method', [ACTION, DENSE]) +def test_occupation_grid_reuses_propagators(method): + """ + The batched mean accumulation of a spectrum over an equally spaced grid crossing epoch boundaries, with a start + time, forms one dense exponential per epoch and step length, or takes one interval action per run on the sparse + path, and agrees with the accumulation to each end time alone. + """ + from unittest.mock import patch + from phasegen.distributions._moments import MomentEvaluator + + Settings.expm_method = method + Settings.flatten_block_counting = False + sfs = pg.Coalescent(n=6, demography=_demography({'pop_0': 1.0}, two_epoch=True)).sfs + t = np.linspace(0.2, 3, 60) + + with patch.object(MomentEvaluator, '_block_expm', side_effect=MomentEvaluator._block_expm) as spy: + grid = sfs.accumulate(1, t, start_time=0.1) + + if method == DENSE: + assert spy.call_count <= 12 + + ref = np.array([sfs.accumulate(1, [u], start_time=0.1)[0] for u in t]) + np.testing.assert_allclose(grid, ref, rtol=1e-11, atol=1e-14 * np.abs(ref).max()) + + +@pytest.mark.parametrize('method', [ACTION, DENSE]) +def test_windowed_accumulation_over_grid(method): + """ + The windowed second moment over an equally spaced grid crossing epoch boundaries, with end times before the start + time, agrees with the moment to each end time alone, on the dense path reusing one exponential per step and on + the sparse path by one interval action per run. + """ + from unittest.mock import patch + from phasegen.distributions._moments import MomentEvaluator + + Settings.expm_method = method + th = pg.Coalescent(n=6, demography=_demography({'pop_0': 1.0}, two_epoch=True)).tree_height + t = np.linspace(0, 3, 40) + + with patch.object(MomentEvaluator, '_block_expm', side_effect=MomentEvaluator._block_expm) as spy: + grid = th.accumulate(2, t, start_time=0.3) + + if method == DENSE: + assert spy.call_count <= 12 + ref = np.array([th.accumulate(2, [u], start_time=0.3)[0] for u in t]) + + np.testing.assert_allclose(grid, ref, rtol=1e-11, atol=1e-14 * np.abs(ref).max()) + assert np.all(grid[t <= 0.3] == 0) diff --git a/testing/test_gradient.py b/testing/test_gradient.py index 668db779..42245073 100644 --- a/testing/test_gradient.py +++ b/testing/test_gradient.py @@ -97,7 +97,7 @@ def f(x, key=key, idx=idx): def test_mean_gradient_matches_central_differences(n, stat, model, action): """The gradient over sizes, migration rates and epoch start times, on the dense and on the sparse-action path.""" if action: - Settings.expm_action_min_dim = 0 + Settings.expm_method = 'action' _assert_mean_gradient(n, stat, model) @@ -132,7 +132,7 @@ def test_mean_gradient_at_zero_migration_rate(action): """The derivative by a migration rate of zero, from the right. Regression: the gradient was taken on the sparsity pattern of the generator of the epoch, which lacks the migration entries at a rate of zero, about 70 times off.""" if action: - Settings.expm_action_min_dim = 0 + Settings.expm_method = 'action' def tree_height(m): return pg.Coalescent(n={'pop_0': 2, 'pop_1': 2}, demography=pg.Demography( @@ -149,28 +149,6 @@ def tree_height(m): assert grad.migration_rates[0, 0] == pytest.approx(one_sided, rel=1e-6) -def test_generator_basis_failure_restores_epoch(monkeypatch): - """A state space without a basis is returned to its epoch, and the failure is kept on it.""" - from phasegen.distributions._gradient import _GeneratorBasis - - def fail(self, *args): - raise ValueError('not affine') - - monkeypatch.setattr(_GeneratorBasis, '_check', fail) - th = pg.Coalescent(n=4, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.5: 2}})).tree_height - ss = th.state_space - epoch = ss.epoch - - with pytest.raises(ValueError, match='not affine'): - _GeneratorBasis(ss) - assert ss.epoch == epoch - - for _ in range(2): - with pytest.raises(ValueError, match='not affine'): - MeanGradient(th).compute_columns(np.asarray(th.reward._get(ss), dtype=float)[:, None]) - assert isinstance(ss.__dict__['_generator_basis'], ValueError) - - def test_mean_gradient_undefined_without_certain_absorption(): """Without certain absorption in the last epoch, the occupation has no closed form and no gradient.""" coal = pg.Coalescent(n={'pop_0': 1, 'pop_1': 1}, demography=pg.Demography(pop_sizes={'pop_0': 1, 'pop_1': 1})) @@ -631,20 +609,18 @@ def _state_spaces(): @pytest.mark.parametrize('get_state_space', _state_spaces()) -def test_generator_basis_reproduces_the_generator(get_state_space): - """The affine basis rebuilds the generator at random population sizes and migration rates, for every coalescent - model and state space, and returns the state space to its epoch.""" +def test_generator_parts_reproduce_the_generator(get_state_space): + """The parts of the generator rebuild it at random population sizes and migration rates, for every coalescent + model and state space.""" from phasegen.demography import Epoch - from phasegen.distributions._gradient import _GeneratorBasis + from phasegen.distributions._gradient import _GeneratorDerivatives ss = get_state_space() epoch = ss.epoch - basis = _GeneratorBasis(ss) + basis = _GeneratorDerivatives(ss) model = ss.model rng = np.random.default_rng(3) - assert ss.epoch == epoch - try: for _ in range(5): sizes = {p: float(np.exp(rng.normal(0, 1))) for p in basis.pops} @@ -669,11 +645,11 @@ def test_generator_basis_size_derivative(model): """The derivative of the generator by a population size, the coefficient times the coalescence part, against central differences of the generator.""" from phasegen.demography import Epoch - from phasegen.distributions._gradient import _GeneratorBasis + from phasegen.distributions._gradient import _GeneratorDerivatives ss = pg.Coalescent(n=5, **({} if model is None else dict(model=model))).sfs.state_space epoch = ss.epoch - basis = _GeneratorBasis(ss) + basis = _GeneratorDerivatives(ss) def S(N): ss.update_epoch(Epoch(pop_sizes={'pop_0': N})) @@ -693,10 +669,10 @@ def test_generator_basis_pattern_holds_migration_at_rate_zero(): """The union pattern of the transient parts holds the migration entries, which a generator at a migration rate of zero lacks.""" from phasegen.demography import Epoch - from phasegen.distributions._gradient import _GeneratorBasis + from phasegen.distributions._gradient import _GeneratorDerivatives ss = pg.Coalescent(n={'a': 2, 'b': 2}, demography=pg.Demography(pop_sizes={'a': 1, 'b': 1})).tree_height.state_space - basis = _GeneratorBasis(ss) + basis = _GeneratorDerivatives(ss) idx_t = np.arange(ss.S.shape[0] - 1) _, M, rows, cols = basis.transient(idx_t) pattern = set(zip(rows.tolist(), cols.tolist())) @@ -780,7 +756,7 @@ def test_gradient_of_higher_moments_matches_differences(moment, gradient, sparse """The derivatives of central, raw and cross moments of order two and three by a population size, an epoch start time, a migration rate and alpha, on the dense exponentials and the sparse actions and solves.""" if sparse: - monkeypatch.setattr(Settings, 'expm_action_min_dim', 1) + monkeypatch.setattr(Settings, 'expm_method', 'action') monkeypatch.setattr(Settings, 'closed_form_sparse_min_states', 1) grad = gradient(_three_epochs()) @@ -921,7 +897,7 @@ def test_gradient_by_recombination_rate_near_zero(n, r, action, expected): reverse pass of the action and of the sparse last epoch then lacked, so the derivative came out as -0.480 for n=3 on the action path and -1.418 for n=5 on the sparse last epoch. At r=1e-9, the central difference of the generator shrank its step to 1e-12 and lost three digits to cancellation.""" - Settings.expm_action_min_dim = 0 if action else 10 ** 9 + Settings.expm_method = 'action' if action else 'dense' assert _two_locus(n, r).tree_height.gradient().parameters['recombination_rate'] == pytest.approx(expected, rel=1e-8) @@ -1150,43 +1126,6 @@ def test_gradient_of_a_zero_reward_is_zero(): assert not th.gradient(k, (zero,) * k, center=center).pop_sizes.any() -def test_parameter_jacobian_of_a_non_affine_generator_uses_differences(monkeypatch, caplog): - """A generator that is not affine in the rates is differentiated by central differences, as noted in the log.""" - import logging - import phasegen.gradient - - def raise_(state_space): - raise ValueError('The generator is not affine in the inverse time scales and migration rates.') - - monkeypatch.setattr(phasegen.gradient, '_generator_basis', raise_) - gradient = pg.Gradient(lambda N: pg.Coalescent(n=4, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.5: N}})), - lambda c: c.tree_height.var) - - with caplog.at_level(logging.INFO, logger='phasegen'): - value, jacobian = gradient.compute(dict(N=1.3)) - - assert jacobian[0] == pytest.approx(_richardson(lambda N: float(gradient.coal(N=N).tree_height.var), 1.3), rel=1e-6) - assert any('not affine' in r.getMessage() for r in caplog.records) - - -def test_inference_names_a_non_affine_generator(monkeypatch, caplog): - """The warning of an inference whose generator is not affine names that reason, not the moments of the loss.""" - import phasegen.gradient - - def raise_(state_space): - raise ValueError('The generator is not affine in the inverse time scales and migration rates.') - - monkeypatch.setattr(phasegen.gradient, '_generator_basis', raise_) - coal = lambda N: pg.Coalescent(n=4, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.5: N}})) - - with caplog.at_level('WARNING'): - _inference(coal, lambda c, obs: float(c.tree_height.var), {'N': 1.0}, {'N': (0.1, 5)}, None)._announce_gradient( - {'N': 1.0}, None) - - messages = [r.getMessage() for r in caplog.records if r.levelname == 'WARNING'] - assert any('not affine' in m for m in messages) and not any('reads more' in m for m in messages) - - def test_loss_gradient_of_moments_with_the_default_window(): """A start time of zero and an infinite end time passed explicitly are no window.""" coal = lambda N: pg.Coalescent(n=4, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.5: N}})) @@ -1250,11 +1189,11 @@ def test_group_terms_reads_trailing_orderings_from_longer_runs(): def test_epoch_contractions_are_cached_across_gradients(monkeypatch): """The contractions of the generator derivatives of an epoch are kept across gradients of the same rates, also for more epochs than the bound of the cache.""" - from phasegen.distributions._gradient import _GeneratorBasis + from phasegen.distributions._gradient import _GeneratorDerivatives calls = [] - derivatives = _GeneratorBasis.parameter_derivatives - monkeypatch.setattr(_GeneratorBasis, 'parameter_derivatives', lambda self, epoch, idx: + derivatives = _GeneratorDerivatives.parameter_derivatives + monkeypatch.setattr(_GeneratorDerivatives, 'parameter_derivatives', lambda self, epoch, idx: calls.append(1) or derivatives(self, epoch, idx)) coal = pg.Coalescent(n=4, model=pg.BetaCoalescent(alpha=1.5), demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.5: 2}})) @@ -1285,7 +1224,7 @@ def test_epoch_contractions_are_bounded_in_bytes(monkeypatch): base = coal(2.0) base.sfs.gradient(2) space = base.state_spaces['block_counting'] - basis = space._generator_basis + basis = space._generator_derivatives assert len(basis._contractions) == 2 size = max(basis._cached.values()) @@ -1306,7 +1245,7 @@ def test_supported_builds_only_the_state_spaces_of_the_passes(): n = 50, taking seconds and warning about its size.""" coal = pg.Coalescent(n=12, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.5: 2}})) assert Gradient(lambda N: coal, lambda c: c.sfs.mean.normalize().polymorphic).supported({'N': 1.0}) - assert coal.state_spaces['block_counting']._generator_basis is None + assert '_basis' not in coal.state_spaces['block_counting'].__dict__ def test_parameter_jacobian_by_a_pulse_time(): @@ -1358,29 +1297,29 @@ def test_scores_of_resampled_statistics_reading_coalescent_moments(): assert Gradient(coal, statistics[0])._scores(x, bounds, [other]) is None -def test_payloads_leave_out_the_generator_basis(): - """The generator basis built for a gradient is left out of the payloads of the coalescent and the inference, +def test_payloads_leave_out_the_generator_derivatives(): + """The derivatives of the generator built for a gradient are left out of the payloads of the coalescent and the inference, and rebuilt on use.""" coal = pg.Coalescent(n=5, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.5: 2}})) expected = coal.tree_height.gradient(2).pop_sizes - assert coal.state_spaces['lineage_counting']._generator_basis is not None + assert coal.state_spaces['lineage_counting']._generator_derivatives is not None restored = pg.Coalescent.from_json(coal.to_json()) - assert restored.state_spaces['lineage_counting']._generator_basis is None + assert restored.state_spaces['lineage_counting']._generator_derivatives is None np.testing.assert_allclose(restored.tree_height.gradient(2).pop_sizes, expected, rtol=1e-12) -def test_drop_cache_drops_the_generator_basis(): - """Dropping the caches of a coalescent frees the generator basis and its contractions. Regression: they were +def test_drop_cache_drops_the_generator_derivatives(): + """Dropping the caches of a coalescent frees the derivatives of the generator and their contractions. Regression: they were kept.""" coal = pg.Coalescent(n=5, model=pg.BetaCoalescent(alpha=1.5), demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.5: 2}})) coal.sfs.gradient(2) - assert coal.state_spaces['block_counting']._generator_basis is not None + assert coal.state_spaces['block_counting']._generator_derivatives is not None coal.drop_cache() - assert coal.state_spaces['block_counting']._generator_basis is None + assert coal.state_spaces['block_counting']._generator_derivatives is None @pytest.mark.parametrize('case', ['lineage weight', 'locus weight', 'custom model']) @@ -1476,11 +1415,11 @@ def coal(): return pg.Coalescent(n=6, model=pg.BetaCoalescent(alpha=2 - 1e-7), demography=pg.Demography( pop_sizes={'pop_0': {0: 1, 0.5: 2, 1.5: 0.5}})) - monkeypatch.setattr(Settings, 'expm_action_min_dim', 10 ** 9) + monkeypatch.setattr(Settings, 'expm_method', 'dense') dense = coal().sfs mean, grad = dense.mean.data, dense.gradient() - monkeypatch.setattr(Settings, 'expm_action_min_dim', 0) + monkeypatch.setattr(Settings, 'expm_method', 'action') monkeypatch.setattr(_expm_multiply, '_expm_multiply_simple_core', counted_core) monkeypatch.setattr(_TapedAction, '_terms', counted_terms) action = coal().sfs diff --git a/testing/test_inference.py b/testing/test_inference.py index 6ff7913d..7c89de5a 100644 --- a/testing/test_inference.py +++ b/testing/test_inference.py @@ -1834,6 +1834,30 @@ def test_log_scale_estimate_on_a_bound_is_the_bound(caplog): assert 'lie on a bound' in caplog.text +def test_log_scale_estimate_on_a_lower_bound_is_the_bound(caplog): + """An estimate on the logarithmic scale that the optimizer leaves on its lower bound is that bound exactly, and the + covariance warns that it lies on a bound. Here exp(log(0.1)) is 0.1 plus one ulp, inside the bounds, so the + estimate was 0.10000000000000002 and its standard error was reported without the on-bound warning.""" + coal = lambda Ne: pg.Coalescent(n=6, demography=pg.Demography(pop_sizes={'pop_0': Ne})) + inf = pg.Inference( + bounds=dict(Ne=(0.1, 10)), + x0=dict(Ne=1.0), + coal=coal, + loss=lambda c, obs: pg.PoissonLikelihood().compute(obs.polymorphic, 2000 * c.sfs.mean.polymorphic), + observation=pg.SFS(np.concatenate([[0], 2000 * coal(0.02).sfs.mean.polymorphic, [0]])), + n_runs=1, + pbar=False, + log_scale=True + ) + inf.run() + + assert inf.params_inferred['Ne'] == 0.1 + + inf.standard_errors() + + assert any('lie on a bound' in r.getMessage() and 'Ne' in r.getMessage() for r in caplog.records) + + def test_log_scale_accepts_a_single_name(): """A single parameter name as ``log_scale`` puts that parameter on the logarithmic scale. It was split into its characters, raising ``ValueError`` for the unknown parameters ``['N', 'e']``.""" diff --git a/testing/test_joint_sfs.py b/testing/test_joint_sfs.py index fd084aa3..f52e19d2 100644 --- a/testing/test_joint_sfs.py +++ b/testing/test_joint_sfs.py @@ -496,10 +496,16 @@ def test_jsfs_valid_configs_pass_validation(two_pop_coalescent): assert jsfs._bin_config(np.array([1, 0])) == (1, 0) and jsfs._bin_config((1.0, 2.0)) == (1, 2) -def test_bin_distributions_are_served_when_the_cache_is_off(two_pop_coalescent): +def test_bin_distributions_are_served_when_the_cache_is_off(symmetric_demography): """With ``Settings.cache`` off, a stored per-bin distribution is still served and a new one is not stored. - Regression: the stored entry was bypassed and its fit rebuilt on every call.""" - for spectrum, key, other in ((pg.Coalescent(n=4).sfs, 1, 2), (two_pop_coalescent.jsfs, (1, 0), (0, 1))): + Regression: the stored entry was bypassed and its fit rebuilt on every call. The coalescents are built here, as + a bin stored by an earlier test on a shared one would defeat the second assertion.""" + joint = pg.Coalescent( + n={'pop_0': 2, 'pop_1': 2}, + demography=symmetric_demography({'pop_0': 1.0, 'pop_1': 1.5}, migration_rate=0.75) + ) + + for spectrum, key, other in ((pg.Coalescent(n=4).sfs, 1, 2), (joint.jsfs, (1, 0), (0, 1))): stored = spectrum._bin_distribution(key) pg.Settings.cache = False diff --git a/testing/test_kingman_flattening.py b/testing/test_kingman_flattening.py new file mode 100644 index 00000000..7ff2ffb5 --- /dev/null +++ b/testing/test_kingman_flattening.py @@ -0,0 +1,244 @@ +""" +Second moments of the site-frequency spectrum flattened onto the lineage-counting state space for one population and +one locus under the standard coalescent (``MomentEvaluator._flattening_applies`` with ``k = 2``). +""" +from unittest.mock import patch + +import numpy as np +import pytest + +import phasegen as pg +from phasegen.distributions import PhaseTypeDistribution +from phasegen.distributions._kingman import KingmanBlockKernel +from phasegen.rewards import UnfoldedSFSReward as U, FoldedSFSReward as F, CombinedReward, TotalBranchLengthReward, \ + UnitReward, TreeHeightReward +from phasegen.settings import Settings + +DEMOGRAPHIES = { + 'constant': {0: 1.0}, + 'three_epochs': {0: 1.0, 0.5: 0.3, 2: 2.0}, + 'stiff': {0: 1e-3, 0.01: 1e4, 5e4: 1e-2}, +} + + +def _coal(n: int, sizes: str = 'three_epochs', **kwargs) -> pg.Coalescent: + return pg.Coalescent(n, demography=pg.Demography(pop_sizes={'pop_0': DEMOGRAPHIES[sizes]}), **kwargs) + + +def _unflattened(f): + """Evaluate ``f`` with flattening disabled.""" + Settings.flatten_block_counting = False + try: + return f() + finally: + Settings.flatten_block_counting = True + + +def _assert_close(actual, desired, rtol=1e-11): + """Agreement relative to the largest entry, as entries of a covariance cancel.""" + actual, desired = np.asarray(actual, dtype=float), np.asarray(desired, dtype=float) + np.testing.assert_allclose(actual, desired, rtol=0, atol=rtol * max(np.abs(desired).max(), 1e-300)) + + +def _fu_cov(n: int) -> np.ndarray: + """The covariance of the branch lengths of the unfolded SFS under a constant size (Fu, 1995), in units where a + pair coalesces at rate 1, so that :math:`\\operatorname{Cov}[L_i, L_j] = 4 \\sigma_{ij}`.""" + a = lambda m: sum(1 / i for i in range(1, m)) + beta = lambda i: 2 * n * (a(n + 1) - a(i)) / ((n - i + 1) * (n - i)) - 2 / (n - i) + sigma = np.zeros((n - 1, n - 1)) + for i in range(1, n): + for j in range(1, n): + if i == j: + if 2 * i < n: + s = beta(i + 1) + elif 2 * i == n: + s = 2 * (a(n) - a(i)) / (n - i) - 1 / i ** 2 + else: + s = beta(i) - 1 / i ** 2 + else: + hi, lo = max(i, j), min(i, j) + if hi + lo < n: + s = (beta(hi + 1) - beta(hi)) / 2 + elif hi + lo == n: + s = (a(n) - a(hi)) / (n - hi) + (a(n) - a(lo)) / (n - lo) - (beta(hi) + beta(lo + 1)) / 2 - \ + 1 / (hi * lo) + else: + s = (beta(lo) - beta(lo + 1)) / 2 - 1 / (hi * lo) + sigma[i - 1, j - 1] = s + return 4 * sigma + + +@pytest.mark.parametrize('n', [2, 3, 10, 40]) +def test_constant_size_covariance_matches_fu(n): + """The flattened covariance of the unfolded SFS under a constant size equals the closed form of Fu (1995).""" + _assert_close(_coal(n, 'constant').sfs.cov.data[1:n, 1:n], _fu_cov(n), rtol=1e-12) + + +def test_literal_values(): + """Covariances of a small case against stored values of the block-counting evaluation.""" + coal = _coal(4) + _assert_close(coal.sfs.cov.data[1:4, 1:4], [ + [0.4730675462864411, -0.0652984048778864, 0.1344052662526054], + [-0.0652984048778864, 0.4171004211904813, -0.07684926261119007], + [0.1344052662526054, -0.07684926261119007, 0.16313682025237042] + ], rtol=1e-13) + _assert_close(coal.fsfs.cov.data[1:3, 1:3], [ + [0.9050148990440223, -0.1421476674890766], + [-0.1421476674890766, 0.4171004211904813] + ], rtol=1e-13) + _assert_close(_coal(4, start_time=0.2, end_time=1.5).sfs.cov.data[1:4, 1:4], [ + [0.269929364034348, -0.03467549550684379, 0.06233746916270477], + [-0.03467549550684379, 0.23643218915838363, -0.06343896136086177], + [0.06233746916270477, -0.06343896136086177, 0.08248634015514864] + ], rtol=1e-13) + + +@pytest.mark.parametrize('n', [2, 3, 7]) +@pytest.mark.parametrize('sizes', list(DEMOGRAPHIES)) +@pytest.mark.parametrize('window', [(0, None), (0.3, None), (0, 1.0), (0.4, 2.5)]) +def test_spectrum_moments_match_unflattened(n, sizes, window): + """The covariance, variance, correlation and second moments of the unfolded and folded spectra agree with the + block-counting evaluation, also within a window.""" + + def moments(): + coal = _coal(n, sizes, start_time=window[0], end_time=window[1]) + return [coal.sfs.cov.data, coal.sfs.var.data, coal.sfs.corr.data, coal.sfs.moment(2, center=False).data, + coal.fsfs.cov.data, coal.fsfs.var.data, coal.fsfs.moment(2).data] + + for flattened, reference in zip(moments(), _unflattened(moments)): + _assert_close(flattened, reference) + + +@pytest.mark.parametrize('sizes', ['constant', 'three_epochs']) +def test_cross_moments_match_unflattened(sizes): + """Cross-moments of two SFS bins of any kind, ordered or averaged over their orderings, central or raw, and + accumulated to several end times agree with the block-counting evaluation.""" + + def moments(): + coal = _coal(6, sizes) + return [ + coal.moment(2, rewards=(U(2), U(3))), + coal.moment(2, rewards=(U(2), U(3)), center=False, permute=False), + coal.moment(2, rewards=(U(3), U(2)), center=False, permute=False), + coal.moment(2, rewards=(F(1), U(4)), start_time=0.2), + coal.sfs.get_cov(1, 5), + coal.fsfs.get_corr(1, 3), + coal.sfs.accumulate(2, end_times=[3.0, 0.2, np.inf, 1.0]), + coal.sfs.moment(2, end_time=1.5).data, + coal.sfs.bin(2).var, + coal.fsfs.bin(1).var, + PhaseTypeDistribution.moment(coal.sfs, 2, rewards=(CombinedReward([UnitReward(), U(1)]), U(2)), + start_time=0.1, end_time=2.0), + ] + + for flattened, reference in zip(moments(), _unflattened(moments)): + _assert_close(flattened, reference) + + +@pytest.mark.parametrize('setting, value', [('expm_method', 'action'), ('closed_form_last_epoch', False), + ('regularize', False)]) +def test_settings_match_unflattened(setting, value): + """The sparse action, the integration to the time of almost sure absorption and the unbalanced exponentials agree + with the block-counting evaluation under the same setting.""" + setattr(Settings, setting, value) + + def moments(): + coal = _coal(5, start_time=0.1) + return [coal.sfs.cov.data, coal.fsfs.cov.data] + + for flattened, reference in zip(moments(), _unflattened(moments)): + _assert_close(flattened, reference, rtol=1e-9) + + +def test_gradient_matches_unflattened(): + """The value and the exact Jacobian of a statistic reading the covariance and the variance of the spectrum are + those of the block-counting evaluation.""" + + def compute(): + return pg.Gradient( + coal=lambda t, Ne: pg.Coalescent(5, demography=pg.Demography(pop_sizes={'pop_0': {0: 1.0, t: Ne, 2.0: 1.5}})), + statistic=lambda c: np.concatenate([c.sfs.cov.data.ravel(), c.fsfs.var.data]) + ).compute(dict(t=0.3, Ne=0.4)) + + (value, jacobian), (value_ref, jacobian_ref) = compute(), _unflattened(compute) + _assert_close(value, value_ref) + _assert_close(jacobian, jacobian_ref, rtol=1e-10) + + +def test_routes_through_lineage_counting_space(): + """The covariance, variance and second moments of the spectrum and the cross-moments of SFS bins read the level + occupation and never build the block-counting state space.""" + coal = _coal(12) + + with patch.object(PhaseTypeDistribution, '_level_cross_moments', autospec=True, + side_effect=PhaseTypeDistribution._level_cross_moments) as spy: + coal.sfs.cov, coal.sfs.var, coal.fsfs.corr, coal.sfs.moment(2), coal.moment(2, rewards=(U(1), F(3))) + + assert spy.call_count >= 1 + assert 'states' not in coal.state_spaces['block_counting'].__dict__ + + +def test_flattening_predicate(): + """The second moment is flattened for two SFS bins with polymorphic blocks of the standard coalescent on one + population and one locus only.""" + sfs = _coal(6).sfs + assert sfs._flattening_applies(2, (U(1), U(5))) + assert sfs._flattening_applies(2, (F(3), CombinedReward([UnitReward(), U(2)]))) + + assert not sfs._flattening_applies(2) + assert not sfs._flattening_applies(2, (U(1), TotalBranchLengthReward())) + assert not sfs._flattening_applies(2, (U(0), U(1))) + assert not sfs._flattening_applies(2, (F(4), U(1))) + assert not sfs._flattening_applies(2, (CombinedReward([U(1), U(2)]), U(1))) + assert not sfs._flattening_applies(2, (CombinedReward([TreeHeightReward(), U(1)]), U(1))) + assert not sfs._flattening_applies(3, (U(1), U(2), U(3))) + + Settings.flatten_block_counting = False + assert not sfs._flattening_applies(2, (U(1), U(2))) + Settings.flatten_block_counting = True + + for coal in [ + pg.Coalescent(6, model=pg.BetaCoalescent(alpha=1.5)), + pg.Coalescent(6, model=pg.DiracCoalescent(psi=0.5, c=1.0)), + pg.Coalescent(n={'pop_0': 3, 'pop_1': 3}, demography=pg.Demography( + pop_sizes={'pop_0': 1, 'pop_1': 1}, migration_rates={('pop_0', 'pop_1'): 1, ('pop_1', 'pop_0'): 1})), + ]: + assert not coal.sfs._flattening_applies(2, (U(1), U(2))) + + two_loci = pg.Coalescent(n=4, loci=2, recombination_rate=1.0) + assert not two_loci.sfs2._flattening_applies(2, (U(1), U(2))) + + +def test_kernel_matches_enumerated_block_moments(): + """The contraction of an occupation with unit mass on one level equals the expected product of the block counts + of that level, enumerated over the block-counting state space.""" + n = 5 + space = pg.Coalescent(n).state_spaces['block_counting'] + kernel = KingmanBlockKernel(n) + + # the level k of each state, and the probability of each state given its level + levels = space.lineages.sum(axis=(1, 2, 3)) + probs = space._state_probs + counts = space.lineages[:, 0, 0, :n - 1] + + for k in range(2, n + 1): + M = np.zeros((n - 1, n - 1)) + M[n - k, n - k] = 1.0 + X = kernel.contract(M) + at = levels == k + expected = np.einsum('s,si,sj->ij', probs[at], counts[at], counts[at]) + np.testing.assert_allclose(X, expected, rtol=1e-13, atol=1e-15) + + +@pytest.mark.parametrize('n', [2, 3, 10, 30]) +def test_lineage_counting_states_decrease_in_lineages(n): + """ + The flattened cross-moments take the level matrix as upper triangular, which needs the single-deme + lineage-counting states ordered by decreasing number of lineages, so that the generator is upper triangular. + """ + ss = _coal(n).state_spaces['lineage_counting'] + counts = ss.lineages.sum(axis=(1, 2, 3)) + S = ss.S.toarray() if hasattr(ss.S, 'toarray') else np.asarray(ss.S) + + assert np.all(np.diff(counts) < 0) + assert not np.tril(S, -1).any() diff --git a/testing/test_lineage_config.py b/testing/test_lineage_config.py index a699b384..b3d8b8e5 100644 --- a/testing/test_lineage_config.py +++ b/testing/test_lineage_config.py @@ -89,3 +89,11 @@ def test_population_names_must_be_strings(): """Integer population names were accepted and failed later when the names were sorted with the defaults.""" with pytest.raises(TypeError, match="Population names must be strings"): pg.LineageConfig({0: 2, 1: 1}) + + +def test_lineage_config_compares_unequal_to_other_types(): + """A lineage configuration is unequal to an object of another type. Regression: the comparison read the other + object's lineage_dict and raised AttributeError.""" + lc = pg.LineageConfig({'a': 2, 'b': 1}) + + assert lc != None and lc != 3 and lc in [3, lc] diff --git a/testing/test_locus_config.py b/testing/test_locus_config.py index e7371926..2a20f383 100644 --- a/testing/test_locus_config.py +++ b/testing/test_locus_config.py @@ -165,3 +165,11 @@ def test_single_locus_with_unlinked_lineages_or_recombination_raises(make): """Unlinked lineages and recombination were silently ignored on a single locus.""" with pytest.raises(ValueError, match="single locus"): make() + + +def test_locus_config_compares_unequal_to_other_types(): + """A locus configuration is unequal to an object of another type. Regression: the comparison read the other + object's n and raised AttributeError.""" + lc = pg.LocusConfig(n=2, n_unlinked=1, recombination_rate=0.5) + + assert lc != None and lc != 5 and lc in [5, lc] diff --git a/testing/test_moment_routing.py b/testing/test_moment_routing.py index 71fd262e..b6c764e4 100644 --- a/testing/test_moment_routing.py +++ b/testing/test_moment_routing.py @@ -15,7 +15,7 @@ import phasegen as pg from phasegen.settings import Settings -from phasegen.distributions import PhaseTypeDistribution +from phasegen.distributions import PhaseTypeDistribution, TreeHeightDistribution from phasegen.distributions._moments import MomentEvaluator from phasegen.expm import Backend @@ -126,6 +126,48 @@ def test_block_triangular_order_detects_grading_and_falls_back(): assert MomentEvaluator._block_triangular_order(cyc) is None +_MIGRATION = dict(pop_sizes={'a': 1, 'b': 2}, migration_rates={('a', 'b'): 0.5, ('b', 'a'): 0.3}) + + +@pytest.mark.parametrize('coal, key, max_fill', [ + (pg.Coalescent(n=10), 'lineage_counting', 1.0), + (pg.Coalescent(n=10), 'block_counting', 1.0), + (pg.Coalescent(n=10, model=pg.BetaCoalescent(alpha=1.5)), 'block_counting', 1.0), + (pg.Coalescent(n=8, model=pg.DiracCoalescent(psi=0.7, c=50)), 'block_counting', 1.0), + (pg.Coalescent(n={'a': 4, 'b': 4}, demography=pg.Demography(**_MIGRATION)), 'lineage_counting', 3), + (pg.Coalescent(n={'a': 4, 'b': 4}, demography=pg.Demography(**_MIGRATION)), 'block_counting', 6), + (pg.Coalescent(n={'a': 4, 'b': 4}, demography=pg.Demography(**_MIGRATION)), 'joint_block_counting', 11), + (pg.Coalescent(n=4, loci=pg.LocusConfig(n=2, recombination_rate=1)), 'lineage_counting', 3), + (pg.Coalescent(n=4, loci=pg.LocusConfig(n=2, recombination_rate=1)), 'two_locus_block_counting', 4), +], ids=['lineage', 'block', 'block-beta', 'block-dirac', 'lineage-2-demes', 'block-2-demes', 'joint-2-demes', + 'lineage-2-loci', 'two-locus']) +def test_state_spaces_factorize_in_block_triangular_form(coal, key, max_fill): + """ + The ordering of ``_block_triangular_order`` brings ``-T`` of every state-space type into block upper + triangular form over its strongly connected components, so the ``NATURAL``-ordered LU fills only inside the + diagonal blocks: not at all on graded single-deme spaces, and within about twice the measured fill under + migration or recombination. On the joint space of two demes with ``n=6+6`` the default COLAMD ordering fills + 15 times more and factorizes four orders of magnitude slower. + """ + import scipy.sparse.csgraph as csg + import scipy.sparse.linalg as spla + + ss = coal.state_spaces[key] + t = np.where(~np.asarray(ss.absorbing))[0] + A = -sp.csr_matrix(ss.S)[t][:, t] + + perm = MomentEvaluator._block_triangular_order(A) + assert perm is not None and np.array_equal(np.sort(perm), np.arange(len(t))) + + P = A[perm][:, perm].tocoo() + _, labels = csg.connected_components(abs(P), directed=True, connection='strong') + below = P.row > P.col + assert np.all(labels[P.row[below]] == labels[P.col[below]]) + + lu = spla.splu(P.tocsc(), permc_spec='NATURAL') + assert (lu.L.nnz + lu.U.nnz - len(t)) / A.nnz <= max_fill + + # ---------------------------------------------------------------------------------------------------------------- # path dispatch (closed-form vs matrix-exponential, dense vs sparse action) # ---------------------------------------------------------------------------------------------------------------- @@ -152,20 +194,20 @@ def test_matrix_exponential_path_when_closed_form_disabled(): assert dispatch.call_count >= 1 -def test_sparse_action_path_taken_below_threshold(): - """A zero ``expm_action_min_dim`` forces the sparse matrix-exponential action (``_action_operator``).""" +def test_sparse_action_path_forced(): + """``Settings.expm_method = 'action'`` forces the sparse matrix-exponential action (``_action_operator``).""" Settings.closed_form_last_epoch = False - Settings.expm_action_min_dim = 0 + Settings.expm_method = 'action' coal = pg.Coalescent(n=5) with _spy('_action_operator') as action: _ = coal.tree_height.mean assert action.call_count >= 1 -def test_dense_expm_path_taken_above_threshold(): - """A huge ``expm_action_min_dim`` keeps the dense Van Loan exponential (no action path).""" +def test_dense_expm_path_forced(): + """``Settings.expm_method = 'dense'`` keeps the dense Van Loan exponential (no action path).""" Settings.closed_form_last_epoch = False - Settings.expm_action_min_dim = 10 ** 12 + Settings.expm_method = 'dense' coal = pg.Coalescent(n=5) with _spy('_action_operator') as action: _ = coal.tree_height.mean @@ -179,7 +221,7 @@ def test_accumulate_restores_input_order_for_unsorted_times(force_sparse): moments for >= 3 unsorted times, with both the dense and the sparse-action exponential of ``_accumulate_windowed``. """ Settings.closed_form_last_epoch = False - Settings.expm_action_min_dim = 0 if force_sparse else 10 ** 12 + Settings.expm_method = 'action' if force_sparse else 'dense' th = pg.Coalescent(n=5).tree_height times = [3.0, 0.5, 2.0, 1.0] # >= 3 entries and unsorted -> exposes the permutation bug @@ -223,7 +265,7 @@ def mean() -> np.ndarray: def test_closed_form_finite_epochs_dense_on_stiff_rates(): """The finite epochs of the closed form use the dense Van Loan exponential on stiff rates below - ``expm_action_min_dim`` even where the last-epoch LU is sparse. Regression: a sparse LU forced the sparse action, + the dimension cap of ``Settings.expm_method = 'auto'`` even where the last-epoch LU is sparse. Regression: a sparse LU forced the sparse action, 15 to 30 times slower on lineage-counting chains from 256 states on.""" Settings.closed_form_sparse_min_states = 0 th = pg.Coalescent(n=10, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.3: 0.2, 1: 2}})).tree_height @@ -233,13 +275,14 @@ def test_closed_form_finite_epochs_dense_on_stiff_rates(): assert action.call_count == 0 # the block-counting space of 17 lineages is not stiff and keeps the sparse action + Settings.flatten_block_counting = False sfs = pg.Coalescent(n=17, demography=th.demography).sfs reward = pg.rewards.CombinedReward([sfs.reward, sfs._get_sfs_reward(2)]) with patch.object(Backend, 'expm_multiply', side_effect=Backend.expm_multiply) as action: PhaseTypeDistribution.moment(sfs, k=2, rewards=(reward, reward)) assert action.call_count > 0 - Settings.expm_action_min_dim = 0 + Settings.expm_method = 'action' assert m == pytest.approx(pg.Coalescent(n=10, demography=th.demography).tree_height.moment(2, start_time=0.2), rel=1e-10) @@ -265,35 +308,10 @@ def test_closed_form_finite_epochs_take_action_below_sparse_lu_threshold(): var = PhaseTypeDistribution.moment(sfs, k=2, rewards=(reward, reward)) assert action.call_count > 0 - Settings.expm_action_min_dim = 10 ** 9 - with patch('phasegen.distributions._moments._DENSE_EXPM_STEP_NORM', 0.0): - dense = pg.Coalescent(n=coal._lineages.lineage_dict, demography=coal.demography) - np.testing.assert_allclose(mean, dense.sfs.mean.data, rtol=1e-12) - assert var == pytest.approx(PhaseTypeDistribution.moment(dense.sfs, k=2, rewards=(reward, reward)), rel=1e-12) - - -@pytest.mark.parametrize('force_sparse', [False, True]) -@pytest.mark.parametrize('folded', [False, True]) -def test_multi_epoch_sfs_cov_stacks_bins(force_sparse, folded): - """The multi-epoch SFS covariance evaluates one closed form per second bin, all first bins stacked in one extended - vector, and matches the per-pair cross-moments. Regression: one closed form per ordered bin pair.""" - Settings.closed_form_sparse_min_states = 0 if force_sparse else 10 ** 9 - Settings.expm_action_min_dim = 0 if force_sparse else 10 ** 9 - coal = pg.Coalescent(n=6, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.3: 0.2, 1: 2}})) - sfs = coal.fsfs if folded else coal.sfs - indices = sfs._get_indices() - - with _spy('_accumulate_closed_form') as cf: - cov = np.asarray(sfs.cov.data) - assert cf.call_count == (len(indices) if force_sparse else len(indices) * (len(indices) + 1)) - - mean = np.asarray(sfs.mean.data) - for i in indices: - for j in indices: - rewards = tuple(pg.rewards.CombinedReward([sfs.reward, sfs._get_sfs_reward(b)]) for b in (i, j)) - m_ij = PhaseTypeDistribution.moment(sfs, k=2, rewards=rewards, center=False, permute=False) - m_ji = PhaseTypeDistribution.moment(sfs, k=2, rewards=rewards[::-1], center=False, permute=False) - assert cov[i, j] == pytest.approx((m_ij + m_ji) / 2 - mean[i] * mean[j], rel=1e-10, abs=1e-12) + Settings.expm_method = 'dense' + dense = pg.Coalescent(n=coal._lineages.lineage_dict, demography=coal.demography) + np.testing.assert_allclose(mean, dense.sfs.mean.data, rtol=1e-12) + assert var == pytest.approx(PhaseTypeDistribution.moment(dense.sfs, k=2, rewards=(reward, reward)), rel=1e-12) # ---------------------------------------------------------------------------------------------------------------- @@ -524,7 +542,7 @@ def test_accumulate_passes_nan_end_time_through(caplog, force_sparse): """A NaN end time gives a NaN moment without a warning and leaves the other end times unchanged. Regression: it logged a warning blaming an ill-conditioned rate matrix.""" Settings.closed_form_last_epoch = False - Settings.expm_action_min_dim = 0 if force_sparse else 10 ** 12 + Settings.expm_method = 'action' if force_sparse else 'dense' th = pg.Coalescent(n=4, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.5: 2}})).tree_height with caplog.at_level('WARNING'): @@ -583,3 +601,365 @@ def test_closed_forms_of_all_orders_share_the_last_epoch_factorization(monkeypat coal.moment(3, rewards=[pg.TreeHeightReward(), tbl, tbl]) assert sum(calls) == 1 + + +# ---------------------------------------------------------------------------------------------------------------- +# dense exponential against sparse action: one cost model for every caller +# ---------------------------------------------------------------------------------------------------------------- + +_THREE_EPOCHS = {0: 1.0, 0.4: 0.3, 1.2: 2.0} + + +def _one_deme(n, model=None, **kwargs) -> pg.Coalescent: + """One deme with three epochs, on the block-counting state space.""" + Settings.flatten_block_counting = False + return pg.Coalescent(n=n, model=model, demography=pg.Demography(pop_sizes={'pop_0': _THREE_EPOCHS}), **kwargs) + + +def _bin_variance(coal: pg.Coalescent) -> float: + """The second moment of the first SFS bin, by the per-bin accumulation.""" + sfs = coal.sfs + reward = pg.rewards.CombinedReward([sfs.reward, sfs._bins()[0][1]]) + return PhaseTypeDistribution.moment(sfs, k=2, rewards=(reward, reward)) + + +def _dispatch(read, spectra_only: bool = False) -> list: + """The shapes and the outcomes of every dense-against-action decision taken while evaluating ``read``, without + those of the tree heights propagated alongside a spectrum if ``spectra_only``.""" + seen = [] + original = MomentEvaluator._dense_expm_is_faster + + def spy(self, *args, **kwargs): + dense = original(self, *args, **kwargs) + if not (spectra_only and isinstance(self, TreeHeightDistribution)): + seen.append((args[:3], dense)) + return dense + + with patch.object(MomentEvaluator, '_dense_expm_is_faster', spy): + read() + + return seen + + +_BETA = pg.BetaCoalescent(alpha=1.5) + + +@pytest.mark.parametrize('read, dense, spectrum', [ + (lambda: _one_deme(10).tree_height.var, True, False), + (lambda: _bin_variance(_one_deme(15, model=_BETA)), False, True), + (lambda: _one_deme(10, end_time=1.5).tree_height.var, True, False), + (lambda: _bin_variance(_one_deme(15, model=_BETA, end_time=1.5)), False, True), + (lambda: _one_deme(8, model=_BETA).sfs.mean, True, True), + (lambda: _one_deme(15, model=_BETA).sfs.mean, False, True), + (lambda: _one_deme(8, model=_BETA).sfs._mean_occupation_grid(np.linspace(0.1, 3, 30)), True, True), + (lambda: _one_deme(15, model=_BETA).sfs._mean_occupation_grid(np.linspace(0.1, 3, 30)), False, True), +], ids=['closed form 30', 'closed form 528', 'window 30', 'window 528', 'occupation 42', 'occupation 350', + 'time grid 44', 'time grid 352']) +def test_every_caller_takes_the_dense_exponential_on_small_spaces_and_the_action_on_large(read, dense, spectrum): + """The closed-form and windowed moments, the occupation times and the occupation on a time grid each decide + through ``_dense_expm_is_faster``, dense on spaces of a few tens of states and the action on hundreds. The tree + height a spectrum propagates alongside decides on its own space.""" + seen = _dispatch(read, spectra_only=spectrum) + + assert seen and all(outcome is dense for _, outcome in seen) + + +def test_dense_expm_rule_boundaries(): + """Dense exactly where the summed step norm and the fixed costs reach the cost of the dense exponentials, that of a + pass recorded for its gradient scaled up, never from the size at which ``Settings.expm_method = 'auto'`` caps them + on or without steps, and dense without reading a generator when the fixed costs alone exceed it.""" + from phasegen.distributions import _moments + + sfs = _one_deme(10).sfs + ss = sfs.state_space + epochs = sfs._get_epochs_until_unbounded(2) + steps = sfs._closed_form_steps(epochs, 0.0) + d_action, d_dense, count = 9 * ss.k, 3 * ss.k, 4 + + norm = 0.0 + for epoch, tau in steps[:-1]: + ss.update_epoch(epoch) + norm += float(abs(ss.S).sum(axis=0).max()) * tau + ratio = ((norm + 2 * _moments._ACTION_STEP_NORM_OFFSET) * (d_action + _moments._MOMENT_COST.offset) / + (count * 2 * d_dense ** 3)) + + with patch.object(_moments, '_EXPM_COST_RATIO', ratio * (1 + 1e-9)): + assert not sfs._dense_expm_is_faster(d_action, d_dense, count, steps) + assert sfs._dense_expm_is_faster(d_action, d_dense, count, steps, n_dense=1) + with patch.object(_moments, '_EXPM_COST_RATIO', ratio * (1 - 1e-9)): + assert sfs._dense_expm_is_faster(d_action, d_dense, count, steps) + assert not sfs._dense_expm_is_faster(d_action, d_dense, count, steps, taped=True) + with patch.object(_moments, '_EXPM_COST_RATIO', ratio / _moments._TAPED_DENSE_COST * (1 - 1e-9)): + assert sfs._dense_expm_is_faster(d_action, d_dense, count, steps, taped=True) + with patch.object(_moments, '_EXPM_COST_RATIO', ratio * (1 - 1e-9)): + with patch.object(_moments, '_EXPM_ACTION_MIN_DIM', d_dense): + assert not sfs._dense_expm_is_faster(d_action, d_dense, count, steps) + with patch.object(_moments, '_EXPM_ACTION_MIN_DIM', d_dense + 1): + assert sfs._dense_expm_is_faster(d_action, d_dense, count, steps) + assert not sfs._dense_expm_is_faster(d_action, d_dense, count, [(epochs[-1], 0.0)]) + + # the fixed costs alone decide without reading a generator + with patch.object(_moments, '_EXPM_COST_RATIO', 0.0), \ + patch.object(type(ss), 'update_epoch', side_effect=AssertionError('generator read')): + assert sfs._dense_expm_is_faster(d_action, d_dense, count, steps) + + +def test_grid_steps_count_one_action_per_point_and_one_exponential_per_step_length(): + """A propagation from ``start_time`` through an equispaced grid takes one action per grid point and per remainder + to an epoch end, and one dense exponential per epoch and step length.""" + sfs = _one_deme(4).sfs + + # within the first epoch [0, 0.4): four equal steps of 0.05 from the start + steps, n_dense = sfs._grid_steps(0.1, np.array([0.15, 0.2, 0.25, 0.3])) + assert [tau for _, tau in steps] == pytest.approx([0.05] * 4) + assert n_dense == 1 + + # across the boundary at 0.4: a step of 0.3, the remainder of 0.1, then steps of 0.2 and 0.3 in the second epoch + steps, n_dense = sfs._grid_steps(0.0, np.array([0.3, 0.6, 0.9])) + assert [e.start_time for e, _ in steps] == [0, 0, 0.4, 0.4] + assert [tau for _, tau in steps] == pytest.approx([0.3, 0.1, 0.2, 0.3]) + assert n_dense == 4 + + # no end time after the start + assert sfs._grid_steps(0.5, np.array([0.2, 0.5])) == ([], 0) + + +def _transform_dispatch(read) -> list: + """The dimensions and outcomes of every dense-against-action decision of the Laplace transform taken while + evaluating ``read``.""" + from phasegen.distributions import reward + + seen = [] + original = reward._takes_action + + def spy(dim, batch, n_epochs, epochs): + action = original(dim, batch, n_epochs, epochs) + seen.append((dim, batch, action)) + return action + + with patch.object(reward, '_takes_action', spy): + read() + + return seen + + +@pytest.mark.parametrize('read, action', [ + (lambda: _one_deme(5).distribution(pg.TotalBranchLengthReward()).cdf(np.linspace(0.1, 6, 5)), False), + (lambda: _one_deme(20).distribution(pg.UnfoldedSFSReward(1)).cdf(np.array([0.5, 1.0])), True), + (lambda: _one_deme(5).joint(pg.TreeHeightReward(), pg.TotalBranchLengthReward()).lst_taylor(-0.5j), False), + (lambda: _one_deme(14).sfs.joint(1, 2)._lst_taylor_batch(-1j * np.linspace(0.1, 30, 64), 'a', 2), True), + (lambda: _one_deme(4).joint(pg.TreeHeightReward(), pg.TotalBranchLengthReward()).conditional('a', 1.0).mean, + False), +], ids=['transform 5', 'transform 627', 'taylor 15', 'taylor 405', 'jump heights']) +def test_transform_takes_dense_exponentials_on_small_spaces_and_the_action_on_large(read, action): + """The batched transform, its Taylor coefficients and the jump heights of the conditionals decide through the + cost model, with dense Pade exponentials on spaces of a few states and the Taylor action on batches of hundreds, + a single argument such as an atom being left to the dense exponentials there.""" + seen = [outcome for _, batch, outcome in _transform_dispatch(read) if batch > 1 or not action] + + assert seen and all(outcome is action for outcome in seen) + + +def test_transform_rule_boundaries(): + """The transform takes the action exactly where the bound of the cost model for its batch exceeds the summed Taylor + step norm, always from the dimension at which ``Settings.expm_method = 'auto'`` caps the dense exponentials on, and the dense exponentials without reading a norm + where the fixed costs of the actions alone exceed them.""" + from phasegen.distributions import reward, _moments + + dim, batch = 40, 8 + rng = np.random.default_rng(0) + diag = -rng.uniform(1, 3, (batch, dim)) + 0j + off_norm = rng.uniform(0, 2, dim) + epochs = lambda: [[(diag[:5], off_norm), (diag[5:], off_norm)], [(2 * diag, 2 * off_norm)]] + + taylor = reward._TaylorAction(diag, off_norm).norm + reward._TaylorAction(2 * diag, 2 * off_norm).norm + + # the ratio at which the bound equals the norm, by linearity of the bound in the ratio + unit = _moments._TRANSFORM_COST.bound(dim, dim, 1, 2, 2, batch=batch) + with patch.object(_moments, '_EXPM_COST_RATIO', 0.0): + offset = _moments._TRANSFORM_COST.bound(dim, dim, 1, 2, 2, batch=batch) + ratio = _moments._EXPM_COST_RATIO * (taylor - offset) / (unit - offset) + + with patch.object(_moments, '_EXPM_COST_RATIO', ratio * (1 + 1e-9)): + assert reward._takes_action(dim, batch, 2, epochs()) + with patch.object(_moments, '_EXPM_COST_RATIO', ratio * (1 - 1e-9)): + assert not reward._takes_action(dim, batch, 2, epochs()) + assert not reward._takes_action(dim, batch, 0, []) + + def unread(): + raise AssertionError('norm read') + yield + + # the fixed costs of the actions alone exceed the dense exponentials, without reading a norm + with patch.object(_moments, '_EXPM_COST_RATIO', 0.0): + assert not reward._takes_action(dim, batch, 2, unread()) + + with patch.object(_moments, '_EXPM_ACTION_MIN_DIM', dim): + assert reward._takes_action(dim, batch, 2, epochs()) + with patch.object(_moments, '_EXPM_ACTION_MIN_DIM', dim + 1): + assert not reward._takes_action(dim, batch, 2, epochs()) + + +def _flattened(n: int) -> pg.Coalescent: + """One deme with three epochs, on the lineage-counting space.""" + return pg.Coalescent(n=n, demography=pg.Demography(pop_sizes={'pop_0': _THREE_EPOCHS})) + + +_MOMENT_SITES = { + 'closed form': lambda: _one_deme(6).tree_height.var, + 'window': lambda: _one_deme(6, end_time=1.5).tree_height.var, + 'occupation': lambda: _one_deme(6, model=_BETA).sfs.mean, + 'time grid': lambda: _one_deme(6, model=_BETA).sfs.accumulate(1, np.linspace(0.1, 3, 10)), + 'stacked pass': lambda: _one_deme(6, model=_BETA).sfs.cov, + 'flattened levels': lambda: _flattened(8).sfs.cov, + 'tree-height sweep': lambda: _one_deme(6).tree_height.cdf(np.linspace(0, 4, 20)), + 'quantile grid': lambda: _one_deme(6).tree_height.quantile(0.5), + 'gradient': lambda: _one_deme(5).tree_height.gradient(), +} + +_TRANSFORM_SITES = { + 'transform': lambda: _one_deme(5).distribution(pg.TotalBranchLengthReward()).cdf(np.array([0.5, 2.0])), + 'taylor': lambda: _one_deme(5).joint(pg.TreeHeightReward(), pg.TotalBranchLengthReward()).lst_taylor(-0.5j), + 'jump heights': lambda: _one_deme(4).joint(pg.TreeHeightReward(), pg.TotalBranchLengthReward()).conditional( + 'a', 1.0).mean, +} + + +@pytest.mark.parametrize('method', ['dense', 'action']) +@pytest.mark.parametrize('site', list(_MOMENT_SITES) + list(_TRANSFORM_SITES)) +def test_expm_method_forces_its_path_at_every_site(site, method): + """``Settings.expm_method`` forces the dense exponentials or the action at every decision of the moments, the + distribution functions and the Laplace transforms, whatever the cost model would choose.""" + Settings.expm_method = method + + if site in _MOMENT_SITES: + seen = [dense for _, dense in _dispatch(_MOMENT_SITES[site])] + assert seen and all(dense is (method == 'dense') for dense in seen) + else: + seen = [action for _, _, action in _transform_dispatch(_TRANSFORM_SITES[site])] + assert seen and all(action is (method == 'action') for action in seen) + + +@pytest.mark.parametrize('value', ['Dense', 'sparse', 1500, None, True]) +def test_expm_method_rejects_other_values(value): + """Any value of ``Settings.expm_method`` other than ``'auto'``, ``'dense'`` and ``'action'`` raises, leaving the + setting unchanged.""" + with pytest.raises(ValueError, match='expm_method'): + Settings.expm_method = value + + assert Settings.expm_method == 'auto' + + +@pytest.mark.parametrize('d_action, d_dense, count, n_actions, n_dense, batch', [ + (10, 10, 1, 1, 1, 1), (230, 230, 1, 7, 3, 1), (90, 30, 4, 2, 2, 1), (1499, 1499, 3, 40, 1, 1), + (40, 40, 1, 2, 2, 8), (627, 627, 1, 44, 44, 64), (3, 3, 1, 1, 1, 1000), +]) +def test_cost_profiles_reproduce_the_fitted_bounds(d_action, d_dense, count, n_actions, n_dense, batch): + """The moment and transform profiles give exactly the bounds of the fitted rules, with K = 0.17 and gamma = 20, + F = 1 (4 for a taped pass) and d0 = 1e4 for the moments, and F = 0.36 and d0 = 3000 for a transform batch.""" + from phasegen.distributions import _moments + + for taped in (False, True): + expected = (0.17 * (4 if taped else 1) * 1 * count * n_dense * d_dense ** 3 / (1 * d_action + 10000) + - 20 * n_actions) + assert _moments._MOMENT_COST.bound(d_action, d_dense, count, n_actions, n_dense, taped=taped) == expected + + expected = 0.17 * 0.36 * batch * count * n_dense * d_dense ** 3 / (batch * d_action + 3000) - 20 * n_actions + assert _moments._TRANSFORM_COST.bound(d_action, d_dense, count, n_actions, n_dense, batch=batch) == expected + + +# ---------------------------------------------------------------------------------------------------------------- +# the tree-height distribution functions decide by the same cost model +# ---------------------------------------------------------------------------------------------------------------- + +def _two_demes(n: int, sizes=1.0, migration: float = 1.0) -> pg.Coalescent: + """Two demes of ``n`` lineages each, the first of the given sizes.""" + return pg.Coalescent(n={'a': n, 'b': n}, demography=pg.Demography( + pop_sizes={'a': sizes, 'b': 1.0}, migration_rates={('a', 'b'): migration, ('b', 'a'): migration})) + + +def _forced(dense: bool): + """Force every dense-against-action decision to ``dense``.""" + return patch.object(MomentEvaluator, '_dense_expm_is_faster', lambda self, *args, **kwargs: dense) + + +@pytest.mark.parametrize('end, dense', [(1e-3, False), (None, True)], ids=['short horizon', 'to absorption']) +def test_tree_height_sweep_decides_once_by_the_cost_model(end, dense): + """On 230 states, five equispaced times within a short horizon take one interval action, while a hundred up to + the time of almost sure absorption reuse one dense exponential, as one decision for the whole sweep.""" + th = _two_demes(10).tree_height + t = np.linspace(0, th.t_max if end is None else end, 5 if end else 100) + + seen = _dispatch(lambda: th._sweep(t)) + + assert seen == [((230, 230, 1), dense)] + + +def test_tree_height_sweep_values_do_not_depend_on_the_decision(): + """The CDF and density of the sweep agree between the dense exponentials and the action, across epochs and on + an irregular grid with an infinite time.""" + th = _two_demes(3, sizes=_THREE_EPOCHS).tree_height + t = np.concatenate([np.sort(np.random.default_rng(0).uniform(0, th.t_max, 40)), [np.inf]]) + + with _forced(True): + dense = th._sweep(t) + with _forced(False): + action = th._sweep(t) + + np.testing.assert_allclose(action[0], dense[0], rtol=0, atol=1e-13) + np.testing.assert_allclose(action[1], dense[1], rtol=0, atol=1e-13 * dense[1].max()) + + +def test_sweep_steps_count_one_action_per_run_and_one_exponential_per_step_length(): + """A sweep takes one interval action per run of several equal steps and one action per other step and per + remainder to an epoch end, one dense exponential per epoch and step length, and neither for an infinite time.""" + th = _one_deme(4).tree_height + + # [0, 0.4): three steps of 0.05 and the remainder 0.25; [0.4, 1.2): two steps of 0.3 and the remainder 0.2 + plan = th._sweep_plan(np.array([0.05, 0.1, 0.15, 0.7, 1.0, np.inf])) + steps, n_dense = th._sweep_steps(plan) + + assert [e.start_time for e, _ in steps] == [0, 0, 0.4, 0.4] + assert [tau for _, tau in steps] == pytest.approx([0.15, 0.25, 0.6, 0.2]) + assert n_dense == 4 + assert [len(runs) for _, runs, _ in plan] == [1, 1, 1] + + +@pytest.mark.parametrize('read, k, dense', [ + (lambda: pg.Coalescent(n=10).tree_height, 10, True), + (lambda: _two_demes(10).tree_height, 230, True), +], ids=['10 states', '230 states']) +def test_quantile_grid_decides_once_by_the_cost_model(read, k, dense): + """The quantile grid weighs the dense propagators of its expected segment widths, per epoch below ``t_max``, + against an action per expected advance, over twice the span of the grid.""" + th = read() + t_max = th.t_max + seen = [] + original = MomentEvaluator._dense_expm_is_faster + + def spy(self, *args, **kwargs): + seen.append(args) + return original(self, *args, **kwargs) + + with patch.object(MomentEvaluator, '_dense_expm_is_faster', spy): + th.quantile(0.5) + + from phasegen.distributions.phase_type import _ExpmFunction + d_action, d_dense, count, steps, n_dense = seen[-1] + assert (d_action, d_dense, count) == (k, k, 1) + assert len(steps) == _ExpmFunction._expected_advances + assert sum(tau for _, tau in steps) == pytest.approx(2 * t_max) + assert n_dense == _ExpmFunction._expected_widths + assert original(th, *seen[-1]) is dense + + +def test_quantile_grid_values_do_not_depend_on_the_decision(): + """The quantiles read off the grid agree between the dense propagators and the action to the tolerance of the + grid.""" + q = np.array([0.01, 0.5, 0.99]) + with _forced(True): + dense = _two_demes(3, sizes=_THREE_EPOCHS).tree_height.quantile(q) + with _forced(False): + action = _two_demes(3, sizes=_THREE_EPOCHS).tree_height.quantile(q) + + np.testing.assert_allclose(action, dense, rtol=1e-8) diff --git a/testing/test_mutation_configs.py b/testing/test_mutation_configs.py index f8e10dd7..86ec6ca2 100644 --- a/testing/test_mutation_configs.py +++ b/testing/test_mutation_configs.py @@ -12,6 +12,7 @@ import pytest import phasegen as pg +from phasegen.distributions import _uniformization from phasegen.distributions.empirical import MsprimeCoalescent #: Migration rates of the two-deme scenarios. @@ -549,8 +550,8 @@ def test_single_epoch_mutation_config_builds_one_state_space(monkeypatch): absorption check built the lineage-counting space of the tree height for its initial vector, which the epoch search reads only for a demography with a finite epoch, adding about 0.3 ms to every fresh coalescent. """ - build, built = pg.StateSpace._construct_numba, [] - monkeypatch.setattr(pg.StateSpace, '_construct_numba', lambda ss: built.append(type(ss)) or build(ss)) + build, built = pg.StateSpace._enumerate, [] + monkeypatch.setattr(pg.StateSpace, '_enumerate', lambda ss: built.append(type(ss)) or build(ss)) pg.Coalescent(n=5).sfs.get_mutation_config((1, 1, 0, 0), theta=1) @@ -580,10 +581,10 @@ def test_multi_epoch_expm_action_matches_dense_exponential(sparse, monkeypatch): monkeypatch.setattr(pg.Settings, 'closed_form_sparse_min_states', 1 if sparse else 10 ** 9) configs = ((0, 0, 0), (1, 0, 0), (2, 1, 0), (0, 1, 2)) - monkeypatch.setattr(pg.Settings, 'expm_action_min_dim', 10 ** 9) + monkeypatch.setattr(pg.Settings, 'expm_method', 'dense') dense = [pg.Coalescent(n=4, demography=ONE_DEME[1]).sfs.get_mutation_config(c, 1.3) for c in configs] - monkeypatch.setattr(pg.Settings, 'expm_action_min_dim', 1) + monkeypatch.setattr(pg.Settings, 'expm_method', 'action') action = [pg.Coalescent(n=4, demography=ONE_DEME[1]).sfs.get_mutation_config(c, 1.3) for c in configs] np.testing.assert_allclose(action, dense, rtol=1e-12) @@ -837,3 +838,74 @@ def counted(*args, **kwargs): p_uncached, n_uncached = probabilities(make()) assert n_uncached > 1 np.testing.assert_allclose(p, p_uncached, rtol=1e-12) + + +@pytest.mark.parametrize('layout, sizes, config, reference', [ + ('fsfs', {0: 0.03, 0.1: 37.0, 1.1: 3.0, 1.2: 0.3}, [15, 14], 5.758978235722657e-42), + ('sfs', {0: 0.03, 0.1: 37.0, 1.1: 3.0}, [8, 6, 3], 2.842654944150204e-15), +]) +def test_multi_epoch_small_probabilities_keep_their_relative_accuracy(layout, sizes, config, reference): + """A configuration probability far below the double-precision resolution of the total keeps its relative accuracy + over several epochs, against a 90-digit evaluation of the same lattice. Reading the occupation of a finite epoch + off the difference of the propagated vectors through a solve cancelled to 1e-11 relative on the unfolded case and + returned -1.5e-26 on the folded one, whether the exponential was dense or a sparse action.""" + coal = pg.Coalescent(n=4, demography=pg.Demography(pop_sizes={'pop_0': sizes})) + + p = getattr(coal, layout).get_mutation_config(config, theta=0.1) + + assert p == pytest.approx(reference, rel=1e-12) + + +def test_absorption_rates_carry_no_cancellation(): + """The probability of no mutation at a high mutation rate over two epochs matches a 90-digit evaluation of the + same lattice. Taking the absorption rates as minus the row sums of the transient rate matrix left a rounding + residue of about 1e-16 of the rates on states that never absorb, which put it 69% low.""" + coal = pg.Coalescent(n=8, demography=pg.Demography(pop_sizes={'pop_0': {0: 92.0, 1.9: 0.024}})) + + p = coal.sfs.get_mutation_config([0] * 7, theta=20.0) + + assert p == pytest.approx(5.472599088389316e-22, rel=1e-11) + + +def test_drained_deme_of_a_split_leaves_mutation_configs_fast_and_unchanged(): + """A derived deme shrunk after a split leaves the configuration probability unchanged, since its lineages left at + the split. Regression: the uniformization rate of every later epoch was the drain rate of the derived deme, a + hundred times its coalescence rate, which under the Dirac timescale reached 1e6 at a size of 0.01, so that states + holding below 1e-20 of the mass took the step in about 46000 chunks, 29 s in place of 0.07 s, and moved the probabilities + by 7e-12 and 1.6e-11 relative through the drift of the chunks.""" + + def p(size: float) -> list: + demography = pg.Demography(pop_sizes={'pop_0': {0: 1, 5: 1.5}, 'pop_1': {0: 1, 0.5: size}}, + events=[pg.PopulationSplit(time=0.3, derived='pop_1', ancestral='pop_0')]) + coal = pg.Coalescent(n={'pop_0': 2, 'pop_1': 2}, demography=demography, + model=pg.DiracCoalescent(psi=0.5, c=1)) + return [coal.sfs.get_mutation_config(config, theta=1.0) for config in ([1, 1, 1], [0, 0, 3])] + + np.testing.assert_allclose(p(0.01), p(1), rtol=1e-12) + + +def test_founder_bottleneck_across_a_split_takes_few_uniformization_chunks(monkeypatch): + """A Dirac founder bottleneck of the derived deme across a split, under migration, keeps the configuration + probabilities of v2.2.0 in fewer than a thousand uniformization chunks. Regression: the split leaves a residue of + 1e-9 in the derived deme, whose states drain a hundred times faster than the fastest coalescence. Taking every + later step at that drain rate over the states reachable from the residue took about 7e4 chunks for these + probabilities, 16 s in place of 0.06 s, and moved them by 9e-11 relative through the drift of the chunks.""" + demography = pg.Demography(pop_sizes={'pop_0': {0: 1.0, 3.0: 2.0}, 'pop_1': {0: 1.0, 0.8: 0.01}}, + migration_rates={('pop_0', 'pop_1'): 0.5, ('pop_1', 'pop_0'): 0.5}, + events=[pg.PopulationSplit(time=1.0, derived='pop_1', ancestral='pop_0')]) + coal = pg.Coalescent(n={'pop_0': 2, 'pop_1': 2}, model=pg.DiracCoalescent(psi=0.3, c=1.0), demography=demography) + + calls = [] + series = _uniformization._series + + def counting(*args): + calls.append(1) + return series(*args) + + monkeypatch.setattr(_uniformization, '_series', counting) + p = [coal.sfs.get_mutation_config(c, theta=1.0) for c in ([1, 0, 0], [0, 0, 1], [1, 1, 1], [2, 1, 0])] + + # v2.2.0 + np.testing.assert_allclose(p, [0.053658726258410464, 0.0062329153619128195, 0.004436058492367974, + 0.03534297033441059], rtol=1e-10) + assert len(calls) < 1000 diff --git a/testing/test_phase_type.py b/testing/test_phase_type.py index 6891aa78..63072e22 100644 --- a/testing/test_phase_type.py +++ b/testing/test_phase_type.py @@ -152,17 +152,17 @@ def test_tree_height_quantile_grid_terminates_when_the_ancestor_migrates(coal): def test_tree_height_quantile_boundary_levels(): """ - Levels 0 and 1 return the ends of the support, NaN levels return NaN, and the shape of the levels is kept. + Levels 0 and 1 return the ends of the support, and the shape of the levels is kept. """ th = pg.Coalescent(n=5, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.5: 0.2}})).tree_height - q = np.array([[0.0, 0.5], [np.nan, 1.0]]) + q = np.array([[0.0, 0.5], [0.25, 1.0]]) out = th.quantile(q) assert out.shape == (2, 2) assert out[0, 0] == 0 assert out[1, 1] == th.t_max - assert np.isnan(out[1, 0]) + assert th.quantile(0.25) == out[1, 0] assert th.quantile(0.5) == out[0, 1] @@ -231,3 +231,96 @@ def test_tree_height_pdf_lower_tail_relative_accuracy(): expected = [1.4799206499923377e-11, 2.6296870454997604e-09, 8.042806633234013e-05, 0.16113377457891845] np.testing.assert_allclose(coal.tree_height.pdf(t), expected, rtol=1e-12, atol=0) + + +def _pointwise_sweep(th: TreeHeightDistribution, t: np.ndarray) -> tuple: + """The CDF and density at each time from a sweep over that time alone.""" + return tuple(np.array(x) for x in zip(*[[v[0] for v in th._sweep(np.array([u]))] for u in t])) + + +def test_sweep_reuses_one_exponential_per_step(): + """ + A sweep over an equally spaced grid forms one dense exponential per epoch and step length, not one per point, and + gives the values of sweeps over each point alone. ``np.linspace`` steps differ in their last bits, which the runs + of equal steps absorb. + """ + from phasegen.distributions import phase_type + + th = pg.Coalescent(n=6, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.5: 0.2, 1.5: 2}})).tree_height + t = np.linspace(0, 4, 400) + _ = th.t_max + + with patch.object(phase_type, 'expm', side_effect=phase_type.expm) as spy: + cdf, pdf = th._sweep(t) + + # three epochs, each with a first step from its start, the run of grid steps and, but for the last, its end + assert spy.call_count <= 8 + + cdf_ref, pdf_ref = _pointwise_sweep(th, t) + np.testing.assert_allclose(cdf, cdf_ref, rtol=1e-13, atol=1e-15) + np.testing.assert_allclose(pdf, pdf_ref, rtol=1e-13, atol=1e-15) + + +@pytest.mark.parametrize('action', [False, True]) +def test_sweep_over_unequal_grid_crossing_epochs(action): + """ + A sweep over unequally spaced times, some of them on epoch boundaries, repeated and beyond the last boundary, + agrees with sweeps over each time alone, on the dense path and on the sparse path, where equal steps take one + interval action. + """ + from phasegen.settings import Settings + + Settings.expm_method = 'action' if action else 'dense' + th = pg.Coalescent(n=5, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.5: 0.2, 1.5: 2}})).tree_height + + rng = np.random.default_rng(0) + t = np.sort(np.concatenate([rng.uniform(0, 5, 30), [0, 0.5, 0.5, 1.5], np.linspace(0.6, 1.4, 20)])) + cdf, pdf = th._sweep(t) + cdf_ref, pdf_ref = _pointwise_sweep(th, t) + + np.testing.assert_allclose(cdf, cdf_ref, rtol=1e-11, atol=1e-15) + np.testing.assert_allclose(pdf, pdf_ref, rtol=1e-11, atol=1e-15) + + +def test_step_runs_split_equal_steps(): + """ + Runs of equal steps continue only within a few unit roundoffs of the time reached, and times at or before it + take a zero step. + """ + from phasegen.distributions._grid import _StepRuns + + runs, end = _StepRuns.split(0.5, np.linspace(0.5, 2.5, 5)[1:]) + assert runs == [(0.5, 4)] and abs(end - 2.5) < 1e-15 + + runs, end = _StepRuns.split(0.0, np.array([0.0, 1.0, 2.0, 2.0, 3.5, 5.0, np.inf, np.inf])) + assert runs == [(0.0, 1), (1.0, 2), (0.0, 1), (1.5, 2), (np.inf, 1), (0.0, 1)] and end == np.inf + + runs, _ = _StepRuns.split(0.0, np.array([1.0, 2.0 + 1e-14])) + assert len(runs) == 2 + + +@pytest.mark.parametrize('action', [False, True]) +def test_sweep_over_a_grid_longer_than_one_run(action): + """ + A run of equal steps longer than ``_MAX_RUN_STEPS`` is cut into runs of at most that many steps, which bounds the + vectors a sweep holds at once, and the sweep over the cut runs agrees with sweeps over single times, including + those at the cuts. Uncut, an equispaced grid of 10^5 points on 1329 states held about 1 GB. + """ + from phasegen.distributions._grid import _MAX_RUN_STEPS, _StepRuns + from phasegen.settings import Settings + + t = np.linspace(0, 6, 3 * _MAX_RUN_STEPS + 6) + runs, end = _StepRuns.split(0.0, t) + + assert [c for _, c in runs] == [1, _MAX_RUN_STEPS, _MAX_RUN_STEPS, _MAX_RUN_STEPS, 5] and abs(end - 6) < 1e-14 + + Settings.expm_method = 'action' if action else 'dense' + th = pg.Coalescent(n=5, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 2: 0.3}})).tree_height + cdf, pdf = th._sweep(t) + + idx = np.array([1, 2, _MAX_RUN_STEPS, _MAX_RUN_STEPS + 1, 2 * _MAX_RUN_STEPS + 1, 3 * _MAX_RUN_STEPS + 2, + len(t) - 1]) + cdf_ref, pdf_ref = _pointwise_sweep(th, t[idx]) + + np.testing.assert_allclose(cdf[idx], cdf_ref, rtol=1e-11, atol=1e-15) + np.testing.assert_allclose(pdf[idx], pdf_ref, rtol=1e-11, atol=1e-15) diff --git a/testing/test_published_examples.py b/testing/test_published_examples.py new file mode 100644 index 00000000..00af03a8 --- /dev/null +++ b/testing/test_published_examples.py @@ -0,0 +1,277 @@ +""" +Smoke tests replaying the code published in the PhaseGen manuscript. + +Each test reruns a code listing shown in a figure of the manuscript, together with the calls of the script its +caption cites (``scripts/plot_manuscript_*.py``, ``scripts/infer_mmc_kingman_2sfs.py``), or the computation of an +appendix example, with smaller samples and fewer runs, bootstraps and grid points. The tests check that the code runs, +not the values it returns. +""" +import matplotlib.pyplot as plt +import numpy as np +import pytest + +import phasegen as pg + + +def _plot_overview(coal: pg.Coalescent): + """ + The tree height density, expected SFS and SFS correlations, as plotted in the panels of the example figures. + """ + _, axs = plt.subplots(2, 2) + + coal.tree_height.pdf.plot(ax=axs[0, 1], show=False) + coal.sfs.mean.plot(ax=axs[1, 0], show=False, title='Expected SFS') + coal.sfs.corr.plot(ax=axs[1, 1], show=False, title='SFS correlations', max_abs=1) + + +def test_kingman_example(): + """ + Figure 1: tree height density, expected SFS and SFS correlations under the Kingman coalescent. + """ + # 8 lineages, pop size of 1 + coal = pg.Coalescent(n=8) + + # tree height PDF, SFS and 2-SFS + pdf = coal.tree_height.pdf + sfs = coal.sfs.mean + sfs2 = coal.sfs.corr + + _plot_overview(coal) + + +def test_two_epoch_example(): + """ + Figure 2: a bottleneck at time 1. + """ + # bottleneck at time 1 + coal = pg.Coalescent( + n={'pop0': 8}, + demography=pg.Demography( + pop_sizes={ + 'pop0': {0: 1, 1: .2} + } + ) + ) + + _plot_overview(coal) + + +def test_migration_example(): + """ + Figure 3: two demes with migration, and the SFS of each deme. + """ + # migration from pop0 to pop1 back in time + coal = pg.Coalescent( + n={'pop0': 4, 'pop1': 4}, + demography=pg.Demography( + pop_sizes={'pop0': 1, 'pop1': 2}, + migration_rates={ + ('pop0', 'pop1'): 0.3 + } + ) + ) + + _plot_overview(coal) + + pg.Spectra(dict(total=coal.sfs.mean, pop0=coal.sfs.demes['pop0'].mean, pop1=coal.sfs.demes['pop1'].mean)).plot( + show=False, title='Expected SFS' + ) + + +def test_mmc_example(): + """ + Figure 4: the Beta coalescent. + """ + # beta coalescent, pop size of 1 + coal = pg.Coalescent( + n=8, # 8 lineages + model=pg.BetaCoalescent(1.4) + ) + + _plot_overview(coal) + + +def test_recombination_example(): + """ + Figure 5: covariance and correlation of the tree heights of two loci, and the tree height density. + """ + + def get_cov(r, N1): + return pg.Coalescent( + n={'pop0': 2}, + loci=pg.LocusConfig( + n=2, recombination_rate=r / 2 + ), + demography=pg.Demography( + pop_sizes={'pop0': {0: 1, 1: N1}} + ) + ).tree_height.loci.cov[0, 1] + + def get_coal(r, N1): + return pg.Coalescent( + n={'pop0': 2}, + loci=pg.LocusConfig(n=2, recombination_rate=r / 2), + demography=pg.Demography(pop_sizes={'pop0': {0: 1, 1: N1}}) + ) + + for N1 in [0.1, 10]: + get_coal(10, N1).tree_height.pdf(np.linspace(0, 3, 20)) + + for r in [0.1, 10]: + get_cov(r, N1) + get_coal(r, N1).tree_height.loci.corr[0, 1] + + +def test_inference_example(): + """ + Figure 6 and the inference result of Figure 7: a 2-epoch inference with bootstraps, and its plots. + """ + inf = pg.Inference( + coal=lambda t, Ne: pg.Coalescent( + n=10, + demography=pg.Demography( + pop_sizes={'pop_0': {0: 1, t: Ne}} + ) + ), + observation=pg.SFS( + [177130, 997, 441, 228, 156, 117, 114, 83, 105, 109, 652] + ), + loss=lambda coal, obs: pg.PoissonLikelihood().compute( + observed=obs.polymorphic, + modelled=( + coal.sfs.mean.polymorphic / coal.sfs.mean.Theta * obs.Theta + ) + ), + bounds=dict(t=(0, 4), Ne=(0.1, 10)), + resample=lambda sfs, _: sfs.resample(), + do_bootstrap=True, + parallelize=False, + n_runs=1, + n_bootstraps=2, + pbar=False + ) + + inf.run() + + spectra = pg.Spectra.from_spectra(dict( + fitted=inf.dist_inferred.sfs.mean / + (inf.dist_inferred.sfs.mean.theta * inf.dist_inferred.sfs.mean.n_sites) * + (inf.observation.theta * inf.observation.n_sites), + observed=inf.observation + )) + + _, axs = plt.subplots(2, 2) + + spectra.plot(ax=axs[0, 0], show=False, title='SFS comparison') + inf.plot_pop_sizes(ax=axs[0, 1], show=False) + inf.plot_bootstraps(ax=axs[1], show=False, kwargs={'bins': 30}, title=['Marginal distribution'] * 2) + + +def test_sfs_correlation_inference_example(): + """ + Figure 8: inference of a Beta coalescent from the SFS and the correlation of two of its bins. + """ + + def get_corr(coal: pg.Coalescent) -> float: + return coal.sfs.get_corr(4, 5) + + dist_inferred = pg.Coalescent(n=6, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.5: 0.3}})) + sfs = dist_inferred.sfs.mean + tree_height = dist_inferred.tree_height.mean + m2 = get_corr(dist_inferred) + + def loss(coal: pg.Coalescent, obs: (pg.SFS, float)) -> float: + sfs, m2 = obs + + loss_sfs = pg.MultinomialLikelihood().compute( + observed=sfs.normalize().polymorphic, + modelled=coal.sfs.mean.normalize().polymorphic + ) + + loss_m2 = np.abs( + m2 - get_corr(coal) + ) + + return loss_sfs + loss_m2 + + inf_m12 = pg.Inference( + coal=lambda t, Ne, alpha: pg.Coalescent( + n=6, + demography=pg.Demography( + pop_sizes={'pop_0': {0: 1, t: Ne}} + ), + model=pg.BetaCoalescent(alpha=alpha, scale_time=False) + ), + observation=(sfs, m2), + loss=loss, + bounds=dict(t=(0, tree_height), Ne=(0.01, 10), alpha=(1.00001, 1.99999)), + resample=lambda obs, _: (obs[0].resample(), obs[1]), + do_bootstrap=True, + n_bootstraps=2, + n_runs=1, + parallelize=False, + pbar=False + ) + + inf_m12.run() + + +def test_complex_example(caplog): + """ + Figures S5 to S7: a two-deme Beta coalescent with a bottleneck and changing migration, its plots and statistics. + """ + coal = pg.Coalescent( + n=pg.LineageConfig({'pop0': 3, 'pop1': 5}), + model=pg.BetaCoalescent(alpha=1.7), + demography=pg.Demography( + pop_sizes={ + 'pop0': {0: 1.0}, + 'pop1': {0: 1.2, 5: 0.1, 5.5: 0.8} + }, + migration_rates={ + ('pop0', 'pop1'): {0: 0.2, 8: 0.3}, + ('pop1', 'pop0'): {0: 0.5} + } + ) + ) + + _, axs = plt.subplots(2, 2, figsize=(6, 5)) + t = np.linspace(0, coal.tree_height.quantile(0.99), 100) + + coal.demography.plot(ax=axs[0, 0], show=False, t=t) + axs[0, 0].legend(prop={'size': 6}, loc='center left') + coal.tree_height.plot_pdf(ax=axs[0, 1], show=False) + assert any('plot_pdf() is deprecated' in r.getMessage() for r in caplog.records) + coal.sfs.mean.plot(ax=axs[1, 0], show=False, title='SFS') + coal.sfs.corr.plot(ax=axs[1, 1], show=False, title='2-SFS') + + plt.tight_layout() + + coal.tree_height.mean + coal.total_branch_length.var + coal.tree_height.cdf(t) + coal.sfs.cov + coal.sfs.demes['pop0'].mean + coal.moment(3, (pg.TotalBranchLengthReward(),) * 3) + + +def test_computation_examples(): + """ + Appendix figures S1 to S4: the SFS moments of the one-epoch and two-epoch computation examples. + """ + coal = pg.Coalescent(n=3, end_time=3) + + coal.moment(k=1, rewards=[pg.UnfoldedSFSReward(1)]) + coal.tree_height.mean + + coal = pg.Coalescent(n=3, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 2: 0.5}})) + rewards = [pg.UnfoldedSFSReward(1), pg.UnfoldedSFSReward(2)] + + m12 = coal.moment(k=2, rewards=rewards, center=False, permute=False) + m21 = coal.moment(k=2, rewards=rewards[::-1], center=False, permute=False) + m1 = coal.moment(k=1, rewards=rewards[:1], center=False, permute=False) + m2 = coal.moment(k=1, rewards=rewards[1:], center=False, permute=False) + + np.testing.assert_allclose((m12 + m21) / 2 - m1 * m2, coal.moment(k=2, rewards=rewards), rtol=1e-12) + + coal.accumulate(k=2, rewards=rewards, end_times=np.linspace(0.01, 100, 20)) diff --git a/testing/test_reward_distribution.py b/testing/test_reward_distribution.py index 8941ee9e..a6c0e1aa 100644 --- a/testing/test_reward_distribution.py +++ b/testing/test_reward_distribution.py @@ -12,6 +12,7 @@ import pytest import scipy.linalg as sla import scipy.sparse as sp +from scipy.integrate import trapezoid import phasegen as pg from phasegen.settings import Settings @@ -356,7 +357,7 @@ def test_two_locus_sfs_has_no_univariate_distribution(): """A 2-SFS entry is a cross-moment (product of two rewards), so CDF/PDF/quantile/plots must raise clearly. Regression: ``sfs2.cdf.plot()`` raised AttributeError.""" sfs2 = pg.Coalescent(n=4, loci=2, recombination_rate=1.0).sfs2 - for method in ('cdf', 'pdf', 'quantile', 'plot_cdf'): + for method in ('cdf', 'pdf', 'quantile', 'plot_cdf', 'plot_pdf'): with pytest.raises(NotImplementedError): getattr(sfs2, method)(1.0) @@ -653,7 +654,7 @@ def test_conditional_distribution(): # a real nested inversion, so keep the grid small) xs = np.linspace(0.3, ma._range(scale=4), 6) cond_means = [jd.conditional('a', float(x))._cumulants()[0] for x in xs] - e_recon = np.trapezoid(np.array(cond_means) * ma.pdf(xs), xs) + e_recon = trapezoid(np.array(cond_means) * ma.pdf(xs), xs) assert e_recon == pytest.approx(mb._cumulants()[0], rel=0.15) # a self-pair conditional is a point mass at ``value`` -> not representable, raises @@ -972,9 +973,9 @@ def test_plot_endpoint_tracks_quantile_setting(): Settings.plot_endpoint_quantile = prev -def test_distribution_functions_are_callable_and_plottable(): +def test_distribution_functions_are_callable_and_plottable(caplog): """``pdf``/``cdf``/``quantile`` are :class:`DistributionFunction`s: calling them evaluates (unchanged), and they - expose ``.plot()``. The former ``plot_cdf`` still works but warns (deprecated).""" + expose ``.plot()``. The former ``plot_cdf`` and ``plot_pdf`` still work but warn (deprecated).""" import matplotlib matplotlib.use('Agg') from phasegen.distributions.base import DistributionFunction @@ -1003,13 +1004,15 @@ def test_distribution_functions_are_callable_and_plottable(): pg.Coalescent(n=4, loci=2, recombination_rate=1.0).sfs2.cdf(1.0) # deprecated aliases still work but warn - with pytest.warns(DeprecationWarning): - coal.sfs.plot_cdf(show=False) - with pytest.warns(DeprecationWarning): - jd.plot_cdf(show=False, n_points=12) + caplog.clear() + coal.sfs.plot_cdf(show=False) + coal.tree_height.plot_pdf(show=False) + jd.plot_cdf(show=False, n_points=12) + assert [r.getMessage().split('(')[0] for r in caplog.records if 'is deprecated' in r.getMessage()] == \ + ['plot_cdf', 'plot_pdf', 'plot_cdf'] -def test_deprecated_plot_cdf_accepts_the_1_2_0_arguments(tmp_path): +def test_deprecated_plot_cdf_accepts_the_1_2_0_arguments(tmp_path, caplog): """``plot_cdf`` takes the keyword arguments of version 1.2.0, ``ax``, ``t``, ``show``, ``file``, ``clear``, ``label`` and ``title``, and passes them to ``cdf.plot()``.""" import matplotlib @@ -1019,14 +1022,14 @@ def test_deprecated_plot_cdf_accepts_the_1_2_0_arguments(tmp_path): ax = plt.figure().gca() file = tmp_path / 'cdf.png' - with pytest.warns(DeprecationWarning): - out = pg.Coalescent(n=4).tree_height.plot_cdf(ax=ax, t=np.linspace(0, 3, 20), show=False, file=str(file), - clear=False, label='th', title='T') + out = pg.Coalescent(n=4).tree_height.plot_cdf(ax=ax, t=np.linspace(0, 3, 20), show=False, file=str(file), + clear=False, label='th', title='T') + + assert any('plot_cdf() is deprecated' in r.getMessage() for r in caplog.records) assert out is ax and ax.get_title() == 'T' and file.exists() np.testing.assert_allclose(ax.lines[-1].get_xdata(), np.linspace(0, 3, 20)) assert ax.lines[-1].get_label() == 'th' - assert not hasattr(pg.Coalescent(n=4).tree_height, 'plot_pdf') plt.close('all') @@ -2305,7 +2308,7 @@ def test_joint_near_origin_check_probes_the_continuous_part(caplog): with caplog.at_level('WARNING'): assert joint._cos2d_wiggle_check < 0.01 - assert not [r for r in caplog.records if 'under-resolves near the origin' in r.getMessage()] + assert not [r for r in caplog.records if 'joint inversion under-resolves' in r.getMessage()] def test_joint_cosine_expansion_follows_the_term_count(): @@ -2678,21 +2681,21 @@ def test_bottleneck_conditional_matches_a_high_truncation_reference(): assert np.abs(np.asarray(cdf(xs[body])) - ref[body]).max() < 2e-3 -def test_quantile_passes_nan_through(): - """A NaN level gives a NaN quantile, leaves the other levels unchanged and builds no de Hoog nodes beyond those - the finite levels need. Regression: a NaN level marched the node ladder to its cap.""" - d = pg.Coalescent(n=4).total_branch_length.distribution() - - out = d.quantile([0.5, np.nan]) +def test_quantile_rejects_nan_levels(): + """The quantiles of a tree height, of an accumulated reward and of a conditional on a line with an atom raise the + documented ValueError for a NaN level, alone or in an array, while their CDFs map NaN to NaN. Regression: the range + check ``(q < 0) | (q > 1)`` is False for NaN, so a NaN level passed it.""" + coal = pg.Coalescent(n=3, model=pg.BetaCoalescent(alpha=1.5)) + joint = coal.joint(pg.rewards.TreeHeightReward(), pg.rewards.TotalBranchLengthReward()) + line = joint.conditional('b', float(joint.marginal('b').quantile(0.5))) + assert line._atom_values.size - assert np.isnan(out[1]) and np.isnan(d.quantile(np.nan)) - assert out[0] == pytest.approx(d.quantile(0.5)) - assert len(d.__dict__['_lst_curve_cache']['cdf_exact']) == 1 + for dist in (coal.tree_height, coal.sfs.bin(1), line): + for q in (np.nan, [0.5, np.nan]): + with pytest.raises(ValueError, match='between 0 and 1'): + dist.quantile(q) - q1 = d.quantile(0.99) - d.quantile([0.99, np.nan]) - assert len(d.__dict__['_lst_curve_cache']['cdf_exact']) < d.quantile._max_exact_nodes - assert d.quantile(0.99) == pytest.approx(q1, rel=1e-8) + assert np.isnan(dist.cdf(np.nan)) def test_joint_axis_terms_follow_live_cos_terms(): @@ -3198,3 +3201,75 @@ def test_multi_epoch_transform_grid_in_row_blocks_matches_one_block(monkeypatch) monkeypatch.setattr(reward, '_LST_VECTOR_ENTRIES', 1) np.testing.assert_allclose(joint._lst_grid(s_a, s_b), whole, rtol=1e-13, atol=0) + + +def test_joint_margin_check_warns_on_an_under_resolved_bottleneck(caplog): + """The margin check of the joint cosine expansion compares both margins with the marginal CDFs over the bulk of + each marginal and names ``Settings.cos_terms_2d`` as the remedy. Through a strong bottleneck, 128 cosine terms give + the margin ``F(x, inf)`` 0.730 at the 0.8 quantile of the tree height, against the exact 0.800, and the joint CDF + at the pair of 0.8 quantiles 0.676 against 0.740 from msprime. Regression: the check compared only the margin of + ``R_a``, at four points up to its 0.4 quantile, found a gap of 0.0115 and logged nothing. A constant population + size stays silent.""" + def warnings(): + return [r.getMessage() for r in caplog.records if 'joint inversion under-resolves' in r.getMessage()] + + bottleneck = pg.Coalescent(n=10, demography=pg.Demography( + pop_sizes={'pop_0': {0: 1, 0.3: 0.02, 0.35: 1.5, 2: 0.5}})) + + with caplog.at_level('WARNING'): + err = bottleneck.joint(pg.TreeHeightReward(), pg.TotalBranchLengthReward())._cos2d_wiggle_check + + assert err > 0.03 + assert len(warnings()) == 1 and 'Settings.cos_terms_2d' in warnings()[0] + + caplog.clear() + with caplog.at_level('WARNING'): + err = pg.Coalescent(n=10).joint(pg.TreeHeightReward(), pg.TotalBranchLengthReward())._cos2d_wiggle_check + + assert err < 0.03 + assert not warnings() + + + +def test_joint_margin_check_warns_on_a_steep_rise_above_an_atom(caplog): + """The margin check of the joint cosine expansion also probes the continuous part just above an atom at 0. For + bins 5 and 1 of the SFS at n = 10 through a short, strong bottleneck, the atom of bin 5 is 0.44 and its continuous + part rises within a small fraction of ``mean + 3 std``, where the joint margin at 128 cosine terms lies 0.066 below + the marginal CDF. Regression: the check probed only quadratically spaced points up to ``mean + 3 std``, whose + first lay past the rise, found 0.028 and logged nothing.""" + coal = pg.Coalescent(n=10, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.1: 0.01, 0.15: 1}})) + + with caplog.at_level('WARNING'): + err = coal.sfs.joint(5, 1)._cos2d_wiggle_check + + assert err > 0.05 + assert [r for r in caplog.records if 'joint inversion under-resolves' in r.getMessage()] + + +def test_joint_margin_check_warns_on_a_narrow_body(caplog): + """The margin check of the joint cosine expansion probes the body of a marginal that holds its mass in a narrow + interval away from the origin. Through a short bottleneck to size 0.02 at n = 5, the tree height lies mostly + within [0.2, 0.25], where the joint margin at 128 cosine terms deviates from the marginal CDF by 0.11. + Regression: the check probed quadratically spaced points of which one fell in the body, found 0.012 and logged + nothing.""" + coal = pg.Coalescent(n=5, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.2: 0.02, 0.25: 1}})) + + with caplog.at_level('WARNING'): + err = coal.joint(pg.TreeHeightReward(), pg.TotalBranchLengthReward())._cos2d_wiggle_check + + assert err > 0.05 + assert [r for r in caplog.records if 'joint inversion under-resolves' in r.getMessage()] + + +def test_reward_distribution_moments_match_the_phase_type_moments(): + """RewardDistribution.moment() and its m2, m3 and m4 equal the moments of the phase-type distribution of the same + reward, as on its siblings. Regression: RewardDistribution provided only the mean and variance.""" + coal = pg.Coalescent(n=5, demography=pg.Demography(pop_sizes={'pop_0': {0: 1, 0.5: 0.3}})) + dist, tbl = coal.total_branch_length.distribution(), coal.total_branch_length + + assert dist.moment(3) == pytest.approx(tbl.moment(3), rel=1e-12) + assert dist.moment(2) == pytest.approx(dist.var, rel=1e-12) + for m in ('m2', 'm3', 'm4'): + assert getattr(dist, m) == pytest.approx(getattr(tbl, m), rel=1e-12) + + assert coal.sfs.bin(1).moment(2, center=False) == pytest.approx(coal.sfs.m2.data[1], rel=1e-12) diff --git a/testing/test_sampling.py b/testing/test_sampling.py index fd731b8c..68b5d072 100644 --- a/testing/test_sampling.py +++ b/testing/test_sampling.py @@ -4,6 +4,8 @@ the exact analytic statistics (up to Monte-Carlo error), the self-consistency that the scenario suite exercises end-to-end via the nested ``tolerance.empirical`` blocks in ``test_scenarios.py`` configs. """ +from fractions import Fraction + import numpy as np import pytest @@ -631,3 +633,81 @@ def test_mutation_binning_matches_a_walk_over_the_mutations(): assert mts.num_trees > 1 and expected.sum() > 10 np.testing.assert_array_equal(stats.mutations, expected) + + +@pytest.mark.parametrize('n_samples', [3.5, -1, -2.0, np.nan, np.inf, '3', True]) +def test_sample_rejects_a_count_that_is_not_a_non_negative_integer(n_samples): + """Every public sampling method raises a ValueError for a count that is not a non-negative integer. Regression: + the count was passed to NumPy, which raised a TypeError for a float and 'negative dimensions' for -1.""" + dem = pg.Demography(pop_sizes={'p0': 1, 'p1': 1}, migration_rates={('p0', 'p1'): 1, ('p1', 'p0'): 1}) + two_locus = pg.Coalescent(n=3, loci=2, recombination_rate=1.0).sfs2 + + for sample in (pg.Coalescent(n=3).tree_height.sample, pg.Coalescent(n=3).sfs.sample, + pg.Coalescent(n={'p0': 2, 'p1': 1}, demography=dem).jsfs.sample, two_locus.sample, + two_locus.sample_per_locus): + with pytest.raises(ValueError, match='number of samples must be a non-negative integer'): + sample(n_samples, seed=SEED) + + +def test_sample_accepts_an_integral_float_count(): + """An integral float count draws that many samples, as the integer count does with the same seed. Regression: + NumPy rejected the float as a shape.""" + dist = pg.Coalescent(n=3).tree_height + + np.testing.assert_array_equal(dist.sample(3.0, seed=SEED), dist.sample(3, seed=SEED)) + assert pg.Coalescent(n=3).sfs.sample(np.float64(2), seed=SEED).shape == (2, 4) + + +@pytest.mark.parametrize('n_samples', [np.array(2), np.int64(2), 2.0, np.float32(2), Fraction(2)]) +def test_every_sampling_entry_point_accepts_an_integral_count_of_any_numeric_type(n_samples): + """Every public sampling entry point draws as many samples for an integral count of any numeric type, a 0-d + array included, as for the integer count. Regression: ``sample()`` rejected a 0-d array, while ``to_empirical()`` + and ``SampledCoalescent`` passed the count to NumPy, which rejected a float as a shape.""" + coal = pg.Coalescent(n=3) + two_locus = pg.Coalescent(n=3, loci=2, recombination_rate=1.0).sfs2 + joint = coal.joint(pg.TreeHeightReward(), pg.TotalBranchLengthReward()) + + assert coal.tree_height.sample(n_samples, seed=SEED).shape == (2,) + assert coal.sfs.sample(n_samples, seed=SEED).shape == (2, 4) + assert two_locus.sample(n_samples, seed=SEED).shape[0] == 2 + assert two_locus.sample_per_locus(n_samples, seed=SEED)[0].shape[0] == 2 + assert coal.tree_height.to_empirical(n_samples, seed=SEED).n_samples == 2 + assert coal.tree_height.loci[0].demes['pop_0'].to_empirical(n_samples, seed=SEED).samples.shape == (2,) + assert len(joint.to_empirical(n_samples, seed=SEED)._a) == 2 + assert coal.sfs.to_empirical(n_samples, seed=SEED).n_samples == 2 + assert SampledCoalescent(coal, n_samples=n_samples, seed=SEED).n_samples == 2 + + +def test_empirical_builds_reject_zero_samples(): + """An empirical distribution needs at least one sample, so to_empirical(), SampledCoalescent and MsprimeCoalescent + reject a count of 0. Regression: the count was accepted, the moments came out NaN and cdf and quantile failed with + reshape and index errors.""" + coal = pg.Coalescent(n=3) + + for build in (coal.tree_height.to_empirical, coal.sfs.to_empirical, coal.tree_height.distribution().to_empirical, + coal.joint(pg.TreeHeightReward(), pg.TotalBranchLengthReward()).to_empirical, + lambda k: SampledCoalescent(coal, n_samples=k), lambda k: MsprimeCoalescent(n=3, num_replicates=k)): + with pytest.raises(ValueError, match='number of samples must be an integer of at least 1'): + build(0) + + assert coal.tree_height.sample(0, seed=SEED).shape == (0,) + + +def test_msprime_coalescent_rejects_unscaled_multiple_merger_time(): + """MsprimeCoalescent rejects a Beta or Dirac coalescent with scale_time=False, whose time scale msprime does not + offer. Regression: msprime simulated its own time scale, giving a mean tree height of 2.60 for Beta(1.5) where the + exact value is 1.63.""" + for model in (pg.BetaCoalescent(alpha=1.5, scale_time=False), pg.DiracCoalescent(psi=0.5, c=1, scale_time=False)): + with pytest.raises(ValueError, match='only on its own time scale'): + MsprimeCoalescent(n=4, model=model, num_replicates=10) + + +def test_empirical_single_deme_covariance_is_a_matrix(): + """The deme and locus covariance and correlation of an empirical scalar statistic are (1, 1) matrices for one deme + and one locus, as for the exact distribution. Regression: np.cov of a single row gave a 0-d array.""" + coal = pg.Coalescent(n=4) + sampled = SampledCoalescent(coal, n_samples=200, seed=SEED).tree_height + + for name in ('cov', 'corr'): + assert getattr(sampled.demes, name).shape == getattr(coal.tree_height.demes, name).shape == (1, 1) + assert getattr(sampled.loci, name).shape == getattr(coal.tree_height.loci, name).shape == (1, 1) diff --git a/testing/test_sparse_dense_equivalence.py b/testing/test_sparse_dense_equivalence.py index 96acffca..e47a7c07 100644 --- a/testing/test_sparse_dense_equivalence.py +++ b/testing/test_sparse_dense_equivalence.py @@ -2,9 +2,9 @@ Equivalence of sparse and dense rate-matrix construction (and the moment paths that consume it). The rate matrix is stored densely for small state spaces and sparsely once the transient count exceeds -:attr:`Settings.dense_rate_matrix_max_states` (see :meth:`StateSpace._construct_numba`). Likewise the moment +:attr:`Settings.dense_rate_matrix_max_states` (see :attr:`StateSpace.S`). Likewise the moment paths switch to sparse linear algebra (expm-action, sparse closed-form LU) above -:attr:`Settings.expm_action_min_dim` / :attr:`Settings.closed_form_sparse_min_states`. These thresholds only +:attr:`Settings.expm_method` / :attr:`Settings.closed_form_sparse_min_states`. These settings only change *how* a result is computed, never *what*; this module pins that down at small, fast sizes by forcing the construction sparse-vs-dense and the moment paths sparse-vs-dense and asserting bit-for-bit (construction) and floating-point (moments) agreement across every state-space type. @@ -140,13 +140,13 @@ def test_moment_paths_sparse_matches_dense(label, make, get): """Forcing the moment paths fully sparse vs fully dense yields the same statistic to floating-point tolerance.""" # fully dense: dense rate matrix and dense expm / closed-form everywhere Settings.dense_rate_matrix_max_states = _HUGE - Settings.expm_action_min_dim = _HUGE + Settings.expm_method = 'dense' Settings.closed_form_sparse_min_states = _HUGE dense = get(make()) # fully sparse: sparse rate matrix and sparse expm-action / closed-form everywhere Settings.dense_rate_matrix_max_states = 0 - Settings.expm_action_min_dim = 0 + Settings.expm_method = 'action' Settings.closed_form_sparse_min_states = 0 sparse = get(make()) @@ -203,7 +203,7 @@ def _three_epoch_single(): # joint-reward inversion on multi-epoch spaces with the bounded epochs of the transform propagated by dense Pade -# exponentials or by the Taylor action, forced through ``expm_action_min_dim``. The cases cover the shifted transform +# exponentials or by the Taylor action, forced through ``expm_method``. The cases cover the shifted transform # (``lst``, the cosine CDF and density), its Taylor coefficients over the polynomial ring (``lst_taylor``), the # conditional mean with its jump heights, the marginal, and a sparse-stored final epoch. JOINT_ACTION_CASES = [ @@ -224,8 +224,8 @@ def test_joint_inversion_action_matches_dense(label, make, cf_min): pts = [(-1j * 0.5, -1j * 0.7), (-1j * 2.0, 1j * 3.0), (np.inf, -1j * 2.0), (-1j * 3.0, np.inf)] xs, ys = np.array([0.3, 0.8, 1.4]), np.array([0.35, 0.9, 1.6]) - def evaluate(action_min_dim): - Settings.expm_action_min_dim = action_min_dim + def evaluate(method): + Settings.expm_method = method Settings.closed_form_sparse_min_states = cf_min Settings.cos_terms_2d = 24 jd = make() @@ -239,7 +239,7 @@ def evaluate(action_min_dim): marginal_cdf=np.asarray(jd.marginal('b').cdf(ys), dtype=float), ) - dense, action = evaluate(_HUGE), evaluate(0) + dense, action = evaluate('dense'), evaluate('action') for key in dense: np.testing.assert_allclose(action[key], dense[key], atol=1e-9, rtol=1e-7, err_msg=f"{label}: {key}") @@ -264,11 +264,11 @@ def test_taylor_action_in_norm_sorted_chunks_matches_dense(monkeypatch): s_a = np.array([0.3, -40j, 2.0, 0.1j, -7 + 3j, 15.0, 0.0, -2j]) s_b = s_a[::-1].copy() - Settings.expm_action_min_dim = _HUGE + Settings.expm_method = 'dense' dense = jd.lst_batch(s_a, s_b) dense_taylor = np.array([jd.lst_taylor(x, on='a', order=2) for x in s_a]) - Settings.expm_action_min_dim = 0 + Settings.expm_method = 'action' monkeypatch.setattr(reward, '_LST_VECTOR_ENTRIES', 1) np.testing.assert_allclose(jd.lst_batch(s_a, s_b), dense, rtol=1e-9, atol=1e-12) np.testing.assert_allclose(jd._lst_taylor_batch(s_a, 'a', 2), dense_taylor, rtol=1e-9, atol=1e-12) diff --git a/testing/test_state_space.py b/testing/test_state_space.py index a31eff63..3a92436e 100644 --- a/testing/test_state_space.py +++ b/testing/test_state_space.py @@ -36,24 +36,19 @@ def test_default_intensity_matrix_n_4(): [0., 0., -1., 1.], [0., 0., 0., -0.]])) - def test_rate_matrix_first_still_records_time_and_primes_states(self): - """Materialising ``S`` before ``states`` must still record the construction time and prime ``states`` -- the - bookkeeping the ``states`` cached_property otherwise owns, so the large-space warning is not skipped and - ``time`` is recorded. Regression for the numba ``_get_rate_matrix`` bypassing the cached_property.""" + def test_rate_matrix_first_still_records_time(self): + """Materialising ``S`` before ``states`` records the construction time, so the large-space warning is not + skipped either. Regression for the numba construction bypassing the bookkeeping of ``states``.""" s = pg.LineageCountingStateSpace( lineage_config=pg.LineageConfig(n=6), model=pg.StandardCoalescent(), epoch=pg.Epoch() ) - if not s._use_numba(): - self.skipTest("the bookkeeping bypass only affects the numba construction path") - assert s.time is None _ = s.S # materialise the rate matrix before ever touching .states assert s.time is not None and s.time >= 0 - assert 'states' in s.__dict__ # states primed, so its cached_property will not rebuild def test_numba_python_equivalence_two_locus_lineage_counting(self): """The numba kernel (kind 3) builds the same two-locus lineage-counting state space -- states and rate matrix @@ -740,32 +735,6 @@ def test_state_space_equality(self): ) ) - def test_state_space_caching(self): - """ - Test that the state space is cached. The ``_cache`` epoch cache is a property of the pure-Python construction - path (the numba path caches the rate matrix via the ``S`` cached-property instead), so this exercises the - Python path explicitly. - """ - pg.Settings.use_numba = False - - try: - s = pg.state_space.LineageCountingStateSpace( - lineage_config=pg.LineageConfig(n=4), - model=pg.StandardCoalescent(), - epoch=pg.Epoch(pop_sizes={'pop_0': 2}) - ) - - # check that the cache is empty - self.assertEqual(s._cache, {}) - - # compute rate matrix - _ = s.S - - # check that the rate matrix is in the cache - self.assertTrue(s.epoch in s._cache) - finally: - pg.Settings.use_numba = True - def test_epoch_equality(self): """ Test that the equality operator works as expected. @@ -873,53 +842,6 @@ def test_rescale_uses_sampled_population_size(): testing.assert_allclose(np.asarray(s.S), np.asarray(fresh.S), rtol=1e-12) -def test_two_deme_two_epoch_cdf_builds_each_rate_matrix_once(monkeypatch): - """ - The tree-height CDF of a two-deme, two-epoch coalescent builds the rate matrix of each epoch once. Regression: - the absorption checks visit the last epoch before the sweep returns to the first, and the rate matrix of every - epoch was dropped on leaving it, so both were built twice. - """ - build, built = pg.StateSpace._construct_numba, [] - monkeypatch.setattr(pg.StateSpace, '_construct_numba', lambda ss: built.append(ss.epoch.start_time) or build(ss)) - - coal = pg.Coalescent(n={'pop_0': 3, 'pop_1': 3}, demography=pg.Demography( - pop_sizes={'pop_0': {0: 1, 0.5: 0.3}, 'pop_1': {0: 0.5}}, - migration_rates={('pop_0', 'pop_1'): {0: 1}, ('pop_1', 'pop_0'): {0: 0.2}} - )) - coal.tree_height.cdf(np.linspace(0, 5, 50)) - - assert built == [0, 0.5] - - -def test_update_epoch_restores_the_rate_matrix_of_the_epoch_left_last(): - """ - Returning to the epoch left last restores its rate matrix, equal to one built afresh for that epoch, and a third - epoch builds its own. - """ - lineages = pg.LineageConfig({'a': 2, 'b': 2}) - epochs = [pg.Epoch(start_time=i, pop_sizes={'a': 1 + i, 'b': 2}, migration_rates={('a', 'b'): 1, ('b', 'a'): 1}) - for i in range(3)] - s = pg.LineageCountingStateSpace(lineage_config=lineages, model=pg.StandardCoalescent(), epoch=epochs[0]) - - S0 = s.S - s.update_epoch(epochs[1]) - S1 = s.S - s.update_epoch(epochs[0]) - assert s.S is S0 - s.update_epoch(epochs[2]) - s.update_epoch(epochs[1]) - assert s.S is not S1 - - for epoch in [epochs[2], epochs[0]]: - s.update_epoch(epoch) - fresh = pg.LineageCountingStateSpace(lineage_config=lineages, model=pg.StandardCoalescent(), epoch=epoch) - testing.assert_array_equal(np.asarray(s.S), np.asarray(fresh.S)) - - s.drop_cache() - s.update_epoch(epochs[2]) - assert 'S' not in s.__dict__ - - @pytest.mark.parametrize('n_states, level', [(4999, None), (5000, 'slow'), (15000, 'very slow'), (50000, 'extremely slow')]) def test_large_state_space_warns_once_at_the_highest_level(n_states, level, caplog, monkeypatch): @@ -942,3 +864,127 @@ def test_large_state_space_warns_once_at_the_highest_level(n_states, level, capl assert not records else: assert len(records) == 1 and records[0].getMessage().endswith(f"may be {level}.") + + +def _multi_epoch_spaces(): + """State spaces of every type and model with the epochs they are compared over, including one without migration.""" + def epochs(pops): + pairs = [(a, b) for a in pops for b in pops if a != b] + return [pg.Epoch(start_time=i, pop_sizes={p: 0.6 + 0.45 * i + 0.2 * j for j, p in enumerate(pops)}, + migration_rates={pair: m * (0.3 + 0.1 * k) for k, pair in enumerate(pairs)}) + for i, m in enumerate([1, 0, 2.5])] + + models = {'kingman': pg.StandardCoalescent(), 'beta': pg.BetaCoalescent(alpha=1.4), + 'dirac': pg.DiracCoalescent(psi=0.4, c=3)} + out = [] + for name, model in models.items(): + out += [ + pytest.param(lambda m=model: pg.LineageCountingStateSpace(pg.LineageConfig(n=5), model=m), + epochs(['pop_0']), id=f'{name}-lineages'), + pytest.param(lambda m=model: pg.BlockCountingStateSpace(pg.LineageConfig(n=5), model=m), + epochs(['pop_0']), id=f'{name}-blocks'), + pytest.param(lambda m=model: pg.LineageCountingStateSpace(pg.LineageConfig({'a': 2, 'b': 1, 'c': 1}), + model=m), + epochs(['a', 'b', 'c']), id=f'{name}-lineages-3-demes'), + pytest.param(lambda m=model: pg.JointBlockCountingStateSpace(pg.LineageConfig({'a': 2, 'b': 2}), model=m), + epochs(['a', 'b']), id=f'{name}-joint'), + pytest.param(lambda m=model: pg.LineageCountingStateSpace( + pg.LineageConfig({'a': 2, 'b': 1}), locus_config=pg.LocusConfig(n=2, recombination_rate=0.8), + model=m), epochs(['a', 'b']), id=f'{name}-lineages-two-loci'), + pytest.param(lambda m=model: pg.TwoLocusBlockCountingStateSpace( + pg.LineageConfig(n=3), locus_config=pg.LocusConfig(n=2, recombination_rate=0.8), model=m), + epochs(['pop_0']), id=f'{name}-blocks-two-loci'), + ] + + return out + + +@pytest.mark.parametrize('use_numba', [True, False], ids=['numba', 'python']) +@pytest.mark.parametrize('dense', [True, False], ids=['dense', 'sparse']) +@pytest.mark.parametrize('make, epochs', _multi_epoch_spaces()) +def test_rate_matrix_of_each_epoch_matches_its_transitions(make, epochs, dense, use_numba): + """ + The rate matrix assembled from the basis for each epoch equals the one built from the transitions enumerated at + that epoch, and its sparse form stores no zero-rate transition, for every state-space type, coalescent model and + construction. + """ + pg.Settings.use_numba = use_numba + pg.Settings.dense_rate_matrix_max_states = 10 ** 6 if dense else 0 + ss = make() + + for epoch in epochs + epochs[::-1]: + ss.update_epoch(epoch) + S = ss.S + assert sp.issparse(S) != dense + + transitions, states = ss.get_transitions() + index = {s: i for i, s in enumerate(ss.states)} + expected = np.zeros((ss.k, ss.k)) + for (a, b), (rate, _) in transitions.items(): + expected[index[a], index[b]] = rate + expected[np.diag_indices(ss.k)] = -expected.sum(axis=1) + + actual = S.toarray() if sp.issparse(S) else S + testing.assert_allclose(actual, expected, rtol=0, atol=1e-13 * np.abs(expected).max()) + + if not dense: + coo = S.tocoo() + assert np.all(coo.data[coo.row != coo.col] != 0) + + +@pytest.mark.parametrize('use_numba', [True, False], ids=['numba', 'python']) +def test_states_are_enumerated_once_per_state_space(use_numba, monkeypatch): + """ + The states and transitions of a state space are enumerated once, whatever the number of epochs and statistics. + Regression: every rate matrix of a space of several demes was rebuilt by a fresh enumeration, about three times + per epoch. + """ + pg.Settings.use_numba = use_numba + enumerate_, calls = pg.StateSpace._enumerate, [] + monkeypatch.setattr(pg.StateSpace, '_enumerate', lambda ss: calls.append(id(ss)) or enumerate_(ss)) + + coal = pg.Coalescent(n={'a': 2, 'b': 2}, demography=pg.Demography( + pop_sizes={'a': {0: 1, 0.5: 0.3, 1.2: 2}, 'b': {0: 0.5, 0.8: 1}}, + migration_rates={('a', 'b'): {0: 1, 1: 0}, ('b', 'a'): {0: 0.2}} + )) + coal.tree_height.cdf(np.linspace(0, 5, 20)) + coal.tree_height.var + coal.jsfs.mean + + assert sorted(calls) == sorted({id(coal.tree_height.state_space), id(coal.jsfs.state_space)}) + + +def test_a_copy_with_another_model_keeps_the_order_of_the_states(): + """A copy with another coalescent model shares the states, and its rate matrix is in their order. The standard + and the Beta coalescent enumerate the states of five lineages in different orders, so the rate matrix of the copy + is permuted.""" + ss = pg.BlockCountingStateSpace(pg.LineageConfig(n=5), model=pg.StandardCoalescent()) + states = ss.states + clone = ss._with(model=pg.BetaCoalescent(alpha=1.7)) + fresh = pg.BlockCountingStateSpace(pg.LineageConfig(n=5), model=pg.BetaCoalescent(alpha=1.7)) + order = [fresh.states.index(s) for s in states] + + assert order != list(range(len(states))) + assert clone.states is states + testing.assert_array_equal(np.asarray(clone.S), np.asarray(fresh.S)[np.ix_(order, order)]) + + +@pytest.mark.parametrize('dump, load', [ + pytest.param(__import__('pickle').dumps, __import__('pickle').loads, id='pickle'), + pytest.param(__import__('dill').dumps, __import__('dill').loads, id='dill'), + pytest.param(lambda x: __import__('jsonpickle').encode(x, keys=True), + lambda x: __import__('jsonpickle').decode(x, keys=True), id='jsonpickle'), +]) +def test_state_space_with_its_basis_round_trips(dump, load): + """A state space serialized with its basis assembles the same rate matrices after loading.""" + epochs = [pg.Epoch(pop_sizes={'a': 1, 'b': 0.4}, migration_rates={('a', 'b'): 0.5, ('b', 'a'): 0.1}), + pg.Epoch(pop_sizes={'a': 2, 'b': 3}, migration_rates={('a', 'b'): 0, ('b', 'a'): 1.5})] + ss = pg.JointBlockCountingStateSpace(pg.LineageConfig({'a': 2, 'b': 1}), epoch=epochs[0]) + _ = ss.S + + restored = load(dump(ss)) + + for epoch in epochs: + ss.update_epoch(epoch) + restored.update_epoch(epoch) + testing.assert_array_equal(np.asarray(restored.S), np.asarray(ss.S)) diff --git a/testing/test_two_locus_sfs.py b/testing/test_two_locus_sfs.py index 3367bd5f..e93b45aa 100644 --- a/testing/test_two_locus_sfs.py +++ b/testing/test_two_locus_sfs.py @@ -36,7 +36,7 @@ def _single_locus_cross_moment(n, model=None): def _mean_per_pair(dist): - """Mean two-locus SFS via the per-pair cross-moment path (the batched form's fallback).""" + """Mean two-locus SFS from the cross-moment of each pair of classes.""" from phasegen.rewards import CombinedReward, TwoLocusSFSReward from phasegen.distributions.phase_type import PhaseTypeDistribution @@ -52,28 +52,18 @@ def _mean_per_pair(dist): return (out + out.T) / 2 -@pytest.mark.parametrize("n,r", [(4, 1.0), (5, 0.5), (4, 10.0), (3, 0.0)]) -def test_batched_mean_matches_per_pair(n, r): +@pytest.mark.parametrize("n,r,sizes", [ + (4, 1.0, {0: 1.0}), (5, 0.5, {0: 1.0}), (4, 10.0, {0: 1.0}), (3, 0.0, {0: 1.0}), + (4, 1.0, {0: 1.0, 0.5: 0.3}), (4, 0.7, {0: 1.0, 0.4: 0.5, 1.0: 2.0}) +]) +def test_batched_mean_matches_per_pair(n, r, sizes): """ - The batched two-locus mean (a single factored two-point contraction) must equal the per-pair cross-moment path - it replaces, and must actually be taken on a single-epoch demography. The factored form avoids materialising the - dense two-point operator ``K``, whose ``O(n_states^2)`` size makes the naive batching slower than per-pair (and - prohibitive at n=10) on the large two-locus state space. + The two-locus mean from one forward pass over the classes of both loci equals the per-pair cross-moments, in one + and several epochs. """ - dist = pg.Coalescent(n=n, loci=2, recombination_rate=r).sfs2 - - batched = dist._mean_batched() - assert batched is not None # single epoch: the batched path is taken - np.testing.assert_allclose(np.asarray(batched.data), _mean_per_pair(dist), atol=1e-8) - - -def test_batched_mean_falls_back_on_multiple_epochs(): - """A multi-epoch demography has no single-epoch two-point closed form, so the batched mean must fall back.""" - dem = pg.Demography(pop_sizes={'pop_0': {0: 1.0, 0.5: 0.3}}) - dist = pg.Coalescent(n=4, loci=2, recombination_rate=1.0, demography=dem).sfs2 + dist = pg.Coalescent(n=n, loci=2, recombination_rate=r, demography=pg.Demography(pop_sizes={'pop_0': sizes})).sfs2 - assert dist._mean_batched() is None - np.testing.assert_allclose(np.asarray(dist.mean.data), _mean_per_pair(dist), atol=1e-9) + np.testing.assert_allclose(np.asarray(dist.mean.data), _mean_per_pair(dist), rtol=1e-12, atol=1e-14) def test_two_locus_to_json_round_trip(): diff --git a/testing/test_uniformization.py b/testing/test_uniformization.py new file mode 100644 index 00000000..c9bdbcfb --- /dev/null +++ b/testing/test_uniformization.py @@ -0,0 +1,222 @@ +""" +Tests for the uniformized exponential and integral of a Metzler sub-generator +(``phasegen.distributions._uniformization._Uniformization``). +""" +from unittest.mock import patch + +import numpy as np +import pytest +import scipy.linalg as sla +from scipy.special import gammaln + +from phasegen.distributions import _uniformization +from phasegen.distributions._uniformization import _Uniformization + + +def _subgenerator(n: int, scale: float, seed: int = 0, exit_scale: float = None) -> np.ndarray: + """A random dense sub-generator with exits to absorption, at rates up to ``exit_scale`` (``scale`` by default).""" + rng = np.random.default_rng(seed) + A = rng.uniform(0, 1, (n, n)) * (rng.uniform(0, 1, (n, n)) < 0.4) * scale + np.fill_diagonal(A, 0) + np.fill_diagonal(A, -A.sum(axis=1) - rng.uniform(0, 1, n) * (scale if exit_scale is None else exit_scale)) + return A + + +def _van_loan(A: np.ndarray, v: np.ndarray, tau: float): + """The exponential and its integral applied to ``v`` from one dense exponential of the Van Loan matrix.""" + n = len(v) + E = sla.expm(np.block([[A, np.eye(n)], [np.zeros((n, n)), np.zeros((n, n))]]) * tau) + return v @ E[:n, :n], v @ E[:n, n:] + + +@pytest.mark.parametrize('scale, exit_scale, tau', [(1.0, None, 0.3), (1.0, None, 4.0), (50.0, 0.01, 30.0)], + ids=['short', 'long', 'chunked']) +def test_uniformization_matches_the_van_loan_exponential(scale, exit_scale, tau): + """Both products agree with the dense Van Loan exponential, also when the step is split into chunks. The exits of + the chunked case are slow, so that most of the mass is left after the last chunk.""" + A = _subgenerator(12, scale, exit_scale=exit_scale) + v = np.random.default_rng(1).uniform(0, 1, 12) + lam = -A.diagonal().min() + assert (lam * tau > _uniformization._MAX_CHUNK) == (scale == 50.0) + + u, occ = _Uniformization(A).propagate(v, tau) + u_ref, occ_ref = _van_loan(A, v, tau) + + if exit_scale is not None: + assert u_ref.sum() > 0.5 * v.sum() + np.testing.assert_allclose(u, u_ref, rtol=1e-12, atol=1e-14 * v.sum()) + np.testing.assert_allclose(occ, occ_ref, rtol=1e-12) + + +def test_uniformization_keeps_tiny_entries_nonnegative_and_accurate(): + """Down a chain where each entry is about a thousand times smaller than the one before, every entry above the + truncation floor keeps its relative accuracy against the closed form, far below the resolution of the vector's + norm, and none is negative or above the closed form.""" + n, rate, a = 20, 1.0, 1e-3 + # exits at rate 1, of which a fraction a moves one step down the chain: entry k at time t is (a t)^k e^{-t} / k! + A = np.diag(-np.full(n, rate)) + np.diag(np.full(n - 1, a * rate), 1) + v = np.zeros(n) + v[0] = 1 + t = 2.0 + + u, occ = _Uniformization(A).propagate(v, t) + + k = np.arange(n) + exact = np.exp(k * np.log(a * t) - t - gammaln(k + 1)) + above = exact > 100 * _uniformization._FLOOR + assert exact[-1] < _uniformization._FLOOR and exact[above].min() < 1e-40 + assert (u >= 0).all() and (occ >= 0).all() and (u <= exact * (1 + 1e-12)).all() + np.testing.assert_allclose(u[above], exact[above], rtol=1e-12) + + +def test_uniformization_of_a_zero_generator_and_step(): + """A zero generator holds the vector, and a zero step leaves it unchanged with zero integral.""" + v = np.array([0.25, 0.75]) + + u, occ = _Uniformization(np.zeros((2, 2))).propagate(v, 2.0) + np.testing.assert_array_equal(u, v) + np.testing.assert_array_equal(occ, 2 * v) + + u, occ = _Uniformization(_subgenerator(2, 1.0)).propagate(v, 0.0) + np.testing.assert_array_equal(u, v) + np.testing.assert_array_equal(occ, 0 * v) + + +def test_uniformization_truncates_at_the_floor(): + """Entries below the truncation floor relative to the norm may be truncated, but never above it, and the + normalization of the truncated weights raises none by more than the floor.""" + with patch.object(_uniformization, '_FLOOR', 1e-10): + n, a, t = 12, 1e-3, 2.0 + A = np.diag(-np.ones(n)) + np.diag(np.full(n - 1, a), 1) + v = np.zeros(n) + v[0] = 1 + u, _ = _Uniformization(A).propagate(v, t) + + k = np.arange(n) + exact = np.exp(k * np.log(a * t) - t - gammaln(k + 1)) + big = exact > 1e-8 + np.testing.assert_allclose(u[big], exact[big], rtol=1e-2) + assert (u <= exact * (1 + 1e-12) / (1 - 1e-10)).all() + + +def test_uniformization_keeps_the_deep_tail_of_a_chunked_step(): + """Down a chain of equal rates, the state reached after k jumps holds the Poisson probability of k at mean lam t. + Over two chunks, the states far down the chain are reached only by series terms deep in the Poisson tail of a + chunk, and every one above the truncation floor keeps its relative accuracy.""" + n, lam, t = 1500, 1.0, 1000.0 + A = np.diag(-np.full(n, lam)) + np.diag(np.full(n - 1, lam), 1) + v = np.zeros(n) + v[0] = 1 + assert np.ceil(lam * t / _uniformization._MAX_CHUNK) == 2 + + u, _ = _Uniformization(A).propagate(v, t) + + k = np.arange(n) + exact = np.exp(k * np.log(lam * t) - lam * t - gammaln(k + 1)) + above = exact > 1e-35 + assert exact[above].min() < 1e-34 and k[above].max() > 1350 + np.testing.assert_allclose(u[above], exact[above], rtol=1e-10) + + +def test_uniformization_weights_sum_to_one(): + """The truncated Poisson weights are normalized. Regression: they summed to 1 - 1.9e-13 at a mean of 500, a + relative bias that every chunk of a long step reapplied.""" + w, Q = _Uniformization._weights(500.0) + + assert abs(w.sum() - 1) <= 4 * np.finfo(float).eps + assert abs(Q[0] - (1 - w[0])) <= 4 * np.finfo(float).eps + + +def test_uniformization_of_a_stiff_step_over_many_chunks(): + """A fast state draining into a slow one over ten thousand chunks keeps the accuracy of the occupation and of the + vector, against the closed form evaluated at 60 digits. Regression: the unnormalized Poisson weights biased each + chunk by 2e-13, which accumulated to a relative error of 4e-10 in the occupation and 2e-9 in the vector.""" + A = np.array([[-1e3, 1e3 - 1e-3], [0, -1e-3]]) + tau = 5000.0 + assert np.ceil(1e3 * tau / _uniformization._MAX_CHUNK) == 1e4 + + u, occ = _Uniformization(A).propagate(np.array([1.0, 0.0]), tau) + + np.testing.assert_allclose(u[1], 0.0067379469990854670966, rtol=5e-10) + np.testing.assert_allclose(occ, [0.001, 993.2610530009145329], rtol=1e-10) + + +def test_uniformization_stops_once_the_vector_vanishes(): + """A fast exit over twenty thousand chunks empties the vector within the first few, after which no chunk is + evaluated, and the occupation keeps its closed form. Regression: every remaining chunk ran its series on the zero + vector, which made a deep bottleneck at a long epoch time take 23 s in place of 1 s.""" + A = np.array([[-1e3, 0.5e3], [0, -1e3]]) + tau = 1e4 + assert np.ceil(1e3 * tau / _uniformization._MAX_CHUNK) == 2e4 + + calls = [] + series = _uniformization._series + + def counting(*args): + calls.append(1) + return series(*args) + + with patch.object(_uniformization, '_series', counting): + u, occ = _Uniformization(A).propagate(np.array([1.0, 0.0]), tau) + + assert len(calls) < 10 + np.testing.assert_array_equal(u, 0) + np.testing.assert_allclose(occ, [1e-3, 0.5e-3], rtol=1e-12) + + +@pytest.mark.parametrize('factor', [0.99, 1.01]) +@pytest.mark.parametrize('rate_factor', [0.99, 1.01]) +def test_uniformization_drops_entries_just_below_the_support_floor(factor, rate_factor): + """Over a long step, a fast state draining into a slow one is dropped when it holds just below the support floor + relative to the 1-norm, and kept just above it. States holding far less that no entry above the floor reaches are + kept when they exit at most the rate ratio times as fast as the states reachable from those above the floor, and + dropped just above. Once a kept fast state has drained over the first chunk, those faster than the rate ratio + allows relative to the rest are dropped as well, and the rest of the step is taken in one chunk. Both products + agree with the closed form to a few unit roundoffs.""" + r = rate_factor * _uniformization._SUPPORT_RATE_RATIO + A = np.array([[-1.0, 0, 0, 0], [1e6, -1e6, 0, 0], [0, 0, -0.5, 0], [0, 0, 0, -r]]) + v = np.array([1.0, 0, 1e-30, 1e-30]) + v[1] = eps = factor * _uniformization._SUPPORT_FLOOR * v.sum() + tau = 1.0 + fast_kept = factor > 1 + kept = rate_factor < 1 or fast_kept + # the time over which the last state is propagated: the step, the first chunk, or nothing + held = tau if rate_factor < 1 else tau / np.ceil(1e6 * tau / _uniformization._MAX_CHUNK) * fast_kept + + keep = _Uniformization(A)._support(v) + u, occ = _Uniformization(A).propagate(v, tau) + + # the drained state adds about eps relative to the slow state it drains into + u_ref = [np.exp(-tau) * (1 + eps * fast_kept), 0, 1e-30 * np.exp(-0.5 * tau), + 1e-30 * np.exp(-r * tau) * (rate_factor < 1)] + occ_ref = [-np.expm1(-tau) * (1 + eps * fast_kept), eps / 1e6 * fast_kept, 1e-30 * -np.expm1(-0.5 * tau) / 0.5, + 1e-30 * -np.expm1(-r * held) / r] + np.testing.assert_array_equal(keep, [True, fast_kept, True, kept]) + np.testing.assert_allclose(u, u_ref, rtol=1e-12, atol=0) + np.testing.assert_allclose(occ, occ_ref, rtol=1e-12, atol=0) + + +def test_uniformization_drops_a_drained_fast_residue_after_its_first_chunk(): + """A residue of 1e-9 on a state draining a million times faster than the bulk sets the rate of the first chunk + only. Once it has drained, the rest of the step is taken at the rate of the bulk in a single chunk, and both + products keep the closed form. Regression: the whole step was taken at the drain rate in 20000 chunks, which made a + Dirac split whose derived deme shrinks afterwards take 282 s in place of 0.08 s.""" + A = np.array([[-1.0, 0], [1e6, -1e6]]) + v = np.array([1.0, 1e-9]) + tau = 10.0 + assert np.ceil(1e6 * tau / _uniformization._MAX_CHUNK) == 2e4 + + calls = [] + series = _uniformization._series + + def counting(*args): + calls.append(1) + return series(*args) + + with patch.object(_uniformization, '_series', counting): + u, occ = _Uniformization(A).propagate(v, tau) + + c = 1e-9 * 1e6 / (1e6 - 1) + assert len(calls) == 2 + np.testing.assert_allclose(u, [np.exp(-tau) * (1 + c), 0], rtol=1e-12, atol=0) + np.testing.assert_allclose(occ, [-np.expm1(-tau) * (1 + c) - c / 1e6, 1e-15], rtol=1e-12)