Skip to content

Add inverse Gaussian distribution (closes #2788) - #3382

Open
GidonFrischkorn wants to merge 14 commits into
stan-dev:developfrom
GidonFrischkorn:feature/issue-2788-inv-gaussian
Open

Add inverse Gaussian distribution (closes #2788)#3382
GidonFrischkorn wants to merge 14 commits into
stan-dev:developfrom
GidonFrischkorn:feature/issue-2788-inv-gaussian

Conversation

@GidonFrischkorn

Copy link
Copy Markdown

Summary

Closes #2788.

This adds the inverse Gaussian (Wald) distribution in the mean/shape parameterization inv_gaussian(y | mu, lambda): inv_gaussian_lpdf, inv_gaussian_cdf, inv_gaussian_lcdf, inv_gaussian_lccdf, and inv_gaussian_rng. All are vectorized over the three arguments with analytic partials via make_partials_propagator, following lognormal_lpdf and normal_lcdf.

The issue suggested wrapping the Boost density. I implemented the distribution natively instead, because the textbook CDF form Phi(z1) + exp(2*lambda/mu) * Phi(-z2) overflows at shape-to-mean ratios that are routine in response-time modeling. The CDF family is computed entirely in log space, with the scaled upper term collapsed analytically so that no opposing large quantities remain, and an internal elementwise log_Phi carries the lower tail past the point where erfc underflows. (std_normal_lcdf cannot be reused because it reduces over its container argument; the helper placement follows von_mises_cdf.hpp and gamma_lccdf.hpp.) The rng uses the Michael, Schucany & Haas (1976) transformation with the smaller root in reciprocal form, since the usual subtractive form loses precision and returns invalid variates at large mu*w/lambda. Both y = 0 and y = inf are accepted as the closure of the support and handled elementwise, with partials defined to be zero there and wherever the log probability has saturated.

Test reference values are computed with mpmath at 60 digits. The implementation is additionally cross-validated against
statmod, with both compared against a high-precision python implementation rather than against each other.

Two questions where I would value feedback:

  • Underflow convention. At survivor underflow the lccdf returns -inf with zero partials; normal_lccdf instead returns a signed infinity for the gradient there. I am happy to switch; the shape partial would then need an explicitly assigned sign.
  • Placement of log_Phi. The elementwise log-CDF helper could be promoted to stan/math/prim/fun/ as a standalone function. I kept it internal to keep this PR self-contained, but I am happy to split it out here or in a follow-up.

This is my first contribution to Stan Math; I work on response-time models in the R package bmm, where the inverse Gaussian currently lives as a user-defined function.

Tests

  • test/prob/inv_gaussian/: the generated distribution fixtures for lpdf / cdf / cdf_log / ccdf_log, covering ordinary-point values and domain errors across every AD and container variant. The fixture reference implementations are written in linear space from erfc, so they are an independent code path from the log-space implementation under test.
  • test/unit/math/mix/prob/: expect_ad for all four functions over scalars and containers, plus the vectorized cdf, whose partials couple through the whole-container product; invalid arguments; tail points that cross the internal asymptotic branch and the region where exp(2*lambda/mu) would overflow.
  • test/unit/math/rev/prob/: hand-derived partials pinned against mpmath; a check that tape growth does not depend on N; vectorized values and adjoints equal to the scalar sums; zero partials at the support boundaries and at saturation, asserted directly because finite differences step off the support there.
  • test/unit/math/prim/prob/: RNG rig with quantile agreement against boost::math::inverse_gaussian, RNG stability at extreme parameters, value pins in the overflow region and the deep lower tail, F + S = 1 consistency, and direct tests of the internal log_Phi.

Side Effects

I am not aware of any; only new functions are added. stan/math/prim/prob.hpp gains the five includes.

Release notes

Added the inverse Gaussian (Wald) distribution: inv_gaussian_lpdf, inv_gaussian_cdf, inv_gaussian_lcdf, inv_gaussian_lccdf, inv_gaussian_rng.

AI use disclosure

I used AI assistance (Claude Code) for this contribution. I am at the start of learning C++ and used it to express established mathematics (the density and CDF identities and the Michael, Schucany & Haas (1976) sampler) in the Stan Math template and autodiff idiom. I verified the mathematics and all test reference values myself, have reviewed and understood the code, and can explain and defend the changes during review.

Checklist

  • Copyright holder: Gidon T. Frischkorn

    The copyright holder is typically you or your assignee, such as a university or company. By submitting this pull request, the copyright holder is agreeing to the license the submitted work under the following licenses:
    - Code: BSD 3-clause (https://opensource.org/licenses/BSD-3-Clause)
    - Documentation: CC-BY 4.0 (https://creativecommons.org/licenses/by/4.0/)

  • the basic tests are passing

    • unit tests pass (to run, use: ./runTests.py test/unit)
    • header checks pass, (make test-headers)
    • dependencies checks pass, (make test-math-dependencies)
    • docs build, (make doxygen)
    • code passes the built in C++ standards checks (make cpplint)
  • the code is written in idiomatic C++ and changes are documented in the doxygen

  • the new changes are tested

- mean/shape parameterization, vectorized over all three arguments
- rng uses the Michael, Schucany & Haas (1976) transform
- compute the CDF family in log space; exp(2*lambda/mu) overflows a double
  above 2*lambda/mu = 710
- write the smaller root as a reciprocal; (1 + u/2)^2 - (u + u^2/4) == 1
- pin stability and the first two moments over mu/lambda up to 1e20
- a boundary element no longer discards the rest of the container
- value pins and error throws already covered by the test/prob fixtures
- Eigen-vectorized expect_ad covered by the generated vv/ffv variants
@GidonFrischkorn GidonFrischkorn changed the title Feature/issue 2788 inv gaussian Add inverse Gaussian distribution (closes #2788) Sep 1, 2026

@WardBrian WardBrian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your submission @GidonFrischkorn!

We have a release feature freeze starting at the end of this week, so don't be too discouraged if we don't look at this for a week or two.

The tests you currently have are failing on jenkins, seemingly due to minor numeric issues. These are probably to be expected if you were setting the tolerances based off e.g. a Mac, and we are testing on Linux, and assuming the values look fine to you it's acceptable to simply loosen the tolerances from 1e-13 to 1e-11 or similar

Comment on lines +191 to +192
EXPECT_NEAR(ref_lcdf, a, 1e-13);
EXPECT_NEAR(ref_lccdf, b, 1e-13);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few of these tolerances seem a bit too tight on our test platform (linux/clang 7). Errors look like:

test/unit/math/prim/prob/inv_gaussian_test.cpp:191: Failure

The difference between ref_lcdf and a is 8.7538865045644343e-12, which exceeds 1e-13, where
ref_lcdf evaluates to -0.69314591898922784,
a evaluates to -0.69314591898047395

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @WardBrian for this info. The tests were indeed run on a Mac.

I checked through the tests and adapted the test tolerances to be scale with lambda over mu. Details are in the comments for the tests

The tests at y == mu probe the rounding of y * (1 / mu) - 1, which
z1 and z2 amplify by sqrt(lambda / y) -- up to ~3e9 for
lambda / mu = 1e19. That rounding is zero on macOS/arm64 but ~1 ulp
with clang 7 on Linux x86, so the tolerances now carry the
sqrt(lambda / mu) * eps scale that bounds the error.
@GidonFrischkorn

Copy link
Copy Markdown
Author

Thanks for your submission @GidonFrischkorn!

We have a release feature freeze starting at the end of this week, so don't be too discouraged if we don't look at this for a week or two.

The tests you currently have are failing on jenkins, seemingly due to minor numeric issues. These are probably to be expected if you were setting the tolerances based off e.g. a Mac, and we are testing on Linux, and assuming the values look fine to you it's acceptable to simply loosen the tolerances from 1e-13 to 1e-11 or similar

No worries about the feature freeze. The feature is not urgent and especially since this is my first PR, I would rather not rush it and make sure everything is in place and well reviewed prior to merging.

@stan-buildbot

Copy link
Copy Markdown
Contributor
Name Old Result New Result Ratio Performance change( 1 - new / old )
stat_comp_benchmarks/benchmarks/gp_regr/gen_gp_data.stan 0.04 0.04 1.01 1.42% faster
stat_comp_benchmarks/benchmarks/gp_regr/gp_regr.stan 0.16 0.16 0.99 -0.93% slower
stat_comp_benchmarks/benchmarks/garch/garch.stan 0.86 0.86 1.0 -0.15% slower
stat_comp_benchmarks/benchmarks/low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.02 0.96 -4.36% slower
stat_comp_benchmarks/benchmarks/eight_schools/eight_schools.stan 0.11 0.11 0.99 -0.88% slower
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix/low_dim_gauss_mix.stan 8.39 8.38 1.0 0.05% faster
stat_comp_benchmarks/benchmarks/gp_pois_regr/gp_pois_regr.stan 3.7 3.75 0.99 -1.22% slower
stat_comp_benchmarks/benchmarks/pkpd/one_comp_mm_elim_abs.stan 32.9 32.84 1.0 0.16% faster
stat_comp_benchmarks/benchmarks/pkpd/sim_one_comp_mm_elim_abs.stan 0.38 0.38 1.0 -0.22% slower
stat_comp_benchmarks/benchmarks/irt_2pl/irt_2pl.stan 6.61 6.6 1.0 0.2% faster
stat_comp_benchmarks/benchmarks/sir/sir.stan 136.07 140.22 0.97 -3.05% slower
stat_comp_benchmarks/benchmarks/arK/arK.stan 3.23 3.21 1.01 0.66% faster
stat_comp_benchmarks/benchmarks/arma/arma.stan 0.6 0.59 1.0 0.47% faster
stat_comp_benchmarks/benchmarks/low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 24.99 25.02 1.0 -0.1% slower
performance.compilation 394.7 401.7 0.98 -1.77% slower
Mean result: 0.9937558625978845

Jenkins Console Log
Jenkins Build Stages
Commit hash: ab7ce750b67aaf45c7f7782a18c2eda05121bc19

Machine information
Distributor ID:	Ubuntu
Description:	Ubuntu 20.04.3 LTS
Release:	20.04
Codename:	focal

CPU:

Architecture:                            x86_64
CPU op-mode(s):                          32-bit, 64-bit
Byte Order:                              Little Endian
Address sizes:                           52 bits physical, 57 bits virtual
CPU(s):                                  192
On-line CPU(s) list:                     0-191
Thread(s) per core:                      2
Core(s) per socket:                      48
Socket(s):                               2
NUMA node(s):                            2
Vendor ID:                               AuthenticAMD
CPU family:                              25
Model:                                   17
Model name:                              AMD EPYC 9474F 48-Core Processor
Stepping:                                1
Frequency boost:                         enabled
CPU MHz:                                 1497.452
CPU max MHz:                             4114.4229
CPU min MHz:                             1500.0000
BogoMIPS:                                7189.04
Virtualization:                          AMD-V
L1d cache:                               3 MiB
L1i cache:                               3 MiB
L2 cache:                                96 MiB
L3 cache:                                512 MiB
NUMA node0 CPU(s):                       0-47,96-143
NUMA node1 CPU(s):                       48-95,144-191
Vulnerability Gather data sampling:      Not affected
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit:             Not affected
Vulnerability L1tf:                      Not affected
Vulnerability Mds:                       Not affected
Vulnerability Meltdown:                  Not affected
Vulnerability Mmio stale data:           Not affected
Vulnerability Reg file data sampling:    Not affected
Vulnerability Retbleed:                  Not affected
Vulnerability Spec rstack overflow:      Mitigation; Safe RET
Vulnerability Spec store bypass:         Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:                Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:                Mitigation; Enhanced / Automatic IBRS; IBPB conditional; STIBP always-on; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                     Not affected
Vulnerability Tsa:                       Mitigation; Clear CPU buffers
Vulnerability Tsx async abort:           Not affected
Vulnerability Vmscape:                   Mitigation; IBPB before exit to userspace
Flags:                                   fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good amd_lbr_v2 nopl xtopology nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local user_shstk avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif x2avic v_spec_ctrl vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d debug_swap

G++:

g++ (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Clang:

clang version 10.0.0-4ubuntu1 
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add inverse Gaussian distribution support

3 participants