Skip to content

Instantly share code, notes, and snippets.

@jonnylaw
Created June 23, 2017 14:24
Show Gist options
  • Save jonnylaw/74c6ebb5135f1a26473ec75df2f2485f to your computer and use it in GitHub Desktop.
Save jonnylaw/74c6ebb5135f1a26473ec75df2f2485f to your computer and use it in GitHub Desktop.
#####################################
# Simulate Data From Regression DLM #
#####################################
regression_dlm = function(n = 6 * 24, psi, X) {
theta = matrix(NA_real_, ncol = ncol(X), nrow = n)
y = numeric(n)
V = psi[1]
W = diag(psi[2:3])
theta[1,] = rnorm(2)
FF = X
y[1] = t(FF[1,]) %*% theta[1,] + rnorm(1, 0, sqrt(V))
for (t in 2:n) {
theta[t,] = theta[t-1,] + MASS::mvrnorm(1, mu = rep(0, ncol(W)), Sigma = sqrt(W))
y[t] = t(FF[t,]) %*% theta[t,] + rnorm(1, 0, sqrt(V))
}
cbind(time = 1:n, state = theta, latency = y, covariates = X)
}
arrival_rate = rpois(6*24, lambda = 5)
nodes = rep(10, 3*24), rep(20, 3*24)
data = regression_dlm(psi = c(1.0, 4.0, 3.0), X = matrix(c(arrival_rate, nodes), ncol = 2)) %>%
as_data_frame()
names(data) = c("time", "theta1", "theta2", "latency", "arrival_rate", "nodes")
data %>%
select(-contains("theta")) %>%
gather(key, value, -time) %>%
ggplot(aes(x = time, y = value, colour = key)) +
geom_line() +
facet_wrap(~key, ncol = 1, scales = "free_y")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment