From ccdfec04dd0b00523c131500ffb25cf9e7250464 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 20 Nov 2026 13:46:08 -0800 Subject: [PATCH 01/56] Add plain-Python oracles of the jitted functions, and comparison helpers tests/oracle/ holds the numba-jitted code of hypergeo, approx, variational, rescaling, phasing, util, prior and discrete with the decorators stripped. These are the reference that every implementation (numba now, the C extension later) is compared against, and they stay once numba is removed. They were checked against compiled numba to be bit-identical on large seeded sweeps. Deviations from the source make plain Python follow compiled numba, and are marked with '# oracle:' comments: - log, exp, sqrt, pow, sin, tan follow C semantics (inf/NaN instead of raising); lgamma comes from the C runtime (libm, or ucrtbase on Windows) via ctypes, because CPython's own lgamma differs by up to thousands of ulp. - integer powers x**n use repeated squaring, as numba's llvm.powi does. - sums and means are sequential, as in numba (numpy sums pairwise). - scalars are Python floats, so a float division by zero raises ZeroDivisionError as in numba (error_model="python"). - gammaincinv calls scipy.special.gammaincinv, which the numba cfunc wraps. - EPFactors is a plain class. tests/oracle/implementations.py registers the implementations under test, and the `impl` fixture parametrises tests over them. tests/oracle/helpers.py compares an implementation with an oracle (values to within a number of ulp, NaN patterns, in-place updates, raised exceptions); expected_error and errors_match are where the C extension's LibraryError will be accepted in place of numba's exceptions. conftest.py adds a seeded rng fixture and small simulated tree sequences (contemporary, unphased singletons, historical samples). --- tests/conftest.py | 50 ++ tests/oracle/__init__.py | 16 + tests/oracle/_libm.py | 130 +++++ tests/oracle/approx.py | 949 ++++++++++++++++++++++++++++++++ tests/oracle/discrete.py | 17 + tests/oracle/helpers.py | 266 +++++++++ tests/oracle/hypergeo.py | 308 +++++++++++ tests/oracle/implementations.py | 75 +++ tests/oracle/phasing.py | 217 ++++++++ tests/oracle/prior.py | 55 ++ tests/oracle/rescaling.py | 390 +++++++++++++ tests/oracle/util.py | 223 ++++++++ tests/oracle/variational.py | 478 ++++++++++++++++ tests/test_oracle_helpers.py | 318 +++++++++++ 14 files changed, 3492 insertions(+) create mode 100644 tests/oracle/__init__.py create mode 100644 tests/oracle/_libm.py create mode 100644 tests/oracle/approx.py create mode 100644 tests/oracle/discrete.py create mode 100644 tests/oracle/helpers.py create mode 100644 tests/oracle/hypergeo.py create mode 100644 tests/oracle/implementations.py create mode 100644 tests/oracle/phasing.py create mode 100644 tests/oracle/prior.py create mode 100644 tests/oracle/rescaling.py create mode 100644 tests/oracle/util.py create mode 100644 tests/oracle/variational.py create mode 100644 tests/test_oracle_helpers.py diff --git a/tests/conftest.py b/tests/conftest.py index d0f9dc15..846ecb53 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,4 +1,7 @@ +import msprime +import numpy as np import pytest +from oracle.implementations import IMPLEMENTATIONS def pytest_addoption(parser): @@ -32,3 +35,50 @@ def pytest_configure(config): config.addinivalue_line( "markers", "makefiles: mark test to run only when --make-files option given" ) + + +@pytest.fixture(params=list(IMPLEMENTATIONS), ids=list(IMPLEMENTATIONS)) +def impl(request): + """Namespace of an implementation (see oracle/implementations.py).""" + return IMPLEMENTATIONS[request.param] + + +@pytest.fixture +def rng(): + return np.random.default_rng(1024) + + +def _small_ts(samples, seed, mutation_rate=2e-8): + ts = msprime.sim_ancestry( + samples=samples, + population_size=1e4, + recombination_rate=1e-8, + sequence_length=2e5, + random_seed=seed, + ) + return msprime.sim_mutations(ts, rate=mutation_rate, random_seed=seed) + + +@pytest.fixture(scope="session") +def small_ts(): + """20 contemporary diploid samples, ~2e5 bp, with mutations.""" + return _small_ts(20, seed=11) + + +@pytest.fixture(scope="session") +def small_ts_unphased(): + """ + Like `small_ts` (15 diploids) with a high mutation rate so that there are many + singletons; use with ``singletons_phased=False``. Samples belong to individuals. + """ + return _small_ts(15, seed=12, mutation_rate=1e-7) + + +@pytest.fixture(scope="session") +def small_ts_historical(): + """15 diploid samples, 5 of them sampled at time 500 (non-contemporary).""" + samples = [ + msprime.SampleSet(10, ploidy=2, time=0), + msprime.SampleSet(5, ploidy=2, time=500), + ] + return _small_ts(samples, seed=13) diff --git a/tests/oracle/__init__.py b/tests/oracle/__init__.py new file mode 100644 index 00000000..bb6d7859 --- /dev/null +++ b/tests/oracle/__init__.py @@ -0,0 +1,16 @@ +""" +Plain-Python reference implementations ("oracles") of tsdate's jitted functions. + +Each function that is compiled with numba (or later ported to C) has an oracle in +the module of the same name here, e.g. ``oracle.approx.moments``. Equivalence tests +compare every implementation listed in ``oracle.implementations.IMPLEMENTATIONS`` +against the oracle. + +Rules: + +* An oracle is the numba source with the decorators stripped. Change the body only + where plain Python differs from compiled numba (e.g. division by zero raising + instead of giving inf/nan, numpy scalar semantics), and put a comment on each change. +* Oracles call other oracles, never tsdate's numba functions. +* Names and signatures match the tsdate functions exactly. +""" diff --git a/tests/oracle/_libm.py b/tests/oracle/_libm.py new file mode 100644 index 00000000..338f8c31 --- /dev/null +++ b/tests/oracle/_libm.py @@ -0,0 +1,130 @@ +""" +C-semantics versions of the `math` functions used by the oracles. + +Compiled numba calls libm directly, so e.g. ``log(0.0) == -inf``, ``exp(1e4) == inf`` +and ``sqrt(-1.0)`` is NaN. Python's `math` module raises ``ValueError`` or +``OverflowError`` in these cases. These wrappers return the C results instead and +otherwise defer to `math`, so values agree with numba's libm calls. `lgamma` goes +to libm itself (see `_load_libm_lgamma`). +""" + +import ctypes +import ctypes.util +import math +import sys + +import numpy as np + +_inf = math.inf +_nan = math.nan + + +def log(x): + try: + return math.log(x) + except ValueError: + return -_inf if x == 0.0 else _nan + + +def exp(x): + try: + return math.exp(x) + except OverflowError: + return _inf + + +def sqrt(x): + try: + return math.sqrt(x) + except ValueError: + return _nan + + +def sin(x): + try: + return math.sin(x) + except ValueError: # sin(+-inf) + return _nan + + +def tan(x): + try: + return math.tan(x) + except ValueError: # tan(+-inf) + return _nan + + +def _load_libm_lgamma(): + """ + The platform C runtime's ``lgamma``, as used by compiled numba (and by the C + library): libm on Linux and macOS, the Universal CRT (``ucrtbase``) on Windows. + CPython's `math.lgamma` is its own Lanczos implementation, which differs from + the C runtime by up to thousands of ulp where lgamma is near zero (x near 1 or + 2), so there is deliberately no fallback to it: if the C runtime can't be + loaded, the import fails rather than the oracle silently drifting. + """ + name = ctypes.util.find_library("m") + if name is None and sys.platform == "win32": + name = "ucrtbase" + if name is None: + raise ImportError("could not locate the C runtime library providing lgamma") + func = ctypes.CDLL(name).lgamma + func.restype = ctypes.c_double + func.argtypes = [ctypes.c_double] + assert math.isclose(func(5.0), math.log(24.0), rel_tol=1e-12) + return func + + +_libm_lgamma = _load_libm_lgamma() + + +def lgamma(x): + return _libm_lgamma(x) + + +def erf(x): + return math.erf(x) + + +def pow(x, y): # noqa: A001 + try: + return math.pow(x, y) + except OverflowError: + return _inf + except ValueError: + # 0 ** negative is a pole; negative ** non-integer is NaN + return _inf if x == 0.0 else _nan + + +def ipow(x, n): + """ + ``x ** n`` for a small positive integer constant ``n``, by repeated squaring. + + Numba lowers a float raised to an integer constant this way (``llvm.powi``), so + ``x ** 2 == x * x``. CPython calls libm ``pow`` instead, which differs from + this by an ulp in a small fraction of cases. Compiled code (and the C port) has + the repeated-squaring behaviour, and it matters where results cancel + (e.g. ``va = sq - mn ** 2``). + """ + result = 1.0 + while True: + if n & 1: + result *= x + n >>= 1 + if n == 0: + return result + x *= x + + +def seq_sum(x): + """ + Sum of a 1d array, accumulating strictly left to right, as numba (and a C loop) + does. ``np.sum`` uses pairwise summation, which differs in the last bits. + """ + x = np.asarray(x) + return x.dtype.type(0) if x.size == 0 else np.cumsum(x)[-1] + + +def seq_mean(x): + """Mean of a 1d array using `seq_sum`, as ``np.mean`` is compiled by numba.""" + return seq_sum(x) / np.size(x) diff --git a/tests/oracle/approx.py b/tests/oracle/approx.py new file mode 100644 index 00000000..863a0a34 --- /dev/null +++ b/tests/oracle/approx.py @@ -0,0 +1,949 @@ +"""Oracles for the jitted functions in ``tsdate.approx``.""" + +from math import inf, nan + +import numpy as np + +from tsdate.approx import _KLMIN_MAXITT, _KLMIN_RELTOL, KLMinimizationFailedError + +from . import hypergeo + +# oracle: plain `math` raises on log(0), exp overflow etc., where compiled numba +# follows C (-inf, inf, nan); `_libm` restores the C results. +# oracle: numba computes `x ** n` for integer constants `n` by repeated squaring, +# whereas CPython calls libm pow, which differs by an ulp in a few percent of cases; +# `ipow` does what numba does (see `_libm.ipow`). Changed lines are marked. +# oracle: `np.log` of a Python float returns an `np.float64`, so that a following +# division by zero gives inf (with a warning) where numba, following Python +# semantics, raises ZeroDivisionError; and NumPy's SIMD log may differ from libm by an +# ulp. All `np.log` calls are replaced by the `_libm.log` of a Python float. +# oracle: for the same reason, elements unpacked from a NumPy array are converted with +# `float` (marked `oracle: float`), since in numba they are Python-semantics floats. +from ._libm import exp, ipow, lgamma, log + + +def approximate_log_moments(mean, variance): + """ + Approximate log moments via a second-order Taylor series expansion around + the mean, e.g.: + + E[f(x)] \\approx E[f(mean)] + variance * f''(mean)/2 + + Returns approximations to E[log x], E[x log x], E[(log x)^2] + """ + assert mean > 0 + assert variance > 0 + logx = log(mean) - 0.5 * variance / ipow(mean, 2) # oracle: ipow + xlogx = mean * log(mean) + 0.5 * variance / mean + logx2 = ipow(log(mean), 2) + (1 - log(mean)) * variance / ipow( + mean, 2 + ) # oracle: ipow + return logx, xlogx, logx2 + + +def approximate_gamma_kl(x, logx): + """ + Use Newton root finding to get gamma natural parameters matching the sufficient + statistics :math:`E[x]` and :math:`E[\\log x]`, minimizing KL divergence. + + The initial condition uses the upper bound :math:`digamma(x) \\leq log(x) - 1/2x`. + + Returns the shape and rate of the approximating gamma. + """ + if x <= 0.0 or np.isinf(logx): + raise KLMinimizationFailedError("Nonpositive or nonfinite moments") + if not log(x) > logx: + raise KLMinimizationFailedError( + "log E[t] <= E[log t] violates Jensen's inequality" + ) + alpha = 0.5 / (log(x) - logx) # lower bound on alpha + # asymptotically the lower bound becomes sharp + if 1.0 / alpha < 1e-4: + return alpha - 1.0, alpha / x + itt = 0 + delta = np.inf + # determine convergence when the change in alpha falls below + # some small value (e.g. square root of machine precision) + while np.abs(delta) > np.abs(alpha) * _KLMIN_RELTOL: + if itt > _KLMIN_MAXITT: + raise KLMinimizationFailedError( + "Maximum iterations reached in KL minimization" + ) + delta = hypergeo._digamma(alpha) - log(alpha) + log(x) - logx + delta /= hypergeo._trigamma(alpha) - 1 / alpha + alpha -= delta + itt += 1 + if not np.isfinite(alpha) or alpha <= 0: + raise KLMinimizationFailedError("Invalid shape parameter in KL minimization") + return alpha - 1.0, alpha / x + + +def approximate_gamma_mom(mean, variance): + """ + Use the method of moments to approximate a distribution with a gamma of the + same mean and variance, returning natural parameters + """ + if not (mean > 0.0 and variance > 0.0): + raise KLMinimizationFailedError("Nonpositive central moments") + shape = ipow(mean, 2) / variance # oracle: ipow + rate = mean / variance + return shape - 1.0, rate + + +def approximate_gamma_iqr(q1, q2, x1, x2, max_shape): + """Find gamma natural parameters that match empirical quantiles""" + + def upper_bound(q, x): # cap shape parameter + beta = hypergeo._gammainc_inv(max_shape, q) / x + return max_shape - 1, beta + + if x2 == x1: + return upper_bound(q1, x1) + if not (q2 > q1 and x2 > x1): + raise KLMinimizationFailedError("Quantiles must be sorted") + alpha = log(q2 / q1) / log(x2 / x1) # lower bound + if alpha > max_shape: + return upper_bound(q1, x1) + + # refine with newton iteration + delta = inf + itt = 0 + while abs(delta) > abs(alpha) * _KLMIN_RELTOL: + if itt > _KLMIN_MAXITT: + raise KLMinimizationFailedError( + "Maximum iterations reached in quantile matching" + ) + y1 = hypergeo._gammainc_inv(alpha, q1) + y2 = hypergeo._gammainc_inv(alpha, q2) + obj = y2 / y1 - x2 / x1 + inv_1 = -exp(y1 + log(y1) * (1 - alpha) + lgamma(alpha)) + inv_2 = -exp(y2 + log(y2) * (1 - alpha) + lgamma(alpha)) + # print(itt, alpha, y1, y2) #DEBUG + gra_1 = hypergeo._gammainc_der(alpha, y1) * inv_1 + gra_2 = hypergeo._gammainc_der(alpha, y2) * inv_2 + gra = (gra_2 * y1 - gra_1 * y2) / ipow(y1, 2) # oracle: ipow + delta = -obj / gra + alpha += delta + itt += 1 + + if not alpha > 0: + raise KLMinimizationFailedError("Negative shape parameter") + if alpha > max_shape: + return upper_bound(q1, x1) + beta = hypergeo._gammainc_inv(alpha, q1) / x1 + return alpha - 1, beta + + +def average_gammas(alpha, beta): + """ + Given natural parameters for a set of gammas, average sufficient + statistics so as to get a "global" gamma, returning natural + parameters + """ + assert alpha.size == beta.size, "Array sizes are not equal" + avg_x = 0.0 + avg_logx = 0.0 + for shape, rate in zip(map(float, alpha + 1.0), map(float, beta)): # oracle: float + avg_logx += hypergeo._digamma(shape) - log(rate) + avg_x += shape / rate + avg_x /= alpha.size + avg_logx /= alpha.size + return approximate_gamma_kl(avg_x, avg_logx) + + +def _valid_moments(mn, va): + if not (np.isfinite(mn) and np.isfinite(va)): + return False + if not (mn > 0.0 and va > 0.0): + return False + return True + + +def _valid_gamma(s, r): + if not (np.isfinite(s) and np.isfinite(r)): + return False + if s <= 0.0 or r <= 0.0: + return False + return True + + +def _valid_hyp1f1(a, b, z): + if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(z)): + return False + if not (b >= a > 0.0): + return False + return True + + +def _valid_hyperu(a, b, z): + if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(z)): + return False + if z <= 0.0: + return False + if not (b > a > 0.0): + return False + return True + + +def _valid_hyp2f1(a, b, c, z): + if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(c)): + return False + if not np.isfinite(z) or z >= 1 or z / (z - 1) >= 1: + return False + if not (a > 0 and b > 0 and c > 0): + return False + return True + + +def moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): + r""" + log p(t_i, t_j) := \ + log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ + log(t_i) * (a_i - 1) - b_i * t_i + \ + log(t_j) * (a_j - 1) - b_j * t_j + + Returns normalizing constant, E[t_i], V[t_i], E[t_j], V[t_j]. + """ + + a = a_j + b = a_i + a_j + y_ij + c = a_j + y_ij + 1 + t = mu_ij + b_i + z = (mu_ij - b_j) / t if t > 0 else nan + + if not _valid_hyp2f1(a, b, c, z): + return nan, nan, nan, nan, nan + + hyp2f1 = hypergeo._hyp2f1_laplace + f0 = hyp2f1(a + 0, b + 0, c + 0, z) + f1 = hyp2f1(a + 1, b + 1, c + 1, z) + f2 = hyp2f1(a + 2, b + 2, c + 2, z) + s1 = a * b / c + s2 = s1 * (a + 1) * (b + 1) / (c + 1) + d1 = s1 * exp(f1 - f0) + d2 = s2 * exp(f2 - f0) + + logl = f0 + hypergeo._betaln(y_ij + 1, a) + lgamma(b) - b * log(t) + + mn_j = d1 / t + sq_j = d2 / ipow(t, 2) # oracle: ipow + va_j = sq_j - ipow(mn_j, 2) # oracle: ipow + + mn_i = mn_j * z + b / t + sq_i = sq_j * ipow(z, 2) + (b + 1) * (mn_i + mn_j * z) / t # oracle: ipow + va_i = sq_i - ipow(mn_i, 2) # oracle: ipow + + return logl, mn_i, va_i, mn_j, va_j + + +def rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): + r""" + log p(t_i) := \ + log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ + log(t_i) * (a_i - 1) - b_i * t_i + + Returns normalizing constant, E[t_i], V[t_i]. + """ + + assert t_j >= 0.0 + + s = a_i + y_ij + r = mu_ij + b_i + + if not _valid_gamma(s, r): + return nan, nan, nan + + if t_j == 0.0: + logl = lgamma(s) - s * log(r) + mn_i = s / r + va_i = s / ipow(r, 2) # oracle: ipow + return logl, mn_i, va_i + + a = y_ij + 1 + b = s + 1 + z = t_j * r + + if not _valid_hyperu(a, b, z): + return nan, nan, nan + + hyperu = hypergeo._hyperu_laplace + f0, d0 = hyperu(a + 0, b + 0, z) + f1, d1 = hyperu(a + 1, b + 1, z) + + logl = f0 - b_i * t_j + (b - 1) * log(t_j) + lgamma(a) + mn_i = t_j * (1 - d0) + va_i = ipow(t_j, 2) * d0 * (d1 - d0) # oracle: ipow + + return logl, mn_i, va_i + + +def leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): + r""" + log p(t_j) := \ + log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ + log(t_j) * (a_j - 1) - b_j * t_j + + Returns normalizing constant, E[t_j], V[t_j]. + """ + + assert t_i > 0.0 + + a = a_j + b = a_j + y_ij + 1 + z = t_i * (mu_ij - b_j) + + if not _valid_hyp1f1(a, b, z): + return nan, nan, nan + + hyp1f1 = hypergeo._hyp1f1_laplace + f0 = hyp1f1(a + 0, b + 0, z) + f1 = hyp1f1(a + 1, b + 1, z) + f2 = hyp1f1(a + 2, b + 2, z) + d1 = a / b * exp(f1 - f0) + d2 = a / b * (a + 1) / (b + 1) * exp(f2 - f0) + + logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + hypergeo._betaln(a, b - a) + mn_j = t_i * d1 + sq_j = ipow(t_i, 2) * d2 # oracle: ipow + va_j = sq_j - ipow(mn_j, 2) # oracle: ipow + + return logl, mn_j, va_j + + +def unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): + r""" + log p(t_i, t_j) := \ + log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ + log(t_i) * (a_i - 1) - b_i * t_i + \ + log(t_j) * (a_j - 1) - b_j * t_j + + Returns normalizing constant, E[t_i], V[t_i], E[t_j], V[t_j]. + """ + + a = a_j + b = a_i + a_j + y_ij + c = a_j + a_i + t = mu_ij + b_i + z = (mu_ij + b_j) / t if t > 0 else nan + + if not _valid_hyp2f1(a, b, c, 1 - z): + return nan, nan, nan, nan, nan + + hyp2f1 = hypergeo._hyp2f1_laplace + f0 = hyp2f1(a + 0, b + 0, c + 0, 1 - z) + f1 = hyp2f1(a + 1, b + 1, c + 1, 1 - z) + f2 = hyp2f1(a + 2, b + 2, c + 2, 1 - z) + s1 = a * b / c + s2 = s1 * (a + 1) * (b + 1) / (c + 1) + d1 = s1 * exp(f1 - f0) + d2 = s2 * exp(f2 - f0) + + logl = f0 + hypergeo._betaln(a_j, a_i) + lgamma(b) - b * log(t) + + mn_j = d1 / t + sq_j = d2 / ipow(t, 2) # oracle: ipow + va_j = sq_j - ipow(mn_j, 2) # oracle: ipow + + mn_i = b / t - mn_j * z + sq_i = sq_j * ipow(z, 2) + (b + 1) * (mn_i - mn_j * z) / t # oracle: ipow + va_i = sq_i - ipow(mn_i, 2) # oracle: ipow + + return logl, mn_i, va_i, mn_j, va_j + + +def twin_moments(a_i, b_i, y_ij, mu_ij): + r""" + log p(t_i) := \ + log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ + log(t_i) * (a_i - 1) - b_i * t_i + + Returns normalizing constant, E[t_i], V[t_i]. + """ + s = a_i + y_ij + r = b_i + 2 * mu_ij + logl = log(2) * y_ij + lgamma(s) - log(r) * s + mn_i = s / r + va_i = s / ipow(r, 2) # oracle: ipow + return logl, mn_i, va_i + + +def sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): + r""" + log p(t_j) := \ + log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ + log(t_j) * (a_j - 1) - b_j * t_j + + Returns normalizing constant, E[t_j], V[t_j]. + """ + + assert t_i > 0.0 + + a = a_j + b = a_j + y_ij + 1 + z = t_i * (mu_ij + b_j) + + if not _valid_hyperu(a, b, z): + return nan, nan, nan + + hyperu = hypergeo._hyperu_laplace + f0, d0 = hyperu(a + 0, b + 0, z) + f1, d1 = hyperu(a + 1, b + 1, z) + + logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + lgamma(a) + mn_j = -t_i * d0 + va_j = ipow(t_i, 2) * d0 * (d1 - d0) # oracle: ipow + + return logl, mn_j, va_j + + +def mutation_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): + r""" + log p(t_m, t_i, t_j) = \ + log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ + log(t_i) * (a_i - 1) - b_i * t_i + \ + log(t_j) * (a_j - 1) - b_j * t_j - \ + log(t_i - t_j) + log(int(t_j < t_m < t_i)) + + Returns E[t_m], V[t_m]. + """ + + a = a_j + b = a_i + a_j + y_ij + c = a_j + y_ij + 1 + t = mu_ij + b_i + z = (mu_ij - b_j) / t if t > 0 else nan + + if not _valid_hyp2f1(a, b, c, z): + return nan, nan + + hyp2f1 = hypergeo._hyp2f1_laplace + f000 = hyp2f1(a + 0, b + 0, c + 0, z) + f020 = hyp2f1(a + 0, b + 2, c + 0, z) + f111 = hyp2f1(a + 1, b + 1, c + 1, z) + f121 = hyp2f1(a + 1, b + 2, c + 1, z) + f222 = hyp2f1(a + 2, b + 2, c + 2, z) + + s1 = a * b / c + d1 = b * (b + 1) / ipow(t, 2) # oracle: ipow + d2 = d1 * a / c + d3 = d2 * (a + 1) / (c + 1) + + mn_m = s1 * exp(f111 - f000) / t / 2 * (1 + z) + b / t / 2 + sq_m = ( + d1 * exp(f020 - f000) / 3 + d2 * exp(f121 - f000) / 3 + d3 * exp(f222 - f000) / 3 + ) + va_m = sq_m - ipow(mn_m, 2) # oracle: ipow + + return mn_m, va_m + + +def mutation_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): + r""" + log p(t_m, t_i) := \ + log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ + log(t_i) * (a_i - 1) - b_i * t_i - \ + log(t_i - t_j) + log(int(t_j < t_m < t_i)) + + Returns E[t_m], V[t_m]. + """ + + logl, mn_i, va_i = rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) + mn_m = mn_i / 2 + t_j / 2 + sq_m = (va_i + ipow(mn_i, 2) + mn_i * t_j + ipow(t_j, 2)) / 3 # oracle: ipow + va_m = sq_m - ipow(mn_m, 2) # oracle: ipow + + return mn_m, va_m + + +def mutation_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): + r""" + log p(t_m, t_j) := \ + log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ + log(t_j) * (a_j - 1) - b_j * t_j - \ + log(t_i - t_j) + log(int(t_j < t_m < t_i)) + + Returns E[t_m], V[t_m]. + """ + + logl, mn_j, va_j = leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) + mn_m = mn_j / 2 + t_i / 2 + sq_m = (va_j + ipow(mn_j, 2) + mn_j * t_i + ipow(t_i, 2)) / 3 # oracle: ipow + va_m = sq_m - ipow(mn_m, 2) # oracle: ipow + + return mn_m, va_m + + +def mutation_unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): + r""" + log p(t_m, t_i, t_j) := \ + log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ + log(t_i) * (a_i - 1) - b_i * t_i + \ + log(t_j) * (a_j - 1) - b_j * t_j + \ + log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ + t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) + + Returns P[m under i], E[t_m], V[t_m]. + """ + + # Conditioning on ages of parents: + # P[x under i | t_i, t_j] = t_i / (t_i + t_j) + # E[x | x under t_i, t_i] = t_i / 2 + # E[x^2 | x under t_i, t_i] = t_i**2 / 3 + # and equivalently for t_j. Integrating these moments over the EP surrogate + # density leads to hypergeometric functions similar to the node case, but + # with integer perturbations of a_i, a_j, y_ij. + + a = a_j + b = a_j + a_i + y_ij + c = a_j + a_i + t = mu_ij + b_i + z = (mu_ij + b_j) / t if t > 0 else nan + + if not _valid_hyp2f1(a, b, c, 1 - z): + return nan, nan, nan + + hyp2f1 = hypergeo._hyp2f1_laplace + f000 = hyp2f1(a + 0, b + 0, c + 0, 1 - z) + f001 = hyp2f1(a + 0, b + 0, c + 1, 1 - z) + f012 = hyp2f1(a + 0, b + 1, c + 2, 1 - z) + f023 = hyp2f1(a + 0, b + 2, c + 3, 1 - z) + f212 = hyp2f1(a + 2, b + 1, c + 2, 1 - z) + f323 = hyp2f1(a + 3, b + 2, c + 3, 1 - z) + + s0 = b / t / c / (c + 1) + s1 = (c - a) * (c - a + 1) + s2 = a * (a + 1) + d0 = s0 * (b + 1) / t / (c + 2) + d1 = s1 * (c - a + 2) + d2 = s2 * (a + 2) + + mn_m = s0 * s1 * exp(f012 - f000) / 2 + s0 * s2 * exp(f212 - f000) / 2 + sq_m = d0 * d1 * exp(f023 - f000) / 3 + d0 * d2 * exp(f323 - f000) / 3 + va_m = sq_m - ipow(mn_m, 2) # oracle: ipow + pr_m = (c - a) / c * exp(f001 - f000) + + return pr_m, mn_m, va_m + + +def mutation_twin_moments(a_i, b_i, y_ij, mu_ij): + r""" + log p(t_m, t_i) := \ + log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ + log(t_i) * (a_i - 1) - b_i * t_i + \ + log(int(0 < t_m < t_i) / t_i) + """ + + s = a_i + y_ij + r = b_i + 2 * mu_ij + pr_m = 0.5 + mn_m = s / r / 2 + sq_m = (s + 1) * s / 3 / ipow(r, 2) # oracle: ipow + va_m = sq_m - ipow(mn_m, 2) # oracle: ipow + + return pr_m, mn_m, va_m + + +def mutation_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): + r""" + log p(t_m, t_j) := \ + log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ + log(t_j) * (a_j - 1) - b_j * t_j + \ + log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ + t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) + + Returns P[m under i], E[t_m], V[t_m]. + """ + + assert t_i > 0 + + # Conditioning on ages of parents: + # P[x under i | t_i, t_j] = t_i / (t_i + t_j) + # E[x | x under t_i, t_i] = t_i / 2 + # E[x^2 | x under t_i, t_i] = t_i**2 / 3 + # and equivalently for t_j. Integrating these moments over the EP surrogate + # density leads to Tricomi functions similar to the node case, but + # with integer perturbations of a_j, y_ij. + + a = a_j + b = a_j + y_ij + 1 + z = t_i * (mu_ij + b_j) + + if not _valid_hyperu(a, b, z): + return nan, nan, nan + + # direct but unstable: + hyperu = hypergeo._hyperu_laplace + f00, d00 = hyperu(a + 0, b + 0, z) + f10, d10 = hyperu(a + 1, b + 0, z) + f21, d21 = hyperu(a + 2, b + 1, z) + f32, d32 = hyperu(a + 3, b + 2, z) + pr_m = 1.0 - exp(f10 - f00) * a + mn_m = pr_m * t_i / 2 + t_i * exp(f21 - f00) * a * (a + 1) / 2 + sq_m = ( + pr_m * ipow(t_i, 2) / 3 + + ipow(t_i, 2) * exp(f32 - f00) * a * (a + 1) * (a + 2) / 3 + ) # oracle: ipow + + # TODO: use a stabler approach with derivatives + # note that exp(f10 - f00) = (a + z * d00) / (a - b + 1) + # however the denominator is 0 if y_ij is 0 + # note that when y_ij == 0 then a == b + 1 and f00 = z**(-a) + + va_m = sq_m - ipow(mn_m, 2) # oracle: ipow + + return pr_m, mn_m, va_m + + +def mutation_edge_moments(t_i, t_j): + r""" + log p(t_m) := \ + log(t_i - t_j) + log(int(t_j < t_m < t_i)) + + Returns E[t_m], V[t_m]. + """ + + mn_m = 1 / 2 * (t_i + t_j) + va_m = 1 / 12 * ipow(t_i - t_j, 2) # oracle: ipow + + return mn_m, va_m + + +def mutation_block_moments(t_i, t_j): + r""" + log p(t_m) := \ + log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ + t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) + + Returns P[m under i], E[t_m], V[t_m]. + """ + + assert t_i > 0 + assert t_j > 0 + + pr_m = t_i / (t_i + t_j) + mn_m = pr_m * t_i / 2 + (1 - pr_m) * t_j / 2 + sq_m = pr_m * ipow(t_i, 2) / 3 + (1 - pr_m) * ipow(t_j, 2) / 3 # oracle: ipow + va_m = sq_m - ipow(mn_m, 2) # oracle: ipow + + return pr_m, mn_m, va_m + + +def gamma_projection(pars_i, pars_j, pars_ij): + r""" + log p(t_i, t_j) := \ + log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ + log(t_i) * (a_i - 1) - b_i * t_i + \ + log(t_j) * (a_j - 1) - b_j * t_j + + Returns normalizing constant, gamma natural parameters for parent and child ages + """ + a_i, b_i = map(float, pars_i) # oracle: float + a_j, b_j = map(float, pars_j) # oracle: float + y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i += 1 + a_j += 1 + + logl, mn_i, va_i, mn_j, va_j = moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) + + if not (_valid_moments(mn_i, va_i) and _valid_moments(mn_j, va_j)): + return np.nan, pars_i, pars_j + + proj_i = approximate_gamma_mom(mn_i, va_i) + proj_j = approximate_gamma_mom(mn_j, va_j) + + return logl, np.array(proj_i), np.array(proj_j) + + +def leafward_projection(t_i, pars_j, pars_ij): + r""" + log p(t_j) := \ + log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ + log(t_j) * (a_j - 1) - b_j * t_j + + Returns normalizing constant, gamma natural parameters for child age + """ + a_j, b_j = map(float, pars_j) # oracle: float + y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_j += 1 + + logl, mn_j, va_j = leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) + + if not _valid_moments(mn_j, va_j): + return np.nan, pars_j + + proj_j = approximate_gamma_mom(mn_j, va_j) + + return logl, np.array(proj_j) + + +def rootward_projection(t_j, pars_i, pars_ij): + r""" + log p(t_i) := \ + log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ + log(t_i) * (a_i - 1) - b_i * t_i + + Returns normalizing constant, gamma natural parameters for parent age + """ + a_i, b_i = map(float, pars_i) # oracle: float + y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i += 1 + + logl, mn_i, va_i = rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) + + if not _valid_moments(mn_i, va_i): + return np.nan, pars_i + + proj_i = approximate_gamma_mom(mn_i, va_i) + + return logl, np.array(proj_i) + + +def unphased_projection(pars_i, pars_j, pars_ij): + r""" + log p(t_i, t_j) := \ + log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ + log(t_i) * (a_i - 1) - b_i * t_i + \ + log(t_j) * (a_j - 1) - b_j * t_j + + Returns normalizing constant, gamma natural parameters for parent ages + """ + a_i, b_i = map(float, pars_i) # oracle: float + a_j, b_j = map(float, pars_j) # oracle: float + y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i += 1 + a_j += 1 + + logl, mn_i, va_i, mn_j, va_j = unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) + + if not _valid_moments(mn_i, va_i) or not _valid_moments(mn_j, va_j): + return np.nan, pars_i, pars_j + + proj_i = approximate_gamma_mom(mn_i, va_i) + proj_j = approximate_gamma_mom(mn_j, va_j) + + return logl, np.array(proj_i), np.array(proj_j) + + +def twin_projection(pars_i, pars_ij): + r""" + log p(t_i) := \ + log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ + log(t_i) * (a_i - 1) - b_i * t_i + + Returns normalizing constant, gamma natural parameters for parent ages + """ + a_i, b_i = map(float, pars_i) # oracle: float + y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i += 1 + + logl, mn_i, va_i = twin_moments(a_i, b_i, y_ij, mu_ij) + + if not _valid_moments(mn_i, va_i): + return np.nan, pars_i + + proj_i = approximate_gamma_mom(mn_i, va_i) + + return logl, np.array(proj_i) + + +def sideways_projection(t_i, pars_j, pars_ij): + r""" + log p(t_j) := \ + log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ + log(t_j) * (a_j - 1) - b_j * t_j + + Returns normalizing constant, gamma natural parameters for nonfixed parent age + """ + a_j, b_j = map(float, pars_j) # oracle: float + y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_j += 1 + + logl, mn_j, va_j = sideways_moments(t_i, a_j, b_j, y_ij, mu_ij) + + if not _valid_moments(mn_j, va_j): + return np.nan, pars_j + + proj_j = approximate_gamma_mom(mn_j, va_j) + + return logl, np.array(proj_j) + + +def mutation_gamma_projection(pars_i, pars_j, pars_ij): + r""" + log p(t_m, t_i, t_j) = \ + log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ + log(t_i) * (a_i - 1) - b_i * t_i + \ + log(t_j) * (a_j - 1) - b_j * t_j - \ + log(t_i - t_j) + log(int(t_j < t_m < t_i)) + + Returns phase probability, gamma natural parameters for mutation age + """ + a_i, b_i = map(float, pars_i) # oracle: float + a_j, b_j = map(float, pars_j) # oracle: float + y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i += 1 + a_j += 1 + + mn_m, va_m = mutation_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) + + if not _valid_moments(mn_m, va_m): + return np.nan, np.full(2, np.nan) + + proj_m = approximate_gamma_mom(mn_m, va_m) + + return 1.0, np.array(proj_m) + + +def mutation_leafward_projection(t_i, pars_j, pars_ij): + r""" + log p(t_m, t_j) := \ + log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ + log(t_j) * (a_j - 1) - b_j * t_j - \ + log(t_i - t_j) + log(int(t_j < t_m < t_i)) + + Returns phase probability, gamma natural parameters for mutation age + """ + a_j, b_j = map(float, pars_j) # oracle: float + y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_j += 1 + + mn_m, va_m = mutation_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) + + if not _valid_moments(mn_m, va_m): + return np.nan, np.full(2, np.nan) + + proj_m = approximate_gamma_mom(mn_m, va_m) + + return 1.0, np.array(proj_m) + + +def mutation_rootward_projection(t_j, pars_i, pars_ij): + r""" + log p(t_m, t_i) := \ + log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ + log(t_i) * (a_i - 1) - b_i * t_i - \ + log(t_i - t_j) + log(int(t_j < t_m < t_i)) + + Returns phase probability, gamma natural parameters for mutation age + """ + a_i, b_i = map(float, pars_i) # oracle: float + y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i += 1 + + mn_m, va_m = mutation_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) + + if not _valid_moments(mn_m, va_m): + return np.nan, np.full(2, np.nan) + + proj_m = approximate_gamma_mom(mn_m, va_m) + + return 1.0, np.array(proj_m) + + +def mutation_edge_projection(t_i, t_j): + r""" + log p(t_m) := \ + log(t_i - t_j) + log(int(t_j < t_m < t_i)) + + Returns phase probability, gamma natural parameters for mutation age + """ + mn_m, va_m = mutation_edge_moments(t_i, t_j) + + if not _valid_moments(mn_m, va_m): + return np.nan, np.full(2, np.nan) + + proj_m = approximate_gamma_mom(mn_m, va_m) + + return 1.0, np.array(proj_m) + + +def mutation_unphased_projection(pars_i, pars_j, pars_ij): + r""" + log p(t_m, t_i, t_j) := \ + log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ + log(t_i) * (a_i - 1) - b_i * t_i + \ + log(t_j) * (a_j - 1) - b_j * t_j + \ + log(t_i / (t_i + t_j) * int(0 < t_m < t_i) + \ + t_j / (t_i + t_j) * int(0 < t_m < t_j)) + + Returns phase probability, gamma natural parameters for mutation age + """ + a_i, b_i = map(float, pars_i) # oracle: float + a_j, b_j = map(float, pars_j) # oracle: float + y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i += 1 + a_j += 1 + + pr_m, mn_m, va_m = mutation_unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) + + if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): + return np.nan, np.full(2, np.nan) + + proj_m = approximate_gamma_mom(mn_m, va_m) + + return pr_m, np.array(proj_m) + + +def mutation_twin_projection(pars_i, pars_ij): + r""" + log p(t_m, t_i) := \ + log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ + log(t_i) * (a_i - 1) - b_i * t_i + \ + log(int(0 < t_m < t_i) / t_i) + + Returns phase probability, gamma natural parameters for mutation age + """ + a_i, b_i = map(float, pars_i) # oracle: float + y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i += 1 + + pr_m, mn_m, va_m = mutation_twin_moments(a_i, b_i, y_ij, mu_ij) + + if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): + return np.nan, np.full(2, np.nan) + + proj_m = approximate_gamma_mom(mn_m, va_m) + + return pr_m, np.array(proj_m) + + +def mutation_sideways_projection(t_i, pars_j, pars_ij): + r""" + log p(t_m, t_j) := \ + log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ + log(t_j) * (a_j - 1) - b_j * t_j + \ + log(t_i / (t_i + t_j) * int(0 < t_m < t_i) + \ + t_j / (t_i + t_j) * int(0 < t_m < t_j)) + + Returns phase probability, gamma natural parameters for mutation age + """ + a_j, b_j = map(float, pars_j) # oracle: float + y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_j += 1 + + pr_m, mn_m, va_m = mutation_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij) + + if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): + return np.nan, np.full(2, np.nan) + + proj_m = approximate_gamma_mom(mn_m, va_m) + + return pr_m, np.array(proj_m) + + +def mutation_block_projection(t_i, t_j): + r""" + log p(t_m) := \ + log(t_i / (t_i + t_j) * int(0 < t_m < t_i) + \ + t_j / (t_i + t_j) * int(0 < t_m < t_j)) + + Returns phase probability, gamma natural parameters for mutation age + """ + pr_m, mn_m, va_m = mutation_block_moments(t_i, t_j) + + if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): + return np.nan, np.full(2, np.nan) + + proj_m = approximate_gamma_mom(mn_m, va_m) + + return pr_m, np.array(proj_m) diff --git a/tests/oracle/discrete.py b/tests/oracle/discrete.py new file mode 100644 index 00000000..5437186e --- /dev/null +++ b/tests/oracle/discrete.py @@ -0,0 +1,17 @@ +"""Oracles for the jitted functions in ``tsdate.discrete``.""" + +import numpy as np + + +def logsumexp(X): + alpha = -np.inf + r = 0.0 + for x in X: + if x != -np.inf: + if x <= alpha: + r += np.exp(x - alpha) + else: + r *= np.exp(alpha - x) + r += 1.0 + alpha = x + return -np.inf if r == 0 else np.log(r) + alpha diff --git a/tests/oracle/helpers.py b/tests/oracle/helpers.py new file mode 100644 index 00000000..7d1417b0 --- /dev/null +++ b/tests/oracle/helpers.py @@ -0,0 +1,266 @@ +"""Comparison helpers shared by the oracle equivalence tests.""" + +import numpy as np +import tskit + + +def _flatten(x, path=""): + """Yield (path, array) for each leaf of a nested tuple/list of scalars/arrays.""" + if isinstance(x, (tuple, list)): + for i, item in enumerate(x): + yield from _flatten(item, f"{path}[{i}]") + else: + yield path, np.asarray(x, dtype=np.float64) + + +def assert_ulp_close(actual, desired, maxulp=4): + """ + Assert that two scalars, arrays, or (nested) tuples of them agree to within + ``maxulp`` units in the last place. NaNs must occur in the same places, and + equal infinities compare equal. Shapes and tuple structure must match. + """ + a_leaves = list(_flatten(actual)) + d_leaves = list(_flatten(desired)) + assert len(a_leaves) == len(d_leaves), ( + f"structure mismatch: {len(a_leaves)} vs {len(d_leaves)} values" + ) + for (path, a), (_, d) in zip(a_leaves, d_leaves): + assert a.shape == d.shape, ( + f"shape mismatch at {path or 'value'}: {a.shape} vs {d.shape}" + ) + nan_a, nan_d = np.isnan(a), np.isnan(d) + assert np.array_equal(nan_a, nan_d), ( + f"NaN pattern mismatch at {path or 'value'}:\n{a}\nvs\n{d}" + ) + inf_mask = np.isinf(a) | np.isinf(d) + assert np.array_equal(a[inf_mask], d[inf_mask]), ( + f"infinity mismatch at {path or 'value'}:\n{a}\nvs\n{d}" + ) + ok = ~(nan_a | inf_mask) + if ok.any(): + try: + np.testing.assert_array_max_ulp(a[ok], d[ok], maxulp=maxulp) + except AssertionError as e: + raise AssertionError( + f"values differ by more than {maxulp} ulp at {path or 'value'}:" + f"\nactual: {a}\ndesired: {d}\n{e}" + ) from None + + +def assert_inplace_close(args_actual, args_desired, maxulp=4): + """ + Compare sequences of arguments after both implementations have modified them + in place (e.g. posterior arrays, ``EPFactors`` fields). Each element is + compared with `assert_ulp_close`; use ``(a.node, a.edge, ...)`` to pass fields. + """ + assert len(args_actual) == len(args_desired) + for i, (a, d) in enumerate(zip(args_actual, args_desired)): + try: + assert_ulp_close(a, d, maxulp=maxulp) + except AssertionError as e: + raise AssertionError( + f"argument {i} differs after in-place update: {e}" + ) from None + + +INF = float("inf") +NAN = float("nan") + + +def call(func, *args, **kwargs): + """Call a function, or the ``ctypes`` interface of a compiled numba ``cfunc``.""" + return getattr(func, "ctypes", func)(*args, **kwargs) + + +def log_uniform(rng, lo, hi, size=None): + """``10 ** U(lo, hi)``: a scalar float if ``size`` is None, else an array.""" + x = 10.0 ** rng.uniform(lo, hi, size) + return float(x) if size is None else x + + +def expected_error(exc_type): + """ + The exceptions an implementation may raise where numba raises ``exc_type`` + (``ZeroDivisionError``, ``AssertionError``, ...), for ``pytest.raises``. The C + port adds ``_tsdate.LibraryError`` here; this is the single place to do so. + """ + return (exc_type,) + + +class Outcome: + """ + What calling a function did: ``value`` (its return value) or ``exception``, and + ``args``, the (copied) arguments after the call, to compare in-place updates. + """ + + def __init__(self, value=None, exception=None, args=()): + self.value = value + self.exception = exception + self.args = args + + @property + def error(self): + return None if self.exception is None else type(self.exception) + + def __repr__(self): + if self.exception is None: + return f"Outcome(value={self.value!r})" + return f"Outcome(exception={self.exception!r})" + + +def _copy_arg(x): + if isinstance(x, np.ndarray): + return x.copy() + if isinstance(x, np.floating): + # numba treats scalars as Python floats (division by zero raises) + return float(x) + return x + + +def outcome(func, *args, **kwargs): + """ + Call ``func`` on copies of ``args`` and return an `Outcome`. NumPy floating + scalars are converted to ``float``; NumPy warnings (which the oracle emits where + numba is silent) are suppressed. + """ + copies = [_copy_arg(x) for x in args] + try: + with np.errstate(all="ignore"): + value = call(func, *copies, **kwargs) + except Exception as e: # noqa: BLE001 + return Outcome(exception=e, args=copies) + return Outcome(value=value, args=copies) + + +def errors_match(actual, expected, check_message=True): + """ + Whether exception ``actual`` (from an implementation) matches ``expected`` (from + the oracle): the same type and, if ``check_message``, the same message. The + message of a ``ZeroDivisionError`` comes from the runtime, not from tsdate (numba + says "division by zero", Python "float division by zero"), so it is not compared. + The C port extends this to accept ``_tsdate.LibraryError`` (see + `expected_error`). + """ + if not isinstance(actual, expected_error(type(expected))): + return False + if isinstance(expected, ZeroDivisionError): + return True + return not check_message or str(actual) == str(expected) + + +def assert_same_outcome(actual, expected, maxulp=4, check_message=True): + """ + Assert that two `Outcome` objects agree: both raise matching exceptions, or both + return values (and leave array arguments) within ``maxulp`` ulp. + """ + if expected.exception is not None: + assert actual.exception is not None, ( + f"implementation returned {actual.value!r}, oracle raised " + f"{expected.exception!r}" + ) + assert errors_match(actual.exception, expected.exception, check_message), ( + f"implementation raised {actual.exception!r}, oracle raised " + f"{expected.exception!r}" + ) + return + assert actual.exception is None, ( + f"implementation raised {actual.exception!r}, oracle returned {expected.value!r}" + ) + assert_ulp_close(actual.value, expected.value, maxulp=maxulp) + for i, (a, d) in enumerate(zip(actual.args, expected.args)): + if isinstance(a, np.ndarray): + try: + assert_ulp_close(a, d, maxulp=maxulp) + except AssertionError as e: + raise AssertionError( + f"argument {i} differs after the call: {e}" + ) from None + + +def compare(impl_func, oracle_func, *args, maxulp=4, check_message=True, **kwargs): + """ + Call the implementation and the oracle on copies of ``args``, assert that their + outcomes agree (`assert_same_outcome`), and return the oracle's `Outcome`. + """ + expected = outcome(oracle_func, *args, **kwargs) + actual = outcome(impl_func, *args, **kwargs) + assert_same_outcome(actual, expected, maxulp=maxulp, check_message=check_message) + return expected + + +def kind(result): + """ + Classify an `Outcome`: the exception class if it raised, ``None`` if it returned + ``None`` (an in-place update), else ``"nan"`` if any returned value is NaN, + ``"finite"`` if all are finite, otherwise ``"nonfinite"``. + """ + if result.exception is not None: + return type(result.exception) + if result.value is None: + return None + values = [leaf for _, leaf in _flatten(result.value)] + values = np.concatenate([v.ravel() for v in values]) if values else [] + if np.isnan(values).any(): + return "nan" + return "finite" if np.isfinite(values).all() else "nonfinite" + + +def assert_outcome(impl_func, oracle_func, args, expected_kind, **kwargs): + """`compare`, then assert the `kind` of the outcome (for edge-case tables).""" + result = compare(impl_func, oracle_func, *args, **kwargs) + assert kind(result) == expected_kind, f"{args}: {result!r}" + return result + + +def both(impl_func, oracle_func, *args, maxulp=4): + """ + `compare`, returning the oracle's value; if both raise, re-raise the oracle's + exception (for use with ``pytest.raises``). + """ + result = compare(impl_func, oracle_func, *args, maxulp=maxulp) + if result.exception is not None: + raise result.exception + return result.value + + +def make_ts(nodes, edges, mutations, length, num_individuals=0): + """ + Tree sequence from ``nodes`` ``(is_sample, time)`` or ``(is_sample, time, + individual)``, ``edges`` ``(left, right, parent, child)`` and ``mutations`` + ``(position, node)``, with ``num_individuals`` empty individuals. + """ + tables = tskit.TableCollection(length) + for _ in range(num_individuals): + tables.individuals.add_row() + for is_sample, time, *individual in nodes: + tables.nodes.add_row( + flags=int(is_sample), + time=time, + individual=individual[0] if individual else -1, + ) + for left, right, parent, child in edges: + tables.edges.add_row(left, right, parent, child) + for i, (position, node) in enumerate(mutations): + tables.sites.add_row(position, "0") + tables.mutations.add_row(i, node, "1") + tables.sort() + return tables.tree_sequence() + + +def i32(*x): + return np.array(x, dtype=np.int32) + + +def f64(*x): + return np.array(x, dtype=np.float64) + + +def b1(*x): + return np.array(x, dtype=bool) + + +def shrink(args, index, size): + """Copy of the argument list with ``args[index]`` truncated to ``size``.""" + args = list(args) + args[index] = args[index][:size] + return args diff --git a/tests/oracle/hypergeo.py b/tests/oracle/hypergeo.py new file mode 100644 index 00000000..9b494def --- /dev/null +++ b/tests/oracle/hypergeo.py @@ -0,0 +1,308 @@ +"""Oracles for the jitted functions in ``tsdate.hypergeo``.""" + +from math import pi + +import numpy as np +import scipy.special + +# oracle: plain `math` raises on log(0), exp overflow etc., where compiled numba +# follows C (-inf, inf, nan); `_libm` restores the C results. +# oracle: numba computes `x ** n` for integer constants `n` by repeated squaring, +# whereas CPython calls libm pow, which differs by an ulp in a few percent of cases; +# `ipow` does what numba does (see `_libm.ipow`). Changed lines are marked. +# oracle: NumPy ufuncs on Python floats return `np.float64`, so a following division +# by zero (e.g. `pi / tan(0)`) gives inf with a warning where numba, following Python +# semantics, raises ZeroDivisionError; and NumPy's SIMD loops may differ from libm. +# `np.log`, `np.tan`, `np.sin` and `np.power` are replaced by their `_libm` versions +# (libm functions on Python floats); numba lowers `np.power(x, k)` to libm `pow`. +from ._libm import erf, exp, ipow, lgamma, log, pow, sin, sqrt, tan # noqa: A004 + + +# oracle: the numba version is a `numba.cfunc` wrapping SciPy's Cython gammaincinv +# (which is `scipy.special.gammaincinv`); here we call that directly. The ufunc returns +# an `np.float64`, which is converted so that callers divide by it with Python +# semantics (ZeroDivisionError), as in numba. +def _gammainc_inv(a, x): + """scipy.special.cython_special.gammaincinv""" + return float(scipy.special.gammaincinv(a, x)) + + +def _digamma(x): + """ + Digamma (psi) function, from asymptotic series expansion. + """ + if x <= 0.0: + return _digamma(1 - x) - np.pi / tan(np.pi * x) + if x <= 1e-5: + return -np.euler_gamma - (1 / x) + if x < 8.5: + return _digamma(1 + x) - 1 / x + xpm2 = 1 / ipow(x, 2) # oracle: ipow + return ( + log(x) + - 0.5 / x + - 0.083333333333333333 * xpm2 + + 0.008333333333333333 * ipow(xpm2, 2) # oracle: ipow + - 0.003968253968253968 * ipow(xpm2, 3) # oracle: ipow + + 0.004166666666666667 * ipow(xpm2, 4) # oracle: ipow + - 0.007575757575757576 * ipow(xpm2, 5) # oracle: ipow + + 0.021092796092796094 * ipow(xpm2, 6) # oracle: ipow + ) + + +def _trigamma(x): + """ + Trigamma function, from asymptotic series expansion + """ + if x <= 0.0: + return -_trigamma(1 - x) + ipow(np.pi, 2) / ipow( + sin(np.pi * x), 2 + ) # oracle: ipow + if x <= 1e-4: + return 1 / ipow(x, 2) # oracle: ipow + if x < 5: + return _trigamma(1 + x) + 1 / ipow(x, 2) # oracle: ipow + xpm1 = 1 / x + xpm2 = 1 / ipow(x, 2) # oracle: ipow + return xpm1 * ( + 1.000000000000000000 + + 0.500000000000000000 * xpm1 + + 0.166666666666666667 * pow(xpm2, 1) + - 0.033333333333333333 * pow(xpm2, 2) + + 0.023809523809523808 * pow(xpm2, 3) + - 0.033333333333333333 * pow(xpm2, 4) + + 0.075757575757575756 * pow(xpm2, 5) + - 0.253113553113553102 * pow(xpm2, 6) + + 1.166666666666666741 * pow(xpm2, 7) + ) + + +def _betaln(p, q): + return lgamma(p) + lgamma(q) - lgamma(p + q) + + +def _hyperu_laplace(a, b, x): + """ + Approximate Tricomi's confluent hypergeometric function with real + arguments, using Laplace's method with a calibration point. + + Also returns derivative wrt x. + + TODO: details + """ + + assert b >= a > 0.0 + assert x > 0.0 + + t = b - x - 1 + u = 2 * a / (sqrt(ipow(t, 2) + 4 * x * a) - t) # oracle: ipow + r = (b - a - 1) * ipow(u, 2) + a * ipow(1 + u, 2) # oracle: ipow + g = (b - a) * log(1 + u) + a * (1 + log(u)) - x * u - log(a) * (a - 1 / 2) + + w = (b - 1) * u + a + v = u * (1 + u) + dr = w / (w * u + a * (1 + u)) + dg = (w - x * v + u) / v + du = -u * v / (w - x * u + a) + + return g - log(r) / 2, (dg - dr) * du - u + + +def _hyp1f1_laplace(a, b, x): + """ + Approximate Kummer's confluent hypergeometric function with real arguments, + using Laplace's method with a calibration point. + + TODO: details + """ + + assert b > a > 0.0 + + if x == 0.0: + return 0.0 + + t = x - b + u = 2 * a / (sqrt(ipow(t, 2) + 4 * x * a) - t) # oracle: ipow + r = ipow(u, 2) * b / a + ipow(1 - u, 2) * b / (b - a) # oracle: ipow + g = ( + (b - a) * log(1 - u) + + a * log(u) + + b * log(b) + - (b - a) * log(b - a) + - a * log(a) + + x * u + ) + + return g - log(r) / 2 + + +def _hyp2f1_laplace(a, b, c, x): + r""" + Approximate a Gaussian hypergeometric function with real arguments, + using Laplace's method with a calibration point. + + TODO: details + """ + + def _hyp2f1_unity(a, b, c, x): + """ + Gauss hypergeometric function when `x` is near unity + + See limits in DLMF 15.4. + + TODO: this works in practice, but when (c - a - b) is close to zero the + limits don't converge. A good reference is Buhring 2003 "Partial sums of + hypergeometric series of unit argument" + """ + assert np.isclose(x, 1.0) + assert x < 1.0 + + g = c - a - b + + if g < 0.0: + return lgamma(c) + lgamma(-g) - lgamma(a) - lgamma(b) + g * log(1 - x) + elif g > 0.0: + # will only occur when a_i + a_j < 1 + return lgamma(c) + lgamma(g) - lgamma(c - a) - lgamma(c - b) + else: + # will only occur when a_i + a_j == 1 + return log(-log(1 - x)) + lgamma(a + b) - lgamma(a) - lgamma(b) + + # TODO: simplify, we can safely assume a,b > 0? + assert c > 0.0 + assert a >= 0.0 + assert b >= 0.0 + assert c >= a + assert x < 1.0 + + if x == 0.0: + return 0.0 + + s = 0.0 + if x < 0.0: + s = -b * log(1 - x) + a = c - a + x = x / (x - 1) + + if np.isclose(x, 1.0): + return s + _hyp2f1_unity(a, b, c, x) + + t = x * (b - a) - c + u = sqrt(ipow(t, 2) - 4 * a * x * (c - b)) - t # oracle: ipow + y = 2 * a / u + + assert 0 < y < 1, "Root on boundary" + + yy = ipow(y, 2) / a # oracle: ipow + my = ipow(1 - y, 2) / (c - a) # oracle: ipow + ymy = ipow(x, 2) * b * yy * my / ipow(1 - x * y, 2) # oracle: ipow + r = yy + my - ymy + f = ( + (c - 1 / 2) * log(c) + + a * (log(y) - log(a)) + + (c - a) * (log(1 - y) - log(c - a)) + - b * log(1 - x * y) + ) + + return f - log(r) / 2 + s + + +def _gammainc_der(p, x): + """ + Derivative of lower incomplete gamma function with regards to `p`. + + Based on Shea B (1988) "Algorithm AS 239" Applied Statistics 37: 466-473 + + Adapted from https://people.math.sc.edu/Burkardt/cpp_src/asa239/asa239.cpp + """ + + elimit = -88.0 + oflo = 1.0e37 + plimit = 1.0e3 + tol = 1.0e-14 + xbig = 1.0e8 + + assert x >= 0.0 + assert p > 0.0 + + if x == 0: + value, grad = 0.0, 0.0 + return grad + + if x > xbig: + value, grad = 1.0, 0.0 + return grad + + if p > plimit: # gaussian approximation + pn1 = 3 * sqrt(p) * (pow(x / p, 1 / 3) + 1 / (9 * p) - 1) + grad = pn1 / (2 * p) - 1 / sqrt(p) * (pow(x / p, 1 / 3) + 1 / (3 * p)) + grad *= 1 / sqrt(2 * pi) * exp(-(ipow(pn1, 2)) / 2) # oracle: ipow + value = (1 + erf(pn1 / sqrt(2))) / 2 + return grad + + if x <= 1 or x < p: # series expansion + arg = p * log(x) - x - lgamma(p + 1) + value, grad = 1.0, 0.0 + c, dc = 1.0, 0.0 + a = p + while True: + a += 1.0 + dc = -c * x / ipow(a, 2) + dc * x / a # oracle: ipow + c *= x / a + value += c + grad += dc + if c <= tol: + break + darg = exp(arg) * (log(x) - _digamma(p + 1)) + grad = grad * exp(arg) + value * darg + arg += log(value) + if arg >= elimit: + value = exp(arg) + else: + grad = 0.0 + value = 0.0 + return grad + else: # continued fraction + arg = p * log(x) - x - lgamma(p) + a = 1.0 - p + b = a + x + 1.0 + c = 0.0 + pn1, pn2, pn3, pn4 = 1.0, x, x + 1.0, x * b + dpn1, dpn2, dpn3, dpn4 = 0.0, 0.0, 0.0, -x + value, grad = pn3 / pn4, 0.0 + while True: + a += 1.0 + b += 2.0 + c += 1.0 + an = a * c + pn5 = b * pn3 - an * pn1 + pn6 = b * pn4 - an * pn2 + dpn5 = b * dpn3 - pn3 - an * dpn1 + c * pn1 + dpn6 = b * dpn4 - pn4 - an * dpn2 + c * pn2 + if pn6 != 0.0: + rn = pn5 / pn6 + grad = (dpn5 * pn6 - pn5 * dpn6) / ipow(pn6, 2) # oracle: ipow + if abs(value - rn) <= min(tol, tol * rn): + break + value = rn + pn1, pn2, pn3, pn4 = pn3, pn4, pn5, pn6 + dpn1, dpn2, dpn3, dpn4 = dpn3, dpn4, dpn5, dpn6 + if oflo <= abs(pn5): + pn1 /= oflo + pn2 /= oflo + pn3 /= oflo + pn4 /= oflo + dpn1 /= oflo + dpn2 /= oflo + dpn3 /= oflo + dpn4 /= oflo + darg = exp(arg) * (log(x) - _digamma(p)) + grad = grad * exp(arg) + value * darg + arg += log(value) + if arg >= elimit: + grad *= -1.0 + value = 1.0 - exp(arg) + else: + grad = 0.0 + value = 1.0 + return grad diff --git a/tests/oracle/implementations.py b/tests/oracle/implementations.py new file mode 100644 index 00000000..66e90e82 --- /dev/null +++ b/tests/oracle/implementations.py @@ -0,0 +1,75 @@ +""" +Registry of implementations to test against the oracles. + +``IMPLEMENTATIONS`` maps a name to a namespace with one attribute per tsdate module +(``hypergeo``, ``approx``, ``variational``, ``rescaling``, ``phasing``, ``util``, +``prior``, ``discrete``), exposing the jitted functions under the same names and +signatures as the oracle modules. To add the C extension, add an entry here; to +drop numba, delete the "numba" entry. +""" + +import types + +import tsdate.approx +import tsdate.hypergeo +import tsdate.phasing +import tsdate.prior +import tsdate.rescaling +import tsdate.util +import tsdate.variational +from tsdate.discrete import LogLikelihoods + +_EP = tsdate.variational.ExpectationPropagation + +# Functions that are staticmethods of ExpectationPropagation, exposed as plain names. +_EP_STATIC = ( + "_check_valid_constraints", + "propagate_likelihood", + "propagate_prior", + "propagate_mutations", +) + + +def _numba_variational(): + """ + Namespace with ``EPFactors`` and the module-level helpers of + ``tsdate.variational`` plus the jitted staticmethods of + ``ExpectationPropagation`` as module-level names. Accessing a staticmethod on + the class returns the underlying dispatcher. + """ + ns = types.SimpleNamespace( + EPFactors=tsdate.variational.EPFactors, + _rescale_factors=tsdate.variational._rescale_factors, + _assemble_factors=tsdate.variational._assemble_factors, + _damp=tsdate.variational._damp, + _rescale=tsdate.variational._rescale, + ) + for name in _EP_STATIC: + setattr(ns, name, getattr(_EP, name)) + return ns + + +def _numba_discrete(): + """ + ``logsumexp`` is a jitted staticmethod of ``LogLikelihoods``; accessing it on + the class gives a callable ``logsumexp(X)``, so it is exposed under that name. + """ + return types.SimpleNamespace(logsumexp=LogLikelihoods.logsumexp) + + +def _numba_namespace(): + return types.SimpleNamespace( + hypergeo=tsdate.hypergeo, + approx=tsdate.approx, + variational=_numba_variational(), + rescaling=tsdate.rescaling, + phasing=tsdate.phasing, + util=tsdate.util, + prior=tsdate.prior, + discrete=_numba_discrete(), + ) + + +IMPLEMENTATIONS: dict[str, types.SimpleNamespace] = { + "numba": _numba_namespace(), +} diff --git a/tests/oracle/phasing.py b/tests/oracle/phasing.py new file mode 100644 index 00000000..f1957cb9 --- /dev/null +++ b/tests/oracle/phasing.py @@ -0,0 +1,217 @@ +"""Oracles for the jitted functions in ``tsdate.phasing``.""" + +import numpy as np +import tskit + + +def reallocate_unphased(edges_likelihood, mutations_phase, mutations_block, blocks_edges): + """ + Add a proportion of each unphased singleton mutation to one of the two + edges to which it maps + """ + assert mutations_phase.size == mutations_block.size + assert blocks_edges.shape[1] == 2 + + num_edges = edges_likelihood.shape[0] + edges_unphased = np.full(num_edges, False) + edges_unphased[blocks_edges[:, 0]] = True + edges_unphased[blocks_edges[:, 1]] = True + + num_unphased = np.sum(edges_likelihood[edges_unphased, 0]) + edges_likelihood[edges_unphased, 0] = 0.0 + for m, b in enumerate(mutations_block): + if b == tskit.NULL: + continue + i, j = blocks_edges[b] + assert tskit.NULL < i < num_edges + assert edges_unphased[i] + assert tskit.NULL < j < num_edges + assert edges_unphased[j] + if np.isnan(mutations_phase[m]): # TODO: fix rare numerical issue + continue + assert 0.0 <= mutations_phase[m] <= 1.0 + edges_likelihood[i, 0] += mutations_phase[m] + edges_likelihood[j, 0] += 1 - mutations_phase[m] + assert np.isclose(num_unphased, np.sum(edges_likelihood[edges_unphased, 0])) + + +def _block_singletons( + individuals_unphased, + nodes_individual, + mutations_node, + mutations_position, + edges_parent, + edges_child, + edges_left, + edges_right, + indexes_insert, + indexes_remove, + sequence_length, +): + """ + TODO + """ + assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size + assert indexes_insert.size == indexes_remove.size == edges_parent.size + assert mutations_node.size == mutations_position.size + + num_mutations = mutations_node.size + num_edges = edges_parent.size + num_individuals = individuals_unphased.size + + indexes_mutation = np.argsort(mutations_position) + position_insert = edges_left[indexes_insert] + position_remove = edges_right[indexes_remove] + position_mutation = mutations_position[indexes_mutation] + + individuals_edges = np.full((num_individuals, 2), tskit.NULL) + individuals_position = np.full(num_individuals, np.nan) + individuals_singletons = np.zeros(num_individuals) + individuals_block = np.full(num_edges, tskit.NULL) + mutations_block = np.full(num_mutations, tskit.NULL) + + blocks_span = [] + blocks_singletons = [] + blocks_edges = [] + blocks_order = [] + + num_blocks = 0 + left = 0.0 + a, b, d = 0, 0, 0 + while a < num_edges or b < num_edges: + while b < num_edges and position_remove[b] == left: # edges out + e = indexes_remove[b] + c = edges_child[e] + i = nodes_individual[c] + if i != tskit.NULL and individuals_unphased[i]: + u, v = individuals_edges[i] + assert u == e or v == e + s = u if v == e else v + individuals_edges[i] = s, tskit.NULL + if s != tskit.NULL: # flush block + blocks_order.append(individuals_block[i]) + blocks_edges.extend([e, s]) + blocks_singletons.append(individuals_singletons[i]) + blocks_span.append(left - individuals_position[i]) + individuals_position[i] = np.nan + individuals_block[i] = tskit.NULL + individuals_singletons[i] = 0.0 + b += 1 + + while a < num_edges and position_insert[a] == left: # edges in + e = indexes_insert[a] + c = edges_child[e] + i = nodes_individual[c] + if i != tskit.NULL and individuals_unphased[i]: + u, v = individuals_edges[i] + assert u == tskit.NULL or v == tskit.NULL + individuals_edges[i] = [e, max(u, v)] + individuals_position[i] = left + if individuals_block[i] == tskit.NULL: + individuals_block[i] = num_blocks + num_blocks += 1 + a += 1 + + right = sequence_length + if b < num_edges: + right = min(right, position_remove[b]) + if a < num_edges: + right = min(right, position_insert[a]) + left = right + + while d < num_mutations and position_mutation[d] < right: # mutations + m = indexes_mutation[d] + c = mutations_node[m] + i = nodes_individual[c] + if i != tskit.NULL and individuals_unphased[i]: + mutations_block[m] = individuals_block[i] + individuals_singletons[i] += 1.0 + d += 1 + + mutations_block = mutations_block.astype(np.int32) + blocks_edges = np.array(blocks_edges, dtype=np.int32).reshape(-1, 2) + blocks_singletons = np.array(blocks_singletons) + blocks_span = np.array(blocks_span) + blocks_order = np.array(blocks_order) + blocks_stats = np.column_stack((blocks_singletons, blocks_span)) + assert num_blocks == blocks_edges.shape[0] == blocks_stats.shape[0] + + # sort block arrays so that mutations_block points to correct row + blocks_order = np.argsort(blocks_order) + blocks_edges = blocks_edges[blocks_order] + blocks_stats = blocks_stats[blocks_order] + + return blocks_stats, blocks_edges, mutations_block + + +def _mutation_frequency( + nodes_sample, + mutations_node, + mutations_position, + edges_parent, + edges_child, + edges_left, + edges_right, + indexes_insert, + indexes_remove, + sequence_length, +): + """ + TODO + """ + assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size + assert indexes_insert.size == indexes_remove.size == edges_parent.size + assert mutations_node.size == mutations_position.size + + num_nodes, num_sample_sets = nodes_sample.shape + num_mutations = mutations_node.size + num_edges = edges_parent.size + + indexes_mutation = np.argsort(mutations_position) + position_insert = edges_left[indexes_insert] + position_remove = edges_right[indexes_remove] + position_mutation = mutations_position[indexes_mutation] + + nodes_parent = np.full(num_nodes, tskit.NULL) + nodes_samples = np.zeros((num_nodes, num_sample_sets), dtype=np.int32) + mutations_freq = np.zeros((num_mutations, num_sample_sets), dtype=np.int32) + + # TODO: there's a better way than passing a big bool array + for i in range(num_sample_sets): + nodes_samples[nodes_sample[:, i], i] = 1.0 + + left = 0.0 + a, b, d = 0, 0, 0 + while a < num_edges or b < num_edges: + while b < num_edges and position_remove[b] == left: # edges out + e = indexes_remove[b] + p, c = edges_parent[e], edges_child[e] + nodes_parent[c] = tskit.NULL + while p != tskit.NULL: + nodes_samples[p] -= nodes_samples[c] + p = nodes_parent[p] + b += 1 + + while a < num_edges and position_insert[a] == left: # edges in + e = indexes_insert[a] + p, c = edges_parent[e], edges_child[e] + nodes_parent[c] = p + while p != tskit.NULL: + nodes_samples[p] += nodes_samples[c] + p = nodes_parent[p] + a += 1 + + right = sequence_length + if b < num_edges: + right = min(right, position_remove[b]) + if a < num_edges: + right = min(right, position_insert[a]) + left = right + + while d < num_mutations and position_mutation[d] < right: + m = indexes_mutation[d] + c = mutations_node[m] + mutations_freq[m] = nodes_samples[c] + d += 1 + + return mutations_freq diff --git a/tests/oracle/prior.py b/tests/oracle/prior.py new file mode 100644 index 00000000..a666c7d1 --- /dev/null +++ b/tests/oracle/prior.py @@ -0,0 +1,55 @@ +"""Oracles for the jitted functions in ``tsdate.prior``.""" + +import numpy as np + + +def _marginalize_over_ancestors(val): + """ + Integrate an expectation over counts of extant ancestors. In a tree with + "n" tips, the probability that there are "a" extent ancestors when a + subtree of size "k" coalesces is hypergeometric-ish (Wuif & Donnelly 1998), + and may be calculated recursively over increasing "a" and decreasing "k" + (e.g. using recursive relationships for binomial coefficients). + """ + n, N = val.shape # number of tips, number of moments + pr_a_ln = [np.nan, np.nan, 0.0] # log Pr(a | k, n) + out = np.zeros((n + 1, N)) + for k in range(n - 1, 1, -1): + # oracle: `np.log(0)` at k == 2 warns (divide by zero) here; numba is silent + # and the value is unused for k == 2, so suppress the warning locally. + with np.errstate(divide="ignore"): + const = np.log(n - k) + np.log(k - 2) - np.log(k + 1) + for a in range(2, n - k + 2): + out[k] += np.exp(pr_a_ln[a]) * val[a] + if k > 2: # Pr(a | k, n) to Pr(a | k - 1, n) + pr_a_ln[a] += const - np.log(n - a - k + 2) + if k > 2: # Pr(n - k + 1 | k - 1, n) to Pr(n - k + 2 | k - 1, n) + pr_a_ln.append(pr_a_ln[-1] + np.log(n - k + 2) - np.log(k + 1) - const) + out[n] = val[1] + return out + + +def conditional_coalescent_variance(num_tips): + """ + Variance of node age conditional on the number of descendant leaves, under + the standard coalescent. Returns array indexed by number of descendant + leaves. + """ + + coal_rates = np.array( + [2 / (i * (i - 1)) if i > 1 else 0.0 for i in range(1, num_tips + 1)] + ) + + # hypoexponential mean and variance; e.g. conditional on the number of + # extant ancestors when the node coalesces, the expected time of + # coalescence is the sum of exponential RVs (Wuif and Donnelly 1998) + mean = coal_rates.copy() + variance = coal_rates.copy() ** 2 + for i in range(coal_rates.size - 2, 0, -1): + mean[i] += mean[i + 1] + variance[i] += variance[i + 1] + + # marginalize over number of ancestors using recursive algorithm + moments = _marginalize_over_ancestors(np.stack((mean, variance + mean**2), 1)) + + return moments[:, 1] - moments[:, 0] ** 2 diff --git a/tests/oracle/rescaling.py b/tests/oracle/rescaling.py new file mode 100644 index 00000000..497309a1 --- /dev/null +++ b/tests/oracle/rescaling.py @@ -0,0 +1,390 @@ +"""Oracles for the jitted functions in ``tsdate.rescaling``.""" + +from math import inf + +import numpy as np +import tskit + +# oracle: plain `math.log` raises on 0, where compiled numba gives -inf; numba's +# np.sum accumulates sequentially, whereas numpy sums pairwise (`seq_sum`). +from ._libm import log, seq_sum +from .approx import approximate_gamma_iqr +from .hypergeo import _gammainc_inv as gammainc_inv + + +def _fixed_changepoints(counts, epochs): + """ + Find breakpoints such that `counts` is divided roughly equally across `epochs` + """ + assert epochs > 0 + Y = np.append(0.0, np.cumsum(counts)) + Z = Y / Y[-1] + z = np.linspace(0, 1, epochs + 1) + e = np.searchsorted(Z, z, "right") - 1 + if e[0] > 0: + e[0] = 0 + if e[-1] < counts.size: + e[-1] = counts.size + return e.astype(np.int32) + + +def _poisson_changepoints(counts, offset, penalty, min_counts, min_offset): + """ + Given Poisson counts and offsets for a sequence of observations, find the set + of changepoints for the Poisson rate that maximizes the profile likelihood + under a linear penalty on complexity (e.g. penalty == 2 is AIC). + + See: "Optimal detection of changepoints with a linear computation cost" + (https://doi.org/10.1080/01621459.2012.737745) + """ + + assert counts.size == offset.size + assert min_counts >= 0 + assert min_offset >= 0 + assert penalty >= 0 + + N = np.append(0, np.cumsum(offset)) + Y = np.append(0, np.cumsum(counts)) + + def f(i, j): # loss + n = N[j] - N[i] + y = Y[j] - Y[i] + s = n < min_offset or y < min_counts + return inf if s else -2 * y * (log(y) - log(n) - 1) + + dim = counts.size + cost = np.empty(dim) + F = np.empty(dim + 1) + C = {0: np.empty(0, dtype=np.int64)} + + F[0] = -penalty + for j in np.arange(1, dim + 1): + argmin, minval = 0, np.inf + for i in C: # minimize + cost[i] = F[i] + f(i, j) + penalty + if cost[i] < minval: + minval = cost[i] + argmin = i + F[j] = minval + for i in set(C): # prune + if cost[i] > F[j] + penalty: + C.pop(i) + C[j] = np.append(C[argmin], argmin) + + breaks = np.append(C[dim], dim).astype(np.int32) + return breaks + + +def _count_mutations( + node_is_sample, + mutations_node, + mutations_position, + edges_parent, + edges_child, + edges_left, + edges_right, + indexes_insert, + indexes_remove, + sequence_length, + size_biased, +): + assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size + assert indexes_insert.size == indexes_remove.size == edges_parent.size + assert mutations_node.size == mutations_position.size + + num_mutations = mutations_node.size + num_edges = edges_parent.size + num_nodes = node_is_sample.size + + indexes_mutation = np.argsort(mutations_position) + position_insert = edges_left[indexes_insert] + position_remove = edges_right[indexes_remove] + position_mutation = mutations_position[indexes_mutation] + + nodes_samples = np.zeros(num_nodes) + nodes_edge = np.full(num_nodes, tskit.NULL) + nodes_parent = np.full(num_nodes, tskit.NULL) + mutations_edge = np.full(num_mutations, tskit.NULL) + edges_mutations = np.zeros(num_edges) + edges_span = np.zeros(num_edges) + + nodes_samples[node_is_sample] = 1.0 + left = 0.0 + a, b, d = 0, 0, 0 + while a < num_edges or b < num_edges: + remainder = sequence_length - left + + while b < num_edges and position_remove[b] == left: # edges out + e = indexes_remove[b] + p, c = edges_parent[e], edges_child[e] + nodes_edge[c] = tskit.NULL + nodes_parent[c] = tskit.NULL + if size_biased: + while p != tskit.NULL: # downdate sample counts + edges_span[e] -= nodes_samples[c] * remainder + nodes_samples[p] -= nodes_samples[c] + e, p = nodes_edge[p], nodes_parent[p] + else: + edges_span[e] -= remainder + b += 1 + + while a < num_edges and position_insert[a] == left: # edges in + e = indexes_insert[a] + p, c = edges_parent[e], edges_child[e] + nodes_edge[c] = e + nodes_parent[c] = p + if size_biased: + while p != tskit.NULL: # update sample counts + edges_span[e] += nodes_samples[c] * remainder + nodes_samples[p] += nodes_samples[c] + e, p = nodes_edge[p], nodes_parent[p] + else: + edges_span[e] += remainder + a += 1 + + right = sequence_length + if b < num_edges: + right = min(right, position_remove[b]) + if a < num_edges: + right = min(right, position_insert[a]) + left = right + + while d < num_mutations and position_mutation[d] < right: + m = indexes_mutation[d] + c = mutations_node[m] + e = nodes_edge[c] + if e != tskit.NULL: + mutations_edge[m] = e + edges_mutations[e] += nodes_samples[c] if size_biased else 1.0 + d += 1 + + mutations_edge = mutations_edge.astype(np.int32) + edges_stats = np.column_stack((edges_mutations, edges_span)) + + return edges_stats, mutations_edge + + +def mutational_area( + nodes_time, + likelihoods, + edges_parent, + edges_child, +): + """ + Calculate the total number of mutations and mutational area per inter-node + interval. These are infinitesimal; e.g. the actual count in an interval is + `returned_count * duration`. + + :param np.ndarray nodes_time: point estimates for node ages + :param np.ndarray likelihoods: edges are rows; mutation + counts and mutational span are columns + :param np.ndarray edges_parent: node index for the parent of each edge + :param np.ndarray edges_child: node index for the child of each edge + :param np.ndarray edges_weight: a weight for each edge + """ + + assert edges_parent.size == edges_child.size + assert likelihoods.shape == (edges_parent.size, 2) + + # index node by unique time breaks + nodes_order = np.argsort(nodes_time) + nodes_index = np.zeros(nodes_time.size, dtype=np.int32) + epoch_breaks = [0.0] + k = 0 + for i, j in zip(nodes_order[1:], nodes_order[:-1]): + if nodes_time[i] > nodes_time[j]: + epoch_breaks.append(nodes_time[i]) + k += 1 + nodes_index[i] = k + epoch_breaks = np.array(epoch_breaks) + num_epochs = epoch_breaks.size - 1 + + # instantaneous mutation rate per edge + edges_length = nodes_time[edges_parent] - nodes_time[edges_child] + edges_subset = edges_length > 0 + edges_counts = likelihoods.copy() + edges_counts[edges_subset, 0] /= edges_length[edges_subset] + + # pass over edges, measuring overlap with each time interval + epoch_counts = np.zeros((num_epochs, 2)) + for e in np.flatnonzero(edges_subset): + p, c = edges_parent[e], edges_child[e] + a, b = nodes_index[c], nodes_index[p] + if a < num_epochs: + epoch_counts[a] += edges_counts[e] + if b < num_epochs: + epoch_counts[b] -= edges_counts[e] + counts = np.cumsum(epoch_counts[:, 0]) + offset = np.cumsum(epoch_counts[:, 1]) + duration = np.diff(epoch_breaks) + + return counts, offset, duration, nodes_index + + +def mutational_timescale( + nodes_time, + likelihoods, + nodes_fixed, + edges_parent, + edges_child, + max_intervals, +): + """ + Rescale node ages so that the instantaneous mutation rate is constant. + Edges with a negative duration are ignored when calculating the total + rate. Returns a rescaled point estimate and the posterior. + + :param np.ndarray nodes_time: point estimates for node ages + :param np.ndarray likelihoods: edges are rows; mutation + counts and mutational span are columns + :param np.ndarray constraints: lower and upper bounds on node age + :param np.ndarray edges_parent: node index for the parent of each edge + :param np.ndarray edges_child: node index for the child of each edge + :param int max_intervals: maximum number of intervals within which to + estimate the time scaling + """ + + assert edges_parent.size == edges_child.size + assert likelihoods.shape[0] == edges_parent.size + assert likelihoods.shape[1] == 2 + assert nodes_fixed.size == nodes_time.size + assert max_intervals > 0 + + counts, offset, duration, indexes = mutational_area( + nodes_time, + likelihoods, + edges_parent, + edges_child, + ) + + # rescale time such that mutation density is constant between changepoints + # TODO: use poisson changepoints to further refine + epoch_breaks = np.append(0.0, np.cumsum(duration)) + changepoints = _fixed_changepoints(offset * duration, max_intervals) + changepoints = np.unique(changepoints) + # changepoints = np.union1d(changepoints, indexes[nodes_fixed]) + adjust = np.zeros(changepoints.size) + + # --- without any internal constraints --- + k = 0 + for i, j in zip(changepoints[:-1], changepoints[1:]): + assert j > i + # TODO: when changepoint intersects a fixed node? + n = seq_sum(offset[i:j]) # oracle: seq_sum + y = seq_sum(counts[i:j]) # oracle: seq_sum + z = seq_sum(duration[i:j]) # oracle: seq_sum + assert n > 0, "Zero edge span in interval" + adjust[k + 1] = z * y / n + k += 1 + + adjust = np.cumsum(adjust) + origin = epoch_breaks[changepoints] + + return origin, adjust + + +def piecewise_scale_posterior( + posteriors, + posteriors_fixed, + original_breaks, + rescaled_breaks, + quantile_width, + max_shape, +): + """ + :param np.ndarray posteriors_fixed: if True do not rescale corresponding posterior + :param float quantile_width: width of interquantile range to use for estimating + rescaled shape parameter, e.g. 0.5 uses interquartile range + """ + + assert posteriors_fixed.size == posteriors.shape[0] + assert original_breaks.size == rescaled_breaks.size + assert 1 > quantile_width > 0 + + if not np.all(np.diff(rescaled_breaks) > 0): + raise ValueError( + "Rescaling produced non-increasing time breakpoints. " + "Try setting `rescaling_intervals` to a smaller value " + "(e.g. half its current value)." + ) + if not np.all(np.diff(original_breaks) > 0): + raise ValueError( + "Rescaling produced non-increasing time breakpoints. " + "Try setting `rescaling_intervals` to a smaller value " + "(e.g. half its current value)." + ) + + dim = posteriors.shape[0] + quant_lower = quantile_width / 2 + quant_upper = 1 - quantile_width / 2 + + freed = ~posteriors_fixed + assert np.all(np.logical_and(posteriors[freed, 0] > -1, posteriors[freed, 1] > 0)) + + # use posterior mean as a point estimate + lower = np.zeros(dim) + upper = np.zeros(dim) + midpt = np.zeros(dim) + for i in np.flatnonzero(freed): + alpha, beta = posteriors[i] + lower[i] = gammainc_inv(alpha + 1, quant_lower) / beta + upper[i] = gammainc_inv(alpha + 1, quant_upper) / beta + midpt[i] = (alpha + 1) / beta + + # rescale quantiles + scalings = np.append(np.diff(rescaled_breaks) / np.diff(original_breaks), 0) + + def rescale(x): + i = np.searchsorted(original_breaks, x, "right") - 1 + assert i.min() >= 0 # DEBUG + assert i.max() < scalings.size # DEBUG + return rescaled_breaks[i] + scalings[i] * (x - original_breaks[i]) + + midpt = rescale(midpt) + lower = rescale(lower) + upper = rescale(upper) + + # reproject posteriors using inter-quantile range + new_posteriors = np.full(posteriors.shape, np.nan) + for i in np.flatnonzero(freed): + # oracle: in numba, a float division by zero raises `ZeroDivisionError`, + # where numpy scalars give inf. `approximate_gamma_iqr` divides by its `x1` + # argument (`x2 / x1`, or `... / x` in `upper_bound`) in every branch that + # doesn't raise earlier, so a zero lower quantile raises there. + if lower[i] == 0.0: + raise ZeroDivisionError("division by zero") + alpha, beta = approximate_gamma_iqr( + quant_lower, quant_upper, lower[i], upper[i], max_shape + ) + if midpt[i] == 0.0: # oracle: as above, numba raises + raise ZeroDivisionError("division by zero") + beta = (alpha + 1) / midpt[i] # choose rate so as to keep mean + new_posteriors[i] = alpha, beta + + return new_posteriors + + +def piecewise_scale_point_estimate( + point_estimate, + point_fixed, + original_breaks, + rescaled_breaks, +): + if not np.all(np.diff(rescaled_breaks) > 0): + raise ValueError( + "Rescaling produced non-increasing time breakpoints. " + "Try setting `rescaling_intervals` to a smaller value " + "(e.g. half its current value)." + ) + if not np.all(np.diff(original_breaks) > 0): + raise ValueError( + "Rescaling produced non-increasing time breakpoints. " + "Try setting `rescaling_intervals` to a smaller value " + "(e.g. half its current value)." + ) + scalings = np.append(np.diff(rescaled_breaks) / np.diff(original_breaks), 0) + idx = np.searchsorted(original_breaks, point_estimate, "right") - 1 + rescaled_estimate = rescaled_breaks[idx] + \ + scalings[idx] * (point_estimate - original_breaks[idx]) # fmt: skip + rescaled_estimate[point_fixed] = point_estimate[point_fixed] + return rescaled_estimate diff --git a/tests/oracle/util.py b/tests/oracle/util.py new file mode 100644 index 00000000..15e329cf --- /dev/null +++ b/tests/oracle/util.py @@ -0,0 +1,223 @@ +"""Oracles for the jitted functions in ``tsdate.util``.""" + +import numpy as np +import tskit + + +def _split_disjoint_nodes( + edges_parent, edges_child, edges_left, edges_right, node_excluded +): + """ + Split disconnected regions of nodes into separate nodes. + + Returns updated edges_parent, edges_child, mutations_node, and indices indicating + from which original node the new nodes are derived. + """ + assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size + num_edges = edges_parent.size + num_nodes = node_excluded.size + + # For each edge, check whether parent/child is separated by a gap from the + # previous edge involving either parent/child. Label disconnected segments + # per node by integers starting at zero. + edges_order = np.argsort(edges_left) + # TODO: is a sort really needed here? + edges_segments = np.full((2, num_edges), -1, dtype=np.int32) + nodes_segments = np.full(num_nodes, -1, dtype=np.int32) + nodes_right = np.full(node_excluded.size, -np.inf, dtype=np.float64) + for e in edges_order: + nodes = edges_parent[e], edges_child[e] + for i, n in enumerate(nodes): + if node_excluded[n]: + continue + nodes_segments[n] += edges_left[e] > nodes_right[n] + edges_segments[i, e] = nodes_segments[n] + nodes_right[n] = max(nodes_right[n], edges_right[e]) + + # Create "nodes_segments[i]" supplementary nodes by copying node "i". + # Store the id of the first supplement for each node in "nodes_map". + split_nodes = [] # the nodes in the original that were split + nodes_map = np.full(num_nodes, -1, dtype=np.int32) + for i, s in enumerate(nodes_segments): + for j in range(s): + if j == 0: + nodes_map[i] = num_nodes + split_nodes.append(i) + num_nodes += 1 + split_nodes = np.array(split_nodes, dtype=np.int32) + nodes_order = np.arange(num_nodes, dtype=np.int32) + if len(split_nodes) > 0: + nodes_order[-len(split_nodes) :] = split_nodes + + # Relabel the nodes on each edge given "nodes_map" + for e in edges_order: + nodes = edges_parent[e], edges_child[e] + for i, n in enumerate(nodes): + if edges_segments[i, e] > 0: + edges_segments[i, e] += nodes_map[n] - 1 + else: + edges_segments[i, e] = n + edges_parent, edges_child = edges_segments[0, ...], edges_segments[1, ...] + + return edges_parent, edges_child, nodes_order, split_nodes + + +def _relabel_mutations_node( + mutations_node, + mutations_position, + nodes_order, + edges_parent, + edges_child, + edges_left, + edges_right, + insert_index, + remove_index, +): + """ + Traverse trees, maintaining a mapping between old and new node IDs in the + current tree. Update `mutations_node` to reflect new IDs. + """ + assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size + assert edges_parent.size == insert_index.size == remove_index.size + assert mutations_position.size == mutations_node.size + + num_nodes = nodes_order.size + num_edges = edges_parent.size + num_mutations = mutations_position.size + + insert_position = edges_left[insert_index] + remove_position = edges_right[remove_index] + sequence_length = remove_position[-1] + + output = np.full(num_mutations, tskit.NULL, dtype=np.int32) + nodes_map = np.full(num_nodes, tskit.NULL, dtype=np.int32) + a, b, m = 0, 0, 0 + left = 0.0 + while left < sequence_length: + while b < num_edges and remove_position[b] == left: # edges out + b += 1 + + while a < num_edges and insert_position[a] == left: # edges in + e = insert_index[a] + c, p = edges_child[e], edges_parent[e] + nodes_map[nodes_order[c]] = c + nodes_map[nodes_order[p]] = p + a += 1 + + right = sequence_length + if b < num_edges: + right = min(right, remove_position[b]) + if a < num_edges: + right = min(right, insert_position[a]) + left = right + + while m < num_mutations and mutations_position[m] < right: + assert nodes_map[mutations_node[m]] != tskit.NULL + output[m] = nodes_map[mutations_node[m]] + m += 1 + + return output + + +def _constrain_ages( + nodes_time, nodes_fixed, edges_parent, edges_child, epsilon, max_iterations +): + """ + Approximate least squares solution to the positive branch length + constraint, using the method of alternating projections. Loosely based on + Dykstra's algorithm, see: + + Dykstra RL, "An algorithm for restricted least squares regression", JASA + 1983 + """ + assert nodes_time.size == nodes_fixed.size + assert edges_parent.size == edges_child.size + + num_edges = edges_parent.size + nodes_time = nodes_time.copy() + edges_cavity = np.zeros((num_edges, 2)) + for _ in range(max_iterations): # method of alternating projections + if np.all(nodes_time[edges_parent] - nodes_time[edges_child] > epsilon): + return nodes_time + for e in range(num_edges): + p, c = edges_parent[e], edges_child[e] + nodes_time[c] -= edges_cavity[e, 0] + nodes_time[p] -= edges_cavity[e, 1] + adjustment = nodes_time[c] - nodes_time[p] # + epsilon + edges_cavity[e, :] = 0.0 + if adjustment > 0: + assert not (nodes_fixed[c] and nodes_fixed[p]) + if not nodes_fixed[c] and not nodes_fixed[p]: + edges_cavity[e, 0] = -adjustment / 2 + edges_cavity[e, 1] = adjustment / 2 + elif nodes_fixed[c] and not nodes_fixed[p]: + edges_cavity[e, 0] = 0 + edges_cavity[e, 1] = adjustment + elif not nodes_fixed[c] and nodes_fixed[p]: + edges_cavity[e, 0] = -adjustment + edges_cavity[e, 1] = 0 + nodes_time[c] += edges_cavity[e, 0] + nodes_time[p] += edges_cavity[e, 1] + # print( + # "min length:", np.min(nodes_time[edges_parent] - nodes_time[edges_child]) + # ) + + # force remaining constraint, which can change the ages of fixed nodes + for e in range(num_edges): + p, c = edges_parent[e], edges_child[e] + # TODO: even if nodes_fixed[p], this will still change the age + if nodes_time[c] + epsilon >= nodes_time[p]: + nodes_time[p] = nodes_time[c] + epsilon + + return nodes_time + + +def _contains_unary_nodes( + nodes_mask, + edges_parent, + edges_left, + edges_right, + indexes_insert, + indexes_remove, + sequence_length, + num_nodes, +): + assert edges_parent.size == edges_left.size == edges_right.size + assert indexes_insert.size == indexes_remove.size == edges_parent.size + + num_edges = edges_parent.size + nodes_children = np.zeros(num_nodes, dtype=np.int32) + position_insert = edges_left[indexes_insert] + position_remove = edges_right[indexes_remove] + + left = 0.0 + a, b = 0, 0 + while a < num_edges or b < num_edges: + check = set() + + while b < num_edges and position_remove[b] == left: # edges out + e = indexes_remove[b] + p = edges_parent[e] + nodes_children[p] -= 1 + check.add(p) + b += 1 + + while a < num_edges and position_insert[a] == left: # edges in + e = indexes_insert[a] + p = edges_parent[e] + nodes_children[p] += 1 + check.add(p) + a += 1 + + for p in check: + if not nodes_mask[p] and nodes_children[p] == 1: + return True + + right = sequence_length + if b < num_edges: + right = min(right, position_remove[b]) + if a < num_edges: + right = min(right, position_insert[a]) + left = right + + return False diff --git a/tests/oracle/variational.py b/tests/oracle/variational.py new file mode 100644 index 00000000..f2811c2c --- /dev/null +++ b/tests/oracle/variational.py @@ -0,0 +1,478 @@ +"""Oracles for the jitted functions in ``tsdate.variational``.""" + +import numpy as np +import tskit + +from tsdate.variational import ( + CONSTRNT, + LEAFWARD, + LOWER, + MIXPRIOR, + ROOTWARD, + TINY, + UPPER, +) + +from . import approx + +# oracle: numba's np.mean accumulates sequentially, whereas numpy sums pairwise, +# which differs in the last bits; `seq_mean` sums sequentially. +from ._libm import seq_mean + + +# oracle: the numba version is a `jitclass`; this is a plain class with the same +# fields (arrays are created with the same dtypes) and constructor. +class EPFactors: + """ + Mutable state of the EP algorithm, that is the factors associated + with each edge likelihood / block likelihood / prior factor, that + together form the posterior. + + Because of constraints on numba's AOT compilation of jitclass, + this is a dataclass (no intrinsic methods). + """ + + def __init__( + self, + node_constraints, + edge_parents, + edge_children, + block_left, + block_right, + ): + assert edge_parents.size == edge_children.size + assert block_left.size == block_right.size + num_nodes = node_constraints.shape[0] + num_edges = edge_parents.size + num_blocks = block_left.size + self.node = np.zeros((num_nodes, 2, 2)) + self.edge = np.zeros((num_edges, 2, 2)) + self.block = np.zeros((num_blocks, 2, 2)) + self.scale = np.ones(num_nodes) + self._p, self._c = edge_parents, edge_children + self._j, self._k = block_left, block_right + + +def _rescale_factors(factors): + """ + At each update, all factors associated with a node need to be rescaled. + This is expensive, so we keep track of the scaling in a separate vector. + As updates progress, the factors will drift upward in magnitude while + the scaling drifts downward. To avoid underflow, we may need to + cancel out the scaling. + """ + factors.edge[:, ROOTWARD] *= factors.scale[factors._p, np.newaxis] + factors.edge[:, LEAFWARD] *= factors.scale[factors._c, np.newaxis] + factors.block[:, ROOTWARD] *= factors.scale[factors._j, np.newaxis] + factors.block[:, LEAFWARD] *= factors.scale[factors._k, np.newaxis] + factors.node[:, MIXPRIOR] *= factors.scale[:, np.newaxis] + factors.node[:, CONSTRNT] *= factors.scale[:, np.newaxis] + factors.scale[:] = 1.0 + + +def _assemble_factors(factors): + """ + Transform factors into posteriors, intended for debugging purposes only. + """ + posterior = np.zeros((factors.scale.size, 2)) + for i, (p, c) in enumerate(zip(factors._p, factors._c)): + posterior[p] += factors.edge[i, ROOTWARD] + posterior[c] += factors.edge[i, LEAFWARD] + for i, (j, k) in enumerate(zip(factors._j, factors._k)): + posterior[j] += factors.block[i, ROOTWARD] + posterior[k] += factors.block[i, LEAFWARD] + posterior += factors.node[:, MIXPRIOR] + posterior += factors.node[:, CONSTRNT] + return posterior + + +def _damp(x, y, s): + """ + If `x - y` is too small, find `d` so that `x - d*y` is large enough: + + x[0] - d*y[0] + 1 >= (x[0] + 1)*s + x[1] - d*y[1] >= y[1]*s + + for `0 < s < 1`. + """ + assert x.size == y.size == 2 + if np.all(y == 0.0) and np.all(x == 0.0): + return 1.0 + assert 0 < s < 1 + assert 0.0 < x[0] + 1 + assert 0.0 < x[1] + a = 1.0 if (1 + x[0] - y[0] > (1 + x[0]) * s) else (1 - s) * (1 + x[0]) / y[0] + b = 1.0 if (x[1] - y[1] > x[1] * s) else (1 - s) * x[1] / y[1] + d = min(a, b) + assert 0.0 < d <= 1.0 + return d + + +def _rescale(x, s): + """ + Find `d` so that `d*x[0] + 1 <= s[0]` or `d*x[0] + 1 >= 1/s[0]` + """ + assert x.size == 2 + if np.all(x == 0.0): + return 1.0 + assert 0 < x[0] + 1 + assert 0 < x[1] + if 1 + x[0] > s: + return (s - 1) / x[0] + elif 1 + x[0] < 1 / s: + return (1 / s - 1) / x[0] + return 1.0 + + +def _check_valid_constraints(constraints, edges_parent, edges_child): + # Check that upper-bound on node age is greater than maximum lower-bound + # for ages of descendants + lower_max = constraints[:, LOWER].copy() + for p, c in zip(edges_parent, edges_child): + lower_max[p] = max(lower_max[c], lower_max[p]) + if np.any(lower_max > constraints[:, UPPER]): + raise ValueError( + "Node age constraints are inconsistent, some descendants have" + " lower bounds that exceed upper bounds of their ancestors." + ) + + +def propagate_likelihood( + edge_order, + edges_parent, + edges_child, + likelihoods, + constraints, + posterior, + factors, + lognorm, + max_shape, + min_step, + unphased, +): + # Update approximating factors for Poisson mutation likelihoods on edges. + # + # :param numpy.ndarray edges_parent: integer array of parent ids per edge + # :param numpy.ndarray edges_child: integer array of child ids per edge + # :param numpy.ndarray likelihoods: array of dimension `[num_edges, 2]` + # containing mutation count and mutational target size per edge. + # :param numpy.ndarray constraints: array of dimension `[num_nodes, 2]` + # containing lower and upper bounds for each node. + # :param numpy.ndarray posterior: array of dimension `[num_nodes, 2]` + # containing natural parameters for each node, updated in-place. + # :param EPFactors factors: object containing parent and child factors + # (natural parameters) for each edge, updated in-place. + # :param numpy.ndarray lognorm: array of dimension `[num_edges]` + # containing the approximate normalizing constants per edge, + # updated in-place. + # :param float max_shape: the maximum allowed shape for node posteriors. + # :param float min_step: the minimum allowed step size in (0, 1). + # :param bool unphased: if True, edges are treated as blocks of unphased + # singletons in contemporary individuals + + assert constraints.shape == posterior.shape + assert edges_child.size == edges_parent.size + assert likelihoods.shape == (edges_parent.size, 2) + assert max_shape >= 1.0 + assert 0.0 < min_step < 1.0 + + def cavity_damping(x, y): + return _damp(x, y, min_step) + + def posterior_damping(x): + return _rescale(x, max_shape) + + def leafward_projection(x, y, z): + if unphased: + return approx.sideways_projection(x, y, z) + return approx.leafward_projection(x, y, z) + + def rootward_projection(x, y, z): + if unphased: + return approx.sideways_projection(x, y, z) + return approx.rootward_projection(x, y, z) + + def gamma_projection(x, y, z): + if unphased: + return approx.unphased_projection(x, y, z) + return approx.gamma_projection(x, y, z) + + def twin_projection(x, y): + assert unphased, "Invalid update" + return approx.twin_projection(x, y) + + fixed = constraints[:, LOWER] == constraints[:, UPPER] + + scale = factors.scale + factor = factors.block if unphased else factors.edge + assert factor.shape == (edges_parent.size, 2, 2) + + for i in edge_order: + p, c = edges_parent[i], edges_child[i] + if scale[p] < TINY or scale[c] < TINY: + # modifies `scale` and `factor` by reference + _rescale_factors(factors) + if fixed[p] and fixed[c]: + continue + elif fixed[p] and not fixed[c]: + # in practice this should only occur if a sample is the + # ancestor of another sample + child_message = factor[i, LEAFWARD] * scale[c] + child_delta = cavity_damping(posterior[c], child_message) + child_cavity = posterior[c] - child_delta * child_message + edge_likelihood = child_delta * likelihoods[i] + parent_age = constraints[p, LOWER] + lognorm[i], posterior[c] = leafward_projection( + parent_age, + child_cavity, + edge_likelihood, + ) + factor[i, LEAFWARD] *= 1.0 - child_delta + factor[i, LEAFWARD] += (posterior[c] - child_cavity) / scale[c] + child_eta = posterior_damping(posterior[c]) + posterior[c] *= child_eta + scale[c] *= child_eta + elif fixed[c] and not fixed[p]: + # in practice this should only occur if a sample has age + # greater than zero + parent_message = factor[i, ROOTWARD] * scale[p] + parent_delta = cavity_damping(posterior[p], parent_message) + parent_cavity = posterior[p] - parent_delta * parent_message + edge_likelihood = parent_delta * likelihoods[i] + child_age = constraints[c, LOWER] + lognorm[i], posterior[p] = rootward_projection( + child_age, + parent_cavity, + edge_likelihood, + ) + factor[i, ROOTWARD] *= 1.0 - parent_delta + factor[i, ROOTWARD] += (posterior[p] - parent_cavity) / scale[p] + parent_eta = posterior_damping(posterior[p]) + posterior[p] *= parent_eta + scale[p] *= parent_eta + else: + if p == c: # singleton block with single parent + parent_message = factor[i, ROOTWARD] * scale[p] + parent_delta = cavity_damping(posterior[p], parent_message) + parent_cavity = posterior[p] - parent_delta * parent_message + edge_likelihood = parent_delta * likelihoods[i] + child_age = constraints[c, LOWER] + lognorm[i], posterior[p] = \ + twin_projection(parent_cavity, edge_likelihood) # fmt: skip + factor[i, ROOTWARD] *= 1.0 - parent_delta + factor[i, ROOTWARD] += (posterior[p] - parent_cavity) / scale[p] + parent_eta = posterior_damping(posterior[p]) + posterior[p] *= parent_eta + scale[p] *= parent_eta + else: + # lower-bound cavity + parent_message = factor[i, ROOTWARD] * scale[p] + child_message = factor[i, LEAFWARD] * scale[c] + parent_delta = cavity_damping(posterior[p], parent_message) + child_delta = cavity_damping(posterior[c], child_message) + delta = min(parent_delta, child_delta) + + parent_cavity = posterior[p] - delta * parent_message + child_cavity = posterior[c] - delta * child_message + edge_likelihood = delta * likelihoods[i] + + # match moments and update factors + lognorm[i], posterior[p], posterior[c] = gamma_projection( + parent_cavity, + child_cavity, + edge_likelihood, + ) + factor[i, ROOTWARD] *= 1.0 - delta + factor[i, ROOTWARD] += (posterior[p] - parent_cavity) / scale[p] + factor[i, LEAFWARD] *= 1.0 - delta + factor[i, LEAFWARD] += (posterior[c] - child_cavity) / scale[c] + + # upper-bound posterior + parent_eta = posterior_damping(posterior[p]) + child_eta = posterior_damping(posterior[c]) + posterior[p] *= parent_eta + posterior[c] *= child_eta + scale[p] *= parent_eta + scale[c] *= child_eta + + +def propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol): + # Update approximating factors for global prior. + # + # :param ndarray free: boolean array for if prior should be applied to node + # :param ndarray penalty: initial value for regularisation penalty + # :param ndarray posterior: rows are nodes, columns are first and + # second natural parameters of gamma posteriors. Updated in place. + # :param EPFactors factors: object containing EP messages for nodes. + # Updated in place. + # :param float max_shape: the maximum allowed shape for node posteriors. + # :param int em_maxitt: the maximum number of EM iterations to use when + # fitting the regularisation. + # :param int em_reltol: the termination criterion for relative change in + # log-likelihood. + + assert free.size == posterior.shape[0] + assert max_shape >= 1.0 + + def posterior_damping(x): + return _rescale(x, max_shape) + + if not np.any(free): + return + + factor = factors.node + scale = factors.scale + assert factor.shape == (free.size, 2, 2) + assert scale.size == free.size + + # fit an exponential to cavity distributions for unconstrained nodes + cavity = posterior - factor[:, MIXPRIOR] * scale[:, np.newaxis] + shape, rate = cavity[free, 0] + 1, cavity[free, 1] + penalty = 1 / seq_mean(shape / rate) # oracle: seq_mean + itt, delta = 0, np.inf + while abs(delta) > abs(penalty) * em_reltol: + if itt > em_maxitt: + break + delta = 1 / seq_mean(shape / (rate + penalty)) - penalty # oracle: seq_mean + penalty += delta + itt += 1 + assert penalty > 0 + + # update posteriors and rescale to keep shape bounded + posterior[free, 1] = cavity[free, 1] + penalty + factor[free, MIXPRIOR] = \ + (posterior[free] - cavity[free]) / scale[free, np.newaxis] # fmt: skip + for i in np.flatnonzero(free): + eta = posterior_damping(posterior[i]) + posterior[i] *= eta + scale[i] *= eta + + +def propagate_mutations( + mutations_order, + mutations_posterior, + mutations_phase, + mutations_edge, + edges_parent, + edges_child, + likelihoods, + constraints, + posterior, + factors, + unphased, +): + # Calculate posteriors for mutations. (publicly undocumented) + # + # :param ndarray mutations_order: integer array giving order in + # which to traverse mutations + # :param ndarray mutations_posterior: array of dimension `(num_mutations, 2)` + # containing natural parameters for each mutation, modified in place + # :param ndarray mutations_phase: array of dimension `(num_mutations, )` + # containing mutation phase, modified in place + # :param ndarray mutations_edge: integer array giving edge for each mutation + # :param ndarray edges_parent: integer array of parent ids per edge + # :param ndarray edges_child: integer array of child ids per edge + # :param ndarray likelihoods: array of dimension `[num_edges, 2]` + # containing mutation count and mutational target size per edge. + # :param ndarray constraints: array of dimension `[num_nodes, 2]` + # containing lower and upper bounds for each node. + # :param ndarray posterior: array of dimension `[num_nodes, 2]` + # containing natural parameters for each node + # :param EPFactors factors: object containing + # containing parent and child factors (natural parameters) for each edge + # :param bool unphased: if True, edges are treated as blocks of unphased + # singletons in contemporary individuals + + # TODO: scale should be 1.0, can we delete + # TODO: we don't seem to need to damp? + + # TODO: assert more stuff here? + assert mutations_phase.size == mutations_edge.size + assert mutations_posterior.shape == (mutations_phase.size, 2) + assert constraints.shape == posterior.shape + assert edges_child.size == edges_parent.size + assert likelihoods.shape == (edges_parent.size, 2) + + def leafward_projection(x, y, z): + if unphased: + return approx.mutation_sideways_projection(x, y, z) + return approx.mutation_leafward_projection(x, y, z) + + def rootward_projection(x, y, z): + if unphased: + return approx.mutation_sideways_projection(x, y, z) + return approx.mutation_rootward_projection(x, y, z) + + def gamma_projection(x, y, z): + if unphased: + return approx.mutation_unphased_projection(x, y, z) + return approx.mutation_gamma_projection(x, y, z) + + def fixed_projection(x, y): + if unphased: + return approx.mutation_block_projection(x, y) + return approx.mutation_edge_projection(x, y) + + twin_projection = approx.mutation_twin_projection + + fixed = constraints[:, LOWER] == constraints[:, UPPER] + + scale = factors.scale + factor = factors.block if unphased else factors.edge + assert factor.shape == (edges_parent.size, 2, 2) + + for m in mutations_order: + i = mutations_edge[m] + if i == tskit.NULL: # skip mutations above root + continue + p, c = edges_parent[i], edges_child[i] + if fixed[p] and fixed[c]: + child_age = constraints[c, 0] + parent_age = constraints[p, 0] + mutations_phase[m], mutations_posterior[m] = \ + fixed_projection(parent_age, child_age) # fmt: skip + elif fixed[p] and not fixed[c]: + child_message = factor[i, LEAFWARD] * scale[c] + child_delta = 1.0 # hopefully we don't need to damp + child_cavity = posterior[c] - child_delta * child_message + edge_likelihood = child_delta * likelihoods[i] + parent_age = constraints[p, LOWER] + mutations_phase[m], mutations_posterior[m] = leafward_projection( + parent_age, + child_cavity, + edge_likelihood, + ) + elif fixed[c] and not fixed[p]: + parent_message = factor[i, ROOTWARD] * scale[p] + parent_delta = 1.0 # hopefully we don't need to damp + parent_cavity = posterior[p] - parent_delta * parent_message + edge_likelihood = parent_delta * likelihoods[i] + child_age = constraints[c, LOWER] + mutations_phase[m], mutations_posterior[m] = rootward_projection( + child_age, + parent_cavity, + edge_likelihood, + ) + else: + if p == c: # singleton block with single parent + parent_message = factor[i, ROOTWARD] * scale[p] + parent_delta = 1.0 # hopefully we don't need to damp + parent_cavity = posterior[p] - parent_delta * parent_message + edge_likelihood = parent_delta * likelihoods[i] + child_age = constraints[c, LOWER] + mutations_phase[m], mutations_posterior[m] = \ + twin_projection(parent_cavity, edge_likelihood) # fmt: skip + else: + parent_message = factor[i, ROOTWARD] * scale[p] + child_message = factor[i, LEAFWARD] * scale[c] + parent_delta = 1.0 # hopefully we don't need to damp + child_delta = 1.0 # hopefully we don't need to damp + delta = min(parent_delta, child_delta) + parent_cavity = posterior[p] - delta * parent_message + child_cavity = posterior[c] - delta * child_message + edge_likelihood = delta * likelihoods[i] + mutations_phase[m], mutations_posterior[m] = gamma_projection( + parent_cavity, + child_cavity, + edge_likelihood, + ) diff --git a/tests/test_oracle_helpers.py b/tests/test_oracle_helpers.py new file mode 100644 index 00000000..b3d5270e --- /dev/null +++ b/tests/test_oracle_helpers.py @@ -0,0 +1,318 @@ +"""Tests of the comparison helpers in ``tests/oracle/helpers.py``.""" + +import numpy as np +import pytest +from oracle.helpers import ( + INF, + NAN, + Outcome, + assert_inplace_close, + assert_outcome, + assert_same_outcome, + assert_ulp_close, + both, + call, + compare, + errors_match, + expected_error, + kind, + outcome, +) + + +def one_ulp_up(x, n=1): + for _ in range(n): + x = np.nextafter(x, np.inf) + return x + + +class TestAssertUlpClose: + @pytest.mark.parametrize( + ("actual", "desired"), + [ + pytest.param(1.5, 1.5, id="scalar"), + pytest.param(1.0, one_ulp_up(1.0), id="one_ulp"), + pytest.param(one_ulp_up(1.0, 4), 1.0, id="four_ulp"), + pytest.param(np.array([1.0, NAN]), np.array([1.0, NAN]), id="nan"), + pytest.param(INF, INF, id="inf"), + pytest.param(-INF, -INF, id="minus_inf"), + pytest.param( + (1.0, np.arange(2.0), (np.zeros(1), NAN)), + (1.0, np.arange(2.0), (np.zeros(1), NAN)), + id="nested", + ), + ], + ) + def test_passes(self, actual, desired): + assert_ulp_close(actual, desired) + + @pytest.mark.parametrize( + ("actual", "desired", "match"), + [ + pytest.param(one_ulp_up(1.0, 5), 1.0, "ulp", id="five_ulp"), + pytest.param( + np.array([1.0, NAN]), np.array([NAN, 1.0]), "NaN", id="nan_place" + ), + pytest.param(1.0, NAN, "NaN", id="nan_vs_number"), + pytest.param(INF, -INF, "infinity", id="inf_sign"), + pytest.param(INF, 1e308, "infinity", id="inf_vs_huge"), + pytest.param((1.0, 2.0), (1.0, 2.0, 3.0), "structure", id="structure"), + pytest.param(np.zeros(3), np.zeros(4), "shape", id="shape"), + pytest.param(np.zeros((2, 2)), np.zeros(4), "shape", id="ndim"), + pytest.param( + (1.0, np.array([1.0, 2.0])), + (1.0, np.array([1.0, 2.5])), + r"\[1\]", + id="path", + ), + ], + ) + def test_fails(self, actual, desired, match): + with pytest.raises(AssertionError, match=match): + assert_ulp_close(actual, desired) + + def test_maxulp(self): + x = one_ulp_up(1.0, 10) + with pytest.raises(AssertionError, match="ulp"): + assert_ulp_close(x, 1.0, maxulp=4) + assert_ulp_close(x, 1.0, maxulp=10) + + +class TestAssertInplaceClose: + def test_agree(self): + assert_inplace_close((np.ones(3), 2.0), (np.ones(3), 2.0)) + + def test_differ(self): + b = np.ones(3) + b[1] = 2.0 + with pytest.raises(AssertionError, match="argument 0"): + assert_inplace_close((np.ones(3), 2.0), (b, 2.0)) + + +class TestOutcome: + def test_return_value(self): + result = outcome(lambda x: x + 1, 1.0) + assert result.value == 2.0 + assert result.exception is None + assert result.error is None + + def test_exception(self): + def fail(): + raise ValueError("bad") + + result = outcome(fail) + assert result.value is None + assert result.error is ValueError + assert str(result.exception) == "bad" + + def test_arrays_are_copied(self): + def modify(x): + x[0] = 5.0 + + x = np.zeros(2) + result = outcome(modify, x) + assert x[0] == 0.0 + assert result.args[0][0] == 5.0 + + def test_numpy_scalar_becomes_float(self): + result = outcome(lambda x: type(x), np.float64(1.0)) + assert result.value is float + + def test_warnings_are_suppressed(self): + with np.errstate(all="raise"): + result = outcome(lambda: np.float64(1.0) / np.zeros(1)) + assert result.exception is None + + def test_keyword_arguments(self): + assert outcome(lambda x, y=0: x + y, 1, y=2).value == 3 + + +class TestCall: + def test_plain_function(self): + assert call(lambda x: x + 1, 1) == 2 + + def test_ctypes_interface(self): + class CFunc: + ctypes = staticmethod(lambda x: x * 2) + + assert call(CFunc(), 2) == 4 + + +class TestErrorsMatch: + def test_same_type_and_message(self): + assert errors_match(ValueError("a"), ValueError("a")) + + def test_subclass_accepted(self): + assert errors_match(FloatingPointError("a"), ArithmeticError("a")) + + def test_type_mismatch(self): + assert not errors_match(KeyError("a"), ValueError("a")) + + def test_message_mismatch(self): + assert not errors_match(ValueError("a"), ValueError("b")) + assert errors_match(ValueError("a"), ValueError("b"), check_message=False) + + def test_zero_division_message_ignored(self): + actual = ZeroDivisionError("division by zero") + assert errors_match(actual, ZeroDivisionError("float division by zero")) + + def test_expected_error(self): + assert ValueError in expected_error(ValueError) + + +def returns(value, modify=None): + def func(x): + if modify is not None: + x[0] = modify + return value + + return func + + +def raises(exception): + def func(x): + raise exception + + return func + + +class TestAssertSameOutcome: + def test_agree(self): + x = np.zeros(2) + a = outcome(returns(np.ones(2)), x) + b = outcome(returns(np.ones(2)), x) + assert_same_outcome(a, b) + + def test_value_mismatch(self): + x = np.zeros(2) + a = outcome(returns(np.ones(2)), x) + b = outcome(returns(np.full(2, 2.0)), x) + with pytest.raises(AssertionError, match="ulp"): + assert_same_outcome(a, b) + + def test_implementation_raises(self): + x = np.zeros(2) + a = outcome(raises(ValueError("a")), x) + b = outcome(returns(1.0), x) + with pytest.raises(AssertionError, match="implementation raised"): + assert_same_outcome(a, b) + + def test_oracle_raises(self): + x = np.zeros(2) + a = outcome(returns(1.0), x) + b = outcome(raises(ValueError("a")), x) + with pytest.raises(AssertionError, match="oracle raised"): + assert_same_outcome(a, b) + + def test_exceptions_agree(self): + x = np.zeros(2) + a = outcome(raises(ValueError("a")), x) + b = outcome(raises(ValueError("a")), x) + assert_same_outcome(a, b) + + def test_exception_type_mismatch(self): + x = np.zeros(2) + a = outcome(raises(KeyError("a")), x) + b = outcome(raises(ValueError("a")), x) + with pytest.raises(AssertionError, match="implementation raised"): + assert_same_outcome(a, b) + + def test_exception_message_mismatch(self): + x = np.zeros(2) + a = outcome(raises(ValueError("a")), x) + b = outcome(raises(ValueError("b")), x) + with pytest.raises(AssertionError, match="implementation raised"): + assert_same_outcome(a, b) + assert_same_outcome(a, b, check_message=False) + + def test_inplace_mismatch(self): + x = np.zeros(2) + a = outcome(returns(1.0, modify=1.0), x) + b = outcome(returns(1.0, modify=2.0), x) + with pytest.raises(AssertionError, match="argument 0"): + assert_same_outcome(a, b) + + def test_maxulp(self): + a = Outcome(value=one_ulp_up(1.0, 6)) + b = Outcome(value=1.0) + with pytest.raises(AssertionError, match="ulp"): + assert_same_outcome(a, b) + assert_same_outcome(a, b, maxulp=6) + + +class TestCompare: + def test_returns_oracle_outcome(self): + result = compare(returns(1.0), returns(1.0), np.zeros(2)) + assert result.value == 1.0 + + def test_arguments_are_copied(self): + x = np.zeros(2) + compare(returns(1.0, modify=3.0), returns(1.0, modify=3.0), x) + assert x[0] == 0.0 + + def test_returns_oracle_args(self): + result = compare(returns(1.0, modify=3.0), returns(1.0, modify=3.0), np.zeros(2)) + assert result.args[0][0] == 3.0 + + def test_mismatch(self): + with pytest.raises(AssertionError): + compare(returns(1.0), returns(2.0), np.zeros(2)) + + def test_oracle_raises_implementation_returns(self): + with pytest.raises(AssertionError, match="oracle raised"): + compare(returns(1.0), raises(ValueError("a")), np.zeros(2)) + + def test_check_message(self): + impl, oracle = raises(ValueError("a")), raises(ValueError("b")) + with pytest.raises(AssertionError): + compare(impl, oracle, np.zeros(2)) + compare(impl, oracle, np.zeros(2), check_message=False) + + def test_keyword_arguments(self): + compare(lambda x, y=0: x + y, lambda x, y=0: x + y, 1.0, y=2.0) + + +class TestKind: + @pytest.mark.parametrize( + ("value", "expected"), + [ + pytest.param(1.0, "finite", id="finite"), + pytest.param(np.zeros(0), "finite", id="empty"), + pytest.param(NAN, "nan", id="nan"), + pytest.param(np.array([1.0, NAN]), "nan", id="array_with_nan"), + pytest.param(INF, "nonfinite", id="inf"), + pytest.param(np.array([-INF, 1.0]), "nonfinite", id="array_with_inf"), + pytest.param((1.0, np.array([INF, NAN])), "nan", id="nan_beats_inf"), + pytest.param((np.ones(2), (1.0, INF)), "nonfinite", id="nested"), + pytest.param((np.ones((2, 3)), np.ones(4)), "finite", id="mixed_ndim"), + pytest.param(None, None, id="none"), + ], + ) + def test_value(self, value, expected): + assert kind(Outcome(value=value)) == expected + + def test_exception(self): + assert kind(Outcome(exception=KeyError("a"))) is KeyError + + +class TestAssertOutcome: + def test_expected_kind(self): + assert_outcome(returns(1.0), returns(1.0), (np.zeros(1),), "finite") + + def test_wrong_kind(self): + with pytest.raises(AssertionError): + assert_outcome(returns(1.0), returns(1.0), (np.zeros(1),), "nan") + + def test_expected_exception(self): + assert_outcome( + raises(KeyError("a")), raises(KeyError("a")), (np.zeros(1),), KeyError + ) + + +class TestBoth: + def test_returns_oracle_value(self): + assert both(returns(1.0), returns(1.0), np.zeros(1)) == 1.0 + + def test_reraises_oracle_exception(self): + with pytest.raises(ValueError, match="a"): + both(raises(ValueError("a")), raises(ValueError("a")), np.zeros(1)) From 2cd2967b896ac8592effe466bc6e5943947f870d Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 20 Nov 2026 13:46:13 -0800 Subject: [PATCH 02/56] Add microbenchmark harness for the accelerated array-level functions evaluation/microbench.py times each array-level numba entry point (EP passes, rescaling, phasing, util, prior, discrete.logsumexp) on inputs built from simulated tree sequences at three sizes, with warm-up, median of N repeats, and compile time reported separately (per dispatcher, and as the difference in `import tsdate` time with and without NUMBA_DISABLE_JIT). Implementations are selected with --impl; IMPLS is the seam for adding the C versions. No changes under tsdate/. Numba baseline (median seconds per call, 7 repeats; compile_s from numba dispatcher timers; total compile at import ~43 s). INDICATIVE ONLY: other jobs were running on this machine, so absolute numbers are noisy. Sizes: small 20 individuals/1e5 bp, medium 100/1e6, large 1000/5e7 (564k edges, 164k mutations). function small medium large compile_s propagate_likelihood[edges] 7.93e-04 1.48e-02 1.15e+00 4.20 propagate_likelihood[blocks] 1.12e-04 9.87e-04 5.69e-02 4.20 propagate_prior 7.52e-06 5.14e-05 2.68e-03 1.63 propagate_mutations[edges] 8.61e-05 1.48e-03 1.68e-01 1.62 propagate_mutations[blocks] 3.58e-05 3.01e-04 2.43e-02 1.62 reallocate_unphased 3.16e-06 4.61e-05 4.71e-03 0.93 _block_singletons 3.16e-05 3.52e-04 4.76e-02 3.21 _mutation_frequency 5.92e-05 1.26e-03 1.69e-01 1.01 mutational_area 3.21e-05 4.95e-04 6.18e-02 2.17 mutational_timescale 5.59e-05 5.30e-04 5.47e-02 3.49 piecewise_scale_point_estimate 6.15e-06 6.71e-05 4.40e-03 0.98 piecewise_scale_posterior 2.13e-03 2.62e-02 1.82e+00 3.07 _fixed_changepoints 1.26e-05 1.91e-05 2.19e-04 1.71 _poisson_changepoints 3.56e-04 3.29e-02 1.81e-02 2.22 _count_mutations 1.77e-05 3.74e-04 1.02e-01 0.82 _split_disjoint_nodes 1.69e-05 7.46e-04 1.35e-01 4.33 _relabel_mutations_node 6.85e-06 9.13e-05 3.10e-02 0.39 _constrain_ages 6.83e-05 1.06e-03 1.28e-01 0.59 _contains_unary_nodes 2.69e-05 4.38e-04 5.69e-02 0.86 _marginalize_over_ancestors 6.63e-05 1.57e-03 1.86e-01 0.40 conditional_coalescent_variance 6.72e-05 1.58e-03 1.85e-01 0.73 logsumexp 3.06e-06 1.27e-05 1.38e-04 0.08 Notes: _poisson_changepoints is unused in production and is capped at 2000 intervals, so it is not monotone in size. --- evaluation/README.md | 30 ++ evaluation/microbench.py | 700 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 730 insertions(+) create mode 100644 evaluation/microbench.py diff --git a/evaluation/README.md b/evaluation/README.md index 461834a9..7fc153ec 100644 --- a/evaluation/README.md +++ b/evaluation/README.md @@ -15,6 +15,7 @@ standard coalescent. | `accuracy.py` | Sweep a parameter (`sample_size`, `length`, `mutation_rate`, `max_iterations`) for `variational_gamma`, comparing estimated to true node times. `--modes true` dates the true topology; `inferred` dates a tsinfer topology and compares to best-matching true nodes via [tscompare](https://github.com/tskit-dev/tscompare) (see issue #301). Writes one row per node (`accuracy_*.csv`). It also compares mutation times (`mutations_*.csv`): sites with a single mutation are matched by position, and tsdate's posterior mean mutation time is compared with the midpoint of the true edge the mutation sits on (the best any method can do; the exact simulated time is also saved as `true_time_exact`). `plot.py` scores scatter, RMSE and bias against the midpoint but PIT and interval coverage against the exact time, since the posterior is for the realised mutation time; `--mutation-truth midpoint` or `exact` forces one truth everywhere. Mutation comparison needs no node matching in either mode. | | `afs.py` | Compare the observed site allele frequency spectrum with the expected one from branch lengths (branch AFS x mutation rate) in genomic windows, for the true times, the true topology dated by tsdate, and a tsinfer topology dated by tsdate. Writes `afs_*.csv`. | | `performance.py` | Wall time and peak RSS, each case in a fresh process. | +| `microbench.py` | Microbenchmarks of the array-level accelerated functions (EP passes, rescaling, phasing, `util`, `prior`), on simulated inputs at three sizes (see below). | | `compare.py` | Compares two `performance.py` CSVs case by case (see below). | | `plot.py` | Reads `results/*.csv` and writes PNGs: error/bias/interval coverage vs parameter (`accuracy_*_summary.png`: top row node times, bottom row mutation times), estimated-vs-true scatter (`accuracy_*_scatter.png`: columns are swept values, rows are node/mutation times for true/tsinferred topology), PIT calibration histograms (`accuracy_*_calibration.png`: node row, mutation row), AFS observed-vs-expected (`afs_*.png`), time and memory scaling. | | `validation.py` | Stub: numerical checks too slow for the unit tests (issue #384). | @@ -73,3 +74,32 @@ repeats (use 5 or more for a reference run). Add `--quick` to `accuracy.py` / `performance.py` for a fast smoke test. Quick runs write to separate `*_quick.csv` files (so they never overwrite full results), and `plot.py` labels their figures "quick run" and names them `*_quick*.png`. + +### Microbenchmarks of the accelerated functions + +`microbench.py` times each array-level numba-jitted entry point on inputs built from +simulated tree sequences (small/medium/large; the large case has ~560k edges, so the +EP edge pass takes about a second). The EP state is produced by running +`ExpectationPropagation.infer` for two iterations, and the functions are called as +`iterate`/`infer`/`rescale` call them (edges with some nonzero-age samples, and +unphased singleton blocks). Arrays modified in place are copied before each repeat, +outside the timed region. Scalar functions (`approx`, `hypergeo`) are timed only +through the EP passes. + +``` +python evaluation/microbench.py --quick # smoke test +python evaluation/microbench.py --repeats 7 --output mb.csv # table + results/mb.csv +python evaluation/microbench.py --sizes medium --only propagate mutational +``` + +Each function is warmed up, then the median of `--repeats` timed calls is reported +(fast calls are batched so each timed block lasts a few ms; times are per call). +Compile time is reported separately: per function from numba's dispatcher timers, and +in total as `import tsdate` with minus without `NUMBA_DISABLE_JIT` in a fresh process +(functions with explicit signatures compile at import, not at first call; skipped +with `--no-import-compile` or `--quick`). The CSV also records provenance. Timings are +only comparable between runs on a quiet machine. + +Implementations are chosen with `--impl`. To add one, write a function returning a +dict of callables with the same names and signatures as `_numba_impl` and register it +in `IMPLS`. diff --git a/evaluation/microbench.py b/evaluation/microbench.py new file mode 100644 index 00000000..3204786a --- /dev/null +++ b/evaluation/microbench.py @@ -0,0 +1,700 @@ +""" +Microbenchmarks of the array-level accelerated entry points in tsdate (the +numba-jitted functions that take and return arrays). Inputs are built from simulated +tree sequences at several sizes, mirroring how the functions are called in +production. Scalar functions (approx, hypergeo) are not timed on their own: they are +exercised through the EP passes. Writes a table to stdout and, with --output, a CSV +to results/. + +Timing: each function is warmed up (one untimed call), then called `--repeats` times +on identical, freshly copied inputs (copies are made outside the timed region); the +median of `time.perf_counter` is reported. Very fast calls are batched, so that a +timed block lasts at least a few ms (reported times are per call). + +Compile time (numba): functions with explicit signatures compile eagerly when tsdate +is imported, so a "first call" timing does not capture it. Instead report (a) the +compile time recorded by each numba dispatcher (its `compiler_lock` timer, which +includes LLVM), and (b) the total cost of `import tsdate` in a fresh process with +and without NUMBA_DISABLE_JIT (the difference is the total compile time at import). + +Implementations are selected with --impl. To add one, write a function returning a +dict from function names (the keys of `_numba_impl`) to callables with the same +signature, and register it in IMPLS; everything else is implementation-agnostic. + +Example: + python evaluation/microbench.py --repeats 7 --output microbench.csv +""" + +import argparse +import dataclasses +import math +import os +import statistics +import subprocess +import sys +import time + +import common +import numpy as np +import pandas as pd +import tskit + +# size name -> (diploid individuals, sequence length) +SIZES = { + "small": (20, 1e5), + "medium": (100, 1e6), + "large": (1000, 5e7), +} +QUICK_SIZES = {"small": (10, 1e5)} +MUTATION_RATE = 1e-8 +MIN_BLOCK_S = 5e-3 # batch fast calls until a timed block lasts this long +MAX_BATCH = 1000 + + +def _numba_impl(): + from tsdate import discrete, phasing, prior, rescaling, util, variational + + ep = variational.ExpectationPropagation + return { + "propagate_likelihood": ep.propagate_likelihood, + "propagate_prior": ep.propagate_prior, + "propagate_mutations": ep.propagate_mutations, + "mutational_area": rescaling.mutational_area, + "mutational_timescale": rescaling.mutational_timescale, + "piecewise_scale_point_estimate": rescaling.piecewise_scale_point_estimate, + "piecewise_scale_posterior": rescaling.piecewise_scale_posterior, + "_fixed_changepoints": rescaling._fixed_changepoints, + "_poisson_changepoints": rescaling._poisson_changepoints, + "_count_mutations": rescaling._count_mutations, + "_block_singletons": phasing._block_singletons, + "reallocate_unphased": phasing.reallocate_unphased, + "_mutation_frequency": phasing._mutation_frequency, + "_split_disjoint_nodes": util._split_disjoint_nodes, + "_relabel_mutations_node": util._relabel_mutations_node, + "_constrain_ages": util._constrain_ages, + "_contains_unary_nodes": util._contains_unary_nodes, + "_marginalize_over_ancestors": prior._marginalize_over_ancestors, + "conditional_coalescent_variance": prior.conditional_coalescent_variance, + "logsumexp": discrete.LogLikelihoods.logsumexp, + } + + +# The seam for adding implementations: name -> {function name -> callable}. A later +# step adds e.g. "c": _c_impl here (a function returning a dict like _numba_impl's, +# possibly wrapping calls to adapt argument types such as EPFactors). +IMPLS = {"numba": _numba_impl} + + +def numba_compile_times(funcs): + """Seconds spent compiling each numba dispatcher (NaN if unavailable).""" + out = {} + for name, f in funcs.items(): + total = 0.0 + try: + for res in f.overloads.values(): + total += res.metadata["timers"]["compiler_lock"] + except (AttributeError, KeyError): + total = math.nan + out[name] = total + return out + + +COMPILE_TIMES = {"numba": numba_compile_times} + + +def numba_import_compile_time(): + """Total compile time at import: `import tsdate` with minus without numba JIT.""" + + def import_time(disable_jit): + env = dict(os.environ, TSDATE_ENABLE_NUMBA_CACHE="0") + env["NUMBA_DISABLE_JIT"] = "1" if disable_jit else "0" + code = ( + "import time; import numpy, tskit, numba, scipy.special; " + "t = time.perf_counter(); import tsdate; " + "print(time.perf_counter() - t)" + ) + out = subprocess.check_output([sys.executable, "-c", code], env=env, text=True) + return float(out.strip().splitlines()[-1]) + + return import_time(False) - import_time(True) + + +# --------------------------------------------------------------------------- +# Inputs +# --------------------------------------------------------------------------- + + +def _with_ancient_samples(ts, fraction=0.1, seed=1): + """ + Give some leaf samples nonzero ages (halfway to their youngest parent), so + that the "fixed child, free parent" branch of the EP passes is exercised. + """ + rng = np.random.default_rng(seed) + tables = ts.dump_tables() + time_ = tables.nodes.time + youngest_parent = np.full(ts.num_nodes, np.inf) + np.minimum.at(youngest_parent, ts.edges_child, ts.nodes_time[ts.edges_parent]) + is_leaf = ~np.isin(np.arange(ts.num_nodes), ts.edges_parent) + candidates = [u for u in ts.samples() if is_leaf[u] and youngest_parent[u] > 1] + chosen = rng.choice(candidates, size=int(fraction * len(candidates)), replace=False) + time_[chosen] = youngest_parent[chosen] / 2 + tables.nodes.time = time_ + tables.mutations.time = np.full(ts.num_mutations, tskit.UNKNOWN_TIME) + return tables.tree_sequence() + + +def _copy_factors(f): + from tsdate.variational import EPFactors + + g = EPFactors( + np.zeros((f.scale.size, 2)), f._p, f._c, f._j, f._k + ) # constraints only give the shape + g.node[:] = f.node + g.edge[:] = f.edge + g.block[:] = f.block + g.scale[:] = f.scale + return g + + +def _run_ep(ts, singletons_phased, iterations): + from tsdate.variational import ExpectationPropagation + + ep = ExpectationPropagation( + ts, mutation_rate=MUTATION_RATE, singletons_phased=singletons_phased + ) + ep.infer( + ep_iterations=iterations, + max_shape=1000, + rescale_intervals=0, # call the rescaling functions separately + rescale_iterations=0, + regularise=True, + rescale_segsites=False, + ) + return ep + + +@dataclasses.dataclass +class Bench: + """ + One benchmark: `make_args()` returns a fresh argument tuple (copying anything + mutated in place) for the function called `func` in the implementation. + """ + + name: str + func: str + make_args: callable + note: str = "" + + +def _const(*args): + return lambda: args + + +def build_benchmarks(n, length, iterations): + """Build all benchmarks (and a dict describing the inputs) for one size.""" + from tsdate import phasing, rescaling, util + from tsdate.variational import ( + LEAFWARD, + ROOTWARD, + USE_BLOCK_LIKELIHOOD, + USE_EDGE_LIKELIHOOD, + ) + + ts_flat = common.simulate(n, length, MUTATION_RATE, seed=1) # contemporary + ts_old = _with_ancient_samples(ts_flat) # some samples with nonzero age + ep_old = _run_ep(ts_old, True, iterations) # edges + ep_flat = _run_ep(ts_flat, False, iterations) # unphased singleton blocks + info = dict( + num_samples=ts_flat.num_samples, + num_nodes=ts_flat.num_nodes, + num_edges=ts_flat.num_edges, + num_mutations=ts_flat.num_mutations, + num_blocks=ep_flat.block_likelihoods.shape[0], + ) + benches = [] + add = benches.append + + # --- variational.py, as in ExpectationPropagation.iterate/infer --- + max_shape, min_step = 1000, 0.1 + for tag, ep, order, par, chi, lik, logc, unph in [ + ( + "edges", + ep_old, + ep_old.edge_order, + ep_old.edge_parents, + ep_old.edge_children, + ep_old.edge_likelihoods, + ep_old.edge_logconst, + USE_EDGE_LIKELIHOOD, + ), + ( + "blocks", + ep_flat, + ep_flat.block_order, + ep_flat.block_nodes[ROOTWARD], + ep_flat.block_nodes[LEAFWARD], + ep_flat.block_likelihoods, + ep_flat.block_logconst, + USE_BLOCK_LIKELIHOOD, + ), + ]: + + def likelihood_args( + ep=ep, order=order, par=par, chi=chi, lik=lik, logc=logc, unph=unph + ): + return ( + order, + par, + chi, + lik, + ep.node_constraints, + ep.node_posterior.copy(), + _copy_factors(ep.factors), + logc.copy(), + max_shape, + min_step, + unph, + ) + + add( + Bench(f"propagate_likelihood[{tag}]", "propagate_likelihood", likelihood_args) + ) + + def prior_args(): + return ( + ep_old.unconstrained_roots, + ep_old.node_posterior.copy(), + _copy_factors(ep_old.factors), + max_shape, + 10, + 1e-8, + ) + + add(Bench("propagate_prior", "propagate_prior", prior_args)) + + for tag, ep, unph in [ + ("edges", ep_old, USE_EDGE_LIKELIHOOD), + ("blocks", ep_flat, USE_BLOCK_LIKELIHOOD), + ]: + phased = ep.mutation_blocks == tskit.NULL + if unph: + sel = ~phased + m_edges, par, chi = ( + ep.mutation_blocks, + ep.block_nodes[ROOTWARD], + ep.block_nodes[LEAFWARD], + ) + lik = ep.block_likelihoods + else: + sel = phased + m_edges, par, chi = ep.mutation_edges, ep.edge_parents, ep.edge_children + lik = ep.edge_likelihoods + + def mutation_args( + ep=ep, sel=sel, m_edges=m_edges, par=par, chi=chi, lik=lik, unph=unph + ): + return ( + ep.mutation_order[sel], + ep.mutation_posterior.copy(), + ep.mutation_phase.copy(), + m_edges, + par, + chi, + lik, + ep.node_constraints, + ep.node_posterior, + ep.factors, + unph, + ) + + add(Bench(f"propagate_mutations[{tag}]", "propagate_mutations", mutation_args)) + + # --- phasing.py --- + likelihoods = ep_flat.sizebiased_likelihoods + add( + Bench( + "reallocate_unphased", + "reallocate_unphased", + lambda: ( + likelihoods.copy(), + ep_flat.mutation_phase, + ep_flat.mutation_blocks, + ep_flat.block_edges, + ), + ) + ) + tree_args = ( + ts_flat.edges_parent, + ts_flat.edges_child, + ts_flat.edges_left, + ts_flat.edges_right, + ) + index_args = ( + ts_flat.indexes_edge_insertion_order, + ts_flat.indexes_edge_removal_order, + ) + muts_pos = ts_flat.sites_position[ts_flat.mutations_site] + nodes_individual = ts_flat.nodes_individual + add( + Bench( + "_block_singletons", + "_block_singletons", + _const( + np.full(ts_flat.num_individuals, True), + nodes_individual, + ts_flat.mutations_node, + muts_pos, + *tree_args, + *index_args, + ts_flat.sequence_length, + ), + ) + ) + nodes_sample = np.full((ts_flat.num_nodes, 1), False) + nodes_sample[list(ts_flat.samples()), 0] = True + add( + Bench( + "_mutation_frequency", + "_mutation_frequency", + _const( + nodes_sample, + ts_flat.mutations_node, + muts_pos, + *tree_args, + *index_args, + ts_flat.sequence_length, + ), + ) + ) + + node_is_sample = np.full(ts_flat.num_nodes, False) + node_is_sample[list(ts_flat.samples())] = True + + # --- rescaling.py, as in ExpectationPropagation.rescale --- + rescale_lik = ep_flat.sizebiased_likelihoods.copy() + phasing.reallocate_unphased( + rescale_lik, + ep_flat.mutation_phase, + ep_flat.mutation_blocks, + ep_flat.block_edges, + ) + nodes_fixed = ep_flat.node_constraints[:, 0] == ep_flat.node_constraints[:, 1] + nodes_time, _ = ep_flat.node_moments() + par, chi = ep_flat.edge_parents, ep_flat.edge_children + intervals = 1000 + add( + Bench( + "mutational_area", + "mutational_area", + _const(nodes_time, rescale_lik, par, chi), + ) + ) + add( + Bench( + "mutational_timescale", + "mutational_timescale", + _const(nodes_time, rescale_lik, nodes_fixed, par, chi, intervals), + ) + ) + original_breaks, rescaled_breaks = rescaling.mutational_timescale( + nodes_time, rescale_lik, nodes_fixed, par, chi, intervals + ) + add( + Bench( + "piecewise_scale_point_estimate", + "piecewise_scale_point_estimate", + _const(nodes_time, nodes_fixed, original_breaks, rescaled_breaks), + ) + ) + rescaled_time = rescaling.piecewise_scale_point_estimate( + nodes_time, nodes_fixed, original_breaks, rescaled_breaks + ) + _, unique = np.unique(rescaled_time[~nodes_fixed], return_index=True) + orig = rescaling.piecewise_scale_point_estimate( + rescaled_breaks, + np.full(rescaled_breaks.size, False), + np.append(0, rescaled_time[~nodes_fixed][unique]), + np.append(0, nodes_time[~nodes_fixed][unique]), + ) + add( + Bench( + "piecewise_scale_posterior", + "piecewise_scale_posterior", + _const( + ep_flat.node_posterior, nodes_fixed, orig, rescaled_breaks, 0.5, max_shape + ), + ) + ) + counts, offset, duration, _ = rescaling.mutational_area( + nodes_time, rescale_lik, par, chi + ) + add( + Bench( + "_fixed_changepoints", + "_fixed_changepoints", + _const(offset * duration, intervals), + ) + ) + # Unused in production (only referenced in a TODO); cap its size as it is slow. + cap = 2000 + add( + Bench( + "_poisson_changepoints", + "_poisson_changepoints", + _const(counts[:cap], offset[:cap], 2.0, 0.0, 0.0), + note=f"unused in production; first {cap} intervals", + ) + ) + add( + Bench( + "_count_mutations", + "_count_mutations", + _const( + node_is_sample, + ts_flat.mutations_node, + muts_pos, + *tree_args, + *index_args, + ts_flat.sequence_length, + True, + ), + ) + ) + + # --- util.py --- + split_args = (*tree_args, node_is_sample) + add(Bench("_split_disjoint_nodes", "_split_disjoint_nodes", _const(*split_args))) + new_parent, new_child, nodes_order, split_nodes = util._split_disjoint_nodes( + *split_args + ) + info["num_split_nodes"] = len(split_nodes) + add( + Bench( + "_relabel_mutations_node", + "_relabel_mutations_node", + _const( + ts_flat.mutations_node, + muts_pos, + nodes_order, + new_parent, + new_child, + ts_flat.edges_left, + ts_flat.edges_right, + *index_args, + ), + ) + ) + rng = np.random.default_rng(1) + noisy_time = ts_flat.nodes_time * np.exp(rng.normal(0, 0.3, ts_flat.num_nodes)) + noisy_time[node_is_sample] = ts_flat.nodes_time[node_is_sample] + add( + Bench( + "_constrain_ages", + "_constrain_ages", + _const( + noisy_time, + node_is_sample, + ts_flat.edges_parent, + ts_flat.edges_child, + 1e-6, + 20, + ), + note="noisy times violate constraints; 20 iterations", + ) + ) + add( + Bench( + "_contains_unary_nodes", + "_contains_unary_nodes", + _const( + node_is_sample, + ts_flat.edges_parent, + ts_flat.edges_left, + ts_flat.edges_right, + *index_args, + ts_flat.sequence_length, + ts_flat.num_nodes, + ), + ) + ) + + # --- prior.py (prior tables are built for up to a few thousand tips) --- + num_tips = ts_flat.num_samples + coal_rates = np.array( + [2 / (i * (i - 1)) if i > 1 else 0.0 for i in range(1, num_tips + 1)] + ) + moments = np.stack((coal_rates, 2 * coal_rates**2), 1) # mean, second moment + add( + Bench( + "_marginalize_over_ancestors", + "_marginalize_over_ancestors", + _const(moments), + ) + ) + add( + Bench( + "conditional_coalescent_variance", + "conditional_coalescent_variance", + _const(np.uint64(num_tips)), + ) + ) + + # --- discrete.py: log-sum-exp over a grid slice --- + grid = rng.normal(-5, 3, 10 * ts_flat.num_samples) + add(Bench("logsumexp", "logsumexp", _const(grid), note="size 10 x num_samples")) + + return benches, info + + +# --------------------------------------------------------------------------- +# Timing +# --------------------------------------------------------------------------- + + +def time_bench(func, bench, repeats): + """Warm up, then return per-call times (seconds) for `repeats` timed blocks.""" + t0 = time.perf_counter() + func(*bench.make_args()) # warm up (also first-call cost, e.g. lazy compilation) + first_call = time.perf_counter() - t0 + # estimate the cost of one call to choose a batch size + args = bench.make_args() + t0 = time.perf_counter() + func(*args) + one = time.perf_counter() - t0 + batch = int(min(MAX_BATCH, max(1, math.ceil(MIN_BLOCK_S / max(one, 1e-9))))) + times = [] + for _ in range(repeats): + batch_args = [bench.make_args() for _ in range(batch)] + t0 = time.perf_counter() + for a in batch_args: + func(*a) + times.append((time.perf_counter() - t0) / batch) + return times, first_call, batch + + +def format_table(rows): + cols = ["function", "size", "impl", "median_s", "min_s", "max_s", "repeats"] + body = [ + [ + r["function"], + r["size"], + r["impl"], + f"{r['median_s']:.3e}", + f"{r['min_s']:.3e}", + f"{r['max_s']:.3e}", + str(r["repeats"]), + ] + for r in rows + ] + widths = [max(len(c), *(len(b[i]) for b in body)) for i, c in enumerate(cols)] + lines = [" ".join(c.ljust(w) for c, w in zip(cols, widths))] + for b in body: + lines.append(" ".join(x.ljust(w) for x, w in zip(b, widths))) + return "\n".join(lines) + + +def main(): + p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + p.add_argument("--impl", nargs="+", default=["numba"], choices=sorted(IMPLS)) + p.add_argument("--sizes", nargs="+", default=list(SIZES), choices=list(SIZES)) + p.add_argument("--repeats", type=int, default=7) + p.add_argument("--ep-iterations", type=int, default=2, help="EP iterations first") + p.add_argument( + "--only", nargs="+", default=None, help="Substrings of benchmark names to run" + ) + p.add_argument( + "--output", + help="Output CSV name in results/ (default: none, print only)", + ) + p.add_argument( + "--no-import-compile", + action="store_true", + help="Skip the (slow, ~1 min) fresh-process measurement of total compile time", + ) + p.add_argument( + "--quick", + action="store_true", + help="Tiny smoke-test run (implies --no-import-compile)", + ) + args = p.parse_args() + sizes = {k: SIZES[k] for k in args.sizes} + if args.quick: + sizes, args.repeats, args.ep_iterations = QUICK_SIZES, 1, 1 + args.no_import_compile = True + + # Compile time is measured with an empty cache, and excluded from timings below. + os.environ["TSDATE_ENABLE_NUMBA_CACHE"] = "0" + impls = {name: IMPLS[name]() for name in args.impl} + import_compile_s = {} + if "numba" in impls and not args.no_import_compile: + import_compile_s["numba"] = numba_import_compile_time() + print( + f"numba: total compile time at import ~ {import_compile_s['numba']:.1f} s " + f"(import tsdate with minus without JIT, fresh process)" + ) + + prov = common.provenance() + rows = [] + for size, (n, length) in sizes.items(): + t0 = time.perf_counter() + benches, info = build_benchmarks(n, length, args.ep_iterations) + print( + f"[{size}] n={n} L={length:g}: {info} " + f"(inputs built in {time.perf_counter() - t0:.1f} s)", + flush=True, + ) + for bench in benches: + if args.only and not any(s in bench.name for s in args.only): + continue + for name, funcs in impls.items(): + times, first, batch = time_bench(funcs[bench.func], bench, args.repeats) + row = dict( + function=bench.name, + size=size, + impl=name, + median_s=statistics.median(times), + min_s=min(times), + max_s=max(times), + repeats=args.repeats, + batch=batch, + first_call_s=first, + import_compile_s=import_compile_s.get(name, math.nan), + sample_size=n, + length=length, + note=bench.note, + **info, + **prov, + ) + rows.append(row) + print( + f" {bench.name:36s} {name:6s} {row['median_s']:.3e} s " + f"(x{batch} per block)", + flush=True, + ) + + # Read after the runs: lazily compiled functions (no explicit signature) only + # compile on first call, which happens in the warm-up. + compile_s = { + name: COMPILE_TIMES[name](funcs) if name in COMPILE_TIMES else {} + for name, funcs in impls.items() + } + for row in rows: + func = next(b.func for b in benches if b.name == row["function"]) + row["compile_s"] = compile_s[row["impl"]].get(func, math.nan) + + print() + print(format_table(rows)) + print() + print("Compile time per dispatcher (s, from numba's timers):") + for name in impls: + for func, secs in sorted(compile_s[name].items(), key=lambda kv: -kv[1]): + print(f" {name:6s} {func:36s} {secs:.2f}") + if args.output: + common.RESULTS.mkdir(exist_ok=True) + out = common.RESULTS / args.output + pd.DataFrame(rows).to_csv(out, index=False) + print("wrote", out) + + +if __name__ == "__main__": + main() From ca9b0f62cba352d892e9fad27fd6f10370f9cd43 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 20 Nov 2026 13:46:21 -0800 Subject: [PATCH 03/56] Test hypergeo and approx against their oracles; add numerical accuracy report Each function in tsdate.hypergeo and tsdate.approx is compared with its oracle to within 4 ulp, including which inputs give NaN and which raise: - edge-case tables: domain boundaries, poles, both sides of each branch switch, degenerate parameters, the regimes expectation propagation reaches (fixed and free nodes, no mutations, huge shapes, tiny and huge rates), with the outcome category (exception, NaN, finite) of each case; - grids over the special functions (incl. 330 points of gammaincinv, which the C port must reproduce bit for bit, as numba wraps cephes igami); - the 2F1 unity branch against its formula, and the projection invariants (NaN exactly when the moments are unusable, inputs returned unchanged); - one seeded random test per function, over typical and extreme ranges. test_oracle_numba_libm.py checks the oracle's integer power against numba's x**n; it goes when numba does. Accuracy of the approximations themselves is not a property of a port, so it is reported by evaluation/numerical_accuracy.py rather than tested: error of the production functions against mpmath, SciPy and closed forms per regime, and violations of symmetry, monotonicity and continuity at switch points. --- evaluation/README.md | 20 + evaluation/numerical_accuracy.py | 666 +++++++++++++++++++++++++ tests/test_oracle_approx.py | 815 +++++++++++++++++++++++++++++++ tests/test_oracle_hypergeo.py | 605 +++++++++++++++++++++++ tests/test_oracle_numba_libm.py | 47 ++ 5 files changed, 2153 insertions(+) create mode 100644 evaluation/numerical_accuracy.py create mode 100644 tests/test_oracle_approx.py create mode 100644 tests/test_oracle_hypergeo.py create mode 100644 tests/test_oracle_numba_libm.py diff --git a/evaluation/README.md b/evaluation/README.md index 7fc153ec..e5a5692c 100644 --- a/evaluation/README.md +++ b/evaluation/README.md @@ -16,6 +16,7 @@ standard coalescent. | `afs.py` | Compare the observed site allele frequency spectrum with the expected one from branch lengths (branch AFS x mutation rate) in genomic windows, for the true times, the true topology dated by tsdate, and a tsinfer topology dated by tsdate. Writes `afs_*.csv`. | | `performance.py` | Wall time and peak RSS, each case in a fresh process. | | `microbench.py` | Microbenchmarks of the array-level accelerated functions (EP passes, rescaling, phasing, `util`, `prior`), on simulated inputs at three sizes (see below). | +| `numerical_accuracy.py` | Accuracy of the special functions and gamma approximations (`tsdate.hypergeo`, `tsdate.approx`) per function and regime: worst error against mpmath, SciPy or closed forms, and violations of properties such as symmetry, monotonicity and continuity at switch points (see below). Not to be confused with `accuracy.py`, which scores dating. | | `compare.py` | Compares two `performance.py` CSVs case by case (see below). | | `plot.py` | Reads `results/*.csv` and writes PNGs: error/bias/interval coverage vs parameter (`accuracy_*_summary.png`: top row node times, bottom row mutation times), estimated-vs-true scatter (`accuracy_*_scatter.png`: columns are swept values, rows are node/mutation times for true/tsinferred topology), PIT calibration histograms (`accuracy_*_calibration.png`: node row, mutation row), AFS observed-vs-expected (`afs_*.png`), time and memory scaling. | | `validation.py` | Stub: numerical checks too slow for the unit tests (issue #384). | @@ -103,3 +104,22 @@ only comparable between runs on a quiet machine. Implementations are chosen with `--impl`. To add one, write a function returning a dict of callables with the same names and signatures as `_numba_impl` and register it in `IMPLS`. + +### Accuracy of the special functions + +`numerical_accuracy.py` measures the approximation error of the production functions in +`tsdate.hypergeo` (digamma, trigamma, `betaln`, the incomplete gamma derivative and +inverse, and the Laplace approximations to U, 1F1 and 2F1, including the +unity limit of 2F1) and `tsdate.approx` (moment matching, gamma fits, closed forms of +the moment functions) against mpmath, SciPy and closed forms. It also reports how often +properties that the exact functions have are violated: symmetry, monotonicity, the Kummer +transformation, continuity across a switch point. One row per function and regime gives +the worst error (`rel`, `abs`, `ulp`) or a violation `count`. The unit tests do not +check any of this (they check only agreement with the oracles), so the table is +where inaccurate regimes show up. + +``` +python evaluation/numerical_accuracy.py --quick # the computation takes seconds; importing tsdate compiles numba +python evaluation/numerical_accuracy.py --only hyp2f1 gammainc # groups: polygamma betaln gammainc hyperu hyp1f1 hyp2f1 approx +python evaluation/numerical_accuracy.py --output acc.csv # also writes results/acc.csv +``` diff --git a/evaluation/numerical_accuracy.py b/evaluation/numerical_accuracy.py new file mode 100644 index 00000000..1d0f7495 --- /dev/null +++ b/evaluation/numerical_accuracy.py @@ -0,0 +1,666 @@ +""" +Numerical accuracy of the special functions and gamma approximations in tsdate +(``tsdate.hypergeo`` and ``tsdate.approx``), per function and regime. Each row of the +table reports the worst error of the production function against a reference (mpmath, +SciPy, a closed form) or the violation of a property the approximation should have +(symmetry, monotonicity, continuity across a switch point). These are measurements, not +tests: the unit tests only check that implementations agree with the numba oracles, so +inaccuracy of the algorithms themselves is recorded here. Behaviour that looks wrong +is a candidate for a fix. + +Errors are relative unless the metric says "abs" (log-scale quantities such as +log U, log 1F1 and log 2F1 are compared in absolute terms), "ulp" or "count". + +Example: + python evaluation/numerical_accuracy.py --quick + python evaluation/numerical_accuracy.py --only hyp2f1 gammainc --output acc.csv +""" + +import argparse +import csv +import math +import pathlib + +import mpmath +import numpy as np +import scipy.special + +from tsdate import approx, hypergeo + +INF = math.inf +RESULTS = pathlib.Path(__file__).parent / "results" + + +def call(func, *args): + """Call a function, or the ``ctypes`` interface of a compiled numba ``cfunc``""" + return getattr(func, "ctypes", func)(*args) + + +def try_call(func, *args): + """The result of ``func``, or None if it raised""" + try: + return call(func, *args) + except Exception: # noqa: BLE001 + return None + + +def log_uniform(rng, lo, hi, size=None): + return 10.0 ** rng.uniform(lo, hi, size) + + +class Report: + """Collects rows of (group, function, regime, metric, value, points, note)""" + + def __init__(self): + self.rows = [] + + def add(self, group, function, regime, metric, value, n=1, note=""): + self.rows.append((group, function, regime, metric, value, n, note)) + + def worst(self, group, function, regime, metric, errors, note=""): + """Worst of ``errors`` (None marks a call that raised)""" + raised = sum(e is None for e in errors) + finite = [e for e in errors if e is not None and math.isfinite(e)] + value = max(finite) if finite else math.nan + nonfinite = len(errors) - raised - len(finite) + if raised or nonfinite: + note = f"{note} raised={raised} nonfinite={nonfinite}".strip() + self.add(group, function, regime, metric, value, len(errors), note) + + def print(self): + header = ("function", "regime", "metric", "value", "n", "note") + body = [(r[1], r[2], r[3], f"{r[4]:.3g}", str(r[5]), r[6]) for r in self.rows] + widths = [max(len(str(x)) for x in col) for col in zip(header, *body)] + group = None + for row, raw in zip(body, self.rows): + if raw[0] != group: + group = raw[0] + print(f"\n== {group} ==") + print(" ".join(h.ljust(w) for h, w in zip(header, widths))) + print(" ".join(x.ljust(w) for x, w in zip(row, widths)).rstrip()) + + def write(self, path): + with open(path, "w", newline="") as f: + writer = csv.writer(f) + writer.writerow(("group", *("function regime metric value n note".split()))) + writer.writerows(self.rows) + + +def rel(actual, expected): + if actual is None: + return None + if actual == expected: + return 0.0 + return abs(actual - expected) / abs(expected) + + +def ulp(actual, expected): + if actual is None: + return None + return abs(actual - expected) / np.spacing(abs(expected)) + + +# --- polygamma, betaln --- # + + +def mp_psi(n, x): + with mpmath.workdps(60): + return float(mpmath.psi(n, x)) + + +POLYGAMMA_REGIMES = { + "x <= 1e-5": [1e-10, 1e-6, 1e-5], + "1e-5 < x < 8.5 (recurrence)": [1e-3, 0.1, 1.0, 2.0, 4.9, 5.0, 8.4], + "x >= 8.5 (asymptotic)": [8.5, 100.0, 1e4, 1e8], + "x < 0 (reflection)": [-1e-5, -0.5, -1.5, -10.5, -100.3, -1e5 - 0.5], + "near a negative integer": [-1.0 + 1e-8, -1.0 - 1e-8, -3.0 - 1e-6, -2.0 + 1e-12], +} + + +def polygamma(report): + for name, order in [("_digamma", 0), ("_trigamma", 1)]: + func = getattr(hypergeo, name) + for regime, xs in POLYGAMMA_REGIMES.items(): + errors = [rel(try_call(func, x), mp_psi(order, x)) for x in xs] + report.worst("polygamma", name, regime, "rel", errors) + # trigamma returns 1 / x**2 for x <= 1e-4, omitting pi**2 / 6 + xs = [1e-6, 1e-5, 1e-4] + errors = [rel(try_call(hypergeo._trigamma, x), mp_psi(1, x)) for x in xs] + report.worst("polygamma", "_trigamma", "x <= 1e-4 (1/x**2)", "rel", errors) + # continuity at the switch points of the series + for x in [1e-5, 8.5]: + lo = hypergeo._digamma(x) + hi = hypergeo._digamma(np.nextafter(x, 2 * x)) + report.add("polygamma", "_digamma", f"jump at x={x}", "rel", rel(lo, hi)) + + +def betaln(report): + regimes = { + "balanced": [(0.5, 0.5), (1.0, 1.0), (1e5, 1e5), (1e15, 1e15), (1e300, 1e300)], + "tiny and tiny": [(1e-10, 1e-10), (1e-300, 1e-300)], + "tiny and huge (cancellation)": [(1e-10, 1e10), (1e8, 1e-8), (1e-5, 1e5)], + } + for regime, points in regimes.items(): + errors = [] + for p, q in points: + errors.append( + rel(try_call(hypergeo._betaln, p, q), scipy.special.betaln(p, q)) + ) + report.worst("betaln", "_betaln", regime, "rel", errors) + + +# --- incomplete gamma --- # + + +def gammainc_der_reference(p, x): + with mpmath.workdps(40): + return float(mpmath.diff(lambda s: mpmath.gammainc(s, 0, x, regularized=True), p)) + + +def gammainc_der(report): + regimes = { + "series (x <= 1 or x < p)": [(1.0, 1.0), (0.5, 1.0), (1e-3, 1.0), (10.0, 0.5)] + + [(2.0, 1.5), (5.0, 3.0), (100.0, 100.0 - 1e-9)], + "continued fraction (x >= p, x > 1)": [(5.0, 5.0), (5.0, 50.0), (100.0, 100.0)] + + [(1e-3, 10.0)], + "just above x = 1 (continued fraction)": [(1.0, np.nextafter(1.0, 2))], + "gaussian (p > 1000)": [(1000.5, 900.0), (2000.0, 2000.0), (2000.0, 2300.0)], + } + for regime, points in regimes.items(): + errors = [] + for p, x in points: + ref = gammainc_der_reference(p, x) + errors.append(rel(try_call(hypergeo._gammainc_der, p, x), ref)) + report.worst("gammainc", "_gammainc_der", regime, "rel", errors) + below = hypergeo._gammainc_der(1000.0, 1000.0) + above = hypergeo._gammainc_der(np.nextafter(1000.0, 2000.0), 1000.0) + report.add("gammainc", "_gammainc_der", "jump at p = 1000", "rel", rel(above, below)) + + +def exact_gammainc_inv(a, q, x0): + """Root of the regularised lower incomplete gamma minus q, near ``x0``; or None""" + with mpmath.workdps(40): + + def f(t): + return mpmath.gammainc(a, 0, t, regularized=True) - q + + try: + bracket = (x0 * (1 - 1e-6), x0 * (1 + 1e-6)) + return float(mpmath.re(mpmath.findroot(f, bracket, solver="illinois"))) + except (ValueError, ZeroDivisionError): + return None + + +def gammainc_inv(report, rng, quick): + func = hypergeo._gammainc_inv + n = 10 if quick else 40 + for a in [0.1, 0.3, 1.0, 2.5, 10.0, 60.0, 1e3, 1e4]: + errors = [] + for q in log_uniform(rng, -12, -0.01, n): + x = try_call(func, a, q) + errors.append(rel(scipy.special.gammainc(a, x), q) if x else None) + report.worst("gammainc", "_gammainc_inv", f"roundtrip, a={a}", "rel", errors) + # relative to an exact inverse + bands = {"a < 0.1": (-2, -1), "0.1 <= a < 1": (-1, 0), "1 <= a < 10": (0, 1)} + bands |= {"10 <= a < 100": (1, 2), "a >= 100": (2, 4)} + n = 8 if quick else 60 + for band, (lo, hi) in bands.items(): + errors = [] + for a, q in zip(log_uniform(rng, lo, hi, n), rng.uniform(1e-8, 1.0, n)): + x = try_call(func, a, q) + exact = exact_gammainc_inv(a, q, x) + if exact is None: + continue + errors.append(ulp(x, exact)) + errors = [e for e in errors if e is not None] + if errors: + report.add( + "gammainc", + "_gammainc_inv", + band, + "ulp median", + np.median(errors), + len(errors), + ) + report.add( + "gammainc", "_gammainc_inv", band, "ulp max", max(errors), len(errors) + ) + qs = np.linspace(0.001, 0.999, 50) + violations = 0 + for a in [0.2, 1.0, 5.0, 100.0]: + x = [call(func, a, q) for q in qs.tolist()] + violations += int(np.sum(np.diff(x) <= 0)) + report.add("gammainc", "_gammainc_inv", "monotone in q", "count", violations, 200) + exact = [(q, call(func, 1.0, q), -math.log1p(-q)) for q in [1e-100, 1e-3, 0.5, 0.999]] + errors = [rel(x, e) for _, x, e in exact] + report.worst("gammainc", "_gammainc_inv", "a = 1, exponential", "rel", errors) + + +# --- Laplace approximations to hypergeometric functions --- # + + +def log_hyperu(a, b, x): + with mpmath.workdps(30): + return float(mpmath.log(mpmath.hyperu(a, b, x, maxterms=10**6))) + + +def log_hyp1f1(a, b, x): + with mpmath.workdps(30): + return float(mpmath.log(mpmath.hyp1f1(a, b, x, maxterms=10**6))) + + +def log_hyp2f1(a, b, c, z): + with mpmath.workdps(30): + return float(mpmath.log(mpmath.re(mpmath.hyp2f1(a, b, c, z, maxterms=10**7)))) + + +def absolute(func, reference, points): + errors = [] + for args in points: + value = try_call(func, *args) + if isinstance(value, tuple): + value = value[0] + errors.append(None if value is None else abs(value - reference(*args))) + return errors + + +def hyperu(report): + func = hypergeo._hyperu_laplace + regimes = { + "a >= 1 (EP: a = y + 1)": [(1.0, 2.0, 1.0), (2.0, 5.0, 0.5), (5.0, 15.0, 1.0)] + + [(10.0, 20.0, 50.0), (50.0, 60.0, 1.0), (1000.0, 1010.0, 1e4)], + "large b - a": [(1.0, 11.0, 1e-2), (1.0, 101.0, 100.0), (50.0, 1050.0, 100.0)], + "b == a": [(1.0, 1.0, 1.0)], + "a < 1 (Stirling)": [(1e-3, 10.001, 1.0), (0.1, 10.1, 1.0), (1.0, 1.001, 1e-6)], + } + for regime, points in regimes.items(): + report.worst( + "hyperu", "_hyperu_laplace", regime, "abs", absolute(func, log_hyperu, points) + ) + errors = [] + for a, b, x in [ + (1.0, 2.0, 1.0), + (2.0, 5.0, 0.5), + (1.0, 11.0, 1e-2), + (10.0, 20.0, 50.0), + ]: + step = 1e-6 * x + fd = (func(a, b, x + step)[0] - func(a, b, x - step)[0]) / (2 * step) + errors.append(rel(func(a, b, x)[1], fd)) + report.worst( + "hyperu", "_hyperu_laplace", "derivative vs finite difference", "rel", errors + ) + grid = [ + (a, a + d, x) + for a in [1.0, 50.0, 1e5] + for d in [1e-10, 1.0, 1e3] + for x in [1e-3, 1.0, 1e3] + ] + values = [try_call(func, *args) for args in grid] + positive = sum(v is not None and v[1] > 0 for v in values) + report.add( + "hyperu", + "_hyperu_laplace", + "d/dx log U > 0, a >= 1", + "count", + positive, + len(grid), + ) + d = func(1e-10, 1.0 + 1e-10, 1e-12)[1] + report.add( + "hyperu", + "_hyperu_laplace", + "d/dx log U at a = 1e-10", + "value", + d, + 1, + "should be < 0", + ) + values = [func(2.0, 2.0, x)[0] for x in [0.5, 1.0, 2.0, 4.0]] + report.add( + "hyperu", + "_hyperu_laplace", + "U(a, a, x) decreasing", + "count", + int(np.sum(np.diff(values) >= 0)), + 3, + ) + + +def hyp1f1(report): + func = hypergeo._hyp1f1_laplace + regimes = { + "moderate": [ + (1.0, 2.0, 1.0), + (1.0, 2.0, -1.0), + (5.0, 8.0, 10.0), + (5.0, 8.0, -10.0), + ], + "large shapes": [(50.0, 1000.0, 100.0), (50.0, 1000.0, -100.0)] + + [(1000.0, 1010.0, 20.0), (1000.0, 1010.0, -20.0)], + "a -> 0": [(1e-10, 1.0 + 1e-10, 1e3), (1e-10, 2e-10, 1.0)], + } + for regime, points in regimes.items(): + report.worst( + "hyp1f1", "_hyp1f1_laplace", regime, "abs", absolute(func, log_hyp1f1, points) + ) + errors = [] + for a, b, x in [(5.0, 8.0, 10.0), (1.0, 3.0, 2.0), (30.0, 40.0, 100.0)]: + errors.append(rel(func(a, b, -x), -x + func(b - a, b, x))) + report.worst("hyp1f1", "_hyp1f1_laplace", "Kummer transformation", "rel", errors) + xs = np.linspace(-50, 50, 41).tolist() + values = [func(2.0, 5.0, x) for x in xs] + report.add( + "hyp1f1", + "_hyp1f1_laplace", + "increasing in x", + "count", + int(np.sum(np.diff(values) <= 0)), + 40, + ) + + +def hyp2f1(report, quick): + func = hypergeo._hyp2f1_laplace + zs = [(-1e9,), (-100.0,), (-1.0,), (0.5,), (0.9,), (0.99,), (0.99998,), (0.999999,)] + abcs = { + "(1, 2, 3)": (1.0, 2.0, 3.0), + "(5, 7, 9)": (5.0, 7.0, 9.0), + "(30, 40, 35)": (30.0, 40.0, 35.0), + "(100, 200, 150)": (100.0, 200.0, 150.0), + "(0.5, 30, 1.5)": (0.5, 30.0, 1.5), + "(1, 2, 5) g > 0": (1.0, 2.0, 5.0), + "(2, 3, 5) g = 0": (2.0, 3.0, 5.0), + "(3, 2, 5)": (3.0, 2.0, 5.0), + "(2, 2, 5)": (2.0, 2.0, 5.0), + "(0.1, 0.2, 1) small": (0.1, 0.2, 1.0), + } + for label, abc in abcs.items(): + for (z,) in zs: + if abc == (100.0, 200.0, 150.0) and z > 0.9999: + continue + if quick and z not in (-100.0, 0.5, 0.99998): + continue + errors = absolute(func, log_hyp2f1, [(*abc, z)]) + regime = f"(a,b,c)={label}, z={z:g}" + report.worst("hyp2f1", "_hyp2f1_laplace", regime, "abs", errors) + # tiny z: 2F1 ~ 1 + a b z / c + errors = [] + for a, b, c in [ + (1.0, 2.0, 3.0), + (5.0, 7.0, 9.0), + (0.5, 30.0, 1.5), + (30.0, 40.0, 35.0), + ]: + for z in [1e-12, 1e-8, 1e-4, -1e-12, -1e-8, -1e-4]: + errors.append(abs(func(a, b, c, z) - a * b / c * z)) + report.worst("hyp2f1", "_hyp2f1_laplace", "|z| <= 1e-4 vs a b z / c", "abs", errors) + # the unity limit, through hugely negative z (the parameters of EP updates) + pars = [ + (202.865, 0.0153, 0.0012724, 101353547.00, 0.0, 2.404560e-05), + (999.998, 0.1041, 0.0012612, 14749022.000, 2.0, 7.830300e-05), + (73.4909, 1.0600, 0.0010028, 56254280956.0, 0.0, 0.0002302392), + (18.9981, 0.1315, 0.0015053, 23443723634.0, 1.0, 2.470348e-05), + ] + errors = [] + for a_i, b_i, a_j, b_j, y, mu in pars: + z = (mu - b_j) / (mu + b_i) + args = (a_j, a_i + a_j + y, a_j + y + 1, z) + errors.append(abs(func(*args) - log_hyp2f1(*args))) + report.worst("hyp2f1", "_hyp2f1_laplace", "unity limit, EP parameters", "abs", errors) + # discontinuity where np.isclose(z, 1) switches to the unity limit + lo, hi = 0.5, 1.0 - 1e-9 + while np.nextafter(lo, 1.0) != hi: + mid = lo + (hi - lo) / 2 + lo, hi = (lo, mid) if np.isclose(mid, 1.0) else (mid, hi) + for abc in [(1.0, 2.0, 3.0), (30.0, 40.0, 35.0)]: + jump = func(*abc, hi) - func(*abc, lo) + report.add( + "hyp2f1", + "_hyp2f1_laplace", + f"jump at switch to unity, {abc}", + "abs", + abs(jump), + ) + sym = [rel(func(2.0, 5.0, 7.0, z), func(5.0, 2.0, 7.0, z)) for z in [-3.0, 0.2, 0.9]] + report.worst("hyp2f1", "_hyp2f1_laplace", "symmetric in a, b", "rel", sym) + values = [func(3.0, 4.0, 8.0, z) for z in np.linspace(-20, 0.98, 60)] + report.add( + "hyp2f1", + "_hyp2f1_laplace", + "increasing in z", + "count", + int(np.sum(np.diff(values) <= 0)), + 59, + ) + + +# --- gamma approximations (tsdate.approx) --- # + + +def gamma_quantiles(shape, rate, q1=0.25, q2=0.75): + x1, x2 = scipy.special.gammaincinv(shape, [q1, q2]) / rate + return q1, q2, float(x1), float(x2) + + +def gamma_fits(report, rng, quick): + kl = approx.approximate_gamma_kl + errors, residuals = [], [] + for x, gap in [ + (1.0, 1e-3), + (1.0, 0.5), + (1.0, 5.0), + (1e-3, 2.0), + (1e6, 0.1), + (3.0, 1e-4), + ]: + shape, rate = kl(x, math.log(x) - gap) + alpha = shape + 1.0 + errors.append(rel(alpha / rate, x)) + residuals.append(abs(scipy.special.digamma(alpha) - math.log(alpha) + gap)) + report.worst("approx", "approximate_gamma_kl", "mean matched", "rel", errors) + report.worst( + "approx", "approximate_gamma_kl", "stationarity residual", "abs", residuals + ) + below = kl(1.0, -np.nextafter(5e-5, 0.0))[0] + above = kl(1.0, -np.nextafter(5e-5, 1.0))[0] + report.add( + "approx", + "approximate_gamma_kl", + "jump at asymptotic switch", + "rel", + rel(below, above), + ) + errors = [] + for mean, variance in [(1.0, 1.0), (10.0, 4.0), (1e3, 1e-6), (1e-3, 1e-3)]: + shape, rate = approx.approximate_gamma_mom(mean, variance) + errors += [rel((shape + 1) / rate, mean), rel((shape + 1) / rate**2, variance)] + report.worst( + "approx", "approximate_gamma_mom", "mean and variance matched", "rel", errors + ) + mean, variance = 3.0, 0.5 + logx, xlogx, logx2 = approx.approximate_log_moments(mean, variance) + expected = ( + math.log(mean) - 0.5 * variance / mean**2, + mean * math.log(mean) + 0.5 * variance / mean, + math.log(mean) ** 2 + (1 - math.log(mean)) * variance / mean**2, + ) + errors = [rel(a, e) for a, e in zip((logx, xlogx, logx2), expected)] + report.worst( + "approx", "approximate_log_moments", "second order expansion", "rel", errors + ) + shapes = [0.01, 0.1, 0.5, 1.0, 2.0, 10.0, 49.0, 50.0, 51.0, 999.0, 1001.0, 1e4, 1e6] + for max_shape in [50.0, 1000.0, 1e6]: + errors = [] + for shape in shapes: + args = (*gamma_quantiles(shape, 0.001), max_shape) + result = try_call(approx.approximate_gamma_iqr, *args) + errors.append( + None if result is None else rel(result[0] + 1.0, min(shape, max_shape)) + ) + report.worst( + "approx", + "approximate_gamma_iqr", + f"shape recovered, max_shape={max_shape:g}", + "rel", + errors, + ) + errors = [ + rel(approx.average_gammas(np.full(3, s), np.full(3, r))[0] + 1.0, s + 1.0) + for s, r in [(3.0, 0.5), (0.5, 2.0)] + ] + report.worst("approx", "average_gammas", "identical gammas recovered", "rel", errors) + shape, rate = approx.average_gammas(np.array([0.0]), np.array([1.0])) + report.add( + "approx", "average_gammas", "single gamma, shape 1", "rel", rel(shape + 1.0, 1.0) + ) + + +def moment_functions(report, quick): + a_i, b_i, y, mu = 10.0, 0.01, 3.0, 1e-4 + s, r = a_i + y, b_i + 2 * mu + got = approx.twin_moments(a_i, b_i, y, mu) + expected = (math.log(2) * y + math.lgamma(s) - math.log(r) * s, s / r, s / r**2) + report.worst( + "approx", + "twin_moments", + "closed form", + "rel", + [rel(g, e) for g, e in zip(got, expected)], + ) + t_i, t_j = 7.0, 2.0 + mn, va = approx.mutation_edge_moments(t_i, t_j) + errors = [rel(mn, 4.5), rel(va, 25.0 / 12.0)] + report.worst("approx", "mutation_edge_moments", "closed form", "rel", errors) + pr, mn, va = approx.mutation_block_moments(t_i, t_j) + errors = [rel(pr, 7.0 / 9.0), rel(mn, pr * t_i / 2 + (1 - pr) * t_j / 2)] + report.worst("approx", "mutation_block_moments", "closed form", "rel", errors) + # rootward with t_j -> 0 approaches the gamma with shape a_i + y, rate b_i + mu + a_i, b_i, y, mu = 10.0, 0.01, 1.0, 1e-4 + s, r = a_i + y, b_i + mu + exact = (math.lgamma(s) - s * math.log(r), s / r, s / r**2) + for t_j in [1e-10, 1e-3]: + got = approx.rootward_moments(t_j, a_i, b_i, y, mu) + report.add( + "approx", + "rootward_moments", + f"t_j={t_j:g} vs t_j=0 closed form, log-lik", + "abs", + abs(got[0] - exact[0]), + ) + report.add( + "approx", + "rootward_moments", + f"t_j={t_j:g} vs t_j=0 closed form, mean", + "rel", + rel(got[1], exact[1]), + ) + # y = 0: U(a, a + 1, z) = z**-a + a_j, b_j, mu, t_i = 10.0, 0.01, 1e-4, 1000.0 + logl, mn, va = approx.sideways_moments(t_i, a_j, b_j, 0.0, mu) + z = t_i * (mu + b_j) + f0 = logl + mu * t_i - a_j * math.log(t_i) - math.lgamma(a_j) + report.add( + "approx", "sideways_moments", "y = 0 vs z**-a", "rel", rel(f0, -a_j * math.log(z)) + ) + # projected gammas reproduce the moments + args = (10.0, 0.01, 10.0, 0.01, 1.0, 1e-4) + _, mn_i, va_i, mn_j, va_j = approx.moments(*args) + _, proj_i, proj_j = approx.gamma_projection( + np.array([9.0, 0.01]), np.array([9.0, 0.01]), np.array([1.0, 1e-4]) + ) + errors = [] + for proj, mn, va in [(proj_i, mn_i, va_i), (proj_j, mn_j, va_j)]: + errors += [ + rel((proj[0] + 1) / proj[1], mn), + rel((proj[0] + 1) / proj[1] ** 2, va), + ] + report.worst( + "approx", "gamma_projection", "projection matches moments", "rel", errors + ) + # variance by cancellation (second moment minus squared mean) + for name, args in [ + ("moments", (1e8, 1e5, 1e8, 1e5, 1, 1e-4)), + ("moments", (10, 0.01, 10, 0.01, 1, 1e-4)), + ]: + va = getattr(approx, name)(*[float(a) for a in args])[2] + regime = "shape 1e8" if args[0] == 1e8 else "typical" + report.add( + "approx", + name, + f"variance of parent age, {regime}", + "value", + va, + 1, + "negative = lost", + ) + rng = np.random.default_rng(1) + count, total = 0, 200 if quick else 2000 + for _ in range(total): + a_i, a_j = rng.uniform(0.5, 30, 2) + b_i, b_j = log_uniform(rng, -5, -2, 2) + y, mu = float(rng.integers(0, 12)), log_uniform(rng, -4, -2) + result = approx.moments(a_i, b_i, a_j, b_j, y, mu) + count += not (result[2] > 0 and result[4] > 0) + report.add( + "approx", + "moments", + "non-positive variance, typical EP range", + "count", + count, + total, + ) + count = 0 + for _ in range(total): + a_i, a_j = rng.uniform(0.5, 30, 2) + b_i, b_j = log_uniform(rng, -5, -2, 2) + y, mu = float(rng.integers(0, 12)), log_uniform(rng, -4, -2) + pr = approx.mutation_unphased_moments(a_i, b_i, a_j, b_j, y, mu)[0] + count += not (0 <= pr <= 1) + report.add( + "approx", + "mutation_unphased_moments", + "probability outside [0, 1], typical EP range", + "count", + count, + total, + ) + + +def main(): + p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + p.add_argument("--quick", action="store_true", help="fewer points, skip slow rows") + p.add_argument("--only", nargs="+", default=None, help="substrings of group names") + p.add_argument("--seed", type=int, default=1) + p.add_argument("--output", default=None, help="CSV file name, written to results/") + args = p.parse_args() + rng = np.random.default_rng(args.seed) + report = Report() + steps = { + "polygamma": lambda: polygamma(report), + "betaln": lambda: betaln(report), + "gammainc": lambda: ( + gammainc_der(report), + gammainc_inv(report, rng, args.quick), + ), + "hyperu": lambda: hyperu(report), + "hyp1f1": lambda: hyp1f1(report), + "hyp2f1": lambda: hyp2f1(report, args.quick), + "approx": lambda: ( + gamma_fits(report, rng, args.quick), + moment_functions(report, args.quick), + ), + } + for name, step in steps.items(): + if args.only is None or any(o in name for o in args.only): + step() + report.print() + if args.output: + RESULTS.mkdir(exist_ok=True) + path = RESULTS / args.output + report.write(path) + print("\nwrote", path) + + +if __name__ == "__main__": + main() diff --git a/tests/test_oracle_approx.py b/tests/test_oracle_approx.py new file mode 100644 index 00000000..159e9df4 --- /dev/null +++ b/tests/test_oracle_approx.py @@ -0,0 +1,815 @@ +""" +Parity of each implementation (``impl``) with the oracles in ``oracle/approx.py`` for +``tsdate.approx``: values to 4 ulp, NaN and infinity patterns, and which exception is +raised. Expected values always come from the oracle. Tables hold deliberate edge cases +(boundaries of the ``_valid_*`` checks, degenerate gamma fits, regimes of the moment and +projection functions); seeded random draws cover ranges typical of expectation +propagation (EP) and extreme ones. + +Conventions of the C port pinned here: a NaN result (not an exception) signals a +parameter outside the valid region of the hypergeometric function; the ``*_projection`` +functions then return NaN and, except for the ``mutation_*`` ones, their input +parameters unchanged; ``AssertionError`` signals a violated precondition (a fixed node +age that is not positive, or a Laplace root on the boundary); ``ZeroDivisionError`` +signals float division by zero; ``KLMinimizationFailedError`` signals a failed gamma +fit. Accuracy of the approximations is measured in ``evaluation/numerical_accuracy.py``. +""" + +import math + +import numpy as np +import pytest +import scipy.special +from oracle import approx +from oracle.helpers import ( + INF, + NAN, + assert_outcome, + compare, + expected_error, + kind, + log_uniform, + outcome, +) + +from tsdate.approx import KLMinimizationFailedError + +nextafter = np.nextafter +MAX = np.finfo(np.float64).max +TINY = 5e-324 + + +def parity(impl, name, args, expected_kind=None): + """ + Compare ``tsdate.approx.(*args)`` with the oracle (returning the oracle's + outcome); optionally check its kind. + """ + func = getattr(impl.approx, name) + oracle = getattr(approx, name) + if expected_kind is None: + return compare(func, oracle, *args) + return assert_outcome(func, oracle, args, expected_kind) + + +def table(name, rows): + """``pytest.param`` rows of ``(name, args, expected_kind)`` with readable ids""" + return [pytest.param(name, args, kind, id=f"{name}{args}") for args, kind in rows] + + +def floats(args): + return tuple(float(a) for a in args) + + +def natural(shape, rate): + """Natural parameters of a gamma""" + return np.array([shape - 1.0, rate]) + + +def gamma_quantiles(shape, rate, q1=0.25, q2=0.75): + x1, x2 = scipy.special.gammaincinv(shape, [q1, q2]) / rate + return q1, q2, float(x1), float(x2) + + +# --- validity checks --- # + +MOMENTS_VALID = [ + ((1.0, 1.0), True), + ((TINY, TINY), True), # just inside + ((MAX, MAX), True), + ((0.0, 1.0), False), # at the boundary + ((1.0, 0.0), False), + ((-0.0, 1.0), False), + ((1.0, -0.0), False), + ((nextafter(0.0, 1.0), 1.0), True), + ((1.0, nextafter(0.0, 1.0)), True), + ((nextafter(0.0, -1.0), 1.0), False), # just outside + ((1.0, nextafter(0.0, -1.0)), False), + ((-1.0, 1.0), False), + ((1.0, -1.0), False), + ((INF, 1.0), False), + ((1.0, INF), False), + ((-INF, 1.0), False), + ((NAN, 1.0), False), + ((1.0, NAN), False), +] + +HYP1F1 = [ + ((1.0, 1.0, 0.0), True), # b == a is allowed + ((1.0, nextafter(1.0, 0.0), 0.0), False), # b just below a + ((1.0, nextafter(1.0, 2.0), 0.0), True), + ((TINY, 1.0, 0.0), True), # a just above zero + ((0.0, 1.0, 0.0), False), + ((-0.0, 1.0, 0.0), False), + ((nextafter(0.0, -1.0), 1.0, 0.0), False), + ((1.0, 2.0, 1e300), True), # z may have any sign and size + ((1.0, 2.0, -1e300), True), + ((1.0, 2.0, TINY), True), + ((1.0, 2.0, INF), False), + ((1.0, 2.0, -INF), False), + ((1.0, 2.0, NAN), False), + ((NAN, 2.0, 0.0), False), + ((1.0, NAN, 0.0), False), + ((INF, INF, 0.0), False), + ((1.0, INF, 0.0), False), + ((MAX, MAX, 0.0), True), +] + +HYPERU = [ + ((1.0, 1.0, 1.0), False), # b == a is not allowed here (unlike hyp1f1) + ((1.0, nextafter(1.0, 2.0), 1.0), True), + ((1.0, nextafter(1.0, 0.0), 1.0), False), + ((TINY, 1.0, 1.0), True), + ((0.0, 1.0, 1.0), False), + ((-0.0, 1.0, 1.0), False), + ((1.0, 2.0, 0.0), False), # z == 0 + ((1.0, 2.0, -0.0), False), + ((1.0, 2.0, TINY), True), # z just above zero + ((1.0, 2.0, nextafter(0.0, -1.0)), False), + ((1.0, 2.0, -1.0), False), + ((1.0, 2.0, 1e300), True), + ((1.0, 2.0, INF), False), + ((1.0, 2.0, NAN), False), + ((NAN, 2.0, 1.0), False), + ((1.0, INF, 1.0), False), + ((INF, INF, 1.0), False), +] + + +def z_below_one(z): + """The condition on z: below one, or for z < 0 that ``z / (z - 1)`` is below one""" + return bool(z / (z - 1) < 1.0 if z < 0.0 else z < 1.0) + + +def hyp2f1_rows(): + """``(args, expected)`` for ``_valid_hyp2f1``: a, b, c positive and finite, z < 1""" + rows = [((1.0, 1.0, 1.0, 0.0), True), ((10.0, 1.0, 1.0, 0.5), True)] # a > c is ok + for i in range(3): + for z in [0.5, -0.0]: + for bad, valid in [(0.0, False), (-0.0, False), (TINY, True)]: + abc = [1.0, 1.0, 1.0] + abc[i] = bad + rows.append(((*abc, z), valid)) + for bad in [INF, NAN, -TINY]: + abc = [1.0, 1.0, 1.0] + abc[i] = bad + rows.append(((*abc, 0.5), False)) + zs = [0.0, -0.0, TINY, 0.5, 1 - 2.0**-53, 1.0, 1 + 2.0**-52, 2.0] + zs += [NAN, INF, -INF, -1.0, -1e15] + rows += [((1.0, 2.0, 3.0, z), z_below_one(z)) for z in zs] + # NOTE: current behaviour, possibly a bug: for z < 0 the check + # z / (z - 1) < 1 fails once z - 1 rounds to z, and between -2**53 and -2**54 it + # alternates with the last bit of z + big = 2.0**53 + zs = [-(big - 2), -(big - 1), -big, -(big + 2), -(big + 4), -(big + 6), -9e15] + zs += [-(2 * big - 2), -2 * big, -(2 * big + 4), -1e17, -1e300, -MAX] + return rows + [((1.0, 2.0, 3.0, z), z_below_one(z)) for z in zs] + + +VALID = ( + [ + (n, args, v) + for n in ["_valid_moments", "_valid_gamma"] + for args, v in MOMENTS_VALID + ] + + [("_valid_hyp1f1", args, v) for args, v in HYP1F1] + + [("_valid_hyperu", args, v) for args, v in HYPERU] + + [("_valid_hyp2f1", args, v) for args, v in hyp2f1_rows()] +) + + +class TestValidChecks: + """ + Boundaries of the ``_valid_*`` checks, at and either side. Each of them is the + gate that turns unusable moments or hypergeometric parameters into NaN. + """ + + @pytest.mark.parametrize( + ("name", "args", "expected"), + [pytest.param(*row, id=f"{row[0]}{row[1]}") for row in VALID], + ) + def test_valid(self, impl, name, args, expected): + result = parity(impl, name, args) + assert bool(result.value) is expected + + +# --- gamma approximations --- # + +LOG_MOMENTS = [ + ((1.0, 1.0), "finite"), + ((1e300, 1e300), "finite"), + ((1e-100, 1e-100), "finite"), + ((0.0, 1.0), AssertionError), + ((1.0, 0.0), AssertionError), + ((-1.0, 1.0), AssertionError), + ((1.0, -1.0), AssertionError), + ((NAN, 1.0), AssertionError), + ((1.0, NAN), AssertionError), + ((INF, 1.0), "nan"), + ((1.0, INF), "nonfinite"), + ((1e-300, 1e-300), ZeroDivisionError), # mean**2 underflows + ((TINY, 1.0), ZeroDivisionError), + ((1e-200, 1.0), ZeroDivisionError), +] + +GAMMA_KL = [ + # (x, logx, expected kind); `gap` = log(x) - logx must be positive (Jensen) + ((1.0, 0.0), KLMinimizationFailedError), # gap == 0 + ((1.0, nextafter(0.0, -1.0)), "nonfinite"), # smallest gap: alpha, rate overflow + ((1.0, -1e-300), "finite"), + ((1.0, -1e-17), "finite"), + ((1.0, -1e-10), "finite"), + ((1.0, -4e-5), "finite"), + ((1.0, -0.5), "finite"), + ((1.0, -1.0), "finite"), # shape < 1 + ((1.0, -10.0), "finite"), + ((1.0, -1e10), "finite"), + ((1.0, -1e160), "finite"), + ((1.0, -1e164), ZeroDivisionError), # shape bound ~1e-164: trigamma divides by 0 + ((1.0, -1e300), ZeroDivisionError), + ((1.0, -INF), KLMinimizationFailedError), + ((1.0, INF), KLMinimizationFailedError), + ((1.0, NAN), KLMinimizationFailedError), # not (log x > nan) + ((0.0, -1.0), KLMinimizationFailedError), + ((-1.0, -1.0), KLMinimizationFailedError), + ((-0.0, -1.0), KLMinimizationFailedError), + ((NAN, -1.0), KLMinimizationFailedError), + ((INF, -1.0), ZeroDivisionError), # alpha = 0.5 / inf = 0 + ((INF, INF), KLMinimizationFailedError), + ((1e-300, -1.0), KLMinimizationFailedError), # log x = -690 < logx + ((1e-300, -700.0), "finite"), + ((TINY, -745.0), "nonfinite"), # rate = alpha / x overflows + ((1e300, 1.0), "finite"), + ((1e300, 690.0), "finite"), + ((1e308, 709.0), "finite"), + ((2.0, 0.5), "finite"), + ((100.0, math.log(100.0) - 1.0), "finite"), + ((1e5, math.log(1e5) - 0.5e-4), "finite"), + ((1e5, math.log(1e5) - 0.5e-8), "finite"), +] + +GAMMA_MOM = [ + ((1.0, 1.0), "finite"), + ((1.0, 0.0), KLMinimizationFailedError), + ((0.0, 1.0), KLMinimizationFailedError), + ((-0.0, 1.0), KLMinimizationFailedError), + ((-1.0, 1.0), KLMinimizationFailedError), + ((1.0, -1.0), KLMinimizationFailedError), + ((NAN, 1.0), KLMinimizationFailedError), + ((1.0, NAN), KLMinimizationFailedError), + ((TINY, TINY), "finite"), + ((1.0, 1e-300), "finite"), # shape 1e300 + ((1.0, TINY), "nonfinite"), # shape overflows + ((INF, 1.0), "nonfinite"), + ((1.0, INF), "finite"), # shape 0 - 1 + ((INF, INF), "nan"), + # NOTE: current behaviour, possibly a bug: mean**2 underflows, shape -1 + ((1e-200, 1e-200), "finite"), + ((1e200, 1e200), "nonfinite"), # mean**2 overflows + ((1e154, 1.0), "finite"), + ((1.0, 1e300), "finite"), + ((1e8, 1.0), "finite"), + ((1e3, 1e-6), "finite"), +] + + +GAMMA_IQR_ERRORS = [ + ((0.25, 0.75, 2.0, 1.0, 50.0), KLMinimizationFailedError), # x unsorted + ((0.75, 0.25, 1.0, 2.0, 50.0), KLMinimizationFailedError), # q unsorted + ((0.25, 0.25, 1.0, 2.0, 50.0), KLMinimizationFailedError), # q equal + ((0.25, 0.75, 1.0, NAN, 50.0), KLMinimizationFailedError), + ((NAN, 0.75, 1.0, 2.0, 50.0), KLMinimizationFailedError), + ((0.25, 0.75, 0.0, 1.0, 50.0), ZeroDivisionError), # log(x2 / 0) + ((0.0, 0.75, 1.0, 2.0, 50.0), ZeroDivisionError), # log(q2 / 0) + ((0.25, 0.75, -1.0, 1.0, 50.0), KLMinimizationFailedError), + ((0.25, 1.0, 1.0, 2.0, 50.0), KLMinimizationFailedError), # q2 == 1: negative shape + ((0.25, 0.75, 1.0, INF, 50.0), AssertionError), + ((0.25, 0.75, 0.0, 0.0, 50.0), ZeroDivisionError), # x1 == x2 == 0 + # the shape is capped at max_shape when x1 == x2, when the lower bound exceeds it + # or when Newton's iteration ends above it + ((0.25, 0.75, 3.0, 3.0, 50.0), "finite"), + ((0.25, 0.75, 1.0, 1.000001, 1e5), "finite"), + # the gradient vanishes with a high cap: the update divides by zero + ((0.25, 0.75, 1.0, 1.0001, 1e6), ZeroDivisionError), + # NOTE: current behaviour, possibly a bug: max_shape is not validated + ((*gamma_quantiles(2.0, 1.0), 0.0), "nan"), + ((*gamma_quantiles(2.0, 1.0), -1.0), "nan"), + ((*gamma_quantiles(2.0, 1.0), 1.0), "finite"), + ((*gamma_quantiles(2.0, 1.0), INF), "finite"), + # NOTE: current behaviour, possibly a bug: the lower quantile of a + # gamma with tiny shape underflows to zero, so the fit divides by zero + ((*gamma_quantiles(1e-3, 1.0), 50.0), ZeroDivisionError), +] +# shapes below, at and above the cap, and beyond the range where `_gammainc_der` uses +# its gaussian approximation (shape > 1e3) +GAMMA_IQR_FITS = [ + (shape, max_shape) + for shape in [0.01, 0.5, 1.0, 10.0, 49.0, 50.0, 51.0, 999.0, 1001.0, 1e4, 1e8] + for max_shape in [10.0, 50.0, 1000.0, 1e5] +] + +AVERAGE_GAMMAS = { + "single": ([1.0], [1.0], "finite"), + "pair": ([0.5, 1.5], [1.0, 1.0], "finite"), + "identical": ([1.0, 1.0], [1.0, 1.0], "finite"), + "tiny shape": ([1e-10], [1.0], "finite"), + "huge shapes": ([1e8, 1e8], [1.0, 1e-3], "finite"), + "mixed shapes": ([0.5, 1e6], [1.0, 1e-3], "finite"), + "wide rates": ([1.0, 2.0], [1e-300, 1e300], "finite"), + "shape+1 near zero": ([-1.0 + 1e-10, 4.0], [1.0, 2.0], "finite"), + "shape+1 zero": ([-1.0], [1.0], ZeroDivisionError), # digamma pole + "shape+1 negative": ([-2.0], [1.0], KLMinimizationFailedError), + "zero rate": ([1.0], [0.0], ZeroDivisionError), + "negative rate": ([1.0], [-1.0], KLMinimizationFailedError), + "nan shape": ([NAN], [1.0], KLMinimizationFailedError), + "inf shape": ([INF], [1.0], KLMinimizationFailedError), + "empty": ([], [], ZeroDivisionError), + "size mismatch": ([1.0], [1.0, 2.0], AssertionError), +} + +GAMMA_DOMAIN = ( + table("approximate_log_moments", LOG_MOMENTS) + + table("approximate_gamma_kl", GAMMA_KL) + + table("approximate_gamma_mom", GAMMA_MOM) + + table("approximate_gamma_iqr", GAMMA_IQR_ERRORS) +) + + +class TestGammaApproximations: + @pytest.mark.parametrize(("name", "args", "expected"), GAMMA_DOMAIN) + def test_domain(self, impl, name, args, expected): + parity(impl, name, args, expected) + + @pytest.mark.parametrize( + ("name", "args", "expected"), + [p for p in GAMMA_DOMAIN if p.values[2] is KLMinimizationFailedError], + ) + def test_error_messages(self, impl, name, args, expected): + # the messages distinguish the failure modes; the port re-raises them + func = getattr(impl.approx, name) + with pytest.raises(expected_error(KLMinimizationFailedError)): + func(*args) + compare(func, getattr(approx, name), *args) + + @pytest.mark.parametrize("gap", [1e-17, 1e-10, 4e-5, 4.99e-5, 5e-5, 6e-5, 1e-3]) + def test_kl_asymptotic_threshold(self, impl, gap): + # for alpha > 1e4 (gap < 5e-5) the lower bound alpha = 0.5 / gap is returned + # without iterating; above, Newton's iteration refines it + result = parity(impl, "approximate_gamma_kl", (1.0, -gap), "finite") + shape = result.value[0] + if gap < 5e-5: + assert shape + 1.0 == 0.5 / gap + else: + assert shape + 1.0 != 0.5 / gap + + @pytest.mark.parametrize(("shape", "max_shape"), GAMMA_IQR_FITS, ids=repr) + def test_iqr_fits(self, impl, shape, max_shape): + args = (*gamma_quantiles(shape, 0.001), max_shape) + parity(impl, "approximate_gamma_iqr", args, "finite") + + +class TestAverageGammas: + @pytest.mark.parametrize("label", list(AVERAGE_GAMMAS)) + def test_cases(self, impl, label): + shapes, rates, expected = AVERAGE_GAMMAS[label] + args = np.array(shapes, dtype=float), np.array(rates, dtype=float) + parity(impl, "average_gammas", args, expected) + + +# --- moments and projections --- # + +# regimes for functions of two free nodes: (a_i, b_i, a_j, b_j, y, mu), with the gamma +# shapes a_i, a_j, rates b_i, b_j, mutation count y and rate mu. With t = mu + b_i and +# z = (mu - b_j) / t the hypergeometric argument is z (parent above child) or 1 - z +# (unphased). +TWO_NODE = { + "typical": (10, 0.01, 10, 0.01, 1, 1e-4), + "y=0": (10, 0.01, 10, 0.01, 0, 1e-4), + "y=100": (10, 0.01, 10, 0.01, 100, 1e-3), + "y=1e4": (10, 0.01, 10, 0.01, 1e4, 1e-3), + "mu=1e-12": (10, 0.01, 10, 0.01, 1, 1e-12), + "mu=0": (10, 0.01, 10, 0.01, 0, 0.0), + "mu=1e6": (10, 0.01, 10, 0.01, 1, 1e6), + "shapes=1e4": (1e4, 10, 1e4, 10, 1, 1e-4), + # NOTE: current behaviour, possibly a bug: the variance is a difference + # of the second moment and the squared mean, and goes negative at huge shapes + "shapes=1e8": (1e8, 1e5, 1e8, 1e5, 1, 1e-4), + "shapes=1e-3": (1e-3, 1e-5, 1e-3, 1e-5, 1, 1e-4), + "rates=1e-12": (10, 1e-12, 10, 1e-12, 1, 1e-14), + "rates=1e8": (10, 1e8, 10, 1e8, 1, 1e5), + "t=0": (10, -1e-4, 10, 0.01, 1, 1e-4), + "t<0": (10, -1e-3, 10, 0.01, 1, 1e-4), + "t=1e-20": (10, nextafter(-1e-4, 0.0), 10, 0.01, 1, 1e-4), + "z=1": (10, 0.01, 10, -0.01, 1, 1e-4), + "z=1-1e-10": (10, 0.01, 10, -0.01 + 1e-12, 1, 1e-4), + "z>1": (10, 0.01, 10, -0.02, 1, 1e-4), + "z=0": (10, 0.01, 10, 1e-4, 1, 1e-4), + "z=-1e9": (10, 0.01, 10, 1e9, 1, 1e-4), + "z=-1e5": (10, 0.01, 10, 1e3, 1, 1e-4), + "a_j=0": (10, 0.01, 0, 0.01, 1, 1e-4), + "a_j=1e-8": (10, 0.01, 1e-8, 0.01, 1, 1e-4), + "a_i=1e8, a_j=1": (1e8, 0.01, 1, 0.01, 1, 1e-4), + "b_j<0 (damped)": (10, 0.01, 10, -0.005, 1, 1e-4), + "b_j=inf": (10, 0.01, 10, INF, 1, 1e-4), +} + +# regimes for a fixed node and one free node: (t, a, b, y, mu) with the free node's +# shape a, rate b; t is the fixed age (child for rootward, parent otherwise). +ONE_NODE = { + "typical": (1000, 10, 0.01, 1, 1e-4), + "y=0": (1000, 10, 0.01, 0, 1e-4), + "y=1e4": (1000, 10, 0.01, 1e4, 1e-3), + "t=1e-10": (1e-10, 10, 0.01, 1, 1e-4), + "t=5e-324": (TINY, 10, 0.01, 1, 1e-4), + "t=1e10": (1e10, 10, 0.01, 1, 1e-4), + "t=0": (0.0, 10, 0.01, 1, 1e-4), + "t=-0": (-0.0, 10, 0.01, 1, 1e-4), + "t<0": (-1.0, 10, 0.01, 1, 1e-4), + "t=nan": (NAN, 10, 0.01, 1, 1e-4), + "t=inf": (INF, 10, 0.01, 1, 1e-4), + "mu=1e-14": (1000, 10, 0.01, 1, 1e-14), + "mu=1e5": (1000, 10, 0.01, 1, 1e5), + "mu=0": (1000, 10, 0.01, 0, 0.0), + "shapes=1e4": (1000, 1e4, 10, 1, 1e-4), + "shapes=1e8": (1000, 1e8, 1e5, 1, 1e-4), + "shapes=1e-3": (1000, 1e-3, 1e-5, 1, 1e-4), + "rates=1e-12": (1000, 10, 1e-12, 1, 1e-14), + "rates=1e8": (1e-5, 10, 1e8, 1, 1e5), + "rate+mu=0": (1000, 10, -1e-4, 1, 1e-4), + "rate+mu<0": (1000, 10, -1e-3, 1, 1e-4), + "rate<0, rate+mu>0": (1000, 10, -5e-5, 1, 1e-4), + "a=0": (1000, 0, 0.01, 1, 1e-4), + "a<0": (1000, -1, 0.01, 1, 1e-4), + # NOTE: current behaviour, possibly a bug: y = -1 passes + # `_valid_hyp1f1` (b == a) but `_hyp1f1_laplace` asserts b > a + "y=-1": (1000, 10, 0.01, -1, 1e-4), + "y=-0.5": (1000, 10, 0.01, -0.5, 1e-4), +} + +# (a_i, b_i, y, mu): a node above both edges of an unphased individual +TWIN = { + "typical": (10, 0.01, 1, 1e-4), + "y=0": (10, 0.01, 0, 1e-4), + "mu=0": (10, 0.01, 0, 0.0), + "shapes=1e8": (1e8, 1e5, 1, 1e-4), + "shapes=1e-3": (1e-3, 1e-5, 1, 1e-4), + "rates=1e-12": (10, 1e-12, 1, 1e-14), + "rates=1e8": (10, 1e8, 1, 1e5), + "r=0": (10, -2e-4, 1, 1e-4), # r = b_i + 2 mu + "r<0": (10, -1e-3, 1, 1e-4), + "r=1e-300": (10, 1e-300, 1, 0.0), + "s=0": (0, 0.01, 0, 1e-4), # s = a_i + y + "s<0": (-1, 0.01, 0, 1e-4), + "a_i=nan": (NAN, 0.01, 1, 1e-4), + "a_i=inf": (INF, 0.01, 1, 1e-4), + "y=1e300": (10, 0.01, 1e300, 1e-4), + "mu=1e300": (10, 0.01, 1, 1e300), +} + +# (t_i, t_j): fixed parent and child ages +TIMES = { + "3,1": (3, 1), + "1,3 (child older)": (1, 3), + # NOTE: current behaviour, possibly a bug: equal ages give zero variance, so the + # edge projection is NaN, but inverted ages (1,3) give a valid result + "equal": (1, 1), + "0,0": (0, 0), + "0,1": (0, 1), + "1,0": (1, 0), + "-0,1": (-0.0, 1), + # NOTE: current behaviour, possibly a bug: edge moments do not check the ages + "neg,1": (-1, 1), + "1,neg": (1, -1), + "1e200,1e-200": (1e200, 1e-200), + "1e300,1": (1e300, 1), + "1e308,1e307": (1e308, 1e307), + "1e-200,1e-210": (1e-200, 1e-210), + "1e-160,1e-170": (1e-160, 1e-170), + "5e-324,5e-324": (TINY, TINY), + "1,1-eps": (1.0, nextafter(1.0, 0.0)), + "nan,1": (NAN, 1), + "inf,1": (INF, 1), + "inf,inf": (INF, INF), +} + + +TWO_NODE_MOMENTS = ["moments", "unphased_moments", "mutation_moments"] +TWO_NODE_MOMENTS += ["mutation_unphased_moments"] +ONE_NODE_MOMENTS = ["rootward_moments", "mutation_rootward_moments", "leafward_moments"] +ONE_NODE_MOMENTS += ["mutation_leafward_moments", "sideways_moments"] +ONE_NODE_MOMENTS += ["mutation_sideways_moments"] +TWIN_MOMENTS = ["twin_moments", "mutation_twin_moments"] +TIMES_MOMENTS = ["mutation_edge_moments", "mutation_block_moments"] + +# the regimes (inputs of the moment function) in which each moment function is called +REGIMES = { + **{name: TWO_NODE for name in TWO_NODE_MOMENTS}, + **{name: ONE_NODE for name in ONE_NODE_MOMENTS}, + **{name: TWIN for name in TWIN_MOMENTS}, + **{name: TIMES for name in TIMES_MOMENTS}, +} + +# For each projection: the moment function it wraps and the checks it applies to the +# moments before fitting a gamma. `pairs` indexes (mean, variance) in the result of +# the moment function; `prob` indexes a probability that must lie in [0, 1]. +PROJECTIONS = { + "gamma_projection": ("moments", [(1, 2), (3, 4)], None), + "unphased_projection": ("unphased_moments", [(1, 2), (3, 4)], None), + "rootward_projection": ("rootward_moments", [(1, 2)], None), + "leafward_projection": ("leafward_moments", [(1, 2)], None), + "sideways_projection": ("sideways_moments", [(1, 2)], None), + "twin_projection": ("twin_moments", [(1, 2)], None), + "mutation_gamma_projection": ("mutation_moments", [(0, 1)], None), + "mutation_rootward_projection": ("mutation_rootward_moments", [(0, 1)], None), + "mutation_leafward_projection": ("mutation_leafward_moments", [(0, 1)], None), + "mutation_edge_projection": ("mutation_edge_moments", [(0, 1)], None), + "mutation_unphased_projection": ("mutation_unphased_moments", [(1, 2)], 0), + "mutation_sideways_projection": ("mutation_sideways_moments", [(1, 2)], 0), + "mutation_twin_projection": ("mutation_twin_moments", [(1, 2)], 0), + "mutation_block_projection": ("mutation_block_moments", [(1, 2)], 0), +} +# projections that return their input parameters unchanged when the moments are invalid +RETURNS_INPUT = { + "gamma_projection", + "unphased_projection", + "rootward_projection", + "leafward_projection", + "sideways_projection", + "twin_projection", +} + + +def projection_args(name, args): + """ + Arguments of a projection from the arguments of the moment function it wraps + (shapes, not natural parameters). + """ + moments = PROJECTIONS[name][0] + if moments in TWO_NODE_MOMENTS: + a_i, b_i, a_j, b_j, y, mu = args + return natural(a_i, b_i), natural(a_j, b_j), np.array([y, mu]) + if moments in TWIN_MOMENTS: + a_i, b_i, y, mu = args + return natural(a_i, b_i), np.array([y, mu]) + if moments in TIMES_MOMENTS: + return tuple(args) + t, a, b, y, mu = args + return t, natural(a, b), np.array([y, mu]) + + +def moment_args(name, proj_args): + """ + The arguments the projection passes to its moment function: shapes are recovered + from the natural parameters, so tiny shapes differ from the original by rounding. + """ + moments = PROJECTIONS[name][0] + if moments in TWO_NODE_MOMENTS: + pars_i, pars_j, (y, mu) = proj_args + return pars_i[0] + 1, pars_i[1], pars_j[0] + 1, pars_j[1], y, mu + if moments in TWIN_MOMENTS: + pars_i, (y, mu) = proj_args + return pars_i[0] + 1, pars_i[1], y, mu + if moments in TIMES_MOMENTS: + return proj_args + t, pars, (y, mu) = proj_args + return t, pars[0] + 1, pars[1], y, mu + + +def is_valid(mean, variance, prob=None): + if prob is not None and not (0 <= prob <= 1): + return False + return bool(np.isfinite(mean) and np.isfinite(variance) and mean > 0 and variance > 0) + + +def check_projection(impl, name, args): + """ + Compare a projection with the oracle, and check the contract on the oracle's + result: the projection raises as its moment function does; otherwise it is NaN + exactly when the moments are unusable (non-finite, non-positive, or a probability + outside [0, 1]), and on NaN the non-mutation projections return the input + parameters unchanged and the mutation ones NaN. + """ + moments, pairs, prob_index = PROJECTIONS[name] + proj_args = projection_args(name, args) + result = parity(impl, name, proj_args) + moment_result = outcome(getattr(approx, moments), *moment_args(name, proj_args)) + if moment_result.exception is not None: + assert type(result.exception) is type(moment_result.exception) + return + values = moment_result.value + prob = values[prob_index] if prob_index is not None else None + expected_nan = not all(is_valid(values[i], values[j], prob) for i, j in pairs) + assert kind(result) != "nan" or expected_nan + if not expected_nan: + assert not np.isnan(result.value[0]) + return + assert np.isnan(result.value[0]) + if name in RETURNS_INPUT: + given = [p for p in proj_args if isinstance(p, np.ndarray)] + for returned, original in zip(result.value[1:], given): + np.testing.assert_array_equal(returned, original) + else: + assert np.isnan(result.value[1]).all() + + +MOMENT_REGIMES = [ + pytest.param(name, label, id=f"{name}-{label}") + for name, regimes in REGIMES.items() + for label in regimes +] +PROJECTION_REGIMES = [ + pytest.param(name, label, id=f"{name}-{label}") + for name, (moments, _, _) in PROJECTIONS.items() + for label in REGIMES[moments] +] + + +class TestMoments: + @pytest.mark.parametrize(("name", "label"), MOMENT_REGIMES) + def test_regimes(self, impl, name, label): + parity(impl, name, floats(REGIMES[name][label])) + + +class TestProjections: + @pytest.mark.parametrize(("name", "label"), PROJECTION_REGIMES) + def test_regimes(self, impl, name, label): + moments = PROJECTIONS[name][0] + check_projection(impl, name, floats(REGIMES[moments][label])) + + @pytest.mark.parametrize("name", list(PROJECTIONS)) + def test_inputs_are_not_modified(self, impl, name): + moments = PROJECTIONS[name][0] + first_regime = next(iter(REGIMES[moments].values())) + proj_args = projection_args(name, floats(first_regime)) + copies = [a.copy() if isinstance(a, np.ndarray) else a for a in proj_args] + getattr(impl.approx, name)(*proj_args) + for arg, copy in zip(proj_args, copies): + np.testing.assert_array_equal(arg, copy) + + def test_unphased_probability_out_of_range(self, impl): + # NOTE: current behaviour, possibly a bug: the Laplace + # approximation can give a probability above one for finite mean and variance, + # which the projection turns into NaN + args = ( + 1289.8261024396659, + 2.1161296052067344, + 0.15552864791315738, + 0.0007984796762152916, + 1.0, + 4.811169071413665e-07, + ) + parity(impl, "mutation_unphased_moments", args, "finite") + name = "mutation_unphased_projection" + parity(impl, name, projection_args(name, args), "nan") + + +# --- seeded random draws --- # + + +def flip_sign(rng, values, prob=0.12): + """Negate one of ``values`` with probability ``prob``, to give invalid input.""" + values = list(values) + if rng.random() < prob: + i = rng.integers(len(values)) + values[i] = -values[i] + return values + + +def draw_gamma(rng): + """Shape and rate of a node age""" + return float(rng.uniform(0.5, 30)), log_uniform(rng, -5, -2) + + +def draw_edge(rng): + """Mutation count and mutational target size on an edge""" + return float(rng.integers(0, 12)), log_uniform(rng, -4, -2) + + +def draw_two_node(rng, extreme): + if extreme: + a_i, b_i, a_j, b_j = (log_uniform(rng, -8, 8) for _ in range(4)) + b_i *= float(rng.choice([-1.0, 1.0, 1.0, 1.0])) + b_j *= float(rng.choice([-1.0, 1.0, 1.0, 1.0])) + y = float(rng.choice([0, 0, 1, 2, 5, 100, 1e4])) + return a_i, b_i, a_j, b_j, y, log_uniform(rng, -12, 3) + a_i, b_i = draw_gamma(rng) + a_j, b_j = draw_gamma(rng) + y, mu = draw_edge(rng) + return (*flip_sign(rng, [a_i, b_i, a_j, b_j]), y, mu) + + +def draw_one_node(rng, extreme): + t = 0.0 if rng.random() < (0.15 if extreme else 0.1) else None + if extreme: + t = log_uniform(rng, -6, 8) if t is None else t + a, b = log_uniform(rng, -8, 8), log_uniform(rng, -8, 8) + b *= float(rng.choice([-1.0, 1.0, 1.0, 1.0])) + y = float(rng.choice([0, 0, 1, 2, 5, 100, 1e4])) + return t, a, b, y, log_uniform(rng, -12, 3) + t = log_uniform(rng, 0, 4) if t is None else t + a, b = flip_sign(rng, draw_gamma(rng)) + return (t, a, b, *draw_edge(rng)) + + +def draw_twin(rng, extreme): + if extreme: + a_i, b_i = log_uniform(rng, -8, 8), log_uniform(rng, -8, 8) + b_i *= float(rng.choice([-1.0, 1.0, 1.0])) + y = float(rng.choice([0, 1, 5, 1e6])) + return a_i, b_i, y, log_uniform(rng, -12, 3) + a_i, b_i = flip_sign(rng, draw_gamma(rng)) + return (a_i, b_i, *draw_edge(rng)) + + +def draw_times(rng, extreme): + lo, hi = (-6, 8) if extreme else (0, 4) + return log_uniform(rng, lo, hi), log_uniform(rng, lo, hi) + + +DRAW_GEOMETRY = { + **{name: draw_two_node for name in TWO_NODE_MOMENTS}, + **{name: draw_one_node for name in ONE_NODE_MOMENTS}, + **{name: draw_twin for name in TWIN_MOMENTS}, + **{name: draw_times for name in TIMES_MOMENTS}, +} + + +def draw_log_moments(rng): + mean = log_uniform(rng, -1, 4) + return mean, mean**2 * log_uniform(rng, -3, 0) + + +def draw_gamma_kl(rng): + # log E[x] > E[log x] by Jensen; sometimes violated or nonpositive + x = log_uniform(rng, -2, 4) + gap = log_uniform(rng, -4, 1) + if rng.random() < 0.1: + gap = -gap + return x, float(np.log(x) - gap) + + +def draw_gamma_mom(rng): + mean = log_uniform(rng, -1, 4) + variance = mean**2 * log_uniform(rng, -3, 1) + return tuple(flip_sign(rng, [mean, variance], 0.1)) + + +def draw_gamma_iqr(rng): + # empirical quantiles of a gamma, so that the shape is recoverable + q1, q2, x1, x2 = gamma_quantiles( + log_uniform(rng, -0.5, 2.5), log_uniform(rng, -5, -2) + ) + max_shape = float(rng.choice([50.0, 1000.0])) + u = rng.random() + if u < 0.05: + x2 = x1 # degenerate, capped shape + elif u < 0.1: + x1, x2 = x2, x1 # unsorted + return q1, q2, x1, x2, max_shape + + +def draw_average_gammas(rng): + n = int(rng.integers(1, 8)) + return rng.uniform(0.5, 30, n) - 1, 10.0 ** rng.uniform(-5, -2, n) + + +MODES = ["typical", "extreme"] +DRAW_HELPERS = { + "approximate_log_moments": draw_log_moments, + "approximate_gamma_kl": draw_gamma_kl, + "approximate_gamma_mom": draw_gamma_mom, + "approximate_gamma_iqr": draw_gamma_iqr, + "average_gammas": draw_average_gammas, +} + +DRAWS = [(name, "typical") for name in DRAW_HELPERS] +DRAWS += [(name, mode) for name in [*REGIMES, *PROJECTIONS] for mode in MODES] + + +class TestRandomDraws: + """ + Seeded draws in ranges typical of EP on tree sequences (gamma shapes of order + 1-30, rates of order 1/(node age), mutation counts 0-12 per edge, a fraction with a + sign flipped so that validity checks fail) and over 16 orders of magnitude + ("extreme", where exceptions, NaN and infinity are common). The failing draw is + named in the assertion. + """ + + @pytest.mark.parametrize("seed", [1, 2, 3]) + @pytest.mark.parametrize(("name", "mode"), DRAWS) + def test_random_draws(self, impl, name, mode, seed): + rng = np.random.default_rng(seed) + extreme = mode == "extreme" + for i in range(30): + if name in DRAW_HELPERS: + args = DRAW_HELPERS[name](rng) + check = parity + elif name in PROJECTIONS: + args = DRAW_GEOMETRY[PROJECTIONS[name][0]](rng, extreme) + check = check_projection + else: + args = DRAW_GEOMETRY[name](rng, extreme) + check = parity + try: + check(impl, name, args) + except AssertionError as e: + raise AssertionError(f"draw {i}: {name}{args}: {e}") from None diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py new file mode 100644 index 00000000..8f8aa9c5 --- /dev/null +++ b/tests/test_oracle_hypergeo.py @@ -0,0 +1,605 @@ +""" +Parity of each implementation (``impl``) with the oracles in ``oracle/hypergeo.py`` +for the special functions in ``tsdate.hypergeo``: values to 4 ulp, NaN and infinity +patterns, and which exception is raised (``AssertionError`` for the domain checks, +``ZeroDivisionError`` for float division by zero). Expected values always come from the +oracle. Tables hold deliberate edge cases (poles, domain boundaries, both sides of a +branch switch); grids and seeded random draws cover the interior and extreme ranges. +Accuracy of the approximations is measured in ``evaluation/numerical_accuracy.py``. +""" + +import numpy as np +import pytest +from oracle import hypergeo +from oracle._libm import lgamma, log +from oracle.helpers import ( + INF, + NAN, + assert_outcome, + assert_ulp_close, + compare, + log_uniform, +) + +nextafter = np.nextafter + + +def parity(impl, name, args, expected_kind=None): + """ + Compare ``tsdate.hypergeo.(*args)`` with the oracle; optionally check kind. + """ + func = getattr(impl.hypergeo, name) + oracle = getattr(hypergeo, name) + if expected_kind is None: + return compare(func, oracle, *args) + return assert_outcome(func, oracle, args, expected_kind) + + +def table(name, rows): + """``pytest.param`` rows of ``(name, args, expected_kind)`` with readable ids""" + return [pytest.param(name, args, kind, id=f"{name}{args}") for args, kind in rows] + + +DIGAMMA_POINTS = [ + 5e-324, + 1e-300, + 1e-10, + 1e-6, + 1e-5, + nextafter(1e-5, 1), # series switch + 1e-4, + nextafter(1e-4, 1), # trigamma switch + 1e-3, + 0.1, + 0.5, + 1.0, + 2.0, + 4.9, + 5.0, + 8.4, + 8.5, # asymptotic series switch + nextafter(8.5, 0), + nextafter(8.5, 9), + 10.0, + 100.0, + 1e4, + 1e8, + 1e15, + 1e100, + 1e300, + 1e308, + INF, + NAN, + 0.0, + -0.0, + -1e-300, + -1e-10, + -1e-5, + -0.1, + -0.5, + -1.0, # reflection formula, poles + -2.0, + -1.0 + 1e-8, + -1.0 - 1e-8, + -1.5, + -2.0 + 1e-12, + -3.0 - 1e-6, + -10.5, + -100.3, + -1e5 - 0.5, + -1e10 - 0.5, + -1e15, + -INF, +] + +POLYGAMMA_KINDS = [ + # poles raise (Python float division); digamma(tiny) is -inf rather than raising, + # trigamma raises for x < ~1e-154 where 1 / x**2 divides by an underflowed zero + ((0.0,), ZeroDivisionError), + ((-0.0,), ZeroDivisionError), + ((5e-324,), "nonfinite"), + ((NAN,), "nan"), + ((-INF,), "nan"), + ((INF,), "nonfinite"), +] +TRIGAMMA_KINDS = [ + ((0.0,), ZeroDivisionError), + ((-0.0,), ZeroDivisionError), + ((1e-300,), ZeroDivisionError), + ((-1e-300,), ZeroDivisionError), + ((5e-324,), ZeroDivisionError), + ((NAN,), "nan"), + ((-INF,), "nan"), + ((INF,), "finite"), +] + + +class TestPolygamma: + @pytest.mark.parametrize("name", ["_digamma", "_trigamma"]) + @pytest.mark.parametrize("x", DIGAMMA_POINTS, ids=repr) + def test_matches_oracle(self, impl, name, x): + parity(impl, name, (x,)) + + @pytest.mark.parametrize( + ("name", "args", "expected"), + table("_digamma", POLYGAMMA_KINDS) + table("_trigamma", TRIGAMMA_KINDS), + ) + def test_poles_and_nonfinite(self, impl, name, args, expected): + parity(impl, name, args, expected) + + +BETALN_POINTS = [ + (1e-300, 1e-300), + (1e-10, 1e-10), + (1e-10, 1e10), # lgamma cancellation + (1e10, 1e-10), + (1e-5, 1e5), + (1e8, 1e-8), + (1.0, 1.0), + (0.5, 0.5), + (1e5, 1e5), + (1e15, 1e15), + (1e100, 1e100), + (1e300, 1e300), + (1e305, 1e305), + (1e308, 1e308), # lgamma overflows + (1e308, 1.0), + (5e-324, 1.0), + (1e-320, 1.0), + (0.0, 1.0), + (1.0, 0.0), + (-1.0, 2.0), + (-0.5, 2.0), + (NAN, 1.0), + (1.0, INF), + (INF, INF), +] + + +class TestBetaln: + @pytest.mark.parametrize(("p", "q"), BETALN_POINTS, ids=repr) + def test_matches_oracle(self, impl, p, q): + parity(impl, "_betaln", (p, q)) + + +# `_gammainc_der(p, x)`: regimes are x == 0, x > 1e8, p > 1e3 (gaussian), +# x <= 1 or x < p (series) and otherwise a continued fraction. +GAMMAINC_DER_POINTS = [ + (1.0, 0.0), + (1.0, 5e-324), + (1.0, 1e-300), + (1.0, 1.0), + (1.0, nextafter(1.0, 2)), + (0.5, 1.0), + (0.5, nextafter(1.0, 2)), + (2.0, 1.5), + (2.0, 2.0), + (2.0, nextafter(2.0, 3)), + (2.0, nextafter(2.0, 0)), + (5.0, 3.0), + (5.0, 5.0), + (5.0, nextafter(5.0, 6)), + (5.0, 50.0), + (5.0, 1e3), + (5.0, 1e8), + (5.0, nextafter(1e8, 2e8)), + (5.0, 1e8 + 1), + (5.0, INF), + (1e-3, 1e-3), + (1e-3, 1.0), + (1e-3, 10.0), + (1e-10, 1e-10), + (1e-300, 1e-300), + (100.0, 100.0), + (100.0, 300.0), + (999.9, 1000.0), + (1000.0, 1000.0), + (nextafter(1000.0, 0), 1000.0), + (nextafter(1000.0, 2000), 1000.0), + (1000.5, 900.0), + (1000.5, 1100.0), + (2000.0, 2000.0), + (2000.0, 2300.0), + (2000.0, 0.0), + (2000.0, 1.0), + (1e5, 1e5), + (1e5, 1.01e5), + (1e7, 1e7), + (1e12, 1e12), + (1e300, 1.0), + (1e300, 1e300), + (INF, 1.0), + (10.0, 1e-30), + (10.0, 0.5), + (1.0, 1e-30), + (50.0, 1e-3), +] + +GAMMAINC_DER_DOMAIN = [ + ((-1.0, 1.0), AssertionError), + ((0.0, 1.0), AssertionError), + ((-0.0, 1.0), AssertionError), + ((1.0, -1.0), AssertionError), + ((1.0, -5e-324), AssertionError), + ((NAN, 1.0), AssertionError), + ((1.0, NAN), AssertionError), +] + + +class TestGammaincDer: + @pytest.mark.parametrize(("p", "x"), GAMMAINC_DER_POINTS, ids=repr) + def test_matches_oracle(self, impl, p, x): + parity(impl, "_gammainc_der", (p, x)) + + @pytest.mark.parametrize( + ("name", "args", "expected"), table("_gammainc_der", GAMMAINC_DER_DOMAIN) + ) + def test_domain(self, impl, name, args, expected): + parity(impl, name, args, expected) + + +def gammainc_inv_grid(): + shapes = [1e-300, 1e-100, 1e-10, 1e-3, 0.1, 0.5, 1.0, 2.0, 10.0, 100.0] + shapes += [1e3, 1e4, 1e5, 1e6, 1e8, 1e10, 1e15, 1e300, INF, 0.0, -1.0, NAN] + quantiles = [0.0, 5e-324, 1e-300, 1e-100, 1e-20, 1e-10, 1e-3, 0.5, 0.999] + quantiles += [1 - 1e-10, nextafter(1.0, 0), 1.0, nextafter(1.0, 2), -0.1, NAN] + return [(a, q) for a in shapes for q in quantiles] + + +class TestGammaincInv: + """ + `_gammainc_inv` wraps SciPy's ``gammaincinv`` (cephes ``igami``): the port has to + reproduce it to 4 ulp, including away from the interior of the domain (the + result is a NaN, 0 or inf for invalid shapes and quantiles, with no exception). + """ + + @pytest.mark.parametrize(("a", "q"), gammainc_inv_grid(), ids=repr) + def test_matches_oracle(self, impl, a, q): + parity(impl, "_gammainc_inv", (a, q)) + + +HYPERU_DOMAIN = [ + ((1.0, 1.0, 1.0), "finite"), # b == a is allowed + ((1.0, nextafter(1.0, 0), 1.0), AssertionError), # b < a + ((0.0, 1.0, 1.0), AssertionError), + ((-0.0, 1.0, 1.0), AssertionError), + ((-1.0, 1.0, 1.0), AssertionError), + ((5e-324, 1.0, 1.0), "finite"), + ((1.0, 2.0, 0.0), AssertionError), + ((1.0, 2.0, -0.0), AssertionError), + ((1.0, 2.0, -1.0), AssertionError), + ((1.0, 2.0, 1.0), "finite"), + ((NAN, 2.0, 1.0), AssertionError), + ((1.0, NAN, 1.0), AssertionError), + ((1.0, 2.0, NAN), AssertionError), + ((INF, INF, 1.0), "nan"), + ((1.0, INF, 1.0), "nan"), + # the Laplace root divides by zero when the square root equals t in floating point + ((1.0, 2.0, INF), ZeroDivisionError), + ((1.0, 2.0, 1e300), ZeroDivisionError), + ((1.0, 2.0, 1e-300), ZeroDivisionError), + ((1.0, 2.0, 5e-324), ZeroDivisionError), + ((1e300, 1e300, 1.0), ZeroDivisionError), + ((1.0, 1e10, 1e-3), ZeroDivisionError), + ((3.6072737850966632e-06, 87694833.655647, 0.10794027431688721), ZeroDivisionError), + # NOTE: current behaviour, possibly a bug: U(1, 1, x) is finite for + # small x but the approximation overflows + ((1.0, 1.0, 1e-300), "nonfinite"), +] + +HYP1F1_DOMAIN = [ + ((1.0, 2.0, 0.0), "finite"), + ((1.0, 2.0, -0.0), "finite"), + # NOTE: current behaviour, possibly a bug: b == a is allowed by `_valid_hyp1f1` + # (in approx) but asserted against here + ((1.0, 1.0, 1.0), AssertionError), + ((1.0, 0.5, 1.0), AssertionError), + ((0.0, 1.0, 1.0), AssertionError), + ((0.0, 1.0, 0.0), AssertionError), # asserted before the x == 0 shortcut + ((-1.0, 1.0, 0.0), AssertionError), + ((NAN, 2.0, 1.0), AssertionError), + ((1.0, NAN, 1.0), AssertionError), + ((5e-324, 1.0, 0.0), "finite"), + ((1.0, nextafter(1.0, 2), 1.0), "nonfinite"), + ((1.0, 2.0, NAN), "nan"), + ((1.0, 2.0, INF), "nan"), + ((1.0, 2.0, -INF), "nan"), + ((1.0, 2.0, 5e-324), "finite"), + ((1.0, 2.0, 1e-300), "finite"), + # NOTE: current behaviour, possibly a bug: -inf for very large x + ((1.0, 2.0, 1e300), "nonfinite"), + ((1.0, 2.0, -1e300), "nonfinite"), + ((1.0, 2.0, 1e15), "nonfinite"), + ((1e300, 2e300, 1.0), "nonfinite"), + ((1.0, 1e300, 1.0), "nonfinite"), + ((1e-300, 1.0, 1.0), "finite"), + ((1e-10, 2e-10, 1e8), ZeroDivisionError), +] + +HYP2F1_DOMAIN = [ + ((1.0, 2.0, 3.0, 0.5), "finite"), + ((2.0, 1.0, 3.0, 0.5), "finite"), + ((1.0, 2.0, 2.0, 0.5), "finite"), # c == b + ((1.0, 0.5, 1.5, 0.5), "finite"), + ((0.0, 1.0, 1.0, 0.0), "finite"), # z == 0 is checked after the assertions + ((1.0, 2.0, 3.0, -0.0), "finite"), + ((0.0, 1.0, 1.0, 0.5), AssertionError), # a = 0: root on boundary + ((0.0, 1.0, 1.0, -0.5), AssertionError), + ((0.0, 0.0, 1.0, 0.5), AssertionError), + ((1.0, 0.0, 1.0, 0.5), AssertionError), # b = 0, c = a + ((1.0, 0.0, 2.0, 0.5), "finite"), # b = 0 is fine when c > a + ((1.0, 2.0, 1.0, 0.5), AssertionError), # c == a: root on boundary + ((1.0, 1.0, 1.0, 0.5), AssertionError), + ((1.0, 2.0, nextafter(1.0, 0), 0.5), AssertionError), # c < a + ((1.0, 2.0, 0.0, 0.5), AssertionError), + ((1.0, 2.0, -1.0, 0.5), AssertionError), + ((-1.0, 2.0, 3.0, 0.5), AssertionError), # a < 0 + ((1.0, -1.0, 3.0, 0.5), AssertionError), # b < 0 + ((1.0, 2.0, 3.0, 1.0), AssertionError), # z >= 1 + ((1.0, 2.0, 3.0, nextafter(1.0, 2)), AssertionError), + ((1.0, 2.0, 3.0, 1.5), AssertionError), + ((1.0, 2.0, 3.0, nextafter(1.0, 0)), "finite"), + ((1.0, 2.0, 3.0, NAN), AssertionError), + ((NAN, 2.0, 3.0, 0.5), AssertionError), + ((1.0, 2.0, 3.0, -INF), AssertionError), + ((1.0, 2.0, 3.0, -1e300), AssertionError), # z / (z - 1) rounds to 1.0 + ((1.0, 2.0, 3.0, -1e16), AssertionError), + ((1.0, 2.0, 3.0, -9e15), "finite"), + ((0.0, 1.0, 1e-300, 0.5), ZeroDivisionError), + ((1e-300, 1.0, 1.0, 0.5), "finite"), + ((1.0, 1e-300, 1.0, 0.5), AssertionError), + ((1e300, 1e300, 1e300, 0.5), AssertionError), + ((1.0, 2.0, 1e300, 0.5), AssertionError), + ((1.0, 1e300, 2.0, 0.5), AssertionError), +] + + +def laplace_grid(name): + if name == "_hyperu_laplace": + return [ + (a, a + db, x) + for a in [1e-10, 1e-3, 1.0, 50.0, 1e5] + for db in [0.0, 1e-10, 1.0, 1e3, 1e10] + for x in [1e-12, 1e-3, 1.0, 1e3, 1e8, 1e15] + ] + if name == "_hyp1f1_laplace": + return [ + (a, a + db, x) + for a in [1e-10, 1e-3, 1.0, 50.0, 1e5] + for db in [1e-10, 1.0, 1e3, 1e10] + for x in [-1e8, -1e3, -1.0, -1e-10, 1e-10, 1.0, 1e3, 1e8, 1e15] + ] + zs = [5e-324, 1e-300, -1e-12, 1e-8, -1e-4, 0.5, 0.9, 1 - 1e-4, 1 - 1e-6] + zs += [-1.0, -100.0, -1e9] + abcs = [(1.0, 2.0, 3.0), (5.0, 7.0, 9.0), (0.5, 30.0, 1.5), (30.0, 40.0, 35.0)] + return [(*abc, z) for abc in abcs for z in zs] + + +LAPLACE = { + "_hyperu_laplace": HYPERU_DOMAIN, + "_hyp1f1_laplace": HYP1F1_DOMAIN, + "_hyp2f1_laplace": HYP2F1_DOMAIN, +} + + +def unity_formula(a, b, c, z): + """ + The result of `_hyp2f1_laplace` in the unity limit, written out. See DLMF 15.4: + the sign of ``g = c - a - b`` selects the limit, and negative ``z`` is mapped to + ``z / (z - 1)`` close to one by Pfaff's transformation. + """ + s = 0.0 + if z < 0.0: + s = -b * log(1 - z) + a = c - a + z = z / (z - 1) + g = c - a - b + if g < 0.0: + value = lgamma(c) + lgamma(-g) - lgamma(a) - lgamma(b) + g * log(1 - z) + elif g > 0.0: + value = lgamma(c) + lgamma(g) - lgamma(c - a) - lgamma(c - b) + else: + value = log(-log(1 - z)) + lgamma(a + b) - lgamma(a) - lgamma(b) + return s + value + + +def unity_threshold(): + """Largest ``x < 1`` for which ``np.isclose(x, 1.0)`` fails, and the next one up""" + lo, hi = 0.5, 1.0 - 1e-9 # not close, close + while nextafter(lo, 1.0) != hi: + mid = lo + (hi - lo) / 2 + if np.isclose(mid, 1.0): + hi = mid + else: + lo = mid + return lo, hi + + +def negative_unity_threshold(): + """As `unity_threshold`, for ``z < 0`` mapped to ``z / (z - 1)``""" + lo, hi = -1e3, -1e9 # not close, close + while nextafter(lo, hi) != hi: + mid = lo + (hi - lo) / 2 + if np.isclose(mid / (mid - 1), 1.0): + hi = mid + else: + lo = mid + return lo, hi + + +def unity_args_from_ep(a_i, b_i, a_j, b_j, y, mu): + """Arguments of `_hyp2f1_laplace` in the edge update of EP, for hugely negative z""" + return a_j, a_i + a_j + y, a_j + y + 1, (mu - b_j) / (mu + b_i) + + +# (a, b, c, z) for the three limits (g < 0, g > 0, g == 0), for z close to one and, +# via Pfaff's transformation, for large negative z (where g = a - b) +UNITY_CASES = [ + (2.0, 3.0, 4.0, 1 - 1e-8), + (1.0, 2.0, 5.0, 1 - 1e-8), + (1.0, 2.0, 3.0, 1 - 1e-8), + (2.0, 3.0, 4.0, -1e8), + (3.0, 2.0, 5.0, -1e8), + (2.0, 2.0, 5.0, -1e8), + (19.0, 30.0, 25.0, 1 - 1e-7), + (1.0, 2.0, 1.0 + 2.0 + 1e-3, 1 - 1e-9), # g tiny positive + (1.0, 2.0, 3.0 - 1e-3, 1 - 1e-9), # g tiny negative + # parameters of EP updates that reach the limit (formerly the skipped Test2F1Unity) + unity_args_from_ep(202.865, 0.0153, 0.0012724, 101353547.00, 0.0, 2.404560e-05), + unity_args_from_ep(999.998, 0.1041, 0.0012612, 14749022.000, 2.0, 7.830300e-05), + unity_args_from_ep(157.778, 0.0182, 0.0011993, 20861958.000, 0.0, 4.128000e-07), + unity_args_from_ep(1000.00, 0.1431, 0.0009718, 22638776.000, 0.0, 5.881110e-05), + unity_args_from_ep(405.482, 0.1484, 0.0009711, 41053809.000, 0.0, 6.229410e-05), + unity_args_from_ep(115.773, 0.7506, 0.0015549, 23315696857.0, 0.0, 3.601680e-05), + unity_args_from_ep(73.4909, 1.0600, 0.0010028, 56254280956.0, 0.0, 0.0002302392), + unity_args_from_ep(18.9981, 0.1315, 0.0015053, 23443723634.0, 1.0, 2.470348e-05), +] + + +class TestLaplaceDomain: + """ + Edge cases of `_hyperu_laplace`, `_hyp1f1_laplace` and `_hyp2f1_laplace`: the + domain assertions, the zero shortcuts (``x == 0`` returns 0 after the checks), the + division by zero when a Laplace root cancels, and overflow. + """ + + @pytest.mark.parametrize( + ("name", "args", "expected"), + [p for name, rows in LAPLACE.items() for p in table(name, rows)], + ) + def test_domain(self, impl, name, args, expected): + parity(impl, name, args, expected) + + @pytest.mark.parametrize( + ("name", "args"), + [ + pytest.param(name, args, id=f"{name}{args}") + for name in LAPLACE + for args in laplace_grid(name) + ], + ) + def test_grid(self, impl, name, args): + parity(impl, name, args) + + +class TestHyp2f1Unity: + """The unity limit (`_hyp2f1_unity`, reached when ``z`` is ``np.isclose`` to one)""" + + @pytest.mark.parametrize("args", UNITY_CASES, ids=repr) + def test_unity_branches(self, impl, args): + a, b, c, z = args + mapped = z / (z - 1) if z < 0 else z + assert np.isclose(mapped, 1.0), "case must take the unity branch" + result = parity(impl, "_hyp2f1_laplace", args) + assert_ulp_close(result.value, unity_formula(a, b, c, z)) + + @pytest.mark.parametrize("sign", ["positive", "negative"]) + @pytest.mark.parametrize("side", ["not_close", "close"]) + def test_switch_point(self, impl, sign, side): + # the unity formula is used from the first np.isclose argument onwards + if sign == "positive": + not_close, close = unity_threshold() + else: + not_close, close = negative_unity_threshold() + z = close if side == "close" else not_close + parity(impl, "_hyp2f1_laplace", (5.0, 7.0, 9.0, z), "finite") + + +def draw_polygamma(rng, extreme): + if extreme: + return (float(rng.choice([-1.0, 1.0]) * log_uniform(rng, -12, 12)),) + x = log_uniform(rng, -7, 3) + if rng.random() < 0.15: + x = -rng.uniform(0.01, 20) # reflection formula + return (float(x),) + + +def draw_betaln(rng, extreme): + lo, hi = (-8, 8) if extreme else (-2, 3) + return log_uniform(rng, lo, hi), log_uniform(rng, lo, hi) + + +def draw_gammainc_der(rng, extreme): + if extreme: + return log_uniform(rng, -8, 8), log_uniform(rng, -8, 8) + # series, continued fraction and gaussian regimes + return log_uniform(rng, -1, 3.5), log_uniform(rng, -3, 4) + + +def draw_gammainc_inv(rng, extreme): + if extreme: + return log_uniform(rng, -8, 8), float(rng.uniform(0, 1)) + return log_uniform(rng, -1, 3), float(rng.uniform(0.001, 0.999)) + + +def draw_hyperu(rng, extreme): + # requires b >= a > 0 and x > 0 + if extreme: + a = log_uniform(rng, -8, 8) + return a, a + log_uniform(rng, -8, 8), log_uniform(rng, -12, 12) + a = log_uniform(rng, -1, 2) + return a, a + log_uniform(rng, -2, 2), log_uniform(rng, -3, 3) + + +def draw_hyp1f1(rng, extreme): + # requires b > a > 0, x of either sign + sign = float(rng.choice([-1.0, 1.0])) + if extreme: + a = log_uniform(rng, -8, 8) + return a, a + log_uniform(rng, -8, 8), sign * log_uniform(rng, -12, 12) + a = log_uniform(rng, -1, 2) + return a, a + log_uniform(rng, -2, 2), sign * log_uniform(rng, -2, 2) + + +def draw_hyp2f1(rng, extreme): + if extreme: + a = log_uniform(rng, -8, 8) + b = log_uniform(rng, -8, 8) + c = a + (0.0 if rng.random() < 0.3 else log_uniform(rng, -8, 8)) + z = float(rng.choice([-1.0, 1.0, 1.0]) * log_uniform(rng, -14, 0)) + return a, b, c, z + 1.0 if rng.random() < 0.3 else z + # parameters of the edge (c = a_j + y + 1) and unphased (c = a_i + a_j) updates, + # with z < 1 on either side of zero and close to unity + a_i, a_j = rng.uniform(0.5, 30, 2) + y = float(rng.integers(0, 12)) + c = a_j + y + 1 if rng.random() < 0.5 else a_i + a_j + u = rng.random() + if u < 0.4: + z = -log_uniform(rng, -3, 3) + elif u < 0.8: + z = 1 - log_uniform(rng, -6, 0) + else: + z = 1 - log_uniform(rng, -12, -9) + return float(a_j), float(a_i + a_j + y), float(c), z + + +DRAWS = { + "_digamma": draw_polygamma, + "_trigamma": draw_polygamma, + "_betaln": draw_betaln, + "_gammainc_der": draw_gammainc_der, + "_gammainc_inv": draw_gammainc_inv, + "_hyperu_laplace": draw_hyperu, + "_hyp1f1_laplace": draw_hyp1f1, + "_hyp2f1_laplace": draw_hyp2f1, +} + + +class TestRandomDraws: + """ + Seeded draws of arguments, in ranges typical of EP and over 16 orders of magnitude + ("extreme", where exceptions and non-finite values are common). The failing + draw is named in the assertion. + """ + + @pytest.mark.parametrize("seed", [1, 2, 3]) + @pytest.mark.parametrize("mode", ["typical", "extreme"]) + @pytest.mark.parametrize("name", list(DRAWS)) + def test_random_draws(self, impl, name, mode, seed): + rng = np.random.default_rng(seed) + for i in range(40): + args = DRAWS[name](rng, mode == "extreme") + try: + parity(impl, name, args) + except AssertionError as e: + raise AssertionError(f"draw {i}: {name}{args}: {e}") from None diff --git a/tests/test_oracle_numba_libm.py b/tests/test_oracle_numba_libm.py new file mode 100644 index 00000000..c5b3d09b --- /dev/null +++ b/tests/test_oracle_numba_libm.py @@ -0,0 +1,47 @@ +""" +The oracle's ``ipow`` (``oracle/_libm.py``) against numba's ``x ** n``, for the small +integer constants ``n`` used in tsdate. + +This is the only test module that imports numba. It checks the oracle against the +numba behaviour it imitates, so it is deleted together with numba (step E). +""" + +import numba +import numpy as np +import pytest +from oracle._libm import ipow +from oracle.helpers import INF, NAN + + +def compile_power(n): + @numba.njit("f8[:](f8[:])") + def power(x): + out = np.empty_like(x) + for i in range(x.size): + out[i] = x[i] ** n + return out + + return power + + +class TestIpow: + @pytest.mark.parametrize("seed", [1, 2]) + @pytest.mark.parametrize("n", [2, 3, 4, 5, 6, 7]) + def test_matches_numba(self, n, seed): + rng = np.random.default_rng(seed) + x = np.concatenate( + [ + 10.0 ** rng.uniform(-3, 3, 2000), + -(10.0 ** rng.uniform(-100, 100, 500)), + [0.0, -0.0, 1.0, -1.0, 5e-324, 1e-170, 1e170, INF, -INF, NAN], + ] + ) + actual = compile_power(n)(x) + with np.errstate(all="ignore"): + expected = np.array([ipow(xi, n) for xi in x.tolist()]) + np.testing.assert_array_equal(np.isnan(actual), np.isnan(expected)) + finite = ~np.isnan(expected) + # bit for bit, including the sign of zero + np.testing.assert_array_equal( + actual[finite].view(np.int64), expected[finite].view(np.int64) + ) From 4b4c5be8ace35f63ab8a0c03051032094aea6349 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 20 Nov 2026 13:46:29 -0800 Subject: [PATCH 04/56] Test the EP helpers and passes against their oracles; add EP sensitivity report Each implementation of the variational module is compared with its oracle: EPFactors, _damp, _rescale (every branch, and the boundaries one ulp either side), _rescale_factors and _assemble_factors (incl. the rescaling of tiny scales mid-pass), _check_valid_constraints, and the passes propagate_likelihood, propagate_prior and propagate_mutations. Inputs are snapshots of real EP state on the simulated tree sequences (tests/oracle/ep_state.py), with constraints edited to force every branch, one-edge states for each branch, and tables of boundary and failure cases (skipped updates, failed projections, EM stopping, invalid parameters). Single calls agree to within 4 ulp. Over whole sweeps a difference in the last bit of an intermediate grows (about 1e-6 relative after the first sweep, 1e-8 after several), so the multi-sweep test allows rtol 1e-4 after the first sweep and 1e-6 later, with identical patterns of skipped updates. evaluation/ep_sensitivity.py measures that growth with the production code. Where compiled numba raises ZeroDivisionError and the plain-Python oracle does not, the test checks that the implementation raises. --- evaluation/README.md | 16 + evaluation/ep_sensitivity.py | 84 +++ tests/oracle/ep_state.py | 396 ++++++++++++++ tests/test_oracle_variational.py | 897 +++++++++++++++++++++++++++++++ 4 files changed, 1393 insertions(+) create mode 100644 evaluation/ep_sensitivity.py create mode 100644 tests/oracle/ep_state.py create mode 100644 tests/test_oracle_variational.py diff --git a/evaluation/README.md b/evaluation/README.md index e5a5692c..6d533c13 100644 --- a/evaluation/README.md +++ b/evaluation/README.md @@ -17,6 +17,7 @@ standard coalescent. | `performance.py` | Wall time and peak RSS, each case in a fresh process. | | `microbench.py` | Microbenchmarks of the array-level accelerated functions (EP passes, rescaling, phasing, `util`, `prior`), on simulated inputs at three sizes (see below). | | `numerical_accuracy.py` | Accuracy of the special functions and gamma approximations (`tsdate.hypergeo`, `tsdate.approx`) per function and regime: worst error against mpmath, SciPy or closed forms, and violations of properties such as symmetry, monotonicity and continuity at switch points (see below). Not to be confused with `accuracy.py`, which scores dating. | +| `ep_sensitivity.py` | How a one-ulp change in the edge mutational targets grows over EP sweeps (maximum relative change in node means), which sets the tolerance of the multi-sweep test in `tests/test_oracle_variational.py` (see below). | | `compare.py` | Compares two `performance.py` CSVs case by case (see below). | | `plot.py` | Reads `results/*.csv` and writes PNGs: error/bias/interval coverage vs parameter (`accuracy_*_summary.png`: top row node times, bottom row mutation times), estimated-vs-true scatter (`accuracy_*_scatter.png`: columns are swept values, rows are node/mutation times for true/tsinferred topology), PIT calibration histograms (`accuracy_*_calibration.png`: node row, mutation row), AFS observed-vs-expected (`afs_*.png`), time and memory scaling. | | `validation.py` | Stub: numerical checks too slow for the unit tests (issue #384). | @@ -105,6 +106,21 @@ Implementations are chosen with `--impl`. To add one, write a function returning dict of callables with the same names and signatures as `_numba_impl` and register it in `IMPLS`. +### Sensitivity of EP to last-bit differences + +`ep_sensitivity.py` perturbs the mutational target of every edge by one ulp and reports +how far the node means move over successive EP sweeps (maximum relative change after +selected sweeps, using tsdate's own `ExpectationPropagation`). This is the noise that an +implementation with differently rounded intermediates has to live with, and the reason +the multi-sweep comparison in `tests/test_oracle_variational.py` uses relative +tolerances (1e-4 after the first sweep, 1e-6 later) instead of an ulp bound. Typical +values: about 1e-6 to 1e-7 after one sweep, 1e-8 to 1e-9 after ten. + +``` +python evaluation/ep_sensitivity.py --quick +python evaluation/ep_sensitivity.py --sizes 20 100 --seeds 1 2 3 --sweeps 1 5 10 +``` + ### Accuracy of the special functions `numerical_accuracy.py` measures the approximation error of the production functions in diff --git a/evaluation/ep_sensitivity.py b/evaluation/ep_sensitivity.py new file mode 100644 index 00000000..ed85ce37 --- /dev/null +++ b/evaluation/ep_sensitivity.py @@ -0,0 +1,84 @@ +""" +How much do whole EP sweeps amplify last-bit differences? + +The mutational target of every edge (the input of the likelihood pass) is perturbed +by one ulp, and the trajectory of node means is compared with the unperturbed run, +using tsdate's production `ExpectationPropagation`. This is the noise level that a +reimplementation with differently rounded intermediates has to live with, and the +reason that multi-sweep comparisons in `tests/test_oracle_variational.py` use +relative tolerances (1e-4 after the first sweep, 1e-6 later) and not ulps. + +Prints, for each tree sequence, the maximum relative change in node means after +selected sweeps, and whether the pattern of skipped updates (NaN edge log-normalising +constants) changes. + +Example: + python evaluation/ep_sensitivity.py --quick + python evaluation/ep_sensitivity.py --sizes 20 100 --seeds 1 2 3 --sweeps 1 5 10 +""" + +import argparse + +import common +import numpy as np + +from tsdate.variational import ExpectationPropagation + + +def node_means(posterior): + """Means of the gamma distributions with natural parameters `posterior`""" + with np.errstate(all="ignore"): + return (posterior[:, 0] + 1) / posterior[:, 1] + + +def run_pair(ts, mutation_rate, num_sweeps, max_shape, min_step): + """ + Run EP with and without the perturbation; yield, after each sweep, the maximum + relative difference in node means and whether the skipped updates differ. + """ + eps = [] + for perturb in (False, True): + ep = ExpectationPropagation(ts, mutation_rate=mutation_rate) + if perturb: + target = ep.edge_likelihoods[:, 1] + ep.edge_likelihoods[:, 1] = np.nextafter(target, np.inf) + eps.append(ep) + for _ in range(num_sweeps): + for ep in eps: + ep.iterate(max_shape=max_shape, min_step=min_step) + base, perturbed = (node_means(ep.node_posterior) for ep in eps) + ok = np.isfinite(base) & np.isfinite(perturbed) + change = np.abs(perturbed[ok] - base[ok]) / np.abs(base[ok]) + skipped = [np.isnan(ep.edge_logconst) for ep in eps] + yield float(change.max(initial=0.0)), not np.array_equal(*skipped) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--sizes", type=int, nargs="+", default=[20, 100]) + parser.add_argument("--length", type=float, default=2e5) + parser.add_argument("--seeds", type=int, nargs="+", default=[1, 2, 3]) + parser.add_argument("--sweeps", type=int, nargs="+", default=[1, 2, 5, 10]) + parser.add_argument("--mutation-rate", type=float, default=1e-8) + parser.add_argument("--max-shape", type=float, default=1000.0) + parser.add_argument("--min-step", type=float, default=0.1) + parser.add_argument("--quick", action="store_true", help="one small simulation") + args = parser.parse_args() + if args.quick: + args.sizes, args.seeds, args.sweeps, args.length = [10], [1], [1, 3], 1e5 + header = "".join(f"{f'sweep {s}':>12}" for s in args.sweeps) + print(f"{'samples':>8}{'seed':>6}{header} skipped-pattern-changed") + for n in args.sizes: + for seed in args.seeds: + ts = common.simulate(n, args.length, args.mutation_rate, seed) + runs = run_pair( + ts, args.mutation_rate, max(args.sweeps), args.max_shape, args.min_step + ) + results = list(runs) + row = "".join(f"{results[s - 1][0]:12.2e}" for s in args.sweeps) + changed = any(r[1] for r in results) + print(f"{n:>8}{seed:>6}{row} {changed}") + + +if __name__ == "__main__": + main() diff --git a/tests/oracle/ep_state.py b/tests/oracle/ep_state.py new file mode 100644 index 00000000..80140fc2 --- /dev/null +++ b/tests/oracle/ep_state.py @@ -0,0 +1,396 @@ +""" +Expectation propagation state for the equivalence tests of ``tsdate.variational``: +snapshots of real state from ``ExpectationPropagation`` (editable, so that tests can +force branches), one-edge snapshots, and runners that call the ``propagate_*`` +functions of a namespace on copies of a snapshot. +""" + +import numpy as np +import tskit + +from tsdate.variational import ( + CONSTRNT, + LEAFWARD, + LOWER, + MIXPRIOR, + ROOTWARD, + UPPER, + USE_BLOCK_LIKELIHOOD, + USE_EDGE_LIKELIHOOD, + ExpectationPropagation, +) + +# fixture name -> (singletons_phased, mutation_rate) +SNAPSHOT_SPECS = { + "small_ts": (True, 1e-8), + "small_ts_unphased": (False, 1e-7), + "small_ts_historical": (True, 1e-8), +} + +_COPIED = ( + "edge_order", + "edge_parents", + "edge_children", + "edge_likelihoods", + "block_order", + "block_likelihoods", + "block_nodes", + "node_constraints", + "node_posterior", + "edge_logconst", + "block_logconst", + "unconstrained_roots", + "roots", + "leaves", + "mutation_order", + "mutation_edges", + "mutation_blocks", +) + + +class Snapshot: + """ + Copies of the arrays of an ``ExpectationPropagation`` after some iterations, so + that tests can edit them freely and rebuild fresh ``EPFactors`` of any class. + """ + + def __init__(self, ts, ep): + self.ts = ts + for name in _COPIED: + setattr(self, name, getattr(ep, name).copy()) + factors = ep.factors + self.fields = {k: getattr(factors, k).copy() for k in self.FIELDS} + self.num_mutations = ep.mutation_phase.size + + FIELDS = ("node", "edge", "block", "scale") + + def copy(self): + new = object.__new__(Snapshot) + for k, v in self.__dict__.items(): + if isinstance(v, np.ndarray): + v = v.copy() + elif isinstance(v, dict): + v = {a: b.copy() for a, b in v.items()} + setattr(new, k, v) + return new + + def factors(self, cls): + """New ``EPFactors`` of class ``cls`` holding a copy of the factors""" + factors = cls( + self.node_constraints, + self.edge_parents, + self.edge_children, + self.block_nodes[ROOTWARD], + self.block_nodes[LEAFWARD], + ) + for k, v in self.fields.items(): + getattr(factors, k)[:] = v + return factors + + def unscale(self, nodes, scale): + """ + Make the state equivalent but with ``scale[nodes] = scale``, by dividing all + factors associated with those nodes (see ``_rescale_factors``) by ``scale``. + """ + sel = np.zeros(self.node_posterior.shape[0], dtype=bool) + sel[nodes] = True + f = self.fields + f["edge"][sel[self.edge_parents], ROOTWARD] /= scale + f["edge"][sel[self.edge_children], LEAFWARD] /= scale + f["block"][sel[self.block_nodes[ROOTWARD]], ROOTWARD] /= scale + f["block"][sel[self.block_nodes[LEAFWARD]], LEAFWARD] /= scale + f["node"][sel, MIXPRIOR] /= scale + f["node"][sel, CONSTRNT] /= scale + f["scale"][sel] = scale + + def fix_nodes(self, nodes): + """Constrain ``nodes`` to their true (simulated) ages""" + nodes = np.asarray(nodes) + times = self.ts.nodes_time[nodes] + self.node_constraints[nodes, LOWER] = times + self.node_constraints[nodes, UPPER] = times + + @property + def fixed(self): + return self.node_constraints[:, LOWER] == self.node_constraints[:, UPPER] + + def branch_counts(self, unphased): + """Number of edges (blocks) of each kind visited by the propagate functions""" + if unphased: + p, c = self.block_nodes[ROOTWARD], self.block_nodes[LEAFWARD] + else: + p, c = self.edge_parents, self.edge_children + fp, fc = self.fixed[p], self.fixed[c] + return { + "both_fixed": int(np.sum(fp & fc)), + "fixed_parent": int(np.sum(fp & ~fc)), + "fixed_child": int(np.sum(~fp & fc)), + "twin": int(np.sum(~fp & ~fc & (p == c))), + "both_free": int(np.sum(~fp & ~fc & (p != c))), + } + + def after_pass(self, state): + """Copy with the state returned by `run_likelihood` as its current state""" + posterior, _, *fields = state + new = self.copy() + new.node_posterior = posterior.copy() + new.fields = {k: v.copy() for k, v in zip(self.FIELDS, fields)} + return new + + +def make_snapshot(ts, name, iterations=2): + """Snapshot of the state of EP on ``ts`` (fixture ``name``) after some iterations""" + singletons_phased, mutation_rate = SNAPSHOT_SPECS[name] + ep = ExpectationPropagation( + ts, mutation_rate=mutation_rate, singletons_phased=singletons_phased + ) + for _ in range(iterations): + ep.iterate(max_shape=1000, min_step=0.1) + return Snapshot(ts, ep) + + +def fixed_internal_snapshot(snap, unphased, every=4): + """ + Copy of a snapshot with every ``every``th internal node (every ``every``th block + node, for unphased blocks) fixed at its true age; the first block has both nodes + fixed. Gives all branches of the propagate functions. + """ + snap = snap.copy() + if unphased: + nodes = np.unique(snap.block_nodes) + fixed = list(nodes[::every]) + fixed += [snap.block_nodes[ROOTWARD][0], snap.block_nodes[LEAFWARD][0]] + else: + internal = np.flatnonzero(~snap.fixed) + fixed = list(internal[::every]) + snap.fix_nodes(np.unique(fixed)) + return snap + + +# One edge (block) in each branch of `propagate_likelihood`/`propagate_mutations`: +# (unphased, constraints of the nodes, parent, child). Fixed nodes have ages 0 +# (child) or 10 (parent) or 5 (block nodes). +INF = np.inf +BRANCHES = { + "fixed_child": (False, [[0, 0], [0, INF]], 1, 0), + "fixed_parent": (False, [[0, INF], [10, 10]], 1, 0), + "both_free": (False, [[0, INF], [0, INF]], 1, 0), + "both_fixed": (False, [[0, 0], [10, 10]], 1, 0), + "twin": (True, [[0, INF], [0, INF]], 1, 1), + "sideways_fixed_parent": (True, [[0, INF], [5, 5], [0, INF]], 1, 2), + "sideways_fixed_child": (True, [[0, INF], [0, INF], [5, 5]], 1, 2), + "unphased_both_free": (True, [[0, INF], [0, INF], [0, INF]], 1, 2), + "unphased_both_fixed": (True, [[0, 0], [5, 5], [5, 5]], 1, 2), +} +# cavity and message of every node; `node` = cavity + message +CAVITY, MESSAGE = np.array([3.0, 0.5]), np.array([1.0, 0.1]) +# message so large relative to the cavity that the cavity has to be damped +DAMPED_CAVITY, DAMPED_MESSAGE = np.array([1.0, 0.05]), np.array([22.0, 2.4]) + + +def tiny_snapshot(branch, cavity=CAVITY, message=MESSAGE, likelihood=(3.0, 0.1)): + """Snapshot of a single edge (or block) whose factor is `message` at each end""" + unphased, constraints, p, c = BRANCHES[branch] + constraints = np.array(constraints, dtype=np.float64) + n = constraints.shape[0] + snap = Snapshot.__new__(Snapshot) + snap.ts = None + snap.node_constraints = constraints + snap.node_posterior = np.tile(cavity + message, (n, 1)) + parents, children = np.array([p], np.int32), np.array([c], np.int32) + snap.edge_parents, snap.edge_children = parents, children + snap.block_nodes = np.array([parents, children]) + snap.edge_order = snap.block_order = np.zeros(1, np.int32) + snap.edge_likelihoods = snap.block_likelihoods = np.array([likelihood]) + snap.edge_logconst = np.zeros(1) + snap.block_logconst = np.zeros(1) + snap.mutation_order = np.zeros(1, np.int32) + snap.mutation_edges = np.zeros(1, np.int32) + snap.mutation_blocks = np.full(1, 0 if unphased else tskit.NULL, np.int32) + snap.num_mutations = 1 + fields = { + "node": np.zeros((n, 2, 2)), + "edge": np.zeros((1, 2, 2)), + "block": np.zeros((1, 2, 2)), + "scale": np.ones(n), + } + factor = fields["block" if unphased else "edge"] + factor[0, ROOTWARD] = message + factor[0, LEAFWARD] = message + snap.fields = fields + snap.unphased = unphased + snap.unconstrained_roots = np.zeros(n, dtype=bool) + return snap + + +def likelihood_args(snap, unphased, order=None, likelihoods=None): + """Leading arguments of `propagate_likelihood` and the matching `lognorm`""" + if unphased: + args = ( + snap.block_order if order is None else order, + snap.block_nodes[ROOTWARD], + snap.block_nodes[LEAFWARD], + snap.block_likelihoods if likelihoods is None else likelihoods, + ) + return args, snap.block_logconst + args = ( + snap.edge_order if order is None else order, + snap.edge_parents, + snap.edge_children, + snap.edge_likelihoods if likelihoods is None else likelihoods, + ) + return args, snap.edge_logconst + + +def run_likelihood( + ns, snap, unphased, max_shape=1000.0, min_step=0.1, order=None, likelihoods=None +): + """ + Run `propagate_likelihood` of namespace ``ns`` on copies of ``snap``; return + ``(posterior, lognorm, node, edge, block, scale)`` after the pass. + """ + args, lognorm = likelihood_args(snap, unphased, order, likelihoods) + factors = snap.factors(ns.EPFactors) + posterior = snap.node_posterior.copy() + lognorm = lognorm.copy() + ns.propagate_likelihood( + *args, + snap.node_constraints, + posterior, + factors, + lognorm, + max_shape, + min_step, + USE_BLOCK_LIKELIHOOD if unphased else USE_EDGE_LIKELIHOOD, + ) + return (posterior, lognorm, factors.node, factors.edge, factors.block, factors.scale) + + +def run_prior(ns, snap, free, max_shape=1000.0, em_maxitt=10, em_reltol=1e-8): + """Run `propagate_prior`; return ``(posterior, node, scale)`` after the pass.""" + factors = snap.factors(ns.EPFactors) + posterior = snap.node_posterior.copy() + ns.propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol) + return (posterior, factors.node, factors.scale) + + +def run_mutations(ns, snap, unphased, edges=None, posterior=None, order=None): + """ + Run `propagate_mutations` on the phased (or unphased) mutations; return + ``(mutation_posterior, phase, node, edge, block, scale)``. + """ + factors = snap.factors(ns.EPFactors) + mut_posterior = np.full((snap.num_mutations, 2), np.nan) + phase = np.ones(snap.num_mutations) + phased = snap.mutation_blocks == tskit.NULL + if unphased: + order = snap.mutation_order[~phased] if order is None else order + args = ( + snap.mutation_blocks, + snap.block_nodes[ROOTWARD], + snap.block_nodes[LEAFWARD], + snap.block_likelihoods, + ) + else: + order = snap.mutation_order[phased] if order is None else order + args = ( + snap.mutation_edges if edges is None else edges, + snap.edge_parents, + snap.edge_children, + snap.edge_likelihoods, + ) + ns.propagate_mutations( + order, + mut_posterior, + phase, + *args, + snap.node_constraints, + snap.node_posterior if posterior is None else posterior, + factors, + USE_BLOCK_LIKELIHOOD if unphased else USE_EDGE_LIKELIHOOD, + ) + return ( + mut_posterior, + phase, + factors.node, + factors.edge, + factors.block, + factors.scale, + ) + + +def run_sweeps(ns, snap, num_sweeps, max_shape=1000.0, min_step=0.1, em_maxitt=10): + """ + Run EP sweeps (the loop of `ExpectationPropagation.iterate`, then the mutation + passes of `infer`) with namespace ``ns`` from a copy of ``snap``. Returns, per + sweep, ``(posterior, edge_logconst, block_logconst)`` copies, and the mutation + ``(posterior, phase)``. + """ + factors = snap.factors(ns.EPFactors) + posterior = snap.node_posterior.copy() + edge_logconst = snap.edge_logconst.copy() + block_logconst = snap.block_logconst.copy() + mut_posterior = np.full((snap.num_mutations, 2), np.nan) + mut_phase = np.ones(snap.num_mutations) + block_nodes = snap.block_nodes + states = [] + for _ in range(num_sweeps): + ns.propagate_likelihood( + snap.block_order, + block_nodes[ROOTWARD], + block_nodes[LEAFWARD], + snap.block_likelihoods, + snap.node_constraints, + posterior, + factors, + block_logconst, + max_shape, + min_step, + USE_BLOCK_LIKELIHOOD, + ) + ns.propagate_likelihood( + snap.edge_order, + snap.edge_parents, + snap.edge_children, + snap.edge_likelihoods, + snap.node_constraints, + posterior, + factors, + edge_logconst, + max_shape, + min_step, + USE_EDGE_LIKELIHOOD, + ) + ns.propagate_prior( + snap.unconstrained_roots, posterior, factors, max_shape, em_maxitt, 1e-8 + ) + ns._rescale_factors(factors) + states.append((posterior.copy(), edge_logconst.copy(), block_logconst.copy())) + phased = snap.mutation_blocks == tskit.NULL + ns.propagate_mutations( + snap.mutation_order[~phased], + mut_posterior, + mut_phase, + snap.mutation_blocks, + block_nodes[ROOTWARD], + block_nodes[LEAFWARD], + snap.block_likelihoods, + snap.node_constraints, + posterior, + factors, + USE_BLOCK_LIKELIHOOD, + ) + ns.propagate_mutations( + snap.mutation_order[phased], + mut_posterior, + mut_phase, + snap.mutation_edges, + snap.edge_parents, + snap.edge_children, + snap.edge_likelihoods, + snap.node_constraints, + posterior, + factors, + USE_EDGE_LIKELIHOOD, + ) + return states, (mut_posterior, mut_phase) diff --git a/tests/test_oracle_variational.py b/tests/test_oracle_variational.py new file mode 100644 index 00000000..fe63fd9d --- /dev/null +++ b/tests/test_oracle_variational.py @@ -0,0 +1,897 @@ +""" +Equivalence of each implementation of ``tsdate.variational`` with its oracle: the +EP helpers (``EPFactors``, ``_damp``, ``_rescale``, ``_rescale_factors``, +``_check_valid_constraints``) and the passes ``propagate_likelihood``, +``propagate_prior`` and ``propagate_mutations``, plus whole sweeps. + +Inputs are snapshots of real EP state (``oracle.ep_state``) on the session fixtures, +with constraints edited to force branches, one-edge snapshots for each branch, and +tables of boundary and failure cases. Expected values always come from the oracle. +Where compiled code raises ``ZeroDivisionError`` and the oracle does not, the +implementation alone is checked (the C port reports an error code there). +""" + +from functools import partial + +import numpy as np +import pytest +import tskit +from oracle import ep_state, variational +from oracle.ep_state import BRANCHES, SNAPSHOT_SPECS, tiny_snapshot +from oracle.helpers import ( + INF, + NAN, + assert_inplace_close, + assert_same_outcome, + compare, + expected_error, + f64, + kind, + log_uniform, + outcome, +) + +from tsdate.variational import ( + LOWER, + MIXPRIOR, + TINY, + UPPER, +) + +up = np.nextafter +TS_NAMES = list(SNAPSHOT_SPECS) +INCONSISTENT_MESSAGE = ( + "Node age constraints are inconsistent, some descendants have" + " lower bounds that exceed upper bounds of their ancestors." +) + + +@pytest.fixture(scope="module") +def snaps(small_ts, small_ts_unphased, small_ts_historical): + """Snapshots of EP state two iterations in, by fixture name""" + tss = [small_ts, small_ts_unphased, small_ts_historical] + return {name: ep_state.make_snapshot(ts, name) for name, ts in zip(TS_NAMES, tss)} + + +@pytest.fixture(scope="module") +def fresh(small_ts, small_ts_unphased, small_ts_historical): + """Snapshots of the initial EP state, by fixture name""" + tss = [small_ts, small_ts_unphased, small_ts_historical] + return { + name: ep_state.make_snapshot(ts, name, iterations=0) + for name, ts in zip(TS_NAMES, tss) + } + + +@pytest.fixture(scope="module") +def scaled_snap(snaps): + """``small_ts`` after a likelihood pass with a small cap, so that scales are not 1""" + snap = snaps["small_ts"] + state = ep_state.run_likelihood(variational, snap, False, max_shape=3.0) + return snap.after_pass(state) + + +def compare_runs(runner, impl, snap, *args, **kwargs): + """Run ``runner`` (an ``ep_state.run_*``) with the implementation and the oracle""" + actual = partial(runner, impl.variational) + expected = partial(runner, variational) + return compare(actual, expected, snap, *args, **kwargs) + + +def assert_run_kind(runner, impl, snap, expected_kind, *args, **kwargs): + result = compare_runs(runner, impl, snap, *args, **kwargs) + assert kind(result) == expected_kind + + +def unphased_name(ts_name): + return ts_name == "small_ts_unphased" + + +class TestEPFactors: + def test_constructor(self, impl, snaps): + snap = snaps["small_ts"] + actual = snap.factors(impl.variational.EPFactors) + expected = snap.factors(variational.EPFactors) + for field in ("node", "edge", "block", "scale"): + a, e = getattr(actual, field), getattr(expected, field) + assert a.dtype == e.dtype + assert a.shape == e.shape + for field in ("_p", "_c", "_j", "_k"): + assert np.array_equal(getattr(actual, field), getattr(expected, field)) + fields = ("node", "edge", "block", "scale") + assert_inplace_close( + [getattr(actual, f) for f in fields], [getattr(expected, f) for f in fields] + ) + + +class TestRescaleFactors: + @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_unphased"]) + @pytest.mark.parametrize("scale", ["seed0", "seed1", 1e-160, 1e100]) + def test_rescale_factors(self, impl, snaps, ts_name, scale): + snap = snaps[ts_name].copy() + num_nodes = snap.node_posterior.shape[0] + if isinstance(scale, str): + rng = np.random.default_rng(int(scale[-1])) + scale = rng.uniform(0.5, 2.0, num_nodes) + snap.fields["scale"][:] = scale + actual = snap.factors(impl.variational.EPFactors) + expected = snap.factors(variational.EPFactors) + impl.variational._rescale_factors(actual) + variational._rescale_factors(expected) + fields = ("node", "edge", "block", "scale") + assert_inplace_close( + [getattr(actual, f) for f in fields], [getattr(expected, f) for f in fields] + ) + + def test_rescale_factors_twice(self, impl, snaps): + # the scale is reset to 1, so a second call changes nothing + snap = snaps["small_ts"] + factors = snap.factors(impl.variational.EPFactors) + impl.variational._rescale_factors(factors) + once = [factors.node.copy(), factors.edge.copy(), factors.block.copy()] + impl.variational._rescale_factors(factors) + for before, after in zip(once, (factors.node, factors.edge, factors.block)): + assert np.array_equal(before, after) + + @pytest.mark.parametrize("ts_name", TS_NAMES) + def test_assemble_factors(self, impl, snaps, scaled_snap, ts_name): + snap = scaled_snap if ts_name == "small_ts" else snaps[ts_name] + actual = impl.variational._assemble_factors( + snap.factors(impl.variational.EPFactors) + ) + expected = variational._assemble_factors(snap.factors(variational.EPFactors)) + assert_same_outcome(outcome(lambda: actual), outcome(lambda: expected)) + + +# fmt: off +DAMP_TABLE = [ + # (id, x, y, s, kind); first component test is `1 + x0 - y0 > (1 + x0) * s`, + # second is `x1 - y1 > x1 * s`. With x = (1, 2) and s = 0.5 the thresholds are + # y0 = 1 and y1 = 1. + ("zeros", f64(0, 0), f64(0, 0), 0.5, "finite"), + ("zeros_invalid_s", f64(0, 0), f64(0, 0), 5.0, "finite"), + ("zero_y", f64(1, 2), f64(0, 0), 0.5, "finite"), + ("a_below", f64(1, 2), f64(up(1.0, 0.0), 0), 0.5, "finite"), + ("a_at", f64(1, 2), f64(1.0, 0), 0.5, "finite"), + ("a_above", f64(1, 2), f64(up(1.0, 2.0), 0), 0.5, "finite"), + ("a_damped", f64(1, 2), f64(4, 0), 0.5, "finite"), + ("a_negative_y", f64(1, 2), f64(-5, 0), 0.5, "finite"), + ("b_below", f64(1, 2), f64(0, up(1.0, 0.0)), 0.5, "finite"), + ("b_at", f64(1, 2), f64(0, 1.0), 0.5, "finite"), + ("b_above", f64(1, 2), f64(0, up(1.0, 2.0)), 0.5, "finite"), + ("b_damped", f64(1, 2), f64(0, 8), 0.5, "finite"), + ("b_negative_y", f64(1, 2), f64(0, -5), 0.5, "finite"), + ("min_is_a", f64(1, 2), f64(4, 2), 0.5, "finite"), + ("min_is_b", f64(1, 2), f64(2, 8), 0.5, "finite"), + ("both_negative_y", f64(1, 2), f64(-1, -1), 0.5, "finite"), + ("tiny_s", f64(1, 2), f64(2, 2), up(0.0, 1.0), "finite"), + ("s_below_one", f64(1, 2), f64(2, 2), up(1.0, 0.0), "finite"), + ("x0_just_above_minus_one", f64(up(-1.0, 0.0), 1), f64(0, 0), 0.5, "finite"), + # NOTE: current behaviour, possibly a bug: `min(a, b)` swallows a + # NaN in the second component of y, so the damping is silently skipped. + ("y1_nan", f64(1, 1), f64(0, NAN), 0.5, "finite"), + ("y1_nan_a_damped", f64(1, 1), f64(8, NAN), 0.5, "finite"), + ("y0_minus_inf", f64(1, 1), f64(-INF, 0), 0.5, "finite"), + ("y1_minus_inf", f64(1, 1), f64(0, -INF), 0.5, "finite"), + # asserts: sizes and `s` are checked by the callers (direct calls only) + ("size_x", f64(1, 1, 1), f64(0, 0), 0.5, AssertionError), + ("size_y", f64(1, 1), f64(0, 0, 0), 0.5, AssertionError), + ("s_zero", f64(1, 1), f64(0, 0), 0.0, AssertionError), + ("s_one", f64(1, 1), f64(0, 0), 1.0, AssertionError), + ("s_negative", f64(1, 1), f64(0, 0), -0.5, AssertionError), + ("s_nan", f64(1, 1), f64(0, 0), NAN, AssertionError), + # `0 < x[0] + 1` and `0 < x[1]`: reachable from improper or NaN posteriors + ("x0_minus_one", f64(-1, 1), f64(0, 0), 0.5, AssertionError), + ("x0_nan", f64(NAN, 1), f64(0, 0), 0.5, AssertionError), + ("x1_zero", f64(1, 0), f64(0, 0), 0.5, AssertionError), + ("x1_negative", f64(1, -1), f64(0, 0), 0.5, AssertionError), + ("x1_nan", f64(1, NAN), f64(0, 0), 0.5, AssertionError), + ("x_zero_y_not", f64(0, 0), f64(1, 1), 0.5, AssertionError), + # `0 < d` fails when d underflows or y[0] is NaN + ("d_underflow", f64(1, 1e-300), f64(0, 1e300), 0.5, AssertionError), + ("y0_nan", f64(1, 1), f64(NAN, 0), 0.5, AssertionError), +] +RESCALE_TABLE = [ + # (id, x, s, kind); branches `1 + x0 > s` and `1 + x0 < 1 / s` + ("zeros", f64(0, 0), 10.0, "finite"), + ("zeros_invalid_s", f64(0, 0), 0.0, "finite"), + ("x0_zero", f64(0, 1), 10.0, "finite"), + ("inside", f64(5, 1), 10.0, "finite"), + ("inside_low", f64(-0.5, 1), 2.0, "finite"), + ("upper_below", f64(up(9.0, 0.0), 1), 10.0, "finite"), + ("upper_at", f64(9, 1), 10.0, "finite"), + ("upper_above", f64(up(9.0, 10.0), 1), 10.0, "finite"), + ("lower_above", f64(up(-0.5, 0.0), 1), 2.0, "finite"), + ("lower_at", f64(-0.5, 1), 2.0, "finite"), + ("lower_below", f64(up(-0.5, -1.0), 1), 2.0, "finite"), + ("lower_far", f64(-0.95, 1), 10.0, "finite"), + ("infinite_rate", f64(99, INF), 10.0, "finite"), + ("infinite_shape", f64(INF, 1), 10.0, "finite"), + # NOTE: current behaviour, possibly a bug: with `max_shape = 1` + # (allowed by the asserts in `propagate_*`) the factor is 0 and wipes out the + # posterior. + ("s_one_upper", f64(1, 1), 1.0, "finite"), + ("s_one_lower", f64(-0.5, 1), 1.0, "finite"), + # asserts (reachable as for `_damp`) + ("size", f64(1, 1, 1), 10.0, AssertionError), + ("x0_minus_one", f64(-1, 1), 10.0, AssertionError), + ("x0_nan", f64(NAN, 1), 10.0, AssertionError), + ("x1_zero", f64(1, 0), 10.0, AssertionError), + ("x1_negative", f64(1, -1), 10.0, AssertionError), + ("x1_nan", f64(1, NAN), 10.0, AssertionError), +] +# fmt: on + + +class TestDamp: + @pytest.mark.parametrize( + ("x", "y", "s", "expected_kind"), + [pytest.param(*row[1:], id=row[0]) for row in DAMP_TABLE], + ) + def test_table(self, impl, x, y, s, expected_kind): + result = compare(impl.variational._damp, variational._damp, x, y, s) + assert kind(result) == expected_kind + + @pytest.mark.parametrize("seed", range(8)) + def test_random(self, impl, seed): + rng = np.random.default_rng(seed) + x = f64(rng.uniform(-0.9, 30), log_uniform(rng, -4, -1)) + y = f64(rng.uniform(-5, 30), log_uniform(rng, -4, -1)) + s = float(rng.uniform(0.05, 0.95)) + compare(impl.variational._damp, variational._damp, x, y, s) + + @pytest.mark.parametrize("which", [0, 1]) + def test_infinite_posterior_zero_message(self, impl, which): + # Compiled code divides inf by 0.0 and raises; the oracle returns d = 1. Needs + # an infinite posterior, which is unreachable without a prior failure. + x = f64(1, 1) + x[which] = INF + with pytest.raises(expected_error(ZeroDivisionError)): + impl.variational._damp(x, f64(0, 0), 0.5) + + +class TestRescale: + @pytest.mark.parametrize( + ("x", "s", "expected_kind"), + [pytest.param(*row[1:], id=row[0]) for row in RESCALE_TABLE], + ) + def test_table(self, impl, x, s, expected_kind): + result = compare(impl.variational._rescale, variational._rescale, x, s) + assert kind(result) == expected_kind + + @pytest.mark.parametrize("seed", range(8)) + def test_random(self, impl, seed): + rng = np.random.default_rng(seed) + x = f64(rng.uniform(-0.9, 3000), log_uniform(rng, -4, -1)) + s = float(rng.choice([10.0, 100.0, 1000.0])) + compare(impl.variational._rescale, variational._rescale, x, s) + + def test_zero_shape_offset_cap_below_one(self, impl): + # Compiled code divides by zero and raises; the oracle returns -inf. Direct + # call only: `propagate_*` assert `max_shape >= 1`. + with pytest.raises(expected_error(ZeroDivisionError)): + impl.variational._rescale(f64(0, 1), 0.5) + + +class TestCheckValidConstraints: + @staticmethod + def check(impl, constraints, parents, children, valid): + args = ( + np.array(constraints, dtype=np.float64), + np.array(parents, dtype=np.int32), + np.array(children, dtype=np.int32), + ) + func = impl.variational._check_valid_constraints + result = compare(func, variational._check_valid_constraints, *args) + if valid: + assert result.exception is None + else: + assert kind(result) is ValueError + assert str(result.exception) == INCONSISTENT_MESSAGE + + @pytest.mark.parametrize( + ("constraints", "parents", "children", "valid"), + [ + pytest.param(*row[1:], id=row[0]) + for row in [ + ("no_edges", [[0, 1], [0, 1]], [], [], True), + ("free_nodes", [[0, 0], [0, INF]], [1], [0], True), + ("lower_below_upper", [[0, 5], [3, 9]], [1], [0], True), + # boundary: the parent's upper bound equals the child's lower bound + ("equal_bounds", [[5, 5], [0, 5]], [1], [0], True), + ("equal_samples", [[5, 5], [5, 5]], [1], [0], True), + ("child_just_above", [[up(5.0, 6.0), 6], [0, 5]], [1], [0], False), + ("parent_just_below", [[5, 5], [0, up(5.0, 4.0)]], [1], [0], False), + # the max lower bound propagates up a chain, and from every child + ("chain_valid", [[5, 5], [0, 9], [0, 9]], [1, 2], [0, 1], True), + ("chain_invalid", [[5, 5], [0, INF], [0, 4]], [1, 2], [0, 1], False), + ("two_children", [[0, 0], [7, 7], [0, 6]], [2, 2], [0, 1], False), + ("sample_ancestor", [[0, 0], [10, 10]], [1], [0], True), + ("sample_descendant_older", [[10, 10], [0, 0]], [1], [0], False), + # NOTE: current behaviour, possibly a bug: the check is + # a single pass in edge order, so edges must be sorted children-first. + ( + "chain_edges_reversed", + [[5, 5], [0, INF], [0, 4]], + [2, 1], + [1, 0], + True, + ), + # NaN comparisons are false: NaN bounds are never inconsistent + ("nan_lower", [[NAN, NAN], [0, 5]], [1], [0], True), + ("nan_upper", [[5, 5], [0, NAN]], [1], [0], True), + ] + ], + ) + def test_table(self, impl, constraints, parents, children, valid): + self.check(impl, constraints, parents, children, valid) + + @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_historical"]) + @pytest.mark.parametrize("gap", ["equal", "one_ulp"]) + def test_real_edges(self, impl, snaps, ts_name, gap): + # the lower bound of a child equals the upper bound of its parent, or exceeds it + snap = snaps[ts_name] + constraints = snap.node_constraints.copy() + p, c = snap.edge_parents[-1], snap.edge_children[-1] + constraints[c, LOWER] = 500.0 + constraints[p, UPPER] = 500.0 if gap == "equal" else up(500.0, 0.0) + valid = gap == "equal" + self.check(impl, constraints, snap.edge_parents, snap.edge_children, valid) + + +class TestPropagateLikelihoodBranches: + """One edge (block) in each branch, with valid and failing projections""" + + CASES = { + "valid": dict(), + "damped": dict(cavity=ep_state.DAMPED_CAVITY, message=ep_state.DAMPED_MESSAGE), + # NOTE: current behaviour, possibly a bug: a failed projection + # is not reported; the posterior becomes the cavity and `lognorm` is NaN. + "projection_fails": dict(likelihood=(1.0, 1e300)), + } + + @pytest.mark.parametrize("case", CASES) + @pytest.mark.parametrize("branch", [b for b in BRANCHES if "both_fixed" not in b]) + def test_single_edge(self, impl, branch, case): + snap = tiny_snapshot(branch, **self.CASES[case]) + kwargs = dict(max_shape=1e300) # no posterior rescaling + if "sideways" in branch and case == "projection_fails": + # `sideways_moments` divides by zero for an astronomically large mutation + # target: compiled code raises where the oracle returns NaN and skips. + with pytest.raises(expected_error(ZeroDivisionError)): + ep_state.run_likelihood(impl.variational, snap, snap.unphased, **kwargs) + else: + compare_runs(ep_state.run_likelihood, impl, snap, snap.unphased, **kwargs) + + def test_twin_edge_in_phased_pass(self, impl): + # p == c is only valid for blocks; `twin_projection` asserts `unphased`. + # Direct call only: edges never have p == c in a tree sequence. + snap = tiny_snapshot("twin") + result = compare_runs(ep_state.run_likelihood, impl, snap, False) + assert kind(result) is AssertionError + assert str(result.exception) == "Invalid update" + + +class TestPropagateLikelihood: + SUBSET = slice(0, 400) # an initial portion of the pass keeps the oracle quick + + @staticmethod + def order(snap, unphased, subset=None): + order = snap.block_order if unphased else snap.edge_order + return order if subset is None else order[subset] + + @pytest.mark.parametrize( + ("ts_name", "max_shape", "min_step"), + [ + ("small_ts", 1000.0, 0.1), + ("small_ts_unphased", 1000.0, 0.1), + ("small_ts_historical", 1000.0, 0.1), + ("small_ts", 10.0, 0.5), + ("small_ts_unphased", 10.0, 0.5), + ], + ) + def test_natural(self, impl, snaps, ts_name, max_shape, min_step): + snap = snaps[ts_name] + unphased = unphased_name(ts_name) + counts = snap.branch_counts(unphased) + assert counts["both_free"] > 0 + assert counts["both_fixed"] == counts["fixed_parent"] == 0 + compare_runs( + ep_state.run_likelihood, + impl, + snap, + unphased, + max_shape=max_shape, + min_step=min_step, + ) + + @pytest.mark.parametrize( + "ts_name", ["small_ts", "small_ts_unphased", "small_ts_historical"] + ) + def test_forced_fixed_nodes(self, impl, snaps, ts_name): + # every branch: both nodes fixed (skipped), one fixed, both free + unphased = unphased_name(ts_name) + snap = ep_state.fixed_internal_snapshot(snaps[ts_name], unphased) + counts = snap.branch_counts(unphased) + assert all(v > 0 for k, v in counts.items() if k != "twin" or unphased) + compare_runs(ep_state.run_likelihood, impl, snap, unphased) + + @pytest.mark.parametrize("kind_of_order", ["empty", "partial_and_repeated"]) + def test_order(self, impl, snaps, kind_of_order): + # the order array is arbitrary: empty, or any subset with repeats + snap = snaps["small_ts"] + if kind_of_order == "empty": + order = np.zeros(0, dtype=np.int32) + else: + order = snap.edge_order[100:140] + order = np.concatenate((order, order[::-1], order[:5])).astype(np.int32) + compare_runs(ep_state.run_likelihood, impl, snap, False, order=order) + + @pytest.mark.parametrize( + "max_shape", + # NOTE: current behaviour, possibly a bug: a cap of exactly 1 + # zeroes posteriors and scales (and then every later update is NaN) + [1.0, up(1.0, 2.0), 3.0, 1e300], + ids=lambda v: f"max_shape={v:g}", + ) + @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_unphased"]) + def test_max_shape(self, impl, snaps, ts_name, max_shape): + snap = snaps[ts_name] + unphased = unphased_name(ts_name) + order = self.order(snap, unphased, self.SUBSET) + compare_runs( + ep_state.run_likelihood, + impl, + snap, + unphased, + max_shape=max_shape, + order=order, + ) + + @pytest.mark.parametrize( + "min_step", + [up(0.0, 1.0), 0.1, 0.99, 1 - 1e-9], + ids=lambda v: f"min_step={v:g}", + ) + @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_unphased"]) + def test_min_step(self, impl, snaps, ts_name, min_step): + snap = snaps[ts_name] + unphased = unphased_name(ts_name) + order = self.order(snap, unphased, self.SUBSET) + # a small cap makes passes difficult, so that damping is exercised + compare_runs( + ep_state.run_likelihood, + impl, + snap, + unphased, + min_step=min_step, + max_shape=3.0, + order=order, + ) + + @pytest.mark.parametrize("multiplier", [1e12, 1e300], ids=lambda v: f"y*{v:g}") + def test_extreme_counts(self, impl, snaps, multiplier): + # 1e12: projection failures are skipped (NaN lognorm). 1e300: a posterior + # becomes NaN and the next `_damp` asserts `0 < x[0] + 1`, + # reachable from real data (~1e300 mutations on an edge). + snap = snaps["small_ts"] + likelihoods = snap.edge_likelihoods * [multiplier, 1.0] + order = snap.edge_order[: self.SUBSET.stop] + compare_runs( + ep_state.run_likelihood, + impl, + snap, + False, + order=order, + likelihoods=likelihoods, + ) + + @pytest.mark.parametrize( + "kwargs", + [ + pytest.param(dict(max_shape=up(1.0, 0.0)), id="max_shape_below_one"), + pytest.param(dict(max_shape=0.0), id="max_shape_zero"), + pytest.param(dict(max_shape=NAN), id="max_shape_nan"), + pytest.param(dict(min_step=0.0), id="min_step_zero"), + pytest.param(dict(min_step=1.0), id="min_step_one"), + pytest.param(dict(min_step=-0.1), id="min_step_negative"), + pytest.param(dict(min_step=1.5), id="min_step_above_one"), + pytest.param(dict(min_step=NAN), id="min_step_nan"), + ], + ) + def test_invalid_parameters(self, impl, snaps, kwargs): + # reachable from user input (`max_shape`, `min_step` of `iterate`/`infer`): + # parameter errors in the C port, not internal asserts + snap = snaps["small_ts"] + order = snap.edge_order[:10] + assert_run_kind( + ep_state.run_likelihood, + impl, + snap, + AssertionError, + False, + order=order, + **kwargs, + ) + + @pytest.mark.parametrize( + "change", + ["children", "likelihoods", "constraints", "factors_larger"], + ) + def test_shape_mismatches(self, impl, snaps, change): + # direct calls only: these are checked while parsing arguments in C + snap = snaps["small_ts"] + args, lognorm = ep_state.likelihood_args(snap, False) + order, parents, children, likelihoods = args + constraints = snap.node_constraints + if change == "children": + children = children[:-1] + elif change == "likelihoods": + likelihoods = likelihoods[:-1] + elif change == "constraints": + constraints = constraints[:-1] + else: # factors have more edges than the arrays + parents, children = parents[:-1], children[:-1] + likelihoods = likelihoods[:-1] + + def call(ns): + ns.propagate_likelihood( + order, + parents, + children, + likelihoods, + constraints, + snap.node_posterior.copy(), + snap.factors(ns.EPFactors), + lognorm.copy(), + 1000.0, + 0.1, + ep_state.USE_EDGE_LIKELIHOOD, + ) + + result = compare( + lambda: call(impl.variational), lambda: call(variational), maxulp=0 + ) + assert kind(result) is AssertionError + + +class TestPropagateLikelihoodTinyScale: + """ + `propagate_likelihood` calls `_rescale_factors` (mid-pass) whenever the scale of + either node of the next edge is below `TINY` (strict), even if the edge is skipped + because both nodes are fixed. + """ + + @staticmethod + def shrunk(snap, role, scale): + """Equivalent state with the scale of one node tiny, first used mid-pass""" + snap = snap.copy() + nodes = snap.edge_parents if role == "parent" else snap.edge_children + first = {} + for pos, i in enumerate(snap.edge_order): + first.setdefault(nodes[i], pos) + target = len(snap.edge_order) // 3 + node = min(first, key=lambda n: abs(first[n] - target)) + snap.unscale([node], scale) + return snap + + @pytest.mark.parametrize( + ("role", "scale"), + [ + ("parent", TINY / 1e6), + ("child", TINY / 1e6), + ("child", up(TINY, 0.0)), + ("child", TINY), + ("parent", 2 * TINY), + ], + ids=[ + "parent-below", + "child-below", + "child-just-below", + "child-at", + "parent-above", + ], + ) + def test_threshold(self, impl, snaps, role, scale): + snap = self.shrunk(snaps["small_ts"], role, scale) + order = snap.edge_order[: len(snap.edge_order) // 2] + compare_runs(ep_state.run_likelihood, impl, snap, False, order=order) + + def test_skipped_fixed_edge(self, impl, snaps): + # a fixed sample with a tiny scale whose edge is skipped (both nodes fixed) + base = snaps["small_ts_historical"].copy() + sample = np.flatnonzero(base.fixed)[0] + edge = np.flatnonzero(base.edge_children == sample)[0] + base.fix_nodes([base.edge_parents[edge]]) + assert base.branch_counts(False)["both_fixed"] > 0 + base.unscale([sample], TINY / 1e6) + compare_runs(ep_state.run_likelihood, impl, base, False) + + +class TestPropagatePrior: + @pytest.mark.parametrize("ts_name", TS_NAMES) + def test_natural(self, impl, snaps, ts_name): + snap = snaps[ts_name] + assert snap.unconstrained_roots.any() + compare_runs(ep_state.run_prior, impl, snap, snap.unconstrained_roots) + + @pytest.mark.parametrize( + ("scaled", "em_maxitt", "em_reltol"), + # `em_maxitt`: no iteration (-1), one (0), the cap binding (3), convergence + # binding (1000); `em_reltol`: run to the cap (0), tight, loose, NaN (no + # iteration) + [(False, m, r) for m in [-1, 0, 3, 1000] for r in [0.0, 1e-8, 0.5, NAN]] + + [(True, 0, 1e-8), (True, 3, 1e-8), (True, 1000, 0.5)], + ids=lambda v: f"{v}" if isinstance(v, bool) else f"{v:g}", + ) + def test_em(self, impl, snaps, scaled_snap, scaled, em_maxitt, em_reltol): + snap = scaled_snap if scaled else snaps["small_ts"] + compare_runs( + ep_state.run_prior, + impl, + snap, + snap.unconstrained_roots, + em_maxitt=em_maxitt, + em_reltol=em_reltol, + max_shape=1e300, + ) + + @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_historical"]) + @pytest.mark.parametrize( + "max_shape", + # NOTE: current behaviour, possibly a bug: a cap of exactly 1 + # zeroes the posteriors and scales of the free nodes + [1.0, 1.5, 1e300], + ids=lambda v: f"max_shape={v:g}", + ) + def test_max_shape(self, impl, snaps, ts_name, max_shape): + snap = snaps[ts_name] + compare_runs( + ep_state.run_prior, + impl, + snap, + snap.unconstrained_roots, + max_shape=max_shape, + ) + + @pytest.mark.parametrize( + ("ts_name", "free", "kwargs"), + [ + ("small_ts", "single_root", {}), + # any node set with proper cavities works, not only roots + ("small_ts_unphased", "internal", {}), + ("small_ts", "none", {}), + # no free nodes returns before looking at anything else + ("small_ts", "none", dict(em_maxitt=-5, em_reltol=NAN, max_shape=1.0)), + ], + ids=["single_root", "internal", "none", "none_odd_arguments"], + ) + def test_free_nodes(self, impl, snaps, ts_name, free, kwargs): + snap = snaps[ts_name] + mask = np.zeros(snap.node_posterior.shape[0], dtype=bool) + if free == "single_root": + mask[np.flatnonzero(snap.unconstrained_roots)[0]] = True + elif free == "internal": + mask = ~snap.fixed & ~snap.roots | snap.unconstrained_roots + compare_runs(ep_state.run_prior, impl, snap, mask, **kwargs) + + @staticmethod + def zero_posterior(snap): + snap = snap.copy() + snap.node_posterior[:] = 0.0 + snap.fields["node"][:] = 0.0 + return snap + + @staticmethod + def negative_cavity_rate(snap): + snap = snap.copy() + free = snap.unconstrained_roots + snap.fields["node"][free, MIXPRIOR, 1] = snap.node_posterior[free, 1] + 1.0 + return snap + + @pytest.mark.parametrize( + "case", + [ + # `assert penalty > 0` fails when the mean of shape / rate is infinite or + # negative: free nodes whose cavity has zero rate (fixed leaves, or a root + # where every update was skipped) or negative rate + "all_nodes", + "leaves", + "zero_posterior", + "negative_cavity_rate", + # reachable from user input + "max_shape_below_one", + "max_shape_zero", + "max_shape_nan", + # direct calls only + "free_too_short", + "free_too_long", + ], + ) + def test_assertions(self, impl, snaps, case): + snap = snaps["small_ts"] + free = snap.unconstrained_roots + kwargs = {} + if case == "all_nodes": + free = np.ones_like(free) + elif case == "leaves": + free = snap.leaves + elif case == "zero_posterior": + snap = self.zero_posterior(snap) + elif case == "negative_cavity_rate": + snap = self.negative_cavity_rate(snap) + elif case.startswith("max_shape"): + kwargs["max_shape"] = { + "below_one": up(1.0, 0.0), + "zero": 0.0, + "nan": NAN, + }[case[len("max_shape_") :]] + elif case == "free_too_short": + free = free[:-1] + else: + free = np.append(free, True) + assert_run_kind(ep_state.run_prior, impl, snap, AssertionError, free, **kwargs) + + def test_penalty_assert_reachable_from_ep(self, impl, fresh): + # NOTE: current behaviour, possibly a bug: a likelihood pass in + # which every update is skipped (a huge mutational target) leaves the roots + # with a zero posterior, so that `iterate(regularise=True)` fails the + # `penalty > 0` assert (an AssertionError, not NaN). + base = fresh["small_ts"].copy() + base.edge_likelihoods = base.edge_likelihoods * [1.0, 1e300] + + def run(ns): + state = ep_state.run_likelihood(ns, base, False) + step = base.after_pass(state) + return ep_state.run_prior(ns, step, step.unconstrained_roots) + + result = compare(lambda: run(impl.variational), lambda: run(variational)) + assert kind(result) is AssertionError + + +class TestPropagateMutations: + @pytest.mark.parametrize( + ("ts_name", "unphased"), + [ + ("small_ts", False), + ("small_ts_historical", False), + ("small_ts_unphased", False), + ("small_ts_unphased", True), + ], + ) + def test_natural(self, impl, snaps, ts_name, unphased): + compare_runs(ep_state.run_mutations, impl, snaps[ts_name], unphased) + + @pytest.mark.parametrize( + ("ts_name", "unphased"), + [ + ("small_ts", False), + ("small_ts_historical", False), + ("small_ts_unphased", True), + ], + ) + def test_forced_fixed_nodes(self, impl, snaps, ts_name, unphased): + # mutations on edges of every kind: both nodes fixed, one of the two fixed + snap = ep_state.fixed_internal_snapshot(snaps[ts_name], unphased) + counts = snap.branch_counts(unphased) + assert all(counts[k] > 0 for k in ("both_fixed", "fixed_parent", "fixed_child")) + compare_runs(ep_state.run_mutations, impl, snap, unphased) + + @pytest.mark.parametrize("case", ["null_edges", "order_subset_and_repeats"]) + def test_mutation_selection(self, impl, snaps, case): + # mutations above the root have edge NULL and are skipped; the order is any + # subset of the mutations, with repeats + snap = snaps["small_ts"] + kwargs = {} + if case == "null_edges": + edges = snap.mutation_edges.copy() + edges[::7] = tskit.NULL + kwargs["edges"] = edges + else: + kwargs["order"] = np.array([5, 3, 3, 100, 5], dtype=np.int32) + compare_runs(ep_state.run_mutations, impl, snap, False, **kwargs) + + @pytest.mark.parametrize( + ("branch", "case"), + [ + (b, c) + for b in BRANCHES + for c in ["valid", "projection_fails"] + # fixed edges do not use the likelihood + if not (c == "projection_fails" and "both_fixed" in b) + ], + ) + def test_single_edge(self, impl, branch, case): + # NOTE: current behaviour, possibly a bug: a mutation whose + # projection fails gets NaN posterior and phase, silently left in the result. + fails = case == "projection_fails" + likelihood = (1.0, 1e300) if fails else (3.0, 0.1) + snap = tiny_snapshot(branch, likelihood=likelihood) + if fails and "sideways" in branch: + # as in propagate_likelihood: compiled `*_sideways_moments` raises + with pytest.raises(expected_error(ZeroDivisionError)): + ep_state.run_mutations(impl.variational, snap, snap.unphased) + else: + compare_runs(ep_state.run_mutations, impl, snap, snap.unphased) + + def test_twin_in_phased_pass(self, impl): + # unlike propagate_likelihood, there is no `unphased` assert for p == c; the + # twin projection is used as is (direct call only: edges never have p == c) + snap = tiny_snapshot("twin") + snap.mutation_blocks[:] = tskit.NULL + assert_run_kind(ep_state.run_mutations, impl, snap, "finite", False) + + @pytest.mark.parametrize( + ("ages", "expected_kind"), + [ + # the edge projection is uniform on (child, parent): variance 0 fails; + # reachable with two samples of the same time, one the + # ancestor of the other + pytest.param([[5, 5], [5, 5]], "nan", id="equal_ages"), + pytest.param([[5, 5], [up(5.0, 6.0)] * 2], "finite", id="nextafter_ages"), + # NOTE: current behaviour, possibly a bug: ages in the wrong + # order are not detected (the moments are symmetric) + pytest.param([[10, 10], [0, 0]], "finite", id="inverted_ages"), + ], + ) + def test_fixed_edge_ages(self, impl, ages, expected_kind): + snap = tiny_snapshot("both_fixed") + snap.node_constraints[:] = ages + assert_run_kind(ep_state.run_mutations, impl, snap, expected_kind, False) + + @pytest.mark.parametrize("change", ["edges_size", "posterior_size"]) + def test_shape_mismatches(self, impl, snaps, change): + # direct calls only: checked while parsing arguments in C + snap = snaps["small_ts"] + if change == "edges_size": + kwargs = dict(edges=snap.mutation_edges[:-1]) + else: + kwargs = dict(posterior=snap.node_posterior[:-1]) + assert_run_kind( + ep_state.run_mutations, impl, snap, AssertionError, False, **kwargs + ) + + +class TestMultiSweep: + """ + Whole sweeps from the initial state. One ulp of difference in an intermediate + result grows to ~1e-6 in node means after a sweep (see + `evaluation/ep_sensitivity.py`), so node means are compared to a relative + tolerance, and the pattern of skipped updates (NaN) must be identical. + """ + + CASES = { + "small_ts": ("small_ts", {}), + "small_ts_unphased": ("small_ts_unphased", {}), + "small_ts_historical_cap": ( + "small_ts_historical", + dict(max_shape=10.0, min_step=0.5, em_maxitt=3), + ), + } + + @staticmethod + def means(posterior): + with np.errstate(all="ignore"): + return (posterior[:, 0] + 1) / posterior[:, 1] + + def assert_means_close(self, actual, expected, rtol): + a, e = self.means(actual), self.means(expected) + assert np.array_equal(np.isfinite(a), np.isfinite(e)) + ok = np.isfinite(a) + np.testing.assert_allclose(a[ok], e[ok], rtol=rtol) + + @pytest.mark.parametrize("case", CASES) + def test_sweeps(self, impl, fresh, case): + name, kwargs = self.CASES[case] + snap = fresh[name] + sweeps = 4 + actual = ep_state.run_sweeps(impl.variational, snap, sweeps, **kwargs) + expected = ep_state.run_sweeps(variational, snap, sweeps, **kwargs) + for sweep, (a, e) in enumerate(zip(actual[0], expected[0])): + assert np.array_equal(np.isnan(a[1]), np.isnan(e[1])) # edge lognorm + assert np.array_equal(np.isnan(a[2]), np.isnan(e[2])) # block lognorm + rtol = 1e-4 if sweep == 0 else 1e-6 + self.assert_means_close(a[0], e[0], rtol) + mutation_actual, mutation_expected = actual[1][0], expected[1][0] + assert np.array_equal(np.isnan(mutation_actual), np.isnan(mutation_expected)) + self.assert_means_close(mutation_actual, mutation_expected, 1e-6) From 58cab9fbdaa7c63aa224e1ecc0fdc728a1a1d634 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 20 Nov 2026 13:46:37 -0800 Subject: [PATCH 05/56] Test rescaling, phasing, util, prior and discrete against their oracles Each jitted function in these modules is compared with its oracle to within 4 ulp, including the arrays it updates in place and the exceptions it raises: on simulated tree sequences and real EP output, on small hand-built tree sequences that isolate one case each (no edges, no mutations, gaps, breakpoints, unsorted input, excluded or fixed nodes, NaN phases), on boundary values of the arguments, and on one seeded random input per function. Argument validation is covered by truncating each array argument in turn. Behaviour that looks wrong is kept and marked "current behaviour, possibly a bug", so that a port reproduces it and a later fix shows up as a deliberate test change. --- tests/test_oracle_discrete.py | 67 +++ tests/test_oracle_phasing.py | 391 ++++++++++++++++ tests/test_oracle_prior.py | 124 +++++ tests/test_oracle_rescaling.py | 827 +++++++++++++++++++++++++++++++++ tests/test_oracle_util.py | 400 ++++++++++++++++ 5 files changed, 1809 insertions(+) create mode 100644 tests/test_oracle_discrete.py create mode 100644 tests/test_oracle_phasing.py create mode 100644 tests/test_oracle_prior.py create mode 100644 tests/test_oracle_rescaling.py create mode 100644 tests/test_oracle_util.py diff --git a/tests/test_oracle_discrete.py b/tests/test_oracle_discrete.py new file mode 100644 index 00000000..830c57e4 --- /dev/null +++ b/tests/test_oracle_discrete.py @@ -0,0 +1,67 @@ +""" +Parity of ``LogLikelihoods.logsumexp`` (a streaming log-sum-exp) with its oracle, +including NaN and infinities (which are not errors) and non-contiguous input. +""" + +import numpy as np +import pytest +from oracle import discrete +from oracle.helpers import INF, NAN, assert_outcome, assert_ulp_close, compare + +# x, outcome category of the oracle +EDGE_CASES = [ + pytest.param([], "nonfinite", id="empty"), + pytest.param([5.0], "finite", id="single"), + pytest.param([1e-320], "finite", id="single_subnormal"), + pytest.param([-INF], "nonfinite", id="single_minus_inf"), + pytest.param([-INF] * 7, "nonfinite", id="all_minus_inf"), + pytest.param([-INF, 5.0, -INF], "finite", id="minus_inf_ignored"), + pytest.param([-3.5, -INF, -INF], "finite", id="finite_first"), + pytest.param([-INF, -INF, -3.5], "finite", id="finite_last"), + pytest.param([-0.0, 0.0], "finite", id="negative_zero"), + pytest.param([1000.0, 1000.0], "finite", id="would_overflow_naively"), + pytest.param([-1000.0, -1000.0], "finite", id="would_underflow_naively"), + pytest.param([1e308, 1e308], "finite", id="huge_equal"), + pytest.param([-1e308, 1e308], "finite", id="huge_opposite"), + pytest.param([1e308, -1e308], "finite", id="huge_opposite_reversed"), + pytest.param([-800.0, 0.0, -800.0], "finite", id="dominated_middle"), + pytest.param([0.0, -800.0, -800.0], "finite", id="dominated_first"), + pytest.param([-800.0, -800.0, 0.0], "finite", id="dominated_last"), + pytest.param([1.0, 2.0, 3.0], "finite", id="increasing"), + pytest.param([3.0, 2.0, 1.0], "finite", id="decreasing"), + # NOTE: a single +inf gives +inf, but inf - inf makes NaN with two of them + pytest.param([INF], "nonfinite", id="inf"), + pytest.param([0.0, INF], "nonfinite", id="finite_and_inf"), + pytest.param([INF, INF], "nan", id="two_inf"), + pytest.param([INF, -INF, INF], "nan", id="two_inf_with_minus_inf"), + pytest.param([INF, -INF], "nonfinite", id="inf_and_minus_inf"), + # NOTE: NaN is not -inf and fails `x <= alpha`, so it takes the "new maximum" + # branch and poisons the result wherever it is + pytest.param([NAN], "nan", id="nan"), + pytest.param([NAN, 1.0], "nan", id="nan_first"), + pytest.param([1.0, NAN], "nan", id="nan_last"), + pytest.param([1.0, NAN, 2.0], "nan", id="nan_middle"), +] + + +class TestLogsumexp: + @pytest.mark.parametrize(("x", "expected_kind"), EDGE_CASES) + def test_edge_cases(self, impl, x, expected_kind): + x = np.array(x, dtype=float) + assert_outcome(impl.discrete.logsumexp, discrete.logsumexp, (x,), expected_kind) + + def test_non_contiguous_input(self, impl): + # `compare` copies its arguments to contiguous arrays, so call directly + x = np.arange(1.0, 10.0)[::2] + assert not x.flags.c_contiguous + assert_ulp_close(impl.discrete.logsumexp(x), discrete.logsumexp(x)) + + @pytest.mark.parametrize("mode", ["typical", "extreme"]) + @pytest.mark.parametrize("seed", range(4)) + def test_random(self, impl, seed, mode): + rng = np.random.default_rng(seed) + size = int(rng.integers(1, 500)) + scale = {"typical": 5.0, "extreme": 1e5}[mode] + x = rng.normal(0, scale, size) + x[rng.random(size) < rng.uniform(0, 1)] = -INF + compare(impl.discrete.logsumexp, discrete.logsumexp, x) diff --git a/tests/test_oracle_phasing.py b/tests/test_oracle_phasing.py new file mode 100644 index 00000000..24e9d253 --- /dev/null +++ b/tests/test_oracle_phasing.py @@ -0,0 +1,391 @@ +""" +Parity of the jitted functions in ``tsdate.phasing`` with their oracles: random +inputs built as in ``ExpectationPropagation``, degenerate inputs, and every +``assert``. +""" + +import numpy as np +import pytest +import tskit +from oracle import phasing +from oracle.helpers import INF, NAN, assert_ulp_close, compare, make_ts, shrink + +from tsdate.phasing import block_singletons +from tsdate.rescaling import count_mutations + + +def sweep_args(ts): + """Tree sequence arguments shared by the sweep-line functions""" + return [ + ts.mutations_node, + ts.sites_position[ts.mutations_site], + ts.edges_parent, + ts.edges_child, + ts.edges_left, + ts.edges_right, + ts.indexes_edge_insertion_order, + ts.indexes_edge_removal_order, + ts.sequence_length, + ] + + +# nodes 0, 1 belong to individual 0, nodes 2, 3 to individual 1, node 4 is the root +NODES = [(1, 0, 0), (1, 0, 0), (1, 0, 1), (1, 0, 1), (0, 1, -1)] +STAR = [(0, 10, 4, 0), (0, 10, 4, 1), (0, 10, 4, 2), (0, 10, 4, 3)] +GAP = [(0, 4, 4, 0), (0, 4, 4, 1), (6, 10, 4, 0), (6, 10, 4, 1)] + STAR[2:] +SKEW = [(0, 4, 4, 0), (0, 6, 4, 1), (4, 10, 4, 0), (6, 10, 4, 1)] + STAR[2:] +SPLIT = [(0, 5, 4, 0), (5, 10, 4, 0), (0, 10, 4, 1)] + STAR[2:] +NO_INDIVIDUALS = [(1, 0, -1), (1, 0, -1), (0, 1, -1)] +ONE_INDIVIDUAL = [(1, 0, 0), (1, 0, 0), (1, 0, -1), (0, 1, -1)] + +# nodes, number of individuals, edges, mutations, unphased, exception of the oracle +BLOCK_EDGE_CASES = [ + pytest.param(NODES, 2, STAR, [(1, 4)], [1, 1], None, id="no_singletons"), + pytest.param(NODES, 2, STAR, [(1, 0)], [1, 1], None, id="singleton"), + pytest.param(NODES, 2, STAR, [(1, 0)], [0, 0], None, id="all_phased"), + pytest.param(NODES, 2, STAR, [], [1, 1], None, id="no_mutations"), + pytest.param(NODES, 2, [], [(1, 0)], [1, 1], None, id="no_edges"), + pytest.param( + NO_INDIVIDUALS, + 0, + [(0, 10, 2, 0), (0, 10, 2, 1)], + [(1, 0)], + [], + None, + id="no_individuals", + ), + pytest.param( + ONE_INDIVIDUAL, + 1, + [(0, 10, 3, 0), (0, 10, 3, 1), (0, 10, 3, 2)], + [(1, 0), (2, 2)], + [1], + None, + id="node_without_individual", + ), + # NOTE: current behaviour, possibly a bug: reachable from real data + # (one haplotype of an unphased individual missing over a region); its block is + # never flushed and the final consistency check fails with a bare AssertionError + pytest.param( + NODES, + 2, + [(0, 10, 4, 0), (0, 10, 4, 2), (0, 10, 4, 3)], + [(1, 0)], + [1, 1], + AssertionError, + id="one_haplotype_edge_missing", + ), +] + +# edges, mutations, unphased, mutation_block (block ids are numbered in the order +# that blocks start; a mutation in no block is NULL) +BLOCK_NUMBERING = [ + pytest.param(STAR, [(1, 0)], [1, 1], [0], id="singleton"), + pytest.param(STAR, [(1, 0), (2, 2), (3, 0)], [1, 0], [0, tskit.NULL, 0], id="mixed"), + pytest.param( + GAP, + [(1, 0), (5, 0), (7, 0), (7.5, 1)], + [1, 1], + [0, tskit.NULL, 2, 2], + id="mutation_in_gap", + ), + pytest.param(SPLIT, [(1, 0), (7, 0)], [1, 1], [0, 2], id="breakpoint_one_node"), + pytest.param( + SKEW, + [(1, 0), (5, 0), (5.5, 1), (8, 1), (8.5, 0)], + [1, 1], + [0, 2, 2, 3, 3], + id="breakpoints_differ", + ), +] + + +class TestBlockSingletons: + @staticmethod + def args(ts, unphased): + unphased = np.array(unphased, dtype=bool) + return [unphased, ts.nodes_individual, *sweep_args(ts)] + + @staticmethod + def compare(impl, args): + return compare(impl.phasing._block_singletons, phasing._block_singletons, *args) + + @pytest.mark.parametrize( + ("nodes", "num_individuals", "edges", "mutations", "unphased", "expected_error"), + BLOCK_EDGE_CASES, + ) + def test_edge_cases( + self, impl, nodes, num_individuals, edges, mutations, unphased, expected_error + ): + ts = make_ts(nodes, edges, mutations, 10.0, num_individuals) + result = self.compare(impl, self.args(ts, unphased)) + assert result.error is expected_error + + @pytest.mark.parametrize( + ("edges", "mutations", "unphased", "expected"), BLOCK_NUMBERING + ) + def test_block_numbering(self, impl, edges, mutations, unphased, expected): + ts = make_ts(NODES, edges, mutations, 10.0, 2) + _, _, mutation_block = self.compare(impl, self.args(ts, unphased)).value + assert mutation_block.tolist() == expected + + @pytest.mark.parametrize(("index", "size"), [(5, 3), (8, 3), (3, 1)]) + def test_size_mismatch(self, impl, index, size): + ts = make_ts(NODES, STAR, [(1, 0), (2, 1)], 10.0, 2) + args = shrink(self.args(ts, [1, 1]), index, size) + result = self.compare(impl, args) + assert result.error is AssertionError + + @pytest.mark.parametrize("fraction", [0.0, 0.5, 1.0]) + @pytest.mark.parametrize("seed", range(2)) + def test_random(self, impl, small_ts_unphased, seed, fraction): + ts = small_ts_unphased + rng = np.random.default_rng(seed) + unphased = rng.random(ts.num_individuals) < fraction + args = self.args(ts, unphased) + result = self.compare(impl, args) + # also the dtypes, which `compare` ignores, and the public wrapper + actual = impl.phasing._block_singletons(*args) + assert actual[1].dtype == actual[2].dtype == np.int32 + assert_ulp_close(actual, block_singletons(ts, unphased)) + assert result.value[1].dtype == np.int32 + + +@pytest.fixture(scope="module") +def blocks(small_ts_unphased): + """Likelihoods and blocks for `reallocate_unphased`, with all individuals unphased""" + ts = small_ts_unphased + unphased = np.full(ts.num_individuals, True) + _, block_edges, mutation_blocks = block_singletons(ts, unphased) + likelihoods, _ = count_mutations(ts) + return ts, likelihoods, mutation_blocks, block_edges + + +# likelihoods, phase, mutation_blocks, blocks_edges, outcome of the oracle +REALLOCATE_SMALL = [ + pytest.param( + np.array([[2.0, 5.0], [0.0, 5.0]]), + np.array([0.0, 0.0]), + np.array([0, 0], dtype=np.int32), + np.array([[0, 1]], dtype=np.int32), + None, + id="phases_zero", + ), + pytest.param( + np.array([[2.0, 5.0], [0.0, 5.0]]), + np.array([1.0, 1.0]), + np.array([0, 0], dtype=np.int32), + np.array([[0, 1]], dtype=np.int32), + None, + id="phases_one", + ), + pytest.param( + np.array([[2.0, 5.0], [0.0, 5.0], [7.0, 5.0]]), + np.array([0.25, 1.0, NAN]), + np.array([0, 0, -1], dtype=np.int32), + np.array([[0, 1]], dtype=np.int32), + None, + id="single_block_with_unblocked_nan", + ), + pytest.param( + np.array([[3.0, 1.0], [1.0, 1.0], [0.0, 1.0]]), + np.full(4, 0.5), + np.array([0, 0, 1, 1], dtype=np.int32), + np.array([[0, 1], [1, 2]], dtype=np.int32), + None, + id="edge_in_two_blocks", + ), + pytest.param( + np.zeros((0, 2)), + np.zeros(0), + np.zeros(0, dtype=np.int32), + np.zeros((0, 2), dtype=np.int32), + None, + id="nothing_at_all", + ), + pytest.param( + np.ones((2, 2)), + np.array([0.5]), + np.array([0], dtype=np.int32), + np.array([[0, -1]], dtype=np.int32), + AssertionError, + id="null_edge_in_block", + ), +] + + +class TestReallocateUnphased: + @staticmethod + def compare(impl, *args): + return compare( + impl.phasing.reallocate_unphased, phasing.reallocate_unphased, *args + ) + + @pytest.mark.parametrize( + ("lik", "phase", "mutation_blocks", "blocks_edges", "expected_error"), + REALLOCATE_SMALL, + ) + def test_small(self, impl, lik, phase, mutation_blocks, blocks_edges, expected_error): + result = self.compare(impl, lik, phase, mutation_blocks, blocks_edges) + assert result.error is expected_error + + @pytest.mark.parametrize("mode", ["fractional", "mixed"]) + @pytest.mark.parametrize("seed", range(3)) + def test_random(self, impl, blocks, seed, mode): + ts, lik, mutation_blocks, block_edges = blocks + rng = np.random.default_rng(seed) + if mode == "fractional": + phase = rng.uniform(0, 1, ts.num_mutations) + else: + phase = rng.choice([0.0, 1.0, 0.5, 0.25], ts.num_mutations) + self.compare(impl, lik, phase, mutation_blocks, block_edges) + + @pytest.mark.parametrize("value", [1.5, -1e-9, INF, -INF]) + def test_phase_out_of_range(self, impl, blocks, value): + _, lik, mutation_blocks, block_edges = blocks + phase = np.full(mutation_blocks.size, 0.5) + phase[np.flatnonzero(mutation_blocks >= 0)[0]] = value + result = self.compare(impl, lik, phase, mutation_blocks, block_edges) + assert result.error is AssertionError + + @pytest.mark.parametrize("value", [NAN, 7.0]) + def test_phase_ignored_without_block(self, impl, blocks, value): + _, lik, mutation_blocks, block_edges = blocks + phase = np.full(mutation_blocks.size, 0.5) + phase[mutation_blocks == tskit.NULL] = value + result = self.compare(impl, lik, phase, mutation_blocks, block_edges) + assert result.error is None + + def test_nan_phase(self, impl, blocks): + # NOTE: current behaviour, possibly a bug: a NaN phase on a + # blocked mutation is skipped, leaving its singleton unallocated, so the + # final `np.isclose` check fails (a bare AssertionError). It only passes if + # the likelihoods happen to total one less + _, lik, mutation_blocks, block_edges = blocks + phase = np.full(mutation_blocks.size, 0.5) + phase[np.flatnonzero(mutation_blocks >= 0)[0]] = NAN + result = self.compare(impl, lik, phase, mutation_blocks, block_edges) + assert result.error is AssertionError + lik = lik.copy() + lik[block_edges[0, 0], 0] -= 1.0 + result = self.compare(impl, lik, phase, mutation_blocks, block_edges) + assert result.error is None + + @pytest.mark.parametrize("case", ["no_mutations", "all_unblocked"]) + def test_blocks_without_singletons(self, impl, blocks, case): + # likelihood mass on the block edges, but no mutation to allocate it + ts, lik, _, block_edges = blocks + size = 0 if case == "no_mutations" else ts.num_mutations + phase = np.full(size, 0.5) + mutation_blocks = np.full(size, tskit.NULL, dtype=np.int32) + result = self.compare(impl, lik, phase, mutation_blocks, block_edges) + assert result.error is AssertionError + + @pytest.mark.parametrize("case", ["phase", "blocks_transposed"]) + def test_size_mismatch(self, impl, blocks, case): + ts, lik, mutation_blocks, block_edges = blocks + phase = np.full(ts.num_mutations, 0.5) + if case == "phase": + phase = phase[:-1] + else: + block_edges = np.ascontiguousarray(block_edges.T) + result = self.compare(impl, lik, phase, mutation_blocks, block_edges) + assert result.error is AssertionError + + +# samples 0, 1, 2 (time 0), internal nodes 3 (time 1) and 4 (time 2); node 3 is a +# child of 4 throughout, but its parent edge is split at position 5 +FREQ_NODES = [(1, 0), (1, 0), (1, 0), (0, 1), (0, 2)] +FREQ_EDGES = [(0, 10, 3, 0), (0, 10, 3, 1), (0, 5, 4, 3), (0, 10, 4, 2), (5, 10, 4, 3)] +FREQ_MUTATIONS = [(1, 0), (2, 3), (3, 4), (6, 2), (7, 3)] + +SAMPLE_SETS = [ + pytest.param([[0, 1, 2]], id="all_samples"), + pytest.param([[0]], id="single_sample"), + pytest.param([[]], id="empty_set"), + pytest.param([], id="no_sets"), + pytest.param([[], [0, 1, 2]], id="empty_and_full"), + pytest.param([[0, 1], [1, 2], [0, 1, 2]], id="overlapping"), + pytest.param([[0, 1], [0, 1]], id="identical"), + pytest.param([[3]], id="internal_node"), + pytest.param([[4, 0]], id="root_and_sample"), +] + + +@pytest.fixture(scope="module") +def freq_ts(): + return make_ts(FREQ_NODES, FREQ_EDGES, FREQ_MUTATIONS, 10.0) + + +class TestMutationFrequency: + @staticmethod + def compare(impl, nodes_sample, args): + return compare( + impl.phasing._mutation_frequency, + phasing._mutation_frequency, + nodes_sample, + *args, + ) + + @staticmethod + def nodes_sample(ts, members): + nodes_sample = np.zeros((ts.num_nodes, len(members)), dtype=bool) + for i, m in enumerate(members): + nodes_sample[list(m), i] = True + return nodes_sample + + @pytest.mark.parametrize("members", SAMPLE_SETS) + def test_sample_sets(self, impl, freq_ts, members): + nodes_sample = self.nodes_sample(freq_ts, members) + self.compare(impl, nodes_sample, sweep_args(freq_ts)) + + def test_no_mutations(self, impl): + ts = make_ts([(1, 0), (0, 1)], [(0, 10, 1, 0)], [], 10.0) + self.compare(impl, self.nodes_sample(ts, [[0]]), sweep_args(ts)) + + def test_no_edges(self, impl): + # NOTE: current behaviour, possibly a bug: with no edges the + # sweep is never entered, so every frequency is zero, even above a member + ts = make_ts([(1, 0), (0, 1)], [], [(1, 0), (2, 1)], 10.0) + self.compare(impl, self.nodes_sample(ts, [[0, 1]]), sweep_args(ts)) + + def test_mutation_beyond_last_edge(self, impl): + nodes = [(1, 0), (1, 0), (0, 1)] + edges = [(0, 5, 2, 0), (0, 5, 2, 1)] + ts = make_ts(nodes, edges, [(1, 2), (7, 2)], 10.0) + self.compare(impl, self.nodes_sample(ts, [[0, 1]]), sweep_args(ts)) + + def test_mutation_at_breakpoint(self, impl): + # a mutation exactly at a breakpoint belongs to the tree to its right + ts = make_ts(FREQ_NODES, FREQ_EDGES, [(5, 4)], 10.0) + self.compare(impl, self.nodes_sample(ts, [[0, 1, 2]]), sweep_args(ts)) + + def test_unsorted_mutations(self, impl, freq_ts): + order = np.array([3, 0, 4, 1, 2]) + args = sweep_args(freq_ts) + args[0], args[1] = args[0][order], args[1][order] + self.compare(impl, self.nodes_sample(freq_ts, [[0, 1, 2]]), args) + + @pytest.mark.parametrize(("index", "size"), [(3, 3), (6, 3), (1, 2)]) + def test_size_mismatch(self, impl, freq_ts, index, size): + nodes_sample = np.ones((freq_ts.num_nodes, 1), dtype=bool) + args = shrink(sweep_args(freq_ts), index, size) + result = self.compare(impl, nodes_sample, args) + assert result.error is AssertionError + + @pytest.mark.parametrize("num_sets", [1, 4]) + @pytest.mark.parametrize("seed", range(2)) + def test_random(self, impl, small_ts, seed, num_sets): + ts = small_ts + rng = np.random.default_rng(seed) + members = [ + rng.choice( + ts.samples(), size=int(rng.integers(0, ts.num_samples + 1)), replace=False + ) + for _ in range(num_sets) + ] + nodes_sample = self.nodes_sample(ts, members) + result = self.compare(impl, nodes_sample, sweep_args(ts)) + # also the dtype, which `compare` ignores + actual = impl.phasing._mutation_frequency(nodes_sample, *sweep_args(ts)) + assert actual.dtype == result.value.dtype == np.int32 diff --git a/tests/test_oracle_prior.py b/tests/test_oracle_prior.py new file mode 100644 index 00000000..0be90cd0 --- /dev/null +++ b/tests/test_oracle_prior.py @@ -0,0 +1,124 @@ +""" +Parity of ``_marginalize_over_ancestors`` and ``conditional_coalescent_variance`` +with their oracles, and a pin of how ``tsdate`` calls the latter with a single tip. +""" + +import numpy as np +import pytest +import tskit +from oracle import prior +from oracle.helpers import INF, NAN, assert_outcome, compare + +import tsdate +from tsdate import prior as tsdate_prior + + +def coalescent_moments(num_tips): + """The argument that `conditional_coalescent_variance` passes""" + rates = np.array( + [2 / (i * (i - 1)) if i > 1 else 0.0 for i in range(1, num_tips + 1)] + ) + mean, variance = rates.copy(), rates.copy() ** 2 + for i in range(rates.size - 2, 0, -1): + mean[i] += mean[i + 1] + variance[i] += variance[i + 1] + return np.stack((mean, variance + mean**2), 1) + + +# val, outcome category of the oracle +MARGINALIZE_EDGE_CASES = [ + pytest.param(np.array([[1.0, 2.0], [3.0, 4.0]]), "finite", id="two_tips"), + pytest.param(np.zeros((6, 2)), "finite", id="zeros"), + pytest.param(np.full((6, 2), NAN), "nan", id="all_nan"), + # NOTE: non-finite values are propagated by the weighted sum, with no checks + pytest.param( + np.array([[1.0, 2.0], [INF, 1.0], [3.0, 3.0], [1.0, NAN]]), "nan", id="inf_nan" + ), +] + + +class TestMarginalizeOverAncestors: + @pytest.mark.parametrize("num_tips", [2, 3, 10, 60, 200]) + @pytest.mark.parametrize("seed", range(2)) + def test_random(self, impl, seed, num_tips): + rng = np.random.default_rng(seed) + val = rng.uniform(0.1, 10.0, (num_tips, 2)) + result = compare( + impl.prior._marginalize_over_ancestors, + prior._marginalize_over_ancestors, + val, + ) + assert result.value.shape == (num_tips + 1, 2) + + @pytest.mark.parametrize("num_columns", [1, 3]) + def test_number_of_moments(self, impl, num_columns): + val = np.random.default_rng(0).uniform(0.1, 10.0, (12, num_columns)) + compare( + impl.prior._marginalize_over_ancestors, + prior._marginalize_over_ancestors, + val, + ) + + @pytest.mark.parametrize("num_tips", [3, 10, 100]) + def test_coalescent_moments(self, impl, num_tips): + compare( + impl.prior._marginalize_over_ancestors, + prior._marginalize_over_ancestors, + coalescent_moments(num_tips), + ) + + @pytest.mark.parametrize(("val", "expected_kind"), MARGINALIZE_EDGE_CASES) + def test_edge_cases(self, impl, val, expected_kind): + assert_outcome( + impl.prior._marginalize_over_ancestors, + prior._marginalize_over_ancestors, + (val,), + expected_kind, + ) + + def test_input_not_modified(self, impl): + # `compare` passes copies, so call directly + val = np.random.default_rng(0).uniform(0.1, 10.0, (8, 2)) + copy = val.copy() + impl.prior._marginalize_over_ancestors(val) + assert np.array_equal(val, copy) + + +class TestConditionalCoalescentVariance: + @pytest.mark.parametrize("num_tips", [2, 3, 5, 20, 100, 250]) + def test_variance(self, impl, num_tips): + result = compare( + impl.prior.conditional_coalescent_variance, + prior.conditional_coalescent_variance, + num_tips, + ) + assert result.value.shape == (num_tips + 1,) + + +class TestSingleTip: + def test_called_with_one_tip(self, monkeypatch): + # NOTE: current behaviour, possibly a bug: a tree with one + # attached sample (with `allow_unary`) calls + # `conditional_coalescent_variance(1)`, whose result is unused. That call is + # replaced here, because in numba it reads and writes out of bounds. + tables = tskit.TableCollection(1000.0) + for _ in range(3): + tables.nodes.add_row(flags=tskit.NODE_IS_SAMPLE, time=0) + tables.nodes.add_row(time=1.0) + tables.edges.add_row(0, 1000, 3, 0) + tables.edges.add_row(500, 1000, 3, 1) + tables.edges.add_row(500, 1000, 3, 2) + tables.sort() + ts = tables.tree_sequence() + called = [] + original = tsdate_prior.conditional_coalescent_variance + + def record(num_tips): + called.append(int(num_tips)) + if num_tips == 1: + return np.zeros(2) + return original(num_tips) + + monkeypatch.setattr(tsdate_prior, "conditional_coalescent_variance", record) + tsdate.build_prior_grid(ts, timepoints=5, population_size=1e4, allow_unary=True) + assert called == [3, 1] diff --git a/tests/test_oracle_rescaling.py b/tests/test_oracle_rescaling.py new file mode 100644 index 00000000..bf26a570 --- /dev/null +++ b/tests/test_oracle_rescaling.py @@ -0,0 +1,827 @@ +""" +Parity of the jitted functions in ``tsdate.rescaling`` with their oracles: random +inputs, inputs from ``ExpectationPropagation.rescale`` on simulated tree sequences, +degenerate inputs, and every ``assert``/``raise``. +""" + +import numpy as np +import pytest +from oracle import rescaling +from oracle.helpers import ( + INF, + NAN, + assert_outcome, + b1, + compare, + f64, + i32, + make_ts, + shrink, +) + +import tsdate.approx +from tsdate.variational import ExpectationPropagation + +BREAKS_MSG = "non-increasing time breakpoints" +KLFailed = tsdate.approx.KLMinimizationFailedError + + +@pytest.fixture(params=["small_ts_unphased", "small_ts_historical"]) +def sim_ts(request): + return request.getfixturevalue(request.param) + + +@pytest.fixture(scope="module") +def eps(small_ts, small_ts_historical): + """`ExpectationPropagation` after a few iterations, for each simulated ts""" + eps = {} + for name, ts in [ + ("small_ts", small_ts), + ("small_ts_historical", small_ts_historical), + ]: + ep = ExpectationPropagation(ts, mutation_rate=1e-8) + ep.iterate(max_shape=1000, min_step=0.1) + eps[name] = ep + return eps + + +@pytest.fixture(params=["small_ts", "small_ts_historical"]) +def ep(request, eps): + return eps[request.param] + + +def rescale_inputs(ep): + """Arguments of `mutational_timescale`, as in `ExpectationPropagation.rescale`""" + nodes_time, _ = ep.node_moments() + nodes_fixed = ep.node_constraints[:, 0] == ep.node_constraints[:, 1] + return ( + nodes_time, + ep.sizebiased_likelihoods, + nodes_fixed, + ep.edge_parents, + ep.edge_children, + ) + + +def count_args(ts, size_biased, node_is_sample=None): + if node_is_sample is None: + node_is_sample = np.full(ts.num_nodes, False) + node_is_sample[ts.samples()] = True + return [ + node_is_sample, + ts.mutations_node, + ts.sites_position[ts.mutations_site], + ts.edges_parent, + ts.edges_child, + ts.edges_left, + ts.edges_right, + ts.indexes_edge_insertion_order, + ts.indexes_edge_removal_order, + ts.sequence_length, + size_biased, + ] + + +def piecewise_rates(rng, size, num_pieces, offset_range, rate_range): + """Poisson counts and offsets for `size` observations, with piecewise constant rate""" + offset = rng.uniform(*offset_range, size) + rate = np.repeat(rng.uniform(*rate_range, num_pieces), size // num_pieces + 1)[:size] + counts = rng.poisson(rate * offset).astype(float) + return counts, offset + + +# counts, epochs, outcome category of the oracle +FIXED_CHANGEPOINT_CASES = [ + pytest.param([1.0, 2.0, 3.0], 1, "finite", id="one_epoch"), + pytest.param([5.0], 1, "finite", id="one_epoch_one_count"), + pytest.param([0.0, 0.0, 4.0, 0.0], 1, "finite", id="one_epoch_concentrated"), + pytest.param([1.0, 2.0, 3.0], 10, "finite", id="more_epochs_than_counts"), + pytest.param([0.0, 0.0, 4.0, 0.0], 4, "finite", id="concentrated_counts"), + pytest.param([0.0, 0.0, 5.0, 5.0], 3, "finite", id="zeros_at_start"), + pytest.param([5.0, 5.0, 0.0, 0.0], 3, "finite", id="zeros_at_end"), + pytest.param([0.0, 5.0, 0.0, 5.0, 0.0], 3, "finite", id="zeros_in_middle"), + pytest.param([1.0] * 4, 4, "finite", id="quantiles_exact"), + pytest.param([1.0] * 4, 2, "finite", id="quantiles_exact_half"), + pytest.param([1.0, 2.0], 0, AssertionError, id="zero_epochs"), + pytest.param([1.0, 2.0], -1, AssertionError, id="negative_epochs"), + # NOTE: current behaviour, possibly a bug: with no counts the + # cumulative distribution is 0 / 0 = NaN, which `searchsorted` places last, so + # every breakpoint but the last is -1 + pytest.param([0.0, 0.0, 0.0], 3, "finite", id="zero_total"), + pytest.param([], 3, "finite", id="empty"), +] + + +class TestFixedChangepoints: + @staticmethod + def compare(impl, counts, epochs): + return compare( + impl.rescaling._fixed_changepoints, + rescaling._fixed_changepoints, + np.asarray(counts, dtype=float), + epochs, + ) + + @pytest.mark.parametrize( + ("counts", "epochs", "expected_kind"), FIXED_CHANGEPOINT_CASES + ) + def test_edge_cases(self, impl, counts, epochs, expected_kind): + assert_outcome( + impl.rescaling._fixed_changepoints, + rescaling._fixed_changepoints, + (np.asarray(counts, dtype=float), epochs), + expected_kind, + ) + + @pytest.mark.parametrize("mode", ["typical", "zeros"]) + @pytest.mark.parametrize("seed", range(3)) + def test_random(self, impl, seed, mode): + rng = np.random.default_rng(seed) + size = int(rng.integers(3, 300)) + counts = rng.exponential(1.0, size) + epochs = int(rng.integers(1, 40)) + if mode == "zeros": + counts *= rng.random(size) < 0.6 + counts[0] += 1.0 + epochs = int(rng.integers(1, 120)) + result = self.compare(impl, counts, epochs) + # also the dtype, which `compare` ignores + actual = impl.rescaling._fixed_changepoints(counts, epochs) + assert actual.dtype == result.value.dtype == np.int32 + + +COUNTS = [5.0, 6.0, 20.0, 22.0, 21.0, 3.0] +ONES = [1.0] * 6 +# counts, offset, penalty, min_counts, min_offset, outcome category of the oracle +POISSON_CASES = [ + pytest.param(COUNTS, ONES, 0.0, 0.0, 0.0, "finite", id="no_penalty"), + pytest.param(COUNTS, ONES, 2.0, 0.0, 0.0, "finite", id="penalty"), + pytest.param(COUNTS, ONES, 1e6, 0.0, 0.0, "finite", id="huge_penalty"), + pytest.param(COUNTS, ONES, INF, 0.0, 0.0, "finite", id="infinite_penalty"), + # the exact counts of two observations are 21 and 22 + pytest.param(COUNTS, ONES, 2.0, 21.0, 0.0, "finite", id="min_counts_21"), + pytest.param(COUNTS, ONES, 2.0, 22.0, 0.0, "finite", id="min_counts_22"), + pytest.param(COUNTS, ONES, 2.0, 1000.0, 0.0, "finite", id="min_counts_unreachable"), + pytest.param(COUNTS, ONES, 0.0, 0.0, 1.5, "finite", id="min_offset_1.5"), + pytest.param(COUNTS, ONES, 0.0, 0.0, 6.0, "finite", id="min_offset_total"), + pytest.param(COUNTS, ONES, 0.0, 0.0, 6.5, "finite", id="min_offset_over_total"), + pytest.param(COUNTS, ONES, 2.0, 0.0, 100.0, "finite", id="min_offset_unreachable"), + pytest.param( + COUNTS, [1.0, 1.0, 0.0, 1.0, 1.0, 1.0], 2.0, 0.0, 0.0, "finite", id="zero_offset" + ), + pytest.param( + COUNTS, + [1.0, 1.0, 0.0, 1.0, 1.0, 1.0], + 2.0, + 0.0, + 0.5, + "finite", + id="zero_offset_min_offset", + ), + pytest.param([], [], 2.0, 0.0, 0.0, "finite", id="empty"), + pytest.param([4.0], [1.0], 2.0, 0.0, 0.0, "finite", id="single_observation"), + # log(0) is -inf and 0 * -inf is NaN, so the loss is NaN + pytest.param([0.0] * 3, [1.0] * 3, 0.0, 0.0, 0.0, "finite", id="zero_counts"), + pytest.param([0.0] * 3, [1.0] * 3, 2.0, 1.0, 0.0, "finite", id="zero_counts_min"), + pytest.param(COUNTS, ONES, -1.0, 0.0, 0.0, AssertionError, id="negative_penalty"), + pytest.param(COUNTS, ONES, NAN, 0.0, 0.0, AssertionError, id="nan_penalty"), + pytest.param(COUNTS, ONES, 2.0, -1.0, 0.0, AssertionError, id="negative_min_counts"), + pytest.param(COUNTS, ONES, 2.0, 0.0, -1.0, AssertionError, id="negative_min_offset"), + pytest.param(COUNTS, ONES[:3], 2.0, 0.0, 0.0, AssertionError, id="size_mismatch"), +] + + +class TestPoissonChangepoints: + @pytest.mark.parametrize( + ("counts", "offset", "penalty", "min_counts", "min_offset", "expected_kind"), + POISSON_CASES, + ) + def test_edge_cases( + self, impl, counts, offset, penalty, min_counts, min_offset, expected_kind + ): + args = (f64(*counts), f64(*offset), penalty, min_counts, min_offset) + assert_outcome( + impl.rescaling._poisson_changepoints, + rescaling._poisson_changepoints, + args, + expected_kind, + ) + + @pytest.mark.parametrize("mode", ["typical", "extreme"]) + @pytest.mark.parametrize("seed", range(3)) + def test_random(self, impl, seed, mode): + rng = np.random.default_rng(seed) + size = int(rng.integers(8, 45)) + if mode == "typical": + counts, offset = piecewise_rates(rng, size, 3, (0.5, 2.0), (0.5, 20.0)) + args = (counts, offset, float(rng.choice([0.0, 2.0, 10.0])), 1.0, 0.1) + else: + counts, offset = piecewise_rates(rng, size, 4, (0.2, 3.0), (0.2, 30.0)) + args = (counts, offset, float(rng.choice([1.0, 50.0])), 10.0, 0.5) + result = compare( + impl.rescaling._poisson_changepoints, + rescaling._poisson_changepoints, + *args, + ) + # also the dtype, which `compare` ignores + actual = impl.rescaling._poisson_changepoints(*args) + assert actual.dtype == result.value.dtype == np.int32 + + +COUNT_NODES = [(1, 0), (1, 0), (0, 1)] +COUNT_EDGES = [(0, 10, 2, 0), (0, 10, 2, 1)] +GAPPED = [(0, 4, 2, 0), (6, 10, 2, 0), (0, 10, 2, 1)] +BREAKPOINT = [(0, 5, 2, 0), (5, 10, 2, 0), (0, 10, 2, 1)] +SAMPLE_TREE_NODES = [(1, 0), (1, 0), (1, 0), (0, 1), (0, 2)] +SAMPLE_TREE_EDGES = [(0, 10, 3, 0), (0, 10, 3, 1), (0, 10, 4, 3), (0, 10, 4, 2)] + +# nodes, edges, mutations, length; run with and without size bias +COUNT_CASES = [ + # node 2 is the root, so a mutation on it has no edge; several per edge + pytest.param( + COUNT_NODES, + COUNT_EDGES, + [(1, 0), (2, 0), (3, 1), (5, 2)], + 10.0, + id="mutation_above_root", + ), + pytest.param(COUNT_NODES, COUNT_EDGES, [], 10.0, id="no_mutations"), + pytest.param(COUNT_NODES, [], [(1, 0)], 10.0, id="no_edges"), + pytest.param(COUNT_NODES, [], [], 10.0, id="no_edges_no_mutations"), + pytest.param( + [(1, 0), (0, 1)], [(0, 4, 1, 0)], [(1, 0), (5, 0)], 10.0, id="beyond_the_edge" + ), + pytest.param(COUNT_NODES, GAPPED, [(4, 0), (5, 0)], 10.0, id="in_gap"), + pytest.param(COUNT_NODES, BREAKPOINT, [(5, 0), (4.5, 0)], 10.0, id="at_breakpoint"), + pytest.param( + SAMPLE_TREE_NODES, + SAMPLE_TREE_EDGES, + [(1, 0), (2, 3), (3, 3)], + 10.0, + id="weighted_by_samples", + ), +] + + +class TestCountMutations: + @staticmethod + def compare(impl, args): + return compare(impl.rescaling._count_mutations, rescaling._count_mutations, *args) + + @pytest.mark.parametrize("size_biased", [False, True]) + @pytest.mark.parametrize(("nodes", "edges", "mutations", "length"), COUNT_CASES) + def test_edge_cases(self, impl, nodes, edges, mutations, length, size_biased): + ts = make_ts(nodes, edges, mutations, length) + self.compare(impl, count_args(ts, size_biased)) + + def test_mutation_edges(self, impl): + # a mutation at a breakpoint belongs to the tree to its right; none above + # the root; the edge id of a mutation is NULL if no edge covers it + mutations = [(1, 0), (2, 0), (3, 1), (5, 2)] + ts = make_ts(COUNT_NODES, COUNT_EDGES, mutations, 10.0) + _, mutation_edge = self.compare(impl, count_args(ts, False)).value + assert mutation_edge.tolist() == [0, 0, 1, -1] + + @pytest.mark.parametrize("size_biased", [False, True]) + def test_no_samples_flagged(self, impl, size_biased): + ts = make_ts(COUNT_NODES, COUNT_EDGES, [(1, 0)], 10.0) + none = np.full(ts.num_nodes, False) + self.compare(impl, count_args(ts, size_biased, node_is_sample=none)) + + def test_unsorted_mutations(self, impl): + mutations = [(1, 0), (2, 1), (6, 0), (8, 1), (9, 2)] + ts = make_ts(COUNT_NODES, BREAKPOINT, mutations, 10.0) + args = count_args(ts, False) + order = np.array([3, 0, 4, 1, 2]) + args[1], args[2] = args[1][order], args[2][order] + self.compare(impl, args) + + @pytest.mark.parametrize(("index", "size"), [(4, 1), (7, 1), (2, 1)]) + def test_size_mismatch(self, impl, index, size): + ts = make_ts(COUNT_NODES, COUNT_EDGES, [(1, 0), (2, 1)], 10.0) + args = shrink(count_args(ts, False), index, size) + result = self.compare(impl, args) + assert result.error is AssertionError + + @pytest.mark.parametrize("size_biased", [False, True]) + def test_simulated(self, impl, sim_ts, size_biased): + args = count_args(sim_ts, size_biased) + result = self.compare(impl, args) + # also the dtype, which `compare` ignores + actual = impl.rescaling._count_mutations(*args) + assert actual[1].dtype == result.value[1].dtype == np.int32 + + +def area_args(nodes_time, likelihoods, parents, children): + likelihoods = np.array(likelihoods, dtype=float) + if likelihoods.size == 0: + likelihoods = likelihoods.reshape(0, 2) + return ( + f64(*nodes_time), + likelihoods, + i32(*parents), + i32(*children), + ) + + +LIK = [[2, 10], [1, 10]] +# nodes_time, likelihoods, parents, children, exception of the oracle +AREA_CASES = [ + pytest.param([0, 0, 1], LIK, [2, 2], [0, 1], None, id="single_epoch"), + # all nodes at time zero: no epoch, and every edge has zero length + pytest.param([0, 0, 0], LIK, [2, 2], [0, 1], None, id="no_epochs"), + pytest.param([0, 1], [], [], [], None, id="no_edges"), + pytest.param([0.0], [], [], [], None, id="single_node"), + pytest.param([], [], [], [], None, id="no_nodes"), + pytest.param( + [0, 0, 1, 1, 3], + [[2, 10], [1, 10], [4, 5]], + [2, 2, 4], + [0, 1, 3], + None, + id="zero_length_edge", + ), + # an edge whose parent is younger than its child is skipped entirely + pytest.param([0, 1, 0.5], LIK, [1, 2], [0, 1], None, id="negative_length_edge"), + pytest.param([0, 0, 1, 3], [[6, 12], [3, 12]], [3, 2], [0, 1], None, id="two_epochs"), + # NOTE: current behaviour, possibly a bug: the first epoch always + # starts at zero, even if the youngest node is older + pytest.param([1, 2], [[2, 10]], [1], [0], None, id="no_node_at_time_zero"), + pytest.param( + [3, 0, 1, 0, 1, 5], + [[2, 10], [1, 10], [3, 10], [2, 10]], + [4, 2, 5, 2], + [1, 3, 0, 1], + None, + id="ties_and_unsorted_times", + ), + pytest.param([0, 0, 1], LIK, [2], [0, 1], AssertionError, id="parents_mismatch"), + pytest.param( + [0, 0, 1], [[1, 1]] * 3, [2, 2], [0, 1], AssertionError, id="likelihood_rows" + ), + pytest.param( + [0, 0, 1], + [[1, 1, 1]] * 2, + [2, 2], + [0, 1], + AssertionError, + id="likelihood_columns", + ), +] + + +class TestMutationalArea: + @staticmethod + def compare(impl, *args): + return compare(impl.rescaling.mutational_area, rescaling.mutational_area, *args) + + @pytest.mark.parametrize( + ("nodes_time", "likelihoods", "parents", "children", "expected_error"), AREA_CASES + ) + def test_edge_cases( + self, impl, nodes_time, likelihoods, parents, children, expected_error + ): + args = area_args(nodes_time, likelihoods, parents, children) + result = self.compare(impl, *args) + assert result.error is expected_error + + @pytest.mark.parametrize("seed", range(2)) + def test_random(self, impl, sim_ts, seed): + ts = sim_ts + rng = np.random.default_rng(seed) + times = ts.nodes_time * rng.uniform(0.8, 1.2, ts.num_nodes) + times[ts.samples()] = ts.nodes_time[ts.samples()] + likelihoods = rng.uniform(0, 5, (ts.num_edges, 2)) + args = (times, likelihoods, ts.edges_parent, ts.edges_child) + result = self.compare(impl, *args) + # also the dtype, which `compare` ignores + actual = impl.rescaling.mutational_area(*args) + assert actual[3].dtype == result.value[3].dtype == np.int32 + + def test_simulated(self, impl, ep): + nodes_time, likelihoods, _, parents, children = rescale_inputs(ep) + self.compare(impl, nodes_time, likelihoods, parents, children) + + +def timescale_args(nodes_time, likelihoods, nodes_fixed, parents, children, k): + return ( + f64(*nodes_time), + np.array(likelihoods, dtype=float).reshape(-1, 2), + b1(*nodes_fixed), + i32(*parents), + i32(*children), + k, + ) + + +# nodes 0, 1 are samples at time 0, 2 and 3 are internal +CHAIN = ( + [0, 0, 1.0, 2.0], + [[2, 10], [1, 10], [3, 10]], + [1, 1, 0, 0], + [2, 2, 3], + [0, 1, 2], +) +# sample 1 is historical +HISTORICAL = ([0, 500, 100, 700], [[2, 10], [1, 10], [3, 10]]) +HISTORICAL_EDGES = ([2, 3, 3], [0, 2, 1]) + + +def chain(k, fixed=None): + times, lik, nodes_fixed, parents, children = CHAIN + return timescale_args(times, lik, fixed or nodes_fixed, parents, children, k) + + +def historical(k, fixed): + times, lik = HISTORICAL + parents, children = HISTORICAL_EDGES + return timescale_args(times, lik, fixed, parents, children, k) + + +# arguments, outcome category (or exception) of the oracle +TIMESCALE_CASES = [ + pytest.param(chain(1), "finite", id="one_interval"), + pytest.param(chain(2), "finite", id="two_intervals"), + pytest.param(chain(3), "finite", id="as_many_as_epochs"), + pytest.param(chain(10000), "finite", id="more_than_epochs"), + pytest.param(chain(0), AssertionError, id="zero_intervals"), + pytest.param(chain(-1), AssertionError, id="negative_intervals"), + # NOTE: current behaviour, possibly a bug: `nodes_fixed` is only + # size-checked, so which nodes are fixed does not matter + pytest.param(chain(3, [0, 0, 0, 0]), "finite", id="no_fixed_nodes"), + pytest.param(chain(3, [1, 1, 1, 1]), "finite", id="all_fixed_nodes"), + pytest.param(historical(1, [1, 0, 0, 0]), "finite", id="contemporary_one"), + pytest.param(historical(3, [1, 1, 0, 0]), "finite", id="historical_three"), + pytest.param(historical(100, [1, 1, 0, 0]), "finite", id="historical_many"), + # the top edge has no span, so the last epoch has no weight and is merged + pytest.param( + timescale_args( + [0, 0, 1.0, 2.0], + [[2, 10], [1, 10], [3, 0]], + [1, 1, 0, 0], + [2, 2, 3], + [0, 1, 2], + 1, + ), + "finite", + id="zero_span_top_edge", + ), + # edge 2 -> 3 is negative (3 is older than 2): skipped from the totals + pytest.param( + timescale_args( + [0, 0, 2.0, 1.0], + [[2, 10], [1, 10], [5, 10]], + [1, 1, 0, 0], + [2, 2, 3], + [0, 1, 2], + 2, + ), + "finite", + id="negative_length_edge", + ), + # NOTE: current behaviour, possibly a bug: every edge over an + # interval has zero span (a zero mutation rate) or there are no edges + pytest.param( + timescale_args([0, 0, 1.0], [[2, 0], [1, 0]], [1, 1, 0], [2, 2], [0, 1], 1), + AssertionError, + id="zero_edge_span", + ), + pytest.param( + timescale_args([0.0, 1.0], [], [1, 1], [], [], 1), AssertionError, id="no_edges" + ), + pytest.param( + timescale_args([0.0, 0.0, 0.0], [[1, 10], [1, 10]], [1, 1, 1], [2, 2], [0, 1], 1), + AssertionError, + id="all_nodes_at_time_zero", + ), +] + + +class TestMutationalTimescale: + @staticmethod + def compare(impl, *args): + return compare( + impl.rescaling.mutational_timescale, rescaling.mutational_timescale, *args + ) + + @pytest.mark.parametrize(("args", "expected"), TIMESCALE_CASES) + def test_edge_cases(self, impl, args, expected): + assert_outcome( + impl.rescaling.mutational_timescale, + rescaling.mutational_timescale, + args, + expected, + ) + + def test_zero_edge_span_message(self, impl): + # the message is compared as well as the type + args = timescale_args([0, 0, 1.0], [[2, 0], [1, 0]], [1, 1, 0], [2, 2], [0, 1], 1) + result = self.compare(impl, *args) + assert "Zero edge span in interval" in str(result.exception) + + @pytest.mark.parametrize("which", ["fixed", "parents", "likelihood_rows", "columns"]) + def test_size_mismatch(self, impl, which): + args = list(chain(2)) + if which == "fixed": + args[2] = b1(1, 1) + elif which == "parents": + args[3] = i32(2, 2) + elif which == "likelihood_rows": + args[1] = np.ones((2, 2)) + else: + args[1] = np.ones((3, 3)) + result = self.compare(impl, *args) + assert result.error is AssertionError + + @pytest.mark.parametrize("max_intervals", [3, 1000]) + @pytest.mark.parametrize("seed", range(2)) + def test_random(self, impl, sim_ts, seed, max_intervals): + ts = sim_ts + rng = np.random.default_rng(seed) + times = ts.nodes_time * rng.uniform(0.9, 1.1, ts.num_nodes) + times[ts.samples()] = ts.nodes_time[ts.samples()] + likelihoods = np.column_stack( + ( + rng.poisson(2.0, ts.num_edges).astype(float), + rng.uniform(1, 5, ts.num_edges), + ) + ) + fixed = np.full(ts.num_nodes, False) + fixed[ts.samples()] = True + args = (times, likelihoods, fixed, ts.edges_parent, ts.edges_child, max_intervals) + self.compare(impl, *args) + + @pytest.mark.parametrize("max_intervals", [1, 10, 1000]) + def test_simulated(self, impl, ep, max_intervals): + self.compare(impl, *rescale_inputs(ep), max_intervals) + + +ORIGINAL = [0.0, 1.0, 3.0] +RESCALED = [0.0, 2.0, 3.5] +# estimate, fixed, original, rescaled, outcome category of the oracle +POINT_ESTIMATE_CASES = [ + pytest.param( + [0.0, 0.5, 1.0, 2.0, 3.0], None, ORIGINAL, RESCALED, "finite", id="inside" + ), + # the last scaling is zero, so everything beyond collapses to the last point + pytest.param( + [3.0, 4.0, 10.0, 1e300], None, ORIGINAL, RESCALED, "finite", id="beyond" + ), + pytest.param([INF], None, ORIGINAL, RESCALED, "nan", id="infinite"), + # NOTE: current behaviour, possibly a bug: a time below the first + # break has search index -1, which wraps to the last breakpoint; -inf gives NaN + pytest.param( + [-1.0, -1e-9, 0.0], None, ORIGINAL, RESCALED, "finite", id="below_first" + ), + pytest.param([-INF], None, ORIGINAL, RESCALED, "nan", id="minus_infinity"), + pytest.param([NAN], None, ORIGINAL, RESCALED, "nan", id="nan"), + pytest.param( + [0.0, 0.5, 3.0, 4.0], [1, 0, 1, 1], ORIGINAL, RESCALED, "finite", id="some_fixed" + ), + pytest.param([NAN, 1.0], [1, 0], ORIGINAL, RESCALED, "nan", id="fixed_nan"), + pytest.param([], None, ORIGINAL, RESCALED, "finite", id="empty"), + pytest.param([0.0, 0.5, 7.0], None, [0.0], [0.0], "finite", id="single_breakpoint"), + pytest.param([0.0, 0.5, 7.0], None, [0.0], [2.0], "finite", id="single_scaled"), + pytest.param([0.0, 0.3, 1.0], None, [0.0, 5.0], [0.0, 5.0], "finite", id="identity"), + pytest.param( + [0.5], None, [0.0, 1.0, 3.0], [0.0, 2.0, 2.0], ValueError, id="flat_rescaled" + ), + pytest.param( + [0.5], None, [0.0, 1.0, 3.0], [0.0, 2.0, 1.0], ValueError, id="decreasing" + ), + pytest.param( + [0.5], None, [0.0, 1.0, 1.0], [0.0, 2.0, 3.0], ValueError, id="flat_original" + ), + pytest.param( + [0.5], None, [0.0, 2.0, 1.0], [0.0, 1.0, 2.0], ValueError, id="decr_original" + ), + pytest.param( + [0.5], None, [0.0, 1.0, NAN], [0.0, 1.0, 2.0], ValueError, id="nan_original" + ), + pytest.param( + [0.5], None, [0.0, 1.0, 2.0], [0.0, 1.0, NAN], ValueError, id="nan_rescaled" + ), +] + + +class TestPiecewiseScalePointEstimate: + @pytest.mark.parametrize( + ("estimate", "fixed", "original", "rescaled", "expected_kind"), + POINT_ESTIMATE_CASES, + ) + def test_edge_cases(self, impl, estimate, fixed, original, rescaled, expected_kind): + estimate = f64(*estimate) + fixed = np.full(estimate.size, False) if fixed is None else b1(*fixed) + args = (estimate, fixed, f64(*original), f64(*rescaled)) + assert_outcome( + impl.rescaling.piecewise_scale_point_estimate, + rescaling.piecewise_scale_point_estimate, + args, + expected_kind, + ) + + def test_breaks_message(self, impl): + # the message names the offending option, and is compared as well as the type + args = (f64(0.5), b1(0), f64(0.0, 1.0, 1.0), f64(0.0, 2.0, 3.0)) + result = compare( + impl.rescaling.piecewise_scale_point_estimate, + rescaling.piecewise_scale_point_estimate, + *args, + ) + assert BREAKS_MSG in str(result.exception) + + @pytest.mark.parametrize("seed", range(3)) + def test_random(self, impl, seed): + rng = np.random.default_rng(seed) + k = int(rng.integers(2, 12)) + original = np.concatenate(([0.0], np.cumsum(rng.uniform(0.1, 5.0, k)))) + rescaled = np.concatenate(([0.0], np.cumsum(rng.uniform(0.1, 5.0, k)))) + estimate = rng.uniform(0, original[-1] * 1.2, 40) + fixed = rng.random(40) < 0.2 + compare( + impl.rescaling.piecewise_scale_point_estimate, + rescaling.piecewise_scale_point_estimate, + estimate, + fixed, + original, + rescaled, + ) + + def test_simulated(self, impl, ep): + nodes_time, likelihoods, nodes_fixed, parents, children = rescale_inputs(ep) + original, rescaled = rescaling.mutational_timescale( + nodes_time, likelihoods, nodes_fixed, parents, children, 10 + ) + compare( + impl.rescaling.piecewise_scale_point_estimate, + rescaling.piecewise_scale_point_estimate, + nodes_time, + nodes_fixed, + original, + rescaled, + ) + + +POSTERIORS = [[1.0, 1.0], [2.0, 3.0], [0.0, 1.0], [5.0, 2.0]] + + +# posteriors, keyword arguments of `posterior_args`, outcome category (or exception) +# of the oracle +POSTERIOR_CASES = [ + pytest.param(POSTERIORS, {}, "finite", id="default"), + pytest.param(POSTERIORS, {"quantile_width": 1e-3}, "finite", id="narrow_quantile"), + pytest.param(POSTERIORS, {"quantile_width": 0.999}, "finite", id="wide_quantile"), + pytest.param( + POSTERIORS, {"quantile_width": 1 - 1e-9}, "finite", id="widest_quantile" + ), + *[ + pytest.param(POSTERIORS, {"quantile_width": w}, AssertionError, id=f"width_{w}") + for w in [0.0, 1.0, -0.1, 1.5, NAN, INF] + ], + pytest.param(POSTERIORS, {"fixed": [1, 0, 1, 0]}, "nan", id="some_fixed"), + pytest.param(POSTERIORS, {"fixed": [1] * 4}, "nan", id="all_fixed"), + # fixed rows are not validated + pytest.param( + [[-5.0, -5.0], [1.0, 1.0]], {"fixed": [1, 0]}, "nan", id="fixed_negative" + ), + pytest.param([[NAN, NAN], [1.0, 1.0]], {"fixed": [1, 0]}, "nan", id="fixed_nan"), + # NOTE: current behaviour, possibly a bug: no posteriors raises + # numpy's "zero-size array" ValueError from a debug assertion + pytest.param(np.zeros((0, 2)), {"fixed": []}, ValueError, id="no_posteriors"), + *[ + pytest.param([row], {}, "finite", id=f"valid_{i}") + for i, row in enumerate( + [[-0.99, 1.0], [0.0, 1.0], [1.0, 1e-300], [1.0, 1e300], [1e6, 1e6]] + ) + ], + # NOTE: current behaviour, possibly a bug: for a shape this close + # to -1 the lower quantile underflows to zero and numba raises ZeroDivisionError + # (IEEE would give inf), rather than KLMinimizationFailedError + *[ + pytest.param([row], {}, ZeroDivisionError, id=f"shape_near_minus_one_{i}") + for i, row in enumerate([[-0.9999, 1.0], [-1 + 1e-12, 1.0], [-0.9999999, 2.0]]) + ], + pytest.param([[1.0, INF]], {}, ZeroDivisionError, id="infinite_rate"), + # NOTE: current behaviour, possibly a bug: the error leaks out of + # `approximate_gamma_iqr` + pytest.param([[INF, 1.0]], {}, KLFailed, id="infinite_shape"), + *[ + pytest.param([row], {}, AssertionError, id=f"invalid_{i}") + for i, row in enumerate( + [[-1.0, 1.0], [1.0, 0.0], [1.0, -1.0], [NAN, 1.0], [1.0, NAN], [-INF, 1.0]] + ) + ], + pytest.param( + [[1.0, 1.0], [2.0, 3.0], [0.0, 1.0], [-1.0, 2.0]], + {}, + AssertionError, + id="one_invalid", + ), + # all quantiles map to one point beyond the last break: zero interquantile range + pytest.param([[1.0, 0.001], [1.0, 1e-9]], {}, "finite", id="beyond_last_break"), + pytest.param( + POSTERIORS, {"original": [0.5, 1.0, 3.0]}, AssertionError, id="below_first" + ), + # NOTE: current behaviour, possibly a bug: `max_shape=0` gives + # shape -1 (improper) and zero rate + pytest.param(POSTERIORS, {"max_shape": 0.0}, "finite", id="max_shape_0"), + pytest.param(POSTERIORS, {"max_shape": 1.0}, "finite", id="max_shape_1"), + pytest.param(POSTERIORS, {"max_shape": 10.0}, "finite", id="max_shape_10"), + pytest.param(POSTERIORS, {"max_shape": 1e8}, "finite", id="max_shape_1e8"), + pytest.param(POSTERIORS, {"max_shape": INF}, "finite", id="max_shape_inf"), + pytest.param(POSTERIORS, {"max_shape": NAN}, "finite", id="max_shape_nan"), + *[ + pytest.param(POSTERIORS, {"original": o, "rescaled": r}, ValueError, id=i) + for i, o, r in [ + ("original_flat", [0.0, 1.0, 1.0], RESCALED), + ("rescaled_flat", ORIGINAL, [0.0, 2.0, 2.0]), + ("rescaled_decreasing", ORIGINAL, [0.0, 2.0, 1.0]), + ("rescaled_nan", ORIGINAL, [0.0, 2.0, NAN]), + ] + ], + # the breaks are checked before the posteriors + pytest.param( + [[-5.0, 1.0]], + {"original": [0.0, 0.0], "rescaled": [0.0, 1.0]}, + ValueError, + id="bad_breaks_before_posteriors", + ), + # a single (zero-length) interval: everything is beyond the last break + pytest.param( + POSTERIORS, + {"original": [0.0], "rescaled": [0.0]}, + ZeroDivisionError, + id="single_break_zero", + ), + pytest.param( + POSTERIORS, {"original": [0.0], "rescaled": [4.0]}, "finite", id="single_break" + ), + pytest.param(POSTERIORS, {"fixed": [0] * 3}, AssertionError, id="fixed_mismatch"), + pytest.param( + POSTERIORS, + {"original": [0.0, 1.0], "rescaled": RESCALED}, + AssertionError, + id="breaks_mismatch", + ), +] + + +def posterior_args( + posteriors, + fixed=None, + original=None, + rescaled=None, + quantile_width=0.5, + max_shape=1000.0, +): + posteriors = np.asarray(posteriors, dtype=float).reshape(-1, 2) + fixed = np.full(posteriors.shape[0], False) if fixed is None else b1(*fixed) + original = f64(*(ORIGINAL if original is None else original)) + rescaled = f64(*(RESCALED if rescaled is None else rescaled)) + return (posteriors, fixed, original, rescaled, quantile_width, max_shape) + + +class TestPiecewiseScalePosterior: + @pytest.mark.parametrize(("posteriors", "kwargs", "expected"), POSTERIOR_CASES) + def test_edge_cases(self, impl, posteriors, kwargs, expected): + args = posterior_args(posteriors, **kwargs) + assert_outcome( + impl.rescaling.piecewise_scale_posterior, + rescaling.piecewise_scale_posterior, + args, + expected, + ) + + @pytest.mark.parametrize("seed", range(3)) + def test_random(self, impl, seed): + rng = np.random.default_rng(seed) + k = int(rng.integers(2, 10)) + original = np.concatenate(([0.0], np.cumsum(rng.uniform(0.1, 5.0, k)))) + rescaled = np.concatenate(([0.0], np.cumsum(rng.uniform(0.1, 5.0, k)))) + alpha = rng.uniform(-0.8, 60.0, 15) + beta = np.exp(rng.uniform(-2, 4, 15)) * (alpha + 1) / (original[-1] * 0.8) + args = ( + np.column_stack((alpha, beta)), + rng.random(15) < 0.2, + original, + rescaled, + float(rng.uniform(0.2, 0.9)), + float(rng.choice([2.0, 100.0, 1000.0])), + ) + compare( + impl.rescaling.piecewise_scale_posterior, + rescaling.piecewise_scale_posterior, + *args, + ) + + def test_simulated(self, impl, ep): + nodes_time, likelihoods, nodes_fixed, parents, children = rescale_inputs(ep) + original, rescaled = rescaling.mutational_timescale( + nodes_time, likelihoods, nodes_fixed, parents, children, 10 + ) + args = (ep.node_posterior, nodes_fixed, original, rescaled, 0.8, 1000.0) + compare( + impl.rescaling.piecewise_scale_posterior, + rescaling.piecewise_scale_posterior, + *args, + ) diff --git a/tests/test_oracle_util.py b/tests/test_oracle_util.py new file mode 100644 index 00000000..5ebab8d7 --- /dev/null +++ b/tests/test_oracle_util.py @@ -0,0 +1,400 @@ +""" +Parity of the jitted functions in ``tsdate.util`` with their oracles: simulated tree +sequences, degenerate inputs, and every ``assert``. +""" + +import numpy as np +import pytest +import tskit +from oracle import util +from oracle.helpers import NAN, assert_outcome, b1, compare, f64, i32, make_ts, shrink + + +@pytest.fixture(params=["small_ts", "small_ts_historical"]) +def sim_ts(request): + return request.getfixturevalue(request.param) + + +def sample_flags(ts): + return np.bitwise_and(ts.nodes_flags, tskit.NODE_IS_SAMPLE).astype(bool) + + +# parent, child, left, right, excluded, split nodes (new nodes are numbered from the +# number of nodes, and each is a copy of an old node: `split_nodes` lists the old ids) +SPLIT_CASES = [ + pytest.param([2, 2], [0, 1], [0, 0], [10, 10], [1, 1, 0], [], id="no_disjoint"), + pytest.param([], [], [], [], [1, 0], [], id="no_edges"), + pytest.param([], [], [], [], [], [], id="no_nodes"), + pytest.param( + [2, 2, 2], [0, 1, 1], [0, 2, 6], [2, 4, 8], [1, 1, 0], [2], id="one_split" + ), + pytest.param( + [2, 2, 2], [0, 0, 1], [0, 6, 0], [4, 10, 10], [1, 1, 0], [], id="excluded" + ), + pytest.param( + [3, 3, 3], [0, 0, 0], [0, 3, 6], [1, 4, 7], [1, 1, 1, 1], [], id="all_excluded" + ), + pytest.param( + [3, 3, 3], + [0, 0, 0], + [0, 3, 6], + [1, 4, 7], + [0, 0, 0, 0], + [0, 0, 3, 3], + id="many_splits", + ), + pytest.param( + [3, 3, 3, 3, 4], + [0, 0, 0, 1, 3], + [0, 3, 6, 0, 0], + [1, 4, 7, 10, 10], + [1, 1, 1, 0, 0], + [], + id="contiguous_over_another_child", + ), + pytest.param([3, 3], [0, 0], [0, 1], [1, 2], [0] * 4, [], id="touching"), + pytest.param([3, 3], [0, 0], [0, 0], [2, 5], [0] * 4, [], id="overlapping"), + pytest.param([3, 3], [0, 0], [0, 1.0000001], [1, 2], [0] * 4, [0, 3], id="tiny_gap"), + pytest.param( + [2, 2, 2], [1, 1, 0], [6, 2, 0], [8, 4, 2], [1, 1, 0], [2], id="unsorted" + ), + pytest.param([2], [0], [0], [1], [1, 0, 0], [], id="first_edge_at_zero"), +] + + +class TestSplitDisjointNodes: + @staticmethod + def compare(impl, *args): + return compare(impl.util._split_disjoint_nodes, util._split_disjoint_nodes, *args) + + @pytest.mark.parametrize( + ("parent", "child", "left", "right", "excluded", "expected"), SPLIT_CASES + ) + def test_edge_cases(self, impl, parent, child, left, right, excluded, expected): + args = (i32(*parent), i32(*child), f64(*left), f64(*right), b1(*excluded)) + _, _, _, split_nodes = self.compare(impl, *args).value + assert split_nodes.tolist() == expected + + @pytest.mark.parametrize(("index", "size"), [(1, 1), (2, 1), (3, 1)]) + def test_size_mismatch(self, impl, index, size): + args = [i32(2, 2), i32(0, 1), f64(0, 0), f64(10, 10), b1(1, 1, 0)] + result = self.compare(impl, *shrink(args, index, size)) + assert result.error is AssertionError + + def test_simulated(self, impl, sim_ts): + ts = sim_ts + args = ( + ts.edges_parent, + ts.edges_child, + ts.edges_left, + ts.edges_right, + sample_flags(ts), + ) + result = self.compare(impl, *args) + # also the dtypes, which `compare` ignores + actual = impl.util._split_disjoint_nodes(*args) + assert all(a.dtype == e.dtype == np.int32 for a, e in zip(actual, result.value)) + + +def relabel_args(ts): + """Arguments of `_relabel_mutations_node`, with the nodes split as by `util`""" + parent, child, order, _ = util._split_disjoint_nodes( + ts.edges_parent, + ts.edges_child, + ts.edges_left, + ts.edges_right, + sample_flags(ts), + ) + return [ + ts.mutations_node, + ts.sites_position[ts.mutations_site], + order, + parent, + child, + ts.edges_left, + ts.edges_right, + ts.indexes_edge_insertion_order, + ts.indexes_edge_removal_order, + ] + + +# nodes 0, 1 are samples, 2 and 3 are internal and have a gap at [4, 6) +GAP_NODES = [(1, 0), (1, 0), (0, 1), (0, 2)] +GAP_EDGES = [(0, 4, 2, 0), (0, 4, 2, 1), (6, 10, 2, 0), (6, 10, 2, 1)] +GAP_EDGES += [(0, 4, 3, 2), (6, 10, 3, 2)] +BINARY_EDGES = [(0, 10, 2, 0), (0, 10, 2, 1)] + +# nodes, edges, mutations, sequence length, exception of the oracle +RELABEL_CASES = [ + pytest.param(GAP_NODES, GAP_EDGES, [], 10.0, None, id="no_mutations"), + pytest.param( + GAP_NODES[:3], + BINARY_EDGES, + [(1, 0), (2, 2), (3, 1)], + 10.0, + None, + id="no_splits", + ), + # the sweep stops at the largest edge right coordinate: later mutations are NULL + pytest.param( + GAP_NODES, GAP_EDGES, [(1, 2), (10.0, 2)], 20.0, None, id="beyond_last_edge" + ), + pytest.param( + GAP_NODES, BINARY_EDGES, [(1, 3)], 10.0, AssertionError, id="node_not_in_tree" + ), +] + + +class TestRelabelMutationsNode: + @staticmethod + def compare(impl, args): + return compare( + impl.util._relabel_mutations_node, util._relabel_mutations_node, *args + ) + + @pytest.mark.parametrize( + ("nodes", "edges", "mutations", "length", "expected_error"), RELABEL_CASES + ) + def test_edge_cases(self, impl, nodes, edges, mutations, length, expected_error): + ts = make_ts(nodes, edges, mutations, length) + result = self.compare(impl, relabel_args(ts)) + assert result.error is expected_error + + def test_mutations_on_split_nodes(self, impl): + mutations = [(0.5, 0), (1, 2), (2, 3), (5, 0), (7, 2), (8, 3)] + ts = make_ts(GAP_NODES, GAP_EDGES, mutations, 10.0) + result = self.compare(impl, relabel_args(ts)) + # right-hand pieces of nodes 2 and 3 are the new nodes 4 and 5; the mutation + # at 5 is in the gap, on the (unsplit) sample 0 + assert result.value.tolist() == [0, 2, 3, 0, 4, 5] + + @pytest.mark.parametrize(("index", "size"), [(4, 2), (7, 2), (1, 1)]) + def test_size_mismatch(self, impl, index, size): + ts = make_ts(GAP_NODES, GAP_EDGES, [(1, 2), (7, 2)], 10.0) + result = self.compare(impl, shrink(relabel_args(ts), index, size)) + assert result.error is AssertionError + + def test_simulated(self, impl, sim_ts): + args = relabel_args(sim_ts) + result = self.compare(impl, args) + # also the dtype, which `compare` ignores + actual = impl.util._relabel_mutations_node(*args) + assert actual.dtype == result.value.dtype == np.int32 + + +# times, fixed, parents, children, epsilon, max_iterations, outcome category +# node 2 (age 1) is above samples 0, 1; node 3 (age 0.5) is above node 2: violated +VIOLATED = ([0, 0, 1.0, 0.5], [1, 1, 0, 0], [2, 3], [0, 2]) +CONSISTENT = ([0, 0, 1.0], [1, 1, 0], [2, 2], [0, 1]) +# one edge with parent age 0 and child age 1 (a violation); node 0 is the parent +INVERTED = ([0.0, 1.0], [0, 0], [0], [1]) +CONSTRAIN_EDGE_CASES = [ + pytest.param(*CONSISTENT, 1e-6, 0, "finite", id="consistent_forced"), + pytest.param(*CONSISTENT, 1e-6, 10, "finite", id="consistent_iterated"), + pytest.param(*CONSISTENT, 1.0, 0, "finite", id="branch_length_equals_epsilon"), + pytest.param(*CONSISTENT, 1.0, 10, "finite", id="branch_length_equals_epsilon_it"), + pytest.param([0, 1.0], [1, 0], [1], [0], 2.0, 0, "finite", id="shorter_than_epsilon"), + pytest.param(*VIOLATED, 1e-6, -1, "finite", id="negative_iterations"), + pytest.param(*INVERTED, 0.1, 100, "finite", id="free_nodes_meet"), + pytest.param([0.0, 1.0], [1, 0], [0], [1], 0.1, 100, "finite", id="fixed_parent"), + pytest.param([0.0, 1.0], [0, 1], [0], [1], 0.1, 100, "finite", id="fixed_child"), + # NOTE: current behaviour, possibly a bug: two fixed nodes on a + # violated edge fail an assertion (reachable via `constrain_ages` with + # inconsistent ancient sample ages); with no iterations the forcing step + # silently changes the age of a fixed node + pytest.param([0.0, 1.0], [1, 1], [0], [1], 0.1, 100, AssertionError, id="both_fixed"), + pytest.param([0.0, 1.0], [1, 1], [0], [1], 0.1, 0, "finite", id="both_fixed_forced"), + pytest.param([0.0, 1.0], [1, 0], [], [], 0.1, 10, "finite", id="no_edges"), + pytest.param([], [], [], [], 0.1, 10, "finite", id="no_nodes"), + # NaN comparisons are all false: no branch is a violation, and NaN is carried + pytest.param([0.0, NAN], [1, 0], [1], [0], 0.1, 3, "nan", id="nan_child"), + pytest.param([NAN, 1.0], [1, 0], [1], [0], 0.1, 3, "nan", id="nan_parent"), + pytest.param([0.0, 1.0], [1, 0], [1], [0], -0.5, 3, "finite", id="negative_epsilon"), + pytest.param( + [0.0, 0.0], [1, 0], [1], [0], 0.0, 3, "finite", id="equal_ages_zero_eps" + ), + pytest.param( + [1.0] * 5, + [1, 0, 0, 0, 0], + [1, 2, 3, 4], + [0, 1, 2, 3], + 1e-3, + 1000, + "finite", + id="slow_convergence_chain", + ), +] + + +class TestConstrainAges: + @staticmethod + def args(times, fixed, parents, children, epsilon, max_iterations): + return ( + f64(*times), + b1(*fixed), + i32(*parents), + i32(*children), + epsilon, + max_iterations, + ) + + @staticmethod + def compare(impl, args): + return compare(impl.util._constrain_ages, util._constrain_ages, *args) + + @pytest.mark.parametrize("max_iterations", [0, 1, 1000]) + @pytest.mark.parametrize("epsilon", [0.0, 1e-6, 0.5]) + def test_violation(self, impl, epsilon, max_iterations): + self.compare(impl, self.args(*VIOLATED, epsilon, max_iterations)) + + @pytest.mark.parametrize( + ("times", "fixed", "parents", "children", "epsilon", "max_iterations", "kind"), + CONSTRAIN_EDGE_CASES, + ) + def test_edge_cases( + self, impl, times, fixed, parents, children, epsilon, max_iterations, kind + ): + args = self.args(times, fixed, parents, children, epsilon, max_iterations) + assert_outcome(impl.util._constrain_ages, util._constrain_ages, args, kind) + + @pytest.mark.parametrize( + "args", + [ + pytest.param(([0, 1], [1], [1], [0]), id="fixed"), + pytest.param(([0, 1], [1, 0], [1], [0, 0]), id="children"), + ], + ) + def test_size_mismatch(self, impl, args): + result = self.compare(impl, self.args(*args, 0.1, 3)) + assert result.error is AssertionError + + def test_input_not_modified(self, impl): + # `compare` passes copies, so call directly + times = f64(*VIOLATED[0]) + copy = times.copy() + out = impl.util._constrain_ages( + times, b1(*VIOLATED[1]), i32(2, 3), i32(0, 2), 1e-6, 5 + ) + assert np.array_equal(times, copy) + assert out is not times + + @pytest.mark.parametrize("mode", ["iterated", "forced"]) + @pytest.mark.parametrize("seed", range(2)) + def test_simulated(self, impl, sim_ts, seed, mode): + ts = sim_ts + rng = np.random.default_rng(seed) + fixed = sample_flags(ts) + low, high, epsilon, max_iterations = { + "iterated": (0.9, 1.1, 1e-6, 50), + "forced": (0.5, 1.5, 1e-2, 0), + }[mode] + nodes_time = ts.nodes_time * rng.uniform(low, high, ts.num_nodes) + nodes_time[fixed] = ts.nodes_time[fixed] + args = ( + nodes_time, + fixed, + ts.edges_parent, + ts.edges_child, + epsilon, + max_iterations, + ) + self.compare(impl, args) + + +# nodes, edges, expected for (samples skipped, samples not skipped) +UNARY_CASES = [ + pytest.param([(1, 0), (1, 0), (0, 1)], BINARY_EDGES, False, False, id="binary"), + pytest.param([(1, 0), (1, 0)], [], False, False, id="no_edges"), + pytest.param( + [(1, 0), (1, 0), (0, 1), (0, 2)], + BINARY_EDGES + [(0, 10, 3, 2)], + True, + True, + id="unary_internal_node", + ), + pytest.param( + # sample 3 has the single child 0; the root has three children + [(1, 0), (1, 0), (1, 0), (1, 1), (0, 2)], + [(0, 10, 3, 0), (0, 10, 4, 3), (0, 10, 4, 1), (0, 10, 4, 2)], + False, + True, + id="unary_sample", + ), + pytest.param( + # node 3 is unary only over [4, 6) + [(1, 0), (1, 0), (1, 0), (0, 1), (0, 2)], + [(0, 4, 3, 0), (0, 4, 3, 1), (4, 6, 3, 0), (6, 10, 3, 0)] + + [(6, 10, 3, 1), (0, 10, 4, 3), (0, 10, 4, 2)], + True, + True, + id="unary_in_middle_tree", + ), + pytest.param( + # node 3 loses child 0 and gains child 2 at 5: it always has two children + [(1, 0), (1, 0), (1, 0), (0, 1)], + [(0, 5, 3, 0), (0, 10, 3, 1), (5, 10, 3, 2)], + False, + False, + id="child_replaced_at_breakpoint", + ), + pytest.param( + [(1, 0), (1, 0), (0, 1)], + [(0, 5, 2, 0), (0, 5, 2, 1), (5, 10, 2, 0)], + True, + True, + id="unary_in_last_tree", + ), + pytest.param( + [(1, 0), (1, 0), (0, 1)], + [(0, 5, 2, 0), (5, 10, 2, 0), (5, 10, 2, 1)], + True, + True, + id="unary_in_first_tree", + ), +] + + +class TestContainsUnaryNodes: + @staticmethod + def compare(impl, ts, mask): + return compare( + impl.util._contains_unary_nodes, + util._contains_unary_nodes, + mask, + ts.edges_parent, + ts.edges_left, + ts.edges_right, + ts.indexes_edge_insertion_order, + ts.indexes_edge_removal_order, + ts.sequence_length, + ts.num_nodes, + ) + + @staticmethod + def mask(ts, skip_samples): + mask = np.full(ts.num_nodes, False) + if skip_samples: + mask[ts.samples()] = True + return mask + + @pytest.mark.parametrize(("nodes", "edges", "skipped", "not_skipped"), UNARY_CASES) + def test_hand_built(self, impl, nodes, edges, skipped, not_skipped): + ts = make_ts(nodes, edges, [], 10.0) + result = self.compare(impl, ts, self.mask(ts, True)) + assert bool(result.value) is skipped + result = self.compare(impl, ts, self.mask(ts, False)) + assert bool(result.value) is not_skipped + + def test_all_nodes_masked(self, impl): + nodes = [(1, 0), (0, 1), (0, 2)] + ts = make_ts(nodes, [(0, 10, 1, 0), (0, 10, 2, 1)], [], 10.0) + result = self.compare(impl, ts, np.full(ts.num_nodes, True)) + assert not result.value + + @pytest.mark.parametrize("skip_samples", [True, False]) + @pytest.mark.parametrize("keep", [None, 3, 20]) + def test_simulated(self, impl, sim_ts, keep, skip_samples): + ts = sim_ts + if keep is not None: + ts = ts.simplify(ts.samples()[:keep], keep_unary=True) + self.compare(impl, ts, self.mask(ts, skip_samples)) From d75e3aae38cb541290237ef5ef7c99b2265fd38c Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Mon, 23 Nov 2026 11:17:04 -0800 Subject: [PATCH 06/56] Port tsdate.hypergeo to C, with the scalar-function infrastructure Add lib/hypergeo.c: _digamma, _trigamma, _betaln, _gammainc_der, _hyperu_laplace, _hyp1f1_laplace and _hyp2f1_laplace (with the unity limit), following the numba operation order, ipow multiplications and libm calls. lib/mathutil.h has the shared helpers (ipow, Python min/max, np.isclose). gammaincinv is not reimplemented: as numba did, SciPy's is called through the C API of scipy.special.cython_special. The module reads the capsule __pyx_capi__["gammaincinv"] at import (using the capsule's own name for the pointer lookup; the import fails with ImportError if SciPy or the symbol is missing) and keeps the pointer in a module-level static. The library has no global state and no SciPy dependency: tsd_gammaincinv_fn, a function pointer type documented in tsdate.h, is passed as an argument to the library functions that need it (none yet in this commit). gammainc_inv is exposed as a scalar function. Errors: new codes TSD_ERR_INVALID_HYPERGEO (every violated domain assertion of the hypergeometric functions and of _gammainc_der, and a root on the boundary) and TSD_ERR_ZERO_DIVISION (numba's ZeroDivisionError). Divisions are checked only where the tests reach them: the poles of digamma/trigamma, the Laplace root of hyperu/hyp1f1/hyp2f1, 1/v in hyperu, and c - a in hyp2f1. NaN and infinite results stay in-band. _tsdatemodule.c exposes scalar C functions through one table (name, number of inputs, number of outputs, adapter), with one generic wrapper that returns a float or a tuple and maps library errors to _tsdate.LibraryError. Tests: the oracle implementation registry gets a "c" entry whose unported names skip; expected_error/errors_match accept LibraryError (and ValueError for an oracle AssertionError); tests of the wrapper, of gammainc_inv against SciPy and of the import failure without SciPy's Cython API; CUnit smoke and error-path tests. The microbenchmark harness gets an (empty) C implementation and skips functions it lacks. --- _tsdatemodule.c | 272 ++++++++++++++++++ evaluation/microbench.py | 20 +- lib/err.c | 6 + lib/err.h | 6 + lib/hypergeo.c | 491 ++++++++++++++++++++++++++++++++ lib/mathutil.h | 85 ++++++ lib/meson.build | 2 +- lib/tests/tests.c | 209 +++++++++++++- lib/tsdate.h | 26 ++ setup.py | 2 +- tests/oracle/helpers.py | 33 ++- tests/oracle/implementations.py | 55 +++- tests/test_oracle_helpers.py | 55 ++++ tests/test_oracle_hypergeo.py | 7 +- tests/test_python_c_scalar.py | 159 +++++++++++ 15 files changed, 1412 insertions(+), 16 deletions(-) create mode 100644 lib/hypergeo.c create mode 100644 lib/mathutil.h create mode 100644 tests/test_python_c_scalar.py diff --git a/_tsdatemodule.c b/_tsdatemodule.c index 13d13df7..df5a5b12 100644 --- a/_tsdatemodule.c +++ b/_tsdatemodule.c @@ -34,6 +34,13 @@ static PyObject *TsdLibraryError; +/* + * SciPy's gammaincinv, taken from the C API of scipy.special.cython_special at module + * initialisation (as numba did). The third argument is Cython's __pyx_skip_dispatch. + */ +typedef double (*cython_gammaincinv_fn)(double a, double p, int skip_dispatch); +static cython_gammaincinv_fn scipy_gammaincinv; + static void handle_library_error(int err) { @@ -74,6 +81,216 @@ tsdate_raise_library_error(PyObject *Py_UNUSED(self), PyObject *args) return ret; } +/* + * Scalar functions: "N doubles in, M doubles out" functions of the C library are + * exposed to Python through the table below, with one generic wrapper. To expose a + * new function, write an adapter that unpacks `in` into the C call and stores the + * results in `out`, returning 0 or a library error code, and add a row. + * The Python function takes `num_in` numbers and returns a float (one output) or a + * tuple of floats. + */ +#define MAX_SCALAR_IO 16 + +typedef int (*scalar_adapter_t)(const double *in, double *out); + +typedef struct { + const char *name; + int num_in; + int num_out; + scalar_adapter_t adapter; +} scalar_function_t; + +static int +adapt_digamma(const double *in, double *out) +{ + return tsd_digamma(in[0], out); +} + +static int +adapt_trigamma(const double *in, double *out) +{ + return tsd_trigamma(in[0], out); +} + +static int +adapt_betaln(const double *in, double *out) +{ + out[0] = tsd_betaln(in[0], in[1]); + return 0; +} + +static int +adapt_gammainc_der(const double *in, double *out) +{ + return tsd_gammainc_der(in[0], in[1], out); +} + +/* A tsd_gammaincinv_fn: this is what is passed to library functions that need it. */ +static double +gammaincinv(double a, double p) +{ + return scipy_gammaincinv(a, p, 0); +} + +static int +adapt_gammainc_inv(const double *in, double *out) +{ + out[0] = gammaincinv(in[0], in[1]); + return 0; +} + +static int +adapt_hyperu_laplace(const double *in, double *out) +{ + return tsd_hyperu_laplace(in[0], in[1], in[2], out, out + 1); +} + +static int +adapt_hyp1f1_laplace(const double *in, double *out) +{ + return tsd_hyp1f1_laplace(in[0], in[1], in[2], out); +} + +static int +adapt_hyp2f1_laplace(const double *in, double *out) +{ + return tsd_hyp2f1_laplace(in[0], in[1], in[2], in[3], out); +} + +/* clang-format off */ +static const scalar_function_t scalar_functions[] = { + /* hypergeo */ + { "digamma", 1, 1, adapt_digamma }, + { "trigamma", 1, 1, adapt_trigamma }, + { "betaln", 2, 1, adapt_betaln }, + { "gammainc_der", 2, 1, adapt_gammainc_der }, + { "gammainc_inv", 2, 1, adapt_gammainc_inv }, + { "hyperu_laplace", 3, 2, adapt_hyperu_laplace }, + { "hyp1f1_laplace", 3, 1, adapt_hyp1f1_laplace }, + { "hyp2f1_laplace", 4, 1, adapt_hyp2f1_laplace }, +}; +/* clang-format on */ + +#define NUM_SCALAR_FUNCTIONS (sizeof(scalar_functions) / sizeof(scalar_functions[0])) + +/* Method definitions of the scalar functions, filled in at module initialisation. */ +static PyMethodDef scalar_method_defs[NUM_SCALAR_FUNCTIONS]; + +/* Parse `num_in` numbers from the argument tuple. Returns 0, or -1 with an exception. */ +static int +scalar_parse_args(const scalar_function_t *row, PyObject *args, double *in) +{ + int ret = -1; + Py_ssize_t j; + Py_ssize_t num_args = PyTuple_GET_SIZE(args); + + if (num_args != row->num_in) { + PyErr_Format(PyExc_TypeError, "%s() takes exactly %d arguments (%zd given)", + row->name, row->num_in, num_args); + goto out; + } + for (j = 0; j < num_args; j++) { + in[j] = PyFloat_AsDouble(PyTuple_GET_ITEM(args, j)); + if (in[j] == -1.0 && PyErr_Occurred()) { + goto out; + } + } + ret = 0; +out: + return ret; +} + +/* Build the return value: a float for one output, otherwise a tuple of floats. */ +static PyObject * +scalar_build_result(const scalar_function_t *row, const double *out) +{ + PyObject *ret = NULL; + PyObject *item = NULL; + PyObject *tuple = NULL; + int j; + + if (row->num_out == 1) { + ret = PyFloat_FromDouble(out[0]); + goto out; + } + tuple = PyTuple_New(row->num_out); + if (tuple == NULL) { + goto out; + } + for (j = 0; j < row->num_out; j++) { + item = PyFloat_FromDouble(out[j]); + if (item == NULL) { + goto out; + } + PyTuple_SET_ITEM(tuple, j, item); /* steals the reference */ + } + ret = tuple; + tuple = NULL; +out: + Py_XDECREF(tuple); + return ret; +} + +/* The generic wrapper; `self` is the index of the row in the table. */ +static PyObject * +scalar_call(PyObject *self, PyObject *args) +{ + PyObject *ret = NULL; + const scalar_function_t *row; + double in[MAX_SCALAR_IO]; + double out[MAX_SCALAR_IO]; + Py_ssize_t index = PyLong_AsSsize_t(self); + int err; + + row = &scalar_functions[index]; + if (scalar_parse_args(row, args, in) != 0) { + goto out; + } + err = row->adapter(in, out); + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = scalar_build_result(row, out); +out: + return ret; +} + +/* Add one Python function per row of the table to the module. */ +static int +add_scalar_functions(PyObject *module) +{ + int ret = -1; + PyObject *index = NULL; + PyObject *func = NULL; + size_t j; + + for (j = 0; j < NUM_SCALAR_FUNCTIONS; j++) { + scalar_method_defs[j].ml_name = scalar_functions[j].name; + scalar_method_defs[j].ml_meth = (PyCFunction) scalar_call; + scalar_method_defs[j].ml_flags = METH_VARARGS; + scalar_method_defs[j].ml_doc = "Scalar function of the C library."; + index = PyLong_FromSize_t(j); + if (index == NULL) { + goto out; + } + func = PyCFunction_New(&scalar_method_defs[j], index); + Py_DECREF(index); + index = NULL; + if (func == NULL) { + goto out; + } + if (PyModule_AddObject(module, scalar_functions[j].name, func) != 0) { + goto out; + } + func = NULL; /* the module owns the reference now */ + } + ret = 0; +out: + Py_XDECREF(func); + return ret; +} + static PyMethodDef tsdate_methods[] = { { "strerror", (PyCFunction) tsdate_strerror, METH_VARARGS, "Return the message for a library error code." }, @@ -85,6 +302,52 @@ static PyMethodDef tsdate_methods[] = { static struct PyModuleDef tsdatemodule = { PyModuleDef_HEAD_INIT, "_tsdate", MODULE_DOC, -1, tsdate_methods, NULL, NULL, NULL, NULL }; +/* + * Look up scipy.special.cython_special.gammaincinv through its Cython C API capsule. + * The capsule's name is its C signature, which is used as given to get the pointer. + */ +static int +load_scipy_gammaincinv(void) +{ + int ret = -1; + PyObject *cython_special = NULL; + PyObject *capi = NULL; + PyObject *capsule = NULL; + const char *name; + void *ptr; + + cython_special = PyImport_ImportModule("scipy.special.cython_special"); + if (cython_special == NULL) { + PyErr_SetString( + PyExc_ImportError, "_tsdate requires scipy.special.cython_special"); + goto out; + } + capi = PyObject_GetAttrString(cython_special, "__pyx_capi__"); + if (capi == NULL) { + goto out; + } + capsule = PyDict_GetItemString(capi, "gammaincinv"); /* borrowed */ + if (capsule == NULL || !PyCapsule_CheckExact(capsule)) { + PyErr_SetString(PyExc_ImportError, + "scipy.special.cython_special does not provide gammaincinv"); + goto out; + } + name = PyCapsule_GetName(capsule); + if (name == NULL) { + goto out; + } + ptr = PyCapsule_GetPointer(capsule, name); + if (ptr == NULL) { + goto out; + } + scipy_gammaincinv = (cython_gammaincinv_fn) ptr; + ret = 0; +out: + Py_XDECREF(cython_special); + Py_XDECREF(capi); + return ret; +} + PyObject * PyInit__tsdate(void) { @@ -100,5 +363,14 @@ PyInit__tsdate(void) Py_INCREF(TsdLibraryError); PyModule_AddObject(module, "LibraryError", TsdLibraryError); + if (load_scipy_gammaincinv() != 0) { + Py_DECREF(module); + return NULL; + } + if (add_scalar_functions(module) != 0) { + Py_DECREF(module); + return NULL; + } + return module; } diff --git a/evaluation/microbench.py b/evaluation/microbench.py index 3204786a..f54a37c8 100644 --- a/evaluation/microbench.py +++ b/evaluation/microbench.py @@ -79,10 +79,20 @@ def _numba_impl(): } -# The seam for adding implementations: name -> {function name -> callable}. A later -# step adds e.g. "c": _c_impl here (a function returning a dict like _numba_impl's, -# possibly wrapping calls to adapt argument types such as EPFactors). -IMPLS = {"numba": _numba_impl} +def _c_impl(): + """ + Callables of the C implementation. Each ported array-level function is added as + ``name: callable`` (taking the arguments of the numba function of that name); the + functions that are missing are skipped in the benchmarks. + """ + return {} + + +# The seam for adding implementations: name -> {function name -> callable}. A +# function returning a dict like _numba_impl's (possibly wrapping calls to adapt +# argument types such as EPFactors). Benchmarks that an implementation lacks are +# skipped for it. +IMPLS = {"numba": _numba_impl, "c": _c_impl} def numba_compile_times(funcs): @@ -647,6 +657,8 @@ def main(): if args.only and not any(s in bench.name for s in args.only): continue for name, funcs in impls.items(): + if bench.func not in funcs: + continue times, first, batch = time_bench(funcs[bench.func], bench, args.repeats) row = dict( function=bench.name, diff --git a/lib/err.c b/lib/err.c index 7d241c75..da5cdcb1 100644 --- a/lib/err.c +++ b/lib/err.c @@ -44,6 +44,12 @@ tsd_strerror(int err) case TSD_ERR_BAD_PARAM: ret = "Bad parameter value provided"; break; + case TSD_ERR_ZERO_DIVISION: + ret = "Floating-point division by zero"; + break; + case TSD_ERR_INVALID_HYPERGEO: + ret = "Parameters outside the domain of the hypergeometric function"; + break; default: break; } diff --git a/lib/err.h b/lib/err.h index 294c9ebf..268dd30e 100644 --- a/lib/err.h +++ b/lib/err.h @@ -36,6 +36,12 @@ extern "C" { #define TSD_ERR_GENERIC -1 #define TSD_ERR_NO_MEMORY -2 #define TSD_ERR_BAD_PARAM -3 + +/* Floating-point division by zero, where numba raises ZeroDivisionError */ +#define TSD_ERR_ZERO_DIVISION -4 + +/* hypergeo */ +#define TSD_ERR_INVALID_HYPERGEO -5 /* clang-format on */ #ifdef __GNUC__ diff --git a/lib/hypergeo.c b/lib/hypergeo.c new file mode 100644 index 00000000..62d66ae7 --- /dev/null +++ b/lib/hypergeo.c @@ -0,0 +1,491 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* + * Numerically stable implementations of the Gauss hypergeometric function and related + * special functions, ported from tsdate/hypergeo.py (numba). Operation order and + * libm calls follow the numba code so that results agree to the last bit or two. + * + * In numba, a float division by zero raises ZeroDivisionError; here it returns + * TSD_ERR_ZERO_DIVISION, but only at the divisions that the tests show to be + * reachable (those of the poles of the polygamma functions and of the Laplace + * roots). The other divisions follow IEEE semantics (infinity or NaN). + */ + +#include + +#include "mathutil.h" +#include "tsdate.h" + +/* Digamma function for x > 0 (or NaN), by recurrence and asymptotic series. */ +static double +digamma_positive(double x) +{ + double xpm2, value; + + if (x <= 1e-5) { + return -TSD_EULER_GAMMA - (1 / x); + } + if (x < 8.5) { + return digamma_positive(1 + x) - 1 / x; + } + xpm2 = 1 / tsd_ipow(x, 2); + value = log(x); + value -= 0.5 / x; + value -= 0.083333333333333333 * xpm2; + value += 0.008333333333333333 * tsd_ipow(xpm2, 2); + value -= 0.003968253968253968 * tsd_ipow(xpm2, 3); + value += 0.004166666666666667 * tsd_ipow(xpm2, 4); + value -= 0.007575757575757576 * tsd_ipow(xpm2, 5); + value += 0.021092796092796094 * tsd_ipow(xpm2, 6); + return value; +} + +/* Digamma (psi) function, from asymptotic series expansion. */ +int +tsd_digamma(double x, double *out) +{ + int ret = 0; + double reflected, tan_pix; + + if (x <= 0.0) { + /* Reflection formula; 1 - x >= 1 */ + reflected = digamma_positive(1 - x); + tan_pix = tan(TSD_PI * x); + if (tan_pix == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + *out = reflected - TSD_PI / tan_pix; + } else { + *out = digamma_positive(x); + } +out: + return ret; +} + +/* Trigamma function for x > 1e-4 (or NaN), by recurrence and asymptotic series. */ +static double +trigamma_large(double x) +{ + double x_sq, xpm1, xpm2, value; + + x_sq = tsd_ipow(x, 2); + if (x < 5) { + return trigamma_large(1 + x) + 1 / x_sq; + } + xpm1 = 1 / x; + xpm2 = 1 / x_sq; + value = 1.000000000000000000; + value += 0.500000000000000000 * xpm1; + value += 0.166666666666666667 * pow(xpm2, 1); + value -= 0.033333333333333333 * pow(xpm2, 2); + value += 0.023809523809523808 * pow(xpm2, 3); + value -= 0.033333333333333333 * pow(xpm2, 4); + value += 0.075757575757575756 * pow(xpm2, 5); + value -= 0.253113553113553102 * pow(xpm2, 6); + value += 1.166666666666666741 * pow(xpm2, 7); + return xpm1 * value; +} + +/* Trigamma function, from asymptotic series expansion. */ +int +tsd_trigamma(double x, double *out) +{ + int ret = 0; + double reflected, sin_pix, sin_sq, x_sq; + + if (x <= 0.0) { + /* Reflection formula; 1 - x >= 1 */ + reflected = trigamma_large(1 - x); + sin_pix = sin(TSD_PI * x); + sin_sq = tsd_ipow(sin_pix, 2); + if (sin_sq == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + *out = -reflected + tsd_ipow(TSD_PI, 2) / sin_sq; + } else if (x <= 1e-4) { + x_sq = tsd_ipow(x, 2); + if (x_sq == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + *out = 1 / x_sq; + } else { + *out = trigamma_large(x); + } +out: + return ret; +} + +/* Log of the beta function. */ +double +tsd_betaln(double p, double q) +{ + return lgamma(p) + lgamma(q) - lgamma(p + q); +} + +/* + * Approximate Tricomi's confluent hypergeometric function with real arguments, using + * Laplace's method with a calibration point. Also returns the derivative wrt x. + */ +int +tsd_hyperu_laplace(double a, double b, double x, double *value, double *dvalue) +{ + int ret = 0; + double t, denom, u, r, g, w, v, dr, dg, du; + + if (!(b >= a && a > 0.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_HYPERGEO); + goto out; + } + if (!(x > 0.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_HYPERGEO); + goto out; + } + + t = b - x - 1; + denom = sqrt(tsd_ipow(t, 2) + 4 * x * a) - t; + if (denom == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + u = 2 * a / denom; + r = (b - a - 1) * tsd_ipow(u, 2) + a * tsd_ipow(1 + u, 2); + g = (b - a) * log(1 + u); + g += a * (1 + log(u)); + g -= x * u; + g -= log(a) * (a - 0.5); + + w = (b - 1) * u + a; + v = u * (1 + u); + dr = w / (w * u + a * (1 + u)); + if (v == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + dg = (w - x * v + u) / v; + du = -u * v / (w - x * u + a); + + *value = g - log(r) / 2; + *dvalue = (dg - dr) * du - u; +out: + return ret; +} + +/* + * Approximate Kummer's confluent hypergeometric function with real arguments, using + * Laplace's method with a calibration point. + */ +int +tsd_hyp1f1_laplace(double a, double b, double x, double *out) +{ + int ret = 0; + double t, denom, u, r, g; + + if (!(b > a && a > 0.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_HYPERGEO); + goto out; + } + + if (x == 0.0) { + *out = 0.0; + goto out; + } + + t = x - b; + denom = sqrt(tsd_ipow(t, 2) + 4 * x * a) - t; + if (denom == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + u = 2 * a / denom; + r = tsd_ipow(u, 2) * b / a + tsd_ipow(1 - u, 2) * b / (b - a); + g = (b - a) * log(1 - u); + g += a * log(u); + g += b * log(b); + g -= (b - a) * log(b - a); + g -= a * log(a); + g += x * u; + + *out = g - log(r) / 2; +out: + return ret; +} + +/* + * Gauss hypergeometric function when `x` is near unity. See limits in DLMF 15.4. + * + * TODO: this works in practice, but when (c - a - b) is close to zero the limits don't + * converge. A good reference is Buhring 2003 "Partial sums of hypergeometric series of + * unit argument" + */ +static int +hyp2f1_unity(double a, double b, double c, double x, double *out) +{ + int ret = 0; + double g, value; + + tsd_bug_assert(tsd_isclose(x, 1.0)); + if (!(x < 1.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_HYPERGEO); + goto out; + } + + g = c - a - b; + + if (g < 0.0) { + value = lgamma(c) + lgamma(-g) - lgamma(a) - lgamma(b) + g * log(1 - x); + } else if (g > 0.0) { + /* will only occur when a_i + a_j < 1 */ + value = lgamma(c) + lgamma(g) - lgamma(c - a) - lgamma(c - b); + } else { + /* will only occur when a_i + a_j == 1 */ + value = log(-log(1 - x)) + lgamma(a + b) - lgamma(a) - lgamma(b); + } + *out = value; +out: + return ret; +} + +/* + * Approximate a Gaussian hypergeometric function with real arguments, using Laplace's + * method with a calibration point. + */ +int +tsd_hyp2f1_laplace(double a, double b, double c, double x, double *out) +{ + int ret = 0; + double s, t, u, y, yy, my, ymy, r, f, unity, denom; + + /* TODO: simplify, we can safely assume a,b > 0? */ + if (!(c > 0.0 && a >= 0.0 && b >= 0.0 && c >= a && x < 1.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_HYPERGEO); + goto out; + } + + if (x == 0.0) { + *out = 0.0; + goto out; + } + + s = 0.0; + if (x < 0.0) { + s = -b * log(1 - x); + a = c - a; + x = x / (x - 1); + } + + if (tsd_isclose(x, 1.0)) { + ret = hyp2f1_unity(a, b, c, x, &unity); + if (ret != 0) { + goto out; + } + *out = s + unity; + goto out; + } + + t = x * (b - a) - c; + u = sqrt(tsd_ipow(t, 2) - 4 * a * x * (c - b)) - t; + if (u == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + y = 2 * a / u; + + /* Root on boundary */ + if (!(0 < y && y < 1)) { + ret = tsd_trace_error(TSD_ERR_INVALID_HYPERGEO); + goto out; + } + + yy = tsd_ipow(y, 2) / a; + denom = c - a; + if (denom == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + my = tsd_ipow(1 - y, 2) / denom; + ymy = tsd_ipow(x, 2) * b * yy * my / tsd_ipow(1 - x * y, 2); + r = yy + my - ymy; + f = (c - 0.5) * log(c); + f += a * (log(y) - log(a)); + f += (c - a) * (log(1 - y) - log(c - a)); + f -= b * log(1 - x * y); + + *out = f - log(r) / 2 + s; +out: + return ret; +} + +/* Gaussian approximation of the derivative of the lower incomplete gamma function. */ +static double +gammainc_der_gaussian(double p, double x) +{ + double pn1, grad, cbrt_ratio; + + cbrt_ratio = pow(x / p, 1.0 / 3.0); + pn1 = 3 * sqrt(p) * (cbrt_ratio + 1 / (9 * p) - 1); + grad = pn1 / (2 * p) - 1 / sqrt(p) * (cbrt_ratio + 1 / (3 * p)); + grad *= 1 / sqrt(2 * TSD_PI) * exp(-(tsd_ipow(pn1, 2)) / 2); + return grad; +} + +/* Derivative of the lower incomplete gamma function by series expansion. */ +static double +gammainc_der_series(double p, double x, double tol, double elimit) +{ + double arg, value, grad, c, dc, a, darg; + + arg = p * log(x) - x - lgamma(p + 1); + value = 1.0; + grad = 0.0; + c = 1.0; + dc = 0.0; + a = p; + while (1) { + a += 1.0; + dc = -c * x / tsd_ipow(a, 2) + dc * x / a; + c *= x / a; + value += c; + grad += dc; + if (c <= tol) { + break; + } + } + darg = exp(arg) * (log(x) - digamma_positive(p + 1)); + grad = grad * exp(arg) + value * darg; + arg += log(value); + if (!(arg >= elimit)) { + grad = 0.0; + } + return grad; +} + +/* Derivative of the upper incomplete gamma function by continued fraction. */ +static double +gammainc_der_fraction(double p, double x, double tol, double elimit, double oflo) +{ + double arg, a, b, c, an, value, grad, rn, darg; + double pn1, pn2, pn3, pn4, pn5, pn6; + double dpn1, dpn2, dpn3, dpn4, dpn5, dpn6; + + arg = p * log(x) - x - lgamma(p); + a = 1.0 - p; + b = a + x + 1.0; + c = 0.0; + pn1 = 1.0; + pn2 = x; + pn3 = x + 1.0; + pn4 = x * b; + dpn1 = 0.0; + dpn2 = 0.0; + dpn3 = 0.0; + dpn4 = -x; + value = pn3 / pn4; + grad = 0.0; + while (1) { + a += 1.0; + b += 2.0; + c += 1.0; + an = a * c; + pn5 = b * pn3 - an * pn1; + pn6 = b * pn4 - an * pn2; + dpn5 = b * dpn3 - pn3 - an * dpn1 + c * pn1; + dpn6 = b * dpn4 - pn4 - an * dpn2 + c * pn2; + if (pn6 != 0.0) { + rn = pn5 / pn6; + grad = (dpn5 * pn6 - pn5 * dpn6) / tsd_ipow(pn6, 2); + if (fabs(value - rn) <= tsd_min(tol, tol * rn)) { + break; + } + value = rn; + } + pn1 = pn3; + pn2 = pn4; + pn3 = pn5; + pn4 = pn6; + dpn1 = dpn3; + dpn2 = dpn4; + dpn3 = dpn5; + dpn4 = dpn6; + if (oflo <= fabs(pn5)) { + pn1 /= oflo; + pn2 /= oflo; + pn3 /= oflo; + pn4 /= oflo; + dpn1 /= oflo; + dpn2 /= oflo; + dpn3 /= oflo; + dpn4 /= oflo; + } + } + darg = exp(arg) * (log(x) - digamma_positive(p)); + grad = grad * exp(arg) + value * darg; + arg += log(value); + if (arg >= elimit) { + grad *= -1.0; + } else { + grad = 0.0; + } + return grad; +} + +/* + * Derivative of the lower incomplete gamma function with regards to `p`. + * + * Based on Shea B (1988) "Algorithm AS 239" Applied Statistics 37: 466-473 + * + * Adapted from https://people.math.sc.edu/Burkardt/cpp_src/asa239/asa239.cpp + */ +int +tsd_gammainc_der(double p, double x, double *out) +{ + int ret = 0; + const double elimit = -88.0; + const double oflo = 1.0e37; + const double plimit = 1.0e3; + const double tol = 1.0e-14; + const double xbig = 1.0e8; + + if (!(x >= 0.0 && p > 0.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_HYPERGEO); + goto out; + } + + if (x == 0) { + *out = 0.0; + } else if (x > xbig) { + *out = 0.0; + } else if (p > plimit) { + *out = gammainc_der_gaussian(p, x); + } else if (x <= 1 || x < p) { + *out = gammainc_der_series(p, x, tol, elimit); + } else { + *out = gammainc_der_fraction(p, x, tol, elimit, oflo); + } +out: + return ret; +} diff --git a/lib/mathutil.h b/lib/mathutil.h new file mode 100644 index 00000000..769479ad --- /dev/null +++ b/lib/mathutil.h @@ -0,0 +1,85 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef TSD_MATHUTIL_H +#define TSD_MATHUTIL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/* Constants that only defines as extensions (and MSVC not by default). */ +#define TSD_PI 3.141592653589793 +#define TSD_EULER_GAMMA 0.5772156649015329 + +/* + * x ** n for a small positive integer constant n, by repeated squaring. This is the + * multiplication order of llvm.powi, which numba uses for `x ** n`; ipow(x, 2) is + * exactly x * x. It can differ in the last bit from pow(x, n). + */ +static inline double +tsd_ipow(double x, int n) +{ + double result = 1.0; + + while (1) { + if (n & 1) { + result *= x; + } + n >>= 1; + if (n == 0) { + return result; + } + x *= x; + } +} + +/* Python's min(a, b): b if b < a else a (so NaN handling differs from fmin). */ +static inline double +tsd_min(double a, double b) +{ + return b < a ? b : a; +} + +/* Python's max(a, b): b if b > a else a (so NaN handling differs from fmax). */ +static inline double +tsd_max(double a, double b) +{ + return b > a ? b : a; +} + +/* np.isclose(a, b) for finite or NaN arguments, with default rtol and atol. */ +static inline int +tsd_isclose(double a, double b) +{ + return fabs(a - b) <= 1e-8 + 1e-5 * fabs(b); +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/lib/meson.build b/lib/meson.build index bbcc384f..a5ef894c 100644 --- a/lib/meson.build +++ b/lib/meson.build @@ -15,7 +15,7 @@ if get_option('buildtype') == 'debug' extra_c_args += ['-DTSD_TRACE_ERRORS'] endif -tsdate_sources = ['err.c'] +tsdate_sources = ['err.c', 'hypergeo.c'] tsdate_lib = static_library('tsdate', sources: tsdate_sources, dependencies: [m_dep], diff --git a/lib/tests/tests.c b/lib/tests/tests.c index 07c5e970..75c6110f 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -27,6 +27,7 @@ * memory handling only; numerical correctness is tested from Python. */ +#include #include #include #include @@ -38,7 +39,8 @@ static void test_strerror(void) { - const int codes[] = { 0, TSD_ERR_GENERIC, TSD_ERR_NO_MEMORY, TSD_ERR_BAD_PARAM }; + const int codes[] = { 0, TSD_ERR_GENERIC, TSD_ERR_NO_MEMORY, TSD_ERR_BAD_PARAM, + TSD_ERR_ZERO_DIVISION, TSD_ERR_INVALID_HYPERGEO }; const int num_codes = (int) (sizeof(codes) / sizeof(codes[0])); const char *msg_i; const char *msg_j; @@ -95,6 +97,200 @@ test_bug_assert_passes(void) tsd_bug_assert(1 + 1 == 2); } +static void +test_polygamma(void) +{ + const double points[] = { 1e-6, 0.5, 4.9, 8.4, 10.0, 100.0, -0.5, -1.5, -10.5 }; + const int num_points = (int) (sizeof(points) / sizeof(points[0])); + double value; + int j, ret; + + for (j = 0; j < num_points; j++) { + ret = tsd_digamma(points[j], &value); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(isfinite(value)); + ret = tsd_trigamma(points[j], &value); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(isfinite(value)); + } + /* NaN is in-band */ + ret = tsd_digamma(NAN, &value); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(isnan(value)); + ret = tsd_trigamma(NAN, &value); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(isnan(value)); +} + +static void +test_polygamma_poles(void) +{ + double value; + int ret; + + ret = tsd_digamma(0.0, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + ret = tsd_trigamma(0.0, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + /* x ** 2 underflows to zero */ + ret = tsd_trigamma(1e-300, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); +} + +static void +test_betaln(void) +{ + double value = tsd_betaln(2.0, 3.0); + + CU_ASSERT_DOUBLE_EQUAL(value, log(1.0 / 12.0), 1e-12); +} + +static void +test_gammainc_der(void) +{ + /* x == 0, x > xbig, gaussian, series and continued fraction regimes */ + const double points[][2] = { { 1.0, 0.0 }, { 5.0, 1e9 }, { 2000.0, 2000.0 }, + { 2.0, 1.5 }, { 5.0, 50.0 } }; + const int num_points = (int) (sizeof(points) / sizeof(points[0])); + double value; + int j, ret; + + for (j = 0; j < num_points; j++) { + ret = tsd_gammainc_der(points[j][0], points[j][1], &value); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(isfinite(value)); + } + /* Series with a very small value: the result is truncated to zero */ + ret = tsd_gammainc_der(50.0, 1e-3, &value); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(value, 0.0); +} + +static void +test_gammainc_der_errors(void) +{ + double value; + int ret; + + ret = tsd_gammainc_der(-1.0, 1.0, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + ret = tsd_gammainc_der(1.0, -1.0, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + ret = tsd_gammainc_der(NAN, 1.0, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); +} + +static void +test_hyperu_laplace(void) +{ + double value, dvalue; + int ret; + + ret = tsd_hyperu_laplace(1.0, 2.0, 1.0, &value, &dvalue); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(isfinite(value)); + CU_ASSERT(isfinite(dvalue)); +} + +static void +test_hyperu_laplace_errors(void) +{ + double value, dvalue; + int ret; + + ret = tsd_hyperu_laplace(1.0, 0.5, 1.0, &value, &dvalue); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + ret = tsd_hyperu_laplace(0.0, 1.0, 1.0, &value, &dvalue); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + ret = tsd_hyperu_laplace(1.0, 2.0, 0.0, &value, &dvalue); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + ret = tsd_hyperu_laplace(1.0, 2.0, NAN, &value, &dvalue); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + /* The Laplace root divides by zero */ + ret = tsd_hyperu_laplace(1.0, 2.0, 1e300, &value, &dvalue); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + ret = tsd_hyperu_laplace(1.0, 2.0, INFINITY, &value, &dvalue); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); +} + +static void +test_hyp1f1_laplace(void) +{ + double value; + int ret; + + ret = tsd_hyp1f1_laplace(1.0, 2.0, 1.0, &value); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(isfinite(value)); + ret = tsd_hyp1f1_laplace(1.0, 2.0, 0.0, &value); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(value, 0.0); +} + +static void +test_hyp1f1_laplace_errors(void) +{ + double value; + int ret; + + ret = tsd_hyp1f1_laplace(1.0, 1.0, 1.0, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + ret = tsd_hyp1f1_laplace(0.0, 1.0, 1.0, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + ret = tsd_hyp1f1_laplace(1e-10, 2e-10, 1e8, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); +} + +static void +test_hyp2f1_laplace(void) +{ + /* The interior, z < 0 and the three unity limits, including negative z */ + const double args[][4] = { { 1.0, 2.0, 3.0, 0.5 }, { 1.0, 2.0, 3.0, -0.5 }, + { 1.0, 2.0, 3.0, 0.0 }, { 2.0, 3.0, 4.0, 1 - 1e-8 }, { 1.0, 2.0, 5.0, 1 - 1e-8 }, + { 1.0, 2.0, 3.0, 1 - 1e-8 }, { 2.0, 3.0, 4.0, -1e8 }, { 3.0, 2.0, 5.0, -1e8 }, + { 2.0, 2.0, 5.0, -1e8 } }; + const int num_args = (int) (sizeof(args) / sizeof(args[0])); + double value; + int j, ret; + + for (j = 0; j < num_args; j++) { + ret = tsd_hyp2f1_laplace(args[j][0], args[j][1], args[j][2], args[j][3], &value); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(isfinite(value)); + } +} + +static void +test_hyp2f1_laplace_errors(void) +{ + double value; + int ret; + + /* Each condition of the domain, and the root on the boundary */ + ret = tsd_hyp2f1_laplace(1.0, 2.0, 0.0, 0.5, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + ret = tsd_hyp2f1_laplace(-1.0, 2.0, 3.0, 0.5, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + ret = tsd_hyp2f1_laplace(1.0, -1.0, 3.0, 0.5, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + ret = tsd_hyp2f1_laplace(2.0, 1.0, 1.0, 0.5, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + ret = tsd_hyp2f1_laplace(1.0, 2.0, 3.0, 1.0, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + ret = tsd_hyp2f1_laplace(0.0, 1.0, 1.0, 0.5, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + /* z / (z - 1) rounds to one, outside the domain of the unity limit */ + ret = tsd_hyp2f1_laplace(1.0, 2.0, 3.0, -1e16, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + /* The Laplace root divides by zero */ + ret = tsd_hyp2f1_laplace(0.0, 1.0, 1e-300, 0.5, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + /* c == a, with a root that rounds into (0, 1) */ + ret = tsd_hyp2f1_laplace(1.1774154985086274, 504.4082462406216, 1.1774154985086274, + 0.1427180165924374, &value); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); +} + static void handle_cunit_error(void) { @@ -115,6 +311,17 @@ main(int argc, char **argv) { "test_trace_error", test_trace_error }, { "test_safe_free", test_safe_free }, { "test_bug_assert_passes", test_bug_assert_passes }, + { "test_polygamma", test_polygamma }, + { "test_polygamma_poles", test_polygamma_poles }, + { "test_betaln", test_betaln }, + { "test_gammainc_der", test_gammainc_der }, + { "test_gammainc_der_errors", test_gammainc_der_errors }, + { "test_hyperu_laplace", test_hyperu_laplace }, + { "test_hyperu_laplace_errors", test_hyperu_laplace_errors }, + { "test_hyp1f1_laplace", test_hyp1f1_laplace }, + { "test_hyp1f1_laplace_errors", test_hyp1f1_laplace_errors }, + { "test_hyp2f1_laplace", test_hyp2f1_laplace }, + { "test_hyp2f1_laplace_errors", test_hyp2f1_laplace_errors }, CU_TEST_INFO_NULL, }; CU_SuiteInfo suites[] = { diff --git a/lib/tsdate.h b/lib/tsdate.h index 96575cc6..f28661e6 100644 --- a/lib/tsdate.h +++ b/lib/tsdate.h @@ -38,6 +38,32 @@ typedef int32_t tsd_id_t; /* Counts and sizes; matches tsk_size_t. */ typedef uint64_t tsd_size_t; +/* + * Scalar special functions (hypergeo.c). Functions that can fail return 0 or a + * negative TSD_ERR_* code and write their results to the trailing output pointers; + * those that cannot fail return the result. As in the numba code they replace, NaN + * and infinite results are in-band (not errors): only violated domain assertions + * (TSD_ERR_INVALID_HYPERGEO) and divisions by zero (TSD_ERR_ZERO_DIVISION) fail. + */ +int tsd_digamma(double x, double *out); +int tsd_trigamma(double x, double *out); +double tsd_betaln(double p, double q); +int tsd_gammainc_der(double p, double x, double *out); +int tsd_hyperu_laplace(double a, double b, double x, double *value, double *dvalue); +int tsd_hyp1f1_laplace(double a, double b, double x, double *out); +int tsd_hyp2f1_laplace(double a, double b, double c, double x, double *out); + +/* + * The inverse of the regularised lower incomplete gamma function, x such that + * gammainc(a, x) = p, is not implemented in the library: SciPy's gammaincinv is + * called, as the numba code did. The caller (the Python module) supplies it, and + * library functions that need it (the approx and rescaling functions) take a + * parameter of this type, so that the library has no global state and no dependency + * on SciPy. The function returns NaN, 0 or infinity (not an error) for arguments + * outside the domain. + */ +typedef double (*tsd_gammaincinv_fn)(double a, double p); + #ifdef __cplusplus } #endif diff --git a/setup.py b/setup.py index e9b07c08..46239cc8 100644 --- a/setup.py +++ b/setup.py @@ -9,7 +9,7 @@ libdir = "lib" includes = [libdir] -tsd_source_files = ["err.c"] +tsd_source_files = ["err.c", "hypergeo.c"] sources = ["_tsdatemodule.c"] + [os.path.join(libdir, f) for f in tsd_source_files] diff --git a/tests/oracle/helpers.py b/tests/oracle/helpers.py index 7d1417b0..f6f4cd72 100644 --- a/tests/oracle/helpers.py +++ b/tests/oracle/helpers.py @@ -3,6 +3,11 @@ import numpy as np import tskit +try: + from _tsdate import LibraryError +except ImportError: # the extension has not been built + LibraryError = None + def _flatten(x, path=""): """Yield (path, array) for each leaf of a nested tuple/list of scalars/arrays.""" @@ -78,13 +83,28 @@ def log_uniform(rng, lo, hi, size=None): return float(x) if size is None else x +# Exceptions of the oracle (and numba) that the C library reports as a LibraryError. +_LIBRARY_ERROR_NAMES = ( + "ZeroDivisionError", + "AssertionError", + "KLMinimizationFailedError", + "ValueError", +) + + def expected_error(exc_type): """ The exceptions an implementation may raise where numba raises ``exc_type`` (``ZeroDivisionError``, ``AssertionError``, ...), for ``pytest.raises``. The C - port adds ``_tsdate.LibraryError`` here; this is the single place to do so. + library reports these as ``_tsdate.LibraryError``, and its argument checks raise + ``ValueError`` where numba asserts on array shapes and sizes. """ - return (exc_type,) + allowed = (exc_type,) + if LibraryError is not None and exc_type.__name__ in _LIBRARY_ERROR_NAMES: + allowed += (LibraryError,) + if exc_type is AssertionError: + allowed += (ValueError,) + return allowed class Outcome: @@ -138,13 +158,18 @@ def errors_match(actual, expected, check_message=True): the oracle): the same type and, if ``check_message``, the same message. The message of a ``ZeroDivisionError`` comes from the runtime, not from tsdate (numba says "division by zero", Python "float division by zero"), so it is not compared. - The C port extends this to accept ``_tsdate.LibraryError`` (see - `expected_error`). + A ``_tsdate.LibraryError`` (or, for an ``AssertionError``, a ``ValueError`` from + the module's shape checks) is accepted in place of the exceptions of + `expected_error`; its message is compared only with those of the tsdate-authored, + user-facing errors (``KLMinimizationFailedError`` and ``ValueError``), as the + messages of the others (assertions, divisions) are not part of the interface. """ if not isinstance(actual, expected_error(type(expected))): return False if isinstance(expected, ZeroDivisionError): return True + if isinstance(expected, AssertionError) and not isinstance(actual, AssertionError): + return True return not check_message or str(actual) == str(expected) diff --git a/tests/oracle/implementations.py b/tests/oracle/implementations.py index 66e90e82..2d6810d3 100644 --- a/tests/oracle/implementations.py +++ b/tests/oracle/implementations.py @@ -4,12 +4,18 @@ ``IMPLEMENTATIONS`` maps a name to a namespace with one attribute per tsdate module (``hypergeo``, ``approx``, ``variational``, ``rescaling``, ``phasing``, ``util``, ``prior``, ``discrete``), exposing the jitted functions under the same names and -signatures as the oracle modules. To add the C extension, add an entry here; to -drop numba, delete the "numba" entry. +signatures as the oracle modules. To drop numba, delete the "numba" entry. + +The "c" entry exists if the ``_tsdate`` extension can be imported. Its namespaces +have the attributes of the functions that have been ported (as thin adapters where the +oracle's signature or return type differs from the module's); other names skip the test +that uses them. """ import types +import pytest + import tsdate.approx import tsdate.hypergeo import tsdate.phasing @@ -70,6 +76,51 @@ def _numba_namespace(): ) +class _PortedNamespace(types.SimpleNamespace): + """ + A namespace of the functions ported to C: using a name that has not been ported yet + skips the test. Add ported functions as attributes in `_c_namespace`. + """ + + def __getattr__(self, name): + if name.startswith("__"): + raise AttributeError(name) + pytest.skip("not yet ported to C") + + +def _c_hypergeo(_tsdate): + return _PortedNamespace( + _digamma=_tsdate.digamma, + _trigamma=_tsdate.trigamma, + _betaln=_tsdate.betaln, + _gammainc_der=_tsdate.gammainc_der, + _gammainc_inv=_tsdate.gammainc_inv, + _hyperu_laplace=_tsdate.hyperu_laplace, + _hyp1f1_laplace=_tsdate.hyp1f1_laplace, + _hyp2f1_laplace=_tsdate.hyp2f1_laplace, + ) + + +def _c_namespace(): + import _tsdate + + return types.SimpleNamespace( + hypergeo=_c_hypergeo(_tsdate), + approx=_PortedNamespace(), + variational=_PortedNamespace(), + rescaling=_PortedNamespace(), + phasing=_PortedNamespace(), + util=_PortedNamespace(), + prior=_PortedNamespace(), + discrete=_PortedNamespace(), + ) + + IMPLEMENTATIONS: dict[str, types.SimpleNamespace] = { "numba": _numba_namespace(), } + +try: + IMPLEMENTATIONS["c"] = _c_namespace() +except ImportError: # the extension has not been built + pass diff --git a/tests/test_oracle_helpers.py b/tests/test_oracle_helpers.py index b3d5270e..aa6ff0ac 100644 --- a/tests/test_oracle_helpers.py +++ b/tests/test_oracle_helpers.py @@ -1,5 +1,6 @@ """Tests of the comparison helpers in ``tests/oracle/helpers.py``.""" +import _tsdate import numpy as np import pytest from oracle.helpers import ( @@ -160,6 +161,60 @@ def test_expected_error(self): assert ValueError in expected_error(ValueError) +KLFailed = type("KLMinimizationFailedError", (Exception,), {}) + + +class TestLibraryError: + """ + The C library reports numba's ZeroDivisionError, AssertionError, + KLMinimizationFailedError and ValueError as ``_tsdate.LibraryError``; messages are + compared only for the last two. + """ + + @pytest.mark.parametrize( + "exc_type", [ZeroDivisionError, AssertionError, ValueError, KLFailed] + ) + def test_expected_error_includes_library_error(self, exc_type): + assert exc_type in expected_error(exc_type) + assert _tsdate.LibraryError in expected_error(exc_type) + + def test_expected_error_other_types(self): + assert expected_error(KeyError) == (KeyError,) + + def test_assertion_error_accepts_shape_check_value_error(self): + assert ValueError in expected_error(AssertionError) + assert ValueError not in expected_error(ZeroDivisionError) + + @pytest.mark.parametrize( + "oracle_exc", + [ZeroDivisionError("float division by zero"), AssertionError("Root")], + ) + def test_messages_ignored(self, oracle_exc): + assert errors_match(_tsdate.LibraryError("other message"), oracle_exc) + + def test_assertion_error_matches_shape_check_value_error(self): + assert errors_match(ValueError("bad shape"), AssertionError()) + + @pytest.mark.parametrize("oracle_type", [ValueError, KLFailed]) + def test_messages_compared(self, oracle_type): + assert errors_match(_tsdate.LibraryError("a"), oracle_type("a")) + assert not errors_match(_tsdate.LibraryError("b"), oracle_type("a")) + assert errors_match( + _tsdate.LibraryError("b"), oracle_type("a"), check_message=False + ) + + @pytest.mark.parametrize("oracle_exc", [KeyError("a"), IndexError("a")], ids=type) + def test_other_oracle_errors_rejected(self, oracle_exc): + assert not errors_match(_tsdate.LibraryError("a"), oracle_exc) + + def test_value_error_rejected_for_zero_division(self): + assert not errors_match(ValueError("a"), ZeroDivisionError("a")) + + def test_assertion_error_still_compared_with_assertion_error(self): + assert errors_match(AssertionError("a"), AssertionError("a")) + assert not errors_match(AssertionError("b"), AssertionError("a")) + + def returns(value, modify=None): def func(x): if modify is not None: diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index 8f8aa9c5..03592495 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -248,9 +248,10 @@ def gammainc_inv_grid(): class TestGammaincInv: """ - `_gammainc_inv` wraps SciPy's ``gammaincinv`` (cephes ``igami``): the port has to - reproduce it to 4 ulp, including away from the interior of the domain (the - result is a NaN, 0 or inf for invalid shapes and quantiles, with no exception). + `_gammainc_inv` is SciPy's ``gammaincinv`` (cephes ``igami``), which every + implementation calls; checked to 4 ulp, including away from the interior of the + domain (the result is a NaN, 0 or inf for invalid shapes and quantiles, with no + exception). """ @pytest.mark.parametrize(("a", "q"), gammainc_inv_grid(), ids=repr) diff --git a/tests/test_python_c_scalar.py b/tests/test_python_c_scalar.py new file mode 100644 index 00000000..93f72038 --- /dev/null +++ b/tests/test_python_c_scalar.py @@ -0,0 +1,159 @@ +""" +Tests of the generic scalar-function wrapper of the low-level _tsdate module: argument +handling, return types, and the mapping of library errors to exceptions. Numerical +values are tested against the oracles in test_oracle_*.py. +""" + +import math +import subprocess +import sys + +import _tsdate +import numpy as np +import pytest +import scipy.special + +SCALAR_FUNCTIONS = { + # name: (number of arguments, number of results, valid arguments) + "digamma": (1, 1, (1.5,)), + "trigamma": (1, 1, (1.5,)), + "betaln": (2, 1, (2.0, 3.0)), + "gammainc_der": (2, 1, (2.0, 1.5)), + "gammainc_inv": (2, 1, (2.0, 0.3)), + "hyperu_laplace": (3, 2, (1.0, 2.0, 1.0)), + "hyp1f1_laplace": (3, 1, (1.0, 2.0, 1.0)), + "hyp2f1_laplace": (4, 1, (1.0, 2.0, 3.0, 0.5)), +} + + +class TestScalarFunctions: + @pytest.mark.parametrize("name", SCALAR_FUNCTIONS) + def test_result_type(self, name): + _, num_results, args = SCALAR_FUNCTIONS[name] + result = getattr(_tsdate, name)(*args) + if num_results == 1: + assert isinstance(result, float) + else: + assert isinstance(result, tuple) + assert len(result) == num_results + assert all(isinstance(x, float) for x in result) + + def test_integers_accepted(self): + assert _tsdate.betaln(2, 3) == _tsdate.betaln(2.0, 3.0) + + @pytest.mark.parametrize("name", SCALAR_FUNCTIONS) + def test_wrong_number_of_arguments(self, name): + num_args, _, args = SCALAR_FUNCTIONS[name] + func = getattr(_tsdate, name) + with pytest.raises(TypeError, match=f"{name}.*{num_args} arguments"): + func() + with pytest.raises(TypeError, match=f"{name}.*{num_args} arguments"): + func(*args, 1.0) + + @pytest.mark.parametrize("name", SCALAR_FUNCTIONS) + def test_non_numeric_argument(self, name): + _, _, args = SCALAR_FUNCTIONS[name] + func = getattr(_tsdate, name) + with pytest.raises(TypeError): + func("x", *args[1:]) + with pytest.raises(TypeError): + func(*args[:-1], None) + + @pytest.mark.parametrize("name", SCALAR_FUNCTIONS) + def test_keyword_arguments_rejected(self, name): + _, _, args = SCALAR_FUNCTIONS[name] + with pytest.raises(TypeError): + getattr(_tsdate, name)(*args[:-1], x=args[-1]) + + +class TestScalarErrors: + def test_zero_division(self): + with pytest.raises(_tsdate.LibraryError, match="division by zero"): + _tsdate.digamma(0.0) + + def test_invalid_hypergeo(self): + with pytest.raises(_tsdate.LibraryError, match="domain of the hypergeometric"): + _tsdate.hyp2f1_laplace(1.0, 2.0, 3.0, 1.0) + + def test_messages_match_strerror(self): + with pytest.raises(_tsdate.LibraryError) as exc_info: + _tsdate.gammainc_der(-1.0, 1.0) + assert str(exc_info.value) == _tsdate.strerror(-5) + + def test_nan_is_not_an_error(self): + assert math.isnan(_tsdate.gammainc_inv(math.nan, 0.5)) + + +def gammainc_inv_grid(): + inf, nan = math.inf, math.nan + shapes = [nan, -inf, -1e300, -1e5 - 0.5, -100.5, -40.7, -40.0, -35.7, -35.0, -34.5] + shapes += [-33.5, -1.5, -1.0, -0.5, -1e-10, 3e305] + shapes += [-0.0, 0.0, 5e-324, 1e-300, 1e-100, 1e-10, 1e-3, 0.01, 0.1, 0.2, 0.25] + shapes += [0.3, 0.5, 0.9, 1.0, 1.1, 2.0, 5.0, 10.0, 20.0, 21.0, 50.0, 150.0] + shapes += [ + 25.0, + 30.0, + 40.0, + 60.0, + 100.0, + 170.0, + 171.7, + 199.0, + 200.0, + 201.0, + 500.0, + 1e3, + 1e4, + 1e5, + 1e6, + 1e8, + ] + shapes += [1e10, 1e15, 1e300, inf] + quantiles = [nan, -inf, -0.1, -0.0, 0.0, 5e-324, 1e-300, 1e-100, 1e-20, 1e-10] + quantiles += [1e-5, 1e-3, 0.01, 0.1, 0.3, 0.5, 0.7, 0.9, np.nextafter(0.9, 1)] + quantiles += [0.95, 0.99, 1 - 1e-10, np.nextafter(1.0, 0), 1.0] + quantiles += [np.nextafter(1.0, 2), 1.1, inf] + return [(a, q) for a in shapes for q in quantiles] + + +def assert_identical(actual, expected): + """Equal values (including the sign of zero), or both NaN""" + both_nan = np.isnan(actual) & np.isnan(expected) + same = (actual == expected) & (np.signbit(actual) == np.signbit(expected)) + assert np.all(both_nan | same) + + +class TestGammaincInv: + """ + ``gammainc_inv`` calls SciPy's ``gammaincinv`` through its Cython C API, so it is + identical to ``scipy.special.gammaincinv``, including outside the domain. + """ + + def test_grid(self): + a, q = np.array(gammainc_inv_grid()).T + actual = np.array([_tsdate.gammainc_inv(*x) for x in zip(a, q)]) + assert_identical(actual, scipy.special.gammaincinv(a, q)) + + @pytest.mark.parametrize("seed", [1, 2]) + def test_random_draws(self, seed): + rng = np.random.default_rng(seed) + a = 10 ** rng.uniform(-6, 6, 5000) + q = np.where( + rng.random(5000) < 0.5, rng.random(5000), 10 ** rng.uniform(-12, 0, 5000) + ) + actual = np.array([_tsdate.gammainc_inv(*x) for x in zip(a, q)]) + assert_identical(actual, scipy.special.gammaincinv(a, q)) + + +class TestScipyDependency: + def test_import_fails_without_scipy_cython_api(self): + code = ( + "import sys; sys.modules['scipy.special.cython_special'] = None\n" + "import _tsdate" + ) + result = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True + ) + assert result.returncode != 0 + assert "ImportError" in result.stderr + assert "cython_special" in result.stderr From 2dea8b09c68218c63fc21270eb561aaa469a4e91 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Mon, 23 Nov 2026 13:52:59 -0800 Subject: [PATCH 07/56] Port tsdate.approx to C Add lib/approx.c, following the numba operation order and libm calls, with every function registered in the module's scalar table and in the "c" test implementation, agreeing with the oracles to within 4 ulp: - the helpers: approximate_log_moments, approximate_gamma_kl, approximate_gamma_mom, approximate_gamma_iqr (the gammaincinv it needs is passed in as a tsd_gammaincinv_fn), average_gammas (an array-level function) and the _valid_* predicates; - the node moments (moments, rootward, leafward, unphased, twin, sideways) and their projections; - the mutation moments (incl. edge and block) and their projections. lib/tsdate.h documents the signature convention: natural parameters in, outputs through pointers written on success, int return. Moments return NaN in every output when the parameters are outside the valid region of the hypergeometric functions (in-band, as in numba). Projections then return a NaN normalising constant and their input parameters unchanged (node projections), or NaN probability and parameters (mutation projections). Errors: every KLMinimizationFailedError message becomes an error code whose tsd_strerror text is the numba message verbatim (nonpositive or nonfinite moments, Jensen's inequality, maximum iterations in KL minimization, invalid shape, nonpositive central moments, unsorted quantiles, maximum iterations in quantile matching, negative shape). The asserts of approximate_log_moments become TSD_ERR_NONPOSITIVE_MOMENTS, and those on the age of a fixed node TSD_ERR_INVALID_FIXED_AGE. Divisions by zero that numba raises on and the tests reach (mean ** 2 underflowing, a zero shape bound, an empty or zero-rate average, zero quantiles, a vanishing quantile gradient, r or r ** 2 zero in the twin moments) return TSD_ERR_ZERO_DIVISION; divisions that only vanish in regimes no test reaches follow IEEE semantics. Errors of the hypergeometric functions propagate. Tests: the C parametrisations of the approx oracle tests; error messages, argument checking of average_gammas, and failures of the quantile fit that the oracle tests do not reach; CUnit smoke and error-path tests. --- _tsdatemodule.c | 343 ++++++++ lib/approx.c | 1361 +++++++++++++++++++++++++++++++ lib/err.c | 30 + lib/err.h | 13 + lib/meson.build | 2 +- lib/tests/tests.c | 397 ++++++++- lib/tsdate.h | 114 +++ setup.py | 2 +- tests/oracle/implementations.py | 77 +- tests/test_python_c_approx.py | 123 +++ 10 files changed, 2458 insertions(+), 4 deletions(-) create mode 100644 lib/approx.c create mode 100644 tests/test_python_c_approx.py diff --git a/_tsdatemodule.c b/_tsdatemodule.c index df5a5b12..b0f5f03b 100644 --- a/_tsdatemodule.c +++ b/_tsdatemodule.c @@ -157,6 +157,256 @@ adapt_hyp2f1_laplace(const double *in, double *out) return tsd_hyp2f1_laplace(in[0], in[1], in[2], in[3], out); } +/* approx: helpers */ + +static int +adapt_approximate_log_moments(const double *in, double *out) +{ + return tsd_approximate_log_moments(in[0], in[1], out, out + 1, out + 2); +} + +static int +adapt_approximate_gamma_kl(const double *in, double *out) +{ + return tsd_approximate_gamma_kl(in[0], in[1], out); +} + +static int +adapt_approximate_gamma_mom(const double *in, double *out) +{ + return tsd_approximate_gamma_mom(in[0], in[1], out); +} + +static int +adapt_approximate_gamma_iqr(const double *in, double *out) +{ + return tsd_approximate_gamma_iqr( + in[0], in[1], in[2], in[3], in[4], gammaincinv, out); +} + +static int +adapt_valid_moments(const double *in, double *out) +{ + out[0] = tsd_valid_moments(in[0], in[1]); + return 0; +} + +static int +adapt_valid_gamma(const double *in, double *out) +{ + out[0] = tsd_valid_gamma(in[0], in[1]); + return 0; +} + +static int +adapt_valid_hyp1f1(const double *in, double *out) +{ + out[0] = tsd_valid_hyp1f1(in[0], in[1], in[2]); + return 0; +} + +static int +adapt_valid_hyperu(const double *in, double *out) +{ + out[0] = tsd_valid_hyperu(in[0], in[1], in[2]); + return 0; +} + +static int +adapt_valid_hyp2f1(const double *in, double *out) +{ + out[0] = tsd_valid_hyp2f1(in[0], in[1], in[2], in[3]); + return 0; +} + +/* + * Adapters of the moment and projection functions. Inputs are flat: ages and shape/rate + * scalars, then the natural parameters `pars_i`, `pars_j`, `pars_ij` (two each) as + * consecutive doubles. Outputs are flat: `logl` or `pr_m`, then the pairs `proj_i`, + * `proj_j` or `proj_m`. + */ + +/* approx: node moments */ +static int +adapt_moments(const double *in, double *out) +{ + return tsd_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, out + 2, + out + 3, out + 4); +} + +static int +adapt_rootward_moments(const double *in, double *out) +{ + return tsd_rootward_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); +} + +static int +adapt_leafward_moments(const double *in, double *out) +{ + return tsd_leafward_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); +} + +static int +adapt_unphased_moments(const double *in, double *out) +{ + return tsd_unphased_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, + out + 2, out + 3, out + 4); +} + +static int +adapt_twin_moments(const double *in, double *out) +{ + return tsd_twin_moments(in[0], in[1], in[2], in[3], out, out + 1, out + 2); +} + +static int +adapt_sideways_moments(const double *in, double *out) +{ + return tsd_sideways_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); +} + +/* approx: node projections */ +static int +adapt_gamma_projection(const double *in, double *out) +{ + return tsd_gamma_projection(in, in + 2, in + 4, out, out + 1, out + 3); +} + +static int +adapt_leafward_projection(const double *in, double *out) +{ + return tsd_leafward_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +adapt_rootward_projection(const double *in, double *out) +{ + return tsd_rootward_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +adapt_unphased_projection(const double *in, double *out) +{ + return tsd_unphased_projection(in, in + 2, in + 4, out, out + 1, out + 3); +} + +static int +adapt_twin_projection(const double *in, double *out) +{ + return tsd_twin_projection(in, in + 2, out, out + 1); +} + +static int +adapt_sideways_projection(const double *in, double *out) +{ + return tsd_sideways_projection(in[0], in + 1, in + 3, out, out + 1); +} + +/* approx: mutation moments */ +static int +adapt_mutation_moments(const double *in, double *out) +{ + return tsd_mutation_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1); +} + +static int +adapt_mutation_rootward_moments(const double *in, double *out) +{ + return tsd_mutation_rootward_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1); +} + +static int +adapt_mutation_leafward_moments(const double *in, double *out) +{ + return tsd_mutation_leafward_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1); +} + +static int +adapt_mutation_unphased_moments(const double *in, double *out) +{ + return tsd_mutation_unphased_moments( + in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, out + 2); +} + +static int +adapt_mutation_twin_moments(const double *in, double *out) +{ + return tsd_mutation_twin_moments(in[0], in[1], in[2], in[3], out, out + 1, out + 2); +} + +static int +adapt_mutation_sideways_moments(const double *in, double *out) +{ + return tsd_mutation_sideways_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); +} + +static int +adapt_mutation_edge_moments(const double *in, double *out) +{ + return tsd_mutation_edge_moments(in[0], in[1], out, out + 1); +} + +static int +adapt_mutation_block_moments(const double *in, double *out) +{ + return tsd_mutation_block_moments(in[0], in[1], out, out + 1, out + 2); +} + +/* approx: mutation projections */ +static int +adapt_mutation_gamma_projection(const double *in, double *out) +{ + return tsd_mutation_gamma_projection(in, in + 2, in + 4, out, out + 1); +} + +static int +adapt_mutation_leafward_projection(const double *in, double *out) +{ + return tsd_mutation_leafward_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +adapt_mutation_rootward_projection(const double *in, double *out) +{ + return tsd_mutation_rootward_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +adapt_mutation_edge_projection(const double *in, double *out) +{ + return tsd_mutation_edge_projection(in[0], in[1], out, out + 1); +} + +static int +adapt_mutation_unphased_projection(const double *in, double *out) +{ + return tsd_mutation_unphased_projection(in, in + 2, in + 4, out, out + 1); +} + +static int +adapt_mutation_twin_projection(const double *in, double *out) +{ + return tsd_mutation_twin_projection(in, in + 2, out, out + 1); +} + +static int +adapt_mutation_sideways_projection(const double *in, double *out) +{ + return tsd_mutation_sideways_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +adapt_mutation_block_projection(const double *in, double *out) +{ + return tsd_mutation_block_projection(in[0], in[1], out, out + 1); +} + /* clang-format off */ static const scalar_function_t scalar_functions[] = { /* hypergeo */ @@ -168,6 +418,48 @@ static const scalar_function_t scalar_functions[] = { { "hyperu_laplace", 3, 2, adapt_hyperu_laplace }, { "hyp1f1_laplace", 3, 1, adapt_hyp1f1_laplace }, { "hyp2f1_laplace", 4, 1, adapt_hyp2f1_laplace }, + /* approx: helpers */ + { "approximate_log_moments", 2, 3, adapt_approximate_log_moments }, + { "approximate_gamma_kl", 2, 2, adapt_approximate_gamma_kl }, + { "approximate_gamma_mom", 2, 2, adapt_approximate_gamma_mom }, + { "approximate_gamma_iqr", 5, 2, adapt_approximate_gamma_iqr }, + { "valid_moments", 2, 1, adapt_valid_moments }, + { "valid_gamma", 2, 1, adapt_valid_gamma }, + { "valid_hyp1f1", 3, 1, adapt_valid_hyp1f1 }, + { "valid_hyperu", 3, 1, adapt_valid_hyperu }, + { "valid_hyp2f1", 4, 1, adapt_valid_hyp2f1 }, + /* approx: node moments */ + { "moments", 6, 5, adapt_moments }, + { "rootward_moments", 5, 3, adapt_rootward_moments }, + { "leafward_moments", 5, 3, adapt_leafward_moments }, + { "unphased_moments", 6, 5, adapt_unphased_moments }, + { "twin_moments", 4, 3, adapt_twin_moments }, + { "sideways_moments", 5, 3, adapt_sideways_moments }, + /* approx: node projections */ + { "gamma_projection", 6, 5, adapt_gamma_projection }, + { "leafward_projection", 5, 3, adapt_leafward_projection }, + { "rootward_projection", 5, 3, adapt_rootward_projection }, + { "unphased_projection", 6, 5, adapt_unphased_projection }, + { "twin_projection", 4, 3, adapt_twin_projection }, + { "sideways_projection", 5, 3, adapt_sideways_projection }, + /* approx: mutation moments */ + { "mutation_moments", 6, 2, adapt_mutation_moments }, + { "mutation_rootward_moments", 5, 2, adapt_mutation_rootward_moments }, + { "mutation_leafward_moments", 5, 2, adapt_mutation_leafward_moments }, + { "mutation_unphased_moments", 6, 3, adapt_mutation_unphased_moments }, + { "mutation_twin_moments", 4, 3, adapt_mutation_twin_moments }, + { "mutation_sideways_moments", 5, 3, adapt_mutation_sideways_moments }, + { "mutation_edge_moments", 2, 2, adapt_mutation_edge_moments }, + { "mutation_block_moments", 2, 3, adapt_mutation_block_moments }, + /* approx: mutation projections */ + { "mutation_gamma_projection", 6, 3, adapt_mutation_gamma_projection }, + { "mutation_leafward_projection", 5, 3, adapt_mutation_leafward_projection }, + { "mutation_rootward_projection", 5, 3, adapt_mutation_rootward_projection }, + { "mutation_edge_projection", 2, 3, adapt_mutation_edge_projection }, + { "mutation_unphased_projection", 6, 3, adapt_mutation_unphased_projection }, + { "mutation_twin_projection", 4, 3, adapt_mutation_twin_projection }, + { "mutation_sideways_projection", 5, 3, adapt_mutation_sideways_projection }, + { "mutation_block_projection", 2, 3, adapt_mutation_block_projection }, }; /* clang-format on */ @@ -291,11 +583,62 @@ add_scalar_functions(PyObject *module) return ret; } +/* average_gammas(alpha, beta): natural parameters of the averaged gamma. */ +static PyObject * +tsdate_average_gammas(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *alpha_obj = NULL; + PyObject *beta_obj = NULL; + PyArrayObject *alpha_array = NULL; + PyArrayObject *beta_array = NULL; + double out[2]; + npy_intp num_alpha, num_beta; + int err; + + if (!PyArg_ParseTuple(args, "OO", &alpha_obj, &beta_obj)) { + goto out; + } + alpha_array = (PyArrayObject *) PyArray_FROMANY( + alpha_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (alpha_array == NULL) { + goto out; + } + beta_array = (PyArrayObject *) PyArray_FROMANY( + beta_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (beta_array == NULL) { + goto out; + } + num_alpha = PyArray_DIM(alpha_array, 0); + num_beta = PyArray_DIM(beta_array, 0); + if (num_alpha != num_beta) { + PyErr_SetString(PyExc_ValueError, "Array sizes are not equal"); + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_average_gammas((tsd_size_t) num_alpha, + (const double *) PyArray_DATA(alpha_array), + (const double *) PyArray_DATA(beta_array), out); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = Py_BuildValue("dd", out[0], out[1]); +out: + Py_XDECREF(alpha_array); + Py_XDECREF(beta_array); + return ret; +} + static PyMethodDef tsdate_methods[] = { { "strerror", (PyCFunction) tsdate_strerror, METH_VARARGS, "Return the message for a library error code." }, { "raise_library_error", (PyCFunction) tsdate_raise_library_error, METH_VARARGS, "Raise the Python exception corresponding to a library error code." }, + { "average_gammas", (PyCFunction) tsdate_average_gammas, METH_VARARGS, + "Natural parameters of the gamma averaging the sufficient statistics of an " + "array of gammas, given as natural parameters." }, { NULL } /* Sentinel */ }; diff --git a/lib/approx.c b/lib/approx.c new file mode 100644 index 00000000..5b31ab08 --- /dev/null +++ b/lib/approx.c @@ -0,0 +1,1361 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* + * Gamma approximations and the moments of the EP updates, ported from + * tsdate/approx.py (numba). Operation order and libm calls follow the numba code so + * that results agree to the last bit or two. + * + * In numba, a float division by zero raises ZeroDivisionError; here it returns + * TSD_ERR_ZERO_DIVISION, but only at the divisions that the tests show to be + * reachable. The other divisions follow IEEE semantics (infinity or NaN). + */ + +#include + +#include "mathutil.h" +#include "tsdate.h" + +/* The convergence tolerance of the Newton iterations: sqrt(DBL_EPSILON), exactly. */ +#define KLMIN_RELTOL 1.4901161193847656e-08 +#define KLMIN_MAXITT 100 + +/* ------------------------------------------------------------------------- * + * Helpers: gamma approximations and validity checks + * ------------------------------------------------------------------------- */ + +/* + * Approximate log moments via a second-order Taylor series expansion around the mean: + * E[f(x)] ~ f(mean) + variance * f''(mean) / 2. Returns E[log x], E[x log x] and + * E[(log x)^2]. + */ +int +tsd_approximate_log_moments( + double mean, double variance, double *logx, double *xlogx, double *logx2) +{ + int ret = 0; + double log_mean, mean_sq; + + if (!(mean > 0.0) || !(variance > 0.0)) { + ret = tsd_trace_error(TSD_ERR_NONPOSITIVE_MOMENTS); + goto out; + } + log_mean = log(mean); + mean_sq = tsd_ipow(mean, 2); + if (mean_sq == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + *logx = log_mean - 0.5 * variance / mean_sq; + *xlogx = mean * log_mean + 0.5 * variance / mean; + *logx2 = tsd_ipow(log_mean, 2) + (1 - log_mean) * variance / mean_sq; +out: + return ret; +} + +/* + * Newton root finding for the gamma natural parameters matching E[x] and E[log x], + * minimising KL divergence. The initial condition uses the upper bound + * digamma(x) <= log(x) - 1/2x. + */ +int +tsd_approximate_gamma_kl(double x, double logx, double out[2]) +{ + int ret = 0; + int itt = 0; + double log_x, alpha, delta, dg, tg, denom; + + if (x <= 0.0 || isinf(logx)) { + ret = tsd_trace_error(TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS); + goto out; + } + log_x = log(x); + if (!(log_x > logx)) { + ret = tsd_trace_error(TSD_ERR_JENSEN_VIOLATION); + goto out; + } + alpha = 0.5 / (log_x - logx); /* lower bound on alpha */ + if (alpha == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + /* asymptotically the lower bound becomes sharp */ + if (1.0 / alpha < 1e-4) { + out[0] = alpha - 1.0; + out[1] = alpha / x; + goto out; + } + /* converged when the change in alpha falls below the square root of machine + * precision */ + delta = INFINITY; + while (fabs(delta) > fabs(alpha) * KLMIN_RELTOL) { + if (itt > KLMIN_MAXITT) { + ret = tsd_trace_error(TSD_ERR_KL_MAX_ITERATIONS); + goto out; + } + ret = tsd_digamma(alpha, &dg); + if (ret != 0) { + goto out; + } + delta = dg - log(alpha) + log_x - logx; + ret = tsd_trigamma(alpha, &tg); + if (ret != 0) { + goto out; + } + /* alpha is not zero (the polygamma functions would have failed) */ + denom = tg - 1 / alpha; + delta /= denom; + alpha -= delta; + itt++; + } + if (!isfinite(alpha) || alpha <= 0) { + ret = tsd_trace_error(TSD_ERR_KL_INVALID_SHAPE); + goto out; + } + out[0] = alpha - 1.0; + out[1] = alpha / x; +out: + return ret; +} + +/* + * The method of moments: natural parameters of the gamma with the given mean and + * variance. + */ +int +tsd_approximate_gamma_mom(double mean, double variance, double out[2]) +{ + int ret = 0; + double shape, rate; + + if (!(mean > 0.0 && variance > 0.0)) { + ret = tsd_trace_error(TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS); + goto out; + } + shape = tsd_ipow(mean, 2) / variance; + rate = mean / variance; + out[0] = shape - 1.0; + out[1] = rate; +out: + return ret; +} + +/* The gamma with shape `max_shape` whose q-quantile is x. */ +static int +gamma_iqr_upper_bound( + double q, double x, double max_shape, tsd_gammaincinv_fn gammaincinv, double out[2]) +{ + int ret = 0; + + if (x == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + out[0] = max_shape - 1; + out[1] = gammaincinv(max_shape, q) / x; +out: + return ret; +} + +/* + * One Newton step on the shape of a gamma whose quantiles are in the given ratio. + * Updates alpha and writes the step to delta. + */ +static int +gamma_iqr_newton_step(double q1, double q2, double x1, double x2, + tsd_gammaincinv_fn gammaincinv, double *alpha, double *delta) +{ + int ret = 0; + double y1, y2, obj, inv_1, inv_2, der_1, der_2, gra_1, gra_2, y1_sq, gra; + + y1 = gammaincinv(*alpha, q1); + y2 = gammaincinv(*alpha, q2); + if (y1 == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + obj = y2 / y1 - x2 / x1; + inv_1 = -exp(y1 + log(y1) * (1 - *alpha) + lgamma(*alpha)); + inv_2 = -exp(y2 + log(y2) * (1 - *alpha) + lgamma(*alpha)); + ret = tsd_gammainc_der(*alpha, y1, &der_1); + if (ret != 0) { + goto out; + } + gra_1 = der_1 * inv_1; + ret = tsd_gammainc_der(*alpha, y2, &der_2); + if (ret != 0) { + goto out; + } + gra_2 = der_2 * inv_2; + y1_sq = tsd_ipow(y1, 2); + if (y1_sq == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + gra = (gra_2 * y1 - gra_1 * y2) / y1_sq; + if (gra == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + *delta = -obj / gra; + *alpha += *delta; +out: + return ret; +} + +/* + * Natural parameters of a gamma matching two quantiles: q1, q2 are probabilities and + * x1, x2 the corresponding quantiles. The shape is capped at max_shape. + */ +int +tsd_approximate_gamma_iqr(double q1, double q2, double x1, double x2, double max_shape, + tsd_gammaincinv_fn gammaincinv, double out[2]) +{ + int ret = 0; + int itt = 0; + double alpha, delta, ratio_q, ratio_x; + + if (x2 == x1) { + ret = gamma_iqr_upper_bound(q1, x1, max_shape, gammaincinv, out); + goto out; + } + if (!(q2 > q1 && x2 > x1)) { + ret = tsd_trace_error(TSD_ERR_UNSORTED_QUANTILES); + goto out; + } + if (q1 == 0.0 || x1 == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + ratio_q = q2 / q1; + ratio_x = x2 / x1; + alpha = log(ratio_q) / log(ratio_x); /* lower bound */ + if (alpha > max_shape) { + ret = gamma_iqr_upper_bound(q1, x1, max_shape, gammaincinv, out); + goto out; + } + /* refine with Newton iteration */ + delta = INFINITY; + while (fabs(delta) > fabs(alpha) * KLMIN_RELTOL) { + if (itt > KLMIN_MAXITT) { + ret = tsd_trace_error(TSD_ERR_QUANTILE_MAX_ITERATIONS); + goto out; + } + ret = gamma_iqr_newton_step(q1, q2, x1, x2, gammaincinv, &alpha, &delta); + if (ret != 0) { + goto out; + } + itt++; + } + if (!(alpha > 0)) { + ret = tsd_trace_error(TSD_ERR_NEGATIVE_SHAPE); + goto out; + } + if (alpha > max_shape) { + ret = gamma_iqr_upper_bound(q1, x1, max_shape, gammaincinv, out); + goto out; + } + out[0] = alpha - 1; + out[1] = gammaincinv(alpha, q1) / x1; +out: + return ret; +} + +int +tsd_average_gammas( + tsd_size_t num_gammas, const double *alpha, const double *beta, double out[2]) +{ + int ret = 0; + tsd_size_t j; + double shape, rate, dg; + double avg_x = 0.0; + double avg_logx = 0.0; + + if (num_gammas == 0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + for (j = 0; j < num_gammas; j++) { + shape = alpha[j] + 1.0; + rate = beta[j]; + ret = tsd_digamma(shape, &dg); + if (ret != 0) { + goto out; + } + avg_logx += dg - log(rate); + if (rate == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + avg_x += shape / rate; + } + avg_x /= (double) num_gammas; + avg_logx /= (double) num_gammas; + ret = tsd_approximate_gamma_kl(avg_x, avg_logx, out); +out: + return ret; +} + +int +tsd_valid_moments(double mn, double va) +{ + if (!(isfinite(mn) && isfinite(va))) { + return 0; + } + if (!(mn > 0.0 && va > 0.0)) { + return 0; + } + return 1; +} + +int +tsd_valid_gamma(double s, double r) +{ + if (!(isfinite(s) && isfinite(r))) { + return 0; + } + if (s <= 0.0 || r <= 0.0) { + return 0; + } + return 1; +} + +int +tsd_valid_hyp1f1(double a, double b, double z) +{ + if (!(isfinite(a) && isfinite(b) && isfinite(z))) { + return 0; + } + if (!(b >= a && a > 0.0)) { + return 0; + } + return 1; +} + +int +tsd_valid_hyperu(double a, double b, double z) +{ + if (!(isfinite(a) && isfinite(b) && isfinite(z))) { + return 0; + } + if (z <= 0.0) { + return 0; + } + if (!(b > a && a > 0.0)) { + return 0; + } + return 1; +} + +int +tsd_valid_hyp2f1(double a, double b, double c, double z) +{ + if (!(isfinite(a) && isfinite(b) && isfinite(c))) { + return 0; + } + if (!isfinite(z) || z >= 1 || z / (z - 1) >= 1) { + return 0; + } + if (!(a > 0 && b > 0 && c > 0)) { + return 0; + } + return 1; +} + +/* ------------------------------------------------------------------------- * + * Node moments + * ------------------------------------------------------------------------- */ + +/* The moments of an edge between two free nodes are unusable: all NaN. */ +static void +set_nan_two_node(double *logl, double *mn_i, double *va_i, double *mn_j, double *va_j) +{ + *logl = NAN; + *mn_i = NAN; + *va_i = NAN; + *mn_j = NAN; + *va_j = NAN; +} + +static void +set_nan_one_node(double *logl, double *mn, double *va) +{ + *logl = NAN; + *mn = NAN; + *va = NAN; +} + +/* + * log p(t_i, t_j) = log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + * + log(t_i) * (a_i - 1) - b_i * t_i + log(t_j) * (a_j - 1) - b_j * t_j + * Writes the normalising constant, E[t_i], V[t_i], E[t_j], V[t_j]. + */ +int +tsd_moments(double a_i, double b_i, double a_j, double b_j, double y_ij, double mu_ij, + double *logl, double *mn_i, double *va_i, double *mn_j, double *va_j) +{ + int ret = 0; + double a, b, c, t, z, f0, f1, f2, s1, s2, d1, d2; + double sq_i, sq_j, mn_i_, mn_j_, va_i_, va_j_, logl_; + + a = a_j; + b = a_i + a_j + y_ij; + c = a_j + y_ij + 1; + t = mu_ij + b_i; + z = t > 0 ? (mu_ij - b_j) / t : NAN; + + if (!tsd_valid_hyp2f1(a, b, c, z)) { + set_nan_two_node(logl, mn_i, va_i, mn_j, va_j); + goto out; + } + + ret = tsd_hyp2f1_laplace(a, b, c, z, &f0); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 1, b + 1, c + 1, z, &f1); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 2, b + 2, c + 2, z, &f2); + if (ret != 0) { + goto out; + } + s1 = a * b / c; + s2 = s1 * (a + 1) * (b + 1) / (c + 1); + d1 = s1 * exp(f1 - f0); + d2 = s2 * exp(f2 - f0); + + logl_ = f0 + tsd_betaln(y_ij + 1, a) + lgamma(b) - b * log(t); + + mn_j_ = d1 / t; + sq_j = d2 / (t * t); + va_j_ = sq_j - mn_j_ * mn_j_; + + mn_i_ = mn_j_ * z + b / t; + sq_i = sq_j * (z * z) + (b + 1) * (mn_i_ + mn_j_ * z) / t; + va_i_ = sq_i - mn_i_ * mn_i_; + + *logl = logl_; + *mn_i = mn_i_; + *va_i = va_i_; + *mn_j = mn_j_; + *va_j = va_j_; +out: + return ret; +} + +/* + * log p(t_i) = log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + * + log(t_i) * (a_i - 1) - b_i * t_i + * for a fixed child age t_j >= 0. Writes the normalising constant, E[t_i], V[t_i]. + */ +int +tsd_rootward_moments(double t_j, double a_i, double b_i, double y_ij, double mu_ij, + double *logl, double *mn_i, double *va_i) +{ + int ret = 0; + double s, r, a, b, z, f0, d0, f1, d1; + + if (!(t_j >= 0.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_FIXED_AGE); + goto out; + } + + s = a_i + y_ij; + r = mu_ij + b_i; + + if (!tsd_valid_gamma(s, r)) { + set_nan_one_node(logl, mn_i, va_i); + goto out; + } + + if (t_j == 0.0) { + *logl = lgamma(s) - s * log(r); + *mn_i = s / r; + *va_i = s / (r * r); + goto out; + } + + a = y_ij + 1; + b = s + 1; + z = t_j * r; + + if (!tsd_valid_hyperu(a, b, z)) { + set_nan_one_node(logl, mn_i, va_i); + goto out; + } + + ret = tsd_hyperu_laplace(a, b, z, &f0, &d0); + if (ret != 0) { + goto out; + } + ret = tsd_hyperu_laplace(a + 1, b + 1, z, &f1, &d1); + if (ret != 0) { + goto out; + } + + *logl = f0 - b_i * t_j + (b - 1) * log(t_j) + lgamma(a); + *mn_i = t_j * (1 - d0); + *va_i = (t_j * t_j) * d0 * (d1 - d0); +out: + return ret; +} + +/* + * log p(t_j) = log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + * + log(t_j) * (a_j - 1) - b_j * t_j + * for a fixed parent age t_i > 0. Writes the normalising constant, E[t_j], V[t_j]. + */ +int +tsd_leafward_moments(double t_i, double a_j, double b_j, double y_ij, double mu_ij, + double *logl, double *mn_j, double *va_j) +{ + int ret = 0; + double a, b, z, f0, f1, f2, d1, d2, sq_j, mn_j_, logl_; + + if (!(t_i > 0.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_FIXED_AGE); + goto out; + } + + a = a_j; + b = a_j + y_ij + 1; + z = t_i * (mu_ij - b_j); + + if (!tsd_valid_hyp1f1(a, b, z)) { + set_nan_one_node(logl, mn_j, va_j); + goto out; + } + + ret = tsd_hyp1f1_laplace(a, b, z, &f0); + if (ret != 0) { + goto out; + } + ret = tsd_hyp1f1_laplace(a + 1, b + 1, z, &f1); + if (ret != 0) { + goto out; + } + ret = tsd_hyp1f1_laplace(a + 2, b + 2, z, &f2); + if (ret != 0) { + goto out; + } + d1 = a / b * exp(f1 - f0); + d2 = a / b * (a + 1) / (b + 1) * exp(f2 - f0); + + logl_ = f0 - mu_ij * t_i + (b - 1) * log(t_i) + tsd_betaln(a, b - a); + mn_j_ = t_i * d1; + sq_j = (t_i * t_i) * d2; + + *logl = logl_; + *mn_j = mn_j_; + *va_j = sq_j - mn_j_ * mn_j_; +out: + return ret; +} + +/* + * log p(t_i, t_j) = log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + * + log(t_i) * (a_i - 1) - b_i * t_i + log(t_j) * (a_j - 1) - b_j * t_j + * Writes the normalising constant, E[t_i], V[t_i], E[t_j], V[t_j]. + */ +int +tsd_unphased_moments(double a_i, double b_i, double a_j, double b_j, double y_ij, + double mu_ij, double *logl, double *mn_i, double *va_i, double *mn_j, double *va_j) +{ + int ret = 0; + double a, b, c, t, z, f0, f1, f2, s1, s2, d1, d2; + double sq_i, sq_j, mn_i_, mn_j_, va_i_, va_j_, logl_; + + a = a_j; + b = a_i + a_j + y_ij; + c = a_j + a_i; + t = mu_ij + b_i; + z = t > 0 ? (mu_ij + b_j) / t : NAN; + + if (!tsd_valid_hyp2f1(a, b, c, 1 - z)) { + set_nan_two_node(logl, mn_i, va_i, mn_j, va_j); + goto out; + } + + ret = tsd_hyp2f1_laplace(a, b, c, 1 - z, &f0); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 1, b + 1, c + 1, 1 - z, &f1); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 2, b + 2, c + 2, 1 - z, &f2); + if (ret != 0) { + goto out; + } + s1 = a * b / c; + s2 = s1 * (a + 1) * (b + 1) / (c + 1); + d1 = s1 * exp(f1 - f0); + d2 = s2 * exp(f2 - f0); + + logl_ = f0 + tsd_betaln(a_j, a_i) + lgamma(b) - b * log(t); + + mn_j_ = d1 / t; + sq_j = d2 / (t * t); + va_j_ = sq_j - mn_j_ * mn_j_; + + mn_i_ = b / t - mn_j_ * z; + sq_i = sq_j * (z * z) + (b + 1) * (mn_i_ - mn_j_ * z) / t; + va_i_ = sq_i - mn_i_ * mn_i_; + + *logl = logl_; + *mn_i = mn_i_; + *va_i = va_i_; + *mn_j = mn_j_; + *va_j = va_j_; +out: + return ret; +} + +/* + * log p(t_i) = log(2 t_i) * y_ij - mu_ij * (2 t_i) + log(t_i) * (a_i - 1) - b_i * t_i + * for the two edges of an unphased individual to the same parent. Writes the + * normalising constant, E[t_i], V[t_i]. As numba raised ZeroDivisionError for a zero + * rate r (or one whose square underflows), this returns TSD_ERR_ZERO_DIVISION. + */ +int +tsd_twin_moments(double a_i, double b_i, double y_ij, double mu_ij, double *logl, + double *mn_i, double *va_i) +{ + int ret = 0; + double s, r, r_sq; + + s = a_i + y_ij; + r = b_i + 2 * mu_ij; + r_sq = r * r; + if (r == 0.0 || r_sq == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + + *logl = log(2.0) * y_ij + lgamma(s) - log(r) * s; + *mn_i = s / r; + *va_i = s / r_sq; +out: + return ret; +} + +/* + * log p(t_j) = log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + * + log(t_j) * (a_j - 1) - b_j * t_j + * for a fixed age t_i > 0. Writes the normalising constant, E[t_j], V[t_j]. + */ +int +tsd_sideways_moments(double t_i, double a_j, double b_j, double y_ij, double mu_ij, + double *logl, double *mn_j, double *va_j) +{ + int ret = 0; + double a, b, z, f0, d0, f1, d1; + + if (!(t_i > 0.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_FIXED_AGE); + goto out; + } + + a = a_j; + b = a_j + y_ij + 1; + z = t_i * (mu_ij + b_j); + + if (!tsd_valid_hyperu(a, b, z)) { + set_nan_one_node(logl, mn_j, va_j); + goto out; + } + + ret = tsd_hyperu_laplace(a, b, z, &f0, &d0); + if (ret != 0) { + goto out; + } + ret = tsd_hyperu_laplace(a + 1, b + 1, z, &f1, &d1); + if (ret != 0) { + goto out; + } + + *logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + lgamma(a); + *mn_j = -t_i * d0; + *va_j = (t_i * t_i) * d0 * (d1 - d0); +out: + return ret; +} + +/* ------------------------------------------------------------------------- * + * Node projections + * ------------------------------------------------------------------------- */ + +/* + * Project the moments of one marginal onto a gamma, writing its natural parameters to + * `proj`; if the moments are unusable, write a copy of `pars` instead and set + * `*usable` to 0. + */ +static int +project_moments(double mn, double va, const double pars[2], double proj[2], int *usable) +{ + int ret = 0; + + *usable = tsd_valid_moments(mn, va); + if (!*usable) { + proj[0] = pars[0]; + proj[1] = pars[1]; + goto out; + } + ret = tsd_approximate_gamma_mom(mn, va, proj); +out: + return ret; +} + +/* The projection of the two marginals of a two-parameter update; as numba, both are + * checked before either is projected. */ +static int +project_pair(double mn_i, double va_i, double mn_j, double va_j, const double pars_i[2], + const double pars_j[2], double *logl, double logl_value, double proj_i[2], + double proj_j[2]) +{ + int ret = 0; + int valid_i = tsd_valid_moments(mn_i, va_i); + int valid_j = tsd_valid_moments(mn_j, va_j); + + if (!(valid_i && valid_j)) { + *logl = NAN; + proj_i[0] = pars_i[0]; + proj_i[1] = pars_i[1]; + proj_j[0] = pars_j[0]; + proj_j[1] = pars_j[1]; + goto out; + } + ret = tsd_approximate_gamma_mom(mn_i, va_i, proj_i); + if (ret != 0) { + goto out; + } + ret = tsd_approximate_gamma_mom(mn_j, va_j, proj_j); + if (ret != 0) { + goto out; + } + *logl = logl_value; +out: + return ret; +} + +/* Project a single marginal; on unusable moments `*logl` is NaN. */ +static int +project_single(double mn, double va, const double pars[2], double logl_value, + double *logl, double proj[2]) +{ + int ret = 0; + int usable; + + ret = project_moments(mn, va, pars, proj, &usable); + if (ret != 0) { + goto out; + } + *logl = usable ? logl_value : NAN; +out: + return ret; +} + +int +tsd_gamma_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *logl, double proj_i[2], double proj_j[2]) +{ + int ret = 0; + double a_i = pars_i[0] + 1; + double b_i = pars_i[1]; + double a_j = pars_j[0] + 1; + double b_j = pars_j[1]; + double y_ij = pars_ij[0]; + double mu_ij = pars_ij[1]; + double logl_value, mn_i, va_i, mn_j, va_j; + + ret = tsd_moments( + a_i, b_i, a_j, b_j, y_ij, mu_ij, &logl_value, &mn_i, &va_i, &mn_j, &va_j); + if (ret != 0) { + goto out; + } + ret = project_pair( + mn_i, va_i, mn_j, va_j, pars_i, pars_j, logl, logl_value, proj_i, proj_j); +out: + return ret; +} + +int +tsd_leafward_projection(double t_i, const double pars_j[2], const double pars_ij[2], + double *logl, double proj_j[2]) +{ + int ret = 0; + double a_j = pars_j[0] + 1; + double b_j = pars_j[1]; + double y_ij = pars_ij[0]; + double mu_ij = pars_ij[1]; + double logl_value, mn_j, va_j; + + ret = tsd_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij, &logl_value, &mn_j, &va_j); + if (ret != 0) { + goto out; + } + ret = project_single(mn_j, va_j, pars_j, logl_value, logl, proj_j); +out: + return ret; +} + +int +tsd_rootward_projection(double t_j, const double pars_i[2], const double pars_ij[2], + double *logl, double proj_i[2]) +{ + int ret = 0; + double a_i = pars_i[0] + 1; + double b_i = pars_i[1]; + double y_ij = pars_ij[0]; + double mu_ij = pars_ij[1]; + double logl_value, mn_i, va_i; + + ret = tsd_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij, &logl_value, &mn_i, &va_i); + if (ret != 0) { + goto out; + } + ret = project_single(mn_i, va_i, pars_i, logl_value, logl, proj_i); +out: + return ret; +} + +int +tsd_unphased_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *logl, double proj_i[2], double proj_j[2]) +{ + int ret = 0; + double a_i = pars_i[0] + 1; + double b_i = pars_i[1]; + double a_j = pars_j[0] + 1; + double b_j = pars_j[1]; + double y_ij = pars_ij[0]; + double mu_ij = pars_ij[1]; + double logl_value, mn_i, va_i, mn_j, va_j; + + ret = tsd_unphased_moments( + a_i, b_i, a_j, b_j, y_ij, mu_ij, &logl_value, &mn_i, &va_i, &mn_j, &va_j); + if (ret != 0) { + goto out; + } + ret = project_pair( + mn_i, va_i, mn_j, va_j, pars_i, pars_j, logl, logl_value, proj_i, proj_j); +out: + return ret; +} + +int +tsd_twin_projection( + const double pars_i[2], const double pars_ij[2], double *logl, double proj_i[2]) +{ + int ret = 0; + double a_i = pars_i[0] + 1; + double b_i = pars_i[1]; + double y_ij = pars_ij[0]; + double mu_ij = pars_ij[1]; + double logl_value, mn_i, va_i; + + ret = tsd_twin_moments(a_i, b_i, y_ij, mu_ij, &logl_value, &mn_i, &va_i); + if (ret != 0) { + goto out; + } + ret = project_single(mn_i, va_i, pars_i, logl_value, logl, proj_i); +out: + return ret; +} + +int +tsd_sideways_projection(double t_i, const double pars_j[2], const double pars_ij[2], + double *logl, double proj_j[2]) +{ + int ret = 0; + double a_j = pars_j[0] + 1; + double b_j = pars_j[1]; + double y_ij = pars_ij[0]; + double mu_ij = pars_ij[1]; + double logl_value, mn_j, va_j; + + ret = tsd_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij, &logl_value, &mn_j, &va_j); + if (ret != 0) { + goto out; + } + ret = project_single(mn_j, va_j, pars_j, logl_value, logl, proj_j); +out: + return ret; +} + +/* ------------------------------------------------------------------------- * + * Mutation moments + * ------------------------------------------------------------------------- */ + +/* + * Moments of the mutation age t_m. Conditional on the node ages, t_m is uniform on + * (t_j, t_i) for a phased edge; the moments are those of the EP surrogate density + * integrated over the node ages, in terms of hypergeometric functions. A result that + * numba returns as NaN (arguments outside the domain) is NaN here, not an error. + */ +int +tsd_mutation_moments(double a_i, double b_i, double a_j, double b_j, double y_ij, + double mu_ij, double *mn_m, double *va_m) +{ + int ret = 0; + double a, b, c, t, z, s1, d1, d2, d3, sq_m; + double f000, f020, f111, f121, f222; + + a = a_j; + b = a_i + a_j + y_ij; + c = a_j + y_ij + 1; + t = mu_ij + b_i; + z = t > 0 ? (mu_ij - b_j) / t : NAN; + + if (!tsd_valid_hyp2f1(a, b, c, z)) { + *mn_m = NAN; + *va_m = NAN; + goto out; + } + + ret = tsd_hyp2f1_laplace(a + 0, b + 0, c + 0, z, &f000); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 0, b + 2, c + 0, z, &f020); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 1, b + 1, c + 1, z, &f111); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 1, b + 2, c + 1, z, &f121); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 2, b + 2, c + 2, z, &f222); + if (ret != 0) { + goto out; + } + + s1 = a * b / c; + d1 = b * (b + 1) / tsd_ipow(t, 2); + d2 = d1 * a / c; + d3 = d2 * (a + 1) / (c + 1); + + *mn_m = s1 * exp(f111 - f000) / t / 2 * (1 + z) + b / t / 2; + sq_m = d1 * exp(f020 - f000) / 3 + d2 * exp(f121 - f000) / 3 + + d3 * exp(f222 - f000) / 3; + *va_m = sq_m - tsd_ipow(*mn_m, 2); +out: + return ret; +} + +/* Moments of t_m given a fixed child age t_j: uniform on (t_j, t_i). */ +int +tsd_mutation_rootward_moments(double t_j, double a_i, double b_i, double y_ij, + double mu_ij, double *mn_m, double *va_m) +{ + int ret = 0; + double logl, mn_i, va_i, sq_m; + + ret = tsd_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij, &logl, &mn_i, &va_i); + if (ret != 0) { + goto out; + } + *mn_m = mn_i / 2 + t_j / 2; + sq_m = (va_i + tsd_ipow(mn_i, 2) + mn_i * t_j + tsd_ipow(t_j, 2)) / 3; + *va_m = sq_m - tsd_ipow(*mn_m, 2); +out: + return ret; +} + +/* Moments of t_m given a fixed parent age t_i: uniform on (t_j, t_i). */ +int +tsd_mutation_leafward_moments(double t_i, double a_j, double b_j, double y_ij, + double mu_ij, double *mn_m, double *va_m) +{ + int ret = 0; + double logl, mn_j, va_j, sq_m; + + ret = tsd_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij, &logl, &mn_j, &va_j); + if (ret != 0) { + goto out; + } + *mn_m = mn_j / 2 + t_i / 2; + sq_m = (va_j + tsd_ipow(mn_j, 2) + mn_j * t_i + tsd_ipow(t_i, 2)) / 3; + *va_m = sq_m - tsd_ipow(*mn_m, 2); +out: + return ret; +} + +/* + * Unphased edge: the mutation is under node i with probability t_i / (t_i + t_j), and + * uniform on (0, t_i) or (0, t_j). Integrating over the EP surrogate density gives + * hypergeometric functions with integer perturbations of a_i, a_j and y_ij. + */ +int +tsd_mutation_unphased_moments(double a_i, double b_i, double a_j, double b_j, + double y_ij, double mu_ij, double *pr_m, double *mn_m, double *va_m) +{ + int ret = 0; + double a, b, c, t, z, s0, s1, s2, d0, d1, d2, sq_m; + double f000, f001, f012, f023, f212, f323; + + a = a_j; + b = a_j + a_i + y_ij; + c = a_j + a_i; + t = mu_ij + b_i; + z = t > 0 ? (mu_ij + b_j) / t : NAN; + + if (!tsd_valid_hyp2f1(a, b, c, 1 - z)) { + *pr_m = NAN; + *mn_m = NAN; + *va_m = NAN; + goto out; + } + + ret = tsd_hyp2f1_laplace(a + 0, b + 0, c + 0, 1 - z, &f000); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 0, b + 0, c + 1, 1 - z, &f001); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 0, b + 1, c + 2, 1 - z, &f012); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 0, b + 2, c + 3, 1 - z, &f023); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 2, b + 1, c + 2, 1 - z, &f212); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 3, b + 2, c + 3, 1 - z, &f323); + if (ret != 0) { + goto out; + } + + s0 = b / t / c / (c + 1); + s1 = (c - a) * (c - a + 1); + s2 = a * (a + 1); + d0 = s0 * (b + 1) / t / (c + 2); + d1 = s1 * (c - a + 2); + d2 = s2 * (a + 2); + + *mn_m = s0 * s1 * exp(f012 - f000) / 2 + s0 * s2 * exp(f212 - f000) / 2; + sq_m = d0 * d1 * exp(f023 - f000) / 3 + d0 * d2 * exp(f323 - f000) / 3; + *va_m = sq_m - tsd_ipow(*mn_m, 2); + *pr_m = (c - a) / c * exp(f001 - f000); +out: + return ret; +} + +/* Twin nodes (both parents are the same node): a closed form. */ +int +tsd_mutation_twin_moments(double a_i, double b_i, double y_ij, double mu_ij, + double *pr_m, double *mn_m, double *va_m) +{ + int ret = 0; + double s, r, r_sq, sq_m; + + s = a_i + y_ij; + r = b_i + 2 * mu_ij; + r_sq = tsd_ipow(r, 2); + if (r_sq == 0.0) { + /* r is zero or its square underflows */ + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + *pr_m = 0.5; + *mn_m = s / r / 2; + sq_m = (s + 1) * s / 3 / r_sq; + *va_m = sq_m - tsd_ipow(*mn_m, 2); +out: + return ret; +} + +/* Unphased edge with a fixed parent age t_i, in terms of Tricomi functions. */ +int +tsd_mutation_sideways_moments(double t_i, double a_j, double b_j, double y_ij, + double mu_ij, double *pr_m, double *mn_m, double *va_m) +{ + int ret = 0; + double a, b, z, sq_m; + double f00, d00, f10, d10, f21, d21, f32, d32; + + if (!(t_i > 0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_FIXED_AGE); + goto out; + } + + a = a_j; + b = a_j + y_ij + 1; + z = t_i * (mu_ij + b_j); + + if (!tsd_valid_hyperu(a, b, z)) { + *pr_m = NAN; + *mn_m = NAN; + *va_m = NAN; + goto out; + } + + ret = tsd_hyperu_laplace(a + 0, b + 0, z, &f00, &d00); + if (ret != 0) { + goto out; + } + ret = tsd_hyperu_laplace(a + 1, b + 0, z, &f10, &d10); + if (ret != 0) { + goto out; + } + ret = tsd_hyperu_laplace(a + 2, b + 1, z, &f21, &d21); + if (ret != 0) { + goto out; + } + ret = tsd_hyperu_laplace(a + 3, b + 2, z, &f32, &d32); + if (ret != 0) { + goto out; + } + + *pr_m = 1.0 - exp(f10 - f00) * a; + *mn_m = *pr_m * t_i / 2 + t_i * exp(f21 - f00) * a * (a + 1) / 2; + sq_m = *pr_m * tsd_ipow(t_i, 2) / 3 + + tsd_ipow(t_i, 2) * exp(f32 - f00) * a * (a + 1) * (a + 2) / 3; + *va_m = sq_m - tsd_ipow(*mn_m, 2); +out: + return ret; +} + +/* Both node ages fixed and phased: t_m is uniform on (t_j, t_i). */ +int +tsd_mutation_edge_moments(double t_i, double t_j, double *mn_m, double *va_m) +{ + *mn_m = 1.0 / 2 * (t_i + t_j); + *va_m = 1.0 / 12 * tsd_ipow(t_i - t_j, 2); + return 0; +} + +/* Both node ages fixed and unphased: t_m is uniform on (0, t_i) or (0, t_j). */ +int +tsd_mutation_block_moments( + double t_i, double t_j, double *pr_m, double *mn_m, double *va_m) +{ + int ret = 0; + double sq_m; + + if (!(t_i > 0) || !(t_j > 0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_FIXED_AGE); + goto out; + } + *pr_m = t_i / (t_i + t_j); + *mn_m = *pr_m * t_i / 2 + (1 - *pr_m) * t_j / 2; + sq_m = *pr_m * tsd_ipow(t_i, 2) / 3 + (1 - *pr_m) * tsd_ipow(t_j, 2) / 3; + *va_m = sq_m - tsd_ipow(*mn_m, 2); +out: + return ret; +} + +/* ------------------------------------------------------------------------- * + * Mutation projections + * ------------------------------------------------------------------------- */ + +/* Set the outputs of a projection whose moments are unusable: NaN, in-band. */ +static void +mutation_projection_invalid(double *pr_m, double proj_m[2]) +{ + *pr_m = NAN; + proj_m[0] = NAN; + proj_m[1] = NAN; +} + +/* + * The gamma matching the mean and variance of the mutation age, with phase + * probability `pr`; NaN outputs if the moments are not usable. Phase probabilities + * outside [0, 1] (or NaN) are unusable when `check_pr` is set. + */ +static int +mutation_project_moments( + double pr, int check_pr, double mn_m, double va_m, double *pr_m, double proj_m[2]) +{ + int ret = 0; + int usable = tsd_valid_moments(mn_m, va_m); + + if (check_pr && !(pr >= 0.0 && pr <= 1.0)) { + usable = 0; + } + if (!usable) { + mutation_projection_invalid(pr_m, proj_m); + goto out; + } + ret = tsd_approximate_gamma_mom(mn_m, va_m, proj_m); + if (ret != 0) { + goto out; + } + *pr_m = pr; +out: + return ret; +} + +int +tsd_mutation_gamma_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]) +{ + int ret = 0; + double mn_m, va_m; + const double a_i = pars_i[0] + 1; + const double a_j = pars_j[0] + 1; + + ret = tsd_mutation_moments( + a_i, pars_i[1], a_j, pars_j[1], pars_ij[0], pars_ij[1], &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(1.0, 0, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} + +int +tsd_mutation_leafward_projection(double t_i, const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]) +{ + int ret = 0; + double mn_m, va_m; + const double a_j = pars_j[0] + 1; + + ret = tsd_mutation_leafward_moments( + t_i, a_j, pars_j[1], pars_ij[0], pars_ij[1], &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(1.0, 0, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} + +int +tsd_mutation_rootward_projection(double t_j, const double pars_i[2], + const double pars_ij[2], double *pr_m, double proj_m[2]) +{ + int ret = 0; + double mn_m, va_m; + const double a_i = pars_i[0] + 1; + + ret = tsd_mutation_rootward_moments( + t_j, a_i, pars_i[1], pars_ij[0], pars_ij[1], &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(1.0, 0, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} + +int +tsd_mutation_edge_projection(double t_i, double t_j, double *pr_m, double proj_m[2]) +{ + int ret = 0; + double mn_m, va_m; + + ret = tsd_mutation_edge_moments(t_i, t_j, &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(1.0, 0, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} + +int +tsd_mutation_unphased_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]) +{ + int ret = 0; + double pr, mn_m, va_m; + const double a_i = pars_i[0] + 1; + const double a_j = pars_j[0] + 1; + + ret = tsd_mutation_unphased_moments( + a_i, pars_i[1], a_j, pars_j[1], pars_ij[0], pars_ij[1], &pr, &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(pr, 1, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} + +int +tsd_mutation_twin_projection( + const double pars_i[2], const double pars_ij[2], double *pr_m, double proj_m[2]) +{ + int ret = 0; + double pr, mn_m, va_m; + const double a_i = pars_i[0] + 1; + + ret = tsd_mutation_twin_moments( + a_i, pars_i[1], pars_ij[0], pars_ij[1], &pr, &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(pr, 1, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} + +int +tsd_mutation_sideways_projection(double t_i, const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]) +{ + int ret = 0; + double pr, mn_m, va_m; + const double a_j = pars_j[0] + 1; + + ret = tsd_mutation_sideways_moments( + t_i, a_j, pars_j[1], pars_ij[0], pars_ij[1], &pr, &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(pr, 1, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} + +int +tsd_mutation_block_projection(double t_i, double t_j, double *pr_m, double proj_m[2]) +{ + int ret = 0; + double pr, mn_m, va_m; + + ret = tsd_mutation_block_moments(t_i, t_j, &pr, &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(pr, 1, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} diff --git a/lib/err.c b/lib/err.c index da5cdcb1..6336d832 100644 --- a/lib/err.c +++ b/lib/err.c @@ -50,6 +50,36 @@ tsd_strerror(int err) case TSD_ERR_INVALID_HYPERGEO: ret = "Parameters outside the domain of the hypergeometric function"; break; + case TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS: + ret = "Nonpositive or nonfinite moments"; + break; + case TSD_ERR_JENSEN_VIOLATION: + ret = "log E[t] <= E[log t] violates Jensen's inequality"; + break; + case TSD_ERR_KL_MAX_ITERATIONS: + ret = "Maximum iterations reached in KL minimization"; + break; + case TSD_ERR_KL_INVALID_SHAPE: + ret = "Invalid shape parameter in KL minimization"; + break; + case TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS: + ret = "Nonpositive central moments"; + break; + case TSD_ERR_UNSORTED_QUANTILES: + ret = "Quantiles must be sorted"; + break; + case TSD_ERR_QUANTILE_MAX_ITERATIONS: + ret = "Maximum iterations reached in quantile matching"; + break; + case TSD_ERR_NEGATIVE_SHAPE: + ret = "Negative shape parameter"; + break; + case TSD_ERR_NONPOSITIVE_MOMENTS: + ret = "The mean and variance must be positive"; + break; + case TSD_ERR_INVALID_FIXED_AGE: + ret = "The age of a fixed node is outside the domain of the function"; + break; default: break; } diff --git a/lib/err.h b/lib/err.h index 268dd30e..c323ddaf 100644 --- a/lib/err.h +++ b/lib/err.h @@ -42,6 +42,19 @@ extern "C" { /* hypergeo */ #define TSD_ERR_INVALID_HYPERGEO -5 + +/* approx: messages are those of numba's KLMinimizationFailedError, verbatim */ +#define TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS -6 +#define TSD_ERR_JENSEN_VIOLATION -7 +#define TSD_ERR_KL_MAX_ITERATIONS -8 +#define TSD_ERR_KL_INVALID_SHAPE -9 +#define TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS -10 +#define TSD_ERR_UNSORTED_QUANTILES -11 +#define TSD_ERR_QUANTILE_MAX_ITERATIONS -12 +#define TSD_ERR_NEGATIVE_SHAPE -13 +/* approx: violated preconditions (numba asserts) */ +#define TSD_ERR_NONPOSITIVE_MOMENTS -14 +#define TSD_ERR_INVALID_FIXED_AGE -15 /* clang-format on */ #ifdef __GNUC__ diff --git a/lib/meson.build b/lib/meson.build index a5ef894c..9affad84 100644 --- a/lib/meson.build +++ b/lib/meson.build @@ -15,7 +15,7 @@ if get_option('buildtype') == 'debug' extra_c_args += ['-DTSD_TRACE_ERRORS'] endif -tsdate_sources = ['err.c', 'hypergeo.c'] +tsdate_sources = ['err.c', 'hypergeo.c', 'approx.c'] tsdate_lib = static_library('tsdate', sources: tsdate_sources, dependencies: [m_dep], diff --git a/lib/tests/tests.c b/lib/tests/tests.c index 75c6110f..49e1a423 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -40,7 +40,12 @@ static void test_strerror(void) { const int codes[] = { 0, TSD_ERR_GENERIC, TSD_ERR_NO_MEMORY, TSD_ERR_BAD_PARAM, - TSD_ERR_ZERO_DIVISION, TSD_ERR_INVALID_HYPERGEO }; + TSD_ERR_ZERO_DIVISION, TSD_ERR_INVALID_HYPERGEO, + TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS, TSD_ERR_JENSEN_VIOLATION, + TSD_ERR_KL_MAX_ITERATIONS, TSD_ERR_KL_INVALID_SHAPE, + TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS, TSD_ERR_UNSORTED_QUANTILES, + TSD_ERR_QUANTILE_MAX_ITERATIONS, TSD_ERR_NEGATIVE_SHAPE, + TSD_ERR_NONPOSITIVE_MOMENTS, TSD_ERR_INVALID_FIXED_AGE }; const int num_codes = (int) (sizeof(codes) / sizeof(codes[0])); const char *msg_i; const char *msg_j; @@ -291,6 +296,386 @@ test_hyp2f1_laplace_errors(void) CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); } +/* + * A stand-in for SciPy's gammaincinv: the inverse of the regularised lower + * incomplete gamma function by bisection, with the series expansion of the function. + */ +static double +test_gammainc(double a, double x) +{ + double term = 1.0 / a; + double sum = term; + int n; + + for (n = 1; n < 1000; n++) { + term *= x / (a + n); + sum += term; + } + return sum * exp(a * log(x) - x - lgamma(a)); +} + +static double +test_gammaincinv(double a, double p) +{ + double lo = 0.0; + double hi = 1.0; + double mid; + int j; + + while (test_gammainc(a, hi) < p) { + hi *= 2; + } + for (j = 0; j < 100; j++) { + mid = (lo + hi) / 2; + if (test_gammainc(a, mid) < p) { + lo = mid; + } else { + hi = mid; + } + } + return (lo + hi) / 2; +} + +static double +test_zero_inv(double a, double p) +{ + return a * 0.0 * p; +} + +static double +test_tiny_inv(double a, double p) +{ + return 1e-200 * a * p; +} + +static void +test_approximate_log_moments(void) +{ + double logx, xlogx, logx2; + int ret; + + ret = tsd_approximate_log_moments(2.0, 0.5, &logx, &xlogx, &logx2); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(isfinite(logx) && isfinite(xlogx) && isfinite(logx2)); + ret = tsd_approximate_log_moments(0.0, 0.5, &logx, &xlogx, &logx2); + CU_ASSERT_EQUAL(ret, TSD_ERR_NONPOSITIVE_MOMENTS); + ret = tsd_approximate_log_moments(1.0, NAN, &logx, &xlogx, &logx2); + CU_ASSERT_EQUAL(ret, TSD_ERR_NONPOSITIVE_MOMENTS); + /* mean ** 2 underflows */ + ret = tsd_approximate_log_moments(1e-200, 1.0, &logx, &xlogx, &logx2); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); +} + +static void +test_approximate_gamma_kl(void) +{ + double out[2]; + int ret; + + ret = tsd_approximate_gamma_kl(2.0, 0.5, out); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(isfinite(out[0]) && isfinite(out[1])); + /* the asymptotic lower bound */ + ret = tsd_approximate_gamma_kl(1.0, -1e-10, out); + CU_ASSERT_EQUAL(ret, 0); + ret = tsd_approximate_gamma_kl(0.0, -1.0, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS); + ret = tsd_approximate_gamma_kl(1.0, 0.0, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_JENSEN_VIOLATION); + /* the lower bound on the shape is zero */ + ret = tsd_approximate_gamma_kl(INFINITY, -1.0, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + /* the trigamma function divides by zero */ + ret = tsd_approximate_gamma_kl(1.0, -1e164, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); +} + +static void +test_approximate_gamma_mom(void) +{ + double out[2]; + int ret; + + ret = tsd_approximate_gamma_mom(2.0, 4.0, out); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(out[0], 0.0); + CU_ASSERT_EQUAL(out[1], 0.5); + ret = tsd_approximate_gamma_mom(2.0, 0.0, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS); + ret = tsd_approximate_gamma_mom(NAN, 1.0, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS); +} + +static void +test_approximate_gamma_iqr(void) +{ + double out[2]; + double shape = 5.0; + double x1 = test_gammaincinv(shape, 0.25); + double x2 = test_gammaincinv(shape, 0.75); + int ret; + + /* Newton iteration recovers the shape */ + ret = tsd_approximate_gamma_iqr(0.25, 0.75, x1, x2, 50.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_DOUBLE_EQUAL(out[0], shape - 1, 1e-6); + /* capped shape: equal quantiles, a lower bound or an iteration above the cap */ + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 3.0, 3.0, 50.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(out[0], 49.0); + ret = tsd_approximate_gamma_iqr(0.25, 0.75, x1, x2, 2.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(out[0], 1.0); + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 1.1, 1e5, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, 0); + /* errors */ + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 2.0, 1.0, 50.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_UNSORTED_QUANTILES); + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 0.0, 0.0, 50.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + ret = tsd_approximate_gamma_iqr(0.0, 0.75, 1.0, 2.0, 50.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 0.0, 1.0, 50.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + ret = tsd_approximate_gamma_iqr(0.25, 1.0, 1.0, 2.0, 50.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_NEGATIVE_SHAPE); + /* a quantile function that returns zero, or underflows when squared */ + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 2.0, 50.0, test_zero_inv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 2.0, 50.0, test_tiny_inv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); +} + +static void +test_average_gammas(void) +{ + const double alpha[] = { 0.5, 3.0 }; + const double beta[] = { 1.0, 2.0 }; + const double zero_rate[] = { 1.0, 0.0 }; + const double pole[] = { -1.0, 3.0 }; + double out[2]; + int ret; + + ret = tsd_average_gammas(2, alpha, beta, out); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(isfinite(out[0]) && isfinite(out[1])); + ret = tsd_average_gammas(0, alpha, beta, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + ret = tsd_average_gammas(2, alpha, zero_rate, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + /* digamma has a pole at shape 0 */ + ret = tsd_average_gammas(2, pole, beta, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); +} + +static void +test_valid(void) +{ + CU_ASSERT_TRUE(tsd_valid_moments(1.0, 1.0)); + CU_ASSERT_FALSE(tsd_valid_moments(NAN, 1.0)); + CU_ASSERT_FALSE(tsd_valid_moments(1.0, 0.0)); + CU_ASSERT_TRUE(tsd_valid_gamma(1.0, 1.0)); + CU_ASSERT_FALSE(tsd_valid_gamma(1.0, INFINITY)); + CU_ASSERT_FALSE(tsd_valid_gamma(0.0, 1.0)); + CU_ASSERT_TRUE(tsd_valid_hyp1f1(1.0, 2.0, 0.5)); + CU_ASSERT_FALSE(tsd_valid_hyp1f1(1.0, NAN, 0.5)); + CU_ASSERT_FALSE(tsd_valid_hyp1f1(2.0, 1.0, 0.5)); + CU_ASSERT_TRUE(tsd_valid_hyperu(1.0, 2.0, 0.5)); + CU_ASSERT_FALSE(tsd_valid_hyperu(1.0, 2.0, INFINITY)); + CU_ASSERT_FALSE(tsd_valid_hyperu(1.0, 2.0, 0.0)); + CU_ASSERT_FALSE(tsd_valid_hyperu(1.0, 1.0, 0.5)); + CU_ASSERT_TRUE(tsd_valid_hyp2f1(1.0, 2.0, 3.0, 0.5)); + CU_ASSERT_FALSE(tsd_valid_hyp2f1(1.0, 2.0, NAN, 0.5)); + CU_ASSERT_FALSE(tsd_valid_hyp2f1(1.0, 2.0, 3.0, NAN)); + CU_ASSERT_FALSE(tsd_valid_hyp2f1(1.0, 2.0, 3.0, 1.0)); + CU_ASSERT_FALSE(tsd_valid_hyp2f1(1.0, 2.0, 3.0, -1e16)); + CU_ASSERT_FALSE(tsd_valid_hyp2f1(0.0, 2.0, 3.0, 0.5)); +} + +/* approx: node moments */ +static void +test_node_moments(void) +{ + int ret; + double v[5]; + + ret = tsd_moments(10, 0.01, 10, 0.01, 1, 1e-4, v, v + 1, v + 2, v + 3, v + 4); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isfinite(v[0])); + ret = tsd_moments(10, 0.01, 10, -0.02, 1, 1e-4, v, v + 1, v + 2, v + 3, v + 4); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isnan(v[0])); + ret = tsd_moments(10, 0.01, 10, 0.01, 1, 1e-4, v, v + 1, v + 2, v + 3, v + 4); + CU_ASSERT_EQUAL(ret, 0); + + ret = tsd_unphased_moments( + 10, 0.01, 10, 0.01, 1, 1e-4, v, v + 1, v + 2, v + 3, v + 4); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isfinite(v[0])); + ret = tsd_unphased_moments( + 10, -1.0, 10, 0.01, 1, 1e-4, v, v + 1, v + 2, v + 3, v + 4); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isnan(v[0])); + + /* a positive, a zero and an invalid child age; negative and NaN ages are errors */ + ret = tsd_rootward_moments(1000, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isfinite(v[0])); + ret = tsd_rootward_moments(0, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isfinite(v[0])); + ret = tsd_rootward_moments(1000, 10, -1.0, 1, 1e-4, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isnan(v[0])); + ret = tsd_rootward_moments(1e308, 10, 1e10, 1, 1e-4, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isnan(v[0])); + ret = tsd_rootward_moments(-1.0, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_FIXED_AGE); + ret = tsd_rootward_moments(NAN, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_FIXED_AGE); + + ret = tsd_leafward_moments(1000, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isfinite(v[0])); + ret = tsd_leafward_moments(1000, 0, 0.01, 1, 1e-4, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isnan(v[0])); + ret = tsd_leafward_moments(0, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_FIXED_AGE); + + ret = tsd_sideways_moments(1000, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isfinite(v[0])); + ret = tsd_sideways_moments(1000, 10, -1.0, 1, 1e-4, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isnan(v[0])); + ret = tsd_sideways_moments(0, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_FIXED_AGE); + + ret = tsd_twin_moments(10, 0.01, 1, 1e-4, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isfinite(v[0])); + ret = tsd_twin_moments(10, -2e-4, 1, 1e-4, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + ret = tsd_twin_moments(10, 1e-300, 1, 0.0, v, v + 1, v + 2); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); +} + +/* Each projection once with usable moments, and once with unusable ones (NaN). */ +static void +test_mutation_projections(void) +{ + const double pars_i[2] = { 2.0, 1.0 }; + const double pars_j[2] = { 1.0, 2.0 }; + const double pars_ij[2] = { 1.0, 1.0 }; + double pr_m; + double proj[2]; + + CU_ASSERT_EQUAL( + tsd_mutation_gamma_projection(pars_i, pars_j, pars_ij, &pr_m, proj), 0); + CU_ASSERT_EQUAL(pr_m, 1.0); + CU_ASSERT_EQUAL( + tsd_mutation_leafward_projection(2.0, pars_j, pars_ij, &pr_m, proj), 0); + CU_ASSERT_EQUAL( + tsd_mutation_rootward_projection(1.0, pars_i, pars_ij, &pr_m, proj), 0); + CU_ASSERT_EQUAL(tsd_mutation_edge_projection(2.0, 1.0, &pr_m, proj), 0); + CU_ASSERT_EQUAL(pr_m, 1.0); + CU_ASSERT_EQUAL( + tsd_mutation_unphased_projection(pars_i, pars_j, pars_ij, &pr_m, proj), 0); + CU_ASSERT_EQUAL(tsd_mutation_twin_projection(pars_i, pars_ij, &pr_m, proj), 0); + CU_ASSERT_EQUAL( + tsd_mutation_sideways_projection(2.0, pars_j, pars_ij, &pr_m, proj), 0); + CU_ASSERT_EQUAL(tsd_mutation_block_projection(2.0, 1.0, &pr_m, proj), 0); + CU_ASSERT_TRUE(pr_m > 0.0 && pr_m < 1.0); + + /* Zero variance: the moments are unusable, which is in-band. */ + CU_ASSERT_EQUAL(tsd_mutation_edge_projection(1.0, 1.0, &pr_m, proj), 0); + CU_ASSERT_TRUE(isnan(pr_m)); + CU_ASSERT_TRUE(isnan(proj[0])); + CU_ASSERT_TRUE(isnan(proj[1])); +} + +/* The node projections: usable moments, and unusable ones (NaN, input copied). */ +static void +test_node_projections(void) +{ + const double pars[2] = { 1.0, 2.0 }; + const double bad[2] = { -5.0, 1.0 }; + const double edge[2] = { 2.0, 0.5 }; + double logl; + double proj_i[2]; + double proj_j[2]; + + CU_ASSERT_EQUAL(tsd_gamma_projection(pars, pars, edge, &logl, proj_i, proj_j), 0); + CU_ASSERT_TRUE(isfinite(logl)); + CU_ASSERT_EQUAL(tsd_gamma_projection(bad, pars, edge, &logl, proj_i, proj_j), 0); + CU_ASSERT_TRUE(isnan(logl)); + CU_ASSERT_EQUAL(proj_i[0], bad[0]); + CU_ASSERT_EQUAL(proj_j[1], pars[1]); + + CU_ASSERT_EQUAL(tsd_unphased_projection(pars, pars, edge, &logl, proj_i, proj_j), 0); + CU_ASSERT_TRUE(isfinite(logl)); + CU_ASSERT_EQUAL(tsd_unphased_projection(bad, pars, edge, &logl, proj_i, proj_j), 0); + CU_ASSERT_TRUE(isnan(logl)); + + CU_ASSERT_EQUAL(tsd_leafward_projection(2.0, pars, edge, &logl, proj_j), 0); + CU_ASSERT_TRUE(isfinite(logl)); + CU_ASSERT_EQUAL(tsd_leafward_projection(2.0, bad, edge, &logl, proj_j), 0); + CU_ASSERT_TRUE(isnan(logl)); + CU_ASSERT_EQUAL(proj_j[0], bad[0]); + + CU_ASSERT_EQUAL(tsd_rootward_projection(0.5, pars, edge, &logl, proj_i), 0); + CU_ASSERT_TRUE(isfinite(logl)); + CU_ASSERT_EQUAL(tsd_rootward_projection(0.5, bad, edge, &logl, proj_i), 0); + CU_ASSERT_TRUE(isnan(logl)); + + CU_ASSERT_EQUAL(tsd_twin_projection(pars, edge, &logl, proj_i), 0); + CU_ASSERT_TRUE(isfinite(logl)); + CU_ASSERT_EQUAL(tsd_twin_projection(bad, edge, &logl, proj_i), 0); + CU_ASSERT_TRUE(isnan(logl)); + + CU_ASSERT_EQUAL(tsd_sideways_projection(1.0, pars, edge, &logl, proj_j), 0); + CU_ASSERT_TRUE(isfinite(logl)); + CU_ASSERT_EQUAL(tsd_sideways_projection(1.0, bad, edge, &logl, proj_j), 0); + CU_ASSERT_TRUE(isnan(logl)); +} + +/* approx: mutation moments */ +static void +test_mutation_moments(void) +{ + double pr, mn, va; + + CU_ASSERT_EQUAL(tsd_mutation_moments(5, 0.01, 6, 0.02, 2, 0.001, &mn, &va), 0); + CU_ASSERT_TRUE(mn > 0); + /* t <= 0: the hypergeometric domain check fails, in-band */ + CU_ASSERT_EQUAL(tsd_mutation_moments(5, -1, 6, 0.02, 2, 0.5, &mn, &va), 0); + CU_ASSERT_TRUE(isnan(mn)); + CU_ASSERT_EQUAL(tsd_mutation_rootward_moments(1, 5, 0.01, 2, 0.001, &mn, &va), 0); + CU_ASSERT_EQUAL(tsd_mutation_leafward_moments(50, 5, 0.01, 2, 0.001, &mn, &va), 0); + CU_ASSERT_EQUAL( + tsd_mutation_unphased_moments(5, 0.01, 6, 0.02, 2, 0.001, &pr, &mn, &va), 0); + CU_ASSERT_TRUE(pr > 0); + CU_ASSERT_EQUAL( + tsd_mutation_unphased_moments(5, -1, 6, 0.02, 2, 0.5, &pr, &mn, &va), 0); + CU_ASSERT_TRUE(isnan(pr)); + CU_ASSERT_EQUAL(tsd_mutation_twin_moments(5, 0.01, 2, 0.001, &pr, &mn, &va), 0); + CU_ASSERT_EQUAL( + tsd_mutation_sideways_moments(10, 5, 0.01, 2, 0.001, &pr, &mn, &va), 0); + CU_ASSERT_EQUAL( + tsd_mutation_sideways_moments(10, -5, 0.01, 2, 0.001, &pr, &mn, &va), 0); + CU_ASSERT_TRUE(isnan(pr)); + CU_ASSERT_EQUAL(tsd_mutation_sideways_moments(0, 5, 0.01, 2, 0.001, &pr, &mn, &va), + TSD_ERR_INVALID_FIXED_AGE); + CU_ASSERT_EQUAL(tsd_mutation_edge_moments(10, 2, &mn, &va), 0); + CU_ASSERT_EQUAL(tsd_mutation_block_moments(10, 2, &pr, &mn, &va), 0); + CU_ASSERT_EQUAL( + tsd_mutation_block_moments(0, 2, &pr, &mn, &va), TSD_ERR_INVALID_FIXED_AGE); + CU_ASSERT_EQUAL( + tsd_mutation_block_moments(2, 0, &pr, &mn, &va), TSD_ERR_INVALID_FIXED_AGE); +} + static void handle_cunit_error(void) { @@ -322,6 +707,16 @@ main(int argc, char **argv) { "test_hyp1f1_laplace_errors", test_hyp1f1_laplace_errors }, { "test_hyp2f1_laplace", test_hyp2f1_laplace }, { "test_hyp2f1_laplace_errors", test_hyp2f1_laplace_errors }, + { "test_approximate_log_moments", test_approximate_log_moments }, + { "test_approximate_gamma_kl", test_approximate_gamma_kl }, + { "test_approximate_gamma_mom", test_approximate_gamma_mom }, + { "test_approximate_gamma_iqr", test_approximate_gamma_iqr }, + { "test_average_gammas", test_average_gammas }, + { "test_valid", test_valid }, + { "test_node_moments", test_node_moments }, + { "test_node_projections", test_node_projections }, + { "test_mutation_moments", test_mutation_moments }, + { "test_mutation_projections", test_mutation_projections }, CU_TEST_INFO_NULL, }; CU_SuiteInfo suites[] = { diff --git a/lib/tsdate.h b/lib/tsdate.h index f28661e6..50d753bf 100644 --- a/lib/tsdate.h +++ b/lib/tsdate.h @@ -64,6 +64,120 @@ int tsd_hyp2f1_laplace(double a, double b, double c, double x, double *out); */ typedef double (*tsd_gammaincinv_fn)(double a, double p); +/* + * Approximations of gamma distributions and of the moments of the EP updates + * (approx.c). + * + * Gamma distributions are written as shape and rate (a, b), with density + * proportional to t^(a - 1) exp(-b t), or as "natural parameters" (a - 1, b); the + * latter are what the gamma_* approximation functions and the projections return and + * take. Errors are as for the special functions above, plus the TSD_ERR_* codes of + * the approximations whose messages are those of numba's KLMinimizationFailedError. + * + * Convention for the moment and projection functions (sections of approx.c): + * + * - A function that can fail returns int: 0 or a negative TSD_ERR_* code. Results + * are written through trailing output pointers, which are written only on + * success (return 0) and must not alias the inputs. + * - Moment functions take, in the order of the numba arguments, ages (`t_i`, `t_j`: + * a fixed parent or child) and gamma SHAPE and rate (`a_i`, `b_i`, `a_j`, `b_j`: + * not natural parameters), the mutation count `y_ij` and the rate `mu_ij`. They + * write the values that numba returns, in the same order: the log normalising + * constant (`logl`) or the phase probability (`pr_m`), then means and variances. + * A result that numba returns as NaN (an invalid hypergeometric domain) is + * returned as NaN in every output, with return value 0. + * - Projection functions take the natural parameters of the cavity gammas as + * `const double pars_i[2]`, `pars_j[2]` and the edge data as `pars_ij[2]` + * (`y_ij`, `mu_ij`), or ages as in the moment functions. They write the log + * normalising constant (`*logl`, or `*pr_m` for mutation projections) and the + * projected natural parameters through `double proj_i[2]`, `proj_j[2]` (or + * `proj_m[2]`). Where numba returns the input parameters because the moments are + * unusable, `*logl` is NaN and `proj_*` is a copy of `pars_*`; mutation + * projections write NaN to `*pr_m` and to both entries of `proj_m`. + * - Functions of the gamma approximations that numba returns as a pair of natural + * parameters write them through `double out[2]`. + * - The `tsd_valid_*` predicates return 1 if the arguments are usable and 0 if not; + * a failure is in-band (numba returned False), not an error. + */ +int tsd_approximate_log_moments( + double mean, double variance, double *logx, double *xlogx, double *logx2); +int tsd_approximate_gamma_kl(double x, double logx, double out[2]); +int tsd_approximate_gamma_mom(double mean, double variance, double out[2]); +int tsd_approximate_gamma_iqr(double q1, double q2, double x1, double x2, + double max_shape, tsd_gammaincinv_fn gammaincinv, double out[2]); +/* The natural parameters of the gamma whose mean and mean log are the averages of + * those of `num_gammas` gammas given by natural parameters `alpha`, `beta`. */ +int tsd_average_gammas( + tsd_size_t num_gammas, const double *alpha, const double *beta, double out[2]); + +int tsd_valid_moments(double mn, double va); +int tsd_valid_gamma(double s, double r); +int tsd_valid_hyp1f1(double a, double b, double z); +int tsd_valid_hyperu(double a, double b, double z); +int tsd_valid_hyp2f1(double a, double b, double c, double z); + +/* Node moments (approx.c) */ +int tsd_moments(double a_i, double b_i, double a_j, double b_j, double y_ij, + double mu_ij, double *logl, double *mn_i, double *va_i, double *mn_j, double *va_j); +int tsd_rootward_moments(double t_j, double a_i, double b_i, double y_ij, double mu_ij, + double *logl, double *mn_i, double *va_i); +int tsd_leafward_moments(double t_i, double a_j, double b_j, double y_ij, double mu_ij, + double *logl, double *mn_j, double *va_j); +int tsd_unphased_moments(double a_i, double b_i, double a_j, double b_j, double y_ij, + double mu_ij, double *logl, double *mn_i, double *va_i, double *mn_j, double *va_j); +int tsd_twin_moments(double a_i, double b_i, double y_ij, double mu_ij, double *logl, + double *mn_i, double *va_i); +int tsd_sideways_moments(double t_i, double a_j, double b_j, double y_ij, double mu_ij, + double *logl, double *mn_j, double *va_j); + +/* Node projections */ +int tsd_gamma_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *logl, double proj_i[2], double proj_j[2]); +int tsd_leafward_projection(double t_i, const double pars_j[2], const double pars_ij[2], + double *logl, double proj_j[2]); +int tsd_rootward_projection(double t_j, const double pars_i[2], const double pars_ij[2], + double *logl, double proj_i[2]); +int tsd_unphased_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *logl, double proj_i[2], double proj_j[2]); +int tsd_twin_projection( + const double pars_i[2], const double pars_ij[2], double *logl, double proj_i[2]); +int tsd_sideways_projection(double t_i, const double pars_j[2], const double pars_ij[2], + double *logl, double proj_j[2]); + +/* Mutation moments */ +int tsd_mutation_moments(double a_i, double b_i, double a_j, double b_j, double y_ij, + double mu_ij, double *mn_m, double *va_m); +int tsd_mutation_rootward_moments(double t_j, double a_i, double b_i, double y_ij, + double mu_ij, double *mn_m, double *va_m); +int tsd_mutation_leafward_moments(double t_i, double a_j, double b_j, double y_ij, + double mu_ij, double *mn_m, double *va_m); +int tsd_mutation_unphased_moments(double a_i, double b_i, double a_j, double b_j, + double y_ij, double mu_ij, double *pr_m, double *mn_m, double *va_m); +int tsd_mutation_twin_moments(double a_i, double b_i, double y_ij, double mu_ij, + double *pr_m, double *mn_m, double *va_m); +int tsd_mutation_sideways_moments(double t_i, double a_j, double b_j, double y_ij, + double mu_ij, double *pr_m, double *mn_m, double *va_m); +int tsd_mutation_edge_moments(double t_i, double t_j, double *mn_m, double *va_m); +int tsd_mutation_block_moments( + double t_i, double t_j, double *pr_m, double *mn_m, double *va_m); + +/* Mutation projections */ +int tsd_mutation_gamma_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]); +int tsd_mutation_leafward_projection(double t_i, const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]); +int tsd_mutation_rootward_projection(double t_j, const double pars_i[2], + const double pars_ij[2], double *pr_m, double proj_m[2]); +int tsd_mutation_edge_projection(double t_i, double t_j, double *pr_m, double proj_m[2]); +int tsd_mutation_unphased_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]); +int tsd_mutation_twin_projection( + const double pars_i[2], const double pars_ij[2], double *pr_m, double proj_m[2]); +int tsd_mutation_sideways_projection(double t_i, const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]); +int tsd_mutation_block_projection( + double t_i, double t_j, double *pr_m, double proj_m[2]); + #ifdef __cplusplus } #endif diff --git a/setup.py b/setup.py index 46239cc8..9ad8a6a0 100644 --- a/setup.py +++ b/setup.py @@ -9,7 +9,7 @@ libdir = "lib" includes = [libdir] -tsd_source_files = ["err.c", "hypergeo.c"] +tsd_source_files = ["err.c", "hypergeo.c", "approx.c"] sources = ["_tsdatemodule.c"] + [os.path.join(libdir, f) for f in tsd_source_files] diff --git a/tests/oracle/implementations.py b/tests/oracle/implementations.py index 2d6810d3..8f618d26 100644 --- a/tests/oracle/implementations.py +++ b/tests/oracle/implementations.py @@ -14,6 +14,7 @@ import types +import numpy as np import pytest import tsdate.approx @@ -101,12 +102,86 @@ def _c_hypergeo(_tsdate): ) +def _c_valid(func): + """The `_valid_*` checks return a bool in numba; the C function a float.""" + + def valid(*args): + return bool(func(*args)) + + return valid + + +def _c_projection(func): + """ + Adapter for a projection. The C function takes flat arguments (the ages, and the + entries of the parameter arrays) and returns a flat tuple: the first result, then + the pairs of natural parameters; the oracle takes arrays and returns the first + result and one array per pair. + """ + + def projection(*args): + flat = [float(x) for arg in args for x in np.atleast_1d(arg)] + first, *rest = func(*flat) + pairs = [np.array(rest[i : i + 2]) for i in range(0, len(rest), 2)] + return (first, *pairs) + + return projection + + +def _c_approx(_tsdate): + # The helpers; each commented section is owned by the agent that ports it. + return _PortedNamespace( + approximate_log_moments=_tsdate.approximate_log_moments, + approximate_gamma_kl=_tsdate.approximate_gamma_kl, + approximate_gamma_mom=_tsdate.approximate_gamma_mom, + approximate_gamma_iqr=_tsdate.approximate_gamma_iqr, + average_gammas=_tsdate.average_gammas, + _valid_moments=_c_valid(_tsdate.valid_moments), + _valid_gamma=_c_valid(_tsdate.valid_gamma), + _valid_hyp1f1=_c_valid(_tsdate.valid_hyp1f1), + _valid_hyperu=_c_valid(_tsdate.valid_hyperu), + _valid_hyp2f1=_c_valid(_tsdate.valid_hyp2f1), + # approx: node moments + moments=_tsdate.moments, + rootward_moments=_tsdate.rootward_moments, + leafward_moments=_tsdate.leafward_moments, + unphased_moments=_tsdate.unphased_moments, + twin_moments=_tsdate.twin_moments, + sideways_moments=_tsdate.sideways_moments, + # approx: node projections + gamma_projection=_c_projection(_tsdate.gamma_projection), + leafward_projection=_c_projection(_tsdate.leafward_projection), + rootward_projection=_c_projection(_tsdate.rootward_projection), + unphased_projection=_c_projection(_tsdate.unphased_projection), + twin_projection=_c_projection(_tsdate.twin_projection), + sideways_projection=_c_projection(_tsdate.sideways_projection), + # approx: mutation moments + mutation_moments=_tsdate.mutation_moments, + mutation_rootward_moments=_tsdate.mutation_rootward_moments, + mutation_leafward_moments=_tsdate.mutation_leafward_moments, + mutation_unphased_moments=_tsdate.mutation_unphased_moments, + mutation_twin_moments=_tsdate.mutation_twin_moments, + mutation_sideways_moments=_tsdate.mutation_sideways_moments, + mutation_edge_moments=_tsdate.mutation_edge_moments, + mutation_block_moments=_tsdate.mutation_block_moments, + # approx: mutation projections + mutation_gamma_projection=_c_projection(_tsdate.mutation_gamma_projection), + mutation_leafward_projection=_c_projection(_tsdate.mutation_leafward_projection), + mutation_rootward_projection=_c_projection(_tsdate.mutation_rootward_projection), + mutation_edge_projection=_c_projection(_tsdate.mutation_edge_projection), + mutation_unphased_projection=_c_projection(_tsdate.mutation_unphased_projection), + mutation_twin_projection=_c_projection(_tsdate.mutation_twin_projection), + mutation_sideways_projection=_c_projection(_tsdate.mutation_sideways_projection), + mutation_block_projection=_c_projection(_tsdate.mutation_block_projection), + ) + + def _c_namespace(): import _tsdate return types.SimpleNamespace( hypergeo=_c_hypergeo(_tsdate), - approx=_PortedNamespace(), + approx=_c_approx(_tsdate), variational=_PortedNamespace(), rescaling=_PortedNamespace(), phasing=_PortedNamespace(), diff --git a/tests/test_python_c_approx.py b/tests/test_python_c_approx.py new file mode 100644 index 00000000..7cdf4616 --- /dev/null +++ b/tests/test_python_c_approx.py @@ -0,0 +1,123 @@ +""" +Tests of the low-level _tsdate module for the approx functions: error messages, +argument checking of the array-level function, and the test adapters. Numerical values +are tested against the oracles in test_oracle_approx.py. +""" + +import re + +import _tsdate +import numpy as np +import pytest +from oracle import approx +from oracle.helpers import compare +from oracle.implementations import _c_projection + +# error code: the message of numba's KLMinimizationFailedError (or the assertion) +APPROX_ERRORS = { + -6: "Nonpositive or nonfinite moments", + -7: "log E[t] <= E[log t] violates Jensen's inequality", + -8: "Maximum iterations reached in KL minimization", + -9: "Invalid shape parameter in KL minimization", + -10: "Nonpositive central moments", + -11: "Quantiles must be sorted", + -12: "Maximum iterations reached in quantile matching", + -13: "Negative shape parameter", + -14: "The mean and variance must be positive", + -15: "The age of a fixed node is outside the domain of the function", +} + + +class TestApproxErrors: + @pytest.mark.parametrize(("code", "message"), APPROX_ERRORS.items()) + def test_messages(self, code, message): + assert _tsdate.strerror(code) == message + with pytest.raises(_tsdate.LibraryError, match=re.escape(message)): + _tsdate.raise_library_error(code) + + +class TestAverageGammas: + def test_matches_kl_of_averages(self): + alpha = np.array([0.5, 3.0]) + beta = np.array([1.0, 2.0]) + result = _tsdate.average_gammas(alpha, beta) + assert isinstance(result, tuple) + assert len(result) == 2 + assert all(isinstance(x, float) for x in result) + + def test_accepts_lists_and_integers(self): + assert _tsdate.average_gammas([1, 2], [1, 2]) == _tsdate.average_gammas( + np.array([1.0, 2.0]), np.array([1.0, 2.0]) + ) + + def test_size_mismatch(self): + with pytest.raises(ValueError, match="Array sizes are not equal"): + _tsdate.average_gammas(np.ones(2), np.ones(3)) + + @pytest.mark.parametrize("shape", [(), (2, 2)]) + def test_wrong_dimension(self, shape): + with pytest.raises(ValueError): + _tsdate.average_gammas(np.ones(shape), np.ones(shape)) + + def test_wrong_dimension_second_argument(self): + with pytest.raises(ValueError): + _tsdate.average_gammas(np.ones(2), np.ones((2, 2))) + + def test_not_numeric(self): + with pytest.raises(ValueError): + _tsdate.average_gammas(["a"], [1.0]) + + def test_wrong_number_of_arguments(self): + with pytest.raises(TypeError): + _tsdate.average_gammas(np.ones(2)) + + def test_library_error(self): + with pytest.raises(_tsdate.LibraryError, match="division by zero"): + _tsdate.average_gammas(np.array([]), np.array([])) + + +class TestProjectionAdapter: + def test_flattens_arrays_and_wraps_pairs(self): + calls = [] + + def func(*flat): + calls.append(flat) + return 7.0, 1.0, 2.0, 3.0, 4.0 + + result = _c_projection(func)(2.5, np.array([1.0, 2.0]), np.array([3.0, 4.0])) + assert calls == [(2.5, 1.0, 2.0, 3.0, 4.0)] + assert result[0] == 7.0 + np.testing.assert_array_equal(result[1], [1.0, 2.0]) + np.testing.assert_array_equal(result[2], [3.0, 4.0]) + + +# Failures of the quantile fit (found by random search), each at a different step of +# the Newton iteration: the lower quantile underflows to zero, its square underflows +# to zero, and the iteration does not converge. +GAMMA_IQR_FAILURES = { + "lower quantile is zero": (1e-300, 1e-299, 1.0, 1e30, 50.0), + "lower quantile squared is zero": ( + 0.25, + 0.75, + 5.256386560310826e-218, + 9.53e-42, + 50.0, + ), + "no convergence": ( + 4.195119806947257e-42, + 1.3790748660114965e-37, + 1.656873535271179e-06, + 8.871129030923311e-06, + 1e7, + ), +} + + +class TestGammaIqrFailures: + @pytest.mark.parametrize("label", list(GAMMA_IQR_FAILURES)) + def test_failures(self, label): + args = GAMMA_IQR_FAILURES[label] + expected = compare( + _tsdate.approximate_gamma_iqr, approx.approximate_gamma_iqr, *args + ) + assert expected.exception is not None From e89acb8e47459a9c253415c76be003418c6299a0 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Mon, 23 Nov 2026 13:45:17 -0800 Subject: [PATCH 08/56] Port the phasing, util and prior functions to C Adds lib/phasing.c (block_singletons, reallocate_unphased, mutation_frequency), lib/util.c (split_disjoint_nodes, relabel_mutations_node, constrain_ages, contains_unary_nodes, and a stable argsort) and lib/prior.c (marginalize_over_ancestors, conditional_coalescent_variance), with the module wrappers, C smoke tests, the "c" entries of the oracle test fixture and of the microbenchmarks, and low-level tests of the error paths. Error codes: the asserts reached by the tests become TSD_ERR_UNPHASED_INDIVIDUAL_EDGES (an individual with more than two edges, or a block never completed), TSD_ERR_BLOCK_OUT_OF_RANGE, TSD_ERR_PHASE_OUT_OF_RANGE, TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED, TSD_ERR_MUTATION_NODE_NOT_IN_TREE and TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT. Size asserts are ValueErrors in the module. Deliberate deviations from numba, which is undefined where the C code is defined: block_singletons sizes its per-individual state by individuals, not by edges; conditional_coalescent_variance(1) returns two zeros instead of reading past the end; relabel_mutations_node with no edges leaves every mutation NULL instead of indexing an empty array; out-of-range block ids in reallocate_unphased are an error. --- _tsdatemodule.c | 615 ++++++++++++++++++++++++++++++++ evaluation/microbench.py | 14 +- lib/err.c | 19 + lib/err.h | 10 + lib/meson.build | 3 +- lib/phasing.c | 427 ++++++++++++++++++++++ lib/prior.c | 163 +++++++++ lib/tests/tests.c | 250 ++++++++++++- lib/tsdate.h | 55 +++ lib/util.c | 504 ++++++++++++++++++++++++++ setup.py | 2 +- tests/oracle/implementations.py | 30 +- tests/test_python_c_tables.py | 151 ++++++++ 13 files changed, 2236 insertions(+), 7 deletions(-) create mode 100644 lib/phasing.c create mode 100644 lib/prior.c create mode 100644 lib/util.c create mode 100644 tests/test_python_c_tables.py diff --git a/_tsdatemodule.c b/_tsdatemodule.c index b0f5f03b..62a21bd5 100644 --- a/_tsdatemodule.c +++ b/_tsdatemodule.c @@ -26,6 +26,7 @@ #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include +#include #include #include "lib/tsdate.h" @@ -631,6 +632,601 @@ tsdate_average_gammas(PyObject *Py_UNUSED(self), PyObject *args) return ret; } +/* + * Phasing, utilities and prior: array-level functions. Each takes the arguments of the + * numba function it replaces. Size checks that numba asserted raise ValueError. + */ + +#define MAX_ARRAYS 10 + +/* Convert `num_arrays` objects to C-contiguous arrays of the given types and ndim. */ +static int +parse_arrays(PyObject **objs, const int *typenums, int ndim, int num_arrays, + PyArrayObject **arrays) +{ + int j; + + for (j = 0; j < num_arrays; j++) { + arrays[j] = (PyArrayObject *) PyArray_FROMANY( + objs[j], typenums[j], ndim, ndim, NPY_ARRAY_IN_ARRAY); + if (arrays[j] == NULL) { + return -1; + } + } + return 0; +} + +static void +release_arrays(PyArrayObject **arrays, int num_arrays) +{ + int j; + + for (j = 0; j < num_arrays; j++) { + Py_XDECREF(arrays[j]); + } +} + +#define ARRAY_SIZE(array) ((tsd_size_t) PyArray_SIZE(array)) +#define ARRAY_DIM(array, axis) ((tsd_size_t) PyArray_DIM(array, axis)) + +/* Whether all the arrays have the same size; raises ValueError if not. */ +static int +check_sizes_equal(PyArrayObject **arrays, int num_arrays) +{ + int j; + + for (j = 1; j < num_arrays; j++) { + if (ARRAY_SIZE(arrays[j]) != ARRAY_SIZE(arrays[0])) { + PyErr_SetString(PyExc_ValueError, "Array sizes are not equal"); + return -1; + } + } + return 0; +} + +/* A new array of the given type and shape, copying `size` bytes from `data`. */ +static PyObject * +array_from_data(int typenum, int ndim, npy_intp *dims, const void *data, size_t size) +{ + PyObject *ret = PyArray_SimpleNew(ndim, dims, typenum); + + if (ret != NULL && size > 0) { + memcpy(PyArray_DATA((PyArrayObject *) ret), data, size); + } + return ret; +} + +/* + * block_singletons(individuals_unphased, nodes_individual, mutations_node, + * mutations_position, edges_parent, edges_child, edges_left, edges_right, + * indexes_insert, indexes_remove, sequence_length) + * returns (blocks_stats, blocks_edges, mutations_block). + */ +static PyObject * +tsdate_block_singletons(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *objs[10]; + const int typenums[10] = { NPY_BOOL, NPY_INT32, NPY_INT32, NPY_FLOAT64, NPY_INT32, + NPY_INT32, NPY_FLOAT64, NPY_FLOAT64, NPY_INT32, NPY_INT32 }; + PyArrayObject *arrays[10] = { NULL }; + PyObject *stats_array = NULL; + PyObject *edges_array = NULL; + PyObject *mutations_block = NULL; + double *blocks_stats = NULL; + tsd_id_t *blocks_edges = NULL; + tsd_size_t num_blocks = 0; + npy_intp dims[2]; + double sequence_length; + int err; + + if (!PyArg_ParseTuple(args, "OOOOOOOOOOd", &objs[0], &objs[1], &objs[2], &objs[3], + &objs[4], &objs[5], &objs[6], &objs[7], &objs[8], &objs[9], + &sequence_length)) { + goto out; + } + if (parse_arrays(objs, typenums, 1, 10, arrays) != 0) { + goto out; + } + if (check_sizes_equal(arrays + 4, 4) != 0 || check_sizes_equal(arrays + 8, 2) != 0 + || check_sizes_equal(arrays + 2, 2) != 0 + || ARRAY_SIZE(arrays[8]) != ARRAY_SIZE(arrays[4])) { + PyErr_SetString(PyExc_ValueError, "Array sizes are not equal"); + goto out; + } + dims[0] = PyArray_DIM(arrays[2], 0); + mutations_block = PyArray_SimpleNew(1, dims, NPY_INT32); + if (mutations_block == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_block_singletons(ARRAY_SIZE(arrays[0]), ARRAY_SIZE(arrays[4]), + ARRAY_SIZE(arrays[2]), (const uint8_t *) PyArray_DATA(arrays[0]), + (const tsd_id_t *) PyArray_DATA(arrays[1]), + (const tsd_id_t *) PyArray_DATA(arrays[2]), + (const double *) PyArray_DATA(arrays[3]), + (const tsd_id_t *) PyArray_DATA(arrays[5]), + (const double *) PyArray_DATA(arrays[6]), + (const double *) PyArray_DATA(arrays[7]), + (const tsd_id_t *) PyArray_DATA(arrays[8]), + (const tsd_id_t *) PyArray_DATA(arrays[9]), sequence_length, &num_blocks, + &blocks_stats, &blocks_edges, + (tsd_id_t *) PyArray_DATA((PyArrayObject *) mutations_block)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + dims[0] = (npy_intp) num_blocks; + dims[1] = 2; + stats_array = array_from_data( + NPY_FLOAT64, 2, dims, blocks_stats, 2 * num_blocks * sizeof(*blocks_stats)); + edges_array = array_from_data( + NPY_INT32, 2, dims, blocks_edges, 2 * num_blocks * sizeof(*blocks_edges)); + if (stats_array == NULL || edges_array == NULL) { + goto out; + } + ret = Py_BuildValue("OOO", stats_array, edges_array, mutations_block); +out: + release_arrays(arrays, 10); + Py_XDECREF(stats_array); + Py_XDECREF(edges_array); + Py_XDECREF(mutations_block); + tsd_safe_free(blocks_stats); + tsd_safe_free(blocks_edges); + return ret; +} + +/* + * reallocate_unphased(edges_likelihood, mutations_phase, mutations_block, + * blocks_edges): updates edges_likelihood in place. + */ +static PyObject * +tsdate_reallocate_unphased(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *likelihood_obj = NULL; + PyObject *phase_obj = NULL; + PyObject *block_obj = NULL; + PyObject *edges_obj = NULL; + PyArrayObject *likelihood_array = NULL; + PyArrayObject *phase_array = NULL; + PyArrayObject *block_array = NULL; + PyArrayObject *edges_array = NULL; + int err; + + if (!PyArg_ParseTuple( + args, "OOOO", &likelihood_obj, &phase_obj, &block_obj, &edges_obj)) { + goto out; + } + likelihood_array = (PyArrayObject *) PyArray_FROMANY( + likelihood_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_INOUT_ARRAY); + phase_array = (PyArrayObject *) PyArray_FROMANY( + phase_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + block_array = (PyArrayObject *) PyArray_FROMANY( + block_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + edges_array = (PyArrayObject *) PyArray_FROMANY( + edges_obj, NPY_INT32, 2, 2, NPY_ARRAY_IN_ARRAY); + if (likelihood_array == NULL || phase_array == NULL || block_array == NULL + || edges_array == NULL) { + goto out; + } + if (ARRAY_SIZE(phase_array) != ARRAY_SIZE(block_array)) { + PyErr_SetString(PyExc_ValueError, "Array sizes are not equal"); + goto out; + } + if (ARRAY_DIM(edges_array, 1) != 2 || ARRAY_DIM(likelihood_array, 1) != 2) { + PyErr_SetString(PyExc_ValueError, "Arrays must have two columns"); + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_reallocate_unphased(ARRAY_DIM(likelihood_array, 0), + ARRAY_SIZE(phase_array), ARRAY_DIM(edges_array, 0), + (const double *) PyArray_DATA(phase_array), + (const tsd_id_t *) PyArray_DATA(block_array), + (const tsd_id_t *) PyArray_DATA(edges_array), + (double *) PyArray_DATA(likelihood_array)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = Py_None; + Py_INCREF(ret); +out: + Py_XDECREF(likelihood_array); + Py_XDECREF(phase_array); + Py_XDECREF(block_array); + Py_XDECREF(edges_array); + return ret; +} + +/* + * mutation_frequency(nodes_sample, mutations_node, mutations_position, edges_parent, + * edges_child, edges_left, edges_right, indexes_insert, indexes_remove, + * sequence_length) returns an int32 array of shape (mutations, sample sets). + */ +static PyObject * +tsdate_mutation_frequency(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *sample_obj = NULL; + PyObject *objs[MAX_ARRAYS]; + const int typenums[9] = { NPY_INT32, NPY_FLOAT64, NPY_INT32, NPY_INT32, NPY_FLOAT64, + NPY_FLOAT64, NPY_INT32, NPY_INT32 }; + PyArrayObject *sample_array = NULL; + PyArrayObject *arrays[8] = { NULL }; + PyObject *freq_array = NULL; + npy_intp dims[2]; + double sequence_length; + int err; + + if (!PyArg_ParseTuple(args, "OOOOOOOOOd", &sample_obj, &objs[0], &objs[1], &objs[2], + &objs[3], &objs[4], &objs[5], &objs[6], &objs[7], &sequence_length)) { + goto out; + } + sample_array = (PyArrayObject *) PyArray_FROMANY( + sample_obj, NPY_BOOL, 2, 2, NPY_ARRAY_IN_ARRAY); + if (sample_array == NULL) { + goto out; + } + if (parse_arrays(objs, typenums, 1, 8, arrays) != 0) { + goto out; + } + if (check_sizes_equal(arrays + 2, 4) != 0 || check_sizes_equal(arrays + 6, 2) != 0 + || check_sizes_equal(arrays, 2) != 0 + || ARRAY_SIZE(arrays[6]) != ARRAY_SIZE(arrays[2])) { + PyErr_SetString(PyExc_ValueError, "Array sizes are not equal"); + goto out; + } + dims[0] = PyArray_DIM(arrays[0], 0); + dims[1] = PyArray_DIM(sample_array, 1); + freq_array = PyArray_SimpleNew(2, dims, NPY_INT32); + if (freq_array == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_mutation_frequency(ARRAY_DIM(sample_array, 0), ARRAY_DIM(sample_array, 1), + ARRAY_SIZE(arrays[2]), ARRAY_SIZE(arrays[0]), + (const uint8_t *) PyArray_DATA(sample_array), + (const tsd_id_t *) PyArray_DATA(arrays[0]), + (const double *) PyArray_DATA(arrays[1]), + (const tsd_id_t *) PyArray_DATA(arrays[2]), + (const tsd_id_t *) PyArray_DATA(arrays[3]), + (const double *) PyArray_DATA(arrays[4]), + (const double *) PyArray_DATA(arrays[5]), + (const tsd_id_t *) PyArray_DATA(arrays[6]), + (const tsd_id_t *) PyArray_DATA(arrays[7]), sequence_length, + (int32_t *) PyArray_DATA((PyArrayObject *) freq_array)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = freq_array; + freq_array = NULL; +out: + Py_XDECREF(sample_array); + release_arrays(arrays, 8); + Py_XDECREF(freq_array); + return ret; +} + +/* + * split_disjoint_nodes(edges_parent, edges_child, edges_left, edges_right, + * node_excluded) returns (edges_parent, edges_child, nodes_order, split_nodes). + */ +static PyObject * +tsdate_split_disjoint_nodes(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *objs[5]; + const int typenums[5] = { NPY_INT32, NPY_INT32, NPY_FLOAT64, NPY_FLOAT64, NPY_BOOL }; + PyArrayObject *arrays[5] = { NULL }; + PyObject *parent_array = NULL; + PyObject *child_array = NULL; + PyObject *order_array = NULL; + PyObject *split_array = NULL; + tsd_id_t *nodes_order = NULL; + tsd_size_t num_nodes, num_split = 0; + npy_intp dims[1]; + int err; + + if (!PyArg_ParseTuple( + args, "OOOOO", &objs[0], &objs[1], &objs[2], &objs[3], &objs[4])) { + goto out; + } + if (parse_arrays(objs, typenums, 1, 5, arrays) != 0) { + goto out; + } + if (check_sizes_equal(arrays, 4) != 0) { + goto out; + } + num_nodes = ARRAY_SIZE(arrays[4]); + dims[0] = PyArray_DIM(arrays[0], 0); + parent_array = PyArray_SimpleNew(1, dims, NPY_INT32); + child_array = PyArray_SimpleNew(1, dims, NPY_INT32); + if (parent_array == NULL || child_array == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_split_disjoint_nodes(num_nodes, ARRAY_SIZE(arrays[0]), + (const tsd_id_t *) PyArray_DATA(arrays[0]), + (const tsd_id_t *) PyArray_DATA(arrays[1]), + (const double *) PyArray_DATA(arrays[2]), + (const double *) PyArray_DATA(arrays[3]), + (const uint8_t *) PyArray_DATA(arrays[4]), + (tsd_id_t *) PyArray_DATA((PyArrayObject *) parent_array), + (tsd_id_t *) PyArray_DATA((PyArrayObject *) child_array), &num_split, + &nodes_order); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + dims[0] = (npy_intp) (num_nodes + num_split); + order_array = array_from_data( + NPY_INT32, 1, dims, nodes_order, (num_nodes + num_split) * sizeof(*nodes_order)); + dims[0] = (npy_intp) num_split; + split_array = array_from_data( + NPY_INT32, 1, dims, nodes_order + num_nodes, num_split * sizeof(*nodes_order)); + if (order_array == NULL || split_array == NULL) { + goto out; + } + ret = Py_BuildValue("OOOO", parent_array, child_array, order_array, split_array); +out: + release_arrays(arrays, 5); + Py_XDECREF(parent_array); + Py_XDECREF(child_array); + Py_XDECREF(order_array); + Py_XDECREF(split_array); + tsd_safe_free(nodes_order); + return ret; +} + +/* + * relabel_mutations_node(mutations_node, mutations_position, nodes_order, + * edges_parent, edges_child, edges_left, edges_right, insert_index, + * remove_index) returns the new node of each mutation. + */ +static PyObject * +tsdate_relabel_mutations_node(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *objs[9]; + const int typenums[9] = { NPY_INT32, NPY_FLOAT64, NPY_INT32, NPY_INT32, NPY_INT32, + NPY_FLOAT64, NPY_FLOAT64, NPY_INT32, NPY_INT32 }; + PyArrayObject *arrays[9] = { NULL }; + PyObject *output = NULL; + npy_intp dims[1]; + int err; + + if (!PyArg_ParseTuple(args, "OOOOOOOOO", &objs[0], &objs[1], &objs[2], &objs[3], + &objs[4], &objs[5], &objs[6], &objs[7], &objs[8])) { + goto out; + } + if (parse_arrays(objs, typenums, 1, 9, arrays) != 0) { + goto out; + } + if (check_sizes_equal(arrays + 3, 6) != 0 || check_sizes_equal(arrays, 2) != 0) { + goto out; + } + dims[0] = PyArray_DIM(arrays[0], 0); + output = PyArray_SimpleNew(1, dims, NPY_INT32); + if (output == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_relabel_mutations_node(ARRAY_SIZE(arrays[2]), ARRAY_SIZE(arrays[3]), + ARRAY_SIZE(arrays[0]), (const tsd_id_t *) PyArray_DATA(arrays[0]), + (const double *) PyArray_DATA(arrays[1]), + (const tsd_id_t *) PyArray_DATA(arrays[2]), + (const tsd_id_t *) PyArray_DATA(arrays[3]), + (const tsd_id_t *) PyArray_DATA(arrays[4]), + (const double *) PyArray_DATA(arrays[5]), + (const double *) PyArray_DATA(arrays[6]), + (const tsd_id_t *) PyArray_DATA(arrays[7]), + (const tsd_id_t *) PyArray_DATA(arrays[8]), + (tsd_id_t *) PyArray_DATA((PyArrayObject *) output)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = output; + output = NULL; +out: + release_arrays(arrays, 9); + Py_XDECREF(output); + return ret; +} + +/* + * constrain_ages(nodes_time, nodes_fixed, edges_parent, edges_child, epsilon, + * max_iterations) returns a new array of node times. + */ +static PyObject * +tsdate_constrain_ages(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *objs[4]; + const int typenums[4] = { NPY_FLOAT64, NPY_BOOL, NPY_INT32, NPY_INT32 }; + PyArrayObject *arrays[4] = { NULL }; + PyObject *output = NULL; + npy_intp dims[1]; + double epsilon; + long long max_iterations; + int err; + + if (!PyArg_ParseTuple(args, "OOOOdL", &objs[0], &objs[1], &objs[2], &objs[3], + &epsilon, &max_iterations)) { + goto out; + } + if (parse_arrays(objs, typenums, 1, 4, arrays) != 0) { + goto out; + } + if (check_sizes_equal(arrays, 2) != 0 || check_sizes_equal(arrays + 2, 2) != 0) { + goto out; + } + dims[0] = PyArray_DIM(arrays[0], 0); + output = PyArray_SimpleNew(1, dims, NPY_FLOAT64); + if (output == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_constrain_ages(ARRAY_SIZE(arrays[0]), ARRAY_SIZE(arrays[2]), + (const double *) PyArray_DATA(arrays[0]), + (const uint8_t *) PyArray_DATA(arrays[1]), + (const tsd_id_t *) PyArray_DATA(arrays[2]), + (const tsd_id_t *) PyArray_DATA(arrays[3]), epsilon, (int64_t) max_iterations, + (double *) PyArray_DATA((PyArrayObject *) output)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = output; + output = NULL; +out: + release_arrays(arrays, 4); + Py_XDECREF(output); + return ret; +} + +/* + * contains_unary_nodes(nodes_mask, edges_parent, edges_left, edges_right, + * indexes_insert, indexes_remove, sequence_length, num_nodes) returns a bool. + */ +static PyObject * +tsdate_contains_unary_nodes(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *objs[6]; + const int typenums[6] + = { NPY_BOOL, NPY_INT32, NPY_FLOAT64, NPY_FLOAT64, NPY_INT32, NPY_INT32 }; + PyArrayObject *arrays[6] = { NULL }; + double sequence_length; + Py_ssize_t num_nodes; + int contains_unary = 0; + int err; + + if (!PyArg_ParseTuple(args, "OOOOOOdn", &objs[0], &objs[1], &objs[2], &objs[3], + &objs[4], &objs[5], &sequence_length, &num_nodes)) { + goto out; + } + if (parse_arrays(objs, typenums, 1, 6, arrays) != 0) { + goto out; + } + if (check_sizes_equal(arrays + 1, 5) != 0) { + goto out; + } + if (num_nodes < 0 || ARRAY_SIZE(arrays[0]) != (tsd_size_t) num_nodes) { + PyErr_SetString( + PyExc_ValueError, "Mask size does not match the number of nodes"); + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_contains_unary_nodes((tsd_size_t) num_nodes, ARRAY_SIZE(arrays[1]), + (const uint8_t *) PyArray_DATA(arrays[0]), + (const tsd_id_t *) PyArray_DATA(arrays[1]), + (const double *) PyArray_DATA(arrays[2]), + (const double *) PyArray_DATA(arrays[3]), + (const tsd_id_t *) PyArray_DATA(arrays[4]), + (const tsd_id_t *) PyArray_DATA(arrays[5]), sequence_length, &contains_unary); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = PyBool_FromLong(contains_unary); +out: + release_arrays(arrays, 6); + return ret; +} + +/* marginalize_over_ancestors(val): val has at least two rows. */ +static PyObject * +tsdate_marginalize_over_ancestors(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *val_obj = NULL; + PyArrayObject *val_array = NULL; + PyObject *output = NULL; + npy_intp dims[2]; + int err; + + if (!PyArg_ParseTuple(args, "O", &val_obj)) { + goto out; + } + val_array = (PyArrayObject *) PyArray_FROMANY( + val_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (val_array == NULL) { + goto out; + } + if (ARRAY_DIM(val_array, 0) < 2) { + PyErr_SetString(PyExc_ValueError, "At least two tips are required"); + goto out; + } + dims[0] = PyArray_DIM(val_array, 0) + 1; + dims[1] = PyArray_DIM(val_array, 1); + output = PyArray_SimpleNew(2, dims, NPY_FLOAT64); + if (output == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_marginalize_over_ancestors(ARRAY_DIM(val_array, 0), + ARRAY_DIM(val_array, 1), (const double *) PyArray_DATA(val_array), + (double *) PyArray_DATA((PyArrayObject *) output)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = output; + output = NULL; +out: + Py_XDECREF(val_array); + Py_XDECREF(output); + return ret; +} + +/* conditional_coalescent_variance(num_tips): an array of num_tips + 1 variances. */ +static PyObject * +tsdate_conditional_coalescent_variance(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *output = NULL; + Py_ssize_t num_tips; + npy_intp dims[1]; + int err; + + if (!PyArg_ParseTuple(args, "n", &num_tips)) { + goto out; + } + if (num_tips < 1) { + PyErr_SetString(PyExc_ValueError, "The number of tips must be positive"); + goto out; + } + dims[0] = (npy_intp) num_tips + 1; + output = PyArray_SimpleNew(1, dims, NPY_FLOAT64); + if (output == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_conditional_coalescent_variance( + (tsd_size_t) num_tips, (double *) PyArray_DATA((PyArrayObject *) output)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = output; + output = NULL; +out: + Py_XDECREF(output); + return ret; +} + static PyMethodDef tsdate_methods[] = { { "strerror", (PyCFunction) tsdate_strerror, METH_VARARGS, "Return the message for a library error code." }, @@ -639,6 +1235,25 @@ static PyMethodDef tsdate_methods[] = { { "average_gammas", (PyCFunction) tsdate_average_gammas, METH_VARARGS, "Natural parameters of the gamma averaging the sufficient statistics of an " "array of gammas, given as natural parameters." }, + { "block_singletons", (PyCFunction) tsdate_block_singletons, METH_VARARGS, + "Group the singletons of unphased individuals into blocks." }, + { "reallocate_unphased", (PyCFunction) tsdate_reallocate_unphased, METH_VARARGS, + "Reallocate the likelihood of unphased blocks, in place." }, + { "mutation_frequency", (PyCFunction) tsdate_mutation_frequency, METH_VARARGS, + "The number of members of each sample set below each mutation." }, + { "split_disjoint_nodes", (PyCFunction) tsdate_split_disjoint_nodes, METH_VARARGS, + "Split disconnected regions of nodes into separate nodes." }, + { "relabel_mutations_node", (PyCFunction) tsdate_relabel_mutations_node, + METH_VARARGS, "The new node of each mutation, after splitting nodes." }, + { "constrain_ages", (PyCFunction) tsdate_constrain_ages, METH_VARARGS, + "Constrain node ages to be consistent with the edges." }, + { "contains_unary_nodes", (PyCFunction) tsdate_contains_unary_nodes, METH_VARARGS, + "Whether any unmasked node has a single child in some tree." }, + { "marginalize_over_ancestors", (PyCFunction) tsdate_marginalize_over_ancestors, + METH_VARARGS, "Integrate an expectation over counts of extant ancestors." }, + { "conditional_coalescent_variance", + (PyCFunction) tsdate_conditional_coalescent_variance, METH_VARARGS, + "Variance of node age given the number of descendant leaves." }, { NULL } /* Sentinel */ }; diff --git a/evaluation/microbench.py b/evaluation/microbench.py index f54a37c8..fe10e278 100644 --- a/evaluation/microbench.py +++ b/evaluation/microbench.py @@ -85,7 +85,19 @@ def _c_impl(): ``name: callable`` (taking the arguments of the numba function of that name); the functions that are missing are skipped in the benchmarks. """ - return {} + import _tsdate + + return { + "_block_singletons": _tsdate.block_singletons, + "reallocate_unphased": _tsdate.reallocate_unphased, + "_mutation_frequency": _tsdate.mutation_frequency, + "_split_disjoint_nodes": _tsdate.split_disjoint_nodes, + "_relabel_mutations_node": _tsdate.relabel_mutations_node, + "_constrain_ages": _tsdate.constrain_ages, + "_contains_unary_nodes": _tsdate.contains_unary_nodes, + "_marginalize_over_ancestors": _tsdate.marginalize_over_ancestors, + "conditional_coalescent_variance": _tsdate.conditional_coalescent_variance, + } # The seam for adding implementations: name -> {function name -> callable}. A diff --git a/lib/err.c b/lib/err.c index 6336d832..b8e628b0 100644 --- a/lib/err.c +++ b/lib/err.c @@ -80,6 +80,25 @@ tsd_strerror(int err) case TSD_ERR_INVALID_FIXED_AGE: ret = "The age of a fixed node is outside the domain of the function"; break; + case TSD_ERR_UNPHASED_INDIVIDUAL_EDGES: + ret = "An unphased individual does not have exactly two edges over each " + "of its blocks"; + break; + case TSD_ERR_BLOCK_OUT_OF_RANGE: + ret = "A block or an edge of a block is out of range"; + break; + case TSD_ERR_PHASE_OUT_OF_RANGE: + ret = "The phase of a mutation is not between zero and one"; + break; + case TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED: + ret = "The total likelihood of the unphased edges is not conserved"; + break; + case TSD_ERR_MUTATION_NODE_NOT_IN_TREE: + ret = "A mutation is above a node that is not in any tree before it"; + break; + case TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT: + ret = "An edge between two fixed nodes violates the age constraint"; + break; default: break; } diff --git a/lib/err.h b/lib/err.h index c323ddaf..25f30dad 100644 --- a/lib/err.h +++ b/lib/err.h @@ -55,6 +55,16 @@ extern "C" { /* approx: violated preconditions (numba asserts) */ #define TSD_ERR_NONPOSITIVE_MOMENTS -14 #define TSD_ERR_INVALID_FIXED_AGE -15 + +/* phasing */ +#define TSD_ERR_UNPHASED_INDIVIDUAL_EDGES -16 +#define TSD_ERR_BLOCK_OUT_OF_RANGE -17 +#define TSD_ERR_PHASE_OUT_OF_RANGE -18 +#define TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED -19 + +/* util */ +#define TSD_ERR_MUTATION_NODE_NOT_IN_TREE -20 +#define TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT -21 /* clang-format on */ #ifdef __GNUC__ diff --git a/lib/meson.build b/lib/meson.build index 9affad84..a418bd66 100644 --- a/lib/meson.build +++ b/lib/meson.build @@ -15,7 +15,8 @@ if get_option('buildtype') == 'debug' extra_c_args += ['-DTSD_TRACE_ERRORS'] endif -tsdate_sources = ['err.c', 'hypergeo.c', 'approx.c'] +tsdate_sources = ['err.c', 'hypergeo.c', 'approx.c', + 'phasing.c', 'util.c', 'prior.c'] tsdate_lib = static_library('tsdate', sources: tsdate_sources, dependencies: [m_dep], diff --git a/lib/phasing.c b/lib/phasing.c new file mode 100644 index 00000000..0aab33b1 --- /dev/null +++ b/lib/phasing.c @@ -0,0 +1,427 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* + * Phasing of singleton mutations in unphased individuals, ported from + * tsdate/phasing.py (numba). + */ + +#include +#include +#include + +#include "mathutil.h" +#include "tsdate.h" + +/* The state of the sweep over trees that assigns singletons to blocks. */ +typedef struct { + const uint8_t *individuals_unphased; + const tsd_id_t *nodes_individual; + const tsd_id_t *edges_child; + tsd_id_t *individuals_edges; /* two edges per individual */ + double *individuals_position; + double *individuals_singletons; + tsd_id_t *individuals_block; + double *blocks_stats; + tsd_id_t *blocks_edges; + tsd_size_t num_blocks; + tsd_size_t num_flushed; +} block_state_t; + +/* An edge ends: if its individual then has a single edge, the block is complete. */ +static void +block_edge_out(block_state_t *state, tsd_id_t e, double left) +{ + const tsd_id_t i = state->nodes_individual[state->edges_child[e]]; + tsd_id_t *edges; + tsd_id_t s, block; + + if (i == TSD_NULL || !state->individuals_unphased[i]) { + return; + } + edges = state->individuals_edges + 2 * i; + tsd_bug_assert(edges[0] == e || edges[1] == e); + s = edges[1] == e ? edges[0] : edges[1]; + edges[0] = s; + edges[1] = TSD_NULL; + if (s != TSD_NULL) { + block = state->individuals_block[i]; + tsd_bug_assert(block != TSD_NULL); + state->blocks_edges[2 * block] = e; + state->blocks_edges[2 * block + 1] = s; + state->blocks_stats[2 * block] = state->individuals_singletons[i]; + state->blocks_stats[2 * block + 1] = left - state->individuals_position[i]; + state->num_flushed++; + state->individuals_position[i] = NAN; + state->individuals_block[i] = TSD_NULL; + state->individuals_singletons[i] = 0.0; + } +} + +/* An edge starts: it becomes an edge of its individual, and may start a block. */ +static int +block_edge_in(block_state_t *state, tsd_id_t e, double left) +{ + int ret = 0; + const tsd_id_t i = state->nodes_individual[state->edges_child[e]]; + tsd_id_t *edges; + tsd_id_t u, v; + + if (i == TSD_NULL || !state->individuals_unphased[i]) { + goto out; + } + edges = state->individuals_edges + 2 * i; + u = edges[0]; + v = edges[1]; + if (u != TSD_NULL && v != TSD_NULL) { + ret = tsd_trace_error(TSD_ERR_UNPHASED_INDIVIDUAL_EDGES); + goto out; + } + edges[0] = e; + edges[1] = v > u ? v : u; + state->individuals_position[i] = left; + if (state->individuals_block[i] == TSD_NULL) { + state->individuals_block[i] = (tsd_id_t) state->num_blocks; + state->num_blocks++; + } +out: + return ret; +} + +/* + * Group the singleton mutations of unphased individuals into blocks: the regions over + * which both haplotype edges of an individual are unchanged. A mutation's block is its + * individual's block at its position, or TSD_NULL. + * + * Writes `mutations_block` (one id per mutation) and allocates `blocks_stats` (rows of + * the number of singletons and the span of each block) and `blocks_edges` (rows of + * the two edges of each block), both `*num_blocks` rows, indexed by block id. The + * caller frees them. + */ +int +tsd_block_singletons(tsd_size_t num_individuals, tsd_size_t num_edges, + tsd_size_t num_mutations, const uint8_t *individuals_unphased, + const tsd_id_t *nodes_individual, const tsd_id_t *mutations_node, + const double *mutations_position, const tsd_id_t *edges_child, + const double *edges_left, const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length, tsd_size_t *num_blocks, + double **blocks_stats, tsd_id_t **blocks_edges, tsd_id_t *mutations_block) +{ + int ret = 0; + block_state_t state; + tsd_id_t *indexes_mutation = NULL; + tsd_id_t *individuals_edges = NULL; + tsd_id_t *individuals_block = NULL; + double *individuals_position = NULL; + double *individuals_singletons = NULL; + double *stats = NULL; + tsd_id_t *block_edges = NULL; + const tsd_size_t num_rows = num_edges > 0 ? num_edges : 1; + const tsd_size_t num_ind = num_individuals > 0 ? num_individuals : 1; + tsd_size_t a, b, d, j; + tsd_id_t m, i; + double left, right; + + indexes_mutation + = malloc((num_mutations > 0 ? num_mutations : 1) * sizeof(tsd_id_t)); + individuals_edges = malloc(2 * num_ind * sizeof(*individuals_edges)); + individuals_block = malloc(num_ind * sizeof(*individuals_block)); + individuals_position = malloc(num_ind * sizeof(*individuals_position)); + individuals_singletons = malloc(num_ind * sizeof(*individuals_singletons)); + stats = malloc(2 * num_rows * sizeof(*stats)); + block_edges = malloc(2 * num_rows * sizeof(*block_edges)); + if (indexes_mutation == NULL || individuals_edges == NULL + || individuals_block == NULL || individuals_position == NULL + || individuals_singletons == NULL || stats == NULL || block_edges == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + ret = tsd_argsort(num_mutations, mutations_position, indexes_mutation); + if (ret != 0) { + goto out; + } + for (j = 0; j < num_individuals; j++) { + individuals_edges[2 * j] = TSD_NULL; + individuals_edges[2 * j + 1] = TSD_NULL; + individuals_block[j] = TSD_NULL; + individuals_position[j] = NAN; + individuals_singletons[j] = 0.0; + } + for (j = 0; j < num_mutations; j++) { + mutations_block[j] = TSD_NULL; + } + + state.individuals_unphased = individuals_unphased; + state.nodes_individual = nodes_individual; + state.edges_child = edges_child; + state.individuals_edges = individuals_edges; + state.individuals_position = individuals_position; + state.individuals_singletons = individuals_singletons; + state.individuals_block = individuals_block; + state.blocks_stats = stats; + state.blocks_edges = block_edges; + state.num_blocks = 0; + state.num_flushed = 0; + + a = 0; + b = 0; + d = 0; + left = 0.0; + while (a < num_edges || b < num_edges) { + while (b < num_edges && edges_right[indexes_remove[b]] == left) { + block_edge_out(&state, indexes_remove[b], left); + b++; + } + while (a < num_edges && edges_left[indexes_insert[a]] == left) { + ret = block_edge_in(&state, indexes_insert[a], left); + if (ret != 0) { + goto out; + } + a++; + } + right = sequence_length; + if (b < num_edges) { + right = tsd_min(right, edges_right[indexes_remove[b]]); + } + if (a < num_edges) { + right = tsd_min(right, edges_left[indexes_insert[a]]); + } + left = right; + while (d < num_mutations && mutations_position[indexes_mutation[d]] < right) { + m = indexes_mutation[d]; + i = nodes_individual[mutations_node[m]]; + if (i != TSD_NULL && individuals_unphased[i]) { + mutations_block[m] = individuals_block[i]; + individuals_singletons[i] += 1.0; + } + d++; + } + } + /* Every block must have been completed */ + if (state.num_blocks != state.num_flushed) { + ret = tsd_trace_error(TSD_ERR_UNPHASED_INDIVIDUAL_EDGES); + goto out; + } + *num_blocks = state.num_blocks; + *blocks_stats = stats; + *blocks_edges = block_edges; + stats = NULL; + block_edges = NULL; +out: + tsd_safe_free(indexes_mutation); + tsd_safe_free(individuals_edges); + tsd_safe_free(individuals_block); + tsd_safe_free(individuals_position); + tsd_safe_free(individuals_singletons); + tsd_safe_free(stats); + tsd_safe_free(block_edges); + return ret; +} + +/* The sum of the first column of the likelihoods of the flagged edges. */ +static double +sum_flagged_likelihoods( + tsd_size_t num_edges, const double *edges_likelihood, const uint8_t *edges_unphased) +{ + double total = 0.0; + tsd_size_t e; + + for (e = 0; e < num_edges; e++) { + if (edges_unphased[e]) { + total += edges_likelihood[2 * e]; + } + } + return total; +} + +/* + * Reallocate the likelihood of the edges of unphased blocks: the mutations in a block + * give each edge of the block its phase probability of a mutation, and the other + * edge the remainder. `edges_likelihood` has two columns and is updated in place. + */ +int +tsd_reallocate_unphased(tsd_size_t num_edges, tsd_size_t num_mutations, + tsd_size_t num_blocks, const double *mutations_phase, + const tsd_id_t *mutations_block, const tsd_id_t *blocks_edges, + double *edges_likelihood) +{ + int ret = 0; + uint8_t *edges_unphased = NULL; + tsd_size_t m, e, j; + tsd_id_t b, i, k; + double num_unphased, phase; + + edges_unphased = calloc(num_edges > 0 ? num_edges : 1, sizeof(*edges_unphased)); + if (edges_unphased == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + /* Edges that are not in range are caught below, if a mutation refers to them */ + for (j = 0; j < 2 * num_blocks; j++) { + e = (tsd_size_t) blocks_edges[j]; + if (blocks_edges[j] > TSD_NULL && e < num_edges) { + edges_unphased[e] = 1; + } + } + num_unphased = sum_flagged_likelihoods(num_edges, edges_likelihood, edges_unphased); + for (e = 0; e < num_edges; e++) { + if (edges_unphased[e]) { + edges_likelihood[2 * e] = 0.0; + } + } + + for (m = 0; m < num_mutations; m++) { + b = mutations_block[m]; + if (b == TSD_NULL) { + continue; + } + if (b < 0 || (tsd_size_t) b >= num_blocks) { + ret = tsd_trace_error(TSD_ERR_BLOCK_OUT_OF_RANGE); + goto out; + } + i = blocks_edges[2 * b]; + k = blocks_edges[2 * b + 1]; + if (i <= TSD_NULL || (tsd_size_t) i >= num_edges || k <= TSD_NULL + || (tsd_size_t) k >= num_edges) { + ret = tsd_trace_error(TSD_ERR_BLOCK_OUT_OF_RANGE); + goto out; + } + phase = mutations_phase[m]; + if (isnan(phase)) { /* TODO (numba): fix rare numerical issue */ + continue; + } + if (!(phase >= 0.0 && phase <= 1.0)) { + ret = tsd_trace_error(TSD_ERR_PHASE_OUT_OF_RANGE); + goto out; + } + edges_likelihood[2 * i] += phase; + edges_likelihood[2 * k] += 1 - phase; + } + if (!tsd_isclose(num_unphased, + sum_flagged_likelihoods(num_edges, edges_likelihood, edges_unphased))) { + ret = tsd_trace_error(TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED); + goto out; + } +out: + tsd_safe_free(edges_unphased); + return ret; +} + +/* The number of members of each sample set below each mutation, for each tree. */ +int +tsd_mutation_frequency(tsd_size_t num_nodes, tsd_size_t num_sample_sets, + tsd_size_t num_edges, tsd_size_t num_mutations, const uint8_t *nodes_sample, + const tsd_id_t *mutations_node, const double *mutations_position, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, const double *edges_left, + const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length, int32_t *mutations_freq) +{ + int ret = 0; + tsd_id_t *indexes_mutation = NULL; + tsd_id_t *nodes_parent = NULL; + int32_t *nodes_samples = NULL; + const tsd_size_t S = num_sample_sets; + tsd_size_t a, b, d, j, k; + tsd_id_t e, p, c, m; + double left, right; + + indexes_mutation + = malloc((num_mutations > 0 ? num_mutations : 1) * sizeof(tsd_id_t)); + nodes_parent = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*nodes_parent)); + nodes_samples = malloc((num_nodes * S > 0 ? num_nodes * S : 1) * sizeof(int32_t)); + if (indexes_mutation == NULL || nodes_parent == NULL || nodes_samples == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + ret = tsd_argsort(num_mutations, mutations_position, indexes_mutation); + if (ret != 0) { + goto out; + } + for (j = 0; j < num_nodes; j++) { + nodes_parent[j] = TSD_NULL; + for (k = 0; k < S; k++) { + nodes_samples[j * S + k] = nodes_sample[j * S + k] ? 1 : 0; + } + } + for (j = 0; j < num_mutations * S; j++) { + mutations_freq[j] = 0; + } + + a = 0; + b = 0; + d = 0; + left = 0.0; + while (a < num_edges || b < num_edges) { + while (b < num_edges && edges_right[indexes_remove[b]] == left) { /* out */ + e = indexes_remove[b]; + p = edges_parent[e]; + c = edges_child[e]; + nodes_parent[c] = TSD_NULL; + while (p != TSD_NULL) { + for (k = 0; k < S; k++) { + nodes_samples[(tsd_size_t) p * S + k] + -= nodes_samples[(tsd_size_t) c * S + k]; + } + p = nodes_parent[p]; + } + b++; + } + while (a < num_edges && edges_left[indexes_insert[a]] == left) { /* in */ + e = indexes_insert[a]; + p = edges_parent[e]; + c = edges_child[e]; + nodes_parent[c] = p; + while (p != TSD_NULL) { + for (k = 0; k < S; k++) { + nodes_samples[(tsd_size_t) p * S + k] + += nodes_samples[(tsd_size_t) c * S + k]; + } + p = nodes_parent[p]; + } + a++; + } + right = sequence_length; + if (b < num_edges) { + right = tsd_min(right, edges_right[indexes_remove[b]]); + } + if (a < num_edges) { + right = tsd_min(right, edges_left[indexes_insert[a]]); + } + left = right; + while (d < num_mutations && mutations_position[indexes_mutation[d]] < right) { + m = indexes_mutation[d]; + c = mutations_node[m]; + for (k = 0; k < S; k++) { + mutations_freq[(tsd_size_t) m * S + k] + = nodes_samples[(tsd_size_t) c * S + k]; + } + d++; + } + } +out: + tsd_safe_free(indexes_mutation); + tsd_safe_free(nodes_parent); + tsd_safe_free(nodes_samples); + return ret; +} diff --git a/lib/prior.c b/lib/prior.c new file mode 100644 index 00000000..cfbfd58d --- /dev/null +++ b/lib/prior.c @@ -0,0 +1,163 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* + * Moments of node ages under the coalescent, conditional on the number of descendant + * leaves, ported from tsdate/prior.py (numba). Operation order and libm calls follow + * the numba code so that results agree to the last bit or two. + */ + +#include +#include + +#include "mathutil.h" +#include "tsdate.h" + +/* + * Integrate an expectation over counts of extant ancestors. In a tree with "n" tips, + * the probability that there are "a" extant ancestors when a subtree of size "k" + * coalesces is hypergeometric-ish (Wuif & Donnelly 1998), and may be calculated + * recursively over increasing "a" and decreasing "k" (e.g. using recursive + * relationships for binomial coefficients). + * + * `val` has `num_tips` (at least two) rows and `num_moments` columns; `out` has + * `num_tips + 1` rows and is written in full. + */ +int +tsd_marginalize_over_ancestors( + tsd_size_t num_tips, tsd_size_t num_moments, const double *val, double *out) +{ + int ret = 0; + double *pr_a_ln = NULL; /* log Pr(a | k, n) */ + const tsd_size_t n = num_tips; + const tsd_size_t N = num_moments; + tsd_size_t k, a, j; + double dk, dnk, dnak, weight, constant; + + tsd_bug_assert(num_tips >= 2); + pr_a_ln = malloc((n + 1) * sizeof(*pr_a_ln)); + if (pr_a_ln == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + for (j = 0; j < (n + 1) * N; j++) { + out[j] = 0.0; + } + pr_a_ln[0] = NAN; + pr_a_ln[1] = NAN; + pr_a_ln[2] = 0.0; + for (k = n - 1; k > 1; k--) { + dk = (double) k; + dnk = (double) (n - k); + /* log(0) at k == 2 is -infinity, and the value is unused then */ + constant = log(dnk) + log((double) (k - 2)) - log(dk + 1); + for (a = 2; a < n - k + 2; a++) { + weight = exp(pr_a_ln[a]); + for (j = 0; j < N; j++) { + out[k * N + j] += weight * val[a * N + j]; + } + if (k > 2) { /* Pr(a | k, n) to Pr(a | k - 1, n) */ + dnak = (double) (n - a - k + 2); + pr_a_ln[a] += constant - log(dnak); + } + } + if (k > 2) { /* Pr(n - k + 1 | k - 1, n) to Pr(n - k + 2 | k - 1, n) */ + pr_a_ln[n - k + 2] = pr_a_ln[n - k + 1] + log((double) (n - k + 2)) + - log(dk + 1) - constant; + } + } + for (j = 0; j < N; j++) { + out[n * N + j] = val[N + j]; + } +out: + tsd_safe_free(pr_a_ln); + return ret; +} + +/* + * Variance of node age conditional on the number of descendant leaves, under the + * standard coalescent. Writes `num_tips + 1` values, indexed by the number of + * descendant leaves. (For a single tip the numba code reads out of bounds; the + * variances are zero.) + */ +int +tsd_conditional_coalescent_variance(tsd_size_t num_tips, double *variance_out) +{ + int ret = 0; + double *mean = NULL; + double *variance = NULL; + double *val = NULL; + double *moments = NULL; + tsd_size_t i, n; + double rate; + + tsd_bug_assert(num_tips >= 1); + n = num_tips; + if (n == 1) { + variance_out[0] = 0.0; + variance_out[1] = 0.0; + goto out; + } + mean = malloc(n * sizeof(*mean)); + variance = malloc(n * sizeof(*variance)); + val = malloc(2 * n * sizeof(*val)); + moments = malloc(2 * (n + 1) * sizeof(*moments)); + if (mean == NULL || variance == NULL || val == NULL || moments == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + /* coalescence rates, indexed by the number of lineages minus one */ + for (i = 0; i < n; i++) { + rate = 0.0; + if (i > 0) { + rate = 2.0 / (double) ((i + 1) * i); + } + mean[i] = rate; + variance[i] = rate * rate; + } + /* hypoexponential mean and variance; e.g. conditional on the number of extant + * ancestors when the node coalesces, the expected time of coalescence is the sum + * of exponential RVs (Wuif and Donnelly 1998) */ + for (i = n - 2; i > 0; i--) { + mean[i] += mean[i + 1]; + variance[i] += variance[i + 1]; + } + for (i = 0; i < n; i++) { + val[2 * i] = mean[i]; + val[2 * i + 1] = variance[i] + mean[i] * mean[i]; + } + ret = tsd_marginalize_over_ancestors(n, 2, val, moments); + if (ret != 0) { + goto out; + } + for (i = 0; i <= n; i++) { + variance_out[i] = moments[2 * i + 1] - moments[2 * i] * moments[2 * i]; + } +out: + tsd_safe_free(mean); + tsd_safe_free(variance); + tsd_safe_free(val); + tsd_safe_free(moments); + return ret; +} diff --git a/lib/tests/tests.c b/lib/tests/tests.c index 49e1a423..609a3d99 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -45,7 +45,10 @@ test_strerror(void) TSD_ERR_KL_MAX_ITERATIONS, TSD_ERR_KL_INVALID_SHAPE, TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS, TSD_ERR_UNSORTED_QUANTILES, TSD_ERR_QUANTILE_MAX_ITERATIONS, TSD_ERR_NEGATIVE_SHAPE, - TSD_ERR_NONPOSITIVE_MOMENTS, TSD_ERR_INVALID_FIXED_AGE }; + TSD_ERR_NONPOSITIVE_MOMENTS, TSD_ERR_INVALID_FIXED_AGE, + TSD_ERR_UNPHASED_INDIVIDUAL_EDGES, TSD_ERR_BLOCK_OUT_OF_RANGE, + TSD_ERR_PHASE_OUT_OF_RANGE, TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED, + TSD_ERR_MUTATION_NODE_NOT_IN_TREE, TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT }; const int num_codes = (int) (sizeof(codes) / sizeof(codes[0])); const char *msg_i; const char *msg_j; @@ -676,6 +679,244 @@ test_mutation_moments(void) tsd_mutation_block_moments(2, 0, &pr, &mn, &va), TSD_ERR_INVALID_FIXED_AGE); } +/* Two samples in each of two individuals below a root: 0, 1 | 2, 3 | root 4 */ +static const tsd_id_t phase_nodes_individual[] = { 0, 0, 1, 1, TSD_NULL }; +static const tsd_id_t phase_edges_parent[] = { 4, 4, 4, 4 }; +static const tsd_id_t phase_edges_child[] = { 0, 1, 2, 3 }; +static const double phase_edges_left[] = { 0, 0, 0, 0 }; +static const double phase_edges_right[] = { 10, 10, 10, 10 }; +static const tsd_id_t phase_order[] = { 0, 1, 2, 3 }; + +static void +test_block_singletons(void) +{ + const uint8_t unphased[] = { 1, 1 }; + const tsd_id_t mutations_node[] = { 0, 4, 2 }; + const double mutations_position[] = { 5, 1, 2 }; + const tsd_id_t child_missing[] = { 0, 2, 3, 3 }; + tsd_id_t mutations_block[3]; + tsd_id_t *blocks_edges = NULL; + double *blocks_stats = NULL; + tsd_size_t num_blocks = 0; + int ret; + + ret = tsd_block_singletons(2, 4, 3, unphased, phase_nodes_individual, mutations_node, + mutations_position, phase_edges_child, phase_edges_left, phase_edges_right, + phase_order, phase_order, 10.0, &num_blocks, &blocks_stats, &blocks_edges, + mutations_block); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(num_blocks, 2); + CU_ASSERT_EQUAL(mutations_block[0], 0); + CU_ASSERT_EQUAL(mutations_block[1], TSD_NULL); + CU_ASSERT_EQUAL(mutations_block[2], 1); + CU_ASSERT_EQUAL(blocks_stats[0], 1.0); + CU_ASSERT_EQUAL(blocks_stats[1], 10.0); + tsd_safe_free(blocks_stats); + tsd_safe_free(blocks_edges); + + /* A haplotype edge is missing: the block is never completed */ + ret = tsd_block_singletons(2, 4, 3, unphased, phase_nodes_individual, mutations_node, + mutations_position, child_missing, phase_edges_left, phase_edges_right, + phase_order, phase_order, 10.0, &num_blocks, &blocks_stats, &blocks_edges, + mutations_block); + CU_ASSERT_EQUAL(ret, TSD_ERR_UNPHASED_INDIVIDUAL_EDGES); + CU_ASSERT_PTR_NULL(blocks_stats); + + /* No edges and no individuals */ + ret = tsd_block_singletons(0, 0, 0, unphased, phase_nodes_individual, mutations_node, + mutations_position, phase_edges_child, phase_edges_left, phase_edges_right, + phase_order, phase_order, 10.0, &num_blocks, &blocks_stats, &blocks_edges, + mutations_block); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(num_blocks, 0); + tsd_safe_free(blocks_stats); + tsd_safe_free(blocks_edges); +} + +static void +test_reallocate_unphased(void) +{ + const tsd_id_t blocks_edges[] = { 0, 1 }; + const tsd_id_t mutations_block[] = { 0, TSD_NULL }; + const tsd_id_t mutations_block_bad[] = { 1, 0 }; + const tsd_id_t blocks_edges_bad[] = { 0, 7 }; + const double phase[] = { 0.25, NAN }; + const double phase_bad[] = { 1.5, 0.0 }; + const double phase_nan[] = { NAN, 0.0 }; + const double initial[] = { 1.0, 5.0, 0.0, 5.0 }; + double likelihood[4]; + int ret; + + memcpy(likelihood, initial, sizeof(initial)); + ret = tsd_reallocate_unphased( + 2, 2, 1, phase, mutations_block, blocks_edges, likelihood); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_DOUBLE_EQUAL(likelihood[0], 0.25, 1e-12); + CU_ASSERT_DOUBLE_EQUAL(likelihood[2], 0.75, 1e-12); + memcpy(likelihood, initial, sizeof(initial)); + ret = tsd_reallocate_unphased( + 2, 2, 1, phase_bad, mutations_block, blocks_edges, likelihood); + CU_ASSERT_EQUAL(ret, TSD_ERR_PHASE_OUT_OF_RANGE); + /* The mass of the skipped mutation is not allocated */ + memcpy(likelihood, initial, sizeof(initial)); + ret = tsd_reallocate_unphased( + 2, 2, 1, phase_nan, mutations_block, blocks_edges, likelihood); + CU_ASSERT_EQUAL(ret, TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED); + memcpy(likelihood, initial, sizeof(initial)); + ret = tsd_reallocate_unphased( + 2, 2, 1, phase, mutations_block_bad, blocks_edges, likelihood); + CU_ASSERT_EQUAL(ret, TSD_ERR_BLOCK_OUT_OF_RANGE); + memcpy(likelihood, initial, sizeof(initial)); + ret = tsd_reallocate_unphased( + 2, 2, 1, phase, mutations_block, blocks_edges_bad, likelihood); + CU_ASSERT_EQUAL(ret, TSD_ERR_BLOCK_OUT_OF_RANGE); +} + +static void +test_mutation_frequency(void) +{ + const uint8_t nodes_sample[] = { 1, 1, 0, 0, 0 }; + const tsd_id_t mutations_node[] = { 4, 0 }; + const double mutations_position[] = { 5, 1 }; + int32_t freq[2]; + int ret; + + ret = tsd_mutation_frequency(5, 1, 4, 2, nodes_sample, mutations_node, + mutations_position, phase_edges_parent, phase_edges_child, phase_edges_left, + phase_edges_right, phase_order, phase_order, 10.0, freq); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(freq[0], 2); + CU_ASSERT_EQUAL(freq[1], 1); +} + +static void +test_split_and_relabel(void) +{ + /* Node 1 has edges over [0, 2) and [4, 6): split into node 1 and a copy, 3 */ + const tsd_id_t parent[] = { 2, 2, 2 }; + const tsd_id_t child[] = { 0, 1, 1 }; + const double left[] = { 0, 0, 4 }; + const double right[] = { 6, 2, 6 }; + const uint8_t excluded[] = { 1, 0, 0 }; + const tsd_id_t insert[] = { 0, 1, 2 }; + const tsd_id_t remove[] = { 1, 0, 2 }; + const tsd_id_t mutations_node[] = { 1, 1 }; + const double mutations_position[] = { 1, 5 }; + tsd_id_t new_parent[3], new_child[3], output[2]; + tsd_id_t *nodes_order = NULL; + tsd_size_t num_split = 0; + int ret; + + ret = tsd_split_disjoint_nodes(3, 3, parent, child, left, right, excluded, + new_parent, new_child, &num_split, &nodes_order); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(num_split, 1); + CU_ASSERT_EQUAL(nodes_order[3], 1); + CU_ASSERT_EQUAL(new_child[2], 3); + ret = tsd_relabel_mutations_node(4, 3, 2, mutations_node, mutations_position, + nodes_order, new_parent, new_child, left, right, insert, remove, output); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(output[0], 1); + CU_ASSERT_EQUAL(output[1], 3); + /* A mutation above a node that is not in any tree */ + { + const tsd_id_t absent[] = { 3, 3 }; + + ret = tsd_relabel_mutations_node(4, 3, 2, absent, mutations_position, + nodes_order, new_parent, new_child, left, right, insert, remove, output); + CU_ASSERT_EQUAL(ret, TSD_ERR_MUTATION_NODE_NOT_IN_TREE); + } + /* No edges: the mutations are not reached */ + ret = tsd_relabel_mutations_node(4, 0, 2, mutations_node, mutations_position, + nodes_order, new_parent, new_child, left, right, insert, remove, output); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(output[1], TSD_NULL); + tsd_safe_free(nodes_order); +} + +static void +test_constrain_ages(void) +{ + const double times[] = { 0.0, 1.0, 0.5 }; + const uint8_t fixed[] = { 1, 1, 0 }; + const uint8_t all_fixed[] = { 1, 1, 1 }; + const uint8_t free_nodes[] = { 0, 0, 0 }; + const uint8_t fixed_child[] = { 1, 0, 0 }; + const tsd_id_t parent[] = { 1, 2 }; + const tsd_id_t child[] = { 0, 1 }; + double out[3]; + int ret; + + /* Node 2 is younger than its child, node 1, which is fixed */ + ret = tsd_constrain_ages(3, 2, times, fixed, parent, child, 1e-6, 10, out); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(out[2] > out[1]); + /* Free nodes meet in the middle; a fixed parent or child does not move */ + ret = tsd_constrain_ages(3, 2, times, free_nodes, parent, child, 1e-6, 100, out); + CU_ASSERT_EQUAL(ret, 0); + ret = tsd_constrain_ages(3, 2, times, fixed_child, parent, child, 1e-6, 100, out); + CU_ASSERT_EQUAL(ret, 0); + /* Already consistent */ + ret = tsd_constrain_ages(3, 1, times, fixed, parent, child, 1e-6, 10, out); + CU_ASSERT_EQUAL(ret, 0); + /* Forcing without iterations */ + ret = tsd_constrain_ages(3, 2, times, fixed, parent, child, 1e-6, 0, out); + CU_ASSERT_EQUAL(ret, 0); + { + const double bad[] = { 0.0, 1.0, 0.0 }; + + ret = tsd_constrain_ages(3, 1, bad, all_fixed, child, parent, 1e-6, 10, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT); + } +} + +static void +test_contains_unary_nodes(void) +{ + const uint8_t no_mask[] = { 0, 0, 0, 0, 0 }; + const uint8_t all_mask[] = { 1, 1, 1, 1, 1 }; + const tsd_id_t unary_parent[] = { 4, 3 }; + const double left[] = { 0, 0 }; + const double right[] = { 10, 10 }; + const tsd_id_t order[] = { 0, 1 }; + int contains = -1; + int ret; + + ret = tsd_contains_unary_nodes(5, 4, no_mask, phase_edges_parent, phase_edges_left, + phase_edges_right, phase_order, phase_order, 10.0, &contains); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(contains, 0); + ret = tsd_contains_unary_nodes( + 5, 2, no_mask, unary_parent, left, right, order, order, 10.0, &contains); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(contains, 1); + ret = tsd_contains_unary_nodes( + 5, 2, all_mask, unary_parent, left, right, order, order, 10.0, &contains); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(contains, 0); +} + +static void +test_conditional_coalescent_variance(void) +{ + const double val[] = { 1.0, 2.0, 3.0, 4.0 }; + double out[6], variance[11]; + int ret; + int j; + + ret = tsd_marginalize_over_ancestors(2, 2, val, out); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(out[4], 3.0); + ret = tsd_conditional_coalescent_variance(1, variance); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(variance[1], 0.0); + ret = tsd_conditional_coalescent_variance(10, variance); + CU_ASSERT_EQUAL(ret, 0); + for (j = 2; j <= 10; j++) { + CU_ASSERT(variance[j] > 0.0); + } +} + static void handle_cunit_error(void) { @@ -717,6 +958,13 @@ main(int argc, char **argv) { "test_node_projections", test_node_projections }, { "test_mutation_moments", test_mutation_moments }, { "test_mutation_projections", test_mutation_projections }, + { "test_block_singletons", test_block_singletons }, + { "test_reallocate_unphased", test_reallocate_unphased }, + { "test_mutation_frequency", test_mutation_frequency }, + { "test_split_and_relabel", test_split_and_relabel }, + { "test_constrain_ages", test_constrain_ages }, + { "test_contains_unary_nodes", test_contains_unary_nodes }, + { "test_conditional_coalescent_variance", test_conditional_coalescent_variance }, CU_TEST_INFO_NULL, }; CU_SuiteInfo suites[] = { diff --git a/lib/tsdate.h b/lib/tsdate.h index 50d753bf..add62f59 100644 --- a/lib/tsdate.h +++ b/lib/tsdate.h @@ -178,6 +178,61 @@ int tsd_mutation_sideways_projection(double t_i, const double pars_j[2], int tsd_mutation_block_projection( double t_i, double t_j, double *pr_m, double proj_m[2]); +/* The id of no node, edge, mutation, individual or block. */ +#define TSD_NULL ((tsd_id_t) - 1) + +/* + * Phasing of singletons (phasing.c), tree sequence utilities (util.c) and the + * coalescent prior (prior.c). Flags are arrays of uint8_t (numpy bool); the arrays + * of the edges are those of a tree sequence, with the indexes of the insertion and + * removal orders. Results of unknown size are allocated by the function and freed by + * the caller. + */ +int tsd_argsort(tsd_size_t num_items, const double *keys, tsd_id_t *order); + +int tsd_block_singletons(tsd_size_t num_individuals, tsd_size_t num_edges, + tsd_size_t num_mutations, const uint8_t *individuals_unphased, + const tsd_id_t *nodes_individual, const tsd_id_t *mutations_node, + const double *mutations_position, const tsd_id_t *edges_child, + const double *edges_left, const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length, tsd_size_t *num_blocks, + double **blocks_stats, tsd_id_t **blocks_edges, tsd_id_t *mutations_block); +int tsd_reallocate_unphased(tsd_size_t num_edges, tsd_size_t num_mutations, + tsd_size_t num_blocks, const double *mutations_phase, + const tsd_id_t *mutations_block, const tsd_id_t *blocks_edges, + double *edges_likelihood); +int tsd_mutation_frequency(tsd_size_t num_nodes, tsd_size_t num_sample_sets, + tsd_size_t num_edges, tsd_size_t num_mutations, const uint8_t *nodes_sample, + const tsd_id_t *mutations_node, const double *mutations_position, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, const double *edges_left, + const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length, int32_t *mutations_freq); + +int tsd_split_disjoint_nodes(tsd_size_t num_nodes, tsd_size_t num_edges, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, const double *edges_left, + const double *edges_right, const uint8_t *node_excluded, tsd_id_t *new_parent, + tsd_id_t *new_child, tsd_size_t *num_split, tsd_id_t **nodes_order); +int tsd_relabel_mutations_node(tsd_size_t num_nodes, tsd_size_t num_edges, + tsd_size_t num_mutations, const tsd_id_t *mutations_node, + const double *mutations_position, const tsd_id_t *nodes_order, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, const double *edges_left, + const double *edges_right, const tsd_id_t *insert_index, + const tsd_id_t *remove_index, tsd_id_t *output); +int tsd_constrain_ages(tsd_size_t num_nodes, tsd_size_t num_edges, + const double *nodes_time, const uint8_t *nodes_fixed, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, double epsilon, int64_t max_iterations, + double *out_time); +int tsd_contains_unary_nodes(tsd_size_t num_nodes, tsd_size_t num_edges, + const uint8_t *nodes_mask, const tsd_id_t *edges_parent, const double *edges_left, + const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length, int *contains_unary); + +/* `val` has `num_tips` >= 2 rows; `out` has `num_tips + 1` rows. */ +int tsd_marginalize_over_ancestors( + tsd_size_t num_tips, tsd_size_t num_moments, const double *val, double *out); +/* `variance` has `num_tips + 1` entries; `num_tips` >= 1. */ +int tsd_conditional_coalescent_variance(tsd_size_t num_tips, double *variance); + #ifdef __cplusplus } #endif diff --git a/lib/util.c b/lib/util.c new file mode 100644 index 00000000..b920e585 --- /dev/null +++ b/lib/util.c @@ -0,0 +1,504 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* + * Utilities for the tree sequence tables, ported from tsdate/util.py (numba): splitting + * nodes that are disconnected along the sequence, relabelling mutations accordingly, + * constraining node ages, and a test for unary nodes. + */ + +#include +#include +#include + +#include "mathutil.h" +#include "tsdate.h" + +/* A key with the index it came from. */ +typedef struct { + double key; + tsd_id_t index; +} tsd_sort_item_t; + +/* + * Stable bottom-up merge sort of `items` by key, using `buffer` (the same size) as + * scratch. Written out, rather than using qsort, because the comparison dominates the + * cost of sorting the edges and cannot be inlined through qsort. + */ +static void +sort_items(tsd_size_t num_items, tsd_sort_item_t *items, tsd_sort_item_t *buffer) +{ + tsd_sort_item_t *src = items; + tsd_sort_item_t *dst = buffer; + tsd_sort_item_t *swap; + tsd_size_t width, start, mid, stop, i, j, k; + + for (width = 1; width < num_items; width *= 2) { + for (start = 0; start < num_items; start += 2 * width) { + mid = start + width < num_items ? start + width : num_items; + stop = start + 2 * width < num_items ? start + 2 * width : num_items; + i = start; + j = mid; + for (k = start; k < stop; k++) { + if (i < mid && (j >= stop || !(src[j].key < src[i].key))) { + dst[k] = src[i]; + i++; + } else { + dst[k] = src[j]; + j++; + } + } + } + swap = src; + src = dst; + dst = swap; + } + if (src != items) { + memcpy(items, src, num_items * sizeof(*items)); + } +} + +/* + * The indexes that sort `keys`, ties broken by index (np.argsort, made deterministic: + * the callers do not depend on the order of ties). + */ +int +tsd_argsort(tsd_size_t num_items, const double *keys, tsd_id_t *order) +{ + int ret = 0; + tsd_sort_item_t *items = NULL; + tsd_sort_item_t *buffer = NULL; + const tsd_size_t alloc = num_items > 0 ? num_items : 1; + tsd_size_t j; + + items = malloc(alloc * sizeof(*items)); + buffer = malloc(alloc * sizeof(*buffer)); + if (items == NULL || buffer == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + for (j = 0; j < num_items; j++) { + items[j].key = keys[j]; + items[j].index = (tsd_id_t) j; + } + sort_items(num_items, items, buffer); + for (j = 0; j < num_items; j++) { + order[j] = items[j].index; + } +out: + tsd_safe_free(items); + tsd_safe_free(buffer); + return ret; +} + +/* + * Label the disconnected segments of each non-excluded node along its edges: the + * segment of an edge increases when the edge starts after the previous edges of the + * node have ended. `edges_segments` holds the labels of the parents (first + * `num_edges` entries) and children. + */ +static int +label_node_segments(tsd_size_t num_nodes, tsd_size_t num_edges, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, const double *edges_left, + const double *edges_right, const uint8_t *node_excluded, tsd_id_t *edges_segments, + tsd_id_t *nodes_segments) +{ + int ret = 0; + tsd_id_t *edges_order = NULL; + double *nodes_right = NULL; + tsd_size_t j, k, side; + tsd_id_t e, n; + int new_segment; + + edges_order = malloc((num_edges > 0 ? num_edges : 1) * sizeof(*edges_order)); + nodes_right = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*nodes_right)); + if (edges_order == NULL || nodes_right == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + ret = tsd_argsort(num_edges, edges_left, edges_order); + if (ret != 0) { + goto out; + } + for (j = 0; j < num_nodes; j++) { + nodes_segments[j] = -1; + nodes_right[j] = -INFINITY; + } + for (j = 0; j < 2 * num_edges; j++) { + edges_segments[j] = -1; + } + for (j = 0; j < num_edges; j++) { + e = edges_order[j]; + for (side = 0; side < 2; side++) { + n = side == 0 ? edges_parent[e] : edges_child[e]; + if (node_excluded[n]) { + continue; + } + new_segment = edges_left[e] > nodes_right[n]; + nodes_segments[n] = (tsd_id_t) (nodes_segments[n] + new_segment); + k = side * num_edges + (tsd_size_t) e; + edges_segments[k] = nodes_segments[n]; + nodes_right[n] = tsd_max(nodes_right[n], edges_right[e]); + } + } +out: + tsd_safe_free(edges_order); + tsd_safe_free(nodes_right); + return ret; +} + +/* + * Split disconnected regions of nodes into separate nodes. A node with s + 1 + * disconnected segments gets s copies, numbered from `num_nodes`; the segments after + * the first are relabelled onto the copies. + * + * Writes the relabelled edges to `new_parent` and `new_child`. Allocates + * `*nodes_order`, of length `num_nodes + *num_split`: the identity on the original + * nodes, followed by the original node of each copy (the "split nodes"). The caller + * frees it. + */ +int +tsd_split_disjoint_nodes(tsd_size_t num_nodes, tsd_size_t num_edges, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, const double *edges_left, + const double *edges_right, const uint8_t *node_excluded, tsd_id_t *new_parent, + tsd_id_t *new_child, tsd_size_t *num_split, tsd_id_t **nodes_order) +{ + int ret = 0; + tsd_id_t *edges_segments = NULL; + tsd_id_t *nodes_segments = NULL; + tsd_id_t *nodes_map = NULL; + tsd_id_t *order = NULL; + tsd_size_t j, side, k, total, next; + tsd_id_t s, n, segment, e; + + edges_segments = malloc((2 * num_edges + 1) * sizeof(*edges_segments)); + nodes_segments = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*nodes_segments)); + nodes_map = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*nodes_map)); + if (edges_segments == NULL || nodes_segments == NULL || nodes_map == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + ret = label_node_segments(num_nodes, num_edges, edges_parent, edges_child, + edges_left, edges_right, node_excluded, edges_segments, nodes_segments); + if (ret != 0) { + goto out; + } + + total = 0; + for (j = 0; j < num_nodes; j++) { + if (nodes_segments[j] > 0) { + total += (tsd_size_t) nodes_segments[j]; + } + } + order = malloc((num_nodes + total + 1) * sizeof(*order)); + if (order == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + /* Copies of node j are numbered consecutively, the first being nodes_map[j] */ + next = num_nodes; + for (j = 0; j < num_nodes; j++) { + order[j] = (tsd_id_t) j; + nodes_map[j] = TSD_NULL; + s = nodes_segments[j]; + if (s > 0) { + nodes_map[j] = (tsd_id_t) next; + } + while (s > 0) { + order[next] = (tsd_id_t) j; + next++; + s--; + } + } + + for (e = 0; (tsd_size_t) e < num_edges; e++) { + for (side = 0; side < 2; side++) { + n = side == 0 ? edges_parent[e] : edges_child[e]; + k = side * num_edges + (tsd_size_t) e; + segment = edges_segments[k]; + if (segment > 0) { + segment = (tsd_id_t) (nodes_map[n] + segment - 1); + } else { + segment = n; + } + if (side == 0) { + new_parent[e] = segment; + } else { + new_child[e] = segment; + } + } + } + *num_split = total; + *nodes_order = order; + order = NULL; +out: + tsd_safe_free(edges_segments); + tsd_safe_free(nodes_segments); + tsd_safe_free(nodes_map); + tsd_safe_free(order); + return ret; +} + +/* + * Traverse the trees, maintaining the map from the old to the new id of the nodes in + * the current tree, and write the new node of each mutation. Mutations beyond the + * last edge, which the sweep does not reach, are NULL. + */ +int +tsd_relabel_mutations_node(tsd_size_t num_nodes, tsd_size_t num_edges, + tsd_size_t num_mutations, const tsd_id_t *mutations_node, + const double *mutations_position, const tsd_id_t *nodes_order, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, const double *edges_left, + const double *edges_right, const tsd_id_t *insert_index, + const tsd_id_t *remove_index, tsd_id_t *output) +{ + int ret = 0; + tsd_id_t *nodes_map = NULL; + tsd_size_t a, b, m, j; + tsd_id_t e, c, p; + double left, right, sequence_length; + + nodes_map = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*nodes_map)); + if (nodes_map == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + for (j = 0; j < num_nodes; j++) { + nodes_map[j] = TSD_NULL; + } + for (m = 0; m < num_mutations; m++) { + output[m] = TSD_NULL; + } + + sequence_length = 0.0; + if (num_edges > 0) { + sequence_length = edges_right[remove_index[num_edges - 1]]; + } + a = 0; + b = 0; + m = 0; + left = 0.0; + while (left < sequence_length) { + while (b < num_edges && edges_right[remove_index[b]] == left) { /* edges out */ + b++; + } + while (a < num_edges && edges_left[insert_index[a]] == left) { /* edges in */ + e = insert_index[a]; + c = edges_child[e]; + p = edges_parent[e]; + nodes_map[nodes_order[c]] = c; + nodes_map[nodes_order[p]] = p; + a++; + } + right = sequence_length; + if (b < num_edges) { + right = tsd_min(right, edges_right[remove_index[b]]); + } + if (a < num_edges) { + right = tsd_min(right, edges_left[insert_index[a]]); + } + left = right; + while (m < num_mutations && mutations_position[m] < right) { + if (nodes_map[mutations_node[m]] == TSD_NULL) { + ret = tsd_trace_error(TSD_ERR_MUTATION_NODE_NOT_IN_TREE); + goto out; + } + output[m] = nodes_map[mutations_node[m]]; + m++; + } + } +out: + tsd_safe_free(nodes_map); + return ret; +} + +/* Whether every edge is longer than epsilon, as a vector check of the ages. */ +static int +edges_satisfy_constraint(tsd_size_t num_edges, const double *nodes_time, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, double epsilon) +{ + tsd_size_t e; + double length; + + for (e = 0; e < num_edges; e++) { + length = nodes_time[edges_parent[e]] - nodes_time[edges_child[e]]; + if (!(length > epsilon)) { + return 0; + } + } + return 1; +} + +/* + * Approximate least squares solution to the positive branch length constraint, using + * the method of alternating projections. Loosely based on Dykstra's algorithm: Dykstra + * RL, "An algorithm for restricted least squares regression", JASA 1983. + * + * Writes the constrained ages to `out_time`, which does not alias `nodes_time`. + */ +int +tsd_constrain_ages(tsd_size_t num_nodes, tsd_size_t num_edges, const double *nodes_time, + const uint8_t *nodes_fixed, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, double epsilon, int64_t max_iterations, + double *out_time) +{ + int ret = 0; + double *edges_cavity = NULL; + int64_t iteration; + tsd_size_t e; + tsd_id_t p, c; + double adjustment; + double *cavity; + + edges_cavity = calloc(2 * num_edges + 1, sizeof(*edges_cavity)); + if (edges_cavity == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + memcpy(out_time, nodes_time, num_nodes * sizeof(*out_time)); + + for (iteration = 0; iteration < max_iterations; iteration++) { + if (edges_satisfy_constraint( + num_edges, out_time, edges_parent, edges_child, epsilon)) { + goto out; + } + for (e = 0; e < num_edges; e++) { + p = edges_parent[e]; + c = edges_child[e]; + cavity = edges_cavity + 2 * e; + out_time[c] -= cavity[0]; + out_time[p] -= cavity[1]; + adjustment = out_time[c] - out_time[p]; + cavity[0] = 0.0; + cavity[1] = 0.0; + if (adjustment > 0) { + if (nodes_fixed[c] && nodes_fixed[p]) { + ret = tsd_trace_error(TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT); + goto out; + } + if (!nodes_fixed[c] && !nodes_fixed[p]) { + cavity[0] = -adjustment / 2; + cavity[1] = adjustment / 2; + } else if (nodes_fixed[c]) { + cavity[1] = adjustment; + } else { + cavity[0] = -adjustment; + } + } + out_time[c] += cavity[0]; + out_time[p] += cavity[1]; + } + } + + /* Force the remaining constraint, which can change the ages of fixed nodes */ + for (e = 0; e < num_edges; e++) { + p = edges_parent[e]; + c = edges_child[e]; + if (out_time[c] + epsilon >= out_time[p]) { + out_time[p] = out_time[c] + epsilon; + } + } +out: + tsd_safe_free(edges_cavity); + return ret; +} + +/* Whether any unmasked node among the parents of the given edges has one child. */ +static int +parents_are_unary(tsd_size_t num_edges, const tsd_id_t *edges_parent, + const tsd_id_t *indexes, tsd_size_t start, tsd_size_t stop, + const uint8_t *nodes_mask, const tsd_id_t *nodes_children) +{ + tsd_size_t j; + tsd_id_t p; + + tsd_bug_assert(stop <= num_edges); + for (j = start; j < stop; j++) { + p = edges_parent[indexes[j]]; + if (!nodes_mask[p] && nodes_children[p] == 1) { + return 1; + } + } + return 0; +} + +/* + * Whether any unmasked node has exactly one child edge in any tree. Sets + * `*contains_unary` to 1 or 0. + */ +int +tsd_contains_unary_nodes(tsd_size_t num_nodes, tsd_size_t num_edges, + const uint8_t *nodes_mask, const tsd_id_t *edges_parent, const double *edges_left, + const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length, int *contains_unary) +{ + int ret = 0; + tsd_id_t *nodes_children = NULL; + tsd_size_t a, b, a_start, b_start; + tsd_id_t p; + double left, right; + + nodes_children = calloc(num_nodes > 0 ? num_nodes : 1, sizeof(*nodes_children)); + if (nodes_children == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + *contains_unary = 0; + a = 0; + b = 0; + left = 0.0; + while (a < num_edges || b < num_edges) { + a_start = a; + b_start = b; + while (b < num_edges && edges_right[indexes_remove[b]] == left) { /* out */ + p = edges_parent[indexes_remove[b]]; + nodes_children[p]--; + b++; + } + while (a < num_edges && edges_left[indexes_insert[a]] == left) { /* in */ + p = edges_parent[indexes_insert[a]]; + nodes_children[p]++; + a++; + } + /* The nodes to check are the parents of the edges that changed */ + if (parents_are_unary(num_edges, edges_parent, indexes_remove, b_start, b, + nodes_mask, nodes_children) + || parents_are_unary(num_edges, edges_parent, indexes_insert, a_start, a, + nodes_mask, nodes_children)) { + *contains_unary = 1; + goto out; + } + right = sequence_length; + if (b < num_edges) { + right = tsd_min(right, edges_right[indexes_remove[b]]); + } + if (a < num_edges) { + right = tsd_min(right, edges_left[indexes_insert[a]]); + } + left = right; + } +out: + tsd_safe_free(nodes_children); + return ret; +} diff --git a/setup.py b/setup.py index 9ad8a6a0..5d91696e 100644 --- a/setup.py +++ b/setup.py @@ -9,7 +9,7 @@ libdir = "lib" includes = [libdir] -tsd_source_files = ["err.c", "hypergeo.c", "approx.c"] +tsd_source_files = ["err.c", "hypergeo.c", "approx.c", "phasing.c", "util.c", "prior.c"] sources = ["_tsdatemodule.c"] + [os.path.join(libdir, f) for f in tsd_source_files] diff --git a/tests/oracle/implementations.py b/tests/oracle/implementations.py index 8f618d26..fcaf041f 100644 --- a/tests/oracle/implementations.py +++ b/tests/oracle/implementations.py @@ -176,6 +176,30 @@ def _c_approx(_tsdate): ) +def _c_phasing(_tsdate): + return _PortedNamespace( + _block_singletons=_tsdate.block_singletons, + reallocate_unphased=_tsdate.reallocate_unphased, + _mutation_frequency=_tsdate.mutation_frequency, + ) + + +def _c_util(_tsdate): + return _PortedNamespace( + _split_disjoint_nodes=_tsdate.split_disjoint_nodes, + _relabel_mutations_node=_tsdate.relabel_mutations_node, + _constrain_ages=_tsdate.constrain_ages, + _contains_unary_nodes=_tsdate.contains_unary_nodes, + ) + + +def _c_prior(_tsdate): + return _PortedNamespace( + _marginalize_over_ancestors=_tsdate.marginalize_over_ancestors, + conditional_coalescent_variance=_tsdate.conditional_coalescent_variance, + ) + + def _c_namespace(): import _tsdate @@ -184,9 +208,9 @@ def _c_namespace(): approx=_c_approx(_tsdate), variational=_PortedNamespace(), rescaling=_PortedNamespace(), - phasing=_PortedNamespace(), - util=_PortedNamespace(), - prior=_PortedNamespace(), + phasing=_c_phasing(_tsdate), + util=_c_util(_tsdate), + prior=_c_prior(_tsdate), discrete=_PortedNamespace(), ) diff --git a/tests/test_python_c_tables.py b/tests/test_python_c_tables.py new file mode 100644 index 00000000..56a0d66e --- /dev/null +++ b/tests/test_python_c_tables.py @@ -0,0 +1,151 @@ +""" +Low-level tests of the phasing, util and prior functions of the ``_tsdate`` module: +argument checking and the error paths that the oracle tests do not reach. +""" + +import _tsdate +import numpy as np +import pytest +from oracle.helpers import b1, f64, i32, make_ts + +# nodes 0, 1, 2 belong to individual 0; node 3 is the root +THREE_HAPLOTYPES = [(1, 0, 0), (1, 0, 0), (1, 0, 0), (0, 1, -1)] +STAR = [(0, 10, 3, 0), (0, 10, 3, 1), (0, 10, 3, 2)] + + +class TestBlockSingletons: + def test_individual_with_three_edges(self): + ts = make_ts(THREE_HAPLOTYPES, STAR, [(1, 0)], 10.0, 1) + with pytest.raises(_tsdate.LibraryError, match="unphased individual"): + _tsdate.block_singletons( + b1(1), + ts.nodes_individual, + ts.mutations_node, + ts.sites_position[ts.mutations_site], + ts.edges_parent, + ts.edges_child, + ts.edges_left, + ts.edges_right, + ts.indexes_edge_insertion_order, + ts.indexes_edge_removal_order, + ts.sequence_length, + ) + + def test_wrong_dtype(self): + ts = make_ts(THREE_HAPLOTYPES, STAR, [(1, 0)], 10.0, 1) + with pytest.raises(TypeError): + _tsdate.block_singletons( + b1(1), + ts.nodes_individual, + ts.mutations_node.astype(np.int64), + ts.sites_position[ts.mutations_site], + ts.edges_parent, + ts.edges_child, + ts.edges_left, + ts.edges_right, + ts.indexes_edge_insertion_order, + ts.indexes_edge_removal_order, + ts.sequence_length, + ) + + +class TestReallocateUnphased: + @staticmethod + def call(likelihood, phase, mutations_block, blocks_edges): + _tsdate.reallocate_unphased( + likelihood, + f64(*phase), + i32(*mutations_block), + np.array(blocks_edges, dtype=np.int32).reshape(-1, 2), + ) + + def test_block_out_of_range(self): + with pytest.raises(_tsdate.LibraryError, match="out of range"): + self.call(np.ones((2, 2)), [0.5], [1], [[0, 1]]) + + def test_edge_out_of_range(self): + with pytest.raises(_tsdate.LibraryError, match="out of range"): + self.call(np.ones((2, 2)), [0.5], [0], [[0, 7]]) + + def test_updates_in_place(self): + likelihood = np.array([[1.0, 5.0], [0.0, 5.0]]) + self.call(likelihood, [0.25], [0], [[0, 1]]) + assert likelihood[:, 0].tolist() == [0.25, 0.75] + + def test_columns(self): + with pytest.raises(ValueError, match="two columns"): + self.call(np.ones((2, 3)), [0.5], [0], [[0, 1]]) + + +class TestMutationFrequency: + def test_nodes_sample_dtype(self): + ts = make_ts(THREE_HAPLOTYPES, STAR, [(1, 0)], 10.0, 1) + with pytest.raises(TypeError): + _tsdate.mutation_frequency( + np.ones((ts.num_nodes, 1), dtype=np.float64), + ts.mutations_node, + ts.sites_position[ts.mutations_site], + ts.edges_parent, + ts.edges_child, + ts.edges_left, + ts.edges_right, + ts.indexes_edge_insertion_order, + ts.indexes_edge_removal_order, + ts.sequence_length, + ) + + +class TestUtil: + def test_constrain_ages_wrong_dtype(self): + with pytest.raises(TypeError): + _tsdate.constrain_ages(f64(0, 1), b1(1, 0), i32(1), np.array([0]), 0.1, 3) + + def test_contains_unary_nodes_mask_size(self): + ts = make_ts(THREE_HAPLOTYPES, STAR, [], 10.0, 1) + with pytest.raises(ValueError, match="number of nodes"): + _tsdate.contains_unary_nodes( + b1(0, 0), + ts.edges_parent, + ts.edges_left, + ts.edges_right, + ts.indexes_edge_insertion_order, + ts.indexes_edge_removal_order, + ts.sequence_length, + ts.num_nodes, + ) + + def test_relabel_mutation_node_not_in_tree(self): + # node 4 has no edges + nodes = THREE_HAPLOTYPES + [(0, 2, -1)] + ts = make_ts(nodes, STAR, [(1, 4)], 10.0, 1) + with pytest.raises(_tsdate.LibraryError, match="not in any tree"): + _tsdate.relabel_mutations_node( + ts.mutations_node, + f64(1.0), + i32(0, 1, 2, 3, 4), + ts.edges_parent, + ts.edges_child, + ts.edges_left, + ts.edges_right, + ts.indexes_edge_insertion_order, + ts.indexes_edge_removal_order, + ) + + def test_constrain_ages_fixed_nodes(self): + with pytest.raises(_tsdate.LibraryError, match="two fixed nodes"): + _tsdate.constrain_ages(f64(0, 1), b1(1, 1), i32(0), i32(1), 0.1, 3) + + +class TestPrior: + def test_marginalize_over_ancestors_one_tip(self): + with pytest.raises(ValueError, match="At least two"): + _tsdate.marginalize_over_ancestors(np.ones((1, 2))) + + @pytest.mark.parametrize("num_tips", [0, -1]) + def test_variance_no_tips(self, num_tips): + with pytest.raises(ValueError, match="positive"): + _tsdate.conditional_coalescent_variance(num_tips) + + def test_variance_one_tip(self): + # numba reads out of bounds here; the result is unused + assert _tsdate.conditional_coalescent_variance(1).tolist() == [0.0, 0.0] From 5e6b2c65a93a7d3fd5588a40c7e02181395df571 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Mon, 23 Nov 2026 13:55:25 -0800 Subject: [PATCH 09/56] Port the jitted functions of tsdate.rescaling to C Adds lib/rescaling.c with _fixed_changepoints, _poisson_changepoints, _count_mutations, mutational_area, mutational_timescale, piecewise_scale_point_estimate and piecewise_scale_posterior, exposed from _tsdatemodule.c as array-level functions, and registers them in the "c" implementation of the oracle tests and of the microbenchmarks. Error codes: the changepoint and interval-count asserts share TSD_ERR_NONPOSITIVE_INTERVALS and TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER; "Zero edge span in interval", the non-increasing breakpoint ValueError, the quantile width, posterior domain and below-first-breakpoint asserts each have a code, with the numba messages where numba had one. A zero lower quantile or mean in piecewise_scale_posterior gives TSD_ERR_ZERO_DIVISION. Size and shape asserts are checked in the module and raise ValueError; the others, that cannot be reached, are tsd_bug_assert. Deviations from numba: no out-of-bounds access (negative slice and index wrap-around are done explicitly); the sorts are not those of numba but ties do not affect the results. --- _tsdatemodule.c | 528 ++++++++++++++++++ evaluation/microbench.py | 8 + lib/err.c | 28 + lib/err.h | 10 + lib/meson.build | 2 +- lib/rescaling.c | 911 +++++++++++++++++++++++++++++++ lib/tests/tests.c | 237 +++++++- lib/tsdate.h | 54 ++ setup.py | 10 +- tests/oracle/implementations.py | 14 +- tests/test_python_c_rescaling.py | 146 +++++ 11 files changed, 1944 insertions(+), 4 deletions(-) create mode 100644 lib/rescaling.c create mode 100644 tests/test_python_c_rescaling.py diff --git a/_tsdatemodule.c b/_tsdatemodule.c index 62a21bd5..76a6e372 100644 --- a/_tsdatemodule.c +++ b/_tsdatemodule.c @@ -1227,6 +1227,519 @@ tsdate_conditional_coalescent_variance(PyObject *Py_UNUSED(self), PyObject *args return ret; } +/* + * Rescaling functions (lib/rescaling.c). The checks of array sizes and shapes that the + * numba code made with assert are made here and raise ValueError. + */ + +/* A one-dimensional array of tsd_id_t (int32), copied from `data`. */ +static PyObject * +new_id_array(tsd_size_t size, const tsd_id_t *data) +{ + npy_intp dim = (npy_intp) size; + PyObject *ret = PyArray_SimpleNew(1, &dim, NPY_INT32); + + if (ret != NULL && size > 0) { + memcpy(PyArray_DATA((PyArrayObject *) ret), data, size * sizeof(*data)); + } + return ret; +} + +/* A one-dimensional array of doubles, copied from `data`. */ +static PyObject * +new_double_array(tsd_size_t size, const double *data) +{ + npy_intp dim = (npy_intp) size; + PyObject *ret = PyArray_SimpleNew(1, &dim, NPY_FLOAT64); + + if (ret != NULL && size > 0) { + memcpy(PyArray_DATA((PyArrayObject *) ret), data, size * sizeof(*data)); + } + return ret; +} + +/* A C-contiguous array of the given type and dimension from `obj`, or NULL. */ +static PyArrayObject * +get_array(PyObject *obj, int typenum, int ndim) +{ + return (PyArrayObject *) PyArray_FROMANY( + obj, typenum, ndim, ndim, NPY_ARRAY_IN_ARRAY); +} + +/* Raise ValueError and return -1 unless `ok`. */ +static int +check_sizes(int ok, const char *message) +{ + if (!ok) { + PyErr_SetString(PyExc_ValueError, message); + return -1; + } + return 0; +} + +#define ARRAY_LEN(array) ((tsd_size_t) PyArray_DIM((array), 0)) +#define DOUBLES(array) ((const double *) PyArray_DATA(array)) +#define IDS(array) ((const tsd_id_t *) PyArray_DATA(array)) +#define FLAGS(array) ((const uint8_t *) PyArray_DATA(array)) + +static PyObject * +tsdate_fixed_changepoints(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *counts_obj = NULL; + PyArrayObject *counts = NULL; + long long epochs; + tsd_id_t *breaks = NULL; + tsd_size_t num_breaks = 0; + int err; + + if (!PyArg_ParseTuple(args, "OL", &counts_obj, &epochs)) { + goto out; + } + counts = get_array(counts_obj, NPY_FLOAT64, 1); + if (counts == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_fixed_changepoints( + ARRAY_LEN(counts), DOUBLES(counts), (int64_t) epochs, &breaks, &num_breaks); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = new_id_array(num_breaks, breaks); +out: + tsd_safe_free(breaks); + Py_XDECREF(counts); + return ret; +} + +static PyObject * +tsdate_poisson_changepoints(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *counts_obj = NULL; + PyObject *offset_obj = NULL; + PyArrayObject *counts = NULL; + PyArrayObject *offset = NULL; + double penalty, min_counts, min_offset; + tsd_id_t *breaks = NULL; + tsd_size_t num_breaks = 0; + int err; + + if (!PyArg_ParseTuple(args, "OOddd", &counts_obj, &offset_obj, &penalty, &min_counts, + &min_offset)) { + goto out; + } + counts = get_array(counts_obj, NPY_FLOAT64, 1); + offset = get_array(offset_obj, NPY_FLOAT64, 1); + if (counts == NULL || offset == NULL) { + goto out; + } + if (check_sizes(ARRAY_LEN(counts) == ARRAY_LEN(offset), + "counts and offset must have the same size") + != 0) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_poisson_changepoints(ARRAY_LEN(counts), DOUBLES(counts), DOUBLES(offset), + penalty, min_counts, min_offset, &breaks, &num_breaks); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = new_id_array(num_breaks, breaks); +out: + tsd_safe_free(breaks); + Py_XDECREF(counts); + Py_XDECREF(offset); + return ret; +} + +static PyObject * +tsdate_count_mutations(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *obj[9]; + PyArrayObject *node_is_sample = NULL; + PyArrayObject *mutations_node = NULL; + PyArrayObject *mutations_position = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *edges_left = NULL; + PyArrayObject *edges_right = NULL; + PyArrayObject *indexes_insert = NULL; + PyArrayObject *indexes_remove = NULL; + PyArrayObject *edges_stats = NULL; + PyArrayObject *mutations_edge = NULL; + double sequence_length; + int size_biased; + tsd_size_t num_edges, num_mutations; + npy_intp stats_dims[2]; + npy_intp mutations_dim; + int err; + + if (!PyArg_ParseTuple(args, "OOOOOOOOOdp", &obj[0], &obj[1], &obj[2], &obj[3], + &obj[4], &obj[5], &obj[6], &obj[7], &obj[8], &sequence_length, + &size_biased)) { + goto out; + } + node_is_sample = get_array(obj[0], NPY_BOOL, 1); + mutations_node = get_array(obj[1], NPY_INT32, 1); + mutations_position = get_array(obj[2], NPY_FLOAT64, 1); + edges_parent = get_array(obj[3], NPY_INT32, 1); + edges_child = get_array(obj[4], NPY_INT32, 1); + edges_left = get_array(obj[5], NPY_FLOAT64, 1); + edges_right = get_array(obj[6], NPY_FLOAT64, 1); + indexes_insert = get_array(obj[7], NPY_INT32, 1); + indexes_remove = get_array(obj[8], NPY_INT32, 1); + if (node_is_sample == NULL || mutations_node == NULL || mutations_position == NULL + || edges_parent == NULL || edges_child == NULL || edges_left == NULL + || edges_right == NULL || indexes_insert == NULL || indexes_remove == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + num_mutations = ARRAY_LEN(mutations_node); + if (check_sizes(ARRAY_LEN(edges_child) == num_edges + && ARRAY_LEN(edges_left) == num_edges + && ARRAY_LEN(edges_right) == num_edges, + "Edge arrays must have the same size") + != 0) { + goto out; + } + if (check_sizes(ARRAY_LEN(indexes_insert) == num_edges + && ARRAY_LEN(indexes_remove) == num_edges, + "Edge index arrays must have one entry per edge") + != 0) { + goto out; + } + if (check_sizes(ARRAY_LEN(mutations_position) == num_mutations, + "Mutation arrays must have the same size") + != 0) { + goto out; + } + stats_dims[0] = (npy_intp) num_edges; + stats_dims[1] = 2; + mutations_dim = (npy_intp) num_mutations; + edges_stats = (PyArrayObject *) PyArray_SimpleNew(2, stats_dims, NPY_FLOAT64); + mutations_edge = (PyArrayObject *) PyArray_SimpleNew(1, &mutations_dim, NPY_INT32); + if (edges_stats == NULL || mutations_edge == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_count_mutations(ARRAY_LEN(node_is_sample), FLAGS(node_is_sample), + num_mutations, IDS(mutations_node), DOUBLES(mutations_position), num_edges, + IDS(edges_parent), IDS(edges_child), DOUBLES(edges_left), DOUBLES(edges_right), + IDS(indexes_insert), IDS(indexes_remove), sequence_length, size_biased, + (double *) PyArray_DATA(edges_stats), (tsd_id_t *) PyArray_DATA(mutations_edge)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = Py_BuildValue("OO", edges_stats, mutations_edge); +out: + Py_XDECREF(node_is_sample); + Py_XDECREF(mutations_node); + Py_XDECREF(mutations_position); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(edges_left); + Py_XDECREF(edges_right); + Py_XDECREF(indexes_insert); + Py_XDECREF(indexes_remove); + Py_XDECREF(edges_stats); + Py_XDECREF(mutations_edge); + return ret; +} + +/* + * Check the arrays that describe the edges and their likelihoods, shared by + * mutational_area and mutational_timescale. Returns 0, or -1 with ValueError. + */ +static int +check_edge_likelihoods( + PyArrayObject *likelihoods, PyArrayObject *edges_parent, PyArrayObject *edges_child) +{ + tsd_size_t num_edges = ARRAY_LEN(edges_parent); + int ret = -1; + + if (check_sizes( + ARRAY_LEN(edges_child) == num_edges, "Edge arrays must have the same size") + != 0) { + goto out; + } + if (check_sizes((tsd_size_t) PyArray_DIM(likelihoods, 0) == num_edges + && PyArray_DIM(likelihoods, 1) == 2, + "Likelihoods must have one row of two columns per edge") + != 0) { + goto out; + } + ret = 0; +out: + return ret; +} + +static PyObject * +tsdate_mutational_area(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *obj[4]; + PyArrayObject *nodes_time = NULL; + PyArrayObject *likelihoods = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *nodes_index = NULL; + PyObject *counts = NULL; + PyObject *offset = NULL; + PyObject *duration = NULL; + tsd_epoch_stats_t stats = { 0, NULL, NULL, NULL }; + npy_intp nodes_dim; + int err; + + if (!PyArg_ParseTuple(args, "OOOO", &obj[0], &obj[1], &obj[2], &obj[3])) { + goto out; + } + nodes_time = get_array(obj[0], NPY_FLOAT64, 1); + likelihoods = get_array(obj[1], NPY_FLOAT64, 2); + edges_parent = get_array(obj[2], NPY_INT32, 1); + edges_child = get_array(obj[3], NPY_INT32, 1); + if (nodes_time == NULL || likelihoods == NULL || edges_parent == NULL + || edges_child == NULL) { + goto out; + } + if (check_edge_likelihoods(likelihoods, edges_parent, edges_child) != 0) { + goto out; + } + nodes_dim = (npy_intp) ARRAY_LEN(nodes_time); + nodes_index = (PyArrayObject *) PyArray_SimpleNew(1, &nodes_dim, NPY_INT32); + if (nodes_index == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_mutational_area(ARRAY_LEN(nodes_time), DOUBLES(nodes_time), + ARRAY_LEN(edges_parent), DOUBLES(likelihoods), IDS(edges_parent), + IDS(edges_child), &stats, (tsd_id_t *) PyArray_DATA(nodes_index)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + counts = new_double_array(stats.num_epochs, stats.counts); + offset = new_double_array(stats.num_epochs, stats.offset); + duration = new_double_array(stats.num_epochs, stats.duration); + if (counts == NULL || offset == NULL || duration == NULL) { + goto out; + } + ret = Py_BuildValue("OOOO", counts, offset, duration, nodes_index); +out: + tsd_epoch_stats_free(&stats); + Py_XDECREF(nodes_time); + Py_XDECREF(likelihoods); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(nodes_index); + Py_XDECREF(counts); + Py_XDECREF(offset); + Py_XDECREF(duration); + return ret; +} + +static PyObject * +tsdate_mutational_timescale(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *obj[5]; + PyArrayObject *nodes_time = NULL; + PyArrayObject *likelihoods = NULL; + PyArrayObject *nodes_fixed = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyObject *origin_array = NULL; + PyObject *adjust_array = NULL; + long long max_intervals; + double *origin = NULL; + double *adjust = NULL; + tsd_size_t num_breaks = 0; + int err; + + if (!PyArg_ParseTuple(args, "OOOOOL", &obj[0], &obj[1], &obj[2], &obj[3], &obj[4], + &max_intervals)) { + goto out; + } + nodes_time = get_array(obj[0], NPY_FLOAT64, 1); + likelihoods = get_array(obj[1], NPY_FLOAT64, 2); + nodes_fixed = get_array(obj[2], NPY_BOOL, 1); + edges_parent = get_array(obj[3], NPY_INT32, 1); + edges_child = get_array(obj[4], NPY_INT32, 1); + if (nodes_time == NULL || likelihoods == NULL || nodes_fixed == NULL + || edges_parent == NULL || edges_child == NULL) { + goto out; + } + if (check_edge_likelihoods(likelihoods, edges_parent, edges_child) != 0) { + goto out; + } + if (check_sizes(ARRAY_LEN(nodes_fixed) == ARRAY_LEN(nodes_time), + "nodes_fixed and nodes_time must have the same size") + != 0) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_mutational_timescale(ARRAY_LEN(nodes_time), DOUBLES(nodes_time), + ARRAY_LEN(edges_parent), DOUBLES(likelihoods), IDS(edges_parent), + IDS(edges_child), (int64_t) max_intervals, &num_breaks, &origin, &adjust); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + origin_array = new_double_array(num_breaks, origin); + adjust_array = new_double_array(num_breaks, adjust); + if (origin_array == NULL || adjust_array == NULL) { + goto out; + } + ret = Py_BuildValue("OO", origin_array, adjust_array); +out: + tsd_safe_free(origin); + tsd_safe_free(adjust); + Py_XDECREF(nodes_time); + Py_XDECREF(likelihoods); + Py_XDECREF(nodes_fixed); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(origin_array); + Py_XDECREF(adjust_array); + return ret; +} + +static PyObject * +tsdate_piecewise_scale_point_estimate(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *obj[4]; + PyArrayObject *point_estimate = NULL; + PyArrayObject *point_fixed = NULL; + PyArrayObject *original_breaks = NULL; + PyArrayObject *rescaled_breaks = NULL; + PyArrayObject *rescaled = NULL; + npy_intp dim; + int err; + + if (!PyArg_ParseTuple(args, "OOOO", &obj[0], &obj[1], &obj[2], &obj[3])) { + goto out; + } + point_estimate = get_array(obj[0], NPY_FLOAT64, 1); + point_fixed = get_array(obj[1], NPY_BOOL, 1); + original_breaks = get_array(obj[2], NPY_FLOAT64, 1); + rescaled_breaks = get_array(obj[3], NPY_FLOAT64, 1); + if (point_estimate == NULL || point_fixed == NULL || original_breaks == NULL + || rescaled_breaks == NULL) { + goto out; + } + if (check_sizes(ARRAY_LEN(point_fixed) == ARRAY_LEN(point_estimate), + "point_fixed and point_estimate must have the same size") + != 0) { + goto out; + } + if (check_sizes(ARRAY_LEN(original_breaks) == ARRAY_LEN(rescaled_breaks) + && ARRAY_LEN(original_breaks) > 0, + "Breakpoints must be non-empty and of the same size") + != 0) { + goto out; + } + dim = (npy_intp) ARRAY_LEN(point_estimate); + rescaled = (PyArrayObject *) PyArray_SimpleNew(1, &dim, NPY_FLOAT64); + if (rescaled == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_piecewise_scale_point_estimate(ARRAY_LEN(point_estimate), + DOUBLES(point_estimate), FLAGS(point_fixed), ARRAY_LEN(original_breaks), + DOUBLES(original_breaks), DOUBLES(rescaled_breaks), + (double *) PyArray_DATA(rescaled)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + Py_INCREF(rescaled); + ret = (PyObject *) rescaled; +out: + Py_XDECREF(point_estimate); + Py_XDECREF(point_fixed); + Py_XDECREF(original_breaks); + Py_XDECREF(rescaled_breaks); + Py_XDECREF(rescaled); + return ret; +} + +static PyObject * +tsdate_piecewise_scale_posterior(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *obj[4]; + PyArrayObject *posteriors = NULL; + PyArrayObject *posteriors_fixed = NULL; + PyArrayObject *original_breaks = NULL; + PyArrayObject *rescaled_breaks = NULL; + PyArrayObject *new_posteriors = NULL; + double quantile_width, max_shape; + npy_intp dims[2]; + int err; + + if (!PyArg_ParseTuple(args, "OOOOdd", &obj[0], &obj[1], &obj[2], &obj[3], + &quantile_width, &max_shape)) { + goto out; + } + posteriors = get_array(obj[0], NPY_FLOAT64, 2); + posteriors_fixed = get_array(obj[1], NPY_BOOL, 1); + original_breaks = get_array(obj[2], NPY_FLOAT64, 1); + rescaled_breaks = get_array(obj[3], NPY_FLOAT64, 1); + if (posteriors == NULL || posteriors_fixed == NULL || original_breaks == NULL + || rescaled_breaks == NULL) { + goto out; + } + if (check_sizes(PyArray_DIM(posteriors, 1) == 2 + && ARRAY_LEN(posteriors_fixed) == ARRAY_LEN(posteriors), + "Posteriors must have two columns and one row per fixed flag") + != 0) { + goto out; + } + if (check_sizes(ARRAY_LEN(original_breaks) == ARRAY_LEN(rescaled_breaks) + && ARRAY_LEN(original_breaks) > 0, + "Breakpoints must be non-empty and of the same size") + != 0) { + goto out; + } + dims[0] = PyArray_DIM(posteriors, 0); + dims[1] = 2; + new_posteriors = (PyArrayObject *) PyArray_SimpleNew(2, dims, NPY_FLOAT64); + if (new_posteriors == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_piecewise_scale_posterior(ARRAY_LEN(posteriors), DOUBLES(posteriors), + FLAGS(posteriors_fixed), ARRAY_LEN(original_breaks), DOUBLES(original_breaks), + DOUBLES(rescaled_breaks), quantile_width, max_shape, gammaincinv, + (double *) PyArray_DATA(new_posteriors)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + Py_INCREF(new_posteriors); + ret = (PyObject *) new_posteriors; +out: + Py_XDECREF(posteriors); + Py_XDECREF(posteriors_fixed); + Py_XDECREF(original_breaks); + Py_XDECREF(rescaled_breaks); + Py_XDECREF(new_posteriors); + return ret; +} + static PyMethodDef tsdate_methods[] = { { "strerror", (PyCFunction) tsdate_strerror, METH_VARARGS, "Return the message for a library error code." }, @@ -1254,6 +1767,21 @@ static PyMethodDef tsdate_methods[] = { { "conditional_coalescent_variance", (PyCFunction) tsdate_conditional_coalescent_variance, METH_VARARGS, "Variance of node age given the number of descendant leaves." }, + { "fixed_changepoints", (PyCFunction) tsdate_fixed_changepoints, METH_VARARGS, + "Breakpoints dividing counts roughly equally between epochs." }, + { "poisson_changepoints", (PyCFunction) tsdate_poisson_changepoints, METH_VARARGS, + "Changepoints of a Poisson rate under a linear penalty." }, + { "count_mutations", (PyCFunction) tsdate_count_mutations, METH_VARARGS, + "Mutation counts and spans per edge, and the edge of each mutation." }, + { "mutational_area", (PyCFunction) tsdate_mutational_area, METH_VARARGS, + "Mutation counts and area per inter-node interval." }, + { "mutational_timescale", (PyCFunction) tsdate_mutational_timescale, METH_VARARGS, + "Breakpoints for rescaling time so that the mutation rate is constant." }, + { "piecewise_scale_point_estimate", + (PyCFunction) tsdate_piecewise_scale_point_estimate, METH_VARARGS, + "Rescale point estimates of node ages." }, + { "piecewise_scale_posterior", (PyCFunction) tsdate_piecewise_scale_posterior, + METH_VARARGS, "Rescale gamma posteriors of node ages." }, { NULL } /* Sentinel */ }; diff --git a/evaluation/microbench.py b/evaluation/microbench.py index fe10e278..2f4912e8 100644 --- a/evaluation/microbench.py +++ b/evaluation/microbench.py @@ -97,6 +97,14 @@ def _c_impl(): "_contains_unary_nodes": _tsdate.contains_unary_nodes, "_marginalize_over_ancestors": _tsdate.marginalize_over_ancestors, "conditional_coalescent_variance": _tsdate.conditional_coalescent_variance, + # rescaling + "mutational_area": _tsdate.mutational_area, + "mutational_timescale": _tsdate.mutational_timescale, + "piecewise_scale_point_estimate": _tsdate.piecewise_scale_point_estimate, + "piecewise_scale_posterior": _tsdate.piecewise_scale_posterior, + "_fixed_changepoints": _tsdate.fixed_changepoints, + "_poisson_changepoints": _tsdate.poisson_changepoints, + "_count_mutations": _tsdate.count_mutations, } diff --git a/lib/err.c b/lib/err.c index b8e628b0..89d168e7 100644 --- a/lib/err.c +++ b/lib/err.c @@ -99,6 +99,34 @@ tsd_strerror(int err) case TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT: ret = "An edge between two fixed nodes violates the age constraint"; break; + case TSD_ERR_NONPOSITIVE_INTERVALS: + ret = "The number of intervals must be positive"; + break; + case TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER: + ret = "The penalty, minimum counts and minimum offset must not be negative"; + break; + case TSD_ERR_ZERO_EDGE_SPAN: + ret = "Zero edge span in interval"; + break; + case TSD_ERR_NON_INCREASING_BREAKPOINTS: + ret = "Rescaling produced non-increasing time breakpoints. " + "Try setting `rescaling_intervals` to a smaller value " + "(e.g. half its current value)."; + break; + case TSD_ERR_INVALID_QUANTILE_WIDTH: + ret = "The quantile width must be greater than zero and less than one"; + break; + case TSD_ERR_INVALID_POSTERIOR: + ret = "A posterior to be rescaled has shape not greater than -1 or rate " + "not greater than zero"; + break; + case TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT: + ret = "A time to be rescaled is below the first time breakpoint"; + break; + case TSD_ERR_NO_POSTERIORS: + ret = "zero-size array to reduction operation minimum which has no " + "identity"; + break; default: break; } diff --git a/lib/err.h b/lib/err.h index 25f30dad..14c4ee6a 100644 --- a/lib/err.h +++ b/lib/err.h @@ -65,6 +65,16 @@ extern "C" { /* util */ #define TSD_ERR_MUTATION_NODE_NOT_IN_TREE -20 #define TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT -21 + +/* rescaling */ +#define TSD_ERR_NONPOSITIVE_INTERVALS -22 +#define TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER -23 +#define TSD_ERR_ZERO_EDGE_SPAN -24 +#define TSD_ERR_NON_INCREASING_BREAKPOINTS -25 +#define TSD_ERR_INVALID_QUANTILE_WIDTH -26 +#define TSD_ERR_INVALID_POSTERIOR -27 +#define TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT -28 +#define TSD_ERR_NO_POSTERIORS -29 /* clang-format on */ #ifdef __GNUC__ diff --git a/lib/meson.build b/lib/meson.build index a418bd66..f40289c0 100644 --- a/lib/meson.build +++ b/lib/meson.build @@ -15,7 +15,7 @@ if get_option('buildtype') == 'debug' extra_c_args += ['-DTSD_TRACE_ERRORS'] endif -tsdate_sources = ['err.c', 'hypergeo.c', 'approx.c', +tsdate_sources = ['err.c', 'hypergeo.c', 'approx.c', 'rescaling.c', 'phasing.c', 'util.c', 'prior.c'] tsdate_lib = static_library('tsdate', diff --git a/lib/rescaling.c b/lib/rescaling.c new file mode 100644 index 00000000..ef7bb3e9 --- /dev/null +++ b/lib/rescaling.c @@ -0,0 +1,911 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* + * Rescaling of time so that the mutation rate is constant, ported from + * tsdate/rescaling.py (numba). Operation order and libm calls follow the numba code so + * that results agree to the last bit or two. + * + * Arrays whose size is not known beforehand are allocated with room for one more + * element than needed, so that empty inputs still give valid pointers. + */ + +#include +#include +#include + +#include "mathutil.h" +#include "tsdate.h" + +/* The null id, as tskit.NULL */ +#define NO_ID ((tsd_id_t) - 1) + +/* A value with its position, for sorting (the equivalent of np.argsort). */ +typedef struct { + double value; + tsd_id_t index; +} sort_item_t; + +/* Order by value, NaN last, ties by position. */ +static int +compare_sort_items(const void *a, const void *b) +{ + const sort_item_t *x = (const sort_item_t *) a; + const sort_item_t *y = (const sort_item_t *) b; + int x_nan = isnan(x->value); + int y_nan = isnan(y->value); + int ret; + + if (x_nan != y_nan) { + ret = x_nan ? 1 : -1; + } else if (!x_nan && x->value < y->value) { + ret = -1; + } else if (!x_nan && x->value > y->value) { + ret = 1; + } else { + ret = (x->index > y->index) - (x->index < y->index); + } + return ret; +} + +static int +compare_ids(const void *a, const void *b) +{ + tsd_id_t x = *(const tsd_id_t *) a; + tsd_id_t y = *(const tsd_id_t *) b; + + return (x > y) - (x < y); +} + +/* Whether `a` is less than or equal to `key`, where NaN `key` is above everything. */ +static int +less_equal(double a, double key) +{ + return isnan(key) || a <= key; +} + +/* + * The first index in [min_idx, max_idx] at which the sorted array `a` exceeds `key` + * (the search of np.searchsorted(a, key, "right"), which numba reproduces): the number + * of entries less than or equal to `key` if the range contains it. As in numba, NaN is + * greater than every number. + */ +static tsd_size_t +bisect_right(const double *a, double key, tsd_size_t min_idx, tsd_size_t max_idx) +{ + tsd_size_t mid_idx; + + while (min_idx < max_idx) { + mid_idx = min_idx + ((max_idx - min_idx) >> 1); + if (less_equal(a[mid_idx], key)) { + min_idx = mid_idx + 1; + } else { + max_idx = mid_idx; + } + } + return min_idx; +} + +/* np.searchsorted(a, key, "right") for one key */ +static tsd_size_t +searchsorted_right(tsd_size_t n, const double *a, double key) +{ + return bisect_right(a, key, 0, n); +} + +/* Whether np.all(np.diff(a) > 0) */ +static int +is_increasing(tsd_size_t n, const double *a) +{ + tsd_size_t j; + double diff; + + for (j = 1; j < n; j++) { + diff = a[j] - a[j - 1]; + if (!(diff > 0)) { + return 0; + } + } + return 1; +} + +/* + * The time `x` mapped from the original to the rescaled breakpoints by the piece + * `i`, which has the slope (the last piece is flat, as it has no upper breakpoint). + */ +static double +rescale_piece(tsd_size_t n, const double *original_breaks, const double *rescaled_breaks, + tsd_size_t i, double x) +{ + double scaling = 0.0; + double offset; + + if (i + 1 < n) { + scaling = (rescaled_breaks[i + 1] - rescaled_breaks[i]) + / (original_breaks[i + 1] - original_breaks[i]); + } + offset = x - original_breaks[i]; + return rescaled_breaks[i] + scaling * offset; +} + +void +tsd_epoch_stats_free(tsd_epoch_stats_t *stats) +{ + tsd_safe_free(stats->counts); + tsd_safe_free(stats->offset); + tsd_safe_free(stats->duration); + stats->num_epochs = 0; +} + +/* ------------------------------------------------------------------------- * + * Changepoints + * ------------------------------------------------------------------------- */ + +int +tsd_fixed_changepoints(tsd_size_t num_counts, const double *counts, int64_t epochs, + tsd_id_t **breaks, tsd_size_t *num_breaks) +{ + int ret = 0; + double *cumulative = NULL; + tsd_id_t *e = NULL; + tsd_size_t j, num_e, min_idx, max_idx; + double total, step, z, last_z; + + if (epochs <= 0) { + ret = tsd_trace_error(TSD_ERR_NONPOSITIVE_INTERVALS); + goto out; + } + num_e = (tsd_size_t) epochs + 1; + cumulative = malloc((num_counts + 1) * sizeof(*cumulative)); + e = malloc(num_e * sizeof(*e)); + if (cumulative == NULL || e == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + /* The cumulative counts, normalised by the total. Division by zero is not an + * error: the result is NaN, which compares as greater than every number. */ + cumulative[0] = 0.0; + for (j = 0; j < num_counts; j++) { + cumulative[j + 1] = cumulative[j] + counts[j]; + } + total = cumulative[num_counts]; + for (j = 0; j <= num_counts; j++) { + cumulative[j] = cumulative[j] / total; + } + /* + * Equally spaced quantiles, as np.linspace(0, 1, epochs + 1), searched for as + * numba does: the quantiles increase, so each search starts from the last result. + */ + step = 1.0 / (double) epochs; + last_z = 0.0; + min_idx = 0; + max_idx = num_counts + 1; + for (j = 0; j < num_e; j++) { + z = 0.0 + (double) j * step; + if (j + 1 == num_e) { + z = 1.0; + } + if (j == 0 || less_equal(last_z, z)) { + max_idx = num_counts + 1; + } else { + min_idx = 0; + max_idx = max_idx < num_counts + 1 ? max_idx + 1 : num_counts + 1; + } + last_z = z; + min_idx = bisect_right(cumulative, z, min_idx, max_idx); + e[j] = (tsd_id_t) ((int64_t) min_idx - 1); + } + if (e[0] > 0) { + e[0] = 0; + } + if (e[num_e - 1] < (int64_t) num_counts) { + e[num_e - 1] = (tsd_id_t) num_counts; + } + *breaks = e; + *num_breaks = num_e; + e = NULL; +out: + tsd_safe_free(cumulative); + tsd_safe_free(e); + return ret; +} + +/* The loss of a constant rate for the observations from `i` to `j` */ +static double +poisson_loss(const double *cum_offset, const double *cum_counts, tsd_size_t i, + tsd_size_t j, double min_counts, double min_offset) +{ + double n = cum_offset[j] - cum_offset[i]; + double y = cum_counts[j] - cum_counts[i]; + double loss; + + if (n < min_offset || y < min_counts) { + return INFINITY; + } + loss = -2.0 * y * (log(y) - log(n) - 1.0); + return loss; +} + +int +tsd_poisson_changepoints(tsd_size_t num_counts, const double *counts, + const double *offset, double penalty, double min_counts, double min_offset, + tsd_id_t **breaks, tsd_size_t *num_breaks) +{ + int ret = 0; + double *cum_offset = NULL; + double *cum_counts = NULL; + double *cost = NULL; + double *best = NULL; + tsd_id_t *previous = NULL; + tsd_id_t *candidates = NULL; + tsd_id_t *path = NULL; + tsd_size_t j, k, c, i, num_candidates, num_kept, argmin, num_path; + tsd_id_t current; + double min_cost; + const tsd_size_t dim = num_counts; + + if (!(min_counts >= 0 && min_offset >= 0 && penalty >= 0)) { + ret = tsd_trace_error(TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER); + goto out; + } + cum_offset = malloc((dim + 1) * sizeof(*cum_offset)); + cum_counts = malloc((dim + 1) * sizeof(*cum_counts)); + cost = malloc((dim + 1) * sizeof(*cost)); + best = malloc((dim + 1) * sizeof(*best)); + previous = malloc((dim + 1) * sizeof(*previous)); + candidates = malloc((dim + 1) * sizeof(*candidates)); + if (cum_offset == NULL || cum_counts == NULL || cost == NULL || best == NULL + || previous == NULL || candidates == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + cum_offset[0] = 0.0; + cum_counts[0] = 0.0; + for (j = 0; j < dim; j++) { + cum_offset[j + 1] = cum_offset[j] + offset[j]; + cum_counts[j + 1] = cum_counts[j] + counts[j]; + } + + /* + * Optimal partitioning with pruning: `candidates` are the start positions of the + * last segment that can still be optimal, in increasing order; `previous[j]` is + * the start of the last segment of the best partition of the first `j` + * observations. + */ + best[0] = -penalty; + candidates[0] = 0; + num_candidates = 1; + for (j = 1; j <= dim; j++) { + argmin = 0; + min_cost = INFINITY; + for (c = 0; c < num_candidates; c++) { + i = (tsd_size_t) candidates[c]; + cost[i] + = best[i] + + poisson_loss(cum_offset, cum_counts, i, j, min_counts, min_offset) + + penalty; + if (cost[i] < min_cost) { + min_cost = cost[i]; + argmin = i; + } + } + best[j] = min_cost; + num_kept = 0; + for (c = 0; c < num_candidates; c++) { + i = (tsd_size_t) candidates[c]; + if (!(cost[i] > best[j] + penalty)) { + candidates[num_kept] = candidates[c]; + num_kept++; + } + } + candidates[num_kept] = (tsd_id_t) j; + num_candidates = num_kept + 1; + previous[j] = (tsd_id_t) argmin; + } + + /* The changepoints are those on the path from `dim` back to zero */ + num_path = 0; + current = (tsd_id_t) dim; + while (current != 0) { + current = previous[current]; + num_path++; + } + path = malloc((num_path + 1) * sizeof(*path)); + if (path == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + path[num_path] = (tsd_id_t) dim; + current = (tsd_id_t) dim; + for (k = num_path; k > 0; k--) { + current = previous[current]; + path[k - 1] = current; + } + *breaks = path; + *num_breaks = num_path + 1; + path = NULL; +out: + tsd_safe_free(cum_offset); + tsd_safe_free(cum_counts); + tsd_safe_free(cost); + tsd_safe_free(best); + tsd_safe_free(previous); + tsd_safe_free(candidates); + tsd_safe_free(path); + return ret; +} + +/* ------------------------------------------------------------------------- * + * Counting mutations + * ------------------------------------------------------------------------- */ + +/* + * Add (sign = 1) or remove (sign = -1) the span of the edge `e`, to the parent `p` of + * its child `c`, and to every ancestor of `p`, in proportion to the number of + * samples below `c`; and update the sample counts of the ancestors. + */ +static void +count_update_ancestors(tsd_id_t e, tsd_id_t p, tsd_id_t c, double sign, double remainder, + const tsd_id_t *nodes_edge, const tsd_id_t *nodes_parent, double *nodes_samples, + double *edges_stats) +{ + tsd_id_t next_e, next_p; + double span; + + while (p != NO_ID) { + span = nodes_samples[c] * remainder; + edges_stats[2 * e + 1] += sign * span; + nodes_samples[p] += sign * nodes_samples[c]; + next_e = nodes_edge[p]; + next_p = nodes_parent[p]; + e = next_e; + p = next_p; + } +} + +int +tsd_count_mutations(tsd_size_t num_nodes, const uint8_t *node_is_sample, + tsd_size_t num_mutations, const tsd_id_t *mutations_node, + const double *mutations_position, tsd_size_t num_edges, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, const double *edges_left, const double *edges_right, + const tsd_id_t *indexes_insert, const tsd_id_t *indexes_remove, + double sequence_length, int size_biased, double *edges_stats, + tsd_id_t *mutations_edge) +{ + int ret = 0; + sort_item_t *mutation_order = NULL; + double *nodes_samples = NULL; + tsd_id_t *nodes_edge = NULL; + tsd_id_t *nodes_parent = NULL; + tsd_size_t j, a, b, d; + tsd_id_t e, p, c, m; + double left, right, remainder, edge_position; + + mutation_order = malloc((num_mutations + 1) * sizeof(*mutation_order)); + nodes_samples = malloc((num_nodes + 1) * sizeof(*nodes_samples)); + nodes_edge = malloc((num_nodes + 1) * sizeof(*nodes_edge)); + nodes_parent = malloc((num_nodes + 1) * sizeof(*nodes_parent)); + if (mutation_order == NULL || nodes_samples == NULL || nodes_edge == NULL + || nodes_parent == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + for (j = 0; j < num_mutations; j++) { + mutation_order[j].value = mutations_position[j]; + mutation_order[j].index = (tsd_id_t) j; + mutations_edge[j] = NO_ID; + } + qsort(mutation_order, num_mutations, sizeof(*mutation_order), compare_sort_items); + for (j = 0; j < num_nodes; j++) { + nodes_samples[j] = node_is_sample[j] ? 1.0 : 0.0; + nodes_edge[j] = NO_ID; + nodes_parent[j] = NO_ID; + } + memset(edges_stats, 0, 2 * num_edges * sizeof(*edges_stats)); + + left = 0.0; + a = 0; + b = 0; + d = 0; + while (a < num_edges || b < num_edges) { + remainder = sequence_length - left; + + /* edges out */ + while (b < num_edges && edges_right[indexes_remove[b]] == left) { + e = indexes_remove[b]; + p = edges_parent[e]; + c = edges_child[e]; + nodes_edge[c] = NO_ID; + nodes_parent[c] = NO_ID; + if (size_biased) { + count_update_ancestors(e, p, c, -1.0, remainder, nodes_edge, + nodes_parent, nodes_samples, edges_stats); + } else { + edges_stats[2 * e + 1] -= remainder; + } + b++; + } + + /* edges in */ + while (a < num_edges && edges_left[indexes_insert[a]] == left) { + e = indexes_insert[a]; + p = edges_parent[e]; + c = edges_child[e]; + nodes_edge[c] = e; + nodes_parent[c] = p; + if (size_biased) { + count_update_ancestors(e, p, c, 1.0, remainder, nodes_edge, nodes_parent, + nodes_samples, edges_stats); + } else { + edges_stats[2 * e + 1] += remainder; + } + a++; + } + + right = sequence_length; + if (b < num_edges) { + edge_position = edges_right[indexes_remove[b]]; + right = tsd_min(right, edge_position); + } + if (a < num_edges) { + edge_position = edges_left[indexes_insert[a]]; + right = tsd_min(right, edge_position); + } + left = right; + + while (d < num_mutations && mutation_order[d].value < right) { + m = mutation_order[d].index; + c = mutations_node[m]; + e = nodes_edge[c]; + if (e != NO_ID) { + mutations_edge[m] = e; + edges_stats[2 * e] += size_biased ? nodes_samples[c] : 1.0; + } + d++; + } + } +out: + tsd_safe_free(mutation_order); + tsd_safe_free(nodes_samples); + tsd_safe_free(nodes_edge); + tsd_safe_free(nodes_parent); + return ret; +} + +/* ------------------------------------------------------------------------- * + * Mutational area and the time scale + * ------------------------------------------------------------------------- */ + +int +tsd_mutational_area(tsd_size_t num_nodes, const double *nodes_time, tsd_size_t num_edges, + const double *likelihoods, const tsd_id_t *edges_parent, const tsd_id_t *edges_child, + tsd_epoch_stats_t *stats, tsd_id_t *nodes_index) +{ + int ret = 0; + sort_item_t *order = NULL; + double *epoch_breaks = NULL; + double *epoch_counts = NULL; + double *counts = NULL; + double *offset = NULL; + double *duration = NULL; + tsd_size_t j, k, num_breaks, num_epochs, a, b; + tsd_id_t p, c, node, previous; + double length, edge_count, edge_span; + + order = malloc((num_nodes + 1) * sizeof(*order)); + epoch_breaks = malloc((num_nodes + 1) * sizeof(*epoch_breaks)); + if (order == NULL || epoch_breaks == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + + /* Index the nodes by unique time breaks; the first epoch starts at zero */ + for (j = 0; j < num_nodes; j++) { + order[j].value = nodes_time[j]; + order[j].index = (tsd_id_t) j; + nodes_index[j] = 0; + } + qsort(order, num_nodes, sizeof(*order), compare_sort_items); + epoch_breaks[0] = 0.0; + num_breaks = 1; + k = 0; + for (j = 1; j < num_nodes; j++) { + node = order[j].index; + previous = order[j - 1].index; + if (nodes_time[node] > nodes_time[previous]) { + epoch_breaks[num_breaks] = nodes_time[node]; + num_breaks++; + k++; + } + nodes_index[node] = (tsd_id_t) k; + } + num_epochs = num_breaks - 1; + + epoch_counts = calloc(2 * num_epochs + 1, sizeof(*epoch_counts)); + counts = malloc((num_epochs + 1) * sizeof(*counts)); + offset = malloc((num_epochs + 1) * sizeof(*offset)); + duration = malloc((num_epochs + 1) * sizeof(*duration)); + if (epoch_counts == NULL || counts == NULL || offset == NULL || duration == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + + /* Pass over edges, measuring overlap with each time interval, using the + * instantaneous mutation rate of each edge. */ + for (j = 0; j < num_edges; j++) { + p = edges_parent[j]; + c = edges_child[j]; + length = nodes_time[p] - nodes_time[c]; + if (!(length > 0)) { + continue; + } + edge_count = likelihoods[2 * j] / length; + edge_span = likelihoods[2 * j + 1]; + a = (tsd_size_t) nodes_index[c]; + b = (tsd_size_t) nodes_index[p]; + if (a < num_epochs) { + epoch_counts[2 * a] += edge_count; + epoch_counts[2 * a + 1] += edge_span; + } + if (b < num_epochs) { + epoch_counts[2 * b] -= edge_count; + epoch_counts[2 * b + 1] -= edge_span; + } + } + for (k = 0; k < num_epochs; k++) { + counts[k] = epoch_counts[2 * k]; + offset[k] = epoch_counts[2 * k + 1]; + if (k > 0) { + counts[k] += counts[k - 1]; + offset[k] += offset[k - 1]; + } + duration[k] = epoch_breaks[k + 1] - epoch_breaks[k]; + } + stats->num_epochs = num_epochs; + stats->counts = counts; + stats->offset = offset; + stats->duration = duration; + counts = NULL; + offset = NULL; + duration = NULL; +out: + tsd_safe_free(order); + tsd_safe_free(epoch_breaks); + tsd_safe_free(epoch_counts); + tsd_safe_free(counts); + tsd_safe_free(offset); + tsd_safe_free(duration); + return ret; +} + +/* + * The sum of x[i:j] in the sense of Python slices of an array of the given size (a + * negative `i` counts from the end), accumulated from the first element. + */ +static double +slice_sum(const double *x, tsd_size_t size, tsd_id_t i, tsd_id_t j) +{ + int64_t start = i; + int64_t stop = j; + int64_t isize = (int64_t) size; + int64_t k; + double sum; + + if (start < 0) { + start = start + isize < 0 ? 0 : start + isize; + } + if (stop < 0) { + stop = stop + isize < 0 ? 0 : stop + isize; + } + start = start > isize ? isize : start; + stop = stop > isize ? isize : stop; + if (start >= stop) { + return 0.0; + } + sum = x[start]; + for (k = start + 1; k < stop; k++) { + sum += x[k]; + } + return sum; +} + +/* Sort `ids` and remove duplicates (np.unique); returns the number that remain. */ +static tsd_size_t +unique_ids(tsd_size_t n, tsd_id_t *ids) +{ + tsd_size_t j; + tsd_size_t num_unique = 0; + + qsort(ids, n, sizeof(*ids), compare_ids); + for (j = 0; j < n; j++) { + if (j == 0 || ids[j] != ids[j - 1]) { + ids[num_unique] = ids[j]; + num_unique++; + } + } + return num_unique; +} + +int +tsd_mutational_timescale(tsd_size_t num_nodes, const double *nodes_time, + tsd_size_t num_edges, const double *likelihoods, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, int64_t max_intervals, tsd_size_t *num_breaks, + double **origin_out, double **adjust_out) +{ + int ret = 0; + tsd_epoch_stats_t stats = { 0, NULL, NULL, NULL }; + tsd_id_t *nodes_index = NULL; + tsd_id_t *changepoints = NULL; + double *epoch_breaks = NULL; + double *weight = NULL; + double *adjust = NULL; + double *origin = NULL; + tsd_size_t k, num_epochs, num_changepoints, num_unique; + tsd_id_t i, j, index; + double n, y, z; + + if (max_intervals <= 0) { + ret = tsd_trace_error(TSD_ERR_NONPOSITIVE_INTERVALS); + goto out; + } + nodes_index = malloc((num_nodes + 1) * sizeof(*nodes_index)); + if (nodes_index == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + ret = tsd_mutational_area(num_nodes, nodes_time, num_edges, likelihoods, + edges_parent, edges_child, &stats, nodes_index); + if (ret != 0) { + goto out; + } + num_epochs = stats.num_epochs; + epoch_breaks = malloc((num_epochs + 1) * sizeof(*epoch_breaks)); + weight = malloc((num_epochs + 1) * sizeof(*weight)); + if (epoch_breaks == NULL || weight == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + epoch_breaks[0] = 0.0; + for (k = 0; k < num_epochs; k++) { + epoch_breaks[k + 1] = epoch_breaks[k] + stats.duration[k]; + weight[k] = stats.offset[k] * stats.duration[k]; + } + + /* Rescale time such that mutation density is constant between changepoints */ + ret = tsd_fixed_changepoints( + num_epochs, weight, max_intervals, &changepoints, &num_changepoints); + if (ret != 0) { + goto out; + } + num_unique = unique_ids(num_changepoints, changepoints); + adjust = malloc((num_unique + 1) * sizeof(*adjust)); + origin = malloc((num_unique + 1) * sizeof(*origin)); + if (adjust == NULL || origin == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + adjust[0] = 0.0; + for (k = 0; k + 1 < num_unique; k++) { + i = changepoints[k]; + j = changepoints[k + 1]; + tsd_bug_assert(j > i); + n = slice_sum(stats.offset, num_epochs, i, j); + y = slice_sum(stats.counts, num_epochs, i, j); + z = slice_sum(stats.duration, num_epochs, i, j); + if (!(n > 0)) { + ret = tsd_trace_error(TSD_ERR_ZERO_EDGE_SPAN); + goto out; + } + adjust[k + 1] = z * y / n; + } + for (k = 0; k < num_unique; k++) { + if (k > 0) { + adjust[k] += adjust[k - 1]; + } + /* a negative changepoint indexes from the end, as in numpy */ + index = changepoints[k]; + if (index < 0) { + index = (tsd_id_t) ((tsd_size_t) index + num_epochs + 1); + } + origin[k] = epoch_breaks[index]; + } + *num_breaks = num_unique; + *origin_out = origin; + *adjust_out = adjust; + origin = NULL; + adjust = NULL; +out: + tsd_epoch_stats_free(&stats); + tsd_safe_free(nodes_index); + tsd_safe_free(changepoints); + tsd_safe_free(epoch_breaks); + tsd_safe_free(weight); + tsd_safe_free(adjust); + tsd_safe_free(origin); + return ret; +} + +/* ------------------------------------------------------------------------- * + * Rescaling point estimates and posteriors + * ------------------------------------------------------------------------- */ + +int +tsd_piecewise_scale_point_estimate(tsd_size_t num_points, const double *point_estimate, + const uint8_t *point_fixed, tsd_size_t num_breaks, const double *original_breaks, + const double *rescaled_breaks, double *rescaled) +{ + int ret = 0; + tsd_size_t j; + int64_t idx; + double x; + + tsd_bug_assert(num_breaks > 0); + if (!is_increasing(num_breaks, rescaled_breaks) + || !is_increasing(num_breaks, original_breaks)) { + ret = tsd_trace_error(TSD_ERR_NON_INCREASING_BREAKPOINTS); + goto out; + } + for (j = 0; j < num_points; j++) { + x = point_estimate[j]; + idx = (int64_t) searchsorted_right(num_breaks, original_breaks, x) - 1; + if (idx < 0) { + /* as in numba, a time before the first breakpoint wraps to the last */ + idx += (int64_t) num_breaks; + } + rescaled[j] = rescale_piece( + num_breaks, original_breaks, rescaled_breaks, (tsd_size_t) idx, x); + if (point_fixed[j]) { + rescaled[j] = x; + } + } +out: + return ret; +} + +/* Rescale `x` in place, or fail if it is below the first breakpoint. */ +static int +rescale_quantile(tsd_size_t num_breaks, const double *original_breaks, + const double *rescaled_breaks, double *x) +{ + int ret = 0; + int64_t idx; + + idx = (int64_t) searchsorted_right(num_breaks, original_breaks, *x) - 1; + if (idx < 0) { + ret = tsd_trace_error(TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT); + goto out; + } + *x = rescale_piece( + num_breaks, original_breaks, rescaled_breaks, (tsd_size_t) idx, *x); +out: + return ret; +} + +int +tsd_piecewise_scale_posterior(tsd_size_t num_posteriors, const double *posteriors, + const uint8_t *posteriors_fixed, tsd_size_t num_breaks, + const double *original_breaks, const double *rescaled_breaks, double quantile_width, + double max_shape, tsd_gammaincinv_fn gammaincinv, double *new_posteriors) +{ + int ret = 0; + double *lower = NULL; + double *upper = NULL; + double *midpt = NULL; + tsd_size_t j; + double alpha, beta, quant_lower, quant_upper, new_beta; + double gamma_pars[2]; + + tsd_bug_assert(num_breaks > 0); + if (!(quantile_width < 1 && quantile_width > 0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_QUANTILE_WIDTH); + goto out; + } + if (!is_increasing(num_breaks, rescaled_breaks) + || !is_increasing(num_breaks, original_breaks)) { + ret = tsd_trace_error(TSD_ERR_NON_INCREASING_BREAKPOINTS); + goto out; + } + quant_lower = quantile_width / 2; + quant_upper = 1 - quantile_width / 2; + for (j = 0; j < num_posteriors; j++) { + if (!posteriors_fixed[j] + && !(posteriors[2 * j] > -1 && posteriors[2 * j + 1] > 0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_POSTERIOR); + goto out; + } + } + if (num_posteriors == 0) { + /* numba raises this from reducing an empty array: pinned by the tests */ + ret = tsd_trace_error(TSD_ERR_NO_POSTERIORS); + goto out; + } + lower = calloc(num_posteriors, sizeof(*lower)); + upper = calloc(num_posteriors, sizeof(*upper)); + midpt = calloc(num_posteriors, sizeof(*midpt)); + if (lower == NULL || upper == NULL || midpt == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + + /* use posterior mean as a point estimate */ + for (j = 0; j < num_posteriors; j++) { + if (!posteriors_fixed[j]) { + alpha = posteriors[2 * j]; + beta = posteriors[2 * j + 1]; + lower[j] = gammaincinv(alpha + 1, quant_lower) / beta; + upper[j] = gammaincinv(alpha + 1, quant_upper) / beta; + midpt[j] = (alpha + 1) / beta; + } + } + /* rescale the quantiles; those of fixed posteriors are zero, and are checked too */ + for (j = 0; j < num_posteriors; j++) { + ret = rescale_quantile(num_breaks, original_breaks, rescaled_breaks, &midpt[j]); + if (ret != 0) { + goto out; + } + } + for (j = 0; j < num_posteriors; j++) { + ret = rescale_quantile(num_breaks, original_breaks, rescaled_breaks, &lower[j]); + if (ret != 0) { + goto out; + } + } + for (j = 0; j < num_posteriors; j++) { + ret = rescale_quantile(num_breaks, original_breaks, rescaled_breaks, &upper[j]); + if (ret != 0) { + goto out; + } + } + + /* reproject posteriors using inter-quantile range */ + for (j = 0; j < num_posteriors; j++) { + new_posteriors[2 * j] = NAN; + new_posteriors[2 * j + 1] = NAN; + if (posteriors_fixed[j]) { + continue; + } + if (lower[j] == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + ret = tsd_approximate_gamma_iqr(quant_lower, quant_upper, lower[j], upper[j], + max_shape, gammaincinv, gamma_pars); + if (ret != 0) { + goto out; + } + if (midpt[j] == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + /* choose rate so as to keep mean */ + new_beta = (gamma_pars[0] + 1) / midpt[j]; + new_posteriors[2 * j] = gamma_pars[0]; + new_posteriors[2 * j + 1] = new_beta; + } +out: + tsd_safe_free(lower); + tsd_safe_free(upper); + tsd_safe_free(midpt); + return ret; +} diff --git a/lib/tests/tests.c b/lib/tests/tests.c index 609a3d99..5d71e886 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -48,7 +48,11 @@ test_strerror(void) TSD_ERR_NONPOSITIVE_MOMENTS, TSD_ERR_INVALID_FIXED_AGE, TSD_ERR_UNPHASED_INDIVIDUAL_EDGES, TSD_ERR_BLOCK_OUT_OF_RANGE, TSD_ERR_PHASE_OUT_OF_RANGE, TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED, - TSD_ERR_MUTATION_NODE_NOT_IN_TREE, TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT }; + TSD_ERR_MUTATION_NODE_NOT_IN_TREE, TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT, + TSD_ERR_NONPOSITIVE_INTERVALS, TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER, + TSD_ERR_ZERO_EDGE_SPAN, TSD_ERR_NON_INCREASING_BREAKPOINTS, + TSD_ERR_INVALID_QUANTILE_WIDTH, TSD_ERR_INVALID_POSTERIOR, + TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT, TSD_ERR_NO_POSTERIORS }; const int num_codes = (int) (sizeof(codes) / sizeof(codes[0])); const char *msg_i; const char *msg_j; @@ -917,6 +921,231 @@ test_conditional_coalescent_variance(void) } } +/* ---- rescaling ---- */ + +static void +test_fixed_changepoints(void) +{ + const double counts[] = { 1.0, 2.0, 3.0, 4.0 }; + const double zeros[] = { 0.0, 0.0 }; + tsd_id_t *breaks = NULL; + tsd_size_t num_breaks; + int ret; + + ret = tsd_fixed_changepoints(4, counts, 2, &breaks, &num_breaks); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(num_breaks, 3); + CU_ASSERT_EQUAL(breaks[0], 0); + CU_ASSERT_EQUAL(breaks[2], 4); + tsd_safe_free(breaks); + /* no counts: NaN cumulative distribution, and no observations at all */ + ret = tsd_fixed_changepoints(2, zeros, 3, &breaks, &num_breaks); + CU_ASSERT_EQUAL(ret, 0); + tsd_safe_free(breaks); + ret = tsd_fixed_changepoints(0, counts, 1, &breaks, &num_breaks); + CU_ASSERT_EQUAL(ret, 0); + tsd_safe_free(breaks); + ret = tsd_fixed_changepoints(4, counts, 0, &breaks, &num_breaks); + CU_ASSERT_EQUAL(ret, TSD_ERR_NONPOSITIVE_INTERVALS); +} + +static void +test_poisson_changepoints(void) +{ + const double counts[] = { 5.0, 6.0, 20.0, 22.0, 21.0, 3.0 }; + const double offset[] = { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; + tsd_id_t *breaks = NULL; + tsd_size_t num_breaks; + int ret; + + ret = tsd_poisson_changepoints( + 6, counts, offset, 2.0, 0.0, 0.0, &breaks, &num_breaks); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(num_breaks >= 2); + CU_ASSERT_EQUAL(breaks[0], 0); + CU_ASSERT_EQUAL(breaks[num_breaks - 1], 6); + tsd_safe_free(breaks); + /* thresholds that rule out short segments */ + ret = tsd_poisson_changepoints( + 6, counts, offset, 2.0, 21.0, 1.5, &breaks, &num_breaks); + CU_ASSERT_EQUAL(ret, 0); + tsd_safe_free(breaks); + ret = tsd_poisson_changepoints( + 0, counts, offset, 2.0, 0.0, 0.0, &breaks, &num_breaks); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(num_breaks, 1); + tsd_safe_free(breaks); + ret = tsd_poisson_changepoints( + 6, counts, offset, -1.0, 0.0, 0.0, &breaks, &num_breaks); + CU_ASSERT_EQUAL(ret, TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER); + ret = tsd_poisson_changepoints( + 6, counts, offset, 2.0, NAN, 0.0, &breaks, &num_breaks); + CU_ASSERT_EQUAL(ret, TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER); +} + +/* + * Two samples (nodes 0 and 1) below a root (node 2), with edges over [0, 10), and a + * mutation on each sample branch and one above the root. + */ +static void +test_count_mutations(void) +{ + const uint8_t is_sample[] = { 1, 1, 0 }; + const tsd_id_t mutations_node[] = { 1, 0, 2 }; + const double mutations_position[] = { 6.0, 1.0, 2.0 }; + const tsd_id_t parent[] = { 2, 2 }; + const tsd_id_t child[] = { 0, 1 }; + const double left[] = { 0.0, 0.0 }; + const double right[] = { 10.0, 5.0 }; + const tsd_id_t insert[] = { 0, 1 }; + const tsd_id_t remove[] = { 1, 0 }; + double stats[4]; + tsd_id_t mutations_edge[3]; + int size_biased; + int ret; + + for (size_biased = 0; size_biased < 2; size_biased++) { + ret = tsd_count_mutations(3, is_sample, 3, mutations_node, mutations_position, 2, + parent, child, left, right, insert, remove, 10.0, size_biased, stats, + mutations_edge); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(mutations_edge[0], -1); + CU_ASSERT_EQUAL(mutations_edge[1], 0); + CU_ASSERT_EQUAL(mutations_edge[2], -1); + CU_ASSERT_EQUAL(stats[0], 1.0); + CU_ASSERT_EQUAL(stats[1], 10.0); + CU_ASSERT_EQUAL(stats[3], 5.0); + } + /* no edges, no mutations */ + ret = tsd_count_mutations(3, is_sample, 0, NULL, NULL, 0, NULL, NULL, NULL, NULL, + NULL, NULL, 10.0, 0, NULL, NULL); + CU_ASSERT_EQUAL(ret, 0); +} + +/* Two samples at time zero, below a node at time 1, below a root at time 2. */ +static void +test_mutational_area_and_timescale(void) +{ + const double nodes_time[] = { 0.0, 0.0, 1.0, 2.0 }; + const double likelihoods[] = { 2.0, 10.0, 1.0, 10.0, 3.0, 10.0 }; + const double zero_span[] = { 2.0, 0.0, 1.0, 0.0, 3.0, 0.0 }; + const tsd_id_t parent[] = { 2, 2, 3 }; + const tsd_id_t child[] = { 0, 1, 2 }; + tsd_epoch_stats_t stats; + tsd_id_t nodes_index[4]; + tsd_size_t num_breaks; + double *origin = NULL; + double *adjust = NULL; + int ret; + + ret = tsd_mutational_area( + 4, nodes_time, 3, likelihoods, parent, child, &stats, nodes_index); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(stats.num_epochs, 2); + CU_ASSERT_EQUAL(nodes_index[3], 2); + tsd_epoch_stats_free(&stats); + /* no nodes */ + ret = tsd_mutational_area(0, NULL, 0, NULL, NULL, NULL, &stats, NULL); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(stats.num_epochs, 0); + tsd_epoch_stats_free(&stats); + + ret = tsd_mutational_timescale( + 4, nodes_time, 3, likelihoods, parent, child, 2, &num_breaks, &origin, &adjust); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(num_breaks >= 2); + CU_ASSERT_EQUAL(origin[0], 0.0); + CU_ASSERT_EQUAL(adjust[0], 0.0); + tsd_safe_free(origin); + tsd_safe_free(adjust); + ret = tsd_mutational_timescale( + 4, nodes_time, 3, likelihoods, parent, child, 0, &num_breaks, &origin, &adjust); + CU_ASSERT_EQUAL(ret, TSD_ERR_NONPOSITIVE_INTERVALS); + ret = tsd_mutational_timescale( + 4, nodes_time, 3, zero_span, parent, child, 2, &num_breaks, &origin, &adjust); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_EDGE_SPAN); + /* all nodes at time zero: there are no epochs, and the span is zero */ + ret = tsd_mutational_timescale( + 2, nodes_time, 0, NULL, NULL, NULL, 1, &num_breaks, &origin, &adjust); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_EDGE_SPAN); +} + +static void +test_piecewise_scale_point_estimate(void) +{ + const double estimate[] = { 0.5, 1.5, 4.0, -1.0, NAN }; + const uint8_t fixed[] = { 0, 0, 1, 0, 0 }; + const double original[] = { 0.0, 1.0, 3.0 }; + const double rescaled[] = { 0.0, 2.0, 3.5 }; + const double flat[] = { 0.0, 2.0, 2.0 }; + double out[5]; + int ret; + + ret = tsd_piecewise_scale_point_estimate( + 5, estimate, fixed, 3, original, rescaled, out); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_DOUBLE_EQUAL(out[0], 1.0, 1e-12); + CU_ASSERT_DOUBLE_EQUAL(out[1], 2.375, 1e-12); + CU_ASSERT_EQUAL(out[2], 4.0); + CU_ASSERT(isnan(out[4])); + ret = tsd_piecewise_scale_point_estimate(5, estimate, fixed, 3, original, flat, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_NON_INCREASING_BREAKPOINTS); + ret = tsd_piecewise_scale_point_estimate(5, estimate, fixed, 3, flat, rescaled, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_NON_INCREASING_BREAKPOINTS); +} + +static void +test_piecewise_scale_posterior(void) +{ + const double posteriors[] = { 1.0, 1.0, 2.0, 3.0, 0.0, 1.0, 5.0, 2.0 }; + const uint8_t fixed[] = { 0, 0, 1, 0 }; + const uint8_t none_fixed[] = { 0, 0, 0, 0 }; + const double original[] = { 0.0, 1.0, 3.0 }; + const double rescaled[] = { 0.0, 2.0, 3.5 }; + const double late_original[] = { 0.5, 1.0, 3.0 }; + const double flat[] = { 0.0, 2.0, 2.0 }; + const double bad_posteriors[] = { -1.0, 1.0, 1.0, 1.0 }; + const double zero_rate[] = { 1.0, INFINITY }; + const double near_pole[] = { -0.9999, 1.0 }; + double out[8]; + int ret; + + ret = tsd_piecewise_scale_posterior( + 4, posteriors, fixed, 3, original, rescaled, 0.5, 1000.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(isnan(out[4])); + CU_ASSERT(isfinite(out[0]) && isfinite(out[1])); + ret = tsd_piecewise_scale_posterior(4, posteriors, none_fixed, 3, original, rescaled, + 0.5, 1000.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, 0); + ret = tsd_piecewise_scale_posterior( + 4, posteriors, fixed, 3, original, rescaled, 1.0, 1000.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_QUANTILE_WIDTH); + ret = tsd_piecewise_scale_posterior( + 4, posteriors, fixed, 3, original, flat, 0.5, 1000.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_NON_INCREASING_BREAKPOINTS); + ret = tsd_piecewise_scale_posterior(2, bad_posteriors, none_fixed, 3, original, + rescaled, 0.5, 1000.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_POSTERIOR); + ret = tsd_piecewise_scale_posterior(4, posteriors, fixed, 3, late_original, rescaled, + 0.5, 1000.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT); + ret = tsd_piecewise_scale_posterior( + 0, posteriors, fixed, 3, original, rescaled, 0.5, 1000.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_NO_POSTERIORS); + /* an infinite rate gives a zero lower quantile, and a zero rate a zero mean */ + ret = tsd_piecewise_scale_posterior(1, zero_rate, none_fixed, 3, original, rescaled, + 0.5, 1000.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + ret = tsd_piecewise_scale_posterior(1, near_pole, none_fixed, 3, original, rescaled, + 0.5, 1000.0, test_zero_inv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + /* failures of the interquantile approximation are passed on */ + ret = tsd_piecewise_scale_posterior(1, posteriors, none_fixed, 3, original, rescaled, + 0.5, 1000.0, test_zero_inv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); +} + static void handle_cunit_error(void) { @@ -965,6 +1194,12 @@ main(int argc, char **argv) { "test_constrain_ages", test_constrain_ages }, { "test_contains_unary_nodes", test_contains_unary_nodes }, { "test_conditional_coalescent_variance", test_conditional_coalescent_variance }, + { "test_fixed_changepoints", test_fixed_changepoints }, + { "test_poisson_changepoints", test_poisson_changepoints }, + { "test_count_mutations", test_count_mutations }, + { "test_mutational_area_and_timescale", test_mutational_area_and_timescale }, + { "test_piecewise_scale_point_estimate", test_piecewise_scale_point_estimate }, + { "test_piecewise_scale_posterior", test_piecewise_scale_posterior }, CU_TEST_INFO_NULL, }; CU_SuiteInfo suites[] = { diff --git a/lib/tsdate.h b/lib/tsdate.h index add62f59..75ef8b61 100644 --- a/lib/tsdate.h +++ b/lib/tsdate.h @@ -232,6 +232,60 @@ int tsd_marginalize_over_ancestors( tsd_size_t num_tips, tsd_size_t num_moments, const double *val, double *out); /* `variance` has `num_tips + 1` entries; `num_tips` >= 1. */ int tsd_conditional_coalescent_variance(tsd_size_t num_tips, double *variance); +/* + * Time rescaling (rescaling.c). + * + * Array arguments are contiguous. `likelihoods` and the edge statistics are + * row-major with two columns per edge (mutation count, mutational span). The + * functions that return arrays whose size is not known beforehand allocate them + * with malloc, and the caller frees them (tsd_safe_free, tsd_epoch_stats_free). + * Array sizes are the caller's responsibility (tsd_bug_assert); the numerical + * preconditions that numba asserted are reported as errors. + */ + +/* Per-epoch results of tsd_mutational_area; every array has `num_epochs` entries. */ +typedef struct { + tsd_size_t num_epochs; + double *counts; + double *offset; + double *duration; +} tsd_epoch_stats_t; + +void tsd_epoch_stats_free(tsd_epoch_stats_t *stats); + +/* Breakpoints (`*num_breaks == epochs + 1` of them) dividing the counts roughly + * equally between `epochs` epochs. */ +int tsd_fixed_changepoints(tsd_size_t num_counts, const double *counts, int64_t epochs, + tsd_id_t **breaks, tsd_size_t *num_breaks); +int tsd_poisson_changepoints(tsd_size_t num_counts, const double *counts, + const double *offset, double penalty, double min_counts, double min_offset, + tsd_id_t **breaks, tsd_size_t *num_breaks); +/* `edges_stats` has 2 * num_edges entries and `mutations_edge` num_mutations. */ +int tsd_count_mutations(tsd_size_t num_nodes, const uint8_t *node_is_sample, + tsd_size_t num_mutations, const tsd_id_t *mutations_node, + const double *mutations_position, tsd_size_t num_edges, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, const double *edges_left, const double *edges_right, + const tsd_id_t *indexes_insert, const tsd_id_t *indexes_remove, + double sequence_length, int size_biased, double *edges_stats, + tsd_id_t *mutations_edge); +/* `nodes_index` has num_nodes entries. */ +int tsd_mutational_area(tsd_size_t num_nodes, const double *nodes_time, + tsd_size_t num_edges, const double *likelihoods, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, tsd_epoch_stats_t *stats, tsd_id_t *nodes_index); +/* `*origin` and `*adjust` have `*num_breaks` entries. */ +int tsd_mutational_timescale(tsd_size_t num_nodes, const double *nodes_time, + tsd_size_t num_edges, const double *likelihoods, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, int64_t max_intervals, tsd_size_t *num_breaks, + double **origin, double **adjust); +/* There must be at least one breakpoint; `rescaled` has `num_points` entries. */ +int tsd_piecewise_scale_point_estimate(tsd_size_t num_points, + const double *point_estimate, const uint8_t *point_fixed, tsd_size_t num_breaks, + const double *original_breaks, const double *rescaled_breaks, double *rescaled); +/* `posteriors` and `new_posteriors` are natural parameters, row-major, two columns. */ +int tsd_piecewise_scale_posterior(tsd_size_t num_posteriors, const double *posteriors, + const uint8_t *posteriors_fixed, tsd_size_t num_breaks, + const double *original_breaks, const double *rescaled_breaks, double quantile_width, + double max_shape, tsd_gammaincinv_fn gammaincinv, double *new_posteriors); #ifdef __cplusplus } diff --git a/setup.py b/setup.py index 5d91696e..203868ab 100644 --- a/setup.py +++ b/setup.py @@ -9,7 +9,15 @@ libdir = "lib" includes = [libdir] -tsd_source_files = ["err.c", "hypergeo.c", "approx.c", "phasing.c", "util.c", "prior.c"] +tsd_source_files = [ + "err.c", + "hypergeo.c", + "approx.c", + "rescaling.c", + "phasing.c", + "util.c", + "prior.c", +] sources = ["_tsdatemodule.c"] + [os.path.join(libdir, f) for f in tsd_source_files] diff --git a/tests/oracle/implementations.py b/tests/oracle/implementations.py index fcaf041f..718bb288 100644 --- a/tests/oracle/implementations.py +++ b/tests/oracle/implementations.py @@ -200,6 +200,18 @@ def _c_prior(_tsdate): ) +def _c_rescaling(_tsdate): + return _PortedNamespace( + _fixed_changepoints=_tsdate.fixed_changepoints, + _poisson_changepoints=_tsdate.poisson_changepoints, + _count_mutations=_tsdate.count_mutations, + mutational_area=_tsdate.mutational_area, + mutational_timescale=_tsdate.mutational_timescale, + piecewise_scale_point_estimate=_tsdate.piecewise_scale_point_estimate, + piecewise_scale_posterior=_tsdate.piecewise_scale_posterior, + ) + + def _c_namespace(): import _tsdate @@ -207,7 +219,7 @@ def _c_namespace(): hypergeo=_c_hypergeo(_tsdate), approx=_c_approx(_tsdate), variational=_PortedNamespace(), - rescaling=_PortedNamespace(), + rescaling=_c_rescaling(_tsdate), phasing=_c_phasing(_tsdate), util=_c_util(_tsdate), prior=_c_prior(_tsdate), diff --git a/tests/test_python_c_rescaling.py b/tests/test_python_c_rescaling.py new file mode 100644 index 00000000..d349eccb --- /dev/null +++ b/tests/test_python_c_rescaling.py @@ -0,0 +1,146 @@ +""" +Tests of the rescaling functions of the low-level _tsdate module that the oracle tests +in test_oracle_rescaling.py do not reach: argument handling, and inputs outside what +a tree sequence can produce. Values are compared with the oracles. +""" + +import _tsdate +import numpy as np +import pytest +from oracle import rescaling +from oracle.helpers import compare + +NODES_TIME = np.array([0.0, 0.0, 1.0, 2.0]) +PARENTS = np.array([2, 3], dtype=np.int32) +CHILDREN = np.array([0, 2], dtype=np.int32) + + +class TestArguments: + def test_epochs_beyond_int32(self): + with pytest.raises(OverflowError): + _tsdate.fixed_changepoints(np.ones(3), 2**70) + + def test_wrong_dtype(self): + with pytest.raises(TypeError): + _tsdate.mutational_area( + NODES_TIME, np.ones((2, 2)), PARENTS.astype(np.int64), CHILDREN + ) + + def test_wrong_dimension(self): + with pytest.raises(ValueError, match="depth"): + _tsdate.mutational_area(NODES_TIME, np.ones(4), PARENTS, CHILDREN) + + def test_empty_breaks(self): + empty = np.zeros(0) + with pytest.raises(ValueError, match="non-empty"): + _tsdate.piecewise_scale_point_estimate( + np.zeros(1), np.zeros(1, dtype=bool), empty, empty + ) + with pytest.raises(ValueError, match="non-empty"): + _tsdate.piecewise_scale_posterior( + np.ones((1, 2)), np.zeros(1, dtype=bool), empty, empty, 0.5, 1000.0 + ) + + def test_point_estimate_fixed_size(self): + with pytest.raises(ValueError, match="same size"): + _tsdate.piecewise_scale_point_estimate( + np.zeros(2), np.zeros(1, dtype=bool), np.zeros(1), np.zeros(1) + ) + + def test_posterior_columns(self): + with pytest.raises(ValueError, match="two columns"): + _tsdate.piecewise_scale_posterior( + np.ones((1, 3)), + np.zeros(1, dtype=bool), + np.zeros(1), + np.zeros(1), + 0.5, + 1.0, + ) + + def test_poisson_sizes(self): + with pytest.raises(ValueError, match="same size"): + _tsdate.poisson_changepoints(np.ones(3), np.ones(2), 2.0, 0.0, 0.0) + + def test_count_mutations_sizes(self): + args = [ + np.zeros(2, dtype=bool), + np.zeros(1, dtype=np.int32), + np.zeros(1), + np.zeros(1, dtype=np.int32), + np.zeros(1, dtype=np.int32), + np.zeros(1), + np.zeros(1), + np.zeros(1, dtype=np.int32), + np.zeros(1, dtype=np.int32), + 1.0, + False, + ] + for index in [4, 7, 2]: + bad = list(args) + bad[index] = np.zeros(2, dtype=bad[index].dtype) + with pytest.raises(ValueError, match="same size|one entry per edge"): + _tsdate.count_mutations(*bad) + + +class TestOutsideTreeSequences: + def test_nan_node_times(self): + # NaN is ordered last, whichever its position + times = np.array([0.0, np.nan, 1.0, np.nan, 2.0]) + likelihoods = np.array([[1.0, 1.0], [1.0, 1.0]]) + parents = np.array([2, 4], dtype=np.int32) + children = np.array([0, 2], dtype=np.int32) + compare( + _tsdate.mutational_area, + rescaling.mutational_area, + times, + likelihoods, + parents, + children, + ) + + def test_changepoint_before_the_first_epoch(self): + # The mutational spans make the offsets of the four epochs 1, 1, -3 and 1, so + # that the total weight is zero and the cumulative distribution is NaN where + # it is looked up: the first changepoint is -1, which counts from the end as + # in numpy. + nodes_time = np.array([0.0, 0.0, 1.0, 2.0, 3.0, 4.0]) + likelihoods = np.array([[1.0, 1.0], [1.0, 1.0], [1.0, -3.0], [1.0, 1.0]]) + parents = np.array([2, 3, 4, 5], dtype=np.int32) + children = np.array([0, 2, 3, 4], dtype=np.int32) + fixed = np.full(6, False) + args = (nodes_time, likelihoods, fixed, parents, children, 2) + result = compare( + _tsdate.mutational_timescale, rescaling.mutational_timescale, *args + ) + assert result.value[0].tolist() == [4.0, 4.0] + + def test_quantile_below_first_breakpoint(self): + # the lower quantile (1.1) is below the first breakpoint, the mean (2) is not + args = ( + np.array([[1.0, 1.0]]), + np.array([False]), + np.array([1.5, 3.0, 5.0]), + np.array([0.0, 1.0, 2.0]), + 0.5, + 1000.0, + ) + result = compare( + _tsdate.piecewise_scale_posterior, rescaling.piecewise_scale_posterior, *args + ) + assert isinstance(result.exception, AssertionError) + + def test_fixed_posteriors_below_first_breakpoint(self): + # the rescaled quantiles of fixed posteriors are zero, and are checked too + args = ( + np.array([[1.0, 1.0]]), + np.array([True]), + np.array([0.5, 2.0, 5.0]), + np.array([0.0, 1.0, 2.0]), + 0.5, + 1000.0, + ) + result = compare( + _tsdate.piecewise_scale_posterior, rescaling.piecewise_scale_posterior, *args + ) + assert isinstance(result.exception, AssertionError) From 3f3afdd2605042fdfb9dd704eb44bba896b21463 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Tue, 24 Nov 2026 20:38:33 -0800 Subject: [PATCH 10/56] Port the jitted functions of tsdate.variational to C Adds lib/variational.c: _damp, _rescale, _rescale_factors, _assemble_factors, _check_valid_constraints, propagate_likelihood (the closure dispatch over edge types is a set of per-branch functions), propagate_prior and propagate_mutations. The EP state stays in numpy arrays owned by Python: the factors are passed to the module as a tuple of the eight arrays of an EPFactors and updated in place, and the GIL is released around each pass. _damp and _rescale are in the scalar table. Results are bit-identical to numba on four sweeps of the test tree sequences. Errors (new codes -30 to -36): - max_shape < 1 (or NaN) and 0 < min_step < 1 failing are parameter errors with messages (TSD_ERR_INVALID_MAX_SHAPE, TSD_ERR_INVALID_MIN_STEP); - the posterior asserts of _damp and _rescale (TSD_ERR_INVALID_NODE_POSTERIOR), the damping assert 0 < d <= 1 (TSD_ERR_INVALID_DAMPING), propagate_prior's penalty > 0 (TSD_ERR_NONPOSITIVE_PENALTY), and the twin_projection assert that an edge with equal parent and child is only used in an unphased pass (TSD_ERR_TWIN_EDGE_IN_PHASED_PASS); - _check_valid_constraints raises TSD_ERR_INCONSISTENT_CONSTRAINTS, with numba's message verbatim; - divisions where numba raises ZeroDivisionError and a test pins it (_damp by y, _rescale by x[0]) return TSD_ERR_ZERO_DIVISION; errors of the approx projections are forwarded; - array size and shape asserts are ValueError in the module. Arrays that are updated in place must not need converting (a copy would lose the update), so they raise ValueError instead of being copied. Deviations from numba: array sizes are checked in the module, but node and edge ids are not; lognorm must have one entry per edge. The oracle tests of tests.oracle.variational now run against C, with adapters in implementations.py; microbench registers the three passes for C. --- _tsdatemodule.c | 479 +++++++++++++++++++ evaluation/microbench.py | 27 ++ lib/err.c | 24 + lib/err.h | 9 + lib/meson.build | 2 +- lib/tests/tests.c | 304 +++++++++++- lib/tsdate.h | 63 +++ lib/variational.c | 734 +++++++++++++++++++++++++++++ setup.py | 1 + tests/oracle/implementations.py | 114 ++++- tests/test_python_c_variational.py | 334 +++++++++++++ 11 files changed, 2088 insertions(+), 3 deletions(-) create mode 100644 lib/variational.c create mode 100644 tests/test_python_c_variational.py diff --git a/_tsdatemodule.c b/_tsdatemodule.c index 76a6e372..b6e7c741 100644 --- a/_tsdatemodule.c +++ b/_tsdatemodule.c @@ -408,6 +408,19 @@ adapt_mutation_block_projection(const double *in, double *out) return tsd_mutation_block_projection(in[0], in[1], out, out + 1); } +/* variational: x and y are the natural parameters of two gammas, in `in` */ +static int +adapt_damp(const double *in, double *out) +{ + return tsd_damp(in, in + 2, in[4], out); +} + +static int +adapt_rescale(const double *in, double *out) +{ + return tsd_rescale(in, in[2], out); +} + /* clang-format off */ static const scalar_function_t scalar_functions[] = { /* hypergeo */ @@ -461,6 +474,9 @@ static const scalar_function_t scalar_functions[] = { { "mutation_twin_projection", 4, 3, adapt_mutation_twin_projection }, { "mutation_sideways_projection", 5, 3, adapt_mutation_sideways_projection }, { "mutation_block_projection", 2, 3, adapt_mutation_block_projection }, + /* variational: x0, x1, [y0, y1,] s */ + { "damp", 5, 1, adapt_damp }, + { "rescale", 3, 1, adapt_rescale }, }; /* clang-format on */ @@ -1740,6 +1756,457 @@ tsdate_piecewise_scale_posterior(PyObject *Py_UNUSED(self), PyObject *args) return ret; } +/* + * Expectation propagation. The factors are passed as a tuple of eight arrays, + * (node, edge, block, scale, edges_parent, edges_child, blocks_left, blocks_right), + * the fields of EPFactors; the arrays of the first four are updated in place by the + * passes that change them. + */ +#define NUM_FACTOR_ARRAYS 8 + +typedef struct { + PyArrayObject *arrays[NUM_FACTOR_ARRAYS]; + tsd_ep_factors_t c; +} py_factors_t; + +static void +release_factors(py_factors_t *factors) +{ + release_arrays(factors->arrays, NUM_FACTOR_ARRAYS); +} + +/* + * A float64 array of the given dimension that the call updates in place: `obj` itself, + * which must not need converting (a copy would silently lose the updates). + */ +static PyArrayObject * +get_inout_array(PyObject *obj, int ndim) +{ + PyArrayObject *ret = (PyArrayObject *) PyArray_FROMANY( + obj, NPY_FLOAT64, ndim, ndim, NPY_ARRAY_INOUT_ARRAY); + + if (ret != NULL && (PyObject *) ret != obj) { + Py_DECREF(ret); + ret = NULL; + PyErr_SetString(PyExc_ValueError, + "Arrays that are updated must be writeable, C-contiguous float64 arrays"); + } + return ret; +} + +/* + * Parse a tuple of factors, writing the sizes and pointers to `factors->c`. The arrays + * that the caller needs to update must be (and are required to be) writeable, aligned + * and C-contiguous if `writeable`. Returns 0, or -1 with an exception. + */ +static int +parse_factors(PyObject *obj, int writeable, py_factors_t *factors) +{ + int ret = -1; + const int typenums[NUM_FACTOR_ARRAYS] = { NPY_FLOAT64, NPY_FLOAT64, NPY_FLOAT64, + NPY_FLOAT64, NPY_INT32, NPY_INT32, NPY_INT32, NPY_INT32 }; + const int ndims[NUM_FACTOR_ARRAYS] = { 3, 3, 3, 1, 1, 1, 1, 1 }; + PyArrayObject **a = factors->arrays; + PyObject *item; + int j; + + if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != NUM_FACTOR_ARRAYS) { + PyErr_SetString(PyExc_TypeError, "factors must be a tuple of eight arrays"); + goto out; + } + for (j = 0; j < NUM_FACTOR_ARRAYS; j++) { + item = PyTuple_GET_ITEM(obj, j); + if (writeable && j < 4) { + a[j] = get_inout_array(item, ndims[j]); + } else { + a[j] = (PyArrayObject *) PyArray_FROMANY( + item, typenums[j], ndims[j], ndims[j], NPY_ARRAY_IN_ARRAY); + } + if (a[j] == NULL) { + goto out; + } + } + for (j = 0; j < 3; j++) { + if (check_sizes(PyArray_DIM(a[j], 1) == 2 && PyArray_DIM(a[j], 2) == 2, + "Factors must have shape (n, 2, 2)") + != 0) { + goto out; + } + } + if (check_sizes(ARRAY_DIM(a[0], 0) == ARRAY_SIZE(a[3]) + && ARRAY_DIM(a[1], 0) == ARRAY_SIZE(a[4]) + && ARRAY_DIM(a[1], 0) == ARRAY_SIZE(a[5]) + && ARRAY_DIM(a[2], 0) == ARRAY_SIZE(a[6]) + && ARRAY_DIM(a[2], 0) == ARRAY_SIZE(a[7]), + "Factor arrays have inconsistent sizes") + != 0) { + goto out; + } + factors->c.num_nodes = ARRAY_DIM(a[0], 0); + factors->c.num_edges = ARRAY_DIM(a[1], 0); + factors->c.num_blocks = ARRAY_DIM(a[2], 0); + factors->c.node = (double *) PyArray_DATA(a[0]); + factors->c.edge = (double *) PyArray_DATA(a[1]); + factors->c.block = (double *) PyArray_DATA(a[2]); + factors->c.scale = (double *) PyArray_DATA(a[3]); + factors->c.edges_parent = IDS(a[4]); + factors->c.edges_child = IDS(a[5]); + factors->c.blocks_left = IDS(a[6]); + factors->c.blocks_right = IDS(a[7]); + ret = 0; +out: + return ret; +} + +/* Whether `array` has `rows` rows of two columns; else raise ValueError. */ +static int +check_pairs(PyArrayObject *array, tsd_size_t rows, const char *message) +{ + return check_sizes( + ARRAY_DIM(array, 0) == rows && PyArray_DIM(array, 1) == 2, message); +} + +/* rescale_factors(factors): multiply the factors by the node scales, in place. */ +static PyObject * +tsdate_rescale_factors(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *factors_obj = NULL; + py_factors_t factors = { { NULL }, { 0 } }; + + if (!PyArg_ParseTuple(args, "O", &factors_obj)) { + goto out; + } + if (parse_factors(factors_obj, 1, &factors) != 0) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + tsd_rescale_factors(&factors.c); + Py_END_ALLOW_THREADS + ret = Py_None; + Py_INCREF(ret); +out: + release_factors(&factors); + return ret; +} + +/* assemble_factors(factors): the posteriors implied by the factors. */ +static PyObject * +tsdate_assemble_factors(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *factors_obj = NULL; + PyObject *posterior = NULL; + py_factors_t factors = { { NULL }, { 0 } }; + npy_intp dims[2]; + + if (!PyArg_ParseTuple(args, "O", &factors_obj)) { + goto out; + } + if (parse_factors(factors_obj, 0, &factors) != 0) { + goto out; + } + dims[0] = (npy_intp) factors.c.num_nodes; + dims[1] = 2; + posterior = PyArray_SimpleNew(2, dims, NPY_FLOAT64); + if (posterior == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + tsd_assemble_factors( + &factors.c, (double *) PyArray_DATA((PyArrayObject *) posterior)); + Py_END_ALLOW_THREADS + ret = posterior; + posterior = NULL; +out: + release_factors(&factors); + Py_XDECREF(posterior); + return ret; +} + +/* check_valid_constraints(constraints, edges_parent, edges_child) */ +static PyObject * +tsdate_check_valid_constraints(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *obj[3]; + PyArrayObject *constraints = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + int err; + + if (!PyArg_ParseTuple(args, "OOO", &obj[0], &obj[1], &obj[2])) { + goto out; + } + constraints = get_array(obj[0], NPY_FLOAT64, 2); + edges_parent = get_array(obj[1], NPY_INT32, 1); + edges_child = get_array(obj[2], NPY_INT32, 1); + if (constraints == NULL || edges_parent == NULL || edges_child == NULL) { + goto out; + } + if (check_pairs( + constraints, ARRAY_DIM(constraints, 0), "Constraints must have two columns") + != 0 + || check_sizes(ARRAY_LEN(edges_parent) == ARRAY_LEN(edges_child), + "Edge arrays must have the same size") + != 0) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_check_valid_constraints(ARRAY_LEN(constraints), ARRAY_LEN(edges_parent), + DOUBLES(constraints), IDS(edges_parent), IDS(edges_child)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = Py_None; + Py_INCREF(ret); +out: + Py_XDECREF(constraints); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + return ret; +} + +/* + * propagate_likelihood(edge_order, edges_parent, edges_child, likelihoods, + * constraints, posterior, factors, lognorm, max_shape, min_step, unphased) + * updates posterior, the factors and lognorm in place. + */ +static PyObject * +tsdate_propagate_likelihood(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *obj[8]; + PyArrayObject *edge_order = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *likelihoods = NULL; + PyArrayObject *constraints = NULL; + PyArrayObject *posterior = NULL; + PyArrayObject *lognorm = NULL; + py_factors_t factors = { { NULL }, { 0 } }; + double max_shape, min_step; + int unphased; + tsd_size_t num_edges; + int err; + + if (!PyArg_ParseTuple(args, "OOOOOOOOddp", &obj[0], &obj[1], &obj[2], &obj[3], + &obj[4], &obj[5], &obj[6], &obj[7], &max_shape, &min_step, &unphased)) { + goto out; + } + edge_order = get_array(obj[0], NPY_INT32, 1); + edges_parent = get_array(obj[1], NPY_INT32, 1); + edges_child = get_array(obj[2], NPY_INT32, 1); + likelihoods = get_array(obj[3], NPY_FLOAT64, 2); + constraints = get_array(obj[4], NPY_FLOAT64, 2); + posterior = get_inout_array(obj[5], 2); + lognorm = get_inout_array(obj[7], 1); + if (edge_order == NULL || edges_parent == NULL || edges_child == NULL + || likelihoods == NULL || constraints == NULL || posterior == NULL + || lognorm == NULL) { + goto out; + } + if (parse_factors(obj[6], 1, &factors) != 0) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + if (check_sizes( + ARRAY_LEN(edges_child) == num_edges, "Edge arrays must have the same size") + != 0 + || check_pairs(likelihoods, num_edges, "Likelihoods must have shape (edges, 2)") + != 0 + || check_pairs(constraints, factors.c.num_nodes, + "Constraints must have shape (nodes, 2)") + != 0 + || check_pairs(posterior, factors.c.num_nodes, + "Posterior must have the same shape as constraints") + != 0 + || check_sizes( + ARRAY_LEN(lognorm) == num_edges, "Lognorm must have one entry per edge") + != 0 + || check_sizes( + num_edges == (unphased ? factors.c.num_blocks : factors.c.num_edges), + "Factors must have one entry per edge") + != 0) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_propagate_likelihood(ARRAY_LEN(edge_order), IDS(edge_order), num_edges, + IDS(edges_parent), IDS(edges_child), DOUBLES(likelihoods), DOUBLES(constraints), + max_shape, min_step, unphased, (double *) PyArray_DATA(posterior), &factors.c, + (double *) PyArray_DATA(lognorm)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = Py_None; + Py_INCREF(ret); +out: + Py_XDECREF(edge_order); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(likelihoods); + Py_XDECREF(constraints); + Py_XDECREF(posterior); + Py_XDECREF(lognorm); + release_factors(&factors); + return ret; +} + +/* + * propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol) + * updates posterior and the factors in place. + */ +static PyObject * +tsdate_propagate_prior(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *obj[3]; + PyArrayObject *free_nodes = NULL; + PyArrayObject *posterior = NULL; + py_factors_t factors = { { NULL }, { 0 } }; + double max_shape, em_reltol; + long long em_maxitt; + int err; + + if (!PyArg_ParseTuple(args, "OOOdLd", &obj[0], &obj[1], &obj[2], &max_shape, + &em_maxitt, &em_reltol)) { + goto out; + } + free_nodes + = (PyArrayObject *) PyArray_FROMANY(obj[0], NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + posterior = get_inout_array(obj[1], 2); + if (free_nodes == NULL || posterior == NULL) { + goto out; + } + if (parse_factors(obj[2], 1, &factors) != 0) { + goto out; + } + if (check_sizes(ARRAY_LEN(free_nodes) == factors.c.num_nodes + && ARRAY_DIM(posterior, 0) == factors.c.num_nodes + && PyArray_DIM(posterior, 1) == 2, + "The free nodes, posterior and factors must have one entry per node") + != 0) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_propagate_prior(FLAGS(free_nodes), max_shape, (int64_t) em_maxitt, + em_reltol, (double *) PyArray_DATA(posterior), &factors.c); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = Py_None; + Py_INCREF(ret); +out: + Py_XDECREF(free_nodes); + Py_XDECREF(posterior); + release_factors(&factors); + return ret; +} + +/* + * propagate_mutations(mutations_order, mutations_posterior, mutations_phase, + * mutations_edge, edges_parent, edges_child, likelihoods, constraints, posterior, + * factors, unphased) + * updates mutations_posterior and mutations_phase in place. + */ +static PyObject * +tsdate_propagate_mutations(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *obj[10]; + PyArrayObject *mutations_order = NULL; + PyArrayObject *mutations_posterior = NULL; + PyArrayObject *mutations_phase = NULL; + PyArrayObject *mutations_edge = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *likelihoods = NULL; + PyArrayObject *constraints = NULL; + PyArrayObject *posterior = NULL; + py_factors_t factors = { { NULL }, { 0 } }; + int unphased; + tsd_size_t num_edges, num_mutations; + int err; + + if (!PyArg_ParseTuple(args, "OOOOOOOOOOp", &obj[0], &obj[1], &obj[2], &obj[3], + &obj[4], &obj[5], &obj[6], &obj[7], &obj[8], &obj[9], &unphased)) { + goto out; + } + mutations_order = get_array(obj[0], NPY_INT32, 1); + mutations_posterior = get_inout_array(obj[1], 2); + mutations_phase = get_inout_array(obj[2], 1); + mutations_edge = get_array(obj[3], NPY_INT32, 1); + edges_parent = get_array(obj[4], NPY_INT32, 1); + edges_child = get_array(obj[5], NPY_INT32, 1); + likelihoods = get_array(obj[6], NPY_FLOAT64, 2); + constraints = get_array(obj[7], NPY_FLOAT64, 2); + posterior = get_array(obj[8], NPY_FLOAT64, 2); + if (mutations_order == NULL || mutations_posterior == NULL || mutations_phase == NULL + || mutations_edge == NULL || edges_parent == NULL || edges_child == NULL + || likelihoods == NULL || constraints == NULL || posterior == NULL) { + goto out; + } + if (parse_factors(obj[9], 0, &factors) != 0) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + num_mutations = ARRAY_LEN(mutations_phase); + if (check_sizes(ARRAY_LEN(mutations_edge) == num_mutations, + "Mutation arrays must have the same size") + != 0 + || check_pairs(mutations_posterior, num_mutations, + "Mutation posterior must have shape (mutations, 2)") + != 0 + || check_sizes(ARRAY_LEN(edges_child) == num_edges, + "Edge arrays must have the same size") + != 0 + || check_pairs(likelihoods, num_edges, "Likelihoods must have shape (edges, 2)") + != 0 + || check_pairs(constraints, factors.c.num_nodes, + "Constraints must have shape (nodes, 2)") + != 0 + || check_pairs(posterior, factors.c.num_nodes, + "Posterior must have the same shape as constraints") + != 0 + || check_sizes( + num_edges == (unphased ? factors.c.num_blocks : factors.c.num_edges), + "Factors must have one entry per edge") + != 0) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_propagate_mutations(ARRAY_LEN(mutations_order), IDS(mutations_order), + IDS(mutations_edge), IDS(edges_parent), IDS(edges_child), DOUBLES(likelihoods), + DOUBLES(constraints), DOUBLES(posterior), &factors.c, unphased, + (double *) PyArray_DATA(mutations_posterior), + (double *) PyArray_DATA(mutations_phase)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = Py_None; + Py_INCREF(ret); +out: + Py_XDECREF(mutations_order); + Py_XDECREF(mutations_posterior); + Py_XDECREF(mutations_phase); + Py_XDECREF(mutations_edge); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(likelihoods); + Py_XDECREF(constraints); + Py_XDECREF(posterior); + release_factors(&factors); + return ret; +} + static PyMethodDef tsdate_methods[] = { { "strerror", (PyCFunction) tsdate_strerror, METH_VARARGS, "Return the message for a library error code." }, @@ -1782,6 +2249,18 @@ static PyMethodDef tsdate_methods[] = { "Rescale point estimates of node ages." }, { "piecewise_scale_posterior", (PyCFunction) tsdate_piecewise_scale_posterior, METH_VARARGS, "Rescale gamma posteriors of node ages." }, + { "rescale_factors", (PyCFunction) tsdate_rescale_factors, METH_VARARGS, + "Multiply the EP factors by the node scales, in place." }, + { "assemble_factors", (PyCFunction) tsdate_assemble_factors, METH_VARARGS, + "The node posteriors implied by the EP factors." }, + { "check_valid_constraints", (PyCFunction) tsdate_check_valid_constraints, + METH_VARARGS, "Check that node age constraints are consistent with the edges." }, + { "propagate_likelihood", (PyCFunction) tsdate_propagate_likelihood, METH_VARARGS, + "Update the factors of the edge likelihoods, in place." }, + { "propagate_prior", (PyCFunction) tsdate_propagate_prior, METH_VARARGS, + "Update the factors of the prior, in place." }, + { "propagate_mutations", (PyCFunction) tsdate_propagate_mutations, METH_VARARGS, + "Posteriors of the ages of mutations, in place." }, { NULL } /* Sentinel */ }; diff --git a/evaluation/microbench.py b/evaluation/microbench.py index 2f4912e8..ec90da57 100644 --- a/evaluation/microbench.py +++ b/evaluation/microbench.py @@ -79,6 +79,30 @@ def _numba_impl(): } +def _factor_arrays(factors): + """The fields of an ``EPFactors`` as the tuple of arrays that `_tsdate` takes.""" + return ( + factors.node, + factors.edge, + factors.block, + factors.scale, + factors._p, + factors._c, + factors._j, + factors._k, + ) + + +def _with_factors(func, position): + """Wrap a `_tsdate` function so that it takes an ``EPFactors`` at `position`.""" + + def wrapped(*args): + factors = _factor_arrays(args[position]) + return func(*args[:position], factors, *args[position + 1 :]) + + return wrapped + + def _c_impl(): """ Callables of the C implementation. Each ported array-level function is added as @@ -88,6 +112,9 @@ def _c_impl(): import _tsdate return { + "propagate_likelihood": _with_factors(_tsdate.propagate_likelihood, 6), + "propagate_prior": _with_factors(_tsdate.propagate_prior, 2), + "propagate_mutations": _with_factors(_tsdate.propagate_mutations, 9), "_block_singletons": _tsdate.block_singletons, "reallocate_unphased": _tsdate.reallocate_unphased, "_mutation_frequency": _tsdate.mutation_frequency, diff --git a/lib/err.c b/lib/err.c index 89d168e7..6fefe932 100644 --- a/lib/err.c +++ b/lib/err.c @@ -127,6 +127,30 @@ tsd_strerror(int err) ret = "zero-size array to reduction operation minimum which has no " "identity"; break; + case TSD_ERR_INVALID_MAX_SHAPE: + ret = "The maximum shape must be at least one"; + break; + case TSD_ERR_INVALID_MIN_STEP: + ret = "The minimum step size must be greater than zero and less than one"; + break; + case TSD_ERR_INVALID_NODE_POSTERIOR: + ret = "A node posterior has shape not greater than -1 or rate not greater " + "than zero"; + break; + case TSD_ERR_INVALID_DAMPING: + ret = "The damping factor is not greater than zero and at most one"; + break; + case TSD_ERR_INCONSISTENT_CONSTRAINTS: + ret = "Node age constraints are inconsistent, some descendants have" + " lower bounds that exceed upper bounds of their ancestors."; + break; + case TSD_ERR_TWIN_EDGE_IN_PHASED_PASS: + ret = "An edge with the same parent and child can only be updated in an " + "unphased pass"; + break; + case TSD_ERR_NONPOSITIVE_PENALTY: + ret = "The fitted regularisation penalty is not positive"; + break; default: break; } diff --git a/lib/err.h b/lib/err.h index 14c4ee6a..19a19a14 100644 --- a/lib/err.h +++ b/lib/err.h @@ -75,6 +75,15 @@ extern "C" { #define TSD_ERR_INVALID_POSTERIOR -27 #define TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT -28 #define TSD_ERR_NO_POSTERIORS -29 + +/* variational */ +#define TSD_ERR_INVALID_MAX_SHAPE -30 +#define TSD_ERR_INVALID_MIN_STEP -31 +#define TSD_ERR_INVALID_NODE_POSTERIOR -32 +#define TSD_ERR_INVALID_DAMPING -33 +#define TSD_ERR_INCONSISTENT_CONSTRAINTS -34 +#define TSD_ERR_TWIN_EDGE_IN_PHASED_PASS -35 +#define TSD_ERR_NONPOSITIVE_PENALTY -36 /* clang-format on */ #ifdef __GNUC__ diff --git a/lib/meson.build b/lib/meson.build index f40289c0..674e8648 100644 --- a/lib/meson.build +++ b/lib/meson.build @@ -16,7 +16,7 @@ if get_option('buildtype') == 'debug' endif tsdate_sources = ['err.c', 'hypergeo.c', 'approx.c', 'rescaling.c', - 'phasing.c', 'util.c', 'prior.c'] + 'phasing.c', 'util.c', 'prior.c', 'variational.c'] tsdate_lib = static_library('tsdate', sources: tsdate_sources, dependencies: [m_dep], diff --git a/lib/tests/tests.c b/lib/tests/tests.c index 5d71e886..d56bedcd 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -52,7 +52,11 @@ test_strerror(void) TSD_ERR_NONPOSITIVE_INTERVALS, TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER, TSD_ERR_ZERO_EDGE_SPAN, TSD_ERR_NON_INCREASING_BREAKPOINTS, TSD_ERR_INVALID_QUANTILE_WIDTH, TSD_ERR_INVALID_POSTERIOR, - TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT, TSD_ERR_NO_POSTERIORS }; + TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT, TSD_ERR_NO_POSTERIORS, + TSD_ERR_INVALID_MAX_SHAPE, TSD_ERR_INVALID_MIN_STEP, + TSD_ERR_INVALID_NODE_POSTERIOR, TSD_ERR_INVALID_DAMPING, + TSD_ERR_INCONSISTENT_CONSTRAINTS, TSD_ERR_TWIN_EDGE_IN_PHASED_PASS, + TSD_ERR_NONPOSITIVE_PENALTY }; const int num_codes = (int) (sizeof(codes) / sizeof(codes[0])); const char *msg_i; const char *msg_j; @@ -1154,6 +1158,298 @@ handle_cunit_error(void) exit(EXIT_FAILURE); } +/* Expectation propagation (variational.c): a four node, four edge fixture */ +typedef struct { + double node[16]; + double edge[16]; + double block[16]; + double scale[4]; + tsd_id_t parent[4]; + tsd_id_t child[4]; + tsd_id_t left[4]; + tsd_id_t right[4]; + tsd_ep_factors_t factors; +} ep_fixture_t; + +/* Nodes 0 and 1 are fixed, at ages 1 and 5; 2 and 3 are free. */ +static const double ep_constraints[8] = { 1, 1, 5, 5, 0, INFINITY, 0, INFINITY }; +static const double ep_likelihoods[8] = { 1, 0.1, 1, 0.1, 1, 0.1, 1, 0.1 }; + +static void +ep_fixture_init(ep_fixture_t *fixture, const tsd_id_t *parent, const tsd_id_t *child) +{ + tsd_ep_factors_t *f = &fixture->factors; + int j; + + for (j = 0; j < 16; j++) { + fixture->node[j] = 0; + fixture->edge[j] = 0; + fixture->block[j] = 0; + } + for (j = 0; j < 4; j++) { + fixture->scale[j] = 1.0; + fixture->parent[j] = parent[j]; + fixture->child[j] = child[j]; + fixture->left[j] = parent[j]; + fixture->right[j] = child[j]; + } + f->num_nodes = 4; + f->num_edges = 4; + f->num_blocks = 4; + f->node = fixture->node; + f->edge = fixture->edge; + f->block = fixture->block; + f->scale = fixture->scale; + f->edges_parent = fixture->parent; + f->edges_child = fixture->child; + f->blocks_left = fixture->left; + f->blocks_right = fixture->right; +} + +static void +test_damp_and_rescale(void) +{ + const double zero[2] = { 0, 0 }; + const double x[2] = { 1, 2 }; + const double y[2] = { 4, 8 }; + const double improper[2] = { -1, 1 }; + const double infinite[2] = { INFINITY, 1 }; + const double nan_y[2] = { NAN, 0 }; + const double small_y[2] = { 0, 1e300 }; + const double tiny_x[2] = { 1, 1e-300 }; + double d; + + CU_ASSERT_EQUAL(tsd_damp(zero, zero, 5.0, &d), 0); + CU_ASSERT_EQUAL(d, 1.0); + CU_ASSERT_EQUAL(tsd_damp(x, zero, 0.5, &d), 0); + CU_ASSERT_EQUAL(d, 1.0); + CU_ASSERT_EQUAL(tsd_damp(x, y, 0.5, &d), 0); + CU_ASSERT_TRUE(d > 0 && d < 1); + CU_ASSERT_EQUAL(tsd_damp(x, y, 1.0, &d), TSD_ERR_INVALID_MIN_STEP); + CU_ASSERT_EQUAL(tsd_damp(improper, zero, 0.5, &d), TSD_ERR_INVALID_NODE_POSTERIOR); + CU_ASSERT_EQUAL(tsd_damp(infinite, zero, 0.5, &d), TSD_ERR_ZERO_DIVISION); + CU_ASSERT_EQUAL(tsd_damp(x, nan_y, 0.5, &d), TSD_ERR_INVALID_DAMPING); + CU_ASSERT_EQUAL(tsd_damp(tiny_x, small_y, 0.5, &d), TSD_ERR_INVALID_DAMPING); + CU_ASSERT_EQUAL(tsd_damp(tiny_x, y, 0.5, &d), 0); + + CU_ASSERT_EQUAL(tsd_rescale(zero, 0.5, &d), 0); + CU_ASSERT_EQUAL(d, 1.0); + CU_ASSERT_EQUAL(tsd_rescale(x, 10.0, &d), 0); + CU_ASSERT_EQUAL(d, 1.0); + CU_ASSERT_EQUAL(tsd_rescale(x, 1.5, &d), 0); + CU_ASSERT_DOUBLE_EQUAL(d, 0.5, 1e-15); + CU_ASSERT_EQUAL(tsd_rescale(x, 0.1, &d), 0); + CU_ASSERT_EQUAL(tsd_rescale(tiny_x, 1.0, &d), 0); + CU_ASSERT_EQUAL(tsd_rescale(improper, 10.0, &d), TSD_ERR_INVALID_NODE_POSTERIOR); + CU_ASSERT_EQUAL(tsd_rescale(infinite, 10.0, &d), 0); + CU_ASSERT_EQUAL(tsd_rescale(nan_y, 10.0, &d), TSD_ERR_INVALID_NODE_POSTERIOR); + { + const double zero_shape[2] = { 0, 1 }; + const double low[2] = { -0.5, 1 }; + + CU_ASSERT_EQUAL(tsd_rescale(zero_shape, 0.5, &d), TSD_ERR_ZERO_DIVISION); + CU_ASSERT_EQUAL(tsd_rescale(low, 1.0, &d), 0); + CU_ASSERT_EQUAL(tsd_rescale(low, 2.0, &d), 0); + CU_ASSERT_EQUAL(tsd_rescale(low, 1.5, &d), 0); + CU_ASSERT_DOUBLE_EQUAL(d, 2.0 / 3.0, 1e-12); + } +} + +static void +test_rescale_and_assemble_factors(void) +{ + const tsd_id_t parent[4] = { 2, 1, 3, 1 }; + const tsd_id_t child[4] = { 0, 3, 2, 0 }; + ep_fixture_t fixture; + double posterior[8]; + int j; + + ep_fixture_init(&fixture, parent, child); + for (j = 0; j < 16; j++) { + fixture.node[j] = 1.0 + j; + fixture.edge[j] = 1.0 + j; + fixture.block[j] = 0.5 * (1.0 + j); + } + for (j = 0; j < 4; j++) { + fixture.scale[j] = 2.0; + } + tsd_assemble_factors(&fixture.factors, posterior); + CU_ASSERT_TRUE(posterior[0] > 0); + tsd_rescale_factors(&fixture.factors); + CU_ASSERT_EQUAL(fixture.scale[3], 1.0); + CU_ASSERT_EQUAL(fixture.node[0], 2.0); + CU_ASSERT_EQUAL(fixture.edge[0], 2.0); + CU_ASSERT_EQUAL(fixture.block[0], 1.0); +} + +static void +test_check_valid_constraints(void) +{ + const tsd_id_t parent[2] = { 1, 2 }; + const tsd_id_t child[2] = { 0, 1 }; + const double valid[6] = { 0, 0, 1, 5, 2, INFINITY }; + const double invalid[6] = { 3, 3, 1, 2, 2, INFINITY }; + + CU_ASSERT_EQUAL(tsd_check_valid_constraints(3, 2, valid, parent, child), 0); + CU_ASSERT_EQUAL(tsd_check_valid_constraints(3, 0, valid, parent, child), 0); + CU_ASSERT_EQUAL(tsd_check_valid_constraints(3, 2, invalid, parent, child), + TSD_ERR_INCONSISTENT_CONSTRAINTS); + CU_ASSERT_EQUAL(tsd_check_valid_constraints(0, 0, valid, parent, child), 0); +} + +/* The branches of an EP pass: fixed child, fixed parent, free, both fixed. */ +static void +run_likelihood_pass(int unphased, const tsd_id_t *parent, const tsd_id_t *child) +{ + const tsd_id_t order[5] = { 0, 1, 2, 3, 2 }; + ep_fixture_t fixture; + double posterior[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; + double lognorm[4] = { 0 }; + int ret; + + ep_fixture_init(&fixture, parent, child); + ret = tsd_propagate_likelihood(5, order, 4, parent, child, ep_likelihoods, + ep_constraints, 1000.0, 0.1, unphased, posterior, &fixture.factors, lognorm); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isfinite(lognorm[2])); + /* a small scale triggers a rescaling of the factors in mid-pass */ + fixture.scale[2] = 1e-200; + ret = tsd_propagate_likelihood(5, order, 4, parent, child, ep_likelihoods, + ep_constraints, 1000.0, 0.1, unphased, posterior, &fixture.factors, lognorm); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(fixture.scale[0], 1.0); +} + +static void +test_propagate_likelihood(void) +{ + const tsd_id_t parent[4] = { 2, 1, 3, 1 }; + const tsd_id_t child[4] = { 0, 3, 2, 0 }; + const tsd_id_t twin_parent[4] = { 2, 1, 3, 2 }; + const tsd_id_t twin_child[4] = { 0, 3, 2, 2 }; + const tsd_id_t order[1] = { 3 }; + const double huge[8] = { 1, 1e300, 1, 1e300, 1, 1e300, 1, 1e300 }; + ep_fixture_t fixture; + double posterior[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; + double lognorm[4] = { 0 }; + const tsd_id_t sideways[1] = { 0 }; + + run_likelihood_pass(0, parent, child); + run_likelihood_pass(1, parent, child); + ep_fixture_init(&fixture, twin_parent, twin_child); + /* a block with a single node: the twin update, only in an unphased pass */ + CU_ASSERT_EQUAL( + tsd_propagate_likelihood(1, order, 4, twin_parent, twin_child, ep_likelihoods, + ep_constraints, 1000.0, 0.1, 1, posterior, &fixture.factors, lognorm), + 0); + CU_ASSERT_EQUAL( + tsd_propagate_likelihood(1, order, 4, twin_parent, twin_child, ep_likelihoods, + ep_constraints, 1000.0, 0.1, 0, posterior, &fixture.factors, lognorm), + TSD_ERR_TWIN_EDGE_IN_PHASED_PASS); + /* the projection of an edge with a huge mutational target divides by zero */ + CU_ASSERT_EQUAL( + tsd_propagate_likelihood(1, sideways, 4, parent, child, huge, ep_constraints, + 1000.0, 0.1, 1, posterior, &fixture.factors, lognorm), + TSD_ERR_ZERO_DIVISION); + /* an improper posterior, a damping that fails, and bad parameters */ + posterior[4] = -5; + CU_ASSERT_EQUAL( + tsd_propagate_likelihood(1, sideways, 4, parent, child, ep_likelihoods, + ep_constraints, 1000.0, 0.1, 0, posterior, &fixture.factors, lognorm), + TSD_ERR_INVALID_NODE_POSTERIOR); + CU_ASSERT_EQUAL( + tsd_propagate_likelihood(1, order, 4, parent, child, ep_likelihoods, + ep_constraints, 0.5, 0.1, 0, posterior, &fixture.factors, lognorm), + TSD_ERR_INVALID_MAX_SHAPE); + CU_ASSERT_EQUAL( + tsd_propagate_likelihood(1, order, 4, parent, child, ep_likelihoods, + ep_constraints, 1000.0, 1.0, 0.0, posterior, &fixture.factors, lognorm), + TSD_ERR_INVALID_MIN_STEP); +} + +static void +test_propagate_prior(void) +{ + const tsd_id_t parent[4] = { 2, 1, 3, 1 }; + const tsd_id_t child[4] = { 0, 3, 2, 0 }; + const uint8_t free_nodes[4] = { 0, 0, 1, 1 }; + const uint8_t none[4] = { 0, 0, 0, 0 }; + ep_fixture_t fixture; + double posterior[8] = { 0, 0, 0, 0, 2, 1, 3, 2 }; + double improper[8] = { 0, 0, 0, 0, 1, 0, 1, 0 }; + + ep_fixture_init(&fixture, parent, child); + CU_ASSERT_EQUAL( + tsd_propagate_prior(free_nodes, 1000.0, 10, 1e-8, posterior, &fixture.factors), + 0); + CU_ASSERT_TRUE(fixture.node[9] != 0); + CU_ASSERT_EQUAL( + tsd_propagate_prior(none, 0.5, 10, 1e-8, posterior, &fixture.factors), + TSD_ERR_INVALID_MAX_SHAPE); + CU_ASSERT_EQUAL( + tsd_propagate_prior(none, 1000.0, 10, 1e-8, posterior, &fixture.factors), 0); + CU_ASSERT_EQUAL( + tsd_propagate_prior(free_nodes, 1000.0, 10, 1e-8, improper, &fixture.factors), + TSD_ERR_NONPOSITIVE_PENALTY); + /* the fit succeeds, but a posterior that is improper cannot be rescaled */ + posterior[4] = -5; + posterior[6] = 99; + CU_ASSERT_EQUAL( + tsd_propagate_prior(free_nodes, 1000.0, 10, 1e-8, posterior, &fixture.factors), + TSD_ERR_INVALID_NODE_POSTERIOR); +} + +static void +run_mutations_pass(int unphased) +{ + const tsd_id_t parent[4] = { 2, 1, 3, 1 }; + const tsd_id_t child[4] = { 0, 3, 2, 0 }; + const tsd_id_t twin_parent[4] = { 2, 1, 3, 2 }; + const tsd_id_t twin_child[4] = { 0, 3, 2, 2 }; + const tsd_id_t order[6] = { 0, 1, 2, 3, 4, 5 }; + const tsd_id_t edges[6] = { 0, 1, 2, 3, TSD_NULL, 3 }; + const double posterior[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; + const tsd_id_t *twin_edges = twin_parent; + ep_fixture_t fixture; + double mutations_posterior[12]; + double mutations_phase[6]; + int ret; + + ep_fixture_init(&fixture, parent, child); + ret = tsd_propagate_mutations(6, order, edges, parent, child, ep_likelihoods, + ep_constraints, posterior, &fixture.factors, unphased, mutations_posterior, + mutations_phase); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isfinite(mutations_phase[2])); + ep_fixture_init(&fixture, twin_parent, twin_child); + ret = tsd_propagate_mutations(6, order, edges, twin_edges, twin_child, + ep_likelihoods, ep_constraints, posterior, &fixture.factors, unphased, + mutations_posterior, mutations_phase); + CU_ASSERT_EQUAL(ret, 0); +} + +static void +test_propagate_mutations(void) +{ + const tsd_id_t parent[4] = { 2, 1, 3, 1 }; + const tsd_id_t child[4] = { 0, 3, 2, 0 }; + const tsd_id_t order[1] = { 0 }; + const tsd_id_t edge[1] = { 0 }; + const double posterior[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; + const double huge[8] = { 1, 1e300, 1, 1e300, 1, 1e300, 1, 1e300 }; + ep_fixture_t fixture; + double mutations_posterior[2]; + double mutations_phase[1]; + + run_mutations_pass(0); + run_mutations_pass(1); + ep_fixture_init(&fixture, parent, child); + CU_ASSERT_EQUAL( + tsd_propagate_mutations(1, order, edge, parent, child, huge, ep_constraints, + posterior, &fixture.factors, 1, mutations_posterior, mutations_phase), + TSD_ERR_ZERO_DIVISION); +} + int main(int argc, char **argv) { @@ -1200,6 +1496,12 @@ main(int argc, char **argv) { "test_mutational_area_and_timescale", test_mutational_area_and_timescale }, { "test_piecewise_scale_point_estimate", test_piecewise_scale_point_estimate }, { "test_piecewise_scale_posterior", test_piecewise_scale_posterior }, + { "test_damp_and_rescale", test_damp_and_rescale }, + { "test_rescale_and_assemble_factors", test_rescale_and_assemble_factors }, + { "test_check_valid_constraints", test_check_valid_constraints }, + { "test_propagate_likelihood", test_propagate_likelihood }, + { "test_propagate_prior", test_propagate_prior }, + { "test_propagate_mutations", test_propagate_mutations }, CU_TEST_INFO_NULL, }; CU_SuiteInfo suites[] = { diff --git a/lib/tsdate.h b/lib/tsdate.h index 75ef8b61..976cc9d1 100644 --- a/lib/tsdate.h +++ b/lib/tsdate.h @@ -287,6 +287,69 @@ int tsd_piecewise_scale_posterior(tsd_size_t num_posteriors, const double *poste const double *original_breaks, const double *rescaled_breaks, double quantile_width, double max_shape, tsd_gammaincinv_fn gammaincinv, double *new_posteriors); +/* + * Expectation propagation passes (variational.c). + * + * The state of the algorithm stays in arrays owned by the caller, which the passes + * update in place. Natural parameters of a node are two doubles, so the posteriors + * and constraints have two columns, and the factors have shape [n][2][2]: for each + * edge (block), the factor to the parent (first block node) and to the child + * (second), each of two natural parameters; for each node, the mixture prior and the + * constraint. Array sizes are the caller's responsibility (tsd_bug_assert); errors are + * those of the numerical preconditions that numba asserted (parameters, improper + * posteriors), and of the projections. + */ +typedef struct { + tsd_size_t num_nodes; + tsd_size_t num_edges; + tsd_size_t num_blocks; + double *node; /* num_nodes x 2 x 2 */ + double *edge; /* num_edges x 2 x 2 */ + double *block; /* num_blocks x 2 x 2 */ + double *scale; /* num_nodes */ + const tsd_id_t *edges_parent; + const tsd_id_t *edges_child; + const tsd_id_t *blocks_left; + const tsd_id_t *blocks_right; +} tsd_ep_factors_t; + +/* Multiply the factors by the scale of their node, and reset the scale to one. */ +void tsd_rescale_factors(const tsd_ep_factors_t *factors); +/* The posteriors implied by the factors; `posterior` has num_nodes x 2 entries. */ +void tsd_assemble_factors(const tsd_ep_factors_t *factors, double *posterior); +/* The step `d` in (0, 1] so that the cavity `x - d * y` is proper, for `0 < s < 1`. */ +int tsd_damp(const double x[2], const double y[2], double s, double *out); +/* The factor that brings the shape of `x` between 1 / s and s; `s` is `max_shape`. */ +int tsd_rescale(const double x[2], double s, double *out); +/* `constraints` has num_nodes x 2 entries (lower and upper bound). */ +int tsd_check_valid_constraints(tsd_size_t num_nodes, tsd_size_t num_edges, + const double *constraints, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child); +/* + * Update the factors of the edges (blocks of unphased singletons, if `unphased`), + * visited in the given order. `edges_parent`, `edges_child` and `likelihoods` (two + * columns) are those of the edges or blocks; `factors` must have `num_edges` of them. + */ +int tsd_propagate_likelihood(tsd_size_t num_order, const tsd_id_t *edge_order, + tsd_size_t num_edges, const tsd_id_t *edges_parent, const tsd_id_t *edges_child, + const double *likelihoods, const double *constraints, double max_shape, + double min_step, int unphased, double *posterior, const tsd_ep_factors_t *factors, + double *lognorm); +/* Fit an exponential prior to the cavities of the free nodes and update their factors. + */ +int tsd_propagate_prior(const uint8_t *free, double max_shape, int64_t em_maxitt, + double em_reltol, double *posterior, const tsd_ep_factors_t *factors); +/* + * Posteriors (`mutations_posterior`, two columns) and phases of the mutations in the + * given order, from the edges (blocks) above them; `mutations_edge` has the edge of + * each mutation, or TSD_NULL. The factors are not changed. + */ +int tsd_propagate_mutations(tsd_size_t num_order, const tsd_id_t *mutations_order, + const tsd_id_t *mutations_edge, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, const double *likelihoods, const double *constraints, + const double *posterior, const tsd_ep_factors_t *factors, int unphased, + double *mutations_posterior, double *mutations_phase); + #ifdef __cplusplus } #endif diff --git a/lib/variational.c b/lib/variational.c new file mode 100644 index 00000000..3d4f057c --- /dev/null +++ b/lib/variational.c @@ -0,0 +1,734 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* + * The expectation propagation passes, ported from tsdate/variational.py (numba): the + * damping helpers, the passes over edges (blocks of unphased singletons), the prior + * and the mutations. Operation order follows the numba code so that results agree + * bit for bit. + */ + +#include +#include +#include + +#include "mathutil.h" +#include "tsdate.h" + +/* Indexes into the factors, as in tsdate.variational */ +#define ROOTWARD 0 +#define LEAFWARD 1 +#define MIXPRIOR 0 +#define CONSTRNT 1 +#define LOWER 0 +#define UPPER 1 + +/* Entry `i` of an array of pairs, `j` of an array of 2x2 factors. */ +#define PAIR(array, i) ((array) + 2 * (tsd_size_t) (i)) +#define FACTOR(array, i, which) ((array) + 4 * (tsd_size_t) (i) + 2 * (which)) + +void +tsd_rescale_factors(const tsd_ep_factors_t *factors) +{ + const double *scale = factors->scale; + tsd_size_t j, k; + double *f; + + for (j = 0; j < factors->num_edges; j++) { + f = FACTOR(factors->edge, j, ROOTWARD); + for (k = 0; k < 2; k++) { + f[k] *= scale[factors->edges_parent[j]]; + } + f = FACTOR(factors->edge, j, LEAFWARD); + for (k = 0; k < 2; k++) { + f[k] *= scale[factors->edges_child[j]]; + } + } + for (j = 0; j < factors->num_blocks; j++) { + f = FACTOR(factors->block, j, ROOTWARD); + for (k = 0; k < 2; k++) { + f[k] *= scale[factors->blocks_left[j]]; + } + f = FACTOR(factors->block, j, LEAFWARD); + for (k = 0; k < 2; k++) { + f[k] *= scale[factors->blocks_right[j]]; + } + } + for (j = 0; j < factors->num_nodes; j++) { + f = FACTOR(factors->node, j, MIXPRIOR); + for (k = 0; k < 2; k++) { + f[k] *= scale[j]; + } + f = FACTOR(factors->node, j, CONSTRNT); + for (k = 0; k < 2; k++) { + f[k] *= scale[j]; + } + factors->scale[j] = 1.0; + } +} + +void +tsd_assemble_factors(const tsd_ep_factors_t *factors, double *posterior) +{ + tsd_size_t j, k; + double *post; + const double *f; + + for (j = 0; j < 2 * factors->num_nodes; j++) { + posterior[j] = 0.0; + } + for (j = 0; j < factors->num_edges; j++) { + post = PAIR(posterior, factors->edges_parent[j]); + f = FACTOR(factors->edge, j, ROOTWARD); + for (k = 0; k < 2; k++) { + post[k] += f[k]; + } + post = PAIR(posterior, factors->edges_child[j]); + f = FACTOR(factors->edge, j, LEAFWARD); + for (k = 0; k < 2; k++) { + post[k] += f[k]; + } + } + for (j = 0; j < factors->num_blocks; j++) { + post = PAIR(posterior, factors->blocks_left[j]); + f = FACTOR(factors->block, j, ROOTWARD); + for (k = 0; k < 2; k++) { + post[k] += f[k]; + } + post = PAIR(posterior, factors->blocks_right[j]); + f = FACTOR(factors->block, j, LEAFWARD); + for (k = 0; k < 2; k++) { + post[k] += f[k]; + } + } + for (j = 0; j < factors->num_nodes; j++) { + post = PAIR(posterior, j); + f = FACTOR(factors->node, j, MIXPRIOR); + for (k = 0; k < 2; k++) { + post[k] += f[k]; + } + } + for (j = 0; j < factors->num_nodes; j++) { + post = PAIR(posterior, j); + f = FACTOR(factors->node, j, CONSTRNT); + for (k = 0; k < 2; k++) { + post[k] += f[k]; + } + } +} + +/* + * If `x - y` is too small, find `d` so that `x - d * y` is large enough: + * + * x[0] - d * y[0] + 1 >= (x[0] + 1) * s + * x[1] - d * y[1] >= y[1] * s + * + * for `0 < s < 1`. + */ +int +tsd_damp(const double x[2], const double y[2], double s, double *out) +{ + int ret = 0; + double a, b, d; + + if (y[0] == 0.0 && y[1] == 0.0 && x[0] == 0.0 && x[1] == 0.0) { + *out = 1.0; + goto out; + } + if (!(0 < s && s < 1)) { + ret = tsd_trace_error(TSD_ERR_INVALID_MIN_STEP); + goto out; + } + if (!(0.0 < x[0] + 1 && 0.0 < x[1])) { + ret = tsd_trace_error(TSD_ERR_INVALID_NODE_POSTERIOR); + goto out; + } + a = 1.0; + if (!(1 + x[0] - y[0] > (1 + x[0]) * s)) { + if (y[0] == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + a = (1 - s) * (1 + x[0]) / y[0]; + } + b = 1.0; + if (!(x[1] - y[1] > x[1] * s)) { + if (y[1] == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + b = (1 - s) * x[1] / y[1]; + } + d = tsd_min(a, b); + if (!(0.0 < d && d <= 1.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_DAMPING); + goto out; + } + *out = d; +out: + return ret; +} + +/* Find `d` so that `d * x[0] + 1 <= s` or `d * x[0] + 1 >= 1 / s`. */ +int +tsd_rescale(const double x[2], double s, double *out) +{ + int ret = 0; + + if (x[0] == 0.0 && x[1] == 0.0) { + *out = 1.0; + goto out; + } + if (!(0 < x[0] + 1 && 0 < x[1])) { + ret = tsd_trace_error(TSD_ERR_INVALID_NODE_POSTERIOR); + goto out; + } + if (1 + x[0] > s) { + if (x[0] == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + *out = (s - 1) / x[0]; + } else if (1 + x[0] < 1 / s) { + /* x[0] is not zero: that would have taken the first branch (s < 1). */ + *out = (1 / s - 1) / x[0]; + } else { + *out = 1.0; + } +out: + return ret; +} + +/* + * Check that the upper bound on node age is greater than the maximum lower bound for + * ages of descendants. + */ +int +tsd_check_valid_constraints(tsd_size_t num_nodes, tsd_size_t num_edges, + const double *constraints, const tsd_id_t *edges_parent, const tsd_id_t *edges_child) +{ + int ret = 0; + double *lower_max = NULL; + tsd_size_t j; + tsd_id_t p, c; + + lower_max = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*lower_max)); + if (lower_max == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + for (j = 0; j < num_nodes; j++) { + lower_max[j] = constraints[2 * j + LOWER]; + } + for (j = 0; j < num_edges; j++) { + p = edges_parent[j]; + c = edges_child[j]; + lower_max[p] = tsd_max(lower_max[c], lower_max[p]); + } + for (j = 0; j < num_nodes; j++) { + if (lower_max[j] > constraints[2 * j + UPPER]) { + ret = tsd_trace_error(TSD_ERR_INCONSISTENT_CONSTRAINTS); + goto out; + } + } +out: + tsd_safe_free(lower_max); + return ret; +} + +/* cavity = posterior - delta * message */ +static void +get_cavity( + const double posterior[2], double delta, const double message[2], double cavity[2]) +{ + cavity[0] = posterior[0] - delta * message[0]; + cavity[1] = posterior[1] - delta * message[1]; +} + +/* The message from a factor, which is stored divided by the scale of the node. */ +static void +get_message(const double factor[2], double scale, double message[2]) +{ + message[0] = factor[0] * scale; + message[1] = factor[1] * scale; +} + +/* + * Update a factor given the cavity and the new posterior: + * factor = factor * (1 - delta) + (posterior - cavity) / scale + */ +static void +update_factor(double factor[2], double delta, const double posterior[2], + const double cavity[2], double scale) +{ + const double keep = 1.0 - delta; + + factor[0] *= keep; + factor[1] *= keep; + factor[0] += (posterior[0] - cavity[0]) / scale; + factor[1] += (posterior[1] - cavity[1]) / scale; +} + +/* Rescale the posterior of a node to keep its shape bounded, and its scale to match. */ +static int +rescale_posterior(double posterior[2], double *scale, double max_shape) +{ + int ret; + double eta; + + ret = tsd_rescale(posterior, max_shape, &eta); + if (ret != 0) { + goto out; + } + posterior[0] *= eta; + posterior[1] *= eta; + *scale *= eta; +out: + return ret; +} + +/* The arguments of the update of one edge (block), shared by all the edges of a pass. */ +typedef struct { + double max_shape; + double min_step; + int unphased; + const double *constraints; + const double *likelihoods; + double *posterior; + double *scale; + double *factor; /* the edge or block factors */ + double *lognorm; +} likelihood_pass_t; + +/* + * Update an edge with a fixed parent (`fixed_parent`) or a fixed child: only the + * free node, `free_node`, has a posterior to update. + */ +static int +update_fixed_edge(const likelihood_pass_t *pass, tsd_id_t i, tsd_id_t fixed_node, + tsd_id_t free_node, int fixed_parent) +{ + int ret = 0; + const int which = fixed_parent ? LEAFWARD : ROOTWARD; + double *post = PAIR(pass->posterior, free_node); + double *factor = FACTOR(pass->factor, i, which); + double *scale = pass->scale + free_node; + const double fixed_age = pass->constraints[2 * (tsd_size_t) fixed_node + LOWER]; + double message[2], cavity[2], edge_likelihood[2], proj[2]; + double delta, logl; + + get_message(factor, *scale, message); + ret = tsd_damp(post, message, pass->min_step, &delta); + if (ret != 0) { + goto out; + } + get_cavity(post, delta, message, cavity); + edge_likelihood[0] = delta * PAIR(pass->likelihoods, i)[0]; + edge_likelihood[1] = delta * PAIR(pass->likelihoods, i)[1]; + if (pass->unphased) { + ret = tsd_sideways_projection(fixed_age, cavity, edge_likelihood, &logl, proj); + } else if (fixed_parent) { + ret = tsd_leafward_projection(fixed_age, cavity, edge_likelihood, &logl, proj); + } else { + ret = tsd_rootward_projection(fixed_age, cavity, edge_likelihood, &logl, proj); + } + if (ret != 0) { + goto out; + } + pass->lognorm[i] = logl; + post[0] = proj[0]; + post[1] = proj[1]; + update_factor(factor, delta, post, cavity, *scale); + ret = rescale_posterior(post, scale, pass->max_shape); +out: + return ret; +} + +/* A block with a single node: the parent of the edge is its child. */ +static int +update_twin_edge(const likelihood_pass_t *pass, tsd_id_t i, tsd_id_t node) +{ + int ret = 0; + double *post = PAIR(pass->posterior, node); + double *factor = FACTOR(pass->factor, i, ROOTWARD); + double *scale = pass->scale + node; + double message[2], cavity[2], edge_likelihood[2], proj[2]; + double delta, logl; + + get_message(factor, *scale, message); + ret = tsd_damp(post, message, pass->min_step, &delta); + if (ret != 0) { + goto out; + } + get_cavity(post, delta, message, cavity); + edge_likelihood[0] = delta * PAIR(pass->likelihoods, i)[0]; + edge_likelihood[1] = delta * PAIR(pass->likelihoods, i)[1]; + if (!pass->unphased) { + ret = tsd_trace_error(TSD_ERR_TWIN_EDGE_IN_PHASED_PASS); + goto out; + } + ret = tsd_twin_projection(cavity, edge_likelihood, &logl, proj); + if (ret != 0) { + goto out; + } + pass->lognorm[i] = logl; + post[0] = proj[0]; + post[1] = proj[1]; + update_factor(factor, delta, post, cavity, *scale); + ret = rescale_posterior(post, scale, pass->max_shape); +out: + return ret; +} + +/* An edge with both nodes free, and a different parent and child. */ +static int +update_free_edge(const likelihood_pass_t *pass, tsd_id_t i, tsd_id_t p, tsd_id_t c) +{ + int ret = 0; + double *post_p = PAIR(pass->posterior, p); + double *post_c = PAIR(pass->posterior, c); + double *factor_p = FACTOR(pass->factor, i, ROOTWARD); + double *factor_c = FACTOR(pass->factor, i, LEAFWARD); + double *scale_p = pass->scale + p; + double *scale_c = pass->scale + c; + double message_p[2], message_c[2], cavity_p[2], cavity_c[2], edge_likelihood[2]; + double proj_p[2], proj_c[2]; + double delta_p, delta_c, delta, logl; + + get_message(factor_p, *scale_p, message_p); + get_message(factor_c, *scale_c, message_c); + ret = tsd_damp(post_p, message_p, pass->min_step, &delta_p); + if (ret != 0) { + goto out; + } + ret = tsd_damp(post_c, message_c, pass->min_step, &delta_c); + if (ret != 0) { + goto out; + } + delta = tsd_min(delta_p, delta_c); + get_cavity(post_p, delta, message_p, cavity_p); + get_cavity(post_c, delta, message_c, cavity_c); + edge_likelihood[0] = delta * PAIR(pass->likelihoods, i)[0]; + edge_likelihood[1] = delta * PAIR(pass->likelihoods, i)[1]; + if (pass->unphased) { + ret = tsd_unphased_projection( + cavity_p, cavity_c, edge_likelihood, &logl, proj_p, proj_c); + } else { + ret = tsd_gamma_projection( + cavity_p, cavity_c, edge_likelihood, &logl, proj_p, proj_c); + } + if (ret != 0) { + goto out; + } + pass->lognorm[i] = logl; + post_p[0] = proj_p[0]; + post_p[1] = proj_p[1]; + post_c[0] = proj_c[0]; + post_c[1] = proj_c[1]; + update_factor(factor_p, delta, post_p, cavity_p, *scale_p); + update_factor(factor_c, delta, post_c, cavity_c, *scale_c); + ret = rescale_posterior(post_p, scale_p, pass->max_shape); + if (ret != 0) { + goto out; + } + ret = rescale_posterior(post_c, scale_c, pass->max_shape); +out: + return ret; +} + +int +tsd_propagate_likelihood(tsd_size_t num_order, const tsd_id_t *edge_order, + tsd_size_t num_edges, const tsd_id_t *edges_parent, const tsd_id_t *edges_child, + const double *likelihoods, const double *constraints, double max_shape, + double min_step, int unphased, double *posterior, const tsd_ep_factors_t *factors, + double *lognorm) +{ + int ret = 0; + const double tiny = sqrt(DBL_MIN); + likelihood_pass_t pass; + tsd_size_t j; + tsd_id_t i, p, c; + int fixed_p, fixed_c; + + if (!(max_shape >= 1.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_MAX_SHAPE); + goto out; + } + if (!(0.0 < min_step && min_step < 1.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_MIN_STEP); + goto out; + } + pass.max_shape = max_shape; + pass.min_step = min_step; + pass.unphased = unphased; + pass.constraints = constraints; + pass.likelihoods = likelihoods; + pass.posterior = posterior; + pass.scale = factors->scale; + pass.factor = unphased ? factors->block : factors->edge; + pass.lognorm = lognorm; + tsd_bug_assert(num_edges == (unphased ? factors->num_blocks : factors->num_edges)); + + for (j = 0; j < num_order; j++) { + i = edge_order[j]; + p = edges_parent[i]; + c = edges_child[i]; + if (pass.scale[p] < tiny || pass.scale[c] < tiny) { + tsd_rescale_factors(factors); + } + fixed_p = constraints[2 * (tsd_size_t) p + LOWER] + == constraints[2 * (tsd_size_t) p + UPPER]; + fixed_c = constraints[2 * (tsd_size_t) c + LOWER] + == constraints[2 * (tsd_size_t) c + UPPER]; + if (fixed_p && fixed_c) { + continue; + } else if (fixed_p) { + /* a sample is the ancestor of another sample */ + ret = update_fixed_edge(&pass, i, p, c, 1); + } else if (fixed_c) { + /* a sample has age greater than zero */ + ret = update_fixed_edge(&pass, i, c, p, 0); + } else if (p == c) { + /* singleton block with single parent */ + ret = update_twin_edge(&pass, i, p); + } else { + ret = update_free_edge(&pass, i, p, c); + } + if (ret != 0) { + goto out; + } + } +out: + return ret; +} + +/* The prior cavity of a free node: the posterior without the mixture prior factor. */ +static void +get_prior_cavity(const tsd_ep_factors_t *factors, const double *posterior, tsd_size_t j, + double cavity[2]) +{ + double message[2]; + + get_message(FACTOR(factors->node, j, MIXPRIOR), factors->scale[j], message); + get_cavity(PAIR(posterior, j), 1.0, message, cavity); +} + +/* + * The mean over free nodes of shape / rate, with `penalty` added to the rate if + * `with_penalty`, summing sequentially. + */ +static double +mean_shape_over_rate(const tsd_ep_factors_t *factors, const double *posterior, + const uint8_t *free, int with_penalty, double penalty) +{ + double cavity[2]; + double shape, rate, term; + double total = 0.0; + tsd_size_t j, count = 0; + + for (j = 0; j < factors->num_nodes; j++) { + if (free[j]) { + get_prior_cavity(factors, posterior, j, cavity); + shape = cavity[0] + 1; + rate = cavity[1]; + if (with_penalty) { + rate = rate + penalty; + } + term = shape / rate; + total += term; + count++; + } + } + return total / (double) count; +} + +int +tsd_propagate_prior(const uint8_t *free, double max_shape, int64_t em_maxitt, + double em_reltol, double *posterior, const tsd_ep_factors_t *factors) +{ + int ret = 0; + const tsd_size_t num_nodes = factors->num_nodes; + double cavity[2]; + double penalty, delta; + int64_t itt; + tsd_size_t j; + int any_free = 0; + + if (!(max_shape >= 1.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_MAX_SHAPE); + goto out; + } + for (j = 0; j < num_nodes; j++) { + any_free = any_free || free[j]; + } + if (!any_free) { + goto out; + } + + /* fit an exponential to cavity distributions for unconstrained nodes */ + penalty = 1 / mean_shape_over_rate(factors, posterior, free, 0, 0.0); + itt = 0; + delta = INFINITY; + while (fabs(delta) > fabs(penalty) * em_reltol) { + if (itt > em_maxitt) { + break; + } + delta = 1 / mean_shape_over_rate(factors, posterior, free, 1, penalty) - penalty; + penalty += delta; + itt++; + } + if (!(penalty > 0)) { + ret = tsd_trace_error(TSD_ERR_NONPOSITIVE_PENALTY); + goto out; + } + + /* update posteriors and rescale to keep shape bounded */ + for (j = 0; j < num_nodes; j++) { + if (free[j]) { + get_prior_cavity(factors, posterior, j, cavity); + PAIR(posterior, j)[1] = cavity[1] + penalty; + FACTOR(factors->node, j, MIXPRIOR) + [0] = (PAIR(posterior, j)[0] - cavity[0]) / factors->scale[j]; + FACTOR(factors->node, j, MIXPRIOR) + [1] = (PAIR(posterior, j)[1] - cavity[1]) / factors->scale[j]; + } + } + for (j = 0; j < num_nodes; j++) { + if (free[j]) { + ret = rescale_posterior(PAIR(posterior, j), factors->scale + j, max_shape); + if (ret != 0) { + goto out; + } + } + } +out: + return ret; +} + +/* The arguments of the projection of mutations; nothing is updated. */ +typedef struct { + int unphased; + const double *constraints; + const double *likelihoods; + const double *posterior; + const double *scale; + const double *factor; /* the edge or block factors */ +} mutation_pass_t; + +/* + * The posterior of one mutation, from the edge (block) above it: with both nodes + * fixed, the age of each; with one fixed, the fixed age and the cavity of the other; + * otherwise the cavities of both. The messages are not damped (the step is one). + */ +static int +project_mutation(const mutation_pass_t *pass, tsd_id_t i, tsd_id_t p, tsd_id_t c, + double *phase, double proj[2]) +{ + int ret = 0; + const double *constraints = pass->constraints; + const int fixed_p = constraints[2 * (tsd_size_t) p + LOWER] + == constraints[2 * (tsd_size_t) p + UPPER]; + const int fixed_c = constraints[2 * (tsd_size_t) c + LOWER] + == constraints[2 * (tsd_size_t) c + UPPER]; + const double age_p = constraints[2 * (tsd_size_t) p + LOWER]; + const double age_c = constraints[2 * (tsd_size_t) c + LOWER]; + const double *post_p = PAIR(pass->posterior, p); + const double *post_c = PAIR(pass->posterior, c); + const double *likelihood = PAIR(pass->likelihoods, i); + double message_p[2], message_c[2], cavity_p[2], cavity_c[2]; + + get_message(FACTOR(pass->factor, i, ROOTWARD), pass->scale[p], message_p); + get_message(FACTOR(pass->factor, i, LEAFWARD), pass->scale[c], message_c); + get_cavity(post_p, 1.0, message_p, cavity_p); + get_cavity(post_c, 1.0, message_c, cavity_c); + if (fixed_p && fixed_c) { + if (pass->unphased) { + ret = tsd_mutation_block_projection(age_p, age_c, phase, proj); + } else { + ret = tsd_mutation_edge_projection(age_p, age_c, phase, proj); + } + } else if (fixed_p) { + if (pass->unphased) { + ret = tsd_mutation_sideways_projection( + age_p, cavity_c, likelihood, phase, proj); + } else { + ret = tsd_mutation_leafward_projection( + age_p, cavity_c, likelihood, phase, proj); + } + } else if (fixed_c) { + if (pass->unphased) { + ret = tsd_mutation_sideways_projection( + age_c, cavity_p, likelihood, phase, proj); + } else { + ret = tsd_mutation_rootward_projection( + age_c, cavity_p, likelihood, phase, proj); + } + } else if (p == c) { + /* singleton block with single parent */ + ret = tsd_mutation_twin_projection(cavity_p, likelihood, phase, proj); + } else if (pass->unphased) { + ret = tsd_mutation_unphased_projection( + cavity_p, cavity_c, likelihood, phase, proj); + } else { + ret = tsd_mutation_gamma_projection(cavity_p, cavity_c, likelihood, phase, proj); + } + return ret; +} + +int +tsd_propagate_mutations(tsd_size_t num_order, const tsd_id_t *mutations_order, + const tsd_id_t *mutations_edge, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, const double *likelihoods, const double *constraints, + const double *posterior, const tsd_ep_factors_t *factors, int unphased, + double *mutations_posterior, double *mutations_phase) +{ + int ret = 0; + mutation_pass_t pass; + tsd_size_t j; + tsd_id_t m, i; + double phase, proj[2]; + + pass.unphased = unphased; + pass.constraints = constraints; + pass.likelihoods = likelihoods; + pass.posterior = posterior; + pass.scale = factors->scale; + pass.factor = unphased ? factors->block : factors->edge; + for (j = 0; j < num_order; j++) { + m = mutations_order[j]; + i = mutations_edge[m]; + if (i == TSD_NULL) { /* skip mutations above root */ + continue; + } + ret = project_mutation(&pass, i, edges_parent[i], edges_child[i], &phase, proj); + if (ret != 0) { + goto out; + } + mutations_phase[m] = phase; + mutations_posterior[2 * (tsd_size_t) m] = proj[0]; + mutations_posterior[2 * (tsd_size_t) m + 1] = proj[1]; + } +out: + return ret; +} diff --git a/setup.py b/setup.py index 203868ab..57fed3f8 100644 --- a/setup.py +++ b/setup.py @@ -17,6 +17,7 @@ "phasing.c", "util.c", "prior.c", + "variational.c", ] sources = ["_tsdatemodule.c"] + [os.path.join(libdir, f) for f in tsd_source_files] diff --git a/tests/oracle/implementations.py b/tests/oracle/implementations.py index 718bb288..66f7b530 100644 --- a/tests/oracle/implementations.py +++ b/tests/oracle/implementations.py @@ -26,6 +26,8 @@ import tsdate.variational from tsdate.discrete import LogLikelihoods +from . import variational as oracle_variational + _EP = tsdate.variational.ExpectationPropagation # Functions that are staticmethods of ExpectationPropagation, exposed as plain names. @@ -212,13 +214,123 @@ def _c_rescaling(_tsdate): ) +def _factor_arrays(factors): + """The fields of an ``EPFactors`` that the module takes, as a tuple of arrays.""" + return ( + factors.node, + factors.edge, + factors.block, + factors.scale, + factors._p, + factors._c, + factors._j, + factors._k, + ) + + +def _c_variational(_tsdate): + """ + The EP state stays in the numpy arrays of an ``EPFactors`` (the oracle's plain + class), which the module updates in place; the adapters unpack the object. + """ + + def check_size_two(*arrays): + if any(a.size != 2 for a in arrays): + raise ValueError("Natural parameters must have two entries") + + def damp(x, y, s): + check_size_two(x, y) + return _tsdate.damp(x[0], x[1], y[0], y[1], s) + + def rescale(x, s): + check_size_two(x) + return _tsdate.rescale(x[0], x[1], s) + + def rescale_factors(factors): + _tsdate.rescale_factors(_factor_arrays(factors)) + + def assemble_factors(factors): + return _tsdate.assemble_factors(_factor_arrays(factors)) + + def propagate_likelihood( + edge_order, + edges_parent, + edges_child, + likelihoods, + constraints, + posterior, + factors, + lognorm, + max_shape, + min_step, + unphased, + ): + _tsdate.propagate_likelihood( + edge_order, + edges_parent, + edges_child, + likelihoods, + constraints, + posterior, + _factor_arrays(factors), + lognorm, + max_shape, + min_step, + unphased, + ) + + def propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol): + _tsdate.propagate_prior( + free, posterior, _factor_arrays(factors), max_shape, em_maxitt, em_reltol + ) + + def propagate_mutations( + mutations_order, + mutations_posterior, + mutations_phase, + mutations_edge, + edges_parent, + edges_child, + likelihoods, + constraints, + posterior, + factors, + unphased, + ): + _tsdate.propagate_mutations( + mutations_order, + mutations_posterior, + mutations_phase, + mutations_edge, + edges_parent, + edges_child, + likelihoods, + constraints, + posterior, + _factor_arrays(factors), + unphased, + ) + + return _PortedNamespace( + EPFactors=oracle_variational.EPFactors, + _rescale_factors=rescale_factors, + _assemble_factors=assemble_factors, + _damp=damp, + _rescale=rescale, + _check_valid_constraints=_tsdate.check_valid_constraints, + propagate_likelihood=propagate_likelihood, + propagate_prior=propagate_prior, + propagate_mutations=propagate_mutations, + ) + + def _c_namespace(): import _tsdate return types.SimpleNamespace( hypergeo=_c_hypergeo(_tsdate), approx=_c_approx(_tsdate), - variational=_PortedNamespace(), + variational=_c_variational(_tsdate), rescaling=_c_rescaling(_tsdate), phasing=_c_phasing(_tsdate), util=_c_util(_tsdate), diff --git a/tests/test_python_c_variational.py b/tests/test_python_c_variational.py new file mode 100644 index 00000000..b3a7492f --- /dev/null +++ b/tests/test_python_c_variational.py @@ -0,0 +1,334 @@ +""" +Tests of the expectation propagation functions of the low-level _tsdate module that +the oracle tests in test_oracle_variational.py do not reach: argument handling, and +the messages of library errors. +""" + +import _tsdate +import numpy as np +import pytest + +INF = np.inf + + +def factors(num_nodes=3, num_edges=2, num_blocks=1): + """The tuple of arrays that describes EP factors, for a small example.""" + return ( + np.zeros((num_nodes, 2, 2)), + np.zeros((num_edges, 2, 2)), + np.zeros((num_blocks, 2, 2)), + np.ones(num_nodes), + np.array([2, 2][:num_edges], dtype=np.int32), + np.array([0, 1][:num_edges], dtype=np.int32), + np.full(num_blocks, 2, dtype=np.int32), + np.full(num_blocks, 1, dtype=np.int32), + ) + + +def likelihood_args(**changes): + """Arguments of propagate_likelihood on two edges (2, 0) and (2, 1).""" + args = dict( + edge_order=np.array([0, 1], dtype=np.int32), + edges_parent=np.array([2, 2], dtype=np.int32), + edges_child=np.array([0, 1], dtype=np.int32), + likelihoods=np.array([[1.0, 0.1], [1.0, 0.1]]), + constraints=np.array([[0.0, 0.0], [0.0, INF], [0.0, INF]]), + posterior=np.ones((3, 2)), + factors=factors(), + lognorm=np.zeros(2), + max_shape=1000.0, + min_step=0.1, + unphased=False, + ) + args.update(changes) + return list(args.values()) + + +def prior_args(**changes): + args = dict( + free=np.array([False, True, True]), + posterior=np.full((3, 2), 2.0), + factors=factors(), + max_shape=1000.0, + em_maxitt=10, + em_reltol=1e-8, + ) + args.update(changes) + return list(args.values()) + + +def mutation_args(**changes): + args = dict( + mutations_order=np.array([0, 1], dtype=np.int32), + mutations_posterior=np.zeros((2, 2)), + mutations_phase=np.zeros(2), + mutations_edge=np.array([0, 1], dtype=np.int32), + edges_parent=np.array([2, 2], dtype=np.int32), + edges_child=np.array([0, 1], dtype=np.int32), + likelihoods=np.array([[1.0, 0.1], [1.0, 0.1]]), + constraints=np.array([[1.0, 1.0], [0.0, INF], [0.0, INF]]), + posterior=np.ones((3, 2)), + factors=factors(), + unphased=False, + ) + args.update(changes) + return list(args.values()) + + +class TestFactors: + def test_not_a_tuple(self): + with pytest.raises(TypeError, match="tuple of eight"): + _tsdate.rescale_factors(list(factors())) + with pytest.raises(TypeError, match="tuple of eight"): + _tsdate.assemble_factors(factors()[:7]) + + def test_wrong_dtype(self): + f = list(factors()) + f[4] = f[4].astype(np.int64) + with pytest.raises(TypeError): + _tsdate.rescale_factors(tuple(f)) + + def test_wrong_shape(self): + f = list(factors()) + f[1] = np.zeros((2, 2, 3)) + with pytest.raises(ValueError, match="shape"): + _tsdate.rescale_factors(tuple(f)) + + def test_inconsistent_sizes(self): + f = list(factors()) + f[3] = np.ones(4) + with pytest.raises(ValueError, match="inconsistent"): + _tsdate.assemble_factors(tuple(f)) + + def test_readonly_arrays(self): + f = list(factors()) + f[0].flags.writeable = False + with pytest.raises(ValueError): + _tsdate.rescale_factors(tuple(f)) + # nothing is written by the assembly + assert _tsdate.assemble_factors(tuple(f)).shape == (3, 2) + + def test_rescale_in_place(self): + f = factors() + f[3][:] = [2.0, 3.0, 4.0] + f[0][:] = 1.0 + _tsdate.rescale_factors(f) + assert np.all(f[3] == 1.0) + assert np.array_equal(f[0][:, 0, 0], [2.0, 3.0, 4.0]) + + +class TestCheckValidConstraints: + def test_columns(self): + with pytest.raises(ValueError, match="two columns"): + _tsdate.check_valid_constraints( + np.zeros((3, 3)), np.zeros(0, np.int32), np.zeros(0, np.int32) + ) + + def test_edge_sizes(self): + with pytest.raises(ValueError, match="same size"): + _tsdate.check_valid_constraints( + np.zeros((3, 2)), np.zeros(2, np.int32), np.zeros(1, np.int32) + ) + + +class TestPropagateLikelihood: + def test_runs(self): + args = likelihood_args() + assert _tsdate.propagate_likelihood(*args) is None + assert np.all(np.isfinite(args[7])) + + @pytest.mark.parametrize( + ("change", "message"), + [ + ("edges_child", "same size"), + ("likelihoods", "shape"), + ("constraints", "shape"), + ("posterior", "same shape"), + ("lognorm", "one entry per edge"), + ], + ) + def test_shape_errors(self, change, message): + value = dict( + edges_child=np.zeros(1, np.int32), + likelihoods=np.zeros((1, 2)), + constraints=np.zeros((2, 2)), + posterior=np.ones((2, 2)), + lognorm=np.zeros(3), + )[change] + with pytest.raises(ValueError, match=message): + _tsdate.propagate_likelihood(*likelihood_args(**{change: value})) + + def test_factors_do_not_match_kind(self): + # the unphased pass uses the blocks, of which there is one + with pytest.raises(ValueError, match="one entry per edge"): + _tsdate.propagate_likelihood(*likelihood_args(unphased=True)) + + def test_library_errors(self): + with pytest.raises(_tsdate.LibraryError, match="at least one"): + _tsdate.propagate_likelihood(*likelihood_args(max_shape=0.5)) + with pytest.raises(_tsdate.LibraryError, match="greater than zero and less"): + _tsdate.propagate_likelihood(*likelihood_args(min_step=1.0)) + with pytest.raises(_tsdate.LibraryError, match="not greater than -1"): + _tsdate.propagate_likelihood( + *likelihood_args(posterior=np.full((3, 2), -5.0)) + ) + + @pytest.mark.parametrize("kind", ["float32", "strided"]) + def test_array_updated_in_place_must_not_be_converted(self, kind): + # a copy would silently lose the update + if kind == "float32": + posterior = np.ones((3, 2), dtype=np.float32) + else: + posterior = np.ones((3, 4))[:, ::2] + with pytest.raises(ValueError, match="writeable, C-contiguous"): + _tsdate.propagate_likelihood(*likelihood_args(posterior=posterior)) + + @pytest.mark.parametrize("improper", [0, 1, 2]) + def test_improper_posterior_of_free_edge(self, improper): + # the posterior of either node of an edge (or of a twin block) is not proper + posterior = np.full((3, 2), 2.0) + posterior[improper] = -5.0 + args = likelihood_args( + constraints=np.array([[0.0, INF]] * 3), + posterior=posterior, + edges_parent=np.array([0, 2], dtype=np.int32), + edges_child=np.array([1, 2], dtype=np.int32), + ) + with pytest.raises(_tsdate.LibraryError, match="not greater than -1"): + _tsdate.propagate_likelihood(*args) + + def test_improper_posterior_of_twin_block(self): + args = likelihood_args( + constraints=np.array([[0.0, INF]] * 3), + posterior=np.array([[2.0, 2.0], [2.0, 2.0], [-5.0, 2.0]]), + edges_parent=np.array([2, 2], dtype=np.int32), + edges_child=np.array([2, 2], dtype=np.int32), + factors=factors(num_blocks=2), + unphased=True, + ) + with pytest.raises(_tsdate.LibraryError, match="not greater than -1"): + _tsdate.propagate_likelihood(*args) + + def test_twin_projection_fails(self): + # a zero cavity (the damping step is one for zeros) and no mutation target + args = likelihood_args( + constraints=np.array([[0.0, INF]] * 3), + posterior=np.zeros((3, 2)), + edges_parent=np.array([2, 2], dtype=np.int32), + edges_child=np.array([2, 2], dtype=np.int32), + likelihoods=np.array([[1.0, 0.0], [1.0, 0.0]]), + factors=factors(num_blocks=2), + unphased=True, + ) + with pytest.raises(_tsdate.LibraryError, match="division by zero"): + _tsdate.propagate_likelihood(*args) + + def test_wrong_dtype(self): + with pytest.raises(TypeError): + _tsdate.propagate_likelihood( + *likelihood_args(edge_order=np.array([0, 1], dtype=np.int64)) + ) + + +class TestPropagatePrior: + def test_runs(self): + args = prior_args() + assert _tsdate.propagate_prior(*args) is None + assert np.all(args[1][1:, 1] > 2.0) + + def test_sizes(self): + with pytest.raises(ValueError, match="one entry per node"): + _tsdate.propagate_prior(*prior_args(free=np.ones(2, dtype=bool))) + with pytest.raises(ValueError, match="one entry per node"): + _tsdate.propagate_prior(*prior_args(posterior=np.ones((2, 2)))) + + def test_library_errors(self): + with pytest.raises(_tsdate.LibraryError, match="at least one"): + _tsdate.propagate_prior(*prior_args(max_shape=0.0)) + with pytest.raises(_tsdate.LibraryError, match="penalty is not positive"): + _tsdate.propagate_prior(*prior_args(posterior=np.zeros((3, 2)))) + + def test_improper_posterior_cannot_be_rescaled(self): + # the fit succeeds (the other node has a large shape) but one posterior is + # not proper, so that it cannot be rescaled + posterior = np.array([[2.0, 2.0], [-5.0, 1.0], [99.0, 1.0]]) + with pytest.raises(_tsdate.LibraryError, match="not greater than -1"): + _tsdate.propagate_prior(*prior_args(posterior=posterior)) + + +class TestPropagateMutations: + def test_runs(self): + args = mutation_args() + assert _tsdate.propagate_mutations(*args) is None + assert np.all(np.isfinite(args[2])) + + @pytest.mark.parametrize( + ("change", "message"), + [ + ("mutations_edge", "same size"), + ("mutations_posterior", "shape"), + ("edges_child", "same size"), + ("likelihoods", "shape"), + ("constraints", "shape"), + ("posterior", "same shape"), + ], + ) + def test_shape_errors(self, change, message): + value = dict( + mutations_edge=np.zeros(1, np.int32), + mutations_posterior=np.zeros((3, 2)), + edges_child=np.zeros(1, np.int32), + likelihoods=np.zeros((1, 2)), + constraints=np.zeros((2, 2)), + posterior=np.ones((2, 2)), + )[change] + with pytest.raises(ValueError, match=message): + _tsdate.propagate_mutations(*mutation_args(**{change: value})) + + def test_factors_do_not_match_kind(self): + with pytest.raises(ValueError, match="one entry per edge"): + _tsdate.propagate_mutations(*mutation_args(unphased=True)) + + +class TestArgumentParsing: + @pytest.mark.parametrize( + "name", + [ + "rescale_factors", + "assemble_factors", + "check_valid_constraints", + "propagate_likelihood", + "propagate_prior", + "propagate_mutations", + ], + ) + def test_wrong_number_of_arguments(self, name): + with pytest.raises(TypeError): + getattr(_tsdate, name)() + + def test_check_valid_constraints_wrong_dtype(self): + with pytest.raises(TypeError): + _tsdate.check_valid_constraints( + np.zeros((3, 2)), np.zeros(0, np.int64), np.zeros(0, np.int32) + ) + + def test_bad_factors(self): + bad = list(factors()) + for func, args in [ + (_tsdate.propagate_likelihood, likelihood_args(factors=bad)), + (_tsdate.propagate_prior, prior_args(factors=bad)), + (_tsdate.propagate_mutations, mutation_args(factors=bad)), + ]: + with pytest.raises(TypeError, match="tuple of eight"): + func(*args) + + def test_wrong_dtypes(self): + for func, args in [ + (_tsdate.propagate_prior, prior_args(free=np.ones(3))), + ( + _tsdate.propagate_mutations, + mutation_args(mutations_order=np.zeros(1, np.int64)), + ), + ]: + with pytest.raises(TypeError): + func(*args) From 28d78fa044812e560824893005feeb963daf7422 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Tue, 24 Nov 2026 21:26:50 -0800 Subject: [PATCH 11/56] Switch tsdate to the C extension Production code now calls _tsdate instead of numba. - hypergeo, approx: removed. Nothing in tsdate calls them any more (the C passes call the special functions and gamma approximations directly), and they were not documented. Their tests (test_hypergeo.py, test_approximations.py) and evaluation/numerical_accuracy.py call the _tsdate functions instead, with imports and names updated (e.g. hypergeo._digamma -> _tsdate.digamma) and a failed KL minimisation expected as _tsdate.LibraryError with the same message. The oracles define their own KLMinimizationFailedError. - phasing, util, prior, rescaling: the jitted functions are the _tsdate functions; the piecewise rescaling functions check for increasing breakpoints in Python first, so the user-facing ValueError is kept. - variational: EPFactors is a plain class of numpy arrays; the EP passes call _tsdate with factors.arrays(). The ValueError for inconsistent node age constraints is kept. - discrete: the jitted logsumexp is scipy.special.logsumexp, and the row sums use np.logaddexp.reduceat (calling scipy per row made inside_outside ~44x slower). - reallocate_unphased now refuses arrays that would have to be copied (as the variational wrappers do), with a test; the other in-place wrappers already used the same helper. - The "numba" implementation is removed from the oracle test registry and from evaluation/microbench.py (default --impl c, no compile-time reporting); the discrete oracle and its test are removed. logsumexp, numba vs scipy.special.logsumexp: 1.3M calls from test_functions, test_inference and test_cli (inside_outside): max abs 5.7e-14, no -inf or NaN mismatches; 20000 random rows incl. -inf entries and all -inf rows: max abs 5.7e-14, max rel 1.0e-13 (|value| > 1e-6). End to end tsdate.date, numba tree (3f3afdd) vs this tree, median of 3 runs excluding import/compile (numba: import 39 s, first-call warm-up 1.1 s; C: import 0.75 s, warm-up 3.3 s): small 25 dip x 1 Mb gamma: node times identical; 0.368 s -> 0.239 s medium 500 dip x 10 Mb: node times identical; 7.05 s -> 4.35 s singletons_phased=False: node times identical; 2.66 s -> 1.68 s inside_outside: max abs 3.6e-11, max rel 2.6e-15; 1.94 s -> 2.06 s --- CHANGELOG.md | 3 + _tsdatemodule.c | 41 +- evaluation/README.md | 23 +- evaluation/microbench.py | 140 +--- evaluation/numerical_accuracy.py | 70 +- tests/oracle/approx.py | 12 +- tests/oracle/discrete.py | 17 - tests/oracle/hypergeo.py | 2 +- tests/oracle/implementations.py | 68 +- tests/test_approximations.py | 59 +- tests/test_hypergeo.py | 21 +- tests/test_oracle_approx.py | 15 +- tests/test_oracle_discrete.py | 67 -- tests/test_oracle_hypergeo.py | 6 +- tests/test_oracle_rescaling.py | 4 +- tests/test_python_c_tables.py | 13 + tsdate/approx.py | 1037 ------------------------------ tsdate/core.py | 1 - tsdate/discrete.py | 46 +- tsdate/hypergeo.py | 347 ---------- tsdate/phasing.py | 223 +------ tsdate/prior.py | 52 +- tsdate/rescaling.py | 491 +------------- tsdate/util.py | 226 +------ tsdate/variational.py | 498 +------------- 25 files changed, 230 insertions(+), 3252 deletions(-) delete mode 100644 tests/oracle/discrete.py delete mode 100644 tests/test_oracle_discrete.py delete mode 100644 tsdate/approx.py delete mode 100644 tsdate/hypergeo.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b58d4b0..e8a3017c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ In development diagnostics are superseded by the scripts in `evaluation/`, the AFS diagnostics moved to `evaluation/afs.py`, and the polytomy test helpers to `tests/`. +- Removed the internal `tsdate.approx` and `tsdate.hypergeo` modules; the special + functions and gamma approximations are now part of the `_tsdate` C extension. + **Bugfixes** - Removed an assertion in `split_disjoint_nodes` that is not guarenteed diff --git a/_tsdatemodule.c b/_tsdatemodule.c index b6e7c741..f30ff578 100644 --- a/_tsdatemodule.c +++ b/_tsdatemodule.c @@ -793,6 +793,25 @@ tsdate_block_singletons(PyObject *Py_UNUSED(self), PyObject *args) return ret; } +/* + * A float64 array of the given dimension that the call updates in place: `obj` itself, + * which must not need converting (a copy would silently lose the updates). + */ +static PyArrayObject * +get_inout_array(PyObject *obj, int ndim) +{ + PyArrayObject *ret = (PyArrayObject *) PyArray_FROMANY( + obj, NPY_FLOAT64, ndim, ndim, NPY_ARRAY_INOUT_ARRAY); + + if (ret != NULL && (PyObject *) ret != obj) { + Py_DECREF(ret); + ret = NULL; + PyErr_SetString(PyExc_ValueError, + "Arrays that are updated must be writeable, C-contiguous float64 arrays"); + } + return ret; +} + /* * reallocate_unphased(edges_likelihood, mutations_phase, mutations_block, * blocks_edges): updates edges_likelihood in place. @@ -815,8 +834,7 @@ tsdate_reallocate_unphased(PyObject *Py_UNUSED(self), PyObject *args) args, "OOOO", &likelihood_obj, &phase_obj, &block_obj, &edges_obj)) { goto out; } - likelihood_array = (PyArrayObject *) PyArray_FROMANY( - likelihood_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_INOUT_ARRAY); + likelihood_array = get_inout_array(likelihood_obj, 2); phase_array = (PyArrayObject *) PyArray_FROMANY( phase_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); block_array = (PyArrayObject *) PyArray_FROMANY( @@ -1775,25 +1793,6 @@ release_factors(py_factors_t *factors) release_arrays(factors->arrays, NUM_FACTOR_ARRAYS); } -/* - * A float64 array of the given dimension that the call updates in place: `obj` itself, - * which must not need converting (a copy would silently lose the updates). - */ -static PyArrayObject * -get_inout_array(PyObject *obj, int ndim) -{ - PyArrayObject *ret = (PyArrayObject *) PyArray_FROMANY( - obj, NPY_FLOAT64, ndim, ndim, NPY_ARRAY_INOUT_ARRAY); - - if (ret != NULL && (PyObject *) ret != obj) { - Py_DECREF(ret); - ret = NULL; - PyErr_SetString(PyExc_ValueError, - "Arrays that are updated must be writeable, C-contiguous float64 arrays"); - } - return ret; -} - /* * Parse a tuple of factors, writing the sizes and pointers to `factors->c`. The arrays * that the caller needs to update must be (and are required to be) writeable, aligned diff --git a/evaluation/README.md b/evaluation/README.md index 6d533c13..e9b02918 100644 --- a/evaluation/README.md +++ b/evaluation/README.md @@ -16,7 +16,7 @@ standard coalescent. | `afs.py` | Compare the observed site allele frequency spectrum with the expected one from branch lengths (branch AFS x mutation rate) in genomic windows, for the true times, the true topology dated by tsdate, and a tsinfer topology dated by tsdate. Writes `afs_*.csv`. | | `performance.py` | Wall time and peak RSS, each case in a fresh process. | | `microbench.py` | Microbenchmarks of the array-level accelerated functions (EP passes, rescaling, phasing, `util`, `prior`), on simulated inputs at three sizes (see below). | -| `numerical_accuracy.py` | Accuracy of the special functions and gamma approximations (`tsdate.hypergeo`, `tsdate.approx`) per function and regime: worst error against mpmath, SciPy or closed forms, and violations of properties such as symmetry, monotonicity and continuity at switch points (see below). Not to be confused with `accuracy.py`, which scores dating. | +| `numerical_accuracy.py` | Accuracy of the special functions and gamma approximations (the scalar functions of `_tsdate`) per function and regime: worst error against mpmath, SciPy or closed forms, and violations of properties such as symmetry, monotonicity and continuity at switch points (see below). Not to be confused with `accuracy.py`, which scores dating. | | `ep_sensitivity.py` | How a one-ulp change in the edge mutational targets grows over EP sweeps (maximum relative change in node means), which sets the tolerance of the multi-sweep test in `tests/test_oracle_variational.py` (see below). | | `compare.py` | Compares two `performance.py` CSVs case by case (see below). | | `plot.py` | Reads `results/*.csv` and writes PNGs: error/bias/interval coverage vs parameter (`accuracy_*_summary.png`: top row node times, bottom row mutation times), estimated-vs-true scatter (`accuracy_*_scatter.png`: columns are swept values, rows are node/mutation times for true/tsinferred topology), PIT calibration histograms (`accuracy_*_calibration.png`: node row, mutation row), AFS observed-vs-expected (`afs_*.png`), time and memory scaling. | @@ -77,9 +77,9 @@ Add `--quick` to `accuracy.py` / `performance.py` for a fast smoke test. Quick r to separate `*_quick.csv` files (so they never overwrite full results), and `plot.py` labels their figures "quick run" and names them `*_quick*.png`. -### Microbenchmarks of the accelerated functions +### Microbenchmarks of the C extension -`microbench.py` times each array-level numba-jitted entry point on inputs built from +`microbench.py` times each array-level entry point of the `_tsdate` extension on inputs built from simulated tree sequences (small/medium/large; the large case has ~560k edges, so the EP edge pass takes about a second). The EP state is produced by running `ExpectationPropagation.infer` for two iterations, and the functions are called as @@ -96,14 +96,11 @@ python evaluation/microbench.py --sizes medium --only propagate mutational Each function is warmed up, then the median of `--repeats` timed calls is reported (fast calls are batched so each timed block lasts a few ms; times are per call). -Compile time is reported separately: per function from numba's dispatcher timers, and -in total as `import tsdate` with minus without `NUMBA_DISABLE_JIT` in a fresh process -(functions with explicit signatures compile at import, not at first call; skipped -with `--no-import-compile` or `--quick`). The CSV also records provenance. Timings are -only comparable between runs on a quiet machine. +The CSV also records provenance. Timings are only comparable between runs on a quiet +machine. Implementations are chosen with `--impl`. To add one, write a function returning a -dict of callables with the same names and signatures as `_numba_impl` and register it +dict of callables with the same names and signatures as `_c_impl` and register it in `IMPLS`. ### Sensitivity of EP to last-bit differences @@ -123,10 +120,10 @@ python evaluation/ep_sensitivity.py --sizes 20 100 --seeds 1 2 3 --sweeps 1 5 10 ### Accuracy of the special functions -`numerical_accuracy.py` measures the approximation error of the production functions in -`tsdate.hypergeo` (digamma, trigamma, `betaln`, the incomplete gamma derivative and +`numerical_accuracy.py` measures the approximation error of the special functions in +`_tsdate` (digamma, trigamma, `betaln`, the incomplete gamma derivative and inverse, and the Laplace approximations to U, 1F1 and 2F1, including the -unity limit of 2F1) and `tsdate.approx` (moment matching, gamma fits, closed forms of +unity limit of 2F1) and the gamma approximations (moment matching, gamma fits, closed forms of the moment functions) against mpmath, SciPy and closed forms. It also reports how often properties that the exact functions have are violated: symmetry, monotonicity, the Kummer transformation, continuity across a switch point. One row per function and regime gives @@ -135,7 +132,7 @@ check any of this (they check only agreement with the oracles), so the table is where inaccurate regimes show up. ``` -python evaluation/numerical_accuracy.py --quick # the computation takes seconds; importing tsdate compiles numba +python evaluation/numerical_accuracy.py --quick # the computation takes seconds python evaluation/numerical_accuracy.py --only hyp2f1 gammainc # groups: polygamma betaln gammainc hyperu hyp1f1 hyp2f1 approx python evaluation/numerical_accuracy.py --output acc.csv # also writes results/acc.csv ``` diff --git a/evaluation/microbench.py b/evaluation/microbench.py index ec90da57..c62526eb 100644 --- a/evaluation/microbench.py +++ b/evaluation/microbench.py @@ -1,6 +1,6 @@ """ -Microbenchmarks of the array-level accelerated entry points in tsdate (the -numba-jitted functions that take and return arrays). Inputs are built from simulated +Microbenchmarks of the array-level entry points of the `_tsdate` extension in tsdate +(the functions that take and return arrays). Inputs are built from simulated tree sequences at several sizes, mirroring how the functions are called in production. Scalar functions (approx, hypergeo) are not timed on their own: they are exercised through the EP passes. Writes a table to stdout and, with --output, a CSV @@ -11,14 +11,8 @@ median of `time.perf_counter` is reported. Very fast calls are batched, so that a timed block lasts at least a few ms (reported times are per call). -Compile time (numba): functions with explicit signatures compile eagerly when tsdate -is imported, so a "first call" timing does not capture it. Instead report (a) the -compile time recorded by each numba dispatcher (its `compiler_lock` timer, which -includes LLVM), and (b) the total cost of `import tsdate` in a fresh process with -and without NUMBA_DISABLE_JIT (the difference is the total compile time at import). - Implementations are selected with --impl. To add one, write a function returning a -dict from function names (the keys of `_numba_impl`) to callables with the same +dict from function names (the keys of `_c_impl`) to callables with the same signature, and register it in IMPLS; everything else is implementation-agnostic. Example: @@ -28,10 +22,7 @@ import argparse import dataclasses import math -import os import statistics -import subprocess -import sys import time import common @@ -51,53 +42,11 @@ MAX_BATCH = 1000 -def _numba_impl(): - from tsdate import discrete, phasing, prior, rescaling, util, variational - - ep = variational.ExpectationPropagation - return { - "propagate_likelihood": ep.propagate_likelihood, - "propagate_prior": ep.propagate_prior, - "propagate_mutations": ep.propagate_mutations, - "mutational_area": rescaling.mutational_area, - "mutational_timescale": rescaling.mutational_timescale, - "piecewise_scale_point_estimate": rescaling.piecewise_scale_point_estimate, - "piecewise_scale_posterior": rescaling.piecewise_scale_posterior, - "_fixed_changepoints": rescaling._fixed_changepoints, - "_poisson_changepoints": rescaling._poisson_changepoints, - "_count_mutations": rescaling._count_mutations, - "_block_singletons": phasing._block_singletons, - "reallocate_unphased": phasing.reallocate_unphased, - "_mutation_frequency": phasing._mutation_frequency, - "_split_disjoint_nodes": util._split_disjoint_nodes, - "_relabel_mutations_node": util._relabel_mutations_node, - "_constrain_ages": util._constrain_ages, - "_contains_unary_nodes": util._contains_unary_nodes, - "_marginalize_over_ancestors": prior._marginalize_over_ancestors, - "conditional_coalescent_variance": prior.conditional_coalescent_variance, - "logsumexp": discrete.LogLikelihoods.logsumexp, - } - - -def _factor_arrays(factors): - """The fields of an ``EPFactors`` as the tuple of arrays that `_tsdate` takes.""" - return ( - factors.node, - factors.edge, - factors.block, - factors.scale, - factors._p, - factors._c, - factors._j, - factors._k, - ) - - def _with_factors(func, position): """Wrap a `_tsdate` function so that it takes an ``EPFactors`` at `position`.""" def wrapped(*args): - factors = _factor_arrays(args[position]) + factors = args[position].arrays() return func(*args[:position], factors, *args[position + 1 :]) return wrapped @@ -106,7 +55,7 @@ def wrapped(*args): def _c_impl(): """ Callables of the C implementation. Each ported array-level function is added as - ``name: callable`` (taking the arguments of the numba function of that name); the + ``name: callable`` (taking the arguments of the function of that name); the functions that are missing are skipped in the benchmarks. """ import _tsdate @@ -136,44 +85,10 @@ def _c_impl(): # The seam for adding implementations: name -> {function name -> callable}. A -# function returning a dict like _numba_impl's (possibly wrapping calls to adapt +# function returning a dict like _c_impl's (possibly wrapping calls to adapt # argument types such as EPFactors). Benchmarks that an implementation lacks are # skipped for it. -IMPLS = {"numba": _numba_impl, "c": _c_impl} - - -def numba_compile_times(funcs): - """Seconds spent compiling each numba dispatcher (NaN if unavailable).""" - out = {} - for name, f in funcs.items(): - total = 0.0 - try: - for res in f.overloads.values(): - total += res.metadata["timers"]["compiler_lock"] - except (AttributeError, KeyError): - total = math.nan - out[name] = total - return out - - -COMPILE_TIMES = {"numba": numba_compile_times} - - -def numba_import_compile_time(): - """Total compile time at import: `import tsdate` with minus without numba JIT.""" - - def import_time(disable_jit): - env = dict(os.environ, TSDATE_ENABLE_NUMBA_CACHE="0") - env["NUMBA_DISABLE_JIT"] = "1" if disable_jit else "0" - code = ( - "import time; import numpy, tskit, numba, scipy.special; " - "t = time.perf_counter(); import tsdate; " - "print(time.perf_counter() - t)" - ) - out = subprocess.check_output([sys.executable, "-c", code], env=env, text=True) - return float(out.strip().splitlines()[-1]) - - return import_time(False) - import_time(True) +IMPLS = {"c": _c_impl} # --------------------------------------------------------------------------- @@ -596,10 +511,6 @@ def mutation_args( ) ) - # --- discrete.py: log-sum-exp over a grid slice --- - grid = rng.normal(-5, 3, 10 * ts_flat.num_samples) - add(Bench("logsumexp", "logsumexp", _const(grid), note="size 10 x num_samples")) - return benches, info @@ -611,7 +522,7 @@ def mutation_args( def time_bench(func, bench, repeats): """Warm up, then return per-call times (seconds) for `repeats` timed blocks.""" t0 = time.perf_counter() - func(*bench.make_args()) # warm up (also first-call cost, e.g. lazy compilation) + func(*bench.make_args()) # warm up (also the first-call cost) first_call = time.perf_counter() - t0 # estimate the cost of one call to choose a batch size args = bench.make_args() @@ -652,7 +563,7 @@ def format_table(rows): def main(): p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - p.add_argument("--impl", nargs="+", default=["numba"], choices=sorted(IMPLS)) + p.add_argument("--impl", nargs="+", default=["c"], choices=sorted(IMPLS)) p.add_argument("--sizes", nargs="+", default=list(SIZES), choices=list(SIZES)) p.add_argument("--repeats", type=int, default=7) p.add_argument("--ep-iterations", type=int, default=2, help="EP iterations first") @@ -663,32 +574,17 @@ def main(): "--output", help="Output CSV name in results/ (default: none, print only)", ) - p.add_argument( - "--no-import-compile", - action="store_true", - help="Skip the (slow, ~1 min) fresh-process measurement of total compile time", - ) p.add_argument( "--quick", action="store_true", - help="Tiny smoke-test run (implies --no-import-compile)", + help="Tiny smoke-test run", ) args = p.parse_args() sizes = {k: SIZES[k] for k in args.sizes} if args.quick: sizes, args.repeats, args.ep_iterations = QUICK_SIZES, 1, 1 - args.no_import_compile = True - # Compile time is measured with an empty cache, and excluded from timings below. - os.environ["TSDATE_ENABLE_NUMBA_CACHE"] = "0" impls = {name: IMPLS[name]() for name in args.impl} - import_compile_s = {} - if "numba" in impls and not args.no_import_compile: - import_compile_s["numba"] = numba_import_compile_time() - print( - f"numba: total compile time at import ~ {import_compile_s['numba']:.1f} s " - f"(import tsdate with minus without JIT, fresh process)" - ) prov = common.provenance() rows = [] @@ -717,7 +613,6 @@ def main(): repeats=args.repeats, batch=batch, first_call_s=first, - import_compile_s=import_compile_s.get(name, math.nan), sample_size=n, length=length, note=bench.note, @@ -731,23 +626,8 @@ def main(): flush=True, ) - # Read after the runs: lazily compiled functions (no explicit signature) only - # compile on first call, which happens in the warm-up. - compile_s = { - name: COMPILE_TIMES[name](funcs) if name in COMPILE_TIMES else {} - for name, funcs in impls.items() - } - for row in rows: - func = next(b.func for b in benches if b.name == row["function"]) - row["compile_s"] = compile_s[row["impl"]].get(func, math.nan) - print() print(format_table(rows)) - print() - print("Compile time per dispatcher (s, from numba's timers):") - for name in impls: - for func, secs in sorted(compile_s[name].items(), key=lambda kv: -kv[1]): - print(f" {name:6s} {func:36s} {secs:.2f}") if args.output: common.RESULTS.mkdir(exist_ok=True) out = common.RESULTS / args.output diff --git a/evaluation/numerical_accuracy.py b/evaluation/numerical_accuracy.py index 1d0f7495..8590ff4d 100644 --- a/evaluation/numerical_accuracy.py +++ b/evaluation/numerical_accuracy.py @@ -1,6 +1,7 @@ """ Numerical accuracy of the special functions and gamma approximations in tsdate -(``tsdate.hypergeo`` and ``tsdate.approx``), per function and regime. Each row of the +(the scalar functions of ``_tsdate``, ported from the numba modules +``tsdate.hypergeo`` and ``tsdate.approx``), per function and regime. Each row of the table reports the worst error of the production function against a reference (mpmath, SciPy, a closed form) or the violation of a property the approximation should have (symmetry, monotonicity, continuity across a switch point). These are measurements, not @@ -21,12 +22,11 @@ import math import pathlib +import _tsdate import mpmath import numpy as np import scipy.special -from tsdate import approx, hypergeo - INF = math.inf RESULTS = pathlib.Path(__file__).parent / "results" @@ -119,18 +119,18 @@ def mp_psi(n, x): def polygamma(report): for name, order in [("_digamma", 0), ("_trigamma", 1)]: - func = getattr(hypergeo, name) + func = getattr(_tsdate, name.lstrip("_")) for regime, xs in POLYGAMMA_REGIMES.items(): errors = [rel(try_call(func, x), mp_psi(order, x)) for x in xs] report.worst("polygamma", name, regime, "rel", errors) # trigamma returns 1 / x**2 for x <= 1e-4, omitting pi**2 / 6 xs = [1e-6, 1e-5, 1e-4] - errors = [rel(try_call(hypergeo._trigamma, x), mp_psi(1, x)) for x in xs] + errors = [rel(try_call(_tsdate.trigamma, x), mp_psi(1, x)) for x in xs] report.worst("polygamma", "_trigamma", "x <= 1e-4 (1/x**2)", "rel", errors) # continuity at the switch points of the series for x in [1e-5, 8.5]: - lo = hypergeo._digamma(x) - hi = hypergeo._digamma(np.nextafter(x, 2 * x)) + lo = _tsdate.digamma(x) + hi = _tsdate.digamma(np.nextafter(x, 2 * x)) report.add("polygamma", "_digamma", f"jump at x={x}", "rel", rel(lo, hi)) @@ -143,9 +143,7 @@ def betaln(report): for regime, points in regimes.items(): errors = [] for p, q in points: - errors.append( - rel(try_call(hypergeo._betaln, p, q), scipy.special.betaln(p, q)) - ) + errors.append(rel(try_call(_tsdate.betaln, p, q), scipy.special.betaln(p, q))) report.worst("betaln", "_betaln", regime, "rel", errors) @@ -170,10 +168,10 @@ def gammainc_der(report): errors = [] for p, x in points: ref = gammainc_der_reference(p, x) - errors.append(rel(try_call(hypergeo._gammainc_der, p, x), ref)) + errors.append(rel(try_call(_tsdate.gammainc_der, p, x), ref)) report.worst("gammainc", "_gammainc_der", regime, "rel", errors) - below = hypergeo._gammainc_der(1000.0, 1000.0) - above = hypergeo._gammainc_der(np.nextafter(1000.0, 2000.0), 1000.0) + below = _tsdate.gammainc_der(1000.0, 1000.0) + above = _tsdate.gammainc_der(np.nextafter(1000.0, 2000.0), 1000.0) report.add("gammainc", "_gammainc_der", "jump at p = 1000", "rel", rel(above, below)) @@ -192,7 +190,7 @@ def f(t): def gammainc_inv(report, rng, quick): - func = hypergeo._gammainc_inv + func = _tsdate.gammainc_inv n = 10 if quick else 40 for a in [0.1, 0.3, 1.0, 2.5, 10.0, 60.0, 1e3, 1e4]: errors = [] @@ -265,7 +263,7 @@ def absolute(func, reference, points): def hyperu(report): - func = hypergeo._hyperu_laplace + func = _tsdate.hyperu_laplace regimes = { "a >= 1 (EP: a = y + 1)": [(1.0, 2.0, 1.0), (2.0, 5.0, 0.5), (5.0, 15.0, 1.0)] + [(10.0, 20.0, 50.0), (50.0, 60.0, 1.0), (1000.0, 1010.0, 1e4)], @@ -328,7 +326,7 @@ def hyperu(report): def hyp1f1(report): - func = hypergeo._hyp1f1_laplace + func = _tsdate.hyp1f1_laplace regimes = { "moderate": [ (1.0, 2.0, 1.0), @@ -361,7 +359,7 @@ def hyp1f1(report): def hyp2f1(report, quick): - func = hypergeo._hyp2f1_laplace + func = _tsdate.hyp2f1_laplace zs = [(-1e9,), (-100.0,), (-1.0,), (0.5,), (0.9,), (0.99,), (0.99998,), (0.999999,)] abcs = { "(1, 2, 3)": (1.0, 2.0, 3.0), @@ -435,7 +433,7 @@ def hyp2f1(report, quick): ) -# --- gamma approximations (tsdate.approx) --- # +# --- gamma approximations --- # def gamma_quantiles(shape, rate, q1=0.25, q2=0.75): @@ -444,7 +442,7 @@ def gamma_quantiles(shape, rate, q1=0.25, q2=0.75): def gamma_fits(report, rng, quick): - kl = approx.approximate_gamma_kl + kl = _tsdate.approximate_gamma_kl errors, residuals = [], [] for x, gap in [ (1.0, 1e-3), @@ -473,13 +471,13 @@ def gamma_fits(report, rng, quick): ) errors = [] for mean, variance in [(1.0, 1.0), (10.0, 4.0), (1e3, 1e-6), (1e-3, 1e-3)]: - shape, rate = approx.approximate_gamma_mom(mean, variance) + shape, rate = _tsdate.approximate_gamma_mom(mean, variance) errors += [rel((shape + 1) / rate, mean), rel((shape + 1) / rate**2, variance)] report.worst( "approx", "approximate_gamma_mom", "mean and variance matched", "rel", errors ) mean, variance = 3.0, 0.5 - logx, xlogx, logx2 = approx.approximate_log_moments(mean, variance) + logx, xlogx, logx2 = _tsdate.approximate_log_moments(mean, variance) expected = ( math.log(mean) - 0.5 * variance / mean**2, mean * math.log(mean) + 0.5 * variance / mean, @@ -494,7 +492,7 @@ def gamma_fits(report, rng, quick): errors = [] for shape in shapes: args = (*gamma_quantiles(shape, 0.001), max_shape) - result = try_call(approx.approximate_gamma_iqr, *args) + result = try_call(_tsdate.approximate_gamma_iqr, *args) errors.append( None if result is None else rel(result[0] + 1.0, min(shape, max_shape)) ) @@ -506,11 +504,11 @@ def gamma_fits(report, rng, quick): errors, ) errors = [ - rel(approx.average_gammas(np.full(3, s), np.full(3, r))[0] + 1.0, s + 1.0) + rel(_tsdate.average_gammas(np.full(3, s), np.full(3, r))[0] + 1.0, s + 1.0) for s, r in [(3.0, 0.5), (0.5, 2.0)] ] report.worst("approx", "average_gammas", "identical gammas recovered", "rel", errors) - shape, rate = approx.average_gammas(np.array([0.0]), np.array([1.0])) + shape, rate = _tsdate.average_gammas(np.array([0.0]), np.array([1.0])) report.add( "approx", "average_gammas", "single gamma, shape 1", "rel", rel(shape + 1.0, 1.0) ) @@ -519,7 +517,7 @@ def gamma_fits(report, rng, quick): def moment_functions(report, quick): a_i, b_i, y, mu = 10.0, 0.01, 3.0, 1e-4 s, r = a_i + y, b_i + 2 * mu - got = approx.twin_moments(a_i, b_i, y, mu) + got = _tsdate.twin_moments(a_i, b_i, y, mu) expected = (math.log(2) * y + math.lgamma(s) - math.log(r) * s, s / r, s / r**2) report.worst( "approx", @@ -529,10 +527,10 @@ def moment_functions(report, quick): [rel(g, e) for g, e in zip(got, expected)], ) t_i, t_j = 7.0, 2.0 - mn, va = approx.mutation_edge_moments(t_i, t_j) + mn, va = _tsdate.mutation_edge_moments(t_i, t_j) errors = [rel(mn, 4.5), rel(va, 25.0 / 12.0)] report.worst("approx", "mutation_edge_moments", "closed form", "rel", errors) - pr, mn, va = approx.mutation_block_moments(t_i, t_j) + pr, mn, va = _tsdate.mutation_block_moments(t_i, t_j) errors = [rel(pr, 7.0 / 9.0), rel(mn, pr * t_i / 2 + (1 - pr) * t_j / 2)] report.worst("approx", "mutation_block_moments", "closed form", "rel", errors) # rootward with t_j -> 0 approaches the gamma with shape a_i + y, rate b_i + mu @@ -540,7 +538,7 @@ def moment_functions(report, quick): s, r = a_i + y, b_i + mu exact = (math.lgamma(s) - s * math.log(r), s / r, s / r**2) for t_j in [1e-10, 1e-3]: - got = approx.rootward_moments(t_j, a_i, b_i, y, mu) + got = _tsdate.rootward_moments(t_j, a_i, b_i, y, mu) report.add( "approx", "rootward_moments", @@ -557,7 +555,7 @@ def moment_functions(report, quick): ) # y = 0: U(a, a + 1, z) = z**-a a_j, b_j, mu, t_i = 10.0, 0.01, 1e-4, 1000.0 - logl, mn, va = approx.sideways_moments(t_i, a_j, b_j, 0.0, mu) + logl, mn, va = _tsdate.sideways_moments(t_i, a_j, b_j, 0.0, mu) z = t_i * (mu + b_j) f0 = logl + mu * t_i - a_j * math.log(t_i) - math.lgamma(a_j) report.add( @@ -565,10 +563,10 @@ def moment_functions(report, quick): ) # projected gammas reproduce the moments args = (10.0, 0.01, 10.0, 0.01, 1.0, 1e-4) - _, mn_i, va_i, mn_j, va_j = approx.moments(*args) - _, proj_i, proj_j = approx.gamma_projection( - np.array([9.0, 0.01]), np.array([9.0, 0.01]), np.array([1.0, 1e-4]) - ) + _, mn_i, va_i, mn_j, va_j = _tsdate.moments(*args) + _, *flat = _tsdate.gamma_projection(9.0, 0.01, 9.0, 0.01, 1.0, 1e-4) + proj_i = flat[0:2] + proj_j = flat[2:4] errors = [] for proj, mn, va in [(proj_i, mn_i, va_i), (proj_j, mn_j, va_j)]: errors += [ @@ -583,7 +581,7 @@ def moment_functions(report, quick): ("moments", (1e8, 1e5, 1e8, 1e5, 1, 1e-4)), ("moments", (10, 0.01, 10, 0.01, 1, 1e-4)), ]: - va = getattr(approx, name)(*[float(a) for a in args])[2] + va = getattr(_tsdate, name)(*[float(a) for a in args])[2] regime = "shape 1e8" if args[0] == 1e8 else "typical" report.add( "approx", @@ -600,7 +598,7 @@ def moment_functions(report, quick): a_i, a_j = rng.uniform(0.5, 30, 2) b_i, b_j = log_uniform(rng, -5, -2, 2) y, mu = float(rng.integers(0, 12)), log_uniform(rng, -4, -2) - result = approx.moments(a_i, b_i, a_j, b_j, y, mu) + result = _tsdate.moments(a_i, b_i, a_j, b_j, y, mu) count += not (result[2] > 0 and result[4] > 0) report.add( "approx", @@ -615,7 +613,7 @@ def moment_functions(report, quick): a_i, a_j = rng.uniform(0.5, 30, 2) b_i, b_j = log_uniform(rng, -5, -2, 2) y, mu = float(rng.integers(0, 12)), log_uniform(rng, -4, -2) - pr = approx.mutation_unphased_moments(a_i, b_i, a_j, b_j, y, mu)[0] + pr = _tsdate.mutation_unphased_moments(a_i, b_i, a_j, b_j, y, mu)[0] count += not (0 <= pr <= 1) report.add( "approx", diff --git a/tests/oracle/approx.py b/tests/oracle/approx.py index 863a0a34..0cd4620b 100644 --- a/tests/oracle/approx.py +++ b/tests/oracle/approx.py @@ -1,11 +1,9 @@ -"""Oracles for the jitted functions in ``tsdate.approx``.""" +"""Oracles for the gamma approximations (formerly the numba module ``tsdate.approx``).""" from math import inf, nan import numpy as np -from tsdate.approx import _KLMIN_MAXITT, _KLMIN_RELTOL, KLMinimizationFailedError - from . import hypergeo # oracle: plain `math` raises on log(0), exp overflow etc., where compiled numba @@ -21,6 +19,14 @@ # `float` (marked `oracle: float`), since in numba they are Python-semantics floats. from ._libm import exp, ipow, lgamma, log +# the tolerances of the KL minimisation, as in the library +_KLMIN_MAXITT = 100 +_KLMIN_RELTOL = np.sqrt(np.finfo(np.float64).eps) + + +class KLMinimizationFailedError(Exception): + pass + def approximate_log_moments(mean, variance): """ diff --git a/tests/oracle/discrete.py b/tests/oracle/discrete.py deleted file mode 100644 index 5437186e..00000000 --- a/tests/oracle/discrete.py +++ /dev/null @@ -1,17 +0,0 @@ -"""Oracles for the jitted functions in ``tsdate.discrete``.""" - -import numpy as np - - -def logsumexp(X): - alpha = -np.inf - r = 0.0 - for x in X: - if x != -np.inf: - if x <= alpha: - r += np.exp(x - alpha) - else: - r *= np.exp(alpha - x) - r += 1.0 - alpha = x - return -np.inf if r == 0 else np.log(r) + alpha diff --git a/tests/oracle/hypergeo.py b/tests/oracle/hypergeo.py index 9b494def..1b1b9b6a 100644 --- a/tests/oracle/hypergeo.py +++ b/tests/oracle/hypergeo.py @@ -1,4 +1,4 @@ -"""Oracles for the jitted functions in ``tsdate.hypergeo``.""" +"""Oracles for the special functions (formerly the numba module ``tsdate.hypergeo``).""" from math import pi diff --git a/tests/oracle/implementations.py b/tests/oracle/implementations.py index 66f7b530..dd917b28 100644 --- a/tests/oracle/implementations.py +++ b/tests/oracle/implementations.py @@ -3,8 +3,8 @@ ``IMPLEMENTATIONS`` maps a name to a namespace with one attribute per tsdate module (``hypergeo``, ``approx``, ``variational``, ``rescaling``, ``phasing``, ``util``, -``prior``, ``discrete``), exposing the jitted functions under the same names and -signatures as the oracle modules. To drop numba, delete the "numba" entry. +``prior``), exposing the functions under the same names and signatures as the oracle +modules. The "c" entry exists if the ``_tsdate`` extension can be imported. Its namespaces have the attributes of the functions that have been ported (as thin adapters where the @@ -17,67 +17,8 @@ import numpy as np import pytest -import tsdate.approx -import tsdate.hypergeo -import tsdate.phasing -import tsdate.prior -import tsdate.rescaling -import tsdate.util -import tsdate.variational -from tsdate.discrete import LogLikelihoods - from . import variational as oracle_variational -_EP = tsdate.variational.ExpectationPropagation - -# Functions that are staticmethods of ExpectationPropagation, exposed as plain names. -_EP_STATIC = ( - "_check_valid_constraints", - "propagate_likelihood", - "propagate_prior", - "propagate_mutations", -) - - -def _numba_variational(): - """ - Namespace with ``EPFactors`` and the module-level helpers of - ``tsdate.variational`` plus the jitted staticmethods of - ``ExpectationPropagation`` as module-level names. Accessing a staticmethod on - the class returns the underlying dispatcher. - """ - ns = types.SimpleNamespace( - EPFactors=tsdate.variational.EPFactors, - _rescale_factors=tsdate.variational._rescale_factors, - _assemble_factors=tsdate.variational._assemble_factors, - _damp=tsdate.variational._damp, - _rescale=tsdate.variational._rescale, - ) - for name in _EP_STATIC: - setattr(ns, name, getattr(_EP, name)) - return ns - - -def _numba_discrete(): - """ - ``logsumexp`` is a jitted staticmethod of ``LogLikelihoods``; accessing it on - the class gives a callable ``logsumexp(X)``, so it is exposed under that name. - """ - return types.SimpleNamespace(logsumexp=LogLikelihoods.logsumexp) - - -def _numba_namespace(): - return types.SimpleNamespace( - hypergeo=tsdate.hypergeo, - approx=tsdate.approx, - variational=_numba_variational(), - rescaling=tsdate.rescaling, - phasing=tsdate.phasing, - util=tsdate.util, - prior=tsdate.prior, - discrete=_numba_discrete(), - ) - class _PortedNamespace(types.SimpleNamespace): """ @@ -335,13 +276,10 @@ def _c_namespace(): phasing=_c_phasing(_tsdate), util=_c_util(_tsdate), prior=_c_prior(_tsdate), - discrete=_PortedNamespace(), ) -IMPLEMENTATIONS: dict[str, types.SimpleNamespace] = { - "numba": _numba_namespace(), -} +IMPLEMENTATIONS: dict[str, types.SimpleNamespace] = {} try: IMPLEMENTATIONS["c"] = _c_namespace() diff --git a/tests/test_approximations.py b/tests/test_approximations.py index 454e72a6..f2496389 100644 --- a/tests/test_approximations.py +++ b/tests/test_approximations.py @@ -27,6 +27,7 @@ from math import sqrt +import _tsdate import numpy as np import pytest import scipy.integrate @@ -49,8 +50,6 @@ unphased_moments, ) -from tsdate import approx, hypergeo - # TODO: better test set? _gamma_trio_test_cases = [ # [shape1, rate1, shape2, rate2, muts, rate] [2.0, 0.0005, 1.5, 0.005, 0.0, 0.001], @@ -71,7 +70,7 @@ def test_moments(self, pars): Test mean and variance when ages of both nodes are free """ rtol = 1e-2 - ll, mn_i, va_i, mn_j, va_j = approx.moments(*pars) + ll, mn_i, va_i, mn_j, va_j = _tsdate.moments(*pars) ck_ll, ck_mn_i, ck_va_i, ck_mn_j, ck_va_j = moments(*pars) assert np.isclose(ck_ll, ll, rtol=rtol) assert np.isclose(ck_mn_i, mn_i, rtol=rtol) @@ -88,7 +87,7 @@ def test_rootward_moments(self, pars): pars_redux = (a_i, b_i, y, mu) mn_j = a_j / b_j for t_j in [0.0, mn_j]: - ll, mn_i, va_i = approx.rootward_moments(t_j, *pars_redux) + ll, mn_i, va_i = _tsdate.rootward_moments(t_j, *pars_redux) ck_ll, ck_mn_i, ck_va_i = rootward_moments(t_j, *pars_redux) assert np.isclose(ck_ll, ll, rtol=rtol) assert np.isclose(ck_mn_i, mn_i, rtol=rtol) @@ -102,7 +101,7 @@ def test_leafward_moments(self, pars): a_i, b_i, a_j, b_j, y, mu = pars t_i = a_i / b_i pars_redux = (a_j, b_j, y, mu) - ll, mn_j, va_j = approx.leafward_moments(t_i, *pars_redux) + ll, mn_j, va_j = _tsdate.leafward_moments(t_i, *pars_redux) ck_ll, ck_mn_j, ck_va_j = leafward_moments(t_i, *pars_redux) assert np.isclose(ck_ll, ll, rtol=rtol) assert np.isclose(ck_mn_j, mn_j, rtol=rtol) @@ -113,7 +112,7 @@ def test_unphased_moments(self, pars): Parent ages for an singleton nodes above an unphased individual """ rtol = 1e-2 - ll, mn_i, va_i, mn_j, va_j = approx.unphased_moments(*pars) + ll, mn_i, va_i, mn_j, va_j = _tsdate.unphased_moments(*pars) ck_ll, ck_mn_i, ck_va_i, ck_mn_j, ck_va_j = unphased_moments(*pars) assert np.isclose(ck_ll, ll, rtol=rtol) assert np.isclose(ck_mn_i, mn_i, rtol=rtol) @@ -128,7 +127,7 @@ def test_twin_moments(self, pars): """ a_i, b_i, a_j, b_j, y_ij, mu_ij = pars pars_redux = (a_i, b_i, y_ij, mu_ij) - ll, mn_i, va_i = approx.twin_moments(*pars_redux) + ll, mn_i, va_i = _tsdate.twin_moments(*pars_redux) ck_ll, ck_mn_i, ck_va_i = twin_moments(*pars_redux) assert np.isclose(ck_ll, ll) assert np.isclose(ck_mn_i, mn_i) @@ -143,7 +142,7 @@ def test_sideways_moments(self, pars): a_i, b_i, a_j, b_j, y, mu = pars pars_redux = (a_j, b_j, y, mu) t_i = a_i / b_i - ll, mn_j, va_j = approx.sideways_moments(t_i, *pars_redux) + ll, mn_j, va_j = _tsdate.sideways_moments(t_i, *pars_redux) ck_ll, ck_mn_j, ck_va_j = sideways_moments(t_i, *pars_redux) assert np.isclose(ck_ll, ll, rtol=rtol) assert np.isclose(ck_mn_j, mn_j, rtol=rtol) @@ -154,7 +153,7 @@ def test_mutation_moments(self, pars): Mutation mapped to a single branch with both nodes free """ rtol = 2e-2 - mn, va = approx.mutation_moments(*pars) + mn, va = _tsdate.mutation_moments(*pars) ck_mn, ck_va = mutation_moments(*pars) assert np.isclose(ck_mn, mn, rtol=rtol) assert np.isclose(sqrt(ck_va), sqrt(va), rtol=rtol) @@ -168,7 +167,7 @@ def test_mutation_rootward_moments(self, pars): pars_redux = (a_i, b_i, y, mu) mn_j = a_j / b_j for t_j in [0.0, mn_j]: - mn, va = approx.mutation_rootward_moments(t_j, *pars_redux) + mn, va = _tsdate.mutation_rootward_moments(t_j, *pars_redux) ck_mn, ck_va = mutation_rootward_moments(t_j, *pars_redux) assert np.isclose(ck_mn, mn, rtol=rtol) assert np.isclose(sqrt(ck_va), sqrt(va), rtol=rtol) @@ -181,7 +180,7 @@ def test_mutation_leafward_moments(self, pars): a_i, b_i, a_j, b_j, y, mu = pars t_i = a_i / b_i pars_redux = (a_j, b_j, y, mu) - mn, va = approx.mutation_leafward_moments(t_i, *pars_redux) + mn, va = _tsdate.mutation_leafward_moments(t_i, *pars_redux) ck_mn, ck_va = mutation_leafward_moments(t_i, *pars_redux) assert np.isclose(ck_mn, mn, rtol=rtol) assert np.isclose(sqrt(ck_va), sqrt(va), rtol=rtol) @@ -191,7 +190,7 @@ def test_mutation_unphased_moments(self, pars): Mutation mapped to two singleton branches with children fixed to time zero """ rtol = 1e-2 - pr, mn, va = approx.mutation_unphased_moments(*pars) + pr, mn, va = _tsdate.mutation_unphased_moments(*pars) ck_pr, ck_mn, ck_va = mutation_unphased_moments(*pars) assert np.isclose(ck_pr, pr, rtol=rtol) assert np.isclose(ck_mn, mn, rtol=rtol) @@ -204,7 +203,7 @@ def test_mutation_twin_moments(self, pars): """ a_i, b_i, a_j, b_j, y_ij, mu_ij = pars pars_redux = (a_i, b_i, y_ij, mu_ij) - pr, mn, va = approx.mutation_twin_moments(*pars_redux) + pr, mn, va = _tsdate.mutation_twin_moments(*pars_redux) ck_pr, ck_mn, ck_va = mutation_twin_moments(*pars_redux) assert np.isclose(ck_pr, pr) assert np.isclose(ck_mn, mn) @@ -219,7 +218,7 @@ def test_mutation_sideways_moments(self, pars): a_i, b_i, a_j, b_j, y, mu = pars t_i = a_i / b_i pars_redux = (a_j, b_j, y, mu) - pr, mn, va = approx.mutation_sideways_moments(t_i, *pars_redux) + pr, mn, va = _tsdate.mutation_sideways_moments(t_i, *pars_redux) ck_pr, ck_mn, ck_va = mutation_sideways_moments(t_i, *pars_redux) assert np.isclose(ck_pr, pr, rtol=rtol) assert np.isclose(ck_mn, mn, rtol=rtol) @@ -232,7 +231,7 @@ def test_mutation_edge_moments(self, pars): a_i, b_i, a_j, b_j, y, mu = pars t_i = a_i / b_i t_j = a_j / b_j - mn, va = approx.mutation_edge_moments(t_i, t_j) + mn, va = _tsdate.mutation_edge_moments(t_i, t_j) ck_mn, ck_va = mutation_edge_moments(t_i, t_j) assert np.isclose(ck_mn, mn) assert np.isclose(sqrt(ck_va), sqrt(va)) @@ -245,7 +244,7 @@ def test_mutation_block_moments(self, pars): a_i, b_i, a_j, b_j, y, mu = pars t_i = a_i / b_i t_j = a_j / b_j - pr, mn, va = approx.mutation_block_moments(t_i, t_j) + pr, mn, va = _tsdate.mutation_block_moments(t_i, t_j) ck_pr, ck_mn, ck_va = mutation_block_moments(t_i, t_j) assert np.isclose(ck_pr, pr) assert np.isclose(ck_mn, mn) @@ -254,24 +253,24 @@ def test_mutation_block_moments(self, pars): def test_approximate_gamma_kl(self, pars): a_i, b_i, a_j, b_j, y, mu = pars t_i = a_i / b_i - ln_t_i = hypergeo._digamma(a_i) - np.log(b_i) + ln_t_i = _tsdate.digamma(a_i) - np.log(b_i) t_j = a_j / b_j - ln_t_j = hypergeo._digamma(a_j) - np.log(b_j) - alpha_i, beta_i = approx.approximate_gamma_kl(t_i, ln_t_i) - alpha_j, beta_j = approx.approximate_gamma_kl(t_j, ln_t_j) + ln_t_j = _tsdate.digamma(a_j) - np.log(b_j) + alpha_i, beta_i = _tsdate.approximate_gamma_kl(t_i, ln_t_i) + alpha_j, beta_j = _tsdate.approximate_gamma_kl(t_j, ln_t_j) ck_t_i = (alpha_i + 1) / beta_i assert np.isclose(t_i, ck_t_i) ck_t_j = (alpha_j + 1) / beta_j assert np.isclose(t_j, ck_t_j) - ck_ln_t_i = hypergeo._digamma(alpha_i + 1) - np.log(beta_i) + ck_ln_t_i = _tsdate.digamma(alpha_i + 1) - np.log(beta_i) assert np.isclose(ln_t_i, ck_ln_t_i) - ck_ln_t_j = hypergeo._digamma(alpha_j + 1) - np.log(beta_j) + ck_ln_t_j = _tsdate.digamma(alpha_j + 1) - np.log(beta_j) assert np.isclose(ln_t_j, ck_ln_t_j) def test_approximate_gamma_mom(self, pars): - _, t_i, va_t_i, t_j, va_t_j = approx.moments(*pars) - alpha_i, beta_i = approx.approximate_gamma_mom(t_i, va_t_i) - alpha_j, beta_j = approx.approximate_gamma_mom(t_j, va_t_j) + _, t_i, va_t_i, t_j, va_t_j = _tsdate.moments(*pars) + alpha_i, beta_i = _tsdate.approximate_gamma_mom(t_i, va_t_i) + alpha_j, beta_j = _tsdate.approximate_gamma_mom(t_j, va_t_j) ck_t_i = (alpha_i + 1) / beta_i assert np.isclose(t_i, ck_t_i) ck_t_j = (alpha_j + 1) / beta_j @@ -292,7 +291,7 @@ def test_average_gammas(self): # E[log x] = digamma(shape) - log(rate) shape = np.array([0.5, 1.5]) rate = np.array([1.0, 1.0]) - avg_shape, avg_rate = approx.average_gammas(shape, rate) + avg_shape, avg_rate = _tsdate.average_gammas(shape, rate) E_x = np.mean(shape + 1) E_logx = np.mean(scipy.special.digamma(shape + 1)) assert np.isclose(E_x, (avg_shape + 1) / avg_rate) @@ -305,20 +304,20 @@ class TestKLMinimizationFailed: """ def test_violates_jensen(self): - with pytest.raises(approx.KLMinimizationFailedError, match="violates Jensen's"): - approx.approximate_gamma_kl(1, 0) + with pytest.raises(_tsdate.LibraryError, match="violates Jensen's"): + _tsdate.approximate_gamma_kl(1, 0) def test_asymptotic_bound(self): # check that bound is returned over threshold (rather than optimization) logx = -0.000001 - alpha, _ = approx.approximate_gamma_kl(1, logx) + alpha, _ = _tsdate.approximate_gamma_kl(1, logx) alpha += 1 alpha_bound = -0.5 / logx assert alpha == alpha_bound assert alpha > 1e4 # check that bound matches optimization result just under threshold logx = -0.000051 - alpha, _ = approx.approximate_gamma_kl(1, logx) + alpha, _ = _tsdate.approximate_gamma_kl(1, logx) alpha += 1 alpha_bound = -0.5 / logx assert np.abs(alpha - alpha_bound) < 1 diff --git a/tests/test_hypergeo.py b/tests/test_hypergeo.py index cfb3e566..a0356b46 100644 --- a/tests/test_hypergeo.py +++ b/tests/test_hypergeo.py @@ -26,13 +26,12 @@ from math import lgamma +import _tsdate import mpmath import numdifftools as nd import numpy as np import pytest -from tsdate import hypergeo - @pytest.mark.parametrize("x", [-0.3, 1e-10, 1e-6, 1e-2, 1e1, 1e2, 1e3, 1e5, 1e10]) class TestPolygamma: @@ -44,14 +43,14 @@ def test_lgamma(self, x): assert np.isclose(lgamma(x), float(mpmath.re(mpmath.loggamma(x)))) def test_digamma(self, x): - assert np.isclose(hypergeo._digamma(x), float(mpmath.psi(0, x))) + assert np.isclose(_tsdate.digamma(x), float(mpmath.psi(0, x))) def test_trigamma(self, x): - assert np.isclose(hypergeo._trigamma(x), float(mpmath.psi(1, x))) + assert np.isclose(_tsdate.trigamma(x), float(mpmath.psi(1, x))) def test_betaln(self, x): assert np.isclose( - hypergeo._betaln(x, 2 * x), + _tsdate.betaln(x, 2 * x), float(mpmath.re(mpmath.log(mpmath.beta(x, 2 * x)))), ) @@ -90,7 +89,7 @@ def test_2f1(self, pars): B = a_i + a_j + y C = a_j + y + 1 z = (mu - b_j) / (mu + b_i) - f = hypergeo._hyp2f1_laplace(A, B, C, z) + f = _tsdate.hyp2f1_laplace(A, B, C, z) check = float(mpmath.log(self._2f1_validate(*pars))) assert np.isclose(f, check, rtol=2e-2) @@ -134,7 +133,7 @@ def test_2f1(self, pars): s = -B * np.log(1 - z) A = C - A z = z / (z - 1) - f = hypergeo._hyp2f1_unity(A, B, C, z) + s + f = _tsdate.hyp2f1_unity(A, B, C, z) + s check = float(mpmath.log(self._2f1_validate(*pars))) assert np.isclose(f, check, rtol=1e-2) @@ -169,10 +168,8 @@ def test_hyperu(self, pars): A = y + 1 B = a_i + y + 1 z = t_j * (mu + b_i) - f, df = hypergeo._hyperu_laplace(A, B, z) - der = nd.Derivative( - lambda z: hypergeo._hyperu_laplace(A, B, z)[0], n=1, step=1e-4 - ) + f, df = _tsdate.hyperu_laplace(A, B, z) + der = nd.Derivative(lambda z: _tsdate.hyperu_laplace(A, B, z)[0], n=1, step=1e-4) check_f = float(mpmath.log(self._hyperu_validate(*pars))) check_df = der(z) assert np.isclose(f, check_f, rtol=2e-2) @@ -211,6 +208,6 @@ def test_hyp1f1(self, pars): A = a_j B = a_j + y + 1 z = t_i * (b_j - mu) - f = hypergeo._hyp1f1_laplace(A, B, z) + f = _tsdate.hyp1f1_laplace(A, B, z) check = float(mpmath.log(self._hyp1f1_validate(*pars))) assert np.isclose(f, check, rtol=2e-2) diff --git a/tests/test_oracle_approx.py b/tests/test_oracle_approx.py index 159e9df4..712ecb3c 100644 --- a/tests/test_oracle_approx.py +++ b/tests/test_oracle_approx.py @@ -1,10 +1,10 @@ """ Parity of each implementation (``impl``) with the oracles in ``oracle/approx.py`` for -``tsdate.approx``: values to 4 ulp, NaN and infinity patterns, and which exception is -raised. Expected values always come from the oracle. Tables hold deliberate edge cases -(boundaries of the ``_valid_*`` checks, degenerate gamma fits, regimes of the moment and -projection functions); seeded random draws cover ranges typical of expectation -propagation (EP) and extreme ones. +the gamma approximations: values to 4 ulp, NaN and infinity patterns, and which +exception is raised. Expected values always come from the oracle. Tables hold +deliberate edge cases (boundaries of the ``_valid_*`` checks, degenerate gamma fits, +regimes of the moment and projection functions); seeded random draws cover ranges +typical of expectation propagation (EP) and extreme ones. Conventions of the C port pinned here: a NaN result (not an exception) signals a parameter outside the valid region of the hypergeometric function; the ``*_projection`` @@ -21,6 +21,7 @@ import pytest import scipy.special from oracle import approx +from oracle.approx import KLMinimizationFailedError from oracle.helpers import ( INF, NAN, @@ -32,8 +33,6 @@ outcome, ) -from tsdate.approx import KLMinimizationFailedError - nextafter = np.nextafter MAX = np.finfo(np.float64).max TINY = 5e-324 @@ -41,7 +40,7 @@ def parity(impl, name, args, expected_kind=None): """ - Compare ``tsdate.approx.(*args)`` with the oracle (returning the oracle's + Compare ``impl.approx.(*args)`` with the oracle (returning the oracle's outcome); optionally check its kind. """ func = getattr(impl.approx, name) diff --git a/tests/test_oracle_discrete.py b/tests/test_oracle_discrete.py deleted file mode 100644 index 830c57e4..00000000 --- a/tests/test_oracle_discrete.py +++ /dev/null @@ -1,67 +0,0 @@ -""" -Parity of ``LogLikelihoods.logsumexp`` (a streaming log-sum-exp) with its oracle, -including NaN and infinities (which are not errors) and non-contiguous input. -""" - -import numpy as np -import pytest -from oracle import discrete -from oracle.helpers import INF, NAN, assert_outcome, assert_ulp_close, compare - -# x, outcome category of the oracle -EDGE_CASES = [ - pytest.param([], "nonfinite", id="empty"), - pytest.param([5.0], "finite", id="single"), - pytest.param([1e-320], "finite", id="single_subnormal"), - pytest.param([-INF], "nonfinite", id="single_minus_inf"), - pytest.param([-INF] * 7, "nonfinite", id="all_minus_inf"), - pytest.param([-INF, 5.0, -INF], "finite", id="minus_inf_ignored"), - pytest.param([-3.5, -INF, -INF], "finite", id="finite_first"), - pytest.param([-INF, -INF, -3.5], "finite", id="finite_last"), - pytest.param([-0.0, 0.0], "finite", id="negative_zero"), - pytest.param([1000.0, 1000.0], "finite", id="would_overflow_naively"), - pytest.param([-1000.0, -1000.0], "finite", id="would_underflow_naively"), - pytest.param([1e308, 1e308], "finite", id="huge_equal"), - pytest.param([-1e308, 1e308], "finite", id="huge_opposite"), - pytest.param([1e308, -1e308], "finite", id="huge_opposite_reversed"), - pytest.param([-800.0, 0.0, -800.0], "finite", id="dominated_middle"), - pytest.param([0.0, -800.0, -800.0], "finite", id="dominated_first"), - pytest.param([-800.0, -800.0, 0.0], "finite", id="dominated_last"), - pytest.param([1.0, 2.0, 3.0], "finite", id="increasing"), - pytest.param([3.0, 2.0, 1.0], "finite", id="decreasing"), - # NOTE: a single +inf gives +inf, but inf - inf makes NaN with two of them - pytest.param([INF], "nonfinite", id="inf"), - pytest.param([0.0, INF], "nonfinite", id="finite_and_inf"), - pytest.param([INF, INF], "nan", id="two_inf"), - pytest.param([INF, -INF, INF], "nan", id="two_inf_with_minus_inf"), - pytest.param([INF, -INF], "nonfinite", id="inf_and_minus_inf"), - # NOTE: NaN is not -inf and fails `x <= alpha`, so it takes the "new maximum" - # branch and poisons the result wherever it is - pytest.param([NAN], "nan", id="nan"), - pytest.param([NAN, 1.0], "nan", id="nan_first"), - pytest.param([1.0, NAN], "nan", id="nan_last"), - pytest.param([1.0, NAN, 2.0], "nan", id="nan_middle"), -] - - -class TestLogsumexp: - @pytest.mark.parametrize(("x", "expected_kind"), EDGE_CASES) - def test_edge_cases(self, impl, x, expected_kind): - x = np.array(x, dtype=float) - assert_outcome(impl.discrete.logsumexp, discrete.logsumexp, (x,), expected_kind) - - def test_non_contiguous_input(self, impl): - # `compare` copies its arguments to contiguous arrays, so call directly - x = np.arange(1.0, 10.0)[::2] - assert not x.flags.c_contiguous - assert_ulp_close(impl.discrete.logsumexp(x), discrete.logsumexp(x)) - - @pytest.mark.parametrize("mode", ["typical", "extreme"]) - @pytest.mark.parametrize("seed", range(4)) - def test_random(self, impl, seed, mode): - rng = np.random.default_rng(seed) - size = int(rng.integers(1, 500)) - scale = {"typical": 5.0, "extreme": 1e5}[mode] - x = rng.normal(0, scale, size) - x[rng.random(size) < rng.uniform(0, 1)] = -INF - compare(impl.discrete.logsumexp, discrete.logsumexp, x) diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index 03592495..14b7ec87 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -1,7 +1,7 @@ """ Parity of each implementation (``impl``) with the oracles in ``oracle/hypergeo.py`` -for the special functions in ``tsdate.hypergeo``: values to 4 ulp, NaN and infinity -patterns, and which exception is raised (``AssertionError`` for the domain checks, +for the special functions: values to 4 ulp, NaN and infinity patterns, and which +exception is raised (``AssertionError`` for the domain checks, ``ZeroDivisionError`` for float division by zero). Expected values always come from the oracle. Tables hold deliberate edge cases (poles, domain boundaries, both sides of a branch switch); grids and seeded random draws cover the interior and extreme ranges. @@ -26,7 +26,7 @@ def parity(impl, name, args, expected_kind=None): """ - Compare ``tsdate.hypergeo.(*args)`` with the oracle; optionally check kind. + Compare ``impl.hypergeo.(*args)`` with the oracle; optionally check kind. """ func = getattr(impl.hypergeo, name) oracle = getattr(hypergeo, name) diff --git a/tests/test_oracle_rescaling.py b/tests/test_oracle_rescaling.py index bf26a570..750fd948 100644 --- a/tests/test_oracle_rescaling.py +++ b/tests/test_oracle_rescaling.py @@ -6,6 +6,7 @@ import numpy as np import pytest +from oracle import approx as oracle_approx from oracle import rescaling from oracle.helpers import ( INF, @@ -19,11 +20,10 @@ shrink, ) -import tsdate.approx from tsdate.variational import ExpectationPropagation BREAKS_MSG = "non-increasing time breakpoints" -KLFailed = tsdate.approx.KLMinimizationFailedError +KLFailed = oracle_approx.KLMinimizationFailedError @pytest.fixture(params=["small_ts_unphased", "small_ts_historical"]) diff --git a/tests/test_python_c_tables.py b/tests/test_python_c_tables.py index 56a0d66e..1ecf36a6 100644 --- a/tests/test_python_c_tables.py +++ b/tests/test_python_c_tables.py @@ -76,6 +76,19 @@ def test_columns(self): with pytest.raises(ValueError, match="two columns"): self.call(np.ones((2, 3)), [0.5], [0], [[0, 1]]) + @pytest.mark.parametrize("kind", ["float32", "strided", "readonly"]) + def test_array_updated_in_place_must_not_be_converted(self, kind): + # a copy would silently lose the update + if kind == "float32": + likelihood = np.ones((2, 2), dtype=np.float32) + elif kind == "strided": + likelihood = np.ones((2, 4))[:, ::2] + else: + likelihood = np.ones((2, 2)) + likelihood.flags.writeable = False + with pytest.raises(ValueError): + self.call(likelihood, [0.5], [0], [[0, 1]]) + class TestMutationFrequency: def test_nodes_sample_dtype(self): diff --git a/tsdate/approx.py b/tsdate/approx.py deleted file mode 100644 index 0671378a..00000000 --- a/tsdate/approx.py +++ /dev/null @@ -1,1037 +0,0 @@ -# MIT License -# -# Copyright (c) 2021-23 Tskit Developers -# Copyright (c) 2020-21 University of Oxford -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -""" -Tools for approximating combinations of Gamma variates with Gamma distributions -""" - -from math import exp, inf, lgamma, log, nan - -import numba -import numpy as np - -from . import hypergeo -from .accelerate import numba_jit - -# TODO: these are reasonable defaults but could -# be set via a control dict -_KLMIN_MAXITT = 100 -_KLMIN_RELTOL = np.sqrt(np.finfo(np.float64).eps) - - -# shorthand for numba readonly array types, [type][dimension][constness] -# type is one of "i" (int32), "f" (float64), "b" (boolean) -# constness is one of "r" (read-only) or "w" (writable) -_f = numba.types.float64 -_i = numba.types.int32 -_b = numba.types.bool_ -_f1w = numba.types.Array(_f, 1, "C", readonly=False) -_f1r = numba.types.Array(_f, 1, "C", readonly=True) -_f2w = numba.types.Array(_f, 2, "C", readonly=False) -_f2r = numba.types.Array(_f, 2, "C", readonly=True) -_f3w = numba.types.Array(_f, 3, "C", readonly=False) -_f3r = numba.types.Array(_f, 3, "C", readonly=True) -_i1w = numba.types.Array(_i, 1, "C", readonly=False) -_i1r = numba.types.Array(_i, 1, "C", readonly=True) -_i2w = numba.types.Array(_i, 2, "C", readonly=False) -_i2r = numba.types.Array(_i, 2, "C", readonly=True) -_i3w = numba.types.Array(_i, 3, "C", readonly=False) -_i3r = numba.types.Array(_i, 3, "C", readonly=True) -_b1w = numba.types.Array(_b, 1, "C", readonly=False) -_b1r = numba.types.Array(_b, 1, "C", readonly=True) -_b2w = numba.types.Array(_b, 2, "C", readonly=False) -_b2r = numba.types.Array(_b, 2, "C", readonly=True) -_b3w = numba.types.Array(_b, 3, "C", readonly=False) -_b3r = numba.types.Array(_b, 3, "C", readonly=True) -_tuple = numba.types.Tuple -_unituple = numba.types.UniTuple -_void = numba.types.void - - -class KLMinimizationFailedError(Exception): - pass - - -@numba_jit(_unituple(_f, 3)(_f, _f)) -def approximate_log_moments(mean, variance): - """ - Approximate log moments via a second-order Taylor series expansion around - the mean, e.g.: - - E[f(x)] \\approx E[f(mean)] + variance * f''(mean)/2 - - Returns approximations to E[log x], E[x log x], E[(log x)^2] - """ - assert mean > 0 - assert variance > 0 - logx = np.log(mean) - 0.5 * variance / mean**2 - xlogx = mean * np.log(mean) + 0.5 * variance / mean - logx2 = np.log(mean) ** 2 + (1 - np.log(mean)) * variance / mean**2 - return logx, xlogx, logx2 - - -@numba_jit(_unituple(_f, 2)(_f, _f)) -def approximate_gamma_kl(x, logx): - """ - Use Newton root finding to get gamma natural parameters matching the sufficient - statistics :math:`E[x]` and :math:`E[\\log x]`, minimizing KL divergence. - - The initial condition uses the upper bound :math:`digamma(x) \\leq log(x) - 1/2x`. - - Returns the shape and rate of the approximating gamma. - """ - if x <= 0.0 or np.isinf(logx): - raise KLMinimizationFailedError("Nonpositive or nonfinite moments") - if not np.log(x) > logx: - raise KLMinimizationFailedError( - "log E[t] <= E[log t] violates Jensen's inequality" - ) - alpha = 0.5 / (np.log(x) - logx) # lower bound on alpha - # asymptotically the lower bound becomes sharp - if 1.0 / alpha < 1e-4: - return alpha - 1.0, alpha / x - itt = 0 - delta = np.inf - # determine convergence when the change in alpha falls below - # some small value (e.g. square root of machine precision) - while np.abs(delta) > np.abs(alpha) * _KLMIN_RELTOL: - if itt > _KLMIN_MAXITT: - raise KLMinimizationFailedError( - "Maximum iterations reached in KL minimization" - ) - delta = hypergeo._digamma(alpha) - np.log(alpha) + np.log(x) - logx - delta /= hypergeo._trigamma(alpha) - 1 / alpha - alpha -= delta - itt += 1 - if not np.isfinite(alpha) or alpha <= 0: - raise KLMinimizationFailedError("Invalid shape parameter in KL minimization") - return alpha - 1.0, alpha / x - - -@numba_jit(_unituple(_f, 2)(_f, _f)) -def approximate_gamma_mom(mean, variance): - """ - Use the method of moments to approximate a distribution with a gamma of the - same mean and variance, returning natural parameters - """ - if not (mean > 0.0 and variance > 0.0): - raise KLMinimizationFailedError("Nonpositive central moments") - shape = mean**2 / variance - rate = mean / variance - return shape - 1.0, rate - - -@numba.njit(_unituple(_f, 2)(_f, _f, _f, _f, _f)) -def approximate_gamma_iqr(q1, q2, x1, x2, max_shape): - """Find gamma natural parameters that match empirical quantiles""" - - def upper_bound(q, x): # cap shape parameter - beta = hypergeo._gammainc_inv(max_shape, q) / x - return max_shape - 1, beta - - if x2 == x1: - return upper_bound(q1, x1) - if not (q2 > q1 and x2 > x1): - raise KLMinimizationFailedError("Quantiles must be sorted") - alpha = log(q2 / q1) / log(x2 / x1) # lower bound - if alpha > max_shape: - return upper_bound(q1, x1) - - # refine with newton iteration - delta = inf - itt = 0 - while abs(delta) > abs(alpha) * _KLMIN_RELTOL: - if itt > _KLMIN_MAXITT: - raise KLMinimizationFailedError( - "Maximum iterations reached in quantile matching" - ) - y1 = hypergeo._gammainc_inv(alpha, q1) - y2 = hypergeo._gammainc_inv(alpha, q2) - obj = y2 / y1 - x2 / x1 - inv_1 = -exp(y1 + log(y1) * (1 - alpha) + lgamma(alpha)) - inv_2 = -exp(y2 + log(y2) * (1 - alpha) + lgamma(alpha)) - # print(itt, alpha, y1, y2) #DEBUG - gra_1 = hypergeo._gammainc_der(alpha, y1) * inv_1 - gra_2 = hypergeo._gammainc_der(alpha, y2) * inv_2 - gra = (gra_2 * y1 - gra_1 * y2) / y1**2 - delta = -obj / gra - alpha += delta - itt += 1 - - if not alpha > 0: - raise KLMinimizationFailedError("Negative shape parameter") - if alpha > max_shape: - return upper_bound(q1, x1) - beta = hypergeo._gammainc_inv(alpha, q1) / x1 - return alpha - 1, beta - - -@numba_jit(_unituple(_f, 2)(_f1r, _f1r)) -def average_gammas(alpha, beta): - """ - Given natural parameters for a set of gammas, average sufficient - statistics so as to get a "global" gamma, returning natural - parameters - """ - assert alpha.size == beta.size, "Array sizes are not equal" - avg_x = 0.0 - avg_logx = 0.0 - for shape, rate in zip(alpha + 1.0, beta): - avg_logx += hypergeo._digamma(shape) - np.log(rate) - avg_x += shape / rate - avg_x /= alpha.size - avg_logx /= alpha.size - return approximate_gamma_kl(avg_x, avg_logx) - - -@numba_jit(_b(_f, _f)) -def _valid_moments(mn, va): - if not (np.isfinite(mn) and np.isfinite(va)): - return False - if not (mn > 0.0 and va > 0.0): - return False - return True - - -@numba_jit(_b(_f, _f)) -def _valid_gamma(s, r): - if not (np.isfinite(s) and np.isfinite(r)): - return False - if s <= 0.0 or r <= 0.0: - return False - return True - - -@numba_jit(_b(_f, _f, _f)) -def _valid_hyp1f1(a, b, z): - if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(z)): - return False - if not (b >= a > 0.0): - return False - return True - - -@numba_jit(_b(_f, _f, _f)) -def _valid_hyperu(a, b, z): - if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(z)): - return False - if z <= 0.0: - return False - if not (b > a > 0.0): - return False - return True - - -@numba_jit(_b(_f, _f, _f, _f)) -def _valid_hyp2f1(a, b, c, z): - if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(c)): - return False - if not np.isfinite(z) or z >= 1 or z / (z - 1) >= 1: - return False - if not (a > 0 and b > 0 and c > 0): - return False - return True - - -# --- various EP updates --- # - - -@numba_jit(_unituple(_f, 5)(_f, _f, _f, _f, _f, _f)) -def moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_i, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, E[t_i], V[t_i], E[t_j], V[t_j]. - """ - - a = a_j - b = a_i + a_j + y_ij - c = a_j + y_ij + 1 - t = mu_ij + b_i - z = (mu_ij - b_j) / t if t > 0 else nan - - if not _valid_hyp2f1(a, b, c, z): - return nan, nan, nan, nan, nan - - hyp2f1 = hypergeo._hyp2f1_laplace - f0 = hyp2f1(a + 0, b + 0, c + 0, z) - f1 = hyp2f1(a + 1, b + 1, c + 1, z) - f2 = hyp2f1(a + 2, b + 2, c + 2, z) - s1 = a * b / c - s2 = s1 * (a + 1) * (b + 1) / (c + 1) - d1 = s1 * exp(f1 - f0) - d2 = s2 * exp(f2 - f0) - - logl = f0 + hypergeo._betaln(y_ij + 1, a) + lgamma(b) - b * log(t) - - mn_j = d1 / t - sq_j = d2 / t**2 - va_j = sq_j - mn_j**2 - - mn_i = mn_j * z + b / t - sq_i = sq_j * z**2 + (b + 1) * (mn_i + mn_j * z) / t - va_i = sq_i - mn_i**2 - - return logl, mn_i, va_i, mn_j, va_j - - -@numba_jit(_unituple(_f, 3)(_f, _f, _f, _f, _f)) -def rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): - r""" - log p(t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i - - Returns normalizing constant, E[t_i], V[t_i]. - """ - - assert t_j >= 0.0 - - s = a_i + y_ij - r = mu_ij + b_i - - if not _valid_gamma(s, r): - return nan, nan, nan - - if t_j == 0.0: - logl = lgamma(s) - s * log(r) - mn_i = s / r - va_i = s / r**2 - return logl, mn_i, va_i - - a = y_ij + 1 - b = s + 1 - z = t_j * r - - if not _valid_hyperu(a, b, z): - return nan, nan, nan - - hyperu = hypergeo._hyperu_laplace - f0, d0 = hyperu(a + 0, b + 0, z) - f1, d1 = hyperu(a + 1, b + 1, z) - - logl = f0 - b_i * t_j + (b - 1) * log(t_j) + lgamma(a) - mn_i = t_j * (1 - d0) - va_i = t_j**2 * d0 * (d1 - d0) - - return logl, mn_i, va_i - - -@numba_jit(_unituple(_f, 3)(_f, _f, _f, _f, _f)) -def leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, E[t_j], V[t_j]. - """ - - assert t_i > 0.0 - - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij - b_j) - - if not _valid_hyp1f1(a, b, z): - return nan, nan, nan - - hyp1f1 = hypergeo._hyp1f1_laplace - f0 = hyp1f1(a + 0, b + 0, z) - f1 = hyp1f1(a + 1, b + 1, z) - f2 = hyp1f1(a + 2, b + 2, z) - d1 = a / b * exp(f1 - f0) - d2 = a / b * (a + 1) / (b + 1) * exp(f2 - f0) - - logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + hypergeo._betaln(a, b - a) - mn_j = t_i * d1 - sq_j = t_i**2 * d2 - va_j = sq_j - mn_j**2 - - return logl, mn_j, va_j - - -@numba_jit(_unituple(_f, 5)(_f, _f, _f, _f, _f, _f)) -def unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, E[t_i], V[t_i], E[t_j], V[t_j]. - """ - - a = a_j - b = a_i + a_j + y_ij - c = a_j + a_i - t = mu_ij + b_i - z = (mu_ij + b_j) / t if t > 0 else nan - - if not _valid_hyp2f1(a, b, c, 1 - z): - return nan, nan, nan, nan, nan - - hyp2f1 = hypergeo._hyp2f1_laplace - f0 = hyp2f1(a + 0, b + 0, c + 0, 1 - z) - f1 = hyp2f1(a + 1, b + 1, c + 1, 1 - z) - f2 = hyp2f1(a + 2, b + 2, c + 2, 1 - z) - s1 = a * b / c - s2 = s1 * (a + 1) * (b + 1) / (c + 1) - d1 = s1 * exp(f1 - f0) - d2 = s2 * exp(f2 - f0) - - logl = f0 + hypergeo._betaln(a_j, a_i) + lgamma(b) - b * log(t) - - mn_j = d1 / t - sq_j = d2 / t**2 - va_j = sq_j - mn_j**2 - - mn_i = b / t - mn_j * z - sq_i = sq_j * z**2 + (b + 1) * (mn_i - mn_j * z) / t - va_i = sq_i - mn_i**2 - - return logl, mn_i, va_i, mn_j, va_j - - -@numba_jit(_unituple(_f, 3)(_f, _f, _f, _f)) -def twin_moments(a_i, b_i, y_ij, mu_ij): - r""" - log p(t_i) := \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i - - Returns normalizing constant, E[t_i], V[t_i]. - """ - s = a_i + y_ij - r = b_i + 2 * mu_ij - logl = log(2) * y_ij + lgamma(s) - log(r) * s - mn_i = s / r - va_i = s / r**2 - return logl, mn_i, va_i - - -@numba_jit(_unituple(_f, 3)(_f, _f, _f, _f, _f)) -def sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, E[t_j], V[t_j]. - """ - - assert t_i > 0.0 - - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij + b_j) - - if not _valid_hyperu(a, b, z): - return nan, nan, nan - - hyperu = hypergeo._hyperu_laplace - f0, d0 = hyperu(a + 0, b + 0, z) - f1, d1 = hyperu(a + 1, b + 1, z) - - logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + lgamma(a) - mn_j = -t_i * d0 - va_j = t_i**2 * d0 * (d1 - d0) - - return logl, mn_j, va_j - - -@numba_jit(_unituple(_f, 2)(_f, _f, _f, _f, _f, _f)) -def mutation_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_m, t_i, t_j) = \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns E[t_m], V[t_m]. - """ - - a = a_j - b = a_i + a_j + y_ij - c = a_j + y_ij + 1 - t = mu_ij + b_i - z = (mu_ij - b_j) / t if t > 0 else nan - - if not _valid_hyp2f1(a, b, c, z): - return nan, nan - - hyp2f1 = hypergeo._hyp2f1_laplace - f000 = hyp2f1(a + 0, b + 0, c + 0, z) - f020 = hyp2f1(a + 0, b + 2, c + 0, z) - f111 = hyp2f1(a + 1, b + 1, c + 1, z) - f121 = hyp2f1(a + 1, b + 2, c + 1, z) - f222 = hyp2f1(a + 2, b + 2, c + 2, z) - - s1 = a * b / c - d1 = b * (b + 1) / t**2 - d2 = d1 * a / c - d3 = d2 * (a + 1) / (c + 1) - - mn_m = s1 * exp(f111 - f000) / t / 2 * (1 + z) + b / t / 2 - sq_m = ( - d1 * exp(f020 - f000) / 3 + d2 * exp(f121 - f000) / 3 + d3 * exp(f222 - f000) / 3 - ) - va_m = sq_m - mn_m**2 - - return mn_m, va_m - - -@numba_jit(_unituple(_f, 2)(_f, _f, _f, _f, _f)) -def mutation_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): - r""" - log p(t_m, t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns E[t_m], V[t_m]. - """ - - logl, mn_i, va_i = rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) - mn_m = mn_i / 2 + t_j / 2 - sq_m = (va_i + mn_i**2 + mn_i * t_j + t_j**2) / 3 - va_m = sq_m - mn_m**2 - - return mn_m, va_m - - -@numba_jit(_unituple(_f, 2)(_f, _f, _f, _f, _f)) -def mutation_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_m, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns E[t_m], V[t_m]. - """ - - logl, mn_j, va_j = leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) - mn_m = mn_j / 2 + t_i / 2 - sq_m = (va_j + mn_j**2 + mn_j * t_i + t_i**2) / 3 - va_m = sq_m - mn_m**2 - - return mn_m, va_m - - -@numba_jit(_unituple(_f, 3)(_f, _f, _f, _f, _f, _f)) -def mutation_unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_m, t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - - Returns P[m under i], E[t_m], V[t_m]. - """ - - # Conditioning on ages of parents: - # P[x under i | t_i, t_j] = t_i / (t_i + t_j) - # E[x | x under t_i, t_i] = t_i / 2 - # E[x^2 | x under t_i, t_i] = t_i**2 / 3 - # and equivalently for t_j. Integrating these moments over the EP surrogate - # density leads to hypergeometric functions similar to the node case, but - # with integer perturbations of a_i, a_j, y_ij. - - a = a_j - b = a_j + a_i + y_ij - c = a_j + a_i - t = mu_ij + b_i - z = (mu_ij + b_j) / t if t > 0 else nan - - if not _valid_hyp2f1(a, b, c, 1 - z): - return nan, nan, nan - - hyp2f1 = hypergeo._hyp2f1_laplace - f000 = hyp2f1(a + 0, b + 0, c + 0, 1 - z) - f001 = hyp2f1(a + 0, b + 0, c + 1, 1 - z) - f012 = hyp2f1(a + 0, b + 1, c + 2, 1 - z) - f023 = hyp2f1(a + 0, b + 2, c + 3, 1 - z) - f212 = hyp2f1(a + 2, b + 1, c + 2, 1 - z) - f323 = hyp2f1(a + 3, b + 2, c + 3, 1 - z) - - s0 = b / t / c / (c + 1) - s1 = (c - a) * (c - a + 1) - s2 = a * (a + 1) - d0 = s0 * (b + 1) / t / (c + 2) - d1 = s1 * (c - a + 2) - d2 = s2 * (a + 2) - - mn_m = s0 * s1 * exp(f012 - f000) / 2 + s0 * s2 * exp(f212 - f000) / 2 - sq_m = d0 * d1 * exp(f023 - f000) / 3 + d0 * d2 * exp(f323 - f000) / 3 - va_m = sq_m - mn_m**2 - pr_m = (c - a) / c * exp(f001 - f000) - - return pr_m, mn_m, va_m - - -@numba_jit(_unituple(_f, 3)(_f, _f, _f, _f)) -def mutation_twin_moments(a_i, b_i, y_ij, mu_ij): - r""" - log p(t_m, t_i) := \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(int(0 < t_m < t_i) / t_i) - """ - - s = a_i + y_ij - r = b_i + 2 * mu_ij - pr_m = 0.5 - mn_m = s / r / 2 - sq_m = (s + 1) * s / 3 / r**2 - va_m = sq_m - mn_m**2 - - return pr_m, mn_m, va_m - - -@numba_jit(_unituple(_f, 3)(_f, _f, _f, _f, _f)) -def mutation_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_m, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - - Returns P[m under i], E[t_m], V[t_m]. - """ - - assert t_i > 0 - - # Conditioning on ages of parents: - # P[x under i | t_i, t_j] = t_i / (t_i + t_j) - # E[x | x under t_i, t_i] = t_i / 2 - # E[x^2 | x under t_i, t_i] = t_i**2 / 3 - # and equivalently for t_j. Integrating these moments over the EP surrogate - # density leads to Tricomi functions similar to the node case, but - # with integer perturbations of a_j, y_ij. - - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij + b_j) - - if not _valid_hyperu(a, b, z): - return nan, nan, nan - - # direct but unstable: - hyperu = hypergeo._hyperu_laplace - f00, d00 = hyperu(a + 0, b + 0, z) - f10, d10 = hyperu(a + 1, b + 0, z) - f21, d21 = hyperu(a + 2, b + 1, z) - f32, d32 = hyperu(a + 3, b + 2, z) - pr_m = 1.0 - exp(f10 - f00) * a - mn_m = pr_m * t_i / 2 + t_i * exp(f21 - f00) * a * (a + 1) / 2 - sq_m = pr_m * t_i**2 / 3 + t_i**2 * exp(f32 - f00) * a * (a + 1) * (a + 2) / 3 - - # TODO: use a stabler approach with derivatives - # note that exp(f10 - f00) = (a + z * d00) / (a - b + 1) - # however the denominator is 0 if y_ij is 0 - # note that when y_ij == 0 then a == b + 1 and f00 = z**(-a) - - va_m = sq_m - mn_m**2 - - return pr_m, mn_m, va_m - - -@numba_jit(_unituple(_f, 2)(_f, _f)) -def mutation_edge_moments(t_i, t_j): - r""" - log p(t_m) := \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns E[t_m], V[t_m]. - """ - - mn_m = 1 / 2 * (t_i + t_j) - va_m = 1 / 12 * (t_i - t_j) ** 2 - - return mn_m, va_m - - -@numba_jit(_unituple(_f, 3)(_f, _f)) -def mutation_block_moments(t_i, t_j): - r""" - log p(t_m) := \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - - Returns P[m under i], E[t_m], V[t_m]. - """ - - assert t_i > 0 - assert t_j > 0 - - pr_m = t_i / (t_i + t_j) - mn_m = pr_m * t_i / 2 + (1 - pr_m) * t_j / 2 - sq_m = pr_m * t_i**2 / 3 + (1 - pr_m) * t_j**2 / 3 - va_m = sq_m - mn_m**2 - - return pr_m, mn_m, va_m - - -# --- wrappers around updates --- # - - -@numba_jit(_tuple((_f, _f1r, _f1r))(_f1r, _f1r, _f1r)) -def gamma_projection(pars_i, pars_j, pars_ij): - r""" - log p(t_i, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, gamma natural parameters for parent and child ages - """ - a_i, b_i = pars_i - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_i += 1 - a_j += 1 - - logl, mn_i, va_i, mn_j, va_j = moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) - - if not (_valid_moments(mn_i, va_i) and _valid_moments(mn_j, va_j)): - return np.nan, pars_i, pars_j - - proj_i = approximate_gamma_mom(mn_i, va_i) - proj_j = approximate_gamma_mom(mn_j, va_j) - - return logl, np.array(proj_i), np.array(proj_j) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f1r, _f1r)) -def leafward_projection(t_i, pars_j, pars_ij): - r""" - log p(t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, gamma natural parameters for child age - """ - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_j += 1 - - logl, mn_j, va_j = leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) - - if not _valid_moments(mn_j, va_j): - return np.nan, pars_j - - proj_j = approximate_gamma_mom(mn_j, va_j) - - return logl, np.array(proj_j) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f1r, _f1r)) -def rootward_projection(t_j, pars_i, pars_ij): - r""" - log p(t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i - - Returns normalizing constant, gamma natural parameters for parent age - """ - a_i, b_i = pars_i - y_ij, mu_ij = pars_ij - a_i += 1 - - logl, mn_i, va_i = rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) - - if not _valid_moments(mn_i, va_i): - return np.nan, pars_i - - proj_i = approximate_gamma_mom(mn_i, va_i) - - return logl, np.array(proj_i) - - -@numba_jit(_tuple((_f, _f1r, _f1r))(_f1r, _f1r, _f1r)) -def unphased_projection(pars_i, pars_j, pars_ij): - r""" - log p(t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, gamma natural parameters for parent ages - """ - a_i, b_i = pars_i - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_i += 1 - a_j += 1 - - logl, mn_i, va_i, mn_j, va_j = unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) - - if not _valid_moments(mn_i, va_i) or not _valid_moments(mn_j, va_j): - return np.nan, pars_i, pars_j - - proj_i = approximate_gamma_mom(mn_i, va_i) - proj_j = approximate_gamma_mom(mn_j, va_j) - - return logl, np.array(proj_i), np.array(proj_j) - - -@numba_jit(_tuple((_f, _f1r))(_f1r, _f1r)) -def twin_projection(pars_i, pars_ij): - r""" - log p(t_i) := \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i - - Returns normalizing constant, gamma natural parameters for parent ages - """ - a_i, b_i = pars_i - y_ij, mu_ij = pars_ij - a_i += 1 - - logl, mn_i, va_i = twin_moments(a_i, b_i, y_ij, mu_ij) - - if not _valid_moments(mn_i, va_i): - return np.nan, pars_i - - proj_i = approximate_gamma_mom(mn_i, va_i) - - return logl, np.array(proj_i) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f1r, _f1r)) -def sideways_projection(t_i, pars_j, pars_ij): - r""" - log p(t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, gamma natural parameters for nonfixed parent age - """ - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_j += 1 - - logl, mn_j, va_j = sideways_moments(t_i, a_j, b_j, y_ij, mu_ij) - - if not _valid_moments(mn_j, va_j): - return np.nan, pars_j - - proj_j = approximate_gamma_mom(mn_j, va_j) - - return logl, np.array(proj_j) - - -@numba_jit(_tuple((_f, _f1r))(_f1r, _f1r, _f1r)) -def mutation_gamma_projection(pars_i, pars_j, pars_ij): - r""" - log p(t_m, t_i, t_j) = \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_i, b_i = pars_i - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_i += 1 - a_j += 1 - - mn_m, va_m = mutation_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) - - if not _valid_moments(mn_m, va_m): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return 1.0, np.array(proj_m) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f1r, _f1r)) -def mutation_leafward_projection(t_i, pars_j, pars_ij): - r""" - log p(t_m, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_j += 1 - - mn_m, va_m = mutation_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) - - if not _valid_moments(mn_m, va_m): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return 1.0, np.array(proj_m) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f1r, _f1r)) -def mutation_rootward_projection(t_j, pars_i, pars_ij): - r""" - log p(t_m, t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_i, b_i = pars_i - y_ij, mu_ij = pars_ij - a_i += 1 - - mn_m, va_m = mutation_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) - - if not _valid_moments(mn_m, va_m): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return 1.0, np.array(proj_m) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f)) -def mutation_edge_projection(t_i, t_j): - r""" - log p(t_m) := \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns phase probability, gamma natural parameters for mutation age - """ - mn_m, va_m = mutation_edge_moments(t_i, t_j) - - if not _valid_moments(mn_m, va_m): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return 1.0, np.array(proj_m) - - -@numba_jit(_tuple((_f, _f1r))(_f1r, _f1r, _f1r)) -def mutation_unphased_projection(pars_i, pars_j, pars_ij): - r""" - log p(t_m, t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_i, b_i = pars_i - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_i += 1 - a_j += 1 - - pr_m, mn_m, va_m = mutation_unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) - - if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return pr_m, np.array(proj_m) - - -@numba_jit(_tuple((_f, _f1r))(_f1r, _f1r)) -def mutation_twin_projection(pars_i, pars_ij): - r""" - log p(t_m, t_i) := \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(int(0 < t_m < t_i) / t_i) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_i, b_i = pars_i - y_ij, mu_ij = pars_ij - a_i += 1 - - pr_m, mn_m, va_m = mutation_twin_moments(a_i, b_i, y_ij, mu_ij) - - if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return pr_m, np.array(proj_m) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f1r, _f1r)) -def mutation_sideways_projection(t_i, pars_j, pars_ij): - r""" - log p(t_m, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_j += 1 - - pr_m, mn_m, va_m = mutation_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij) - - if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return pr_m, np.array(proj_m) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f)) -def mutation_block_projection(t_i, t_j): - r""" - log p(t_m) := \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j)) - - Returns phase probability, gamma natural parameters for mutation age - """ - pr_m, mn_m, va_m = mutation_block_moments(t_i, t_j) - - if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return pr_m, np.array(proj_m) diff --git a/tsdate/core.py b/tsdate/core.py index 02bdbfdc..06e040e6 100644 --- a/tsdate/core.py +++ b/tsdate/core.py @@ -248,7 +248,6 @@ def get_modified_ts(self, result): f"Set ages of {num_root_muts} nonsegregating mutations to root times." ) if self.provenance_params is not None: - # Note that the time recorded in provenance excludes numba compilation time provenance.record_provenance( tables, self.name, self.start_time, **self.provenance_params ) diff --git a/tsdate/discrete.py b/tsdate/discrete.py index e2e656d5..5229e85d 100644 --- a/tsdate/discrete.py +++ b/tsdate/discrete.py @@ -7,11 +7,11 @@ from collections import defaultdict import numpy as np +import scipy.special import scipy.stats import tskit from tqdm.auto import tqdm -from .accelerate import numba_jit from .node_time_class import LIN_GRID, LOG_GRID @@ -362,25 +362,7 @@ class LogLikelihoods(Likelihoods): identity_constant = 0.0 null_constant = -np.inf - """ - Uses an alternative to logsumexp, useful for large grid sizes, see - http://www.nowozin.net/sebastian/blog/streaming-log-sum-exp-computation.html - """ - - @staticmethod - @numba_jit - def logsumexp(X): - alpha = -np.inf - r = 0.0 - for x in X: - if x != -np.inf: - if x <= alpha: - r += np.exp(x - alpha) - else: - r *= np.exp(alpha - x) - r += 1.0 - alpha = x - return -np.inf if r == 0 else np.log(r) + alpha + logsumexp = staticmethod(scipy.special.logsumexp) @staticmethod def _lik(muts, span, dt, mutation_rate, standardize=True): @@ -404,32 +386,12 @@ def _lik_wrapper(muts_span, dt, mutation_rate, standardize=True): ) def rowsum_lower_tri(self, input_array): - """ - The function below is equivalent to (but numba makes it faster than) - np.logaddexp.reduceat(input_array, self.row_indices[0]) - """ assert len(input_array) == self.tri_size - res = list() - i_start = self.row_indices[0][0] - for i in self.row_indices[0][1:]: - res.append(self.logsumexp(input_array[i_start:i])) - i_start = i - res.append(self.logsumexp(input_array[i:])) - return np.array(res) + return np.logaddexp.reduceat(input_array, self.row_indices[0]) def rowsum_upper_tri(self, input_array): - """ - The function below is equivalent to (but numba makes it faster than) - np.logaddexp.reduceat(input_array, self.col_indices) - """ assert len(input_array) == self.tri_size - res = list() - i_start = self.col_indices[0] - for i in self.col_indices[1:]: - res.append(self.logsumexp(input_array[i_start:i])) - i_start = i - res.append(self.logsumexp(input_array[i:])) - return np.array(res) + return np.logaddexp.reduceat(input_array, self.col_indices) def _recombination_loglik(self, edge, fixed=True): # Needs to return a lower tri *or* flattened array depending on `fixed` diff --git a/tsdate/hypergeo.py b/tsdate/hypergeo.py deleted file mode 100644 index ab3d121e..00000000 --- a/tsdate/hypergeo.py +++ /dev/null @@ -1,347 +0,0 @@ -# MIT License -# -# Copyright (c) 2021-23 Tskit Developers -# Copyright (c) 2020-21 University of Oxford -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -""" -Numerically stable implementations of the Gauss hypergeometric function with numba. -""" - -import ctypes -from math import erf, exp, lgamma, log, pi, pow, sqrt # noqa: A004 - -import numba -import numpy as np -from numba.extending import get_cython_function_address - -from .accelerate import numba_jit - -_HYP2F1_TOL = 1e-10 -_HYP2F1_MAXTERM = int(1e6) - - -class Invalid2F1(Exception): # noqa N818 - pass - - -# --- numba bindings for scipy cython interface --- # - -_dbl = ctypes.c_double - -# for caching reasons, we use math.lgamma rather than scipy.special.cython_special.gammaln - -# gammaincinv -_gammaincinv_addr = get_cython_function_address( - "scipy.special.cython_special", "gammaincinv" -) -_gammaincinv_functype = ctypes.CFUNCTYPE(_dbl, _dbl, _dbl) -_gammaincinv_f8 = _gammaincinv_functype(_gammaincinv_addr) - - -@numba.cfunc("f8(f8, f8)") -def _gammainc_inv(a, x): - """scipy.special.cython_special.gammaincinv""" - return _gammaincinv_f8(a, x) - - -@numba_jit("f8(f8)") -def _digamma(x): - """ - Digamma (psi) function, from asymptotic series expansion. - """ - if x <= 0.0: - return _digamma(1 - x) - np.pi / np.tan(np.pi * x) - if x <= 1e-5: - return -np.euler_gamma - (1 / x) - if x < 8.5: - return _digamma(1 + x) - 1 / x - xpm2 = 1 / x**2 - return ( - np.log(x) - - 0.5 / x - - 0.083333333333333333 * xpm2 - + 0.008333333333333333 * xpm2**2 - - 0.003968253968253968 * xpm2**3 - + 0.004166666666666667 * xpm2**4 - - 0.007575757575757576 * xpm2**5 - + 0.021092796092796094 * xpm2**6 - ) - - -@numba_jit("f8(f8)") -def _trigamma(x): - """ - Trigamma function, from asymptotic series expansion - """ - if x <= 0.0: - return -_trigamma(1 - x) + np.pi**2 / np.sin(np.pi * x) ** 2 - if x <= 1e-4: - return 1 / x**2 - if x < 5: - return _trigamma(1 + x) + 1 / x**2 - xpm1 = 1 / x - xpm2 = 1 / x**2 - return xpm1 * ( - 1.000000000000000000 - + 0.500000000000000000 * xpm1 - + 0.166666666666666667 * np.power(xpm2, 1) - - 0.033333333333333333 * np.power(xpm2, 2) - + 0.023809523809523808 * np.power(xpm2, 3) - - 0.033333333333333333 * np.power(xpm2, 4) - + 0.075757575757575756 * np.power(xpm2, 5) - - 0.253113553113553102 * np.power(xpm2, 6) - + 1.166666666666666741 * np.power(xpm2, 7) - ) - - -@numba_jit("f8(f8, f8)") -def _betaln(p, q): - return lgamma(p) + lgamma(q) - lgamma(p + q) - - -@numba_jit("UniTuple(f8, 2)(f8, f8, f8)") -def _hyperu_laplace(a, b, x): - """ - Approximate Tricomi's confluent hypergeometric function with real - arguments, using Laplace's method with a calibration point. - - Also returns derivative wrt x. - - TODO: details - """ - - assert b >= a > 0.0 - assert x > 0.0 - - t = b - x - 1 - u = 2 * a / (sqrt(t**2 + 4 * x * a) - t) - r = (b - a - 1) * u**2 + a * (1 + u) ** 2 - g = (b - a) * log(1 + u) + a * (1 + log(u)) - x * u - log(a) * (a - 1 / 2) - - w = (b - 1) * u + a - v = u * (1 + u) - dr = w / (w * u + a * (1 + u)) - dg = (w - x * v + u) / v - du = -u * v / (w - x * u + a) - - return g - log(r) / 2, (dg - dr) * du - u - - -@numba_jit("f8(f8, f8, f8)") -def _hyp1f1_laplace(a, b, x): - """ - Approximate Kummer's confluent hypergeometric function with real arguments, - using Laplace's method with a calibration point. - - TODO: details - """ - - assert b > a > 0.0 - - if x == 0.0: - return 0.0 - - t = x - b - u = 2 * a / (sqrt(t**2 + 4 * x * a) - t) - r = u**2 * b / a + (1 - u) ** 2 * b / (b - a) - g = ( - (b - a) * log(1 - u) - + a * log(u) - + b * log(b) - - (b - a) * log(b - a) - - a * log(a) - + x * u - ) - - return g - log(r) / 2 - - -@numba_jit("f8(f8, f8, f8, f8)") -def _hyp2f1_laplace(a, b, c, x): - r""" - Approximate a Gaussian hypergeometric function with real arguments, - using Laplace's method with a calibration point. - - TODO: details - """ - - def _hyp2f1_unity(a, b, c, x): - """ - Gauss hypergeometric function when `x` is near unity - - See limits in DLMF 15.4. - - TODO: this works in practice, but when (c - a - b) is close to zero the - limits don't converge. A good reference is Buhring 2003 "Partial sums of - hypergeometric series of unit argument" - """ - assert np.isclose(x, 1.0) - assert x < 1.0 - - g = c - a - b - - if g < 0.0: - return lgamma(c) + lgamma(-g) - lgamma(a) - lgamma(b) + g * log(1 - x) - elif g > 0.0: - # will only occur when a_i + a_j < 1 - return lgamma(c) + lgamma(g) - lgamma(c - a) - lgamma(c - b) - else: - # will only occur when a_i + a_j == 1 - return log(-log(1 - x)) + lgamma(a + b) - lgamma(a) - lgamma(b) - - # TODO: simplify, we can safely assume a,b > 0? - assert c > 0.0 - assert a >= 0.0 - assert b >= 0.0 - assert c >= a - assert x < 1.0 - - if x == 0.0: - return 0.0 - - s = 0.0 - if x < 0.0: - s = -b * log(1 - x) - a = c - a - x = x / (x - 1) - - if np.isclose(x, 1.0): - return s + _hyp2f1_unity(a, b, c, x) - - t = x * (b - a) - c - u = sqrt(t**2 - 4 * a * x * (c - b)) - t - y = 2 * a / u - - assert 0 < y < 1, "Root on boundary" - - yy = y**2 / a - my = (1 - y) ** 2 / (c - a) - ymy = x**2 * b * yy * my / (1 - x * y) ** 2 - r = yy + my - ymy - f = ( - (c - 1 / 2) * log(c) - + a * (log(y) - log(a)) - + (c - a) * (log(1 - y) - log(c - a)) - - b * log(1 - x * y) - ) - - return f - log(r) / 2 + s - - -@numba_jit("f8(f8, f8)") -def _gammainc_der(p, x): - """ - Derivative of lower incomplete gamma function with regards to `p`. - - Based on Shea B (1988) "Algorithm AS 239" Applied Statistics 37: 466-473 - - Adapted from https://people.math.sc.edu/Burkardt/cpp_src/asa239/asa239.cpp - """ - - elimit = -88.0 - oflo = 1.0e37 - plimit = 1.0e3 - tol = 1.0e-14 - xbig = 1.0e8 - - assert x >= 0.0 - assert p > 0.0 - - if x == 0: - value, grad = 0.0, 0.0 - return grad - - if x > xbig: - value, grad = 1.0, 0.0 - return grad - - if p > plimit: # gaussian approximation - pn1 = 3 * sqrt(p) * (pow(x / p, 1 / 3) + 1 / (9 * p) - 1) - grad = pn1 / (2 * p) - 1 / sqrt(p) * (pow(x / p, 1 / 3) + 1 / (3 * p)) - grad *= 1 / sqrt(2 * pi) * exp(-(pn1**2) / 2) - value = (1 + erf(pn1 / sqrt(2))) / 2 - return grad - - if x <= 1 or x < p: # series expansion - arg = p * log(x) - x - lgamma(p + 1) - value, grad = 1.0, 0.0 - c, dc = 1.0, 0.0 - a = p - while True: - a += 1.0 - dc = -c * x / a**2 + dc * x / a - c *= x / a - value += c - grad += dc - if c <= tol: - break - darg = exp(arg) * (log(x) - _digamma(p + 1)) - grad = grad * exp(arg) + value * darg - arg += log(value) - if arg >= elimit: - value = exp(arg) - else: - grad = 0.0 - value = 0.0 - return grad - else: # continued fraction - arg = p * log(x) - x - lgamma(p) - a = 1.0 - p - b = a + x + 1.0 - c = 0.0 - pn1, pn2, pn3, pn4 = 1.0, x, x + 1.0, x * b - dpn1, dpn2, dpn3, dpn4 = 0.0, 0.0, 0.0, -x - value, grad = pn3 / pn4, 0.0 - while True: - a += 1.0 - b += 2.0 - c += 1.0 - an = a * c - pn5 = b * pn3 - an * pn1 - pn6 = b * pn4 - an * pn2 - dpn5 = b * dpn3 - pn3 - an * dpn1 + c * pn1 - dpn6 = b * dpn4 - pn4 - an * dpn2 + c * pn2 - if pn6 != 0.0: - rn = pn5 / pn6 - grad = (dpn5 * pn6 - pn5 * dpn6) / pn6**2 - if abs(value - rn) <= min(tol, tol * rn): - break - value = rn - pn1, pn2, pn3, pn4 = pn3, pn4, pn5, pn6 - dpn1, dpn2, dpn3, dpn4 = dpn3, dpn4, dpn5, dpn6 - if oflo <= abs(pn5): - pn1 /= oflo - pn2 /= oflo - pn3 /= oflo - pn4 /= oflo - dpn1 /= oflo - dpn2 /= oflo - dpn3 /= oflo - dpn4 /= oflo - darg = exp(arg) * (log(x) - _digamma(p)) - grad = grad * exp(arg) + value * darg - arg += log(value) - if arg >= elimit: - grad *= -1.0 - value = 1.0 - exp(arg) - else: - grad = 0.0 - value = 1.0 - return grad diff --git a/tsdate/phasing.py b/tsdate/phasing.py index 5dba4d7b..84d861e6 100644 --- a/tsdate/phasing.py +++ b/tsdate/phasing.py @@ -23,159 +23,15 @@ Tools for phasing singleton mutations """ +import _tsdate import numpy as np import tskit -from .accelerate import numba_jit -from .approx import _b1r, _b2r, _f, _f1r, _f2w, _i1r, _i1w, _i2r, _i2w, _tuple, _void - # --- machinery used by ExpectationPropagation class --- # -@numba_jit(_void(_f2w, _f1r, _i1r, _i2r)) -def reallocate_unphased(edges_likelihood, mutations_phase, mutations_block, blocks_edges): - """ - Add a proportion of each unphased singleton mutation to one of the two - edges to which it maps - """ - assert mutations_phase.size == mutations_block.size - assert blocks_edges.shape[1] == 2 - - num_edges = edges_likelihood.shape[0] - edges_unphased = np.full(num_edges, False) - edges_unphased[blocks_edges[:, 0]] = True - edges_unphased[blocks_edges[:, 1]] = True - - num_unphased = np.sum(edges_likelihood[edges_unphased, 0]) - edges_likelihood[edges_unphased, 0] = 0.0 - for m, b in enumerate(mutations_block): - if b == tskit.NULL: - continue - i, j = blocks_edges[b] - assert tskit.NULL < i < num_edges - assert edges_unphased[i] - assert tskit.NULL < j < num_edges - assert edges_unphased[j] - if np.isnan(mutations_phase[m]): # TODO: fix rare numerical issue - continue - assert 0.0 <= mutations_phase[m] <= 1.0 - edges_likelihood[i, 0] += mutations_phase[m] - edges_likelihood[j, 0] += 1 - mutations_phase[m] - assert np.isclose(num_unphased, np.sum(edges_likelihood[edges_unphased, 0])) - - -@numba_jit( - _tuple((_f2w, _i2w, _i1w))( - _b1r, _i1r, _i1r, _f1r, _i1r, _i1r, _f1r, _f1r, _i1r, _i1r, _f - ) -) -def _block_singletons( - individuals_unphased, - nodes_individual, - mutations_node, - mutations_position, - edges_parent, - edges_child, - edges_left, - edges_right, - indexes_insert, - indexes_remove, - sequence_length, -): - """ - TODO - """ - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size - assert indexes_insert.size == indexes_remove.size == edges_parent.size - assert mutations_node.size == mutations_position.size - - num_mutations = mutations_node.size - num_edges = edges_parent.size - num_individuals = individuals_unphased.size - - indexes_mutation = np.argsort(mutations_position) - position_insert = edges_left[indexes_insert] - position_remove = edges_right[indexes_remove] - position_mutation = mutations_position[indexes_mutation] - - individuals_edges = np.full((num_individuals, 2), tskit.NULL) - individuals_position = np.full(num_individuals, np.nan) - individuals_singletons = np.zeros(num_individuals) - individuals_block = np.full(num_edges, tskit.NULL) - mutations_block = np.full(num_mutations, tskit.NULL) - - blocks_span = [] - blocks_singletons = [] - blocks_edges = [] - blocks_order = [] - - num_blocks = 0 - left = 0.0 - a, b, d = 0, 0, 0 - while a < num_edges or b < num_edges: - while b < num_edges and position_remove[b] == left: # edges out - e = indexes_remove[b] - c = edges_child[e] - i = nodes_individual[c] - if i != tskit.NULL and individuals_unphased[i]: - u, v = individuals_edges[i] - assert u == e or v == e - s = u if v == e else v - individuals_edges[i] = s, tskit.NULL - if s != tskit.NULL: # flush block - blocks_order.append(individuals_block[i]) - blocks_edges.extend([e, s]) - blocks_singletons.append(individuals_singletons[i]) - blocks_span.append(left - individuals_position[i]) - individuals_position[i] = np.nan - individuals_block[i] = tskit.NULL - individuals_singletons[i] = 0.0 - b += 1 - - while a < num_edges and position_insert[a] == left: # edges in - e = indexes_insert[a] - c = edges_child[e] - i = nodes_individual[c] - if i != tskit.NULL and individuals_unphased[i]: - u, v = individuals_edges[i] - assert u == tskit.NULL or v == tskit.NULL - individuals_edges[i] = [e, max(u, v)] - individuals_position[i] = left - if individuals_block[i] == tskit.NULL: - individuals_block[i] = num_blocks - num_blocks += 1 - a += 1 - - right = sequence_length - if b < num_edges: - right = min(right, position_remove[b]) - if a < num_edges: - right = min(right, position_insert[a]) - left = right - - while d < num_mutations and position_mutation[d] < right: # mutations - m = indexes_mutation[d] - c = mutations_node[m] - i = nodes_individual[c] - if i != tskit.NULL and individuals_unphased[i]: - mutations_block[m] = individuals_block[i] - individuals_singletons[i] += 1.0 - d += 1 - - mutations_block = mutations_block.astype(np.int32) - blocks_edges = np.array(blocks_edges, dtype=np.int32).reshape(-1, 2) - blocks_singletons = np.array(blocks_singletons) - blocks_span = np.array(blocks_span) - blocks_order = np.array(blocks_order) - blocks_stats = np.column_stack((blocks_singletons, blocks_span)) - assert num_blocks == blocks_edges.shape[0] == blocks_stats.shape[0] - - # sort block arrays so that mutations_block points to correct row - blocks_order = np.argsort(blocks_order) - blocks_edges = blocks_edges[blocks_order] - blocks_stats = blocks_stats[blocks_order] - - return blocks_stats, blocks_edges, mutations_block +reallocate_unphased = _tsdate.reallocate_unphased +_block_singletons = _tsdate.block_singletons def block_singletons(ts, individuals_unphased): @@ -205,78 +61,7 @@ def block_singletons(ts, individuals_unphased): ) -@numba_jit(_i2w(_b2r, _i1r, _f1r, _i1r, _i1r, _f1r, _f1r, _i1r, _i1r, _f)) -def _mutation_frequency( - nodes_sample, - mutations_node, - mutations_position, - edges_parent, - edges_child, - edges_left, - edges_right, - indexes_insert, - indexes_remove, - sequence_length, -): - """ - TODO - """ - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size - assert indexes_insert.size == indexes_remove.size == edges_parent.size - assert mutations_node.size == mutations_position.size - - num_nodes, num_sample_sets = nodes_sample.shape - num_mutations = mutations_node.size - num_edges = edges_parent.size - - indexes_mutation = np.argsort(mutations_position) - position_insert = edges_left[indexes_insert] - position_remove = edges_right[indexes_remove] - position_mutation = mutations_position[indexes_mutation] - - nodes_parent = np.full(num_nodes, tskit.NULL) - nodes_samples = np.zeros((num_nodes, num_sample_sets), dtype=np.int32) - mutations_freq = np.zeros((num_mutations, num_sample_sets), dtype=np.int32) - - # TODO: there's a better way than passing a big bool array - for i in range(num_sample_sets): - nodes_samples[nodes_sample[:, i], i] = 1.0 - - left = 0.0 - a, b, d = 0, 0, 0 - while a < num_edges or b < num_edges: - while b < num_edges and position_remove[b] == left: # edges out - e = indexes_remove[b] - p, c = edges_parent[e], edges_child[e] - nodes_parent[c] = tskit.NULL - while p != tskit.NULL: - nodes_samples[p] -= nodes_samples[c] - p = nodes_parent[p] - b += 1 - - while a < num_edges and position_insert[a] == left: # edges in - e = indexes_insert[a] - p, c = edges_parent[e], edges_child[e] - nodes_parent[c] = p - while p != tskit.NULL: - nodes_samples[p] += nodes_samples[c] - p = nodes_parent[p] - a += 1 - - right = sequence_length - if b < num_edges: - right = min(right, position_remove[b]) - if a < num_edges: - right = min(right, position_insert[a]) - left = right - - while d < num_mutations and position_mutation[d] < right: - m = indexes_mutation[d] - c = mutations_node[m] - mutations_freq[m] = nodes_samples[c] - d += 1 - - return mutations_freq +_mutation_frequency = _tsdate.mutation_frequency def mutation_frequency(ts, sample_sets=None): diff --git a/tsdate/prior.py b/tsdate/prior.py index 2cb0095f..3bbfd5e5 100644 --- a/tsdate/prior.py +++ b/tsdate/prior.py @@ -28,6 +28,7 @@ import os from collections import defaultdict, namedtuple +import _tsdate import numpy as np import scipy.cluster import scipy.special @@ -36,7 +37,6 @@ from tqdm.auto import tqdm from . import cache, demography, node_time_class, provenance, util -from .accelerate import numba_jit #: The default value for `approx_prior_size` (see :func:`~tsdate.build_prior_grid` and #: :func:`~tsdate.build_parameter_grid`) @@ -67,55 +67,7 @@ def gamma_approx(mean, variance): return (mean**2) / variance, mean / variance -@numba_jit("float64[:, :](float64[:, :])") -def _marginalize_over_ancestors(val): - """ - Integrate an expectation over counts of extant ancestors. In a tree with - "n" tips, the probability that there are "a" extent ancestors when a - subtree of size "k" coalesces is hypergeometric-ish (Wuif & Donnelly 1998), - and may be calculated recursively over increasing "a" and decreasing "k" - (e.g. using recursive relationships for binomial coefficients). - """ - n, N = val.shape # number of tips, number of moments - pr_a_ln = [np.nan, np.nan, 0.0] # log Pr(a | k, n) - out = np.zeros((n + 1, N)) - for k in range(n - 1, 1, -1): - const = np.log(n - k) + np.log(k - 2) - np.log(k + 1) - for a in range(2, n - k + 2): - out[k] += np.exp(pr_a_ln[a]) * val[a] - if k > 2: # Pr(a | k, n) to Pr(a | k - 1, n) - pr_a_ln[a] += const - np.log(n - a - k + 2) - if k > 2: # Pr(n - k + 1 | k - 1, n) to Pr(n - k + 2 | k - 1, n) - pr_a_ln.append(pr_a_ln[-1] + np.log(n - k + 2) - np.log(k + 1) - const) - out[n] = val[1] - return out - - -@numba_jit("float64[:](uint64)") -def conditional_coalescent_variance(num_tips): - """ - Variance of node age conditional on the number of descendant leaves, under - the standard coalescent. Returns array indexed by number of descendant - leaves. - """ - - coal_rates = np.array( - [2 / (i * (i - 1)) if i > 1 else 0.0 for i in range(1, num_tips + 1)] - ) - - # hypoexponential mean and variance; e.g. conditional on the number of - # extant ancestors when the node coalesces, the expected time of - # coalescence is the sum of exponential RVs (Wuif and Donnelly 1998) - mean = coal_rates.copy() - variance = coal_rates.copy() ** 2 - for i in range(coal_rates.size - 2, 0, -1): - mean[i] += mean[i + 1] - variance[i] += variance[i + 1] - - # marginalize over number of ancestors using recursive algorithm - moments = _marginalize_over_ancestors(np.stack((mean, variance + mean**2), 1)) - - return moments[:, 1] - moments[:, 0] ** 2 +conditional_coalescent_variance = _tsdate.conditional_coalescent_variance class ConditionalCoalescentTimes: diff --git a/tsdate/rescaling.py b/tsdate/rescaling.py index 3792011f..f118707e 100644 --- a/tsdate/rescaling.py +++ b/tsdate/rescaling.py @@ -23,187 +23,19 @@ Utilities for rescaling time according to a mutational clock """ -from math import inf, log - -import numba +import _tsdate import numpy as np import tskit -from .accelerate import numba_jit -from .approx import ( - _b, - _b1r, - _f, - _f1r, - _f1w, - _f2r, - _f2w, - _i, - _i1r, - _i1w, - _tuple, - _unituple, - approximate_gamma_iqr, -) -from .hypergeo import _gammainc_inv as gammainc_inv from .util import mutation_span_array # NOQA: F401 +_fixed_changepoints = _tsdate.fixed_changepoints -@numba_jit(_i1w(_f1r, _i)) -def _fixed_changepoints(counts, epochs): - """ - Find breakpoints such that `counts` is divided roughly equally across `epochs` - """ - assert epochs > 0 - Y = np.append(0.0, np.cumsum(counts)) - Z = Y / Y[-1] - z = np.linspace(0, 1, epochs + 1) - e = np.searchsorted(Z, z, "right") - 1 - if e[0] > 0: - e[0] = 0 - if e[-1] < counts.size: - e[-1] = counts.size - return e.astype(np.int32) - - -@numba_jit(_i1w(_f1r, _f1r, _f, _f, _f)) -def _poisson_changepoints(counts, offset, penalty, min_counts, min_offset): - """ - Given Poisson counts and offsets for a sequence of observations, find the set - of changepoints for the Poisson rate that maximizes the profile likelihood - under a linear penalty on complexity (e.g. penalty == 2 is AIC). - - See: "Optimal detection of changepoints with a linear computation cost" - (https://doi.org/10.1080/01621459.2012.737745) - """ - - assert counts.size == offset.size - assert min_counts >= 0 - assert min_offset >= 0 - assert penalty >= 0 - - N = np.append(0, np.cumsum(offset)) - Y = np.append(0, np.cumsum(counts)) - - def f(i, j): # loss - n = N[j] - N[i] - y = Y[j] - Y[i] - s = n < min_offset or y < min_counts - return inf if s else -2 * y * (log(y) - log(n) - 1) - - dim = counts.size - cost = np.empty(dim) - F = np.empty(dim + 1) - C = {0: np.empty(0, dtype=np.int64)} - - F[0] = -penalty - for j in np.arange(1, dim + 1): - argmin, minval = 0, np.inf - for i in C: # minimize - cost[i] = F[i] + f(i, j) + penalty - if cost[i] < minval: - minval = cost[i] - argmin = i - F[j] = minval - for i in set(C): # prune - if cost[i] > F[j] + penalty: - C.pop(i) - C[j] = np.append(C[argmin], argmin) - - breaks = np.append(C[dim], dim).astype(np.int32) - return breaks - - -@numba_jit( - _tuple((_f2w, _i1w))(_b1r, _i1r, _f1r, _i1r, _i1r, _f1r, _f1r, _i1r, _i1r, _f, _b) -) -def _count_mutations( - node_is_sample, - mutations_node, - mutations_position, - edges_parent, - edges_child, - edges_left, - edges_right, - indexes_insert, - indexes_remove, - sequence_length, - size_biased, -): - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size - assert indexes_insert.size == indexes_remove.size == edges_parent.size - assert mutations_node.size == mutations_position.size - - num_mutations = mutations_node.size - num_edges = edges_parent.size - num_nodes = node_is_sample.size - - indexes_mutation = np.argsort(mutations_position) - position_insert = edges_left[indexes_insert] - position_remove = edges_right[indexes_remove] - position_mutation = mutations_position[indexes_mutation] - - nodes_samples = np.zeros(num_nodes) - nodes_edge = np.full(num_nodes, tskit.NULL) - nodes_parent = np.full(num_nodes, tskit.NULL) - mutations_edge = np.full(num_mutations, tskit.NULL) - edges_mutations = np.zeros(num_edges) - edges_span = np.zeros(num_edges) - - nodes_samples[node_is_sample] = 1.0 - left = 0.0 - a, b, d = 0, 0, 0 - while a < num_edges or b < num_edges: - remainder = sequence_length - left - - while b < num_edges and position_remove[b] == left: # edges out - e = indexes_remove[b] - p, c = edges_parent[e], edges_child[e] - nodes_edge[c] = tskit.NULL - nodes_parent[c] = tskit.NULL - if size_biased: - while p != tskit.NULL: # downdate sample counts - edges_span[e] -= nodes_samples[c] * remainder - nodes_samples[p] -= nodes_samples[c] - e, p = nodes_edge[p], nodes_parent[p] - else: - edges_span[e] -= remainder - b += 1 - - while a < num_edges and position_insert[a] == left: # edges in - e = indexes_insert[a] - p, c = edges_parent[e], edges_child[e] - nodes_edge[c] = e - nodes_parent[c] = p - if size_biased: - while p != tskit.NULL: # update sample counts - edges_span[e] += nodes_samples[c] * remainder - nodes_samples[p] += nodes_samples[c] - e, p = nodes_edge[p], nodes_parent[p] - else: - edges_span[e] += remainder - a += 1 - - right = sequence_length - if b < num_edges: - right = min(right, position_remove[b]) - if a < num_edges: - right = min(right, position_insert[a]) - left = right - while d < num_mutations and position_mutation[d] < right: - m = indexes_mutation[d] - c = mutations_node[m] - e = nodes_edge[c] - if e != tskit.NULL: - mutations_edge[m] = e - edges_mutations[e] += nodes_samples[c] if size_biased else 1.0 - d += 1 +_poisson_changepoints = _tsdate.poisson_changepoints - mutations_edge = mutations_edge.astype(np.int32) - edges_stats = np.column_stack((edges_mutations, edges_span)) - return edges_stats, mutations_edge +_count_mutations = _tsdate.count_mutations def count_mutations(ts, node_is_sample=None, size_biased=False): @@ -239,216 +71,23 @@ def count_mutations(ts, node_is_sample=None, size_biased=False): ) -@numba_jit(_tuple((_f1w, _f1w, _f1w, _i1w))(_f1r, _f2r, _i1r, _i1r)) -def mutational_area( - nodes_time, - likelihoods, - edges_parent, - edges_child, -): - """ - Calculate the total number of mutations and mutational area per inter-node - interval. These are infinitesimal; e.g. the actual count in an interval is - `returned_count * duration`. - - :param np.ndarray nodes_time: point estimates for node ages - :param np.ndarray likelihoods: edges are rows; mutation - counts and mutational span are columns - :param np.ndarray edges_parent: node index for the parent of each edge - :param np.ndarray edges_child: node index for the child of each edge - :param np.ndarray edges_weight: a weight for each edge - """ - - assert edges_parent.size == edges_child.size - assert likelihoods.shape == (edges_parent.size, 2) - - # index node by unique time breaks - nodes_order = np.argsort(nodes_time) - nodes_index = np.zeros(nodes_time.size, dtype=np.int32) - epoch_breaks = [0.0] - k = 0 - for i, j in zip(nodes_order[1:], nodes_order[:-1]): - if nodes_time[i] > nodes_time[j]: - epoch_breaks.append(nodes_time[i]) - k += 1 - nodes_index[i] = k - epoch_breaks = np.array(epoch_breaks) - num_epochs = epoch_breaks.size - 1 - - # instantaneous mutation rate per edge - edges_length = nodes_time[edges_parent] - nodes_time[edges_child] - edges_subset = edges_length > 0 - edges_counts = likelihoods.copy() - edges_counts[edges_subset, 0] /= edges_length[edges_subset] - - # pass over edges, measuring overlap with each time interval - epoch_counts = np.zeros((num_epochs, 2)) - for e in np.flatnonzero(edges_subset): - p, c = edges_parent[e], edges_child[e] - a, b = nodes_index[c], nodes_index[p] - if a < num_epochs: - epoch_counts[a] += edges_counts[e] - if b < num_epochs: - epoch_counts[b] -= edges_counts[e] - counts = np.cumsum(epoch_counts[:, 0]) - offset = np.cumsum(epoch_counts[:, 1]) - duration = np.diff(epoch_breaks) - - return counts, offset, duration, nodes_index - - -# --- version before refactor, keeping around for reference --- -# @numba_jit(_unituple(_f1w, 2)(_f1r, _f2r, _f2r, _i1r, _i1r, _f1r, _i)) -# def mutational_timescale( -# nodes_time, -# likelihoods, -# constraints, -# edges_parent, -# edges_child, -# edges_weight, -# max_intervals, -# ): -# """ -# Rescale node ages so that the instantaneous mutation rate is constant. -# Edges with a negative duration are ignored when calculating the total -# rate. Returns a rescaled point estimate and the posterior. -# -# :param np.ndarray nodes_time: point estimates for node ages -# :param np.ndarray likelihoods: edges are rows; mutation -# counts and mutational span are columns -# :param np.ndarray constraints: lower and upper bounds on node age -# :param np.ndarray edges_parent: node index for the parent of each edge -# :param np.ndarray edges_child: node index for the child of each edge -# :param np.ndarray edges_weight: a weight for each edge -# :param int max_intervals: maximum number of intervals within which to -# estimate the time scaling -# """ -# -# assert edges_parent.size == edges_child.size == edges_weight.size -# assert likelihoods.shape[0] == edges_parent.size and likelihoods.shape[1] == 2 -# assert constraints.shape[0] == nodes_time.size and constraints.shape[1] == 2 -# assert max_intervals > 0 -# -# nodes_fixed = constraints[:, 0] == constraints[:, 1] -# assert np.all(nodes_time[nodes_fixed] == constraints[nodes_fixed, 0]) -# -# # index node by unique time breaks -# nodes_order = np.argsort(nodes_time) -# nodes_index = np.zeros(nodes_time.size, dtype=np.int32) -# epoch_breaks = [0.0] -# k = 0 -# for i, j in zip(nodes_order[1:], nodes_order[:-1]): -# if nodes_time[i] > nodes_time[j]: -# epoch_breaks.append(nodes_time[i]) -# k += 1 -# nodes_index[i] = k -# epoch_breaks = np.array(epoch_breaks) -# epoch_length = np.diff(epoch_breaks) -# num_epochs = epoch_length.size -# -# # instantaneous mutation rate per edge -# edges_length = nodes_time[edges_parent] - nodes_time[edges_child] -# edges_subset = edges_length > 0 -# edges_counts = likelihoods.copy() -# edges_counts[edges_subset, 0] /= edges_length[edges_subset] -# -# # pass over edges, measuring overlap with each time interval -# epoch_counts = np.zeros((num_epochs, 2)) -# for e in np.flatnonzero(edges_subset): -# p, c = edges_parent[e], edges_child[e] -# a, b = nodes_index[c], nodes_index[p] -# if a < num_epochs: -# epoch_counts[a] += edges_counts[e] * edges_weight[e] -# if b < num_epochs: -# epoch_counts[b] -= edges_counts[e] * edges_weight[e] -# counts = np.cumsum(epoch_counts[:, 0]) -# offset = np.cumsum(epoch_counts[:, 1]) -# -# # rescale time such that mutation density is constant between changepoints -# # TODO: use poisson changepoints to further refine -# changepoints = _fixed_changepoints(offset * epoch_length, max_intervals) -# changepoints = np.union1d(changepoints, nodes_index[nodes_fixed]) -# adjust = np.zeros(changepoints.size) -# k = 0 -# for i, j in zip(changepoints[:-1], changepoints[1:]): -# assert j > i -# # TODO: when changepoint intersects a fixed node? -# n = np.sum(offset[i:j]) -# y = np.sum(counts[i:j]) -# z = np.sum(epoch_length[i:j]) -# assert n > 0, "Zero edge span in interval" -# adjust[k + 1] = z * y / n -# k += 1 -# adjust = np.cumsum(adjust) -# origin = epoch_breaks[changepoints] -# -# return origin, adjust - - -@numba_jit(_unituple(_f1w, 2)(_f1r, _f2r, _b1r, _i1r, _i1r, _i)) -def mutational_timescale( - nodes_time, - likelihoods, - nodes_fixed, - edges_parent, - edges_child, - max_intervals, -): - """ - Rescale node ages so that the instantaneous mutation rate is constant. - Edges with a negative duration are ignored when calculating the total - rate. Returns a rescaled point estimate and the posterior. - - :param np.ndarray nodes_time: point estimates for node ages - :param np.ndarray likelihoods: edges are rows; mutation - counts and mutational span are columns - :param np.ndarray constraints: lower and upper bounds on node age - :param np.ndarray edges_parent: node index for the parent of each edge - :param np.ndarray edges_child: node index for the child of each edge - :param int max_intervals: maximum number of intervals within which to - estimate the time scaling - """ - - assert edges_parent.size == edges_child.size - assert likelihoods.shape[0] == edges_parent.size - assert likelihoods.shape[1] == 2 - assert nodes_fixed.size == nodes_time.size - assert max_intervals > 0 - - counts, offset, duration, indexes = mutational_area( - nodes_time, - likelihoods, - edges_parent, - edges_child, - ) +mutational_area = _tsdate.mutational_area - # rescale time such that mutation density is constant between changepoints - # TODO: use poisson changepoints to further refine - epoch_breaks = np.append(0.0, np.cumsum(duration)) - changepoints = _fixed_changepoints(offset * duration, max_intervals) - changepoints = np.unique(changepoints) - # changepoints = np.union1d(changepoints, indexes[nodes_fixed]) - adjust = np.zeros(changepoints.size) - # --- without any internal constraints --- - k = 0 - for i, j in zip(changepoints[:-1], changepoints[1:]): - assert j > i - # TODO: when changepoint intersects a fixed node? - n = np.sum(offset[i:j]) - y = np.sum(counts[i:j]) - z = np.sum(duration[i:j]) - assert n > 0, "Zero edge span in interval" - adjust[k + 1] = z * y / n - k += 1 +mutational_timescale = _tsdate.mutational_timescale - adjust = np.cumsum(adjust) - origin = epoch_breaks[changepoints] - return origin, adjust +def _check_increasing_breaks(original_breaks, rescaled_breaks): + if not np.all(np.diff(rescaled_breaks) > 0) or not np.all( + np.diff(original_breaks) > 0 + ): + raise ValueError( + "Rescaling produced non-increasing time breakpoints. " + "Try setting `rescaling_intervals` to a smaller value " + "(e.g. half its current value)." + ) -@numba.njit(_f2w(_f2r, _b1r, _f1r, _f1r, _f, _f)) def piecewise_scale_posterior( posteriors, posteriors_fixed, @@ -457,96 +96,24 @@ def piecewise_scale_posterior( quantile_width, max_shape, ): - """ - :param np.ndarray posteriors_fixed: if True do not rescale corresponding posterior - :param float quantile_width: width of interquantile range to use for estimating - rescaled shape parameter, e.g. 0.5 uses interquartile range - """ - - assert posteriors_fixed.size == posteriors.shape[0] - assert original_breaks.size == rescaled_breaks.size - assert 1 > quantile_width > 0 - - if not np.all(np.diff(rescaled_breaks) > 0): - raise ValueError( - "Rescaling produced non-increasing time breakpoints. " - "Try setting `rescaling_intervals` to a smaller value " - "(e.g. half its current value)." - ) - if not np.all(np.diff(original_breaks) > 0): - raise ValueError( - "Rescaling produced non-increasing time breakpoints. " - "Try setting `rescaling_intervals` to a smaller value " - "(e.g. half its current value)." - ) - - dim = posteriors.shape[0] - quant_lower = quantile_width / 2 - quant_upper = 1 - quantile_width / 2 - - freed = ~posteriors_fixed - assert np.all(np.logical_and(posteriors[freed, 0] > -1, posteriors[freed, 1] > 0)) - - # use posterior mean as a point estimate - lower = np.zeros(dim) - upper = np.zeros(dim) - midpt = np.zeros(dim) - for i in np.flatnonzero(freed): - alpha, beta = posteriors[i] - lower[i] = gammainc_inv(alpha + 1, quant_lower) / beta - upper[i] = gammainc_inv(alpha + 1, quant_upper) / beta - midpt[i] = (alpha + 1) / beta - - # rescale quantiles - scalings = np.append(np.diff(rescaled_breaks) / np.diff(original_breaks), 0) - - def rescale(x): - i = np.searchsorted(original_breaks, x, "right") - 1 - assert i.min() >= 0 # DEBUG - assert i.max() < scalings.size # DEBUG - return rescaled_breaks[i] + scalings[i] * (x - original_breaks[i]) - - midpt = rescale(midpt) - lower = rescale(lower) - upper = rescale(upper) - - # reproject posteriors using inter-quantile range - new_posteriors = np.full(posteriors.shape, np.nan) - for i in np.flatnonzero(freed): - alpha, beta = approximate_gamma_iqr( - quant_lower, quant_upper, lower[i], upper[i], max_shape - ) - beta = (alpha + 1) / midpt[i] # choose rate so as to keep mean - new_posteriors[i] = alpha, beta - - return new_posteriors + _check_increasing_breaks(original_breaks, rescaled_breaks) + return _tsdate.piecewise_scale_posterior( + posteriors, + posteriors_fixed, + original_breaks, + rescaled_breaks, + quantile_width, + max_shape, + ) -@numba_jit(_f1w(_f1r, _b1r, _f1r, _f1r)) def piecewise_scale_point_estimate( - point_estimate, - point_fixed, - original_breaks, - rescaled_breaks, + point_estimate, point_fixed, original_breaks, rescaled_breaks ): - if not np.all(np.diff(rescaled_breaks) > 0): - raise ValueError( - "Rescaling produced non-increasing time breakpoints. " - "Try setting `rescaling_intervals` to a smaller value " - "(e.g. half its current value)." - ) - if not np.all(np.diff(original_breaks) > 0): - raise ValueError( - "Rescaling produced non-increasing time breakpoints. " - "Try setting `rescaling_intervals` to a smaller value " - "(e.g. half its current value)." - ) - scalings = np.append(np.diff(rescaled_breaks) / np.diff(original_breaks), 0) - idx = np.searchsorted(original_breaks, point_estimate, "right") - 1 - rescaled_estimate = rescaled_breaks[idx] + \ - scalings[idx] * (point_estimate - original_breaks[idx]) # fmt: skip - rescaled_estimate[point_fixed] = point_estimate[point_fixed] - return rescaled_estimate + _check_increasing_breaks(original_breaks, rescaled_breaks) + return _tsdate.piecewise_scale_point_estimate( + point_estimate, point_fixed, original_breaks, rescaled_breaks + ) # standalone API for rescaling (TODO: needs testing) diff --git a/tsdate/util.py b/tsdate/util.py index a31e0960..bf94be53 100644 --- a/tsdate/util.py +++ b/tsdate/util.py @@ -28,15 +28,13 @@ import logging import time +import _tsdate import numpy as np import tskit -from numba.types import UniTuple as _unituple # NOQA: N813 import tsdate from . import provenance -from .accelerate import numba_jit -from .approx import _b, _b1r, _f, _f1r, _f1w, _i, _i1r, _i1w logger = logging.getLogger(__name__) @@ -373,7 +371,6 @@ def mutation_span_array(tree_sequence): # Some functions for changing tskit metadata # See https://github.com/tskit-dev/tskit/discussions/2954 -# TODO - potentially possible to speed up using numba? def _reorder_nodes(node_table, order, extra_md_dict): # extra_md_dict ({rowid: new_byte_metadata}) can be used to pass metadata to replace # the existing metadata in a row. This works by creating new rows for the metadata, @@ -405,121 +402,10 @@ def _reorder_nodes(node_table, order, extra_md_dict): ) -@numba_jit(_unituple(_i1w, 4)(_i1r, _i1r, _f1r, _f1r, _b1r)) -def _split_disjoint_nodes( - edges_parent, edges_child, edges_left, edges_right, node_excluded -): - """ - Split disconnected regions of nodes into separate nodes. +_split_disjoint_nodes = _tsdate.split_disjoint_nodes - Returns updated edges_parent, edges_child, mutations_node, and indices indicating - from which original node the new nodes are derived. - """ - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size - num_edges = edges_parent.size - num_nodes = node_excluded.size - - # For each edge, check whether parent/child is separated by a gap from the - # previous edge involving either parent/child. Label disconnected segments - # per node by integers starting at zero. - edges_order = np.argsort(edges_left) - # TODO: is a sort really needed here? - edges_segments = np.full((2, num_edges), -1, dtype=np.int32) - nodes_segments = np.full(num_nodes, -1, dtype=np.int32) - nodes_right = np.full(node_excluded.size, -np.inf, dtype=np.float64) - for e in edges_order: - nodes = edges_parent[e], edges_child[e] - for i, n in enumerate(nodes): - if node_excluded[n]: - continue - nodes_segments[n] += edges_left[e] > nodes_right[n] - edges_segments[i, e] = nodes_segments[n] - nodes_right[n] = max(nodes_right[n], edges_right[e]) - - # Create "nodes_segments[i]" supplementary nodes by copying node "i". - # Store the id of the first supplement for each node in "nodes_map". - split_nodes = [] # the nodes in the original that were split - nodes_map = np.full(num_nodes, -1, dtype=np.int32) - for i, s in enumerate(nodes_segments): - for j in range(s): - if j == 0: - nodes_map[i] = num_nodes - split_nodes.append(i) - num_nodes += 1 - split_nodes = np.array(split_nodes, dtype=np.int32) - nodes_order = np.arange(num_nodes, dtype=np.int32) - if len(split_nodes) > 0: - nodes_order[-len(split_nodes) :] = split_nodes - - # Relabel the nodes on each edge given "nodes_map" - for e in edges_order: - nodes = edges_parent[e], edges_child[e] - for i, n in enumerate(nodes): - if edges_segments[i, e] > 0: - edges_segments[i, e] += nodes_map[n] - 1 - else: - edges_segments[i, e] = n - edges_parent, edges_child = edges_segments[0, ...], edges_segments[1, ...] - - return edges_parent, edges_child, nodes_order, split_nodes - - -@numba_jit(_i1w(_i1r, _f1r, _i1r, _i1r, _i1r, _f1r, _f1r, _i1r, _i1r)) -def _relabel_mutations_node( - mutations_node, - mutations_position, - nodes_order, - edges_parent, - edges_child, - edges_left, - edges_right, - insert_index, - remove_index, -): - """ - Traverse trees, maintaining a mapping between old and new node IDs in the - current tree. Update `mutations_node` to reflect new IDs. - """ - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size - assert edges_parent.size == insert_index.size == remove_index.size - assert mutations_position.size == mutations_node.size - - num_nodes = nodes_order.size - num_edges = edges_parent.size - num_mutations = mutations_position.size - - insert_position = edges_left[insert_index] - remove_position = edges_right[remove_index] - sequence_length = remove_position[-1] - - output = np.full(num_mutations, tskit.NULL, dtype=np.int32) - nodes_map = np.full(num_nodes, tskit.NULL, dtype=np.int32) - a, b, m = 0, 0, 0 - left = 0.0 - while left < sequence_length: - while b < num_edges and remove_position[b] == left: # edges out - b += 1 - - while a < num_edges and insert_position[a] == left: # edges in - e = insert_index[a] - c, p = edges_child[e], edges_parent[e] - nodes_map[nodes_order[c]] = c - nodes_map[nodes_order[p]] = p - a += 1 - - right = sequence_length - if b < num_edges: - right = min(right, remove_position[b]) - if a < num_edges: - right = min(right, insert_position[a]) - left = right - - while m < num_mutations and mutations_position[m] < right: - assert nodes_map[mutations_node[m]] != tskit.NULL - output[m] = nodes_map[mutations_node[m]] - m += 1 - - return output + +_relabel_mutations_node = _tsdate.relabel_mutations_node def split_disjoint_nodes(ts, *, record_provenance=None): @@ -596,58 +482,7 @@ def split_disjoint_nodes(ts, *, record_provenance=None): return tables.tree_sequence() -@numba_jit(_f1w(_f1r, _b1r, _i1r, _i1r, _f, _i)) -def _constrain_ages( - nodes_time, nodes_fixed, edges_parent, edges_child, epsilon, max_iterations -): - """ - Approximate least squares solution to the positive branch length - constraint, using the method of alternating projections. Loosely based on - Dykstra's algorithm, see: - - Dykstra RL, "An algorithm for restricted least squares regression", JASA - 1983 - """ - assert nodes_time.size == nodes_fixed.size - assert edges_parent.size == edges_child.size - - num_edges = edges_parent.size - nodes_time = nodes_time.copy() - edges_cavity = np.zeros((num_edges, 2)) - for _ in range(max_iterations): # method of alternating projections - if np.all(nodes_time[edges_parent] - nodes_time[edges_child] > epsilon): - return nodes_time - for e in range(num_edges): - p, c = edges_parent[e], edges_child[e] - nodes_time[c] -= edges_cavity[e, 0] - nodes_time[p] -= edges_cavity[e, 1] - adjustment = nodes_time[c] - nodes_time[p] # + epsilon - edges_cavity[e, :] = 0.0 - if adjustment > 0: - assert not (nodes_fixed[c] and nodes_fixed[p]) - if not nodes_fixed[c] and not nodes_fixed[p]: - edges_cavity[e, 0] = -adjustment / 2 - edges_cavity[e, 1] = adjustment / 2 - elif nodes_fixed[c] and not nodes_fixed[p]: - edges_cavity[e, 0] = 0 - edges_cavity[e, 1] = adjustment - elif not nodes_fixed[c] and nodes_fixed[p]: - edges_cavity[e, 0] = -adjustment - edges_cavity[e, 1] = 0 - nodes_time[c] += edges_cavity[e, 0] - nodes_time[p] += edges_cavity[e, 1] - # print( - # "min length:", np.min(nodes_time[edges_parent] - nodes_time[edges_child]) - # ) - - # force remaining constraint, which can change the ages of fixed nodes - for e in range(num_edges): - p, c = edges_parent[e], edges_child[e] - # TODO: even if nodes_fixed[p], this will still change the age - if nodes_time[c] + epsilon >= nodes_time[p]: - nodes_time[p] = nodes_time[c] + epsilon - - return nodes_time +_constrain_ages = _tsdate.constrain_ages def constrain_ages(ts, nodes_time, epsilon=1e-6, max_iterations=0): @@ -690,56 +525,7 @@ def constrain_ages(ts, nodes_time, epsilon=1e-6, max_iterations=0): return constrained_nodes_time -@numba_jit(_b(_b1r, _i1r, _f1r, _f1r, _i1r, _i1r, _f, _i)) -def _contains_unary_nodes( - nodes_mask, - edges_parent, - edges_left, - edges_right, - indexes_insert, - indexes_remove, - sequence_length, - num_nodes, -): - assert edges_parent.size == edges_left.size == edges_right.size - assert indexes_insert.size == indexes_remove.size == edges_parent.size - - num_edges = edges_parent.size - nodes_children = np.zeros(num_nodes, dtype=np.int32) - position_insert = edges_left[indexes_insert] - position_remove = edges_right[indexes_remove] - - left = 0.0 - a, b = 0, 0 - while a < num_edges or b < num_edges: - check = set() - - while b < num_edges and position_remove[b] == left: # edges out - e = indexes_remove[b] - p = edges_parent[e] - nodes_children[p] -= 1 - check.add(p) - b += 1 - - while a < num_edges and position_insert[a] == left: # edges in - e = indexes_insert[a] - p = edges_parent[e] - nodes_children[p] += 1 - check.add(p) - a += 1 - - for p in check: - if not nodes_mask[p] and nodes_children[p] == 1: - return True - - right = sequence_length - if b < num_edges: - right = min(right, position_remove[b]) - if a < num_edges: - right = min(right, position_insert[a]) - left = right - - return False +_contains_unary_nodes = _tsdate.contains_unary_nodes def contains_unary_nodes(ts, skip_samples=True): diff --git a/tsdate/variational.py b/tsdate/variational.py index 0056e6bc..9bdfa53e 100644 --- a/tsdate/variational.py +++ b/tsdate/variational.py @@ -27,15 +27,11 @@ import logging import time -import numba +import _tsdate import numpy as np import tskit -from numba.types import void as _void from tqdm.auto import tqdm -from . import approx -from .accelerate import numba_jit -from .approx import _b, _b1r, _f, _f1r, _f1w, _f2r, _f2w, _f3w, _i, _i1r from .phasing import block_singletons, reallocate_unphased from .rescaling import ( count_mutations, @@ -69,28 +65,12 @@ TINY = np.sqrt(np.finfo(np.float64).tiny) # DEBUG -# dataclass for factors -_EPFactors = [ - ("node", _f3w), - ("edge", _f3w), - ("block", _f3w), - ("scale", _f1w), - ("_p", _i1r), - ("_c", _i1r), - ("_j", _i1r), - ("_k", _i1r), -] - -@numba.experimental.jitclass(_EPFactors) class EPFactors: """ Mutable state of the EP algorithm, that is the factors associated with each edge likelihood / block likelihood / prior factor, that together form the posterior. - - Because of constraints on numba's AOT compilation of jitclass, - this is a dataclass (no intrinsic methods). """ def __init__( @@ -113,86 +93,21 @@ def __init__( self._p, self._c = edge_parents, edge_children self._j, self._k = block_left, block_right - -# bypass bug in https://github.com/numba/numba/issues/7808 -_fac = numba.deferred_type() if numba.config.DISABLE_JIT \ - else EPFactors.class_type.instance_type # fmt: skip - - -# helper functions for numerical stability -@numba_jit(_void(_fac)) -def _rescale_factors(factors): - """ - At each update, all factors associated with a node need to be rescaled. - This is expensive, so we keep track of the scaling in a separate vector. - As updates progress, the factors will drift upward in magnitude while - the scaling drifts downward. To avoid underflow, we may need to - cancel out the scaling. - """ - factors.edge[:, ROOTWARD] *= factors.scale[factors._p, np.newaxis] - factors.edge[:, LEAFWARD] *= factors.scale[factors._c, np.newaxis] - factors.block[:, ROOTWARD] *= factors.scale[factors._j, np.newaxis] - factors.block[:, LEAFWARD] *= factors.scale[factors._k, np.newaxis] - factors.node[:, MIXPRIOR] *= factors.scale[:, np.newaxis] - factors.node[:, CONSTRNT] *= factors.scale[:, np.newaxis] - factors.scale[:] = 1.0 - - -@numba_jit(_f2w(_fac)) -def _assemble_factors(factors): - """ - Transform factors into posteriors, intended for debugging purposes only. - """ - posterior = np.zeros((factors.scale.size, 2)) - for i, (p, c) in enumerate(zip(factors._p, factors._c)): - posterior[p] += factors.edge[i, ROOTWARD] - posterior[c] += factors.edge[i, LEAFWARD] - for i, (j, k) in enumerate(zip(factors._j, factors._k)): - posterior[j] += factors.block[i, ROOTWARD] - posterior[k] += factors.block[i, LEAFWARD] - posterior += factors.node[:, MIXPRIOR] - posterior += factors.node[:, CONSTRNT] - return posterior - - -@numba_jit(_f(_f1r, _f1r, _f)) -def _damp(x, y, s): - """ - If `x - y` is too small, find `d` so that `x - d*y` is large enough: - - x[0] - d*y[0] + 1 >= (x[0] + 1)*s - x[1] - d*y[1] >= y[1]*s - - for `0 < s < 1`. - """ - assert x.size == y.size == 2 - if np.all(y == 0.0) and np.all(x == 0.0): - return 1.0 - assert 0 < s < 1 - assert 0.0 < x[0] + 1 - assert 0.0 < x[1] - a = 1.0 if (1 + x[0] - y[0] > (1 + x[0]) * s) else (1 - s) * (1 + x[0]) / y[0] - b = 1.0 if (x[1] - y[1] > x[1] * s) else (1 - s) * x[1] / y[1] - d = min(a, b) - assert 0.0 < d <= 1.0 - return d - - -@numba_jit(_f(_f1r, _f)) -def _rescale(x, s): - """ - Find `d` so that `d*x[0] + 1 <= s[0]` or `d*x[0] + 1 >= 1/s[0]` - """ - assert x.size == 2 - if np.all(x == 0.0): - return 1.0 - assert 0 < x[0] + 1 - assert 0 < x[1] - if 1 + x[0] > s: - return (s - 1) / x[0] - elif 1 + x[0] < 1 / s: - return (1 / s - 1) / x[0] - return 1.0 + def arrays(self): + """ + The arrays, as the tuple that the functions of ``_tsdate`` take; the first + four are updated in place by them. + """ + return ( + self.node, + self.edge, + self.block, + self.scale, + self._p, + self._c, + self._j, + self._k, + ) # main algorithm @@ -231,18 +146,13 @@ class ExpectationPropagation: """ @staticmethod - @numba_jit(_void(_f2r, _i1r, _i1r)) def _check_valid_constraints(constraints, edges_parent, edges_child): # Check that upper-bound on node age is greater than maximum lower-bound # for ages of descendants - lower_max = constraints[:, LOWER].copy() - for p, c in zip(edges_parent, edges_child): - lower_max[p] = max(lower_max[c], lower_max[p]) - if np.any(lower_max > constraints[:, UPPER]): - raise ValueError( - "Node age constraints are inconsistent, some descendants have" - " lower bounds that exceed upper bounds of their ancestors." - ) + try: + _tsdate.check_valid_constraints(constraints, edges_parent, edges_child) + except _tsdate.LibraryError as e: + raise ValueError(str(e)) from None @staticmethod def _check_valid_inputs(ts, mutation_rate, allow_unary): @@ -257,7 +167,7 @@ def _check_valid_state( factors, ): # Check that the messages sum to the posterior (debugging only) - posterior_check = _assemble_factors(factors) + posterior_check = _tsdate.assemble_factors(factors.arrays()) np.testing.assert_allclose(posterior_check, posterior) def __init__(self, ts, *, mutation_rate, allow_unary=False, singletons_phased=True): @@ -350,350 +260,6 @@ def __init__(self, ts, *, mutation_rate, allow_unary=False, singletons_phased=Tr self.block_order = np.arange(num_blocks, dtype=np.int32) self.mutation_order = np.arange(ts.num_mutations, dtype=np.int32) - @staticmethod - @numba_jit(_void(_i1r, _i1r, _i1r, _f2r, _f2r, _f2w, _fac, _f1w, _f, _f, _b)) - def propagate_likelihood( - edge_order, - edges_parent, - edges_child, - likelihoods, - constraints, - posterior, - factors, - lognorm, - max_shape, - min_step, - unphased, - ): - # Update approximating factors for Poisson mutation likelihoods on edges. - # - # :param numpy.ndarray edges_parent: integer array of parent ids per edge - # :param numpy.ndarray edges_child: integer array of child ids per edge - # :param numpy.ndarray likelihoods: array of dimension `[num_edges, 2]` - # containing mutation count and mutational target size per edge. - # :param numpy.ndarray constraints: array of dimension `[num_nodes, 2]` - # containing lower and upper bounds for each node. - # :param numpy.ndarray posterior: array of dimension `[num_nodes, 2]` - # containing natural parameters for each node, updated in-place. - # :param EPFactors factors: object containing parent and child factors - # (natural parameters) for each edge, updated in-place. - # :param numpy.ndarray lognorm: array of dimension `[num_edges]` - # containing the approximate normalizing constants per edge, - # updated in-place. - # :param float max_shape: the maximum allowed shape for node posteriors. - # :param float min_step: the minimum allowed step size in (0, 1). - # :param bool unphased: if True, edges are treated as blocks of unphased - # singletons in contemporary individuals - - assert constraints.shape == posterior.shape - assert edges_child.size == edges_parent.size - assert likelihoods.shape == (edges_parent.size, 2) - assert max_shape >= 1.0 - assert 0.0 < min_step < 1.0 - - def cavity_damping(x, y): - return _damp(x, y, min_step) - - def posterior_damping(x): - return _rescale(x, max_shape) - - def leafward_projection(x, y, z): - if unphased: - return approx.sideways_projection(x, y, z) - return approx.leafward_projection(x, y, z) - - def rootward_projection(x, y, z): - if unphased: - return approx.sideways_projection(x, y, z) - return approx.rootward_projection(x, y, z) - - def gamma_projection(x, y, z): - if unphased: - return approx.unphased_projection(x, y, z) - return approx.gamma_projection(x, y, z) - - def twin_projection(x, y): - assert unphased, "Invalid update" - return approx.twin_projection(x, y) - - fixed = constraints[:, LOWER] == constraints[:, UPPER] - - scale = factors.scale - factor = factors.block if unphased else factors.edge - assert factor.shape == (edges_parent.size, 2, 2) - - for i in edge_order: - p, c = edges_parent[i], edges_child[i] - if scale[p] < TINY or scale[c] < TINY: - # modifies `scale` and `factor` by reference - _rescale_factors(factors) - if fixed[p] and fixed[c]: - continue - elif fixed[p] and not fixed[c]: - # in practice this should only occur if a sample is the - # ancestor of another sample - child_message = factor[i, LEAFWARD] * scale[c] - child_delta = cavity_damping(posterior[c], child_message) - child_cavity = posterior[c] - child_delta * child_message - edge_likelihood = child_delta * likelihoods[i] - parent_age = constraints[p, LOWER] - lognorm[i], posterior[c] = leafward_projection( - parent_age, - child_cavity, - edge_likelihood, - ) - factor[i, LEAFWARD] *= 1.0 - child_delta - factor[i, LEAFWARD] += (posterior[c] - child_cavity) / scale[c] - child_eta = posterior_damping(posterior[c]) - posterior[c] *= child_eta - scale[c] *= child_eta - elif fixed[c] and not fixed[p]: - # in practice this should only occur if a sample has age - # greater than zero - parent_message = factor[i, ROOTWARD] * scale[p] - parent_delta = cavity_damping(posterior[p], parent_message) - parent_cavity = posterior[p] - parent_delta * parent_message - edge_likelihood = parent_delta * likelihoods[i] - child_age = constraints[c, LOWER] - lognorm[i], posterior[p] = rootward_projection( - child_age, - parent_cavity, - edge_likelihood, - ) - factor[i, ROOTWARD] *= 1.0 - parent_delta - factor[i, ROOTWARD] += (posterior[p] - parent_cavity) / scale[p] - parent_eta = posterior_damping(posterior[p]) - posterior[p] *= parent_eta - scale[p] *= parent_eta - else: - if p == c: # singleton block with single parent - parent_message = factor[i, ROOTWARD] * scale[p] - parent_delta = cavity_damping(posterior[p], parent_message) - parent_cavity = posterior[p] - parent_delta * parent_message - edge_likelihood = parent_delta * likelihoods[i] - child_age = constraints[c, LOWER] - lognorm[i], posterior[p] = \ - twin_projection(parent_cavity, edge_likelihood) # fmt: skip - factor[i, ROOTWARD] *= 1.0 - parent_delta - factor[i, ROOTWARD] += (posterior[p] - parent_cavity) / scale[p] - parent_eta = posterior_damping(posterior[p]) - posterior[p] *= parent_eta - scale[p] *= parent_eta - else: - # lower-bound cavity - parent_message = factor[i, ROOTWARD] * scale[p] - child_message = factor[i, LEAFWARD] * scale[c] - parent_delta = cavity_damping(posterior[p], parent_message) - child_delta = cavity_damping(posterior[c], child_message) - delta = min(parent_delta, child_delta) - - parent_cavity = posterior[p] - delta * parent_message - child_cavity = posterior[c] - delta * child_message - edge_likelihood = delta * likelihoods[i] - - # match moments and update factors - lognorm[i], posterior[p], posterior[c] = gamma_projection( - parent_cavity, - child_cavity, - edge_likelihood, - ) - factor[i, ROOTWARD] *= 1.0 - delta - factor[i, ROOTWARD] += (posterior[p] - parent_cavity) / scale[p] - factor[i, LEAFWARD] *= 1.0 - delta - factor[i, LEAFWARD] += (posterior[c] - child_cavity) / scale[c] - - # upper-bound posterior - parent_eta = posterior_damping(posterior[p]) - child_eta = posterior_damping(posterior[c]) - posterior[p] *= parent_eta - posterior[c] *= child_eta - scale[p] *= parent_eta - scale[c] *= child_eta - - @staticmethod - @numba_jit(_void(_b1r, _f2w, _fac, _f, _i, _f)) - def propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol): - # Update approximating factors for global prior. - # - # :param ndarray free: boolean array for if prior should be applied to node - # :param ndarray penalty: initial value for regularisation penalty - # :param ndarray posterior: rows are nodes, columns are first and - # second natural parameters of gamma posteriors. Updated in place. - # :param EPFactors factors: object containing EP messages for nodes. - # Updated in place. - # :param float max_shape: the maximum allowed shape for node posteriors. - # :param int em_maxitt: the maximum number of EM iterations to use when - # fitting the regularisation. - # :param int em_reltol: the termination criterion for relative change in - # log-likelihood. - - assert free.size == posterior.shape[0] - assert max_shape >= 1.0 - - def posterior_damping(x): - return _rescale(x, max_shape) - - if not np.any(free): - return - - factor = factors.node - scale = factors.scale - assert factor.shape == (free.size, 2, 2) - assert scale.size == free.size - - # fit an exponential to cavity distributions for unconstrained nodes - cavity = posterior - factor[:, MIXPRIOR] * scale[:, np.newaxis] - shape, rate = cavity[free, 0] + 1, cavity[free, 1] - penalty = 1 / np.mean(shape / rate) - itt, delta = 0, np.inf - while abs(delta) > abs(penalty) * em_reltol: - if itt > em_maxitt: - break - delta = 1 / np.mean(shape / (rate + penalty)) - penalty - penalty += delta - itt += 1 - assert penalty > 0 - - # update posteriors and rescale to keep shape bounded - posterior[free, 1] = cavity[free, 1] + penalty - factor[free, MIXPRIOR] = \ - (posterior[free] - cavity[free]) / scale[free, np.newaxis] # fmt: skip - for i in np.flatnonzero(free): - eta = posterior_damping(posterior[i]) - posterior[i] *= eta - scale[i] *= eta - - @staticmethod - @numba_jit(_void(_i1r, _f2w, _f1w, _i1r, _i1r, _i1r, _f2r, _f2r, _f2r, _fac, _b)) - def propagate_mutations( - mutations_order, - mutations_posterior, - mutations_phase, - mutations_edge, - edges_parent, - edges_child, - likelihoods, - constraints, - posterior, - factors, - unphased, - ): - # Calculate posteriors for mutations. (publicly undocumented) - # - # :param ndarray mutations_order: integer array giving order in - # which to traverse mutations - # :param ndarray mutations_posterior: array of dimension `(num_mutations, 2)` - # containing natural parameters for each mutation, modified in place - # :param ndarray mutations_phase: array of dimension `(num_mutations, )` - # containing mutation phase, modified in place - # :param ndarray mutations_edge: integer array giving edge for each mutation - # :param ndarray edges_parent: integer array of parent ids per edge - # :param ndarray edges_child: integer array of child ids per edge - # :param ndarray likelihoods: array of dimension `[num_edges, 2]` - # containing mutation count and mutational target size per edge. - # :param ndarray constraints: array of dimension `[num_nodes, 2]` - # containing lower and upper bounds for each node. - # :param ndarray posterior: array of dimension `[num_nodes, 2]` - # containing natural parameters for each node - # :param EPFactors factors: object containing - # containing parent and child factors (natural parameters) for each edge - # :param bool unphased: if True, edges are treated as blocks of unphased - # singletons in contemporary individuals - - # TODO: scale should be 1.0, can we delete - # TODO: we don't seem to need to damp? - - # TODO: assert more stuff here? - assert mutations_phase.size == mutations_edge.size - assert mutations_posterior.shape == (mutations_phase.size, 2) - assert constraints.shape == posterior.shape - assert edges_child.size == edges_parent.size - assert likelihoods.shape == (edges_parent.size, 2) - - def leafward_projection(x, y, z): - if unphased: - return approx.mutation_sideways_projection(x, y, z) - return approx.mutation_leafward_projection(x, y, z) - - def rootward_projection(x, y, z): - if unphased: - return approx.mutation_sideways_projection(x, y, z) - return approx.mutation_rootward_projection(x, y, z) - - def gamma_projection(x, y, z): - if unphased: - return approx.mutation_unphased_projection(x, y, z) - return approx.mutation_gamma_projection(x, y, z) - - def fixed_projection(x, y): - if unphased: - return approx.mutation_block_projection(x, y) - return approx.mutation_edge_projection(x, y) - - twin_projection = approx.mutation_twin_projection - - fixed = constraints[:, LOWER] == constraints[:, UPPER] - - scale = factors.scale - factor = factors.block if unphased else factors.edge - assert factor.shape == (edges_parent.size, 2, 2) - - for m in mutations_order: - i = mutations_edge[m] - if i == tskit.NULL: # skip mutations above root - continue - p, c = edges_parent[i], edges_child[i] - if fixed[p] and fixed[c]: - child_age = constraints[c, 0] - parent_age = constraints[p, 0] - mutations_phase[m], mutations_posterior[m] = \ - fixed_projection(parent_age, child_age) # fmt: skip - elif fixed[p] and not fixed[c]: - child_message = factor[i, LEAFWARD] * scale[c] - child_delta = 1.0 # hopefully we don't need to damp - child_cavity = posterior[c] - child_delta * child_message - edge_likelihood = child_delta * likelihoods[i] - parent_age = constraints[p, LOWER] - mutations_phase[m], mutations_posterior[m] = leafward_projection( - parent_age, - child_cavity, - edge_likelihood, - ) - elif fixed[c] and not fixed[p]: - parent_message = factor[i, ROOTWARD] * scale[p] - parent_delta = 1.0 # hopefully we don't need to damp - parent_cavity = posterior[p] - parent_delta * parent_message - edge_likelihood = parent_delta * likelihoods[i] - child_age = constraints[c, LOWER] - mutations_phase[m], mutations_posterior[m] = rootward_projection( - child_age, - parent_cavity, - edge_likelihood, - ) - else: - if p == c: # singleton block with single parent - parent_message = factor[i, ROOTWARD] * scale[p] - parent_delta = 1.0 # hopefully we don't need to damp - parent_cavity = posterior[p] - parent_delta * parent_message - edge_likelihood = parent_delta * likelihoods[i] - child_age = constraints[c, LOWER] - mutations_phase[m], mutations_posterior[m] = \ - twin_projection(parent_cavity, edge_likelihood) # fmt: skip - else: - parent_message = factor[i, ROOTWARD] * scale[p] - child_message = factor[i, LEAFWARD] * scale[c] - parent_delta = 1.0 # hopefully we don't need to damp - child_delta = 1.0 # hopefully we don't need to damp - delta = min(parent_delta, child_delta) - parent_cavity = posterior[p] - delta * parent_message - child_cavity = posterior[c] - delta * child_message - edge_likelihood = delta * likelihoods[i] - mutations_phase[m], mutations_posterior[m] = gamma_projection( - parent_cavity, - child_cavity, - edge_likelihood, - ) - def iterate( self, *, @@ -705,14 +271,14 @@ def iterate( check_valid=False, # for debugging ): logger.debug("Passing through singleton blocks") - self.propagate_likelihood( + _tsdate.propagate_likelihood( self.block_order, self.block_nodes[ROOTWARD], self.block_nodes[LEAFWARD], self.block_likelihoods, self.node_constraints, self.node_posterior, - self.factors, + self.factors.arrays(), self.block_logconst, max_shape, min_step, @@ -720,14 +286,14 @@ def iterate( ) logger.debug("Rootward + leafward pass through edges") - self.propagate_likelihood( + _tsdate.propagate_likelihood( self.edge_order, self.edge_parents, self.edge_children, self.edge_likelihoods, self.node_constraints, self.node_posterior, - self.factors, + self.factors.arrays(), self.edge_logconst, max_shape, min_step, @@ -736,17 +302,17 @@ def iterate( if regularise: logger.debug("Exponential regularization on roots") - self.propagate_prior( + _tsdate.propagate_prior( self.unconstrained_roots, self.node_posterior, - self.factors, + self.factors.arrays(), max_shape, em_maxitt, em_reltol, ) logger.debug("Absorbing scaling term into the factors") - _rescale_factors(self.factors) + _tsdate.rescale_factors(self.factors.arrays()) if check_valid: # for debugging self._check_valid_state(self.node_posterior, self.factors) @@ -852,7 +418,7 @@ def infer( muts_timing = time.time() mutations_phased = self.mutation_blocks == tskit.NULL logger.debug("Passing through unphased singletons") - self.propagate_mutations( # unphased singletons + _tsdate.propagate_mutations( # unphased singletons self.mutation_order[~mutations_phased], self.mutation_posterior, self.mutation_phase, @@ -862,11 +428,11 @@ def infer( self.block_likelihoods, self.node_constraints, self.node_posterior, - self.factors, + self.factors.arrays(), USE_BLOCK_LIKELIHOOD, ) logger.debug("Passing through phased mutations") - self.propagate_mutations( # phased mutations + _tsdate.propagate_mutations( # phased mutations self.mutation_order[mutations_phased], self.mutation_posterior, self.mutation_phase, @@ -876,7 +442,7 @@ def infer( self.edge_likelihoods, self.node_constraints, self.node_posterior, - self.factors, + self.factors.arrays(), USE_EDGE_LIKELIHOOD, ) muts_timing -= time.time() From 845f3b9017374d7602f45010fab625de057093cb Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Tue, 24 Nov 2026 22:03:47 -0800 Subject: [PATCH 12/56] Trim test scaffolding - The multi-sweep test of the EP passes now requires the C implementation to match the oracle exactly: it does, on every sweep. The relative tolerances that allowed for last-bit differences between numba and the oracle are gone, and with them evaluation/ep_sensitivity.py, which measured how such differences grow over sweeps. - test_oracle_helpers.py keeps only the tests that show the comparison helpers detect disagreements (values, NaN and infinity patterns, exceptions, in-place updates, library error mapping). - test_python_c_approx.py: drop the test of the test adapter for projections. - test_python_c_scalar.py: gammainc_inv is SciPy's function called through its C API, so a few values (including outside the domain) replace the grid and random draws. - Remove tests/distribution_functions.py: nothing imports it, and it calls functions that no longer exist. --- evaluation/README.md | 16 - evaluation/ep_sensitivity.py | 84 ----- tests/distribution_functions.py | 506 ------------------------------- tests/test_oracle_helpers.py | 376 ++++------------------- tests/test_oracle_variational.py | 30 +- tests/test_python_c_approx.py | 18 +- tests/test_python_c_scalar.py | 72 ++--- 7 files changed, 91 insertions(+), 1011 deletions(-) delete mode 100644 evaluation/ep_sensitivity.py delete mode 100644 tests/distribution_functions.py diff --git a/evaluation/README.md b/evaluation/README.md index e9b02918..8176c391 100644 --- a/evaluation/README.md +++ b/evaluation/README.md @@ -17,7 +17,6 @@ standard coalescent. | `performance.py` | Wall time and peak RSS, each case in a fresh process. | | `microbench.py` | Microbenchmarks of the array-level accelerated functions (EP passes, rescaling, phasing, `util`, `prior`), on simulated inputs at three sizes (see below). | | `numerical_accuracy.py` | Accuracy of the special functions and gamma approximations (the scalar functions of `_tsdate`) per function and regime: worst error against mpmath, SciPy or closed forms, and violations of properties such as symmetry, monotonicity and continuity at switch points (see below). Not to be confused with `accuracy.py`, which scores dating. | -| `ep_sensitivity.py` | How a one-ulp change in the edge mutational targets grows over EP sweeps (maximum relative change in node means), which sets the tolerance of the multi-sweep test in `tests/test_oracle_variational.py` (see below). | | `compare.py` | Compares two `performance.py` CSVs case by case (see below). | | `plot.py` | Reads `results/*.csv` and writes PNGs: error/bias/interval coverage vs parameter (`accuracy_*_summary.png`: top row node times, bottom row mutation times), estimated-vs-true scatter (`accuracy_*_scatter.png`: columns are swept values, rows are node/mutation times for true/tsinferred topology), PIT calibration histograms (`accuracy_*_calibration.png`: node row, mutation row), AFS observed-vs-expected (`afs_*.png`), time and memory scaling. | | `validation.py` | Stub: numerical checks too slow for the unit tests (issue #384). | @@ -103,21 +102,6 @@ Implementations are chosen with `--impl`. To add one, write a function returning dict of callables with the same names and signatures as `_c_impl` and register it in `IMPLS`. -### Sensitivity of EP to last-bit differences - -`ep_sensitivity.py` perturbs the mutational target of every edge by one ulp and reports -how far the node means move over successive EP sweeps (maximum relative change after -selected sweeps, using tsdate's own `ExpectationPropagation`). This is the noise that an -implementation with differently rounded intermediates has to live with, and the reason -the multi-sweep comparison in `tests/test_oracle_variational.py` uses relative -tolerances (1e-4 after the first sweep, 1e-6 later) instead of an ulp bound. Typical -values: about 1e-6 to 1e-7 after one sweep, 1e-8 to 1e-9 after ten. - -``` -python evaluation/ep_sensitivity.py --quick -python evaluation/ep_sensitivity.py --sizes 20 100 --seeds 1 2 3 --sweeps 1 5 10 -``` - ### Accuracy of the special functions `numerical_accuracy.py` measures the approximation error of the special functions in diff --git a/evaluation/ep_sensitivity.py b/evaluation/ep_sensitivity.py deleted file mode 100644 index ed85ce37..00000000 --- a/evaluation/ep_sensitivity.py +++ /dev/null @@ -1,84 +0,0 @@ -""" -How much do whole EP sweeps amplify last-bit differences? - -The mutational target of every edge (the input of the likelihood pass) is perturbed -by one ulp, and the trajectory of node means is compared with the unperturbed run, -using tsdate's production `ExpectationPropagation`. This is the noise level that a -reimplementation with differently rounded intermediates has to live with, and the -reason that multi-sweep comparisons in `tests/test_oracle_variational.py` use -relative tolerances (1e-4 after the first sweep, 1e-6 later) and not ulps. - -Prints, for each tree sequence, the maximum relative change in node means after -selected sweeps, and whether the pattern of skipped updates (NaN edge log-normalising -constants) changes. - -Example: - python evaluation/ep_sensitivity.py --quick - python evaluation/ep_sensitivity.py --sizes 20 100 --seeds 1 2 3 --sweeps 1 5 10 -""" - -import argparse - -import common -import numpy as np - -from tsdate.variational import ExpectationPropagation - - -def node_means(posterior): - """Means of the gamma distributions with natural parameters `posterior`""" - with np.errstate(all="ignore"): - return (posterior[:, 0] + 1) / posterior[:, 1] - - -def run_pair(ts, mutation_rate, num_sweeps, max_shape, min_step): - """ - Run EP with and without the perturbation; yield, after each sweep, the maximum - relative difference in node means and whether the skipped updates differ. - """ - eps = [] - for perturb in (False, True): - ep = ExpectationPropagation(ts, mutation_rate=mutation_rate) - if perturb: - target = ep.edge_likelihoods[:, 1] - ep.edge_likelihoods[:, 1] = np.nextafter(target, np.inf) - eps.append(ep) - for _ in range(num_sweeps): - for ep in eps: - ep.iterate(max_shape=max_shape, min_step=min_step) - base, perturbed = (node_means(ep.node_posterior) for ep in eps) - ok = np.isfinite(base) & np.isfinite(perturbed) - change = np.abs(perturbed[ok] - base[ok]) / np.abs(base[ok]) - skipped = [np.isnan(ep.edge_logconst) for ep in eps] - yield float(change.max(initial=0.0)), not np.array_equal(*skipped) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - parser.add_argument("--sizes", type=int, nargs="+", default=[20, 100]) - parser.add_argument("--length", type=float, default=2e5) - parser.add_argument("--seeds", type=int, nargs="+", default=[1, 2, 3]) - parser.add_argument("--sweeps", type=int, nargs="+", default=[1, 2, 5, 10]) - parser.add_argument("--mutation-rate", type=float, default=1e-8) - parser.add_argument("--max-shape", type=float, default=1000.0) - parser.add_argument("--min-step", type=float, default=0.1) - parser.add_argument("--quick", action="store_true", help="one small simulation") - args = parser.parse_args() - if args.quick: - args.sizes, args.seeds, args.sweeps, args.length = [10], [1], [1, 3], 1e5 - header = "".join(f"{f'sweep {s}':>12}" for s in args.sweeps) - print(f"{'samples':>8}{'seed':>6}{header} skipped-pattern-changed") - for n in args.sizes: - for seed in args.seeds: - ts = common.simulate(n, args.length, args.mutation_rate, seed) - runs = run_pair( - ts, args.mutation_rate, max(args.sweeps), args.max_shape, args.min_step - ) - results = list(runs) - row = "".join(f"{results[s - 1][0]:12.2e}" for s in args.sweeps) - changed = any(r[1] for r in results) - print(f"{n:>8}{seed:>6}{row} {changed}") - - -if __name__ == "__main__": - main() diff --git a/tests/distribution_functions.py b/tests/distribution_functions.py deleted file mode 100644 index 6eb2d567..00000000 --- a/tests/distribution_functions.py +++ /dev/null @@ -1,506 +0,0 @@ -# MIT License -# -# Copyright (C) 2023 Tskit Developers -# Copyright (C) 2023 University of Oxford -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -""" -Utility functions to construct distributions used in variational inference, -for testing purposes -""" - -import mpmath -import numpy as np -import scipy.integrate -import scipy.special - -from tsdate import approx, hypergeo - - -def kl_divergence(p, logq): - """ - KL(p||q) divergence for fixed p - """ - val, _ = scipy.integrate.quad(lambda x: -p(x) * logq(x), 0, np.inf) - return val - - -def conditional_coalescent_pdf(t, n, k): - """ - Evaluate the PDF of the conditional coalescent, using results from Wiuf and - Donnelly (1999). - """ - - def pr_t_bar_a(t, a, n): - """ - Phase-type distribution for sum of waiting times during which - there are n, n-1, ..., a+1 ancestors. - """ - lineages = np.arange(n, a, -1) - rate = (lineages * (lineages - 1)) / 2 - weight = [] - for i in range(len(rate)): - weight.append(1) - for j in range(len(rate)): - if i != j: - weight[-1] *= rate[j] / (rate[j] - rate[i]) - weight = np.array(weight) - val = np.sum(weight * rate * np.exp(-rate * t)) - return val - - def pr_a(a, n, k): - """ - Hypergeometric-ish distribution for number of ancestors "a" after - subsample of size "k" has coalesced in tree of size "n" - """ - return np.exp( - np.log(n + 1) - + scipy.special.betaln(n - k, k + 2) - - np.log(n - a) - - scipy.special.betaln(n - a - k + 2, k - 1) - - np.log(a + 1) - - scipy.special.betaln(a - 1, 3) - ) - - if n == k: - return pr_t_bar_a(t, 1) - else: - return np.sum([pr_a(a, n, k) * pr_t_bar_a(t, a, n) for a in range(2, n - k + 2)]) - - -class TiltedGammaDiff: - r""" - The distribution of the difference of two gamma RVs restricted to the - positive reals, tilted by an exponential function. - - Specifically, for p(x; a, b) = b^a/Gamma(a) x^{a-1} e^{-xb}, this is - - p(u; a1, a2, a3, b1, b2, b3) \propto p(u, a3, b3) \times - \int_u^inf p(x; a1, b1) p(x - u; a2, b2) dx, u \geq 0 - """ - - @staticmethod - def _2F1(a, b, c, z): - """ - log of |Re| for Gaussian hypergeometric function - """ - val = mpmath.log(mpmath.hyp2f1(a, b, c, z)) - return float(val) - - @staticmethod - def _U(a, b, z): - """ - log of |Re| for confluent hypergeometric function of the second kind - """ - val = mpmath.log(mpmath.hyperu(a, b, z)) - return float(val) - - def __init__(self, shape1, shape2, shape3, rate1, rate2, rate3, reorder=True): - assert shape1 > 0 - assert shape2 > 0 - assert shape3 > 0 - assert rate1 >= 0 - assert rate2 > 0 - assert rate3 >= 0 - # for convergence of 2F1, we need rate2 > rate3. Invariant - # transformations of 2F1 allow us to switch arguments, with - # appropriate rescaling - self.reparametrize = rate3 > rate2 - self.shape1 = shape1 - self.shape2 = shape2 - self.shape3 = shape3 - self.rate1 = rate1 - self.rate2 = rate2 - self.rate3 = rate3 - mu = (1.0 - shape1 - shape2) / 2 - nu = (shape3 - 1) + (shape1 + shape2) / 2 - zeta = 1 / 2 - (rate2 - rate3) / (rate1 + rate2) - assert zeta > -1 / 2, "Invalid parameters" - assert nu + 1 / 2 > abs(mu), "Invalid parameters" - - def pdf(self, x): - r""" - Probability density function, derived using equation 3.383.4 from - Gradshteyn & Ryzhik (2000) "Table of Integrals, Series, and Products" - - That is: - - u^{a3 - 1} e^{(b2 - b3) u} \times - \int_u^inf x^{a1-1} (x-u)^{a2-1} e^{-x(b1+b2)} dx = - u^{a3 - 1} e^{(b2 - b3) u} (b1+b2)^{-(a1+a2)/2} Gamma(a2) \times - u^{(a1+a2)/2-1} e^{-(b1+b2)/2 u} W((a1-a2)/2, (1-a1-a2)/2, (b1+b2)u) = - (b1+b2)^{-(a1+a2)/2} Gamma(a2) u^{a3 + (a1+a2)/2 - 2} \times - e^{-u(b1+b2)(1/2+(b3 - b2)/(b1 + b2))} \times - W((a1-a2)/2, (1-a1-a2)/2, (b1+b2)u) - - s.t. a2 > 0, (b1+b2)u > 0 - - Change variables, t = (b1+b2)*u and integrate t using 13.23.4 of DLMF, - to find the normalizing constant: - - (b1+b2)^{-(a1+a2)/2} Gamma(a2) (b1+b2)^{-a3-(a1+a2)/2+2} \times - \int_0^inf t^{a3+(a1+a2)/2-2} e^{-t (1/2+(b3-b2)/(b1+b2))} \times - W((a1-a2)/2, (1-a1-a2)/2, t) 1/(b1+b2) dt = - (b1+b2)^{-a1-a2-a3+1} Gamma(a1+a2+a3-1) Beta(a2,a3) \times - 2F1(a1+a2+a3-1, a3, a3+a2, (b2-b3)/(b1+b2)) - - Note that 2F1 is regularized in this equation, e.g. 2F1(a,b;c;z) = - 2F1(a,b;c;z)/Gamma(c) - - Transform W to U, and use Kummer's transformations: - - W((a1-a2)/2, (1-a1-a2)/2, (b1+b2)u) = - exp(-u(b1+b2)/2) (b1+b2)^(1-a1/2-a2/2) \times - u^(1-a1/2-a2/2) U(1-a1, 2-a1-a2, (b1+b2)u) = - exp(-u(b1+b2)/2) (b1+b2)^(a1/2+a2/2) \times - u^(a1/2+a2/2) U(a2, a1+a2, (b1+b2)u) - - so that the kernel becomes, - - Gamma(a2) u^(a3 + a1 + a2 - 2) \times - e^(-u(b1+b3)) U(a2, a1+a2, (b1+b2)u) - - In the special case where b1 == b3 == 0 and a1 == a3 == 1, the integral - becomes (via 3.382.2 GR2000): - - e^{u b2} \int_u^inf (x-u)^{a2-1} e^{-x b2} dx = Gamma(a2) b2^{-a2} - - e.g. a constant (this should never happen if the edge update order is - correct and samples are fixed to the present day, or if a proper prior - is used) - """ - assert x >= 0.0, "PDF is only defined for non-negative reals" - A = self.shape1 + self.shape2 + self.shape3 - 1 - B = self.shape3 - C = self.shape2 + self.shape3 - S = self.rate2 - self.rate3 - T = self.rate2 + self.rate1 - if self.reparametrize: - val = ( - scipy.stats.gamma.logpdf(x, A, scale=1 / (self.rate1 + self.rate3)) - + self._U( - self.shape2, - self.shape1 + self.shape2, - (self.rate1 + self.rate2) * x, - ) - + scipy.special.loggamma(self.shape2 + self.shape3) - - scipy.special.loggamma(self.shape3) - - self._2F1(A, C - B, C, S / (S - T)) - ) - else: - val = ( - scipy.stats.gamma.logpdf(x, A, scale=1 / (self.rate1 + self.rate3)) - + self._U( - self.shape2, - self.shape1 + self.shape2, - (self.rate1 + self.rate2) * x, - ) - + scipy.special.loggamma(self.shape2 + self.shape3) - - scipy.special.loggamma(self.shape3) - + A * np.log(T / (T - S)) - - self._2F1(A, B, C, S / T) - ) - return np.exp(val) - - def moments(self): - r""" - Returns the first two raw moments. - - Derived from differentiating the Laplace transform, and using the relation - - d^n 2F1(A, B, C, z) / dz^n = a_n b_n / c_n 2F1(A + 1, B + 1, C + 1, z) - - where x_n = x (x + 1) \dots (x + n - 1) is the rising factorial and 2F1 is the - Gaussian hypergeometric function. See 15.5.2 in DLMF. - """ - A = self.shape1 + self.shape2 + self.shape3 - 1 - B = self.shape3 - C = self.shape2 + self.shape3 - S = self.rate2 - self.rate3 - T = self.rate1 + self.rate2 - numer = 0 - denom = 0 - moments = [] - if self.reparametrize: - F0 = self._2F1(A, C - B, C, S / (S - T)) - A * np.log(1 - S / T) - for i in range(2): - numer += np.log(A + i) + np.log(B + i) - np.log(C + i) - np.log(T) - denom = ( - F0 - - self._2F1(A + i + 1, C - B, C + i + 1, S / (S - T)) - + (A + i + 1) * np.log(1 - S / T) - ) - moments.append(np.exp(numer - denom)) - else: - F0 = self._2F1(A, B, C, S / T) - for i in range(2): - numer += np.log(A + i) + np.log(B + i) - np.log(C + i) - np.log(T) - denom = F0 - self._2F1(A + i + 1, B + i + 1, C + i + 1, S / T) - moments.append(np.exp(numer - denom)) - return moments[0], moments[1] - - def sufficient_statistics(self): - r""" - Return E[x], E[x^2], and E[log x]. - - To get raw moments use the Laplace transform E[e^{-su}]: - - (b1+b2)^{-a1-a2-a3+1} Gamma(a1+a2+a3-1) Beta(a2,a3) \times - 2F1(a1+a2+a3-1, a3, a3+a2, (b2-b3-s)/(b1+b2)) - - To get log moments use the Mellin transform E[u^s]: - - (b1+b2)^{-a1-a2-a3-s+1} Gamma(a1+a2+a3+s-1) Beta(a2,a3+s) \times - 2F1(a1+a2+a3+s-1, a3+s, a3+s+a2, (b2-b3)/(b1+b2)) - - In both cases: differentiate wrt s, evaluate at zero, and normalize - """ - A = self.shape1 + self.shape2 + self.shape3 - 1 - B = self.shape3 - C = self.shape2 + self.shape3 - S = self.rate2 - self.rate3 - T = self.rate1 + self.rate2 - if self.reparametrize: - # underflow protection is used, so the actual derivatives are - # np.exp(F) * dF_dz, etc. - F, dF_da, _, dF_dc, dF_dz, d2F_dz2 = hypergeo._hyp2f1_series( - A, - C - B, - C, - S / (S - T), - ) - logconst = ( - F - + scipy.special.betaln(self.shape2, self.shape3) - + scipy.special.loggamma(A) - - A * np.log(T - S) - ) - x = -dF_dz * T / (S - T) ** 2 - A / (S - T) - xsq = ( - d2F_dz2 * T**2 / (S - T) ** 4 - + A * (A + 1) / (T - S) ** 2 - + 2 * dF_dz * (1 + A) * T / (S - T) ** (3) - ) - logx = ( - (dF_da + dF_dc) - + -np.log(1 - S / T) - + scipy.special.digamma(A) - + scipy.special.digamma(B) - - scipy.special.digamma(C) - - np.log(T) - ) - else: - F, dF_da, dF_db, dF_dc, dF_dz, d2F_dz2 = hypergeo._hyp2f1_series( - A, - B, - C, - S / T, - ) - logconst = ( - F - + scipy.special.betaln(self.shape2, self.shape3) - + scipy.special.loggamma(A) - - A * np.log(T) - ) - x = dF_dz / T - xsq = d2F_dz2 / T**2 - logx = ( - (dF_da + dF_db + dF_dc) - + scipy.special.digamma(A) - + scipy.special.digamma(B) - - scipy.special.digamma(C) - - np.log(T) - ) - return logconst, x, xsq, logx - - def to_gamma(self, minimize_kl=True): - """ - Return the shape and rate parameters of a gamma distribution with the - same expected sufficient statistics (if ``minimize_kl`` is ``True``), and - otherwise one with the same mean and variance. - """ - logconst, x, xsq, logx = self.sufficient_statistics() - if minimize_kl: - _, xlogx, _ = approx.approximate_log_moments(x, xsq) - alpha, beta = approx.approximate_gamma_kl(x, logx, xlogx) - else: - alpha, beta = approx.approximate_gamma_mom(x, xsq) - return logconst, alpha, beta - - -class TiltedGammaSum: - r""" - The distribution of the sum of two gamma RVs, tilted by an exponential function. - - Specifically, for p(x; a, b) = b^a/Gamma(a) x^{a-1} e^{-xb}, this is - - p(u; a1, a2, a3, b1, b2, b3) \propto p(u; a3, b3) \times - \int_0^u p(x; a1, b1) p(u - x; a2, b2) dx, u \geq 0 - """ - - @staticmethod - def _2F1(a, b, c, z): - """ - log of |Re| for Gaussian hypergeometric function - """ - val = mpmath.log(mpmath.hyp2f1(a, b, c, z)) - return float(val) - - @staticmethod - def _M(a, b, x): - """ - log of |Re| for confluent hypergeometric function (aka 1F1) - """ - val = mpmath.log(mpmath.hyp1f1(a, b, x)) - return float(val) - - def __init__(self, shape1, shape2, shape3, rate1, rate2, rate3): - assert shape1 > 0 - assert shape2 > 0 - assert shape3 > 0 - assert rate1 >= 0 - assert rate2 > 0 - assert rate3 >= 0 - # for numeric stability of hypergeometric we need rate2 > rate1 - # as this is a convolution, the order of (1) and (2) don't matter - self.reparametrize = rate1 > rate2 - self.shape1 = shape2 if self.reparametrize else shape1 - self.shape2 = shape1 if self.reparametrize else shape2 - self.shape3 = shape3 - self.rate1 = rate2 if self.reparametrize else rate1 - self.rate2 = rate1 if self.reparametrize else rate2 - self.rate3 = rate3 - assert shape1 + shape2 + shape3 - 1 > 0, "Invalid parameters" - assert rate3 + rate2 > max(0, rate2 - rate1), "Invalid parameters" - - def pdf(self, x): - r""" - Probability density function, derived using equation 3.383.1 from - Gradshteyn & Ryzhik (2000) "Table of Integrals, Series, and Products" - - u^{a3-1} e^{-u b3} \times - \int_0^u x^{a1-1} (u-x)^{a2-1} e^{-x b1} e^{-(u-x) b2} dx = - u^{a3-1} e^{-u (b2 + b3)} \times - \int_0^u x^{a1-1} (u-x)^{a2-1} e^{x (b2-b1)} dx = - Beta(a2, a1) u^{a1 + a2 + a3 - 2} e^{-u (b2+b3)} M(a1, a1+a2, (b2-b1) u) - - s.t. a1 > 0, a2 > 0 - - Then integrate u using 13.10.3 of DLMF -- note that this equation is - regularized, so that we have M(a,c,kt)/Gamma(c) and - 2F1(a,b;c;z)/Gamma(c) - - \int_0^\infty e^{-u (b2+b3)} u^{a1+a2+a3-2} M(a1, a1+a2, (b2-b1) u) du = - Gamma(a1+a2+a3-1) (b2+b3)^{-a1-a2-a3+1} \times - 2F1(a1, a1+a2+a3-1, a1+a2, (b2-b1)/(b2+b3)) - - s.t. a1+a2 > 1 - s.t. b2 > max(b2-b1, 0) - - In the special case where b1 == b3 == 0 and a1 == a3 == 1, the integrals - become (via 3.382.1 in GR2000): - - e^{-u b2} \int_0^u (u-x)^{a2-1} e^{x b2} dx = b2^(-a2) gamma(a2, b2 u) - - which is improper (this special case should never happen if edge order - is correct or priors are proper) - """ - assert x >= 0.0, "PDF is only defined for non-negative reals" - A = self.shape1 - B = self.shape1 + self.shape2 + self.shape3 - 1 - C = self.shape1 + self.shape2 - T = self.rate2 - self.rate1 - S = self.rate2 + self.rate3 - val = ( - scipy.stats.gamma.logpdf(x, B, scale=1 / S) - + self._M(self.shape1, self.shape1 + self.shape2, T * x) - - self._2F1(A, B, C, T / S) - ) - return np.exp(val) - - def moments(self): - r""" - First two raw moments, from differentiating the Laplace transform - """ - A = self.shape1 - B = self.shape1 + self.shape2 + self.shape3 - 1 - C = self.shape1 + self.shape2 - T = self.rate2 - self.rate1 - S = self.rate2 + self.rate3 - F0 = self._2F1(A, B, C, T / S) - Z1 = np.log(A) + np.log(B) - np.log(C) - F1 = self._2F1(A + 1, B + 1, C + 1, T / S) - Z2 = Z1 + np.log(A + 1) + np.log(B + 1) - np.log(C + 1) - F2 = self._2F1(A + 2, B + 2, C + 2, T / S) - x = np.exp(F1 - F0 + Z1) * T / S**2 + B / S - xsq = ( - B * (B + 1) / S**2 - + 2 * (B + 1) * T / S**3 * np.exp(Z1 + F1 - F0) - + T**2 / S**4 * np.exp(Z2 + F2 - F0) - ) - return x, xsq - - def sufficient_statistics(self): - r""" - Return E[x], E[x^2], and E[log x]. - - To get raw moments use the Laplace transform E[e^{-su}]: - - Gamma(a1+a2+a3-1) (b2+b3+s)^{-a1-a2-a3+1} \times - 2F1(a1, a1+a2+a3-1, a1+a2, (b2-b1)/(b2+b3+s)) - - To get log moments use the Mellin transform E[u^s]: - - Gamma(a1+a2+a3+s-1) (b2+b3)^{-a1-a2-a3+s+1} \times - 2F1(a1, a1+a2+a3+s-1, a1+a2, (b2-b1)/(b2+b3)) - - In both cases: differentiate wrt s, evaluate at zero, and normalize - """ - A = self.shape1 - B = self.shape1 + self.shape2 + self.shape3 - 1 - C = self.shape1 + self.shape2 - T = self.rate2 - self.rate1 - S = self.rate2 + self.rate3 - # underflow protection is used, so the actual derivatives are - # np.exp(F) * dF_dz, etc. - F, _, dF_db, _, dF_dz, d2F_dz2 = hypergeo._hyp2f1_series(A, B, C, T / S) - logconst = ( - F - + scipy.special.loggamma(B) - - B * np.log(S) - + scipy.special.betaln(self.shape1, self.shape2) - ) - x = dF_dz * T / S**2 + B / S - xsq = d2F_dz2 * T**2 / S**4 + B * (B + 1) / S**2 + 2 * dF_dz * (1 + B) * T / S**3 - logx = dF_db + scipy.special.digamma(B) - np.log(S) - return logconst, x, xsq, logx - - def to_gamma(self, minimize_kl=True): - """ - Return the shape and rate parameters of a gamma distribution with the - same expected sufficient statistics (if ``minimize_kl`` is ``True``), and - otherwise one with the same mean and variance. - """ - logconst, x, xsq, logx = self.sufficient_statistics() - if minimize_kl: - _, xlogx, _ = approx.approximate_log_moments(x, xsq) - alpha, beta = approx.approximate_gamma_kl(x, logx, xlogx) - else: - alpha, beta = approx.approximate_gamma_mom(x, xsq) - return logconst, alpha, beta diff --git a/tests/test_oracle_helpers.py b/tests/test_oracle_helpers.py index aa6ff0ac..f1d47a11 100644 --- a/tests/test_oracle_helpers.py +++ b/tests/test_oracle_helpers.py @@ -1,4 +1,7 @@ -"""Tests of the comparison helpers in ``tests/oracle/helpers.py``.""" +""" +The comparison helpers in ``tests/oracle/helpers.py`` detect disagreements: a helper +that passed everything would make every parity test vacuous. +""" import _tsdate import numpy as np @@ -6,202 +9,115 @@ from oracle.helpers import ( INF, NAN, - Outcome, - assert_inplace_close, assert_outcome, assert_same_outcome, assert_ulp_close, - both, - call, compare, errors_match, - expected_error, - kind, outcome, ) +KLFailed = type("KLMinimizationFailedError", (Exception,), {}) + -def one_ulp_up(x, n=1): +def ulps_up(x, n): for _ in range(n): x = np.nextafter(x, np.inf) return x -class TestAssertUlpClose: - @pytest.mark.parametrize( - ("actual", "desired"), - [ - pytest.param(1.5, 1.5, id="scalar"), - pytest.param(1.0, one_ulp_up(1.0), id="one_ulp"), - pytest.param(one_ulp_up(1.0, 4), 1.0, id="four_ulp"), - pytest.param(np.array([1.0, NAN]), np.array([1.0, NAN]), id="nan"), - pytest.param(INF, INF, id="inf"), - pytest.param(-INF, -INF, id="minus_inf"), - pytest.param( - (1.0, np.arange(2.0), (np.zeros(1), NAN)), - (1.0, np.arange(2.0), (np.zeros(1), NAN)), - id="nested", - ), - ], - ) - def test_passes(self, actual, desired): - assert_ulp_close(actual, desired) +def returns(value, modify=None): + def func(x): + if modify is not None: + x[0] = modify + return value + return func + + +def raises(exception): + def func(x): + raise exception + + return func + + +class TestAssertUlpClose: @pytest.mark.parametrize( ("actual", "desired", "match"), [ - pytest.param(one_ulp_up(1.0, 5), 1.0, "ulp", id="five_ulp"), + pytest.param(ulps_up(1.0, 5), 1.0, "ulp", id="five_ulp"), pytest.param( np.array([1.0, NAN]), np.array([NAN, 1.0]), "NaN", id="nan_place" ), pytest.param(1.0, NAN, "NaN", id="nan_vs_number"), pytest.param(INF, -INF, "infinity", id="inf_sign"), - pytest.param(INF, 1e308, "infinity", id="inf_vs_huge"), pytest.param((1.0, 2.0), (1.0, 2.0, 3.0), "structure", id="structure"), pytest.param(np.zeros(3), np.zeros(4), "shape", id="shape"), - pytest.param(np.zeros((2, 2)), np.zeros(4), "shape", id="ndim"), - pytest.param( - (1.0, np.array([1.0, 2.0])), - (1.0, np.array([1.0, 2.5])), - r"\[1\]", - id="path", - ), ], ) def test_fails(self, actual, desired, match): with pytest.raises(AssertionError, match=match): assert_ulp_close(actual, desired) - def test_maxulp(self): - x = one_ulp_up(1.0, 10) - with pytest.raises(AssertionError, match="ulp"): - assert_ulp_close(x, 1.0, maxulp=4) - assert_ulp_close(x, 1.0, maxulp=10) - -class TestAssertInplaceClose: - def test_agree(self): - assert_inplace_close((np.ones(3), 2.0), (np.ones(3), 2.0)) - - def test_differ(self): - b = np.ones(3) - b[1] = 2.0 - with pytest.raises(AssertionError, match="argument 0"): - assert_inplace_close((np.ones(3), 2.0), (b, 2.0)) - - -class TestOutcome: - def test_return_value(self): - result = outcome(lambda x: x + 1, 1.0) - assert result.value == 2.0 - assert result.exception is None - assert result.error is None - - def test_exception(self): - def fail(): - raise ValueError("bad") - - result = outcome(fail) - assert result.value is None - assert result.error is ValueError - assert str(result.exception) == "bad" - - def test_arrays_are_copied(self): - def modify(x): - x[0] = 5.0 +class TestAssertSameOutcome: + @pytest.mark.parametrize( + ("impl", "oracle", "match"), + [ + pytest.param(returns(1.0), returns(2.0), "ulp", id="value"), + pytest.param( + raises(ValueError("a")), returns(1.0), "implementation", id="impl_raises" + ), + pytest.param( + returns(1.0), raises(ValueError("a")), "oracle", id="oracle_raises" + ), + pytest.param( + raises(KeyError("a")), + raises(ValueError("a")), + "implementation", + id="type", + ), + pytest.param( + raises(ValueError("a")), + raises(ValueError("b")), + "implementation", + id="message", + ), + pytest.param( + returns(1.0, modify=1.0), + returns(1.0, modify=2.0), + "argument 0", + id="inplace", + ), + ], + ) + def test_fails(self, impl, oracle, match): + x = np.zeros(2) + with pytest.raises(AssertionError, match=match): + assert_same_outcome(outcome(impl, x), outcome(oracle, x)) + def test_compare_copies_arguments(self): x = np.zeros(2) - result = outcome(modify, x) + compare(returns(1.0, modify=3.0), returns(1.0, modify=3.0), x) assert x[0] == 0.0 - assert result.args[0][0] == 5.0 - - def test_numpy_scalar_becomes_float(self): - result = outcome(lambda x: type(x), np.float64(1.0)) - assert result.value is float - - def test_warnings_are_suppressed(self): - with np.errstate(all="raise"): - result = outcome(lambda: np.float64(1.0) / np.zeros(1)) - assert result.exception is None - - def test_keyword_arguments(self): - assert outcome(lambda x, y=0: x + y, 1, y=2).value == 3 - -class TestCall: - def test_plain_function(self): - assert call(lambda x: x + 1, 1) == 2 - - def test_ctypes_interface(self): - class CFunc: - ctypes = staticmethod(lambda x: x * 2) - - assert call(CFunc(), 2) == 4 - - -class TestErrorsMatch: - def test_same_type_and_message(self): - assert errors_match(ValueError("a"), ValueError("a")) - - def test_subclass_accepted(self): - assert errors_match(FloatingPointError("a"), ArithmeticError("a")) - - def test_type_mismatch(self): - assert not errors_match(KeyError("a"), ValueError("a")) - - def test_message_mismatch(self): - assert not errors_match(ValueError("a"), ValueError("b")) - assert errors_match(ValueError("a"), ValueError("b"), check_message=False) - - def test_zero_division_message_ignored(self): - actual = ZeroDivisionError("division by zero") - assert errors_match(actual, ZeroDivisionError("float division by zero")) - - def test_expected_error(self): - assert ValueError in expected_error(ValueError) - - -KLFailed = type("KLMinimizationFailedError", (Exception,), {}) + def test_wrong_kind(self): + with pytest.raises(AssertionError): + assert_outcome(returns(1.0), returns(1.0), (np.zeros(1),), "nan") class TestLibraryError: """ - The C library reports numba's ZeroDivisionError, AssertionError, + The C library reports the oracle's ZeroDivisionError, AssertionError, KLMinimizationFailedError and ValueError as ``_tsdate.LibraryError``; messages are compared only for the last two. """ - @pytest.mark.parametrize( - "exc_type", [ZeroDivisionError, AssertionError, ValueError, KLFailed] - ) - def test_expected_error_includes_library_error(self, exc_type): - assert exc_type in expected_error(exc_type) - assert _tsdate.LibraryError in expected_error(exc_type) - - def test_expected_error_other_types(self): - assert expected_error(KeyError) == (KeyError,) - - def test_assertion_error_accepts_shape_check_value_error(self): - assert ValueError in expected_error(AssertionError) - assert ValueError not in expected_error(ZeroDivisionError) - - @pytest.mark.parametrize( - "oracle_exc", - [ZeroDivisionError("float division by zero"), AssertionError("Root")], - ) - def test_messages_ignored(self, oracle_exc): - assert errors_match(_tsdate.LibraryError("other message"), oracle_exc) - - def test_assertion_error_matches_shape_check_value_error(self): - assert errors_match(ValueError("bad shape"), AssertionError()) - @pytest.mark.parametrize("oracle_type", [ValueError, KLFailed]) def test_messages_compared(self, oracle_type): assert errors_match(_tsdate.LibraryError("a"), oracle_type("a")) assert not errors_match(_tsdate.LibraryError("b"), oracle_type("a")) - assert errors_match( - _tsdate.LibraryError("b"), oracle_type("a"), check_message=False - ) @pytest.mark.parametrize("oracle_exc", [KeyError("a"), IndexError("a")], ids=type) def test_other_oracle_errors_rejected(self, oracle_exc): @@ -209,165 +125,3 @@ def test_other_oracle_errors_rejected(self, oracle_exc): def test_value_error_rejected_for_zero_division(self): assert not errors_match(ValueError("a"), ZeroDivisionError("a")) - - def test_assertion_error_still_compared_with_assertion_error(self): - assert errors_match(AssertionError("a"), AssertionError("a")) - assert not errors_match(AssertionError("b"), AssertionError("a")) - - -def returns(value, modify=None): - def func(x): - if modify is not None: - x[0] = modify - return value - - return func - - -def raises(exception): - def func(x): - raise exception - - return func - - -class TestAssertSameOutcome: - def test_agree(self): - x = np.zeros(2) - a = outcome(returns(np.ones(2)), x) - b = outcome(returns(np.ones(2)), x) - assert_same_outcome(a, b) - - def test_value_mismatch(self): - x = np.zeros(2) - a = outcome(returns(np.ones(2)), x) - b = outcome(returns(np.full(2, 2.0)), x) - with pytest.raises(AssertionError, match="ulp"): - assert_same_outcome(a, b) - - def test_implementation_raises(self): - x = np.zeros(2) - a = outcome(raises(ValueError("a")), x) - b = outcome(returns(1.0), x) - with pytest.raises(AssertionError, match="implementation raised"): - assert_same_outcome(a, b) - - def test_oracle_raises(self): - x = np.zeros(2) - a = outcome(returns(1.0), x) - b = outcome(raises(ValueError("a")), x) - with pytest.raises(AssertionError, match="oracle raised"): - assert_same_outcome(a, b) - - def test_exceptions_agree(self): - x = np.zeros(2) - a = outcome(raises(ValueError("a")), x) - b = outcome(raises(ValueError("a")), x) - assert_same_outcome(a, b) - - def test_exception_type_mismatch(self): - x = np.zeros(2) - a = outcome(raises(KeyError("a")), x) - b = outcome(raises(ValueError("a")), x) - with pytest.raises(AssertionError, match="implementation raised"): - assert_same_outcome(a, b) - - def test_exception_message_mismatch(self): - x = np.zeros(2) - a = outcome(raises(ValueError("a")), x) - b = outcome(raises(ValueError("b")), x) - with pytest.raises(AssertionError, match="implementation raised"): - assert_same_outcome(a, b) - assert_same_outcome(a, b, check_message=False) - - def test_inplace_mismatch(self): - x = np.zeros(2) - a = outcome(returns(1.0, modify=1.0), x) - b = outcome(returns(1.0, modify=2.0), x) - with pytest.raises(AssertionError, match="argument 0"): - assert_same_outcome(a, b) - - def test_maxulp(self): - a = Outcome(value=one_ulp_up(1.0, 6)) - b = Outcome(value=1.0) - with pytest.raises(AssertionError, match="ulp"): - assert_same_outcome(a, b) - assert_same_outcome(a, b, maxulp=6) - - -class TestCompare: - def test_returns_oracle_outcome(self): - result = compare(returns(1.0), returns(1.0), np.zeros(2)) - assert result.value == 1.0 - - def test_arguments_are_copied(self): - x = np.zeros(2) - compare(returns(1.0, modify=3.0), returns(1.0, modify=3.0), x) - assert x[0] == 0.0 - - def test_returns_oracle_args(self): - result = compare(returns(1.0, modify=3.0), returns(1.0, modify=3.0), np.zeros(2)) - assert result.args[0][0] == 3.0 - - def test_mismatch(self): - with pytest.raises(AssertionError): - compare(returns(1.0), returns(2.0), np.zeros(2)) - - def test_oracle_raises_implementation_returns(self): - with pytest.raises(AssertionError, match="oracle raised"): - compare(returns(1.0), raises(ValueError("a")), np.zeros(2)) - - def test_check_message(self): - impl, oracle = raises(ValueError("a")), raises(ValueError("b")) - with pytest.raises(AssertionError): - compare(impl, oracle, np.zeros(2)) - compare(impl, oracle, np.zeros(2), check_message=False) - - def test_keyword_arguments(self): - compare(lambda x, y=0: x + y, lambda x, y=0: x + y, 1.0, y=2.0) - - -class TestKind: - @pytest.mark.parametrize( - ("value", "expected"), - [ - pytest.param(1.0, "finite", id="finite"), - pytest.param(np.zeros(0), "finite", id="empty"), - pytest.param(NAN, "nan", id="nan"), - pytest.param(np.array([1.0, NAN]), "nan", id="array_with_nan"), - pytest.param(INF, "nonfinite", id="inf"), - pytest.param(np.array([-INF, 1.0]), "nonfinite", id="array_with_inf"), - pytest.param((1.0, np.array([INF, NAN])), "nan", id="nan_beats_inf"), - pytest.param((np.ones(2), (1.0, INF)), "nonfinite", id="nested"), - pytest.param((np.ones((2, 3)), np.ones(4)), "finite", id="mixed_ndim"), - pytest.param(None, None, id="none"), - ], - ) - def test_value(self, value, expected): - assert kind(Outcome(value=value)) == expected - - def test_exception(self): - assert kind(Outcome(exception=KeyError("a"))) is KeyError - - -class TestAssertOutcome: - def test_expected_kind(self): - assert_outcome(returns(1.0), returns(1.0), (np.zeros(1),), "finite") - - def test_wrong_kind(self): - with pytest.raises(AssertionError): - assert_outcome(returns(1.0), returns(1.0), (np.zeros(1),), "nan") - - def test_expected_exception(self): - assert_outcome( - raises(KeyError("a")), raises(KeyError("a")), (np.zeros(1),), KeyError - ) - - -class TestBoth: - def test_returns_oracle_value(self): - assert both(returns(1.0), returns(1.0), np.zeros(1)) == 1.0 - - def test_reraises_oracle_exception(self): - with pytest.raises(ValueError, match="a"): - both(raises(ValueError("a")), raises(ValueError("a")), np.zeros(1)) diff --git a/tests/test_oracle_variational.py b/tests/test_oracle_variational.py index fe63fd9d..05cad301 100644 --- a/tests/test_oracle_variational.py +++ b/tests/test_oracle_variational.py @@ -854,10 +854,8 @@ def test_shape_mismatches(self, impl, snaps, change): class TestMultiSweep: """ - Whole sweeps from the initial state. One ulp of difference in an intermediate - result grows to ~1e-6 in node means after a sweep (see - `evaluation/ep_sensitivity.py`), so node means are compared to a relative - tolerance, and the pattern of skipped updates (NaN) must be identical. + Whole sweeps from the initial state: the node posteriors, likelihood + normalisers and mutation posteriors of every sweep are identical to the oracle's. """ CASES = { @@ -869,17 +867,6 @@ class TestMultiSweep: ), } - @staticmethod - def means(posterior): - with np.errstate(all="ignore"): - return (posterior[:, 0] + 1) / posterior[:, 1] - - def assert_means_close(self, actual, expected, rtol): - a, e = self.means(actual), self.means(expected) - assert np.array_equal(np.isfinite(a), np.isfinite(e)) - ok = np.isfinite(a) - np.testing.assert_allclose(a[ok], e[ok], rtol=rtol) - @pytest.mark.parametrize("case", CASES) def test_sweeps(self, impl, fresh, case): name, kwargs = self.CASES[case] @@ -887,11 +874,8 @@ def test_sweeps(self, impl, fresh, case): sweeps = 4 actual = ep_state.run_sweeps(impl.variational, snap, sweeps, **kwargs) expected = ep_state.run_sweeps(variational, snap, sweeps, **kwargs) - for sweep, (a, e) in enumerate(zip(actual[0], expected[0])): - assert np.array_equal(np.isnan(a[1]), np.isnan(e[1])) # edge lognorm - assert np.array_equal(np.isnan(a[2]), np.isnan(e[2])) # block lognorm - rtol = 1e-4 if sweep == 0 else 1e-6 - self.assert_means_close(a[0], e[0], rtol) - mutation_actual, mutation_expected = actual[1][0], expected[1][0] - assert np.array_equal(np.isnan(mutation_actual), np.isnan(mutation_expected)) - self.assert_means_close(mutation_actual, mutation_expected, 1e-6) + for a, e in zip(actual[0], expected[0]): + for x, y in zip(a, e): # node posterior, edge and block lognorm + np.testing.assert_array_equal(x, y) + for x, y in zip(actual[1], expected[1]): # mutation posterior, phase + np.testing.assert_array_equal(x, y) diff --git a/tests/test_python_c_approx.py b/tests/test_python_c_approx.py index 7cdf4616..ddf8627c 100644 --- a/tests/test_python_c_approx.py +++ b/tests/test_python_c_approx.py @@ -11,7 +11,6 @@ import pytest from oracle import approx from oracle.helpers import compare -from oracle.implementations import _c_projection # error code: the message of numba's KLMinimizationFailedError (or the assertion) APPROX_ERRORS = { @@ -37,7 +36,7 @@ def test_messages(self, code, message): class TestAverageGammas: - def test_matches_kl_of_averages(self): + def test_returns_floats(self): alpha = np.array([0.5, 3.0]) beta = np.array([1.0, 2.0]) result = _tsdate.average_gammas(alpha, beta) @@ -76,21 +75,6 @@ def test_library_error(self): _tsdate.average_gammas(np.array([]), np.array([])) -class TestProjectionAdapter: - def test_flattens_arrays_and_wraps_pairs(self): - calls = [] - - def func(*flat): - calls.append(flat) - return 7.0, 1.0, 2.0, 3.0, 4.0 - - result = _c_projection(func)(2.5, np.array([1.0, 2.0]), np.array([3.0, 4.0])) - assert calls == [(2.5, 1.0, 2.0, 3.0, 4.0)] - assert result[0] == 7.0 - np.testing.assert_array_equal(result[1], [1.0, 2.0]) - np.testing.assert_array_equal(result[2], [3.0, 4.0]) - - # Failures of the quantile fit (found by random search), each at a different step of # the Newton iteration: the lower quantile underflows to zero, its square underflows # to zero, and the iteration does not converge. diff --git a/tests/test_python_c_scalar.py b/tests/test_python_c_scalar.py index 93f72038..05775b76 100644 --- a/tests/test_python_c_scalar.py +++ b/tests/test_python_c_scalar.py @@ -9,7 +9,6 @@ import sys import _tsdate -import numpy as np import pytest import scipy.special @@ -84,65 +83,30 @@ def test_nan_is_not_an_error(self): assert math.isnan(_tsdate.gammainc_inv(math.nan, 0.5)) -def gammainc_inv_grid(): - inf, nan = math.inf, math.nan - shapes = [nan, -inf, -1e300, -1e5 - 0.5, -100.5, -40.7, -40.0, -35.7, -35.0, -34.5] - shapes += [-33.5, -1.5, -1.0, -0.5, -1e-10, 3e305] - shapes += [-0.0, 0.0, 5e-324, 1e-300, 1e-100, 1e-10, 1e-3, 0.01, 0.1, 0.2, 0.25] - shapes += [0.3, 0.5, 0.9, 1.0, 1.1, 2.0, 5.0, 10.0, 20.0, 21.0, 50.0, 150.0] - shapes += [ - 25.0, - 30.0, - 40.0, - 60.0, - 100.0, - 170.0, - 171.7, - 199.0, - 200.0, - 201.0, - 500.0, - 1e3, - 1e4, - 1e5, - 1e6, - 1e8, - ] - shapes += [1e10, 1e15, 1e300, inf] - quantiles = [nan, -inf, -0.1, -0.0, 0.0, 5e-324, 1e-300, 1e-100, 1e-20, 1e-10] - quantiles += [1e-5, 1e-3, 0.01, 0.1, 0.3, 0.5, 0.7, 0.9, np.nextafter(0.9, 1)] - quantiles += [0.95, 0.99, 1 - 1e-10, np.nextafter(1.0, 0), 1.0] - quantiles += [np.nextafter(1.0, 2), 1.1, inf] - return [(a, q) for a in shapes for q in quantiles] - - -def assert_identical(actual, expected): - """Equal values (including the sign of zero), or both NaN""" - both_nan = np.isnan(actual) & np.isnan(expected) - same = (actual == expected) & (np.signbit(actual) == np.signbit(expected)) - assert np.all(both_nan | same) - - class TestGammaincInv: """ ``gammainc_inv`` calls SciPy's ``gammaincinv`` through its Cython C API, so it is identical to ``scipy.special.gammaincinv``, including outside the domain. """ - def test_grid(self): - a, q = np.array(gammainc_inv_grid()).T - actual = np.array([_tsdate.gammainc_inv(*x) for x in zip(a, q)]) - assert_identical(actual, scipy.special.gammaincinv(a, q)) - - @pytest.mark.parametrize("seed", [1, 2]) - def test_random_draws(self, seed): - rng = np.random.default_rng(seed) - a = 10 ** rng.uniform(-6, 6, 5000) - q = np.where( - rng.random(5000) < 0.5, rng.random(5000), 10 ** rng.uniform(-12, 0, 5000) - ) - actual = np.array([_tsdate.gammainc_inv(*x) for x in zip(a, q)]) - assert_identical(actual, scipy.special.gammaincinv(a, q)) + @pytest.mark.parametrize( + ("a", "q"), + [ + (0.5, 0.3), + (2.0, 0.9), + (1e5, 1e-10), + (1e-3, 0.99), + (2.0, 0.0), + (2.0, 1.0), + (-1.0, 0.5), + (2.0, 1.5), + (math.nan, 0.5), + ], + ) + def test_matches_scipy(self, a, q): + actual = _tsdate.gammainc_inv(a, q) + expected = scipy.special.gammaincinv(a, q) + assert actual == expected or (math.isnan(actual) and math.isnan(expected)) class TestScipyDependency: From 9e1034d0dcd3f70d1b19c03062be47f1523e758f Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Tue, 24 Nov 2026 22:05:51 -0800 Subject: [PATCH 13/56] Drop numba - Remove tsdate/accelerate.py and the numba dependency, with the numba cache setting (TSDATE_ENABLE_NUMBA_CACHE) and its documentation. - cibuildwheel: build musllinux wheels and test the macOS x86_64 ones; both were skipped only because numba publishes no wheels there. win32 stays skipped (no scipy wheels). - Tests: the oracle tests run against the C implementation only, so the registry of implementations and its skipping of unported functions are gone, as is the test of the oracle's integer powers against numba and the helper for calling numba cfuncs. - evaluation: microbench.py times the C functions without an implementation switch; performance.py no longer warms up or caches numba compilation. --- CHANGELOG.md | 10 +++++ docs/installation.md | 11 ----- docs/usage.md | 6 --- evaluation/README.md | 6 +-- evaluation/accuracy.py | 2 +- evaluation/microbench.py | 72 +++++++++++--------------------- evaluation/numerical_accuracy.py | 16 +++---- evaluation/performance.py | 8 ---- pyproject.toml | 11 ++--- tests/conftest.py | 10 ++--- tests/oracle/__init__.py | 14 +++---- tests/oracle/helpers.py | 7 +--- tests/oracle/implementations.py | 48 ++++++--------------- tests/test_oracle_numba_libm.py | 47 --------------------- tsdate/accelerate.py | 27 ------------ uv.lock | 2 - 16 files changed, 70 insertions(+), 227 deletions(-) delete mode 100644 tests/test_oracle_numba_libm.py delete mode 100644 tsdate/accelerate.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e8a3017c..2cefdcfa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ In development +- The numerical core (the special functions, gamma approximations, expectation + propagation passes, rescaling and utilities) is now a C extension instead of + numba-compiled Python, with identical results. numba is no longer a dependency, + so importing tsdate no longer takes tens of seconds to compile, and + `TSDATE_ENABLE_NUMBA_CACHE` is gone. Wheels are now tested on macOS x86_64 and + built for musllinux. + +- The inside-outside method uses `scipy.special.logsumexp`, which can change + results in the last few digits. + - `preprocess_ts` now always sorts the tree sequence, which may change the order of mutations diff --git a/docs/installation.md b/docs/installation.md index 816b1a84..ad2416f7 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -49,14 +49,3 @@ Install development dependencies with `uv sync` and run the tests with: `uv sync` also (re)builds the C extension. After editing C code, run `uv sync` (or `make`) again to rebuild it. - -_Tsdate_ makes extensive use of [numba](https://numba.pydata.org)'s -"just in time" (jit) compilation to speed up time-consuming numerical functions. -Because of the need to compile these functions, loading the tsdate package can take -tens of seconds. To speed up loading time, you can set the environment variable - - TSDATE_ENABLE_NUMBA_CACHE=1 - -The compiled code is not cached by default as it can be problematic when -e.g. running the same installation on different CPU types in a cluster, -and can occassionally lead to unexpected crashes. diff --git a/docs/usage.md b/docs/usage.md index 26d6809c..dee196dd 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -320,12 +320,6 @@ As the time taken to date a tree sequence using _tsdate_ is only a fraction of t required to infer the initial tree sequence, the core _tsdate_ algorithm has not been parallelised to allow running on many CPU cores. -:::{note} -Extensive use of just-in-time compilation via [numba](https://numba.pydata.org) -means that it can take tens of seconds to load the _tsdate_ module into python. -See {ref}`here ` for a workaround if this is causing you problems. -::: - ## CLI use Computationally-intensive uses of _tsdate_ are likely to involve diff --git a/evaluation/README.md b/evaluation/README.md index 8176c391..cebf40ea 100644 --- a/evaluation/README.md +++ b/evaluation/README.md @@ -15,7 +15,7 @@ standard coalescent. | `accuracy.py` | Sweep a parameter (`sample_size`, `length`, `mutation_rate`, `max_iterations`) for `variational_gamma`, comparing estimated to true node times. `--modes true` dates the true topology; `inferred` dates a tsinfer topology and compares to best-matching true nodes via [tscompare](https://github.com/tskit-dev/tscompare) (see issue #301). Writes one row per node (`accuracy_*.csv`). It also compares mutation times (`mutations_*.csv`): sites with a single mutation are matched by position, and tsdate's posterior mean mutation time is compared with the midpoint of the true edge the mutation sits on (the best any method can do; the exact simulated time is also saved as `true_time_exact`). `plot.py` scores scatter, RMSE and bias against the midpoint but PIT and interval coverage against the exact time, since the posterior is for the realised mutation time; `--mutation-truth midpoint` or `exact` forces one truth everywhere. Mutation comparison needs no node matching in either mode. | | `afs.py` | Compare the observed site allele frequency spectrum with the expected one from branch lengths (branch AFS x mutation rate) in genomic windows, for the true times, the true topology dated by tsdate, and a tsinfer topology dated by tsdate. Writes `afs_*.csv`. | | `performance.py` | Wall time and peak RSS, each case in a fresh process. | -| `microbench.py` | Microbenchmarks of the array-level accelerated functions (EP passes, rescaling, phasing, `util`, `prior`), on simulated inputs at three sizes (see below). | +| `microbench.py` | Microbenchmarks of the array-level functions of `_tsdate` (EP passes, rescaling, phasing, `util`, `prior`), on simulated inputs at three sizes (see below). | | `numerical_accuracy.py` | Accuracy of the special functions and gamma approximations (the scalar functions of `_tsdate`) per function and regime: worst error against mpmath, SciPy or closed forms, and violations of properties such as symmetry, monotonicity and continuity at switch points (see below). Not to be confused with `accuracy.py`, which scores dating. | | `compare.py` | Compares two `performance.py` CSVs case by case (see below). | | `plot.py` | Reads `results/*.csv` and writes PNGs: error/bias/interval coverage vs parameter (`accuracy_*_summary.png`: top row node times, bottom row mutation times), estimated-vs-true scatter (`accuracy_*_scatter.png`: columns are swept values, rows are node/mutation times for true/tsinferred topology), PIT calibration histograms (`accuracy_*_calibration.png`: node row, mutation row), AFS observed-vs-expected (`afs_*.png`), time and memory scaling. | @@ -98,10 +98,6 @@ Each function is warmed up, then the median of `--repeats` timed calls is report The CSV also records provenance. Timings are only comparable between runs on a quiet machine. -Implementations are chosen with `--impl`. To add one, write a function returning a -dict of callables with the same names and signatures as `_c_impl` and register it -in `IMPLS`. - ### Accuracy of the special functions `numerical_accuracy.py` measures the approximation error of the special functions in diff --git a/evaluation/accuracy.py b/evaluation/accuracy.py index ed9a5166..681adfd3 100644 --- a/evaluation/accuracy.py +++ b/evaluation/accuracy.py @@ -188,7 +188,7 @@ def run(args): mut_frames += muts progress.update() else: - # Spawn (not fork) so that numba and tsinfer state is not shared + # Spawn (not fork) so that tsinfer state is not shared ctx = multiprocessing.get_context("spawn") with concurrent.futures.ProcessPoolExecutor(args.cores, mp_context=ctx) as ex: futures = [ex.submit(run_case, args, v, s, prov) for v, s in cases] diff --git a/evaluation/microbench.py b/evaluation/microbench.py index c62526eb..acfe9ff0 100644 --- a/evaluation/microbench.py +++ b/evaluation/microbench.py @@ -11,10 +11,6 @@ median of `time.perf_counter` is reported. Very fast calls are batched, so that a timed block lasts at least a few ms (reported times are per call). -Implementations are selected with --impl. To add one, write a function returning a -dict from function names (the keys of `_c_impl`) to callables with the same -signature, and register it in IMPLS; everything else is implementation-agnostic. - Example: python evaluation/microbench.py --repeats 7 --output microbench.csv """ @@ -52,12 +48,8 @@ def wrapped(*args): return wrapped -def _c_impl(): - """ - Callables of the C implementation. Each ported array-level function is added as - ``name: callable`` (taking the arguments of the function of that name); the - functions that are missing are skipped in the benchmarks. - """ +def _functions(): + """The benchmarked functions of `_tsdate`, by the name the benchmarks use.""" import _tsdate return { @@ -84,13 +76,6 @@ def _c_impl(): } -# The seam for adding implementations: name -> {function name -> callable}. A -# function returning a dict like _c_impl's (possibly wrapping calls to adapt -# argument types such as EPFactors). Benchmarks that an implementation lacks are -# skipped for it. -IMPLS = {"c": _c_impl} - - # --------------------------------------------------------------------------- # Inputs # --------------------------------------------------------------------------- @@ -541,12 +526,11 @@ def time_bench(func, bench, repeats): def format_table(rows): - cols = ["function", "size", "impl", "median_s", "min_s", "max_s", "repeats"] + cols = ["function", "size", "median_s", "min_s", "max_s", "repeats"] body = [ [ r["function"], r["size"], - r["impl"], f"{r['median_s']:.3e}", f"{r['min_s']:.3e}", f"{r['max_s']:.3e}", @@ -563,7 +547,6 @@ def format_table(rows): def main(): p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) - p.add_argument("--impl", nargs="+", default=["c"], choices=sorted(IMPLS)) p.add_argument("--sizes", nargs="+", default=list(SIZES), choices=list(SIZES)) p.add_argument("--repeats", type=int, default=7) p.add_argument("--ep-iterations", type=int, default=2, help="EP iterations first") @@ -584,7 +567,7 @@ def main(): if args.quick: sizes, args.repeats, args.ep_iterations = QUICK_SIZES, 1, 1 - impls = {name: IMPLS[name]() for name in args.impl} + funcs = _functions() prov = common.provenance() rows = [] @@ -599,32 +582,27 @@ def main(): for bench in benches: if args.only and not any(s in bench.name for s in args.only): continue - for name, funcs in impls.items(): - if bench.func not in funcs: - continue - times, first, batch = time_bench(funcs[bench.func], bench, args.repeats) - row = dict( - function=bench.name, - size=size, - impl=name, - median_s=statistics.median(times), - min_s=min(times), - max_s=max(times), - repeats=args.repeats, - batch=batch, - first_call_s=first, - sample_size=n, - length=length, - note=bench.note, - **info, - **prov, - ) - rows.append(row) - print( - f" {bench.name:36s} {name:6s} {row['median_s']:.3e} s " - f"(x{batch} per block)", - flush=True, - ) + times, first, batch = time_bench(funcs[bench.func], bench, args.repeats) + row = dict( + function=bench.name, + size=size, + median_s=statistics.median(times), + min_s=min(times), + max_s=max(times), + repeats=args.repeats, + batch=batch, + first_call_s=first, + sample_size=n, + length=length, + note=bench.note, + **info, + **prov, + ) + rows.append(row) + print( + f" {bench.name:36s} {row['median_s']:.3e} s (x{batch} per block)", + flush=True, + ) print() print(format_table(rows)) diff --git a/evaluation/numerical_accuracy.py b/evaluation/numerical_accuracy.py index 8590ff4d..ff1a001d 100644 --- a/evaluation/numerical_accuracy.py +++ b/evaluation/numerical_accuracy.py @@ -1,11 +1,10 @@ """ Numerical accuracy of the special functions and gamma approximations in tsdate -(the scalar functions of ``_tsdate``, ported from the numba modules -``tsdate.hypergeo`` and ``tsdate.approx``), per function and regime. Each row of the +(the scalar functions of ``_tsdate``), per function and regime. Each row of the table reports the worst error of the production function against a reference (mpmath, SciPy, a closed form) or the violation of a property the approximation should have (symmetry, monotonicity, continuity across a switch point). These are measurements, not -tests: the unit tests only check that implementations agree with the numba oracles, so +tests: the unit tests only check that the C implementation agrees with the oracles, so inaccuracy of the algorithms themselves is recorded here. Behaviour that looks wrong is a candidate for a fix. @@ -31,15 +30,10 @@ RESULTS = pathlib.Path(__file__).parent / "results" -def call(func, *args): - """Call a function, or the ``ctypes`` interface of a compiled numba ``cfunc``""" - return getattr(func, "ctypes", func)(*args) - - def try_call(func, *args): """The result of ``func``, or None if it raised""" try: - return call(func, *args) + return func(*args) except Exception: # noqa: BLE001 return None @@ -226,10 +220,10 @@ def gammainc_inv(report, rng, quick): qs = np.linspace(0.001, 0.999, 50) violations = 0 for a in [0.2, 1.0, 5.0, 100.0]: - x = [call(func, a, q) for q in qs.tolist()] + x = [func(a, q) for q in qs.tolist()] violations += int(np.sum(np.diff(x) <= 0)) report.add("gammainc", "_gammainc_inv", "monotone in q", "count", violations, 200) - exact = [(q, call(func, 1.0, q), -math.log1p(-q)) for q in [1e-100, 1e-3, 0.5, 0.999]] + exact = [(q, func(1.0, q), -math.log1p(-q)) for q in [1e-100, 1e-3, 0.5, 0.999]] errors = [rel(x, e) for _, x, e in exact] report.worst("gammainc", "_gammainc_inv", "a = 1, exponential", "rel", errors) diff --git a/evaluation/performance.py b/evaluation/performance.py index d08500ff..f59af35a 100644 --- a/evaluation/performance.py +++ b/evaluation/performance.py @@ -11,7 +11,6 @@ import argparse import multiprocessing -import os import queue as queue_lib import time @@ -29,10 +28,6 @@ def _case(queue, n, length, mutation_rate, seed, inferred): ts = common.simulate(n, length, mutation_rate, seed) if inferred: ts = common.infer_topology(ts) - # Warm up numba compilation on a tiny case so it isn't timed - tsdate.date( - common.simulate(5, 1e4, 1e-8, 1), mutation_rate=1e-8, method="variational_gamma" - ) queue.put(("start", None)) start = time.perf_counter() tsdate.date(ts, mutation_rate=mutation_rate, method="variational_gamma") @@ -103,9 +98,6 @@ def main(): if args.quick: args.sizes, args.lengths, args.repeats = [10, 30], [1e5], 1 - # Compiled code is not part of the timing or the memory increase (it is warmed up - # first), so cache it on disk to avoid recompiling in every fresh process - os.environ.setdefault("TSDATE_ENABLE_NUMBA_CACHE", "1") prov = common.provenance() rows = [] total = len(args.sizes) * len(args.lengths) * args.repeats diff --git a/pyproject.toml b/pyproject.toml index 6a302b1a..00ac66a0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,7 +50,6 @@ dependencies = [ "tskit>=1.0.0", "numpy", "scipy>=1.13.0", - "numba>=0.58.1", "mpmath", "tqdm", "appdirs", @@ -163,13 +162,9 @@ known-third-party = [ build = ["cp311-*", "cp312-*", "cp313-*", "cp314-*", "cp315-*"] build-frontend = "build" build-verbosity = 1 -# scipy and numba publish no win32 wheels, and numba none for musllinux, so -# installing these wheels would mean building the dependencies from source. -skip = ["*musllinux*", "*-win32"] -# numba publishes no macOS x86_64 wheels after 0.62.1 (none at all for -# Python >= 3.14), so the install test fails there. Build these wheels, but -# only test them once numba is no longer a dependency. -test-skip = ["*-macosx_x86_64"] +# scipy publishes no win32 wheels, so installing these wheels would mean building +# it from source. +skip = ["*-win32"] test-command = [ "python -c \"import _tsdate\"", "tsdate --help", diff --git a/tests/conftest.py b/tests/conftest.py index 846ecb53..ef8919be 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,7 +1,7 @@ import msprime import numpy as np import pytest -from oracle.implementations import IMPLEMENTATIONS +from oracle.implementations import C def pytest_addoption(parser): @@ -37,10 +37,10 @@ def pytest_configure(config): ) -@pytest.fixture(params=list(IMPLEMENTATIONS), ids=list(IMPLEMENTATIONS)) -def impl(request): - """Namespace of an implementation (see oracle/implementations.py).""" - return IMPLEMENTATIONS[request.param] +@pytest.fixture(scope="session") +def impl(): + """The C implementation, with the signatures of the oracles.""" + return C @pytest.fixture diff --git a/tests/oracle/__init__.py b/tests/oracle/__init__.py index bb6d7859..4588d35c 100644 --- a/tests/oracle/__init__.py +++ b/tests/oracle/__init__.py @@ -1,16 +1,16 @@ """ -Plain-Python reference implementations ("oracles") of tsdate's jitted functions. +Plain-Python reference implementations ("oracles") of the functions of the C +extension ``_tsdate``, made from the numba code that the extension replaced. -Each function that is compiled with numba (or later ported to C) has an oracle in -the module of the same name here, e.g. ``oracle.approx.moments``. Equivalence tests -compare every implementation listed in ``oracle.implementations.IMPLEMENTATIONS`` -against the oracle. +Each function has an oracle in the module of the same name here, e.g. +``oracle.approx.moments``. Equivalence tests compare the C implementation +(``oracle.implementations.C``) against the oracle. Rules: * An oracle is the numba source with the decorators stripped. Change the body only where plain Python differs from compiled numba (e.g. division by zero raising instead of giving inf/nan, numpy scalar semantics), and put a comment on each change. -* Oracles call other oracles, never tsdate's numba functions. -* Names and signatures match the tsdate functions exactly. +* Oracles call other oracles, never the C implementation. +* Names and signatures match the numba functions they were made from. """ diff --git a/tests/oracle/helpers.py b/tests/oracle/helpers.py index f6f4cd72..45f3b803 100644 --- a/tests/oracle/helpers.py +++ b/tests/oracle/helpers.py @@ -72,11 +72,6 @@ def assert_inplace_close(args_actual, args_desired, maxulp=4): NAN = float("nan") -def call(func, *args, **kwargs): - """Call a function, or the ``ctypes`` interface of a compiled numba ``cfunc``.""" - return getattr(func, "ctypes", func)(*args, **kwargs) - - def log_uniform(rng, lo, hi, size=None): """``10 ** U(lo, hi)``: a scalar float if ``size`` is None, else an array.""" x = 10.0 ** rng.uniform(lo, hi, size) @@ -146,7 +141,7 @@ def outcome(func, *args, **kwargs): copies = [_copy_arg(x) for x in args] try: with np.errstate(all="ignore"): - value = call(func, *copies, **kwargs) + value = func(*copies, **kwargs) except Exception as e: # noqa: BLE001 return Outcome(exception=e, args=copies) return Outcome(value=value, args=copies) diff --git a/tests/oracle/implementations.py b/tests/oracle/implementations.py index dd917b28..a5a2edc9 100644 --- a/tests/oracle/implementations.py +++ b/tests/oracle/implementations.py @@ -1,39 +1,20 @@ """ -Registry of implementations to test against the oracles. - -``IMPLEMENTATIONS`` maps a name to a namespace with one attribute per tsdate module +The C implementation, as a namespace with one attribute per tsdate module (``hypergeo``, ``approx``, ``variational``, ``rescaling``, ``phasing``, ``util``, -``prior``), exposing the functions under the same names and signatures as the oracle -modules. - -The "c" entry exists if the ``_tsdate`` extension can be imported. Its namespaces -have the attributes of the functions that have been ported (as thin adapters where the -oracle's signature or return type differs from the module's); other names skip the test -that uses them. +``prior``) exposing the functions of ``_tsdate`` under the names and signatures of the +oracle modules, through thin adapters where the oracle's signature or return type +differs from the extension's. """ import types import numpy as np -import pytest from . import variational as oracle_variational -class _PortedNamespace(types.SimpleNamespace): - """ - A namespace of the functions ported to C: using a name that has not been ported yet - skips the test. Add ported functions as attributes in `_c_namespace`. - """ - - def __getattr__(self, name): - if name.startswith("__"): - raise AttributeError(name) - pytest.skip("not yet ported to C") - - def _c_hypergeo(_tsdate): - return _PortedNamespace( + return types.SimpleNamespace( _digamma=_tsdate.digamma, _trigamma=_tsdate.trigamma, _betaln=_tsdate.betaln, @@ -73,7 +54,7 @@ def projection(*args): def _c_approx(_tsdate): # The helpers; each commented section is owned by the agent that ports it. - return _PortedNamespace( + return types.SimpleNamespace( approximate_log_moments=_tsdate.approximate_log_moments, approximate_gamma_kl=_tsdate.approximate_gamma_kl, approximate_gamma_mom=_tsdate.approximate_gamma_mom, @@ -120,7 +101,7 @@ def _c_approx(_tsdate): def _c_phasing(_tsdate): - return _PortedNamespace( + return types.SimpleNamespace( _block_singletons=_tsdate.block_singletons, reallocate_unphased=_tsdate.reallocate_unphased, _mutation_frequency=_tsdate.mutation_frequency, @@ -128,7 +109,7 @@ def _c_phasing(_tsdate): def _c_util(_tsdate): - return _PortedNamespace( + return types.SimpleNamespace( _split_disjoint_nodes=_tsdate.split_disjoint_nodes, _relabel_mutations_node=_tsdate.relabel_mutations_node, _constrain_ages=_tsdate.constrain_ages, @@ -137,14 +118,14 @@ def _c_util(_tsdate): def _c_prior(_tsdate): - return _PortedNamespace( + return types.SimpleNamespace( _marginalize_over_ancestors=_tsdate.marginalize_over_ancestors, conditional_coalescent_variance=_tsdate.conditional_coalescent_variance, ) def _c_rescaling(_tsdate): - return _PortedNamespace( + return types.SimpleNamespace( _fixed_changepoints=_tsdate.fixed_changepoints, _poisson_changepoints=_tsdate.poisson_changepoints, _count_mutations=_tsdate.count_mutations, @@ -252,7 +233,7 @@ def propagate_mutations( unphased, ) - return _PortedNamespace( + return types.SimpleNamespace( EPFactors=oracle_variational.EPFactors, _rescale_factors=rescale_factors, _assemble_factors=assemble_factors, @@ -279,9 +260,4 @@ def _c_namespace(): ) -IMPLEMENTATIONS: dict[str, types.SimpleNamespace] = {} - -try: - IMPLEMENTATIONS["c"] = _c_namespace() -except ImportError: # the extension has not been built - pass +C = _c_namespace() diff --git a/tests/test_oracle_numba_libm.py b/tests/test_oracle_numba_libm.py deleted file mode 100644 index c5b3d09b..00000000 --- a/tests/test_oracle_numba_libm.py +++ /dev/null @@ -1,47 +0,0 @@ -""" -The oracle's ``ipow`` (``oracle/_libm.py``) against numba's ``x ** n``, for the small -integer constants ``n`` used in tsdate. - -This is the only test module that imports numba. It checks the oracle against the -numba behaviour it imitates, so it is deleted together with numba (step E). -""" - -import numba -import numpy as np -import pytest -from oracle._libm import ipow -from oracle.helpers import INF, NAN - - -def compile_power(n): - @numba.njit("f8[:](f8[:])") - def power(x): - out = np.empty_like(x) - for i in range(x.size): - out[i] = x[i] ** n - return out - - return power - - -class TestIpow: - @pytest.mark.parametrize("seed", [1, 2]) - @pytest.mark.parametrize("n", [2, 3, 4, 5, 6, 7]) - def test_matches_numba(self, n, seed): - rng = np.random.default_rng(seed) - x = np.concatenate( - [ - 10.0 ** rng.uniform(-3, 3, 2000), - -(10.0 ** rng.uniform(-100, 100, 500)), - [0.0, -0.0, 1.0, -1.0, 5e-324, 1e-170, 1e170, INF, -INF, NAN], - ] - ) - actual = compile_power(n)(x) - with np.errstate(all="ignore"): - expected = np.array([ipow(xi, n) for xi in x.tolist()]) - np.testing.assert_array_equal(np.isnan(actual), np.isnan(expected)) - finite = ~np.isnan(expected) - # bit for bit, including the sign of zero - np.testing.assert_array_equal( - actual[finite].view(np.int64), expected[finite].view(np.int64) - ) diff --git a/tsdate/accelerate.py b/tsdate/accelerate.py deleted file mode 100644 index 1fe81050..00000000 --- a/tsdate/accelerate.py +++ /dev/null @@ -1,27 +0,0 @@ -import os -from collections.abc import Callable - -from numba import jit - -# By default we disable the numba cache. See e.g. -# https://github.com/sgkit-dev/sgkit/blob/main/sgkit/accelerate.py -_ENABLE_CACHE = os.environ.get("TSDATE_ENABLE_NUMBA_CACHE", "0") - -try: - CACHE_NUMBA = {"0": False, "1": True}[_ENABLE_CACHE] -except KeyError as e: # pragma: no cover - raise KeyError( - "Environment variable 'TSDATE_ENABLE_NUMBA_CACHE' must be '0' or '1'" - ) from e - - -DEFAULT_NUMBA_ARGS = { - "nopython": True, - "cache": CACHE_NUMBA, -} - - -def numba_jit(*args, **kwargs) -> Callable: # pragma: no cover - kwargs_ = DEFAULT_NUMBA_ARGS.copy() - kwargs_.update(kwargs) - return jit(*args, **kwargs_) diff --git a/uv.lock b/uv.lock index b46f01c8..1aceac12 100644 --- a/uv.lock +++ b/uv.lock @@ -3814,7 +3814,6 @@ source = { editable = "." } dependencies = [ { name = "appdirs" }, { name = "mpmath" }, - { name = "numba" }, { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, @@ -3893,7 +3892,6 @@ wheels = [ requires-dist = [ { name = "appdirs" }, { name = "mpmath" }, - { name = "numba", specifier = ">=0.58.1" }, { name = "numpy" }, { name = "scipy", specifier = ">=1.13.0" }, { name = "tqdm" }, From c9952c9278d7bd223c419600f1ceb1b0c821d469 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 09:19:38 -0800 Subject: [PATCH 14/56] Describe the code, not its history Comments and docstrings of the C library, the module, the oracles and their tests now say what the code does rather than how it relates to the numba code it replaced. The scalar adapters of _tsdatemodule.c are renamed scalar_* (from adapt_*), matching the rest of the scalar-function machinery. The single-tip prior test no longer stubs out conditional_coalescent_variance(1), which the C library handles. --- _tsdatemodule.c | 198 +++++++++++++++---------------- evaluation/performance.py | 4 +- lib/approx.c | 23 ++-- lib/err.h | 6 +- lib/hypergeo.c | 11 +- lib/mathutil.h | 4 +- lib/phasing.c | 5 +- lib/prior.c | 7 +- lib/rescaling.c | 19 ++- lib/tsdate.h | 37 +++--- lib/util.c | 2 +- lib/variational.c | 7 +- tests/oracle/__init__.py | 12 +- tests/oracle/_libm.py | 19 ++- tests/oracle/approx.py | 20 ++-- tests/oracle/helpers.py | 25 ++-- tests/oracle/hypergeo.py | 27 ++--- tests/oracle/implementations.py | 2 +- tests/oracle/phasing.py | 2 +- tests/oracle/prior.py | 4 +- tests/oracle/rescaling.py | 17 +-- tests/oracle/util.py | 2 +- tests/oracle/variational.py | 11 +- tests/test_oracle_approx.py | 6 +- tests/test_oracle_hypergeo.py | 4 +- tests/test_oracle_phasing.py | 2 +- tests/test_oracle_prior.py | 5 +- tests/test_oracle_rescaling.py | 4 +- tests/test_oracle_util.py | 2 +- tests/test_oracle_variational.py | 8 +- tests/test_python_c_approx.py | 2 +- tests/test_python_c_tables.py | 2 +- 32 files changed, 242 insertions(+), 257 deletions(-) diff --git a/_tsdatemodule.c b/_tsdatemodule.c index f30ff578..eab5cdc8 100644 --- a/_tsdatemodule.c +++ b/_tsdatemodule.c @@ -37,7 +37,7 @@ static PyObject *TsdLibraryError; /* * SciPy's gammaincinv, taken from the C API of scipy.special.cython_special at module - * initialisation (as numba did). The third argument is Cython's __pyx_skip_dispatch. + * initialisation. The third argument is Cython's __pyx_skip_dispatch. */ typedef double (*cython_gammaincinv_fn)(double a, double p, int skip_dispatch); static cython_gammaincinv_fn scipy_gammaincinv; @@ -102,26 +102,26 @@ typedef struct { } scalar_function_t; static int -adapt_digamma(const double *in, double *out) +scalar_digamma(const double *in, double *out) { return tsd_digamma(in[0], out); } static int -adapt_trigamma(const double *in, double *out) +scalar_trigamma(const double *in, double *out) { return tsd_trigamma(in[0], out); } static int -adapt_betaln(const double *in, double *out) +scalar_betaln(const double *in, double *out) { out[0] = tsd_betaln(in[0], in[1]); return 0; } static int -adapt_gammainc_der(const double *in, double *out) +scalar_gammainc_der(const double *in, double *out) { return tsd_gammainc_der(in[0], in[1], out); } @@ -134,26 +134,26 @@ gammaincinv(double a, double p) } static int -adapt_gammainc_inv(const double *in, double *out) +scalar_gammainc_inv(const double *in, double *out) { out[0] = gammaincinv(in[0], in[1]); return 0; } static int -adapt_hyperu_laplace(const double *in, double *out) +scalar_hyperu_laplace(const double *in, double *out) { return tsd_hyperu_laplace(in[0], in[1], in[2], out, out + 1); } static int -adapt_hyp1f1_laplace(const double *in, double *out) +scalar_hyp1f1_laplace(const double *in, double *out) { return tsd_hyp1f1_laplace(in[0], in[1], in[2], out); } static int -adapt_hyp2f1_laplace(const double *in, double *out) +scalar_hyp2f1_laplace(const double *in, double *out) { return tsd_hyp2f1_laplace(in[0], in[1], in[2], in[3], out); } @@ -161,60 +161,60 @@ adapt_hyp2f1_laplace(const double *in, double *out) /* approx: helpers */ static int -adapt_approximate_log_moments(const double *in, double *out) +scalar_approximate_log_moments(const double *in, double *out) { return tsd_approximate_log_moments(in[0], in[1], out, out + 1, out + 2); } static int -adapt_approximate_gamma_kl(const double *in, double *out) +scalar_approximate_gamma_kl(const double *in, double *out) { return tsd_approximate_gamma_kl(in[0], in[1], out); } static int -adapt_approximate_gamma_mom(const double *in, double *out) +scalar_approximate_gamma_mom(const double *in, double *out) { return tsd_approximate_gamma_mom(in[0], in[1], out); } static int -adapt_approximate_gamma_iqr(const double *in, double *out) +scalar_approximate_gamma_iqr(const double *in, double *out) { return tsd_approximate_gamma_iqr( in[0], in[1], in[2], in[3], in[4], gammaincinv, out); } static int -adapt_valid_moments(const double *in, double *out) +scalar_valid_moments(const double *in, double *out) { out[0] = tsd_valid_moments(in[0], in[1]); return 0; } static int -adapt_valid_gamma(const double *in, double *out) +scalar_valid_gamma(const double *in, double *out) { out[0] = tsd_valid_gamma(in[0], in[1]); return 0; } static int -adapt_valid_hyp1f1(const double *in, double *out) +scalar_valid_hyp1f1(const double *in, double *out) { out[0] = tsd_valid_hyp1f1(in[0], in[1], in[2]); return 0; } static int -adapt_valid_hyperu(const double *in, double *out) +scalar_valid_hyperu(const double *in, double *out) { out[0] = tsd_valid_hyperu(in[0], in[1], in[2]); return 0; } static int -adapt_valid_hyp2f1(const double *in, double *out) +scalar_valid_hyp2f1(const double *in, double *out) { out[0] = tsd_valid_hyp2f1(in[0], in[1], in[2], in[3]); return 0; @@ -229,41 +229,41 @@ adapt_valid_hyp2f1(const double *in, double *out) /* approx: node moments */ static int -adapt_moments(const double *in, double *out) +scalar_moments(const double *in, double *out) { return tsd_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, out + 2, out + 3, out + 4); } static int -adapt_rootward_moments(const double *in, double *out) +scalar_rootward_moments(const double *in, double *out) { return tsd_rootward_moments( in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); } static int -adapt_leafward_moments(const double *in, double *out) +scalar_leafward_moments(const double *in, double *out) { return tsd_leafward_moments( in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); } static int -adapt_unphased_moments(const double *in, double *out) +scalar_unphased_moments(const double *in, double *out) { return tsd_unphased_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, out + 2, out + 3, out + 4); } static int -adapt_twin_moments(const double *in, double *out) +scalar_twin_moments(const double *in, double *out) { return tsd_twin_moments(in[0], in[1], in[2], in[3], out, out + 1, out + 2); } static int -adapt_sideways_moments(const double *in, double *out) +scalar_sideways_moments(const double *in, double *out) { return tsd_sideways_moments( in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); @@ -271,152 +271,152 @@ adapt_sideways_moments(const double *in, double *out) /* approx: node projections */ static int -adapt_gamma_projection(const double *in, double *out) +scalar_gamma_projection(const double *in, double *out) { return tsd_gamma_projection(in, in + 2, in + 4, out, out + 1, out + 3); } static int -adapt_leafward_projection(const double *in, double *out) +scalar_leafward_projection(const double *in, double *out) { return tsd_leafward_projection(in[0], in + 1, in + 3, out, out + 1); } static int -adapt_rootward_projection(const double *in, double *out) +scalar_rootward_projection(const double *in, double *out) { return tsd_rootward_projection(in[0], in + 1, in + 3, out, out + 1); } static int -adapt_unphased_projection(const double *in, double *out) +scalar_unphased_projection(const double *in, double *out) { return tsd_unphased_projection(in, in + 2, in + 4, out, out + 1, out + 3); } static int -adapt_twin_projection(const double *in, double *out) +scalar_twin_projection(const double *in, double *out) { return tsd_twin_projection(in, in + 2, out, out + 1); } static int -adapt_sideways_projection(const double *in, double *out) +scalar_sideways_projection(const double *in, double *out) { return tsd_sideways_projection(in[0], in + 1, in + 3, out, out + 1); } /* approx: mutation moments */ static int -adapt_mutation_moments(const double *in, double *out) +scalar_mutation_moments(const double *in, double *out) { return tsd_mutation_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1); } static int -adapt_mutation_rootward_moments(const double *in, double *out) +scalar_mutation_rootward_moments(const double *in, double *out) { return tsd_mutation_rootward_moments( in[0], in[1], in[2], in[3], in[4], out, out + 1); } static int -adapt_mutation_leafward_moments(const double *in, double *out) +scalar_mutation_leafward_moments(const double *in, double *out) { return tsd_mutation_leafward_moments( in[0], in[1], in[2], in[3], in[4], out, out + 1); } static int -adapt_mutation_unphased_moments(const double *in, double *out) +scalar_mutation_unphased_moments(const double *in, double *out) { return tsd_mutation_unphased_moments( in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, out + 2); } static int -adapt_mutation_twin_moments(const double *in, double *out) +scalar_mutation_twin_moments(const double *in, double *out) { return tsd_mutation_twin_moments(in[0], in[1], in[2], in[3], out, out + 1, out + 2); } static int -adapt_mutation_sideways_moments(const double *in, double *out) +scalar_mutation_sideways_moments(const double *in, double *out) { return tsd_mutation_sideways_moments( in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); } static int -adapt_mutation_edge_moments(const double *in, double *out) +scalar_mutation_edge_moments(const double *in, double *out) { return tsd_mutation_edge_moments(in[0], in[1], out, out + 1); } static int -adapt_mutation_block_moments(const double *in, double *out) +scalar_mutation_block_moments(const double *in, double *out) { return tsd_mutation_block_moments(in[0], in[1], out, out + 1, out + 2); } /* approx: mutation projections */ static int -adapt_mutation_gamma_projection(const double *in, double *out) +scalar_mutation_gamma_projection(const double *in, double *out) { return tsd_mutation_gamma_projection(in, in + 2, in + 4, out, out + 1); } static int -adapt_mutation_leafward_projection(const double *in, double *out) +scalar_mutation_leafward_projection(const double *in, double *out) { return tsd_mutation_leafward_projection(in[0], in + 1, in + 3, out, out + 1); } static int -adapt_mutation_rootward_projection(const double *in, double *out) +scalar_mutation_rootward_projection(const double *in, double *out) { return tsd_mutation_rootward_projection(in[0], in + 1, in + 3, out, out + 1); } static int -adapt_mutation_edge_projection(const double *in, double *out) +scalar_mutation_edge_projection(const double *in, double *out) { return tsd_mutation_edge_projection(in[0], in[1], out, out + 1); } static int -adapt_mutation_unphased_projection(const double *in, double *out) +scalar_mutation_unphased_projection(const double *in, double *out) { return tsd_mutation_unphased_projection(in, in + 2, in + 4, out, out + 1); } static int -adapt_mutation_twin_projection(const double *in, double *out) +scalar_mutation_twin_projection(const double *in, double *out) { return tsd_mutation_twin_projection(in, in + 2, out, out + 1); } static int -adapt_mutation_sideways_projection(const double *in, double *out) +scalar_mutation_sideways_projection(const double *in, double *out) { return tsd_mutation_sideways_projection(in[0], in + 1, in + 3, out, out + 1); } static int -adapt_mutation_block_projection(const double *in, double *out) +scalar_mutation_block_projection(const double *in, double *out) { return tsd_mutation_block_projection(in[0], in[1], out, out + 1); } /* variational: x and y are the natural parameters of two gammas, in `in` */ static int -adapt_damp(const double *in, double *out) +scalar_damp(const double *in, double *out) { return tsd_damp(in, in + 2, in[4], out); } static int -adapt_rescale(const double *in, double *out) +scalar_rescale(const double *in, double *out) { return tsd_rescale(in, in[2], out); } @@ -424,59 +424,59 @@ adapt_rescale(const double *in, double *out) /* clang-format off */ static const scalar_function_t scalar_functions[] = { /* hypergeo */ - { "digamma", 1, 1, adapt_digamma }, - { "trigamma", 1, 1, adapt_trigamma }, - { "betaln", 2, 1, adapt_betaln }, - { "gammainc_der", 2, 1, adapt_gammainc_der }, - { "gammainc_inv", 2, 1, adapt_gammainc_inv }, - { "hyperu_laplace", 3, 2, adapt_hyperu_laplace }, - { "hyp1f1_laplace", 3, 1, adapt_hyp1f1_laplace }, - { "hyp2f1_laplace", 4, 1, adapt_hyp2f1_laplace }, + { "digamma", 1, 1, scalar_digamma }, + { "trigamma", 1, 1, scalar_trigamma }, + { "betaln", 2, 1, scalar_betaln }, + { "gammainc_der", 2, 1, scalar_gammainc_der }, + { "gammainc_inv", 2, 1, scalar_gammainc_inv }, + { "hyperu_laplace", 3, 2, scalar_hyperu_laplace }, + { "hyp1f1_laplace", 3, 1, scalar_hyp1f1_laplace }, + { "hyp2f1_laplace", 4, 1, scalar_hyp2f1_laplace }, /* approx: helpers */ - { "approximate_log_moments", 2, 3, adapt_approximate_log_moments }, - { "approximate_gamma_kl", 2, 2, adapt_approximate_gamma_kl }, - { "approximate_gamma_mom", 2, 2, adapt_approximate_gamma_mom }, - { "approximate_gamma_iqr", 5, 2, adapt_approximate_gamma_iqr }, - { "valid_moments", 2, 1, adapt_valid_moments }, - { "valid_gamma", 2, 1, adapt_valid_gamma }, - { "valid_hyp1f1", 3, 1, adapt_valid_hyp1f1 }, - { "valid_hyperu", 3, 1, adapt_valid_hyperu }, - { "valid_hyp2f1", 4, 1, adapt_valid_hyp2f1 }, + { "approximate_log_moments", 2, 3, scalar_approximate_log_moments }, + { "approximate_gamma_kl", 2, 2, scalar_approximate_gamma_kl }, + { "approximate_gamma_mom", 2, 2, scalar_approximate_gamma_mom }, + { "approximate_gamma_iqr", 5, 2, scalar_approximate_gamma_iqr }, + { "valid_moments", 2, 1, scalar_valid_moments }, + { "valid_gamma", 2, 1, scalar_valid_gamma }, + { "valid_hyp1f1", 3, 1, scalar_valid_hyp1f1 }, + { "valid_hyperu", 3, 1, scalar_valid_hyperu }, + { "valid_hyp2f1", 4, 1, scalar_valid_hyp2f1 }, /* approx: node moments */ - { "moments", 6, 5, adapt_moments }, - { "rootward_moments", 5, 3, adapt_rootward_moments }, - { "leafward_moments", 5, 3, adapt_leafward_moments }, - { "unphased_moments", 6, 5, adapt_unphased_moments }, - { "twin_moments", 4, 3, adapt_twin_moments }, - { "sideways_moments", 5, 3, adapt_sideways_moments }, + { "moments", 6, 5, scalar_moments }, + { "rootward_moments", 5, 3, scalar_rootward_moments }, + { "leafward_moments", 5, 3, scalar_leafward_moments }, + { "unphased_moments", 6, 5, scalar_unphased_moments }, + { "twin_moments", 4, 3, scalar_twin_moments }, + { "sideways_moments", 5, 3, scalar_sideways_moments }, /* approx: node projections */ - { "gamma_projection", 6, 5, adapt_gamma_projection }, - { "leafward_projection", 5, 3, adapt_leafward_projection }, - { "rootward_projection", 5, 3, adapt_rootward_projection }, - { "unphased_projection", 6, 5, adapt_unphased_projection }, - { "twin_projection", 4, 3, adapt_twin_projection }, - { "sideways_projection", 5, 3, adapt_sideways_projection }, + { "gamma_projection", 6, 5, scalar_gamma_projection }, + { "leafward_projection", 5, 3, scalar_leafward_projection }, + { "rootward_projection", 5, 3, scalar_rootward_projection }, + { "unphased_projection", 6, 5, scalar_unphased_projection }, + { "twin_projection", 4, 3, scalar_twin_projection }, + { "sideways_projection", 5, 3, scalar_sideways_projection }, /* approx: mutation moments */ - { "mutation_moments", 6, 2, adapt_mutation_moments }, - { "mutation_rootward_moments", 5, 2, adapt_mutation_rootward_moments }, - { "mutation_leafward_moments", 5, 2, adapt_mutation_leafward_moments }, - { "mutation_unphased_moments", 6, 3, adapt_mutation_unphased_moments }, - { "mutation_twin_moments", 4, 3, adapt_mutation_twin_moments }, - { "mutation_sideways_moments", 5, 3, adapt_mutation_sideways_moments }, - { "mutation_edge_moments", 2, 2, adapt_mutation_edge_moments }, - { "mutation_block_moments", 2, 3, adapt_mutation_block_moments }, + { "mutation_moments", 6, 2, scalar_mutation_moments }, + { "mutation_rootward_moments", 5, 2, scalar_mutation_rootward_moments }, + { "mutation_leafward_moments", 5, 2, scalar_mutation_leafward_moments }, + { "mutation_unphased_moments", 6, 3, scalar_mutation_unphased_moments }, + { "mutation_twin_moments", 4, 3, scalar_mutation_twin_moments }, + { "mutation_sideways_moments", 5, 3, scalar_mutation_sideways_moments }, + { "mutation_edge_moments", 2, 2, scalar_mutation_edge_moments }, + { "mutation_block_moments", 2, 3, scalar_mutation_block_moments }, /* approx: mutation projections */ - { "mutation_gamma_projection", 6, 3, adapt_mutation_gamma_projection }, - { "mutation_leafward_projection", 5, 3, adapt_mutation_leafward_projection }, - { "mutation_rootward_projection", 5, 3, adapt_mutation_rootward_projection }, - { "mutation_edge_projection", 2, 3, adapt_mutation_edge_projection }, - { "mutation_unphased_projection", 6, 3, adapt_mutation_unphased_projection }, - { "mutation_twin_projection", 4, 3, adapt_mutation_twin_projection }, - { "mutation_sideways_projection", 5, 3, adapt_mutation_sideways_projection }, - { "mutation_block_projection", 2, 3, adapt_mutation_block_projection }, + { "mutation_gamma_projection", 6, 3, scalar_mutation_gamma_projection }, + { "mutation_leafward_projection", 5, 3, scalar_mutation_leafward_projection }, + { "mutation_rootward_projection", 5, 3, scalar_mutation_rootward_projection }, + { "mutation_edge_projection", 2, 3, scalar_mutation_edge_projection }, + { "mutation_unphased_projection", 6, 3, scalar_mutation_unphased_projection }, + { "mutation_twin_projection", 4, 3, scalar_mutation_twin_projection }, + { "mutation_sideways_projection", 5, 3, scalar_mutation_sideways_projection }, + { "mutation_block_projection", 2, 3, scalar_mutation_block_projection }, /* variational: x0, x1, [y0, y1,] s */ - { "damp", 5, 1, adapt_damp }, - { "rescale", 3, 1, adapt_rescale }, + { "damp", 5, 1, scalar_damp }, + { "rescale", 3, 1, scalar_rescale }, }; /* clang-format on */ @@ -649,8 +649,8 @@ tsdate_average_gammas(PyObject *Py_UNUSED(self), PyObject *args) } /* - * Phasing, utilities and prior: array-level functions. Each takes the arguments of the - * numba function it replaces. Size checks that numba asserted raise ValueError. + * Phasing, utilities and prior: array-level functions. Each takes the arguments of its + * oracle in tests/oracle; array sizes and shapes are checked here and raise ValueError. */ #define MAX_ARRAYS 10 @@ -1262,8 +1262,8 @@ tsdate_conditional_coalescent_variance(PyObject *Py_UNUSED(self), PyObject *args } /* - * Rescaling functions (lib/rescaling.c). The checks of array sizes and shapes that the - * numba code made with assert are made here and raise ValueError. + * Rescaling functions (lib/rescaling.c). Array sizes and shapes are checked here and + * raise ValueError. */ /* A one-dimensional array of tsd_id_t (int32), copied from `data`. */ diff --git a/evaluation/performance.py b/evaluation/performance.py index f59af35a..1d740af1 100644 --- a/evaluation/performance.py +++ b/evaluation/performance.py @@ -2,8 +2,8 @@ Time and memory of tsdate.variational_gamma. Each case runs in a fresh (spawned) process so that memory is not polluted by earlier cases. Memory is the increase in resident set size (RSS) during dating over the level just before it, sampled from -the parent process (the process itself would be starved by jitted code holding the -GIL). Writes results/performance.csv; use plot.py to make figures. +the parent process (the process itself would be starved by C code holding the GIL). +Writes results/performance.csv; use plot.py to make figures. Example: python evaluation/performance.py --sizes 10 50 100 500 1000 --lengths 1e6 1e7 diff --git a/lib/approx.c b/lib/approx.c index 5b31ab08..e864d8c3 100644 --- a/lib/approx.c +++ b/lib/approx.c @@ -23,13 +23,12 @@ */ /* - * Gamma approximations and the moments of the EP updates, ported from - * tsdate/approx.py (numba). Operation order and libm calls follow the numba code so - * that results agree to the last bit or two. + * Gamma approximations and the moments of the EP updates. Operation order and libm + * calls match the oracles in tests/oracle, which the tests compare to the last bit. * - * In numba, a float division by zero raises ZeroDivisionError; here it returns - * TSD_ERR_ZERO_DIVISION, but only at the divisions that the tests show to be - * reachable. The other divisions follow IEEE semantics (infinity or NaN). + * A float division by zero returns TSD_ERR_ZERO_DIVISION at the divisions that the + * tests show to be reachable (where the oracle raises ZeroDivisionError). The other + * divisions follow IEEE semantics (infinity or NaN). */ #include @@ -638,8 +637,8 @@ tsd_unphased_moments(double a_i, double b_i, double a_j, double b_j, double y_ij /* * log p(t_i) = log(2 t_i) * y_ij - mu_ij * (2 t_i) + log(t_i) * (a_i - 1) - b_i * t_i * for the two edges of an unphased individual to the same parent. Writes the - * normalising constant, E[t_i], V[t_i]. As numba raised ZeroDivisionError for a zero - * rate r (or one whose square underflows), this returns TSD_ERR_ZERO_DIVISION. + * normalising constant, E[t_i], V[t_i]. A zero rate r (or one whose square + * underflows) returns TSD_ERR_ZERO_DIVISION. */ int tsd_twin_moments(double a_i, double b_i, double y_ij, double mu_ij, double *logl, @@ -730,8 +729,8 @@ project_moments(double mn, double va, const double pars[2], double proj[2], int return ret; } -/* The projection of the two marginals of a two-parameter update; as numba, both are - * checked before either is projected. */ +/* The projection of the two marginals of a two-parameter update; both are checked + * before either is projected. */ static int project_pair(double mn_i, double va_i, double mn_j, double va_j, const double pars_i[2], const double pars_j[2], double *logl, double logl_value, double proj_i[2], @@ -914,8 +913,8 @@ tsd_sideways_projection(double t_i, const double pars_j[2], const double pars_ij /* * Moments of the mutation age t_m. Conditional on the node ages, t_m is uniform on * (t_j, t_i) for a phased edge; the moments are those of the EP surrogate density - * integrated over the node ages, in terms of hypergeometric functions. A result that - * numba returns as NaN (arguments outside the domain) is NaN here, not an error. + * integrated over the node ages, in terms of hypergeometric functions. Arguments outside + * the domain give NaN, not an error. */ int tsd_mutation_moments(double a_i, double b_i, double a_j, double b_j, double y_ij, diff --git a/lib/err.h b/lib/err.h index 19a19a14..f2f93661 100644 --- a/lib/err.h +++ b/lib/err.h @@ -37,13 +37,13 @@ extern "C" { #define TSD_ERR_NO_MEMORY -2 #define TSD_ERR_BAD_PARAM -3 -/* Floating-point division by zero, where numba raises ZeroDivisionError */ +/* Floating-point division by zero */ #define TSD_ERR_ZERO_DIVISION -4 /* hypergeo */ #define TSD_ERR_INVALID_HYPERGEO -5 -/* approx: messages are those of numba's KLMinimizationFailedError, verbatim */ +/* approx: failures of the gamma approximations */ #define TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS -6 #define TSD_ERR_JENSEN_VIOLATION -7 #define TSD_ERR_KL_MAX_ITERATIONS -8 @@ -52,7 +52,7 @@ extern "C" { #define TSD_ERR_UNSORTED_QUANTILES -11 #define TSD_ERR_QUANTILE_MAX_ITERATIONS -12 #define TSD_ERR_NEGATIVE_SHAPE -13 -/* approx: violated preconditions (numba asserts) */ +/* approx: violated preconditions */ #define TSD_ERR_NONPOSITIVE_MOMENTS -14 #define TSD_ERR_INVALID_FIXED_AGE -15 diff --git a/lib/hypergeo.c b/lib/hypergeo.c index 62d66ae7..3418e524 100644 --- a/lib/hypergeo.c +++ b/lib/hypergeo.c @@ -24,13 +24,12 @@ /* * Numerically stable implementations of the Gauss hypergeometric function and related - * special functions, ported from tsdate/hypergeo.py (numba). Operation order and - * libm calls follow the numba code so that results agree to the last bit or two. + * special functions. Operation order and libm calls match the oracles in tests/oracle, + * which the tests compare to the last bit or two. * - * In numba, a float division by zero raises ZeroDivisionError; here it returns - * TSD_ERR_ZERO_DIVISION, but only at the divisions that the tests show to be - * reachable (those of the poles of the polygamma functions and of the Laplace - * roots). The other divisions follow IEEE semantics (infinity or NaN). + * A float division by zero returns TSD_ERR_ZERO_DIVISION at the divisions that the + * tests show to be reachable (those of the poles of the polygamma functions and of the + * Laplace roots). The other divisions follow IEEE semantics (infinity or NaN). */ #include diff --git a/lib/mathutil.h b/lib/mathutil.h index 769479ad..5109cb99 100644 --- a/lib/mathutil.h +++ b/lib/mathutil.h @@ -36,8 +36,8 @@ extern "C" { #define TSD_EULER_GAMMA 0.5772156649015329 /* - * x ** n for a small positive integer constant n, by repeated squaring. This is the - * multiplication order of llvm.powi, which numba uses for `x ** n`; ipow(x, 2) is + * x ** n for a small positive integer constant n, by repeated squaring (the + * multiplication order of LLVM's llvm.powi, and of the oracles' `ipow`); ipow(x, 2) is * exactly x * x. It can differ in the last bit from pow(x, n). */ static inline double diff --git a/lib/phasing.c b/lib/phasing.c index 0aab33b1..123e4f04 100644 --- a/lib/phasing.c +++ b/lib/phasing.c @@ -23,8 +23,7 @@ */ /* - * Phasing of singleton mutations in unphased individuals, ported from - * tsdate/phasing.py (numba). + * Phasing of singleton mutations in unphased individuals. */ #include @@ -308,7 +307,7 @@ tsd_reallocate_unphased(tsd_size_t num_edges, tsd_size_t num_mutations, goto out; } phase = mutations_phase[m]; - if (isnan(phase)) { /* TODO (numba): fix rare numerical issue */ + if (isnan(phase)) { /* TODO: fix rare numerical issue */ continue; } if (!(phase >= 0.0 && phase <= 1.0)) { diff --git a/lib/prior.c b/lib/prior.c index cfbfd58d..7379c161 100644 --- a/lib/prior.c +++ b/lib/prior.c @@ -24,8 +24,8 @@ /* * Moments of node ages under the coalescent, conditional on the number of descendant - * leaves, ported from tsdate/prior.py (numba). Operation order and libm calls follow - * the numba code so that results agree to the last bit or two. + * leaves. Operation order and libm calls match the oracles in tests/oracle, which the + * tests compare to the last bit or two. */ #include @@ -98,8 +98,7 @@ tsd_marginalize_over_ancestors( /* * Variance of node age conditional on the number of descendant leaves, under the * standard coalescent. Writes `num_tips + 1` values, indexed by the number of - * descendant leaves. (For a single tip the numba code reads out of bounds; the - * variances are zero.) + * descendant leaves. For a single tip the variances are zero. */ int tsd_conditional_coalescent_variance(tsd_size_t num_tips, double *variance_out) diff --git a/lib/rescaling.c b/lib/rescaling.c index ef7bb3e9..b29737f7 100644 --- a/lib/rescaling.c +++ b/lib/rescaling.c @@ -23,9 +23,9 @@ */ /* - * Rescaling of time so that the mutation rate is constant, ported from - * tsdate/rescaling.py (numba). Operation order and libm calls follow the numba code so - * that results agree to the last bit or two. + * Rescaling of time so that the mutation rate is constant. Operation order and libm + * calls match the oracles in tests/oracle, which the tests compare to the last bit or + * two. * * Arrays whose size is not known beforehand are allocated with room for one more * element than needed, so that empty inputs still give valid pointers. @@ -87,9 +87,8 @@ less_equal(double a, double key) /* * The first index in [min_idx, max_idx] at which the sorted array `a` exceeds `key` - * (the search of np.searchsorted(a, key, "right"), which numba reproduces): the number - * of entries less than or equal to `key` if the range contains it. As in numba, NaN is - * greater than every number. + * (the search of np.searchsorted(a, key, "right")): the number of entries less than or + * equal to `key` if the range contains it. NaN is greater than every number. */ static tsd_size_t bisect_right(const double *a, double key, tsd_size_t min_idx, tsd_size_t max_idx) @@ -194,8 +193,8 @@ tsd_fixed_changepoints(tsd_size_t num_counts, const double *counts, int64_t epoc cumulative[j] = cumulative[j] / total; } /* - * Equally spaced quantiles, as np.linspace(0, 1, epochs + 1), searched for as - * numba does: the quantiles increase, so each search starts from the last result. + * Equally spaced quantiles, as np.linspace(0, 1, epochs + 1). The quantiles + * increase, so each search starts from the last result. */ step = 1.0 / (double) epochs; last_z = 0.0; @@ -770,7 +769,7 @@ tsd_piecewise_scale_point_estimate(tsd_size_t num_points, const double *point_es x = point_estimate[j]; idx = (int64_t) searchsorted_right(num_breaks, original_breaks, x) - 1; if (idx < 0) { - /* as in numba, a time before the first breakpoint wraps to the last */ + /* a time before the first breakpoint wraps to the last */ idx += (int64_t) num_breaks; } rescaled[j] = rescale_piece( @@ -836,7 +835,7 @@ tsd_piecewise_scale_posterior(tsd_size_t num_posteriors, const double *posterior } } if (num_posteriors == 0) { - /* numba raises this from reducing an empty array: pinned by the tests */ + /* no posterior to reduce */ ret = tsd_trace_error(TSD_ERR_NO_POSTERIORS); goto out; } diff --git a/lib/tsdate.h b/lib/tsdate.h index 976cc9d1..160c22f2 100644 --- a/lib/tsdate.h +++ b/lib/tsdate.h @@ -41,9 +41,9 @@ typedef uint64_t tsd_size_t; /* * Scalar special functions (hypergeo.c). Functions that can fail return 0 or a * negative TSD_ERR_* code and write their results to the trailing output pointers; - * those that cannot fail return the result. As in the numba code they replace, NaN - * and infinite results are in-band (not errors): only violated domain assertions - * (TSD_ERR_INVALID_HYPERGEO) and divisions by zero (TSD_ERR_ZERO_DIVISION) fail. + * those that cannot fail return the result. NaN and infinite results are in-band (not + * errors): only violated domain assertions (TSD_ERR_INVALID_HYPERGEO) and divisions by + * zero (TSD_ERR_ZERO_DIVISION) fail. */ int tsd_digamma(double x, double *out); int tsd_trigamma(double x, double *out); @@ -56,7 +56,7 @@ int tsd_hyp2f1_laplace(double a, double b, double c, double x, double *out); /* * The inverse of the regularised lower incomplete gamma function, x such that * gammainc(a, x) = p, is not implemented in the library: SciPy's gammaincinv is - * called, as the numba code did. The caller (the Python module) supplies it, and + * called. The caller (the Python module) supplies it, and * library functions that need it (the approx and rescaling functions) take a * parameter of this type, so that the library has no global state and no dependency * on SciPy. The function returns NaN, 0 or infinity (not an error) for arguments @@ -72,32 +72,31 @@ typedef double (*tsd_gammaincinv_fn)(double a, double p); * proportional to t^(a - 1) exp(-b t), or as "natural parameters" (a - 1, b); the * latter are what the gamma_* approximation functions and the projections return and * take. Errors are as for the special functions above, plus the TSD_ERR_* codes of - * the approximations whose messages are those of numba's KLMinimizationFailedError. + * the approximations. * * Convention for the moment and projection functions (sections of approx.c): * * - A function that can fail returns int: 0 or a negative TSD_ERR_* code. Results * are written through trailing output pointers, which are written only on * success (return 0) and must not alias the inputs. - * - Moment functions take, in the order of the numba arguments, ages (`t_i`, `t_j`: + * - Moment functions take, in the order of the oracles' arguments, ages (`t_i`, `t_j`: * a fixed parent or child) and gamma SHAPE and rate (`a_i`, `b_i`, `a_j`, `b_j`: * not natural parameters), the mutation count `y_ij` and the rate `mu_ij`. They - * write the values that numba returns, in the same order: the log normalising + * write the values that the oracles return, in the same order: the log normalising * constant (`logl`) or the phase probability (`pr_m`), then means and variances. - * A result that numba returns as NaN (an invalid hypergeometric domain) is - * returned as NaN in every output, with return value 0. + * An invalid hypergeometric domain gives NaN in every output, with return value 0. * - Projection functions take the natural parameters of the cavity gammas as * `const double pars_i[2]`, `pars_j[2]` and the edge data as `pars_ij[2]` * (`y_ij`, `mu_ij`), or ages as in the moment functions. They write the log * normalising constant (`*logl`, or `*pr_m` for mutation projections) and the * projected natural parameters through `double proj_i[2]`, `proj_j[2]` (or - * `proj_m[2]`). Where numba returns the input parameters because the moments are - * unusable, `*logl` is NaN and `proj_*` is a copy of `pars_*`; mutation - * projections write NaN to `*pr_m` and to both entries of `proj_m`. - * - Functions of the gamma approximations that numba returns as a pair of natural - * parameters write them through `double out[2]`. + * `proj_m[2]`). Where the moments are unusable, `*logl` is NaN and `proj_*` is + * a copy of `pars_*`; mutation projections write NaN to `*pr_m` and to both + * entries of `proj_m`. + * - Functions of the gamma approximations that give a pair of natural parameters + * write them through `double out[2]`. * - The `tsd_valid_*` predicates return 1 if the arguments are usable and 0 if not; - * a failure is in-band (numba returned False), not an error. + * a failure is in-band, not an error. */ int tsd_approximate_log_moments( double mean, double variance, double *logx, double *xlogx, double *logx2); @@ -239,8 +238,8 @@ int tsd_conditional_coalescent_variance(tsd_size_t num_tips, double *variance); * row-major with two columns per edge (mutation count, mutational span). The * functions that return arrays whose size is not known beforehand allocate them * with malloc, and the caller frees them (tsd_safe_free, tsd_epoch_stats_free). - * Array sizes are the caller's responsibility (tsd_bug_assert); the numerical - * preconditions that numba asserted are reported as errors. + * Array sizes are the caller's responsibility (tsd_bug_assert); violated numerical + * preconditions are reported as errors. */ /* Per-epoch results of tsd_mutational_area; every array has `num_epochs` entries. */ @@ -296,8 +295,8 @@ int tsd_piecewise_scale_posterior(tsd_size_t num_posteriors, const double *poste * edge (block), the factor to the parent (first block node) and to the child * (second), each of two natural parameters; for each node, the mixture prior and the * constraint. Array sizes are the caller's responsibility (tsd_bug_assert); errors are - * those of the numerical preconditions that numba asserted (parameters, improper - * posteriors), and of the projections. + * violated numerical preconditions (parameters, improper posteriors) and those of the + * projections. */ typedef struct { tsd_size_t num_nodes; diff --git a/lib/util.c b/lib/util.c index b920e585..2207f7ab 100644 --- a/lib/util.c +++ b/lib/util.c @@ -23,7 +23,7 @@ */ /* - * Utilities for the tree sequence tables, ported from tsdate/util.py (numba): splitting + * Utilities for the tree sequence tables: splitting * nodes that are disconnected along the sequence, relabelling mutations accordingly, * constraining node ages, and a test for unary nodes. */ diff --git a/lib/variational.c b/lib/variational.c index 3d4f057c..46ac4e9b 100644 --- a/lib/variational.c +++ b/lib/variational.c @@ -23,10 +23,9 @@ */ /* - * The expectation propagation passes, ported from tsdate/variational.py (numba): the - * damping helpers, the passes over edges (blocks of unphased singletons), the prior - * and the mutations. Operation order follows the numba code so that results agree - * bit for bit. + * The expectation propagation passes: the damping helpers, the passes over edges + * (blocks of unphased singletons), the prior and the mutations. Operation order + * matches the oracles in tests/oracle, which the tests compare bit for bit. */ #include diff --git a/tests/oracle/__init__.py b/tests/oracle/__init__.py index 4588d35c..ab9a292f 100644 --- a/tests/oracle/__init__.py +++ b/tests/oracle/__init__.py @@ -1,6 +1,6 @@ """ Plain-Python reference implementations ("oracles") of the functions of the C -extension ``_tsdate``, made from the numba code that the extension replaced. +extension ``_tsdate``. Each function has an oracle in the module of the same name here, e.g. ``oracle.approx.moments``. Equivalence tests compare the C implementation @@ -8,9 +8,11 @@ Rules: -* An oracle is the numba source with the decorators stripped. Change the body only - where plain Python differs from compiled numba (e.g. division by zero raising - instead of giving inf/nan, numpy scalar semantics), and put a comment on each change. +* An oracle is written as array code in plain Python with the operation order of the + C library. Where plain Python semantics differ from C (e.g. division by zero + raising instead of giving inf/nan, numpy scalar semantics), a comment marks the + line that compensates. * Oracles call other oracles, never the C implementation. -* Names and signatures match the numba functions they were made from. +* Names and signatures are those of ``tsdate``'s functions of the same names, where + they exist. """ diff --git a/tests/oracle/_libm.py b/tests/oracle/_libm.py index 338f8c31..775a3022 100644 --- a/tests/oracle/_libm.py +++ b/tests/oracle/_libm.py @@ -1,10 +1,10 @@ """ C-semantics versions of the `math` functions used by the oracles. -Compiled numba calls libm directly, so e.g. ``log(0.0) == -inf``, ``exp(1e4) == inf`` +C calls libm directly, so e.g. ``log(0.0) == -inf``, ``exp(1e4) == inf`` and ``sqrt(-1.0)`` is NaN. Python's `math` module raises ``ValueError`` or ``OverflowError`` in these cases. These wrappers return the C results instead and -otherwise defer to `math`, so values agree with numba's libm calls. `lgamma` goes +otherwise defer to `math`, so values agree with the C library's libm calls. `lgamma` goes to libm itself (see `_load_libm_lgamma`). """ @@ -56,8 +56,8 @@ def tan(x): def _load_libm_lgamma(): """ - The platform C runtime's ``lgamma``, as used by compiled numba (and by the C - library): libm on Linux and macOS, the Universal CRT (``ucrtbase``) on Windows. + The platform C runtime's ``lgamma``, as used by the C library: libm on Linux and + macOS, the Universal CRT (``ucrtbase``) on Windows. CPython's `math.lgamma` is its own Lanczos implementation, which differs from the C runtime by up to thousands of ulp where lgamma is near zero (x near 1 or 2), so there is deliberately no fallback to it: if the C runtime can't be @@ -100,10 +100,9 @@ def ipow(x, n): """ ``x ** n`` for a small positive integer constant ``n``, by repeated squaring. - Numba lowers a float raised to an integer constant this way (``llvm.powi``), so - ``x ** 2 == x * x``. CPython calls libm ``pow`` instead, which differs from - this by an ulp in a small fraction of cases. Compiled code (and the C port) has - the repeated-squaring behaviour, and it matters where results cancel + The C library computes ``x ** n`` this way (``tsd_ipow``), so ``x ** 2 == x * x``. + CPython calls libm ``pow`` instead, which differs from this by an ulp in a small + fraction of cases. The difference matters where results cancel (e.g. ``va = sq - mn ** 2``). """ result = 1.0 @@ -118,7 +117,7 @@ def ipow(x, n): def seq_sum(x): """ - Sum of a 1d array, accumulating strictly left to right, as numba (and a C loop) + Sum of a 1d array, accumulating strictly left to right, as a C loop does. ``np.sum`` uses pairwise summation, which differs in the last bits. """ x = np.asarray(x) @@ -126,5 +125,5 @@ def seq_sum(x): def seq_mean(x): - """Mean of a 1d array using `seq_sum`, as ``np.mean`` is compiled by numba.""" + """Mean of a 1d array using `seq_sum`, as the C library computes means.""" return seq_sum(x) / np.size(x) diff --git a/tests/oracle/approx.py b/tests/oracle/approx.py index 0cd4620b..a87ebcaa 100644 --- a/tests/oracle/approx.py +++ b/tests/oracle/approx.py @@ -1,4 +1,4 @@ -"""Oracles for the gamma approximations (formerly the numba module ``tsdate.approx``).""" +"""Oracles for the gamma approximations (``lib/approx.c``).""" from math import inf, nan @@ -6,17 +6,17 @@ from . import hypergeo -# oracle: plain `math` raises on log(0), exp overflow etc., where compiled numba -# follows C (-inf, inf, nan); `_libm` restores the C results. -# oracle: numba computes `x ** n` for integer constants `n` by repeated squaring, -# whereas CPython calls libm pow, which differs by an ulp in a few percent of cases; -# `ipow` does what numba does (see `_libm.ipow`). Changed lines are marked. +# oracle: plain `math` raises on log(0), exp overflow etc., where C gives -inf, inf or +# nan; `_libm` gives the C results. +# oracle: C computes `x ** n` for integer constants `n` by repeated squaring, whereas +# CPython calls libm pow, which differs by an ulp in a few percent of cases; `ipow` +# squares (see `_libm.ipow`). Lines that use it are marked. # oracle: `np.log` of a Python float returns an `np.float64`, so that a following -# division by zero gives inf (with a warning) where numba, following Python -# semantics, raises ZeroDivisionError; and NumPy's SIMD log may differ from libm by an -# ulp. All `np.log` calls are replaced by the `_libm.log` of a Python float. +# division by zero gives inf (with a warning) instead of the ZeroDivisionError that +# stands for the library's TSD_ERR_ZERO_DIVISION; and NumPy's SIMD log may differ +# from libm by an ulp. Logs are the `_libm.log` of a Python float. # oracle: for the same reason, elements unpacked from a NumPy array are converted with -# `float` (marked `oracle: float`), since in numba they are Python-semantics floats. +# `float` (marked `oracle: float`). from ._libm import exp, ipow, lgamma, log # the tolerances of the KL minimisation, as in the library diff --git a/tests/oracle/helpers.py b/tests/oracle/helpers.py index 45f3b803..0f7eea16 100644 --- a/tests/oracle/helpers.py +++ b/tests/oracle/helpers.py @@ -78,7 +78,7 @@ def log_uniform(rng, lo, hi, size=None): return float(x) if size is None else x -# Exceptions of the oracle (and numba) that the C library reports as a LibraryError. +# Exceptions of the oracle that the C library reports as a LibraryError. _LIBRARY_ERROR_NAMES = ( "ZeroDivisionError", "AssertionError", @@ -89,10 +89,10 @@ def log_uniform(rng, lo, hi, size=None): def expected_error(exc_type): """ - The exceptions an implementation may raise where numba raises ``exc_type`` + The exceptions an implementation may raise where the oracle raises ``exc_type`` (``ZeroDivisionError``, ``AssertionError``, ...), for ``pytest.raises``. The C library reports these as ``_tsdate.LibraryError``, and its argument checks raise - ``ValueError`` where numba asserts on array shapes and sizes. + ``ValueError`` where the oracle asserts on array shapes and sizes. """ allowed = (exc_type,) if LibraryError is not None and exc_type.__name__ in _LIBRARY_ERROR_NAMES: @@ -127,7 +127,7 @@ def _copy_arg(x): if isinstance(x, np.ndarray): return x.copy() if isinstance(x, np.floating): - # numba treats scalars as Python floats (division by zero raises) + # the oracles expect Python floats (division by zero raises) return float(x) return x @@ -136,7 +136,7 @@ def outcome(func, *args, **kwargs): """ Call ``func`` on copies of ``args`` and return an `Outcome`. NumPy floating scalars are converted to ``float``; NumPy warnings (which the oracle emits where - numba is silent) are suppressed. + C is silent) are suppressed. """ copies = [_copy_arg(x) for x in args] try: @@ -150,14 +150,13 @@ def outcome(func, *args, **kwargs): def errors_match(actual, expected, check_message=True): """ Whether exception ``actual`` (from an implementation) matches ``expected`` (from - the oracle): the same type and, if ``check_message``, the same message. The - message of a ``ZeroDivisionError`` comes from the runtime, not from tsdate (numba - says "division by zero", Python "float division by zero"), so it is not compared. - A ``_tsdate.LibraryError`` (or, for an ``AssertionError``, a ``ValueError`` from - the module's shape checks) is accepted in place of the exceptions of - `expected_error`; its message is compared only with those of the tsdate-authored, - user-facing errors (``KLMinimizationFailedError`` and ``ValueError``), as the - messages of the others (assertions, divisions) are not part of the interface. + the oracle): the same type and, if ``check_message``, the same message (never for + a ``ZeroDivisionError``). A ``_tsdate.LibraryError`` (or, for an + ``AssertionError``, a ``ValueError`` from the module's shape checks) is accepted + in place of the exceptions of `expected_error`; its message is compared only with + those of the tsdate-authored, user-facing errors (``KLMinimizationFailedError`` + and ``ValueError``), as the messages of the others (assertions, divisions) are not + part of the interface. """ if not isinstance(actual, expected_error(type(expected))): return False diff --git a/tests/oracle/hypergeo.py b/tests/oracle/hypergeo.py index 1b1b9b6a..8e47be37 100644 --- a/tests/oracle/hypergeo.py +++ b/tests/oracle/hypergeo.py @@ -1,27 +1,26 @@ -"""Oracles for the special functions (formerly the numba module ``tsdate.hypergeo``).""" +"""Oracles for the special functions (``lib/hypergeo.c``).""" from math import pi import numpy as np import scipy.special -# oracle: plain `math` raises on log(0), exp overflow etc., where compiled numba -# follows C (-inf, inf, nan); `_libm` restores the C results. -# oracle: numba computes `x ** n` for integer constants `n` by repeated squaring, -# whereas CPython calls libm pow, which differs by an ulp in a few percent of cases; -# `ipow` does what numba does (see `_libm.ipow`). Changed lines are marked. +# oracle: plain `math` raises on log(0), exp overflow etc., where C gives -inf, inf or +# nan; `_libm` gives the C results. +# oracle: C computes `x ** n` for integer constants `n` by repeated squaring, whereas +# CPython calls libm pow, which differs by an ulp in a few percent of cases; `ipow` +# squares (see `_libm.ipow`). Lines that use it are marked. # oracle: NumPy ufuncs on Python floats return `np.float64`, so a following division -# by zero (e.g. `pi / tan(0)`) gives inf with a warning where numba, following Python -# semantics, raises ZeroDivisionError; and NumPy's SIMD loops may differ from libm. -# `np.log`, `np.tan`, `np.sin` and `np.power` are replaced by their `_libm` versions -# (libm functions on Python floats); numba lowers `np.power(x, k)` to libm `pow`. +# by zero (e.g. `pi / tan(0)`) gives inf with a warning instead of the +# ZeroDivisionError that stands for the library's TSD_ERR_ZERO_DIVISION; and NumPy's +# SIMD loops may differ from libm. Logs, tangents, sines and powers are the `_libm` +# versions (libm functions on Python floats). from ._libm import erf, exp, ipow, lgamma, log, pow, sin, sqrt, tan # noqa: A004 -# oracle: the numba version is a `numba.cfunc` wrapping SciPy's Cython gammaincinv -# (which is `scipy.special.gammaincinv`); here we call that directly. The ufunc returns -# an `np.float64`, which is converted so that callers divide by it with Python -# semantics (ZeroDivisionError), as in numba. +# oracle: the C library calls SciPy's Cython gammaincinv, which is +# `scipy.special.gammaincinv`. The ufunc returns an `np.float64`, which is converted +# so that callers divide by it with Python semantics (ZeroDivisionError). def _gammainc_inv(a, x): """scipy.special.cython_special.gammaincinv""" return float(scipy.special.gammaincinv(a, x)) diff --git a/tests/oracle/implementations.py b/tests/oracle/implementations.py index a5a2edc9..d7a03598 100644 --- a/tests/oracle/implementations.py +++ b/tests/oracle/implementations.py @@ -27,7 +27,7 @@ def _c_hypergeo(_tsdate): def _c_valid(func): - """The `_valid_*` checks return a bool in numba; the C function a float.""" + """The `_valid_*` oracles return a bool; the C functions a float.""" def valid(*args): return bool(func(*args)) diff --git a/tests/oracle/phasing.py b/tests/oracle/phasing.py index f1957cb9..43bb8f37 100644 --- a/tests/oracle/phasing.py +++ b/tests/oracle/phasing.py @@ -1,4 +1,4 @@ -"""Oracles for the jitted functions in ``tsdate.phasing``.""" +"""Oracles for the phasing functions (``lib/phasing.c``).""" import numpy as np import tskit diff --git a/tests/oracle/prior.py b/tests/oracle/prior.py index a666c7d1..0b855847 100644 --- a/tests/oracle/prior.py +++ b/tests/oracle/prior.py @@ -1,4 +1,4 @@ -"""Oracles for the jitted functions in ``tsdate.prior``.""" +"""Oracles for the prior functions (``lib/prior.c``).""" import numpy as np @@ -15,7 +15,7 @@ def _marginalize_over_ancestors(val): pr_a_ln = [np.nan, np.nan, 0.0] # log Pr(a | k, n) out = np.zeros((n + 1, N)) for k in range(n - 1, 1, -1): - # oracle: `np.log(0)` at k == 2 warns (divide by zero) here; numba is silent + # oracle: `np.log(0)` at k == 2 warns (divide by zero) here; C is silent # and the value is unused for k == 2, so suppress the warning locally. with np.errstate(divide="ignore"): const = np.log(n - k) + np.log(k - 2) - np.log(k + 1) diff --git a/tests/oracle/rescaling.py b/tests/oracle/rescaling.py index 497309a1..ecd42b65 100644 --- a/tests/oracle/rescaling.py +++ b/tests/oracle/rescaling.py @@ -1,12 +1,12 @@ -"""Oracles for the jitted functions in ``tsdate.rescaling``.""" +"""Oracles for the rescaling functions (``lib/rescaling.c``).""" from math import inf import numpy as np import tskit -# oracle: plain `math.log` raises on 0, where compiled numba gives -inf; numba's -# np.sum accumulates sequentially, whereas numpy sums pairwise (`seq_sum`). +# oracle: plain `math.log` raises on 0, where C gives -inf; C sums sequentially, +# whereas numpy sums pairwise (`seq_sum`). from ._libm import log, seq_sum from .approx import approximate_gamma_iqr from .hypergeo import _gammainc_inv as gammainc_inv @@ -347,16 +347,17 @@ def rescale(x): # reproject posteriors using inter-quantile range new_posteriors = np.full(posteriors.shape, np.nan) for i in np.flatnonzero(freed): - # oracle: in numba, a float division by zero raises `ZeroDivisionError`, - # where numpy scalars give inf. `approximate_gamma_iqr` divides by its `x1` - # argument (`x2 / x1`, or `... / x` in `upper_bound`) in every branch that - # doesn't raise earlier, so a zero lower quantile raises there. + # oracle: the library reports a float division by zero here (as + # `ZeroDivisionError` in the oracle), where numpy scalars give inf. + # `approximate_gamma_iqr` divides by its `x1` argument (`x2 / x1`, or `... / x` + # in `upper_bound`) in every branch that doesn't raise earlier, so a zero lower + # quantile raises there. if lower[i] == 0.0: raise ZeroDivisionError("division by zero") alpha, beta = approximate_gamma_iqr( quant_lower, quant_upper, lower[i], upper[i], max_shape ) - if midpt[i] == 0.0: # oracle: as above, numba raises + if midpt[i] == 0.0: # oracle: as above raise ZeroDivisionError("division by zero") beta = (alpha + 1) / midpt[i] # choose rate so as to keep mean new_posteriors[i] = alpha, beta diff --git a/tests/oracle/util.py b/tests/oracle/util.py index 15e329cf..2d26aa34 100644 --- a/tests/oracle/util.py +++ b/tests/oracle/util.py @@ -1,4 +1,4 @@ -"""Oracles for the jitted functions in ``tsdate.util``.""" +"""Oracles for the tree sequence utilities (``lib/util.c``).""" import numpy as np import tskit diff --git a/tests/oracle/variational.py b/tests/oracle/variational.py index f2811c2c..27140287 100644 --- a/tests/oracle/variational.py +++ b/tests/oracle/variational.py @@ -1,4 +1,4 @@ -"""Oracles for the jitted functions in ``tsdate.variational``.""" +"""Oracles for the expectation propagation passes (``lib/variational.c``).""" import numpy as np import tskit @@ -15,21 +15,16 @@ from . import approx -# oracle: numba's np.mean accumulates sequentially, whereas numpy sums pairwise, -# which differs in the last bits; `seq_mean` sums sequentially. +# oracle: C sums sequentially, whereas numpy sums pairwise, which differs in the last +# bits; `seq_mean` sums sequentially. from ._libm import seq_mean -# oracle: the numba version is a `jitclass`; this is a plain class with the same -# fields (arrays are created with the same dtypes) and constructor. class EPFactors: """ Mutable state of the EP algorithm, that is the factors associated with each edge likelihood / block likelihood / prior factor, that together form the posterior. - - Because of constraints on numba's AOT compilation of jitclass, - this is a dataclass (no intrinsic methods). """ def __init__( diff --git a/tests/test_oracle_approx.py b/tests/test_oracle_approx.py index 712ecb3c..a0791e0d 100644 --- a/tests/test_oracle_approx.py +++ b/tests/test_oracle_approx.py @@ -1,12 +1,12 @@ """ -Parity of each implementation (``impl``) with the oracles in ``oracle/approx.py`` for +Parity of the C implementation (``impl``) with the oracles in ``oracle/approx.py`` for the gamma approximations: values to 4 ulp, NaN and infinity patterns, and which exception is raised. Expected values always come from the oracle. Tables hold deliberate edge cases (boundaries of the ``_valid_*`` checks, degenerate gamma fits, regimes of the moment and projection functions); seeded random draws cover ranges typical of expectation propagation (EP) and extreme ones. -Conventions of the C port pinned here: a NaN result (not an exception) signals a +Conventions pinned here: a NaN result (not an exception) signals a parameter outside the valid region of the hypergeometric function; the ``*_projection`` functions then return NaN and, except for the ``mutation_*`` ones, their input parameters unchanged; ``AssertionError`` signals a violated precondition (a fixed node @@ -343,7 +343,7 @@ def test_domain(self, impl, name, args, expected): [p for p in GAMMA_DOMAIN if p.values[2] is KLMinimizationFailedError], ) def test_error_messages(self, impl, name, args, expected): - # the messages distinguish the failure modes; the port re-raises them + # the messages distinguish the failure modes func = getattr(impl.approx, name) with pytest.raises(expected_error(KLMinimizationFailedError)): func(*args) diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index 14b7ec87..80ba1651 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -1,5 +1,5 @@ """ -Parity of each implementation (``impl``) with the oracles in ``oracle/hypergeo.py`` +Parity of the C implementation (``impl``) with the oracles in ``oracle/hypergeo.py`` for the special functions: values to 4 ulp, NaN and infinity patterns, and which exception is raised (``AssertionError`` for the domain checks, ``ZeroDivisionError`` for float division by zero). Expected values always come from the @@ -445,7 +445,7 @@ def unity_args_from_ep(a_i, b_i, a_j, b_j, y, mu): (19.0, 30.0, 25.0, 1 - 1e-7), (1.0, 2.0, 1.0 + 2.0 + 1e-3, 1 - 1e-9), # g tiny positive (1.0, 2.0, 3.0 - 1e-3, 1 - 1e-9), # g tiny negative - # parameters of EP updates that reach the limit (formerly the skipped Test2F1Unity) + # parameters of EP updates that reach the limit unity_args_from_ep(202.865, 0.0153, 0.0012724, 101353547.00, 0.0, 2.404560e-05), unity_args_from_ep(999.998, 0.1041, 0.0012612, 14749022.000, 2.0, 7.830300e-05), unity_args_from_ep(157.778, 0.0182, 0.0011993, 20861958.000, 0.0, 4.128000e-07), diff --git a/tests/test_oracle_phasing.py b/tests/test_oracle_phasing.py index 24e9d253..2c1b13ac 100644 --- a/tests/test_oracle_phasing.py +++ b/tests/test_oracle_phasing.py @@ -1,5 +1,5 @@ """ -Parity of the jitted functions in ``tsdate.phasing`` with their oracles: random +Parity of the phasing functions of ``_tsdate`` with their oracles: random inputs built as in ``ExpectationPropagation``, degenerate inputs, and every ``assert``. """ diff --git a/tests/test_oracle_prior.py b/tests/test_oracle_prior.py index 0be90cd0..7956ca33 100644 --- a/tests/test_oracle_prior.py +++ b/tests/test_oracle_prior.py @@ -99,8 +99,7 @@ class TestSingleTip: def test_called_with_one_tip(self, monkeypatch): # NOTE: current behaviour, possibly a bug: a tree with one # attached sample (with `allow_unary`) calls - # `conditional_coalescent_variance(1)`, whose result is unused. That call is - # replaced here, because in numba it reads and writes out of bounds. + # `conditional_coalescent_variance(1)`, whose result is unused. tables = tskit.TableCollection(1000.0) for _ in range(3): tables.nodes.add_row(flags=tskit.NODE_IS_SAMPLE, time=0) @@ -115,8 +114,6 @@ def test_called_with_one_tip(self, monkeypatch): def record(num_tips): called.append(int(num_tips)) - if num_tips == 1: - return np.zeros(2) return original(num_tips) monkeypatch.setattr(tsdate_prior, "conditional_coalescent_variance", record) diff --git a/tests/test_oracle_rescaling.py b/tests/test_oracle_rescaling.py index 750fd948..2ec211a0 100644 --- a/tests/test_oracle_rescaling.py +++ b/tests/test_oracle_rescaling.py @@ -1,5 +1,5 @@ """ -Parity of the jitted functions in ``tsdate.rescaling`` with their oracles: random +Parity of the rescaling functions of ``_tsdate`` with their oracles: random inputs, inputs from ``ExpectationPropagation.rescale`` on simulated tree sequences, degenerate inputs, and every ``assert``/``raise``. """ @@ -695,7 +695,7 @@ def test_simulated(self, impl, ep): ) ], # NOTE: current behaviour, possibly a bug: for a shape this close - # to -1 the lower quantile underflows to zero and numba raises ZeroDivisionError + # to -1 the lower quantile underflows to zero and the division by it is an error # (IEEE would give inf), rather than KLMinimizationFailedError *[ pytest.param([row], {}, ZeroDivisionError, id=f"shape_near_minus_one_{i}") diff --git a/tests/test_oracle_util.py b/tests/test_oracle_util.py index 5ebab8d7..c67822d7 100644 --- a/tests/test_oracle_util.py +++ b/tests/test_oracle_util.py @@ -1,5 +1,5 @@ """ -Parity of the jitted functions in ``tsdate.util`` with their oracles: simulated tree +Parity of the tree sequence utilities of ``_tsdate`` with their oracles: simulated tree sequences, degenerate inputs, and every ``assert``. """ diff --git a/tests/test_oracle_variational.py b/tests/test_oracle_variational.py index 05cad301..4ac75f15 100644 --- a/tests/test_oracle_variational.py +++ b/tests/test_oracle_variational.py @@ -1,5 +1,5 @@ """ -Equivalence of each implementation of ``tsdate.variational`` with its oracle: the +Equivalence of the C implementation of ``tsdate.variational`` with its oracle: the EP helpers (``EPFactors``, ``_damp``, ``_rescale``, ``_rescale_factors``, ``_check_valid_constraints``) and the passes ``propagate_likelihood``, ``propagate_prior`` and ``propagate_mutations``, plus whole sweeps. @@ -7,8 +7,8 @@ Inputs are snapshots of real EP state (``oracle.ep_state``) on the session fixtures, with constraints edited to force branches, one-edge snapshots for each branch, and tables of boundary and failure cases. Expected values always come from the oracle. -Where compiled code raises ``ZeroDivisionError`` and the oracle does not, the -implementation alone is checked (the C port reports an error code there). +Where the C library reports a division by zero and the oracle does not raise, the +implementation alone is checked. """ from functools import partial @@ -501,7 +501,7 @@ def test_extreme_counts(self, impl, snaps, multiplier): ) def test_invalid_parameters(self, impl, snaps, kwargs): # reachable from user input (`max_shape`, `min_step` of `iterate`/`infer`): - # parameter errors in the C port, not internal asserts + # parameter errors in the C library, not internal asserts snap = snaps["small_ts"] order = snap.edge_order[:10] assert_run_kind( diff --git a/tests/test_python_c_approx.py b/tests/test_python_c_approx.py index ddf8627c..f178434e 100644 --- a/tests/test_python_c_approx.py +++ b/tests/test_python_c_approx.py @@ -12,7 +12,7 @@ from oracle import approx from oracle.helpers import compare -# error code: the message of numba's KLMinimizationFailedError (or the assertion) +# error code: the message of the oracle's KLMinimizationFailedError (or assertion) APPROX_ERRORS = { -6: "Nonpositive or nonfinite moments", -7: "log E[t] <= E[log t] violates Jensen's inequality", diff --git a/tests/test_python_c_tables.py b/tests/test_python_c_tables.py index 1ecf36a6..de56d3fb 100644 --- a/tests/test_python_c_tables.py +++ b/tests/test_python_c_tables.py @@ -160,5 +160,5 @@ def test_variance_no_tips(self, num_tips): _tsdate.conditional_coalescent_variance(num_tips) def test_variance_one_tip(self): - # numba reads out of bounds here; the result is unused + # the result is unused by tsdate assert _tsdate.conditional_coalescent_variance(1).tolist() == [0.0, 0.0] From cad52dc0e0ee3b99f907d537d6843dce1440aa19 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 09:32:31 -0800 Subject: [PATCH 15/56] Remove the per-line oracle markers The oracles' headers explain where plain Python differs from C; the inline '# oracle: ipow' (float, seq_sum, seq_mean) tags repeated that on each line. Other explanatory comments lose the 'oracle:' prefix. --- tests/oracle/__init__.py | 4 +- tests/oracle/approx.py | 136 ++++++++++++++++++------------------ tests/oracle/hypergeo.py | 54 +++++++------- tests/oracle/prior.py | 2 +- tests/oracle/rescaling.py | 12 ++-- tests/oracle/variational.py | 6 +- 6 files changed, 105 insertions(+), 109 deletions(-) diff --git a/tests/oracle/__init__.py b/tests/oracle/__init__.py index ab9a292f..c6920d45 100644 --- a/tests/oracle/__init__.py +++ b/tests/oracle/__init__.py @@ -10,8 +10,8 @@ * An oracle is written as array code in plain Python with the operation order of the C library. Where plain Python semantics differ from C (e.g. division by zero - raising instead of giving inf/nan, numpy scalar semantics), a comment marks the - line that compensates. + raising instead of giving inf/nan, numpy scalar semantics), a comment explains the + compensation, once in the module header where it applies throughout. * Oracles call other oracles, never the C implementation. * Names and signatures are those of ``tsdate``'s functions of the same names, where they exist. diff --git a/tests/oracle/approx.py b/tests/oracle/approx.py index a87ebcaa..33de6393 100644 --- a/tests/oracle/approx.py +++ b/tests/oracle/approx.py @@ -6,17 +6,17 @@ from . import hypergeo -# oracle: plain `math` raises on log(0), exp overflow etc., where C gives -inf, inf or +# Plain `math` raises on log(0), exp overflow etc., where C gives -inf, inf or # nan; `_libm` gives the C results. -# oracle: C computes `x ** n` for integer constants `n` by repeated squaring, whereas +# C computes `x ** n` for integer constants `n` by repeated squaring, whereas # CPython calls libm pow, which differs by an ulp in a few percent of cases; `ipow` -# squares (see `_libm.ipow`). Lines that use it are marked. -# oracle: `np.log` of a Python float returns an `np.float64`, so that a following +# squares (see `_libm.ipow`). +# `np.log` of a Python float returns an `np.float64`, so that a following # division by zero gives inf (with a warning) instead of the ZeroDivisionError that # stands for the library's TSD_ERR_ZERO_DIVISION; and NumPy's SIMD log may differ # from libm by an ulp. Logs are the `_libm.log` of a Python float. -# oracle: for the same reason, elements unpacked from a NumPy array are converted with -# `float` (marked `oracle: float`). +# For the same reason, elements unpacked from a NumPy array are converted with +# `float`. from ._libm import exp, ipow, lgamma, log # the tolerances of the KL minimisation, as in the library @@ -39,11 +39,9 @@ def approximate_log_moments(mean, variance): """ assert mean > 0 assert variance > 0 - logx = log(mean) - 0.5 * variance / ipow(mean, 2) # oracle: ipow + logx = log(mean) - 0.5 * variance / ipow(mean, 2) xlogx = mean * log(mean) + 0.5 * variance / mean - logx2 = ipow(log(mean), 2) + (1 - log(mean)) * variance / ipow( - mean, 2 - ) # oracle: ipow + logx2 = ipow(log(mean), 2) + (1 - log(mean)) * variance / ipow(mean, 2) return logx, xlogx, logx2 @@ -91,7 +89,7 @@ def approximate_gamma_mom(mean, variance): """ if not (mean > 0.0 and variance > 0.0): raise KLMinimizationFailedError("Nonpositive central moments") - shape = ipow(mean, 2) / variance # oracle: ipow + shape = ipow(mean, 2) / variance rate = mean / variance return shape - 1.0, rate @@ -127,7 +125,7 @@ def upper_bound(q, x): # cap shape parameter # print(itt, alpha, y1, y2) #DEBUG gra_1 = hypergeo._gammainc_der(alpha, y1) * inv_1 gra_2 = hypergeo._gammainc_der(alpha, y2) * inv_2 - gra = (gra_2 * y1 - gra_1 * y2) / ipow(y1, 2) # oracle: ipow + gra = (gra_2 * y1 - gra_1 * y2) / ipow(y1, 2) delta = -obj / gra alpha += delta itt += 1 @@ -149,7 +147,7 @@ def average_gammas(alpha, beta): assert alpha.size == beta.size, "Array sizes are not equal" avg_x = 0.0 avg_logx = 0.0 - for shape, rate in zip(map(float, alpha + 1.0), map(float, beta)): # oracle: float + for shape, rate in zip(map(float, alpha + 1.0), map(float, beta)): avg_logx += hypergeo._digamma(shape) - log(rate) avg_x += shape / rate avg_x /= alpha.size @@ -232,12 +230,12 @@ def moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): logl = f0 + hypergeo._betaln(y_ij + 1, a) + lgamma(b) - b * log(t) mn_j = d1 / t - sq_j = d2 / ipow(t, 2) # oracle: ipow - va_j = sq_j - ipow(mn_j, 2) # oracle: ipow + sq_j = d2 / ipow(t, 2) + va_j = sq_j - ipow(mn_j, 2) mn_i = mn_j * z + b / t - sq_i = sq_j * ipow(z, 2) + (b + 1) * (mn_i + mn_j * z) / t # oracle: ipow - va_i = sq_i - ipow(mn_i, 2) # oracle: ipow + sq_i = sq_j * ipow(z, 2) + (b + 1) * (mn_i + mn_j * z) / t + va_i = sq_i - ipow(mn_i, 2) return logl, mn_i, va_i, mn_j, va_j @@ -262,7 +260,7 @@ def rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): if t_j == 0.0: logl = lgamma(s) - s * log(r) mn_i = s / r - va_i = s / ipow(r, 2) # oracle: ipow + va_i = s / ipow(r, 2) return logl, mn_i, va_i a = y_ij + 1 @@ -278,7 +276,7 @@ def rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): logl = f0 - b_i * t_j + (b - 1) * log(t_j) + lgamma(a) mn_i = t_j * (1 - d0) - va_i = ipow(t_j, 2) * d0 * (d1 - d0) # oracle: ipow + va_i = ipow(t_j, 2) * d0 * (d1 - d0) return logl, mn_i, va_i @@ -310,8 +308,8 @@ def leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + hypergeo._betaln(a, b - a) mn_j = t_i * d1 - sq_j = ipow(t_i, 2) * d2 # oracle: ipow - va_j = sq_j - ipow(mn_j, 2) # oracle: ipow + sq_j = ipow(t_i, 2) * d2 + va_j = sq_j - ipow(mn_j, 2) return logl, mn_j, va_j @@ -347,12 +345,12 @@ def unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): logl = f0 + hypergeo._betaln(a_j, a_i) + lgamma(b) - b * log(t) mn_j = d1 / t - sq_j = d2 / ipow(t, 2) # oracle: ipow - va_j = sq_j - ipow(mn_j, 2) # oracle: ipow + sq_j = d2 / ipow(t, 2) + va_j = sq_j - ipow(mn_j, 2) mn_i = b / t - mn_j * z - sq_i = sq_j * ipow(z, 2) + (b + 1) * (mn_i - mn_j * z) / t # oracle: ipow - va_i = sq_i - ipow(mn_i, 2) # oracle: ipow + sq_i = sq_j * ipow(z, 2) + (b + 1) * (mn_i - mn_j * z) / t + va_i = sq_i - ipow(mn_i, 2) return logl, mn_i, va_i, mn_j, va_j @@ -369,7 +367,7 @@ def twin_moments(a_i, b_i, y_ij, mu_ij): r = b_i + 2 * mu_ij logl = log(2) * y_ij + lgamma(s) - log(r) * s mn_i = s / r - va_i = s / ipow(r, 2) # oracle: ipow + va_i = s / ipow(r, 2) return logl, mn_i, va_i @@ -397,7 +395,7 @@ def sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + lgamma(a) mn_j = -t_i * d0 - va_j = ipow(t_i, 2) * d0 * (d1 - d0) # oracle: ipow + va_j = ipow(t_i, 2) * d0 * (d1 - d0) return logl, mn_j, va_j @@ -430,7 +428,7 @@ def mutation_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): f222 = hyp2f1(a + 2, b + 2, c + 2, z) s1 = a * b / c - d1 = b * (b + 1) / ipow(t, 2) # oracle: ipow + d1 = b * (b + 1) / ipow(t, 2) d2 = d1 * a / c d3 = d2 * (a + 1) / (c + 1) @@ -438,7 +436,7 @@ def mutation_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): sq_m = ( d1 * exp(f020 - f000) / 3 + d2 * exp(f121 - f000) / 3 + d3 * exp(f222 - f000) / 3 ) - va_m = sq_m - ipow(mn_m, 2) # oracle: ipow + va_m = sq_m - ipow(mn_m, 2) return mn_m, va_m @@ -455,8 +453,8 @@ def mutation_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): logl, mn_i, va_i = rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) mn_m = mn_i / 2 + t_j / 2 - sq_m = (va_i + ipow(mn_i, 2) + mn_i * t_j + ipow(t_j, 2)) / 3 # oracle: ipow - va_m = sq_m - ipow(mn_m, 2) # oracle: ipow + sq_m = (va_i + ipow(mn_i, 2) + mn_i * t_j + ipow(t_j, 2)) / 3 + va_m = sq_m - ipow(mn_m, 2) return mn_m, va_m @@ -473,8 +471,8 @@ def mutation_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): logl, mn_j, va_j = leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) mn_m = mn_j / 2 + t_i / 2 - sq_m = (va_j + ipow(mn_j, 2) + mn_j * t_i + ipow(t_i, 2)) / 3 # oracle: ipow - va_m = sq_m - ipow(mn_m, 2) # oracle: ipow + sq_m = (va_j + ipow(mn_j, 2) + mn_j * t_i + ipow(t_i, 2)) / 3 + va_m = sq_m - ipow(mn_m, 2) return mn_m, va_m @@ -525,7 +523,7 @@ def mutation_unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): mn_m = s0 * s1 * exp(f012 - f000) / 2 + s0 * s2 * exp(f212 - f000) / 2 sq_m = d0 * d1 * exp(f023 - f000) / 3 + d0 * d2 * exp(f323 - f000) / 3 - va_m = sq_m - ipow(mn_m, 2) # oracle: ipow + va_m = sq_m - ipow(mn_m, 2) pr_m = (c - a) / c * exp(f001 - f000) return pr_m, mn_m, va_m @@ -543,8 +541,8 @@ def mutation_twin_moments(a_i, b_i, y_ij, mu_ij): r = b_i + 2 * mu_ij pr_m = 0.5 mn_m = s / r / 2 - sq_m = (s + 1) * s / 3 / ipow(r, 2) # oracle: ipow - va_m = sq_m - ipow(mn_m, 2) # oracle: ipow + sq_m = (s + 1) * s / 3 / ipow(r, 2) + va_m = sq_m - ipow(mn_m, 2) return pr_m, mn_m, va_m @@ -588,14 +586,14 @@ def mutation_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): sq_m = ( pr_m * ipow(t_i, 2) / 3 + ipow(t_i, 2) * exp(f32 - f00) * a * (a + 1) * (a + 2) / 3 - ) # oracle: ipow + ) # TODO: use a stabler approach with derivatives # note that exp(f10 - f00) = (a + z * d00) / (a - b + 1) # however the denominator is 0 if y_ij is 0 # note that when y_ij == 0 then a == b + 1 and f00 = z**(-a) - va_m = sq_m - ipow(mn_m, 2) # oracle: ipow + va_m = sq_m - ipow(mn_m, 2) return pr_m, mn_m, va_m @@ -609,7 +607,7 @@ def mutation_edge_moments(t_i, t_j): """ mn_m = 1 / 2 * (t_i + t_j) - va_m = 1 / 12 * ipow(t_i - t_j, 2) # oracle: ipow + va_m = 1 / 12 * ipow(t_i - t_j, 2) return mn_m, va_m @@ -628,8 +626,8 @@ def mutation_block_moments(t_i, t_j): pr_m = t_i / (t_i + t_j) mn_m = pr_m * t_i / 2 + (1 - pr_m) * t_j / 2 - sq_m = pr_m * ipow(t_i, 2) / 3 + (1 - pr_m) * ipow(t_j, 2) / 3 # oracle: ipow - va_m = sq_m - ipow(mn_m, 2) # oracle: ipow + sq_m = pr_m * ipow(t_i, 2) / 3 + (1 - pr_m) * ipow(t_j, 2) / 3 + va_m = sq_m - ipow(mn_m, 2) return pr_m, mn_m, va_m @@ -643,9 +641,9 @@ def gamma_projection(pars_i, pars_j, pars_ij): Returns normalizing constant, gamma natural parameters for parent and child ages """ - a_i, b_i = map(float, pars_i) # oracle: float - a_j, b_j = map(float, pars_j) # oracle: float - y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i, b_i = map(float, pars_i) + a_j, b_j = map(float, pars_j) + y_ij, mu_ij = map(float, pars_ij) a_i += 1 a_j += 1 @@ -668,8 +666,8 @@ def leafward_projection(t_i, pars_j, pars_ij): Returns normalizing constant, gamma natural parameters for child age """ - a_j, b_j = map(float, pars_j) # oracle: float - y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_j, b_j = map(float, pars_j) + y_ij, mu_ij = map(float, pars_ij) a_j += 1 logl, mn_j, va_j = leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) @@ -690,8 +688,8 @@ def rootward_projection(t_j, pars_i, pars_ij): Returns normalizing constant, gamma natural parameters for parent age """ - a_i, b_i = map(float, pars_i) # oracle: float - y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i, b_i = map(float, pars_i) + y_ij, mu_ij = map(float, pars_ij) a_i += 1 logl, mn_i, va_i = rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) @@ -713,9 +711,9 @@ def unphased_projection(pars_i, pars_j, pars_ij): Returns normalizing constant, gamma natural parameters for parent ages """ - a_i, b_i = map(float, pars_i) # oracle: float - a_j, b_j = map(float, pars_j) # oracle: float - y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i, b_i = map(float, pars_i) + a_j, b_j = map(float, pars_j) + y_ij, mu_ij = map(float, pars_ij) a_i += 1 a_j += 1 @@ -738,8 +736,8 @@ def twin_projection(pars_i, pars_ij): Returns normalizing constant, gamma natural parameters for parent ages """ - a_i, b_i = map(float, pars_i) # oracle: float - y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i, b_i = map(float, pars_i) + y_ij, mu_ij = map(float, pars_ij) a_i += 1 logl, mn_i, va_i = twin_moments(a_i, b_i, y_ij, mu_ij) @@ -760,8 +758,8 @@ def sideways_projection(t_i, pars_j, pars_ij): Returns normalizing constant, gamma natural parameters for nonfixed parent age """ - a_j, b_j = map(float, pars_j) # oracle: float - y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_j, b_j = map(float, pars_j) + y_ij, mu_ij = map(float, pars_ij) a_j += 1 logl, mn_j, va_j = sideways_moments(t_i, a_j, b_j, y_ij, mu_ij) @@ -784,9 +782,9 @@ def mutation_gamma_projection(pars_i, pars_j, pars_ij): Returns phase probability, gamma natural parameters for mutation age """ - a_i, b_i = map(float, pars_i) # oracle: float - a_j, b_j = map(float, pars_j) # oracle: float - y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i, b_i = map(float, pars_i) + a_j, b_j = map(float, pars_j) + y_ij, mu_ij = map(float, pars_ij) a_i += 1 a_j += 1 @@ -809,8 +807,8 @@ def mutation_leafward_projection(t_i, pars_j, pars_ij): Returns phase probability, gamma natural parameters for mutation age """ - a_j, b_j = map(float, pars_j) # oracle: float - y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_j, b_j = map(float, pars_j) + y_ij, mu_ij = map(float, pars_ij) a_j += 1 mn_m, va_m = mutation_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) @@ -832,8 +830,8 @@ def mutation_rootward_projection(t_j, pars_i, pars_ij): Returns phase probability, gamma natural parameters for mutation age """ - a_i, b_i = map(float, pars_i) # oracle: float - y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i, b_i = map(float, pars_i) + y_ij, mu_ij = map(float, pars_ij) a_i += 1 mn_m, va_m = mutation_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) @@ -874,9 +872,9 @@ def mutation_unphased_projection(pars_i, pars_j, pars_ij): Returns phase probability, gamma natural parameters for mutation age """ - a_i, b_i = map(float, pars_i) # oracle: float - a_j, b_j = map(float, pars_j) # oracle: float - y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i, b_i = map(float, pars_i) + a_j, b_j = map(float, pars_j) + y_ij, mu_ij = map(float, pars_ij) a_i += 1 a_j += 1 @@ -899,8 +897,8 @@ def mutation_twin_projection(pars_i, pars_ij): Returns phase probability, gamma natural parameters for mutation age """ - a_i, b_i = map(float, pars_i) # oracle: float - y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_i, b_i = map(float, pars_i) + y_ij, mu_ij = map(float, pars_ij) a_i += 1 pr_m, mn_m, va_m = mutation_twin_moments(a_i, b_i, y_ij, mu_ij) @@ -923,8 +921,8 @@ def mutation_sideways_projection(t_i, pars_j, pars_ij): Returns phase probability, gamma natural parameters for mutation age """ - a_j, b_j = map(float, pars_j) # oracle: float - y_ij, mu_ij = map(float, pars_ij) # oracle: float + a_j, b_j = map(float, pars_j) + y_ij, mu_ij = map(float, pars_ij) a_j += 1 pr_m, mn_m, va_m = mutation_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij) diff --git a/tests/oracle/hypergeo.py b/tests/oracle/hypergeo.py index 8e47be37..5ae65208 100644 --- a/tests/oracle/hypergeo.py +++ b/tests/oracle/hypergeo.py @@ -5,12 +5,12 @@ import numpy as np import scipy.special -# oracle: plain `math` raises on log(0), exp overflow etc., where C gives -inf, inf or +# Plain `math` raises on log(0), exp overflow etc., where C gives -inf, inf or # nan; `_libm` gives the C results. -# oracle: C computes `x ** n` for integer constants `n` by repeated squaring, whereas +# C computes `x ** n` for integer constants `n` by repeated squaring, whereas # CPython calls libm pow, which differs by an ulp in a few percent of cases; `ipow` -# squares (see `_libm.ipow`). Lines that use it are marked. -# oracle: NumPy ufuncs on Python floats return `np.float64`, so a following division +# squares (see `_libm.ipow`). +# NumPy ufuncs on Python floats return `np.float64`, so a following division # by zero (e.g. `pi / tan(0)`) gives inf with a warning instead of the # ZeroDivisionError that stands for the library's TSD_ERR_ZERO_DIVISION; and NumPy's # SIMD loops may differ from libm. Logs, tangents, sines and powers are the `_libm` @@ -18,7 +18,7 @@ from ._libm import erf, exp, ipow, lgamma, log, pow, sin, sqrt, tan # noqa: A004 -# oracle: the C library calls SciPy's Cython gammaincinv, which is +# The C library calls SciPy's Cython gammaincinv, which is # `scipy.special.gammaincinv`. The ufunc returns an `np.float64`, which is converted # so that callers divide by it with Python semantics (ZeroDivisionError). def _gammainc_inv(a, x): @@ -36,16 +36,16 @@ def _digamma(x): return -np.euler_gamma - (1 / x) if x < 8.5: return _digamma(1 + x) - 1 / x - xpm2 = 1 / ipow(x, 2) # oracle: ipow + xpm2 = 1 / ipow(x, 2) return ( log(x) - 0.5 / x - 0.083333333333333333 * xpm2 - + 0.008333333333333333 * ipow(xpm2, 2) # oracle: ipow - - 0.003968253968253968 * ipow(xpm2, 3) # oracle: ipow - + 0.004166666666666667 * ipow(xpm2, 4) # oracle: ipow - - 0.007575757575757576 * ipow(xpm2, 5) # oracle: ipow - + 0.021092796092796094 * ipow(xpm2, 6) # oracle: ipow + + 0.008333333333333333 * ipow(xpm2, 2) + - 0.003968253968253968 * ipow(xpm2, 3) + + 0.004166666666666667 * ipow(xpm2, 4) + - 0.007575757575757576 * ipow(xpm2, 5) + + 0.021092796092796094 * ipow(xpm2, 6) ) @@ -54,15 +54,13 @@ def _trigamma(x): Trigamma function, from asymptotic series expansion """ if x <= 0.0: - return -_trigamma(1 - x) + ipow(np.pi, 2) / ipow( - sin(np.pi * x), 2 - ) # oracle: ipow + return -_trigamma(1 - x) + ipow(np.pi, 2) / ipow(sin(np.pi * x), 2) if x <= 1e-4: - return 1 / ipow(x, 2) # oracle: ipow + return 1 / ipow(x, 2) if x < 5: - return _trigamma(1 + x) + 1 / ipow(x, 2) # oracle: ipow + return _trigamma(1 + x) + 1 / ipow(x, 2) xpm1 = 1 / x - xpm2 = 1 / ipow(x, 2) # oracle: ipow + xpm2 = 1 / ipow(x, 2) return xpm1 * ( 1.000000000000000000 + 0.500000000000000000 * xpm1 @@ -94,8 +92,8 @@ def _hyperu_laplace(a, b, x): assert x > 0.0 t = b - x - 1 - u = 2 * a / (sqrt(ipow(t, 2) + 4 * x * a) - t) # oracle: ipow - r = (b - a - 1) * ipow(u, 2) + a * ipow(1 + u, 2) # oracle: ipow + u = 2 * a / (sqrt(ipow(t, 2) + 4 * x * a) - t) + r = (b - a - 1) * ipow(u, 2) + a * ipow(1 + u, 2) g = (b - a) * log(1 + u) + a * (1 + log(u)) - x * u - log(a) * (a - 1 / 2) w = (b - 1) * u + a @@ -121,8 +119,8 @@ def _hyp1f1_laplace(a, b, x): return 0.0 t = x - b - u = 2 * a / (sqrt(ipow(t, 2) + 4 * x * a) - t) # oracle: ipow - r = ipow(u, 2) * b / a + ipow(1 - u, 2) * b / (b - a) # oracle: ipow + u = 2 * a / (sqrt(ipow(t, 2) + 4 * x * a) - t) + r = ipow(u, 2) * b / a + ipow(1 - u, 2) * b / (b - a) g = ( (b - a) * log(1 - u) + a * log(u) @@ -187,14 +185,14 @@ def _hyp2f1_unity(a, b, c, x): return s + _hyp2f1_unity(a, b, c, x) t = x * (b - a) - c - u = sqrt(ipow(t, 2) - 4 * a * x * (c - b)) - t # oracle: ipow + u = sqrt(ipow(t, 2) - 4 * a * x * (c - b)) - t y = 2 * a / u assert 0 < y < 1, "Root on boundary" - yy = ipow(y, 2) / a # oracle: ipow - my = ipow(1 - y, 2) / (c - a) # oracle: ipow - ymy = ipow(x, 2) * b * yy * my / ipow(1 - x * y, 2) # oracle: ipow + yy = ipow(y, 2) / a + my = ipow(1 - y, 2) / (c - a) + ymy = ipow(x, 2) * b * yy * my / ipow(1 - x * y, 2) r = yy + my - ymy f = ( (c - 1 / 2) * log(c) @@ -235,7 +233,7 @@ def _gammainc_der(p, x): if p > plimit: # gaussian approximation pn1 = 3 * sqrt(p) * (pow(x / p, 1 / 3) + 1 / (9 * p) - 1) grad = pn1 / (2 * p) - 1 / sqrt(p) * (pow(x / p, 1 / 3) + 1 / (3 * p)) - grad *= 1 / sqrt(2 * pi) * exp(-(ipow(pn1, 2)) / 2) # oracle: ipow + grad *= 1 / sqrt(2 * pi) * exp(-(ipow(pn1, 2)) / 2) value = (1 + erf(pn1 / sqrt(2))) / 2 return grad @@ -246,7 +244,7 @@ def _gammainc_der(p, x): a = p while True: a += 1.0 - dc = -c * x / ipow(a, 2) + dc * x / a # oracle: ipow + dc = -c * x / ipow(a, 2) + dc * x / a c *= x / a value += c grad += dc @@ -280,7 +278,7 @@ def _gammainc_der(p, x): dpn6 = b * dpn4 - pn4 - an * dpn2 + c * pn2 if pn6 != 0.0: rn = pn5 / pn6 - grad = (dpn5 * pn6 - pn5 * dpn6) / ipow(pn6, 2) # oracle: ipow + grad = (dpn5 * pn6 - pn5 * dpn6) / ipow(pn6, 2) if abs(value - rn) <= min(tol, tol * rn): break value = rn diff --git a/tests/oracle/prior.py b/tests/oracle/prior.py index 0b855847..325c1a08 100644 --- a/tests/oracle/prior.py +++ b/tests/oracle/prior.py @@ -15,7 +15,7 @@ def _marginalize_over_ancestors(val): pr_a_ln = [np.nan, np.nan, 0.0] # log Pr(a | k, n) out = np.zeros((n + 1, N)) for k in range(n - 1, 1, -1): - # oracle: `np.log(0)` at k == 2 warns (divide by zero) here; C is silent + # `np.log(0)` at k == 2 warns (divide by zero) here; C is silent # and the value is unused for k == 2, so suppress the warning locally. with np.errstate(divide="ignore"): const = np.log(n - k) + np.log(k - 2) - np.log(k + 1) diff --git a/tests/oracle/rescaling.py b/tests/oracle/rescaling.py index ecd42b65..43f2b43f 100644 --- a/tests/oracle/rescaling.py +++ b/tests/oracle/rescaling.py @@ -5,7 +5,7 @@ import numpy as np import tskit -# oracle: plain `math.log` raises on 0, where C gives -inf; C sums sequentially, +# Plain `math.log` raises on 0, where C gives -inf; C sums sequentially, # whereas numpy sums pairwise (`seq_sum`). from ._libm import log, seq_sum from .approx import approximate_gamma_iqr @@ -270,9 +270,9 @@ def mutational_timescale( for i, j in zip(changepoints[:-1], changepoints[1:]): assert j > i # TODO: when changepoint intersects a fixed node? - n = seq_sum(offset[i:j]) # oracle: seq_sum - y = seq_sum(counts[i:j]) # oracle: seq_sum - z = seq_sum(duration[i:j]) # oracle: seq_sum + n = seq_sum(offset[i:j]) + y = seq_sum(counts[i:j]) + z = seq_sum(duration[i:j]) assert n > 0, "Zero edge span in interval" adjust[k + 1] = z * y / n k += 1 @@ -347,7 +347,7 @@ def rescale(x): # reproject posteriors using inter-quantile range new_posteriors = np.full(posteriors.shape, np.nan) for i in np.flatnonzero(freed): - # oracle: the library reports a float division by zero here (as + # The library reports a float division by zero here (as # `ZeroDivisionError` in the oracle), where numpy scalars give inf. # `approximate_gamma_iqr` divides by its `x1` argument (`x2 / x1`, or `... / x` # in `upper_bound`) in every branch that doesn't raise earlier, so a zero lower @@ -357,7 +357,7 @@ def rescale(x): alpha, beta = approximate_gamma_iqr( quant_lower, quant_upper, lower[i], upper[i], max_shape ) - if midpt[i] == 0.0: # oracle: as above + if midpt[i] == 0.0: raise ZeroDivisionError("division by zero") beta = (alpha + 1) / midpt[i] # choose rate so as to keep mean new_posteriors[i] = alpha, beta diff --git a/tests/oracle/variational.py b/tests/oracle/variational.py index 27140287..0902c9ed 100644 --- a/tests/oracle/variational.py +++ b/tests/oracle/variational.py @@ -15,7 +15,7 @@ from . import approx -# oracle: C sums sequentially, whereas numpy sums pairwise, which differs in the last +# C sums sequentially, whereas numpy sums pairwise, which differs in the last # bits; `seq_mean` sums sequentially. from ._libm import seq_mean @@ -323,12 +323,12 @@ def posterior_damping(x): # fit an exponential to cavity distributions for unconstrained nodes cavity = posterior - factor[:, MIXPRIOR] * scale[:, np.newaxis] shape, rate = cavity[free, 0] + 1, cavity[free, 1] - penalty = 1 / seq_mean(shape / rate) # oracle: seq_mean + penalty = 1 / seq_mean(shape / rate) itt, delta = 0, np.inf while abs(delta) > abs(penalty) * em_reltol: if itt > em_maxitt: break - delta = 1 / seq_mean(shape / (rate + penalty)) - penalty # oracle: seq_mean + delta = 1 / seq_mean(shape / (rate + penalty)) - penalty penalty += delta itt += 1 assert penalty > 0 From 818bdaadc7134d3fc78b34fee300977e91b3b35c Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 09:38:31 -0800 Subject: [PATCH 16/56] Document the phasing functions and the undocumented oracles block_singletons and mutation_frequency had TODO docstrings; they now describe their arguments, results and requirements. Each oracle that had no docstring (or a TODO) gets a one-line summary of what it returns, and the comment of tsd_mutation_frequency says that the counts are per mutation. --- lib/phasing.c | 5 ++++- tests/oracle/approx.py | 5 +++++ tests/oracle/hypergeo.py | 1 + tests/oracle/phasing.py | 6 ++++-- tests/oracle/rescaling.py | 8 ++++++++ tests/oracle/util.py | 1 + tsdate/phasing.py | 24 ++++++++++++++++++++++-- 7 files changed, 45 insertions(+), 5 deletions(-) diff --git a/lib/phasing.c b/lib/phasing.c index 123e4f04..3fc962ce 100644 --- a/lib/phasing.c +++ b/lib/phasing.c @@ -327,7 +327,10 @@ tsd_reallocate_unphased(tsd_size_t num_edges, tsd_size_t num_mutations, return ret; } -/* The number of members of each sample set below each mutation, for each tree. */ +/* + * For each mutation and each sample set, the number of members of the set below the + * mutation's node in the tree at the mutation's position. + */ int tsd_mutation_frequency(tsd_size_t num_nodes, tsd_size_t num_sample_sets, tsd_size_t num_edges, tsd_size_t num_mutations, const uint8_t *nodes_sample, diff --git a/tests/oracle/approx.py b/tests/oracle/approx.py index 33de6393..a419c21c 100644 --- a/tests/oracle/approx.py +++ b/tests/oracle/approx.py @@ -156,6 +156,7 @@ def average_gammas(alpha, beta): def _valid_moments(mn, va): + """Whether a mean and variance are finite and positive.""" if not (np.isfinite(mn) and np.isfinite(va)): return False if not (mn > 0.0 and va > 0.0): @@ -164,6 +165,7 @@ def _valid_moments(mn, va): def _valid_gamma(s, r): + """Whether a gamma shape and rate are finite and positive.""" if not (np.isfinite(s) and np.isfinite(r)): return False if s <= 0.0 or r <= 0.0: @@ -172,6 +174,7 @@ def _valid_gamma(s, r): def _valid_hyp1f1(a, b, z): + """Whether the arguments are in the domain of `_hyp1f1_laplace`.""" if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(z)): return False if not (b >= a > 0.0): @@ -180,6 +183,7 @@ def _valid_hyp1f1(a, b, z): def _valid_hyperu(a, b, z): + """Whether the arguments are in the domain of `_hyperu_laplace`.""" if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(z)): return False if z <= 0.0: @@ -190,6 +194,7 @@ def _valid_hyperu(a, b, z): def _valid_hyp2f1(a, b, c, z): + """Whether the arguments are in the domain of `_hyp2f1_laplace`.""" if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(c)): return False if not np.isfinite(z) or z >= 1 or z / (z - 1) >= 1: diff --git a/tests/oracle/hypergeo.py b/tests/oracle/hypergeo.py index 5ae65208..682922dd 100644 --- a/tests/oracle/hypergeo.py +++ b/tests/oracle/hypergeo.py @@ -75,6 +75,7 @@ def _trigamma(x): def _betaln(p, q): + """Log of the beta function.""" return lgamma(p) + lgamma(q) - lgamma(p + q) diff --git a/tests/oracle/phasing.py b/tests/oracle/phasing.py index 43bb8f37..6fd1e0ab 100644 --- a/tests/oracle/phasing.py +++ b/tests/oracle/phasing.py @@ -49,7 +49,8 @@ def _block_singletons( sequence_length, ): """ - TODO + Blocks of the singleton mutations of unphased individuals: ``(blocks_stats, + blocks_edges, mutations_block)``. """ assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size assert indexes_insert.size == indexes_remove.size == edges_parent.size @@ -157,7 +158,8 @@ def _mutation_frequency( sequence_length, ): """ - TODO + The number of samples of each sample set below each mutation, as an array of + shape ``(num_mutations, num_sample_sets)``. """ assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size assert indexes_insert.size == indexes_remove.size == edges_parent.size diff --git a/tests/oracle/rescaling.py b/tests/oracle/rescaling.py index 43f2b43f..7ad01efb 100644 --- a/tests/oracle/rescaling.py +++ b/tests/oracle/rescaling.py @@ -88,6 +88,10 @@ def _count_mutations( sequence_length, size_biased, ): + """ + The mutations on each edge and the edge's span, weighted by the number of samples + below the edge if ``size_biased``, as ``(edges_stats, mutations_edge)``. + """ assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size assert indexes_insert.size == indexes_remove.size == edges_parent.size assert mutations_node.size == mutations_position.size @@ -371,6 +375,10 @@ def piecewise_scale_point_estimate( original_breaks, rescaled_breaks, ): + """ + Node ages mapped piecewise linearly from ``original_breaks`` to + ``rescaled_breaks``; ages where ``point_fixed`` are unchanged. + """ if not np.all(np.diff(rescaled_breaks) > 0): raise ValueError( "Rescaling produced non-increasing time breakpoints. " diff --git a/tests/oracle/util.py b/tests/oracle/util.py index 2d26aa34..86432fa2 100644 --- a/tests/oracle/util.py +++ b/tests/oracle/util.py @@ -182,6 +182,7 @@ def _contains_unary_nodes( sequence_length, num_nodes, ): + """Whether a node outside ``nodes_mask`` has exactly one child in some tree.""" assert edges_parent.size == edges_left.size == edges_right.size assert indexes_insert.size == indexes_remove.size == edges_parent.size diff --git a/tsdate/phasing.py b/tsdate/phasing.py index 84d861e6..d9599e81 100644 --- a/tsdate/phasing.py +++ b/tsdate/phasing.py @@ -36,7 +36,20 @@ def block_singletons(ts, individuals_unphased): """ - TODO + Group the singleton mutations of unphased individuals into blocks: the regions + over which both edges above an individual's two nodes are unchanged. The + unphased individuals must be diploid and contemporary. + + :param tskit.TreeSequence ts: The tree sequence. + :param numpy.ndarray individuals_unphased: Boolean array, one entry per + individual, true for the individuals whose singletons are blocked. + :return: A tuple ``(blocks_stats, blocks_edges, mutations_block)``: + ``blocks_stats`` has one row per block, the number of singletons in the + block and its span; ``blocks_edges`` has one row per block, the two edges of + the block; ``mutations_block`` gives the block of each mutation, or + ``tskit.NULL`` for mutations outside the unphased individuals. + :raises ValueError: If an unphased individual is not diploid or not + contemporary. """ for i in ts.individuals(): if individuals_unphased[i.id]: @@ -66,7 +79,14 @@ def block_singletons(ts, individuals_unphased): def mutation_frequency(ts, sample_sets=None): """ - TODO + The number of samples of each sample set that carry each mutation, that is the + samples below the mutation's node in the tree at its position. + + :param tskit.TreeSequence ts: The tree sequence. + :param list sample_sets: A list of lists of sample node ids (default: one set of + all samples). + :return: An integer array of shape ``(num_mutations, num_sample_sets)``, with + dimensions of size one removed (so 1-d for a single sample set). """ if sample_sets is None: sample_sets = [list(ts.samples())] From 75d7d9ef47a2eca4a13b09d5f57b36560358b97d Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 09:41:34 -0800 Subject: [PATCH 17/56] Put docstring quotes on their own lines --- evaluation/microbench.py | 16 +++++++++++---- evaluation/numerical_accuracy.py | 16 +++++++++++---- tests/conftest.py | 12 ++++++++--- tests/oracle/_libm.py | 4 +++- tests/oracle/approx.py | 28 +++++++++++++++++++------- tests/oracle/ep_state.py | 32 ++++++++++++++++++++++-------- tests/oracle/helpers.py | 20 ++++++++++++++----- tests/oracle/hypergeo.py | 12 ++++++++--- tests/oracle/implementations.py | 8 ++++++-- tests/oracle/phasing.py | 4 +++- tests/oracle/prior.py | 4 +++- tests/oracle/rescaling.py | 4 +++- tests/oracle/util.py | 8 ++++++-- tests/oracle/variational.py | 4 +++- tests/test_oracle_approx.py | 28 +++++++++++++++++++------- tests/test_oracle_hypergeo.py | 20 ++++++++++++++----- tests/test_oracle_phasing.py | 8 ++++++-- tests/test_oracle_prior.py | 4 +++- tests/test_oracle_rescaling.py | 12 ++++++++--- tests/test_oracle_util.py | 4 +++- tests/test_oracle_variational.py | 24 ++++++++++++++++------ tests/test_python_c_variational.py | 8 ++++++-- 22 files changed, 210 insertions(+), 70 deletions(-) diff --git a/evaluation/microbench.py b/evaluation/microbench.py index acfe9ff0..002a5393 100644 --- a/evaluation/microbench.py +++ b/evaluation/microbench.py @@ -39,7 +39,9 @@ def _with_factors(func, position): - """Wrap a `_tsdate` function so that it takes an ``EPFactors`` at `position`.""" + """ + Wrap a `_tsdate` function so that it takes an ``EPFactors`` at `position`. + """ def wrapped(*args): factors = args[position].arrays() @@ -49,7 +51,9 @@ def wrapped(*args): def _functions(): - """The benchmarked functions of `_tsdate`, by the name the benchmarks use.""" + """ + The benchmarked functions of `_tsdate`, by the name the benchmarks use. + """ import _tsdate return { @@ -148,7 +152,9 @@ def _const(*args): def build_benchmarks(n, length, iterations): - """Build all benchmarks (and a dict describing the inputs) for one size.""" + """ + Build all benchmarks (and a dict describing the inputs) for one size. + """ from tsdate import phasing, rescaling, util from tsdate.variational import ( LEAFWARD, @@ -505,7 +511,9 @@ def mutation_args( def time_bench(func, bench, repeats): - """Warm up, then return per-call times (seconds) for `repeats` timed blocks.""" + """ + Warm up, then return per-call times (seconds) for `repeats` timed blocks. + """ t0 = time.perf_counter() func(*bench.make_args()) # warm up (also the first-call cost) first_call = time.perf_counter() - t0 diff --git a/evaluation/numerical_accuracy.py b/evaluation/numerical_accuracy.py index ff1a001d..516cfdc9 100644 --- a/evaluation/numerical_accuracy.py +++ b/evaluation/numerical_accuracy.py @@ -31,7 +31,9 @@ def try_call(func, *args): - """The result of ``func``, or None if it raised""" + """ + The result of ``func``, or None if it raised + """ try: return func(*args) except Exception: # noqa: BLE001 @@ -43,7 +45,9 @@ def log_uniform(rng, lo, hi, size=None): class Report: - """Collects rows of (group, function, regime, metric, value, points, note)""" + """ + Collects rows of (group, function, regime, metric, value, points, note) + """ def __init__(self): self.rows = [] @@ -52,7 +56,9 @@ def add(self, group, function, regime, metric, value, n=1, note=""): self.rows.append((group, function, regime, metric, value, n, note)) def worst(self, group, function, regime, metric, errors, note=""): - """Worst of ``errors`` (None marks a call that raised)""" + """ + Worst of ``errors`` (None marks a call that raised) + """ raised = sum(e is None for e in errors) finite = [e for e in errors if e is not None and math.isfinite(e)] value = max(finite) if finite else math.nan @@ -170,7 +176,9 @@ def gammainc_der(report): def exact_gammainc_inv(a, q, x0): - """Root of the regularised lower incomplete gamma minus q, near ``x0``; or None""" + """ + Root of the regularised lower incomplete gamma minus q, near ``x0``; or None + """ with mpmath.workdps(40): def f(t): diff --git a/tests/conftest.py b/tests/conftest.py index ef8919be..db23c934 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -39,7 +39,9 @@ def pytest_configure(config): @pytest.fixture(scope="session") def impl(): - """The C implementation, with the signatures of the oracles.""" + """ + The C implementation, with the signatures of the oracles. + """ return C @@ -61,7 +63,9 @@ def _small_ts(samples, seed, mutation_rate=2e-8): @pytest.fixture(scope="session") def small_ts(): - """20 contemporary diploid samples, ~2e5 bp, with mutations.""" + """ + 20 contemporary diploid samples, ~2e5 bp, with mutations. + """ return _small_ts(20, seed=11) @@ -76,7 +80,9 @@ def small_ts_unphased(): @pytest.fixture(scope="session") def small_ts_historical(): - """15 diploid samples, 5 of them sampled at time 500 (non-contemporary).""" + """ + 15 diploid samples, 5 of them sampled at time 500 (non-contemporary). + """ samples = [ msprime.SampleSet(10, ploidy=2, time=0), msprime.SampleSet(5, ploidy=2, time=500), diff --git a/tests/oracle/_libm.py b/tests/oracle/_libm.py index 775a3022..afb7e8d6 100644 --- a/tests/oracle/_libm.py +++ b/tests/oracle/_libm.py @@ -125,5 +125,7 @@ def seq_sum(x): def seq_mean(x): - """Mean of a 1d array using `seq_sum`, as the C library computes means.""" + """ + Mean of a 1d array using `seq_sum`, as the C library computes means. + """ return seq_sum(x) / np.size(x) diff --git a/tests/oracle/approx.py b/tests/oracle/approx.py index a419c21c..5d8c6ada 100644 --- a/tests/oracle/approx.py +++ b/tests/oracle/approx.py @@ -1,4 +1,6 @@ -"""Oracles for the gamma approximations (``lib/approx.c``).""" +""" +Oracles for the gamma approximations (``lib/approx.c``). +""" from math import inf, nan @@ -95,7 +97,9 @@ def approximate_gamma_mom(mean, variance): def approximate_gamma_iqr(q1, q2, x1, x2, max_shape): - """Find gamma natural parameters that match empirical quantiles""" + """ + Find gamma natural parameters that match empirical quantiles + """ def upper_bound(q, x): # cap shape parameter beta = hypergeo._gammainc_inv(max_shape, q) / x @@ -156,7 +160,9 @@ def average_gammas(alpha, beta): def _valid_moments(mn, va): - """Whether a mean and variance are finite and positive.""" + """ + Whether a mean and variance are finite and positive. + """ if not (np.isfinite(mn) and np.isfinite(va)): return False if not (mn > 0.0 and va > 0.0): @@ -165,7 +171,9 @@ def _valid_moments(mn, va): def _valid_gamma(s, r): - """Whether a gamma shape and rate are finite and positive.""" + """ + Whether a gamma shape and rate are finite and positive. + """ if not (np.isfinite(s) and np.isfinite(r)): return False if s <= 0.0 or r <= 0.0: @@ -174,7 +182,9 @@ def _valid_gamma(s, r): def _valid_hyp1f1(a, b, z): - """Whether the arguments are in the domain of `_hyp1f1_laplace`.""" + """ + Whether the arguments are in the domain of `_hyp1f1_laplace`. + """ if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(z)): return False if not (b >= a > 0.0): @@ -183,7 +193,9 @@ def _valid_hyp1f1(a, b, z): def _valid_hyperu(a, b, z): - """Whether the arguments are in the domain of `_hyperu_laplace`.""" + """ + Whether the arguments are in the domain of `_hyperu_laplace`. + """ if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(z)): return False if z <= 0.0: @@ -194,7 +206,9 @@ def _valid_hyperu(a, b, z): def _valid_hyp2f1(a, b, c, z): - """Whether the arguments are in the domain of `_hyp2f1_laplace`.""" + """ + Whether the arguments are in the domain of `_hyp2f1_laplace`. + """ if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(c)): return False if not np.isfinite(z) or z >= 1 or z / (z - 1) >= 1: diff --git a/tests/oracle/ep_state.py b/tests/oracle/ep_state.py index 80140fc2..5ba1c108 100644 --- a/tests/oracle/ep_state.py +++ b/tests/oracle/ep_state.py @@ -75,7 +75,9 @@ def copy(self): return new def factors(self, cls): - """New ``EPFactors`` of class ``cls`` holding a copy of the factors""" + """ + New ``EPFactors`` of class ``cls`` holding a copy of the factors + """ factors = cls( self.node_constraints, self.edge_parents, @@ -104,7 +106,9 @@ def unscale(self, nodes, scale): f["scale"][sel] = scale def fix_nodes(self, nodes): - """Constrain ``nodes`` to their true (simulated) ages""" + """ + Constrain ``nodes`` to their true (simulated) ages + """ nodes = np.asarray(nodes) times = self.ts.nodes_time[nodes] self.node_constraints[nodes, LOWER] = times @@ -115,7 +119,9 @@ def fixed(self): return self.node_constraints[:, LOWER] == self.node_constraints[:, UPPER] def branch_counts(self, unphased): - """Number of edges (blocks) of each kind visited by the propagate functions""" + """ + Number of edges (blocks) of each kind visited by the propagate functions + """ if unphased: p, c = self.block_nodes[ROOTWARD], self.block_nodes[LEAFWARD] else: @@ -130,7 +136,9 @@ def branch_counts(self, unphased): } def after_pass(self, state): - """Copy with the state returned by `run_likelihood` as its current state""" + """ + Copy with the state returned by `run_likelihood` as its current state + """ posterior, _, *fields = state new = self.copy() new.node_posterior = posterior.copy() @@ -139,7 +147,9 @@ def after_pass(self, state): def make_snapshot(ts, name, iterations=2): - """Snapshot of the state of EP on ``ts`` (fixture ``name``) after some iterations""" + """ + Snapshot of the state of EP on ``ts`` (fixture ``name``) after some iterations + """ singletons_phased, mutation_rate = SNAPSHOT_SPECS[name] ep = ExpectationPropagation( ts, mutation_rate=mutation_rate, singletons_phased=singletons_phased @@ -189,7 +199,9 @@ def fixed_internal_snapshot(snap, unphased, every=4): def tiny_snapshot(branch, cavity=CAVITY, message=MESSAGE, likelihood=(3.0, 0.1)): - """Snapshot of a single edge (or block) whose factor is `message` at each end""" + """ + Snapshot of a single edge (or block) whose factor is `message` at each end + """ unphased, constraints, p, c = BRANCHES[branch] constraints = np.array(constraints, dtype=np.float64) n = constraints.shape[0] @@ -224,7 +236,9 @@ def tiny_snapshot(branch, cavity=CAVITY, message=MESSAGE, likelihood=(3.0, 0.1)) def likelihood_args(snap, unphased, order=None, likelihoods=None): - """Leading arguments of `propagate_likelihood` and the matching `lognorm`""" + """ + Leading arguments of `propagate_likelihood` and the matching `lognorm` + """ if unphased: args = ( snap.block_order if order is None else order, @@ -267,7 +281,9 @@ def run_likelihood( def run_prior(ns, snap, free, max_shape=1000.0, em_maxitt=10, em_reltol=1e-8): - """Run `propagate_prior`; return ``(posterior, node, scale)`` after the pass.""" + """ + Run `propagate_prior`; return ``(posterior, node, scale)`` after the pass. + """ factors = snap.factors(ns.EPFactors) posterior = snap.node_posterior.copy() ns.propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol) diff --git a/tests/oracle/helpers.py b/tests/oracle/helpers.py index 0f7eea16..10bfb77a 100644 --- a/tests/oracle/helpers.py +++ b/tests/oracle/helpers.py @@ -1,4 +1,6 @@ -"""Comparison helpers shared by the oracle equivalence tests.""" +""" +Comparison helpers shared by the oracle equivalence tests. +""" import numpy as np import tskit @@ -10,7 +12,9 @@ def _flatten(x, path=""): - """Yield (path, array) for each leaf of a nested tuple/list of scalars/arrays.""" + """ + Yield (path, array) for each leaf of a nested tuple/list of scalars/arrays. + """ if isinstance(x, (tuple, list)): for i, item in enumerate(x): yield from _flatten(item, f"{path}[{i}]") @@ -73,7 +77,9 @@ def assert_inplace_close(args_actual, args_desired, maxulp=4): def log_uniform(rng, lo, hi, size=None): - """``10 ** U(lo, hi)``: a scalar float if ``size`` is None, else an array.""" + """ + ``10 ** U(lo, hi)``: a scalar float if ``size`` is None, else an array. + """ x = 10.0 ** rng.uniform(lo, hi, size) return float(x) if size is None else x @@ -225,7 +231,9 @@ def kind(result): def assert_outcome(impl_func, oracle_func, args, expected_kind, **kwargs): - """`compare`, then assert the `kind` of the outcome (for edge-case tables).""" + """ + `compare`, then assert the `kind` of the outcome (for edge-case tables). + """ result = compare(impl_func, oracle_func, *args, **kwargs) assert kind(result) == expected_kind, f"{args}: {result!r}" return result @@ -279,7 +287,9 @@ def b1(*x): def shrink(args, index, size): - """Copy of the argument list with ``args[index]`` truncated to ``size``.""" + """ + Copy of the argument list with ``args[index]`` truncated to ``size``. + """ args = list(args) args[index] = args[index][:size] return args diff --git a/tests/oracle/hypergeo.py b/tests/oracle/hypergeo.py index 682922dd..3539dfbd 100644 --- a/tests/oracle/hypergeo.py +++ b/tests/oracle/hypergeo.py @@ -1,4 +1,6 @@ -"""Oracles for the special functions (``lib/hypergeo.c``).""" +""" +Oracles for the special functions (``lib/hypergeo.c``). +""" from math import pi @@ -22,7 +24,9 @@ # `scipy.special.gammaincinv`. The ufunc returns an `np.float64`, which is converted # so that callers divide by it with Python semantics (ZeroDivisionError). def _gammainc_inv(a, x): - """scipy.special.cython_special.gammaincinv""" + """ + scipy.special.cython_special.gammaincinv + """ return float(scipy.special.gammaincinv(a, x)) @@ -75,7 +79,9 @@ def _trigamma(x): def _betaln(p, q): - """Log of the beta function.""" + """ + Log of the beta function. + """ return lgamma(p) + lgamma(q) - lgamma(p + q) diff --git a/tests/oracle/implementations.py b/tests/oracle/implementations.py index d7a03598..7b5b0024 100644 --- a/tests/oracle/implementations.py +++ b/tests/oracle/implementations.py @@ -27,7 +27,9 @@ def _c_hypergeo(_tsdate): def _c_valid(func): - """The `_valid_*` oracles return a bool; the C functions a float.""" + """ + The `_valid_*` oracles return a bool; the C functions a float. + """ def valid(*args): return bool(func(*args)) @@ -137,7 +139,9 @@ def _c_rescaling(_tsdate): def _factor_arrays(factors): - """The fields of an ``EPFactors`` that the module takes, as a tuple of arrays.""" + """ + The fields of an ``EPFactors`` that the module takes, as a tuple of arrays. + """ return ( factors.node, factors.edge, diff --git a/tests/oracle/phasing.py b/tests/oracle/phasing.py index 6fd1e0ab..29967737 100644 --- a/tests/oracle/phasing.py +++ b/tests/oracle/phasing.py @@ -1,4 +1,6 @@ -"""Oracles for the phasing functions (``lib/phasing.c``).""" +""" +Oracles for the phasing functions (``lib/phasing.c``). +""" import numpy as np import tskit diff --git a/tests/oracle/prior.py b/tests/oracle/prior.py index 325c1a08..8c212508 100644 --- a/tests/oracle/prior.py +++ b/tests/oracle/prior.py @@ -1,4 +1,6 @@ -"""Oracles for the prior functions (``lib/prior.c``).""" +""" +Oracles for the prior functions (``lib/prior.c``). +""" import numpy as np diff --git a/tests/oracle/rescaling.py b/tests/oracle/rescaling.py index 7ad01efb..1fdd87ac 100644 --- a/tests/oracle/rescaling.py +++ b/tests/oracle/rescaling.py @@ -1,4 +1,6 @@ -"""Oracles for the rescaling functions (``lib/rescaling.c``).""" +""" +Oracles for the rescaling functions (``lib/rescaling.c``). +""" from math import inf diff --git a/tests/oracle/util.py b/tests/oracle/util.py index 86432fa2..8c556871 100644 --- a/tests/oracle/util.py +++ b/tests/oracle/util.py @@ -1,4 +1,6 @@ -"""Oracles for the tree sequence utilities (``lib/util.c``).""" +""" +Oracles for the tree sequence utilities (``lib/util.c``). +""" import numpy as np import tskit @@ -182,7 +184,9 @@ def _contains_unary_nodes( sequence_length, num_nodes, ): - """Whether a node outside ``nodes_mask`` has exactly one child in some tree.""" + """ + Whether a node outside ``nodes_mask`` has exactly one child in some tree. + """ assert edges_parent.size == edges_left.size == edges_right.size assert indexes_insert.size == indexes_remove.size == edges_parent.size diff --git a/tests/oracle/variational.py b/tests/oracle/variational.py index 0902c9ed..047c2cc7 100644 --- a/tests/oracle/variational.py +++ b/tests/oracle/variational.py @@ -1,4 +1,6 @@ -"""Oracles for the expectation propagation passes (``lib/variational.c``).""" +""" +Oracles for the expectation propagation passes (``lib/variational.c``). +""" import numpy as np import tskit diff --git a/tests/test_oracle_approx.py b/tests/test_oracle_approx.py index a0791e0d..3a1313d0 100644 --- a/tests/test_oracle_approx.py +++ b/tests/test_oracle_approx.py @@ -51,7 +51,9 @@ def parity(impl, name, args, expected_kind=None): def table(name, rows): - """``pytest.param`` rows of ``(name, args, expected_kind)`` with readable ids""" + """ + ``pytest.param`` rows of ``(name, args, expected_kind)`` with readable ids + """ return [pytest.param(name, args, kind, id=f"{name}{args}") for args, kind in rows] @@ -60,7 +62,9 @@ def floats(args): def natural(shape, rate): - """Natural parameters of a gamma""" + """ + Natural parameters of a gamma + """ return np.array([shape - 1.0, rate]) @@ -135,12 +139,16 @@ def gamma_quantiles(shape, rate, q1=0.25, q2=0.75): def z_below_one(z): - """The condition on z: below one, or for z < 0 that ``z / (z - 1)`` is below one""" + """ + The condition on z: below one, or for z < 0 that ``z / (z - 1)`` is below one + """ return bool(z / (z - 1) < 1.0 if z < 0.0 else z < 1.0) def hyp2f1_rows(): - """``(args, expected)`` for ``_valid_hyp2f1``: a, b, c positive and finite, z < 1""" + """ + ``(args, expected)`` for ``_valid_hyp2f1``: a, b, c positive and finite, z < 1 + """ rows = [((1.0, 1.0, 1.0, 0.0), True), ((10.0, 1.0, 1.0, 0.5), True)] # a > c is ok for i in range(3): for z in [0.5, -0.0]: @@ -665,7 +673,9 @@ def test_unphased_probability_out_of_range(self, impl): def flip_sign(rng, values, prob=0.12): - """Negate one of ``values`` with probability ``prob``, to give invalid input.""" + """ + Negate one of ``values`` with probability ``prob``, to give invalid input. + """ values = list(values) if rng.random() < prob: i = rng.integers(len(values)) @@ -674,12 +684,16 @@ def flip_sign(rng, values, prob=0.12): def draw_gamma(rng): - """Shape and rate of a node age""" + """ + Shape and rate of a node age + """ return float(rng.uniform(0.5, 30)), log_uniform(rng, -5, -2) def draw_edge(rng): - """Mutation count and mutational target size on an edge""" + """ + Mutation count and mutational target size on an edge + """ return float(rng.integers(0, 12)), log_uniform(rng, -4, -2) diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index 80ba1651..f3c835e1 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -36,7 +36,9 @@ def parity(impl, name, args, expected_kind=None): def table(name, rows): - """``pytest.param`` rows of ``(name, args, expected_kind)`` with readable ids""" + """ + ``pytest.param`` rows of ``(name, args, expected_kind)`` with readable ids + """ return [pytest.param(name, args, kind, id=f"{name}{args}") for args, kind in rows] @@ -405,7 +407,9 @@ def unity_formula(a, b, c, z): def unity_threshold(): - """Largest ``x < 1`` for which ``np.isclose(x, 1.0)`` fails, and the next one up""" + """ + Largest ``x < 1`` for which ``np.isclose(x, 1.0)`` fails, and the next one up + """ lo, hi = 0.5, 1.0 - 1e-9 # not close, close while nextafter(lo, 1.0) != hi: mid = lo + (hi - lo) / 2 @@ -417,7 +421,9 @@ def unity_threshold(): def negative_unity_threshold(): - """As `unity_threshold`, for ``z < 0`` mapped to ``z / (z - 1)``""" + """ + As `unity_threshold`, for ``z < 0`` mapped to ``z / (z - 1)`` + """ lo, hi = -1e3, -1e9 # not close, close while nextafter(lo, hi) != hi: mid = lo + (hi - lo) / 2 @@ -429,7 +435,9 @@ def negative_unity_threshold(): def unity_args_from_ep(a_i, b_i, a_j, b_j, y, mu): - """Arguments of `_hyp2f1_laplace` in the edge update of EP, for hugely negative z""" + """ + Arguments of `_hyp2f1_laplace` in the edge update of EP, for hugely negative z + """ return a_j, a_i + a_j + y, a_j + y + 1, (mu - b_j) / (mu + b_i) @@ -484,7 +492,9 @@ def test_grid(self, impl, name, args): class TestHyp2f1Unity: - """The unity limit (`_hyp2f1_unity`, reached when ``z`` is ``np.isclose`` to one)""" + """ + The unity limit (`_hyp2f1_unity`, reached when ``z`` is ``np.isclose`` to one) + """ @pytest.mark.parametrize("args", UNITY_CASES, ids=repr) def test_unity_branches(self, impl, args): diff --git a/tests/test_oracle_phasing.py b/tests/test_oracle_phasing.py index 2c1b13ac..61ea83db 100644 --- a/tests/test_oracle_phasing.py +++ b/tests/test_oracle_phasing.py @@ -15,7 +15,9 @@ def sweep_args(ts): - """Tree sequence arguments shared by the sweep-line functions""" + """ + Tree sequence arguments shared by the sweep-line functions + """ return [ ts.mutations_node, ts.sites_position[ts.mutations_site], @@ -153,7 +155,9 @@ def test_random(self, impl, small_ts_unphased, seed, fraction): @pytest.fixture(scope="module") def blocks(small_ts_unphased): - """Likelihoods and blocks for `reallocate_unphased`, with all individuals unphased""" + """ + Likelihoods and blocks for `reallocate_unphased`, with all individuals unphased + """ ts = small_ts_unphased unphased = np.full(ts.num_individuals, True) _, block_edges, mutation_blocks = block_singletons(ts, unphased) diff --git a/tests/test_oracle_prior.py b/tests/test_oracle_prior.py index 7956ca33..3ea98fbc 100644 --- a/tests/test_oracle_prior.py +++ b/tests/test_oracle_prior.py @@ -14,7 +14,9 @@ def coalescent_moments(num_tips): - """The argument that `conditional_coalescent_variance` passes""" + """ + The argument that `conditional_coalescent_variance` passes + """ rates = np.array( [2 / (i * (i - 1)) if i > 1 else 0.0 for i in range(1, num_tips + 1)] ) diff --git a/tests/test_oracle_rescaling.py b/tests/test_oracle_rescaling.py index 2ec211a0..d05ee8c8 100644 --- a/tests/test_oracle_rescaling.py +++ b/tests/test_oracle_rescaling.py @@ -33,7 +33,9 @@ def sim_ts(request): @pytest.fixture(scope="module") def eps(small_ts, small_ts_historical): - """`ExpectationPropagation` after a few iterations, for each simulated ts""" + """ + `ExpectationPropagation` after a few iterations, for each simulated ts + """ eps = {} for name, ts in [ ("small_ts", small_ts), @@ -51,7 +53,9 @@ def ep(request, eps): def rescale_inputs(ep): - """Arguments of `mutational_timescale`, as in `ExpectationPropagation.rescale`""" + """ + Arguments of `mutational_timescale`, as in `ExpectationPropagation.rescale` + """ nodes_time, _ = ep.node_moments() nodes_fixed = ep.node_constraints[:, 0] == ep.node_constraints[:, 1] return ( @@ -83,7 +87,9 @@ def count_args(ts, size_biased, node_is_sample=None): def piecewise_rates(rng, size, num_pieces, offset_range, rate_range): - """Poisson counts and offsets for `size` observations, with piecewise constant rate""" + """ + Poisson counts and offsets for `size` observations, with piecewise constant rate + """ offset = rng.uniform(*offset_range, size) rate = np.repeat(rng.uniform(*rate_range, num_pieces), size // num_pieces + 1)[:size] counts = rng.poisson(rate * offset).astype(float) diff --git a/tests/test_oracle_util.py b/tests/test_oracle_util.py index c67822d7..ed1f2dc7 100644 --- a/tests/test_oracle_util.py +++ b/tests/test_oracle_util.py @@ -97,7 +97,9 @@ def test_simulated(self, impl, sim_ts): def relabel_args(ts): - """Arguments of `_relabel_mutations_node`, with the nodes split as by `util`""" + """ + Arguments of `_relabel_mutations_node`, with the nodes split as by `util` + """ parent, child, order, _ = util._split_disjoint_nodes( ts.edges_parent, ts.edges_child, diff --git a/tests/test_oracle_variational.py b/tests/test_oracle_variational.py index 4ac75f15..f512bf86 100644 --- a/tests/test_oracle_variational.py +++ b/tests/test_oracle_variational.py @@ -48,14 +48,18 @@ @pytest.fixture(scope="module") def snaps(small_ts, small_ts_unphased, small_ts_historical): - """Snapshots of EP state two iterations in, by fixture name""" + """ + Snapshots of EP state two iterations in, by fixture name + """ tss = [small_ts, small_ts_unphased, small_ts_historical] return {name: ep_state.make_snapshot(ts, name) for name, ts in zip(TS_NAMES, tss)} @pytest.fixture(scope="module") def fresh(small_ts, small_ts_unphased, small_ts_historical): - """Snapshots of the initial EP state, by fixture name""" + """ + Snapshots of the initial EP state, by fixture name + """ tss = [small_ts, small_ts_unphased, small_ts_historical] return { name: ep_state.make_snapshot(ts, name, iterations=0) @@ -65,14 +69,18 @@ def fresh(small_ts, small_ts_unphased, small_ts_historical): @pytest.fixture(scope="module") def scaled_snap(snaps): - """``small_ts`` after a likelihood pass with a small cap, so that scales are not 1""" + """ + ``small_ts`` after a likelihood pass with a small cap, so that scales are not 1 + """ snap = snaps["small_ts"] state = ep_state.run_likelihood(variational, snap, False, max_shape=3.0) return snap.after_pass(state) def compare_runs(runner, impl, snap, *args, **kwargs): - """Run ``runner`` (an ``ep_state.run_*``) with the implementation and the oracle""" + """ + Run ``runner`` (an ``ep_state.run_*``) with the implementation and the oracle + """ actual = partial(runner, impl.variational) expected = partial(runner, variational) return compare(actual, expected, snap, *args, **kwargs) @@ -340,7 +348,9 @@ def test_real_edges(self, impl, snaps, ts_name, gap): class TestPropagateLikelihoodBranches: - """One edge (block) in each branch, with valid and failing projections""" + """ + One edge (block) in each branch, with valid and failing projections + """ CASES = { "valid": dict(), @@ -564,7 +574,9 @@ class TestPropagateLikelihoodTinyScale: @staticmethod def shrunk(snap, role, scale): - """Equivalent state with the scale of one node tiny, first used mid-pass""" + """ + Equivalent state with the scale of one node tiny, first used mid-pass + """ snap = snap.copy() nodes = snap.edge_parents if role == "parent" else snap.edge_children first = {} diff --git a/tests/test_python_c_variational.py b/tests/test_python_c_variational.py index b3a7492f..76ac7362 100644 --- a/tests/test_python_c_variational.py +++ b/tests/test_python_c_variational.py @@ -12,7 +12,9 @@ def factors(num_nodes=3, num_edges=2, num_blocks=1): - """The tuple of arrays that describes EP factors, for a small example.""" + """ + The tuple of arrays that describes EP factors, for a small example. + """ return ( np.zeros((num_nodes, 2, 2)), np.zeros((num_edges, 2, 2)), @@ -26,7 +28,9 @@ def factors(num_nodes=3, num_edges=2, num_blocks=1): def likelihood_args(**changes): - """Arguments of propagate_likelihood on two edges (2, 0) and (2, 1).""" + """ + Arguments of propagate_likelihood on two edges (2, 0) and (2, 1). + """ args = dict( edge_order=np.array([0, 1], dtype=np.int32), edges_parent=np.array([2, 2], dtype=np.int32), From 33e0c993d6a7114cea75da7e8b6a38412a58d832 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 09:49:01 -0800 Subject: [PATCH 18/56] Make the constraint check a predicate tsd_check_valid_constraints returned an error code that the Python wrapper translated back into a ValueError. It is now tsd_constraints_are_consistent, which reports the result through an output flag; ExpectationPropagation raises the ValueError (same message as before) itself. TSD_ERR_INCONSISTENT_CONSTRAINTS is removed and the two codes after it are renumbered. --- _tsdatemodule.c | 16 ++++++++-------- lib/err.c | 4 ---- lib/err.h | 5 ++--- lib/tests/tests.c | 25 ++++++++++++++++--------- lib/tsdate.h | 6 +++--- lib/variational.c | 14 ++++++++------ tests/oracle/implementations.py | 2 +- tests/oracle/variational.py | 14 ++++++-------- tests/test_oracle_variational.py | 23 ++++++++++++++--------- tests/test_python_c_variational.py | 12 ++++++------ tsdate/variational.py | 9 +++++---- 11 files changed, 69 insertions(+), 61 deletions(-) diff --git a/_tsdatemodule.c b/_tsdatemodule.c index eab5cdc8..257051c5 100644 --- a/_tsdatemodule.c +++ b/_tsdatemodule.c @@ -1923,15 +1923,16 @@ tsdate_assemble_factors(PyObject *Py_UNUSED(self), PyObject *args) return ret; } -/* check_valid_constraints(constraints, edges_parent, edges_child) */ +/* constraints_are_consistent(constraints, edges_parent, edges_child) -> bool */ static PyObject * -tsdate_check_valid_constraints(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_constraints_are_consistent(PyObject *Py_UNUSED(self), PyObject *args) { PyObject *ret = NULL; PyObject *obj[3]; PyArrayObject *constraints = NULL; PyArrayObject *edges_parent = NULL; PyArrayObject *edges_child = NULL; + int consistent = 0; int err; if (!PyArg_ParseTuple(args, "OOO", &obj[0], &obj[1], &obj[2])) { @@ -1952,15 +1953,14 @@ tsdate_check_valid_constraints(PyObject *Py_UNUSED(self), PyObject *args) goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_check_valid_constraints(ARRAY_LEN(constraints), ARRAY_LEN(edges_parent), - DOUBLES(constraints), IDS(edges_parent), IDS(edges_child)); + err = tsd_constraints_are_consistent(ARRAY_LEN(constraints), ARRAY_LEN(edges_parent), + DOUBLES(constraints), IDS(edges_parent), IDS(edges_child), &consistent); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); goto out; } - ret = Py_None; - Py_INCREF(ret); + ret = PyBool_FromLong(consistent); out: Py_XDECREF(constraints); Py_XDECREF(edges_parent); @@ -2252,8 +2252,8 @@ static PyMethodDef tsdate_methods[] = { "Multiply the EP factors by the node scales, in place." }, { "assemble_factors", (PyCFunction) tsdate_assemble_factors, METH_VARARGS, "The node posteriors implied by the EP factors." }, - { "check_valid_constraints", (PyCFunction) tsdate_check_valid_constraints, - METH_VARARGS, "Check that node age constraints are consistent with the edges." }, + { "constraints_are_consistent", (PyCFunction) tsdate_constraints_are_consistent, + METH_VARARGS, "Whether node age constraints are consistent with the edges." }, { "propagate_likelihood", (PyCFunction) tsdate_propagate_likelihood, METH_VARARGS, "Update the factors of the edge likelihoods, in place." }, { "propagate_prior", (PyCFunction) tsdate_propagate_prior, METH_VARARGS, diff --git a/lib/err.c b/lib/err.c index 6fefe932..6deb216a 100644 --- a/lib/err.c +++ b/lib/err.c @@ -140,10 +140,6 @@ tsd_strerror(int err) case TSD_ERR_INVALID_DAMPING: ret = "The damping factor is not greater than zero and at most one"; break; - case TSD_ERR_INCONSISTENT_CONSTRAINTS: - ret = "Node age constraints are inconsistent, some descendants have" - " lower bounds that exceed upper bounds of their ancestors."; - break; case TSD_ERR_TWIN_EDGE_IN_PHASED_PASS: ret = "An edge with the same parent and child can only be updated in an " "unphased pass"; diff --git a/lib/err.h b/lib/err.h index f2f93661..29de9ae7 100644 --- a/lib/err.h +++ b/lib/err.h @@ -81,9 +81,8 @@ extern "C" { #define TSD_ERR_INVALID_MIN_STEP -31 #define TSD_ERR_INVALID_NODE_POSTERIOR -32 #define TSD_ERR_INVALID_DAMPING -33 -#define TSD_ERR_INCONSISTENT_CONSTRAINTS -34 -#define TSD_ERR_TWIN_EDGE_IN_PHASED_PASS -35 -#define TSD_ERR_NONPOSITIVE_PENALTY -36 +#define TSD_ERR_TWIN_EDGE_IN_PHASED_PASS -34 +#define TSD_ERR_NONPOSITIVE_PENALTY -35 /* clang-format on */ #ifdef __GNUC__ diff --git a/lib/tests/tests.c b/lib/tests/tests.c index d56bedcd..b0e3417e 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -55,8 +55,7 @@ test_strerror(void) TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT, TSD_ERR_NO_POSTERIORS, TSD_ERR_INVALID_MAX_SHAPE, TSD_ERR_INVALID_MIN_STEP, TSD_ERR_INVALID_NODE_POSTERIOR, TSD_ERR_INVALID_DAMPING, - TSD_ERR_INCONSISTENT_CONSTRAINTS, TSD_ERR_TWIN_EDGE_IN_PHASED_PASS, - TSD_ERR_NONPOSITIVE_PENALTY }; + TSD_ERR_TWIN_EDGE_IN_PHASED_PASS, TSD_ERR_NONPOSITIVE_PENALTY }; const int num_codes = (int) (sizeof(codes) / sizeof(codes[0])); const char *msg_i; const char *msg_j; @@ -1283,18 +1282,26 @@ test_rescale_and_assemble_factors(void) } static void -test_check_valid_constraints(void) +test_constraints_are_consistent(void) { const tsd_id_t parent[2] = { 1, 2 }; const tsd_id_t child[2] = { 0, 1 }; const double valid[6] = { 0, 0, 1, 5, 2, INFINITY }; const double invalid[6] = { 3, 3, 1, 2, 2, INFINITY }; + int consistent; - CU_ASSERT_EQUAL(tsd_check_valid_constraints(3, 2, valid, parent, child), 0); - CU_ASSERT_EQUAL(tsd_check_valid_constraints(3, 0, valid, parent, child), 0); - CU_ASSERT_EQUAL(tsd_check_valid_constraints(3, 2, invalid, parent, child), - TSD_ERR_INCONSISTENT_CONSTRAINTS); - CU_ASSERT_EQUAL(tsd_check_valid_constraints(0, 0, valid, parent, child), 0); + CU_ASSERT_EQUAL( + tsd_constraints_are_consistent(3, 2, valid, parent, child, &consistent), 0); + CU_ASSERT_EQUAL(consistent, 1); + CU_ASSERT_EQUAL( + tsd_constraints_are_consistent(3, 0, valid, parent, child, &consistent), 0); + CU_ASSERT_EQUAL(consistent, 1); + CU_ASSERT_EQUAL( + tsd_constraints_are_consistent(3, 2, invalid, parent, child, &consistent), 0); + CU_ASSERT_EQUAL(consistent, 0); + CU_ASSERT_EQUAL( + tsd_constraints_are_consistent(0, 0, valid, parent, child, &consistent), 0); + CU_ASSERT_EQUAL(consistent, 1); } /* The branches of an EP pass: fixed child, fixed parent, free, both fixed. */ @@ -1498,7 +1505,7 @@ main(int argc, char **argv) { "test_piecewise_scale_posterior", test_piecewise_scale_posterior }, { "test_damp_and_rescale", test_damp_and_rescale }, { "test_rescale_and_assemble_factors", test_rescale_and_assemble_factors }, - { "test_check_valid_constraints", test_check_valid_constraints }, + { "test_constraints_are_consistent", test_constraints_are_consistent }, { "test_propagate_likelihood", test_propagate_likelihood }, { "test_propagate_prior", test_propagate_prior }, { "test_propagate_mutations", test_propagate_mutations }, diff --git a/lib/tsdate.h b/lib/tsdate.h index 160c22f2..55f0d709 100644 --- a/lib/tsdate.h +++ b/lib/tsdate.h @@ -321,9 +321,9 @@ int tsd_damp(const double x[2], const double y[2], double s, double *out); /* The factor that brings the shape of `x` between 1 / s and s; `s` is `max_shape`. */ int tsd_rescale(const double x[2], double s, double *out); /* `constraints` has num_nodes x 2 entries (lower and upper bound). */ -int tsd_check_valid_constraints(tsd_size_t num_nodes, tsd_size_t num_edges, - const double *constraints, const tsd_id_t *edges_parent, - const tsd_id_t *edges_child); +int tsd_constraints_are_consistent(tsd_size_t num_nodes, tsd_size_t num_edges, + const double *constraints, const tsd_id_t *edges_parent, const tsd_id_t *edges_child, + int *consistent); /* * Update the factors of the edges (blocks of unphased singletons, if `unphased`), * visited in the given order. `edges_parent`, `edges_child` and `likelihoods` (two diff --git a/lib/variational.c b/lib/variational.c index 46ac4e9b..fb5e991f 100644 --- a/lib/variational.c +++ b/lib/variational.c @@ -220,12 +220,13 @@ tsd_rescale(const double x[2], double s, double *out) } /* - * Check that the upper bound on node age is greater than the maximum lower bound for - * ages of descendants. + * Whether the upper bound on each node's age is at least the maximum lower bound of + * its descendants' ages. Writes 1 to `consistent` if so, 0 if not. */ int -tsd_check_valid_constraints(tsd_size_t num_nodes, tsd_size_t num_edges, - const double *constraints, const tsd_id_t *edges_parent, const tsd_id_t *edges_child) +tsd_constraints_are_consistent(tsd_size_t num_nodes, tsd_size_t num_edges, + const double *constraints, const tsd_id_t *edges_parent, const tsd_id_t *edges_child, + int *consistent) { int ret = 0; double *lower_max = NULL; @@ -245,10 +246,11 @@ tsd_check_valid_constraints(tsd_size_t num_nodes, tsd_size_t num_edges, c = edges_child[j]; lower_max[p] = tsd_max(lower_max[c], lower_max[p]); } + *consistent = 1; for (j = 0; j < num_nodes; j++) { if (lower_max[j] > constraints[2 * j + UPPER]) { - ret = tsd_trace_error(TSD_ERR_INCONSISTENT_CONSTRAINTS); - goto out; + *consistent = 0; + break; } } out: diff --git a/tests/oracle/implementations.py b/tests/oracle/implementations.py index 7b5b0024..d893c650 100644 --- a/tests/oracle/implementations.py +++ b/tests/oracle/implementations.py @@ -243,7 +243,7 @@ def propagate_mutations( _assemble_factors=assemble_factors, _damp=damp, _rescale=rescale, - _check_valid_constraints=_tsdate.check_valid_constraints, + _constraints_are_consistent=_tsdate.constraints_are_consistent, propagate_likelihood=propagate_likelihood, propagate_prior=propagate_prior, propagate_mutations=propagate_mutations, diff --git a/tests/oracle/variational.py b/tests/oracle/variational.py index 047c2cc7..850daa7e 100644 --- a/tests/oracle/variational.py +++ b/tests/oracle/variational.py @@ -121,17 +121,15 @@ def _rescale(x, s): return 1.0 -def _check_valid_constraints(constraints, edges_parent, edges_child): - # Check that upper-bound on node age is greater than maximum lower-bound - # for ages of descendants +def _constraints_are_consistent(constraints, edges_parent, edges_child): + """ + Whether the upper bound on each node's age is at least the maximum lower bound of + its descendants' ages. + """ lower_max = constraints[:, LOWER].copy() for p, c in zip(edges_parent, edges_child): lower_max[p] = max(lower_max[c], lower_max[p]) - if np.any(lower_max > constraints[:, UPPER]): - raise ValueError( - "Node age constraints are inconsistent, some descendants have" - " lower bounds that exceed upper bounds of their ancestors." - ) + return not np.any(lower_max > constraints[:, UPPER]) def propagate_likelihood( diff --git a/tests/test_oracle_variational.py b/tests/test_oracle_variational.py index f512bf86..cb0e543a 100644 --- a/tests/test_oracle_variational.py +++ b/tests/test_oracle_variational.py @@ -1,7 +1,7 @@ """ Equivalence of the C implementation of ``tsdate.variational`` with its oracle: the EP helpers (``EPFactors``, ``_damp``, ``_rescale``, ``_rescale_factors``, -``_check_valid_constraints``) and the passes ``propagate_likelihood``, +``_constraints_are_consistent``) and the passes ``propagate_likelihood``, ``propagate_prior`` and ``propagate_mutations``, plus whole sweeps. Inputs are snapshots of real EP state (``oracle.ep_state``) on the session fixtures, @@ -11,6 +11,7 @@ implementation alone is checked. """ +import re from functools import partial import numpy as np @@ -36,6 +37,7 @@ MIXPRIOR, TINY, UPPER, + ExpectationPropagation, ) up = np.nextafter @@ -281,7 +283,7 @@ def test_zero_shape_offset_cap_below_one(self, impl): impl.variational._rescale(f64(0, 1), 0.5) -class TestCheckValidConstraints: +class TestConstraintsAreConsistent: @staticmethod def check(impl, constraints, parents, children, valid): args = ( @@ -289,13 +291,9 @@ def check(impl, constraints, parents, children, valid): np.array(parents, dtype=np.int32), np.array(children, dtype=np.int32), ) - func = impl.variational._check_valid_constraints - result = compare(func, variational._check_valid_constraints, *args) - if valid: - assert result.exception is None - else: - assert kind(result) is ValueError - assert str(result.exception) == INCONSISTENT_MESSAGE + func = impl.variational._constraints_are_consistent + result = compare(func, variational._constraints_are_consistent, *args) + assert result.value is valid @pytest.mark.parametrize( ("constraints", "parents", "children", "valid"), @@ -346,6 +344,13 @@ def test_real_edges(self, impl, snaps, ts_name, gap): valid = gap == "equal" self.check(impl, constraints, snap.edge_parents, snap.edge_children, valid) + def test_production_raises(self): + constraints = np.array([[10.0, 10.0], [0.0, 0.0]]) + edge = np.array([1], dtype=np.int32), np.array([0], dtype=np.int32) + check = ExpectationPropagation._check_valid_constraints + with pytest.raises(ValueError, match=re.escape(INCONSISTENT_MESSAGE)): + check(constraints, *edge) + class TestPropagateLikelihoodBranches: """ diff --git a/tests/test_python_c_variational.py b/tests/test_python_c_variational.py index 76ac7362..b78f611e 100644 --- a/tests/test_python_c_variational.py +++ b/tests/test_python_c_variational.py @@ -121,16 +121,16 @@ def test_rescale_in_place(self): assert np.array_equal(f[0][:, 0, 0], [2.0, 3.0, 4.0]) -class TestCheckValidConstraints: +class TestConstraintsAreConsistent: def test_columns(self): with pytest.raises(ValueError, match="two columns"): - _tsdate.check_valid_constraints( + _tsdate.constraints_are_consistent( np.zeros((3, 3)), np.zeros(0, np.int32), np.zeros(0, np.int32) ) def test_edge_sizes(self): with pytest.raises(ValueError, match="same size"): - _tsdate.check_valid_constraints( + _tsdate.constraints_are_consistent( np.zeros((3, 2)), np.zeros(2, np.int32), np.zeros(1, np.int32) ) @@ -300,7 +300,7 @@ class TestArgumentParsing: [ "rescale_factors", "assemble_factors", - "check_valid_constraints", + "constraints_are_consistent", "propagate_likelihood", "propagate_prior", "propagate_mutations", @@ -310,9 +310,9 @@ def test_wrong_number_of_arguments(self, name): with pytest.raises(TypeError): getattr(_tsdate, name)() - def test_check_valid_constraints_wrong_dtype(self): + def test_constraints_are_consistent_wrong_dtype(self): with pytest.raises(TypeError): - _tsdate.check_valid_constraints( + _tsdate.constraints_are_consistent( np.zeros((3, 2)), np.zeros(0, np.int64), np.zeros(0, np.int32) ) diff --git a/tsdate/variational.py b/tsdate/variational.py index 9bdfa53e..eceb3890 100644 --- a/tsdate/variational.py +++ b/tsdate/variational.py @@ -149,10 +149,11 @@ class ExpectationPropagation: def _check_valid_constraints(constraints, edges_parent, edges_child): # Check that upper-bound on node age is greater than maximum lower-bound # for ages of descendants - try: - _tsdate.check_valid_constraints(constraints, edges_parent, edges_child) - except _tsdate.LibraryError as e: - raise ValueError(str(e)) from None + if not _tsdate.constraints_are_consistent(constraints, edges_parent, edges_child): + raise ValueError( + "Node age constraints are inconsistent, some descendants have" + " lower bounds that exceed upper bounds of their ancestors." + ) @staticmethod def _check_valid_inputs(ts, mutation_rate, allow_unary): From d555043ee8d38e6b52058d2392fbd97bf33de1e8 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 09:56:44 -0800 Subject: [PATCH 19/56] Compare C with the oracles exactly C agrees with the oracles bit for bit on every test, so the 4-ulp tolerance (assert_ulp_close and the maxulp parameters) is replaced by exact equality (assert_same_values). Also removes the unused helper both(), assert_inplace_close (the same comparison as assert_same_values on a list), and the fallback for an unbuilt extension around the LibraryError import. --- lib/approx.c | 2 +- lib/hypergeo.c | 2 +- lib/prior.c | 2 +- lib/rescaling.c | 3 +- lib/variational.c | 2 +- tests/oracle/helpers.py | 72 ++++++-------------------------- tests/test_oracle_approx.py | 2 +- tests/test_oracle_helpers.py | 22 ++++------ tests/test_oracle_hypergeo.py | 10 ++--- tests/test_oracle_phasing.py | 4 +- tests/test_oracle_variational.py | 10 ++--- 11 files changed, 38 insertions(+), 93 deletions(-) diff --git a/lib/approx.c b/lib/approx.c index e864d8c3..0e8a4ba5 100644 --- a/lib/approx.c +++ b/lib/approx.c @@ -24,7 +24,7 @@ /* * Gamma approximations and the moments of the EP updates. Operation order and libm - * calls match the oracles in tests/oracle, which the tests compare to the last bit. + * calls match the oracles in tests/oracle, which the tests compare exactly. * * A float division by zero returns TSD_ERR_ZERO_DIVISION at the divisions that the * tests show to be reachable (where the oracle raises ZeroDivisionError). The other diff --git a/lib/hypergeo.c b/lib/hypergeo.c index 3418e524..2c6810bd 100644 --- a/lib/hypergeo.c +++ b/lib/hypergeo.c @@ -25,7 +25,7 @@ /* * Numerically stable implementations of the Gauss hypergeometric function and related * special functions. Operation order and libm calls match the oracles in tests/oracle, - * which the tests compare to the last bit or two. + * which the tests compare exactly. * * A float division by zero returns TSD_ERR_ZERO_DIVISION at the divisions that the * tests show to be reachable (those of the poles of the polygamma functions and of the diff --git a/lib/prior.c b/lib/prior.c index 7379c161..295d3050 100644 --- a/lib/prior.c +++ b/lib/prior.c @@ -25,7 +25,7 @@ /* * Moments of node ages under the coalescent, conditional on the number of descendant * leaves. Operation order and libm calls match the oracles in tests/oracle, which the - * tests compare to the last bit or two. + * tests compare exactly. */ #include diff --git a/lib/rescaling.c b/lib/rescaling.c index b29737f7..e4cd7291 100644 --- a/lib/rescaling.c +++ b/lib/rescaling.c @@ -24,8 +24,7 @@ /* * Rescaling of time so that the mutation rate is constant. Operation order and libm - * calls match the oracles in tests/oracle, which the tests compare to the last bit or - * two. + * calls match the oracles in tests/oracle, which the tests compare exactly. * * Arrays whose size is not known beforehand are allocated with room for one more * element than needed, so that empty inputs still give valid pointers. diff --git a/lib/variational.c b/lib/variational.c index fb5e991f..6fb5633e 100644 --- a/lib/variational.c +++ b/lib/variational.c @@ -25,7 +25,7 @@ /* * The expectation propagation passes: the damping helpers, the passes over edges * (blocks of unphased singletons), the prior and the mutations. Operation order - * matches the oracles in tests/oracle, which the tests compare bit for bit. + * matches the oracles in tests/oracle, which the tests compare exactly. */ #include diff --git a/tests/oracle/helpers.py b/tests/oracle/helpers.py index 10bfb77a..be7a404c 100644 --- a/tests/oracle/helpers.py +++ b/tests/oracle/helpers.py @@ -4,11 +4,7 @@ import numpy as np import tskit - -try: - from _tsdate import LibraryError -except ImportError: # the extension has not been built - LibraryError = None +from _tsdate import LibraryError def _flatten(x, path=""): @@ -22,11 +18,10 @@ def _flatten(x, path=""): yield path, np.asarray(x, dtype=np.float64) -def assert_ulp_close(actual, desired, maxulp=4): +def assert_same_values(actual, desired): """ - Assert that two scalars, arrays, or (nested) tuples of them agree to within - ``maxulp`` units in the last place. NaNs must occur in the same places, and - equal infinities compare equal. Shapes and tuple structure must match. + Assert that two scalars, arrays, or (nested) tuples of them are equal, with NaNs in + the same places. Shapes and tuple structure must match. """ a_leaves = list(_flatten(actual)) d_leaves = list(_flatten(desired)) @@ -37,39 +32,9 @@ def assert_ulp_close(actual, desired, maxulp=4): assert a.shape == d.shape, ( f"shape mismatch at {path or 'value'}: {a.shape} vs {d.shape}" ) - nan_a, nan_d = np.isnan(a), np.isnan(d) - assert np.array_equal(nan_a, nan_d), ( - f"NaN pattern mismatch at {path or 'value'}:\n{a}\nvs\n{d}" - ) - inf_mask = np.isinf(a) | np.isinf(d) - assert np.array_equal(a[inf_mask], d[inf_mask]), ( - f"infinity mismatch at {path or 'value'}:\n{a}\nvs\n{d}" + assert np.array_equal(a, d, equal_nan=True), ( + f"values differ at {path or 'value'}:\nactual: {a}\ndesired: {d}" ) - ok = ~(nan_a | inf_mask) - if ok.any(): - try: - np.testing.assert_array_max_ulp(a[ok], d[ok], maxulp=maxulp) - except AssertionError as e: - raise AssertionError( - f"values differ by more than {maxulp} ulp at {path or 'value'}:" - f"\nactual: {a}\ndesired: {d}\n{e}" - ) from None - - -def assert_inplace_close(args_actual, args_desired, maxulp=4): - """ - Compare sequences of arguments after both implementations have modified them - in place (e.g. posterior arrays, ``EPFactors`` fields). Each element is - compared with `assert_ulp_close`; use ``(a.node, a.edge, ...)`` to pass fields. - """ - assert len(args_actual) == len(args_desired) - for i, (a, d) in enumerate(zip(args_actual, args_desired)): - try: - assert_ulp_close(a, d, maxulp=maxulp) - except AssertionError as e: - raise AssertionError( - f"argument {i} differs after in-place update: {e}" - ) from None INF = float("inf") @@ -101,7 +66,7 @@ def expected_error(exc_type): ``ValueError`` where the oracle asserts on array shapes and sizes. """ allowed = (exc_type,) - if LibraryError is not None and exc_type.__name__ in _LIBRARY_ERROR_NAMES: + if exc_type.__name__ in _LIBRARY_ERROR_NAMES: allowed += (LibraryError,) if exc_type is AssertionError: allowed += (ValueError,) @@ -173,10 +138,10 @@ def errors_match(actual, expected, check_message=True): return not check_message or str(actual) == str(expected) -def assert_same_outcome(actual, expected, maxulp=4, check_message=True): +def assert_same_outcome(actual, expected, check_message=True): """ Assert that two `Outcome` objects agree: both raise matching exceptions, or both - return values (and leave array arguments) within ``maxulp`` ulp. + return the same values and leave array arguments the same. """ if expected.exception is not None: assert actual.exception is not None, ( @@ -191,25 +156,25 @@ def assert_same_outcome(actual, expected, maxulp=4, check_message=True): assert actual.exception is None, ( f"implementation raised {actual.exception!r}, oracle returned {expected.value!r}" ) - assert_ulp_close(actual.value, expected.value, maxulp=maxulp) + assert_same_values(actual.value, expected.value) for i, (a, d) in enumerate(zip(actual.args, expected.args)): if isinstance(a, np.ndarray): try: - assert_ulp_close(a, d, maxulp=maxulp) + assert_same_values(a, d) except AssertionError as e: raise AssertionError( f"argument {i} differs after the call: {e}" ) from None -def compare(impl_func, oracle_func, *args, maxulp=4, check_message=True, **kwargs): +def compare(impl_func, oracle_func, *args, check_message=True, **kwargs): """ Call the implementation and the oracle on copies of ``args``, assert that their outcomes agree (`assert_same_outcome`), and return the oracle's `Outcome`. """ expected = outcome(oracle_func, *args, **kwargs) actual = outcome(impl_func, *args, **kwargs) - assert_same_outcome(actual, expected, maxulp=maxulp, check_message=check_message) + assert_same_outcome(actual, expected, check_message=check_message) return expected @@ -239,17 +204,6 @@ def assert_outcome(impl_func, oracle_func, args, expected_kind, **kwargs): return result -def both(impl_func, oracle_func, *args, maxulp=4): - """ - `compare`, returning the oracle's value; if both raise, re-raise the oracle's - exception (for use with ``pytest.raises``). - """ - result = compare(impl_func, oracle_func, *args, maxulp=maxulp) - if result.exception is not None: - raise result.exception - return result.value - - def make_ts(nodes, edges, mutations, length, num_individuals=0): """ Tree sequence from ``nodes`` ``(is_sample, time)`` or ``(is_sample, time, diff --git a/tests/test_oracle_approx.py b/tests/test_oracle_approx.py index 3a1313d0..83276b6e 100644 --- a/tests/test_oracle_approx.py +++ b/tests/test_oracle_approx.py @@ -1,6 +1,6 @@ """ Parity of the C implementation (``impl``) with the oracles in ``oracle/approx.py`` for -the gamma approximations: values to 4 ulp, NaN and infinity patterns, and which +the gamma approximations: exact values (including NaNs and infinities), and which exception is raised. Expected values always come from the oracle. Tables hold deliberate edge cases (boundaries of the ``_valid_*`` checks, degenerate gamma fits, regimes of the moment and projection functions); seeded random draws cover ranges diff --git a/tests/test_oracle_helpers.py b/tests/test_oracle_helpers.py index f1d47a11..db154f51 100644 --- a/tests/test_oracle_helpers.py +++ b/tests/test_oracle_helpers.py @@ -11,7 +11,7 @@ NAN, assert_outcome, assert_same_outcome, - assert_ulp_close, + assert_same_values, compare, errors_match, outcome, @@ -20,12 +20,6 @@ KLFailed = type("KLMinimizationFailedError", (Exception,), {}) -def ulps_up(x, n): - for _ in range(n): - x = np.nextafter(x, np.inf) - return x - - def returns(value, modify=None): def func(x): if modify is not None: @@ -42,30 +36,30 @@ def func(x): return func -class TestAssertUlpClose: +class TestAssertSameValues: @pytest.mark.parametrize( ("actual", "desired", "match"), [ - pytest.param(ulps_up(1.0, 5), 1.0, "ulp", id="five_ulp"), + pytest.param(np.nextafter(1.0, 2.0), 1.0, "differ", id="one_ulp"), pytest.param( - np.array([1.0, NAN]), np.array([NAN, 1.0]), "NaN", id="nan_place" + np.array([1.0, NAN]), np.array([NAN, 1.0]), "differ", id="nan_place" ), - pytest.param(1.0, NAN, "NaN", id="nan_vs_number"), - pytest.param(INF, -INF, "infinity", id="inf_sign"), + pytest.param(1.0, NAN, "differ", id="nan_vs_number"), + pytest.param(INF, -INF, "differ", id="inf_sign"), pytest.param((1.0, 2.0), (1.0, 2.0, 3.0), "structure", id="structure"), pytest.param(np.zeros(3), np.zeros(4), "shape", id="shape"), ], ) def test_fails(self, actual, desired, match): with pytest.raises(AssertionError, match=match): - assert_ulp_close(actual, desired) + assert_same_values(actual, desired) class TestAssertSameOutcome: @pytest.mark.parametrize( ("impl", "oracle", "match"), [ - pytest.param(returns(1.0), returns(2.0), "ulp", id="value"), + pytest.param(returns(1.0), returns(2.0), "differ", id="value"), pytest.param( raises(ValueError("a")), returns(1.0), "implementation", id="impl_raises" ), diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index f3c835e1..8dbab548 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -1,6 +1,6 @@ """ Parity of the C implementation (``impl``) with the oracles in ``oracle/hypergeo.py`` -for the special functions: values to 4 ulp, NaN and infinity patterns, and which +for the special functions: exact values (including NaNs and infinities), and which exception is raised (``AssertionError`` for the domain checks, ``ZeroDivisionError`` for float division by zero). Expected values always come from the oracle. Tables hold deliberate edge cases (poles, domain boundaries, both sides of a @@ -16,7 +16,7 @@ INF, NAN, assert_outcome, - assert_ulp_close, + assert_same_values, compare, log_uniform, ) @@ -250,8 +250,8 @@ def gammainc_inv_grid(): class TestGammaincInv: """ - `_gammainc_inv` is SciPy's ``gammaincinv`` (cephes ``igami``), which every - implementation calls; checked to 4 ulp, including away from the interior of the + `_gammainc_inv` is SciPy's ``gammaincinv`` (cephes ``igami``), which the C + library calls; checked exactly, including away from the interior of the domain (the result is a NaN, 0 or inf for invalid shapes and quantiles, with no exception). """ @@ -502,7 +502,7 @@ def test_unity_branches(self, impl, args): mapped = z / (z - 1) if z < 0 else z assert np.isclose(mapped, 1.0), "case must take the unity branch" result = parity(impl, "_hyp2f1_laplace", args) - assert_ulp_close(result.value, unity_formula(a, b, c, z)) + assert_same_values(result.value, unity_formula(a, b, c, z)) @pytest.mark.parametrize("sign", ["positive", "negative"]) @pytest.mark.parametrize("side", ["not_close", "close"]) diff --git a/tests/test_oracle_phasing.py b/tests/test_oracle_phasing.py index 61ea83db..9ae51d18 100644 --- a/tests/test_oracle_phasing.py +++ b/tests/test_oracle_phasing.py @@ -8,7 +8,7 @@ import pytest import tskit from oracle import phasing -from oracle.helpers import INF, NAN, assert_ulp_close, compare, make_ts, shrink +from oracle.helpers import INF, NAN, assert_same_values, compare, make_ts, shrink from tsdate.phasing import block_singletons from tsdate.rescaling import count_mutations @@ -149,7 +149,7 @@ def test_random(self, impl, small_ts_unphased, seed, fraction): # also the dtypes, which `compare` ignores, and the public wrapper actual = impl.phasing._block_singletons(*args) assert actual[1].dtype == actual[2].dtype == np.int32 - assert_ulp_close(actual, block_singletons(ts, unphased)) + assert_same_values(actual, block_singletons(ts, unphased)) assert result.value[1].dtype == np.int32 diff --git a/tests/test_oracle_variational.py b/tests/test_oracle_variational.py index cb0e543a..61866ecc 100644 --- a/tests/test_oracle_variational.py +++ b/tests/test_oracle_variational.py @@ -22,8 +22,8 @@ from oracle.helpers import ( INF, NAN, - assert_inplace_close, assert_same_outcome, + assert_same_values, compare, expected_error, f64, @@ -109,7 +109,7 @@ def test_constructor(self, impl, snaps): for field in ("_p", "_c", "_j", "_k"): assert np.array_equal(getattr(actual, field), getattr(expected, field)) fields = ("node", "edge", "block", "scale") - assert_inplace_close( + assert_same_values( [getattr(actual, f) for f in fields], [getattr(expected, f) for f in fields] ) @@ -129,7 +129,7 @@ def test_rescale_factors(self, impl, snaps, ts_name, scale): impl.variational._rescale_factors(actual) variational._rescale_factors(expected) fields = ("node", "edge", "block", "scale") - assert_inplace_close( + assert_same_values( [getattr(actual, f) for f in fields], [getattr(expected, f) for f in fields] ) @@ -564,9 +564,7 @@ def call(ns): ep_state.USE_EDGE_LIKELIHOOD, ) - result = compare( - lambda: call(impl.variational), lambda: call(variational), maxulp=0 - ) + result = compare(lambda: call(impl.variational), lambda: call(variational)) assert kind(result) is AssertionError From 5d557c4ad62b15a94acc41b780052fa53fc92638 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 10:05:39 -0800 Subject: [PATCH 20/56] Replace the gammaincinv stand-in in the C tests with a placeholder The C tests check return codes; numerical correctness is tested from Python against SciPy's gammaincinv. The series-and-bisection inverse in tests.c is replaced by a placeholder that ignores the shape, with inputs chosen to reach the same branches of the interquantile fit (and its iteration limit and derivative errors). The two rare branches of the incomplete gamma derivative that the stand-in reached incidentally are now tested directly. --- lib/tests/tests.c | 72 ++++++++++++++++------------------------------- 1 file changed, 24 insertions(+), 48 deletions(-) diff --git a/lib/tests/tests.c b/lib/tests/tests.c index b0e3417e..664fbb0e 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -163,9 +163,12 @@ test_betaln(void) static void test_gammainc_der(void) { - /* x == 0, x > xbig, gaussian, series and continued fraction regimes */ + /* + * x == 0, x > xbig, gaussian, series and continued fraction regimes, and a + * continued fraction that is rescaled to avoid overflow + */ const double points[][2] = { { 1.0, 0.0 }, { 5.0, 1e9 }, { 2000.0, 2000.0 }, - { 2.0, 1.5 }, { 5.0, 50.0 } }; + { 2.0, 1.5 }, { 5.0, 50.0 }, { 100.0, 110.0 } }; const int num_points = (int) (sizeof(points) / sizeof(points[0])); double value; int j, ret; @@ -175,10 +178,13 @@ test_gammainc_der(void) CU_ASSERT_EQUAL(ret, 0); CU_ASSERT(isfinite(value)); } - /* Series with a very small value: the result is truncated to zero */ + /* Series or continued fraction with a very small value: truncated to zero */ ret = tsd_gammainc_der(50.0, 1e-3, &value); CU_ASSERT_EQUAL(ret, 0); CU_ASSERT_EQUAL(value, 0.0); + ret = tsd_gammainc_der(5.0, 800.0, &value); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(value, 0.0); } static void @@ -307,43 +313,15 @@ test_hyp2f1_laplace_errors(void) } /* - * A stand-in for SciPy's gammaincinv: the inverse of the regularised lower - * incomplete gamma function by bisection, with the series expansion of the function. + * A placeholder for the gamma quantile function that ignores the shape. Quantiles + * x1, x2 in the ratio q2 / q1 match it for any shape, so that the Newton iteration of + * the interquantile fit stops after one step; other ratios fail. */ -static double -test_gammainc(double a, double x) -{ - double term = 1.0 / a; - double sum = term; - int n; - - for (n = 1; n < 1000; n++) { - term *= x / (a + n); - sum += term; - } - return sum * exp(a * log(x) - x - lgamma(a)); -} - static double test_gammaincinv(double a, double p) { - double lo = 0.0; - double hi = 1.0; - double mid; - int j; - - while (test_gammainc(a, hi) < p) { - hi *= 2; - } - for (j = 0; j < 100; j++) { - mid = (lo + hi) / 2; - if (test_gammainc(a, mid) < p) { - lo = mid; - } else { - hi = mid; - } - } - return (lo + hi) / 2; + (void) a; + return p; } static double @@ -420,24 +398,18 @@ static void test_approximate_gamma_iqr(void) { double out[2]; - double shape = 5.0; - double x1 = test_gammaincinv(shape, 0.25); - double x2 = test_gammaincinv(shape, 0.75); int ret; - /* Newton iteration recovers the shape */ - ret = tsd_approximate_gamma_iqr(0.25, 0.75, x1, x2, 50.0, test_gammaincinv, out); + /* Newton iteration */ + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 3.0, 50.0, test_gammaincinv, out); CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_DOUBLE_EQUAL(out[0], shape - 1, 1e-6); - /* capped shape: equal quantiles, a lower bound or an iteration above the cap */ + /* capped shape: equal quantiles, or a lower bound above the cap */ ret = tsd_approximate_gamma_iqr(0.25, 0.75, 3.0, 3.0, 50.0, test_gammaincinv, out); CU_ASSERT_EQUAL(ret, 0); CU_ASSERT_EQUAL(out[0], 49.0); - ret = tsd_approximate_gamma_iqr(0.25, 0.75, x1, x2, 2.0, test_gammaincinv, out); + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 1.1, 2.0, test_gammaincinv, out); CU_ASSERT_EQUAL(ret, 0); CU_ASSERT_EQUAL(out[0], 1.0); - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 1.1, 1e5, test_gammaincinv, out); - CU_ASSERT_EQUAL(ret, 0); /* errors */ ret = tsd_approximate_gamma_iqr(0.25, 0.75, 2.0, 1.0, 50.0, test_gammaincinv, out); CU_ASSERT_EQUAL(ret, TSD_ERR_UNSORTED_QUANTILES); @@ -447,8 +419,12 @@ test_approximate_gamma_iqr(void) CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); ret = tsd_approximate_gamma_iqr(0.25, 0.75, 0.0, 1.0, 50.0, test_gammaincinv, out); CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - ret = tsd_approximate_gamma_iqr(0.25, 1.0, 1.0, 2.0, 50.0, test_gammaincinv, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_NEGATIVE_SHAPE); + /* quantiles that the placeholder cannot match: no convergence, or a step outside + * the domain of the incomplete gamma derivative */ + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 2.9, 50.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_QUANTILE_MAX_ITERATIONS); + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 10.0, 50.0, test_gammaincinv, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); /* a quantile function that returns zero, or underflows when squared */ ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 2.0, 50.0, test_zero_inv, out); CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); From f036bf61a9ddba78dfb8c39cffb6a12e3448872f Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 10:09:08 -0800 Subject: [PATCH 21/56] Call _tsdate directly in the oracle tests The oracle tests call the _tsdate functions directly and compare them with the oracles. Where the C signature differs from the oracle's, a small adapter in the test module that needs it bridges the two: projection flattening and the bool result of the _valid_* checks in test_oracle_approx.py, and the EPFactors unpacking and size-two parameter pairs in test_oracle_variational.py. The ep_state runners take the propagate functions they call, and Snapshot.factors always builds the oracle EPFactors. --- tests/conftest.py | 9 - tests/oracle/__init__.py | 7 +- tests/oracle/ep_state.py | 77 ++++--- tests/oracle/implementations.py | 267 ------------------------ tests/test_oracle_approx.py | 105 +++++++--- tests/test_oracle_hypergeo.py | 56 ++--- tests/test_oracle_phasing.py | 97 +++++---- tests/test_oracle_prior.py | 25 +-- tests/test_oracle_rescaling.py | 127 ++++++----- tests/test_oracle_util.py | 83 ++++---- tests/test_oracle_variational.py | 348 +++++++++++++++++++++---------- 11 files changed, 561 insertions(+), 640 deletions(-) delete mode 100644 tests/oracle/implementations.py diff --git a/tests/conftest.py b/tests/conftest.py index db23c934..8d200e4e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,7 +1,6 @@ import msprime import numpy as np import pytest -from oracle.implementations import C def pytest_addoption(parser): @@ -37,14 +36,6 @@ def pytest_configure(config): ) -@pytest.fixture(scope="session") -def impl(): - """ - The C implementation, with the signatures of the oracles. - """ - return C - - @pytest.fixture def rng(): return np.random.default_rng(1024) diff --git a/tests/oracle/__init__.py b/tests/oracle/__init__.py index c6920d45..1de7829d 100644 --- a/tests/oracle/__init__.py +++ b/tests/oracle/__init__.py @@ -3,8 +3,9 @@ extension ``_tsdate``. Each function has an oracle in the module of the same name here, e.g. -``oracle.approx.moments``. Equivalence tests compare the C implementation -(``oracle.implementations.C``) against the oracle. +``oracle.approx.moments``. Equivalence tests (``tests/test_oracle_*.py``) call the +``_tsdate`` functions, through small adapters where the C signature differs, and +compare them against the oracles. Rules: @@ -12,7 +13,7 @@ C library. Where plain Python semantics differ from C (e.g. division by zero raising instead of giving inf/nan, numpy scalar semantics), a comment explains the compensation, once in the module header where it applies throughout. -* Oracles call other oracles, never the C implementation. +* Oracles call other oracles, never ``_tsdate``. * Names and signatures are those of ``tsdate``'s functions of the same names, where they exist. """ diff --git a/tests/oracle/ep_state.py b/tests/oracle/ep_state.py index 5ba1c108..531a6d9e 100644 --- a/tests/oracle/ep_state.py +++ b/tests/oracle/ep_state.py @@ -1,8 +1,8 @@ """ Expectation propagation state for the equivalence tests of ``tsdate.variational``: snapshots of real state from ``ExpectationPropagation`` (editable, so that tests can -force branches), one-edge snapshots, and runners that call the ``propagate_*`` -functions of a namespace on copies of a snapshot. +force branches), one-edge snapshots, and runners that call given ``propagate_*`` +functions (the oracles, or adapters of the C functions) on copies of a snapshot. """ import numpy as np @@ -20,6 +20,8 @@ ExpectationPropagation, ) +from .variational import EPFactors + # fixture name -> (singletons_phased, mutation_rate) SNAPSHOT_SPECS = { "small_ts": (True, 1e-8), @@ -51,7 +53,7 @@ class Snapshot: """ Copies of the arrays of an ``ExpectationPropagation`` after some iterations, so - that tests can edit them freely and rebuild fresh ``EPFactors`` of any class. + that tests can edit them freely and rebuild fresh ``EPFactors``. """ def __init__(self, ts, ep): @@ -74,11 +76,11 @@ def copy(self): setattr(new, k, v) return new - def factors(self, cls): + def factors(self): """ - New ``EPFactors`` of class ``cls`` holding a copy of the factors + New ``EPFactors`` holding a copy of the factors """ - factors = cls( + factors = EPFactors( self.node_constraints, self.edge_parents, self.edge_children, @@ -257,17 +259,23 @@ def likelihood_args(snap, unphased, order=None, likelihoods=None): def run_likelihood( - ns, snap, unphased, max_shape=1000.0, min_step=0.1, order=None, likelihoods=None + propagate_likelihood, + snap, + unphased, + max_shape=1000.0, + min_step=0.1, + order=None, + likelihoods=None, ): """ - Run `propagate_likelihood` of namespace ``ns`` on copies of ``snap``; return + Run ``propagate_likelihood`` on copies of ``snap``; return ``(posterior, lognorm, node, edge, block, scale)`` after the pass. """ args, lognorm = likelihood_args(snap, unphased, order, likelihoods) - factors = snap.factors(ns.EPFactors) + factors = snap.factors() posterior = snap.node_posterior.copy() lognorm = lognorm.copy() - ns.propagate_likelihood( + propagate_likelihood( *args, snap.node_constraints, posterior, @@ -280,22 +288,27 @@ def run_likelihood( return (posterior, lognorm, factors.node, factors.edge, factors.block, factors.scale) -def run_prior(ns, snap, free, max_shape=1000.0, em_maxitt=10, em_reltol=1e-8): +def run_prior( + propagate_prior, snap, free, max_shape=1000.0, em_maxitt=10, em_reltol=1e-8 +): """ - Run `propagate_prior`; return ``(posterior, node, scale)`` after the pass. + Run ``propagate_prior`` on copies of ``snap``; return + ``(posterior, node, scale)`` after the pass. """ - factors = snap.factors(ns.EPFactors) + factors = snap.factors() posterior = snap.node_posterior.copy() - ns.propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol) + propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol) return (posterior, factors.node, factors.scale) -def run_mutations(ns, snap, unphased, edges=None, posterior=None, order=None): +def run_mutations( + propagate_mutations, snap, unphased, edges=None, posterior=None, order=None +): """ - Run `propagate_mutations` on the phased (or unphased) mutations; return + Run ``propagate_mutations`` on the phased (or unphased) mutations; return ``(mutation_posterior, phase, node, edge, block, scale)``. """ - factors = snap.factors(ns.EPFactors) + factors = snap.factors() mut_posterior = np.full((snap.num_mutations, 2), np.nan) phase = np.ones(snap.num_mutations) phased = snap.mutation_blocks == tskit.NULL @@ -315,7 +328,7 @@ def run_mutations(ns, snap, unphased, edges=None, posterior=None, order=None): snap.edge_children, snap.edge_likelihoods, ) - ns.propagate_mutations( + propagate_mutations( order, mut_posterior, phase, @@ -335,14 +348,24 @@ def run_mutations(ns, snap, unphased, edges=None, posterior=None, order=None): ) -def run_sweeps(ns, snap, num_sweeps, max_shape=1000.0, min_step=0.1, em_maxitt=10): +def run_sweeps( + propagate_likelihood, + propagate_prior, + propagate_mutations, + rescale_factors, + snap, + num_sweeps, + max_shape=1000.0, + min_step=0.1, + em_maxitt=10, +): """ Run EP sweeps (the loop of `ExpectationPropagation.iterate`, then the mutation - passes of `infer`) with namespace ``ns`` from a copy of ``snap``. Returns, per + passes of `infer`) with the given functions from a copy of ``snap``. Returns, per sweep, ``(posterior, edge_logconst, block_logconst)`` copies, and the mutation ``(posterior, phase)``. """ - factors = snap.factors(ns.EPFactors) + factors = snap.factors() posterior = snap.node_posterior.copy() edge_logconst = snap.edge_logconst.copy() block_logconst = snap.block_logconst.copy() @@ -351,7 +374,7 @@ def run_sweeps(ns, snap, num_sweeps, max_shape=1000.0, min_step=0.1, em_maxitt=1 block_nodes = snap.block_nodes states = [] for _ in range(num_sweeps): - ns.propagate_likelihood( + propagate_likelihood( snap.block_order, block_nodes[ROOTWARD], block_nodes[LEAFWARD], @@ -364,7 +387,7 @@ def run_sweeps(ns, snap, num_sweeps, max_shape=1000.0, min_step=0.1, em_maxitt=1 min_step, USE_BLOCK_LIKELIHOOD, ) - ns.propagate_likelihood( + propagate_likelihood( snap.edge_order, snap.edge_parents, snap.edge_children, @@ -377,13 +400,13 @@ def run_sweeps(ns, snap, num_sweeps, max_shape=1000.0, min_step=0.1, em_maxitt=1 min_step, USE_EDGE_LIKELIHOOD, ) - ns.propagate_prior( + propagate_prior( snap.unconstrained_roots, posterior, factors, max_shape, em_maxitt, 1e-8 ) - ns._rescale_factors(factors) + rescale_factors(factors) states.append((posterior.copy(), edge_logconst.copy(), block_logconst.copy())) phased = snap.mutation_blocks == tskit.NULL - ns.propagate_mutations( + propagate_mutations( snap.mutation_order[~phased], mut_posterior, mut_phase, @@ -396,7 +419,7 @@ def run_sweeps(ns, snap, num_sweeps, max_shape=1000.0, min_step=0.1, em_maxitt=1 factors, USE_BLOCK_LIKELIHOOD, ) - ns.propagate_mutations( + propagate_mutations( snap.mutation_order[phased], mut_posterior, mut_phase, diff --git a/tests/oracle/implementations.py b/tests/oracle/implementations.py deleted file mode 100644 index d893c650..00000000 --- a/tests/oracle/implementations.py +++ /dev/null @@ -1,267 +0,0 @@ -""" -The C implementation, as a namespace with one attribute per tsdate module -(``hypergeo``, ``approx``, ``variational``, ``rescaling``, ``phasing``, ``util``, -``prior``) exposing the functions of ``_tsdate`` under the names and signatures of the -oracle modules, through thin adapters where the oracle's signature or return type -differs from the extension's. -""" - -import types - -import numpy as np - -from . import variational as oracle_variational - - -def _c_hypergeo(_tsdate): - return types.SimpleNamespace( - _digamma=_tsdate.digamma, - _trigamma=_tsdate.trigamma, - _betaln=_tsdate.betaln, - _gammainc_der=_tsdate.gammainc_der, - _gammainc_inv=_tsdate.gammainc_inv, - _hyperu_laplace=_tsdate.hyperu_laplace, - _hyp1f1_laplace=_tsdate.hyp1f1_laplace, - _hyp2f1_laplace=_tsdate.hyp2f1_laplace, - ) - - -def _c_valid(func): - """ - The `_valid_*` oracles return a bool; the C functions a float. - """ - - def valid(*args): - return bool(func(*args)) - - return valid - - -def _c_projection(func): - """ - Adapter for a projection. The C function takes flat arguments (the ages, and the - entries of the parameter arrays) and returns a flat tuple: the first result, then - the pairs of natural parameters; the oracle takes arrays and returns the first - result and one array per pair. - """ - - def projection(*args): - flat = [float(x) for arg in args for x in np.atleast_1d(arg)] - first, *rest = func(*flat) - pairs = [np.array(rest[i : i + 2]) for i in range(0, len(rest), 2)] - return (first, *pairs) - - return projection - - -def _c_approx(_tsdate): - # The helpers; each commented section is owned by the agent that ports it. - return types.SimpleNamespace( - approximate_log_moments=_tsdate.approximate_log_moments, - approximate_gamma_kl=_tsdate.approximate_gamma_kl, - approximate_gamma_mom=_tsdate.approximate_gamma_mom, - approximate_gamma_iqr=_tsdate.approximate_gamma_iqr, - average_gammas=_tsdate.average_gammas, - _valid_moments=_c_valid(_tsdate.valid_moments), - _valid_gamma=_c_valid(_tsdate.valid_gamma), - _valid_hyp1f1=_c_valid(_tsdate.valid_hyp1f1), - _valid_hyperu=_c_valid(_tsdate.valid_hyperu), - _valid_hyp2f1=_c_valid(_tsdate.valid_hyp2f1), - # approx: node moments - moments=_tsdate.moments, - rootward_moments=_tsdate.rootward_moments, - leafward_moments=_tsdate.leafward_moments, - unphased_moments=_tsdate.unphased_moments, - twin_moments=_tsdate.twin_moments, - sideways_moments=_tsdate.sideways_moments, - # approx: node projections - gamma_projection=_c_projection(_tsdate.gamma_projection), - leafward_projection=_c_projection(_tsdate.leafward_projection), - rootward_projection=_c_projection(_tsdate.rootward_projection), - unphased_projection=_c_projection(_tsdate.unphased_projection), - twin_projection=_c_projection(_tsdate.twin_projection), - sideways_projection=_c_projection(_tsdate.sideways_projection), - # approx: mutation moments - mutation_moments=_tsdate.mutation_moments, - mutation_rootward_moments=_tsdate.mutation_rootward_moments, - mutation_leafward_moments=_tsdate.mutation_leafward_moments, - mutation_unphased_moments=_tsdate.mutation_unphased_moments, - mutation_twin_moments=_tsdate.mutation_twin_moments, - mutation_sideways_moments=_tsdate.mutation_sideways_moments, - mutation_edge_moments=_tsdate.mutation_edge_moments, - mutation_block_moments=_tsdate.mutation_block_moments, - # approx: mutation projections - mutation_gamma_projection=_c_projection(_tsdate.mutation_gamma_projection), - mutation_leafward_projection=_c_projection(_tsdate.mutation_leafward_projection), - mutation_rootward_projection=_c_projection(_tsdate.mutation_rootward_projection), - mutation_edge_projection=_c_projection(_tsdate.mutation_edge_projection), - mutation_unphased_projection=_c_projection(_tsdate.mutation_unphased_projection), - mutation_twin_projection=_c_projection(_tsdate.mutation_twin_projection), - mutation_sideways_projection=_c_projection(_tsdate.mutation_sideways_projection), - mutation_block_projection=_c_projection(_tsdate.mutation_block_projection), - ) - - -def _c_phasing(_tsdate): - return types.SimpleNamespace( - _block_singletons=_tsdate.block_singletons, - reallocate_unphased=_tsdate.reallocate_unphased, - _mutation_frequency=_tsdate.mutation_frequency, - ) - - -def _c_util(_tsdate): - return types.SimpleNamespace( - _split_disjoint_nodes=_tsdate.split_disjoint_nodes, - _relabel_mutations_node=_tsdate.relabel_mutations_node, - _constrain_ages=_tsdate.constrain_ages, - _contains_unary_nodes=_tsdate.contains_unary_nodes, - ) - - -def _c_prior(_tsdate): - return types.SimpleNamespace( - _marginalize_over_ancestors=_tsdate.marginalize_over_ancestors, - conditional_coalescent_variance=_tsdate.conditional_coalescent_variance, - ) - - -def _c_rescaling(_tsdate): - return types.SimpleNamespace( - _fixed_changepoints=_tsdate.fixed_changepoints, - _poisson_changepoints=_tsdate.poisson_changepoints, - _count_mutations=_tsdate.count_mutations, - mutational_area=_tsdate.mutational_area, - mutational_timescale=_tsdate.mutational_timescale, - piecewise_scale_point_estimate=_tsdate.piecewise_scale_point_estimate, - piecewise_scale_posterior=_tsdate.piecewise_scale_posterior, - ) - - -def _factor_arrays(factors): - """ - The fields of an ``EPFactors`` that the module takes, as a tuple of arrays. - """ - return ( - factors.node, - factors.edge, - factors.block, - factors.scale, - factors._p, - factors._c, - factors._j, - factors._k, - ) - - -def _c_variational(_tsdate): - """ - The EP state stays in the numpy arrays of an ``EPFactors`` (the oracle's plain - class), which the module updates in place; the adapters unpack the object. - """ - - def check_size_two(*arrays): - if any(a.size != 2 for a in arrays): - raise ValueError("Natural parameters must have two entries") - - def damp(x, y, s): - check_size_two(x, y) - return _tsdate.damp(x[0], x[1], y[0], y[1], s) - - def rescale(x, s): - check_size_two(x) - return _tsdate.rescale(x[0], x[1], s) - - def rescale_factors(factors): - _tsdate.rescale_factors(_factor_arrays(factors)) - - def assemble_factors(factors): - return _tsdate.assemble_factors(_factor_arrays(factors)) - - def propagate_likelihood( - edge_order, - edges_parent, - edges_child, - likelihoods, - constraints, - posterior, - factors, - lognorm, - max_shape, - min_step, - unphased, - ): - _tsdate.propagate_likelihood( - edge_order, - edges_parent, - edges_child, - likelihoods, - constraints, - posterior, - _factor_arrays(factors), - lognorm, - max_shape, - min_step, - unphased, - ) - - def propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol): - _tsdate.propagate_prior( - free, posterior, _factor_arrays(factors), max_shape, em_maxitt, em_reltol - ) - - def propagate_mutations( - mutations_order, - mutations_posterior, - mutations_phase, - mutations_edge, - edges_parent, - edges_child, - likelihoods, - constraints, - posterior, - factors, - unphased, - ): - _tsdate.propagate_mutations( - mutations_order, - mutations_posterior, - mutations_phase, - mutations_edge, - edges_parent, - edges_child, - likelihoods, - constraints, - posterior, - _factor_arrays(factors), - unphased, - ) - - return types.SimpleNamespace( - EPFactors=oracle_variational.EPFactors, - _rescale_factors=rescale_factors, - _assemble_factors=assemble_factors, - _damp=damp, - _rescale=rescale, - _constraints_are_consistent=_tsdate.constraints_are_consistent, - propagate_likelihood=propagate_likelihood, - propagate_prior=propagate_prior, - propagate_mutations=propagate_mutations, - ) - - -def _c_namespace(): - import _tsdate - - return types.SimpleNamespace( - hypergeo=_c_hypergeo(_tsdate), - approx=_c_approx(_tsdate), - variational=_c_variational(_tsdate), - rescaling=_c_rescaling(_tsdate), - phasing=_c_phasing(_tsdate), - util=_c_util(_tsdate), - prior=_c_prior(_tsdate), - ) - - -C = _c_namespace() diff --git a/tests/test_oracle_approx.py b/tests/test_oracle_approx.py index 83276b6e..474c9e7f 100644 --- a/tests/test_oracle_approx.py +++ b/tests/test_oracle_approx.py @@ -1,6 +1,6 @@ """ -Parity of the C implementation (``impl``) with the oracles in ``oracle/approx.py`` for -the gamma approximations: exact values (including NaNs and infinities), and which +Parity of the gamma approximations of ``_tsdate`` with their oracles in +``oracle/approx.py``: exact values (including NaNs and infinities), and which exception is raised. Expected values always come from the oracle. Tables hold deliberate edge cases (boundaries of the ``_valid_*`` checks, degenerate gamma fits, regimes of the moment and projection functions); seeded random draws cover ranges @@ -17,6 +17,7 @@ import math +import _tsdate import numpy as np import pytest import scipy.special @@ -38,12 +39,53 @@ TINY = 5e-324 -def parity(impl, name, args, expected_kind=None): +def valid_check(func): """ - Compare ``impl.approx.(*args)`` with the oracle (returning the oracle's - outcome); optionally check its kind. + A ``_valid_*`` C function returning a bool, as its oracle does, instead of a float """ - func = getattr(impl.approx, name) + + def valid(*args): + return bool(func(*args)) + + return valid + + +def projection(func): + """ + A projection C function with the signature of its oracle. The C function takes + flat arguments (the ages, and the entries of the parameter arrays) and returns a + flat tuple: the first result, then the pairs of natural parameters; the oracle + takes arrays and returns the first result and one array per pair. + """ + + def project(*args): + flat = [float(x) for arg in args for x in np.atleast_1d(arg)] + first, *rest = func(*flat) + pairs = [np.array(rest[i : i + 2]) for i in range(0, len(rest), 2)] + return (first, *pairs) + + return project + + +def c_function(name): + """ + The C function for the oracle ``approx.`` (its name without the leading + underscore), with the oracle's signature + """ + func = getattr(_tsdate, name.removeprefix("_")) + if name.startswith("_valid_"): + return valid_check(func) + if name.endswith("_projection"): + return projection(func) + return func + + +def parity(name, args, expected_kind=None): + """ + Compare the C function for the oracle ``approx.`` with the oracle on + ``args`` (returning the oracle's outcome); optionally check its kind. + """ + func = c_function(name) oracle = getattr(approx, name) if expected_kind is None: return compare(func, oracle, *args) @@ -194,8 +236,8 @@ class TestValidChecks: ("name", "args", "expected"), [pytest.param(*row, id=f"{row[0]}{row[1]}") for row in VALID], ) - def test_valid(self, impl, name, args, expected): - result = parity(impl, name, args) + def test_valid(self, name, args, expected): + result = parity(name, args) assert bool(result.value) is expected @@ -343,25 +385,25 @@ def test_valid(self, impl, name, args, expected): class TestGammaApproximations: @pytest.mark.parametrize(("name", "args", "expected"), GAMMA_DOMAIN) - def test_domain(self, impl, name, args, expected): - parity(impl, name, args, expected) + def test_domain(self, name, args, expected): + parity(name, args, expected) @pytest.mark.parametrize( ("name", "args", "expected"), [p for p in GAMMA_DOMAIN if p.values[2] is KLMinimizationFailedError], ) - def test_error_messages(self, impl, name, args, expected): + def test_error_messages(self, name, args, expected): # the messages distinguish the failure modes - func = getattr(impl.approx, name) + func = c_function(name) with pytest.raises(expected_error(KLMinimizationFailedError)): func(*args) compare(func, getattr(approx, name), *args) @pytest.mark.parametrize("gap", [1e-17, 1e-10, 4e-5, 4.99e-5, 5e-5, 6e-5, 1e-3]) - def test_kl_asymptotic_threshold(self, impl, gap): + def test_kl_asymptotic_threshold(self, gap): # for alpha > 1e4 (gap < 5e-5) the lower bound alpha = 0.5 / gap is returned # without iterating; above, Newton's iteration refines it - result = parity(impl, "approximate_gamma_kl", (1.0, -gap), "finite") + result = parity("approximate_gamma_kl", (1.0, -gap), "finite") shape = result.value[0] if gap < 5e-5: assert shape + 1.0 == 0.5 / gap @@ -369,17 +411,17 @@ def test_kl_asymptotic_threshold(self, impl, gap): assert shape + 1.0 != 0.5 / gap @pytest.mark.parametrize(("shape", "max_shape"), GAMMA_IQR_FITS, ids=repr) - def test_iqr_fits(self, impl, shape, max_shape): + def test_iqr_fits(self, shape, max_shape): args = (*gamma_quantiles(shape, 0.001), max_shape) - parity(impl, "approximate_gamma_iqr", args, "finite") + parity("approximate_gamma_iqr", args, "finite") class TestAverageGammas: @pytest.mark.parametrize("label", list(AVERAGE_GAMMAS)) - def test_cases(self, impl, label): + def test_cases(self, label): shapes, rates, expected = AVERAGE_GAMMAS[label] args = np.array(shapes, dtype=float), np.array(rates, dtype=float) - parity(impl, "average_gammas", args, expected) + parity("average_gammas", args, expected) # --- moments and projections --- # @@ -587,7 +629,7 @@ def is_valid(mean, variance, prob=None): return bool(np.isfinite(mean) and np.isfinite(variance) and mean > 0 and variance > 0) -def check_projection(impl, name, args): +def check_projection(name, args): """ Compare a projection with the oracle, and check the contract on the oracle's result: the projection raises as its moment function does; otherwise it is NaN @@ -597,7 +639,7 @@ def check_projection(impl, name, args): """ moments, pairs, prob_index = PROJECTIONS[name] proj_args = projection_args(name, args) - result = parity(impl, name, proj_args) + result = parity(name, proj_args) moment_result = outcome(getattr(approx, moments), *moment_args(name, proj_args)) if moment_result.exception is not None: assert type(result.exception) is type(moment_result.exception) @@ -632,27 +674,28 @@ def check_projection(impl, name, args): class TestMoments: @pytest.mark.parametrize(("name", "label"), MOMENT_REGIMES) - def test_regimes(self, impl, name, label): - parity(impl, name, floats(REGIMES[name][label])) + def test_regimes(self, name, label): + parity(name, floats(REGIMES[name][label])) class TestProjections: @pytest.mark.parametrize(("name", "label"), PROJECTION_REGIMES) - def test_regimes(self, impl, name, label): + def test_regimes(self, name, label): moments = PROJECTIONS[name][0] - check_projection(impl, name, floats(REGIMES[moments][label])) + check_projection(name, floats(REGIMES[moments][label])) @pytest.mark.parametrize("name", list(PROJECTIONS)) - def test_inputs_are_not_modified(self, impl, name): + def test_inputs_are_not_modified(self, name): moments = PROJECTIONS[name][0] first_regime = next(iter(REGIMES[moments].values())) proj_args = projection_args(name, floats(first_regime)) copies = [a.copy() if isinstance(a, np.ndarray) else a for a in proj_args] - getattr(impl.approx, name)(*proj_args) + func = c_function(name) + func(*proj_args) for arg, copy in zip(proj_args, copies): np.testing.assert_array_equal(arg, copy) - def test_unphased_probability_out_of_range(self, impl): + def test_unphased_probability_out_of_range(self): # NOTE: current behaviour, possibly a bug: the Laplace # approximation can give a probability above one for finite mean and variance, # which the projection turns into NaN @@ -664,9 +707,9 @@ def test_unphased_probability_out_of_range(self, impl): 1.0, 4.811169071413665e-07, ) - parity(impl, "mutation_unphased_moments", args, "finite") + parity("mutation_unphased_moments", args, "finite") name = "mutation_unphased_projection" - parity(impl, name, projection_args(name, args), "nan") + parity(name, projection_args(name, args), "nan") # --- seeded random draws --- # @@ -809,7 +852,7 @@ class TestRandomDraws: @pytest.mark.parametrize("seed", [1, 2, 3]) @pytest.mark.parametrize(("name", "mode"), DRAWS) - def test_random_draws(self, impl, name, mode, seed): + def test_random_draws(self, name, mode, seed): rng = np.random.default_rng(seed) extreme = mode == "extreme" for i in range(30): @@ -823,6 +866,6 @@ def test_random_draws(self, impl, name, mode, seed): args = DRAW_GEOMETRY[name](rng, extreme) check = parity try: - check(impl, name, args) + check(name, args) except AssertionError as e: raise AssertionError(f"draw {i}: {name}{args}: {e}") from None diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index 8dbab548..f8789350 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -1,6 +1,6 @@ """ -Parity of the C implementation (``impl``) with the oracles in ``oracle/hypergeo.py`` -for the special functions: exact values (including NaNs and infinities), and which +Parity of the special functions of ``_tsdate`` with their oracles in +``oracle/hypergeo.py``: exact values (including NaNs and infinities), and which exception is raised (``AssertionError`` for the domain checks, ``ZeroDivisionError`` for float division by zero). Expected values always come from the oracle. Tables hold deliberate edge cases (poles, domain boundaries, both sides of a @@ -8,6 +8,7 @@ Accuracy of the approximations is measured in ``evaluation/numerical_accuracy.py``. """ +import _tsdate import numpy as np import pytest from oracle import hypergeo @@ -24,11 +25,12 @@ nextafter = np.nextafter -def parity(impl, name, args, expected_kind=None): +def parity(name, args, expected_kind=None): """ - Compare ``impl.hypergeo.(*args)`` with the oracle; optionally check kind. + Compare the C function for the oracle ``hypergeo.`` (its name without the + leading underscore) with the oracle on ``args``; optionally check the kind. """ - func = getattr(impl.hypergeo, name) + func = getattr(_tsdate, name.removeprefix("_")) oracle = getattr(hypergeo, name) if expected_kind is None: return compare(func, oracle, *args) @@ -119,15 +121,15 @@ def table(name, rows): class TestPolygamma: @pytest.mark.parametrize("name", ["_digamma", "_trigamma"]) @pytest.mark.parametrize("x", DIGAMMA_POINTS, ids=repr) - def test_matches_oracle(self, impl, name, x): - parity(impl, name, (x,)) + def test_matches_oracle(self, name, x): + parity(name, (x,)) @pytest.mark.parametrize( ("name", "args", "expected"), table("_digamma", POLYGAMMA_KINDS) + table("_trigamma", TRIGAMMA_KINDS), ) - def test_poles_and_nonfinite(self, impl, name, args, expected): - parity(impl, name, args, expected) + def test_poles_and_nonfinite(self, name, args, expected): + parity(name, args, expected) BETALN_POINTS = [ @@ -160,8 +162,8 @@ def test_poles_and_nonfinite(self, impl, name, args, expected): class TestBetaln: @pytest.mark.parametrize(("p", "q"), BETALN_POINTS, ids=repr) - def test_matches_oracle(self, impl, p, q): - parity(impl, "_betaln", (p, q)) + def test_matches_oracle(self, p, q): + parity("_betaln", (p, q)) # `_gammainc_der(p, x)`: regimes are x == 0, x > 1e8, p > 1e3 (gaussian), @@ -230,14 +232,14 @@ def test_matches_oracle(self, impl, p, q): class TestGammaincDer: @pytest.mark.parametrize(("p", "x"), GAMMAINC_DER_POINTS, ids=repr) - def test_matches_oracle(self, impl, p, x): - parity(impl, "_gammainc_der", (p, x)) + def test_matches_oracle(self, p, x): + parity("_gammainc_der", (p, x)) @pytest.mark.parametrize( ("name", "args", "expected"), table("_gammainc_der", GAMMAINC_DER_DOMAIN) ) - def test_domain(self, impl, name, args, expected): - parity(impl, name, args, expected) + def test_domain(self, name, args, expected): + parity(name, args, expected) def gammainc_inv_grid(): @@ -257,8 +259,8 @@ class TestGammaincInv: """ @pytest.mark.parametrize(("a", "q"), gammainc_inv_grid(), ids=repr) - def test_matches_oracle(self, impl, a, q): - parity(impl, "_gammainc_inv", (a, q)) + def test_matches_oracle(self, a, q): + parity("_gammainc_inv", (a, q)) HYPERU_DOMAIN = [ @@ -476,8 +478,8 @@ class TestLaplaceDomain: ("name", "args", "expected"), [p for name, rows in LAPLACE.items() for p in table(name, rows)], ) - def test_domain(self, impl, name, args, expected): - parity(impl, name, args, expected) + def test_domain(self, name, args, expected): + parity(name, args, expected) @pytest.mark.parametrize( ("name", "args"), @@ -487,8 +489,8 @@ def test_domain(self, impl, name, args, expected): for args in laplace_grid(name) ], ) - def test_grid(self, impl, name, args): - parity(impl, name, args) + def test_grid(self, name, args): + parity(name, args) class TestHyp2f1Unity: @@ -497,23 +499,23 @@ class TestHyp2f1Unity: """ @pytest.mark.parametrize("args", UNITY_CASES, ids=repr) - def test_unity_branches(self, impl, args): + def test_unity_branches(self, args): a, b, c, z = args mapped = z / (z - 1) if z < 0 else z assert np.isclose(mapped, 1.0), "case must take the unity branch" - result = parity(impl, "_hyp2f1_laplace", args) + result = parity("_hyp2f1_laplace", args) assert_same_values(result.value, unity_formula(a, b, c, z)) @pytest.mark.parametrize("sign", ["positive", "negative"]) @pytest.mark.parametrize("side", ["not_close", "close"]) - def test_switch_point(self, impl, sign, side): + def test_switch_point(self, sign, side): # the unity formula is used from the first np.isclose argument onwards if sign == "positive": not_close, close = unity_threshold() else: not_close, close = negative_unity_threshold() z = close if side == "close" else not_close - parity(impl, "_hyp2f1_laplace", (5.0, 7.0, 9.0, z), "finite") + parity("_hyp2f1_laplace", (5.0, 7.0, 9.0, z), "finite") def draw_polygamma(rng, extreme): @@ -606,11 +608,11 @@ class TestRandomDraws: @pytest.mark.parametrize("seed", [1, 2, 3]) @pytest.mark.parametrize("mode", ["typical", "extreme"]) @pytest.mark.parametrize("name", list(DRAWS)) - def test_random_draws(self, impl, name, mode, seed): + def test_random_draws(self, name, mode, seed): rng = np.random.default_rng(seed) for i in range(40): args = DRAWS[name](rng, mode == "extreme") try: - parity(impl, name, args) + parity(name, args) except AssertionError as e: raise AssertionError(f"draw {i}: {name}{args}: {e}") from None diff --git a/tests/test_oracle_phasing.py b/tests/test_oracle_phasing.py index 9ae51d18..c7185097 100644 --- a/tests/test_oracle_phasing.py +++ b/tests/test_oracle_phasing.py @@ -4,6 +4,7 @@ ``assert``. """ +import _tsdate import numpy as np import pytest import tskit @@ -109,45 +110,45 @@ def args(ts, unphased): return [unphased, ts.nodes_individual, *sweep_args(ts)] @staticmethod - def compare(impl, args): - return compare(impl.phasing._block_singletons, phasing._block_singletons, *args) + def compare(args): + return compare(_tsdate.block_singletons, phasing._block_singletons, *args) @pytest.mark.parametrize( ("nodes", "num_individuals", "edges", "mutations", "unphased", "expected_error"), BLOCK_EDGE_CASES, ) def test_edge_cases( - self, impl, nodes, num_individuals, edges, mutations, unphased, expected_error + self, nodes, num_individuals, edges, mutations, unphased, expected_error ): ts = make_ts(nodes, edges, mutations, 10.0, num_individuals) - result = self.compare(impl, self.args(ts, unphased)) + result = self.compare(self.args(ts, unphased)) assert result.error is expected_error @pytest.mark.parametrize( ("edges", "mutations", "unphased", "expected"), BLOCK_NUMBERING ) - def test_block_numbering(self, impl, edges, mutations, unphased, expected): + def test_block_numbering(self, edges, mutations, unphased, expected): ts = make_ts(NODES, edges, mutations, 10.0, 2) - _, _, mutation_block = self.compare(impl, self.args(ts, unphased)).value + _, _, mutation_block = self.compare(self.args(ts, unphased)).value assert mutation_block.tolist() == expected @pytest.mark.parametrize(("index", "size"), [(5, 3), (8, 3), (3, 1)]) - def test_size_mismatch(self, impl, index, size): + def test_size_mismatch(self, index, size): ts = make_ts(NODES, STAR, [(1, 0), (2, 1)], 10.0, 2) args = shrink(self.args(ts, [1, 1]), index, size) - result = self.compare(impl, args) + result = self.compare(args) assert result.error is AssertionError @pytest.mark.parametrize("fraction", [0.0, 0.5, 1.0]) @pytest.mark.parametrize("seed", range(2)) - def test_random(self, impl, small_ts_unphased, seed, fraction): + def test_random(self, small_ts_unphased, seed, fraction): ts = small_ts_unphased rng = np.random.default_rng(seed) unphased = rng.random(ts.num_individuals) < fraction args = self.args(ts, unphased) - result = self.compare(impl, args) + result = self.compare(args) # also the dtypes, which `compare` ignores, and the public wrapper - actual = impl.phasing._block_singletons(*args) + actual = _tsdate.block_singletons(*args) assert actual[1].dtype == actual[2].dtype == np.int32 assert_same_values(actual, block_singletons(ts, unphased)) assert result.value[1].dtype == np.int32 @@ -220,47 +221,45 @@ def blocks(small_ts_unphased): class TestReallocateUnphased: @staticmethod - def compare(impl, *args): - return compare( - impl.phasing.reallocate_unphased, phasing.reallocate_unphased, *args - ) + def compare(*args): + return compare(_tsdate.reallocate_unphased, phasing.reallocate_unphased, *args) @pytest.mark.parametrize( ("lik", "phase", "mutation_blocks", "blocks_edges", "expected_error"), REALLOCATE_SMALL, ) - def test_small(self, impl, lik, phase, mutation_blocks, blocks_edges, expected_error): - result = self.compare(impl, lik, phase, mutation_blocks, blocks_edges) + def test_small(self, lik, phase, mutation_blocks, blocks_edges, expected_error): + result = self.compare(lik, phase, mutation_blocks, blocks_edges) assert result.error is expected_error @pytest.mark.parametrize("mode", ["fractional", "mixed"]) @pytest.mark.parametrize("seed", range(3)) - def test_random(self, impl, blocks, seed, mode): + def test_random(self, blocks, seed, mode): ts, lik, mutation_blocks, block_edges = blocks rng = np.random.default_rng(seed) if mode == "fractional": phase = rng.uniform(0, 1, ts.num_mutations) else: phase = rng.choice([0.0, 1.0, 0.5, 0.25], ts.num_mutations) - self.compare(impl, lik, phase, mutation_blocks, block_edges) + self.compare(lik, phase, mutation_blocks, block_edges) @pytest.mark.parametrize("value", [1.5, -1e-9, INF, -INF]) - def test_phase_out_of_range(self, impl, blocks, value): + def test_phase_out_of_range(self, blocks, value): _, lik, mutation_blocks, block_edges = blocks phase = np.full(mutation_blocks.size, 0.5) phase[np.flatnonzero(mutation_blocks >= 0)[0]] = value - result = self.compare(impl, lik, phase, mutation_blocks, block_edges) + result = self.compare(lik, phase, mutation_blocks, block_edges) assert result.error is AssertionError @pytest.mark.parametrize("value", [NAN, 7.0]) - def test_phase_ignored_without_block(self, impl, blocks, value): + def test_phase_ignored_without_block(self, blocks, value): _, lik, mutation_blocks, block_edges = blocks phase = np.full(mutation_blocks.size, 0.5) phase[mutation_blocks == tskit.NULL] = value - result = self.compare(impl, lik, phase, mutation_blocks, block_edges) + result = self.compare(lik, phase, mutation_blocks, block_edges) assert result.error is None - def test_nan_phase(self, impl, blocks): + def test_nan_phase(self, blocks): # NOTE: current behaviour, possibly a bug: a NaN phase on a # blocked mutation is skipped, leaving its singleton unallocated, so the # final `np.isclose` check fails (a bare AssertionError). It only passes if @@ -268,32 +267,32 @@ def test_nan_phase(self, impl, blocks): _, lik, mutation_blocks, block_edges = blocks phase = np.full(mutation_blocks.size, 0.5) phase[np.flatnonzero(mutation_blocks >= 0)[0]] = NAN - result = self.compare(impl, lik, phase, mutation_blocks, block_edges) + result = self.compare(lik, phase, mutation_blocks, block_edges) assert result.error is AssertionError lik = lik.copy() lik[block_edges[0, 0], 0] -= 1.0 - result = self.compare(impl, lik, phase, mutation_blocks, block_edges) + result = self.compare(lik, phase, mutation_blocks, block_edges) assert result.error is None @pytest.mark.parametrize("case", ["no_mutations", "all_unblocked"]) - def test_blocks_without_singletons(self, impl, blocks, case): + def test_blocks_without_singletons(self, blocks, case): # likelihood mass on the block edges, but no mutation to allocate it ts, lik, _, block_edges = blocks size = 0 if case == "no_mutations" else ts.num_mutations phase = np.full(size, 0.5) mutation_blocks = np.full(size, tskit.NULL, dtype=np.int32) - result = self.compare(impl, lik, phase, mutation_blocks, block_edges) + result = self.compare(lik, phase, mutation_blocks, block_edges) assert result.error is AssertionError @pytest.mark.parametrize("case", ["phase", "blocks_transposed"]) - def test_size_mismatch(self, impl, blocks, case): + def test_size_mismatch(self, blocks, case): ts, lik, mutation_blocks, block_edges = blocks phase = np.full(ts.num_mutations, 0.5) if case == "phase": phase = phase[:-1] else: block_edges = np.ascontiguousarray(block_edges.T) - result = self.compare(impl, lik, phase, mutation_blocks, block_edges) + result = self.compare(lik, phase, mutation_blocks, block_edges) assert result.error is AssertionError @@ -323,9 +322,9 @@ def freq_ts(): class TestMutationFrequency: @staticmethod - def compare(impl, nodes_sample, args): + def compare(nodes_sample, args): return compare( - impl.phasing._mutation_frequency, + _tsdate.mutation_frequency, phasing._mutation_frequency, nodes_sample, *args, @@ -339,47 +338,47 @@ def nodes_sample(ts, members): return nodes_sample @pytest.mark.parametrize("members", SAMPLE_SETS) - def test_sample_sets(self, impl, freq_ts, members): + def test_sample_sets(self, freq_ts, members): nodes_sample = self.nodes_sample(freq_ts, members) - self.compare(impl, nodes_sample, sweep_args(freq_ts)) + self.compare(nodes_sample, sweep_args(freq_ts)) - def test_no_mutations(self, impl): + def test_no_mutations(self): ts = make_ts([(1, 0), (0, 1)], [(0, 10, 1, 0)], [], 10.0) - self.compare(impl, self.nodes_sample(ts, [[0]]), sweep_args(ts)) + self.compare(self.nodes_sample(ts, [[0]]), sweep_args(ts)) - def test_no_edges(self, impl): + def test_no_edges(self): # NOTE: current behaviour, possibly a bug: with no edges the # sweep is never entered, so every frequency is zero, even above a member ts = make_ts([(1, 0), (0, 1)], [], [(1, 0), (2, 1)], 10.0) - self.compare(impl, self.nodes_sample(ts, [[0, 1]]), sweep_args(ts)) + self.compare(self.nodes_sample(ts, [[0, 1]]), sweep_args(ts)) - def test_mutation_beyond_last_edge(self, impl): + def test_mutation_beyond_last_edge(self): nodes = [(1, 0), (1, 0), (0, 1)] edges = [(0, 5, 2, 0), (0, 5, 2, 1)] ts = make_ts(nodes, edges, [(1, 2), (7, 2)], 10.0) - self.compare(impl, self.nodes_sample(ts, [[0, 1]]), sweep_args(ts)) + self.compare(self.nodes_sample(ts, [[0, 1]]), sweep_args(ts)) - def test_mutation_at_breakpoint(self, impl): + def test_mutation_at_breakpoint(self): # a mutation exactly at a breakpoint belongs to the tree to its right ts = make_ts(FREQ_NODES, FREQ_EDGES, [(5, 4)], 10.0) - self.compare(impl, self.nodes_sample(ts, [[0, 1, 2]]), sweep_args(ts)) + self.compare(self.nodes_sample(ts, [[0, 1, 2]]), sweep_args(ts)) - def test_unsorted_mutations(self, impl, freq_ts): + def test_unsorted_mutations(self, freq_ts): order = np.array([3, 0, 4, 1, 2]) args = sweep_args(freq_ts) args[0], args[1] = args[0][order], args[1][order] - self.compare(impl, self.nodes_sample(freq_ts, [[0, 1, 2]]), args) + self.compare(self.nodes_sample(freq_ts, [[0, 1, 2]]), args) @pytest.mark.parametrize(("index", "size"), [(3, 3), (6, 3), (1, 2)]) - def test_size_mismatch(self, impl, freq_ts, index, size): + def test_size_mismatch(self, freq_ts, index, size): nodes_sample = np.ones((freq_ts.num_nodes, 1), dtype=bool) args = shrink(sweep_args(freq_ts), index, size) - result = self.compare(impl, nodes_sample, args) + result = self.compare(nodes_sample, args) assert result.error is AssertionError @pytest.mark.parametrize("num_sets", [1, 4]) @pytest.mark.parametrize("seed", range(2)) - def test_random(self, impl, small_ts, seed, num_sets): + def test_random(self, small_ts, seed, num_sets): ts = small_ts rng = np.random.default_rng(seed) members = [ @@ -389,7 +388,7 @@ def test_random(self, impl, small_ts, seed, num_sets): for _ in range(num_sets) ] nodes_sample = self.nodes_sample(ts, members) - result = self.compare(impl, nodes_sample, sweep_args(ts)) + result = self.compare(nodes_sample, sweep_args(ts)) # also the dtype, which `compare` ignores - actual = impl.phasing._mutation_frequency(nodes_sample, *sweep_args(ts)) + actual = _tsdate.mutation_frequency(nodes_sample, *sweep_args(ts)) assert actual.dtype == result.value.dtype == np.int32 diff --git a/tests/test_oracle_prior.py b/tests/test_oracle_prior.py index 3ea98fbc..4d5eda2f 100644 --- a/tests/test_oracle_prior.py +++ b/tests/test_oracle_prior.py @@ -3,6 +3,7 @@ with their oracles, and a pin of how ``tsdate`` calls the latter with a single tip. """ +import _tsdate import numpy as np import pytest import tskit @@ -42,55 +43,55 @@ def coalescent_moments(num_tips): class TestMarginalizeOverAncestors: @pytest.mark.parametrize("num_tips", [2, 3, 10, 60, 200]) @pytest.mark.parametrize("seed", range(2)) - def test_random(self, impl, seed, num_tips): + def test_random(self, seed, num_tips): rng = np.random.default_rng(seed) val = rng.uniform(0.1, 10.0, (num_tips, 2)) result = compare( - impl.prior._marginalize_over_ancestors, + _tsdate.marginalize_over_ancestors, prior._marginalize_over_ancestors, val, ) assert result.value.shape == (num_tips + 1, 2) @pytest.mark.parametrize("num_columns", [1, 3]) - def test_number_of_moments(self, impl, num_columns): + def test_number_of_moments(self, num_columns): val = np.random.default_rng(0).uniform(0.1, 10.0, (12, num_columns)) compare( - impl.prior._marginalize_over_ancestors, + _tsdate.marginalize_over_ancestors, prior._marginalize_over_ancestors, val, ) @pytest.mark.parametrize("num_tips", [3, 10, 100]) - def test_coalescent_moments(self, impl, num_tips): + def test_coalescent_moments(self, num_tips): compare( - impl.prior._marginalize_over_ancestors, + _tsdate.marginalize_over_ancestors, prior._marginalize_over_ancestors, coalescent_moments(num_tips), ) @pytest.mark.parametrize(("val", "expected_kind"), MARGINALIZE_EDGE_CASES) - def test_edge_cases(self, impl, val, expected_kind): + def test_edge_cases(self, val, expected_kind): assert_outcome( - impl.prior._marginalize_over_ancestors, + _tsdate.marginalize_over_ancestors, prior._marginalize_over_ancestors, (val,), expected_kind, ) - def test_input_not_modified(self, impl): + def test_input_not_modified(self): # `compare` passes copies, so call directly val = np.random.default_rng(0).uniform(0.1, 10.0, (8, 2)) copy = val.copy() - impl.prior._marginalize_over_ancestors(val) + _tsdate.marginalize_over_ancestors(val) assert np.array_equal(val, copy) class TestConditionalCoalescentVariance: @pytest.mark.parametrize("num_tips", [2, 3, 5, 20, 100, 250]) - def test_variance(self, impl, num_tips): + def test_variance(self, num_tips): result = compare( - impl.prior.conditional_coalescent_variance, + _tsdate.conditional_coalescent_variance, prior.conditional_coalescent_variance, num_tips, ) diff --git a/tests/test_oracle_rescaling.py b/tests/test_oracle_rescaling.py index d05ee8c8..f6fc98eb 100644 --- a/tests/test_oracle_rescaling.py +++ b/tests/test_oracle_rescaling.py @@ -4,6 +4,7 @@ degenerate inputs, and every ``assert``/``raise``. """ +import _tsdate import numpy as np import pytest from oracle import approx as oracle_approx @@ -120,9 +121,9 @@ def piecewise_rates(rng, size, num_pieces, offset_range, rate_range): class TestFixedChangepoints: @staticmethod - def compare(impl, counts, epochs): + def compare(counts, epochs): return compare( - impl.rescaling._fixed_changepoints, + _tsdate.fixed_changepoints, rescaling._fixed_changepoints, np.asarray(counts, dtype=float), epochs, @@ -131,9 +132,9 @@ def compare(impl, counts, epochs): @pytest.mark.parametrize( ("counts", "epochs", "expected_kind"), FIXED_CHANGEPOINT_CASES ) - def test_edge_cases(self, impl, counts, epochs, expected_kind): + def test_edge_cases(self, counts, epochs, expected_kind): assert_outcome( - impl.rescaling._fixed_changepoints, + _tsdate.fixed_changepoints, rescaling._fixed_changepoints, (np.asarray(counts, dtype=float), epochs), expected_kind, @@ -141,7 +142,7 @@ def test_edge_cases(self, impl, counts, epochs, expected_kind): @pytest.mark.parametrize("mode", ["typical", "zeros"]) @pytest.mark.parametrize("seed", range(3)) - def test_random(self, impl, seed, mode): + def test_random(self, seed, mode): rng = np.random.default_rng(seed) size = int(rng.integers(3, 300)) counts = rng.exponential(1.0, size) @@ -150,9 +151,9 @@ def test_random(self, impl, seed, mode): counts *= rng.random(size) < 0.6 counts[0] += 1.0 epochs = int(rng.integers(1, 120)) - result = self.compare(impl, counts, epochs) + result = self.compare(counts, epochs) # also the dtype, which `compare` ignores - actual = impl.rescaling._fixed_changepoints(counts, epochs) + actual = _tsdate.fixed_changepoints(counts, epochs) assert actual.dtype == result.value.dtype == np.int32 @@ -203,11 +204,11 @@ class TestPoissonChangepoints: POISSON_CASES, ) def test_edge_cases( - self, impl, counts, offset, penalty, min_counts, min_offset, expected_kind + self, counts, offset, penalty, min_counts, min_offset, expected_kind ): args = (f64(*counts), f64(*offset), penalty, min_counts, min_offset) assert_outcome( - impl.rescaling._poisson_changepoints, + _tsdate.poisson_changepoints, rescaling._poisson_changepoints, args, expected_kind, @@ -215,7 +216,7 @@ def test_edge_cases( @pytest.mark.parametrize("mode", ["typical", "extreme"]) @pytest.mark.parametrize("seed", range(3)) - def test_random(self, impl, seed, mode): + def test_random(self, seed, mode): rng = np.random.default_rng(seed) size = int(rng.integers(8, 45)) if mode == "typical": @@ -225,12 +226,12 @@ def test_random(self, impl, seed, mode): counts, offset = piecewise_rates(rng, size, 4, (0.2, 3.0), (0.2, 30.0)) args = (counts, offset, float(rng.choice([1.0, 50.0])), 10.0, 0.5) result = compare( - impl.rescaling._poisson_changepoints, + _tsdate.poisson_changepoints, rescaling._poisson_changepoints, *args, ) # also the dtype, which `compare` ignores - actual = impl.rescaling._poisson_changepoints(*args) + actual = _tsdate.poisson_changepoints(*args) assert actual.dtype == result.value.dtype == np.int32 @@ -271,50 +272,50 @@ def test_random(self, impl, seed, mode): class TestCountMutations: @staticmethod - def compare(impl, args): - return compare(impl.rescaling._count_mutations, rescaling._count_mutations, *args) + def compare(args): + return compare(_tsdate.count_mutations, rescaling._count_mutations, *args) @pytest.mark.parametrize("size_biased", [False, True]) @pytest.mark.parametrize(("nodes", "edges", "mutations", "length"), COUNT_CASES) - def test_edge_cases(self, impl, nodes, edges, mutations, length, size_biased): + def test_edge_cases(self, nodes, edges, mutations, length, size_biased): ts = make_ts(nodes, edges, mutations, length) - self.compare(impl, count_args(ts, size_biased)) + self.compare(count_args(ts, size_biased)) - def test_mutation_edges(self, impl): + def test_mutation_edges(self): # a mutation at a breakpoint belongs to the tree to its right; none above # the root; the edge id of a mutation is NULL if no edge covers it mutations = [(1, 0), (2, 0), (3, 1), (5, 2)] ts = make_ts(COUNT_NODES, COUNT_EDGES, mutations, 10.0) - _, mutation_edge = self.compare(impl, count_args(ts, False)).value + _, mutation_edge = self.compare(count_args(ts, False)).value assert mutation_edge.tolist() == [0, 0, 1, -1] @pytest.mark.parametrize("size_biased", [False, True]) - def test_no_samples_flagged(self, impl, size_biased): + def test_no_samples_flagged(self, size_biased): ts = make_ts(COUNT_NODES, COUNT_EDGES, [(1, 0)], 10.0) none = np.full(ts.num_nodes, False) - self.compare(impl, count_args(ts, size_biased, node_is_sample=none)) + self.compare(count_args(ts, size_biased, node_is_sample=none)) - def test_unsorted_mutations(self, impl): + def test_unsorted_mutations(self): mutations = [(1, 0), (2, 1), (6, 0), (8, 1), (9, 2)] ts = make_ts(COUNT_NODES, BREAKPOINT, mutations, 10.0) args = count_args(ts, False) order = np.array([3, 0, 4, 1, 2]) args[1], args[2] = args[1][order], args[2][order] - self.compare(impl, args) + self.compare(args) @pytest.mark.parametrize(("index", "size"), [(4, 1), (7, 1), (2, 1)]) - def test_size_mismatch(self, impl, index, size): + def test_size_mismatch(self, index, size): ts = make_ts(COUNT_NODES, COUNT_EDGES, [(1, 0), (2, 1)], 10.0) args = shrink(count_args(ts, False), index, size) - result = self.compare(impl, args) + result = self.compare(args) assert result.error is AssertionError @pytest.mark.parametrize("size_biased", [False, True]) - def test_simulated(self, impl, sim_ts, size_biased): + def test_simulated(self, sim_ts, size_biased): args = count_args(sim_ts, size_biased) - result = self.compare(impl, args) + result = self.compare(args) # also the dtype, which `compare` ignores - actual = impl.rescaling._count_mutations(*args) + actual = _tsdate.count_mutations(*args) assert actual[1].dtype == result.value[1].dtype == np.int32 @@ -378,35 +379,33 @@ def area_args(nodes_time, likelihoods, parents, children): class TestMutationalArea: @staticmethod - def compare(impl, *args): - return compare(impl.rescaling.mutational_area, rescaling.mutational_area, *args) + def compare(*args): + return compare(_tsdate.mutational_area, rescaling.mutational_area, *args) @pytest.mark.parametrize( ("nodes_time", "likelihoods", "parents", "children", "expected_error"), AREA_CASES ) - def test_edge_cases( - self, impl, nodes_time, likelihoods, parents, children, expected_error - ): + def test_edge_cases(self, nodes_time, likelihoods, parents, children, expected_error): args = area_args(nodes_time, likelihoods, parents, children) - result = self.compare(impl, *args) + result = self.compare(*args) assert result.error is expected_error @pytest.mark.parametrize("seed", range(2)) - def test_random(self, impl, sim_ts, seed): + def test_random(self, sim_ts, seed): ts = sim_ts rng = np.random.default_rng(seed) times = ts.nodes_time * rng.uniform(0.8, 1.2, ts.num_nodes) times[ts.samples()] = ts.nodes_time[ts.samples()] likelihoods = rng.uniform(0, 5, (ts.num_edges, 2)) args = (times, likelihoods, ts.edges_parent, ts.edges_child) - result = self.compare(impl, *args) + result = self.compare(*args) # also the dtype, which `compare` ignores - actual = impl.rescaling.mutational_area(*args) + actual = _tsdate.mutational_area(*args) assert actual[3].dtype == result.value[3].dtype == np.int32 - def test_simulated(self, impl, ep): + def test_simulated(self, ep): nodes_time, likelihoods, _, parents, children = rescale_inputs(ep) - self.compare(impl, nodes_time, likelihoods, parents, children) + self.compare(nodes_time, likelihoods, parents, children) def timescale_args(nodes_time, likelihoods, nodes_fixed, parents, children, k): @@ -505,28 +504,28 @@ def historical(k, fixed): class TestMutationalTimescale: @staticmethod - def compare(impl, *args): + def compare(*args): return compare( - impl.rescaling.mutational_timescale, rescaling.mutational_timescale, *args + _tsdate.mutational_timescale, rescaling.mutational_timescale, *args ) @pytest.mark.parametrize(("args", "expected"), TIMESCALE_CASES) - def test_edge_cases(self, impl, args, expected): + def test_edge_cases(self, args, expected): assert_outcome( - impl.rescaling.mutational_timescale, + _tsdate.mutational_timescale, rescaling.mutational_timescale, args, expected, ) - def test_zero_edge_span_message(self, impl): + def test_zero_edge_span_message(self): # the message is compared as well as the type args = timescale_args([0, 0, 1.0], [[2, 0], [1, 0]], [1, 1, 0], [2, 2], [0, 1], 1) - result = self.compare(impl, *args) + result = self.compare(*args) assert "Zero edge span in interval" in str(result.exception) @pytest.mark.parametrize("which", ["fixed", "parents", "likelihood_rows", "columns"]) - def test_size_mismatch(self, impl, which): + def test_size_mismatch(self, which): args = list(chain(2)) if which == "fixed": args[2] = b1(1, 1) @@ -536,12 +535,12 @@ def test_size_mismatch(self, impl, which): args[1] = np.ones((2, 2)) else: args[1] = np.ones((3, 3)) - result = self.compare(impl, *args) + result = self.compare(*args) assert result.error is AssertionError @pytest.mark.parametrize("max_intervals", [3, 1000]) @pytest.mark.parametrize("seed", range(2)) - def test_random(self, impl, sim_ts, seed, max_intervals): + def test_random(self, sim_ts, seed, max_intervals): ts = sim_ts rng = np.random.default_rng(seed) times = ts.nodes_time * rng.uniform(0.9, 1.1, ts.num_nodes) @@ -555,11 +554,11 @@ def test_random(self, impl, sim_ts, seed, max_intervals): fixed = np.full(ts.num_nodes, False) fixed[ts.samples()] = True args = (times, likelihoods, fixed, ts.edges_parent, ts.edges_child, max_intervals) - self.compare(impl, *args) + self.compare(*args) @pytest.mark.parametrize("max_intervals", [1, 10, 1000]) - def test_simulated(self, impl, ep, max_intervals): - self.compare(impl, *rescale_inputs(ep), max_intervals) + def test_simulated(self, ep, max_intervals): + self.compare(*rescale_inputs(ep), max_intervals) ORIGINAL = [0.0, 1.0, 3.0] @@ -615,29 +614,29 @@ class TestPiecewiseScalePointEstimate: ("estimate", "fixed", "original", "rescaled", "expected_kind"), POINT_ESTIMATE_CASES, ) - def test_edge_cases(self, impl, estimate, fixed, original, rescaled, expected_kind): + def test_edge_cases(self, estimate, fixed, original, rescaled, expected_kind): estimate = f64(*estimate) fixed = np.full(estimate.size, False) if fixed is None else b1(*fixed) args = (estimate, fixed, f64(*original), f64(*rescaled)) assert_outcome( - impl.rescaling.piecewise_scale_point_estimate, + _tsdate.piecewise_scale_point_estimate, rescaling.piecewise_scale_point_estimate, args, expected_kind, ) - def test_breaks_message(self, impl): + def test_breaks_message(self): # the message names the offending option, and is compared as well as the type args = (f64(0.5), b1(0), f64(0.0, 1.0, 1.0), f64(0.0, 2.0, 3.0)) result = compare( - impl.rescaling.piecewise_scale_point_estimate, + _tsdate.piecewise_scale_point_estimate, rescaling.piecewise_scale_point_estimate, *args, ) assert BREAKS_MSG in str(result.exception) @pytest.mark.parametrize("seed", range(3)) - def test_random(self, impl, seed): + def test_random(self, seed): rng = np.random.default_rng(seed) k = int(rng.integers(2, 12)) original = np.concatenate(([0.0], np.cumsum(rng.uniform(0.1, 5.0, k)))) @@ -645,7 +644,7 @@ def test_random(self, impl, seed): estimate = rng.uniform(0, original[-1] * 1.2, 40) fixed = rng.random(40) < 0.2 compare( - impl.rescaling.piecewise_scale_point_estimate, + _tsdate.piecewise_scale_point_estimate, rescaling.piecewise_scale_point_estimate, estimate, fixed, @@ -653,13 +652,13 @@ def test_random(self, impl, seed): rescaled, ) - def test_simulated(self, impl, ep): + def test_simulated(self, ep): nodes_time, likelihoods, nodes_fixed, parents, children = rescale_inputs(ep) original, rescaled = rescaling.mutational_timescale( nodes_time, likelihoods, nodes_fixed, parents, children, 10 ) compare( - impl.rescaling.piecewise_scale_point_estimate, + _tsdate.piecewise_scale_point_estimate, rescaling.piecewise_scale_point_estimate, nodes_time, nodes_fixed, @@ -789,17 +788,17 @@ def posterior_args( class TestPiecewiseScalePosterior: @pytest.mark.parametrize(("posteriors", "kwargs", "expected"), POSTERIOR_CASES) - def test_edge_cases(self, impl, posteriors, kwargs, expected): + def test_edge_cases(self, posteriors, kwargs, expected): args = posterior_args(posteriors, **kwargs) assert_outcome( - impl.rescaling.piecewise_scale_posterior, + _tsdate.piecewise_scale_posterior, rescaling.piecewise_scale_posterior, args, expected, ) @pytest.mark.parametrize("seed", range(3)) - def test_random(self, impl, seed): + def test_random(self, seed): rng = np.random.default_rng(seed) k = int(rng.integers(2, 10)) original = np.concatenate(([0.0], np.cumsum(rng.uniform(0.1, 5.0, k)))) @@ -815,19 +814,19 @@ def test_random(self, impl, seed): float(rng.choice([2.0, 100.0, 1000.0])), ) compare( - impl.rescaling.piecewise_scale_posterior, + _tsdate.piecewise_scale_posterior, rescaling.piecewise_scale_posterior, *args, ) - def test_simulated(self, impl, ep): + def test_simulated(self, ep): nodes_time, likelihoods, nodes_fixed, parents, children = rescale_inputs(ep) original, rescaled = rescaling.mutational_timescale( nodes_time, likelihoods, nodes_fixed, parents, children, 10 ) args = (ep.node_posterior, nodes_fixed, original, rescaled, 0.8, 1000.0) compare( - impl.rescaling.piecewise_scale_posterior, + _tsdate.piecewise_scale_posterior, rescaling.piecewise_scale_posterior, *args, ) diff --git a/tests/test_oracle_util.py b/tests/test_oracle_util.py index ed1f2dc7..adf703d2 100644 --- a/tests/test_oracle_util.py +++ b/tests/test_oracle_util.py @@ -3,6 +3,7 @@ sequences, degenerate inputs, and every ``assert``. """ +import _tsdate import numpy as np import pytest import tskit @@ -64,24 +65,24 @@ def sample_flags(ts): class TestSplitDisjointNodes: @staticmethod - def compare(impl, *args): - return compare(impl.util._split_disjoint_nodes, util._split_disjoint_nodes, *args) + def compare(*args): + return compare(_tsdate.split_disjoint_nodes, util._split_disjoint_nodes, *args) @pytest.mark.parametrize( ("parent", "child", "left", "right", "excluded", "expected"), SPLIT_CASES ) - def test_edge_cases(self, impl, parent, child, left, right, excluded, expected): + def test_edge_cases(self, parent, child, left, right, excluded, expected): args = (i32(*parent), i32(*child), f64(*left), f64(*right), b1(*excluded)) - _, _, _, split_nodes = self.compare(impl, *args).value + _, _, _, split_nodes = self.compare(*args).value assert split_nodes.tolist() == expected @pytest.mark.parametrize(("index", "size"), [(1, 1), (2, 1), (3, 1)]) - def test_size_mismatch(self, impl, index, size): + def test_size_mismatch(self, index, size): args = [i32(2, 2), i32(0, 1), f64(0, 0), f64(10, 10), b1(1, 1, 0)] - result = self.compare(impl, *shrink(args, index, size)) + result = self.compare(*shrink(args, index, size)) assert result.error is AssertionError - def test_simulated(self, impl, sim_ts): + def test_simulated(self, sim_ts): ts = sim_ts args = ( ts.edges_parent, @@ -90,9 +91,9 @@ def test_simulated(self, impl, sim_ts): ts.edges_right, sample_flags(ts), ) - result = self.compare(impl, *args) + result = self.compare(*args) # also the dtypes, which `compare` ignores - actual = impl.util._split_disjoint_nodes(*args) + actual = _tsdate.split_disjoint_nodes(*args) assert all(a.dtype == e.dtype == np.int32 for a, e in zip(actual, result.value)) @@ -149,38 +150,38 @@ def relabel_args(ts): class TestRelabelMutationsNode: @staticmethod - def compare(impl, args): + def compare(args): return compare( - impl.util._relabel_mutations_node, util._relabel_mutations_node, *args + _tsdate.relabel_mutations_node, util._relabel_mutations_node, *args ) @pytest.mark.parametrize( ("nodes", "edges", "mutations", "length", "expected_error"), RELABEL_CASES ) - def test_edge_cases(self, impl, nodes, edges, mutations, length, expected_error): + def test_edge_cases(self, nodes, edges, mutations, length, expected_error): ts = make_ts(nodes, edges, mutations, length) - result = self.compare(impl, relabel_args(ts)) + result = self.compare(relabel_args(ts)) assert result.error is expected_error - def test_mutations_on_split_nodes(self, impl): + def test_mutations_on_split_nodes(self): mutations = [(0.5, 0), (1, 2), (2, 3), (5, 0), (7, 2), (8, 3)] ts = make_ts(GAP_NODES, GAP_EDGES, mutations, 10.0) - result = self.compare(impl, relabel_args(ts)) + result = self.compare(relabel_args(ts)) # right-hand pieces of nodes 2 and 3 are the new nodes 4 and 5; the mutation # at 5 is in the gap, on the (unsplit) sample 0 assert result.value.tolist() == [0, 2, 3, 0, 4, 5] @pytest.mark.parametrize(("index", "size"), [(4, 2), (7, 2), (1, 1)]) - def test_size_mismatch(self, impl, index, size): + def test_size_mismatch(self, index, size): ts = make_ts(GAP_NODES, GAP_EDGES, [(1, 2), (7, 2)], 10.0) - result = self.compare(impl, shrink(relabel_args(ts), index, size)) + result = self.compare(shrink(relabel_args(ts), index, size)) assert result.error is AssertionError - def test_simulated(self, impl, sim_ts): + def test_simulated(self, sim_ts): args = relabel_args(sim_ts) - result = self.compare(impl, args) + result = self.compare(args) # also the dtype, which `compare` ignores - actual = impl.util._relabel_mutations_node(*args) + actual = _tsdate.relabel_mutations_node(*args) assert actual.dtype == result.value.dtype == np.int32 @@ -241,23 +242,23 @@ def args(times, fixed, parents, children, epsilon, max_iterations): ) @staticmethod - def compare(impl, args): - return compare(impl.util._constrain_ages, util._constrain_ages, *args) + def compare(args): + return compare(_tsdate.constrain_ages, util._constrain_ages, *args) @pytest.mark.parametrize("max_iterations", [0, 1, 1000]) @pytest.mark.parametrize("epsilon", [0.0, 1e-6, 0.5]) - def test_violation(self, impl, epsilon, max_iterations): - self.compare(impl, self.args(*VIOLATED, epsilon, max_iterations)) + def test_violation(self, epsilon, max_iterations): + self.compare(self.args(*VIOLATED, epsilon, max_iterations)) @pytest.mark.parametrize( ("times", "fixed", "parents", "children", "epsilon", "max_iterations", "kind"), CONSTRAIN_EDGE_CASES, ) def test_edge_cases( - self, impl, times, fixed, parents, children, epsilon, max_iterations, kind + self, times, fixed, parents, children, epsilon, max_iterations, kind ): args = self.args(times, fixed, parents, children, epsilon, max_iterations) - assert_outcome(impl.util._constrain_ages, util._constrain_ages, args, kind) + assert_outcome(_tsdate.constrain_ages, util._constrain_ages, args, kind) @pytest.mark.parametrize( "args", @@ -266,15 +267,15 @@ def test_edge_cases( pytest.param(([0, 1], [1, 0], [1], [0, 0]), id="children"), ], ) - def test_size_mismatch(self, impl, args): - result = self.compare(impl, self.args(*args, 0.1, 3)) + def test_size_mismatch(self, args): + result = self.compare(self.args(*args, 0.1, 3)) assert result.error is AssertionError - def test_input_not_modified(self, impl): + def test_input_not_modified(self): # `compare` passes copies, so call directly times = f64(*VIOLATED[0]) copy = times.copy() - out = impl.util._constrain_ages( + out = _tsdate.constrain_ages( times, b1(*VIOLATED[1]), i32(2, 3), i32(0, 2), 1e-6, 5 ) assert np.array_equal(times, copy) @@ -282,7 +283,7 @@ def test_input_not_modified(self, impl): @pytest.mark.parametrize("mode", ["iterated", "forced"]) @pytest.mark.parametrize("seed", range(2)) - def test_simulated(self, impl, sim_ts, seed, mode): + def test_simulated(self, sim_ts, seed, mode): ts = sim_ts rng = np.random.default_rng(seed) fixed = sample_flags(ts) @@ -300,7 +301,7 @@ def test_simulated(self, impl, sim_ts, seed, mode): epsilon, max_iterations, ) - self.compare(impl, args) + self.compare(args) # nodes, edges, expected for (samples skipped, samples not skipped) @@ -358,9 +359,9 @@ def test_simulated(self, impl, sim_ts, seed, mode): class TestContainsUnaryNodes: @staticmethod - def compare(impl, ts, mask): + def compare(ts, mask): return compare( - impl.util._contains_unary_nodes, + _tsdate.contains_unary_nodes, util._contains_unary_nodes, mask, ts.edges_parent, @@ -380,23 +381,23 @@ def mask(ts, skip_samples): return mask @pytest.mark.parametrize(("nodes", "edges", "skipped", "not_skipped"), UNARY_CASES) - def test_hand_built(self, impl, nodes, edges, skipped, not_skipped): + def test_hand_built(self, nodes, edges, skipped, not_skipped): ts = make_ts(nodes, edges, [], 10.0) - result = self.compare(impl, ts, self.mask(ts, True)) + result = self.compare(ts, self.mask(ts, True)) assert bool(result.value) is skipped - result = self.compare(impl, ts, self.mask(ts, False)) + result = self.compare(ts, self.mask(ts, False)) assert bool(result.value) is not_skipped - def test_all_nodes_masked(self, impl): + def test_all_nodes_masked(self): nodes = [(1, 0), (0, 1), (0, 2)] ts = make_ts(nodes, [(0, 10, 1, 0), (0, 10, 2, 1)], [], 10.0) - result = self.compare(impl, ts, np.full(ts.num_nodes, True)) + result = self.compare(ts, np.full(ts.num_nodes, True)) assert not result.value @pytest.mark.parametrize("skip_samples", [True, False]) @pytest.mark.parametrize("keep", [None, 3, 20]) - def test_simulated(self, impl, sim_ts, keep, skip_samples): + def test_simulated(self, sim_ts, keep, skip_samples): ts = sim_ts if keep is not None: ts = ts.simplify(ts.samples()[:keep], keep_unary=True) - self.compare(impl, ts, self.mask(ts, skip_samples)) + self.compare(ts, self.mask(ts, skip_samples)) diff --git a/tests/test_oracle_variational.py b/tests/test_oracle_variational.py index 61866ecc..24d85ddb 100644 --- a/tests/test_oracle_variational.py +++ b/tests/test_oracle_variational.py @@ -1,19 +1,23 @@ """ -Equivalence of the C implementation of ``tsdate.variational`` with its oracle: the -EP helpers (``EPFactors``, ``_damp``, ``_rescale``, ``_rescale_factors``, -``_constraints_are_consistent``) and the passes ``propagate_likelihood``, -``propagate_prior`` and ``propagate_mutations``, plus whole sweeps. +Equivalence of the expectation propagation functions of ``_tsdate`` with the oracle of +``tsdate.variational``: the EP helpers (``EPFactors``, ``_damp``, ``_rescale``, +``_rescale_factors``, ``_constraints_are_consistent``) and the passes +``propagate_likelihood``, ``propagate_prior`` and ``propagate_mutations``, plus whole +sweeps. The ``c_*`` adapters give the C functions the signatures of the oracles: the +EP state stays in the numpy arrays of an oracle ``EPFactors``, which the C functions +take as a tuple and update in place. Inputs are snapshots of real EP state (``oracle.ep_state``) on the session fixtures, with constraints edited to force branches, one-edge snapshots for each branch, and tables of boundary and failure cases. Expected values always come from the oracle. -Where the C library reports a division by zero and the oracle does not raise, the -implementation alone is checked. +Where the C library reports a division by zero and the oracle does not raise, the C +function alone is checked. """ import re from functools import partial +import _tsdate import numpy as np import pytest import tskit @@ -48,6 +52,115 @@ ) +def factor_arrays(factors): + """ + The arrays of an ``EPFactors`` that the C functions take, as a tuple + """ + return ( + factors.node, + factors.edge, + factors.block, + factors.scale, + factors._p, + factors._c, + factors._j, + factors._k, + ) + + +def check_size_two(*arrays): + if any(a.size != 2 for a in arrays): + raise ValueError("Natural parameters must have two entries") + + +def c_damp(x, y, s): + check_size_two(x, y) + return _tsdate.damp(x[0], x[1], y[0], y[1], s) + + +def c_rescale(x, s): + check_size_two(x) + return _tsdate.rescale(x[0], x[1], s) + + +def c_rescale_factors(factors): + _tsdate.rescale_factors(factor_arrays(factors)) + + +def c_assemble_factors(factors): + return _tsdate.assemble_factors(factor_arrays(factors)) + + +def c_propagate_likelihood( + edge_order, + edges_parent, + edges_child, + likelihoods, + constraints, + posterior, + factors, + lognorm, + max_shape, + min_step, + unphased, +): + _tsdate.propagate_likelihood( + edge_order, + edges_parent, + edges_child, + likelihoods, + constraints, + posterior, + factor_arrays(factors), + lognorm, + max_shape, + min_step, + unphased, + ) + + +def c_propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol): + _tsdate.propagate_prior( + free, posterior, factor_arrays(factors), max_shape, em_maxitt, em_reltol + ) + + +def c_propagate_mutations( + mutations_order, + mutations_posterior, + mutations_phase, + mutations_edge, + edges_parent, + edges_child, + likelihoods, + constraints, + posterior, + factors, + unphased, +): + _tsdate.propagate_mutations( + mutations_order, + mutations_posterior, + mutations_phase, + mutations_edge, + edges_parent, + edges_child, + likelihoods, + constraints, + posterior, + factor_arrays(factors), + unphased, + ) + + +# the C function and the oracle of the pass that each runner of ``ep_state`` calls +PASSES = { + ep_state.run_likelihood: (c_propagate_likelihood, variational.propagate_likelihood), + ep_state.run_prior: (c_propagate_prior, variational.propagate_prior), + ep_state.run_mutations: (c_propagate_mutations, variational.propagate_mutations), +} + + @pytest.fixture(scope="module") def snaps(small_ts, small_ts_unphased, small_ts_historical): """ @@ -75,21 +188,23 @@ def scaled_snap(snaps): ``small_ts`` after a likelihood pass with a small cap, so that scales are not 1 """ snap = snaps["small_ts"] - state = ep_state.run_likelihood(variational, snap, False, max_shape=3.0) + propagate = variational.propagate_likelihood + state = ep_state.run_likelihood(propagate, snap, False, max_shape=3.0) return snap.after_pass(state) -def compare_runs(runner, impl, snap, *args, **kwargs): +def compare_runs(runner, snap, *args, **kwargs): """ - Run ``runner`` (an ``ep_state.run_*``) with the implementation and the oracle + Run ``runner`` (an ``ep_state.run_*``) with the C function and with the oracle """ - actual = partial(runner, impl.variational) - expected = partial(runner, variational) + c_pass, oracle_pass = PASSES[runner] + actual = partial(runner, c_pass) + expected = partial(runner, oracle_pass) return compare(actual, expected, snap, *args, **kwargs) -def assert_run_kind(runner, impl, snap, expected_kind, *args, **kwargs): - result = compare_runs(runner, impl, snap, *args, **kwargs) +def assert_run_kind(runner, snap, expected_kind, *args, **kwargs): + result = compare_runs(runner, snap, *args, **kwargs) assert kind(result) == expected_kind @@ -98,10 +213,10 @@ def unphased_name(ts_name): class TestEPFactors: - def test_constructor(self, impl, snaps): + def test_constructor(self, snaps): snap = snaps["small_ts"] - actual = snap.factors(impl.variational.EPFactors) - expected = snap.factors(variational.EPFactors) + actual = snap.factors() + expected = snap.factors() for field in ("node", "edge", "block", "scale"): a, e = getattr(actual, field), getattr(expected, field) assert a.dtype == e.dtype @@ -117,39 +232,37 @@ def test_constructor(self, impl, snaps): class TestRescaleFactors: @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_unphased"]) @pytest.mark.parametrize("scale", ["seed0", "seed1", 1e-160, 1e100]) - def test_rescale_factors(self, impl, snaps, ts_name, scale): + def test_rescale_factors(self, snaps, ts_name, scale): snap = snaps[ts_name].copy() num_nodes = snap.node_posterior.shape[0] if isinstance(scale, str): rng = np.random.default_rng(int(scale[-1])) scale = rng.uniform(0.5, 2.0, num_nodes) snap.fields["scale"][:] = scale - actual = snap.factors(impl.variational.EPFactors) - expected = snap.factors(variational.EPFactors) - impl.variational._rescale_factors(actual) + actual = snap.factors() + expected = snap.factors() + c_rescale_factors(actual) variational._rescale_factors(expected) fields = ("node", "edge", "block", "scale") assert_same_values( [getattr(actual, f) for f in fields], [getattr(expected, f) for f in fields] ) - def test_rescale_factors_twice(self, impl, snaps): + def test_rescale_factors_twice(self, snaps): # the scale is reset to 1, so a second call changes nothing snap = snaps["small_ts"] - factors = snap.factors(impl.variational.EPFactors) - impl.variational._rescale_factors(factors) + factors = snap.factors() + c_rescale_factors(factors) once = [factors.node.copy(), factors.edge.copy(), factors.block.copy()] - impl.variational._rescale_factors(factors) + c_rescale_factors(factors) for before, after in zip(once, (factors.node, factors.edge, factors.block)): assert np.array_equal(before, after) @pytest.mark.parametrize("ts_name", TS_NAMES) - def test_assemble_factors(self, impl, snaps, scaled_snap, ts_name): + def test_assemble_factors(self, snaps, scaled_snap, ts_name): snap = scaled_snap if ts_name == "small_ts" else snaps[ts_name] - actual = impl.variational._assemble_factors( - snap.factors(impl.variational.EPFactors) - ) - expected = variational._assemble_factors(snap.factors(variational.EPFactors)) + actual = c_assemble_factors(snap.factors()) + expected = variational._assemble_factors(snap.factors()) assert_same_outcome(outcome(lambda: actual), outcome(lambda: expected)) @@ -238,26 +351,26 @@ class TestDamp: ("x", "y", "s", "expected_kind"), [pytest.param(*row[1:], id=row[0]) for row in DAMP_TABLE], ) - def test_table(self, impl, x, y, s, expected_kind): - result = compare(impl.variational._damp, variational._damp, x, y, s) + def test_table(self, x, y, s, expected_kind): + result = compare(c_damp, variational._damp, x, y, s) assert kind(result) == expected_kind @pytest.mark.parametrize("seed", range(8)) - def test_random(self, impl, seed): + def test_random(self, seed): rng = np.random.default_rng(seed) x = f64(rng.uniform(-0.9, 30), log_uniform(rng, -4, -1)) y = f64(rng.uniform(-5, 30), log_uniform(rng, -4, -1)) s = float(rng.uniform(0.05, 0.95)) - compare(impl.variational._damp, variational._damp, x, y, s) + compare(c_damp, variational._damp, x, y, s) @pytest.mark.parametrize("which", [0, 1]) - def test_infinite_posterior_zero_message(self, impl, which): + def test_infinite_posterior_zero_message(self, which): # Compiled code divides inf by 0.0 and raises; the oracle returns d = 1. Needs # an infinite posterior, which is unreachable without a prior failure. x = f64(1, 1) x[which] = INF with pytest.raises(expected_error(ZeroDivisionError)): - impl.variational._damp(x, f64(0, 0), 0.5) + c_damp(x, f64(0, 0), 0.5) class TestRescale: @@ -265,33 +378,33 @@ class TestRescale: ("x", "s", "expected_kind"), [pytest.param(*row[1:], id=row[0]) for row in RESCALE_TABLE], ) - def test_table(self, impl, x, s, expected_kind): - result = compare(impl.variational._rescale, variational._rescale, x, s) + def test_table(self, x, s, expected_kind): + result = compare(c_rescale, variational._rescale, x, s) assert kind(result) == expected_kind @pytest.mark.parametrize("seed", range(8)) - def test_random(self, impl, seed): + def test_random(self, seed): rng = np.random.default_rng(seed) x = f64(rng.uniform(-0.9, 3000), log_uniform(rng, -4, -1)) s = float(rng.choice([10.0, 100.0, 1000.0])) - compare(impl.variational._rescale, variational._rescale, x, s) + compare(c_rescale, variational._rescale, x, s) - def test_zero_shape_offset_cap_below_one(self, impl): + def test_zero_shape_offset_cap_below_one(self): # Compiled code divides by zero and raises; the oracle returns -inf. Direct # call only: `propagate_*` assert `max_shape >= 1`. with pytest.raises(expected_error(ZeroDivisionError)): - impl.variational._rescale(f64(0, 1), 0.5) + c_rescale(f64(0, 1), 0.5) class TestConstraintsAreConsistent: @staticmethod - def check(impl, constraints, parents, children, valid): + def check(constraints, parents, children, valid): args = ( np.array(constraints, dtype=np.float64), np.array(parents, dtype=np.int32), np.array(children, dtype=np.int32), ) - func = impl.variational._constraints_are_consistent + func = _tsdate.constraints_are_consistent result = compare(func, variational._constraints_are_consistent, *args) assert result.value is valid @@ -329,12 +442,12 @@ def check(impl, constraints, parents, children, valid): ] ], ) - def test_table(self, impl, constraints, parents, children, valid): - self.check(impl, constraints, parents, children, valid) + def test_table(self, constraints, parents, children, valid): + self.check(constraints, parents, children, valid) @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_historical"]) @pytest.mark.parametrize("gap", ["equal", "one_ulp"]) - def test_real_edges(self, impl, snaps, ts_name, gap): + def test_real_edges(self, snaps, ts_name, gap): # the lower bound of a child equals the upper bound of its parent, or exceeds it snap = snaps[ts_name] constraints = snap.node_constraints.copy() @@ -342,7 +455,7 @@ def test_real_edges(self, impl, snaps, ts_name, gap): constraints[c, LOWER] = 500.0 constraints[p, UPPER] = 500.0 if gap == "equal" else up(500.0, 0.0) valid = gap == "equal" - self.check(impl, constraints, snap.edge_parents, snap.edge_children, valid) + self.check(constraints, snap.edge_parents, snap.edge_children, valid) def test_production_raises(self): constraints = np.array([[10.0, 10.0], [0.0, 0.0]]) @@ -367,22 +480,24 @@ class TestPropagateLikelihoodBranches: @pytest.mark.parametrize("case", CASES) @pytest.mark.parametrize("branch", [b for b in BRANCHES if "both_fixed" not in b]) - def test_single_edge(self, impl, branch, case): + def test_single_edge(self, branch, case): snap = tiny_snapshot(branch, **self.CASES[case]) kwargs = dict(max_shape=1e300) # no posterior rescaling if "sideways" in branch and case == "projection_fails": # `sideways_moments` divides by zero for an astronomically large mutation # target: compiled code raises where the oracle returns NaN and skips. with pytest.raises(expected_error(ZeroDivisionError)): - ep_state.run_likelihood(impl.variational, snap, snap.unphased, **kwargs) + ep_state.run_likelihood( + c_propagate_likelihood, snap, snap.unphased, **kwargs + ) else: - compare_runs(ep_state.run_likelihood, impl, snap, snap.unphased, **kwargs) + compare_runs(ep_state.run_likelihood, snap, snap.unphased, **kwargs) - def test_twin_edge_in_phased_pass(self, impl): + def test_twin_edge_in_phased_pass(self): # p == c is only valid for blocks; `twin_projection` asserts `unphased`. # Direct call only: edges never have p == c in a tree sequence. snap = tiny_snapshot("twin") - result = compare_runs(ep_state.run_likelihood, impl, snap, False) + result = compare_runs(ep_state.run_likelihood, snap, False) assert kind(result) is AssertionError assert str(result.exception) == "Invalid update" @@ -405,7 +520,7 @@ def order(snap, unphased, subset=None): ("small_ts_unphased", 10.0, 0.5), ], ) - def test_natural(self, impl, snaps, ts_name, max_shape, min_step): + def test_natural(self, snaps, ts_name, max_shape, min_step): snap = snaps[ts_name] unphased = unphased_name(ts_name) counts = snap.branch_counts(unphased) @@ -413,7 +528,6 @@ def test_natural(self, impl, snaps, ts_name, max_shape, min_step): assert counts["both_fixed"] == counts["fixed_parent"] == 0 compare_runs( ep_state.run_likelihood, - impl, snap, unphased, max_shape=max_shape, @@ -423,16 +537,16 @@ def test_natural(self, impl, snaps, ts_name, max_shape, min_step): @pytest.mark.parametrize( "ts_name", ["small_ts", "small_ts_unphased", "small_ts_historical"] ) - def test_forced_fixed_nodes(self, impl, snaps, ts_name): + def test_forced_fixed_nodes(self, snaps, ts_name): # every branch: both nodes fixed (skipped), one fixed, both free unphased = unphased_name(ts_name) snap = ep_state.fixed_internal_snapshot(snaps[ts_name], unphased) counts = snap.branch_counts(unphased) assert all(v > 0 for k, v in counts.items() if k != "twin" or unphased) - compare_runs(ep_state.run_likelihood, impl, snap, unphased) + compare_runs(ep_state.run_likelihood, snap, unphased) @pytest.mark.parametrize("kind_of_order", ["empty", "partial_and_repeated"]) - def test_order(self, impl, snaps, kind_of_order): + def test_order(self, snaps, kind_of_order): # the order array is arbitrary: empty, or any subset with repeats snap = snaps["small_ts"] if kind_of_order == "empty": @@ -440,7 +554,7 @@ def test_order(self, impl, snaps, kind_of_order): else: order = snap.edge_order[100:140] order = np.concatenate((order, order[::-1], order[:5])).astype(np.int32) - compare_runs(ep_state.run_likelihood, impl, snap, False, order=order) + compare_runs(ep_state.run_likelihood, snap, False, order=order) @pytest.mark.parametrize( "max_shape", @@ -450,13 +564,12 @@ def test_order(self, impl, snaps, kind_of_order): ids=lambda v: f"max_shape={v:g}", ) @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_unphased"]) - def test_max_shape(self, impl, snaps, ts_name, max_shape): + def test_max_shape(self, snaps, ts_name, max_shape): snap = snaps[ts_name] unphased = unphased_name(ts_name) order = self.order(snap, unphased, self.SUBSET) compare_runs( ep_state.run_likelihood, - impl, snap, unphased, max_shape=max_shape, @@ -469,14 +582,13 @@ def test_max_shape(self, impl, snaps, ts_name, max_shape): ids=lambda v: f"min_step={v:g}", ) @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_unphased"]) - def test_min_step(self, impl, snaps, ts_name, min_step): + def test_min_step(self, snaps, ts_name, min_step): snap = snaps[ts_name] unphased = unphased_name(ts_name) order = self.order(snap, unphased, self.SUBSET) # a small cap makes passes difficult, so that damping is exercised compare_runs( ep_state.run_likelihood, - impl, snap, unphased, min_step=min_step, @@ -485,7 +597,7 @@ def test_min_step(self, impl, snaps, ts_name, min_step): ) @pytest.mark.parametrize("multiplier", [1e12, 1e300], ids=lambda v: f"y*{v:g}") - def test_extreme_counts(self, impl, snaps, multiplier): + def test_extreme_counts(self, snaps, multiplier): # 1e12: projection failures are skipped (NaN lognorm). 1e300: a posterior # becomes NaN and the next `_damp` asserts `0 < x[0] + 1`, # reachable from real data (~1e300 mutations on an edge). @@ -494,7 +606,6 @@ def test_extreme_counts(self, impl, snaps, multiplier): order = snap.edge_order[: self.SUBSET.stop] compare_runs( ep_state.run_likelihood, - impl, snap, False, order=order, @@ -514,14 +625,13 @@ def test_extreme_counts(self, impl, snaps, multiplier): pytest.param(dict(min_step=NAN), id="min_step_nan"), ], ) - def test_invalid_parameters(self, impl, snaps, kwargs): + def test_invalid_parameters(self, snaps, kwargs): # reachable from user input (`max_shape`, `min_step` of `iterate`/`infer`): # parameter errors in the C library, not internal asserts snap = snaps["small_ts"] order = snap.edge_order[:10] assert_run_kind( ep_state.run_likelihood, - impl, snap, AssertionError, False, @@ -533,7 +643,7 @@ def test_invalid_parameters(self, impl, snaps, kwargs): "change", ["children", "likelihoods", "constraints", "factors_larger"], ) - def test_shape_mismatches(self, impl, snaps, change): + def test_shape_mismatches(self, snaps, change): # direct calls only: these are checked while parsing arguments in C snap = snaps["small_ts"] args, lognorm = ep_state.likelihood_args(snap, False) @@ -549,22 +659,25 @@ def test_shape_mismatches(self, impl, snaps, change): parents, children = parents[:-1], children[:-1] likelihoods = likelihoods[:-1] - def call(ns): - ns.propagate_likelihood( + def call(propagate_likelihood): + propagate_likelihood( order, parents, children, likelihoods, constraints, snap.node_posterior.copy(), - snap.factors(ns.EPFactors), + snap.factors(), lognorm.copy(), 1000.0, 0.1, ep_state.USE_EDGE_LIKELIHOOD, ) - result = compare(lambda: call(impl.variational), lambda: call(variational)) + result = compare( + lambda: call(c_propagate_likelihood), + lambda: call(variational.propagate_likelihood), + ) assert kind(result) is AssertionError @@ -607,12 +720,12 @@ def shrunk(snap, role, scale): "parent-above", ], ) - def test_threshold(self, impl, snaps, role, scale): + def test_threshold(self, snaps, role, scale): snap = self.shrunk(snaps["small_ts"], role, scale) order = snap.edge_order[: len(snap.edge_order) // 2] - compare_runs(ep_state.run_likelihood, impl, snap, False, order=order) + compare_runs(ep_state.run_likelihood, snap, False, order=order) - def test_skipped_fixed_edge(self, impl, snaps): + def test_skipped_fixed_edge(self, snaps): # a fixed sample with a tiny scale whose edge is skipped (both nodes fixed) base = snaps["small_ts_historical"].copy() sample = np.flatnonzero(base.fixed)[0] @@ -620,15 +733,15 @@ def test_skipped_fixed_edge(self, impl, snaps): base.fix_nodes([base.edge_parents[edge]]) assert base.branch_counts(False)["both_fixed"] > 0 base.unscale([sample], TINY / 1e6) - compare_runs(ep_state.run_likelihood, impl, base, False) + compare_runs(ep_state.run_likelihood, base, False) class TestPropagatePrior: @pytest.mark.parametrize("ts_name", TS_NAMES) - def test_natural(self, impl, snaps, ts_name): + def test_natural(self, snaps, ts_name): snap = snaps[ts_name] assert snap.unconstrained_roots.any() - compare_runs(ep_state.run_prior, impl, snap, snap.unconstrained_roots) + compare_runs(ep_state.run_prior, snap, snap.unconstrained_roots) @pytest.mark.parametrize( ("scaled", "em_maxitt", "em_reltol"), @@ -639,11 +752,10 @@ def test_natural(self, impl, snaps, ts_name): + [(True, 0, 1e-8), (True, 3, 1e-8), (True, 1000, 0.5)], ids=lambda v: f"{v}" if isinstance(v, bool) else f"{v:g}", ) - def test_em(self, impl, snaps, scaled_snap, scaled, em_maxitt, em_reltol): + def test_em(self, snaps, scaled_snap, scaled, em_maxitt, em_reltol): snap = scaled_snap if scaled else snaps["small_ts"] compare_runs( ep_state.run_prior, - impl, snap, snap.unconstrained_roots, em_maxitt=em_maxitt, @@ -659,11 +771,10 @@ def test_em(self, impl, snaps, scaled_snap, scaled, em_maxitt, em_reltol): [1.0, 1.5, 1e300], ids=lambda v: f"max_shape={v:g}", ) - def test_max_shape(self, impl, snaps, ts_name, max_shape): + def test_max_shape(self, snaps, ts_name, max_shape): snap = snaps[ts_name] compare_runs( ep_state.run_prior, - impl, snap, snap.unconstrained_roots, max_shape=max_shape, @@ -681,14 +792,14 @@ def test_max_shape(self, impl, snaps, ts_name, max_shape): ], ids=["single_root", "internal", "none", "none_odd_arguments"], ) - def test_free_nodes(self, impl, snaps, ts_name, free, kwargs): + def test_free_nodes(self, snaps, ts_name, free, kwargs): snap = snaps[ts_name] mask = np.zeros(snap.node_posterior.shape[0], dtype=bool) if free == "single_root": mask[np.flatnonzero(snap.unconstrained_roots)[0]] = True elif free == "internal": mask = ~snap.fixed & ~snap.roots | snap.unconstrained_roots - compare_runs(ep_state.run_prior, impl, snap, mask, **kwargs) + compare_runs(ep_state.run_prior, snap, mask, **kwargs) @staticmethod def zero_posterior(snap): @@ -723,7 +834,7 @@ def negative_cavity_rate(snap): "free_too_long", ], ) - def test_assertions(self, impl, snaps, case): + def test_assertions(self, snaps, case): snap = snaps["small_ts"] free = snap.unconstrained_roots kwargs = {} @@ -745,9 +856,9 @@ def test_assertions(self, impl, snaps, case): free = free[:-1] else: free = np.append(free, True) - assert_run_kind(ep_state.run_prior, impl, snap, AssertionError, free, **kwargs) + assert_run_kind(ep_state.run_prior, snap, AssertionError, free, **kwargs) - def test_penalty_assert_reachable_from_ep(self, impl, fresh): + def test_penalty_assert_reachable_from_ep(self, fresh): # NOTE: current behaviour, possibly a bug: a likelihood pass in # which every update is skipped (a huge mutational target) leaves the roots # with a zero posterior, so that `iterate(regularise=True)` fails the @@ -755,12 +866,15 @@ def test_penalty_assert_reachable_from_ep(self, impl, fresh): base = fresh["small_ts"].copy() base.edge_likelihoods = base.edge_likelihoods * [1.0, 1e300] - def run(ns): - state = ep_state.run_likelihood(ns, base, False) + def run(propagate_likelihood, propagate_prior): + state = ep_state.run_likelihood(propagate_likelihood, base, False) step = base.after_pass(state) - return ep_state.run_prior(ns, step, step.unconstrained_roots) + return ep_state.run_prior(propagate_prior, step, step.unconstrained_roots) - result = compare(lambda: run(impl.variational), lambda: run(variational)) + result = compare( + lambda: run(c_propagate_likelihood, c_propagate_prior), + lambda: run(variational.propagate_likelihood, variational.propagate_prior), + ) assert kind(result) is AssertionError @@ -774,8 +888,8 @@ class TestPropagateMutations: ("small_ts_unphased", True), ], ) - def test_natural(self, impl, snaps, ts_name, unphased): - compare_runs(ep_state.run_mutations, impl, snaps[ts_name], unphased) + def test_natural(self, snaps, ts_name, unphased): + compare_runs(ep_state.run_mutations, snaps[ts_name], unphased) @pytest.mark.parametrize( ("ts_name", "unphased"), @@ -785,15 +899,15 @@ def test_natural(self, impl, snaps, ts_name, unphased): ("small_ts_unphased", True), ], ) - def test_forced_fixed_nodes(self, impl, snaps, ts_name, unphased): + def test_forced_fixed_nodes(self, snaps, ts_name, unphased): # mutations on edges of every kind: both nodes fixed, one of the two fixed snap = ep_state.fixed_internal_snapshot(snaps[ts_name], unphased) counts = snap.branch_counts(unphased) assert all(counts[k] > 0 for k in ("both_fixed", "fixed_parent", "fixed_child")) - compare_runs(ep_state.run_mutations, impl, snap, unphased) + compare_runs(ep_state.run_mutations, snap, unphased) @pytest.mark.parametrize("case", ["null_edges", "order_subset_and_repeats"]) - def test_mutation_selection(self, impl, snaps, case): + def test_mutation_selection(self, snaps, case): # mutations above the root have edge NULL and are skipped; the order is any # subset of the mutations, with repeats snap = snaps["small_ts"] @@ -804,7 +918,7 @@ def test_mutation_selection(self, impl, snaps, case): kwargs["edges"] = edges else: kwargs["order"] = np.array([5, 3, 3, 100, 5], dtype=np.int32) - compare_runs(ep_state.run_mutations, impl, snap, False, **kwargs) + compare_runs(ep_state.run_mutations, snap, False, **kwargs) @pytest.mark.parametrize( ("branch", "case"), @@ -816,7 +930,7 @@ def test_mutation_selection(self, impl, snaps, case): if not (c == "projection_fails" and "both_fixed" in b) ], ) - def test_single_edge(self, impl, branch, case): + def test_single_edge(self, branch, case): # NOTE: current behaviour, possibly a bug: a mutation whose # projection fails gets NaN posterior and phase, silently left in the result. fails = case == "projection_fails" @@ -825,16 +939,16 @@ def test_single_edge(self, impl, branch, case): if fails and "sideways" in branch: # as in propagate_likelihood: compiled `*_sideways_moments` raises with pytest.raises(expected_error(ZeroDivisionError)): - ep_state.run_mutations(impl.variational, snap, snap.unphased) + ep_state.run_mutations(c_propagate_mutations, snap, snap.unphased) else: - compare_runs(ep_state.run_mutations, impl, snap, snap.unphased) + compare_runs(ep_state.run_mutations, snap, snap.unphased) - def test_twin_in_phased_pass(self, impl): + def test_twin_in_phased_pass(self): # unlike propagate_likelihood, there is no `unphased` assert for p == c; the # twin projection is used as is (direct call only: edges never have p == c) snap = tiny_snapshot("twin") snap.mutation_blocks[:] = tskit.NULL - assert_run_kind(ep_state.run_mutations, impl, snap, "finite", False) + assert_run_kind(ep_state.run_mutations, snap, "finite", False) @pytest.mark.parametrize( ("ages", "expected_kind"), @@ -849,22 +963,20 @@ def test_twin_in_phased_pass(self, impl): pytest.param([[10, 10], [0, 0]], "finite", id="inverted_ages"), ], ) - def test_fixed_edge_ages(self, impl, ages, expected_kind): + def test_fixed_edge_ages(self, ages, expected_kind): snap = tiny_snapshot("both_fixed") snap.node_constraints[:] = ages - assert_run_kind(ep_state.run_mutations, impl, snap, expected_kind, False) + assert_run_kind(ep_state.run_mutations, snap, expected_kind, False) @pytest.mark.parametrize("change", ["edges_size", "posterior_size"]) - def test_shape_mismatches(self, impl, snaps, change): + def test_shape_mismatches(self, snaps, change): # direct calls only: checked while parsing arguments in C snap = snaps["small_ts"] if change == "edges_size": kwargs = dict(edges=snap.mutation_edges[:-1]) else: kwargs = dict(posterior=snap.node_posterior[:-1]) - assert_run_kind( - ep_state.run_mutations, impl, snap, AssertionError, False, **kwargs - ) + assert_run_kind(ep_state.run_mutations, snap, AssertionError, False, **kwargs) class TestMultiSweep: @@ -883,12 +995,28 @@ class TestMultiSweep: } @pytest.mark.parametrize("case", CASES) - def test_sweeps(self, impl, fresh, case): + def test_sweeps(self, fresh, case): name, kwargs = self.CASES[case] snap = fresh[name] sweeps = 4 - actual = ep_state.run_sweeps(impl.variational, snap, sweeps, **kwargs) - expected = ep_state.run_sweeps(variational, snap, sweeps, **kwargs) + actual = ep_state.run_sweeps( + c_propagate_likelihood, + c_propagate_prior, + c_propagate_mutations, + c_rescale_factors, + snap, + sweeps, + **kwargs, + ) + expected = ep_state.run_sweeps( + variational.propagate_likelihood, + variational.propagate_prior, + variational.propagate_mutations, + variational._rescale_factors, + snap, + sweeps, + **kwargs, + ) for a, e in zip(actual[0], expected[0]): for x, y in zip(a, e): # node posterior, edge and block lognorm np.testing.assert_array_equal(x, y) From 37f8414b9562603b33ba09deb87336e82028cbf5 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 10:10:32 -0800 Subject: [PATCH 22/56] Remove tests of the test adapters The size checks of the damp/rescale adapters and the EPFactors constructor test compared test code with itself; the C functions take scalars and the factors are always the oracle's. Comments name what the C library does rather than compiled code. --- tests/test_oracle_variational.py | 40 ++++++-------------------------- 1 file changed, 7 insertions(+), 33 deletions(-) diff --git a/tests/test_oracle_variational.py b/tests/test_oracle_variational.py index 24d85ddb..2abd9f04 100644 --- a/tests/test_oracle_variational.py +++ b/tests/test_oracle_variational.py @@ -1,6 +1,6 @@ """ Equivalence of the expectation propagation functions of ``_tsdate`` with the oracle of -``tsdate.variational``: the EP helpers (``EPFactors``, ``_damp``, ``_rescale``, +``tsdate.variational``: the EP helpers (``_damp``, ``_rescale``, ``_rescale_factors``, ``_constraints_are_consistent``) and the passes ``propagate_likelihood``, ``propagate_prior`` and ``propagate_mutations``, plus whole sweeps. The ``c_*`` adapters give the C functions the signatures of the oracles: the @@ -68,18 +68,11 @@ def factor_arrays(factors): ) -def check_size_two(*arrays): - if any(a.size != 2 for a in arrays): - raise ValueError("Natural parameters must have two entries") - - def c_damp(x, y, s): - check_size_two(x, y) return _tsdate.damp(x[0], x[1], y[0], y[1], s) def c_rescale(x, s): - check_size_two(x) return _tsdate.rescale(x[0], x[1], s) @@ -212,23 +205,6 @@ def unphased_name(ts_name): return ts_name == "small_ts_unphased" -class TestEPFactors: - def test_constructor(self, snaps): - snap = snaps["small_ts"] - actual = snap.factors() - expected = snap.factors() - for field in ("node", "edge", "block", "scale"): - a, e = getattr(actual, field), getattr(expected, field) - assert a.dtype == e.dtype - assert a.shape == e.shape - for field in ("_p", "_c", "_j", "_k"): - assert np.array_equal(getattr(actual, field), getattr(expected, field)) - fields = ("node", "edge", "block", "scale") - assert_same_values( - [getattr(actual, f) for f in fields], [getattr(expected, f) for f in fields] - ) - - class TestRescaleFactors: @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_unphased"]) @pytest.mark.parametrize("scale", ["seed0", "seed1", 1e-160, 1e100]) @@ -296,9 +272,7 @@ def test_assemble_factors(self, snaps, scaled_snap, ts_name): ("y1_nan_a_damped", f64(1, 1), f64(8, NAN), 0.5, "finite"), ("y0_minus_inf", f64(1, 1), f64(-INF, 0), 0.5, "finite"), ("y1_minus_inf", f64(1, 1), f64(0, -INF), 0.5, "finite"), - # asserts: sizes and `s` are checked by the callers (direct calls only) - ("size_x", f64(1, 1, 1), f64(0, 0), 0.5, AssertionError), - ("size_y", f64(1, 1), f64(0, 0, 0), 0.5, AssertionError), + # asserts: `s` is checked by the callers (direct calls only) ("s_zero", f64(1, 1), f64(0, 0), 0.0, AssertionError), ("s_one", f64(1, 1), f64(0, 0), 1.0, AssertionError), ("s_negative", f64(1, 1), f64(0, 0), -0.5, AssertionError), @@ -336,7 +310,6 @@ def test_assemble_factors(self, snaps, scaled_snap, ts_name): ("s_one_upper", f64(1, 1), 1.0, "finite"), ("s_one_lower", f64(-0.5, 1), 1.0, "finite"), # asserts (reachable as for `_damp`) - ("size", f64(1, 1, 1), 10.0, AssertionError), ("x0_minus_one", f64(-1, 1), 10.0, AssertionError), ("x0_nan", f64(NAN, 1), 10.0, AssertionError), ("x1_zero", f64(1, 0), 10.0, AssertionError), @@ -365,7 +338,7 @@ def test_random(self, seed): @pytest.mark.parametrize("which", [0, 1]) def test_infinite_posterior_zero_message(self, which): - # Compiled code divides inf by 0.0 and raises; the oracle returns d = 1. Needs + # C reports the division of inf by 0.0; the oracle returns d = 1. Needs # an infinite posterior, which is unreachable without a prior failure. x = f64(1, 1) x[which] = INF @@ -390,7 +363,7 @@ def test_random(self, seed): compare(c_rescale, variational._rescale, x, s) def test_zero_shape_offset_cap_below_one(self): - # Compiled code divides by zero and raises; the oracle returns -inf. Direct + # C reports the division by zero; the oracle returns -inf. Direct # call only: `propagate_*` assert `max_shape >= 1`. with pytest.raises(expected_error(ZeroDivisionError)): c_rescale(f64(0, 1), 0.5) @@ -485,7 +458,7 @@ def test_single_edge(self, branch, case): kwargs = dict(max_shape=1e300) # no posterior rescaling if "sideways" in branch and case == "projection_fails": # `sideways_moments` divides by zero for an astronomically large mutation - # target: compiled code raises where the oracle returns NaN and skips. + # target: C reports it where the oracle returns NaN and skips. with pytest.raises(expected_error(ZeroDivisionError)): ep_state.run_likelihood( c_propagate_likelihood, snap, snap.unphased, **kwargs @@ -937,7 +910,8 @@ def test_single_edge(self, branch, case): likelihood = (1.0, 1e300) if fails else (3.0, 0.1) snap = tiny_snapshot(branch, likelihood=likelihood) if fails and "sideways" in branch: - # as in propagate_likelihood: compiled `*_sideways_moments` raises + # as in propagate_likelihood: C reports a division by zero in + # `*_sideways_moments` with pytest.raises(expected_error(ZeroDivisionError)): ep_state.run_mutations(c_propagate_mutations, snap, snap.unphased) else: From b00dd00a43e4df8252ac26b99496c5ddf4773b6f Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 10:14:15 -0800 Subject: [PATCH 23/56] Map the oracles to C functions with explicit tables test_oracle_approx and test_oracle_hypergeo look up the C function for each oracle in a table instead of deriving its name and adapter from the oracle's. --- tests/test_oracle_approx.py | 58 ++++++++++++++++++++++++++--------- tests/test_oracle_hypergeo.py | 18 +++++++++-- 2 files changed, 59 insertions(+), 17 deletions(-) diff --git a/tests/test_oracle_approx.py b/tests/test_oracle_approx.py index 474c9e7f..069c2db7 100644 --- a/tests/test_oracle_approx.py +++ b/tests/test_oracle_approx.py @@ -67,17 +67,47 @@ def project(*args): return project -def c_function(name): - """ - The C function for the oracle ``approx.`` (its name without the leading - underscore), with the oracle's signature - """ - func = getattr(_tsdate, name.removeprefix("_")) - if name.startswith("_valid_"): - return valid_check(func) - if name.endswith("_projection"): - return projection(func) - return func +# The C function for each oracle in ``approx``, with the oracle's signature +C_FUNCTIONS = { + "approximate_log_moments": _tsdate.approximate_log_moments, + "approximate_gamma_kl": _tsdate.approximate_gamma_kl, + "approximate_gamma_mom": _tsdate.approximate_gamma_mom, + "approximate_gamma_iqr": _tsdate.approximate_gamma_iqr, + "average_gammas": _tsdate.average_gammas, + "moments": _tsdate.moments, + "rootward_moments": _tsdate.rootward_moments, + "leafward_moments": _tsdate.leafward_moments, + "unphased_moments": _tsdate.unphased_moments, + "twin_moments": _tsdate.twin_moments, + "sideways_moments": _tsdate.sideways_moments, + "mutation_moments": _tsdate.mutation_moments, + "mutation_rootward_moments": _tsdate.mutation_rootward_moments, + "mutation_leafward_moments": _tsdate.mutation_leafward_moments, + "mutation_unphased_moments": _tsdate.mutation_unphased_moments, + "mutation_twin_moments": _tsdate.mutation_twin_moments, + "mutation_sideways_moments": _tsdate.mutation_sideways_moments, + "mutation_edge_moments": _tsdate.mutation_edge_moments, + "mutation_block_moments": _tsdate.mutation_block_moments, + "_valid_moments": valid_check(_tsdate.valid_moments), + "_valid_gamma": valid_check(_tsdate.valid_gamma), + "_valid_hyp1f1": valid_check(_tsdate.valid_hyp1f1), + "_valid_hyperu": valid_check(_tsdate.valid_hyperu), + "_valid_hyp2f1": valid_check(_tsdate.valid_hyp2f1), + "gamma_projection": projection(_tsdate.gamma_projection), + "leafward_projection": projection(_tsdate.leafward_projection), + "rootward_projection": projection(_tsdate.rootward_projection), + "unphased_projection": projection(_tsdate.unphased_projection), + "twin_projection": projection(_tsdate.twin_projection), + "sideways_projection": projection(_tsdate.sideways_projection), + "mutation_gamma_projection": projection(_tsdate.mutation_gamma_projection), + "mutation_leafward_projection": projection(_tsdate.mutation_leafward_projection), + "mutation_rootward_projection": projection(_tsdate.mutation_rootward_projection), + "mutation_edge_projection": projection(_tsdate.mutation_edge_projection), + "mutation_unphased_projection": projection(_tsdate.mutation_unphased_projection), + "mutation_twin_projection": projection(_tsdate.mutation_twin_projection), + "mutation_sideways_projection": projection(_tsdate.mutation_sideways_projection), + "mutation_block_projection": projection(_tsdate.mutation_block_projection), +} def parity(name, args, expected_kind=None): @@ -85,7 +115,7 @@ def parity(name, args, expected_kind=None): Compare the C function for the oracle ``approx.`` with the oracle on ``args`` (returning the oracle's outcome); optionally check its kind. """ - func = c_function(name) + func = C_FUNCTIONS[name] oracle = getattr(approx, name) if expected_kind is None: return compare(func, oracle, *args) @@ -394,7 +424,7 @@ def test_domain(self, name, args, expected): ) def test_error_messages(self, name, args, expected): # the messages distinguish the failure modes - func = c_function(name) + func = C_FUNCTIONS[name] with pytest.raises(expected_error(KLMinimizationFailedError)): func(*args) compare(func, getattr(approx, name), *args) @@ -690,7 +720,7 @@ def test_inputs_are_not_modified(self, name): first_regime = next(iter(REGIMES[moments].values())) proj_args = projection_args(name, floats(first_regime)) copies = [a.copy() if isinstance(a, np.ndarray) else a for a in proj_args] - func = c_function(name) + func = C_FUNCTIONS[name] func(*proj_args) for arg, copy in zip(proj_args, copies): np.testing.assert_array_equal(arg, copy) diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index f8789350..0044387d 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -24,13 +24,25 @@ nextafter = np.nextafter +# The C function for each oracle in ``hypergeo`` +C_FUNCTIONS = { + "_digamma": _tsdate.digamma, + "_trigamma": _tsdate.trigamma, + "_betaln": _tsdate.betaln, + "_gammainc_der": _tsdate.gammainc_der, + "_gammainc_inv": _tsdate.gammainc_inv, + "_hyperu_laplace": _tsdate.hyperu_laplace, + "_hyp1f1_laplace": _tsdate.hyp1f1_laplace, + "_hyp2f1_laplace": _tsdate.hyp2f1_laplace, +} + def parity(name, args, expected_kind=None): """ - Compare the C function for the oracle ``hypergeo.`` (its name without the - leading underscore) with the oracle on ``args``; optionally check the kind. + Compare the C function for the oracle ``hypergeo.`` with the oracle on + ``args``; optionally check the kind. """ - func = getattr(_tsdate, name.removeprefix("_")) + func = C_FUNCTIONS[name] oracle = getattr(hypergeo, name) if expected_kind is None: return compare(func, oracle, *args) From 36d42374b9c9e3ff175d7b0ac3c706e9bb221b48 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 10:20:24 -0800 Subject: [PATCH 24/56] Explain the gammaincinv placeholder in the C tests --- lib/tests/tests.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/lib/tests/tests.c b/lib/tests/tests.c index 664fbb0e..c97f9204 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -313,9 +313,8 @@ test_hyp2f1_laplace_errors(void) } /* - * A placeholder for the gamma quantile function that ignores the shape. Quantiles - * x1, x2 in the ratio q2 / q1 match it for any shape, so that the Newton iteration of - * the interquantile fit stops after one step; other ratios fail. + * The library takes gammaincinv as a parameter (the Python module passes SciPy's). + * These tests check return codes only, so a placeholder that ignores the shape will do. */ static double test_gammaincinv(double a, double p) From 1d5acdb6cdfbb248f35e9209845e524e3ec15901 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 10:48:32 -0800 Subject: [PATCH 25/56] Port gammaincinv from xsf to C Add lib/gammaincinv.c, a C translation of xsf's cephes igami (the implementation of scipy.special.gammaincinv) and the functions it reaches, and call it directly from the approx and rescaling functions. This removes the gammaincinv function-pointer parameter and the loading of SciPy's Cython gammaincinv at module import, so _tsdate no longer imports SciPy. The port agrees bit for bit with scipy.special.gammaincinv (SciPy 1.18.1) on 3 million random points across regimes, including the complemented inversion, tiny quantiles and arguments outside the domain. --- _tsdatemodule.c | 71 +- lib/approx.c | 27 +- lib/gammaincinv.c | 1668 +++++++++++++++++++++++++++++++++ lib/meson.build | 2 +- lib/rescaling.c | 10 +- lib/tests/tests.c | 102 +- lib/tsdate.h | 19 +- setup.py | 1 + tests/oracle/hypergeo.py | 8 +- tests/test_oracle_hypergeo.py | 59 +- tests/test_python_c_scalar.py | 15 +- 11 files changed, 1817 insertions(+), 165 deletions(-) create mode 100644 lib/gammaincinv.c diff --git a/_tsdatemodule.c b/_tsdatemodule.c index 257051c5..bee6780b 100644 --- a/_tsdatemodule.c +++ b/_tsdatemodule.c @@ -35,13 +35,6 @@ static PyObject *TsdLibraryError; -/* - * SciPy's gammaincinv, taken from the C API of scipy.special.cython_special at module - * initialisation. The third argument is Cython's __pyx_skip_dispatch. - */ -typedef double (*cython_gammaincinv_fn)(double a, double p, int skip_dispatch); -static cython_gammaincinv_fn scipy_gammaincinv; - static void handle_library_error(int err) { @@ -126,17 +119,10 @@ scalar_gammainc_der(const double *in, double *out) return tsd_gammainc_der(in[0], in[1], out); } -/* A tsd_gammaincinv_fn: this is what is passed to library functions that need it. */ -static double -gammaincinv(double a, double p) -{ - return scipy_gammaincinv(a, p, 0); -} - static int scalar_gammainc_inv(const double *in, double *out) { - out[0] = gammaincinv(in[0], in[1]); + out[0] = tsd_gammaincinv(in[0], in[1]); return 0; } @@ -181,8 +167,7 @@ scalar_approximate_gamma_mom(const double *in, double *out) static int scalar_approximate_gamma_iqr(const double *in, double *out) { - return tsd_approximate_gamma_iqr( - in[0], in[1], in[2], in[3], in[4], gammaincinv, out); + return tsd_approximate_gamma_iqr(in[0], in[1], in[2], in[3], in[4], out); } static int @@ -1756,7 +1741,7 @@ tsdate_piecewise_scale_posterior(PyObject *Py_UNUSED(self), PyObject *args) Py_BEGIN_ALLOW_THREADS err = tsd_piecewise_scale_posterior(ARRAY_LEN(posteriors), DOUBLES(posteriors), FLAGS(posteriors_fixed), ARRAY_LEN(original_breaks), DOUBLES(original_breaks), - DOUBLES(rescaled_breaks), quantile_width, max_shape, gammaincinv, + DOUBLES(rescaled_breaks), quantile_width, max_shape, (double *) PyArray_DATA(new_posteriors)); Py_END_ALLOW_THREADS if (err != 0) { @@ -2266,52 +2251,6 @@ static PyMethodDef tsdate_methods[] = { static struct PyModuleDef tsdatemodule = { PyModuleDef_HEAD_INIT, "_tsdate", MODULE_DOC, -1, tsdate_methods, NULL, NULL, NULL, NULL }; -/* - * Look up scipy.special.cython_special.gammaincinv through its Cython C API capsule. - * The capsule's name is its C signature, which is used as given to get the pointer. - */ -static int -load_scipy_gammaincinv(void) -{ - int ret = -1; - PyObject *cython_special = NULL; - PyObject *capi = NULL; - PyObject *capsule = NULL; - const char *name; - void *ptr; - - cython_special = PyImport_ImportModule("scipy.special.cython_special"); - if (cython_special == NULL) { - PyErr_SetString( - PyExc_ImportError, "_tsdate requires scipy.special.cython_special"); - goto out; - } - capi = PyObject_GetAttrString(cython_special, "__pyx_capi__"); - if (capi == NULL) { - goto out; - } - capsule = PyDict_GetItemString(capi, "gammaincinv"); /* borrowed */ - if (capsule == NULL || !PyCapsule_CheckExact(capsule)) { - PyErr_SetString(PyExc_ImportError, - "scipy.special.cython_special does not provide gammaincinv"); - goto out; - } - name = PyCapsule_GetName(capsule); - if (name == NULL) { - goto out; - } - ptr = PyCapsule_GetPointer(capsule, name); - if (ptr == NULL) { - goto out; - } - scipy_gammaincinv = (cython_gammaincinv_fn) ptr; - ret = 0; -out: - Py_XDECREF(cython_special); - Py_XDECREF(capi); - return ret; -} - PyObject * PyInit__tsdate(void) { @@ -2327,10 +2266,6 @@ PyInit__tsdate(void) Py_INCREF(TsdLibraryError); PyModule_AddObject(module, "LibraryError", TsdLibraryError); - if (load_scipy_gammaincinv() != 0) { - Py_DECREF(module); - return NULL; - } if (add_scalar_functions(module) != 0) { Py_DECREF(module); return NULL; diff --git a/lib/approx.c b/lib/approx.c index 0e8a4ba5..3aa4a762 100644 --- a/lib/approx.c +++ b/lib/approx.c @@ -162,8 +162,7 @@ tsd_approximate_gamma_mom(double mean, double variance, double out[2]) /* The gamma with shape `max_shape` whose q-quantile is x. */ static int -gamma_iqr_upper_bound( - double q, double x, double max_shape, tsd_gammaincinv_fn gammaincinv, double out[2]) +gamma_iqr_upper_bound(double q, double x, double max_shape, double out[2]) { int ret = 0; @@ -172,7 +171,7 @@ gamma_iqr_upper_bound( goto out; } out[0] = max_shape - 1; - out[1] = gammaincinv(max_shape, q) / x; + out[1] = tsd_gammaincinv(max_shape, q) / x; out: return ret; } @@ -182,14 +181,14 @@ gamma_iqr_upper_bound( * Updates alpha and writes the step to delta. */ static int -gamma_iqr_newton_step(double q1, double q2, double x1, double x2, - tsd_gammaincinv_fn gammaincinv, double *alpha, double *delta) +gamma_iqr_newton_step( + double q1, double q2, double x1, double x2, double *alpha, double *delta) { int ret = 0; double y1, y2, obj, inv_1, inv_2, der_1, der_2, gra_1, gra_2, y1_sq, gra; - y1 = gammaincinv(*alpha, q1); - y2 = gammaincinv(*alpha, q2); + y1 = tsd_gammaincinv(*alpha, q1); + y2 = tsd_gammaincinv(*alpha, q2); if (y1 == 0.0) { ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); goto out; @@ -228,15 +227,15 @@ gamma_iqr_newton_step(double q1, double q2, double x1, double x2, * x1, x2 the corresponding quantiles. The shape is capped at max_shape. */ int -tsd_approximate_gamma_iqr(double q1, double q2, double x1, double x2, double max_shape, - tsd_gammaincinv_fn gammaincinv, double out[2]) +tsd_approximate_gamma_iqr( + double q1, double q2, double x1, double x2, double max_shape, double out[2]) { int ret = 0; int itt = 0; double alpha, delta, ratio_q, ratio_x; if (x2 == x1) { - ret = gamma_iqr_upper_bound(q1, x1, max_shape, gammaincinv, out); + ret = gamma_iqr_upper_bound(q1, x1, max_shape, out); goto out; } if (!(q2 > q1 && x2 > x1)) { @@ -251,7 +250,7 @@ tsd_approximate_gamma_iqr(double q1, double q2, double x1, double x2, double max ratio_x = x2 / x1; alpha = log(ratio_q) / log(ratio_x); /* lower bound */ if (alpha > max_shape) { - ret = gamma_iqr_upper_bound(q1, x1, max_shape, gammaincinv, out); + ret = gamma_iqr_upper_bound(q1, x1, max_shape, out); goto out; } /* refine with Newton iteration */ @@ -261,7 +260,7 @@ tsd_approximate_gamma_iqr(double q1, double q2, double x1, double x2, double max ret = tsd_trace_error(TSD_ERR_QUANTILE_MAX_ITERATIONS); goto out; } - ret = gamma_iqr_newton_step(q1, q2, x1, x2, gammaincinv, &alpha, &delta); + ret = gamma_iqr_newton_step(q1, q2, x1, x2, &alpha, &delta); if (ret != 0) { goto out; } @@ -272,11 +271,11 @@ tsd_approximate_gamma_iqr(double q1, double q2, double x1, double x2, double max goto out; } if (alpha > max_shape) { - ret = gamma_iqr_upper_bound(q1, x1, max_shape, gammaincinv, out); + ret = gamma_iqr_upper_bound(q1, x1, max_shape, out); goto out; } out[0] = alpha - 1; - out[1] = gammaincinv(alpha, q1) / x1; + out[1] = tsd_gammaincinv(alpha, q1) / x1; out: return ret; } diff --git a/lib/gammaincinv.c b/lib/gammaincinv.c new file mode 100644 index 00000000..71c350b5 --- /dev/null +++ b/lib/gammaincinv.c @@ -0,0 +1,1668 @@ +/* + * The inverse of the regularised lower incomplete gamma function, tsd_gammaincinv. + * + * This is a C translation of the double precision igami() of the xsf library + * (https://github.com/scipy/xsf, commit f7b85f505a94fd398024478d2e747b01dd2d7a6d), + * which is scipy.special.gammaincinv, together with the functions it reaches, from + * include/xsf/cephes/: igami.h (igami, igamci, find_inverse_gamma, find_inverse_s, + * didonato_SN), igam.h (igam, igamc, igam_fac, igam_series, igamc_series, + * igamc_continued_fraction, asymptotic_series), igam_asymp_coeff.h, gamma.h (Gamma, + * stirf, lgam, lgam_sgn, lgam_large_x), lanczos.h (lanczos_sum_expg_scaled), + * unity.h (log1p, log1pmx, expm1, lgam1p, lgam1p_taylor), zeta.h (zeta), ndtr.h + * (erf, erfc), trig.h (sinpi), polevl.h (polevl, p1evl, ratevl) and const.h. The + * operations, constants, branches and iteration limits are those of xsf; error + * reporting (set_error, a no-op in xsf's default build) is dropped and the in-band + * return values are kept. + * + * The notices of the original files and the licences they are distributed under + * follow. + * + * ---------------------------------------------------------------------------- + * + * xsf: Copyright (c) 2024, SciPy. Translated into C++ by SciPy developers in 2024. + * + * Cephes Math Library (igam, gamma, lgam, polevl, zeta, ndtr, const): + * Copyright 1984, 1985, 1987, 1988, 1989, 1992, 1995 by Stephen L. Moshier. + * Cephes is distributed under the BSD 3-Clause License below with the permission + * of the author. + * + * igami.h (the Didonato and Morris initial approximation and the Halley iteration) + * and lanczos.h: (C) Copyright John Maddock 2006. Use, modification and + * distribution are subject to the Boost Software License, Version 1.0, below. + * + * trig.h: original author Josh Wilson, 2020. + * + * ---------------------------------------------------------------------------- + * + * BSD 3-Clause License + * + * Copyright (c) 2024, SciPy + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * ---------------------------------------------------------------------------- + * + * Boost Software License - Version 1.0 - August 17th, 2003 + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#include +#include + +#include "tsdate.h" + +/* const.h, and the constants that MSVC does not define by default. */ +#define CEPH_MAXITER 500 +#define CEPH_MACHEP 1.1102230246251565404236316680908203125E-16 +#define CEPH_MAXLOG 7.097827128933839730962063185871E2 +#define CEPH_SQRT2PI 2.506628274631000502415765284811045253007 +#define CEPH_LOGPI 1.144729885849400174143427351353058711647 +#define CEPH_MAXGAM 171.624376956302725 +#define CEPH_SCIPY_EULER 0.577215664901532860606512090082402431 +#define CEPH_PI 3.14159265358979323846 +#define CEPH_SQRT2 1.41421356237309504880 +#define CEPH_SQRT1_2 0.707106781186547524401 + +/* polevl.h */ + +static double +ceph_polevl(double x, const double coef[], int N) +{ + double ans; + int i; + const double *p; + + p = coef; + ans = *p++; + i = N; + + do { + ans = ans * x + *p++; + } while (--i); + + return ans; +} + +static double +ceph_p1evl(double x, const double coef[], int N) +{ + double ans; + const double *p; + int i; + + p = coef; + ans = x + *p++; + i = N - 1; + + do { + ans = ans * x + *p++; + } while (--i); + + return ans; +} + +static double +ceph_ratevl(double x, const double num[], int M, const double denom[], int N) +{ + int i, dir; + double y, num_ans, denom_ans; + double absx = fabs(x); + const double *p; + + if (absx > 1) { + /* Evaluate as a polynomial in 1/x. */ + dir = -1; + p = num + M; + y = 1 / x; + } else { + dir = 1; + p = num; + y = x; + } + + /* Evaluate the numerator */ + num_ans = *p; + p += dir; + for (i = 1; i <= M; i++) { + num_ans = num_ans * y + *p; + p += dir; + } + + /* Evaluate the denominator */ + if (absx > 1) { + p = denom + N; + } else { + p = denom; + } + + denom_ans = *p; + p += dir; + for (i = 1; i <= N; i++) { + denom_ans = denom_ans * y + *p; + p += dir; + } + + if (absx > 1) { + i = M - N; + return pow(x, i) * num_ans / denom_ans; + } else { + return num_ans / denom_ans; + } +} + +/* trig.h: sin(pi * x). */ +static double +ceph_sinpi(double x) +{ + double s = 1.0; + double r; + + if (signbit(x)) { + x = -x; + s = -1.0; + } + + r = fmod(x, 2.0); + if (r < 0.5) { + return s * sin(CEPH_PI * r); + } else if (r > 1.5) { + return s * sin(CEPH_PI * (r - 2.0)); + } else { + return -s * sin(CEPH_PI * (r - 1.0)); + } +} + +/* gamma.h */ + +static const double gamma_P[] = { 1.60119522476751861407E-4, 1.19135147006586384913E-3, + 1.04213797561761569935E-2, 4.76367800457137231464E-2, 2.07448227648435975150E-1, + 4.94214826801497100753E-1, 9.99999999999999996796E-1 }; + +static const double gamma_Q[] = { -2.31581873324120129819E-5, 5.39605580493303397842E-4, + -4.45641913851797240494E-3, 1.18139785222060435552E-2, 3.58236398605498653373E-2, + -2.34591795718243348568E-1, 7.14304917030273074085E-2, 1.00000000000000000320E0 }; + +/* Stirling's formula for the Gamma function */ +static const double gamma_STIR[5] = { + 7.87311395793093628397E-4, + -2.29549961613378126380E-4, + -2.68132617805781232825E-3, + 3.47222221605458667310E-3, + 8.33333333333482257126E-2, +}; + +#define GAMMA_MAXSTIR 143.01608 + +/* Gamma function computed by Stirling's formula. + * The polynomial STIR is valid for 33 <= x <= 172. + */ +static double +ceph_stirf(double x) +{ + double y, w, v; + + if (x >= CEPH_MAXGAM) { + return INFINITY; + } + w = 1.0 / x; + w = 1.0 + w * ceph_polevl(w, gamma_STIR, 4); + y = exp(x); + if (x > GAMMA_MAXSTIR) { /* Avoid overflow in pow() */ + v = pow(x, 0.5 * x - 0.25); + y = v * (v / y); + } else { + y = pow(x, x - 0.5) / y; + } + y = CEPH_SQRT2PI * y * w; + return y; +} + +static double +ceph_Gamma(double x) +{ + double p, q, z; + int i; + int sgngam = 1; + + if (!isfinite(x)) { + if (x > 0) { + /* gamma(+inf) = +inf */ + return x; + } + /* gamma(NaN) and gamma(-inf) both should equal NaN. */ + return NAN; + } + + if (x == 0) { + /* For pole at zero, value depends on sign of zero. + * +inf when approaching from right, -inf when approaching + * from left. */ + return copysign(INFINITY, x); + } + + q = fabs(x); + + if (q > 33.0) { + if (x < 0.0) { + p = floor(q); + if (p == q) { + /* x is a negative integer. This is a pole. */ + return NAN; + } + i = (int) p; + if ((i & 1) == 0) { + sgngam = -1; + } + z = q - p; + if (z > 0.5) { + p += 1.0; + z = q - p; + } + z = q * ceph_sinpi(z); + if (z == 0.0) { + return sgngam * (double) INFINITY; + } + z = fabs(z); + z = CEPH_PI / (z * ceph_stirf(q)); + } else { + z = ceph_stirf(x); + } + return sgngam * z; + } + + z = 1.0; + while (x >= 3.0) { + x -= 1.0; + z *= x; + } + + while (x < 0.0) { + if (x > -1.E-9) { + goto small; + } + z /= x; + x += 1.0; + } + + while (x < 2.0) { + if (x < 1.e-9) { + goto small; + } + z /= x; + x += 1.0; + } + + if (x == 2.0) { + return z; + } + + x -= 2.0; + p = ceph_polevl(x, gamma_P, 6); + q = ceph_polevl(x, gamma_Q, 7); + return z * p / q; + +small: + if (x == 0.0) { + /* For this to have happened, x must have started as a negative integer. */ + return NAN; + } else { + return z / ((1.0 + 0.5772156649015329 * x) * x); + } +} + +/* A[]: Stirling's formula expansion of log Gamma + * B[], C[]: log Gamma function between 2 and 3 + */ +static const double gamma_A[] = { 8.11614167470508450300E-4, -5.95061904284301438324E-4, + 7.93650340457716943945E-4, -2.77777777730099687205E-3, 8.33333333333331927722E-2 }; + +static const double gamma_B[] = { -1.37825152569120859100E3, -3.88016315134637840924E4, + -3.31612992738871184744E5, -1.16237097492762307383E6, -1.72173700820839662146E6, + -8.53555664245765465627E5 }; + +static const double gamma_C[] = { /* 1.00000000000000000000E0, */ + -3.51815701436523470549E2, -1.70642106651881159223E4, -2.20528590553854454839E5, + -1.13933444367982507207E6, -2.53252307177582951285E6, -2.01889141433532773231E6 +}; + +/* log( sqrt( 2*pi ) ) */ +#define GAMMA_LS2PI 0.91893853320467274178 +#define GAMMA_MAXLGM 2.556348e305 + +static double +ceph_lgam_large_x(double x) +{ + double q = (x - 0.5) * log(x) - x + GAMMA_LS2PI; + double p; + + if (x > 1.0e8) { + return q; + } + p = 1.0 / (x * x); + p = ((7.9365079365079365079365e-4 * p - 2.7777777777777777777778e-3) * p + + 0.0833333333333333333333) + / x; + return q + p; +} + +static double +ceph_lgam_sgn(double x, int *sign) +{ + double p, q, u, w, z; + int i; + + *sign = 1; + + if (!isfinite(x)) { + return x; + } + + if (x < -34.0) { + q = -x; + w = ceph_lgam_sgn(q, sign); + p = floor(q); + if (p == q) { + lgsing: + return INFINITY; + } + i = (int) p; + if ((i & 1) == 0) { + *sign = -1; + } else { + *sign = 1; + } + z = q - p; + if (z > 0.5) { + p += 1.0; + z = p - q; + } + z = q * ceph_sinpi(z); + if (z == 0.0) { + goto lgsing; + } + /* z = log(M_PI) - log( z ) - w; */ + z = CEPH_LOGPI - log(z) - w; + return z; + } + + if (x < 13.0) { + z = 1.0; + p = 0.0; + u = x; + while (u >= 3.0) { + p -= 1.0; + u = x + p; + z *= u; + } + while (u < 2.0) { + if (u == 0.0) { + goto lgsing; + } + z /= u; + p += 1.0; + u = x + p; + } + if (z < 0.0) { + *sign = -1; + z = -z; + } else { + *sign = 1; + } + if (u == 2.0) { + return log(z); + } + p -= 2.0; + x = x + p; + p = x * ceph_polevl(x, gamma_B, 5) / ceph_p1evl(x, gamma_C, 6); + return log(z) + p; + } + + if (x > GAMMA_MAXLGM) { + return *sign * (double) INFINITY; + } + + if (x >= 1000.0) { + return ceph_lgam_large_x(x); + } + + q = (x - 0.5) * log(x) - x + GAMMA_LS2PI; + p = 1.0 / (x * x); + return q + ceph_polevl(p, gamma_A, 4) / x; +} + +/* Logarithm of Gamma function */ +static double +ceph_lgam(double x) +{ + int sign; + return ceph_lgam_sgn(x, &sign); +} + +/* lanczos.h */ + +static const double lanczos_sum_expg_scaled_num[] = { + 0.006061842346248906525783753964555936883222, + 0.5098416655656676188125178644804694509993, + 19.51992788247617482847860966235652136208, + 449.9445569063168119446858607650988409623, + 6955.999602515376140356310115515198987526, + 75999.29304014542649875303443598909137092, + 601859.6171681098786670226533699352302507, + 3481712.15498064590882071018964774556468, + 14605578.08768506808414169982791359218571, + 43338889.32467613834773723740590533316085, + 86363131.28813859145546927288977868422342, + 103794043.1163445451906271053616070238554, + 56906521.91347156388090791033559122686859, +}; + +static const double lanczos_sum_expg_scaled_denom[] = { 1, 66, 1925, 32670, 357423, + 2637558, 13339535, 45995730, 105258076, 150917976, 120543840, 39916800, 0 }; + +#define LANCZOS_G 6.024680040776729583740234375 + +static double +ceph_lanczos_sum_expg_scaled(double x) +{ + return ceph_ratevl( + x, lanczos_sum_expg_scaled_num, 12, lanczos_sum_expg_scaled_denom, 12); +} + +/* unity.h */ + +/* Coefficients for log(1+x) = x - x**2/2 + x**3 P(x)/Q(x) + * 1/sqrt(2) <= x < sqrt(2) + * Theoretical peak relative error = 2.32e-20 + */ +static const double unity_LP[] = { + 4.5270000862445199635215E-5, + 4.9854102823193375972212E-1, + 6.5787325942061044846969E0, + 2.9911919328553073277375E1, + 6.0949667980987787057556E1, + 5.7112963590585538103336E1, + 2.0039553499201281259648E1, +}; + +static const double unity_LQ[] = { + /* 1.0000000000000000000000E0, */ + 1.5062909083469192043167E1, + 8.3047565967967209469434E1, + 2.2176239823732856465394E2, + 3.0909872225312059774938E2, + 2.1642788614495947685003E2, + 6.0118660497603843919306E1, +}; + +static double +ceph_log1p(double x) +{ + double z; + + z = 1.0 + x; + if ((z < CEPH_SQRT1_2) || (z > CEPH_SQRT2)) { + return log(z); + } + z = x * x; + z = -0.5 * z + x * (z * ceph_polevl(x, unity_LP, 6) / ceph_p1evl(x, unity_LQ, 6)); + return x + z; +} + +/* log(1 + x) - x */ +static double +ceph_log1pmx(double x) +{ + uint64_t n; + double xfac, term, res; + + if (fabs(x) < 0.5) { + xfac = x; + res = 0; + for (n = 2; n < CEPH_MAXITER; n++) { + xfac *= -x; + term = xfac / (double) n; + res += term; + if (fabs(term) < CEPH_MACHEP * fabs(res)) { + break; + } + } + return res; + } else { + return ceph_log1p(x) - x; + } +} + +/* e^x = 1 + 2x P(x^2)/( Q(x^2) - P(x^2) ) + * -0.5 <= x <= 0.5 + */ +static const double unity_EP[3] = { + 1.2617719307481059087798E-4, + 3.0299440770744196129956E-2, + 9.9999999999999999991025E-1, +}; + +static const double unity_EQ[4] = { + 3.0019850513866445504159E-6, + 2.5244834034968410419224E-3, + 2.2726554820815502876593E-1, + 2.0000000000000000000897E0, +}; + +static double +ceph_expm1(double x) +{ + double r, xx; + + if (!isfinite(x)) { + if (isnan(x)) { + return x; + } else if (x > 0) { + return x; + } else { + return -1.0; + } + } + if ((x < -0.5) || (x > 0.5)) { + return exp(x) - 1.0; + } + xx = x * x; + r = x * ceph_polevl(xx, unity_EP, 2); + r = r / (ceph_polevl(xx, unity_EQ, 3) - r); + return r + r; +} + +/* zeta.h */ + +/* Expansion coefficients + * for Euler-Maclaurin summation formula + * (2k)! / B2k + * where B2k are Bernoulli numbers + */ +static const double zeta_A[] = { + 12.0, -720.0, 30240.0, -1209600.0, 47900160.0, + -1.8924375803183791606e9, /*1.307674368e12/691 */ + 7.47242496e10, -2.950130727918164224e12, /*1.067062284288e16/3617 */ + 1.1646782814350067249e14, /*5.109094217170944e18/43867 */ + -4.5979787224074726105e15, /*8.028576626982912e20/174611 */ + 1.8152105401943546773e17, /*1.5511210043330985984e23/854513 */ + -7.1661652561756670113e18 /*1.6938241367317436694528e27/236364091 */ +}; + +/* The Hurwitz zeta function. Its only caller, ceph_lgam1p_taylor, passes an integer + * x >= 2 and q = 1, so the branches of zeta() for x <= 1, q <= 0 and q > 1e8 are + * omitted. */ +static double +ceph_zeta(double x, double q) +{ + int i; + double a, b, k, s, t, w; + + /* Euler-Maclaurin summation formula */ + s = pow(q, -x); + a = q; + i = 0; + b = 0.0; + while ((i < 9) || (a <= 9.0)) { + i += 1; + a += 1.0; + b = pow(a, -x); + s += b; + if (fabs(b / s) < CEPH_MACHEP) { + goto done; + } + } + + w = a; + s += b * w / (x - 1.0); + s -= 0.5 * b; + a = 1.0; + k = 0.0; + for (i = 0; i < 12; i++) { + a *= x + k; + b /= w; + t = a * b / zeta_A[i]; + s = s + t; + t = fabs(t / s); + if (t < CEPH_MACHEP) { + goto done; + } + k += 1.0; + a *= x + k; + b /= w; + k += 1.0; + } +done: + return s; +} + +/* Compute lgam(x + 1) around x = 0 using its Taylor series. */ +static double +ceph_lgam1p_taylor(double x) +{ + int n; + double xfac, coeff, res; + + if (x == 0) { + return 0; + } + res = -CEPH_SCIPY_EULER * x; + xfac = -x; + for (n = 2; n < 42; n++) { + xfac *= -x; + coeff = ceph_zeta(n, 1) * xfac / n; + res += coeff; + if (fabs(coeff) < CEPH_MACHEP * fabs(res)) { + break; + } + } + + return res; +} + +/* Compute lgam(x + 1). */ +static double +ceph_lgam1p(double x) +{ + if (fabs(x) <= 0.5) { + return ceph_lgam1p_taylor(x); + } else if (fabs(x - 1) < 0.5) { + return log(x) + ceph_lgam1p_taylor(x - 1); + } else { + return ceph_lgam(x + 1); + } +} + +/* ndtr.h */ + +static const double ndtr_P[] + = { 2.46196981473530512524E-10, 5.64189564831068821977E-1, 7.46321056442269912687E0, + 4.86371970985681366614E1, 1.96520832956077098242E2, 5.26445194995477358631E2, + 9.34528527171957607540E2, 1.02755188689515710272E3, 5.57535335369399327526E2 }; + +static const double ndtr_Q[] = { /* 1.00000000000000000000E0, */ + 1.32281951154744992508E1, 8.67072140885989742329E1, 3.54937778887819891062E2, + 9.75708501743205489753E2, 1.82390916687909736289E3, 2.24633760818710981792E3, + 1.65666309194161350182E3, 5.57535340817727675546E2 +}; + +static const double ndtr_R[] + = { 5.64189583547755073984E-1, 1.27536670759978104416E0, 5.01905042251180477414E0, + 6.16021097993053585195E0, 7.40974269950448939160E0, 2.97886665372100240670E0 }; + +static const double ndtr_S[] = { /* 1.00000000000000000000E0, */ + 2.26052863220117276590E0, 9.39603524938001434673E0, 1.20489539808096656605E1, + 1.70814450747565897222E1, 9.60896809063285878198E0, 3.36907645100081516050E0 +}; + +static const double ndtr_T[] = { 9.60497373987051638749E0, 9.00260197203842689217E1, + 2.23200534594684319226E3, 7.00332514112805075473E3, 5.55923013010394962768E4 }; + +static const double ndtr_U[] = { /* 1.00000000000000000000E0, */ + 3.35617141647503099647E1, 5.21357949780152679795E2, 4.59432382970980127987E3, + 2.26290000613890934246E4, 4.92673942608635921086E4 +}; + +static double ceph_erf(double x); + +static double +ceph_erfc(double a) +{ + double p, q, x, y, z; + + if (isnan(a)) { + return NAN; + } + + if (a < 0.0) { + x = -a; + } else { + x = a; + } + + if (x < 1.0) { + return 1.0 - ceph_erf(a); + } + + z = -a * a; + + if (z < -CEPH_MAXLOG) { + goto under; + } + + z = exp(z); + + if (x < 8.0) { + p = ceph_polevl(x, ndtr_P, 8); + q = ceph_p1evl(x, ndtr_Q, 8); + } else { + p = ceph_polevl(x, ndtr_R, 5); + q = ceph_p1evl(x, ndtr_S, 6); + } + y = (z * p) / q; + + if (a < 0) { + y = 2.0 - y; + } + + if (y != 0.0) { + return y; + } + +under: + if (a < 0) { + return 2.0; + } else { + return 0.0; + } +} + +static double +ceph_erf(double x) +{ + double y, z; + + if (isnan(x)) { + return NAN; + } + + if (x < 0.0) { + return -ceph_erf(-x); + } + + if (fabs(x) > 1.0) { + return 1.0 - ceph_erfc(x); + } + z = x * x; + + y = x * ceph_polevl(z, ndtr_T, 4) / ceph_p1evl(z, ndtr_U, 5); + return y; +} + +/* igam_asymp_coeff.h */ + +#define IGAM_ASYMP_COEFF_K 25 +#define IGAM_ASYMP_COEFF_N 25 + +static const double igam_asymp_coeff_d[IGAM_ASYMP_COEFF_K][IGAM_ASYMP_COEFF_N] = { + { -3.3333333333333333e-1, 8.3333333333333333e-2, -1.4814814814814815e-2, + 1.1574074074074074e-3, 3.527336860670194e-4, -1.7875514403292181e-4, + 3.9192631785224378e-5, -2.1854485106799922e-6, -1.85406221071516e-6, + 8.296711340953086e-7, -1.7665952736826079e-7, 6.7078535434014986e-9, + 1.0261809784240308e-8, -4.3820360184533532e-9, 9.1476995822367902e-10, + -2.551419399494625e-11, -5.8307721325504251e-11, 2.4361948020667416e-11, + -5.0276692801141756e-12, 1.1004392031956135e-13, 3.3717632624009854e-13, + -1.3923887224181621e-13, 2.8534893807047443e-14, -5.1391118342425726e-16, + -1.9752288294349443e-15 }, + { -1.8518518518518519e-3, -3.4722222222222222e-3, 2.6455026455026455e-3, + -9.9022633744855967e-4, 2.0576131687242798e-4, -4.0187757201646091e-7, + -1.8098550334489978e-5, 7.6491609160811101e-6, -1.6120900894563446e-6, + 4.6471278028074343e-9, 1.378633446915721e-7, -5.752545603517705e-8, + 1.1951628599778147e-8, -1.7543241719747648e-11, -1.0091543710600413e-9, + 4.1627929918425826e-10, -8.5639070264929806e-11, 6.0672151016047586e-14, + 7.1624989648114854e-12, -2.9331866437714371e-12, 5.9966963656836887e-13, + -2.1671786527323314e-16, -4.9783399723692616e-14, 2.0291628823713425e-14, + -4.13125571381061e-15 }, + { 4.1335978835978836e-3, -2.6813271604938272e-3, 7.7160493827160494e-4, + 2.0093878600823045e-6, -1.0736653226365161e-4, 5.2923448829120125e-5, + -1.2760635188618728e-5, 3.4235787340961381e-8, 1.3721957309062933e-6, + -6.298992138380055e-7, 1.4280614206064242e-7, -2.0477098421990866e-10, + -1.4092529910867521e-8, 6.228974084922022e-9, -1.3670488396617113e-9, + 9.4283561590146782e-13, 1.2872252400089318e-10, -5.5645956134363321e-11, + 1.1975935546366981e-11, -4.1689782251838635e-15, -1.0940640427884594e-12, + 4.6622399463901357e-13, -9.905105763906906e-14, 1.8931876768373515e-17, + 8.8592218725911273e-15 }, + { 6.4943415637860082e-4, 2.2947209362139918e-4, -4.6918949439525571e-4, + 2.6772063206283885e-4, -7.5618016718839764e-5, -2.3965051138672967e-7, + 1.1082654115347302e-5, -5.6749528269915966e-6, 1.4230900732435884e-6, + -2.7861080291528142e-11, -1.6958404091930277e-7, 8.0994649053880824e-8, + -1.9111168485973654e-8, 2.3928620439808118e-12, 2.0620131815488798e-9, + -9.4604966618551322e-10, 2.1541049775774908e-10, -1.388823336813903e-14, + -2.1894761681963939e-11, 9.7909989511716851e-12, -2.1782191880180962e-12, + 6.2088195734079014e-17, 2.126978363279737e-13, -9.3446887915174333e-14, + 2.0453671226782849e-14 }, + { -8.618882909167117e-4, 7.8403922172006663e-4, -2.9907248030319018e-4, + -1.4638452578843418e-6, 6.6414982154651222e-5, -3.9683650471794347e-5, + 1.1375726970678419e-5, 2.5074972262375328e-10, -1.6954149536558306e-6, + 8.9075075322053097e-7, -2.2929348340008049e-7, 2.956794137544049e-11, + 2.8865829742708784e-8, -1.4189739437803219e-8, 3.4463580499464897e-9, + -2.3024517174528067e-13, -3.9409233028046405e-10, 1.8602338968504502e-10, + -4.356323005056618e-11, 1.2786001016296231e-15, 4.6792750266579195e-12, + -2.1492464706134829e-12, 4.9088156148096522e-13, -6.3385914848915603e-18, + -5.0453320690800944e-14 }, + { -3.3679855336635815e-4, -6.9728137583658578e-5, 2.7727532449593921e-4, + -1.9932570516188848e-4, 6.7977804779372078e-5, 1.419062920643967e-7, + -1.3594048189768693e-5, 8.0184702563342015e-6, -2.2914811765080952e-6, + -3.252473551298454e-10, 3.4652846491085265e-7, -1.8447187191171343e-7, + 4.8240967037894181e-8, -1.7989466721743515e-14, -6.3061945000135234e-9, + 3.1624176287745679e-9, -7.8409242536974293e-10, 5.1926791652540407e-15, + 9.3589442423067836e-11, -4.5134262161632782e-11, 1.0799129993116827e-11, + -3.661886712685252e-17, -1.210902069055155e-12, 5.6807435849905643e-13, + -1.3249659916340829e-13 }, + { 5.3130793646399222e-4, -5.9216643735369388e-4, 2.7087820967180448e-4, + 7.9023532326603279e-7, -8.1539693675619688e-5, 5.6116827531062497e-5, + -1.8329116582843376e-5, -3.0796134506033048e-9, 3.4651553688036091e-6, + -2.0291327396058604e-6, 5.7887928631490037e-7, 2.338630673826657e-13, + -8.8286007463304835e-8, 4.7435958880408128e-8, -1.2545415020710382e-8, + 8.6496488580102925e-14, 1.6846058979264063e-9, -8.5754928235775947e-10, + 2.1598224929232125e-10, -7.6132305204761539e-16, -2.6639822008536144e-11, + 1.3065700536611057e-11, -3.1799163902367977e-12, 4.7109761213674315e-18, + 3.6902800842763467e-13 }, + { 3.4436760689237767e-4, 5.1717909082605922e-5, -3.3493161081142236e-4, + 2.812695154763237e-4, -1.0976582244684731e-4, -1.2741009095484485e-7, + 2.7744451511563644e-5, -1.8263488805711333e-5, 5.7876949497350524e-6, + 4.9387589339362704e-10, -1.0595367014026043e-6, 6.1667143761104075e-7, + -1.7562973359060462e-7, -1.2974473287015439e-12, 2.695423606288966e-8, + -1.4578352908731271e-8, 3.887645959386175e-9, -3.8810022510194121e-17, + -5.3279941738772867e-10, 2.7437977643314845e-10, -6.9957960920705679e-11, + 2.5899863874868481e-17, 8.8566890996696381e-12, -4.403168815871311e-12, + 1.0865561947091654e-12 }, + { -6.5262391859530942e-4, 8.3949872067208728e-4, -4.3829709854172101e-4, + -6.969091458420552e-7, 1.6644846642067548e-4, -1.2783517679769219e-4, + 4.6299532636913043e-5, 4.5579098679227077e-9, -1.0595271125805195e-5, + 6.7833429048651666e-6, -2.1075476666258804e-6, -1.7213731432817145e-11, + 3.7735877416110979e-7, -2.1867506700122867e-7, 6.2202288040189269e-8, + 6.5977038267330006e-16, -9.5903864974256858e-9, 5.2132144922808078e-9, + -1.3991589583935709e-9, 5.382058999060575e-16, 1.9484714275467745e-10, + -1.0127287556389682e-10, 2.6077347197254926e-11, -5.0904186999932993e-18, + -3.3721464474854592e-12 }, + { -5.9676129019274625e-4, -7.2048954160200106e-5, 6.7823088376673284e-4, + -6.4014752602627585e-4, 2.7750107634328704e-4, 1.8197008380465151e-7, + -8.4795071170685032e-5, 6.105192082501531e-5, -2.1073920183404862e-5, + -8.8585890141255994e-10, 4.5284535953805377e-6, -2.8427815022504408e-6, + 8.7082341778646412e-7, 3.6886101871706965e-12, -1.5344695190702061e-7, + 8.862466778790695e-8, -2.5184812301826817e-8, -1.0225912098215092e-14, + 3.8969470758154777e-9, -2.1267304792235635e-9, 5.7370135528051385e-10, + -1.887749850169741e-19, -8.0931538694657866e-11, 4.2382723283449199e-11, + -1.1002224534207726e-11 }, + { 1.3324454494800656e-3, -1.9144384985654775e-3, 1.1089369134596637e-3, + 9.932404122642299e-7, -5.0874501293093199e-4, 4.2735056665392884e-4, + -1.6858853767910799e-4, -8.1301893922784998e-9, 4.5284402370562147e-5, + -3.127053674781734e-5, 1.044986828530338e-5, 4.8435226265680926e-11, + -2.1482565873456258e-6, 1.329369701097492e-6, -4.0295693092101029e-7, + -1.7567877666323291e-13, 7.0145043163668257e-8, -4.040787734999483e-8, + 1.1474026743371963e-8, 3.9642746853563325e-18, -1.7804938269892714e-9, + 9.7480262548731646e-10, -2.6405338676507616e-10, 5.794875163403742e-18, + 3.7647749553543836e-11 }, + { 1.579727660730835e-3, 1.6251626278391582e-4, -2.0633421035543276e-3, + 2.1389686185689098e-3, -1.0108559391263003e-3, -3.9912705529919201e-7, + 3.6235025084764691e-4, -2.8143901463712154e-4, 1.0449513336495887e-4, + 2.1211418491830297e-9, -2.5779417251947842e-5, 1.7281818956040463e-5, + -5.6413773872904282e-6, -1.1024320105776174e-11, 1.1223224418895175e-6, + -6.8693396379526735e-7, 2.0653236975414887e-7, 4.6714772409838506e-14, + -3.5609886164949055e-8, 2.0470855345905963e-8, -5.8091738633283358e-9, + -1.332821287582869e-16, 9.0354604391335133e-10, -4.9598782517330834e-10, + 1.3481607129399749e-10 }, + { -4.0725121195140166e-3, 6.4033628338080698e-3, -4.0410161081676618e-3, + -2.183732802866233e-6, 2.1740441801254639e-3, -1.9700440518418892e-3, + 8.3595469747962458e-4, 1.9445447567109655e-8, -2.5779387120421696e-4, + 1.9009987368139304e-4, -6.7696499937438965e-5, -1.4440629666426572e-10, + 1.5712512518742269e-5, -1.0304008744776893e-5, 3.304517767401387e-6, + 7.9829760242325709e-13, -6.4097794149313004e-7, 3.8894624761300056e-7, + -1.1618347644948869e-7, -2.816808630596451e-15, 1.9878012911297093e-8, + -1.1407719956357511e-8, 3.2355857064185555e-9, 4.1759468293455945e-20, + -5.0423112718105824e-10 }, + { -5.9475779383993003e-3, -5.4016476789260452e-4, 8.7910413550767898e-3, + -9.8576315587856125e-3, 5.0134695031021538e-3, 1.2807521786221875e-6, + -2.0626019342754683e-3, 1.7109128573523058e-3, -6.7695312714133799e-4, + -6.9011545676562133e-9, 1.8855128143995902e-4, -1.3395215663491969e-4, + 4.6263183033528039e-5, 4.0034230613321351e-11, -1.0255652921494033e-5, + 6.612086372797651e-6, -2.0913022027253008e-6, -2.0951775649603837e-13, + 3.9756029041993247e-7, -2.3956211978815887e-7, 7.1182883382145864e-8, + 8.925574873053455e-16, -1.2101547235064676e-8, 6.9350618248334386e-9, + -1.9661464453856102e-9 }, + { 1.7402027787522711e-2, -2.9527880945699121e-2, 2.0045875571402799e-2, + 7.0289515966903407e-6, -1.2375421071343148e-2, 1.1976293444235254e-2, + -5.4156038466518525e-3, -6.3290893396418616e-8, 1.8855118129005065e-3, + -1.473473274825001e-3, 5.5515810097708387e-4, 5.2406834412550662e-10, + -1.4357913535784836e-4, 9.9181293224943297e-5, -3.3460834749478311e-5, + -3.5755837291098993e-12, 7.1560851960630076e-6, -4.5516802628155526e-6, + 1.4236576649271475e-6, 1.8803149082089664e-14, -2.6623403898929211e-7, + 1.5950642189595716e-7, -4.7187514673841102e-8, -6.5107872958755177e-17, + 7.9795091026746235e-9 }, + { 3.0249124160905891e-2, 2.4817436002649977e-3, -4.9939134373457022e-2, + 5.9915643009307869e-2, -3.2483207601623391e-2, -5.7212968652103441e-6, + 1.5085251778569354e-2, -1.3261324005088445e-2, 5.5515262632426148e-3, + 3.0263182257030016e-8, -1.7229548406756723e-3, 1.2893570099929637e-3, + -4.6845138348319876e-4, -1.830259937893045e-10, 1.1449739014822654e-4, + -7.7378565221244477e-5, 2.5625836246985201e-5, 1.0766165333192814e-12, + -5.3246809282422621e-6, 3.349634863064464e-6, -1.0381253128684018e-6, + -5.608909920621128e-15, 1.9150821930676591e-7, -1.1418365800203486e-7, + 3.3654425209171788e-8 }, + { -9.9051020880159045e-2, 1.7954011706123486e-1, -1.2989606383463778e-1, + -3.1478872752284357e-5, 9.0510635276848131e-2, -9.2828824411184397e-2, + 4.4412112839877808e-2, 2.7779236316835888e-7, -1.7229543805449697e-2, + 1.4182925050891573e-2, -5.6214161633747336e-3, -2.39598509186381e-9, + 1.6029634366079908e-3, -1.1606784674435773e-3, 4.1001337768153873e-4, + 1.8365800754090661e-11, -9.5844256563655903e-5, 6.3643062337764708e-5, + -2.076250624489065e-5, -1.1806020912804483e-13, 4.2131808239120649e-6, + -2.6262241337012467e-6, 8.0770620494930662e-7, 6.0125912123632725e-16, + -1.4729737374018841e-7 }, + { -1.9994542198219728e-1, -1.5056113040026424e-2, 3.6470239469348489e-1, + -4.6435192311733545e-1, 2.6640934719197893e-1, 3.4038266027147191e-5, + -1.3784338709329624e-1, 1.276467178337056e-1, -5.6213828755200985e-2, + -1.753150885483011e-7, 1.9235592956768113e-2, -1.5088821281095315e-2, + 5.7401854451350123e-3, 1.0622382710310225e-9, -1.5335082692563998e-3, + 1.0819320643228214e-3, -3.7372510193945659e-4, -6.6170909729031985e-12, + 8.4263617380909628e-5, -5.5150706827483479e-5, 1.7769536448348069e-5, + 3.8827923210205533e-14, -3.53513697488768e-6, 2.1865832130045269e-6, + -6.6812849447625594e-7 }, + { 7.2438608504029431e-1, -1.3918010932653375, 1.0654143352413968, + 1.876173868950258e-4, -8.2705501176152696e-1, 8.9352433347828414e-1, + -4.4971003995291339e-1, -1.6107401567546652e-6, 1.9235590165271091e-1, + -1.6597702160042609e-1, 6.8882222681814333e-2, 1.3910091724608687e-8, + -2.146911561508663e-2, 1.6228980898865892e-2, -5.9796016172584256e-3, + -1.1287469112826745e-10, 1.5167451119784857e-3, -1.0478634293553899e-3, + 3.5539072889126421e-4, 8.1704322111801517e-13, -7.7773013442452395e-5, + 5.0291413897007722e-5, -1.6035083867000518e-5, 1.2469354315487605e-14, + 3.1369106244517615e-6 }, + { 1.6668949727276811, 1.165462765994632e-1, -3.3288393225018906, 4.4692325482864037, + -2.6977693045875807, -2.600667859891061e-4, 1.5389017615694539, + -1.4937962361134612, 6.8881964633233148e-1, 1.3077482004552385e-6, + -2.5762963325596288e-1, 2.1097676102125449e-1, -8.3714408359219882e-2, + -7.7920428881354753e-9, 2.4267923064833599e-2, -1.7813678334552311e-2, + 6.3970330388900056e-3, 4.9430807090480523e-11, -1.5554602758465635e-3, + 1.0561196919903214e-3, -3.5277184460472902e-4, 9.3002334645022459e-14, + 7.5285855026557172e-5, -4.8186515569156351e-5, 1.5227271505597605e-5 }, + { -6.6188298861372935, 1.3397985455142589e+1, -1.0789350606845146e+1, + -1.4352254537875018e-3, 9.2333694596189809, -1.0456552819547769e+1, + 5.5105526029033471, 1.2024439690716742e-5, -2.5762961164755816, + 2.3207442745387179, -1.0045728797216284, -1.0207833290021914e-7, + 3.3975092171169466e-1, -2.6720517450757468e-1, 1.0235252851562706e-1, + 8.4329730484871625e-10, -2.7998284958442595e-2, 2.0066274144976813e-2, + -7.0554368915086242e-3, 1.9402238183698188e-12, 1.6562888105449611e-3, + -1.1082898580743683e-3, 3.654545161310169e-4, -5.1290032026971794e-11, + -7.6340103696869031e-5 }, + { -1.7112706061976095e+1, -1.1208044642899116, 3.7131966511885444e+1, + -5.2298271025348962e+1, 3.3058589696624618e+1, 2.4791298976200222e-3, + -2.061089403411526e+1, 2.088672775145582e+1, -1.0045703956517752e+1, + -1.2238783449063012e-5, 4.0770134274221141, -3.473667358470195, + 1.4329352617312006, 7.1359914411879712e-8, -4.4797257159115612e-1, + 3.4112666080644461e-1, -1.2699786326594923e-1, -2.8953677269081528e-10, + 3.3125776278259863e-2, -2.3274087021036101e-2, 8.0399993503648882e-3, + -1.177805216235265e-9, -1.8321624891071668e-3, 1.2108282933588665e-3, + -3.9479941246822517e-4 }, + { 7.389033153567425e+1, -1.5680141270402273e+2, 1.322177542759164e+2, + 1.3692876877324546e-2, -1.2366496885920151e+2, 1.4620689391062729e+2, + -8.0365587724865346e+1, -1.1259851148881298e-4, 4.0770132196179938e+1, + -3.8210340013273034e+1, 1.719522294277362e+1, 9.3519707955168356e-7, + -6.2716159907747034, 5.1168999071852637, -2.0319658112299095, + -4.9507215582761543e-9, 5.9626397294332597e-1, -4.4220765337238094e-1, + 1.6079998700166273e-1, -2.4733786203223402e-8, -4.0307574759979762e-2, + 2.7849050747097869e-2, -9.4751858992054221e-3, 6.419922235909132e-6, + 2.1250180774699461e-3 }, + { 2.1216837098382522e+2, 1.3107863022633868e+1, -4.9698285932871748e+2, + 7.3121595266969204e+2, -4.8213821720890847e+2, -2.8817248692894889e-2, + 3.2616720302947102e+2, -3.4389340280087117e+2, 1.7195193870816232e+2, + 1.4038077378096158e-4, -7.52594195897599e+1, 6.651969984520934e+1, + -2.8447519748152462e+1, -7.613702615875391e-7, 9.5402237105304373, + -7.5175301113311376, 2.8943997568871961, -4.6612194999538201e-7, + -8.0615149598794088e-1, 5.8483006570631029e-1, -2.0845408972964956e-1, + 1.4765818959305817e-4, 5.1000433863753019e-2, -3.3066252141883665e-2, + 1.5109265210467774e-2 }, + { -9.8959643098322368e+2, 2.1925555360905233e+3, -1.9283586782723356e+3, + -1.5925738122215253e-1, 1.9569985945919857e+3, -2.4072514765081556e+3, + 1.3756149959336496e+3, 1.2920735237496668e-3, -7.525941715948055e+2, + 7.3171668742208716e+2, -3.4137023466220065e+2, -9.9857390260608043e-6, + 1.3356313181291573e+2, -1.1276295161252794e+2, 4.6310396098204458e+1, + -7.9237387133614756e-6, -1.4510726927018646e+1, 1.1111771248100563e+1, + -4.1690817945270892, 3.1008219800117808e-3, 1.1220095449981468, + -7.6052379926149916e-1, 3.6262236505085254e-1, 2.216867741940747e-1, + 4.8683443692930507e-1 } +}; + +/* igam.h */ + +#define IGAM_MAXITER 2000 +#define IGAM_IGAM 1 +#define IGAM_IGAMC 0 +#define IGAM_SMALL 20 +#define IGAM_LARGE 200 +#define IGAM_SMALLRATIO 0.3 +#define IGAM_LARGERATIO 4.5 +#define IGAM_BIG 4.503599627370496e15 +#define IGAM_BIGINV 2.22044604925031308085e-16 + +/* Compute + * + * x^a * exp(-x) / gamma(a) + * + * corrected from (15) and (16) in [2] by replacing exp(x - a) with + * exp(a - x). + */ +static double +ceph_igam_fac(double a, double x) +{ + double ax, fac, res, num; + + if (fabs(a - x) > 0.4 * fabs(a)) { + ax = a * log(x) - x - ceph_lgam(a); + if (ax < -CEPH_MAXLOG) { + return 0.0; + } + return exp(ax); + } + + fac = a + LANCZOS_G - 0.5; + res = sqrt(fac / exp(1)) / ceph_lanczos_sum_expg_scaled(a); + + if ((a < 200) && (x < 200)) { + res *= exp(a - x) * pow(x / fac, a); + } else { + num = x - a - LANCZOS_G + 0.5; + res *= exp(a * ceph_log1pmx(num / fac) + x * (0.5 - LANCZOS_G) / fac); + } + + return res; +} + +/* Compute igamc using DLMF 8.9.2. */ +static double +ceph_igamc_continued_fraction(double a, double x) +{ + int i; + double ans, ax, c, yc, r, t, y, z; + double pk, pkm1, pkm2, qk, qkm1, qkm2; + + ax = ceph_igam_fac(a, x); + if (ax == 0.0) { + return 0.0; + } + + /* continued fraction */ + y = 1.0 - a; + z = x + y + 1.0; + c = 0.0; + pkm2 = 1.0; + qkm2 = x; + pkm1 = x + 1.0; + qkm1 = z * x; + ans = pkm1 / qkm1; + + for (i = 0; i < IGAM_MAXITER; i++) { + c += 1.0; + y += 1.0; + z += 2.0; + yc = y * c; + pk = pkm1 * z - pkm2 * yc; + qk = qkm1 * z - qkm2 * yc; + if (qk != 0) { + r = pk / qk; + t = fabs((ans - r) / r); + ans = r; + } else { + t = 1.0; + } + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; + if (fabs(pk) > IGAM_BIG) { + pkm2 *= IGAM_BIGINV; + pkm1 *= IGAM_BIGINV; + qkm2 *= IGAM_BIGINV; + qkm1 *= IGAM_BIGINV; + } + if (t <= CEPH_MACHEP) { + break; + } + } + + return ans * ax; +} + +/* Compute igam using DLMF 8.11.4. */ +static double +ceph_igam_series(double a, double x) +{ + int i; + double ans, ax, c, r; + + ax = ceph_igam_fac(a, x); + if (ax == 0.0) { + return 0.0; + } + + /* power series */ + r = a; + c = 1.0; + ans = 1.0; + + for (i = 0; i < IGAM_MAXITER; i++) { + r += 1.0; + c *= x / r; + ans += c; + if (c <= CEPH_MACHEP * ans) { + break; + } + } + + return ans * ax / a; +} + +/* Compute igamc using DLMF 8.7.3. This is related to the series in + * igam_series but extra care is taken to avoid cancellation. + */ +static double +ceph_igamc_series(double a, double x) +{ + int n; + double fac = 1; + double sum = 0; + double term, logx; + + for (n = 1; n < IGAM_MAXITER; n++) { + fac *= -x / n; + term = fac / (a + n); + sum += term; + if (fabs(term) <= CEPH_MACHEP * fabs(sum)) { + break; + } + } + + logx = log(x); + term = -ceph_expm1(a * logx - ceph_lgam1p(a)); + return term - exp(a * logx - ceph_lgam(a)) * sum; +} + +/* Compute igam/igamc using DLMF 8.12.3/8.12.4. */ +static double +ceph_asymptotic_series(double a, double x, int func) +{ + int k, n, sgn; + int maxpow = 0; + double lambda = x / a; + double sigma = (x - a) / a; + double eta, res, ck, ckterm, term, absterm; + double absoldterm = INFINITY; + double etapow[IGAM_ASYMP_COEFF_N] = { 1 }; + double sum = 0; + double afac = 1; + + if (func == IGAM_IGAM) { + sgn = -1; + } else { + sgn = 1; + } + + if (lambda > 1) { + eta = sqrt(-2 * ceph_log1pmx(sigma)); + } else if (lambda < 1) { + eta = -sqrt(-2 * ceph_log1pmx(sigma)); + } else { + eta = 0; + } + res = 0.5 * ceph_erfc(sgn * eta * sqrt(a / 2)); + + for (k = 0; k < IGAM_ASYMP_COEFF_K; k++) { + ck = igam_asymp_coeff_d[k][0]; + for (n = 1; n < IGAM_ASYMP_COEFF_N; n++) { + if (n > maxpow) { + etapow[n] = eta * etapow[n - 1]; + maxpow += 1; + } + ckterm = igam_asymp_coeff_d[k][n] * etapow[n]; + ck += ckterm; + if (fabs(ckterm) < CEPH_MACHEP * fabs(ck)) { + break; + } + } + term = ck * afac; + absterm = fabs(term); + if (absterm > absoldterm) { + break; + } + sum += term; + if (absterm < CEPH_MACHEP * fabs(sum)) { + break; + } + absoldterm = absterm; + afac /= a; + } + res += sgn * exp(-0.5 * a * eta * eta) * sum / sqrt(2 * CEPH_PI * a); + + return res; +} + +static double ceph_igamc(double a, double x); + +static double +ceph_igam(double a, double x) +{ + double absxma_a; + + if (isnan(a) || isnan(x)) { + return NAN; + } + + if (x < 0 || a < 0) { + return NAN; + } else if (a == 0) { + if (x > 0) { + return 1; + } else { + return NAN; + } + } else if (x == 0) { + /* Zero integration limit */ + return 0; + } else if (isinf(a)) { + if (isinf(x)) { + return NAN; + } + return 0; + } else if (isinf(x)) { + return 1; + } + + /* Asymptotic regime where a ~ x; see [2]. */ + absxma_a = fabs(x - a) / a; + if ((a > IGAM_SMALL) && (a < IGAM_LARGE) && (absxma_a < IGAM_SMALLRATIO)) { + return ceph_asymptotic_series(a, x, IGAM_IGAM); + } else if ((a > IGAM_LARGE) && (absxma_a < IGAM_LARGERATIO / sqrt(a))) { + return ceph_asymptotic_series(a, x, IGAM_IGAM); + } + + if ((x > 1.0) && (x > a)) { + return 1.0 - ceph_igamc(a, x); + } + + return ceph_igam_series(a, x); +} + +static double +ceph_igamc(double a, double x) +{ + double absxma_a; + + if (isnan(a) || isnan(x)) { + return NAN; + } + + if (x < 0 || a < 0) { + return NAN; + } else if (a == 0) { + if (x > 0) { + return 0; + } else { + return NAN; + } + } else if (x == 0) { + return 1; + } else if (isinf(a)) { + if (isinf(x)) { + return NAN; + } + return 1; + } else if (isinf(x)) { + return 0; + } + + /* Asymptotic regime where a ~ x; see [2]. */ + absxma_a = fabs(x - a) / a; + if ((a > IGAM_SMALL) && (a < IGAM_LARGE) && (absxma_a < IGAM_SMALLRATIO)) { + return ceph_asymptotic_series(a, x, IGAM_IGAMC); + } else if ((a > IGAM_LARGE) && (absxma_a < IGAM_LARGERATIO / sqrt(a))) { + return ceph_asymptotic_series(a, x, IGAM_IGAMC); + } + + /* Everywhere else; see [2]. */ + if (x > 1.1) { + if (x < a) { + return 1.0 - ceph_igam_series(a, x); + } else { + return ceph_igamc_continued_fraction(a, x); + } + } else if (x <= 0.5) { + if (-0.4 / log(x) < a) { + return 1.0 - ceph_igam_series(a, x); + } else { + return ceph_igamc_series(a, x); + } + } else { + if (x * 1.1 < a) { + return 1.0 - ceph_igam_series(a, x); + } else { + return ceph_igamc_series(a, x); + } + } +} + +/* igami.h */ + +static double +ceph_find_inverse_s(double p, double q) +{ + /* + * Computation of the Incomplete Gamma Function Ratios and their Inverse + * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR. + * ACM Transactions on Mathematical Software, Vol. 12, No. 4, + * December 1986, Pages 377-393. + * + * See equation 32. + */ + double s, t; + static const double a[4] + = { 0.213623493715853, 4.28342155967104, 11.6616720288968, 3.31125922108741 }; + static const double b[5] = { 0.3611708101884203e-1, 1.27364489782223, + 6.40691597760039, 6.61053765625462, 1 }; + + if (p < 0.5) { + t = sqrt(-2 * log(p)); + } else { + t = sqrt(-2 * log(q)); + } + s = t - ceph_polevl(t, a, 3) / ceph_polevl(t, b, 4); + if (p < 0.5) { + s = -s; + } + return s; +} + +static double +ceph_didonato_SN(double a, double x, unsigned N, double tolerance) +{ + /* + * Computation of the Incomplete Gamma Function Ratios and their Inverse + * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR. + * ACM Transactions on Mathematical Software, Vol. 12, No. 4, + * December 1986, Pages 377-393. + * + * See equation 34. + */ + double sum = 1.0; + unsigned i; + double partial; + + if (N >= 1) { + partial = x / (a + 1); + + sum += partial; + for (i = 2; i <= N; ++i) { + partial *= x / (a + i); + sum += partial; + if (partial < tolerance) { + break; + } + } + } + return sum; +} + +static double +ceph_find_inverse_gamma(double a, double p, double q) +{ + /* + * In order to understand what's going on here, you will + * need to refer to: + * + * Computation of the Incomplete Gamma Function Ratios and their Inverse + * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR. + * ACM Transactions on Mathematical Software, Vol. 12, No. 4, + * December 1986, Pages 377-393. + */ + double result; + double g, b, u, t, y, c1, c1_2, c1_3, c1_4, a_2, a_3, c2, c3, c4, c5, y_2, y_3, y_4; + double s, s_2, s_3, s_4, s_5, ra, w, D, lg, lb, z, ap1, ap2, v, ls; + + if (a == 1) { + if (q > 0.9) { + result = -log1p(-p); + } else { + result = -log(q); + } + } else if (a < 1) { + g = ceph_Gamma(a); + b = q * g; + + if ((b > 0.6) || ((b >= 0.45) && (a >= 0.3))) { + /* DiDonato & Morris Eq 21: + * + * There is a slight variation from DiDonato and Morris here: + * the first form given here is unstable when p is close to 1, + * making it impossible to compute the inverse of Q(a,x) for small + * q. Fortunately the second form works perfectly well in this case. + */ + if ((b * q > 1e-8) && (q > 1e-5)) { + u = pow(p * g * a, 1 / a); + } else { + u = exp((-q / a) - CEPH_SCIPY_EULER); + } + result = u / (1 - (u / (a + 1))); + } else if ((a < 0.3) && (b >= 0.35)) { + /* DiDonato & Morris Eq 22: */ + t = exp(-CEPH_SCIPY_EULER - b); + u = t * exp(t); + result = t * exp(u); + } else if ((b > 0.15) || (a >= 0.3)) { + /* DiDonato & Morris Eq 23: */ + y = -log(b); + u = y - (1 - a) * log(y); + result = y - (1 - a) * log(u) - log(1 + (1 - a) / (1 + u)); + } else if (b > 0.1) { + /* DiDonato & Morris Eq 24: */ + y = -log(b); + u = y - (1 - a) * log(y); + result = y - (1 - a) * log(u) + - log((u * u + 2 * (3 - a) * u + (2 - a) * (3 - a)) + / (u * u + (5 - a) * u + 2)); + } else { + /* DiDonato & Morris Eq 25: */ + y = -log(b); + c1 = (a - 1) * log(y); + c1_2 = c1 * c1; + c1_3 = c1_2 * c1; + c1_4 = c1_2 * c1_2; + a_2 = a * a; + a_3 = a_2 * a; + + c2 = (a - 1) * (1 + c1); + c3 = (a - 1) * (-(c1_2 / 2) + (a - 2) * c1 + (3 * a - 5) / 2); + c4 = (a - 1) + * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + (a_2 - 6 * a + 7) * c1 + + (11 * a_2 - 46 * a + 47) / 6); + c5 = (a - 1) + * (-(c1_4 / 4) + (11 * a - 17) * c1_3 / 6 + + (-3 * a_2 + 13 * a - 13) * c1_2 + + (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2 + + (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12); + + y_2 = y * y; + y_3 = y_2 * y; + y_4 = y_2 * y_2; + result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4); + } + } else { + /* DiDonato and Morris Eq 31: */ + s = ceph_find_inverse_s(p, q); + + s_2 = s * s; + s_3 = s_2 * s; + s_4 = s_2 * s_2; + s_5 = s_4 * s; + ra = sqrt(a); + + w = a + s * ra + (s_2 - 1) / 3; + w += (s_3 - 7 * s) / (36 * ra); + w -= (3 * s_4 + 7 * s_2 - 16) / (810 * a); + w += (9 * s_5 + 256 * s_3 - 433 * s) / (38880 * a * ra); + + if ((a >= 500) && (fabs(1 - w / a) < 1e-6)) { + result = w; + } else if (p > 0.5) { + if (w < 3 * a) { + result = w; + } else { + D = fmax(2, a * (a - 1)); + lg = ceph_lgam(a); + lb = log(q) + lg; + if (lb < -D * 2.3) { + /* DiDonato and Morris Eq 25: */ + y = -lb; + c1 = (a - 1) * log(y); + c1_2 = c1 * c1; + c1_3 = c1_2 * c1; + c1_4 = c1_2 * c1_2; + a_2 = a * a; + a_3 = a_2 * a; + + c2 = (a - 1) * (1 + c1); + c3 = (a - 1) * (-(c1_2 / 2) + (a - 2) * c1 + (3 * a - 5) / 2); + c4 = (a - 1) + * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + (a_2 - 6 * a + 7) * c1 + + (11 * a_2 - 46 * a + 47) / 6); + c5 = (a - 1) + * (-(c1_4 / 4) + (11 * a - 17) * c1_3 / 6 + + (-3 * a_2 + 13 * a - 13) * c1_2 + + (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2 + + (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12); + + y_2 = y * y; + y_3 = y_2 * y; + y_4 = y_2 * y_2; + result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4); + } else { + /* DiDonato and Morris Eq 33: */ + u = -lb + (a - 1) * log(w) - log(1 + (1 - a) / (1 + w)); + result = -lb + (a - 1) * log(u) - log(1 + (1 - a) / (1 + u)); + } + } + } else { + z = w; + ap1 = a + 1; + ap2 = a + 2; + if (w < 0.15 * ap1) { + /* DiDonato and Morris Eq 35: */ + v = log(p) + ceph_lgam(ap1); + z = exp((v + w) / a); + s = log1p(z / ap1 * (1 + z / ap2)); + z = exp((v + z - s) / a); + s = log1p(z / ap1 * (1 + z / ap2)); + z = exp((v + z - s) / a); + s = log1p(z / ap1 * (1 + z / ap2 * (1 + z / (a + 3)))); + z = exp((v + z - s) / a); + } + + if ((z <= 0.01 * ap1) || (z > 0.7 * ap1)) { + result = z; + } else { + /* DiDonato and Morris Eq 36: */ + ls = log(ceph_didonato_SN(a, z, 100, 1e-4)); + v = log(p) + ceph_lgam(ap1); + z = exp((v + z - ls) / a); + result = z * (1 - (a * log(z) - z - v + ls) / (a - z)); + } + } + } + return result; +} + +/* The inverse of igamc. Its only caller, tsd_gammaincinv, passes 0 < q < 0.1 and + * a >= 0, so the argument checks of igamci() are omitted. */ +static double +ceph_igamci(double a, double q) +{ + int i; + double x, fac, f_fp, fpp_fp; + + x = ceph_find_inverse_gamma(a, 1 - q, q); + for (i = 0; i < 3; i++) { + fac = ceph_igam_fac(a, x); + if (fac == 0.0) { + return x; + } + f_fp = (ceph_igamc(a, x) - q) * x / (-fac); + fpp_fp = -1.0 + (a - 1) / x; + if (isinf(fpp_fp)) { + x = x - f_fp; + } else { + x = x - f_fp / (1.0 - 0.5 * f_fp * fpp_fp); + } + } + + return x; +} + +/* igami(). As in xsf, where set_error only reports it, an `a` or `p` outside the + * domain is not rejected: the computation goes on (and its result is NaN). */ +double +tsd_gammaincinv(double a, double p) +{ + int i; + double x, fac, f_fp, fpp_fp; + + if (isnan(a) || isnan(p)) { + return NAN; + } else if ((a < 0) || (p < 0) || (p > 1)) { + /* Outside the domain: fall through. */ + } else if (p == 0.0) { + return 0.0; + } else if (p == 1.0) { + return INFINITY; + } else if (p > 0.9) { + return ceph_igamci(a, 1 - p); + } + + x = ceph_find_inverse_gamma(a, p, 1 - p); + /* Halley's method */ + for (i = 0; i < 3; i++) { + fac = ceph_igam_fac(a, x); + if (fac == 0.0) { + return x; + } + f_fp = (ceph_igam(a, x) - p) * x / fac; + /* The ratio of the first and second derivatives simplifies */ + fpp_fp = -1.0 + (a - 1) / x; + if (isinf(fpp_fp)) { + /* Resort to Newton's method in the case of overflow */ + x = x - f_fp; + } else { + x = x - f_fp / (1.0 - 0.5 * f_fp * fpp_fp); + } + } + + return x; +} diff --git a/lib/meson.build b/lib/meson.build index 674e8648..25a02366 100644 --- a/lib/meson.build +++ b/lib/meson.build @@ -15,7 +15,7 @@ if get_option('buildtype') == 'debug' extra_c_args += ['-DTSD_TRACE_ERRORS'] endif -tsdate_sources = ['err.c', 'hypergeo.c', 'approx.c', 'rescaling.c', +tsdate_sources = ['err.c', 'gammaincinv.c', 'hypergeo.c', 'approx.c', 'rescaling.c', 'phasing.c', 'util.c', 'prior.c', 'variational.c'] tsdate_lib = static_library('tsdate', diff --git a/lib/rescaling.c b/lib/rescaling.c index e4cd7291..83ec5d69 100644 --- a/lib/rescaling.c +++ b/lib/rescaling.c @@ -804,7 +804,7 @@ int tsd_piecewise_scale_posterior(tsd_size_t num_posteriors, const double *posteriors, const uint8_t *posteriors_fixed, tsd_size_t num_breaks, const double *original_breaks, const double *rescaled_breaks, double quantile_width, - double max_shape, tsd_gammaincinv_fn gammaincinv, double *new_posteriors) + double max_shape, double *new_posteriors) { int ret = 0; double *lower = NULL; @@ -851,8 +851,8 @@ tsd_piecewise_scale_posterior(tsd_size_t num_posteriors, const double *posterior if (!posteriors_fixed[j]) { alpha = posteriors[2 * j]; beta = posteriors[2 * j + 1]; - lower[j] = gammaincinv(alpha + 1, quant_lower) / beta; - upper[j] = gammaincinv(alpha + 1, quant_upper) / beta; + lower[j] = tsd_gammaincinv(alpha + 1, quant_lower) / beta; + upper[j] = tsd_gammaincinv(alpha + 1, quant_upper) / beta; midpt[j] = (alpha + 1) / beta; } } @@ -887,8 +887,8 @@ tsd_piecewise_scale_posterior(tsd_size_t num_posteriors, const double *posterior ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); goto out; } - ret = tsd_approximate_gamma_iqr(quant_lower, quant_upper, lower[j], upper[j], - max_shape, gammaincinv, gamma_pars); + ret = tsd_approximate_gamma_iqr( + quant_lower, quant_upper, lower[j], upper[j], max_shape, gamma_pars); if (ret != 0) { goto out; } diff --git a/lib/tests/tests.c b/lib/tests/tests.c index c97f9204..02ae5260 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -312,27 +312,21 @@ test_hyp2f1_laplace_errors(void) CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); } -/* - * The library takes gammaincinv as a parameter (the Python module passes SciPy's). - * These tests check return codes only, so a placeholder that ignores the shape will do. - */ -static double -test_gammaincinv(double a, double p) -{ - (void) a; - return p; -} - -static double -test_zero_inv(double a, double p) -{ - return a * 0.0 * p; -} - -static double -test_tiny_inv(double a, double p) +static void +test_gammaincinv(void) { - return 1e-200 * a * p; + CU_ASSERT(isfinite(tsd_gammaincinv(0.5, 0.25))); + CU_ASSERT(isfinite(tsd_gammaincinv(1.0, 0.5))); + CU_ASSERT(isfinite(tsd_gammaincinv(3.0, 0.95))); + CU_ASSERT(isfinite(tsd_gammaincinv(1e4, 1e-10))); + CU_ASSERT_EQUAL(tsd_gammaincinv(2.0, 0.0), 0.0); + CU_ASSERT(isinf(tsd_gammaincinv(2.0, 1.0))); + /* p ** (1 / a) underflows */ + CU_ASSERT_EQUAL(tsd_gammaincinv(1e-4, 0.25), 0.0); + CU_ASSERT(isnan(tsd_gammaincinv(NAN, 0.5))); + CU_ASSERT(isnan(tsd_gammaincinv(2.0, NAN))); + CU_ASSERT(isnan(tsd_gammaincinv(-1.0, 0.5))); + CU_ASSERT(isnan(tsd_gammaincinv(2.0, 1.5))); } static void @@ -400,34 +394,38 @@ test_approximate_gamma_iqr(void) int ret; /* Newton iteration */ - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 3.0, 50.0, test_gammaincinv, out); + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 3.0, 50.0, out); CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(isfinite(out[0]) && isfinite(out[1])); /* capped shape: equal quantiles, or a lower bound above the cap */ - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 3.0, 3.0, 50.0, test_gammaincinv, out); + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 3.0, 3.0, 50.0, out); CU_ASSERT_EQUAL(ret, 0); CU_ASSERT_EQUAL(out[0], 49.0); - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 1.1, 2.0, test_gammaincinv, out); + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 1.1, 2.0, out); CU_ASSERT_EQUAL(ret, 0); CU_ASSERT_EQUAL(out[0], 1.0); /* errors */ - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 2.0, 1.0, 50.0, test_gammaincinv, out); + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 2.0, 1.0, 50.0, out); CU_ASSERT_EQUAL(ret, TSD_ERR_UNSORTED_QUANTILES); - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 0.0, 0.0, 50.0, test_gammaincinv, out); + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 0.0, 0.0, 50.0, out); CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - ret = tsd_approximate_gamma_iqr(0.0, 0.75, 1.0, 2.0, 50.0, test_gammaincinv, out); + ret = tsd_approximate_gamma_iqr(0.0, 0.75, 1.0, 2.0, 50.0, out); CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 0.0, 1.0, 50.0, test_gammaincinv, out); + ret = tsd_approximate_gamma_iqr(0.25, 0.75, 0.0, 1.0, 50.0, out); CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - /* quantiles that the placeholder cannot match: no convergence, or a step outside - * the domain of the incomplete gamma derivative */ - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 2.9, 50.0, test_gammaincinv, out); + /* no convergence, or a step outside the domain of the incomplete gamma + * derivative */ + ret = tsd_approximate_gamma_iqr(1e-200, 0.99, 1.0, 1.2, 1e300, out); CU_ASSERT_EQUAL(ret, TSD_ERR_QUANTILE_MAX_ITERATIONS); - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 10.0, 50.0, test_gammaincinv, out); + ret = tsd_approximate_gamma_iqr(1e-250, 0.5, 1.0, 1e100, 1e300, out); CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - /* a quantile function that returns zero, or underflows when squared */ - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 2.0, 50.0, test_zero_inv, out); + /* the lower quantile is zero, or underflows when squared */ + ret = tsd_approximate_gamma_iqr(1e-10, 0.01, 1.0, 1e300, 50.0, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + ret = tsd_approximate_gamma_iqr(1e-200, 0.5, 1.0, 5e199, 50.0, out); CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 2.0, 50.0, test_tiny_inv, out); + /* the gradient is zero */ + ret = tsd_approximate_gamma_iqr(0.1, 0.9, 1.0, 1.0000001, 1e20, out); CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); } @@ -1085,42 +1083,43 @@ test_piecewise_scale_posterior(void) const double bad_posteriors[] = { -1.0, 1.0, 1.0, 1.0 }; const double zero_rate[] = { 1.0, INFINITY }; const double near_pole[] = { -0.9999, 1.0 }; + const double large_shape[] = { 1e8, 1e8 }; double out[8]; int ret; ret = tsd_piecewise_scale_posterior( - 4, posteriors, fixed, 3, original, rescaled, 0.5, 1000.0, test_gammaincinv, out); + 4, posteriors, fixed, 3, original, rescaled, 0.5, 1000.0, out); CU_ASSERT_EQUAL(ret, 0); CU_ASSERT(isnan(out[4])); CU_ASSERT(isfinite(out[0]) && isfinite(out[1])); - ret = tsd_piecewise_scale_posterior(4, posteriors, none_fixed, 3, original, rescaled, - 0.5, 1000.0, test_gammaincinv, out); + ret = tsd_piecewise_scale_posterior( + 4, posteriors, none_fixed, 3, original, rescaled, 0.5, 1000.0, out); CU_ASSERT_EQUAL(ret, 0); ret = tsd_piecewise_scale_posterior( - 4, posteriors, fixed, 3, original, rescaled, 1.0, 1000.0, test_gammaincinv, out); + 4, posteriors, fixed, 3, original, rescaled, 1.0, 1000.0, out); CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_QUANTILE_WIDTH); ret = tsd_piecewise_scale_posterior( - 4, posteriors, fixed, 3, original, flat, 0.5, 1000.0, test_gammaincinv, out); + 4, posteriors, fixed, 3, original, flat, 0.5, 1000.0, out); CU_ASSERT_EQUAL(ret, TSD_ERR_NON_INCREASING_BREAKPOINTS); - ret = tsd_piecewise_scale_posterior(2, bad_posteriors, none_fixed, 3, original, - rescaled, 0.5, 1000.0, test_gammaincinv, out); + ret = tsd_piecewise_scale_posterior( + 2, bad_posteriors, none_fixed, 3, original, rescaled, 0.5, 1000.0, out); CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_POSTERIOR); - ret = tsd_piecewise_scale_posterior(4, posteriors, fixed, 3, late_original, rescaled, - 0.5, 1000.0, test_gammaincinv, out); + ret = tsd_piecewise_scale_posterior( + 4, posteriors, fixed, 3, late_original, rescaled, 0.5, 1000.0, out); CU_ASSERT_EQUAL(ret, TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT); ret = tsd_piecewise_scale_posterior( - 0, posteriors, fixed, 3, original, rescaled, 0.5, 1000.0, test_gammaincinv, out); + 0, posteriors, fixed, 3, original, rescaled, 0.5, 1000.0, out); CU_ASSERT_EQUAL(ret, TSD_ERR_NO_POSTERIORS); - /* an infinite rate gives a zero lower quantile, and a zero rate a zero mean */ - ret = tsd_piecewise_scale_posterior(1, zero_rate, none_fixed, 3, original, rescaled, - 0.5, 1000.0, test_gammaincinv, out); + /* an infinite rate, or a shape close to zero, gives a zero lower quantile */ + ret = tsd_piecewise_scale_posterior( + 1, zero_rate, none_fixed, 3, original, rescaled, 0.5, 1000.0, out); CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - ret = tsd_piecewise_scale_posterior(1, near_pole, none_fixed, 3, original, rescaled, - 0.5, 1000.0, test_zero_inv, out); + ret = tsd_piecewise_scale_posterior( + 1, near_pole, none_fixed, 3, original, rescaled, 0.5, 1000.0, out); CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); /* failures of the interquantile approximation are passed on */ - ret = tsd_piecewise_scale_posterior(1, posteriors, none_fixed, 3, original, rescaled, - 0.5, 1000.0, test_zero_inv, out); + ret = tsd_piecewise_scale_posterior( + 1, large_shape, none_fixed, 3, original, rescaled, 0.5, 1e300, out); CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); } @@ -1455,6 +1454,7 @@ main(int argc, char **argv) { "test_hyp1f1_laplace_errors", test_hyp1f1_laplace_errors }, { "test_hyp2f1_laplace", test_hyp2f1_laplace }, { "test_hyp2f1_laplace_errors", test_hyp2f1_laplace_errors }, + { "test_gammaincinv", test_gammaincinv }, { "test_approximate_log_moments", test_approximate_log_moments }, { "test_approximate_gamma_kl", test_approximate_gamma_kl }, { "test_approximate_gamma_mom", test_approximate_gamma_mom }, diff --git a/lib/tsdate.h b/lib/tsdate.h index 55f0d709..b2843594 100644 --- a/lib/tsdate.h +++ b/lib/tsdate.h @@ -54,15 +54,12 @@ int tsd_hyp1f1_laplace(double a, double b, double x, double *out); int tsd_hyp2f1_laplace(double a, double b, double c, double x, double *out); /* - * The inverse of the regularised lower incomplete gamma function, x such that - * gammainc(a, x) = p, is not implemented in the library: SciPy's gammaincinv is - * called. The caller (the Python module) supplies it, and - * library functions that need it (the approx and rescaling functions) take a - * parameter of this type, so that the library has no global state and no dependency - * on SciPy. The function returns NaN, 0 or infinity (not an error) for arguments - * outside the domain. + * The inverse of the regularised lower incomplete gamma function (gammaincinv.c): x + * such that gammainc(a, x) = p, identical to scipy.special.gammaincinv. It returns 0 + * for p = 0, infinity for p = 1 and NaN (not an error) for arguments outside the + * domain. */ -typedef double (*tsd_gammaincinv_fn)(double a, double p); +double tsd_gammaincinv(double a, double p); /* * Approximations of gamma distributions and of the moments of the EP updates @@ -102,8 +99,8 @@ int tsd_approximate_log_moments( double mean, double variance, double *logx, double *xlogx, double *logx2); int tsd_approximate_gamma_kl(double x, double logx, double out[2]); int tsd_approximate_gamma_mom(double mean, double variance, double out[2]); -int tsd_approximate_gamma_iqr(double q1, double q2, double x1, double x2, - double max_shape, tsd_gammaincinv_fn gammaincinv, double out[2]); +int tsd_approximate_gamma_iqr( + double q1, double q2, double x1, double x2, double max_shape, double out[2]); /* The natural parameters of the gamma whose mean and mean log are the averages of * those of `num_gammas` gammas given by natural parameters `alpha`, `beta`. */ int tsd_average_gammas( @@ -284,7 +281,7 @@ int tsd_piecewise_scale_point_estimate(tsd_size_t num_points, int tsd_piecewise_scale_posterior(tsd_size_t num_posteriors, const double *posteriors, const uint8_t *posteriors_fixed, tsd_size_t num_breaks, const double *original_breaks, const double *rescaled_breaks, double quantile_width, - double max_shape, tsd_gammaincinv_fn gammaincinv, double *new_posteriors); + double max_shape, double *new_posteriors); /* * Expectation propagation passes (variational.c). diff --git a/setup.py b/setup.py index 57fed3f8..65b09b83 100644 --- a/setup.py +++ b/setup.py @@ -11,6 +11,7 @@ tsd_source_files = [ "err.c", + "gammaincinv.c", "hypergeo.c", "approx.c", "rescaling.c", diff --git a/tests/oracle/hypergeo.py b/tests/oracle/hypergeo.py index 3539dfbd..fe58ea59 100644 --- a/tests/oracle/hypergeo.py +++ b/tests/oracle/hypergeo.py @@ -20,12 +20,12 @@ from ._libm import erf, exp, ipow, lgamma, log, pow, sin, sqrt, tan # noqa: A004 -# The C library calls SciPy's Cython gammaincinv, which is -# `scipy.special.gammaincinv`. The ufunc returns an `np.float64`, which is converted -# so that callers divide by it with Python semantics (ZeroDivisionError). +# The C library's gammaincinv is a port of `scipy.special.gammaincinv`, which is the +# reference. The ufunc returns an `np.float64`, which is converted so that callers +# divide by it with Python semantics (ZeroDivisionError). def _gammainc_inv(a, x): """ - scipy.special.cython_special.gammaincinv + scipy.special.gammaincinv """ return float(scipy.special.gammaincinv(a, x)) diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index 0044387d..07908940 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -254,18 +254,60 @@ def test_domain(self, name, args, expected): parity(name, args, expected) +GAMMAINC_INV_EDGES = [ + # shapes outside the domain reach the poles, the reflection formula and Stirling's + # formula in the gamma function of the initial approximation + (-40.0, 0.5), + (-1e-10, 0.5), + (-46.752919088367761, -0.92813118104822934), + (-39.271336710778996, -5.5046762376648753e-13), + (-640.33633048902459, 0.13827951904386282), + (-150.91834423637511, 1.0674574812874198), + (-63.911108928063285, -0.68496137764304876), + # the gamma function's recurrence lands on 2 exactly + (nextafter(1.0, 0), 0.5), + # the series of igamc for small arguments, and a Newton step where the ratio of the + # derivatives overflows, in the complemented inversion + (0.0018725572425875394, 0.93432222410629528), + (1.4851015014453666e-07, 0.99989259056538193), +] + + def gammainc_inv_grid(): shapes = [1e-300, 1e-100, 1e-10, 1e-3, 0.1, 0.5, 1.0, 2.0, 10.0, 100.0] shapes += [1e3, 1e4, 1e5, 1e6, 1e8, 1e10, 1e15, 1e300, INF, 0.0, -1.0, NAN] quantiles = [0.0, 5e-324, 1e-300, 1e-100, 1e-20, 1e-10, 1e-3, 0.5, 0.999] quantiles += [1 - 1e-10, nextafter(1.0, 0), 1.0, nextafter(1.0, 2), -0.1, NAN] - return [(a, q) for a in shapes for q in quantiles] + grid = [(a, q) for a in shapes for q in quantiles] + return grid + GAMMAINC_INV_EDGES + + +def gammainc_inv_random(): + rng = np.random.default_rng(5) + n = 1000 + specials = [0.0, 5e-324, 1e-300, nextafter(1.0, 0), 1.0, -0.1, 1.1, NAN] + invalid_shapes = [0.0, -0.0, -1e-3, -0.5, -1.0, -1.5, -40.5, -INF, INF, NAN] + shapes = [ + log_uniform(rng, -3, 5, 2 * n), + log_uniform(rng, -3, 5, n), + log_uniform(rng, -3, 5, n // 2), + log_uniform(rng, -3, 5, n // 4), + rng.choice(invalid_shapes, n // 4), + ] + quantiles = [ + rng.uniform(0, 1, 2 * n), + log_uniform(rng, -300, 0, n), + 1 - log_uniform(rng, -16, -1, n // 2), + rng.choice(specials, n // 4), + rng.uniform(-0.5, 1.5, n // 4), + ] + return np.concatenate(shapes), np.concatenate(quantiles) class TestGammaincInv: """ - `_gammainc_inv` is SciPy's ``gammaincinv`` (cephes ``igami``), which the C - library calls; checked exactly, including away from the interior of the + `_gammainc_inv` is SciPy's ``gammaincinv`` (cephes ``igami``), of which the C + library's is a port; checked exactly, including away from the interior of the domain (the result is a NaN, 0 or inf for invalid shapes and quantiles, with no exception). """ @@ -274,6 +316,17 @@ class TestGammaincInv: def test_matches_oracle(self, a, q): parity("_gammainc_inv", (a, q)) + def test_matches_oracle_random(self): + """ + Seeded draws of log-uniform shapes with quantiles that are uniform, tiny, close + to one (the complemented inversion), special values or outside [0, 1], and of + shapes outside the domain. + """ + shapes, quantiles = gammainc_inv_random() + actual = [_tsdate.gammainc_inv(a, q) for a, q in zip(shapes, quantiles)] + desired = [hypergeo._gammainc_inv(a, q) for a, q in zip(shapes, quantiles)] + assert_same_values(np.array(actual), np.array(desired)) + HYPERU_DOMAIN = [ ((1.0, 1.0, 1.0), "finite"), # b == a is allowed diff --git a/tests/test_python_c_scalar.py b/tests/test_python_c_scalar.py index 05775b76..ac6ff91a 100644 --- a/tests/test_python_c_scalar.py +++ b/tests/test_python_c_scalar.py @@ -85,8 +85,8 @@ def test_nan_is_not_an_error(self): class TestGammaincInv: """ - ``gammainc_inv`` calls SciPy's ``gammaincinv`` through its Cython C API, so it is - identical to ``scipy.special.gammaincinv``, including outside the domain. + ``gammainc_inv`` is a port of SciPy's ``gammaincinv``, identical to + ``scipy.special.gammaincinv``, including outside the domain. """ @pytest.mark.parametrize( @@ -110,14 +110,13 @@ def test_matches_scipy(self, a, q): class TestScipyDependency: - def test_import_fails_without_scipy_cython_api(self): + def test_import_without_scipy(self): code = ( - "import sys; sys.modules['scipy.special.cython_special'] = None\n" - "import _tsdate" + "import sys; sys.modules['scipy'] = None\n" + "import _tsdate; print(_tsdate.gammainc_inv(2.0, 0.5))" ) result = subprocess.run( [sys.executable, "-c", code], capture_output=True, text=True ) - assert result.returncode != 0 - assert "ImportError" in result.stderr - assert "cython_special" in result.stderr + assert result.returncode == 0, result.stderr + assert float(result.stdout) == scipy.special.gammaincinv(2.0, 0.5) From 8126562f717bd7be7a231606945c6a4ebff0e56c Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 11:21:30 -0800 Subject: [PATCH 26/56] Return NaN for gammaincinv arguments outside the domain tsd_gammaincinv returns NaN directly for a < 0, p outside [0, 1], and a = 0 or a = inf with 0 < p < 1 (p = 0 and p = 1 still give 0 and inf), instead of letting the computation run into NaN. Inside the domain the results are unchanged and identical to scipy.special.gammaincinv (0 mismatches in about 4 million points). The helpers keep only the branches their arguments can reach: Gamma is only called for 0 < x < 1 and lgam for positive finite x, so the poles, the reflection formulas, Stirling's formula, sinpi and the sign of lgam go, as do the checks on the shape in igam and igamc. The oracle applies the same domain. --- lib/gammaincinv.c | 253 ++++------------------------------ tests/oracle/hypergeo.py | 16 ++- tests/test_oracle_hypergeo.py | 16 +-- 3 files changed, 44 insertions(+), 241 deletions(-) diff --git a/lib/gammaincinv.c b/lib/gammaincinv.c index 71c350b5..9b635a91 100644 --- a/lib/gammaincinv.c +++ b/lib/gammaincinv.c @@ -7,12 +7,13 @@ * include/xsf/cephes/: igami.h (igami, igamci, find_inverse_gamma, find_inverse_s, * didonato_SN), igam.h (igam, igamc, igam_fac, igam_series, igamc_series, * igamc_continued_fraction, asymptotic_series), igam_asymp_coeff.h, gamma.h (Gamma, - * stirf, lgam, lgam_sgn, lgam_large_x), lanczos.h (lanczos_sum_expg_scaled), - * unity.h (log1p, log1pmx, expm1, lgam1p, lgam1p_taylor), zeta.h (zeta), ndtr.h - * (erf, erfc), trig.h (sinpi), polevl.h (polevl, p1evl, ratevl) and const.h. The - * operations, constants, branches and iteration limits are those of xsf; error - * reporting (set_error, a no-op in xsf's default build) is dropped and the in-band - * return values are kept. + * lgam, lgam_large_x), lanczos.h (lanczos_sum_expg_scaled), unity.h (log1p, + * log1pmx, expm1, lgam1p, lgam1p_taylor), zeta.h (zeta), ndtr.h (erf, erfc), + * polevl.h (polevl, p1evl, ratevl) and const.h. The operations, constants, branches + * and iteration limits are those of xsf. Arguments outside the domain give NaN + * directly, and the helper functions keep only the branches that the arguments they + * receive can reach; error reporting (set_error, a no-op in xsf's default build) is + * dropped and the in-band return values are kept. * * The notices of the original files and the licences they are distributed under * follow. @@ -30,8 +31,6 @@ * and lanczos.h: (C) Copyright John Maddock 2006. Use, modification and * distribution are subject to the Boost Software License, Version 1.0, below. * - * trig.h: original author Josh Wilson, 2020. - * * ---------------------------------------------------------------------------- * * BSD 3-Clause License @@ -99,9 +98,6 @@ #define CEPH_MAXITER 500 #define CEPH_MACHEP 1.1102230246251565404236316680908203125E-16 #define CEPH_MAXLOG 7.097827128933839730962063185871E2 -#define CEPH_SQRT2PI 2.506628274631000502415765284811045253007 -#define CEPH_LOGPI 1.144729885849400174143427351353058711647 -#define CEPH_MAXGAM 171.624376956302725 #define CEPH_SCIPY_EULER 0.577215664901532860606512090082402431 #define CEPH_PI 3.14159265358979323846 #define CEPH_SQRT2 1.41421356237309504880 @@ -194,28 +190,6 @@ ceph_ratevl(double x, const double num[], int M, const double denom[], int N) } } -/* trig.h: sin(pi * x). */ -static double -ceph_sinpi(double x) -{ - double s = 1.0; - double r; - - if (signbit(x)) { - x = -x; - s = -1.0; - } - - r = fmod(x, 2.0); - if (r < 0.5) { - return s * sin(CEPH_PI * r); - } else if (r > 1.5) { - return s * sin(CEPH_PI * (r - 2.0)); - } else { - return -s * sin(CEPH_PI * (r - 1.0)); - } -} - /* gamma.h */ static const double gamma_P[] = { 1.60119522476751861407E-4, 1.19135147006586384913E-3, @@ -226,111 +200,16 @@ static const double gamma_Q[] = { -2.31581873324120129819E-5, 5.3960558049330339 -4.45641913851797240494E-3, 1.18139785222060435552E-2, 3.58236398605498653373E-2, -2.34591795718243348568E-1, 7.14304917030273074085E-2, 1.00000000000000000320E0 }; -/* Stirling's formula for the Gamma function */ -static const double gamma_STIR[5] = { - 7.87311395793093628397E-4, - -2.29549961613378126380E-4, - -2.68132617805781232825E-3, - 3.47222221605458667310E-3, - 8.33333333333482257126E-2, -}; - -#define GAMMA_MAXSTIR 143.01608 - -/* Gamma function computed by Stirling's formula. - * The polynomial STIR is valid for 33 <= x <= 172. - */ -static double -ceph_stirf(double x) -{ - double y, w, v; - - if (x >= CEPH_MAXGAM) { - return INFINITY; - } - w = 1.0 / x; - w = 1.0 + w * ceph_polevl(w, gamma_STIR, 4); - y = exp(x); - if (x > GAMMA_MAXSTIR) { /* Avoid overflow in pow() */ - v = pow(x, 0.5 * x - 0.25); - y = v * (v / y); - } else { - y = pow(x, x - 0.5) / y; - } - y = CEPH_SQRT2PI * y * w; - return y; -} - +/* The Gamma function for 0 < x < 1, the only arguments it receives. */ static double ceph_Gamma(double x) { double p, q, z; - int i; - int sgngam = 1; - - if (!isfinite(x)) { - if (x > 0) { - /* gamma(+inf) = +inf */ - return x; - } - /* gamma(NaN) and gamma(-inf) both should equal NaN. */ - return NAN; - } - - if (x == 0) { - /* For pole at zero, value depends on sign of zero. - * +inf when approaching from right, -inf when approaching - * from left. */ - return copysign(INFINITY, x); - } - - q = fabs(x); - - if (q > 33.0) { - if (x < 0.0) { - p = floor(q); - if (p == q) { - /* x is a negative integer. This is a pole. */ - return NAN; - } - i = (int) p; - if ((i & 1) == 0) { - sgngam = -1; - } - z = q - p; - if (z > 0.5) { - p += 1.0; - z = q - p; - } - z = q * ceph_sinpi(z); - if (z == 0.0) { - return sgngam * (double) INFINITY; - } - z = fabs(z); - z = CEPH_PI / (z * ceph_stirf(q)); - } else { - z = ceph_stirf(x); - } - return sgngam * z; - } z = 1.0; - while (x >= 3.0) { - x -= 1.0; - z *= x; - } - - while (x < 0.0) { - if (x > -1.E-9) { - goto small; - } - z /= x; - x += 1.0; - } - while (x < 2.0) { if (x < 1.e-9) { - goto small; + return z / ((1.0 + 0.5772156649015329 * x) * x); } z /= x; x += 1.0; @@ -344,14 +223,6 @@ ceph_Gamma(double x) p = ceph_polevl(x, gamma_P, 6); q = ceph_polevl(x, gamma_Q, 7); return z * p / q; - -small: - if (x == 0.0) { - /* For this to have happened, x must have started as a negative integer. */ - return NAN; - } else { - return z / ((1.0 + 0.5772156649015329 * x) * x); - } } /* A[]: Stirling's formula expansion of log Gamma @@ -389,45 +260,12 @@ ceph_lgam_large_x(double x) return q + p; } +/* Logarithm of the Gamma function for positive finite x, the only arguments it + * receives. */ static double -ceph_lgam_sgn(double x, int *sign) +ceph_lgam(double x) { - double p, q, u, w, z; - int i; - - *sign = 1; - - if (!isfinite(x)) { - return x; - } - - if (x < -34.0) { - q = -x; - w = ceph_lgam_sgn(q, sign); - p = floor(q); - if (p == q) { - lgsing: - return INFINITY; - } - i = (int) p; - if ((i & 1) == 0) { - *sign = -1; - } else { - *sign = 1; - } - z = q - p; - if (z > 0.5) { - p += 1.0; - z = p - q; - } - z = q * ceph_sinpi(z); - if (z == 0.0) { - goto lgsing; - } - /* z = log(M_PI) - log( z ) - w; */ - z = CEPH_LOGPI - log(z) - w; - return z; - } + double p, q, u, z; if (x < 13.0) { z = 1.0; @@ -439,19 +277,10 @@ ceph_lgam_sgn(double x, int *sign) z *= u; } while (u < 2.0) { - if (u == 0.0) { - goto lgsing; - } z /= u; p += 1.0; u = x + p; } - if (z < 0.0) { - *sign = -1; - z = -z; - } else { - *sign = 1; - } if (u == 2.0) { return log(z); } @@ -462,7 +291,7 @@ ceph_lgam_sgn(double x, int *sign) } if (x > GAMMA_MAXLGM) { - return *sign * (double) INFINITY; + return INFINITY; } if (x >= 1000.0) { @@ -474,14 +303,6 @@ ceph_lgam_sgn(double x, int *sign) return q + ceph_polevl(p, gamma_A, 4) / x; } -/* Logarithm of Gamma function */ -static double -ceph_lgam(double x) -{ - int sign; - return ceph_lgam_sgn(x, &sign); -} - /* lanczos.h */ static const double lanczos_sum_expg_scaled_num[] = { @@ -1274,26 +1095,15 @@ ceph_igam(double a, double x) { double absxma_a; - if (isnan(a) || isnan(x)) { + if (isnan(x)) { return NAN; } - if (x < 0 || a < 0) { + if (x < 0) { return NAN; - } else if (a == 0) { - if (x > 0) { - return 1; - } else { - return NAN; - } } else if (x == 0) { /* Zero integration limit */ return 0; - } else if (isinf(a)) { - if (isinf(x)) { - return NAN; - } - return 0; } else if (isinf(x)) { return 1; } @@ -1318,25 +1128,14 @@ ceph_igamc(double a, double x) { double absxma_a; - if (isnan(a) || isnan(x)) { + if (isnan(x)) { return NAN; } - if (x < 0 || a < 0) { + if (x < 0) { return NAN; - } else if (a == 0) { - if (x > 0) { - return 0; - } else { - return NAN; - } } else if (x == 0) { return 1; - } else if (isinf(a)) { - if (isinf(x)) { - return NAN; - } - return 1; } else if (isinf(x)) { return 0; } @@ -1634,15 +1433,19 @@ tsd_gammaincinv(double a, double p) int i; double x, fac, f_fp, fpp_fp; - if (isnan(a) || isnan(p)) { + if (!(a >= 0) || !(p >= 0 && p <= 1)) { return NAN; - } else if ((a < 0) || (p < 0) || (p > 1)) { - /* Outside the domain: fall through. */ - } else if (p == 0.0) { + } + if (p == 0.0) { return 0.0; - } else if (p == 1.0) { + } + if (p == 1.0) { return INFINITY; - } else if (p > 0.9) { + } + if (a == 0 || isinf(a)) { + return NAN; + } + if (p > 0.9) { return ceph_igamci(a, 1 - p); } diff --git a/tests/oracle/hypergeo.py b/tests/oracle/hypergeo.py index fe58ea59..7b6eefa3 100644 --- a/tests/oracle/hypergeo.py +++ b/tests/oracle/hypergeo.py @@ -2,6 +2,7 @@ Oracles for the special functions (``lib/hypergeo.c``). """ +import math from math import pi import numpy as np @@ -21,12 +22,21 @@ # The C library's gammaincinv is a port of `scipy.special.gammaincinv`, which is the -# reference. The ufunc returns an `np.float64`, which is converted so that callers -# divide by it with Python semantics (ZeroDivisionError). +# reference inside the domain. The ufunc returns an `np.float64`, which is converted +# so that callers divide by it with Python semantics (ZeroDivisionError). def _gammainc_inv(a, x): """ - scipy.special.gammaincinv + scipy.special.gammaincinv for 0 < a < inf and 0 <= x <= 1, with x = 0 and x = 1 + giving 0 and inf for any a >= 0; NaN otherwise. """ + if not (a >= 0 and 0 <= x <= 1): + return math.nan + if x == 0: + return 0.0 + if x == 1: + return math.inf + if a == 0 or math.isinf(a): + return math.nan return float(scipy.special.gammaincinv(a, x)) diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index 07908940..2d1441c8 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -255,15 +255,6 @@ def test_domain(self, name, args, expected): GAMMAINC_INV_EDGES = [ - # shapes outside the domain reach the poles, the reflection formula and Stirling's - # formula in the gamma function of the initial approximation - (-40.0, 0.5), - (-1e-10, 0.5), - (-46.752919088367761, -0.92813118104822934), - (-39.271336710778996, -5.5046762376648753e-13), - (-640.33633048902459, 0.13827951904386282), - (-150.91834423637511, 1.0674574812874198), - (-63.911108928063285, -0.68496137764304876), # the gamma function's recurrence lands on 2 exactly (nextafter(1.0, 0), 0.5), # the series of igamc for small arguments, and a Newton step where the ratio of the @@ -306,10 +297,9 @@ def gammainc_inv_random(): class TestGammaincInv: """ - `_gammainc_inv` is SciPy's ``gammaincinv`` (cephes ``igami``), of which the C - library's is a port; checked exactly, including away from the interior of the - domain (the result is a NaN, 0 or inf for invalid shapes and quantiles, with no - exception). + `_gammainc_inv` is SciPy's ``gammaincinv`` (cephes ``igami``) inside the domain, + of which the C library's is a port; checked exactly, including the edges of the + domain and outside it (NaN, with no exception). """ @pytest.mark.parametrize(("a", "q"), gammainc_inv_grid(), ids=repr) From 5d93ae5ab71e8c056e7e73b6a014f82334e5866d Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 11:28:59 -0800 Subject: [PATCH 27/56] Test the gammaincinv branches that valid arguments reach Four inputs found by fuzzing reach the remaining lines that any valid argument reaches: cephes log1p, a NaN Halley iterate in igam and igamc, lgam1p's Taylor series at zero and erfc of a negative argument. --- tests/test_oracle_hypergeo.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index 2d1441c8..b41bd37a 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -261,6 +261,14 @@ def test_domain(self, name, args, expected): # derivatives overflows, in the complemented inversion (0.0018725572425875394, 0.93432222410629528), (1.4851015014453666e-07, 0.99989259056538193), + # a subnormal shape: cephes log1p in log1pmx (complemented inversion), and a NaN + # Halley iterate reaching igam + (9.9999999999999694e-311, 0.95988221384026817), + (9.9999999999999694e-311, 0.56112084484672486), + # the Taylor series of lgam1p at zero + (1.0, 0.64358723829337949), + # erfc of a negative argument in the asymptotic series + (1.3693230946091463e32, 0.84677972577643534), ] From 2dfabef3448ec71e503e2d1e52d4598eaedfe2ca Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 11:31:08 -0800 Subject: [PATCH 28/56] Mark the gammaincinv branches that valid arguments do not reach The branches kept from xsf that no valid argument reached in 20 million random draws carry GCOVR_EXCL markers, and the file header says so; gcovr (and so the coverage reports) leaves them out. --- lib/gammaincinv.c | 58 ++++++++++++++++++++++++++--------------------- 1 file changed, 32 insertions(+), 26 deletions(-) diff --git a/lib/gammaincinv.c b/lib/gammaincinv.c index 9b635a91..d565e9a3 100644 --- a/lib/gammaincinv.c +++ b/lib/gammaincinv.c @@ -13,7 +13,9 @@ * and iteration limits are those of xsf. Arguments outside the domain give NaN * directly, and the helper functions keep only the branches that the arguments they * receive can reach; error reporting (set_error, a no-op in xsf's default build) is - * dropped and the in-band return values are kept. + * dropped and the in-band return values are kept. Branches marked GCOVR_EXCL are + * kept unmodified from xsf although valid arguments do not reach them (none of 20 + * million random draws did), so the tests do not cover them. * * The notices of the original files and the licences they are distributed under * follow. @@ -251,7 +253,7 @@ ceph_lgam_large_x(double x) double p; if (x > 1.0e8) { - return q; + return q; /* GCOVR_EXCL_LINE */ } p = 1.0 / (x * x); p = ((7.9365079365079365079365e-4 * p - 2.7777777777777777777778e-3) * p @@ -291,7 +293,7 @@ ceph_lgam(double x) } if (x > GAMMA_MAXLGM) { - return INFINITY; + return INFINITY; /* GCOVR_EXCL_LINE */ } if (x >= 1000.0) { @@ -366,7 +368,7 @@ ceph_log1p(double x) z = 1.0 + x; if ((z < CEPH_SQRT1_2) || (z > CEPH_SQRT2)) { - return log(z); + return log(z); /* GCOVR_EXCL_LINE */ } z = x * x; z = -0.5 * z + x * (z * ceph_polevl(x, unity_LP, 6) / ceph_p1evl(x, unity_LQ, 6)); @@ -418,6 +420,7 @@ ceph_expm1(double x) { double r, xx; + /* GCOVR_EXCL_START */ if (!isfinite(x)) { if (isnan(x)) { return x; @@ -427,8 +430,9 @@ ceph_expm1(double x) return -1.0; } } + /* GCOVR_EXCL_STOP */ if ((x < -0.5) || (x > 0.5)) { - return exp(x) - 1.0; + return exp(x) - 1.0; /* GCOVR_EXCL_LINE */ } xx = x * x; r = x * ceph_polevl(xx, unity_EP, 2); @@ -496,7 +500,7 @@ ceph_zeta(double x, double q) b /= w; k += 1.0; } -done: +done: /* GCOVR_EXCL_LINE: reached, but gcov counts no execution of the label */ return s; } @@ -533,7 +537,7 @@ ceph_lgam1p(double x) } else if (fabs(x - 1) < 0.5) { return log(x) + ceph_lgam1p_taylor(x - 1); } else { - return ceph_lgam(x + 1); + return ceph_lgam(x + 1); /* GCOVR_EXCL_LINE */ } } @@ -575,7 +579,7 @@ ceph_erfc(double a) double p, q, x, y, z; if (isnan(a)) { - return NAN; + return NAN; /* GCOVR_EXCL_LINE */ } if (a < 0.0) { @@ -591,7 +595,7 @@ ceph_erfc(double a) z = -a * a; if (z < -CEPH_MAXLOG) { - goto under; + goto under; /* GCOVR_EXCL_LINE */ } z = exp(z); @@ -600,8 +604,8 @@ ceph_erfc(double a) p = ceph_polevl(x, ndtr_P, 8); q = ceph_p1evl(x, ndtr_Q, 8); } else { - p = ceph_polevl(x, ndtr_R, 5); - q = ceph_p1evl(x, ndtr_S, 6); + p = ceph_polevl(x, ndtr_R, 5); /* GCOVR_EXCL_LINE */ + q = ceph_p1evl(x, ndtr_S, 6); /* GCOVR_EXCL_LINE */ } y = (z * p) / q; @@ -613,12 +617,14 @@ ceph_erfc(double a) return y; } + /* GCOVR_EXCL_START */ under: if (a < 0) { return 2.0; } else { return 0.0; } + /* GCOVR_EXCL_STOP */ } static double @@ -627,7 +633,7 @@ ceph_erf(double x) double y, z; if (isnan(x)) { - return NAN; + return NAN; /* GCOVR_EXCL_LINE */ } if (x < 0.0) { @@ -635,7 +641,7 @@ ceph_erf(double x) } if (fabs(x) > 1.0) { - return 1.0 - ceph_erfc(x); + return 1.0 - ceph_erfc(x); /* GCOVR_EXCL_LINE */ } z = x * x; @@ -930,7 +936,7 @@ ceph_igamc_continued_fraction(double a, double x) ax = ceph_igam_fac(a, x); if (ax == 0.0) { - return 0.0; + return 0.0; /* GCOVR_EXCL_LINE */ } /* continued fraction */ @@ -955,7 +961,7 @@ ceph_igamc_continued_fraction(double a, double x) t = fabs((ans - r) / r); ans = r; } else { - t = 1.0; + t = 1.0; /* GCOVR_EXCL_LINE */ } pkm2 = pkm1; pkm1 = pk; @@ -984,7 +990,7 @@ ceph_igam_series(double a, double x) ax = ceph_igam_fac(a, x); if (ax == 0.0) { - return 0.0; + return 0.0; /* GCOVR_EXCL_LINE */ } /* power series */ @@ -1074,7 +1080,7 @@ ceph_asymptotic_series(double a, double x, int func) term = ck * afac; absterm = fabs(term); if (absterm > absoldterm) { - break; + break; /* GCOVR_EXCL_LINE */ } sum += term; if (absterm < CEPH_MACHEP * fabs(sum)) { @@ -1100,12 +1106,12 @@ ceph_igam(double a, double x) } if (x < 0) { - return NAN; + return NAN; /* GCOVR_EXCL_LINE */ } else if (x == 0) { /* Zero integration limit */ - return 0; + return 0; /* GCOVR_EXCL_LINE */ } else if (isinf(x)) { - return 1; + return 1; /* GCOVR_EXCL_LINE */ } /* Asymptotic regime where a ~ x; see [2]. */ @@ -1133,11 +1139,11 @@ ceph_igamc(double a, double x) } if (x < 0) { - return NAN; + return NAN; /* GCOVR_EXCL_LINE */ } else if (x == 0) { - return 1; + return 1; /* GCOVR_EXCL_LINE */ } else if (isinf(x)) { - return 0; + return 0; /* GCOVR_EXCL_LINE */ } /* Asymptotic regime where a ~ x; see [2]. */ @@ -1151,19 +1157,19 @@ ceph_igamc(double a, double x) /* Everywhere else; see [2]. */ if (x > 1.1) { if (x < a) { - return 1.0 - ceph_igam_series(a, x); + return 1.0 - ceph_igam_series(a, x); /* GCOVR_EXCL_LINE */ } else { return ceph_igamc_continued_fraction(a, x); } } else if (x <= 0.5) { if (-0.4 / log(x) < a) { - return 1.0 - ceph_igam_series(a, x); + return 1.0 - ceph_igam_series(a, x); /* GCOVR_EXCL_LINE */ } else { return ceph_igamc_series(a, x); } } else { if (x * 1.1 < a) { - return 1.0 - ceph_igam_series(a, x); + return 1.0 - ceph_igam_series(a, x); /* GCOVR_EXCL_LINE */ } else { return ceph_igamc_series(a, x); } From df7afc95e8059f6ad43f88967e28e7fe1814199b Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 11:44:18 -0800 Subject: [PATCH 29/56] Use libm log and exp in the prior oracle NumPy's SIMD log and exp differ from libm in the last bit on some CPUs (the Ubuntu CI runners), so the exact comparisons with the C library failed there. The prior oracle now uses the libm wrappers of _libm, as the other oracles do. --- tests/oracle/prior.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/tests/oracle/prior.py b/tests/oracle/prior.py index 8c212508..1439fe7b 100644 --- a/tests/oracle/prior.py +++ b/tests/oracle/prior.py @@ -4,6 +4,10 @@ import numpy as np +# NumPy's SIMD log and exp can differ from libm in the last bit on some CPUs; `_libm` +# gives the C library's results. +from ._libm import exp, log + def _marginalize_over_ancestors(val): """ @@ -17,16 +21,14 @@ def _marginalize_over_ancestors(val): pr_a_ln = [np.nan, np.nan, 0.0] # log Pr(a | k, n) out = np.zeros((n + 1, N)) for k in range(n - 1, 1, -1): - # `np.log(0)` at k == 2 warns (divide by zero) here; C is silent - # and the value is unused for k == 2, so suppress the warning locally. - with np.errstate(divide="ignore"): - const = np.log(n - k) + np.log(k - 2) - np.log(k + 1) + # log(0) at k == 2 is -inf; the value is unused for k == 2 + const = log(n - k) + log(k - 2) - log(k + 1) for a in range(2, n - k + 2): - out[k] += np.exp(pr_a_ln[a]) * val[a] + out[k] += exp(pr_a_ln[a]) * val[a] if k > 2: # Pr(a | k, n) to Pr(a | k - 1, n) - pr_a_ln[a] += const - np.log(n - a - k + 2) + pr_a_ln[a] += const - log(n - a - k + 2) if k > 2: # Pr(n - k + 1 | k - 1, n) to Pr(n - k + 2 | k - 1, n) - pr_a_ln.append(pr_a_ln[-1] + np.log(n - k + 2) - np.log(k + 1) - const) + pr_a_ln.append(pr_a_ln[-1] + log(n - k + 2) - log(k + 1) - const) out[n] = val[1] return out From 1ae43ecb90405255f506c7844d7bf21ab4c2412f Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 11:54:06 -0800 Subject: [PATCH 30/56] Compare gammaincinv with SciPy only in its own tests SciPy's arm64 macOS wheels fuse multiply-adds in gammaincinv, so the port differs from them by about 1e-15 relative, and the interquantile fits amplify that. The oracles now take gammaincinv from the C library, as they take libm, so the oracle comparisons of approx and rescaling stay exact everywhere. TestGammaincInv compares the port with scipy.special.gammaincinv: exactly on x86-64 (Linux and Windows CI agree bit for bit), and to 1e-11 relative elsewhere (a build of the port with fused multiply-adds differs by at most 4e-13 over 600000 points). --- tests/oracle/__init__.py | 4 ++- tests/oracle/hypergeo.py | 24 +++------------ tests/test_oracle_hypergeo.py | 58 +++++++++++++++++++++++++---------- tests/test_python_c_scalar.py | 26 ---------------- 4 files changed, 49 insertions(+), 63 deletions(-) diff --git a/tests/oracle/__init__.py b/tests/oracle/__init__.py index 1de7829d..9664b649 100644 --- a/tests/oracle/__init__.py +++ b/tests/oracle/__init__.py @@ -13,7 +13,9 @@ C library. Where plain Python semantics differ from C (e.g. division by zero raising instead of giving inf/nan, numpy scalar semantics), a comment explains the compensation, once in the module header where it applies throughout. -* Oracles call other oracles, never ``_tsdate``. +* Oracles call other oracles, never ``_tsdate``, except for ``gammaincinv`` + (``hypergeo._gammainc_inv``), which they take from the C library as they take libm, + and which is compared with SciPy instead. * Names and signatures are those of ``tsdate``'s functions of the same names, where they exist. """ diff --git a/tests/oracle/hypergeo.py b/tests/oracle/hypergeo.py index 7b6eefa3..179b37ae 100644 --- a/tests/oracle/hypergeo.py +++ b/tests/oracle/hypergeo.py @@ -2,11 +2,10 @@ Oracles for the special functions (``lib/hypergeo.c``). """ -import math from math import pi +import _tsdate import numpy as np -import scipy.special # Plain `math` raises on log(0), exp overflow etc., where C gives -inf, inf or # nan; `_libm` gives the C results. @@ -20,24 +19,9 @@ # versions (libm functions on Python floats). from ._libm import erf, exp, ipow, lgamma, log, pow, sin, sqrt, tan # noqa: A004 - -# The C library's gammaincinv is a port of `scipy.special.gammaincinv`, which is the -# reference inside the domain. The ufunc returns an `np.float64`, which is converted -# so that callers divide by it with Python semantics (ZeroDivisionError). -def _gammainc_inv(a, x): - """ - scipy.special.gammaincinv for 0 < a < inf and 0 <= x <= 1, with x = 0 and x = 1 - giving 0 and inf for any a >= 0; NaN otherwise. - """ - if not (a >= 0 and 0 <= x <= 1): - return math.nan - if x == 0: - return 0.0 - if x == 1: - return math.inf - if a == 0 or math.isinf(a): - return math.nan - return float(scipy.special.gammaincinv(a, x)) +# gammaincinv is a primitive of the oracles, as the libm functions are: the C library's +# port of `scipy.special.gammaincinv`, which `TestGammaincInv` compares with SciPy. +_gammainc_inv = _tsdate.gammainc_inv def _digamma(x): diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index b41bd37a..e9b1ee23 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -8,9 +8,13 @@ Accuracy of the approximations is measured in ``evaluation/numerical_accuracy.py``. """ +import math +import platform + import _tsdate import numpy as np import pytest +import scipy.special from oracle import hypergeo from oracle._libm import lgamma, log from oracle.helpers import ( @@ -30,7 +34,6 @@ "_trigamma": _tsdate.trigamma, "_betaln": _tsdate.betaln, "_gammainc_der": _tsdate.gammainc_der, - "_gammainc_inv": _tsdate.gammainc_inv, "_hyperu_laplace": _tsdate.hyperu_laplace, "_hyp1f1_laplace": _tsdate.hyp1f1_laplace, "_hyp2f1_laplace": _tsdate.hyp2f1_laplace, @@ -303,18 +306,48 @@ def gammainc_inv_random(): return np.concatenate(shapes), np.concatenate(quantiles) +def scipy_gammaincinv(a, q): + """ + scipy.special.gammaincinv inside the domain of the C library's port (0 < a < inf, + 0 <= q <= 1, with q = 0 and q = 1 giving 0 and inf for any a >= 0); NaN outside it + """ + if not (a >= 0 and 0 <= q <= 1): + return math.nan + if q == 0: + return 0.0 + if q == 1: + return math.inf + if a == 0 or math.isinf(a): + return math.nan + return float(scipy.special.gammaincinv(a, q)) + + +# SciPy's wheels for x86-64 compute gammaincinv without fused multiply-adds, as the C +# library does, so the two agree exactly; wheels for other architectures (e.g. arm64 +# macOS, built with clang) may fuse them, which changes results by up to about 1e-12 +# relative. +GAMMAINCINV_EXACT = platform.machine().lower() in ("x86_64", "amd64") + + +def assert_matches_scipy(actual, desired): + if GAMMAINCINV_EXACT: + assert_same_values(actual, desired) + else: + np.testing.assert_allclose(actual, desired, rtol=1e-11, atol=0, equal_nan=True) + + class TestGammaincInv: """ - `_gammainc_inv` is SciPy's ``gammaincinv`` (cephes ``igami``) inside the domain, - of which the C library's is a port; checked exactly, including the edges of the - domain and outside it (NaN, with no exception). + The C library's gammaincinv is a port of SciPy's (cephes ``igami``): compared with + ``scipy.special.gammaincinv`` inside the domain, including its edges, and NaN + outside it. """ @pytest.mark.parametrize(("a", "q"), gammainc_inv_grid(), ids=repr) - def test_matches_oracle(self, a, q): - parity("_gammainc_inv", (a, q)) + def test_matches_scipy(self, a, q): + assert_matches_scipy(_tsdate.gammainc_inv(a, q), scipy_gammaincinv(a, q)) - def test_matches_oracle_random(self): + def test_matches_scipy_random(self): """ Seeded draws of log-uniform shapes with quantiles that are uniform, tiny, close to one (the complemented inversion), special values or outside [0, 1], and of @@ -322,8 +355,8 @@ def test_matches_oracle_random(self): """ shapes, quantiles = gammainc_inv_random() actual = [_tsdate.gammainc_inv(a, q) for a, q in zip(shapes, quantiles)] - desired = [hypergeo._gammainc_inv(a, q) for a, q in zip(shapes, quantiles)] - assert_same_values(np.array(actual), np.array(desired)) + desired = [scipy_gammaincinv(a, q) for a, q in zip(shapes, quantiles)] + assert_matches_scipy(np.array(actual), np.array(desired)) HYPERU_DOMAIN = [ @@ -602,12 +635,6 @@ def draw_gammainc_der(rng, extreme): return log_uniform(rng, -1, 3.5), log_uniform(rng, -3, 4) -def draw_gammainc_inv(rng, extreme): - if extreme: - return log_uniform(rng, -8, 8), float(rng.uniform(0, 1)) - return log_uniform(rng, -1, 3), float(rng.uniform(0.001, 0.999)) - - def draw_hyperu(rng, extreme): # requires b >= a > 0 and x > 0 if extreme: @@ -654,7 +681,6 @@ def draw_hyp2f1(rng, extreme): "_trigamma": draw_polygamma, "_betaln": draw_betaln, "_gammainc_der": draw_gammainc_der, - "_gammainc_inv": draw_gammainc_inv, "_hyperu_laplace": draw_hyperu, "_hyp1f1_laplace": draw_hyp1f1, "_hyp2f1_laplace": draw_hyp2f1, diff --git a/tests/test_python_c_scalar.py b/tests/test_python_c_scalar.py index ac6ff91a..b0691533 100644 --- a/tests/test_python_c_scalar.py +++ b/tests/test_python_c_scalar.py @@ -83,32 +83,6 @@ def test_nan_is_not_an_error(self): assert math.isnan(_tsdate.gammainc_inv(math.nan, 0.5)) -class TestGammaincInv: - """ - ``gammainc_inv`` is a port of SciPy's ``gammaincinv``, identical to - ``scipy.special.gammaincinv``, including outside the domain. - """ - - @pytest.mark.parametrize( - ("a", "q"), - [ - (0.5, 0.3), - (2.0, 0.9), - (1e5, 1e-10), - (1e-3, 0.99), - (2.0, 0.0), - (2.0, 1.0), - (-1.0, 0.5), - (2.0, 1.5), - (math.nan, 0.5), - ], - ) - def test_matches_scipy(self, a, q): - actual = _tsdate.gammainc_inv(a, q) - expected = scipy.special.gammaincinv(a, q) - assert actual == expected or (math.isnan(actual) and math.isnan(expected)) - - class TestScipyDependency: def test_import_without_scipy(self): code = ( From 1b7d2def5b8a4f517c07f198b86c69d73c914603 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 11:59:29 -0800 Subject: [PATCH 31/56] Compare gammaincinv with SciPy to a relative tolerance on every platform Agreement with SciPy depends on SciPy's build, not only on the architecture: SciPy 1.17.1's Windows wheel differs from the port by up to 7e-13 relative (at a = 0.001), as the arm64 macOS wheels do. The platform switch is replaced by rtol = 1e-10 everywhere; the port agrees bit for bit with SciPy 1.18 on x86-64 Linux. --- tests/test_oracle_hypergeo.py | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index e9b1ee23..0dff5e7d 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -9,7 +9,6 @@ """ import math -import platform import _tsdate import numpy as np @@ -322,18 +321,14 @@ def scipy_gammaincinv(a, q): return float(scipy.special.gammaincinv(a, q)) -# SciPy's wheels for x86-64 compute gammaincinv without fused multiply-adds, as the C -# library does, so the two agree exactly; wheels for other architectures (e.g. arm64 -# macOS, built with clang) may fuse them, which changes results by up to about 1e-12 -# relative. -GAMMAINCINV_EXACT = platform.machine().lower() in ("x86_64", "amd64") - - def assert_matches_scipy(actual, desired): - if GAMMAINCINV_EXACT: - assert_same_values(actual, desired) - else: - np.testing.assert_allclose(actual, desired, rtol=1e-11, atol=0, equal_nan=True) + """ + SciPy's result depends on its build: wheels that fuse multiply-adds (arm64 macOS) + or use another libm (SciPy 1.17 on Windows) differ from the port by up to about + 1e-12 relative, more for tiny shapes, where the inverse amplifies errors by about + 1 / a. The port agrees bit for bit with SciPy 1.18 on x86-64 Linux. + """ + np.testing.assert_allclose(actual, desired, rtol=1e-10, atol=0, equal_nan=True) class TestGammaincInv: From 34155c380bff586bf5cda39bb05b1571cfa173eb Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 12:16:12 -0800 Subject: [PATCH 32/56] Give the oracles the signatures of the C functions Each oracle has the name, arguments and results of its _tsdate function: the validity checks return 1.0 or 0.0, the projections, damp and rescale take flat scalars and the projections return flat tuples, and the EP state is the tuple of eight factor arrays. The tests call both with the same arguments, so the adapters and the C_FUNCTIONS tables go, and the ep_state runners take the module whose passes they run. --- tests/oracle/__init__.py | 14 +- tests/oracle/approx.py | 310 ++++++++++++++----------------- tests/oracle/ep_state.py | 92 ++++----- tests/oracle/hypergeo.py | 28 +-- tests/oracle/phasing.py | 4 +- tests/oracle/prior.py | 4 +- tests/oracle/rescaling.py | 10 +- tests/oracle/util.py | 8 +- tests/oracle/variational.py | 215 ++++++++++----------- tests/test_oracle_approx.py | 147 ++++----------- tests/test_oracle_hypergeo.py | 65 +++---- tests/test_oracle_phasing.py | 4 +- tests/test_oracle_prior.py | 10 +- tests/test_oracle_rescaling.py | 10 +- tests/test_oracle_util.py | 16 +- tests/test_oracle_variational.py | 215 +++++---------------- 16 files changed, 457 insertions(+), 695 deletions(-) diff --git a/tests/oracle/__init__.py b/tests/oracle/__init__.py index 9664b649..1741874a 100644 --- a/tests/oracle/__init__.py +++ b/tests/oracle/__init__.py @@ -3,9 +3,9 @@ extension ``_tsdate``. Each function has an oracle in the module of the same name here, e.g. -``oracle.approx.moments``. Equivalence tests (``tests/test_oracle_*.py``) call the -``_tsdate`` functions, through small adapters where the C signature differs, and -compare them against the oracles. +``oracle.approx.moments`` for ``_tsdate.moments``. Equivalence tests +(``tests/test_oracle_*.py``) call the ``_tsdate`` functions and the oracles with the +same arguments and compare the outcomes. Rules: @@ -14,8 +14,10 @@ raising instead of giving inf/nan, numpy scalar semantics), a comment explains the compensation, once in the module header where it applies throughout. * Oracles call other oracles, never ``_tsdate``, except for ``gammaincinv`` - (``hypergeo._gammainc_inv``), which they take from the C library as they take libm, + (``hypergeo.gammainc_inv``), which they take from the C library as they take libm, and which is compared with SciPy instead. -* Names and signatures are those of ``tsdate``'s functions of the same names, where - they exist. +* Names, arguments and results are those of ``_tsdate``'s functions: the same + argument lists, and results of the same types and layout (floats where ``_tsdate`` + returns floats, the same tuples). The EP state is the tuple of factor arrays that + ``_tsdate`` takes. """ diff --git a/tests/oracle/approx.py b/tests/oracle/approx.py index 5d8c6ada..899f6062 100644 --- a/tests/oracle/approx.py +++ b/tests/oracle/approx.py @@ -75,8 +75,8 @@ def approximate_gamma_kl(x, logx): raise KLMinimizationFailedError( "Maximum iterations reached in KL minimization" ) - delta = hypergeo._digamma(alpha) - log(alpha) + log(x) - logx - delta /= hypergeo._trigamma(alpha) - 1 / alpha + delta = hypergeo.digamma(alpha) - log(alpha) + log(x) - logx + delta /= hypergeo.trigamma(alpha) - 1 / alpha alpha -= delta itt += 1 if not np.isfinite(alpha) or alpha <= 0: @@ -102,7 +102,7 @@ def approximate_gamma_iqr(q1, q2, x1, x2, max_shape): """ def upper_bound(q, x): # cap shape parameter - beta = hypergeo._gammainc_inv(max_shape, q) / x + beta = hypergeo.gammainc_inv(max_shape, q) / x return max_shape - 1, beta if x2 == x1: @@ -121,14 +121,14 @@ def upper_bound(q, x): # cap shape parameter raise KLMinimizationFailedError( "Maximum iterations reached in quantile matching" ) - y1 = hypergeo._gammainc_inv(alpha, q1) - y2 = hypergeo._gammainc_inv(alpha, q2) + y1 = hypergeo.gammainc_inv(alpha, q1) + y2 = hypergeo.gammainc_inv(alpha, q2) obj = y2 / y1 - x2 / x1 inv_1 = -exp(y1 + log(y1) * (1 - alpha) + lgamma(alpha)) inv_2 = -exp(y2 + log(y2) * (1 - alpha) + lgamma(alpha)) # print(itt, alpha, y1, y2) #DEBUG - gra_1 = hypergeo._gammainc_der(alpha, y1) * inv_1 - gra_2 = hypergeo._gammainc_der(alpha, y2) * inv_2 + gra_1 = hypergeo.gammainc_der(alpha, y1) * inv_1 + gra_2 = hypergeo.gammainc_der(alpha, y2) * inv_2 gra = (gra_2 * y1 - gra_1 * y2) / ipow(y1, 2) delta = -obj / gra alpha += delta @@ -138,7 +138,7 @@ def upper_bound(q, x): # cap shape parameter raise KLMinimizationFailedError("Negative shape parameter") if alpha > max_shape: return upper_bound(q1, x1) - beta = hypergeo._gammainc_inv(alpha, q1) / x1 + beta = hypergeo.gammainc_inv(alpha, q1) / x1 return alpha - 1, beta @@ -152,70 +152,70 @@ def average_gammas(alpha, beta): avg_x = 0.0 avg_logx = 0.0 for shape, rate in zip(map(float, alpha + 1.0), map(float, beta)): - avg_logx += hypergeo._digamma(shape) - log(rate) + avg_logx += hypergeo.digamma(shape) - log(rate) avg_x += shape / rate avg_x /= alpha.size avg_logx /= alpha.size return approximate_gamma_kl(avg_x, avg_logx) -def _valid_moments(mn, va): +def valid_moments(mn, va): """ - Whether a mean and variance are finite and positive. + 1.0 if a mean and variance are finite and positive, else 0.0. """ if not (np.isfinite(mn) and np.isfinite(va)): - return False + return 0.0 if not (mn > 0.0 and va > 0.0): - return False - return True + return 0.0 + return 1.0 -def _valid_gamma(s, r): +def valid_gamma(s, r): """ - Whether a gamma shape and rate are finite and positive. + 1.0 if a gamma shape and rate are finite and positive, else 0.0. """ if not (np.isfinite(s) and np.isfinite(r)): - return False + return 0.0 if s <= 0.0 or r <= 0.0: - return False - return True + return 0.0 + return 1.0 -def _valid_hyp1f1(a, b, z): +def valid_hyp1f1(a, b, z): """ - Whether the arguments are in the domain of `_hyp1f1_laplace`. + 1.0 if the arguments are in the domain of `hyp1f1_laplace`, else 0.0. """ if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(z)): - return False + return 0.0 if not (b >= a > 0.0): - return False - return True + return 0.0 + return 1.0 -def _valid_hyperu(a, b, z): +def valid_hyperu(a, b, z): """ - Whether the arguments are in the domain of `_hyperu_laplace`. + 1.0 if the arguments are in the domain of `hyperu_laplace`, else 0.0. """ if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(z)): - return False + return 0.0 if z <= 0.0: - return False + return 0.0 if not (b > a > 0.0): - return False - return True + return 0.0 + return 1.0 -def _valid_hyp2f1(a, b, c, z): +def valid_hyp2f1(a, b, c, z): """ - Whether the arguments are in the domain of `_hyp2f1_laplace`. + 1.0 if the arguments are in the domain of `hyp2f1_laplace`, else 0.0. """ if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(c)): - return False + return 0.0 if not np.isfinite(z) or z >= 1 or z / (z - 1) >= 1: - return False + return 0.0 if not (a > 0 and b > 0 and c > 0): - return False - return True + return 0.0 + return 1.0 def moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): @@ -234,10 +234,10 @@ def moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): t = mu_ij + b_i z = (mu_ij - b_j) / t if t > 0 else nan - if not _valid_hyp2f1(a, b, c, z): + if not valid_hyp2f1(a, b, c, z): return nan, nan, nan, nan, nan - hyp2f1 = hypergeo._hyp2f1_laplace + hyp2f1 = hypergeo.hyp2f1_laplace f0 = hyp2f1(a + 0, b + 0, c + 0, z) f1 = hyp2f1(a + 1, b + 1, c + 1, z) f2 = hyp2f1(a + 2, b + 2, c + 2, z) @@ -246,7 +246,7 @@ def moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): d1 = s1 * exp(f1 - f0) d2 = s2 * exp(f2 - f0) - logl = f0 + hypergeo._betaln(y_ij + 1, a) + lgamma(b) - b * log(t) + logl = f0 + hypergeo.betaln(y_ij + 1, a) + lgamma(b) - b * log(t) mn_j = d1 / t sq_j = d2 / ipow(t, 2) @@ -273,7 +273,7 @@ def rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): s = a_i + y_ij r = mu_ij + b_i - if not _valid_gamma(s, r): + if not valid_gamma(s, r): return nan, nan, nan if t_j == 0.0: @@ -286,10 +286,10 @@ def rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): b = s + 1 z = t_j * r - if not _valid_hyperu(a, b, z): + if not valid_hyperu(a, b, z): return nan, nan, nan - hyperu = hypergeo._hyperu_laplace + hyperu = hypergeo.hyperu_laplace f0, d0 = hyperu(a + 0, b + 0, z) f1, d1 = hyperu(a + 1, b + 1, z) @@ -315,17 +315,17 @@ def leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): b = a_j + y_ij + 1 z = t_i * (mu_ij - b_j) - if not _valid_hyp1f1(a, b, z): + if not valid_hyp1f1(a, b, z): return nan, nan, nan - hyp1f1 = hypergeo._hyp1f1_laplace + hyp1f1 = hypergeo.hyp1f1_laplace f0 = hyp1f1(a + 0, b + 0, z) f1 = hyp1f1(a + 1, b + 1, z) f2 = hyp1f1(a + 2, b + 2, z) d1 = a / b * exp(f1 - f0) d2 = a / b * (a + 1) / (b + 1) * exp(f2 - f0) - logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + hypergeo._betaln(a, b - a) + logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + hypergeo.betaln(a, b - a) mn_j = t_i * d1 sq_j = ipow(t_i, 2) * d2 va_j = sq_j - ipow(mn_j, 2) @@ -349,10 +349,10 @@ def unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): t = mu_ij + b_i z = (mu_ij + b_j) / t if t > 0 else nan - if not _valid_hyp2f1(a, b, c, 1 - z): + if not valid_hyp2f1(a, b, c, 1 - z): return nan, nan, nan, nan, nan - hyp2f1 = hypergeo._hyp2f1_laplace + hyp2f1 = hypergeo.hyp2f1_laplace f0 = hyp2f1(a + 0, b + 0, c + 0, 1 - z) f1 = hyp2f1(a + 1, b + 1, c + 1, 1 - z) f2 = hyp2f1(a + 2, b + 2, c + 2, 1 - z) @@ -361,7 +361,7 @@ def unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): d1 = s1 * exp(f1 - f0) d2 = s2 * exp(f2 - f0) - logl = f0 + hypergeo._betaln(a_j, a_i) + lgamma(b) - b * log(t) + logl = f0 + hypergeo.betaln(a_j, a_i) + lgamma(b) - b * log(t) mn_j = d1 / t sq_j = d2 / ipow(t, 2) @@ -405,10 +405,10 @@ def sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): b = a_j + y_ij + 1 z = t_i * (mu_ij + b_j) - if not _valid_hyperu(a, b, z): + if not valid_hyperu(a, b, z): return nan, nan, nan - hyperu = hypergeo._hyperu_laplace + hyperu = hypergeo.hyperu_laplace f0, d0 = hyperu(a + 0, b + 0, z) f1, d1 = hyperu(a + 1, b + 1, z) @@ -436,10 +436,10 @@ def mutation_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): t = mu_ij + b_i z = (mu_ij - b_j) / t if t > 0 else nan - if not _valid_hyp2f1(a, b, c, z): + if not valid_hyp2f1(a, b, c, z): return nan, nan - hyp2f1 = hypergeo._hyp2f1_laplace + hyp2f1 = hypergeo.hyp2f1_laplace f000 = hyp2f1(a + 0, b + 0, c + 0, z) f020 = hyp2f1(a + 0, b + 2, c + 0, z) f111 = hyp2f1(a + 1, b + 1, c + 1, z) @@ -522,10 +522,10 @@ def mutation_unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): t = mu_ij + b_i z = (mu_ij + b_j) / t if t > 0 else nan - if not _valid_hyp2f1(a, b, c, 1 - z): + if not valid_hyp2f1(a, b, c, 1 - z): return nan, nan, nan - hyp2f1 = hypergeo._hyp2f1_laplace + hyp2f1 = hypergeo.hyp2f1_laplace f000 = hyp2f1(a + 0, b + 0, c + 0, 1 - z) f001 = hyp2f1(a + 0, b + 0, c + 1, 1 - z) f012 = hyp2f1(a + 0, b + 1, c + 2, 1 - z) @@ -591,11 +591,11 @@ def mutation_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): b = a_j + y_ij + 1 z = t_i * (mu_ij + b_j) - if not _valid_hyperu(a, b, z): + if not valid_hyperu(a, b, z): return nan, nan, nan # direct but unstable: - hyperu = hypergeo._hyperu_laplace + hyperu = hypergeo.hyperu_laplace f00, d00 = hyperu(a + 0, b + 0, z) f10, d10 = hyperu(a + 1, b + 0, z) f21, d21 = hyperu(a + 2, b + 1, z) @@ -651,7 +651,13 @@ def mutation_block_moments(t_i, t_j): return pr_m, mn_m, va_m -def gamma_projection(pars_i, pars_j, pars_ij): +# The projections take the natural parameters (alpha, beta) = (shape - 1, rate) of the +# gamma of each free node, and the mutation count and mutational target size +# (y_ij, mu_ij) of the edge, as flat arguments; they return the first result followed +# by the natural parameters of each projected gamma. + + +def gamma_projection(alpha_i, beta_i, alpha_j, beta_j, y_ij, mu_ij): r""" log p(t_i, t_j) := \ log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ @@ -660,24 +666,21 @@ def gamma_projection(pars_i, pars_j, pars_ij): Returns normalizing constant, gamma natural parameters for parent and child ages """ - a_i, b_i = map(float, pars_i) - a_j, b_j = map(float, pars_j) - y_ij, mu_ij = map(float, pars_ij) - a_i += 1 - a_j += 1 + a_i = alpha_i + 1 + a_j = alpha_j + 1 - logl, mn_i, va_i, mn_j, va_j = moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) + logl, mn_i, va_i, mn_j, va_j = moments(a_i, beta_i, a_j, beta_j, y_ij, mu_ij) - if not (_valid_moments(mn_i, va_i) and _valid_moments(mn_j, va_j)): - return np.nan, pars_i, pars_j + if not (valid_moments(mn_i, va_i) and valid_moments(mn_j, va_j)): + return nan, alpha_i, beta_i, alpha_j, beta_j proj_i = approximate_gamma_mom(mn_i, va_i) proj_j = approximate_gamma_mom(mn_j, va_j) - return logl, np.array(proj_i), np.array(proj_j) + return logl, *proj_i, *proj_j -def leafward_projection(t_i, pars_j, pars_ij): +def leafward_projection(t_i, alpha_j, beta_j, y_ij, mu_ij): r""" log p(t_j) := \ log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ @@ -685,21 +688,19 @@ def leafward_projection(t_i, pars_j, pars_ij): Returns normalizing constant, gamma natural parameters for child age """ - a_j, b_j = map(float, pars_j) - y_ij, mu_ij = map(float, pars_ij) - a_j += 1 + a_j = alpha_j + 1 - logl, mn_j, va_j = leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) + logl, mn_j, va_j = leafward_moments(t_i, a_j, beta_j, y_ij, mu_ij) - if not _valid_moments(mn_j, va_j): - return np.nan, pars_j + if not valid_moments(mn_j, va_j): + return nan, alpha_j, beta_j proj_j = approximate_gamma_mom(mn_j, va_j) - return logl, np.array(proj_j) + return logl, *proj_j -def rootward_projection(t_j, pars_i, pars_ij): +def rootward_projection(t_j, alpha_i, beta_i, y_ij, mu_ij): r""" log p(t_i) := \ log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ @@ -707,21 +708,19 @@ def rootward_projection(t_j, pars_i, pars_ij): Returns normalizing constant, gamma natural parameters for parent age """ - a_i, b_i = map(float, pars_i) - y_ij, mu_ij = map(float, pars_ij) - a_i += 1 + a_i = alpha_i + 1 - logl, mn_i, va_i = rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) + logl, mn_i, va_i = rootward_moments(t_j, a_i, beta_i, y_ij, mu_ij) - if not _valid_moments(mn_i, va_i): - return np.nan, pars_i + if not valid_moments(mn_i, va_i): + return nan, alpha_i, beta_i proj_i = approximate_gamma_mom(mn_i, va_i) - return logl, np.array(proj_i) + return logl, *proj_i -def unphased_projection(pars_i, pars_j, pars_ij): +def unphased_projection(alpha_i, beta_i, alpha_j, beta_j, y_ij, mu_ij): r""" log p(t_i, t_j) := \ log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ @@ -730,24 +729,21 @@ def unphased_projection(pars_i, pars_j, pars_ij): Returns normalizing constant, gamma natural parameters for parent ages """ - a_i, b_i = map(float, pars_i) - a_j, b_j = map(float, pars_j) - y_ij, mu_ij = map(float, pars_ij) - a_i += 1 - a_j += 1 + a_i = alpha_i + 1 + a_j = alpha_j + 1 - logl, mn_i, va_i, mn_j, va_j = unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) + logl, mn_i, va_i, mn_j, va_j = unphased_moments(a_i, beta_i, a_j, beta_j, y_ij, mu_ij) - if not _valid_moments(mn_i, va_i) or not _valid_moments(mn_j, va_j): - return np.nan, pars_i, pars_j + if not valid_moments(mn_i, va_i) or not valid_moments(mn_j, va_j): + return nan, alpha_i, beta_i, alpha_j, beta_j proj_i = approximate_gamma_mom(mn_i, va_i) proj_j = approximate_gamma_mom(mn_j, va_j) - return logl, np.array(proj_i), np.array(proj_j) + return logl, *proj_i, *proj_j -def twin_projection(pars_i, pars_ij): +def twin_projection(alpha_i, beta_i, y_ij, mu_ij): r""" log p(t_i) := \ log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ @@ -755,21 +751,19 @@ def twin_projection(pars_i, pars_ij): Returns normalizing constant, gamma natural parameters for parent ages """ - a_i, b_i = map(float, pars_i) - y_ij, mu_ij = map(float, pars_ij) - a_i += 1 + a_i = alpha_i + 1 - logl, mn_i, va_i = twin_moments(a_i, b_i, y_ij, mu_ij) + logl, mn_i, va_i = twin_moments(a_i, beta_i, y_ij, mu_ij) - if not _valid_moments(mn_i, va_i): - return np.nan, pars_i + if not valid_moments(mn_i, va_i): + return nan, alpha_i, beta_i proj_i = approximate_gamma_mom(mn_i, va_i) - return logl, np.array(proj_i) + return logl, *proj_i -def sideways_projection(t_i, pars_j, pars_ij): +def sideways_projection(t_i, alpha_j, beta_j, y_ij, mu_ij): r""" log p(t_j) := \ log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ @@ -777,21 +771,19 @@ def sideways_projection(t_i, pars_j, pars_ij): Returns normalizing constant, gamma natural parameters for nonfixed parent age """ - a_j, b_j = map(float, pars_j) - y_ij, mu_ij = map(float, pars_ij) - a_j += 1 + a_j = alpha_j + 1 - logl, mn_j, va_j = sideways_moments(t_i, a_j, b_j, y_ij, mu_ij) + logl, mn_j, va_j = sideways_moments(t_i, a_j, beta_j, y_ij, mu_ij) - if not _valid_moments(mn_j, va_j): - return np.nan, pars_j + if not valid_moments(mn_j, va_j): + return nan, alpha_j, beta_j proj_j = approximate_gamma_mom(mn_j, va_j) - return logl, np.array(proj_j) + return logl, *proj_j -def mutation_gamma_projection(pars_i, pars_j, pars_ij): +def mutation_gamma_projection(alpha_i, beta_i, alpha_j, beta_j, y_ij, mu_ij): r""" log p(t_m, t_i, t_j) = \ log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ @@ -801,23 +793,20 @@ def mutation_gamma_projection(pars_i, pars_j, pars_ij): Returns phase probability, gamma natural parameters for mutation age """ - a_i, b_i = map(float, pars_i) - a_j, b_j = map(float, pars_j) - y_ij, mu_ij = map(float, pars_ij) - a_i += 1 - a_j += 1 + a_i = alpha_i + 1 + a_j = alpha_j + 1 - mn_m, va_m = mutation_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) + mn_m, va_m = mutation_moments(a_i, beta_i, a_j, beta_j, y_ij, mu_ij) - if not _valid_moments(mn_m, va_m): - return np.nan, np.full(2, np.nan) + if not valid_moments(mn_m, va_m): + return nan, nan, nan proj_m = approximate_gamma_mom(mn_m, va_m) - return 1.0, np.array(proj_m) + return 1.0, *proj_m -def mutation_leafward_projection(t_i, pars_j, pars_ij): +def mutation_leafward_projection(t_i, alpha_j, beta_j, y_ij, mu_ij): r""" log p(t_m, t_j) := \ log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ @@ -826,21 +815,19 @@ def mutation_leafward_projection(t_i, pars_j, pars_ij): Returns phase probability, gamma natural parameters for mutation age """ - a_j, b_j = map(float, pars_j) - y_ij, mu_ij = map(float, pars_ij) - a_j += 1 + a_j = alpha_j + 1 - mn_m, va_m = mutation_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) + mn_m, va_m = mutation_leafward_moments(t_i, a_j, beta_j, y_ij, mu_ij) - if not _valid_moments(mn_m, va_m): - return np.nan, np.full(2, np.nan) + if not valid_moments(mn_m, va_m): + return nan, nan, nan proj_m = approximate_gamma_mom(mn_m, va_m) - return 1.0, np.array(proj_m) + return 1.0, *proj_m -def mutation_rootward_projection(t_j, pars_i, pars_ij): +def mutation_rootward_projection(t_j, alpha_i, beta_i, y_ij, mu_ij): r""" log p(t_m, t_i) := \ log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ @@ -849,18 +836,16 @@ def mutation_rootward_projection(t_j, pars_i, pars_ij): Returns phase probability, gamma natural parameters for mutation age """ - a_i, b_i = map(float, pars_i) - y_ij, mu_ij = map(float, pars_ij) - a_i += 1 + a_i = alpha_i + 1 - mn_m, va_m = mutation_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) + mn_m, va_m = mutation_rootward_moments(t_j, a_i, beta_i, y_ij, mu_ij) - if not _valid_moments(mn_m, va_m): - return np.nan, np.full(2, np.nan) + if not valid_moments(mn_m, va_m): + return nan, nan, nan proj_m = approximate_gamma_mom(mn_m, va_m) - return 1.0, np.array(proj_m) + return 1.0, *proj_m def mutation_edge_projection(t_i, t_j): @@ -872,15 +857,15 @@ def mutation_edge_projection(t_i, t_j): """ mn_m, va_m = mutation_edge_moments(t_i, t_j) - if not _valid_moments(mn_m, va_m): - return np.nan, np.full(2, np.nan) + if not valid_moments(mn_m, va_m): + return nan, nan, nan proj_m = approximate_gamma_mom(mn_m, va_m) - return 1.0, np.array(proj_m) + return 1.0, *proj_m -def mutation_unphased_projection(pars_i, pars_j, pars_ij): +def mutation_unphased_projection(alpha_i, beta_i, alpha_j, beta_j, y_ij, mu_ij): r""" log p(t_m, t_i, t_j) := \ log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ @@ -891,23 +876,20 @@ def mutation_unphased_projection(pars_i, pars_j, pars_ij): Returns phase probability, gamma natural parameters for mutation age """ - a_i, b_i = map(float, pars_i) - a_j, b_j = map(float, pars_j) - y_ij, mu_ij = map(float, pars_ij) - a_i += 1 - a_j += 1 + a_i = alpha_i + 1 + a_j = alpha_j + 1 - pr_m, mn_m, va_m = mutation_unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) + pr_m, mn_m, va_m = mutation_unphased_moments(a_i, beta_i, a_j, beta_j, y_ij, mu_ij) - if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return np.nan, np.full(2, np.nan) + if not valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): + return nan, nan, nan proj_m = approximate_gamma_mom(mn_m, va_m) - return pr_m, np.array(proj_m) + return pr_m, *proj_m -def mutation_twin_projection(pars_i, pars_ij): +def mutation_twin_projection(alpha_i, beta_i, y_ij, mu_ij): r""" log p(t_m, t_i) := \ log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ @@ -916,21 +898,19 @@ def mutation_twin_projection(pars_i, pars_ij): Returns phase probability, gamma natural parameters for mutation age """ - a_i, b_i = map(float, pars_i) - y_ij, mu_ij = map(float, pars_ij) - a_i += 1 + a_i = alpha_i + 1 - pr_m, mn_m, va_m = mutation_twin_moments(a_i, b_i, y_ij, mu_ij) + pr_m, mn_m, va_m = mutation_twin_moments(a_i, beta_i, y_ij, mu_ij) - if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return np.nan, np.full(2, np.nan) + if not valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): + return nan, nan, nan proj_m = approximate_gamma_mom(mn_m, va_m) - return pr_m, np.array(proj_m) + return pr_m, *proj_m -def mutation_sideways_projection(t_i, pars_j, pars_ij): +def mutation_sideways_projection(t_i, alpha_j, beta_j, y_ij, mu_ij): r""" log p(t_m, t_j) := \ log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ @@ -940,18 +920,16 @@ def mutation_sideways_projection(t_i, pars_j, pars_ij): Returns phase probability, gamma natural parameters for mutation age """ - a_j, b_j = map(float, pars_j) - y_ij, mu_ij = map(float, pars_ij) - a_j += 1 + a_j = alpha_j + 1 - pr_m, mn_m, va_m = mutation_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij) + pr_m, mn_m, va_m = mutation_sideways_moments(t_i, a_j, beta_j, y_ij, mu_ij) - if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return np.nan, np.full(2, np.nan) + if not valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): + return nan, nan, nan proj_m = approximate_gamma_mom(mn_m, va_m) - return pr_m, np.array(proj_m) + return pr_m, *proj_m def mutation_block_projection(t_i, t_j): @@ -964,9 +942,9 @@ def mutation_block_projection(t_i, t_j): """ pr_m, mn_m, va_m = mutation_block_moments(t_i, t_j) - if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return np.nan, np.full(2, np.nan) + if not valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): + return nan, nan, nan proj_m = approximate_gamma_mom(mn_m, va_m) - return pr_m, np.array(proj_m) + return pr_m, *proj_m diff --git a/tests/oracle/ep_state.py b/tests/oracle/ep_state.py index 531a6d9e..712529e0 100644 --- a/tests/oracle/ep_state.py +++ b/tests/oracle/ep_state.py @@ -1,8 +1,9 @@ """ Expectation propagation state for the equivalence tests of ``tsdate.variational``: snapshots of real state from ``ExpectationPropagation`` (editable, so that tests can -force branches), one-edge snapshots, and runners that call given ``propagate_*`` -functions (the oracles, or adapters of the C functions) on copies of a snapshot. +force branches), one-edge snapshots, and runners that call the ``propagate_*`` +functions of a given module (``_tsdate``, or the oracle ``oracle.variational``) on +copies of a snapshot. """ import numpy as np @@ -20,8 +21,6 @@ ExpectationPropagation, ) -from .variational import EPFactors - # fixture name -> (singletons_phased, mutation_rate) SNAPSHOT_SPECS = { "small_ts": (True, 1e-8), @@ -53,7 +52,7 @@ class Snapshot: """ Copies of the arrays of an ``ExpectationPropagation`` after some iterations, so - that tests can edit them freely and rebuild fresh ``EPFactors``. + that tests can edit them freely and rebuild fresh factors. """ def __init__(self, ts, ep): @@ -78,23 +77,25 @@ def copy(self): def factors(self): """ - New ``EPFactors`` holding a copy of the factors + A copy of the factors, as the tuple of arrays ``(node, edge, block, scale, + edges_parent, edges_child, blocks_left, blocks_right)`` that the passes take """ - factors = EPFactors( - self.node_constraints, - self.edge_parents, - self.edge_children, - self.block_nodes[ROOTWARD], - self.block_nodes[LEAFWARD], + f = self.fields + return ( + f["node"].copy(), + f["edge"].copy(), + f["block"].copy(), + f["scale"].copy(), + self.edge_parents.copy(), + self.edge_children.copy(), + self.block_nodes[ROOTWARD].copy(), + self.block_nodes[LEAFWARD].copy(), ) - for k, v in self.fields.items(): - getattr(factors, k)[:] = v - return factors def unscale(self, nodes, scale): """ Make the state equivalent but with ``scale[nodes] = scale``, by dividing all - factors associated with those nodes (see ``_rescale_factors``) by ``scale``. + factors associated with those nodes (see ``rescale_factors``) by ``scale``. """ sel = np.zeros(self.node_posterior.shape[0], dtype=bool) sel[nodes] = True @@ -259,7 +260,7 @@ def likelihood_args(snap, unphased, order=None, likelihoods=None): def run_likelihood( - propagate_likelihood, + module, snap, unphased, max_shape=1000.0, @@ -268,14 +269,14 @@ def run_likelihood( likelihoods=None, ): """ - Run ``propagate_likelihood`` on copies of ``snap``; return + Run ``module.propagate_likelihood`` on copies of ``snap``; return ``(posterior, lognorm, node, edge, block, scale)`` after the pass. """ args, lognorm = likelihood_args(snap, unphased, order, likelihoods) factors = snap.factors() posterior = snap.node_posterior.copy() lognorm = lognorm.copy() - propagate_likelihood( + module.propagate_likelihood( *args, snap.node_constraints, posterior, @@ -285,27 +286,24 @@ def run_likelihood( min_step, USE_BLOCK_LIKELIHOOD if unphased else USE_EDGE_LIKELIHOOD, ) - return (posterior, lognorm, factors.node, factors.edge, factors.block, factors.scale) + return (posterior, lognorm, *factors[:4]) -def run_prior( - propagate_prior, snap, free, max_shape=1000.0, em_maxitt=10, em_reltol=1e-8 -): +def run_prior(module, snap, free, max_shape=1000.0, em_maxitt=10, em_reltol=1e-8): """ - Run ``propagate_prior`` on copies of ``snap``; return + Run ``module.propagate_prior`` on copies of ``snap``; return ``(posterior, node, scale)`` after the pass. """ factors = snap.factors() + node, edge, block, scale, *_ = factors posterior = snap.node_posterior.copy() - propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol) - return (posterior, factors.node, factors.scale) + module.propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol) + return (posterior, node, scale) -def run_mutations( - propagate_mutations, snap, unphased, edges=None, posterior=None, order=None -): +def run_mutations(module, snap, unphased, edges=None, posterior=None, order=None): """ - Run ``propagate_mutations`` on the phased (or unphased) mutations; return + Run ``module.propagate_mutations`` on the phased (or unphased) mutations; return ``(mutation_posterior, phase, node, edge, block, scale)``. """ factors = snap.factors() @@ -328,7 +326,7 @@ def run_mutations( snap.edge_children, snap.edge_likelihoods, ) - propagate_mutations( + module.propagate_mutations( order, mut_posterior, phase, @@ -338,21 +336,11 @@ def run_mutations( factors, USE_BLOCK_LIKELIHOOD if unphased else USE_EDGE_LIKELIHOOD, ) - return ( - mut_posterior, - phase, - factors.node, - factors.edge, - factors.block, - factors.scale, - ) + return (mut_posterior, phase, *factors[:4]) def run_sweeps( - propagate_likelihood, - propagate_prior, - propagate_mutations, - rescale_factors, + module, snap, num_sweeps, max_shape=1000.0, @@ -361,9 +349,9 @@ def run_sweeps( ): """ Run EP sweeps (the loop of `ExpectationPropagation.iterate`, then the mutation - passes of `infer`) with the given functions from a copy of ``snap``. Returns, per - sweep, ``(posterior, edge_logconst, block_logconst)`` copies, and the mutation - ``(posterior, phase)``. + passes of `infer`) with the functions of ``module`` from a copy of ``snap``. + Returns, per sweep, ``(posterior, edge_logconst, block_logconst)`` copies, and the + mutation ``(posterior, phase)``. """ factors = snap.factors() posterior = snap.node_posterior.copy() @@ -374,7 +362,7 @@ def run_sweeps( block_nodes = snap.block_nodes states = [] for _ in range(num_sweeps): - propagate_likelihood( + module.propagate_likelihood( snap.block_order, block_nodes[ROOTWARD], block_nodes[LEAFWARD], @@ -387,7 +375,7 @@ def run_sweeps( min_step, USE_BLOCK_LIKELIHOOD, ) - propagate_likelihood( + module.propagate_likelihood( snap.edge_order, snap.edge_parents, snap.edge_children, @@ -400,13 +388,13 @@ def run_sweeps( min_step, USE_EDGE_LIKELIHOOD, ) - propagate_prior( + module.propagate_prior( snap.unconstrained_roots, posterior, factors, max_shape, em_maxitt, 1e-8 ) - rescale_factors(factors) + module.rescale_factors(factors) states.append((posterior.copy(), edge_logconst.copy(), block_logconst.copy())) phased = snap.mutation_blocks == tskit.NULL - propagate_mutations( + module.propagate_mutations( snap.mutation_order[~phased], mut_posterior, mut_phase, @@ -419,7 +407,7 @@ def run_sweeps( factors, USE_BLOCK_LIKELIHOOD, ) - propagate_mutations( + module.propagate_mutations( snap.mutation_order[phased], mut_posterior, mut_phase, diff --git a/tests/oracle/hypergeo.py b/tests/oracle/hypergeo.py index 179b37ae..626d72b7 100644 --- a/tests/oracle/hypergeo.py +++ b/tests/oracle/hypergeo.py @@ -21,19 +21,19 @@ # gammaincinv is a primitive of the oracles, as the libm functions are: the C library's # port of `scipy.special.gammaincinv`, which `TestGammaincInv` compares with SciPy. -_gammainc_inv = _tsdate.gammainc_inv +gammainc_inv = _tsdate.gammainc_inv -def _digamma(x): +def digamma(x): """ Digamma (psi) function, from asymptotic series expansion. """ if x <= 0.0: - return _digamma(1 - x) - np.pi / tan(np.pi * x) + return digamma(1 - x) - np.pi / tan(np.pi * x) if x <= 1e-5: return -np.euler_gamma - (1 / x) if x < 8.5: - return _digamma(1 + x) - 1 / x + return digamma(1 + x) - 1 / x xpm2 = 1 / ipow(x, 2) return ( log(x) @@ -47,16 +47,16 @@ def _digamma(x): ) -def _trigamma(x): +def trigamma(x): """ Trigamma function, from asymptotic series expansion """ if x <= 0.0: - return -_trigamma(1 - x) + ipow(np.pi, 2) / ipow(sin(np.pi * x), 2) + return -trigamma(1 - x) + ipow(np.pi, 2) / ipow(sin(np.pi * x), 2) if x <= 1e-4: return 1 / ipow(x, 2) if x < 5: - return _trigamma(1 + x) + 1 / ipow(x, 2) + return trigamma(1 + x) + 1 / ipow(x, 2) xpm1 = 1 / x xpm2 = 1 / ipow(x, 2) return xpm1 * ( @@ -72,14 +72,14 @@ def _trigamma(x): ) -def _betaln(p, q): +def betaln(p, q): """ Log of the beta function. """ return lgamma(p) + lgamma(q) - lgamma(p + q) -def _hyperu_laplace(a, b, x): +def hyperu_laplace(a, b, x): """ Approximate Tricomi's confluent hypergeometric function with real arguments, using Laplace's method with a calibration point. @@ -106,7 +106,7 @@ def _hyperu_laplace(a, b, x): return g - log(r) / 2, (dg - dr) * du - u -def _hyp1f1_laplace(a, b, x): +def hyp1f1_laplace(a, b, x): """ Approximate Kummer's confluent hypergeometric function with real arguments, using Laplace's method with a calibration point. @@ -134,7 +134,7 @@ def _hyp1f1_laplace(a, b, x): return g - log(r) / 2 -def _hyp2f1_laplace(a, b, c, x): +def hyp2f1_laplace(a, b, c, x): r""" Approximate a Gaussian hypergeometric function with real arguments, using Laplace's method with a calibration point. @@ -205,7 +205,7 @@ def _hyp2f1_unity(a, b, c, x): return f - log(r) / 2 + s -def _gammainc_der(p, x): +def gammainc_der(p, x): """ Derivative of lower incomplete gamma function with regards to `p`. @@ -251,7 +251,7 @@ def _gammainc_der(p, x): grad += dc if c <= tol: break - darg = exp(arg) * (log(x) - _digamma(p + 1)) + darg = exp(arg) * (log(x) - digamma(p + 1)) grad = grad * exp(arg) + value * darg arg += log(value) if arg >= elimit: @@ -294,7 +294,7 @@ def _gammainc_der(p, x): dpn2 /= oflo dpn3 /= oflo dpn4 /= oflo - darg = exp(arg) * (log(x) - _digamma(p)) + darg = exp(arg) * (log(x) - digamma(p)) grad = grad * exp(arg) + value * darg arg += log(value) if arg >= elimit: diff --git a/tests/oracle/phasing.py b/tests/oracle/phasing.py index 29967737..f7b1c0eb 100644 --- a/tests/oracle/phasing.py +++ b/tests/oracle/phasing.py @@ -37,7 +37,7 @@ def reallocate_unphased(edges_likelihood, mutations_phase, mutations_block, bloc assert np.isclose(num_unphased, np.sum(edges_likelihood[edges_unphased, 0])) -def _block_singletons( +def block_singletons( individuals_unphased, nodes_individual, mutations_node, @@ -147,7 +147,7 @@ def _block_singletons( return blocks_stats, blocks_edges, mutations_block -def _mutation_frequency( +def mutation_frequency( nodes_sample, mutations_node, mutations_position, diff --git a/tests/oracle/prior.py b/tests/oracle/prior.py index 1439fe7b..0802c9cd 100644 --- a/tests/oracle/prior.py +++ b/tests/oracle/prior.py @@ -9,7 +9,7 @@ from ._libm import exp, log -def _marginalize_over_ancestors(val): +def marginalize_over_ancestors(val): """ Integrate an expectation over counts of extant ancestors. In a tree with "n" tips, the probability that there are "a" extent ancestors when a @@ -54,6 +54,6 @@ def conditional_coalescent_variance(num_tips): variance[i] += variance[i + 1] # marginalize over number of ancestors using recursive algorithm - moments = _marginalize_over_ancestors(np.stack((mean, variance + mean**2), 1)) + moments = marginalize_over_ancestors(np.stack((mean, variance + mean**2), 1)) return moments[:, 1] - moments[:, 0] ** 2 diff --git a/tests/oracle/rescaling.py b/tests/oracle/rescaling.py index 1fdd87ac..5cf675e8 100644 --- a/tests/oracle/rescaling.py +++ b/tests/oracle/rescaling.py @@ -11,10 +11,10 @@ # whereas numpy sums pairwise (`seq_sum`). from ._libm import log, seq_sum from .approx import approximate_gamma_iqr -from .hypergeo import _gammainc_inv as gammainc_inv +from .hypergeo import gammainc_inv -def _fixed_changepoints(counts, epochs): +def fixed_changepoints(counts, epochs): """ Find breakpoints such that `counts` is divided roughly equally across `epochs` """ @@ -30,7 +30,7 @@ def _fixed_changepoints(counts, epochs): return e.astype(np.int32) -def _poisson_changepoints(counts, offset, penalty, min_counts, min_offset): +def poisson_changepoints(counts, offset, penalty, min_counts, min_offset): """ Given Poisson counts and offsets for a sequence of observations, find the set of changepoints for the Poisson rate that maximizes the profile likelihood @@ -77,7 +77,7 @@ def f(i, j): # loss return breaks -def _count_mutations( +def count_mutations( node_is_sample, mutations_node, mutations_position, @@ -266,7 +266,7 @@ def mutational_timescale( # rescale time such that mutation density is constant between changepoints # TODO: use poisson changepoints to further refine epoch_breaks = np.append(0.0, np.cumsum(duration)) - changepoints = _fixed_changepoints(offset * duration, max_intervals) + changepoints = fixed_changepoints(offset * duration, max_intervals) changepoints = np.unique(changepoints) # changepoints = np.union1d(changepoints, indexes[nodes_fixed]) adjust = np.zeros(changepoints.size) diff --git a/tests/oracle/util.py b/tests/oracle/util.py index 8c556871..c162f75d 100644 --- a/tests/oracle/util.py +++ b/tests/oracle/util.py @@ -6,7 +6,7 @@ import tskit -def _split_disjoint_nodes( +def split_disjoint_nodes( edges_parent, edges_child, edges_left, edges_right, node_excluded ): """ @@ -64,7 +64,7 @@ def _split_disjoint_nodes( return edges_parent, edges_child, nodes_order, split_nodes -def _relabel_mutations_node( +def relabel_mutations_node( mutations_node, mutations_position, nodes_order, @@ -121,7 +121,7 @@ def _relabel_mutations_node( return output -def _constrain_ages( +def constrain_ages( nodes_time, nodes_fixed, edges_parent, edges_child, epsilon, max_iterations ): """ @@ -174,7 +174,7 @@ def _constrain_ages( return nodes_time -def _contains_unary_nodes( +def contains_unary_nodes( nodes_mask, edges_parent, edges_left, diff --git a/tests/oracle/variational.py b/tests/oracle/variational.py index 850daa7e..d1ad54aa 100644 --- a/tests/oracle/variational.py +++ b/tests/oracle/variational.py @@ -1,5 +1,10 @@ """ Oracles for the expectation propagation passes (``lib/variational.c``). + +The mutable state of the EP algorithm, the factors associated with each edge +likelihood, block likelihood and prior factor that together form the posterior, is a +tuple of eight arrays ``(node, edge, block, scale, edges_parent, edges_child, +blocks_left, blocks_right)``; the passes update the first four in place. """ import numpy as np @@ -22,35 +27,7 @@ from ._libm import seq_mean -class EPFactors: - """ - Mutable state of the EP algorithm, that is the factors associated - with each edge likelihood / block likelihood / prior factor, that - together form the posterior. - """ - - def __init__( - self, - node_constraints, - edge_parents, - edge_children, - block_left, - block_right, - ): - assert edge_parents.size == edge_children.size - assert block_left.size == block_right.size - num_nodes = node_constraints.shape[0] - num_edges = edge_parents.size - num_blocks = block_left.size - self.node = np.zeros((num_nodes, 2, 2)) - self.edge = np.zeros((num_edges, 2, 2)) - self.block = np.zeros((num_blocks, 2, 2)) - self.scale = np.ones(num_nodes) - self._p, self._c = edge_parents, edge_children - self._j, self._k = block_left, block_right - - -def _rescale_factors(factors): +def rescale_factors(factors): """ At each update, all factors associated with a node need to be rescaled. This is expensive, so we keep track of the scaling in a separate vector. @@ -58,70 +35,74 @@ def _rescale_factors(factors): the scaling drifts downward. To avoid underflow, we may need to cancel out the scaling. """ - factors.edge[:, ROOTWARD] *= factors.scale[factors._p, np.newaxis] - factors.edge[:, LEAFWARD] *= factors.scale[factors._c, np.newaxis] - factors.block[:, ROOTWARD] *= factors.scale[factors._j, np.newaxis] - factors.block[:, LEAFWARD] *= factors.scale[factors._k, np.newaxis] - factors.node[:, MIXPRIOR] *= factors.scale[:, np.newaxis] - factors.node[:, CONSTRNT] *= factors.scale[:, np.newaxis] - factors.scale[:] = 1.0 - - -def _assemble_factors(factors): + node, edge, block, scale, edges_parent, edges_child, blocks_left, blocks_right = ( + factors + ) + edge[:, ROOTWARD] *= scale[edges_parent, np.newaxis] + edge[:, LEAFWARD] *= scale[edges_child, np.newaxis] + block[:, ROOTWARD] *= scale[blocks_left, np.newaxis] + block[:, LEAFWARD] *= scale[blocks_right, np.newaxis] + node[:, MIXPRIOR] *= scale[:, np.newaxis] + node[:, CONSTRNT] *= scale[:, np.newaxis] + scale[:] = 1.0 + + +def assemble_factors(factors): """ Transform factors into posteriors, intended for debugging purposes only. """ - posterior = np.zeros((factors.scale.size, 2)) - for i, (p, c) in enumerate(zip(factors._p, factors._c)): - posterior[p] += factors.edge[i, ROOTWARD] - posterior[c] += factors.edge[i, LEAFWARD] - for i, (j, k) in enumerate(zip(factors._j, factors._k)): - posterior[j] += factors.block[i, ROOTWARD] - posterior[k] += factors.block[i, LEAFWARD] - posterior += factors.node[:, MIXPRIOR] - posterior += factors.node[:, CONSTRNT] + node, edge, block, scale, edges_parent, edges_child, blocks_left, blocks_right = ( + factors + ) + posterior = np.zeros((scale.size, 2)) + for i, (p, c) in enumerate(zip(edges_parent, edges_child)): + posterior[p] += edge[i, ROOTWARD] + posterior[c] += edge[i, LEAFWARD] + for i, (j, k) in enumerate(zip(blocks_left, blocks_right)): + posterior[j] += block[i, ROOTWARD] + posterior[k] += block[i, LEAFWARD] + posterior += node[:, MIXPRIOR] + posterior += node[:, CONSTRNT] return posterior -def _damp(x, y, s): +def damp(x0, x1, y0, y1, s): """ If `x - y` is too small, find `d` so that `x - d*y` is large enough: - x[0] - d*y[0] + 1 >= (x[0] + 1)*s - x[1] - d*y[1] >= y[1]*s + x0 - d*y0 + 1 >= (x0 + 1)*s + x1 - d*y1 >= y1*s for `0 < s < 1`. """ - assert x.size == y.size == 2 - if np.all(y == 0.0) and np.all(x == 0.0): + if y0 == 0.0 and y1 == 0.0 and x0 == 0.0 and x1 == 0.0: return 1.0 assert 0 < s < 1 - assert 0.0 < x[0] + 1 - assert 0.0 < x[1] - a = 1.0 if (1 + x[0] - y[0] > (1 + x[0]) * s) else (1 - s) * (1 + x[0]) / y[0] - b = 1.0 if (x[1] - y[1] > x[1] * s) else (1 - s) * x[1] / y[1] + assert 0.0 < x0 + 1 + assert 0.0 < x1 + a = 1.0 if (1 + x0 - y0 > (1 + x0) * s) else (1 - s) * (1 + x0) / y0 + b = 1.0 if (x1 - y1 > x1 * s) else (1 - s) * x1 / y1 d = min(a, b) assert 0.0 < d <= 1.0 return d -def _rescale(x, s): +def rescale(x0, x1, s): """ - Find `d` so that `d*x[0] + 1 <= s[0]` or `d*x[0] + 1 >= 1/s[0]` + Find `d` so that `d*x0 + 1 <= s` or `d*x0 + 1 >= 1/s` """ - assert x.size == 2 - if np.all(x == 0.0): + if x0 == 0.0 and x1 == 0.0: return 1.0 - assert 0 < x[0] + 1 - assert 0 < x[1] - if 1 + x[0] > s: - return (s - 1) / x[0] - elif 1 + x[0] < 1 / s: - return (1 / s - 1) / x[0] + assert 0 < x0 + 1 + assert 0 < x1 + if 1 + x0 > s: + return (s - 1) / x0 + elif 1 + x0 < 1 / s: + return (1 / s - 1) / x0 return 1.0 -def _constraints_are_consistent(constraints, edges_parent, edges_child): +def constraints_are_consistent(constraints, edges_parent, edges_child): """ Whether the upper bound on each node's age is at least the maximum lower bound of its descendants' ages. @@ -155,7 +136,7 @@ def propagate_likelihood( # containing lower and upper bounds for each node. # :param numpy.ndarray posterior: array of dimension `[num_nodes, 2]` # containing natural parameters for each node, updated in-place. - # :param EPFactors factors: object containing parent and child factors + # :param tuple factors: the factor arrays, containing parent and child factors # (natural parameters) for each edge, updated in-place. # :param numpy.ndarray lognorm: array of dimension `[num_edges]` # containing the approximate normalizing constants per edge, @@ -172,41 +153,46 @@ def propagate_likelihood( assert 0.0 < min_step < 1.0 def cavity_damping(x, y): - return _damp(x, y, min_step) + return damp(x[0], x[1], y[0], y[1], min_step) def posterior_damping(x): - return _rescale(x, max_shape) + return rescale(x[0], x[1], max_shape) - def leafward_projection(x, y, z): - if unphased: - return approx.sideways_projection(x, y, z) - return approx.leafward_projection(x, y, z) + # the projections take the entries of the cavities and of the edge likelihood + # as floats, and return the normalizing constant and the projected natural + # parameters of each node - def rootward_projection(x, y, z): - if unphased: - return approx.sideways_projection(x, y, z) - return approx.rootward_projection(x, y, z) + def leafward_projection(t, x, y): + project = approx.sideways_projection if unphased else approx.leafward_projection + logl, *proj = project(t, *map(float, x), *map(float, y)) + return logl, proj + + def rootward_projection(t, x, y): + project = approx.sideways_projection if unphased else approx.rootward_projection + logl, *proj = project(t, *map(float, x), *map(float, y)) + return logl, proj def gamma_projection(x, y, z): - if unphased: - return approx.unphased_projection(x, y, z) - return approx.gamma_projection(x, y, z) + project = approx.unphased_projection if unphased else approx.gamma_projection + logl, *proj = project(*map(float, x), *map(float, y), *map(float, z)) + return logl, proj[:2], proj[2:] def twin_projection(x, y): assert unphased, "Invalid update" - return approx.twin_projection(x, y) + logl, *proj = approx.twin_projection(*map(float, x), *map(float, y)) + return logl, proj fixed = constraints[:, LOWER] == constraints[:, UPPER] - scale = factors.scale - factor = factors.block if unphased else factors.edge + node, edge, block, scale, *_ = factors + factor = block if unphased else edge assert factor.shape == (edges_parent.size, 2, 2) for i in edge_order: p, c = edges_parent[i], edges_child[i] if scale[p] < TINY or scale[c] < TINY: # modifies `scale` and `factor` by reference - _rescale_factors(factors) + rescale_factors(factors) if fixed[p] and fixed[c]: continue elif fixed[p] and not fixed[c]: @@ -298,7 +284,7 @@ def propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol): # :param ndarray penalty: initial value for regularisation penalty # :param ndarray posterior: rows are nodes, columns are first and # second natural parameters of gamma posteriors. Updated in place. - # :param EPFactors factors: object containing EP messages for nodes. + # :param tuple factors: the factor arrays, containing EP messages for nodes. # Updated in place. # :param float max_shape: the maximum allowed shape for node posteriors. # :param int em_maxitt: the maximum number of EM iterations to use when @@ -310,13 +296,13 @@ def propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol): assert max_shape >= 1.0 def posterior_damping(x): - return _rescale(x, max_shape) + return rescale(x[0], x[1], max_shape) if not np.any(free): return - factor = factors.node - scale = factors.scale + node, edge, block, scale, *_ = factors + factor = node assert factor.shape == (free.size, 2, 2) assert scale.size == free.size @@ -373,8 +359,8 @@ def propagate_mutations( # containing lower and upper bounds for each node. # :param ndarray posterior: array of dimension `[num_nodes, 2]` # containing natural parameters for each node - # :param EPFactors factors: object containing - # containing parent and child factors (natural parameters) for each edge + # :param tuple factors: the factor arrays, containing parent and child factors + # (natural parameters) for each edge # :param bool unphased: if True, edges are treated as blocks of unphased # singletons in contemporary individuals @@ -388,32 +374,49 @@ def propagate_mutations( assert edges_child.size == edges_parent.size assert likelihoods.shape == (edges_parent.size, 2) - def leafward_projection(x, y, z): + # the projections take the entries of the cavities and of the edge likelihood + # as floats, and return the phase and the natural parameters of the mutation + + def leafward_projection(t, x, y): if unphased: - return approx.mutation_sideways_projection(x, y, z) - return approx.mutation_leafward_projection(x, y, z) + project = approx.mutation_sideways_projection + else: + project = approx.mutation_leafward_projection + phase, *proj = project(t, *map(float, x), *map(float, y)) + return phase, proj - def rootward_projection(x, y, z): + def rootward_projection(t, x, y): if unphased: - return approx.mutation_sideways_projection(x, y, z) - return approx.mutation_rootward_projection(x, y, z) + project = approx.mutation_sideways_projection + else: + project = approx.mutation_rootward_projection + phase, *proj = project(t, *map(float, x), *map(float, y)) + return phase, proj def gamma_projection(x, y, z): if unphased: - return approx.mutation_unphased_projection(x, y, z) - return approx.mutation_gamma_projection(x, y, z) + project = approx.mutation_unphased_projection + else: + project = approx.mutation_gamma_projection + phase, *proj = project(*map(float, x), *map(float, y), *map(float, z)) + return phase, proj - def fixed_projection(x, y): + def fixed_projection(t_i, t_j): if unphased: - return approx.mutation_block_projection(x, y) - return approx.mutation_edge_projection(x, y) + project = approx.mutation_block_projection + else: + project = approx.mutation_edge_projection + phase, *proj = project(t_i, t_j) + return phase, proj - twin_projection = approx.mutation_twin_projection + def twin_projection(x, y): + phase, *proj = approx.mutation_twin_projection(*map(float, x), *map(float, y)) + return phase, proj fixed = constraints[:, LOWER] == constraints[:, UPPER] - scale = factors.scale - factor = factors.block if unphased else factors.edge + node, edge, block, scale, *_ = factors + factor = block if unphased else edge assert factor.shape == (edges_parent.size, 2, 2) for m in mutations_order: diff --git a/tests/test_oracle_approx.py b/tests/test_oracle_approx.py index 069c2db7..e369c752 100644 --- a/tests/test_oracle_approx.py +++ b/tests/test_oracle_approx.py @@ -2,7 +2,7 @@ Parity of the gamma approximations of ``_tsdate`` with their oracles in ``oracle/approx.py``: exact values (including NaNs and infinities), and which exception is raised. Expected values always come from the oracle. Tables hold -deliberate edge cases (boundaries of the ``_valid_*`` checks, degenerate gamma fits, +deliberate edge cases (boundaries of the ``valid_*`` checks, degenerate gamma fits, regimes of the moment and projection functions); seeded random draws cover ranges typical of expectation propagation (EP) and extreme ones. @@ -39,83 +39,12 @@ TINY = 5e-324 -def valid_check(func): - """ - A ``_valid_*`` C function returning a bool, as its oracle does, instead of a float - """ - - def valid(*args): - return bool(func(*args)) - - return valid - - -def projection(func): - """ - A projection C function with the signature of its oracle. The C function takes - flat arguments (the ages, and the entries of the parameter arrays) and returns a - flat tuple: the first result, then the pairs of natural parameters; the oracle - takes arrays and returns the first result and one array per pair. - """ - - def project(*args): - flat = [float(x) for arg in args for x in np.atleast_1d(arg)] - first, *rest = func(*flat) - pairs = [np.array(rest[i : i + 2]) for i in range(0, len(rest), 2)] - return (first, *pairs) - - return project - - -# The C function for each oracle in ``approx``, with the oracle's signature -C_FUNCTIONS = { - "approximate_log_moments": _tsdate.approximate_log_moments, - "approximate_gamma_kl": _tsdate.approximate_gamma_kl, - "approximate_gamma_mom": _tsdate.approximate_gamma_mom, - "approximate_gamma_iqr": _tsdate.approximate_gamma_iqr, - "average_gammas": _tsdate.average_gammas, - "moments": _tsdate.moments, - "rootward_moments": _tsdate.rootward_moments, - "leafward_moments": _tsdate.leafward_moments, - "unphased_moments": _tsdate.unphased_moments, - "twin_moments": _tsdate.twin_moments, - "sideways_moments": _tsdate.sideways_moments, - "mutation_moments": _tsdate.mutation_moments, - "mutation_rootward_moments": _tsdate.mutation_rootward_moments, - "mutation_leafward_moments": _tsdate.mutation_leafward_moments, - "mutation_unphased_moments": _tsdate.mutation_unphased_moments, - "mutation_twin_moments": _tsdate.mutation_twin_moments, - "mutation_sideways_moments": _tsdate.mutation_sideways_moments, - "mutation_edge_moments": _tsdate.mutation_edge_moments, - "mutation_block_moments": _tsdate.mutation_block_moments, - "_valid_moments": valid_check(_tsdate.valid_moments), - "_valid_gamma": valid_check(_tsdate.valid_gamma), - "_valid_hyp1f1": valid_check(_tsdate.valid_hyp1f1), - "_valid_hyperu": valid_check(_tsdate.valid_hyperu), - "_valid_hyp2f1": valid_check(_tsdate.valid_hyp2f1), - "gamma_projection": projection(_tsdate.gamma_projection), - "leafward_projection": projection(_tsdate.leafward_projection), - "rootward_projection": projection(_tsdate.rootward_projection), - "unphased_projection": projection(_tsdate.unphased_projection), - "twin_projection": projection(_tsdate.twin_projection), - "sideways_projection": projection(_tsdate.sideways_projection), - "mutation_gamma_projection": projection(_tsdate.mutation_gamma_projection), - "mutation_leafward_projection": projection(_tsdate.mutation_leafward_projection), - "mutation_rootward_projection": projection(_tsdate.mutation_rootward_projection), - "mutation_edge_projection": projection(_tsdate.mutation_edge_projection), - "mutation_unphased_projection": projection(_tsdate.mutation_unphased_projection), - "mutation_twin_projection": projection(_tsdate.mutation_twin_projection), - "mutation_sideways_projection": projection(_tsdate.mutation_sideways_projection), - "mutation_block_projection": projection(_tsdate.mutation_block_projection), -} - - def parity(name, args, expected_kind=None): """ - Compare the C function for the oracle ``approx.`` with the oracle on - ``args`` (returning the oracle's outcome); optionally check its kind. + Compare ``_tsdate.`` with the oracle ``approx.`` on ``args`` + (returning the oracle's outcome); optionally check its kind. """ - func = C_FUNCTIONS[name] + func = getattr(_tsdate, name) oracle = getattr(approx, name) if expected_kind is None: return compare(func, oracle, *args) @@ -137,7 +66,7 @@ def natural(shape, rate): """ Natural parameters of a gamma """ - return np.array([shape - 1.0, rate]) + return shape - 1.0, rate def gamma_quantiles(shape, rate, q1=0.25, q2=0.75): @@ -219,7 +148,7 @@ def z_below_one(z): def hyp2f1_rows(): """ - ``(args, expected)`` for ``_valid_hyp2f1``: a, b, c positive and finite, z < 1 + ``(args, expected)`` for ``valid_hyp2f1``: a, b, c positive and finite, z < 1 """ rows = [((1.0, 1.0, 1.0, 0.0), True), ((10.0, 1.0, 1.0, 0.5), True)] # a > c is ok for i in range(3): @@ -245,20 +174,16 @@ def hyp2f1_rows(): VALID = ( - [ - (n, args, v) - for n in ["_valid_moments", "_valid_gamma"] - for args, v in MOMENTS_VALID - ] - + [("_valid_hyp1f1", args, v) for args, v in HYP1F1] - + [("_valid_hyperu", args, v) for args, v in HYPERU] - + [("_valid_hyp2f1", args, v) for args, v in hyp2f1_rows()] + [(n, args, v) for n in ["valid_moments", "valid_gamma"] for args, v in MOMENTS_VALID] + + [("valid_hyp1f1", args, v) for args, v in HYP1F1] + + [("valid_hyperu", args, v) for args, v in HYPERU] + + [("valid_hyp2f1", args, v) for args, v in hyp2f1_rows()] ) class TestValidChecks: """ - Boundaries of the ``_valid_*`` checks, at and either side. Each of them is the + Boundaries of the ``valid_*`` checks, at and either side. Each of them is the gate that turns unusable moments or hypergeometric parameters into NaN. """ @@ -268,7 +193,7 @@ class TestValidChecks: ) def test_valid(self, name, args, expected): result = parity(name, args) - assert bool(result.value) is expected + assert result.value == float(expected) # --- gamma approximations --- # @@ -378,7 +303,7 @@ def test_valid(self, name, args, expected): # gamma with tiny shape underflows to zero, so the fit divides by zero ((*gamma_quantiles(1e-3, 1.0), 50.0), ZeroDivisionError), ] -# shapes below, at and above the cap, and beyond the range where `_gammainc_der` uses +# shapes below, at and above the cap, and beyond the range where `gammainc_der` uses # its gaussian approximation (shape > 1e3) GAMMA_IQR_FITS = [ (shape, max_shape) @@ -424,7 +349,7 @@ def test_domain(self, name, args, expected): ) def test_error_messages(self, name, args, expected): # the messages distinguish the failure modes - func = C_FUNCTIONS[name] + func = getattr(_tsdate, name) with pytest.raises(expected_error(KLMinimizationFailedError)): func(*args) compare(func, getattr(approx, name), *args) @@ -519,7 +444,7 @@ def test_cases(self, label): "a=0": (1000, 0, 0.01, 1, 1e-4), "a<0": (1000, -1, 0.01, 1, 1e-4), # NOTE: current behaviour, possibly a bug: y = -1 passes - # `_valid_hyp1f1` (b == a) but `_hyp1f1_laplace` asserts b > a + # `valid_hyp1f1` (b == a) but `hyp1f1_laplace` asserts b > a "y=-1": (1000, 10, 0.01, -1, 1e-4), "y=-0.5": (1000, 10, 0.01, -0.5, 1e-4), } @@ -625,14 +550,14 @@ def projection_args(name, args): moments = PROJECTIONS[name][0] if moments in TWO_NODE_MOMENTS: a_i, b_i, a_j, b_j, y, mu = args - return natural(a_i, b_i), natural(a_j, b_j), np.array([y, mu]) + return (*natural(a_i, b_i), *natural(a_j, b_j), y, mu) if moments in TWIN_MOMENTS: a_i, b_i, y, mu = args - return natural(a_i, b_i), np.array([y, mu]) + return (*natural(a_i, b_i), y, mu) if moments in TIMES_MOMENTS: return tuple(args) t, a, b, y, mu = args - return t, natural(a, b), np.array([y, mu]) + return (t, *natural(a, b), y, mu) def moment_args(name, proj_args): @@ -642,15 +567,25 @@ def moment_args(name, proj_args): """ moments = PROJECTIONS[name][0] if moments in TWO_NODE_MOMENTS: - pars_i, pars_j, (y, mu) = proj_args - return pars_i[0] + 1, pars_i[1], pars_j[0] + 1, pars_j[1], y, mu + alpha_i, beta_i, alpha_j, beta_j, y, mu = proj_args + return alpha_i + 1, beta_i, alpha_j + 1, beta_j, y, mu if moments in TWIN_MOMENTS: - pars_i, (y, mu) = proj_args - return pars_i[0] + 1, pars_i[1], y, mu + alpha_i, beta_i, y, mu = proj_args + return alpha_i + 1, beta_i, y, mu if moments in TIMES_MOMENTS: return proj_args - t, pars, (y, mu) = proj_args - return t, pars[0] + 1, pars[1], y, mu + t, alpha, beta, y, mu = proj_args + return t, alpha + 1, beta, y, mu + + +def natural_args(name, proj_args): + """ + The natural parameters among the arguments of a projection + """ + moments = PROJECTIONS[name][0] + if moments in ONE_NODE_MOMENTS: + return proj_args[1:-2] + return proj_args[:-2] def is_valid(mean, variance, prob=None): @@ -683,11 +618,10 @@ def check_projection(name, args): return assert np.isnan(result.value[0]) if name in RETURNS_INPUT: - given = [p for p in proj_args if isinstance(p, np.ndarray)] - for returned, original in zip(result.value[1:], given): - np.testing.assert_array_equal(returned, original) + given = natural_args(name, proj_args) + np.testing.assert_array_equal(result.value[1:], given) else: - assert np.isnan(result.value[1]).all() + assert np.isnan(result.value[1:]).all() MOMENT_REGIMES = [ @@ -719,11 +653,10 @@ def test_inputs_are_not_modified(self, name): moments = PROJECTIONS[name][0] first_regime = next(iter(REGIMES[moments].values())) proj_args = projection_args(name, floats(first_regime)) - copies = [a.copy() if isinstance(a, np.ndarray) else a for a in proj_args] - func = C_FUNCTIONS[name] + copies = list(proj_args) + func = getattr(_tsdate, name) func(*proj_args) - for arg, copy in zip(proj_args, copies): - np.testing.assert_array_equal(arg, copy) + assert list(proj_args) == copies def test_unphased_probability_out_of_range(self): # NOTE: current behaviour, possibly a bug: the Laplace diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index 0dff5e7d..4fc6e381 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -27,24 +27,13 @@ nextafter = np.nextafter -# The C function for each oracle in ``hypergeo`` -C_FUNCTIONS = { - "_digamma": _tsdate.digamma, - "_trigamma": _tsdate.trigamma, - "_betaln": _tsdate.betaln, - "_gammainc_der": _tsdate.gammainc_der, - "_hyperu_laplace": _tsdate.hyperu_laplace, - "_hyp1f1_laplace": _tsdate.hyp1f1_laplace, - "_hyp2f1_laplace": _tsdate.hyp2f1_laplace, -} - def parity(name, args, expected_kind=None): """ - Compare the C function for the oracle ``hypergeo.`` with the oracle on - ``args``; optionally check the kind. + Compare ``_tsdate.`` with the oracle ``hypergeo.`` on ``args``; + optionally check the kind. """ - func = C_FUNCTIONS[name] + func = getattr(_tsdate, name) oracle = getattr(hypergeo, name) if expected_kind is None: return compare(func, oracle, *args) @@ -133,14 +122,14 @@ def table(name, rows): class TestPolygamma: - @pytest.mark.parametrize("name", ["_digamma", "_trigamma"]) + @pytest.mark.parametrize("name", ["digamma", "trigamma"]) @pytest.mark.parametrize("x", DIGAMMA_POINTS, ids=repr) def test_matches_oracle(self, name, x): parity(name, (x,)) @pytest.mark.parametrize( ("name", "args", "expected"), - table("_digamma", POLYGAMMA_KINDS) + table("_trigamma", TRIGAMMA_KINDS), + table("digamma", POLYGAMMA_KINDS) + table("trigamma", TRIGAMMA_KINDS), ) def test_poles_and_nonfinite(self, name, args, expected): parity(name, args, expected) @@ -177,10 +166,10 @@ def test_poles_and_nonfinite(self, name, args, expected): class TestBetaln: @pytest.mark.parametrize(("p", "q"), BETALN_POINTS, ids=repr) def test_matches_oracle(self, p, q): - parity("_betaln", (p, q)) + parity("betaln", (p, q)) -# `_gammainc_der(p, x)`: regimes are x == 0, x > 1e8, p > 1e3 (gaussian), +# `gammainc_der(p, x)`: regimes are x == 0, x > 1e8, p > 1e3 (gaussian), # x <= 1 or x < p (series) and otherwise a continued fraction. GAMMAINC_DER_POINTS = [ (1.0, 0.0), @@ -247,10 +236,10 @@ def test_matches_oracle(self, p, q): class TestGammaincDer: @pytest.mark.parametrize(("p", "x"), GAMMAINC_DER_POINTS, ids=repr) def test_matches_oracle(self, p, x): - parity("_gammainc_der", (p, x)) + parity("gammainc_der", (p, x)) @pytest.mark.parametrize( - ("name", "args", "expected"), table("_gammainc_der", GAMMAINC_DER_DOMAIN) + ("name", "args", "expected"), table("gammainc_der", GAMMAINC_DER_DOMAIN) ) def test_domain(self, name, args, expected): parity(name, args, expected) @@ -386,7 +375,7 @@ def test_matches_scipy_random(self): HYP1F1_DOMAIN = [ ((1.0, 2.0, 0.0), "finite"), ((1.0, 2.0, -0.0), "finite"), - # NOTE: current behaviour, possibly a bug: b == a is allowed by `_valid_hyp1f1` + # NOTE: current behaviour, possibly a bug: b == a is allowed by `valid_hyp1f1` # (in approx) but asserted against here ((1.0, 1.0, 1.0), AssertionError), ((1.0, 0.5, 1.0), AssertionError), @@ -451,14 +440,14 @@ def test_matches_scipy_random(self): def laplace_grid(name): - if name == "_hyperu_laplace": + if name == "hyperu_laplace": return [ (a, a + db, x) for a in [1e-10, 1e-3, 1.0, 50.0, 1e5] for db in [0.0, 1e-10, 1.0, 1e3, 1e10] for x in [1e-12, 1e-3, 1.0, 1e3, 1e8, 1e15] ] - if name == "_hyp1f1_laplace": + if name == "hyp1f1_laplace": return [ (a, a + db, x) for a in [1e-10, 1e-3, 1.0, 50.0, 1e5] @@ -472,15 +461,15 @@ def laplace_grid(name): LAPLACE = { - "_hyperu_laplace": HYPERU_DOMAIN, - "_hyp1f1_laplace": HYP1F1_DOMAIN, - "_hyp2f1_laplace": HYP2F1_DOMAIN, + "hyperu_laplace": HYPERU_DOMAIN, + "hyp1f1_laplace": HYP1F1_DOMAIN, + "hyp2f1_laplace": HYP2F1_DOMAIN, } def unity_formula(a, b, c, z): """ - The result of `_hyp2f1_laplace` in the unity limit, written out. See DLMF 15.4: + The result of `hyp2f1_laplace` in the unity limit, written out. See DLMF 15.4: the sign of ``g = c - a - b`` selects the limit, and negative ``z`` is mapped to ``z / (z - 1)`` close to one by Pfaff's transformation. """ @@ -529,7 +518,7 @@ def negative_unity_threshold(): def unity_args_from_ep(a_i, b_i, a_j, b_j, y, mu): """ - Arguments of `_hyp2f1_laplace` in the edge update of EP, for hugely negative z + Arguments of `hyp2f1_laplace` in the edge update of EP, for hugely negative z """ return a_j, a_i + a_j + y, a_j + y + 1, (mu - b_j) / (mu + b_i) @@ -560,7 +549,7 @@ def unity_args_from_ep(a_i, b_i, a_j, b_j, y, mu): class TestLaplaceDomain: """ - Edge cases of `_hyperu_laplace`, `_hyp1f1_laplace` and `_hyp2f1_laplace`: the + Edge cases of `hyperu_laplace`, `hyp1f1_laplace` and `hyp2f1_laplace`: the domain assertions, the zero shortcuts (``x == 0`` returns 0 after the checks), the division by zero when a Laplace root cancels, and overflow. """ @@ -594,7 +583,7 @@ def test_unity_branches(self, args): a, b, c, z = args mapped = z / (z - 1) if z < 0 else z assert np.isclose(mapped, 1.0), "case must take the unity branch" - result = parity("_hyp2f1_laplace", args) + result = parity("hyp2f1_laplace", args) assert_same_values(result.value, unity_formula(a, b, c, z)) @pytest.mark.parametrize("sign", ["positive", "negative"]) @@ -606,7 +595,7 @@ def test_switch_point(self, sign, side): else: not_close, close = negative_unity_threshold() z = close if side == "close" else not_close - parity("_hyp2f1_laplace", (5.0, 7.0, 9.0, z), "finite") + parity("hyp2f1_laplace", (5.0, 7.0, 9.0, z), "finite") def draw_polygamma(rng, extreme): @@ -672,13 +661,13 @@ def draw_hyp2f1(rng, extreme): DRAWS = { - "_digamma": draw_polygamma, - "_trigamma": draw_polygamma, - "_betaln": draw_betaln, - "_gammainc_der": draw_gammainc_der, - "_hyperu_laplace": draw_hyperu, - "_hyp1f1_laplace": draw_hyp1f1, - "_hyp2f1_laplace": draw_hyp2f1, + "digamma": draw_polygamma, + "trigamma": draw_polygamma, + "betaln": draw_betaln, + "gammainc_der": draw_gammainc_der, + "hyperu_laplace": draw_hyperu, + "hyp1f1_laplace": draw_hyp1f1, + "hyp2f1_laplace": draw_hyp2f1, } diff --git a/tests/test_oracle_phasing.py b/tests/test_oracle_phasing.py index c7185097..d4179b72 100644 --- a/tests/test_oracle_phasing.py +++ b/tests/test_oracle_phasing.py @@ -111,7 +111,7 @@ def args(ts, unphased): @staticmethod def compare(args): - return compare(_tsdate.block_singletons, phasing._block_singletons, *args) + return compare(_tsdate.block_singletons, phasing.block_singletons, *args) @pytest.mark.parametrize( ("nodes", "num_individuals", "edges", "mutations", "unphased", "expected_error"), @@ -325,7 +325,7 @@ class TestMutationFrequency: def compare(nodes_sample, args): return compare( _tsdate.mutation_frequency, - phasing._mutation_frequency, + phasing.mutation_frequency, nodes_sample, *args, ) diff --git a/tests/test_oracle_prior.py b/tests/test_oracle_prior.py index 4d5eda2f..b2d48800 100644 --- a/tests/test_oracle_prior.py +++ b/tests/test_oracle_prior.py @@ -1,5 +1,5 @@ """ -Parity of ``_marginalize_over_ancestors`` and ``conditional_coalescent_variance`` +Parity of ``marginalize_over_ancestors`` and ``conditional_coalescent_variance`` with their oracles, and a pin of how ``tsdate`` calls the latter with a single tip. """ @@ -48,7 +48,7 @@ def test_random(self, seed, num_tips): val = rng.uniform(0.1, 10.0, (num_tips, 2)) result = compare( _tsdate.marginalize_over_ancestors, - prior._marginalize_over_ancestors, + prior.marginalize_over_ancestors, val, ) assert result.value.shape == (num_tips + 1, 2) @@ -58,7 +58,7 @@ def test_number_of_moments(self, num_columns): val = np.random.default_rng(0).uniform(0.1, 10.0, (12, num_columns)) compare( _tsdate.marginalize_over_ancestors, - prior._marginalize_over_ancestors, + prior.marginalize_over_ancestors, val, ) @@ -66,7 +66,7 @@ def test_number_of_moments(self, num_columns): def test_coalescent_moments(self, num_tips): compare( _tsdate.marginalize_over_ancestors, - prior._marginalize_over_ancestors, + prior.marginalize_over_ancestors, coalescent_moments(num_tips), ) @@ -74,7 +74,7 @@ def test_coalescent_moments(self, num_tips): def test_edge_cases(self, val, expected_kind): assert_outcome( _tsdate.marginalize_over_ancestors, - prior._marginalize_over_ancestors, + prior.marginalize_over_ancestors, (val,), expected_kind, ) diff --git a/tests/test_oracle_rescaling.py b/tests/test_oracle_rescaling.py index f6fc98eb..e96a7c33 100644 --- a/tests/test_oracle_rescaling.py +++ b/tests/test_oracle_rescaling.py @@ -124,7 +124,7 @@ class TestFixedChangepoints: def compare(counts, epochs): return compare( _tsdate.fixed_changepoints, - rescaling._fixed_changepoints, + rescaling.fixed_changepoints, np.asarray(counts, dtype=float), epochs, ) @@ -135,7 +135,7 @@ def compare(counts, epochs): def test_edge_cases(self, counts, epochs, expected_kind): assert_outcome( _tsdate.fixed_changepoints, - rescaling._fixed_changepoints, + rescaling.fixed_changepoints, (np.asarray(counts, dtype=float), epochs), expected_kind, ) @@ -209,7 +209,7 @@ def test_edge_cases( args = (f64(*counts), f64(*offset), penalty, min_counts, min_offset) assert_outcome( _tsdate.poisson_changepoints, - rescaling._poisson_changepoints, + rescaling.poisson_changepoints, args, expected_kind, ) @@ -227,7 +227,7 @@ def test_random(self, seed, mode): args = (counts, offset, float(rng.choice([1.0, 50.0])), 10.0, 0.5) result = compare( _tsdate.poisson_changepoints, - rescaling._poisson_changepoints, + rescaling.poisson_changepoints, *args, ) # also the dtype, which `compare` ignores @@ -273,7 +273,7 @@ def test_random(self, seed, mode): class TestCountMutations: @staticmethod def compare(args): - return compare(_tsdate.count_mutations, rescaling._count_mutations, *args) + return compare(_tsdate.count_mutations, rescaling.count_mutations, *args) @pytest.mark.parametrize("size_biased", [False, True]) @pytest.mark.parametrize(("nodes", "edges", "mutations", "length"), COUNT_CASES) diff --git a/tests/test_oracle_util.py b/tests/test_oracle_util.py index adf703d2..e96fd71e 100644 --- a/tests/test_oracle_util.py +++ b/tests/test_oracle_util.py @@ -66,7 +66,7 @@ def sample_flags(ts): class TestSplitDisjointNodes: @staticmethod def compare(*args): - return compare(_tsdate.split_disjoint_nodes, util._split_disjoint_nodes, *args) + return compare(_tsdate.split_disjoint_nodes, util.split_disjoint_nodes, *args) @pytest.mark.parametrize( ("parent", "child", "left", "right", "excluded", "expected"), SPLIT_CASES @@ -99,9 +99,9 @@ def test_simulated(self, sim_ts): def relabel_args(ts): """ - Arguments of `_relabel_mutations_node`, with the nodes split as by `util` + Arguments of `relabel_mutations_node`, with the nodes split as by `util` """ - parent, child, order, _ = util._split_disjoint_nodes( + parent, child, order, _ = util.split_disjoint_nodes( ts.edges_parent, ts.edges_child, ts.edges_left, @@ -151,9 +151,7 @@ def relabel_args(ts): class TestRelabelMutationsNode: @staticmethod def compare(args): - return compare( - _tsdate.relabel_mutations_node, util._relabel_mutations_node, *args - ) + return compare(_tsdate.relabel_mutations_node, util.relabel_mutations_node, *args) @pytest.mark.parametrize( ("nodes", "edges", "mutations", "length", "expected_error"), RELABEL_CASES @@ -243,7 +241,7 @@ def args(times, fixed, parents, children, epsilon, max_iterations): @staticmethod def compare(args): - return compare(_tsdate.constrain_ages, util._constrain_ages, *args) + return compare(_tsdate.constrain_ages, util.constrain_ages, *args) @pytest.mark.parametrize("max_iterations", [0, 1, 1000]) @pytest.mark.parametrize("epsilon", [0.0, 1e-6, 0.5]) @@ -258,7 +256,7 @@ def test_edge_cases( self, times, fixed, parents, children, epsilon, max_iterations, kind ): args = self.args(times, fixed, parents, children, epsilon, max_iterations) - assert_outcome(_tsdate.constrain_ages, util._constrain_ages, args, kind) + assert_outcome(_tsdate.constrain_ages, util.constrain_ages, args, kind) @pytest.mark.parametrize( "args", @@ -362,7 +360,7 @@ class TestContainsUnaryNodes: def compare(ts, mask): return compare( _tsdate.contains_unary_nodes, - util._contains_unary_nodes, + util.contains_unary_nodes, mask, ts.edges_parent, ts.edges_left, diff --git a/tests/test_oracle_variational.py b/tests/test_oracle_variational.py index 2abd9f04..531105b6 100644 --- a/tests/test_oracle_variational.py +++ b/tests/test_oracle_variational.py @@ -1,11 +1,9 @@ """ Equivalence of the expectation propagation functions of ``_tsdate`` with the oracle of -``tsdate.variational``: the EP helpers (``_damp``, ``_rescale``, -``_rescale_factors``, ``_constraints_are_consistent``) and the passes +``tsdate.variational``: the EP helpers (``damp``, ``rescale``, +``rescale_factors``, ``constraints_are_consistent``) and the passes ``propagate_likelihood``, ``propagate_prior`` and ``propagate_mutations``, plus whole -sweeps. The ``c_*`` adapters give the C functions the signatures of the oracles: the -EP state stays in the numpy arrays of an oracle ``EPFactors``, which the C functions -take as a tuple and update in place. +sweeps. The EP state is a tuple of factor arrays, which the passes update in place. Inputs are snapshots of real EP state (``oracle.ep_state``) on the session fixtures, with constraints edited to force branches, one-edge snapshots for each branch, and @@ -52,108 +50,6 @@ ) -def factor_arrays(factors): - """ - The arrays of an ``EPFactors`` that the C functions take, as a tuple - """ - return ( - factors.node, - factors.edge, - factors.block, - factors.scale, - factors._p, - factors._c, - factors._j, - factors._k, - ) - - -def c_damp(x, y, s): - return _tsdate.damp(x[0], x[1], y[0], y[1], s) - - -def c_rescale(x, s): - return _tsdate.rescale(x[0], x[1], s) - - -def c_rescale_factors(factors): - _tsdate.rescale_factors(factor_arrays(factors)) - - -def c_assemble_factors(factors): - return _tsdate.assemble_factors(factor_arrays(factors)) - - -def c_propagate_likelihood( - edge_order, - edges_parent, - edges_child, - likelihoods, - constraints, - posterior, - factors, - lognorm, - max_shape, - min_step, - unphased, -): - _tsdate.propagate_likelihood( - edge_order, - edges_parent, - edges_child, - likelihoods, - constraints, - posterior, - factor_arrays(factors), - lognorm, - max_shape, - min_step, - unphased, - ) - - -def c_propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol): - _tsdate.propagate_prior( - free, posterior, factor_arrays(factors), max_shape, em_maxitt, em_reltol - ) - - -def c_propagate_mutations( - mutations_order, - mutations_posterior, - mutations_phase, - mutations_edge, - edges_parent, - edges_child, - likelihoods, - constraints, - posterior, - factors, - unphased, -): - _tsdate.propagate_mutations( - mutations_order, - mutations_posterior, - mutations_phase, - mutations_edge, - edges_parent, - edges_child, - likelihoods, - constraints, - posterior, - factor_arrays(factors), - unphased, - ) - - -# the C function and the oracle of the pass that each runner of ``ep_state`` calls -PASSES = { - ep_state.run_likelihood: (c_propagate_likelihood, variational.propagate_likelihood), - ep_state.run_prior: (c_propagate_prior, variational.propagate_prior), - ep_state.run_mutations: (c_propagate_mutations, variational.propagate_mutations), -} - - @pytest.fixture(scope="module") def snaps(small_ts, small_ts_unphased, small_ts_historical): """ @@ -181,18 +77,16 @@ def scaled_snap(snaps): ``small_ts`` after a likelihood pass with a small cap, so that scales are not 1 """ snap = snaps["small_ts"] - propagate = variational.propagate_likelihood - state = ep_state.run_likelihood(propagate, snap, False, max_shape=3.0) + state = ep_state.run_likelihood(variational, snap, False, max_shape=3.0) return snap.after_pass(state) def compare_runs(runner, snap, *args, **kwargs): """ - Run ``runner`` (an ``ep_state.run_*``) with the C function and with the oracle + Run ``runner`` (an ``ep_state.run_*``) with ``_tsdate`` and with the oracle """ - c_pass, oracle_pass = PASSES[runner] - actual = partial(runner, c_pass) - expected = partial(runner, oracle_pass) + actual = partial(runner, _tsdate) + expected = partial(runner, variational) return compare(actual, expected, snap, *args, **kwargs) @@ -217,28 +111,25 @@ def test_rescale_factors(self, snaps, ts_name, scale): snap.fields["scale"][:] = scale actual = snap.factors() expected = snap.factors() - c_rescale_factors(actual) - variational._rescale_factors(expected) - fields = ("node", "edge", "block", "scale") - assert_same_values( - [getattr(actual, f) for f in fields], [getattr(expected, f) for f in fields] - ) + _tsdate.rescale_factors(actual) + variational.rescale_factors(expected) + assert_same_values(actual[:4], expected[:4]) def test_rescale_factors_twice(self, snaps): # the scale is reset to 1, so a second call changes nothing snap = snaps["small_ts"] factors = snap.factors() - c_rescale_factors(factors) - once = [factors.node.copy(), factors.edge.copy(), factors.block.copy()] - c_rescale_factors(factors) - for before, after in zip(once, (factors.node, factors.edge, factors.block)): + _tsdate.rescale_factors(factors) + once = [f.copy() for f in factors[:3]] + _tsdate.rescale_factors(factors) + for before, after in zip(once, factors[:3]): assert np.array_equal(before, after) @pytest.mark.parametrize("ts_name", TS_NAMES) def test_assemble_factors(self, snaps, scaled_snap, ts_name): snap = scaled_snap if ts_name == "small_ts" else snaps[ts_name] - actual = c_assemble_factors(snap.factors()) - expected = variational._assemble_factors(snap.factors()) + actual = _tsdate.assemble_factors(snap.factors()) + expected = variational.assemble_factors(snap.factors()) assert_same_outcome(outcome(lambda: actual), outcome(lambda: expected)) @@ -309,7 +200,7 @@ def test_assemble_factors(self, snaps, scaled_snap, ts_name): # posterior. ("s_one_upper", f64(1, 1), 1.0, "finite"), ("s_one_lower", f64(-0.5, 1), 1.0, "finite"), - # asserts (reachable as for `_damp`) + # asserts (reachable as for `damp`) ("x0_minus_one", f64(-1, 1), 10.0, AssertionError), ("x0_nan", f64(NAN, 1), 10.0, AssertionError), ("x1_zero", f64(1, 0), 10.0, AssertionError), @@ -325,7 +216,7 @@ class TestDamp: [pytest.param(*row[1:], id=row[0]) for row in DAMP_TABLE], ) def test_table(self, x, y, s, expected_kind): - result = compare(c_damp, variational._damp, x, y, s) + result = compare(_tsdate.damp, variational.damp, *x, *y, s) assert kind(result) == expected_kind @pytest.mark.parametrize("seed", range(8)) @@ -334,16 +225,17 @@ def test_random(self, seed): x = f64(rng.uniform(-0.9, 30), log_uniform(rng, -4, -1)) y = f64(rng.uniform(-5, 30), log_uniform(rng, -4, -1)) s = float(rng.uniform(0.05, 0.95)) - compare(c_damp, variational._damp, x, y, s) + compare(_tsdate.damp, variational.damp, *x, *y, s) @pytest.mark.parametrize("which", [0, 1]) def test_infinite_posterior_zero_message(self, which): - # C reports the division of inf by 0.0; the oracle returns d = 1. Needs - # an infinite posterior, which is unreachable without a prior failure. + # C reports the division of inf by 0.0; the oracle, on the NumPy scalars of + # the passes, returns d = 1. Needs an infinite posterior, which is + # unreachable without a prior failure. x = f64(1, 1) x[which] = INF with pytest.raises(expected_error(ZeroDivisionError)): - c_damp(x, f64(0, 0), 0.5) + _tsdate.damp(*x, 0.0, 0.0, 0.5) class TestRescale: @@ -352,7 +244,7 @@ class TestRescale: [pytest.param(*row[1:], id=row[0]) for row in RESCALE_TABLE], ) def test_table(self, x, s, expected_kind): - result = compare(c_rescale, variational._rescale, x, s) + result = compare(_tsdate.rescale, variational.rescale, *x, s) assert kind(result) == expected_kind @pytest.mark.parametrize("seed", range(8)) @@ -360,13 +252,13 @@ def test_random(self, seed): rng = np.random.default_rng(seed) x = f64(rng.uniform(-0.9, 3000), log_uniform(rng, -4, -1)) s = float(rng.choice([10.0, 100.0, 1000.0])) - compare(c_rescale, variational._rescale, x, s) + compare(_tsdate.rescale, variational.rescale, *x, s) def test_zero_shape_offset_cap_below_one(self): - # C reports the division by zero; the oracle returns -inf. Direct - # call only: `propagate_*` assert `max_shape >= 1`. + # C reports the division by zero; the oracle, on NumPy scalars, returns + # -inf. Direct call only: `propagate_*` assert `max_shape >= 1`. with pytest.raises(expected_error(ZeroDivisionError)): - c_rescale(f64(0, 1), 0.5) + _tsdate.rescale(0.0, 1.0, 0.5) class TestConstraintsAreConsistent: @@ -378,7 +270,7 @@ def check(constraints, parents, children, valid): np.array(children, dtype=np.int32), ) func = _tsdate.constraints_are_consistent - result = compare(func, variational._constraints_are_consistent, *args) + result = compare(func, variational.constraints_are_consistent, *args) assert result.value is valid @pytest.mark.parametrize( @@ -460,9 +352,7 @@ def test_single_edge(self, branch, case): # `sideways_moments` divides by zero for an astronomically large mutation # target: C reports it where the oracle returns NaN and skips. with pytest.raises(expected_error(ZeroDivisionError)): - ep_state.run_likelihood( - c_propagate_likelihood, snap, snap.unphased, **kwargs - ) + ep_state.run_likelihood(_tsdate, snap, snap.unphased, **kwargs) else: compare_runs(ep_state.run_likelihood, snap, snap.unphased, **kwargs) @@ -572,7 +462,7 @@ def test_min_step(self, snaps, ts_name, min_step): @pytest.mark.parametrize("multiplier", [1e12, 1e300], ids=lambda v: f"y*{v:g}") def test_extreme_counts(self, snaps, multiplier): # 1e12: projection failures are skipped (NaN lognorm). 1e300: a posterior - # becomes NaN and the next `_damp` asserts `0 < x[0] + 1`, + # becomes NaN and the next `damp` asserts `0 < x[0] + 1`, # reachable from real data (~1e300 mutations on an edge). snap = snaps["small_ts"] likelihoods = snap.edge_likelihoods * [multiplier, 1.0] @@ -632,8 +522,8 @@ def test_shape_mismatches(self, snaps, change): parents, children = parents[:-1], children[:-1] likelihoods = likelihoods[:-1] - def call(propagate_likelihood): - propagate_likelihood( + def call(module): + module.propagate_likelihood( order, parents, children, @@ -648,15 +538,15 @@ def call(propagate_likelihood): ) result = compare( - lambda: call(c_propagate_likelihood), - lambda: call(variational.propagate_likelihood), + lambda: call(_tsdate), + lambda: call(variational), ) assert kind(result) is AssertionError class TestPropagateLikelihoodTinyScale: """ - `propagate_likelihood` calls `_rescale_factors` (mid-pass) whenever the scale of + `propagate_likelihood` calls `rescale_factors` (mid-pass) whenever the scale of either node of the next edge is below `TINY` (strict), even if the edge is skipped because both nodes are fixed. """ @@ -839,15 +729,12 @@ def test_penalty_assert_reachable_from_ep(self, fresh): base = fresh["small_ts"].copy() base.edge_likelihoods = base.edge_likelihoods * [1.0, 1e300] - def run(propagate_likelihood, propagate_prior): - state = ep_state.run_likelihood(propagate_likelihood, base, False) + def run(module): + state = ep_state.run_likelihood(module, base, False) step = base.after_pass(state) - return ep_state.run_prior(propagate_prior, step, step.unconstrained_roots) + return ep_state.run_prior(module, step, step.unconstrained_roots) - result = compare( - lambda: run(c_propagate_likelihood, c_propagate_prior), - lambda: run(variational.propagate_likelihood, variational.propagate_prior), - ) + result = compare(lambda: run(_tsdate), lambda: run(variational)) assert kind(result) is AssertionError @@ -913,7 +800,7 @@ def test_single_edge(self, branch, case): # as in propagate_likelihood: C reports a division by zero in # `*_sideways_moments` with pytest.raises(expected_error(ZeroDivisionError)): - ep_state.run_mutations(c_propagate_mutations, snap, snap.unphased) + ep_state.run_mutations(_tsdate, snap, snap.unphased) else: compare_runs(ep_state.run_mutations, snap, snap.unphased) @@ -973,24 +860,8 @@ def test_sweeps(self, fresh, case): name, kwargs = self.CASES[case] snap = fresh[name] sweeps = 4 - actual = ep_state.run_sweeps( - c_propagate_likelihood, - c_propagate_prior, - c_propagate_mutations, - c_rescale_factors, - snap, - sweeps, - **kwargs, - ) - expected = ep_state.run_sweeps( - variational.propagate_likelihood, - variational.propagate_prior, - variational.propagate_mutations, - variational._rescale_factors, - snap, - sweeps, - **kwargs, - ) + actual = ep_state.run_sweeps(_tsdate, snap, sweeps, **kwargs) + expected = ep_state.run_sweeps(variational, snap, sweeps, **kwargs) for a, e in zip(actual[0], expected[0]): for x, y in zip(a, e): # node posterior, edge and block lognorm np.testing.assert_array_equal(x, y) From 6d766359a582eaef8842c49681bff68d877f4715 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 12:34:33 -0800 Subject: [PATCH 33/56] Remove tautological and redundant tests - message tests that rerun a parity-table row and check only the oracle's message (zero edge span, breakpoints, the KL failure messages) - the comparison of the hyp2f1 unity limit with a copy of the oracle's formula - input-not-modified tests, which compare already checks on the copied arguments - the comparison of _tsdate.block_singletons with the wrapper that calls it, and checks of the oracle's dtypes, shapes and messages - a duplicate in-place test of reallocate_unphased, and a C test of tsd_bug_assert(1 + 1 == 2) The SciPy-free import test compares with gammainc_inv in the test process rather than with SciPy, whose result depends on its build. The C tests' description allows coarse sanity checks of results. --- lib/tests/tests.c | 12 +++--------- tests/test_oracle_approx.py | 22 ---------------------- tests/test_oracle_hypergeo.py | 28 ++-------------------------- tests/test_oracle_phasing.py | 12 +++++------- tests/test_oracle_prior.py | 13 ++----------- tests/test_oracle_rescaling.py | 32 ++++++++------------------------ tests/test_oracle_util.py | 18 ++++-------------- tests/test_oracle_variational.py | 1 - tests/test_python_c_scalar.py | 3 +-- tests/test_python_c_tables.py | 5 ----- 10 files changed, 25 insertions(+), 121 deletions(-) diff --git a/lib/tests/tests.c b/lib/tests/tests.c index 02ae5260..b505689e 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -23,8 +23,9 @@ */ /* - * Smoke tests for the low-level tsdate API. These check return codes and - * memory handling only; numerical correctness is tested from Python. + * Smoke tests for the low-level tsdate API: return codes, error paths and memory + * handling, with coarse sanity checks of results (finite, NaN, simple values). + * Numerical correctness is tested from Python. */ #include @@ -106,12 +107,6 @@ test_safe_free(void) CU_ASSERT_PTR_NULL(x); } -static void -test_bug_assert_passes(void) -{ - tsd_bug_assert(1 + 1 == 2); -} - static void test_polygamma(void) { @@ -1442,7 +1437,6 @@ main(int argc, char **argv) { "test_strerror_unknown", test_strerror_unknown }, { "test_trace_error", test_trace_error }, { "test_safe_free", test_safe_free }, - { "test_bug_assert_passes", test_bug_assert_passes }, { "test_polygamma", test_polygamma }, { "test_polygamma_poles", test_polygamma_poles }, { "test_betaln", test_betaln }, diff --git a/tests/test_oracle_approx.py b/tests/test_oracle_approx.py index e369c752..ccd15fcf 100644 --- a/tests/test_oracle_approx.py +++ b/tests/test_oracle_approx.py @@ -28,7 +28,6 @@ NAN, assert_outcome, compare, - expected_error, kind, log_uniform, outcome, @@ -343,17 +342,6 @@ class TestGammaApproximations: def test_domain(self, name, args, expected): parity(name, args, expected) - @pytest.mark.parametrize( - ("name", "args", "expected"), - [p for p in GAMMA_DOMAIN if p.values[2] is KLMinimizationFailedError], - ) - def test_error_messages(self, name, args, expected): - # the messages distinguish the failure modes - func = getattr(_tsdate, name) - with pytest.raises(expected_error(KLMinimizationFailedError)): - func(*args) - compare(func, getattr(approx, name), *args) - @pytest.mark.parametrize("gap", [1e-17, 1e-10, 4e-5, 4.99e-5, 5e-5, 6e-5, 1e-3]) def test_kl_asymptotic_threshold(self, gap): # for alpha > 1e4 (gap < 5e-5) the lower bound alpha = 0.5 / gap is returned @@ -648,16 +636,6 @@ def test_regimes(self, name, label): moments = PROJECTIONS[name][0] check_projection(name, floats(REGIMES[moments][label])) - @pytest.mark.parametrize("name", list(PROJECTIONS)) - def test_inputs_are_not_modified(self, name): - moments = PROJECTIONS[name][0] - first_regime = next(iter(REGIMES[moments].values())) - proj_args = projection_args(name, floats(first_regime)) - copies = list(proj_args) - func = getattr(_tsdate, name) - func(*proj_args) - assert list(proj_args) == copies - def test_unphased_probability_out_of_range(self): # NOTE: current behaviour, possibly a bug: the Laplace # approximation can give a probability above one for finite mean and variance, diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index 4fc6e381..10b95d87 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -15,12 +15,10 @@ import pytest import scipy.special from oracle import hypergeo -from oracle._libm import lgamma, log from oracle.helpers import ( INF, NAN, assert_outcome, - assert_same_values, compare, log_uniform, ) @@ -467,27 +465,6 @@ def laplace_grid(name): } -def unity_formula(a, b, c, z): - """ - The result of `hyp2f1_laplace` in the unity limit, written out. See DLMF 15.4: - the sign of ``g = c - a - b`` selects the limit, and negative ``z`` is mapped to - ``z / (z - 1)`` close to one by Pfaff's transformation. - """ - s = 0.0 - if z < 0.0: - s = -b * log(1 - z) - a = c - a - z = z / (z - 1) - g = c - a - b - if g < 0.0: - value = lgamma(c) + lgamma(-g) - lgamma(a) - lgamma(b) + g * log(1 - z) - elif g > 0.0: - value = lgamma(c) + lgamma(g) - lgamma(c - a) - lgamma(c - b) - else: - value = log(-log(1 - z)) + lgamma(a + b) - lgamma(a) - lgamma(b) - return s + value - - def unity_threshold(): """ Largest ``x < 1`` for which ``np.isclose(x, 1.0)`` fails, and the next one up @@ -580,11 +557,10 @@ class TestHyp2f1Unity: @pytest.mark.parametrize("args", UNITY_CASES, ids=repr) def test_unity_branches(self, args): - a, b, c, z = args + z = args[3] mapped = z / (z - 1) if z < 0 else z assert np.isclose(mapped, 1.0), "case must take the unity branch" - result = parity("hyp2f1_laplace", args) - assert_same_values(result.value, unity_formula(a, b, c, z)) + parity("hyp2f1_laplace", args) @pytest.mark.parametrize("sign", ["positive", "negative"]) @pytest.mark.parametrize("side", ["not_close", "close"]) diff --git a/tests/test_oracle_phasing.py b/tests/test_oracle_phasing.py index d4179b72..5e163bc5 100644 --- a/tests/test_oracle_phasing.py +++ b/tests/test_oracle_phasing.py @@ -9,7 +9,7 @@ import pytest import tskit from oracle import phasing -from oracle.helpers import INF, NAN, assert_same_values, compare, make_ts, shrink +from oracle.helpers import INF, NAN, compare, make_ts, shrink from tsdate.phasing import block_singletons from tsdate.rescaling import count_mutations @@ -146,12 +146,10 @@ def test_random(self, small_ts_unphased, seed, fraction): rng = np.random.default_rng(seed) unphased = rng.random(ts.num_individuals) < fraction args = self.args(ts, unphased) - result = self.compare(args) - # also the dtypes, which `compare` ignores, and the public wrapper + self.compare(args) + # also the dtypes, which `compare` ignores actual = _tsdate.block_singletons(*args) assert actual[1].dtype == actual[2].dtype == np.int32 - assert_same_values(actual, block_singletons(ts, unphased)) - assert result.value[1].dtype == np.int32 @pytest.fixture(scope="module") @@ -388,7 +386,7 @@ def test_random(self, small_ts, seed, num_sets): for _ in range(num_sets) ] nodes_sample = self.nodes_sample(ts, members) - result = self.compare(nodes_sample, sweep_args(ts)) + self.compare(nodes_sample, sweep_args(ts)) # also the dtype, which `compare` ignores actual = _tsdate.mutation_frequency(nodes_sample, *sweep_args(ts)) - assert actual.dtype == result.value.dtype == np.int32 + assert actual.dtype == np.int32 diff --git a/tests/test_oracle_prior.py b/tests/test_oracle_prior.py index b2d48800..854f8de5 100644 --- a/tests/test_oracle_prior.py +++ b/tests/test_oracle_prior.py @@ -46,12 +46,11 @@ class TestMarginalizeOverAncestors: def test_random(self, seed, num_tips): rng = np.random.default_rng(seed) val = rng.uniform(0.1, 10.0, (num_tips, 2)) - result = compare( + compare( _tsdate.marginalize_over_ancestors, prior.marginalize_over_ancestors, val, ) - assert result.value.shape == (num_tips + 1, 2) @pytest.mark.parametrize("num_columns", [1, 3]) def test_number_of_moments(self, num_columns): @@ -79,23 +78,15 @@ def test_edge_cases(self, val, expected_kind): expected_kind, ) - def test_input_not_modified(self): - # `compare` passes copies, so call directly - val = np.random.default_rng(0).uniform(0.1, 10.0, (8, 2)) - copy = val.copy() - _tsdate.marginalize_over_ancestors(val) - assert np.array_equal(val, copy) - class TestConditionalCoalescentVariance: @pytest.mark.parametrize("num_tips", [2, 3, 5, 20, 100, 250]) def test_variance(self, num_tips): - result = compare( + compare( _tsdate.conditional_coalescent_variance, prior.conditional_coalescent_variance, num_tips, ) - assert result.value.shape == (num_tips + 1,) class TestSingleTip: diff --git a/tests/test_oracle_rescaling.py b/tests/test_oracle_rescaling.py index e96a7c33..e0824c71 100644 --- a/tests/test_oracle_rescaling.py +++ b/tests/test_oracle_rescaling.py @@ -151,10 +151,10 @@ def test_random(self, seed, mode): counts *= rng.random(size) < 0.6 counts[0] += 1.0 epochs = int(rng.integers(1, 120)) - result = self.compare(counts, epochs) + self.compare(counts, epochs) # also the dtype, which `compare` ignores actual = _tsdate.fixed_changepoints(counts, epochs) - assert actual.dtype == result.value.dtype == np.int32 + assert actual.dtype == np.int32 COUNTS = [5.0, 6.0, 20.0, 22.0, 21.0, 3.0] @@ -225,14 +225,14 @@ def test_random(self, seed, mode): else: counts, offset = piecewise_rates(rng, size, 4, (0.2, 3.0), (0.2, 30.0)) args = (counts, offset, float(rng.choice([1.0, 50.0])), 10.0, 0.5) - result = compare( + compare( _tsdate.poisson_changepoints, rescaling.poisson_changepoints, *args, ) # also the dtype, which `compare` ignores actual = _tsdate.poisson_changepoints(*args) - assert actual.dtype == result.value.dtype == np.int32 + assert actual.dtype == np.int32 COUNT_NODES = [(1, 0), (1, 0), (0, 1)] @@ -313,10 +313,10 @@ def test_size_mismatch(self, index, size): @pytest.mark.parametrize("size_biased", [False, True]) def test_simulated(self, sim_ts, size_biased): args = count_args(sim_ts, size_biased) - result = self.compare(args) + self.compare(args) # also the dtype, which `compare` ignores actual = _tsdate.count_mutations(*args) - assert actual[1].dtype == result.value[1].dtype == np.int32 + assert actual[1].dtype == np.int32 def area_args(nodes_time, likelihoods, parents, children): @@ -398,10 +398,10 @@ def test_random(self, sim_ts, seed): times[ts.samples()] = ts.nodes_time[ts.samples()] likelihoods = rng.uniform(0, 5, (ts.num_edges, 2)) args = (times, likelihoods, ts.edges_parent, ts.edges_child) - result = self.compare(*args) + self.compare(*args) # also the dtype, which `compare` ignores actual = _tsdate.mutational_area(*args) - assert actual[3].dtype == result.value[3].dtype == np.int32 + assert actual[3].dtype == np.int32 def test_simulated(self, ep): nodes_time, likelihoods, _, parents, children = rescale_inputs(ep) @@ -518,12 +518,6 @@ def test_edge_cases(self, args, expected): expected, ) - def test_zero_edge_span_message(self): - # the message is compared as well as the type - args = timescale_args([0, 0, 1.0], [[2, 0], [1, 0]], [1, 1, 0], [2, 2], [0, 1], 1) - result = self.compare(*args) - assert "Zero edge span in interval" in str(result.exception) - @pytest.mark.parametrize("which", ["fixed", "parents", "likelihood_rows", "columns"]) def test_size_mismatch(self, which): args = list(chain(2)) @@ -625,16 +619,6 @@ def test_edge_cases(self, estimate, fixed, original, rescaled, expected_kind): expected_kind, ) - def test_breaks_message(self): - # the message names the offending option, and is compared as well as the type - args = (f64(0.5), b1(0), f64(0.0, 1.0, 1.0), f64(0.0, 2.0, 3.0)) - result = compare( - _tsdate.piecewise_scale_point_estimate, - rescaling.piecewise_scale_point_estimate, - *args, - ) - assert BREAKS_MSG in str(result.exception) - @pytest.mark.parametrize("seed", range(3)) def test_random(self, seed): rng = np.random.default_rng(seed) diff --git a/tests/test_oracle_util.py b/tests/test_oracle_util.py index e96fd71e..1bd599ec 100644 --- a/tests/test_oracle_util.py +++ b/tests/test_oracle_util.py @@ -91,10 +91,10 @@ def test_simulated(self, sim_ts): ts.edges_right, sample_flags(ts), ) - result = self.compare(*args) + self.compare(*args) # also the dtypes, which `compare` ignores actual = _tsdate.split_disjoint_nodes(*args) - assert all(a.dtype == e.dtype == np.int32 for a, e in zip(actual, result.value)) + assert all(a.dtype == np.int32 for a in actual) def relabel_args(ts): @@ -177,10 +177,10 @@ def test_size_mismatch(self, index, size): def test_simulated(self, sim_ts): args = relabel_args(sim_ts) - result = self.compare(args) + self.compare(args) # also the dtype, which `compare` ignores actual = _tsdate.relabel_mutations_node(*args) - assert actual.dtype == result.value.dtype == np.int32 + assert actual.dtype == np.int32 # times, fixed, parents, children, epsilon, max_iterations, outcome category @@ -269,16 +269,6 @@ def test_size_mismatch(self, args): result = self.compare(self.args(*args, 0.1, 3)) assert result.error is AssertionError - def test_input_not_modified(self): - # `compare` passes copies, so call directly - times = f64(*VIOLATED[0]) - copy = times.copy() - out = _tsdate.constrain_ages( - times, b1(*VIOLATED[1]), i32(2, 3), i32(0, 2), 1e-6, 5 - ) - assert np.array_equal(times, copy) - assert out is not times - @pytest.mark.parametrize("mode", ["iterated", "forced"]) @pytest.mark.parametrize("seed", range(2)) def test_simulated(self, sim_ts, seed, mode): diff --git a/tests/test_oracle_variational.py b/tests/test_oracle_variational.py index 531105b6..34fd7267 100644 --- a/tests/test_oracle_variational.py +++ b/tests/test_oracle_variational.py @@ -362,7 +362,6 @@ def test_twin_edge_in_phased_pass(self): snap = tiny_snapshot("twin") result = compare_runs(ep_state.run_likelihood, snap, False) assert kind(result) is AssertionError - assert str(result.exception) == "Invalid update" class TestPropagateLikelihood: diff --git a/tests/test_python_c_scalar.py b/tests/test_python_c_scalar.py index b0691533..3633afef 100644 --- a/tests/test_python_c_scalar.py +++ b/tests/test_python_c_scalar.py @@ -10,7 +10,6 @@ import _tsdate import pytest -import scipy.special SCALAR_FUNCTIONS = { # name: (number of arguments, number of results, valid arguments) @@ -93,4 +92,4 @@ def test_import_without_scipy(self): [sys.executable, "-c", code], capture_output=True, text=True ) assert result.returncode == 0, result.stderr - assert float(result.stdout) == scipy.special.gammaincinv(2.0, 0.5) + assert float(result.stdout) == _tsdate.gammainc_inv(2.0, 0.5) diff --git a/tests/test_python_c_tables.py b/tests/test_python_c_tables.py index de56d3fb..176965e5 100644 --- a/tests/test_python_c_tables.py +++ b/tests/test_python_c_tables.py @@ -67,11 +67,6 @@ def test_edge_out_of_range(self): with pytest.raises(_tsdate.LibraryError, match="out of range"): self.call(np.ones((2, 2)), [0.5], [0], [[0, 7]]) - def test_updates_in_place(self): - likelihood = np.array([[1.0, 5.0], [0.0, 5.0]]) - self.call(likelihood, [0.25], [0], [[0, 1]]) - assert likelihood[:, 0].tolist() == [0.25, 0.75] - def test_columns(self): with pytest.raises(ValueError, match="two columns"): self.call(np.ones((2, 3)), [0.5], [0], [[0, 1]]) From 3394bf7b8c0b570aaa2699a6726dd53cbfc8c96f Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 12:47:23 -0800 Subject: [PATCH 34/56] Raise the library's errors in the oracles The oracles raise the errors of the C library in its terms: a _tsdate.LibraryError with the message of the error code that the library returns at that point (oracle/errors.py mirrors lib/err.h), and the ValueError of the module's argument checks with its message. Internal invariants stay plain asserts, and a ZeroDivisionError stands for TSD_ERR_ZERO_DIVISION. The equivalence tests compare the type and message of every exception, so that the error codes are compared; the edge-case tables name the expected error code. The helpers' translation of oracle exceptions is gone, as are the module tests that only repeated an oracle row with a message check. --- tests/oracle/__init__.py | 10 +- tests/oracle/approx.py | 52 +++++------ tests/oracle/errors.py | 61 ++++++++++++ tests/oracle/helpers.py | 71 +++++--------- tests/oracle/hypergeo.py | 29 +++--- tests/oracle/phasing.py | 54 ++++++++--- tests/oracle/rescaling.py | 96 +++++++++---------- tests/oracle/util.py | 42 +++++++-- tests/oracle/variational.py | 101 +++++++++++++------- tests/test_oracle_approx.py | 91 +++++++++--------- tests/test_oracle_helpers.py | 69 +++++++++++--- tests/test_oracle_hypergeo.py | 104 ++++++++++----------- tests/test_oracle_phasing.py | 34 ++++--- tests/test_oracle_rescaling.py | 153 +++++++++++++++++++++++-------- tests/test_oracle_util.py | 31 +++++-- tests/test_oracle_variational.py | 153 +++++++++++++++++-------------- tests/test_python_c_approx.py | 10 +- tests/test_python_c_rescaling.py | 29 +----- tests/test_python_c_scalar.py | 17 +--- tests/test_python_c_tables.py | 21 ----- 20 files changed, 729 insertions(+), 499 deletions(-) create mode 100644 tests/oracle/errors.py diff --git a/tests/oracle/__init__.py b/tests/oracle/__init__.py index 1741874a..b6b18706 100644 --- a/tests/oracle/__init__.py +++ b/tests/oracle/__init__.py @@ -15,7 +15,15 @@ compensation, once in the module header where it applies throughout. * Oracles call other oracles, never ``_tsdate``, except for ``gammaincinv`` (``hypergeo.gammainc_inv``), which they take from the C library as they take libm, - and which is compared with SciPy instead. + and which is compared with SciPy instead, and the messages of the library's error + codes (``errors``, as ``_tsdate.strerror`` gives them). +* Oracles raise errors in the library's terms: where the C library returns an error + code, the oracle raises ``errors.library_error(code)``, the ``_tsdate.LibraryError`` + with that code's message; for the shapes and sizes of arrays that ``_tsdate`` + checks, the oracle raises ``ValueError`` with its message. The equivalence tests + compare the type and message of the exceptions. A ``ZeroDivisionError`` (from a + Python float division) stands for the library's ``TSD_ERR_ZERO_DIVISION``. Internal + invariants, which the library does not report, are plain ``assert`` statements. * Names, arguments and results are those of ``_tsdate``'s functions: the same argument lists, and results of the same types and layout (floats where ``_tsdate`` returns floats, the same tuples). The EP state is the tuple of factor arrays that diff --git a/tests/oracle/approx.py b/tests/oracle/approx.py index 899f6062..a1c0bacc 100644 --- a/tests/oracle/approx.py +++ b/tests/oracle/approx.py @@ -6,7 +6,7 @@ import numpy as np -from . import hypergeo +from . import errors, hypergeo # Plain `math` raises on log(0), exp overflow etc., where C gives -inf, inf or # nan; `_libm` gives the C results. @@ -20,16 +20,13 @@ # For the same reason, elements unpacked from a NumPy array are converted with # `float`. from ._libm import exp, ipow, lgamma, log +from .errors import library_error # the tolerances of the KL minimisation, as in the library _KLMIN_MAXITT = 100 _KLMIN_RELTOL = np.sqrt(np.finfo(np.float64).eps) -class KLMinimizationFailedError(Exception): - pass - - def approximate_log_moments(mean, variance): """ Approximate log moments via a second-order Taylor series expansion around @@ -39,8 +36,8 @@ def approximate_log_moments(mean, variance): Returns approximations to E[log x], E[x log x], E[(log x)^2] """ - assert mean > 0 - assert variance > 0 + if not (mean > 0 and variance > 0): + raise library_error(errors.NONPOSITIVE_MOMENTS) logx = log(mean) - 0.5 * variance / ipow(mean, 2) xlogx = mean * log(mean) + 0.5 * variance / mean logx2 = ipow(log(mean), 2) + (1 - log(mean)) * variance / ipow(mean, 2) @@ -57,11 +54,9 @@ def approximate_gamma_kl(x, logx): Returns the shape and rate of the approximating gamma. """ if x <= 0.0 or np.isinf(logx): - raise KLMinimizationFailedError("Nonpositive or nonfinite moments") + raise library_error(errors.NONPOSITIVE_OR_NONFINITE_MOMENTS) if not log(x) > logx: - raise KLMinimizationFailedError( - "log E[t] <= E[log t] violates Jensen's inequality" - ) + raise library_error(errors.JENSEN_VIOLATION) alpha = 0.5 / (log(x) - logx) # lower bound on alpha # asymptotically the lower bound becomes sharp if 1.0 / alpha < 1e-4: @@ -72,15 +67,13 @@ def approximate_gamma_kl(x, logx): # some small value (e.g. square root of machine precision) while np.abs(delta) > np.abs(alpha) * _KLMIN_RELTOL: if itt > _KLMIN_MAXITT: - raise KLMinimizationFailedError( - "Maximum iterations reached in KL minimization" - ) + raise library_error(errors.KL_MAX_ITERATIONS) delta = hypergeo.digamma(alpha) - log(alpha) + log(x) - logx delta /= hypergeo.trigamma(alpha) - 1 / alpha alpha -= delta itt += 1 if not np.isfinite(alpha) or alpha <= 0: - raise KLMinimizationFailedError("Invalid shape parameter in KL minimization") + raise library_error(errors.KL_INVALID_SHAPE) return alpha - 1.0, alpha / x @@ -90,7 +83,7 @@ def approximate_gamma_mom(mean, variance): same mean and variance, returning natural parameters """ if not (mean > 0.0 and variance > 0.0): - raise KLMinimizationFailedError("Nonpositive central moments") + raise library_error(errors.NONPOSITIVE_CENTRAL_MOMENTS) shape = ipow(mean, 2) / variance rate = mean / variance return shape - 1.0, rate @@ -108,7 +101,7 @@ def upper_bound(q, x): # cap shape parameter if x2 == x1: return upper_bound(q1, x1) if not (q2 > q1 and x2 > x1): - raise KLMinimizationFailedError("Quantiles must be sorted") + raise library_error(errors.UNSORTED_QUANTILES) alpha = log(q2 / q1) / log(x2 / x1) # lower bound if alpha > max_shape: return upper_bound(q1, x1) @@ -118,9 +111,7 @@ def upper_bound(q, x): # cap shape parameter itt = 0 while abs(delta) > abs(alpha) * _KLMIN_RELTOL: if itt > _KLMIN_MAXITT: - raise KLMinimizationFailedError( - "Maximum iterations reached in quantile matching" - ) + raise library_error(errors.QUANTILE_MAX_ITERATIONS) y1 = hypergeo.gammainc_inv(alpha, q1) y2 = hypergeo.gammainc_inv(alpha, q2) obj = y2 / y1 - x2 / x1 @@ -135,7 +126,7 @@ def upper_bound(q, x): # cap shape parameter itt += 1 if not alpha > 0: - raise KLMinimizationFailedError("Negative shape parameter") + raise library_error(errors.NEGATIVE_SHAPE) if alpha > max_shape: return upper_bound(q1, x1) beta = hypergeo.gammainc_inv(alpha, q1) / x1 @@ -148,7 +139,8 @@ def average_gammas(alpha, beta): statistics so as to get a "global" gamma, returning natural parameters """ - assert alpha.size == beta.size, "Array sizes are not equal" + if alpha.size != beta.size: + raise ValueError("Array sizes are not equal") avg_x = 0.0 avg_logx = 0.0 for shape, rate in zip(map(float, alpha + 1.0), map(float, beta)): @@ -268,7 +260,8 @@ def rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): Returns normalizing constant, E[t_i], V[t_i]. """ - assert t_j >= 0.0 + if not (t_j >= 0.0): + raise library_error(errors.INVALID_FIXED_AGE) s = a_i + y_ij r = mu_ij + b_i @@ -309,7 +302,8 @@ def leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): Returns normalizing constant, E[t_j], V[t_j]. """ - assert t_i > 0.0 + if not (t_i > 0.0): + raise library_error(errors.INVALID_FIXED_AGE) a = a_j b = a_j + y_ij + 1 @@ -399,7 +393,8 @@ def sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): Returns normalizing constant, E[t_j], V[t_j]. """ - assert t_i > 0.0 + if not (t_i > 0.0): + raise library_error(errors.INVALID_FIXED_AGE) a = a_j b = a_j + y_ij + 1 @@ -577,7 +572,8 @@ def mutation_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): Returns P[m under i], E[t_m], V[t_m]. """ - assert t_i > 0 + if not (t_i > 0): + raise library_error(errors.INVALID_FIXED_AGE) # Conditioning on ages of parents: # P[x under i | t_i, t_j] = t_i / (t_i + t_j) @@ -640,8 +636,8 @@ def mutation_block_moments(t_i, t_j): Returns P[m under i], E[t_m], V[t_m]. """ - assert t_i > 0 - assert t_j > 0 + if not (t_i > 0 and t_j > 0): + raise library_error(errors.INVALID_FIXED_AGE) pr_m = t_i / (t_i + t_j) mn_m = pr_m * t_i / 2 + (1 - pr_m) * t_j / 2 diff --git a/tests/oracle/errors.py b/tests/oracle/errors.py new file mode 100644 index 00000000..a0e08f5a --- /dev/null +++ b/tests/oracle/errors.py @@ -0,0 +1,61 @@ +""" +The error codes of the C library (``lib/err.h``, without the ``TSD_ERR_`` prefix), +and the exceptions with which ``_tsdate`` reports them. +""" + +import _tsdate + +GENERIC = -1 +NO_MEMORY = -2 +BAD_PARAM = -3 +ZERO_DIVISION = -4 +INVALID_HYPERGEO = -5 +NONPOSITIVE_OR_NONFINITE_MOMENTS = -6 +JENSEN_VIOLATION = -7 +KL_MAX_ITERATIONS = -8 +KL_INVALID_SHAPE = -9 +NONPOSITIVE_CENTRAL_MOMENTS = -10 +UNSORTED_QUANTILES = -11 +QUANTILE_MAX_ITERATIONS = -12 +NEGATIVE_SHAPE = -13 +NONPOSITIVE_MOMENTS = -14 +INVALID_FIXED_AGE = -15 +UNPHASED_INDIVIDUAL_EDGES = -16 +BLOCK_OUT_OF_RANGE = -17 +PHASE_OUT_OF_RANGE = -18 +UNPHASED_LIKELIHOOD_NOT_CONSERVED = -19 +MUTATION_NODE_NOT_IN_TREE = -20 +FIXED_NODES_VIOLATE_CONSTRAINT = -21 +NONPOSITIVE_INTERVALS = -22 +NEGATIVE_CHANGEPOINT_PARAMETER = -23 +ZERO_EDGE_SPAN = -24 +NON_INCREASING_BREAKPOINTS = -25 +INVALID_QUANTILE_WIDTH = -26 +INVALID_POSTERIOR = -27 +TIME_BELOW_FIRST_BREAKPOINT = -28 +NO_POSTERIORS = -29 +INVALID_MAX_SHAPE = -30 +INVALID_MIN_STEP = -31 +INVALID_NODE_POSTERIOR = -32 +INVALID_DAMPING = -33 +TWIN_EDGE_IN_PHASED_PASS = -34 +NONPOSITIVE_PENALTY = -35 + +CODES = range(NONPOSITIVE_PENALTY, 0) + + +def library_error(code): + """ + The exception with which ``_tsdate`` reports error ``code``. + """ + message = _tsdate.strerror(code) + return _tsdate.LibraryError(message) + + +def code_of(exception): + """ + The error code of a ``_tsdate.LibraryError``, from its message. + """ + message = str(exception) + (code,) = [code for code in CODES if _tsdate.strerror(code) == message] + return code diff --git a/tests/oracle/helpers.py b/tests/oracle/helpers.py index be7a404c..235ff6e9 100644 --- a/tests/oracle/helpers.py +++ b/tests/oracle/helpers.py @@ -6,6 +6,9 @@ import tskit from _tsdate import LibraryError +from . import errors +from .errors import library_error + def _flatten(x, path=""): """ @@ -49,30 +52,6 @@ def log_uniform(rng, lo, hi, size=None): return float(x) if size is None else x -# Exceptions of the oracle that the C library reports as a LibraryError. -_LIBRARY_ERROR_NAMES = ( - "ZeroDivisionError", - "AssertionError", - "KLMinimizationFailedError", - "ValueError", -) - - -def expected_error(exc_type): - """ - The exceptions an implementation may raise where the oracle raises ``exc_type`` - (``ZeroDivisionError``, ``AssertionError``, ...), for ``pytest.raises``. The C - library reports these as ``_tsdate.LibraryError``, and its argument checks raise - ``ValueError`` where the oracle asserts on array shapes and sizes. - """ - allowed = (exc_type,) - if exc_type.__name__ in _LIBRARY_ERROR_NAMES: - allowed += (LibraryError,) - if exc_type is AssertionError: - allowed += (ValueError,) - return allowed - - class Outcome: """ What calling a function did: ``value`` (its return value) or ``exception``, and @@ -86,7 +65,15 @@ def __init__(self, value=None, exception=None, args=()): @property def error(self): - return None if self.exception is None else type(self.exception) + """ + ``None`` if the call returned, the error code (an `errors` constant) if it + raised a ``_tsdate.LibraryError``, else the class of the exception. + """ + if self.exception is None: + return None + if isinstance(self.exception, LibraryError): + return errors.code_of(self.exception) + return type(self.exception) def __repr__(self): if self.exception is None: @@ -118,27 +105,19 @@ def outcome(func, *args, **kwargs): return Outcome(value=value, args=copies) -def errors_match(actual, expected, check_message=True): +def errors_match(actual, expected): """ Whether exception ``actual`` (from an implementation) matches ``expected`` (from - the oracle): the same type and, if ``check_message``, the same message (never for - a ``ZeroDivisionError``). A ``_tsdate.LibraryError`` (or, for an - ``AssertionError``, a ``ValueError`` from the module's shape checks) is accepted - in place of the exceptions of `expected_error`; its message is compared only with - those of the tsdate-authored, user-facing errors (``KLMinimizationFailedError`` - and ``ValueError``), as the messages of the others (assertions, divisions) are not - part of the interface. - """ - if not isinstance(actual, expected_error(type(expected))): - return False + the oracle): the same type and message. An oracle ``ZeroDivisionError`` stands for + the library's ``TSD_ERR_ZERO_DIVISION``, and matches the ``_tsdate.LibraryError`` + that reports it. + """ if isinstance(expected, ZeroDivisionError): - return True - if isinstance(expected, AssertionError) and not isinstance(actual, AssertionError): - return True - return not check_message or str(actual) == str(expected) + expected = library_error(errors.ZERO_DIVISION) + return type(actual) is type(expected) and str(actual) == str(expected) -def assert_same_outcome(actual, expected, check_message=True): +def assert_same_outcome(actual, expected): """ Assert that two `Outcome` objects agree: both raise matching exceptions, or both return the same values and leave array arguments the same. @@ -148,7 +127,7 @@ def assert_same_outcome(actual, expected, check_message=True): f"implementation returned {actual.value!r}, oracle raised " f"{expected.exception!r}" ) - assert errors_match(actual.exception, expected.exception, check_message), ( + assert errors_match(actual.exception, expected.exception), ( f"implementation raised {actual.exception!r}, oracle raised " f"{expected.exception!r}" ) @@ -167,25 +146,25 @@ def assert_same_outcome(actual, expected, check_message=True): ) from None -def compare(impl_func, oracle_func, *args, check_message=True, **kwargs): +def compare(impl_func, oracle_func, *args, **kwargs): """ Call the implementation and the oracle on copies of ``args``, assert that their outcomes agree (`assert_same_outcome`), and return the oracle's `Outcome`. """ expected = outcome(oracle_func, *args, **kwargs) actual = outcome(impl_func, *args, **kwargs) - assert_same_outcome(actual, expected, check_message=check_message) + assert_same_outcome(actual, expected) return expected def kind(result): """ - Classify an `Outcome`: the exception class if it raised, ``None`` if it returned + Classify an `Outcome`: its `Outcome.error` if it raised, ``None`` if it returned ``None`` (an in-place update), else ``"nan"`` if any returned value is NaN, ``"finite"`` if all are finite, otherwise ``"nonfinite"``. """ if result.exception is not None: - return type(result.exception) + return result.error if result.value is None: return None values = [leaf for _, leaf in _flatten(result.value)] diff --git a/tests/oracle/hypergeo.py b/tests/oracle/hypergeo.py index 626d72b7..bc37e6af 100644 --- a/tests/oracle/hypergeo.py +++ b/tests/oracle/hypergeo.py @@ -7,6 +7,8 @@ import _tsdate import numpy as np +from . import errors + # Plain `math` raises on log(0), exp overflow etc., where C gives -inf, inf or # nan; `_libm` gives the C results. # C computes `x ** n` for integer constants `n` by repeated squaring, whereas @@ -18,6 +20,7 @@ # SIMD loops may differ from libm. Logs, tangents, sines and powers are the `_libm` # versions (libm functions on Python floats). from ._libm import erf, exp, ipow, lgamma, log, pow, sin, sqrt, tan # noqa: A004 +from .errors import library_error # gammaincinv is a primitive of the oracles, as the libm functions are: the C library's # port of `scipy.special.gammaincinv`, which `TestGammaincInv` compares with SciPy. @@ -89,8 +92,10 @@ def hyperu_laplace(a, b, x): TODO: details """ - assert b >= a > 0.0 - assert x > 0.0 + if not (b >= a > 0.0): + raise library_error(errors.INVALID_HYPERGEO) + if not (x > 0.0): + raise library_error(errors.INVALID_HYPERGEO) t = b - x - 1 u = 2 * a / (sqrt(ipow(t, 2) + 4 * x * a) - t) @@ -114,7 +119,8 @@ def hyp1f1_laplace(a, b, x): TODO: details """ - assert b > a > 0.0 + if not (b > a > 0.0): + raise library_error(errors.INVALID_HYPERGEO) if x == 0.0: return 0.0 @@ -153,7 +159,8 @@ def _hyp2f1_unity(a, b, c, x): hypergeometric series of unit argument" """ assert np.isclose(x, 1.0) - assert x < 1.0 + if not (x < 1.0): + raise library_error(errors.INVALID_HYPERGEO) g = c - a - b @@ -167,11 +174,8 @@ def _hyp2f1_unity(a, b, c, x): return log(-log(1 - x)) + lgamma(a + b) - lgamma(a) - lgamma(b) # TODO: simplify, we can safely assume a,b > 0? - assert c > 0.0 - assert a >= 0.0 - assert b >= 0.0 - assert c >= a - assert x < 1.0 + if not (c > 0.0 and a >= 0.0 and b >= 0.0 and c >= a and x < 1.0): + raise library_error(errors.INVALID_HYPERGEO) if x == 0.0: return 0.0 @@ -189,7 +193,8 @@ def _hyp2f1_unity(a, b, c, x): u = sqrt(ipow(t, 2) - 4 * a * x * (c - b)) - t y = 2 * a / u - assert 0 < y < 1, "Root on boundary" + if not (0 < y < 1): # root on boundary + raise library_error(errors.INVALID_HYPERGEO) yy = ipow(y, 2) / a my = ipow(1 - y, 2) / (c - a) @@ -220,8 +225,8 @@ def gammainc_der(p, x): tol = 1.0e-14 xbig = 1.0e8 - assert x >= 0.0 - assert p > 0.0 + if not (x >= 0.0 and p > 0.0): + raise library_error(errors.INVALID_HYPERGEO) if x == 0: value, grad = 0.0, 0.0 diff --git a/tests/oracle/phasing.py b/tests/oracle/phasing.py index f7b1c0eb..11f4b5bc 100644 --- a/tests/oracle/phasing.py +++ b/tests/oracle/phasing.py @@ -5,14 +5,19 @@ import numpy as np import tskit +from . import errors +from .errors import library_error + def reallocate_unphased(edges_likelihood, mutations_phase, mutations_block, blocks_edges): """ Add a proportion of each unphased singleton mutation to one of the two edges to which it maps """ - assert mutations_phase.size == mutations_block.size - assert blocks_edges.shape[1] == 2 + if mutations_phase.size != mutations_block.size: + raise ValueError("Array sizes are not equal") + if blocks_edges.shape[1] != 2: + raise ValueError("Arrays must have two columns") num_edges = edges_likelihood.shape[0] edges_unphased = np.full(num_edges, False) @@ -25,16 +30,18 @@ def reallocate_unphased(edges_likelihood, mutations_phase, mutations_block, bloc if b == tskit.NULL: continue i, j = blocks_edges[b] - assert tskit.NULL < i < num_edges + if not (tskit.NULL < i < num_edges and tskit.NULL < j < num_edges): + raise library_error(errors.BLOCK_OUT_OF_RANGE) assert edges_unphased[i] - assert tskit.NULL < j < num_edges assert edges_unphased[j] if np.isnan(mutations_phase[m]): # TODO: fix rare numerical issue continue - assert 0.0 <= mutations_phase[m] <= 1.0 + if not (0.0 <= mutations_phase[m] <= 1.0): + raise library_error(errors.PHASE_OUT_OF_RANGE) edges_likelihood[i, 0] += mutations_phase[m] edges_likelihood[j, 0] += 1 - mutations_phase[m] - assert np.isclose(num_unphased, np.sum(edges_likelihood[edges_unphased, 0])) + if not np.isclose(num_unphased, np.sum(edges_likelihood[edges_unphased, 0])): + raise library_error(errors.UNPHASED_LIKELIHOOD_NOT_CONSERVED) def block_singletons( @@ -54,9 +61,17 @@ def block_singletons( Blocks of the singleton mutations of unphased individuals: ``(blocks_stats, blocks_edges, mutations_block)``. """ - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size - assert indexes_insert.size == indexes_remove.size == edges_parent.size - assert mutations_node.size == mutations_position.size + if not ( + edges_parent.size + == edges_child.size + == edges_left.size + == edges_right.size + == indexes_insert.size + == indexes_remove.size + ): + raise ValueError("Array sizes are not equal") + if mutations_node.size != mutations_position.size: + raise ValueError("Array sizes are not equal") num_mutations = mutations_node.size num_edges = edges_parent.size @@ -107,7 +122,8 @@ def block_singletons( i = nodes_individual[c] if i != tskit.NULL and individuals_unphased[i]: u, v = individuals_edges[i] - assert u == tskit.NULL or v == tskit.NULL + if u != tskit.NULL and v != tskit.NULL: + raise library_error(errors.UNPHASED_INDIVIDUAL_EDGES) individuals_edges[i] = [e, max(u, v)] individuals_position[i] = left if individuals_block[i] == tskit.NULL: @@ -137,7 +153,9 @@ def block_singletons( blocks_span = np.array(blocks_span) blocks_order = np.array(blocks_order) blocks_stats = np.column_stack((blocks_singletons, blocks_span)) - assert num_blocks == blocks_edges.shape[0] == blocks_stats.shape[0] + # every block must have been completed + if num_blocks != blocks_edges.shape[0]: + raise library_error(errors.UNPHASED_INDIVIDUAL_EDGES) # sort block arrays so that mutations_block points to correct row blocks_order = np.argsort(blocks_order) @@ -163,9 +181,17 @@ def mutation_frequency( The number of samples of each sample set below each mutation, as an array of shape ``(num_mutations, num_sample_sets)``. """ - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size - assert indexes_insert.size == indexes_remove.size == edges_parent.size - assert mutations_node.size == mutations_position.size + if not ( + edges_parent.size + == edges_child.size + == edges_left.size + == edges_right.size + == indexes_insert.size + == indexes_remove.size + ): + raise ValueError("Array sizes are not equal") + if mutations_node.size != mutations_position.size: + raise ValueError("Array sizes are not equal") num_nodes, num_sample_sets = nodes_sample.shape num_mutations = mutations_node.size diff --git a/tests/oracle/rescaling.py b/tests/oracle/rescaling.py index 5cf675e8..708be90d 100644 --- a/tests/oracle/rescaling.py +++ b/tests/oracle/rescaling.py @@ -7,10 +7,13 @@ import numpy as np import tskit +from . import errors + # Plain `math.log` raises on 0, where C gives -inf; C sums sequentially, # whereas numpy sums pairwise (`seq_sum`). from ._libm import log, seq_sum from .approx import approximate_gamma_iqr +from .errors import library_error from .hypergeo import gammainc_inv @@ -18,7 +21,8 @@ def fixed_changepoints(counts, epochs): """ Find breakpoints such that `counts` is divided roughly equally across `epochs` """ - assert epochs > 0 + if not (epochs > 0): + raise library_error(errors.NONPOSITIVE_INTERVALS) Y = np.append(0.0, np.cumsum(counts)) Z = Y / Y[-1] z = np.linspace(0, 1, epochs + 1) @@ -40,10 +44,10 @@ def poisson_changepoints(counts, offset, penalty, min_counts, min_offset): (https://doi.org/10.1080/01621459.2012.737745) """ - assert counts.size == offset.size - assert min_counts >= 0 - assert min_offset >= 0 - assert penalty >= 0 + if counts.size != offset.size: + raise ValueError("counts and offset must have the same size") + if not (min_counts >= 0 and min_offset >= 0 and penalty >= 0): + raise library_error(errors.NEGATIVE_CHANGEPOINT_PARAMETER) N = np.append(0, np.cumsum(offset)) Y = np.append(0, np.cumsum(counts)) @@ -94,9 +98,12 @@ def count_mutations( The mutations on each edge and the edge's span, weighted by the number of samples below the edge if ``size_biased``, as ``(edges_stats, mutations_edge)``. """ - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size - assert indexes_insert.size == indexes_remove.size == edges_parent.size - assert mutations_node.size == mutations_position.size + if not (edges_parent.size == edges_child.size == edges_left.size == edges_right.size): + raise ValueError("Edge arrays must have the same size") + if not (indexes_insert.size == indexes_remove.size == edges_parent.size): + raise ValueError("Edge index arrays must have one entry per edge") + if mutations_node.size != mutations_position.size: + raise ValueError("Mutation arrays must have the same size") num_mutations = mutations_node.size num_edges = edges_parent.size @@ -189,8 +196,10 @@ def mutational_area( :param np.ndarray edges_weight: a weight for each edge """ - assert edges_parent.size == edges_child.size - assert likelihoods.shape == (edges_parent.size, 2) + if edges_parent.size != edges_child.size: + raise ValueError("Edge arrays must have the same size") + if likelihoods.shape != (edges_parent.size, 2): + raise ValueError("Likelihoods must have one row of two columns per edge") # index node by unique time breaks nodes_order = np.argsort(nodes_time) @@ -250,11 +259,14 @@ def mutational_timescale( estimate the time scaling """ - assert edges_parent.size == edges_child.size - assert likelihoods.shape[0] == edges_parent.size - assert likelihoods.shape[1] == 2 - assert nodes_fixed.size == nodes_time.size - assert max_intervals > 0 + if edges_parent.size != edges_child.size: + raise ValueError("Edge arrays must have the same size") + if likelihoods.shape != (edges_parent.size, 2): + raise ValueError("Likelihoods must have one row of two columns per edge") + if nodes_fixed.size != nodes_time.size: + raise ValueError("nodes_fixed and nodes_time must have the same size") + if not (max_intervals > 0): + raise library_error(errors.NONPOSITIVE_INTERVALS) counts, offset, duration, indexes = mutational_area( nodes_time, @@ -279,7 +291,8 @@ def mutational_timescale( n = seq_sum(offset[i:j]) y = seq_sum(counts[i:j]) z = seq_sum(duration[i:j]) - assert n > 0, "Zero edge span in interval" + if not (n > 0): + raise library_error(errors.ZERO_EDGE_SPAN) adjust[k + 1] = z * y / n k += 1 @@ -303,29 +316,27 @@ def piecewise_scale_posterior( rescaled shape parameter, e.g. 0.5 uses interquartile range """ - assert posteriors_fixed.size == posteriors.shape[0] - assert original_breaks.size == rescaled_breaks.size - assert 1 > quantile_width > 0 + if not (posteriors.shape[1] == 2 and posteriors_fixed.size == posteriors.shape[0]): + raise ValueError("Posteriors must have two columns and one row per fixed flag") + if not (original_breaks.size == rescaled_breaks.size and original_breaks.size > 0): + raise ValueError("Breakpoints must be non-empty and of the same size") + if not (1 > quantile_width > 0): + raise library_error(errors.INVALID_QUANTILE_WIDTH) - if not np.all(np.diff(rescaled_breaks) > 0): - raise ValueError( - "Rescaling produced non-increasing time breakpoints. " - "Try setting `rescaling_intervals` to a smaller value " - "(e.g. half its current value)." - ) - if not np.all(np.diff(original_breaks) > 0): - raise ValueError( - "Rescaling produced non-increasing time breakpoints. " - "Try setting `rescaling_intervals` to a smaller value " - "(e.g. half its current value)." - ) + if not ( + np.all(np.diff(rescaled_breaks) > 0) and np.all(np.diff(original_breaks) > 0) + ): + raise library_error(errors.NON_INCREASING_BREAKPOINTS) dim = posteriors.shape[0] quant_lower = quantile_width / 2 quant_upper = 1 - quantile_width / 2 freed = ~posteriors_fixed - assert np.all(np.logical_and(posteriors[freed, 0] > -1, posteriors[freed, 1] > 0)) + if not np.all(np.logical_and(posteriors[freed, 0] > -1, posteriors[freed, 1] > 0)): + raise library_error(errors.INVALID_POSTERIOR) + if dim == 0: + raise library_error(errors.NO_POSTERIORS) # use posterior mean as a point estimate lower = np.zeros(dim) @@ -342,8 +353,9 @@ def piecewise_scale_posterior( def rescale(x): i = np.searchsorted(original_breaks, x, "right") - 1 - assert i.min() >= 0 # DEBUG - assert i.max() < scalings.size # DEBUG + if not (i.min() >= 0): + raise library_error(errors.TIME_BELOW_FIRST_BREAKPOINT) + assert i.max() < scalings.size return rescaled_breaks[i] + scalings[i] * (x - original_breaks[i]) midpt = rescale(midpt) @@ -381,18 +393,10 @@ def piecewise_scale_point_estimate( Node ages mapped piecewise linearly from ``original_breaks`` to ``rescaled_breaks``; ages where ``point_fixed`` are unchanged. """ - if not np.all(np.diff(rescaled_breaks) > 0): - raise ValueError( - "Rescaling produced non-increasing time breakpoints. " - "Try setting `rescaling_intervals` to a smaller value " - "(e.g. half its current value)." - ) - if not np.all(np.diff(original_breaks) > 0): - raise ValueError( - "Rescaling produced non-increasing time breakpoints. " - "Try setting `rescaling_intervals` to a smaller value " - "(e.g. half its current value)." - ) + if not ( + np.all(np.diff(rescaled_breaks) > 0) and np.all(np.diff(original_breaks) > 0) + ): + raise library_error(errors.NON_INCREASING_BREAKPOINTS) scalings = np.append(np.diff(rescaled_breaks) / np.diff(original_breaks), 0) idx = np.searchsorted(original_breaks, point_estimate, "right") - 1 rescaled_estimate = rescaled_breaks[idx] + \ diff --git a/tests/oracle/util.py b/tests/oracle/util.py index c162f75d..365f6e24 100644 --- a/tests/oracle/util.py +++ b/tests/oracle/util.py @@ -5,6 +5,9 @@ import numpy as np import tskit +from . import errors +from .errors import library_error + def split_disjoint_nodes( edges_parent, edges_child, edges_left, edges_right, node_excluded @@ -15,7 +18,8 @@ def split_disjoint_nodes( Returns updated edges_parent, edges_child, mutations_node, and indices indicating from which original node the new nodes are derived. """ - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size + if not (edges_parent.size == edges_child.size == edges_left.size == edges_right.size): + raise ValueError("Array sizes are not equal") num_edges = edges_parent.size num_nodes = node_excluded.size @@ -79,9 +83,17 @@ def relabel_mutations_node( Traverse trees, maintaining a mapping between old and new node IDs in the current tree. Update `mutations_node` to reflect new IDs. """ - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size - assert edges_parent.size == insert_index.size == remove_index.size - assert mutations_position.size == mutations_node.size + if not ( + edges_parent.size + == edges_child.size + == edges_left.size + == edges_right.size + == insert_index.size + == remove_index.size + ): + raise ValueError("Array sizes are not equal") + if mutations_position.size != mutations_node.size: + raise ValueError("Array sizes are not equal") num_nodes = nodes_order.size num_edges = edges_parent.size @@ -114,7 +126,8 @@ def relabel_mutations_node( left = right while m < num_mutations and mutations_position[m] < right: - assert nodes_map[mutations_node[m]] != tskit.NULL + if nodes_map[mutations_node[m]] == tskit.NULL: + raise library_error(errors.MUTATION_NODE_NOT_IN_TREE) output[m] = nodes_map[mutations_node[m]] m += 1 @@ -132,8 +145,10 @@ def constrain_ages( Dykstra RL, "An algorithm for restricted least squares regression", JASA 1983 """ - assert nodes_time.size == nodes_fixed.size - assert edges_parent.size == edges_child.size + if nodes_time.size != nodes_fixed.size: + raise ValueError("Array sizes are not equal") + if edges_parent.size != edges_child.size: + raise ValueError("Array sizes are not equal") num_edges = edges_parent.size nodes_time = nodes_time.copy() @@ -148,7 +163,8 @@ def constrain_ages( adjustment = nodes_time[c] - nodes_time[p] # + epsilon edges_cavity[e, :] = 0.0 if adjustment > 0: - assert not (nodes_fixed[c] and nodes_fixed[p]) + if nodes_fixed[c] and nodes_fixed[p]: + raise library_error(errors.FIXED_NODES_VIOLATE_CONSTRAINT) if not nodes_fixed[c] and not nodes_fixed[p]: edges_cavity[e, 0] = -adjustment / 2 edges_cavity[e, 1] = adjustment / 2 @@ -187,8 +203,14 @@ def contains_unary_nodes( """ Whether a node outside ``nodes_mask`` has exactly one child in some tree. """ - assert edges_parent.size == edges_left.size == edges_right.size - assert indexes_insert.size == indexes_remove.size == edges_parent.size + if not ( + edges_parent.size + == edges_left.size + == edges_right.size + == indexes_insert.size + == indexes_remove.size + ): + raise ValueError("Array sizes are not equal") num_edges = edges_parent.size nodes_children = np.zeros(num_nodes, dtype=np.int32) diff --git a/tests/oracle/variational.py b/tests/oracle/variational.py index d1ad54aa..695e3f8a 100644 --- a/tests/oracle/variational.py +++ b/tests/oracle/variational.py @@ -20,11 +20,12 @@ UPPER, ) -from . import approx +from . import approx, errors # C sums sequentially, whereas numpy sums pairwise, which differs in the last # bits; `seq_mean` sums sequentially. from ._libm import seq_mean +from .errors import library_error def rescale_factors(factors): @@ -77,13 +78,15 @@ def damp(x0, x1, y0, y1, s): """ if y0 == 0.0 and y1 == 0.0 and x0 == 0.0 and x1 == 0.0: return 1.0 - assert 0 < s < 1 - assert 0.0 < x0 + 1 - assert 0.0 < x1 + if not (0 < s < 1): + raise library_error(errors.INVALID_MIN_STEP) + if not (0.0 < x0 + 1 and 0.0 < x1): + raise library_error(errors.INVALID_NODE_POSTERIOR) a = 1.0 if (1 + x0 - y0 > (1 + x0) * s) else (1 - s) * (1 + x0) / y0 b = 1.0 if (x1 - y1 > x1 * s) else (1 - s) * x1 / y1 d = min(a, b) - assert 0.0 < d <= 1.0 + if not (0.0 < d <= 1.0): + raise library_error(errors.INVALID_DAMPING) return d @@ -93,8 +96,8 @@ def rescale(x0, x1, s): """ if x0 == 0.0 and x1 == 0.0: return 1.0 - assert 0 < x0 + 1 - assert 0 < x1 + if not (0 < x0 + 1 and 0 < x1): + raise library_error(errors.INVALID_NODE_POSTERIOR) if 1 + x0 > s: return (s - 1) / x0 elif 1 + x0 < 1 / s: @@ -146,11 +149,27 @@ def propagate_likelihood( # :param bool unphased: if True, edges are treated as blocks of unphased # singletons in contemporary individuals - assert constraints.shape == posterior.shape - assert edges_child.size == edges_parent.size - assert likelihoods.shape == (edges_parent.size, 2) - assert max_shape >= 1.0 - assert 0.0 < min_step < 1.0 + node, edge, block, scale, *_ = factors + factor = block if unphased else edge + num_nodes = node.shape[0] + if factor.shape[1:] != (2, 2): + raise ValueError("Factors must have shape (n, 2, 2)") + if edges_child.size != edges_parent.size: + raise ValueError("Edge arrays must have the same size") + if likelihoods.shape != (edges_parent.size, 2): + raise ValueError("Likelihoods must have shape (edges, 2)") + if constraints.shape != (num_nodes, 2): + raise ValueError("Constraints must have shape (nodes, 2)") + if posterior.shape != (num_nodes, 2): + raise ValueError("Posterior must have the same shape as constraints") + if lognorm.size != edges_parent.size: + raise ValueError("Lognorm must have one entry per edge") + if factor.shape[0] != edges_parent.size: + raise ValueError("Factors must have one entry per edge") + if not (max_shape >= 1.0): + raise library_error(errors.INVALID_MAX_SHAPE) + if not (0.0 < min_step < 1.0): + raise library_error(errors.INVALID_MIN_STEP) def cavity_damping(x, y): return damp(x[0], x[1], y[0], y[1], min_step) @@ -178,16 +197,13 @@ def gamma_projection(x, y, z): return logl, proj[:2], proj[2:] def twin_projection(x, y): - assert unphased, "Invalid update" + if not unphased: + raise library_error(errors.TWIN_EDGE_IN_PHASED_PASS) logl, *proj = approx.twin_projection(*map(float, x), *map(float, y)) return logl, proj fixed = constraints[:, LOWER] == constraints[:, UPPER] - node, edge, block, scale, *_ = factors - factor = block if unphased else edge - assert factor.shape == (edges_parent.size, 2, 2) - for i in edge_order: p, c = edges_parent[i], edges_child[i] if scale[p] < TINY or scale[c] < TINY: @@ -292,8 +308,18 @@ def propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol): # :param int em_reltol: the termination criterion for relative change in # log-likelihood. - assert free.size == posterior.shape[0] - assert max_shape >= 1.0 + node, edge, block, scale, *_ = factors + factor = node + if factor.shape[1:] != (2, 2): + raise ValueError("Factors must have shape (n, 2, 2)") + if scale.size != factor.shape[0]: + raise ValueError("Factor arrays have inconsistent sizes") + if not (free.size == factor.shape[0] and posterior.shape == (free.size, 2)): + raise ValueError( + "The free nodes, posterior and factors must have one entry per node" + ) + if not (max_shape >= 1.0): + raise library_error(errors.INVALID_MAX_SHAPE) def posterior_damping(x): return rescale(x[0], x[1], max_shape) @@ -301,11 +327,6 @@ def posterior_damping(x): if not np.any(free): return - node, edge, block, scale, *_ = factors - factor = node - assert factor.shape == (free.size, 2, 2) - assert scale.size == free.size - # fit an exponential to cavity distributions for unconstrained nodes cavity = posterior - factor[:, MIXPRIOR] * scale[:, np.newaxis] shape, rate = cavity[free, 0] + 1, cavity[free, 1] @@ -317,7 +338,8 @@ def posterior_damping(x): delta = 1 / seq_mean(shape / (rate + penalty)) - penalty penalty += delta itt += 1 - assert penalty > 0 + if not (penalty > 0): + raise library_error(errors.NONPOSITIVE_PENALTY) # update posteriors and rescale to keep shape bounded posterior[free, 1] = cavity[free, 1] + penalty @@ -367,12 +389,25 @@ def propagate_mutations( # TODO: scale should be 1.0, can we delete # TODO: we don't seem to need to damp? - # TODO: assert more stuff here? - assert mutations_phase.size == mutations_edge.size - assert mutations_posterior.shape == (mutations_phase.size, 2) - assert constraints.shape == posterior.shape - assert edges_child.size == edges_parent.size - assert likelihoods.shape == (edges_parent.size, 2) + node, edge, block, scale, *_ = factors + factor = block if unphased else edge + num_nodes = node.shape[0] + if factor.shape[1:] != (2, 2): + raise ValueError("Factors must have shape (n, 2, 2)") + if mutations_edge.size != mutations_phase.size: + raise ValueError("Mutation arrays must have the same size") + if mutations_posterior.shape != (mutations_phase.size, 2): + raise ValueError("Mutation posterior must have shape (mutations, 2)") + if edges_child.size != edges_parent.size: + raise ValueError("Edge arrays must have the same size") + if likelihoods.shape != (edges_parent.size, 2): + raise ValueError("Likelihoods must have shape (edges, 2)") + if constraints.shape != (num_nodes, 2): + raise ValueError("Constraints must have shape (nodes, 2)") + if posterior.shape != (num_nodes, 2): + raise ValueError("Posterior must have the same shape as constraints") + if factor.shape[0] != edges_parent.size: + raise ValueError("Factors must have one entry per edge") # the projections take the entries of the cavities and of the edge likelihood # as floats, and return the phase and the natural parameters of the mutation @@ -415,10 +450,6 @@ def twin_projection(x, y): fixed = constraints[:, LOWER] == constraints[:, UPPER] - node, edge, block, scale, *_ = factors - factor = block if unphased else edge - assert factor.shape == (edges_parent.size, 2, 2) - for m in mutations_order: i = mutations_edge[m] if i == tskit.NULL: # skip mutations above root diff --git a/tests/test_oracle_approx.py b/tests/test_oracle_approx.py index ccd15fcf..e96c4170 100644 --- a/tests/test_oracle_approx.py +++ b/tests/test_oracle_approx.py @@ -9,10 +9,11 @@ Conventions pinned here: a NaN result (not an exception) signals a parameter outside the valid region of the hypergeometric function; the ``*_projection`` functions then return NaN and, except for the ``mutation_*`` ones, their input -parameters unchanged; ``AssertionError`` signals a violated precondition (a fixed node -age that is not positive, or a Laplace root on the boundary); ``ZeroDivisionError`` -signals float division by zero; ``KLMinimizationFailedError`` signals a failed gamma -fit. Accuracy of the approximations is measured in ``evaluation/numerical_accuracy.py``. +parameters unchanged; errors are those of the library, as error codes (a violated +precondition such as a fixed node age that is not positive or a Laplace root on the +boundary, or a failed gamma fit), with ``ZeroDivisionError`` in the oracle for the +library's float division by zero. Accuracy of the approximations is measured in +``evaluation/numerical_accuracy.py``. """ import math @@ -22,7 +23,15 @@ import pytest import scipy.special from oracle import approx -from oracle.approx import KLMinimizationFailedError +from oracle.errors import ( + INVALID_HYPERGEO, + JENSEN_VIOLATION, + NEGATIVE_SHAPE, + NONPOSITIVE_CENTRAL_MOMENTS, + NONPOSITIVE_MOMENTS, + NONPOSITIVE_OR_NONFINITE_MOMENTS, + UNSORTED_QUANTILES, +) from oracle.helpers import ( INF, NAN, @@ -201,12 +210,12 @@ def test_valid(self, name, args, expected): ((1.0, 1.0), "finite"), ((1e300, 1e300), "finite"), ((1e-100, 1e-100), "finite"), - ((0.0, 1.0), AssertionError), - ((1.0, 0.0), AssertionError), - ((-1.0, 1.0), AssertionError), - ((1.0, -1.0), AssertionError), - ((NAN, 1.0), AssertionError), - ((1.0, NAN), AssertionError), + ((0.0, 1.0), NONPOSITIVE_MOMENTS), + ((1.0, 0.0), NONPOSITIVE_MOMENTS), + ((-1.0, 1.0), NONPOSITIVE_MOMENTS), + ((1.0, -1.0), NONPOSITIVE_MOMENTS), + ((NAN, 1.0), NONPOSITIVE_MOMENTS), + ((1.0, NAN), NONPOSITIVE_MOMENTS), ((INF, 1.0), "nan"), ((1.0, INF), "nonfinite"), ((1e-300, 1e-300), ZeroDivisionError), # mean**2 underflows @@ -216,7 +225,7 @@ def test_valid(self, name, args, expected): GAMMA_KL = [ # (x, logx, expected kind); `gap` = log(x) - logx must be positive (Jensen) - ((1.0, 0.0), KLMinimizationFailedError), # gap == 0 + ((1.0, 0.0), JENSEN_VIOLATION), # gap == 0 ((1.0, nextafter(0.0, -1.0)), "nonfinite"), # smallest gap: alpha, rate overflow ((1.0, -1e-300), "finite"), ((1.0, -1e-17), "finite"), @@ -229,16 +238,16 @@ def test_valid(self, name, args, expected): ((1.0, -1e160), "finite"), ((1.0, -1e164), ZeroDivisionError), # shape bound ~1e-164: trigamma divides by 0 ((1.0, -1e300), ZeroDivisionError), - ((1.0, -INF), KLMinimizationFailedError), - ((1.0, INF), KLMinimizationFailedError), - ((1.0, NAN), KLMinimizationFailedError), # not (log x > nan) - ((0.0, -1.0), KLMinimizationFailedError), - ((-1.0, -1.0), KLMinimizationFailedError), - ((-0.0, -1.0), KLMinimizationFailedError), - ((NAN, -1.0), KLMinimizationFailedError), + ((1.0, -INF), NONPOSITIVE_OR_NONFINITE_MOMENTS), + ((1.0, INF), NONPOSITIVE_OR_NONFINITE_MOMENTS), + ((1.0, NAN), JENSEN_VIOLATION), # not (log x > nan) + ((0.0, -1.0), NONPOSITIVE_OR_NONFINITE_MOMENTS), + ((-1.0, -1.0), NONPOSITIVE_OR_NONFINITE_MOMENTS), + ((-0.0, -1.0), NONPOSITIVE_OR_NONFINITE_MOMENTS), + ((NAN, -1.0), JENSEN_VIOLATION), ((INF, -1.0), ZeroDivisionError), # alpha = 0.5 / inf = 0 - ((INF, INF), KLMinimizationFailedError), - ((1e-300, -1.0), KLMinimizationFailedError), # log x = -690 < logx + ((INF, INF), NONPOSITIVE_OR_NONFINITE_MOMENTS), + ((1e-300, -1.0), JENSEN_VIOLATION), # log x = -690 < logx ((1e-300, -700.0), "finite"), ((TINY, -745.0), "nonfinite"), # rate = alpha / x overflows ((1e300, 1.0), "finite"), @@ -252,13 +261,13 @@ def test_valid(self, name, args, expected): GAMMA_MOM = [ ((1.0, 1.0), "finite"), - ((1.0, 0.0), KLMinimizationFailedError), - ((0.0, 1.0), KLMinimizationFailedError), - ((-0.0, 1.0), KLMinimizationFailedError), - ((-1.0, 1.0), KLMinimizationFailedError), - ((1.0, -1.0), KLMinimizationFailedError), - ((NAN, 1.0), KLMinimizationFailedError), - ((1.0, NAN), KLMinimizationFailedError), + ((1.0, 0.0), NONPOSITIVE_CENTRAL_MOMENTS), + ((0.0, 1.0), NONPOSITIVE_CENTRAL_MOMENTS), + ((-0.0, 1.0), NONPOSITIVE_CENTRAL_MOMENTS), + ((-1.0, 1.0), NONPOSITIVE_CENTRAL_MOMENTS), + ((1.0, -1.0), NONPOSITIVE_CENTRAL_MOMENTS), + ((NAN, 1.0), NONPOSITIVE_CENTRAL_MOMENTS), + ((1.0, NAN), NONPOSITIVE_CENTRAL_MOMENTS), ((TINY, TINY), "finite"), ((1.0, 1e-300), "finite"), # shape 1e300 ((1.0, TINY), "nonfinite"), # shape overflows @@ -276,16 +285,16 @@ def test_valid(self, name, args, expected): GAMMA_IQR_ERRORS = [ - ((0.25, 0.75, 2.0, 1.0, 50.0), KLMinimizationFailedError), # x unsorted - ((0.75, 0.25, 1.0, 2.0, 50.0), KLMinimizationFailedError), # q unsorted - ((0.25, 0.25, 1.0, 2.0, 50.0), KLMinimizationFailedError), # q equal - ((0.25, 0.75, 1.0, NAN, 50.0), KLMinimizationFailedError), - ((NAN, 0.75, 1.0, 2.0, 50.0), KLMinimizationFailedError), + ((0.25, 0.75, 2.0, 1.0, 50.0), UNSORTED_QUANTILES), # x unsorted + ((0.75, 0.25, 1.0, 2.0, 50.0), UNSORTED_QUANTILES), # q unsorted + ((0.25, 0.25, 1.0, 2.0, 50.0), UNSORTED_QUANTILES), # q equal + ((0.25, 0.75, 1.0, NAN, 50.0), UNSORTED_QUANTILES), + ((NAN, 0.75, 1.0, 2.0, 50.0), UNSORTED_QUANTILES), ((0.25, 0.75, 0.0, 1.0, 50.0), ZeroDivisionError), # log(x2 / 0) ((0.0, 0.75, 1.0, 2.0, 50.0), ZeroDivisionError), # log(q2 / 0) - ((0.25, 0.75, -1.0, 1.0, 50.0), KLMinimizationFailedError), - ((0.25, 1.0, 1.0, 2.0, 50.0), KLMinimizationFailedError), # q2 == 1: negative shape - ((0.25, 0.75, 1.0, INF, 50.0), AssertionError), + ((0.25, 0.75, -1.0, 1.0, 50.0), NEGATIVE_SHAPE), + ((0.25, 1.0, 1.0, 2.0, 50.0), NEGATIVE_SHAPE), # q2 == 1: negative shape + ((0.25, 0.75, 1.0, INF, 50.0), INVALID_HYPERGEO), ((0.25, 0.75, 0.0, 0.0, 50.0), ZeroDivisionError), # x1 == x2 == 0 # the shape is capped at max_shape when x1 == x2, when the lower bound exceeds it # or when Newton's iteration ends above it @@ -320,13 +329,13 @@ def test_valid(self, name, args, expected): "wide rates": ([1.0, 2.0], [1e-300, 1e300], "finite"), "shape+1 near zero": ([-1.0 + 1e-10, 4.0], [1.0, 2.0], "finite"), "shape+1 zero": ([-1.0], [1.0], ZeroDivisionError), # digamma pole - "shape+1 negative": ([-2.0], [1.0], KLMinimizationFailedError), + "shape+1 negative": ([-2.0], [1.0], NONPOSITIVE_OR_NONFINITE_MOMENTS), "zero rate": ([1.0], [0.0], ZeroDivisionError), - "negative rate": ([1.0], [-1.0], KLMinimizationFailedError), - "nan shape": ([NAN], [1.0], KLMinimizationFailedError), - "inf shape": ([INF], [1.0], KLMinimizationFailedError), + "negative rate": ([1.0], [-1.0], NONPOSITIVE_OR_NONFINITE_MOMENTS), + "nan shape": ([NAN], [1.0], JENSEN_VIOLATION), + "inf shape": ([INF], [1.0], NONPOSITIVE_OR_NONFINITE_MOMENTS), "empty": ([], [], ZeroDivisionError), - "size mismatch": ([1.0], [1.0, 2.0], AssertionError), + "size mismatch": ([1.0], [1.0, 2.0], ValueError), } GAMMA_DOMAIN = ( diff --git a/tests/test_oracle_helpers.py b/tests/test_oracle_helpers.py index db154f51..21835167 100644 --- a/tests/test_oracle_helpers.py +++ b/tests/test_oracle_helpers.py @@ -6,6 +6,8 @@ import _tsdate import numpy as np import pytest +from oracle import errors +from oracle.errors import library_error from oracle.helpers import ( INF, NAN, @@ -14,11 +16,10 @@ assert_same_values, compare, errors_match, + kind, outcome, ) -KLFailed = type("KLMinimizationFailedError", (Exception,), {}) - def returns(value, modify=None): def func(x): @@ -101,21 +102,59 @@ def test_wrong_kind(self): assert_outcome(returns(1.0), returns(1.0), (np.zeros(1),), "nan") -class TestLibraryError: +class TestErrorsMatch: + """ + Exceptions match if they have the same type and message; an oracle + ``ZeroDivisionError`` matches the library's error for a float division by zero. + """ + + def test_same_library_error(self): + error = library_error(errors.INVALID_HYPERGEO) + assert errors_match(library_error(errors.INVALID_HYPERGEO), error) + + def test_library_error_code_differs(self): + error = library_error(errors.INVALID_HYPERGEO) + assert not errors_match(library_error(errors.ZERO_DIVISION), error) + + def test_type_differs(self): + message = _tsdate.strerror(errors.INVALID_MAX_SHAPE) + assert not errors_match(_tsdate.LibraryError(message), ValueError(message)) + assert not errors_match(ValueError(message), _tsdate.LibraryError(message)) + + def test_value_error_message_differs(self): + assert not errors_match(ValueError("b"), ValueError("a")) + + def test_zero_division(self): + actual = library_error(errors.ZERO_DIVISION) + assert errors_match(actual, ZeroDivisionError("division by zero")) + + @pytest.mark.parametrize( + "actual", + [ + library_error(errors.INVALID_HYPERGEO), + ValueError(_tsdate.strerror(errors.ZERO_DIVISION)), + ZeroDivisionError("division by zero"), + ], + ids=repr, + ) + def test_zero_division_rejects(self, actual): + assert not errors_match(actual, ZeroDivisionError("division by zero")) + + +class TestErrors: """ - The C library reports the oracle's ZeroDivisionError, AssertionError, - KLMinimizationFailedError and ValueError as ``_tsdate.LibraryError``; messages are - compared only for the last two. + The error codes of ``oracle.errors`` are those of the library. """ - @pytest.mark.parametrize("oracle_type", [ValueError, KLFailed]) - def test_messages_compared(self, oracle_type): - assert errors_match(_tsdate.LibraryError("a"), oracle_type("a")) - assert not errors_match(_tsdate.LibraryError("b"), oracle_type("a")) + def test_every_code_has_a_distinct_message(self): + messages = {_tsdate.strerror(code) for code in errors.CODES} + assert len(messages) == len(errors.CODES) + assert "Unknown error" not in messages - @pytest.mark.parametrize("oracle_exc", [KeyError("a"), IndexError("a")], ids=type) - def test_other_oracle_errors_rejected(self, oracle_exc): - assert not errors_match(_tsdate.LibraryError("a"), oracle_exc) + def test_no_further_codes(self): + code = errors.CODES[0] - 1 + assert _tsdate.strerror(code) == "Unknown error" - def test_value_error_rejected_for_zero_division(self): - assert not errors_match(ValueError("a"), ZeroDivisionError("a")) + def test_kind_is_the_code(self): + result = outcome(raises(library_error(errors.NO_POSTERIORS)), np.zeros(1)) + assert kind(result) == errors.NO_POSTERIORS diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py index 10b95d87..81db3130 100644 --- a/tests/test_oracle_hypergeo.py +++ b/tests/test_oracle_hypergeo.py @@ -1,10 +1,11 @@ """ Parity of the special functions of ``_tsdate`` with their oracles in ``oracle/hypergeo.py``: exact values (including NaNs and infinities), and which -exception is raised (``AssertionError`` for the domain checks, -``ZeroDivisionError`` for float division by zero). Expected values always come from the -oracle. Tables hold deliberate edge cases (poles, domain boundaries, both sides of a -branch switch); grids and seeded random draws cover the interior and extreme ranges. +error is raised (``INVALID_HYPERGEO`` for the domain checks, ``ZeroDivisionError`` in +the oracle for the library's float division by zero). Expected values always come +from the oracle. Tables hold deliberate edge cases (poles, domain boundaries, both +sides of a branch switch); grids and seeded random draws cover the interior and extreme +ranges. Accuracy of the approximations is measured in ``evaluation/numerical_accuracy.py``. """ @@ -15,6 +16,7 @@ import pytest import scipy.special from oracle import hypergeo +from oracle.errors import INVALID_HYPERGEO from oracle.helpers import ( INF, NAN, @@ -221,13 +223,13 @@ def test_matches_oracle(self, p, q): ] GAMMAINC_DER_DOMAIN = [ - ((-1.0, 1.0), AssertionError), - ((0.0, 1.0), AssertionError), - ((-0.0, 1.0), AssertionError), - ((1.0, -1.0), AssertionError), - ((1.0, -5e-324), AssertionError), - ((NAN, 1.0), AssertionError), - ((1.0, NAN), AssertionError), + ((-1.0, 1.0), INVALID_HYPERGEO), + ((0.0, 1.0), INVALID_HYPERGEO), + ((-0.0, 1.0), INVALID_HYPERGEO), + ((1.0, -1.0), INVALID_HYPERGEO), + ((1.0, -5e-324), INVALID_HYPERGEO), + ((NAN, 1.0), INVALID_HYPERGEO), + ((1.0, NAN), INVALID_HYPERGEO), ] @@ -343,18 +345,18 @@ def test_matches_scipy_random(self): HYPERU_DOMAIN = [ ((1.0, 1.0, 1.0), "finite"), # b == a is allowed - ((1.0, nextafter(1.0, 0), 1.0), AssertionError), # b < a - ((0.0, 1.0, 1.0), AssertionError), - ((-0.0, 1.0, 1.0), AssertionError), - ((-1.0, 1.0, 1.0), AssertionError), + ((1.0, nextafter(1.0, 0), 1.0), INVALID_HYPERGEO), # b < a + ((0.0, 1.0, 1.0), INVALID_HYPERGEO), + ((-0.0, 1.0, 1.0), INVALID_HYPERGEO), + ((-1.0, 1.0, 1.0), INVALID_HYPERGEO), ((5e-324, 1.0, 1.0), "finite"), - ((1.0, 2.0, 0.0), AssertionError), - ((1.0, 2.0, -0.0), AssertionError), - ((1.0, 2.0, -1.0), AssertionError), + ((1.0, 2.0, 0.0), INVALID_HYPERGEO), + ((1.0, 2.0, -0.0), INVALID_HYPERGEO), + ((1.0, 2.0, -1.0), INVALID_HYPERGEO), ((1.0, 2.0, 1.0), "finite"), - ((NAN, 2.0, 1.0), AssertionError), - ((1.0, NAN, 1.0), AssertionError), - ((1.0, 2.0, NAN), AssertionError), + ((NAN, 2.0, 1.0), INVALID_HYPERGEO), + ((1.0, NAN, 1.0), INVALID_HYPERGEO), + ((1.0, 2.0, NAN), INVALID_HYPERGEO), ((INF, INF, 1.0), "nan"), ((1.0, INF, 1.0), "nan"), # the Laplace root divides by zero when the square root equals t in floating point @@ -375,13 +377,13 @@ def test_matches_scipy_random(self): ((1.0, 2.0, -0.0), "finite"), # NOTE: current behaviour, possibly a bug: b == a is allowed by `valid_hyp1f1` # (in approx) but asserted against here - ((1.0, 1.0, 1.0), AssertionError), - ((1.0, 0.5, 1.0), AssertionError), - ((0.0, 1.0, 1.0), AssertionError), - ((0.0, 1.0, 0.0), AssertionError), # asserted before the x == 0 shortcut - ((-1.0, 1.0, 0.0), AssertionError), - ((NAN, 2.0, 1.0), AssertionError), - ((1.0, NAN, 1.0), AssertionError), + ((1.0, 1.0, 1.0), INVALID_HYPERGEO), + ((1.0, 0.5, 1.0), INVALID_HYPERGEO), + ((0.0, 1.0, 1.0), INVALID_HYPERGEO), + ((0.0, 1.0, 0.0), INVALID_HYPERGEO), # asserted before the x == 0 shortcut + ((-1.0, 1.0, 0.0), INVALID_HYPERGEO), + ((NAN, 2.0, 1.0), INVALID_HYPERGEO), + ((1.0, NAN, 1.0), INVALID_HYPERGEO), ((5e-324, 1.0, 0.0), "finite"), ((1.0, nextafter(1.0, 2), 1.0), "nonfinite"), ((1.0, 2.0, NAN), "nan"), @@ -406,34 +408,34 @@ def test_matches_scipy_random(self): ((1.0, 0.5, 1.5, 0.5), "finite"), ((0.0, 1.0, 1.0, 0.0), "finite"), # z == 0 is checked after the assertions ((1.0, 2.0, 3.0, -0.0), "finite"), - ((0.0, 1.0, 1.0, 0.5), AssertionError), # a = 0: root on boundary - ((0.0, 1.0, 1.0, -0.5), AssertionError), - ((0.0, 0.0, 1.0, 0.5), AssertionError), - ((1.0, 0.0, 1.0, 0.5), AssertionError), # b = 0, c = a + ((0.0, 1.0, 1.0, 0.5), INVALID_HYPERGEO), # a = 0: root on boundary + ((0.0, 1.0, 1.0, -0.5), INVALID_HYPERGEO), + ((0.0, 0.0, 1.0, 0.5), INVALID_HYPERGEO), + ((1.0, 0.0, 1.0, 0.5), INVALID_HYPERGEO), # b = 0, c = a ((1.0, 0.0, 2.0, 0.5), "finite"), # b = 0 is fine when c > a - ((1.0, 2.0, 1.0, 0.5), AssertionError), # c == a: root on boundary - ((1.0, 1.0, 1.0, 0.5), AssertionError), - ((1.0, 2.0, nextafter(1.0, 0), 0.5), AssertionError), # c < a - ((1.0, 2.0, 0.0, 0.5), AssertionError), - ((1.0, 2.0, -1.0, 0.5), AssertionError), - ((-1.0, 2.0, 3.0, 0.5), AssertionError), # a < 0 - ((1.0, -1.0, 3.0, 0.5), AssertionError), # b < 0 - ((1.0, 2.0, 3.0, 1.0), AssertionError), # z >= 1 - ((1.0, 2.0, 3.0, nextafter(1.0, 2)), AssertionError), - ((1.0, 2.0, 3.0, 1.5), AssertionError), + ((1.0, 2.0, 1.0, 0.5), INVALID_HYPERGEO), # c == a: root on boundary + ((1.0, 1.0, 1.0, 0.5), INVALID_HYPERGEO), + ((1.0, 2.0, nextafter(1.0, 0), 0.5), INVALID_HYPERGEO), # c < a + ((1.0, 2.0, 0.0, 0.5), INVALID_HYPERGEO), + ((1.0, 2.0, -1.0, 0.5), INVALID_HYPERGEO), + ((-1.0, 2.0, 3.0, 0.5), INVALID_HYPERGEO), # a < 0 + ((1.0, -1.0, 3.0, 0.5), INVALID_HYPERGEO), # b < 0 + ((1.0, 2.0, 3.0, 1.0), INVALID_HYPERGEO), # z >= 1 + ((1.0, 2.0, 3.0, nextafter(1.0, 2)), INVALID_HYPERGEO), + ((1.0, 2.0, 3.0, 1.5), INVALID_HYPERGEO), ((1.0, 2.0, 3.0, nextafter(1.0, 0)), "finite"), - ((1.0, 2.0, 3.0, NAN), AssertionError), - ((NAN, 2.0, 3.0, 0.5), AssertionError), - ((1.0, 2.0, 3.0, -INF), AssertionError), - ((1.0, 2.0, 3.0, -1e300), AssertionError), # z / (z - 1) rounds to 1.0 - ((1.0, 2.0, 3.0, -1e16), AssertionError), + ((1.0, 2.0, 3.0, NAN), INVALID_HYPERGEO), + ((NAN, 2.0, 3.0, 0.5), INVALID_HYPERGEO), + ((1.0, 2.0, 3.0, -INF), INVALID_HYPERGEO), + ((1.0, 2.0, 3.0, -1e300), INVALID_HYPERGEO), # z / (z - 1) rounds to 1.0 + ((1.0, 2.0, 3.0, -1e16), INVALID_HYPERGEO), ((1.0, 2.0, 3.0, -9e15), "finite"), ((0.0, 1.0, 1e-300, 0.5), ZeroDivisionError), ((1e-300, 1.0, 1.0, 0.5), "finite"), - ((1.0, 1e-300, 1.0, 0.5), AssertionError), - ((1e300, 1e300, 1e300, 0.5), AssertionError), - ((1.0, 2.0, 1e300, 0.5), AssertionError), - ((1.0, 1e300, 2.0, 0.5), AssertionError), + ((1.0, 1e-300, 1.0, 0.5), INVALID_HYPERGEO), + ((1e300, 1e300, 1e300, 0.5), INVALID_HYPERGEO), + ((1.0, 2.0, 1e300, 0.5), INVALID_HYPERGEO), + ((1.0, 1e300, 2.0, 0.5), INVALID_HYPERGEO), ] diff --git a/tests/test_oracle_phasing.py b/tests/test_oracle_phasing.py index 5e163bc5..d691b997 100644 --- a/tests/test_oracle_phasing.py +++ b/tests/test_oracle_phasing.py @@ -1,7 +1,7 @@ """ Parity of the phasing functions of ``_tsdate`` with their oracles: random inputs built as in ``ExpectationPropagation``, degenerate inputs, and every -``assert``. +error. """ import _tsdate @@ -9,6 +9,12 @@ import pytest import tskit from oracle import phasing +from oracle.errors import ( + BLOCK_OUT_OF_RANGE, + PHASE_OUT_OF_RANGE, + UNPHASED_INDIVIDUAL_EDGES, + UNPHASED_LIKELIHOOD_NOT_CONSERVED, +) from oracle.helpers import INF, NAN, compare, make_ts, shrink from tsdate.phasing import block_singletons @@ -68,14 +74,14 @@ def sweep_args(ts): ), # NOTE: current behaviour, possibly a bug: reachable from real data # (one haplotype of an unphased individual missing over a region); its block is - # never flushed and the final consistency check fails with a bare AssertionError + # never flushed and the final consistency check fails pytest.param( NODES, 2, [(0, 10, 4, 0), (0, 10, 4, 2), (0, 10, 4, 3)], [(1, 0)], [1, 1], - AssertionError, + UNPHASED_INDIVIDUAL_EDGES, id="one_haplotype_edge_missing", ), ] @@ -122,7 +128,7 @@ def test_edge_cases( ): ts = make_ts(nodes, edges, mutations, 10.0, num_individuals) result = self.compare(self.args(ts, unphased)) - assert result.error is expected_error + assert result.error == expected_error @pytest.mark.parametrize( ("edges", "mutations", "unphased", "expected"), BLOCK_NUMBERING @@ -137,7 +143,7 @@ def test_size_mismatch(self, index, size): ts = make_ts(NODES, STAR, [(1, 0), (2, 1)], 10.0, 2) args = shrink(self.args(ts, [1, 1]), index, size) result = self.compare(args) - assert result.error is AssertionError + assert result.error is ValueError @pytest.mark.parametrize("fraction", [0.0, 0.5, 1.0]) @pytest.mark.parametrize("seed", range(2)) @@ -211,7 +217,7 @@ def blocks(small_ts_unphased): np.array([0.5]), np.array([0], dtype=np.int32), np.array([[0, -1]], dtype=np.int32), - AssertionError, + BLOCK_OUT_OF_RANGE, id="null_edge_in_block", ), ] @@ -228,7 +234,7 @@ def compare(*args): ) def test_small(self, lik, phase, mutation_blocks, blocks_edges, expected_error): result = self.compare(lik, phase, mutation_blocks, blocks_edges) - assert result.error is expected_error + assert result.error == expected_error @pytest.mark.parametrize("mode", ["fractional", "mixed"]) @pytest.mark.parametrize("seed", range(3)) @@ -247,7 +253,7 @@ def test_phase_out_of_range(self, blocks, value): phase = np.full(mutation_blocks.size, 0.5) phase[np.flatnonzero(mutation_blocks >= 0)[0]] = value result = self.compare(lik, phase, mutation_blocks, block_edges) - assert result.error is AssertionError + assert result.error == PHASE_OUT_OF_RANGE @pytest.mark.parametrize("value", [NAN, 7.0]) def test_phase_ignored_without_block(self, blocks, value): @@ -260,13 +266,13 @@ def test_phase_ignored_without_block(self, blocks, value): def test_nan_phase(self, blocks): # NOTE: current behaviour, possibly a bug: a NaN phase on a # blocked mutation is skipped, leaving its singleton unallocated, so the - # final `np.isclose` check fails (a bare AssertionError). It only passes if - # the likelihoods happen to total one less + # final `np.isclose` check fails. It only passes if the likelihoods happen to + # total one less _, lik, mutation_blocks, block_edges = blocks phase = np.full(mutation_blocks.size, 0.5) phase[np.flatnonzero(mutation_blocks >= 0)[0]] = NAN result = self.compare(lik, phase, mutation_blocks, block_edges) - assert result.error is AssertionError + assert result.error == UNPHASED_LIKELIHOOD_NOT_CONSERVED lik = lik.copy() lik[block_edges[0, 0], 0] -= 1.0 result = self.compare(lik, phase, mutation_blocks, block_edges) @@ -280,7 +286,7 @@ def test_blocks_without_singletons(self, blocks, case): phase = np.full(size, 0.5) mutation_blocks = np.full(size, tskit.NULL, dtype=np.int32) result = self.compare(lik, phase, mutation_blocks, block_edges) - assert result.error is AssertionError + assert result.error == UNPHASED_LIKELIHOOD_NOT_CONSERVED @pytest.mark.parametrize("case", ["phase", "blocks_transposed"]) def test_size_mismatch(self, blocks, case): @@ -291,7 +297,7 @@ def test_size_mismatch(self, blocks, case): else: block_edges = np.ascontiguousarray(block_edges.T) result = self.compare(lik, phase, mutation_blocks, block_edges) - assert result.error is AssertionError + assert result.error is ValueError # samples 0, 1, 2 (time 0), internal nodes 3 (time 1) and 4 (time 2); node 3 is a @@ -372,7 +378,7 @@ def test_size_mismatch(self, freq_ts, index, size): nodes_sample = np.ones((freq_ts.num_nodes, 1), dtype=bool) args = shrink(sweep_args(freq_ts), index, size) result = self.compare(nodes_sample, args) - assert result.error is AssertionError + assert result.error is ValueError @pytest.mark.parametrize("num_sets", [1, 4]) @pytest.mark.parametrize("seed", range(2)) diff --git a/tests/test_oracle_rescaling.py b/tests/test_oracle_rescaling.py index e0824c71..262cb067 100644 --- a/tests/test_oracle_rescaling.py +++ b/tests/test_oracle_rescaling.py @@ -1,14 +1,24 @@ """ Parity of the rescaling functions of ``_tsdate`` with their oracles: random inputs, inputs from ``ExpectationPropagation.rescale`` on simulated tree sequences, -degenerate inputs, and every ``assert``/``raise``. +degenerate inputs, and every error. """ import _tsdate import numpy as np import pytest -from oracle import approx as oracle_approx from oracle import rescaling +from oracle.errors import ( + INVALID_POSTERIOR, + INVALID_QUANTILE_WIDTH, + NEGATIVE_CHANGEPOINT_PARAMETER, + NO_POSTERIORS, + NON_INCREASING_BREAKPOINTS, + NONPOSITIVE_INTERVALS, + TIME_BELOW_FIRST_BREAKPOINT, + UNSORTED_QUANTILES, + ZERO_EDGE_SPAN, +) from oracle.helpers import ( INF, NAN, @@ -24,7 +34,6 @@ from tsdate.variational import ExpectationPropagation BREAKS_MSG = "non-increasing time breakpoints" -KLFailed = oracle_approx.KLMinimizationFailedError @pytest.fixture(params=["small_ts_unphased", "small_ts_historical"]) @@ -109,8 +118,8 @@ def piecewise_rates(rng, size, num_pieces, offset_range, rate_range): pytest.param([0.0, 5.0, 0.0, 5.0, 0.0], 3, "finite", id="zeros_in_middle"), pytest.param([1.0] * 4, 4, "finite", id="quantiles_exact"), pytest.param([1.0] * 4, 2, "finite", id="quantiles_exact_half"), - pytest.param([1.0, 2.0], 0, AssertionError, id="zero_epochs"), - pytest.param([1.0, 2.0], -1, AssertionError, id="negative_epochs"), + pytest.param([1.0, 2.0], 0, NONPOSITIVE_INTERVALS, id="zero_epochs"), + pytest.param([1.0, 2.0], -1, NONPOSITIVE_INTERVALS, id="negative_epochs"), # NOTE: current behaviour, possibly a bug: with no counts the # cumulative distribution is 0 / 0 = NaN, which `searchsorted` places last, so # every breakpoint but the last is -1 @@ -190,11 +199,37 @@ def test_random(self, seed, mode): # log(0) is -inf and 0 * -inf is NaN, so the loss is NaN pytest.param([0.0] * 3, [1.0] * 3, 0.0, 0.0, 0.0, "finite", id="zero_counts"), pytest.param([0.0] * 3, [1.0] * 3, 2.0, 1.0, 0.0, "finite", id="zero_counts_min"), - pytest.param(COUNTS, ONES, -1.0, 0.0, 0.0, AssertionError, id="negative_penalty"), - pytest.param(COUNTS, ONES, NAN, 0.0, 0.0, AssertionError, id="nan_penalty"), - pytest.param(COUNTS, ONES, 2.0, -1.0, 0.0, AssertionError, id="negative_min_counts"), - pytest.param(COUNTS, ONES, 2.0, 0.0, -1.0, AssertionError, id="negative_min_offset"), - pytest.param(COUNTS, ONES[:3], 2.0, 0.0, 0.0, AssertionError, id="size_mismatch"), + pytest.param( + COUNTS, + ONES, + -1.0, + 0.0, + 0.0, + NEGATIVE_CHANGEPOINT_PARAMETER, + id="negative_penalty", + ), + pytest.param( + COUNTS, ONES, NAN, 0.0, 0.0, NEGATIVE_CHANGEPOINT_PARAMETER, id="nan_penalty" + ), + pytest.param( + COUNTS, + ONES, + 2.0, + -1.0, + 0.0, + NEGATIVE_CHANGEPOINT_PARAMETER, + id="negative_min_counts", + ), + pytest.param( + COUNTS, + ONES, + 2.0, + 0.0, + -1.0, + NEGATIVE_CHANGEPOINT_PARAMETER, + id="negative_min_offset", + ), + pytest.param(COUNTS, ONES[:3], 2.0, 0.0, 0.0, ValueError, id="size_mismatch"), ] @@ -308,7 +343,7 @@ def test_size_mismatch(self, index, size): ts = make_ts(COUNT_NODES, COUNT_EDGES, [(1, 0), (2, 1)], 10.0) args = shrink(count_args(ts, False), index, size) result = self.compare(args) - assert result.error is AssertionError + assert result.error is ValueError @pytest.mark.parametrize("size_biased", [False, True]) def test_simulated(self, sim_ts, size_biased): @@ -362,16 +397,16 @@ def area_args(nodes_time, likelihoods, parents, children): None, id="ties_and_unsorted_times", ), - pytest.param([0, 0, 1], LIK, [2], [0, 1], AssertionError, id="parents_mismatch"), + pytest.param([0, 0, 1], LIK, [2], [0, 1], ValueError, id="parents_mismatch"), pytest.param( - [0, 0, 1], [[1, 1]] * 3, [2, 2], [0, 1], AssertionError, id="likelihood_rows" + [0, 0, 1], [[1, 1]] * 3, [2, 2], [0, 1], ValueError, id="likelihood_rows" ), pytest.param( [0, 0, 1], [[1, 1, 1]] * 2, [2, 2], [0, 1], - AssertionError, + ValueError, id="likelihood_columns", ), ] @@ -449,8 +484,8 @@ def historical(k, fixed): pytest.param(chain(2), "finite", id="two_intervals"), pytest.param(chain(3), "finite", id="as_many_as_epochs"), pytest.param(chain(10000), "finite", id="more_than_epochs"), - pytest.param(chain(0), AssertionError, id="zero_intervals"), - pytest.param(chain(-1), AssertionError, id="negative_intervals"), + pytest.param(chain(0), NONPOSITIVE_INTERVALS, id="zero_intervals"), + pytest.param(chain(-1), NONPOSITIVE_INTERVALS, id="negative_intervals"), # NOTE: current behaviour, possibly a bug: `nodes_fixed` is only # size-checked, so which nodes are fixed does not matter pytest.param(chain(3, [0, 0, 0, 0]), "finite", id="no_fixed_nodes"), @@ -488,15 +523,15 @@ def historical(k, fixed): # interval has zero span (a zero mutation rate) or there are no edges pytest.param( timescale_args([0, 0, 1.0], [[2, 0], [1, 0]], [1, 1, 0], [2, 2], [0, 1], 1), - AssertionError, + ZERO_EDGE_SPAN, id="zero_edge_span", ), pytest.param( - timescale_args([0.0, 1.0], [], [1, 1], [], [], 1), AssertionError, id="no_edges" + timescale_args([0.0, 1.0], [], [1, 1], [], [], 1), ZERO_EDGE_SPAN, id="no_edges" ), pytest.param( timescale_args([0.0, 0.0, 0.0], [[1, 10], [1, 10]], [1, 1, 1], [2, 2], [0, 1], 1), - AssertionError, + ZERO_EDGE_SPAN, id="all_nodes_at_time_zero", ), ] @@ -530,7 +565,7 @@ def test_size_mismatch(self, which): else: args[1] = np.ones((3, 3)) result = self.compare(*args) - assert result.error is AssertionError + assert result.error is ValueError @pytest.mark.parametrize("max_intervals", [3, 1000]) @pytest.mark.parametrize("seed", range(2)) @@ -583,22 +618,52 @@ def test_simulated(self, ep, max_intervals): pytest.param([0.0, 0.5, 7.0], None, [0.0], [2.0], "finite", id="single_scaled"), pytest.param([0.0, 0.3, 1.0], None, [0.0, 5.0], [0.0, 5.0], "finite", id="identity"), pytest.param( - [0.5], None, [0.0, 1.0, 3.0], [0.0, 2.0, 2.0], ValueError, id="flat_rescaled" + [0.5], + None, + [0.0, 1.0, 3.0], + [0.0, 2.0, 2.0], + NON_INCREASING_BREAKPOINTS, + id="flat_rescaled", ), pytest.param( - [0.5], None, [0.0, 1.0, 3.0], [0.0, 2.0, 1.0], ValueError, id="decreasing" + [0.5], + None, + [0.0, 1.0, 3.0], + [0.0, 2.0, 1.0], + NON_INCREASING_BREAKPOINTS, + id="decreasing", ), pytest.param( - [0.5], None, [0.0, 1.0, 1.0], [0.0, 2.0, 3.0], ValueError, id="flat_original" + [0.5], + None, + [0.0, 1.0, 1.0], + [0.0, 2.0, 3.0], + NON_INCREASING_BREAKPOINTS, + id="flat_original", ), pytest.param( - [0.5], None, [0.0, 2.0, 1.0], [0.0, 1.0, 2.0], ValueError, id="decr_original" + [0.5], + None, + [0.0, 2.0, 1.0], + [0.0, 1.0, 2.0], + NON_INCREASING_BREAKPOINTS, + id="decr_original", ), pytest.param( - [0.5], None, [0.0, 1.0, NAN], [0.0, 1.0, 2.0], ValueError, id="nan_original" + [0.5], + None, + [0.0, 1.0, NAN], + [0.0, 1.0, 2.0], + NON_INCREASING_BREAKPOINTS, + id="nan_original", ), pytest.param( - [0.5], None, [0.0, 1.0, 2.0], [0.0, 1.0, NAN], ValueError, id="nan_rescaled" + [0.5], + None, + [0.0, 1.0, 2.0], + [0.0, 1.0, NAN], + NON_INCREASING_BREAKPOINTS, + id="nan_rescaled", ), ] @@ -664,7 +729,9 @@ def test_simulated(self, ep): POSTERIORS, {"quantile_width": 1 - 1e-9}, "finite", id="widest_quantile" ), *[ - pytest.param(POSTERIORS, {"quantile_width": w}, AssertionError, id=f"width_{w}") + pytest.param( + POSTERIORS, {"quantile_width": w}, INVALID_QUANTILE_WIDTH, id=f"width_{w}" + ) for w in [0.0, 1.0, -0.1, 1.5, NAN, INF] ], pytest.param(POSTERIORS, {"fixed": [1, 0, 1, 0]}, "nan", id="some_fixed"), @@ -674,9 +741,9 @@ def test_simulated(self, ep): [[-5.0, -5.0], [1.0, 1.0]], {"fixed": [1, 0]}, "nan", id="fixed_negative" ), pytest.param([[NAN, NAN], [1.0, 1.0]], {"fixed": [1, 0]}, "nan", id="fixed_nan"), - # NOTE: current behaviour, possibly a bug: no posteriors raises - # numpy's "zero-size array" ValueError from a debug assertion - pytest.param(np.zeros((0, 2)), {"fixed": []}, ValueError, id="no_posteriors"), + # NOTE: current behaviour, possibly a bug: no posteriors is an error, + # with numpy's "zero-size array" message + pytest.param(np.zeros((0, 2)), {"fixed": []}, NO_POSTERIORS, id="no_posteriors"), *[ pytest.param([row], {}, "finite", id=f"valid_{i}") for i, row in enumerate( @@ -685,7 +752,7 @@ def test_simulated(self, ep): ], # NOTE: current behaviour, possibly a bug: for a shape this close # to -1 the lower quantile underflows to zero and the division by it is an error - # (IEEE would give inf), rather than KLMinimizationFailedError + # (IEEE would give inf), rather than a failed gamma fit *[ pytest.param([row], {}, ZeroDivisionError, id=f"shape_near_minus_one_{i}") for i, row in enumerate([[-0.9999, 1.0], [-1 + 1e-12, 1.0], [-0.9999999, 2.0]]) @@ -693,9 +760,9 @@ def test_simulated(self, ep): pytest.param([[1.0, INF]], {}, ZeroDivisionError, id="infinite_rate"), # NOTE: current behaviour, possibly a bug: the error leaks out of # `approximate_gamma_iqr` - pytest.param([[INF, 1.0]], {}, KLFailed, id="infinite_shape"), + pytest.param([[INF, 1.0]], {}, UNSORTED_QUANTILES, id="infinite_shape"), *[ - pytest.param([row], {}, AssertionError, id=f"invalid_{i}") + pytest.param([row], {}, INVALID_POSTERIOR, id=f"invalid_{i}") for i, row in enumerate( [[-1.0, 1.0], [1.0, 0.0], [1.0, -1.0], [NAN, 1.0], [1.0, NAN], [-INF, 1.0]] ) @@ -703,13 +770,16 @@ def test_simulated(self, ep): pytest.param( [[1.0, 1.0], [2.0, 3.0], [0.0, 1.0], [-1.0, 2.0]], {}, - AssertionError, + INVALID_POSTERIOR, id="one_invalid", ), # all quantiles map to one point beyond the last break: zero interquantile range pytest.param([[1.0, 0.001], [1.0, 1e-9]], {}, "finite", id="beyond_last_break"), pytest.param( - POSTERIORS, {"original": [0.5, 1.0, 3.0]}, AssertionError, id="below_first" + POSTERIORS, + {"original": [0.5, 1.0, 3.0]}, + TIME_BELOW_FIRST_BREAKPOINT, + id="below_first", ), # NOTE: current behaviour, possibly a bug: `max_shape=0` gives # shape -1 (improper) and zero rate @@ -720,7 +790,12 @@ def test_simulated(self, ep): pytest.param(POSTERIORS, {"max_shape": INF}, "finite", id="max_shape_inf"), pytest.param(POSTERIORS, {"max_shape": NAN}, "finite", id="max_shape_nan"), *[ - pytest.param(POSTERIORS, {"original": o, "rescaled": r}, ValueError, id=i) + pytest.param( + POSTERIORS, + {"original": o, "rescaled": r}, + NON_INCREASING_BREAKPOINTS, + id=i, + ) for i, o, r in [ ("original_flat", [0.0, 1.0, 1.0], RESCALED), ("rescaled_flat", ORIGINAL, [0.0, 2.0, 2.0]), @@ -732,7 +807,7 @@ def test_simulated(self, ep): pytest.param( [[-5.0, 1.0]], {"original": [0.0, 0.0], "rescaled": [0.0, 1.0]}, - ValueError, + NON_INCREASING_BREAKPOINTS, id="bad_breaks_before_posteriors", ), # a single (zero-length) interval: everything is beyond the last break @@ -745,11 +820,11 @@ def test_simulated(self, ep): pytest.param( POSTERIORS, {"original": [0.0], "rescaled": [4.0]}, "finite", id="single_break" ), - pytest.param(POSTERIORS, {"fixed": [0] * 3}, AssertionError, id="fixed_mismatch"), + pytest.param(POSTERIORS, {"fixed": [0] * 3}, ValueError, id="fixed_mismatch"), pytest.param( POSTERIORS, {"original": [0.0, 1.0], "rescaled": RESCALED}, - AssertionError, + ValueError, id="breaks_mismatch", ), ] diff --git a/tests/test_oracle_util.py b/tests/test_oracle_util.py index 1bd599ec..6f5f64d9 100644 --- a/tests/test_oracle_util.py +++ b/tests/test_oracle_util.py @@ -1,6 +1,6 @@ """ Parity of the tree sequence utilities of ``_tsdate`` with their oracles: simulated tree -sequences, degenerate inputs, and every ``assert``. +sequences, degenerate inputs, and every error. """ import _tsdate @@ -8,6 +8,7 @@ import pytest import tskit from oracle import util +from oracle.errors import FIXED_NODES_VIOLATE_CONSTRAINT, MUTATION_NODE_NOT_IN_TREE from oracle.helpers import NAN, assert_outcome, b1, compare, f64, i32, make_ts, shrink @@ -80,7 +81,7 @@ def test_edge_cases(self, parent, child, left, right, excluded, expected): def test_size_mismatch(self, index, size): args = [i32(2, 2), i32(0, 1), f64(0, 0), f64(10, 10), b1(1, 1, 0)] result = self.compare(*shrink(args, index, size)) - assert result.error is AssertionError + assert result.error is ValueError def test_simulated(self, sim_ts): ts = sim_ts @@ -143,7 +144,12 @@ def relabel_args(ts): GAP_NODES, GAP_EDGES, [(1, 2), (10.0, 2)], 20.0, None, id="beyond_last_edge" ), pytest.param( - GAP_NODES, BINARY_EDGES, [(1, 3)], 10.0, AssertionError, id="node_not_in_tree" + GAP_NODES, + BINARY_EDGES, + [(1, 3)], + 10.0, + MUTATION_NODE_NOT_IN_TREE, + id="node_not_in_tree", ), ] @@ -159,7 +165,7 @@ def compare(args): def test_edge_cases(self, nodes, edges, mutations, length, expected_error): ts = make_ts(nodes, edges, mutations, length) result = self.compare(relabel_args(ts)) - assert result.error is expected_error + assert result.error == expected_error def test_mutations_on_split_nodes(self): mutations = [(0.5, 0), (1, 2), (2, 3), (5, 0), (7, 2), (8, 3)] @@ -173,7 +179,7 @@ def test_mutations_on_split_nodes(self): def test_size_mismatch(self, index, size): ts = make_ts(GAP_NODES, GAP_EDGES, [(1, 2), (7, 2)], 10.0) result = self.compare(shrink(relabel_args(ts), index, size)) - assert result.error is AssertionError + assert result.error is ValueError def test_simulated(self, sim_ts): args = relabel_args(sim_ts) @@ -200,10 +206,19 @@ def test_simulated(self, sim_ts): pytest.param([0.0, 1.0], [1, 0], [0], [1], 0.1, 100, "finite", id="fixed_parent"), pytest.param([0.0, 1.0], [0, 1], [0], [1], 0.1, 100, "finite", id="fixed_child"), # NOTE: current behaviour, possibly a bug: two fixed nodes on a - # violated edge fail an assertion (reachable via `constrain_ages` with + # violated edge are an error (reachable via `constrain_ages` with # inconsistent ancient sample ages); with no iterations the forcing step # silently changes the age of a fixed node - pytest.param([0.0, 1.0], [1, 1], [0], [1], 0.1, 100, AssertionError, id="both_fixed"), + pytest.param( + [0.0, 1.0], + [1, 1], + [0], + [1], + 0.1, + 100, + FIXED_NODES_VIOLATE_CONSTRAINT, + id="both_fixed", + ), pytest.param([0.0, 1.0], [1, 1], [0], [1], 0.1, 0, "finite", id="both_fixed_forced"), pytest.param([0.0, 1.0], [1, 0], [], [], 0.1, 10, "finite", id="no_edges"), pytest.param([], [], [], [], 0.1, 10, "finite", id="no_nodes"), @@ -267,7 +282,7 @@ def test_edge_cases( ) def test_size_mismatch(self, args): result = self.compare(self.args(*args, 0.1, 3)) - assert result.error is AssertionError + assert result.error is ValueError @pytest.mark.parametrize("mode", ["iterated", "forced"]) @pytest.mark.parametrize("seed", range(2)) diff --git a/tests/test_oracle_variational.py b/tests/test_oracle_variational.py index 34fd7267..16623fcf 100644 --- a/tests/test_oracle_variational.py +++ b/tests/test_oracle_variational.py @@ -21,13 +21,21 @@ import tskit from oracle import ep_state, variational from oracle.ep_state import BRANCHES, SNAPSHOT_SPECS, tiny_snapshot +from oracle.errors import ( + INVALID_DAMPING, + INVALID_MAX_SHAPE, + INVALID_MIN_STEP, + INVALID_NODE_POSTERIOR, + NONPOSITIVE_PENALTY, + TWIN_EDGE_IN_PHASED_PASS, + ZERO_DIVISION, +) from oracle.helpers import ( INF, NAN, assert_same_outcome, assert_same_values, compare, - expected_error, f64, kind, log_uniform, @@ -99,6 +107,14 @@ def unphased_name(ts_name): return ts_name == "small_ts_unphased" +def raises_zero_division(): + """ + ``pytest.raises`` for the library's float division by zero + """ + message = _tsdate.strerror(ZERO_DIVISION) + return pytest.raises(_tsdate.LibraryError, match=re.escape(message)) + + class TestRescaleFactors: @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_unphased"]) @pytest.mark.parametrize("scale", ["seed0", "seed1", 1e-160, 1e100]) @@ -163,21 +179,21 @@ def test_assemble_factors(self, snaps, scaled_snap, ts_name): ("y1_nan_a_damped", f64(1, 1), f64(8, NAN), 0.5, "finite"), ("y0_minus_inf", f64(1, 1), f64(-INF, 0), 0.5, "finite"), ("y1_minus_inf", f64(1, 1), f64(0, -INF), 0.5, "finite"), - # asserts: `s` is checked by the callers (direct calls only) - ("s_zero", f64(1, 1), f64(0, 0), 0.0, AssertionError), - ("s_one", f64(1, 1), f64(0, 0), 1.0, AssertionError), - ("s_negative", f64(1, 1), f64(0, 0), -0.5, AssertionError), - ("s_nan", f64(1, 1), f64(0, 0), NAN, AssertionError), + # `s` is checked by the callers (direct calls only) + ("s_zero", f64(1, 1), f64(0, 0), 0.0, INVALID_MIN_STEP), + ("s_one", f64(1, 1), f64(0, 0), 1.0, INVALID_MIN_STEP), + ("s_negative", f64(1, 1), f64(0, 0), -0.5, INVALID_MIN_STEP), + ("s_nan", f64(1, 1), f64(0, 0), NAN, INVALID_MIN_STEP), # `0 < x[0] + 1` and `0 < x[1]`: reachable from improper or NaN posteriors - ("x0_minus_one", f64(-1, 1), f64(0, 0), 0.5, AssertionError), - ("x0_nan", f64(NAN, 1), f64(0, 0), 0.5, AssertionError), - ("x1_zero", f64(1, 0), f64(0, 0), 0.5, AssertionError), - ("x1_negative", f64(1, -1), f64(0, 0), 0.5, AssertionError), - ("x1_nan", f64(1, NAN), f64(0, 0), 0.5, AssertionError), - ("x_zero_y_not", f64(0, 0), f64(1, 1), 0.5, AssertionError), + ("x0_minus_one", f64(-1, 1), f64(0, 0), 0.5, INVALID_NODE_POSTERIOR), + ("x0_nan", f64(NAN, 1), f64(0, 0), 0.5, INVALID_NODE_POSTERIOR), + ("x1_zero", f64(1, 0), f64(0, 0), 0.5, INVALID_NODE_POSTERIOR), + ("x1_negative", f64(1, -1), f64(0, 0), 0.5, INVALID_NODE_POSTERIOR), + ("x1_nan", f64(1, NAN), f64(0, 0), 0.5, INVALID_NODE_POSTERIOR), + ("x_zero_y_not", f64(0, 0), f64(1, 1), 0.5, INVALID_NODE_POSTERIOR), # `0 < d` fails when d underflows or y[0] is NaN - ("d_underflow", f64(1, 1e-300), f64(0, 1e300), 0.5, AssertionError), - ("y0_nan", f64(1, 1), f64(NAN, 0), 0.5, AssertionError), + ("d_underflow", f64(1, 1e-300), f64(0, 1e300), 0.5, INVALID_DAMPING), + ("y0_nan", f64(1, 1), f64(NAN, 0), 0.5, INVALID_DAMPING), ] RESCALE_TABLE = [ # (id, x, s, kind); branches `1 + x0 > s` and `1 + x0 < 1 / s` @@ -196,16 +212,16 @@ def test_assemble_factors(self, snaps, scaled_snap, ts_name): ("infinite_rate", f64(99, INF), 10.0, "finite"), ("infinite_shape", f64(INF, 1), 10.0, "finite"), # NOTE: current behaviour, possibly a bug: with `max_shape = 1` - # (allowed by the asserts in `propagate_*`) the factor is 0 and wipes out the + # (allowed by the checks in `propagate_*`) the factor is 0 and wipes out the # posterior. ("s_one_upper", f64(1, 1), 1.0, "finite"), ("s_one_lower", f64(-0.5, 1), 1.0, "finite"), - # asserts (reachable as for `damp`) - ("x0_minus_one", f64(-1, 1), 10.0, AssertionError), - ("x0_nan", f64(NAN, 1), 10.0, AssertionError), - ("x1_zero", f64(1, 0), 10.0, AssertionError), - ("x1_negative", f64(1, -1), 10.0, AssertionError), - ("x1_nan", f64(1, NAN), 10.0, AssertionError), + # reachable as for `damp` + ("x0_minus_one", f64(-1, 1), 10.0, INVALID_NODE_POSTERIOR), + ("x0_nan", f64(NAN, 1), 10.0, INVALID_NODE_POSTERIOR), + ("x1_zero", f64(1, 0), 10.0, INVALID_NODE_POSTERIOR), + ("x1_negative", f64(1, -1), 10.0, INVALID_NODE_POSTERIOR), + ("x1_nan", f64(1, NAN), 10.0, INVALID_NODE_POSTERIOR), ] # fmt: on @@ -234,7 +250,7 @@ def test_infinite_posterior_zero_message(self, which): # unreachable without a prior failure. x = f64(1, 1) x[which] = INF - with pytest.raises(expected_error(ZeroDivisionError)): + with raises_zero_division(): _tsdate.damp(*x, 0.0, 0.0, 0.5) @@ -256,8 +272,8 @@ def test_random(self, seed): def test_zero_shape_offset_cap_below_one(self): # C reports the division by zero; the oracle, on NumPy scalars, returns - # -inf. Direct call only: `propagate_*` assert `max_shape >= 1`. - with pytest.raises(expected_error(ZeroDivisionError)): + # -inf. Direct call only: `propagate_*` check `max_shape >= 1`. + with raises_zero_division(): _tsdate.rescale(0.0, 1.0, 0.5) @@ -351,17 +367,17 @@ def test_single_edge(self, branch, case): if "sideways" in branch and case == "projection_fails": # `sideways_moments` divides by zero for an astronomically large mutation # target: C reports it where the oracle returns NaN and skips. - with pytest.raises(expected_error(ZeroDivisionError)): + with raises_zero_division(): ep_state.run_likelihood(_tsdate, snap, snap.unphased, **kwargs) else: compare_runs(ep_state.run_likelihood, snap, snap.unphased, **kwargs) def test_twin_edge_in_phased_pass(self): - # p == c is only valid for blocks; `twin_projection` asserts `unphased`. + # p == c is only valid for blocks; `twin_projection` checks `unphased`. # Direct call only: edges never have p == c in a tree sequence. snap = tiny_snapshot("twin") result = compare_runs(ep_state.run_likelihood, snap, False) - assert kind(result) is AssertionError + assert kind(result) == TWIN_EDGE_IN_PHASED_PASS class TestPropagateLikelihood: @@ -461,7 +477,7 @@ def test_min_step(self, snaps, ts_name, min_step): @pytest.mark.parametrize("multiplier", [1e12, 1e300], ids=lambda v: f"y*{v:g}") def test_extreme_counts(self, snaps, multiplier): # 1e12: projection failures are skipped (NaN lognorm). 1e300: a posterior - # becomes NaN and the next `damp` asserts `0 < x[0] + 1`, + # becomes NaN and the next `damp` fails its check `0 < x[0] + 1`, # reachable from real data (~1e300 mutations on an edge). snap = snaps["small_ts"] likelihoods = snap.edge_likelihoods * [multiplier, 1.0] @@ -475,27 +491,29 @@ def test_extreme_counts(self, snaps, multiplier): ) @pytest.mark.parametrize( - "kwargs", + ("kwargs", "expected"), [ - pytest.param(dict(max_shape=up(1.0, 0.0)), id="max_shape_below_one"), - pytest.param(dict(max_shape=0.0), id="max_shape_zero"), - pytest.param(dict(max_shape=NAN), id="max_shape_nan"), - pytest.param(dict(min_step=0.0), id="min_step_zero"), - pytest.param(dict(min_step=1.0), id="min_step_one"), - pytest.param(dict(min_step=-0.1), id="min_step_negative"), - pytest.param(dict(min_step=1.5), id="min_step_above_one"), - pytest.param(dict(min_step=NAN), id="min_step_nan"), + pytest.param( + dict(max_shape=up(1.0, 0.0)), INVALID_MAX_SHAPE, id="max_shape_below_one" + ), + pytest.param(dict(max_shape=0.0), INVALID_MAX_SHAPE, id="max_shape_zero"), + pytest.param(dict(max_shape=NAN), INVALID_MAX_SHAPE, id="max_shape_nan"), + pytest.param(dict(min_step=0.0), INVALID_MIN_STEP, id="min_step_zero"), + pytest.param(dict(min_step=1.0), INVALID_MIN_STEP, id="min_step_one"), + pytest.param(dict(min_step=-0.1), INVALID_MIN_STEP, id="min_step_negative"), + pytest.param(dict(min_step=1.5), INVALID_MIN_STEP, id="min_step_above_one"), + pytest.param(dict(min_step=NAN), INVALID_MIN_STEP, id="min_step_nan"), ], ) - def test_invalid_parameters(self, snaps, kwargs): + def test_invalid_parameters(self, snaps, kwargs, expected): # reachable from user input (`max_shape`, `min_step` of `iterate`/`infer`): - # parameter errors in the C library, not internal asserts + # parameter errors in the C library, not internal invariants snap = snaps["small_ts"] order = snap.edge_order[:10] assert_run_kind( ep_state.run_likelihood, snap, - AssertionError, + expected, False, order=order, **kwargs, @@ -540,7 +558,7 @@ def call(module): lambda: call(_tsdate), lambda: call(variational), ) - assert kind(result) is AssertionError + assert kind(result) is ValueError class TestPropagateLikelihoodTinyScale: @@ -677,26 +695,25 @@ def negative_cavity_rate(snap): snap.fields["node"][free, MIXPRIOR, 1] = snap.node_posterior[free, 1] + 1.0 return snap - @pytest.mark.parametrize( - "case", - [ - # `assert penalty > 0` fails when the mean of shape / rate is infinite or - # negative: free nodes whose cavity has zero rate (fixed leaves, or a root - # where every update was skipped) or negative rate - "all_nodes", - "leaves", - "zero_posterior", - "negative_cavity_rate", - # reachable from user input - "max_shape_below_one", - "max_shape_zero", - "max_shape_nan", - # direct calls only - "free_too_short", - "free_too_long", - ], - ) - def test_assertions(self, snaps, case): + ERRORS = { + # `penalty > 0` fails when the mean of shape / rate is infinite or negative: + # free nodes whose cavity has zero rate (fixed leaves, or a root where every + # update was skipped) or negative rate + "all_nodes": NONPOSITIVE_PENALTY, + "leaves": NONPOSITIVE_PENALTY, + "zero_posterior": NONPOSITIVE_PENALTY, + "negative_cavity_rate": NONPOSITIVE_PENALTY, + # reachable from user input + "max_shape_below_one": INVALID_MAX_SHAPE, + "max_shape_zero": INVALID_MAX_SHAPE, + "max_shape_nan": INVALID_MAX_SHAPE, + # direct calls only + "free_too_short": ValueError, + "free_too_long": ValueError, + } + + @pytest.mark.parametrize("case", ERRORS) + def test_errors(self, snaps, case): snap = snaps["small_ts"] free = snap.unconstrained_roots kwargs = {} @@ -718,13 +735,13 @@ def test_assertions(self, snaps, case): free = free[:-1] else: free = np.append(free, True) - assert_run_kind(ep_state.run_prior, snap, AssertionError, free, **kwargs) + assert_run_kind(ep_state.run_prior, snap, self.ERRORS[case], free, **kwargs) - def test_penalty_assert_reachable_from_ep(self, fresh): + def test_penalty_error_reachable_from_ep(self, fresh): # NOTE: current behaviour, possibly a bug: a likelihood pass in # which every update is skipped (a huge mutational target) leaves the roots # with a zero posterior, so that `iterate(regularise=True)` fails the - # `penalty > 0` assert (an AssertionError, not NaN). + # `penalty > 0` check (an error, not NaN). base = fresh["small_ts"].copy() base.edge_likelihoods = base.edge_likelihoods * [1.0, 1e300] @@ -734,7 +751,7 @@ def run(module): return ep_state.run_prior(module, step, step.unconstrained_roots) result = compare(lambda: run(_tsdate), lambda: run(variational)) - assert kind(result) is AssertionError + assert kind(result) == NONPOSITIVE_PENALTY class TestPropagateMutations: @@ -798,13 +815,13 @@ def test_single_edge(self, branch, case): if fails and "sideways" in branch: # as in propagate_likelihood: C reports a division by zero in # `*_sideways_moments` - with pytest.raises(expected_error(ZeroDivisionError)): + with raises_zero_division(): ep_state.run_mutations(_tsdate, snap, snap.unphased) else: compare_runs(ep_state.run_mutations, snap, snap.unphased) def test_twin_in_phased_pass(self): - # unlike propagate_likelihood, there is no `unphased` assert for p == c; the + # unlike propagate_likelihood, there is no `unphased` check for p == c; the # twin projection is used as is (direct call only: edges never have p == c) snap = tiny_snapshot("twin") snap.mutation_blocks[:] = tskit.NULL @@ -836,7 +853,7 @@ def test_shape_mismatches(self, snaps, change): kwargs = dict(edges=snap.mutation_edges[:-1]) else: kwargs = dict(posterior=snap.node_posterior[:-1]) - assert_run_kind(ep_state.run_mutations, snap, AssertionError, False, **kwargs) + assert_run_kind(ep_state.run_mutations, snap, ValueError, False, **kwargs) class TestMultiSweep: diff --git a/tests/test_python_c_approx.py b/tests/test_python_c_approx.py index f178434e..658547f8 100644 --- a/tests/test_python_c_approx.py +++ b/tests/test_python_c_approx.py @@ -12,7 +12,7 @@ from oracle import approx from oracle.helpers import compare -# error code: the message of the oracle's KLMinimizationFailedError (or assertion) +# error code: message APPROX_ERRORS = { -6: "Nonpositive or nonfinite moments", -7: "log E[t] <= E[log t] violates Jensen's inequality", @@ -49,10 +49,6 @@ def test_accepts_lists_and_integers(self): np.array([1.0, 2.0]), np.array([1.0, 2.0]) ) - def test_size_mismatch(self): - with pytest.raises(ValueError, match="Array sizes are not equal"): - _tsdate.average_gammas(np.ones(2), np.ones(3)) - @pytest.mark.parametrize("shape", [(), (2, 2)]) def test_wrong_dimension(self, shape): with pytest.raises(ValueError): @@ -70,10 +66,6 @@ def test_wrong_number_of_arguments(self): with pytest.raises(TypeError): _tsdate.average_gammas(np.ones(2)) - def test_library_error(self): - with pytest.raises(_tsdate.LibraryError, match="division by zero"): - _tsdate.average_gammas(np.array([]), np.array([])) - # Failures of the quantile fit (found by random search), each at a different step of # the Newton iteration: the lower quantile underflows to zero, its square underflows diff --git a/tests/test_python_c_rescaling.py b/tests/test_python_c_rescaling.py index d349eccb..5b569d2f 100644 --- a/tests/test_python_c_rescaling.py +++ b/tests/test_python_c_rescaling.py @@ -8,6 +8,7 @@ import numpy as np import pytest from oracle import rescaling +from oracle.errors import TIME_BELOW_FIRST_BREAKPOINT from oracle.helpers import compare NODES_TIME = np.array([0.0, 0.0, 1.0, 2.0]) @@ -58,30 +59,6 @@ def test_posterior_columns(self): 1.0, ) - def test_poisson_sizes(self): - with pytest.raises(ValueError, match="same size"): - _tsdate.poisson_changepoints(np.ones(3), np.ones(2), 2.0, 0.0, 0.0) - - def test_count_mutations_sizes(self): - args = [ - np.zeros(2, dtype=bool), - np.zeros(1, dtype=np.int32), - np.zeros(1), - np.zeros(1, dtype=np.int32), - np.zeros(1, dtype=np.int32), - np.zeros(1), - np.zeros(1), - np.zeros(1, dtype=np.int32), - np.zeros(1, dtype=np.int32), - 1.0, - False, - ] - for index in [4, 7, 2]: - bad = list(args) - bad[index] = np.zeros(2, dtype=bad[index].dtype) - with pytest.raises(ValueError, match="same size|one entry per edge"): - _tsdate.count_mutations(*bad) - class TestOutsideTreeSequences: def test_nan_node_times(self): @@ -128,7 +105,7 @@ def test_quantile_below_first_breakpoint(self): result = compare( _tsdate.piecewise_scale_posterior, rescaling.piecewise_scale_posterior, *args ) - assert isinstance(result.exception, AssertionError) + assert result.error == TIME_BELOW_FIRST_BREAKPOINT def test_fixed_posteriors_below_first_breakpoint(self): # the rescaled quantiles of fixed posteriors are zero, and are checked too @@ -143,4 +120,4 @@ def test_fixed_posteriors_below_first_breakpoint(self): result = compare( _tsdate.piecewise_scale_posterior, rescaling.piecewise_scale_posterior, *args ) - assert isinstance(result.exception, AssertionError) + assert result.error == TIME_BELOW_FIRST_BREAKPOINT diff --git a/tests/test_python_c_scalar.py b/tests/test_python_c_scalar.py index 3633afef..4e2da73b 100644 --- a/tests/test_python_c_scalar.py +++ b/tests/test_python_c_scalar.py @@ -1,7 +1,7 @@ """ Tests of the generic scalar-function wrapper of the low-level _tsdate module: argument -handling, return types, and the mapping of library errors to exceptions. Numerical -values are tested against the oracles in test_oracle_*.py. +handling and return types. Numerical values and library errors are tested against the +oracles in test_oracle_*.py. """ import math @@ -65,19 +65,6 @@ def test_keyword_arguments_rejected(self, name): class TestScalarErrors: - def test_zero_division(self): - with pytest.raises(_tsdate.LibraryError, match="division by zero"): - _tsdate.digamma(0.0) - - def test_invalid_hypergeo(self): - with pytest.raises(_tsdate.LibraryError, match="domain of the hypergeometric"): - _tsdate.hyp2f1_laplace(1.0, 2.0, 3.0, 1.0) - - def test_messages_match_strerror(self): - with pytest.raises(_tsdate.LibraryError) as exc_info: - _tsdate.gammainc_der(-1.0, 1.0) - assert str(exc_info.value) == _tsdate.strerror(-5) - def test_nan_is_not_an_error(self): assert math.isnan(_tsdate.gammainc_inv(math.nan, 0.5)) diff --git a/tests/test_python_c_tables.py b/tests/test_python_c_tables.py index 176965e5..59d953a4 100644 --- a/tests/test_python_c_tables.py +++ b/tests/test_python_c_tables.py @@ -122,27 +122,6 @@ def test_contains_unary_nodes_mask_size(self): ts.num_nodes, ) - def test_relabel_mutation_node_not_in_tree(self): - # node 4 has no edges - nodes = THREE_HAPLOTYPES + [(0, 2, -1)] - ts = make_ts(nodes, STAR, [(1, 4)], 10.0, 1) - with pytest.raises(_tsdate.LibraryError, match="not in any tree"): - _tsdate.relabel_mutations_node( - ts.mutations_node, - f64(1.0), - i32(0, 1, 2, 3, 4), - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ) - - def test_constrain_ages_fixed_nodes(self): - with pytest.raises(_tsdate.LibraryError, match="two fixed nodes"): - _tsdate.constrain_ages(f64(0, 1), b1(1, 1), i32(0), i32(1), 0.1, 3) - class TestPrior: def test_marginalize_over_ancestors_one_tip(self): From bd4e5a6f729de340e66f1ee80ccb008e5d080d0e Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 12:48:39 -0800 Subject: [PATCH 35/56] Remove an unused constant from the rescaling oracle tests --- tests/test_oracle_rescaling.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/test_oracle_rescaling.py b/tests/test_oracle_rescaling.py index 262cb067..8abaffac 100644 --- a/tests/test_oracle_rescaling.py +++ b/tests/test_oracle_rescaling.py @@ -33,8 +33,6 @@ from tsdate.variational import ExpectationPropagation -BREAKS_MSG = "non-increasing time breakpoints" - @pytest.fixture(params=["small_ts_unphased", "small_ts_historical"]) def sim_ts(request): From 91512a0629a5a9c03ad99659131e58120ff0f72e Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 18:48:18 -0800 Subject: [PATCH 36/56] Remove unused C++ guards, macros and an include from the C library --- lib/err.h | 18 ------------------ lib/mathutil.h | 8 -------- lib/phasing.c | 1 - lib/tsdate.h | 8 -------- 4 files changed, 35 deletions(-) diff --git a/lib/err.h b/lib/err.h index 29de9ae7..85f4436b 100644 --- a/lib/err.h +++ b/lib/err.h @@ -25,10 +25,6 @@ #ifndef TSD_ERR_H #define TSD_ERR_H -#ifdef __cplusplus -extern "C" { -#endif - #include #include @@ -85,16 +81,6 @@ extern "C" { #define TSD_ERR_NONPOSITIVE_PENALTY -35 /* clang-format on */ -#ifdef __GNUC__ -#define WARN_UNUSED __attribute__((warn_unused_result)) -#define unlikely(expr) __builtin_expect(!!(expr), 0) -#define likely(expr) __builtin_expect(!!(expr), 1) -#else -#define WARN_UNUSED -#define unlikely(expr) (expr) -#define likely(expr) (expr) -#endif - const char *tsd_strerror(int err); #ifdef TSD_TRACE_ERRORS @@ -129,8 +115,4 @@ _tsd_trace_error(int err, int line, const char *file) void _tsd_safe_free(void **ptr); #define tsd_safe_free(pointer) _tsd_safe_free((void **) &(pointer)) -#ifdef __cplusplus -} -#endif - #endif diff --git a/lib/mathutil.h b/lib/mathutil.h index 5109cb99..6e583a89 100644 --- a/lib/mathutil.h +++ b/lib/mathutil.h @@ -25,10 +25,6 @@ #ifndef TSD_MATHUTIL_H #define TSD_MATHUTIL_H -#ifdef __cplusplus -extern "C" { -#endif - #include /* Constants that only defines as extensions (and MSVC not by default). */ @@ -78,8 +74,4 @@ tsd_isclose(double a, double b) return fabs(a - b) <= 1e-8 + 1e-5 * fabs(b); } -#ifdef __cplusplus -} -#endif - #endif diff --git a/lib/phasing.c b/lib/phasing.c index 3fc962ce..7b0db97c 100644 --- a/lib/phasing.c +++ b/lib/phasing.c @@ -28,7 +28,6 @@ #include #include -#include #include "mathutil.h" #include "tsdate.h" diff --git a/lib/tsdate.h b/lib/tsdate.h index b2843594..b1e62b7d 100644 --- a/lib/tsdate.h +++ b/lib/tsdate.h @@ -25,10 +25,6 @@ #ifndef TSDATE_H #define TSDATE_H -#ifdef __cplusplus -extern "C" { -#endif - #include #include "err.h" @@ -346,8 +342,4 @@ int tsd_propagate_mutations(tsd_size_t num_order, const tsd_id_t *mutations_orde const double *posterior, const tsd_ep_factors_t *factors, int unphased, double *mutations_posterior, double *mutations_phase); -#ifdef __cplusplus -} -#endif - #endif From 2129bbaaea4d361bd9d2e661b0e9e2b1b885f25d Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 18:57:01 -0800 Subject: [PATCH 37/56] Call _tsdate directly instead of through private aliases, and note the zero-count changepoints --- lib/rescaling.c | 8 ++++++-- tsdate/phasing.py | 8 ++------ tsdate/rescaling.py | 10 +--------- tsdate/util.py | 20 ++++---------------- 4 files changed, 13 insertions(+), 33 deletions(-) diff --git a/lib/rescaling.c b/lib/rescaling.c index 83ec5d69..1759d726 100644 --- a/lib/rescaling.c +++ b/lib/rescaling.c @@ -181,8 +181,12 @@ tsd_fixed_changepoints(tsd_size_t num_counts, const double *counts, int64_t epoc ret = tsd_trace_error(TSD_ERR_NO_MEMORY); goto out; } - /* The cumulative counts, normalised by the total. Division by zero is not an - * error: the result is NaN, which compares as greater than every number. */ + /* + * The cumulative counts, normalised by the total. Division by zero is not an + * error: the result is NaN, which compares as greater than every number. + * NOTE: current behaviour, possibly a bug: if all counts are zero, every + * normalised count is NaN and the breakpoints are [-1, ..., -1, num_counts]. + */ cumulative[0] = 0.0; for (j = 0; j < num_counts; j++) { cumulative[j + 1] = cumulative[j] + counts[j]; diff --git a/tsdate/phasing.py b/tsdate/phasing.py index d9599e81..2b004b77 100644 --- a/tsdate/phasing.py +++ b/tsdate/phasing.py @@ -31,7 +31,6 @@ reallocate_unphased = _tsdate.reallocate_unphased -_block_singletons = _tsdate.block_singletons def block_singletons(ts, individuals_unphased): @@ -59,7 +58,7 @@ def block_singletons(ts, individuals_unphased): raise ValueError("Singleton blocking assumes contemporary individuals") # TODO: adjust spans by an accessibility mask - return _block_singletons( + return _tsdate.block_singletons( individuals_unphased, ts.nodes_individual, ts.mutations_node, @@ -74,9 +73,6 @@ def block_singletons(ts, individuals_unphased): ) -_mutation_frequency = _tsdate.mutation_frequency - - def mutation_frequency(ts, sample_sets=None): """ The number of samples of each sample set that carry each mutation, that is the @@ -96,7 +92,7 @@ def mutation_frequency(ts, sample_sets=None): assert min(s) >= 0 and max(s) < ts.num_samples, "Sample out of range" # NOQA: PT018 nodes_sample[s, i] = True - return _mutation_frequency( + return _tsdate.mutation_frequency( nodes_sample, ts.mutations_node, ts.sites_position[ts.mutations_site], diff --git a/tsdate/rescaling.py b/tsdate/rescaling.py index f118707e..fd5ea2b4 100644 --- a/tsdate/rescaling.py +++ b/tsdate/rescaling.py @@ -29,14 +29,6 @@ from .util import mutation_span_array # NOQA: F401 -_fixed_changepoints = _tsdate.fixed_changepoints - - -_poisson_changepoints = _tsdate.poisson_changepoints - - -_count_mutations = _tsdate.count_mutations - def count_mutations(ts, node_is_sample=None, size_biased=False): """ @@ -56,7 +48,7 @@ def count_mutations(ts, node_is_sample=None, size_biased=False): else: assert node_is_sample.size != ts.num_nodes - return _count_mutations( + return _tsdate.count_mutations( node_is_sample, ts.mutations_node, ts.sites_position[ts.mutations_site], diff --git a/tsdate/util.py b/tsdate/util.py index bf94be53..309bf73e 100644 --- a/tsdate/util.py +++ b/tsdate/util.py @@ -402,12 +402,6 @@ def _reorder_nodes(node_table, order, extra_md_dict): ) -_split_disjoint_nodes = _tsdate.split_disjoint_nodes - - -_relabel_mutations_node = _tsdate.relabel_mutations_node - - def split_disjoint_nodes(ts, *, record_provenance=None): """ For each non-sample node, split regions separated by gaps into distinct @@ -431,7 +425,7 @@ def split_disjoint_nodes(ts, *, record_provenance=None): if record_provenance is None: record_provenance = True node_is_sample = np.bitwise_and(ts.nodes_flags, tskit.NODE_IS_SAMPLE).astype(bool) - edges_parent, edges_child, nodes_order, split_nodes = _split_disjoint_nodes( + edges_parent, edges_child, nodes_order, split_nodes = _tsdate.split_disjoint_nodes( ts.edges_parent, ts.edges_child, ts.edges_left, @@ -439,7 +433,7 @@ def split_disjoint_nodes(ts, *, record_provenance=None): node_is_sample, ) - mutations_node = _relabel_mutations_node( + mutations_node = _tsdate.relabel_mutations_node( ts.mutations_node, ts.sites_position[ts.mutations_site], nodes_order, @@ -482,9 +476,6 @@ def split_disjoint_nodes(ts, *, record_provenance=None): return tables.tree_sequence() -_constrain_ages = _tsdate.constrain_ages - - def constrain_ages(ts, nodes_time, epsilon=1e-6, max_iterations=0): """ Use a hybrid approach to adjust node times such that branch lengths are @@ -511,7 +502,7 @@ def constrain_ages(ts, nodes_time, epsilon=1e-6, max_iterations=0): assert max_iterations >= 0 nodes_fixed = np.bitwise_and(ts.nodes_flags, tskit.NODE_IS_SAMPLE).astype(bool) - constrained_nodes_time = _constrain_ages( + constrained_nodes_time = _tsdate.constrain_ages( nodes_time, nodes_fixed, ts.edges_parent, @@ -525,9 +516,6 @@ def constrain_ages(ts, nodes_time, epsilon=1e-6, max_iterations=0): return constrained_nodes_time -_contains_unary_nodes = _tsdate.contains_unary_nodes - - def contains_unary_nodes(ts, skip_samples=True): """ Check if any internal node in the tree sequence is unary over some portion @@ -539,7 +527,7 @@ def contains_unary_nodes(ts, skip_samples=True): if skip_samples: nodes_mask[list(ts.samples())] = True - return _contains_unary_nodes( + return _tsdate.contains_unary_nodes( nodes_mask, ts.edges_parent, ts.edges_left, From d118e6c16e3e29ce85979bef63c2f03a841006de Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Thu, 26 Nov 2026 19:10:28 -0800 Subject: [PATCH 38/56] Seed the noise in test_constrain_ages_backcompat The reference implementation bumps a parent only when a child is at least as old, whereas constrain_ages keeps parents at least epsilon above their children. Noise that leaves a parent within epsilon of a child makes the two differ by up to epsilon, which fails the comparison in about 0.08% of seeds. --- tests/test_functions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_functions.py b/tests/test_functions.py index f7444887..40b080f8 100644 --- a/tests/test_functions.py +++ b/tests/test_functions.py @@ -1653,7 +1653,7 @@ def test_constrain_ages_backcompat(self): ts = msprime.sim_mutations(ts, rate=1e-8, random_seed=1) sample_data = tsinfer.SampleData.from_tree_sequence(ts) inf_ts = tsinfer.infer(sample_data).simplify() - rng = np.random.default_rng() + rng = np.random.default_rng(1) noise = rng.uniform(0, 0.1, size=inf_ts.num_nodes) nodes_time = inf_ts.nodes_time + noise eps = 1e-6 From e840fa9caa6e35f6bfbece820de412c6b530d9d5 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 09:59:25 -0800 Subject: [PATCH 39/56] Fix the inverted size check on the sample mask in count_mutations --- tests/test_rescaling.py | 14 ++++++++++++++ tsdate/rescaling.py | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/tests/test_rescaling.py b/tests/test_rescaling.py index 60659427..5b55fcae 100644 --- a/tests/test_rescaling.py +++ b/tests/test_rescaling.py @@ -227,6 +227,20 @@ def test_count_sizebiased(self, inferred_ts): np.testing.assert_array_almost_equal(ck_edge_stats, edge_stats) np.testing.assert_array_equal(ck_muts_edge, muts_edge) + def test_count_with_sample_mask(self, inferred_ts): + node_is_sample = np.full(inferred_ts.num_nodes, False) + node_is_sample[inferred_ts.samples()] = True + edge_stats, muts_edge = count_mutations( + inferred_ts, node_is_sample=node_is_sample, size_biased=True + ) + ck_edge_stats, ck_muts_edge = self.naive_count_sizebiased(inferred_ts) + np.testing.assert_array_almost_equal(ck_edge_stats, edge_stats) + np.testing.assert_array_equal(ck_muts_edge, muts_edge) + + def test_count_with_wrong_size_mask(self, inferred_ts): + with pytest.raises(AssertionError): + count_mutations(inferred_ts, node_is_sample=np.full(1, True)) + @pytest.mark.skip("Ancient samples not implemented") def test_count_sizebiased_with_ancient(self, inferred_ts): # TODO: if there are ancestral samples, these should not be used as weights. diff --git a/tsdate/rescaling.py b/tsdate/rescaling.py index fd5ea2b4..1e29e563 100644 --- a/tsdate/rescaling.py +++ b/tsdate/rescaling.py @@ -46,7 +46,7 @@ def count_mutations(ts, node_is_sample=None, size_biased=False): node_is_sample = np.full(ts.num_nodes, False) node_is_sample[list(ts.samples())] = True else: - assert node_is_sample.size != ts.num_nodes + assert node_is_sample.size == ts.num_nodes return _tsdate.count_mutations( node_is_sample, From 4b669f1b9d7c392363a2c9fed6352449976245b8 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 09:59:25 -0800 Subject: [PATCH 40/56] Index pair arrays in tsd_size_t arithmetic --- lib/phasing.c | 21 +++++++++++---------- lib/rescaling.c | 8 ++++---- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/lib/phasing.c b/lib/phasing.c index 7b0db97c..334456a0 100644 --- a/lib/phasing.c +++ b/lib/phasing.c @@ -58,7 +58,7 @@ block_edge_out(block_state_t *state, tsd_id_t e, double left) if (i == TSD_NULL || !state->individuals_unphased[i]) { return; } - edges = state->individuals_edges + 2 * i; + edges = state->individuals_edges + 2 * (tsd_size_t) i; tsd_bug_assert(edges[0] == e || edges[1] == e); s = edges[1] == e ? edges[0] : edges[1]; edges[0] = s; @@ -66,10 +66,11 @@ block_edge_out(block_state_t *state, tsd_id_t e, double left) if (s != TSD_NULL) { block = state->individuals_block[i]; tsd_bug_assert(block != TSD_NULL); - state->blocks_edges[2 * block] = e; - state->blocks_edges[2 * block + 1] = s; - state->blocks_stats[2 * block] = state->individuals_singletons[i]; - state->blocks_stats[2 * block + 1] = left - state->individuals_position[i]; + state->blocks_edges[2 * (tsd_size_t) block] = e; + state->blocks_edges[2 * (tsd_size_t) block + 1] = s; + state->blocks_stats[2 * (tsd_size_t) block] = state->individuals_singletons[i]; + state->blocks_stats[2 * (tsd_size_t) block + 1] + = left - state->individuals_position[i]; state->num_flushed++; state->individuals_position[i] = NAN; state->individuals_block[i] = TSD_NULL; @@ -89,7 +90,7 @@ block_edge_in(block_state_t *state, tsd_id_t e, double left) if (i == TSD_NULL || !state->individuals_unphased[i]) { goto out; } - edges = state->individuals_edges + 2 * i; + edges = state->individuals_edges + 2 * (tsd_size_t) i; u = edges[0]; v = edges[1]; if (u != TSD_NULL && v != TSD_NULL) { @@ -298,8 +299,8 @@ tsd_reallocate_unphased(tsd_size_t num_edges, tsd_size_t num_mutations, ret = tsd_trace_error(TSD_ERR_BLOCK_OUT_OF_RANGE); goto out; } - i = blocks_edges[2 * b]; - k = blocks_edges[2 * b + 1]; + i = blocks_edges[2 * (tsd_size_t) b]; + k = blocks_edges[2 * (tsd_size_t) b + 1]; if (i <= TSD_NULL || (tsd_size_t) i >= num_edges || k <= TSD_NULL || (tsd_size_t) k >= num_edges) { ret = tsd_trace_error(TSD_ERR_BLOCK_OUT_OF_RANGE); @@ -313,8 +314,8 @@ tsd_reallocate_unphased(tsd_size_t num_edges, tsd_size_t num_mutations, ret = tsd_trace_error(TSD_ERR_PHASE_OUT_OF_RANGE); goto out; } - edges_likelihood[2 * i] += phase; - edges_likelihood[2 * k] += 1 - phase; + edges_likelihood[2 * (tsd_size_t) i] += phase; + edges_likelihood[2 * (tsd_size_t) k] += 1 - phase; } if (!tsd_isclose(num_unphased, sum_flagged_likelihoods(num_edges, edges_likelihood, edges_unphased))) { diff --git a/lib/rescaling.c b/lib/rescaling.c index 1759d726..1f522129 100644 --- a/lib/rescaling.c +++ b/lib/rescaling.c @@ -377,7 +377,7 @@ count_update_ancestors(tsd_id_t e, tsd_id_t p, tsd_id_t c, double sign, double r while (p != NO_ID) { span = nodes_samples[c] * remainder; - edges_stats[2 * e + 1] += sign * span; + edges_stats[2 * (tsd_size_t) e + 1] += sign * span; nodes_samples[p] += sign * nodes_samples[c]; next_e = nodes_edge[p]; next_p = nodes_parent[p]; @@ -444,7 +444,7 @@ tsd_count_mutations(tsd_size_t num_nodes, const uint8_t *node_is_sample, count_update_ancestors(e, p, c, -1.0, remainder, nodes_edge, nodes_parent, nodes_samples, edges_stats); } else { - edges_stats[2 * e + 1] -= remainder; + edges_stats[2 * (tsd_size_t) e + 1] -= remainder; } b++; } @@ -460,7 +460,7 @@ tsd_count_mutations(tsd_size_t num_nodes, const uint8_t *node_is_sample, count_update_ancestors(e, p, c, 1.0, remainder, nodes_edge, nodes_parent, nodes_samples, edges_stats); } else { - edges_stats[2 * e + 1] += remainder; + edges_stats[2 * (tsd_size_t) e + 1] += remainder; } a++; } @@ -482,7 +482,7 @@ tsd_count_mutations(tsd_size_t num_nodes, const uint8_t *node_is_sample, e = nodes_edge[c]; if (e != NO_ID) { mutations_edge[m] = e; - edges_stats[2 * e] += size_biased ? nodes_samples[c] : 1.0; + edges_stats[2 * (tsd_size_t) e] += size_biased ? nodes_samples[c] : 1.0; } d++; } From 0ad452647cdd8330ad5662f3f8a9194334e238d4 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 09:59:25 -0800 Subject: [PATCH 41/56] Describe the domain of tsd_gammaincinv accurately --- lib/gammaincinv.c | 4 ++-- lib/tsdate.h | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/gammaincinv.c b/lib/gammaincinv.c index d565e9a3..58de06be 100644 --- a/lib/gammaincinv.c +++ b/lib/gammaincinv.c @@ -1431,8 +1431,8 @@ ceph_igamci(double a, double q) return x; } -/* igami(). As in xsf, where set_error only reports it, an `a` or `p` outside the - * domain is not rejected: the computation goes on (and its result is NaN). */ +/* igami(). NaN for `a` < 0, `p` outside [0, 1], `a` = 0 or `a` = infinity (with + * 0 < p < 1), and NaN arguments. */ double tsd_gammaincinv(double a, double p) { diff --git a/lib/tsdate.h b/lib/tsdate.h index b1e62b7d..532d0426 100644 --- a/lib/tsdate.h +++ b/lib/tsdate.h @@ -51,9 +51,9 @@ int tsd_hyp2f1_laplace(double a, double b, double c, double x, double *out); /* * The inverse of the regularised lower incomplete gamma function (gammaincinv.c): x - * such that gammainc(a, x) = p, identical to scipy.special.gammaincinv. It returns 0 - * for p = 0, infinity for p = 1 and NaN (not an error) for arguments outside the - * domain. + * such that gammainc(a, x) = p. Inside the domain it agrees with + * scipy.special.gammaincinv, bit for bit on x86-64 Linux. It returns 0 for p = 0, + * infinity for p = 1 and NaN (not an error) for arguments outside the domain. */ double tsd_gammaincinv(double a, double p); From 32365cfd9d524fdf8e8bdf8ad4b8c1dda2ae0662 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 09:59:25 -0800 Subject: [PATCH 42/56] Sum log likelihoods row by row with one exponential per element np.logaddexp.reduceat computes an exponential and a logarithm per element, which made the inside-outside and maximization methods 10-15% slower than the numba row sums. A max-shifted sum per row with np.maximum.reduceat and np.add.reduceat is faster than both. --- CHANGELOG.md | 7 ++++--- tsdate/discrete.py | 23 +++++++++++++++++++---- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2cefdcfa..3cbe23bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,13 +6,14 @@ In development - The numerical core (the special functions, gamma approximations, expectation propagation passes, rescaling and utilities) is now a C extension instead of - numba-compiled Python, with identical results. numba is no longer a dependency, + numba-compiled Python. Results are identical on x86-64 Linux; elsewhere they can + differ in the last few digits. numba is no longer a dependency, so importing tsdate no longer takes tens of seconds to compile, and `TSDATE_ENABLE_NUMBA_CACHE` is gone. Wheels are now tested on macOS x86_64 and built for musllinux. -- The inside-outside method uses `scipy.special.logsumexp`, which can change - results in the last few digits. +- The inside-outside method sums likelihoods in log space with numpy, which can + change results in the last few digits. - `preprocess_ts` now always sorts the tree sequence, which may change the order of mutations diff --git a/tsdate/discrete.py b/tsdate/discrete.py index 5229e85d..b959729e 100644 --- a/tsdate/discrete.py +++ b/tsdate/discrete.py @@ -7,7 +7,6 @@ from collections import defaultdict import numpy as np -import scipy.special import scipy.stats import tskit from tqdm.auto import tqdm @@ -353,6 +352,20 @@ def scale_geometric(self, fraction, value): return value**fraction +def logsumexp_reduceat(x, indices): + """ + The log of the sum of exp(x) over each slice of `x` starting at `indices`, as + np.logaddexp.reduceat(x, indices) for increasing `indices`, with one exponential + per element + """ + maxima = np.maximum.reduceat(x, indices) + shifts = np.where(np.isfinite(maxima), maxima, 0.0) + lengths = np.diff(indices, append=x.size) + sums = np.add.reduceat(np.exp(x - np.repeat(shifts, lengths)), indices) + with np.errstate(divide="ignore"): + return np.log(sums) + shifts + + class LogLikelihoods(Likelihoods): """ Identical to the Likelihoods class but stores and returns log likelihoods @@ -362,7 +375,9 @@ class LogLikelihoods(Likelihoods): identity_constant = 0.0 null_constant = -np.inf - logsumexp = staticmethod(scipy.special.logsumexp) + @staticmethod + def logsumexp(X): + return logsumexp_reduceat(X, np.zeros(1, dtype=int))[0] @staticmethod def _lik(muts, span, dt, mutation_rate, standardize=True): @@ -387,11 +402,11 @@ def _lik_wrapper(muts_span, dt, mutation_rate, standardize=True): def rowsum_lower_tri(self, input_array): assert len(input_array) == self.tri_size - return np.logaddexp.reduceat(input_array, self.row_indices[0]) + return logsumexp_reduceat(input_array, self.row_indices[0]) def rowsum_upper_tri(self, input_array): assert len(input_array) == self.tri_size - return np.logaddexp.reduceat(input_array, self.col_indices) + return logsumexp_reduceat(input_array, self.col_indices) def _recombination_loglik(self, edge, fixed=True): # Needs to return a lower tri *or* flattened array depending on `fixed` From 4786dd95a98209b36eda436ecd9cddc9dadf2640 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 10:42:45 -0800 Subject: [PATCH 43/56] Validate ids and edge intervals in the library Functions given node, edge or individual ids now check them and return TSD_ERR_NODE_OUT_OF_BOUNDS, TSD_ERR_EDGE_OUT_OF_BOUNDS or TSD_ERR_INDIVIDUAL_OUT_OF_BOUNDS instead of reading or writing out of bounds. The tree sweeps check that every edge has 0 <= left < right <= sequence_length and that the insertion and removal indexes list every edge once in order of position, the conditions under which the sweep terminates; the ancestor walks stop with TSD_ERR_EDGES_FORM_CYCLE. tsd_block_singletons takes the number of nodes. Too few tips and no breakpoints are errors of the library rather than assertions or checks in the module. BLOCK_OUT_OF_RANGE becomes BLOCK_OUT_OF_BOUNDS. --- _tsdatemodule.c | 23 +-- lib/err.c | 28 ++- lib/err.h | 12 +- lib/phasing.c | 86 +++++++-- lib/prior.c | 10 +- lib/rescaling.c | 55 ++++-- lib/tests/tests.c | 259 +++++++++++++++++++++++++-- lib/tsdate.h | 27 ++- lib/util.c | 144 +++++++++++++++ lib/variational.c | 4 + tests/oracle/errors.py | 12 +- tests/oracle/phasing.py | 2 +- tests/oracle/rescaling.py | 8 +- tests/test_oracle_phasing.py | 4 +- tests/test_python_c.py | 291 +++++++++++++++++++++++++++++++ tests/test_python_c_rescaling.py | 4 +- tests/test_python_c_tables.py | 21 ++- 17 files changed, 905 insertions(+), 85 deletions(-) diff --git a/_tsdatemodule.c b/_tsdatemodule.c index bee6780b..a0937b8b 100644 --- a/_tsdatemodule.c +++ b/_tsdatemodule.c @@ -741,8 +741,9 @@ tsdate_block_singletons(PyObject *Py_UNUSED(self), PyObject *args) goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_block_singletons(ARRAY_SIZE(arrays[0]), ARRAY_SIZE(arrays[4]), - ARRAY_SIZE(arrays[2]), (const uint8_t *) PyArray_DATA(arrays[0]), + err = tsd_block_singletons(ARRAY_SIZE(arrays[1]), ARRAY_SIZE(arrays[0]), + ARRAY_SIZE(arrays[4]), ARRAY_SIZE(arrays[2]), + (const uint8_t *) PyArray_DATA(arrays[0]), (const tsd_id_t *) PyArray_DATA(arrays[1]), (const tsd_id_t *) PyArray_DATA(arrays[2]), (const double *) PyArray_DATA(arrays[3]), @@ -1182,10 +1183,6 @@ tsdate_marginalize_over_ancestors(PyObject *Py_UNUSED(self), PyObject *args) if (val_array == NULL) { goto out; } - if (ARRAY_DIM(val_array, 0) < 2) { - PyErr_SetString(PyExc_ValueError, "At least two tips are required"); - goto out; - } dims[0] = PyArray_DIM(val_array, 0) + 1; dims[1] = PyArray_DIM(val_array, 1); output = PyArray_SimpleNew(2, dims, NPY_FLOAT64); @@ -1222,8 +1219,8 @@ tsdate_conditional_coalescent_variance(PyObject *Py_UNUSED(self), PyObject *args if (!PyArg_ParseTuple(args, "n", &num_tips)) { goto out; } - if (num_tips < 1) { - PyErr_SetString(PyExc_ValueError, "The number of tips must be positive"); + if (num_tips < 0) { + PyErr_SetString(PyExc_ValueError, "The number of tips must be non-negative"); goto out; } dims[0] = (npy_intp) num_tips + 1; @@ -1662,9 +1659,8 @@ tsdate_piecewise_scale_point_estimate(PyObject *Py_UNUSED(self), PyObject *args) != 0) { goto out; } - if (check_sizes(ARRAY_LEN(original_breaks) == ARRAY_LEN(rescaled_breaks) - && ARRAY_LEN(original_breaks) > 0, - "Breakpoints must be non-empty and of the same size") + if (check_sizes(ARRAY_LEN(original_breaks) == ARRAY_LEN(rescaled_breaks), + "Breakpoints must be of the same size") != 0) { goto out; } @@ -1726,9 +1722,8 @@ tsdate_piecewise_scale_posterior(PyObject *Py_UNUSED(self), PyObject *args) != 0) { goto out; } - if (check_sizes(ARRAY_LEN(original_breaks) == ARRAY_LEN(rescaled_breaks) - && ARRAY_LEN(original_breaks) > 0, - "Breakpoints must be non-empty and of the same size") + if (check_sizes(ARRAY_LEN(original_breaks) == ARRAY_LEN(rescaled_breaks), + "Breakpoints must be of the same size") != 0) { goto out; } diff --git a/lib/err.c b/lib/err.c index 6deb216a..c0b71b67 100644 --- a/lib/err.c +++ b/lib/err.c @@ -84,8 +84,8 @@ tsd_strerror(int err) ret = "An unphased individual does not have exactly two edges over each " "of its blocks"; break; - case TSD_ERR_BLOCK_OUT_OF_RANGE: - ret = "A block or an edge of a block is out of range"; + case TSD_ERR_BLOCK_OUT_OF_BOUNDS: + ret = "Block id, or an edge of a block, out of bounds"; break; case TSD_ERR_PHASE_OUT_OF_RANGE: ret = "The phase of a mutation is not between zero and one"; @@ -147,6 +147,30 @@ tsd_strerror(int err) case TSD_ERR_NONPOSITIVE_PENALTY: ret = "The fitted regularisation penalty is not positive"; break; + case TSD_ERR_NODE_OUT_OF_BOUNDS: + ret = "Node id out of bounds"; + break; + case TSD_ERR_EDGE_OUT_OF_BOUNDS: + ret = "Edge id out of bounds"; + break; + case TSD_ERR_INDIVIDUAL_OUT_OF_BOUNDS: + ret = "Individual id out of bounds"; + break; + case TSD_ERR_BAD_EDGE_INTERVAL: + ret = "Edge interval is empty or outside [0, sequence_length]"; + break; + case TSD_ERR_BAD_EDGE_INDEXES: + ret = "Edge indexes must list every edge once, in order of position"; + break; + case TSD_ERR_EDGES_FORM_CYCLE: + ret = "Edges form a cycle"; + break; + case TSD_ERR_TOO_FEW_TIPS: + ret = "Too few tips"; + break; + case TSD_ERR_NO_BREAKPOINTS: + ret = "No breakpoints"; + break; default: break; } diff --git a/lib/err.h b/lib/err.h index 85f4436b..a8289db2 100644 --- a/lib/err.h +++ b/lib/err.h @@ -54,7 +54,7 @@ /* phasing */ #define TSD_ERR_UNPHASED_INDIVIDUAL_EDGES -16 -#define TSD_ERR_BLOCK_OUT_OF_RANGE -17 +#define TSD_ERR_BLOCK_OUT_OF_BOUNDS -17 #define TSD_ERR_PHASE_OUT_OF_RANGE -18 #define TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED -19 @@ -79,6 +79,16 @@ #define TSD_ERR_INVALID_DAMPING -33 #define TSD_ERR_TWIN_EDGE_IN_PHASED_PASS -34 #define TSD_ERR_NONPOSITIVE_PENALTY -35 + +/* Arguments that a caller can get wrong */ +#define TSD_ERR_NODE_OUT_OF_BOUNDS -36 +#define TSD_ERR_EDGE_OUT_OF_BOUNDS -37 +#define TSD_ERR_INDIVIDUAL_OUT_OF_BOUNDS -38 +#define TSD_ERR_BAD_EDGE_INTERVAL -39 +#define TSD_ERR_BAD_EDGE_INDEXES -40 +#define TSD_ERR_EDGES_FORM_CYCLE -41 +#define TSD_ERR_TOO_FEW_TIPS -42 +#define TSD_ERR_NO_BREAKPOINTS -43 /* clang-format on */ const char *tsd_strerror(int err); diff --git a/lib/phasing.c b/lib/phasing.c index 334456a0..b062ff80 100644 --- a/lib/phasing.c +++ b/lib/phasing.c @@ -119,8 +119,8 @@ block_edge_in(block_state_t *state, tsd_id_t e, double left) * caller frees them. */ int -tsd_block_singletons(tsd_size_t num_individuals, tsd_size_t num_edges, - tsd_size_t num_mutations, const uint8_t *individuals_unphased, +tsd_block_singletons(tsd_size_t num_nodes, tsd_size_t num_individuals, + tsd_size_t num_edges, tsd_size_t num_mutations, const uint8_t *individuals_unphased, const tsd_id_t *nodes_individual, const tsd_id_t *mutations_node, const double *mutations_position, const tsd_id_t *edges_child, const double *edges_left, const double *edges_right, const tsd_id_t *indexes_insert, @@ -142,6 +142,26 @@ tsd_block_singletons(tsd_size_t num_individuals, tsd_size_t num_edges, tsd_id_t m, i; double left, right; + ret = tsd_check_ids(num_nodes, nodes_individual, num_individuals, 1, + TSD_ERR_INDIVIDUAL_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_ids( + num_edges, edges_child, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_ids( + num_mutations, mutations_node, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_edge_sweep(num_edges, edges_left, edges_right, indexes_insert, + indexes_remove, sequence_length); + if (ret != 0) { + goto out; + } indexes_mutation = malloc((num_mutations > 0 ? num_mutations : 1) * sizeof(tsd_id_t)); individuals_edges = malloc(2 * num_ind * sizeof(*individuals_edges)); @@ -296,14 +316,14 @@ tsd_reallocate_unphased(tsd_size_t num_edges, tsd_size_t num_mutations, continue; } if (b < 0 || (tsd_size_t) b >= num_blocks) { - ret = tsd_trace_error(TSD_ERR_BLOCK_OUT_OF_RANGE); + ret = tsd_trace_error(TSD_ERR_BLOCK_OUT_OF_BOUNDS); goto out; } i = blocks_edges[2 * (tsd_size_t) b]; k = blocks_edges[2 * (tsd_size_t) b + 1]; if (i <= TSD_NULL || (tsd_size_t) i >= num_edges || k <= TSD_NULL || (tsd_size_t) k >= num_edges) { - ret = tsd_trace_error(TSD_ERR_BLOCK_OUT_OF_RANGE); + ret = tsd_trace_error(TSD_ERR_BLOCK_OUT_OF_BOUNDS); goto out; } phase = mutations_phase[m]; @@ -327,6 +347,31 @@ tsd_reallocate_unphased(tsd_size_t num_edges, tsd_size_t num_mutations, return ret; } +/* + * Add (sign = 1) or subtract (sign = -1) the sample counts of node `c` to those of + * `p` and of every ancestor of `p`. + */ +static int +update_ancestors(tsd_size_t num_nodes, tsd_size_t num_sample_sets, tsd_id_t p, + tsd_id_t c, int32_t sign, const tsd_id_t *nodes_parent, int32_t *nodes_samples) +{ + const tsd_size_t S = num_sample_sets; + tsd_size_t k, depth = 0; + + while (p != TSD_NULL) { + if (depth == num_nodes) { + return tsd_trace_error(TSD_ERR_EDGES_FORM_CYCLE); + } + for (k = 0; k < S; k++) { + nodes_samples[(tsd_size_t) p * S + k] + += sign * nodes_samples[(tsd_size_t) c * S + k]; + } + p = nodes_parent[p]; + depth++; + } + return 0; +} + /* * For each mutation and each sample set, the number of members of the set below the * mutation's node in the tree at the mutation's position. @@ -348,6 +393,20 @@ tsd_mutation_frequency(tsd_size_t num_nodes, tsd_size_t num_sample_sets, tsd_id_t e, p, c, m; double left, right; + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } + ret = tsd_check_ids( + num_mutations, mutations_node, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_edge_sweep(num_edges, edges_left, edges_right, indexes_insert, + indexes_remove, sequence_length); + if (ret != 0) { + goto out; + } indexes_mutation = malloc((num_mutations > 0 ? num_mutations : 1) * sizeof(tsd_id_t)); nodes_parent = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*nodes_parent)); @@ -380,13 +439,9 @@ tsd_mutation_frequency(tsd_size_t num_nodes, tsd_size_t num_sample_sets, p = edges_parent[e]; c = edges_child[e]; nodes_parent[c] = TSD_NULL; - while (p != TSD_NULL) { - for (k = 0; k < S; k++) { - nodes_samples[(tsd_size_t) p * S + k] - -= nodes_samples[(tsd_size_t) c * S + k]; - } - p = nodes_parent[p]; - } + ret = update_ancestors(num_nodes, S, p, c, -1, nodes_parent, nodes_samples); + /* A cycle is found when the edge that closes it is inserted */ + tsd_bug_assert(ret == 0); b++; } while (a < num_edges && edges_left[indexes_insert[a]] == left) { /* in */ @@ -394,12 +449,9 @@ tsd_mutation_frequency(tsd_size_t num_nodes, tsd_size_t num_sample_sets, p = edges_parent[e]; c = edges_child[e]; nodes_parent[c] = p; - while (p != TSD_NULL) { - for (k = 0; k < S; k++) { - nodes_samples[(tsd_size_t) p * S + k] - += nodes_samples[(tsd_size_t) c * S + k]; - } - p = nodes_parent[p]; + ret = update_ancestors(num_nodes, S, p, c, 1, nodes_parent, nodes_samples); + if (ret != 0) { + goto out; } a++; } diff --git a/lib/prior.c b/lib/prior.c index 295d3050..e0cf61b5 100644 --- a/lib/prior.c +++ b/lib/prior.c @@ -55,7 +55,10 @@ tsd_marginalize_over_ancestors( tsd_size_t k, a, j; double dk, dnk, dnak, weight, constant; - tsd_bug_assert(num_tips >= 2); + if (num_tips < 2) { + ret = tsd_trace_error(TSD_ERR_TOO_FEW_TIPS); + goto out; + } pr_a_ln = malloc((n + 1) * sizeof(*pr_a_ln)); if (pr_a_ln == NULL) { ret = tsd_trace_error(TSD_ERR_NO_MEMORY); @@ -111,7 +114,10 @@ tsd_conditional_coalescent_variance(tsd_size_t num_tips, double *variance_out) tsd_size_t i, n; double rate; - tsd_bug_assert(num_tips >= 1); + if (num_tips < 1) { + ret = tsd_trace_error(TSD_ERR_TOO_FEW_TIPS); + goto out; + } n = num_tips; if (n == 1) { variance_out[0] = 0.0; diff --git a/lib/rescaling.c b/lib/rescaling.c index 1f522129..f078cea5 100644 --- a/lib/rescaling.c +++ b/lib/rescaling.c @@ -367,15 +367,19 @@ tsd_poisson_changepoints(tsd_size_t num_counts, const double *counts, * its child `c`, and to every ancestor of `p`, in proportion to the number of * samples below `c`; and update the sample counts of the ancestors. */ -static void -count_update_ancestors(tsd_id_t e, tsd_id_t p, tsd_id_t c, double sign, double remainder, - const tsd_id_t *nodes_edge, const tsd_id_t *nodes_parent, double *nodes_samples, - double *edges_stats) +static int +count_update_ancestors(tsd_size_t num_nodes, tsd_id_t e, tsd_id_t p, tsd_id_t c, + double sign, double remainder, const tsd_id_t *nodes_edge, + const tsd_id_t *nodes_parent, double *nodes_samples, double *edges_stats) { tsd_id_t next_e, next_p; + tsd_size_t depth = 0; double span; while (p != NO_ID) { + if (depth == num_nodes) { + return tsd_trace_error(TSD_ERR_EDGES_FORM_CYCLE); + } span = nodes_samples[c] * remainder; edges_stats[2 * (tsd_size_t) e + 1] += sign * span; nodes_samples[p] += sign * nodes_samples[c]; @@ -383,7 +387,9 @@ count_update_ancestors(tsd_id_t e, tsd_id_t p, tsd_id_t c, double sign, double r next_p = nodes_parent[p]; e = next_e; p = next_p; + depth++; } + return 0; } int @@ -404,6 +410,20 @@ tsd_count_mutations(tsd_size_t num_nodes, const uint8_t *node_is_sample, tsd_id_t e, p, c, m; double left, right, remainder, edge_position; + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } + ret = tsd_check_ids( + num_mutations, mutations_node, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_edge_sweep(num_edges, edges_left, edges_right, indexes_insert, + indexes_remove, sequence_length); + if (ret != 0) { + goto out; + } mutation_order = malloc((num_mutations + 1) * sizeof(*mutation_order)); nodes_samples = malloc((num_nodes + 1) * sizeof(*nodes_samples)); nodes_edge = malloc((num_nodes + 1) * sizeof(*nodes_edge)); @@ -441,8 +461,10 @@ tsd_count_mutations(tsd_size_t num_nodes, const uint8_t *node_is_sample, nodes_edge[c] = NO_ID; nodes_parent[c] = NO_ID; if (size_biased) { - count_update_ancestors(e, p, c, -1.0, remainder, nodes_edge, - nodes_parent, nodes_samples, edges_stats); + ret = count_update_ancestors(num_nodes, e, p, c, -1.0, remainder, + nodes_edge, nodes_parent, nodes_samples, edges_stats); + /* A cycle is found when the edge that closes it is inserted */ + tsd_bug_assert(ret == 0); } else { edges_stats[2 * (tsd_size_t) e + 1] -= remainder; } @@ -457,8 +479,11 @@ tsd_count_mutations(tsd_size_t num_nodes, const uint8_t *node_is_sample, nodes_edge[c] = e; nodes_parent[c] = p; if (size_biased) { - count_update_ancestors(e, p, c, 1.0, remainder, nodes_edge, nodes_parent, - nodes_samples, edges_stats); + ret = count_update_ancestors(num_nodes, e, p, c, 1.0, remainder, + nodes_edge, nodes_parent, nodes_samples, edges_stats); + if (ret != 0) { + goto out; + } } else { edges_stats[2 * (tsd_size_t) e + 1] += remainder; } @@ -515,6 +540,10 @@ tsd_mutational_area(tsd_size_t num_nodes, const double *nodes_time, tsd_size_t n tsd_id_t p, c, node, previous; double length, edge_count, edge_span; + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } order = malloc((num_nodes + 1) * sizeof(*order)); epoch_breaks = malloc((num_nodes + 1) * sizeof(*epoch_breaks)); if (order == NULL || epoch_breaks == NULL) { @@ -762,7 +791,10 @@ tsd_piecewise_scale_point_estimate(tsd_size_t num_points, const double *point_es int64_t idx; double x; - tsd_bug_assert(num_breaks > 0); + if (num_breaks == 0) { + ret = tsd_trace_error(TSD_ERR_NO_BREAKPOINTS); + goto out; + } if (!is_increasing(num_breaks, rescaled_breaks) || !is_increasing(num_breaks, original_breaks)) { ret = tsd_trace_error(TSD_ERR_NON_INCREASING_BREAKPOINTS); @@ -818,7 +850,10 @@ tsd_piecewise_scale_posterior(tsd_size_t num_posteriors, const double *posterior double alpha, beta, quant_lower, quant_upper, new_beta; double gamma_pars[2]; - tsd_bug_assert(num_breaks > 0); + if (num_breaks == 0) { + ret = tsd_trace_error(TSD_ERR_NO_BREAKPOINTS); + goto out; + } if (!(quantile_width < 1 && quantile_width > 0)) { ret = tsd_trace_error(TSD_ERR_INVALID_QUANTILE_WIDTH); goto out; diff --git a/lib/tests/tests.c b/lib/tests/tests.c index b505689e..c0d03919 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -47,7 +47,7 @@ test_strerror(void) TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS, TSD_ERR_UNSORTED_QUANTILES, TSD_ERR_QUANTILE_MAX_ITERATIONS, TSD_ERR_NEGATIVE_SHAPE, TSD_ERR_NONPOSITIVE_MOMENTS, TSD_ERR_INVALID_FIXED_AGE, - TSD_ERR_UNPHASED_INDIVIDUAL_EDGES, TSD_ERR_BLOCK_OUT_OF_RANGE, + TSD_ERR_UNPHASED_INDIVIDUAL_EDGES, TSD_ERR_BLOCK_OUT_OF_BOUNDS, TSD_ERR_PHASE_OUT_OF_RANGE, TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED, TSD_ERR_MUTATION_NODE_NOT_IN_TREE, TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT, TSD_ERR_NONPOSITIVE_INTERVALS, TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER, @@ -56,7 +56,11 @@ test_strerror(void) TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT, TSD_ERR_NO_POSTERIORS, TSD_ERR_INVALID_MAX_SHAPE, TSD_ERR_INVALID_MIN_STEP, TSD_ERR_INVALID_NODE_POSTERIOR, TSD_ERR_INVALID_DAMPING, - TSD_ERR_TWIN_EDGE_IN_PHASED_PASS, TSD_ERR_NONPOSITIVE_PENALTY }; + TSD_ERR_TWIN_EDGE_IN_PHASED_PASS, TSD_ERR_NONPOSITIVE_PENALTY, + TSD_ERR_NODE_OUT_OF_BOUNDS, TSD_ERR_EDGE_OUT_OF_BOUNDS, + TSD_ERR_INDIVIDUAL_OUT_OF_BOUNDS, TSD_ERR_BAD_EDGE_INTERVAL, + TSD_ERR_BAD_EDGE_INDEXES, TSD_ERR_EDGES_FORM_CYCLE, TSD_ERR_TOO_FEW_TIPS, + TSD_ERR_NO_BREAKPOINTS }; const int num_codes = (int) (sizeof(codes) / sizeof(codes[0])); const char *msg_i; const char *msg_j; @@ -675,10 +679,10 @@ test_block_singletons(void) tsd_size_t num_blocks = 0; int ret; - ret = tsd_block_singletons(2, 4, 3, unphased, phase_nodes_individual, mutations_node, - mutations_position, phase_edges_child, phase_edges_left, phase_edges_right, - phase_order, phase_order, 10.0, &num_blocks, &blocks_stats, &blocks_edges, - mutations_block); + ret = tsd_block_singletons(5, 2, 4, 3, unphased, phase_nodes_individual, + mutations_node, mutations_position, phase_edges_child, phase_edges_left, + phase_edges_right, phase_order, phase_order, 10.0, &num_blocks, &blocks_stats, + &blocks_edges, mutations_block); CU_ASSERT_EQUAL(ret, 0); CU_ASSERT_EQUAL(num_blocks, 2); CU_ASSERT_EQUAL(mutations_block[0], 0); @@ -690,18 +694,18 @@ test_block_singletons(void) tsd_safe_free(blocks_edges); /* A haplotype edge is missing: the block is never completed */ - ret = tsd_block_singletons(2, 4, 3, unphased, phase_nodes_individual, mutations_node, - mutations_position, child_missing, phase_edges_left, phase_edges_right, - phase_order, phase_order, 10.0, &num_blocks, &blocks_stats, &blocks_edges, - mutations_block); + ret = tsd_block_singletons(5, 2, 4, 3, unphased, phase_nodes_individual, + mutations_node, mutations_position, child_missing, phase_edges_left, + phase_edges_right, phase_order, phase_order, 10.0, &num_blocks, &blocks_stats, + &blocks_edges, mutations_block); CU_ASSERT_EQUAL(ret, TSD_ERR_UNPHASED_INDIVIDUAL_EDGES); CU_ASSERT_PTR_NULL(blocks_stats); /* No edges and no individuals */ - ret = tsd_block_singletons(0, 0, 0, unphased, phase_nodes_individual, mutations_node, - mutations_position, phase_edges_child, phase_edges_left, phase_edges_right, - phase_order, phase_order, 10.0, &num_blocks, &blocks_stats, &blocks_edges, - mutations_block); + ret = tsd_block_singletons(0, 0, 0, 0, unphased, phase_nodes_individual, + mutations_node, mutations_position, phase_edges_child, phase_edges_left, + phase_edges_right, phase_order, phase_order, 10.0, &num_blocks, &blocks_stats, + &blocks_edges, mutations_block); CU_ASSERT_EQUAL(ret, 0); CU_ASSERT_EQUAL(num_blocks, 0); tsd_safe_free(blocks_stats); @@ -740,11 +744,11 @@ test_reallocate_unphased(void) memcpy(likelihood, initial, sizeof(initial)); ret = tsd_reallocate_unphased( 2, 2, 1, phase, mutations_block_bad, blocks_edges, likelihood); - CU_ASSERT_EQUAL(ret, TSD_ERR_BLOCK_OUT_OF_RANGE); + CU_ASSERT_EQUAL(ret, TSD_ERR_BLOCK_OUT_OF_BOUNDS); memcpy(likelihood, initial, sizeof(initial)); ret = tsd_reallocate_unphased( 2, 2, 1, phase, mutations_block, blocks_edges_bad, likelihood); - CU_ASSERT_EQUAL(ret, TSD_ERR_BLOCK_OUT_OF_RANGE); + CU_ASSERT_EQUAL(ret, TSD_ERR_BLOCK_OUT_OF_BOUNDS); } static void @@ -871,6 +875,218 @@ test_contains_unary_nodes(void) CU_ASSERT_EQUAL(contains, 0); } +static void +test_check_arguments(void) +{ + const tsd_id_t ids[] = { 0, TSD_NULL, 4 }; + const double left_unsorted[] = { 5, 0, 0, 0 }; + const double right_unsorted[] = { 10, 5, 10, 10 }; + const tsd_id_t order_duplicate[] = { 0, 1, 1, 3 }; + const tsd_id_t order_bad[] = { 0, 1, 2, 4 }; + const double left_empty[] = { 0, 0, 0, 10 }; + const double right_long[] = { 10, 10, 10, 11 }; + const double left_nan[] = { 0, 0, 0, NAN }; + + CU_ASSERT_EQUAL(tsd_check_ids(3, ids, 5, 1, TSD_ERR_NODE_OUT_OF_BOUNDS), 0); + CU_ASSERT_EQUAL(tsd_check_ids(3, ids, 5, 0, TSD_ERR_NODE_OUT_OF_BOUNDS), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_check_ids(3, ids, 4, 1, TSD_ERR_EDGE_OUT_OF_BOUNDS), + TSD_ERR_EDGE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_check_edges(5, 4, phase_edges_parent, phase_edges_child), 0); + CU_ASSERT_EQUAL(tsd_check_edges(4, 4, phase_edges_parent, phase_edges_child), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_check_edges(4, 4, phase_edges_child, phase_edges_parent), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, phase_edges_left, phase_edges_right, + phase_order, phase_order, 10.0), + 0); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(0, NULL, NULL, NULL, NULL, 10.0), 0); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, left_empty, phase_edges_right, phase_order, + phase_order, 10.0), + TSD_ERR_BAD_EDGE_INTERVAL); + CU_ASSERT_EQUAL(tsd_check_edge_sweep( + 4, phase_edges_left, right_long, phase_order, phase_order, 10.0), + TSD_ERR_BAD_EDGE_INTERVAL); + CU_ASSERT_EQUAL(tsd_check_edge_sweep( + 4, left_nan, phase_edges_right, phase_order, phase_order, 10.0), + TSD_ERR_BAD_EDGE_INTERVAL); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, phase_edges_left, phase_edges_right, + order_bad, phase_order, 10.0), + TSD_ERR_EDGE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, phase_edges_left, phase_edges_right, + phase_order, order_bad, 10.0), + TSD_ERR_EDGE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, phase_edges_left, phase_edges_right, + order_duplicate, phase_order, 10.0), + TSD_ERR_BAD_EDGE_INDEXES); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, phase_edges_left, phase_edges_right, + phase_order, order_duplicate, 10.0), + TSD_ERR_BAD_EDGE_INDEXES); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, left_unsorted, phase_edges_right, + phase_order, phase_order, 10.0), + TSD_ERR_BAD_EDGE_INDEXES); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, phase_edges_left, right_unsorted, + phase_order, phase_order, 10.0), + TSD_ERR_BAD_EDGE_INDEXES); +} + +/* + * Each function given an id out of bounds, edges that cannot be swept, or edges that + * form a cycle. The fixture has nodes 0-4 and edges from node 4 to nodes 0-3. + */ +static void +test_bad_tree_arguments(void) +{ + const uint8_t flags[] = { 1, 1, 1, 1, 0 }; + const double times[] = { 0, 0, 0, 0, 1 }; + const double constraints[] = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 }; + const double likelihoods[] = { 1, 1, 1, 1, 1, 1, 1, 1 }; + const tsd_id_t identity[] = { 0, 1, 2, 3, 4 }; + const tsd_id_t bad_nodes[] = { 0, 1, 2, 5 }; + const tsd_id_t bad_individuals[] = { 0, 0, 1, 2, TSD_NULL }; + const double right_long[] = { 10, 10, 10, 11 }; + const tsd_id_t cycle_parent[] = { 1, 0 }; + const tsd_id_t cycle_child[] = { 0, 1 }; + const double cycle_left[] = { 0, 0 }; + const double cycle_right[] = { 10, 10 }; + const tsd_id_t mutation_node[] = { 0 }; + const tsd_id_t bad_mutation_node[] = { 5 }; + const double mutation_position[] = { 1 }; + tsd_id_t new_parent[4], new_child[4], output[1], mutations_edge[1], index[5]; + tsd_id_t *nodes_order = NULL; + tsd_id_t *blocks_edges = NULL; + double *blocks_stats = NULL; + double *origin = NULL; + double *adjust = NULL; + double stats[8], out[5]; + int32_t freq[5]; + tsd_size_t num_split, num_blocks, num_breaks; + tsd_epoch_stats_t epochs; + int result; + + /* tsd_split_disjoint_nodes */ + CU_ASSERT_EQUAL( + tsd_split_disjoint_nodes(5, 4, phase_edges_parent, bad_nodes, phase_edges_left, + phase_edges_right, flags, new_parent, new_child, &num_split, &nodes_order), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_PTR_NULL(nodes_order); + + /* tsd_relabel_mutations_node */ + CU_ASSERT_EQUAL(tsd_relabel_mutations_node(5, 4, 1, mutation_node, mutation_position, + identity, phase_edges_parent, bad_nodes, phase_edges_left, + phase_edges_right, phase_order, phase_order, output), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_relabel_mutations_node(5, 4, 1, mutation_node, mutation_position, bad_nodes, + phase_edges_parent, phase_edges_child, phase_edges_left, phase_edges_right, + phase_order, phase_order, output), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_relabel_mutations_node(5, 4, 1, bad_mutation_node, mutation_position, + identity, phase_edges_parent, phase_edges_child, phase_edges_left, + phase_edges_right, phase_order, phase_order, output), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_relabel_mutations_node(5, 4, 1, mutation_node, mutation_position, identity, + phase_edges_parent, phase_edges_child, phase_edges_left, phase_edges_right, + bad_nodes, phase_order, output), + TSD_ERR_EDGE_OUT_OF_BOUNDS); + + /* tsd_constrain_ages */ + CU_ASSERT_EQUAL(tsd_constrain_ages( + 5, 4, times, flags, bad_nodes, phase_edges_child, 1e-6, 1, out), + TSD_ERR_NODE_OUT_OF_BOUNDS); + + /* tsd_contains_unary_nodes */ + CU_ASSERT_EQUAL(tsd_contains_unary_nodes(5, 4, flags, bad_nodes, phase_edges_left, + phase_edges_right, phase_order, phase_order, 10.0, &result), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_contains_unary_nodes(5, 4, flags, phase_edges_parent, phase_edges_left, + right_long, phase_order, phase_order, 10.0, &result), + TSD_ERR_BAD_EDGE_INTERVAL); + + /* tsd_constraints_are_consistent */ + CU_ASSERT_EQUAL(tsd_constraints_are_consistent( + 5, 4, constraints, phase_edges_parent, bad_nodes, &result), + TSD_ERR_NODE_OUT_OF_BOUNDS); + + /* tsd_count_mutations */ + CU_ASSERT_EQUAL( + tsd_count_mutations(5, flags, 1, mutation_node, mutation_position, 4, + phase_edges_parent, bad_nodes, phase_edges_left, phase_edges_right, + phase_order, phase_order, 10.0, 0, stats, mutations_edge), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_count_mutations(5, flags, 1, bad_mutation_node, mutation_position, 4, + phase_edges_parent, phase_edges_child, phase_edges_left, phase_edges_right, + phase_order, phase_order, 10.0, 0, stats, mutations_edge), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_count_mutations(5, flags, 1, mutation_node, mutation_position, 4, + phase_edges_parent, phase_edges_child, phase_edges_left, right_long, + phase_order, phase_order, 10.0, 0, stats, mutations_edge), + TSD_ERR_BAD_EDGE_INTERVAL); + CU_ASSERT_EQUAL(tsd_count_mutations(2, flags, 1, mutation_node, mutation_position, 2, + cycle_parent, cycle_child, cycle_left, cycle_right, phase_order, + phase_order, 10.0, 1, stats, mutations_edge), + TSD_ERR_EDGES_FORM_CYCLE); + + /* tsd_mutational_area and tsd_mutational_timescale */ + CU_ASSERT_EQUAL(tsd_mutational_area(5, times, 4, likelihoods, phase_edges_parent, + bad_nodes, &epochs, index), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_mutational_timescale(5, times, 4, likelihoods, + phase_edges_parent, bad_nodes, 1, &num_breaks, &origin, &adjust), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_PTR_NULL(origin); + + /* tsd_block_singletons */ + CU_ASSERT_EQUAL(tsd_block_singletons(5, 2, 4, 1, flags, bad_individuals, + mutation_node, mutation_position, phase_edges_child, + phase_edges_left, phase_edges_right, phase_order, phase_order, + 10.0, &num_blocks, &blocks_stats, &blocks_edges, output), + TSD_ERR_INDIVIDUAL_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_block_singletons(5, 2, 4, 1, flags, phase_nodes_individual, + mutation_node, mutation_position, bad_nodes, phase_edges_left, + phase_edges_right, phase_order, phase_order, 10.0, &num_blocks, + &blocks_stats, &blocks_edges, output), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_block_singletons(5, 2, 4, 1, flags, phase_nodes_individual, + bad_mutation_node, mutation_position, phase_edges_child, + phase_edges_left, phase_edges_right, phase_order, phase_order, + 10.0, &num_blocks, &blocks_stats, &blocks_edges, output), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_block_singletons(5, 2, 4, 1, flags, phase_nodes_individual, + mutation_node, mutation_position, phase_edges_child, + phase_edges_left, right_long, phase_order, phase_order, 10.0, + &num_blocks, &blocks_stats, &blocks_edges, output), + TSD_ERR_BAD_EDGE_INTERVAL); + CU_ASSERT_PTR_NULL(blocks_stats); + CU_ASSERT_PTR_NULL(blocks_edges); + + /* tsd_mutation_frequency */ + CU_ASSERT_EQUAL( + tsd_mutation_frequency(5, 1, 4, 1, flags, mutation_node, mutation_position, + phase_edges_parent, bad_nodes, phase_edges_left, phase_edges_right, + phase_order, phase_order, 10.0, freq), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_mutation_frequency(5, 1, 4, 1, flags, bad_mutation_node, mutation_position, + phase_edges_parent, phase_edges_child, phase_edges_left, phase_edges_right, + phase_order, phase_order, 10.0, freq), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_mutation_frequency(5, 1, 4, 1, flags, mutation_node, mutation_position, + phase_edges_parent, phase_edges_child, phase_edges_left, right_long, + phase_order, phase_order, 10.0, freq), + TSD_ERR_BAD_EDGE_INTERVAL); + CU_ASSERT_EQUAL(tsd_mutation_frequency(2, 1, 2, 1, flags, mutation_node, + mutation_position, cycle_parent, cycle_child, cycle_left, + cycle_right, phase_order, phase_order, 10.0, freq), + TSD_ERR_EDGES_FORM_CYCLE); +} + static void test_conditional_coalescent_variance(void) { @@ -890,6 +1106,10 @@ test_conditional_coalescent_variance(void) for (j = 2; j <= 10; j++) { CU_ASSERT(variance[j] > 0.0); } + ret = tsd_marginalize_over_ancestors(1, 2, val, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_TOO_FEW_TIPS); + ret = tsd_conditional_coalescent_variance(0, variance); + CU_ASSERT_EQUAL(ret, TSD_ERR_TOO_FEW_TIPS); } /* ---- rescaling ---- */ @@ -1063,6 +1283,8 @@ test_piecewise_scale_point_estimate(void) CU_ASSERT_EQUAL(ret, TSD_ERR_NON_INCREASING_BREAKPOINTS); ret = tsd_piecewise_scale_point_estimate(5, estimate, fixed, 3, flat, rescaled, out); CU_ASSERT_EQUAL(ret, TSD_ERR_NON_INCREASING_BREAKPOINTS); + ret = tsd_piecewise_scale_point_estimate(5, estimate, fixed, 0, NULL, NULL, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_NO_BREAKPOINTS); } static void @@ -1086,6 +1308,9 @@ test_piecewise_scale_posterior(void) 4, posteriors, fixed, 3, original, rescaled, 0.5, 1000.0, out); CU_ASSERT_EQUAL(ret, 0); CU_ASSERT(isnan(out[4])); + ret = tsd_piecewise_scale_posterior( + 4, posteriors, fixed, 0, NULL, NULL, 0.5, 1000.0, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_NO_BREAKPOINTS); CU_ASSERT(isfinite(out[0]) && isfinite(out[1])); ret = tsd_piecewise_scale_posterior( 4, posteriors, none_fixed, 3, original, rescaled, 0.5, 1000.0, out); @@ -1465,6 +1690,8 @@ main(int argc, char **argv) { "test_split_and_relabel", test_split_and_relabel }, { "test_constrain_ages", test_constrain_ages }, { "test_contains_unary_nodes", test_contains_unary_nodes }, + { "test_check_arguments", test_check_arguments }, + { "test_bad_tree_arguments", test_bad_tree_arguments }, { "test_conditional_coalescent_variance", test_conditional_coalescent_variance }, { "test_fixed_changepoints", test_fixed_changepoints }, { "test_poisson_changepoints", test_poisson_changepoints }, diff --git a/lib/tsdate.h b/lib/tsdate.h index 532d0426..665a2774 100644 --- a/lib/tsdate.h +++ b/lib/tsdate.h @@ -178,12 +178,29 @@ int tsd_mutation_block_projection( * coalescent prior (prior.c). Flags are arrays of uint8_t (numpy bool); the arrays * of the edges are those of a tree sequence, with the indexes of the insertion and * removal orders. Results of unknown size are allocated by the function and freed by - * the caller. + * the caller. Ids out of bounds, edges that a sweep over the trees cannot traverse + * (tsd_check_edge_sweep) and edges that form a cycle are errors. */ int tsd_argsort(tsd_size_t num_items, const double *keys, tsd_id_t *order); -int tsd_block_singletons(tsd_size_t num_individuals, tsd_size_t num_edges, - tsd_size_t num_mutations, const uint8_t *individuals_unphased, +/* `err` unless every id is in [0, bound), or TSD_NULL if `allow_null`. */ +int tsd_check_ids( + tsd_size_t num_ids, const tsd_id_t *ids, tsd_size_t bound, int allow_null, int err); +/* TSD_ERR_NODE_OUT_OF_BOUNDS unless the parent and child of every edge are nodes. */ +int tsd_check_edges(tsd_size_t num_nodes, tsd_size_t num_edges, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child); +/* + * The conditions under which a sweep over the trees terminates: every edge satisfies + * 0 <= left < right <= sequence_length (TSD_ERR_BAD_EDGE_INTERVAL), and the insertion + * and removal indexes each list every edge once (TSD_ERR_EDGE_OUT_OF_BOUNDS, + * TSD_ERR_BAD_EDGE_INDEXES), in order of left and right position respectively. + */ +int tsd_check_edge_sweep(tsd_size_t num_edges, const double *edges_left, + const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length); + +int tsd_block_singletons(tsd_size_t num_nodes, tsd_size_t num_individuals, + tsd_size_t num_edges, tsd_size_t num_mutations, const uint8_t *individuals_unphased, const tsd_id_t *nodes_individual, const tsd_id_t *mutations_node, const double *mutations_position, const tsd_id_t *edges_child, const double *edges_left, const double *edges_right, const tsd_id_t *indexes_insert, @@ -219,10 +236,10 @@ int tsd_contains_unary_nodes(tsd_size_t num_nodes, tsd_size_t num_edges, const double *edges_right, const tsd_id_t *indexes_insert, const tsd_id_t *indexes_remove, double sequence_length, int *contains_unary); -/* `val` has `num_tips` >= 2 rows; `out` has `num_tips + 1` rows. */ +/* `val` has `num_tips` rows, at least two; `out` has `num_tips + 1` rows. */ int tsd_marginalize_over_ancestors( tsd_size_t num_tips, tsd_size_t num_moments, const double *val, double *out); -/* `variance` has `num_tips + 1` entries; `num_tips` >= 1. */ +/* `variance` has `num_tips + 1` entries; there is at least one tip. */ int tsd_conditional_coalescent_variance(tsd_size_t num_tips, double *variance); /* * Time rescaling (rescaling.c). diff --git a/lib/util.c b/lib/util.c index 2207f7ab..f10f2865 100644 --- a/lib/util.c +++ b/lib/util.c @@ -112,6 +112,113 @@ tsd_argsort(tsd_size_t num_items, const double *keys, tsd_id_t *order) return ret; } +int +tsd_check_ids( + tsd_size_t num_ids, const tsd_id_t *ids, tsd_size_t bound, int allow_null, int err) +{ + tsd_size_t j; + tsd_id_t id; + + for (j = 0; j < num_ids; j++) { + id = ids[j]; + if (allow_null && id == TSD_NULL) { + continue; + } + if (id < 0 || (tsd_size_t) id >= bound) { + return tsd_trace_error(err); + } + } + return 0; +} + +int +tsd_check_edges(tsd_size_t num_nodes, tsd_size_t num_edges, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child) +{ + int ret; + + ret = tsd_check_ids( + num_edges, edges_parent, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + return ret; + } + return tsd_check_ids( + num_edges, edges_child, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); +} + +/* Whether each id in [0, num_edges) appears once in `index`. */ +static int +is_permutation(tsd_size_t num_edges, const tsd_id_t *index, uint8_t *seen) +{ + tsd_size_t j; + + memset(seen, 0, num_edges * sizeof(*seen)); + for (j = 0; j < num_edges; j++) { + if (seen[index[j]]) { + return 0; + } + seen[index[j]] = 1; + } + return 1; +} + +/* Whether `position[index[j]]` does not decrease with j. */ +static int +is_sorted_by(tsd_size_t num_edges, const tsd_id_t *index, const double *position) +{ + tsd_size_t j; + + for (j = 1; j < num_edges; j++) { + if (position[index[j]] < position[index[j - 1]]) { + return 0; + } + } + return 1; +} + +int +tsd_check_edge_sweep(tsd_size_t num_edges, const double *edges_left, + const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length) +{ + int ret = 0; + uint8_t *seen = NULL; + tsd_size_t e; + + for (e = 0; e < num_edges; e++) { + if (!(edges_left[e] >= 0 && edges_left[e] < edges_right[e] + && edges_right[e] <= sequence_length)) { + ret = tsd_trace_error(TSD_ERR_BAD_EDGE_INTERVAL); + goto out; + } + } + ret = tsd_check_ids( + num_edges, indexes_insert, num_edges, 0, TSD_ERR_EDGE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_ids( + num_edges, indexes_remove, num_edges, 0, TSD_ERR_EDGE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + seen = malloc(num_edges > 0 ? num_edges : 1); + if (seen == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + if (!is_permutation(num_edges, indexes_insert, seen) + || !is_permutation(num_edges, indexes_remove, seen) + || !is_sorted_by(num_edges, indexes_insert, edges_left) + || !is_sorted_by(num_edges, indexes_remove, edges_right)) { + ret = tsd_trace_error(TSD_ERR_BAD_EDGE_INDEXES); + goto out; + } +out: + tsd_safe_free(seen); + return ret; +} + /* * Label the disconnected segments of each non-excluded node along its edges: the * segment of an edge increases when the edge starts after the previous edges of the @@ -192,6 +299,10 @@ tsd_split_disjoint_nodes(tsd_size_t num_nodes, tsd_size_t num_edges, tsd_size_t j, side, k, total, next; tsd_id_t s, n, segment, e; + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } edges_segments = malloc((2 * num_edges + 1) * sizeof(*edges_segments)); nodes_segments = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*nodes_segments)); nodes_map = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*nodes_map)); @@ -279,6 +390,25 @@ tsd_relabel_mutations_node(tsd_size_t num_nodes, tsd_size_t num_edges, tsd_id_t e, c, p; double left, right, sequence_length; + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } + ret = tsd_check_ids( + num_nodes, nodes_order, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_ids( + num_mutations, mutations_node, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_edge_sweep( + num_edges, edges_left, edges_right, insert_index, remove_index, INFINITY); + if (ret != 0) { + goto out; + } nodes_map = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*nodes_map)); if (nodes_map == NULL) { ret = tsd_trace_error(TSD_ERR_NO_MEMORY); @@ -371,6 +501,10 @@ tsd_constrain_ages(tsd_size_t num_nodes, tsd_size_t num_edges, const double *nod double adjustment; double *cavity; + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } edges_cavity = calloc(2 * num_edges + 1, sizeof(*edges_cavity)); if (edges_cavity == NULL) { ret = tsd_trace_error(TSD_ERR_NO_MEMORY); @@ -459,6 +593,16 @@ tsd_contains_unary_nodes(tsd_size_t num_nodes, tsd_size_t num_edges, tsd_id_t p; double left, right; + ret = tsd_check_ids( + num_edges, edges_parent, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_edge_sweep(num_edges, edges_left, edges_right, indexes_insert, + indexes_remove, sequence_length); + if (ret != 0) { + goto out; + } nodes_children = calloc(num_nodes > 0 ? num_nodes : 1, sizeof(*nodes_children)); if (nodes_children == NULL) { ret = tsd_trace_error(TSD_ERR_NO_MEMORY); diff --git a/lib/variational.c b/lib/variational.c index 6fb5633e..e23b1197 100644 --- a/lib/variational.c +++ b/lib/variational.c @@ -233,6 +233,10 @@ tsd_constraints_are_consistent(tsd_size_t num_nodes, tsd_size_t num_edges, tsd_size_t j; tsd_id_t p, c; + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } lower_max = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*lower_max)); if (lower_max == NULL) { ret = tsd_trace_error(TSD_ERR_NO_MEMORY); diff --git a/tests/oracle/errors.py b/tests/oracle/errors.py index a0e08f5a..1c96c0ed 100644 --- a/tests/oracle/errors.py +++ b/tests/oracle/errors.py @@ -21,7 +21,7 @@ NONPOSITIVE_MOMENTS = -14 INVALID_FIXED_AGE = -15 UNPHASED_INDIVIDUAL_EDGES = -16 -BLOCK_OUT_OF_RANGE = -17 +BLOCK_OUT_OF_BOUNDS = -17 PHASE_OUT_OF_RANGE = -18 UNPHASED_LIKELIHOOD_NOT_CONSERVED = -19 MUTATION_NODE_NOT_IN_TREE = -20 @@ -40,8 +40,16 @@ INVALID_DAMPING = -33 TWIN_EDGE_IN_PHASED_PASS = -34 NONPOSITIVE_PENALTY = -35 +NODE_OUT_OF_BOUNDS = -36 +EDGE_OUT_OF_BOUNDS = -37 +INDIVIDUAL_OUT_OF_BOUNDS = -38 +BAD_EDGE_INTERVAL = -39 +BAD_EDGE_INDEXES = -40 +EDGES_FORM_CYCLE = -41 +TOO_FEW_TIPS = -42 +NO_BREAKPOINTS = -43 -CODES = range(NONPOSITIVE_PENALTY, 0) +CODES = range(NO_BREAKPOINTS, 0) def library_error(code): diff --git a/tests/oracle/phasing.py b/tests/oracle/phasing.py index 11f4b5bc..aae6c6d6 100644 --- a/tests/oracle/phasing.py +++ b/tests/oracle/phasing.py @@ -31,7 +31,7 @@ def reallocate_unphased(edges_likelihood, mutations_phase, mutations_block, bloc continue i, j = blocks_edges[b] if not (tskit.NULL < i < num_edges and tskit.NULL < j < num_edges): - raise library_error(errors.BLOCK_OUT_OF_RANGE) + raise library_error(errors.BLOCK_OUT_OF_BOUNDS) assert edges_unphased[i] assert edges_unphased[j] if np.isnan(mutations_phase[m]): # TODO: fix rare numerical issue diff --git a/tests/oracle/rescaling.py b/tests/oracle/rescaling.py index 708be90d..25dcd914 100644 --- a/tests/oracle/rescaling.py +++ b/tests/oracle/rescaling.py @@ -318,8 +318,10 @@ def piecewise_scale_posterior( if not (posteriors.shape[1] == 2 and posteriors_fixed.size == posteriors.shape[0]): raise ValueError("Posteriors must have two columns and one row per fixed flag") - if not (original_breaks.size == rescaled_breaks.size and original_breaks.size > 0): - raise ValueError("Breakpoints must be non-empty and of the same size") + if not (original_breaks.size == rescaled_breaks.size): + raise ValueError("Breakpoints must be of the same size") + if original_breaks.size == 0: + raise library_error(errors.NO_BREAKPOINTS) if not (1 > quantile_width > 0): raise library_error(errors.INVALID_QUANTILE_WIDTH) @@ -393,6 +395,8 @@ def piecewise_scale_point_estimate( Node ages mapped piecewise linearly from ``original_breaks`` to ``rescaled_breaks``; ages where ``point_fixed`` are unchanged. """ + if original_breaks.size == 0: + raise library_error(errors.NO_BREAKPOINTS) if not ( np.all(np.diff(rescaled_breaks) > 0) and np.all(np.diff(original_breaks) > 0) ): diff --git a/tests/test_oracle_phasing.py b/tests/test_oracle_phasing.py index d691b997..a1362ed3 100644 --- a/tests/test_oracle_phasing.py +++ b/tests/test_oracle_phasing.py @@ -10,7 +10,7 @@ import tskit from oracle import phasing from oracle.errors import ( - BLOCK_OUT_OF_RANGE, + BLOCK_OUT_OF_BOUNDS, PHASE_OUT_OF_RANGE, UNPHASED_INDIVIDUAL_EDGES, UNPHASED_LIKELIHOOD_NOT_CONSERVED, @@ -217,7 +217,7 @@ def blocks(small_ts_unphased): np.array([0.5]), np.array([0], dtype=np.int32), np.array([[0, -1]], dtype=np.int32), - BLOCK_OUT_OF_RANGE, + BLOCK_OUT_OF_BOUNDS, id="null_edge_in_block", ), ] diff --git a/tests/test_python_c.py b/tests/test_python_c.py index d3d5def1..00cfa462 100644 --- a/tests/test_python_c.py +++ b/tests/test_python_c.py @@ -3,6 +3,8 @@ """ import _tsdate +import msprime +import numpy as np import pytest ERR_GENERIC = -1 @@ -64,3 +66,292 @@ def test_unknown_code(self): def test_bad_argument(self): with pytest.raises(TypeError): _tsdate.raise_library_error("x") + + +@pytest.fixture(scope="module") +def ts(): + """ + A small tree sequence with recombination, mutations and two diploid individuals + """ + ts = msprime.sim_ancestry( + 2, + sequence_length=1e4, + recombination_rate=1e-8, + population_size=1e4, + random_seed=2, + ) + return msprime.sim_mutations(ts, rate=1e-7, random_seed=2) + + +def bad_ids(ids, value): + """ + A copy of ``ids`` with the last entry replaced by ``value`` + """ + ids = ids.copy() + ids[-1] = value + return ids + + +def sweep_args(ts, **replace): + """ + The edge arrays of ``ts`` used by a sweep over its trees, with replacements + """ + args = { + "edges_parent": ts.edges_parent, + "edges_child": ts.edges_child, + "edges_left": ts.edges_left, + "edges_right": ts.edges_right, + "insert": ts.indexes_edge_insertion_order, + "remove": ts.indexes_edge_removal_order, + "mutations_node": ts.mutations_node, + } + args.update(replace) + return args + + +def call_sweep(name, ts, a): + """ + Call the sweep function ``name`` with the arrays ``a`` + """ + position = ts.sites_position[ts.mutations_site] + edges = (a["edges_parent"], a["edges_child"], a["edges_left"], a["edges_right"]) + indexes = (a["insert"], a["remove"]) + if name == "count_mutations": + sample = np.zeros(ts.num_nodes, dtype=bool) + sample[ts.samples()] = True + return _tsdate.count_mutations( + sample, + a["mutations_node"], + position, + *edges, + *indexes, + ts.sequence_length, + True, + ) + if name == "mutation_frequency": + sample = np.zeros((ts.num_nodes, 1), dtype=bool) + sample[ts.samples(), 0] = True + return _tsdate.mutation_frequency( + sample, a["mutations_node"], position, *edges, *indexes, ts.sequence_length + ) + if name == "block_singletons": + return _tsdate.block_singletons( + np.ones(ts.num_individuals, dtype=bool), + ts.nodes_individual, + a["mutations_node"], + position, + *edges, + *indexes, + ts.sequence_length, + ) + if name == "contains_unary_nodes": + return _tsdate.contains_unary_nodes( + np.zeros(ts.num_nodes, dtype=bool), + a["edges_parent"], + a["edges_left"], + a["edges_right"], + *indexes, + ts.sequence_length, + ts.num_nodes, + ) + assert name == "relabel_mutations_node" + return _tsdate.relabel_mutations_node( + a["mutations_node"], + position, + np.arange(ts.num_nodes, dtype=np.int32), + *edges, + *indexes, + ) + + +SWEEPS = [ + "count_mutations", + "mutation_frequency", + "block_singletons", + "contains_unary_nodes", + "relabel_mutations_node", +] + + +class TestBadTreeArguments: + """ + The library's errors for ids out of bounds and for edges that cannot be swept + """ + + @pytest.mark.parametrize("name", SWEEPS) + def test_valid(self, ts, name): + call_sweep(name, ts, sweep_args(ts)) + + @pytest.mark.parametrize("name", sorted(set(SWEEPS) - {"block_singletons"})) + @pytest.mark.parametrize("value", [-1, 2**30]) + def test_parent_out_of_bounds(self, ts, name, value): + a = sweep_args(ts, edges_parent=bad_ids(ts.edges_parent, value)) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + call_sweep(name, ts, a) + + @pytest.mark.parametrize("name", sorted(set(SWEEPS) - {"contains_unary_nodes"})) + def test_mutation_node_out_of_bounds(self, ts, name): + a = sweep_args(ts, mutations_node=bad_ids(ts.mutations_node, ts.num_nodes)) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + call_sweep(name, ts, a) + + @pytest.mark.parametrize("name", SWEEPS) + def test_nan_interval(self, ts, name): + a = sweep_args(ts, edges_right=bad_ids(ts.edges_right, np.nan)) + with pytest.raises(_tsdate.LibraryError, match="Edge interval"): + call_sweep(name, ts, a) + + @pytest.mark.parametrize("name", sorted(set(SWEEPS) - {"relabel_mutations_node"})) + def test_interval_past_end(self, ts, name): + right = bad_ids(ts.edges_right, 2 * ts.sequence_length) + with pytest.raises(_tsdate.LibraryError, match="Edge interval"): + call_sweep(name, ts, sweep_args(ts, edges_right=right)) + + @pytest.mark.parametrize("name", SWEEPS) + def test_empty_interval(self, ts, name): + left = ts.edges_left.copy() + left[-1] = ts.edges_right[-1] + with pytest.raises(_tsdate.LibraryError, match="Edge interval"): + call_sweep(name, ts, sweep_args(ts, edges_left=left)) + + @pytest.mark.parametrize("name", SWEEPS) + def test_index_out_of_bounds(self, ts, name): + insert = bad_ids(ts.indexes_edge_insertion_order, ts.num_edges) + with pytest.raises(_tsdate.LibraryError, match="Edge id out of bounds"): + call_sweep(name, ts, sweep_args(ts, insert=insert)) + + @pytest.mark.parametrize("name", SWEEPS) + def test_unsorted_index(self, ts, name): + remove = ts.indexes_edge_removal_order[::-1].copy() + with pytest.raises(_tsdate.LibraryError, match="Edge indexes must list"): + call_sweep(name, ts, sweep_args(ts, remove=remove)) + + @pytest.mark.parametrize("name", ["count_mutations", "mutation_frequency"]) + def test_cycle(self, ts, name): + # every edge from node 0 to node 1 and back over the whole sequence + num_edges = 2 + a = { + "edges_parent": np.array([1, 0], dtype=np.int32), + "edges_child": np.array([0, 1], dtype=np.int32), + "edges_left": np.zeros(num_edges), + "edges_right": np.full(num_edges, ts.sequence_length), + "insert": np.arange(num_edges, dtype=np.int32), + "remove": np.arange(num_edges, dtype=np.int32), + "mutations_node": ts.mutations_node, + } + with pytest.raises(_tsdate.LibraryError, match="Edges form a cycle"): + call_sweep(name, ts, a) + + def test_individual_out_of_bounds(self, ts): + nodes_individual = bad_ids(ts.nodes_individual, ts.num_individuals) + with pytest.raises(_tsdate.LibraryError, match="Individual id out of bounds"): + _tsdate.block_singletons( + np.ones(ts.num_individuals, dtype=bool), + nodes_individual, + ts.mutations_node, + ts.sites_position[ts.mutations_site], + ts.edges_parent, + ts.edges_child, + ts.edges_left, + ts.edges_right, + ts.indexes_edge_insertion_order, + ts.indexes_edge_removal_order, + ts.sequence_length, + ) + + @pytest.mark.parametrize("value", [-1, 2**30]) + def test_constrain_ages(self, ts, value): + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.constrain_ages( + ts.nodes_time, + np.zeros(ts.num_nodes, dtype=bool), + ts.edges_parent, + bad_ids(ts.edges_child, value), + 1e-6, + 3, + ) + + def test_split_disjoint_nodes(self, ts): + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.split_disjoint_nodes( + bad_ids(ts.edges_parent, ts.num_nodes), + ts.edges_child, + ts.edges_left, + ts.edges_right, + np.zeros(ts.num_nodes, dtype=bool), + ) + + def test_relabel_nodes_order(self, ts): + nodes_order = bad_ids(np.arange(ts.num_nodes, dtype=np.int32), ts.num_nodes) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.relabel_mutations_node( + ts.mutations_node, + ts.sites_position[ts.mutations_site], + nodes_order, + ts.edges_parent, + ts.edges_child, + ts.edges_left, + ts.edges_right, + ts.indexes_edge_insertion_order, + ts.indexes_edge_removal_order, + ) + + def test_constraints_are_consistent(self, ts): + constraints = np.tile([0.0, np.inf], (ts.num_nodes, 1)) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.constraints_are_consistent( + constraints, bad_ids(ts.edges_parent, -1), ts.edges_child + ) + + def test_mutational_area(self, ts): + likelihoods = np.ones((ts.num_edges, 2)) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.mutational_area( + ts.nodes_time, + likelihoods, + ts.edges_parent, + bad_ids(ts.edges_child, ts.num_nodes), + ) + + def test_mutational_timescale(self, ts): + likelihoods = np.ones((ts.num_edges, 2)) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.mutational_timescale( + ts.nodes_time, + likelihoods, + np.zeros(ts.num_nodes, dtype=bool), + ts.edges_parent, + bad_ids(ts.edges_child, ts.num_nodes), + 2, + ) + + +class TestTooFew: + """ + The library's errors for too few tips or breakpoints + """ + + def test_conditional_coalescent_variance(self): + with pytest.raises(_tsdate.LibraryError, match="Too few tips"): + _tsdate.conditional_coalescent_variance(0) + + def test_marginalize_over_ancestors(self): + with pytest.raises(_tsdate.LibraryError, match="Too few tips"): + _tsdate.marginalize_over_ancestors(np.ones((1, 2))) + + def test_piecewise_scale_point_estimate(self): + with pytest.raises(_tsdate.LibraryError, match="No breakpoints"): + _tsdate.piecewise_scale_point_estimate( + np.zeros(1), np.zeros(1, dtype=bool), np.zeros(0), np.zeros(0) + ) + + def test_piecewise_scale_posterior(self): + with pytest.raises(_tsdate.LibraryError, match="No breakpoints"): + _tsdate.piecewise_scale_posterior( + np.ones((1, 2)), + np.zeros(1, dtype=bool), + np.zeros(0), + np.zeros(0), + 0.5, + 1000.0, + ) diff --git a/tests/test_python_c_rescaling.py b/tests/test_python_c_rescaling.py index 5b569d2f..8b5c6662 100644 --- a/tests/test_python_c_rescaling.py +++ b/tests/test_python_c_rescaling.py @@ -33,11 +33,11 @@ def test_wrong_dimension(self): def test_empty_breaks(self): empty = np.zeros(0) - with pytest.raises(ValueError, match="non-empty"): + with pytest.raises(_tsdate.LibraryError, match="No breakpoints"): _tsdate.piecewise_scale_point_estimate( np.zeros(1), np.zeros(1, dtype=bool), empty, empty ) - with pytest.raises(ValueError, match="non-empty"): + with pytest.raises(_tsdate.LibraryError, match="No breakpoints"): _tsdate.piecewise_scale_posterior( np.ones((1, 2)), np.zeros(1, dtype=bool), empty, empty, 0.5, 1000.0 ) diff --git a/tests/test_python_c_tables.py b/tests/test_python_c_tables.py index 59d953a4..d27698fb 100644 --- a/tests/test_python_c_tables.py +++ b/tests/test_python_c_tables.py @@ -59,12 +59,12 @@ def call(likelihood, phase, mutations_block, blocks_edges): np.array(blocks_edges, dtype=np.int32).reshape(-1, 2), ) - def test_block_out_of_range(self): - with pytest.raises(_tsdate.LibraryError, match="out of range"): + def test_block_out_of_bounds(self): + with pytest.raises(_tsdate.LibraryError, match="out of bounds"): self.call(np.ones((2, 2)), [0.5], [1], [[0, 1]]) - def test_edge_out_of_range(self): - with pytest.raises(_tsdate.LibraryError, match="out of range"): + def test_edge_out_of_bounds(self): + with pytest.raises(_tsdate.LibraryError, match="out of bounds"): self.call(np.ones((2, 2)), [0.5], [0], [[0, 7]]) def test_columns(self): @@ -125,13 +125,16 @@ def test_contains_unary_nodes_mask_size(self): class TestPrior: def test_marginalize_over_ancestors_one_tip(self): - with pytest.raises(ValueError, match="At least two"): + with pytest.raises(_tsdate.LibraryError, match="Too few tips"): _tsdate.marginalize_over_ancestors(np.ones((1, 2))) - @pytest.mark.parametrize("num_tips", [0, -1]) - def test_variance_no_tips(self, num_tips): - with pytest.raises(ValueError, match="positive"): - _tsdate.conditional_coalescent_variance(num_tips) + def test_variance_no_tips(self): + with pytest.raises(_tsdate.LibraryError, match="Too few tips"): + _tsdate.conditional_coalescent_variance(0) + + def test_variance_negative_tips(self): + with pytest.raises(ValueError, match="non-negative"): + _tsdate.conditional_coalescent_variance(-1) def test_variance_one_tip(self): # the result is unused by tsdate From a7a7d6f408db17eeeaa7168fb77227f361b17911 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 10:45:45 -0800 Subject: [PATCH 44/56] Explain the bound on the ancestor walks --- lib/phasing.c | 3 ++- lib/rescaling.c | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/phasing.c b/lib/phasing.c index b062ff80..94a7f96a 100644 --- a/lib/phasing.c +++ b/lib/phasing.c @@ -349,7 +349,8 @@ tsd_reallocate_unphased(tsd_size_t num_edges, tsd_size_t num_mutations, /* * Add (sign = 1) or subtract (sign = -1) the sample counts of node `c` to those of - * `p` and of every ancestor of `p`. + * `p` and of every ancestor of `p`. Each node has one parent in the current tree, so a + * walk of more than num_nodes steps has repeated a node: the edges form a cycle. */ static int update_ancestors(tsd_size_t num_nodes, tsd_size_t num_sample_sets, tsd_id_t p, diff --git a/lib/rescaling.c b/lib/rescaling.c index f078cea5..48dbb56c 100644 --- a/lib/rescaling.c +++ b/lib/rescaling.c @@ -365,7 +365,9 @@ tsd_poisson_changepoints(tsd_size_t num_counts, const double *counts, /* * Add (sign = 1) or remove (sign = -1) the span of the edge `e`, to the parent `p` of * its child `c`, and to every ancestor of `p`, in proportion to the number of - * samples below `c`; and update the sample counts of the ancestors. + * samples below `c`; and update the sample counts of the ancestors. Each node has one + * parent in the current tree, so a walk of more than num_nodes steps has repeated a + * node: the edges form a cycle. */ static int count_update_ancestors(tsd_size_t num_nodes, tsd_id_t e, tsd_id_t p, tsd_id_t c, From 5097c332253cca57d24db8a644532d975e8d72f3 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 11:59:45 -0800 Subject: [PATCH 45/56] Hold the expectation propagation state in a C type, and write the module conventionally The library holds the EP state in tsd_ep_t, with tsd_ep_init (which copies the inputs and validates the node ids once) and tsd_ep_free; the passes are functions of it, and tsd_ep_propagate_mutations returns the posteriors and phases of the mutations above given edges. _tsdate.ExpectationPropagation wraps it, with the passes as methods and copies of the posteriors and log normalising constants as read-only properties. Each function of the module that tsdate calls has its own wrapper, parsing keyword arguments (which the callers pass) into named arrays. No function updates a caller's array: reallocate_unphased returns the reallocated likelihoods. block_singletons no longer takes the unused edge parents, and contains_unary_nodes takes the number of nodes from the mask. The oracle has an ExpectationPropagation with the same methods, and the EP equivalence tests run the same passes on both from the same inputs. States that tests set directly to reach branches (single edges with chosen cavities, scales at the rescaling threshold, failing projections) are tables of the C tests, with expected values from the reference implementation, compared within 4 ulps. --- CHANGELOG.md | 10 + _tsdatemodule.c | 2463 ++++++++++++++++------------ lib/tests/tests.c | 1892 +++++++++++++++++++-- lib/tsdate.h | 98 +- lib/variational.c | 258 ++- tests/oracle/ep_state.py | 375 +---- tests/oracle/phasing.py | 27 +- tests/oracle/rescaling.py | 17 +- tests/oracle/util.py | 37 +- tests/oracle/variational.py | 152 +- tests/test_oracle_phasing.py | 6 +- tests/test_oracle_util.py | 1 - tests/test_oracle_variational.py | 658 +++----- tests/test_python_c.py | 276 +++- tests/test_python_c_tables.py | 26 +- tests/test_python_c_variational.py | 338 ---- tsdate/phasing.py | 41 +- tsdate/prior.py | 5 +- tsdate/rescaling.py | 51 +- tsdate/util.py | 55 +- tsdate/variational.py | 185 +-- 21 files changed, 4318 insertions(+), 2653 deletions(-) delete mode 100644 tests/test_python_c_variational.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cbe23bb..6766b7f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,11 +25,21 @@ In development - Removed the internal `tsdate.approx` and `tsdate.hypergeo` modules; the special functions and gamma approximations are now part of the `_tsdate` C extension. +- The state of `ExpectationPropagation` (the factors, posteriors and normalising + constants) is held by the C extension: the `factors` attribute and the + `EPFactors` class are gone, and `node_posterior`, `edge_logconst` and + `block_logconst` are copies updated by `iterate`. + `tsdate.phasing.reallocate_unphased` returns the reallocated likelihoods instead + of updating its first argument. + **Bugfixes** - Removed an assertion in `split_disjoint_nodes` that is not guarenteed to hold since table sorting changes the order of mutations in tskit 1.0.0 onwards +- `tsdate.rescaling.count_mutations` rejected sample masks of the right size and + accepted those of the wrong size. + ## [0.2.6] - 2026-03-06 Maintenance release. diff --git a/_tsdatemodule.c b/_tsdatemodule.c index a0937b8b..82a85d73 100644 --- a/_tsdatemodule.c +++ b/_tsdatemodule.c @@ -634,126 +634,139 @@ tsdate_average_gammas(PyObject *Py_UNUSED(self), PyObject *args) } /* - * Phasing, utilities and prior: array-level functions. Each takes the arguments of its - * oracle in tests/oracle; array sizes and shapes are checked here and raise ValueError. + * Functions of the tree sequence (phasing, utilities, prior and rescaling). Arrays are + * converted to C-contiguous arrays of the right type and dimension; sizes of arrays + * that share a dimension are checked here (ValueError), and everything else by the + * library. */ -#define MAX_ARRAYS 10 - -/* Convert `num_arrays` objects to C-contiguous arrays of the given types and ndim. */ -static int -parse_arrays(PyObject **objs, const int *typenums, int ndim, int num_arrays, - PyArrayObject **arrays) -{ - int j; - - for (j = 0; j < num_arrays; j++) { - arrays[j] = (PyArrayObject *) PyArray_FROMANY( - objs[j], typenums[j], ndim, ndim, NPY_ARRAY_IN_ARRAY); - if (arrays[j] == NULL) { - return -1; - } - } - return 0; -} - -static void -release_arrays(PyArrayObject **arrays, int num_arrays) -{ - int j; - - for (j = 0; j < num_arrays; j++) { - Py_XDECREF(arrays[j]); - } -} - -#define ARRAY_SIZE(array) ((tsd_size_t) PyArray_SIZE(array)) -#define ARRAY_DIM(array, axis) ((tsd_size_t) PyArray_DIM(array, axis)) - -/* Whether all the arrays have the same size; raises ValueError if not. */ -static int -check_sizes_equal(PyArrayObject **arrays, int num_arrays) -{ - int j; - - for (j = 1; j < num_arrays; j++) { - if (ARRAY_SIZE(arrays[j]) != ARRAY_SIZE(arrays[0])) { - PyErr_SetString(PyExc_ValueError, "Array sizes are not equal"); - return -1; - } - } - return 0; -} +#define ARRAY_LEN(array) ((tsd_size_t) PyArray_DIM((array), 0)) +#define DOUBLES(array) ((double *) PyArray_DATA(array)) +#define IDS(array) ((tsd_id_t *) PyArray_DATA(array)) +#define FLAGS(array) ((uint8_t *) PyArray_DATA(array)) -/* A new array of the given type and shape, copying `size` bytes from `data`. */ -static PyObject * -array_from_data(int typenum, int ndim, npy_intp *dims, const void *data, size_t size) +/* A new array of the given type and shape holding a copy of `data`. */ +static PyArrayObject * +new_array_from_data(int typenum, int ndim, npy_intp *dims, const void *data) { - PyObject *ret = PyArray_SimpleNew(ndim, dims, typenum); + PyArrayObject *ret = (PyArrayObject *) PyArray_SimpleNew(ndim, dims, typenum); - if (ret != NULL && size > 0) { - memcpy(PyArray_DATA((PyArrayObject *) ret), data, size); + if (ret != NULL) { + memcpy(PyArray_DATA(ret), data, (size_t) PyArray_NBYTES(ret)); } return ret; } -/* - * block_singletons(individuals_unphased, nodes_individual, mutations_node, - * mutations_position, edges_parent, edges_child, edges_left, edges_right, - * indexes_insert, indexes_remove, sequence_length) - * returns (blocks_stats, blocks_edges, mutations_block). - */ static PyObject * -tsdate_block_singletons(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_block_singletons(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *objs[10]; - const int typenums[10] = { NPY_BOOL, NPY_INT32, NPY_INT32, NPY_FLOAT64, NPY_INT32, - NPY_INT32, NPY_FLOAT64, NPY_FLOAT64, NPY_INT32, NPY_INT32 }; - PyArrayObject *arrays[10] = { NULL }; - PyObject *stats_array = NULL; - PyObject *edges_array = NULL; - PyObject *mutations_block = NULL; - double *blocks_stats = NULL; - tsd_id_t *blocks_edges = NULL; - tsd_size_t num_blocks = 0; - npy_intp dims[2]; + static char *kwlist[] = { "individuals_unphased", "nodes_individual", + "mutations_node", "mutations_position", "edges_child", "edges_left", + "edges_right", "indexes_insert", "indexes_remove", "sequence_length", NULL }; + PyObject *individuals_unphased_obj = NULL; + PyObject *nodes_individual_obj = NULL; + PyObject *mutations_node_obj = NULL; + PyObject *mutations_position_obj = NULL; + PyObject *edges_child_obj = NULL; + PyObject *edges_left_obj = NULL; + PyObject *edges_right_obj = NULL; + PyObject *indexes_insert_obj = NULL; + PyObject *indexes_remove_obj = NULL; + PyArrayObject *individuals_unphased = NULL; + PyArrayObject *nodes_individual = NULL; + PyArrayObject *mutations_node = NULL; + PyArrayObject *mutations_position = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *edges_left = NULL; + PyArrayObject *edges_right = NULL; + PyArrayObject *indexes_insert = NULL; + PyArrayObject *indexes_remove = NULL; + PyArrayObject *blocks_stats = NULL; + PyArrayObject *blocks_edges = NULL; + PyArrayObject *mutations_block = NULL; + double *stats = NULL; + tsd_id_t *edges = NULL; double sequence_length; + tsd_size_t num_edges, num_mutations, num_blocks = 0; + npy_intp dims[2]; int err; - if (!PyArg_ParseTuple(args, "OOOOOOOOOOd", &objs[0], &objs[1], &objs[2], &objs[3], - &objs[4], &objs[5], &objs[6], &objs[7], &objs[8], &objs[9], - &sequence_length)) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOOd", kwlist, + &individuals_unphased_obj, &nodes_individual_obj, &mutations_node_obj, + &mutations_position_obj, &edges_child_obj, &edges_left_obj, &edges_right_obj, + &indexes_insert_obj, &indexes_remove_obj, &sequence_length)) { goto out; } - if (parse_arrays(objs, typenums, 1, 10, arrays) != 0) { + individuals_unphased = (PyArrayObject *) PyArray_FROMANY( + individuals_unphased_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (individuals_unphased == NULL) { goto out; } - if (check_sizes_equal(arrays + 4, 4) != 0 || check_sizes_equal(arrays + 8, 2) != 0 - || check_sizes_equal(arrays + 2, 2) != 0 - || ARRAY_SIZE(arrays[8]) != ARRAY_SIZE(arrays[4])) { - PyErr_SetString(PyExc_ValueError, "Array sizes are not equal"); + nodes_individual = (PyArrayObject *) PyArray_FROMANY( + nodes_individual_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_individual == NULL) { + goto out; + } + mutations_node = (PyArrayObject *) PyArray_FROMANY( + mutations_node_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_node == NULL) { + goto out; + } + mutations_position = (PyArrayObject *) PyArray_FROMANY( + mutations_position_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_position == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + edges_left = (PyArrayObject *) PyArray_FROMANY( + edges_left_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_left == NULL) { + goto out; + } + edges_right = (PyArrayObject *) PyArray_FROMANY( + edges_right_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_right == NULL) { + goto out; + } + indexes_insert = (PyArrayObject *) PyArray_FROMANY( + indexes_insert_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_insert == NULL) { + goto out; + } + indexes_remove = (PyArrayObject *) PyArray_FROMANY( + indexes_remove_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_remove == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_child); + num_mutations = ARRAY_LEN(mutations_node); + if (ARRAY_LEN(edges_left) != num_edges || ARRAY_LEN(edges_right) != num_edges + || ARRAY_LEN(indexes_insert) != num_edges + || ARRAY_LEN(indexes_remove) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); goto out; } - dims[0] = PyArray_DIM(arrays[2], 0); - mutations_block = PyArray_SimpleNew(1, dims, NPY_INT32); + if (ARRAY_LEN(mutations_position) != num_mutations) { + PyErr_SetString(PyExc_ValueError, "Mutation arrays must have the same size"); + goto out; + } + dims[0] = (npy_intp) num_mutations; + mutations_block = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_INT32); if (mutations_block == NULL) { goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_block_singletons(ARRAY_SIZE(arrays[1]), ARRAY_SIZE(arrays[0]), - ARRAY_SIZE(arrays[4]), ARRAY_SIZE(arrays[2]), - (const uint8_t *) PyArray_DATA(arrays[0]), - (const tsd_id_t *) PyArray_DATA(arrays[1]), - (const tsd_id_t *) PyArray_DATA(arrays[2]), - (const double *) PyArray_DATA(arrays[3]), - (const tsd_id_t *) PyArray_DATA(arrays[5]), - (const double *) PyArray_DATA(arrays[6]), - (const double *) PyArray_DATA(arrays[7]), - (const tsd_id_t *) PyArray_DATA(arrays[8]), - (const tsd_id_t *) PyArray_DATA(arrays[9]), sequence_length, &num_blocks, - &blocks_stats, &blocks_edges, - (tsd_id_t *) PyArray_DATA((PyArrayObject *) mutations_block)); + err = tsd_block_singletons(ARRAY_LEN(nodes_individual), + ARRAY_LEN(individuals_unphased), num_edges, num_mutations, + FLAGS(individuals_unphased), IDS(nodes_individual), IDS(mutations_node), + DOUBLES(mutations_position), IDS(edges_child), DOUBLES(edges_left), + DOUBLES(edges_right), IDS(indexes_insert), IDS(indexes_remove), sequence_length, + &num_blocks, &stats, &edges, IDS(mutations_block)); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); @@ -761,398 +774,613 @@ tsdate_block_singletons(PyObject *Py_UNUSED(self), PyObject *args) } dims[0] = (npy_intp) num_blocks; dims[1] = 2; - stats_array = array_from_data( - NPY_FLOAT64, 2, dims, blocks_stats, 2 * num_blocks * sizeof(*blocks_stats)); - edges_array = array_from_data( - NPY_INT32, 2, dims, blocks_edges, 2 * num_blocks * sizeof(*blocks_edges)); - if (stats_array == NULL || edges_array == NULL) { + blocks_stats = new_array_from_data(NPY_FLOAT64, 2, dims, stats); + if (blocks_stats == NULL) { + goto out; + } + blocks_edges = new_array_from_data(NPY_INT32, 2, dims, edges); + if (blocks_edges == NULL) { goto out; } - ret = Py_BuildValue("OOO", stats_array, edges_array, mutations_block); + ret = Py_BuildValue("OOO", blocks_stats, blocks_edges, mutations_block); out: - release_arrays(arrays, 10); - Py_XDECREF(stats_array); - Py_XDECREF(edges_array); + tsd_safe_free(stats); + tsd_safe_free(edges); + Py_XDECREF(individuals_unphased); + Py_XDECREF(nodes_individual); + Py_XDECREF(mutations_node); + Py_XDECREF(mutations_position); + Py_XDECREF(edges_child); + Py_XDECREF(edges_left); + Py_XDECREF(edges_right); + Py_XDECREF(indexes_insert); + Py_XDECREF(indexes_remove); + Py_XDECREF(blocks_stats); + Py_XDECREF(blocks_edges); Py_XDECREF(mutations_block); - tsd_safe_free(blocks_stats); - tsd_safe_free(blocks_edges); - return ret; -} - -/* - * A float64 array of the given dimension that the call updates in place: `obj` itself, - * which must not need converting (a copy would silently lose the updates). - */ -static PyArrayObject * -get_inout_array(PyObject *obj, int ndim) -{ - PyArrayObject *ret = (PyArrayObject *) PyArray_FROMANY( - obj, NPY_FLOAT64, ndim, ndim, NPY_ARRAY_INOUT_ARRAY); - - if (ret != NULL && (PyObject *) ret != obj) { - Py_DECREF(ret); - ret = NULL; - PyErr_SetString(PyExc_ValueError, - "Arrays that are updated must be writeable, C-contiguous float64 arrays"); - } return ret; } -/* - * reallocate_unphased(edges_likelihood, mutations_phase, mutations_block, - * blocks_edges): updates edges_likelihood in place. - */ static PyObject * -tsdate_reallocate_unphased(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_reallocate_unphased(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *likelihood_obj = NULL; - PyObject *phase_obj = NULL; - PyObject *block_obj = NULL; - PyObject *edges_obj = NULL; - PyArrayObject *likelihood_array = NULL; - PyArrayObject *phase_array = NULL; - PyArrayObject *block_array = NULL; - PyArrayObject *edges_array = NULL; + static char *kwlist[] = { "edges_likelihood", "mutations_phase", "mutations_block", + "blocks_edges", NULL }; + PyObject *edges_likelihood_obj = NULL; + PyObject *mutations_phase_obj = NULL; + PyObject *mutations_block_obj = NULL; + PyObject *blocks_edges_obj = NULL; + PyArrayObject *edges_likelihood = NULL; + PyArrayObject *mutations_phase = NULL; + PyArrayObject *mutations_block = NULL; + PyArrayObject *blocks_edges = NULL; + PyArrayObject *new_likelihood = NULL; int err; - if (!PyArg_ParseTuple( - args, "OOOO", &likelihood_obj, &phase_obj, &block_obj, &edges_obj)) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOO", kwlist, &edges_likelihood_obj, + &mutations_phase_obj, &mutations_block_obj, &blocks_edges_obj)) { goto out; } - likelihood_array = get_inout_array(likelihood_obj, 2); - phase_array = (PyArrayObject *) PyArray_FROMANY( - phase_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); - block_array = (PyArrayObject *) PyArray_FROMANY( - block_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); - edges_array = (PyArrayObject *) PyArray_FROMANY( - edges_obj, NPY_INT32, 2, 2, NPY_ARRAY_IN_ARRAY); - if (likelihood_array == NULL || phase_array == NULL || block_array == NULL - || edges_array == NULL) { + edges_likelihood = (PyArrayObject *) PyArray_FROMANY( + edges_likelihood_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (edges_likelihood == NULL) { goto out; } - if (ARRAY_SIZE(phase_array) != ARRAY_SIZE(block_array)) { - PyErr_SetString(PyExc_ValueError, "Array sizes are not equal"); + mutations_phase = (PyArrayObject *) PyArray_FROMANY( + mutations_phase_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_phase == NULL) { + goto out; + } + mutations_block = (PyArrayObject *) PyArray_FROMANY( + mutations_block_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_block == NULL) { goto out; } - if (ARRAY_DIM(edges_array, 1) != 2 || ARRAY_DIM(likelihood_array, 1) != 2) { - PyErr_SetString(PyExc_ValueError, "Arrays must have two columns"); + blocks_edges = (PyArrayObject *) PyArray_FROMANY( + blocks_edges_obj, NPY_INT32, 2, 2, NPY_ARRAY_IN_ARRAY); + if (blocks_edges == NULL) { + goto out; + } + if (PyArray_DIM(edges_likelihood, 1) != 2 || PyArray_DIM(blocks_edges, 1) != 2) { + PyErr_SetString( + PyExc_ValueError, "edges_likelihood and blocks_edges must have two columns"); + goto out; + } + if (ARRAY_LEN(mutations_block) != ARRAY_LEN(mutations_phase)) { + PyErr_SetString(PyExc_ValueError, "Mutation arrays must have the same size"); + goto out; + } + new_likelihood = (PyArrayObject *) PyArray_NewCopy(edges_likelihood, NPY_CORDER); + if (new_likelihood == NULL) { goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_reallocate_unphased(ARRAY_DIM(likelihood_array, 0), - ARRAY_SIZE(phase_array), ARRAY_DIM(edges_array, 0), - (const double *) PyArray_DATA(phase_array), - (const tsd_id_t *) PyArray_DATA(block_array), - (const tsd_id_t *) PyArray_DATA(edges_array), - (double *) PyArray_DATA(likelihood_array)); + err = tsd_reallocate_unphased(ARRAY_LEN(new_likelihood), ARRAY_LEN(mutations_phase), + ARRAY_LEN(blocks_edges), DOUBLES(mutations_phase), IDS(mutations_block), + IDS(blocks_edges), DOUBLES(new_likelihood)); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); goto out; } - ret = Py_None; - Py_INCREF(ret); + ret = (PyObject *) new_likelihood; + new_likelihood = NULL; out: - Py_XDECREF(likelihood_array); - Py_XDECREF(phase_array); - Py_XDECREF(block_array); - Py_XDECREF(edges_array); + Py_XDECREF(edges_likelihood); + Py_XDECREF(mutations_phase); + Py_XDECREF(mutations_block); + Py_XDECREF(blocks_edges); + Py_XDECREF(new_likelihood); return ret; } -/* - * mutation_frequency(nodes_sample, mutations_node, mutations_position, edges_parent, - * edges_child, edges_left, edges_right, indexes_insert, indexes_remove, - * sequence_length) returns an int32 array of shape (mutations, sample sets). - */ static PyObject * -tsdate_mutation_frequency(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_mutation_frequency(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *sample_obj = NULL; - PyObject *objs[MAX_ARRAYS]; - const int typenums[9] = { NPY_INT32, NPY_FLOAT64, NPY_INT32, NPY_INT32, NPY_FLOAT64, - NPY_FLOAT64, NPY_INT32, NPY_INT32 }; - PyArrayObject *sample_array = NULL; - PyArrayObject *arrays[8] = { NULL }; - PyObject *freq_array = NULL; - npy_intp dims[2]; + static char *kwlist[] = { "nodes_sample", "mutations_node", "mutations_position", + "edges_parent", "edges_child", "edges_left", "edges_right", "indexes_insert", + "indexes_remove", "sequence_length", NULL }; + PyObject *nodes_sample_obj = NULL; + PyObject *mutations_node_obj = NULL; + PyObject *mutations_position_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyObject *edges_left_obj = NULL; + PyObject *edges_right_obj = NULL; + PyObject *indexes_insert_obj = NULL; + PyObject *indexes_remove_obj = NULL; + PyArrayObject *nodes_sample = NULL; + PyArrayObject *mutations_node = NULL; + PyArrayObject *mutations_position = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *edges_left = NULL; + PyArrayObject *edges_right = NULL; + PyArrayObject *indexes_insert = NULL; + PyArrayObject *indexes_remove = NULL; + PyArrayObject *mutations_freq = NULL; double sequence_length; + tsd_size_t num_edges, num_mutations; + npy_intp dims[2]; int err; - if (!PyArg_ParseTuple(args, "OOOOOOOOOd", &sample_obj, &objs[0], &objs[1], &objs[2], - &objs[3], &objs[4], &objs[5], &objs[6], &objs[7], &sequence_length)) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOOd", kwlist, &nodes_sample_obj, + &mutations_node_obj, &mutations_position_obj, &edges_parent_obj, + &edges_child_obj, &edges_left_obj, &edges_right_obj, &indexes_insert_obj, + &indexes_remove_obj, &sequence_length)) { goto out; } - sample_array = (PyArrayObject *) PyArray_FROMANY( - sample_obj, NPY_BOOL, 2, 2, NPY_ARRAY_IN_ARRAY); - if (sample_array == NULL) { + nodes_sample = (PyArrayObject *) PyArray_FROMANY( + nodes_sample_obj, NPY_BOOL, 2, 2, NPY_ARRAY_IN_ARRAY); + if (nodes_sample == NULL) { goto out; } - if (parse_arrays(objs, typenums, 1, 8, arrays) != 0) { + mutations_node = (PyArrayObject *) PyArray_FROMANY( + mutations_node_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_node == NULL) { goto out; } - if (check_sizes_equal(arrays + 2, 4) != 0 || check_sizes_equal(arrays + 6, 2) != 0 - || check_sizes_equal(arrays, 2) != 0 - || ARRAY_SIZE(arrays[6]) != ARRAY_SIZE(arrays[2])) { - PyErr_SetString(PyExc_ValueError, "Array sizes are not equal"); + mutations_position = (PyArrayObject *) PyArray_FROMANY( + mutations_position_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_position == NULL) { + goto out; + } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + edges_left = (PyArrayObject *) PyArray_FROMANY( + edges_left_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_left == NULL) { + goto out; + } + edges_right = (PyArrayObject *) PyArray_FROMANY( + edges_right_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_right == NULL) { + goto out; + } + indexes_insert = (PyArrayObject *) PyArray_FROMANY( + indexes_insert_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_insert == NULL) { + goto out; + } + indexes_remove = (PyArrayObject *) PyArray_FROMANY( + indexes_remove_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_remove == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + num_mutations = ARRAY_LEN(mutations_node); + if (ARRAY_LEN(edges_child) != num_edges || ARRAY_LEN(edges_left) != num_edges + || ARRAY_LEN(edges_right) != num_edges || ARRAY_LEN(indexes_insert) != num_edges + || ARRAY_LEN(indexes_remove) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + if (ARRAY_LEN(mutations_position) != num_mutations) { + PyErr_SetString(PyExc_ValueError, "Mutation arrays must have the same size"); goto out; } - dims[0] = PyArray_DIM(arrays[0], 0); - dims[1] = PyArray_DIM(sample_array, 1); - freq_array = PyArray_SimpleNew(2, dims, NPY_INT32); - if (freq_array == NULL) { + dims[0] = (npy_intp) num_mutations; + dims[1] = PyArray_DIM(nodes_sample, 1); + mutations_freq = (PyArrayObject *) PyArray_SimpleNew(2, dims, NPY_INT32); + if (mutations_freq == NULL) { goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_mutation_frequency(ARRAY_DIM(sample_array, 0), ARRAY_DIM(sample_array, 1), - ARRAY_SIZE(arrays[2]), ARRAY_SIZE(arrays[0]), - (const uint8_t *) PyArray_DATA(sample_array), - (const tsd_id_t *) PyArray_DATA(arrays[0]), - (const double *) PyArray_DATA(arrays[1]), - (const tsd_id_t *) PyArray_DATA(arrays[2]), - (const tsd_id_t *) PyArray_DATA(arrays[3]), - (const double *) PyArray_DATA(arrays[4]), - (const double *) PyArray_DATA(arrays[5]), - (const tsd_id_t *) PyArray_DATA(arrays[6]), - (const tsd_id_t *) PyArray_DATA(arrays[7]), sequence_length, - (int32_t *) PyArray_DATA((PyArrayObject *) freq_array)); + err = tsd_mutation_frequency(ARRAY_LEN(nodes_sample), + (tsd_size_t) PyArray_DIM(nodes_sample, 1), num_edges, num_mutations, + FLAGS(nodes_sample), IDS(mutations_node), DOUBLES(mutations_position), + IDS(edges_parent), IDS(edges_child), DOUBLES(edges_left), DOUBLES(edges_right), + IDS(indexes_insert), IDS(indexes_remove), sequence_length, + (int32_t *) PyArray_DATA(mutations_freq)); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); goto out; } - ret = freq_array; - freq_array = NULL; + ret = (PyObject *) mutations_freq; + mutations_freq = NULL; out: - Py_XDECREF(sample_array); - release_arrays(arrays, 8); - Py_XDECREF(freq_array); + Py_XDECREF(nodes_sample); + Py_XDECREF(mutations_node); + Py_XDECREF(mutations_position); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(edges_left); + Py_XDECREF(edges_right); + Py_XDECREF(indexes_insert); + Py_XDECREF(indexes_remove); + Py_XDECREF(mutations_freq); return ret; } -/* - * split_disjoint_nodes(edges_parent, edges_child, edges_left, edges_right, - * node_excluded) returns (edges_parent, edges_child, nodes_order, split_nodes). - */ static PyObject * -tsdate_split_disjoint_nodes(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_split_disjoint_nodes(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *objs[5]; - const int typenums[5] = { NPY_INT32, NPY_INT32, NPY_FLOAT64, NPY_FLOAT64, NPY_BOOL }; - PyArrayObject *arrays[5] = { NULL }; - PyObject *parent_array = NULL; - PyObject *child_array = NULL; - PyObject *order_array = NULL; - PyObject *split_array = NULL; - tsd_id_t *nodes_order = NULL; - tsd_size_t num_nodes, num_split = 0; + static char *kwlist[] = { "edges_parent", "edges_child", "edges_left", "edges_right", + "nodes_excluded", NULL }; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyObject *edges_left_obj = NULL; + PyObject *edges_right_obj = NULL; + PyObject *nodes_excluded_obj = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *edges_left = NULL; + PyArrayObject *edges_right = NULL; + PyArrayObject *nodes_excluded = NULL; + PyArrayObject *new_parent = NULL; + PyArrayObject *new_child = NULL; + PyArrayObject *nodes_order = NULL; + PyArrayObject *split_nodes = NULL; + tsd_id_t *order = NULL; + tsd_size_t num_nodes, num_edges, num_split = 0; npy_intp dims[1]; int err; - if (!PyArg_ParseTuple( - args, "OOOOO", &objs[0], &objs[1], &objs[2], &objs[3], &objs[4])) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOO", kwlist, &edges_parent_obj, + &edges_child_obj, &edges_left_obj, &edges_right_obj, &nodes_excluded_obj)) { goto out; } - if (parse_arrays(objs, typenums, 1, 5, arrays) != 0) { + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { goto out; } - if (check_sizes_equal(arrays, 4) != 0) { + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { goto out; } - num_nodes = ARRAY_SIZE(arrays[4]); - dims[0] = PyArray_DIM(arrays[0], 0); - parent_array = PyArray_SimpleNew(1, dims, NPY_INT32); - child_array = PyArray_SimpleNew(1, dims, NPY_INT32); - if (parent_array == NULL || child_array == NULL) { + edges_left = (PyArrayObject *) PyArray_FROMANY( + edges_left_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_left == NULL) { + goto out; + } + edges_right = (PyArrayObject *) PyArray_FROMANY( + edges_right_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_right == NULL) { + goto out; + } + nodes_excluded = (PyArrayObject *) PyArray_FROMANY( + nodes_excluded_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_excluded == NULL) { + goto out; + } + num_nodes = ARRAY_LEN(nodes_excluded); + num_edges = ARRAY_LEN(edges_parent); + if (ARRAY_LEN(edges_child) != num_edges || ARRAY_LEN(edges_left) != num_edges + || ARRAY_LEN(edges_right) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + dims[0] = (npy_intp) num_edges; + new_parent = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_INT32); + if (new_parent == NULL) { + goto out; + } + new_child = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_INT32); + if (new_child == NULL) { goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_split_disjoint_nodes(num_nodes, ARRAY_SIZE(arrays[0]), - (const tsd_id_t *) PyArray_DATA(arrays[0]), - (const tsd_id_t *) PyArray_DATA(arrays[1]), - (const double *) PyArray_DATA(arrays[2]), - (const double *) PyArray_DATA(arrays[3]), - (const uint8_t *) PyArray_DATA(arrays[4]), - (tsd_id_t *) PyArray_DATA((PyArrayObject *) parent_array), - (tsd_id_t *) PyArray_DATA((PyArrayObject *) child_array), &num_split, - &nodes_order); + err = tsd_split_disjoint_nodes(num_nodes, num_edges, IDS(edges_parent), + IDS(edges_child), DOUBLES(edges_left), DOUBLES(edges_right), + FLAGS(nodes_excluded), IDS(new_parent), IDS(new_child), &num_split, &order); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); goto out; } dims[0] = (npy_intp) (num_nodes + num_split); - order_array = array_from_data( - NPY_INT32, 1, dims, nodes_order, (num_nodes + num_split) * sizeof(*nodes_order)); + nodes_order = new_array_from_data(NPY_INT32, 1, dims, order); + if (nodes_order == NULL) { + goto out; + } dims[0] = (npy_intp) num_split; - split_array = array_from_data( - NPY_INT32, 1, dims, nodes_order + num_nodes, num_split * sizeof(*nodes_order)); - if (order_array == NULL || split_array == NULL) { + split_nodes = new_array_from_data(NPY_INT32, 1, dims, order + num_nodes); + if (split_nodes == NULL) { goto out; } - ret = Py_BuildValue("OOOO", parent_array, child_array, order_array, split_array); + ret = Py_BuildValue("OOOO", new_parent, new_child, nodes_order, split_nodes); out: - release_arrays(arrays, 5); - Py_XDECREF(parent_array); - Py_XDECREF(child_array); - Py_XDECREF(order_array); - Py_XDECREF(split_array); - tsd_safe_free(nodes_order); + tsd_safe_free(order); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(edges_left); + Py_XDECREF(edges_right); + Py_XDECREF(nodes_excluded); + Py_XDECREF(new_parent); + Py_XDECREF(new_child); + Py_XDECREF(nodes_order); + Py_XDECREF(split_nodes); return ret; } -/* - * relabel_mutations_node(mutations_node, mutations_position, nodes_order, - * edges_parent, edges_child, edges_left, edges_right, insert_index, - * remove_index) returns the new node of each mutation. - */ static PyObject * -tsdate_relabel_mutations_node(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_relabel_mutations_node(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *objs[9]; - const int typenums[9] = { NPY_INT32, NPY_FLOAT64, NPY_INT32, NPY_INT32, NPY_INT32, - NPY_FLOAT64, NPY_FLOAT64, NPY_INT32, NPY_INT32 }; - PyArrayObject *arrays[9] = { NULL }; - PyObject *output = NULL; + static char *kwlist[] = { "mutations_node", "mutations_position", "nodes_order", + "edges_parent", "edges_child", "edges_left", "edges_right", "indexes_insert", + "indexes_remove", NULL }; + PyObject *mutations_node_obj = NULL; + PyObject *mutations_position_obj = NULL; + PyObject *nodes_order_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyObject *edges_left_obj = NULL; + PyObject *edges_right_obj = NULL; + PyObject *indexes_insert_obj = NULL; + PyObject *indexes_remove_obj = NULL; + PyArrayObject *mutations_node = NULL; + PyArrayObject *mutations_position = NULL; + PyArrayObject *nodes_order = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *edges_left = NULL; + PyArrayObject *edges_right = NULL; + PyArrayObject *indexes_insert = NULL; + PyArrayObject *indexes_remove = NULL; + PyArrayObject *new_node = NULL; + tsd_size_t num_edges, num_mutations; npy_intp dims[1]; int err; - if (!PyArg_ParseTuple(args, "OOOOOOOOO", &objs[0], &objs[1], &objs[2], &objs[3], - &objs[4], &objs[5], &objs[6], &objs[7], &objs[8])) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOO", kwlist, + &mutations_node_obj, &mutations_position_obj, &nodes_order_obj, + &edges_parent_obj, &edges_child_obj, &edges_left_obj, &edges_right_obj, + &indexes_insert_obj, &indexes_remove_obj)) { goto out; } - if (parse_arrays(objs, typenums, 1, 9, arrays) != 0) { + mutations_node = (PyArrayObject *) PyArray_FROMANY( + mutations_node_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_node == NULL) { goto out; } - if (check_sizes_equal(arrays + 3, 6) != 0 || check_sizes_equal(arrays, 2) != 0) { + mutations_position = (PyArrayObject *) PyArray_FROMANY( + mutations_position_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_position == NULL) { goto out; } - dims[0] = PyArray_DIM(arrays[0], 0); - output = PyArray_SimpleNew(1, dims, NPY_INT32); - if (output == NULL) { + nodes_order = (PyArrayObject *) PyArray_FROMANY( + nodes_order_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_order == NULL) { + goto out; + } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + edges_left = (PyArrayObject *) PyArray_FROMANY( + edges_left_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_left == NULL) { + goto out; + } + edges_right = (PyArrayObject *) PyArray_FROMANY( + edges_right_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_right == NULL) { + goto out; + } + indexes_insert = (PyArrayObject *) PyArray_FROMANY( + indexes_insert_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_insert == NULL) { + goto out; + } + indexes_remove = (PyArrayObject *) PyArray_FROMANY( + indexes_remove_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_remove == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + num_mutations = ARRAY_LEN(mutations_node); + if (ARRAY_LEN(edges_child) != num_edges || ARRAY_LEN(edges_left) != num_edges + || ARRAY_LEN(edges_right) != num_edges || ARRAY_LEN(indexes_insert) != num_edges + || ARRAY_LEN(indexes_remove) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + if (ARRAY_LEN(mutations_position) != num_mutations) { + PyErr_SetString(PyExc_ValueError, "Mutation arrays must have the same size"); + goto out; + } + dims[0] = (npy_intp) num_mutations; + new_node = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_INT32); + if (new_node == NULL) { goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_relabel_mutations_node(ARRAY_SIZE(arrays[2]), ARRAY_SIZE(arrays[3]), - ARRAY_SIZE(arrays[0]), (const tsd_id_t *) PyArray_DATA(arrays[0]), - (const double *) PyArray_DATA(arrays[1]), - (const tsd_id_t *) PyArray_DATA(arrays[2]), - (const tsd_id_t *) PyArray_DATA(arrays[3]), - (const tsd_id_t *) PyArray_DATA(arrays[4]), - (const double *) PyArray_DATA(arrays[5]), - (const double *) PyArray_DATA(arrays[6]), - (const tsd_id_t *) PyArray_DATA(arrays[7]), - (const tsd_id_t *) PyArray_DATA(arrays[8]), - (tsd_id_t *) PyArray_DATA((PyArrayObject *) output)); + err = tsd_relabel_mutations_node(ARRAY_LEN(nodes_order), num_edges, num_mutations, + IDS(mutations_node), DOUBLES(mutations_position), IDS(nodes_order), + IDS(edges_parent), IDS(edges_child), DOUBLES(edges_left), DOUBLES(edges_right), + IDS(indexes_insert), IDS(indexes_remove), IDS(new_node)); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); goto out; } - ret = output; - output = NULL; + ret = (PyObject *) new_node; + new_node = NULL; out: - release_arrays(arrays, 9); - Py_XDECREF(output); + Py_XDECREF(mutations_node); + Py_XDECREF(mutations_position); + Py_XDECREF(nodes_order); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(edges_left); + Py_XDECREF(edges_right); + Py_XDECREF(indexes_insert); + Py_XDECREF(indexes_remove); + Py_XDECREF(new_node); return ret; } -/* - * constrain_ages(nodes_time, nodes_fixed, edges_parent, edges_child, epsilon, - * max_iterations) returns a new array of node times. - */ static PyObject * -tsdate_constrain_ages(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_constrain_ages(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *objs[4]; - const int typenums[4] = { NPY_FLOAT64, NPY_BOOL, NPY_INT32, NPY_INT32 }; - PyArrayObject *arrays[4] = { NULL }; - PyObject *output = NULL; - npy_intp dims[1]; + static char *kwlist[] = { "nodes_time", "nodes_fixed", "edges_parent", "edges_child", + "epsilon", "max_iterations", NULL }; + PyObject *nodes_time_obj = NULL; + PyObject *nodes_fixed_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyArrayObject *nodes_time = NULL; + PyArrayObject *nodes_fixed = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *new_time = NULL; double epsilon; long long max_iterations; + tsd_size_t num_nodes, num_edges; + npy_intp dims[1]; int err; - if (!PyArg_ParseTuple(args, "OOOOdL", &objs[0], &objs[1], &objs[2], &objs[3], - &epsilon, &max_iterations)) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOdL", kwlist, &nodes_time_obj, + &nodes_fixed_obj, &edges_parent_obj, &edges_child_obj, &epsilon, + &max_iterations)) { goto out; } - if (parse_arrays(objs, typenums, 1, 4, arrays) != 0) { + nodes_time = (PyArrayObject *) PyArray_FROMANY( + nodes_time_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_time == NULL) { goto out; } - if (check_sizes_equal(arrays, 2) != 0 || check_sizes_equal(arrays + 2, 2) != 0) { + nodes_fixed = (PyArrayObject *) PyArray_FROMANY( + nodes_fixed_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_fixed == NULL) { goto out; } - dims[0] = PyArray_DIM(arrays[0], 0); - output = PyArray_SimpleNew(1, dims, NPY_FLOAT64); - if (output == NULL) { + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + num_nodes = ARRAY_LEN(nodes_time); + num_edges = ARRAY_LEN(edges_parent); + if (ARRAY_LEN(nodes_fixed) != num_nodes) { + PyErr_SetString(PyExc_ValueError, "Node arrays must have the same size"); + goto out; + } + if (ARRAY_LEN(edges_child) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + dims[0] = (npy_intp) num_nodes; + new_time = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_FLOAT64); + if (new_time == NULL) { goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_constrain_ages(ARRAY_SIZE(arrays[0]), ARRAY_SIZE(arrays[2]), - (const double *) PyArray_DATA(arrays[0]), - (const uint8_t *) PyArray_DATA(arrays[1]), - (const tsd_id_t *) PyArray_DATA(arrays[2]), - (const tsd_id_t *) PyArray_DATA(arrays[3]), epsilon, (int64_t) max_iterations, - (double *) PyArray_DATA((PyArrayObject *) output)); + err = tsd_constrain_ages(num_nodes, num_edges, DOUBLES(nodes_time), + FLAGS(nodes_fixed), IDS(edges_parent), IDS(edges_child), epsilon, + (int64_t) max_iterations, DOUBLES(new_time)); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); goto out; } - ret = output; - output = NULL; + ret = (PyObject *) new_time; + new_time = NULL; out: - release_arrays(arrays, 4); - Py_XDECREF(output); + Py_XDECREF(nodes_time); + Py_XDECREF(nodes_fixed); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(new_time); return ret; } -/* - * contains_unary_nodes(nodes_mask, edges_parent, edges_left, edges_right, - * indexes_insert, indexes_remove, sequence_length, num_nodes) returns a bool. - */ static PyObject * -tsdate_contains_unary_nodes(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_contains_unary_nodes(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *objs[6]; - const int typenums[6] - = { NPY_BOOL, NPY_INT32, NPY_FLOAT64, NPY_FLOAT64, NPY_INT32, NPY_INT32 }; - PyArrayObject *arrays[6] = { NULL }; + static char *kwlist[] = { "nodes_mask", "edges_parent", "edges_left", "edges_right", + "indexes_insert", "indexes_remove", "sequence_length", NULL }; + PyObject *nodes_mask_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_left_obj = NULL; + PyObject *edges_right_obj = NULL; + PyObject *indexes_insert_obj = NULL; + PyObject *indexes_remove_obj = NULL; + PyArrayObject *nodes_mask = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_left = NULL; + PyArrayObject *edges_right = NULL; + PyArrayObject *indexes_insert = NULL; + PyArrayObject *indexes_remove = NULL; double sequence_length; - Py_ssize_t num_nodes; + tsd_size_t num_edges; int contains_unary = 0; int err; - if (!PyArg_ParseTuple(args, "OOOOOOdn", &objs[0], &objs[1], &objs[2], &objs[3], - &objs[4], &objs[5], &sequence_length, &num_nodes)) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOd", kwlist, &nodes_mask_obj, + &edges_parent_obj, &edges_left_obj, &edges_right_obj, &indexes_insert_obj, + &indexes_remove_obj, &sequence_length)) { goto out; } - if (parse_arrays(objs, typenums, 1, 6, arrays) != 0) { + nodes_mask = (PyArrayObject *) PyArray_FROMANY( + nodes_mask_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_mask == NULL) { goto out; } - if (check_sizes_equal(arrays + 1, 5) != 0) { + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { goto out; } - if (num_nodes < 0 || ARRAY_SIZE(arrays[0]) != (tsd_size_t) num_nodes) { - PyErr_SetString( - PyExc_ValueError, "Mask size does not match the number of nodes"); + edges_left = (PyArrayObject *) PyArray_FROMANY( + edges_left_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_left == NULL) { + goto out; + } + edges_right = (PyArrayObject *) PyArray_FROMANY( + edges_right_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_right == NULL) { + goto out; + } + indexes_insert = (PyArrayObject *) PyArray_FROMANY( + indexes_insert_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_insert == NULL) { + goto out; + } + indexes_remove = (PyArrayObject *) PyArray_FROMANY( + indexes_remove_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_remove == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + if (ARRAY_LEN(edges_left) != num_edges || ARRAY_LEN(edges_right) != num_edges + || ARRAY_LEN(indexes_insert) != num_edges + || ARRAY_LEN(indexes_remove) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_contains_unary_nodes((tsd_size_t) num_nodes, ARRAY_SIZE(arrays[1]), - (const uint8_t *) PyArray_DATA(arrays[0]), - (const tsd_id_t *) PyArray_DATA(arrays[1]), - (const double *) PyArray_DATA(arrays[2]), - (const double *) PyArray_DATA(arrays[3]), - (const tsd_id_t *) PyArray_DATA(arrays[4]), - (const tsd_id_t *) PyArray_DATA(arrays[5]), sequence_length, &contains_unary); + err = tsd_contains_unary_nodes(ARRAY_LEN(nodes_mask), num_edges, FLAGS(nodes_mask), + IDS(edges_parent), DOUBLES(edges_left), DOUBLES(edges_right), + IDS(indexes_insert), IDS(indexes_remove), sequence_length, &contains_unary); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); @@ -1160,63 +1388,27 @@ tsdate_contains_unary_nodes(PyObject *Py_UNUSED(self), PyObject *args) } ret = PyBool_FromLong(contains_unary); out: - release_arrays(arrays, 6); + Py_XDECREF(nodes_mask); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_left); + Py_XDECREF(edges_right); + Py_XDECREF(indexes_insert); + Py_XDECREF(indexes_remove); return ret; } -/* marginalize_over_ancestors(val): val has at least two rows. */ -static PyObject * -tsdate_marginalize_over_ancestors(PyObject *Py_UNUSED(self), PyObject *args) -{ - PyObject *ret = NULL; - PyObject *val_obj = NULL; - PyArrayObject *val_array = NULL; - PyObject *output = NULL; - npy_intp dims[2]; - int err; - - if (!PyArg_ParseTuple(args, "O", &val_obj)) { - goto out; - } - val_array = (PyArrayObject *) PyArray_FROMANY( - val_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); - if (val_array == NULL) { - goto out; - } - dims[0] = PyArray_DIM(val_array, 0) + 1; - dims[1] = PyArray_DIM(val_array, 1); - output = PyArray_SimpleNew(2, dims, NPY_FLOAT64); - if (output == NULL) { - goto out; - } - Py_BEGIN_ALLOW_THREADS - err = tsd_marginalize_over_ancestors(ARRAY_DIM(val_array, 0), - ARRAY_DIM(val_array, 1), (const double *) PyArray_DATA(val_array), - (double *) PyArray_DATA((PyArrayObject *) output)); - Py_END_ALLOW_THREADS - if (err != 0) { - handle_library_error(err); - goto out; - } - ret = output; - output = NULL; -out: - Py_XDECREF(val_array); - Py_XDECREF(output); - return ret; -} - -/* conditional_coalescent_variance(num_tips): an array of num_tips + 1 variances. */ static PyObject * -tsdate_conditional_coalescent_variance(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_conditional_coalescent_variance( + PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *output = NULL; + static char *kwlist[] = { "num_tips", NULL }; + PyArrayObject *variance = NULL; Py_ssize_t num_tips; npy_intp dims[1]; int err; - if (!PyArg_ParseTuple(args, "n", &num_tips)) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "n", kwlist, &num_tips)) { goto out; } if (num_tips < 0) { @@ -1224,232 +1416,137 @@ tsdate_conditional_coalescent_variance(PyObject *Py_UNUSED(self), PyObject *args goto out; } dims[0] = (npy_intp) num_tips + 1; - output = PyArray_SimpleNew(1, dims, NPY_FLOAT64); - if (output == NULL) { + variance = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_FLOAT64); + if (variance == NULL) { goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_conditional_coalescent_variance( - (tsd_size_t) num_tips, (double *) PyArray_DATA((PyArrayObject *) output)); + err = tsd_conditional_coalescent_variance((tsd_size_t) num_tips, DOUBLES(variance)); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); goto out; } - ret = output; - output = NULL; + ret = (PyObject *) variance; + variance = NULL; out: - Py_XDECREF(output); - return ret; -} - -/* - * Rescaling functions (lib/rescaling.c). Array sizes and shapes are checked here and - * raise ValueError. - */ - -/* A one-dimensional array of tsd_id_t (int32), copied from `data`. */ -static PyObject * -new_id_array(tsd_size_t size, const tsd_id_t *data) -{ - npy_intp dim = (npy_intp) size; - PyObject *ret = PyArray_SimpleNew(1, &dim, NPY_INT32); - - if (ret != NULL && size > 0) { - memcpy(PyArray_DATA((PyArrayObject *) ret), data, size * sizeof(*data)); - } - return ret; -} - -/* A one-dimensional array of doubles, copied from `data`. */ -static PyObject * -new_double_array(tsd_size_t size, const double *data) -{ - npy_intp dim = (npy_intp) size; - PyObject *ret = PyArray_SimpleNew(1, &dim, NPY_FLOAT64); - - if (ret != NULL && size > 0) { - memcpy(PyArray_DATA((PyArrayObject *) ret), data, size * sizeof(*data)); - } + Py_XDECREF(variance); return ret; } -/* A C-contiguous array of the given type and dimension from `obj`, or NULL. */ -static PyArrayObject * -get_array(PyObject *obj, int typenum, int ndim) -{ - return (PyArrayObject *) PyArray_FROMANY( - obj, typenum, ndim, ndim, NPY_ARRAY_IN_ARRAY); -} - -/* Raise ValueError and return -1 unless `ok`. */ -static int -check_sizes(int ok, const char *message) -{ - if (!ok) { - PyErr_SetString(PyExc_ValueError, message); - return -1; - } - return 0; -} - -#define ARRAY_LEN(array) ((tsd_size_t) PyArray_DIM((array), 0)) -#define DOUBLES(array) ((const double *) PyArray_DATA(array)) -#define IDS(array) ((const tsd_id_t *) PyArray_DATA(array)) -#define FLAGS(array) ((const uint8_t *) PyArray_DATA(array)) - static PyObject * -tsdate_fixed_changepoints(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_count_mutations(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *counts_obj = NULL; - PyArrayObject *counts = NULL; - long long epochs; - tsd_id_t *breaks = NULL; - tsd_size_t num_breaks = 0; + static char *kwlist[] = { "nodes_sample", "mutations_node", "mutations_position", + "edges_parent", "edges_child", "edges_left", "edges_right", "indexes_insert", + "indexes_remove", "sequence_length", "size_biased", NULL }; + PyObject *nodes_sample_obj = NULL; + PyObject *mutations_node_obj = NULL; + PyObject *mutations_position_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyObject *edges_left_obj = NULL; + PyObject *edges_right_obj = NULL; + PyObject *indexes_insert_obj = NULL; + PyObject *indexes_remove_obj = NULL; + PyArrayObject *nodes_sample = NULL; + PyArrayObject *mutations_node = NULL; + PyArrayObject *mutations_position = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *edges_left = NULL; + PyArrayObject *edges_right = NULL; + PyArrayObject *indexes_insert = NULL; + PyArrayObject *indexes_remove = NULL; + PyArrayObject *edges_stats = NULL; + PyArrayObject *mutations_edge = NULL; + double sequence_length; + int size_biased; + tsd_size_t num_edges, num_mutations; + npy_intp dims[2]; int err; - if (!PyArg_ParseTuple(args, "OL", &counts_obj, &epochs)) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOOdp", kwlist, + &nodes_sample_obj, &mutations_node_obj, &mutations_position_obj, + &edges_parent_obj, &edges_child_obj, &edges_left_obj, &edges_right_obj, + &indexes_insert_obj, &indexes_remove_obj, &sequence_length, &size_biased)) { goto out; } - counts = get_array(counts_obj, NPY_FLOAT64, 1); - if (counts == NULL) { + nodes_sample = (PyArrayObject *) PyArray_FROMANY( + nodes_sample_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_sample == NULL) { goto out; } - Py_BEGIN_ALLOW_THREADS - err = tsd_fixed_changepoints( - ARRAY_LEN(counts), DOUBLES(counts), (int64_t) epochs, &breaks, &num_breaks); - Py_END_ALLOW_THREADS - if (err != 0) { - handle_library_error(err); + mutations_node = (PyArrayObject *) PyArray_FROMANY( + mutations_node_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_node == NULL) { goto out; } - ret = new_id_array(num_breaks, breaks); -out: - tsd_safe_free(breaks); - Py_XDECREF(counts); - return ret; -} - -static PyObject * -tsdate_poisson_changepoints(PyObject *Py_UNUSED(self), PyObject *args) -{ - PyObject *ret = NULL; - PyObject *counts_obj = NULL; - PyObject *offset_obj = NULL; - PyArrayObject *counts = NULL; - PyArrayObject *offset = NULL; - double penalty, min_counts, min_offset; - tsd_id_t *breaks = NULL; - tsd_size_t num_breaks = 0; - int err; - - if (!PyArg_ParseTuple(args, "OOddd", &counts_obj, &offset_obj, &penalty, &min_counts, - &min_offset)) { + mutations_position = (PyArrayObject *) PyArray_FROMANY( + mutations_position_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_position == NULL) { goto out; } - counts = get_array(counts_obj, NPY_FLOAT64, 1); - offset = get_array(offset_obj, NPY_FLOAT64, 1); - if (counts == NULL || offset == NULL) { + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { goto out; } - if (check_sizes(ARRAY_LEN(counts) == ARRAY_LEN(offset), - "counts and offset must have the same size") - != 0) { + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { goto out; } - Py_BEGIN_ALLOW_THREADS - err = tsd_poisson_changepoints(ARRAY_LEN(counts), DOUBLES(counts), DOUBLES(offset), - penalty, min_counts, min_offset, &breaks, &num_breaks); - Py_END_ALLOW_THREADS - if (err != 0) { - handle_library_error(err); + edges_left = (PyArrayObject *) PyArray_FROMANY( + edges_left_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_left == NULL) { goto out; } - ret = new_id_array(num_breaks, breaks); -out: - tsd_safe_free(breaks); - Py_XDECREF(counts); - Py_XDECREF(offset); - return ret; -} - -static PyObject * -tsdate_count_mutations(PyObject *Py_UNUSED(self), PyObject *args) -{ - PyObject *ret = NULL; - PyObject *obj[9]; - PyArrayObject *node_is_sample = NULL; - PyArrayObject *mutations_node = NULL; - PyArrayObject *mutations_position = NULL; - PyArrayObject *edges_parent = NULL; - PyArrayObject *edges_child = NULL; - PyArrayObject *edges_left = NULL; - PyArrayObject *edges_right = NULL; - PyArrayObject *indexes_insert = NULL; - PyArrayObject *indexes_remove = NULL; - PyArrayObject *edges_stats = NULL; - PyArrayObject *mutations_edge = NULL; - double sequence_length; - int size_biased; - tsd_size_t num_edges, num_mutations; - npy_intp stats_dims[2]; - npy_intp mutations_dim; - int err; - - if (!PyArg_ParseTuple(args, "OOOOOOOOOdp", &obj[0], &obj[1], &obj[2], &obj[3], - &obj[4], &obj[5], &obj[6], &obj[7], &obj[8], &sequence_length, - &size_biased)) { + edges_right = (PyArrayObject *) PyArray_FROMANY( + edges_right_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_right == NULL) { goto out; } - node_is_sample = get_array(obj[0], NPY_BOOL, 1); - mutations_node = get_array(obj[1], NPY_INT32, 1); - mutations_position = get_array(obj[2], NPY_FLOAT64, 1); - edges_parent = get_array(obj[3], NPY_INT32, 1); - edges_child = get_array(obj[4], NPY_INT32, 1); - edges_left = get_array(obj[5], NPY_FLOAT64, 1); - edges_right = get_array(obj[6], NPY_FLOAT64, 1); - indexes_insert = get_array(obj[7], NPY_INT32, 1); - indexes_remove = get_array(obj[8], NPY_INT32, 1); - if (node_is_sample == NULL || mutations_node == NULL || mutations_position == NULL - || edges_parent == NULL || edges_child == NULL || edges_left == NULL - || edges_right == NULL || indexes_insert == NULL || indexes_remove == NULL) { + indexes_insert = (PyArrayObject *) PyArray_FROMANY( + indexes_insert_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_insert == NULL) { + goto out; + } + indexes_remove = (PyArrayObject *) PyArray_FROMANY( + indexes_remove_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_remove == NULL) { goto out; } num_edges = ARRAY_LEN(edges_parent); num_mutations = ARRAY_LEN(mutations_node); - if (check_sizes(ARRAY_LEN(edges_child) == num_edges - && ARRAY_LEN(edges_left) == num_edges - && ARRAY_LEN(edges_right) == num_edges, - "Edge arrays must have the same size") - != 0) { + if (ARRAY_LEN(edges_child) != num_edges || ARRAY_LEN(edges_left) != num_edges + || ARRAY_LEN(edges_right) != num_edges || ARRAY_LEN(indexes_insert) != num_edges + || ARRAY_LEN(indexes_remove) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); goto out; } - if (check_sizes(ARRAY_LEN(indexes_insert) == num_edges - && ARRAY_LEN(indexes_remove) == num_edges, - "Edge index arrays must have one entry per edge") - != 0) { + if (ARRAY_LEN(mutations_position) != num_mutations) { + PyErr_SetString(PyExc_ValueError, "Mutation arrays must have the same size"); goto out; } - if (check_sizes(ARRAY_LEN(mutations_position) == num_mutations, - "Mutation arrays must have the same size") - != 0) { + dims[0] = (npy_intp) num_edges; + dims[1] = 2; + edges_stats = (PyArrayObject *) PyArray_SimpleNew(2, dims, NPY_FLOAT64); + if (edges_stats == NULL) { goto out; } - stats_dims[0] = (npy_intp) num_edges; - stats_dims[1] = 2; - mutations_dim = (npy_intp) num_mutations; - edges_stats = (PyArrayObject *) PyArray_SimpleNew(2, stats_dims, NPY_FLOAT64); - mutations_edge = (PyArrayObject *) PyArray_SimpleNew(1, &mutations_dim, NPY_INT32); - if (edges_stats == NULL || mutations_edge == NULL) { + dims[0] = (npy_intp) num_mutations; + mutations_edge = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_INT32); + if (mutations_edge == NULL) { goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_count_mutations(ARRAY_LEN(node_is_sample), FLAGS(node_is_sample), + err = tsd_count_mutations(ARRAY_LEN(nodes_sample), FLAGS(nodes_sample), num_mutations, IDS(mutations_node), DOUBLES(mutations_position), num_edges, IDS(edges_parent), IDS(edges_child), DOUBLES(edges_left), DOUBLES(edges_right), IDS(indexes_insert), IDS(indexes_remove), sequence_length, size_biased, - (double *) PyArray_DATA(edges_stats), (tsd_id_t *) PyArray_DATA(mutations_edge)); + DOUBLES(edges_stats), IDS(mutations_edge)); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); @@ -1457,7 +1554,7 @@ tsdate_count_mutations(PyObject *Py_UNUSED(self), PyObject *args) } ret = Py_BuildValue("OO", edges_stats, mutations_edge); out: - Py_XDECREF(node_is_sample); + Py_XDECREF(nodes_sample); Py_XDECREF(mutations_node); Py_XDECREF(mutations_position); Py_XDECREF(edges_parent); @@ -1471,216 +1568,280 @@ tsdate_count_mutations(PyObject *Py_UNUSED(self), PyObject *args) return ret; } -/* - * Check the arrays that describe the edges and their likelihoods, shared by - * mutational_area and mutational_timescale. Returns 0, or -1 with ValueError. - */ -static int -check_edge_likelihoods( - PyArrayObject *likelihoods, PyArrayObject *edges_parent, PyArrayObject *edges_child) -{ - tsd_size_t num_edges = ARRAY_LEN(edges_parent); - int ret = -1; - - if (check_sizes( - ARRAY_LEN(edges_child) == num_edges, "Edge arrays must have the same size") - != 0) { - goto out; - } - if (check_sizes((tsd_size_t) PyArray_DIM(likelihoods, 0) == num_edges - && PyArray_DIM(likelihoods, 1) == 2, - "Likelihoods must have one row of two columns per edge") - != 0) { - goto out; - } - ret = 0; -out: - return ret; -} - static PyObject * -tsdate_mutational_area(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_mutational_area(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *obj[4]; + static char *kwlist[] + = { "nodes_time", "edges_likelihood", "edges_parent", "edges_child", NULL }; + PyObject *nodes_time_obj = NULL; + PyObject *edges_likelihood_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; PyArrayObject *nodes_time = NULL; - PyArrayObject *likelihoods = NULL; + PyArrayObject *edges_likelihood = NULL; PyArrayObject *edges_parent = NULL; PyArrayObject *edges_child = NULL; + PyArrayObject *counts = NULL; + PyArrayObject *offset = NULL; + PyArrayObject *duration = NULL; PyArrayObject *nodes_index = NULL; - PyObject *counts = NULL; - PyObject *offset = NULL; - PyObject *duration = NULL; tsd_epoch_stats_t stats = { 0, NULL, NULL, NULL }; - npy_intp nodes_dim; + tsd_size_t num_nodes, num_edges; + npy_intp dims[1]; int err; - if (!PyArg_ParseTuple(args, "OOOO", &obj[0], &obj[1], &obj[2], &obj[3])) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOO", kwlist, &nodes_time_obj, + &edges_likelihood_obj, &edges_parent_obj, &edges_child_obj)) { + goto out; + } + nodes_time = (PyArrayObject *) PyArray_FROMANY( + nodes_time_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_time == NULL) { goto out; } - nodes_time = get_array(obj[0], NPY_FLOAT64, 1); - likelihoods = get_array(obj[1], NPY_FLOAT64, 2); - edges_parent = get_array(obj[2], NPY_INT32, 1); - edges_child = get_array(obj[3], NPY_INT32, 1); - if (nodes_time == NULL || likelihoods == NULL || edges_parent == NULL - || edges_child == NULL) { + edges_likelihood = (PyArrayObject *) PyArray_FROMANY( + edges_likelihood_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (edges_likelihood == NULL) { goto out; } - if (check_edge_likelihoods(likelihoods, edges_parent, edges_child) != 0) { + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + num_nodes = ARRAY_LEN(nodes_time); + num_edges = ARRAY_LEN(edges_parent); + if (ARRAY_LEN(edges_child) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + if (ARRAY_LEN(edges_likelihood) != num_edges + || PyArray_DIM(edges_likelihood, 1) != 2) { + PyErr_SetString( + PyExc_ValueError, "Likelihoods must have one row of two columns per edge"); goto out; } - nodes_dim = (npy_intp) ARRAY_LEN(nodes_time); - nodes_index = (PyArrayObject *) PyArray_SimpleNew(1, &nodes_dim, NPY_INT32); + dims[0] = (npy_intp) num_nodes; + nodes_index = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_INT32); if (nodes_index == NULL) { goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_mutational_area(ARRAY_LEN(nodes_time), DOUBLES(nodes_time), - ARRAY_LEN(edges_parent), DOUBLES(likelihoods), IDS(edges_parent), - IDS(edges_child), &stats, (tsd_id_t *) PyArray_DATA(nodes_index)); + err = tsd_mutational_area(num_nodes, DOUBLES(nodes_time), num_edges, + DOUBLES(edges_likelihood), IDS(edges_parent), IDS(edges_child), &stats, + IDS(nodes_index)); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); goto out; } - counts = new_double_array(stats.num_epochs, stats.counts); - offset = new_double_array(stats.num_epochs, stats.offset); - duration = new_double_array(stats.num_epochs, stats.duration); - if (counts == NULL || offset == NULL || duration == NULL) { + dims[0] = (npy_intp) stats.num_epochs; + counts = new_array_from_data(NPY_FLOAT64, 1, dims, stats.counts); + if (counts == NULL) { + goto out; + } + offset = new_array_from_data(NPY_FLOAT64, 1, dims, stats.offset); + if (offset == NULL) { + goto out; + } + duration = new_array_from_data(NPY_FLOAT64, 1, dims, stats.duration); + if (duration == NULL) { goto out; } ret = Py_BuildValue("OOOO", counts, offset, duration, nodes_index); out: tsd_epoch_stats_free(&stats); Py_XDECREF(nodes_time); - Py_XDECREF(likelihoods); + Py_XDECREF(edges_likelihood); Py_XDECREF(edges_parent); Py_XDECREF(edges_child); - Py_XDECREF(nodes_index); Py_XDECREF(counts); Py_XDECREF(offset); Py_XDECREF(duration); + Py_XDECREF(nodes_index); return ret; } static PyObject * -tsdate_mutational_timescale(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_mutational_timescale(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *obj[5]; + static char *kwlist[] = { "nodes_time", "edges_likelihood", "nodes_fixed", + "edges_parent", "edges_child", "max_intervals", NULL }; + PyObject *nodes_time_obj = NULL; + PyObject *edges_likelihood_obj = NULL; + PyObject *nodes_fixed_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; PyArrayObject *nodes_time = NULL; - PyArrayObject *likelihoods = NULL; + PyArrayObject *edges_likelihood = NULL; PyArrayObject *nodes_fixed = NULL; PyArrayObject *edges_parent = NULL; PyArrayObject *edges_child = NULL; - PyObject *origin_array = NULL; - PyObject *adjust_array = NULL; + PyArrayObject *origin = NULL; + PyArrayObject *adjust = NULL; + double *origin_data = NULL; + double *adjust_data = NULL; long long max_intervals; - double *origin = NULL; - double *adjust = NULL; - tsd_size_t num_breaks = 0; + tsd_size_t num_edges, num_breaks = 0; + npy_intp dims[1]; int err; - if (!PyArg_ParseTuple(args, "OOOOOL", &obj[0], &obj[1], &obj[2], &obj[3], &obj[4], + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOL", kwlist, &nodes_time_obj, + &edges_likelihood_obj, &nodes_fixed_obj, &edges_parent_obj, &edges_child_obj, &max_intervals)) { goto out; } - nodes_time = get_array(obj[0], NPY_FLOAT64, 1); - likelihoods = get_array(obj[1], NPY_FLOAT64, 2); - nodes_fixed = get_array(obj[2], NPY_BOOL, 1); - edges_parent = get_array(obj[3], NPY_INT32, 1); - edges_child = get_array(obj[4], NPY_INT32, 1); - if (nodes_time == NULL || likelihoods == NULL || nodes_fixed == NULL - || edges_parent == NULL || edges_child == NULL) { + nodes_time = (PyArrayObject *) PyArray_FROMANY( + nodes_time_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_time == NULL) { goto out; } - if (check_edge_likelihoods(likelihoods, edges_parent, edges_child) != 0) { + edges_likelihood = (PyArrayObject *) PyArray_FROMANY( + edges_likelihood_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (edges_likelihood == NULL) { goto out; } - if (check_sizes(ARRAY_LEN(nodes_fixed) == ARRAY_LEN(nodes_time), - "nodes_fixed and nodes_time must have the same size") - != 0) { + nodes_fixed = (PyArrayObject *) PyArray_FROMANY( + nodes_fixed_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_fixed == NULL) { + goto out; + } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + if (ARRAY_LEN(edges_child) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + if (ARRAY_LEN(edges_likelihood) != num_edges + || PyArray_DIM(edges_likelihood, 1) != 2) { + PyErr_SetString( + PyExc_ValueError, "Likelihoods must have one row of two columns per edge"); + goto out; + } + if (ARRAY_LEN(nodes_fixed) != ARRAY_LEN(nodes_time)) { + PyErr_SetString( + PyExc_ValueError, "nodes_fixed and nodes_time must have the same size"); goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_mutational_timescale(ARRAY_LEN(nodes_time), DOUBLES(nodes_time), - ARRAY_LEN(edges_parent), DOUBLES(likelihoods), IDS(edges_parent), - IDS(edges_child), (int64_t) max_intervals, &num_breaks, &origin, &adjust); + err = tsd_mutational_timescale(ARRAY_LEN(nodes_time), DOUBLES(nodes_time), num_edges, + DOUBLES(edges_likelihood), IDS(edges_parent), IDS(edges_child), + (int64_t) max_intervals, &num_breaks, &origin_data, &adjust_data); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); goto out; } - origin_array = new_double_array(num_breaks, origin); - adjust_array = new_double_array(num_breaks, adjust); - if (origin_array == NULL || adjust_array == NULL) { + dims[0] = (npy_intp) num_breaks; + origin = new_array_from_data(NPY_FLOAT64, 1, dims, origin_data); + if (origin == NULL) { + goto out; + } + adjust = new_array_from_data(NPY_FLOAT64, 1, dims, adjust_data); + if (adjust == NULL) { goto out; } - ret = Py_BuildValue("OO", origin_array, adjust_array); + ret = Py_BuildValue("OO", origin, adjust); out: - tsd_safe_free(origin); - tsd_safe_free(adjust); + tsd_safe_free(origin_data); + tsd_safe_free(adjust_data); Py_XDECREF(nodes_time); - Py_XDECREF(likelihoods); + Py_XDECREF(edges_likelihood); Py_XDECREF(nodes_fixed); Py_XDECREF(edges_parent); Py_XDECREF(edges_child); - Py_XDECREF(origin_array); - Py_XDECREF(adjust_array); + Py_XDECREF(origin); + Py_XDECREF(adjust); return ret; } static PyObject * -tsdate_piecewise_scale_point_estimate(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_piecewise_scale_point_estimate( + PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *obj[4]; + static char *kwlist[] = { "point_estimate", "point_fixed", "original_breaks", + "rescaled_breaks", NULL }; + PyObject *point_estimate_obj = NULL; + PyObject *point_fixed_obj = NULL; + PyObject *original_breaks_obj = NULL; + PyObject *rescaled_breaks_obj = NULL; PyArrayObject *point_estimate = NULL; PyArrayObject *point_fixed = NULL; PyArrayObject *original_breaks = NULL; PyArrayObject *rescaled_breaks = NULL; PyArrayObject *rescaled = NULL; - npy_intp dim; + tsd_size_t num_points, num_breaks; + npy_intp dims[1]; int err; - if (!PyArg_ParseTuple(args, "OOOO", &obj[0], &obj[1], &obj[2], &obj[3])) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOO", kwlist, &point_estimate_obj, + &point_fixed_obj, &original_breaks_obj, &rescaled_breaks_obj)) { goto out; } - point_estimate = get_array(obj[0], NPY_FLOAT64, 1); - point_fixed = get_array(obj[1], NPY_BOOL, 1); - original_breaks = get_array(obj[2], NPY_FLOAT64, 1); - rescaled_breaks = get_array(obj[3], NPY_FLOAT64, 1); - if (point_estimate == NULL || point_fixed == NULL || original_breaks == NULL - || rescaled_breaks == NULL) { + point_estimate = (PyArrayObject *) PyArray_FROMANY( + point_estimate_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (point_estimate == NULL) { goto out; } - if (check_sizes(ARRAY_LEN(point_fixed) == ARRAY_LEN(point_estimate), - "point_fixed and point_estimate must have the same size") - != 0) { + point_fixed = (PyArrayObject *) PyArray_FROMANY( + point_fixed_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (point_fixed == NULL) { goto out; } - if (check_sizes(ARRAY_LEN(original_breaks) == ARRAY_LEN(rescaled_breaks), - "Breakpoints must be of the same size") - != 0) { + original_breaks = (PyArrayObject *) PyArray_FROMANY( + original_breaks_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (original_breaks == NULL) { goto out; } - dim = (npy_intp) ARRAY_LEN(point_estimate); - rescaled = (PyArrayObject *) PyArray_SimpleNew(1, &dim, NPY_FLOAT64); - if (rescaled == NULL) { + rescaled_breaks = (PyArrayObject *) PyArray_FROMANY( + rescaled_breaks_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (rescaled_breaks == NULL) { goto out; } - Py_BEGIN_ALLOW_THREADS - err = tsd_piecewise_scale_point_estimate(ARRAY_LEN(point_estimate), - DOUBLES(point_estimate), FLAGS(point_fixed), ARRAY_LEN(original_breaks), - DOUBLES(original_breaks), DOUBLES(rescaled_breaks), - (double *) PyArray_DATA(rescaled)); - Py_END_ALLOW_THREADS - if (err != 0) { + num_points = ARRAY_LEN(point_estimate); + num_breaks = ARRAY_LEN(original_breaks); + if (ARRAY_LEN(point_fixed) != num_points) { + PyErr_SetString( + PyExc_ValueError, "point_fixed and point_estimate must have the same size"); + goto out; + } + if (ARRAY_LEN(rescaled_breaks) != num_breaks) { + PyErr_SetString(PyExc_ValueError, "Breakpoints must be of the same size"); + goto out; + } + dims[0] = (npy_intp) num_points; + rescaled = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_FLOAT64); + if (rescaled == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_piecewise_scale_point_estimate(num_points, DOUBLES(point_estimate), + FLAGS(point_fixed), num_breaks, DOUBLES(original_breaks), + DOUBLES(rescaled_breaks), DOUBLES(rescaled)); + Py_END_ALLOW_THREADS + if (err != 0) { handle_library_error(err); goto out; } - Py_INCREF(rescaled); ret = (PyObject *) rescaled; + rescaled = NULL; out: Py_XDECREF(point_estimate); Py_XDECREF(point_fixed); @@ -1691,60 +1852,80 @@ tsdate_piecewise_scale_point_estimate(PyObject *Py_UNUSED(self), PyObject *args) } static PyObject * -tsdate_piecewise_scale_posterior(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_piecewise_scale_posterior( + PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *obj[4]; + static char *kwlist[] = { "posteriors", "posteriors_fixed", "original_breaks", + "rescaled_breaks", "quantile_width", "max_shape", NULL }; + PyObject *posteriors_obj = NULL; + PyObject *posteriors_fixed_obj = NULL; + PyObject *original_breaks_obj = NULL; + PyObject *rescaled_breaks_obj = NULL; PyArrayObject *posteriors = NULL; PyArrayObject *posteriors_fixed = NULL; PyArrayObject *original_breaks = NULL; PyArrayObject *rescaled_breaks = NULL; PyArrayObject *new_posteriors = NULL; double quantile_width, max_shape; + tsd_size_t num_posteriors, num_breaks; npy_intp dims[2]; int err; - if (!PyArg_ParseTuple(args, "OOOOdd", &obj[0], &obj[1], &obj[2], &obj[3], + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOdd", kwlist, &posteriors_obj, + &posteriors_fixed_obj, &original_breaks_obj, &rescaled_breaks_obj, &quantile_width, &max_shape)) { goto out; } - posteriors = get_array(obj[0], NPY_FLOAT64, 2); - posteriors_fixed = get_array(obj[1], NPY_BOOL, 1); - original_breaks = get_array(obj[2], NPY_FLOAT64, 1); - rescaled_breaks = get_array(obj[3], NPY_FLOAT64, 1); - if (posteriors == NULL || posteriors_fixed == NULL || original_breaks == NULL - || rescaled_breaks == NULL) { + posteriors = (PyArrayObject *) PyArray_FROMANY( + posteriors_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (posteriors == NULL) { goto out; } - if (check_sizes(PyArray_DIM(posteriors, 1) == 2 - && ARRAY_LEN(posteriors_fixed) == ARRAY_LEN(posteriors), - "Posteriors must have two columns and one row per fixed flag") - != 0) { + posteriors_fixed = (PyArrayObject *) PyArray_FROMANY( + posteriors_fixed_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (posteriors_fixed == NULL) { goto out; } - if (check_sizes(ARRAY_LEN(original_breaks) == ARRAY_LEN(rescaled_breaks), - "Breakpoints must be of the same size") - != 0) { + original_breaks = (PyArrayObject *) PyArray_FROMANY( + original_breaks_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (original_breaks == NULL) { goto out; } - dims[0] = PyArray_DIM(posteriors, 0); + rescaled_breaks = (PyArrayObject *) PyArray_FROMANY( + rescaled_breaks_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (rescaled_breaks == NULL) { + goto out; + } + num_posteriors = ARRAY_LEN(posteriors); + num_breaks = ARRAY_LEN(original_breaks); + if (PyArray_DIM(posteriors, 1) != 2 + || ARRAY_LEN(posteriors_fixed) != num_posteriors) { + PyErr_SetString(PyExc_ValueError, + "Posteriors must have two columns and one row per fixed flag"); + goto out; + } + if (ARRAY_LEN(rescaled_breaks) != num_breaks) { + PyErr_SetString(PyExc_ValueError, "Breakpoints must be of the same size"); + goto out; + } + dims[0] = (npy_intp) num_posteriors; dims[1] = 2; new_posteriors = (PyArrayObject *) PyArray_SimpleNew(2, dims, NPY_FLOAT64); if (new_posteriors == NULL) { goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_piecewise_scale_posterior(ARRAY_LEN(posteriors), DOUBLES(posteriors), - FLAGS(posteriors_fixed), ARRAY_LEN(original_breaks), DOUBLES(original_breaks), - DOUBLES(rescaled_breaks), quantile_width, max_shape, - (double *) PyArray_DATA(new_posteriors)); + err = tsd_piecewise_scale_posterior(num_posteriors, DOUBLES(posteriors), + FLAGS(posteriors_fixed), num_breaks, DOUBLES(original_breaks), + DOUBLES(rescaled_breaks), quantile_width, max_shape, DOUBLES(new_posteriors)); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); goto out; } - Py_INCREF(new_posteriors); ret = (PyObject *) new_posteriors; + new_posteriors = NULL; out: Py_XDECREF(posteriors); Py_XDECREF(posteriors_fixed); @@ -1754,435 +1935,649 @@ tsdate_piecewise_scale_posterior(PyObject *Py_UNUSED(self), PyObject *args) return ret; } -/* - * Expectation propagation. The factors are passed as a tuple of eight arrays, - * (node, edge, block, scale, edges_parent, edges_child, blocks_left, blocks_right), - * the fields of EPFactors; the arrays of the first four are updated in place by the - * passes that change them. +static PyObject * +tsdate_constraints_are_consistent( + PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "constraints", "edges_parent", "edges_child", NULL }; + PyObject *constraints_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyArrayObject *constraints = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + tsd_size_t num_edges; + int consistent = 0; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOO", kwlist, &constraints_obj, + &edges_parent_obj, &edges_child_obj)) { + goto out; + } + constraints = (PyArrayObject *) PyArray_FROMANY( + constraints_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (constraints == NULL) { + goto out; + } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + if (PyArray_DIM(constraints, 1) != 2) { + PyErr_SetString(PyExc_ValueError, "constraints must have two columns"); + goto out; + } + if (ARRAY_LEN(edges_child) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_constraints_are_consistent(ARRAY_LEN(constraints), num_edges, + DOUBLES(constraints), IDS(edges_parent), IDS(edges_child), &consistent); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = PyBool_FromLong(consistent); +out: + Py_XDECREF(constraints); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + return ret; +} + +/*=================================================================== + * ExpectationPropagation + *=================================================================== */ -#define NUM_FACTOR_ARRAYS 8 typedef struct { - PyArrayObject *arrays[NUM_FACTOR_ARRAYS]; - tsd_ep_factors_t c; -} py_factors_t; + PyObject_HEAD + tsd_ep_t *ep; +} ExpectationPropagation; + +static int +ExpectationPropagation_check_state(ExpectationPropagation *self) +{ + int ret = 0; + + if (self->ep == NULL) { + PyErr_SetString(PyExc_SystemError, "ExpectationPropagation not initialised"); + ret = -1; + } + return ret; +} static void -release_factors(py_factors_t *factors) +ExpectationPropagation_dealloc(ExpectationPropagation *self) { - release_arrays(factors->arrays, NUM_FACTOR_ARRAYS); + if (self->ep != NULL) { + tsd_ep_free(self->ep); + PyMem_Free(self->ep); + self->ep = NULL; + } + Py_TYPE(self)->tp_free((PyObject *) self); } -/* - * Parse a tuple of factors, writing the sizes and pointers to `factors->c`. The arrays - * that the caller needs to update must be (and are required to be) writeable, aligned - * and C-contiguous if `writeable`. Returns 0, or -1 with an exception. - */ static int -parse_factors(PyObject *obj, int writeable, py_factors_t *factors) +ExpectationPropagation_init(ExpectationPropagation *self, PyObject *args, PyObject *kwds) { int ret = -1; - const int typenums[NUM_FACTOR_ARRAYS] = { NPY_FLOAT64, NPY_FLOAT64, NPY_FLOAT64, - NPY_FLOAT64, NPY_INT32, NPY_INT32, NPY_INT32, NPY_INT32 }; - const int ndims[NUM_FACTOR_ARRAYS] = { 3, 3, 3, 1, 1, 1, 1, 1 }; - PyArrayObject **a = factors->arrays; - PyObject *item; - int j; + static char *kwlist[] = { "constraints", "edges_parent", "edges_child", + "edges_likelihood", "blocks_left", "blocks_right", "blocks_likelihood", NULL }; + PyObject *constraints_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyObject *edges_likelihood_obj = NULL; + PyObject *blocks_left_obj = NULL; + PyObject *blocks_right_obj = NULL; + PyObject *blocks_likelihood_obj = NULL; + PyArrayObject *constraints = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *edges_likelihood = NULL; + PyArrayObject *blocks_left = NULL; + PyArrayObject *blocks_right = NULL; + PyArrayObject *blocks_likelihood = NULL; + tsd_size_t num_edges, num_blocks; + int err; - if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != NUM_FACTOR_ARRAYS) { - PyErr_SetString(PyExc_TypeError, "factors must be a tuple of eight arrays"); + if (self->ep != NULL) { + tsd_ep_free(self->ep); + PyMem_Free(self->ep); + self->ep = NULL; + } + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOO", kwlist, &constraints_obj, + &edges_parent_obj, &edges_child_obj, &edges_likelihood_obj, &blocks_left_obj, + &blocks_right_obj, &blocks_likelihood_obj)) { goto out; } - for (j = 0; j < NUM_FACTOR_ARRAYS; j++) { - item = PyTuple_GET_ITEM(obj, j); - if (writeable && j < 4) { - a[j] = get_inout_array(item, ndims[j]); - } else { - a[j] = (PyArrayObject *) PyArray_FROMANY( - item, typenums[j], ndims[j], ndims[j], NPY_ARRAY_IN_ARRAY); - } - if (a[j] == NULL) { - goto out; - } + constraints = (PyArrayObject *) PyArray_FROMANY( + constraints_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (constraints == NULL) { + goto out; } - for (j = 0; j < 3; j++) { - if (check_sizes(PyArray_DIM(a[j], 1) == 2 && PyArray_DIM(a[j], 2) == 2, - "Factors must have shape (n, 2, 2)") - != 0) { - goto out; - } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; } - if (check_sizes(ARRAY_DIM(a[0], 0) == ARRAY_SIZE(a[3]) - && ARRAY_DIM(a[1], 0) == ARRAY_SIZE(a[4]) - && ARRAY_DIM(a[1], 0) == ARRAY_SIZE(a[5]) - && ARRAY_DIM(a[2], 0) == ARRAY_SIZE(a[6]) - && ARRAY_DIM(a[2], 0) == ARRAY_SIZE(a[7]), - "Factor arrays have inconsistent sizes") - != 0) { + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + edges_likelihood = (PyArrayObject *) PyArray_FROMANY( + edges_likelihood_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (edges_likelihood == NULL) { + goto out; + } + blocks_left = (PyArrayObject *) PyArray_FROMANY( + blocks_left_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (blocks_left == NULL) { + goto out; + } + blocks_right = (PyArrayObject *) PyArray_FROMANY( + blocks_right_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (blocks_right == NULL) { + goto out; + } + blocks_likelihood = (PyArrayObject *) PyArray_FROMANY( + blocks_likelihood_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (blocks_likelihood == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + num_blocks = ARRAY_LEN(blocks_left); + if (PyArray_DIM(constraints, 1) != 2 || PyArray_DIM(edges_likelihood, 1) != 2 + || PyArray_DIM(blocks_likelihood, 1) != 2) { + PyErr_SetString(PyExc_ValueError, + "constraints, edges_likelihood and blocks_likelihood must have two columns"); + goto out; + } + if (ARRAY_LEN(edges_child) != num_edges + || ARRAY_LEN(edges_likelihood) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + if (ARRAY_LEN(blocks_right) != num_blocks + || ARRAY_LEN(blocks_likelihood) != num_blocks) { + PyErr_SetString(PyExc_ValueError, "Block arrays must have the same size"); + goto out; + } + self->ep = PyMem_Malloc(sizeof(*self->ep)); + if (self->ep == NULL) { + PyErr_NoMemory(); + goto out; + } + err = tsd_ep_init(self->ep, ARRAY_LEN(constraints), num_edges, num_blocks, + DOUBLES(constraints), IDS(edges_parent), IDS(edges_child), + DOUBLES(edges_likelihood), IDS(blocks_left), IDS(blocks_right), + DOUBLES(blocks_likelihood)); + if (err != 0) { + handle_library_error(err); + tsd_ep_free(self->ep); + PyMem_Free(self->ep); + self->ep = NULL; goto out; } - factors->c.num_nodes = ARRAY_DIM(a[0], 0); - factors->c.num_edges = ARRAY_DIM(a[1], 0); - factors->c.num_blocks = ARRAY_DIM(a[2], 0); - factors->c.node = (double *) PyArray_DATA(a[0]); - factors->c.edge = (double *) PyArray_DATA(a[1]); - factors->c.block = (double *) PyArray_DATA(a[2]); - factors->c.scale = (double *) PyArray_DATA(a[3]); - factors->c.edges_parent = IDS(a[4]); - factors->c.edges_child = IDS(a[5]); - factors->c.blocks_left = IDS(a[6]); - factors->c.blocks_right = IDS(a[7]); ret = 0; out: + Py_XDECREF(constraints); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(edges_likelihood); + Py_XDECREF(blocks_left); + Py_XDECREF(blocks_right); + Py_XDECREF(blocks_likelihood); return ret; } -/* Whether `array` has `rows` rows of two columns; else raise ValueError. */ -static int -check_pairs(PyArrayObject *array, tsd_size_t rows, const char *message) -{ - return check_sizes( - ARRAY_DIM(array, 0) == rows && PyArray_DIM(array, 1) == 2, message); -} - -/* rescale_factors(factors): multiply the factors by the node scales, in place. */ static PyObject * -tsdate_rescale_factors(PyObject *Py_UNUSED(self), PyObject *args) +ExpectationPropagation_propagate_likelihood( + ExpectationPropagation *self, PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *factors_obj = NULL; - py_factors_t factors = { { NULL }, { 0 } }; + static char *kwlist[] = { "order", "unphased", "max_shape", "min_step", NULL }; + PyObject *order_obj = NULL; + PyArrayObject *order = NULL; + int unphased; + double max_shape, min_step; + int err; - if (!PyArg_ParseTuple(args, "O", &factors_obj)) { + if (ExpectationPropagation_check_state(self) != 0) { goto out; } - if (parse_factors(factors_obj, 1, &factors) != 0) { + if (!PyArg_ParseTupleAndKeywords( + args, kwds, "Opdd", kwlist, &order_obj, &unphased, &max_shape, &min_step)) { + goto out; + } + order = (PyArrayObject *) PyArray_FROMANY( + order_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (order == NULL) { goto out; } Py_BEGIN_ALLOW_THREADS - tsd_rescale_factors(&factors.c); + err = tsd_ep_propagate_likelihood( + self->ep, ARRAY_LEN(order), IDS(order), unphased, max_shape, min_step); Py_END_ALLOW_THREADS - ret = Py_None; - Py_INCREF(ret); + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = Py_BuildValue(""); out: - release_factors(&factors); + Py_XDECREF(order); return ret; } -/* assemble_factors(factors): the posteriors implied by the factors. */ static PyObject * -tsdate_assemble_factors(PyObject *Py_UNUSED(self), PyObject *args) +ExpectationPropagation_propagate_prior( + ExpectationPropagation *self, PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *factors_obj = NULL; - PyObject *posterior = NULL; - py_factors_t factors = { { NULL }, { 0 } }; - npy_intp dims[2]; + static char *kwlist[] = { "free", "max_shape", "em_maxitt", "em_reltol", NULL }; + PyObject *free_obj = NULL; + PyArrayObject *free = NULL; + double max_shape, em_reltol; + long long em_maxitt; + int err; - if (!PyArg_ParseTuple(args, "O", &factors_obj)) { + if (ExpectationPropagation_check_state(self) != 0) { goto out; } - if (parse_factors(factors_obj, 0, &factors) != 0) { + if (!PyArg_ParseTupleAndKeywords( + args, kwds, "OdLd", kwlist, &free_obj, &max_shape, &em_maxitt, &em_reltol)) { goto out; } - dims[0] = (npy_intp) factors.c.num_nodes; - dims[1] = 2; - posterior = PyArray_SimpleNew(2, dims, NPY_FLOAT64); - if (posterior == NULL) { + free = (PyArrayObject *) PyArray_FROMANY( + free_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (free == NULL) { + goto out; + } + if (ARRAY_LEN(free) != self->ep->num_nodes) { + PyErr_SetString(PyExc_ValueError, "free must have one entry per node"); goto out; } Py_BEGIN_ALLOW_THREADS - tsd_assemble_factors( - &factors.c, (double *) PyArray_DATA((PyArrayObject *) posterior)); + err = tsd_ep_propagate_prior( + self->ep, FLAGS(free), max_shape, (int64_t) em_maxitt, em_reltol); Py_END_ALLOW_THREADS - ret = posterior; - posterior = NULL; + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = Py_BuildValue(""); out: - release_factors(&factors); - Py_XDECREF(posterior); + Py_XDECREF(free); return ret; } -/* constraints_are_consistent(constraints, edges_parent, edges_child) -> bool */ static PyObject * -tsdate_constraints_are_consistent(PyObject *Py_UNUSED(self), PyObject *args) +ExpectationPropagation_propagate_mutations( + ExpectationPropagation *self, PyObject *args, PyObject *kwds) { PyObject *ret = NULL; - PyObject *obj[3]; - PyArrayObject *constraints = NULL; - PyArrayObject *edges_parent = NULL; - PyArrayObject *edges_child = NULL; - int consistent = 0; + static char *kwlist[] = { "mutations_edge", "unphased", NULL }; + PyObject *mutations_edge_obj = NULL; + PyArrayObject *mutations_edge = NULL; + PyArrayObject *mutations_posterior = NULL; + PyArrayObject *mutations_phase = NULL; + int unphased; + npy_intp dims[2]; int err; - if (!PyArg_ParseTuple(args, "OOO", &obj[0], &obj[1], &obj[2])) { + if (ExpectationPropagation_check_state(self) != 0) { + goto out; + } + if (!PyArg_ParseTupleAndKeywords( + args, kwds, "Op", kwlist, &mutations_edge_obj, &unphased)) { goto out; } - constraints = get_array(obj[0], NPY_FLOAT64, 2); - edges_parent = get_array(obj[1], NPY_INT32, 1); - edges_child = get_array(obj[2], NPY_INT32, 1); - if (constraints == NULL || edges_parent == NULL || edges_child == NULL) { + mutations_edge = (PyArrayObject *) PyArray_FROMANY( + mutations_edge_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_edge == NULL) { + goto out; + } + dims[0] = PyArray_DIM(mutations_edge, 0); + dims[1] = 2; + mutations_posterior = (PyArrayObject *) PyArray_SimpleNew(2, dims, NPY_FLOAT64); + if (mutations_posterior == NULL) { goto out; } - if (check_pairs( - constraints, ARRAY_DIM(constraints, 0), "Constraints must have two columns") - != 0 - || check_sizes(ARRAY_LEN(edges_parent) == ARRAY_LEN(edges_child), - "Edge arrays must have the same size") - != 0) { + mutations_phase = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_FLOAT64); + if (mutations_phase == NULL) { goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_constraints_are_consistent(ARRAY_LEN(constraints), ARRAY_LEN(edges_parent), - DOUBLES(constraints), IDS(edges_parent), IDS(edges_child), &consistent); + err = tsd_ep_propagate_mutations(self->ep, ARRAY_LEN(mutations_edge), + IDS(mutations_edge), unphased, DOUBLES(mutations_posterior), + DOUBLES(mutations_phase)); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); goto out; } - ret = PyBool_FromLong(consistent); + ret = Py_BuildValue("OO", mutations_posterior, mutations_phase); out: - Py_XDECREF(constraints); - Py_XDECREF(edges_parent); - Py_XDECREF(edges_child); + Py_XDECREF(mutations_edge); + Py_XDECREF(mutations_posterior); + Py_XDECREF(mutations_phase); return ret; } -/* - * propagate_likelihood(edge_order, edges_parent, edges_child, likelihoods, - * constraints, posterior, factors, lognorm, max_shape, min_step, unphased) - * updates posterior, the factors and lognorm in place. - */ static PyObject * -tsdate_propagate_likelihood(PyObject *Py_UNUSED(self), PyObject *args) +ExpectationPropagation_rescale_factors( + ExpectationPropagation *self, PyObject *Py_UNUSED(args)) { PyObject *ret = NULL; - PyObject *obj[8]; - PyArrayObject *edge_order = NULL; - PyArrayObject *edges_parent = NULL; - PyArrayObject *edges_child = NULL; - PyArrayObject *likelihoods = NULL; - PyArrayObject *constraints = NULL; - PyArrayObject *posterior = NULL; - PyArrayObject *lognorm = NULL; - py_factors_t factors = { { NULL }, { 0 } }; - double max_shape, min_step; - int unphased; - tsd_size_t num_edges; - int err; - if (!PyArg_ParseTuple(args, "OOOOOOOOddp", &obj[0], &obj[1], &obj[2], &obj[3], - &obj[4], &obj[5], &obj[6], &obj[7], &max_shape, &min_step, &unphased)) { + if (ExpectationPropagation_check_state(self) != 0) { goto out; } - edge_order = get_array(obj[0], NPY_INT32, 1); - edges_parent = get_array(obj[1], NPY_INT32, 1); - edges_child = get_array(obj[2], NPY_INT32, 1); - likelihoods = get_array(obj[3], NPY_FLOAT64, 2); - constraints = get_array(obj[4], NPY_FLOAT64, 2); - posterior = get_inout_array(obj[5], 2); - lognorm = get_inout_array(obj[7], 1); - if (edge_order == NULL || edges_parent == NULL || edges_child == NULL - || likelihoods == NULL || constraints == NULL || posterior == NULL - || lognorm == NULL) { + tsd_ep_rescale_factors(self->ep); + ret = Py_BuildValue(""); +out: + return ret; +} + +static PyObject * +ExpectationPropagation_assemble_factors( + ExpectationPropagation *self, PyObject *Py_UNUSED(args)) +{ + PyObject *ret = NULL; + PyArrayObject *posterior = NULL; + npy_intp dims[2]; + + if (ExpectationPropagation_check_state(self) != 0) { goto out; } - if (parse_factors(obj[6], 1, &factors) != 0) { + dims[0] = (npy_intp) self->ep->num_nodes; + dims[1] = 2; + posterior = (PyArrayObject *) PyArray_SimpleNew(2, dims, NPY_FLOAT64); + if (posterior == NULL) { goto out; } - num_edges = ARRAY_LEN(edges_parent); - if (check_sizes( - ARRAY_LEN(edges_child) == num_edges, "Edge arrays must have the same size") - != 0 - || check_pairs(likelihoods, num_edges, "Likelihoods must have shape (edges, 2)") - != 0 - || check_pairs(constraints, factors.c.num_nodes, - "Constraints must have shape (nodes, 2)") - != 0 - || check_pairs(posterior, factors.c.num_nodes, - "Posterior must have the same shape as constraints") - != 0 - || check_sizes( - ARRAY_LEN(lognorm) == num_edges, "Lognorm must have one entry per edge") - != 0 - || check_sizes( - num_edges == (unphased ? factors.c.num_blocks : factors.c.num_edges), - "Factors must have one entry per edge") - != 0) { + tsd_ep_assemble_factors(self->ep, DOUBLES(posterior)); + ret = (PyObject *) posterior; + posterior = NULL; +out: + Py_XDECREF(posterior); + return ret; +} + +static PyObject * +ExpectationPropagation_get_posterior( + ExpectationPropagation *self, void *Py_UNUSED(closure)) +{ + PyObject *ret = NULL; + npy_intp dims[2]; + + if (ExpectationPropagation_check_state(self) != 0) { goto out; } - Py_BEGIN_ALLOW_THREADS - err = tsd_propagate_likelihood(ARRAY_LEN(edge_order), IDS(edge_order), num_edges, - IDS(edges_parent), IDS(edges_child), DOUBLES(likelihoods), DOUBLES(constraints), - max_shape, min_step, unphased, (double *) PyArray_DATA(posterior), &factors.c, - (double *) PyArray_DATA(lognorm)); - Py_END_ALLOW_THREADS - if (err != 0) { - handle_library_error(err); + dims[0] = (npy_intp) self->ep->num_nodes; + dims[1] = 2; + ret = (PyObject *) new_array_from_data(NPY_FLOAT64, 2, dims, self->ep->posterior); +out: + return ret; +} + +static PyObject * +ExpectationPropagation_get_edges_lognorm( + ExpectationPropagation *self, void *Py_UNUSED(closure)) +{ + PyObject *ret = NULL; + npy_intp dims[1]; + + if (ExpectationPropagation_check_state(self) != 0) { goto out; } - ret = Py_None; - Py_INCREF(ret); + dims[0] = (npy_intp) self->ep->num_edges; + ret = (PyObject *) new_array_from_data( + NPY_FLOAT64, 1, dims, self->ep->edges_lognorm); out: - Py_XDECREF(edge_order); - Py_XDECREF(edges_parent); - Py_XDECREF(edges_child); - Py_XDECREF(likelihoods); - Py_XDECREF(constraints); - Py_XDECREF(posterior); - Py_XDECREF(lognorm); - release_factors(&factors); return ret; } -/* - * propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol) - * updates posterior and the factors in place. - */ static PyObject * -tsdate_propagate_prior(PyObject *Py_UNUSED(self), PyObject *args) +ExpectationPropagation_get_blocks_lognorm( + ExpectationPropagation *self, void *Py_UNUSED(closure)) { PyObject *ret = NULL; - PyObject *obj[3]; - PyArrayObject *free_nodes = NULL; - PyArrayObject *posterior = NULL; - py_factors_t factors = { { NULL }, { 0 } }; - double max_shape, em_reltol; - long long em_maxitt; - int err; + npy_intp dims[1]; - if (!PyArg_ParseTuple(args, "OOOdLd", &obj[0], &obj[1], &obj[2], &max_shape, - &em_maxitt, &em_reltol)) { + if (ExpectationPropagation_check_state(self) != 0) { goto out; } - free_nodes - = (PyArrayObject *) PyArray_FROMANY(obj[0], NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); - posterior = get_inout_array(obj[1], 2); - if (free_nodes == NULL || posterior == NULL) { + dims[0] = (npy_intp) self->ep->num_blocks; + ret = (PyObject *) new_array_from_data( + NPY_FLOAT64, 1, dims, self->ep->blocks_lognorm); +out: + return ret; +} + +static PyMethodDef ExpectationPropagation_methods[] = { + { "propagate_likelihood", + (PyCFunction) (void (*)(void)) ExpectationPropagation_propagate_likelihood, + METH_VARARGS | METH_KEYWORDS, + "Update the factors of the edges (blocks, if unphased) in the given order." }, + { "propagate_prior", + (PyCFunction) (void (*)(void)) ExpectationPropagation_propagate_prior, + METH_VARARGS | METH_KEYWORDS, + "Fit an exponential prior to the free nodes and update their factors." }, + { "propagate_mutations", + (PyCFunction) (void (*)(void)) ExpectationPropagation_propagate_mutations, + METH_VARARGS | METH_KEYWORDS, + "The posteriors and phases of mutations above the given edges (blocks)." }, + { "rescale_factors", (PyCFunction) ExpectationPropagation_rescale_factors, + METH_NOARGS, "Multiply the factors by the scales of their nodes." }, + { "assemble_factors", (PyCFunction) ExpectationPropagation_assemble_factors, + METH_NOARGS, "The posteriors implied by the factors." }, + { NULL } /* Sentinel */ +}; + +static PyGetSetDef ExpectationPropagation_getsetters[] = { + { "posterior", (getter) ExpectationPropagation_get_posterior, NULL, + "A copy of the posteriors of the nodes (natural parameters).", NULL }, + { "edges_lognorm", (getter) ExpectationPropagation_get_edges_lognorm, NULL, + "A copy of the log normalising constants of the edges.", NULL }, + { "blocks_lognorm", (getter) ExpectationPropagation_get_blocks_lognorm, NULL, + "A copy of the log normalising constants of the blocks.", NULL }, + { NULL } /* Sentinel */ +}; + +static PyTypeObject ExpectationPropagationType = { + // clang-format off + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "_tsdate.ExpectationPropagation", + // clang-format on + .tp_basicsize = sizeof(ExpectationPropagation), + .tp_dealloc = (destructor) ExpectationPropagation_dealloc, + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_doc = "The state of expectation propagation.", + .tp_methods = ExpectationPropagation_methods, + .tp_getset = ExpectationPropagation_getsetters, + .tp_init = (initproc) ExpectationPropagation_init, + .tp_new = PyType_GenericNew, +}; + +#define ARRAY_DIM(array, axis) ((tsd_size_t) PyArray_DIM(array, axis)) + +/* marginalize_over_ancestors(val): val has at least two rows. */ +static PyObject * +tsdate_marginalize_over_ancestors(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *val_obj = NULL; + PyArrayObject *val_array = NULL; + PyObject *output = NULL; + npy_intp dims[2]; + int err; + + if (!PyArg_ParseTuple(args, "O", &val_obj)) { goto out; } - if (parse_factors(obj[2], 1, &factors) != 0) { + val_array = (PyArrayObject *) PyArray_FROMANY( + val_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (val_array == NULL) { goto out; } - if (check_sizes(ARRAY_LEN(free_nodes) == factors.c.num_nodes - && ARRAY_DIM(posterior, 0) == factors.c.num_nodes - && PyArray_DIM(posterior, 1) == 2, - "The free nodes, posterior and factors must have one entry per node") - != 0) { + dims[0] = PyArray_DIM(val_array, 0) + 1; + dims[1] = PyArray_DIM(val_array, 1); + output = PyArray_SimpleNew(2, dims, NPY_FLOAT64); + if (output == NULL) { goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_propagate_prior(FLAGS(free_nodes), max_shape, (int64_t) em_maxitt, - em_reltol, (double *) PyArray_DATA(posterior), &factors.c); + err = tsd_marginalize_over_ancestors(ARRAY_DIM(val_array, 0), + ARRAY_DIM(val_array, 1), (const double *) PyArray_DATA(val_array), + (double *) PyArray_DATA((PyArrayObject *) output)); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); goto out; } - ret = Py_None; - Py_INCREF(ret); + ret = output; + output = NULL; out: - Py_XDECREF(free_nodes); - Py_XDECREF(posterior); - release_factors(&factors); + Py_XDECREF(val_array); + Py_XDECREF(output); return ret; } /* - * propagate_mutations(mutations_order, mutations_posterior, mutations_phase, - * mutations_edge, edges_parent, edges_child, likelihoods, constraints, posterior, - * factors, unphased) - * updates mutations_posterior and mutations_phase in place. + * Rescaling functions (lib/rescaling.c). Array sizes and shapes are checked here and + * raise ValueError. */ + +/* A one-dimensional array of tsd_id_t (int32), copied from `data`. */ +static PyObject * +new_id_array(tsd_size_t size, const tsd_id_t *data) +{ + npy_intp dim = (npy_intp) size; + PyObject *ret = PyArray_SimpleNew(1, &dim, NPY_INT32); + + if (ret != NULL && size > 0) { + memcpy(PyArray_DATA((PyArrayObject *) ret), data, size * sizeof(*data)); + } + return ret; +} + +/* A one-dimensional array of doubles, copied from `data`. */ +static PyObject * +new_double_array(tsd_size_t size, const double *data) +{ + npy_intp dim = (npy_intp) size; + PyObject *ret = PyArray_SimpleNew(1, &dim, NPY_FLOAT64); + + if (ret != NULL && size > 0) { + memcpy(PyArray_DATA((PyArrayObject *) ret), data, size * sizeof(*data)); + } + return ret; +} + +/* A C-contiguous array of the given type and dimension from `obj`, or NULL. */ +static PyArrayObject * +get_array(PyObject *obj, int typenum, int ndim) +{ + return (PyArrayObject *) PyArray_FROMANY( + obj, typenum, ndim, ndim, NPY_ARRAY_IN_ARRAY); +} + +/* Raise ValueError and return -1 unless `ok`. */ +static int +check_sizes(int ok, const char *message) +{ + if (!ok) { + PyErr_SetString(PyExc_ValueError, message); + return -1; + } + return 0; +} + static PyObject * -tsdate_propagate_mutations(PyObject *Py_UNUSED(self), PyObject *args) +tsdate_fixed_changepoints(PyObject *Py_UNUSED(self), PyObject *args) { PyObject *ret = NULL; - PyObject *obj[10]; - PyArrayObject *mutations_order = NULL; - PyArrayObject *mutations_posterior = NULL; - PyArrayObject *mutations_phase = NULL; - PyArrayObject *mutations_edge = NULL; - PyArrayObject *edges_parent = NULL; - PyArrayObject *edges_child = NULL; - PyArrayObject *likelihoods = NULL; - PyArrayObject *constraints = NULL; - PyArrayObject *posterior = NULL; - py_factors_t factors = { { NULL }, { 0 } }; - int unphased; - tsd_size_t num_edges, num_mutations; + PyObject *counts_obj = NULL; + PyArrayObject *counts = NULL; + long long epochs; + tsd_id_t *breaks = NULL; + tsd_size_t num_breaks = 0; int err; - if (!PyArg_ParseTuple(args, "OOOOOOOOOOp", &obj[0], &obj[1], &obj[2], &obj[3], - &obj[4], &obj[5], &obj[6], &obj[7], &obj[8], &obj[9], &unphased)) { + if (!PyArg_ParseTuple(args, "OL", &counts_obj, &epochs)) { goto out; } - mutations_order = get_array(obj[0], NPY_INT32, 1); - mutations_posterior = get_inout_array(obj[1], 2); - mutations_phase = get_inout_array(obj[2], 1); - mutations_edge = get_array(obj[3], NPY_INT32, 1); - edges_parent = get_array(obj[4], NPY_INT32, 1); - edges_child = get_array(obj[5], NPY_INT32, 1); - likelihoods = get_array(obj[6], NPY_FLOAT64, 2); - constraints = get_array(obj[7], NPY_FLOAT64, 2); - posterior = get_array(obj[8], NPY_FLOAT64, 2); - if (mutations_order == NULL || mutations_posterior == NULL || mutations_phase == NULL - || mutations_edge == NULL || edges_parent == NULL || edges_child == NULL - || likelihoods == NULL || constraints == NULL || posterior == NULL) { + counts = get_array(counts_obj, NPY_FLOAT64, 1); + if (counts == NULL) { goto out; } - if (parse_factors(obj[9], 0, &factors) != 0) { + Py_BEGIN_ALLOW_THREADS + err = tsd_fixed_changepoints( + ARRAY_LEN(counts), DOUBLES(counts), (int64_t) epochs, &breaks, &num_breaks); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); goto out; } - num_edges = ARRAY_LEN(edges_parent); - num_mutations = ARRAY_LEN(mutations_phase); - if (check_sizes(ARRAY_LEN(mutations_edge) == num_mutations, - "Mutation arrays must have the same size") - != 0 - || check_pairs(mutations_posterior, num_mutations, - "Mutation posterior must have shape (mutations, 2)") - != 0 - || check_sizes(ARRAY_LEN(edges_child) == num_edges, - "Edge arrays must have the same size") - != 0 - || check_pairs(likelihoods, num_edges, "Likelihoods must have shape (edges, 2)") - != 0 - || check_pairs(constraints, factors.c.num_nodes, - "Constraints must have shape (nodes, 2)") - != 0 - || check_pairs(posterior, factors.c.num_nodes, - "Posterior must have the same shape as constraints") - != 0 - || check_sizes( - num_edges == (unphased ? factors.c.num_blocks : factors.c.num_edges), - "Factors must have one entry per edge") - != 0) { + ret = new_id_array(num_breaks, breaks); +out: + tsd_safe_free(breaks); + Py_XDECREF(counts); + return ret; +} + +static PyObject * +tsdate_poisson_changepoints(PyObject *Py_UNUSED(self), PyObject *args) +{ + PyObject *ret = NULL; + PyObject *counts_obj = NULL; + PyObject *offset_obj = NULL; + PyArrayObject *counts = NULL; + PyArrayObject *offset = NULL; + double penalty, min_counts, min_offset; + tsd_id_t *breaks = NULL; + tsd_size_t num_breaks = 0; + int err; + + if (!PyArg_ParseTuple(args, "OOddd", &counts_obj, &offset_obj, &penalty, &min_counts, + &min_offset)) { + goto out; + } + counts = get_array(counts_obj, NPY_FLOAT64, 1); + offset = get_array(offset_obj, NPY_FLOAT64, 1); + if (counts == NULL || offset == NULL) { + goto out; + } + if (check_sizes(ARRAY_LEN(counts) == ARRAY_LEN(offset), + "counts and offset must have the same size") + != 0) { goto out; } Py_BEGIN_ALLOW_THREADS - err = tsd_propagate_mutations(ARRAY_LEN(mutations_order), IDS(mutations_order), - IDS(mutations_edge), IDS(edges_parent), IDS(edges_child), DOUBLES(likelihoods), - DOUBLES(constraints), DOUBLES(posterior), &factors.c, unphased, - (double *) PyArray_DATA(mutations_posterior), - (double *) PyArray_DATA(mutations_phase)); + err = tsd_poisson_changepoints(ARRAY_LEN(counts), DOUBLES(counts), DOUBLES(offset), + penalty, min_counts, min_offset, &breaks, &num_breaks); Py_END_ALLOW_THREADS if (err != 0) { handle_library_error(err); goto out; } - ret = Py_None; - Py_INCREF(ret); + ret = new_id_array(num_breaks, breaks); out: - Py_XDECREF(mutations_order); - Py_XDECREF(mutations_posterior); - Py_XDECREF(mutations_phase); - Py_XDECREF(mutations_edge); - Py_XDECREF(edges_parent); - Py_XDECREF(edges_child); - Py_XDECREF(likelihoods); - Py_XDECREF(constraints); - Py_XDECREF(posterior); - release_factors(&factors); + tsd_safe_free(breaks); + Py_XDECREF(counts); + Py_XDECREF(offset); return ret; } @@ -2194,52 +2589,57 @@ static PyMethodDef tsdate_methods[] = { { "average_gammas", (PyCFunction) tsdate_average_gammas, METH_VARARGS, "Natural parameters of the gamma averaging the sufficient statistics of an " "array of gammas, given as natural parameters." }, - { "block_singletons", (PyCFunction) tsdate_block_singletons, METH_VARARGS, + { "marginalize_over_ancestors", (PyCFunction) tsdate_marginalize_over_ancestors, + METH_VARARGS, "Integrate an expectation over counts of extant ancestors." }, + { "fixed_changepoints", (PyCFunction) tsdate_fixed_changepoints, METH_VARARGS, + "Breakpoints dividing counts roughly equally between epochs." }, + { "poisson_changepoints", (PyCFunction) tsdate_poisson_changepoints, METH_VARARGS, + "Changepoints of a Poisson rate under a linear penalty." }, + { "block_singletons", (PyCFunction) (void (*)(void)) tsdate_block_singletons, + METH_VARARGS | METH_KEYWORDS, "Group the singletons of unphased individuals into blocks." }, - { "reallocate_unphased", (PyCFunction) tsdate_reallocate_unphased, METH_VARARGS, - "Reallocate the likelihood of unphased blocks, in place." }, - { "mutation_frequency", (PyCFunction) tsdate_mutation_frequency, METH_VARARGS, + { "reallocate_unphased", (PyCFunction) (void (*)(void)) tsdate_reallocate_unphased, + METH_VARARGS | METH_KEYWORDS, + "The edge likelihoods with those of unphased blocks reallocated by phase." }, + { "mutation_frequency", (PyCFunction) (void (*)(void)) tsdate_mutation_frequency, + METH_VARARGS | METH_KEYWORDS, "The number of members of each sample set below each mutation." }, - { "split_disjoint_nodes", (PyCFunction) tsdate_split_disjoint_nodes, METH_VARARGS, + { "split_disjoint_nodes", (PyCFunction) (void (*)(void)) tsdate_split_disjoint_nodes, + METH_VARARGS | METH_KEYWORDS, "Split disconnected regions of nodes into separate nodes." }, - { "relabel_mutations_node", (PyCFunction) tsdate_relabel_mutations_node, - METH_VARARGS, "The new node of each mutation, after splitting nodes." }, - { "constrain_ages", (PyCFunction) tsdate_constrain_ages, METH_VARARGS, + { "relabel_mutations_node", + (PyCFunction) (void (*)(void)) tsdate_relabel_mutations_node, + METH_VARARGS | METH_KEYWORDS, + "The new node of each mutation, after splitting nodes." }, + { "constrain_ages", (PyCFunction) (void (*)(void)) tsdate_constrain_ages, + METH_VARARGS | METH_KEYWORDS, "Constrain node ages to be consistent with the edges." }, - { "contains_unary_nodes", (PyCFunction) tsdate_contains_unary_nodes, METH_VARARGS, + { "contains_unary_nodes", (PyCFunction) (void (*)(void)) tsdate_contains_unary_nodes, + METH_VARARGS | METH_KEYWORDS, "Whether any unmasked node has a single child in some tree." }, - { "marginalize_over_ancestors", (PyCFunction) tsdate_marginalize_over_ancestors, - METH_VARARGS, "Integrate an expectation over counts of extant ancestors." }, { "conditional_coalescent_variance", - (PyCFunction) tsdate_conditional_coalescent_variance, METH_VARARGS, + (PyCFunction) (void (*)(void)) tsdate_conditional_coalescent_variance, + METH_VARARGS | METH_KEYWORDS, "Variance of node age given the number of descendant leaves." }, - { "fixed_changepoints", (PyCFunction) tsdate_fixed_changepoints, METH_VARARGS, - "Breakpoints dividing counts roughly equally between epochs." }, - { "poisson_changepoints", (PyCFunction) tsdate_poisson_changepoints, METH_VARARGS, - "Changepoints of a Poisson rate under a linear penalty." }, - { "count_mutations", (PyCFunction) tsdate_count_mutations, METH_VARARGS, + { "count_mutations", (PyCFunction) (void (*)(void)) tsdate_count_mutations, + METH_VARARGS | METH_KEYWORDS, "Mutation counts and spans per edge, and the edge of each mutation." }, - { "mutational_area", (PyCFunction) tsdate_mutational_area, METH_VARARGS, + { "mutational_area", (PyCFunction) (void (*)(void)) tsdate_mutational_area, + METH_VARARGS | METH_KEYWORDS, "Mutation counts and area per inter-node interval." }, - { "mutational_timescale", (PyCFunction) tsdate_mutational_timescale, METH_VARARGS, + { "mutational_timescale", (PyCFunction) (void (*)(void)) tsdate_mutational_timescale, + METH_VARARGS | METH_KEYWORDS, "Breakpoints for rescaling time so that the mutation rate is constant." }, { "piecewise_scale_point_estimate", - (PyCFunction) tsdate_piecewise_scale_point_estimate, METH_VARARGS, - "Rescale point estimates of node ages." }, - { "piecewise_scale_posterior", (PyCFunction) tsdate_piecewise_scale_posterior, - METH_VARARGS, "Rescale gamma posteriors of node ages." }, - { "rescale_factors", (PyCFunction) tsdate_rescale_factors, METH_VARARGS, - "Multiply the EP factors by the node scales, in place." }, - { "assemble_factors", (PyCFunction) tsdate_assemble_factors, METH_VARARGS, - "The node posteriors implied by the EP factors." }, - { "constraints_are_consistent", (PyCFunction) tsdate_constraints_are_consistent, - METH_VARARGS, "Whether node age constraints are consistent with the edges." }, - { "propagate_likelihood", (PyCFunction) tsdate_propagate_likelihood, METH_VARARGS, - "Update the factors of the edge likelihoods, in place." }, - { "propagate_prior", (PyCFunction) tsdate_propagate_prior, METH_VARARGS, - "Update the factors of the prior, in place." }, - { "propagate_mutations", (PyCFunction) tsdate_propagate_mutations, METH_VARARGS, - "Posteriors of the ages of mutations, in place." }, + (PyCFunction) (void (*)(void)) tsdate_piecewise_scale_point_estimate, + METH_VARARGS | METH_KEYWORDS, "Rescale point estimates of node ages." }, + { "piecewise_scale_posterior", + (PyCFunction) (void (*)(void)) tsdate_piecewise_scale_posterior, + METH_VARARGS | METH_KEYWORDS, "Rescale gamma posteriors of node ages." }, + { "constraints_are_consistent", + (PyCFunction) (void (*)(void)) tsdate_constraints_are_consistent, + METH_VARARGS | METH_KEYWORDS, + "Whether node age constraints are consistent with the edges." }, { NULL } /* Sentinel */ }; @@ -2261,6 +2661,19 @@ PyInit__tsdate(void) Py_INCREF(TsdLibraryError); PyModule_AddObject(module, "LibraryError", TsdLibraryError); + if (PyType_Ready(&ExpectationPropagationType) < 0) { + Py_DECREF(module); + return NULL; + } + Py_INCREF(&ExpectationPropagationType); + if (PyModule_AddObject( + module, "ExpectationPropagation", (PyObject *) &ExpectationPropagationType) + != 0) { + Py_DECREF(&ExpectationPropagationType); + Py_DECREF(module); + return NULL; + } + if (add_scalar_functions(module) != 0) { Py_DECREF(module); return NULL; diff --git a/lib/tests/tests.c b/lib/tests/tests.c index c0d03919..145a66c4 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -25,7 +25,9 @@ /* * Smoke tests for the low-level tsdate API: return codes, error paths and memory * handling, with coarse sanity checks of results (finite, NaN, simple values). - * Numerical correctness is tested from Python. + * Numerical correctness is tested from Python, except for the expectation + * propagation passes on states set directly in the library's struct, which have + * tables of expected values. */ #include @@ -1351,52 +1353,26 @@ handle_cunit_error(void) exit(EXIT_FAILURE); } -/* Expectation propagation (variational.c): a four node, four edge fixture */ -typedef struct { - double node[16]; - double edge[16]; - double block[16]; - double scale[4]; - tsd_id_t parent[4]; - tsd_id_t child[4]; - tsd_id_t left[4]; - tsd_id_t right[4]; - tsd_ep_factors_t factors; -} ep_fixture_t; - /* Nodes 0 and 1 are fixed, at ages 1 and 5; 2 and 3 are free. */ static const double ep_constraints[8] = { 1, 1, 5, 5, 0, INFINITY, 0, INFINITY }; static const double ep_likelihoods[8] = { 1, 0.1, 1, 0.1, 1, 0.1, 1, 0.1 }; +static const double ep_huge[8] = { 1, 1e300, 1, 1e300, 1, 1e300, 1, 1e300 }; +static const tsd_id_t ep_parent[4] = { 2, 1, 3, 1 }; +static const tsd_id_t ep_child[4] = { 0, 3, 2, 0 }; +static const tsd_id_t ep_twin_parent[4] = { 2, 1, 3, 2 }; +static const tsd_id_t ep_twin_child[4] = { 0, 3, 2, 2 }; +/* Four nodes with four edges, and the same four as blocks, with posterior `post`. */ static void -ep_fixture_init(ep_fixture_t *fixture, const tsd_id_t *parent, const tsd_id_t *child) +ep_init(tsd_ep_t *ep, const tsd_id_t *parent, const tsd_id_t *child, + const double *likelihoods, const double *post) { - tsd_ep_factors_t *f = &fixture->factors; - int j; + int ret; - for (j = 0; j < 16; j++) { - fixture->node[j] = 0; - fixture->edge[j] = 0; - fixture->block[j] = 0; - } - for (j = 0; j < 4; j++) { - fixture->scale[j] = 1.0; - fixture->parent[j] = parent[j]; - fixture->child[j] = child[j]; - fixture->left[j] = parent[j]; - fixture->right[j] = child[j]; - } - f->num_nodes = 4; - f->num_edges = 4; - f->num_blocks = 4; - f->node = fixture->node; - f->edge = fixture->edge; - f->block = fixture->block; - f->scale = fixture->scale; - f->edges_parent = fixture->parent; - f->edges_child = fixture->child; - f->blocks_left = fixture->left; - f->blocks_right = fixture->right; + ret = tsd_ep_init(ep, 4, 4, 4, ep_constraints, parent, child, likelihoods, parent, + child, likelihoods); + CU_ASSERT_FATAL(ret == 0); + memcpy(ep->posterior, post, 8 * sizeof(*post)); } static void @@ -1448,31 +1424,57 @@ test_damp_and_rescale(void) } } +static void +test_ep_init(void) +{ + const tsd_id_t bad[4] = { 2, 1, 3, 4 }; + tsd_ep_t ep; + + CU_ASSERT_EQUAL(tsd_ep_init(&ep, 4, 4, 4, ep_constraints, ep_parent, ep_child, + ep_likelihoods, ep_parent, ep_child, ep_likelihoods), + 0); + CU_ASSERT_EQUAL(ep.scale[3], 1.0); + CU_ASSERT_EQUAL(ep.posterior[7], 0.0); + CU_ASSERT_EQUAL(ep.edges_parent[3], 1); + tsd_ep_free(&ep); + CU_ASSERT_EQUAL(tsd_ep_init(&ep, 4, 4, 4, ep_constraints, bad, ep_child, + ep_likelihoods, ep_parent, ep_child, ep_likelihoods), + TSD_ERR_NODE_OUT_OF_BOUNDS); + tsd_ep_free(&ep); + CU_ASSERT_EQUAL(tsd_ep_init(&ep, 4, 4, 4, ep_constraints, ep_parent, ep_child, + ep_likelihoods, ep_parent, bad, ep_likelihoods), + TSD_ERR_NODE_OUT_OF_BOUNDS); + tsd_ep_free(&ep); + CU_ASSERT_EQUAL( + tsd_ep_init(&ep, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL), 0); + tsd_ep_free(&ep); +} + static void test_rescale_and_assemble_factors(void) { - const tsd_id_t parent[4] = { 2, 1, 3, 1 }; - const tsd_id_t child[4] = { 0, 3, 2, 0 }; - ep_fixture_t fixture; + const double zero[8] = { 0 }; + tsd_ep_t ep; double posterior[8]; int j; - ep_fixture_init(&fixture, parent, child); + ep_init(&ep, ep_parent, ep_child, ep_likelihoods, zero); for (j = 0; j < 16; j++) { - fixture.node[j] = 1.0 + j; - fixture.edge[j] = 1.0 + j; - fixture.block[j] = 0.5 * (1.0 + j); + ep.node[j] = 1.0 + j; + ep.edge[j] = 1.0 + j; + ep.block[j] = 0.5 * (1.0 + j); } for (j = 0; j < 4; j++) { - fixture.scale[j] = 2.0; + ep.scale[j] = 2.0; } - tsd_assemble_factors(&fixture.factors, posterior); + tsd_ep_assemble_factors(&ep, posterior); CU_ASSERT_TRUE(posterior[0] > 0); - tsd_rescale_factors(&fixture.factors); - CU_ASSERT_EQUAL(fixture.scale[3], 1.0); - CU_ASSERT_EQUAL(fixture.node[0], 2.0); - CU_ASSERT_EQUAL(fixture.edge[0], 2.0); - CU_ASSERT_EQUAL(fixture.block[0], 1.0); + tsd_ep_rescale_factors(&ep); + CU_ASSERT_EQUAL(ep.scale[3], 1.0); + CU_ASSERT_EQUAL(ep.node[0], 2.0); + CU_ASSERT_EQUAL(ep.edge[0], 2.0); + CU_ASSERT_EQUAL(ep.block[0], 1.0); + tsd_ep_free(&ep); } static void @@ -1500,155 +1502,1749 @@ test_constraints_are_consistent(void) /* The branches of an EP pass: fixed child, fixed parent, free, both fixed. */ static void -run_likelihood_pass(int unphased, const tsd_id_t *parent, const tsd_id_t *child) +run_likelihood_pass(int unphased) { const tsd_id_t order[5] = { 0, 1, 2, 3, 2 }; - ep_fixture_t fixture; - double posterior[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; - double lognorm[4] = { 0 }; + const double post[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; + double *lognorm; + tsd_ep_t ep; int ret; - ep_fixture_init(&fixture, parent, child); - ret = tsd_propagate_likelihood(5, order, 4, parent, child, ep_likelihoods, - ep_constraints, 1000.0, 0.1, unphased, posterior, &fixture.factors, lognorm); + ep_init(&ep, ep_parent, ep_child, ep_likelihoods, post); + lognorm = unphased ? ep.blocks_lognorm : ep.edges_lognorm; + ret = tsd_ep_propagate_likelihood(&ep, 5, order, unphased, 1000.0, 0.1); CU_ASSERT_EQUAL(ret, 0); CU_ASSERT_TRUE(isfinite(lognorm[2])); /* a small scale triggers a rescaling of the factors in mid-pass */ - fixture.scale[2] = 1e-200; - ret = tsd_propagate_likelihood(5, order, 4, parent, child, ep_likelihoods, - ep_constraints, 1000.0, 0.1, unphased, posterior, &fixture.factors, lognorm); + ep.scale[2] = 1e-200; + ret = tsd_ep_propagate_likelihood(&ep, 5, order, unphased, 1000.0, 0.1); CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_EQUAL(fixture.scale[0], 1.0); + CU_ASSERT_EQUAL(ep.scale[0], 1.0); + tsd_ep_free(&ep); } static void test_propagate_likelihood(void) { - const tsd_id_t parent[4] = { 2, 1, 3, 1 }; - const tsd_id_t child[4] = { 0, 3, 2, 0 }; - const tsd_id_t twin_parent[4] = { 2, 1, 3, 2 }; - const tsd_id_t twin_child[4] = { 0, 3, 2, 2 }; const tsd_id_t order[1] = { 3 }; - const double huge[8] = { 1, 1e300, 1, 1e300, 1, 1e300, 1, 1e300 }; - ep_fixture_t fixture; - double posterior[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; - double lognorm[4] = { 0 }; const tsd_id_t sideways[1] = { 0 }; + const tsd_id_t bad[1] = { 4 }; + const double post[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; + tsd_ep_t ep; - run_likelihood_pass(0, parent, child); - run_likelihood_pass(1, parent, child); - ep_fixture_init(&fixture, twin_parent, twin_child); + run_likelihood_pass(0); + run_likelihood_pass(1); /* a block with a single node: the twin update, only in an unphased pass */ - CU_ASSERT_EQUAL( - tsd_propagate_likelihood(1, order, 4, twin_parent, twin_child, ep_likelihoods, - ep_constraints, 1000.0, 0.1, 1, posterior, &fixture.factors, lognorm), - 0); - CU_ASSERT_EQUAL( - tsd_propagate_likelihood(1, order, 4, twin_parent, twin_child, ep_likelihoods, - ep_constraints, 1000.0, 0.1, 0, posterior, &fixture.factors, lognorm), + ep_init(&ep, ep_twin_parent, ep_twin_child, ep_likelihoods, post); + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, order, 1, 1000.0, 0.1), 0); + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, order, 0, 1000.0, 0.1), TSD_ERR_TWIN_EDGE_IN_PHASED_PASS); + tsd_ep_free(&ep); /* the projection of an edge with a huge mutational target divides by zero */ - CU_ASSERT_EQUAL( - tsd_propagate_likelihood(1, sideways, 4, parent, child, huge, ep_constraints, - 1000.0, 0.1, 1, posterior, &fixture.factors, lognorm), + ep_init(&ep, ep_parent, ep_child, ep_huge, post); + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, sideways, 1, 1000.0, 0.1), TSD_ERR_ZERO_DIVISION); - /* an improper posterior, a damping that fails, and bad parameters */ - posterior[4] = -5; - CU_ASSERT_EQUAL( - tsd_propagate_likelihood(1, sideways, 4, parent, child, ep_likelihoods, - ep_constraints, 1000.0, 0.1, 0, posterior, &fixture.factors, lognorm), + tsd_ep_free(&ep); + /* an improper posterior, bad parameters and ids out of bounds */ + ep_init(&ep, ep_parent, ep_child, ep_likelihoods, post); + ep.posterior[4] = -5; + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, sideways, 0, 1000.0, 0.1), TSD_ERR_INVALID_NODE_POSTERIOR); - CU_ASSERT_EQUAL( - tsd_propagate_likelihood(1, order, 4, parent, child, ep_likelihoods, - ep_constraints, 0.5, 0.1, 0, posterior, &fixture.factors, lognorm), + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, order, 0, 0.5, 0.1), TSD_ERR_INVALID_MAX_SHAPE); - CU_ASSERT_EQUAL( - tsd_propagate_likelihood(1, order, 4, parent, child, ep_likelihoods, - ep_constraints, 1000.0, 1.0, 0.0, posterior, &fixture.factors, lognorm), + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, order, 0, 1000.0, 1.0), TSD_ERR_INVALID_MIN_STEP); + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, bad, 0, 1000.0, 0.1), + TSD_ERR_EDGE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, bad, 1, 1000.0, 0.1), + TSD_ERR_BLOCK_OUT_OF_BOUNDS); + tsd_ep_free(&ep); } static void test_propagate_prior(void) { - const tsd_id_t parent[4] = { 2, 1, 3, 1 }; - const tsd_id_t child[4] = { 0, 3, 2, 0 }; const uint8_t free_nodes[4] = { 0, 0, 1, 1 }; const uint8_t none[4] = { 0, 0, 0, 0 }; - ep_fixture_t fixture; - double posterior[8] = { 0, 0, 0, 0, 2, 1, 3, 2 }; - double improper[8] = { 0, 0, 0, 0, 1, 0, 1, 0 }; + const double post[8] = { 0, 0, 0, 0, 2, 1, 3, 2 }; + const double improper[8] = { 0, 0, 0, 0, 1, 0, 1, 0 }; + tsd_ep_t ep; - ep_fixture_init(&fixture, parent, child); - CU_ASSERT_EQUAL( - tsd_propagate_prior(free_nodes, 1000.0, 10, 1e-8, posterior, &fixture.factors), - 0); - CU_ASSERT_TRUE(fixture.node[9] != 0); + ep_init(&ep, ep_parent, ep_child, ep_likelihoods, post); + CU_ASSERT_EQUAL(tsd_ep_propagate_prior(&ep, free_nodes, 1000.0, 10, 1e-8), 0); + CU_ASSERT_TRUE(ep.node[9] != 0); CU_ASSERT_EQUAL( - tsd_propagate_prior(none, 0.5, 10, 1e-8, posterior, &fixture.factors), - TSD_ERR_INVALID_MAX_SHAPE); - CU_ASSERT_EQUAL( - tsd_propagate_prior(none, 1000.0, 10, 1e-8, posterior, &fixture.factors), 0); - CU_ASSERT_EQUAL( - tsd_propagate_prior(free_nodes, 1000.0, 10, 1e-8, improper, &fixture.factors), - TSD_ERR_NONPOSITIVE_PENALTY); + tsd_ep_propagate_prior(&ep, none, 0.5, 10, 1e-8), TSD_ERR_INVALID_MAX_SHAPE); + CU_ASSERT_EQUAL(tsd_ep_propagate_prior(&ep, none, 1000.0, 10, 1e-8), 0); /* the fit succeeds, but a posterior that is improper cannot be rescaled */ - posterior[4] = -5; - posterior[6] = 99; - CU_ASSERT_EQUAL( - tsd_propagate_prior(free_nodes, 1000.0, 10, 1e-8, posterior, &fixture.factors), + ep.posterior[4] = -5; + ep.posterior[6] = 99; + CU_ASSERT_EQUAL(tsd_ep_propagate_prior(&ep, free_nodes, 1000.0, 10, 1e-8), TSD_ERR_INVALID_NODE_POSTERIOR); + tsd_ep_free(&ep); + ep_init(&ep, ep_parent, ep_child, ep_likelihoods, improper); + CU_ASSERT_EQUAL(tsd_ep_propagate_prior(&ep, free_nodes, 1000.0, 10, 1e-8), + TSD_ERR_NONPOSITIVE_PENALTY); + tsd_ep_free(&ep); } static void run_mutations_pass(int unphased) { - const tsd_id_t parent[4] = { 2, 1, 3, 1 }; - const tsd_id_t child[4] = { 0, 3, 2, 0 }; - const tsd_id_t twin_parent[4] = { 2, 1, 3, 2 }; - const tsd_id_t twin_child[4] = { 0, 3, 2, 2 }; - const tsd_id_t order[6] = { 0, 1, 2, 3, 4, 5 }; const tsd_id_t edges[6] = { 0, 1, 2, 3, TSD_NULL, 3 }; - const double posterior[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; - const tsd_id_t *twin_edges = twin_parent; - ep_fixture_t fixture; + const double post[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; double mutations_posterior[12]; double mutations_phase[6]; + tsd_ep_t ep; int ret; - ep_fixture_init(&fixture, parent, child); - ret = tsd_propagate_mutations(6, order, edges, parent, child, ep_likelihoods, - ep_constraints, posterior, &fixture.factors, unphased, mutations_posterior, - mutations_phase); + ep_init(&ep, ep_parent, ep_child, ep_likelihoods, post); + ret = tsd_ep_propagate_mutations( + &ep, 6, edges, unphased, mutations_posterior, mutations_phase); CU_ASSERT_EQUAL(ret, 0); CU_ASSERT_TRUE(isfinite(mutations_phase[2])); - ep_fixture_init(&fixture, twin_parent, twin_child); - ret = tsd_propagate_mutations(6, order, edges, twin_edges, twin_child, - ep_likelihoods, ep_constraints, posterior, &fixture.factors, unphased, - mutations_posterior, mutations_phase); - CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isnan(mutations_posterior[8])); + CU_ASSERT_EQUAL(mutations_phase[4], 1.0); + tsd_ep_free(&ep); + ep_init(&ep, ep_twin_parent, ep_twin_child, ep_likelihoods, post); + ret = tsd_ep_propagate_mutations( + &ep, 6, edges, unphased, mutations_posterior, mutations_phase); + CU_ASSERT_EQUAL(ret, 0); + tsd_ep_free(&ep); } static void test_propagate_mutations(void) { - const tsd_id_t parent[4] = { 2, 1, 3, 1 }; - const tsd_id_t child[4] = { 0, 3, 2, 0 }; - const tsd_id_t order[1] = { 0 }; const tsd_id_t edge[1] = { 0 }; - const double posterior[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; - const double huge[8] = { 1, 1e300, 1, 1e300, 1, 1e300, 1, 1e300 }; - ep_fixture_t fixture; + const tsd_id_t bad[1] = { 4 }; + const double post[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; double mutations_posterior[2]; double mutations_phase[1]; + tsd_ep_t ep; run_mutations_pass(0); run_mutations_pass(1); - ep_fixture_init(&fixture, parent, child); - CU_ASSERT_EQUAL( - tsd_propagate_mutations(1, order, edge, parent, child, huge, ep_constraints, - posterior, &fixture.factors, 1, mutations_posterior, mutations_phase), + ep_init(&ep, ep_parent, ep_child, ep_huge, post); + CU_ASSERT_EQUAL(tsd_ep_propagate_mutations( + &ep, 1, edge, 1, mutations_posterior, mutations_phase), TSD_ERR_ZERO_DIVISION); + CU_ASSERT_EQUAL( + tsd_ep_propagate_mutations(&ep, 1, bad, 0, mutations_posterior, mutations_phase), + TSD_ERR_EDGE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_ep_propagate_mutations(&ep, 1, bad, 1, mutations_posterior, mutations_phase), + TSD_ERR_BLOCK_OUT_OF_BOUNDS); + tsd_ep_free(&ep); +} + +/* + * Tables of expectation propagation passes: the inputs of tsd_ep_init, the state + * that a case sets after it, and the state (or mutations) expected after the pass. + * Entries of the arrays beyond the sizes of the inputs are unused. + */ +#define EP_MAX_NODES 8 +#define EP_MAX_EDGES 8 +#define EP_MAX_ORDER 8 +#define EP_MAX_MUTATIONS 4 +#define EP_ULPS 4 + +typedef struct { + tsd_size_t num_nodes; + tsd_size_t num_edges; + tsd_size_t num_blocks; + double constraints[EP_MAX_NODES][2]; + tsd_id_t edges_parent[EP_MAX_EDGES]; + tsd_id_t edges_child[EP_MAX_EDGES]; + double edges_likelihood[EP_MAX_EDGES][2]; + tsd_id_t blocks_left[EP_MAX_EDGES]; + tsd_id_t blocks_right[EP_MAX_EDGES]; + double blocks_likelihood[EP_MAX_EDGES][2]; +} ep_inputs_t; + +typedef struct { + double posterior[EP_MAX_NODES][2]; + double node[EP_MAX_NODES][2][2]; + double edge[EP_MAX_EDGES][2][2]; + double block[EP_MAX_EDGES][2][2]; + double scale[EP_MAX_NODES]; + double edges_lognorm[EP_MAX_EDGES]; + double blocks_lognorm[EP_MAX_EDGES]; +} ep_state_t; + +/* The expected state `after` is only checked if `ret` is 0. */ +typedef struct { + const ep_inputs_t *inputs; + const ep_state_t *before; + tsd_size_t num_order; + tsd_id_t order[EP_MAX_ORDER]; + int unphased; + double max_shape; + double min_step; + int ret; + ep_state_t after; +} ep_likelihood_row_t; + +typedef struct { + const ep_inputs_t *inputs; + const ep_state_t *before; + ep_state_t after; +} ep_rescale_row_t; + +typedef struct { + const ep_inputs_t *inputs; + const ep_state_t *before; + uint8_t free[EP_MAX_NODES]; + double max_shape; + int64_t em_maxitt; + double em_reltol; + int ret; + ep_state_t after; +} ep_prior_row_t; + +typedef struct { + const ep_inputs_t *inputs; + const ep_state_t *before; + tsd_size_t num_mutations; + tsd_id_t mutations_edge[EP_MAX_MUTATIONS]; + int unphased; + int ret; + double posterior[EP_MAX_MUTATIONS][2]; + double phase[EP_MAX_MUTATIONS]; +} ep_mutations_row_t; + +/* The bits of `x` as an integer that increases with `x` (with -0 equal to 0). */ +static int64_t +ordered_bits(double x) +{ + int64_t bits; + + memcpy(&bits, &x, sizeof(bits)); + if (bits < 0) { + bits = INT64_MIN - bits; + } + return bits; +} + +/* `actual` is within `ulps` units in the last place of `expected`; NaNs are equal. */ +static void +assert_close_ulps(double actual, double expected, int ulps) +{ + int64_t a, b; + uint64_t distance; + + if (isnan(expected)) { + CU_ASSERT_TRUE(isnan(actual)); + } else if (!isfinite(expected) || !isfinite(actual)) { + CU_ASSERT_EQUAL(actual, expected); + } else { + a = ordered_bits(actual); + b = ordered_bits(expected); + distance = a > b ? (uint64_t) a - (uint64_t) b : (uint64_t) b - (uint64_t) a; + CU_ASSERT_TRUE(distance <= (uint64_t) ulps); + } +} + +static void +assert_array_close(const double *actual, const double *expected, tsd_size_t n) +{ + tsd_size_t j; + + for (j = 0; j < n; j++) { + assert_close_ulps(actual[j], expected[j], EP_ULPS); + } +} + +static void +ep_setup(tsd_ep_t *ep, const ep_inputs_t *in, const ep_state_t *state) +{ + const tsd_size_t n = in->num_nodes; + const tsd_size_t e = in->num_edges; + const tsd_size_t b = in->num_blocks; + int ret; + + ret = tsd_ep_init(ep, n, e, b, &in->constraints[0][0], in->edges_parent, + in->edges_child, &in->edges_likelihood[0][0], in->blocks_left, in->blocks_right, + &in->blocks_likelihood[0][0]); + CU_ASSERT_FATAL(ret == 0); + memcpy(ep->posterior, state->posterior, 2 * n * sizeof(double)); + memcpy(ep->node, state->node, 4 * n * sizeof(double)); + memcpy(ep->edge, state->edge, 4 * e * sizeof(double)); + memcpy(ep->block, state->block, 4 * b * sizeof(double)); + memcpy(ep->scale, state->scale, n * sizeof(double)); + memcpy(ep->edges_lognorm, state->edges_lognorm, e * sizeof(double)); + memcpy(ep->blocks_lognorm, state->blocks_lognorm, b * sizeof(double)); +} + +static void +assert_ep_state(const tsd_ep_t *ep, const ep_state_t *expected) +{ + const tsd_size_t n = ep->num_nodes; + const tsd_size_t e = ep->num_edges; + const tsd_size_t b = ep->num_blocks; + + assert_array_close(ep->posterior, &expected->posterior[0][0], 2 * n); + assert_array_close(ep->node, &expected->node[0][0][0], 4 * n); + assert_array_close(ep->edge, &expected->edge[0][0][0], 4 * e); + assert_array_close(ep->block, &expected->block[0][0][0], 4 * b); + assert_array_close(ep->scale, expected->scale, n); + assert_array_close(ep->edges_lognorm, expected->edges_lognorm, e); + assert_array_close(ep->blocks_lognorm, expected->blocks_lognorm, b); +} + +static const ep_inputs_t ep_inputs_fixed_child = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, 0 }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_state_t ep_state_edge2_valid = { .posterior = { { 4, 0.6 }, { 4, 0.6 } }, + .edge = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1 } }; + +static const ep_state_t ep_state_edge2_damped + = { .posterior = { { 23, 2.4499999999999997 }, { 23, 2.4499999999999997 } }, + .edge = { { { 22, 2.4 }, { 22, 2.4 } } }, + .scale = { 1, 1 } }; + +static const ep_inputs_t ep_inputs_fixed_child_huge_span = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, 0 }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 1, 1e+300 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 1, 1e+300 } } }; + +static const ep_inputs_t ep_inputs_fixed_parent = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 10, 10 } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_inputs_t ep_inputs_fixed_parent_huge_span = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 10, 10 } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 1, 1e+300 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 1, 1e+300 } } }; + +static const ep_inputs_t ep_inputs_both_free = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_inputs_t ep_inputs_both_free_huge_span = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 1, 1e+300 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 1, 1e+300 } } }; + +static const ep_inputs_t ep_inputs_both_fixed = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, 0 }, { 10, 10 } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_inputs_t ep_inputs_twin = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 1 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 1 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_state_t ep_state_block2_valid + = { .posterior = { { 4, 0.6 }, { 4, 0.6 } }, + .block = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1 } }; + +static const ep_state_t ep_state_block2_damped + = { .posterior = { { 23, 2.4499999999999997 }, { 23, 2.4499999999999997 } }, + .block = { { { 22, 2.4 }, { 22, 2.4 } } }, + .scale = { 1, 1 } }; + +static const ep_inputs_t ep_inputs_twin_huge_span = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 1 }, + .edges_likelihood = { { 1, 1e+300 } }, + .blocks_left = { 1 }, + .blocks_right = { 1 }, + .blocks_likelihood = { { 1, 1e+300 } } }; + +static const ep_inputs_t ep_inputs_sideways_fixed_parent = { .num_nodes = 3, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 5, 5 }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 2 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 2 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_state_t ep_state_block3_valid + = { .posterior = { { 4, 0.6 }, { 4, 0.6 }, { 4, 0.6 } }, + .block = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1, 1 } }; + +static const ep_state_t ep_state_block3_damped + = { .posterior = { { 23, 2.4499999999999997 }, { 23, 2.4499999999999997 }, + { 23, 2.4499999999999997 } }, + .block = { { { 22, 2.4 }, { 22, 2.4 } } }, + .scale = { 1, 1, 1 } }; + +static const ep_inputs_t ep_inputs_sideways_fixed_parent_huge_span = { .num_nodes = 3, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 5, 5 }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 2 }, + .edges_likelihood = { { 1, 1e+300 } }, + .blocks_left = { 1 }, + .blocks_right = { 2 }, + .blocks_likelihood = { { 1, 1e+300 } } }; + +static const ep_inputs_t ep_inputs_sideways_fixed_child = { .num_nodes = 3, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY }, { 5, 5 } }, + .edges_parent = { 1 }, + .edges_child = { 2 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 2 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_inputs_t ep_inputs_sideways_fixed_child_huge_span = { .num_nodes = 3, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY }, { 5, 5 } }, + .edges_parent = { 1 }, + .edges_child = { 2 }, + .edges_likelihood = { { 1, 1e+300 } }, + .blocks_left = { 1 }, + .blocks_right = { 2 }, + .blocks_likelihood = { { 1, 1e+300 } } }; + +static const ep_inputs_t ep_inputs_unphased_both_free = { .num_nodes = 3, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 2 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 2 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_inputs_t ep_inputs_unphased_both_free_huge_span = { .num_nodes = 3, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 2 }, + .edges_likelihood = { { 1, 1e+300 } }, + .blocks_left = { 1 }, + .blocks_right = { 2 }, + .blocks_likelihood = { { 1, 1e+300 } } }; + +static const ep_inputs_t ep_inputs_unphased_both_fixed = { .num_nodes = 3, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, 0 }, { 5, 5 }, { 5, 5 } }, + .edges_parent = { 1 }, + .edges_child = { 2 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 2 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_state_t ep_state_block2_improper_posterior + = { .posterior = { { 4, 0.6 }, { -2, 0.6 } }, + .block = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1 } }; + +static const ep_state_t ep_state_edge2_improper_parent + = { .posterior = { { 4, 0.6 }, { -2, 0.6 } }, + .edge = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1 } }; + +static const ep_state_t ep_state_edge2_improper_child + = { .posterior = { { -2, 0.6 }, { 4, 0.6 } }, + .edge = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1 } }; + +static const ep_state_t ep_state_edge2_infinite_rate + = { .posterior = { { 4, 0.6 }, { 3, INFINITY } }, + .edge = { { { 1, 0 }, { 1, 0.1 } } }, + .scale = { 1, 1 } }; + +static const ep_state_t ep_state_edge2_nan_parent_message + = { .posterior = { { 4, 0.6 }, { 4, 0.6 } }, + .edge = { { { 1, NAN }, { 1, 0.1 } } }, + .scale = { 1, 1 } }; + +static const ep_inputs_t ep_inputs_both_free_huge_count = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 1e+300, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 1e+300, 0.1 } } }; + +static const ep_inputs_t ep_inputs_twin_huge_count = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 1 }, + .edges_likelihood = { { 1e+300, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 1 }, + .blocks_likelihood = { { 1e+300, 0.1 } } }; + +static const ep_inputs_t ep_inputs_twin_negative_span = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 1 }, + .edges_likelihood = { { 3, -0.25 } }, + .blocks_left = { 1 }, + .blocks_right = { 1 }, + .blocks_likelihood = { { 3, -0.25 } } }; + +static const ep_inputs_t ep_inputs_small = { .num_nodes = 8, + .num_edges = 7, + .num_blocks = 2, + .constraints = { { 0, 0 }, { 0, 0 }, { 1, 1 }, { 0, INFINITY }, { 0, INFINITY }, + { 3, 3 }, { 0, INFINITY }, { 0, 0 } }, + .edges_parent = { 5, 5, 6, 3, 3, 4, 4 }, + .edges_child = { 2, 6, 7, 0, 1, 3, 5 }, + .edges_likelihood = { { 2, 0.4 }, { 1, 0.3 }, { 3, 0.5 }, { 1, 0.2 }, { 2, 0.6 }, + { 4, 0.5 }, { 0, 0.3 } }, + .blocks_left = { 3, 3 }, + .blocks_right = { 3, 6 }, + .blocks_likelihood = { { 1, 0.1 }, { 2, 0.3 } } }; + +static const ep_state_t ep_state_small_parent_below = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 6.7039039649712985e+159, 3.3519519824856493e+159 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 6.703903964971305e+159, 1.3407807929942595e+159 }, { 0, 0 } }, + { { 4.006486409929041e+160, 1.2019459229787126e+160 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 6.734058618746918e+159, 1.196199483833472e+160 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 6.7039039649712985e+159, 1.3407807929942595e+159 }, { 0, 0 } }, + { { 5.135700831885259e+159, 1.0968339446850352e+159 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 1.4916681462400413e-160, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small_child_below + = { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 6.7039039649712985e+159, 3.3519519824856493e+159 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 6.711708791635453e+160, 4.428121176801834e+160 } }, + { { 1.4375744407383892e+161, 2.395957401230648e+160 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 1.90559227298618e+159, 3.9026956224027946e+158 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 1.4916681462400413e-160, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } }; + +static const ep_state_t ep_state_small_child_just_below + = { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 6.7039039649713e+153, 3.35195198248565e+153 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 6.711708791635454e+154, 4.4281211768018344e+154 } }, + { { 1.4375744407383894e+155, 2.395957401230648e+154 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 1.9055922729861804e+153, 3.9026956224027947e+152 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 1.4916681462400412e-154, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } }; + +static const ep_state_t ep_state_small_child_at + = { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 6.703903964971299e+153, 3.3519519824856493e+153 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 6.711708791635453e+154, 4.428121176801834e+154 } }, + { { 1.4375744407383891e+155, 2.3959574012306478e+154 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 1.90559227298618e+153, 3.902695622402794e+152 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 1.4916681462400413e-154, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } }; + +static const ep_state_t ep_state_small_parent_above = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 3.3519519824856493e+153, 1.6759759912428246e+153 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 3.351951982485652e+153, 6.703903964971297e+152 }, { 0, 0 } }, + { { 2.0032432049645207e+154, 6.0097296148935625e+153 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 3.367029309373459e+153, 5.9809974191673596e+153 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 3.3519519824856493e+153, 6.703903964971297e+152 }, { 0, 0 } }, + { { 2.5678504159426292e+153, 5.484169723425176e+152 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 2.983336292480083e-154, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small_skipped_below = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 1, 0.11336363853632214 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1.4916681462400413e-160, 0.18609979046343747, 0.14043594343309676, + 1, 0.06108785244275427, 1 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small_random_scales = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 1, 0.11336363853632214 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale + = { 1.4554425309821815, 0.9046800706458055, 0.5614602859042921, 0.5247914532927936, + 1.7199053588004087, 1.8691333659165825, 1.4099536636507697, 1.5942448414759975 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small_scales_1em160 = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 1, 0.11336363853632214 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1e-160, 1e-160, 1e-160, 1e-160, 1e-160, 1e-160, 1e-160, 1e-160 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small_scales_1e100 = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 1, 0.11336363853632214 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1e+100, 1e+100, 1e+100, 1e+100, 1e+100, 1e+100, 1e+100, 1e+100 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 1, 0.11336363853632214 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale + = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, 0.06108785244275427, 1 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small_zero = { + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale + = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, 0.06108785244275427, 1 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small_negative_rate = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 1, 9.638256465887746 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale + = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, 0.06108785244275427, 1 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_inputs_t ep_inputs_both_fixed_equal = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 5, 5 }, { 5, 5 } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_inputs_t ep_inputs_both_fixed_adjacent = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 5, 5 }, { 5.000000000000001, 5.000000000000001 } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_inputs_t ep_inputs_both_fixed_inverted = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 10, 10 }, { 0, 0 } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +/* One edge (block) in each branch of the likelihood pass, with valid, damped and failing + * projections, and failures of the damping; expected values are those of the reference + * implementation, except for the divisions by zero that the library reports and the + * reference implementation computes in floating point. */ +static const ep_likelihood_row_t ep_likelihood_branch_rows[] = { + /* fixed_child, valid */ + { &ep_inputs_fixed_child, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior = { { 4, 0.6 }, { 6.000000000000001, 0.6 } }, + .edge = { { { 3.000000000000001, 0.09999999999999998 }, { 1, 0.1 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { 10.155030578372036 } } }, + /* fixed_child, damped */ + { &ep_inputs_fixed_child, &ep_state_edge2_damped, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior + = { { 23, 2.4499999999999997 }, { 5.543750000000004, 0.3368750000000001 } }, + .edge = { { { 4.543750000000002, 0.2868750000000003 }, { 22, 2.4 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { 12.861044274991544 } } }, + /* fixed_child, projection_fails */ + { &ep_inputs_fixed_child_huge_span, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, + 0, + { .posterior = { { 4, 0.6 }, { 3, 0.5 } }, + .edge = { { { 0, 0 }, { 1, 0.1 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { NAN } } }, + /* fixed_parent, valid */ + { &ep_inputs_fixed_parent, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior = { { 5.237205312432989, 1.5864148365014894 }, { 4, 0.6 } }, + .edge = { { { 1, 0.1 }, { 2.237205312432989, 1.0864148365014894 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { 8.392109396313824 } } }, + /* fixed_parent, damped */ + { &ep_inputs_fixed_parent, &ep_state_edge2_damped, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior + = { { 6.2859049125683475, 1.59224630406714 }, { 23, 2.4499999999999997 } }, + .edge = { { { 22, 2.4 }, { 5.285904912568346, 1.5422463040671401 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { 8.819556344925992 } } }, + /* fixed_parent, projection_fails */ + { &ep_inputs_fixed_parent_huge_span, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, + 0, + { .posterior = { { 3, 0.5 }, { 4, 0.6 } }, + .edge = { { { 1, 0.1 }, { 0, 0 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { NAN } } }, + /* both_free, valid */ + { &ep_inputs_both_free, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior = { { 3.340990263647014, 0.8598058362787732 }, + { 9.208111413904785, 0.6820200768549769 } }, + .edge = { { { 6.208111413904785, 0.1820200768549769 }, + { 0.3409902636470141, 0.35980583627877316 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { 13.088415737608075 } } }, + /* both_free, damped */ + { &ep_inputs_both_free, &ep_state_edge2_damped, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior = { { 3.191895535259021, 0.4211261303374999 }, + { 8.897091337020257, 0.3785701047221309 } }, + .edge = { { { 7.897091337020255, 0.3285701047221311 }, + { 2.191895535259019, 0.3711261303375002 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { 18.31439947231522 } } }, + /* both_free, projection_fails */ + { &ep_inputs_both_free_huge_span, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior = { { 3, 0.5 }, { 3, 0.5 } }, + .scale = { 1, 1 }, + .edges_lognorm = { NAN } } }, + /* both_fixed, valid */ + { &ep_inputs_both_fixed, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior = { { 4, 0.6 }, { 4, 0.6 } }, + .edge = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1 } } }, + /* twin, valid */ + { &ep_inputs_twin, &ep_state_block2_valid, 1, { 0 }, 1, 1e+300, 0.1, 0, + { .posterior = { { 4, 0.6 }, { 5.999999999999999, 0.6999999999999998 } }, + .block = { { { 2.999999999999999, 0.19999999999999984 }, { 1, 0.1 } } }, + .scale = { 1, 1 }, + .blocks_lognorm = { 11.155417361261065 } } }, + /* twin, damped */ + { &ep_inputs_twin, &ep_state_block2_damped, 1, { 0 }, 1, 1e+300, 0.1, 0, + { .posterior + = { { 23, 2.4499999999999997 }, { 5.543750000000005, 0.4287500000000001 } }, + .block = { { { 4.543750000000003, 0.37875000000000036 }, { 22, 2.4 } } }, + .scale = { 1, 1 }, + .blocks_lognorm = { 13.193426982114381 } } }, + /* twin, projection_fails */ + { &ep_inputs_twin_huge_span, &ep_state_block2_valid, 1, { 0 }, 1, 1e+300, 0.1, 0, + { .posterior = { { 4, 0.6 }, { 3, 0.5 } }, + .block = { { { 0, 0 }, { 1, 0.1 } } }, + .scale = { 1, 1 }, + .blocks_lognorm = { NAN } } }, + /* sideways_fixed_parent, valid */ + { &ep_inputs_sideways_fixed_parent, &ep_state_block3_valid, 1, { 0 }, 1, 1e+300, 0.1, + 0, + { .posterior + = { { 4, 0.6 }, { 4, 0.6 }, { 4.231122949265319, 0.5314156646872705 } }, + .block = { { { 1, 0.1 }, { 1.2311229492653188, 0.03141566468727053 } } }, + .scale = { 1, 1, 1 }, + .blocks_lognorm = { 10.937231963805417 } } }, + /* sideways_fixed_parent, damped */ + { &ep_inputs_sideways_fixed_parent, &ep_state_block3_damped, 1, { 0 }, 1, 1e+300, + 0.1, 0, + { .posterior = { { 23, 2.4499999999999997 }, { 23, 2.4499999999999997 }, + { 4.3632947068956724, 0.308279227260758 } }, + .block = { { { 22, 2.4 }, { 3.3632947068956707, 0.25827922726075825 } } }, + .scale = { 1, 1, 1 }, + .blocks_lognorm = { 13.159832686323291 } } }, + /* sideways_fixed_parent, projection_fails */ + { &ep_inputs_sideways_fixed_parent_huge_span, &ep_state_block3_valid, 1, { 0 }, 1, + 1e+300, 0.1, TSD_ERR_ZERO_DIVISION, { .scale = { 0 } } }, + /* sideways_fixed_child, valid */ + { &ep_inputs_sideways_fixed_child, &ep_state_block3_valid, 1, { 0 }, 1, 1e+300, 0.1, + 0, + { .posterior + = { { 4, 0.6 }, { 4.231122949265319, 0.5314156646872705 }, { 4, 0.6 } }, + .block = { { { 1.2311229492653188, 0.03141566468727053 }, { 1, 0.1 } } }, + .scale = { 1, 1, 1 }, + .blocks_lognorm = { 10.937231963805417 } } }, + /* sideways_fixed_child, damped */ + { &ep_inputs_sideways_fixed_child, &ep_state_block3_damped, 1, { 0 }, 1, 1e+300, 0.1, + 0, + { .posterior = { { 23, 2.4499999999999997 }, + { 4.3632947068956724, 0.308279227260758 }, { 23, 2.4499999999999997 } }, + .block = { { { 3.3632947068956707, 0.25827922726075825 }, { 22, 2.4 } } }, + .scale = { 1, 1, 1 }, + .blocks_lognorm = { 13.159832686323291 } } }, + /* sideways_fixed_child, projection_fails */ + { &ep_inputs_sideways_fixed_child_huge_span, &ep_state_block3_valid, 1, { 0 }, 1, + 1e+300, 0.1, TSD_ERR_ZERO_DIVISION, { .scale = { 0 } } }, + /* unphased_both_free, valid */ + { &ep_inputs_unphased_both_free, &ep_state_block3_valid, 1, { 0 }, 1, 1e+300, 0.1, 0, + { .posterior = { { 4, 0.6 }, { 3.7142857142857224, 0.5142857142857151 }, + { 3.7142857142857224, 0.5142857142857151 } }, + .block = { { { 0.7142857142857224, 0.014285714285715123 }, + { 0.7142857142857224, 0.014285714285715123 } } }, + .scale = { 1, 1, 1 }, + .blocks_lognorm = { 15.781852011892113 } } }, + /* unphased_both_free, damped */ + { &ep_inputs_unphased_both_free, &ep_state_block3_damped, 1, { 0 }, 1, 1e+300, 0.1, + 0, + { .posterior + = { { 23, 2.4499999999999997 }, { 3.4503846153846256, 0.2902307692307697 }, + { 3.4503846153846256, 0.2902307692307697 } }, + .block = { { { 2.450384615384624, 0.24023076923076994 }, + { 2.450384615384624, 0.24023076923076994 } } }, + .scale = { 1, 1, 1 }, + .blocks_lognorm = { 20.176250719010007 } } }, + /* unphased_both_free, projection_fails */ + { &ep_inputs_unphased_both_free_huge_span, &ep_state_block3_valid, 1, { 0 }, 1, + 1e+300, 0.1, 0, + { .posterior = { { 4, 0.6 }, { 3, 0.5 }, { 3, 0.5 } }, + .scale = { 1, 1, 1 }, + .blocks_lognorm = { NAN } } }, + /* unphased_both_fixed, valid */ + { &ep_inputs_unphased_both_fixed, &ep_state_block3_valid, 1, { 0 }, 1, 1e+300, 0.1, + 0, + { .posterior = { { 4, 0.6 }, { 4, 0.6 }, { 4, 0.6 } }, + .block = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1, 1 } } }, + /* twin, in a phased pass */ + { &ep_inputs_twin, &ep_state_block2_valid, 1, { 0 }, 0, 1e+300, 0.1, + TSD_ERR_TWIN_EDGE_IN_PHASED_PASS, { .scale = { 0 } } }, + /* twin, improper posterior */ + { &ep_inputs_twin, &ep_state_block2_improper_posterior, 1, { 0 }, 1, 1e+300, 0.1, + TSD_ERR_INVALID_NODE_POSTERIOR, { .scale = { 0 } } }, + /* both_free, improper parent posterior */ + { &ep_inputs_both_free, &ep_state_edge2_improper_parent, 1, { 0 }, 0, 1e+300, 0.1, + TSD_ERR_INVALID_NODE_POSTERIOR, { .scale = { 0 } } }, + /* both_free, improper child posterior */ + { &ep_inputs_both_free, &ep_state_edge2_improper_child, 1, { 0 }, 0, 1e+300, 0.1, + TSD_ERR_INVALID_NODE_POSTERIOR, { .scale = { 0 } } }, + /* fixed_child, infinite posterior rate */ + { &ep_inputs_fixed_child, &ep_state_edge2_infinite_rate, 1, { 0 }, 0, 1e+300, 0.1, + TSD_ERR_ZERO_DIVISION, { .scale = { 0 } } }, + /* both_free, NaN rate of the parent message */ + { &ep_inputs_both_free, &ep_state_edge2_nan_parent_message, 1, { 0 }, 0, 1e+300, 0.1, + TSD_ERR_INVALID_NODE_POSTERIOR, { .scale = { 0 } } }, + /* both_free, huge mutation count */ + { &ep_inputs_both_free_huge_count, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, + TSD_ERR_INVALID_HYPERGEO, { .scale = { 0 } } }, + /* twin, huge mutation count */ + { &ep_inputs_twin_huge_count, &ep_state_block2_valid, 1, { 0 }, 1, 1e+300, 0.1, 0, + { .posterior = { { 4, 0.6 }, { NAN, 0 } }, + .block = { { { INFINITY, 0.19999999999999996 }, { 1, 0.1 } } }, + .scale = { 1, 0 }, + .blocks_lognorm = { 6.908253500227124e+302 } } }, + /* twin, span that cancels the cavity rate */ + { &ep_inputs_twin_negative_span, &ep_state_block2_valid, 1, { 0 }, 1, 1e+300, 0.1, + TSD_ERR_ZERO_DIVISION, { .scale = { 0 } } }, +}; + +/* A node scale below sqrt(DBL_MIN) rescales the factors mid-pass (even for a skipped + * edge); expected values are those of the reference implementation. */ +static const ep_likelihood_row_t ep_likelihood_tiny_scale_rows[] = { + /* parent 3, scale far below sqrt(DBL_MIN) */ + { &ep_inputs_small, &ep_state_small_parent_below, 7, { 6, 0, 3, 1, 2, 4, 5 }, 0, + 1000, 0.1, 0, + { .posterior + = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0.5843090800906015, 0.4141118212927717 }, + { 4.576142402519787, 0.6250950421834373 }, { 0, 0 }, + { 7.309791285287766, 4.2876962848892894 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 0.14043594343309676, 0.015920329528856966 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 0.06108785244275427, 0.030543926221377134 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 4.231339141799602, 3.7535961130003725 } }, + { { 3.000000000000001, 0.49999999999999956 }, { 0, 0 } }, + { { 0.9999999999999996, 0.19999999999999984 }, { 0, 0 } }, + { { 4.252444351577177, 1.2757333054731532 }, { 0, 0 } }, + { { 2.587238914201411, 0.12364381294339392 }, + { 1.3127109581979957, 1.8519547257352813 } }, + { { 1.848467544885279, 0.48553089971118635 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.01736429104540892, 0.003556245667539863 } } }, + .scale = { 1, 1, 1, 1, 1, 1, 1, 1 }, + .edges_lognorm + = { 0, 0.8096806220619701, -2.9410830709207385, 1.132872360686421, + 1.2487332284559316, 6.048304970158144, 2.570276182534273 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* child 6, scale far below sqrt(DBL_MIN) */ + { &ep_inputs_small, &ep_state_small_child_below, 7, { 6, 0, 3, 1, 2, 4, 5 }, 0, 1000, + 0.1, 0, + { .posterior + = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 3.7958421321682865, 1.333492106759158 }, + { 10.065420818105734, 1.1253981016342018 }, { 0, 0 }, + { 0.771929388179595, 2.9935415583239657 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.18609979046343747, 0.09304989523171874 }, { 0, 0 } }, + { { 0.14043594343309676, 0.015920329528856966 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 14.85515137621622, 9.954829484254553 } }, + { { 15.37226023426819, 2.562043372378031 }, { 0, 0 } }, + { { 0.9999999999999999, 0.19999999999999973 }, { 0, 0 } }, + { { 1.9999999999999993, 0.5999999999999999 }, { 0, 0 } }, + { { 8.076517329787357, 0.6239468723941586 }, + { 0.28107594323350105, 0.3727742386144888 } }, + { { 1.848467544885279, 0.48553089971118635 }, { 0, 0 } } }, + .block = { { { 0.18609979046343747, 0.03721995809268749 }, { 0, 0 } }, + { { 0.1425666080079117, 0.030448014820263693 }, + { 0.2842511293334642, 0.05821526744408701 } } }, + .scale = { 1, 1, 1, 1, 1, 1, 1, 1 }, + .edges_lognorm + = { 0, 1.3769145175226662, -2.0216361082280465, 1.4634663891508815, + 1.5314734140184885, 8.186688217624864, 2.570276182534273 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* child 6, scale just below sqrt(DBL_MIN) */ + { &ep_inputs_small, &ep_state_small_child_just_below, 7, { 6, 0, 3, 1, 2, 4, 5 }, 0, + 1000, 0.1, 0, + { .posterior + = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 3.7958421321682865, 1.333492106759158 }, + { 10.065420818105734, 1.1253981016342018 }, { 0, 0 }, + { 0.771929388179595, 2.9935415583239657 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.18609979046343747, 0.09304989523171874 }, { 0, 0 } }, + { { 0.14043594343309676, 0.015920329528856966 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 14.85515137621622, 9.954829484254553 } }, + { { 15.37226023426819, 2.562043372378031 }, { 0, 0 } }, + { { 0.9999999999999999, 0.19999999999999973 }, { 0, 0 } }, + { { 1.9999999999999993, 0.5999999999999999 }, { 0, 0 } }, + { { 8.076517329787357, 0.6239468723941586 }, + { 0.28107594323350105, 0.3727742386144888 } }, + { { 1.848467544885279, 0.48553089971118635 }, { 0, 0 } } }, + .block = { { { 0.18609979046343747, 0.03721995809268749 }, { 0, 0 } }, + { { 0.1425666080079117, 0.030448014820263693 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 1, 1, 1, 1, 1 }, + .edges_lognorm + = { 0, 1.3769145175226662, -2.0216361082280465, 1.4634663891508815, + 1.5314734140184885, 8.186688217624864, 2.570276182534273 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* child 6, scale at sqrt(DBL_MIN) */ + { &ep_inputs_small, &ep_state_small_child_at, 7, { 6, 0, 3, 1, 2, 4, 5 }, 0, 1000, + 0.1, 0, + { .posterior + = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 3.7958421321682865, 1.333492106759158 }, + { 10.065420818105734, 1.1253981016342018 }, { 0, 0 }, + { 0.771929388179595, 2.9935415583239657 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 6.703903964971299e+153, 3.3519519824856493e+153 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 9.958750821126476e+154, 6.673622085010729e+154 } }, + { { 1.0305415633508114e+155, 1.717569272251352e+154 }, { 0, 0 } }, + { { 5.37346118181937, 1.0746922363638727 }, { 0, 0 } }, + { { 10.746922363638738, 3.224076709091622 }, { 0, 0 } }, + { { 57.51032913902832, 4.442928620274516 }, + { 1.510350670108483, 2.003087900777227 } }, + { { 13.162353594796642, 3.457312194028815 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 1.90559227298618e+153, 3.902695622402794e+152 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 1.4916681462400413e-154, 1 }, + .edges_lognorm + = { 0, 1.3769145175226662, -2.0216361082280465, 1.4634663891508815, + 1.5314734140184885, 8.186688217624864, 2.570276182534273 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* parent 3, scale above sqrt(DBL_MIN) */ + { &ep_inputs_small, &ep_state_small_parent_above, 7, { 6, 0, 3, 1, 2, 4, 5 }, 0, + 1000, 0.1, 0, + { .posterior + = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0.584309080090585, 0.41411182129276836 }, + { 4.5761424025197845, 0.6250950421834371 }, { 0, 0 }, + { 7.309791285287766, 4.2876962848892894 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 3.3519519824856493e+153, 1.6759759912428246e+153 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 69.26645761143446, 61.445867924689054 } }, + { { 49.10960002745744, 8.184933337909563 }, { 0, 0 } }, + { { 3.3519519824856478e+153, 6.703903964971293e+152 }, { 0, 0 } }, + { { 1.425398927467902e+154, 4.276196782403706e+153 }, { 0, 0 } }, + { { 18.422911193201482, 0.8804285421580647 }, + { 4.400144098762354e+153, 6.207663314402032e+153 } }, + { { 13.162353594796642, 3.457312194028815 }, { 0, 0 } } }, + .block = { { { 3.3519519824856493e+153, 6.703903964971297e+152 }, { 0, 0 } }, + { { 2.5678504159426292e+153, 5.484169723425176e+152 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 2.983336292480083e-154, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm + = { 0, 0.8096806220619701, -2.9410830709207385, 1.132872360686421, + 1.2487332284559312, 6.048304970158142, 2.570276182534273 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* child of a skipped edge between fixed nodes 2, scale far below sqrt(DBL_MIN) */ + { &ep_inputs_small, &ep_state_small_skipped_below, 7, { 6, 0, 3, 1, 2, 4, 5 }, 0, + 1000, 0.1, 0, + { .posterior + = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 3.7958421321682865, 1.333492106759158 }, + { 10.065420818105734, 1.1253981016342018 }, { 0, 0 }, + { 7.309791285287766, 4.2876962848892894 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.18609979046343747, 0.09304989523171874 }, { 0, 0 } }, + { { 0.14043594343309676, 0.015920329528856966 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 0.06108785244275427, 0.030543926221377134 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 4.231339141799602, 3.7535961130003725 } }, + { { 3.000000000000001, 0.49999999999999956 }, { 0, 0 } }, + { { 0.9999999999999998, 0.19999999999999973 }, { 0, 0 } }, + { { 1.9999999999999993, 0.5999999999999999 }, { 0, 0 } }, + { { 8.076517329787357, 0.6239468723941586 }, + { 0.28107594323350105, 0.3727742386144888 } }, + { { 1.848467544885279, 0.48553089971118635 }, { 0, 0 } } }, + .block = { { { 0.18609979046343747, 0.03721995809268749 }, { 0, 0 } }, + { { 0.1425666080079117, 0.030448014820263693 }, + { 0.01736429104540892, 0.003556245667539863 } } }, + .scale = { 1, 1, 1, 1, 1, 1, 1, 1 }, + .edges_lognorm + = { 0, 0.8096806220619701, -2.9410830709207385, 1.4634663891508815, + 1.5314734140184885, 8.186688217624864, 2.570276182534273 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, +}; + +/* Rescaling the factors of the small state; expected values are those of the reference + * implementation. */ +static const ep_rescale_row_t ep_rescale_rows[] = { + /* random scales */ + { &ep_inputs_small, &ep_state_small_random_scales, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.5247914532927936, 0.2623957266463968 }, { 0, 0 } }, + { { 1.7199053588004087, 0.19497472941173297 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 1.4099536636507697, 0.7049768318253848 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 14.115951615013927, 9.3131490381486 } }, + { { 30.2348207862264, 5.039136797704399 }, { 0, 0 } }, + { { 0.5247914532927941, 0.1049582906585587 }, { 0, 0 } }, + { { 3.1363364341891953, 0.9409009302567586 }, { 0, 0 } }, + { { 11.942651274661499, 0.9022213410919251 }, + { 0.5271520039004896, 0.9364025332539873 } }, + { { 10.831249108225103, 3.2327900038258597 }, { 0, 0 } } }, + .block = { { { 0.5247914532927936, 0.1049582906585587 }, { 0, 0 } }, + { { 0.4020302076707349, 0.08586177291019587 }, + { 0.4007809212005866, 0.08208082961319985 } } }, + .scale = { 1, 1, 1, 1, 1, 1, 1, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* scales 1e-160 */ + { &ep_inputs_small, &ep_state_small_scales_1em160, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1e-160, 5e-161 }, { 0, 0 } }, + { { 1e-160, 1.1336363853632214e-161 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1e-160, 5e-161 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 1.0011642211321843e-159, 6.605287307126262e-160 } }, + { { 2.1443840010982971e-159, 3.5739733351638275e-160 }, { 0, 0 } }, + { { 1.000000000000001e-160, 1.9999999999999997e-161 }, { 0, 0 } }, + { { 5.976348156034772e-160, 1.7929044468104316e-160 }, { 0, 0 } }, + { { 6.943783978317971e-160, 5.24576155586376e-161 }, + { 1.0044980736497989e-160, 1.7843326665831694e-160 } }, + { { 6.297584371607302e-160, 1.8796324968024114e-160 }, { 0, 0 } } }, + .block = { { { 1e-160, 1.9999999999999997e-161 }, { 0, 0 } }, + { { 7.660761339541722e-161, 1.6361122570014785e-161 }, + { 2.842511293334642e-161, 5.8215267444087e-162 } } }, + .scale = { 1, 1, 1, 1, 1, 1, 1, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* scales 1e100 */ + { &ep_inputs_small, &ep_state_small_scales_1e100, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1e+100, 5e+99 }, { 0, 0 } }, + { { 1e+100, 1.1336363853632215e+99 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1e+100, 5e+99 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 1.0011642211321844e+101, 6.605287307126262e+100 } }, + { { 2.144384001098297e+101, 3.5739733351638276e+100 }, { 0, 0 } }, + { { 1.000000000000001e+100, 1.9999999999999997e+99 }, { 0, 0 } }, + { { 5.9763481560347715e+100, 1.7929044468104318e+100 }, { 0, 0 } }, + { { 6.9437839783179705e+100, 5.24576155586376e+99 }, + { 1.0044980736497988e+100, 1.7843326665831695e+100 } }, + { { 6.297584371607302e+100, 1.8796324968024115e+100 }, { 0, 0 } } }, + .block = { { { 1e+100, 1.9999999999999997e+99 }, { 0, 0 } }, + { { 7.660761339541722e+99, 1.6361122570014786e+99 }, + { 2.842511293334642e+99, 5.8215267444087e+98 } } }, + .scale = { 1, 1, 1, 1, 1, 1, 1, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, +}; + +/* The prior pass on the small state, with and without EM iterations, and its failures; + * expected values are those of the reference implementation. */ +static const ep_prior_row_t ep_prior_rows[] = { + /* the root */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 0, 1, 0, 0, 0 }, 1000, 10, 1e-08, 0, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.5192046941817232 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 1.0000000000000007, 1.2928839970373238 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* free internal nodes */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 1, 1, 0, 1, 0 }, 1000, 10, 1e-08, 0, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 1.057316890860762 }, + { 2, 0.624343192922776 }, { 0, 0 }, + { 1.9999999999999998, 0.9120913003746354 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.9999999999999996, 1.5406029308285045 }, { 0, 0 } }, + { { 1.0000000000000007, 2.041542041202067 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 1.0000000000000002, 4.693337073573113 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* no EM iteration */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 1, 1, 0, 1, 0 }, 1000, -1, 1e-08, 0, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.9489678090196197 }, + { 2, 0.5159941110816337 }, { 0, 0 }, + { 1.9999999999999998, 0.803742218533493 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.9999999999999996, 0.9583933454693566 }, { 0, 0 } }, + { { 1.0000000000000007, 1.270022448764114 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 1.0000000000000002, 2.919677049386196 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* EM iterations reach the maximum */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 1, 1, 0, 1, 0 }, 1000, 3, 0, 0, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 1.0553334660423712 }, + { 2, 0.6223597681043852 }, { 0, 0 }, + { 1.9999999999999998, 0.9101078755562446 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.9999999999999996, 1.5299450745598246 }, { 0, 0 } }, + { { 1.0000000000000007, 2.0274186994855237 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 1.0000000000000002, 4.660868673734545 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* NaN tolerance: no EM iteration */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 1, 1, 0, 1, 0 }, 1000, 10, NAN, 0, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.9489678090196197 }, + { 2, 0.5159941110816337 }, { 0, 0 }, + { 1.9999999999999998, 0.803742218533493 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.9999999999999996, 0.9583933454693566 }, { 0, 0 } }, + { { 1.0000000000000007, 1.270022448764114 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 1.0000000000000002, 2.919677049386196 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* the cap on the shape binds */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 1, 1, 0, 1, 0 }, 1.5, 10, 1e-08, 0, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0.5, 0.2643292227151905 }, + { 0.5, 0.156085798230694 }, { 0, 0 }, { 0.5, 0.2280228250936589 }, + { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.9999999999999996, 1.5406029308285045 }, { 0, 0 } }, + { { 1.0000000000000007, 2.041542041202067 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 1.0000000000000002, 4.693337073573113 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 0.04652494761585937, 0.03510898585827419, 1, + 0.01527196311068857, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* no free nodes */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 0, 0, 0, 0, 0 }, 1000, 10, 1e-08, 0, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* zero posteriors */ + { &ep_inputs_small, &ep_state_small_zero, { 0, 0, 0, 0, 1, 0, 0, 0 }, 1000, 10, + 1e-08, TSD_ERR_NONPOSITIVE_PENALTY, { .scale = { 0 } } }, + /* negative cavity rate */ + { &ep_inputs_small, &ep_state_small_negative_rate, { 0, 0, 0, 0, 1, 0, 0, 0 }, 1000, + 10, 1e-08, TSD_ERR_NONPOSITIVE_PENALTY, { .scale = { 0 } } }, + /* max_shape below one */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 0, 1, 0, 0, 0 }, 0.5, 10, 1e-08, + TSD_ERR_INVALID_MAX_SHAPE, { .scale = { 0 } } }, +}; + +/* The mutations above one edge (block) in each branch, with fixed ages, and on the small + * state; expected values are those of the reference implementation, except for the + * divisions by zero that the library reports and the reference implementation computes + * in floating point. */ +static const ep_mutations_row_t ep_mutations_rows[] = { + /* fixed_child, valid */ + { &ep_inputs_fixed_child, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { 0.9090909090909085, 0.32727272727272716 } }, { 1 } }, + /* fixed_child, projection_fails */ + { &ep_inputs_fixed_child_huge_span, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { NAN, NAN } }, { NAN } }, + /* fixed_parent, valid */ + { &ep_inputs_fixed_parent, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { 11.458120369143545, 1.788464840386457 } }, { 1 } }, + /* fixed_parent, projection_fails */ + { &ep_inputs_fixed_parent_huge_span, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { NAN, NAN } }, { NAN } }, + /* both_free, valid */ + { &ep_inputs_both_free, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { 4.300199693233025, 0.529589210511545 } }, { 1 } }, + /* both_free, projection_fails */ + { &ep_inputs_both_free_huge_span, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { NAN, NAN } }, { NAN } }, + /* both_fixed, valid */ + { &ep_inputs_both_fixed, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { 2.0000000000000004, 0.6000000000000001 } }, { 1 } }, + /* twin, valid */ + { &ep_inputs_twin, &ep_state_block2_valid, 1, { 0 }, 1, 0, + { { 0.9090909090909081, 0.3818181818181816 } }, { 0.5 } }, + /* twin, projection_fails */ + { &ep_inputs_twin_huge_span, &ep_state_block2_valid, 1, { 0 }, 1, 0, + { { NAN, NAN } }, { NAN } }, + /* sideways_fixed_parent, valid */ + { &ep_inputs_sideways_fixed_parent, &ep_state_block3_valid, 1, { 0 }, 1, 0, + { { 0.4631781099265906, 0.3438769242905483 } }, { 0.36382649552564394 } }, + /* sideways_fixed_parent, projection_fails */ + { &ep_inputs_sideways_fixed_parent_huge_span, &ep_state_block3_valid, 1, { 0 }, 1, + TSD_ERR_ZERO_DIVISION, { { 0 } }, { 0 } }, + /* sideways_fixed_child, valid */ + { &ep_inputs_sideways_fixed_child, &ep_state_block3_valid, 1, { 0 }, 1, 0, + { { 0.4631781099265906, 0.3438769242905483 } }, { 0.36382649552564394 } }, + /* sideways_fixed_child, projection_fails */ + { &ep_inputs_sideways_fixed_child_huge_span, &ep_state_block3_valid, 1, { 0 }, 1, + TSD_ERR_ZERO_DIVISION, { { 0 } }, { 0 } }, + /* unphased_both_free, valid */ + { &ep_inputs_unphased_both_free, &ep_state_block3_valid, 1, { 0 }, 1, 0, + { { 0.7515923566878997, 0.3439490445859875 } }, { 0.5 } }, + /* unphased_both_free, projection_fails */ + { &ep_inputs_unphased_both_free_huge_span, &ep_state_block3_valid, 1, { 0 }, 1, 0, + { { NAN, NAN } }, { NAN } }, + /* unphased_both_fixed, valid */ + { &ep_inputs_unphased_both_fixed, &ep_state_block3_valid, 1, { 0 }, 1, 0, + { { 1.9999999999999991, 1.1999999999999997 } }, { 0.5 } }, + /* twin, in a phased pass */ + { &ep_inputs_twin, &ep_state_block2_valid, 1, { 0 }, 0, 0, + { { 1.0000000000000013, 0.40000000000000024 } }, { 0.5 } }, + /* equal fixed ages */ + { &ep_inputs_both_fixed_equal, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { NAN, NAN } }, { NAN } }, + /* adjacent fixed ages */ + { &ep_inputs_both_fixed_adjacent, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { 3.802951800684688e+32, 7.605903601369376e+31 } }, { 1 } }, + /* inverted fixed ages */ + { &ep_inputs_both_fixed_inverted, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { 2.0000000000000004, 0.6000000000000001 } }, { 1 } }, + /* edges of each branch, and a root */ + { &ep_inputs_small, &ep_state_small, 4, { 3, -1, 1, 6 }, 0, 0, + { { 0.46427524306562473, 0.788165385679627 }, { NAN, NAN }, + { 17.735867699826013, 8.054195276382863 }, + { 3.653465150153581, 0.9407997952233624 } }, + { 1, 1, 1, 1 } }, + /* blocks, and a root */ + { &ep_inputs_small, &ep_state_small, 3, { 1, -1, 0 }, 1, 0, + { { 0.5085725565286765, 0.6842153617467468 }, { NAN, NAN }, + { 0.4642752430656252, 0.7881653856796274 } }, + { 0.43985052500362354, 1, 0.5 } }, +}; + +static void +run_likelihood_rows(const ep_likelihood_row_t *rows, size_t num_rows) +{ + const ep_likelihood_row_t *row; + tsd_ep_t ep; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = rows + j; + ep_setup(&ep, row->inputs, row->before); + ret = tsd_ep_propagate_likelihood(&ep, row->num_order, row->order, row->unphased, + row->max_shape, row->min_step); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_ep_state(&ep, &row->after); + } + tsd_ep_free(&ep); + } +} + +static void +test_propagate_likelihood_branches(void) +{ + run_likelihood_rows(ep_likelihood_branch_rows, + sizeof(ep_likelihood_branch_rows) / sizeof(ep_likelihood_branch_rows[0])); +} + +static void +test_propagate_likelihood_tiny_scale(void) +{ + run_likelihood_rows( + ep_likelihood_tiny_scale_rows, sizeof(ep_likelihood_tiny_scale_rows) + / sizeof(ep_likelihood_tiny_scale_rows[0])); +} + +static void +test_rescale_factors(void) +{ + const size_t num_rows = sizeof(ep_rescale_rows) / sizeof(ep_rescale_rows[0]); + const ep_rescale_row_t *row; + tsd_ep_t ep; + size_t j; + + for (j = 0; j < num_rows; j++) { + row = ep_rescale_rows + j; + ep_setup(&ep, row->inputs, row->before); + tsd_ep_rescale_factors(&ep); + assert_ep_state(&ep, &row->after); + tsd_ep_free(&ep); + } +} + +static void +test_propagate_prior_table(void) +{ + const size_t num_rows = sizeof(ep_prior_rows) / sizeof(ep_prior_rows[0]); + const ep_prior_row_t *row; + tsd_ep_t ep; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = ep_prior_rows + j; + ep_setup(&ep, row->inputs, row->before); + ret = tsd_ep_propagate_prior( + &ep, row->free, row->max_shape, row->em_maxitt, row->em_reltol); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_ep_state(&ep, &row->after); + } + tsd_ep_free(&ep); + } +} + +static void +test_propagate_mutations_table(void) +{ + const size_t num_rows = sizeof(ep_mutations_rows) / sizeof(ep_mutations_rows[0]); + const ep_mutations_row_t *row; + double posterior[2 * EP_MAX_MUTATIONS]; + double phase[EP_MAX_MUTATIONS]; + tsd_ep_t ep; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = ep_mutations_rows + j; + ep_setup(&ep, row->inputs, row->before); + ret = tsd_ep_propagate_mutations(&ep, row->num_mutations, row->mutations_edge, + row->unphased, posterior, phase); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_array_close(posterior, &row->posterior[0][0], 2 * row->num_mutations); + assert_array_close(phase, row->phase, row->num_mutations); + } + tsd_ep_free(&ep); + } } int @@ -1700,11 +3296,17 @@ main(int argc, char **argv) { "test_piecewise_scale_point_estimate", test_piecewise_scale_point_estimate }, { "test_piecewise_scale_posterior", test_piecewise_scale_posterior }, { "test_damp_and_rescale", test_damp_and_rescale }, + { "test_ep_init", test_ep_init }, { "test_rescale_and_assemble_factors", test_rescale_and_assemble_factors }, { "test_constraints_are_consistent", test_constraints_are_consistent }, { "test_propagate_likelihood", test_propagate_likelihood }, { "test_propagate_prior", test_propagate_prior }, { "test_propagate_mutations", test_propagate_mutations }, + { "test_propagate_likelihood_branches", test_propagate_likelihood_branches }, + { "test_propagate_likelihood_tiny_scale", test_propagate_likelihood_tiny_scale }, + { "test_rescale_factors", test_rescale_factors }, + { "test_propagate_prior_table", test_propagate_prior_table }, + { "test_propagate_mutations_table", test_propagate_mutations_table }, CU_TEST_INFO_NULL, }; CU_SuiteInfo suites[] = { diff --git a/lib/tsdate.h b/lib/tsdate.h index 665a2774..e3913fca 100644 --- a/lib/tsdate.h +++ b/lib/tsdate.h @@ -297,35 +297,69 @@ int tsd_piecewise_scale_posterior(tsd_size_t num_posteriors, const double *poste double max_shape, double *new_posteriors); /* - * Expectation propagation passes (variational.c). + * Expectation propagation (variational.c). * - * The state of the algorithm stays in arrays owned by the caller, which the passes - * update in place. Natural parameters of a node are two doubles, so the posteriors - * and constraints have two columns, and the factors have shape [n][2][2]: for each - * edge (block), the factor to the parent (first block node) and to the child - * (second), each of two natural parameters; for each node, the mixture prior and the - * constraint. Array sizes are the caller's responsibility (tsd_bug_assert); errors are - * violated numerical preconditions (parameters, improper posteriors) and those of the - * projections. + * The state of the algorithm. Natural parameters of a node are two doubles, so the + * constraints, likelihoods and posteriors have two columns, and the factors have + * shape [n][2][2]: for each edge (block of unphased singletons), the factor to the + * parent (first block node) and to the child (second), each of two natural + * parameters; for each node, the mixture prior and the constraint. Factors are + * stored divided by the scale of their node. Errors are violated numerical + * preconditions (parameters, improper posteriors) and those of the projections. */ typedef struct { tsd_size_t num_nodes; tsd_size_t num_edges; tsd_size_t num_blocks; - double *node; /* num_nodes x 2 x 2 */ - double *edge; /* num_edges x 2 x 2 */ - double *block; /* num_blocks x 2 x 2 */ - double *scale; /* num_nodes */ - const tsd_id_t *edges_parent; - const tsd_id_t *edges_child; - const tsd_id_t *blocks_left; - const tsd_id_t *blocks_right; -} tsd_ep_factors_t; + double *constraints; /* num_nodes x 2: lower and upper bound on the age */ + tsd_id_t *edges_parent; /* num_edges */ + tsd_id_t *edges_child; /* num_edges */ + double *edges_likelihood; /* num_edges x 2: mutations and mutational span */ + tsd_id_t *blocks_left; /* num_blocks */ + tsd_id_t *blocks_right; /* num_blocks */ + double *blocks_likelihood; /* num_blocks x 2 */ + double *node; /* num_nodes x 2 x 2 */ + double *edge; /* num_edges x 2 x 2 */ + double *block; /* num_blocks x 2 x 2 */ + double *scale; /* num_nodes */ + double *posterior; /* num_nodes x 2 */ + double *edges_lognorm; /* num_edges */ + double *blocks_lognorm; /* num_blocks */ +} tsd_ep_t; +/* + * Copy the inputs; the factors, posteriors and normalising constants start at zero + * and the scales at one. The ids must be nodes (TSD_ERR_NODE_OUT_OF_BOUNDS). + */ +int tsd_ep_init(tsd_ep_t *self, tsd_size_t num_nodes, tsd_size_t num_edges, + tsd_size_t num_blocks, const double *constraints, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, const double *edges_likelihood, + const tsd_id_t *blocks_left, const tsd_id_t *blocks_right, + const double *blocks_likelihood); +void tsd_ep_free(tsd_ep_t *self); /* Multiply the factors by the scale of their node, and reset the scale to one. */ -void tsd_rescale_factors(const tsd_ep_factors_t *factors); +void tsd_ep_rescale_factors(tsd_ep_t *self); /* The posteriors implied by the factors; `posterior` has num_nodes x 2 entries. */ -void tsd_assemble_factors(const tsd_ep_factors_t *factors, double *posterior); +void tsd_ep_assemble_factors(const tsd_ep_t *self, double *posterior); +/* + * Update the factors of the edges (blocks, if `unphased`) in `order`, which may + * repeat or omit them. + */ +int tsd_ep_propagate_likelihood(tsd_ep_t *self, tsd_size_t num_order, + const tsd_id_t *order, int unphased, double max_shape, double min_step); +/* Fit an exponential prior to the cavities of the free nodes and update their factors. + */ +int tsd_ep_propagate_prior(tsd_ep_t *self, const uint8_t *free, double max_shape, + int64_t em_maxitt, double em_reltol); +/* + * Posteriors (two columns) and phases of mutations from the edges (blocks) above + * them, `mutations_edge`; a mutation whose edge is TSD_NULL, above a root, has NaN + * posterior and phase one. The state is not changed. + */ +int tsd_ep_propagate_mutations(const tsd_ep_t *self, tsd_size_t num_mutations, + const tsd_id_t *mutations_edge, int unphased, double *mutations_posterior, + double *mutations_phase); + /* The step `d` in (0, 1] so that the cavity `x - d * y` is proper, for `0 < s < 1`. */ int tsd_damp(const double x[2], const double y[2], double s, double *out); /* The factor that brings the shape of `x` between 1 / s and s; `s` is `max_shape`. */ @@ -334,29 +368,5 @@ int tsd_rescale(const double x[2], double s, double *out); int tsd_constraints_are_consistent(tsd_size_t num_nodes, tsd_size_t num_edges, const double *constraints, const tsd_id_t *edges_parent, const tsd_id_t *edges_child, int *consistent); -/* - * Update the factors of the edges (blocks of unphased singletons, if `unphased`), - * visited in the given order. `edges_parent`, `edges_child` and `likelihoods` (two - * columns) are those of the edges or blocks; `factors` must have `num_edges` of them. - */ -int tsd_propagate_likelihood(tsd_size_t num_order, const tsd_id_t *edge_order, - tsd_size_t num_edges, const tsd_id_t *edges_parent, const tsd_id_t *edges_child, - const double *likelihoods, const double *constraints, double max_shape, - double min_step, int unphased, double *posterior, const tsd_ep_factors_t *factors, - double *lognorm); -/* Fit an exponential prior to the cavities of the free nodes and update their factors. - */ -int tsd_propagate_prior(const uint8_t *free, double max_shape, int64_t em_maxitt, - double em_reltol, double *posterior, const tsd_ep_factors_t *factors); -/* - * Posteriors (`mutations_posterior`, two columns) and phases of the mutations in the - * given order, from the edges (blocks) above them; `mutations_edge` has the edge of - * each mutation, or TSD_NULL. The factors are not changed. - */ -int tsd_propagate_mutations(tsd_size_t num_order, const tsd_id_t *mutations_order, - const tsd_id_t *mutations_edge, const tsd_id_t *edges_parent, - const tsd_id_t *edges_child, const double *likelihoods, const double *constraints, - const double *posterior, const tsd_ep_factors_t *factors, int unphased, - double *mutations_posterior, double *mutations_phase); #endif diff --git a/lib/variational.c b/lib/variational.c index e23b1197..a2ce8d53 100644 --- a/lib/variational.c +++ b/lib/variational.c @@ -31,6 +31,7 @@ #include #include #include +#include #include "mathutil.h" #include "tsdate.h" @@ -47,90 +48,172 @@ #define PAIR(array, i) ((array) + 2 * (tsd_size_t) (i)) #define FACTOR(array, i, which) ((array) + 4 * (tsd_size_t) (i) + 2 * (which)) +int +tsd_ep_init(tsd_ep_t *self, tsd_size_t num_nodes, tsd_size_t num_edges, + tsd_size_t num_blocks, const double *constraints, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, const double *edges_likelihood, + const tsd_id_t *blocks_left, const tsd_id_t *blocks_right, + const double *blocks_likelihood) +{ + int ret = 0; + tsd_size_t j; + + memset(self, 0, sizeof(*self)); + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } + ret = tsd_check_edges(num_nodes, num_blocks, blocks_left, blocks_right); + if (ret != 0) { + goto out; + } + self->num_nodes = num_nodes; + self->num_edges = num_edges; + self->num_blocks = num_blocks; + self->constraints = malloc((2 * num_nodes + 1) * sizeof(*self->constraints)); + self->edges_parent = malloc((num_edges + 1) * sizeof(*self->edges_parent)); + self->edges_child = malloc((num_edges + 1) * sizeof(*self->edges_child)); + self->edges_likelihood + = malloc((2 * num_edges + 1) * sizeof(*self->edges_likelihood)); + self->blocks_left = malloc((num_blocks + 1) * sizeof(*self->blocks_left)); + self->blocks_right = malloc((num_blocks + 1) * sizeof(*self->blocks_right)); + self->blocks_likelihood + = malloc((2 * num_blocks + 1) * sizeof(*self->blocks_likelihood)); + self->node = calloc(4 * num_nodes + 1, sizeof(*self->node)); + self->edge = calloc(4 * num_edges + 1, sizeof(*self->edge)); + self->block = calloc(4 * num_blocks + 1, sizeof(*self->block)); + self->scale = malloc((num_nodes + 1) * sizeof(*self->scale)); + self->posterior = calloc(2 * num_nodes + 1, sizeof(*self->posterior)); + self->edges_lognorm = calloc(num_edges + 1, sizeof(*self->edges_lognorm)); + self->blocks_lognorm = calloc(num_blocks + 1, sizeof(*self->blocks_lognorm)); + if (self->constraints == NULL || self->edges_parent == NULL + || self->edges_child == NULL || self->edges_likelihood == NULL + || self->blocks_left == NULL || self->blocks_right == NULL + || self->blocks_likelihood == NULL || self->node == NULL || self->edge == NULL + || self->block == NULL || self->scale == NULL || self->posterior == NULL + || self->edges_lognorm == NULL || self->blocks_lognorm == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + memcpy(self->constraints, constraints, 2 * num_nodes * sizeof(*constraints)); + memcpy(self->edges_parent, edges_parent, num_edges * sizeof(*edges_parent)); + memcpy(self->edges_child, edges_child, num_edges * sizeof(*edges_child)); + memcpy(self->edges_likelihood, edges_likelihood, + 2 * num_edges * sizeof(*edges_likelihood)); + memcpy(self->blocks_left, blocks_left, num_blocks * sizeof(*blocks_left)); + memcpy(self->blocks_right, blocks_right, num_blocks * sizeof(*blocks_right)); + memcpy(self->blocks_likelihood, blocks_likelihood, + 2 * num_blocks * sizeof(*blocks_likelihood)); + for (j = 0; j < num_nodes; j++) { + self->scale[j] = 1.0; + } +out: + return ret; +} + void -tsd_rescale_factors(const tsd_ep_factors_t *factors) +tsd_ep_free(tsd_ep_t *self) { - const double *scale = factors->scale; + tsd_safe_free(self->constraints); + tsd_safe_free(self->edges_parent); + tsd_safe_free(self->edges_child); + tsd_safe_free(self->edges_likelihood); + tsd_safe_free(self->blocks_left); + tsd_safe_free(self->blocks_right); + tsd_safe_free(self->blocks_likelihood); + tsd_safe_free(self->node); + tsd_safe_free(self->edge); + tsd_safe_free(self->block); + tsd_safe_free(self->scale); + tsd_safe_free(self->posterior); + tsd_safe_free(self->edges_lognorm); + tsd_safe_free(self->blocks_lognorm); +} + +void +tsd_ep_rescale_factors(tsd_ep_t *self) +{ + const double *scale = self->scale; tsd_size_t j, k; double *f; - for (j = 0; j < factors->num_edges; j++) { - f = FACTOR(factors->edge, j, ROOTWARD); + for (j = 0; j < self->num_edges; j++) { + f = FACTOR(self->edge, j, ROOTWARD); for (k = 0; k < 2; k++) { - f[k] *= scale[factors->edges_parent[j]]; + f[k] *= scale[self->edges_parent[j]]; } - f = FACTOR(factors->edge, j, LEAFWARD); + f = FACTOR(self->edge, j, LEAFWARD); for (k = 0; k < 2; k++) { - f[k] *= scale[factors->edges_child[j]]; + f[k] *= scale[self->edges_child[j]]; } } - for (j = 0; j < factors->num_blocks; j++) { - f = FACTOR(factors->block, j, ROOTWARD); + for (j = 0; j < self->num_blocks; j++) { + f = FACTOR(self->block, j, ROOTWARD); for (k = 0; k < 2; k++) { - f[k] *= scale[factors->blocks_left[j]]; + f[k] *= scale[self->blocks_left[j]]; } - f = FACTOR(factors->block, j, LEAFWARD); + f = FACTOR(self->block, j, LEAFWARD); for (k = 0; k < 2; k++) { - f[k] *= scale[factors->blocks_right[j]]; + f[k] *= scale[self->blocks_right[j]]; } } - for (j = 0; j < factors->num_nodes; j++) { - f = FACTOR(factors->node, j, MIXPRIOR); + for (j = 0; j < self->num_nodes; j++) { + f = FACTOR(self->node, j, MIXPRIOR); for (k = 0; k < 2; k++) { f[k] *= scale[j]; } - f = FACTOR(factors->node, j, CONSTRNT); + f = FACTOR(self->node, j, CONSTRNT); for (k = 0; k < 2; k++) { f[k] *= scale[j]; } - factors->scale[j] = 1.0; + self->scale[j] = 1.0; } } void -tsd_assemble_factors(const tsd_ep_factors_t *factors, double *posterior) +tsd_ep_assemble_factors(const tsd_ep_t *self, double *posterior) { tsd_size_t j, k; double *post; const double *f; - for (j = 0; j < 2 * factors->num_nodes; j++) { + for (j = 0; j < 2 * self->num_nodes; j++) { posterior[j] = 0.0; } - for (j = 0; j < factors->num_edges; j++) { - post = PAIR(posterior, factors->edges_parent[j]); - f = FACTOR(factors->edge, j, ROOTWARD); + for (j = 0; j < self->num_edges; j++) { + post = PAIR(posterior, self->edges_parent[j]); + f = FACTOR(self->edge, j, ROOTWARD); for (k = 0; k < 2; k++) { post[k] += f[k]; } - post = PAIR(posterior, factors->edges_child[j]); - f = FACTOR(factors->edge, j, LEAFWARD); + post = PAIR(posterior, self->edges_child[j]); + f = FACTOR(self->edge, j, LEAFWARD); for (k = 0; k < 2; k++) { post[k] += f[k]; } } - for (j = 0; j < factors->num_blocks; j++) { - post = PAIR(posterior, factors->blocks_left[j]); - f = FACTOR(factors->block, j, ROOTWARD); + for (j = 0; j < self->num_blocks; j++) { + post = PAIR(posterior, self->blocks_left[j]); + f = FACTOR(self->block, j, ROOTWARD); for (k = 0; k < 2; k++) { post[k] += f[k]; } - post = PAIR(posterior, factors->blocks_right[j]); - f = FACTOR(factors->block, j, LEAFWARD); + post = PAIR(posterior, self->blocks_right[j]); + f = FACTOR(self->block, j, LEAFWARD); for (k = 0; k < 2; k++) { post[k] += f[k]; } } - for (j = 0; j < factors->num_nodes; j++) { + for (j = 0; j < self->num_nodes; j++) { post = PAIR(posterior, j); - f = FACTOR(factors->node, j, MIXPRIOR); + f = FACTOR(self->node, j, MIXPRIOR); for (k = 0; k < 2; k++) { post[k] += f[k]; } } - for (j = 0; j < factors->num_nodes; j++) { + for (j = 0; j < self->num_nodes; j++) { post = PAIR(posterior, j); - f = FACTOR(factors->node, j, CONSTRNT); + f = FACTOR(self->node, j, CONSTRNT); for (k = 0; k < 2; k++) { post[k] += f[k]; } @@ -463,14 +546,15 @@ update_free_edge(const likelihood_pass_t *pass, tsd_id_t i, tsd_id_t p, tsd_id_t } int -tsd_propagate_likelihood(tsd_size_t num_order, const tsd_id_t *edge_order, - tsd_size_t num_edges, const tsd_id_t *edges_parent, const tsd_id_t *edges_child, - const double *likelihoods, const double *constraints, double max_shape, - double min_step, int unphased, double *posterior, const tsd_ep_factors_t *factors, - double *lognorm) +tsd_ep_propagate_likelihood(tsd_ep_t *self, tsd_size_t num_order, const tsd_id_t *order, + int unphased, double max_shape, double min_step) { int ret = 0; const double tiny = sqrt(DBL_MIN); + const double *constraints = self->constraints; + const tsd_size_t num_edges = unphased ? self->num_blocks : self->num_edges; + const tsd_id_t *edges_parent = unphased ? self->blocks_left : self->edges_parent; + const tsd_id_t *edges_child = unphased ? self->blocks_right : self->edges_child; likelihood_pass_t pass; tsd_size_t j; tsd_id_t i, p, c; @@ -484,23 +568,27 @@ tsd_propagate_likelihood(tsd_size_t num_order, const tsd_id_t *edge_order, ret = tsd_trace_error(TSD_ERR_INVALID_MIN_STEP); goto out; } + ret = tsd_check_ids(num_order, order, num_edges, 0, + unphased ? TSD_ERR_BLOCK_OUT_OF_BOUNDS : TSD_ERR_EDGE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } pass.max_shape = max_shape; pass.min_step = min_step; pass.unphased = unphased; pass.constraints = constraints; - pass.likelihoods = likelihoods; - pass.posterior = posterior; - pass.scale = factors->scale; - pass.factor = unphased ? factors->block : factors->edge; - pass.lognorm = lognorm; - tsd_bug_assert(num_edges == (unphased ? factors->num_blocks : factors->num_edges)); + pass.likelihoods = unphased ? self->blocks_likelihood : self->edges_likelihood; + pass.posterior = self->posterior; + pass.scale = self->scale; + pass.factor = unphased ? self->block : self->edge; + pass.lognorm = unphased ? self->blocks_lognorm : self->edges_lognorm; for (j = 0; j < num_order; j++) { - i = edge_order[j]; + i = order[j]; p = edges_parent[i]; c = edges_child[i]; if (pass.scale[p] < tiny || pass.scale[c] < tiny) { - tsd_rescale_factors(factors); + tsd_ep_rescale_factors(self); } fixed_p = constraints[2 * (tsd_size_t) p + LOWER] == constraints[2 * (tsd_size_t) p + UPPER]; @@ -530,13 +618,12 @@ tsd_propagate_likelihood(tsd_size_t num_order, const tsd_id_t *edge_order, /* The prior cavity of a free node: the posterior without the mixture prior factor. */ static void -get_prior_cavity(const tsd_ep_factors_t *factors, const double *posterior, tsd_size_t j, - double cavity[2]) +get_prior_cavity(const tsd_ep_t *self, tsd_size_t j, double cavity[2]) { double message[2]; - get_message(FACTOR(factors->node, j, MIXPRIOR), factors->scale[j], message); - get_cavity(PAIR(posterior, j), 1.0, message, cavity); + get_message(FACTOR(self->node, j, MIXPRIOR), self->scale[j], message); + get_cavity(PAIR(self->posterior, j), 1.0, message, cavity); } /* @@ -544,17 +631,17 @@ get_prior_cavity(const tsd_ep_factors_t *factors, const double *posterior, tsd_s * `with_penalty`, summing sequentially. */ static double -mean_shape_over_rate(const tsd_ep_factors_t *factors, const double *posterior, - const uint8_t *free, int with_penalty, double penalty) +mean_shape_over_rate( + const tsd_ep_t *self, const uint8_t *free, int with_penalty, double penalty) { double cavity[2]; double shape, rate, term; double total = 0.0; tsd_size_t j, count = 0; - for (j = 0; j < factors->num_nodes; j++) { + for (j = 0; j < self->num_nodes; j++) { if (free[j]) { - get_prior_cavity(factors, posterior, j, cavity); + get_prior_cavity(self, j, cavity); shape = cavity[0] + 1; rate = cavity[1]; if (with_penalty) { @@ -569,11 +656,12 @@ mean_shape_over_rate(const tsd_ep_factors_t *factors, const double *posterior, } int -tsd_propagate_prior(const uint8_t *free, double max_shape, int64_t em_maxitt, - double em_reltol, double *posterior, const tsd_ep_factors_t *factors) +tsd_ep_propagate_prior(tsd_ep_t *self, const uint8_t *free, double max_shape, + int64_t em_maxitt, double em_reltol) { int ret = 0; - const tsd_size_t num_nodes = factors->num_nodes; + const tsd_size_t num_nodes = self->num_nodes; + double *posterior = self->posterior; double cavity[2]; double penalty, delta; int64_t itt; @@ -592,14 +680,14 @@ tsd_propagate_prior(const uint8_t *free, double max_shape, int64_t em_maxitt, } /* fit an exponential to cavity distributions for unconstrained nodes */ - penalty = 1 / mean_shape_over_rate(factors, posterior, free, 0, 0.0); + penalty = 1 / mean_shape_over_rate(self, free, 0, 0.0); itt = 0; delta = INFINITY; while (fabs(delta) > fabs(penalty) * em_reltol) { if (itt > em_maxitt) { break; } - delta = 1 / mean_shape_over_rate(factors, posterior, free, 1, penalty) - penalty; + delta = 1 / mean_shape_over_rate(self, free, 1, penalty) - penalty; penalty += delta; itt++; } @@ -611,17 +699,17 @@ tsd_propagate_prior(const uint8_t *free, double max_shape, int64_t em_maxitt, /* update posteriors and rescale to keep shape bounded */ for (j = 0; j < num_nodes; j++) { if (free[j]) { - get_prior_cavity(factors, posterior, j, cavity); + get_prior_cavity(self, j, cavity); PAIR(posterior, j)[1] = cavity[1] + penalty; - FACTOR(factors->node, j, MIXPRIOR) - [0] = (PAIR(posterior, j)[0] - cavity[0]) / factors->scale[j]; - FACTOR(factors->node, j, MIXPRIOR) - [1] = (PAIR(posterior, j)[1] - cavity[1]) / factors->scale[j]; + FACTOR(self->node, j, MIXPRIOR) + [0] = (PAIR(posterior, j)[0] - cavity[0]) / self->scale[j]; + FACTOR(self->node, j, MIXPRIOR) + [1] = (PAIR(posterior, j)[1] - cavity[1]) / self->scale[j]; } } for (j = 0; j < num_nodes; j++) { if (free[j]) { - ret = rescale_posterior(PAIR(posterior, j), factors->scale + j, max_shape); + ret = rescale_posterior(PAIR(posterior, j), self->scale + j, max_shape); if (ret != 0) { goto out; } @@ -702,28 +790,36 @@ project_mutation(const mutation_pass_t *pass, tsd_id_t i, tsd_id_t p, tsd_id_t c } int -tsd_propagate_mutations(tsd_size_t num_order, const tsd_id_t *mutations_order, - const tsd_id_t *mutations_edge, const tsd_id_t *edges_parent, - const tsd_id_t *edges_child, const double *likelihoods, const double *constraints, - const double *posterior, const tsd_ep_factors_t *factors, int unphased, - double *mutations_posterior, double *mutations_phase) +tsd_ep_propagate_mutations(const tsd_ep_t *self, tsd_size_t num_mutations, + const tsd_id_t *mutations_edge, int unphased, double *mutations_posterior, + double *mutations_phase) { int ret = 0; + const tsd_size_t num_edges = unphased ? self->num_blocks : self->num_edges; + const tsd_id_t *edges_parent = unphased ? self->blocks_left : self->edges_parent; + const tsd_id_t *edges_child = unphased ? self->blocks_right : self->edges_child; mutation_pass_t pass; - tsd_size_t j; - tsd_id_t m, i; + tsd_size_t m; + tsd_id_t i; double phase, proj[2]; + ret = tsd_check_ids(num_mutations, mutations_edge, num_edges, 1, + unphased ? TSD_ERR_BLOCK_OUT_OF_BOUNDS : TSD_ERR_EDGE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } pass.unphased = unphased; - pass.constraints = constraints; - pass.likelihoods = likelihoods; - pass.posterior = posterior; - pass.scale = factors->scale; - pass.factor = unphased ? factors->block : factors->edge; - for (j = 0; j < num_order; j++) { - m = mutations_order[j]; + pass.constraints = self->constraints; + pass.likelihoods = unphased ? self->blocks_likelihood : self->edges_likelihood; + pass.posterior = self->posterior; + pass.scale = self->scale; + pass.factor = unphased ? self->block : self->edge; + for (m = 0; m < num_mutations; m++) { + mutations_posterior[2 * m] = NAN; + mutations_posterior[2 * m + 1] = NAN; + mutations_phase[m] = 1.0; i = mutations_edge[m]; - if (i == TSD_NULL) { /* skip mutations above root */ + if (i == TSD_NULL) { /* a mutation above a root */ continue; } ret = project_mutation(&pass, i, edges_parent[i], edges_child[i], &phase, proj); @@ -731,8 +827,8 @@ tsd_propagate_mutations(tsd_size_t num_order, const tsd_id_t *mutations_order, goto out; } mutations_phase[m] = phase; - mutations_posterior[2 * (tsd_size_t) m] = proj[0]; - mutations_posterior[2 * (tsd_size_t) m + 1] = proj[1]; + mutations_posterior[2 * m] = proj[0]; + mutations_posterior[2 * m + 1] = proj[1]; } out: return ret; diff --git a/tests/oracle/ep_state.py b/tests/oracle/ep_state.py index 712529e0..f68a6a61 100644 --- a/tests/oracle/ep_state.py +++ b/tests/oracle/ep_state.py @@ -1,19 +1,17 @@ """ -Expectation propagation state for the equivalence tests of ``tsdate.variational``: -snapshots of real state from ``ExpectationPropagation`` (editable, so that tests can -force branches), one-edge snapshots, and runners that call the ``propagate_*`` -functions of a given module (``_tsdate``, or the oracle ``oracle.variational``) on -copies of a snapshot. +Expectation propagation inputs for the equivalence tests of ``tsdate.variational``: +the inputs of ``ExpectationPropagation`` on the session fixtures (editable, so that +tests can force branches), and the loop of ``iterate``, run with the +``ExpectationPropagation`` of a given module (``_tsdate``, or the oracle +``oracle.variational``). """ import numpy as np import tskit from tsdate.variational import ( - CONSTRNT, LEAFWARD, LOWER, - MIXPRIOR, ROOTWARD, UPPER, USE_BLOCK_LIKELIHOOD, @@ -22,7 +20,7 @@ ) # fixture name -> (singletons_phased, mutation_rate) -SNAPSHOT_SPECS = { +SPECS = { "small_ts": (True, 1e-8), "small_ts_unphased": (False, 1e-7), "small_ts_historical": (True, 1e-8), @@ -37,77 +35,44 @@ "block_likelihoods", "block_nodes", "node_constraints", - "node_posterior", - "edge_logconst", - "block_logconst", "unconstrained_roots", "roots", "leaves", - "mutation_order", "mutation_edges", "mutation_blocks", ) -class Snapshot: +class Inputs: """ - Copies of the arrays of an ``ExpectationPropagation`` after some iterations, so - that tests can edit them freely and rebuild fresh factors. + Copies of the inputs of an ``ExpectationPropagation``, which tests can edit """ def __init__(self, ts, ep): self.ts = ts for name in _COPIED: setattr(self, name, getattr(ep, name).copy()) - factors = ep.factors - self.fields = {k: getattr(factors, k).copy() for k in self.FIELDS} - self.num_mutations = ep.mutation_phase.size - - FIELDS = ("node", "edge", "block", "scale") def copy(self): - new = object.__new__(Snapshot) + new = object.__new__(Inputs) for k, v in self.__dict__.items(): - if isinstance(v, np.ndarray): - v = v.copy() - elif isinstance(v, dict): - v = {a: b.copy() for a, b in v.items()} - setattr(new, k, v) + setattr(new, k, v.copy() if isinstance(v, np.ndarray) else v) return new - def factors(self): + def kwargs(self): """ - A copy of the factors, as the tuple of arrays ``(node, edge, block, scale, - edges_parent, edges_child, blocks_left, blocks_right)`` that the passes take + The arguments of ``ExpectationPropagation`` """ - f = self.fields - return ( - f["node"].copy(), - f["edge"].copy(), - f["block"].copy(), - f["scale"].copy(), - self.edge_parents.copy(), - self.edge_children.copy(), - self.block_nodes[ROOTWARD].copy(), - self.block_nodes[LEAFWARD].copy(), + return dict( + constraints=self.node_constraints, + edges_parent=self.edge_parents, + edges_child=self.edge_children, + edges_likelihood=self.edge_likelihoods, + blocks_left=self.block_nodes[ROOTWARD], + blocks_right=self.block_nodes[LEAFWARD], + blocks_likelihood=self.block_likelihoods, ) - def unscale(self, nodes, scale): - """ - Make the state equivalent but with ``scale[nodes] = scale``, by dividing all - factors associated with those nodes (see ``rescale_factors``) by ``scale``. - """ - sel = np.zeros(self.node_posterior.shape[0], dtype=bool) - sel[nodes] = True - f = self.fields - f["edge"][sel[self.edge_parents], ROOTWARD] /= scale - f["edge"][sel[self.edge_children], LEAFWARD] /= scale - f["block"][sel[self.block_nodes[ROOTWARD]], ROOTWARD] /= scale - f["block"][sel[self.block_nodes[LEAFWARD]], LEAFWARD] /= scale - f["node"][sel, MIXPRIOR] /= scale - f["node"][sel, CONSTRNT] /= scale - f["scale"][sel] = scale - def fix_nodes(self, nodes): """ Constrain ``nodes`` to their true (simulated) ages @@ -123,7 +88,7 @@ def fixed(self): def branch_counts(self, unphased): """ - Number of edges (blocks) of each kind visited by the propagate functions + Number of edges (blocks) of each kind visited by the likelihood passes """ if unphased: p, c = self.block_nodes[ROOTWARD], self.block_nodes[LEAFWARD] @@ -138,286 +103,82 @@ def branch_counts(self, unphased): "both_free": int(np.sum(~fp & ~fc & (p != c))), } - def after_pass(self, state): + def mutations_edge(self, unphased): """ - Copy with the state returned by `run_likelihood` as its current state + The edges (blocks) of the phased (unphased) mutations """ - posterior, _, *fields = state - new = self.copy() - new.node_posterior = posterior.copy() - new.fields = {k: v.copy() for k, v in zip(self.FIELDS, fields)} - return new + phased = self.mutation_blocks == tskit.NULL + if unphased: + return self.mutation_blocks[~phased] + return self.mutation_edges[phased] -def make_snapshot(ts, name, iterations=2): +def make_inputs(ts, name): """ - Snapshot of the state of EP on ``ts`` (fixture ``name``) after some iterations + The inputs of EP on ``ts`` (fixture ``name``) """ - singletons_phased, mutation_rate = SNAPSHOT_SPECS[name] + singletons_phased, mutation_rate = SPECS[name] ep = ExpectationPropagation( ts, mutation_rate=mutation_rate, singletons_phased=singletons_phased ) - for _ in range(iterations): - ep.iterate(max_shape=1000, min_step=0.1) - return Snapshot(ts, ep) + return Inputs(ts, ep) -def fixed_internal_snapshot(snap, unphased, every=4): +def fixed_internal(inputs, unphased, every=4): """ - Copy of a snapshot with every ``every``th internal node (every ``every``th block + Copy of the inputs with every ``every``th internal node (every ``every``th block node, for unphased blocks) fixed at its true age; the first block has both nodes - fixed. Gives all branches of the propagate functions. + fixed. Gives all branches of the passes. """ - snap = snap.copy() + inputs = inputs.copy() if unphased: - nodes = np.unique(snap.block_nodes) + nodes = np.unique(inputs.block_nodes) fixed = list(nodes[::every]) - fixed += [snap.block_nodes[ROOTWARD][0], snap.block_nodes[LEAFWARD][0]] + fixed += [inputs.block_nodes[ROOTWARD][0], inputs.block_nodes[LEAFWARD][0]] else: - internal = np.flatnonzero(~snap.fixed) + internal = np.flatnonzero(~inputs.fixed) fixed = list(internal[::every]) - snap.fix_nodes(np.unique(fixed)) - return snap - - -# One edge (block) in each branch of `propagate_likelihood`/`propagate_mutations`: -# (unphased, constraints of the nodes, parent, child). Fixed nodes have ages 0 -# (child) or 10 (parent) or 5 (block nodes). -INF = np.inf -BRANCHES = { - "fixed_child": (False, [[0, 0], [0, INF]], 1, 0), - "fixed_parent": (False, [[0, INF], [10, 10]], 1, 0), - "both_free": (False, [[0, INF], [0, INF]], 1, 0), - "both_fixed": (False, [[0, 0], [10, 10]], 1, 0), - "twin": (True, [[0, INF], [0, INF]], 1, 1), - "sideways_fixed_parent": (True, [[0, INF], [5, 5], [0, INF]], 1, 2), - "sideways_fixed_child": (True, [[0, INF], [0, INF], [5, 5]], 1, 2), - "unphased_both_free": (True, [[0, INF], [0, INF], [0, INF]], 1, 2), - "unphased_both_fixed": (True, [[0, 0], [5, 5], [5, 5]], 1, 2), -} -# cavity and message of every node; `node` = cavity + message -CAVITY, MESSAGE = np.array([3.0, 0.5]), np.array([1.0, 0.1]) -# message so large relative to the cavity that the cavity has to be damped -DAMPED_CAVITY, DAMPED_MESSAGE = np.array([1.0, 0.05]), np.array([22.0, 2.4]) - - -def tiny_snapshot(branch, cavity=CAVITY, message=MESSAGE, likelihood=(3.0, 0.1)): - """ - Snapshot of a single edge (or block) whose factor is `message` at each end - """ - unphased, constraints, p, c = BRANCHES[branch] - constraints = np.array(constraints, dtype=np.float64) - n = constraints.shape[0] - snap = Snapshot.__new__(Snapshot) - snap.ts = None - snap.node_constraints = constraints - snap.node_posterior = np.tile(cavity + message, (n, 1)) - parents, children = np.array([p], np.int32), np.array([c], np.int32) - snap.edge_parents, snap.edge_children = parents, children - snap.block_nodes = np.array([parents, children]) - snap.edge_order = snap.block_order = np.zeros(1, np.int32) - snap.edge_likelihoods = snap.block_likelihoods = np.array([likelihood]) - snap.edge_logconst = np.zeros(1) - snap.block_logconst = np.zeros(1) - snap.mutation_order = np.zeros(1, np.int32) - snap.mutation_edges = np.zeros(1, np.int32) - snap.mutation_blocks = np.full(1, 0 if unphased else tskit.NULL, np.int32) - snap.num_mutations = 1 - fields = { - "node": np.zeros((n, 2, 2)), - "edge": np.zeros((1, 2, 2)), - "block": np.zeros((1, 2, 2)), - "scale": np.ones(n), - } - factor = fields["block" if unphased else "edge"] - factor[0, ROOTWARD] = message - factor[0, LEAFWARD] = message - snap.fields = fields - snap.unphased = unphased - snap.unconstrained_roots = np.zeros(n, dtype=bool) - return snap + inputs.fix_nodes(np.unique(fixed)) + return inputs -def likelihood_args(snap, unphased, order=None, likelihoods=None): +def iterate(ep, inputs, max_shape=1000.0, min_step=0.1, em_maxitt=10, em_reltol=1e-8): """ - Leading arguments of `propagate_likelihood` and the matching `lognorm` + The loop of ``tsdate.variational.ExpectationPropagation.iterate`` """ - if unphased: - args = ( - snap.block_order if order is None else order, - snap.block_nodes[ROOTWARD], - snap.block_nodes[LEAFWARD], - snap.block_likelihoods if likelihoods is None else likelihoods, - ) - return args, snap.block_logconst - args = ( - snap.edge_order if order is None else order, - snap.edge_parents, - snap.edge_children, - snap.edge_likelihoods if likelihoods is None else likelihoods, + ep.propagate_likelihood( + order=inputs.block_order, + unphased=USE_BLOCK_LIKELIHOOD, + max_shape=max_shape, + min_step=min_step, ) - return args, snap.edge_logconst - - -def run_likelihood( - module, - snap, - unphased, - max_shape=1000.0, - min_step=0.1, - order=None, - likelihoods=None, -): - """ - Run ``module.propagate_likelihood`` on copies of ``snap``; return - ``(posterior, lognorm, node, edge, block, scale)`` after the pass. - """ - args, lognorm = likelihood_args(snap, unphased, order, likelihoods) - factors = snap.factors() - posterior = snap.node_posterior.copy() - lognorm = lognorm.copy() - module.propagate_likelihood( - *args, - snap.node_constraints, - posterior, - factors, - lognorm, - max_shape, - min_step, - USE_BLOCK_LIKELIHOOD if unphased else USE_EDGE_LIKELIHOOD, + ep.propagate_likelihood( + order=inputs.edge_order, + unphased=USE_EDGE_LIKELIHOOD, + max_shape=max_shape, + min_step=min_step, ) - return (posterior, lognorm, *factors[:4]) - - -def run_prior(module, snap, free, max_shape=1000.0, em_maxitt=10, em_reltol=1e-8): - """ - Run ``module.propagate_prior`` on copies of ``snap``; return - ``(posterior, node, scale)`` after the pass. - """ - factors = snap.factors() - node, edge, block, scale, *_ = factors - posterior = snap.node_posterior.copy() - module.propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol) - return (posterior, node, scale) + ep.propagate_prior( + free=inputs.unconstrained_roots, + max_shape=max_shape, + em_maxitt=em_maxitt, + em_reltol=em_reltol, + ) + ep.rescale_factors() -def run_mutations(module, snap, unphased, edges=None, posterior=None, order=None): +def start(module, inputs, iterations=2): """ - Run ``module.propagate_mutations`` on the phased (or unphased) mutations; return - ``(mutation_posterior, phase, node, edge, block, scale)``. + The ``ExpectationPropagation`` of ``module`` on ``inputs`` after ``iterations`` """ - factors = snap.factors() - mut_posterior = np.full((snap.num_mutations, 2), np.nan) - phase = np.ones(snap.num_mutations) - phased = snap.mutation_blocks == tskit.NULL - if unphased: - order = snap.mutation_order[~phased] if order is None else order - args = ( - snap.mutation_blocks, - snap.block_nodes[ROOTWARD], - snap.block_nodes[LEAFWARD], - snap.block_likelihoods, - ) - else: - order = snap.mutation_order[phased] if order is None else order - args = ( - snap.mutation_edges if edges is None else edges, - snap.edge_parents, - snap.edge_children, - snap.edge_likelihoods, - ) - module.propagate_mutations( - order, - mut_posterior, - phase, - *args, - snap.node_constraints, - snap.node_posterior if posterior is None else posterior, - factors, - USE_BLOCK_LIKELIHOOD if unphased else USE_EDGE_LIKELIHOOD, - ) - return (mut_posterior, phase, *factors[:4]) + ep = module.ExpectationPropagation(**inputs.kwargs()) + for _ in range(iterations): + iterate(ep, inputs) + return ep -def run_sweeps( - module, - snap, - num_sweeps, - max_shape=1000.0, - min_step=0.1, - em_maxitt=10, -): +def state(ep): """ - Run EP sweeps (the loop of `ExpectationPropagation.iterate`, then the mutation - passes of `infer`) with the functions of ``module`` from a copy of ``snap``. - Returns, per sweep, ``(posterior, edge_logconst, block_logconst)`` copies, and the - mutation ``(posterior, phase)``. + Copies of the node posteriors and the log normalising constants """ - factors = snap.factors() - posterior = snap.node_posterior.copy() - edge_logconst = snap.edge_logconst.copy() - block_logconst = snap.block_logconst.copy() - mut_posterior = np.full((snap.num_mutations, 2), np.nan) - mut_phase = np.ones(snap.num_mutations) - block_nodes = snap.block_nodes - states = [] - for _ in range(num_sweeps): - module.propagate_likelihood( - snap.block_order, - block_nodes[ROOTWARD], - block_nodes[LEAFWARD], - snap.block_likelihoods, - snap.node_constraints, - posterior, - factors, - block_logconst, - max_shape, - min_step, - USE_BLOCK_LIKELIHOOD, - ) - module.propagate_likelihood( - snap.edge_order, - snap.edge_parents, - snap.edge_children, - snap.edge_likelihoods, - snap.node_constraints, - posterior, - factors, - edge_logconst, - max_shape, - min_step, - USE_EDGE_LIKELIHOOD, - ) - module.propagate_prior( - snap.unconstrained_roots, posterior, factors, max_shape, em_maxitt, 1e-8 - ) - module.rescale_factors(factors) - states.append((posterior.copy(), edge_logconst.copy(), block_logconst.copy())) - phased = snap.mutation_blocks == tskit.NULL - module.propagate_mutations( - snap.mutation_order[~phased], - mut_posterior, - mut_phase, - snap.mutation_blocks, - block_nodes[ROOTWARD], - block_nodes[LEAFWARD], - snap.block_likelihoods, - snap.node_constraints, - posterior, - factors, - USE_BLOCK_LIKELIHOOD, - ) - module.propagate_mutations( - snap.mutation_order[phased], - mut_posterior, - mut_phase, - snap.mutation_edges, - snap.edge_parents, - snap.edge_children, - snap.edge_likelihoods, - snap.node_constraints, - posterior, - factors, - USE_EDGE_LIKELIHOOD, - ) - return states, (mut_posterior, mut_phase) + return ep.posterior, ep.edges_lognorm, ep.blocks_lognorm diff --git a/tests/oracle/phasing.py b/tests/oracle/phasing.py index aae6c6d6..35d599ad 100644 --- a/tests/oracle/phasing.py +++ b/tests/oracle/phasing.py @@ -11,13 +11,15 @@ def reallocate_unphased(edges_likelihood, mutations_phase, mutations_block, blocks_edges): """ - Add a proportion of each unphased singleton mutation to one of the two - edges to which it maps + The edge likelihoods with a proportion of each unphased singleton mutation added + to one of the two edges to which it maps """ + if edges_likelihood.shape[1] != 2 or blocks_edges.shape[1] != 2: + raise ValueError("edges_likelihood and blocks_edges must have two columns") if mutations_phase.size != mutations_block.size: - raise ValueError("Array sizes are not equal") - if blocks_edges.shape[1] != 2: - raise ValueError("Arrays must have two columns") + raise ValueError("Mutation arrays must have the same size") + + edges_likelihood = edges_likelihood.copy() num_edges = edges_likelihood.shape[0] edges_unphased = np.full(num_edges, False) @@ -42,6 +44,7 @@ def reallocate_unphased(edges_likelihood, mutations_phase, mutations_block, bloc edges_likelihood[j, 0] += 1 - mutations_phase[m] if not np.isclose(num_unphased, np.sum(edges_likelihood[edges_unphased, 0])): raise library_error(errors.UNPHASED_LIKELIHOOD_NOT_CONSERVED) + return edges_likelihood def block_singletons( @@ -49,7 +52,6 @@ def block_singletons( nodes_individual, mutations_node, mutations_position, - edges_parent, edges_child, edges_left, edges_right, @@ -62,19 +64,18 @@ def block_singletons( blocks_edges, mutations_block)``. """ if not ( - edges_parent.size - == edges_child.size + edges_child.size == edges_left.size == edges_right.size == indexes_insert.size == indexes_remove.size ): - raise ValueError("Array sizes are not equal") + raise ValueError("Edge arrays must have the same size") if mutations_node.size != mutations_position.size: - raise ValueError("Array sizes are not equal") + raise ValueError("Mutation arrays must have the same size") num_mutations = mutations_node.size - num_edges = edges_parent.size + num_edges = edges_child.size num_individuals = individuals_unphased.size indexes_mutation = np.argsort(mutations_position) @@ -189,9 +190,9 @@ def mutation_frequency( == indexes_insert.size == indexes_remove.size ): - raise ValueError("Array sizes are not equal") + raise ValueError("Edge arrays must have the same size") if mutations_node.size != mutations_position.size: - raise ValueError("Array sizes are not equal") + raise ValueError("Mutation arrays must have the same size") num_nodes, num_sample_sets = nodes_sample.shape num_mutations = mutations_node.size diff --git a/tests/oracle/rescaling.py b/tests/oracle/rescaling.py index 25dcd914..a2a862ae 100644 --- a/tests/oracle/rescaling.py +++ b/tests/oracle/rescaling.py @@ -82,7 +82,7 @@ def f(i, j): # loss def count_mutations( - node_is_sample, + nodes_sample, mutations_node, mutations_position, edges_parent, @@ -98,16 +98,21 @@ def count_mutations( The mutations on each edge and the edge's span, weighted by the number of samples below the edge if ``size_biased``, as ``(edges_stats, mutations_edge)``. """ - if not (edges_parent.size == edges_child.size == edges_left.size == edges_right.size): + if not ( + edges_parent.size + == edges_child.size + == edges_left.size + == edges_right.size + == indexes_insert.size + == indexes_remove.size + ): raise ValueError("Edge arrays must have the same size") - if not (indexes_insert.size == indexes_remove.size == edges_parent.size): - raise ValueError("Edge index arrays must have one entry per edge") if mutations_node.size != mutations_position.size: raise ValueError("Mutation arrays must have the same size") num_mutations = mutations_node.size num_edges = edges_parent.size - num_nodes = node_is_sample.size + num_nodes = nodes_sample.size indexes_mutation = np.argsort(mutations_position) position_insert = edges_left[indexes_insert] @@ -121,7 +126,7 @@ def count_mutations( edges_mutations = np.zeros(num_edges) edges_span = np.zeros(num_edges) - nodes_samples[node_is_sample] = 1.0 + nodes_samples[nodes_sample] = 1.0 left = 0.0 a, b, d = 0, 0, 0 while a < num_edges or b < num_edges: diff --git a/tests/oracle/util.py b/tests/oracle/util.py index 365f6e24..2bbc145d 100644 --- a/tests/oracle/util.py +++ b/tests/oracle/util.py @@ -10,7 +10,7 @@ def split_disjoint_nodes( - edges_parent, edges_child, edges_left, edges_right, node_excluded + edges_parent, edges_child, edges_left, edges_right, nodes_excluded ): """ Split disconnected regions of nodes into separate nodes. @@ -19,9 +19,9 @@ def split_disjoint_nodes( from which original node the new nodes are derived. """ if not (edges_parent.size == edges_child.size == edges_left.size == edges_right.size): - raise ValueError("Array sizes are not equal") + raise ValueError("Edge arrays must have the same size") num_edges = edges_parent.size - num_nodes = node_excluded.size + num_nodes = nodes_excluded.size # For each edge, check whether parent/child is separated by a gap from the # previous edge involving either parent/child. Label disconnected segments @@ -30,11 +30,11 @@ def split_disjoint_nodes( # TODO: is a sort really needed here? edges_segments = np.full((2, num_edges), -1, dtype=np.int32) nodes_segments = np.full(num_nodes, -1, dtype=np.int32) - nodes_right = np.full(node_excluded.size, -np.inf, dtype=np.float64) + nodes_right = np.full(nodes_excluded.size, -np.inf, dtype=np.float64) for e in edges_order: nodes = edges_parent[e], edges_child[e] for i, n in enumerate(nodes): - if node_excluded[n]: + if nodes_excluded[n]: continue nodes_segments[n] += edges_left[e] > nodes_right[n] edges_segments[i, e] = nodes_segments[n] @@ -76,8 +76,8 @@ def relabel_mutations_node( edges_child, edges_left, edges_right, - insert_index, - remove_index, + indexes_insert, + indexes_remove, ): """ Traverse trees, maintaining a mapping between old and new node IDs in the @@ -88,19 +88,19 @@ def relabel_mutations_node( == edges_child.size == edges_left.size == edges_right.size - == insert_index.size - == remove_index.size + == indexes_insert.size + == indexes_remove.size ): - raise ValueError("Array sizes are not equal") + raise ValueError("Edge arrays must have the same size") if mutations_position.size != mutations_node.size: - raise ValueError("Array sizes are not equal") + raise ValueError("Mutation arrays must have the same size") num_nodes = nodes_order.size num_edges = edges_parent.size num_mutations = mutations_position.size - insert_position = edges_left[insert_index] - remove_position = edges_right[remove_index] + insert_position = edges_left[indexes_insert] + remove_position = edges_right[indexes_remove] sequence_length = remove_position[-1] output = np.full(num_mutations, tskit.NULL, dtype=np.int32) @@ -112,7 +112,7 @@ def relabel_mutations_node( b += 1 while a < num_edges and insert_position[a] == left: # edges in - e = insert_index[a] + e = indexes_insert[a] c, p = edges_child[e], edges_parent[e] nodes_map[nodes_order[c]] = c nodes_map[nodes_order[p]] = p @@ -146,9 +146,9 @@ def constrain_ages( 1983 """ if nodes_time.size != nodes_fixed.size: - raise ValueError("Array sizes are not equal") + raise ValueError("Node arrays must have the same size") if edges_parent.size != edges_child.size: - raise ValueError("Array sizes are not equal") + raise ValueError("Edge arrays must have the same size") num_edges = edges_parent.size nodes_time = nodes_time.copy() @@ -198,7 +198,6 @@ def contains_unary_nodes( indexes_insert, indexes_remove, sequence_length, - num_nodes, ): """ Whether a node outside ``nodes_mask`` has exactly one child in some tree. @@ -210,10 +209,10 @@ def contains_unary_nodes( == indexes_insert.size == indexes_remove.size ): - raise ValueError("Array sizes are not equal") + raise ValueError("Edge arrays must have the same size") num_edges = edges_parent.size - nodes_children = np.zeros(num_nodes, dtype=np.int32) + nodes_children = np.zeros(nodes_mask.size, dtype=np.int32) position_insert = edges_left[indexes_insert] position_remove = edges_right[indexes_remove] diff --git a/tests/oracle/variational.py b/tests/oracle/variational.py index 695e3f8a..cd25be73 100644 --- a/tests/oracle/variational.py +++ b/tests/oracle/variational.py @@ -1,10 +1,11 @@ """ Oracles for the expectation propagation passes (``lib/variational.c``). -The mutable state of the EP algorithm, the factors associated with each edge -likelihood, block likelihood and prior factor that together form the posterior, is a -tuple of eight arrays ``(node, edge, block, scale, edges_parent, edges_child, -blocks_left, blocks_right)``; the passes update the first four in place. +``ExpectationPropagation`` has the methods and properties of +``_tsdate.ExpectationPropagation``. The passes it calls take the factors associated +with each edge likelihood, block likelihood and prior factor, which together form +the posterior, as a tuple of eight arrays ``(node, edge, block, scale, edges_parent, +edges_child, blocks_left, blocks_right)``, and update the first four in place. """ import numpy as np @@ -505,3 +506,146 @@ def twin_projection(x, y): child_cavity, edge_likelihood, ) + + +class ExpectationPropagation: + """ + The state of expectation propagation, with the methods and properties of + ``_tsdate.ExpectationPropagation`` + """ + + def __init__( + self, + constraints, + edges_parent, + edges_child, + edges_likelihood, + blocks_left, + blocks_right, + blocks_likelihood, + ): + num_nodes = constraints.shape[0] + for ids in (edges_parent, edges_child, blocks_left, blocks_right): + if np.any((ids < 0) | (ids >= num_nodes)): + raise library_error(errors.NODE_OUT_OF_BOUNDS) + self.constraints = constraints.copy() + self.edges_parent = edges_parent.copy() + self.edges_child = edges_child.copy() + self.edges_likelihood = edges_likelihood.copy() + self.blocks_left = blocks_left.copy() + self.blocks_right = blocks_right.copy() + self.blocks_likelihood = blocks_likelihood.copy() + self.node = np.zeros((num_nodes, 2, 2)) + self.edge = np.zeros((edges_parent.size, 2, 2)) + self.block = np.zeros((blocks_left.size, 2, 2)) + self.scale = np.ones(num_nodes) + self._posterior = np.zeros((num_nodes, 2)) + self._edges_lognorm = np.zeros(edges_parent.size) + self._blocks_lognorm = np.zeros(blocks_left.size) + + def factors(self): + """ + The factors as the tuple of arrays that the passes take + """ + return ( + self.node, + self.edge, + self.block, + self.scale, + self.edges_parent, + self.edges_child, + self.blocks_left, + self.blocks_right, + ) + + def _edges(self, unphased): + if unphased: + return self.blocks_left, self.blocks_right, self.blocks_likelihood + return self.edges_parent, self.edges_child, self.edges_likelihood + + def propagate_likelihood(self, order, unphased, max_shape, min_step): + """ + Update the factors of the edges (blocks, if ``unphased``) in ``order`` + """ + parents, children, likelihood = self._edges(unphased) + lognorm = self._blocks_lognorm if unphased else self._edges_lognorm + if not (max_shape >= 1.0): + raise library_error(errors.INVALID_MAX_SHAPE) + if not (0.0 < min_step < 1.0): + raise library_error(errors.INVALID_MIN_STEP) + if np.any((order < 0) | (order >= parents.size)): + code = errors.BLOCK_OUT_OF_BOUNDS if unphased else errors.EDGE_OUT_OF_BOUNDS + raise library_error(code) + propagate_likelihood( + order, + parents, + children, + likelihood, + self.constraints, + self._posterior, + self.factors(), + lognorm, + max_shape, + min_step, + unphased, + ) + + def propagate_prior(self, free, max_shape, em_maxitt, em_reltol): + """ + Fit an exponential prior to the cavities of the ``free`` nodes + """ + if free.size != self.scale.size: + raise ValueError("free must have one entry per node") + propagate_prior( + free, self._posterior, self.factors(), max_shape, em_maxitt, em_reltol + ) + + def rescale_factors(self): + """ + Multiply the factors by the scales of their nodes + """ + rescale_factors(self.factors()) + + def assemble_factors(self): + """ + The posteriors implied by the factors + """ + return assemble_factors(self.factors()) + + def propagate_mutations(self, mutations_edge, unphased): + """ + The posteriors and phases of mutations above ``mutations_edge`` + """ + parents, children, likelihood = self._edges(unphased) + if np.any((mutations_edge < tskit.NULL) | (mutations_edge >= parents.size)): + code = errors.BLOCK_OUT_OF_BOUNDS if unphased else errors.EDGE_OUT_OF_BOUNDS + raise library_error(code) + num_mutations = mutations_edge.size + posterior = np.full((num_mutations, 2), np.nan) + phase = np.ones(num_mutations) + propagate_mutations( + np.arange(num_mutations, dtype=np.int32), + posterior, + phase, + mutations_edge, + parents, + children, + likelihood, + self.constraints, + self._posterior, + self.factors(), + unphased, + ) + return posterior, phase + + @property + def posterior(self): + return self._posterior.copy() + + @property + def edges_lognorm(self): + return self._edges_lognorm.copy() + + @property + def blocks_lognorm(self): + return self._blocks_lognorm.copy() diff --git a/tests/test_oracle_phasing.py b/tests/test_oracle_phasing.py index a1362ed3..3c224b4d 100644 --- a/tests/test_oracle_phasing.py +++ b/tests/test_oracle_phasing.py @@ -113,7 +113,9 @@ class TestBlockSingletons: @staticmethod def args(ts, unphased): unphased = np.array(unphased, dtype=bool) - return [unphased, ts.nodes_individual, *sweep_args(ts)] + args = sweep_args(ts) + del args[2] # the parents are not used + return [unphased, ts.nodes_individual, *args] @staticmethod def compare(args): @@ -138,7 +140,7 @@ def test_block_numbering(self, edges, mutations, unphased, expected): _, _, mutation_block = self.compare(self.args(ts, unphased)).value assert mutation_block.tolist() == expected - @pytest.mark.parametrize(("index", "size"), [(5, 3), (8, 3), (3, 1)]) + @pytest.mark.parametrize(("index", "size"), [(4, 3), (7, 3), (3, 1)]) def test_size_mismatch(self, index, size): ts = make_ts(NODES, STAR, [(1, 0), (2, 1)], 10.0, 2) args = shrink(self.args(ts, [1, 1]), index, size) diff --git a/tests/test_oracle_util.py b/tests/test_oracle_util.py index 6f5f64d9..3cf9358c 100644 --- a/tests/test_oracle_util.py +++ b/tests/test_oracle_util.py @@ -373,7 +373,6 @@ def compare(ts, mask): ts.indexes_edge_insertion_order, ts.indexes_edge_removal_order, ts.sequence_length, - ts.num_nodes, ) @staticmethod diff --git a/tests/test_oracle_variational.py b/tests/test_oracle_variational.py index 16623fcf..296f836b 100644 --- a/tests/test_oracle_variational.py +++ b/tests/test_oracle_variational.py @@ -1,57 +1,43 @@ """ -Equivalence of the expectation propagation functions of ``_tsdate`` with the oracle of +Equivalence of the expectation propagation of ``_tsdate`` with the oracle of ``tsdate.variational``: the EP helpers (``damp``, ``rescale``, -``rescale_factors``, ``constraints_are_consistent``) and the passes -``propagate_likelihood``, ``propagate_prior`` and ``propagate_mutations``, plus whole -sweeps. The EP state is a tuple of factor arrays, which the passes update in place. - -Inputs are snapshots of real EP state (``oracle.ep_state``) on the session fixtures, -with constraints edited to force branches, one-edge snapshots for each branch, and -tables of boundary and failure cases. Expected values always come from the oracle. -Where the C library reports a division by zero and the oracle does not raise, the C -function alone is checked. +``constraints_are_consistent``), and the methods of ``ExpectationPropagation``, +compared after the same sequence of passes from the same inputs. + +Inputs are those of EP on the session fixtures, with constraints and counts edited to +force branches, and tables of boundary and failure cases. Expected values always come +from the oracle. Where the C library reports a division by zero and the oracle does +not raise, the C function alone is checked. """ +import copy import re -from functools import partial import _tsdate import numpy as np import pytest import tskit from oracle import ep_state, variational -from oracle.ep_state import BRANCHES, SNAPSHOT_SPECS, tiny_snapshot from oracle.errors import ( INVALID_DAMPING, INVALID_MAX_SHAPE, INVALID_MIN_STEP, INVALID_NODE_POSTERIOR, NONPOSITIVE_PENALTY, - TWIN_EDGE_IN_PHASED_PASS, ZERO_DIVISION, ) -from oracle.helpers import ( - INF, - NAN, - assert_same_outcome, - assert_same_values, - compare, - f64, - kind, - log_uniform, - outcome, -) +from oracle.helpers import INF, NAN, compare, f64, kind, log_uniform from tsdate.variational import ( LOWER, - MIXPRIOR, - TINY, UPPER, + USE_BLOCK_LIKELIHOOD, + USE_EDGE_LIKELIHOOD, ExpectationPropagation, ) up = np.nextafter -TS_NAMES = list(SNAPSHOT_SPECS) +TS_NAMES = list(ep_state.SPECS) INCONSISTENT_MESSAGE = ( "Node age constraints are inconsistent, some descendants have" " lower bounds that exceed upper bounds of their ancestors." @@ -59,48 +45,42 @@ @pytest.fixture(scope="module") -def snaps(small_ts, small_ts_unphased, small_ts_historical): +def inputs(small_ts, small_ts_unphased, small_ts_historical): """ - Snapshots of EP state two iterations in, by fixture name + The inputs of EP, by fixture name """ tss = [small_ts, small_ts_unphased, small_ts_historical] - return {name: ep_state.make_snapshot(ts, name) for name, ts in zip(TS_NAMES, tss)} + return {name: ep_state.make_inputs(ts, name) for name, ts in zip(TS_NAMES, tss)} @pytest.fixture(scope="module") -def fresh(small_ts, small_ts_unphased, small_ts_historical): +def started(inputs): """ - Snapshots of the initial EP state, by fixture name + The oracle's EP two iterations in, by fixture name """ - tss = [small_ts, small_ts_unphased, small_ts_historical] - return { - name: ep_state.make_snapshot(ts, name, iterations=0) - for name, ts in zip(TS_NAMES, tss) - } + return {name: ep_state.start(variational, ins) for name, ins in inputs.items()} -@pytest.fixture(scope="module") -def scaled_snap(snaps): +def compare_runs(ins, step, started=None, iterations=2): """ - ``small_ts`` after a likelihood pass with a small cap, so that scales are not 1 + Run ``step`` on the ``ExpectationPropagation`` of ``_tsdate`` and of the oracle + after ``iterations`` (``started``, if given, is the oracle's), and compare what it + returns and the state after it """ - snap = snaps["small_ts"] - state = ep_state.run_likelihood(variational, snap, False, max_shape=3.0) - return snap.after_pass(state) + def run(ep): + result = step(ep) + return result, *ep_state.state(ep) -def compare_runs(runner, snap, *args, **kwargs): - """ - Run ``runner`` (an ``ep_state.run_*``) with ``_tsdate`` and with the oracle - """ - actual = partial(runner, _tsdate) - expected = partial(runner, variational) - return compare(actual, expected, snap, *args, **kwargs) + def actual(): + return run(ep_state.start(_tsdate, ins, iterations)) + def expected(): + if started is None: + return run(ep_state.start(variational, ins, iterations)) + return run(copy.deepcopy(started)) -def assert_run_kind(runner, snap, expected_kind, *args, **kwargs): - result = compare_runs(runner, snap, *args, **kwargs) - assert kind(result) == expected_kind + return compare(actual, expected) def unphased_name(ts_name): @@ -115,38 +95,41 @@ def raises_zero_division(): return pytest.raises(_tsdate.LibraryError, match=re.escape(message)) -class TestRescaleFactors: - @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_unphased"]) - @pytest.mark.parametrize("scale", ["seed0", "seed1", 1e-160, 1e100]) - def test_rescale_factors(self, snaps, ts_name, scale): - snap = snaps[ts_name].copy() - num_nodes = snap.node_posterior.shape[0] - if isinstance(scale, str): - rng = np.random.default_rng(int(scale[-1])) - scale = rng.uniform(0.5, 2.0, num_nodes) - snap.fields["scale"][:] = scale - actual = snap.factors() - expected = snap.factors() - _tsdate.rescale_factors(actual) - variational.rescale_factors(expected) - assert_same_values(actual[:4], expected[:4]) - - def test_rescale_factors_twice(self, snaps): - # the scale is reset to 1, so a second call changes nothing - snap = snaps["small_ts"] - factors = snap.factors() - _tsdate.rescale_factors(factors) - once = [f.copy() for f in factors[:3]] - _tsdate.rescale_factors(factors) - for before, after in zip(once, factors[:3]): - assert np.array_equal(before, after) +def likelihood_pass(order, unphased, max_shape=1000.0, min_step=0.1): + """ + A step that runs ``propagate_likelihood`` + """ - @pytest.mark.parametrize("ts_name", TS_NAMES) - def test_assemble_factors(self, snaps, scaled_snap, ts_name): - snap = scaled_snap if ts_name == "small_ts" else snaps[ts_name] - actual = _tsdate.assemble_factors(snap.factors()) - expected = variational.assemble_factors(snap.factors()) - assert_same_outcome(outcome(lambda: actual), outcome(lambda: expected)) + def step(ep): + ep.propagate_likelihood( + order=order, unphased=unphased, max_shape=max_shape, min_step=min_step + ) + + return step + + +def prior_pass(free, max_shape=1000.0, em_maxitt=10, em_reltol=1e-8): + """ + A step that runs ``propagate_prior`` + """ + + def step(ep): + ep.propagate_prior( + free=free, max_shape=max_shape, em_maxitt=em_maxitt, em_reltol=em_reltol + ) + + return step + + +def mutations_pass(mutations_edge, unphased): + """ + A step that runs ``propagate_mutations`` + """ + + def step(ep): + return ep.propagate_mutations(mutations_edge=mutations_edge, unphased=unphased) + + return step # fmt: off @@ -328,15 +311,15 @@ def test_table(self, constraints, parents, children, valid): @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_historical"]) @pytest.mark.parametrize("gap", ["equal", "one_ulp"]) - def test_real_edges(self, snaps, ts_name, gap): + def test_real_edges(self, inputs, ts_name, gap): # the lower bound of a child equals the upper bound of its parent, or exceeds it - snap = snaps[ts_name] - constraints = snap.node_constraints.copy() - p, c = snap.edge_parents[-1], snap.edge_children[-1] + ins = inputs[ts_name] + constraints = ins.node_constraints.copy() + p, c = ins.edge_parents[-1], ins.edge_children[-1] constraints[c, LOWER] = 500.0 constraints[p, UPPER] = 500.0 if gap == "equal" else up(500.0, 0.0) valid = gap == "equal" - self.check(constraints, snap.edge_parents, snap.edge_children, valid) + self.check(constraints, ins.edge_parents, ins.edge_children, valid) def test_production_raises(self): constraints = np.array([[10.0, 10.0], [0.0, 0.0]]) @@ -346,46 +329,32 @@ def test_production_raises(self): check(constraints, *edge) -class TestPropagateLikelihoodBranches: - """ - One edge (block) in each branch, with valid and failing projections - """ +class TestFactors: + @pytest.mark.parametrize("ts_name", TS_NAMES) + def test_rescale_factors(self, inputs, started, ts_name): + # a pass with a small cap leaves scales that are not one + ins = inputs[ts_name] + unphased = unphased_name(ts_name) + order = ins.block_order if unphased else ins.edge_order - CASES = { - "valid": dict(), - "damped": dict(cavity=ep_state.DAMPED_CAVITY, message=ep_state.DAMPED_MESSAGE), - # NOTE: current behaviour, possibly a bug: a failed projection - # is not reported; the posterior becomes the cavity and `lognorm` is NaN. - "projection_fails": dict(likelihood=(1.0, 1e300)), - } + def step(ep): + likelihood_pass(order, unphased, max_shape=3.0)(ep) + ep.rescale_factors() + return ep.assemble_factors() - @pytest.mark.parametrize("case", CASES) - @pytest.mark.parametrize("branch", [b for b in BRANCHES if "both_fixed" not in b]) - def test_single_edge(self, branch, case): - snap = tiny_snapshot(branch, **self.CASES[case]) - kwargs = dict(max_shape=1e300) # no posterior rescaling - if "sideways" in branch and case == "projection_fails": - # `sideways_moments` divides by zero for an astronomically large mutation - # target: C reports it where the oracle returns NaN and skips. - with raises_zero_division(): - ep_state.run_likelihood(_tsdate, snap, snap.unphased, **kwargs) - else: - compare_runs(ep_state.run_likelihood, snap, snap.unphased, **kwargs) + compare_runs(ins, step, started[ts_name]) - def test_twin_edge_in_phased_pass(self): - # p == c is only valid for blocks; `twin_projection` checks `unphased`. - # Direct call only: edges never have p == c in a tree sequence. - snap = tiny_snapshot("twin") - result = compare_runs(ep_state.run_likelihood, snap, False) - assert kind(result) == TWIN_EDGE_IN_PHASED_PASS + @pytest.mark.parametrize("ts_name", TS_NAMES) + def test_assemble_factors(self, inputs, started, ts_name): + compare_runs(inputs[ts_name], lambda ep: ep.assemble_factors(), started[ts_name]) class TestPropagateLikelihood: SUBSET = slice(0, 400) # an initial portion of the pass keeps the oracle quick @staticmethod - def order(snap, unphased, subset=None): - order = snap.block_order if unphased else snap.edge_order + def order(ins, unphased, subset=None): + order = ins.block_order if unphased else ins.edge_order return order if subset is None else order[subset] @pytest.mark.parametrize( @@ -398,41 +367,35 @@ def order(snap, unphased, subset=None): ("small_ts_unphased", 10.0, 0.5), ], ) - def test_natural(self, snaps, ts_name, max_shape, min_step): - snap = snaps[ts_name] + def test_natural(self, inputs, started, ts_name, max_shape, min_step): + ins = inputs[ts_name] unphased = unphased_name(ts_name) - counts = snap.branch_counts(unphased) + counts = ins.branch_counts(unphased) assert counts["both_free"] > 0 assert counts["both_fixed"] == counts["fixed_parent"] == 0 - compare_runs( - ep_state.run_likelihood, - snap, - unphased, - max_shape=max_shape, - min_step=min_step, - ) + step = likelihood_pass(self.order(ins, unphased), unphased, max_shape, min_step) + compare_runs(ins, step, started[ts_name]) - @pytest.mark.parametrize( - "ts_name", ["small_ts", "small_ts_unphased", "small_ts_historical"] - ) - def test_forced_fixed_nodes(self, snaps, ts_name): + @pytest.mark.parametrize("ts_name", TS_NAMES) + def test_forced_fixed_nodes(self, inputs, ts_name): # every branch: both nodes fixed (skipped), one fixed, both free unphased = unphased_name(ts_name) - snap = ep_state.fixed_internal_snapshot(snaps[ts_name], unphased) - counts = snap.branch_counts(unphased) + ins = ep_state.fixed_internal(inputs[ts_name], unphased) + counts = ins.branch_counts(unphased) assert all(v > 0 for k, v in counts.items() if k != "twin" or unphased) - compare_runs(ep_state.run_likelihood, snap, unphased) + step = likelihood_pass(self.order(ins, unphased), unphased) + compare_runs(ins, step, iterations=1) @pytest.mark.parametrize("kind_of_order", ["empty", "partial_and_repeated"]) - def test_order(self, snaps, kind_of_order): + def test_order(self, inputs, started, kind_of_order): # the order array is arbitrary: empty, or any subset with repeats - snap = snaps["small_ts"] + ins = inputs["small_ts"] if kind_of_order == "empty": order = np.zeros(0, dtype=np.int32) else: - order = snap.edge_order[100:140] + order = ins.edge_order[100:140] order = np.concatenate((order, order[::-1], order[:5])).astype(np.int32) - compare_runs(ep_state.run_likelihood, snap, False, order=order) + compare_runs(ins, likelihood_pass(order, False), started["small_ts"]) @pytest.mark.parametrize( "max_shape", @@ -442,17 +405,12 @@ def test_order(self, snaps, kind_of_order): ids=lambda v: f"max_shape={v:g}", ) @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_unphased"]) - def test_max_shape(self, snaps, ts_name, max_shape): - snap = snaps[ts_name] + def test_max_shape(self, inputs, started, ts_name, max_shape): + ins = inputs[ts_name] unphased = unphased_name(ts_name) - order = self.order(snap, unphased, self.SUBSET) - compare_runs( - ep_state.run_likelihood, - snap, - unphased, - max_shape=max_shape, - order=order, - ) + order = self.order(ins, unphased, self.SUBSET) + step = likelihood_pass(order, unphased, max_shape=max_shape) + compare_runs(ins, step, started[ts_name]) @pytest.mark.parametrize( "min_step", @@ -460,35 +418,23 @@ def test_max_shape(self, snaps, ts_name, max_shape): ids=lambda v: f"min_step={v:g}", ) @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_unphased"]) - def test_min_step(self, snaps, ts_name, min_step): - snap = snaps[ts_name] + def test_min_step(self, inputs, started, ts_name, min_step): + ins = inputs[ts_name] unphased = unphased_name(ts_name) - order = self.order(snap, unphased, self.SUBSET) + order = self.order(ins, unphased, self.SUBSET) # a small cap makes passes difficult, so that damping is exercised - compare_runs( - ep_state.run_likelihood, - snap, - unphased, - min_step=min_step, - max_shape=3.0, - order=order, - ) + step = likelihood_pass(order, unphased, max_shape=3.0, min_step=min_step) + compare_runs(ins, step, started[ts_name]) @pytest.mark.parametrize("multiplier", [1e12, 1e300], ids=lambda v: f"y*{v:g}") - def test_extreme_counts(self, snaps, multiplier): + def test_extreme_counts(self, inputs, multiplier): # 1e12: projection failures are skipped (NaN lognorm). 1e300: a posterior # becomes NaN and the next `damp` fails its check `0 < x[0] + 1`, # reachable from real data (~1e300 mutations on an edge). - snap = snaps["small_ts"] - likelihoods = snap.edge_likelihoods * [multiplier, 1.0] - order = snap.edge_order[: self.SUBSET.stop] - compare_runs( - ep_state.run_likelihood, - snap, - False, - order=order, - likelihoods=likelihoods, - ) + ins = inputs["small_ts"].copy() + ins.edge_likelihoods = ins.edge_likelihoods * [multiplier, 1.0] + order = ins.edge_order[: self.SUBSET.stop] + compare_runs(ins, likelihood_pass(order, False), iterations=0) @pytest.mark.parametrize( ("kwargs", "expected"), @@ -505,143 +451,39 @@ def test_extreme_counts(self, snaps, multiplier): pytest.param(dict(min_step=NAN), INVALID_MIN_STEP, id="min_step_nan"), ], ) - def test_invalid_parameters(self, snaps, kwargs, expected): + def test_invalid_parameters(self, inputs, kwargs, expected): # reachable from user input (`max_shape`, `min_step` of `iterate`/`infer`): # parameter errors in the C library, not internal invariants - snap = snaps["small_ts"] - order = snap.edge_order[:10] - assert_run_kind( - ep_state.run_likelihood, - snap, - expected, - False, - order=order, - **kwargs, - ) - - @pytest.mark.parametrize( - "change", - ["children", "likelihoods", "constraints", "factors_larger"], - ) - def test_shape_mismatches(self, snaps, change): - # direct calls only: these are checked while parsing arguments in C - snap = snaps["small_ts"] - args, lognorm = ep_state.likelihood_args(snap, False) - order, parents, children, likelihoods = args - constraints = snap.node_constraints - if change == "children": - children = children[:-1] - elif change == "likelihoods": - likelihoods = likelihoods[:-1] - elif change == "constraints": - constraints = constraints[:-1] - else: # factors have more edges than the arrays - parents, children = parents[:-1], children[:-1] - likelihoods = likelihoods[:-1] - - def call(module): - module.propagate_likelihood( - order, - parents, - children, - likelihoods, - constraints, - snap.node_posterior.copy(), - snap.factors(), - lognorm.copy(), - 1000.0, - 0.1, - ep_state.USE_EDGE_LIKELIHOOD, - ) - - result = compare( - lambda: call(_tsdate), - lambda: call(variational), - ) - assert kind(result) is ValueError - - -class TestPropagateLikelihoodTinyScale: - """ - `propagate_likelihood` calls `rescale_factors` (mid-pass) whenever the scale of - either node of the next edge is below `TINY` (strict), even if the edge is skipped - because both nodes are fixed. - """ - - @staticmethod - def shrunk(snap, role, scale): - """ - Equivalent state with the scale of one node tiny, first used mid-pass - """ - snap = snap.copy() - nodes = snap.edge_parents if role == "parent" else snap.edge_children - first = {} - for pos, i in enumerate(snap.edge_order): - first.setdefault(nodes[i], pos) - target = len(snap.edge_order) // 3 - node = min(first, key=lambda n: abs(first[n] - target)) - snap.unscale([node], scale) - return snap - - @pytest.mark.parametrize( - ("role", "scale"), - [ - ("parent", TINY / 1e6), - ("child", TINY / 1e6), - ("child", up(TINY, 0.0)), - ("child", TINY), - ("parent", 2 * TINY), - ], - ids=[ - "parent-below", - "child-below", - "child-just-below", - "child-at", - "parent-above", - ], - ) - def test_threshold(self, snaps, role, scale): - snap = self.shrunk(snaps["small_ts"], role, scale) - order = snap.edge_order[: len(snap.edge_order) // 2] - compare_runs(ep_state.run_likelihood, snap, False, order=order) - - def test_skipped_fixed_edge(self, snaps): - # a fixed sample with a tiny scale whose edge is skipped (both nodes fixed) - base = snaps["small_ts_historical"].copy() - sample = np.flatnonzero(base.fixed)[0] - edge = np.flatnonzero(base.edge_children == sample)[0] - base.fix_nodes([base.edge_parents[edge]]) - assert base.branch_counts(False)["both_fixed"] > 0 - base.unscale([sample], TINY / 1e6) - compare_runs(ep_state.run_likelihood, base, False) + ins = inputs["small_ts"] + step = likelihood_pass(ins.edge_order[:10], False, **kwargs) + result = compare_runs(ins, step, iterations=0) + assert kind(result) == expected class TestPropagatePrior: @pytest.mark.parametrize("ts_name", TS_NAMES) - def test_natural(self, snaps, ts_name): - snap = snaps[ts_name] - assert snap.unconstrained_roots.any() - compare_runs(ep_state.run_prior, snap, snap.unconstrained_roots) + def test_natural(self, inputs, started, ts_name): + ins = inputs[ts_name] + assert ins.unconstrained_roots.any() + compare_runs(ins, prior_pass(ins.unconstrained_roots), started[ts_name]) @pytest.mark.parametrize( - ("scaled", "em_maxitt", "em_reltol"), + ("em_maxitt", "em_reltol"), # `em_maxitt`: no iteration (-1), one (0), the cap binding (3), convergence # binding (1000); `em_reltol`: run to the cap (0), tight, loose, NaN (no # iteration) - [(False, m, r) for m in [-1, 0, 3, 1000] for r in [0.0, 1e-8, 0.5, NAN]] - + [(True, 0, 1e-8), (True, 3, 1e-8), (True, 1000, 0.5)], - ids=lambda v: f"{v}" if isinstance(v, bool) else f"{v:g}", + [(m, r) for m in [-1, 0, 3, 1000] for r in [0.0, 1e-8, 0.5, NAN]], + ids=lambda v: f"{v:g}", ) - def test_em(self, snaps, scaled_snap, scaled, em_maxitt, em_reltol): - snap = scaled_snap if scaled else snaps["small_ts"] - compare_runs( - ep_state.run_prior, - snap, - snap.unconstrained_roots, + def test_em(self, inputs, started, em_maxitt, em_reltol): + ins = inputs["small_ts"] + step = prior_pass( + ins.unconstrained_roots, em_maxitt=em_maxitt, em_reltol=em_reltol, max_shape=1e300, ) + compare_runs(ins, step, started["small_ts"]) @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_historical"]) @pytest.mark.parametrize( @@ -651,14 +493,10 @@ def test_em(self, snaps, scaled_snap, scaled, em_maxitt, em_reltol): [1.0, 1.5, 1e300], ids=lambda v: f"max_shape={v:g}", ) - def test_max_shape(self, snaps, ts_name, max_shape): - snap = snaps[ts_name] - compare_runs( - ep_state.run_prior, - snap, - snap.unconstrained_roots, - max_shape=max_shape, - ) + def test_max_shape(self, inputs, started, ts_name, max_shape): + ins = inputs[ts_name] + step = prior_pass(ins.unconstrained_roots, max_shape=max_shape) + compare_runs(ins, step, started[ts_name]) @pytest.mark.parametrize( ("ts_name", "free", "kwargs"), @@ -672,85 +510,58 @@ def test_max_shape(self, snaps, ts_name, max_shape): ], ids=["single_root", "internal", "none", "none_odd_arguments"], ) - def test_free_nodes(self, snaps, ts_name, free, kwargs): - snap = snaps[ts_name] - mask = np.zeros(snap.node_posterior.shape[0], dtype=bool) + def test_free_nodes(self, inputs, started, ts_name, free, kwargs): + ins = inputs[ts_name] + mask = np.zeros(ins.node_constraints.shape[0], dtype=bool) if free == "single_root": - mask[np.flatnonzero(snap.unconstrained_roots)[0]] = True + mask[np.flatnonzero(ins.unconstrained_roots)[0]] = True elif free == "internal": - mask = ~snap.fixed & ~snap.roots | snap.unconstrained_roots - compare_runs(ep_state.run_prior, snap, mask, **kwargs) - - @staticmethod - def zero_posterior(snap): - snap = snap.copy() - snap.node_posterior[:] = 0.0 - snap.fields["node"][:] = 0.0 - return snap + mask = ~ins.fixed & ~ins.roots | ins.unconstrained_roots + compare_runs(ins, prior_pass(mask, **kwargs), started[ts_name]) - @staticmethod - def negative_cavity_rate(snap): - snap = snap.copy() - free = snap.unconstrained_roots - snap.fields["node"][free, MIXPRIOR, 1] = snap.node_posterior[free, 1] + 1.0 - return snap - - ERRORS = { - # `penalty > 0` fails when the mean of shape / rate is infinite or negative: - # free nodes whose cavity has zero rate (fixed leaves, or a root where every - # update was skipped) or negative rate - "all_nodes": NONPOSITIVE_PENALTY, - "leaves": NONPOSITIVE_PENALTY, - "zero_posterior": NONPOSITIVE_PENALTY, - "negative_cavity_rate": NONPOSITIVE_PENALTY, - # reachable from user input - "max_shape_below_one": INVALID_MAX_SHAPE, - "max_shape_zero": INVALID_MAX_SHAPE, - "max_shape_nan": INVALID_MAX_SHAPE, - # direct calls only - "free_too_short": ValueError, - "free_too_long": ValueError, - } - - @pytest.mark.parametrize("case", ERRORS) - def test_errors(self, snaps, case): - snap = snaps["small_ts"] - free = snap.unconstrained_roots + @pytest.mark.parametrize( + ("case", "expected"), + [ + # `penalty > 0` fails when the mean of shape / rate is infinite or + # negative: free nodes whose cavity has zero rate (fixed leaves) + ("all_nodes", NONPOSITIVE_PENALTY), + ("leaves", NONPOSITIVE_PENALTY), + # reachable from user input + ("max_shape_below_one", INVALID_MAX_SHAPE), + ("max_shape_zero", INVALID_MAX_SHAPE), + ("max_shape_nan", INVALID_MAX_SHAPE), + ], + ) + def test_errors(self, inputs, started, case, expected): + ins = inputs["small_ts"] + free = ins.unconstrained_roots kwargs = {} if case == "all_nodes": free = np.ones_like(free) elif case == "leaves": - free = snap.leaves - elif case == "zero_posterior": - snap = self.zero_posterior(snap) - elif case == "negative_cavity_rate": - snap = self.negative_cavity_rate(snap) - elif case.startswith("max_shape"): + free = ins.leaves + else: kwargs["max_shape"] = { "below_one": up(1.0, 0.0), "zero": 0.0, "nan": NAN, }[case[len("max_shape_") :]] - elif case == "free_too_short": - free = free[:-1] - else: - free = np.append(free, True) - assert_run_kind(ep_state.run_prior, snap, self.ERRORS[case], free, **kwargs) + result = compare_runs(ins, prior_pass(free, **kwargs), started["small_ts"]) + assert kind(result) == expected - def test_penalty_error_reachable_from_ep(self, fresh): + def test_penalty_error_reachable_from_ep(self, inputs): # NOTE: current behaviour, possibly a bug: a likelihood pass in # which every update is skipped (a huge mutational target) leaves the roots # with a zero posterior, so that `iterate(regularise=True)` fails the # `penalty > 0` check (an error, not NaN). - base = fresh["small_ts"].copy() - base.edge_likelihoods = base.edge_likelihoods * [1.0, 1e300] + ins = inputs["small_ts"].copy() + ins.edge_likelihoods = ins.edge_likelihoods * [1.0, 1e300] - def run(module): - state = ep_state.run_likelihood(module, base, False) - step = base.after_pass(state) - return ep_state.run_prior(module, step, step.unconstrained_roots) + def step(ep): + likelihood_pass(ins.edge_order, False)(ep) + prior_pass(ins.unconstrained_roots)(ep) - result = compare(lambda: run(_tsdate), lambda: run(variational)) + result = compare_runs(ins, step, iterations=0) assert kind(result) == NONPOSITIVE_PENALTY @@ -764,8 +575,10 @@ class TestPropagateMutations: ("small_ts_unphased", True), ], ) - def test_natural(self, snaps, ts_name, unphased): - compare_runs(ep_state.run_mutations, snaps[ts_name], unphased) + def test_natural(self, inputs, started, ts_name, unphased): + ins = inputs[ts_name] + step = mutations_pass(ins.mutations_edge(unphased), unphased) + compare_runs(ins, step, started[ts_name]) @pytest.mark.parametrize( ("ts_name", "unphased"), @@ -775,85 +588,25 @@ def test_natural(self, snaps, ts_name, unphased): ("small_ts_unphased", True), ], ) - def test_forced_fixed_nodes(self, snaps, ts_name, unphased): + def test_forced_fixed_nodes(self, inputs, ts_name, unphased): # mutations on edges of every kind: both nodes fixed, one of the two fixed - snap = ep_state.fixed_internal_snapshot(snaps[ts_name], unphased) - counts = snap.branch_counts(unphased) + ins = ep_state.fixed_internal(inputs[ts_name], unphased) + counts = ins.branch_counts(unphased) assert all(counts[k] > 0 for k in ("both_fixed", "fixed_parent", "fixed_child")) - compare_runs(ep_state.run_mutations, snap, unphased) - - @pytest.mark.parametrize("case", ["null_edges", "order_subset_and_repeats"]) - def test_mutation_selection(self, snaps, case): - # mutations above the root have edge NULL and are skipped; the order is any - # subset of the mutations, with repeats - snap = snaps["small_ts"] - kwargs = {} + step = mutations_pass(ins.mutations_edge(unphased), unphased) + compare_runs(ins, step, iterations=1) + + @pytest.mark.parametrize("case", ["null_edges", "subset_and_repeats"]) + def test_mutation_selection(self, inputs, started, case): + # mutations above the root have edge NULL and get NaN posteriors; the + # mutations are any edges, with repeats + ins = inputs["small_ts"] + edges = ins.mutations_edge(False).copy() if case == "null_edges": - edges = snap.mutation_edges.copy() edges[::7] = tskit.NULL - kwargs["edges"] = edges - else: - kwargs["order"] = np.array([5, 3, 3, 100, 5], dtype=np.int32) - compare_runs(ep_state.run_mutations, snap, False, **kwargs) - - @pytest.mark.parametrize( - ("branch", "case"), - [ - (b, c) - for b in BRANCHES - for c in ["valid", "projection_fails"] - # fixed edges do not use the likelihood - if not (c == "projection_fails" and "both_fixed" in b) - ], - ) - def test_single_edge(self, branch, case): - # NOTE: current behaviour, possibly a bug: a mutation whose - # projection fails gets NaN posterior and phase, silently left in the result. - fails = case == "projection_fails" - likelihood = (1.0, 1e300) if fails else (3.0, 0.1) - snap = tiny_snapshot(branch, likelihood=likelihood) - if fails and "sideways" in branch: - # as in propagate_likelihood: C reports a division by zero in - # `*_sideways_moments` - with raises_zero_division(): - ep_state.run_mutations(_tsdate, snap, snap.unphased) else: - compare_runs(ep_state.run_mutations, snap, snap.unphased) - - def test_twin_in_phased_pass(self): - # unlike propagate_likelihood, there is no `unphased` check for p == c; the - # twin projection is used as is (direct call only: edges never have p == c) - snap = tiny_snapshot("twin") - snap.mutation_blocks[:] = tskit.NULL - assert_run_kind(ep_state.run_mutations, snap, "finite", False) - - @pytest.mark.parametrize( - ("ages", "expected_kind"), - [ - # the edge projection is uniform on (child, parent): variance 0 fails; - # reachable with two samples of the same time, one the - # ancestor of the other - pytest.param([[5, 5], [5, 5]], "nan", id="equal_ages"), - pytest.param([[5, 5], [up(5.0, 6.0)] * 2], "finite", id="nextafter_ages"), - # NOTE: current behaviour, possibly a bug: ages in the wrong - # order are not detected (the moments are symmetric) - pytest.param([[10, 10], [0, 0]], "finite", id="inverted_ages"), - ], - ) - def test_fixed_edge_ages(self, ages, expected_kind): - snap = tiny_snapshot("both_fixed") - snap.node_constraints[:] = ages - assert_run_kind(ep_state.run_mutations, snap, expected_kind, False) - - @pytest.mark.parametrize("change", ["edges_size", "posterior_size"]) - def test_shape_mismatches(self, snaps, change): - # direct calls only: checked while parsing arguments in C - snap = snaps["small_ts"] - if change == "edges_size": - kwargs = dict(edges=snap.mutation_edges[:-1]) - else: - kwargs = dict(posterior=snap.node_posterior[:-1]) - assert_run_kind(ep_state.run_mutations, snap, ValueError, False, **kwargs) + edges = edges[[5, 3, 3, 100, 5]] + compare_runs(ins, mutations_pass(edges, False), started["small_ts"]) class TestMultiSweep: @@ -871,15 +624,30 @@ class TestMultiSweep: ), } + @staticmethod + def run(module, ins, sweeps, kwargs): + ep = module.ExpectationPropagation(**ins.kwargs()) + states = [] + for _ in range(sweeps): + ep_state.iterate(ep, ins, **kwargs) + states.append(ep_state.state(ep)) + mutations = [ + ep.propagate_mutations( + mutations_edge=ins.mutations_edge(unphased), unphased=unphased + ) + for unphased in (USE_BLOCK_LIKELIHOOD, USE_EDGE_LIKELIHOOD) + ] + return states, mutations + @pytest.mark.parametrize("case", CASES) - def test_sweeps(self, fresh, case): + def test_sweeps(self, inputs, case): name, kwargs = self.CASES[case] - snap = fresh[name] - sweeps = 4 - actual = ep_state.run_sweeps(_tsdate, snap, sweeps, **kwargs) - expected = ep_state.run_sweeps(variational, snap, sweeps, **kwargs) + ins = inputs[name] + actual = self.run(_tsdate, ins, 4, kwargs) + expected = self.run(variational, ins, 4, kwargs) for a, e in zip(actual[0], expected[0]): for x, y in zip(a, e): # node posterior, edge and block lognorm np.testing.assert_array_equal(x, y) - for x, y in zip(actual[1], expected[1]): # mutation posterior, phase - np.testing.assert_array_equal(x, y) + for a, e in zip(actual[1], expected[1]): # mutation posterior, phase + for x, y in zip(a, e): + np.testing.assert_array_equal(x, y) diff --git a/tests/test_python_c.py b/tests/test_python_c.py index 00cfa462..4d78b9b2 100644 --- a/tests/test_python_c.py +++ b/tests/test_python_c.py @@ -2,6 +2,8 @@ Tests for the low-level _tsdate C module. """ +import re + import _tsdate import msprime import numpy as np @@ -10,9 +12,21 @@ ERR_GENERIC = -1 ERR_NO_MEMORY = -2 ERR_BAD_PARAM = -3 +ERR_ZERO_DIVISION = -4 +ERR_INVALID_MAX_SHAPE = -30 +ERR_INVALID_MIN_STEP = -31 +ERR_TWIN_EDGE_IN_PHASED_PASS = -34 +ERR_NONPOSITIVE_PENALTY = -35 ALL_ERRORS = [ERR_GENERIC, ERR_NO_MEMORY, ERR_BAD_PARAM] +def raises_library_error(code): + """ + ``pytest.raises`` for the library error ``code`` + """ + return pytest.raises(_tsdate.LibraryError, match=re.escape(_tsdate.strerror(code))) + + class TestModule: def test_name(self): assert _tsdate.__name__ == "_tsdate" @@ -140,7 +154,7 @@ def call_sweep(name, ts, a): ts.nodes_individual, a["mutations_node"], position, - *edges, + *edges[1:], *indexes, ts.sequence_length, ) @@ -152,7 +166,6 @@ def call_sweep(name, ts, a): a["edges_right"], *indexes, ts.sequence_length, - ts.num_nodes, ) assert name == "relabel_mutations_node" return _tsdate.relabel_mutations_node( @@ -250,7 +263,6 @@ def test_individual_out_of_bounds(self, ts): nodes_individual, ts.mutations_node, ts.sites_position[ts.mutations_site], - ts.edges_parent, ts.edges_child, ts.edges_left, ts.edges_right, @@ -355,3 +367,261 @@ def test_piecewise_scale_posterior(self): 0.5, 1000.0, ) + + +def ep_arrays(**replace): + """ + Arguments of ``ExpectationPropagation``: two samples (nodes 0 and 1) below a free + root (node 2), and a block whose nodes are both the root + """ + args = { + "constraints": np.array([[0.0, 0.0], [0.0, 0.0], [0.0, np.inf]]), + "edges_parent": np.array([2, 2], dtype=np.int32), + "edges_child": np.array([0, 1], dtype=np.int32), + "edges_likelihood": np.array([[1.0, 1.0], [2.0, 1.0]]), + "blocks_left": np.array([2], dtype=np.int32), + "blocks_right": np.array([2], dtype=np.int32), + "blocks_likelihood": np.array([[1.0, 1.0]]), + } + args.update(replace) + return args + + +def new_ep(**replace): + """ + An ``ExpectationPropagation`` with the arguments of ``ep_arrays`` + """ + return _tsdate.ExpectationPropagation(**ep_arrays(**replace)) + + +EDGES = np.array([0, 1], dtype=np.int32) +BLOCKS = np.array([0], dtype=np.int32) + + +class TestExpectationPropagationInit: + def test_initial_state(self): + ep = new_ep() + assert ep.posterior.tolist() == [[0.0, 0.0]] * 3 + assert ep.edges_lognorm.tolist() == [0.0, 0.0] + assert ep.blocks_lognorm.tolist() == [0.0] + + def test_positional_arguments(self): + ep = _tsdate.ExpectationPropagation(*ep_arrays().values()) + assert ep.posterior.shape == (3, 2) + + def test_no_blocks(self): + empty = np.zeros(0, dtype=np.int32) + ep = new_ep( + blocks_left=empty, blocks_right=empty, blocks_likelihood=np.zeros((0, 2)) + ) + assert ep.blocks_lognorm.size == 0 + + @pytest.mark.parametrize("num_args", [0, 6, 8]) + def test_wrong_number_of_arguments(self, num_args): + args = list(ep_arrays().values()) + [None] + with pytest.raises(TypeError): + _tsdate.ExpectationPropagation(*args[:num_args]) + + @pytest.mark.parametrize("name", list(ep_arrays())) + def test_bad_dtype(self, name): + value = ep_arrays()[name] + bad = value.astype(np.float64 if value.dtype == np.int32 else np.complex128) + with pytest.raises(TypeError): + new_ep(**{name: bad}) + + @pytest.mark.parametrize("name", list(ep_arrays())) + def test_bad_dimension(self, name): + value = ep_arrays()[name] + bad = value.reshape(-1) if value.ndim == 2 else value.reshape(1, -1) + with pytest.raises(ValueError): + new_ep(**{name: bad}) + + @pytest.mark.parametrize( + "name", ["constraints", "edges_likelihood", "blocks_likelihood"] + ) + def test_three_columns(self, name): + value = ep_arrays()[name] + bad = np.hstack((value, value[:, :1])) + with pytest.raises(ValueError, match="two columns"): + new_ep(**{name: bad}) + + @pytest.mark.parametrize( + ("name", "match"), + [ + ("edges_child", "Edge arrays"), + ("edges_likelihood", "Edge arrays"), + ("blocks_right", "Block arrays"), + ("blocks_likelihood", "Block arrays"), + ], + ) + def test_mismatched_lengths(self, name, match): + bad = ep_arrays()[name][:-1] + with pytest.raises(ValueError, match=match): + new_ep(**{name: bad}) + + @pytest.mark.parametrize( + "name", ["edges_parent", "edges_child", "blocks_left", "blocks_right"] + ) + @pytest.mark.parametrize("value", [-1, 3]) + def test_node_out_of_bounds(self, name, value): + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + new_ep(**{name: bad_ids(ep_arrays()[name], value)}) + + def test_failed_init_leaves_no_state(self): + ep = new_ep() + with pytest.raises(_tsdate.LibraryError): + ep.__init__(**ep_arrays(edges_parent=np.array([2, 9], dtype=np.int32))) + with pytest.raises(SystemError, match="not initialised"): + ep.rescale_factors() + + def test_uninitialised(self): + ep = _tsdate.ExpectationPropagation.__new__(_tsdate.ExpectationPropagation) + for method in (ep.rescale_factors, ep.assemble_factors): + with pytest.raises(SystemError, match="not initialised"): + method() + for name in ("posterior", "edges_lognorm", "blocks_lognorm"): + with pytest.raises(SystemError, match="not initialised"): + getattr(ep, name) + with pytest.raises(SystemError, match="not initialised"): + ep.propagate_likelihood(EDGES, False, 1000.0, 0.1) + with pytest.raises(SystemError, match="not initialised"): + ep.propagate_prior(np.ones(3, dtype=bool), 1000.0, 10, 1e-8) + with pytest.raises(SystemError, match="not initialised"): + ep.propagate_mutations(EDGES, False) + + def test_properties_are_read_only_copies(self): + ep = new_ep() + posterior = ep.posterior + posterior[:] = 1.0 + assert ep.posterior.tolist() == [[0.0, 0.0]] * 3 + with pytest.raises(AttributeError): + ep.posterior = posterior + + def test_inputs_are_copied(self): + arrays = ep_arrays() + ep = _tsdate.ExpectationPropagation(**arrays) + arrays["edges_parent"][:] = 99 + ep.propagate_likelihood(EDGES, False, 1000.0, 0.1) + assert np.all(np.isfinite(ep.posterior[2])) + + +class TestExpectationPropagationMethods: + def test_iteration(self): + ep = new_ep() + ep.propagate_likelihood( + order=EDGES, unphased=False, max_shape=1000.0, min_step=0.1 + ) + ep.propagate_likelihood( + order=BLOCKS, unphased=True, max_shape=1000.0, min_step=0.1 + ) + ep.rescale_factors() + assert np.all(ep.posterior[2] > 0) + assert np.all(np.isfinite(ep.edges_lognorm)) + np.testing.assert_allclose(ep.assemble_factors(), ep.posterior) + + def test_propagate_prior(self): + ep = new_ep() + ep.propagate_likelihood(EDGES, False, 1000.0, 0.1) + free = np.array([False, False, True]) + ep.propagate_prior(free=free, max_shape=1000.0, em_maxitt=10, em_reltol=1e-8) + assert np.all(ep.posterior[2] > 0) + + def test_propagate_mutations(self): + ep = new_ep() + ep.propagate_likelihood(EDGES, False, 1000.0, 0.1) + edges = np.array([0, -1, 1], dtype=np.int32) + posterior, phase = ep.propagate_mutations(mutations_edge=edges, unphased=False) + assert posterior.shape == (3, 2) + assert np.all(np.isnan(posterior[1])) + assert phase.tolist()[1] == 1.0 + assert np.all(np.isfinite(posterior[[0, 2]])) + + @pytest.mark.parametrize( + "method", ["propagate_likelihood", "propagate_prior", "propagate_mutations"] + ) + def test_wrong_number_of_arguments(self, method): + with pytest.raises(TypeError): + getattr(new_ep(), method)(EDGES) + + @pytest.mark.parametrize("method", ["rescale_factors", "assemble_factors"]) + def test_no_arguments(self, method): + with pytest.raises(TypeError): + getattr(new_ep(), method)(1) + + def test_bad_arrays(self): + ep = new_ep() + with pytest.raises(TypeError): + ep.propagate_likelihood(EDGES.astype(np.float64), False, 1000.0, 0.1) + with pytest.raises(ValueError): + ep.propagate_likelihood(EDGES.reshape(1, -1), False, 1000.0, 0.1) + with pytest.raises(TypeError): + ep.propagate_prior(np.ones(3), 1000.0, 10, 1e-8) + with pytest.raises(ValueError, match="one entry per node"): + ep.propagate_prior(np.ones(2, dtype=bool), 1000.0, 10, 1e-8) + with pytest.raises(TypeError): + ep.propagate_mutations(EDGES.astype(np.float64), False) + with pytest.raises(ValueError): + ep.propagate_mutations(EDGES.reshape(1, -1), False) + + @pytest.mark.parametrize( + ("order", "unphased", "match"), + [ + ([2], False, "Edge id out of bounds"), + ([-1], False, "Edge id out of bounds"), + ([1], True, "Block id"), + ], + ) + def test_order_out_of_bounds(self, order, unphased, match): + order = np.array(order, dtype=np.int32) + with pytest.raises(_tsdate.LibraryError, match=match): + new_ep().propagate_likelihood(order, unphased, 1000.0, 0.1) + + @pytest.mark.parametrize( + ("edges", "unphased", "match"), + [ + ([2], False, "Edge id out of bounds"), + ([-2], False, "Edge id out of bounds"), + ([1], True, "Block id"), + ], + ) + def test_mutations_edge_out_of_bounds(self, edges, unphased, match): + edges = np.array(edges, dtype=np.int32) + with pytest.raises(_tsdate.LibraryError, match=match): + new_ep().propagate_mutations(edges, unphased) + + @pytest.mark.parametrize( + ("kwargs", "code"), + [ + (dict(max_shape=0.5), ERR_INVALID_MAX_SHAPE), + (dict(min_step=1.0), ERR_INVALID_MIN_STEP), + ], + ) + def test_likelihood_parameters(self, kwargs, code): + args = dict(order=EDGES, unphased=False, max_shape=1000.0, min_step=0.1) + args.update(kwargs) + with raises_library_error(code): + new_ep().propagate_likelihood(**args) + + def test_prior_max_shape(self): + with raises_library_error(ERR_INVALID_MAX_SHAPE): + new_ep().propagate_prior(np.ones(3, dtype=bool), 0.5, 10, 1e-8) + + def test_twin_edge_in_phased_pass(self): + ep = new_ep(edges_child=np.array([0, 2], dtype=np.int32)) + with raises_library_error(ERR_TWIN_EDGE_IN_PHASED_PASS): + ep.propagate_likelihood(np.array([1], dtype=np.int32), False, 1000.0, 0.1) + + def test_nonpositive_penalty(self): + # the fixed samples have cavities of zero rate + with raises_library_error(ERR_NONPOSITIVE_PENALTY): + new_ep().propagate_prior(np.ones(3, dtype=bool), 1000.0, 10, 1e-8) + + def test_zero_division(self): + # a huge mutational target, with a fixed node of an unphased block + ep = new_ep( + constraints=np.array([[0.0, 0.0], [5.0, 5.0], [0.0, np.inf]]), + blocks_right=np.array([1], dtype=np.int32), + blocks_likelihood=np.array([[1.0, 1e300]]), + ) + with raises_library_error(ERR_ZERO_DIVISION): + ep.propagate_likelihood(BLOCKS, True, 1000.0, 0.1) diff --git a/tests/test_python_c_tables.py b/tests/test_python_c_tables.py index d27698fb..34181778 100644 --- a/tests/test_python_c_tables.py +++ b/tests/test_python_c_tables.py @@ -22,7 +22,6 @@ def test_individual_with_three_edges(self): ts.nodes_individual, ts.mutations_node, ts.sites_position[ts.mutations_site], - ts.edges_parent, ts.edges_child, ts.edges_left, ts.edges_right, @@ -39,7 +38,6 @@ def test_wrong_dtype(self): ts.nodes_individual, ts.mutations_node.astype(np.int64), ts.sites_position[ts.mutations_site], - ts.edges_parent, ts.edges_child, ts.edges_left, ts.edges_right, @@ -71,18 +69,13 @@ def test_columns(self): with pytest.raises(ValueError, match="two columns"): self.call(np.ones((2, 3)), [0.5], [0], [[0, 1]]) - @pytest.mark.parametrize("kind", ["float32", "strided", "readonly"]) - def test_array_updated_in_place_must_not_be_converted(self, kind): - # a copy would silently lose the update - if kind == "float32": - likelihood = np.ones((2, 2), dtype=np.float32) - elif kind == "strided": - likelihood = np.ones((2, 4))[:, ::2] - else: - likelihood = np.ones((2, 2)) - likelihood.flags.writeable = False - with pytest.raises(ValueError): - self.call(likelihood, [0.5], [0], [[0, 1]]) + def test_input_unchanged(self): + likelihood = np.array([[1.0, 5.0], [0.0, 5.0]]) + result = _tsdate.reallocate_unphased( + likelihood, f64(0.25), i32(0), np.array([[0, 1]], dtype=np.int32) + ) + assert result.tolist() == [[0.25, 5.0], [0.75, 5.0]] + assert likelihood.tolist() == [[1.0, 5.0], [0.0, 5.0]] class TestMutationFrequency: @@ -108,9 +101,9 @@ def test_constrain_ages_wrong_dtype(self): with pytest.raises(TypeError): _tsdate.constrain_ages(f64(0, 1), b1(1, 0), i32(1), np.array([0]), 0.1, 3) - def test_contains_unary_nodes_mask_size(self): + def test_contains_unary_nodes_mask_too_short(self): ts = make_ts(THREE_HAPLOTYPES, STAR, [], 10.0, 1) - with pytest.raises(ValueError, match="number of nodes"): + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): _tsdate.contains_unary_nodes( b1(0, 0), ts.edges_parent, @@ -119,7 +112,6 @@ def test_contains_unary_nodes_mask_size(self): ts.indexes_edge_insertion_order, ts.indexes_edge_removal_order, ts.sequence_length, - ts.num_nodes, ) diff --git a/tests/test_python_c_variational.py b/tests/test_python_c_variational.py deleted file mode 100644 index b78f611e..00000000 --- a/tests/test_python_c_variational.py +++ /dev/null @@ -1,338 +0,0 @@ -""" -Tests of the expectation propagation functions of the low-level _tsdate module that -the oracle tests in test_oracle_variational.py do not reach: argument handling, and -the messages of library errors. -""" - -import _tsdate -import numpy as np -import pytest - -INF = np.inf - - -def factors(num_nodes=3, num_edges=2, num_blocks=1): - """ - The tuple of arrays that describes EP factors, for a small example. - """ - return ( - np.zeros((num_nodes, 2, 2)), - np.zeros((num_edges, 2, 2)), - np.zeros((num_blocks, 2, 2)), - np.ones(num_nodes), - np.array([2, 2][:num_edges], dtype=np.int32), - np.array([0, 1][:num_edges], dtype=np.int32), - np.full(num_blocks, 2, dtype=np.int32), - np.full(num_blocks, 1, dtype=np.int32), - ) - - -def likelihood_args(**changes): - """ - Arguments of propagate_likelihood on two edges (2, 0) and (2, 1). - """ - args = dict( - edge_order=np.array([0, 1], dtype=np.int32), - edges_parent=np.array([2, 2], dtype=np.int32), - edges_child=np.array([0, 1], dtype=np.int32), - likelihoods=np.array([[1.0, 0.1], [1.0, 0.1]]), - constraints=np.array([[0.0, 0.0], [0.0, INF], [0.0, INF]]), - posterior=np.ones((3, 2)), - factors=factors(), - lognorm=np.zeros(2), - max_shape=1000.0, - min_step=0.1, - unphased=False, - ) - args.update(changes) - return list(args.values()) - - -def prior_args(**changes): - args = dict( - free=np.array([False, True, True]), - posterior=np.full((3, 2), 2.0), - factors=factors(), - max_shape=1000.0, - em_maxitt=10, - em_reltol=1e-8, - ) - args.update(changes) - return list(args.values()) - - -def mutation_args(**changes): - args = dict( - mutations_order=np.array([0, 1], dtype=np.int32), - mutations_posterior=np.zeros((2, 2)), - mutations_phase=np.zeros(2), - mutations_edge=np.array([0, 1], dtype=np.int32), - edges_parent=np.array([2, 2], dtype=np.int32), - edges_child=np.array([0, 1], dtype=np.int32), - likelihoods=np.array([[1.0, 0.1], [1.0, 0.1]]), - constraints=np.array([[1.0, 1.0], [0.0, INF], [0.0, INF]]), - posterior=np.ones((3, 2)), - factors=factors(), - unphased=False, - ) - args.update(changes) - return list(args.values()) - - -class TestFactors: - def test_not_a_tuple(self): - with pytest.raises(TypeError, match="tuple of eight"): - _tsdate.rescale_factors(list(factors())) - with pytest.raises(TypeError, match="tuple of eight"): - _tsdate.assemble_factors(factors()[:7]) - - def test_wrong_dtype(self): - f = list(factors()) - f[4] = f[4].astype(np.int64) - with pytest.raises(TypeError): - _tsdate.rescale_factors(tuple(f)) - - def test_wrong_shape(self): - f = list(factors()) - f[1] = np.zeros((2, 2, 3)) - with pytest.raises(ValueError, match="shape"): - _tsdate.rescale_factors(tuple(f)) - - def test_inconsistent_sizes(self): - f = list(factors()) - f[3] = np.ones(4) - with pytest.raises(ValueError, match="inconsistent"): - _tsdate.assemble_factors(tuple(f)) - - def test_readonly_arrays(self): - f = list(factors()) - f[0].flags.writeable = False - with pytest.raises(ValueError): - _tsdate.rescale_factors(tuple(f)) - # nothing is written by the assembly - assert _tsdate.assemble_factors(tuple(f)).shape == (3, 2) - - def test_rescale_in_place(self): - f = factors() - f[3][:] = [2.0, 3.0, 4.0] - f[0][:] = 1.0 - _tsdate.rescale_factors(f) - assert np.all(f[3] == 1.0) - assert np.array_equal(f[0][:, 0, 0], [2.0, 3.0, 4.0]) - - -class TestConstraintsAreConsistent: - def test_columns(self): - with pytest.raises(ValueError, match="two columns"): - _tsdate.constraints_are_consistent( - np.zeros((3, 3)), np.zeros(0, np.int32), np.zeros(0, np.int32) - ) - - def test_edge_sizes(self): - with pytest.raises(ValueError, match="same size"): - _tsdate.constraints_are_consistent( - np.zeros((3, 2)), np.zeros(2, np.int32), np.zeros(1, np.int32) - ) - - -class TestPropagateLikelihood: - def test_runs(self): - args = likelihood_args() - assert _tsdate.propagate_likelihood(*args) is None - assert np.all(np.isfinite(args[7])) - - @pytest.mark.parametrize( - ("change", "message"), - [ - ("edges_child", "same size"), - ("likelihoods", "shape"), - ("constraints", "shape"), - ("posterior", "same shape"), - ("lognorm", "one entry per edge"), - ], - ) - def test_shape_errors(self, change, message): - value = dict( - edges_child=np.zeros(1, np.int32), - likelihoods=np.zeros((1, 2)), - constraints=np.zeros((2, 2)), - posterior=np.ones((2, 2)), - lognorm=np.zeros(3), - )[change] - with pytest.raises(ValueError, match=message): - _tsdate.propagate_likelihood(*likelihood_args(**{change: value})) - - def test_factors_do_not_match_kind(self): - # the unphased pass uses the blocks, of which there is one - with pytest.raises(ValueError, match="one entry per edge"): - _tsdate.propagate_likelihood(*likelihood_args(unphased=True)) - - def test_library_errors(self): - with pytest.raises(_tsdate.LibraryError, match="at least one"): - _tsdate.propagate_likelihood(*likelihood_args(max_shape=0.5)) - with pytest.raises(_tsdate.LibraryError, match="greater than zero and less"): - _tsdate.propagate_likelihood(*likelihood_args(min_step=1.0)) - with pytest.raises(_tsdate.LibraryError, match="not greater than -1"): - _tsdate.propagate_likelihood( - *likelihood_args(posterior=np.full((3, 2), -5.0)) - ) - - @pytest.mark.parametrize("kind", ["float32", "strided"]) - def test_array_updated_in_place_must_not_be_converted(self, kind): - # a copy would silently lose the update - if kind == "float32": - posterior = np.ones((3, 2), dtype=np.float32) - else: - posterior = np.ones((3, 4))[:, ::2] - with pytest.raises(ValueError, match="writeable, C-contiguous"): - _tsdate.propagate_likelihood(*likelihood_args(posterior=posterior)) - - @pytest.mark.parametrize("improper", [0, 1, 2]) - def test_improper_posterior_of_free_edge(self, improper): - # the posterior of either node of an edge (or of a twin block) is not proper - posterior = np.full((3, 2), 2.0) - posterior[improper] = -5.0 - args = likelihood_args( - constraints=np.array([[0.0, INF]] * 3), - posterior=posterior, - edges_parent=np.array([0, 2], dtype=np.int32), - edges_child=np.array([1, 2], dtype=np.int32), - ) - with pytest.raises(_tsdate.LibraryError, match="not greater than -1"): - _tsdate.propagate_likelihood(*args) - - def test_improper_posterior_of_twin_block(self): - args = likelihood_args( - constraints=np.array([[0.0, INF]] * 3), - posterior=np.array([[2.0, 2.0], [2.0, 2.0], [-5.0, 2.0]]), - edges_parent=np.array([2, 2], dtype=np.int32), - edges_child=np.array([2, 2], dtype=np.int32), - factors=factors(num_blocks=2), - unphased=True, - ) - with pytest.raises(_tsdate.LibraryError, match="not greater than -1"): - _tsdate.propagate_likelihood(*args) - - def test_twin_projection_fails(self): - # a zero cavity (the damping step is one for zeros) and no mutation target - args = likelihood_args( - constraints=np.array([[0.0, INF]] * 3), - posterior=np.zeros((3, 2)), - edges_parent=np.array([2, 2], dtype=np.int32), - edges_child=np.array([2, 2], dtype=np.int32), - likelihoods=np.array([[1.0, 0.0], [1.0, 0.0]]), - factors=factors(num_blocks=2), - unphased=True, - ) - with pytest.raises(_tsdate.LibraryError, match="division by zero"): - _tsdate.propagate_likelihood(*args) - - def test_wrong_dtype(self): - with pytest.raises(TypeError): - _tsdate.propagate_likelihood( - *likelihood_args(edge_order=np.array([0, 1], dtype=np.int64)) - ) - - -class TestPropagatePrior: - def test_runs(self): - args = prior_args() - assert _tsdate.propagate_prior(*args) is None - assert np.all(args[1][1:, 1] > 2.0) - - def test_sizes(self): - with pytest.raises(ValueError, match="one entry per node"): - _tsdate.propagate_prior(*prior_args(free=np.ones(2, dtype=bool))) - with pytest.raises(ValueError, match="one entry per node"): - _tsdate.propagate_prior(*prior_args(posterior=np.ones((2, 2)))) - - def test_library_errors(self): - with pytest.raises(_tsdate.LibraryError, match="at least one"): - _tsdate.propagate_prior(*prior_args(max_shape=0.0)) - with pytest.raises(_tsdate.LibraryError, match="penalty is not positive"): - _tsdate.propagate_prior(*prior_args(posterior=np.zeros((3, 2)))) - - def test_improper_posterior_cannot_be_rescaled(self): - # the fit succeeds (the other node has a large shape) but one posterior is - # not proper, so that it cannot be rescaled - posterior = np.array([[2.0, 2.0], [-5.0, 1.0], [99.0, 1.0]]) - with pytest.raises(_tsdate.LibraryError, match="not greater than -1"): - _tsdate.propagate_prior(*prior_args(posterior=posterior)) - - -class TestPropagateMutations: - def test_runs(self): - args = mutation_args() - assert _tsdate.propagate_mutations(*args) is None - assert np.all(np.isfinite(args[2])) - - @pytest.mark.parametrize( - ("change", "message"), - [ - ("mutations_edge", "same size"), - ("mutations_posterior", "shape"), - ("edges_child", "same size"), - ("likelihoods", "shape"), - ("constraints", "shape"), - ("posterior", "same shape"), - ], - ) - def test_shape_errors(self, change, message): - value = dict( - mutations_edge=np.zeros(1, np.int32), - mutations_posterior=np.zeros((3, 2)), - edges_child=np.zeros(1, np.int32), - likelihoods=np.zeros((1, 2)), - constraints=np.zeros((2, 2)), - posterior=np.ones((2, 2)), - )[change] - with pytest.raises(ValueError, match=message): - _tsdate.propagate_mutations(*mutation_args(**{change: value})) - - def test_factors_do_not_match_kind(self): - with pytest.raises(ValueError, match="one entry per edge"): - _tsdate.propagate_mutations(*mutation_args(unphased=True)) - - -class TestArgumentParsing: - @pytest.mark.parametrize( - "name", - [ - "rescale_factors", - "assemble_factors", - "constraints_are_consistent", - "propagate_likelihood", - "propagate_prior", - "propagate_mutations", - ], - ) - def test_wrong_number_of_arguments(self, name): - with pytest.raises(TypeError): - getattr(_tsdate, name)() - - def test_constraints_are_consistent_wrong_dtype(self): - with pytest.raises(TypeError): - _tsdate.constraints_are_consistent( - np.zeros((3, 2)), np.zeros(0, np.int64), np.zeros(0, np.int32) - ) - - def test_bad_factors(self): - bad = list(factors()) - for func, args in [ - (_tsdate.propagate_likelihood, likelihood_args(factors=bad)), - (_tsdate.propagate_prior, prior_args(factors=bad)), - (_tsdate.propagate_mutations, mutation_args(factors=bad)), - ]: - with pytest.raises(TypeError, match="tuple of eight"): - func(*args) - - def test_wrong_dtypes(self): - for func, args in [ - (_tsdate.propagate_prior, prior_args(free=np.ones(3))), - ( - _tsdate.propagate_mutations, - mutation_args(mutations_order=np.zeros(1, np.int64)), - ), - ]: - with pytest.raises(TypeError): - func(*args) diff --git a/tsdate/phasing.py b/tsdate/phasing.py index 2b004b77..e3815687 100644 --- a/tsdate/phasing.py +++ b/tsdate/phasing.py @@ -59,17 +59,16 @@ def block_singletons(ts, individuals_unphased): # TODO: adjust spans by an accessibility mask return _tsdate.block_singletons( - individuals_unphased, - ts.nodes_individual, - ts.mutations_node, - ts.sites_position[ts.mutations_site], - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, + individuals_unphased=individuals_unphased, + nodes_individual=ts.nodes_individual, + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, ) @@ -93,16 +92,16 @@ def mutation_frequency(ts, sample_sets=None): nodes_sample[s, i] = True return _tsdate.mutation_frequency( - nodes_sample, - ts.mutations_node, - ts.sites_position[ts.mutations_site], - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, + nodes_sample=nodes_sample, + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, ).squeeze() diff --git a/tsdate/prior.py b/tsdate/prior.py index 3bbfd5e5..7c8c722d 100644 --- a/tsdate/prior.py +++ b/tsdate/prior.py @@ -215,7 +215,8 @@ def precalculate_priors_for_approximation(self, precalc_approximation_n): prior_lookup_table = np.zeros((n, 2)) all_tips = np.arange(2, n + 1) prior_lookup_table[1:, 0] = all_tips / n - prior_lookup_table[1:, 1] = conditional_coalescent_variance(n + 1)[all_tips] + variance = conditional_coalescent_variance(num_tips=n + 1) + prior_lookup_table[1:, 1] = variance[all_tips] np.savetxt(self.get_precalc_cache(n), prior_lookup_table) return prior_lookup_table @@ -268,7 +269,7 @@ def tau_var_lookup(self, total_tips, all_tips): return interpolated_priors def tau_var_exact(self, total_tips, all_tips): - return conditional_coalescent_variance(total_tips)[all_tips] + return conditional_coalescent_variance(num_tips=total_tips)[all_tips] def mixture_expect_and_var(self, mixture, weight_by_log_span=False): """ diff --git a/tsdate/rescaling.py b/tsdate/rescaling.py index 1e29e563..0878f133 100644 --- a/tsdate/rescaling.py +++ b/tsdate/rescaling.py @@ -49,17 +49,17 @@ def count_mutations(ts, node_is_sample=None, size_biased=False): assert node_is_sample.size == ts.num_nodes return _tsdate.count_mutations( - node_is_sample, - ts.mutations_node, - ts.sites_position[ts.mutations_site], - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, - size_biased, + nodes_sample=node_is_sample, + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, + size_biased=size_biased, ) @@ -90,12 +90,12 @@ def piecewise_scale_posterior( ): _check_increasing_breaks(original_breaks, rescaled_breaks) return _tsdate.piecewise_scale_posterior( - posteriors, - posteriors_fixed, - original_breaks, - rescaled_breaks, - quantile_width, - max_shape, + posteriors=posteriors, + posteriors_fixed=posteriors_fixed, + original_breaks=original_breaks, + rescaled_breaks=rescaled_breaks, + quantile_width=quantile_width, + max_shape=max_shape, ) @@ -104,7 +104,10 @@ def piecewise_scale_point_estimate( ): _check_increasing_breaks(original_breaks, rescaled_breaks) return _tsdate.piecewise_scale_point_estimate( - point_estimate, point_fixed, original_breaks, rescaled_breaks + point_estimate=point_estimate, + point_fixed=point_fixed, + original_breaks=original_breaks, + rescaled_breaks=rescaled_breaks, ) @@ -148,12 +151,12 @@ def rescale_tree_sequence( nodes_time = ts.nodes_time.copy() for _ in np.arange(num_iterations): original_breaks, rescaled_breaks = mutational_timescale( - nodes_time, - mutations_span, - constraints, - ts.edges_parent, - ts.edges_child, - num_intervals, + nodes_time=nodes_time, + edges_likelihood=mutations_span, + nodes_fixed=constraints, + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + max_intervals=num_intervals, ) nodes_time = piecewise_scale_point_estimate( nodes_time, fixed_nodes, original_breaks, rescaled_breaks diff --git a/tsdate/util.py b/tsdate/util.py index 309bf73e..8e833e99 100644 --- a/tsdate/util.py +++ b/tsdate/util.py @@ -426,23 +426,23 @@ def split_disjoint_nodes(ts, *, record_provenance=None): record_provenance = True node_is_sample = np.bitwise_and(ts.nodes_flags, tskit.NODE_IS_SAMPLE).astype(bool) edges_parent, edges_child, nodes_order, split_nodes = _tsdate.split_disjoint_nodes( - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - node_is_sample, + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + nodes_excluded=node_is_sample, ) mutations_node = _tsdate.relabel_mutations_node( - ts.mutations_node, - ts.sites_position[ts.mutations_site], - nodes_order, - edges_parent, - edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + nodes_order=nodes_order, + edges_parent=edges_parent, + edges_child=edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, ) tables = ts.dump_tables() @@ -503,12 +503,12 @@ def constrain_ages(ts, nodes_time, epsilon=1e-6, max_iterations=0): nodes_fixed = np.bitwise_and(ts.nodes_flags, tskit.NODE_IS_SAMPLE).astype(bool) constrained_nodes_time = _tsdate.constrain_ages( - nodes_time, - nodes_fixed, - ts.edges_parent, - ts.edges_child, - epsilon, - max_iterations, + nodes_time=nodes_time, + nodes_fixed=nodes_fixed, + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + epsilon=epsilon, + max_iterations=max_iterations, ) modified = np.sum(~np.isclose(nodes_time, constrained_nodes_time)) logging.info(f"Modified ages of {modified} nodes to satisfy constraints") @@ -528,14 +528,13 @@ def contains_unary_nodes(ts, skip_samples=True): nodes_mask[list(ts.samples())] = True return _tsdate.contains_unary_nodes( - nodes_mask, - ts.edges_parent, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, - ts.num_nodes, + nodes_mask=nodes_mask, + edges_parent=ts.edges_parent, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, ) diff --git a/tsdate/variational.py b/tsdate/variational.py index eceb3890..438352b2 100644 --- a/tsdate/variational.py +++ b/tsdate/variational.py @@ -66,50 +66,6 @@ TINY = np.sqrt(np.finfo(np.float64).tiny) # DEBUG -class EPFactors: - """ - Mutable state of the EP algorithm, that is the factors associated - with each edge likelihood / block likelihood / prior factor, that - together form the posterior. - """ - - def __init__( - self, - node_constraints, - edge_parents, - edge_children, - block_left, - block_right, - ): - assert edge_parents.size == edge_children.size - assert block_left.size == block_right.size - num_nodes = node_constraints.shape[0] - num_edges = edge_parents.size - num_blocks = block_left.size - self.node = np.zeros((num_nodes, 2, 2)) - self.edge = np.zeros((num_edges, 2, 2)) - self.block = np.zeros((num_blocks, 2, 2)) - self.scale = np.ones(num_nodes) - self._p, self._c = edge_parents, edge_children - self._j, self._k = block_left, block_right - - def arrays(self): - """ - The arrays, as the tuple that the functions of ``_tsdate`` take; the first - four are updated in place by them. - """ - return ( - self.node, - self.edge, - self.block, - self.scale, - self._p, - self._c, - self._j, - self._k, - ) - - # main algorithm class ExpectationPropagation: r""" @@ -149,7 +105,10 @@ class ExpectationPropagation: def _check_valid_constraints(constraints, edges_parent, edges_child): # Check that upper-bound on node age is greater than maximum lower-bound # for ages of descendants - if not _tsdate.constraints_are_consistent(constraints, edges_parent, edges_child): + consistent = _tsdate.constraints_are_consistent( + constraints=constraints, edges_parent=edges_parent, edges_child=edges_child + ) + if not consistent: raise ValueError( "Node age constraints are inconsistent, some descendants have" " lower bounds that exceed upper bounds of their ancestors." @@ -162,14 +121,10 @@ def _check_valid_inputs(ts, mutation_rate, allow_unary): if not allow_unary and contains_unary_nodes(ts): raise ValueError("Tree sequence contains unary nodes, simplify first") - @staticmethod - def _check_valid_state( - posterior, - factors, - ): + def _check_valid_state(self): # Check that the messages sum to the posterior (debugging only) - posterior_check = _tsdate.assemble_factors(factors.arrays()) - np.testing.assert_allclose(posterior_check, posterior) + posterior_check = self._ep.assemble_factors() + np.testing.assert_allclose(posterior_check, self._ep.posterior) def __init__(self, ts, *, mutation_rate, allow_unary=False, singletons_phased=True): """ @@ -225,12 +180,14 @@ def __init__(self, ts, *, mutation_rate, allow_unary=False, singletons_phased=Tr logger.debug(f"Phased singletons in {abs(phase_timing):.2f} seconds") # mutable - self.factors = EPFactors( - self.node_constraints, - self.edge_parents, - self.edge_children, - self.block_nodes[0], - self.block_nodes[1], + self._ep = _tsdate.ExpectationPropagation( + constraints=self.node_constraints, + edges_parent=self.edge_parents, + edges_child=self.edge_children, + edges_likelihood=self.edge_likelihoods, + blocks_left=self.block_nodes[ROOTWARD], + blocks_right=self.block_nodes[LEAFWARD], + blocks_likelihood=self.block_likelihoods, ) self.node_posterior = np.zeros((ts.num_nodes, 2)) self.mutation_posterior = np.full((ts.num_mutations, 2), np.nan) @@ -259,7 +216,6 @@ def __init__(self, ts, *, mutation_rate, allow_unary=False, singletons_phased=Tr edges = np.arange(ts.num_edges, dtype=np.int32)[~edge_unphased] self.edge_order = np.concatenate((edges[:-1], np.flip(edges))) self.block_order = np.arange(num_blocks, dtype=np.int32) - self.mutation_order = np.arange(ts.num_mutations, dtype=np.int32) def iterate( self, @@ -272,51 +228,38 @@ def iterate( check_valid=False, # for debugging ): logger.debug("Passing through singleton blocks") - _tsdate.propagate_likelihood( - self.block_order, - self.block_nodes[ROOTWARD], - self.block_nodes[LEAFWARD], - self.block_likelihoods, - self.node_constraints, - self.node_posterior, - self.factors.arrays(), - self.block_logconst, - max_shape, - min_step, - USE_BLOCK_LIKELIHOOD, + self._ep.propagate_likelihood( + order=self.block_order, + unphased=USE_BLOCK_LIKELIHOOD, + max_shape=max_shape, + min_step=min_step, ) logger.debug("Rootward + leafward pass through edges") - _tsdate.propagate_likelihood( - self.edge_order, - self.edge_parents, - self.edge_children, - self.edge_likelihoods, - self.node_constraints, - self.node_posterior, - self.factors.arrays(), - self.edge_logconst, - max_shape, - min_step, - USE_EDGE_LIKELIHOOD, + self._ep.propagate_likelihood( + order=self.edge_order, + unphased=USE_EDGE_LIKELIHOOD, + max_shape=max_shape, + min_step=min_step, ) if regularise: logger.debug("Exponential regularization on roots") - _tsdate.propagate_prior( - self.unconstrained_roots, - self.node_posterior, - self.factors.arrays(), - max_shape, - em_maxitt, - em_reltol, + self._ep.propagate_prior( + free=self.unconstrained_roots, + max_shape=max_shape, + em_maxitt=em_maxitt, + em_reltol=em_reltol, ) logger.debug("Absorbing scaling term into the factors") - _tsdate.rescale_factors(self.factors.arrays()) + self._ep.rescale_factors() + self.node_posterior = self._ep.posterior + self.edge_logconst = self._ep.edges_lognorm + self.block_logconst = self._ep.blocks_lognorm if check_valid: # for debugging - self._check_valid_state(self.node_posterior, self.factors) + self._check_valid_state() def rescale( self, @@ -331,11 +274,11 @@ def rescale( # Normalise posteriors so that empirical mutation rate is constant likelihoods = self.edge_likelihoods if rescale_segsites \ else self.sizebiased_likelihoods # fmt: skip - reallocate_unphased( # correct mutation counts for unphased singletons - likelihoods, - self.mutation_phase, - self.mutation_blocks, - self.block_edges, + likelihoods = reallocate_unphased( # correct counts for unphased singletons + edges_likelihood=likelihoods, + mutations_phase=self.mutation_phase, + mutations_block=self.mutation_blocks, + blocks_edges=self.block_edges, ) nodes_fixed = self.node_constraints[:, 0] == self.node_constraints[:, 1] mutations_fixed = np.isnan(self.mutation_posterior[:, 0]) @@ -343,12 +286,12 @@ def rescale( rescaled_nodes_time = nodes_time.copy() for _ in np.arange(rescale_iterations): # estimate time rescaling original_breaks, rescaled_breaks = mutational_timescale( - rescaled_nodes_time, - likelihoods, - nodes_fixed, - self.edge_parents, - self.edge_children, - rescale_intervals, + nodes_time=rescaled_nodes_time, + edges_likelihood=likelihoods, + nodes_fixed=nodes_fixed, + edges_parent=self.edge_parents, + edges_child=self.edge_children, + max_intervals=rescale_intervals, ) rescaled_nodes_time = piecewise_scale_point_estimate( rescaled_nodes_time, @@ -417,35 +360,21 @@ def infer( logger.info(f"Calculated node posteriors in {abs(nodes_timing):.2f} seconds") muts_timing = time.time() - mutations_phased = self.mutation_blocks == tskit.NULL + unphased = self.mutation_blocks != tskit.NULL logger.debug("Passing through unphased singletons") - _tsdate.propagate_mutations( # unphased singletons - self.mutation_order[~mutations_phased], - self.mutation_posterior, - self.mutation_phase, - self.mutation_blocks, - self.block_nodes[ROOTWARD], - self.block_nodes[LEAFWARD], - self.block_likelihoods, - self.node_constraints, - self.node_posterior, - self.factors.arrays(), - USE_BLOCK_LIKELIHOOD, + posterior, phase = self._ep.propagate_mutations( + mutations_edge=self.mutation_blocks[unphased], + unphased=USE_BLOCK_LIKELIHOOD, ) + self.mutation_posterior[unphased] = posterior + self.mutation_phase[unphased] = phase logger.debug("Passing through phased mutations") - _tsdate.propagate_mutations( # phased mutations - self.mutation_order[mutations_phased], - self.mutation_posterior, - self.mutation_phase, - self.mutation_edges, - self.edge_parents, - self.edge_children, - self.edge_likelihoods, - self.node_constraints, - self.node_posterior, - self.factors.arrays(), - USE_EDGE_LIKELIHOOD, + posterior, phase = self._ep.propagate_mutations( + mutations_edge=self.mutation_edges[~unphased], + unphased=USE_EDGE_LIKELIHOOD, ) + self.mutation_posterior[~unphased] = posterior + self.mutation_phase[~unphased] = phase muts_timing -= time.time() skipped_muts = np.sum(np.isnan(self.mutation_posterior[:, 0])) logger.info(f"Skipped {skipped_muts} mutations with invalid posteriors") From d8a95ac57ac784bfcefaa6574f9a2b4257e2f13b Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 12:20:17 -0800 Subject: [PATCH 46/56] Test the argument handling of every function in test_python_c.py The low-level module's tests are in the one file that the shared CI workflow runs. Every function that tsdate calls is tested for keyword and positional arguments, too few or too many arguments, unknown keywords, the type and dimension of each array, numerical arguments of the wrong type, arrays that must have the same length, two-column arrays, and each error of the library that it reports. The comparisons with the oracle on inputs that tree sequences cannot produce join the other rescaling oracle tests. --- tests/test_oracle_rescaling.py | 63 ++++ tests/test_python_c.py | 550 +++++++++++++++++++++++++++++++ tests/test_python_c_rescaling.py | 123 ------- tests/test_python_c_tables.py | 133 -------- 4 files changed, 613 insertions(+), 256 deletions(-) delete mode 100644 tests/test_python_c_rescaling.py delete mode 100644 tests/test_python_c_tables.py diff --git a/tests/test_oracle_rescaling.py b/tests/test_oracle_rescaling.py index 8abaffac..d718fa1c 100644 --- a/tests/test_oracle_rescaling.py +++ b/tests/test_oracle_rescaling.py @@ -887,3 +887,66 @@ def test_simulated(self, ep): rescaling.piecewise_scale_posterior, *args, ) + + +class TestOutsideTreeSequences: + def test_nan_node_times(self): + # NaN is ordered last, whichever its position + times = np.array([0.0, np.nan, 1.0, np.nan, 2.0]) + likelihoods = np.array([[1.0, 1.0], [1.0, 1.0]]) + parents = np.array([2, 4], dtype=np.int32) + children = np.array([0, 2], dtype=np.int32) + compare( + _tsdate.mutational_area, + rescaling.mutational_area, + times, + likelihoods, + parents, + children, + ) + + def test_changepoint_before_the_first_epoch(self): + # The mutational spans make the offsets of the four epochs 1, 1, -3 and 1, so + # that the total weight is zero and the cumulative distribution is NaN where + # it is looked up: the first changepoint is -1, which counts from the end as + # in numpy. + nodes_time = np.array([0.0, 0.0, 1.0, 2.0, 3.0, 4.0]) + likelihoods = np.array([[1.0, 1.0], [1.0, 1.0], [1.0, -3.0], [1.0, 1.0]]) + parents = np.array([2, 3, 4, 5], dtype=np.int32) + children = np.array([0, 2, 3, 4], dtype=np.int32) + fixed = np.full(6, False) + args = (nodes_time, likelihoods, fixed, parents, children, 2) + result = compare( + _tsdate.mutational_timescale, rescaling.mutational_timescale, *args + ) + assert result.value[0].tolist() == [4.0, 4.0] + + def test_quantile_below_first_breakpoint(self): + # the lower quantile (1.1) is below the first breakpoint, the mean (2) is not + args = ( + np.array([[1.0, 1.0]]), + np.array([False]), + np.array([1.5, 3.0, 5.0]), + np.array([0.0, 1.0, 2.0]), + 0.5, + 1000.0, + ) + result = compare( + _tsdate.piecewise_scale_posterior, rescaling.piecewise_scale_posterior, *args + ) + assert result.error == TIME_BELOW_FIRST_BREAKPOINT + + def test_fixed_posteriors_below_first_breakpoint(self): + # the rescaled quantiles of fixed posteriors are zero, and are checked too + args = ( + np.array([[1.0, 1.0]]), + np.array([True]), + np.array([0.5, 2.0, 5.0]), + np.array([0.0, 1.0, 2.0]), + 0.5, + 1000.0, + ) + result = compare( + _tsdate.piecewise_scale_posterior, rescaling.piecewise_scale_posterior, *args + ) + assert result.error == TIME_BELOW_FIRST_BREAKPOINT diff --git a/tests/test_python_c.py b/tests/test_python_c.py index 4d78b9b2..6735146a 100644 --- a/tests/test_python_c.py +++ b/tests/test_python_c.py @@ -9,10 +9,26 @@ import numpy as np import pytest +import tsdate + ERR_GENERIC = -1 ERR_NO_MEMORY = -2 ERR_BAD_PARAM = -3 ERR_ZERO_DIVISION = -4 +ERR_UNSORTED_QUANTILES = -11 +ERR_UNPHASED_INDIVIDUAL_EDGES = -16 +ERR_BLOCK_OUT_OF_BOUNDS = -17 +ERR_PHASE_OUT_OF_RANGE = -18 +ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED = -19 +ERR_MUTATION_NODE_NOT_IN_TREE = -20 +ERR_FIXED_NODES_VIOLATE_CONSTRAINT = -21 +ERR_NONPOSITIVE_INTERVALS = -22 +ERR_ZERO_EDGE_SPAN = -24 +ERR_NON_INCREASING_BREAKPOINTS = -25 +ERR_INVALID_QUANTILE_WIDTH = -26 +ERR_INVALID_POSTERIOR = -27 +ERR_TIME_BELOW_FIRST_BREAKPOINT = -28 +ERR_NO_POSTERIORS = -29 ERR_INVALID_MAX_SHAPE = -30 ERR_INVALID_MIN_STEP = -31 ERR_TWIN_EDGE_IN_PHASED_PASS = -34 @@ -625,3 +641,537 @@ def test_zero_division(self): ) with raises_library_error(ERR_ZERO_DIVISION): ep.propagate_likelihood(BLOCKS, True, 1000.0, 0.1) + + +def sweep_kwargs(ts, parents=True): + """ + The edge, index and mutation arrays of ``ts`` as keyword arguments + """ + kwargs = { + "mutations_node": ts.mutations_node, + "mutations_position": ts.sites_position[ts.mutations_site], + "edges_parent": ts.edges_parent, + "edges_child": ts.edges_child, + "edges_left": ts.edges_left, + "edges_right": ts.edges_right, + "indexes_insert": ts.indexes_edge_insertion_order, + "indexes_remove": ts.indexes_edge_removal_order, + } + if not parents: + del kwargs["edges_parent"] + return kwargs + + +EDGE_ARRAYS = ["edges_parent", "edges_child", "edges_left", "edges_right"] +INDEXES = ["indexes_insert", "indexes_remove"] +MUTATION_ARRAYS = ["mutations_node", "mutations_position"] + + +def function_specs(ts): + """ + For each function of the module that tsdate calls: valid keyword arguments, the + groups of arrays that must have the same length, and the arrays of two columns + """ + samples = np.zeros(ts.num_nodes, dtype=bool) + samples[ts.samples()] = True + unphased = np.ones(ts.num_individuals, dtype=bool) + _, blocks_edges, mutations_block = tsdate.phasing.block_singletons(ts, unphased) + likelihood, _ = tsdate.rescaling.count_mutations(ts) + constraints = np.zeros((ts.num_nodes, 2)) + constraints[:, 1] = np.inf + constraints[samples] = 0.0 + breaks = np.array([0.0, 1.0, 10.0]), np.array([0.0, 2.0, 20.0]) + posteriors = np.ones((ts.num_nodes, 2)) + return { + "block_singletons": ( + dict( + individuals_unphased=unphased, + nodes_individual=ts.nodes_individual, + **sweep_kwargs(ts, parents=False), + sequence_length=ts.sequence_length, + ), + [EDGE_ARRAYS[1:] + INDEXES, MUTATION_ARRAYS], + [], + ), + "reallocate_unphased": ( + dict( + edges_likelihood=likelihood, + mutations_phase=np.full(ts.num_mutations, 0.5), + mutations_block=mutations_block, + blocks_edges=blocks_edges, + ), + [["mutations_phase", "mutations_block"]], + ["edges_likelihood", "blocks_edges"], + ), + "mutation_frequency": ( + dict( + nodes_sample=samples[:, np.newaxis], + **sweep_kwargs(ts), + sequence_length=ts.sequence_length, + ), + [EDGE_ARRAYS + INDEXES, MUTATION_ARRAYS], + [], + ), + "split_disjoint_nodes": ( + dict( + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + nodes_excluded=samples, + ), + [EDGE_ARRAYS], + [], + ), + "relabel_mutations_node": ( + dict( + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + nodes_order=np.arange(ts.num_nodes, dtype=np.int32), + **{ + k: v + for k, v in sweep_kwargs(ts).items() + if k.startswith(("edges", "indexes")) + }, + ), + [EDGE_ARRAYS + INDEXES, MUTATION_ARRAYS], + [], + ), + "constrain_ages": ( + dict( + nodes_time=ts.nodes_time, + nodes_fixed=samples, + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + epsilon=1e-6, + max_iterations=2, + ), + [["nodes_time", "nodes_fixed"], ["edges_parent", "edges_child"]], + [], + ), + "contains_unary_nodes": ( + dict( + nodes_mask=samples, + edges_parent=ts.edges_parent, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, + ), + [["edges_parent", "edges_left", "edges_right"] + INDEXES], + [], + ), + "conditional_coalescent_variance": (dict(num_tips=5), [], []), + "count_mutations": ( + dict( + nodes_sample=samples, + **sweep_kwargs(ts), + sequence_length=ts.sequence_length, + size_biased=True, + ), + [EDGE_ARRAYS + INDEXES, MUTATION_ARRAYS], + [], + ), + "mutational_area": ( + dict( + nodes_time=ts.nodes_time, + edges_likelihood=likelihood, + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + ), + [["edges_parent", "edges_child", "edges_likelihood"]], + ["edges_likelihood"], + ), + "mutational_timescale": ( + dict( + nodes_time=ts.nodes_time, + edges_likelihood=likelihood, + nodes_fixed=samples, + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + max_intervals=3, + ), + [ + ["edges_parent", "edges_child", "edges_likelihood"], + ["nodes_time", "nodes_fixed"], + ], + ["edges_likelihood"], + ), + "piecewise_scale_point_estimate": ( + dict( + point_estimate=ts.nodes_time, + point_fixed=samples, + original_breaks=breaks[0], + rescaled_breaks=breaks[1], + ), + [["point_estimate", "point_fixed"], ["original_breaks", "rescaled_breaks"]], + [], + ), + "piecewise_scale_posterior": ( + dict( + posteriors=posteriors, + posteriors_fixed=samples, + original_breaks=breaks[0], + rescaled_breaks=breaks[1], + quantile_width=0.5, + max_shape=1000.0, + ), + [ + ["posteriors", "posteriors_fixed"], + ["original_breaks", "rescaled_breaks"], + ], + ["posteriors"], + ), + "constraints_are_consistent": ( + dict( + constraints=constraints, + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + ), + [["edges_parent", "edges_child"]], + ["constraints"], + ), + } + + +FUNCTIONS = [ + "block_singletons", + "reallocate_unphased", + "mutation_frequency", + "split_disjoint_nodes", + "relabel_mutations_node", + "constrain_ages", + "contains_unary_nodes", + "conditional_coalescent_variance", + "count_mutations", + "mutational_area", + "mutational_timescale", + "piecewise_scale_point_estimate", + "piecewise_scale_posterior", + "constraints_are_consistent", +] + + +@pytest.fixture(scope="module") +def specs(ts): + return function_specs(ts) + + +def array_arguments(): + """ + (function, argument) for every array argument + """ + specs = function_specs(make_ts_for_specs()) + return [ + (name, arg) + for name in FUNCTIONS + for arg, value in specs[name][0].items() + if isinstance(value, np.ndarray) + ] + + +def scalar_arguments(): + """ + (function, argument) for every numerical scalar argument (flags take any object, + as Python's truth values) + """ + specs = function_specs(make_ts_for_specs()) + return [ + (name, arg) + for name in FUNCTIONS + for arg, value in specs[name][0].items() + if not isinstance(value, (np.ndarray, bool)) + ] + + +def make_ts_for_specs(): + """ + The tree sequence of the ``ts`` fixture, for parametrising tests + """ + ts = msprime.sim_ancestry( + 2, + sequence_length=1e4, + recombination_rate=1e-8, + population_size=1e4, + random_seed=2, + ) + return msprime.sim_mutations(ts, rate=1e-7, random_seed=2) + + +def bad_dtype(value): + """ + An array of a type that cannot be cast safely to the type of ``value`` + """ + if value.dtype == np.float64: + return value.astype(np.complex128) + return value.astype(np.float64) + + +class TestArguments: + """ + Argument handling of each function: counts, keywords, types, dimensions and lengths + """ + + @pytest.mark.parametrize("name", FUNCTIONS) + def test_keywords(self, specs, name): + kwargs, _, _ = specs[name] + getattr(_tsdate, name)(**kwargs) + + @pytest.mark.parametrize("name", FUNCTIONS) + def test_positional(self, specs, name): + kwargs, _, _ = specs[name] + getattr(_tsdate, name)(*kwargs.values()) + + @pytest.mark.parametrize("name", FUNCTIONS) + def test_too_few_arguments(self, specs, name): + args = list(specs[name][0].values()) + with pytest.raises(TypeError): + getattr(_tsdate, name)(*args[:-1]) + + @pytest.mark.parametrize("name", FUNCTIONS) + def test_too_many_arguments(self, specs, name): + args = list(specs[name][0].values()) + with pytest.raises(TypeError): + getattr(_tsdate, name)(*args, args[-1]) + + @pytest.mark.parametrize("name", FUNCTIONS) + def test_unknown_keyword(self, specs, name): + kwargs = dict(specs[name][0], not_an_argument=1) + with pytest.raises(TypeError): + getattr(_tsdate, name)(**kwargs) + + @pytest.mark.parametrize(("name", "arg"), array_arguments()) + def test_bad_dtype(self, specs, name, arg): + kwargs = dict(specs[name][0]) + kwargs[arg] = bad_dtype(kwargs[arg]) + with pytest.raises(TypeError): + getattr(_tsdate, name)(**kwargs) + + @pytest.mark.parametrize(("name", "arg"), array_arguments()) + def test_bad_dimension(self, specs, name, arg): + kwargs = dict(specs[name][0]) + value = kwargs[arg] + kwargs[arg] = value.reshape(-1) if value.ndim == 2 else value[np.newaxis, :] + with pytest.raises(ValueError): + getattr(_tsdate, name)(**kwargs) + + @pytest.mark.parametrize(("name", "arg"), array_arguments()) + def test_not_an_array(self, specs, name, arg): + kwargs = dict(specs[name][0]) + kwargs[arg] = "not an array" + with pytest.raises((TypeError, ValueError)): + getattr(_tsdate, name)(**kwargs) + + @pytest.mark.parametrize(("name", "arg"), scalar_arguments()) + def test_bad_scalar(self, specs, name, arg): + kwargs = dict(specs[name][0]) + kwargs[arg] = "not a number" + with pytest.raises(TypeError): + getattr(_tsdate, name)(**kwargs) + + @pytest.mark.parametrize("name", FUNCTIONS) + def test_mismatched_lengths(self, specs, name): + kwargs, groups, _ = specs[name] + for group in groups: + for arg in group[1:]: + bad = dict(kwargs) + bad[arg] = kwargs[arg][:-1] + with pytest.raises(ValueError): + getattr(_tsdate, name)(**bad) + + @pytest.mark.parametrize("name", FUNCTIONS) + def test_two_columns(self, specs, name): + kwargs, _, two_columns = specs[name] + for arg in two_columns: + bad = dict(kwargs) + bad[arg] = np.hstack((kwargs[arg], kwargs[arg][:, :1])) + with pytest.raises(ValueError, match="two columns"): + getattr(_tsdate, name)(**bad) + + +def first_blocked(kwargs): + """ + The first mutation of ``reallocate_unphased``'s arguments that is in a block + """ + return np.flatnonzero(kwargs["mutations_block"] >= 0)[0] + + +def edit(arg, change): + """ + An edit of the keyword arguments that sets ``arg`` to ``change(kwargs)`` + """ + + def apply(kwargs): + kwargs[arg] = change(kwargs) + + return apply + + +def with_entry(arg, index, value): + """ + An edit that sets entry ``index`` of array ``arg`` to ``value``; either can be a + function of the arguments + """ + + def change(kwargs): + array = kwargs[arg].copy() + entry = index(kwargs) if callable(index) else index + array[entry] = value(kwargs) if callable(value) else value + return array + + return edit(arg, change) + + +def node_not_in_tree(kwargs): + """ + A node with no edge over the position of the first mutation + """ + position = kwargs["mutations_position"][0] + left, right = kwargs["edges_left"], kwargs["edges_right"] + over = (left <= position) & (position < right) + present = set(kwargs["edges_parent"][over]) | set(kwargs["edges_child"][over]) + return min(set(range(kwargs["nodes_order"].size)) - present) + + +def reversed_ages(kwargs): + return kwargs["nodes_time"].max() - kwargs["nodes_time"] + + +ERROR_CASES = { + "block_singletons_three_edges": ( + "block_singletons", + with_entry("nodes_individual", 2, 0), + ERR_UNPHASED_INDIVIDUAL_EDGES, + ), + "reallocate_block": ( + "reallocate_unphased", + with_entry("mutations_block", first_blocked, 1000), + ERR_BLOCK_OUT_OF_BOUNDS, + ), + "reallocate_edge_of_block": ( + "reallocate_unphased", + with_entry("blocks_edges", 0, 10**6), + ERR_BLOCK_OUT_OF_BOUNDS, + ), + "reallocate_phase": ( + "reallocate_unphased", + with_entry("mutations_phase", first_blocked, 1.5), + ERR_PHASE_OUT_OF_RANGE, + ), + "reallocate_not_conserved": ( + "reallocate_unphased", + with_entry("mutations_phase", first_blocked, np.nan), + ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED, + ), + "relabel_node_not_in_tree": ( + "relabel_mutations_node", + with_entry("mutations_node", 0, node_not_in_tree), + ERR_MUTATION_NODE_NOT_IN_TREE, + ), + "constrain_fixed_nodes": ( + "constrain_ages", + lambda kwargs: kwargs.update( + nodes_fixed=np.ones_like(kwargs["nodes_fixed"]), + nodes_time=reversed_ages(kwargs), + ), + ERR_FIXED_NODES_VIOLATE_CONSTRAINT, + ), + "timescale_intervals": ( + "mutational_timescale", + edit("max_intervals", lambda kwargs: 0), + ERR_NONPOSITIVE_INTERVALS, + ), + "timescale_zero_span": ( + "mutational_timescale", + edit("edges_likelihood", lambda kwargs: kwargs["edges_likelihood"] * [1, 0]), + ERR_ZERO_EDGE_SPAN, + ), + "point_estimate_breaks": ( + "piecewise_scale_point_estimate", + edit("original_breaks", lambda kwargs: kwargs["original_breaks"][::-1].copy()), + ERR_NON_INCREASING_BREAKPOINTS, + ), + "posterior_breaks": ( + "piecewise_scale_posterior", + edit("rescaled_breaks", lambda kwargs: kwargs["rescaled_breaks"][::-1].copy()), + ERR_NON_INCREASING_BREAKPOINTS, + ), + "posterior_quantile_width": ( + "piecewise_scale_posterior", + edit("quantile_width", lambda kwargs: 1.0), + ERR_INVALID_QUANTILE_WIDTH, + ), + "posterior_invalid": ( + "piecewise_scale_posterior", + with_entry("posteriors", (0, 1), 0.0), + ERR_INVALID_POSTERIOR, + ), + "posterior_none": ( + "piecewise_scale_posterior", + lambda kwargs: kwargs.update( + posteriors=np.zeros((0, 2)), posteriors_fixed=np.zeros(0, dtype=bool) + ), + ERR_NO_POSTERIORS, + ), + "posterior_below_first_break": ( + "piecewise_scale_posterior", + edit("original_breaks", lambda kwargs: kwargs["original_breaks"] + 50.0), + ERR_TIME_BELOW_FIRST_BREAKPOINT, + ), + "posterior_zero_quantile": ( + "piecewise_scale_posterior", + with_entry("posteriors", (0, 1), np.inf), + ERR_ZERO_DIVISION, + ), + "posterior_approximation": ( + "piecewise_scale_posterior", + with_entry("posteriors", (0, 0), np.inf), + ERR_UNSORTED_QUANTILES, + ), +} + + +class TestLibraryErrors: + """ + Errors of the library, through each function that reports them + """ + + @pytest.mark.parametrize("case", ERROR_CASES) + def test_error(self, specs, case): + name, change, code = ERROR_CASES[case] + kwargs = dict(specs[name][0]) + if name == "piecewise_scale_posterior": + kwargs["posteriors_fixed"] = np.zeros_like(kwargs["posteriors_fixed"]) + change(kwargs) + with raises_library_error(code): + getattr(_tsdate, name)(**kwargs) + + +class TestValues: + """ + Results that the other tests do not check + """ + + def test_reallocate_unphased_leaves_input(self): + likelihood = np.array([[1.0, 5.0], [0.0, 5.0]]) + result = _tsdate.reallocate_unphased( + edges_likelihood=likelihood, + mutations_phase=np.array([0.25]), + mutations_block=np.array([0], dtype=np.int32), + blocks_edges=np.array([[0, 1]], dtype=np.int32), + ) + assert result.tolist() == [[0.25, 5.0], [0.75, 5.0]] + assert likelihood.tolist() == [[1.0, 5.0], [0.0, 5.0]] + + def test_variance_one_tip(self): + # the result is unused by tsdate + assert _tsdate.conditional_coalescent_variance(1).tolist() == [0.0, 0.0] + + def test_variance_negative_tips(self): + with pytest.raises(ValueError, match="non-negative"): + _tsdate.conditional_coalescent_variance(-1) + + def test_fixed_changepoints_epochs_beyond_int64(self): + with pytest.raises(OverflowError): + _tsdate.fixed_changepoints(np.ones(3), 2**70) diff --git a/tests/test_python_c_rescaling.py b/tests/test_python_c_rescaling.py deleted file mode 100644 index 8b5c6662..00000000 --- a/tests/test_python_c_rescaling.py +++ /dev/null @@ -1,123 +0,0 @@ -""" -Tests of the rescaling functions of the low-level _tsdate module that the oracle tests -in test_oracle_rescaling.py do not reach: argument handling, and inputs outside what -a tree sequence can produce. Values are compared with the oracles. -""" - -import _tsdate -import numpy as np -import pytest -from oracle import rescaling -from oracle.errors import TIME_BELOW_FIRST_BREAKPOINT -from oracle.helpers import compare - -NODES_TIME = np.array([0.0, 0.0, 1.0, 2.0]) -PARENTS = np.array([2, 3], dtype=np.int32) -CHILDREN = np.array([0, 2], dtype=np.int32) - - -class TestArguments: - def test_epochs_beyond_int32(self): - with pytest.raises(OverflowError): - _tsdate.fixed_changepoints(np.ones(3), 2**70) - - def test_wrong_dtype(self): - with pytest.raises(TypeError): - _tsdate.mutational_area( - NODES_TIME, np.ones((2, 2)), PARENTS.astype(np.int64), CHILDREN - ) - - def test_wrong_dimension(self): - with pytest.raises(ValueError, match="depth"): - _tsdate.mutational_area(NODES_TIME, np.ones(4), PARENTS, CHILDREN) - - def test_empty_breaks(self): - empty = np.zeros(0) - with pytest.raises(_tsdate.LibraryError, match="No breakpoints"): - _tsdate.piecewise_scale_point_estimate( - np.zeros(1), np.zeros(1, dtype=bool), empty, empty - ) - with pytest.raises(_tsdate.LibraryError, match="No breakpoints"): - _tsdate.piecewise_scale_posterior( - np.ones((1, 2)), np.zeros(1, dtype=bool), empty, empty, 0.5, 1000.0 - ) - - def test_point_estimate_fixed_size(self): - with pytest.raises(ValueError, match="same size"): - _tsdate.piecewise_scale_point_estimate( - np.zeros(2), np.zeros(1, dtype=bool), np.zeros(1), np.zeros(1) - ) - - def test_posterior_columns(self): - with pytest.raises(ValueError, match="two columns"): - _tsdate.piecewise_scale_posterior( - np.ones((1, 3)), - np.zeros(1, dtype=bool), - np.zeros(1), - np.zeros(1), - 0.5, - 1.0, - ) - - -class TestOutsideTreeSequences: - def test_nan_node_times(self): - # NaN is ordered last, whichever its position - times = np.array([0.0, np.nan, 1.0, np.nan, 2.0]) - likelihoods = np.array([[1.0, 1.0], [1.0, 1.0]]) - parents = np.array([2, 4], dtype=np.int32) - children = np.array([0, 2], dtype=np.int32) - compare( - _tsdate.mutational_area, - rescaling.mutational_area, - times, - likelihoods, - parents, - children, - ) - - def test_changepoint_before_the_first_epoch(self): - # The mutational spans make the offsets of the four epochs 1, 1, -3 and 1, so - # that the total weight is zero and the cumulative distribution is NaN where - # it is looked up: the first changepoint is -1, which counts from the end as - # in numpy. - nodes_time = np.array([0.0, 0.0, 1.0, 2.0, 3.0, 4.0]) - likelihoods = np.array([[1.0, 1.0], [1.0, 1.0], [1.0, -3.0], [1.0, 1.0]]) - parents = np.array([2, 3, 4, 5], dtype=np.int32) - children = np.array([0, 2, 3, 4], dtype=np.int32) - fixed = np.full(6, False) - args = (nodes_time, likelihoods, fixed, parents, children, 2) - result = compare( - _tsdate.mutational_timescale, rescaling.mutational_timescale, *args - ) - assert result.value[0].tolist() == [4.0, 4.0] - - def test_quantile_below_first_breakpoint(self): - # the lower quantile (1.1) is below the first breakpoint, the mean (2) is not - args = ( - np.array([[1.0, 1.0]]), - np.array([False]), - np.array([1.5, 3.0, 5.0]), - np.array([0.0, 1.0, 2.0]), - 0.5, - 1000.0, - ) - result = compare( - _tsdate.piecewise_scale_posterior, rescaling.piecewise_scale_posterior, *args - ) - assert result.error == TIME_BELOW_FIRST_BREAKPOINT - - def test_fixed_posteriors_below_first_breakpoint(self): - # the rescaled quantiles of fixed posteriors are zero, and are checked too - args = ( - np.array([[1.0, 1.0]]), - np.array([True]), - np.array([0.5, 2.0, 5.0]), - np.array([0.0, 1.0, 2.0]), - 0.5, - 1000.0, - ) - result = compare( - _tsdate.piecewise_scale_posterior, rescaling.piecewise_scale_posterior, *args - ) - assert result.error == TIME_BELOW_FIRST_BREAKPOINT diff --git a/tests/test_python_c_tables.py b/tests/test_python_c_tables.py deleted file mode 100644 index 34181778..00000000 --- a/tests/test_python_c_tables.py +++ /dev/null @@ -1,133 +0,0 @@ -""" -Low-level tests of the phasing, util and prior functions of the ``_tsdate`` module: -argument checking and the error paths that the oracle tests do not reach. -""" - -import _tsdate -import numpy as np -import pytest -from oracle.helpers import b1, f64, i32, make_ts - -# nodes 0, 1, 2 belong to individual 0; node 3 is the root -THREE_HAPLOTYPES = [(1, 0, 0), (1, 0, 0), (1, 0, 0), (0, 1, -1)] -STAR = [(0, 10, 3, 0), (0, 10, 3, 1), (0, 10, 3, 2)] - - -class TestBlockSingletons: - def test_individual_with_three_edges(self): - ts = make_ts(THREE_HAPLOTYPES, STAR, [(1, 0)], 10.0, 1) - with pytest.raises(_tsdate.LibraryError, match="unphased individual"): - _tsdate.block_singletons( - b1(1), - ts.nodes_individual, - ts.mutations_node, - ts.sites_position[ts.mutations_site], - ts.edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, - ) - - def test_wrong_dtype(self): - ts = make_ts(THREE_HAPLOTYPES, STAR, [(1, 0)], 10.0, 1) - with pytest.raises(TypeError): - _tsdate.block_singletons( - b1(1), - ts.nodes_individual, - ts.mutations_node.astype(np.int64), - ts.sites_position[ts.mutations_site], - ts.edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, - ) - - -class TestReallocateUnphased: - @staticmethod - def call(likelihood, phase, mutations_block, blocks_edges): - _tsdate.reallocate_unphased( - likelihood, - f64(*phase), - i32(*mutations_block), - np.array(blocks_edges, dtype=np.int32).reshape(-1, 2), - ) - - def test_block_out_of_bounds(self): - with pytest.raises(_tsdate.LibraryError, match="out of bounds"): - self.call(np.ones((2, 2)), [0.5], [1], [[0, 1]]) - - def test_edge_out_of_bounds(self): - with pytest.raises(_tsdate.LibraryError, match="out of bounds"): - self.call(np.ones((2, 2)), [0.5], [0], [[0, 7]]) - - def test_columns(self): - with pytest.raises(ValueError, match="two columns"): - self.call(np.ones((2, 3)), [0.5], [0], [[0, 1]]) - - def test_input_unchanged(self): - likelihood = np.array([[1.0, 5.0], [0.0, 5.0]]) - result = _tsdate.reallocate_unphased( - likelihood, f64(0.25), i32(0), np.array([[0, 1]], dtype=np.int32) - ) - assert result.tolist() == [[0.25, 5.0], [0.75, 5.0]] - assert likelihood.tolist() == [[1.0, 5.0], [0.0, 5.0]] - - -class TestMutationFrequency: - def test_nodes_sample_dtype(self): - ts = make_ts(THREE_HAPLOTYPES, STAR, [(1, 0)], 10.0, 1) - with pytest.raises(TypeError): - _tsdate.mutation_frequency( - np.ones((ts.num_nodes, 1), dtype=np.float64), - ts.mutations_node, - ts.sites_position[ts.mutations_site], - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, - ) - - -class TestUtil: - def test_constrain_ages_wrong_dtype(self): - with pytest.raises(TypeError): - _tsdate.constrain_ages(f64(0, 1), b1(1, 0), i32(1), np.array([0]), 0.1, 3) - - def test_contains_unary_nodes_mask_too_short(self): - ts = make_ts(THREE_HAPLOTYPES, STAR, [], 10.0, 1) - with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): - _tsdate.contains_unary_nodes( - b1(0, 0), - ts.edges_parent, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, - ) - - -class TestPrior: - def test_marginalize_over_ancestors_one_tip(self): - with pytest.raises(_tsdate.LibraryError, match="Too few tips"): - _tsdate.marginalize_over_ancestors(np.ones((1, 2))) - - def test_variance_no_tips(self): - with pytest.raises(_tsdate.LibraryError, match="Too few tips"): - _tsdate.conditional_coalescent_variance(0) - - def test_variance_negative_tips(self): - with pytest.raises(ValueError, match="non-negative"): - _tsdate.conditional_coalescent_variance(-1) - - def test_variance_one_tip(self): - # the result is unused by tsdate - assert _tsdate.conditional_coalescent_variance(1).tolist() == [0.0, 0.0] From 4e22f1c15f3bdd80e08a1566dfdd9d1d54bce297 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 17:03:42 -0800 Subject: [PATCH 47/56] Move the comparison helpers of the C tests to the top of the file --- lib/tests/tests.c | 83 ++++++++++++++++++++++++++++------------------- 1 file changed, 49 insertions(+), 34 deletions(-) diff --git a/lib/tests/tests.c b/lib/tests/tests.c index 145a66c4..a841ec1e 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -39,6 +39,54 @@ #include "tsdate.h" +/* Tolerance of the comparisons with the reference implementation */ +#define ULPS 4 + +/* The bits of `x` as an integer that increases with `x` (with -0 equal to 0). */ +static int64_t +ordered_bits(double x) +{ + int64_t bits; + + memcpy(&bits, &x, sizeof(bits)); + if (bits < 0) { + bits = INT64_MIN - bits; + } + return bits; +} + +/* `actual` is within `ulps` units in the last place of `expected`; NaNs are equal. */ +static void +assert_close_ulps(double actual, double expected, int ulps) +{ + int64_t a, b; + uint64_t distance; + + if (isnan(expected)) { + CU_ASSERT_TRUE(isnan(actual)); + } else if (!isfinite(expected) || !isfinite(actual)) { + CU_ASSERT_EQUAL(actual, expected); + } else { + a = ordered_bits(actual); + b = ordered_bits(expected); + distance = a > b ? (uint64_t) a - (uint64_t) b : (uint64_t) b - (uint64_t) a; + CU_ASSERT_TRUE(distance <= (uint64_t) ulps); + } +} + +/* |actual - expected| <= atol + rtol * |expected|, as numpy.isclose; NaNs are equal. */ +static void +assert_close_tol(double actual, double expected, double rtol, double atol) +{ + if (isnan(expected)) { + CU_ASSERT_TRUE(isnan(actual)); + } else if (!isfinite(expected)) { + CU_ASSERT_EQUAL(actual, expected); + } else { + CU_ASSERT_TRUE(fabs(actual - expected) <= atol + rtol * fabs(expected)); + } +} + static void test_strerror(void) { @@ -1647,7 +1695,6 @@ test_propagate_mutations(void) #define EP_MAX_EDGES 8 #define EP_MAX_ORDER 8 #define EP_MAX_MUTATIONS 4 -#define EP_ULPS 4 typedef struct { tsd_size_t num_nodes; @@ -1713,45 +1760,13 @@ typedef struct { double phase[EP_MAX_MUTATIONS]; } ep_mutations_row_t; -/* The bits of `x` as an integer that increases with `x` (with -0 equal to 0). */ -static int64_t -ordered_bits(double x) -{ - int64_t bits; - - memcpy(&bits, &x, sizeof(bits)); - if (bits < 0) { - bits = INT64_MIN - bits; - } - return bits; -} - -/* `actual` is within `ulps` units in the last place of `expected`; NaNs are equal. */ -static void -assert_close_ulps(double actual, double expected, int ulps) -{ - int64_t a, b; - uint64_t distance; - - if (isnan(expected)) { - CU_ASSERT_TRUE(isnan(actual)); - } else if (!isfinite(expected) || !isfinite(actual)) { - CU_ASSERT_EQUAL(actual, expected); - } else { - a = ordered_bits(actual); - b = ordered_bits(expected); - distance = a > b ? (uint64_t) a - (uint64_t) b : (uint64_t) b - (uint64_t) a; - CU_ASSERT_TRUE(distance <= (uint64_t) ulps); - } -} - static void assert_array_close(const double *actual, const double *expected, tsd_size_t n) { tsd_size_t j; for (j = 0; j < n; j++) { - assert_close_ulps(actual[j], expected[j], EP_ULPS); + assert_close_ulps(actual[j], expected[j], ULPS); } } From 222ab99e756526c231bc404c25c4a16238907551 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 17:13:12 -0800 Subject: [PATCH 48/56] Test the special functions against tables of reference values --- lib/tests/tests.c | 673 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 516 insertions(+), 157 deletions(-) diff --git a/lib/tests/tests.c b/lib/tests/tests.c index a841ec1e..2d90ea43 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -161,221 +161,584 @@ test_safe_free(void) CU_ASSERT_PTR_NULL(x); } +/* Special functions: arguments, expected values and return codes */ +typedef struct { + double x; + double expected; + int ret; +} sf_case1_t; + +typedef struct { + double p, x; + double expected; + int ret; +} sf_case2_t; + +typedef struct { + double a, b, x; + double expected; + int ret; +} sf_case3_t; + +typedef struct { + double a, b, c, x; + double expected; + int ret; +} sf_case4_t; + +typedef struct { + double a, b, x; + double value, dvalue; + int ret; +} sf_hyperu_case_t; + +/* Special functions: arguments and reference values */ +typedef struct { + double x; + double expected; +} sf_ref1_t; + +typedef struct { + double x, y; + double expected; +} sf_ref2_t; + +typedef struct { + double a, b, x; + double expected; +} sf_ref3_t; + +typedef struct { + double a, b, c, x; + double expected; +} sf_ref4_t; + +typedef struct { + double a, b, x; + double value, dvalue; +} sf_hyperu_ref_t; + +/* Tolerances of the comparisons with mpmath */ +#define POLYGAMMA_RTOL 1e-5 +#define POLYGAMMA_ATOL 1e-8 +#define LAPLACE_RTOL 2e-2 +#define LAPLACE_ATOL 1e-8 +/* The unity limit of hyp2f1 is within 1% of the exact value */ +#define UNITY_RTOL 1e-2 +/* The derivative of the Laplace approximation of hyperu is within 2.5% of the exact */ +#define HYPERU_DERIVATIVE_RTOL 2.5e-2 +/* Tolerance of the comparison with SciPy, whose results depend on its build */ +#define GAMMAINCINV_RTOL 1e-10 + +/* Expected values of the reference implementation */ +static const sf_case1_t digamma_cases[] = { + { 0.0, 0.0, TSD_ERR_ZERO_DIVISION }, + { -0.0, 0.0, TSD_ERR_ZERO_DIVISION }, + { 4.9406564584124654e-324, -INFINITY, 0 }, + { 9.9999999999999995e-07, -1000000.5772156649, 0 }, + { 1.0000000000000001e-05, -100000.57721566489, 0 }, + { 1.0000000000000003e-05, -100000.57719921565, 0 }, + { 0.5, -1.9635100260214153, 0 }, + { 4.9000000000000004, 1.483737793254901, 0 }, + { 8.4999999999999982, 2.0800908175794208, 0 }, + { 8.5, 2.0800908175794279, 0 }, + { 100.0, 4.6001618527380881, 0 }, + { 1.0000000000000001e+300, 690.77552789821368, 0 }, + { INFINITY, INFINITY, 0 }, + { NAN, NAN, 0 }, + { -0.5, 0.036489973978584861, 0 }, + { -1.0, -25653050788007548.0, 0 }, + { -1.5, 0.70315664064525185, 0 }, + { -10.5, 2.3982391295357801, 0 }, + { -1e-300, 1.0000000000000001e+300, 0 }, + { -INFINITY, NAN, 0 }, +}; + +/* Expected values of the reference implementation */ +static const sf_case1_t trigamma_cases[] = { + { 0.0, 0.0, TSD_ERR_ZERO_DIVISION }, + { -0.0, 0.0, TSD_ERR_ZERO_DIVISION }, + { -1e-300, 0.0, TSD_ERR_ZERO_DIVISION }, + { 1e-300, 0.0, TSD_ERR_ZERO_DIVISION }, + { 4.9406564584124654e-324, 0.0, TSD_ERR_ZERO_DIVISION }, + { 1e-10, 9.9999999999999984e+19, 0 }, + { 0.0001, 100000000.0, 0 }, + { 0.00010000000000000002, 100000001.64469366, 0 }, + { 0.5, 4.9348022005461569, 0 }, + { 4.9000000000000004, 0.22631146419213941, 0 }, + { 5.0, 0.22132295574429867, 0 }, + { 100.0, 0.010050166663333571, 0 }, + { 1.0000000000000001e+300, 1e-300, 0 }, + { INFINITY, 0.0, 0 }, + { NAN, NAN, 0 }, + { -0.5, 8.9348022005432011, 0 }, + { -1.5, 9.3792466449876457, 0 }, + { -10.5, 9.7787577398148109, 0 }, + { -INFINITY, NAN, 0 }, +}; + +/* Expected values of the reference implementation */ +static const sf_ref2_t betaln_cases[] = { + { 1.0, 1.0, 0.0 }, + { 0.5, 0.5, 1.1447298858494002 }, + { 2.0, 3.0, -2.4849066497880004 }, + { 1e-10, 10000000000.0, 23.025848388671875 }, + { 100000.0, 100000.0, -138633.92706134822 }, + { 1.0000000000000001e+300, 1.0000000000000001e+300, -1.3862943611198268e+300 }, + { 1e+308, 1e+308, NAN }, + { 0.0, 1.0, INFINITY }, + { -0.5, 2.0, 1.3862943611198906 }, + { NAN, 1.0, NAN }, + { 1.0, INFINITY, NAN }, +}; + +/* Expected values of the reference implementation */ +static const sf_case2_t gammainc_der_cases[] = { + { 1.0, 0.0, 0.0, 0 }, + { 5.0, 100000000.00000001, 0.0, 0 }, + { 5.0, INFINITY, 0.0, 0 }, + { 2000.0, 2000.0, -0.00892111615358839, 0 }, + { 1000.0000000000001, 1000.0, -0.012617064253050618, 0 }, + { 1000.0, 1000.0, -0.012616713994069394, 0 }, + { 0.5, 1.0, -0.3898372643285174, 0 }, + { 2.0, 1.5, -0.31348863782508085, 0 }, + { 1e-10, 1e-10, -22.448635214909299, 0 }, + { 50.0, 0.001, 0.0, 0 }, + { 0.5, 1.0000000000000002, -0.3898372643285154, 0 }, + { 5.0, 50.0, -1.3227071908086766e-16, 0 }, + { 100.0, 110.0, -0.023808656854890219, 0 }, + { 0.001, 10.0, -4.1816615862918354e-06, 0 }, + { 5.0, 800.0, 0.0, 0 }, + { -1.0, 1.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 0.0, 1.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, -4.9406564584124654e-324, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { NAN, 1.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, NAN, 0.0, TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const sf_hyperu_case_t hyperu_laplace_cases[] = { + { 1.0, 2.0, 1.0, 1.1102230246251565e-16, -1.0, 0 }, + { 1.0, 1.0, 1.0, -0.5016052919180235, -0.6944271909999159, 0 }, + { 0.5, 30.0, 0.001, 267.79385089219738, -28998.983352647308, 0 }, + { 50.0, 51.0, 1000.0, -345.38776394910684, -0.049999999999999996, 0 }, + { 0.001, 1.0, 100000000.0, -0.018420680743962414, -9.9999999998999994e-12, 0 }, + { 1.0, INFINITY, 1.0, NAN, NAN, 0 }, + { 4.9406564584124654e-324, 1.0, 1.0, 0.0, -4.9406564584124654e-324, 0 }, + { 1.0, 0.99999999999999989, 1.0, 0.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 0.0, 1.0, 1.0, 0.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { NAN, 2.0, 1.0, 0.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, 2.0, 0.0, 0.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, 2.0, NAN, 0.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, 2.0, 1.0000000000000001e+300, 0.0, 0.0, TSD_ERR_ZERO_DIVISION }, + { 1.0, 2.0, INFINITY, 0.0, 0.0, TSD_ERR_ZERO_DIVISION }, + { 1.0, 2.0, 4.9406564584124654e-324, 0.0, 0.0, TSD_ERR_ZERO_DIVISION }, + { 4.9406564584124654e-324, 1.0, 10.0, 0.0, 0.0, TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const sf_case3_t hyp1f1_laplace_cases[] = { + { 1.0, 2.0, 1.0, 0.5335775438918825, 0 }, + { 1.0, 2.0, 0.0, 0.0, 0 }, + { 1.0, 2.0, -0.0, 0.0, 0 }, + { 0.5, 30.0, -1000.0, -1.7799338025575939, 0 }, + { 50.0, 1050.0, 1000.0, 97.194122480810705, 0 }, + { 0.001, 1.0009999999999999, 1e-10, 9.9826374162340947e-14, 0 }, + { 1.0, 2.0, NAN, NAN, 0 }, + { 1.0, 2.0, INFINITY, NAN, 0 }, + { 1.0, 2.0, 1.0000000000000001e+300, -INFINITY, 0 }, + { 1.0, 1.0, 1.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 0.0, 1.0, 0.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { NAN, 2.0, 1.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1e-10, 2.0000000000000001e-10, 100000000.0, 0.0, TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const sf_case4_t hyp2f1_laplace_cases[] = { + { 1.0, 2.0, 3.0, 0.5, 0.43844776148964582, 0 }, + { 5.0, 7.0, 9.0, 0.90000000000000002, 8.1454130153612532, 0 }, + { 30.0, 40.0, 35.0, 1e-08, 3.4285713113035854e-07, 0 }, + { 0.0, 1.0, 1.0, 0.0, 0.0, 0 }, + { 1.0, 2.0, 3.0, -0.5, -0.27842079965849342, 0 }, + { 0.5, 30.0, 1.5, -100.0, -4.0851309087682068, 0 }, + { 2.0, 3.0, 4.0, 0.99999998999999995, 19.519293027595719, 0 }, + { 1.0, 2.0, 5.0, 0.99999998999999995, 0.69314718055994551, 0 }, + { 1.0, 2.0, 3.0, 0.99999998999999995, 3.6066211672149588, 0 }, + { 2.0, 3.0, 4.0, -100000000.0, -35.742749223159137, 0 }, + { 3.0, 2.0, 5.0, -100000000.0, -35.049602038676674, 0 }, + { 2.0, 2.0, 5.0, -100000000.0, -31.44298087085901, 0 }, + { 1.0, 2.0, 3.0, -10000000000000000.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, 2.0, 0.0, 0.5, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { -1.0, 2.0, 3.0, 0.5, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, -1.0, 3.0, 0.5, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 2.0, 1.0, 1.0, 0.5, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, 2.0, 3.0, 1.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, 2.0, 3.0, NAN, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 0.0, 1.0, 1.0, 0.5, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, 2.0, 1.0, 0.5, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 0.0, 1.0, 1e-300, 0.5, 0.0, TSD_ERR_ZERO_DIVISION }, + { 1.1774154985086274, 504.40824624062162, 1.1774154985086274, 0.14271801659243741, + 0.0, TSD_ERR_ZERO_DIVISION }, +}; + +/* scipy.special.gammaincinv (SciPy 1.18.1); 0 for p = 0, infinity for p = 1 and NaN + * outside the domain */ +static const sf_ref2_t gammaincinv_cases[] = { + { 0.99999999999999989, 0.5, 0.69314718055994506 }, + { 0.0018725572425875394, 0.93432222410629528, 9.8708778280225384e-17 }, + { 1.4851015014453666e-07, 0.99989259056538193, 4.2708929514115105e-315 }, + { 9.9999999999999694e-311, 0.95988221384026817, NAN }, + { 9.9999999999999694e-311, 0.56112084484672486, NAN }, + { 1.0, 0.64358723829337949, 1.0316657767689139 }, + { 1.3693230946091463e+32, 0.84677972577643534, 1.3693230946091465e+32 }, + { 3.3463277181277915, 0.99999999999894673, 34.949768724325295 }, + { 22.041778641418698, 0.093156553752253735, 16.126803358230266 }, + { 1e-10, 0.99999999999999989, 11.214230215647511 }, + { 2.0, 4.9406564584124654e-324, 3.1434555694052403e-162 }, + { 1000.0, 1e-300, 233.92836429052818 }, + { 1000.0, 0.999, 1100.5780982933145 }, + { 0.67948734660549959, 0.7818881580083944, 1.0450131885835172 }, + { 0.024285952691655305, 0.99728941525830839, 1.4475359182943457 }, + { 0.033000366354340456, 0.98377018057938537, 0.5706929538725517 }, + { 32.69007854626318, 0.99999999999999645, 98.692064965782848 }, + { 1e-300, 0.99999999989999999, 0.0 }, + { 1.0000000000000001e+300, 4.9406564584124654e-324, 1.0000000000000001e+300 }, + { 1e-300, 0.0, 0.0 }, + { 1e-300, 1.0, INFINITY }, + { 1e-300, 1.0000000000000002, NAN }, + { 1.0, 4.9406564584124654e-324, 4.9406564584124654e-324 }, + { 1000000.0, 9.9999999999999995e-21, 990765.90325837862 }, + { INFINITY, 4.9406564584124654e-324, NAN }, + { 2907.5441489134673, 0.85784200187994619, 2965.322214703659 }, + { 64.283331812787964, 0.98660725921411685, 83.323363883964191 }, + { 0.0024060602718259248, 0.17939292031798137, 4.1575279095986522e-311 }, + { 1e-300, -0.10000000000000001, NAN }, + { 1e-10, 0.99999999989999999, 0.2647369819114741 }, + { 0.5, 0.999, 5.4137830853313664 }, + { 100.0, 1e-300, 0.038006988916941875 }, + { 1000.0, 0.99999999989999999, 1214.4995558668779 }, + { 0.0, 4.9406564584124654e-324, NAN }, + { -1.0, 0.0, NAN }, + { NAN, 0.5, NAN }, + { 2.0, NAN, NAN }, + { 0.0001, 0.25, 0.0 }, + { 0.5, 0.25, 0.050765522133810782 }, + { 3.0, 0.94999999999999996, 6.2957936218719883 }, +}; + +/* mpmath psi(0, x) at 15 digits */ +static const sf_ref1_t digamma_mpmath[] = { + { -0.29999999999999999, 2.113309779635399 }, + { 1e-10, -10000000000.577215 }, + { 9.9999999999999995e-07, -1000000.57721402 }, + { 0.01, -100.56088545786866 }, + { 10.0, 2.2517525890667209 }, + { 100.0, 4.6001618527380872 }, + { 1000.0, 6.907255195648812 }, + { 100000.0, 11.512920464961896 }, + { 10000000000.0, 23.025850929890456 }, +}; + +/* mpmath psi(1, x) at 15 digits */ +static const sf_ref1_t trigamma_mpmath[] = { + { -0.29999999999999999, 13.945160267805722 }, + { 1e-10, 1e+20 }, + { 9.9999999999999995e-07, 1000000000001.645 }, + { 0.01, 10001.621213528313 }, + { 10.0, 0.10516633568168575 }, + { 100.0, 0.010050166663333571 }, + { 1000.0, 0.0010005001666666333 }, + { 100000.0, 1.0000050000166667e-05 }, + { 10000000000.0, 1.00000000005e-10 }, +}; + +/* Real part of mpmath log(beta(p, q)) at 15 digits */ +static const sf_ref2_t betaln_mpmath[] = { + { -0.29999999999999999, -0.59999999999999998, 0.41427032493334498 }, + { 1e-10, 2.0000000000000001e-10, 23.431316038048621 }, + { 9.9999999999999995e-07, 1.9999999999999999e-06, 14.220975666069149 }, + { 0.01, 0.02, 5.0103133506979862 }, + { 10.0, 20.0, -19.115327299887046 }, + { 100.0, 200.0, -192.13419227497894 }, + { 1000.0, 2000.0, -1911.8746142144516 }, + { 100000.0, 200000.0, -190958.88527911686 }, + { 10000000000.0, 20000000000.0, -19095425059.235638 }, +}; + +/* Log of mpmath hyp2f1 at 15 digits */ +static const sf_ref4_t hyp2f1_laplace_mpmath[] = { + { 984.72000000000003, 1954.22, 985.72000000000003, -1.1392534691231597, + -1478.1738051381913 }, + { 936.02999999999997, 1834.8299999999999, 938.02999999999997, -1.0739817123857025, + -1330.0059628227482 }, + { 413.54000000000002, 451.48000000000002, 414.54000000000002, -12.853557923685116, + -1181.3138708305196 }, + { 544.64999999999998, 1292.75, 545.64999999999998, -0.71439839463641541, + -693.46877093725595 }, + { 21.898, 43.078000000000003, 22.898, -1.2310276509604619, -31.917963510674785 }, + { 1000.0, 1007.931, 1001.0, -129.62015503875969, -4904.8528786755833 }, + { 42.006999999999998, 119.15700000000001, 43.006999999999998, -0.70922612322041212, + -59.975223456559483 }, + { 130.68000000000001, 1122.1800000000001, 132.68000000000001, -0.1533946760574047, + -152.42035404495687 }, + { 121.70999999999999, 802.61000000000001, 124.70999999999999, -0.80594900849858353, + -303.45631195318833 }, +}; + +/* Log of mpmath hyp2f1 at 15 digits, for z / (z - 1) close to one */ +static const sf_ref4_t hyp2f1_laplace_unity_mpmath[] = { + { 0.0012723999999999999, 202.86627240000001, 1.0012724, -6614020190.5935307, + -0.036261751566401573 }, + { 0.0012612000000000001, 1001.9992612000001, 3.0012612000000001, -141574796.04867145, + -0.031220448825817738 }, + { 0.0011992999999999999, 157.77919929999999, 1.0011992999999999, -1146235430.4403243, + -0.031774253197474109 }, + { 0.00097179999999999999, 1000.0009718, 1.0009718000000001, -158137496.57453805, + -0.025619221224780213 }, + { 0.00097110000000000002, 405.48297110000004, 1.0009710999999999, + -276526839.68553674, -0.025266157355002965 }, + { 0.0015548999999999999, 115.7745549, 1.0015548999999999, -31061255169.177708, + -0.045842304967148521 }, + { 0.0010028000000000001, 73.491902799999991, 1.0010028, -53058551695.758659, + -0.029644174580337579 }, + { 0.0015053, 19.999605300000002, 2.0015052999999998, -178245782075.18933, + -0.042831241419712583 }, +}; + +/* Log of mpmath hyperu at 15 digits, and its derivative with respect to x */ +static const sf_hyperu_ref_t hyperu_laplace_mpmath[] = { + { 1.0, 4.3380000000000001, 0.7752291021399601, 2.6258894260525927, + -3.3991838624960096 }, + { 1.0, 4.6779999999999999, 0.76981102428276016, 3.1203053508031515, + -3.8351394948119681 }, + { 2.0, 5.9990000000000006, 5.1995955076999998, -2.202169012479116, + -0.57735145331711235 }, + { 9.0, 14.251000000000001, 2.5473150302860001, -1.5490292494382205, + -4.9021077003749038 }, + { 4.0, 18.460000000000001, 11.246026052960001, -3.7214576615414909, + -0.90331659933332087 }, + { 2.0, 2.9990000000000001, 3.7769370770299999, -2.6582253243210303, + -0.52944685391153801 }, +}; + +/* Log of mpmath hyp1f1 at 15 digits */ +static const sf_ref3_t hyp1f1_laplace_mpmath[] = { + { 132.47999999999999, 133.47999999999999, 170.98504810547999, 170.15807254764488 }, + { 997.09000000000003, 999.09000000000003, 1492.6979568568001, 1490.8690564465708 }, + { 978.24000000000001, 979.24000000000001, 1031.693903284, 1030.9740566223463 }, + { 713.51999999999998, 722.51999999999998, 739.07796118750002, 732.72108850452321 }, + { 999.99000000000001, 1003.99, 2916.7083719407506, 2911.2536982489523 }, + { 989.08000000000004, 992.08000000000004, 1125.8335771375, 1123.5567170478762 }, + { 28.545999999999999, 29.545999999999999, 38.4316856035, 37.587465253533537 }, + { 30.956, 31.956, 28.834237509375001, 28.184054387129486 }, +}; + static void -test_polygamma(void) +test_digamma(void) { - const double points[] = { 1e-6, 0.5, 4.9, 8.4, 10.0, 100.0, -0.5, -1.5, -10.5 }; - const int num_points = (int) (sizeof(points) / sizeof(points[0])); + const size_t num_cases = sizeof(digamma_cases) / sizeof(*digamma_cases); + const size_t num_refs = sizeof(digamma_mpmath) / sizeof(*digamma_mpmath); + const sf_case1_t *row; double value; - int j, ret; + size_t j; + int ret; - for (j = 0; j < num_points; j++) { - ret = tsd_digamma(points[j], &value); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(isfinite(value)); - ret = tsd_trigamma(points[j], &value); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(isfinite(value)); + for (j = 0; j < num_cases; j++) { + row = &digamma_cases[j]; + ret = tsd_digamma(row->x, &value); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0) { + assert_close_ulps(value, row->expected, ULPS); + } + } + for (j = 0; j < num_refs; j++) { + ret = tsd_digamma(digamma_mpmath[j].x, &value); + CU_ASSERT_EQUAL_FATAL(ret, 0); + assert_close_tol( + value, digamma_mpmath[j].expected, POLYGAMMA_RTOL, POLYGAMMA_ATOL); } - /* NaN is in-band */ - ret = tsd_digamma(NAN, &value); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(isnan(value)); - ret = tsd_trigamma(NAN, &value); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(isnan(value)); } static void -test_polygamma_poles(void) +test_trigamma(void) { + const size_t num_cases = sizeof(trigamma_cases) / sizeof(*trigamma_cases); + const size_t num_refs = sizeof(trigamma_mpmath) / sizeof(*trigamma_mpmath); + const sf_case1_t *row; double value; + size_t j; int ret; - ret = tsd_digamma(0.0, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - ret = tsd_trigamma(0.0, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - /* x ** 2 underflows to zero */ - ret = tsd_trigamma(1e-300, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + for (j = 0; j < num_cases; j++) { + row = &trigamma_cases[j]; + ret = tsd_trigamma(row->x, &value); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0) { + assert_close_ulps(value, row->expected, ULPS); + } + } + for (j = 0; j < num_refs; j++) { + ret = tsd_trigamma(trigamma_mpmath[j].x, &value); + CU_ASSERT_EQUAL_FATAL(ret, 0); + assert_close_tol( + value, trigamma_mpmath[j].expected, POLYGAMMA_RTOL, POLYGAMMA_ATOL); + } } static void test_betaln(void) { - double value = tsd_betaln(2.0, 3.0); - - CU_ASSERT_DOUBLE_EQUAL(value, log(1.0 / 12.0), 1e-12); -} - -static void -test_gammainc_der(void) -{ - /* - * x == 0, x > xbig, gaussian, series and continued fraction regimes, and a - * continued fraction that is rescaled to avoid overflow - */ - const double points[][2] = { { 1.0, 0.0 }, { 5.0, 1e9 }, { 2000.0, 2000.0 }, - { 2.0, 1.5 }, { 5.0, 50.0 }, { 100.0, 110.0 } }; - const int num_points = (int) (sizeof(points) / sizeof(points[0])); + const size_t num_cases = sizeof(betaln_cases) / sizeof(*betaln_cases); + const size_t num_refs = sizeof(betaln_mpmath) / sizeof(*betaln_mpmath); + const sf_ref2_t *row; double value; - int j, ret; + size_t j; - for (j = 0; j < num_points; j++) { - ret = tsd_gammainc_der(points[j][0], points[j][1], &value); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(isfinite(value)); + for (j = 0; j < num_cases; j++) { + row = &betaln_cases[j]; + value = tsd_betaln(row->x, row->y); + assert_close_ulps(value, row->expected, ULPS); + } + for (j = 0; j < num_refs; j++) { + row = &betaln_mpmath[j]; + value = tsd_betaln(row->x, row->y); + assert_close_tol(value, row->expected, POLYGAMMA_RTOL, POLYGAMMA_ATOL); } - /* Series or continued fraction with a very small value: truncated to zero */ - ret = tsd_gammainc_der(50.0, 1e-3, &value); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_EQUAL(value, 0.0); - ret = tsd_gammainc_der(5.0, 800.0, &value); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_EQUAL(value, 0.0); } static void -test_gammainc_der_errors(void) +test_gammainc_der(void) { + const size_t num_cases = sizeof(gammainc_der_cases) / sizeof(*gammainc_der_cases); + const sf_case2_t *row; double value; + size_t j; int ret; - ret = tsd_gammainc_der(-1.0, 1.0, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - ret = tsd_gammainc_der(1.0, -1.0, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - ret = tsd_gammainc_der(NAN, 1.0, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); + for (j = 0; j < num_cases; j++) { + row = &gammainc_der_cases[j]; + ret = tsd_gammainc_der(row->p, row->x, &value); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0) { + assert_close_ulps(value, row->expected, ULPS); + } + } } static void test_hyperu_laplace(void) { + const size_t num_cases + = sizeof(hyperu_laplace_cases) / sizeof(*hyperu_laplace_cases); + const size_t num_refs + = sizeof(hyperu_laplace_mpmath) / sizeof(*hyperu_laplace_mpmath); + const sf_hyperu_case_t *row; + const sf_hyperu_ref_t *ref; double value, dvalue; + size_t j; int ret; - ret = tsd_hyperu_laplace(1.0, 2.0, 1.0, &value, &dvalue); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(isfinite(value)); - CU_ASSERT(isfinite(dvalue)); -} - -static void -test_hyperu_laplace_errors(void) -{ - double value, dvalue; - int ret; - - ret = tsd_hyperu_laplace(1.0, 0.5, 1.0, &value, &dvalue); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - ret = tsd_hyperu_laplace(0.0, 1.0, 1.0, &value, &dvalue); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - ret = tsd_hyperu_laplace(1.0, 2.0, 0.0, &value, &dvalue); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - ret = tsd_hyperu_laplace(1.0, 2.0, NAN, &value, &dvalue); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - /* The Laplace root divides by zero */ - ret = tsd_hyperu_laplace(1.0, 2.0, 1e300, &value, &dvalue); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - ret = tsd_hyperu_laplace(1.0, 2.0, INFINITY, &value, &dvalue); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + for (j = 0; j < num_cases; j++) { + row = &hyperu_laplace_cases[j]; + ret = tsd_hyperu_laplace(row->a, row->b, row->x, &value, &dvalue); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0) { + assert_close_ulps(value, row->value, ULPS); + assert_close_ulps(dvalue, row->dvalue, ULPS); + } + } + for (j = 0; j < num_refs; j++) { + ref = &hyperu_laplace_mpmath[j]; + ret = tsd_hyperu_laplace(ref->a, ref->b, ref->x, &value, &dvalue); + CU_ASSERT_EQUAL_FATAL(ret, 0); + assert_close_tol(value, ref->value, LAPLACE_RTOL, LAPLACE_ATOL); + assert_close_tol(dvalue, ref->dvalue, HYPERU_DERIVATIVE_RTOL, LAPLACE_ATOL); + } } static void test_hyp1f1_laplace(void) { + const size_t num_cases + = sizeof(hyp1f1_laplace_cases) / sizeof(*hyp1f1_laplace_cases); + const size_t num_refs + = sizeof(hyp1f1_laplace_mpmath) / sizeof(*hyp1f1_laplace_mpmath); + const sf_case3_t *row; + const sf_ref3_t *ref; double value; + size_t j; int ret; - ret = tsd_hyp1f1_laplace(1.0, 2.0, 1.0, &value); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(isfinite(value)); - ret = tsd_hyp1f1_laplace(1.0, 2.0, 0.0, &value); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_EQUAL(value, 0.0); + for (j = 0; j < num_cases; j++) { + row = &hyp1f1_laplace_cases[j]; + ret = tsd_hyp1f1_laplace(row->a, row->b, row->x, &value); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0) { + assert_close_ulps(value, row->expected, ULPS); + } + } + for (j = 0; j < num_refs; j++) { + ref = &hyp1f1_laplace_mpmath[j]; + ret = tsd_hyp1f1_laplace(ref->a, ref->b, ref->x, &value); + CU_ASSERT_EQUAL_FATAL(ret, 0); + assert_close_tol(value, ref->expected, LAPLACE_RTOL, LAPLACE_ATOL); + } } +/* Compare tsd_hyp2f1_laplace with `num_refs` mpmath values to within `rtol`. */ static void -test_hyp1f1_laplace_errors(void) +check_hyp2f1_laplace_mpmath(const sf_ref4_t *refs, size_t num_refs, double rtol) { double value; + size_t j; int ret; - ret = tsd_hyp1f1_laplace(1.0, 1.0, 1.0, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - ret = tsd_hyp1f1_laplace(0.0, 1.0, 1.0, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - ret = tsd_hyp1f1_laplace(1e-10, 2e-10, 1e8, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + for (j = 0; j < num_refs; j++) { + ret = tsd_hyp2f1_laplace(refs[j].a, refs[j].b, refs[j].c, refs[j].x, &value); + CU_ASSERT_EQUAL_FATAL(ret, 0); + assert_close_tol(value, refs[j].expected, rtol, LAPLACE_ATOL); + } } static void test_hyp2f1_laplace(void) { - /* The interior, z < 0 and the three unity limits, including negative z */ - const double args[][4] = { { 1.0, 2.0, 3.0, 0.5 }, { 1.0, 2.0, 3.0, -0.5 }, - { 1.0, 2.0, 3.0, 0.0 }, { 2.0, 3.0, 4.0, 1 - 1e-8 }, { 1.0, 2.0, 5.0, 1 - 1e-8 }, - { 1.0, 2.0, 3.0, 1 - 1e-8 }, { 2.0, 3.0, 4.0, -1e8 }, { 3.0, 2.0, 5.0, -1e8 }, - { 2.0, 2.0, 5.0, -1e8 } }; - const int num_args = (int) (sizeof(args) / sizeof(args[0])); + const size_t num_cases + = sizeof(hyp2f1_laplace_cases) / sizeof(*hyp2f1_laplace_cases); + const size_t num_refs + = sizeof(hyp2f1_laplace_mpmath) / sizeof(*hyp2f1_laplace_mpmath); + const size_t num_unity_refs + = sizeof(hyp2f1_laplace_unity_mpmath) / sizeof(*hyp2f1_laplace_unity_mpmath); + const sf_case4_t *row; double value; - int j, ret; + size_t j; + int ret; - for (j = 0; j < num_args; j++) { - ret = tsd_hyp2f1_laplace(args[j][0], args[j][1], args[j][2], args[j][3], &value); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(isfinite(value)); + for (j = 0; j < num_cases; j++) { + row = &hyp2f1_laplace_cases[j]; + ret = tsd_hyp2f1_laplace(row->a, row->b, row->c, row->x, &value); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0) { + assert_close_ulps(value, row->expected, ULPS); + } } + check_hyp2f1_laplace_mpmath(hyp2f1_laplace_mpmath, num_refs, LAPLACE_RTOL); + check_hyp2f1_laplace_mpmath(hyp2f1_laplace_unity_mpmath, num_unity_refs, UNITY_RTOL); } static void -test_hyp2f1_laplace_errors(void) +test_gammaincinv(void) { + const size_t num_cases = sizeof(gammaincinv_cases) / sizeof(*gammaincinv_cases); + const sf_ref2_t *row; double value; - int ret; - - /* Each condition of the domain, and the root on the boundary */ - ret = tsd_hyp2f1_laplace(1.0, 2.0, 0.0, 0.5, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - ret = tsd_hyp2f1_laplace(-1.0, 2.0, 3.0, 0.5, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - ret = tsd_hyp2f1_laplace(1.0, -1.0, 3.0, 0.5, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - ret = tsd_hyp2f1_laplace(2.0, 1.0, 1.0, 0.5, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - ret = tsd_hyp2f1_laplace(1.0, 2.0, 3.0, 1.0, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - ret = tsd_hyp2f1_laplace(0.0, 1.0, 1.0, 0.5, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - /* z / (z - 1) rounds to one, outside the domain of the unity limit */ - ret = tsd_hyp2f1_laplace(1.0, 2.0, 3.0, -1e16, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - /* The Laplace root divides by zero */ - ret = tsd_hyp2f1_laplace(0.0, 1.0, 1e-300, 0.5, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - /* c == a, with a root that rounds into (0, 1) */ - ret = tsd_hyp2f1_laplace(1.1774154985086274, 504.4082462406216, 1.1774154985086274, - 0.1427180165924374, &value); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); -} + size_t j; -static void -test_gammaincinv(void) -{ - CU_ASSERT(isfinite(tsd_gammaincinv(0.5, 0.25))); - CU_ASSERT(isfinite(tsd_gammaincinv(1.0, 0.5))); - CU_ASSERT(isfinite(tsd_gammaincinv(3.0, 0.95))); - CU_ASSERT(isfinite(tsd_gammaincinv(1e4, 1e-10))); - CU_ASSERT_EQUAL(tsd_gammaincinv(2.0, 0.0), 0.0); - CU_ASSERT(isinf(tsd_gammaincinv(2.0, 1.0))); - /* p ** (1 / a) underflows */ - CU_ASSERT_EQUAL(tsd_gammaincinv(1e-4, 0.25), 0.0); - CU_ASSERT(isnan(tsd_gammaincinv(NAN, 0.5))); - CU_ASSERT(isnan(tsd_gammaincinv(2.0, NAN))); - CU_ASSERT(isnan(tsd_gammaincinv(-1.0, 0.5))); - CU_ASSERT(isnan(tsd_gammaincinv(2.0, 1.5))); + for (j = 0; j < num_cases; j++) { + row = &gammaincinv_cases[j]; + value = tsd_gammaincinv(row->x, row->y); + assert_close_tol(value, row->expected, GAMMAINCINV_RTOL, 0); + } } static void @@ -3273,17 +3636,13 @@ main(int argc, char **argv) { "test_strerror_unknown", test_strerror_unknown }, { "test_trace_error", test_trace_error }, { "test_safe_free", test_safe_free }, - { "test_polygamma", test_polygamma }, - { "test_polygamma_poles", test_polygamma_poles }, + { "test_digamma", test_digamma }, + { "test_trigamma", test_trigamma }, { "test_betaln", test_betaln }, { "test_gammainc_der", test_gammainc_der }, - { "test_gammainc_der_errors", test_gammainc_der_errors }, { "test_hyperu_laplace", test_hyperu_laplace }, - { "test_hyperu_laplace_errors", test_hyperu_laplace_errors }, { "test_hyp1f1_laplace", test_hyp1f1_laplace }, - { "test_hyp1f1_laplace_errors", test_hyp1f1_laplace_errors }, { "test_hyp2f1_laplace", test_hyp2f1_laplace }, - { "test_hyp2f1_laplace_errors", test_hyp2f1_laplace_errors }, { "test_gammaincinv", test_gammaincinv }, { "test_approximate_log_moments", test_approximate_log_moments }, { "test_approximate_gamma_kl", test_approximate_gamma_kl }, From 6a00973b006c9244187902183b7ae824a3768b0d Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 17:13:16 -0800 Subject: [PATCH 49/56] Test rescaling, priors and damping against tables of reference values --- lib/tests/tests.c | 1929 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 1652 insertions(+), 277 deletions(-) diff --git a/lib/tests/tests.c b/lib/tests/tests.c index 2d90ea43..4f3d7702 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -26,8 +26,8 @@ * Smoke tests for the low-level tsdate API: return codes, error paths and memory * handling, with coarse sanity checks of results (finite, NaN, simple values). * Numerical correctness is tested from Python, except for the expectation - * propagation passes on states set directly in the library's struct, which have - * tables of expected values. + * propagation passes on states set directly in the library's struct, and the + * rescaling, prior and damping functions, which have tables of expected values. */ #include @@ -87,6 +87,16 @@ assert_close_tol(double actual, double expected, double rtol, double atol) } } +static void +assert_array_close(const double *actual, const double *expected, tsd_size_t n) +{ + tsd_size_t j; + + for (j = 0; j < n; j++) { + assert_close_ulps(actual[j], expected[j], ULPS); + } +} + static void test_strerror(void) { @@ -1500,260 +1510,1441 @@ test_bad_tree_arguments(void) TSD_ERR_EDGES_FORM_CYCLE); } +/* ---- priors ---- */ + +#define TABLE_MAX_TIPS 20 +#define TABLE_MAX_MARGINAL_TIPS 10 +#define TABLE_MAX_MOMENTS 3 + +typedef struct { + tsd_size_t num_tips; + tsd_size_t num_moments; + double val[TABLE_MAX_MARGINAL_TIPS * TABLE_MAX_MOMENTS]; + double out[(TABLE_MAX_MARGINAL_TIPS + 1) * TABLE_MAX_MOMENTS]; + int ret; +} marginalize_row_t; + +typedef struct { + tsd_size_t num_tips; + double variance[TABLE_MAX_TIPS + 1]; + int ret; +} variance_row_t; + +/* Expected values of the reference implementation */ +static const marginalize_row_t marginalize_rows[] = { + { .num_tips = 2, + .num_moments = 2, + .val = { 1, 2, 3, 4 }, + .out = { 0, 0, 0, 0, 3, 4 }, + .ret = 0 }, + { .num_tips = 3, + .num_moments = 2, + .val = { 6.405920704482398, 2.770888466262316, 0.5056378869683275, + 0.26362359173243805, 8.151375368082697, 9.136280215049444 }, + .out = { 0, 0, 0, 0, 8.151375368082697, 9.136280215049444, 0.5056378869683275, + 0.26362359173243805 }, + .ret = 0 }, + { .num_tips = 6, + .num_moments = 1, + .val = { 6.105694180095081, 7.322015953741584, 5.481887415507686, + 9.357216995498906, 8.176950185803168, 0.12711115168446616 }, + .out = { 0, 0, 4.1943175516834055, 8.11004435562237, 7.419552205503297, + 5.481887415507686, 7.322015953741584 }, + .ret = 0 }, + { .num_tips = 5, + .num_moments = 3, + .val = { 8.588302338216936, 0.43249719552409716, 7.323588919656446, + 1.8389906439653343, 8.645471331263877, 5.4604660804660075, + 3.0671477163201097, 4.284603489856819, 0.3803647443400834, + 1.3304044373456831, 6.73918170546694, 6.507176164585076, 6.192312603664413, + 3.8984077871926464, 9.972378364313188 }, + .out = { 0, 0, 0, 0, 0, 0, 4.421223665034365, 4.789259532941353, + 7.973616342397445, 2.025101748935454, 5.757350419222893, 4.056451596487079, + 3.0671477163201097, 4.284603489856819, 0.3803647443400834, + 1.8389906439653343, 8.645471331263877, 5.4604660804660075 }, + .ret = 0 }, + { .num_tips = 10, + .num_moments = 2, + .val = { 9.810269853884678, 6.886865646358878, 6.5395468350513815, + 6.9156226326523065, 3.9503220973931277, 1.437455399721871, 7.242734567921409, + 5.301007792509686, 3.1713945680336613, 4.909770052434712, 8.905929560055103, + 9.347030807966872, 3.6421724474197954, 5.758145324224633, 3.2865069716518276, + 5.983570298976998, 3.4453211325206197, 3.9770281052287966, 8.913716084847444, + 2.3488601759804593 }, + .out = { 0, 0, 0, 0, 5.623151605758174, 4.568435971625975, 4.799050195244742, + 5.94494257642139, 5.422355848514381, 5.987743974404029, 5.5903751937122115, + 5.348623913661779, 5.40321218005653, 4.413497494215927, 5.163430081689842, + 3.4458516438653746, 4.938045838551611, 2.5965211175582152, + 3.9503220973931277, 1.437455399721871, 6.5395468350513815, + 6.9156226326523065 }, + .ret = 0 }, + { .num_tips = 8, + .num_moments = 2, + .val = { 0, 0, 1.75, 4.21937641723356, 0.75, 0.71937641723356, + 0.41666666666666663, 0.21937641723356005, 0.25, 0.08048752834467121, 0.15, + 0.0304875283446712, 0.08333333333333333, 0.0104875283446712, + 0.03571428571428571, 0.002551020408163265 }, + .out = { 0, 0, 0, 0, 0.125, 0.04243197278911563, 0.25000000000000006, + 0.12064625850340137, 0.3750000000000001, 0.23028911564625854, 0.5, + 0.3681859410430839, 0.625, 0.53187641723356, 0.75, 0.71937641723356, 1.75, + 4.21937641723356 }, + .ret = 0 }, + { .num_tips = 6, + .num_moments = 2, + .val = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + .out = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + .ret = 0 }, + { .num_tips = 6, + .num_moments = 2, + .val = { NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN }, + .out = { 0, 0, 0, 0, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN }, + .ret = 0 }, + /* NOTE: non-finite values are propagated by the weighted sum, with no checks */ + { .num_tips = 4, + .num_moments = 2, + .val = { 1, 2, INFINITY, 1, 3, 3, 1, NAN }, + .out = { 0, 0, 0, 0, 1.5, NAN, 3, 3, INFINITY, 1 }, + .ret = 0 }, + { .num_tips = 1, .num_moments = 2, .val = { 1, 2 }, .ret = TSD_ERR_TOO_FEW_TIPS }, +}; + +/* Expected values of the reference implementation */ +static const variance_row_t variance_rows[] = { + /* a single tip has zero variance */ + { .num_tips = 1, .variance = { 0, 0 }, .ret = 0 }, + { .num_tips = 2, .variance = { 0, 0, 1 }, .ret = 0 }, + { .num_tips = 3, + .variance = { 0, 0, 0.1111111111111111, 1.1111111111111112 }, + .ret = 0 }, + { .num_tips = 4, + .variance = { 0, 0, 0.0763888888888889, 0.1388888888888889, 1.1388888888888888 }, + .ret = 0 }, + { .num_tips = 5, + .variance = { 0, 0, 0.05555555555555555, 0.10888888888888887, + 0.14888888888888885, 1.148888888888889 }, + .ret = 0 }, + { .num_tips = 7, + .variance + = { 0, 0, 0.033197278911564626, 0.07034013605442176, 0.10571428571428576, + 0.13519274376417229, 0.15560090702947849, 1.1556009070294788 }, + .ret = 0 }, + { .num_tips = 10, + .variance + = { 0, 0, 0.018567019400352734, 0.041611237087427574, 0.06639581758629377, + 0.09089317208364828, 0.11351221970269593, 0.13295666414714036, + 0.1481418493323255, 0.15814184933232545, 1.158141849332326 }, + .ret = 0 }, + { .num_tips = 15, + .variance = { 0, 0, 0.009275031033272787, 0.021737639649727542, + 0.03624521961185298, 0.051927046202770555, 0.06808446902686013, + 0.0841377367467945, 0.09959413220318991, 0.11402731806494726, + 0.1270631711007999, 0.13836964240727112, 0.1476492516868806, + 0.15463337867100768, 0.15907782311545215, 1.1590778231154522 }, + .ret = 0 }, + { .num_tips = 20, + .variance = { 0, 0, 0.005572819114451828, 0.013375800851143278, + 0.022807509758699017, 0.033400737695193194, 0.04477484272918324, + 0.05660993547639791, 0.068631190860954, 0.08059855293878618, + 0.09229959605553426, 0.10354436416820739, 0.11416151633721722, + 0.12399537093168672, 0.1329035891897501, 0.14075532637585275, + 0.1474297329805997, 0.1528147232340108, 0.15680595130418618, + 0.15930595130418657, 1.1593059513041868 }, + .ret = 0 }, + { .num_tips = 0, .ret = TSD_ERR_TOO_FEW_TIPS }, +}; + +static void +test_marginalize_over_ancestors(void) +{ + const size_t num_rows = sizeof(marginalize_rows) / sizeof(marginalize_rows[0]); + const marginalize_row_t *row; + double out[(TABLE_MAX_MARGINAL_TIPS + 1) * TABLE_MAX_MOMENTS]; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = marginalize_rows + j; + ret = tsd_marginalize_over_ancestors( + row->num_tips, row->num_moments, row->val, out); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_array_close(out, row->out, (row->num_tips + 1) * row->num_moments); + } + } +} + static void test_conditional_coalescent_variance(void) { - const double val[] = { 1.0, 2.0, 3.0, 4.0 }; - double out[6], variance[11]; + const size_t num_rows = sizeof(variance_rows) / sizeof(variance_rows[0]); + const variance_row_t *row; + double variance[TABLE_MAX_TIPS + 1]; + size_t j; int ret; - int j; - ret = tsd_marginalize_over_ancestors(2, 2, val, out); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_EQUAL(out[4], 3.0); - ret = tsd_conditional_coalescent_variance(1, variance); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_EQUAL(variance[1], 0.0); - ret = tsd_conditional_coalescent_variance(10, variance); - CU_ASSERT_EQUAL(ret, 0); - for (j = 2; j <= 10; j++) { - CU_ASSERT(variance[j] > 0.0); + for (j = 0; j < num_rows; j++) { + row = variance_rows + j; + ret = tsd_conditional_coalescent_variance(row->num_tips, variance); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_array_close(variance, row->variance, row->num_tips + 1); + } } - ret = tsd_marginalize_over_ancestors(1, 2, val, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_TOO_FEW_TIPS); - ret = tsd_conditional_coalescent_variance(0, variance); - CU_ASSERT_EQUAL(ret, TSD_ERR_TOO_FEW_TIPS); } /* ---- rescaling ---- */ -static void -test_fixed_changepoints(void) -{ - const double counts[] = { 1.0, 2.0, 3.0, 4.0 }; - const double zeros[] = { 0.0, 0.0 }; - tsd_id_t *breaks = NULL; +#define TABLE_MAX_COUNTS 8 +#define TABLE_MAX_BREAKS 12 +#define TABLE_MAX_NODES 6 +#define TABLE_MAX_EDGES 4 +#define TABLE_MAX_MUTATIONS 5 +#define TABLE_MAX_POINTS 5 +#define TABLE_MAX_POSTERIORS 4 + +typedef struct { + tsd_size_t num_counts; + double counts[TABLE_MAX_COUNTS]; + int64_t epochs; tsd_size_t num_breaks; + tsd_id_t breaks[TABLE_MAX_BREAKS]; int ret; +} changepoints_row_t; - ret = tsd_fixed_changepoints(4, counts, 2, &breaks, &num_breaks); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_EQUAL(num_breaks, 3); - CU_ASSERT_EQUAL(breaks[0], 0); - CU_ASSERT_EQUAL(breaks[2], 4); - tsd_safe_free(breaks); - /* no counts: NaN cumulative distribution, and no observations at all */ - ret = tsd_fixed_changepoints(2, zeros, 3, &breaks, &num_breaks); - CU_ASSERT_EQUAL(ret, 0); - tsd_safe_free(breaks); - ret = tsd_fixed_changepoints(0, counts, 1, &breaks, &num_breaks); - CU_ASSERT_EQUAL(ret, 0); - tsd_safe_free(breaks); - ret = tsd_fixed_changepoints(4, counts, 0, &breaks, &num_breaks); - CU_ASSERT_EQUAL(ret, TSD_ERR_NONPOSITIVE_INTERVALS); -} +typedef struct { + tsd_size_t num_nodes; + uint8_t is_sample[TABLE_MAX_NODES]; + tsd_size_t num_mutations; + tsd_id_t mutations_node[TABLE_MAX_MUTATIONS]; + double mutations_position[TABLE_MAX_MUTATIONS]; + tsd_size_t num_edges; + tsd_id_t edges_parent[TABLE_MAX_EDGES]; + tsd_id_t edges_child[TABLE_MAX_EDGES]; + double edges_left[TABLE_MAX_EDGES]; + double edges_right[TABLE_MAX_EDGES]; + tsd_id_t indexes_insert[TABLE_MAX_EDGES]; + tsd_id_t indexes_remove[TABLE_MAX_EDGES]; + double sequence_length; + int size_biased; + double edges_stats[TABLE_MAX_EDGES][2]; + tsd_id_t mutations_edge[TABLE_MAX_MUTATIONS]; +} count_mutations_row_t; + +typedef struct { + tsd_size_t num_nodes; + double nodes_time[TABLE_MAX_NODES]; + tsd_size_t num_edges; + double likelihoods[TABLE_MAX_EDGES][2]; + tsd_id_t edges_parent[TABLE_MAX_EDGES]; + tsd_id_t edges_child[TABLE_MAX_EDGES]; + tsd_size_t num_epochs; + double counts[TABLE_MAX_NODES]; + double offset[TABLE_MAX_NODES]; + double duration[TABLE_MAX_NODES]; + tsd_id_t nodes_index[TABLE_MAX_NODES]; +} area_row_t; + +typedef struct { + tsd_size_t num_nodes; + double nodes_time[TABLE_MAX_NODES]; + tsd_size_t num_edges; + double likelihoods[TABLE_MAX_EDGES][2]; + tsd_id_t edges_parent[TABLE_MAX_EDGES]; + tsd_id_t edges_child[TABLE_MAX_EDGES]; + int64_t max_intervals; + tsd_size_t num_breaks; + double origin[TABLE_MAX_NODES]; + double adjust[TABLE_MAX_NODES]; + int ret; +} timescale_row_t; + +typedef struct { + tsd_size_t num_points; + double estimate[TABLE_MAX_POINTS]; + uint8_t fixed[TABLE_MAX_POINTS]; + tsd_size_t num_breaks; + double original[TABLE_MAX_BREAKS]; + double rescaled[TABLE_MAX_BREAKS]; + double out[TABLE_MAX_POINTS]; + int ret; +} point_row_t; + +typedef struct { + tsd_size_t num_posteriors; + double posteriors[TABLE_MAX_POSTERIORS][2]; + uint8_t fixed[TABLE_MAX_POSTERIORS]; + tsd_size_t num_breaks; + double original[TABLE_MAX_BREAKS]; + double rescaled[TABLE_MAX_BREAKS]; + double quantile_width; + double max_shape; + double out[TABLE_MAX_POSTERIORS][2]; + int ret; +} posterior_row_t; + +/* Expected values of the reference implementation */ +static const changepoints_row_t changepoints_rows[] = { + { .num_counts = 3, + .counts = { 1, 2, 3 }, + .epochs = 1, + .num_breaks = 2, + .breaks = { 0, 3 }, + .ret = 0 }, + { .num_counts = 1, + .counts = { 5 }, + .epochs = 1, + .num_breaks = 2, + .breaks = { 0, 1 }, + .ret = 0 }, + { .num_counts = 4, + .counts = { 0, 0, 4, 0 }, + .epochs = 1, + .num_breaks = 2, + .breaks = { 0, 4 }, + .ret = 0 }, + { .num_counts = 3, + .counts = { 1, 2, 3 }, + .epochs = 10, + .num_breaks = 11, + .breaks = { 0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 3 }, + .ret = 0 }, + { .num_counts = 4, + .counts = { 0, 0, 4, 0 }, + .epochs = 4, + .num_breaks = 5, + .breaks = { 0, 2, 2, 2, 4 }, + .ret = 0 }, + { .num_counts = 4, + .counts = { 0, 0, 5, 5 }, + .epochs = 3, + .num_breaks = 4, + .breaks = { 0, 2, 3, 4 }, + .ret = 0 }, + { .num_counts = 4, + .counts = { 5, 5, 0, 0 }, + .epochs = 3, + .num_breaks = 4, + .breaks = { 0, 0, 1, 4 }, + .ret = 0 }, + { .num_counts = 5, + .counts = { 0, 5, 0, 5, 0 }, + .epochs = 3, + .num_breaks = 4, + .breaks = { 0, 1, 3, 5 }, + .ret = 0 }, + { .num_counts = 4, + .counts = { 1, 1, 1, 1 }, + .epochs = 4, + .num_breaks = 5, + .breaks = { 0, 1, 2, 3, 4 }, + .ret = 0 }, + { .num_counts = 4, + .counts = { 1, 1, 1, 1 }, + .epochs = 2, + .num_breaks = 3, + .breaks = { 0, 2, 4 }, + .ret = 0 }, + { .num_counts = 8, + .counts = { 1.0730290263725388, 0.30845314412528435, 5.375436872608127, + 0.36642711289983193, 0.11536203910680366, 1.7997970856557877, + 0.498639097854449, 0.5514213768237073 }, + .epochs = 3, + .num_breaks = 4, + .breaks = { 0, 2, 2, 8 }, + .ret = 0 }, + { .num_counts = 8, + .counts = { 2.073029026372539, 0, 5.375436872608127, 0.36642711289983193, 0, + 1.7997970856557877, 0.498639097854449, 0.5514213768237073 }, + .epochs = 5, + .num_breaks = 6, + .breaks = { 0, 2, 2, 2, 5, 8 }, + .ret = 0 }, + /* NOTE: current behaviour, possibly a bug: with no counts the cumulative + distribution is 0 / 0 = NaN, so every breakpoint but the last is -1 */ + { .num_counts = 3, + .counts = { 0, 0, 0 }, + .epochs = 3, + .num_breaks = 4, + .breaks = { -1, -1, -1, 3 }, + .ret = 0 }, + { .num_counts = 0, + .epochs = 3, + .num_breaks = 4, + .breaks = { -1, -1, -1, 0 }, + .ret = 0 }, + { .num_counts = 2, + .counts = { 1, 2 }, + .epochs = 0, + .ret = TSD_ERR_NONPOSITIVE_INTERVALS }, + { .num_counts = 2, + .counts = { 1, 2 }, + .epochs = -1, + .ret = TSD_ERR_NONPOSITIVE_INTERVALS }, +}; static void -test_poisson_changepoints(void) +test_fixed_changepoints(void) { - const double counts[] = { 5.0, 6.0, 20.0, 22.0, 21.0, 3.0 }; - const double offset[] = { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; + const size_t num_rows = sizeof(changepoints_rows) / sizeof(changepoints_rows[0]); + const changepoints_row_t *row; tsd_id_t *breaks = NULL; - tsd_size_t num_breaks; + tsd_size_t num_breaks, k; + size_t j; int ret; - ret = tsd_poisson_changepoints( - 6, counts, offset, 2.0, 0.0, 0.0, &breaks, &num_breaks); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(num_breaks >= 2); - CU_ASSERT_EQUAL(breaks[0], 0); - CU_ASSERT_EQUAL(breaks[num_breaks - 1], 6); - tsd_safe_free(breaks); - /* thresholds that rule out short segments */ - ret = tsd_poisson_changepoints( - 6, counts, offset, 2.0, 21.0, 1.5, &breaks, &num_breaks); - CU_ASSERT_EQUAL(ret, 0); - tsd_safe_free(breaks); - ret = tsd_poisson_changepoints( - 0, counts, offset, 2.0, 0.0, 0.0, &breaks, &num_breaks); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_EQUAL(num_breaks, 1); - tsd_safe_free(breaks); - ret = tsd_poisson_changepoints( - 6, counts, offset, -1.0, 0.0, 0.0, &breaks, &num_breaks); - CU_ASSERT_EQUAL(ret, TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER); - ret = tsd_poisson_changepoints( - 6, counts, offset, 2.0, NAN, 0.0, &breaks, &num_breaks); - CU_ASSERT_EQUAL(ret, TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER); + for (j = 0; j < num_rows; j++) { + row = changepoints_rows + j; + ret = tsd_fixed_changepoints( + row->num_counts, row->counts, row->epochs, &breaks, &num_breaks); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + CU_ASSERT_EQUAL_FATAL(num_breaks, row->num_breaks); + for (k = 0; k < num_breaks; k++) { + CU_ASSERT_EQUAL(breaks[k], row->breaks[k]); + } + } + tsd_safe_free(breaks); + breaks = NULL; + } } -/* - * Two samples (nodes 0 and 1) below a root (node 2), with edges over [0, 10), and a - * mutation on each sample branch and one above the root. - */ +/* Expected values of the reference implementation */ +static const count_mutations_row_t count_mutations_rows[] = { + /* a mutation above the root has no edge */ + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 4, + .mutations_node = { 0, 0, 1, 2 }, + .mutations_position = { 1, 2, 3, 5 }, + .num_edges = 2, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .edges_left = { 0, 0 }, + .edges_right = { 10, 10 }, + .indexes_insert = { 0, 1 }, + .indexes_remove = { 1, 0 }, + .sequence_length = 10, + .size_biased = 0, + .edges_stats = { { 2, 10 }, { 1, 10 } }, + .mutations_edge = { 0, 0, 1, -1 } }, + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 4, + .mutations_node = { 0, 0, 1, 2 }, + .mutations_position = { 1, 2, 3, 5 }, + .num_edges = 2, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .edges_left = { 0, 0 }, + .edges_right = { 10, 10 }, + .indexes_insert = { 0, 1 }, + .indexes_remove = { 1, 0 }, + .sequence_length = 10, + .size_biased = 1, + .edges_stats = { { 2, 10 }, { 1, 10 } }, + .mutations_edge = { 0, 0, 1, -1 } }, + /* no mutations */ + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 0, + .num_edges = 2, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .edges_left = { 0, 0 }, + .edges_right = { 10, 10 }, + .indexes_insert = { 0, 1 }, + .indexes_remove = { 1, 0 }, + .sequence_length = 10, + .size_biased = 0, + .edges_stats = { { 0, 10 }, { 0, 10 } } }, + /* no edges */ + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 1, + .mutations_node = { 0 }, + .mutations_position = { 1 }, + .num_edges = 0, + .sequence_length = 10, + .size_biased = 1, + .mutations_edge = { -1 } }, + /* no edges and no mutations */ + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 0, + .num_edges = 0, + .sequence_length = 10, + .size_biased = 0 }, + /* a mutation beyond the edge */ + { .num_nodes = 2, + .is_sample = { 1, 0 }, + .num_mutations = 2, + .mutations_node = { 0, 0 }, + .mutations_position = { 1, 5 }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_left = { 0 }, + .edges_right = { 4 }, + .indexes_insert = { 0 }, + .indexes_remove = { 0 }, + .sequence_length = 10, + .size_biased = 0, + .edges_stats = { { 1, 4 } }, + .mutations_edge = { 0, -1 } }, + { .num_nodes = 2, + .is_sample = { 1, 0 }, + .num_mutations = 2, + .mutations_node = { 0, 0 }, + .mutations_position = { 1, 5 }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_left = { 0 }, + .edges_right = { 4 }, + .indexes_insert = { 0 }, + .indexes_remove = { 0 }, + .sequence_length = 10, + .size_biased = 1, + .edges_stats = { { 1, 4 } }, + .mutations_edge = { 0, -1 } }, + /* a mutation in a gap between the edges of a node */ + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 2, + .mutations_node = { 0, 0 }, + .mutations_position = { 4, 5 }, + .num_edges = 3, + .edges_parent = { 2, 2, 2 }, + .edges_child = { 0, 0, 1 }, + .edges_left = { 0, 6, 0 }, + .edges_right = { 4, 10, 10 }, + .indexes_insert = { 0, 2, 1 }, + .indexes_remove = { 0, 2, 1 }, + .sequence_length = 10, + .size_biased = 0, + .edges_stats = { { 0, 4 }, { 0, 4 }, { 0, 10 } }, + .mutations_edge = { -1, -1 } }, + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 2, + .mutations_node = { 0, 0 }, + .mutations_position = { 4, 5 }, + .num_edges = 3, + .edges_parent = { 2, 2, 2 }, + .edges_child = { 0, 0, 1 }, + .edges_left = { 0, 6, 0 }, + .edges_right = { 4, 10, 10 }, + .indexes_insert = { 0, 2, 1 }, + .indexes_remove = { 0, 2, 1 }, + .sequence_length = 10, + .size_biased = 1, + .edges_stats = { { 0, 4 }, { 0, 4 }, { 0, 10 } }, + .mutations_edge = { -1, -1 } }, + /* a mutation at a breakpoint belongs to the tree on its right */ + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 2, + .mutations_node = { 0, 0 }, + .mutations_position = { 4.5, 5 }, + .num_edges = 3, + .edges_parent = { 2, 2, 2 }, + .edges_child = { 0, 0, 1 }, + .edges_left = { 0, 5, 0 }, + .edges_right = { 5, 10, 10 }, + .indexes_insert = { 0, 2, 1 }, + .indexes_remove = { 0, 2, 1 }, + .sequence_length = 10, + .size_biased = 0, + .edges_stats = { { 1, 5 }, { 1, 5 }, { 0, 10 } }, + .mutations_edge = { 0, 1 } }, + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 2, + .mutations_node = { 0, 0 }, + .mutations_position = { 4.5, 5 }, + .num_edges = 3, + .edges_parent = { 2, 2, 2 }, + .edges_child = { 0, 0, 1 }, + .edges_left = { 0, 5, 0 }, + .edges_right = { 5, 10, 10 }, + .indexes_insert = { 0, 2, 1 }, + .indexes_remove = { 0, 2, 1 }, + .sequence_length = 10, + .size_biased = 1, + .edges_stats = { { 1, 5 }, { 1, 5 }, { 0, 10 } }, + .mutations_edge = { 0, 1 } }, + /* counts weighted by the samples below the edge */ + { .num_nodes = 5, + .is_sample = { 1, 1, 1, 0, 0 }, + .num_mutations = 3, + .mutations_node = { 0, 3, 3 }, + .mutations_position = { 1, 2, 3 }, + .num_edges = 4, + .edges_parent = { 3, 3, 4, 4 }, + .edges_child = { 0, 1, 2, 3 }, + .edges_left = { 0, 0, 0, 0 }, + .edges_right = { 10, 10, 10, 10 }, + .indexes_insert = { 0, 1, 2, 3 }, + .indexes_remove = { 3, 2, 1, 0 }, + .sequence_length = 10, + .size_biased = 0, + .edges_stats = { { 1, 10 }, { 0, 10 }, { 0, 10 }, { 2, 10 } }, + .mutations_edge = { 0, 3, 3 } }, + { .num_nodes = 5, + .is_sample = { 1, 1, 1, 0, 0 }, + .num_mutations = 3, + .mutations_node = { 0, 3, 3 }, + .mutations_position = { 1, 2, 3 }, + .num_edges = 4, + .edges_parent = { 3, 3, 4, 4 }, + .edges_child = { 0, 1, 2, 3 }, + .edges_left = { 0, 0, 0, 0 }, + .edges_right = { 10, 10, 10, 10 }, + .indexes_insert = { 0, 1, 2, 3 }, + .indexes_remove = { 3, 2, 1, 0 }, + .sequence_length = 10, + .size_biased = 1, + .edges_stats = { { 1, 10 }, { 0, 10 }, { 0, 10 }, { 4, 20 } }, + .mutations_edge = { 0, 3, 3 } }, + /* no samples flagged */ + { .num_nodes = 3, + .is_sample = { 0, 0, 0 }, + .num_mutations = 1, + .mutations_node = { 0 }, + .mutations_position = { 1 }, + .num_edges = 2, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .edges_left = { 0, 0 }, + .edges_right = { 10, 10 }, + .indexes_insert = { 0, 1 }, + .indexes_remove = { 1, 0 }, + .sequence_length = 10, + .size_biased = 1, + .edges_stats = { { 0, 0 }, { 0, 0 } }, + .mutations_edge = { 0 } }, + /* mutations not in order of position */ + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 5, + .mutations_node = { 1, 0, 2, 1, 0 }, + .mutations_position = { 8, 1, 9, 2, 6 }, + .num_edges = 3, + .edges_parent = { 2, 2, 2 }, + .edges_child = { 0, 0, 1 }, + .edges_left = { 0, 5, 0 }, + .edges_right = { 5, 10, 10 }, + .indexes_insert = { 0, 2, 1 }, + .indexes_remove = { 0, 2, 1 }, + .sequence_length = 10, + .size_biased = 0, + .edges_stats = { { 1, 5 }, { 1, 5 }, { 2, 10 } }, + .mutations_edge = { 2, 0, -1, 2, 1 } }, +}; + static void test_count_mutations(void) { - const uint8_t is_sample[] = { 1, 1, 0 }; - const tsd_id_t mutations_node[] = { 1, 0, 2 }; - const double mutations_position[] = { 6.0, 1.0, 2.0 }; - const tsd_id_t parent[] = { 2, 2 }; - const tsd_id_t child[] = { 0, 1 }; - const double left[] = { 0.0, 0.0 }; - const double right[] = { 10.0, 5.0 }; - const tsd_id_t insert[] = { 0, 1 }; - const tsd_id_t remove[] = { 1, 0 }; - double stats[4]; - tsd_id_t mutations_edge[3]; - int size_biased; + const size_t num_rows + = sizeof(count_mutations_rows) / sizeof(count_mutations_rows[0]); + const count_mutations_row_t *row; + double stats[2 * TABLE_MAX_EDGES]; + tsd_id_t mutations_edge[TABLE_MAX_MUTATIONS]; + tsd_size_t k; + size_t j; int ret; - for (size_biased = 0; size_biased < 2; size_biased++) { - ret = tsd_count_mutations(3, is_sample, 3, mutations_node, mutations_position, 2, - parent, child, left, right, insert, remove, 10.0, size_biased, stats, - mutations_edge); + for (j = 0; j < num_rows; j++) { + row = count_mutations_rows + j; + ret = tsd_count_mutations(row->num_nodes, row->is_sample, row->num_mutations, + row->mutations_node, row->mutations_position, row->num_edges, + row->edges_parent, row->edges_child, row->edges_left, row->edges_right, + row->indexes_insert, row->indexes_remove, row->sequence_length, + row->size_biased, stats, mutations_edge); CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_EQUAL(mutations_edge[0], -1); - CU_ASSERT_EQUAL(mutations_edge[1], 0); - CU_ASSERT_EQUAL(mutations_edge[2], -1); - CU_ASSERT_EQUAL(stats[0], 1.0); - CU_ASSERT_EQUAL(stats[1], 10.0); - CU_ASSERT_EQUAL(stats[3], 5.0); + assert_array_close(stats, &row->edges_stats[0][0], 2 * row->num_edges); + for (k = 0; k < row->num_mutations; k++) { + CU_ASSERT_EQUAL(mutations_edge[k], row->mutations_edge[k]); + } } - /* no edges, no mutations */ - ret = tsd_count_mutations(3, is_sample, 0, NULL, NULL, 0, NULL, NULL, NULL, NULL, - NULL, NULL, 10.0, 0, NULL, NULL); - CU_ASSERT_EQUAL(ret, 0); } -/* Two samples at time zero, below a node at time 1, below a root at time 2. */ +/* Expected values of the reference implementation */ +static const area_row_t area_rows[] = { + /* a single epoch */ + { .num_nodes = 3, + .nodes_time = { 0, 0, 1 }, + .num_edges = 2, + .likelihoods = { { 2, 10 }, { 1, 10 } }, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .num_epochs = 1, + .counts = { 3 }, + .offset = { 20 }, + .duration = { 1 }, + .nodes_index = { 0, 0, 1 } }, + /* all nodes at time zero: no epoch, and every edge has zero length */ + { .num_nodes = 3, + .nodes_time = { 0, 0, 0 }, + .num_edges = 2, + .likelihoods = { { 2, 10 }, { 1, 10 } }, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .num_epochs = 0, + .nodes_index = { 0, 0, 0 } }, + /* no edges */ + { .num_nodes = 2, + .nodes_time = { 0, 1 }, + .num_edges = 0, + .num_epochs = 1, + .counts = { 0 }, + .offset = { 0 }, + .duration = { 1 }, + .nodes_index = { 0, 1 } }, + /* a single node */ + { .num_nodes = 1, + .nodes_time = { 0 }, + .num_edges = 0, + .num_epochs = 0, + .nodes_index = { 0 } }, + /* no nodes */ + { .num_nodes = 0, .num_edges = 0, .num_epochs = 0 }, + /* an edge of zero length */ + { .num_nodes = 5, + .nodes_time = { 0, 0, 1, 1, 3 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 4, 5 } }, + .edges_parent = { 2, 2, 4 }, + .edges_child = { 0, 1, 3 }, + .num_epochs = 2, + .counts = { 3, 2 }, + .offset = { 20, 5 }, + .duration = { 1, 2 }, + .nodes_index = { 0, 0, 1, 1, 2 } }, + /* an edge whose parent is younger than its child is skipped */ + { .num_nodes = 3, + .nodes_time = { 0, 1, 0.5 }, + .num_edges = 2, + .likelihoods = { { 2, 10 }, { 1, 10 } }, + .edges_parent = { 1, 2 }, + .edges_child = { 0, 1 }, + .num_epochs = 2, + .counts = { 2, 2 }, + .offset = { 10, 10 }, + .duration = { 0.5, 0.5 }, + .nodes_index = { 0, 2, 1 } }, + /* two epochs */ + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 3 }, + .num_edges = 2, + .likelihoods = { { 6, 12 }, { 3, 12 } }, + .edges_parent = { 3, 2 }, + .edges_child = { 0, 1 }, + .num_epochs = 2, + .counts = { 5, 2 }, + .offset = { 24, 12 }, + .duration = { 1, 2 }, + .nodes_index = { 0, 0, 1, 2 } }, + /* NOTE: current behaviour, possibly a bug: the first epoch always starts at zero, + even if the youngest node is older */ + { .num_nodes = 2, + .nodes_time = { 1, 2 }, + .num_edges = 1, + .likelihoods = { { 2, 10 } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .num_epochs = 1, + .counts = { 2 }, + .offset = { 10 }, + .duration = { 2 }, + .nodes_index = { 0, 1 } }, + /* tied and unsorted times */ + { .num_nodes = 6, + .nodes_time = { 3, 0, 1, 0, 1, 5 }, + .num_edges = 4, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 }, { 2, 10 } }, + .edges_parent = { 4, 2, 5, 2 }, + .edges_child = { 1, 3, 0, 1 }, + .num_epochs = 3, + .counts = { 5, 0, 1.5 }, + .offset = { 30, 0, 10 }, + .duration = { 1, 2, 2 }, + .nodes_index = { 2, 0, 1, 0, 1, 3 } }, + /* NaN times are ordered last, whichever their position */ + { .num_nodes = 5, + .nodes_time = { 0, NAN, 1, NAN, 2 }, + .num_edges = 2, + .likelihoods = { { 1, 1 }, { 1, 1 } }, + .edges_parent = { 2, 4 }, + .edges_child = { 0, 2 }, + .num_epochs = 2, + .counts = { 1, 1 }, + .offset = { 1, 1 }, + .duration = { 1, 1 }, + .nodes_index = { 0, 2, 1, 2, 2 } }, +}; + static void -test_mutational_area_and_timescale(void) +test_mutational_area(void) { - const double nodes_time[] = { 0.0, 0.0, 1.0, 2.0 }; - const double likelihoods[] = { 2.0, 10.0, 1.0, 10.0, 3.0, 10.0 }; - const double zero_span[] = { 2.0, 0.0, 1.0, 0.0, 3.0, 0.0 }; - const tsd_id_t parent[] = { 2, 2, 3 }; - const tsd_id_t child[] = { 0, 1, 2 }; + const size_t num_rows = sizeof(area_rows) / sizeof(area_rows[0]); + const area_row_t *row; tsd_epoch_stats_t stats; - tsd_id_t nodes_index[4]; - tsd_size_t num_breaks; + tsd_id_t nodes_index[TABLE_MAX_NODES]; + tsd_size_t k; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = area_rows + j; + ret = tsd_mutational_area(row->num_nodes, row->nodes_time, row->num_edges, + &row->likelihoods[0][0], row->edges_parent, row->edges_child, &stats, + nodes_index); + CU_ASSERT_EQUAL_FATAL(ret, 0); + CU_ASSERT_EQUAL_FATAL(stats.num_epochs, row->num_epochs); + assert_array_close(stats.counts, row->counts, row->num_epochs); + assert_array_close(stats.offset, row->offset, row->num_epochs); + assert_array_close(stats.duration, row->duration, row->num_epochs); + for (k = 0; k < row->num_nodes; k++) { + CU_ASSERT_EQUAL(nodes_index[k], row->nodes_index[k]); + } + tsd_epoch_stats_free(&stats); + } +} + +/* Expected values of the reference implementation */ +static const timescale_row_t timescale_rows[] = { + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 2 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = 1, + .num_breaks = 2, + .origin = { 0, 2 }, + .adjust = { 0, 0.4 }, + .ret = 0 }, + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 2 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = 2, + .num_breaks = 2, + .origin = { 0, 2 }, + .adjust = { 0, 0.4 }, + .ret = 0 }, + /* as many intervals as epochs */ + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 2 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = 3, + .num_breaks = 3, + .origin = { 0, 1, 2 }, + .adjust = { 0, 0.15, 0.44999999999999996 }, + .ret = 0 }, + /* more intervals than epochs */ + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 2 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = 10000, + .num_breaks = 3, + .origin = { 0, 1, 2 }, + .adjust = { 0, 0.15, 0.44999999999999996 }, + .ret = 0 }, + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 2 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = 0, + .ret = TSD_ERR_NONPOSITIVE_INTERVALS }, + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 2 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = -1, + .ret = TSD_ERR_NONPOSITIVE_INTERVALS }, + /* a historical sample */ + { .num_nodes = 4, + .nodes_time = { 0, 500, 100, 700 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 3, 3 }, + .edges_child = { 0, 2, 1 }, + .max_intervals = 1, + .num_breaks = 2, + .origin = { 0, 700 }, + .adjust = { 0, 0.6708333333333333 }, + .ret = 0 }, + { .num_nodes = 4, + .nodes_time = { 0, 500, 100, 700 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 3, 3 }, + .edges_child = { 0, 2, 1 }, + .max_intervals = 3, + .num_breaks = 4, + .origin = { 0, 100, 500, 700 }, + .adjust = { 0, 0.2, 0.2666666666666667, 0.4333333333333334 }, + .ret = 0 }, + { .num_nodes = 4, + .nodes_time = { 0, 500, 100, 700 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 3, 3 }, + .edges_child = { 0, 2, 1 }, + .max_intervals = 100, + .num_breaks = 4, + .origin = { 0, 100, 500, 700 }, + .adjust = { 0, 0.2, 0.2666666666666667, 0.4333333333333334 }, + .ret = 0 }, + /* the top edge has no span, so the last epoch has no weight and is merged */ + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 2 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 0 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = 1, + .num_breaks = 2, + .origin = { 0, 2 }, + .adjust = { 0, 0.6 }, + .ret = 0 }, + /* an edge of negative length is skipped from the totals */ + { .num_nodes = 4, + .nodes_time = { 0, 0, 2, 1 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 5, 10 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = 2, + .num_breaks = 3, + .origin = { 0, 1, 2 }, + .adjust = { 0, 0.075, 0.15 }, + .ret = 0 }, + /* the total weight is zero, so the first changepoint is -1, which counts from the + end */ + { .num_nodes = 6, + .nodes_time = { 0, 0, 1, 2, 3, 4 }, + .num_edges = 4, + .likelihoods = { { 1, 1 }, { 1, 1 }, { 1, -3 }, { 1, 1 } }, + .edges_parent = { 2, 3, 4, 5 }, + .edges_child = { 0, 2, 3, 4 }, + .max_intervals = 2, + .num_breaks = 2, + .origin = { 4, 4 }, + .adjust = { 0, 1 }, + .ret = 0 }, + /* NOTE: current behaviour, possibly a bug: every edge over an interval has zero span + (a zero mutation rate) or there are no edges */ + { .num_nodes = 3, + .nodes_time = { 0, 0, 1 }, + .num_edges = 2, + .likelihoods = { { 2, 0 }, { 1, 0 } }, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .max_intervals = 1, + .ret = TSD_ERR_ZERO_EDGE_SPAN }, + { .num_nodes = 2, + .nodes_time = { 0, 1 }, + .num_edges = 0, + .max_intervals = 1, + .ret = TSD_ERR_ZERO_EDGE_SPAN }, + /* all nodes at time zero: no epochs, and the span is zero */ + { .num_nodes = 3, + .nodes_time = { 0, 0, 0 }, + .num_edges = 2, + .likelihoods = { { 1, 10 }, { 1, 10 } }, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .max_intervals = 1, + .ret = TSD_ERR_ZERO_EDGE_SPAN }, +}; + +static void +test_mutational_timescale(void) +{ + const size_t num_rows = sizeof(timescale_rows) / sizeof(timescale_rows[0]); + const timescale_row_t *row; double *origin = NULL; double *adjust = NULL; + tsd_size_t num_breaks; + size_t j; int ret; - ret = tsd_mutational_area( - 4, nodes_time, 3, likelihoods, parent, child, &stats, nodes_index); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_EQUAL(stats.num_epochs, 2); - CU_ASSERT_EQUAL(nodes_index[3], 2); - tsd_epoch_stats_free(&stats); - /* no nodes */ - ret = tsd_mutational_area(0, NULL, 0, NULL, NULL, NULL, &stats, NULL); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_EQUAL(stats.num_epochs, 0); - tsd_epoch_stats_free(&stats); - - ret = tsd_mutational_timescale( - 4, nodes_time, 3, likelihoods, parent, child, 2, &num_breaks, &origin, &adjust); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(num_breaks >= 2); - CU_ASSERT_EQUAL(origin[0], 0.0); - CU_ASSERT_EQUAL(adjust[0], 0.0); - tsd_safe_free(origin); - tsd_safe_free(adjust); - ret = tsd_mutational_timescale( - 4, nodes_time, 3, likelihoods, parent, child, 0, &num_breaks, &origin, &adjust); - CU_ASSERT_EQUAL(ret, TSD_ERR_NONPOSITIVE_INTERVALS); - ret = tsd_mutational_timescale( - 4, nodes_time, 3, zero_span, parent, child, 2, &num_breaks, &origin, &adjust); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_EDGE_SPAN); - /* all nodes at time zero: there are no epochs, and the span is zero */ - ret = tsd_mutational_timescale( - 2, nodes_time, 0, NULL, NULL, NULL, 1, &num_breaks, &origin, &adjust); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_EDGE_SPAN); + for (j = 0; j < num_rows; j++) { + row = timescale_rows + j; + ret = tsd_mutational_timescale(row->num_nodes, row->nodes_time, row->num_edges, + &row->likelihoods[0][0], row->edges_parent, row->edges_child, + row->max_intervals, &num_breaks, &origin, &adjust); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + CU_ASSERT_EQUAL_FATAL(num_breaks, row->num_breaks); + assert_array_close(origin, row->origin, num_breaks); + assert_array_close(adjust, row->adjust, num_breaks); + } + tsd_safe_free(origin); + tsd_safe_free(adjust); + origin = NULL; + adjust = NULL; + } } +/* Expected values of the reference implementation */ +static const point_row_t point_rows[] = { + { .num_points = 5, + .estimate = { 0, 0.5, 1, 2, 3 }, + .fixed = { 0, 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .out = { 0, 1, 2, 2.75, 3.5 }, + .ret = 0 }, + /* the last piece is flat, so everything beyond it maps to the last point */ + { .num_points = 5, + .estimate = { 3, 4, 10, 1e+300, INFINITY }, + .fixed = { 0, 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .out = { 3.5, 3.5, 3.5, 3.5, NAN }, + .ret = 0 }, + /* NOTE: current behaviour, possibly a bug: a time below the first break has search + index -1, which wraps to the last breakpoint; -inf gives NaN */ + { .num_points = 4, + .estimate = { -1, -1e-09, 0, -INFINITY }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .out = { 3.5, 3.5, 0, NAN }, + .ret = 0 }, + /* NaN, fixed or not */ + { .num_points = 3, + .estimate = { NAN, 1, NAN }, + .fixed = { 1, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .out = { NAN, 2, NAN }, + .ret = 0 }, + /* some fixed */ + { .num_points = 4, + .estimate = { 0, 0.5, 3, 4 }, + .fixed = { 1, 0, 1, 1 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .out = { 0, 1, 3, 4 }, + .ret = 0 }, + { .num_points = 0, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .ret = 0 }, + /* a single breakpoint */ + { .num_points = 3, + .estimate = { 0, 0.5, 7 }, + .fixed = { 0, 0, 0 }, + .num_breaks = 1, + .original = { 0 }, + .rescaled = { 2 }, + .out = { 2, 2, 2 }, + .ret = 0 }, + { .num_points = 3, + .estimate = { 0, 0.3, 1 }, + .fixed = { 0, 0, 0 }, + .num_breaks = 2, + .original = { 0, 5 }, + .rescaled = { 0, 5 }, + .out = { 0, 0.3, 1 }, + .ret = 0 }, + { .num_points = 1, + .estimate = { 0.5 }, + .fixed = { 0 }, + .num_breaks = 0, + .ret = TSD_ERR_NO_BREAKPOINTS }, + { .num_points = 1, + .estimate = { 0.5 }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 2 }, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, + { .num_points = 1, + .estimate = { 0.5 }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 1 }, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, + { .num_points = 1, + .estimate = { 0.5 }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 2, 1 }, + .rescaled = { 0, 1, 2 }, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, + { .num_points = 1, + .estimate = { 0.5 }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, NAN }, + .rescaled = { 0, 1, 2 }, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, + { .num_points = 1, + .estimate = { 0.5 }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, 2 }, + .rescaled = { 0, 1, NAN }, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, +}; + static void test_piecewise_scale_point_estimate(void) { - const double estimate[] = { 0.5, 1.5, 4.0, -1.0, NAN }; - const uint8_t fixed[] = { 0, 0, 1, 0, 0 }; - const double original[] = { 0.0, 1.0, 3.0 }; - const double rescaled[] = { 0.0, 2.0, 3.5 }; - const double flat[] = { 0.0, 2.0, 2.0 }; - double out[5]; + const size_t num_rows = sizeof(point_rows) / sizeof(point_rows[0]); + const point_row_t *row; + double out[TABLE_MAX_POINTS]; + size_t j; int ret; - ret = tsd_piecewise_scale_point_estimate( - 5, estimate, fixed, 3, original, rescaled, out); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_DOUBLE_EQUAL(out[0], 1.0, 1e-12); - CU_ASSERT_DOUBLE_EQUAL(out[1], 2.375, 1e-12); - CU_ASSERT_EQUAL(out[2], 4.0); - CU_ASSERT(isnan(out[4])); - ret = tsd_piecewise_scale_point_estimate(5, estimate, fixed, 3, original, flat, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_NON_INCREASING_BREAKPOINTS); - ret = tsd_piecewise_scale_point_estimate(5, estimate, fixed, 3, flat, rescaled, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_NON_INCREASING_BREAKPOINTS); - ret = tsd_piecewise_scale_point_estimate(5, estimate, fixed, 0, NULL, NULL, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_NO_BREAKPOINTS); + for (j = 0; j < num_rows; j++) { + row = point_rows + j; + ret = tsd_piecewise_scale_point_estimate(row->num_points, row->estimate, + row->fixed, row->num_breaks, row->original, row->rescaled, out); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_array_close(out, row->out, row->num_points); + } + } } +/* Expected values of the reference implementation */ +static const posterior_row_t posterior_rows[] = { + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .out = { { 5.752572529118271, 2.455480919679371 }, + { 3.460836454696765, 2.2304182273483826 }, + { 0.22573432805250393, 0.612867164026252 }, + { 39.903223991686914, 11.686635426196261 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.001, + .max_shape = 1000, + .out = { { 2.471583651492129, 1.2623940550880468 }, + { 3.210845310401922, 2.105422655200961 }, + { 0.23603088036204523, 0.6180154401810226 }, + { 26.04896064141572, 7.72827446897592 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.999999999, + .max_shape = 1000, + .out = { { 6.175396703307324, 2.609235164839027 }, + { 1.9999982566565375, 1.4999991283282688 }, + { -2.6908024519656237e-07, 0.4999998654598774 }, + { 13.715489108570114, 4.204425459591461 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0, + .max_shape = 1000, + .ret = TSD_ERR_INVALID_QUANTILE_WIDTH }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 1, + .max_shape = 1000, + .ret = TSD_ERR_INVALID_QUANTILE_WIDTH }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = NAN, + .max_shape = 1000, + .ret = TSD_ERR_INVALID_QUANTILE_WIDTH }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 1, 0, 1, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .out = { { NAN, NAN }, { 3.460836454696765, 2.2304182273483826 }, { NAN, NAN }, + { 39.903223991686914, 11.686635426196261 } }, + .ret = 0 }, + /* fixed rows are not validated */ + { .num_posteriors = 2, + .posteriors = { { NAN, NAN }, { 1, 1 } }, + .fixed = { 1, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .out = { { NAN, NAN }, { 5.752572529118271, 2.455480919679371 } }, + .ret = 0 }, + /* NOTE: current behaviour, possibly a bug: no posteriors is an error */ + { .num_posteriors = 0, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_NO_POSTERIORS }, + { .num_posteriors = 4, + .posteriors + = { { -0.99, 1 }, { 1, 1e-300 }, { 1, 1e+300 }, { 1000000, 1000000 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .out = { { -0.99, 0.5 }, { 999, 285.7142857142857 }, + { 1.000000000000004, 5.00000000000001e+299 }, { 999, 499.99981250007033 } }, + .ret = 0 }, + /* NOTE: current behaviour, possibly a bug: for a shape this close to -1 the lower + quantile underflows to zero and the division by it is an error (IEEE would give + inf), rather than a failed gamma fit */ + { .num_posteriors = 1, + .posteriors = { { -0.9999, 1 } }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_ZERO_DIVISION }, + { .num_posteriors = 1, + .posteriors = { { 1, INFINITY } }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_ZERO_DIVISION }, + /* NOTE: current behaviour, possibly a bug: the error of tsd_approximate_gamma_iqr is + passed on */ + { .num_posteriors = 1, + .posteriors = { { INFINITY, 1 } }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_UNSORTED_QUANTILES }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { -1, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_INVALID_POSTERIOR }, + { .num_posteriors = 1, + .posteriors = { { 1, NAN } }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_INVALID_POSTERIOR }, + /* all quantiles map to one point beyond the last break: zero interquantile range */ + { .num_posteriors = 2, + .posteriors = { { 1, 0.001 }, { 1, 1e-09 } }, + .fixed = { 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .out = { { 999, 285.7142857142857 }, { 999, 285.7142857142857 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0.5, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT }, + /* the lower quantile is below the first breakpoint, the mean is not */ + { .num_posteriors = 1, + .posteriors = { { 1, 1 } }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 1.5, 3, 5 }, + .rescaled = { 0, 1, 2 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT }, + /* the rescaled quantiles of fixed posteriors are zero, and are checked too */ + { .num_posteriors = 1, + .posteriors = { { 1, 1 } }, + .fixed = { 1 }, + .num_breaks = 3, + .original = { 0.5, 2, 5 }, + .rescaled = { 0, 1, 2 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT }, + /* NOTE: current behaviour, possibly a bug: max_shape = 0 gives shape -1 (improper) + and zero rate */ + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 0, + .out = { { -1, 0 }, { -1, 0 }, { -1, 0 }, { -1, 0 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1, + .out = { { 0, 0.36363636363636365 }, { 0, 0.5 }, { 0, 0.5 }, + { 0, 0.2857142857142857 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = NAN, + .out = { { 5.752572529118271, 2.455480919679371 }, + { 3.460836454696765, 2.2304182273483826 }, + { 0.22573432805250393, 0.612867164026252 }, + { 39.903223991686914, 11.686635426196261 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 1 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 2 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, + /* the breaks are checked before the posteriors */ + { .num_posteriors = 1, + .posteriors = { { -5, 1 } }, + .fixed = { 0 }, + .num_breaks = 2, + .original = { 0, 0 }, + .rescaled = { 0, 1 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, + /* a single breakpoint at zero: every quantile maps to zero */ + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 1, + .original = { 0 }, + .rescaled = { 0 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_ZERO_DIVISION }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 1, + .original = { 0 }, + .rescaled = { 4 }, + .quantile_width = 0.5, + .max_shape = 1000, + .out = { { 999, 250 }, { 999, 250 }, { 999, 250 }, { 999, 250 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 0, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_NO_BREAKPOINTS }, +}; + static void test_piecewise_scale_posterior(void) { - const double posteriors[] = { 1.0, 1.0, 2.0, 3.0, 0.0, 1.0, 5.0, 2.0 }; - const uint8_t fixed[] = { 0, 0, 1, 0 }; - const uint8_t none_fixed[] = { 0, 0, 0, 0 }; - const double original[] = { 0.0, 1.0, 3.0 }; - const double rescaled[] = { 0.0, 2.0, 3.5 }; - const double late_original[] = { 0.5, 1.0, 3.0 }; - const double flat[] = { 0.0, 2.0, 2.0 }; - const double bad_posteriors[] = { -1.0, 1.0, 1.0, 1.0 }; - const double zero_rate[] = { 1.0, INFINITY }; - const double near_pole[] = { -0.9999, 1.0 }; - const double large_shape[] = { 1e8, 1e8 }; - double out[8]; + const size_t num_rows = sizeof(posterior_rows) / sizeof(posterior_rows[0]); + const posterior_row_t *row; + double out[2 * TABLE_MAX_POSTERIORS]; + size_t j; int ret; - ret = tsd_piecewise_scale_posterior( - 4, posteriors, fixed, 3, original, rescaled, 0.5, 1000.0, out); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(isnan(out[4])); - ret = tsd_piecewise_scale_posterior( - 4, posteriors, fixed, 0, NULL, NULL, 0.5, 1000.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_NO_BREAKPOINTS); - CU_ASSERT(isfinite(out[0]) && isfinite(out[1])); - ret = tsd_piecewise_scale_posterior( - 4, posteriors, none_fixed, 3, original, rescaled, 0.5, 1000.0, out); - CU_ASSERT_EQUAL(ret, 0); - ret = tsd_piecewise_scale_posterior( - 4, posteriors, fixed, 3, original, rescaled, 1.0, 1000.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_QUANTILE_WIDTH); - ret = tsd_piecewise_scale_posterior( - 4, posteriors, fixed, 3, original, flat, 0.5, 1000.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_NON_INCREASING_BREAKPOINTS); - ret = tsd_piecewise_scale_posterior( - 2, bad_posteriors, none_fixed, 3, original, rescaled, 0.5, 1000.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_POSTERIOR); - ret = tsd_piecewise_scale_posterior( - 4, posteriors, fixed, 3, late_original, rescaled, 0.5, 1000.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT); - ret = tsd_piecewise_scale_posterior( - 0, posteriors, fixed, 3, original, rescaled, 0.5, 1000.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_NO_POSTERIORS); - /* an infinite rate, or a shape close to zero, gives a zero lower quantile */ - ret = tsd_piecewise_scale_posterior( - 1, zero_rate, none_fixed, 3, original, rescaled, 0.5, 1000.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - ret = tsd_piecewise_scale_posterior( - 1, near_pole, none_fixed, 3, original, rescaled, 0.5, 1000.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - /* failures of the interquantile approximation are passed on */ - ret = tsd_piecewise_scale_posterior( - 1, large_shape, none_fixed, 3, original, rescaled, 0.5, 1e300, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + for (j = 0; j < num_rows; j++) { + row = posterior_rows + j; + ret = tsd_piecewise_scale_posterior(row->num_posteriors, &row->posteriors[0][0], + row->fixed, row->num_breaks, row->original, row->rescaled, + row->quantile_width, row->max_shape, out); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_array_close(out, &row->out[0][0], 2 * row->num_posteriors); + } + } } static void @@ -1786,52 +2977,149 @@ ep_init(tsd_ep_t *ep, const tsd_id_t *parent, const tsd_id_t *child, memcpy(ep->posterior, post, 8 * sizeof(*post)); } +typedef struct { + double x[2]; + double y[2]; + double s; + double d; + int ret; +} damp_row_t; + +typedef struct { + double x[2]; + double s; + double d; + int ret; +} rescale_row_t; + +/* Expected values of the reference implementation */ +static const damp_row_t damp_rows[] = { + { .x = { 0, 0 }, .y = { 0, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + /* zero x and y: s is not checked */ + { .x = { 0, 0 }, .y = { 0, 0 }, .s = 5, .d = 1, .ret = 0 }, + { .x = { 0, 1 }, .y = { 0, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, .y = { 0, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, .y = { 0.9999999999999999, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, .y = { 1, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, + .y = { 1.0000000000000002, 0 }, + .s = 0.5, + .d = 0.9999999999999998, + .ret = 0 }, + { .x = { 1, 2 }, .y = { 4, 0 }, .s = 0.5, .d = 0.25, .ret = 0 }, + { .x = { 1, 2 }, .y = { -5, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, .y = { 0, 0.9999999999999999 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, .y = { 0, 1 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, + .y = { 0, 1.0000000000000002 }, + .s = 0.5, + .d = 0.9999999999999998, + .ret = 0 }, + { .x = { 1, 2 }, .y = { 0, 8 }, .s = 0.5, .d = 0.125, .ret = 0 }, + { .x = { 1, 2 }, .y = { 0, -5 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, .y = { 4, 2 }, .s = 0.5, .d = 0.25, .ret = 0 }, + { .x = { 1, 2 }, .y = { 2, 8 }, .s = 0.5, .d = 0.125, .ret = 0 }, + { .x = { 1, 2 }, .y = { -1, -1 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, .y = { 2, 2 }, .s = 5e-324, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, + .y = { 2, 2 }, + .s = 0.9999999999999999, + .d = 1.1102230246251565e-16, + .ret = 0 }, + { .x = { -0.9999999999999999, 1 }, .y = { 0, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 1e-300 }, .y = { 1, 4 }, .s = 0.5, .d = 1.25e-301, .ret = 0 }, + /* NOTE: current behaviour, possibly a bug: the minimum swallows a NaN in the second + component of y, so the damping is silently skipped */ + { .x = { 1, 1 }, .y = { 0, NAN }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 1 }, .y = { 8, NAN }, .s = 0.5, .d = 0.125, .ret = 0 }, + { .x = { 1, 1 }, .y = { -INFINITY, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 1 }, .y = { 0, -INFINITY }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 1 }, .y = { 0, 0 }, .s = 0, .ret = TSD_ERR_INVALID_MIN_STEP }, + { .x = { 1, 1 }, .y = { 0, 0 }, .s = 1, .ret = TSD_ERR_INVALID_MIN_STEP }, + { .x = { 1, 1 }, .y = { 0, 0 }, .s = NAN, .ret = TSD_ERR_INVALID_MIN_STEP }, + { .x = { -1, 1 }, .y = { 0, 0 }, .s = 0.5, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { NAN, 1 }, .y = { 0, 0 }, .s = 0.5, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { 1, 0 }, .y = { 0, 0 }, .s = 0.5, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { 1, NAN }, .y = { 0, 0 }, .s = 0.5, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { 0, 0 }, .y = { 1, 1 }, .s = 0.5, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + /* d underflows */ + { .x = { 1, 1e-300 }, .y = { 0, 1e+300 }, .s = 0.5, .ret = TSD_ERR_INVALID_DAMPING }, + { .x = { 1, 1 }, .y = { NAN, 0 }, .s = 0.5, .ret = TSD_ERR_INVALID_DAMPING }, + /* d is rounded to just above one */ + { .x = { 24.23005039128842, 15.403466578537675 }, + .y = { 2.409458061921995, 1.471023884360475 }, + .s = 0.9045004657321672, + .ret = TSD_ERR_INVALID_DAMPING }, + /* an infinite posterior and a zero message: a division by zero */ + { .x = { INFINITY, 1 }, .y = { 0, 0 }, .s = 0.5, .ret = TSD_ERR_ZERO_DIVISION }, + /* an infinite posterior and a zero message: a division by zero */ + { .x = { 1, INFINITY }, .y = { 0, 0 }, .s = 0.5, .ret = TSD_ERR_ZERO_DIVISION }, +}; + static void -test_damp_and_rescale(void) -{ - const double zero[2] = { 0, 0 }; - const double x[2] = { 1, 2 }; - const double y[2] = { 4, 8 }; - const double improper[2] = { -1, 1 }; - const double infinite[2] = { INFINITY, 1 }; - const double nan_y[2] = { NAN, 0 }; - const double small_y[2] = { 0, 1e300 }; - const double tiny_x[2] = { 1, 1e-300 }; +test_damp(void) +{ + const size_t num_rows = sizeof(damp_rows) / sizeof(damp_rows[0]); + const damp_row_t *row; double d; + size_t j; + int ret; - CU_ASSERT_EQUAL(tsd_damp(zero, zero, 5.0, &d), 0); - CU_ASSERT_EQUAL(d, 1.0); - CU_ASSERT_EQUAL(tsd_damp(x, zero, 0.5, &d), 0); - CU_ASSERT_EQUAL(d, 1.0); - CU_ASSERT_EQUAL(tsd_damp(x, y, 0.5, &d), 0); - CU_ASSERT_TRUE(d > 0 && d < 1); - CU_ASSERT_EQUAL(tsd_damp(x, y, 1.0, &d), TSD_ERR_INVALID_MIN_STEP); - CU_ASSERT_EQUAL(tsd_damp(improper, zero, 0.5, &d), TSD_ERR_INVALID_NODE_POSTERIOR); - CU_ASSERT_EQUAL(tsd_damp(infinite, zero, 0.5, &d), TSD_ERR_ZERO_DIVISION); - CU_ASSERT_EQUAL(tsd_damp(x, nan_y, 0.5, &d), TSD_ERR_INVALID_DAMPING); - CU_ASSERT_EQUAL(tsd_damp(tiny_x, small_y, 0.5, &d), TSD_ERR_INVALID_DAMPING); - CU_ASSERT_EQUAL(tsd_damp(tiny_x, y, 0.5, &d), 0); - - CU_ASSERT_EQUAL(tsd_rescale(zero, 0.5, &d), 0); - CU_ASSERT_EQUAL(d, 1.0); - CU_ASSERT_EQUAL(tsd_rescale(x, 10.0, &d), 0); - CU_ASSERT_EQUAL(d, 1.0); - CU_ASSERT_EQUAL(tsd_rescale(x, 1.5, &d), 0); - CU_ASSERT_DOUBLE_EQUAL(d, 0.5, 1e-15); - CU_ASSERT_EQUAL(tsd_rescale(x, 0.1, &d), 0); - CU_ASSERT_EQUAL(tsd_rescale(tiny_x, 1.0, &d), 0); - CU_ASSERT_EQUAL(tsd_rescale(improper, 10.0, &d), TSD_ERR_INVALID_NODE_POSTERIOR); - CU_ASSERT_EQUAL(tsd_rescale(infinite, 10.0, &d), 0); - CU_ASSERT_EQUAL(tsd_rescale(nan_y, 10.0, &d), TSD_ERR_INVALID_NODE_POSTERIOR); - { - const double zero_shape[2] = { 0, 1 }; - const double low[2] = { -0.5, 1 }; - - CU_ASSERT_EQUAL(tsd_rescale(zero_shape, 0.5, &d), TSD_ERR_ZERO_DIVISION); - CU_ASSERT_EQUAL(tsd_rescale(low, 1.0, &d), 0); - CU_ASSERT_EQUAL(tsd_rescale(low, 2.0, &d), 0); - CU_ASSERT_EQUAL(tsd_rescale(low, 1.5, &d), 0); - CU_ASSERT_DOUBLE_EQUAL(d, 2.0 / 3.0, 1e-12); + for (j = 0; j < num_rows; j++) { + row = damp_rows + j; + ret = tsd_damp(row->x, row->y, row->s, &d); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_close_ulps(d, row->d, ULPS); + } + } +} + +/* Expected values of the reference implementation */ +static const rescale_row_t rescale_rows[] = { + { .x = { 0, 0 }, .s = 10, .d = 1, .ret = 0 }, + /* zero x: s is not checked */ + { .x = { 0, 0 }, .s = 0, .d = 1, .ret = 0 }, + { .x = { 0, 1 }, .s = 10, .d = 1, .ret = 0 }, + { .x = { 5, 1 }, .s = 10, .d = 1, .ret = 0 }, + { .x = { -0.5, 1 }, .s = 2, .d = 1, .ret = 0 }, + { .x = { 8.999999999999998, 1 }, .s = 10, .d = 1, .ret = 0 }, + { .x = { 9, 1 }, .s = 10, .d = 1, .ret = 0 }, + { .x = { 9.000000000000002, 1 }, .s = 10, .d = 0.9999999999999998, .ret = 0 }, + { .x = { -0.49999999999999994, 1 }, .s = 2, .d = 1, .ret = 0 }, + { .x = { -0.5000000000000001, 1 }, .s = 2, .d = 0.9999999999999998, .ret = 0 }, + { .x = { -0.95, 1 }, .s = 10, .d = 0.9473684210526316, .ret = 0 }, + { .x = { 99, INFINITY }, .s = 10, .d = 0.09090909090909091, .ret = 0 }, + { .x = { INFINITY, 1 }, .s = 10, .d = 0, .ret = 0 }, + /* NOTE: current behaviour, possibly a bug: with max_shape = 1 the factor is 0 and + wipes out the posterior */ + { .x = { 1, 1 }, .s = 1, .d = 0, .ret = 0 }, + { .x = { -0.5, 1 }, .s = 1, .d = -0, .ret = 0 }, + { .x = { -1, 1 }, .s = 10, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { NAN, 1 }, .s = 10, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { 1, 0 }, .s = 10, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { 1, -1 }, .s = 10, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { 1, NAN }, .s = 10, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + /* a zero shape with a cap below one: a division by zero */ + { .x = { 0, 1 }, .s = 0.5, .ret = TSD_ERR_ZERO_DIVISION }, +}; + +static void +test_rescale(void) +{ + const size_t num_rows = sizeof(rescale_rows) / sizeof(rescale_rows[0]); + const rescale_row_t *row; + double d; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = rescale_rows + j; + ret = tsd_rescale(row->x, row->s, &d); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_close_ulps(d, row->d, ULPS); + } } } @@ -1888,27 +3176,120 @@ test_rescale_and_assemble_factors(void) tsd_ep_free(&ep); } +typedef struct { + tsd_size_t num_nodes; + double constraints[3][2]; + tsd_size_t num_edges; + tsd_id_t edges_parent[2]; + tsd_id_t edges_child[2]; + int consistent; +} consistency_row_t; + +/* Expected values of the reference implementation */ +static const consistency_row_t consistency_rows[] = { + { .num_nodes = 0, .num_edges = 0, .consistent = 1 }, + /* no edges */ + { .num_nodes = 2, + .constraints = { { 0, 1 }, { 0, 1 } }, + .num_edges = 0, + .consistent = 1 }, + { .num_nodes = 2, + .constraints = { { 0, 0 }, { 0, INFINITY } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 1 }, + { .num_nodes = 2, + .constraints = { { 0, 5 }, { 3, 9 } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 1 }, + /* the parent's upper bound equals the child's lower bound */ + { .num_nodes = 2, + .constraints = { { 5, 5 }, { 0, 5 } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 1 }, + { .num_nodes = 2, + .constraints = { { 5.000000000000001, 6 }, { 0, 5 } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 0 }, + { .num_nodes = 2, + .constraints = { { 5, 5 }, { 0, 4.999999999999999 } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 0 }, + /* the maximum lower bound propagates up a chain */ + { .num_nodes = 3, + .constraints = { { 5, 5 }, { 0, 9 }, { 0, 9 } }, + .num_edges = 2, + .edges_parent = { 1, 2 }, + .edges_child = { 0, 1 }, + .consistent = 1 }, + { .num_nodes = 3, + .constraints = { { 5, 5 }, { 0, INFINITY }, { 0, 4 } }, + .num_edges = 2, + .edges_parent = { 1, 2 }, + .edges_child = { 0, 1 }, + .consistent = 0 }, + /* and from every child */ + { .num_nodes = 3, + .constraints = { { 0, 0 }, { 7, 7 }, { 0, 6 } }, + .num_edges = 2, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .consistent = 0 }, + { .num_nodes = 2, + .constraints = { { 10, 10 }, { 0, 0 } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 0 }, + /* NOTE: current behaviour, possibly a bug: the check is a single pass in edge order, + so edges must be sorted children-first */ + { .num_nodes = 3, + .constraints = { { 5, 5 }, { 0, INFINITY }, { 0, 4 } }, + .num_edges = 2, + .edges_parent = { 2, 1 }, + .edges_child = { 1, 0 }, + .consistent = 1 }, + /* NaN bounds are never inconsistent */ + { .num_nodes = 2, + .constraints = { { NAN, NAN }, { 0, 5 } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 1 }, + { .num_nodes = 2, + .constraints = { { 5, 5 }, { 0, NAN } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 1 }, +}; + static void test_constraints_are_consistent(void) { - const tsd_id_t parent[2] = { 1, 2 }; - const tsd_id_t child[2] = { 0, 1 }; - const double valid[6] = { 0, 0, 1, 5, 2, INFINITY }; - const double invalid[6] = { 3, 3, 1, 2, 2, INFINITY }; + const size_t num_rows = sizeof(consistency_rows) / sizeof(consistency_rows[0]); + const consistency_row_t *row; int consistent; + size_t j; + int ret; - CU_ASSERT_EQUAL( - tsd_constraints_are_consistent(3, 2, valid, parent, child, &consistent), 0); - CU_ASSERT_EQUAL(consistent, 1); - CU_ASSERT_EQUAL( - tsd_constraints_are_consistent(3, 0, valid, parent, child, &consistent), 0); - CU_ASSERT_EQUAL(consistent, 1); - CU_ASSERT_EQUAL( - tsd_constraints_are_consistent(3, 2, invalid, parent, child, &consistent), 0); - CU_ASSERT_EQUAL(consistent, 0); - CU_ASSERT_EQUAL( - tsd_constraints_are_consistent(0, 0, valid, parent, child, &consistent), 0); - CU_ASSERT_EQUAL(consistent, 1); + for (j = 0; j < num_rows; j++) { + row = consistency_rows + j; + consistent = -1; + ret = tsd_constraints_are_consistent(row->num_nodes, row->num_edges, + &row->constraints[0][0], row->edges_parent, row->edges_child, &consistent); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(consistent, row->consistent); + } } /* The branches of an EP pass: fixed child, fixed parent, free, both fixed. */ @@ -1965,6 +3346,8 @@ test_propagate_likelihood(void) TSD_ERR_INVALID_MAX_SHAPE); CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, order, 0, 1000.0, 1.0), TSD_ERR_INVALID_MIN_STEP); + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, order, 0, 1000.0, 0.0), + TSD_ERR_INVALID_MIN_STEP); CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, bad, 0, 1000.0, 0.1), TSD_ERR_EDGE_OUT_OF_BOUNDS); CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, bad, 1, 1000.0, 0.1), @@ -2123,16 +3506,6 @@ typedef struct { double phase[EP_MAX_MUTATIONS]; } ep_mutations_row_t; -static void -assert_array_close(const double *actual, const double *expected, tsd_size_t n) -{ - tsd_size_t j; - - for (j = 0; j < n; j++) { - assert_close_ulps(actual[j], expected[j], ULPS); - } -} - static void ep_setup(tsd_ep_t *ep, const ep_inputs_t *in, const ep_state_t *state) { @@ -3662,14 +5035,16 @@ main(int argc, char **argv) { "test_contains_unary_nodes", test_contains_unary_nodes }, { "test_check_arguments", test_check_arguments }, { "test_bad_tree_arguments", test_bad_tree_arguments }, + { "test_marginalize_over_ancestors", test_marginalize_over_ancestors }, { "test_conditional_coalescent_variance", test_conditional_coalescent_variance }, { "test_fixed_changepoints", test_fixed_changepoints }, - { "test_poisson_changepoints", test_poisson_changepoints }, { "test_count_mutations", test_count_mutations }, - { "test_mutational_area_and_timescale", test_mutational_area_and_timescale }, + { "test_mutational_area", test_mutational_area }, + { "test_mutational_timescale", test_mutational_timescale }, { "test_piecewise_scale_point_estimate", test_piecewise_scale_point_estimate }, { "test_piecewise_scale_posterior", test_piecewise_scale_posterior }, - { "test_damp_and_rescale", test_damp_and_rescale }, + { "test_damp", test_damp }, + { "test_rescale", test_rescale }, { "test_ep_init", test_ep_init }, { "test_rescale_and_assemble_factors", test_rescale_and_assemble_factors }, { "test_constraints_are_consistent", test_constraints_are_consistent }, From 29138601ff1c7fad65a04e916aa42f748264bd2e Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 17:14:27 -0800 Subject: [PATCH 50/56] Test the gamma approximations against tables of reference values --- lib/tests/tests.c | 1752 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 1487 insertions(+), 265 deletions(-) diff --git a/lib/tests/tests.c b/lib/tests/tests.c index 4f3d7702..acf36d19 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -751,137 +751,1417 @@ test_gammaincinv(void) } } +/* + * Tables for the functions of approx.c. Each function is called through an adapter + * that takes its inputs and writes its outputs as arrays; the natural parameters of + * the projections are consecutive pairs of inputs. + */ +typedef int (*approx_func_t)(const double *in, double *out); + +/* Inputs, and the expected outputs or (nonzero) return code. */ +typedef struct { + double in[6]; + double out[5]; + int ret; +} approx_row_t; + +#define NUM_ROWS(rows) (sizeof(rows) / sizeof(*(rows))) + static void -test_approximate_log_moments(void) +check_rows( + approx_func_t func, const approx_row_t *rows, size_t num_rows, size_t num_outputs) { - double logx, xlogx, logx2; + size_t j, k; int ret; + double out[5]; - ret = tsd_approximate_log_moments(2.0, 0.5, &logx, &xlogx, &logx2); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(isfinite(logx) && isfinite(xlogx) && isfinite(logx2)); - ret = tsd_approximate_log_moments(0.0, 0.5, &logx, &xlogx, &logx2); - CU_ASSERT_EQUAL(ret, TSD_ERR_NONPOSITIVE_MOMENTS); - ret = tsd_approximate_log_moments(1.0, NAN, &logx, &xlogx, &logx2); - CU_ASSERT_EQUAL(ret, TSD_ERR_NONPOSITIVE_MOMENTS); - /* mean ** 2 underflows */ - ret = tsd_approximate_log_moments(1e-200, 1.0, &logx, &xlogx, &logx2); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + for (j = 0; j < num_rows; j++) { + ret = func(rows[j].in, out); + CU_ASSERT_EQUAL(ret, rows[j].ret); + if (ret == 0 && rows[j].ret == 0) { + for (k = 0; k < num_outputs; k++) { + assert_close_ulps(out[k], rows[j].out[k], ULPS); + } + } + } } +/* + * Compare with reference values to within `rtol` (and an absolute tolerance of 1e-8); + * the outputs whose bits are set in `sd_mask` are variances, compared as standard + * deviations. + */ static void -test_approximate_gamma_kl(void) +check_reference_rows(approx_func_t func, const approx_row_t *rows, size_t num_rows, + size_t num_outputs, unsigned int sd_mask, double rtol) { - double out[2]; + size_t j, k; int ret; + double out[5]; + double actual, expected; - ret = tsd_approximate_gamma_kl(2.0, 0.5, out); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(isfinite(out[0]) && isfinite(out[1])); - /* the asymptotic lower bound */ - ret = tsd_approximate_gamma_kl(1.0, -1e-10, out); - CU_ASSERT_EQUAL(ret, 0); - ret = tsd_approximate_gamma_kl(0.0, -1.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS); - ret = tsd_approximate_gamma_kl(1.0, 0.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_JENSEN_VIOLATION); - /* the lower bound on the shape is zero */ - ret = tsd_approximate_gamma_kl(INFINITY, -1.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - /* the trigamma function divides by zero */ - ret = tsd_approximate_gamma_kl(1.0, -1e164, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + for (j = 0; j < num_rows; j++) { + ret = func(rows[j].in, out); + CU_ASSERT_EQUAL_FATAL(ret, 0); + for (k = 0; k < num_outputs; k++) { + actual = out[k]; + expected = rows[j].out[k]; + if (sd_mask & (1u << k)) { + actual = sqrt(actual); + expected = sqrt(expected); + } + assert_close_tol(actual, expected, rtol, 1e-8); + } + } +} + +static int +eval_log_moments(const double *in, double *out) +{ + return tsd_approximate_log_moments(in[0], in[1], out, out + 1, out + 2); +} + +static int +eval_gamma_kl(const double *in, double *out) +{ + return tsd_approximate_gamma_kl(in[0], in[1], out); +} + +static int +eval_gamma_mom(const double *in, double *out) +{ + return tsd_approximate_gamma_mom(in[0], in[1], out); +} + +static int +eval_gamma_iqr(const double *in, double *out) +{ + return tsd_approximate_gamma_iqr(in[0], in[1], in[2], in[3], in[4], out); +} + +static int +eval_valid_moments(const double *in, double *out) +{ + out[0] = tsd_valid_moments(in[0], in[1]); + return 0; +} + +static int +eval_valid_gamma(const double *in, double *out) +{ + out[0] = tsd_valid_gamma(in[0], in[1]); + return 0; +} + +static int +eval_moments(const double *in, double *out) +{ + return tsd_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, out + 2, + out + 3, out + 4); +} + +static int +eval_unphased_moments(const double *in, double *out) +{ + return tsd_unphased_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, + out + 2, out + 3, out + 4); +} + +static int +eval_rootward_moments(const double *in, double *out) +{ + return tsd_rootward_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); +} + +static int +eval_leafward_moments(const double *in, double *out) +{ + return tsd_leafward_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); +} + +static int +eval_sideways_moments(const double *in, double *out) +{ + return tsd_sideways_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); +} + +static int +eval_twin_moments(const double *in, double *out) +{ + return tsd_twin_moments(in[0], in[1], in[2], in[3], out, out + 1, out + 2); +} + +static int +eval_mutation_moments(const double *in, double *out) +{ + return tsd_mutation_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1); +} + +static int +eval_mutation_rootward_moments(const double *in, double *out) +{ + return tsd_mutation_rootward_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1); +} + +static int +eval_mutation_leafward_moments(const double *in, double *out) +{ + return tsd_mutation_leafward_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1); +} + +static int +eval_mutation_unphased_moments(const double *in, double *out) +{ + return tsd_mutation_unphased_moments( + in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, out + 2); +} + +static int +eval_mutation_twin_moments(const double *in, double *out) +{ + return tsd_mutation_twin_moments(in[0], in[1], in[2], in[3], out, out + 1, out + 2); +} + +static int +eval_mutation_sideways_moments(const double *in, double *out) +{ + return tsd_mutation_sideways_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); +} + +static int +eval_mutation_edge_moments(const double *in, double *out) +{ + return tsd_mutation_edge_moments(in[0], in[1], out, out + 1); +} + +static int +eval_mutation_block_moments(const double *in, double *out) +{ + return tsd_mutation_block_moments(in[0], in[1], out, out + 1, out + 2); +} + +static int +eval_gamma_projection(const double *in, double *out) +{ + return tsd_gamma_projection(in, in + 2, in + 4, out, out + 1, out + 3); +} + +static int +eval_leafward_projection(const double *in, double *out) +{ + return tsd_leafward_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +eval_rootward_projection(const double *in, double *out) +{ + return tsd_rootward_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +eval_unphased_projection(const double *in, double *out) +{ + return tsd_unphased_projection(in, in + 2, in + 4, out, out + 1, out + 3); +} + +static int +eval_twin_projection(const double *in, double *out) +{ + return tsd_twin_projection(in, in + 2, out, out + 1); +} + +static int +eval_sideways_projection(const double *in, double *out) +{ + return tsd_sideways_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +eval_mutation_gamma_projection(const double *in, double *out) +{ + return tsd_mutation_gamma_projection(in, in + 2, in + 4, out, out + 1); +} + +static int +eval_mutation_leafward_projection(const double *in, double *out) +{ + return tsd_mutation_leafward_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +eval_mutation_rootward_projection(const double *in, double *out) +{ + return tsd_mutation_rootward_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +eval_mutation_edge_projection(const double *in, double *out) +{ + return tsd_mutation_edge_projection(in[0], in[1], out, out + 1); +} + +static int +eval_mutation_unphased_projection(const double *in, double *out) +{ + return tsd_mutation_unphased_projection(in, in + 2, in + 4, out, out + 1); +} + +static int +eval_mutation_twin_projection(const double *in, double *out) +{ + return tsd_mutation_twin_projection(in, in + 2, out, out + 1); +} + +static int +eval_mutation_sideways_projection(const double *in, double *out) +{ + return tsd_mutation_sideways_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +eval_mutation_block_projection(const double *in, double *out) +{ + return tsd_mutation_block_projection(in[0], in[1], out, out + 1); +} + +/* Expected values of the reference implementation */ +static const approx_row_t log_moments_rows[] = { + { .in = { 1.0, 1.0 }, .out = { -0.5, 0.5, 1.0 } }, + { .in = { 2.0, 0.5 }, + .out = { 0.6306471805599453, 1.5112943611198906, 0.5188096163482082 } }, + { .in = { 1e+300, 1e+300 }, + .out = { 690.7755278982137, 6.907755278982137e+302, 477170.8299430558 } }, + { .in = { 1e-100, 1e-100 }, .out = { -5e+99, 0.5, 2.312585092994046e+102 } }, + { .in = { 0.0, 1.0 }, .ret = TSD_ERR_NONPOSITIVE_MOMENTS }, + { .in = { -1.0, 1.0 }, .ret = TSD_ERR_NONPOSITIVE_MOMENTS }, + { .in = { 1.0, NAN }, .ret = TSD_ERR_NONPOSITIVE_MOMENTS }, + { .in = { INFINITY, 1.0 }, .out = { INFINITY, INFINITY, NAN } }, + { .in = { 1.0, INFINITY }, .out = { -INFINITY, INFINITY, INFINITY } }, + { .in = { 1e-200, 1.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 5e-324, 1.0 }, .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t gamma_kl_rows[] = { + { .in = { 2.0, 0.5 }, .out = { 1.7439641139785955, 1.3719820569892978 } }, + { .in = { 1.0, -0.5 }, .out = { 0.13772472714785322, 1.1377247271478532 } }, + { .in = { 1.0, -1.0 }, .out = { -0.3844432335204093, 0.6155567664795907 } }, + { .in = { 1.0, -10.0 }, .out = { -0.9169429520050368, 0.08305704799496319 } }, + { .in = { 1.0, -1e+160 }, .out = { -1.0, 5e-161 } }, + { .in = { 1e-300, -700.0 }, .out = { -0.9107243662191306, 8.927563378086943e+298 } }, + { .in = { 1e+308, 709.0 }, .out = { 1.7033875448561395, 2.7033875448561395e-308 } }, + { .in = { 100.0, 3.605170185988092 }, + .out = { -0.3844432335204093, 0.0061555676647959065 } }, + { .in = { 1.0, -1e-06 }, .out = { 499999.0, 500000.0 } }, + { .in = { 1.0, -5.1e-05 }, .out = { 9803.088232501696, 9804.088232501696 } }, + { .in = { 1.0, -5e-324 }, .out = { INFINITY, INFINITY } }, + { .in = { 5e-324, -745.0 }, .out = { 0.02761135468838516, INFINITY } }, + { .in = { 1.0, 0.0 }, .ret = TSD_ERR_JENSEN_VIOLATION }, + { .in = { 1.0, NAN }, .ret = TSD_ERR_JENSEN_VIOLATION }, + { .in = { 1.0, -INFINITY }, .ret = TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS }, + { .in = { 1.0, INFINITY }, .ret = TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS }, + { .in = { 0.0, -1.0 }, .ret = TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS }, + { .in = { INFINITY, -1.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 1.0, -1e+164 }, .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t gamma_mom_rows[] = { + { .in = { 1.0, 1.0 }, .out = { 0.0, 1.0 } }, + { .in = { 2.0, 4.0 }, .out = { 0.0, 0.5 } }, + { .in = { 1000.0, 1e-06 }, .out = { 999999999999.0, 1000000000.0 } }, + { .in = { 5e-324, 5e-324 }, .out = { -1.0, 1.0 } }, + { .in = { 1.0, 1e-300 }, .out = { 9.999999999999999e+299, 9.999999999999999e+299 } }, + { .in = { 1.0, 5e-324 }, .out = { INFINITY, INFINITY } }, + { .in = { INFINITY, 1.0 }, .out = { INFINITY, INFINITY } }, + { .in = { INFINITY, INFINITY }, .out = { NAN, NAN } }, + { .in = { 1e-200, 1e-200 }, .out = { -1.0, 1.0 } }, + { .in = { 1.0, 0.0 }, .ret = TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS }, + { .in = { -1.0, 1.0 }, .ret = TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS }, + { .in = { NAN, 1.0 }, .ret = TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t gamma_iqr_rows[] = { + { .in = { 0.25, 0.75, 1.0, 3.0, 50.0 }, + .out = { 0.7901246810530893, 0.8091070002056516 } }, + { .in = { 0.25, 0.75, 7725.886769523864, 11913.846021515428, 50.0 }, + .out = { 9.00000000000002, 0.0010000000000000022 } }, + { .in = { 0.25, 0.75, 50.765522133810784, 661.6518484657332, 10.0 }, + .out = { -0.5000000000000002, 0.0009999999999999998 } }, + { .in = { 0.25, 0.75, 9932370.564904187, 10067266.062388988, 100000.0 }, + .out = { 9999.000000001251, 0.0010000000000001258 } }, + { .in = { 0.25, 0.75, 46018.97506946053, 55618.243378532934, 50.0 }, + .out = { 49.0, 0.0009793049455175092 } }, + { .in = { 0.25, 0.75, 3.0, 3.0, 50.0 }, .out = { 49.0, 15.022203291056554 } }, + { .in = { 0.25, 0.75, 1.0, 1.1, 2.0 }, .out = { 1.0, 0.9612787631147771 } }, + { .in = { 0.25, 0.75, 0.9612787631147771, 2.692634528889695, 0.0 }, + .out = { -1.0, NAN } }, + { .in = { 0.25, 0.75, 2.0, 1.0, 50.0 }, .ret = TSD_ERR_UNSORTED_QUANTILES }, + { .in = { NAN, 0.75, 1.0, 2.0, 50.0 }, .ret = TSD_ERR_UNSORTED_QUANTILES }, + { .in = { 0.25, 0.75, 0.0, 0.0, 50.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 0.25, 0.75, 0.0, 1.0, 50.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 0.0, 0.75, 1.0, 2.0, 50.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 0.25, 1.0, 1.0, 2.0, 50.0 }, .ret = TSD_ERR_NEGATIVE_SHAPE }, + { .in = { 0.25, 0.75, 1.0, INFINITY, 50.0 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 0.25, 1.5, 1.0, 2.0, 50.0 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 1e-200, 0.99, 1.0, 1.2, 1e+300 }, .ret = TSD_ERR_QUANTILE_MAX_ITERATIONS }, + { .in = { 1e-300, 1e-299, 1.0, 1e+30, 50.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 0.25, 0.75, 5.256386560310826e-218, 9.53e-42, 50.0 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 0.25, 0.75, 1.0, 1.0001, 1000000.0 }, .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t valid_moments_rows[] = { + { .in = { 1.0, 1.0 }, .out = { 1.0 } }, + { .in = { 5e-324, 5e-324 }, .out = { 1.0 } }, + { .in = { 1.7976931348623157e+308, 1.7976931348623157e+308 }, .out = { 1.0 } }, + { .in = { 0.0, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, 0.0 }, .out = { 0.0 } }, + { .in = { -1.0, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, -1.0 }, .out = { 0.0 } }, + { .in = { INFINITY, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, INFINITY }, .out = { 0.0 } }, + { .in = { -INFINITY, 1.0 }, .out = { 0.0 } }, + { .in = { NAN, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, NAN }, .out = { 0.0 } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t valid_gamma_rows[] = { + { .in = { 1.0, 1.0 }, .out = { 1.0 } }, + { .in = { 5e-324, 5e-324 }, .out = { 1.0 } }, + { .in = { 1.7976931348623157e+308, 1.7976931348623157e+308 }, .out = { 1.0 } }, + { .in = { 0.0, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, 0.0 }, .out = { 0.0 } }, + { .in = { -1.0, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, -1.0 }, .out = { 0.0 } }, + { .in = { INFINITY, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, INFINITY }, .out = { 0.0 } }, + { .in = { -INFINITY, 1.0 }, .out = { 0.0 } }, + { .in = { NAN, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, NAN }, .out = { 0.0 } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t moments_rows[] = { + { .in = { 10.0, 0.01, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 122.80948170104746, 1325.342857454897, 103491.97326437547, + 769.094660576317, 48824.51252025319 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 116.94940823258497, 1166.8217386979982, 84456.19337045238, + 829.8081251666888, 51480.22818100476 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 10000.0, 0.001 }, + .out = { 127387.4510634497, 910499.7977042779, 82752252.49682617, + 500.247250327001, 25024.723677237344 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 0.0, 0.0 }, + .out = { 116.98310817144016, 1172.1993731606126, 85998.44190601562, + 827.8006268393875, 51558.56727389339 } }, + { .in = { 100000000.0, 100000.0, 100000000.0, 100000.0, 1.0, 0.0001 }, + .out = { 1181551036.2989483, 1000.0872852957206, -0.41215872892644256, + 999.9127247041049, -0.41216047620400786 } }, + { .in = { 0.001, 1e-05, 0.001, 1e-05, 1.0, 0.0001 }, + .out = { 16.039512161262337, 9119.186826812647, 83189097.62379722, + 12.339454993237442, 292219.6727362964 } }, + { .in = { 10.0, 100000000.0, 10.0, 100000000.0, 1.0, 100000.0 }, + .out = { -360.6830669942327, 1.3322053216930383e-07, 1.0517374989732554e-15, + 7.672297026879568e-08, 4.877419678730164e-16 } }, + { .in = { 10.0, -0.0001, 10.0, 0.01, 1.0, 0.0001 }, + .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, -0.01, 1.0, 0.0001 }, + .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, -0.02, 1.0, 0.0001 }, + .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, 1000000000.0, 1.0, 0.0001 }, + .out = { -128.77903467642818, 1089.108910901103, 107832.56543473178, + 9.99999999989986e-09, 9.999999999796698e-18 } }, + { .in = { 10.0, 0.01, 0.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, -0.005, 1.0, 0.0001 }, + .out = { 146.80391572052676, 3936.496779205956, 768709.069610931, + 3678.160288231403, 765043.3391407449 } }, + { .in = { 10.0, 0.01, 10.0, INFINITY, 1.0, 0.0001 }, + .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 1210672666.2995348, 852947.3207951145, 7951733.774369938, + 595712303.1396025, -1.5, 2.8337046167584198e-14 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 394.178342527288, 2.415712247192439e-10, 2724.719060396573, + 0.008288652462722177, -1.0, 6.154356625573251e-06 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 5411.613776267856, 5038406234.100642, 4.2430562971178696e-09, + 0.042821205396860865, -1.0, 1163.787749187542 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 14401.04443044055, 18400282.490663443, 7.134225181058526e-10, + 0.005953404256099466, -1.0, 3.5941767717509845e-12 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t unphased_moments_rows[] = { + { .in = { 10.0, 0.01, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 125.0990041915503, 1039.6039603960396, 105381.825311244, + 1039.6039603960396, 105381.825311244 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 117.5080520628614, 990.0990099009902, 98029.60494069196, + 990.0990099009902, 98029.60494069196 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 1.0, 1000000.0 }, + .out = { -261.5263346935328, 1.0499999895000001e-05, 1.0749999784999992e-11, + 1.0499999895000001e-05, 1.0749999784999992e-11 } }, + { .in = { 0.001, 1e-05, 0.001, 1e-05, 1.0, 0.0001 }, + .out = { 16.733009924901715, 4554.545454545454, 62066115.70247932, + 4554.545454545454, 62066115.70247932 } }, + { .in = { 10.0, 0.01, 10.0, 0.0001, 1.0, 0.0001 }, + .out = { 167.56758070890876, 992.1010384560702, 98428.07930575986, + 54898.897557968456, 275005184.82919836 } }, + { .in = { 10.0, 0.01, 10.0, 1000000000.0, 1.0, 0.0001 }, + .out = { -128.77903467622025, 1089.108910891121, 107832.56543475669, + 9.999999999998677e-09, 9.999999999996884e-18 } }, + { .in = { 10.0, -0.001, 10.0, 0.01, 1.0, 0.0001 }, + .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, -0.01, 1.0, 0.0001 }, + .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 0.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, -0.005, 1.0, 0.0001 }, + .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 1.7660035936782157e-09, 670.7541722816065, 72.24709050049042, + 1.592021596132961e-05, 100000000.0, 627.5241160659726 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 2.1430622617768165e-06, 116952.43478981475, 3.3934123772179934e-07, + 9526762.492287748, 100000000.0, 1.1701319088974114 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 1.127136132156607e-08, 8599826.4555504, 3.892603570447169e-09, + 114569.03037514388, 100000000.0, 9.492307871836265e-08 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t rootward_moments_rows[] = { + { .in = { 1000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 63.61325539024935, 1455.418762370423, 74402.48694603037 } }, + { .in = { 1000.0, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 58.00176214728721, 1257.0756375530668, 50989.18526668936 } }, + { .in = { 1000.0, 100000000.0, 100000.0, 1.0, 0.0001 }, + .out = { 590775516.345561, 1000.1237501242261, 0.004335264883656005 } }, + { .in = { 0.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 65.65183097955968, 1089.1089108910892, 107832.5654347613 } }, + { .in = { -1.0, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { NAN, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 5e-324, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 10.0, -0.0001, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, -1.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 10.0, 0.01, -1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 8.45730940350531e-08, 17123191.868610334, 2.9302830155736855e-05, + 100000000.0, 7.326444260535366e-08 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 4.821917030411909e-10, 4.169349483790142e-07, 6.852235429528821e-10, 0.0, + 1.456098777070529e-12 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t leafward_moments_rows[] = { + { .in = { 1000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 63.63521858348348, 670.1964376749686, 22340.35255159228 } }, + { .in = { 1000.0, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 58.18323329851714, 777.4330182308169, 23337.819922300754 } }, + { .in = { 5e-324, 10.0, 0.01, 1.0, 0.0001 }, + .out = { -8193.541271500986, 5e-324, 0.0 } }, + { .in = { 1000.0, 10.0, 0.01, 0.0, 0.0 }, + .out = { 58.20531612967109, 775.058535890135, 23627.901122838375 } }, + { .in = { 1000.0, 10.0, -0.001, 1.0, 0.0001 }, + .out = { 72.10770342368787, 844.497150879899, 9617.330910037155 } }, + { .in = { 0.0, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { NAN, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 0.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 10.0, 0.01, -1.0, 0.0001 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 330585155.6728075, 1.7609486342004178e-07, -25365.04126587679, -1.0, + 7.750515488516166e-07 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 4.74294373446301e-05, 1.4259421729061415e-08, 0.0006672649725106216, -1.0, + 6.017038390421106e-14 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 0.00011848982522731698, 3.0738172972482273e-07, 0.0033569587369897754, + -1.0, 0.02896515217052944 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t sideways_moments_rows[] = { + { .in = { 1000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 66.24960717136513, 1039.3289310811742, 105361.4400384126 } }, + { .in = { 1000.0, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 58.6540260314307, 990.0990099009899, 98029.60494069227 } }, + { .in = { 10000000000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { -999918.2201229396, 990.0990197039497, 98029.60688187221 } }, + { .in = { 1000.0, 0.001, 1e-05, 1.0, 0.0001 }, + .out = { 11.711002789755941, 6980.512954646106, 73216544.51397169 } }, + { .in = { 0.0, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 10.0, -0.001, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 0.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 7951733.774369938, 2.83370461675842e-10, 2.3019958853100635e-08, + 100000000.0, 1.604270854947341e-07 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 4.821917030411909e-10, 4.169349483790142e-07, 6.852235429528821e-10, 0.0, + 1.456098777070529e-12 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t twin_moments_rows[] = { + { .in = { 10.0, 0.01, 1.0, 0.0001 }, + .out = { 66.23660289924649, 1078.4313725490194, 105728.56593617838 } }, + { .in = { 10.0, 0.01, 0.0, 0.0001 }, + .out = { 58.65550306700058, 980.3921568627451, 96116.87812379852 } }, + { .in = { 10.0, 0.01, 0.0, 0.0 }, .out = { 58.85352933996238, 1000.0, 100000.0 } }, + { .in = { 0.001, 1e-05, 1.0, 0.0001 }, + .out = { 9.169442217235714, 4766.666666666666, 22698412.698412694 } }, + { .in = { 10.0, -0.0002, 1.0, 0.0001 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 10.0, 1e-300, 1.0, 0.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 10.0, -0.001, 1.0, 0.0001 }, .out = { NAN, -13750.0, 17187500.0 } }, + { .in = { 0.0, 0.01, 0.0, 0.0001 }, .out = { INFINITY, 0.0, 0.0 } }, + { .in = { NAN, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 1e+300, 0.0001 }, + .out + = { 6.950540426374656e+302, 9.80392156862745e+301, 9.611687812379853e+303 } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_moments_rows[] = { + { .in = { 10.0, 0.01, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 1047.218759015607, 84537.65971991606 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 998.3149319323435, 62090.58297391038 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 100.0, 0.001 }, + .out = { 5502.047266948612, 8593441.597390726 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 0.0, 0.0 }, .out = { 1000.0, 62985.06423178315 } }, + { .in = { 10000.0, 10.0, 10000.0, 10.0, 1.0, 0.0001 }, + .out = { 1000.0499125037055, 81.2219550292939 } }, + { .in = { 10.0, 0.01, 1e-08, 0.01, 1.0, 0.0001 }, + .out = { 544.5544559496102, 134790.70668813813 } }, + { .in = { 10.0, 0.01, 10.0, -0.005, 1.0, 0.0001 }, + .out = { 3807.328533718679, 767088.4841929078 } }, + { .in = { 10.0, -0.0001, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, -0.02, 1.0, 0.0001 }, .out = { NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, 1000.0, 1.0, 0.0001 }, + .out = { 544.3849588249741, 135333.42707343184 } }, + { .in = { 1210672666.2995348, 852947.3207951145, 7951733.774369938, + 595712303.1396025, -1.5, 2.8337046167584198e-14 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 1582171.4459529708, 300601562.7452449, 0.0001303504890295087, + -1852940.2349876668, -1.0, 38.337696337086264 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 5411.613776267856, 5038406234.100642, 4.2430562971178696e-09, + 0.042821205396860865, -1.0, 1163.787749187542 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 634745702.2698317, 329.06825010605945, 0.038930042876279006, + 1.3003726540202816, -0.5, 871.1707853483364 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 14401.04443044055, 18400282.490663443, 7.134225181058526e-10, + 0.005953404256099466, -1.0, 3.5941767717509845e-12 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_rootward_moments_rows[] = { + { .in = { 1000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 1227.7093811852114, 42084.6830752613 } }, + { .in = { 0.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 544.5544554455446, 134790.70679345162 } }, + { .in = { 10000000000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 10000000099.00991, 0.0 } }, + { .in = { 1000.0, 10.0, 0.01, 1.0, 100000.0 }, .out = { 1000.00001, 0.0 } }, + { .in = { 1000.0, 0.001, 1e-05, 1.0, 0.0001 }, + .out = { 6236.530310629031, 38372903.84425615 } }, + { .in = { 1000.0, 10.0, 0.01, -0.5, 0.0001 }, + .out = { 1061.7041169771032, 11122.429033691995 } }, + { .in = { -1.0, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { 1000.0, 10.0, -0.0001, 1.0, 0.0001 }, .out = { NAN, NAN } }, + { .in = { 1000.0, 0.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN } }, + { .in = { 8.45730940350531e-08, 17123191.868610334, 2.9302830155736855e-05, + 100000000.0, 7.326444260535366e-08 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_leafward_moments_rows[] = { + { .in = { 1000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 835.0982188374843, 16510.9833273876 } }, + { .in = { 1000.0, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 888.7165091154084, 11907.278421920608 } }, + { .in = { 1e-10, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 9.166666666666644e-11, 5.876068376064695e-23 } }, + { .in = { 1000.0, 10.0, 0.01, 1.0, 100000.0 }, + .out = { 999.7437094147001, 206.32833492441569 } }, + { .in = { 1000.0, 100000000.0, 100000.0, 1.0, 0.0001 }, + .out = { 999.9383327981366, -0.20729712094180286 } }, + { .in = { 1000.0, 10.0, -0.001, 1.0, 0.0001 }, + .out = { 922.2485754399495, 5220.871643718099 } }, + { .in = { 0.0, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN } }, + { .in = { 1000.0, -1.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN } }, + { .in = { 1000.0, 10.0, 0.01, -1.0, 0.0001 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 330585155.6728075, 1.7609486342004178e-07, -25365.04126587679, -1.0, + 7.750515488516166e-07 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_unphased_moments_rows[] = { + { .in = { 10.0, 0.01, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 0.5, 544.5544554455446, 134790.70679345162 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 0.5, 518.6232909005187, 123148.30189828435 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 0.0, 0.0 }, + .out = { 0.5, 523.8095238095239, 125623.58276643988 } }, + { .in = { 10.0, 0.01, 10.0, 1000000000.0, 1.0, 0.0001 }, + .out = { 1.0000000000000018, 544.5527343394893, 134789.85476212116 } }, + { .in = { 10.0, 0.01, 10.0, 1000.0, 1.0, 0.0001 }, + .out = { 0.9994316225667118, 544.2449430101359, 134882.545335442 } }, + { .in = { 1289.8261024396659, 2.1161296052067344, 0.15552864791315738, + 0.0007984796762152916, 1.0, 4.811169071413665e-07 }, + .out = { 1.0305283005758967, 552.3102881259031, 250943.13466915407 } }, + { .in = { 10.0, -0.001, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 0.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1.7660035936782157e-09, 670.7541722816065, 72.24709050049042, + 1.592021596132961e-05, 100000000.0, 627.5241160659726 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 2.1430622617768165e-06, 116952.43478981475, 3.3934123772179934e-07, + 9526762.492287748, 100000000.0, 1.1701319088974114 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 0.03147408814983863, -3.572097767193457e-06, 6.968397736253467e-05, + 0.0003977607105897399, 100000000.0, 0.00014045130994169163 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 0.8357818401616357, 1.3209477340917621e-09, 0.002340461703952937, + 0.00025633858557600413, 100000000.0, 0.0006572496535582051 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 8.487509248373367e-05, 993617.5506944145, 44356376.30250234, + 12.330141147550119, 100000000.0, 1.5394974045964461e-09 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 8.411928444767107e-07, 5.338254701078075e-06, 7363270781.288286, + -0.012693009987637643, 2.0, 2.6034067423152516 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_twin_moments_rows[] = { + { .in = { 10.0, 0.01, 1.0, 0.0001 }, + .out = { 0.5, 539.2156862745097, 132160.70742022299 } }, + { .in = { 10.0, 0.01, 0.0, 0.0001 }, + .out = { 0.5, 490.19607843137254, 112136.35781109825 } }, + { .in = { 0.001, 1e-05, 1.0, 0.0001 }, + .out = { 0.5, 2383.333333333333, 9459563.49206349 } }, + { .in = { 10.0, -0.001, 1.0, 0.0001 }, .out = { 0.5, -6875.0, 21484375.0 } }, + { .in = { -1.0, 0.01, 0.0, 0.0001 }, + .out = { 0.5, -49.01960784313725, -2402.921953094963 } }, + { .in = { 10.0, -0.0002, 1.0, 0.0001 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 10.0, 1e-300, 1.0, 0.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { NAN, 0.01, 1.0, 0.0001 }, .out = { 0.5, NAN, NAN } }, + { .in = { 10.0, 0.01, 1e+300, 0.0001 }, + .out = { 0.5, 4.901960784313725e+301, NAN } }, + { .in = { 10.0, 0.01, 1.0, 1e+300 }, .out = { 0.5, 2.75e-300, 0.0 } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_sideways_moments_rows[] = { + { .in = { 1000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 0.5023091569426977, 522.1743444926516, 109439.4612022693 } }, + { .in = { 1000.0, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 0.5144541526611798, 509.6511047608551, 102996.39823434927 } }, + { .in = { 1e-10, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 0.0007564619471360778, 544.1407948153603, 134914.7638092785 } }, + { .in = { 0.0, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 10.0, -0.0001, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 0.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 10.0, 0.01, -0.5, 0.0001 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 7951733.774369938, 2.83370461675842e-10, 2.3019958853100635e-08, + 100000000.0, 1.604270854947341e-07 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 3439589.3148461175, 51334026.94161953, -8.147893520675203e-06, -0.5, + 23.460646619971012 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 17.77466115825119, 8.850693381150145e-07, 1.2068705882784672e-08, 0.0, + 7.490387184896008e-07 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 3.785982048609923e-06, 8.363428340996249, 0.0001149777112112498, 10000.0, + 9.903472470733758e-13 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_edge_moments_rows[] = { + { .in = { 3.0, 1.0 }, .out = { 2.0, 0.3333333333333333 } }, + { .in = { 1.0, 3.0 }, .out = { 2.0, 0.3333333333333333 } }, + { .in = { 1.0, 1.0 }, .out = { 1.0, 0.0 } }, + { .in = { 0.0, 0.0 }, .out = { 0.0, 0.0 } }, + { .in = { -1.0, 1.0 }, .out = { 0.0, 0.3333333333333333 } }, + { .in = { 1e+300, 1.0 }, .out = { 5e+299, INFINITY } }, + { .in = { 1e-200, 1e-210 }, .out = { 5.0000000005e-201, 0.0 } }, + { .in = { 1.0, 0.9999999999999999 }, .out = { 1.0, 1.0271626370065257e-33 } }, + { .in = { NAN, 1.0 }, .out = { NAN, NAN } }, + { .in = { INFINITY, INFINITY }, .out = { INFINITY, NAN } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_block_moments_rows[] = { + { .in = { 3.0, 1.0 }, .out = { 0.75, 1.25, 0.7708333333333335 } }, + { .in = { 1.0, 3.0 }, .out = { 0.25, 1.25, 0.7708333333333335 } }, + { .in = { 1.0, 1.0 }, .out = { 0.5, 0.5, 0.08333333333333331 } }, + { .in = { 1e-160, 1e-170 }, .out = { 0.9999999999, 4.9999999995e-161, 8.35e-322 } }, + { .in = { 1e+300, 1.0 }, .out = { 1.0, 5e+299, NAN } }, + { .in = { INFINITY, 1.0 }, .out = { NAN, NAN, NAN } }, + { .in = { 0.0, 1.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { 1.0, 0.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { -1.0, 1.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { NAN, 1.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t gamma_projection_rows[] = { + { .in = { 9.0, 0.01, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 122.80948170104746, 15.972656278565271, 0.012806238161767791, + 11.11495141260517, 0.015752224054613635 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 116.94940823258497, 15.12046334987365, 0.0138157036462671, + 12.375650204416319, 0.016118967504360683 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 10000.0, 0.001 }, + .out = { 127387.4510634497, 10016.973609254037, 0.011002719203796883, + 9.000002984542515, 0.01999012084125545 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 0.0, 0.0 }, + .out = { 116.98310817144016, 14.977630989405377, 0.013630472217643944, + 12.29078587764909, 0.01605553976009227 } }, + { .in = { 99999999.0, 100000.0, 99999999.0, 100000.0, 1.0, 0.0001 }, + .out = { NAN, 99999999.0, 100000.0, 99999999.0, 100000.0 } }, + { .in = { -0.999, 1e-05, -0.999, 1e-05, 1.0, 0.0001 }, + .out = { 16.039512161262337, -0.0003549652818382043, 0.00010961997530075378, + -0.9994789462731773, 4.222664024530874e-05 } }, + { .in = { 9.0, 100000000.0, 9.0, 100000000.0, 1.0, 100000.0 }, + .out = { -360.6830669942327, 15.874657610666617, 126667093.54697211, + 11.068705493063154, 157302375.68724146 } }, + { .in = { 9.0, -0.0001, 9.0, 0.01, 1.0, 0.0001 }, + .out = { NAN, 9.0, -0.0001, 9.0, 0.01 } }, + { .in = { 9.0, 0.01, 9.0, -0.01, 1.0, 0.0001 }, + .out = { NAN, 9.0, 0.01, 9.0, -0.01 } }, + { .in = { 9.0, 0.01, 9.0, -0.02, 1.0, 0.0001 }, + .out = { NAN, 9.0, 0.01, 9.0, -0.02 } }, + { .in = { 9.0, 0.01, 9.0, 1000000000.0, 1.0, 0.0001 }, + .out = { -128.77903467642818, 10.000000000205292, 0.01010000000009563, + 9.000000000003022, 1000000000.0103163 } }, + { .in = { 9.0, 0.01, -1.0, 0.01, 1.0, 0.0001 }, + .out = { NAN, 9.0, 0.01, -1.0, 0.01 } }, + { .in = { 9.0, 0.01, 9.0, -0.005, 1.0, 0.0001 }, + .out = { 146.80391572052676, 19.158480633696577, 0.005120918868822957, + 16.68378654354066, 0.004807780291718522 } }, + { .in = { 9.0, 0.01, 9.0, INFINITY, 1.0, 0.0001 }, + .out = { NAN, 9.0, 0.01, 9.0, INFINITY } }, + { .in = { 1210672665.2995348, 852947.3207951145, 7951732.774369938, + 595712303.1396025, -1.5, 2.8337046167584198e-14 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 393.178342527288, 2.415712247192439e-10, 2723.719060396573, + 0.008288652462722177, -1.0, 6.154356625573251e-06 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 5410.613776267856, 5038406234.100642, -0.9999999957569436, + 0.042821205396860865, -1.0, 1163.787749187542 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 14400.04443044055, 18400282.490663443, -0.9999999992865775, + 0.005953404256099466, -1.0, 3.5941767717509845e-12 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 36.27758386050227, 12.719368036205545, 26317363.808861483, + 1.6898146193313483e-07, 2.0, 3.273276230928174e-07 }, + .out = { NAN, 36.27758386050227, 12.719368036205545, 26317363.808861483, + 1.6898146193313483e-07 } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t leafward_projection_rows[] = { + { .in = { 1000.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 63.63521858348348, 19.105468973013345, 0.029999367115054822 } }, + { .in = { 1000.0, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 58.18323329851714, 24.897967327185235, 0.033312152584052235 } }, + { .in = { 5e-324, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, 9.0, 0.01 } }, + { .in = { 1000.0, 9.0, 0.01, 0.0, 0.0 }, + .out = { 58.20531612967109, 24.42399898040528, 0.032802682382184804 } }, + { .in = { 1000.0, 9.0, -0.001, 1.0, 0.0001 }, + .out = { 72.10770342368787, 73.15523543023349, 0.08780992967586641 } }, + { .in = { 0.0, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { NAN, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, 9.0, 0.01 } }, + { .in = { 1000.0, -1.0, 0.01, 1.0, 0.0001 }, .out = { NAN, -1.0, 0.01 } }, + { .in = { 1000.0, 9.0, 0.01, -1.0, 0.0001 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 330585155.6728075, -0.9999998239051365, -25365.04126587679, -1.0, + 7.750515488516166e-07 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 4.74294373446301e-05, -0.9999999857405782, 0.0006672649725106216, -1.0, + 6.017038390421106e-14 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 0.00011848982522731698, -0.9999996926182703, 0.0033569587369897754, -1.0, + 0.02896515217052944 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t rootward_projection_rows[] = { + { .in = { 1000.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 63.61325539024935, 27.47006680564822, 0.01956142626557827 } }, + { .in = { 1000.0, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 58.00176214728721, 29.991653431297348, 0.024653769833312078 } }, + { .in = { 1000.0, 99999999.0, 100000.0, 1.0, 0.0001 }, + .out = { 590775516.345561, 230723505.49979642, 230694.95797008928 } }, + { .in = { 0.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 65.65183097955968, 10.0, 0.0101 } }, + { .in = { -1.0, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { NAN, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, 9.0, 0.01 } }, + { .in = { 5e-324, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, 9.0, 0.01 } }, + { .in = { 1000.0, 9.0, -0.0001, 1.0, 0.0001 }, .out = { NAN, 9.0, -0.0001 } }, + { .in = { 1000.0, -2.0, 0.01, 1.0, 0.0001 }, .out = { NAN, -2.0, 0.01 } }, + { .in = { 1000.0, 9.0, 0.01, -1.0, 0.0001 }, .out = { NAN, 9.0, 0.01 } }, + { .in = { 8.45730940350531e-08, 17123190.868610334, 2.9302830155736855e-05, + 100000000.0, 7.326444260535366e-08 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 4.821917030411909e-10, -0.9999995830650517, 6.852235429528821e-10, 0.0, + 1.456098777070529e-12 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t unphased_projection_rows[] = { + { .in = { 9.0, 0.01, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 125.0990041915503, 9.255813953488373, 0.009865116279069767, + 9.255813953488373, 0.009865116279069767 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 117.5080520628614, 9.000000000000014, 0.010100000000000013, + 9.000000000000014, 0.010100000000000013 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 1.0, 1000000.0 }, + .out = { -261.5263346935328, 9.255813953488383, 976744.1958139545, + 9.255813953488383, 976744.1958139545 } }, + { .in = { -0.999, 1e-05, -0.999, 1e-05, 1.0, 0.0001 }, + .out = { 16.733009924901715, -0.6657776298268974, 7.338215712383491e-05, + -0.6657776298268974, 7.338215712383491e-05 } }, + { .in = { 9.0, 0.01, 9.0, 0.0001, 1.0, 0.0001 }, + .out = { 167.56758070890876, 8.999834167728347, 0.010079451366455893, + 9.959389565517451, 0.00019962859097389507 } }, + { .in = { 9.0, 0.01, 9.0, 1000000000.0, 1.0, 0.0001 }, + .out = { -128.77903467622025, 10.000000000001114, 0.010100000000000728, + 9.000000000000469, 1000000000.0001793 } }, + { .in = { 9.0, -0.001, 9.0, 0.01, 1.0, 0.0001 }, + .out = { NAN, 9.0, -0.001, 9.0, 0.01 } }, + { .in = { 9.0, 0.01, 9.0, -0.01, 1.0, 0.0001 }, + .out = { NAN, 9.0, 0.01, 9.0, -0.01 } }, + { .in = { 9.0, 0.01, -1.0, 0.01, 1.0, 0.0001 }, + .out = { NAN, 9.0, 0.01, -1.0, 0.01 } }, + { .in = { 9.0, 0.01, 9.0, -0.005, 1.0, 0.0001 }, + .out = { NAN, 9.0, 0.01, 9.0, -0.005 } }, + { .in = { -0.9999999982339964, 670.7541722816065, 71.24709050049042, + 1.592021596132961e-05, 100000000.0, 627.5241160659726 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { -0.9999978569377382, 116952.43478981475, -0.9999996606587622, + 9526762.492287748, 100000000.0, 1.1701319088974114 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { -0.9999999887286387, 8599826.4555504, -0.9999999961073964, + 114569.03037514388, 100000000.0, 9.492307871836265e-08 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 24464916.038703892, 183.8190229856431, 15606407.365774523, + 29.436886993709617, 100.0, 0.036593097704101483 }, + .out = { NAN, 24464916.038703892, 183.8190229856431, 15606407.365774523, + 29.436886993709617 } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t twin_projection_rows[] = { + { .in = { 9.0, 0.01, 1.0, 0.0001 }, .out = { 66.23660289924649, 10.0, 0.0102 } }, + { .in = { 9.0, 0.01, 0.0, 0.0001 }, + .out = { 58.65550306700058, 9.000000000000002, 0.0102 } }, + { .in = { 9.0, 0.01, 0.0, 0.0 }, .out = { 58.85352933996238, 9.0, 0.01 } }, + { .in = { -0.999, 1e-05, 1.0, 0.0001 }, + .out = { 9.169442217235714, 0.0009999999999998899, 0.00021 } }, + { .in = { 9.0, -0.0002, 1.0, 0.0001 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 9.0, 1e-300, 1.0, 0.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 9.0, -0.001, 1.0, 0.0001 }, .out = { NAN, 9.0, -0.001 } }, + { .in = { -1.0, 0.01, 0.0, 0.0001 }, .out = { NAN, -1.0, 0.01 } }, + { .in = { NAN, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, 0.01 } }, + { .in = { 9.0, 0.01, 1e+300, 0.0001 }, + .out = { 6.950540426374656e+302, INFINITY, 0.0102 } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t sideways_projection_rows[] = { + { .in = { 1000.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 66.24960717136513, 9.252371518351646, 0.009864414635015015 } }, + { .in = { 1000.0, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 58.6540260314307, 8.999999999999979, 0.01009999999999998 } }, + { .in = { 10000000000.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { -999918.2201229396, 9.0, 0.01009999990000001 } }, + { .in = { 1000.0, -0.999, 1e-05, 1.0, 0.0001 }, + .out = { 11.711002789755941, -0.3344733566238761, 9.534065013562661e-05 } }, + { .in = { 0.0, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, 9.0, 0.01 } }, + { .in = { 1000.0, 9.0, -0.001, 1.0, 0.0001 }, .out = { NAN, 9.0, -0.001 } }, + { .in = { 1000.0, -1.0, 0.01, 1.0, 0.0001 }, .out = { NAN, -1.0, 0.01 } }, + { .in = { 7951733.774369938, -0.9999999997166296, 2.3019958853100635e-08, + 100000000.0, 1.604270854947341e-07 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 4.821917030411909e-10, -0.9999995830650517, 6.852235429528821e-10, 0.0, + 1.456098777070529e-12 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_gamma_projection_rows[] = { + { .in = { 9.0, 0.01, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 1.0, 11.972527662435708, 0.012387600537857034 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 1.0, 15.051269863867297, 0.016078362999938683 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 100.0, 0.001 }, + .out = { 1.0, 2.5227474097139964, 0.0006402612043839605 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 0.0, 0.0 }, + .out = { 1.0, 14.876779871495089, 0.01587677987149509 } }, + { .in = { 9999.0, 10.0, 9999.0, 10.0, 1.0, 0.0001 }, + .out = { 1.0, 12312.171077179419, 12.312556526656158 } }, + { .in = { 9.0, 0.01, -0.99999999, 0.01, 1.0, 0.0001 }, + .out = { 1.0, 1.2000000057917348, 0.004040000006896114 } }, + { .in = { 9.0, 0.01, 9.0, -0.005, 1.0, 0.0001 }, + .out = { 1.0, 17.89710360978777, 0.004963349877067389 } }, + { .in = { 9.0, -0.0001, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 9.0, 0.01, 9.0, -0.02, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 9.0, 0.01, 9.0, 1000.0, 1.0, 0.0001 }, + .out = { 1.0, 1.1898136314398267, 0.004022546170574629 } }, + { .in = { 1210672665.2995348, 852947.3207951145, 7951732.774369938, + 595712303.1396025, -1.5, 2.8337046167584198e-14 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 1582170.4459529708, 300601562.7452449, -0.9998696495109705, + -1852940.2349876668, -1.0, 38.337696337086264 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 5410.613776267856, 5038406234.100642, -0.9999999957569436, + 0.042821205396860865, -1.0, 1163.787749187542 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 634745701.2698317, 329.06825010605945, -0.961069957123721, + 1.3003726540202816, -0.5, 871.1707853483364 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 14400.04443044055, 18400282.490663443, -0.9999999992865775, + 0.005953404256099466, -1.0, 3.5941767717509845e-12 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_leafward_projection_rows[] = { + { .in = { 1000.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 1.0, 41.23788621654923, 0.05057834547335923 } }, + { .in = { 1000.0, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 1.0, 65.33060936244428, 0.074636409566046 } }, + { .in = { 1e-10, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 1.0, 142.00000000008887, 1560000000000.9734 } }, + { .in = { 1000.0, 9.0, 0.01, 1.0, 100000.0 }, + .out = { 1.0, 4843.160085333926, 4.845401916227049 } }, + { .in = { 1000.0, 99999999.0, 100000.0, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 9.0, -0.001, 1.0, 0.0001 }, + .out = { 1.0, 161.91196048162053, 0.17664647560328842 } }, + { .in = { 0.0, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, -2.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 9.0, 0.01, -1.0, 0.0001 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 330585155.6728075, -0.9999998239051365, -25365.04126587679, -1.0, + 7.750515488516166e-07 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_rootward_projection_rows[] = { + { .in = { 1000.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 1.0, 34.81517584330332, 0.0291723565789877 } }, + { .in = { 0.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 1.0, 1.2000000000000002, 0.00404 } }, + { .in = { 10000000000.0, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 9.0, 0.01, 1.0, 100000.0 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, -0.999, 1e-05, 1.0, 0.0001 }, + .out = { 1.0, 0.01358788152324153, 0.00016252432539224022 } }, + { .in = { 1000.0, 9.0, 0.01, -0.5, 0.0001 }, + .out = { 1.0, 100.34617434659063, 0.0954561376621056 } }, + { .in = { -1.0, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { 1000.0, 9.0, -0.0001, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, -1.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 8.45730940350531e-08, 17123190.868610334, 2.9302830155736855e-05, + 100000000.0, 7.326444260535366e-08 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_edge_projection_rows[] = { + { .in = { 3.0, 1.0 }, .out = { 1.0, 11.0, 6.0 } }, + { .in = { 1.0, 3.0 }, .out = { 1.0, 11.0, 6.0 } }, + { .in = { 1.0, 1.0 }, .out = { NAN, NAN, NAN } }, + { .in = { 0.0, 0.0 }, .out = { NAN, NAN, NAN } }, + { .in = { -1.0, 1.0 }, .out = { NAN, NAN, NAN } }, + { .in = { 1e+300, 1.0 }, .out = { NAN, NAN, NAN } }, + { .in = { 1e-200, 1e-210 }, .out = { NAN, NAN, NAN } }, + { .in = { 1.0, 0.9999999999999999 }, + .out = { 1.0, 9.735556609752802e+32, 9.735556609752802e+32 } }, + { .in = { NAN, 1.0 }, .out = { NAN, NAN, NAN } }, + { .in = { INFINITY, INFINITY }, .out = { NAN, NAN, NAN } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_unphased_projection_rows[] = { + { .in = { 9.0, 0.01, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 0.5, 1.2000000000000002, 0.00404 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 0.5, 1.1841155234657053, 0.004211371841155237 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 0.0, 0.0 }, + .out = { 0.5, 1.1841155234657048, 0.004169675090252709 } }, + { .in = { 9.0, 0.01, 9.0, 1000000000.0, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 9.0, 0.01, 9.0, 1000.0, 1.0, 0.0001 }, + .out = { 0.9994316225667118, 1.19600362119112, 0.004034954572191996 } }, + { .in = { 1288.8261024396659, 2.1161296052067344, -0.8444713520868427, + 0.0007984796762152916, 1.0, 4.811169071413665e-07 }, + .out = { NAN, NAN, NAN } }, + { .in = { 9.0, -0.001, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 9.0, 0.01, -1.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { -0.9999999982339964, 670.7541722816065, 71.24709050049042, + 1.592021596132961e-05, 100000000.0, 627.5241160659726 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { -0.9999978569377382, 116952.43478981475, -0.9999996606587622, + 9526762.492287748, 100000000.0, 1.1701319088974114 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { -0.9685259118501613, -3.572097767193457e-06, -0.9999303160226375, + 0.0003977607105897399, 100000000.0, 0.00014045130994169163 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { -0.1642181598383643, 1.3209477340917621e-09, -0.997659538296047, + 0.00025633858557600413, 100000000.0, 0.0006572496535582051 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { -0.9999151249075162, 993617.5506944145, 44356375.30250234, + 12.330141147550119, 100000000.0, 1.5394974045964461e-09 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { -0.9999991588071555, 5.338254701078075e-06, 7363270780.288286, + -0.012693009987637643, 2.0, 2.6034067423152516 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_twin_projection_rows[] = { + { .in = { 9.0, 0.01, 1.0, 0.0001 }, + .out = { 0.5, 1.1999999999999997, 0.004079999999999999 } }, + { .in = { 9.0, 0.01, 0.0, 0.0001 }, + .out = { 0.5, 1.1428571428571437, 0.004371428571428573 } }, + { .in = { -0.999, 1e-05, 1.0, 0.0001 }, + .out = { 0.5, -0.39952009598080396, 0.0002519496100779844 } }, + { .in = { 9.0, -0.001, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { -2.0, 0.01, 0.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 9.0, -0.0002, 1.0, 0.0001 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 9.0, 1e-300, 1.0, 0.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { NAN, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 9.0, 0.01, 1e+300, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 9.0, 0.01, 1.0, 1e+300 }, .out = { NAN, NAN, NAN } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_sideways_projection_rows[] = { + { .in = { 1000.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 0.5023091569426977, 1.4914783301279306, 0.0047713533926081126 } }, + { .in = { 1000.0, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 0.5144541526611798, 1.5218770077081731, 0.004948242011349156 } }, + { .in = { 1e-10, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 0.0007564619471360778, 1.1946390166820953, 0.004033219044763566 } }, + { .in = { 0.0, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 9.0, -0.0001, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, -1.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 9.0, 0.01, -0.5, 0.0001 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 7951733.774369938, -0.9999999997166296, 2.3019958853100635e-08, + 100000000.0, 1.604270854947341e-07 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 3439589.3148461175, 51334025.94161953, -8.147893520675203e-06, -0.5, + 23.460646619971012 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 17.77466115825119, -0.9999991149306618, 1.2068705882784672e-08, 0.0, + 7.490387184896008e-07 }, + .out = { 0.9999721035237816, -0.9998224001070971, 1.8801875677074958e-05 } }, + { .in = { 3.785982048609923e-06, 7.363428340996249, 0.0001149777112112498, 10000.0, + 9.903472470733758e-13 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_block_projection_rows[] = { + { .in = { 3.0, 1.0 }, .out = { 0.75, 1.0270270270270268, 1.6216216216216213 } }, + { .in = { 1.0, 3.0 }, .out = { 0.25, 1.0270270270270268, 1.6216216216216213 } }, + { .in = { 1.0, 1.0 }, .out = { 0.5, 2.000000000000001, 6.000000000000002 } }, + { .in = { 1e-160, 1e-170 }, + .out = { 0.9999999999, 1.9940828402366866, 5.988232345771314e+160 } }, + { .in = { 1e+300, 1.0 }, .out = { NAN, NAN, NAN } }, + { .in = { INFINITY, 1.0 }, .out = { NAN, NAN, NAN } }, + { .in = { 0.0, 1.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { 1.0, 0.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { -1.0, 1.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { NAN, 1.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t moments_reference_rows[] = { + { .in = { 2.0, 0.0005, 1.5, 0.005, 0.0, 0.001 }, + .out = { 21.031253635355096, 1465.2981427174977, 867475.244355388, + 325.5131964809384, 65995.30447794562 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 1.0, 0.001 }, + .out = { 28.069848515296044, 2190.3945111492285, 1346202.2405353924, + 303.6020583190394, 59860.71923480909 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 2.0, 0.001 }, + .out = { 35.61248206671415, 2881.212121212121, 1802822.4058769522, + 294.5454545454545, 57044.62809917363 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 3.0, 0.001 }, + .out = { 43.470607391223304, 3561.0746641674477, 2253426.739788929, + 289.5970009372071, 55436.63575142145 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t rootward_moments_reference_rows[] = { + { .in = { 0.0, 2.0, 0.0005, 0.0, 0.001 }, + .out = { 13.004580341747944, 1333.3333333333333, 888888.8888888889 } }, + { .in = { 300.0, 2.0, 0.0005, 0.0, 0.001 }, + .out = { 13.226143898180428, 1426.4367816091954, 846082.7057735494 } }, + { .in = { 0.0, 2.0, 0.0005, 1.0, 0.001 }, + .out = { 20.20001769318186, 2000.0, 1333333.3333333333 } }, + { .in = { 300.0, 2.0, 0.0005, 1.0, 0.001 }, + .out = { 20.252958537178554, 2177.551020408163, 1318339.5807302524 } }, + { .in = { 0.0, 2.0, 0.0005, 2.0, 0.001 }, + .out = { 27.800920152723943, 2666.6666666666665, 1777777.7777777778 } }, + { .in = { 300.0, 2.0, 0.0005, 2.0, 0.001 }, + .out = { 27.7906820950991, 2879.7101449275365, 1770216.3411048136 } }, + { .in = { 0.0, 2.0, 0.0005, 3.0, 0.001 }, + .out = { 35.689504684717804, 3333.3333333333335, 2222222.222222222 } }, + { .in = { 300.0, 2.0, 0.0005, 3.0, 0.001 }, + .out = { 35.64611441977607, 3565.9176029962564, 2217677.341525332 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t leafward_moments_reference_rows[] = { + { .in = { 4000.0, 1.5, 0.005, 0.0, 0.001 }, + .out = { 4.161408615811342, 374.9979682813893, 93742.12708625503 } }, + { .in = { 4000.0, 1.5, 0.005, 1.0, 0.001 }, + .out = { 12.357018743574061, 349.13808564794067, 80150.76468380277 } }, + { .in = { 4000.0, 1.5, 0.005, 2.0, 0.001 }, + .out = { 20.55973730319209, 327.1841562569884, 69769.3287114679 } }, + { .in = { 4000.0, 1.5, 0.005, 3.0, 0.001 }, + .out = { 28.7684512099228, 308.1880149638367, 61530.72786327265 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t unphased_moments_reference_rows[] = { + { .in = { 2.0, 0.0005, 1.5, 0.005, 0.0, 0.001 }, + .out = { 20.557791818743823, 1333.333333333334, 888888.8888888899, + 249.99999999999991, 41666.6666666667 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 1.0, 0.001 }, + .out = { 27.925079427104397, 1894.7368421052631, 1322253.0009233607, + 276.3157894736842, 49746.07571560478 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 2.0, 0.001 }, + .out = { 35.60804683970079, 2496.969696969697, 1775916.7431894708, + 292.4242424242424, 55691.766146311726 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 3.0, 0.001 }, + .out = { 43.54162646489553, 3123.6646749954734, 2233786.6546523217, + 302.4171645844649, 59861.8318883694 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t twin_moments_reference_rows[] = { + { .in = { 2.0, 0.0005, 0.0, 0.001 }, + .out = { 11.982929094215963, 800.0, 320000.0 } }, + { .in = { 2.0, 0.0005, 1.0, 0.001 }, + .out = { 19.360688002443837, 1200.0, 480000.0 } }, + { .in = { 2.0, 0.0005, 2.0, 0.001 }, + .out = { 27.143912018779872, 1600.0, 640000.0 } }, + { .in = { 2.0, 0.0005, 3.0, 0.001 }, + .out = { 35.21481810756769, 2000.0, 800000.0 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t sideways_moments_reference_rows[] = { + { .in = { 4000.0, 1.5, 0.005, 0.0, 0.001 }, + .out = { 3.5532114769958763, 250.00000000000006, 41666.6666666666 } }, + { .in = { 4000.0, 1.5, 0.005, 1.0, 0.001 }, + .out = { 11.907885738914343, 259.80392156862735, 44838.52364475213 } }, + { .in = { 4000.0, 1.5, 0.005, 2.0, 0.001 }, + .out = { 20.26486414931765, 270.32988108937496, 48349.64184973649 } }, + { .in = { 4000.0, 1.5, 0.005, 3.0, 0.001 }, + .out = { 28.62431050808071, 281.6521075206035, 52244.75880734118 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_moments_reference_rows[] = { + { .in = { 2.0, 0.0005, 1.5, 0.005, 0.0, 0.001 }, + .out = { 895.4056695992181, 433089.7662654356 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 1.0, 0.001 }, + .out = { 1246.998284734134, 779610.7291236585 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 2.0, 0.001 }, + .out = { 1587.8787878787878, 1192274.2577288034 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 3.0, 0.001 }, + .out = { 1925.3358325523272, 1676579.5131383222 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_rootward_moments_reference_rows[] = { + { .in = { 0.0, 2.0, 0.0005, 0.0, 0.001 }, + .out = { 666.6666666666666, 444444.4444444445 } }, + { .in = { 300.0, 2.0, 0.0005, 0.0, 0.001 }, + .out = { 863.2183908045977, 387765.8871713566 } }, + { .in = { 0.0, 2.0, 0.0005, 1.0, 0.001 }, .out = { 1000.0, 777777.7777777778 } }, + { .in = { 300.0, 2.0, 0.0005, 1.0, 0.001 }, + .out = { 1238.7755102040815, 733213.0130963952 } }, + { .in = { 0.0, 2.0, 0.0005, 2.0, 0.001 }, + .out = { 1333.3333333333333, 1185185.1851851852 } }, + { .in = { 300.0, 2.0, 0.0005, 2.0, 0.001 }, + .out = { 1589.8550724637682, 1144647.4830217757 } }, + { .in = { 0.0, 2.0, 0.0005, 3.0, 0.001 }, + .out = { 1666.6666666666667, 1666666.666666667 } }, + { .in = { 300.0, 2.0, 0.0005, 3.0, 0.001 }, + .out = { 1932.9588014981282, 1628077.262971844 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_leafward_moments_reference_rows[] = { + { .in = { 4000.0, 1.5, 0.005, 0.0, 0.001 }, + .out = { 2187.4989841406946, 1126300.6865257565 } }, + { .in = { 4000.0, 1.5, 0.005, 1.0, 0.001 }, + .out = { 2174.5690428239704, 1137449.6480334653 } }, + { .in = { 4000.0, 1.5, 0.005, 2.0, 0.001 }, + .out = { 2163.592078128494, 1147387.794741298 } }, + { .in = { 4000.0, 1.5, 0.005, 3.0, 0.001 }, + .out = { 2154.094007481918, 1156299.8870258126 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_unphased_moments_reference_rows[] = { + { .in = { 2.0, 0.0005, 1.5, 0.005, 0.0, 0.001 }, + .out = { 0.8007688806687693, 613.2908705909567, 436374.30804978625 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 1.0, 0.001 }, + .out = { 0.8421052631578948, 875.0000000000001, 744243.4210526317 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 2.0, 0.001 }, + .out = { 0.8727272727272726, 1160.3535353535353, 1136786.7436996226 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 3.0, 0.001 }, + .out = { 0.8951656708310697, 1461.2453980324701, 1609952.4534499124 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_twin_moments_reference_rows[] = { + { .in = { 2.0, 0.0005, 0.0, 0.001 }, .out = { 0.5, 400.0, 160000.0 } }, + { .in = { 2.0, 0.0005, 1.0, 0.001 }, .out = { 0.5, 600.0, 280000.0 } }, + { .in = { 2.0, 0.0005, 2.0, 0.001 }, .out = { 0.5, 800.0, 426666.66666666674 } }, + { .in = { 2.0, 0.0005, 3.0, 0.001 }, .out = { 0.5, 1000.0, 600000.0 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_sideways_moments_reference_rows[] = { + { .in = { 4000.0, 1.5, 0.005, 0.0, 0.001 }, + .out = { 0.9432066834365437, 1897.8267337461748, 1432975.9109005476 } }, + { .in = { 4000.0, 1.5, 0.005, 1.0, 0.001 }, + .out = { 0.9411764705882353, 1894.6078431372548, 1434834.7590670255 } }, + { .in = { 4000.0, 1.5, 0.005, 2.0, 0.001 }, + .out = { 0.9390103567318757, 1891.2063674721903, 1436707.9296666533 } }, + { .in = { 4000.0, 1.5, 0.005, 3.0, 0.001 }, + .out = { 0.9366957849587928, 1887.609193595473, 1438586.278385757 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_edge_moments_reference_rows[] = { + { .in = { 4000.0, 300.0 }, .out = { 2150.0, 1140833.3333333333 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_block_moments_reference_rows[] = { + { .in = { 4000.0, 300.0 }, + .out = { 0.9302325581395349, 1870.9302325581393, 1462953.3982332796 } }, +}; + +/* E[x] and E[log x] of gammas, to be matched by the fitted gamma */ +static const approx_row_t gamma_kl_reference_rows[] = { + { .in = { 4000.0, 8.023686794640554 } }, + { .in = { 300.0, 5.334807340526621 } }, +}; + +/* Means and variances, to be matched by the fitted gamma */ +static const approx_row_t gamma_mom_reference_rows[] = { + { .in = { 1468.0830957704875, 872665.4081509365 } }, + { .in = { 324.4688390860673, 66202.99256425913 } }, + { .in = { 2191.550649932301, 1347335.0097574154 } }, + { .in = { 303.16850627538713, 59803.23888483012 } }, + { .in = { 2881.7094765803945, 1803178.2179688085 } }, + { .in = { 294.35894628235206, 57001.41004303977 } }, + { .in = { 3561.3208124108723, 2253566.347481519 } }, + { .in = { 289.5046953459227, 55410.11528755033 } }, +}; + +static void +test_approximate_log_moments(void) +{ + check_rows(eval_log_moments, log_moments_rows, NUM_ROWS(log_moments_rows), 3); } static void -test_approximate_gamma_mom(void) +test_approximate_gamma_kl(void) { - double out[2]; + size_t j; int ret; + double x, logx, shape, rate, dg; + double out[2]; - ret = tsd_approximate_gamma_mom(2.0, 4.0, out); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_EQUAL(out[0], 0.0); - CU_ASSERT_EQUAL(out[1], 0.5); - ret = tsd_approximate_gamma_mom(2.0, 0.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS); - ret = tsd_approximate_gamma_mom(NAN, 1.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS); + check_rows(eval_gamma_kl, gamma_kl_rows, NUM_ROWS(gamma_kl_rows), 2); + for (j = 0; j < NUM_ROWS(gamma_kl_reference_rows); j++) { + x = gamma_kl_reference_rows[j].in[0]; + logx = gamma_kl_reference_rows[j].in[1]; + ret = tsd_approximate_gamma_kl(x, logx, out); + CU_ASSERT_EQUAL_FATAL(ret, 0); + shape = out[0] + 1; + rate = out[1]; + ret = tsd_digamma(shape, &dg); + CU_ASSERT_EQUAL_FATAL(ret, 0); + assert_close_tol(shape / rate, x, 1e-5, 1e-8); + assert_close_tol(dg - log(rate), logx, 1e-5, 1e-8); + } } static void -test_approximate_gamma_iqr(void) +test_approximate_gamma_mom(void) { - double out[2]; + size_t j; int ret; + double mean, variance, shape, rate; + double out[2]; - /* Newton iteration */ - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 3.0, 50.0, out); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(isfinite(out[0]) && isfinite(out[1])); - /* capped shape: equal quantiles, or a lower bound above the cap */ - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 3.0, 3.0, 50.0, out); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_EQUAL(out[0], 49.0); - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 1.0, 1.1, 2.0, out); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_EQUAL(out[0], 1.0); - /* errors */ - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 2.0, 1.0, 50.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_UNSORTED_QUANTILES); - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 0.0, 0.0, 50.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - ret = tsd_approximate_gamma_iqr(0.0, 0.75, 1.0, 2.0, 50.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - ret = tsd_approximate_gamma_iqr(0.25, 0.75, 0.0, 1.0, 50.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - /* no convergence, or a step outside the domain of the incomplete gamma - * derivative */ - ret = tsd_approximate_gamma_iqr(1e-200, 0.99, 1.0, 1.2, 1e300, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_QUANTILE_MAX_ITERATIONS); - ret = tsd_approximate_gamma_iqr(1e-250, 0.5, 1.0, 1e100, 1e300, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_HYPERGEO); - /* the lower quantile is zero, or underflows when squared */ - ret = tsd_approximate_gamma_iqr(1e-10, 0.01, 1.0, 1e300, 50.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - ret = tsd_approximate_gamma_iqr(1e-200, 0.5, 1.0, 5e199, 50.0, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - /* the gradient is zero */ - ret = tsd_approximate_gamma_iqr(0.1, 0.9, 1.0, 1.0000001, 1e20, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + check_rows(eval_gamma_mom, gamma_mom_rows, NUM_ROWS(gamma_mom_rows), 2); + for (j = 0; j < NUM_ROWS(gamma_mom_reference_rows); j++) { + mean = gamma_mom_reference_rows[j].in[0]; + variance = gamma_mom_reference_rows[j].in[1]; + ret = tsd_approximate_gamma_mom(mean, variance, out); + CU_ASSERT_EQUAL_FATAL(ret, 0); + shape = out[0] + 1; + rate = out[1]; + assert_close_tol(shape / rate, mean, 1e-5, 1e-8); + assert_close_tol(shape / (rate * rate), variance, 1e-5, 1e-8); + } } static void -test_average_gammas(void) +test_approximate_gamma_iqr(void) { - const double alpha[] = { 0.5, 3.0 }; - const double beta[] = { 1.0, 2.0 }; - const double zero_rate[] = { 1.0, 0.0 }; - const double pole[] = { -1.0, 3.0 }; - double out[2]; - int ret; + check_rows(eval_gamma_iqr, gamma_iqr_rows, NUM_ROWS(gamma_iqr_rows), 2); +} - ret = tsd_average_gammas(2, alpha, beta, out); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT(isfinite(out[0]) && isfinite(out[1])); - ret = tsd_average_gammas(0, alpha, beta, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - ret = tsd_average_gammas(2, alpha, zero_rate, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - /* digamma has a pole at shape 0 */ - ret = tsd_average_gammas(2, pole, beta, out); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); +static void +test_valid_moments_and_gamma(void) +{ + check_rows(eval_valid_moments, valid_moments_rows, NUM_ROWS(valid_moments_rows), 1); + check_rows(eval_valid_gamma, valid_gamma_rows, NUM_ROWS(valid_gamma_rows), 1); } static void test_valid(void) { - CU_ASSERT_TRUE(tsd_valid_moments(1.0, 1.0)); - CU_ASSERT_FALSE(tsd_valid_moments(NAN, 1.0)); - CU_ASSERT_FALSE(tsd_valid_moments(1.0, 0.0)); - CU_ASSERT_TRUE(tsd_valid_gamma(1.0, 1.0)); - CU_ASSERT_FALSE(tsd_valid_gamma(1.0, INFINITY)); - CU_ASSERT_FALSE(tsd_valid_gamma(0.0, 1.0)); CU_ASSERT_TRUE(tsd_valid_hyp1f1(1.0, 2.0, 0.5)); CU_ASSERT_FALSE(tsd_valid_hyp1f1(1.0, NAN, 0.5)); CU_ASSERT_FALSE(tsd_valid_hyp1f1(2.0, 1.0, 0.5)); @@ -897,188 +2177,128 @@ test_valid(void) CU_ASSERT_FALSE(tsd_valid_hyp2f1(0.0, 2.0, 3.0, 0.5)); } -/* approx: node moments */ static void test_node_moments(void) { - int ret; - double v[5]; - - ret = tsd_moments(10, 0.01, 10, 0.01, 1, 1e-4, v, v + 1, v + 2, v + 3, v + 4); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_TRUE(isfinite(v[0])); - ret = tsd_moments(10, 0.01, 10, -0.02, 1, 1e-4, v, v + 1, v + 2, v + 3, v + 4); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_TRUE(isnan(v[0])); - ret = tsd_moments(10, 0.01, 10, 0.01, 1, 1e-4, v, v + 1, v + 2, v + 3, v + 4); - CU_ASSERT_EQUAL(ret, 0); - - ret = tsd_unphased_moments( - 10, 0.01, 10, 0.01, 1, 1e-4, v, v + 1, v + 2, v + 3, v + 4); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_TRUE(isfinite(v[0])); - ret = tsd_unphased_moments( - 10, -1.0, 10, 0.01, 1, 1e-4, v, v + 1, v + 2, v + 3, v + 4); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_TRUE(isnan(v[0])); - - /* a positive, a zero and an invalid child age; negative and NaN ages are errors */ - ret = tsd_rootward_moments(1000, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_TRUE(isfinite(v[0])); - ret = tsd_rootward_moments(0, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_TRUE(isfinite(v[0])); - ret = tsd_rootward_moments(1000, 10, -1.0, 1, 1e-4, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_TRUE(isnan(v[0])); - ret = tsd_rootward_moments(1e308, 10, 1e10, 1, 1e-4, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_TRUE(isnan(v[0])); - ret = tsd_rootward_moments(-1.0, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_FIXED_AGE); - ret = tsd_rootward_moments(NAN, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_FIXED_AGE); - - ret = tsd_leafward_moments(1000, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_TRUE(isfinite(v[0])); - ret = tsd_leafward_moments(1000, 0, 0.01, 1, 1e-4, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_TRUE(isnan(v[0])); - ret = tsd_leafward_moments(0, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_FIXED_AGE); - - ret = tsd_sideways_moments(1000, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_TRUE(isfinite(v[0])); - ret = tsd_sideways_moments(1000, 10, -1.0, 1, 1e-4, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_TRUE(isnan(v[0])); - ret = tsd_sideways_moments(0, 10, 0.01, 1, 1e-4, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, TSD_ERR_INVALID_FIXED_AGE); - - ret = tsd_twin_moments(10, 0.01, 1, 1e-4, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, 0); - CU_ASSERT_TRUE(isfinite(v[0])); - ret = tsd_twin_moments(10, -2e-4, 1, 1e-4, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); - ret = tsd_twin_moments(10, 1e-300, 1, 0.0, v, v + 1, v + 2); - CU_ASSERT_EQUAL(ret, TSD_ERR_ZERO_DIVISION); + check_rows(eval_moments, moments_rows, NUM_ROWS(moments_rows), 5); + check_rows(eval_unphased_moments, unphased_moments_rows, + NUM_ROWS(unphased_moments_rows), 5); + check_rows(eval_rootward_moments, rootward_moments_rows, + NUM_ROWS(rootward_moments_rows), 3); + check_rows(eval_leafward_moments, leafward_moments_rows, + NUM_ROWS(leafward_moments_rows), 3); + check_rows(eval_sideways_moments, sideways_moments_rows, + NUM_ROWS(sideways_moments_rows), 3); + check_rows(eval_twin_moments, twin_moments_rows, NUM_ROWS(twin_moments_rows), 3); } -/* Each projection once with usable moments, and once with unusable ones (NaN). */ +/* The Laplace approximations against exact moments, with the tolerances of each. */ static void -test_mutation_projections(void) +test_node_moments_reference(void) { - const double pars_i[2] = { 2.0, 1.0 }; - const double pars_j[2] = { 1.0, 2.0 }; - const double pars_ij[2] = { 1.0, 1.0 }; - double pr_m; - double proj[2]; - - CU_ASSERT_EQUAL( - tsd_mutation_gamma_projection(pars_i, pars_j, pars_ij, &pr_m, proj), 0); - CU_ASSERT_EQUAL(pr_m, 1.0); - CU_ASSERT_EQUAL( - tsd_mutation_leafward_projection(2.0, pars_j, pars_ij, &pr_m, proj), 0); - CU_ASSERT_EQUAL( - tsd_mutation_rootward_projection(1.0, pars_i, pars_ij, &pr_m, proj), 0); - CU_ASSERT_EQUAL(tsd_mutation_edge_projection(2.0, 1.0, &pr_m, proj), 0); - CU_ASSERT_EQUAL(pr_m, 1.0); - CU_ASSERT_EQUAL( - tsd_mutation_unphased_projection(pars_i, pars_j, pars_ij, &pr_m, proj), 0); - CU_ASSERT_EQUAL(tsd_mutation_twin_projection(pars_i, pars_ij, &pr_m, proj), 0); - CU_ASSERT_EQUAL( - tsd_mutation_sideways_projection(2.0, pars_j, pars_ij, &pr_m, proj), 0); - CU_ASSERT_EQUAL(tsd_mutation_block_projection(2.0, 1.0, &pr_m, proj), 0); - CU_ASSERT_TRUE(pr_m > 0.0 && pr_m < 1.0); - - /* Zero variance: the moments are unusable, which is in-band. */ - CU_ASSERT_EQUAL(tsd_mutation_edge_projection(1.0, 1.0, &pr_m, proj), 0); - CU_ASSERT_TRUE(isnan(pr_m)); - CU_ASSERT_TRUE(isnan(proj[0])); - CU_ASSERT_TRUE(isnan(proj[1])); + const unsigned int sd_two_node = (1u << 2) | (1u << 4); + const unsigned int sd_one_node = 1u << 2; + + check_reference_rows(eval_moments, moments_reference_rows, + NUM_ROWS(moments_reference_rows), 5, sd_two_node, 1e-2); + check_reference_rows(eval_rootward_moments, rootward_moments_reference_rows, + NUM_ROWS(rootward_moments_reference_rows), 3, sd_one_node, 2e-2); + check_reference_rows(eval_leafward_moments, leafward_moments_reference_rows, + NUM_ROWS(leafward_moments_reference_rows), 3, sd_one_node, 1e-2); + check_reference_rows(eval_unphased_moments, unphased_moments_reference_rows, + NUM_ROWS(unphased_moments_reference_rows), 5, sd_two_node, 1e-2); + check_reference_rows(eval_twin_moments, twin_moments_reference_rows, + NUM_ROWS(twin_moments_reference_rows), 3, sd_one_node, 1e-5); + check_reference_rows(eval_sideways_moments, sideways_moments_reference_rows, + NUM_ROWS(sideways_moments_reference_rows), 3, sd_one_node, 1e-2); } -/* The node projections: usable moments, and unusable ones (NaN, input copied). */ static void test_node_projections(void) { - const double pars[2] = { 1.0, 2.0 }; - const double bad[2] = { -5.0, 1.0 }; - const double edge[2] = { 2.0, 0.5 }; - double logl; - double proj_i[2]; - double proj_j[2]; - - CU_ASSERT_EQUAL(tsd_gamma_projection(pars, pars, edge, &logl, proj_i, proj_j), 0); - CU_ASSERT_TRUE(isfinite(logl)); - CU_ASSERT_EQUAL(tsd_gamma_projection(bad, pars, edge, &logl, proj_i, proj_j), 0); - CU_ASSERT_TRUE(isnan(logl)); - CU_ASSERT_EQUAL(proj_i[0], bad[0]); - CU_ASSERT_EQUAL(proj_j[1], pars[1]); - - CU_ASSERT_EQUAL(tsd_unphased_projection(pars, pars, edge, &logl, proj_i, proj_j), 0); - CU_ASSERT_TRUE(isfinite(logl)); - CU_ASSERT_EQUAL(tsd_unphased_projection(bad, pars, edge, &logl, proj_i, proj_j), 0); - CU_ASSERT_TRUE(isnan(logl)); - - CU_ASSERT_EQUAL(tsd_leafward_projection(2.0, pars, edge, &logl, proj_j), 0); - CU_ASSERT_TRUE(isfinite(logl)); - CU_ASSERT_EQUAL(tsd_leafward_projection(2.0, bad, edge, &logl, proj_j), 0); - CU_ASSERT_TRUE(isnan(logl)); - CU_ASSERT_EQUAL(proj_j[0], bad[0]); - - CU_ASSERT_EQUAL(tsd_rootward_projection(0.5, pars, edge, &logl, proj_i), 0); - CU_ASSERT_TRUE(isfinite(logl)); - CU_ASSERT_EQUAL(tsd_rootward_projection(0.5, bad, edge, &logl, proj_i), 0); - CU_ASSERT_TRUE(isnan(logl)); - - CU_ASSERT_EQUAL(tsd_twin_projection(pars, edge, &logl, proj_i), 0); - CU_ASSERT_TRUE(isfinite(logl)); - CU_ASSERT_EQUAL(tsd_twin_projection(bad, edge, &logl, proj_i), 0); - CU_ASSERT_TRUE(isnan(logl)); - - CU_ASSERT_EQUAL(tsd_sideways_projection(1.0, pars, edge, &logl, proj_j), 0); - CU_ASSERT_TRUE(isfinite(logl)); - CU_ASSERT_EQUAL(tsd_sideways_projection(1.0, bad, edge, &logl, proj_j), 0); - CU_ASSERT_TRUE(isnan(logl)); + check_rows(eval_gamma_projection, gamma_projection_rows, + NUM_ROWS(gamma_projection_rows), 5); + check_rows(eval_leafward_projection, leafward_projection_rows, + NUM_ROWS(leafward_projection_rows), 3); + check_rows(eval_rootward_projection, rootward_projection_rows, + NUM_ROWS(rootward_projection_rows), 3); + check_rows(eval_unphased_projection, unphased_projection_rows, + NUM_ROWS(unphased_projection_rows), 5); + check_rows( + eval_twin_projection, twin_projection_rows, NUM_ROWS(twin_projection_rows), 3); + check_rows(eval_sideways_projection, sideways_projection_rows, + NUM_ROWS(sideways_projection_rows), 3); } -/* approx: mutation moments */ static void test_mutation_moments(void) { - double pr, mn, va; - - CU_ASSERT_EQUAL(tsd_mutation_moments(5, 0.01, 6, 0.02, 2, 0.001, &mn, &va), 0); - CU_ASSERT_TRUE(mn > 0); - /* t <= 0: the hypergeometric domain check fails, in-band */ - CU_ASSERT_EQUAL(tsd_mutation_moments(5, -1, 6, 0.02, 2, 0.5, &mn, &va), 0); - CU_ASSERT_TRUE(isnan(mn)); - CU_ASSERT_EQUAL(tsd_mutation_rootward_moments(1, 5, 0.01, 2, 0.001, &mn, &va), 0); - CU_ASSERT_EQUAL(tsd_mutation_leafward_moments(50, 5, 0.01, 2, 0.001, &mn, &va), 0); - CU_ASSERT_EQUAL( - tsd_mutation_unphased_moments(5, 0.01, 6, 0.02, 2, 0.001, &pr, &mn, &va), 0); - CU_ASSERT_TRUE(pr > 0); - CU_ASSERT_EQUAL( - tsd_mutation_unphased_moments(5, -1, 6, 0.02, 2, 0.5, &pr, &mn, &va), 0); - CU_ASSERT_TRUE(isnan(pr)); - CU_ASSERT_EQUAL(tsd_mutation_twin_moments(5, 0.01, 2, 0.001, &pr, &mn, &va), 0); - CU_ASSERT_EQUAL( - tsd_mutation_sideways_moments(10, 5, 0.01, 2, 0.001, &pr, &mn, &va), 0); - CU_ASSERT_EQUAL( - tsd_mutation_sideways_moments(10, -5, 0.01, 2, 0.001, &pr, &mn, &va), 0); - CU_ASSERT_TRUE(isnan(pr)); - CU_ASSERT_EQUAL(tsd_mutation_sideways_moments(0, 5, 0.01, 2, 0.001, &pr, &mn, &va), - TSD_ERR_INVALID_FIXED_AGE); - CU_ASSERT_EQUAL(tsd_mutation_edge_moments(10, 2, &mn, &va), 0); - CU_ASSERT_EQUAL(tsd_mutation_block_moments(10, 2, &pr, &mn, &va), 0); - CU_ASSERT_EQUAL( - tsd_mutation_block_moments(0, 2, &pr, &mn, &va), TSD_ERR_INVALID_FIXED_AGE); - CU_ASSERT_EQUAL( - tsd_mutation_block_moments(2, 0, &pr, &mn, &va), TSD_ERR_INVALID_FIXED_AGE); + check_rows(eval_mutation_moments, mutation_moments_rows, + NUM_ROWS(mutation_moments_rows), 2); + check_rows(eval_mutation_rootward_moments, mutation_rootward_moments_rows, + NUM_ROWS(mutation_rootward_moments_rows), 2); + check_rows(eval_mutation_leafward_moments, mutation_leafward_moments_rows, + NUM_ROWS(mutation_leafward_moments_rows), 2); + check_rows(eval_mutation_unphased_moments, mutation_unphased_moments_rows, + NUM_ROWS(mutation_unphased_moments_rows), 3); + check_rows(eval_mutation_twin_moments, mutation_twin_moments_rows, + NUM_ROWS(mutation_twin_moments_rows), 3); + check_rows(eval_mutation_sideways_moments, mutation_sideways_moments_rows, + NUM_ROWS(mutation_sideways_moments_rows), 3); + check_rows(eval_mutation_edge_moments, mutation_edge_moments_rows, + NUM_ROWS(mutation_edge_moments_rows), 2); + check_rows(eval_mutation_block_moments, mutation_block_moments_rows, + NUM_ROWS(mutation_block_moments_rows), 3); +} + +/* The Laplace approximations against exact moments, with the tolerances of each. */ +static void +test_mutation_moments_reference(void) +{ + check_reference_rows(eval_mutation_moments, mutation_moments_reference_rows, + NUM_ROWS(mutation_moments_reference_rows), 2, 1u << 1, 2e-2); + check_reference_rows(eval_mutation_rootward_moments, + mutation_rootward_moments_reference_rows, + NUM_ROWS(mutation_rootward_moments_reference_rows), 2, 1u << 1, 1e-2); + check_reference_rows(eval_mutation_leafward_moments, + mutation_leafward_moments_reference_rows, + NUM_ROWS(mutation_leafward_moments_reference_rows), 2, 1u << 1, 1e-2); + check_reference_rows(eval_mutation_unphased_moments, + mutation_unphased_moments_reference_rows, + NUM_ROWS(mutation_unphased_moments_reference_rows), 3, 1u << 2, 1e-2); + check_reference_rows(eval_mutation_twin_moments, + mutation_twin_moments_reference_rows, + NUM_ROWS(mutation_twin_moments_reference_rows), 3, 1u << 2, 1e-5); + check_reference_rows(eval_mutation_sideways_moments, + mutation_sideways_moments_reference_rows, + NUM_ROWS(mutation_sideways_moments_reference_rows), 3, 1u << 2, 1e-2); + check_reference_rows(eval_mutation_edge_moments, + mutation_edge_moments_reference_rows, + NUM_ROWS(mutation_edge_moments_reference_rows), 2, 1u << 1, 1e-5); + check_reference_rows(eval_mutation_block_moments, + mutation_block_moments_reference_rows, + NUM_ROWS(mutation_block_moments_reference_rows), 3, 1u << 2, 1e-5); +} + +static void +test_mutation_projections(void) +{ + check_rows(eval_mutation_gamma_projection, mutation_gamma_projection_rows, + NUM_ROWS(mutation_gamma_projection_rows), 3); + check_rows(eval_mutation_leafward_projection, mutation_leafward_projection_rows, + NUM_ROWS(mutation_leafward_projection_rows), 3); + check_rows(eval_mutation_rootward_projection, mutation_rootward_projection_rows, + NUM_ROWS(mutation_rootward_projection_rows), 3); + check_rows(eval_mutation_edge_projection, mutation_edge_projection_rows, + NUM_ROWS(mutation_edge_projection_rows), 3); + check_rows(eval_mutation_unphased_projection, mutation_unphased_projection_rows, + NUM_ROWS(mutation_unphased_projection_rows), 3); + check_rows(eval_mutation_twin_projection, mutation_twin_projection_rows, + NUM_ROWS(mutation_twin_projection_rows), 3); + check_rows(eval_mutation_sideways_projection, mutation_sideways_projection_rows, + NUM_ROWS(mutation_sideways_projection_rows), 3); + check_rows(eval_mutation_block_projection, mutation_block_projection_rows, + NUM_ROWS(mutation_block_projection_rows), 3); } /* Two samples in each of two individuals below a root: 0, 1 | 2, 3 | root 4 */ @@ -5021,11 +6241,13 @@ main(int argc, char **argv) { "test_approximate_gamma_kl", test_approximate_gamma_kl }, { "test_approximate_gamma_mom", test_approximate_gamma_mom }, { "test_approximate_gamma_iqr", test_approximate_gamma_iqr }, - { "test_average_gammas", test_average_gammas }, + { "test_valid_moments_and_gamma", test_valid_moments_and_gamma }, { "test_valid", test_valid }, { "test_node_moments", test_node_moments }, + { "test_node_moments_reference", test_node_moments_reference }, { "test_node_projections", test_node_projections }, { "test_mutation_moments", test_mutation_moments }, + { "test_mutation_moments_reference", test_mutation_moments_reference }, { "test_mutation_projections", test_mutation_projections }, { "test_block_singletons", test_block_singletons }, { "test_reallocate_unphased", test_reallocate_unphased }, From b68a6a5dd32d752583bedfbd2804156ffcce8a83 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 17:16:37 -0800 Subject: [PATCH 51/56] Remove the exports that only the tests used _tsdate now exports only what tsdate calls, plus strerror and raise_library_error. The scalar functions, average_gammas, marginalize_over_ancestors, fixed_changepoints and poisson_changepoints are tested by the tables in lib/tests/tests.c instead, and the reference implementations of approx, hypergeo, prior, rescaling and variational are deleted with their tests, as are the mpmath and quadrature tests that the tables carry. tsd_average_gammas and tsd_poisson_changepoints had no callers and are deleted with their error code. --- _tsdatemodule.c | 742 --------------------- lib/approx.c | 35 - lib/err.c | 3 - lib/err.h | 1 - lib/rescaling.c | 125 ---- lib/tests/tests.c | 22 +- lib/tsdate.h | 7 - pyproject.toml | 1 - tests/exact_moments.py | 1036 ------------------------------ tests/oracle/__init__.py | 30 +- tests/oracle/_libm.py | 131 ---- tests/oracle/approx.py | 946 --------------------------- tests/oracle/ep_state.py | 184 ------ tests/oracle/errors.py | 4 +- tests/oracle/helpers.py | 8 - tests/oracle/hypergeo.py | 311 --------- tests/oracle/prior.py | 59 -- tests/oracle/rescaling.py | 414 ------------ tests/oracle/variational.py | 651 ------------------- tests/test_approximations.py | 324 ---------- tests/test_hypergeo.py | 213 ------ tests/test_oracle_approx.py | 821 ----------------------- tests/test_oracle_hypergeo.py | 669 ------------------- tests/test_oracle_prior.py | 115 ---- tests/test_oracle_rescaling.py | 952 --------------------------- tests/test_oracle_variational.py | 653 ------------------- tests/test_python_c.py | 8 - tests/test_python_c_approx.py | 99 --- tests/test_python_c_scalar.py | 82 --- uv.lock | 19 - 30 files changed, 25 insertions(+), 8640 deletions(-) delete mode 100644 tests/exact_moments.py delete mode 100644 tests/oracle/_libm.py delete mode 100644 tests/oracle/approx.py delete mode 100644 tests/oracle/ep_state.py delete mode 100644 tests/oracle/hypergeo.py delete mode 100644 tests/oracle/prior.py delete mode 100644 tests/oracle/rescaling.py delete mode 100644 tests/oracle/variational.py delete mode 100644 tests/test_approximations.py delete mode 100644 tests/test_hypergeo.py delete mode 100644 tests/test_oracle_approx.py delete mode 100644 tests/test_oracle_hypergeo.py delete mode 100644 tests/test_oracle_prior.py delete mode 100644 tests/test_oracle_rescaling.py delete mode 100644 tests/test_oracle_variational.py delete mode 100644 tests/test_python_c_approx.py delete mode 100644 tests/test_python_c_scalar.py diff --git a/_tsdatemodule.c b/_tsdatemodule.c index 82a85d73..ea4bf2a6 100644 --- a/_tsdatemodule.c +++ b/_tsdatemodule.c @@ -75,564 +75,6 @@ tsdate_raise_library_error(PyObject *Py_UNUSED(self), PyObject *args) return ret; } -/* - * Scalar functions: "N doubles in, M doubles out" functions of the C library are - * exposed to Python through the table below, with one generic wrapper. To expose a - * new function, write an adapter that unpacks `in` into the C call and stores the - * results in `out`, returning 0 or a library error code, and add a row. - * The Python function takes `num_in` numbers and returns a float (one output) or a - * tuple of floats. - */ -#define MAX_SCALAR_IO 16 - -typedef int (*scalar_adapter_t)(const double *in, double *out); - -typedef struct { - const char *name; - int num_in; - int num_out; - scalar_adapter_t adapter; -} scalar_function_t; - -static int -scalar_digamma(const double *in, double *out) -{ - return tsd_digamma(in[0], out); -} - -static int -scalar_trigamma(const double *in, double *out) -{ - return tsd_trigamma(in[0], out); -} - -static int -scalar_betaln(const double *in, double *out) -{ - out[0] = tsd_betaln(in[0], in[1]); - return 0; -} - -static int -scalar_gammainc_der(const double *in, double *out) -{ - return tsd_gammainc_der(in[0], in[1], out); -} - -static int -scalar_gammainc_inv(const double *in, double *out) -{ - out[0] = tsd_gammaincinv(in[0], in[1]); - return 0; -} - -static int -scalar_hyperu_laplace(const double *in, double *out) -{ - return tsd_hyperu_laplace(in[0], in[1], in[2], out, out + 1); -} - -static int -scalar_hyp1f1_laplace(const double *in, double *out) -{ - return tsd_hyp1f1_laplace(in[0], in[1], in[2], out); -} - -static int -scalar_hyp2f1_laplace(const double *in, double *out) -{ - return tsd_hyp2f1_laplace(in[0], in[1], in[2], in[3], out); -} - -/* approx: helpers */ - -static int -scalar_approximate_log_moments(const double *in, double *out) -{ - return tsd_approximate_log_moments(in[0], in[1], out, out + 1, out + 2); -} - -static int -scalar_approximate_gamma_kl(const double *in, double *out) -{ - return tsd_approximate_gamma_kl(in[0], in[1], out); -} - -static int -scalar_approximate_gamma_mom(const double *in, double *out) -{ - return tsd_approximate_gamma_mom(in[0], in[1], out); -} - -static int -scalar_approximate_gamma_iqr(const double *in, double *out) -{ - return tsd_approximate_gamma_iqr(in[0], in[1], in[2], in[3], in[4], out); -} - -static int -scalar_valid_moments(const double *in, double *out) -{ - out[0] = tsd_valid_moments(in[0], in[1]); - return 0; -} - -static int -scalar_valid_gamma(const double *in, double *out) -{ - out[0] = tsd_valid_gamma(in[0], in[1]); - return 0; -} - -static int -scalar_valid_hyp1f1(const double *in, double *out) -{ - out[0] = tsd_valid_hyp1f1(in[0], in[1], in[2]); - return 0; -} - -static int -scalar_valid_hyperu(const double *in, double *out) -{ - out[0] = tsd_valid_hyperu(in[0], in[1], in[2]); - return 0; -} - -static int -scalar_valid_hyp2f1(const double *in, double *out) -{ - out[0] = tsd_valid_hyp2f1(in[0], in[1], in[2], in[3]); - return 0; -} - -/* - * Adapters of the moment and projection functions. Inputs are flat: ages and shape/rate - * scalars, then the natural parameters `pars_i`, `pars_j`, `pars_ij` (two each) as - * consecutive doubles. Outputs are flat: `logl` or `pr_m`, then the pairs `proj_i`, - * `proj_j` or `proj_m`. - */ - -/* approx: node moments */ -static int -scalar_moments(const double *in, double *out) -{ - return tsd_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, out + 2, - out + 3, out + 4); -} - -static int -scalar_rootward_moments(const double *in, double *out) -{ - return tsd_rootward_moments( - in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); -} - -static int -scalar_leafward_moments(const double *in, double *out) -{ - return tsd_leafward_moments( - in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); -} - -static int -scalar_unphased_moments(const double *in, double *out) -{ - return tsd_unphased_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, - out + 2, out + 3, out + 4); -} - -static int -scalar_twin_moments(const double *in, double *out) -{ - return tsd_twin_moments(in[0], in[1], in[2], in[3], out, out + 1, out + 2); -} - -static int -scalar_sideways_moments(const double *in, double *out) -{ - return tsd_sideways_moments( - in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); -} - -/* approx: node projections */ -static int -scalar_gamma_projection(const double *in, double *out) -{ - return tsd_gamma_projection(in, in + 2, in + 4, out, out + 1, out + 3); -} - -static int -scalar_leafward_projection(const double *in, double *out) -{ - return tsd_leafward_projection(in[0], in + 1, in + 3, out, out + 1); -} - -static int -scalar_rootward_projection(const double *in, double *out) -{ - return tsd_rootward_projection(in[0], in + 1, in + 3, out, out + 1); -} - -static int -scalar_unphased_projection(const double *in, double *out) -{ - return tsd_unphased_projection(in, in + 2, in + 4, out, out + 1, out + 3); -} - -static int -scalar_twin_projection(const double *in, double *out) -{ - return tsd_twin_projection(in, in + 2, out, out + 1); -} - -static int -scalar_sideways_projection(const double *in, double *out) -{ - return tsd_sideways_projection(in[0], in + 1, in + 3, out, out + 1); -} - -/* approx: mutation moments */ -static int -scalar_mutation_moments(const double *in, double *out) -{ - return tsd_mutation_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1); -} - -static int -scalar_mutation_rootward_moments(const double *in, double *out) -{ - return tsd_mutation_rootward_moments( - in[0], in[1], in[2], in[3], in[4], out, out + 1); -} - -static int -scalar_mutation_leafward_moments(const double *in, double *out) -{ - return tsd_mutation_leafward_moments( - in[0], in[1], in[2], in[3], in[4], out, out + 1); -} - -static int -scalar_mutation_unphased_moments(const double *in, double *out) -{ - return tsd_mutation_unphased_moments( - in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, out + 2); -} - -static int -scalar_mutation_twin_moments(const double *in, double *out) -{ - return tsd_mutation_twin_moments(in[0], in[1], in[2], in[3], out, out + 1, out + 2); -} - -static int -scalar_mutation_sideways_moments(const double *in, double *out) -{ - return tsd_mutation_sideways_moments( - in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); -} - -static int -scalar_mutation_edge_moments(const double *in, double *out) -{ - return tsd_mutation_edge_moments(in[0], in[1], out, out + 1); -} - -static int -scalar_mutation_block_moments(const double *in, double *out) -{ - return tsd_mutation_block_moments(in[0], in[1], out, out + 1, out + 2); -} - -/* approx: mutation projections */ -static int -scalar_mutation_gamma_projection(const double *in, double *out) -{ - return tsd_mutation_gamma_projection(in, in + 2, in + 4, out, out + 1); -} - -static int -scalar_mutation_leafward_projection(const double *in, double *out) -{ - return tsd_mutation_leafward_projection(in[0], in + 1, in + 3, out, out + 1); -} - -static int -scalar_mutation_rootward_projection(const double *in, double *out) -{ - return tsd_mutation_rootward_projection(in[0], in + 1, in + 3, out, out + 1); -} - -static int -scalar_mutation_edge_projection(const double *in, double *out) -{ - return tsd_mutation_edge_projection(in[0], in[1], out, out + 1); -} - -static int -scalar_mutation_unphased_projection(const double *in, double *out) -{ - return tsd_mutation_unphased_projection(in, in + 2, in + 4, out, out + 1); -} - -static int -scalar_mutation_twin_projection(const double *in, double *out) -{ - return tsd_mutation_twin_projection(in, in + 2, out, out + 1); -} - -static int -scalar_mutation_sideways_projection(const double *in, double *out) -{ - return tsd_mutation_sideways_projection(in[0], in + 1, in + 3, out, out + 1); -} - -static int -scalar_mutation_block_projection(const double *in, double *out) -{ - return tsd_mutation_block_projection(in[0], in[1], out, out + 1); -} - -/* variational: x and y are the natural parameters of two gammas, in `in` */ -static int -scalar_damp(const double *in, double *out) -{ - return tsd_damp(in, in + 2, in[4], out); -} - -static int -scalar_rescale(const double *in, double *out) -{ - return tsd_rescale(in, in[2], out); -} - -/* clang-format off */ -static const scalar_function_t scalar_functions[] = { - /* hypergeo */ - { "digamma", 1, 1, scalar_digamma }, - { "trigamma", 1, 1, scalar_trigamma }, - { "betaln", 2, 1, scalar_betaln }, - { "gammainc_der", 2, 1, scalar_gammainc_der }, - { "gammainc_inv", 2, 1, scalar_gammainc_inv }, - { "hyperu_laplace", 3, 2, scalar_hyperu_laplace }, - { "hyp1f1_laplace", 3, 1, scalar_hyp1f1_laplace }, - { "hyp2f1_laplace", 4, 1, scalar_hyp2f1_laplace }, - /* approx: helpers */ - { "approximate_log_moments", 2, 3, scalar_approximate_log_moments }, - { "approximate_gamma_kl", 2, 2, scalar_approximate_gamma_kl }, - { "approximate_gamma_mom", 2, 2, scalar_approximate_gamma_mom }, - { "approximate_gamma_iqr", 5, 2, scalar_approximate_gamma_iqr }, - { "valid_moments", 2, 1, scalar_valid_moments }, - { "valid_gamma", 2, 1, scalar_valid_gamma }, - { "valid_hyp1f1", 3, 1, scalar_valid_hyp1f1 }, - { "valid_hyperu", 3, 1, scalar_valid_hyperu }, - { "valid_hyp2f1", 4, 1, scalar_valid_hyp2f1 }, - /* approx: node moments */ - { "moments", 6, 5, scalar_moments }, - { "rootward_moments", 5, 3, scalar_rootward_moments }, - { "leafward_moments", 5, 3, scalar_leafward_moments }, - { "unphased_moments", 6, 5, scalar_unphased_moments }, - { "twin_moments", 4, 3, scalar_twin_moments }, - { "sideways_moments", 5, 3, scalar_sideways_moments }, - /* approx: node projections */ - { "gamma_projection", 6, 5, scalar_gamma_projection }, - { "leafward_projection", 5, 3, scalar_leafward_projection }, - { "rootward_projection", 5, 3, scalar_rootward_projection }, - { "unphased_projection", 6, 5, scalar_unphased_projection }, - { "twin_projection", 4, 3, scalar_twin_projection }, - { "sideways_projection", 5, 3, scalar_sideways_projection }, - /* approx: mutation moments */ - { "mutation_moments", 6, 2, scalar_mutation_moments }, - { "mutation_rootward_moments", 5, 2, scalar_mutation_rootward_moments }, - { "mutation_leafward_moments", 5, 2, scalar_mutation_leafward_moments }, - { "mutation_unphased_moments", 6, 3, scalar_mutation_unphased_moments }, - { "mutation_twin_moments", 4, 3, scalar_mutation_twin_moments }, - { "mutation_sideways_moments", 5, 3, scalar_mutation_sideways_moments }, - { "mutation_edge_moments", 2, 2, scalar_mutation_edge_moments }, - { "mutation_block_moments", 2, 3, scalar_mutation_block_moments }, - /* approx: mutation projections */ - { "mutation_gamma_projection", 6, 3, scalar_mutation_gamma_projection }, - { "mutation_leafward_projection", 5, 3, scalar_mutation_leafward_projection }, - { "mutation_rootward_projection", 5, 3, scalar_mutation_rootward_projection }, - { "mutation_edge_projection", 2, 3, scalar_mutation_edge_projection }, - { "mutation_unphased_projection", 6, 3, scalar_mutation_unphased_projection }, - { "mutation_twin_projection", 4, 3, scalar_mutation_twin_projection }, - { "mutation_sideways_projection", 5, 3, scalar_mutation_sideways_projection }, - { "mutation_block_projection", 2, 3, scalar_mutation_block_projection }, - /* variational: x0, x1, [y0, y1,] s */ - { "damp", 5, 1, scalar_damp }, - { "rescale", 3, 1, scalar_rescale }, -}; -/* clang-format on */ - -#define NUM_SCALAR_FUNCTIONS (sizeof(scalar_functions) / sizeof(scalar_functions[0])) - -/* Method definitions of the scalar functions, filled in at module initialisation. */ -static PyMethodDef scalar_method_defs[NUM_SCALAR_FUNCTIONS]; - -/* Parse `num_in` numbers from the argument tuple. Returns 0, or -1 with an exception. */ -static int -scalar_parse_args(const scalar_function_t *row, PyObject *args, double *in) -{ - int ret = -1; - Py_ssize_t j; - Py_ssize_t num_args = PyTuple_GET_SIZE(args); - - if (num_args != row->num_in) { - PyErr_Format(PyExc_TypeError, "%s() takes exactly %d arguments (%zd given)", - row->name, row->num_in, num_args); - goto out; - } - for (j = 0; j < num_args; j++) { - in[j] = PyFloat_AsDouble(PyTuple_GET_ITEM(args, j)); - if (in[j] == -1.0 && PyErr_Occurred()) { - goto out; - } - } - ret = 0; -out: - return ret; -} - -/* Build the return value: a float for one output, otherwise a tuple of floats. */ -static PyObject * -scalar_build_result(const scalar_function_t *row, const double *out) -{ - PyObject *ret = NULL; - PyObject *item = NULL; - PyObject *tuple = NULL; - int j; - - if (row->num_out == 1) { - ret = PyFloat_FromDouble(out[0]); - goto out; - } - tuple = PyTuple_New(row->num_out); - if (tuple == NULL) { - goto out; - } - for (j = 0; j < row->num_out; j++) { - item = PyFloat_FromDouble(out[j]); - if (item == NULL) { - goto out; - } - PyTuple_SET_ITEM(tuple, j, item); /* steals the reference */ - } - ret = tuple; - tuple = NULL; -out: - Py_XDECREF(tuple); - return ret; -} - -/* The generic wrapper; `self` is the index of the row in the table. */ -static PyObject * -scalar_call(PyObject *self, PyObject *args) -{ - PyObject *ret = NULL; - const scalar_function_t *row; - double in[MAX_SCALAR_IO]; - double out[MAX_SCALAR_IO]; - Py_ssize_t index = PyLong_AsSsize_t(self); - int err; - - row = &scalar_functions[index]; - if (scalar_parse_args(row, args, in) != 0) { - goto out; - } - err = row->adapter(in, out); - if (err != 0) { - handle_library_error(err); - goto out; - } - ret = scalar_build_result(row, out); -out: - return ret; -} - -/* Add one Python function per row of the table to the module. */ -static int -add_scalar_functions(PyObject *module) -{ - int ret = -1; - PyObject *index = NULL; - PyObject *func = NULL; - size_t j; - - for (j = 0; j < NUM_SCALAR_FUNCTIONS; j++) { - scalar_method_defs[j].ml_name = scalar_functions[j].name; - scalar_method_defs[j].ml_meth = (PyCFunction) scalar_call; - scalar_method_defs[j].ml_flags = METH_VARARGS; - scalar_method_defs[j].ml_doc = "Scalar function of the C library."; - index = PyLong_FromSize_t(j); - if (index == NULL) { - goto out; - } - func = PyCFunction_New(&scalar_method_defs[j], index); - Py_DECREF(index); - index = NULL; - if (func == NULL) { - goto out; - } - if (PyModule_AddObject(module, scalar_functions[j].name, func) != 0) { - goto out; - } - func = NULL; /* the module owns the reference now */ - } - ret = 0; -out: - Py_XDECREF(func); - return ret; -} - -/* average_gammas(alpha, beta): natural parameters of the averaged gamma. */ -static PyObject * -tsdate_average_gammas(PyObject *Py_UNUSED(self), PyObject *args) -{ - PyObject *ret = NULL; - PyObject *alpha_obj = NULL; - PyObject *beta_obj = NULL; - PyArrayObject *alpha_array = NULL; - PyArrayObject *beta_array = NULL; - double out[2]; - npy_intp num_alpha, num_beta; - int err; - - if (!PyArg_ParseTuple(args, "OO", &alpha_obj, &beta_obj)) { - goto out; - } - alpha_array = (PyArrayObject *) PyArray_FROMANY( - alpha_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); - if (alpha_array == NULL) { - goto out; - } - beta_array = (PyArrayObject *) PyArray_FROMANY( - beta_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); - if (beta_array == NULL) { - goto out; - } - num_alpha = PyArray_DIM(alpha_array, 0); - num_beta = PyArray_DIM(beta_array, 0); - if (num_alpha != num_beta) { - PyErr_SetString(PyExc_ValueError, "Array sizes are not equal"); - goto out; - } - Py_BEGIN_ALLOW_THREADS - err = tsd_average_gammas((tsd_size_t) num_alpha, - (const double *) PyArray_DATA(alpha_array), - (const double *) PyArray_DATA(beta_array), out); - Py_END_ALLOW_THREADS - if (err != 0) { - handle_library_error(err); - goto out; - } - ret = Py_BuildValue("dd", out[0], out[1]); -out: - Py_XDECREF(alpha_array); - Py_XDECREF(beta_array); - return ret; -} - /* * Functions of the tree sequence (phasing, utilities, prior and rescaling). Arrays are * converted to C-contiguous arrays of the right type and dimension; sizes of arrays @@ -2411,190 +1853,11 @@ static PyTypeObject ExpectationPropagationType = { .tp_new = PyType_GenericNew, }; -#define ARRAY_DIM(array, axis) ((tsd_size_t) PyArray_DIM(array, axis)) - -/* marginalize_over_ancestors(val): val has at least two rows. */ -static PyObject * -tsdate_marginalize_over_ancestors(PyObject *Py_UNUSED(self), PyObject *args) -{ - PyObject *ret = NULL; - PyObject *val_obj = NULL; - PyArrayObject *val_array = NULL; - PyObject *output = NULL; - npy_intp dims[2]; - int err; - - if (!PyArg_ParseTuple(args, "O", &val_obj)) { - goto out; - } - val_array = (PyArrayObject *) PyArray_FROMANY( - val_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); - if (val_array == NULL) { - goto out; - } - dims[0] = PyArray_DIM(val_array, 0) + 1; - dims[1] = PyArray_DIM(val_array, 1); - output = PyArray_SimpleNew(2, dims, NPY_FLOAT64); - if (output == NULL) { - goto out; - } - Py_BEGIN_ALLOW_THREADS - err = tsd_marginalize_over_ancestors(ARRAY_DIM(val_array, 0), - ARRAY_DIM(val_array, 1), (const double *) PyArray_DATA(val_array), - (double *) PyArray_DATA((PyArrayObject *) output)); - Py_END_ALLOW_THREADS - if (err != 0) { - handle_library_error(err); - goto out; - } - ret = output; - output = NULL; -out: - Py_XDECREF(val_array); - Py_XDECREF(output); - return ret; -} - -/* - * Rescaling functions (lib/rescaling.c). Array sizes and shapes are checked here and - * raise ValueError. - */ - -/* A one-dimensional array of tsd_id_t (int32), copied from `data`. */ -static PyObject * -new_id_array(tsd_size_t size, const tsd_id_t *data) -{ - npy_intp dim = (npy_intp) size; - PyObject *ret = PyArray_SimpleNew(1, &dim, NPY_INT32); - - if (ret != NULL && size > 0) { - memcpy(PyArray_DATA((PyArrayObject *) ret), data, size * sizeof(*data)); - } - return ret; -} - -/* A one-dimensional array of doubles, copied from `data`. */ -static PyObject * -new_double_array(tsd_size_t size, const double *data) -{ - npy_intp dim = (npy_intp) size; - PyObject *ret = PyArray_SimpleNew(1, &dim, NPY_FLOAT64); - - if (ret != NULL && size > 0) { - memcpy(PyArray_DATA((PyArrayObject *) ret), data, size * sizeof(*data)); - } - return ret; -} - -/* A C-contiguous array of the given type and dimension from `obj`, or NULL. */ -static PyArrayObject * -get_array(PyObject *obj, int typenum, int ndim) -{ - return (PyArrayObject *) PyArray_FROMANY( - obj, typenum, ndim, ndim, NPY_ARRAY_IN_ARRAY); -} - -/* Raise ValueError and return -1 unless `ok`. */ -static int -check_sizes(int ok, const char *message) -{ - if (!ok) { - PyErr_SetString(PyExc_ValueError, message); - return -1; - } - return 0; -} - -static PyObject * -tsdate_fixed_changepoints(PyObject *Py_UNUSED(self), PyObject *args) -{ - PyObject *ret = NULL; - PyObject *counts_obj = NULL; - PyArrayObject *counts = NULL; - long long epochs; - tsd_id_t *breaks = NULL; - tsd_size_t num_breaks = 0; - int err; - - if (!PyArg_ParseTuple(args, "OL", &counts_obj, &epochs)) { - goto out; - } - counts = get_array(counts_obj, NPY_FLOAT64, 1); - if (counts == NULL) { - goto out; - } - Py_BEGIN_ALLOW_THREADS - err = tsd_fixed_changepoints( - ARRAY_LEN(counts), DOUBLES(counts), (int64_t) epochs, &breaks, &num_breaks); - Py_END_ALLOW_THREADS - if (err != 0) { - handle_library_error(err); - goto out; - } - ret = new_id_array(num_breaks, breaks); -out: - tsd_safe_free(breaks); - Py_XDECREF(counts); - return ret; -} - -static PyObject * -tsdate_poisson_changepoints(PyObject *Py_UNUSED(self), PyObject *args) -{ - PyObject *ret = NULL; - PyObject *counts_obj = NULL; - PyObject *offset_obj = NULL; - PyArrayObject *counts = NULL; - PyArrayObject *offset = NULL; - double penalty, min_counts, min_offset; - tsd_id_t *breaks = NULL; - tsd_size_t num_breaks = 0; - int err; - - if (!PyArg_ParseTuple(args, "OOddd", &counts_obj, &offset_obj, &penalty, &min_counts, - &min_offset)) { - goto out; - } - counts = get_array(counts_obj, NPY_FLOAT64, 1); - offset = get_array(offset_obj, NPY_FLOAT64, 1); - if (counts == NULL || offset == NULL) { - goto out; - } - if (check_sizes(ARRAY_LEN(counts) == ARRAY_LEN(offset), - "counts and offset must have the same size") - != 0) { - goto out; - } - Py_BEGIN_ALLOW_THREADS - err = tsd_poisson_changepoints(ARRAY_LEN(counts), DOUBLES(counts), DOUBLES(offset), - penalty, min_counts, min_offset, &breaks, &num_breaks); - Py_END_ALLOW_THREADS - if (err != 0) { - handle_library_error(err); - goto out; - } - ret = new_id_array(num_breaks, breaks); -out: - tsd_safe_free(breaks); - Py_XDECREF(counts); - Py_XDECREF(offset); - return ret; -} - static PyMethodDef tsdate_methods[] = { { "strerror", (PyCFunction) tsdate_strerror, METH_VARARGS, "Return the message for a library error code." }, { "raise_library_error", (PyCFunction) tsdate_raise_library_error, METH_VARARGS, "Raise the Python exception corresponding to a library error code." }, - { "average_gammas", (PyCFunction) tsdate_average_gammas, METH_VARARGS, - "Natural parameters of the gamma averaging the sufficient statistics of an " - "array of gammas, given as natural parameters." }, - { "marginalize_over_ancestors", (PyCFunction) tsdate_marginalize_over_ancestors, - METH_VARARGS, "Integrate an expectation over counts of extant ancestors." }, - { "fixed_changepoints", (PyCFunction) tsdate_fixed_changepoints, METH_VARARGS, - "Breakpoints dividing counts roughly equally between epochs." }, - { "poisson_changepoints", (PyCFunction) tsdate_poisson_changepoints, METH_VARARGS, - "Changepoints of a Poisson rate under a linear penalty." }, { "block_singletons", (PyCFunction) (void (*)(void)) tsdate_block_singletons, METH_VARARGS | METH_KEYWORDS, "Group the singletons of unphased individuals into blocks." }, @@ -2674,10 +1937,5 @@ PyInit__tsdate(void) return NULL; } - if (add_scalar_functions(module) != 0) { - Py_DECREF(module); - return NULL; - } - return module; } diff --git a/lib/approx.c b/lib/approx.c index 3aa4a762..2ef17b91 100644 --- a/lib/approx.c +++ b/lib/approx.c @@ -280,41 +280,6 @@ tsd_approximate_gamma_iqr( return ret; } -int -tsd_average_gammas( - tsd_size_t num_gammas, const double *alpha, const double *beta, double out[2]) -{ - int ret = 0; - tsd_size_t j; - double shape, rate, dg; - double avg_x = 0.0; - double avg_logx = 0.0; - - if (num_gammas == 0) { - ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); - goto out; - } - for (j = 0; j < num_gammas; j++) { - shape = alpha[j] + 1.0; - rate = beta[j]; - ret = tsd_digamma(shape, &dg); - if (ret != 0) { - goto out; - } - avg_logx += dg - log(rate); - if (rate == 0.0) { - ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); - goto out; - } - avg_x += shape / rate; - } - avg_x /= (double) num_gammas; - avg_logx /= (double) num_gammas; - ret = tsd_approximate_gamma_kl(avg_x, avg_logx, out); -out: - return ret; -} - int tsd_valid_moments(double mn, double va) { diff --git a/lib/err.c b/lib/err.c index c0b71b67..b3bc132a 100644 --- a/lib/err.c +++ b/lib/err.c @@ -102,9 +102,6 @@ tsd_strerror(int err) case TSD_ERR_NONPOSITIVE_INTERVALS: ret = "The number of intervals must be positive"; break; - case TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER: - ret = "The penalty, minimum counts and minimum offset must not be negative"; - break; case TSD_ERR_ZERO_EDGE_SPAN: ret = "Zero edge span in interval"; break; diff --git a/lib/err.h b/lib/err.h index a8289db2..b164fb6b 100644 --- a/lib/err.h +++ b/lib/err.h @@ -64,7 +64,6 @@ /* rescaling */ #define TSD_ERR_NONPOSITIVE_INTERVALS -22 -#define TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER -23 #define TSD_ERR_ZERO_EDGE_SPAN -24 #define TSD_ERR_NON_INCREASING_BREAKPOINTS -25 #define TSD_ERR_INVALID_QUANTILE_WIDTH -26 diff --git a/lib/rescaling.c b/lib/rescaling.c index 48dbb56c..99250c4c 100644 --- a/lib/rescaling.c +++ b/lib/rescaling.c @@ -233,131 +233,6 @@ tsd_fixed_changepoints(tsd_size_t num_counts, const double *counts, int64_t epoc return ret; } -/* The loss of a constant rate for the observations from `i` to `j` */ -static double -poisson_loss(const double *cum_offset, const double *cum_counts, tsd_size_t i, - tsd_size_t j, double min_counts, double min_offset) -{ - double n = cum_offset[j] - cum_offset[i]; - double y = cum_counts[j] - cum_counts[i]; - double loss; - - if (n < min_offset || y < min_counts) { - return INFINITY; - } - loss = -2.0 * y * (log(y) - log(n) - 1.0); - return loss; -} - -int -tsd_poisson_changepoints(tsd_size_t num_counts, const double *counts, - const double *offset, double penalty, double min_counts, double min_offset, - tsd_id_t **breaks, tsd_size_t *num_breaks) -{ - int ret = 0; - double *cum_offset = NULL; - double *cum_counts = NULL; - double *cost = NULL; - double *best = NULL; - tsd_id_t *previous = NULL; - tsd_id_t *candidates = NULL; - tsd_id_t *path = NULL; - tsd_size_t j, k, c, i, num_candidates, num_kept, argmin, num_path; - tsd_id_t current; - double min_cost; - const tsd_size_t dim = num_counts; - - if (!(min_counts >= 0 && min_offset >= 0 && penalty >= 0)) { - ret = tsd_trace_error(TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER); - goto out; - } - cum_offset = malloc((dim + 1) * sizeof(*cum_offset)); - cum_counts = malloc((dim + 1) * sizeof(*cum_counts)); - cost = malloc((dim + 1) * sizeof(*cost)); - best = malloc((dim + 1) * sizeof(*best)); - previous = malloc((dim + 1) * sizeof(*previous)); - candidates = malloc((dim + 1) * sizeof(*candidates)); - if (cum_offset == NULL || cum_counts == NULL || cost == NULL || best == NULL - || previous == NULL || candidates == NULL) { - ret = tsd_trace_error(TSD_ERR_NO_MEMORY); - goto out; - } - cum_offset[0] = 0.0; - cum_counts[0] = 0.0; - for (j = 0; j < dim; j++) { - cum_offset[j + 1] = cum_offset[j] + offset[j]; - cum_counts[j + 1] = cum_counts[j] + counts[j]; - } - - /* - * Optimal partitioning with pruning: `candidates` are the start positions of the - * last segment that can still be optimal, in increasing order; `previous[j]` is - * the start of the last segment of the best partition of the first `j` - * observations. - */ - best[0] = -penalty; - candidates[0] = 0; - num_candidates = 1; - for (j = 1; j <= dim; j++) { - argmin = 0; - min_cost = INFINITY; - for (c = 0; c < num_candidates; c++) { - i = (tsd_size_t) candidates[c]; - cost[i] - = best[i] - + poisson_loss(cum_offset, cum_counts, i, j, min_counts, min_offset) - + penalty; - if (cost[i] < min_cost) { - min_cost = cost[i]; - argmin = i; - } - } - best[j] = min_cost; - num_kept = 0; - for (c = 0; c < num_candidates; c++) { - i = (tsd_size_t) candidates[c]; - if (!(cost[i] > best[j] + penalty)) { - candidates[num_kept] = candidates[c]; - num_kept++; - } - } - candidates[num_kept] = (tsd_id_t) j; - num_candidates = num_kept + 1; - previous[j] = (tsd_id_t) argmin; - } - - /* The changepoints are those on the path from `dim` back to zero */ - num_path = 0; - current = (tsd_id_t) dim; - while (current != 0) { - current = previous[current]; - num_path++; - } - path = malloc((num_path + 1) * sizeof(*path)); - if (path == NULL) { - ret = tsd_trace_error(TSD_ERR_NO_MEMORY); - goto out; - } - path[num_path] = (tsd_id_t) dim; - current = (tsd_id_t) dim; - for (k = num_path; k > 0; k--) { - current = previous[current]; - path[k - 1] = current; - } - *breaks = path; - *num_breaks = num_path + 1; - path = NULL; -out: - tsd_safe_free(cum_offset); - tsd_safe_free(cum_counts); - tsd_safe_free(cost); - tsd_safe_free(best); - tsd_safe_free(previous); - tsd_safe_free(candidates); - tsd_safe_free(path); - return ret; -} - /* ------------------------------------------------------------------------- * * Counting mutations * ------------------------------------------------------------------------- */ diff --git a/lib/tests/tests.c b/lib/tests/tests.c index acf36d19..2930de94 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -23,11 +23,14 @@ */ /* - * Smoke tests for the low-level tsdate API: return codes, error paths and memory - * handling, with coarse sanity checks of results (finite, NaN, simple values). - * Numerical correctness is tested from Python, except for the expectation - * propagation passes on states set directly in the library's struct, and the - * rescaling, prior and damping functions, which have tables of expected values. + * Tests of the low-level tsdate library: return codes, error paths and memory + * handling, and the values of the numerical functions, as tables of inputs and + * expected outputs. The expected values come from the reference implementation of + * each function (compared to within a few ulps) or, for the approximations to + * special functions and moments, from independent references such as mpmath + * (compared to within the accuracy of the approximation). The tree-sweep functions + * of phasing.c and util.c are compared with their reference implementations from + * Python. */ #include @@ -110,11 +113,10 @@ test_strerror(void) TSD_ERR_UNPHASED_INDIVIDUAL_EDGES, TSD_ERR_BLOCK_OUT_OF_BOUNDS, TSD_ERR_PHASE_OUT_OF_RANGE, TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED, TSD_ERR_MUTATION_NODE_NOT_IN_TREE, TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT, - TSD_ERR_NONPOSITIVE_INTERVALS, TSD_ERR_NEGATIVE_CHANGEPOINT_PARAMETER, - TSD_ERR_ZERO_EDGE_SPAN, TSD_ERR_NON_INCREASING_BREAKPOINTS, - TSD_ERR_INVALID_QUANTILE_WIDTH, TSD_ERR_INVALID_POSTERIOR, - TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT, TSD_ERR_NO_POSTERIORS, - TSD_ERR_INVALID_MAX_SHAPE, TSD_ERR_INVALID_MIN_STEP, + TSD_ERR_NONPOSITIVE_INTERVALS, TSD_ERR_ZERO_EDGE_SPAN, + TSD_ERR_NON_INCREASING_BREAKPOINTS, TSD_ERR_INVALID_QUANTILE_WIDTH, + TSD_ERR_INVALID_POSTERIOR, TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT, + TSD_ERR_NO_POSTERIORS, TSD_ERR_INVALID_MAX_SHAPE, TSD_ERR_INVALID_MIN_STEP, TSD_ERR_INVALID_NODE_POSTERIOR, TSD_ERR_INVALID_DAMPING, TSD_ERR_TWIN_EDGE_IN_PHASED_PASS, TSD_ERR_NONPOSITIVE_PENALTY, TSD_ERR_NODE_OUT_OF_BOUNDS, TSD_ERR_EDGE_OUT_OF_BOUNDS, diff --git a/lib/tsdate.h b/lib/tsdate.h index e3913fca..9a3ce118 100644 --- a/lib/tsdate.h +++ b/lib/tsdate.h @@ -97,10 +97,6 @@ int tsd_approximate_gamma_kl(double x, double logx, double out[2]); int tsd_approximate_gamma_mom(double mean, double variance, double out[2]); int tsd_approximate_gamma_iqr( double q1, double q2, double x1, double x2, double max_shape, double out[2]); -/* The natural parameters of the gamma whose mean and mean log are the averages of - * those of `num_gammas` gammas given by natural parameters `alpha`, `beta`. */ -int tsd_average_gammas( - tsd_size_t num_gammas, const double *alpha, const double *beta, double out[2]); int tsd_valid_moments(double mn, double va); int tsd_valid_gamma(double s, double r); @@ -266,9 +262,6 @@ void tsd_epoch_stats_free(tsd_epoch_stats_t *stats); * equally between `epochs` epochs. */ int tsd_fixed_changepoints(tsd_size_t num_counts, const double *counts, int64_t epochs, tsd_id_t **breaks, tsd_size_t *num_breaks); -int tsd_poisson_changepoints(tsd_size_t num_counts, const double *counts, - const double *offset, double penalty, double min_counts, double min_offset, - tsd_id_t **breaks, tsd_size_t *num_breaks); /* `edges_stats` has 2 * num_edges entries and `mutations_edge` num_mutations. */ int tsd_count_mutations(tsd_size_t num_nodes, const uint8_t *node_is_sample, tsd_size_t num_mutations, const tsd_id_t *mutations_node, diff --git a/pyproject.toml b/pyproject.toml index 00ac66a0..d68c9e69 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -76,7 +76,6 @@ test = [ "pytest-cov", "msprime", "tsinfer", - "numdifftools", "matplotlib", ] diff --git a/tests/exact_moments.py b/tests/exact_moments.py deleted file mode 100644 index 827d00c8..00000000 --- a/tests/exact_moments.py +++ /dev/null @@ -1,1036 +0,0 @@ -# flake8: noqa -""" -Moments for EP updates using exact hypergeometric evaluations rather than -a Laplace approximation; intended for testing and accuracy benchmarking. -""" - -from math import exp -from math import log - -import mpmath -import numpy as np -import scipy -from scipy.special import betaln -from math import lgamma - - -def moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_i, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - """ - a = a_j - b = a_i + a_j + y_ij - c = a_j + y_ij + 1 - t = mu_ij + b_i - z = (mu_ij - b_j) / t - f0 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 0, c + 0, z))) - f1 = float(mpmath.log(mpmath.hyp2f1(a + 1, b + 1, c + 1, z))) - f2 = float(mpmath.log(mpmath.hyp2f1(a + 2, b + 2, c + 2, z))) - s1 = a * b / c - s2 = s1 * (a + 1) * (b + 1) / (c + 1) - d1 = s1 * exp(f1 - f0) - d2 = s2 * exp(f2 - f0) - logl = f0 + betaln(y_ij + 1, a) + lgamma(b) - b * log(t) - mn_j = d1 / t - sq_j = d2 / t**2 - va_j = sq_j - mn_j**2 - mn_i = mn_j * z + b / t - sq_i = sq_j * z**2 + (b + 1) * (mn_i + mn_j * z) / t - va_i = sq_i - mn_i**2 - return logl, mn_i, va_i, mn_j, va_j - - -def rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): - """ - log p(t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i - """ - assert t_j >= 0.0 - s = a_i + y_ij - r = mu_ij + b_i - a = y_ij + 1 - b = s + 1 - z = t_j * r - if t_j == 0.0: - logl = lgamma(s) - s * log(r) - mn_i = s / r - va_i = s / r**2 - return logl, mn_i, va_i - f0 = float(mpmath.log(mpmath.hyperu(a + 0, b + 0, z))) - f1 = float(mpmath.log(mpmath.hyperu(a + 1, b + 1, z))) - f2 = float(mpmath.log(mpmath.hyperu(a + 2, b + 2, z))) - d0 = -a * exp(f1 - f0) - d1 = -(a + 1) * exp(f2 - f1) - logl = f0 - b_i * t_j + (b - 1) * log(t_j) + lgamma(a) - mn_i = t_j * (1 - d0) - va_i = t_j**2 * d0 * (d1 - d0) - return logl, mn_i, va_i - - -def leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - """ - assert t_i > 0.0 - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij - b_j) - f0 = float(mpmath.log(mpmath.hyp1f1(a + 0, b + 0, z))) - f1 = float(mpmath.log(mpmath.hyp1f1(a + 1, b + 1, z))) - f2 = float(mpmath.log(mpmath.hyp1f1(a + 2, b + 2, z))) - d1 = a / b * exp(f1 - f0) - d2 = a / b * (a + 1) / (b + 1) * exp(f2 - f0) - logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + betaln(a, b - a) - mn_j = t_i * d1 - sq_j = t_i**2 * d2 - va_j = sq_j - mn_j**2 - return logl, mn_j, va_j - - -def unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - """ - a = a_j - b = a_i + a_j + y_ij - c = a_j + a_i - t = mu_ij + b_i - z = (mu_ij + b_j) / t - f0 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 0, c + 0, 1 - z))) - f1 = float(mpmath.log(mpmath.hyp2f1(a + 1, b + 1, c + 1, 1 - z))) - f2 = float(mpmath.log(mpmath.hyp2f1(a + 2, b + 2, c + 2, 1 - z))) - s1 = a * b / c - s2 = s1 * (a + 1) * (b + 1) / (c + 1) - d1 = s1 * exp(f1 - f0) - d2 = s2 * exp(f2 - f0) - logl = f0 + betaln(a_j, a_i) + lgamma(b) - b * log(t) - mn_j = d1 / t - sq_j = d2 / t**2 - va_j = sq_j - mn_j**2 - mn_i = b / t - mn_j * z - sq_i = sq_j * z**2 + (b + 1) * (mn_i - mn_j * z) / t - va_i = sq_i - mn_i**2 - return logl, mn_i, va_i, mn_j, va_j - - -def twin_moments(a_i, b_i, y_ij, mu_ij): - """ - log p(t_i) := \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i - """ - s = a_i + y_ij - r = b_i + 2 * mu_ij - logl = log(2) * y_ij + lgamma(s) - log(r) * s - mn_i = s / r - va_i = s / r**2 - return logl, mn_i, va_i - - -def sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - """ - assert t_i > 0.0 - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij + b_j) - f0 = float(mpmath.log(mpmath.hyperu(a + 0, b + 0, z))) - f1 = float(mpmath.log(mpmath.hyperu(a + 1, b + 1, z))) - f2 = float(mpmath.log(mpmath.hyperu(a + 2, b + 2, z))) - d0 = -a * exp(f1 - f0) - d1 = -(a + 1) * exp(f2 - f1) - logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + lgamma(a) - mn_j = -t_i * d0 - va_j = t_i**2 * d0 * (d1 - d0) - return logl, mn_j, va_j - - -def mutation_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_m, t_i, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(int(t_j < t_m < t_i) / (t_i - t_j)) - """ - a = a_j - b = a_i + a_j + y_ij - c = a_j + y_ij + 1 - t = mu_ij + b_i - z = (mu_ij - b_j) / t - f000 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 0, c + 0, z))) - f020 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 2, c + 0, z))) - f111 = float(mpmath.log(mpmath.hyp2f1(a + 1, b + 1, c + 1, z))) - f121 = float(mpmath.log(mpmath.hyp2f1(a + 1, b + 2, c + 1, z))) - f222 = float(mpmath.log(mpmath.hyp2f1(a + 2, b + 2, c + 2, z))) - s1 = a * b / c - s2 = s1 * (a + 1) * (b + 1) / (c + 1) - d1 = b * (b + 1) / t**2 - d2 = d1 * a / c - d3 = d2 * (a + 1) / (c + 1) - mn_m = s1 * exp(f111 - f000) / t / 2 * (1 + z) + b / t / 2 - sq_m = ( - d1 * exp(f020 - f000) / 3 + d2 * exp(f121 - f000) / 3 + d3 * exp(f222 - f000) / 3 - ) - va_m = sq_m - mn_m**2 - return mn_m, va_m - - -def mutation_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): - """ - log p(t_m, t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(int(t_j < t_m < t_i) / (t_i - t_j)) - """ - logl, mn_i, va_i = rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) - mn_m = mn_i / 2 + t_j / 2 - sq_m = (va_i + mn_i**2 + mn_i * t_j + t_j**2) / 3 - va_m = sq_m - mn_m**2 - return mn_m, va_m - - -def mutation_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_m, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(int(t_j < t_m < t_i) / (t_i - t_j)) - """ - logl, mn_j, va_j = leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) - mn_m = mn_j / 2 + t_i / 2 - sq_m = (va_j + mn_j**2 + mn_j * t_i + t_i**2) / 3 - va_m = sq_m - mn_m**2 - return mn_m, va_m - - -def mutation_unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_m, t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - """ - a = a_j - b = a_j + a_i + y_ij - c = a_j + a_i - t = mu_ij + b_i - z = (mu_ij + b_j) / t - f000 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 0, c + 0, 1 - z))) - f001 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 0, c + 1, 1 - z))) - f012 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 1, c + 2, 1 - z))) - f023 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 2, c + 3, 1 - z))) - f212 = float(mpmath.log(mpmath.hyp2f1(a + 2, b + 1, c + 2, 1 - z))) - f323 = float(mpmath.log(mpmath.hyp2f1(a + 3, b + 2, c + 3, 1 - z))) - s0 = b / t / c / (c + 1) - s1 = (c - a) * (c - a + 1) - s2 = a * (a + 1) - d0 = s0 * (b + 1) / t / (c + 2) - d1 = s1 * (c - a + 2) - d2 = s2 * (a + 2) - mn_m = s0 * s1 * exp(f012 - f000) / 2 + s0 * s2 * exp(f212 - f000) / 2 - sq_m = d0 * d1 * exp(f023 - f000) / 3 + d0 * d2 * exp(f323 - f000) / 3 - va_m = sq_m - mn_m**2 - pr_m = (c - a) / c * exp(f001 - f000) - return pr_m, mn_m, va_m - - -def mutation_twin_moments(a_i, b_i, y_ij, mu_ij): - """ - log p(t_m, t_i) := \ - log(int(0 < t_m < t_i) / t_i) + \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i - """ - s = a_i + y_ij - r = b_i + 2 * mu_ij - pr_m = 0.5 - mn_m = s / r / 2 - sq_m = (s + 1) * s / 3 / r**2 - va_m = sq_m - mn_m**2 - return pr_m, mn_m, va_m - - -def mutation_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_m, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - """ - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij + b_j) - f00 = float(mpmath.log(mpmath.hyperu(a + 0, b + 0, z))) - f10 = float(mpmath.log(mpmath.hyperu(a + 1, b + 0, z))) - f21 = float(mpmath.log(mpmath.hyperu(a + 2, b + 1, z))) - f32 = float(mpmath.log(mpmath.hyperu(a + 3, b + 2, z))) - pr_m = 1.0 - exp(f10 - f00) * a - mn_m = pr_m * t_i / 2 + t_i * exp(f21 - f00) * a * (a + 1) / 2 - sq_m = pr_m * t_i**2 / 3 + t_i**2 * exp(f32 - f00) * a * (a + 1) * (a + 2) / 3 - va_m = sq_m - mn_m**2 - return pr_m, mn_m, va_m - - -def mutation_edge_moments(t_i, t_j): - """ - log p(t_m) := int(t_j < t_m < t_i) / (t_i - t_j) - """ - mn_m = t_i / 2 + t_j / 2 - va_m = (t_i - t_j) ** 2 / 12 - return mn_m, va_m - - -def mutation_block_moments(t_i, t_j): - """ - log p(t_m) := \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - """ - pr_m = t_i / (t_i + t_j) - mn_m = pr_m * t_i / 2 + (1 - pr_m) * t_j / 2 - sq_m = pr_m * t_i**2 / 3 + (1 - pr_m) * t_j**2 / 3 - va_m = sq_m - mn_m**2 - return pr_m, mn_m, va_m - - -# --- verify exact solutions with quadrature --- # - - -class TestExactMoments: - @staticmethod - def pdf(t_i, t_j, a_i, b_i, a_j, b_j, y, mu): - """ - Target joint (pair) distribution, proportional to the parent/child - marginals (gamma) and a Poisson mutation likelihood - """ - assert 0 < t_j < t_i - return ( - t_i ** (a_i - 1) - * np.exp(-t_i * b_i) - * t_j ** (a_j - 1) - * np.exp(-t_j * b_j) - * (t_i - t_j) ** y - * np.exp(-(t_i - t_j) * mu) - ) - - @staticmethod - def pdf_rootward(t_i, t_j, a_i, b_i, y, mu): - """ - Target conditional distribution, proportional to the parent - marginals (gamma) and a Poisson mutation likelihood at a - fixed child age - """ - assert 0 <= t_j < t_i - return ( - t_i ** (a_i - 1) - * np.exp(-t_i * b_i) - * (t_i - t_j) ** y - * np.exp(-(t_i - t_j) * mu) - ) - - @staticmethod - def pdf_leafward(t_i, t_j, a_j, b_j, y, mu): - """ - Target conditional distribution, proportional to the child - marginals (gamma) and a Poisson mutation likelihood at a - fixed parent age - """ - assert 0 < t_j < t_i - return ( - t_j ** (a_j - 1) - * np.exp(-t_j * b_j) - * (t_i - t_j) ** y - * np.exp(-(t_i - t_j) * mu) - ) - - @staticmethod - def pdf_unphased(t_i, t_j, a_i, b_i, a_j, b_j, y, mu): - """ - Target joint (pair) distribution, proportional to the parent - marginals (gamma) and a Poisson mutation likelihood over the - two branches leading from (present-day) individual to parents - """ - assert t_i > 0 and t_j > 0 - return ( - t_i ** (a_i - 1) - * np.exp(-t_i * b_i) - * t_j ** (a_j - 1) - * np.exp(-t_j * b_j) - * (t_i + t_j) ** y - * np.exp(-(t_i + t_j) * mu) - ) - - @staticmethod - def pdf_twin(t_i, a_i, b_i, y, mu): - """ - Target marginal distribution, proportional to the parent - marginal (gamma) and a Poisson mutation likelihood over the two - branches leading from (present-day) individual to a *single* parent - """ - assert t_i > 0 - return ( - t_i ** (a_i - 1) - * np.exp(-t_i * b_i) - * (t_i + t_i) ** y - * np.exp(-(t_i + t_i) * mu) - ) - - @staticmethod - def pdf_sideways(t_i, t_j, a_j, b_j, y, mu): - """ - Target joint (pair) distribution, proportional to the parent - marginals (gamma) and a Poisson mutation likelihood over the - two branches leading from (present-day) individual to parents, - with left parent fixed to t_i - """ - assert t_i > 0 and t_j > 0 - return ( - t_j ** (a_j - 1) - * np.exp(-t_j * b_j) - * (t_i + t_j) ** y - * np.exp(-(t_i + t_j) * mu) - ) - - @staticmethod - def pdf_edge(x, t_i, t_j): - """ - Mutation uniformly distributed between child and parent - """ - assert t_i > 0 and t_j > 0 - return int(t_j < x < t_i) / (t_i - t_j) - - @staticmethod - def pdf_block(x, t_i, t_j): - """ - Mutation uniformly distributed between child at time zero and one of - two parents with fixed ages - """ - assert t_i > 0 and t_j > 0 - return (int(0 < x < t_i) + int(0 < x < t_j)) / (t_i + t_j) - - def test_moments(self, pars): - """ - Test mean and variance when ages of both nodes are free - """ - logconst, t_i, var_t_i, t_j, var_t_j = moments(*pars) - ck_normconst = scipy.integrate.dblquad( - lambda t_i, t_j: self.pdf(t_i, t_j, *pars), - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - assert np.isclose(logconst, np.log(ck_normconst)) - ck_t_i = scipy.integrate.dblquad( - lambda t_i, t_j: t_i * self.pdf(t_i, t_j, *pars) / ck_normconst, - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - assert np.isclose(t_i, ck_t_i) - ck_t_j = scipy.integrate.dblquad( - lambda t_i, t_j: t_j * self.pdf(t_i, t_j, *pars) / ck_normconst, - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - assert np.isclose(t_j, ck_t_j) - ck_var_t_i = ( - scipy.integrate.dblquad( - lambda t_i, t_j: t_i**2 * self.pdf(t_i, t_j, *pars) / ck_normconst, - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - - ck_t_i**2 - ) - assert np.isclose(var_t_i, ck_var_t_i) - ck_var_t_j = ( - scipy.integrate.dblquad( - lambda t_i, t_j: t_j**2 * self.pdf(t_i, t_j, *pars) / ck_normconst, - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - - ck_t_j**2 - ) - assert np.isclose(var_t_j, ck_var_t_j) - - def test_rootward_moments(self, pars): - """ - Test mean and variance of parent age when child age is fixed to a nonzero value - """ - a_i, b_i, a_j, b_j, y, mu = pars - pars_redux = (a_i, b_i, y, mu) - mn_j = a_j / b_j # point "estimate" for child - for t_j in [0.0, mn_j]: - logconst, t_i, var_t_i = rootward_moments(t_j, *pars_redux) - ck_normconst = scipy.integrate.quad( - lambda t_i: self.pdf_rootward(t_i, t_j, *pars_redux), - t_j, - np.inf, - epsabs=0, - )[0] - assert np.isclose(logconst, np.log(ck_normconst)) - ck_t_i = scipy.integrate.quad( - lambda t_i: t_i * self.pdf_rootward(t_i, t_j, *pars_redux) / ck_normconst, - t_j, - np.inf, - epsabs=0, - )[0] - assert np.isclose(t_i, ck_t_i) - ck_var_t_i = ( - scipy.integrate.quad( - lambda t_i: ( - t_i**2 * self.pdf_rootward(t_i, t_j, *pars_redux) / ck_normconst - ), - t_j, - np.inf, - epsabs=0, - )[0] - - ck_t_i**2 - ) - assert np.isclose(var_t_i, ck_var_t_i) - - def test_leafward_moments(self, pars): - """ - Test mean and variance of child age when parent age is fixed to a nonzero value - """ - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i # point "estimate" for parent - pars_redux = (a_j, b_j, y, mu) - logconst, t_j, var_t_j = leafward_moments(t_i, *pars_redux) - ck_normconst = scipy.integrate.quad( - lambda t_j: self.pdf_leafward(t_i, t_j, *pars_redux), - 0, - t_i, - epsabs=0, - )[0] - assert np.isclose(logconst, np.log(ck_normconst)) - ck_t_j = scipy.integrate.quad( - lambda t_j: t_j * self.pdf_leafward(t_i, t_j, *pars_redux) / ck_normconst, - 0, - t_i, - epsabs=0, - )[0] - assert np.isclose(t_j, ck_t_j) - ck_var_t_j = ( - scipy.integrate.quad( - lambda t_j: ( - t_j**2 * self.pdf_leafward(t_i, t_j, *pars_redux) / ck_normconst - ), - 0, - t_i, - epsabs=0, - )[0] - - ck_t_j**2 - ) - assert np.isclose(var_t_j, ck_var_t_j) - - def test_unphased_moments(self, pars): - """ - Parent ages for an singleton nodes above an unphased individual - """ - logconst, t_i, var_t_i, t_j, var_t_j = unphased_moments(*pars) - ck_normconst = scipy.integrate.dblquad( - lambda t_i, t_j: self.pdf_unphased(t_i, t_j, *pars), - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - assert np.isclose(logconst, np.log(ck_normconst)) - ck_t_i = scipy.integrate.dblquad( - lambda t_i, t_j: t_i * self.pdf_unphased(t_i, t_j, *pars) / ck_normconst, - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - assert np.isclose(t_i, ck_t_i) - ck_t_j = scipy.integrate.dblquad( - lambda t_i, t_j: t_j * self.pdf_unphased(t_i, t_j, *pars) / ck_normconst, - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - assert np.isclose(t_j, ck_t_j) - ck_var_t_i = ( - scipy.integrate.dblquad( - lambda t_i, t_j: ( - t_i**2 * self.pdf_unphased(t_i, t_j, *pars) / ck_normconst - ), - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - - ck_t_i**2 - ) - assert np.isclose(var_t_i, ck_var_t_i) - ck_var_t_j = ( - scipy.integrate.dblquad( - lambda t_i, t_j: ( - t_j**2 * self.pdf_unphased(t_i, t_j, *pars) / ck_normconst - ), - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - - ck_t_j**2 - ) - assert np.isclose(var_t_j, ck_var_t_j) - - def test_twin_moments(self, pars): - """ - Parent age for one singleton node above an unphased individual - """ - a_i, b_i, a_j, b_j, y_ij, mu_ij = pars - pars_redux = (a_i, b_i, y_ij, mu_ij) - logconst, t_i, var_t_i = twin_moments(*pars_redux) - ck_normconst = scipy.integrate.quad( - lambda t_i: self.pdf_twin(t_i, *pars_redux), - 0, - np.inf, - epsabs=0, - )[0] - assert np.isclose(logconst, np.log(ck_normconst)) - ck_t_i = scipy.integrate.quad( - lambda t_i: t_i * self.pdf_twin(t_i, *pars_redux) / ck_normconst, - 0, - np.inf, - epsabs=0, - )[0] - assert np.isclose(t_i, ck_t_i) - ck_var_t_i = ( - scipy.integrate.quad( - lambda t_i: t_i**2 * self.pdf_twin(t_i, *pars_redux) / ck_normconst, - 0, - np.inf, - epsabs=0, - )[0] - - ck_t_i**2 - ) - assert np.isclose(var_t_i, ck_var_t_i) - - def test_sideways_moments(self, pars): - """ - Parent ages for an singleton nodes above an unphased individual, where - second parent is fixed to a particular time - """ - a_i, b_i, a_j, b_j, y, mu = pars - pars_redux = (a_j, b_j, y, mu) - t_i = a_i / b_i # point "estimate" for left parent - nc, mn, va = sideways_moments(t_i, *pars_redux) - ck_nc = scipy.integrate.quad( - lambda t_j: self.pdf_sideways(t_i, t_j, *pars_redux), - 0, - np.inf, - )[0] - assert np.isclose(np.exp(nc), ck_nc) - ck_mn = ( - scipy.integrate.quad( - lambda t_j: t_j * self.pdf_sideways(t_i, t_j, *pars_redux), - 0, - np.inf, - )[0] - / ck_nc - ) - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.quad( - lambda t_j: t_j**2 * self.pdf_sideways(t_i, t_j, *pars_redux), - 0, - np.inf, - )[0] - / ck_nc - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_moments(self, pars): - """ - Mutation mapped to a single branch with both nodes free - """ - - def f(t_i, t_j): - assert t_j < t_i - mn = t_i / 2 + t_j / 2 - sq = (t_i**2 + t_i * t_j + t_j**2) / 3 - return mn, sq - - mn, va = mutation_moments(*pars) - nc = scipy.integrate.dblquad( - lambda t_i, t_j: self.pdf(t_i, t_j, *pars), - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - ck_mn = ( - scipy.integrate.dblquad( - lambda t_i, t_j: f(t_i, t_j)[0] * self.pdf(t_i, t_j, *pars), - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - / nc - ) - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.dblquad( - lambda t_i, t_j: f(t_i, t_j)[1] * self.pdf(t_i, t_j, *pars), - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - / nc - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_rootward_moments(self, pars): - """ - Mutation mapped to a single branch with child node fixed - """ - - def f(t_i, t_j): # conditional moments - assert t_j < t_i - mn = t_i / 2 + t_j / 2 - sq = (t_i**2 + t_i * t_j + t_j**2) / 3 - return mn, sq - - a_i, b_i, a_j, b_j, y, mu = pars - pars_redux = (a_i, b_i, y, mu) - mn_j = a_j / b_j # point "estimate" for child - for t_j in [0.0, mn_j]: - mn, va = mutation_rootward_moments(t_j, *pars_redux) - nc = scipy.integrate.quad( - lambda t_i: self.pdf_rootward(t_i, t_j, *pars_redux), - t_j, - np.inf, - )[0] - ck_mn = ( - scipy.integrate.quad( - lambda t_i: f(t_i, t_j)[0] * self.pdf_rootward(t_i, t_j, *pars_redux), - t_j, - np.inf, - )[0] - / nc - ) - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.quad( - lambda t_i: f(t_i, t_j)[1] * self.pdf_rootward(t_i, t_j, *pars_redux), - t_j, - np.inf, - )[0] - / nc - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_leafward_moments(self, pars): - """ - Mutation mapped to a single branch with parent node fixed - """ - - def f(t_i, t_j): - assert t_j < t_i - mn = t_i / 2 + t_j / 2 - sq = (t_i**2 + t_i * t_j + t_j**2) / 3 - return mn, sq - - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i # point "estimate" for parent - pars_redux = (a_j, b_j, y, mu) - mn, va = mutation_leafward_moments(t_i, *pars_redux) - nc = scipy.integrate.quad( - lambda t_j: self.pdf_leafward(t_i, t_j, *pars_redux), - 0, - t_i, - )[0] - ck_mn = ( - scipy.integrate.quad( - lambda t_j: f(t_i, t_j)[0] * self.pdf_leafward(t_i, t_j, *pars_redux), - 0, - t_i, - )[0] - / nc - ) - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.quad( - lambda t_j: f(t_i, t_j)[1] * self.pdf_leafward(t_i, t_j, *pars_redux), - 0, - t_i, - )[0] - / nc - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_unphased_moments(self, pars): - """ - Mutation mapped to two singleton branches with children fixed to time zero - """ - - def f(t_i, t_j): # conditional moments - pr = t_i / (t_i + t_j) - mn = pr * t_i / 2 + (1 - pr) * t_j / 2 - sq = pr * t_i**2 / 3 + (1 - pr) * t_j**2 / 3 - return pr, mn, sq - - pr, mn, va = mutation_unphased_moments(*pars) - nc = scipy.integrate.dblquad( - lambda t_i, t_j: self.pdf_unphased(t_i, t_j, *pars), - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - ck_pr = ( - scipy.integrate.dblquad( - lambda t_i, t_j: f(t_i, t_j)[0] * self.pdf_unphased(t_i, t_j, *pars), - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - / nc - ) - assert np.isclose(pr, ck_pr) - ck_mn = ( - scipy.integrate.dblquad( - lambda t_i, t_j: f(t_i, t_j)[1] * self.pdf_unphased(t_i, t_j, *pars), - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - / nc - ) - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.dblquad( - lambda t_i, t_j: f(t_i, t_j)[2] * self.pdf_unphased(t_i, t_j, *pars), - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - / nc - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_twin_moments(self, pars): - """ - Mutation mapped to two singleton branches with children fixed to time zero - and a single parent node - """ - - def f(t_i): # conditional moments - pr = 0.5 - mn = t_i / 2 - sq = t_i**2 / 3 - return pr, mn, sq - - a_i, b_i, a_j, b_j, y_ij, mu_ij = pars - pars_redux = (a_i, b_i, y_ij, mu_ij) - pr, mn, va = mutation_twin_moments(*pars_redux) - nc = scipy.integrate.quad( - lambda t_i: self.pdf_twin(t_i, *pars_redux), - 0, - np.inf, - epsabs=0, - )[0] - ck_pr = ( - scipy.integrate.quad( - lambda t_i: f(t_i)[0] * self.pdf_twin(t_i, *pars_redux), - 0, - np.inf, - epsabs=0, - )[0] - / nc - ) - assert np.isclose(pr, ck_pr) - ck_mn = ( - scipy.integrate.quad( - lambda t_i: f(t_i)[1] * self.pdf_twin(t_i, *pars_redux), - 0, - np.inf, - epsabs=0, - )[0] - / nc - ) - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.quad( - lambda t_i: f(t_i)[2] * self.pdf_twin(t_i, *pars_redux), - 0, - np.inf, - epsabs=0, - )[0] - / nc - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_sideways_moments(self, pars): - """ - Mutation mapped to two branches with children fixed to time zero, and - left parent (i) fixed - """ - - def f(t_i, t_j): # conditional moments - pr = t_i / (t_i + t_j) - mn = pr * t_i / 2 + (1 - pr) * t_j / 2 - sq = pr * t_i**2 / 3 + (1 - pr) * t_j**2 / 3 - return pr, mn, sq - - a_i, b_i, a_j, b_j, y, mu = pars - pars_redux = a_j, b_j, y, mu - t_i = a_i / b_i # point "estimate" for left parent - pr, mn, va = mutation_sideways_moments(t_i, *pars_redux) - nc = scipy.integrate.quad( - lambda t_j: self.pdf_sideways(t_i, t_j, *pars_redux), - 0, - np.inf, - )[0] - ck_pr = ( - scipy.integrate.quad( - lambda t_j: f(t_i, t_j)[0] * self.pdf_sideways(t_i, t_j, *pars_redux), - 0, - np.inf, - )[0] - / nc - ) - assert np.isclose(pr, ck_pr) - ck_mn = ( - scipy.integrate.quad( - lambda t_j: f(t_i, t_j)[1] * self.pdf_sideways(t_i, t_j, *pars_redux), - 0, - np.inf, - )[0] - / nc - ) - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.quad( - lambda t_j: f(t_i, t_j)[2] * self.pdf_sideways(t_i, t_j, *pars_redux), - 0, - np.inf, - )[0] - / nc - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_edge_moments(self, pars): - """ - Mutation mapped to two branches with children fixed to time zero, and - both parents fixed - """ - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - t_j = a_j / b_j - mn, va = mutation_edge_moments(t_i, t_j) - ck_mn = scipy.integrate.quad( - lambda x: x * self.pdf_edge(x, t_i, t_j), - 0, - max(t_i, t_j), - )[0] - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.quad( - lambda x: x**2 * self.pdf_edge(x, t_i, t_j), - 0, - max(t_i, t_j), - )[0] - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_block_moments(self, pars): - """ - Mutation mapped to two branches with children fixed to time zero, and - both parents fixed - """ - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - t_j = a_j / b_j - pars_redux = (a_j, b_j, y, mu) - pr, mn, va = mutation_block_moments(t_i, t_j) - ck_pr = t_i / (t_i + t_j) - assert np.isclose(pr, ck_pr) - ck_mn = scipy.integrate.quad( - lambda x: x * self.pdf_block(x, t_i, t_j), - 0, - max(t_i, t_j), - )[0] - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.quad( - lambda x: x**2 * self.pdf_block(x, t_i, t_j), - 0, - max(t_i, t_j), - )[0] - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - -def validate(): - tests = TestExactMoments() - test_names = [f for f in dir(tests) if f.startswith("test")] - test_cases = [ # [shape1, rate1, shape2, rate2, muts, rate] - [2.0, 0.0005, 1.5, 0.005, 0.0, 0.001], - [2.0, 0.0005, 1.5, 0.005, 1.0, 0.001], - [2.0, 0.0005, 1.5, 0.005, 2.0, 0.001], - [2.0, 0.0005, 1.5, 0.005, 3.0, 0.001], - ] - for pars in test_cases: - for test in test_names: - getattr(tests, test)(pars) diff --git a/tests/oracle/__init__.py b/tests/oracle/__init__.py index b6b18706..17acb5ff 100644 --- a/tests/oracle/__init__.py +++ b/tests/oracle/__init__.py @@ -1,31 +1,23 @@ """ -Plain-Python reference implementations ("oracles") of the functions of the C -extension ``_tsdate``. +Plain-Python reference implementations ("oracles") of the tree-sweep functions of the +C extension ``_tsdate``. Each function has an oracle in the module of the same name here, e.g. -``oracle.approx.moments`` for ``_tsdate.moments``. Equivalence tests -(``tests/test_oracle_*.py``) call the ``_tsdate`` functions and the oracles with the -same arguments and compare the outcomes. +``oracle.phasing.block_singletons`` for ``_tsdate.block_singletons``. Equivalence +tests (``tests/test_oracle_*.py``) call the ``_tsdate`` functions and the oracles with +the same arguments and compare the outcomes. Rules: * An oracle is written as array code in plain Python with the operation order of the - C library. Where plain Python semantics differ from C (e.g. division by zero - raising instead of giving inf/nan, numpy scalar semantics), a comment explains the - compensation, once in the module header where it applies throughout. -* Oracles call other oracles, never ``_tsdate``, except for ``gammaincinv`` - (``hypergeo.gammainc_inv``), which they take from the C library as they take libm, - and which is compared with SciPy instead, and the messages of the library's error - codes (``errors``, as ``_tsdate.strerror`` gives them). + C library. +* Oracles call other oracles, never ``_tsdate``, except for the messages of the + library's error codes (``errors``, as ``_tsdate.strerror`` gives them). * Oracles raise errors in the library's terms: where the C library returns an error code, the oracle raises ``errors.library_error(code)``, the ``_tsdate.LibraryError`` with that code's message; for the shapes and sizes of arrays that ``_tsdate`` checks, the oracle raises ``ValueError`` with its message. The equivalence tests - compare the type and message of the exceptions. A ``ZeroDivisionError`` (from a - Python float division) stands for the library's ``TSD_ERR_ZERO_DIVISION``. Internal - invariants, which the library does not report, are plain ``assert`` statements. -* Names, arguments and results are those of ``_tsdate``'s functions: the same - argument lists, and results of the same types and layout (floats where ``_tsdate`` - returns floats, the same tuples). The EP state is the tuple of factor arrays that - ``_tsdate`` takes. + compare the type and message of the exceptions. Internal invariants, which the + library does not report, are plain ``assert`` statements. +* Names, arguments and results are those of ``_tsdate``'s functions. """ diff --git a/tests/oracle/_libm.py b/tests/oracle/_libm.py deleted file mode 100644 index afb7e8d6..00000000 --- a/tests/oracle/_libm.py +++ /dev/null @@ -1,131 +0,0 @@ -""" -C-semantics versions of the `math` functions used by the oracles. - -C calls libm directly, so e.g. ``log(0.0) == -inf``, ``exp(1e4) == inf`` -and ``sqrt(-1.0)`` is NaN. Python's `math` module raises ``ValueError`` or -``OverflowError`` in these cases. These wrappers return the C results instead and -otherwise defer to `math`, so values agree with the C library's libm calls. `lgamma` goes -to libm itself (see `_load_libm_lgamma`). -""" - -import ctypes -import ctypes.util -import math -import sys - -import numpy as np - -_inf = math.inf -_nan = math.nan - - -def log(x): - try: - return math.log(x) - except ValueError: - return -_inf if x == 0.0 else _nan - - -def exp(x): - try: - return math.exp(x) - except OverflowError: - return _inf - - -def sqrt(x): - try: - return math.sqrt(x) - except ValueError: - return _nan - - -def sin(x): - try: - return math.sin(x) - except ValueError: # sin(+-inf) - return _nan - - -def tan(x): - try: - return math.tan(x) - except ValueError: # tan(+-inf) - return _nan - - -def _load_libm_lgamma(): - """ - The platform C runtime's ``lgamma``, as used by the C library: libm on Linux and - macOS, the Universal CRT (``ucrtbase``) on Windows. - CPython's `math.lgamma` is its own Lanczos implementation, which differs from - the C runtime by up to thousands of ulp where lgamma is near zero (x near 1 or - 2), so there is deliberately no fallback to it: if the C runtime can't be - loaded, the import fails rather than the oracle silently drifting. - """ - name = ctypes.util.find_library("m") - if name is None and sys.platform == "win32": - name = "ucrtbase" - if name is None: - raise ImportError("could not locate the C runtime library providing lgamma") - func = ctypes.CDLL(name).lgamma - func.restype = ctypes.c_double - func.argtypes = [ctypes.c_double] - assert math.isclose(func(5.0), math.log(24.0), rel_tol=1e-12) - return func - - -_libm_lgamma = _load_libm_lgamma() - - -def lgamma(x): - return _libm_lgamma(x) - - -def erf(x): - return math.erf(x) - - -def pow(x, y): # noqa: A001 - try: - return math.pow(x, y) - except OverflowError: - return _inf - except ValueError: - # 0 ** negative is a pole; negative ** non-integer is NaN - return _inf if x == 0.0 else _nan - - -def ipow(x, n): - """ - ``x ** n`` for a small positive integer constant ``n``, by repeated squaring. - - The C library computes ``x ** n`` this way (``tsd_ipow``), so ``x ** 2 == x * x``. - CPython calls libm ``pow`` instead, which differs from this by an ulp in a small - fraction of cases. The difference matters where results cancel - (e.g. ``va = sq - mn ** 2``). - """ - result = 1.0 - while True: - if n & 1: - result *= x - n >>= 1 - if n == 0: - return result - x *= x - - -def seq_sum(x): - """ - Sum of a 1d array, accumulating strictly left to right, as a C loop - does. ``np.sum`` uses pairwise summation, which differs in the last bits. - """ - x = np.asarray(x) - return x.dtype.type(0) if x.size == 0 else np.cumsum(x)[-1] - - -def seq_mean(x): - """ - Mean of a 1d array using `seq_sum`, as the C library computes means. - """ - return seq_sum(x) / np.size(x) diff --git a/tests/oracle/approx.py b/tests/oracle/approx.py deleted file mode 100644 index a1c0bacc..00000000 --- a/tests/oracle/approx.py +++ /dev/null @@ -1,946 +0,0 @@ -""" -Oracles for the gamma approximations (``lib/approx.c``). -""" - -from math import inf, nan - -import numpy as np - -from . import errors, hypergeo - -# Plain `math` raises on log(0), exp overflow etc., where C gives -inf, inf or -# nan; `_libm` gives the C results. -# C computes `x ** n` for integer constants `n` by repeated squaring, whereas -# CPython calls libm pow, which differs by an ulp in a few percent of cases; `ipow` -# squares (see `_libm.ipow`). -# `np.log` of a Python float returns an `np.float64`, so that a following -# division by zero gives inf (with a warning) instead of the ZeroDivisionError that -# stands for the library's TSD_ERR_ZERO_DIVISION; and NumPy's SIMD log may differ -# from libm by an ulp. Logs are the `_libm.log` of a Python float. -# For the same reason, elements unpacked from a NumPy array are converted with -# `float`. -from ._libm import exp, ipow, lgamma, log -from .errors import library_error - -# the tolerances of the KL minimisation, as in the library -_KLMIN_MAXITT = 100 -_KLMIN_RELTOL = np.sqrt(np.finfo(np.float64).eps) - - -def approximate_log_moments(mean, variance): - """ - Approximate log moments via a second-order Taylor series expansion around - the mean, e.g.: - - E[f(x)] \\approx E[f(mean)] + variance * f''(mean)/2 - - Returns approximations to E[log x], E[x log x], E[(log x)^2] - """ - if not (mean > 0 and variance > 0): - raise library_error(errors.NONPOSITIVE_MOMENTS) - logx = log(mean) - 0.5 * variance / ipow(mean, 2) - xlogx = mean * log(mean) + 0.5 * variance / mean - logx2 = ipow(log(mean), 2) + (1 - log(mean)) * variance / ipow(mean, 2) - return logx, xlogx, logx2 - - -def approximate_gamma_kl(x, logx): - """ - Use Newton root finding to get gamma natural parameters matching the sufficient - statistics :math:`E[x]` and :math:`E[\\log x]`, minimizing KL divergence. - - The initial condition uses the upper bound :math:`digamma(x) \\leq log(x) - 1/2x`. - - Returns the shape and rate of the approximating gamma. - """ - if x <= 0.0 or np.isinf(logx): - raise library_error(errors.NONPOSITIVE_OR_NONFINITE_MOMENTS) - if not log(x) > logx: - raise library_error(errors.JENSEN_VIOLATION) - alpha = 0.5 / (log(x) - logx) # lower bound on alpha - # asymptotically the lower bound becomes sharp - if 1.0 / alpha < 1e-4: - return alpha - 1.0, alpha / x - itt = 0 - delta = np.inf - # determine convergence when the change in alpha falls below - # some small value (e.g. square root of machine precision) - while np.abs(delta) > np.abs(alpha) * _KLMIN_RELTOL: - if itt > _KLMIN_MAXITT: - raise library_error(errors.KL_MAX_ITERATIONS) - delta = hypergeo.digamma(alpha) - log(alpha) + log(x) - logx - delta /= hypergeo.trigamma(alpha) - 1 / alpha - alpha -= delta - itt += 1 - if not np.isfinite(alpha) or alpha <= 0: - raise library_error(errors.KL_INVALID_SHAPE) - return alpha - 1.0, alpha / x - - -def approximate_gamma_mom(mean, variance): - """ - Use the method of moments to approximate a distribution with a gamma of the - same mean and variance, returning natural parameters - """ - if not (mean > 0.0 and variance > 0.0): - raise library_error(errors.NONPOSITIVE_CENTRAL_MOMENTS) - shape = ipow(mean, 2) / variance - rate = mean / variance - return shape - 1.0, rate - - -def approximate_gamma_iqr(q1, q2, x1, x2, max_shape): - """ - Find gamma natural parameters that match empirical quantiles - """ - - def upper_bound(q, x): # cap shape parameter - beta = hypergeo.gammainc_inv(max_shape, q) / x - return max_shape - 1, beta - - if x2 == x1: - return upper_bound(q1, x1) - if not (q2 > q1 and x2 > x1): - raise library_error(errors.UNSORTED_QUANTILES) - alpha = log(q2 / q1) / log(x2 / x1) # lower bound - if alpha > max_shape: - return upper_bound(q1, x1) - - # refine with newton iteration - delta = inf - itt = 0 - while abs(delta) > abs(alpha) * _KLMIN_RELTOL: - if itt > _KLMIN_MAXITT: - raise library_error(errors.QUANTILE_MAX_ITERATIONS) - y1 = hypergeo.gammainc_inv(alpha, q1) - y2 = hypergeo.gammainc_inv(alpha, q2) - obj = y2 / y1 - x2 / x1 - inv_1 = -exp(y1 + log(y1) * (1 - alpha) + lgamma(alpha)) - inv_2 = -exp(y2 + log(y2) * (1 - alpha) + lgamma(alpha)) - # print(itt, alpha, y1, y2) #DEBUG - gra_1 = hypergeo.gammainc_der(alpha, y1) * inv_1 - gra_2 = hypergeo.gammainc_der(alpha, y2) * inv_2 - gra = (gra_2 * y1 - gra_1 * y2) / ipow(y1, 2) - delta = -obj / gra - alpha += delta - itt += 1 - - if not alpha > 0: - raise library_error(errors.NEGATIVE_SHAPE) - if alpha > max_shape: - return upper_bound(q1, x1) - beta = hypergeo.gammainc_inv(alpha, q1) / x1 - return alpha - 1, beta - - -def average_gammas(alpha, beta): - """ - Given natural parameters for a set of gammas, average sufficient - statistics so as to get a "global" gamma, returning natural - parameters - """ - if alpha.size != beta.size: - raise ValueError("Array sizes are not equal") - avg_x = 0.0 - avg_logx = 0.0 - for shape, rate in zip(map(float, alpha + 1.0), map(float, beta)): - avg_logx += hypergeo.digamma(shape) - log(rate) - avg_x += shape / rate - avg_x /= alpha.size - avg_logx /= alpha.size - return approximate_gamma_kl(avg_x, avg_logx) - - -def valid_moments(mn, va): - """ - 1.0 if a mean and variance are finite and positive, else 0.0. - """ - if not (np.isfinite(mn) and np.isfinite(va)): - return 0.0 - if not (mn > 0.0 and va > 0.0): - return 0.0 - return 1.0 - - -def valid_gamma(s, r): - """ - 1.0 if a gamma shape and rate are finite and positive, else 0.0. - """ - if not (np.isfinite(s) and np.isfinite(r)): - return 0.0 - if s <= 0.0 or r <= 0.0: - return 0.0 - return 1.0 - - -def valid_hyp1f1(a, b, z): - """ - 1.0 if the arguments are in the domain of `hyp1f1_laplace`, else 0.0. - """ - if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(z)): - return 0.0 - if not (b >= a > 0.0): - return 0.0 - return 1.0 - - -def valid_hyperu(a, b, z): - """ - 1.0 if the arguments are in the domain of `hyperu_laplace`, else 0.0. - """ - if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(z)): - return 0.0 - if z <= 0.0: - return 0.0 - if not (b > a > 0.0): - return 0.0 - return 1.0 - - -def valid_hyp2f1(a, b, c, z): - """ - 1.0 if the arguments are in the domain of `hyp2f1_laplace`, else 0.0. - """ - if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(c)): - return 0.0 - if not np.isfinite(z) or z >= 1 or z / (z - 1) >= 1: - return 0.0 - if not (a > 0 and b > 0 and c > 0): - return 0.0 - return 1.0 - - -def moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_i, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, E[t_i], V[t_i], E[t_j], V[t_j]. - """ - - a = a_j - b = a_i + a_j + y_ij - c = a_j + y_ij + 1 - t = mu_ij + b_i - z = (mu_ij - b_j) / t if t > 0 else nan - - if not valid_hyp2f1(a, b, c, z): - return nan, nan, nan, nan, nan - - hyp2f1 = hypergeo.hyp2f1_laplace - f0 = hyp2f1(a + 0, b + 0, c + 0, z) - f1 = hyp2f1(a + 1, b + 1, c + 1, z) - f2 = hyp2f1(a + 2, b + 2, c + 2, z) - s1 = a * b / c - s2 = s1 * (a + 1) * (b + 1) / (c + 1) - d1 = s1 * exp(f1 - f0) - d2 = s2 * exp(f2 - f0) - - logl = f0 + hypergeo.betaln(y_ij + 1, a) + lgamma(b) - b * log(t) - - mn_j = d1 / t - sq_j = d2 / ipow(t, 2) - va_j = sq_j - ipow(mn_j, 2) - - mn_i = mn_j * z + b / t - sq_i = sq_j * ipow(z, 2) + (b + 1) * (mn_i + mn_j * z) / t - va_i = sq_i - ipow(mn_i, 2) - - return logl, mn_i, va_i, mn_j, va_j - - -def rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): - r""" - log p(t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i - - Returns normalizing constant, E[t_i], V[t_i]. - """ - - if not (t_j >= 0.0): - raise library_error(errors.INVALID_FIXED_AGE) - - s = a_i + y_ij - r = mu_ij + b_i - - if not valid_gamma(s, r): - return nan, nan, nan - - if t_j == 0.0: - logl = lgamma(s) - s * log(r) - mn_i = s / r - va_i = s / ipow(r, 2) - return logl, mn_i, va_i - - a = y_ij + 1 - b = s + 1 - z = t_j * r - - if not valid_hyperu(a, b, z): - return nan, nan, nan - - hyperu = hypergeo.hyperu_laplace - f0, d0 = hyperu(a + 0, b + 0, z) - f1, d1 = hyperu(a + 1, b + 1, z) - - logl = f0 - b_i * t_j + (b - 1) * log(t_j) + lgamma(a) - mn_i = t_j * (1 - d0) - va_i = ipow(t_j, 2) * d0 * (d1 - d0) - - return logl, mn_i, va_i - - -def leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, E[t_j], V[t_j]. - """ - - if not (t_i > 0.0): - raise library_error(errors.INVALID_FIXED_AGE) - - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij - b_j) - - if not valid_hyp1f1(a, b, z): - return nan, nan, nan - - hyp1f1 = hypergeo.hyp1f1_laplace - f0 = hyp1f1(a + 0, b + 0, z) - f1 = hyp1f1(a + 1, b + 1, z) - f2 = hyp1f1(a + 2, b + 2, z) - d1 = a / b * exp(f1 - f0) - d2 = a / b * (a + 1) / (b + 1) * exp(f2 - f0) - - logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + hypergeo.betaln(a, b - a) - mn_j = t_i * d1 - sq_j = ipow(t_i, 2) * d2 - va_j = sq_j - ipow(mn_j, 2) - - return logl, mn_j, va_j - - -def unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, E[t_i], V[t_i], E[t_j], V[t_j]. - """ - - a = a_j - b = a_i + a_j + y_ij - c = a_j + a_i - t = mu_ij + b_i - z = (mu_ij + b_j) / t if t > 0 else nan - - if not valid_hyp2f1(a, b, c, 1 - z): - return nan, nan, nan, nan, nan - - hyp2f1 = hypergeo.hyp2f1_laplace - f0 = hyp2f1(a + 0, b + 0, c + 0, 1 - z) - f1 = hyp2f1(a + 1, b + 1, c + 1, 1 - z) - f2 = hyp2f1(a + 2, b + 2, c + 2, 1 - z) - s1 = a * b / c - s2 = s1 * (a + 1) * (b + 1) / (c + 1) - d1 = s1 * exp(f1 - f0) - d2 = s2 * exp(f2 - f0) - - logl = f0 + hypergeo.betaln(a_j, a_i) + lgamma(b) - b * log(t) - - mn_j = d1 / t - sq_j = d2 / ipow(t, 2) - va_j = sq_j - ipow(mn_j, 2) - - mn_i = b / t - mn_j * z - sq_i = sq_j * ipow(z, 2) + (b + 1) * (mn_i - mn_j * z) / t - va_i = sq_i - ipow(mn_i, 2) - - return logl, mn_i, va_i, mn_j, va_j - - -def twin_moments(a_i, b_i, y_ij, mu_ij): - r""" - log p(t_i) := \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i - - Returns normalizing constant, E[t_i], V[t_i]. - """ - s = a_i + y_ij - r = b_i + 2 * mu_ij - logl = log(2) * y_ij + lgamma(s) - log(r) * s - mn_i = s / r - va_i = s / ipow(r, 2) - return logl, mn_i, va_i - - -def sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, E[t_j], V[t_j]. - """ - - if not (t_i > 0.0): - raise library_error(errors.INVALID_FIXED_AGE) - - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij + b_j) - - if not valid_hyperu(a, b, z): - return nan, nan, nan - - hyperu = hypergeo.hyperu_laplace - f0, d0 = hyperu(a + 0, b + 0, z) - f1, d1 = hyperu(a + 1, b + 1, z) - - logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + lgamma(a) - mn_j = -t_i * d0 - va_j = ipow(t_i, 2) * d0 * (d1 - d0) - - return logl, mn_j, va_j - - -def mutation_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_m, t_i, t_j) = \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns E[t_m], V[t_m]. - """ - - a = a_j - b = a_i + a_j + y_ij - c = a_j + y_ij + 1 - t = mu_ij + b_i - z = (mu_ij - b_j) / t if t > 0 else nan - - if not valid_hyp2f1(a, b, c, z): - return nan, nan - - hyp2f1 = hypergeo.hyp2f1_laplace - f000 = hyp2f1(a + 0, b + 0, c + 0, z) - f020 = hyp2f1(a + 0, b + 2, c + 0, z) - f111 = hyp2f1(a + 1, b + 1, c + 1, z) - f121 = hyp2f1(a + 1, b + 2, c + 1, z) - f222 = hyp2f1(a + 2, b + 2, c + 2, z) - - s1 = a * b / c - d1 = b * (b + 1) / ipow(t, 2) - d2 = d1 * a / c - d3 = d2 * (a + 1) / (c + 1) - - mn_m = s1 * exp(f111 - f000) / t / 2 * (1 + z) + b / t / 2 - sq_m = ( - d1 * exp(f020 - f000) / 3 + d2 * exp(f121 - f000) / 3 + d3 * exp(f222 - f000) / 3 - ) - va_m = sq_m - ipow(mn_m, 2) - - return mn_m, va_m - - -def mutation_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): - r""" - log p(t_m, t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns E[t_m], V[t_m]. - """ - - logl, mn_i, va_i = rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) - mn_m = mn_i / 2 + t_j / 2 - sq_m = (va_i + ipow(mn_i, 2) + mn_i * t_j + ipow(t_j, 2)) / 3 - va_m = sq_m - ipow(mn_m, 2) - - return mn_m, va_m - - -def mutation_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_m, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns E[t_m], V[t_m]. - """ - - logl, mn_j, va_j = leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) - mn_m = mn_j / 2 + t_i / 2 - sq_m = (va_j + ipow(mn_j, 2) + mn_j * t_i + ipow(t_i, 2)) / 3 - va_m = sq_m - ipow(mn_m, 2) - - return mn_m, va_m - - -def mutation_unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_m, t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - - Returns P[m under i], E[t_m], V[t_m]. - """ - - # Conditioning on ages of parents: - # P[x under i | t_i, t_j] = t_i / (t_i + t_j) - # E[x | x under t_i, t_i] = t_i / 2 - # E[x^2 | x under t_i, t_i] = t_i**2 / 3 - # and equivalently for t_j. Integrating these moments over the EP surrogate - # density leads to hypergeometric functions similar to the node case, but - # with integer perturbations of a_i, a_j, y_ij. - - a = a_j - b = a_j + a_i + y_ij - c = a_j + a_i - t = mu_ij + b_i - z = (mu_ij + b_j) / t if t > 0 else nan - - if not valid_hyp2f1(a, b, c, 1 - z): - return nan, nan, nan - - hyp2f1 = hypergeo.hyp2f1_laplace - f000 = hyp2f1(a + 0, b + 0, c + 0, 1 - z) - f001 = hyp2f1(a + 0, b + 0, c + 1, 1 - z) - f012 = hyp2f1(a + 0, b + 1, c + 2, 1 - z) - f023 = hyp2f1(a + 0, b + 2, c + 3, 1 - z) - f212 = hyp2f1(a + 2, b + 1, c + 2, 1 - z) - f323 = hyp2f1(a + 3, b + 2, c + 3, 1 - z) - - s0 = b / t / c / (c + 1) - s1 = (c - a) * (c - a + 1) - s2 = a * (a + 1) - d0 = s0 * (b + 1) / t / (c + 2) - d1 = s1 * (c - a + 2) - d2 = s2 * (a + 2) - - mn_m = s0 * s1 * exp(f012 - f000) / 2 + s0 * s2 * exp(f212 - f000) / 2 - sq_m = d0 * d1 * exp(f023 - f000) / 3 + d0 * d2 * exp(f323 - f000) / 3 - va_m = sq_m - ipow(mn_m, 2) - pr_m = (c - a) / c * exp(f001 - f000) - - return pr_m, mn_m, va_m - - -def mutation_twin_moments(a_i, b_i, y_ij, mu_ij): - r""" - log p(t_m, t_i) := \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(int(0 < t_m < t_i) / t_i) - """ - - s = a_i + y_ij - r = b_i + 2 * mu_ij - pr_m = 0.5 - mn_m = s / r / 2 - sq_m = (s + 1) * s / 3 / ipow(r, 2) - va_m = sq_m - ipow(mn_m, 2) - - return pr_m, mn_m, va_m - - -def mutation_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_m, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - - Returns P[m under i], E[t_m], V[t_m]. - """ - - if not (t_i > 0): - raise library_error(errors.INVALID_FIXED_AGE) - - # Conditioning on ages of parents: - # P[x under i | t_i, t_j] = t_i / (t_i + t_j) - # E[x | x under t_i, t_i] = t_i / 2 - # E[x^2 | x under t_i, t_i] = t_i**2 / 3 - # and equivalently for t_j. Integrating these moments over the EP surrogate - # density leads to Tricomi functions similar to the node case, but - # with integer perturbations of a_j, y_ij. - - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij + b_j) - - if not valid_hyperu(a, b, z): - return nan, nan, nan - - # direct but unstable: - hyperu = hypergeo.hyperu_laplace - f00, d00 = hyperu(a + 0, b + 0, z) - f10, d10 = hyperu(a + 1, b + 0, z) - f21, d21 = hyperu(a + 2, b + 1, z) - f32, d32 = hyperu(a + 3, b + 2, z) - pr_m = 1.0 - exp(f10 - f00) * a - mn_m = pr_m * t_i / 2 + t_i * exp(f21 - f00) * a * (a + 1) / 2 - sq_m = ( - pr_m * ipow(t_i, 2) / 3 - + ipow(t_i, 2) * exp(f32 - f00) * a * (a + 1) * (a + 2) / 3 - ) - - # TODO: use a stabler approach with derivatives - # note that exp(f10 - f00) = (a + z * d00) / (a - b + 1) - # however the denominator is 0 if y_ij is 0 - # note that when y_ij == 0 then a == b + 1 and f00 = z**(-a) - - va_m = sq_m - ipow(mn_m, 2) - - return pr_m, mn_m, va_m - - -def mutation_edge_moments(t_i, t_j): - r""" - log p(t_m) := \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns E[t_m], V[t_m]. - """ - - mn_m = 1 / 2 * (t_i + t_j) - va_m = 1 / 12 * ipow(t_i - t_j, 2) - - return mn_m, va_m - - -def mutation_block_moments(t_i, t_j): - r""" - log p(t_m) := \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - - Returns P[m under i], E[t_m], V[t_m]. - """ - - if not (t_i > 0 and t_j > 0): - raise library_error(errors.INVALID_FIXED_AGE) - - pr_m = t_i / (t_i + t_j) - mn_m = pr_m * t_i / 2 + (1 - pr_m) * t_j / 2 - sq_m = pr_m * ipow(t_i, 2) / 3 + (1 - pr_m) * ipow(t_j, 2) / 3 - va_m = sq_m - ipow(mn_m, 2) - - return pr_m, mn_m, va_m - - -# The projections take the natural parameters (alpha, beta) = (shape - 1, rate) of the -# gamma of each free node, and the mutation count and mutational target size -# (y_ij, mu_ij) of the edge, as flat arguments; they return the first result followed -# by the natural parameters of each projected gamma. - - -def gamma_projection(alpha_i, beta_i, alpha_j, beta_j, y_ij, mu_ij): - r""" - log p(t_i, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, gamma natural parameters for parent and child ages - """ - a_i = alpha_i + 1 - a_j = alpha_j + 1 - - logl, mn_i, va_i, mn_j, va_j = moments(a_i, beta_i, a_j, beta_j, y_ij, mu_ij) - - if not (valid_moments(mn_i, va_i) and valid_moments(mn_j, va_j)): - return nan, alpha_i, beta_i, alpha_j, beta_j - - proj_i = approximate_gamma_mom(mn_i, va_i) - proj_j = approximate_gamma_mom(mn_j, va_j) - - return logl, *proj_i, *proj_j - - -def leafward_projection(t_i, alpha_j, beta_j, y_ij, mu_ij): - r""" - log p(t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, gamma natural parameters for child age - """ - a_j = alpha_j + 1 - - logl, mn_j, va_j = leafward_moments(t_i, a_j, beta_j, y_ij, mu_ij) - - if not valid_moments(mn_j, va_j): - return nan, alpha_j, beta_j - - proj_j = approximate_gamma_mom(mn_j, va_j) - - return logl, *proj_j - - -def rootward_projection(t_j, alpha_i, beta_i, y_ij, mu_ij): - r""" - log p(t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i - - Returns normalizing constant, gamma natural parameters for parent age - """ - a_i = alpha_i + 1 - - logl, mn_i, va_i = rootward_moments(t_j, a_i, beta_i, y_ij, mu_ij) - - if not valid_moments(mn_i, va_i): - return nan, alpha_i, beta_i - - proj_i = approximate_gamma_mom(mn_i, va_i) - - return logl, *proj_i - - -def unphased_projection(alpha_i, beta_i, alpha_j, beta_j, y_ij, mu_ij): - r""" - log p(t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, gamma natural parameters for parent ages - """ - a_i = alpha_i + 1 - a_j = alpha_j + 1 - - logl, mn_i, va_i, mn_j, va_j = unphased_moments(a_i, beta_i, a_j, beta_j, y_ij, mu_ij) - - if not valid_moments(mn_i, va_i) or not valid_moments(mn_j, va_j): - return nan, alpha_i, beta_i, alpha_j, beta_j - - proj_i = approximate_gamma_mom(mn_i, va_i) - proj_j = approximate_gamma_mom(mn_j, va_j) - - return logl, *proj_i, *proj_j - - -def twin_projection(alpha_i, beta_i, y_ij, mu_ij): - r""" - log p(t_i) := \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i - - Returns normalizing constant, gamma natural parameters for parent ages - """ - a_i = alpha_i + 1 - - logl, mn_i, va_i = twin_moments(a_i, beta_i, y_ij, mu_ij) - - if not valid_moments(mn_i, va_i): - return nan, alpha_i, beta_i - - proj_i = approximate_gamma_mom(mn_i, va_i) - - return logl, *proj_i - - -def sideways_projection(t_i, alpha_j, beta_j, y_ij, mu_ij): - r""" - log p(t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, gamma natural parameters for nonfixed parent age - """ - a_j = alpha_j + 1 - - logl, mn_j, va_j = sideways_moments(t_i, a_j, beta_j, y_ij, mu_ij) - - if not valid_moments(mn_j, va_j): - return nan, alpha_j, beta_j - - proj_j = approximate_gamma_mom(mn_j, va_j) - - return logl, *proj_j - - -def mutation_gamma_projection(alpha_i, beta_i, alpha_j, beta_j, y_ij, mu_ij): - r""" - log p(t_m, t_i, t_j) = \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_i = alpha_i + 1 - a_j = alpha_j + 1 - - mn_m, va_m = mutation_moments(a_i, beta_i, a_j, beta_j, y_ij, mu_ij) - - if not valid_moments(mn_m, va_m): - return nan, nan, nan - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return 1.0, *proj_m - - -def mutation_leafward_projection(t_i, alpha_j, beta_j, y_ij, mu_ij): - r""" - log p(t_m, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_j = alpha_j + 1 - - mn_m, va_m = mutation_leafward_moments(t_i, a_j, beta_j, y_ij, mu_ij) - - if not valid_moments(mn_m, va_m): - return nan, nan, nan - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return 1.0, *proj_m - - -def mutation_rootward_projection(t_j, alpha_i, beta_i, y_ij, mu_ij): - r""" - log p(t_m, t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_i = alpha_i + 1 - - mn_m, va_m = mutation_rootward_moments(t_j, a_i, beta_i, y_ij, mu_ij) - - if not valid_moments(mn_m, va_m): - return nan, nan, nan - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return 1.0, *proj_m - - -def mutation_edge_projection(t_i, t_j): - r""" - log p(t_m) := \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns phase probability, gamma natural parameters for mutation age - """ - mn_m, va_m = mutation_edge_moments(t_i, t_j) - - if not valid_moments(mn_m, va_m): - return nan, nan, nan - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return 1.0, *proj_m - - -def mutation_unphased_projection(alpha_i, beta_i, alpha_j, beta_j, y_ij, mu_ij): - r""" - log p(t_m, t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_i = alpha_i + 1 - a_j = alpha_j + 1 - - pr_m, mn_m, va_m = mutation_unphased_moments(a_i, beta_i, a_j, beta_j, y_ij, mu_ij) - - if not valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return nan, nan, nan - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return pr_m, *proj_m - - -def mutation_twin_projection(alpha_i, beta_i, y_ij, mu_ij): - r""" - log p(t_m, t_i) := \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(int(0 < t_m < t_i) / t_i) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_i = alpha_i + 1 - - pr_m, mn_m, va_m = mutation_twin_moments(a_i, beta_i, y_ij, mu_ij) - - if not valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return nan, nan, nan - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return pr_m, *proj_m - - -def mutation_sideways_projection(t_i, alpha_j, beta_j, y_ij, mu_ij): - r""" - log p(t_m, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_j = alpha_j + 1 - - pr_m, mn_m, va_m = mutation_sideways_moments(t_i, a_j, beta_j, y_ij, mu_ij) - - if not valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return nan, nan, nan - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return pr_m, *proj_m - - -def mutation_block_projection(t_i, t_j): - r""" - log p(t_m) := \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j)) - - Returns phase probability, gamma natural parameters for mutation age - """ - pr_m, mn_m, va_m = mutation_block_moments(t_i, t_j) - - if not valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return nan, nan, nan - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return pr_m, *proj_m diff --git a/tests/oracle/ep_state.py b/tests/oracle/ep_state.py deleted file mode 100644 index f68a6a61..00000000 --- a/tests/oracle/ep_state.py +++ /dev/null @@ -1,184 +0,0 @@ -""" -Expectation propagation inputs for the equivalence tests of ``tsdate.variational``: -the inputs of ``ExpectationPropagation`` on the session fixtures (editable, so that -tests can force branches), and the loop of ``iterate``, run with the -``ExpectationPropagation`` of a given module (``_tsdate``, or the oracle -``oracle.variational``). -""" - -import numpy as np -import tskit - -from tsdate.variational import ( - LEAFWARD, - LOWER, - ROOTWARD, - UPPER, - USE_BLOCK_LIKELIHOOD, - USE_EDGE_LIKELIHOOD, - ExpectationPropagation, -) - -# fixture name -> (singletons_phased, mutation_rate) -SPECS = { - "small_ts": (True, 1e-8), - "small_ts_unphased": (False, 1e-7), - "small_ts_historical": (True, 1e-8), -} - -_COPIED = ( - "edge_order", - "edge_parents", - "edge_children", - "edge_likelihoods", - "block_order", - "block_likelihoods", - "block_nodes", - "node_constraints", - "unconstrained_roots", - "roots", - "leaves", - "mutation_edges", - "mutation_blocks", -) - - -class Inputs: - """ - Copies of the inputs of an ``ExpectationPropagation``, which tests can edit - """ - - def __init__(self, ts, ep): - self.ts = ts - for name in _COPIED: - setattr(self, name, getattr(ep, name).copy()) - - def copy(self): - new = object.__new__(Inputs) - for k, v in self.__dict__.items(): - setattr(new, k, v.copy() if isinstance(v, np.ndarray) else v) - return new - - def kwargs(self): - """ - The arguments of ``ExpectationPropagation`` - """ - return dict( - constraints=self.node_constraints, - edges_parent=self.edge_parents, - edges_child=self.edge_children, - edges_likelihood=self.edge_likelihoods, - blocks_left=self.block_nodes[ROOTWARD], - blocks_right=self.block_nodes[LEAFWARD], - blocks_likelihood=self.block_likelihoods, - ) - - def fix_nodes(self, nodes): - """ - Constrain ``nodes`` to their true (simulated) ages - """ - nodes = np.asarray(nodes) - times = self.ts.nodes_time[nodes] - self.node_constraints[nodes, LOWER] = times - self.node_constraints[nodes, UPPER] = times - - @property - def fixed(self): - return self.node_constraints[:, LOWER] == self.node_constraints[:, UPPER] - - def branch_counts(self, unphased): - """ - Number of edges (blocks) of each kind visited by the likelihood passes - """ - if unphased: - p, c = self.block_nodes[ROOTWARD], self.block_nodes[LEAFWARD] - else: - p, c = self.edge_parents, self.edge_children - fp, fc = self.fixed[p], self.fixed[c] - return { - "both_fixed": int(np.sum(fp & fc)), - "fixed_parent": int(np.sum(fp & ~fc)), - "fixed_child": int(np.sum(~fp & fc)), - "twin": int(np.sum(~fp & ~fc & (p == c))), - "both_free": int(np.sum(~fp & ~fc & (p != c))), - } - - def mutations_edge(self, unphased): - """ - The edges (blocks) of the phased (unphased) mutations - """ - phased = self.mutation_blocks == tskit.NULL - if unphased: - return self.mutation_blocks[~phased] - return self.mutation_edges[phased] - - -def make_inputs(ts, name): - """ - The inputs of EP on ``ts`` (fixture ``name``) - """ - singletons_phased, mutation_rate = SPECS[name] - ep = ExpectationPropagation( - ts, mutation_rate=mutation_rate, singletons_phased=singletons_phased - ) - return Inputs(ts, ep) - - -def fixed_internal(inputs, unphased, every=4): - """ - Copy of the inputs with every ``every``th internal node (every ``every``th block - node, for unphased blocks) fixed at its true age; the first block has both nodes - fixed. Gives all branches of the passes. - """ - inputs = inputs.copy() - if unphased: - nodes = np.unique(inputs.block_nodes) - fixed = list(nodes[::every]) - fixed += [inputs.block_nodes[ROOTWARD][0], inputs.block_nodes[LEAFWARD][0]] - else: - internal = np.flatnonzero(~inputs.fixed) - fixed = list(internal[::every]) - inputs.fix_nodes(np.unique(fixed)) - return inputs - - -def iterate(ep, inputs, max_shape=1000.0, min_step=0.1, em_maxitt=10, em_reltol=1e-8): - """ - The loop of ``tsdate.variational.ExpectationPropagation.iterate`` - """ - ep.propagate_likelihood( - order=inputs.block_order, - unphased=USE_BLOCK_LIKELIHOOD, - max_shape=max_shape, - min_step=min_step, - ) - ep.propagate_likelihood( - order=inputs.edge_order, - unphased=USE_EDGE_LIKELIHOOD, - max_shape=max_shape, - min_step=min_step, - ) - ep.propagate_prior( - free=inputs.unconstrained_roots, - max_shape=max_shape, - em_maxitt=em_maxitt, - em_reltol=em_reltol, - ) - ep.rescale_factors() - - -def start(module, inputs, iterations=2): - """ - The ``ExpectationPropagation`` of ``module`` on ``inputs`` after ``iterations`` - """ - ep = module.ExpectationPropagation(**inputs.kwargs()) - for _ in range(iterations): - iterate(ep, inputs) - return ep - - -def state(ep): - """ - Copies of the node posteriors and the log normalising constants - """ - return ep.posterior, ep.edges_lognorm, ep.blocks_lognorm diff --git a/tests/oracle/errors.py b/tests/oracle/errors.py index 1c96c0ed..0c6bc37a 100644 --- a/tests/oracle/errors.py +++ b/tests/oracle/errors.py @@ -27,7 +27,6 @@ MUTATION_NODE_NOT_IN_TREE = -20 FIXED_NODES_VIOLATE_CONSTRAINT = -21 NONPOSITIVE_INTERVALS = -22 -NEGATIVE_CHANGEPOINT_PARAMETER = -23 ZERO_EDGE_SPAN = -24 NON_INCREASING_BREAKPOINTS = -25 INVALID_QUANTILE_WIDTH = -26 @@ -49,7 +48,8 @@ TOO_FEW_TIPS = -42 NO_BREAKPOINTS = -43 -CODES = range(NO_BREAKPOINTS, 0) +# -23 is unused +CODES = [code for code in range(NO_BREAKPOINTS, 0) if code != -23] def library_error(code): diff --git a/tests/oracle/helpers.py b/tests/oracle/helpers.py index 235ff6e9..9c6d1f2a 100644 --- a/tests/oracle/helpers.py +++ b/tests/oracle/helpers.py @@ -44,14 +44,6 @@ def assert_same_values(actual, desired): NAN = float("nan") -def log_uniform(rng, lo, hi, size=None): - """ - ``10 ** U(lo, hi)``: a scalar float if ``size`` is None, else an array. - """ - x = 10.0 ** rng.uniform(lo, hi, size) - return float(x) if size is None else x - - class Outcome: """ What calling a function did: ``value`` (its return value) or ``exception``, and diff --git a/tests/oracle/hypergeo.py b/tests/oracle/hypergeo.py deleted file mode 100644 index bc37e6af..00000000 --- a/tests/oracle/hypergeo.py +++ /dev/null @@ -1,311 +0,0 @@ -""" -Oracles for the special functions (``lib/hypergeo.c``). -""" - -from math import pi - -import _tsdate -import numpy as np - -from . import errors - -# Plain `math` raises on log(0), exp overflow etc., where C gives -inf, inf or -# nan; `_libm` gives the C results. -# C computes `x ** n` for integer constants `n` by repeated squaring, whereas -# CPython calls libm pow, which differs by an ulp in a few percent of cases; `ipow` -# squares (see `_libm.ipow`). -# NumPy ufuncs on Python floats return `np.float64`, so a following division -# by zero (e.g. `pi / tan(0)`) gives inf with a warning instead of the -# ZeroDivisionError that stands for the library's TSD_ERR_ZERO_DIVISION; and NumPy's -# SIMD loops may differ from libm. Logs, tangents, sines and powers are the `_libm` -# versions (libm functions on Python floats). -from ._libm import erf, exp, ipow, lgamma, log, pow, sin, sqrt, tan # noqa: A004 -from .errors import library_error - -# gammaincinv is a primitive of the oracles, as the libm functions are: the C library's -# port of `scipy.special.gammaincinv`, which `TestGammaincInv` compares with SciPy. -gammainc_inv = _tsdate.gammainc_inv - - -def digamma(x): - """ - Digamma (psi) function, from asymptotic series expansion. - """ - if x <= 0.0: - return digamma(1 - x) - np.pi / tan(np.pi * x) - if x <= 1e-5: - return -np.euler_gamma - (1 / x) - if x < 8.5: - return digamma(1 + x) - 1 / x - xpm2 = 1 / ipow(x, 2) - return ( - log(x) - - 0.5 / x - - 0.083333333333333333 * xpm2 - + 0.008333333333333333 * ipow(xpm2, 2) - - 0.003968253968253968 * ipow(xpm2, 3) - + 0.004166666666666667 * ipow(xpm2, 4) - - 0.007575757575757576 * ipow(xpm2, 5) - + 0.021092796092796094 * ipow(xpm2, 6) - ) - - -def trigamma(x): - """ - Trigamma function, from asymptotic series expansion - """ - if x <= 0.0: - return -trigamma(1 - x) + ipow(np.pi, 2) / ipow(sin(np.pi * x), 2) - if x <= 1e-4: - return 1 / ipow(x, 2) - if x < 5: - return trigamma(1 + x) + 1 / ipow(x, 2) - xpm1 = 1 / x - xpm2 = 1 / ipow(x, 2) - return xpm1 * ( - 1.000000000000000000 - + 0.500000000000000000 * xpm1 - + 0.166666666666666667 * pow(xpm2, 1) - - 0.033333333333333333 * pow(xpm2, 2) - + 0.023809523809523808 * pow(xpm2, 3) - - 0.033333333333333333 * pow(xpm2, 4) - + 0.075757575757575756 * pow(xpm2, 5) - - 0.253113553113553102 * pow(xpm2, 6) - + 1.166666666666666741 * pow(xpm2, 7) - ) - - -def betaln(p, q): - """ - Log of the beta function. - """ - return lgamma(p) + lgamma(q) - lgamma(p + q) - - -def hyperu_laplace(a, b, x): - """ - Approximate Tricomi's confluent hypergeometric function with real - arguments, using Laplace's method with a calibration point. - - Also returns derivative wrt x. - - TODO: details - """ - - if not (b >= a > 0.0): - raise library_error(errors.INVALID_HYPERGEO) - if not (x > 0.0): - raise library_error(errors.INVALID_HYPERGEO) - - t = b - x - 1 - u = 2 * a / (sqrt(ipow(t, 2) + 4 * x * a) - t) - r = (b - a - 1) * ipow(u, 2) + a * ipow(1 + u, 2) - g = (b - a) * log(1 + u) + a * (1 + log(u)) - x * u - log(a) * (a - 1 / 2) - - w = (b - 1) * u + a - v = u * (1 + u) - dr = w / (w * u + a * (1 + u)) - dg = (w - x * v + u) / v - du = -u * v / (w - x * u + a) - - return g - log(r) / 2, (dg - dr) * du - u - - -def hyp1f1_laplace(a, b, x): - """ - Approximate Kummer's confluent hypergeometric function with real arguments, - using Laplace's method with a calibration point. - - TODO: details - """ - - if not (b > a > 0.0): - raise library_error(errors.INVALID_HYPERGEO) - - if x == 0.0: - return 0.0 - - t = x - b - u = 2 * a / (sqrt(ipow(t, 2) + 4 * x * a) - t) - r = ipow(u, 2) * b / a + ipow(1 - u, 2) * b / (b - a) - g = ( - (b - a) * log(1 - u) - + a * log(u) - + b * log(b) - - (b - a) * log(b - a) - - a * log(a) - + x * u - ) - - return g - log(r) / 2 - - -def hyp2f1_laplace(a, b, c, x): - r""" - Approximate a Gaussian hypergeometric function with real arguments, - using Laplace's method with a calibration point. - - TODO: details - """ - - def _hyp2f1_unity(a, b, c, x): - """ - Gauss hypergeometric function when `x` is near unity - - See limits in DLMF 15.4. - - TODO: this works in practice, but when (c - a - b) is close to zero the - limits don't converge. A good reference is Buhring 2003 "Partial sums of - hypergeometric series of unit argument" - """ - assert np.isclose(x, 1.0) - if not (x < 1.0): - raise library_error(errors.INVALID_HYPERGEO) - - g = c - a - b - - if g < 0.0: - return lgamma(c) + lgamma(-g) - lgamma(a) - lgamma(b) + g * log(1 - x) - elif g > 0.0: - # will only occur when a_i + a_j < 1 - return lgamma(c) + lgamma(g) - lgamma(c - a) - lgamma(c - b) - else: - # will only occur when a_i + a_j == 1 - return log(-log(1 - x)) + lgamma(a + b) - lgamma(a) - lgamma(b) - - # TODO: simplify, we can safely assume a,b > 0? - if not (c > 0.0 and a >= 0.0 and b >= 0.0 and c >= a and x < 1.0): - raise library_error(errors.INVALID_HYPERGEO) - - if x == 0.0: - return 0.0 - - s = 0.0 - if x < 0.0: - s = -b * log(1 - x) - a = c - a - x = x / (x - 1) - - if np.isclose(x, 1.0): - return s + _hyp2f1_unity(a, b, c, x) - - t = x * (b - a) - c - u = sqrt(ipow(t, 2) - 4 * a * x * (c - b)) - t - y = 2 * a / u - - if not (0 < y < 1): # root on boundary - raise library_error(errors.INVALID_HYPERGEO) - - yy = ipow(y, 2) / a - my = ipow(1 - y, 2) / (c - a) - ymy = ipow(x, 2) * b * yy * my / ipow(1 - x * y, 2) - r = yy + my - ymy - f = ( - (c - 1 / 2) * log(c) - + a * (log(y) - log(a)) - + (c - a) * (log(1 - y) - log(c - a)) - - b * log(1 - x * y) - ) - - return f - log(r) / 2 + s - - -def gammainc_der(p, x): - """ - Derivative of lower incomplete gamma function with regards to `p`. - - Based on Shea B (1988) "Algorithm AS 239" Applied Statistics 37: 466-473 - - Adapted from https://people.math.sc.edu/Burkardt/cpp_src/asa239/asa239.cpp - """ - - elimit = -88.0 - oflo = 1.0e37 - plimit = 1.0e3 - tol = 1.0e-14 - xbig = 1.0e8 - - if not (x >= 0.0 and p > 0.0): - raise library_error(errors.INVALID_HYPERGEO) - - if x == 0: - value, grad = 0.0, 0.0 - return grad - - if x > xbig: - value, grad = 1.0, 0.0 - return grad - - if p > plimit: # gaussian approximation - pn1 = 3 * sqrt(p) * (pow(x / p, 1 / 3) + 1 / (9 * p) - 1) - grad = pn1 / (2 * p) - 1 / sqrt(p) * (pow(x / p, 1 / 3) + 1 / (3 * p)) - grad *= 1 / sqrt(2 * pi) * exp(-(ipow(pn1, 2)) / 2) - value = (1 + erf(pn1 / sqrt(2))) / 2 - return grad - - if x <= 1 or x < p: # series expansion - arg = p * log(x) - x - lgamma(p + 1) - value, grad = 1.0, 0.0 - c, dc = 1.0, 0.0 - a = p - while True: - a += 1.0 - dc = -c * x / ipow(a, 2) + dc * x / a - c *= x / a - value += c - grad += dc - if c <= tol: - break - darg = exp(arg) * (log(x) - digamma(p + 1)) - grad = grad * exp(arg) + value * darg - arg += log(value) - if arg >= elimit: - value = exp(arg) - else: - grad = 0.0 - value = 0.0 - return grad - else: # continued fraction - arg = p * log(x) - x - lgamma(p) - a = 1.0 - p - b = a + x + 1.0 - c = 0.0 - pn1, pn2, pn3, pn4 = 1.0, x, x + 1.0, x * b - dpn1, dpn2, dpn3, dpn4 = 0.0, 0.0, 0.0, -x - value, grad = pn3 / pn4, 0.0 - while True: - a += 1.0 - b += 2.0 - c += 1.0 - an = a * c - pn5 = b * pn3 - an * pn1 - pn6 = b * pn4 - an * pn2 - dpn5 = b * dpn3 - pn3 - an * dpn1 + c * pn1 - dpn6 = b * dpn4 - pn4 - an * dpn2 + c * pn2 - if pn6 != 0.0: - rn = pn5 / pn6 - grad = (dpn5 * pn6 - pn5 * dpn6) / ipow(pn6, 2) - if abs(value - rn) <= min(tol, tol * rn): - break - value = rn - pn1, pn2, pn3, pn4 = pn3, pn4, pn5, pn6 - dpn1, dpn2, dpn3, dpn4 = dpn3, dpn4, dpn5, dpn6 - if oflo <= abs(pn5): - pn1 /= oflo - pn2 /= oflo - pn3 /= oflo - pn4 /= oflo - dpn1 /= oflo - dpn2 /= oflo - dpn3 /= oflo - dpn4 /= oflo - darg = exp(arg) * (log(x) - digamma(p)) - grad = grad * exp(arg) + value * darg - arg += log(value) - if arg >= elimit: - grad *= -1.0 - value = 1.0 - exp(arg) - else: - grad = 0.0 - value = 1.0 - return grad diff --git a/tests/oracle/prior.py b/tests/oracle/prior.py deleted file mode 100644 index 0802c9cd..00000000 --- a/tests/oracle/prior.py +++ /dev/null @@ -1,59 +0,0 @@ -""" -Oracles for the prior functions (``lib/prior.c``). -""" - -import numpy as np - -# NumPy's SIMD log and exp can differ from libm in the last bit on some CPUs; `_libm` -# gives the C library's results. -from ._libm import exp, log - - -def marginalize_over_ancestors(val): - """ - Integrate an expectation over counts of extant ancestors. In a tree with - "n" tips, the probability that there are "a" extent ancestors when a - subtree of size "k" coalesces is hypergeometric-ish (Wuif & Donnelly 1998), - and may be calculated recursively over increasing "a" and decreasing "k" - (e.g. using recursive relationships for binomial coefficients). - """ - n, N = val.shape # number of tips, number of moments - pr_a_ln = [np.nan, np.nan, 0.0] # log Pr(a | k, n) - out = np.zeros((n + 1, N)) - for k in range(n - 1, 1, -1): - # log(0) at k == 2 is -inf; the value is unused for k == 2 - const = log(n - k) + log(k - 2) - log(k + 1) - for a in range(2, n - k + 2): - out[k] += exp(pr_a_ln[a]) * val[a] - if k > 2: # Pr(a | k, n) to Pr(a | k - 1, n) - pr_a_ln[a] += const - log(n - a - k + 2) - if k > 2: # Pr(n - k + 1 | k - 1, n) to Pr(n - k + 2 | k - 1, n) - pr_a_ln.append(pr_a_ln[-1] + log(n - k + 2) - log(k + 1) - const) - out[n] = val[1] - return out - - -def conditional_coalescent_variance(num_tips): - """ - Variance of node age conditional on the number of descendant leaves, under - the standard coalescent. Returns array indexed by number of descendant - leaves. - """ - - coal_rates = np.array( - [2 / (i * (i - 1)) if i > 1 else 0.0 for i in range(1, num_tips + 1)] - ) - - # hypoexponential mean and variance; e.g. conditional on the number of - # extant ancestors when the node coalesces, the expected time of - # coalescence is the sum of exponential RVs (Wuif and Donnelly 1998) - mean = coal_rates.copy() - variance = coal_rates.copy() ** 2 - for i in range(coal_rates.size - 2, 0, -1): - mean[i] += mean[i + 1] - variance[i] += variance[i + 1] - - # marginalize over number of ancestors using recursive algorithm - moments = marginalize_over_ancestors(np.stack((mean, variance + mean**2), 1)) - - return moments[:, 1] - moments[:, 0] ** 2 diff --git a/tests/oracle/rescaling.py b/tests/oracle/rescaling.py deleted file mode 100644 index a2a862ae..00000000 --- a/tests/oracle/rescaling.py +++ /dev/null @@ -1,414 +0,0 @@ -""" -Oracles for the rescaling functions (``lib/rescaling.c``). -""" - -from math import inf - -import numpy as np -import tskit - -from . import errors - -# Plain `math.log` raises on 0, where C gives -inf; C sums sequentially, -# whereas numpy sums pairwise (`seq_sum`). -from ._libm import log, seq_sum -from .approx import approximate_gamma_iqr -from .errors import library_error -from .hypergeo import gammainc_inv - - -def fixed_changepoints(counts, epochs): - """ - Find breakpoints such that `counts` is divided roughly equally across `epochs` - """ - if not (epochs > 0): - raise library_error(errors.NONPOSITIVE_INTERVALS) - Y = np.append(0.0, np.cumsum(counts)) - Z = Y / Y[-1] - z = np.linspace(0, 1, epochs + 1) - e = np.searchsorted(Z, z, "right") - 1 - if e[0] > 0: - e[0] = 0 - if e[-1] < counts.size: - e[-1] = counts.size - return e.astype(np.int32) - - -def poisson_changepoints(counts, offset, penalty, min_counts, min_offset): - """ - Given Poisson counts and offsets for a sequence of observations, find the set - of changepoints for the Poisson rate that maximizes the profile likelihood - under a linear penalty on complexity (e.g. penalty == 2 is AIC). - - See: "Optimal detection of changepoints with a linear computation cost" - (https://doi.org/10.1080/01621459.2012.737745) - """ - - if counts.size != offset.size: - raise ValueError("counts and offset must have the same size") - if not (min_counts >= 0 and min_offset >= 0 and penalty >= 0): - raise library_error(errors.NEGATIVE_CHANGEPOINT_PARAMETER) - - N = np.append(0, np.cumsum(offset)) - Y = np.append(0, np.cumsum(counts)) - - def f(i, j): # loss - n = N[j] - N[i] - y = Y[j] - Y[i] - s = n < min_offset or y < min_counts - return inf if s else -2 * y * (log(y) - log(n) - 1) - - dim = counts.size - cost = np.empty(dim) - F = np.empty(dim + 1) - C = {0: np.empty(0, dtype=np.int64)} - - F[0] = -penalty - for j in np.arange(1, dim + 1): - argmin, minval = 0, np.inf - for i in C: # minimize - cost[i] = F[i] + f(i, j) + penalty - if cost[i] < minval: - minval = cost[i] - argmin = i - F[j] = minval - for i in set(C): # prune - if cost[i] > F[j] + penalty: - C.pop(i) - C[j] = np.append(C[argmin], argmin) - - breaks = np.append(C[dim], dim).astype(np.int32) - return breaks - - -def count_mutations( - nodes_sample, - mutations_node, - mutations_position, - edges_parent, - edges_child, - edges_left, - edges_right, - indexes_insert, - indexes_remove, - sequence_length, - size_biased, -): - """ - The mutations on each edge and the edge's span, weighted by the number of samples - below the edge if ``size_biased``, as ``(edges_stats, mutations_edge)``. - """ - if not ( - edges_parent.size - == edges_child.size - == edges_left.size - == edges_right.size - == indexes_insert.size - == indexes_remove.size - ): - raise ValueError("Edge arrays must have the same size") - if mutations_node.size != mutations_position.size: - raise ValueError("Mutation arrays must have the same size") - - num_mutations = mutations_node.size - num_edges = edges_parent.size - num_nodes = nodes_sample.size - - indexes_mutation = np.argsort(mutations_position) - position_insert = edges_left[indexes_insert] - position_remove = edges_right[indexes_remove] - position_mutation = mutations_position[indexes_mutation] - - nodes_samples = np.zeros(num_nodes) - nodes_edge = np.full(num_nodes, tskit.NULL) - nodes_parent = np.full(num_nodes, tskit.NULL) - mutations_edge = np.full(num_mutations, tskit.NULL) - edges_mutations = np.zeros(num_edges) - edges_span = np.zeros(num_edges) - - nodes_samples[nodes_sample] = 1.0 - left = 0.0 - a, b, d = 0, 0, 0 - while a < num_edges or b < num_edges: - remainder = sequence_length - left - - while b < num_edges and position_remove[b] == left: # edges out - e = indexes_remove[b] - p, c = edges_parent[e], edges_child[e] - nodes_edge[c] = tskit.NULL - nodes_parent[c] = tskit.NULL - if size_biased: - while p != tskit.NULL: # downdate sample counts - edges_span[e] -= nodes_samples[c] * remainder - nodes_samples[p] -= nodes_samples[c] - e, p = nodes_edge[p], nodes_parent[p] - else: - edges_span[e] -= remainder - b += 1 - - while a < num_edges and position_insert[a] == left: # edges in - e = indexes_insert[a] - p, c = edges_parent[e], edges_child[e] - nodes_edge[c] = e - nodes_parent[c] = p - if size_biased: - while p != tskit.NULL: # update sample counts - edges_span[e] += nodes_samples[c] * remainder - nodes_samples[p] += nodes_samples[c] - e, p = nodes_edge[p], nodes_parent[p] - else: - edges_span[e] += remainder - a += 1 - - right = sequence_length - if b < num_edges: - right = min(right, position_remove[b]) - if a < num_edges: - right = min(right, position_insert[a]) - left = right - - while d < num_mutations and position_mutation[d] < right: - m = indexes_mutation[d] - c = mutations_node[m] - e = nodes_edge[c] - if e != tskit.NULL: - mutations_edge[m] = e - edges_mutations[e] += nodes_samples[c] if size_biased else 1.0 - d += 1 - - mutations_edge = mutations_edge.astype(np.int32) - edges_stats = np.column_stack((edges_mutations, edges_span)) - - return edges_stats, mutations_edge - - -def mutational_area( - nodes_time, - likelihoods, - edges_parent, - edges_child, -): - """ - Calculate the total number of mutations and mutational area per inter-node - interval. These are infinitesimal; e.g. the actual count in an interval is - `returned_count * duration`. - - :param np.ndarray nodes_time: point estimates for node ages - :param np.ndarray likelihoods: edges are rows; mutation - counts and mutational span are columns - :param np.ndarray edges_parent: node index for the parent of each edge - :param np.ndarray edges_child: node index for the child of each edge - :param np.ndarray edges_weight: a weight for each edge - """ - - if edges_parent.size != edges_child.size: - raise ValueError("Edge arrays must have the same size") - if likelihoods.shape != (edges_parent.size, 2): - raise ValueError("Likelihoods must have one row of two columns per edge") - - # index node by unique time breaks - nodes_order = np.argsort(nodes_time) - nodes_index = np.zeros(nodes_time.size, dtype=np.int32) - epoch_breaks = [0.0] - k = 0 - for i, j in zip(nodes_order[1:], nodes_order[:-1]): - if nodes_time[i] > nodes_time[j]: - epoch_breaks.append(nodes_time[i]) - k += 1 - nodes_index[i] = k - epoch_breaks = np.array(epoch_breaks) - num_epochs = epoch_breaks.size - 1 - - # instantaneous mutation rate per edge - edges_length = nodes_time[edges_parent] - nodes_time[edges_child] - edges_subset = edges_length > 0 - edges_counts = likelihoods.copy() - edges_counts[edges_subset, 0] /= edges_length[edges_subset] - - # pass over edges, measuring overlap with each time interval - epoch_counts = np.zeros((num_epochs, 2)) - for e in np.flatnonzero(edges_subset): - p, c = edges_parent[e], edges_child[e] - a, b = nodes_index[c], nodes_index[p] - if a < num_epochs: - epoch_counts[a] += edges_counts[e] - if b < num_epochs: - epoch_counts[b] -= edges_counts[e] - counts = np.cumsum(epoch_counts[:, 0]) - offset = np.cumsum(epoch_counts[:, 1]) - duration = np.diff(epoch_breaks) - - return counts, offset, duration, nodes_index - - -def mutational_timescale( - nodes_time, - likelihoods, - nodes_fixed, - edges_parent, - edges_child, - max_intervals, -): - """ - Rescale node ages so that the instantaneous mutation rate is constant. - Edges with a negative duration are ignored when calculating the total - rate. Returns a rescaled point estimate and the posterior. - - :param np.ndarray nodes_time: point estimates for node ages - :param np.ndarray likelihoods: edges are rows; mutation - counts and mutational span are columns - :param np.ndarray constraints: lower and upper bounds on node age - :param np.ndarray edges_parent: node index for the parent of each edge - :param np.ndarray edges_child: node index for the child of each edge - :param int max_intervals: maximum number of intervals within which to - estimate the time scaling - """ - - if edges_parent.size != edges_child.size: - raise ValueError("Edge arrays must have the same size") - if likelihoods.shape != (edges_parent.size, 2): - raise ValueError("Likelihoods must have one row of two columns per edge") - if nodes_fixed.size != nodes_time.size: - raise ValueError("nodes_fixed and nodes_time must have the same size") - if not (max_intervals > 0): - raise library_error(errors.NONPOSITIVE_INTERVALS) - - counts, offset, duration, indexes = mutational_area( - nodes_time, - likelihoods, - edges_parent, - edges_child, - ) - - # rescale time such that mutation density is constant between changepoints - # TODO: use poisson changepoints to further refine - epoch_breaks = np.append(0.0, np.cumsum(duration)) - changepoints = fixed_changepoints(offset * duration, max_intervals) - changepoints = np.unique(changepoints) - # changepoints = np.union1d(changepoints, indexes[nodes_fixed]) - adjust = np.zeros(changepoints.size) - - # --- without any internal constraints --- - k = 0 - for i, j in zip(changepoints[:-1], changepoints[1:]): - assert j > i - # TODO: when changepoint intersects a fixed node? - n = seq_sum(offset[i:j]) - y = seq_sum(counts[i:j]) - z = seq_sum(duration[i:j]) - if not (n > 0): - raise library_error(errors.ZERO_EDGE_SPAN) - adjust[k + 1] = z * y / n - k += 1 - - adjust = np.cumsum(adjust) - origin = epoch_breaks[changepoints] - - return origin, adjust - - -def piecewise_scale_posterior( - posteriors, - posteriors_fixed, - original_breaks, - rescaled_breaks, - quantile_width, - max_shape, -): - """ - :param np.ndarray posteriors_fixed: if True do not rescale corresponding posterior - :param float quantile_width: width of interquantile range to use for estimating - rescaled shape parameter, e.g. 0.5 uses interquartile range - """ - - if not (posteriors.shape[1] == 2 and posteriors_fixed.size == posteriors.shape[0]): - raise ValueError("Posteriors must have two columns and one row per fixed flag") - if not (original_breaks.size == rescaled_breaks.size): - raise ValueError("Breakpoints must be of the same size") - if original_breaks.size == 0: - raise library_error(errors.NO_BREAKPOINTS) - if not (1 > quantile_width > 0): - raise library_error(errors.INVALID_QUANTILE_WIDTH) - - if not ( - np.all(np.diff(rescaled_breaks) > 0) and np.all(np.diff(original_breaks) > 0) - ): - raise library_error(errors.NON_INCREASING_BREAKPOINTS) - - dim = posteriors.shape[0] - quant_lower = quantile_width / 2 - quant_upper = 1 - quantile_width / 2 - - freed = ~posteriors_fixed - if not np.all(np.logical_and(posteriors[freed, 0] > -1, posteriors[freed, 1] > 0)): - raise library_error(errors.INVALID_POSTERIOR) - if dim == 0: - raise library_error(errors.NO_POSTERIORS) - - # use posterior mean as a point estimate - lower = np.zeros(dim) - upper = np.zeros(dim) - midpt = np.zeros(dim) - for i in np.flatnonzero(freed): - alpha, beta = posteriors[i] - lower[i] = gammainc_inv(alpha + 1, quant_lower) / beta - upper[i] = gammainc_inv(alpha + 1, quant_upper) / beta - midpt[i] = (alpha + 1) / beta - - # rescale quantiles - scalings = np.append(np.diff(rescaled_breaks) / np.diff(original_breaks), 0) - - def rescale(x): - i = np.searchsorted(original_breaks, x, "right") - 1 - if not (i.min() >= 0): - raise library_error(errors.TIME_BELOW_FIRST_BREAKPOINT) - assert i.max() < scalings.size - return rescaled_breaks[i] + scalings[i] * (x - original_breaks[i]) - - midpt = rescale(midpt) - lower = rescale(lower) - upper = rescale(upper) - - # reproject posteriors using inter-quantile range - new_posteriors = np.full(posteriors.shape, np.nan) - for i in np.flatnonzero(freed): - # The library reports a float division by zero here (as - # `ZeroDivisionError` in the oracle), where numpy scalars give inf. - # `approximate_gamma_iqr` divides by its `x1` argument (`x2 / x1`, or `... / x` - # in `upper_bound`) in every branch that doesn't raise earlier, so a zero lower - # quantile raises there. - if lower[i] == 0.0: - raise ZeroDivisionError("division by zero") - alpha, beta = approximate_gamma_iqr( - quant_lower, quant_upper, lower[i], upper[i], max_shape - ) - if midpt[i] == 0.0: - raise ZeroDivisionError("division by zero") - beta = (alpha + 1) / midpt[i] # choose rate so as to keep mean - new_posteriors[i] = alpha, beta - - return new_posteriors - - -def piecewise_scale_point_estimate( - point_estimate, - point_fixed, - original_breaks, - rescaled_breaks, -): - """ - Node ages mapped piecewise linearly from ``original_breaks`` to - ``rescaled_breaks``; ages where ``point_fixed`` are unchanged. - """ - if original_breaks.size == 0: - raise library_error(errors.NO_BREAKPOINTS) - if not ( - np.all(np.diff(rescaled_breaks) > 0) and np.all(np.diff(original_breaks) > 0) - ): - raise library_error(errors.NON_INCREASING_BREAKPOINTS) - scalings = np.append(np.diff(rescaled_breaks) / np.diff(original_breaks), 0) - idx = np.searchsorted(original_breaks, point_estimate, "right") - 1 - rescaled_estimate = rescaled_breaks[idx] + \ - scalings[idx] * (point_estimate - original_breaks[idx]) # fmt: skip - rescaled_estimate[point_fixed] = point_estimate[point_fixed] - return rescaled_estimate diff --git a/tests/oracle/variational.py b/tests/oracle/variational.py deleted file mode 100644 index cd25be73..00000000 --- a/tests/oracle/variational.py +++ /dev/null @@ -1,651 +0,0 @@ -""" -Oracles for the expectation propagation passes (``lib/variational.c``). - -``ExpectationPropagation`` has the methods and properties of -``_tsdate.ExpectationPropagation``. The passes it calls take the factors associated -with each edge likelihood, block likelihood and prior factor, which together form -the posterior, as a tuple of eight arrays ``(node, edge, block, scale, edges_parent, -edges_child, blocks_left, blocks_right)``, and update the first four in place. -""" - -import numpy as np -import tskit - -from tsdate.variational import ( - CONSTRNT, - LEAFWARD, - LOWER, - MIXPRIOR, - ROOTWARD, - TINY, - UPPER, -) - -from . import approx, errors - -# C sums sequentially, whereas numpy sums pairwise, which differs in the last -# bits; `seq_mean` sums sequentially. -from ._libm import seq_mean -from .errors import library_error - - -def rescale_factors(factors): - """ - At each update, all factors associated with a node need to be rescaled. - This is expensive, so we keep track of the scaling in a separate vector. - As updates progress, the factors will drift upward in magnitude while - the scaling drifts downward. To avoid underflow, we may need to - cancel out the scaling. - """ - node, edge, block, scale, edges_parent, edges_child, blocks_left, blocks_right = ( - factors - ) - edge[:, ROOTWARD] *= scale[edges_parent, np.newaxis] - edge[:, LEAFWARD] *= scale[edges_child, np.newaxis] - block[:, ROOTWARD] *= scale[blocks_left, np.newaxis] - block[:, LEAFWARD] *= scale[blocks_right, np.newaxis] - node[:, MIXPRIOR] *= scale[:, np.newaxis] - node[:, CONSTRNT] *= scale[:, np.newaxis] - scale[:] = 1.0 - - -def assemble_factors(factors): - """ - Transform factors into posteriors, intended for debugging purposes only. - """ - node, edge, block, scale, edges_parent, edges_child, blocks_left, blocks_right = ( - factors - ) - posterior = np.zeros((scale.size, 2)) - for i, (p, c) in enumerate(zip(edges_parent, edges_child)): - posterior[p] += edge[i, ROOTWARD] - posterior[c] += edge[i, LEAFWARD] - for i, (j, k) in enumerate(zip(blocks_left, blocks_right)): - posterior[j] += block[i, ROOTWARD] - posterior[k] += block[i, LEAFWARD] - posterior += node[:, MIXPRIOR] - posterior += node[:, CONSTRNT] - return posterior - - -def damp(x0, x1, y0, y1, s): - """ - If `x - y` is too small, find `d` so that `x - d*y` is large enough: - - x0 - d*y0 + 1 >= (x0 + 1)*s - x1 - d*y1 >= y1*s - - for `0 < s < 1`. - """ - if y0 == 0.0 and y1 == 0.0 and x0 == 0.0 and x1 == 0.0: - return 1.0 - if not (0 < s < 1): - raise library_error(errors.INVALID_MIN_STEP) - if not (0.0 < x0 + 1 and 0.0 < x1): - raise library_error(errors.INVALID_NODE_POSTERIOR) - a = 1.0 if (1 + x0 - y0 > (1 + x0) * s) else (1 - s) * (1 + x0) / y0 - b = 1.0 if (x1 - y1 > x1 * s) else (1 - s) * x1 / y1 - d = min(a, b) - if not (0.0 < d <= 1.0): - raise library_error(errors.INVALID_DAMPING) - return d - - -def rescale(x0, x1, s): - """ - Find `d` so that `d*x0 + 1 <= s` or `d*x0 + 1 >= 1/s` - """ - if x0 == 0.0 and x1 == 0.0: - return 1.0 - if not (0 < x0 + 1 and 0 < x1): - raise library_error(errors.INVALID_NODE_POSTERIOR) - if 1 + x0 > s: - return (s - 1) / x0 - elif 1 + x0 < 1 / s: - return (1 / s - 1) / x0 - return 1.0 - - -def constraints_are_consistent(constraints, edges_parent, edges_child): - """ - Whether the upper bound on each node's age is at least the maximum lower bound of - its descendants' ages. - """ - lower_max = constraints[:, LOWER].copy() - for p, c in zip(edges_parent, edges_child): - lower_max[p] = max(lower_max[c], lower_max[p]) - return not np.any(lower_max > constraints[:, UPPER]) - - -def propagate_likelihood( - edge_order, - edges_parent, - edges_child, - likelihoods, - constraints, - posterior, - factors, - lognorm, - max_shape, - min_step, - unphased, -): - # Update approximating factors for Poisson mutation likelihoods on edges. - # - # :param numpy.ndarray edges_parent: integer array of parent ids per edge - # :param numpy.ndarray edges_child: integer array of child ids per edge - # :param numpy.ndarray likelihoods: array of dimension `[num_edges, 2]` - # containing mutation count and mutational target size per edge. - # :param numpy.ndarray constraints: array of dimension `[num_nodes, 2]` - # containing lower and upper bounds for each node. - # :param numpy.ndarray posterior: array of dimension `[num_nodes, 2]` - # containing natural parameters for each node, updated in-place. - # :param tuple factors: the factor arrays, containing parent and child factors - # (natural parameters) for each edge, updated in-place. - # :param numpy.ndarray lognorm: array of dimension `[num_edges]` - # containing the approximate normalizing constants per edge, - # updated in-place. - # :param float max_shape: the maximum allowed shape for node posteriors. - # :param float min_step: the minimum allowed step size in (0, 1). - # :param bool unphased: if True, edges are treated as blocks of unphased - # singletons in contemporary individuals - - node, edge, block, scale, *_ = factors - factor = block if unphased else edge - num_nodes = node.shape[0] - if factor.shape[1:] != (2, 2): - raise ValueError("Factors must have shape (n, 2, 2)") - if edges_child.size != edges_parent.size: - raise ValueError("Edge arrays must have the same size") - if likelihoods.shape != (edges_parent.size, 2): - raise ValueError("Likelihoods must have shape (edges, 2)") - if constraints.shape != (num_nodes, 2): - raise ValueError("Constraints must have shape (nodes, 2)") - if posterior.shape != (num_nodes, 2): - raise ValueError("Posterior must have the same shape as constraints") - if lognorm.size != edges_parent.size: - raise ValueError("Lognorm must have one entry per edge") - if factor.shape[0] != edges_parent.size: - raise ValueError("Factors must have one entry per edge") - if not (max_shape >= 1.0): - raise library_error(errors.INVALID_MAX_SHAPE) - if not (0.0 < min_step < 1.0): - raise library_error(errors.INVALID_MIN_STEP) - - def cavity_damping(x, y): - return damp(x[0], x[1], y[0], y[1], min_step) - - def posterior_damping(x): - return rescale(x[0], x[1], max_shape) - - # the projections take the entries of the cavities and of the edge likelihood - # as floats, and return the normalizing constant and the projected natural - # parameters of each node - - def leafward_projection(t, x, y): - project = approx.sideways_projection if unphased else approx.leafward_projection - logl, *proj = project(t, *map(float, x), *map(float, y)) - return logl, proj - - def rootward_projection(t, x, y): - project = approx.sideways_projection if unphased else approx.rootward_projection - logl, *proj = project(t, *map(float, x), *map(float, y)) - return logl, proj - - def gamma_projection(x, y, z): - project = approx.unphased_projection if unphased else approx.gamma_projection - logl, *proj = project(*map(float, x), *map(float, y), *map(float, z)) - return logl, proj[:2], proj[2:] - - def twin_projection(x, y): - if not unphased: - raise library_error(errors.TWIN_EDGE_IN_PHASED_PASS) - logl, *proj = approx.twin_projection(*map(float, x), *map(float, y)) - return logl, proj - - fixed = constraints[:, LOWER] == constraints[:, UPPER] - - for i in edge_order: - p, c = edges_parent[i], edges_child[i] - if scale[p] < TINY or scale[c] < TINY: - # modifies `scale` and `factor` by reference - rescale_factors(factors) - if fixed[p] and fixed[c]: - continue - elif fixed[p] and not fixed[c]: - # in practice this should only occur if a sample is the - # ancestor of another sample - child_message = factor[i, LEAFWARD] * scale[c] - child_delta = cavity_damping(posterior[c], child_message) - child_cavity = posterior[c] - child_delta * child_message - edge_likelihood = child_delta * likelihoods[i] - parent_age = constraints[p, LOWER] - lognorm[i], posterior[c] = leafward_projection( - parent_age, - child_cavity, - edge_likelihood, - ) - factor[i, LEAFWARD] *= 1.0 - child_delta - factor[i, LEAFWARD] += (posterior[c] - child_cavity) / scale[c] - child_eta = posterior_damping(posterior[c]) - posterior[c] *= child_eta - scale[c] *= child_eta - elif fixed[c] and not fixed[p]: - # in practice this should only occur if a sample has age - # greater than zero - parent_message = factor[i, ROOTWARD] * scale[p] - parent_delta = cavity_damping(posterior[p], parent_message) - parent_cavity = posterior[p] - parent_delta * parent_message - edge_likelihood = parent_delta * likelihoods[i] - child_age = constraints[c, LOWER] - lognorm[i], posterior[p] = rootward_projection( - child_age, - parent_cavity, - edge_likelihood, - ) - factor[i, ROOTWARD] *= 1.0 - parent_delta - factor[i, ROOTWARD] += (posterior[p] - parent_cavity) / scale[p] - parent_eta = posterior_damping(posterior[p]) - posterior[p] *= parent_eta - scale[p] *= parent_eta - else: - if p == c: # singleton block with single parent - parent_message = factor[i, ROOTWARD] * scale[p] - parent_delta = cavity_damping(posterior[p], parent_message) - parent_cavity = posterior[p] - parent_delta * parent_message - edge_likelihood = parent_delta * likelihoods[i] - child_age = constraints[c, LOWER] - lognorm[i], posterior[p] = \ - twin_projection(parent_cavity, edge_likelihood) # fmt: skip - factor[i, ROOTWARD] *= 1.0 - parent_delta - factor[i, ROOTWARD] += (posterior[p] - parent_cavity) / scale[p] - parent_eta = posterior_damping(posterior[p]) - posterior[p] *= parent_eta - scale[p] *= parent_eta - else: - # lower-bound cavity - parent_message = factor[i, ROOTWARD] * scale[p] - child_message = factor[i, LEAFWARD] * scale[c] - parent_delta = cavity_damping(posterior[p], parent_message) - child_delta = cavity_damping(posterior[c], child_message) - delta = min(parent_delta, child_delta) - - parent_cavity = posterior[p] - delta * parent_message - child_cavity = posterior[c] - delta * child_message - edge_likelihood = delta * likelihoods[i] - - # match moments and update factors - lognorm[i], posterior[p], posterior[c] = gamma_projection( - parent_cavity, - child_cavity, - edge_likelihood, - ) - factor[i, ROOTWARD] *= 1.0 - delta - factor[i, ROOTWARD] += (posterior[p] - parent_cavity) / scale[p] - factor[i, LEAFWARD] *= 1.0 - delta - factor[i, LEAFWARD] += (posterior[c] - child_cavity) / scale[c] - - # upper-bound posterior - parent_eta = posterior_damping(posterior[p]) - child_eta = posterior_damping(posterior[c]) - posterior[p] *= parent_eta - posterior[c] *= child_eta - scale[p] *= parent_eta - scale[c] *= child_eta - - -def propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol): - # Update approximating factors for global prior. - # - # :param ndarray free: boolean array for if prior should be applied to node - # :param ndarray penalty: initial value for regularisation penalty - # :param ndarray posterior: rows are nodes, columns are first and - # second natural parameters of gamma posteriors. Updated in place. - # :param tuple factors: the factor arrays, containing EP messages for nodes. - # Updated in place. - # :param float max_shape: the maximum allowed shape for node posteriors. - # :param int em_maxitt: the maximum number of EM iterations to use when - # fitting the regularisation. - # :param int em_reltol: the termination criterion for relative change in - # log-likelihood. - - node, edge, block, scale, *_ = factors - factor = node - if factor.shape[1:] != (2, 2): - raise ValueError("Factors must have shape (n, 2, 2)") - if scale.size != factor.shape[0]: - raise ValueError("Factor arrays have inconsistent sizes") - if not (free.size == factor.shape[0] and posterior.shape == (free.size, 2)): - raise ValueError( - "The free nodes, posterior and factors must have one entry per node" - ) - if not (max_shape >= 1.0): - raise library_error(errors.INVALID_MAX_SHAPE) - - def posterior_damping(x): - return rescale(x[0], x[1], max_shape) - - if not np.any(free): - return - - # fit an exponential to cavity distributions for unconstrained nodes - cavity = posterior - factor[:, MIXPRIOR] * scale[:, np.newaxis] - shape, rate = cavity[free, 0] + 1, cavity[free, 1] - penalty = 1 / seq_mean(shape / rate) - itt, delta = 0, np.inf - while abs(delta) > abs(penalty) * em_reltol: - if itt > em_maxitt: - break - delta = 1 / seq_mean(shape / (rate + penalty)) - penalty - penalty += delta - itt += 1 - if not (penalty > 0): - raise library_error(errors.NONPOSITIVE_PENALTY) - - # update posteriors and rescale to keep shape bounded - posterior[free, 1] = cavity[free, 1] + penalty - factor[free, MIXPRIOR] = \ - (posterior[free] - cavity[free]) / scale[free, np.newaxis] # fmt: skip - for i in np.flatnonzero(free): - eta = posterior_damping(posterior[i]) - posterior[i] *= eta - scale[i] *= eta - - -def propagate_mutations( - mutations_order, - mutations_posterior, - mutations_phase, - mutations_edge, - edges_parent, - edges_child, - likelihoods, - constraints, - posterior, - factors, - unphased, -): - # Calculate posteriors for mutations. (publicly undocumented) - # - # :param ndarray mutations_order: integer array giving order in - # which to traverse mutations - # :param ndarray mutations_posterior: array of dimension `(num_mutations, 2)` - # containing natural parameters for each mutation, modified in place - # :param ndarray mutations_phase: array of dimension `(num_mutations, )` - # containing mutation phase, modified in place - # :param ndarray mutations_edge: integer array giving edge for each mutation - # :param ndarray edges_parent: integer array of parent ids per edge - # :param ndarray edges_child: integer array of child ids per edge - # :param ndarray likelihoods: array of dimension `[num_edges, 2]` - # containing mutation count and mutational target size per edge. - # :param ndarray constraints: array of dimension `[num_nodes, 2]` - # containing lower and upper bounds for each node. - # :param ndarray posterior: array of dimension `[num_nodes, 2]` - # containing natural parameters for each node - # :param tuple factors: the factor arrays, containing parent and child factors - # (natural parameters) for each edge - # :param bool unphased: if True, edges are treated as blocks of unphased - # singletons in contemporary individuals - - # TODO: scale should be 1.0, can we delete - # TODO: we don't seem to need to damp? - - node, edge, block, scale, *_ = factors - factor = block if unphased else edge - num_nodes = node.shape[0] - if factor.shape[1:] != (2, 2): - raise ValueError("Factors must have shape (n, 2, 2)") - if mutations_edge.size != mutations_phase.size: - raise ValueError("Mutation arrays must have the same size") - if mutations_posterior.shape != (mutations_phase.size, 2): - raise ValueError("Mutation posterior must have shape (mutations, 2)") - if edges_child.size != edges_parent.size: - raise ValueError("Edge arrays must have the same size") - if likelihoods.shape != (edges_parent.size, 2): - raise ValueError("Likelihoods must have shape (edges, 2)") - if constraints.shape != (num_nodes, 2): - raise ValueError("Constraints must have shape (nodes, 2)") - if posterior.shape != (num_nodes, 2): - raise ValueError("Posterior must have the same shape as constraints") - if factor.shape[0] != edges_parent.size: - raise ValueError("Factors must have one entry per edge") - - # the projections take the entries of the cavities and of the edge likelihood - # as floats, and return the phase and the natural parameters of the mutation - - def leafward_projection(t, x, y): - if unphased: - project = approx.mutation_sideways_projection - else: - project = approx.mutation_leafward_projection - phase, *proj = project(t, *map(float, x), *map(float, y)) - return phase, proj - - def rootward_projection(t, x, y): - if unphased: - project = approx.mutation_sideways_projection - else: - project = approx.mutation_rootward_projection - phase, *proj = project(t, *map(float, x), *map(float, y)) - return phase, proj - - def gamma_projection(x, y, z): - if unphased: - project = approx.mutation_unphased_projection - else: - project = approx.mutation_gamma_projection - phase, *proj = project(*map(float, x), *map(float, y), *map(float, z)) - return phase, proj - - def fixed_projection(t_i, t_j): - if unphased: - project = approx.mutation_block_projection - else: - project = approx.mutation_edge_projection - phase, *proj = project(t_i, t_j) - return phase, proj - - def twin_projection(x, y): - phase, *proj = approx.mutation_twin_projection(*map(float, x), *map(float, y)) - return phase, proj - - fixed = constraints[:, LOWER] == constraints[:, UPPER] - - for m in mutations_order: - i = mutations_edge[m] - if i == tskit.NULL: # skip mutations above root - continue - p, c = edges_parent[i], edges_child[i] - if fixed[p] and fixed[c]: - child_age = constraints[c, 0] - parent_age = constraints[p, 0] - mutations_phase[m], mutations_posterior[m] = \ - fixed_projection(parent_age, child_age) # fmt: skip - elif fixed[p] and not fixed[c]: - child_message = factor[i, LEAFWARD] * scale[c] - child_delta = 1.0 # hopefully we don't need to damp - child_cavity = posterior[c] - child_delta * child_message - edge_likelihood = child_delta * likelihoods[i] - parent_age = constraints[p, LOWER] - mutations_phase[m], mutations_posterior[m] = leafward_projection( - parent_age, - child_cavity, - edge_likelihood, - ) - elif fixed[c] and not fixed[p]: - parent_message = factor[i, ROOTWARD] * scale[p] - parent_delta = 1.0 # hopefully we don't need to damp - parent_cavity = posterior[p] - parent_delta * parent_message - edge_likelihood = parent_delta * likelihoods[i] - child_age = constraints[c, LOWER] - mutations_phase[m], mutations_posterior[m] = rootward_projection( - child_age, - parent_cavity, - edge_likelihood, - ) - else: - if p == c: # singleton block with single parent - parent_message = factor[i, ROOTWARD] * scale[p] - parent_delta = 1.0 # hopefully we don't need to damp - parent_cavity = posterior[p] - parent_delta * parent_message - edge_likelihood = parent_delta * likelihoods[i] - child_age = constraints[c, LOWER] - mutations_phase[m], mutations_posterior[m] = \ - twin_projection(parent_cavity, edge_likelihood) # fmt: skip - else: - parent_message = factor[i, ROOTWARD] * scale[p] - child_message = factor[i, LEAFWARD] * scale[c] - parent_delta = 1.0 # hopefully we don't need to damp - child_delta = 1.0 # hopefully we don't need to damp - delta = min(parent_delta, child_delta) - parent_cavity = posterior[p] - delta * parent_message - child_cavity = posterior[c] - delta * child_message - edge_likelihood = delta * likelihoods[i] - mutations_phase[m], mutations_posterior[m] = gamma_projection( - parent_cavity, - child_cavity, - edge_likelihood, - ) - - -class ExpectationPropagation: - """ - The state of expectation propagation, with the methods and properties of - ``_tsdate.ExpectationPropagation`` - """ - - def __init__( - self, - constraints, - edges_parent, - edges_child, - edges_likelihood, - blocks_left, - blocks_right, - blocks_likelihood, - ): - num_nodes = constraints.shape[0] - for ids in (edges_parent, edges_child, blocks_left, blocks_right): - if np.any((ids < 0) | (ids >= num_nodes)): - raise library_error(errors.NODE_OUT_OF_BOUNDS) - self.constraints = constraints.copy() - self.edges_parent = edges_parent.copy() - self.edges_child = edges_child.copy() - self.edges_likelihood = edges_likelihood.copy() - self.blocks_left = blocks_left.copy() - self.blocks_right = blocks_right.copy() - self.blocks_likelihood = blocks_likelihood.copy() - self.node = np.zeros((num_nodes, 2, 2)) - self.edge = np.zeros((edges_parent.size, 2, 2)) - self.block = np.zeros((blocks_left.size, 2, 2)) - self.scale = np.ones(num_nodes) - self._posterior = np.zeros((num_nodes, 2)) - self._edges_lognorm = np.zeros(edges_parent.size) - self._blocks_lognorm = np.zeros(blocks_left.size) - - def factors(self): - """ - The factors as the tuple of arrays that the passes take - """ - return ( - self.node, - self.edge, - self.block, - self.scale, - self.edges_parent, - self.edges_child, - self.blocks_left, - self.blocks_right, - ) - - def _edges(self, unphased): - if unphased: - return self.blocks_left, self.blocks_right, self.blocks_likelihood - return self.edges_parent, self.edges_child, self.edges_likelihood - - def propagate_likelihood(self, order, unphased, max_shape, min_step): - """ - Update the factors of the edges (blocks, if ``unphased``) in ``order`` - """ - parents, children, likelihood = self._edges(unphased) - lognorm = self._blocks_lognorm if unphased else self._edges_lognorm - if not (max_shape >= 1.0): - raise library_error(errors.INVALID_MAX_SHAPE) - if not (0.0 < min_step < 1.0): - raise library_error(errors.INVALID_MIN_STEP) - if np.any((order < 0) | (order >= parents.size)): - code = errors.BLOCK_OUT_OF_BOUNDS if unphased else errors.EDGE_OUT_OF_BOUNDS - raise library_error(code) - propagate_likelihood( - order, - parents, - children, - likelihood, - self.constraints, - self._posterior, - self.factors(), - lognorm, - max_shape, - min_step, - unphased, - ) - - def propagate_prior(self, free, max_shape, em_maxitt, em_reltol): - """ - Fit an exponential prior to the cavities of the ``free`` nodes - """ - if free.size != self.scale.size: - raise ValueError("free must have one entry per node") - propagate_prior( - free, self._posterior, self.factors(), max_shape, em_maxitt, em_reltol - ) - - def rescale_factors(self): - """ - Multiply the factors by the scales of their nodes - """ - rescale_factors(self.factors()) - - def assemble_factors(self): - """ - The posteriors implied by the factors - """ - return assemble_factors(self.factors()) - - def propagate_mutations(self, mutations_edge, unphased): - """ - The posteriors and phases of mutations above ``mutations_edge`` - """ - parents, children, likelihood = self._edges(unphased) - if np.any((mutations_edge < tskit.NULL) | (mutations_edge >= parents.size)): - code = errors.BLOCK_OUT_OF_BOUNDS if unphased else errors.EDGE_OUT_OF_BOUNDS - raise library_error(code) - num_mutations = mutations_edge.size - posterior = np.full((num_mutations, 2), np.nan) - phase = np.ones(num_mutations) - propagate_mutations( - np.arange(num_mutations, dtype=np.int32), - posterior, - phase, - mutations_edge, - parents, - children, - likelihood, - self.constraints, - self._posterior, - self.factors(), - unphased, - ) - return posterior, phase - - @property - def posterior(self): - return self._posterior.copy() - - @property - def edges_lognorm(self): - return self._edges_lognorm.copy() - - @property - def blocks_lognorm(self): - return self._blocks_lognorm.copy() diff --git a/tests/test_approximations.py b/tests/test_approximations.py deleted file mode 100644 index f2496389..00000000 --- a/tests/test_approximations.py +++ /dev/null @@ -1,324 +0,0 @@ -# MIT License -# -# Copyright (c) 2021-23 Tskit Developers -# Copyright (c) 2020-21 University of Oxford -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -""" -Test cases for the gamma-variational approximations in tsdate -""" - -from math import sqrt - -import _tsdate -import numpy as np -import pytest -import scipy.integrate -import scipy.special -import scipy.stats -from exact_moments import ( - leafward_moments, - moments, - mutation_block_moments, - mutation_edge_moments, - mutation_leafward_moments, - mutation_moments, - mutation_rootward_moments, - mutation_sideways_moments, - mutation_twin_moments, - mutation_unphased_moments, - rootward_moments, - sideways_moments, - twin_moments, - unphased_moments, -) - -# TODO: better test set? -_gamma_trio_test_cases = [ # [shape1, rate1, shape2, rate2, muts, rate] - [2.0, 0.0005, 1.5, 0.005, 0.0, 0.001], - [2.0, 0.0005, 1.5, 0.005, 1.0, 0.001], - [2.0, 0.0005, 1.5, 0.005, 2.0, 0.001], - [2.0, 0.0005, 1.5, 0.005, 3.0, 0.001], -] - - -@pytest.mark.parametrize("pars", _gamma_trio_test_cases) -class TestPosteriorMomentMatching: - """ - Test Laplace approximation of pairwise joint distributions for EP updates - """ - - def test_moments(self, pars): - """ - Test mean and variance when ages of both nodes are free - """ - rtol = 1e-2 - ll, mn_i, va_i, mn_j, va_j = _tsdate.moments(*pars) - ck_ll, ck_mn_i, ck_va_i, ck_mn_j, ck_va_j = moments(*pars) - assert np.isclose(ck_ll, ll, rtol=rtol) - assert np.isclose(ck_mn_i, mn_i, rtol=rtol) - assert np.isclose(ck_mn_j, mn_j, rtol=rtol) - assert np.isclose(sqrt(ck_va_i), sqrt(va_i), rtol=rtol) - assert np.isclose(sqrt(ck_va_j), sqrt(va_j), rtol=rtol) - - def test_rootward_moments(self, pars): - """ - Test mean and variance of parent age when child age is fixed to a nonzero value - """ - rtol = 2e-2 - a_i, b_i, a_j, b_j, y, mu = pars - pars_redux = (a_i, b_i, y, mu) - mn_j = a_j / b_j - for t_j in [0.0, mn_j]: - ll, mn_i, va_i = _tsdate.rootward_moments(t_j, *pars_redux) - ck_ll, ck_mn_i, ck_va_i = rootward_moments(t_j, *pars_redux) - assert np.isclose(ck_ll, ll, rtol=rtol) - assert np.isclose(ck_mn_i, mn_i, rtol=rtol) - assert np.isclose(sqrt(ck_va_i), sqrt(va_i), rtol=rtol) - - def test_leafward_moments(self, pars): - """ - Test mean and variance of child age when parent age is fixed to a nonzero value - """ - rtol = 1e-2 - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - pars_redux = (a_j, b_j, y, mu) - ll, mn_j, va_j = _tsdate.leafward_moments(t_i, *pars_redux) - ck_ll, ck_mn_j, ck_va_j = leafward_moments(t_i, *pars_redux) - assert np.isclose(ck_ll, ll, rtol=rtol) - assert np.isclose(ck_mn_j, mn_j, rtol=rtol) - assert np.isclose(sqrt(ck_va_j), sqrt(va_j), rtol=rtol) - - def test_unphased_moments(self, pars): - """ - Parent ages for an singleton nodes above an unphased individual - """ - rtol = 1e-2 - ll, mn_i, va_i, mn_j, va_j = _tsdate.unphased_moments(*pars) - ck_ll, ck_mn_i, ck_va_i, ck_mn_j, ck_va_j = unphased_moments(*pars) - assert np.isclose(ck_ll, ll, rtol=rtol) - assert np.isclose(ck_mn_i, mn_i, rtol=rtol) - assert np.isclose(ck_mn_j, mn_j, rtol=rtol) - assert np.isclose(sqrt(ck_va_i), sqrt(va_i), rtol=rtol) - assert np.isclose(sqrt(ck_va_j), sqrt(va_j), rtol=rtol) - - def test_twin_moments(self, pars): - """ - Parent age for a singleton node above both edges of an unphased - individual - """ - a_i, b_i, a_j, b_j, y_ij, mu_ij = pars - pars_redux = (a_i, b_i, y_ij, mu_ij) - ll, mn_i, va_i = _tsdate.twin_moments(*pars_redux) - ck_ll, ck_mn_i, ck_va_i = twin_moments(*pars_redux) - assert np.isclose(ck_ll, ll) - assert np.isclose(ck_mn_i, mn_i) - assert np.isclose(sqrt(ck_va_i), sqrt(va_i)) - - def test_sideways_moments(self, pars): - """ - Parent ages for an singleton nodes above an unphased individual, where - second parent is fixed to a particular time - """ - rtol = 1e-2 - a_i, b_i, a_j, b_j, y, mu = pars - pars_redux = (a_j, b_j, y, mu) - t_i = a_i / b_i - ll, mn_j, va_j = _tsdate.sideways_moments(t_i, *pars_redux) - ck_ll, ck_mn_j, ck_va_j = sideways_moments(t_i, *pars_redux) - assert np.isclose(ck_ll, ll, rtol=rtol) - assert np.isclose(ck_mn_j, mn_j, rtol=rtol) - assert np.isclose(sqrt(ck_va_j), sqrt(va_j), rtol=rtol) - - def test_mutation_moments(self, pars): - """ - Mutation mapped to a single branch with both nodes free - """ - rtol = 2e-2 - mn, va = _tsdate.mutation_moments(*pars) - ck_mn, ck_va = mutation_moments(*pars) - assert np.isclose(ck_mn, mn, rtol=rtol) - assert np.isclose(sqrt(ck_va), sqrt(va), rtol=rtol) - - def test_mutation_rootward_moments(self, pars): - """ - Mutation mapped to a single branch with child node fixed - """ - rtol = 1e-2 - a_i, b_i, a_j, b_j, y, mu = pars - pars_redux = (a_i, b_i, y, mu) - mn_j = a_j / b_j - for t_j in [0.0, mn_j]: - mn, va = _tsdate.mutation_rootward_moments(t_j, *pars_redux) - ck_mn, ck_va = mutation_rootward_moments(t_j, *pars_redux) - assert np.isclose(ck_mn, mn, rtol=rtol) - assert np.isclose(sqrt(ck_va), sqrt(va), rtol=rtol) - - def test_mutation_leafward_moments(self, pars): - """ - Mutation mapped to a single branch with parent node fixed - """ - rtol = 1e-2 - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - pars_redux = (a_j, b_j, y, mu) - mn, va = _tsdate.mutation_leafward_moments(t_i, *pars_redux) - ck_mn, ck_va = mutation_leafward_moments(t_i, *pars_redux) - assert np.isclose(ck_mn, mn, rtol=rtol) - assert np.isclose(sqrt(ck_va), sqrt(va), rtol=rtol) - - def test_mutation_unphased_moments(self, pars): - """ - Mutation mapped to two singleton branches with children fixed to time zero - """ - rtol = 1e-2 - pr, mn, va = _tsdate.mutation_unphased_moments(*pars) - ck_pr, ck_mn, ck_va = mutation_unphased_moments(*pars) - assert np.isclose(ck_pr, pr, rtol=rtol) - assert np.isclose(ck_mn, mn, rtol=rtol) - assert np.isclose(sqrt(ck_va), sqrt(va), rtol=rtol) - - def test_mutation_twin_moments(self, pars): - """ - Mutation mapped to two singleton branches with children fixed to time zero - and the same parent - """ - a_i, b_i, a_j, b_j, y_ij, mu_ij = pars - pars_redux = (a_i, b_i, y_ij, mu_ij) - pr, mn, va = _tsdate.mutation_twin_moments(*pars_redux) - ck_pr, ck_mn, ck_va = mutation_twin_moments(*pars_redux) - assert np.isclose(ck_pr, pr) - assert np.isclose(ck_mn, mn) - assert np.isclose(sqrt(ck_va), sqrt(va)) - - def test_mutation_sideways_moments(self, pars): - """ - Mutation mapped to two branches with children fixed to time zero, and - left parent (i) fixed - """ - rtol = 1e-2 - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - pars_redux = (a_j, b_j, y, mu) - pr, mn, va = _tsdate.mutation_sideways_moments(t_i, *pars_redux) - ck_pr, ck_mn, ck_va = mutation_sideways_moments(t_i, *pars_redux) - assert np.isclose(ck_pr, pr, rtol=rtol) - assert np.isclose(ck_mn, mn, rtol=rtol) - assert np.isclose(sqrt(ck_va), sqrt(va), rtol=rtol) - - def test_mutation_edge_moments(self, pars): - """ - Mutation mapped to a single edge with parent and child fixed - """ - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - t_j = a_j / b_j - mn, va = _tsdate.mutation_edge_moments(t_i, t_j) - ck_mn, ck_va = mutation_edge_moments(t_i, t_j) - assert np.isclose(ck_mn, mn) - assert np.isclose(sqrt(ck_va), sqrt(va)) - - def test_mutation_block_moments(self, pars): - """ - Mutation mapped to two branches with children fixed to time zero, and - both parents fixed - """ - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - t_j = a_j / b_j - pr, mn, va = _tsdate.mutation_block_moments(t_i, t_j) - ck_pr, ck_mn, ck_va = mutation_block_moments(t_i, t_j) - assert np.isclose(ck_pr, pr) - assert np.isclose(ck_mn, mn) - assert np.isclose(sqrt(ck_va), sqrt(va)) - - def test_approximate_gamma_kl(self, pars): - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - ln_t_i = _tsdate.digamma(a_i) - np.log(b_i) - t_j = a_j / b_j - ln_t_j = _tsdate.digamma(a_j) - np.log(b_j) - alpha_i, beta_i = _tsdate.approximate_gamma_kl(t_i, ln_t_i) - alpha_j, beta_j = _tsdate.approximate_gamma_kl(t_j, ln_t_j) - ck_t_i = (alpha_i + 1) / beta_i - assert np.isclose(t_i, ck_t_i) - ck_t_j = (alpha_j + 1) / beta_j - assert np.isclose(t_j, ck_t_j) - ck_ln_t_i = _tsdate.digamma(alpha_i + 1) - np.log(beta_i) - assert np.isclose(ln_t_i, ck_ln_t_i) - ck_ln_t_j = _tsdate.digamma(alpha_j + 1) - np.log(beta_j) - assert np.isclose(ln_t_j, ck_ln_t_j) - - def test_approximate_gamma_mom(self, pars): - _, t_i, va_t_i, t_j, va_t_j = _tsdate.moments(*pars) - alpha_i, beta_i = _tsdate.approximate_gamma_mom(t_i, va_t_i) - alpha_j, beta_j = _tsdate.approximate_gamma_mom(t_j, va_t_j) - ck_t_i = (alpha_i + 1) / beta_i - assert np.isclose(t_i, ck_t_i) - ck_t_j = (alpha_j + 1) / beta_j - assert np.isclose(t_j, ck_t_j) - ck_va_t_i = (alpha_i + 1) / beta_i**2 - assert np.isclose(va_t_i, ck_va_t_i) - ck_va_t_j = (alpha_j + 1) / beta_j**2 - assert np.isclose(va_t_j, ck_va_t_j) - - -class TestGammaFactorization: - """ - Test various functions for manipulating factorizations of gamma distributions - """ - - def test_average_gammas(self): - # E[x] = shape/rate - # E[log x] = digamma(shape) - log(rate) - shape = np.array([0.5, 1.5]) - rate = np.array([1.0, 1.0]) - avg_shape, avg_rate = _tsdate.average_gammas(shape, rate) - E_x = np.mean(shape + 1) - E_logx = np.mean(scipy.special.digamma(shape + 1)) - assert np.isclose(E_x, (avg_shape + 1) / avg_rate) - assert np.isclose(E_logx, scipy.special.digamma(avg_shape + 1) - np.log(avg_rate)) - - -class TestKLMinimizationFailed: - """ - Test errors in KL minimization - """ - - def test_violates_jensen(self): - with pytest.raises(_tsdate.LibraryError, match="violates Jensen's"): - _tsdate.approximate_gamma_kl(1, 0) - - def test_asymptotic_bound(self): - # check that bound is returned over threshold (rather than optimization) - logx = -0.000001 - alpha, _ = _tsdate.approximate_gamma_kl(1, logx) - alpha += 1 - alpha_bound = -0.5 / logx - assert alpha == alpha_bound - assert alpha > 1e4 - # check that bound matches optimization result just under threshold - logx = -0.000051 - alpha, _ = _tsdate.approximate_gamma_kl(1, logx) - alpha += 1 - alpha_bound = -0.5 / logx - assert np.abs(alpha - alpha_bound) < 1 - assert alpha < 1e4 diff --git a/tests/test_hypergeo.py b/tests/test_hypergeo.py deleted file mode 100644 index a0356b46..00000000 --- a/tests/test_hypergeo.py +++ /dev/null @@ -1,213 +0,0 @@ -# MIT License -# -# Copyright (c) 2021-23 Tskit Developers -# Copyright (c) 2020-21 University of Oxford -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -""" -Test cases for numba-fied hypergeometric functions -""" - -from math import lgamma - -import _tsdate -import mpmath -import numdifftools as nd -import numpy as np -import pytest - - -@pytest.mark.parametrize("x", [-0.3, 1e-10, 1e-6, 1e-2, 1e1, 1e2, 1e3, 1e5, 1e10]) -class TestPolygamma: - """ - Test numba-fied gamma functions - """ - - def test_lgamma(self, x): - assert np.isclose(lgamma(x), float(mpmath.re(mpmath.loggamma(x)))) - - def test_digamma(self, x): - assert np.isclose(_tsdate.digamma(x), float(mpmath.psi(0, x))) - - def test_trigamma(self, x): - assert np.isclose(_tsdate.trigamma(x), float(mpmath.psi(1, x))) - - def test_betaln(self, x): - assert np.isclose( - _tsdate.betaln(x, 2 * x), - float(mpmath.re(mpmath.log(mpmath.beta(x, 2 * x)))), - ) - - -@pytest.mark.parametrize( - "pars", - [ - [969.5, 0.1062, 984.72, 0.1215, 0.0, 0.000239], - [897.8, 0.0954, 936.03, 0.1042, 1.0, 0.000840], - [37.94, 0.0087, 413.54, 0.1122, 0.0, 2.70e-05], - [748.1, 0.0857, 544.65, 0.0621, 0.0, 0.000511], - [21.18, 0.0226, 21.898, 0.0292, 0.0, 0.000618], - [7.931, 0.0010, 1000.0, 0.1675, 0.0, 0.000290], - [77.15, 0.0484, 42.007, 0.0348, 0.0, 0.000277], - [990.5, 0.1318, 130.68, 0.0205, 1.0, 0.000245], - [678.9, 0.1184, 121.71, 0.0958, 2.0, 0.000208], - ], -) -class TestLaplaceApprox2F1: - """ - Test that Laplace approximation to 2F1 returns reasonable answers - """ - - @staticmethod - def _2f1_validate(a_i, b_i, a_j, b_j, y, mu, offset=1.0): - A = a_j - B = a_i + a_j + y - C = a_j + y + 1 - z = (mu - b_j) / (mu + b_i) - val = mpmath.re(mpmath.hyp2f1(A, B, C, z, maxterms=1e6)) - return val / offset - - def test_2f1(self, pars): - a_i, b_i, a_j, b_j, y, mu = pars - A = a_j - B = a_i + a_j + y - C = a_j + y + 1 - z = (mu - b_j) / (mu + b_i) - f = _tsdate.hyp2f1_laplace(A, B, C, z) - check = float(mpmath.log(self._2f1_validate(*pars))) - assert np.isclose(f, check, rtol=2e-2) - - -@pytest.mark.parametrize( - "pars", - [ - [202.865, 0.0153, 0.0012724, 101353547.00, 0.0, 2.404560e-05], - [999.998, 0.1041, 0.0012612, 14749022.000, 2.0, 7.830300e-05], - [157.778, 0.0182, 0.0011993, 20861958.000, 0.0, 4.128000e-07], - [1000.00, 0.1431, 0.0009718, 22638776.000, 0.0, 5.881110e-05], - [405.482, 0.1484, 0.0009711, 41053809.000, 0.0, 6.229410e-05], - [115.773, 0.7506, 0.0015549, 23315696857.0, 0.0, 3.601680e-05], - [73.4909, 1.0600, 0.0010028, 56254280956.0, 0.0, 0.0002302392], - [18.9981, 0.1315, 0.0015053, 23443723634.0, 1.0, 2.470348e-05], - ], -) -class Test2F1Unity: - """ - As TestLaplaceApprox2F1 but in the argument-close-to-unity limit - """ - - @staticmethod - def _2f1_validate(a_i, b_i, a_j, b_j, y, mu, offset=1.0): - A = a_j - B = a_i + a_j + y - C = a_j + y + 1 - z = (mu - b_j) / (mu + b_i) - val = mpmath.re(mpmath.hyp2f1(A, B, C, z, maxterms=1e7)) - return val / offset - - @pytest.mark.skip(reason="_hyp2f1_unity now an inner function for numba") - def test_2f1(self, pars): - a_i, b_i, a_j, b_j, y, mu = pars - A = a_j - B = a_i + a_j + y - C = a_j + y + 1 - z = (mu - b_j) / (mu + b_i) - s = 0.0 - if z < 0.0: - s = -B * np.log(1 - z) - A = C - A - z = z / (z - 1) - f = _tsdate.hyp2f1_unity(A, B, C, z) + s - check = float(mpmath.log(self._2f1_validate(*pars))) - assert np.isclose(f, check, rtol=1e-2) - - -@pytest.mark.parametrize( - "pars", - [ - [92.301156, 3.338, 0.008172, 0.0, 0.00022691], - [92.301156, 3.678, 0.005831, 0.0, 0.00250921], - [2998.6825, 3.999, 0.000750, 1.0, 0.00098396], - [11985.278, 5.251, 0.000193, 8.0, 1.9537e-05], - [11985.278, 14.46, 0.000822, 3.0, 0.00011632], - [12957.347, 0.999, 9.999e-5, 1.0, 0.00019150], - ], -) -class TestLaplaceApproxU: - """ - Test that Laplace approximation to Tricomi's confluent hypergeometric - function returns reasonable answers - """ - - @staticmethod - def _hyperu_validate(t_j, a_i, b_i, y, mu, offset=1.0): - A = y + 1 - B = a_i + y + 1 - z = t_j * (mu + b_i) - val = mpmath.re(mpmath.hyperu(A, B, z, maxterms=1e6)) - return val / offset - - def test_hyperu(self, pars): - t_j, a_i, b_i, y, mu = pars - A = y + 1 - B = a_i + y + 1 - z = t_j * (mu + b_i) - f, df = _tsdate.hyperu_laplace(A, B, z) - der = nd.Derivative(lambda z: _tsdate.hyperu_laplace(A, B, z)[0], n=1, step=1e-4) - check_f = float(mpmath.log(self._hyperu_validate(*pars))) - check_df = der(z) - assert np.isclose(f, check_f, rtol=2e-2) - assert np.isclose(df, check_df, rtol=2e-2) - - -@pytest.mark.parametrize( - "pars", - [ - [25128.46, 132.48, 0.006849, 0.0, 4.4562e-05], - [15900.89, 997.09, 0.093978, 1.0, 0.00010288], - [10062.80, 978.24, 0.102753, 0.0, 0.00022747], - [11659.45, 713.52, 0.064035, 8.0, 0.00064625], - [40888.01, 999.99, 0.071372, 3.0, 3.7925e-05], - [11659.45, 989.08, 0.096664, 2.0, 0.00010425], - [22333.94, 28.546, 0.001817, 0.0, 9.6225e-05], - [30613.25, 30.956, 0.000942, 0.0, 1.1250e-07], - ], -) -class TestLaplaceApproxM: - """ - Test that Laplace approximation to Kummer's confluent hypergeometric - function returns reasonable answers - """ - - @staticmethod - def _hyp1f1_validate(t_i, a_j, b_j, y, mu, offset=1.0): - A = a_j - B = a_j + y + 1 - z = t_i * (b_j - mu) - val = mpmath.re(mpmath.hyp1f1(A, B, z, maxterms=1e6)) - return val / offset - - def test_hyp1f1(self, pars): - t_i, a_j, b_j, y, mu = pars - A = a_j - B = a_j + y + 1 - z = t_i * (b_j - mu) - f = _tsdate.hyp1f1_laplace(A, B, z) - check = float(mpmath.log(self._hyp1f1_validate(*pars))) - assert np.isclose(f, check, rtol=2e-2) diff --git a/tests/test_oracle_approx.py b/tests/test_oracle_approx.py deleted file mode 100644 index e96c4170..00000000 --- a/tests/test_oracle_approx.py +++ /dev/null @@ -1,821 +0,0 @@ -""" -Parity of the gamma approximations of ``_tsdate`` with their oracles in -``oracle/approx.py``: exact values (including NaNs and infinities), and which -exception is raised. Expected values always come from the oracle. Tables hold -deliberate edge cases (boundaries of the ``valid_*`` checks, degenerate gamma fits, -regimes of the moment and projection functions); seeded random draws cover ranges -typical of expectation propagation (EP) and extreme ones. - -Conventions pinned here: a NaN result (not an exception) signals a -parameter outside the valid region of the hypergeometric function; the ``*_projection`` -functions then return NaN and, except for the ``mutation_*`` ones, their input -parameters unchanged; errors are those of the library, as error codes (a violated -precondition such as a fixed node age that is not positive or a Laplace root on the -boundary, or a failed gamma fit), with ``ZeroDivisionError`` in the oracle for the -library's float division by zero. Accuracy of the approximations is measured in -``evaluation/numerical_accuracy.py``. -""" - -import math - -import _tsdate -import numpy as np -import pytest -import scipy.special -from oracle import approx -from oracle.errors import ( - INVALID_HYPERGEO, - JENSEN_VIOLATION, - NEGATIVE_SHAPE, - NONPOSITIVE_CENTRAL_MOMENTS, - NONPOSITIVE_MOMENTS, - NONPOSITIVE_OR_NONFINITE_MOMENTS, - UNSORTED_QUANTILES, -) -from oracle.helpers import ( - INF, - NAN, - assert_outcome, - compare, - kind, - log_uniform, - outcome, -) - -nextafter = np.nextafter -MAX = np.finfo(np.float64).max -TINY = 5e-324 - - -def parity(name, args, expected_kind=None): - """ - Compare ``_tsdate.`` with the oracle ``approx.`` on ``args`` - (returning the oracle's outcome); optionally check its kind. - """ - func = getattr(_tsdate, name) - oracle = getattr(approx, name) - if expected_kind is None: - return compare(func, oracle, *args) - return assert_outcome(func, oracle, args, expected_kind) - - -def table(name, rows): - """ - ``pytest.param`` rows of ``(name, args, expected_kind)`` with readable ids - """ - return [pytest.param(name, args, kind, id=f"{name}{args}") for args, kind in rows] - - -def floats(args): - return tuple(float(a) for a in args) - - -def natural(shape, rate): - """ - Natural parameters of a gamma - """ - return shape - 1.0, rate - - -def gamma_quantiles(shape, rate, q1=0.25, q2=0.75): - x1, x2 = scipy.special.gammaincinv(shape, [q1, q2]) / rate - return q1, q2, float(x1), float(x2) - - -# --- validity checks --- # - -MOMENTS_VALID = [ - ((1.0, 1.0), True), - ((TINY, TINY), True), # just inside - ((MAX, MAX), True), - ((0.0, 1.0), False), # at the boundary - ((1.0, 0.0), False), - ((-0.0, 1.0), False), - ((1.0, -0.0), False), - ((nextafter(0.0, 1.0), 1.0), True), - ((1.0, nextafter(0.0, 1.0)), True), - ((nextafter(0.0, -1.0), 1.0), False), # just outside - ((1.0, nextafter(0.0, -1.0)), False), - ((-1.0, 1.0), False), - ((1.0, -1.0), False), - ((INF, 1.0), False), - ((1.0, INF), False), - ((-INF, 1.0), False), - ((NAN, 1.0), False), - ((1.0, NAN), False), -] - -HYP1F1 = [ - ((1.0, 1.0, 0.0), True), # b == a is allowed - ((1.0, nextafter(1.0, 0.0), 0.0), False), # b just below a - ((1.0, nextafter(1.0, 2.0), 0.0), True), - ((TINY, 1.0, 0.0), True), # a just above zero - ((0.0, 1.0, 0.0), False), - ((-0.0, 1.0, 0.0), False), - ((nextafter(0.0, -1.0), 1.0, 0.0), False), - ((1.0, 2.0, 1e300), True), # z may have any sign and size - ((1.0, 2.0, -1e300), True), - ((1.0, 2.0, TINY), True), - ((1.0, 2.0, INF), False), - ((1.0, 2.0, -INF), False), - ((1.0, 2.0, NAN), False), - ((NAN, 2.0, 0.0), False), - ((1.0, NAN, 0.0), False), - ((INF, INF, 0.0), False), - ((1.0, INF, 0.0), False), - ((MAX, MAX, 0.0), True), -] - -HYPERU = [ - ((1.0, 1.0, 1.0), False), # b == a is not allowed here (unlike hyp1f1) - ((1.0, nextafter(1.0, 2.0), 1.0), True), - ((1.0, nextafter(1.0, 0.0), 1.0), False), - ((TINY, 1.0, 1.0), True), - ((0.0, 1.0, 1.0), False), - ((-0.0, 1.0, 1.0), False), - ((1.0, 2.0, 0.0), False), # z == 0 - ((1.0, 2.0, -0.0), False), - ((1.0, 2.0, TINY), True), # z just above zero - ((1.0, 2.0, nextafter(0.0, -1.0)), False), - ((1.0, 2.0, -1.0), False), - ((1.0, 2.0, 1e300), True), - ((1.0, 2.0, INF), False), - ((1.0, 2.0, NAN), False), - ((NAN, 2.0, 1.0), False), - ((1.0, INF, 1.0), False), - ((INF, INF, 1.0), False), -] - - -def z_below_one(z): - """ - The condition on z: below one, or for z < 0 that ``z / (z - 1)`` is below one - """ - return bool(z / (z - 1) < 1.0 if z < 0.0 else z < 1.0) - - -def hyp2f1_rows(): - """ - ``(args, expected)`` for ``valid_hyp2f1``: a, b, c positive and finite, z < 1 - """ - rows = [((1.0, 1.0, 1.0, 0.0), True), ((10.0, 1.0, 1.0, 0.5), True)] # a > c is ok - for i in range(3): - for z in [0.5, -0.0]: - for bad, valid in [(0.0, False), (-0.0, False), (TINY, True)]: - abc = [1.0, 1.0, 1.0] - abc[i] = bad - rows.append(((*abc, z), valid)) - for bad in [INF, NAN, -TINY]: - abc = [1.0, 1.0, 1.0] - abc[i] = bad - rows.append(((*abc, 0.5), False)) - zs = [0.0, -0.0, TINY, 0.5, 1 - 2.0**-53, 1.0, 1 + 2.0**-52, 2.0] - zs += [NAN, INF, -INF, -1.0, -1e15] - rows += [((1.0, 2.0, 3.0, z), z_below_one(z)) for z in zs] - # NOTE: current behaviour, possibly a bug: for z < 0 the check - # z / (z - 1) < 1 fails once z - 1 rounds to z, and between -2**53 and -2**54 it - # alternates with the last bit of z - big = 2.0**53 - zs = [-(big - 2), -(big - 1), -big, -(big + 2), -(big + 4), -(big + 6), -9e15] - zs += [-(2 * big - 2), -2 * big, -(2 * big + 4), -1e17, -1e300, -MAX] - return rows + [((1.0, 2.0, 3.0, z), z_below_one(z)) for z in zs] - - -VALID = ( - [(n, args, v) for n in ["valid_moments", "valid_gamma"] for args, v in MOMENTS_VALID] - + [("valid_hyp1f1", args, v) for args, v in HYP1F1] - + [("valid_hyperu", args, v) for args, v in HYPERU] - + [("valid_hyp2f1", args, v) for args, v in hyp2f1_rows()] -) - - -class TestValidChecks: - """ - Boundaries of the ``valid_*`` checks, at and either side. Each of them is the - gate that turns unusable moments or hypergeometric parameters into NaN. - """ - - @pytest.mark.parametrize( - ("name", "args", "expected"), - [pytest.param(*row, id=f"{row[0]}{row[1]}") for row in VALID], - ) - def test_valid(self, name, args, expected): - result = parity(name, args) - assert result.value == float(expected) - - -# --- gamma approximations --- # - -LOG_MOMENTS = [ - ((1.0, 1.0), "finite"), - ((1e300, 1e300), "finite"), - ((1e-100, 1e-100), "finite"), - ((0.0, 1.0), NONPOSITIVE_MOMENTS), - ((1.0, 0.0), NONPOSITIVE_MOMENTS), - ((-1.0, 1.0), NONPOSITIVE_MOMENTS), - ((1.0, -1.0), NONPOSITIVE_MOMENTS), - ((NAN, 1.0), NONPOSITIVE_MOMENTS), - ((1.0, NAN), NONPOSITIVE_MOMENTS), - ((INF, 1.0), "nan"), - ((1.0, INF), "nonfinite"), - ((1e-300, 1e-300), ZeroDivisionError), # mean**2 underflows - ((TINY, 1.0), ZeroDivisionError), - ((1e-200, 1.0), ZeroDivisionError), -] - -GAMMA_KL = [ - # (x, logx, expected kind); `gap` = log(x) - logx must be positive (Jensen) - ((1.0, 0.0), JENSEN_VIOLATION), # gap == 0 - ((1.0, nextafter(0.0, -1.0)), "nonfinite"), # smallest gap: alpha, rate overflow - ((1.0, -1e-300), "finite"), - ((1.0, -1e-17), "finite"), - ((1.0, -1e-10), "finite"), - ((1.0, -4e-5), "finite"), - ((1.0, -0.5), "finite"), - ((1.0, -1.0), "finite"), # shape < 1 - ((1.0, -10.0), "finite"), - ((1.0, -1e10), "finite"), - ((1.0, -1e160), "finite"), - ((1.0, -1e164), ZeroDivisionError), # shape bound ~1e-164: trigamma divides by 0 - ((1.0, -1e300), ZeroDivisionError), - ((1.0, -INF), NONPOSITIVE_OR_NONFINITE_MOMENTS), - ((1.0, INF), NONPOSITIVE_OR_NONFINITE_MOMENTS), - ((1.0, NAN), JENSEN_VIOLATION), # not (log x > nan) - ((0.0, -1.0), NONPOSITIVE_OR_NONFINITE_MOMENTS), - ((-1.0, -1.0), NONPOSITIVE_OR_NONFINITE_MOMENTS), - ((-0.0, -1.0), NONPOSITIVE_OR_NONFINITE_MOMENTS), - ((NAN, -1.0), JENSEN_VIOLATION), - ((INF, -1.0), ZeroDivisionError), # alpha = 0.5 / inf = 0 - ((INF, INF), NONPOSITIVE_OR_NONFINITE_MOMENTS), - ((1e-300, -1.0), JENSEN_VIOLATION), # log x = -690 < logx - ((1e-300, -700.0), "finite"), - ((TINY, -745.0), "nonfinite"), # rate = alpha / x overflows - ((1e300, 1.0), "finite"), - ((1e300, 690.0), "finite"), - ((1e308, 709.0), "finite"), - ((2.0, 0.5), "finite"), - ((100.0, math.log(100.0) - 1.0), "finite"), - ((1e5, math.log(1e5) - 0.5e-4), "finite"), - ((1e5, math.log(1e5) - 0.5e-8), "finite"), -] - -GAMMA_MOM = [ - ((1.0, 1.0), "finite"), - ((1.0, 0.0), NONPOSITIVE_CENTRAL_MOMENTS), - ((0.0, 1.0), NONPOSITIVE_CENTRAL_MOMENTS), - ((-0.0, 1.0), NONPOSITIVE_CENTRAL_MOMENTS), - ((-1.0, 1.0), NONPOSITIVE_CENTRAL_MOMENTS), - ((1.0, -1.0), NONPOSITIVE_CENTRAL_MOMENTS), - ((NAN, 1.0), NONPOSITIVE_CENTRAL_MOMENTS), - ((1.0, NAN), NONPOSITIVE_CENTRAL_MOMENTS), - ((TINY, TINY), "finite"), - ((1.0, 1e-300), "finite"), # shape 1e300 - ((1.0, TINY), "nonfinite"), # shape overflows - ((INF, 1.0), "nonfinite"), - ((1.0, INF), "finite"), # shape 0 - 1 - ((INF, INF), "nan"), - # NOTE: current behaviour, possibly a bug: mean**2 underflows, shape -1 - ((1e-200, 1e-200), "finite"), - ((1e200, 1e200), "nonfinite"), # mean**2 overflows - ((1e154, 1.0), "finite"), - ((1.0, 1e300), "finite"), - ((1e8, 1.0), "finite"), - ((1e3, 1e-6), "finite"), -] - - -GAMMA_IQR_ERRORS = [ - ((0.25, 0.75, 2.0, 1.0, 50.0), UNSORTED_QUANTILES), # x unsorted - ((0.75, 0.25, 1.0, 2.0, 50.0), UNSORTED_QUANTILES), # q unsorted - ((0.25, 0.25, 1.0, 2.0, 50.0), UNSORTED_QUANTILES), # q equal - ((0.25, 0.75, 1.0, NAN, 50.0), UNSORTED_QUANTILES), - ((NAN, 0.75, 1.0, 2.0, 50.0), UNSORTED_QUANTILES), - ((0.25, 0.75, 0.0, 1.0, 50.0), ZeroDivisionError), # log(x2 / 0) - ((0.0, 0.75, 1.0, 2.0, 50.0), ZeroDivisionError), # log(q2 / 0) - ((0.25, 0.75, -1.0, 1.0, 50.0), NEGATIVE_SHAPE), - ((0.25, 1.0, 1.0, 2.0, 50.0), NEGATIVE_SHAPE), # q2 == 1: negative shape - ((0.25, 0.75, 1.0, INF, 50.0), INVALID_HYPERGEO), - ((0.25, 0.75, 0.0, 0.0, 50.0), ZeroDivisionError), # x1 == x2 == 0 - # the shape is capped at max_shape when x1 == x2, when the lower bound exceeds it - # or when Newton's iteration ends above it - ((0.25, 0.75, 3.0, 3.0, 50.0), "finite"), - ((0.25, 0.75, 1.0, 1.000001, 1e5), "finite"), - # the gradient vanishes with a high cap: the update divides by zero - ((0.25, 0.75, 1.0, 1.0001, 1e6), ZeroDivisionError), - # NOTE: current behaviour, possibly a bug: max_shape is not validated - ((*gamma_quantiles(2.0, 1.0), 0.0), "nan"), - ((*gamma_quantiles(2.0, 1.0), -1.0), "nan"), - ((*gamma_quantiles(2.0, 1.0), 1.0), "finite"), - ((*gamma_quantiles(2.0, 1.0), INF), "finite"), - # NOTE: current behaviour, possibly a bug: the lower quantile of a - # gamma with tiny shape underflows to zero, so the fit divides by zero - ((*gamma_quantiles(1e-3, 1.0), 50.0), ZeroDivisionError), -] -# shapes below, at and above the cap, and beyond the range where `gammainc_der` uses -# its gaussian approximation (shape > 1e3) -GAMMA_IQR_FITS = [ - (shape, max_shape) - for shape in [0.01, 0.5, 1.0, 10.0, 49.0, 50.0, 51.0, 999.0, 1001.0, 1e4, 1e8] - for max_shape in [10.0, 50.0, 1000.0, 1e5] -] - -AVERAGE_GAMMAS = { - "single": ([1.0], [1.0], "finite"), - "pair": ([0.5, 1.5], [1.0, 1.0], "finite"), - "identical": ([1.0, 1.0], [1.0, 1.0], "finite"), - "tiny shape": ([1e-10], [1.0], "finite"), - "huge shapes": ([1e8, 1e8], [1.0, 1e-3], "finite"), - "mixed shapes": ([0.5, 1e6], [1.0, 1e-3], "finite"), - "wide rates": ([1.0, 2.0], [1e-300, 1e300], "finite"), - "shape+1 near zero": ([-1.0 + 1e-10, 4.0], [1.0, 2.0], "finite"), - "shape+1 zero": ([-1.0], [1.0], ZeroDivisionError), # digamma pole - "shape+1 negative": ([-2.0], [1.0], NONPOSITIVE_OR_NONFINITE_MOMENTS), - "zero rate": ([1.0], [0.0], ZeroDivisionError), - "negative rate": ([1.0], [-1.0], NONPOSITIVE_OR_NONFINITE_MOMENTS), - "nan shape": ([NAN], [1.0], JENSEN_VIOLATION), - "inf shape": ([INF], [1.0], NONPOSITIVE_OR_NONFINITE_MOMENTS), - "empty": ([], [], ZeroDivisionError), - "size mismatch": ([1.0], [1.0, 2.0], ValueError), -} - -GAMMA_DOMAIN = ( - table("approximate_log_moments", LOG_MOMENTS) - + table("approximate_gamma_kl", GAMMA_KL) - + table("approximate_gamma_mom", GAMMA_MOM) - + table("approximate_gamma_iqr", GAMMA_IQR_ERRORS) -) - - -class TestGammaApproximations: - @pytest.mark.parametrize(("name", "args", "expected"), GAMMA_DOMAIN) - def test_domain(self, name, args, expected): - parity(name, args, expected) - - @pytest.mark.parametrize("gap", [1e-17, 1e-10, 4e-5, 4.99e-5, 5e-5, 6e-5, 1e-3]) - def test_kl_asymptotic_threshold(self, gap): - # for alpha > 1e4 (gap < 5e-5) the lower bound alpha = 0.5 / gap is returned - # without iterating; above, Newton's iteration refines it - result = parity("approximate_gamma_kl", (1.0, -gap), "finite") - shape = result.value[0] - if gap < 5e-5: - assert shape + 1.0 == 0.5 / gap - else: - assert shape + 1.0 != 0.5 / gap - - @pytest.mark.parametrize(("shape", "max_shape"), GAMMA_IQR_FITS, ids=repr) - def test_iqr_fits(self, shape, max_shape): - args = (*gamma_quantiles(shape, 0.001), max_shape) - parity("approximate_gamma_iqr", args, "finite") - - -class TestAverageGammas: - @pytest.mark.parametrize("label", list(AVERAGE_GAMMAS)) - def test_cases(self, label): - shapes, rates, expected = AVERAGE_GAMMAS[label] - args = np.array(shapes, dtype=float), np.array(rates, dtype=float) - parity("average_gammas", args, expected) - - -# --- moments and projections --- # - -# regimes for functions of two free nodes: (a_i, b_i, a_j, b_j, y, mu), with the gamma -# shapes a_i, a_j, rates b_i, b_j, mutation count y and rate mu. With t = mu + b_i and -# z = (mu - b_j) / t the hypergeometric argument is z (parent above child) or 1 - z -# (unphased). -TWO_NODE = { - "typical": (10, 0.01, 10, 0.01, 1, 1e-4), - "y=0": (10, 0.01, 10, 0.01, 0, 1e-4), - "y=100": (10, 0.01, 10, 0.01, 100, 1e-3), - "y=1e4": (10, 0.01, 10, 0.01, 1e4, 1e-3), - "mu=1e-12": (10, 0.01, 10, 0.01, 1, 1e-12), - "mu=0": (10, 0.01, 10, 0.01, 0, 0.0), - "mu=1e6": (10, 0.01, 10, 0.01, 1, 1e6), - "shapes=1e4": (1e4, 10, 1e4, 10, 1, 1e-4), - # NOTE: current behaviour, possibly a bug: the variance is a difference - # of the second moment and the squared mean, and goes negative at huge shapes - "shapes=1e8": (1e8, 1e5, 1e8, 1e5, 1, 1e-4), - "shapes=1e-3": (1e-3, 1e-5, 1e-3, 1e-5, 1, 1e-4), - "rates=1e-12": (10, 1e-12, 10, 1e-12, 1, 1e-14), - "rates=1e8": (10, 1e8, 10, 1e8, 1, 1e5), - "t=0": (10, -1e-4, 10, 0.01, 1, 1e-4), - "t<0": (10, -1e-3, 10, 0.01, 1, 1e-4), - "t=1e-20": (10, nextafter(-1e-4, 0.0), 10, 0.01, 1, 1e-4), - "z=1": (10, 0.01, 10, -0.01, 1, 1e-4), - "z=1-1e-10": (10, 0.01, 10, -0.01 + 1e-12, 1, 1e-4), - "z>1": (10, 0.01, 10, -0.02, 1, 1e-4), - "z=0": (10, 0.01, 10, 1e-4, 1, 1e-4), - "z=-1e9": (10, 0.01, 10, 1e9, 1, 1e-4), - "z=-1e5": (10, 0.01, 10, 1e3, 1, 1e-4), - "a_j=0": (10, 0.01, 0, 0.01, 1, 1e-4), - "a_j=1e-8": (10, 0.01, 1e-8, 0.01, 1, 1e-4), - "a_i=1e8, a_j=1": (1e8, 0.01, 1, 0.01, 1, 1e-4), - "b_j<0 (damped)": (10, 0.01, 10, -0.005, 1, 1e-4), - "b_j=inf": (10, 0.01, 10, INF, 1, 1e-4), -} - -# regimes for a fixed node and one free node: (t, a, b, y, mu) with the free node's -# shape a, rate b; t is the fixed age (child for rootward, parent otherwise). -ONE_NODE = { - "typical": (1000, 10, 0.01, 1, 1e-4), - "y=0": (1000, 10, 0.01, 0, 1e-4), - "y=1e4": (1000, 10, 0.01, 1e4, 1e-3), - "t=1e-10": (1e-10, 10, 0.01, 1, 1e-4), - "t=5e-324": (TINY, 10, 0.01, 1, 1e-4), - "t=1e10": (1e10, 10, 0.01, 1, 1e-4), - "t=0": (0.0, 10, 0.01, 1, 1e-4), - "t=-0": (-0.0, 10, 0.01, 1, 1e-4), - "t<0": (-1.0, 10, 0.01, 1, 1e-4), - "t=nan": (NAN, 10, 0.01, 1, 1e-4), - "t=inf": (INF, 10, 0.01, 1, 1e-4), - "mu=1e-14": (1000, 10, 0.01, 1, 1e-14), - "mu=1e5": (1000, 10, 0.01, 1, 1e5), - "mu=0": (1000, 10, 0.01, 0, 0.0), - "shapes=1e4": (1000, 1e4, 10, 1, 1e-4), - "shapes=1e8": (1000, 1e8, 1e5, 1, 1e-4), - "shapes=1e-3": (1000, 1e-3, 1e-5, 1, 1e-4), - "rates=1e-12": (1000, 10, 1e-12, 1, 1e-14), - "rates=1e8": (1e-5, 10, 1e8, 1, 1e5), - "rate+mu=0": (1000, 10, -1e-4, 1, 1e-4), - "rate+mu<0": (1000, 10, -1e-3, 1, 1e-4), - "rate<0, rate+mu>0": (1000, 10, -5e-5, 1, 1e-4), - "a=0": (1000, 0, 0.01, 1, 1e-4), - "a<0": (1000, -1, 0.01, 1, 1e-4), - # NOTE: current behaviour, possibly a bug: y = -1 passes - # `valid_hyp1f1` (b == a) but `hyp1f1_laplace` asserts b > a - "y=-1": (1000, 10, 0.01, -1, 1e-4), - "y=-0.5": (1000, 10, 0.01, -0.5, 1e-4), -} - -# (a_i, b_i, y, mu): a node above both edges of an unphased individual -TWIN = { - "typical": (10, 0.01, 1, 1e-4), - "y=0": (10, 0.01, 0, 1e-4), - "mu=0": (10, 0.01, 0, 0.0), - "shapes=1e8": (1e8, 1e5, 1, 1e-4), - "shapes=1e-3": (1e-3, 1e-5, 1, 1e-4), - "rates=1e-12": (10, 1e-12, 1, 1e-14), - "rates=1e8": (10, 1e8, 1, 1e5), - "r=0": (10, -2e-4, 1, 1e-4), # r = b_i + 2 mu - "r<0": (10, -1e-3, 1, 1e-4), - "r=1e-300": (10, 1e-300, 1, 0.0), - "s=0": (0, 0.01, 0, 1e-4), # s = a_i + y - "s<0": (-1, 0.01, 0, 1e-4), - "a_i=nan": (NAN, 0.01, 1, 1e-4), - "a_i=inf": (INF, 0.01, 1, 1e-4), - "y=1e300": (10, 0.01, 1e300, 1e-4), - "mu=1e300": (10, 0.01, 1, 1e300), -} - -# (t_i, t_j): fixed parent and child ages -TIMES = { - "3,1": (3, 1), - "1,3 (child older)": (1, 3), - # NOTE: current behaviour, possibly a bug: equal ages give zero variance, so the - # edge projection is NaN, but inverted ages (1,3) give a valid result - "equal": (1, 1), - "0,0": (0, 0), - "0,1": (0, 1), - "1,0": (1, 0), - "-0,1": (-0.0, 1), - # NOTE: current behaviour, possibly a bug: edge moments do not check the ages - "neg,1": (-1, 1), - "1,neg": (1, -1), - "1e200,1e-200": (1e200, 1e-200), - "1e300,1": (1e300, 1), - "1e308,1e307": (1e308, 1e307), - "1e-200,1e-210": (1e-200, 1e-210), - "1e-160,1e-170": (1e-160, 1e-170), - "5e-324,5e-324": (TINY, TINY), - "1,1-eps": (1.0, nextafter(1.0, 0.0)), - "nan,1": (NAN, 1), - "inf,1": (INF, 1), - "inf,inf": (INF, INF), -} - - -TWO_NODE_MOMENTS = ["moments", "unphased_moments", "mutation_moments"] -TWO_NODE_MOMENTS += ["mutation_unphased_moments"] -ONE_NODE_MOMENTS = ["rootward_moments", "mutation_rootward_moments", "leafward_moments"] -ONE_NODE_MOMENTS += ["mutation_leafward_moments", "sideways_moments"] -ONE_NODE_MOMENTS += ["mutation_sideways_moments"] -TWIN_MOMENTS = ["twin_moments", "mutation_twin_moments"] -TIMES_MOMENTS = ["mutation_edge_moments", "mutation_block_moments"] - -# the regimes (inputs of the moment function) in which each moment function is called -REGIMES = { - **{name: TWO_NODE for name in TWO_NODE_MOMENTS}, - **{name: ONE_NODE for name in ONE_NODE_MOMENTS}, - **{name: TWIN for name in TWIN_MOMENTS}, - **{name: TIMES for name in TIMES_MOMENTS}, -} - -# For each projection: the moment function it wraps and the checks it applies to the -# moments before fitting a gamma. `pairs` indexes (mean, variance) in the result of -# the moment function; `prob` indexes a probability that must lie in [0, 1]. -PROJECTIONS = { - "gamma_projection": ("moments", [(1, 2), (3, 4)], None), - "unphased_projection": ("unphased_moments", [(1, 2), (3, 4)], None), - "rootward_projection": ("rootward_moments", [(1, 2)], None), - "leafward_projection": ("leafward_moments", [(1, 2)], None), - "sideways_projection": ("sideways_moments", [(1, 2)], None), - "twin_projection": ("twin_moments", [(1, 2)], None), - "mutation_gamma_projection": ("mutation_moments", [(0, 1)], None), - "mutation_rootward_projection": ("mutation_rootward_moments", [(0, 1)], None), - "mutation_leafward_projection": ("mutation_leafward_moments", [(0, 1)], None), - "mutation_edge_projection": ("mutation_edge_moments", [(0, 1)], None), - "mutation_unphased_projection": ("mutation_unphased_moments", [(1, 2)], 0), - "mutation_sideways_projection": ("mutation_sideways_moments", [(1, 2)], 0), - "mutation_twin_projection": ("mutation_twin_moments", [(1, 2)], 0), - "mutation_block_projection": ("mutation_block_moments", [(1, 2)], 0), -} -# projections that return their input parameters unchanged when the moments are invalid -RETURNS_INPUT = { - "gamma_projection", - "unphased_projection", - "rootward_projection", - "leafward_projection", - "sideways_projection", - "twin_projection", -} - - -def projection_args(name, args): - """ - Arguments of a projection from the arguments of the moment function it wraps - (shapes, not natural parameters). - """ - moments = PROJECTIONS[name][0] - if moments in TWO_NODE_MOMENTS: - a_i, b_i, a_j, b_j, y, mu = args - return (*natural(a_i, b_i), *natural(a_j, b_j), y, mu) - if moments in TWIN_MOMENTS: - a_i, b_i, y, mu = args - return (*natural(a_i, b_i), y, mu) - if moments in TIMES_MOMENTS: - return tuple(args) - t, a, b, y, mu = args - return (t, *natural(a, b), y, mu) - - -def moment_args(name, proj_args): - """ - The arguments the projection passes to its moment function: shapes are recovered - from the natural parameters, so tiny shapes differ from the original by rounding. - """ - moments = PROJECTIONS[name][0] - if moments in TWO_NODE_MOMENTS: - alpha_i, beta_i, alpha_j, beta_j, y, mu = proj_args - return alpha_i + 1, beta_i, alpha_j + 1, beta_j, y, mu - if moments in TWIN_MOMENTS: - alpha_i, beta_i, y, mu = proj_args - return alpha_i + 1, beta_i, y, mu - if moments in TIMES_MOMENTS: - return proj_args - t, alpha, beta, y, mu = proj_args - return t, alpha + 1, beta, y, mu - - -def natural_args(name, proj_args): - """ - The natural parameters among the arguments of a projection - """ - moments = PROJECTIONS[name][0] - if moments in ONE_NODE_MOMENTS: - return proj_args[1:-2] - return proj_args[:-2] - - -def is_valid(mean, variance, prob=None): - if prob is not None and not (0 <= prob <= 1): - return False - return bool(np.isfinite(mean) and np.isfinite(variance) and mean > 0 and variance > 0) - - -def check_projection(name, args): - """ - Compare a projection with the oracle, and check the contract on the oracle's - result: the projection raises as its moment function does; otherwise it is NaN - exactly when the moments are unusable (non-finite, non-positive, or a probability - outside [0, 1]), and on NaN the non-mutation projections return the input - parameters unchanged and the mutation ones NaN. - """ - moments, pairs, prob_index = PROJECTIONS[name] - proj_args = projection_args(name, args) - result = parity(name, proj_args) - moment_result = outcome(getattr(approx, moments), *moment_args(name, proj_args)) - if moment_result.exception is not None: - assert type(result.exception) is type(moment_result.exception) - return - values = moment_result.value - prob = values[prob_index] if prob_index is not None else None - expected_nan = not all(is_valid(values[i], values[j], prob) for i, j in pairs) - assert kind(result) != "nan" or expected_nan - if not expected_nan: - assert not np.isnan(result.value[0]) - return - assert np.isnan(result.value[0]) - if name in RETURNS_INPUT: - given = natural_args(name, proj_args) - np.testing.assert_array_equal(result.value[1:], given) - else: - assert np.isnan(result.value[1:]).all() - - -MOMENT_REGIMES = [ - pytest.param(name, label, id=f"{name}-{label}") - for name, regimes in REGIMES.items() - for label in regimes -] -PROJECTION_REGIMES = [ - pytest.param(name, label, id=f"{name}-{label}") - for name, (moments, _, _) in PROJECTIONS.items() - for label in REGIMES[moments] -] - - -class TestMoments: - @pytest.mark.parametrize(("name", "label"), MOMENT_REGIMES) - def test_regimes(self, name, label): - parity(name, floats(REGIMES[name][label])) - - -class TestProjections: - @pytest.mark.parametrize(("name", "label"), PROJECTION_REGIMES) - def test_regimes(self, name, label): - moments = PROJECTIONS[name][0] - check_projection(name, floats(REGIMES[moments][label])) - - def test_unphased_probability_out_of_range(self): - # NOTE: current behaviour, possibly a bug: the Laplace - # approximation can give a probability above one for finite mean and variance, - # which the projection turns into NaN - args = ( - 1289.8261024396659, - 2.1161296052067344, - 0.15552864791315738, - 0.0007984796762152916, - 1.0, - 4.811169071413665e-07, - ) - parity("mutation_unphased_moments", args, "finite") - name = "mutation_unphased_projection" - parity(name, projection_args(name, args), "nan") - - -# --- seeded random draws --- # - - -def flip_sign(rng, values, prob=0.12): - """ - Negate one of ``values`` with probability ``prob``, to give invalid input. - """ - values = list(values) - if rng.random() < prob: - i = rng.integers(len(values)) - values[i] = -values[i] - return values - - -def draw_gamma(rng): - """ - Shape and rate of a node age - """ - return float(rng.uniform(0.5, 30)), log_uniform(rng, -5, -2) - - -def draw_edge(rng): - """ - Mutation count and mutational target size on an edge - """ - return float(rng.integers(0, 12)), log_uniform(rng, -4, -2) - - -def draw_two_node(rng, extreme): - if extreme: - a_i, b_i, a_j, b_j = (log_uniform(rng, -8, 8) for _ in range(4)) - b_i *= float(rng.choice([-1.0, 1.0, 1.0, 1.0])) - b_j *= float(rng.choice([-1.0, 1.0, 1.0, 1.0])) - y = float(rng.choice([0, 0, 1, 2, 5, 100, 1e4])) - return a_i, b_i, a_j, b_j, y, log_uniform(rng, -12, 3) - a_i, b_i = draw_gamma(rng) - a_j, b_j = draw_gamma(rng) - y, mu = draw_edge(rng) - return (*flip_sign(rng, [a_i, b_i, a_j, b_j]), y, mu) - - -def draw_one_node(rng, extreme): - t = 0.0 if rng.random() < (0.15 if extreme else 0.1) else None - if extreme: - t = log_uniform(rng, -6, 8) if t is None else t - a, b = log_uniform(rng, -8, 8), log_uniform(rng, -8, 8) - b *= float(rng.choice([-1.0, 1.0, 1.0, 1.0])) - y = float(rng.choice([0, 0, 1, 2, 5, 100, 1e4])) - return t, a, b, y, log_uniform(rng, -12, 3) - t = log_uniform(rng, 0, 4) if t is None else t - a, b = flip_sign(rng, draw_gamma(rng)) - return (t, a, b, *draw_edge(rng)) - - -def draw_twin(rng, extreme): - if extreme: - a_i, b_i = log_uniform(rng, -8, 8), log_uniform(rng, -8, 8) - b_i *= float(rng.choice([-1.0, 1.0, 1.0])) - y = float(rng.choice([0, 1, 5, 1e6])) - return a_i, b_i, y, log_uniform(rng, -12, 3) - a_i, b_i = flip_sign(rng, draw_gamma(rng)) - return (a_i, b_i, *draw_edge(rng)) - - -def draw_times(rng, extreme): - lo, hi = (-6, 8) if extreme else (0, 4) - return log_uniform(rng, lo, hi), log_uniform(rng, lo, hi) - - -DRAW_GEOMETRY = { - **{name: draw_two_node for name in TWO_NODE_MOMENTS}, - **{name: draw_one_node for name in ONE_NODE_MOMENTS}, - **{name: draw_twin for name in TWIN_MOMENTS}, - **{name: draw_times for name in TIMES_MOMENTS}, -} - - -def draw_log_moments(rng): - mean = log_uniform(rng, -1, 4) - return mean, mean**2 * log_uniform(rng, -3, 0) - - -def draw_gamma_kl(rng): - # log E[x] > E[log x] by Jensen; sometimes violated or nonpositive - x = log_uniform(rng, -2, 4) - gap = log_uniform(rng, -4, 1) - if rng.random() < 0.1: - gap = -gap - return x, float(np.log(x) - gap) - - -def draw_gamma_mom(rng): - mean = log_uniform(rng, -1, 4) - variance = mean**2 * log_uniform(rng, -3, 1) - return tuple(flip_sign(rng, [mean, variance], 0.1)) - - -def draw_gamma_iqr(rng): - # empirical quantiles of a gamma, so that the shape is recoverable - q1, q2, x1, x2 = gamma_quantiles( - log_uniform(rng, -0.5, 2.5), log_uniform(rng, -5, -2) - ) - max_shape = float(rng.choice([50.0, 1000.0])) - u = rng.random() - if u < 0.05: - x2 = x1 # degenerate, capped shape - elif u < 0.1: - x1, x2 = x2, x1 # unsorted - return q1, q2, x1, x2, max_shape - - -def draw_average_gammas(rng): - n = int(rng.integers(1, 8)) - return rng.uniform(0.5, 30, n) - 1, 10.0 ** rng.uniform(-5, -2, n) - - -MODES = ["typical", "extreme"] -DRAW_HELPERS = { - "approximate_log_moments": draw_log_moments, - "approximate_gamma_kl": draw_gamma_kl, - "approximate_gamma_mom": draw_gamma_mom, - "approximate_gamma_iqr": draw_gamma_iqr, - "average_gammas": draw_average_gammas, -} - -DRAWS = [(name, "typical") for name in DRAW_HELPERS] -DRAWS += [(name, mode) for name in [*REGIMES, *PROJECTIONS] for mode in MODES] - - -class TestRandomDraws: - """ - Seeded draws in ranges typical of EP on tree sequences (gamma shapes of order - 1-30, rates of order 1/(node age), mutation counts 0-12 per edge, a fraction with a - sign flipped so that validity checks fail) and over 16 orders of magnitude - ("extreme", where exceptions, NaN and infinity are common). The failing draw is - named in the assertion. - """ - - @pytest.mark.parametrize("seed", [1, 2, 3]) - @pytest.mark.parametrize(("name", "mode"), DRAWS) - def test_random_draws(self, name, mode, seed): - rng = np.random.default_rng(seed) - extreme = mode == "extreme" - for i in range(30): - if name in DRAW_HELPERS: - args = DRAW_HELPERS[name](rng) - check = parity - elif name in PROJECTIONS: - args = DRAW_GEOMETRY[PROJECTIONS[name][0]](rng, extreme) - check = check_projection - else: - args = DRAW_GEOMETRY[name](rng, extreme) - check = parity - try: - check(name, args) - except AssertionError as e: - raise AssertionError(f"draw {i}: {name}{args}: {e}") from None diff --git a/tests/test_oracle_hypergeo.py b/tests/test_oracle_hypergeo.py deleted file mode 100644 index 81db3130..00000000 --- a/tests/test_oracle_hypergeo.py +++ /dev/null @@ -1,669 +0,0 @@ -""" -Parity of the special functions of ``_tsdate`` with their oracles in -``oracle/hypergeo.py``: exact values (including NaNs and infinities), and which -error is raised (``INVALID_HYPERGEO`` for the domain checks, ``ZeroDivisionError`` in -the oracle for the library's float division by zero). Expected values always come -from the oracle. Tables hold deliberate edge cases (poles, domain boundaries, both -sides of a branch switch); grids and seeded random draws cover the interior and extreme -ranges. -Accuracy of the approximations is measured in ``evaluation/numerical_accuracy.py``. -""" - -import math - -import _tsdate -import numpy as np -import pytest -import scipy.special -from oracle import hypergeo -from oracle.errors import INVALID_HYPERGEO -from oracle.helpers import ( - INF, - NAN, - assert_outcome, - compare, - log_uniform, -) - -nextafter = np.nextafter - - -def parity(name, args, expected_kind=None): - """ - Compare ``_tsdate.`` with the oracle ``hypergeo.`` on ``args``; - optionally check the kind. - """ - func = getattr(_tsdate, name) - oracle = getattr(hypergeo, name) - if expected_kind is None: - return compare(func, oracle, *args) - return assert_outcome(func, oracle, args, expected_kind) - - -def table(name, rows): - """ - ``pytest.param`` rows of ``(name, args, expected_kind)`` with readable ids - """ - return [pytest.param(name, args, kind, id=f"{name}{args}") for args, kind in rows] - - -DIGAMMA_POINTS = [ - 5e-324, - 1e-300, - 1e-10, - 1e-6, - 1e-5, - nextafter(1e-5, 1), # series switch - 1e-4, - nextafter(1e-4, 1), # trigamma switch - 1e-3, - 0.1, - 0.5, - 1.0, - 2.0, - 4.9, - 5.0, - 8.4, - 8.5, # asymptotic series switch - nextafter(8.5, 0), - nextafter(8.5, 9), - 10.0, - 100.0, - 1e4, - 1e8, - 1e15, - 1e100, - 1e300, - 1e308, - INF, - NAN, - 0.0, - -0.0, - -1e-300, - -1e-10, - -1e-5, - -0.1, - -0.5, - -1.0, # reflection formula, poles - -2.0, - -1.0 + 1e-8, - -1.0 - 1e-8, - -1.5, - -2.0 + 1e-12, - -3.0 - 1e-6, - -10.5, - -100.3, - -1e5 - 0.5, - -1e10 - 0.5, - -1e15, - -INF, -] - -POLYGAMMA_KINDS = [ - # poles raise (Python float division); digamma(tiny) is -inf rather than raising, - # trigamma raises for x < ~1e-154 where 1 / x**2 divides by an underflowed zero - ((0.0,), ZeroDivisionError), - ((-0.0,), ZeroDivisionError), - ((5e-324,), "nonfinite"), - ((NAN,), "nan"), - ((-INF,), "nan"), - ((INF,), "nonfinite"), -] -TRIGAMMA_KINDS = [ - ((0.0,), ZeroDivisionError), - ((-0.0,), ZeroDivisionError), - ((1e-300,), ZeroDivisionError), - ((-1e-300,), ZeroDivisionError), - ((5e-324,), ZeroDivisionError), - ((NAN,), "nan"), - ((-INF,), "nan"), - ((INF,), "finite"), -] - - -class TestPolygamma: - @pytest.mark.parametrize("name", ["digamma", "trigamma"]) - @pytest.mark.parametrize("x", DIGAMMA_POINTS, ids=repr) - def test_matches_oracle(self, name, x): - parity(name, (x,)) - - @pytest.mark.parametrize( - ("name", "args", "expected"), - table("digamma", POLYGAMMA_KINDS) + table("trigamma", TRIGAMMA_KINDS), - ) - def test_poles_and_nonfinite(self, name, args, expected): - parity(name, args, expected) - - -BETALN_POINTS = [ - (1e-300, 1e-300), - (1e-10, 1e-10), - (1e-10, 1e10), # lgamma cancellation - (1e10, 1e-10), - (1e-5, 1e5), - (1e8, 1e-8), - (1.0, 1.0), - (0.5, 0.5), - (1e5, 1e5), - (1e15, 1e15), - (1e100, 1e100), - (1e300, 1e300), - (1e305, 1e305), - (1e308, 1e308), # lgamma overflows - (1e308, 1.0), - (5e-324, 1.0), - (1e-320, 1.0), - (0.0, 1.0), - (1.0, 0.0), - (-1.0, 2.0), - (-0.5, 2.0), - (NAN, 1.0), - (1.0, INF), - (INF, INF), -] - - -class TestBetaln: - @pytest.mark.parametrize(("p", "q"), BETALN_POINTS, ids=repr) - def test_matches_oracle(self, p, q): - parity("betaln", (p, q)) - - -# `gammainc_der(p, x)`: regimes are x == 0, x > 1e8, p > 1e3 (gaussian), -# x <= 1 or x < p (series) and otherwise a continued fraction. -GAMMAINC_DER_POINTS = [ - (1.0, 0.0), - (1.0, 5e-324), - (1.0, 1e-300), - (1.0, 1.0), - (1.0, nextafter(1.0, 2)), - (0.5, 1.0), - (0.5, nextafter(1.0, 2)), - (2.0, 1.5), - (2.0, 2.0), - (2.0, nextafter(2.0, 3)), - (2.0, nextafter(2.0, 0)), - (5.0, 3.0), - (5.0, 5.0), - (5.0, nextafter(5.0, 6)), - (5.0, 50.0), - (5.0, 1e3), - (5.0, 1e8), - (5.0, nextafter(1e8, 2e8)), - (5.0, 1e8 + 1), - (5.0, INF), - (1e-3, 1e-3), - (1e-3, 1.0), - (1e-3, 10.0), - (1e-10, 1e-10), - (1e-300, 1e-300), - (100.0, 100.0), - (100.0, 300.0), - (999.9, 1000.0), - (1000.0, 1000.0), - (nextafter(1000.0, 0), 1000.0), - (nextafter(1000.0, 2000), 1000.0), - (1000.5, 900.0), - (1000.5, 1100.0), - (2000.0, 2000.0), - (2000.0, 2300.0), - (2000.0, 0.0), - (2000.0, 1.0), - (1e5, 1e5), - (1e5, 1.01e5), - (1e7, 1e7), - (1e12, 1e12), - (1e300, 1.0), - (1e300, 1e300), - (INF, 1.0), - (10.0, 1e-30), - (10.0, 0.5), - (1.0, 1e-30), - (50.0, 1e-3), -] - -GAMMAINC_DER_DOMAIN = [ - ((-1.0, 1.0), INVALID_HYPERGEO), - ((0.0, 1.0), INVALID_HYPERGEO), - ((-0.0, 1.0), INVALID_HYPERGEO), - ((1.0, -1.0), INVALID_HYPERGEO), - ((1.0, -5e-324), INVALID_HYPERGEO), - ((NAN, 1.0), INVALID_HYPERGEO), - ((1.0, NAN), INVALID_HYPERGEO), -] - - -class TestGammaincDer: - @pytest.mark.parametrize(("p", "x"), GAMMAINC_DER_POINTS, ids=repr) - def test_matches_oracle(self, p, x): - parity("gammainc_der", (p, x)) - - @pytest.mark.parametrize( - ("name", "args", "expected"), table("gammainc_der", GAMMAINC_DER_DOMAIN) - ) - def test_domain(self, name, args, expected): - parity(name, args, expected) - - -GAMMAINC_INV_EDGES = [ - # the gamma function's recurrence lands on 2 exactly - (nextafter(1.0, 0), 0.5), - # the series of igamc for small arguments, and a Newton step where the ratio of the - # derivatives overflows, in the complemented inversion - (0.0018725572425875394, 0.93432222410629528), - (1.4851015014453666e-07, 0.99989259056538193), - # a subnormal shape: cephes log1p in log1pmx (complemented inversion), and a NaN - # Halley iterate reaching igam - (9.9999999999999694e-311, 0.95988221384026817), - (9.9999999999999694e-311, 0.56112084484672486), - # the Taylor series of lgam1p at zero - (1.0, 0.64358723829337949), - # erfc of a negative argument in the asymptotic series - (1.3693230946091463e32, 0.84677972577643534), -] - - -def gammainc_inv_grid(): - shapes = [1e-300, 1e-100, 1e-10, 1e-3, 0.1, 0.5, 1.0, 2.0, 10.0, 100.0] - shapes += [1e3, 1e4, 1e5, 1e6, 1e8, 1e10, 1e15, 1e300, INF, 0.0, -1.0, NAN] - quantiles = [0.0, 5e-324, 1e-300, 1e-100, 1e-20, 1e-10, 1e-3, 0.5, 0.999] - quantiles += [1 - 1e-10, nextafter(1.0, 0), 1.0, nextafter(1.0, 2), -0.1, NAN] - grid = [(a, q) for a in shapes for q in quantiles] - return grid + GAMMAINC_INV_EDGES - - -def gammainc_inv_random(): - rng = np.random.default_rng(5) - n = 1000 - specials = [0.0, 5e-324, 1e-300, nextafter(1.0, 0), 1.0, -0.1, 1.1, NAN] - invalid_shapes = [0.0, -0.0, -1e-3, -0.5, -1.0, -1.5, -40.5, -INF, INF, NAN] - shapes = [ - log_uniform(rng, -3, 5, 2 * n), - log_uniform(rng, -3, 5, n), - log_uniform(rng, -3, 5, n // 2), - log_uniform(rng, -3, 5, n // 4), - rng.choice(invalid_shapes, n // 4), - ] - quantiles = [ - rng.uniform(0, 1, 2 * n), - log_uniform(rng, -300, 0, n), - 1 - log_uniform(rng, -16, -1, n // 2), - rng.choice(specials, n // 4), - rng.uniform(-0.5, 1.5, n // 4), - ] - return np.concatenate(shapes), np.concatenate(quantiles) - - -def scipy_gammaincinv(a, q): - """ - scipy.special.gammaincinv inside the domain of the C library's port (0 < a < inf, - 0 <= q <= 1, with q = 0 and q = 1 giving 0 and inf for any a >= 0); NaN outside it - """ - if not (a >= 0 and 0 <= q <= 1): - return math.nan - if q == 0: - return 0.0 - if q == 1: - return math.inf - if a == 0 or math.isinf(a): - return math.nan - return float(scipy.special.gammaincinv(a, q)) - - -def assert_matches_scipy(actual, desired): - """ - SciPy's result depends on its build: wheels that fuse multiply-adds (arm64 macOS) - or use another libm (SciPy 1.17 on Windows) differ from the port by up to about - 1e-12 relative, more for tiny shapes, where the inverse amplifies errors by about - 1 / a. The port agrees bit for bit with SciPy 1.18 on x86-64 Linux. - """ - np.testing.assert_allclose(actual, desired, rtol=1e-10, atol=0, equal_nan=True) - - -class TestGammaincInv: - """ - The C library's gammaincinv is a port of SciPy's (cephes ``igami``): compared with - ``scipy.special.gammaincinv`` inside the domain, including its edges, and NaN - outside it. - """ - - @pytest.mark.parametrize(("a", "q"), gammainc_inv_grid(), ids=repr) - def test_matches_scipy(self, a, q): - assert_matches_scipy(_tsdate.gammainc_inv(a, q), scipy_gammaincinv(a, q)) - - def test_matches_scipy_random(self): - """ - Seeded draws of log-uniform shapes with quantiles that are uniform, tiny, close - to one (the complemented inversion), special values or outside [0, 1], and of - shapes outside the domain. - """ - shapes, quantiles = gammainc_inv_random() - actual = [_tsdate.gammainc_inv(a, q) for a, q in zip(shapes, quantiles)] - desired = [scipy_gammaincinv(a, q) for a, q in zip(shapes, quantiles)] - assert_matches_scipy(np.array(actual), np.array(desired)) - - -HYPERU_DOMAIN = [ - ((1.0, 1.0, 1.0), "finite"), # b == a is allowed - ((1.0, nextafter(1.0, 0), 1.0), INVALID_HYPERGEO), # b < a - ((0.0, 1.0, 1.0), INVALID_HYPERGEO), - ((-0.0, 1.0, 1.0), INVALID_HYPERGEO), - ((-1.0, 1.0, 1.0), INVALID_HYPERGEO), - ((5e-324, 1.0, 1.0), "finite"), - ((1.0, 2.0, 0.0), INVALID_HYPERGEO), - ((1.0, 2.0, -0.0), INVALID_HYPERGEO), - ((1.0, 2.0, -1.0), INVALID_HYPERGEO), - ((1.0, 2.0, 1.0), "finite"), - ((NAN, 2.0, 1.0), INVALID_HYPERGEO), - ((1.0, NAN, 1.0), INVALID_HYPERGEO), - ((1.0, 2.0, NAN), INVALID_HYPERGEO), - ((INF, INF, 1.0), "nan"), - ((1.0, INF, 1.0), "nan"), - # the Laplace root divides by zero when the square root equals t in floating point - ((1.0, 2.0, INF), ZeroDivisionError), - ((1.0, 2.0, 1e300), ZeroDivisionError), - ((1.0, 2.0, 1e-300), ZeroDivisionError), - ((1.0, 2.0, 5e-324), ZeroDivisionError), - ((1e300, 1e300, 1.0), ZeroDivisionError), - ((1.0, 1e10, 1e-3), ZeroDivisionError), - ((3.6072737850966632e-06, 87694833.655647, 0.10794027431688721), ZeroDivisionError), - # NOTE: current behaviour, possibly a bug: U(1, 1, x) is finite for - # small x but the approximation overflows - ((1.0, 1.0, 1e-300), "nonfinite"), -] - -HYP1F1_DOMAIN = [ - ((1.0, 2.0, 0.0), "finite"), - ((1.0, 2.0, -0.0), "finite"), - # NOTE: current behaviour, possibly a bug: b == a is allowed by `valid_hyp1f1` - # (in approx) but asserted against here - ((1.0, 1.0, 1.0), INVALID_HYPERGEO), - ((1.0, 0.5, 1.0), INVALID_HYPERGEO), - ((0.0, 1.0, 1.0), INVALID_HYPERGEO), - ((0.0, 1.0, 0.0), INVALID_HYPERGEO), # asserted before the x == 0 shortcut - ((-1.0, 1.0, 0.0), INVALID_HYPERGEO), - ((NAN, 2.0, 1.0), INVALID_HYPERGEO), - ((1.0, NAN, 1.0), INVALID_HYPERGEO), - ((5e-324, 1.0, 0.0), "finite"), - ((1.0, nextafter(1.0, 2), 1.0), "nonfinite"), - ((1.0, 2.0, NAN), "nan"), - ((1.0, 2.0, INF), "nan"), - ((1.0, 2.0, -INF), "nan"), - ((1.0, 2.0, 5e-324), "finite"), - ((1.0, 2.0, 1e-300), "finite"), - # NOTE: current behaviour, possibly a bug: -inf for very large x - ((1.0, 2.0, 1e300), "nonfinite"), - ((1.0, 2.0, -1e300), "nonfinite"), - ((1.0, 2.0, 1e15), "nonfinite"), - ((1e300, 2e300, 1.0), "nonfinite"), - ((1.0, 1e300, 1.0), "nonfinite"), - ((1e-300, 1.0, 1.0), "finite"), - ((1e-10, 2e-10, 1e8), ZeroDivisionError), -] - -HYP2F1_DOMAIN = [ - ((1.0, 2.0, 3.0, 0.5), "finite"), - ((2.0, 1.0, 3.0, 0.5), "finite"), - ((1.0, 2.0, 2.0, 0.5), "finite"), # c == b - ((1.0, 0.5, 1.5, 0.5), "finite"), - ((0.0, 1.0, 1.0, 0.0), "finite"), # z == 0 is checked after the assertions - ((1.0, 2.0, 3.0, -0.0), "finite"), - ((0.0, 1.0, 1.0, 0.5), INVALID_HYPERGEO), # a = 0: root on boundary - ((0.0, 1.0, 1.0, -0.5), INVALID_HYPERGEO), - ((0.0, 0.0, 1.0, 0.5), INVALID_HYPERGEO), - ((1.0, 0.0, 1.0, 0.5), INVALID_HYPERGEO), # b = 0, c = a - ((1.0, 0.0, 2.0, 0.5), "finite"), # b = 0 is fine when c > a - ((1.0, 2.0, 1.0, 0.5), INVALID_HYPERGEO), # c == a: root on boundary - ((1.0, 1.0, 1.0, 0.5), INVALID_HYPERGEO), - ((1.0, 2.0, nextafter(1.0, 0), 0.5), INVALID_HYPERGEO), # c < a - ((1.0, 2.0, 0.0, 0.5), INVALID_HYPERGEO), - ((1.0, 2.0, -1.0, 0.5), INVALID_HYPERGEO), - ((-1.0, 2.0, 3.0, 0.5), INVALID_HYPERGEO), # a < 0 - ((1.0, -1.0, 3.0, 0.5), INVALID_HYPERGEO), # b < 0 - ((1.0, 2.0, 3.0, 1.0), INVALID_HYPERGEO), # z >= 1 - ((1.0, 2.0, 3.0, nextafter(1.0, 2)), INVALID_HYPERGEO), - ((1.0, 2.0, 3.0, 1.5), INVALID_HYPERGEO), - ((1.0, 2.0, 3.0, nextafter(1.0, 0)), "finite"), - ((1.0, 2.0, 3.0, NAN), INVALID_HYPERGEO), - ((NAN, 2.0, 3.0, 0.5), INVALID_HYPERGEO), - ((1.0, 2.0, 3.0, -INF), INVALID_HYPERGEO), - ((1.0, 2.0, 3.0, -1e300), INVALID_HYPERGEO), # z / (z - 1) rounds to 1.0 - ((1.0, 2.0, 3.0, -1e16), INVALID_HYPERGEO), - ((1.0, 2.0, 3.0, -9e15), "finite"), - ((0.0, 1.0, 1e-300, 0.5), ZeroDivisionError), - ((1e-300, 1.0, 1.0, 0.5), "finite"), - ((1.0, 1e-300, 1.0, 0.5), INVALID_HYPERGEO), - ((1e300, 1e300, 1e300, 0.5), INVALID_HYPERGEO), - ((1.0, 2.0, 1e300, 0.5), INVALID_HYPERGEO), - ((1.0, 1e300, 2.0, 0.5), INVALID_HYPERGEO), -] - - -def laplace_grid(name): - if name == "hyperu_laplace": - return [ - (a, a + db, x) - for a in [1e-10, 1e-3, 1.0, 50.0, 1e5] - for db in [0.0, 1e-10, 1.0, 1e3, 1e10] - for x in [1e-12, 1e-3, 1.0, 1e3, 1e8, 1e15] - ] - if name == "hyp1f1_laplace": - return [ - (a, a + db, x) - for a in [1e-10, 1e-3, 1.0, 50.0, 1e5] - for db in [1e-10, 1.0, 1e3, 1e10] - for x in [-1e8, -1e3, -1.0, -1e-10, 1e-10, 1.0, 1e3, 1e8, 1e15] - ] - zs = [5e-324, 1e-300, -1e-12, 1e-8, -1e-4, 0.5, 0.9, 1 - 1e-4, 1 - 1e-6] - zs += [-1.0, -100.0, -1e9] - abcs = [(1.0, 2.0, 3.0), (5.0, 7.0, 9.0), (0.5, 30.0, 1.5), (30.0, 40.0, 35.0)] - return [(*abc, z) for abc in abcs for z in zs] - - -LAPLACE = { - "hyperu_laplace": HYPERU_DOMAIN, - "hyp1f1_laplace": HYP1F1_DOMAIN, - "hyp2f1_laplace": HYP2F1_DOMAIN, -} - - -def unity_threshold(): - """ - Largest ``x < 1`` for which ``np.isclose(x, 1.0)`` fails, and the next one up - """ - lo, hi = 0.5, 1.0 - 1e-9 # not close, close - while nextafter(lo, 1.0) != hi: - mid = lo + (hi - lo) / 2 - if np.isclose(mid, 1.0): - hi = mid - else: - lo = mid - return lo, hi - - -def negative_unity_threshold(): - """ - As `unity_threshold`, for ``z < 0`` mapped to ``z / (z - 1)`` - """ - lo, hi = -1e3, -1e9 # not close, close - while nextafter(lo, hi) != hi: - mid = lo + (hi - lo) / 2 - if np.isclose(mid / (mid - 1), 1.0): - hi = mid - else: - lo = mid - return lo, hi - - -def unity_args_from_ep(a_i, b_i, a_j, b_j, y, mu): - """ - Arguments of `hyp2f1_laplace` in the edge update of EP, for hugely negative z - """ - return a_j, a_i + a_j + y, a_j + y + 1, (mu - b_j) / (mu + b_i) - - -# (a, b, c, z) for the three limits (g < 0, g > 0, g == 0), for z close to one and, -# via Pfaff's transformation, for large negative z (where g = a - b) -UNITY_CASES = [ - (2.0, 3.0, 4.0, 1 - 1e-8), - (1.0, 2.0, 5.0, 1 - 1e-8), - (1.0, 2.0, 3.0, 1 - 1e-8), - (2.0, 3.0, 4.0, -1e8), - (3.0, 2.0, 5.0, -1e8), - (2.0, 2.0, 5.0, -1e8), - (19.0, 30.0, 25.0, 1 - 1e-7), - (1.0, 2.0, 1.0 + 2.0 + 1e-3, 1 - 1e-9), # g tiny positive - (1.0, 2.0, 3.0 - 1e-3, 1 - 1e-9), # g tiny negative - # parameters of EP updates that reach the limit - unity_args_from_ep(202.865, 0.0153, 0.0012724, 101353547.00, 0.0, 2.404560e-05), - unity_args_from_ep(999.998, 0.1041, 0.0012612, 14749022.000, 2.0, 7.830300e-05), - unity_args_from_ep(157.778, 0.0182, 0.0011993, 20861958.000, 0.0, 4.128000e-07), - unity_args_from_ep(1000.00, 0.1431, 0.0009718, 22638776.000, 0.0, 5.881110e-05), - unity_args_from_ep(405.482, 0.1484, 0.0009711, 41053809.000, 0.0, 6.229410e-05), - unity_args_from_ep(115.773, 0.7506, 0.0015549, 23315696857.0, 0.0, 3.601680e-05), - unity_args_from_ep(73.4909, 1.0600, 0.0010028, 56254280956.0, 0.0, 0.0002302392), - unity_args_from_ep(18.9981, 0.1315, 0.0015053, 23443723634.0, 1.0, 2.470348e-05), -] - - -class TestLaplaceDomain: - """ - Edge cases of `hyperu_laplace`, `hyp1f1_laplace` and `hyp2f1_laplace`: the - domain assertions, the zero shortcuts (``x == 0`` returns 0 after the checks), the - division by zero when a Laplace root cancels, and overflow. - """ - - @pytest.mark.parametrize( - ("name", "args", "expected"), - [p for name, rows in LAPLACE.items() for p in table(name, rows)], - ) - def test_domain(self, name, args, expected): - parity(name, args, expected) - - @pytest.mark.parametrize( - ("name", "args"), - [ - pytest.param(name, args, id=f"{name}{args}") - for name in LAPLACE - for args in laplace_grid(name) - ], - ) - def test_grid(self, name, args): - parity(name, args) - - -class TestHyp2f1Unity: - """ - The unity limit (`_hyp2f1_unity`, reached when ``z`` is ``np.isclose`` to one) - """ - - @pytest.mark.parametrize("args", UNITY_CASES, ids=repr) - def test_unity_branches(self, args): - z = args[3] - mapped = z / (z - 1) if z < 0 else z - assert np.isclose(mapped, 1.0), "case must take the unity branch" - parity("hyp2f1_laplace", args) - - @pytest.mark.parametrize("sign", ["positive", "negative"]) - @pytest.mark.parametrize("side", ["not_close", "close"]) - def test_switch_point(self, sign, side): - # the unity formula is used from the first np.isclose argument onwards - if sign == "positive": - not_close, close = unity_threshold() - else: - not_close, close = negative_unity_threshold() - z = close if side == "close" else not_close - parity("hyp2f1_laplace", (5.0, 7.0, 9.0, z), "finite") - - -def draw_polygamma(rng, extreme): - if extreme: - return (float(rng.choice([-1.0, 1.0]) * log_uniform(rng, -12, 12)),) - x = log_uniform(rng, -7, 3) - if rng.random() < 0.15: - x = -rng.uniform(0.01, 20) # reflection formula - return (float(x),) - - -def draw_betaln(rng, extreme): - lo, hi = (-8, 8) if extreme else (-2, 3) - return log_uniform(rng, lo, hi), log_uniform(rng, lo, hi) - - -def draw_gammainc_der(rng, extreme): - if extreme: - return log_uniform(rng, -8, 8), log_uniform(rng, -8, 8) - # series, continued fraction and gaussian regimes - return log_uniform(rng, -1, 3.5), log_uniform(rng, -3, 4) - - -def draw_hyperu(rng, extreme): - # requires b >= a > 0 and x > 0 - if extreme: - a = log_uniform(rng, -8, 8) - return a, a + log_uniform(rng, -8, 8), log_uniform(rng, -12, 12) - a = log_uniform(rng, -1, 2) - return a, a + log_uniform(rng, -2, 2), log_uniform(rng, -3, 3) - - -def draw_hyp1f1(rng, extreme): - # requires b > a > 0, x of either sign - sign = float(rng.choice([-1.0, 1.0])) - if extreme: - a = log_uniform(rng, -8, 8) - return a, a + log_uniform(rng, -8, 8), sign * log_uniform(rng, -12, 12) - a = log_uniform(rng, -1, 2) - return a, a + log_uniform(rng, -2, 2), sign * log_uniform(rng, -2, 2) - - -def draw_hyp2f1(rng, extreme): - if extreme: - a = log_uniform(rng, -8, 8) - b = log_uniform(rng, -8, 8) - c = a + (0.0 if rng.random() < 0.3 else log_uniform(rng, -8, 8)) - z = float(rng.choice([-1.0, 1.0, 1.0]) * log_uniform(rng, -14, 0)) - return a, b, c, z + 1.0 if rng.random() < 0.3 else z - # parameters of the edge (c = a_j + y + 1) and unphased (c = a_i + a_j) updates, - # with z < 1 on either side of zero and close to unity - a_i, a_j = rng.uniform(0.5, 30, 2) - y = float(rng.integers(0, 12)) - c = a_j + y + 1 if rng.random() < 0.5 else a_i + a_j - u = rng.random() - if u < 0.4: - z = -log_uniform(rng, -3, 3) - elif u < 0.8: - z = 1 - log_uniform(rng, -6, 0) - else: - z = 1 - log_uniform(rng, -12, -9) - return float(a_j), float(a_i + a_j + y), float(c), z - - -DRAWS = { - "digamma": draw_polygamma, - "trigamma": draw_polygamma, - "betaln": draw_betaln, - "gammainc_der": draw_gammainc_der, - "hyperu_laplace": draw_hyperu, - "hyp1f1_laplace": draw_hyp1f1, - "hyp2f1_laplace": draw_hyp2f1, -} - - -class TestRandomDraws: - """ - Seeded draws of arguments, in ranges typical of EP and over 16 orders of magnitude - ("extreme", where exceptions and non-finite values are common). The failing - draw is named in the assertion. - """ - - @pytest.mark.parametrize("seed", [1, 2, 3]) - @pytest.mark.parametrize("mode", ["typical", "extreme"]) - @pytest.mark.parametrize("name", list(DRAWS)) - def test_random_draws(self, name, mode, seed): - rng = np.random.default_rng(seed) - for i in range(40): - args = DRAWS[name](rng, mode == "extreme") - try: - parity(name, args) - except AssertionError as e: - raise AssertionError(f"draw {i}: {name}{args}: {e}") from None diff --git a/tests/test_oracle_prior.py b/tests/test_oracle_prior.py deleted file mode 100644 index 854f8de5..00000000 --- a/tests/test_oracle_prior.py +++ /dev/null @@ -1,115 +0,0 @@ -""" -Parity of ``marginalize_over_ancestors`` and ``conditional_coalescent_variance`` -with their oracles, and a pin of how ``tsdate`` calls the latter with a single tip. -""" - -import _tsdate -import numpy as np -import pytest -import tskit -from oracle import prior -from oracle.helpers import INF, NAN, assert_outcome, compare - -import tsdate -from tsdate import prior as tsdate_prior - - -def coalescent_moments(num_tips): - """ - The argument that `conditional_coalescent_variance` passes - """ - rates = np.array( - [2 / (i * (i - 1)) if i > 1 else 0.0 for i in range(1, num_tips + 1)] - ) - mean, variance = rates.copy(), rates.copy() ** 2 - for i in range(rates.size - 2, 0, -1): - mean[i] += mean[i + 1] - variance[i] += variance[i + 1] - return np.stack((mean, variance + mean**2), 1) - - -# val, outcome category of the oracle -MARGINALIZE_EDGE_CASES = [ - pytest.param(np.array([[1.0, 2.0], [3.0, 4.0]]), "finite", id="two_tips"), - pytest.param(np.zeros((6, 2)), "finite", id="zeros"), - pytest.param(np.full((6, 2), NAN), "nan", id="all_nan"), - # NOTE: non-finite values are propagated by the weighted sum, with no checks - pytest.param( - np.array([[1.0, 2.0], [INF, 1.0], [3.0, 3.0], [1.0, NAN]]), "nan", id="inf_nan" - ), -] - - -class TestMarginalizeOverAncestors: - @pytest.mark.parametrize("num_tips", [2, 3, 10, 60, 200]) - @pytest.mark.parametrize("seed", range(2)) - def test_random(self, seed, num_tips): - rng = np.random.default_rng(seed) - val = rng.uniform(0.1, 10.0, (num_tips, 2)) - compare( - _tsdate.marginalize_over_ancestors, - prior.marginalize_over_ancestors, - val, - ) - - @pytest.mark.parametrize("num_columns", [1, 3]) - def test_number_of_moments(self, num_columns): - val = np.random.default_rng(0).uniform(0.1, 10.0, (12, num_columns)) - compare( - _tsdate.marginalize_over_ancestors, - prior.marginalize_over_ancestors, - val, - ) - - @pytest.mark.parametrize("num_tips", [3, 10, 100]) - def test_coalescent_moments(self, num_tips): - compare( - _tsdate.marginalize_over_ancestors, - prior.marginalize_over_ancestors, - coalescent_moments(num_tips), - ) - - @pytest.mark.parametrize(("val", "expected_kind"), MARGINALIZE_EDGE_CASES) - def test_edge_cases(self, val, expected_kind): - assert_outcome( - _tsdate.marginalize_over_ancestors, - prior.marginalize_over_ancestors, - (val,), - expected_kind, - ) - - -class TestConditionalCoalescentVariance: - @pytest.mark.parametrize("num_tips", [2, 3, 5, 20, 100, 250]) - def test_variance(self, num_tips): - compare( - _tsdate.conditional_coalescent_variance, - prior.conditional_coalescent_variance, - num_tips, - ) - - -class TestSingleTip: - def test_called_with_one_tip(self, monkeypatch): - # NOTE: current behaviour, possibly a bug: a tree with one - # attached sample (with `allow_unary`) calls - # `conditional_coalescent_variance(1)`, whose result is unused. - tables = tskit.TableCollection(1000.0) - for _ in range(3): - tables.nodes.add_row(flags=tskit.NODE_IS_SAMPLE, time=0) - tables.nodes.add_row(time=1.0) - tables.edges.add_row(0, 1000, 3, 0) - tables.edges.add_row(500, 1000, 3, 1) - tables.edges.add_row(500, 1000, 3, 2) - tables.sort() - ts = tables.tree_sequence() - called = [] - original = tsdate_prior.conditional_coalescent_variance - - def record(num_tips): - called.append(int(num_tips)) - return original(num_tips) - - monkeypatch.setattr(tsdate_prior, "conditional_coalescent_variance", record) - tsdate.build_prior_grid(ts, timepoints=5, population_size=1e4, allow_unary=True) - assert called == [3, 1] diff --git a/tests/test_oracle_rescaling.py b/tests/test_oracle_rescaling.py deleted file mode 100644 index d718fa1c..00000000 --- a/tests/test_oracle_rescaling.py +++ /dev/null @@ -1,952 +0,0 @@ -""" -Parity of the rescaling functions of ``_tsdate`` with their oracles: random -inputs, inputs from ``ExpectationPropagation.rescale`` on simulated tree sequences, -degenerate inputs, and every error. -""" - -import _tsdate -import numpy as np -import pytest -from oracle import rescaling -from oracle.errors import ( - INVALID_POSTERIOR, - INVALID_QUANTILE_WIDTH, - NEGATIVE_CHANGEPOINT_PARAMETER, - NO_POSTERIORS, - NON_INCREASING_BREAKPOINTS, - NONPOSITIVE_INTERVALS, - TIME_BELOW_FIRST_BREAKPOINT, - UNSORTED_QUANTILES, - ZERO_EDGE_SPAN, -) -from oracle.helpers import ( - INF, - NAN, - assert_outcome, - b1, - compare, - f64, - i32, - make_ts, - shrink, -) - -from tsdate.variational import ExpectationPropagation - - -@pytest.fixture(params=["small_ts_unphased", "small_ts_historical"]) -def sim_ts(request): - return request.getfixturevalue(request.param) - - -@pytest.fixture(scope="module") -def eps(small_ts, small_ts_historical): - """ - `ExpectationPropagation` after a few iterations, for each simulated ts - """ - eps = {} - for name, ts in [ - ("small_ts", small_ts), - ("small_ts_historical", small_ts_historical), - ]: - ep = ExpectationPropagation(ts, mutation_rate=1e-8) - ep.iterate(max_shape=1000, min_step=0.1) - eps[name] = ep - return eps - - -@pytest.fixture(params=["small_ts", "small_ts_historical"]) -def ep(request, eps): - return eps[request.param] - - -def rescale_inputs(ep): - """ - Arguments of `mutational_timescale`, as in `ExpectationPropagation.rescale` - """ - nodes_time, _ = ep.node_moments() - nodes_fixed = ep.node_constraints[:, 0] == ep.node_constraints[:, 1] - return ( - nodes_time, - ep.sizebiased_likelihoods, - nodes_fixed, - ep.edge_parents, - ep.edge_children, - ) - - -def count_args(ts, size_biased, node_is_sample=None): - if node_is_sample is None: - node_is_sample = np.full(ts.num_nodes, False) - node_is_sample[ts.samples()] = True - return [ - node_is_sample, - ts.mutations_node, - ts.sites_position[ts.mutations_site], - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, - size_biased, - ] - - -def piecewise_rates(rng, size, num_pieces, offset_range, rate_range): - """ - Poisson counts and offsets for `size` observations, with piecewise constant rate - """ - offset = rng.uniform(*offset_range, size) - rate = np.repeat(rng.uniform(*rate_range, num_pieces), size // num_pieces + 1)[:size] - counts = rng.poisson(rate * offset).astype(float) - return counts, offset - - -# counts, epochs, outcome category of the oracle -FIXED_CHANGEPOINT_CASES = [ - pytest.param([1.0, 2.0, 3.0], 1, "finite", id="one_epoch"), - pytest.param([5.0], 1, "finite", id="one_epoch_one_count"), - pytest.param([0.0, 0.0, 4.0, 0.0], 1, "finite", id="one_epoch_concentrated"), - pytest.param([1.0, 2.0, 3.0], 10, "finite", id="more_epochs_than_counts"), - pytest.param([0.0, 0.0, 4.0, 0.0], 4, "finite", id="concentrated_counts"), - pytest.param([0.0, 0.0, 5.0, 5.0], 3, "finite", id="zeros_at_start"), - pytest.param([5.0, 5.0, 0.0, 0.0], 3, "finite", id="zeros_at_end"), - pytest.param([0.0, 5.0, 0.0, 5.0, 0.0], 3, "finite", id="zeros_in_middle"), - pytest.param([1.0] * 4, 4, "finite", id="quantiles_exact"), - pytest.param([1.0] * 4, 2, "finite", id="quantiles_exact_half"), - pytest.param([1.0, 2.0], 0, NONPOSITIVE_INTERVALS, id="zero_epochs"), - pytest.param([1.0, 2.0], -1, NONPOSITIVE_INTERVALS, id="negative_epochs"), - # NOTE: current behaviour, possibly a bug: with no counts the - # cumulative distribution is 0 / 0 = NaN, which `searchsorted` places last, so - # every breakpoint but the last is -1 - pytest.param([0.0, 0.0, 0.0], 3, "finite", id="zero_total"), - pytest.param([], 3, "finite", id="empty"), -] - - -class TestFixedChangepoints: - @staticmethod - def compare(counts, epochs): - return compare( - _tsdate.fixed_changepoints, - rescaling.fixed_changepoints, - np.asarray(counts, dtype=float), - epochs, - ) - - @pytest.mark.parametrize( - ("counts", "epochs", "expected_kind"), FIXED_CHANGEPOINT_CASES - ) - def test_edge_cases(self, counts, epochs, expected_kind): - assert_outcome( - _tsdate.fixed_changepoints, - rescaling.fixed_changepoints, - (np.asarray(counts, dtype=float), epochs), - expected_kind, - ) - - @pytest.mark.parametrize("mode", ["typical", "zeros"]) - @pytest.mark.parametrize("seed", range(3)) - def test_random(self, seed, mode): - rng = np.random.default_rng(seed) - size = int(rng.integers(3, 300)) - counts = rng.exponential(1.0, size) - epochs = int(rng.integers(1, 40)) - if mode == "zeros": - counts *= rng.random(size) < 0.6 - counts[0] += 1.0 - epochs = int(rng.integers(1, 120)) - self.compare(counts, epochs) - # also the dtype, which `compare` ignores - actual = _tsdate.fixed_changepoints(counts, epochs) - assert actual.dtype == np.int32 - - -COUNTS = [5.0, 6.0, 20.0, 22.0, 21.0, 3.0] -ONES = [1.0] * 6 -# counts, offset, penalty, min_counts, min_offset, outcome category of the oracle -POISSON_CASES = [ - pytest.param(COUNTS, ONES, 0.0, 0.0, 0.0, "finite", id="no_penalty"), - pytest.param(COUNTS, ONES, 2.0, 0.0, 0.0, "finite", id="penalty"), - pytest.param(COUNTS, ONES, 1e6, 0.0, 0.0, "finite", id="huge_penalty"), - pytest.param(COUNTS, ONES, INF, 0.0, 0.0, "finite", id="infinite_penalty"), - # the exact counts of two observations are 21 and 22 - pytest.param(COUNTS, ONES, 2.0, 21.0, 0.0, "finite", id="min_counts_21"), - pytest.param(COUNTS, ONES, 2.0, 22.0, 0.0, "finite", id="min_counts_22"), - pytest.param(COUNTS, ONES, 2.0, 1000.0, 0.0, "finite", id="min_counts_unreachable"), - pytest.param(COUNTS, ONES, 0.0, 0.0, 1.5, "finite", id="min_offset_1.5"), - pytest.param(COUNTS, ONES, 0.0, 0.0, 6.0, "finite", id="min_offset_total"), - pytest.param(COUNTS, ONES, 0.0, 0.0, 6.5, "finite", id="min_offset_over_total"), - pytest.param(COUNTS, ONES, 2.0, 0.0, 100.0, "finite", id="min_offset_unreachable"), - pytest.param( - COUNTS, [1.0, 1.0, 0.0, 1.0, 1.0, 1.0], 2.0, 0.0, 0.0, "finite", id="zero_offset" - ), - pytest.param( - COUNTS, - [1.0, 1.0, 0.0, 1.0, 1.0, 1.0], - 2.0, - 0.0, - 0.5, - "finite", - id="zero_offset_min_offset", - ), - pytest.param([], [], 2.0, 0.0, 0.0, "finite", id="empty"), - pytest.param([4.0], [1.0], 2.0, 0.0, 0.0, "finite", id="single_observation"), - # log(0) is -inf and 0 * -inf is NaN, so the loss is NaN - pytest.param([0.0] * 3, [1.0] * 3, 0.0, 0.0, 0.0, "finite", id="zero_counts"), - pytest.param([0.0] * 3, [1.0] * 3, 2.0, 1.0, 0.0, "finite", id="zero_counts_min"), - pytest.param( - COUNTS, - ONES, - -1.0, - 0.0, - 0.0, - NEGATIVE_CHANGEPOINT_PARAMETER, - id="negative_penalty", - ), - pytest.param( - COUNTS, ONES, NAN, 0.0, 0.0, NEGATIVE_CHANGEPOINT_PARAMETER, id="nan_penalty" - ), - pytest.param( - COUNTS, - ONES, - 2.0, - -1.0, - 0.0, - NEGATIVE_CHANGEPOINT_PARAMETER, - id="negative_min_counts", - ), - pytest.param( - COUNTS, - ONES, - 2.0, - 0.0, - -1.0, - NEGATIVE_CHANGEPOINT_PARAMETER, - id="negative_min_offset", - ), - pytest.param(COUNTS, ONES[:3], 2.0, 0.0, 0.0, ValueError, id="size_mismatch"), -] - - -class TestPoissonChangepoints: - @pytest.mark.parametrize( - ("counts", "offset", "penalty", "min_counts", "min_offset", "expected_kind"), - POISSON_CASES, - ) - def test_edge_cases( - self, counts, offset, penalty, min_counts, min_offset, expected_kind - ): - args = (f64(*counts), f64(*offset), penalty, min_counts, min_offset) - assert_outcome( - _tsdate.poisson_changepoints, - rescaling.poisson_changepoints, - args, - expected_kind, - ) - - @pytest.mark.parametrize("mode", ["typical", "extreme"]) - @pytest.mark.parametrize("seed", range(3)) - def test_random(self, seed, mode): - rng = np.random.default_rng(seed) - size = int(rng.integers(8, 45)) - if mode == "typical": - counts, offset = piecewise_rates(rng, size, 3, (0.5, 2.0), (0.5, 20.0)) - args = (counts, offset, float(rng.choice([0.0, 2.0, 10.0])), 1.0, 0.1) - else: - counts, offset = piecewise_rates(rng, size, 4, (0.2, 3.0), (0.2, 30.0)) - args = (counts, offset, float(rng.choice([1.0, 50.0])), 10.0, 0.5) - compare( - _tsdate.poisson_changepoints, - rescaling.poisson_changepoints, - *args, - ) - # also the dtype, which `compare` ignores - actual = _tsdate.poisson_changepoints(*args) - assert actual.dtype == np.int32 - - -COUNT_NODES = [(1, 0), (1, 0), (0, 1)] -COUNT_EDGES = [(0, 10, 2, 0), (0, 10, 2, 1)] -GAPPED = [(0, 4, 2, 0), (6, 10, 2, 0), (0, 10, 2, 1)] -BREAKPOINT = [(0, 5, 2, 0), (5, 10, 2, 0), (0, 10, 2, 1)] -SAMPLE_TREE_NODES = [(1, 0), (1, 0), (1, 0), (0, 1), (0, 2)] -SAMPLE_TREE_EDGES = [(0, 10, 3, 0), (0, 10, 3, 1), (0, 10, 4, 3), (0, 10, 4, 2)] - -# nodes, edges, mutations, length; run with and without size bias -COUNT_CASES = [ - # node 2 is the root, so a mutation on it has no edge; several per edge - pytest.param( - COUNT_NODES, - COUNT_EDGES, - [(1, 0), (2, 0), (3, 1), (5, 2)], - 10.0, - id="mutation_above_root", - ), - pytest.param(COUNT_NODES, COUNT_EDGES, [], 10.0, id="no_mutations"), - pytest.param(COUNT_NODES, [], [(1, 0)], 10.0, id="no_edges"), - pytest.param(COUNT_NODES, [], [], 10.0, id="no_edges_no_mutations"), - pytest.param( - [(1, 0), (0, 1)], [(0, 4, 1, 0)], [(1, 0), (5, 0)], 10.0, id="beyond_the_edge" - ), - pytest.param(COUNT_NODES, GAPPED, [(4, 0), (5, 0)], 10.0, id="in_gap"), - pytest.param(COUNT_NODES, BREAKPOINT, [(5, 0), (4.5, 0)], 10.0, id="at_breakpoint"), - pytest.param( - SAMPLE_TREE_NODES, - SAMPLE_TREE_EDGES, - [(1, 0), (2, 3), (3, 3)], - 10.0, - id="weighted_by_samples", - ), -] - - -class TestCountMutations: - @staticmethod - def compare(args): - return compare(_tsdate.count_mutations, rescaling.count_mutations, *args) - - @pytest.mark.parametrize("size_biased", [False, True]) - @pytest.mark.parametrize(("nodes", "edges", "mutations", "length"), COUNT_CASES) - def test_edge_cases(self, nodes, edges, mutations, length, size_biased): - ts = make_ts(nodes, edges, mutations, length) - self.compare(count_args(ts, size_biased)) - - def test_mutation_edges(self): - # a mutation at a breakpoint belongs to the tree to its right; none above - # the root; the edge id of a mutation is NULL if no edge covers it - mutations = [(1, 0), (2, 0), (3, 1), (5, 2)] - ts = make_ts(COUNT_NODES, COUNT_EDGES, mutations, 10.0) - _, mutation_edge = self.compare(count_args(ts, False)).value - assert mutation_edge.tolist() == [0, 0, 1, -1] - - @pytest.mark.parametrize("size_biased", [False, True]) - def test_no_samples_flagged(self, size_biased): - ts = make_ts(COUNT_NODES, COUNT_EDGES, [(1, 0)], 10.0) - none = np.full(ts.num_nodes, False) - self.compare(count_args(ts, size_biased, node_is_sample=none)) - - def test_unsorted_mutations(self): - mutations = [(1, 0), (2, 1), (6, 0), (8, 1), (9, 2)] - ts = make_ts(COUNT_NODES, BREAKPOINT, mutations, 10.0) - args = count_args(ts, False) - order = np.array([3, 0, 4, 1, 2]) - args[1], args[2] = args[1][order], args[2][order] - self.compare(args) - - @pytest.mark.parametrize(("index", "size"), [(4, 1), (7, 1), (2, 1)]) - def test_size_mismatch(self, index, size): - ts = make_ts(COUNT_NODES, COUNT_EDGES, [(1, 0), (2, 1)], 10.0) - args = shrink(count_args(ts, False), index, size) - result = self.compare(args) - assert result.error is ValueError - - @pytest.mark.parametrize("size_biased", [False, True]) - def test_simulated(self, sim_ts, size_biased): - args = count_args(sim_ts, size_biased) - self.compare(args) - # also the dtype, which `compare` ignores - actual = _tsdate.count_mutations(*args) - assert actual[1].dtype == np.int32 - - -def area_args(nodes_time, likelihoods, parents, children): - likelihoods = np.array(likelihoods, dtype=float) - if likelihoods.size == 0: - likelihoods = likelihoods.reshape(0, 2) - return ( - f64(*nodes_time), - likelihoods, - i32(*parents), - i32(*children), - ) - - -LIK = [[2, 10], [1, 10]] -# nodes_time, likelihoods, parents, children, exception of the oracle -AREA_CASES = [ - pytest.param([0, 0, 1], LIK, [2, 2], [0, 1], None, id="single_epoch"), - # all nodes at time zero: no epoch, and every edge has zero length - pytest.param([0, 0, 0], LIK, [2, 2], [0, 1], None, id="no_epochs"), - pytest.param([0, 1], [], [], [], None, id="no_edges"), - pytest.param([0.0], [], [], [], None, id="single_node"), - pytest.param([], [], [], [], None, id="no_nodes"), - pytest.param( - [0, 0, 1, 1, 3], - [[2, 10], [1, 10], [4, 5]], - [2, 2, 4], - [0, 1, 3], - None, - id="zero_length_edge", - ), - # an edge whose parent is younger than its child is skipped entirely - pytest.param([0, 1, 0.5], LIK, [1, 2], [0, 1], None, id="negative_length_edge"), - pytest.param([0, 0, 1, 3], [[6, 12], [3, 12]], [3, 2], [0, 1], None, id="two_epochs"), - # NOTE: current behaviour, possibly a bug: the first epoch always - # starts at zero, even if the youngest node is older - pytest.param([1, 2], [[2, 10]], [1], [0], None, id="no_node_at_time_zero"), - pytest.param( - [3, 0, 1, 0, 1, 5], - [[2, 10], [1, 10], [3, 10], [2, 10]], - [4, 2, 5, 2], - [1, 3, 0, 1], - None, - id="ties_and_unsorted_times", - ), - pytest.param([0, 0, 1], LIK, [2], [0, 1], ValueError, id="parents_mismatch"), - pytest.param( - [0, 0, 1], [[1, 1]] * 3, [2, 2], [0, 1], ValueError, id="likelihood_rows" - ), - pytest.param( - [0, 0, 1], - [[1, 1, 1]] * 2, - [2, 2], - [0, 1], - ValueError, - id="likelihood_columns", - ), -] - - -class TestMutationalArea: - @staticmethod - def compare(*args): - return compare(_tsdate.mutational_area, rescaling.mutational_area, *args) - - @pytest.mark.parametrize( - ("nodes_time", "likelihoods", "parents", "children", "expected_error"), AREA_CASES - ) - def test_edge_cases(self, nodes_time, likelihoods, parents, children, expected_error): - args = area_args(nodes_time, likelihoods, parents, children) - result = self.compare(*args) - assert result.error is expected_error - - @pytest.mark.parametrize("seed", range(2)) - def test_random(self, sim_ts, seed): - ts = sim_ts - rng = np.random.default_rng(seed) - times = ts.nodes_time * rng.uniform(0.8, 1.2, ts.num_nodes) - times[ts.samples()] = ts.nodes_time[ts.samples()] - likelihoods = rng.uniform(0, 5, (ts.num_edges, 2)) - args = (times, likelihoods, ts.edges_parent, ts.edges_child) - self.compare(*args) - # also the dtype, which `compare` ignores - actual = _tsdate.mutational_area(*args) - assert actual[3].dtype == np.int32 - - def test_simulated(self, ep): - nodes_time, likelihoods, _, parents, children = rescale_inputs(ep) - self.compare(nodes_time, likelihoods, parents, children) - - -def timescale_args(nodes_time, likelihoods, nodes_fixed, parents, children, k): - return ( - f64(*nodes_time), - np.array(likelihoods, dtype=float).reshape(-1, 2), - b1(*nodes_fixed), - i32(*parents), - i32(*children), - k, - ) - - -# nodes 0, 1 are samples at time 0, 2 and 3 are internal -CHAIN = ( - [0, 0, 1.0, 2.0], - [[2, 10], [1, 10], [3, 10]], - [1, 1, 0, 0], - [2, 2, 3], - [0, 1, 2], -) -# sample 1 is historical -HISTORICAL = ([0, 500, 100, 700], [[2, 10], [1, 10], [3, 10]]) -HISTORICAL_EDGES = ([2, 3, 3], [0, 2, 1]) - - -def chain(k, fixed=None): - times, lik, nodes_fixed, parents, children = CHAIN - return timescale_args(times, lik, fixed or nodes_fixed, parents, children, k) - - -def historical(k, fixed): - times, lik = HISTORICAL - parents, children = HISTORICAL_EDGES - return timescale_args(times, lik, fixed, parents, children, k) - - -# arguments, outcome category (or exception) of the oracle -TIMESCALE_CASES = [ - pytest.param(chain(1), "finite", id="one_interval"), - pytest.param(chain(2), "finite", id="two_intervals"), - pytest.param(chain(3), "finite", id="as_many_as_epochs"), - pytest.param(chain(10000), "finite", id="more_than_epochs"), - pytest.param(chain(0), NONPOSITIVE_INTERVALS, id="zero_intervals"), - pytest.param(chain(-1), NONPOSITIVE_INTERVALS, id="negative_intervals"), - # NOTE: current behaviour, possibly a bug: `nodes_fixed` is only - # size-checked, so which nodes are fixed does not matter - pytest.param(chain(3, [0, 0, 0, 0]), "finite", id="no_fixed_nodes"), - pytest.param(chain(3, [1, 1, 1, 1]), "finite", id="all_fixed_nodes"), - pytest.param(historical(1, [1, 0, 0, 0]), "finite", id="contemporary_one"), - pytest.param(historical(3, [1, 1, 0, 0]), "finite", id="historical_three"), - pytest.param(historical(100, [1, 1, 0, 0]), "finite", id="historical_many"), - # the top edge has no span, so the last epoch has no weight and is merged - pytest.param( - timescale_args( - [0, 0, 1.0, 2.0], - [[2, 10], [1, 10], [3, 0]], - [1, 1, 0, 0], - [2, 2, 3], - [0, 1, 2], - 1, - ), - "finite", - id="zero_span_top_edge", - ), - # edge 2 -> 3 is negative (3 is older than 2): skipped from the totals - pytest.param( - timescale_args( - [0, 0, 2.0, 1.0], - [[2, 10], [1, 10], [5, 10]], - [1, 1, 0, 0], - [2, 2, 3], - [0, 1, 2], - 2, - ), - "finite", - id="negative_length_edge", - ), - # NOTE: current behaviour, possibly a bug: every edge over an - # interval has zero span (a zero mutation rate) or there are no edges - pytest.param( - timescale_args([0, 0, 1.0], [[2, 0], [1, 0]], [1, 1, 0], [2, 2], [0, 1], 1), - ZERO_EDGE_SPAN, - id="zero_edge_span", - ), - pytest.param( - timescale_args([0.0, 1.0], [], [1, 1], [], [], 1), ZERO_EDGE_SPAN, id="no_edges" - ), - pytest.param( - timescale_args([0.0, 0.0, 0.0], [[1, 10], [1, 10]], [1, 1, 1], [2, 2], [0, 1], 1), - ZERO_EDGE_SPAN, - id="all_nodes_at_time_zero", - ), -] - - -class TestMutationalTimescale: - @staticmethod - def compare(*args): - return compare( - _tsdate.mutational_timescale, rescaling.mutational_timescale, *args - ) - - @pytest.mark.parametrize(("args", "expected"), TIMESCALE_CASES) - def test_edge_cases(self, args, expected): - assert_outcome( - _tsdate.mutational_timescale, - rescaling.mutational_timescale, - args, - expected, - ) - - @pytest.mark.parametrize("which", ["fixed", "parents", "likelihood_rows", "columns"]) - def test_size_mismatch(self, which): - args = list(chain(2)) - if which == "fixed": - args[2] = b1(1, 1) - elif which == "parents": - args[3] = i32(2, 2) - elif which == "likelihood_rows": - args[1] = np.ones((2, 2)) - else: - args[1] = np.ones((3, 3)) - result = self.compare(*args) - assert result.error is ValueError - - @pytest.mark.parametrize("max_intervals", [3, 1000]) - @pytest.mark.parametrize("seed", range(2)) - def test_random(self, sim_ts, seed, max_intervals): - ts = sim_ts - rng = np.random.default_rng(seed) - times = ts.nodes_time * rng.uniform(0.9, 1.1, ts.num_nodes) - times[ts.samples()] = ts.nodes_time[ts.samples()] - likelihoods = np.column_stack( - ( - rng.poisson(2.0, ts.num_edges).astype(float), - rng.uniform(1, 5, ts.num_edges), - ) - ) - fixed = np.full(ts.num_nodes, False) - fixed[ts.samples()] = True - args = (times, likelihoods, fixed, ts.edges_parent, ts.edges_child, max_intervals) - self.compare(*args) - - @pytest.mark.parametrize("max_intervals", [1, 10, 1000]) - def test_simulated(self, ep, max_intervals): - self.compare(*rescale_inputs(ep), max_intervals) - - -ORIGINAL = [0.0, 1.0, 3.0] -RESCALED = [0.0, 2.0, 3.5] -# estimate, fixed, original, rescaled, outcome category of the oracle -POINT_ESTIMATE_CASES = [ - pytest.param( - [0.0, 0.5, 1.0, 2.0, 3.0], None, ORIGINAL, RESCALED, "finite", id="inside" - ), - # the last scaling is zero, so everything beyond collapses to the last point - pytest.param( - [3.0, 4.0, 10.0, 1e300], None, ORIGINAL, RESCALED, "finite", id="beyond" - ), - pytest.param([INF], None, ORIGINAL, RESCALED, "nan", id="infinite"), - # NOTE: current behaviour, possibly a bug: a time below the first - # break has search index -1, which wraps to the last breakpoint; -inf gives NaN - pytest.param( - [-1.0, -1e-9, 0.0], None, ORIGINAL, RESCALED, "finite", id="below_first" - ), - pytest.param([-INF], None, ORIGINAL, RESCALED, "nan", id="minus_infinity"), - pytest.param([NAN], None, ORIGINAL, RESCALED, "nan", id="nan"), - pytest.param( - [0.0, 0.5, 3.0, 4.0], [1, 0, 1, 1], ORIGINAL, RESCALED, "finite", id="some_fixed" - ), - pytest.param([NAN, 1.0], [1, 0], ORIGINAL, RESCALED, "nan", id="fixed_nan"), - pytest.param([], None, ORIGINAL, RESCALED, "finite", id="empty"), - pytest.param([0.0, 0.5, 7.0], None, [0.0], [0.0], "finite", id="single_breakpoint"), - pytest.param([0.0, 0.5, 7.0], None, [0.0], [2.0], "finite", id="single_scaled"), - pytest.param([0.0, 0.3, 1.0], None, [0.0, 5.0], [0.0, 5.0], "finite", id="identity"), - pytest.param( - [0.5], - None, - [0.0, 1.0, 3.0], - [0.0, 2.0, 2.0], - NON_INCREASING_BREAKPOINTS, - id="flat_rescaled", - ), - pytest.param( - [0.5], - None, - [0.0, 1.0, 3.0], - [0.0, 2.0, 1.0], - NON_INCREASING_BREAKPOINTS, - id="decreasing", - ), - pytest.param( - [0.5], - None, - [0.0, 1.0, 1.0], - [0.0, 2.0, 3.0], - NON_INCREASING_BREAKPOINTS, - id="flat_original", - ), - pytest.param( - [0.5], - None, - [0.0, 2.0, 1.0], - [0.0, 1.0, 2.0], - NON_INCREASING_BREAKPOINTS, - id="decr_original", - ), - pytest.param( - [0.5], - None, - [0.0, 1.0, NAN], - [0.0, 1.0, 2.0], - NON_INCREASING_BREAKPOINTS, - id="nan_original", - ), - pytest.param( - [0.5], - None, - [0.0, 1.0, 2.0], - [0.0, 1.0, NAN], - NON_INCREASING_BREAKPOINTS, - id="nan_rescaled", - ), -] - - -class TestPiecewiseScalePointEstimate: - @pytest.mark.parametrize( - ("estimate", "fixed", "original", "rescaled", "expected_kind"), - POINT_ESTIMATE_CASES, - ) - def test_edge_cases(self, estimate, fixed, original, rescaled, expected_kind): - estimate = f64(*estimate) - fixed = np.full(estimate.size, False) if fixed is None else b1(*fixed) - args = (estimate, fixed, f64(*original), f64(*rescaled)) - assert_outcome( - _tsdate.piecewise_scale_point_estimate, - rescaling.piecewise_scale_point_estimate, - args, - expected_kind, - ) - - @pytest.mark.parametrize("seed", range(3)) - def test_random(self, seed): - rng = np.random.default_rng(seed) - k = int(rng.integers(2, 12)) - original = np.concatenate(([0.0], np.cumsum(rng.uniform(0.1, 5.0, k)))) - rescaled = np.concatenate(([0.0], np.cumsum(rng.uniform(0.1, 5.0, k)))) - estimate = rng.uniform(0, original[-1] * 1.2, 40) - fixed = rng.random(40) < 0.2 - compare( - _tsdate.piecewise_scale_point_estimate, - rescaling.piecewise_scale_point_estimate, - estimate, - fixed, - original, - rescaled, - ) - - def test_simulated(self, ep): - nodes_time, likelihoods, nodes_fixed, parents, children = rescale_inputs(ep) - original, rescaled = rescaling.mutational_timescale( - nodes_time, likelihoods, nodes_fixed, parents, children, 10 - ) - compare( - _tsdate.piecewise_scale_point_estimate, - rescaling.piecewise_scale_point_estimate, - nodes_time, - nodes_fixed, - original, - rescaled, - ) - - -POSTERIORS = [[1.0, 1.0], [2.0, 3.0], [0.0, 1.0], [5.0, 2.0]] - - -# posteriors, keyword arguments of `posterior_args`, outcome category (or exception) -# of the oracle -POSTERIOR_CASES = [ - pytest.param(POSTERIORS, {}, "finite", id="default"), - pytest.param(POSTERIORS, {"quantile_width": 1e-3}, "finite", id="narrow_quantile"), - pytest.param(POSTERIORS, {"quantile_width": 0.999}, "finite", id="wide_quantile"), - pytest.param( - POSTERIORS, {"quantile_width": 1 - 1e-9}, "finite", id="widest_quantile" - ), - *[ - pytest.param( - POSTERIORS, {"quantile_width": w}, INVALID_QUANTILE_WIDTH, id=f"width_{w}" - ) - for w in [0.0, 1.0, -0.1, 1.5, NAN, INF] - ], - pytest.param(POSTERIORS, {"fixed": [1, 0, 1, 0]}, "nan", id="some_fixed"), - pytest.param(POSTERIORS, {"fixed": [1] * 4}, "nan", id="all_fixed"), - # fixed rows are not validated - pytest.param( - [[-5.0, -5.0], [1.0, 1.0]], {"fixed": [1, 0]}, "nan", id="fixed_negative" - ), - pytest.param([[NAN, NAN], [1.0, 1.0]], {"fixed": [1, 0]}, "nan", id="fixed_nan"), - # NOTE: current behaviour, possibly a bug: no posteriors is an error, - # with numpy's "zero-size array" message - pytest.param(np.zeros((0, 2)), {"fixed": []}, NO_POSTERIORS, id="no_posteriors"), - *[ - pytest.param([row], {}, "finite", id=f"valid_{i}") - for i, row in enumerate( - [[-0.99, 1.0], [0.0, 1.0], [1.0, 1e-300], [1.0, 1e300], [1e6, 1e6]] - ) - ], - # NOTE: current behaviour, possibly a bug: for a shape this close - # to -1 the lower quantile underflows to zero and the division by it is an error - # (IEEE would give inf), rather than a failed gamma fit - *[ - pytest.param([row], {}, ZeroDivisionError, id=f"shape_near_minus_one_{i}") - for i, row in enumerate([[-0.9999, 1.0], [-1 + 1e-12, 1.0], [-0.9999999, 2.0]]) - ], - pytest.param([[1.0, INF]], {}, ZeroDivisionError, id="infinite_rate"), - # NOTE: current behaviour, possibly a bug: the error leaks out of - # `approximate_gamma_iqr` - pytest.param([[INF, 1.0]], {}, UNSORTED_QUANTILES, id="infinite_shape"), - *[ - pytest.param([row], {}, INVALID_POSTERIOR, id=f"invalid_{i}") - for i, row in enumerate( - [[-1.0, 1.0], [1.0, 0.0], [1.0, -1.0], [NAN, 1.0], [1.0, NAN], [-INF, 1.0]] - ) - ], - pytest.param( - [[1.0, 1.0], [2.0, 3.0], [0.0, 1.0], [-1.0, 2.0]], - {}, - INVALID_POSTERIOR, - id="one_invalid", - ), - # all quantiles map to one point beyond the last break: zero interquantile range - pytest.param([[1.0, 0.001], [1.0, 1e-9]], {}, "finite", id="beyond_last_break"), - pytest.param( - POSTERIORS, - {"original": [0.5, 1.0, 3.0]}, - TIME_BELOW_FIRST_BREAKPOINT, - id="below_first", - ), - # NOTE: current behaviour, possibly a bug: `max_shape=0` gives - # shape -1 (improper) and zero rate - pytest.param(POSTERIORS, {"max_shape": 0.0}, "finite", id="max_shape_0"), - pytest.param(POSTERIORS, {"max_shape": 1.0}, "finite", id="max_shape_1"), - pytest.param(POSTERIORS, {"max_shape": 10.0}, "finite", id="max_shape_10"), - pytest.param(POSTERIORS, {"max_shape": 1e8}, "finite", id="max_shape_1e8"), - pytest.param(POSTERIORS, {"max_shape": INF}, "finite", id="max_shape_inf"), - pytest.param(POSTERIORS, {"max_shape": NAN}, "finite", id="max_shape_nan"), - *[ - pytest.param( - POSTERIORS, - {"original": o, "rescaled": r}, - NON_INCREASING_BREAKPOINTS, - id=i, - ) - for i, o, r in [ - ("original_flat", [0.0, 1.0, 1.0], RESCALED), - ("rescaled_flat", ORIGINAL, [0.0, 2.0, 2.0]), - ("rescaled_decreasing", ORIGINAL, [0.0, 2.0, 1.0]), - ("rescaled_nan", ORIGINAL, [0.0, 2.0, NAN]), - ] - ], - # the breaks are checked before the posteriors - pytest.param( - [[-5.0, 1.0]], - {"original": [0.0, 0.0], "rescaled": [0.0, 1.0]}, - NON_INCREASING_BREAKPOINTS, - id="bad_breaks_before_posteriors", - ), - # a single (zero-length) interval: everything is beyond the last break - pytest.param( - POSTERIORS, - {"original": [0.0], "rescaled": [0.0]}, - ZeroDivisionError, - id="single_break_zero", - ), - pytest.param( - POSTERIORS, {"original": [0.0], "rescaled": [4.0]}, "finite", id="single_break" - ), - pytest.param(POSTERIORS, {"fixed": [0] * 3}, ValueError, id="fixed_mismatch"), - pytest.param( - POSTERIORS, - {"original": [0.0, 1.0], "rescaled": RESCALED}, - ValueError, - id="breaks_mismatch", - ), -] - - -def posterior_args( - posteriors, - fixed=None, - original=None, - rescaled=None, - quantile_width=0.5, - max_shape=1000.0, -): - posteriors = np.asarray(posteriors, dtype=float).reshape(-1, 2) - fixed = np.full(posteriors.shape[0], False) if fixed is None else b1(*fixed) - original = f64(*(ORIGINAL if original is None else original)) - rescaled = f64(*(RESCALED if rescaled is None else rescaled)) - return (posteriors, fixed, original, rescaled, quantile_width, max_shape) - - -class TestPiecewiseScalePosterior: - @pytest.mark.parametrize(("posteriors", "kwargs", "expected"), POSTERIOR_CASES) - def test_edge_cases(self, posteriors, kwargs, expected): - args = posterior_args(posteriors, **kwargs) - assert_outcome( - _tsdate.piecewise_scale_posterior, - rescaling.piecewise_scale_posterior, - args, - expected, - ) - - @pytest.mark.parametrize("seed", range(3)) - def test_random(self, seed): - rng = np.random.default_rng(seed) - k = int(rng.integers(2, 10)) - original = np.concatenate(([0.0], np.cumsum(rng.uniform(0.1, 5.0, k)))) - rescaled = np.concatenate(([0.0], np.cumsum(rng.uniform(0.1, 5.0, k)))) - alpha = rng.uniform(-0.8, 60.0, 15) - beta = np.exp(rng.uniform(-2, 4, 15)) * (alpha + 1) / (original[-1] * 0.8) - args = ( - np.column_stack((alpha, beta)), - rng.random(15) < 0.2, - original, - rescaled, - float(rng.uniform(0.2, 0.9)), - float(rng.choice([2.0, 100.0, 1000.0])), - ) - compare( - _tsdate.piecewise_scale_posterior, - rescaling.piecewise_scale_posterior, - *args, - ) - - def test_simulated(self, ep): - nodes_time, likelihoods, nodes_fixed, parents, children = rescale_inputs(ep) - original, rescaled = rescaling.mutational_timescale( - nodes_time, likelihoods, nodes_fixed, parents, children, 10 - ) - args = (ep.node_posterior, nodes_fixed, original, rescaled, 0.8, 1000.0) - compare( - _tsdate.piecewise_scale_posterior, - rescaling.piecewise_scale_posterior, - *args, - ) - - -class TestOutsideTreeSequences: - def test_nan_node_times(self): - # NaN is ordered last, whichever its position - times = np.array([0.0, np.nan, 1.0, np.nan, 2.0]) - likelihoods = np.array([[1.0, 1.0], [1.0, 1.0]]) - parents = np.array([2, 4], dtype=np.int32) - children = np.array([0, 2], dtype=np.int32) - compare( - _tsdate.mutational_area, - rescaling.mutational_area, - times, - likelihoods, - parents, - children, - ) - - def test_changepoint_before_the_first_epoch(self): - # The mutational spans make the offsets of the four epochs 1, 1, -3 and 1, so - # that the total weight is zero and the cumulative distribution is NaN where - # it is looked up: the first changepoint is -1, which counts from the end as - # in numpy. - nodes_time = np.array([0.0, 0.0, 1.0, 2.0, 3.0, 4.0]) - likelihoods = np.array([[1.0, 1.0], [1.0, 1.0], [1.0, -3.0], [1.0, 1.0]]) - parents = np.array([2, 3, 4, 5], dtype=np.int32) - children = np.array([0, 2, 3, 4], dtype=np.int32) - fixed = np.full(6, False) - args = (nodes_time, likelihoods, fixed, parents, children, 2) - result = compare( - _tsdate.mutational_timescale, rescaling.mutational_timescale, *args - ) - assert result.value[0].tolist() == [4.0, 4.0] - - def test_quantile_below_first_breakpoint(self): - # the lower quantile (1.1) is below the first breakpoint, the mean (2) is not - args = ( - np.array([[1.0, 1.0]]), - np.array([False]), - np.array([1.5, 3.0, 5.0]), - np.array([0.0, 1.0, 2.0]), - 0.5, - 1000.0, - ) - result = compare( - _tsdate.piecewise_scale_posterior, rescaling.piecewise_scale_posterior, *args - ) - assert result.error == TIME_BELOW_FIRST_BREAKPOINT - - def test_fixed_posteriors_below_first_breakpoint(self): - # the rescaled quantiles of fixed posteriors are zero, and are checked too - args = ( - np.array([[1.0, 1.0]]), - np.array([True]), - np.array([0.5, 2.0, 5.0]), - np.array([0.0, 1.0, 2.0]), - 0.5, - 1000.0, - ) - result = compare( - _tsdate.piecewise_scale_posterior, rescaling.piecewise_scale_posterior, *args - ) - assert result.error == TIME_BELOW_FIRST_BREAKPOINT diff --git a/tests/test_oracle_variational.py b/tests/test_oracle_variational.py deleted file mode 100644 index 296f836b..00000000 --- a/tests/test_oracle_variational.py +++ /dev/null @@ -1,653 +0,0 @@ -""" -Equivalence of the expectation propagation of ``_tsdate`` with the oracle of -``tsdate.variational``: the EP helpers (``damp``, ``rescale``, -``constraints_are_consistent``), and the methods of ``ExpectationPropagation``, -compared after the same sequence of passes from the same inputs. - -Inputs are those of EP on the session fixtures, with constraints and counts edited to -force branches, and tables of boundary and failure cases. Expected values always come -from the oracle. Where the C library reports a division by zero and the oracle does -not raise, the C function alone is checked. -""" - -import copy -import re - -import _tsdate -import numpy as np -import pytest -import tskit -from oracle import ep_state, variational -from oracle.errors import ( - INVALID_DAMPING, - INVALID_MAX_SHAPE, - INVALID_MIN_STEP, - INVALID_NODE_POSTERIOR, - NONPOSITIVE_PENALTY, - ZERO_DIVISION, -) -from oracle.helpers import INF, NAN, compare, f64, kind, log_uniform - -from tsdate.variational import ( - LOWER, - UPPER, - USE_BLOCK_LIKELIHOOD, - USE_EDGE_LIKELIHOOD, - ExpectationPropagation, -) - -up = np.nextafter -TS_NAMES = list(ep_state.SPECS) -INCONSISTENT_MESSAGE = ( - "Node age constraints are inconsistent, some descendants have" - " lower bounds that exceed upper bounds of their ancestors." -) - - -@pytest.fixture(scope="module") -def inputs(small_ts, small_ts_unphased, small_ts_historical): - """ - The inputs of EP, by fixture name - """ - tss = [small_ts, small_ts_unphased, small_ts_historical] - return {name: ep_state.make_inputs(ts, name) for name, ts in zip(TS_NAMES, tss)} - - -@pytest.fixture(scope="module") -def started(inputs): - """ - The oracle's EP two iterations in, by fixture name - """ - return {name: ep_state.start(variational, ins) for name, ins in inputs.items()} - - -def compare_runs(ins, step, started=None, iterations=2): - """ - Run ``step`` on the ``ExpectationPropagation`` of ``_tsdate`` and of the oracle - after ``iterations`` (``started``, if given, is the oracle's), and compare what it - returns and the state after it - """ - - def run(ep): - result = step(ep) - return result, *ep_state.state(ep) - - def actual(): - return run(ep_state.start(_tsdate, ins, iterations)) - - def expected(): - if started is None: - return run(ep_state.start(variational, ins, iterations)) - return run(copy.deepcopy(started)) - - return compare(actual, expected) - - -def unphased_name(ts_name): - return ts_name == "small_ts_unphased" - - -def raises_zero_division(): - """ - ``pytest.raises`` for the library's float division by zero - """ - message = _tsdate.strerror(ZERO_DIVISION) - return pytest.raises(_tsdate.LibraryError, match=re.escape(message)) - - -def likelihood_pass(order, unphased, max_shape=1000.0, min_step=0.1): - """ - A step that runs ``propagate_likelihood`` - """ - - def step(ep): - ep.propagate_likelihood( - order=order, unphased=unphased, max_shape=max_shape, min_step=min_step - ) - - return step - - -def prior_pass(free, max_shape=1000.0, em_maxitt=10, em_reltol=1e-8): - """ - A step that runs ``propagate_prior`` - """ - - def step(ep): - ep.propagate_prior( - free=free, max_shape=max_shape, em_maxitt=em_maxitt, em_reltol=em_reltol - ) - - return step - - -def mutations_pass(mutations_edge, unphased): - """ - A step that runs ``propagate_mutations`` - """ - - def step(ep): - return ep.propagate_mutations(mutations_edge=mutations_edge, unphased=unphased) - - return step - - -# fmt: off -DAMP_TABLE = [ - # (id, x, y, s, kind); first component test is `1 + x0 - y0 > (1 + x0) * s`, - # second is `x1 - y1 > x1 * s`. With x = (1, 2) and s = 0.5 the thresholds are - # y0 = 1 and y1 = 1. - ("zeros", f64(0, 0), f64(0, 0), 0.5, "finite"), - ("zeros_invalid_s", f64(0, 0), f64(0, 0), 5.0, "finite"), - ("zero_y", f64(1, 2), f64(0, 0), 0.5, "finite"), - ("a_below", f64(1, 2), f64(up(1.0, 0.0), 0), 0.5, "finite"), - ("a_at", f64(1, 2), f64(1.0, 0), 0.5, "finite"), - ("a_above", f64(1, 2), f64(up(1.0, 2.0), 0), 0.5, "finite"), - ("a_damped", f64(1, 2), f64(4, 0), 0.5, "finite"), - ("a_negative_y", f64(1, 2), f64(-5, 0), 0.5, "finite"), - ("b_below", f64(1, 2), f64(0, up(1.0, 0.0)), 0.5, "finite"), - ("b_at", f64(1, 2), f64(0, 1.0), 0.5, "finite"), - ("b_above", f64(1, 2), f64(0, up(1.0, 2.0)), 0.5, "finite"), - ("b_damped", f64(1, 2), f64(0, 8), 0.5, "finite"), - ("b_negative_y", f64(1, 2), f64(0, -5), 0.5, "finite"), - ("min_is_a", f64(1, 2), f64(4, 2), 0.5, "finite"), - ("min_is_b", f64(1, 2), f64(2, 8), 0.5, "finite"), - ("both_negative_y", f64(1, 2), f64(-1, -1), 0.5, "finite"), - ("tiny_s", f64(1, 2), f64(2, 2), up(0.0, 1.0), "finite"), - ("s_below_one", f64(1, 2), f64(2, 2), up(1.0, 0.0), "finite"), - ("x0_just_above_minus_one", f64(up(-1.0, 0.0), 1), f64(0, 0), 0.5, "finite"), - # NOTE: current behaviour, possibly a bug: `min(a, b)` swallows a - # NaN in the second component of y, so the damping is silently skipped. - ("y1_nan", f64(1, 1), f64(0, NAN), 0.5, "finite"), - ("y1_nan_a_damped", f64(1, 1), f64(8, NAN), 0.5, "finite"), - ("y0_minus_inf", f64(1, 1), f64(-INF, 0), 0.5, "finite"), - ("y1_minus_inf", f64(1, 1), f64(0, -INF), 0.5, "finite"), - # `s` is checked by the callers (direct calls only) - ("s_zero", f64(1, 1), f64(0, 0), 0.0, INVALID_MIN_STEP), - ("s_one", f64(1, 1), f64(0, 0), 1.0, INVALID_MIN_STEP), - ("s_negative", f64(1, 1), f64(0, 0), -0.5, INVALID_MIN_STEP), - ("s_nan", f64(1, 1), f64(0, 0), NAN, INVALID_MIN_STEP), - # `0 < x[0] + 1` and `0 < x[1]`: reachable from improper or NaN posteriors - ("x0_minus_one", f64(-1, 1), f64(0, 0), 0.5, INVALID_NODE_POSTERIOR), - ("x0_nan", f64(NAN, 1), f64(0, 0), 0.5, INVALID_NODE_POSTERIOR), - ("x1_zero", f64(1, 0), f64(0, 0), 0.5, INVALID_NODE_POSTERIOR), - ("x1_negative", f64(1, -1), f64(0, 0), 0.5, INVALID_NODE_POSTERIOR), - ("x1_nan", f64(1, NAN), f64(0, 0), 0.5, INVALID_NODE_POSTERIOR), - ("x_zero_y_not", f64(0, 0), f64(1, 1), 0.5, INVALID_NODE_POSTERIOR), - # `0 < d` fails when d underflows or y[0] is NaN - ("d_underflow", f64(1, 1e-300), f64(0, 1e300), 0.5, INVALID_DAMPING), - ("y0_nan", f64(1, 1), f64(NAN, 0), 0.5, INVALID_DAMPING), -] -RESCALE_TABLE = [ - # (id, x, s, kind); branches `1 + x0 > s` and `1 + x0 < 1 / s` - ("zeros", f64(0, 0), 10.0, "finite"), - ("zeros_invalid_s", f64(0, 0), 0.0, "finite"), - ("x0_zero", f64(0, 1), 10.0, "finite"), - ("inside", f64(5, 1), 10.0, "finite"), - ("inside_low", f64(-0.5, 1), 2.0, "finite"), - ("upper_below", f64(up(9.0, 0.0), 1), 10.0, "finite"), - ("upper_at", f64(9, 1), 10.0, "finite"), - ("upper_above", f64(up(9.0, 10.0), 1), 10.0, "finite"), - ("lower_above", f64(up(-0.5, 0.0), 1), 2.0, "finite"), - ("lower_at", f64(-0.5, 1), 2.0, "finite"), - ("lower_below", f64(up(-0.5, -1.0), 1), 2.0, "finite"), - ("lower_far", f64(-0.95, 1), 10.0, "finite"), - ("infinite_rate", f64(99, INF), 10.0, "finite"), - ("infinite_shape", f64(INF, 1), 10.0, "finite"), - # NOTE: current behaviour, possibly a bug: with `max_shape = 1` - # (allowed by the checks in `propagate_*`) the factor is 0 and wipes out the - # posterior. - ("s_one_upper", f64(1, 1), 1.0, "finite"), - ("s_one_lower", f64(-0.5, 1), 1.0, "finite"), - # reachable as for `damp` - ("x0_minus_one", f64(-1, 1), 10.0, INVALID_NODE_POSTERIOR), - ("x0_nan", f64(NAN, 1), 10.0, INVALID_NODE_POSTERIOR), - ("x1_zero", f64(1, 0), 10.0, INVALID_NODE_POSTERIOR), - ("x1_negative", f64(1, -1), 10.0, INVALID_NODE_POSTERIOR), - ("x1_nan", f64(1, NAN), 10.0, INVALID_NODE_POSTERIOR), -] -# fmt: on - - -class TestDamp: - @pytest.mark.parametrize( - ("x", "y", "s", "expected_kind"), - [pytest.param(*row[1:], id=row[0]) for row in DAMP_TABLE], - ) - def test_table(self, x, y, s, expected_kind): - result = compare(_tsdate.damp, variational.damp, *x, *y, s) - assert kind(result) == expected_kind - - @pytest.mark.parametrize("seed", range(8)) - def test_random(self, seed): - rng = np.random.default_rng(seed) - x = f64(rng.uniform(-0.9, 30), log_uniform(rng, -4, -1)) - y = f64(rng.uniform(-5, 30), log_uniform(rng, -4, -1)) - s = float(rng.uniform(0.05, 0.95)) - compare(_tsdate.damp, variational.damp, *x, *y, s) - - @pytest.mark.parametrize("which", [0, 1]) - def test_infinite_posterior_zero_message(self, which): - # C reports the division of inf by 0.0; the oracle, on the NumPy scalars of - # the passes, returns d = 1. Needs an infinite posterior, which is - # unreachable without a prior failure. - x = f64(1, 1) - x[which] = INF - with raises_zero_division(): - _tsdate.damp(*x, 0.0, 0.0, 0.5) - - -class TestRescale: - @pytest.mark.parametrize( - ("x", "s", "expected_kind"), - [pytest.param(*row[1:], id=row[0]) for row in RESCALE_TABLE], - ) - def test_table(self, x, s, expected_kind): - result = compare(_tsdate.rescale, variational.rescale, *x, s) - assert kind(result) == expected_kind - - @pytest.mark.parametrize("seed", range(8)) - def test_random(self, seed): - rng = np.random.default_rng(seed) - x = f64(rng.uniform(-0.9, 3000), log_uniform(rng, -4, -1)) - s = float(rng.choice([10.0, 100.0, 1000.0])) - compare(_tsdate.rescale, variational.rescale, *x, s) - - def test_zero_shape_offset_cap_below_one(self): - # C reports the division by zero; the oracle, on NumPy scalars, returns - # -inf. Direct call only: `propagate_*` check `max_shape >= 1`. - with raises_zero_division(): - _tsdate.rescale(0.0, 1.0, 0.5) - - -class TestConstraintsAreConsistent: - @staticmethod - def check(constraints, parents, children, valid): - args = ( - np.array(constraints, dtype=np.float64), - np.array(parents, dtype=np.int32), - np.array(children, dtype=np.int32), - ) - func = _tsdate.constraints_are_consistent - result = compare(func, variational.constraints_are_consistent, *args) - assert result.value is valid - - @pytest.mark.parametrize( - ("constraints", "parents", "children", "valid"), - [ - pytest.param(*row[1:], id=row[0]) - for row in [ - ("no_edges", [[0, 1], [0, 1]], [], [], True), - ("free_nodes", [[0, 0], [0, INF]], [1], [0], True), - ("lower_below_upper", [[0, 5], [3, 9]], [1], [0], True), - # boundary: the parent's upper bound equals the child's lower bound - ("equal_bounds", [[5, 5], [0, 5]], [1], [0], True), - ("equal_samples", [[5, 5], [5, 5]], [1], [0], True), - ("child_just_above", [[up(5.0, 6.0), 6], [0, 5]], [1], [0], False), - ("parent_just_below", [[5, 5], [0, up(5.0, 4.0)]], [1], [0], False), - # the max lower bound propagates up a chain, and from every child - ("chain_valid", [[5, 5], [0, 9], [0, 9]], [1, 2], [0, 1], True), - ("chain_invalid", [[5, 5], [0, INF], [0, 4]], [1, 2], [0, 1], False), - ("two_children", [[0, 0], [7, 7], [0, 6]], [2, 2], [0, 1], False), - ("sample_ancestor", [[0, 0], [10, 10]], [1], [0], True), - ("sample_descendant_older", [[10, 10], [0, 0]], [1], [0], False), - # NOTE: current behaviour, possibly a bug: the check is - # a single pass in edge order, so edges must be sorted children-first. - ( - "chain_edges_reversed", - [[5, 5], [0, INF], [0, 4]], - [2, 1], - [1, 0], - True, - ), - # NaN comparisons are false: NaN bounds are never inconsistent - ("nan_lower", [[NAN, NAN], [0, 5]], [1], [0], True), - ("nan_upper", [[5, 5], [0, NAN]], [1], [0], True), - ] - ], - ) - def test_table(self, constraints, parents, children, valid): - self.check(constraints, parents, children, valid) - - @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_historical"]) - @pytest.mark.parametrize("gap", ["equal", "one_ulp"]) - def test_real_edges(self, inputs, ts_name, gap): - # the lower bound of a child equals the upper bound of its parent, or exceeds it - ins = inputs[ts_name] - constraints = ins.node_constraints.copy() - p, c = ins.edge_parents[-1], ins.edge_children[-1] - constraints[c, LOWER] = 500.0 - constraints[p, UPPER] = 500.0 if gap == "equal" else up(500.0, 0.0) - valid = gap == "equal" - self.check(constraints, ins.edge_parents, ins.edge_children, valid) - - def test_production_raises(self): - constraints = np.array([[10.0, 10.0], [0.0, 0.0]]) - edge = np.array([1], dtype=np.int32), np.array([0], dtype=np.int32) - check = ExpectationPropagation._check_valid_constraints - with pytest.raises(ValueError, match=re.escape(INCONSISTENT_MESSAGE)): - check(constraints, *edge) - - -class TestFactors: - @pytest.mark.parametrize("ts_name", TS_NAMES) - def test_rescale_factors(self, inputs, started, ts_name): - # a pass with a small cap leaves scales that are not one - ins = inputs[ts_name] - unphased = unphased_name(ts_name) - order = ins.block_order if unphased else ins.edge_order - - def step(ep): - likelihood_pass(order, unphased, max_shape=3.0)(ep) - ep.rescale_factors() - return ep.assemble_factors() - - compare_runs(ins, step, started[ts_name]) - - @pytest.mark.parametrize("ts_name", TS_NAMES) - def test_assemble_factors(self, inputs, started, ts_name): - compare_runs(inputs[ts_name], lambda ep: ep.assemble_factors(), started[ts_name]) - - -class TestPropagateLikelihood: - SUBSET = slice(0, 400) # an initial portion of the pass keeps the oracle quick - - @staticmethod - def order(ins, unphased, subset=None): - order = ins.block_order if unphased else ins.edge_order - return order if subset is None else order[subset] - - @pytest.mark.parametrize( - ("ts_name", "max_shape", "min_step"), - [ - ("small_ts", 1000.0, 0.1), - ("small_ts_unphased", 1000.0, 0.1), - ("small_ts_historical", 1000.0, 0.1), - ("small_ts", 10.0, 0.5), - ("small_ts_unphased", 10.0, 0.5), - ], - ) - def test_natural(self, inputs, started, ts_name, max_shape, min_step): - ins = inputs[ts_name] - unphased = unphased_name(ts_name) - counts = ins.branch_counts(unphased) - assert counts["both_free"] > 0 - assert counts["both_fixed"] == counts["fixed_parent"] == 0 - step = likelihood_pass(self.order(ins, unphased), unphased, max_shape, min_step) - compare_runs(ins, step, started[ts_name]) - - @pytest.mark.parametrize("ts_name", TS_NAMES) - def test_forced_fixed_nodes(self, inputs, ts_name): - # every branch: both nodes fixed (skipped), one fixed, both free - unphased = unphased_name(ts_name) - ins = ep_state.fixed_internal(inputs[ts_name], unphased) - counts = ins.branch_counts(unphased) - assert all(v > 0 for k, v in counts.items() if k != "twin" or unphased) - step = likelihood_pass(self.order(ins, unphased), unphased) - compare_runs(ins, step, iterations=1) - - @pytest.mark.parametrize("kind_of_order", ["empty", "partial_and_repeated"]) - def test_order(self, inputs, started, kind_of_order): - # the order array is arbitrary: empty, or any subset with repeats - ins = inputs["small_ts"] - if kind_of_order == "empty": - order = np.zeros(0, dtype=np.int32) - else: - order = ins.edge_order[100:140] - order = np.concatenate((order, order[::-1], order[:5])).astype(np.int32) - compare_runs(ins, likelihood_pass(order, False), started["small_ts"]) - - @pytest.mark.parametrize( - "max_shape", - # NOTE: current behaviour, possibly a bug: a cap of exactly 1 - # zeroes posteriors and scales (and then every later update is NaN) - [1.0, up(1.0, 2.0), 3.0, 1e300], - ids=lambda v: f"max_shape={v:g}", - ) - @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_unphased"]) - def test_max_shape(self, inputs, started, ts_name, max_shape): - ins = inputs[ts_name] - unphased = unphased_name(ts_name) - order = self.order(ins, unphased, self.SUBSET) - step = likelihood_pass(order, unphased, max_shape=max_shape) - compare_runs(ins, step, started[ts_name]) - - @pytest.mark.parametrize( - "min_step", - [up(0.0, 1.0), 0.1, 0.99, 1 - 1e-9], - ids=lambda v: f"min_step={v:g}", - ) - @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_unphased"]) - def test_min_step(self, inputs, started, ts_name, min_step): - ins = inputs[ts_name] - unphased = unphased_name(ts_name) - order = self.order(ins, unphased, self.SUBSET) - # a small cap makes passes difficult, so that damping is exercised - step = likelihood_pass(order, unphased, max_shape=3.0, min_step=min_step) - compare_runs(ins, step, started[ts_name]) - - @pytest.mark.parametrize("multiplier", [1e12, 1e300], ids=lambda v: f"y*{v:g}") - def test_extreme_counts(self, inputs, multiplier): - # 1e12: projection failures are skipped (NaN lognorm). 1e300: a posterior - # becomes NaN and the next `damp` fails its check `0 < x[0] + 1`, - # reachable from real data (~1e300 mutations on an edge). - ins = inputs["small_ts"].copy() - ins.edge_likelihoods = ins.edge_likelihoods * [multiplier, 1.0] - order = ins.edge_order[: self.SUBSET.stop] - compare_runs(ins, likelihood_pass(order, False), iterations=0) - - @pytest.mark.parametrize( - ("kwargs", "expected"), - [ - pytest.param( - dict(max_shape=up(1.0, 0.0)), INVALID_MAX_SHAPE, id="max_shape_below_one" - ), - pytest.param(dict(max_shape=0.0), INVALID_MAX_SHAPE, id="max_shape_zero"), - pytest.param(dict(max_shape=NAN), INVALID_MAX_SHAPE, id="max_shape_nan"), - pytest.param(dict(min_step=0.0), INVALID_MIN_STEP, id="min_step_zero"), - pytest.param(dict(min_step=1.0), INVALID_MIN_STEP, id="min_step_one"), - pytest.param(dict(min_step=-0.1), INVALID_MIN_STEP, id="min_step_negative"), - pytest.param(dict(min_step=1.5), INVALID_MIN_STEP, id="min_step_above_one"), - pytest.param(dict(min_step=NAN), INVALID_MIN_STEP, id="min_step_nan"), - ], - ) - def test_invalid_parameters(self, inputs, kwargs, expected): - # reachable from user input (`max_shape`, `min_step` of `iterate`/`infer`): - # parameter errors in the C library, not internal invariants - ins = inputs["small_ts"] - step = likelihood_pass(ins.edge_order[:10], False, **kwargs) - result = compare_runs(ins, step, iterations=0) - assert kind(result) == expected - - -class TestPropagatePrior: - @pytest.mark.parametrize("ts_name", TS_NAMES) - def test_natural(self, inputs, started, ts_name): - ins = inputs[ts_name] - assert ins.unconstrained_roots.any() - compare_runs(ins, prior_pass(ins.unconstrained_roots), started[ts_name]) - - @pytest.mark.parametrize( - ("em_maxitt", "em_reltol"), - # `em_maxitt`: no iteration (-1), one (0), the cap binding (3), convergence - # binding (1000); `em_reltol`: run to the cap (0), tight, loose, NaN (no - # iteration) - [(m, r) for m in [-1, 0, 3, 1000] for r in [0.0, 1e-8, 0.5, NAN]], - ids=lambda v: f"{v:g}", - ) - def test_em(self, inputs, started, em_maxitt, em_reltol): - ins = inputs["small_ts"] - step = prior_pass( - ins.unconstrained_roots, - em_maxitt=em_maxitt, - em_reltol=em_reltol, - max_shape=1e300, - ) - compare_runs(ins, step, started["small_ts"]) - - @pytest.mark.parametrize("ts_name", ["small_ts", "small_ts_historical"]) - @pytest.mark.parametrize( - "max_shape", - # NOTE: current behaviour, possibly a bug: a cap of exactly 1 - # zeroes the posteriors and scales of the free nodes - [1.0, 1.5, 1e300], - ids=lambda v: f"max_shape={v:g}", - ) - def test_max_shape(self, inputs, started, ts_name, max_shape): - ins = inputs[ts_name] - step = prior_pass(ins.unconstrained_roots, max_shape=max_shape) - compare_runs(ins, step, started[ts_name]) - - @pytest.mark.parametrize( - ("ts_name", "free", "kwargs"), - [ - ("small_ts", "single_root", {}), - # any node set with proper cavities works, not only roots - ("small_ts_unphased", "internal", {}), - ("small_ts", "none", {}), - # no free nodes returns before looking at anything else - ("small_ts", "none", dict(em_maxitt=-5, em_reltol=NAN, max_shape=1.0)), - ], - ids=["single_root", "internal", "none", "none_odd_arguments"], - ) - def test_free_nodes(self, inputs, started, ts_name, free, kwargs): - ins = inputs[ts_name] - mask = np.zeros(ins.node_constraints.shape[0], dtype=bool) - if free == "single_root": - mask[np.flatnonzero(ins.unconstrained_roots)[0]] = True - elif free == "internal": - mask = ~ins.fixed & ~ins.roots | ins.unconstrained_roots - compare_runs(ins, prior_pass(mask, **kwargs), started[ts_name]) - - @pytest.mark.parametrize( - ("case", "expected"), - [ - # `penalty > 0` fails when the mean of shape / rate is infinite or - # negative: free nodes whose cavity has zero rate (fixed leaves) - ("all_nodes", NONPOSITIVE_PENALTY), - ("leaves", NONPOSITIVE_PENALTY), - # reachable from user input - ("max_shape_below_one", INVALID_MAX_SHAPE), - ("max_shape_zero", INVALID_MAX_SHAPE), - ("max_shape_nan", INVALID_MAX_SHAPE), - ], - ) - def test_errors(self, inputs, started, case, expected): - ins = inputs["small_ts"] - free = ins.unconstrained_roots - kwargs = {} - if case == "all_nodes": - free = np.ones_like(free) - elif case == "leaves": - free = ins.leaves - else: - kwargs["max_shape"] = { - "below_one": up(1.0, 0.0), - "zero": 0.0, - "nan": NAN, - }[case[len("max_shape_") :]] - result = compare_runs(ins, prior_pass(free, **kwargs), started["small_ts"]) - assert kind(result) == expected - - def test_penalty_error_reachable_from_ep(self, inputs): - # NOTE: current behaviour, possibly a bug: a likelihood pass in - # which every update is skipped (a huge mutational target) leaves the roots - # with a zero posterior, so that `iterate(regularise=True)` fails the - # `penalty > 0` check (an error, not NaN). - ins = inputs["small_ts"].copy() - ins.edge_likelihoods = ins.edge_likelihoods * [1.0, 1e300] - - def step(ep): - likelihood_pass(ins.edge_order, False)(ep) - prior_pass(ins.unconstrained_roots)(ep) - - result = compare_runs(ins, step, iterations=0) - assert kind(result) == NONPOSITIVE_PENALTY - - -class TestPropagateMutations: - @pytest.mark.parametrize( - ("ts_name", "unphased"), - [ - ("small_ts", False), - ("small_ts_historical", False), - ("small_ts_unphased", False), - ("small_ts_unphased", True), - ], - ) - def test_natural(self, inputs, started, ts_name, unphased): - ins = inputs[ts_name] - step = mutations_pass(ins.mutations_edge(unphased), unphased) - compare_runs(ins, step, started[ts_name]) - - @pytest.mark.parametrize( - ("ts_name", "unphased"), - [ - ("small_ts", False), - ("small_ts_historical", False), - ("small_ts_unphased", True), - ], - ) - def test_forced_fixed_nodes(self, inputs, ts_name, unphased): - # mutations on edges of every kind: both nodes fixed, one of the two fixed - ins = ep_state.fixed_internal(inputs[ts_name], unphased) - counts = ins.branch_counts(unphased) - assert all(counts[k] > 0 for k in ("both_fixed", "fixed_parent", "fixed_child")) - step = mutations_pass(ins.mutations_edge(unphased), unphased) - compare_runs(ins, step, iterations=1) - - @pytest.mark.parametrize("case", ["null_edges", "subset_and_repeats"]) - def test_mutation_selection(self, inputs, started, case): - # mutations above the root have edge NULL and get NaN posteriors; the - # mutations are any edges, with repeats - ins = inputs["small_ts"] - edges = ins.mutations_edge(False).copy() - if case == "null_edges": - edges[::7] = tskit.NULL - else: - edges = edges[[5, 3, 3, 100, 5]] - compare_runs(ins, mutations_pass(edges, False), started["small_ts"]) - - -class TestMultiSweep: - """ - Whole sweeps from the initial state: the node posteriors, likelihood - normalisers and mutation posteriors of every sweep are identical to the oracle's. - """ - - CASES = { - "small_ts": ("small_ts", {}), - "small_ts_unphased": ("small_ts_unphased", {}), - "small_ts_historical_cap": ( - "small_ts_historical", - dict(max_shape=10.0, min_step=0.5, em_maxitt=3), - ), - } - - @staticmethod - def run(module, ins, sweeps, kwargs): - ep = module.ExpectationPropagation(**ins.kwargs()) - states = [] - for _ in range(sweeps): - ep_state.iterate(ep, ins, **kwargs) - states.append(ep_state.state(ep)) - mutations = [ - ep.propagate_mutations( - mutations_edge=ins.mutations_edge(unphased), unphased=unphased - ) - for unphased in (USE_BLOCK_LIKELIHOOD, USE_EDGE_LIKELIHOOD) - ] - return states, mutations - - @pytest.mark.parametrize("case", CASES) - def test_sweeps(self, inputs, case): - name, kwargs = self.CASES[case] - ins = inputs[name] - actual = self.run(_tsdate, ins, 4, kwargs) - expected = self.run(variational, ins, 4, kwargs) - for a, e in zip(actual[0], expected[0]): - for x, y in zip(a, e): # node posterior, edge and block lognorm - np.testing.assert_array_equal(x, y) - for a, e in zip(actual[1], expected[1]): # mutation posterior, phase - for x, y in zip(a, e): - np.testing.assert_array_equal(x, y) diff --git a/tests/test_python_c.py b/tests/test_python_c.py index 6735146a..81890492 100644 --- a/tests/test_python_c.py +++ b/tests/test_python_c.py @@ -363,10 +363,6 @@ def test_conditional_coalescent_variance(self): with pytest.raises(_tsdate.LibraryError, match="Too few tips"): _tsdate.conditional_coalescent_variance(0) - def test_marginalize_over_ancestors(self): - with pytest.raises(_tsdate.LibraryError, match="Too few tips"): - _tsdate.marginalize_over_ancestors(np.ones((1, 2))) - def test_piecewise_scale_point_estimate(self): with pytest.raises(_tsdate.LibraryError, match="No breakpoints"): _tsdate.piecewise_scale_point_estimate( @@ -1171,7 +1167,3 @@ def test_variance_one_tip(self): def test_variance_negative_tips(self): with pytest.raises(ValueError, match="non-negative"): _tsdate.conditional_coalescent_variance(-1) - - def test_fixed_changepoints_epochs_beyond_int64(self): - with pytest.raises(OverflowError): - _tsdate.fixed_changepoints(np.ones(3), 2**70) diff --git a/tests/test_python_c_approx.py b/tests/test_python_c_approx.py deleted file mode 100644 index 658547f8..00000000 --- a/tests/test_python_c_approx.py +++ /dev/null @@ -1,99 +0,0 @@ -""" -Tests of the low-level _tsdate module for the approx functions: error messages, -argument checking of the array-level function, and the test adapters. Numerical values -are tested against the oracles in test_oracle_approx.py. -""" - -import re - -import _tsdate -import numpy as np -import pytest -from oracle import approx -from oracle.helpers import compare - -# error code: message -APPROX_ERRORS = { - -6: "Nonpositive or nonfinite moments", - -7: "log E[t] <= E[log t] violates Jensen's inequality", - -8: "Maximum iterations reached in KL minimization", - -9: "Invalid shape parameter in KL minimization", - -10: "Nonpositive central moments", - -11: "Quantiles must be sorted", - -12: "Maximum iterations reached in quantile matching", - -13: "Negative shape parameter", - -14: "The mean and variance must be positive", - -15: "The age of a fixed node is outside the domain of the function", -} - - -class TestApproxErrors: - @pytest.mark.parametrize(("code", "message"), APPROX_ERRORS.items()) - def test_messages(self, code, message): - assert _tsdate.strerror(code) == message - with pytest.raises(_tsdate.LibraryError, match=re.escape(message)): - _tsdate.raise_library_error(code) - - -class TestAverageGammas: - def test_returns_floats(self): - alpha = np.array([0.5, 3.0]) - beta = np.array([1.0, 2.0]) - result = _tsdate.average_gammas(alpha, beta) - assert isinstance(result, tuple) - assert len(result) == 2 - assert all(isinstance(x, float) for x in result) - - def test_accepts_lists_and_integers(self): - assert _tsdate.average_gammas([1, 2], [1, 2]) == _tsdate.average_gammas( - np.array([1.0, 2.0]), np.array([1.0, 2.0]) - ) - - @pytest.mark.parametrize("shape", [(), (2, 2)]) - def test_wrong_dimension(self, shape): - with pytest.raises(ValueError): - _tsdate.average_gammas(np.ones(shape), np.ones(shape)) - - def test_wrong_dimension_second_argument(self): - with pytest.raises(ValueError): - _tsdate.average_gammas(np.ones(2), np.ones((2, 2))) - - def test_not_numeric(self): - with pytest.raises(ValueError): - _tsdate.average_gammas(["a"], [1.0]) - - def test_wrong_number_of_arguments(self): - with pytest.raises(TypeError): - _tsdate.average_gammas(np.ones(2)) - - -# Failures of the quantile fit (found by random search), each at a different step of -# the Newton iteration: the lower quantile underflows to zero, its square underflows -# to zero, and the iteration does not converge. -GAMMA_IQR_FAILURES = { - "lower quantile is zero": (1e-300, 1e-299, 1.0, 1e30, 50.0), - "lower quantile squared is zero": ( - 0.25, - 0.75, - 5.256386560310826e-218, - 9.53e-42, - 50.0, - ), - "no convergence": ( - 4.195119806947257e-42, - 1.3790748660114965e-37, - 1.656873535271179e-06, - 8.871129030923311e-06, - 1e7, - ), -} - - -class TestGammaIqrFailures: - @pytest.mark.parametrize("label", list(GAMMA_IQR_FAILURES)) - def test_failures(self, label): - args = GAMMA_IQR_FAILURES[label] - expected = compare( - _tsdate.approximate_gamma_iqr, approx.approximate_gamma_iqr, *args - ) - assert expected.exception is not None diff --git a/tests/test_python_c_scalar.py b/tests/test_python_c_scalar.py deleted file mode 100644 index 4e2da73b..00000000 --- a/tests/test_python_c_scalar.py +++ /dev/null @@ -1,82 +0,0 @@ -""" -Tests of the generic scalar-function wrapper of the low-level _tsdate module: argument -handling and return types. Numerical values and library errors are tested against the -oracles in test_oracle_*.py. -""" - -import math -import subprocess -import sys - -import _tsdate -import pytest - -SCALAR_FUNCTIONS = { - # name: (number of arguments, number of results, valid arguments) - "digamma": (1, 1, (1.5,)), - "trigamma": (1, 1, (1.5,)), - "betaln": (2, 1, (2.0, 3.0)), - "gammainc_der": (2, 1, (2.0, 1.5)), - "gammainc_inv": (2, 1, (2.0, 0.3)), - "hyperu_laplace": (3, 2, (1.0, 2.0, 1.0)), - "hyp1f1_laplace": (3, 1, (1.0, 2.0, 1.0)), - "hyp2f1_laplace": (4, 1, (1.0, 2.0, 3.0, 0.5)), -} - - -class TestScalarFunctions: - @pytest.mark.parametrize("name", SCALAR_FUNCTIONS) - def test_result_type(self, name): - _, num_results, args = SCALAR_FUNCTIONS[name] - result = getattr(_tsdate, name)(*args) - if num_results == 1: - assert isinstance(result, float) - else: - assert isinstance(result, tuple) - assert len(result) == num_results - assert all(isinstance(x, float) for x in result) - - def test_integers_accepted(self): - assert _tsdate.betaln(2, 3) == _tsdate.betaln(2.0, 3.0) - - @pytest.mark.parametrize("name", SCALAR_FUNCTIONS) - def test_wrong_number_of_arguments(self, name): - num_args, _, args = SCALAR_FUNCTIONS[name] - func = getattr(_tsdate, name) - with pytest.raises(TypeError, match=f"{name}.*{num_args} arguments"): - func() - with pytest.raises(TypeError, match=f"{name}.*{num_args} arguments"): - func(*args, 1.0) - - @pytest.mark.parametrize("name", SCALAR_FUNCTIONS) - def test_non_numeric_argument(self, name): - _, _, args = SCALAR_FUNCTIONS[name] - func = getattr(_tsdate, name) - with pytest.raises(TypeError): - func("x", *args[1:]) - with pytest.raises(TypeError): - func(*args[:-1], None) - - @pytest.mark.parametrize("name", SCALAR_FUNCTIONS) - def test_keyword_arguments_rejected(self, name): - _, _, args = SCALAR_FUNCTIONS[name] - with pytest.raises(TypeError): - getattr(_tsdate, name)(*args[:-1], x=args[-1]) - - -class TestScalarErrors: - def test_nan_is_not_an_error(self): - assert math.isnan(_tsdate.gammainc_inv(math.nan, 0.5)) - - -class TestScipyDependency: - def test_import_without_scipy(self): - code = ( - "import sys; sys.modules['scipy'] = None\n" - "import _tsdate; print(_tsdate.gammainc_inv(2.0, 0.5))" - ) - result = subprocess.run( - [sys.executable, "-c", code], capture_output=True, text=True - ) - assert result.returncode == 0, result.stderr - assert float(result.stdout) == _tsdate.gammainc_inv(2.0, 0.5) diff --git a/uv.lock b/uv.lock index 1aceac12..81544af6 100644 --- a/uv.lock +++ b/uv.lock @@ -2119,21 +2119,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8b/ff/904fb9a49fd78801d8f57c19f2193785e8dc242c0f077baf7949f65384a7/numcodecs-0.15.2-cp313-cp313-win_amd64.whl", hash = "sha256:b1c684e0c2113a06cf29263a4311c6f86c710ece72d0729a355bbdb2220e2328", size = 843902, upload-time = "2026-10-20T19:26:17.447Z" }, ] -[[package]] -name = "numdifftools" -version = "0.11.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "numpy", version = "2.5.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "scipy", version = "1.18.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c9/9a/cffaad9e8443d4e04f89f44b8ceb3a6886d6fb529737e6dacc0d2d70fbe0/numdifftools-0.11.2.tar.gz", hash = "sha256:0508bbcea72f4706d8f4d518812bec11949d75bd0656047777d4e36357322344", size = 82603, upload-time = "2026-10-25T23:11:52.281Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ce/7c/9f48699da472a5c5141bdf3f52ae1767a8cee76abfe8f5169705db58a734/numdifftools-0.11.2-py3-none-any.whl", hash = "sha256:1281419f8c63068bc41a0c8b1b52cd644582621f4208e61cbf80eaed5591585f", size = 97817, upload-time = "2026-10-25T23:11:50.92Z" }, -] - [[package]] name = "numpy" version = "2.4.6" @@ -3831,7 +3816,6 @@ dev = [ { name = "jupyter-book" }, { name = "matplotlib" }, { name = "msprime" }, - { name = "numdifftools" }, { name = "pandas" }, { name = "prek" }, { name = "pytest" }, @@ -3877,7 +3861,6 @@ packaging = [ test = [ { name = "matplotlib" }, { name = "msprime" }, - { name = "numdifftools" }, { name = "pytest" }, { name = "pytest-cov" }, { name = "pytest-xdist" }, @@ -3907,7 +3890,6 @@ dev = [ { name = "jupyter-book", specifier = "<2" }, { name = "matplotlib" }, { name = "msprime" }, - { name = "numdifftools" }, { name = "pandas" }, { name = "prek", specifier = "==0.3.3" }, { name = "pytest" }, @@ -3953,7 +3935,6 @@ packaging = [ test = [ { name = "matplotlib" }, { name = "msprime" }, - { name = "numdifftools" }, { name = "pytest" }, { name = "pytest-cov" }, { name = "pytest-xdist" }, From 78d8c8e5775107e1adb36716007547fd403df97a Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 17:26:09 -0800 Subject: [PATCH 52/56] Drop the mpmath dependency, which only the evaluation scripts use --- evaluation/requirements.txt | 1 + pyproject.toml | 1 - uv.lock | 11 ----------- 3 files changed, 1 insertion(+), 12 deletions(-) diff --git a/evaluation/requirements.txt b/evaluation/requirements.txt index 4a8f7d1c..0609b898 100644 --- a/evaluation/requirements.txt +++ b/evaluation/requirements.txt @@ -6,3 +6,4 @@ matplotlib pandas psutil scipy +mpmath diff --git a/pyproject.toml b/pyproject.toml index d68c9e69..6750e360 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,7 +50,6 @@ dependencies = [ "tskit>=1.0.0", "numpy", "scipy>=1.13.0", - "mpmath", "tqdm", "appdirs", ] diff --git a/uv.lock b/uv.lock index 81544af6..638c65a5 100644 --- a/uv.lock +++ b/uv.lock @@ -1893,15 +1893,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5d/57/3c4b1c6f2e0cc29ba023802458ea3d2a996f87085559e4a5f2192d549532/more_itertools-11.2.1-py3-none-any.whl", hash = "sha256:35a7377edd1dd6608dcb2cdf534ded55ea32d49448875ad042cd3f879fb1ded0", size = 74405, upload-time = "2026-10-14T18:50:29.116Z" }, ] -[[package]] -name = "mpmath" -version = "1.4.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c5/b0/6de8e78014ff1842a90cc9a56da6ccfb598a5390ed0257fcdb7d9680c18b/mpmath-1.4.1.tar.gz", hash = "sha256:efd6d1b75f09d69524a67609949812668b28e81ecbfe0ab449ced8c13e92642e", size = 2093211, upload-time = "2026-03-15T01:17:38.245Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/13/f2/abeec3db71d221ccd3cd89d206be1fabf5a3ee7178862f5fba23a59607e0/mpmath-1.4.1-py3-none-any.whl", hash = "sha256:dc4f0ea2304480d4a9a48a94c1020571558ade522b44a6912efac63a586e140f", size = 567787, upload-time = "2026-03-15T01:17:36.392Z" }, -] - [[package]] name = "msprime" version = "1.4.4" @@ -3798,7 +3789,6 @@ name = "tsdate" source = { editable = "." } dependencies = [ { name = "appdirs" }, - { name = "mpmath" }, { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, @@ -3874,7 +3864,6 @@ wheels = [ [package.metadata] requires-dist = [ { name = "appdirs" }, - { name = "mpmath" }, { name = "numpy" }, { name = "scipy", specifier = ">=1.13.0" }, { name = "tqdm" }, From 36ebcd1ddde19985435e09dfa572f139f944e9ea Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Fri, 27 Nov 2026 17:34:55 -0800 Subject: [PATCH 53/56] Call the library's scalar functions from the evaluation scripts with ctypes meson also builds the library as a shared library, which evaluation/clib.py loads with ctypes to call the scalar functions, which _tsdate no longer exports. numerical_accuracy.py uses it, and microbench.py calls the current module: the expectation propagation passes through _tsdate.ExpectationPropagation, and every function with keyword arguments. --- evaluation/README.md | 30 +- evaluation/clib.py | 132 ++++++++ evaluation/microbench.py | 534 +++++++++++++------------------ evaluation/numerical_accuracy.py | 79 ++--- lib/meson.build | 8 +- 5 files changed, 423 insertions(+), 360 deletions(-) create mode 100644 evaluation/clib.py diff --git a/evaluation/README.md b/evaluation/README.md index cebf40ea..1880a725 100644 --- a/evaluation/README.md +++ b/evaluation/README.md @@ -15,8 +15,9 @@ standard coalescent. | `accuracy.py` | Sweep a parameter (`sample_size`, `length`, `mutation_rate`, `max_iterations`) for `variational_gamma`, comparing estimated to true node times. `--modes true` dates the true topology; `inferred` dates a tsinfer topology and compares to best-matching true nodes via [tscompare](https://github.com/tskit-dev/tscompare) (see issue #301). Writes one row per node (`accuracy_*.csv`). It also compares mutation times (`mutations_*.csv`): sites with a single mutation are matched by position, and tsdate's posterior mean mutation time is compared with the midpoint of the true edge the mutation sits on (the best any method can do; the exact simulated time is also saved as `true_time_exact`). `plot.py` scores scatter, RMSE and bias against the midpoint but PIT and interval coverage against the exact time, since the posterior is for the realised mutation time; `--mutation-truth midpoint` or `exact` forces one truth everywhere. Mutation comparison needs no node matching in either mode. | | `afs.py` | Compare the observed site allele frequency spectrum with the expected one from branch lengths (branch AFS x mutation rate) in genomic windows, for the true times, the true topology dated by tsdate, and a tsinfer topology dated by tsdate. Writes `afs_*.csv`. | | `performance.py` | Wall time and peak RSS, each case in a fresh process. | -| `microbench.py` | Microbenchmarks of the array-level functions of `_tsdate` (EP passes, rescaling, phasing, `util`, `prior`), on simulated inputs at three sizes (see below). | -| `numerical_accuracy.py` | Accuracy of the special functions and gamma approximations (the scalar functions of `_tsdate`) per function and regime: worst error against mpmath, SciPy or closed forms, and violations of properties such as symmetry, monotonicity and continuity at switch points (see below). Not to be confused with `accuracy.py`, which scores dating. | +| `microbench.py` | Microbenchmarks of the functions of `_tsdate` (EP passes, rescaling, phasing, `util`, `prior`), on simulated inputs at three sizes (see below). | +| `numerical_accuracy.py` | Accuracy of the special functions and gamma approximations (the scalar functions of the C library, through `clib.py`) per function and regime: worst error against mpmath, SciPy or closed forms, and violations of properties such as symmetry, monotonicity and continuity at switch points (see below). Not to be confused with `accuracy.py`, which scores dating. | +| `clib.py` | The scalar functions of the C library, called with ctypes from the shared library that meson builds (see below). | | `compare.py` | Compares two `performance.py` CSVs case by case (see below). | | `plot.py` | Reads `results/*.csv` and writes PNGs: error/bias/interval coverage vs parameter (`accuracy_*_summary.png`: top row node times, bottom row mutation times), estimated-vs-true scatter (`accuracy_*_scatter.png`: columns are swept values, rows are node/mutation times for true/tsinferred topology), PIT calibration histograms (`accuracy_*_calibration.png`: node row, mutation row), AFS observed-vs-expected (`afs_*.png`), time and memory scaling. | | `validation.py` | Stub: numerical checks too slow for the unit tests (issue #384). | @@ -78,14 +79,14 @@ labels their figures "quick run" and names them `*_quick*.png`. ### Microbenchmarks of the C extension -`microbench.py` times each array-level entry point of the `_tsdate` extension on inputs built from +`microbench.py` times each function of the `_tsdate` extension on inputs built from simulated tree sequences (small/medium/large; the large case has ~560k edges, so the EP edge pass takes about a second). The EP state is produced by running `ExpectationPropagation.infer` for two iterations, and the functions are called as `iterate`/`infer`/`rescale` call them (edges with some nonzero-age samples, and -unphased singleton blocks). Arrays modified in place are copied before each repeat, -outside the timed region. Scalar functions (`approx`, `hypergeo`) are timed only -through the EP passes. +unphased singleton blocks). The EP passes update their state, so each repeat of a +pass gets a new `_tsdate.ExpectationPropagation`, iterated outside the timed region. +Scalar functions (`approx`, `hypergeo`) are timed only through the EP passes. ``` python evaluation/microbench.py --quick # smoke test @@ -100,16 +101,23 @@ machine. ### Accuracy of the special functions -`numerical_accuracy.py` measures the approximation error of the special functions in -`_tsdate` (digamma, trigamma, `betaln`, the incomplete gamma derivative and +`numerical_accuracy.py` measures the approximation error of the special functions of +the C library (digamma, trigamma, `betaln`, the incomplete gamma derivative and inverse, and the Laplace approximations to U, 1F1 and 2F1, including the unity limit of 2F1) and the gamma approximations (moment matching, gamma fits, closed forms of the moment functions) against mpmath, SciPy and closed forms. It also reports how often properties that the exact functions have are violated: symmetry, monotonicity, the Kummer transformation, continuity across a switch point. One row per function and regime gives -the worst error (`rel`, `abs`, `ulp`) or a violation `count`. The unit tests do not -check any of this (they check only agreement with the oracles), so the table is -where inaccurate regimes show up. +the worst error (`rel`, `abs`, `ulp`) or a violation `count`. The unit tests check the +library only at fixed points, so the table is where inaccurate regimes show up. + +The scalar functions are not part of the `_tsdate` module: `clib.py` calls them with +ctypes from the shared library that meson builds, so build it first +(`cd lib && meson setup build && ninja -C build`). `clib.py` names each function as in +C without the `tsd_` prefix; arguments are numbers (a two-element array is given as two +numbers), and the outputs come back as a float or a tuple, for example +`clib.hyp2f1_laplace(1.0, 2.0, 3.0, 0.5)`. Its table of signatures must match +`lib/tsdate.h`. ``` python evaluation/numerical_accuracy.py --quick # the computation takes seconds diff --git a/evaluation/clib.py b/evaluation/clib.py new file mode 100644 index 00000000..d03b5ab1 --- /dev/null +++ b/evaluation/clib.py @@ -0,0 +1,132 @@ +""" +The scalar functions of the C library (``lib/``), called with ctypes from the shared +library that meson builds (``cd lib && meson setup build && ninja -C build``), to +measure their accuracy by hand. They are not part of the ``_tsdate`` module, and the +signatures below must match ``lib/tsdate.h``: a mismatch is not detected and can +crash the interpreter. + +Each function is named as in C without the ``tsd_`` prefix and takes numbers: a +two-element array argument (natural parameters) is given as two numbers. It returns +its outputs as a float, or a tuple of floats with two-element outputs flattened, and +raises ``LibraryError`` for an error code. +""" + +import ctypes +import pathlib + +BUILD = pathlib.Path(__file__).parents[1] / "lib" / "build" + +# Arguments: "d" a double, "p" a two-element array of doubles; outputs: "o" a double, +# "O" a two-element array. Results: "error" (an error code; the outputs are the +# result), "double" or "flag" (the return value is the result; no outputs). +SIGNATURES = { + "digamma": ("d", "o", "error"), + "trigamma": ("d", "o", "error"), + "betaln": ("dd", "", "double"), + "gammainc_der": ("dd", "o", "error"), + "gammaincinv": ("dd", "", "double"), + "hyperu_laplace": ("ddd", "oo", "error"), + "hyp1f1_laplace": ("ddd", "o", "error"), + "hyp2f1_laplace": ("dddd", "o", "error"), + "approximate_log_moments": ("dd", "ooo", "error"), + "approximate_gamma_kl": ("dd", "O", "error"), + "approximate_gamma_mom": ("dd", "O", "error"), + "approximate_gamma_iqr": ("ddddd", "O", "error"), + "valid_moments": ("dd", "", "flag"), + "valid_gamma": ("dd", "", "flag"), + "valid_hyp1f1": ("ddd", "", "flag"), + "valid_hyperu": ("ddd", "", "flag"), + "valid_hyp2f1": ("dddd", "", "flag"), + "moments": ("dddddd", "ooooo", "error"), + "rootward_moments": ("ddddd", "ooo", "error"), + "leafward_moments": ("ddddd", "ooo", "error"), + "unphased_moments": ("dddddd", "ooooo", "error"), + "twin_moments": ("dddd", "ooo", "error"), + "sideways_moments": ("ddddd", "ooo", "error"), + "gamma_projection": ("ppp", "oOO", "error"), + "leafward_projection": ("dpp", "oO", "error"), + "rootward_projection": ("dpp", "oO", "error"), + "unphased_projection": ("ppp", "oOO", "error"), + "twin_projection": ("pp", "oO", "error"), + "sideways_projection": ("dpp", "oO", "error"), + "mutation_moments": ("dddddd", "oo", "error"), + "mutation_rootward_moments": ("ddddd", "oo", "error"), + "mutation_leafward_moments": ("ddddd", "oo", "error"), + "mutation_unphased_moments": ("dddddd", "ooo", "error"), + "mutation_twin_moments": ("dddd", "ooo", "error"), + "mutation_sideways_moments": ("ddddd", "ooo", "error"), + "mutation_edge_moments": ("dd", "oo", "error"), + "mutation_block_moments": ("dd", "ooo", "error"), + "mutation_gamma_projection": ("ppp", "oO", "error"), + "mutation_leafward_projection": ("dpp", "oO", "error"), + "mutation_rootward_projection": ("dpp", "oO", "error"), + "mutation_edge_projection": ("dd", "oO", "error"), + "mutation_unphased_projection": ("ppp", "oO", "error"), + "mutation_twin_projection": ("pp", "oO", "error"), + "mutation_sideways_projection": ("dpp", "oO", "error"), + "mutation_block_projection": ("dd", "oO", "error"), + "damp": ("ppd", "o", "error"), + "rescale": ("pd", "o", "error"), +} + +PAIR = ctypes.c_double * 2 +CTYPES = { + "d": ctypes.c_double, + "p": PAIR, + "o": ctypes.POINTER(ctypes.c_double), + "O": PAIR, +} +RESTYPES = {"error": ctypes.c_int, "double": ctypes.c_double, "flag": ctypes.c_int} + + +class LibraryError(Exception): + pass + + +def _load(): + for name in ["libtsdate.so", "libtsdate.dylib"]: + path = BUILD / name + if path.exists(): + return ctypes.CDLL(str(path)) + raise FileNotFoundError(f"No shared library in {BUILD}: build it with meson") + + +_lib = _load() +_lib.tsd_strerror.argtypes = [ctypes.c_int] +_lib.tsd_strerror.restype = ctypes.c_char_p + + +def _function(name, inputs, outputs, result): + func = getattr(_lib, "tsd_" + name) + func.argtypes = [CTYPES[kind] for kind in inputs + outputs] + func.restype = RESTYPES[result] + num_numbers = inputs.count("d") + 2 * inputs.count("p") + + def call(*numbers): + if len(numbers) != num_numbers: + raise TypeError(f"{name} takes {num_numbers} numbers") + numbers = [float(x) for x in numbers] + args = [] + for kind in inputs: + if kind == "d": + args.append(numbers.pop(0)) + else: + args.append(PAIR(numbers.pop(0), numbers.pop(0))) + outs = [ctypes.c_double() if kind == "o" else PAIR() for kind in outputs] + refs = [ctypes.byref(x) if kind == "o" else x for x, kind in zip(outs, outputs)] + ret = func(*args, *refs) + if result != "error": + return float(ret) + if ret != 0: + raise LibraryError(_lib.tsd_strerror(ret).decode()) + values = [] + for x, kind in zip(outs, outputs): + values.extend([x.value] if kind == "o" else list(x)) + return values[0] if len(values) == 1 else tuple(values) + + call.__name__ = name + return call + + +for _name, _signature in SIGNATURES.items(): + globals()[_name] = _function(_name, *_signature) diff --git a/evaluation/microbench.py b/evaluation/microbench.py index 002a5393..d6474c35 100644 --- a/evaluation/microbench.py +++ b/evaluation/microbench.py @@ -1,15 +1,14 @@ """ -Microbenchmarks of the array-level entry points of the `_tsdate` extension in tsdate -(the functions that take and return arrays). Inputs are built from simulated -tree sequences at several sizes, mirroring how the functions are called in -production. Scalar functions (approx, hypergeo) are not timed on their own: they are -exercised through the EP passes. Writes a table to stdout and, with --output, a CSV -to results/. - -Timing: each function is warmed up (one untimed call), then called `--repeats` times -on identical, freshly copied inputs (copies are made outside the timed region); the -median of `time.perf_counter` is reported. Very fast calls are batched, so that a -timed block lasts at least a few ms (reported times are per call). +Microbenchmarks of the functions of the `_tsdate` extension in tsdate. Inputs are built +from simulated tree sequences at several sizes, mirroring how the functions are called +in production. Scalar functions (approx, hypergeo) are not timed on their own: they are +exercised through the EP passes. Writes a table to stdout and, with --output, a CSV to +results/. + +Timing: each function is warmed up (one untimed call), then called `--repeats` times on +identical inputs (a new EP state for each call of an EP pass, made outside the timed +region); the median of `time.perf_counter` is reported. Very fast calls are batched, so +that a timed block lasts at least a few ms (reported times are per call). Example: python evaluation/microbench.py --repeats 7 --output microbench.csv @@ -38,48 +37,6 @@ MAX_BATCH = 1000 -def _with_factors(func, position): - """ - Wrap a `_tsdate` function so that it takes an ``EPFactors`` at `position`. - """ - - def wrapped(*args): - factors = args[position].arrays() - return func(*args[:position], factors, *args[position + 1 :]) - - return wrapped - - -def _functions(): - """ - The benchmarked functions of `_tsdate`, by the name the benchmarks use. - """ - import _tsdate - - return { - "propagate_likelihood": _with_factors(_tsdate.propagate_likelihood, 6), - "propagate_prior": _with_factors(_tsdate.propagate_prior, 2), - "propagate_mutations": _with_factors(_tsdate.propagate_mutations, 9), - "_block_singletons": _tsdate.block_singletons, - "reallocate_unphased": _tsdate.reallocate_unphased, - "_mutation_frequency": _tsdate.mutation_frequency, - "_split_disjoint_nodes": _tsdate.split_disjoint_nodes, - "_relabel_mutations_node": _tsdate.relabel_mutations_node, - "_constrain_ages": _tsdate.constrain_ages, - "_contains_unary_nodes": _tsdate.contains_unary_nodes, - "_marginalize_over_ancestors": _tsdate.marginalize_over_ancestors, - "conditional_coalescent_variance": _tsdate.conditional_coalescent_variance, - # rescaling - "mutational_area": _tsdate.mutational_area, - "mutational_timescale": _tsdate.mutational_timescale, - "piecewise_scale_point_estimate": _tsdate.piecewise_scale_point_estimate, - "piecewise_scale_posterior": _tsdate.piecewise_scale_posterior, - "_fixed_changepoints": _tsdate.fixed_changepoints, - "_poisson_changepoints": _tsdate.poisson_changepoints, - "_count_mutations": _tsdate.count_mutations, - } - - # --------------------------------------------------------------------------- # Inputs # --------------------------------------------------------------------------- @@ -104,19 +61,6 @@ def _with_ancient_samples(ts, fraction=0.1, seed=1): return tables.tree_sequence() -def _copy_factors(f): - from tsdate.variational import EPFactors - - g = EPFactors( - np.zeros((f.scale.size, 2)), f._p, f._c, f._j, f._k - ) # constraints only give the shape - g.node[:] = f.node - g.edge[:] = f.edge - g.block[:] = f.block - g.scale[:] = f.scale - return g - - def _run_ep(ts, singletons_phased, iterations): from tsdate.variational import ExpectationPropagation @@ -134,34 +78,93 @@ def _run_ep(ts, singletons_phased, iterations): return ep +def _iterated_state(ep, iterations, max_shape): + """ + A new ``_tsdate.ExpectationPropagation`` with the inputs of `ep` (a + ``tsdate.variational.ExpectationPropagation``), after `iterations` iterations + as in ``ExpectationPropagation.iterate`` + """ + import _tsdate + + from tsdate.variational import ( + LEAFWARD, + ROOTWARD, + USE_BLOCK_LIKELIHOOD, + USE_EDGE_LIKELIHOOD, + ) + + state = _tsdate.ExpectationPropagation( + constraints=ep.node_constraints, + edges_parent=ep.edge_parents, + edges_child=ep.edge_children, + edges_likelihood=ep.edge_likelihoods, + blocks_left=ep.block_nodes[ROOTWARD], + blocks_right=ep.block_nodes[LEAFWARD], + blocks_likelihood=ep.block_likelihoods, + ) + for _ in range(iterations): + for order, unphased in [ + (ep.block_order, USE_BLOCK_LIKELIHOOD), + (ep.edge_order, USE_EDGE_LIKELIHOOD), + ]: + state.propagate_likelihood( + order=order, unphased=unphased, max_shape=max_shape, min_step=0.1 + ) + state.propagate_prior( + free=ep.unconstrained_roots, max_shape=max_shape, em_maxitt=10, em_reltol=1e-8 + ) + state.rescale_factors() + return state + + @dataclasses.dataclass class Bench: """ - One benchmark: `make_args()` returns a fresh argument tuple (copying anything - mutated in place) for the function called `func` in the implementation. + One benchmark: `call(**make_kwargs())`, where `make_kwargs()` returns fresh + keyword arguments (with new copies of anything that the call changes). """ name: str - func: str - make_args: callable + call: callable + make_kwargs: callable note: str = "" -def _const(*args): - return lambda: args +def _const(**kwargs): + return lambda: kwargs + + +def _module_function(name): + import _tsdate + + return getattr(_tsdate, name) + + +def _sweep_kwargs(ts, parents=True): + """ + The edge, index and mutation arrays of `ts` as keyword arguments + """ + kwargs = dict( + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + ) + if not parents: + del kwargs["edges_parent"] + return kwargs def build_benchmarks(n, length, iterations): """ Build all benchmarks (and a dict describing the inputs) for one size. """ - from tsdate import phasing, rescaling, util - from tsdate.variational import ( - LEAFWARD, - ROOTWARD, - USE_BLOCK_LIKELIHOOD, - USE_EDGE_LIKELIHOOD, - ) + from tsdate import rescaling + from tsdate.variational import USE_BLOCK_LIKELIHOOD, USE_EDGE_LIKELIHOOD ts_flat = common.simulate(n, length, MUTATION_RATE, seed=1) # contemporary ts_old = _with_ancient_samples(ts_flat) # some samples with nonzero age @@ -176,197 +179,147 @@ def build_benchmarks(n, length, iterations): ) benches = [] add = benches.append + func = _module_function # --- variational.py, as in ExpectationPropagation.iterate/infer --- + # The passes update the state, so each call gets a new state, iterated outside + # the timed region. max_shape, min_step = 1000, 0.1 - for tag, ep, order, par, chi, lik, logc, unph in [ - ( - "edges", - ep_old, - ep_old.edge_order, - ep_old.edge_parents, - ep_old.edge_children, - ep_old.edge_likelihoods, - ep_old.edge_logconst, - USE_EDGE_LIKELIHOOD, - ), - ( - "blocks", - ep_flat, - ep_flat.block_order, - ep_flat.block_nodes[ROOTWARD], - ep_flat.block_nodes[LEAFWARD], - ep_flat.block_likelihoods, - ep_flat.block_logconst, - USE_BLOCK_LIKELIHOOD, - ), + + def propagate_likelihood(state, **kwargs): + state.propagate_likelihood(**kwargs) + + def propagate_prior(state, **kwargs): + state.propagate_prior(**kwargs) + + def propagate_mutations(state, **kwargs): + state.propagate_mutations(**kwargs) + + for tag, ep, order, unphased in [ + ("edges", ep_old, ep_old.edge_order, USE_EDGE_LIKELIHOOD), + ("blocks", ep_flat, ep_flat.block_order, USE_BLOCK_LIKELIHOOD), ]: - def likelihood_args( - ep=ep, order=order, par=par, chi=chi, lik=lik, logc=logc, unph=unph - ): - return ( - order, - par, - chi, - lik, - ep.node_constraints, - ep.node_posterior.copy(), - _copy_factors(ep.factors), - logc.copy(), - max_shape, - min_step, - unph, + def likelihood_kwargs(ep=ep, order=order, unphased=unphased): + return dict( + state=_iterated_state(ep, iterations, max_shape), + order=order, + unphased=unphased, + max_shape=max_shape, + min_step=min_step, ) add( - Bench(f"propagate_likelihood[{tag}]", "propagate_likelihood", likelihood_args) + Bench(f"propagate_likelihood[{tag}]", propagate_likelihood, likelihood_kwargs) ) - def prior_args(): - return ( - ep_old.unconstrained_roots, - ep_old.node_posterior.copy(), - _copy_factors(ep_old.factors), - max_shape, - 10, - 1e-8, + def prior_kwargs(): + return dict( + state=_iterated_state(ep_old, iterations, max_shape), + free=ep_old.unconstrained_roots, + max_shape=max_shape, + em_maxitt=10, + em_reltol=1e-8, ) - add(Bench("propagate_prior", "propagate_prior", prior_args)) + add(Bench("propagate_prior", propagate_prior, prior_kwargs)) - for tag, ep, unph in [ + # propagate_mutations does not change the state + for tag, ep, unphased in [ ("edges", ep_old, USE_EDGE_LIKELIHOOD), ("blocks", ep_flat, USE_BLOCK_LIKELIHOOD), ]: - phased = ep.mutation_blocks == tskit.NULL - if unph: - sel = ~phased - m_edges, par, chi = ( - ep.mutation_blocks, - ep.block_nodes[ROOTWARD], - ep.block_nodes[LEAFWARD], - ) - lik = ep.block_likelihoods + blocked = ep.mutation_blocks != tskit.NULL + if unphased: + mutations_edge = ep.mutation_blocks[blocked] else: - sel = phased - m_edges, par, chi = ep.mutation_edges, ep.edge_parents, ep.edge_children - lik = ep.edge_likelihoods - - def mutation_args( - ep=ep, sel=sel, m_edges=m_edges, par=par, chi=chi, lik=lik, unph=unph - ): - return ( - ep.mutation_order[sel], - ep.mutation_posterior.copy(), - ep.mutation_phase.copy(), - m_edges, - par, - chi, - lik, - ep.node_constraints, - ep.node_posterior, - ep.factors, - unph, + mutations_edge = ep.mutation_edges[~blocked] + add( + Bench( + f"propagate_mutations[{tag}]", + propagate_mutations, + _const(state=ep._ep, mutations_edge=mutations_edge, unphased=unphased), ) - - add(Bench(f"propagate_mutations[{tag}]", "propagate_mutations", mutation_args)) + ) # --- phasing.py --- - likelihoods = ep_flat.sizebiased_likelihoods + reallocate_kwargs = dict( + edges_likelihood=ep_flat.sizebiased_likelihoods, + mutations_phase=ep_flat.mutation_phase, + mutations_block=ep_flat.mutation_blocks, + blocks_edges=ep_flat.block_edges, + ) add( Bench( "reallocate_unphased", - "reallocate_unphased", - lambda: ( - likelihoods.copy(), - ep_flat.mutation_phase, - ep_flat.mutation_blocks, - ep_flat.block_edges, - ), + func("reallocate_unphased"), + _const(**reallocate_kwargs), ) ) - tree_args = ( - ts_flat.edges_parent, - ts_flat.edges_child, - ts_flat.edges_left, - ts_flat.edges_right, - ) - index_args = ( - ts_flat.indexes_edge_insertion_order, - ts_flat.indexes_edge_removal_order, - ) - muts_pos = ts_flat.sites_position[ts_flat.mutations_site] - nodes_individual = ts_flat.nodes_individual add( Bench( - "_block_singletons", - "_block_singletons", + "block_singletons", + func("block_singletons"), _const( - np.full(ts_flat.num_individuals, True), - nodes_individual, - ts_flat.mutations_node, - muts_pos, - *tree_args, - *index_args, - ts_flat.sequence_length, + individuals_unphased=np.full(ts_flat.num_individuals, True), + nodes_individual=ts_flat.nodes_individual, + **_sweep_kwargs(ts_flat, parents=False), + sequence_length=ts_flat.sequence_length, ), ) ) - nodes_sample = np.full((ts_flat.num_nodes, 1), False) - nodes_sample[list(ts_flat.samples()), 0] = True + nodes_sample = np.full(ts_flat.num_nodes, False) + nodes_sample[list(ts_flat.samples())] = True add( Bench( - "_mutation_frequency", - "_mutation_frequency", + "mutation_frequency", + func("mutation_frequency"), _const( - nodes_sample, - ts_flat.mutations_node, - muts_pos, - *tree_args, - *index_args, - ts_flat.sequence_length, + nodes_sample=nodes_sample[:, np.newaxis], + **_sweep_kwargs(ts_flat), + sequence_length=ts_flat.sequence_length, ), ) ) - node_is_sample = np.full(ts_flat.num_nodes, False) - node_is_sample[list(ts_flat.samples())] = True - # --- rescaling.py, as in ExpectationPropagation.rescale --- - rescale_lik = ep_flat.sizebiased_likelihoods.copy() - phasing.reallocate_unphased( - rescale_lik, - ep_flat.mutation_phase, - ep_flat.mutation_blocks, - ep_flat.block_edges, - ) + rescale_lik = func("reallocate_unphased")(**reallocate_kwargs) nodes_fixed = ep_flat.node_constraints[:, 0] == ep_flat.node_constraints[:, 1] nodes_time, _ = ep_flat.node_moments() - par, chi = ep_flat.edge_parents, ep_flat.edge_children + edges = dict(edges_parent=ep_flat.edge_parents, edges_child=ep_flat.edge_children) intervals = 1000 add( Bench( "mutational_area", - "mutational_area", - _const(nodes_time, rescale_lik, par, chi), + func("mutational_area"), + _const(nodes_time=nodes_time, edges_likelihood=rescale_lik, **edges), ) ) + timescale_kwargs = dict( + nodes_time=nodes_time, + edges_likelihood=rescale_lik, + nodes_fixed=nodes_fixed, + **edges, + max_intervals=intervals, + ) add( Bench( "mutational_timescale", - "mutational_timescale", - _const(nodes_time, rescale_lik, nodes_fixed, par, chi, intervals), + func("mutational_timescale"), + _const(**timescale_kwargs), ) ) - original_breaks, rescaled_breaks = rescaling.mutational_timescale( - nodes_time, rescale_lik, nodes_fixed, par, chi, intervals - ) + original_breaks, rescaled_breaks = rescaling.mutational_timescale(**timescale_kwargs) add( Bench( "piecewise_scale_point_estimate", - "piecewise_scale_point_estimate", - _const(nodes_time, nodes_fixed, original_breaks, rescaled_breaks), + func("piecewise_scale_point_estimate"), + _const( + point_estimate=nodes_time, + point_fixed=nodes_fixed, + original_breaks=original_breaks, + rescaled_breaks=rescaled_breaks, + ), ) ) rescaled_time = rescaling.piecewise_scale_point_estimate( @@ -382,123 +335,98 @@ def mutation_args( add( Bench( "piecewise_scale_posterior", - "piecewise_scale_posterior", + func("piecewise_scale_posterior"), _const( - ep_flat.node_posterior, nodes_fixed, orig, rescaled_breaks, 0.5, max_shape + posteriors=ep_flat.node_posterior, + posteriors_fixed=nodes_fixed, + original_breaks=orig, + rescaled_breaks=rescaled_breaks, + quantile_width=0.5, + max_shape=max_shape, ), ) ) - counts, offset, duration, _ = rescaling.mutational_area( - nodes_time, rescale_lik, par, chi - ) add( Bench( - "_fixed_changepoints", - "_fixed_changepoints", - _const(offset * duration, intervals), + "count_mutations", + func("count_mutations"), + _const( + nodes_sample=nodes_sample, + **_sweep_kwargs(ts_flat), + sequence_length=ts_flat.sequence_length, + size_biased=True, + ), ) ) - # Unused in production (only referenced in a TODO); cap its size as it is slow. - cap = 2000 - add( - Bench( - "_poisson_changepoints", - "_poisson_changepoints", - _const(counts[:cap], offset[:cap], 2.0, 0.0, 0.0), - note=f"unused in production; first {cap} intervals", - ) + + # --- util.py --- + tree = dict( + edges_parent=ts_flat.edges_parent, + edges_child=ts_flat.edges_child, + edges_left=ts_flat.edges_left, + edges_right=ts_flat.edges_right, ) + split_kwargs = dict(**tree, nodes_excluded=nodes_sample) add( Bench( - "_count_mutations", - "_count_mutations", - _const( - node_is_sample, - ts_flat.mutations_node, - muts_pos, - *tree_args, - *index_args, - ts_flat.sequence_length, - True, - ), + "split_disjoint_nodes", + func("split_disjoint_nodes"), + _const(**split_kwargs), ) ) - - # --- util.py --- - split_args = (*tree_args, node_is_sample) - add(Bench("_split_disjoint_nodes", "_split_disjoint_nodes", _const(*split_args))) - new_parent, new_child, nodes_order, split_nodes = util._split_disjoint_nodes( - *split_args + new_parent, new_child, nodes_order, split_nodes = func("split_disjoint_nodes")( + **split_kwargs ) info["num_split_nodes"] = len(split_nodes) + sweep = _sweep_kwargs(ts_flat) + sweep.update(edges_parent=new_parent, edges_child=new_child) add( Bench( - "_relabel_mutations_node", - "_relabel_mutations_node", - _const( - ts_flat.mutations_node, - muts_pos, - nodes_order, - new_parent, - new_child, - ts_flat.edges_left, - ts_flat.edges_right, - *index_args, - ), + "relabel_mutations_node", + func("relabel_mutations_node"), + _const(nodes_order=nodes_order, **sweep), ) ) rng = np.random.default_rng(1) noisy_time = ts_flat.nodes_time * np.exp(rng.normal(0, 0.3, ts_flat.num_nodes)) - noisy_time[node_is_sample] = ts_flat.nodes_time[node_is_sample] + noisy_time[nodes_sample] = ts_flat.nodes_time[nodes_sample] add( Bench( - "_constrain_ages", - "_constrain_ages", + "constrain_ages", + func("constrain_ages"), _const( - noisy_time, - node_is_sample, - ts_flat.edges_parent, - ts_flat.edges_child, - 1e-6, - 20, + nodes_time=noisy_time, + nodes_fixed=nodes_sample, + edges_parent=ts_flat.edges_parent, + edges_child=ts_flat.edges_child, + epsilon=1e-6, + max_iterations=20, ), note="noisy times violate constraints; 20 iterations", ) ) add( Bench( - "_contains_unary_nodes", - "_contains_unary_nodes", + "contains_unary_nodes", + func("contains_unary_nodes"), _const( - node_is_sample, - ts_flat.edges_parent, - ts_flat.edges_left, - ts_flat.edges_right, - *index_args, - ts_flat.sequence_length, - ts_flat.num_nodes, + nodes_mask=nodes_sample, + edges_parent=ts_flat.edges_parent, + edges_left=ts_flat.edges_left, + edges_right=ts_flat.edges_right, + indexes_insert=ts_flat.indexes_edge_insertion_order, + indexes_remove=ts_flat.indexes_edge_removal_order, + sequence_length=ts_flat.sequence_length, ), ) ) - # --- prior.py (prior tables are built for up to a few thousand tips) --- - num_tips = ts_flat.num_samples - coal_rates = np.array( - [2 / (i * (i - 1)) if i > 1 else 0.0 for i in range(1, num_tips + 1)] - ) - moments = np.stack((coal_rates, 2 * coal_rates**2), 1) # mean, second moment - add( - Bench( - "_marginalize_over_ancestors", - "_marginalize_over_ancestors", - _const(moments), - ) - ) + # --- prior.py --- add( Bench( "conditional_coalescent_variance", - "conditional_coalescent_variance", - _const(np.uint64(num_tips)), + func("conditional_coalescent_variance"), + _const(num_tips=ts_flat.num_samples), ) ) @@ -510,25 +438,25 @@ def mutation_args( # --------------------------------------------------------------------------- -def time_bench(func, bench, repeats): +def time_bench(bench, repeats): """ Warm up, then return per-call times (seconds) for `repeats` timed blocks. """ t0 = time.perf_counter() - func(*bench.make_args()) # warm up (also the first-call cost) + bench.call(**bench.make_kwargs()) # warm up (also the first-call cost) first_call = time.perf_counter() - t0 # estimate the cost of one call to choose a batch size - args = bench.make_args() + kwargs = bench.make_kwargs() t0 = time.perf_counter() - func(*args) + bench.call(**kwargs) one = time.perf_counter() - t0 batch = int(min(MAX_BATCH, max(1, math.ceil(MIN_BLOCK_S / max(one, 1e-9))))) times = [] for _ in range(repeats): - batch_args = [bench.make_args() for _ in range(batch)] + batch_kwargs = [bench.make_kwargs() for _ in range(batch)] t0 = time.perf_counter() - for a in batch_args: - func(*a) + for kwargs in batch_kwargs: + bench.call(**kwargs) times.append((time.perf_counter() - t0) / batch) return times, first_call, batch @@ -575,8 +503,6 @@ def main(): if args.quick: sizes, args.repeats, args.ep_iterations = QUICK_SIZES, 1, 1 - funcs = _functions() - prov = common.provenance() rows = [] for size, (n, length) in sizes.items(): @@ -590,7 +516,7 @@ def main(): for bench in benches: if args.only and not any(s in bench.name for s in args.only): continue - times, first, batch = time_bench(funcs[bench.func], bench, args.repeats) + times, first, batch = time_bench(bench, args.repeats) row = dict( function=bench.name, size=size, diff --git a/evaluation/numerical_accuracy.py b/evaluation/numerical_accuracy.py index 516cfdc9..c4fb5bf0 100644 --- a/evaluation/numerical_accuracy.py +++ b/evaluation/numerical_accuracy.py @@ -1,12 +1,12 @@ """ -Numerical accuracy of the special functions and gamma approximations in tsdate -(the scalar functions of ``_tsdate``), per function and regime. Each row of the -table reports the worst error of the production function against a reference (mpmath, -SciPy, a closed form) or the violation of a property the approximation should have -(symmetry, monotonicity, continuity across a switch point). These are measurements, not -tests: the unit tests only check that the C implementation agrees with the oracles, so -inaccuracy of the algorithms themselves is recorded here. Behaviour that looks wrong -is a candidate for a fix. +Numerical accuracy of the special functions and gamma approximations in tsdate (the +scalar functions of the C library, called through ``clib``), per function and regime. +Each row of the table reports the worst error of the production function against a +reference (mpmath, SciPy, a closed form) or the violation of a property the +approximation should have (symmetry, monotonicity, continuity across a switch point). +These are measurements, not tests: the unit tests check the C library at fixed points, +so inaccuracy of the algorithms across regimes is recorded here. Behaviour that looks +wrong is a candidate for a fix. Errors are relative unless the metric says "abs" (log-scale quantities such as log U, log 1F1 and log 2F1 are compared in absolute terms), "ulp" or "count". @@ -21,7 +21,7 @@ import math import pathlib -import _tsdate +import clib import mpmath import numpy as np import scipy.special @@ -119,18 +119,18 @@ def mp_psi(n, x): def polygamma(report): for name, order in [("_digamma", 0), ("_trigamma", 1)]: - func = getattr(_tsdate, name.lstrip("_")) + func = getattr(clib, name.lstrip("_")) for regime, xs in POLYGAMMA_REGIMES.items(): errors = [rel(try_call(func, x), mp_psi(order, x)) for x in xs] report.worst("polygamma", name, regime, "rel", errors) # trigamma returns 1 / x**2 for x <= 1e-4, omitting pi**2 / 6 xs = [1e-6, 1e-5, 1e-4] - errors = [rel(try_call(_tsdate.trigamma, x), mp_psi(1, x)) for x in xs] + errors = [rel(try_call(clib.trigamma, x), mp_psi(1, x)) for x in xs] report.worst("polygamma", "_trigamma", "x <= 1e-4 (1/x**2)", "rel", errors) # continuity at the switch points of the series for x in [1e-5, 8.5]: - lo = _tsdate.digamma(x) - hi = _tsdate.digamma(np.nextafter(x, 2 * x)) + lo = clib.digamma(x) + hi = clib.digamma(np.nextafter(x, 2 * x)) report.add("polygamma", "_digamma", f"jump at x={x}", "rel", rel(lo, hi)) @@ -143,7 +143,7 @@ def betaln(report): for regime, points in regimes.items(): errors = [] for p, q in points: - errors.append(rel(try_call(_tsdate.betaln, p, q), scipy.special.betaln(p, q))) + errors.append(rel(try_call(clib.betaln, p, q), scipy.special.betaln(p, q))) report.worst("betaln", "_betaln", regime, "rel", errors) @@ -168,10 +168,10 @@ def gammainc_der(report): errors = [] for p, x in points: ref = gammainc_der_reference(p, x) - errors.append(rel(try_call(_tsdate.gammainc_der, p, x), ref)) + errors.append(rel(try_call(clib.gammainc_der, p, x), ref)) report.worst("gammainc", "_gammainc_der", regime, "rel", errors) - below = _tsdate.gammainc_der(1000.0, 1000.0) - above = _tsdate.gammainc_der(np.nextafter(1000.0, 2000.0), 1000.0) + below = clib.gammainc_der(1000.0, 1000.0) + above = clib.gammainc_der(np.nextafter(1000.0, 2000.0), 1000.0) report.add("gammainc", "_gammainc_der", "jump at p = 1000", "rel", rel(above, below)) @@ -192,7 +192,7 @@ def f(t): def gammainc_inv(report, rng, quick): - func = _tsdate.gammainc_inv + func = clib.gammaincinv n = 10 if quick else 40 for a in [0.1, 0.3, 1.0, 2.5, 10.0, 60.0, 1e3, 1e4]: errors = [] @@ -265,7 +265,7 @@ def absolute(func, reference, points): def hyperu(report): - func = _tsdate.hyperu_laplace + func = clib.hyperu_laplace regimes = { "a >= 1 (EP: a = y + 1)": [(1.0, 2.0, 1.0), (2.0, 5.0, 0.5), (5.0, 15.0, 1.0)] + [(10.0, 20.0, 50.0), (50.0, 60.0, 1.0), (1000.0, 1010.0, 1e4)], @@ -328,7 +328,7 @@ def hyperu(report): def hyp1f1(report): - func = _tsdate.hyp1f1_laplace + func = clib.hyp1f1_laplace regimes = { "moderate": [ (1.0, 2.0, 1.0), @@ -361,7 +361,7 @@ def hyp1f1(report): def hyp2f1(report, quick): - func = _tsdate.hyp2f1_laplace + func = clib.hyp2f1_laplace zs = [(-1e9,), (-100.0,), (-1.0,), (0.5,), (0.9,), (0.99,), (0.99998,), (0.999999,)] abcs = { "(1, 2, 3)": (1.0, 2.0, 3.0), @@ -444,7 +444,7 @@ def gamma_quantiles(shape, rate, q1=0.25, q2=0.75): def gamma_fits(report, rng, quick): - kl = _tsdate.approximate_gamma_kl + kl = clib.approximate_gamma_kl errors, residuals = [], [] for x, gap in [ (1.0, 1e-3), @@ -473,13 +473,13 @@ def gamma_fits(report, rng, quick): ) errors = [] for mean, variance in [(1.0, 1.0), (10.0, 4.0), (1e3, 1e-6), (1e-3, 1e-3)]: - shape, rate = _tsdate.approximate_gamma_mom(mean, variance) + shape, rate = clib.approximate_gamma_mom(mean, variance) errors += [rel((shape + 1) / rate, mean), rel((shape + 1) / rate**2, variance)] report.worst( "approx", "approximate_gamma_mom", "mean and variance matched", "rel", errors ) mean, variance = 3.0, 0.5 - logx, xlogx, logx2 = _tsdate.approximate_log_moments(mean, variance) + logx, xlogx, logx2 = clib.approximate_log_moments(mean, variance) expected = ( math.log(mean) - 0.5 * variance / mean**2, mean * math.log(mean) + 0.5 * variance / mean, @@ -494,7 +494,7 @@ def gamma_fits(report, rng, quick): errors = [] for shape in shapes: args = (*gamma_quantiles(shape, 0.001), max_shape) - result = try_call(_tsdate.approximate_gamma_iqr, *args) + result = try_call(clib.approximate_gamma_iqr, *args) errors.append( None if result is None else rel(result[0] + 1.0, min(shape, max_shape)) ) @@ -505,21 +505,12 @@ def gamma_fits(report, rng, quick): "rel", errors, ) - errors = [ - rel(_tsdate.average_gammas(np.full(3, s), np.full(3, r))[0] + 1.0, s + 1.0) - for s, r in [(3.0, 0.5), (0.5, 2.0)] - ] - report.worst("approx", "average_gammas", "identical gammas recovered", "rel", errors) - shape, rate = _tsdate.average_gammas(np.array([0.0]), np.array([1.0])) - report.add( - "approx", "average_gammas", "single gamma, shape 1", "rel", rel(shape + 1.0, 1.0) - ) def moment_functions(report, quick): a_i, b_i, y, mu = 10.0, 0.01, 3.0, 1e-4 s, r = a_i + y, b_i + 2 * mu - got = _tsdate.twin_moments(a_i, b_i, y, mu) + got = clib.twin_moments(a_i, b_i, y, mu) expected = (math.log(2) * y + math.lgamma(s) - math.log(r) * s, s / r, s / r**2) report.worst( "approx", @@ -529,10 +520,10 @@ def moment_functions(report, quick): [rel(g, e) for g, e in zip(got, expected)], ) t_i, t_j = 7.0, 2.0 - mn, va = _tsdate.mutation_edge_moments(t_i, t_j) + mn, va = clib.mutation_edge_moments(t_i, t_j) errors = [rel(mn, 4.5), rel(va, 25.0 / 12.0)] report.worst("approx", "mutation_edge_moments", "closed form", "rel", errors) - pr, mn, va = _tsdate.mutation_block_moments(t_i, t_j) + pr, mn, va = clib.mutation_block_moments(t_i, t_j) errors = [rel(pr, 7.0 / 9.0), rel(mn, pr * t_i / 2 + (1 - pr) * t_j / 2)] report.worst("approx", "mutation_block_moments", "closed form", "rel", errors) # rootward with t_j -> 0 approaches the gamma with shape a_i + y, rate b_i + mu @@ -540,7 +531,7 @@ def moment_functions(report, quick): s, r = a_i + y, b_i + mu exact = (math.lgamma(s) - s * math.log(r), s / r, s / r**2) for t_j in [1e-10, 1e-3]: - got = _tsdate.rootward_moments(t_j, a_i, b_i, y, mu) + got = clib.rootward_moments(t_j, a_i, b_i, y, mu) report.add( "approx", "rootward_moments", @@ -557,7 +548,7 @@ def moment_functions(report, quick): ) # y = 0: U(a, a + 1, z) = z**-a a_j, b_j, mu, t_i = 10.0, 0.01, 1e-4, 1000.0 - logl, mn, va = _tsdate.sideways_moments(t_i, a_j, b_j, 0.0, mu) + logl, mn, va = clib.sideways_moments(t_i, a_j, b_j, 0.0, mu) z = t_i * (mu + b_j) f0 = logl + mu * t_i - a_j * math.log(t_i) - math.lgamma(a_j) report.add( @@ -565,8 +556,8 @@ def moment_functions(report, quick): ) # projected gammas reproduce the moments args = (10.0, 0.01, 10.0, 0.01, 1.0, 1e-4) - _, mn_i, va_i, mn_j, va_j = _tsdate.moments(*args) - _, *flat = _tsdate.gamma_projection(9.0, 0.01, 9.0, 0.01, 1.0, 1e-4) + _, mn_i, va_i, mn_j, va_j = clib.moments(*args) + _, *flat = clib.gamma_projection(9.0, 0.01, 9.0, 0.01, 1.0, 1e-4) proj_i = flat[0:2] proj_j = flat[2:4] errors = [] @@ -583,7 +574,7 @@ def moment_functions(report, quick): ("moments", (1e8, 1e5, 1e8, 1e5, 1, 1e-4)), ("moments", (10, 0.01, 10, 0.01, 1, 1e-4)), ]: - va = getattr(_tsdate, name)(*[float(a) for a in args])[2] + va = getattr(clib, name)(*[float(a) for a in args])[2] regime = "shape 1e8" if args[0] == 1e8 else "typical" report.add( "approx", @@ -600,7 +591,7 @@ def moment_functions(report, quick): a_i, a_j = rng.uniform(0.5, 30, 2) b_i, b_j = log_uniform(rng, -5, -2, 2) y, mu = float(rng.integers(0, 12)), log_uniform(rng, -4, -2) - result = _tsdate.moments(a_i, b_i, a_j, b_j, y, mu) + result = clib.moments(a_i, b_i, a_j, b_j, y, mu) count += not (result[2] > 0 and result[4] > 0) report.add( "approx", @@ -615,7 +606,7 @@ def moment_functions(report, quick): a_i, a_j = rng.uniform(0.5, 30, 2) b_i, b_j = log_uniform(rng, -5, -2, 2) y, mu = float(rng.integers(0, 12)), log_uniform(rng, -4, -2) - pr = _tsdate.mutation_unphased_moments(a_i, b_i, a_j, b_j, y, mu)[0] + pr = clib.mutation_unphased_moments(a_i, b_i, a_j, b_j, y, mu)[0] count += not (0 <= pr <= 1) report.add( "approx", diff --git a/lib/meson.build b/lib/meson.build index 25a02366..2ba47752 100644 --- a/lib/meson.build +++ b/lib/meson.build @@ -11,14 +11,20 @@ extra_c_args = [ '-Wcast-qual', '-Wwrite-strings', '-Wnested-externs', '-fshort-enums', '-fno-common', '-ffp-contract=off'] +test_c_args = extra_c_args if get_option('buildtype') == 'debug' - extra_c_args += ['-DTSD_TRACE_ERRORS'] + test_c_args += ['-DTSD_TRACE_ERRORS'] endif tsdate_sources = ['err.c', 'gammaincinv.c', 'hypergeo.c', 'approx.c', 'rescaling.c', 'phasing.c', 'util.c', 'prior.c', 'variational.c'] tsdate_lib = static_library('tsdate', + sources: tsdate_sources, dependencies: [m_dep], + c_args: test_c_args) + +# For calling the library from Python with ctypes (evaluation/clib.py) +tsdate_shared = shared_library('tsdate', sources: tsdate_sources, dependencies: [m_dep], c_args: extra_c_args) From 1c9b99a946c80a8a5c41d3aa66fd060b8a3900e5 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Sat, 28 Nov 2026 11:11:19 -0800 Subject: [PATCH 54/56] Put the bad edge of the reallocation error test in a block that has a mutation The library checks the edges of a block only when a mutation is in it, and block 0 of the test's tree sequence need not hold one (it does not on Windows). --- tests/test_python_c.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/test_python_c.py b/tests/test_python_c.py index 81890492..bc50b077 100644 --- a/tests/test_python_c.py +++ b/tests/test_python_c.py @@ -993,6 +993,14 @@ def first_blocked(kwargs): return np.flatnonzero(kwargs["mutations_block"] >= 0)[0] +def first_block(kwargs): + """ + The block of the first mutation of ``reallocate_unphased``'s arguments that is in + a block + """ + return kwargs["mutations_block"][first_blocked(kwargs)] + + def edit(arg, change): """ An edit of the keyword arguments that sets ``arg`` to ``change(kwargs)`` @@ -1047,7 +1055,7 @@ def reversed_ages(kwargs): ), "reallocate_edge_of_block": ( "reallocate_unphased", - with_entry("blocks_edges", 0, 10**6), + with_entry("blocks_edges", first_block, 10**6), ERR_BLOCK_OUT_OF_BOUNDS, ), "reallocate_phase": ( From 29ab5221e837cbac8da8fa8f14c4b66b9e18ce97 Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Sat, 28 Nov 2026 11:23:33 -0800 Subject: [PATCH 55/56] Write the tests of the _tsdate module out explicitly Each function has a class of plain tests: the arrays that must have the same size, and each library error, with the arguments built inline. The tables of argument specifications and edit combinators are gone. Argument parsing and the checks of edge sweeps are parametrised over the functions, each with a function that returns valid keyword arguments. --- tests/test_python_c.py | 1577 ++++++++++++++++++++-------------------- 1 file changed, 795 insertions(+), 782 deletions(-) diff --git a/tests/test_python_c.py b/tests/test_python_c.py index bc50b077..3a5ed56b 100644 --- a/tests/test_python_c.py +++ b/tests/test_python_c.py @@ -1,5 +1,6 @@ """ -Tests for the low-level _tsdate C module. +Tests for the low-level _tsdate C module: argument handling, and each library error +through each function that reports it. """ import re @@ -9,8 +10,6 @@ import numpy as np import pytest -import tsdate - ERR_GENERIC = -1 ERR_NO_MEMORY = -2 ERR_BAD_PARAM = -3 @@ -43,6 +42,15 @@ def raises_library_error(code): return pytest.raises(_tsdate.LibraryError, match=re.escape(_tsdate.strerror(code))) +def with_entry(array, index, value): + """ + A copy of ``array`` with entry ``index`` set to ``value`` + """ + array = array.copy() + array[index] = value + return array + + class TestModule: def test_name(self): assert _tsdate.__name__ == "_tsdate" @@ -98,287 +106,835 @@ def test_bad_argument(self): _tsdate.raise_library_error("x") -@pytest.fixture(scope="module") -def ts(): - """ - A small tree sequence with recombination, mutations and two diploid individuals - """ - ts = msprime.sim_ancestry( +# Two diploid individuals, with recombination (seven trees) and mutations +TS = msprime.sim_mutations( + msprime.sim_ancestry( 2, sequence_length=1e4, recombination_rate=1e-8, population_size=1e4, random_seed=2, + ), + rate=1e-7, + random_seed=2, +) +SAMPLES = np.isin(np.arange(TS.num_nodes), TS.samples()) + + +# Valid keyword arguments of each function, in the order of its parameters + + +def block_singletons_kwargs(): + return dict( + individuals_unphased=np.ones(TS.num_individuals, dtype=bool), + nodes_individual=TS.nodes_individual, + mutations_node=TS.mutations_node, + mutations_position=TS.sites_position[TS.mutations_site], + edges_child=TS.edges_child, + edges_left=TS.edges_left, + edges_right=TS.edges_right, + indexes_insert=TS.indexes_edge_insertion_order, + indexes_remove=TS.indexes_edge_removal_order, + sequence_length=TS.sequence_length, ) - return msprime.sim_mutations(ts, rate=1e-7, random_seed=2) -def bad_ids(ids, value): - """ - A copy of ``ids`` with the last entry replaced by ``value`` - """ - ids = ids.copy() - ids[-1] = value - return ids +def reallocate_unphased_kwargs(): + # one block of edges 0 and 1, with two mutations, and a mutation in no block + return dict( + edges_likelihood=np.array([[2.0, 5.0], [0.0, 5.0], [1.0, 5.0]]), + mutations_phase=np.array([0.25, 0.5, np.nan]), + mutations_block=np.array([0, 0, -1], dtype=np.int32), + blocks_edges=np.array([[0, 1]], dtype=np.int32), + ) -def sweep_args(ts, **replace): - """ - The edge arrays of ``ts`` used by a sweep over its trees, with replacements - """ - args = { - "edges_parent": ts.edges_parent, - "edges_child": ts.edges_child, - "edges_left": ts.edges_left, - "edges_right": ts.edges_right, - "insert": ts.indexes_edge_insertion_order, - "remove": ts.indexes_edge_removal_order, - "mutations_node": ts.mutations_node, - } - args.update(replace) - return args +def mutation_frequency_kwargs(): + return dict( + nodes_sample=SAMPLES[:, np.newaxis], + mutations_node=TS.mutations_node, + mutations_position=TS.sites_position[TS.mutations_site], + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + edges_left=TS.edges_left, + edges_right=TS.edges_right, + indexes_insert=TS.indexes_edge_insertion_order, + indexes_remove=TS.indexes_edge_removal_order, + sequence_length=TS.sequence_length, + ) + + +def split_disjoint_nodes_kwargs(): + return dict( + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + edges_left=TS.edges_left, + edges_right=TS.edges_right, + nodes_excluded=SAMPLES, + ) + + +def relabel_mutations_node_kwargs(): + return dict( + mutations_node=TS.mutations_node, + mutations_position=TS.sites_position[TS.mutations_site], + nodes_order=np.arange(TS.num_nodes, dtype=np.int32), + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + edges_left=TS.edges_left, + edges_right=TS.edges_right, + indexes_insert=TS.indexes_edge_insertion_order, + indexes_remove=TS.indexes_edge_removal_order, + ) + + +def constrain_ages_kwargs(): + return dict( + nodes_time=TS.nodes_time, + nodes_fixed=SAMPLES, + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + epsilon=1e-6, + max_iterations=2, + ) + + +def contains_unary_nodes_kwargs(): + return dict( + nodes_mask=SAMPLES, + edges_parent=TS.edges_parent, + edges_left=TS.edges_left, + edges_right=TS.edges_right, + indexes_insert=TS.indexes_edge_insertion_order, + indexes_remove=TS.indexes_edge_removal_order, + sequence_length=TS.sequence_length, + ) -def call_sweep(name, ts, a): +def conditional_coalescent_variance_kwargs(): + return dict(num_tips=5) + + +def count_mutations_kwargs(): + return dict( + nodes_sample=SAMPLES, + mutations_node=TS.mutations_node, + mutations_position=TS.sites_position[TS.mutations_site], + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + edges_left=TS.edges_left, + edges_right=TS.edges_right, + indexes_insert=TS.indexes_edge_insertion_order, + indexes_remove=TS.indexes_edge_removal_order, + sequence_length=TS.sequence_length, + size_biased=True, + ) + + +def mutational_area_kwargs(): + return dict( + nodes_time=TS.nodes_time, + edges_likelihood=np.ones((TS.num_edges, 2)), + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + ) + + +def mutational_timescale_kwargs(): + return dict( + nodes_time=TS.nodes_time, + edges_likelihood=np.ones((TS.num_edges, 2)), + nodes_fixed=SAMPLES, + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + max_intervals=3, + ) + + +def piecewise_scale_point_estimate_kwargs(): + return dict( + point_estimate=np.array([0.0, 0.5, 5.0]), + point_fixed=np.array([True, False, False]), + original_breaks=np.array([0.0, 1.0, 10.0]), + rescaled_breaks=np.array([0.0, 2.0, 20.0]), + ) + + +def piecewise_scale_posterior_kwargs(): + return dict( + posteriors=np.ones((3, 2)), + posteriors_fixed=np.array([False, False, True]), + original_breaks=np.array([0.0, 1.0, 10.0]), + rescaled_breaks=np.array([0.0, 2.0, 20.0]), + quantile_width=0.5, + max_shape=1000.0, + ) + + +def constraints_are_consistent_kwargs(): + constraints = np.zeros((TS.num_nodes, 2)) + constraints[~SAMPLES, 1] = np.inf + return dict( + constraints=constraints, + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + ) + + +def names(functions): """ - Call the sweep function ``name`` with the arrays ``a`` + The names of the functions of a list of (function, make_kwargs), as test ids """ - position = ts.sites_position[ts.mutations_site] - edges = (a["edges_parent"], a["edges_child"], a["edges_left"], a["edges_right"]) - indexes = (a["insert"], a["remove"]) - if name == "count_mutations": - sample = np.zeros(ts.num_nodes, dtype=bool) - sample[ts.samples()] = True - return _tsdate.count_mutations( - sample, - a["mutations_node"], - position, - *edges, - *indexes, - ts.sequence_length, - True, - ) - if name == "mutation_frequency": - sample = np.zeros((ts.num_nodes, 1), dtype=bool) - sample[ts.samples(), 0] = True - return _tsdate.mutation_frequency( - sample, a["mutations_node"], position, *edges, *indexes, ts.sequence_length - ) - if name == "block_singletons": - return _tsdate.block_singletons( - np.ones(ts.num_individuals, dtype=bool), - ts.nodes_individual, - a["mutations_node"], - position, - *edges[1:], - *indexes, - ts.sequence_length, - ) - if name == "contains_unary_nodes": - return _tsdate.contains_unary_nodes( - np.zeros(ts.num_nodes, dtype=bool), - a["edges_parent"], - a["edges_left"], - a["edges_right"], - *indexes, - ts.sequence_length, - ) - assert name == "relabel_mutations_node" - return _tsdate.relabel_mutations_node( - a["mutations_node"], - position, - np.arange(ts.num_nodes, dtype=np.int32), - *edges, - *indexes, - ) + return [function.__name__ for function, _ in functions] -SWEEPS = [ - "count_mutations", - "mutation_frequency", - "block_singletons", - "contains_unary_nodes", - "relabel_mutations_node", +FUNCTIONS = [ + (_tsdate.block_singletons, block_singletons_kwargs), + (_tsdate.reallocate_unphased, reallocate_unphased_kwargs), + (_tsdate.mutation_frequency, mutation_frequency_kwargs), + (_tsdate.split_disjoint_nodes, split_disjoint_nodes_kwargs), + (_tsdate.relabel_mutations_node, relabel_mutations_node_kwargs), + (_tsdate.constrain_ages, constrain_ages_kwargs), + (_tsdate.contains_unary_nodes, contains_unary_nodes_kwargs), + (_tsdate.conditional_coalescent_variance, conditional_coalescent_variance_kwargs), + (_tsdate.count_mutations, count_mutations_kwargs), + (_tsdate.mutational_area, mutational_area_kwargs), + (_tsdate.mutational_timescale, mutational_timescale_kwargs), + (_tsdate.piecewise_scale_point_estimate, piecewise_scale_point_estimate_kwargs), + (_tsdate.piecewise_scale_posterior, piecewise_scale_posterior_kwargs), + (_tsdate.constraints_are_consistent, constraints_are_consistent_kwargs), ] -class TestBadTreeArguments: +@pytest.mark.parametrize(("function", "make_kwargs"), FUNCTIONS, ids=names(FUNCTIONS)) +class TestArguments: """ - The library's errors for ids out of bounds and for edges that cannot be swept + The parsing of the arguments of each function: counts, keywords and types """ - @pytest.mark.parametrize("name", SWEEPS) - def test_valid(self, ts, name): - call_sweep(name, ts, sweep_args(ts)) + def test_keywords(self, function, make_kwargs): + function(**make_kwargs()) - @pytest.mark.parametrize("name", sorted(set(SWEEPS) - {"block_singletons"})) - @pytest.mark.parametrize("value", [-1, 2**30]) - def test_parent_out_of_bounds(self, ts, name, value): - a = sweep_args(ts, edges_parent=bad_ids(ts.edges_parent, value)) - with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): - call_sweep(name, ts, a) + def test_positional(self, function, make_kwargs): + args = list(make_kwargs().values()) + function(*args) - @pytest.mark.parametrize("name", sorted(set(SWEEPS) - {"contains_unary_nodes"})) - def test_mutation_node_out_of_bounds(self, ts, name): - a = sweep_args(ts, mutations_node=bad_ids(ts.mutations_node, ts.num_nodes)) - with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): - call_sweep(name, ts, a) + def test_too_few_arguments(self, function, make_kwargs): + args = list(make_kwargs().values()) + with pytest.raises(TypeError): + function(*args[:-1]) + + def test_too_many_arguments(self, function, make_kwargs): + args = list(make_kwargs().values()) + with pytest.raises(TypeError): + function(*args, args[-1]) + + def test_unknown_keyword(self, function, make_kwargs): + kwargs = make_kwargs() + with pytest.raises(TypeError): + function(**kwargs, not_an_argument=1) + + def test_bad_dtype(self, function, make_kwargs): + # float arrays as complex numbers, the others as floats: neither casts safely + for name, value in make_kwargs().items(): + if not isinstance(value, np.ndarray): + continue + kwargs = make_kwargs() + if value.dtype == np.float64: + kwargs[name] = value.astype(np.complex128) + else: + kwargs[name] = value.astype(np.float64) + with pytest.raises(TypeError): + function(**kwargs) + + def test_bad_dimension(self, function, make_kwargs): + for name, value in make_kwargs().items(): + if not isinstance(value, np.ndarray): + continue + kwargs = make_kwargs() + if value.ndim == 2: + kwargs[name] = value.reshape(-1) + else: + kwargs[name] = value.reshape(1, -1) + with pytest.raises(ValueError): + function(**kwargs) + + def test_not_an_array(self, function, make_kwargs): + for name, value in make_kwargs().items(): + if not isinstance(value, np.ndarray): + continue + kwargs = make_kwargs() + kwargs[name] = "not an array" + with pytest.raises((TypeError, ValueError)): + function(**kwargs) + + def test_not_a_number(self, function, make_kwargs): + # flags are not included: they take any object, as its truth value + for name, value in make_kwargs().items(): + if isinstance(value, (np.ndarray, bool)): + continue + kwargs = make_kwargs() + kwargs[name] = "not a number" + with pytest.raises(TypeError): + function(**kwargs) + + +SWEEPS_WITH_SEQUENCE_LENGTH = [ + (_tsdate.block_singletons, block_singletons_kwargs), + (_tsdate.mutation_frequency, mutation_frequency_kwargs), + (_tsdate.contains_unary_nodes, contains_unary_nodes_kwargs), + (_tsdate.count_mutations, count_mutations_kwargs), +] +SWEEPS = SWEEPS_WITH_SEQUENCE_LENGTH + [ + (_tsdate.relabel_mutations_node, relabel_mutations_node_kwargs), +] - @pytest.mark.parametrize("name", SWEEPS) - def test_nan_interval(self, ts, name): - a = sweep_args(ts, edges_right=bad_ids(ts.edges_right, np.nan)) + +class TestEdgeSweep: + """ + The library's errors for edges that a sweep over the trees cannot traverse, through + each function that sweeps + """ + + @pytest.mark.parametrize(("function", "make_kwargs"), SWEEPS, ids=names(SWEEPS)) + def test_nan_interval(self, function, make_kwargs): + kwargs = make_kwargs() + kwargs["edges_right"] = with_entry(TS.edges_right, -1, np.nan) with pytest.raises(_tsdate.LibraryError, match="Edge interval"): - call_sweep(name, ts, a) + function(**kwargs) - @pytest.mark.parametrize("name", sorted(set(SWEEPS) - {"relabel_mutations_node"})) - def test_interval_past_end(self, ts, name): - right = bad_ids(ts.edges_right, 2 * ts.sequence_length) + @pytest.mark.parametrize(("function", "make_kwargs"), SWEEPS, ids=names(SWEEPS)) + def test_empty_interval(self, function, make_kwargs): + kwargs = make_kwargs() + kwargs["edges_left"] = with_entry(TS.edges_left, -1, TS.edges_right[-1]) with pytest.raises(_tsdate.LibraryError, match="Edge interval"): - call_sweep(name, ts, sweep_args(ts, edges_right=right)) + function(**kwargs) - @pytest.mark.parametrize("name", SWEEPS) - def test_empty_interval(self, ts, name): - left = ts.edges_left.copy() - left[-1] = ts.edges_right[-1] + @pytest.mark.parametrize( + ("function", "make_kwargs"), + SWEEPS_WITH_SEQUENCE_LENGTH, + ids=names(SWEEPS_WITH_SEQUENCE_LENGTH), + ) + def test_interval_past_end(self, function, make_kwargs): + kwargs = make_kwargs() + kwargs["edges_right"] = with_entry(TS.edges_right, -1, 2 * TS.sequence_length) with pytest.raises(_tsdate.LibraryError, match="Edge interval"): - call_sweep(name, ts, sweep_args(ts, edges_left=left)) + function(**kwargs) - @pytest.mark.parametrize("name", SWEEPS) - def test_index_out_of_bounds(self, ts, name): - insert = bad_ids(ts.indexes_edge_insertion_order, ts.num_edges) + @pytest.mark.parametrize(("function", "make_kwargs"), SWEEPS, ids=names(SWEEPS)) + def test_index_out_of_bounds(self, function, make_kwargs): + kwargs = make_kwargs() + insert = TS.indexes_edge_insertion_order + kwargs["indexes_insert"] = with_entry(insert, -1, TS.num_edges) with pytest.raises(_tsdate.LibraryError, match="Edge id out of bounds"): - call_sweep(name, ts, sweep_args(ts, insert=insert)) + function(**kwargs) - @pytest.mark.parametrize("name", SWEEPS) - def test_unsorted_index(self, ts, name): - remove = ts.indexes_edge_removal_order[::-1].copy() + @pytest.mark.parametrize(("function", "make_kwargs"), SWEEPS, ids=names(SWEEPS)) + def test_unsorted_index(self, function, make_kwargs): + kwargs = make_kwargs() + kwargs["indexes_remove"] = TS.indexes_edge_removal_order[::-1].copy() with pytest.raises(_tsdate.LibraryError, match="Edge indexes must list"): - call_sweep(name, ts, sweep_args(ts, remove=remove)) - - @pytest.mark.parametrize("name", ["count_mutations", "mutation_frequency"]) - def test_cycle(self, ts, name): - # every edge from node 0 to node 1 and back over the whole sequence - num_edges = 2 - a = { - "edges_parent": np.array([1, 0], dtype=np.int32), - "edges_child": np.array([0, 1], dtype=np.int32), - "edges_left": np.zeros(num_edges), - "edges_right": np.full(num_edges, ts.sequence_length), - "insert": np.arange(num_edges, dtype=np.int32), - "remove": np.arange(num_edges, dtype=np.int32), - "mutations_node": ts.mutations_node, - } - with pytest.raises(_tsdate.LibraryError, match="Edges form a cycle"): - call_sweep(name, ts, a) + function(**kwargs) + + +class TestBlockSingletons: + def test_mismatched_edge_arrays(self): + for name in [ + "edges_left", + "edges_right", + "indexes_insert", + "indexes_remove", + ]: + kwargs = block_singletons_kwargs() + kwargs[name] = kwargs[name][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.block_singletons(**kwargs) + + def test_mismatched_mutation_arrays(self): + kwargs = block_singletons_kwargs() + kwargs["mutations_position"] = kwargs["mutations_position"][:-1] + with pytest.raises(ValueError, match="Mutation arrays must have the same size"): + _tsdate.block_singletons(**kwargs) + + def test_mutation_node_out_of_bounds(self): + kwargs = block_singletons_kwargs() + kwargs["mutations_node"] = with_entry(TS.mutations_node, -1, TS.num_nodes) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.block_singletons(**kwargs) - def test_individual_out_of_bounds(self, ts): - nodes_individual = bad_ids(ts.nodes_individual, ts.num_individuals) + def test_individual_out_of_bounds(self): + kwargs = block_singletons_kwargs() + individuals = with_entry(TS.nodes_individual, -1, TS.num_individuals) + kwargs["nodes_individual"] = individuals with pytest.raises(_tsdate.LibraryError, match="Individual id out of bounds"): - _tsdate.block_singletons( - np.ones(ts.num_individuals, dtype=bool), - nodes_individual, - ts.mutations_node, - ts.sites_position[ts.mutations_site], - ts.edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, - ) + _tsdate.block_singletons(**kwargs) + + def test_individual_with_three_nodes(self): + # nodes 0 and 1 belong to individual 0: give it node 2 as well + assert TS.nodes_individual[:3].tolist() == [0, 0, 1] + kwargs = block_singletons_kwargs() + kwargs["nodes_individual"] = with_entry(TS.nodes_individual, 2, 0) + with raises_library_error(ERR_UNPHASED_INDIVIDUAL_EDGES): + _tsdate.block_singletons(**kwargs) + + +class TestReallocateUnphased: + def test_result(self): + # the two mutations give edge 0 their phases and edge 1 the remainders + kwargs = reallocate_unphased_kwargs() + result = _tsdate.reallocate_unphased(**kwargs) + assert result.tolist() == [[0.75, 5.0], [1.25, 5.0], [1.0, 5.0]] + + def test_leaves_input(self): + kwargs = reallocate_unphased_kwargs() + _tsdate.reallocate_unphased(**kwargs) + assert kwargs["edges_likelihood"].tolist() == [[2, 5], [0, 5], [1, 5]] + + def test_mismatched_mutation_arrays(self): + kwargs = reallocate_unphased_kwargs() + kwargs["mutations_block"] = kwargs["mutations_block"][:-1] + with pytest.raises(ValueError, match="Mutation arrays must have the same size"): + _tsdate.reallocate_unphased(**kwargs) + + def test_three_columns(self): + for name in ["edges_likelihood", "blocks_edges"]: + kwargs = reallocate_unphased_kwargs() + value = kwargs[name] + kwargs[name] = np.hstack((value, value[:, :1])) + with pytest.raises(ValueError, match="must have two columns"): + _tsdate.reallocate_unphased(**kwargs) + + def test_block_out_of_bounds(self): + kwargs = reallocate_unphased_kwargs() + kwargs["mutations_block"] = np.array([0, 1, -1], dtype=np.int32) + with raises_library_error(ERR_BLOCK_OUT_OF_BOUNDS): + _tsdate.reallocate_unphased(**kwargs) + + def test_edge_of_block_out_of_bounds(self): + kwargs = reallocate_unphased_kwargs() + kwargs["blocks_edges"] = np.array([[0, 3]], dtype=np.int32) + with raises_library_error(ERR_BLOCK_OUT_OF_BOUNDS): + _tsdate.reallocate_unphased(**kwargs) + + def test_phase_out_of_range(self): + kwargs = reallocate_unphased_kwargs() + kwargs["mutations_phase"] = np.array([0.25, 1.5, np.nan]) + with raises_library_error(ERR_PHASE_OUT_OF_RANGE): + _tsdate.reallocate_unphased(**kwargs) + + def test_likelihood_not_conserved(self): + # a NaN phase is skipped, so one mutation's likelihood is not reallocated + kwargs = reallocate_unphased_kwargs() + kwargs["mutations_phase"] = np.array([0.25, np.nan, np.nan]) + with raises_library_error(ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED): + _tsdate.reallocate_unphased(**kwargs) + + +class TestMutationFrequency: + def test_mismatched_edge_arrays(self): + for name in [ + "edges_child", + "edges_left", + "edges_right", + "indexes_insert", + "indexes_remove", + ]: + kwargs = mutation_frequency_kwargs() + kwargs[name] = kwargs[name][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.mutation_frequency(**kwargs) + + def test_mismatched_mutation_arrays(self): + kwargs = mutation_frequency_kwargs() + kwargs["mutations_position"] = kwargs["mutations_position"][:-1] + with pytest.raises(ValueError, match="Mutation arrays must have the same size"): + _tsdate.mutation_frequency(**kwargs) @pytest.mark.parametrize("value", [-1, 2**30]) - def test_constrain_ages(self, ts, value): + def test_parent_out_of_bounds(self, value): + kwargs = mutation_frequency_kwargs() + kwargs["edges_parent"] = with_entry(TS.edges_parent, -1, value) with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): - _tsdate.constrain_ages( - ts.nodes_time, - np.zeros(ts.num_nodes, dtype=bool), - ts.edges_parent, - bad_ids(ts.edges_child, value), - 1e-6, - 3, - ) - - def test_split_disjoint_nodes(self, ts): + _tsdate.mutation_frequency(**kwargs) + + def test_mutation_node_out_of_bounds(self): + kwargs = mutation_frequency_kwargs() + kwargs["mutations_node"] = with_entry(TS.mutations_node, -1, TS.num_nodes) with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): - _tsdate.split_disjoint_nodes( - bad_ids(ts.edges_parent, ts.num_nodes), - ts.edges_child, - ts.edges_left, - ts.edges_right, - np.zeros(ts.num_nodes, dtype=bool), - ) - - def test_relabel_nodes_order(self, ts): - nodes_order = bad_ids(np.arange(ts.num_nodes, dtype=np.int32), ts.num_nodes) + _tsdate.mutation_frequency(**kwargs) + + def test_cycle(self): + # an edge from node 0 to node 1 and one back, over the whole sequence + kwargs = mutation_frequency_kwargs() + kwargs["edges_parent"] = np.array([1, 0], dtype=np.int32) + kwargs["edges_child"] = np.array([0, 1], dtype=np.int32) + kwargs["edges_left"] = np.array([0.0, 0.0]) + kwargs["edges_right"] = np.array([TS.sequence_length, TS.sequence_length]) + kwargs["indexes_insert"] = np.array([0, 1], dtype=np.int32) + kwargs["indexes_remove"] = np.array([0, 1], dtype=np.int32) + with pytest.raises(_tsdate.LibraryError, match="Edges form a cycle"): + _tsdate.mutation_frequency(**kwargs) + + +class TestSplitDisjointNodes: + def test_mismatched_edge_arrays(self): + for name in ["edges_child", "edges_left", "edges_right"]: + kwargs = split_disjoint_nodes_kwargs() + kwargs[name] = kwargs[name][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.split_disjoint_nodes(**kwargs) + + def test_parent_out_of_bounds(self): + kwargs = split_disjoint_nodes_kwargs() + kwargs["edges_parent"] = with_entry(TS.edges_parent, -1, TS.num_nodes) with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): - _tsdate.relabel_mutations_node( - ts.mutations_node, - ts.sites_position[ts.mutations_site], - nodes_order, - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ) - - def test_constraints_are_consistent(self, ts): - constraints = np.tile([0.0, np.inf], (ts.num_nodes, 1)) + _tsdate.split_disjoint_nodes(**kwargs) + + +class TestRelabelMutationsNode: + def test_mismatched_edge_arrays(self): + for name in [ + "edges_child", + "edges_left", + "edges_right", + "indexes_insert", + "indexes_remove", + ]: + kwargs = relabel_mutations_node_kwargs() + kwargs[name] = kwargs[name][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.relabel_mutations_node(**kwargs) + + def test_mismatched_mutation_arrays(self): + kwargs = relabel_mutations_node_kwargs() + kwargs["mutations_position"] = kwargs["mutations_position"][:-1] + with pytest.raises(ValueError, match="Mutation arrays must have the same size"): + _tsdate.relabel_mutations_node(**kwargs) + + @pytest.mark.parametrize("value", [-1, 2**30]) + def test_parent_out_of_bounds(self, value): + kwargs = relabel_mutations_node_kwargs() + kwargs["edges_parent"] = with_entry(TS.edges_parent, -1, value) with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): - _tsdate.constraints_are_consistent( - constraints, bad_ids(ts.edges_parent, -1), ts.edges_child - ) + _tsdate.relabel_mutations_node(**kwargs) - def test_mutational_area(self, ts): - likelihoods = np.ones((ts.num_edges, 2)) + def test_mutation_node_out_of_bounds(self): + kwargs = relabel_mutations_node_kwargs() + kwargs["mutations_node"] = with_entry(TS.mutations_node, -1, TS.num_nodes) with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): - _tsdate.mutational_area( - ts.nodes_time, - likelihoods, - ts.edges_parent, - bad_ids(ts.edges_child, ts.num_nodes), - ) - - def test_mutational_timescale(self, ts): - likelihoods = np.ones((ts.num_edges, 2)) + _tsdate.relabel_mutations_node(**kwargs) + + def test_nodes_order_out_of_bounds(self): + kwargs = relabel_mutations_node_kwargs() + kwargs["nodes_order"] = with_entry(kwargs["nodes_order"], -1, TS.num_nodes) with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): - _tsdate.mutational_timescale( - ts.nodes_time, - likelihoods, - np.zeros(ts.num_nodes, dtype=bool), - ts.edges_parent, - bad_ids(ts.edges_child, ts.num_nodes), - 2, - ) + _tsdate.relabel_mutations_node(**kwargs) + + def test_mutation_node_not_in_tree(self): + position = TS.sites_position[TS.mutations_site[0]] + absent = set(range(TS.num_nodes)) - set(TS.at(position).nodes()) + kwargs = relabel_mutations_node_kwargs() + kwargs["mutations_node"] = with_entry(TS.mutations_node, 0, min(absent)) + with raises_library_error(ERR_MUTATION_NODE_NOT_IN_TREE): + _tsdate.relabel_mutations_node(**kwargs) + + +class TestConstrainAges: + def test_mismatched_node_arrays(self): + kwargs = constrain_ages_kwargs() + kwargs["nodes_fixed"] = kwargs["nodes_fixed"][:-1] + with pytest.raises(ValueError, match="Node arrays must have the same size"): + _tsdate.constrain_ages(**kwargs) + + def test_mismatched_edge_arrays(self): + kwargs = constrain_ages_kwargs() + kwargs["edges_child"] = kwargs["edges_child"][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.constrain_ages(**kwargs) + @pytest.mark.parametrize("value", [-1, 2**30]) + def test_child_out_of_bounds(self, value): + kwargs = constrain_ages_kwargs() + kwargs["edges_child"] = with_entry(TS.edges_child, -1, value) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.constrain_ages(**kwargs) -class TestTooFew: - """ - The library's errors for too few tips or breakpoints - """ + def test_fixed_nodes_violate_constraint(self): + # every node fixed, at an age that makes every parent younger than its child + kwargs = constrain_ages_kwargs() + kwargs["nodes_fixed"] = np.ones(TS.num_nodes, dtype=bool) + kwargs["nodes_time"] = TS.nodes_time.max() - TS.nodes_time + with raises_library_error(ERR_FIXED_NODES_VIOLATE_CONSTRAINT): + _tsdate.constrain_ages(**kwargs) + + +class TestContainsUnaryNodes: + def test_mismatched_edge_arrays(self): + for name in ["edges_left", "edges_right", "indexes_insert", "indexes_remove"]: + kwargs = contains_unary_nodes_kwargs() + kwargs[name] = kwargs[name][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.contains_unary_nodes(**kwargs) - def test_conditional_coalescent_variance(self): + @pytest.mark.parametrize("value", [-1, 2**30]) + def test_parent_out_of_bounds(self, value): + kwargs = contains_unary_nodes_kwargs() + kwargs["edges_parent"] = with_entry(TS.edges_parent, -1, value) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.contains_unary_nodes(**kwargs) + + +class TestConditionalCoalescentVariance: + def test_one_tip(self): + # the result is unused by tsdate + assert _tsdate.conditional_coalescent_variance(1).tolist() == [0.0, 0.0] + + def test_no_tips(self): with pytest.raises(_tsdate.LibraryError, match="Too few tips"): _tsdate.conditional_coalescent_variance(0) - def test_piecewise_scale_point_estimate(self): - with pytest.raises(_tsdate.LibraryError, match="No breakpoints"): - _tsdate.piecewise_scale_point_estimate( - np.zeros(1), np.zeros(1, dtype=bool), np.zeros(0), np.zeros(0) - ) + def test_negative_tips(self): + with pytest.raises(ValueError, match="non-negative"): + _tsdate.conditional_coalescent_variance(-1) + + +class TestCountMutations: + def test_not_size_biased(self): + kwargs = count_mutations_kwargs() + kwargs["size_biased"] = False + edges_stats, _ = _tsdate.count_mutations(**kwargs) + assert edges_stats.shape == (TS.num_edges, 2) + + def test_mismatched_edge_arrays(self): + for name in [ + "edges_child", + "edges_left", + "edges_right", + "indexes_insert", + "indexes_remove", + ]: + kwargs = count_mutations_kwargs() + kwargs[name] = kwargs[name][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.count_mutations(**kwargs) + + def test_mismatched_mutation_arrays(self): + kwargs = count_mutations_kwargs() + kwargs["mutations_position"] = kwargs["mutations_position"][:-1] + with pytest.raises(ValueError, match="Mutation arrays must have the same size"): + _tsdate.count_mutations(**kwargs) + + @pytest.mark.parametrize("value", [-1, 2**30]) + def test_parent_out_of_bounds(self, value): + kwargs = count_mutations_kwargs() + kwargs["edges_parent"] = with_entry(TS.edges_parent, -1, value) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.count_mutations(**kwargs) - def test_piecewise_scale_posterior(self): + def test_mutation_node_out_of_bounds(self): + kwargs = count_mutations_kwargs() + kwargs["mutations_node"] = with_entry(TS.mutations_node, -1, TS.num_nodes) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.count_mutations(**kwargs) + + def test_cycle(self): + # an edge from node 0 to node 1 and one back, over the whole sequence + kwargs = count_mutations_kwargs() + kwargs["edges_parent"] = np.array([1, 0], dtype=np.int32) + kwargs["edges_child"] = np.array([0, 1], dtype=np.int32) + kwargs["edges_left"] = np.array([0.0, 0.0]) + kwargs["edges_right"] = np.array([TS.sequence_length, TS.sequence_length]) + kwargs["indexes_insert"] = np.array([0, 1], dtype=np.int32) + kwargs["indexes_remove"] = np.array([0, 1], dtype=np.int32) + with pytest.raises(_tsdate.LibraryError, match="Edges form a cycle"): + _tsdate.count_mutations(**kwargs) + + +class TestMutationalArea: + def test_mismatched_edge_arrays(self): + kwargs = mutational_area_kwargs() + kwargs["edges_child"] = kwargs["edges_child"][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.mutational_area(**kwargs) + + def test_mismatched_likelihoods(self): + kwargs = mutational_area_kwargs() + kwargs["edges_likelihood"] = kwargs["edges_likelihood"][:-1] + with pytest.raises(ValueError, match="one row of two columns per edge"): + _tsdate.mutational_area(**kwargs) + + def test_three_columns(self): + kwargs = mutational_area_kwargs() + kwargs["edges_likelihood"] = np.ones((TS.num_edges, 3)) + with pytest.raises(ValueError, match="one row of two columns per edge"): + _tsdate.mutational_area(**kwargs) + + def test_child_out_of_bounds(self): + kwargs = mutational_area_kwargs() + kwargs["edges_child"] = with_entry(TS.edges_child, -1, TS.num_nodes) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.mutational_area(**kwargs) + + +class TestMutationalTimescale: + def test_mismatched_edge_arrays(self): + kwargs = mutational_timescale_kwargs() + kwargs["edges_child"] = kwargs["edges_child"][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.mutational_timescale(**kwargs) + + def test_mismatched_likelihoods(self): + kwargs = mutational_timescale_kwargs() + kwargs["edges_likelihood"] = kwargs["edges_likelihood"][:-1] + with pytest.raises(ValueError, match="one row of two columns per edge"): + _tsdate.mutational_timescale(**kwargs) + + def test_three_columns(self): + kwargs = mutational_timescale_kwargs() + kwargs["edges_likelihood"] = np.ones((TS.num_edges, 3)) + with pytest.raises(ValueError, match="one row of two columns per edge"): + _tsdate.mutational_timescale(**kwargs) + + def test_mismatched_node_arrays(self): + kwargs = mutational_timescale_kwargs() + kwargs["nodes_fixed"] = kwargs["nodes_fixed"][:-1] + with pytest.raises(ValueError, match="nodes_fixed and nodes_time"): + _tsdate.mutational_timescale(**kwargs) + + def test_child_out_of_bounds(self): + kwargs = mutational_timescale_kwargs() + kwargs["edges_child"] = with_entry(TS.edges_child, -1, TS.num_nodes) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.mutational_timescale(**kwargs) + + def test_no_intervals(self): + kwargs = mutational_timescale_kwargs() + kwargs["max_intervals"] = 0 + with raises_library_error(ERR_NONPOSITIVE_INTERVALS): + _tsdate.mutational_timescale(**kwargs) + + def test_zero_edge_span(self): + kwargs = mutational_timescale_kwargs() + kwargs["edges_likelihood"] = np.zeros((TS.num_edges, 2)) + with raises_library_error(ERR_ZERO_EDGE_SPAN): + _tsdate.mutational_timescale(**kwargs) + + +class TestPiecewiseScalePointEstimate: + def test_mismatched_points(self): + kwargs = piecewise_scale_point_estimate_kwargs() + kwargs["point_fixed"] = kwargs["point_fixed"][:-1] + with pytest.raises(ValueError, match="point_fixed and point_estimate"): + _tsdate.piecewise_scale_point_estimate(**kwargs) + + def test_mismatched_breakpoints(self): + kwargs = piecewise_scale_point_estimate_kwargs() + kwargs["rescaled_breaks"] = kwargs["rescaled_breaks"][:-1] + with pytest.raises(ValueError, match="Breakpoints must be of the same size"): + _tsdate.piecewise_scale_point_estimate(**kwargs) + + def test_no_breakpoints(self): + kwargs = piecewise_scale_point_estimate_kwargs() + kwargs["original_breaks"] = np.array([]) + kwargs["rescaled_breaks"] = np.array([]) with pytest.raises(_tsdate.LibraryError, match="No breakpoints"): - _tsdate.piecewise_scale_posterior( - np.ones((1, 2)), - np.zeros(1, dtype=bool), - np.zeros(0), - np.zeros(0), - 0.5, - 1000.0, - ) + _tsdate.piecewise_scale_point_estimate(**kwargs) + + def test_decreasing_breakpoints(self): + kwargs = piecewise_scale_point_estimate_kwargs() + kwargs["original_breaks"] = np.array([10.0, 1.0, 0.0]) + with raises_library_error(ERR_NON_INCREASING_BREAKPOINTS): + _tsdate.piecewise_scale_point_estimate(**kwargs) + + +class TestPiecewiseScalePosterior: + def test_mismatched_posteriors(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["posteriors_fixed"] = kwargs["posteriors_fixed"][:-1] + with pytest.raises(ValueError, match="one row per fixed flag"): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_three_columns(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["posteriors"] = np.ones((3, 3)) + with pytest.raises(ValueError, match="must have two columns"): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_mismatched_breakpoints(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["rescaled_breaks"] = kwargs["rescaled_breaks"][:-1] + with pytest.raises(ValueError, match="Breakpoints must be of the same size"): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_no_breakpoints(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["original_breaks"] = np.array([]) + kwargs["rescaled_breaks"] = np.array([]) + with pytest.raises(_tsdate.LibraryError, match="No breakpoints"): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_decreasing_breakpoints(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["rescaled_breaks"] = np.array([20.0, 2.0, 0.0]) + with raises_library_error(ERR_NON_INCREASING_BREAKPOINTS): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_quantile_width(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["quantile_width"] = 1.0 + with raises_library_error(ERR_INVALID_QUANTILE_WIDTH): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_invalid_posterior(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["posteriors"] = np.array([[1.0, 0.0], [1.0, 1.0], [1.0, 1.0]]) + with raises_library_error(ERR_INVALID_POSTERIOR): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_no_posteriors(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["posteriors"] = np.zeros((0, 2)) + kwargs["posteriors_fixed"] = np.zeros(0, dtype=bool) + with raises_library_error(ERR_NO_POSTERIORS): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_time_below_first_breakpoint(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["original_breaks"] = np.array([50.0, 51.0, 60.0]) + with raises_library_error(ERR_TIME_BELOW_FIRST_BREAKPOINT): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_zero_quantile(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["posteriors"] = np.array([[1.0, np.inf], [1.0, 1.0], [1.0, 1.0]]) + with raises_library_error(ERR_ZERO_DIVISION): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_unsorted_quantiles(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["posteriors"] = np.array([[np.inf, 1.0], [1.0, 1.0], [1.0, 1.0]]) + with raises_library_error(ERR_UNSORTED_QUANTILES): + _tsdate.piecewise_scale_posterior(**kwargs) + + +class TestConstraintsAreConsistent: + def test_mismatched_edge_arrays(self): + kwargs = constraints_are_consistent_kwargs() + kwargs["edges_child"] = kwargs["edges_child"][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.constraints_are_consistent(**kwargs) + + def test_three_columns(self): + kwargs = constraints_are_consistent_kwargs() + kwargs["constraints"] = np.zeros((TS.num_nodes, 3)) + with pytest.raises(ValueError, match="constraints must have two columns"): + _tsdate.constraints_are_consistent(**kwargs) + + def test_parent_out_of_bounds(self): + kwargs = constraints_are_consistent_kwargs() + kwargs["edges_parent"] = with_entry(TS.edges_parent, -1, -1) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.constraints_are_consistent(**kwargs) def ep_arrays(**replace): @@ -477,7 +1033,7 @@ def test_mismatched_lengths(self, name, match): @pytest.mark.parametrize("value", [-1, 3]) def test_node_out_of_bounds(self, name, value): with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): - new_ep(**{name: bad_ids(ep_arrays()[name], value)}) + new_ep(**{name: with_entry(ep_arrays()[name], -1, value)}) def test_failed_init_leaves_no_state(self): ep = new_ep() @@ -601,18 +1157,13 @@ def test_mutations_edge_out_of_bounds(self, edges, unphased, match): with pytest.raises(_tsdate.LibraryError, match=match): new_ep().propagate_mutations(edges, unphased) - @pytest.mark.parametrize( - ("kwargs", "code"), - [ - (dict(max_shape=0.5), ERR_INVALID_MAX_SHAPE), - (dict(min_step=1.0), ERR_INVALID_MIN_STEP), - ], - ) - def test_likelihood_parameters(self, kwargs, code): - args = dict(order=EDGES, unphased=False, max_shape=1000.0, min_step=0.1) - args.update(kwargs) - with raises_library_error(code): - new_ep().propagate_likelihood(**args) + def test_likelihood_max_shape(self): + with raises_library_error(ERR_INVALID_MAX_SHAPE): + new_ep().propagate_likelihood(EDGES, False, 0.5, 0.1) + + def test_likelihood_min_step(self): + with raises_library_error(ERR_INVALID_MIN_STEP): + new_ep().propagate_likelihood(EDGES, False, 1000.0, 1.0) def test_prior_max_shape(self): with raises_library_error(ERR_INVALID_MAX_SHAPE): @@ -637,541 +1188,3 @@ def test_zero_division(self): ) with raises_library_error(ERR_ZERO_DIVISION): ep.propagate_likelihood(BLOCKS, True, 1000.0, 0.1) - - -def sweep_kwargs(ts, parents=True): - """ - The edge, index and mutation arrays of ``ts`` as keyword arguments - """ - kwargs = { - "mutations_node": ts.mutations_node, - "mutations_position": ts.sites_position[ts.mutations_site], - "edges_parent": ts.edges_parent, - "edges_child": ts.edges_child, - "edges_left": ts.edges_left, - "edges_right": ts.edges_right, - "indexes_insert": ts.indexes_edge_insertion_order, - "indexes_remove": ts.indexes_edge_removal_order, - } - if not parents: - del kwargs["edges_parent"] - return kwargs - - -EDGE_ARRAYS = ["edges_parent", "edges_child", "edges_left", "edges_right"] -INDEXES = ["indexes_insert", "indexes_remove"] -MUTATION_ARRAYS = ["mutations_node", "mutations_position"] - - -def function_specs(ts): - """ - For each function of the module that tsdate calls: valid keyword arguments, the - groups of arrays that must have the same length, and the arrays of two columns - """ - samples = np.zeros(ts.num_nodes, dtype=bool) - samples[ts.samples()] = True - unphased = np.ones(ts.num_individuals, dtype=bool) - _, blocks_edges, mutations_block = tsdate.phasing.block_singletons(ts, unphased) - likelihood, _ = tsdate.rescaling.count_mutations(ts) - constraints = np.zeros((ts.num_nodes, 2)) - constraints[:, 1] = np.inf - constraints[samples] = 0.0 - breaks = np.array([0.0, 1.0, 10.0]), np.array([0.0, 2.0, 20.0]) - posteriors = np.ones((ts.num_nodes, 2)) - return { - "block_singletons": ( - dict( - individuals_unphased=unphased, - nodes_individual=ts.nodes_individual, - **sweep_kwargs(ts, parents=False), - sequence_length=ts.sequence_length, - ), - [EDGE_ARRAYS[1:] + INDEXES, MUTATION_ARRAYS], - [], - ), - "reallocate_unphased": ( - dict( - edges_likelihood=likelihood, - mutations_phase=np.full(ts.num_mutations, 0.5), - mutations_block=mutations_block, - blocks_edges=blocks_edges, - ), - [["mutations_phase", "mutations_block"]], - ["edges_likelihood", "blocks_edges"], - ), - "mutation_frequency": ( - dict( - nodes_sample=samples[:, np.newaxis], - **sweep_kwargs(ts), - sequence_length=ts.sequence_length, - ), - [EDGE_ARRAYS + INDEXES, MUTATION_ARRAYS], - [], - ), - "split_disjoint_nodes": ( - dict( - edges_parent=ts.edges_parent, - edges_child=ts.edges_child, - edges_left=ts.edges_left, - edges_right=ts.edges_right, - nodes_excluded=samples, - ), - [EDGE_ARRAYS], - [], - ), - "relabel_mutations_node": ( - dict( - mutations_node=ts.mutations_node, - mutations_position=ts.sites_position[ts.mutations_site], - nodes_order=np.arange(ts.num_nodes, dtype=np.int32), - **{ - k: v - for k, v in sweep_kwargs(ts).items() - if k.startswith(("edges", "indexes")) - }, - ), - [EDGE_ARRAYS + INDEXES, MUTATION_ARRAYS], - [], - ), - "constrain_ages": ( - dict( - nodes_time=ts.nodes_time, - nodes_fixed=samples, - edges_parent=ts.edges_parent, - edges_child=ts.edges_child, - epsilon=1e-6, - max_iterations=2, - ), - [["nodes_time", "nodes_fixed"], ["edges_parent", "edges_child"]], - [], - ), - "contains_unary_nodes": ( - dict( - nodes_mask=samples, - edges_parent=ts.edges_parent, - edges_left=ts.edges_left, - edges_right=ts.edges_right, - indexes_insert=ts.indexes_edge_insertion_order, - indexes_remove=ts.indexes_edge_removal_order, - sequence_length=ts.sequence_length, - ), - [["edges_parent", "edges_left", "edges_right"] + INDEXES], - [], - ), - "conditional_coalescent_variance": (dict(num_tips=5), [], []), - "count_mutations": ( - dict( - nodes_sample=samples, - **sweep_kwargs(ts), - sequence_length=ts.sequence_length, - size_biased=True, - ), - [EDGE_ARRAYS + INDEXES, MUTATION_ARRAYS], - [], - ), - "mutational_area": ( - dict( - nodes_time=ts.nodes_time, - edges_likelihood=likelihood, - edges_parent=ts.edges_parent, - edges_child=ts.edges_child, - ), - [["edges_parent", "edges_child", "edges_likelihood"]], - ["edges_likelihood"], - ), - "mutational_timescale": ( - dict( - nodes_time=ts.nodes_time, - edges_likelihood=likelihood, - nodes_fixed=samples, - edges_parent=ts.edges_parent, - edges_child=ts.edges_child, - max_intervals=3, - ), - [ - ["edges_parent", "edges_child", "edges_likelihood"], - ["nodes_time", "nodes_fixed"], - ], - ["edges_likelihood"], - ), - "piecewise_scale_point_estimate": ( - dict( - point_estimate=ts.nodes_time, - point_fixed=samples, - original_breaks=breaks[0], - rescaled_breaks=breaks[1], - ), - [["point_estimate", "point_fixed"], ["original_breaks", "rescaled_breaks"]], - [], - ), - "piecewise_scale_posterior": ( - dict( - posteriors=posteriors, - posteriors_fixed=samples, - original_breaks=breaks[0], - rescaled_breaks=breaks[1], - quantile_width=0.5, - max_shape=1000.0, - ), - [ - ["posteriors", "posteriors_fixed"], - ["original_breaks", "rescaled_breaks"], - ], - ["posteriors"], - ), - "constraints_are_consistent": ( - dict( - constraints=constraints, - edges_parent=ts.edges_parent, - edges_child=ts.edges_child, - ), - [["edges_parent", "edges_child"]], - ["constraints"], - ), - } - - -FUNCTIONS = [ - "block_singletons", - "reallocate_unphased", - "mutation_frequency", - "split_disjoint_nodes", - "relabel_mutations_node", - "constrain_ages", - "contains_unary_nodes", - "conditional_coalescent_variance", - "count_mutations", - "mutational_area", - "mutational_timescale", - "piecewise_scale_point_estimate", - "piecewise_scale_posterior", - "constraints_are_consistent", -] - - -@pytest.fixture(scope="module") -def specs(ts): - return function_specs(ts) - - -def array_arguments(): - """ - (function, argument) for every array argument - """ - specs = function_specs(make_ts_for_specs()) - return [ - (name, arg) - for name in FUNCTIONS - for arg, value in specs[name][0].items() - if isinstance(value, np.ndarray) - ] - - -def scalar_arguments(): - """ - (function, argument) for every numerical scalar argument (flags take any object, - as Python's truth values) - """ - specs = function_specs(make_ts_for_specs()) - return [ - (name, arg) - for name in FUNCTIONS - for arg, value in specs[name][0].items() - if not isinstance(value, (np.ndarray, bool)) - ] - - -def make_ts_for_specs(): - """ - The tree sequence of the ``ts`` fixture, for parametrising tests - """ - ts = msprime.sim_ancestry( - 2, - sequence_length=1e4, - recombination_rate=1e-8, - population_size=1e4, - random_seed=2, - ) - return msprime.sim_mutations(ts, rate=1e-7, random_seed=2) - - -def bad_dtype(value): - """ - An array of a type that cannot be cast safely to the type of ``value`` - """ - if value.dtype == np.float64: - return value.astype(np.complex128) - return value.astype(np.float64) - - -class TestArguments: - """ - Argument handling of each function: counts, keywords, types, dimensions and lengths - """ - - @pytest.mark.parametrize("name", FUNCTIONS) - def test_keywords(self, specs, name): - kwargs, _, _ = specs[name] - getattr(_tsdate, name)(**kwargs) - - @pytest.mark.parametrize("name", FUNCTIONS) - def test_positional(self, specs, name): - kwargs, _, _ = specs[name] - getattr(_tsdate, name)(*kwargs.values()) - - @pytest.mark.parametrize("name", FUNCTIONS) - def test_too_few_arguments(self, specs, name): - args = list(specs[name][0].values()) - with pytest.raises(TypeError): - getattr(_tsdate, name)(*args[:-1]) - - @pytest.mark.parametrize("name", FUNCTIONS) - def test_too_many_arguments(self, specs, name): - args = list(specs[name][0].values()) - with pytest.raises(TypeError): - getattr(_tsdate, name)(*args, args[-1]) - - @pytest.mark.parametrize("name", FUNCTIONS) - def test_unknown_keyword(self, specs, name): - kwargs = dict(specs[name][0], not_an_argument=1) - with pytest.raises(TypeError): - getattr(_tsdate, name)(**kwargs) - - @pytest.mark.parametrize(("name", "arg"), array_arguments()) - def test_bad_dtype(self, specs, name, arg): - kwargs = dict(specs[name][0]) - kwargs[arg] = bad_dtype(kwargs[arg]) - with pytest.raises(TypeError): - getattr(_tsdate, name)(**kwargs) - - @pytest.mark.parametrize(("name", "arg"), array_arguments()) - def test_bad_dimension(self, specs, name, arg): - kwargs = dict(specs[name][0]) - value = kwargs[arg] - kwargs[arg] = value.reshape(-1) if value.ndim == 2 else value[np.newaxis, :] - with pytest.raises(ValueError): - getattr(_tsdate, name)(**kwargs) - - @pytest.mark.parametrize(("name", "arg"), array_arguments()) - def test_not_an_array(self, specs, name, arg): - kwargs = dict(specs[name][0]) - kwargs[arg] = "not an array" - with pytest.raises((TypeError, ValueError)): - getattr(_tsdate, name)(**kwargs) - - @pytest.mark.parametrize(("name", "arg"), scalar_arguments()) - def test_bad_scalar(self, specs, name, arg): - kwargs = dict(specs[name][0]) - kwargs[arg] = "not a number" - with pytest.raises(TypeError): - getattr(_tsdate, name)(**kwargs) - - @pytest.mark.parametrize("name", FUNCTIONS) - def test_mismatched_lengths(self, specs, name): - kwargs, groups, _ = specs[name] - for group in groups: - for arg in group[1:]: - bad = dict(kwargs) - bad[arg] = kwargs[arg][:-1] - with pytest.raises(ValueError): - getattr(_tsdate, name)(**bad) - - @pytest.mark.parametrize("name", FUNCTIONS) - def test_two_columns(self, specs, name): - kwargs, _, two_columns = specs[name] - for arg in two_columns: - bad = dict(kwargs) - bad[arg] = np.hstack((kwargs[arg], kwargs[arg][:, :1])) - with pytest.raises(ValueError, match="two columns"): - getattr(_tsdate, name)(**bad) - - -def first_blocked(kwargs): - """ - The first mutation of ``reallocate_unphased``'s arguments that is in a block - """ - return np.flatnonzero(kwargs["mutations_block"] >= 0)[0] - - -def first_block(kwargs): - """ - The block of the first mutation of ``reallocate_unphased``'s arguments that is in - a block - """ - return kwargs["mutations_block"][first_blocked(kwargs)] - - -def edit(arg, change): - """ - An edit of the keyword arguments that sets ``arg`` to ``change(kwargs)`` - """ - - def apply(kwargs): - kwargs[arg] = change(kwargs) - - return apply - - -def with_entry(arg, index, value): - """ - An edit that sets entry ``index`` of array ``arg`` to ``value``; either can be a - function of the arguments - """ - - def change(kwargs): - array = kwargs[arg].copy() - entry = index(kwargs) if callable(index) else index - array[entry] = value(kwargs) if callable(value) else value - return array - - return edit(arg, change) - - -def node_not_in_tree(kwargs): - """ - A node with no edge over the position of the first mutation - """ - position = kwargs["mutations_position"][0] - left, right = kwargs["edges_left"], kwargs["edges_right"] - over = (left <= position) & (position < right) - present = set(kwargs["edges_parent"][over]) | set(kwargs["edges_child"][over]) - return min(set(range(kwargs["nodes_order"].size)) - present) - - -def reversed_ages(kwargs): - return kwargs["nodes_time"].max() - kwargs["nodes_time"] - - -ERROR_CASES = { - "block_singletons_three_edges": ( - "block_singletons", - with_entry("nodes_individual", 2, 0), - ERR_UNPHASED_INDIVIDUAL_EDGES, - ), - "reallocate_block": ( - "reallocate_unphased", - with_entry("mutations_block", first_blocked, 1000), - ERR_BLOCK_OUT_OF_BOUNDS, - ), - "reallocate_edge_of_block": ( - "reallocate_unphased", - with_entry("blocks_edges", first_block, 10**6), - ERR_BLOCK_OUT_OF_BOUNDS, - ), - "reallocate_phase": ( - "reallocate_unphased", - with_entry("mutations_phase", first_blocked, 1.5), - ERR_PHASE_OUT_OF_RANGE, - ), - "reallocate_not_conserved": ( - "reallocate_unphased", - with_entry("mutations_phase", first_blocked, np.nan), - ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED, - ), - "relabel_node_not_in_tree": ( - "relabel_mutations_node", - with_entry("mutations_node", 0, node_not_in_tree), - ERR_MUTATION_NODE_NOT_IN_TREE, - ), - "constrain_fixed_nodes": ( - "constrain_ages", - lambda kwargs: kwargs.update( - nodes_fixed=np.ones_like(kwargs["nodes_fixed"]), - nodes_time=reversed_ages(kwargs), - ), - ERR_FIXED_NODES_VIOLATE_CONSTRAINT, - ), - "timescale_intervals": ( - "mutational_timescale", - edit("max_intervals", lambda kwargs: 0), - ERR_NONPOSITIVE_INTERVALS, - ), - "timescale_zero_span": ( - "mutational_timescale", - edit("edges_likelihood", lambda kwargs: kwargs["edges_likelihood"] * [1, 0]), - ERR_ZERO_EDGE_SPAN, - ), - "point_estimate_breaks": ( - "piecewise_scale_point_estimate", - edit("original_breaks", lambda kwargs: kwargs["original_breaks"][::-1].copy()), - ERR_NON_INCREASING_BREAKPOINTS, - ), - "posterior_breaks": ( - "piecewise_scale_posterior", - edit("rescaled_breaks", lambda kwargs: kwargs["rescaled_breaks"][::-1].copy()), - ERR_NON_INCREASING_BREAKPOINTS, - ), - "posterior_quantile_width": ( - "piecewise_scale_posterior", - edit("quantile_width", lambda kwargs: 1.0), - ERR_INVALID_QUANTILE_WIDTH, - ), - "posterior_invalid": ( - "piecewise_scale_posterior", - with_entry("posteriors", (0, 1), 0.0), - ERR_INVALID_POSTERIOR, - ), - "posterior_none": ( - "piecewise_scale_posterior", - lambda kwargs: kwargs.update( - posteriors=np.zeros((0, 2)), posteriors_fixed=np.zeros(0, dtype=bool) - ), - ERR_NO_POSTERIORS, - ), - "posterior_below_first_break": ( - "piecewise_scale_posterior", - edit("original_breaks", lambda kwargs: kwargs["original_breaks"] + 50.0), - ERR_TIME_BELOW_FIRST_BREAKPOINT, - ), - "posterior_zero_quantile": ( - "piecewise_scale_posterior", - with_entry("posteriors", (0, 1), np.inf), - ERR_ZERO_DIVISION, - ), - "posterior_approximation": ( - "piecewise_scale_posterior", - with_entry("posteriors", (0, 0), np.inf), - ERR_UNSORTED_QUANTILES, - ), -} - - -class TestLibraryErrors: - """ - Errors of the library, through each function that reports them - """ - - @pytest.mark.parametrize("case", ERROR_CASES) - def test_error(self, specs, case): - name, change, code = ERROR_CASES[case] - kwargs = dict(specs[name][0]) - if name == "piecewise_scale_posterior": - kwargs["posteriors_fixed"] = np.zeros_like(kwargs["posteriors_fixed"]) - change(kwargs) - with raises_library_error(code): - getattr(_tsdate, name)(**kwargs) - - -class TestValues: - """ - Results that the other tests do not check - """ - - def test_reallocate_unphased_leaves_input(self): - likelihood = np.array([[1.0, 5.0], [0.0, 5.0]]) - result = _tsdate.reallocate_unphased( - edges_likelihood=likelihood, - mutations_phase=np.array([0.25]), - mutations_block=np.array([0], dtype=np.int32), - blocks_edges=np.array([[0, 1]], dtype=np.int32), - ) - assert result.tolist() == [[0.25, 5.0], [0.75, 5.0]] - assert likelihood.tolist() == [[1.0, 5.0], [0.0, 5.0]] - - def test_variance_one_tip(self): - # the result is unused by tsdate - assert _tsdate.conditional_coalescent_variance(1).tolist() == [0.0, 0.0] - - def test_variance_negative_tips(self): - with pytest.raises(ValueError, match="non-negative"): - _tsdate.conditional_coalescent_variance(-1) From dac83487d3c5a0b78edf73b0de00c317a75f7b0e Mon Sep 17 00:00:00 2001 From: Nate Pope Date: Sat, 28 Nov 2026 11:23:34 -0800 Subject: [PATCH 56/56] Simplify the oracle equivalence tests The tests call the functions and their oracles with keyword arguments, through two helpers: assert_same_result and assert_same_error. The outcome classes and their tests are gone, and the oracles no longer check the sizes of arrays, which tests/test_python_c.py tests in the module. --- tests/oracle/__init__.py | 13 +- tests/oracle/errors.py | 52 +--- tests/oracle/helpers.py | 209 +++------------- tests/oracle/phasing.py | 28 --- tests/oracle/util.py | 28 --- tests/test_oracle_helpers.py | 160 ------------ tests/test_oracle_phasing.py | 457 ++++++++++++++++++----------------- tests/test_oracle_util.py | 383 ++++++++++++++--------------- 8 files changed, 464 insertions(+), 866 deletions(-) delete mode 100644 tests/test_oracle_helpers.py diff --git a/tests/oracle/__init__.py b/tests/oracle/__init__.py index 17acb5ff..4d3e2236 100644 --- a/tests/oracle/__init__.py +++ b/tests/oracle/__init__.py @@ -5,7 +5,7 @@ Each function has an oracle in the module of the same name here, e.g. ``oracle.phasing.block_singletons`` for ``_tsdate.block_singletons``. Equivalence tests (``tests/test_oracle_*.py``) call the ``_tsdate`` functions and the oracles with -the same arguments and compare the outcomes. +the same arguments and compare the results. Rules: @@ -13,11 +13,10 @@ C library. * Oracles call other oracles, never ``_tsdate``, except for the messages of the library's error codes (``errors``, as ``_tsdate.strerror`` gives them). -* Oracles raise errors in the library's terms: where the C library returns an error - code, the oracle raises ``errors.library_error(code)``, the ``_tsdate.LibraryError`` - with that code's message; for the shapes and sizes of arrays that ``_tsdate`` - checks, the oracle raises ``ValueError`` with its message. The equivalence tests - compare the type and message of the exceptions. Internal invariants, which the - library does not report, are plain ``assert`` statements. +* Where the C library returns an error code, the oracle raises + ``errors.library_error(code)``, the ``_tsdate.LibraryError`` with that code's + message. Oracles do not check the sizes of their arrays (``_tsdate`` does, and + ``tests/test_python_c.py`` tests it). Internal invariants, which the library does + not report, are plain ``assert`` statements. * Names, arguments and results are those of ``_tsdate``'s functions. """ diff --git a/tests/oracle/errors.py b/tests/oracle/errors.py index 0c6bc37a..1dca105e 100644 --- a/tests/oracle/errors.py +++ b/tests/oracle/errors.py @@ -1,55 +1,16 @@ """ -The error codes of the C library (``lib/err.h``, without the ``TSD_ERR_`` prefix), -and the exceptions with which ``_tsdate`` reports them. +The error codes of the C library that the oracles raise (``lib/err.h``, without the +``TSD_ERR_`` prefix), and the exceptions with which ``_tsdate`` reports them. """ import _tsdate -GENERIC = -1 -NO_MEMORY = -2 -BAD_PARAM = -3 -ZERO_DIVISION = -4 -INVALID_HYPERGEO = -5 -NONPOSITIVE_OR_NONFINITE_MOMENTS = -6 -JENSEN_VIOLATION = -7 -KL_MAX_ITERATIONS = -8 -KL_INVALID_SHAPE = -9 -NONPOSITIVE_CENTRAL_MOMENTS = -10 -UNSORTED_QUANTILES = -11 -QUANTILE_MAX_ITERATIONS = -12 -NEGATIVE_SHAPE = -13 -NONPOSITIVE_MOMENTS = -14 -INVALID_FIXED_AGE = -15 UNPHASED_INDIVIDUAL_EDGES = -16 BLOCK_OUT_OF_BOUNDS = -17 PHASE_OUT_OF_RANGE = -18 UNPHASED_LIKELIHOOD_NOT_CONSERVED = -19 MUTATION_NODE_NOT_IN_TREE = -20 FIXED_NODES_VIOLATE_CONSTRAINT = -21 -NONPOSITIVE_INTERVALS = -22 -ZERO_EDGE_SPAN = -24 -NON_INCREASING_BREAKPOINTS = -25 -INVALID_QUANTILE_WIDTH = -26 -INVALID_POSTERIOR = -27 -TIME_BELOW_FIRST_BREAKPOINT = -28 -NO_POSTERIORS = -29 -INVALID_MAX_SHAPE = -30 -INVALID_MIN_STEP = -31 -INVALID_NODE_POSTERIOR = -32 -INVALID_DAMPING = -33 -TWIN_EDGE_IN_PHASED_PASS = -34 -NONPOSITIVE_PENALTY = -35 -NODE_OUT_OF_BOUNDS = -36 -EDGE_OUT_OF_BOUNDS = -37 -INDIVIDUAL_OUT_OF_BOUNDS = -38 -BAD_EDGE_INTERVAL = -39 -BAD_EDGE_INDEXES = -40 -EDGES_FORM_CYCLE = -41 -TOO_FEW_TIPS = -42 -NO_BREAKPOINTS = -43 - -# -23 is unused -CODES = [code for code in range(NO_BREAKPOINTS, 0) if code != -23] def library_error(code): @@ -58,12 +19,3 @@ def library_error(code): """ message = _tsdate.strerror(code) return _tsdate.LibraryError(message) - - -def code_of(exception): - """ - The error code of a ``_tsdate.LibraryError``, from its message. - """ - message = str(exception) - (code,) = [code for code in CODES if _tsdate.strerror(code) == message] - return code diff --git a/tests/oracle/helpers.py b/tests/oracle/helpers.py index 9c6d1f2a..7c1ab78f 100644 --- a/tests/oracle/helpers.py +++ b/tests/oracle/helpers.py @@ -1,178 +1,58 @@ """ -Comparison helpers shared by the oracle equivalence tests. +Helpers shared by the oracle equivalence tests. """ +import re + +import _tsdate import numpy as np +import pytest import tskit -from _tsdate import LibraryError - -from . import errors -from .errors import library_error - - -def _flatten(x, path=""): - """ - Yield (path, array) for each leaf of a nested tuple/list of scalars/arrays. - """ - if isinstance(x, (tuple, list)): - for i, item in enumerate(x): - yield from _flatten(item, f"{path}[{i}]") - else: - yield path, np.asarray(x, dtype=np.float64) -def assert_same_values(actual, desired): +def copies(kwargs): """ - Assert that two scalars, arrays, or (nested) tuples of them are equal, with NaNs in - the same places. Shapes and tuple structure must match. + The keyword arguments with copies of their arrays """ - a_leaves = list(_flatten(actual)) - d_leaves = list(_flatten(desired)) - assert len(a_leaves) == len(d_leaves), ( - f"structure mismatch: {len(a_leaves)} vs {len(d_leaves)} values" - ) - for (path, a), (_, d) in zip(a_leaves, d_leaves): - assert a.shape == d.shape, ( - f"shape mismatch at {path or 'value'}: {a.shape} vs {d.shape}" - ) - assert np.array_equal(a, d, equal_nan=True), ( - f"values differ at {path or 'value'}:\nactual: {a}\ndesired: {d}" - ) + return { + name: value.copy() if isinstance(value, np.ndarray) else value + for name, value in kwargs.items() + } -INF = float("inf") -NAN = float("nan") - - -class Outcome: - """ - What calling a function did: ``value`` (its return value) or ``exception``, and - ``args``, the (copied) arguments after the call, to compare in-place updates. +def assert_same_result(function, oracle, **kwargs): """ - - def __init__(self, value=None, exception=None, args=()): - self.value = value - self.exception = exception - self.args = args - - @property - def error(self): - """ - ``None`` if the call returned, the error code (an `errors` constant) if it - raised a ``_tsdate.LibraryError``, else the class of the exception. - """ - if self.exception is None: - return None - if isinstance(self.exception, LibraryError): - return errors.code_of(self.exception) - return type(self.exception) - - def __repr__(self): - if self.exception is None: - return f"Outcome(value={self.value!r})" - return f"Outcome(exception={self.exception!r})" - - -def _copy_arg(x): - if isinstance(x, np.ndarray): - return x.copy() - if isinstance(x, np.floating): - # the oracles expect Python floats (division by zero raises) - return float(x) - return x - - -def outcome(func, *args, **kwargs): - """ - Call ``func`` on copies of ``args`` and return an `Outcome`. NumPy floating - scalars are converted to ``float``; NumPy warnings (which the oracle emits where - C is silent) are suppressed. - """ - copies = [_copy_arg(x) for x in args] - try: - with np.errstate(all="ignore"): - value = func(*copies, **kwargs) - except Exception as e: # noqa: BLE001 - return Outcome(exception=e, args=copies) - return Outcome(value=value, args=copies) - - -def errors_match(actual, expected): + Call the ``_tsdate`` function and its oracle with (copies of) the keyword + arguments, assert that they return arrays of the same values, shapes and types, + with NaNs in the same places, and return the result """ - Whether exception ``actual`` (from an implementation) matches ``expected`` (from - the oracle): the same type and message. An oracle ``ZeroDivisionError`` stands for - the library's ``TSD_ERR_ZERO_DIVISION``, and matches the ``_tsdate.LibraryError`` - that reports it. - """ - if isinstance(expected, ZeroDivisionError): - expected = library_error(errors.ZERO_DIVISION) - return type(actual) is type(expected) and str(actual) == str(expected) - - -def assert_same_outcome(actual, expected): - """ - Assert that two `Outcome` objects agree: both raise matching exceptions, or both - return the same values and leave array arguments the same. - """ - if expected.exception is not None: - assert actual.exception is not None, ( - f"implementation returned {actual.value!r}, oracle raised " - f"{expected.exception!r}" - ) - assert errors_match(actual.exception, expected.exception), ( - f"implementation raised {actual.exception!r}, oracle raised " - f"{expected.exception!r}" - ) - return - assert actual.exception is None, ( - f"implementation raised {actual.exception!r}, oracle returned {expected.value!r}" - ) - assert_same_values(actual.value, expected.value) - for i, (a, d) in enumerate(zip(actual.args, expected.args)): - if isinstance(a, np.ndarray): - try: - assert_same_values(a, d) - except AssertionError as e: - raise AssertionError( - f"argument {i} differs after the call: {e}" - ) from None - - -def compare(impl_func, oracle_func, *args, **kwargs): - """ - Call the implementation and the oracle on copies of ``args``, assert that their - outcomes agree (`assert_same_outcome`), and return the oracle's `Outcome`. - """ - expected = outcome(oracle_func, *args, **kwargs) - actual = outcome(impl_func, *args, **kwargs) - assert_same_outcome(actual, expected) - return expected + expected = oracle(**copies(kwargs)) + actual = function(**copies(kwargs)) + if isinstance(expected, tuple): + assert len(actual) == len(expected) + for actual_array, expected_array in zip(actual, expected): + np.testing.assert_array_equal(actual_array, expected_array, strict=True) + else: + np.testing.assert_array_equal(actual, expected, strict=True) + return actual -def kind(result): +def raises_library_error(code): """ - Classify an `Outcome`: its `Outcome.error` if it raised, ``None`` if it returned - ``None`` (an in-place update), else ``"nan"`` if any returned value is NaN, - ``"finite"`` if all are finite, otherwise ``"nonfinite"``. + ``pytest.raises`` for the library error ``code`` """ - if result.exception is not None: - return result.error - if result.value is None: - return None - values = [leaf for _, leaf in _flatten(result.value)] - values = np.concatenate([v.ravel() for v in values]) if values else [] - if np.isnan(values).any(): - return "nan" - return "finite" if np.isfinite(values).all() else "nonfinite" + return pytest.raises(_tsdate.LibraryError, match=re.escape(_tsdate.strerror(code))) -def assert_outcome(impl_func, oracle_func, args, expected_kind, **kwargs): +def assert_same_error(function, oracle, code, **kwargs): """ - `compare`, then assert the `kind` of the outcome (for edge-case tables). + Assert that the ``_tsdate`` function and its oracle both raise the library error + ``code`` for the keyword arguments """ - result = compare(impl_func, oracle_func, *args, **kwargs) - assert kind(result) == expected_kind, f"{args}: {result!r}" - return result + with raises_library_error(code): + oracle(**copies(kwargs)) + with raises_library_error(code): + function(**copies(kwargs)) def make_ts(nodes, edges, mutations, length, num_individuals=0): @@ -197,24 +77,3 @@ def make_ts(nodes, edges, mutations, length, num_individuals=0): tables.mutations.add_row(i, node, "1") tables.sort() return tables.tree_sequence() - - -def i32(*x): - return np.array(x, dtype=np.int32) - - -def f64(*x): - return np.array(x, dtype=np.float64) - - -def b1(*x): - return np.array(x, dtype=bool) - - -def shrink(args, index, size): - """ - Copy of the argument list with ``args[index]`` truncated to ``size``. - """ - args = list(args) - args[index] = args[index][:size] - return args diff --git a/tests/oracle/phasing.py b/tests/oracle/phasing.py index 35d599ad..d21a814c 100644 --- a/tests/oracle/phasing.py +++ b/tests/oracle/phasing.py @@ -14,11 +14,6 @@ def reallocate_unphased(edges_likelihood, mutations_phase, mutations_block, bloc The edge likelihoods with a proportion of each unphased singleton mutation added to one of the two edges to which it maps """ - if edges_likelihood.shape[1] != 2 or blocks_edges.shape[1] != 2: - raise ValueError("edges_likelihood and blocks_edges must have two columns") - if mutations_phase.size != mutations_block.size: - raise ValueError("Mutation arrays must have the same size") - edges_likelihood = edges_likelihood.copy() num_edges = edges_likelihood.shape[0] @@ -63,17 +58,6 @@ def block_singletons( Blocks of the singleton mutations of unphased individuals: ``(blocks_stats, blocks_edges, mutations_block)``. """ - if not ( - edges_child.size - == edges_left.size - == edges_right.size - == indexes_insert.size - == indexes_remove.size - ): - raise ValueError("Edge arrays must have the same size") - if mutations_node.size != mutations_position.size: - raise ValueError("Mutation arrays must have the same size") - num_mutations = mutations_node.size num_edges = edges_child.size num_individuals = individuals_unphased.size @@ -182,18 +166,6 @@ def mutation_frequency( The number of samples of each sample set below each mutation, as an array of shape ``(num_mutations, num_sample_sets)``. """ - if not ( - edges_parent.size - == edges_child.size - == edges_left.size - == edges_right.size - == indexes_insert.size - == indexes_remove.size - ): - raise ValueError("Edge arrays must have the same size") - if mutations_node.size != mutations_position.size: - raise ValueError("Mutation arrays must have the same size") - num_nodes, num_sample_sets = nodes_sample.shape num_mutations = mutations_node.size num_edges = edges_parent.size diff --git a/tests/oracle/util.py b/tests/oracle/util.py index 2bbc145d..fad50e6b 100644 --- a/tests/oracle/util.py +++ b/tests/oracle/util.py @@ -18,8 +18,6 @@ def split_disjoint_nodes( Returns updated edges_parent, edges_child, mutations_node, and indices indicating from which original node the new nodes are derived. """ - if not (edges_parent.size == edges_child.size == edges_left.size == edges_right.size): - raise ValueError("Edge arrays must have the same size") num_edges = edges_parent.size num_nodes = nodes_excluded.size @@ -83,18 +81,6 @@ def relabel_mutations_node( Traverse trees, maintaining a mapping between old and new node IDs in the current tree. Update `mutations_node` to reflect new IDs. """ - if not ( - edges_parent.size - == edges_child.size - == edges_left.size - == edges_right.size - == indexes_insert.size - == indexes_remove.size - ): - raise ValueError("Edge arrays must have the same size") - if mutations_position.size != mutations_node.size: - raise ValueError("Mutation arrays must have the same size") - num_nodes = nodes_order.size num_edges = edges_parent.size num_mutations = mutations_position.size @@ -145,11 +131,6 @@ def constrain_ages( Dykstra RL, "An algorithm for restricted least squares regression", JASA 1983 """ - if nodes_time.size != nodes_fixed.size: - raise ValueError("Node arrays must have the same size") - if edges_parent.size != edges_child.size: - raise ValueError("Edge arrays must have the same size") - num_edges = edges_parent.size nodes_time = nodes_time.copy() edges_cavity = np.zeros((num_edges, 2)) @@ -202,15 +183,6 @@ def contains_unary_nodes( """ Whether a node outside ``nodes_mask`` has exactly one child in some tree. """ - if not ( - edges_parent.size - == edges_left.size - == edges_right.size - == indexes_insert.size - == indexes_remove.size - ): - raise ValueError("Edge arrays must have the same size") - num_edges = edges_parent.size nodes_children = np.zeros(nodes_mask.size, dtype=np.int32) position_insert = edges_left[indexes_insert] diff --git a/tests/test_oracle_helpers.py b/tests/test_oracle_helpers.py deleted file mode 100644 index 21835167..00000000 --- a/tests/test_oracle_helpers.py +++ /dev/null @@ -1,160 +0,0 @@ -""" -The comparison helpers in ``tests/oracle/helpers.py`` detect disagreements: a helper -that passed everything would make every parity test vacuous. -""" - -import _tsdate -import numpy as np -import pytest -from oracle import errors -from oracle.errors import library_error -from oracle.helpers import ( - INF, - NAN, - assert_outcome, - assert_same_outcome, - assert_same_values, - compare, - errors_match, - kind, - outcome, -) - - -def returns(value, modify=None): - def func(x): - if modify is not None: - x[0] = modify - return value - - return func - - -def raises(exception): - def func(x): - raise exception - - return func - - -class TestAssertSameValues: - @pytest.mark.parametrize( - ("actual", "desired", "match"), - [ - pytest.param(np.nextafter(1.0, 2.0), 1.0, "differ", id="one_ulp"), - pytest.param( - np.array([1.0, NAN]), np.array([NAN, 1.0]), "differ", id="nan_place" - ), - pytest.param(1.0, NAN, "differ", id="nan_vs_number"), - pytest.param(INF, -INF, "differ", id="inf_sign"), - pytest.param((1.0, 2.0), (1.0, 2.0, 3.0), "structure", id="structure"), - pytest.param(np.zeros(3), np.zeros(4), "shape", id="shape"), - ], - ) - def test_fails(self, actual, desired, match): - with pytest.raises(AssertionError, match=match): - assert_same_values(actual, desired) - - -class TestAssertSameOutcome: - @pytest.mark.parametrize( - ("impl", "oracle", "match"), - [ - pytest.param(returns(1.0), returns(2.0), "differ", id="value"), - pytest.param( - raises(ValueError("a")), returns(1.0), "implementation", id="impl_raises" - ), - pytest.param( - returns(1.0), raises(ValueError("a")), "oracle", id="oracle_raises" - ), - pytest.param( - raises(KeyError("a")), - raises(ValueError("a")), - "implementation", - id="type", - ), - pytest.param( - raises(ValueError("a")), - raises(ValueError("b")), - "implementation", - id="message", - ), - pytest.param( - returns(1.0, modify=1.0), - returns(1.0, modify=2.0), - "argument 0", - id="inplace", - ), - ], - ) - def test_fails(self, impl, oracle, match): - x = np.zeros(2) - with pytest.raises(AssertionError, match=match): - assert_same_outcome(outcome(impl, x), outcome(oracle, x)) - - def test_compare_copies_arguments(self): - x = np.zeros(2) - compare(returns(1.0, modify=3.0), returns(1.0, modify=3.0), x) - assert x[0] == 0.0 - - def test_wrong_kind(self): - with pytest.raises(AssertionError): - assert_outcome(returns(1.0), returns(1.0), (np.zeros(1),), "nan") - - -class TestErrorsMatch: - """ - Exceptions match if they have the same type and message; an oracle - ``ZeroDivisionError`` matches the library's error for a float division by zero. - """ - - def test_same_library_error(self): - error = library_error(errors.INVALID_HYPERGEO) - assert errors_match(library_error(errors.INVALID_HYPERGEO), error) - - def test_library_error_code_differs(self): - error = library_error(errors.INVALID_HYPERGEO) - assert not errors_match(library_error(errors.ZERO_DIVISION), error) - - def test_type_differs(self): - message = _tsdate.strerror(errors.INVALID_MAX_SHAPE) - assert not errors_match(_tsdate.LibraryError(message), ValueError(message)) - assert not errors_match(ValueError(message), _tsdate.LibraryError(message)) - - def test_value_error_message_differs(self): - assert not errors_match(ValueError("b"), ValueError("a")) - - def test_zero_division(self): - actual = library_error(errors.ZERO_DIVISION) - assert errors_match(actual, ZeroDivisionError("division by zero")) - - @pytest.mark.parametrize( - "actual", - [ - library_error(errors.INVALID_HYPERGEO), - ValueError(_tsdate.strerror(errors.ZERO_DIVISION)), - ZeroDivisionError("division by zero"), - ], - ids=repr, - ) - def test_zero_division_rejects(self, actual): - assert not errors_match(actual, ZeroDivisionError("division by zero")) - - -class TestErrors: - """ - The error codes of ``oracle.errors`` are those of the library. - """ - - def test_every_code_has_a_distinct_message(self): - messages = {_tsdate.strerror(code) for code in errors.CODES} - assert len(messages) == len(errors.CODES) - assert "Unknown error" not in messages - - def test_no_further_codes(self): - code = errors.CODES[0] - 1 - assert _tsdate.strerror(code) == "Unknown error" - - def test_kind_is_the_code(self): - result = outcome(raises(library_error(errors.NO_POSTERIORS)), np.zeros(1)) - assert kind(result) == errors.NO_POSTERIORS diff --git a/tests/test_oracle_phasing.py b/tests/test_oracle_phasing.py index 3c224b4d..1cf5f274 100644 --- a/tests/test_oracle_phasing.py +++ b/tests/test_oracle_phasing.py @@ -1,7 +1,6 @@ """ -Parity of the phasing functions of ``_tsdate`` with their oracles: random -inputs built as in ``ExpectationPropagation``, degenerate inputs, and every -error. +Equivalence of the phasing functions of ``_tsdate`` with their oracles: random +inputs built as in ``ExpectationPropagation``, degenerate inputs, and every error. """ import _tsdate @@ -15,27 +14,25 @@ UNPHASED_INDIVIDUAL_EDGES, UNPHASED_LIKELIHOOD_NOT_CONSERVED, ) -from oracle.helpers import INF, NAN, compare, make_ts, shrink +from oracle.helpers import assert_same_error, assert_same_result, make_ts from tsdate.phasing import block_singletons from tsdate.rescaling import count_mutations -def sweep_args(ts): - """ - Tree sequence arguments shared by the sweep-line functions - """ - return [ - ts.mutations_node, - ts.sites_position[ts.mutations_site], - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, - ] +def block_singletons_kwargs(ts, unphased): + return dict( + individuals_unphased=np.array(unphased, dtype=bool), + nodes_individual=ts.nodes_individual, + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, + ) # nodes 0, 1 belong to individual 0, nodes 2, 3 to individual 1, node 4 is the root @@ -47,20 +44,19 @@ def sweep_args(ts): NO_INDIVIDUALS = [(1, 0, -1), (1, 0, -1), (0, 1, -1)] ONE_INDIVIDUAL = [(1, 0, 0), (1, 0, 0), (1, 0, -1), (0, 1, -1)] -# nodes, number of individuals, edges, mutations, unphased, exception of the oracle +# nodes, number of individuals, edges, mutations, unphased BLOCK_EDGE_CASES = [ - pytest.param(NODES, 2, STAR, [(1, 4)], [1, 1], None, id="no_singletons"), - pytest.param(NODES, 2, STAR, [(1, 0)], [1, 1], None, id="singleton"), - pytest.param(NODES, 2, STAR, [(1, 0)], [0, 0], None, id="all_phased"), - pytest.param(NODES, 2, STAR, [], [1, 1], None, id="no_mutations"), - pytest.param(NODES, 2, [], [(1, 0)], [1, 1], None, id="no_edges"), + pytest.param(NODES, 2, STAR, [(1, 4)], [1, 1], id="no_singletons"), + pytest.param(NODES, 2, STAR, [(1, 0)], [1, 1], id="singleton"), + pytest.param(NODES, 2, STAR, [(1, 0)], [0, 0], id="all_phased"), + pytest.param(NODES, 2, STAR, [], [1, 1], id="no_mutations"), + pytest.param(NODES, 2, [], [(1, 0)], [1, 1], id="no_edges"), pytest.param( NO_INDIVIDUALS, 0, [(0, 10, 2, 0), (0, 10, 2, 1)], [(1, 0)], [], - None, id="no_individuals", ), pytest.param( @@ -69,24 +65,11 @@ def sweep_args(ts): [(0, 10, 3, 0), (0, 10, 3, 1), (0, 10, 3, 2)], [(1, 0), (2, 2)], [1], - None, id="node_without_individual", ), - # NOTE: current behaviour, possibly a bug: reachable from real data - # (one haplotype of an unphased individual missing over a region); its block is - # never flushed and the final consistency check fails - pytest.param( - NODES, - 2, - [(0, 10, 4, 0), (0, 10, 4, 2), (0, 10, 4, 3)], - [(1, 0)], - [1, 1], - UNPHASED_INDIVIDUAL_EDGES, - id="one_haplotype_edge_missing", - ), ] -# edges, mutations, unphased, mutation_block (block ids are numbered in the order +# edges, mutations, unphased, mutations_block (block ids are numbered in the order # that blocks start; a mutation in no block is NULL) BLOCK_NUMBERING = [ pytest.param(STAR, [(1, 0)], [1, 1], [0], id="singleton"), @@ -110,42 +93,39 @@ def sweep_args(ts): class TestBlockSingletons: - @staticmethod - def args(ts, unphased): - unphased = np.array(unphased, dtype=bool) - args = sweep_args(ts) - del args[2] # the parents are not used - return [unphased, ts.nodes_individual, *args] - - @staticmethod - def compare(args): - return compare(_tsdate.block_singletons, phasing.block_singletons, *args) - @pytest.mark.parametrize( - ("nodes", "num_individuals", "edges", "mutations", "unphased", "expected_error"), + ("nodes", "num_individuals", "edges", "mutations", "unphased"), BLOCK_EDGE_CASES, ) - def test_edge_cases( - self, nodes, num_individuals, edges, mutations, unphased, expected_error - ): + def test_edge_cases(self, nodes, num_individuals, edges, mutations, unphased): ts = make_ts(nodes, edges, mutations, 10.0, num_individuals) - result = self.compare(self.args(ts, unphased)) - assert result.error == expected_error + kwargs = block_singletons_kwargs(ts, unphased) + assert_same_result(_tsdate.block_singletons, phasing.block_singletons, **kwargs) + + def test_one_haplotype_edge_missing(self): + # NOTE: current behaviour, possibly a bug: reachable from real data + # (one haplotype of an unphased individual missing over a region); its block + # is never flushed and the final consistency check fails + edges = [(0, 10, 4, 0), (0, 10, 4, 2), (0, 10, 4, 3)] + ts = make_ts(NODES, edges, [(1, 0)], 10.0, 2) + kwargs = block_singletons_kwargs(ts, [1, 1]) + assert_same_error( + _tsdate.block_singletons, + phasing.block_singletons, + UNPHASED_INDIVIDUAL_EDGES, + **kwargs, + ) @pytest.mark.parametrize( ("edges", "mutations", "unphased", "expected"), BLOCK_NUMBERING ) def test_block_numbering(self, edges, mutations, unphased, expected): ts = make_ts(NODES, edges, mutations, 10.0, 2) - _, _, mutation_block = self.compare(self.args(ts, unphased)).value - assert mutation_block.tolist() == expected - - @pytest.mark.parametrize(("index", "size"), [(4, 3), (7, 3), (3, 1)]) - def test_size_mismatch(self, index, size): - ts = make_ts(NODES, STAR, [(1, 0), (2, 1)], 10.0, 2) - args = shrink(self.args(ts, [1, 1]), index, size) - result = self.compare(args) - assert result.error is ValueError + kwargs = block_singletons_kwargs(ts, unphased) + _, _, mutations_block = assert_same_result( + _tsdate.block_singletons, phasing.block_singletons, **kwargs + ) + assert mutations_block.tolist() == expected @pytest.mark.parametrize("fraction", [0.0, 0.5, 1.0]) @pytest.mark.parametrize("seed", range(2)) @@ -153,153 +133,199 @@ def test_random(self, small_ts_unphased, seed, fraction): ts = small_ts_unphased rng = np.random.default_rng(seed) unphased = rng.random(ts.num_individuals) < fraction - args = self.args(ts, unphased) - self.compare(args) - # also the dtypes, which `compare` ignores - actual = _tsdate.block_singletons(*args) - assert actual[1].dtype == actual[2].dtype == np.int32 + kwargs = block_singletons_kwargs(ts, unphased) + assert_same_result(_tsdate.block_singletons, phasing.block_singletons, **kwargs) -@pytest.fixture(scope="module") -def blocks(small_ts_unphased): +def reallocate_unphased_kwargs(ts): """ - Likelihoods and blocks for `reallocate_unphased`, with all individuals unphased + Arguments of ``reallocate_unphased`` for ``ts``, with all individuals unphased and + every phase one half """ - ts = small_ts_unphased unphased = np.full(ts.num_individuals, True) - _, block_edges, mutation_blocks = block_singletons(ts, unphased) - likelihoods, _ = count_mutations(ts) - return ts, likelihoods, mutation_blocks, block_edges + _, blocks_edges, mutations_block = block_singletons(ts, unphased) + edges_likelihood, _ = count_mutations(ts) + return dict( + edges_likelihood=edges_likelihood, + mutations_phase=np.full(ts.num_mutations, 0.5), + mutations_block=mutations_block, + blocks_edges=blocks_edges, + ) -# likelihoods, phase, mutation_blocks, blocks_edges, outcome of the oracle +def first_blocked_mutation(kwargs): + """ + The first mutation that is in a block + """ + return np.flatnonzero(kwargs["mutations_block"] != tskit.NULL)[0] + + +# edges_likelihood, mutations_phase, mutations_block, blocks_edges REALLOCATE_SMALL = [ pytest.param( - np.array([[2.0, 5.0], [0.0, 5.0]]), - np.array([0.0, 0.0]), - np.array([0, 0], dtype=np.int32), - np.array([[0, 1]], dtype=np.int32), - None, + [[2.0, 5.0], [0.0, 5.0]], + [0.0, 0.0], + [0, 0], + [[0, 1]], id="phases_zero", ), pytest.param( - np.array([[2.0, 5.0], [0.0, 5.0]]), - np.array([1.0, 1.0]), - np.array([0, 0], dtype=np.int32), - np.array([[0, 1]], dtype=np.int32), - None, + [[2.0, 5.0], [0.0, 5.0]], + [1.0, 1.0], + [0, 0], + [[0, 1]], id="phases_one", ), pytest.param( - np.array([[2.0, 5.0], [0.0, 5.0], [7.0, 5.0]]), - np.array([0.25, 1.0, NAN]), - np.array([0, 0, -1], dtype=np.int32), - np.array([[0, 1]], dtype=np.int32), - None, + [[2.0, 5.0], [0.0, 5.0], [7.0, 5.0]], + [0.25, 1.0, np.nan], + [0, 0, -1], + [[0, 1]], id="single_block_with_unblocked_nan", ), pytest.param( - np.array([[3.0, 1.0], [1.0, 1.0], [0.0, 1.0]]), - np.full(4, 0.5), - np.array([0, 0, 1, 1], dtype=np.int32), - np.array([[0, 1], [1, 2]], dtype=np.int32), - None, + [[3.0, 1.0], [1.0, 1.0], [0.0, 1.0]], + [0.5, 0.5, 0.5, 0.5], + [0, 0, 1, 1], + [[0, 1], [1, 2]], id="edge_in_two_blocks", ), pytest.param( np.zeros((0, 2)), - np.zeros(0), - np.zeros(0, dtype=np.int32), - np.zeros((0, 2), dtype=np.int32), - None, + [], + [], + np.zeros((0, 2)), id="nothing_at_all", ), - pytest.param( - np.ones((2, 2)), - np.array([0.5]), - np.array([0], dtype=np.int32), - np.array([[0, -1]], dtype=np.int32), - BLOCK_OUT_OF_BOUNDS, - id="null_edge_in_block", - ), ] class TestReallocateUnphased: - @staticmethod - def compare(*args): - return compare(_tsdate.reallocate_unphased, phasing.reallocate_unphased, *args) - @pytest.mark.parametrize( - ("lik", "phase", "mutation_blocks", "blocks_edges", "expected_error"), + ("edges_likelihood", "mutations_phase", "mutations_block", "blocks_edges"), REALLOCATE_SMALL, ) - def test_small(self, lik, phase, mutation_blocks, blocks_edges, expected_error): - result = self.compare(lik, phase, mutation_blocks, blocks_edges) - assert result.error == expected_error + def test_small( + self, edges_likelihood, mutations_phase, mutations_block, blocks_edges + ): + assert_same_result( + _tsdate.reallocate_unphased, + phasing.reallocate_unphased, + edges_likelihood=np.array(edges_likelihood, dtype=np.float64), + mutations_phase=np.array(mutations_phase, dtype=np.float64), + mutations_block=np.array(mutations_block, dtype=np.int32), + blocks_edges=np.array(blocks_edges, dtype=np.int32), + ) + + def test_null_edge_in_block(self): + assert_same_error( + _tsdate.reallocate_unphased, + phasing.reallocate_unphased, + BLOCK_OUT_OF_BOUNDS, + edges_likelihood=np.ones((2, 2)), + mutations_phase=np.array([0.5]), + mutations_block=np.array([0], dtype=np.int32), + blocks_edges=np.array([[0, -1]], dtype=np.int32), + ) @pytest.mark.parametrize("mode", ["fractional", "mixed"]) @pytest.mark.parametrize("seed", range(3)) - def test_random(self, blocks, seed, mode): - ts, lik, mutation_blocks, block_edges = blocks + def test_random(self, small_ts_unphased, seed, mode): + ts = small_ts_unphased rng = np.random.default_rng(seed) + kwargs = reallocate_unphased_kwargs(ts) if mode == "fractional": - phase = rng.uniform(0, 1, ts.num_mutations) + kwargs["mutations_phase"] = rng.uniform(0, 1, ts.num_mutations) else: - phase = rng.choice([0.0, 1.0, 0.5, 0.25], ts.num_mutations) - self.compare(lik, phase, mutation_blocks, block_edges) - - @pytest.mark.parametrize("value", [1.5, -1e-9, INF, -INF]) - def test_phase_out_of_range(self, blocks, value): - _, lik, mutation_blocks, block_edges = blocks - phase = np.full(mutation_blocks.size, 0.5) - phase[np.flatnonzero(mutation_blocks >= 0)[0]] = value - result = self.compare(lik, phase, mutation_blocks, block_edges) - assert result.error == PHASE_OUT_OF_RANGE - - @pytest.mark.parametrize("value", [NAN, 7.0]) - def test_phase_ignored_without_block(self, blocks, value): - _, lik, mutation_blocks, block_edges = blocks - phase = np.full(mutation_blocks.size, 0.5) - phase[mutation_blocks == tskit.NULL] = value - result = self.compare(lik, phase, mutation_blocks, block_edges) - assert result.error is None - - def test_nan_phase(self, blocks): + phases = [0.0, 1.0, 0.5, 0.25] + kwargs["mutations_phase"] = rng.choice(phases, ts.num_mutations) + assert_same_result( + _tsdate.reallocate_unphased, phasing.reallocate_unphased, **kwargs + ) + + @pytest.mark.parametrize("value", [1.5, -1e-9, np.inf, -np.inf]) + def test_phase_out_of_range(self, small_ts_unphased, value): + kwargs = reallocate_unphased_kwargs(small_ts_unphased) + kwargs["mutations_phase"][first_blocked_mutation(kwargs)] = value + assert_same_error( + _tsdate.reallocate_unphased, + phasing.reallocate_unphased, + PHASE_OUT_OF_RANGE, + **kwargs, + ) + + @pytest.mark.parametrize("value", [np.nan, 7.0]) + def test_phase_ignored_without_block(self, small_ts_unphased, value): + kwargs = reallocate_unphased_kwargs(small_ts_unphased) + unblocked = kwargs["mutations_block"] == tskit.NULL + kwargs["mutations_phase"][unblocked] = value + assert_same_result( + _tsdate.reallocate_unphased, phasing.reallocate_unphased, **kwargs + ) + + def test_nan_phase(self, small_ts_unphased): # NOTE: current behaviour, possibly a bug: a NaN phase on a # blocked mutation is skipped, leaving its singleton unallocated, so the # final `np.isclose` check fails. It only passes if the likelihoods happen to # total one less - _, lik, mutation_blocks, block_edges = blocks - phase = np.full(mutation_blocks.size, 0.5) - phase[np.flatnonzero(mutation_blocks >= 0)[0]] = NAN - result = self.compare(lik, phase, mutation_blocks, block_edges) - assert result.error == UNPHASED_LIKELIHOOD_NOT_CONSERVED - lik = lik.copy() - lik[block_edges[0, 0], 0] -= 1.0 - result = self.compare(lik, phase, mutation_blocks, block_edges) - assert result.error is None - - @pytest.mark.parametrize("case", ["no_mutations", "all_unblocked"]) - def test_blocks_without_singletons(self, blocks, case): - # likelihood mass on the block edges, but no mutation to allocate it - ts, lik, _, block_edges = blocks - size = 0 if case == "no_mutations" else ts.num_mutations - phase = np.full(size, 0.5) - mutation_blocks = np.full(size, tskit.NULL, dtype=np.int32) - result = self.compare(lik, phase, mutation_blocks, block_edges) - assert result.error == UNPHASED_LIKELIHOOD_NOT_CONSERVED - - @pytest.mark.parametrize("case", ["phase", "blocks_transposed"]) - def test_size_mismatch(self, blocks, case): - ts, lik, mutation_blocks, block_edges = blocks - phase = np.full(ts.num_mutations, 0.5) - if case == "phase": - phase = phase[:-1] - else: - block_edges = np.ascontiguousarray(block_edges.T) - result = self.compare(lik, phase, mutation_blocks, block_edges) - assert result.error is ValueError + kwargs = reallocate_unphased_kwargs(small_ts_unphased) + kwargs["mutations_phase"][first_blocked_mutation(kwargs)] = np.nan + assert_same_error( + _tsdate.reallocate_unphased, + phasing.reallocate_unphased, + UNPHASED_LIKELIHOOD_NOT_CONSERVED, + **kwargs, + ) + first_edge = kwargs["blocks_edges"][0, 0] + kwargs["edges_likelihood"][first_edge, 0] -= 1.0 + assert_same_result( + _tsdate.reallocate_unphased, phasing.reallocate_unphased, **kwargs + ) + + def test_no_mutations(self, small_ts_unphased): + # likelihood on the edges of the blocks, but no mutation to allocate it + kwargs = reallocate_unphased_kwargs(small_ts_unphased) + kwargs["mutations_phase"] = np.zeros(0) + kwargs["mutations_block"] = np.zeros(0, dtype=np.int32) + assert_same_error( + _tsdate.reallocate_unphased, + phasing.reallocate_unphased, + UNPHASED_LIKELIHOOD_NOT_CONSERVED, + **kwargs, + ) + + def test_no_mutations_in_blocks(self, small_ts_unphased): + # likelihood on the edges of the blocks, but no mutation to allocate it + kwargs = reallocate_unphased_kwargs(small_ts_unphased) + kwargs["mutations_block"][:] = tskit.NULL + assert_same_error( + _tsdate.reallocate_unphased, + phasing.reallocate_unphased, + UNPHASED_LIKELIHOOD_NOT_CONSERVED, + **kwargs, + ) + + +def mutation_frequency_kwargs(ts, sample_sets): + """ + Arguments of ``mutation_frequency`` for ``ts``, with a column of ``nodes_sample`` + for each list of nodes in ``sample_sets`` + """ + nodes_sample = np.zeros((ts.num_nodes, len(sample_sets)), dtype=bool) + for i, nodes in enumerate(sample_sets): + nodes_sample[list(nodes), i] = True + return dict( + nodes_sample=nodes_sample, + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, + ) # samples 0, 1, 2 (time 0), internal nodes 3 (time 1) and 4 (time 2); node 3 is a @@ -307,6 +333,7 @@ def test_size_mismatch(self, blocks, case): FREQ_NODES = [(1, 0), (1, 0), (1, 0), (0, 1), (0, 2)] FREQ_EDGES = [(0, 10, 3, 0), (0, 10, 3, 1), (0, 5, 4, 3), (0, 10, 4, 2), (5, 10, 4, 3)] FREQ_MUTATIONS = [(1, 0), (2, 3), (3, 4), (6, 2), (7, 3)] +FREQ_TS = make_ts(FREQ_NODES, FREQ_EDGES, FREQ_MUTATIONS, 10.0) SAMPLE_SETS = [ pytest.param([[0, 1, 2]], id="all_samples"), @@ -321,80 +348,66 @@ def test_size_mismatch(self, blocks, case): ] -@pytest.fixture(scope="module") -def freq_ts(): - return make_ts(FREQ_NODES, FREQ_EDGES, FREQ_MUTATIONS, 10.0) - - class TestMutationFrequency: - @staticmethod - def compare(nodes_sample, args): - return compare( - _tsdate.mutation_frequency, - phasing.mutation_frequency, - nodes_sample, - *args, + @pytest.mark.parametrize("sample_sets", SAMPLE_SETS) + def test_sample_sets(self, sample_sets): + kwargs = mutation_frequency_kwargs(FREQ_TS, sample_sets) + assert_same_result( + _tsdate.mutation_frequency, phasing.mutation_frequency, **kwargs ) - @staticmethod - def nodes_sample(ts, members): - nodes_sample = np.zeros((ts.num_nodes, len(members)), dtype=bool) - for i, m in enumerate(members): - nodes_sample[list(m), i] = True - return nodes_sample - - @pytest.mark.parametrize("members", SAMPLE_SETS) - def test_sample_sets(self, freq_ts, members): - nodes_sample = self.nodes_sample(freq_ts, members) - self.compare(nodes_sample, sweep_args(freq_ts)) - def test_no_mutations(self): ts = make_ts([(1, 0), (0, 1)], [(0, 10, 1, 0)], [], 10.0) - self.compare(self.nodes_sample(ts, [[0]]), sweep_args(ts)) + kwargs = mutation_frequency_kwargs(ts, [[0]]) + assert_same_result( + _tsdate.mutation_frequency, phasing.mutation_frequency, **kwargs + ) def test_no_edges(self): # NOTE: current behaviour, possibly a bug: with no edges the # sweep is never entered, so every frequency is zero, even above a member ts = make_ts([(1, 0), (0, 1)], [], [(1, 0), (2, 1)], 10.0) - self.compare(self.nodes_sample(ts, [[0, 1]]), sweep_args(ts)) + kwargs = mutation_frequency_kwargs(ts, [[0, 1]]) + assert_same_result( + _tsdate.mutation_frequency, phasing.mutation_frequency, **kwargs + ) def test_mutation_beyond_last_edge(self): nodes = [(1, 0), (1, 0), (0, 1)] edges = [(0, 5, 2, 0), (0, 5, 2, 1)] ts = make_ts(nodes, edges, [(1, 2), (7, 2)], 10.0) - self.compare(self.nodes_sample(ts, [[0, 1]]), sweep_args(ts)) + kwargs = mutation_frequency_kwargs(ts, [[0, 1]]) + assert_same_result( + _tsdate.mutation_frequency, phasing.mutation_frequency, **kwargs + ) def test_mutation_at_breakpoint(self): # a mutation exactly at a breakpoint belongs to the tree to its right ts = make_ts(FREQ_NODES, FREQ_EDGES, [(5, 4)], 10.0) - self.compare(self.nodes_sample(ts, [[0, 1, 2]]), sweep_args(ts)) + kwargs = mutation_frequency_kwargs(ts, [[0, 1, 2]]) + assert_same_result( + _tsdate.mutation_frequency, phasing.mutation_frequency, **kwargs + ) - def test_unsorted_mutations(self, freq_ts): + def test_unsorted_mutations(self): order = np.array([3, 0, 4, 1, 2]) - args = sweep_args(freq_ts) - args[0], args[1] = args[0][order], args[1][order] - self.compare(self.nodes_sample(freq_ts, [[0, 1, 2]]), args) - - @pytest.mark.parametrize(("index", "size"), [(3, 3), (6, 3), (1, 2)]) - def test_size_mismatch(self, freq_ts, index, size): - nodes_sample = np.ones((freq_ts.num_nodes, 1), dtype=bool) - args = shrink(sweep_args(freq_ts), index, size) - result = self.compare(nodes_sample, args) - assert result.error is ValueError + kwargs = mutation_frequency_kwargs(FREQ_TS, [[0, 1, 2]]) + kwargs["mutations_node"] = kwargs["mutations_node"][order] + kwargs["mutations_position"] = kwargs["mutations_position"][order] + assert_same_result( + _tsdate.mutation_frequency, phasing.mutation_frequency, **kwargs + ) @pytest.mark.parametrize("num_sets", [1, 4]) @pytest.mark.parametrize("seed", range(2)) def test_random(self, small_ts, seed, num_sets): ts = small_ts rng = np.random.default_rng(seed) - members = [ - rng.choice( - ts.samples(), size=int(rng.integers(0, ts.num_samples + 1)), replace=False - ) - for _ in range(num_sets) - ] - nodes_sample = self.nodes_sample(ts, members) - self.compare(nodes_sample, sweep_args(ts)) - # also the dtype, which `compare` ignores - actual = _tsdate.mutation_frequency(nodes_sample, *sweep_args(ts)) - assert actual.dtype == np.int32 + sample_sets = [] + for _ in range(num_sets): + size = rng.integers(0, ts.num_samples + 1) + sample_sets.append(rng.choice(ts.samples(), size=size, replace=False)) + kwargs = mutation_frequency_kwargs(ts, sample_sets) + assert_same_result( + _tsdate.mutation_frequency, phasing.mutation_frequency, **kwargs + ) diff --git a/tests/test_oracle_util.py b/tests/test_oracle_util.py index 3cf9358c..ff1b707e 100644 --- a/tests/test_oracle_util.py +++ b/tests/test_oracle_util.py @@ -1,6 +1,6 @@ """ -Parity of the tree sequence utilities of ``_tsdate`` with their oracles: simulated tree -sequences, degenerate inputs, and every error. +Equivalence of the tree sequence utilities of ``_tsdate`` with their oracles: +simulated tree sequences, degenerate inputs, and every error. """ import _tsdate @@ -9,7 +9,7 @@ import tskit from oracle import util from oracle.errors import FIXED_NODES_VIOLATE_CONSTRAINT, MUTATION_NODE_NOT_IN_TREE -from oracle.helpers import NAN, assert_outcome, b1, compare, f64, i32, make_ts, shrink +from oracle.helpers import assert_same_error, assert_same_result, make_ts @pytest.fixture(params=["small_ts", "small_ts_historical"]) @@ -21,8 +21,9 @@ def sample_flags(ts): return np.bitwise_and(ts.nodes_flags, tskit.NODE_IS_SAMPLE).astype(bool) -# parent, child, left, right, excluded, split nodes (new nodes are numbered from the -# number of nodes, and each is a copy of an old node: `split_nodes` lists the old ids) +# edges_parent, edges_child, edges_left, edges_right, nodes_excluded, and the +# expected split_nodes (new nodes are numbered from the number of nodes, and each is +# a copy of an old node: `split_nodes` lists the old ids) SPLIT_CASES = [ pytest.param([2, 2], [0, 1], [0, 0], [10, 10], [1, 1, 0], [], id="no_disjoint"), pytest.param([], [], [], [], [1, 0], [], id="no_edges"), @@ -65,61 +66,56 @@ def sample_flags(ts): class TestSplitDisjointNodes: - @staticmethod - def compare(*args): - return compare(_tsdate.split_disjoint_nodes, util.split_disjoint_nodes, *args) - @pytest.mark.parametrize( ("parent", "child", "left", "right", "excluded", "expected"), SPLIT_CASES ) def test_edge_cases(self, parent, child, left, right, excluded, expected): - args = (i32(*parent), i32(*child), f64(*left), f64(*right), b1(*excluded)) - _, _, _, split_nodes = self.compare(*args).value + _, _, _, split_nodes = assert_same_result( + _tsdate.split_disjoint_nodes, + util.split_disjoint_nodes, + edges_parent=np.array(parent, dtype=np.int32), + edges_child=np.array(child, dtype=np.int32), + edges_left=np.array(left, dtype=np.float64), + edges_right=np.array(right, dtype=np.float64), + nodes_excluded=np.array(excluded, dtype=bool), + ) assert split_nodes.tolist() == expected - @pytest.mark.parametrize(("index", "size"), [(1, 1), (2, 1), (3, 1)]) - def test_size_mismatch(self, index, size): - args = [i32(2, 2), i32(0, 1), f64(0, 0), f64(10, 10), b1(1, 1, 0)] - result = self.compare(*shrink(args, index, size)) - assert result.error is ValueError - def test_simulated(self, sim_ts): - ts = sim_ts - args = ( - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - sample_flags(ts), + assert_same_result( + _tsdate.split_disjoint_nodes, + util.split_disjoint_nodes, + edges_parent=sim_ts.edges_parent, + edges_child=sim_ts.edges_child, + edges_left=sim_ts.edges_left, + edges_right=sim_ts.edges_right, + nodes_excluded=sample_flags(sim_ts), ) - self.compare(*args) - # also the dtypes, which `compare` ignores - actual = _tsdate.split_disjoint_nodes(*args) - assert all(a.dtype == np.int32 for a in actual) -def relabel_args(ts): +def relabel_mutations_node_kwargs(ts): """ - Arguments of `relabel_mutations_node`, with the nodes split as by `util` + Arguments of ``relabel_mutations_node``, with the nodes of ``ts`` split as by + ``util.split_disjoint_nodes`` """ - parent, child, order, _ = util.split_disjoint_nodes( - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - sample_flags(ts), + edges_parent, edges_child, nodes_order, _ = util.split_disjoint_nodes( + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + nodes_excluded=sample_flags(ts), + ) + return dict( + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + nodes_order=nodes_order, + edges_parent=edges_parent, + edges_child=edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, ) - return [ - ts.mutations_node, - ts.sites_position[ts.mutations_site], - order, - parent, - child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ] # nodes 0, 1 are samples, 2 and 3 are internal and have a gap at [4, 6) @@ -128,107 +124,90 @@ def relabel_args(ts): GAP_EDGES += [(0, 4, 3, 2), (6, 10, 3, 2)] BINARY_EDGES = [(0, 10, 2, 0), (0, 10, 2, 1)] -# nodes, edges, mutations, sequence length, exception of the oracle +# nodes, edges, mutations, sequence length RELABEL_CASES = [ - pytest.param(GAP_NODES, GAP_EDGES, [], 10.0, None, id="no_mutations"), + pytest.param(GAP_NODES, GAP_EDGES, [], 10.0, id="no_mutations"), pytest.param( - GAP_NODES[:3], - BINARY_EDGES, - [(1, 0), (2, 2), (3, 1)], - 10.0, - None, - id="no_splits", + GAP_NODES[:3], BINARY_EDGES, [(1, 0), (2, 2), (3, 1)], 10.0, id="no_splits" ), # the sweep stops at the largest edge right coordinate: later mutations are NULL - pytest.param( - GAP_NODES, GAP_EDGES, [(1, 2), (10.0, 2)], 20.0, None, id="beyond_last_edge" - ), - pytest.param( - GAP_NODES, - BINARY_EDGES, - [(1, 3)], - 10.0, - MUTATION_NODE_NOT_IN_TREE, - id="node_not_in_tree", - ), + pytest.param(GAP_NODES, GAP_EDGES, [(1, 2), (10.0, 2)], 20.0, id="beyond_last_edge"), ] class TestRelabelMutationsNode: - @staticmethod - def compare(args): - return compare(_tsdate.relabel_mutations_node, util.relabel_mutations_node, *args) - - @pytest.mark.parametrize( - ("nodes", "edges", "mutations", "length", "expected_error"), RELABEL_CASES - ) - def test_edge_cases(self, nodes, edges, mutations, length, expected_error): + @pytest.mark.parametrize(("nodes", "edges", "mutations", "length"), RELABEL_CASES) + def test_edge_cases(self, nodes, edges, mutations, length): ts = make_ts(nodes, edges, mutations, length) - result = self.compare(relabel_args(ts)) - assert result.error == expected_error + kwargs = relabel_mutations_node_kwargs(ts) + assert_same_result( + _tsdate.relabel_mutations_node, util.relabel_mutations_node, **kwargs + ) + + def test_node_not_in_tree(self): + # node 3 has no edges + ts = make_ts(GAP_NODES, BINARY_EDGES, [(1, 3)], 10.0) + kwargs = relabel_mutations_node_kwargs(ts) + assert_same_error( + _tsdate.relabel_mutations_node, + util.relabel_mutations_node, + MUTATION_NODE_NOT_IN_TREE, + **kwargs, + ) def test_mutations_on_split_nodes(self): mutations = [(0.5, 0), (1, 2), (2, 3), (5, 0), (7, 2), (8, 3)] ts = make_ts(GAP_NODES, GAP_EDGES, mutations, 10.0) - result = self.compare(relabel_args(ts)) + kwargs = relabel_mutations_node_kwargs(ts) + result = assert_same_result( + _tsdate.relabel_mutations_node, util.relabel_mutations_node, **kwargs + ) # right-hand pieces of nodes 2 and 3 are the new nodes 4 and 5; the mutation # at 5 is in the gap, on the (unsplit) sample 0 - assert result.value.tolist() == [0, 2, 3, 0, 4, 5] - - @pytest.mark.parametrize(("index", "size"), [(4, 2), (7, 2), (1, 1)]) - def test_size_mismatch(self, index, size): - ts = make_ts(GAP_NODES, GAP_EDGES, [(1, 2), (7, 2)], 10.0) - result = self.compare(shrink(relabel_args(ts), index, size)) - assert result.error is ValueError + assert result.tolist() == [0, 2, 3, 0, 4, 5] def test_simulated(self, sim_ts): - args = relabel_args(sim_ts) - self.compare(args) - # also the dtype, which `compare` ignores - actual = _tsdate.relabel_mutations_node(*args) - assert actual.dtype == np.int32 + kwargs = relabel_mutations_node_kwargs(sim_ts) + assert_same_result( + _tsdate.relabel_mutations_node, util.relabel_mutations_node, **kwargs + ) + +def constrain_ages_kwargs(times, fixed, parents, children, epsilon, max_iterations): + return dict( + nodes_time=np.array(times, dtype=np.float64), + nodes_fixed=np.array(fixed, dtype=bool), + edges_parent=np.array(parents, dtype=np.int32), + edges_child=np.array(children, dtype=np.int32), + epsilon=epsilon, + max_iterations=max_iterations, + ) -# times, fixed, parents, children, epsilon, max_iterations, outcome category + +# nodes_time, nodes_fixed, edges_parent, edges_child # node 2 (age 1) is above samples 0, 1; node 3 (age 0.5) is above node 2: violated VIOLATED = ([0, 0, 1.0, 0.5], [1, 1, 0, 0], [2, 3], [0, 2]) CONSISTENT = ([0, 0, 1.0], [1, 1, 0], [2, 2], [0, 1]) # one edge with parent age 0 and child age 1 (a violation); node 0 is the parent INVERTED = ([0.0, 1.0], [0, 0], [0], [1]) + +# nodes_time, nodes_fixed, edges_parent, edges_child, epsilon, max_iterations CONSTRAIN_EDGE_CASES = [ - pytest.param(*CONSISTENT, 1e-6, 0, "finite", id="consistent_forced"), - pytest.param(*CONSISTENT, 1e-6, 10, "finite", id="consistent_iterated"), - pytest.param(*CONSISTENT, 1.0, 0, "finite", id="branch_length_equals_epsilon"), - pytest.param(*CONSISTENT, 1.0, 10, "finite", id="branch_length_equals_epsilon_it"), - pytest.param([0, 1.0], [1, 0], [1], [0], 2.0, 0, "finite", id="shorter_than_epsilon"), - pytest.param(*VIOLATED, 1e-6, -1, "finite", id="negative_iterations"), - pytest.param(*INVERTED, 0.1, 100, "finite", id="free_nodes_meet"), - pytest.param([0.0, 1.0], [1, 0], [0], [1], 0.1, 100, "finite", id="fixed_parent"), - pytest.param([0.0, 1.0], [0, 1], [0], [1], 0.1, 100, "finite", id="fixed_child"), - # NOTE: current behaviour, possibly a bug: two fixed nodes on a - # violated edge are an error (reachable via `constrain_ages` with - # inconsistent ancient sample ages); with no iterations the forcing step - # silently changes the age of a fixed node - pytest.param( - [0.0, 1.0], - [1, 1], - [0], - [1], - 0.1, - 100, - FIXED_NODES_VIOLATE_CONSTRAINT, - id="both_fixed", - ), - pytest.param([0.0, 1.0], [1, 1], [0], [1], 0.1, 0, "finite", id="both_fixed_forced"), - pytest.param([0.0, 1.0], [1, 0], [], [], 0.1, 10, "finite", id="no_edges"), - pytest.param([], [], [], [], 0.1, 10, "finite", id="no_nodes"), - # NaN comparisons are all false: no branch is a violation, and NaN is carried - pytest.param([0.0, NAN], [1, 0], [1], [0], 0.1, 3, "nan", id="nan_child"), - pytest.param([NAN, 1.0], [1, 0], [1], [0], 0.1, 3, "nan", id="nan_parent"), - pytest.param([0.0, 1.0], [1, 0], [1], [0], -0.5, 3, "finite", id="negative_epsilon"), - pytest.param( - [0.0, 0.0], [1, 0], [1], [0], 0.0, 3, "finite", id="equal_ages_zero_eps" - ), + pytest.param(*CONSISTENT, 1e-6, 0, id="consistent_forced"), + pytest.param(*CONSISTENT, 1e-6, 10, id="consistent_iterated"), + pytest.param(*CONSISTENT, 1.0, 0, id="branch_length_equals_epsilon"), + pytest.param(*CONSISTENT, 1.0, 10, id="branch_length_equals_epsilon_it"), + pytest.param([0, 1.0], [1, 0], [1], [0], 2.0, 0, id="shorter_than_epsilon"), + pytest.param(*VIOLATED, 1e-6, -1, id="negative_iterations"), + pytest.param(*INVERTED, 0.1, 100, id="free_nodes_meet"), + pytest.param([0.0, 1.0], [1, 0], [0], [1], 0.1, 100, id="fixed_parent"), + pytest.param([0.0, 1.0], [0, 1], [0], [1], 0.1, 100, id="fixed_child"), + # with no iterations the forcing step changes the age of a fixed node + pytest.param([0.0, 1.0], [1, 1], [0], [1], 0.1, 0, id="both_fixed_forced"), + pytest.param([0.0, 1.0], [1, 0], [], [], 0.1, 10, id="no_edges"), + pytest.param([], [], [], [], 0.1, 10, id="no_nodes"), + pytest.param([0.0, 1.0], [1, 0], [1], [0], -0.5, 3, id="negative_epsilon"), + pytest.param([0.0, 0.0], [1, 0], [1], [0], 0.0, 3, id="equal_ages_zero_eps"), pytest.param( [1.0] * 5, [1, 0, 0, 0, 0], @@ -236,78 +215,98 @@ def test_simulated(self, sim_ts): [0, 1, 2, 3], 1e-3, 1000, - "finite", id="slow_convergence_chain", ), ] class TestConstrainAges: - @staticmethod - def args(times, fixed, parents, children, epsilon, max_iterations): - return ( - f64(*times), - b1(*fixed), - i32(*parents), - i32(*children), - epsilon, - max_iterations, - ) - - @staticmethod - def compare(args): - return compare(_tsdate.constrain_ages, util.constrain_ages, *args) - @pytest.mark.parametrize("max_iterations", [0, 1, 1000]) @pytest.mark.parametrize("epsilon", [0.0, 1e-6, 0.5]) def test_violation(self, epsilon, max_iterations): - self.compare(self.args(*VIOLATED, epsilon, max_iterations)) + kwargs = constrain_ages_kwargs(*VIOLATED, epsilon, max_iterations) + assert_same_result(_tsdate.constrain_ages, util.constrain_ages, **kwargs) @pytest.mark.parametrize( - ("times", "fixed", "parents", "children", "epsilon", "max_iterations", "kind"), + ("times", "fixed", "parents", "children", "epsilon", "max_iterations"), CONSTRAIN_EDGE_CASES, ) - def test_edge_cases( - self, times, fixed, parents, children, epsilon, max_iterations, kind - ): - args = self.args(times, fixed, parents, children, epsilon, max_iterations) - assert_outcome(_tsdate.constrain_ages, util.constrain_ages, args, kind) + def test_edge_cases(self, times, fixed, parents, children, epsilon, max_iterations): + kwargs = constrain_ages_kwargs( + times, fixed, parents, children, epsilon, max_iterations + ) + result = assert_same_result(_tsdate.constrain_ages, util.constrain_ages, **kwargs) + assert np.all(np.isfinite(result)) @pytest.mark.parametrize( - "args", - [ - pytest.param(([0, 1], [1], [1], [0]), id="fixed"), - pytest.param(([0, 1], [1, 0], [1], [0, 0]), id="children"), - ], + "times", [pytest.param([0.0, np.nan]), pytest.param([np.nan, 1.0])] ) - def test_size_mismatch(self, args): - result = self.compare(self.args(*args, 0.1, 3)) - assert result.error is ValueError + def test_nan_age(self, times): + # NaN comparisons are all false: no branch is a violation, and NaN is carried + kwargs = constrain_ages_kwargs(times, [1, 0], [1], [0], 0.1, 3) + result = assert_same_result(_tsdate.constrain_ages, util.constrain_ages, **kwargs) + assert np.isnan(result).tolist() == np.isnan(times).tolist() + + def test_both_fixed(self): + # NOTE: current behaviour, possibly a bug: two fixed nodes on a + # violated edge are an error (reachable via `constrain_ages` with + # inconsistent ancient sample ages) + kwargs = constrain_ages_kwargs([0.0, 1.0], [1, 1], [0], [1], 0.1, 100) + assert_same_error( + _tsdate.constrain_ages, + util.constrain_ages, + FIXED_NODES_VIOLATE_CONSTRAINT, + **kwargs, + ) @pytest.mark.parametrize("mode", ["iterated", "forced"]) @pytest.mark.parametrize("seed", range(2)) def test_simulated(self, sim_ts, seed, mode): ts = sim_ts rng = np.random.default_rng(seed) + if mode == "iterated": + noise = rng.uniform(0.9, 1.1, ts.num_nodes) + epsilon = 1e-6 + max_iterations = 50 + else: + noise = rng.uniform(0.5, 1.5, ts.num_nodes) + epsilon = 1e-2 + max_iterations = 0 fixed = sample_flags(ts) - low, high, epsilon, max_iterations = { - "iterated": (0.9, 1.1, 1e-6, 50), - "forced": (0.5, 1.5, 1e-2, 0), - }[mode] - nodes_time = ts.nodes_time * rng.uniform(low, high, ts.num_nodes) + nodes_time = ts.nodes_time * noise nodes_time[fixed] = ts.nodes_time[fixed] - args = ( - nodes_time, - fixed, - ts.edges_parent, - ts.edges_child, - epsilon, - max_iterations, + assert_same_result( + _tsdate.constrain_ages, + util.constrain_ages, + nodes_time=nodes_time, + nodes_fixed=fixed, + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + epsilon=epsilon, + max_iterations=max_iterations, ) - self.compare(args) -# nodes, edges, expected for (samples skipped, samples not skipped) +def contains_unary_nodes_kwargs(ts, skip_samples): + """ + Arguments of ``contains_unary_nodes`` for ``ts``, with the samples masked if + ``skip_samples`` + """ + nodes_mask = np.full(ts.num_nodes, False) + if skip_samples: + nodes_mask[ts.samples()] = True + return dict( + nodes_mask=nodes_mask, + edges_parent=ts.edges_parent, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, + ) + + +# nodes, edges, and the expected results with the samples skipped and not skipped UNARY_CASES = [ pytest.param([(1, 0), (1, 0), (0, 1)], BINARY_EDGES, False, False, id="binary"), pytest.param([(1, 0), (1, 0)], [], False, False, id="no_edges"), @@ -361,40 +360,29 @@ def test_simulated(self, sim_ts, seed, mode): class TestContainsUnaryNodes: - @staticmethod - def compare(ts, mask): - return compare( - _tsdate.contains_unary_nodes, - util.contains_unary_nodes, - mask, - ts.edges_parent, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, - ) - - @staticmethod - def mask(ts, skip_samples): - mask = np.full(ts.num_nodes, False) - if skip_samples: - mask[ts.samples()] = True - return mask - @pytest.mark.parametrize(("nodes", "edges", "skipped", "not_skipped"), UNARY_CASES) def test_hand_built(self, nodes, edges, skipped, not_skipped): ts = make_ts(nodes, edges, [], 10.0) - result = self.compare(ts, self.mask(ts, True)) - assert bool(result.value) is skipped - result = self.compare(ts, self.mask(ts, False)) - assert bool(result.value) is not_skipped + kwargs = contains_unary_nodes_kwargs(ts, skip_samples=True) + result = assert_same_result( + _tsdate.contains_unary_nodes, util.contains_unary_nodes, **kwargs + ) + assert result is skipped + kwargs = contains_unary_nodes_kwargs(ts, skip_samples=False) + result = assert_same_result( + _tsdate.contains_unary_nodes, util.contains_unary_nodes, **kwargs + ) + assert result is not_skipped def test_all_nodes_masked(self): nodes = [(1, 0), (0, 1), (0, 2)] ts = make_ts(nodes, [(0, 10, 1, 0), (0, 10, 2, 1)], [], 10.0) - result = self.compare(ts, np.full(ts.num_nodes, True)) - assert not result.value + kwargs = contains_unary_nodes_kwargs(ts, skip_samples=False) + kwargs["nodes_mask"][:] = True + result = assert_same_result( + _tsdate.contains_unary_nodes, util.contains_unary_nodes, **kwargs + ) + assert result is False @pytest.mark.parametrize("skip_samples", [True, False]) @pytest.mark.parametrize("keep", [None, 3, 20]) @@ -402,4 +390,7 @@ def test_simulated(self, sim_ts, keep, skip_samples): ts = sim_ts if keep is not None: ts = ts.simplify(ts.samples()[:keep], keep_unary=True) - self.compare(ts, self.mask(ts, skip_samples)) + kwargs = contains_unary_nodes_kwargs(ts, skip_samples) + assert_same_result( + _tsdate.contains_unary_nodes, util.contains_unary_nodes, **kwargs + )