TruncatedNormal.logcdf returns nan at the lower bound instead of -inf
Describe the bug
TruncatedNormal.logcdf returns nan at the lower bound instead of -inf.
The support of a truncated normal is closed, [a, b], so cdf(a) is 0 and logcdf(a) is -inf. The guard used a strict <, so at value == lower the call fell through to log_diff_normal_cdf with x == y. That helper's own docstring states the precondition, in pymc/distributions/dist_math.py:
y: float
must be strictly less than x.and it returns nan for any x <= y, including the equal case. The nan is what the caller gets.
scipy.stats.truncnorm.logcdf gives -inf for the same input, and the upper-bound guard two lines below already uses <=, so the two sides of the same function disagreed about whether the bound is included.
Steps to reproduce
import numpy as np, pymc as pm, scipy.stats as st
from pymc.logprob.basic import logcdf
rv = pm.TruncatedNormal.dist(mu=0.0, sigma=1.0, lower=-1.0, upper=1.0)
values = np.array([-1.0, 0.0, 1.0])
print(logcdf(rv, values).eval())
print(st.truncnorm.logcdf(values, -1.0, 1.0))Actual:
[ nan -6.93147186e-01 3.46827433e-09]
[ -inf -0.69314718 0. ]Expected: -inf at the lower bound.
Censored reads logcdf for its censored regions, so an observation sitting exactly on the bound gives the whole model a nan logp:
import numpy as np, pymc as pm
with pm.Model() as model:
pm.Censored(
"v",
pm.TruncatedNormal.dist(mu=0.0, sigma=1.0, lower=-1.0, upper=1.0),
lower=-1.0, upper=1.0,
observed=np.array([-1.0, 0.0, 0.5]),
)
print(model.compile_logp()(model.initial_point()))Actual: nan. Expected: -inf, since the observation is a measure-zero event. logp itself is finite and correct at the bound, so the defect is confined to logcdf.
Environment
- PyMC
mainat3f3b1082e5681503df3a79ae5a790475eed5c626(version 6.3.2) - Python 3.13, macOS
Fix
One character, at pymc/distributions/continuous.py:757:
- logcdf = pt.switch(value < lower, -np.inf, logcdf)
+ logcdf = pt.switch(value <= lower, -np.inf, logcdf)Note that logp's own guard two functions up must stay strict, because logp is finite at the bound.
Related, deliberately not in this fix
pymc/distributions/truncated.py:484 has the same guard and the same nan for the general Truncated wrapper. It cannot be changed the same way: the base distribution there can be discrete, and a discrete CDF at its lower bound is finite rather than zero, so <= would return -inf where it should not. test_truncation_discrete_logcdf pins that behaviour. The discrete-side fix, which moves DiscreteUniform.logcdf the other way, is open as #8452.
Source: pymc-devs/pymc