|
| 1 | +library(macpan2); library(tidyverse) |
| 2 | + |
| 3 | +## step 1: get a spec from the library and simulate |
| 4 | +spec = mp_tmb_library("starter_models", "sir", package = "macpan2") |
| 5 | +sim = mp_simulator(spec, 50, "infection") |
| 6 | +set.seed(1) |
| 7 | +data = (sim |
| 8 | + |> mp_trajectory() |
| 9 | + |> mutate(value = rpois(n(), value)) |
| 10 | +) |
| 11 | + |
| 12 | +## step 2: decompose beta into a baseline and a multiplier |
| 13 | +## to control scenarios about beta during forecasts |
| 14 | +spec_beta_decomp = mp_tmb_insert(spec |
| 15 | + , expressions = list(beta ~ beta0 * beta_multiplier) |
| 16 | + , default = list(beta0 = 0.2, beta_multiplier = 1) |
| 17 | +) |
| 18 | + |
| 19 | +## step 3: calibrate beta0 and gamma |
| 20 | +cal = mp_tmb_calibrator( |
| 21 | + spec_beta_decomp |
| 22 | + , data |
| 23 | + , traj = "infection" |
| 24 | + , par = c("beta0", "gamma") |
| 25 | + , default = list(beta0 = 0.25, gamma = 0.2) |
| 26 | +) |
| 27 | +mp_optimize(cal) |
| 28 | +mp_tmb_coef(cal) |
| 29 | + |
| 30 | +# step 4: create a scenario for beta, where transmission increases by |
| 31 | +# a factor of 1.2 at time 60. |
| 32 | +beta_change = data.frame(matrix = "beta_multiplier", time = 60, value = 1.2) |
| 33 | + |
| 34 | +# step 5: create a forecaster with this scneario |
| 35 | +scen = mp_forecaster(cal, forecast_period_time_steps = 50 |
| 36 | + , data = bind_rows(data, beta_change) |
| 37 | + , tv = "beta_multiplier" |
| 38 | + , outputs = "log_infection" |
| 39 | +) |
| 40 | + |
| 41 | +# step 6: plot the scenario |
| 42 | +(mp_trajectory_sd(scen, conf.int = TRUE) |
| 43 | + |> ggplot() |
| 44 | + + geom_line(aes(time, value)) |
| 45 | + + geom_ribbon(aes(time, ymax = conf.high, ymin = conf.low), alpha = 0.2) |
| 46 | + + geom_point(aes(time, value), data = data) |
| 47 | + + theme_bw() |
| 48 | +) |
0 commit comments