Type: | Package |
Title: | Individual Based Model Population Simulation |
Version: | 1.1.0 |
Date: | 2024-10-10 |
Maintainer: | Daphné Giorgi <daphne.giorgi@sorbonne-universite.fr> |
Description: | Simulation of the random evolution of heterogeneous populations using stochastic Individual-Based Models (IBMs) <doi:10.48550/arXiv.2303.06183>. The package enables users to simulate population evolution, in which individuals are characterized by their age and some characteristics, and the population is modified by different types of events, including births/arrivals, death/exit events, or changes of characteristics. The frequency at which an event can occur to an individual can depend on their age and characteristics, but also on the characteristics of other individuals (interactions). Such models have a wide range of applications. For instance, IBMs can be used for simulating the evolution of a heterogeneous insurance portfolio with selection or for validating mortality forecasts. This package overcomes the limitations of time-consuming IBMs simulations by implementing new efficient algorithms based on thinning methods, which are compiled using the 'Rcpp' package while providing a user-friendly interface. |
URL: | https://github.com/DaphneGiorgi/IBMPopSim, https://DaphneGiorgi.github.io/IBMPopSim/ |
BugReports: | https://github.com/DaphneGiorgi/IBMPopSim/issues |
License: | MIT + file LICENSE |
Depends: | R (≥ 3.5.0) |
Imports: | Rcpp (≥ 0.12), checkmate, stats, readr, rlang, dplyr (≥ 0.8.0), ggplot2 |
Suggests: | RcppArmadillo, knitr, rmarkdown, bookdown, ggfortify, magick, colorspace, gganimate, gridExtra |
LinkingTo: | Rcpp |
LazyData: | true |
NeedsCompilation: | yes |
VignetteBuilder: | knitr |
RoxygenNote: | 7.3.2 |
Encoding: | UTF-8 |
Packaged: | 2024-10-11 09:02:56 UTC; giorgi |
Author: | Daphné Giorgi [aut, cre], Sarah Kaakai [aut], Vincent Lemaire [aut] |
Repository: | CRAN |
Date/Publication: | 2024-10-15 14:20:07 UTC |
IBMPopSim: Individual Based Model Population Simulation
Description
Simulation of the random evolution of heterogeneous populations using stochastic Individual-Based Models (IBMs) doi:10.48550/arXiv.2303.06183. The package enables users to simulate population evolution, in which individuals are characterized by their age and some characteristics, and the population is modified by different types of events, including births/arrivals, death/exit events, or changes of characteristics. The frequency at which an event can occur to an individual can depend on their age and characteristics, but also on the characteristics of other individuals (interactions). Such models have a wide range of applications. For instance, IBMs can be used for simulating the evolution of a heterogeneous insurance portfolio with selection or for validating mortality forecasts. This package overcomes the limitations of time-consuming IBMs simulations by implementing new efficient algorithms based on thinning methods, which are compiled using the 'Rcpp' package while providing a user-friendly interface.
Author(s)
Maintainer: Daphné Giorgi daphne.giorgi@sorbonne-universite.fr
Authors:
Sarah Kaakai sarah.kaakai@univ-lemans.fr
Vincent Lemaire vincent.lemaire@sorbonne-universite.fr
See Also
Useful links:
Report bugs at https://github.com/DaphneGiorgi/IBMPopSim/issues
England and Wales (EW) 2014 population and death rates by Index of Multiple Deprivation (IMD).
Description
EW population, death rates by age, gender and IMD for year 2014 (Source: Office for National Statistics, reference number 006518).
Usage
EW_popIMD_14
Format
A list containing:
age_pyramid
Data frame containing EW age pyramid for year 2014, by gender, IMD and single year of age (0-115).
Individuals in the age class 90+ are distributed in the single year of age classes as in the EW population.
death_rates
List containing 4 fields:
male
Male death rates data frame, by IMD and single year of age (0-90+).
female
Female death rates dataframe, by IMD and single year of age (0-90+).
sample
Population dataframe composed of 100 000 individuals, sampled from
age_pyramid
.
England and Wales (EW) 2014 population, death and birth rates.
Description
EW 2014 population and death rates by age and gender (Source: Office for National Statistics, reference number 006518).
Female birth rates by age of the mother (Source: Office for National Statistics birth summary tables).
Usage
EW_pop_14
Format
A list containing:
age_pyramid
Data frame containing EW age pyramid for year 2014, by gender and single year of age (0-115).
rates
A list containing three data frames:
birth
Birth rates data frame, by age of mother and 5 years age groups.
death_male
Male death rates data frame, by single year of age (0-90+).
death_female
Female death rates dataframe, by single year of age (0-90+).
sample
Population dataframe composed of 100 000 individuals, sampled from
age_pyramid
.
Example of "human population" after 100 years of simulation.
Description
Example of "human population" data frame after 100 years of simulation, based on a sample of England and Wales 2014 population and demographic rates.
Usage
EW_pop_out
Format
Data frame containing a population structured by age and gender,
simulated with an initial population of 100 000 individuals sampled from EW_pop_14$age_pyramid
over 100 years, with birth and death events.
England and Wale mortality data (source: Human Mortality Database)
Description
Obtained with
EWdata_hmd <- hmd.mx(country = "GBRTENW", username = ... , password = ...,label = "England and Wales")
Usage
EWdata_hmd
Format
An object of class demogdata
of length 7.
Generic method for add_characteristic
Description
Generic method for add_characteristic
Usage
add_characteristic(x, name, value = NA)
Arguments
x |
An object. |
name |
Name of the characteristic to add. |
value |
Value of the characteristic. By default |
Add characteristic to a population
Description
Add characteristic to a population
Usage
## S3 method for class 'population'
add_characteristic(x, name, value = NA)
Arguments
x |
Object of population class representing a population. |
name |
Name of the characteristic to add. |
value |
Value of the characteristic. By default |
Generic method for age_pyramid
Description
Generic method for age_pyramid
Usage
age_pyramid(object, time = 0, ages = c(0:110, Inf), ...)
Arguments
object |
Population. |
time |
The age pyramid is computed at instant |
ages |
(Optional) A numeric vector of distinct positive values composing age groups. Must be in increasing order. |
... |
Additional parameters |
Value
An object of class pyramid
containing the age pyramid of a population at instant time
.
Age pyramid from a population at a given time.
Description
Reduce a population containing all individuals (with some characteristics) to an age-groups data frame (preserving characteristics). The function computes the number of individuals at time
in each age group [ages[i],ages[i+1][
, for i
in {1,...,N-1}
.
Usage
## S3 method for class 'population'
age_pyramid(object, time = 0, ages = c(0:110, Inf), ...)
Arguments
object |
Object of |
time |
The age pyramid is computed at instant |
ages |
(Optional) A numeric vector of distinct positive values composing age groups. Must be in increasing order. |
... |
Additional parameters |
Value
An object of class pyramid
containing the age pyramid of the given population at instant time
.
See Also
Examples
age_pyramid(population(EW_pop_14$sample), time = 0)
age_pyramid(population(EW_popIMD_14$sample), time = 0, ages = seq(0, 120, by=2))
Generic method for age_pyramids
Description
Generic method for age_pyramids
Usage
age_pyramids(object, time = 0, ages = c(0:110, Inf))
Arguments
object |
Population. |
time |
The age pyramid is computed at instant |
ages |
(Optional) A numeric vector of distinct positive values composing age groups. Must be in increasing order. |
Age pyramid from a population data frame at some given times.
Description
Vectorial version in time of the function age_pyramid.population
. Not compatible with IBMs including swap events.
Usage
## S3 method for class 'population'
age_pyramids(object, time = 0, ages = c(0:110, Inf))
Arguments
object |
Object of |
time |
The age pyramid is computed at instant |
ages |
(Optional) A numeric vector of distinct positive values composing age groups. Must be in increasing order. |
Details
For convenience. This is a just a lapply
call of age_pyramid.population
on the vector time
.
Function for internal use
Description
Check characteristics.
Usage
assertCharacteristics(characteristics)
Function for internal use
Description
Check events
Usage
assertEvents(events)
Function for internal use
Description
Check parameters.
Usage
assertParameters(parameters)
Function for internal use
Description
Check on the population.
Usage
assertPopulation(object)
Function for internal use
Description
Check on a pyramid.
Usage
assertPyramid(pyramid)
Function for internal use
Description
Capitalize first letter of a word
Usage
capitalize(x)
Check the intensity code.
Description
Verifies that the intensity contains the string 'result'.
Usage
check_intensity_code(code)
Arguments
code |
String containing the intensity code. |
Check the interaction code.
Description
Verifies that the interaction contains the string 'result'.
Usage
check_interaction_code(code)
Arguments
code |
String containing the interaction code. |
Check the kernel code.
Description
Verifies the kernel code.
Usage
check_kernel_code(code)
Arguments
code |
String containing the kernel code. |
Check characteristics-events compatibility
Description
A function to check the compatibility between characteristics and events
Usage
compatibility_chars_events(characteristics, events)
Arguments
characteristics |
List of characteristics |
events |
List of events |
Check population-model compatibility
Description
A function to check the compatibility between a population and a model
Usage
compatibility_pop_model(pop, model)
Arguments
pop |
An object of class population |
model |
An Individual Based Model created with the mk_model function |
Death table
Description
Creates a death table from a population object.
For each i=1..N-1
and j=1..M
, the number of individuals with age at last birthday in [ages[i],ages[i+1])
and died in [times[j],times[j+1])
is computed.
Usage
death_table(pop, ages, period)
Arguments
pop |
Object of class |
ages |
A vector of size |
period |
A vector of size |
Details
The function computes the number of death in each time interval [times[j],times[j+1])
, j=1..M
.
Value
A death table matrix.
Examples
dth_table <- death_table(population(EW_pop_out), 0:101, 0:11)
Autogenerate cpp details documentation
Description
Autogenerating documentation details for cpp functions
Usage
details_cpp()
Autogenerated documentation for intensity code
Description
Autogenerated documentation for intensity code
Usage
details_intensity_code()
Autogenerated documentation for interaction code
Description
Autogenerated documentation for interaction code
Usage
details_interaction_code()
Autogenerated documentation for kernel code
Description
Autogenerated documentation for kernel code
Usage
details_kernel_code()
Autogenerated documentation for event type
Description
Autogenerated documentation for event type
Usage
details_type_event()
Exposure table
Description
Returns the Central Exposure-to-Risk for given ages groups and time period. The central Exposure-to-risk is computed as the sum of the time spent by individuals in a given age group over a given period, where age is the age at last birthday.
Usage
exposure_table(pop, ages, period)
Arguments
pop |
Object of class |
ages |
A vector of size |
period |
A vector of size |
Details
The function computes the central exposure-to-risk in each time interval [t[j],t[j+1])
, j=1..M
, and age groups.
Value
An exposure matrix
Examples
ex_table <- exposure_table(population(EW_pop_out),0:101,0:11)
Function for internal use
Description
Get C++ type of a parameter.
Usage
get_Ctype(x)
Function for internal use
Description
Get R type of a parameter.
Usage
get_Rtype(x)
Generic method for get_characteristics
Description
Generic method for get_characteristics
Usage
get_characteristics(object, ...)
Arguments
object |
An object. |
... |
Additional parameters. |
Returns names and C types of the characteristics.
Description
Returns names and C types of the characteristics (other than birth and death) of the individuals in a population, from a population data frame.
Usage
## S3 method for class 'population'
get_characteristics(object, ...)
Arguments
object |
Object of population class representing a population. |
... |
additional arguments. |
Value
Named vector composed of characteristics names and C types. If the population has no characteristics, which means that it has only the birth
and death
columns, this returns NULL
.
Examples
get_characteristics(population(EW_pop_14$sample))
Gompertz–Makeham intensity function.
Description
The intensity function (or hazard function) for the Gompertz-Makeham law of mortality distribution is defined as
h(x) = \alpha e^{\beta x} + \lambda
with \alpha, \beta, \lambda \in {R}_+
.
Usage
gompertz(alpha, beta, lambda = 0)
Arguments
alpha |
Non-negative real parameter. |
beta |
Non-negative real parameter. |
lambda |
Non-negative real parameter. |
Details
A C++ version of this function is available. See vignette('IBMPopSim_cpp')
for more details.
Value
Function which associates x
to \alpha exp(\beta x) + \lambda
.
See Also
https://en.wikipedia.org/wiki/Gompertz%E2%80%93Makeham_law_of_mortality
Search for a given string in event types
Description
Search for a given string in event types
Usage
has_event_type(events, str)
Arguments
events |
list of events |
str |
string to search |
Value
boolean
Complete a population id
Description
In a population with an id
column, verifies that there are no NA id
values,
and if there are, completes the missing id
s
Usage
id_complete(object, ...)
Arguments
object |
A data frame containing at least a column |
Linear interpolation function.
Description
Return a function performing the linear interpolation.
Usage
linfun(x, y, yleft = y[1], yright = y[length(y)])
Arguments
x , y |
Numeric vectors giving the coordinates of the points to be interpolated. |
yleft |
The value to be returned when input |
yright |
The value to be returned when input |
Details
A C++ version of this function is available. See vignette('IBMPopSim_cpp')
for more details.
Value
Objet of class linfun
and function
which is an approxfun
function with method = 'linear'
.
Returns the maximum of a function of class stepfun
.
Description
Returns the maximum of a function of class stepfun
.
Usage
## S3 method for class 'stepfun'
max(..., na.rm = FALSE)
Arguments
... |
argument of class |
na.rm |
a logical indicating whether missing values should be removed |
Value
The maximum of the step function.
A function returning a merged dataframe from a list of population dataframes with id.
Description
A function returning a merged dataframe from a list of population dataframes with id.
Usage
merge_pop_withid(pop_df_list, chars_tracked = NULL)
Arguments
pop_df_list |
A list of population dataframe where the first three columns of each dataframe are id, birth and death. |
chars_tracked |
A vector of characteristics to be tracked over time. |
Value
A dataframe composed of all individuals with their characteristics at each simulation time.
Creating an event with intensity of class individual
Description
Creates an event with intensity of class individual (without interactions). When the event occurs, something happens to an individual I
in the population.
The created event must be used with mk_model
.
Usage
mk_event_individual(type, name, intensity_code, kernel_code = "")
Arguments
type |
Must be one of |
name |
(Optional) If not specified, the name given to the event is its type. |
intensity_code |
String containing some C++ code describing the intensity function. See details. |
kernel_code |
String containing some C++ code describing the event action. Optional for |
Details
The type
argument is one of the following
'birth'
By default, a new individual
newI
is created, with the same characteristics of the parentI
and birth date equal to the current time. Optional code can be precised inkernel_code
.'death'
By default, the individual
I
dies. Optional code can be precised inkernel_code
.'entry'
A new individual
newI
is added to the population, and its characteristics have to be defined by the user in the entrykernel_code
.'exit'
An individual
I
exits from the population. Optional code can be precised inkernel_code
.'swap'
The user can change the characteristics of the selected individual
I
. This requireskernel_code
.'custom'
None of the above types, the user defines
kernel_code
that can act on the selected individualI
and on the populationpop
.
The intensity_code
argument is a string containing some C++ code describing the event intensity for individual I
at time t
. The intensity value must be stored in the variable result
.
Some of available variables in the C++ code are: t
(the current time), I
(the current individual selected for the event), the name of the model parameters (some variables, or functions, see mk_model
).
See vignette('IBMPopSim_Cpp')
for more details.
The kernel_code
argument is a string containing some C++ code which describing the action of the event. Some of available variables in the C++ code are: t
(the current time), pop
(the current population), I
(the current individual selected for the event), newI
(the new individual if 'birth'
or 'entry'
event), the name of the model parameters (some variables, or functions, see mk_model
).
See vignette('IBMPopSim')
for more details.
Value
An S3 object of class event
of type individual.
See Also
mk_model
, mk_event_poisson
, mk_event_inhomogeneous_poisson
, and mk_event_interaction
.
Examples
params <- list("p_male"= 0.51,
"birth_rate" = stepfun(c(15,40), c(0,0.05,0)),
"death_rate" = gompertz(0.008, 0.02))
death_event <- mk_event_individual(type = "death",
name = "my_death_event",
intensity_code = "result = death_rate(age(I,t));")
birth_event <- mk_event_individual(type = "birth",
intensity_code = "if (I.male) result = 0;
else result = birth_rate(age(I,t));",
kernel_code = "newI.male = CUnif(0, 1) < p_male;")
Creating inhomogeneous Poisson class event
Description
The function mk_event_inhomogeneous_poisson
is used to create an event with intensity type inhomogeneous Poisson (time dependent intensity which does not depend on population).
When the event occurs, something happens in the population.
The created event must be used with mk_model
.
Usage
mk_event_inhomogeneous_poisson(type, name, intensity_code, kernel_code = "")
Arguments
type |
Must be one of |
name |
(Optional) If not specified, the name given to the event is its type. |
intensity_code |
String containing some C++ code describing the intensity function. See details. |
kernel_code |
String containing some C++ code describing the event action. Optional for |
Details
The type
argument is one of the following
'birth'
By default, a new individual
newI
is created, with the same characteristics of the parentI
and birth date equal to the current time. Optional code can be precised inkernel_code
.'death'
By default, the individual
I
dies. Optional code can be precised inkernel_code
.'entry'
A new individual
newI
is added to the population, and its characteristics have to be defined by the user in the entrykernel_code
.'exit'
An individual
I
exits from the population. Optional code can be precised inkernel_code
.'swap'
The user can change the characteristics of the selected individual
I
. This requireskernel_code
.'custom'
None of the above types, the user defines
kernel_code
that can act on the selected individualI
and on the populationpop
.
The intensity_code
argument is a string containing some C++ code describing the event intensity for individual I
at time t
. The intensity value must be stored in the variable result
.
Some of available variables in the C++ code are: t
(the current time), I
(the current individual selected for the event), the name of the model parameters (some variables, or functions, see mk_model
).
See vignette('IBMPopSim_Cpp')
for more details.
The kernel_code
argument is a string containing some C++ code which describing the action of the event. Some of available variables in the C++ code are: t
(the current time), pop
(the current population), I
(the current individual selected for the event), newI
(the new individual if 'birth'
or 'entry'
event), the name of the model parameters (some variables, or functions, see mk_model
).
See vignette('IBMPopSim')
for more details.
Value
An S3 object of class event
of type inhomogeneous Poisson.
See Also
mk_model
, mk_event_poisson
, mk_event_individual
, mk_event_interaction
.
Creating an event with intensity of type interaction
Description
Creates an event whose intensity depends on an individual and interactions with the population. When the event occurs, something happens to an individual I
in the population. The intensity of the event can depend on time, the characteristics of I and other individuals in the population, and can be written as
d(I,t,pop) = \sum_{J \in pop} U(I,J,t),
where U
is called the interaction function.
The created event must be used with mk_model
.
Usage
mk_event_interaction(
type,
name,
interaction_code,
kernel_code = "",
interaction_type = "random"
)
Arguments
type |
Must be one of |
name |
(Optional) If not specified, the name given to the event is its type. |
interaction_code |
String containing some C++ code describing the interaction function. See details. |
kernel_code |
String containing some C++ code describing the event action. Optional for |
interaction_type |
(Optional) Either |
Details
The type
argument is one of the following
'birth'
By default, a new individual
newI
is created, with the same characteristics of the parentI
and birth date equal to the current time. Optional code can be precised inkernel_code
.'death'
By default, the individual
I
dies. Optional code can be precised inkernel_code
.'entry'
A new individual
newI
is added to the population, and its characteristics have to be defined by the user in the entrykernel_code
.'exit'
An individual
I
exits from the population. Optional code can be precised inkernel_code
.'swap'
The user can change the characteristics of the selected individual
I
. This requireskernel_code
.'custom'
None of the above types, the user defines
kernel_code
that can act on the selected individualI
and on the populationpop
.
The interaction_code
argument is a string containing some C++ code describing the event interaction function $U$ at time t
. The interaction value must be stored in the variable result
.
Some of available variables in the C++ code are: t
(the current time), I
(the current individual selected for the event), J
(another individual if interaction_type
is 'random'
), the name of the model parameters (some variables, or functions, see mk_model
).
See vignette('IBMPopSim_Cpp')
for more details.
The kernel_code
argument is a string containing some C++ code which describing the action of the event. Some of available variables in the C++ code are: t
(the current time), pop
(the current population), I
(the current individual selected for the event), newI
(the new individual if 'birth'
or 'entry'
event), the name of the model parameters (some variables, or functions, see mk_model
).
See vignette('IBMPopSim')
for more details.
Value
An S3 object of class event
of type interaction.
See Also
mk_model
, mk_event_poisson
, mk_event_inhomogeneous_poisson
, mk_event_individual
.
Examples
death_interaction_code<- " result = max(J.size -I.size,0);"
event <- mk_event_interaction(type="death",
interaction_code = death_interaction_code)
Creating Poisson class event
Description
The function mk_event_poisson
is used to create an event with intensity of type Poisson (constant intensity which does not depend on population or time).
When the event occurs, something happens in the population.
The created event must be used with mk_model
.
Usage
mk_event_poisson(type, name, intensity, kernel_code = "")
Arguments
type |
Must be one of |
name |
(Optional) If not specified, the name given to the event is its type. |
intensity |
String containing some constant positive value, or name of a parameter which is a constant positive value. |
kernel_code |
String containing some C++ code describing the event action. Optional for |
Details
The type
argument is one of the following
'birth'
By default, a new individual
newI
is created, with the same characteristics of the parentI
and birth date equal to the current time. Optional code can be precised inkernel_code
.'death'
By default, the individual
I
dies. Optional code can be precised inkernel_code
.'entry'
A new individual
newI
is added to the population, and its characteristics have to be defined by the user in the entrykernel_code
.'exit'
An individual
I
exits from the population. Optional code can be precised inkernel_code
.'swap'
The user can change the characteristics of the selected individual
I
. This requireskernel_code
.'custom'
None of the above types, the user defines
kernel_code
that can act on the selected individualI
and on the populationpop
.
The kernel_code
argument is a string containing some C++ code which describing the action of the event. Some of available variables in the C++ code are: t
(the current time), pop
(the current population), I
(the current individual selected for the event), newI
(the new individual if 'birth'
or 'entry'
event), the name of the model parameters (some variables, or functions, see mk_model
).
See vignette('IBMPopSim')
for more details.
Value
An S3 object of class event
of type Poisson.
See Also
mk_model
, mk_event_inhomogeneous_poisson
, mk_event_individual
, mk_event_interaction
.
Examples
birth <- mk_event_poisson('birth', intensity = 10)
params <- list(beta = 10)
death <- mk_event_poisson('death', intensity = 'beta') # name of one parameter
mk_model(events = list(birth, death), parameters = params)
Function for internal use
Description
Get R and C++ type of characteristics.
Usage
mk_individual_type(characteristics)
Creates a model for IBMPopSim.
Description
This function creates an Individual Based Model describing the population, events which can occur in the population, and the model parameters.
Usage
mk_model(
characteristics = NULL,
events,
parameters = NULL,
with_compilation = TRUE
)
Arguments
characteristics |
List containing names and types of characteristics of individuals in the population. See |
events |
List of events in the model. See |
parameters |
Model parameters. A list of parameters of the model. |
with_compilation |
(Optional) Logical parameter, |
Details
It builds the C++ model code and produces the function popsim_cpp
which will be used for simulating the model. The function used to simulate a population from a model is popsim
.
Value
model List containing the built model :
-
individual_type
: Names and types (R and C++) of characteristics. -
parameters_types
: Names and types (R and C++) of model parameters. -
events
: List of events. -
cpp_code
: Output of C++ compilation.
See Also
popsim
, mk_event_poisson
, mk_event_individual
, mk_event_interaction
.
Examples
params <- list("p_male"= 0.51,
"birth_rate" = stepfun(c(15,40),c(0,0.05,0)),
"death_rate" = gompertz(0.008,0.02))
death_event <- mk_event_individual(type = "death",
intensity_code = "result = death_rate(age(I,t));")
birth_event <- mk_event_individual(type = 'birth',
intensity_code = "if (I.male) result = 0;
else result=birth_rate(age(I,t));",
kernel_code = "newI.male = CUnif(0, 1) < p_male;")
model <- mk_model(characteristics = get_characteristics(population(EW_pop_14$sample)),
events = list(death_event,birth_event),
parameters = params)
summary(model)
Extract types (R and C++) of the parameters
Description
Extract types (R and C++) of the parameters
Usage
mk_parameters_types(parameters)
Arguments
parameters |
parameters |
Value
list
Function for internal use
Description
Build source code for individual creation.
Usage
mkcpp_declaration_individual(ind_t)
Function for internal use
Description
Build source code for event definition.
Usage
mkcpp_definition_events(events)
Function for internal use
Description
Build source code for event creation.
Usage
mkcpp_event(event, kernel_type, name_type)
Function for internal use
Description
Build source code for population initialization.
Usage
mkcpp_initialisation_population(ind_t)
Function for internal use
Description
Build source code for output population creation.
Usage
mkcpp_output_population(ind_t)
Function for internal use
Description
Build source code for parameters creation.
Usage
mkcpp_parameters(parameters, parameters_t)
Function for internal use
Description
Build source main code for model simulation.
Usage
mkcpp_popsim(model, with_id)
Piecewise real function.
Description
Given the vectors (breaks[1],...,breaks[n])
and the list of IBMPopSim
compatible
functions funs = (f[0],f[1],...,f[n])
(one value more!), piecewise_x(breaks, funs)
returns
the function
f(x) = f_0(x){1}_{x\le breaks[1]}+\sum_{k=1}^{n-1} f_k(x) {1}_{[breaks_{k}, breaks_{k+1})}(x) + f_n(x){1}_{x \ge breaks[n]}
Usage
piecewise_x(breaks, funs)
Arguments
breaks |
Numeric vector giving the breaks of functions given in |
funs |
List of functions. |
Details
A C++ version of this function is available. See vignette('IBMPopSim_cpp')
for more details.
Value
Piecewise function built with the given intervals and functions.
Examples
dr <- with(EW_pop_14$rates,
stepfun(x=death_male[,"age"], y=c(0,death_male[,"value"])))
# before age 80 the stepfun and after age 80 the gompertz function
f <- piecewise_x(80, list(dr, gompertz(0.00006, 0.085)))
x <- seq(40:120)
plot(x, sapply(x, f))
Piecewise real function of two variables.
Description
Given the vectors (breaks[1],...,breaks[n])
and the list of IBMPopSim
compatible
functions funs = (f[0],f[1],...,f[n])
(one value more!), piecewise_xy(breaks, funs)
returns
the function
f(x,y) = f_0(x) {1}_{y\le breaks[1]}+\sum_{k=1}^{n-1} f_k(x) {1}_{[breaks_{k}, breaks_{k+1})}(y) + f_n(x){1}_{y \ge breaks[n]}
Usage
piecewise_xy(breaks, funs)
Arguments
breaks |
Numeric vector giving the breaks of functions given in |
funs |
List of functions. |
Details
A C++ version of this function is available. See vignette('IBMPopSim_cpp')
for more details.
Value
Piecewise bivariate function built with the given intervals and functions.
Examples
time_dep_function <- piecewise_xy(c(5),
list(gompertz(0.1, 0.005), gompertz(0.08, 0.005)))
time_dep_function(0, 65) # death intensity at time 0 and age 65.
Plot the age pyramid of a population data frame (at a given time).
Description
Plot an age pyramid from age pyramid data frame with possibly several characteristics.
Usage
## S3 method for class 'population'
plot(
x,
group_colors = NULL,
group_legend = "Group",
age_breaks = NULL,
value_breaks = NULL,
...
)
Arguments
x |
Object of class population. |
group_colors |
(Optional) Named character vector. |
group_legend |
(Optional) Legend title name. By default set to |
age_breaks |
(Optional) An ordered vector of indexes of vector |
value_breaks |
(Optional) Breaks for the axis of values. |
... |
Additional arguments |
Value
Plot of age pyramid.
See Also
plot.pyramid
, age_pyramid.population
.
Examples
plot(population(EW_pop_14$sample), time = 0)
Plot an age pyramid.
Description
Plot an age pyramid from age pyramid data frame with possibly several characteristics.
Usage
## S3 method for class 'pyramid'
plot(
x,
group_colors = NULL,
group_legend = "Group",
age_breaks = NULL,
value_breaks = NULL,
...
)
Arguments
x |
Object of class (Optional) For plotting an age pyramid composed of several subgroups, the population data frame must contain a column named |
group_colors |
(Optional) Named character vector. |
group_legend |
(Optional) Legend title name. By default set to |
age_breaks |
(Optional) An ordered vector of indexes of vector |
value_breaks |
(Optional) Breaks for the axis of values. |
... |
Additional parameters |
Value
Plot of the age pyramid.
See Also
Examples
plot.pyramid(subset(pyramid(EW_pop_14$age_pyramid), as.numeric(age) <= 110))
library(colorspace)
pyr_IMD <- subset(pyramid(EW_popIMD_14$age_pyramid), as.numeric(age) <= 110)
pyr_IMD$group_name <- with(pyr_IMD, ifelse(male, paste('Males - IMD', IMD),
paste('Females - IMD', IMD)))
colors <- c(sequential_hcl(n=5, palette = "Magenta"),
sequential_hcl(n=5, palette = "Teal"))
names(colors) <- c(paste('Females - IMD', 1:5),
paste('Males - IMD', 1:5))
# note that you must have setequal(names(colors), pyr_IMD$group_name) is TRUE
plot.pyramid(pyr_IMD, colors)
# age pyramids at different times
library(gganimate)
pyrs = age_pyramids(population(EW_popIMD_14$sample), time = 1:10)
plot.pyramid(pyrs) + transition_time(time) + labs(title = "Time: {frame_time}")
Generic method for popsample
Description
Generic method for popsample
Usage
popsample(age_pyramid, size, age_max = 120, time = 0)
Arguments
age_pyramid |
Age pyramid. |
size |
A non-negative integer giving the number of individuals in population. |
age_max |
(Optional) A non-negative numeric which replace (if exists) the |
time |
(Optional) The age pyramid is computed at instant |
Value
Object of population
class representing a data frame of size size
containing a population of individuals.
Sample a population from an age pyramid (at a given time).
Description
Sample a population from an age pyramid (at a given time).
Usage
## S3 method for class 'pyramid'
popsample(age_pyramid, size, age_max = 120, time = 0)
Arguments
age_pyramid |
Object of |
size |
A non-negative integer giving the number of individuals in population. |
age_max |
(Optional) A non-negative numeric which replace (if exists) the |
time |
(Optional) The age pyramid is computed at instant |
Value
Object of population
class representing a data frame of size size
containing a population of individuals.
Examples
pop_sample_1e4 <- popsample(pyramid(EW_pop_14$age_pyramid), size = 1e4)
Simulation of a model.
Description
This function simulates the random evolution of an IBM.
Usage
popsim(
model,
initial_population,
events_bounds,
parameters = NULL,
age_max = Inf,
time,
multithreading = FALSE,
num_threads = NULL,
clean_step = NULL,
clean_ratio = 0.1,
seed = NULL,
verbose = FALSE
)
Arguments
model |
Model resulting from a call to the function |
initial_population |
Object of population class representing the initial population. |
events_bounds |
Named vector of events bounds, with names corresponding to events names. |
parameters |
List of model parameters. |
age_max |
Maximum age of individuals in the population ( |
time |
Final time (Numeric). Can be of length 1 or a vector of simulation discretized times. |
multithreading |
Logical for multithread activation, |
num_threads |
(Optional) Number of threads used for multithreading. Set by default to the number of concurrent threads supported by the available hardware implementation. |
clean_step |
(Optional) Optional parameter for improving simulation time. Time step for removing dead (or exited) individuals from the population. By default, equal to age_max. |
clean_ratio |
(Optional) Optional parameter for improving simulation time. 0.1 by default. |
seed |
(Optional) Random generator seed, random by default. |
verbose |
(Optional) Activate verbose output, FALSE by default. |
Value
List composed of
- arguments
Simulation inputs (initial population, parameters value, multithreading...)
- logs
Simulation logs (algorithm duration, accepted/rejected events...).
- population
If
time
is of length 1, population is an object of type population containing of all individuals who lived in the population in the time interval[0,time]
. Iftime
is a vector (time[1], ..., time[n]
),population
is a list ofn
objects of type population, each representing the state of the population at timetime[i]
, fori = 1,..., n
.
See Also
Examples
init_size <- 100000
pop_df <- data.frame(birth = rep(0, init_size), death = NA)
pop <- population(pop_df)
birth = mk_event_poisson(type = 'birth', intensity = 'lambda')
death = mk_event_poisson(type = 'death', intensity = 'mu')
params = list('lambda' = 100, 'mu' = 100)
birth_death <- mk_model(events = list(birth, death),
parameters = params)
sim_out <- popsim(model = birth_death,
initial_population = pop,
events_bounds = c('birth' = params$lambda, 'death' = params$mu),
parameters = params,
time = 10)
Class population
Description
Data frame containing a population, with at least a birth and a death column, and eventually some other characteristics
Usage
population(x, entry = FALSE, out = FALSE, id = FALSE)
Arguments
x |
Data frame or list of data frames, containing at least a birth and a death column |
entry |
Boolean flag. By default set to FALSE. If set to TRUE the population must contain a column of numerical values named "entry", If the column doesn't exist a column named "entry" is added to the data frame with all values set to NA. |
out |
Boolean flag. By default set to FALSE. If set to TRUE the population must contain a column of boolean values named "out", If the column doesn't exist a column named "out" is added to the data frame with all the values set to FALSE. |
id |
Boolean flag. By default set to FALSE. If set to TRUE the population must contain a column of integer distinct values named "id". If the column doesn't exist a column named "id" is added to the data frame with values seq(1, nrow(x)). |
Value
Given data frame augmented of the "population" class. If a list of data frames is given, the column names should contain the string "id" and the list corresponds to the evolution of a population at different times. The constructor then returns the last population observed in the list (corresponding to the final state of the population).
Generic method for population_alive
Description
Generic method for population_alive
Usage
population_alive(object, t, a1 = 0, a2 = Inf, ...)
Arguments
object |
A population. |
t |
A numeric indicating the time at which alive individuals are observed. |
a1 |
0 by default. Lower bound for age. |
a2 |
Inf by default. Upper bound for age. |
... |
Additional params. |
Value
All individuals alive at time t
and of age in [a1,a2)
.
Returns a population of individuals alive.
Description
Returns a population of individuals alive.
Usage
## S3 method for class 'population'
population_alive(object, t, a1 = 0, a2 = Inf, ...)
Arguments
object |
A population data frame containing at least a column |
t |
A numeric indicating the time. |
a1 |
0 by default. All individuals of age over |
a2 |
Inf by default. All individuals of age below |
... |
Additional params. |
Value
The function returns a population data frame containing all individuals alive at time t
and of age in [a1,a2)
.
Print Event
Description
print
method for class "event" giving a short description of an event.
Usage
## S3 method for class 'event'
print(x, ...)
Arguments
x |
Argument of class |
... |
Additional arguments affecting the summary produced. |
Printing of a model
Description
print
method for class model
.
Usage
## S3 method for class 'model'
print(x, ...)
Arguments
x |
argument of class |
... |
additional arguments affecting the summary produced. |
Printing population
Description
Print a population
Usage
## S3 method for class 'population'
print(x, ...)
Arguments
x |
Object of population class representing a population. |
... |
Additional arguments |
Value
Print the population
Class pyramid
Description
Data frame containing an age pyramid, with at least an age
and a value
column,
and eventually some other characteristics. If a male
column is present, it must be a logical vector,
if a group
column is present, it must be a vector of type character.
Usage
pyramid(x)
Arguments
x |
Data frame, containing at least an |
Value
Given data frame augmented of the "age_pyramid" class.
Step Function.
Description
Given the vectors (x[1],...,x[n])
and (y[0],y[1],...,y[n])
(one value more!), stepfun(x, y)
returns an interpolating step function, say f_n
. This is the cadlag version (right = FALSE
) of the stepfun
function from package stats
. The step function value f_n(t)
equals to the constant y[k-1]
for t
in [x[k-1], x[k])
so that
f_n(t) = \sum_{k=1}^{n+1} y_{k-1} {1}_{[x_{k-1}, x_{k})}(t),
withx_0=-\infty
and x_{n+1}=+\infty
.
Usage
stepfun(x, y)
Arguments
x |
Numeric vector giving the knots or jump locations of the step function. Must be sorted with unique values. |
y |
Numeric vector one longer than x, giving the heights of the function values between the c |
Details
This function is defined for documentation purposes only. See stepfun
and approxfun
.
A C++ version of this function is available. See vignette('IBMPopSim_cpp')
for more details.
Value
Objet of class stepfun
with option right = FALSE
(cadlag function).
See Also
plot.stepfun
and max.stepfun
.
Summarizing an event
Description
summary
method for class event
giving a detailed description of an event.
Usage
## S3 method for class 'event'
summary(object, ...)
Arguments
object |
Argument of class |
... |
Additional arguments affecting the summary produced. |
Summary logs
Description
Summary of the logs of a simulation
Usage
## S3 method for class 'logs'
summary(object, ...)
Arguments
object |
Logs of the output of a call to popsim function |
... |
Additional arguments affecting the summary produced |
Value
Print column names and number of individuals
Summary of a model
Description
summary
method for class model
.
Usage
## S3 method for class 'model'
summary(object, ...)
Arguments
object |
argument of class |
... |
additional arguments affecting the summary produced. |
Summary population
Description
Summary of a population with column names and number of individuals
Usage
## S3 method for class 'population'
summary(object, ...)
Arguments
object |
Object of population class representing a population. |
... |
Additional arguments affecting the summary produced |
Value
Print column names and number of individuals
Summary simulation output
Description
Summary of a simulation output
Usage
## S3 method for class 'simulation_output'
summary(object, ...)
Arguments
object |
Output of a call to popsim function |
... |
Additional arguments affecting the summary produced |
Value
Summary of population(s) and the logs
Toy parameters for IBMPopSim-human_popIMD vignette example.
Description
Toy parameters for IBMPopSim-human_popIMD vignette example.
Usage
toy_params
Format
A list containing:
birth
A list of 3 numeric vectors (
alpha
,beta
,TFR_weights
) for creating birth intensity with the Weibull probability density function.swap
A List of one numeric vector and two data frames (
ages
,intensities
anddistribution
) for creating the swap intensity and kernel functions.
Weibull function.
Description
The Weibull (density) function is defined as
h(x) = \bigl(\frac{k}{\lambda}\bigr) {\bigl( \frac{x}{\lambda} \bigr)}^{k-1} e^{-(x/\lambda)^k}
with k, \lambda \in (0, +\infty)
.
Usage
weibull(k, lambda = 1)
Arguments
k |
Shape parameter, a positive real number. |
lambda |
Scale parameter, a positive real number, defaults to 1. |
Details
A C++ version of this function is available. See vignette('IBMPopSim_cpp')
for more details.
Value
The Weibull density function dweibull
with shape parameter k
and scale parameter lambda
, see dweibull
.