RTMB: are valid comparisons with a fixed parameter possible?

80 views
Skip to first unread message

William Stockhausen - NOAA Federal

unread,
Feb 25, 2025, 10:59:53 AM2/25/25
to TMB Users
I have a (constant) vector of sizes, `z` say, and I want to calculate a function f(z) only for z=>z1, 
where z1 is a fixed parameter. Is the following allowed in an RTMB objective function:

fv = AD(array(0,dim=length(z))); #--advector for results
iz = which(z>=z1);                       #--indices of z at which to calculate f
fv[iz] = f(z[iz], other parameters); #--the calculation

?
This works fine, of course, in regular R.

Because z1 is fixed (using the `map` input to MakeADFun), it is essentially a constant as far as differentiability of the objective function goes. However, I get "Error: Comparison is generally unsafe for AD types" when I MakeADFun it. The error certainly makes sense if z1 wasn't "fixed", but is there a way to get around it for a "fixed" parameter? Perhaps I'm just not using the map list correctly and it really should work for a fixed parameter? Unfortunately for me, it's very convenient to enter `z1` as a (fixed) parameter, rather than as part of the "data".

Thanks for any ideas!

William T. Stockhausen

Research Fishery Biologist, Alaska Fisheries Science Center

NOAA Fisheries | U.S. Department of Commerce

Office: (206) 526-4241

www.fisheries.noaa.gov


William Stockhausen - NOAA Federal

unread,
Feb 28, 2025, 2:51:29 PM2/28/25
to TMB Users
Hi all,

Just FYI, in answer to the (my own) question, the following seems to work in both regular R and with RTMB: 

Recall (see original message) that I wanted to calculate values for a function "f" used in an objective function only at values of a vector "z" that were less than a fixed parameter "z1".
So
z1: a fixed parameter value using map-list(z1=factor(NA)) when MakeADFun'ing the objective function
in the R function called in the objective function, I used:
if (RTMB:::ad_context()){
  #--in AD mode
  nz1 = RTMB:::getValues(z1); #--convert value to regular numeric
} else {
  nz1 = z1; #--just copy in regular R session
}
fv = AD(array(0,dim=length(z))); #--advector for results
idx = which(z>=z1);                       #--indices of z at which to calculate f
fv[idx] = f(z[idx],other stuff);        #--calculates only at specified indices, 0 otherwise

The above seems to work: got no errors when making the objective function and got sensible results in a simple optimization test case.
The gradient from the objective function for the z1 parameter was 0, as expected, and the gradients for the other parameters I was fitting to were on the order of 10^-6.

Reply all
Reply to author
Forward
0 new messages