Fitting differential equations: how to fit a set of data to a differential equation in R

笑着哭i 提交于 2019-12-12 03:49:13

问题


With a data set:

conc <- data.frame(time = c(0.16, 0.5, 1.0, 1.5, 2.0, 2.5, 3), concentration = c(170, 122, 74, 45, 28, 17, 10))

and I would like to fit this data to the differential equation below:

dC/dt= -kC

where C would be the concentration, and time t in the data set. This would also give a result of k. Could anybody give me a clue how to do this in R? Thanks.


回答1:


This could be a solution:

    require('deSolve')
conc <- data.frame(time <- c(0.16, 0.5, 1.0, 1.5, 2.0, 2.5, 3), concentration <- c(170, 122, 74, 45, 28, 17, 10))

##"Model" with differential equation
model <- function(t, C, k){
  list(-k * C)
}

##Cost function with sum of squared residuals:
cost <- function(k){
  c.start <- 170
  out <- lsoda(c(C=c.start), conc$time, model, k)
  c <- sum( (conc$concentration - out[,"C"])^2)       
  c
}

##Initial value for k
k <- 3
##  Use some optimization procedure
opt <- optim(k, cost, method="Brent", lower=0, upper=10)

k.fitted <- opt$par

Maybe it is a bit naive since using lsoda seems to be a bit overkill for calculating with only one differential equation... But it certainly optimizes your k. You might want to check the start value for C for the integration, I set it to 170 here, don't you have a value for t=0?




回答2:


First use separation of variables to solve the differential equation. This gives log(C)=-k*t+C0.

Plot the data:

plot(log(concentration) ~ time,data=conc)

Fit a linear model:

fit <- lm(log(concentration) ~ time,data=conc)
summary(fit)

# Coefficients:
#               Estimate Std. Error t value Pr(>|t|)    
# (Intercept)   5.299355   0.009787   541.4 4.08e-13 ***
#   time       -0.992208   0.005426  -182.9 9.28e-11 ***
#   ---
#   Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 
# 
# Residual standard error: 0.01388 on 5 degrees of freedom
# Multiple R-squared: 0.9999,  Adjusted R-squared: 0.9998 
# F-statistic: 3.344e+04 on 1 and 5 DF,  p-value: 9.281e-11 

Plot the predicted values:

lines(predict(fit)~conc$time)

Extract k:

k <- -coef(fit)[2]
#0.9922081



来源:https://stackoverflow.com/questions/15660954/fitting-differential-equations-how-to-fit-a-set-of-data-to-a-differential-equat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!