This vignette uses the model-object interface to simulate moves among the Netherlands, Spain and Sweden, following the migration example in Bosco et al. (2024). The model also includes births, deaths and people entering or leaving the study area. We build and run the model on a small sample for the sake of computational efficiency. However, MicSim can also handle larger numbers of cases. Larger models can also be run using multiple CPUs for more efficiency.
The example uses Eurostat data prepared by Claudio Bosco, Daniela Ghio and Maurizio Teobaldelli (European Commission) and Sabine Zinn (German Socio-Economic Panel, Humboldt University Berlin). For more information consult Bosco et al. (2024). We keep the data in this example as published and only adjust them where MicSim 4.0.0 requires it.
The simulation runs from 1 January 2014 to 31 December 2018 with a
maximum age of 100. The state variables record sex (sex),
country of residence (country_R) and parity
(fert, the number of children already born). State labels
follow the order of the variables in state_space(). For
example, "f/ES/2" describes a woman living in Spain with
parity two. Parity is only recorded for women aged 15 to 49, the age
range covered by the fertility data in Bosco et
al. (2024). Everyone outside that range, including children, has
the value "999", and men aged 15 to 49 have
"0". There are no transitions out of "999", so
girls who turn 15 during the four simulation years cannot give
birth.
# 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)initPopMigrExp describes the people present at the start
of the simulation. immigrPopMigrExp describes the people
who enter later, including their arrival date and their state on
arrival. Both datasets are simply loaded from within the package.
# initial population
initPop <- initPopMigrExp
head(initPop)
#> ID birthDate initState
#> 1 1 19411206 m/NL/999
#> 2 2 20070608 m/SE/999
#> 3 3 19750709 m/ES/0
#> 4 4 19220312 f/NL/999
#> 5 5 19740425 f/ES/0
#> 6 6 20110828 m/ES/999
# population of immigrants entering to virtual population over simulation time
immigrPop <- immigrPopMigrExp
head(immigrPop)
#> ID immigrDate birthDate immigrInitState
#> 1 72966 20180925 19830404 m/ES/0
#> 2 72967 20171208 20100319 f/ES/0
#> 3 72968 20151217 19910316 f/NL/0
#> 4 72969 20170105 20070602 m/NL/0
#> 5 72970 20140609 19880623 f/ES/0
#> 6 72971 20171003 19881129 m/NL/0MicSim requires valid Gregorian dates. getInDays()
returns NA for invalid dates, so we use it to find invalid
birth and arrival dates before building the model.
The example data are kept as published in Bosco et al. (2024). They were built with the date arithmetic of earlier MicSim versions, which approximated a month as 30.42 days and so produced some dates that do not exist, such as 30 February. Since version 4.0.0, MicSim works with exact calendar dates, so these dates have to be repaired first.
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)))
#> birth immigrant_birth arrival
#> 784 40 35
head(initPop$birthDate[bad_in(initPop$birthDate)])
#> [1] 19650230 19360931 19510231 19680631 19550229 20070229For the example data, we keep the recorded year and month and move an invalid day back to the last valid day of that month. For example, 29 February in a non-leap year becomes 28 February. The repaired dates are an assumption for this example.
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)))
#> [1] 0 0 0new_newborn_rule() takes a table of possible newborn
states and their probabilities. Every newborn starts with parity zero.
With inherit = 2, MicSim selects the rows that match the
mother’s country of residence, the second state variable. The sex
probabilities vary by country, so the table supplies a pair of
probabilities that add to one for each country. Use
newborn_rule() when each variable can be set or sampled
separately.
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
#> <newborn_rule>
#> state variables: 3
#> inherited from the mother: position(s) 2
#> candidate states: 6
#> m/ES/0 p = 0.5151
#> f/ES/0 p = 0.4849
#> m/NL/0 p = 0.5124
#> f/NL/0 p = 0.4876
#> m/SE/0 p = 0.5146
#> f/SE/0 p = 0.4854The package includes the rate table migrExpRates, with
one column for each rate and one row for each year of age, starting at
zero. Rates are measured per person-year. The age range covers newborns
and extends up to the oldest age band used in the simulation. We check
the dimensions and the number of missing entries before creating rate
functions.
In a typical example, you have to define the rates yourself. For
examples of how to define your own rate functions, see the Transition
rates section of the Introduction to MicSim 4.0.0 vignette:
vignette("introduction-to-new-micsim", package = "MicSim").
rates <- migrExpRates
# Worth looking at before building a model: how far do the tables reach,
# and are there gaps?
dim(rates)
#> [1] 100 30
sum(is.na(rates))
#> [1] 0rate_from_age_vector() creates one function per column.
Each function accepts age and calTime and uses
age to look up the rate. For example, the age-20 row applies from age 20
to just under 21. The lookup returns zero for missing entries or ages
outside the table, which treats the risk of the transition as zero at
those ages.
# 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)
#> [1] "mort_f_ES" "mort_f_NL" "mort_f_SE" "mort_m_ES" "mort_m_NL"
#> [6] "mort_m_SE" "fert_ES_0_1" "fert_ES_1_2" "fert_ES_2_3" "fert_ES_3_4"transition() links an origin state and a destination
state to a rate function. Here we create lists of transitions for
fertility, moves between the three countries, death and emigration.
Importantly, transition() takes the rate
function, not its name.
Each fertility transition advances a woman by one parity category
within her country of residence. For example, a first birth in Spain
moves the mother from "f/ES/0" to "f/ES/1".
The rate can vary by age, country and current parity.
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)
#> [1] 12For each pair of countries, move() changes only the
country of residence and keeps sex and parity, so one declaration covers
every combination of sex and parity. For example, "f/ES/2"
moves to "f/NL/2" when a woman of parity two moves from
Spain to the Netherlands.
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)
#> [1] 6Death and emigration take individuals to the absorbing states
"dead" and "rest", respectively. Entering
either state ends the individual’s simulated life course. For each
combination of sex and country, one mortality rate and one emigration
rate apply across all parity categories.
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)
#> [1] 12A fertility transition changes the mother’s parity. To add the child
to the population at the same event, we pass the labels of those
transitions to fertility() along with the newborn rule.
Everything above comes together in one object. Building it resolves every rate against the state space and checks its shape, so a typo in a state label is an error here rather than three minutes into a run.
Fertility is not an ordinary transition, because it brings a new
person into the population. It is added to the model as a
subsystem: fertility() names the transitions that
create a child and the rule for the child’s state, and
add_subsystem() checks both against the model.
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
#> <micsim_model>
#> state space : sex x country_R x fert = 36 transient state(s)
#> absorbing : dead (death), rest (emigration)
#> transitions : 156 (from 30 declaration(s))
#> population : 500 individual(s)
#> immigrants : 100 arrival(s)
#> horizon : 20140101 to 20181231, max age 100
#> subsystems :
#> fertility: fertility (12 birth transition(s))validate() checks rate values and stops if it encounters
an error, and lists all rates that fail, return NA or a
negative value anywhere (see documentation of validate()
for details). After a successful check, it returns the model to pass to
simulate(). We set a seed so the run can be repeated with
these settings.
result <- model |>
validate() |>
simulate(seed = 12)
result
#> <micsim_result> MicSim 4.0.0
#> 66 event(s) among 619 individual(s) (100 immigrant(s), 19 born during the run)
#> horizon: 20140101 to 20181231, max age 100
#> seed : 12
#> extensions : fertility (see $extensions)
#> reestimation: 30 transition(s), observed/expected 0.00 to 9.91 (see $reestimation, plot())
#> as.data.frame() for the population, as_long() for episodesFor reestimation, the observed/expected ratios vary widely as we only
simulate 500 people over five years, so some transitions only occur a
few times. as.data.frame() extracts the transition history.
Each recorded transition has its own row. An individual with no
transitions has one row with missing transition fields.
pop <- result |> as.data.frame()
head(pop)
#> ID birthDate initState From To transitionTime transitionAge motherID
#> 1 1 19411206 m/NL/999 <NA> <NA> <NA> NA NA
#> 2 2 20070608 m/SE/999 <NA> <NA> <NA> NA NA
#> 3 3 19750709 m/ES/0 <NA> <NA> <NA> NA NA
#> 4 4 19220312 f/NL/999 f/NL/999 dead 20150402 93.06 NA
#> 5 5 19740425 f/ES/0 <NA> <NA> <NA> NA NA
#> 6 6 20110828 m/ES/999 <NA> <NA> <NA> NA NAas_long() gives one row per episode spent in a state.
Tstart and Tstop give the dates, and
statusEntry and statusExit indicate whether
the episode’s start and end were observed. For immigrants, the first
episode starts on the recorded arrival date. Because of the model
object, as_long() does not require any arguments.
popLong <- result |> as_long()
head(popLong)
#> ID birthDate Tstart Tstop statusEntry statusExit OD ns Episode sex
#> 1 1 19411206 20140101 20181231 0 0 cens 1 1 m
#> 2 2 20070608 20140101 20181231 0 0 cens 1 1 m
#> 3 3 19750709 20140101 20181231 0 0 cens 1 1 m
#> 4 4 19220312 20140101 20150402 0 1 dead 1 1 f
#> 5 5 19740425 20140101 20181231 0 0 cens 1 1 f
#> 6 6 20110828 20140101 20181231 0 0 cens 1 1 m
#> country_R fert
#> 1 NL 999
#> 2 SE 999
#> 3 ES 0
#> 4 NL 999
#> 5 ES 0
#> 6 ES 999as_wide() puts each individual’s transitions on one row.
The numbered columns give the origin, destination, date and age for
successive transitions.
popWide <- result |> as_wide()
head(popWide)
#> ID birthDate initState ns From.1 To.1 transitionTime.1 transitionAge.1
#> 1 1 19411206 m/NL/999 0 <NA> <NA> <NA> NA
#> 2 2 20070608 m/SE/999 0 <NA> <NA> <NA> NA
#> 3 3 19750709 m/ES/0 0 <NA> <NA> <NA> NA
#> 4 4 19220312 f/NL/999 1 f/NL/999 dead 20150402 93.06
#> 5 5 19740425 f/ES/0 0 <NA> <NA> <NA> NA
#> 6 6 20110828 m/ES/999 0 <NA> <NA> <NA> NA
#> From.2 To.2 transitionTime.2 transitionAge.2
#> 1 <NA> <NA> <NA> NA
#> 2 <NA> <NA> <NA> NA
#> 3 <NA> <NA> <NA> NA
#> 4 <NA> <NA> <NA> NA
#> 5 <NA> <NA> <NA> NA
#> 6 <NA> <NA> <NA> NAsummary() reports counts and ages at transition, along
with the distribution of states at the end of observation.
result |> summary()
#> Simulated 619 individual(s), 66 event(s)
#>
#> Transitions:
#>
#> f/ES/999 -> dead m/ES/0 -> rest m/ES/999 -> dead f/NL/999 -> dead
#> 9 6 6 5
#> f/ES/0 -> f/ES/1 f/ES/1 -> f/ES/2 f/NL/0 -> rest f/ES/2 -> f/ES/3
#> 4 4 4 3
#> f/NL/0 -> f/NL/1 f/SE/999 -> dead f/ES/0 -> rest f/ES/2 -> rest
#> 3 3 2 2
#> m/ES/999 -> rest f/ES/3 -> f/ES/4+ f/ES/3 -> rest f/ES/999 -> rest
#> 2 1 1 1
#> f/NL/1 -> f/NL/2 f/NL/3 -> dead f/NL/3 -> f/NL/4+ f/NL/4+ -> rest
#> 1 1 1 1
#> f/SE/0 -> f/SE/1 f/SE/0 -> rest f/SE/1 -> f/SE/2 m/ES/0 -> dead
#> 1 1 1 1
#> m/NL/0 -> dead m/SE/0 -> rest
#> 1 1
#>
#> Age at transition, by dimension of the state space:
#> n Min. 1st Qu. Median Mean 3rd Qu. Max.
#> fert 19 24.13 28.09 30.21 30.87 32.48 45.07
#> exit: dead 26 49.05 75.13 85.67 81.53 88.62 98.30
#> exit: rest 21 2.74 21.92 29.96 29.13 35.46 69.67
#>
#> State at the end of observation:
#> final_state
#> m/ES/0 m/ES/999 f/ES/999 f/ES/0 m/NL/0 m/NL/999 m/SE/0 dead
#> 106 82 80 55 43 31 31 26
#> m/SE/999 f/ES/2 f/NL/999 rest f/ES/1 f/NL/0 f/SE/999 f/SE/0
#> 22 21 21 21 17 15 15 9
#> f/NL/1 f/ES/3 f/SE/2 f/NL/2 f/NL/3 f/SE/1 f/ES/4+
#> 6 5 4 3 3 2 1update() replaces the samples with the full starting and
immigrant populations. With cores = 2, MicSim splits the
people across two workers. Every individual draws from their own
random-number stream, so the result is the same as with
cores = 1 and the same seed. Use the same seed to repeat
the run. For a large population, the time saved by splitting the work
can outweigh the time spent starting workers and transferring data.
fullModel <- update(model, population = initPop, immigrants = immigrPop)
popParallel <- fullModel |>
simulate(seed = 34, cores = 2) |>
as.data.frame()
head(popParallel)
#> ID birthDate initState From To transitionTime transitionAge motherID
#> 1 1 19411206 m/NL/999 <NA> <NA> <NA> NA NA
#> 2 2 20070608 m/SE/999 <NA> <NA> <NA> NA NA
#> 3 3 19750709 m/ES/0 <NA> <NA> <NA> NA NA
#> 4 4 19220312 f/NL/999 f/NL/999 dead 20150203 92.90 NA
#> 5 5 19740425 f/ES/0 f/ES/0 f/ES/1 20140331 39.93 NA
#> 6 5 19740425 f/ES/0 f/ES/1 f/ES/2 20160528 42.09 NA