# [R] add constraints to nls or use another function

PtitBleu ptit_bleu at yahoo.fr
Mon Jul 9 13:53:08 CEST 2012

```bbolker wrote
>
> PtitBleu <ptit_bleu <at> yahoo.fr> writes:
>
>>
>> Hello,
>>
>> I'm trying to fit experimental data with a model and nls.
>> For some experiments, I have data with x from 0 to 1.2 and the fit is
>> quite
>> good.
>> But it can happen that I have data only the [0,0.8] range (see the
>> example
>> below) and, then, the fit is not correct.
>>
>> I would like to add a constraint, for example : the second derivative
>> must
>> be positive.
>> But I don't know how to add this to nls and, in fact,  I'm not sure that
>> it
>> is possible.
>> If not, could you give me a package and/or a function (and/or a complete
>> solution, which will be great ...) ?
>>
>> Have a good day,
>> Ptit Bleu.
>>
>
>   This is much less than you asked for -- suggestions rather than
> worked solutions -- but -- if you code your own least-squares function
> and fit it in optim (or use bbmle::mle2 and specify that
> response~dnorm(...)) then you can add a penalty term to the objective
> function that is zero when the second derivative is positive and
> increases quadratically when the second derivative becomes negative.
>
>   There may also (?) be a way to impose such a constraint on
> spline fits.
>
>   By the way, it looks like your model is actually linear
> in the parameters, which might simplify things considerably ...
>
>   Ben Bolker
>

Hello Ben,

It took me time to understand your answer and how to use optim.
I created a function to calculate the theoritical result based on the
equation

fmpv<-function(param,xseq) {
return(param+param*(xseq-1)+param*log(xseq)+param*(xseq-1)*(xseq-1)+param*log(xseq)*log(xseq))
}

and another one to calculate the difference between the theory and the
measurements

fsce<-function(param,xseq,yobs) {
ytheo<-fmpv(param,xseq)
return(sum((yobs-ytheo)^2))
}

and finally apply optim to the data (dftest<-read.table("nlstest_data.txt",
sep=";", dec=".", as.is=T, header=T)  from my first message)
resfit<-optim(c(0,0,0,0,5),fsce,control=list(maxit=1000),method="BFGS",xseq=dftest[,1],
yobs=dftest[,2])

But, as I don't know how to add the constraint on the second derivative, the
parameters provided by optim are (of course)  the same that the ones given
by nls.

Could you just show me how to introduce the constraint ?