Skip to content

C port followup: edge cases in the gamma projections and moment approximations #536

Backlog

Description

@nspope

These behaviours of the moment calculations and gamma fits in lib/approx.c were kept as-is when the numerical code moved from numba to C (#534), and are worth a look. Reproducers call the low-level _tsdate module; projections take natural parameters (shape - 1, rate). When a projection's moments are unusable it returns NaN, and the EP update for that edge is skipped (see the EP issue for how silently that happens).

The reproducers that call internal functions of _tsdate (e.g. _tsdate.moments) run at commit d8a95ac; later commits in #534 removed those exports and test the functions in lib/tests/tests.c instead.

Variance by cancellation goes negative at large shapes

The moment functions (tsd_moments and the other *_moments) compute the variance as E[x^2] - E[x]^2. At large shapes this cancels to zero or below, so the projection returns NaN and the update is skipped:

import _tsdate
_tsdate.moments(1e8, 1e5, 1e8, 1e5, 1.0, 1e-4)
# (1181551036.3, 1000.087, -0.412, 999.913, -0.412)   <- negative variances
_tsdate.gamma_projection(1e8 - 1, 1e5, 1e8 - 1, 1e5, 1.0, 1e-4)
# (nan, 99999999.0, 100000.0, 99999999.0, 100000.0)   <- NaN, posterior = cavity

mutation_unphased_moments can return a probability above one

tsd_mutation_unphased_moments uses a Laplace approximation for the phase probability, which can exceed one for finite mean and variance; tsd_mutation_unphased_projection then returns NaN:

args = (1289.8261024396659, 2.1161296052067344, 0.15552864791315738,
        0.0007984796762152916, 1.0, 4.811169071413665e-07)
_tsdate.mutation_unphased_moments(*args)          # (1.0305..., 552.31..., 250943.1...)
_tsdate.mutation_unphased_projection(
    args[0] - 1, args[1], args[2] - 1, args[3], args[4], args[5])  # (nan, nan, nan)

A NaN phase on an unphased singleton then breaks reallocate_unphased (see the phasing issue).

approximate_gamma_mom gives shape -1 when the mean underflows

tsd_approximate_gamma_mom squares the mean; for tiny moments this underflows to zero and the fitted shape is -1 (an improper gamma) with no error:

_tsdate.approximate_gamma_mom(1e-200, 1e-200)   # (-1.0, 1.0)

approximate_gamma_iqr does not validate max_shape, and divides by a zero quantile

tsd_approximate_gamma_iqr (used when rescaling posteriors):

  • accepts max_shape <= 1, returning an improper or NaN result:
    import scipy.stats
    q = scipy.stats.gamma(2.0).ppf([0.25, 0.75])
    _tsdate.approximate_gamma_iqr(0.25, 0.75, q[0], q[1], 0.0)    # (-1.0, nan)
    _tsdate.approximate_gamma_iqr(0.25, 0.75, q[0], q[1], -1.0)   # (-2.0, nan)
  • for a gamma with a tiny shape, the lower quantile underflows to 0.0 and the fit fails with "Floating-point division by zero" (TSD_ERR_ZERO_DIVISION), rather than as a failed gamma fit:
    q = scipy.stats.gamma(1e-3).ppf([0.25, 0.75])                 # [0.0, 6.5e-126]
    _tsdate.approximate_gamma_iqr(0.25, 0.75, q[0], q[1], 50.0)   # LibraryError

rootward_moments is irregular as the fixed child age goes to zero

tsd_rootward_moments is not continuous as the fixed age t -> 0. It is built on hyperu_laplace, whose Stirling-type approximation is inaccurate in this regime (see the special-functions issue):

for t in (1e-9, 1e-12, 0.0):
    print(_tsdate.rootward_moments(t, 10.0, 0.01, 1.0, 1e-4))
# (65.68560, 1089.1089, 107832.6)
# (65.67946, 1087.8661, 105517.0)
# (65.65183, 1089.1089, 107832.6)

Edge moments do not check the node ages

tsd_mutation_edge_moments (a mutation on an edge with both node ages fixed) does not check the ages: negative ages give a negative mean, and the ages can be in either order. Equal ages give zero variance and a NaN projection, whereas inverted ages give a valid result:

_tsdate.mutation_edge_moments(-3.0, -1.0)    # (-2.0, 0.333...)
_tsdate.mutation_edge_projection(1.0, 3.0)   # (1.0, 11.0, 6.0)   child older than parent
_tsdate.mutation_edge_projection(3.0, 1.0)   # (1.0, 11.0, 6.0)
_tsdate.mutation_edge_projection(1.0, 1.0)   # (nan, nan, nan)

(tsd_mutation_block_moments, the unphased equivalent, does reject non-positive ages.)

approximate_gamma_kl has error branches that random testing never reaches

The "Maximum iterations" (TSD_ERR_KL_MAX_ITERATIONS) and "Invalid shape" (TSD_ERR_KL_INVALID_SHAPE) branches of tsd_approximate_gamma_kl were not reached in 60,000 random draws. They may be dead code, or a sign that the Newton iteration needs a different guard.

Activity

  1. self-assigned this
    on Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions