Simulation

alles aus setup folder configuration des sim objects

Overview Structs

Overview Functions

Simulation

Struct

GEMS.SimulationType
Simulation

A struct for the management of a single run, holding all necessary informations.

Initialization

Simulation(; kwargs...)
Simulation(params::Dict)

You can initialize a simulation without any parameters, which will then use the default configuration file. Providing any additional keyword arguments will override the respective configuration file parameter. If you provide a custom config file, the parameters in the config file will be used as defaults and only the provided keyword arguments will override them.

Here's a list of all available parameters:

ParameterTypeDescription
configfileStringPath to the configuration file. If not provided, the default configuration will be used.
tickunitCharTime unit of one simulation step (tick). Must be one of 'h' (hours), 'd' (days), or 'w' (weeks).
start_dateDateStart date of the simulation.
end_dateDateEnd date of the simulation.
labelStringLabel used for plot visualizations and aggregating simulations into batches.
populationString, Population, or DataFramePath to a population file, a population identifier (e.g., 'DE'), a Population object, or a DataFrame.
pop_sizeIntSize of the population to be created. Will be ignored if a population is provided.
avg_household_sizeFloatAverage household size for the population to be created. Will be ignored if a population is provided.
avg_office_sizeFloatAverage office size for the population to be created. Will be ignored if a population is provided.
avg_school_sizeFloatAverage school size for the population to be created. Will be ignored if a population is provided.
global_settingBoolFlag indicating whether to use the global setting.
settingsfileStringPath to a settings file.
household_contactsContactSamplingMethod or FloatMethod for sampling household contacts or a fixed value that will be regarded as the expected value of a Poisson distribution.
office_contactsContactSamplingMethod or FloatMethod for sampling office contacts or a fixed value that will be regarded as the expected value of a Poisson distribution.
department_contactsContactSamplingMethod or FloatMethod for sampling department contacts or a fixed value that will be regarded as the expected value of a Poisson distribution.
workplace_contactsContactSamplingMethod or FloatMethod for sampling workplace contacts or a fixed value that will be regarded as the expected value of a Poisson distribution.
workplace_site_contactsContactSamplingMethod or FloatMethod for sampling workplace site contacts or a fixed value that will be regarded as the expected value of a Poisson distribution.
school_class_contactsContactSamplingMethod or FloatMethod for sampling school class contacts or a fixed value that will be regarded as the expected value of a Poisson distribution.
school_year_contactsContactSamplingMethod or FloatMethod for sampling school year contacts or a fixed value that will be regarded as the expected value of a Poisson distribution.
school_contactsContactSamplingMethod or FloatMethod for sampling school contacts or a fixed value that will be regarded as the expected value of a Poisson distribution.
school_complex_contactsContactSamplingMethod or FloatMethod for sampling school complex contacts or a fixed value that will be regarded as the expected value of a Poisson distribution.
municipality_contactsContactSamplingMethod or FloatMethod for sampling municipality contacts or a fixed value that will be regarded as the expected value of a Poisson distribution.
global_setting_contactsContactSamplingMethod or FloatMethod for sampling global setting contacts or a fixed value that will be regarded as the expected value of a Poisson distribution. Requires global_setting to be true.
start_conditionStartConditionA StartCondition object defining the initial situation of the simulation.
infected_fractionFloatFraction of the population to be initially infected. Will be ignored if a start_condition is provided.
stop_criterionStopCriterionA StopCriterion object defining the termination condition of the simulation.
pathogensTupleA Tuple of Pathogens to be simulated.
transmission_functionTransmissionFunctionA TransmissionFunction object defining the transmission dynamics of the pathogen. Will be ignored if a pathogen is provided.
transmission_rateFloatA fixed transmission rate that will be used to create a ConstantTransmissionRate transmission function. Will be ignored if a pathogen or transmission_function is provided.
stepmodFunctionA single-argument function that runs custom code on the simulation object in each tick.

Examples

# Initialize a simulation with default configuration
sim = Simulation()

# Initialize a simulation with a custom configuration file
sim = Simulation(configfile="path/to/configfile.toml")

# Initialize a simulation with custom parameters
sim = Simulation(
    tickunit='d',
    label="My Simulation",
    avg_household_size=5,
)

# Initialize a simulation with a predefined population model
sim = Simulation(population="SH") # Schleswig-Holstein, Germany

# Initialize a simulation with a custom population file
sim = Simulation(population="path/to/populationfile.csv")

# Initialize a simulation with a custom start condition
sim = Simulation(start_condition=PatientZero()) # starts with a single infected individual

# Initialize a simulation with a custom transmission rate
sim = Simulation(transmission_rate=0.1) # sets a constant per-contact transmission rate (chance) of 0.1

# Initialize a simulation with a parameter dictionary
params = Dict(
    :tickunit => 'd',
    :label => "My Simulation",
    :avg_household_size => 5,
)
sim = Simulation(params)

Internal Simulation Struct Fields

  • Data Sources
    • configfile::String: Path to config file
  • General
    • tick::Int16: Current tick/timestep
    • tickunit::Char: Time unit of one simulation step (tick)
    • startdate::Date: Start date of the simulation
    • enddate::Date: End date of the simulation
    • start_condition::StartCondition: Starting condition that sets the initial situation
    • stop_criterion::StopCriterion: Criterion that terminates a simulation run
    • label::String: Label for plot visualizations
  • Model
    • population::Population: Container to hold all present individuals
    • settings::SettingsContainer: All settings present in the simulation
    • pathogens::Tuple: A Tuple of Pathoges of which infections are simulated
  • Logger
    • infectionlogger::InfectionLogger: A logger tracking all infections
    • deathlogger::DeathLogger: A logger specifically for the deaths of individuals
    • testlogger::TestLogger: A logger tracking all individual tests
    • pooltestlogger::PoolTestLogger: A logger tracking all pool tests
    • seroprevalencelogger::SeroprevalenceLogger: A logger tracking all seroprevalence tests
    • quarantinelogger::QuarantineLogger: A tracking cumulative quarantines per tick
    • customlogger::CustomLogger: A logger running custom methods on the Simulation object in each tick
  • Interventions
    • symptom_triggers::Vector{ITrigger}: List of all SymptomTriggers
    • tick_triggers::Vector{TickTrigger}: List of all TickTriggers
    • hospitalization_triggers::Vector{ITrigger}: List of all HospitalizationTriggers
    • event_queue::EventQueue: Event Queue to apply intervention measures
    • strategies::Vector{Strategy}: List of all registered intervention strategies
    • testtypes::Vector{AbstractTestType}: List of all TestTypes (e.g. Antigen- or PCR-Test)
  • Runtime Modifiers
    • stepmod::Function: Single-argment function that runs custom code on the simulation object in each tick
  • RNG
    • seed::Int64: Seed used to initialize the main RNG
    • rngs::Vector{Xoshiro}: RNG instances for each thread

Functions

GEMS.add_strategy!Function
add_strategy!(simulation, strategy)

Adds an intervention Strategy to the simulation object. A strategy must be added to the simulation object to make it appear in the report. In order to execute a strategy during the simulation run, you must define a Trigger and link this strategy. Just adding it here will not execute the strategy.

GEMS.add_testtype!Function
add_testtype!(simulation, testtype)

Adds a test type to the simulation.

GEMS.add_tick_trigger!Function
add_tick_trigger!(simulation, trigger)

Adds a TickTrigger to the simulation.

GEMS.agsMethod
ags(patientzeros::PatientZeros)::Vector{Int64}

Returns the vector of ags where intial seeds should be planted.

GEMS.configfileMethod
configfile(simulation)

Returns configfile that was used to initialize simulation.

GEMS.customlogger!Method
customlogger!(simulation, customlogger)

Sets the Simulation's CustomLogger.

GEMS.customloggerMethod
customlogger(simulation)

Returns the CustomLogger of the simulation.

GEMS.customlogsFunction
customlogs(simulation::Simulation)

Calls the dataframe() function on the internal simulation's CustomLogger.

GEMS.deathsMethod
deaths(simulation::Simulation)

Calls the dataframe() function on the internal simulation's DeathLogger.

GEMS.deathloggerMethod
deathlogger(simulation)

Returns the DeathLogger of the simulation.

GEMS.event_queueMethod
event_queue(simulation)

Returns the simulation's intervention event queue.

Missing docstring.

Missing docstring for fire_custom_loggers!(::Simulation). Check Documenter's build log for details.

GEMS.fractionMethod
fraction(infectedFraction::InfectedFraction)

Returns fraction of individuals that shall be infected at the beginning using the InfectedFraction start condition.

GEMS.hospitalization_triggersMethod
hospitalization_triggers(simulation)

Returns the list of HospitalizationTriggers registered in the simulation.

GEMS.incidenceFunction
incidence(simulation::Simulation, pathogen::Pathogen, base_size::Int = 100_000, duration::Int16 = Int16(7))

Returns the incidence at a particular pathogen and a point in time (current simulation tick). The duration defines a time-span for which the incidence is measured (default: 7 ticks). The base_size provides the population size reference (default: 100_000 individuals)

Parameters

  • simulation::Simulation: Simulation object
  • pathogen::Pathogen: Pathogen for which the incidence shall be calculated
  • base_size::Int = 100_000 (optional): Reference population size for incidence calculation
  • duration::Int16 = Int16(7) (optional): Reference duration (in ticks) for the incidence calculation

Returns

  • Float64: Incidence
incidence(simulation::Simulation, pathogen_id::Int8, base_size::Int = 100_000, duration::Int16 = Int16(7))

Convenience wrapper to calculate incidence using a pathogen ID.

incidence(simulation::Simulation, pathogen_name::String, base_size::Int = 100_000, duration::Int16 = Int16(7))

Convenience wrapper to calculate incidence using a pathogen name.

Missing docstring.

Missing docstring for increment!(::Simulation). Check Documenter's build log for details.

GEMS.infectionloggerMethod
infectionlogger(simulation)

Returns the InfectionLogger of the simulation.

GEMS.infectionsMethod
infections(simulation::Simulation)

Calls the dataframe() function on the internal simulation's InfectionLogger.

GEMS.infoMethod
info(sim::Simulation)

Summary output for Simulation object configuration.

GEMS.intervalFunction
interval(trigger::TickTrigger)

Returns the interval associated with a TickTrigger.

GEMS.labelMethod
label(simulation::Simulation)

Returns simulation object's string label.

GEMS.limitFunction
limit(criterion::StopCriterion)

Returns the maximum number of ticks for the criterion, or nothing if the criterion does not have a fixed limit.

limit(timesUp::TimesUp)

Returns time limit of a timesUp stop criterion.

Missing docstring.

Missing docstring for parameters. Check Documenter's build log for details.

Missing docstring.

Missing docstring for pathogen!(::Simulation, ::Pathogen). Check Documenter's build log for details.

GEMS.pathogenFunction
pathogen(sim::Simulation)

Returns the single pathogen in the simulation. Throws an ArgumentError if the simulation contains more than one pathogen; use pathogens(sim) or get_pathogen(sim, id) in that case.

pathogen(importedCases::ImportedCases)

Returns the pathogen used to seed the imported cases.

pathogen(infectedFraction::InfectedFraction)

Returns pathogen used to infect individuals at the beginning using the InfectedFraction start condition.

pathogen(patientzero::PatientZero)

Returns pathogen used to infect individuals at the beginning in this start condition.

pathogen(patientzeros::PatientZeros)

Returns pathogen used to infect individuals at the beginning in this start condition.

pathogen(regionalseeds::RegionalSeeds)

Returns pathogen used to infect individuals at the beginning using the RegionalSeeds start condition.

GEMS.pooltestsFunction
pooltests(simulation::Simulation)

Calls the dataframe() function on the internal simulation's PoolTestLogger.

GEMS.pooltestloggerFunction
pooltestlogger(simulation)

Returns the PoolTestLogger of the simulation.

GEMS.populationMethod
population(simulation)

Returns the population associated with the simulation run.

GEMS.populationDFMethod
populationDF(simulation::Simulation)

Calls the dataframe() function on the simulation's Population object.

GEMS.populationfileMethod
populationfile(simulation)

Returns populationfile that was used to initialize simulation.

Missing docstring.

Missing docstring for process_events!. Check Documenter's build log for details.

GEMS.quarantineloggerMethod
quarantinelogger(simulation)

Returns the QuarantineLogger of the simulation.

GEMS.quarantinesFunction
quarantines(simulation::Simulation)

Calls the dataframe() function on the internal simulation's QuarantineLogger.

Missing docstring.

Missing docstring for remove_empty_settings!(::Simulation). Check Documenter's build log for details.

GEMS.reset!Method
reset!(simulation::Simulation; reset_interventions::Bool = false)

Resets the simulation model to its initial state according to its start condition. This resets all individuals, loggers, the event queue, tick, and RNGs, and re-applies the start condition. If reset_interventions is true (default), all intervention triggers and strategies are also cleared.

GEMS.region_infoMethod
region_info(sim::Simulation)

Returns a DataFrame containing information about the Municipalitys in the model with the following columns:

NameTypeDescription
agsAGSAmtlicher Gemeindeschlüssel (Community Identification Code)
pop_sizeInt64Number of individuals in that municipality
areaFloat64Area size of this municipality in km²

Note: This function will download the Germany shapefile, if it's not available locally, and return missing values for pop_size and area if the download cannot be completed.

GEMS.rngMethod
rng(simulation::Simulation)

Returns the thread-local RNG associated with the simulation run. This way, rng(simulation) can be called inside multi-threaded code to get the correct RNG for the current thread.

GEMS.run!Method
run!(simulation::Simulation; with_progressbar::Bool = true)

Takes and initializes Simulation object and calls the stepping function (step!) until the stop criterion is met.

Returns

  • Simulation: Simulation object
GEMS.seroprevalencetestsMethod
seroprevalencetests(simulation::Simulation)

Calls the dataframe() function on the internal simulation's SeroprevalenceLogger.

GEMS.settingsMethod
settings(simulation::Simulation)

Returns a dictionary containing all settings, separated by setting type (key).

Missing docstring.

Missing docstring for settings(::Simulation, ::DataType). Check Documenter's build log for details.

GEMS.settingscontainerMethod
settingscontainer(simulation::Simulation)

Returns the container object of all settings of the simulation.

GEMS.should_fireFunction
should_fire(trigger::TickTrigger, tick::Int16)

Evaluates whether a trigger should be fired at a given tick. Considers switch_tick and interval.

Returns

  • Bool: True, if the trigger should fire at this tick. False otherwise.
should_fire(trigger::TickTrigger, sim::Simulation)

Evaluates whether a trigger should be fired in the given simulation at its current tick. Considers switch_tick, interval, and the trigger's trigger-level condition.

Returns

  • Bool: True, if the trigger should fire now. False otherwise.
GEMS.start_conditionFunction
start_condition(simulation)

Returns start condition associated with the simulation run.

start_condition(rd::ResultData)

Returns the StartCondition object the simulation was initialized with. Returns an empty dictionary if the data is not available in the input ResultData object.

GEMS.stateloggerMethod
statelogger(simulation)

Returns the StateLogger of the simulation.

GEMS.statesMethod
states(simulation::Simulation)

Calls the dataframe() function on the internal simulation's StateLogger.

GEMS.step!Function
step!(simulation::Simulation)

Increments the simulation status by one tick and executes all events that shall be handled during this tick.

GEMS.stepmodFunction
stepmod(simulation::Simulation)

Returns the defined step mod.

GEMS.stop_criterionMethod
stop_criterion(simulation)

Returns stop criterion associated with the simulation run.

GEMS.strategiesMethod
strategy(simulation)

Returns the intervention Strategys registered in the simulation.

GEMS.symptom_triggersMethod
symptom_triggers(simulation)

Returns the list of SymptomTriggers registered in the simulation.

GEMS.testloggerMethod
testlogger(simulation)

Returns the TestLogger of the simulation.

GEMS.testsMethod
tests(simulation::Simulation)

Calls the dataframe() function on the internal simulation's TestLogger.

GEMS.testtypesMethod
testtypes(simulation)

Returns the test types registered in the simulation.

GEMS.tickMethod
tick(simulation)

Returns current tick of the simulation run.

GEMS.tick_triggersMethod
tick_triggers(simulation)

Returns the list of TickTriggers registered in the simulation.

GEMS.tickunitMethod
tickunit(simulation)

Returns the unit of the ticks as a char like in date formats, i.e. 'd' means days, 'h' mean hours, etc.

Start Conditions

Structs

GEMS.InfectedFractionType
InfectedFraction <: StartCondition

A StartCondition that specifies a fraction of infected individuals (drawn at random).

Fields

  • fraction::Float64: A fraction of the whole population that has to be infected
  • pathogen::String: Pathogen to infect the fraction with; empty string = the only pathogen, ALL_PATHOGENS = every pathogen (each infecting its own fraction)

Example

condition = InfectedFraction(fraction=0.05) # 5% of the population infected at random
sim = Simulation(start_condition = condition)
GEMS.PatientZeroType
PatientZero <: StartCondition

A StartCondition that infects a single individual at random at the beginning of the simulation.

Fields

  • pathogen::String: Pathogen to infect the individual with; empty string = the only pathogen, ALL_PATHOGENS = every pathogen (one individual each)

Example

condition = PatientZero() # single individual infected at random
sim = Simulation(start_condition = condition)
GEMS.PatientZerosType
PatientZeros <: StartCondition

A StartCondition that infects a single individual in each of the given AGS (community identification numbers) at the beginning of the simulation.

Fields

  • pathogen::String: Pathogen to infect the individuals with; empty string = the only pathogen, ALL_PATHOGENS = every pathogen
  • ags::Vector{Int64}: A vector of AGS (community identification number) where the initial seeds should be planted

Example

# single individual infected at random in regions 13003000 and 13076033
# needs to be used with a population that contains these regions, e.g., "MV"
condition = PatientZeros(ags=[13003000, 13076033]) 
sim = Simulation(population = "MV", start_condition = condition)
GEMS.RegionalSeedsType
RegionalSeeds <: StartCondition

A StartCondition that infects the provided number of individual at the beginning (drawn at random) in the regions provided by their AGS (community identification number).

Fields

  • pathogen::String: Pathogen to infect the individual(s) with; empty string = the only pathogen, ALL_PATHOGENS = every pathogen
  • seeds::Dict{Int64, Int64}: Dict that holds {AGS, NUMBER} pairs specifying the regions and the respective number of individuals that shall be infected at initialization.

Example

# 5 and 7 individuals infected at random in regions 13003000 and 13076033
# needs to be used with a population that contains these regions, e.g., "MV"
condition = RegionalSeeds(seeds = Dict(13003000=>5, 13076033=>7))
sim = Simulation(population = "MV", start_condition = condition)
GEMS.ImportedCasesType
ImportedCases <: StartCondition

A StartCondition that seeds infections at scheduled ticks during the run, modelling importation of cases. initialize! only stages the schedule; seed_scheduled! executes each import at its tick.

The three dimensions of an import schedule are independent, and each accepts several forms:

Fields

  • pathogen::String: Pathogen to seed with; empty string = the only pathogen, ALL_PATHOGENS = every pathogen
  • ticks: when imports happen
    • Integer: a single import at that tick
    • AbstractVector{<:Integer}: exactly these ticks (ranges included); a repeated tick schedules several imports on it
    • Function: f(sim) returning the ticks, resolved during initialize!
    • NamedTuple: window form (start_tick =, stop_tick =, interval =, offset =), where interval (gap between imports) and offset (gap from start_tick to the first import, default 0) are each a number or a Distribution
  • count: how many individuals each import infects. An import sized below 1 is skipped, so a 0 entry keeps a per-import vector aligned with its ticks without seeding anything.
    • Integer: the same number every time
    • AbstractVector{<:Integer}: one entry per import
    • Distribution: drawn per import
    • Function: f(sim, tick) returning an integer
  • ags: where the imports land; nothing seeds from the whole population
    • Integer: the same region every time
    • AbstractVector{<:Integer}: one region per import
    • Function: f(sim, tick) returning a community identification number

A vector ags has no way of saying "whole population" for individual entries. Combine several ImportedCases in a MultiStartCondition for mixed regional/nationwide schedules.

Each form is normalized by _ticks_spec/_count_spec/_region_spec at construction and evaluated by _resolve_ticks/_resolve_count/_resolve_region during initialize!. Both halves of a dimension live in the same section below, so a new form is added in one place.

Example

# 3 individuals every 7 ticks, from tick 30 to 200
condition = ImportedCases(count = 3, ticks = 30:7:200)

# the same, written as a window (the form config files use)
condition = ImportedCases(count = 3, ticks = (start_tick = 30, stop_tick = 200, interval = 7))

# a Poisson import process: on average one import every 10 ticks, 2 individuals each
condition = ImportedCases(count = 2,
    ticks = (start_tick = 30, stop_tick = 200, interval = Exponential(10), offset = Exponential(10)))

# two regions on the same tick, with per-import counts
condition = ImportedCases(ticks = [10, 10, 20], count = [5, 3, 1],
    ags = [13003000, 13076033, 13003000])

sim = Simulation(start_condition = condition)

Functions

GEMS.initialize!Function
initialize!(simulation::Simulation, condition::StartCondition; kwargs...)

Initializes the simulation model according to a provided start condition. This is an 'abstract' function that must be implemented for concrete start condition types.

initialize!(simulation)

Initializes the simulation model with a provided start condition.

initialize!(simulation::Simulation, condition::ImportedCases)

Resolves the import schedule and stages one InfectionSeed per import in simulation.seeding_schedule; seeds nothing here (see seed_scheduled!).

initialize!(simulation::Simulation, condition::InfectedFraction; seed_sample::Union{Int64,Nothing}=nothing)

Initialize the simulation model with a fraction of infected individuals, provided by the start condition. For sampling the individuals to infect, a new Xoshiro RNG is created. If seed_sample is nothing (default), the seed is drawn from rng(simulation). Otherwise, the provided seed_sample is used.

initialize!(simulation::Simulation, condition::PatientZero)

Initialize the simulation model by infecting a single individual at random at the beginning of the simulation.

initialize!(simulation::Simulation, condition::PatientZeros)

Initializes the simulation model, infecting a single individual in each of the regions provided by their AGS (community identification number).

initialize!(simulation::Simulation, condition::RegionalSeeds; seed_sample::Union{Int64,Nothing}=nothing)

Initializes the simulation model, infecting the number of individuals in the regions, both provided by the RegionalSeeds start condition. Regions can be specified as states, counties or municipalities.

It would also be possible to provide, e.g., a municiaplity AND its surrounding county. In that case, an individual could be sampled twice. This function will not prevent that but throw a warning.

GEMS.seedsFunction
seeds(regionalseeds::RegionalSeeds)

Returns the dictionary holding the {AGS, NUMBER} pairs, specifying the regions (via community identification number (AGS)) and the number of initial infections using the RegionalSeeds start condition.

Stop Criteria

Structs

GEMS.NoneInfectedType
NoneInfected <: StopCriterion

A StopCriterion that stops the simulation once no individual is infected.

GEMS.TimesUpType
TimesUp <: StopCriterion

A StopCriterion that specifies a time limit.

Fields

  • limit::Int16: A time limit. When reached, the simulation should be terminated.

Ticks are stored as Int16, so limit (and the reachable tick range in general) cannot exceed typemax(Int16) (32767)n

Functions

GEMS.evaluateFunction
evaluate(simulation::Simulation, criterion::StopCriterion)

Evaluates whether the specified stop criterion is met for the simulation model. Return True if criterion was met. This is an 'abstract' function that must be implemented for concrete criterion types.

evaluate(simulation, criterion)

Returns true if none of the individuals are infected.

evaluate(simulation::Simulation, criterion::TimesUp)

Returns true if specified termination tick has been met.