Skip to content

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

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

Add geometric distribution (lpmf, cdf, lcdf, lccdf, rng)#3299
yasumorishima wants to merge 14 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

Comment on lines +36 to +89
template <bool propto, typename T_n, typename T_prob,
require_all_not_nonscalar_prim_or_rev_kernel_expression_t<
T_n, T_prob>* = nullptr>
inline return_type_t<T_prob> geometric_lpmf(const T_n& n, const T_prob& theta) {
using T_n_ref = ref_type_t<T_n>;
using T_prob_ref = ref_type_t<T_prob>;
static constexpr const char* function = "geometric_lpmf";
check_consistent_sizes(function, "Outcome variable", n,
"Success probability parameter", theta);
if (size_zero(n, theta)) {
return 0.0;
}

T_n_ref n_ref = n;
T_prob_ref theta_ref = theta;
check_nonnegative(function, "Outcome variable", n_ref);
check_bounded(function, "Success probability parameter", value_of(theta_ref),
0.0, 1.0);

// theta = 1 => deterministic: P(0) = 1, P(n>0) = 0
// Cannot delegate since beta = theta / (1 - theta) diverges
scalar_seq_view<T_n_ref> n_vec(n_ref);
scalar_seq_view<T_prob_ref> theta_vec(theta_ref);
const size_t max_sz = max_size(n_ref, theta_ref);
bool all_theta_one = true;
for (size_t i = 0; i < max_sz; i++) {
if (value_of(theta_vec[i]) == 1.0) {
if (n_vec[i] > 0) {
return negative_infinity();
}
} else {
all_theta_one = false;
}
}
if (all_theta_one) {
return 0.0;
}

// geometric(theta) = neg_binomial(1, theta / (1 - theta))
if constexpr (is_stan_scalar_v<T_prob>) {
const auto beta = theta_ref / (1.0 - theta_ref);
return neg_binomial_lpmf<propto>(n_ref, 1, beta);
} else if constexpr (is_std_vector_v<T_prob>) {
std::vector<value_type_t<T_prob>> beta;
beta.reserve(stan::math::size(theta));
for (size_t i = 0; i < stan::math::size(theta); i++) {
beta.push_back(theta_vec[i] / (1.0 - theta_vec[i]));
}
return neg_binomial_lpmf<propto>(n_ref, 1, beta);
} else {
const auto beta = elt_divide(theta_ref, subtract(1.0, theta_ref));
return neg_binomial_lpmf<propto>(n_ref, 1, beta);
}
}
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

So looking at this I would prefer we did one of two styles

  1. Completely delegate to neg_binomial_*. You do not need the std::vector here to accumulate the non 1 values.
template <typename T_n, typename T_prob>
inline return_type_t<T_prob> geometric_cdf(const T_n& n, const T_prob& theta) {
  using T_n_ref = ref_type_t<T_n>;
  using T_prob_ref = ref_type_t<T_prob>;
  static constexpr const char* function = "geometric_cdf";
  check_consistent_sizes(function, "Outcome variable", n,
                         "Success probability parameter", theta);
  decltype(auto) n_ref = as_array_or_scalar(to_ref(n));
  decltype(auto) theta_ref = as_array_or_scalar(to_ref(theta));
  check_bounded(function, "Success probability parameter", value_of(theta_ref),
                0.0, 1.0);
  if constexpr (is_stan_scalar_v<T_n>) {
    if (n_ref < 0) {
      return 0.0;
    }
  } else {
    const bool is_any_nonpositive = (n_ref.array() < 0).any();
    if (is_any_nonpositive) {
      return 0.0;
    }
  }
  if constexpr (is_stan_scalar_v<T_prob>) {
    if (theta_ref == 1.0) {
      return 1.0;
    } else {
      return neg_binomial_cdf(n, 1, theta_ref / (1.0 - theta_ref));
    }
  } else {
    return theta_ref.binaryExpr(n_ref, [](const auto& theta_, const auto& n_) { 
      if (theta_ == 1.0) {
        return return_type_t<T_prob>{1.0};
      } else {
        return neg_binomial_cdf(n_, 1, elt_divide(theta_, subtract(1.0, theta_)));
      }
    }).prod();
  }
}
  1. A full autodiff impl with the adjoint calculations
template <typename T_n, typename T_prob>
inline return_type_t<T_prob> geometric_cdf(const T_n& n,
                                           const T_prob& theta) {
  using T_partials_return = partials_return_t<T_prob>;
  using T_n_ref = ref_type_t<T_n>;
  using T_prob_ref = ref_type_t<T_prob>;
  static constexpr const char* function = "geometric_cdf";
  check_consistent_sizes(function, "Outcome variable", n,
                         "Success probability parameter", theta);
  if (size_zero(n, theta)) {
    return 1.0;
  }
  auto n_arr = as_array_or_scalar(to_ref(n));
  auto theta_arr = as_array_or_scalar(to_ref(theta));
  // Need to check theta > 0 && theta <= 1.0. Bounded checks >= and <= 
  check_bounded(function, "Success probability parameter", value_of(theta_arr),
                std::numeric_limits<double>::min(), 1.0);

  auto ops_partials = make_partials_propagator(theta_arr);
  if constexpr (is_stan_scalar_v<T_n>) {
    if (n_arr < 0) {
      return ops_partials.build(0.0);
    }
  } else {
    if (any(n_arr < 0)) {
      return ops_partials.build(0.0);
    }
  }
  auto log1m_theta = log1m(theta_arr);
  auto P_i = -expm1((n_arr + 1.0) * log1m_theta);
  auto P = prod(P_i);
  if constexpr (is_autodiff_v<T_prob>) {
    // d/dtheta [1 - (1 - theta)^(n + 1)]
    //   = (n + 1) * (1 - theta)^n
    //
    // The select handles theta == 1, n == 0, where the derivative is 1
    // and the log form would otherwise run into 0 * -inf.
    auto dP_dtheta = select(
        n_arr == 0, 1.0, (n_arr + 1.0) * exp(n_arr * log1m_theta));
    auto theta_partials = P * elt_divide(dP_dtheta, P_i);
    if constexpr (is_stan_scalar_v<T_prob>) {
      partials<0>(ops_partials) = sum(theta_partials);
    } else {
      partials<0>(ops_partials) = theta_partials;
    }
  }
  return ops_partials.build(P);
}

yasumorishima and others added 3 commits April 25, 2026 01:28
Replace neg_binomial_* delegation with a full autodiff implementation
per PR stan-dev#3299 review. All four functions compute analytic partials on
Eigen arrays directly, with explicit boundary handling for theta=0,
theta=1, n=0, n=INT_MAX. Tests: 180/180 autodiff + 8/8 prim pass.
@yasumorishima
Copy link
Copy Markdown
Author

Thanks for the detailed review @SteveBronder! Went with option 2 — all four functions now use make_partials_propagator with log1m / expm1 / log1m_exp and analytic partials, no std::vector accumulation. CDF follows your sketch exactly; lpmf/lcdf/lccdf use the same pattern.

Boundary handling: short-circuit theta = 1 (lpmf for n>0, lccdf for n>=0), theta = 0 (cdf/lcdf), and n = INT_MAX (lccdf, matching neg_binomial_lccdf for the upper-bound test fixture).

Tests: 180/180 autodiff distribution tests (var/vv/ffv) + 8/8 prim unit tests pass locally. Happy to iterate.

yasumorishima and others added 2 commits April 25, 2026 03:42
Address CodeRabbit review on PR stan-dev#3299: with check_bounded(theta, 0.0,
1.0) (inclusive), passing theta = 0 produced -inf logp but the autodiff
path still evaluated inv(theta_arr), poisoning the partial with +inf.

Replace the inclusive bound with check_positive_finite + check_less_or_
equal in lpmf/cdf/lcdf/lccdf to match the documented domain (0, 1] and
the existing geometric_rng pattern. With the tightened bound the
theta == 0 short-circuits in cdf/lcdf become unreachable; remove them.

Add an EXPECT_THROW unit test covering theta = 0 across all four
distribution functions to lock in the new behavior.
@yasumorishima
Copy link
Copy Markdown
Author

yasumorishima commented Apr 25, 2026

Addressed @coderabbitai's review on geometric_lpmf.hpp (theta=0 producing +inf partials): with check_bounded(theta, 0.0, 1.0) (inclusive), theta = 0 was accepted but inv(theta_arr) then poisoned the autodiff partial with +inf.

In commit 31dcbd6:

  • All four distribution functions (lpmf/cdf/lcdf/lccdf) now use check_positive_finite + check_less_or_equal(..., 1.0), matching the documented (0, 1] domain and the existing geometric_rng pattern.
  • Removed the now-unreachable if (any(theta_arr == 0.0)) short-circuits in cdf/lcdf and the dead // For theta = 0: comment in lccdf.
  • Added a theta_zero_throws unit test covering all four functions.

Local results: prim unit test 9/9 PASS (incl. the new throw test), all 12 generated autodiff distribution test binaries PASS.

yasumorishima and others added 2 commits April 25, 2026 04:50
geometric_lccdf:
- Drop the any(n_arr < 0) early return that silently dropped
  contributions from positive n_i in mixed-sign vectors.
  P(N > n_i) = 1 for n_i < 0 is the multiplicative identity (log 0),
  not an absorbing element, so the term has to remain in the sum.
  Per-element select(n < 0, 0, ...) keeps both value and partials
  paths correct.
- Replace the any(theta == 1.0) blanket guard with a scalar_seq_view
  per-element loop, so theta=1 only forces -inf when paired with
  n_i >= 0 at the same index. Previously theta=[0.5, 1.0], n=[2, -1]
  returned -inf instead of 3*log(0.5).

geometric_lpmf:
- Add the is_stan_scalar_v<T_prob> guard around partials<0> assignment
  so a scalar theta paired with a vector n collapses to a scalar
  partial via sum(...), matching cdf/lcdf/lccdf.

Tests: lccdf_vectorized_mixed_sign and
lccdf_vectorized_theta_one_alignment lock in both contract fixes.
@yasumorishima
Copy link
Copy Markdown
Author

Round 2 of CodeRabbit findings + an alignment bug Opus surfaced during self-review (commit b37a958359):

geometric_lccdf.hpp

  • Removed the any(n_arr < 0) early return that dropped contributions from positive n_i in mixed-sign vectors. P(N > n_i) = 1 for n_i < 0 is the multiplicative identity (log 0), not an absorber, so the term has to stay in the sum. Switched to a per-element select(n < 0, 0, (n+1)*log1m(theta)) for both value and partials.
  • Replaced the any(theta_arr == 1.0) blanket -inf short-circuit with a scalar_seq_view per-element loop, so theta = 1 only forces -inf when paired with n_i >= 0 at the same index. Mirrors the lpmf pattern. Previously theta=[0.5, 1.0], n=[2, -1] returned -inf instead of 3*log(0.5).

geometric_lpmf.hpp

  • Added the is_stan_scalar_v<T_prob> guard around partials<0> so scalar theta paired with a vector n collapses to a scalar partial via sum(...), matching the pattern already used in cdf/lcdf/lccdf.

Tests (geometric_test.cpp)

  • lccdf_vectorized_mixed_sign: locks in the n = [-1, 2], theta = 0.5 -> 3*log(0.5) contract.
  • lccdf_vectorized_theta_one_alignment: locks in the per-element theta = 1 guard with n = [2, -1], theta = [0.5, 1.0] -> 3*log(0.5).

prim 11/11 PASS, autodiff distribution lccdf v/vv/ffv 90/180/90 PASS.

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

4 participants