```{r} # library(ctsmTMB) devtools::load_all("~/github/ctsmTMB/") ############################################################ # Model creation+ ############################################################ # Create model object model <- newModel() # Add system equations model$addSystem( dx ~ theta * (mu-x+u) * dt + sigma_x * dw ) # Add observation equations model$addObs( y ~ x ) # Set observation equation variances model$setVariance( y ~ sigma_y^2 ) # Add vector input model$addInput(u) # Specify parameter initial values and lower/upper bounds in estimation model$setParameter( theta = c(initial=2, lower=1e-5, upper=50), mu = c(initial=2, lower=0, upper=5), sigma_x = c(initial=1e-2, lower=1e-10, upper=30), sigma_y = c(initial=1e-2, lower=1e-10, upper=30) ) # Set initial state mean and covariance initial.state <- list(x0=3, p0=0.01*diag(1)) model$setInitialState(initial.state) ############################################################ # Simulate observations ############################################################ # First we create data (no observations) r.seed <- 20 # this seed for for u.sim rnorm draws set.seed(r.seed) true.pars = c(theta=10, mu=1, sigma_x=1, sigma_y=0.1) dt.sim = 1e-2 t.sim = seq(0, 5, by=dt.sim) u.sim = cumsum(rnorm(length(t.sim),sd=0.05)) # Create arbitrary input signal df.obs <- data.frame( t = t.sim, u = u.sim, y = NA ) # set seeds for simulation. The first seed is brownian motion rng, # the second is for observations noise rng cpp.seeds <- c(20,20) sim <- model$simulate(data=df.obs, # use the true parameters pars = true.pars, # use a smaller stepsize than diff(df.obs$t) sim.timestep = 1e-4, # we only need 1 simulation n.sims = 5, # apply rng seeds cpp.seeds = cpp.seeds) par(mfrow=c(1,1)) matplot(sim$observations$y$i0,type="l",lty="solid") lines(sim$observations$y$i0[,1],col="black",lwd=2) # store simulated observations in the data.frame df.obs$y <- sim$observations$y$i0[,1] ############################################################ # Model estimation ############################################################ # Carry out estimation with default settings (extended kalman filter) fit <- model$estimate(df.obs, method="ekf") # Check parameter estimates against truth fitted.pars <- fit$par.fixed cbind(true.pars, fitted.pars, difference=true.pars-fitted.pars) par(mfrow=c(1,1)) # Plot prior predictions (1-step predictions) against simulation (truth) and observations (data) df.prior <- fit$states$prior$mean_and_sd with(cbind(df.prior,y=df.obs$y), { plot(x=t, y=x, type="n", main="1-Step Prior Estimates vs Observations", xlab="Time", ylab="", ylim=c(0,3)) polygon(c(t, rev(t)), c(x+1.96*x.sd, rev(x-1.96*x.sd)), col="grey70", border=NA) lines(t, x, col="steelblue", lwd=2) points(t, y, col="tomato", pch=16, cex=0.7) } ) # Predict to obtain 10-step-ahead predictions to see model forecasting ability pred.10step <- model$predict(df.obs, k.ahead=10, method="ekf", return.k.ahead = 10) pred.10step$states$mean_and_sd %>% head # Plot 10 step predictions vs data with(pred.10step$states$mean_and_sd,{ plot(x=t.j, y=x, type="n", main="10 Step Predictions vs Observations", xlab="Time", ylab="", ylim=c(0,3)) polygon(c(t.j, rev(t.j)), c(x+1.96*x.sd, rev(x-1.96*x.sd)), col="grey70", border=NA) lines(t.j, x, col="steelblue", lwd=2) } ) points(df.obs$t, df.obs$y, col="tomato", pch=16, cex=0.7) # Compare full (i.e. without updating to data along the way) prediction and simulation pred <- model$predict(df.obs, method="ekf") sim <- model$simulate(df.obs, method="ekf", n.sims=10, sim.timestep=1e-3) xsim <- sim$states$x$i0 x <- pred$states$mean_and_sd$x # All use the same time vector since all series are full predictions matplot(df.obs$t, xsim, type="l", lty="solid", col="grey70", ylim=c(0,3), xlab="Time", main="Full Prediction/Simulations vs Observations") lines(df.obs$t, x, col="steelblue", lwd=2) points(df.obs$t, df.obs$y, col="tomato", pch=16, cex=0.7) # Perform residual analysis plot(fit) ```