I have a curve with a disturbance in the middle (at t=9) which causes a downturn (t<9) and an upturn (t>9) in my data. I would like to fit an exponential function and add a constraint that the area of the two (downturn and upturn) are equal.
See figure:
I can fit the curve using optim, but I can't figure out the constraint. This should be something like:
where f(x) is the exponential function.
I've tried constrOptim, but I am open to using other solvers as well.
y <-c(170, 160, 145, 127, 117, 74, 76, 78, 101, 115, 120, 70, 64, 65)
t <- seq(1,14,1)
# starting values:
lm <-lm(log(y) ~ log(t))
# Exp. Least-Squares minimization:
func <-function(pars) {
a <- pars["a"]
b <- pars["b"]
fitted <- a*exp(b*t)
sum((y-fitted)^2)
}
a <-lm$coefficients[[1]]
b <-lm$coefficients[[2]]
c <-
result <- optim(c(a=a, b=b), func)
# final parameters:
a <- result$par["a"]
b <- result$par["b"]
# predict values:
pred <- a*exp(b*t)
dat = data.frame(y=y, t=t, pred=pred)
library(ggplot2)
ggplot(dat, aes(x=t, y=y)) +
geom_line() +
geom_line(data=dat, aes(x=t, y=pred), color='blue')
Edit:
I know I need to add the constraint to the optimization above. Like so:
i = 6:12
result <- optim(c(a=a, b=b), func, sum(y[i]-a*exp(b*t[i])=0)
But this doesn't seem to be working. optim function does not allow constraints of this kind.