Skip to content

qnorm() AD overload not detected after call to optim() #75

@andrjohns

Description

@andrjohns

I've run into what feels like a very narrow edge-case, where calling the optim function before MakeADFun results in the AD overload for qnorm failing to be found. But if the function is re-declared after the call to optim, then all works as expected:

y <- matrix(rep(0.8, 4), ncol = 2)

library(RTMB)

ll_function <- function(v) {
  # Works if uncommented
  # y <- matrix(rep(0.8, 4), ncol = 2)
  
  lambda <- v[1]
  
  u <- y
  u[,1] <- pexp(y[,1], rate = v[1])
  u[,2] <- pexp(y[,2], rate = v[1])
  
  # Works if uncommented
  #u <- pexp(y, rate = v[1])
  
  sum(qnorm(u))
}

result <- optim(
  par = 0.1,
  fn = \(x) -ll_function(x)
)
#> Warning in optim(par = 0.1, fn = function(x) -ll_function(x)): one-dimensional optimization by Nelder-Mead is unreliable:
#> use "Brent" or optimize() directly


obj <- MakeADFun(
  func = \(v) ll_function(v$v),
  parameters = list(v=0.1),
  silent = TRUE
)
#> Error in stats::qnorm(p = p, mean = mean, sd = sd): Non-numeric argument to mathematical function

# Re-evaluate function declaration
ll_function2 <- eval(parse(text = deparse(ll_function)))

obj <- MakeADFun(
  func = \(v) ll_function2(v$v),
  parameters = list(v=0.1),
  silent = TRUE
)

str(obj)
#> List of 11
#>  $ par         : Named num 0.1
#>   ..- attr(*, "names")= chr "v"
#>  $ fn          :function (x = last.par[lfixed()], ...)  
#>  $ gr          :function (x = last.par[lfixed()], ...)  
#>  $ he          :function (x = last.par[lfixed()], atomic = usingAtomics())  
#>  $ hessian     : logi FALSE
#>  $ method      : chr "BFGS"
#>  $ retape      :function (set.defaults = TRUE)  
#>  $ env         :<environment: 0x1137d0210> 
#>  $ report      :function (par = obj$env$last.par, ...)  
#>  $ simulate    :function (par = obj$env$last.par, ...)  
#>  $ force.update:function ()

Created on 2025-10-18 with reprex v2.1.1

Very odd!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions