## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 6.5,
  fig.height = 4
)

## ----load---------------------------------------------------------------------
library(Stem)

## ----data---------------------------------------------------------------------
data(pm10)

str(pm10, max.level = 1)

coordinates <- pm10$coords * 1000   # from km to meters
covariates <- pm10$covariates
z <- pm10$z

dim(z)            # T x d
dim(covariates)   # (T * d) x r

## ----model--------------------------------------------------------------------
phi <- list(
  beta        = matrix(c(3.65, 0.046, -0.904), 3, 1),
  sigma2eps   = 0.1,
  sigma2omega = 0.2,
  theta       = 0.01,
  G           = matrix(0.77, 1, 1),
  Sigmaeta    = matrix(0.3, 1, 1),
  m0          = as.matrix(0),
  C0          = as.matrix(1)
)

A <- matrix(1, ncol(z), 1)   # a single latent process, loaded on every station

mod <- STEM_Model(
  z = z,
  covariates = covariates,
  coordinates = coordinates,
  phi = phi,
  A = A
)

class(mod)

## ----estimation---------------------------------------------------------------
fit <- STEM_Estimation(mod, precision = 0.01, distance = "euclidean")

round(unlist(fit$estimates$phi.hat), 5)

fit$estimates$loglik
fit$estimates$convergence.par[c("conv.log", "conv.par", "iterEM")]

## ----smoothed, fig.alt = "Smoothed latent temporal process"-------------------
plot(fit$estimates$y.smoothed, ylab = "smoothed latent state", xlab = "day")

## ----bootstrap, eval = FALSE--------------------------------------------------
# boot <- STEM_Bootstrap(fit, B = 100, distance = "euclidean")
# 
# npar <- 9
# boot.estimates <- t(vapply(boot$boot.output, function(b) {
#   p <- b$estimates$phi.hat
#   c(p$beta, p$sigma2eps, p$sigma2omega, p$theta, p$G, p$Sigmaeta, p$m0)
# }, numeric(npar)))
# 
# se <- sqrt(diag(stats::var(stats::na.omit(boot.estimates))))
# round(se, 5)

## ----next, eval = FALSE-------------------------------------------------------
# vignette("SCSTEM", package = "Stem")

## ----map, eval = FALSE--------------------------------------------------------
# vignette("function-map", package = "Stem")

