Nothing
## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
error = FALSE
)
## -----------------------------------------------------------------------------
# Load library
library(MicSim)
## -----------------------------------------------------------------------------
# Defining simulation horizon
startDate <- 20140101 # yyyymmdd
endDate <- 20181231 # yyyymmdd
simHorizon <- c(startDate, endDate)
# Definition of max age
maxAge <- 100
sex <- c("m", "f")
country_R <- c("NL", "ES", "SE")
fert <- c("0", "1", "2", "3", "4+", "999")
stateSpace <- state_space(sex = sex, country_R = country_R, fert = fert)
## -----------------------------------------------------------------------------
stateSpace
## ----setup--------------------------------------------------------------------
# initial population
initPop <- initPopMigrExp
head(initPop)
# population of immigrants entering to virtual population over simulation time
immigrPop <- immigrPopMigrExp
head(immigrPop)
## -----------------------------------------------------------------------------
bad_in <- function(dates) which(is.na(getInDays(dates)))
# The number of invalid dates and a few examples
c(birth = length(bad_in(initPop$birthDate)),
immigrant_birth = length(bad_in(immigrPop$birthDate)),
arrival = length(bad_in(immigrPop$immigrDate)))
head(initPop$birthDate[bad_in(initPop$birthDate)])
## -----------------------------------------------------------------------------
repair_dates <- function(dates) {
dates <- as.character(dates)
for (i in bad_in(dates)) {
year <- as.integer(substr(dates[i], 1, 4))
month <- as.integer(substr(dates[i], 5, 6))
day <- as.integer(substr(dates[i], 7, 8))
while (day > 1L &&
is.na(getInDays(sprintf("%04d%02d%02d", year, month, day)))) {
day <- day - 1L
}
dates[i] <- sprintf("%04d%02d%02d", year, month, day)
}
if (length(bad_in(dates)) > 0L) {
stop("Some dates could not be repaired by stepping the day back: ",
toString(dates[bad_in(dates)]))
}
dates
}
initPop$birthDate <- repair_dates(initPop$birthDate)
immigrPop$birthDate <- repair_dates(immigrPop$birthDate)
immigrPop$immigrDate <- repair_dates(immigrPop$immigrDate)
# Nothing left to complain about.
c(length(bad_in(initPop$birthDate)),
length(bad_in(immigrPop$birthDate)),
length(bad_in(immigrPop$immigrDate)))
## -----------------------------------------------------------------------------
newbornRule <- new_newborn_rule(
# List each possible newborn state in the model's variable order.
states = rbind(
c("m", "ES", "0"), c("f", "ES", "0"),
c("m", "NL", "0"), c("f", "NL", "0"),
c("m", "SE", "0"), c("f", "SE", "0")
),
# Sex ratios, given separately per country.
prob = c(0.5151, 0.4849,
0.5124, 0.4876,
0.5146, 0.4854),
# Inherit the second state variable, country of residence.
inherit = 2
)
newbornRule
## -----------------------------------------------------------------------------
rates <- migrExpRates
# Worth looking at before building a model: how far do the tables reach,
# and are there gaps?
dim(rates)
sum(is.na(rates))
## -----------------------------------------------------------------------------
# Turn a vector of age-specific rates into a MicSim rate function.
rate_from_age_vector <- function(vec, first_age = 0) {
vec <- as.numeric(vec)
vec[is.na(vec)] <- 0 # no data for that age means no risk
force(vec)
force(first_age)
function(age, calTime) {
i <- as.integer(age) - first_age + 1L
out <- rep(0, length(i))
within_table <- i >= 1L & i <= length(vec)
out[within_table] <- vec[i[within_table]]
out
}
}
# One rate function per column of the data, keyed by column name.
rateFn <- rates |>
as.list() |>
lapply(rate_from_age_vector)
head(names(rateFn), 10)
## -----------------------------------------------------------------------------
fertSteps <- cbind(
from = c("0", "1", "2", "3"),
to = c("1", "2", "3", "4+")
)
fertTransitions <- country_R |>
lapply(function(cty) {
lapply(seq_len(nrow(fertSteps)), function(k) {
from <- fertSteps[k, "from"]
to <- fertSteps[k, "to"]
parity <- as.integer(from)
rateName <- sprintf("fert_%s_%d_%d", cty, parity, parity + 1L)
transition(
move("fert", from = from, to = to,
where = sex == "f" & country_R == cty),
rate = rateFn[[rateName]]
)
})
}) |>
unlist(recursive = FALSE)
length(fertTransitions)
## -----------------------------------------------------------------------------
migrPairs <- expand.grid(
from = country_R,
to = country_R,
stringsAsFactors = FALSE
)
migrPairs <- migrPairs[migrPairs$from != migrPairs$to, ]
migrTransitions <- lapply(seq_len(nrow(migrPairs)), function(k) {
origin <- migrPairs$from[k]
destination <- migrPairs$to[k]
rateName <- sprintf("rate_%s_%s", origin, destination)
transition(
move("country_R", from = origin, to = destination),
rate = rateFn[[rateName]]
)
})
length(migrTransitions)
## -----------------------------------------------------------------------------
absorbingTransitions <- expand.grid(sex = sex, country_R = country_R,
stringsAsFactors = FALSE) |>
split(~ sex + country_R) |>
lapply(function(row) {
origins <- paste(row$sex, row$country_R, fert, sep = "/")
list(
transition(origins, "dead",
rateFn[[sprintf("mort_%s_%s", row$sex, row$country_R)]]),
transition(origins, "rest",
rateFn[[sprintf("emig_%s_%s", row$sex, row$country_R)]])
)
}) |>
unlist(recursive = FALSE) |>
unname()
length(absorbingTransitions)
## -----------------------------------------------------------------------------
fertTr <- moves_of("fert")
fertTr
## -----------------------------------------------------------------------------
model <- micsim_model(
state_space = stateSpace,
transitions = do.call(
transitions,
c(fertTransitions, migrTransitions, absorbingTransitions)
),
# For illustration purpose, the run is limited to the first 500 people and
# to 100 migrants. Just remove the restriction to run the whole sample,
# i.e. use `initPop` instead of `initPop[1:500, ]`.
population = initPop[1:500, ],
immigrants = immigrPop[1:100, ],
horizon = simHorizon,
max_age = maxAge,
exits = c(dead = "death", rest = "emigration")
) |>
add_subsystem(fertility(births = fertTr, newborn = newbornRule))
model
## -----------------------------------------------------------------------------
result <- model |>
validate() |>
simulate(seed = 12)
result
## -----------------------------------------------------------------------------
pop <- result |> as.data.frame()
head(pop)
## -----------------------------------------------------------------------------
popLong <- result |> as_long()
head(popLong)
## -----------------------------------------------------------------------------
popWide <- result |> as_wide()
head(popWide)
## -----------------------------------------------------------------------------
result |> summary()
## -----------------------------------------------------------------------------
fullModel <- update(model, population = initPop, immigrants = immigrPop)
popParallel <- fullModel |>
simulate(seed = 34, cores = 2) |>
as.data.frame()
head(popParallel)
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.