AD to numeric in RTMB

34 views
Skip to first unread message

KUNASEKARAN NIRMALKANNA

unread,
Jul 10, 2025, 12:52:57 PMJul 10
to TMB Users
Hi Dr. Kasper Kristensen,

I am trying to convert my TMB codes to RTMB nowadays. I find RTMB is really helpful, especially for beginners. I tried to extract reports from the RTMB object (from MakeADFun), but those are in AD objects, and they cause errors because they are not numeric objects.  

For example, I had the following issue:
> library(RTMB)
> x <- advector(c(1:5))
> data.frame(x)
       x
1 NaN+1i
2 NaN+2i
3 NaN+3i
4 NaN+4i
5 NaN+5i

As a solution, I tried:
> class(x) <- NULL
> data.frame(Im(x))
  Im.x.
1     1
2     2
3     3
4     4
5     5

Following that, I wrote the following code to convert ad objects to numeric objects. 

rep.nowt <- obj$report()
INV_AD <- function(x){
  if("advector"%in%class(x)){
    dim_arr <- dim(x)
    if(!is.null(dim_arr)){
      class(x) <- NULL
      OUT <- array(Im(x), dim = dim_arr)
    }else{
      class(x) <- NULL
      OUT <- Im(x)
    }
  }else{
    OUT <- x
  }
  return(OUT)
}
rep.nowt_new <- list()
for(list_i in 1:length(rep.nowt)){
  rep.nowt_new[[list_i]] <- INV_AD(rep.nowt[[list_i]])
}
names(rep.nowt_new) <- names(rep.nowt)
rep.nowt <- rep.nowt_new

I am not sure whether I am missing anything here. Could you please guide me on this issue?

Thank you.
Regards,
Kanna.

Kasper Kristensen

unread,
Jul 28, 2025, 6:08:06 AMJul 28
to TMB Users
Reported objects should never be AD. Quoting from ?advector:

An ‘advector’ is a class used behind the scenes...
you do not _see_ / _need to know_ it as a normal user...

It is strongly discouraged to convert 'advector' to numeric. However, for debugging purposes one can can extract the underlying numeric values using the un-exported RTMB:::getValues(). Do NOT use the Re()/Im() to extract information!
Reply all
Reply to author
Forward
0 new messages