Unexpected behavior when using "pexp" function within RTMB likelihood and "log.p = TRUE"

17 views
Skip to first unread message

pthomp...@gmail.com

unread,
Apr 14, 2026, 6:36:47 PMApr 14
to TMB Users
Hi there,

I'm building a model with RTMB that requires me to use the "pexp" (i.e., cumulative distribution function) function within the negative log-likelihood (not just "dexp" as is usually used). A simplified version of the model I'm working on is effectively a truncated exponential distribution, of which I provide an example below:

library(RTMB)

N = 1e6
L = 1
Q = 0.75

t_max = qexp(Q, rate = L)

# Generate some exponential data that are artificially truncated
DAT = data.frame(tt = rexp(N, rate = L)) |>
  dplyr::mutate(tt < t_max)

trunc_exp = function(pars, dat = DAT) {
 
  "[<-" <- ADoverload("[<-")
  getAll(pars, dat, warn = FALSE)
 
  # Negative log-likelihood for truncated exponential distribution
  nll_begin = -dexp(tt, exp(lambda_log), log = TRUE)

  # Account for the truncation factor to normalize the probabilities
  nll_weight = RTMB::pexp(t_max, exp(lambda_log), log.p = TRUE)
 
  sum(nll_begin + nll_weight)
 
}

obj = RTMB::MakeADFun(trunc_exp, list(lambda_log = 0))

For me, the final line (making the RTMB model object) throws an error: "Error in RTMB::pexp(t_max, exp(lambda_log), log.p = TRUE) : Non-numeric argument to mathematical function". I tested this out and it turns out the error goes away when you remove the "log.p = TRUE" argument. I'm not sure what the problem is because if you just call the "trunc_exp()" function in R, it works and returns what you'd expect. I've tried a bunch of things but can't seem to figure out how to fix this. Hopefully it's something easy & obvious!

An easy workaround for this is to simply use log(pexp(...)) instead, but this isn't ideal as I believe it's less precise than doing the log calculation inside the pexp() function.

I'm using R 4.5.3 on Windows 11 with RTMB version 1.9 (TMB version 1.9.21).

Let me know if you have any questions and thank you in advance for your help!

Peter R. Thompson, Ph.D.
Reply all
Reply to author
Forward
0 new messages