1% Generated by roxygen2: do not edit by hand
2% Please edit documentation in R/KFAS-package.R
3\docType{package}
4\name{KFAS}
5\alias{KFAS}
6\title{KFAS: Functions for Exponential Family State Space Models}
7\description{
8Package KFAS contains functions for Kalman filtering, smoothing and
9simulation of linear state space models with exact diffuse initialization.
10}
11\details{
12Note, this help page might be more readable in pdf format due to the mathematical
13formulas containing subscripts.
14
15The linear Gaussian state space model is given by
16
17\deqn{y_t = Z_t \alpha_t + \epsilon_t, (\textrm{observation equation})}{
18 y[t] = Z[t]\alpha[t] + \epsilon[t], (observation equation)}
19
20
21\deqn{\alpha_{t+1} = T_t \alpha_t + R_t \eta_t, (\textrm{transition equation})}{\alpha[t+1] = T[t]\alpha[t]
22+ R[t]\eta[t], (transition equation)}
23
24where \eqn{\epsilon_t \sim N(0, H_t)}{\epsilon[t] ~ N(0, H[t])}, \eqn{\eta_t
25\sim N(0, Q_t)}{\eta[t] ~ N(0, Q[t])} and \eqn{\alpha_1 \sim
26N(a_1, P_1)}{\alpha[1] ~ N(a[1], P[1])} independently of each other.
27
28All system and covariance matrices \code{Z}, \code{H}, \code{T}, \code{R} and
29\code{Q} can be time-varying, and partially or totally missing observations
30\eqn{y_t}{y[t]} are allowed.
31
32Covariance matrices H and Q has to be positive semidefinite (although this is
33not checked).
34
35Model components in \code{KFAS} are defined as
36\describe{
37  \item{y}{A n x p matrix containing the observations. }
38  \item{Z}{A p x m x 1 or p x m x n array corresponding to the system matrix
39  of observation equation. }
40  \item{H}{A p x p x 1 or p x p x n array
41  corresponding to the covariance matrix of observational disturbances
42  epsilon. }
43  \item{T}{A m x m x 1 or m x m x n array corresponding to the
44  first system matrix of state equation. }
45  \item{R}{A m x k x 1 or m x k x n array corresponding to the second system matrix of state equation. }
46  \item{Q}{A k x k x 1 or k x k x n array corresponding to the covariance
47  matrix of state disturbances eta }
48  \item{a1}{A m x 1 matrix containing the
49  expected values of the initial states. }
50  \item{P1}{A m x m matrix
51  containing the covariance matrix of the nondiffuse part of the initial
52  state vector. }
53  \item{P1inf}{A m x m matrix containing the covariance
54  matrix of the diffuse part of the initial state vector. }
55  \item{u}{A n x p
56  matrix of an additional parameters in case of non-Gaussian model.}
57}
58In case of any of the series in model is defined as non-Gaussian, the
59observation equation is of form \deqn{\prod_i^p
60p_i(y_{t, p}|\theta_t)}{\prod[i]^p p(y[t, i]|\theta[t]), } with
61\eqn{\theta_{t, i} = Z_{i, t}\alpha_t}{\theta[t, i] = Z[i, t]\alpha[t]} being one of
62the following:
63
64\itemize{
65\item \eqn{y_t \sim N(\mu_t, u_t), }{y[t]~N(\mu[t], u[t]), } with identity link \eqn{\theta_t = \mu_t}{\theta[t] = \mu[t]}.
66Note that now variances are defined using \eqn{u_t}, not \eqn{H_t}.
67If the correlation between Gaussian observation equations is needed, one can use
68\eqn{u_t = 0}{u[t] = 0} and add correlating disturbances into state equation (although care is
69then needed when making inferences about signal which contains the error terms also).
70
71\item \eqn{y_t \sim \textrm{Poisson}(u_t\lambda_t), }{y[t]~Poisson(u[t]\lambda[t]), } where \eqn{u_t}{u[t]}
72is an offset term, with \eqn{\theta_t = log(\lambda_t)}{\theta[t] = log(\lambda[t])}.
73
74\item \eqn{y_t \sim \textrm{binomial}(u_t, \pi_t), }{y[t]~binomial(u[t], \pi[t]), } with \eqn{\theta_t =
75log[\pi_t/(1-\pi_t)]}{\theta[t] = log(\pi[t]/(1-\pi[t]))}, where
76\eqn{\pi_t}{\pi[t]} is the probability of success at time \eqn{t}.
77
78\item \eqn{y_t \sim \textrm{gamma}(u_t, \mu_t), }{y[t]~gamma(u[t], \mu[t]), } with \eqn{\theta_t =
79log(\mu_t)}{[\theta[t] = log(\mu[t])]}, where \eqn{\mu_t}{\mu[t]} is the mean
80parameter and \eqn{u_t}{u[t]} is the shape parameter.
81
82\item \eqn{y_t \sim \textrm{negative binomial}(u_t, \mu_t), }{y[t]~negative binomial(u[t], \mu[t]), }
83 with expected value \eqn{\mu_t}{\mu[t]} and variance \eqn{\mu_t+ \mu_t^2/u_t}{\mu[t]+
84\mu[t]^2/u[t]} (see \code{\link{dnbinom}}), then \eqn{\theta_t =
85log(\mu_t)}{\theta[t] = log(\mu[t])}.
86}
87
88For exponential family models \eqn{u_t = 1}{u[t] = 1} as a default.
89For completely Gaussian models, parameter is omitted. Note that series can
90have different distributions in case of multivariate models.
91
92For the unknown elements of initial state vector \eqn{a_1}{a[1]}, KFAS uses
93exact diffuse initialization by Koopman and Durbin (2000, 2012, 2003), where
94the unknown initial states are set to have a zero mean and infinite variance,
95so \deqn{P_1 = P_{\ast, 1} + \kappa P_{\infty, 1}, }{P[1] = P[*, 1] +
96\kappaP[inf, 1], } with \eqn{\kappa} going to infinity and
97\eqn{P_{\infty, 1}}{P[inf, 1]} being diagonal matrix with ones on diagonal
98elements corresponding to unknown initial states.
99
100This method is basically a equivalent of setting uninformative priors for the
101initial states in a Bayesian framework.
102
103Diffuse phase is continued until rank of \eqn{P_{\infty, t}}{P[inf, t]} becomes
104zero. Rank of \eqn{P_{\infty, t}}{P[inf, t]} decreases by 1, if
105\eqn{F_{\infty, t}>\xi_t>0}{F[inf, t]>\xi[t]>0}, where \eqn{\xi_t}{\xi[t]} is by default
106\code{.Machine$double.eps^0.5*min(X)^2)}, where X is absolute values of non-zero
107elements of array Z. Usually the number of diffuse time points
108equals the number unknown elements of initial state vector, but missing
109observations or time-varying system matrices can affect this. See Koopman and
110Durbin (2000, 2012, 2003) for details for exact diffuse and non-diffuse
111filtering.  If the number of diffuse states is large compared to the data, it
112is possible that the model is degenerate in a sense that not enough
113information is available for leaving the diffuse phase.
114
115To lessen the notation and storage space, KFAS uses letters P, F and K for
116non-diffuse part of the corresponding matrices, omitting the asterisk in
117diffuse phase.
118
119All functions of KFAS use the univariate approach (also known as sequential
120processing, see Anderson and Moore (1979)) which is from Koopman and Durbin
121(2000, 2012). In univariate approach the observations are introduced one
122element at the time. Therefore the prediction error variance matrices F and
123Finf do not need to be non-singular, as there is no matrix inversions in
124univariate approach algorithm.  This provides possibly more
125faster filtering and smoothing than normal multivariate Kalman filter
126algorithm, and simplifies the formulas for diffuse filtering and smoothing.
127If covariance matrix H is not diagonal, it is possible to transform the model by either using
128LDL decomposition on H, or augmenting the state vector with \eqn{\epsilon}
129disturbances (this is done automatically in KFAS if needed).
130See \code{\link{transformSSM}} for more details.
131}
132\examples{
133
134################################################
135# Example of local level model for Nile series #
136################################################
137# See Durbin and Koopman (2012)
138
139model_Nile <- SSModel(Nile ~
140  SSMtrend(1, Q = list(matrix(NA))), H = matrix(NA))
141model_Nile
142model_Nile <- fitSSM(model_Nile, c(log(var(Nile)), log(var(Nile))),
143  method = "BFGS")$model
144
145# Filtering and state smoothing
146out_Nile <- KFS(model_Nile, filtering = "state", smoothing = "state")
147out_Nile
148
149# Confidence and prediction intervals for the expected value and the observations.
150# Note that predict uses original model object, not the output from KFS.
151conf_Nile <- predict(model_Nile, interval = "confidence", level = 0.9)
152pred_Nile <- predict(model_Nile, interval = "prediction", level = 0.9)
153
154ts.plot(cbind(Nile, pred_Nile, conf_Nile[, -1]), col = c(1:2, 3, 3, 4, 4),
155        ylab = "Predicted Annual flow", main = "River Nile")
156
157
158# Missing observations, using the same parameter estimates
159
160NileNA <- Nile
161NileNA[c(21:40, 61:80)] <- NA
162model_NileNA <- SSModel(NileNA ~ SSMtrend(1, Q = list(model_Nile$Q)),
163H = model_Nile$H)
164
165out_NileNA <- KFS(model_NileNA, "mean", "mean")
166
167# Filtered and smoothed states
168ts.plot(NileNA, fitted(out_NileNA, filtered = TRUE), fitted(out_NileNA),
169  col = 1:3, ylab = "Predicted Annual flow",
170  main = "River Nile")
171
172
173\dontrun{
174##################
175# Seatbelts data #
176##################
177# See Durbin and Koopman (2012)
178
179model_drivers <- SSModel(log(drivers) ~ SSMtrend(1, Q = list(NA))+
180   SSMseasonal(period = 12, sea.type = "trigonometric", Q = NA) +
181   log(PetrolPrice) + law, data = Seatbelts, H = NA)
182
183# As trigonometric seasonal contains several disturbances which are all
184# identically distributed, default behaviour of fitSSM is not enough,
185# as we have constrained Q. We can either provide our own
186# model updating function with fitSSM, or just use optim directly:
187
188# option 1:
189ownupdatefn <- function(pars, model){
190  model$H[] <- exp(pars[1])
191  diag(model$Q[, , 1]) <- exp(c(pars[2], rep(pars[3], 11)))
192  model #for optim, replace this with -logLik(model) and call optim directly
193}
194
195fit_drivers <- fitSSM(model_drivers,
196  log(c(var(log(Seatbelts[, "drivers"])), 0.001, 0.0001)),
197  ownupdatefn, method = "BFGS")
198
199out_drivers <- KFS(fit_drivers$model, smoothing = c("state", "mean"))
200out_drivers
201ts.plot(out_drivers$model$y, fitted(out_drivers), lty = 1:2, col = 1:2,
202  main = "Observations and smoothed signal with and without seasonal component")
203lines(signal(out_drivers, states = c("regression", "trend"))$signal,
204  col = 4, lty = 1)
205legend("bottomleft", col = c(1, 2, 4), lty = c(1, 2, 1),
206  legend = c("Observations", "Smoothed signal", "Smoothed level"))
207
208# Multivariate model with constant seasonal pattern,
209# using the the seat belt law dummy only for the front seat passangers,
210# and restricting the rank of the level component by using custom component
211
212model_drivers2 <- SSModel(log(cbind(front, rear)) ~ -1 +
213    log(PetrolPrice) + log(kms) +
214    SSMregression(~law, data = Seatbelts, index = 1) +
215    SSMcustom(Z = diag(2), T = diag(2), R = matrix(1, 2, 1),
216      Q = matrix(1), P1inf = diag(2)) +
217    SSMseasonal(period = 12, sea.type = "trigonometric"),
218  data = Seatbelts, H = matrix(NA, 2, 2))
219
220# An alternative way for defining the rank deficient trend component:
221
222# model_drivers2 <- SSModel(log(cbind(front, rear)) ~ -1 +
223#     log(PetrolPrice) + log(kms) +
224#     SSMregression(~law, data = Seatbelts, index = 1) +
225#     SSMtrend(degree = 1, Q = list(matrix(0, 2, 2))) +
226#     SSMseasonal(period = 12, sea.type = "trigonometric"),
227#   data = Seatbelts, H = matrix(NA, 2, 2))
228#
229# Modify model manually:
230# model_drivers2$Q <- array(1, c(1, 1, 1))
231# model_drivers2$R <- model_drivers2$R[, -2, , drop = FALSE]
232# attr(model_drivers2, "k") <- 1L
233# attr(model_drivers2, "eta_types") <- attr(model_drivers2, "eta_types")[1]
234
235
236likfn <- function(pars, model, estimate = TRUE){
237  diag(model$H[, , 1]) <- exp(0.5 * pars[1:2])
238  model$H[1, 2, 1] <- model$H[2, 1, 1] <-
239    tanh(pars[3]) * prod(sqrt(exp(0.5 * pars[1:2])))
240  model$R[28:29] <- exp(pars[4:5])
241  if(estimate) return(-logLik(model))
242  model
243}
244
245fit_drivers2 <- optim(f = likfn, p = c(-8, -8, 1, -1, -3), method = "BFGS",
246  model = model_drivers2)
247model_drivers2 <- likfn(fit_drivers2$p, model_drivers2, estimate = FALSE)
248model_drivers2$R[28:29, , 1]\%*\%t(model_drivers2$R[28:29, , 1])
249model_drivers2$H
250
251out_drivers2 <- KFS(model_drivers2)
252out_drivers2
253ts.plot(signal(out_drivers2, states = c("custom", "regression"))$signal,
254  model_drivers2$y, col = 1:4)
255
256# For confidence or prediction intervals, use predict on the original model
257pred <- predict(model_drivers2,
258  states = c("custom", "regression"), interval = "prediction")
259
260# Note that even though the intervals were computed without seasonal pattern,
261# PetrolPrice induces seasonal pattern to predictions
262ts.plot(pred$front, pred$rear, model_drivers2$y,
263  col = c(1, 2, 2, 3, 4, 4, 5, 6), lty = c(1, 2, 2, 1, 2, 2, 1, 1))
264}
265
266######################
267# ARMA(2, 2) process #
268######################
269set.seed(1)
270y <- arima.sim(n = 1000, list(ar = c(0.8897, -0.4858), ma = c(-0.2279, 0.2488)),
271               innov = rnorm(1000) * sqrt(0.5))
272
273
274model_arima <- SSModel(y ~ SSMarima(ar = c(0, 0), ma = c(0, 0), Q = 1), H = 0)
275
276likfn <- function(pars, model, estimate = TRUE){
277  tmp <- try(SSMarima(artransform(pars[1:2]), artransform(pars[3:4]),
278    Q = exp(pars[5])), silent = TRUE)
279  if(!inherits(tmp, "try-error")){
280    model["T", "arima"] <- tmp$T
281    model["R", states = "arima", etas = "arima"] <- tmp$R
282    model["P1", "arima"] <- tmp$P1
283    model["Q", etas = "arima"] <- tmp$Q
284    if(estimate){
285      -logLik(model)
286    } else model
287  } else {
288    if(estimate){
289      1e100
290    } else model
291  }
292}
293
294fit_arima <- optim(par = c(rep(0, 4), log(1)), fn = likfn, method = "BFGS",
295  model = model_arima)
296model_arima <- likfn(fit_arima$par, model_arima, FALSE)
297
298# AR coefficients:
299model_arima$T[2:3, 2, 1]
300# MA coefficients:
301model_arima$R[3:4]
302# sigma2:
303model_arima$Q[1]
304# intercept
305KFS(model_arima)
306# same with arima:
307arima(y, c(2, 0, 2))
308# small differences because the intercept is handled differently in arima
309
310\dontrun{
311#################
312# Poisson model #
313#################
314# See Durbin and Koopman (2012)
315model_van <- SSModel(VanKilled ~ law + SSMtrend(1, Q = list(matrix(NA)))+
316               SSMseasonal(period = 12, sea.type = "dummy", Q = NA),
317               data = Seatbelts, distribution = "poisson")
318
319# Estimate variance parameters
320fit_van <- fitSSM(model_van, c(-4, -7), method = "BFGS")
321
322model_van <- fit_van$model
323
324# use approximating model, gives posterior modes
325out_nosim <- KFS(model_van, nsim = 0)
326# State smoothing via importance sampling
327out_sim <- KFS(model_van, nsim = 1000)
328
329out_nosim
330out_sim
331}
332
333## using deterministic inputs in observation and state equations
334model_Nile <- SSModel(Nile ~
335  SSMcustom(Z=1, T = 1, R = 0, a1 = 100, P1inf = 0, P1 = 0, Q = 0, state_names = "d_t") +
336  SSMcustom(Z=0, T = 1, R = 0, a1 = 100, P1inf = 0, P1 = 0, Q = 0, state_names = "c_t") +
337  SSMtrend(1, Q = 1500), H = 15000)
338model_Nile$T
339model_Nile$T[1, 3, 1] <- 1 # add c_t to level
340model_Nile0 <- SSModel(Nile ~
341  SSMtrend(2, Q = list(1500, 0), a1 = c(0, 100), P1inf = diag(c(1, 0))),
342  H = 15000)
343
344ts.plot(KFS(model_Nile0)$mu, KFS(model_Nile)$mu, col = 1:2)
345
346##########################################################
347### Examples of generalized linear modelling with KFAS ###
348##########################################################
349
350# Same example as in ?glm
351counts <- c(18, 17, 15, 20, 10, 20, 25, 13, 12)
352outcome <- gl(3, 1, 9)
353treatment <- gl(3, 3)
354glm_D93 <- glm(counts ~ outcome + treatment, family = poisson())
355
356model_D93 <- SSModel(counts ~ outcome + treatment,
357  distribution = "poisson")
358
359out_D93 <- KFS(model_D93)
360coef(out_D93, last = TRUE)
361coef(glm_D93)
362
363summary(glm_D93)$cov.s
364out_D93$V[, , 1]
365
366# approximating model as in GLM
367out_D93_nosim <- KFS(model_D93, smoothing = c("state", "signal", "mean"),
368  expected = TRUE)
369
370# with importance sampling. Number of simulations is too small here,
371# with large enough nsim the importance sampling actually gives
372# very similar results as the approximating model in this case
373set.seed(1)
374out_D93_sim <- KFS(model_D93,
375  smoothing = c("state", "signal", "mean"), nsim = 1000)
376
377
378## linear predictor
379# GLM
380glm_D93$linear.predictor
381# approximate model, this is the posterior mode of p(theta|y)
382c(out_D93_nosim$thetahat)
383# importance sampling on theta, gives E(theta|y)
384c(out_D93_sim$thetahat)
385
386
387## predictions on response scale
388# GLM
389fitted(glm_D93)
390# approximate model with backtransform, equals GLM
391fitted(out_D93_nosim)
392# importance sampling on exp(theta)
393fitted(out_D93_sim)
394
395# prediction variances on link scale
396# GLM
397as.numeric(predict(glm_D93, type = "link", se.fit = TRUE)$se.fit^2)
398# approx, equals to GLM results
399c(out_D93_nosim$V_theta)
400# importance sampling on theta
401c(out_D93_sim$V_theta)
402
403
404# prediction variances on response scale
405# GLM
406as.numeric(predict(glm_D93, type = "response", se.fit = TRUE)$se.fit^2)
407# approx, equals to GLM results
408c(out_D93_nosim$V_mu)
409# importance sampling on theta
410c(out_D93_sim$V_mu)
411
412# A Gamma example modified from ?glm
413# Now with log-link, and identical intercept terms
414clotting <- data.frame(
415u = c(5,10,15,20,30,40,60,80,100),
416lot1 = c(118,58,42,35,27,25,21,19,18),
417lot2 = c(69,35,26,21,18,16,13,12,12))
418
419model_gamma <- SSModel(cbind(lot1, lot2) ~ -1 + log(u) +
420    SSMregression(~ 1, type = "common", remove.intercept = FALSE),
421  data = clotting, distribution = "gamma")
422
423update_shapes <- function(pars, model) {
424  model$u[, 1] <- pars[1]
425  model$u[, 2] <- pars[2]
426  model
427}
428fit_gamma <- fitSSM(model_gamma, inits = c(1, 1), updatefn = update_shapes,
429method = "L-BFGS-B", lower = 0, upper = 100)
430logLik(fit_gamma$model)
431KFS(fit_gamma$model)
432fit_gamma$model["u", times = 1]
433
434
435
436\dontrun{
437####################################
438### Linear mixed model with KFAS ###
439####################################
440
441# example from ?lmer of lme4 package
442data("sleepstudy", package = "lme4")
443
444model_lmm <- SSModel(Reaction ~ Days +
445    SSMregression(~ Days, Q = array(0, c(2, 2, 180)),
446       P1 = matrix(NA, 2, 2), remove.intercept = FALSE), sleepstudy, H = NA)
447
448# The first 10 time points the third and fouth state
449# defined with SSMregression correspond to the first subject, and next 10 time points
450# are related to second subject and so on.
451
452# need to use ordinary $ assignment as [ assignment operator for SSModel
453# object guards against dimension altering
454model_lmm$T <- array(model_lmm["T"], c(4, 4, 180))
455attr(model_lmm, "tv")[3] <- 1L #needs to be integer type!
456
457# "cut the connection" between the subjects
458times <- seq(10, 180, by = 10)
459model_lmm["T",states = 3:4, times = times] <- 0
460
461# for the first subject the variance of the random effect is defined via P1
462# for others, we use Q
463model_lmm["Q", times = times] <- NA
464
465update_lmm <- function(pars = init, model){
466  P1 <- diag(exp(pars[1:2]))
467  P1[1, 2] <- pars[3]
468  model["P1", states = 3:4] <- model["Q", times = times] <-
469    crossprod(P1)
470  model["H"] <- exp(pars[4])
471  model
472}
473
474inits <- c(0, 0, 0, 3)
475
476fit_lmm <- fitSSM(model_lmm, inits, update_lmm, method = "BFGS")
477out_lmm <- KFS(fit_lmm$model)
478# unconditional covariance matrix of random effects
479fit_lmm$model["P1", states = 3:4]
480
481# conditional covariance matrix of random effects
482# same for each subject and time point due to model structure
483# these differ from the ones obtained from lmer as these are not conditioned
484# on the fixed effects
485out_lmm$V[3:4,3:4,1]
486}
487\dontrun{
488#########################################
489### Example of cubic spline smoothing ###
490#########################################
491# See Durbin and Koopman (2012)
492require("MASS")
493data("mcycle")
494
495model <- SSModel(accel ~ -1 +
496    SSMcustom(Z = matrix(c(1, 0), 1, 2),
497      T = array(diag(2), c(2, 2, nrow(mcycle))),
498      Q = array(0, c(2, 2, nrow(mcycle))),
499      P1inf = diag(2), P1 = diag(0, 2)), data = mcycle)
500
501model$T[1, 2, ] <- c(diff(mcycle$times), 1)
502model$Q[1, 1, ] <- c(diff(mcycle$times), 1)^3/3
503model$Q[1, 2, ] <- model$Q[2, 1, ] <- c(diff(mcycle$times), 1)^2/2
504model$Q[2, 2, ] <- c(diff(mcycle$times), 1)
505
506
507updatefn <- function(pars, model, ...){
508  model["H"] <- exp(pars[1])
509  model["Q"] <- model["Q"] * exp(pars[2])
510  model
511}
512
513fit <- fitSSM(model, inits = c(4, 4), updatefn = updatefn, method = "BFGS")
514
515pred <- predict(fit$model, interval = "conf", level = 0.95)
516plot(x = mcycle$times, y = mcycle$accel, pch = 19)
517lines(x = mcycle$times, y = pred[, 1])
518lines(x = mcycle$times, y = pred[, 2], lty = 2)
519lines(x = mcycle$times, y = pred[, 3], lty = 2)
520}
521
522\dontrun{
523##################################################################
524# Example of multivariate model with common parameters           #
525# and unknown intercept terms in state and observation equations #
526##################################################################
527set.seed(1)
528n1 <- 20
529n2 <- 30
530z1 <- sin(1:n1)
531z2 <- cos(1:n2)
532
533C <- 0.6
534D <- -0.4
535# random walk with drift D
536x1 <- cumsum(rnorm(n1) + D)
537x2 <- cumsum(rnorm(n2) + D)
538
539y1 <- rnorm(n1, z1 * x1 + C * 1)
540y2 <- rnorm(n2, z2 * x2 + C * 2)
541
542n <- max(n1, n2)
543Y <- matrix(NA, n, 2)
544Y[1:n1, 1] <- y1
545Y[1:n2, 2] <- y2
546
547Z <- array(0, c(2, 4, n))
548Z[1, 1, 1:n1] <- z1
549Z[2, 2, 1:n2] <- z2 # trailing zeros are ok, as corresponding y is NA
550Z[1, 3, ] <- 1 # x = 1
551Z[2, 3, ] <- 2 # x = 2
552# last state is only used in state equation so zeros in Z
553
554T <- diag(4) # a1_t for y1, a2_t for y2, C, D
555T[1, 4] <- 1 # D affects a_t
556T[2, 4] <- 1 # D affects a_t
557Q <- diag(c(NA, NA, 0, 0))
558P1inf <- diag(4)
559model <- SSModel(Y ~ -1 + SSMcustom(Z = Z, T = T, Q = Q, P1inf = P1inf,
560  state_names = c("a1", "a2", "C", "D")), H = diag(NA, 2))
561
562updatefn <- function(pars, model) {
563  model$Q[] <- diag(c(exp(pars[1]), exp(pars[1]), 0, 0))
564  model$H[] <- diag(exp(pars[2]), 2)
565  model
566}
567
568fit <- fitSSM(model, inits = rep(-1, 2), updatefn = updatefn)
569
570fit$model$H[1]
571fit$model$Q[1]
572KFS(fit$model)
573
574}
575
576}
577\references{
578Helske J. (2017). KFAS: Exponential Family State Space Models in R,
579Journal of Statistical Software, 78(10), 1-39. doi:10.18637/jss.v078.i10
580
581Koopman, S.J. and Durbin J. (2000).  Fast filtering and
582smoothing for non-stationary time series models, Journal of American
583Statistical Assosiation, 92, 1630-38.
584
585Koopman, S.J. and Durbin J. (2012).  Time Series Analysis by State Space
586Methods. Second edition. Oxford: Oxford University Press.
587
588Koopman, S.J. and Durbin J. (2003).  Filtering and smoothing of state vector
589for diffuse state space models, Journal of Time Series Analysis, Vol. 24,
590No. 1.
591
592Shumway, Robert H. and Stoffer, David S. (2006).  Time Series Analysis and
593Its Applications: With R examples.  \cr
594}
595\seealso{
596See also \code{\link{logLik}}, \code{\link{fitSSM}},
597\code{\link{boat}}, \code{\link{sexratio}},
598\code{\link{GlobalTemp}}, \code{\link{SSModel}},
599\code{\link{importanceSSM}}, \code{\link{approxSSM}} for more examples.
600}
601