Package {MicSim}


Type: Package
Title: Performing Continuous-Time Microsimulation
Version: 4.0.0
Date: 2026-11-18
Description: Performs continuous-time microsimulation for life-science applications in demography, the social sciences and epidemiology. Individual life courses are represented as trajectories of a continuous-time, time-inhomogeneous Markov multi-state process, as described in Zinn (2014) <doi:10.34196/IJM.00105>. Waiting times between state transitions are generated by inverting the integrated transition hazard, and competing risks are resolved by the earliest of the independently drawn destination-specific waiting times.
License: GPL-2 | GPL-3 [expanded from: GPL (≥ 2)]
URL: https://github.com/bieneSchwarze/MicSim
BugReports: https://github.com/bieneSchwarze/MicSim/issues
Encoding: UTF-8
Language: en-GB
Depends: R (≥ 4.1)
Imports: graphics, grDevices, parallel, splines, stats
Suggests: dplyr, ggplot2, knitr, R.rsp, rmarkdown, testthat (≥ 3.0.0), tidyr
LazyData: true
VignetteBuilder: knitr, R.rsp
Config/testthat/edition: 3
Config/Needs/website: pkgdown
Config/roxygen2/version: 8.1.1
NeedsCompilation: no
Packaged: 2026-12-01 09:56:46 UTC; biene
Author: Sabine Zinn [aut, cre], Felix von Heusinger [ctb], Jedrzej Slowinski [ctb], Camila Weber [ctb], Claudio Bosco [ctb] (Contributed to an earlier version of one of the vignettes and its associated code.), Maurizio Teobaldelli [ctb] (Contributed to an earlier version of one of the vignettes and its associated code.)
Maintainer: Sabine Zinn <szinn@diw.de>
Repository: CRAN
Date/Publication: 2026-12-01 23:10:16 UTC

MicSim: Continuous-Time Microsimulation of Individual Life Courses

Description

In the life sciences, microsimulation focuses on individual life courses. A life course is defined by the ordered sequence of states an individual occupies over time, together with the time spent in each state before moving to the next. Simulating the life courses of individuals in a representative synthetic population allows you to study population dynamics on a very detailed scale.

MicSim represents a life course as a trajectory of a continuous-time, time-inhomogeneous Markov multi-state process. "Multi-state" means the process occupies, at every point in time, exactly one of a finite set of discrete states (for example "f/DE/1": female, German, one child). "Time-inhomogeneous" means the transition rates may change continuously with time rather than being held constant over predefined intervals such as calendar years.

Details

Rates (also called transition intensities or hazard rates) are the key input. They are not probabilities: a rate is an instantaneous risk per unit of time and may exceed one.

A rate function can use any combination of three time scales, all of which advance together:

age

time since the individual's birth

calTime

calendar time

duration

time since the last change of the state variable that the transition would change. For example, a smoking relapse rate can use the time since the person quit during the simulation.

All three are passed to rate functions in fractional years. Internally the package counts time in days since 1970-01-01: dates are whole days, while simulated events can fall at any point within a day; see getInDays().

The package is organised in three layers:

specification

a validated, inspectable model object that contains only data and computes nothing

engine

the only component with mutable state and the only one that runs the discrete-event loop

result

a value object carrying the simulated population, the model that produced it, the seed, and run diagnostics

Author(s)

Maintainer: Sabine Zinn szinn@diw.de

Authors:

Other contributors:

References

Zinn, S. (2014). The MicSim Package of R: An Entry-Level Toolkit for Continuous-Time Microsimulation. International Journal of Microsimulation, 7(3), 3-32. doi:10.34196/IJM.00105

Zinn, S. (2011). A Continuous-Time Microsimulation and First Steps Towards a Multi-Level Approach in Demography. Dissertation, University of Rostock.

See Also

MicSim-concepts for a glossary of the terms used throughout the documentation.


Concepts and notation used throughout MicSim

Description

A glossary of the terms and symbols that appear in MicSim's documentation and source code.

State space

state variable (substate)

A categorical attribute used to describe an individual in the model, with a set of possible values. For example, an education variable might take the values "none", "primary" and "secondary". Another variable might record the number of children ever born, also called parity. A state variable need not change during a person's simulated life course.

composite state

The combination of one value from each state variable, describing an individual's current situation. With variables for sex, nationality and parity, "f/DE/1" could describe a German woman with one child. MicSim joins the values with "/", in the order the variables were supplied.

transient state

A state that can be left again.

absorbing state

A state from which the model allows no further transitions. Death is a common example; leaving the study population permanently is another. In micsim_model(), a transition destination outside the transient state space is treated as absorbing. Its label need not be "dead".

role

A condition on the state variables, such as sex == "female", by which a model or a subsystem says what a state means. No label has a built-in meaning; see move().

subsystem

An additional rule for events that ordinary transitions alone cannot describe. A birth changes the mother's state but also adds a child to the population: fertility() supplies that extra action. school_enrolment() adjusts event dates to follow a specified school-enrolment calendar. Use add_subsystem() to add these rules to a model.

Random numbers

random number stream

Each individual has their own random-number stream, derived from the run's seed and the individual's ID; a newborn's stream comes from the mother's. Each time an individual's next event is scheduled, one uniform is drawn for every possible destination, also for destinations whose rate is zero or infinite.

common random numbers

A consequence of the random number streams is that results do not depend on the number of cores or on who else is simulated, and two scenarios simulated with the same seed use the same random numbers for every individual whose rates do not differ (common random numbers).

Rates and waiting times

transition rate, hazard rate, transition intensity

A measure of how quickly a particular transition can occur, written \lambda(t). In MicSim, rates are expressed per year. A rate is not a probability and can exceed one.

integrated hazard (cumulative hazard)

The rate accumulated over a period of time. If the rate stays at 2 per year for half a year, the integrated hazard is 2 * 0.5 = 1. When the rate changes over time, the calculation accounts for those changes. For example, a rate of 0.2 per year for one year, followed by 0.4 per year for another, gives an integrated hazard of 0.6.

This accumulated risk is written as \Lambda(\tau) = \int_0^{\tau} \lambda(s)\,\mathrm{d}s, where \tau is the interval's length in years. It represents the individual's total exposure to the risk of this particular transition over that interval.

waiting time (sojourn time)

How long the individual stays in the current state before a transition occurs.

inverse-transform sampling

A method for turning a random draw into a waiting time that follows the supplied rate. For an ordinary finite rate, MicSim draws a positive random threshold, then calculates when the integrated hazard reaches it. That time is the candidate waiting time. For example, with a constant rate of 2 per year and a threshold of 1, the candidate is half a year away. If the threshold is not reached within the remaining observation period, there is no candidate event in that period.

The threshold, written u, is drawn from an exponential distribution with mean one. The calculation finds \tau such that \Lambda(\tau) = u. Each draw generally gives a different threshold and hence a different waiting time.

forced transition

A transition whose rate is Inf at some point, encoding an event that happens on a known date rather than at random. Elementary-school enrolment is a common example.

Competing risks

Several transitions may be possible from the same state. For example, someone who is a former smoker might resume smoking or die. These possibilities compete because whichever happens first ends the current stay in that state.

MicSim draws a candidate waiting time for each possible destination, as if that transition were the only one possible. If the draw places relapse two years away and death five years away, MicSim schedules relapse. After relapse, it draws new candidates from the person's new state, including a new candidate for death if that transition is allowed. A school-calendar rule adjusts the relevant candidates before the earliest is selected.

The random draws for the different candidates are independent. This is part of the sampling method; it does not claim that real-world causes are unrelated.

Time scales

A transition rate can use three ways of measuring time:

age

Time since the individual's birth.

calendar time

When something happens in the study period, such as 2020 rather than 2010. A rate using calTime can therefore represent changes over historical time, such as falling mortality.

duration

Time since the last change of the state variable that the transition would change. If quitting moves someone from "current_smoker" to "former_smoker" during the simulation, a relapse rate can use duration to measure time since quitting.

All three advance together as time passes. Someone aged 35 who quit two years earlier in the simulation will be 36 with three years since quitting after another year of abstinence. Calendar time also advances by one year. If they resume smoking and later quit again, the new abstinent spell starts with duration zero. Until the first simulated change in a state variable, MicSim measures its duration from birth.

Observation scheme

episode

One uninterrupted stay in a state during observation, recorded with a start and an end date. A person who starts childless, has a first child and then remains in the one-child state until observation ends has two episodes.

left truncation

We know the individual was in a state at the start of observation but not when they entered it. Every member of the starting population is left-truncated.

right censoring

Observation ends before the state is left. Everyone still alive at the end of the simulation horizon is right-censored.

occurrence-exposure rate

The number of relevant events divided by the total time individuals were able to experience them. That time is called exposure or person-time at risk. For a first-birth rate, for example, count first births and sum the observed time spent in the eligible childless states.

Ten events during 200 person-years give 10 / 200 = 0.05 events per person-year. One person observed for two years contributes two person-years, as do two people observed for one year each. This estimates a rate, not the proportion of individuals with an event. It can be compared with the supplied rate when sufficient events and exposure are available. Sampling variation and how rates change within the estimation intervals affect this comparison.

Simulation machinery

discrete-event simulation

A simulation that processes events in time order instead of updating everyone at fixed time steps. If the next scheduled event is on 5 March, the engine advances directly to it rather than processing each intervening day. Individuals remain in their current states between events, although their ages and transition rates can change.

event queue

The list of events already scheduled but not yet processed. Each entry identifies a person, a destination state and an event time. The queue lets the engine find the next event across the whole population. A person has at most one active pending event, chosen from their competing candidates.

global clock

The date of the soonest pending event. It only ever moves forward.

Notation

Symbol Meaning Name in the code
\lambda(x) transition rate x years from now lambda
\Lambda(\tau) rate accumulated over tau years integrated_hazard
u standard-exponential draw u
\tau waiting time, in years tau_years
E number of events in a run -
N number of individuals -

Units in variable names

Many internal names end with a suffix that helps identify the value:

⁠_days⁠

Days since 1970-01-01 for dates, or elapsed days for ages and durations. Values may include fractions of a day.

⁠_years⁠

Time in fractional years, using 365.25 days per year.

⁠_ymd⁠

A date written as year, month and day without separators, for example 20201103 for 3 November 2020.

⁠_idx⁠

A state's number in the internal mapping between labels and numbers.

⁠_slot⁠

A person's row number in the internal person store.

⁠_id⁠

A person identifier used in the inputs or output, such as ID or motherID. It need not equal their row number in the store.


Add a subsystem to a model

Description

Switches on a mechanism that ordinary transitions cannot express, such as transitions that create a newborn (fertility()) or a calendar rule for when a transition takes place (school_enrolment()).

Usage

add_subsystem(model, subsystem)

Arguments

model

A micsim_model().

subsystem

A subsystem, from either fertility() or school_enrolment().

Details

Subsystems are added one at a time, and the call returns the model. Thus, a workflow can look like this:

model <- micsim_model(...) |>
  add_subsystem(fertility(births = moves_of("parity"), newborn = nb)) |>
  add_subsystem(school_enrolment(move("edu", "none", "primary"), month = 9))

Adding a subsystem compiles it against the model. That means every selector is resolved into the model's declared transitions and every parameter is checked. If there is a mistake, it is reported and names the subsystem. Two subsystems with the same name, or two that claim the same transition for the same purpose, will give an error.

Subsystems take effect in the order they were added. Their per-run state is created fresh at the start of every simulate() call, and whatever they report is returned in result$extensions, under their name.

Value

The model with the subsystem installed.

See Also

fertility(), school_enrolment(), move(), MicSim-concepts

Examples

mortality <- function(age) 0.00003 * exp(0.1 * age)
first_birth <- function(age) ifelse(age > 15 & age < 45, 0.1, 0)

model <- micsim_model(
  state_space = state_space(sex = c("male", "female"), parity = c("0", "1")),
  transitions = transitions(
    transition(move("parity", "0", "1", where = sex == "female"), first_birth),
    transition(NA, "deceased", mortality)
  ),
  population = data.frame(ID = 1:20, birthDate = "19850101",
                          initState = "female/0"),
  horizon = c(20140101, 20241231)
) |>
  add_subsystem(fertility(
    births  = moves_of("parity"),
    newborn = newborn_rule(sex = c(male = 0.515, female = 0.485),
                           parity = "0")
  ))
model


The bands, smooth or supplied rate of every transition as one data frame

Description

The bands, smooth or supplied rate of every transition as one data frame

Usage

## S3 method for class 'micsim_reestimation'
as.data.frame(
  x,
  row.names = NULL,
  optional = FALSE,
  what = c("bands", "smooth", "truth"),
  ...
)

Arguments

x

A micsim_reestimation.

row.names, optional

Ignored.

what

"bands" (default), "smooth" (the Poisson-spline fit: x, rate, lower, upper) or "truth" (the supplied rate as drawn).

...

Not used.

Value

A data frame with the columns transition, axis and group (the group's label), followed by the columns of each element's what table.


The simulated population, as a plain data frame

Description

Returns the pop data frame of a result. Includes one row per transition, plus one row with NA transition columns for each individual who never experienced a transition.

Usage

## S3 method for class 'micsim_result'
as.data.frame(x, ...)

Arguments

x

A micsim_result.

...

Not used.

Details

Use this wherever code still expects a plain pop data frame, such as an existing script, an old workflow or another package. It is the same format MicSim has always returned.

Value

The pop data frame.


Convert a result to long or wide format

Description

as_long() gives one row per episode, which is the layout event-history and survival analysis expect. as_wide() gives one row per individual.

Usage

as_long(x, ...)

## S3 method for class 'micsim_result'
as_long(x, migr = !is.null(x$model$immigrants), ...)

as_wide(x, ...)

## S3 method for class 'micsim_result'
as_wide(x, ...)

Arguments

x

A micsim_result.

...

Passed to methods.

migr

Whether immigrants' first episodes begin on their arrival date. Defaults to TRUE whenever the model includes immigrants.

Details

Neither needs arguments. The result already carries the model, and the model knows the state space, the horizon, the absorbing states and the immigrants, which is everything these two converters need.

Both take the result as their first argument, so they can be put in a pipe easily: simulate(model, seed = 234) |> as_long().

Value

A data frame.

as_long() gives one row per episode, with the columns ID, birthDate, Tstart, Tstop, statusEntry, statusExit, OD, ns, Episode, and one column per state variable (a state such as "f/DE/1" is split into columns for sex, nationality and parity). Dates use yyyymmdd format. statusEntry is 1 if the start of the episode was observed and 0 if it was left truncated; statusExit is 1 if its end was observed and 0 if it was right censored. OD says how the episode ended: the name of an absorbing state such as "dead", "cens" if it was still running when observation ended, or the values that changed, such as "0->1". ns is the number of episodes of the individual, and Episode numbers them in order.

as_wide() gives one row per individual, with the columns ID, birthDate, initState, ns (the number of transitions, 0 for someone who never moved) and numbered groups From.1, To.1, transitionTime.1, transitionAge.1, From.2, and so on. motherID is not included; join it from as.data.frame(result) by ID if you need it.

See Also

simulate.micsim_model(), MicSim-concepts


Build a transition matrix from transition patterns

Description

Expands a short description of which transitions a model allows into the full matrix that micSim() expects.

Usage

buildTransitionMatrix(allTransitions, absTransitions, stateSpace)

Arguments

allTransitions

Two-column matrix of transitions between transient states: the pattern "origin->destination" and the name of the rate function. A single transition may be given as a length-2 vector. NULL when the model has none.

absTransitions

Two-column matrix of transitions into absorbing states: the absorbing state's label and the name of the rate function. A single one may be given as a length-2 vector.

stateSpace

User-defined combinations of state-variable values, as produced by base::expand.grid(): one row per transient state and one column per variable. A vector is accepted for a single variable.

Details

Transient transitions are given as "origin->destination". Each side names the state-variable values needed to describe the change. The helper finds origins containing the values on the left and destinations containing the values on the right. Values not mentioned in the pattern must be the same before and after the transition. So in a model of sex, education and parity, "0->1" expands to a first birth for every combination of sex and education, while "f/0->f/1" restricts it to women.

Absorbing transitions are given as a state name rather than a pair, because the origin is "anywhere". "dead" makes every transient state able to reach death; a compound label such as "f/low/dead" restricts it to the states whose other variables match.

The second column of each matrix is the NAME of the function supplying the rate, as a string. Storing names rather than the functions themselves is the convention micSim() expects; it resolves each name once, in the environment it was called from.

Any label can name an absorbing state. "dead", "rest", "abroad" or "institution" are all fine, and a model may have as many as it needs. In a compound label the absorbing part is the component that is not a value of any state variable, so "f/IT/abroad" is the state "abroad", reachable from Italian women.

Value

A character matrix with one row per transient state and one column per state, holding "0" where no transition is possible and otherwise the name of the rate function.

Assumptions

The absorbing states are the columns after the transient ones, and their ORDER is the order of the absorbing states in the state space, which decides which of an individual's random numbers each destination receives. It is "dead" first and "rest" second, where present, then every other absorbing state in the order absTransitions first names it. "rest" conventionally means emigration.

A label that could be read two ways is refused: an absorbing state that is also the value of a state variable, or a compound label with no part, or more than one part, that is not a state value.

A pattern that matches nothing is not an error. It produces a matrix with no cell set, which is usually a typo in a state value; check the result with table(transitionMatrix != "0") if a model behaves unexpectedly.

Deprecated

buildTransitionMatrix() is deprecated as of MicSim 4.0.0 and will be removed in a future release. It still works, and shows a message once per R session naming its replacement: declare the transitions with transition(), move() and transitions() and pass them to micsim_model(). Set options(MicSim.show_deprecation = FALSE) to turn the message off.

See Also

micSim(), MicSim-concepts

Examples

stateSpace <- expand.grid(sex = c("m", "f"), fert = c("0", "1"))
buildTransitionMatrix(
  allTransitions = cbind("f/0->f/1", "fertRates"),
  absTransitions = cbind("dead", "mortRates"),
  stateSpace     = stateSpace
)


Convert simulation output to long format

Description

Reshapes the transitions returned by micSim() into one row per episode.

Usage

convertToLongFormat(
  pop,
  migr = FALSE,
  stateSpace = NULL,
  absStates = NULL,
  allTransitions = NULL,
  simHorizon = NULL,
  immigrPop = NULL,
  maxAge = NULL
)

Arguments

pop

The population data frame returned by micSim().

migr

Logical. If TRUE, start immigrants' first episodes at arrival and mark their entries as observed. Requires immigrPop, either supplied explicitly or recorded on pop.

stateSpace

The state space, as passed to buildTransitionMatrix(). Only its column NAMES are used, to name the state-variable columns of the result. When omitted, the names recorded by micSim() are used, which are var1, var2, ... because a transition matrix does not carry them.

absStates

The absorbing states. Taken from pop when omitted.

allTransitions

Optional transient-transition patterns in the format supplied to buildTransitionMatrix(). Only the first column, containing the patterns, is used. See Details for how patterns are matched to output labels.

simHorizon

A two-element vector c(startDate, endDate) with dates in yyyymmdd format. Taken from pop when omitted.

immigrPop

The immigrant population. Taken from pop when omitted. Needed only when migr is TRUE.

maxAge

The maximum age of the simulation, in years. Taken from pop when omitted. If neither is available, final episodes end at the simulation end without an age limit.

Details

Each row describes one uninterrupted spell in one state. Each row records its start and end dates, the transition that ended it, and flags indicating whether entry and exit were observed. Each state variable has its own column. For example, the state "f/DE/1" is split into separate columns for sex, nationality and parity.

The OD column describes how the episode ended. A transition to an absorbing state is labelled with that state's name, such as "dead". An episode still in progress when observation ends is labelled "cens". Other transitions are labelled with the values that changed. For example, "f/DE/0->f/DE/1" becomes "0->1".

Supplying allTransitions lets a SINGLE-VARIABLE pattern be reported under the user's own name. It cannot do more than that: the match is made component by component, so a pattern naming two or more variables can never equal one of the candidates and the changed-variable form is used instead.

The output can be used to select episodes in a relevant origin states and count observed exits (statusExit == 1) to the destination of interest. Episode lengths in can also be calculated Tstop - Tstart.

The population table is the first argument, so the function supports the native R pipe: pop |> convertToLongFormat(stateSpace = stateSpace).

Value

A data frame with the columns ID, birthDate, Tstart, Tstop, statusEntry, statusExit, OD, ns, Episode, and one column per state variable. Dates use yyyymmdd format. ns gives the total number of episodes for the individual; Episode numbers those episodes in start-date order.

Episode boundaries and observation flags

Left truncation. For individuals born before the simulation starts, the first episode begins at the simulation start and has statusEntry = 0: entry into their initial state was not observed during the simulation. For individuals born on or after the start date, the first episode begins at birth and has statusEntry = 1.

Immigrants. With migr = TRUE, an immigrant's first episode begins on their arrival date rather than at the start of observation, and counts as observed. Their earlier life happened elsewhere and is outside the study.

Right censoring. Anyone who has neither entered an absorbing state nor already got a censored row gets one more episode, running from their last transition to the end of observation: the end of the simulation, or the day they reach maxAge if that comes first. The simulation stops putting a person at risk at ⁠maxAge - 0.01 years⁠,

Deprecated

convertToLongFormat() is deprecated as of MicSim 4.0.0 and will be removed in a future release. It still works, and shows a message once per R session naming its replacement: use as_long() on the result of simulate.micsim_model(). Set options(MicSim.show_deprecation = FALSE) to turn the message off.

See Also

micSim(), convertToWideFormat(), MicSim-concepts

Examples

stateSpace <- expand.grid(sex = c("m", "f"), fert = c("0", "1"))
fertRates <- function(age, calTime) ifelse(age > 15 & age < 45, 0.1, 0)
mortRates <- function(age, calTime) 0.00003 * exp(0.1 * age)

tm <- buildTransitionMatrix(
  allTransitions = cbind("f/0->f/1", "fertRates"),
  absTransitions = cbind("dead", "mortRates"),
  stateSpace     = stateSpace
)

set.seed(1)
pop <- micSim(
  initPop = data.frame(ID = 1:20, birthDate = rep("19850101", 20),
                       initState = rep("f/0", 20),
                       stringsAsFactors = FALSE),
  transitionMatrix = tm,
  varInitStates  = rbind(c("m", "0"), c("f", "0")),
  initStatesProb = c(0.515, 0.485),
  maxAge = 100, simHorizon = c(20140101, 20241231),
  fertTr = "f/0->f/1", verbose = FALSE
)
head(convertToLongFormat(pop, stateSpace = stateSpace))

# pipe-friendly:
pop |> convertToLongFormat(stateSpace = stateSpace) |> head()


Convert simulation output to wide format

Description

Reshapes the population table returned by micSim() into one row per individual, with numbered columns for their recorded transitions.

Usage

convertToWideFormat(pop)

Arguments

pop

The population data frame returned by micSim().

Details

Each transition is represented by four columns: its origin state, destination state, date and age. The first transition appears in From.1, To.1, transitionTime.1 and transitionAge.1; the second appears in the corresponding .2 columns, and so on.

Transitions are numbered in their existing order within each individual, so the input rows should already be in chronological order. Individuals with fewer transitions have NA in the remaining numbered columns.

ns counts an individual's transitions. Someone who never transitioned occupies one row of pop, with NA in all four transition columns, and is reported here with ns = 0.

The output omits motherID. If parent links are needed, retain a separate table of ID and motherID from pop, then join it to the wide result by ID.

The function takes a single data frame, so it is pipe-friendly: pop |> convertToWideFormat().

Value

A data frame with one row per individual and columns ID, birthDate, initState, ns, and numbered groups of From, To, transitionTime and transitionAge.

Deprecated

convertToWideFormat() is deprecated as of MicSim 4.0.0 and will be removed in a future release. It still works, and shows a message once per R session naming its replacement: use as_wide() on the result of simulate.micsim_model(). Set options(MicSim.show_deprecation = FALSE) to turn the message off.

See Also

micSim(), convertToLongFormat(), MicSim-concepts

Examples

stateSpace <- c("m", "f")
mortRates <- function(age, calTime) 0.00003 * exp(0.1 * age)
tm <- buildTransitionMatrix(NULL, cbind("dead", "mortRates"), stateSpace)

set.seed(1)
pop <- micSim(
  initPop = data.frame(ID = 1:10, birthDate = rep("19500101", 10),
                       initState = rep("f", 10),
                       stringsAsFactors = FALSE),
  transitionMatrix = tm, maxAge = 120,
  simHorizon = c(20000101, 20401231), verbose = FALSE
)
convertToWideFormat(pop)

# convertToWideFormat() is pipe-friendly:
pop |> convertToWideFormat()


Add a child when a birth transition occurs

Description

Creates a subsystem for add_subsystem(): whenever one of the births transitions happens, a child is added to the population, with the mother recorded and a state drawn from the newborn rule.

Usage

fertility(births, newborn, mothers = NULL, name = "fertility")

Arguments

births

Declared transitions that create a child: a move() or moves_of() selector, a list of them, or a character vector of transition labels such as "female/0->female/1".

newborn

The state a child is born into: a newborn_rule(), or a table-form rule from new_newborn_rule().

mothers

Optional condition on the state variables, e.g. sex == "female". When given, every birth transition must start in a state satisfying it, or the model is refused.

name

The subsystem's name in the model and in result$extensions.

Details

The births themselves are ordinary transitions with ordinary rates, usually a parity variable going up by one:

transition(move("parity", "0", "1", where = sex == "female"), first_birth)

fertility() only says which of those transitions create a child. Nothing about it depends on what the states are called: there is no reserved label for women. Whoever has a birth transition is a mother. If you want that checked, give mothers, and every birth transition must start in a state satisfying it.

At each birth the subsystem

  1. draws the newborn's state from newborn, given the state the mother has just moved INTO;

  2. registers the child, born at the event's date, with motherID set and every duration clock starting at birth;

  3. schedules the child's first event.

The result's pop then carries a motherID column.

Value

A subsystem, for add_subsystem().

Report

After a run, result$extensions[[name]] holds

n_births

the number of children born during the run;

births

one row per birth: motherID, childID, date (yyyymmdd), motherAge (years, two decimals), transition (the mother's birth transition, "from -> to") and childState (the state the child was born into);

by_transition

births per birth transition, a named integer vector that lists transitions without births as zero;

by_child_state

births per state of the newborn.

After a parallel run the identifiers are those of pop.

See Also

add_subsystem(), newborn_rule(), moves_of()

Examples

fertility(
  births  = moves_of("parity"),
  newborn = newborn_rule(sex = c(male = 0.515, female = 0.485),
                         parity = "0"),
  mothers = sex == "female"
)


Age in days between two dates

Description

The whole number of days between a birth date and a reference date, both written as yyyymmdd.

Usage

getAgeInDays(currDate, birthDate)

Arguments

currDate

Reference date(s), yyyymmdd.

birthDate

Birth date(s), yyyymmdd, recycled against currDate.

Details

The result is in days. Convert it to years (⁠/ 365.25⁠) only when you need the age on the scale a rate function expects. The age reported in the simulation output is also years on that scale (days / 365.25, rounded to two decimals). Event dates, in contrast, are never put on the year scale: they go through the exact calendar in getInDateFormat().

Value

Integer vector of days. Negative when currDate is before birthDate; this is not treated as an error here.

See Also

getInDays()

Examples

getAgeInDays(20200826, 19800605)

First day of a calendar month, as a day count

Description

The day count of the first day of month in year.

Usage

getFirstDayOfMonth(year, month)

getInDays_my(year, month)

Arguments

year, month

integer vectors, recycled against each other; month in 1..12.

Details

Used to pin a forced school-enrolment event to a chosen month. The engine works out when the event would otherwise fall, then moves it to the first day of the enrolment month.

getInDays_my() is an old alias of getFirstDayOfMonth(), should not be used anymore.

Value

integer vector of days since 1970-01-01 or NA where year or month is not a whole number, or month is not between 1 and 12.

Deprecated

getInDays_my() is deprecated as of MicSim 4.0.0 and will be removed in a future release. It still works, and shows a message once per R session naming its replacement, getFirstDayOfMonth(), which takes the same arguments. Set options(MicSim.show_deprecation = FALSE) to turn the message off.

See Also

getInDays(), getInDateFormat()

Examples

getFirstDayOfMonth(2020, 9)
getInDateFormat(getFirstDayOfMonth(2020, 9))   # 20200901

Convert a day count back to a yyyymmdd date

Description

The inverse of getInDays(): turns whole days since 1970-01-01 back into a calendar date written as yyyymmdd.

Usage

getInDateFormat(days)

Arguments

days

numeric vector of days since 1970-01-01.

Details

A fractional day count is first floored to the whole day that contains it (see as_whole_days()), so the result is always a real date.

Value

integer vector of yyyymmdd dates.

See Also

getInDays() for the inverse.

Examples

getInDateFormat(18500)
18500 |> getInDateFormat()

Convert a yyyymmdd date to a day count

Description

Turns calendar dates written as yyyymmdd into whole days since 1970-01-01, which is the scale the engine works on. This is how you usually bring dates into a MicSim model.

Usage

getInDays(yyyymmdd)

Arguments

yyyymmdd

A vector of dates as yyyymmdd (numeric, character or factor). Alternatively, a Date vector, which is passed through.

Details

Accepts numeric, character, factor or Date input. An input that is not a real calendar date (for example 20210229, which is not a leap year) becomes NA.

Validity is checked by inversion. The date is turned into a day count and back again. When that round trip returns the original date, the date is valid.

Value

Integer vector of days since 1970-01-01, negative before it, and NA for any input that is not a real calendar date.

See Also

getInDateFormat() for the inverse.

Examples

getInDays(20200826)
getInDays(20210229)   # not a real date: NA


Calendar year, month, and day of a day count

Description

A fractional day count is floored to the day that contains it; see as_whole_days().

Usage

getYear(days)

getMonth(days)

getDay(days)

Arguments

days

numeric vector of days since 1970-01-01.

Value

integer vector.

Examples

getYear(18500); getMonth(18500); getDay(18500)

Immigrant population data for the migration-flow examples

Description

Entrants arriving after the simulation start, used in the migration-flow vignette.

Usage

immigrPopMigrExp

Format

immigrPopMigrExp

A data frame with 3758 rows and 4 columns:

ID

individual identifier

immigrDate

immigration date

birthDate

birth date

immigrInitState

initial state of the individual, as per the state space


Initial population data for the migration-flow examples

Description

Starting population used in the migration-flow vignette.

Usage

initPopMigrExp

Format

initPopMigrExp

A data frame with 72965 rows and 3 columns:

ID

individual identifier

birthDate

birth date

initState

initial state of the individual, as per the state space


Run a continuous-time microsimulation

Description

Simulates individual life courses as sequences of changes between states. This is the classic interface, which specifies transitions and their rate functions in a transition matrix.

Usage

micSim(
  initPop,
  immigrPop = NULL,
  transitionMatrix,
  absStates = NULL,
  fixInitStates = c(),
  varInitStates = c(),
  initStatesProb = c(),
  maxAge = 99,
  simHorizon,
  fertTr = c(),
  monthSchoolEnrol = c(),
  verbose = TRUE
)

Arguments

initPop

Data frame describing the starting population, with columns ID, birthDate and initState, in that order. Birth dates are yyyymmdd.

immigrPop

Data frame describing individuals who enter the population after the simulation starts, with columns ID, immigrDate, birthDate and immigrInitState. NULL when the model has no immigration.

transitionMatrix

Character matrix as produced by buildTransitionMatrix(): rows are transient states, columns are all states, and a cell holds "0" or the name of a rate function.

absStates

The absorbing states. Accepted for backward compatibility but no longer needed: they are read from the matrix's column names, which removes the risk of the two disagreeing.

fixInitStates

Integer positions of the state variables a newborn inherits from its mother.

varInitStates

Matrix of admissible newborn states, one row per candidate and one column per state variable.

initStatesProb

Weights for the rows of varInitStates. They must sum to one within each combination of inherited attributes.

maxAge

Sharp maximum age, in years.

simHorizon

Length-2 vector c(startDate, endDate), yyyymmdd.

fertTr

Transitions that create a newborn, as "origin->destination" patterns. Empty when the model has no fertility.

monthSchoolEnrol

Month, 1 to 12, on whose first day elementary-school enrolment takes place. Empty when the model does not track school enrolment.

verbose

Report progress through message(), which can be suppressed or captured. Pass FALSE for a silent run.

Details

This is the classic interface based on a transition matrix whose cells name rate functions. micsim_model() provides an alternative interface that keeps the model inputs together and accepts functions directly. Both use the same simulation engine.

The state space contains all possible combinations of the model's state variables, with each state written as its values joined by forward slashes: "f/DE/1" for a German woman with one child. The absorbing states are the columns of transitionMatrix after the transient ones; any label works.

Labels with a meaning. This interface keeps three conventions of MicSim 3.0.0, because it has no other way to be told: only states containing "f" can give birth through fertTr; with monthSchoolEnrol, an allowed transition counts as enrolment if it changes one state variable from "no" to "low" and leaves the other values as they were; and buildTransitionMatrix() puts "dead" and "rest" first among the absorbing states.

Rates are functions of age, calTime and duration, in any subset, all in fractional years. They are transition intensities, not probabilities: a rate may exceed one. They must be vectorised, because the simulation integrates them numerically.

Reproducibility. micSim() takes no seed. It draws the seed of the run from the random stream the caller has set up (one draw), so set.seed(234) immediately before the call makes a run reproducible. Every individual then draws from their own random-number stream, as described in simulate.micsim_model().

Value

A data frame with one row per transition, plus one row per individual who never experienced one, and the columns ID, birthDate, initState, From, To, transitionTime and transitionAge, with motherID added when the model has fertility.

Reproducibility across versions

The return value keeps the same columns, row semantics and ordering. Some values differ from earlier releases, most importantly because dates are now computed on the exact civil calendar. Random numbers are now drawn per individual, so the same seed gives a different, equally valid population than in MicSim 3.0.0.

Deprecated

micSim() is deprecated as of MicSim 4.0.0 and will be removed in a future release. It still works, and shows a message once per R session naming its replacement: build the model with micsim_model() (and add_subsystem()) and run it with simulate.micsim_model(). Set options(MicSim.show_deprecation = FALSE) to turn the message off.

References

Zinn, S. (2014). The MicSim Package of R: An Entry-Level Toolkit for Continuous-Time Microsimulation. International Journal of Microsimulation, 7(3), 3-32. doi:10.34196/IJM.00105

See Also

buildTransitionMatrix(), MicSim-concepts

Examples

# A mortality-only model: five individuals, one absorbing state.
stateSpace <- c("m", "f")
attr(stateSpace, "name") <- "sex"

mortRates <- function(age, calTime) {
  0.00003 * exp(ifelse(calTime <= 2020, 0.1, 0.097) * age)
}

initPop <- data.frame(
  ID        = 1:5,
  birthDate = c("19301231", "19990403", "19561015", "19911111", "19650101"),
  initState = c("f", "m", "f", "m", "m"),
  stringsAsFactors = FALSE
)

transitionMatrix <- buildTransitionMatrix(
  allTransitions = NULL,
  absTransitions = cbind("dead", "mortRates"),
  stateSpace     = stateSpace
)

set.seed(234)
pop <- micSim(
  initPop          = initPop,
  transitionMatrix = transitionMatrix,
  absStates        = "dead",
  maxAge           = 120,
  simHorizon       = c(20000101, 21001231),
  verbose          = FALSE
)
head(pop)


Run a microsimulation on several cores

Description

Splits the population across processor cores, runs micSim() on each, and recombines the results into one pop data frame.

Usage

micSimParallel(
  initPop = NULL,
  immigrPop = NULL,
  initPopList = list(),
  immigrPopList = list(),
  transitionMatrix,
  absStates = NULL,
  varInitStates = c(),
  initStatesProb = c(),
  fixInitStates = c(),
  maxAge = 99,
  simHorizon,
  fertTr = c(),
  monthSchoolEnrol = c(),
  cores = 1L,
  seeds = 1254L,
  verbose = TRUE
)

Arguments

initPop

Data frame describing the starting population; see micSim().

immigrPop

Data frame describing immigrants, or NULL.

initPopList, immigrPopList

Pre-computed splits, one list element per core. Supply these to control which individuals go to which core; otherwise the split is made automatically into near-equal chunks. Immigrants assigned to a core without a starting population are simulated on the first core that has one.

transitionMatrix, absStates, varInitStates, initStatesProb, fixInitStates

As in micSim().

maxAge, simHorizon, fertTr, monthSchoolEnrol

As in micSim().

cores

Number of processor cores to use.

seeds

Integer seed of the run, used by every worker.

verbose

Report progress through message().

Details

Individuals are independent of one another in MicSim's model, so simulating them in separate groups and concatenating the results is exactly equivalent to simulating them together.

Reproducibility. Every worker runs with the seed seeds, and every individual draws from their own L'Ecuyer-CMRG stream derived from it and their ID. The life courses are therefore the same on any number of cores and under any split; only the identifiers of newborns depend on the split (see Identifiers).

Identifiers. Each worker assigns newborn IDs starting above the largest ID in its own group, so different workers can assign the same ID to different newborns. When the results are combined, newborns receive consecutive IDs starting one above the larger of the highest supplied ID and the total number of people in the starting and immigrant populations. All supplied IDs are preserved.

Rate functions are exported to the workers along with everything else visible where micSimParallel() was called.

Value

The same data frame micSim() returns, for the whole population.

Deprecated

micSimParallel() is deprecated as of MicSim 4.0.0 and will be removed in a future release. It still works, and shows a message once per R session naming its replacement: build the model with micsim_model() and run it with simulate(model, seed = , cores = ) (simulate.micsim_model()). Set options(MicSim.show_deprecation = FALSE) to turn the message off.

See Also

micSim(), MicSim-concepts


Define a simulation model

Description

Builds the object that says everything about a model: its states, its transitions, who starts in it and how long it runs. Mechanisms that ordinary transitions cannot express, such as fertility or a school calendar, are added afterwards with add_subsystem().

Usage

micsim_model(
  state_space,
  transitions,
  population,
  horizon,
  max_age = 100,
  immigrants = NULL,
  exits = NULL,
  ...
)

Arguments

state_space

User-defined state variables, from state_space().

transitions

Allowed transitions, from transitions().

population

Data frame describing the starting population, with columns ID, birthDate and initState, in that order. Use unique whole-number IDs within R's integer range, birth dates in yyyymmdd format (numeric, character, Date), and full transient-state labels.

horizon

Two numeric dates in yyyymmdd format, c(start, end), with start before end.

max_age

Maximum age for scheduling transitions, in years; default 100.

immigrants

Data frame with columns ID, immigrDate, birthDate and immigrInitState, or NULL.

exits

Optional named character vector saying what kind of exit each absorbing state is: "death", "emigration" or "other", e.g. c(deceased = "death", abroad = "emigration"). Absorbing states left out are of unspecified kind. Nothing in core MicSim depends on it, but subsystems that must know whether someone died do.

...

Not used.

Details

Building a model enumerates the state space, resolves transitions and checks population formats, dates and identifiers. It also checks rate argument names and, where short test evaluations succeed, the number of values returned. Subsystem-specific checks occur in add_subsystem(). These checks cannot establish that all rates are suitable for every input encountered during a run. validate() provides an additional screen for missing and negative rate values on a grid.

Absorbing states are the destinations of transitions that are not transient states. Call them anything: "dead", "deceased", "tot" and "abroad" are all fine, and a model may have any number of them, including none (then max_age alone ends each life course). If something must tell a death from another kind of exit, say so in exits.

Nothing here consumes random numbers. A model can be built, printed, saved with saveRDS() and simulated repeatedly, and every run from the same seed gives the same result. A model saved under one MicSim version and simulated under another gives a warning; rebuild it with micsim_model() if the run fails or looks wrong.

Value

A micsim_model containing the supplied inputs and internal codec (state mapping), registry (transition-rate lookup) and micsim_version (the MicSim version that built the model).

See Also

state_space(), transitions(), add_subsystem(), validate(), simulate.micsim_model(), MicSim-concepts

Examples

mortality   <- function(age) 0.00003 * exp(0.1 * age)
first_birth <- function(age) ifelse(age >= 18 & age < 45, 0.10, 0)

# The birth is declared once and reused by the fertility subsystem
birth <- move("parity", from = "0", to = "1", where = sex == "female")

trans <- transitions(
  transition(birth, rate = first_birth),
  transition(from = NA, to = "deceased", rate = mortality)
)

model <- micsim_model(
  state_space = state_space(sex = c("female", "male"), parity = c("0", "1")),
  transitions = trans,
  population = data.frame(
    ID        = 1:20,
    birthDate = rep("19850101", 20),
    initState = rep("female/0", 20)
  ),
  horizon = c(20140101, 20241231),
  max_age = 100,
  exits   = c(deceased = "death")
) |>
  add_subsystem(fertility(
    births  = birth,
    newborn = newborn_rule(sex = c(male = 0.515, female = 0.485), parity = "0")
  ))
model


Transition-rate data for the migration-flow examples

Description

Data used to construct transition rates in the migration-flow vignette.

Usage

migrExpRates

Format

migrExpRates

A data frame with 100 rows and 30 columns:

mort_f_ES

mortality rate for females from Spain

mort_f_NL

mortality rate for females from the Netherlands

mort_f_SE

mortality rate for females from Sweden

...


Select the transitions that change one state variable

Description

move() describes a change from one value of a state variable to another, keeping every other variable fixed. Use it in transition() to declare transitions, or in a subsystem to select which transitions it acts on, as in school_enrolment(move("edu", "none", "primary")).

moves_of() selects declared transitions in which var is the only state variable that changes. Subsystems use it to identify relevant transitions, for example fertility(births = moves_of("parity")). It does not declare new transitions.

Usage

move(var, from, to, where = NULL)

moves_of(var, where = NULL)

Arguments

var

Name of the state variable that changes, as a string.

from, to

Its origin and destination values, as different strings.

where

Optional condition on the origin state, written in terms of the state variables, e.g. sex == "female" & nat == "DE".

Details

Suppose the state variables are sex = c("male", "female") and edu = c("none", "primary"). Then move("edu", "none", "primary") describes both "male/none" -> "male/primary" and "female/none" -> "female/primary".

where restricts the origin states. For example, move("parity", "0", "1", where = sex == "female") selects that parity change only for female origin states. The condition is evaluated against the model's table of transient states when the selector is resolved.

Value

A selector object. move() can be used in transition() or by a subsystem; moves_of() can only select declared transitions.

See Also

transition(), add_subsystem(), MicSim-concepts

Examples

# Entry into primary education, regardless of other state variables.
move("edu", from = "none", to = "primary")

# The change from parity 0 to 1 applies only to female origin states.
move("parity", from = "0", to = "1", where = sex == "female")

# Treat all declared changes in parity alone as births.
fertility(
  births = moves_of("parity"),
  newborn = newborn_rule(sex = c(female = 0.5, male = 0.5),
                         parity = "0")
)


Define how a newborn's state is assigned

Description

Builds the rule that decides which state a child occupies at birth. The rule defines which state variables the child takes from its mother and how the remaining ones are drawn.

Usage

new_newborn_rule(states, prob, inherit = integer(0))

Arguments

states

Character matrix of admissible newborn states. A data frame is accepted and converted.

prob

Numeric weights, one per row of states.

inherit

Integer column positions the newborn takes from its mother. When empty nothing is inherited.

Details

states is the table of states a newborn can take. It has one row per possible combination and one column per state variable of the model. The columns follow the model's state variables in order. prob assigns a probability between 0 and 1 for each row to be selected. inherit names the column positions the child takes from its mother.

At a birth the rule keeps only the rows that agree with the mother on every inherited position, and draws one of them with the corresponding probability. When nothing is inherited, it draws from the whole table to decide a newborn's state.

In the example from ?micSim, the state variables are sex, nationality and parity. Nationality is inherited and sex is drawn with a sex ratio that differs by nationality; parity is "0".

states = rbind(c("m","DE","0"), c("f","DE","0"),
               c("m","AT","0"), c("f","AT","0"),
               c("m","IT","0"), c("f","IT","0"))
prob    = c(0.515, 0.485,  0.515, 0.485,  0.515, 0.485)
inherit = 2

A child of an Austrian mother can only be row 3 or row 4, and those two weights sum to one. This is checked by the validation separately for each unique inherited attribute.

Value

An object of class newborn_rule.

Assumptions

The weights within each inherited group must sum to one within PROB_TOL. A table whose weights do not sum to one in some group returns an error, because a mother in that group would otherwise have no well-defined newborn distribution.

A state variable that is neither inherited nor allowed to vary in states takes the single value it has in every row. Parity for example will usually have every newborn starting at "0".

See Also

newborn_rule() for the per-variable form, fertility(), assign_newborn_state(), MicSim-concepts

Examples

rule <- new_newborn_rule(
  states = rbind(c("m", "DE", "0"), c("f", "DE", "0"),
                 c("m", "AT", "0"), c("f", "AT", "0")),
  prob    = c(0.515, 0.485, 0.515, 0.485),
  inherit = 2L
)
rule


Say what state a child is born into

Description

Gives, for every state variable of the model, how a newborn's value is settled: fixed, drawn, or taken from the mother. For fertility().

Usage

newborn_rule(...)

from_mother()

Arguments

...

One named entry per state variable.

Details

Each state variable gets it's own argument of the same name:

a single value

something every child gets, e.g. parity = "0"

a named vector of probabilities

the value is drawn, e.g. sex = c(male = 0.515, female = 0.485). The probabilities must sum to one.

from_mother()

the child takes the mother's value, e.g. nat = from_mother(). The mother's value is the one she holds right after the birth transition.

Drawn variables are drawn independently of one another. When a probability must depend on an inherited value – e. g. a sex ratio that differs by nationality – use the table form, new_newborn_rule().

The rule is checked against the model when the subsystem is added. To pass, every state variable needs an entry, and every value must exist.

Value

An object of class micsim_newborn_spec.

See Also

fertility(), new_newborn_rule()

Examples

newborn_rule(sex = c(male = 0.515, female = 0.485),
             nat = from_mother(),
             parity = "0")


Plot supplied against recovered transition rates

Description

Draws one figure per declared transition. The left panel shows the rate the model was given; the right panel shows the rate recovered from the simulated population (reestimate()): the occurrence/exposure rate of each band as a point whose size reflects its person-years, with its exact 95% Poisson interval, the smooth Poisson-spline fit with its 95% band, and the supplied rate as a dashed reference. Both panels share the x and the y axis.

Usage

## S3 method for class 'micsim_reestimation'
plot(
  x,
  which = NULL,
  log = NULL,
  ask = NULL,
  panels = c("both", "supplied", "recovered"),
  legend = NULL,
  layout = TRUE,
  style = NULL,
  ...
)

## S3 method for class 'micsim_result'
plot(
  x,
  which = NULL,
  log = NULL,
  ask = NULL,
  panels = c("both", "supplied", "recovered"),
  legend = NULL,
  layout = TRUE,
  style = NULL,
  ...
)

## S3 method for class 'micsim_rate_check'
plot(
  x,
  log = NULL,
  panels = c("both", "supplied", "recovered"),
  legend = NULL,
  layout = TRUE,
  style = NULL,
  ...
)

Arguments

x

A micsim_reestimation, a micsim_result, or one element of a reestimation.

which

Transitions to draw: positions or labels (the names of the reestimation). All by default.

log

TRUE or FALSE to force a logarithmic or linear y axis; NULL decides per transition.

ask

Wait between figures? Defaults to TRUE on an interactive device when there is more than one.

panels

"both" (default), "supplied" or "recovered": which panels to draw.

legend

Draw the legend? NULL (default) means TRUE in the full layout and FALSE with layout = FALSE.

layout

TRUE (default) arranges each figure on its own page. FALSE draws the panels into the figure regions already set up, e.g. with par(mfrow = ).

style

Named list of colours overriding the defaults: groups (up to three), truth, points, smooth, forced, grid, axis, muted.

...

Graphical arguments main and sub (one per figure, recycled), xlab, ylab, xlim, ylim (in rate units, also on a log axis) and cex. Others are ignored with a warning.

Details

If the rate depends on a second time scale (age and calendar time, for example), each period of that scale has its own colour in both panels, and the supplied rate is drawn at the middle of each period.

The dashed reference in the right panel is the supplied rate itself when it depends only on the time scale on the x axis. Otherwise it is the supplied rate averaged over the exposure in each band, which is exactly what the band estimate estimates.

The y axis is logarithmic when the values span more than 2.5 orders of magnitude, unless log says otherwise. Points beyond the axis are marked by a triangle at the edge. Shaded regions are where the rate is infinite (a forced transition); there is no hazard to smooth there, and the band estimates reflect the timing rule rather than a rate.

Several figures are drawn in turn; on an interactive device the plot waits for confirmation between them (ask). To keep them, draw to a file device, e.g. pdf("rates.pdf", width = 11, height = 5), or select one with which. A size of about 11 by 5 inches suits them.

Before drawing, the size of the device is checked. If the full layout does not fit, a compact one without legend, subtitle and notes is used. If that does not fit either, an error says so and nothing is drawn.

Use panels and layout = FALSE to draw into a grid of your own, e.g. par(mfrow = c(2, 2)); plot(result, which = 1:4, panels = "recovered", layout = FALSE).

Value

x, invisibly.

See Also

reestimate(), simulate.micsim_model()

Examples

mort <- function(age) 0.0005 * exp(0.07 * age)
model <- micsim_model(
  state_space(sex = c("m", "f")),
  transitions(transition(NA, "dead", mort)),
  data.frame(ID = 1:500, birthDate = "19400101", initState = "f"),
  horizon = c(20000101, 20291231)
)
result <- simulate(model, seed = 1)
plot(result)


Print a simulation model

Description

Provides an overview of the model, including the number of states and transitions, the starting population, the simulation period, and any optional mechanisms enabled.

Usage

## S3 method for class 'micsim_model'
print(x, ...)

Arguments

x

A micsim_model.

...

Not used; present for compatibility with the print() generic.

Value

x, invisibly. Called for the side effect of printing.


Print one transition's reestimation

Description

Print one transition's reestimation

Usage

## S3 method for class 'micsim_rate_check'
print(x, ...)

Arguments

x

A micsim_rate_check.

...

Not used.

Value

x, invisibly.


Print a reestimation

Description

One line per declared transition including events, person-years at risk, expected events under the supplied rate, and observed / expected.

Usage

## S3 method for class 'micsim_reestimation'
print(x, ...)

Arguments

x

A micsim_reestimation.

...

Not used.

Value

x, invisibly.


Print a simulation result

Description

Print a simulation result

Usage

## S3 method for class 'micsim_result'
print(x, ...)

Arguments

x

A micsim_result.

...

Not used; present for compatibility with the print() generic.

Value

x, invisibly. Called for the side effect of printing.


Print a result summary

Description

Print a result summary

Usage

## S3 method for class 'summary.micsim_result'
print(x, ...)

Arguments

x

A summary.micsim_result.

...

Not used.

Value

x, invisibly.


Old transition-rate data for the MDD example, by single year of age

Description

This dataset is superseded by rates_mdd_groups. Data used to construct transition rates for the MDD example.

Usage

rates_mdd

Format

rates_mdd

A data frame with 49 rows and 17 columns:

age

age of the individual

incidence_lo_m

incidence rate, low education, men

cf_incidence_lo_f

counterfactual incidence rate, low education, women

...

Source

https://doi.org/10.1093/eurpub/ckae066


Age-group transition rates for the Educational Inequalities in Depression Vignette

Description

Annual rates of developing (incidence) and recovering from (remission) major depressive disorder (MDD), by education level, sex and age group, as estimated in Lepe et al. (2024).

Usage

rates_mdd_groups

Format

rates_mdd_groups

A data frame with 10 rows and 17 columns. All rates are annual rates, given as proportions:

age

Midpoint of age group in years

incidence_lo_m

incidence rate, low education, men

cf_incidence_lo_f

counterfactual incidence rate, low education, women

...

Source

https://doi.org/10.1093/eurpub/ckae066


Reestimate a model's transition rates from its simulated population

Description

Estimates every transition rate of the model from the life courses it produced and compares each estimate with the rate that was supplied. simulate() does this automatically and stores the result as result$reestimation. You can call reestimate() to redo it with other settings. plot() supplies comparison plots.

Usage

reestimate(x, ...)

## S3 method for class 'micsim_result'
reestimate(x, width = NULL, groups = 3L, axis = NULL, ...)

Arguments

x

A micsim_result.

...

Not used.

width

Width of the bands, in years. NULL (the default) uses 1 year, or a finer width when the observed range is shorter than ten years.

groups

Maximum number of periods of a second time scale, from 1 to 3. Fewer are used when there are few events (each period needs at least 150 events) or when the rate changes by less than 25% along the second scale.

axis

The main time scale for rates that depend on more than one: "age", "calTime" or "duration". It sets both the scale the bands are laid along and the x axis of the plot. A single value applies to every transition whose rate uses that scale. A named vector can set it per transition, with names as in the result. By default the first of age, duration, and calendar time that the rate uses.

Details

For each transition declared with transition():

Rates with more than one time scale. Suppose a mortality rate depends on age and calendar time, and age is its main time scale. The band estimate at age 60 then reflects everyone who was 60 during the run, in whatever calendar years that happened. So it is compared with the supplied rate averaged over those people, not with the rate in one particular year. The plot also shows the 10th to 90th percentile of the supplied rate among them, so you can see how much it varies with calendar time.

If that variation is large (more than 25%), the whole comparison is also done separately for up to three periods of calendar time, each with the same number of person-years, so the plot shows how the rate changes over time.

Rates that are Inf somewhere (forced transitions, such as school enrolment at a set age) have no finite rate to estimate. They are reported with their bands, but without a smooth curve or an expected count.

The band estimates treat the rate as constant within each band. They therefore differ from the supplied rate by Monte Carlo error, which the confidence intervals show, and by however much the rate changes within a band.

Value

An object of class micsim_reestimation. This is a named list with one element per declared transition. Each element holds

label, title

the transition as text and as a plot title.

axis, group_by, groups

the main time scale, the second time scale the bands are grouped by (or NA), and a data frame with one row per period of the second scale: its limits (lo, hi), its person-year-weighted average (at) and the label used in the plot. Without a second scale there is a single row.

bands

one row per band and group: group, lower, upper, mid, events, exposure, rate, ci_lower, ci_upper, expected.

smooth

the fitted curve: group, x, rate, lower, upper.

truth

the supplied rate on a fine grid: group, x, rate, and, for a rate that also depends on another time scale, lower and upper, the 10th and 90th percentile over the people at risk (rate is then their mean).

events, exposure, expected, ratio, ratio_ci

totals, observed / expected, and its exact 95% Poisson interval. If the simulation reproduces the supplied rate, the interval covers 1 in at least 95% of runs.

forced, notes

whether the rate is Inf somewhere, and anything the plot should say.

as.data.frame() stacks the bands of all transitions.

See Also

plot.micsim_reestimation(), simulate.micsim_model()

Examples

mort <- function(age) 0.0005 * exp(0.07 * age)
model <- micsim_model(
  state_space(sex = c("m", "f")),
  transitions(transition(NA, "dead", mort)),
  data.frame(ID = 1:300, birthDate = "19500101", initState = "f"),
  horizon = c(20000101, 20291231)
)
result <- simulate(model, seed = 1)
result$reestimation
head(as.data.frame(result$reestimation))


Adjust transitions to the school enrolment calendar

Description

A subsystem for add_subsystem(): every time one of the given transitions is drawn, its date is moved to the first day of month – in the same year if the drawn date falls in or before that month, otherwise in the next year.

Usage

school_enrolment(transition, month, name = "school_enrolment")

Arguments

transition

Which declared transition(s) the rule applies to: an move() or moves_of() selector, a list of them, or transition labels.

month

The enrolment month, a whole number from 1 to 12.

name

The subsystem's name in the model and in result$extensions.

Details

Elementary-school enrolment is written in two halves. The rate says WHEN in a person's life the transition happens, e.g., function(age) ifelse(age == 6, Inf, 0), an Inf rate that makes the transition forced: it happens on that date rather than at a random one. This subsystem then says on WHICH calendar day it happens.

So with month = 9, a child whose rate fires in March 2018 starts school on 1 September 2018, and one whose rate fires in October 2018 on 1 September 2019.

Which transition is the enrolment is up to the model: name it, e.g. move("edu", "none", "primary"). No education label has a meaning of its own, so a model can call its levels anything, and can have more than one education variable.

The date is moved before competing risks are resolved: the enrolment competes with every other transition at its calendar date, so a child who would die or emigrate before 1 September does so. A date that the rule would move into the past – a child scheduled after the 1st of the enrolment month with an enrolment due now – is placed at the present instead.

Value

A subsystem, for add_subsystem().

Report

After a run, result$extensions[[name]] holds

n_enrolments

the number of enrolments during the run;

enrolments

one row per enrolment: ID, date (yyyymmdd, the enrolment date), age (years, two decimals), transition ("from -> to"), drawnDate (the date the rate alone produced) and shiftDays (enrolment date minus drawn date: positive when the enrolment was postponed to the next enrolment month, negative when it was brought forward to the first day of the month it was drawn in);

n_at_present

enrolments the rule would have moved into the past, placed on the day the child was scheduled instead;

by_transition

enrolments per enrolment transition;

by_month

enrolments by calendar month of the drawn date, "01" to "12": how much the calendar rule moved.

See Also

add_subsystem(), move()

Examples

school_enrolment(move("edu", "none", "primary"), month = 9)


Simulate from a model

Description

Runs the simulation a micsim_model() describes and returns the result together with the model, the seed and what happened during the run.

Usage

## S3 method for class 'micsim_model'
simulate(
  object,
  nsim = 1,
  seed = NULL,
  cores = 1L,
  verbose = FALSE,
  reestimate = TRUE,
  ...
)

Arguments

object

A micsim_model.

nsim

Number of simulations. Only 1 is supported; run the model again, with a different seed, for more.

seed

Integer seed, or NULL to draw one from R's current random number state. The same seed gives the same result on any number of cores.

cores

Number of processor cores. Splitting the population across cores is exact rather than approximate, because individuals in MicSim's model are independent of one another. The result does not depend on the number of cores. No more workers are started than there are individuals in the starting population.

verbose

Report progress through message().

reestimate

Estimate the transition rates from the simulated population after the run and compare them with the supplied ones (reestimate()).

...

Not used.

Details

This is a method for stats::simulate(), so it has that generic's argument names. With the default seed = NULL, a seed is drawn from R's current random number state (one draw), so set.seed(234) before the call makes a run reproducible. The drawn seed is stored in the result. Apart from that draw, the caller's random number state is left exactly as it was, including the generator kind. Every individual in the simulation draws from their own random-number stream, derived from the seed and their ID (a newborn's from its mother's). A life course therefore does not depend on who else is in the population, on the order of the population's rows or of the transitions, or on the number of cores. Two scenarios simulated with the same seed share their random numbers (common random numbers), i.e. an individual whose rates are the same in both lives the same life in both.

A model can be simulated repeatedly. Nothing is shared between runs: every subsystem's state is created fresh at the start of each run. If the model was built by a different MicSim version, a micsim_version_warning is given.

After the run, every transition rate is estimated from the simulated population and compared with the supplied one (reestimate()). Using plot() on the result shows the comparison. Pass reestimate = FALSE to skip it.

Value

An object of class micsim_result, a list with

pop

the simulated population: one row per transition, one row with NA transition columns for an individual who never moved. as.data.frame() returns it.

model

the micsim_model that was simulated, so the result is self-describing and as_long() needs no arguments.

seed

the seed the run used; when none was supplied, the one drawn from R's random number state.

diagnostics

n_events, n_individuals, n_starting, n_immigrants and n_newborns; n_forced (transitions forced by an Inf rate), n_unreliable (waiting times drawn from a degraded numerical integration); peak_queue (largest number of pending events; for a multi-core run the largest of any core), cores (worker processes used) and seconds (wall time of the simulation).

extensions

a named list with what each subsystem reports, e.g. result$extensions$fertility$births; see fertility() and school_enrolment().

reestimation

a micsim_reestimation (reestimate()), or NULL with reestimate = FALSE.

meta

provenance: micsim_version, r_version, platform, rng_kind (always "L'Ecuyer-CMRG"), seed_drawn (TRUE if the seed was drawn from R's random number state), created (time the run finished) and reestimation_seconds.

See Also

micsim_model(), as_long(), as_wide(), MicSim-concepts

Examples

mortality <- function(age, calTime) 0.00003 * exp(0.1 * age)
model <- micsim_model(
  state_space = state_space(sex = c("m", "f")),
  transitions = transitions(transition(NA, "dead", mortality)),
  population  = data.frame(ID = 1:10, birthDate = rep("19500101", 10),
                           initState = rep("f", 10),
                           stringsAsFactors = FALSE),
  horizon = c(20000101, 20401231), max_age = 120
)
result <- simulate(model, seed = 234)
result


Describe a state space

Description

Names the model's state variables and lists the values each may take. Supply this object to micsim_model().

Usage

state_space(...)

Arguments

...

Named character vectors, one per state variable.

Details

The state space contains all combinations of the supplied values. For example, two sexes, three nationalities and two parity values give twelve states. A label such as "f/DE/1" follows the order of the arguments.

Values must be distinct, both within and across variables. Avoid "/" inside a value because that character separates label components.

Value

An object of class micsim_state_space: the named list of state-variable values.

See Also

micsim_model(), MicSim-concepts

Examples

state_space(sex = c("m", "f"), nat = c("DE", "AT"), fert = c("0", "1"))


Summarise a simulation result

Description

Counts what happened: how many of each transition, the ages at which transitions took place separately for each dimension of the state space (each state variable that changes and each absorbing state entered), and how the population was distributed across states at the end.

Usage

## S3 method for class 'micsim_result'
summary(object, ...)

Arguments

object

A micsim_result.

...

Not used.

Value

A list of class summary.micsim_result, printed by its own method.


Describe one allowed transition

Description

Describes an allowed move from one state to another and supplies the function giving its rate.

Usage

transition(from, to, rate)

Arguments

from

Origin state label(s), NA for "every transient state except to", or a move() selector.

to

Destination state label. Omitted when from is a move(), which names its own destinations.

rate

A function that returns transition rates, supplied as a function object rather than its name. It may accept any subset of age, calTime and duration, each measured in fractional years. It must work with vector inputs, returning one numeric rate for each corresponding set of input values. For a constant rate, you may instead supply a function with no arguments that returns a single numeric value.

Details

Three ways to say which states:

transition("female/0", "female/1", rate)

full state labels. from may be a vector of labels.

transition(NA, "deceased", rate)

NA means every transient state, which is how mortality is normally written.

transition(move("edu", "none", "primary"), rate)

one state variable changes and everything else stays, for every state (or those satisfying the edge's where). See move().

A destination that is not a transient state is an absorbing state: the model creates it, under whatever name you give it.

Value

A transition, for passing to transitions().

See Also

transitions(), move(), micsim_model()

Examples

states <- state_space(
  sex = c("female", "male"),
  country = c("DE", "AT"),
  parity = c("0", "1", "2")
)
states

# Full state labels follow the order of the variables in `states`.

# A constant rate is used for all moves between countries.
# This move from Germany to Austria applies to women with no children.
move_to_at <- function() 0.02
transition(from = "female/DE/0", to = "female/AT/0", rate = move_to_at)

# A move from Austria to Germany applies to everyone living in Austria.
# Only the country changes. All other state variables remain constant.
move_to_de <- function() 0.03
transition(move("country", from = "AT", to = "DE"), rate = move_to_de)

# Two origin states share the same emigration rate, and emigration is
# an absorbing state, as "abroad" is not in the state space.
emigration_rate <- function() 0.01
transition(from = c("female/DE/0", "male/DE/0"),
           to = "abroad", rate = emigration_rate)

# First and second births change parity for women in either country.
first_birth <- function(age) ifelse(age >= 18 & age < 45, 0.10, 0)
second_birth <- function(age) ifelse(age >= 18 & age < 45, 0.08, 0)
transition(move("parity", from = "0", to = "1", where = sex == "female"),
           rate = first_birth)
transition(move("parity", from = "1", to = "2", where = sex == "female"),
           rate = second_birth)

# Mortality applies in every transient state.
mortality <- function(age) 0.00003 * exp(0.1 * age)
transition(from = NA, to = "deceased", rate = mortality)


Collect the transitions of a model

Description

Collects the individual transition() declarations into one object for micsim_model(). Each declaration describes an origin, destination and rate function; the collection describes which moves the model allows.

Usage

transitions(...)

Arguments

...

Objects from transition().

Details

Order matters only for readability. Each destination receives its random numbers in the order of the state space, so declaring the same transitions in a different order gives the same population under the same seed.

Value

An object of class micsim_transitions.

See Also

transition(), micsim_model()

Examples

# Set the rates for the allowed transitions 
first_birth <- function(age) ifelse(age >= 18 & age < 45, 0.10, 0)
second_birth <- function(age) ifelse(age >= 18 & age < 45, 0.08, 0)
mortality <- function(age) 0.00003 * exp(0.1 * age)

# Collect all the allowed transitions in one object
trans <- transitions(
  transition(move("parity", from = "0", to = "1", where = sex == "female"),
             rate = first_birth),
  transition(move("parity", from = "1", to = "2", where = sex == "female"),
             rate = second_birth),
  transition(from = NA, to = "deceased", rate = mortality)
)
trans


Checks rate values before simulating Replace the population of a model

Description

Returns a model with a different starting population, immigrant population, or both. All other settings are retained, and the new populations are checked exactly as micsim_model() checks them.

This allows a model developed on a sample to be applied to the full population without repeating the model specification.

Usage

## S3 method for class 'micsim_model'
update(object, population, immigrants, ...)

Arguments

object

A micsim_model.

population

A new starting population, in the format micsim_model() takes. Leave it out to keep the current one.

immigrants

A new immigrant table, or NULL for none. Leave it out to keep the current one.

...

Must be empty.

Details

Only population and immigrants can be changed with this method. To change the state space, transitions, simulation period, maximum age, exit types or subsystems, rebuild the model with micsim_model() and, where needed, add_subsystem().

Replace populations through update() so that the model is checked. Direct assignment, such as model$population <- ..., bypasses these checks and is not supported.

Value

A micsim_model.

See Also

micsim_model(), add_subsystem()

Examples

mort <- function(age, calTime) 0.0001 * exp(0.085 * age)
pop <- data.frame(ID = 1:200, birthDate = "19700101",
                  initState = rep(c("m", "f"), 100))
sample_model <- micsim_model(state_space(sex = c("m", "f")),
                             transitions(transition(NA, "dead", mort)),
                             pop[1:20, ], c(20000101, 20101231))
full_model <- update(sample_model, population = pop)
nrow(full_model$population)

Check an object thoroughly

Description

For a micsim_model(), runs every check and reports everything it finds at once. Errors: a rate that raises an error, returns something other than one number per input, NA or a negative value on a grid of whole ages, calendar years and durations; a newborn table that has no state for a mother. Warnings: a rate that is zero everywhere or exceeds 10 per person-year; a transition nobody can reach; a state nobody can leave. Inf is allowed for forced transitions.

Usage

validate(x, ...)

## S3 method for class 'micsim_model'
validate(x, strict = FALSE, ...)

Arguments

x

An object to check, here micsim_model.

...

Passed to methods.

strict

If TRUE, warnings are treated as errors.

Details

During construction the model already checked that each rate is a function with admissible arguments and that it returns one value per input.

Validation checks the values at the grid points. For example, a rate that passes at whole ages can still fail at a fractional age. Assessing whether the model is suitable for the research question is a separate step.

Because validation returns the model, you can pass it directly to model |> validate() |> simulate(seed = 234)

Value

x, invisibly, if no error is found. Otherwise an error of class micsim_invalid_model listing every problem. Warnings are given as one micsim_model_warning. Both carry ⁠$problems⁠, a data frame with one row per finding.

See Also

micsim_model(), MicSim-concepts