sim: Compile and execute a microsimulation pipeline

Description Usage Arguments Value Examples

View source: R/sim.R

Description

This function compiles and executes a microsimulation pipeline.

Usage

1
2
3
4
5
6
7
sim(
  world,
  pipeline,
  n_iters,
  write.error.dump.file = FALSE,
  write.error.dump.folder
)

Arguments

world

(World)
A World object.

pipeline

(function())
A functional sequence (fseq) object.

n_iters

a number of iterations. (integer(1))
Number of times the microsimulation pipeline should be repeated.

write.error.dump.file

(logical(1))
See tryCatchLog::tryCatchLog.

write.error.dump.folder

(character(1))
path: Saves the dump of the workspace in a specific folder instead of the working directory

Value

NULL

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
library(data.table)

# create simple models
birth_model <- list(yes = 0.1, no = 0.9)
death_model <- list(yes = 0.1, no = 0.9)

# prepare population data
ind_data <-
  data.table::copy(toy_individuals) %>%
  .[, .give_birth := "no"]

# create a World object, a container for all entities and models for simulation
world <- World$new()
world$add(x = Individual$new(.data = ind_data, id_col = "pid"))

# create filters, this is a method for creating functions using `magrittr` and
# data.table's syntax
filter_eligible_females <-
  . %>%
  .[sex == "female" & age %between% c(18, 50)]

filter_alive <-
  . %>%
  .[age != -1]

microsimulation_pipeline <-
  . %>%
  # ageing
  mutate_entity(
    entity = "Individual",
    age := age + 1L,
    subset = age != -1L
  ) %>%
  # simulate birth decision
  transition(
    entity = "Individual",
    model = birth_model,
    attr = ".give_birth",
    preprocessing_fn = . %>% filter_eligible_females() %>% filter_alive()
  ) %>%
  # add newborns
  add_entity(
    entity = "Individual",
    newdata = toy_individuals[age == 0, ],
    target = .$entities$Individual$get_data()[.give_birth == "yes", .N]
  ) %>%
  # reset the birth decision variable
  mutate_entity(
    entity = "Individual",
    .give_birth := "no",
    subset = age != -1L
  ) %>%
  # simulate deaths
  transition(
    entity = "Individual",
    model = death_model,
    attr = "age",
    values = c(yes = -1L),
    preprocessing_fn = filter_alive
  ) %>%
  # log the total number of alive individuals at the end of the iteration
  add_log(
    desc = "count:Individual",
    value = .$entities$Individual$get_data()[age != -1L, .N]
  )

# complie and execute a simulation pipeline
sim(world = world, pipeline = microsimulation_pipeline, n_iters = 10)

dymium-org/dymiumCore documentation built on July 18, 2021, 5:10 p.m.