2
votes

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:

enter image description here

I can fit the curve using optim, but I can't figure out the constraint. This should be something like:

enter image description here 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.

1

1 Answers

1
votes

May I suggest modelling the disturbance as a sine wave?

fit <- nls(y ~ a * exp(b * t) + ifelse(d*(t - m) < 0 | d*(t - m) > 2 * pi, 0 , c * sin(d*(t - m))), 
           start = list(a = 170, b = -0.1, c = -20, d = 1, m = 5))
summary(fit)

dat <- data.frame(y=y, t=t)
preddat <- data.frame(t = seq(min(t), max(t), length.out = 100))
preddat$y <- predict(fit, preddat)
preddat$y1 <- coef(fit)[["a"]] * exp(coef(fit)[["b"]] * preddat$t)


library(ggplot2)
ggplot(dat, aes(x=t, y=y)) +
  geom_line() +
  geom_line(data=preddat, color='blue') +
  geom_line(data=preddat, aes(y = y1), color='red', linetype = 2)

resulting pot

I'm sure someone with a background in signal processing could come up with something better than the ugly ifelse hack.