Skip to content

Add geometric distribution (lpmf, cdf, lcdf, lccdf, rng)#3299

Open
yasumorishima wants to merge 7 commits intostan-dev:developfrom
yasumorishima:feature/issue-3098-geometric-distribution
Open

Add geometric distribution (lpmf, cdf, lcdf, lccdf, rng)#3299
yasumorishima wants to merge 7 commits intostan-dev:developfrom
yasumorishima:feature/issue-3098-geometric-distribution

Conversation

@yasumorishima
Copy link
Copy Markdown

Summary

Implements the geometric distribution as requested in #3098.

  • Parameterization: Number of failures before first success (support {0, 1, 2, ...})
  • PMF: P(n | θ) = θ(1 − θ)^n
  • Consistent with neg_binomial: geometric_lpmf(n, θ) == neg_binomial_lpmf(n, 1, θ/(1−θ)) — verified numerically
  • Full autodiff support for all functions
  • Boundary handling for θ = 0 and θ = 1

Files added/modified

  • stan/math/prim/prob/geometric_lpmf.hpp — log PMF with autodiff gradients
  • stan/math/prim/prob/geometric_cdf.hpp — CDF with autodiff gradients
  • stan/math/prim/prob/geometric_lcdf.hpp — log CDF with autodiff gradients
  • stan/math/prim/prob/geometric_lccdf.hpp — log CCDF with autodiff gradients
  • stan/math/prim/prob/geometric_rng.hpp — RNG via inverse CDF method
  • stan/math/prim/prob.hpp — include additions (alphabetical order)
  • test/unit/math/prim/prob/geometric_test.cpp — unit tests (8 tests)
  • test/prob/geometric/geometric_cdf_test.hpp — CDF gradient test fixture

Tests

  • 8 unit tests passing:
    • errorCheck — validates parameter constraints via test rig
    • distributionCheck — RNG samples match PMF (chi-squared test)
    • error_check — domain errors for invalid θ
    • lpmf_values — hand-calculated PMF values including θ=1 edge case
    • cdf_values — hand-calculated CDF values
    • cdf_below_support — returns 0 / -inf for n < 0
    • lccdf_values — hand-calculated CCDF values
    • rng_theta_one — θ=1 always returns 0

Notes

  • The geometric distribution is a special case of the negative binomial with r = 1, as noted in the issue
  • Follows the same implementation pattern as the recently merged Yule-Simon distribution (add yule_simon_cdf #3283, add yule_simon_rng #3285)
  • Gradient computations are guarded against division by zero at θ = 0 and θ = 1 boundaries

Closes #3098

🤖 Generated with Claude Code

yasumorishima and others added 2 commits March 24, 2026 04:04
Implements the geometric distribution as requested in stan-dev#3098.
The geometric distribution models the number of failures before the
first success, with PMF: P(n|theta) = theta * (1-theta)^n
where n in {0, 1, 2, ...} and theta in (0, 1].

This uses the number-of-failures parameterization, consistent with
the geometric distribution being a special case of the negative
binomial distribution with r=1 (neg_binomial(1, theta/(1-theta))).

Verified: geometric_lpmf(n, theta) == neg_binomial_lpmf(n, 1, theta/(1-theta))
for all tested values.

Includes:
- geometric_lpmf: log probability mass function with autodiff
- geometric_cdf: cumulative distribution function with autodiff
- geometric_lcdf: log CDF with autodiff
- geometric_lccdf: log complementary CDF with autodiff
- geometric_rng: random number generation via inverse CDF method
- Unit tests for all functions including distribution checks
- CDF test fixture for gradient verification

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Guard gradient computations against theta=0 division by zero
  in geometric_lpmf, geometric_cdf, and geometric_lcdf
- Fix include ordering in prob.hpp (gaussian before geometric)
- Fix signed/unsigned comparison in geometric_rng loop index

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@SteveBronder
Copy link
Copy Markdown
Collaborator

Hi @yasumorishima ! Is there a reason we can't just have direct calls to the negative binomial function for all of these? So these would just be calls to neg_binomial that fix alpha to 1

@stan-buildbot
Copy link
Copy Markdown
Contributor


Name Old Result New Result Ratio Performance change( 1 - new / old )
gp_regr/gp_regr.stan 0.09 0.09 0.99 -0.59% slower
gp_regr/gen_gp_data.stan 0.02 0.02 1.02 2.06% faster
arK/arK.stan 1.76 1.74 1.01 0.92% faster
eight_schools/eight_schools.stan 0.05 0.05 1.02 1.7% faster
low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 8.54 8.57 1.0 -0.35% slower
pkpd/one_comp_mm_elim_abs.stan 19.08 19.08 1.0 -0.01% slower
pkpd/sim_one_comp_mm_elim_abs.stan 0.25 0.24 1.02 2.4% faster
sir/sir.stan 70.74 67.48 1.05 4.6% faster
gp_pois_regr/gp_pois_regr.stan 2.82 2.71 1.04 3.94% faster
low_dim_gauss_mix/low_dim_gauss_mix.stan 2.7 2.63 1.03 2.59% faster
irt_2pl/irt_2pl.stan 4.05 3.98 1.02 1.76% faster
arma/arma.stan 0.28 0.27 1.03 2.7% faster
garch/garch.stan 0.41 0.41 1.01 0.54% faster
low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 1.01 0.61% faster
performance.compilation 227.86 218.43 1.04 4.14% faster
Mean result: 1.0186048650959072

Jenkins Console Log
Blue Ocean
Commit hash: e0a54f2c08661b080c37acc67934833d4d8465c6


Machine information No LSB modules are available. 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: 46 bits physical, 48 bits virtual
CPU(s): 80
On-line CPU(s) list: 0-79
Thread(s) per core: 2
Core(s) per socket: 20
Socket(s): 2
NUMA node(s): 2
Vendor ID: GenuineIntel
CPU family: 6
Model: 85
Model name: Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz
Stepping: 4
CPU MHz: 2400.000
CPU max MHz: 3700.0000
CPU min MHz: 1000.0000
BogoMIPS: 4800.00
Virtualization: VT-x
L1d cache: 1.3 MiB
L1i cache: 1.3 MiB
L2 cache: 40 MiB
L3 cache: 55 MiB
NUMA node0 CPU(s): 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78
NUMA node1 CPU(s): 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit: KVM: Mitigation: VMX disabled
Vulnerability L1tf: Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown: Mitigation; PTI
Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed: Mitigation; IBRS
Vulnerability Spec rstack overflow: Not affected
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; IBRS; IBPB conditional; STIBP conditional; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Mitigation; Clear CPU buffers; SMT vulnerable
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 dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single pti intel_ppin ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke md_clear flush_l1d arch_capabilities

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

Refactor lpmf, cdf, lcdf, lccdf, and rng to delegate to the
corresponding neg_binomial functions with alpha=1 and
beta=theta/(1-theta), as suggested in review.

Handle theta=1 (where beta diverges) with early returns.
Add autodiff test HPPs for lpmf, lcdf, and lccdf.
@yasumorishima yasumorishima force-pushed the feature/issue-3098-geometric-distribution branch from f822a16 to 84319ae Compare March 25, 2026 16:32
@yasumorishima
Copy link
Copy Markdown
Author

Hi @SteveBronder, thanks for the review!

Good point — I've refactored all five functions (lpmf, cdf, lcdf, lccdf, rng)
to delegate to the corresponding neg_binomial functions with α = 1 and
β = θ / (1 − θ).

The only special case is θ = 1, where β diverges. Each function handles this
with an early return (e.g., lpmf returns 0 for n = 0 and −∞ for n > 0,
cdf returns 1, etc.).

I also added autodiff test HPPs for lpmf, lcdf, and lccdf — all 1,412 tests
pass (unit + v/ffv/vv for all four functions).

Let me know if you'd like any further changes!

@stan-buildbot
Copy link
Copy Markdown
Contributor


Name Old Result New Result Ratio Performance change( 1 - new / old )
gp_regr/gp_regr.stan 0.09 0.09 1.02 1.64% faster
gp_regr/gen_gp_data.stan 0.02 0.02 1.04 4.19% faster
arK/arK.stan 1.76 1.75 1.0 0.44% faster
eight_schools/eight_schools.stan 0.05 0.05 1.03 2.83% faster
low_dim_gauss_mix_collapse/low_dim_gauss_mix_collapse.stan 8.64 8.41 1.03 2.62% faster
pkpd/one_comp_mm_elim_abs.stan 19.15 18.82 1.02 1.71% faster
pkpd/sim_one_comp_mm_elim_abs.stan 0.25 0.25 1.0 0.24% faster
sir/sir.stan 67.32 68.2 0.99 -1.3% slower
gp_pois_regr/gp_pois_regr.stan 2.78 2.72 1.02 1.99% faster
low_dim_gauss_mix/low_dim_gauss_mix.stan 2.58 2.56 1.01 0.81% faster
irt_2pl/irt_2pl.stan 4.02 3.91 1.03 2.71% faster
arma/arma.stan 0.28 0.27 1.02 2.14% faster
garch/garch.stan 0.41 0.4 1.01 1.23% faster
low_dim_corr_gauss/low_dim_corr_gauss.stan 0.01 0.01 1.04 3.94% faster
performance.compilation 223.37 222.07 1.01 0.58% faster
Mean result: 1.0176813803222107

Jenkins Console Log
Blue Ocean
Commit hash: 240e2dc95a112f175bb961a03b53357d10955996


Machine information No LSB modules are available. 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: 46 bits physical, 48 bits virtual
CPU(s): 80
On-line CPU(s) list: 0-79
Thread(s) per core: 2
Core(s) per socket: 20
Socket(s): 2
NUMA node(s): 2
Vendor ID: GenuineIntel
CPU family: 6
Model: 85
Model name: Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz
Stepping: 4
CPU MHz: 2776.047
CPU max MHz: 3700.0000
CPU min MHz: 1000.0000
BogoMIPS: 4800.00
Virtualization: VT-x
L1d cache: 1.3 MiB
L1i cache: 1.3 MiB
L2 cache: 40 MiB
L3 cache: 55 MiB
NUMA node0 CPU(s): 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78
NUMA node1 CPU(s): 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit: KVM: Mitigation: VMX disabled
Vulnerability L1tf: Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown: Mitigation; PTI
Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed: Mitigation; IBRS
Vulnerability Spec rstack overflow: Not affected
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; IBRS; IBPB conditional; STIBP conditional; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Mitigation; Clear CPU buffers; SMT vulnerable
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 dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single pti intel_ppin ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke md_clear flush_l1d arch_capabilities

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 Geometric distribution

3 participants