Search code examples
roptimizationcurve-fittingnon-linear-regression

R: Optim() fitting parameter limits


I'm looking to put a limit on the output parameters from optim(). It is needlessly converging thousands of phases of out of phase for my sinusoidal function (where 'designL' is my independent variable, and 'ratio' is my dependent variable data, dfm is my dataframe):

lo_0 = 2e-6
kc_0 = 80000
min.RSS <- function(data, par) {
  with(data, sum( (sin(par[2] *(par[1] + designL))^2 - ratio)^2) )
}
resultt <- optim(par = c(lo_0, kc_0), min.RSS, data = dfm)

I want to limit the lo_0 (phase shift) from 0:2e-5. I found some documentaition on this, but it doesn't go into much description on how to achieve: https://ubuntuforums.org/showthread.php?t=1420061


Solution

  • Probably

    resultt <- optim(par = c(lo_0, kc_0), min.RSS, data = dfm[ind_1,],
         method="L-BFGS-B", lower=c(0,-Inf), upper=c(2e-5,Inf))
    

    I strongly suggest that in addition you use the argument control=list(parscale=c(lo_0,kc_0)); optim() expects parameters to be similarly scaled and (when using finite-difference approximations to compute derivatives) to be of order 1.