Skip to content

pnbd dyncov LL: fix jumps of the likelihood close to z = 1 (GSL 2F1 returns GSL_EUNIMPL) - #302

Open
bachmannpatrick wants to merge 1 commit into
developmentfrom
bugfix-dyncov-hyp2f1-close-to-one
Open

bachmannpatrick wants to merge 1 commit into
developmentfrom
bugfix-dyncov-hyp2f1-close-to-one

Conversation

@bachmannpatrick

Copy link
Copy Markdown
Owner

The issue

The log-likelihood of the Pareto/NBD with dynamic covariates is not continuous. For single customers it jumps by 1 to 13 units, and optimizers with numerical gradients stop at a jump with "false convergence".

pnbd_dyncov_LL_i_hyp_beta_g_alpha() and pnbd_dyncov_LL_i_hyp_alpha_ge_beta() compute terms of the form 2F1(r+s+x, b; r+s+x+1; z) / beta^(r+s+x) with gsl_sf_hyperg_2F1_e().

  • For z >= 0.995 and r+s+x >= 10, GSL returns status 24 (GSL_EUNIMPL) and the value 0. Just below either limit it is accurate to 13 digits.
  • The code only handles GSL_EMAXITER and GSL_EDOM. For status 24 it takes the 0, so one term of the customer's likelihood disappears.
  • For the two handled codes the fallback is the leading term for z -> 1, whose relative error is up to 46 % for z between 0.99 and 0.9999.

To reproduce: gsl_sf_hyperg_2F1_e(17.61, 9.62, 18.61, 0.995, &res) returns status 24 and res.val = 0 (GSL 2.7.1). The true value is 1.3886e+20.

The region is reached when beta is large relative to alpha (z = 0.995 means beta is about 200 times alpha) and the customer has many transactions or s is large. In simulated data (20,000 customers, r 0.62, alpha 5, s 2.7, beta 818), 133 customers have a jump when s is varied from 1.5 to 8 at a fixed mean attrition rate, exactly where (beta - alpha) / (beta + t_x) = 0.995 or where r+s+x = 10. In an application with real data about 0.9 % of the customers were affected and no fit converged.

Two related defects:

  • For customers with very many transactions, pow(beta, r+s+x) overflows and the quotient becomes 0 although the true value is representable (for example x = 150 at beta = 3,000).
  • For integer r+x (or integer s in the other case), GSL reports success from z = 0.995 on but is inaccurate, in some cases with the wrong sign.

The change

For z >= 0.995, or whenever GSL does not report success, the terms are computed from the linear transformation z -> 1-z (Abramowitz and Stegun 15.3.6). Because c = a+1, one of the two hypergeometric functions on the right-hand side is elementary. With w = 1-z:

2F1(a, b; a+1; z) =   Gamma(a+1) * Gamma(1-b) / Gamma(a+1-b) * z^(-a)
                    + a/(b-1) * w^(1-b) * sum_n (a+1-b)_n / (2-b)_n * w^n

The series converges like w^n. Both parts are evaluated on the log scale after division by the power, so nothing overflows. Both have a pole at integer b that cancels in the sum; within 1e-4 of an integer the value is interpolated from four neighbouring values of b.

Order of evaluation in the new helper pnbd_dyncov_LL_i_hyp_term():

  1. z < 0.995: GSL as before. Results are bit-identical wherever GSL reports success. If the power overflows, the division is done on the log scale.
  2. Otherwise: the transformation above.
  3. If neither is available: the leading term, as before.

Validation

The two functions were compiled on their own next to the original code (g++, C++11 and C++17, GSL 2.7.1) and compared with a reference computed with 80 digits (mpmath) on about 4,400 random parameter sets (r from 0.2 to 3, s from 0.2 to 12, x from 0 to 150, including integer r and s).

Region of z Cases Old: relative error above 1e-6 New: relative error above 1e-6 New: largest error
below 0.995 2,399 134 (overflow of the power) 0 1.5e-11
from 0.995 1,994 1,331 0 6.9e-09
  • At the three largest jumps of the simulated data the old function changes its sign; the new one is smooth.
  • Above the threshold the new evaluation is about twice as fast (0.32 s against 0.70 s per million calls). Below the threshold nothing changes.
  • New test context "PNBD dyncov hyp2F1 terms close to z = 1" in src/test-cpp.cpp with eight reference values. The original code fails six of them.

Status

Draft. The package has not been built with this change and its test suite has not been run locally; the checks of this pull request are the first build. Only GSL 2.7.1 was tested. NEWS.md is not updated.

Open questions

  • Threshold. 0.995 is GSL's own switch and keeps all results below it unchanged. The new evaluation is much faster than GSL's series just below the threshold. A lower threshold, for example 0.9, would speed up the likelihood for large beta/alpha, at the price of changes in the 13th digit for more customers.
  • Model without covariates. pnbd.cpp calls the same GSL function through clv::vec_hyp2F1() without looking at the status; the affected customers come out as NaN. The helper could be reused there. Not part of this pull request.
  • Near-integer r+x or s. The interpolation has a relative error of up to about 1e-8 within 1e-4 of an integer.
  • Other models. Not checked whether other models call the same GSL function in a comparable region.

Generated by Claude Code

…he transformation z -> 1-z

gsl_sf_hyperg_2F1_e() returns GSL_EUNIMPL with value 0 for z >= 0.995 if r+s+x >= 10. Only GSL_EMAXITER
and GSL_EDOM were handled, so the 0 entered the likelihood and individual log-likelihoods jumped.
For z >= 0.995, or if GSL does not report success, the terms are now computed from the linear
transformation z -> 1-z (A&S 15.3.6), which is elementary plus a short series because c = a+1.
Also divide on the log scale if beta^(r+s+x) overflows. Results for z < 0.995 are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UTYLyr3kUoxePkWEp1bmB4

bachmannpatrick commented Nov 17, 2026 •

Copy link
Copy Markdown
Owner Author

Check in the built package

The branch was installed on a Linux server (renv::install("bachmannpatrick/CLVTools@bugfix-dyncov-hyp2f1-close-to-one")) and the scan that found the jumps was repeated: individual log-likelihoods of the Pareto/NBD with dynamic covariates on 240 values of s between 1.5 and 8, at a fixed mean attrition rate and with all other parameters fixed. A jump is a change between neighbouring points that deviates from the running median of the changes by more than 0.01.

Data Customers Customers with a jump, v0.12.1 Customers with a jump, this branch
Simulated (r 0.62, alpha 5, s 2.7, beta 818) 20,000 133 0
Application with real data 38,047 343 0

No value is infinite or missing in either run, and the run time of the scan is unchanged (15 and 29 minutes).

Checks of this pull request

  • R CMD check passes on Ubuntu (release, oldrel-1, devel), Windows (release, devel) and macOS (release). These jobs run with --no-tests, so they show that the package builds and that the examples run.
  • R CMD check on macOS (devel) fails while installing the dependency data.table from source ('libintl.h' file not found), before CLVTools is compiled. Not related to this change.
  • The test job on macOS (devtools::test() with stop_on_failure = TRUE) passes. Its log lists 177 tests skipped on CI and no failure; neither test-cpp.R, which runs the C++ tests including the new context, nor the dyncov correctness tests are among the skipped ones.
  • The coverage job on Ubuntu passes. It reports 100 % of the lines of src/test-cpp.cpp as executed, so the C++ tests, including the new context, were run, and 96.8 % of the lines of src/pnbd_dyncov_LL.cpp.

Generated by Claude Code

This branch has not been deployed

No deployments
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.

2 participants