API Reference

Simulation

Core

Starsim.SimType
Sim

The main simulation object. Holds all modules and orchestrates initialization and execution.

Keyword arguments

  • pars::SimPars — simulation parameters (or keyword overrides)
  • n_agents::Int — number of agents (default 10_000)
  • start::Real — start year (default 0.0)
  • stop::Real — stop year (default 10.0)
  • dt::Real — timestep in years (default 1.0)
  • rand_seed::Int — RNG seed (default 0)
  • networks — network spec (AbstractNetwork, Dict, Vector, or nothing)
  • diseases — disease spec (AbstractDisease, Dict, Vector, or nothing)
  • demographics — demographics spec (AbstractDemographics, Dict, Vector, or nothing)
  • interventions — intervention spec (or nothing)
  • analyzers — analyzer spec (or nothing)
  • connectors — connector spec (or nothing)

Example

n_contacts = 10
beta = 0.5 / n_contacts

sim = Sim(
    n_agents = 1000,
    networks = RandomNet(n_contacts=n_contacts),
    diseases = SIR(beta=beta, dur_inf=4.0, init_prev=0.01),
    stop = 40.0,
)
run!(sim)
Starsim.SimParsType
SimPars

Standard simulation parameters.

Fields

  • n_agents::Int — number of agents (default 10_000)
  • start::Float64 — simulation start time in years (default 0.0)
  • stop::Float64 — simulation end time in years (default 10.0)
  • dt::Float64 — timestep in years (default 1.0)
  • rand_seed::Int — RNG seed (default 0)
  • pop_scale::Float64 — population scaling factor (default 1.0)
  • use_aging::Bool — whether agents age each timestep (default true)
  • verbose::Int — output verbosity (default 1)

Example

pars = SimPars(n_agents=5000, dt=1/12, stop=2030.0)
Starsim.ParsType
Pars <: AbstractDict{Symbol, Any}

Ordered parameter dictionary with smart merge semantics. Nested updates handle AbstractStarsimDist, AbstractTimePar, and sub-module parameters.

Example

p = Pars(:beta => 0.05, :dur_inf => years(10))
update!(p, :beta => 0.1)
Starsim.demoFunction
demo(; n_agents=1000, verbose=0, kwargs...)

Run a quick SIR demo simulation. Equivalent to Python's ss.demo().

Example

sim = demo()

Running

Starsim.init!Function
init!(sim::Sim)

Initialize the simulation. Follows Python starsim's 10-step init:

  1. Initialize people
  2. init_pre! all modules (registers states, sets up timelines)
  3. init_post! all modules (seed infections, etc.)
  4. Build integration loop
  5. Initialize results

Returns sim for chaining.

Starsim.run!Function
run!(sim::Sim; verbose=nothing, backend=:cpu)

Run the simulation. Initializes first if needed. Returns sim for chaining.

Keywords

  • verbose::Union{Int, Nothing} — override the sim's verbosity level
  • backend::Symbol — execution backend:
    • :cpu (default) — standard CPU execution
    • :gpu / :auto — use the single loaded GPU backend extension
    • :metal — Apple Silicon GPU backend (requires using Metal)
    • :cuda — NVIDIA GPU backend (requires using CUDA)
    • :amdgpu — AMD GPU backend (requires using AMDGPU)

Examples

# CPU (default)
sim = Sim(diseases=SIR(beta=0.1)) |> run!

# GPU — choose automatically if exactly one backend is loaded
sim = Sim(n_agents=1_000_000, diseases=SIR(beta=0.05),
          networks=RandomNet(n_contacts=10))
run!(sim; backend=:gpu)
run!(msim::MultiSim; parallel=true, verbose=0)

Run all simulations. When parallel=true and Julia was started with multiple threads (julia -t N), uses Threads.@threads for true parallel execution — unlike Python starsim which is limited by the GIL.

Thread safety

Each sim has independent state (people, RNG, networks), so parallel runs are fully thread-safe and deterministic.

run!(scenarios::Scenarios; verbose=1, parallel=true)

Run all scenario simulations. Each scenario's MultiSim is run sequentially, but simulations within each MultiSim are parallelized across threads.

run!(calib::Calibration; verbose::Int=1)

Run calibration using random search (simple derivative-free optimization).

Starsim.reset!Function

Reset timeline to the start.

reset!(sim::Sim)

Reset the simulation to its pre-run state. Allows re-running with different seeds or parameters.

Results access

Starsim.to_dataframeFunction
to_dataframe(res::Results, timevec::Vector{Float64})

Convert results to a DataFrame with a time column.

to_dataframe(il::InfectionLog; disease::Union{Nothing, Symbol}=nothing)

Convert infection log to a DataFrame. If disease is specified, return only that disease's log; otherwise concatenate all diseases.

to_dataframe(sim::Sim)

Convert all simulation results to a single DataFrame.

Starsim.get_resultFunction
get_result(sim::Sim, module_name::Symbol, result_name::Symbol) → Vector{Float64}

Get a specific result from any module by name.

get_result(sim::Sim, result_name::Symbol) → Vector{Float64}

Get a sim-level result.

Starsim.all_modulesFunction
all_modules(sim::Sim)

Iterate over all modules in the simulation in order: networks, demographics, diseases, connectors, interventions, analyzers. Returns pairs of (name, module).

Starsim.summarizeFunction
summarize(res::Results)

Compute summary statistics for each result based on its summarize_by field.

summarize(sim::Sim)

Compute summary statistics for all results. Matches Python starsim's sim.summarize().

For each result, the aggregation method depends on the result name prefix:

  • n_* → mean over time
  • new_* → mean over time
  • cum_* → last value
  • prevalence → mean over time
  • otherwise → mean over time

Returns an OrderedDict{Symbol, Float64}.

Example

sim = Sim(diseases=SIR(beta=0.05)); run!(sim)
summary = summarize(sim)

Serialization

Starsim.save_simFunction
save_sim(filename::AbstractString, sim::Sim)

Save a simulation to disk using Julia's Serialization module. Matches Python starsim's sim.save() (which uses gzipped pickle).

Arguments

  • filename — path to save to (.jls extension recommended)
  • sim — the Sim object to save

Example

sim = Sim(diseases=SIR(beta=0.05))
run!(sim)
save_sim("my_sim.jls", sim)
Starsim.load_simFunction
load_sim(filename::AbstractString) → Sim

Load a simulation from disk. Inverse of save_sim.

Example

sim = load_sim("my_sim.jls")
Starsim.to_jsonFunction
to_json(sim::Sim; keys=[:pars, :results])

Export simulation parameters and/or results as a JSON-compatible Dict. Matches Python starsim's sim.to_json().

Arguments

  • keys — which sections to include: :pars, :results, or both

Returns

A Dict{String, Any} suitable for JSON serialization.

Example

sim = Sim(diseases=SIR(beta=0.05)); run!(sim)
d = to_json(sim)                   # Dict with pars + results
to_json(sim; filename="sim.json")  # write to file
Starsim.shrink!Function
shrink!(sim::Sim; in_place::Bool=true)

Remove bulky data (people arrays, loop plan) to reduce memory usage. Matches Python starsim's sim.shrink().

After shrinking, the simulation cannot be re-run or have its people queried, but results are preserved.

If in_place=false, returns a shrunken copy instead of modifying sim.

Example

sim = Sim(diseases=SIR()); run!(sim)
shrink!(sim)

Comparison

Starsim.diff_simsFunction
diff_sims(sim1::Sim, sim2::Sim; keys=nothing) → Dict{Symbol, NamedTuple}

Compare two completed simulations and return a Dict mapping each shared result key to (max_diff=…, mean_diff=…). If keys is provided, only those result keys are compared.

Example

d = diff_sims(sim1, sim2)
d[:sir_prevalence].max_diff
Starsim.check_sims_matchFunction
check_sims_match(sim1::Sim, sim2::Sim; rtol=0.01, atol=1e-8) → Bool

Check if two simulations match within tolerance. Prints mismatches and returns true if all shared results match.

Starsim.mock_simFunction
mock_sim(; n_agents=100, kwargs...) → Sim

Create a minimal SIR simulation for testing purposes.

Example

sim = mock_sim()
run!(sim; verbose=0)

People

Starsim.PeopleType
People

The agent population. Stores all agent states and manages the active UID set. Parametric design allows different array backends.

Built-in states

  • uid — unique agent identifiers
  • slot — RNG slot indices
  • alive — life status
  • age — agent age in years
  • female — biological sex
  • ti_dead — scheduled death time
  • ti_removed — removal time
  • scale — per-agent scaling factor
  • parent — parent UID (for births)

Example

people = People(10_000)
init_people!(people)
Starsim.init_people!Function
init_people!(people::People; use_aging::Bool=true, rand_seed::Int=12345)

Initialize the People object with n_agents_init agents. Uses rand_seed to generate per-seed variation in age and sex assignments, matching Python's slot-based RNG which produces different populations per seed.

Starsim.add_module_state!Function
add_module_state!(people::People, state::StateVector)

Register a module's state with the People object so it is grown on births.

Starsim.grow!Function
grow!(s::StateVector{T}, new_uids::UIDs; new_vals=nothing) where T

Extend the state array to accommodate new agents. Uses 50% over-allocation to amortize resize cost, matching the Python strategy.

Arguments

  • new_uids — UIDs of the new agents
  • new_vals — optional values to assign (otherwise uses default)
grow!(people::People, n::Int; parent_uids::Union{UIDs, Nothing}=nothing)

Add n new agents (births/immigration). Returns UIDs of new agents.

When CRN is enabled (slot_scale > 0), newborn slots are drawn from Uniform(N_init, slot_scale * N_init) to avoid sequential assignment and maintain CRN invariance. If parent_uids are provided and CRN is enabled, the slot RNG is seeded per-parent for reproducibility.

Starsim.request_death!Function
request_death!(people::People, death_uids::UIDs, ti::Int)

Schedule deaths for the given UIDs at the current timestep.

Starsim.finish_step!Function
finish_step!(people::People, dt::Float64, use_aging::Bool)

Remove dead agents from active UIDs, age the population.

finish_step!(mod::AbstractModule, sim)

Post-step cleanup, advance module time.

States and UIDs

UIDs

Starsim.UIDsType
UIDs{A<:AbstractVector{Int}} <: AbstractVector{Int}

Sorted vector of agent unique identifiers. Supports set operations (intersect, union, setdiff, symdiff) and concatenation.

Constructors

UIDs()                     # empty
UIDs([1, 3, 5])            # from vector
UIDs(1:10)                 # from range

State vectors

Starsim.StateVectorType
StateVector{T, A<:AbstractVector{T}} <: AbstractState

Wraps a raw array of agent data with active-UID views and dynamic growth.

The raw field stores data for all agents (including dead/removed). The values property returns only data for currently active agents, filtered by auids (active UIDs).

Fields

  • name::Symbol — state name (e.g., :infected)
  • label::String — human-readable label
  • default — default value for new agents (scalar, function n -> values, or Distribution)
  • nan_val — sentinel for missing data
  • raw::A — underlying array (all agents, including dead)
  • len_used::Int — number of populated slots
  • len_tot::Int — total allocated capacity
  • auids_ref::Ref — reference to the active UIDs (shared with People)
  • initialized::Bool

Indexing

  • state[i::Int] — index into values (active agents)
  • state[u::UIDs] — index into raw by UID
  • state[b::BoolState] — index by boolean mask → UIDs
Starsim.FloatStateFunction
FloatState(name; label, default, nan_val)

Create a floating-point state array.

Example

age = FloatState(:age; default=0.0, label="Age")
Starsim.IntStateFunction
IntState(name; label, default, nan_val)

Create an integer state array.

Example

n_contacts = IntState(:n_contacts; default=0)
Starsim.BoolStateFunction
BoolState(name; label, default)

Create a boolean state array. BoolStates automatically generate result tracking (e.g., n_infected for a state named :infected).

Example

infected = BoolState(:infected; label="Infected")
Starsim.IndexStateFunction
IndexState(name; label)

Create an index/UID state array (integers, NaN sentinel = INT_NAN). Used for uid and slot arrays that are not regular agent states.

State operations

Starsim.init_state!Function
init_state!(s::StateVector, n::Int, auids_ref)

Initialize a state vector for n agents. Links to the shared auids_ref.

Starsim.init_vals!Function
init_vals!(s::StateVector, uids::UIDs)

Populate state values for the given UIDs using the default field. Handles scalar defaults, callable defaults f(n), and Distributions.

Starsim.uidsFunction
uids(s::StateVector{Bool})

Return UIDs of agents where the boolean state is true (active agents only).

Starsim.false_uidsFunction
false_uids(s::StateVector{Bool})

Return UIDs of active agents where the boolean state is false.

Time

Duration

Starsim.DurationType
Duration{U} <: AbstractDuration

A duration with a time unit. The value is stored in the unit specified, and converted to simulation timestep units via to_dt.

Fields

  • value::Float64 — numeric value in the specified unit
  • unit::Symbol — one of :days, :weeks, :months, :years
Starsim.to_daysFunction
to_days(d::Duration)

Convert a duration to days.

Starsim.to_dtFunction
to_dt(d::Duration, dt::Float64)

Convert a duration to simulation timestep units. dt is the simulation timestep in years.

Rate

Starsim.RateType
Rate <: AbstractRate

A rate parameter with time units. Rates can be converted to per-timestep probabilities via to_prob.

Fields

  • value::Float64 — rate value
  • unit::Symbol — time unit (:perday, :perweek, :permonth, :peryear)
Starsim.to_probFunction
to_prob(r::Rate, dt::Float64)

Convert a rate to a per-timestep probability using the exponential formula: p = 1 - exp(-rate * dt). dt is the simulation timestep in years.

to_prob(val::Real, dt::Float64)

For scalar beta values (already a probability), return as-is multiplied by dt.

Timeline

Starsim.TimelineType
Timeline

Tracks simulation time, providing the time vector, current index, and current time value.

Fields

  • start::Float64 — simulation start (years)
  • stop::Float64 — simulation end (years)
  • dt::Float64 — timestep (years)
  • npts::Int — number of timepoints
  • tvec::Vector{Float64} — time vector
  • ti::Int — current time index (1-based)

Diseases

Data containers

Starsim.InfectionDataType
InfectionData

Additional mutable data for infections (diseases with transmission).

Disease models

Starsim.SIRType
SIR <: AbstractInfection

Standard SIR (Susceptible → Infected → Recovered) disease model.

Keyword arguments

  • name::Symbol — disease name (default :sir)
  • init_prev::Real — initial prevalence (default 0.01)
  • beta::Union{Real, Dict} — transmission rate (default 0.1)
  • dur_inf::Real — mean duration of infection in years (default 6.0)
  • p_death::Real — probability of death given infection (default 0.01)

Example

sir = SIR(beta=0.1, dur_inf=10/365)
Starsim.SISType
SIS <: AbstractInfection

SIS disease model with waning immunity — matching Python starsim's SIS.

After recovery, agents gain temporary immunity (imm_boost) that wanes exponentially at rate waning per year. Agents become re-susceptible as immunity decays (rel_sus = max(0, 1 - immunity)).

Keyword arguments

  • name::Symbol: disease name (default :sis)
  • init_prev::Real: initial prevalence fraction (default 0.01)
  • beta::Union{Real,Dict}: transmission rate per year (default 0.05)
  • dur_inf::Real: mean infectious duration in years (default 10.0)
  • waning::Real: immunity waning rate per year (default 0.05)
  • imm_boost::Real: immunity boost on infection (default 1.0)
  • p_death::Real: probability of death on recovery (default 0.0)
  • recovery_dist::Symbol: duration distribution (:lognormal or :exponential)
Starsim.SEIRType
SEIR <: AbstractInfection

SEIR disease model with an exposed (latent) period before infectiousness. Commonly used for diseases like measles, influenza, and COVID-19.

Keyword arguments

  • name::Symbol — disease name (default :seir)
  • init_prev::Real — initial prevalence of infected (default 0.01)
  • beta::Union{Real, Dict} — transmission rate (default 0.05)
  • dur_exp::Real — mean duration of exposed/latent period (default 5.0 days)
  • dur_inf::Real — mean duration of infectious period (default 10.0 days)
  • p_death::Real — probability of death given infection (default 0.0)

Example

seir = SEIR(beta=0.3, dur_exp=8.0, dur_inf=11.0)  # measles-like

Disease functions

Starsim.infect!Function
infect!(d::SIR, sim)

Compute transmission across all networks. When CRN is enabled and a MultiRandom is available, uses pairwise XOR-combined random numbers for CRN-safe transmission. Otherwise uses the standard per-edge RNG.

Transmission logic for SIS. Uses MultiRandom when CRN is enabled.

infect!(d::SEIR, sim)

Compute transmission. Newly infected agents enter the Exposed state.

Networks

Edge storage

Starsim.EdgesType
Edges

Stores network edges as parallel arrays. Matches Python starsim's Edges class with p1/p2/beta/acts arrays. This is the primary storage format.

Fields

  • p1::Vector{Int} — source agent UIDs
  • p2::Vector{Int} — target agent UIDs
  • beta::Vector{Float64} — per-edge transmission multiplier
  • acts::Vector{Float64} — per-edge acts count for per-act compounding (default 1.0)
Starsim.add_edges!Function

Add edges with beta and acts.

Add edges with beta, default acts=1.

Add edges with default beta=1, acts=1.

Network data

Starsim.network_dataFunction
network_data(net::AbstractNetwork) -> NetworkData

Return the NetworkData for a network. Concrete networks must implement this.

Starsim.net_betaFunction
net_beta(net::AbstractNetwork, disease_beta::Float64)

Compute per-edge beta for transmission. Default: edges.beta .* disease_beta. Override for sexual networks (acts-based).

Network types

Starsim.RandomNetType
RandomNet <: AbstractNetwork

Random contact network. Matches Python ss.RandomNet: creates n_contacts÷2 edges per agent, with bidirectional transmission giving an effective n_contacts contacts per agent.

Note on n_contacts

From Python starsim: "n_contacts = 10 will create 5 edges per agent. Since disease transmission usually occurs bidirectionally, this means the effective number of contacts per agent is actually 10."

Keyword arguments

  • name::Symbol — network name (default :random)
  • n_contacts — mean contacts per agent (default 10); Int, Float64, or AbstractStarsimDist

Example

net = RandomNet(n_contacts=10)
Starsim.MFNetType
MFNet <: AbstractNetwork

Heterosexual partnership network (male-female pairs).

Keyword arguments

  • name::Symbol — default :mf
  • mean_dur::Float64 — mean partnership duration (default 5.0)
  • participation_rate::Float64 — fraction of adults in partnerships (default 0.5)
Starsim.MaternalNetType
MaternalNet <: AbstractNetwork

Mother-child contact network for vertical transmission.

Starsim.MixingPoolType
MixingPool <: AbstractNetwork

Well-mixed population contact model. All agents can potentially infect all others, weighted by a contact rate.

Keyword arguments

  • name::Symbol — default :mixing
  • contact_rate::Float64 — effective contacts per agent per dt (default 10.0)
Starsim.StaticNetType
StaticNet <: AbstractNetwork

Static network initialized from a Graphs.jl graph or generator function. Edges are created once at initialization and do not change.

Keyword arguments

  • name::Symbol — default :static
  • graph_fn — function (n, rng) → SimpleGraph that creates the network
  • n_contacts::Int — mean contacts for Erdős-Rényi default (default 10)

Example

# Erdős-Rényi
net = StaticNet(n_contacts=10)

# Custom graph generator
net = StaticNet(graph_fn=(n, rng) -> watts_strogatz(n, 4, 0.3))
Starsim.MSMNetType
MSMNet <: AbstractNetwork

Men-who-have-sex-with-men partnership network. Pairs only male agents.

Keyword arguments

  • name::Symbol — default :msm
  • participation_rate::Float64 — fraction of males in partnerships (default 0.3)
Starsim.PrenatalNetType
PrenatalNet <: AbstractNetwork

Network for prenatal (mother-to-unborn-child) transmission. Edges are managed by the Pregnancy module — they are added when pregnancy starts and removed at delivery. Matches Python starsim's PrenatalNet.

Keyword arguments

  • name::Symbol — default :prenatal
Starsim.PostnatalNetType
PostnatalNet <: AbstractNetwork

Network tracking postnatal contact between mothers and infants. Edges are added at birth (via Pregnancy module) and persist for a specified duration, after which they are automatically removed. Matches Python starsim's PostnatalNet.

Keyword arguments

  • name::Symbol — default :postnatal
  • dur::Union{Nothing, Float64} — edge duration in timesteps. nothing means edges persist indefinitely.
Starsim.BreastfeedingNetType
BreastfeedingNet <: AbstractNetwork

Network for breastfeeding transmission. Requires a Pregnancy module in the simulation. Edges are added at birth if the mother is breastfeeding and removed when breastfeeding ends. Matches Python starsim's BreastfeedingNet.

Keyword arguments

  • name::Symbol — default :breastfeeding
Starsim.HouseholdNetType
HouseholdNet <: AbstractNetwork

A household contact network. Agents are assigned to households, and all members of the same household form symmetric pairwise contacts. Matches Python starsim's HouseholdNet.

Household data is provided as a DataFrame with columns:

  • hh_id — household identifier
  • ages — comma-separated age strings (e.g. "72, 17, 30")
  • sexes (optional) — comma-separated sex codes (1=male, 2=female)

Keyword arguments

  • name::Symbol — default :household
  • hh_data::Union{Nothing, DataFrame} — household survey data
  • dynamic::Bool — whether households evolve over time (default false)

Example

using DataFrames
hh_data = DataFrame(
    hh_id = 1:3,
    ages = ["30, 5, 2", "45, 20", "60, 55, 30, 10"],
)
net = HouseholdNet(hh_data=hh_data)
sim = Sim(n_agents=100, networks=net, diseases=SIR(beta=0.1))
run!(sim)

Graph interop

Starsim.to_graphFunction
to_graph(e::Edges) -> SimpleGraph{Int}

Create a Graphs.jl SimpleGraph from edges. Useful for graph algorithms (connected components, shortest paths, centrality, etc.).

This is a copy, not a live view — call again after edges change.

Example

g = to_graph(network_edges(net))
components = connected_components(g)
degrees = degree(g)
Starsim.to_digraphFunction
to_digraph(e::Edges) -> SimpleDiGraph{Int}

Create a directed graph from edges (p1 → p2).

Starsim.to_adjacency_matrixFunction
to_adjacency_matrix(e::Edges; n::Int=0, weighted::Bool=false) -> SparseMatrixCSC

Create a sparse adjacency matrix from edges. If weighted, entries are the edge beta values; otherwise binary. Useful for GPU offload and linear-algebra-based transmission.

Example

A = to_adjacency_matrix(network_edges(net); weighted=true)
# GPU: A_gpu = Metal.MtlArray(Matrix(A))
Starsim.to_contact_matrixFunction
to_contact_matrix(e::Edges; n::Int=0) -> Matrix{Float64}

Create a dense contact matrix. Useful for small populations or GPU.

Starsim.from_graph!Function
from_graph!(e::Edges, g::SimpleGraph; beta::Float64=1.0)

Populate edges from a Graphs.jl graph.

Network functions

Starsim.update_edges!Function
update_edges!(net::RandomNet, people::People)

Regenerate random edges for the current timestep. Matches Python starsim's approach: each agent produces n_contacts÷2 half-edges, the full array is shuffled to form (source, target) pairs. Transmission runs bidirectionally over each edge, giving n_contacts effective contacts.

Self-loops are not removed (matching Python starsim). They are harmless because an agent cannot be both infected and susceptible for the same disease.

Starsim.add_pairs!Function
add_pairs!(net::PrenatalNet, mother_uids, unborn_uids)

Add edges between mothers and their unborn children. Called by the Pregnancy module when pregnancies are initiated.

add_pairs!(net::PostnatalNet, mother_uids, infant_uids, ti)

Add edges between mothers and their newborns. Called by the Pregnancy module at delivery.

add_pairs!(net::BreastfeedingNet, mother_uids, infant_uids, ti)

Add breastfeeding edges. Called by the Pregnancy module at delivery.

Demographics

Starsim.BirthsType
Births <: AbstractDemographics

Birth module that adds new agents to the population at a given rate.

Keyword arguments

  • name::Symbol — module name (default :births)
  • birth_rate::Real — annual births per 1000 population (default 20.0)
  • init_age::Real — age of newborns (default 0.0)
  • p_female::Real — probability of female sex (default 0.5)

Example

births = Births(birth_rate=25.0)
Starsim.DeathsType
Deaths <: AbstractDemographics

Background mortality module. Applies age-independent or age-dependent death rates.

Keyword arguments

  • name::Symbol — module name (default :deaths)
  • death_rate::Real — annual deaths per 1000 population (default 10.0)

Example

deaths = Deaths(death_rate=8.0)
Starsim.PregnancyType
Pregnancy <: AbstractDemographics

Pregnancy module — tracks pregnant status and delivery. (Simplified version; full version in FPsim.jl extension.)

Interventions

Products

Starsim.VxType
Vx <: AbstractProduct

Vaccination product — reduces susceptibility.

Keyword arguments

  • name::Symbol — product name (default :vx)
  • efficacy::Float64 — vaccine efficacy (default 0.9)
Starsim.DxType
Dx <: AbstractProduct

Diagnostic product — tests agents and returns results.

Keyword arguments

  • name::Symbol — product name (default :dx)
  • sensitivity::Float64 — probability of true positive (default 1.0)
  • specificity::Float64 — probability of true negative (default 1.0)
Starsim.TxType
Tx <: AbstractProduct

Treatment product — applies treatment effect to agents.

Keyword arguments

  • name::Symbol — product name (default :tx)
  • efficacy::Float64 — treatment efficacy (default 1.0)
Starsim.administer!Function
administer!(dx::Dx, uids::UIDs, disease) → diagnosed::UIDs

Apply diagnostic to agents. Returns UIDs of agents who test positive.

administer!(tx::Tx, uids::UIDs, disease) → treated::UIDs

Apply treatment. Returns UIDs of successfully treated agents.

administer!(vx::Vx, uids::UIDs, disease) → vaccinated::UIDs

Apply vaccine. Reduces rel_sus for susceptible agents.

Delivery mechanisms

Starsim.RoutineDeliveryType
RoutineDelivery <: AbstractIntervention

Routine intervention delivery — applies a product to eligible agents at a specified coverage rate each timestep.

Keyword arguments

  • name::Symbol — intervention name (default :routine)
  • product::AbstractProduct — the product to deliver
  • disease_name::Symbol — target disease (default :sir)
  • prob::Float64 — per-timestep delivery probability (default 0.01)
  • start_year::Float64 — year to start delivering (default 0.0)
  • end_year::Float64 — year to stop delivering (default Inf)
  • eligibility::Function — function(sim, uids) → eligible UIDs (default: all alive)

Example

vx = Vx(efficacy=0.9)
routine = RoutineDelivery(product=vx, prob=0.02, disease_name=:sir)
Starsim.CampaignDeliveryType
CampaignDelivery <: AbstractIntervention

Campaign intervention — delivers a product in specific years to a fraction of the eligible population.

Keyword arguments

  • name::Symbol — intervention name (default :campaign)
  • product::AbstractProduct — the product to deliver
  • disease_name::Symbol — target disease (default :sir)
  • years::Vector{Float64} — years to conduct campaigns
  • coverage::Float64 — fraction of eligible population to cover (default 0.5)
  • eligibility::Function — function(sim, uids) → eligible UIDs

Example

vx = Vx(efficacy=0.95)
campaign = CampaignDelivery(product=vx, years=[2025.0, 2030.0], coverage=0.8)
Starsim.FunctionInterventionType
FunctionIntervention <: AbstractIntervention

A simple intervention that calls a user-provided function each timestep.

Example

iv = FunctionIntervention(fn = (sim, ti) -> begin
    # Custom logic here
end)

Convenience constructors

Starsim.routine_vxFunction

Create a routine vaccination delivery. Matches Python ss.routine_vx().

Starsim.campaign_vxFunction

Create a campaign vaccination delivery. Matches Python ss.campaign_vx().

Intervention data

Starsim.intervention_dataFunction
intervention_data(iv::AbstractIntervention) → InterventionData

Return the InterventionData. Concrete intervention types must implement this.

Connectors

Starsim.connector_dataFunction
connector_data(c::AbstractConnector) → ConnectorData

Return the ConnectorData. Concrete connectors must implement this.

Starsim.SeasonalityType
Seasonality <: AbstractConnector

Modulates disease transmission rates with a seasonal (cosine) curve.

Keyword arguments

  • name::Symbol — connector name (default :seasonality)
  • disease_name::Symbol — target disease (default :sir)
  • amplitude::Float64 — seasonal amplitude (0–1, default 0.3)
  • peak_day::Int — day of year for peak transmission (default 1 = Jan 1)

Example

seas = Seasonality(disease_name=:sir, amplitude=0.5, peak_day=180)
Starsim.CoinfectionConnectorType
CoinfectionConnector <: AbstractConnector

Modifies susceptibility or transmissibility based on coinfection status.

Keyword arguments

  • name::Symbol — connector name
  • disease1::Symbol — first disease
  • disease2::Symbol — second disease
  • rel_sus_if_infected::Float64 — multiplier on disease2 susceptibility if infected with disease1
  • rel_trans_if_infected::Float64 — multiplier on disease1 transmissibility if infected with disease2

Analyzers

Starsim.analyzer_dataFunction
analyzer_data(a::AbstractAnalyzer) → AnalyzerData

Return the AnalyzerData. Concrete analyzers must implement this.

Starsim.FunctionAnalyzerType
FunctionAnalyzer <: AbstractAnalyzer

Analyzer that runs a user-provided function each timestep.

Keyword arguments

  • name::Symbol — analyzer name (default :func_analyzer)
  • fn::Function — function(sim, ti) to call each timestep

Example

tracker = FunctionAnalyzer(fn = (sim, ti) -> begin
    println("Step $ti: n_alive = $(length(sim.people.auids))")
end)
Starsim.SnapshotType
Snapshot <: AbstractAnalyzer

Captures copies of simulation state at specified timepoints.

Keyword arguments

  • name::Symbol — analyzer name (default :snapshot)
  • years::Vector{Float64} — years to capture (default: empty = capture every step)
Starsim.InfectionLogType
InfectionLog <: AbstractAnalyzer

Record transmission chains for each disease. Matches Python starsim's infection_log analyzer — activates infection logging in each disease and collects the results after the simulation completes.

The log stores a Vector{TransmissionEvent} per disease and builds a SimpleDiGraph (from Graphs.jl) of the transmission tree.

Example

sim = Sim(
    n_agents = 1000,
    diseases = SIR(beta=0.1, init_prev=0.05),
    networks = RandomNet(n_contacts=10),
    analyzers = [InfectionLog()],
    stop = 30.0, verbose = 0,
)
run!(sim)
log = sim.analyzers[:infection_log]
log.events[:sir]   # Vector{TransmissionEvent}
log.graph[:sir]    # SimpleDiGraph
to_dataframe(log)  # DataFrame with source, target, t columns
Starsim.TransmissionEventType
TransmissionEvent

A single transmission event recorded in the infection log.

Fields

  • source::Int — UID of infecting agent (0 for seed infections)
  • target::Int — UID of infected agent
  • t::Int — timestep of infection
  • data::Dict{Symbol, Any} — optional extra data (network, etc.)

Distributions

Base types

Starsim.StarsimDistType
StarsimDist{D<:Distribution} <: AbstractStarsimDist

Wraps a Distributions.jl distribution with Starsim-specific RNG management.

Fields

  • dist::D — the underlying distribution
  • name::Symbol — unique name for seeding
  • rng::StableRNG — deterministic RNG
  • seed::UInt64 — seed derived from name + base seed
  • slots::Union{Nothing, StateVector{Int64, Vector{Int64}}} — reference to People's slot array (for CRN)
  • initialized::Bool

Example

d = StarsimDist(:dur_inf, Normal(10.0, 2.0))
init_dist!(d, base_seed=42)
vals = rvs(d, 100)  # draw 100 samples
Starsim.BernoulliDistType
BernoulliDist <: AbstractStarsimDist

Bernoulli distribution wrapper with a filter method that returns UIDs of agents who "pass" the trial. Central to initial prevalence seeding and per-timestep probability sampling.

Example

b = BernoulliDist(:init_prev, 0.01)
init_dist!(b, base_seed=42)
infected_uids = filter(b, all_uids)
Starsim.ConstantDistType
ss_constant(; value)

Constant "distribution" — always returns the same value. Matches Python ss.constant().

Starsim.ChoiceDistType
ss_choice(; a, p)

Random choice from discrete options a with optional probabilities p. Matches Python ss.choice().

Distribution operations

Starsim.init_dist!Function
init_dist!(d::StarsimDist; base_seed::Int=0, trace::String="")

Initialize the distribution's RNG from a deterministic seed derived from the trace path and base seed.

Starsim.jump_dt!Function
jump_dt!(d::StarsimDist, ti::Int)

Jump the RNG to a deterministic state for timestep ti. Ensures reproducibility regardless of call order within a timestep.

Starsim.rvsFunction
rvs(d::StarsimDist, n::Int)

Draw n random values from the distribution.

Example

d = StarsimDist(:test, Normal(0, 1))
init_dist!(d, base_seed=42)
vals = rvs(d, 100)
rvs(d::StarsimDist, uids::UIDs)

Draw random values for the given UIDs. When CRN is enabled and slots are available, draws max(slot)+1 values and indexes by slot, ensuring that adding/removing agents does not shift other agents' draws.

rvs(d::StarsimDist)

Draw a single scalar random value.

rvs(b::BernoulliDist, n::Int)

Draw n Bernoulli samples (returns Bool vector).

Starsim.set_slots!Function
set_slots!(d::StarsimDist, slots::StateVector{Int64, Vector{Int64}})

Link the distribution to the People's slot state for CRN-safe draws.

set_slots!(b::BernoulliDist, slots::StateVector{Int64, Vector{Int64}})

Link the distribution to the People's slot state for CRN-safe draws.

set_slots!(mr::MultiRandom, slots::StateVector{Int64, Vector{Int64}})

Link all underlying distributions to the People's slot state.

CRN multi-random

Starsim.MultiRandomType
MultiRandom <: AbstractStarsimDist

Generates CRN-safe pairwise random numbers for transmission edges. Each dimension (e.g., source, target) has its own independent StarsimDist. Results are combined via XOR to produce a single Uniform(0,1) value per edge.

From the Starsim CRN paper (2409.02086v2): for an edge (i,j), compute u_ij = xor(u_i * u_j, u_i - u_j) / typemax(UInt64) where ui, uj are per-agent random UInt64s. This ensures adding/removing agents doesn't shift randomness for other pairs.

Fields

  • dists::Vector{StarsimDist} — one distribution per dimension (Uniform(0,1))
  • name::Symbol — identifier
  • seed::UInt64 — base seed
  • initialized::Bool

Example

mr = MultiRandom(:transmission)
init_dist!(mr, base_seed=42)
probs = multi_rvs(mr, source_uids, target_uids)
Starsim.combine_rvsFunction
combine_rvs(rvs_list::Vector{Vector{Float64}}) → Vector{Float64}

Combine multiple random-value vectors into a single pseudo-uniform vector using XOR combining. Matches Python starsim's combine_rvs:

  1. Reinterpret each float64 as UInt64 (bit-level)
  2. Compute xor(a * b, a - b) in unsigned integer arithmetic (wrapping)
  3. Normalize by typemax(UInt64)

Arguments

  • rvs_list — vector of Float64 vectors, all the same length

Returns

  • Vector{Float64} — combined values in [0, 1)
Starsim.multi_rvsFunction
multi_rvs(mr::MultiRandom, uid_lists::Vector{UIDs}) → Vector{Float64}

Draw CRN-safe pairwise random values. Each UIDs vector corresponds to one dimension of agents (e.g., sources and targets). Each dimension draws from its own RNG, then results are XOR-combined.

Arguments

  • mr — MultiRandom with one dist per dimension
  • uid_lists — one UIDs vector per dimension, all same length

Returns

  • Vector{Float64} — combined random values in [0, 1)
multi_rvs(mr::MultiRandom, sources::UIDs, targets::UIDs) → Vector{Float64}

Convenience method for 2D pairwise random values (common transmission case).

Distribution constructors

Starsim.bernoulliFunction

Create a Bernoulli distribution for prevalence seeding.

Starsim.ss_randomFunction
ss_random()

Uniform(0, 1) random distribution. Matches Python ss.random().

Starsim.ss_normalFunction
ss_normal(; loc, scale)

Normal distribution wrapper. loc can be Real or Duration.

Starsim.ss_lognormalFunction
ss_lognormal(; mean, sigma)

Lognormal distribution (explicit parameterization via mean and sigma).

Starsim.ss_lognormal_imFunction
ss_lognormal_im(; loc, scale)

Lognormal distribution (implicit parameterization: log-space μ and σ). Matches Python ss.lognorm_im().

Distribution container

Starsim.DistsContainerType
DistsContainer

Collects and manages all AbstractStarsimDist instances across a simulation's module tree. Handles bulk initialization and per-timestep RNG jumping.

Starsim.register_dist!Function
register_dist!(dc::DistsContainer, trace::String, dist::AbstractStarsimDist)

Register a distribution with its trace path for seeding.

Starsim.init_dists!Function
init_dists!(dc::DistsContainer)

Initialize all registered distributions with deterministic seeds.

Starsim.jump_all!Function
jump_all!(dc::DistsContainer, ti::Int)

Jump all distributions to the state for timestep ti.

Results

Starsim.ResultType
Result <: AbstractResult

A single time-series result from a simulation module.

Fields

  • name::Symbol — result name (e.g., :new_infections)
  • label::String — human-readable label
  • module_name::Symbol — owning module
  • values::Vector{Float64} — time-series data
  • scale::Bool — whether to scale by pop_scale during finalization
  • auto_plot::Bool — include in default plots
  • summarize_by::Symbol — aggregation method (:sum, :mean, :last)
Starsim.ResultsType
Results

Ordered dictionary of Result objects for a module or simulation.

Example

res = Results()
push!(res, Result(:prevalence; npts=100, scale=false))
res[:prevalence][1] = 0.05
Starsim.scale_results!Function
scale_results!(res::Results, factor::Float64)

Scale results that have scale=true by the given factor.

Module system

Module data

Starsim.ModuleDataType
ModuleData

Common mutable state carried by every module instance. Stored as a field rather than inherited (Julia uses composition over inheritance).

Fields

  • name::Symbol — short key-like name
  • label::String — human-readable label
  • pars::Pars — module parameters
  • t::Timeline — module-specific timeline (may differ from sim)
  • results::Results — module results
  • states::Vector{StateVector} — registered agent states
  • dists::Vector{AbstractStarsimDist} — registered distributions
  • initialized::Bool
Starsim.module_dataFunction
module_data(mod::AbstractModule) → ModuleData

Return the ModuleData for a module. Every concrete module must implement this.

Starsim.module_nameFunction
module_name(mod::AbstractModule) → Symbol

Return the module's name.

Starsim.module_parsFunction
module_pars(mod::AbstractModule) → Pars

Return the module's parameters.

Starsim.module_resultsFunction
module_results(mod::AbstractModule) → Results

Return the module's results.

Starsim.module_statesFunction
module_states(mod::AbstractModule) → Vector{StateVector}

Return the module's registered states.

Definition helpers

Starsim.define_states!Function
define_states!(mod::AbstractModule, states::StateVector...)

Register agent states with the module. These will be added to People during initialization.

Starsim.define_results!Function
define_results!(mod::AbstractModule, results::Result...)

Register results with the module.

Starsim.define_pars!Function
define_pars!(mod::AbstractModule, pairs::Pair...)

Define default parameters for the module.

Lifecycle methods

Starsim.init_pre!Function
init_pre!(mod::AbstractModule, sim)

Link the module to the simulation, register states with People, initialize distributions. Called during init!(sim).

Starsim.init_post!Function
init_post!(mod::AbstractModule, sim)

Initialize state values after all modules are linked. Called after init_pre! for all modules.

Starsim.init_results!Function
init_results!(mod::AbstractModule)

Initialize result arrays. Called after states are set up.

Starsim.start_step!Function
start_step!(mod::AbstractModule, sim)

Pre-step initialization (jump distributions, etc.).

Starsim.step!Function
step!(mod::AbstractModule, sim)

Main module logic for a single timestep.

Remove expired edges based on duration.

Starsim.step_state!Function
step_state!(mod::AbstractModule, sim)

Disease state transitions (before transmission). Default no-op.

step_state!(d::SIR, sim)

Process state transitions: infected → recovered (or dead).

step_state!(d::SEIR, sim)

Process state transitions: exposed → infected, infected → recovered/dead.

Starsim.step_die!Function
step_die!(people::People, ti::Int, diseases::Vector)

Process deaths: identify who dies, call disease step_die!, mark as dead. Returns UIDs of agents who died.

step_die!(mod::AbstractModule, uids::UIDs)

Handle state changes upon agent death. Default no-op.

Starsim.update_results!Function
update_results!(mod::AbstractModule, sim)

Update module results for the current timestep.

Starsim.finalize!Function
finalize!(mod::AbstractModule)
finalize!(mod::AbstractModule, sim)

Final cleanup after simulation completes. The two-argument form passes the simulation for analyzers that need to collect data from other modules.

finalize!(il::InfectionLog, sim)

Collect infection sources from each disease after simulation completes and build transmission graphs.

Integration loop

Starsim.LoopType
Loop

The integration loop. Holds the ordered list of step entries and executes them in sequence for each timestep.

The 16-step order mirrors Python starsim exactly:

  1. sim.start_step
  2. all modules.start_step
  3. custom.step
  4. demographics.step
  5. diseases.step_state
  6. connectors.step
  7. networks.step
  8. interventions.step
  9. diseases.step (transmission)
  10. people.step_die
  11. people.update_results
  12. all modules.update_results
  13. analyzers.step
  14. all modules.finish_step
  15. people.finish_step
  16. sim.finish_step
Starsim.StepEntryType
StepEntry

A single step in the integration loop: a function to call with the sim. Uses FunctionWrapper instead of bare Function to avoid dynamic dispatch overhead in the inner loop.

Starsim.build_loop!Function
build_loop!(loop::Loop, sim)

Construct the integration loop from the simulation's modules. Follows Python starsim's 16-step integration order exactly.

Starsim.run_loop!Function
run_loop!(loop::Loop, sim; verbose::Int=1)

Execute the integration loop for all timesteps.

MultiSim and scenarios

Starsim.MultiSimType
MultiSim

Run multiple simulations and aggregate results. Uses Julia's native multi-threading for true parallelism (no GIL limitation).

Fields

  • base_sim::Sim — the template simulation
  • sims::Vector{Sim} — vector of individual simulations
  • n_runs::Int — number of runs
  • results::Dict{Symbol, Matrix{Float64}} — raw results (name → npts × n_runs)
  • reduced::Dict{Symbol, ReducedResult} — reduced results (after reduce!)
  • which::Union{Nothing, Symbol}:reduced after reduce!, nothing otherwise
  • complete::Bool — whether all runs are complete

Example

base = Sim(diseases=SIR(beta=0.05), n_agents=10_000)
msim = MultiSim(base, n_runs=10)
run!(msim)
reduce!(msim)                         # median + 10th/90th quantiles
reduce!(msim; use_mean=true, bounds=2) # mean ± 2σ
Starsim.ScenariosType
Scenarios

Run simulations with different parameter sets. Each scenario is a MultiSim with modified parameters.

Example

scenarios = Scenarios(
    base_sim = Sim(diseases=SIR()),
    scenarios = Dict(
        :low_beta => Dict(:beta => 0.02),
        :high_beta => Dict(:beta => 0.1),
    ),
    n_runs = 5,
)
run!(scenarios)
Starsim.ReducedResultType
ReducedResult

A single result reduced across multiple simulation runs. Stores the central value (median or mean) and lower/upper bounds.

Fields

  • name::Symbol — result name
  • values::Vector{Float64} — central values (median or mean)
  • low::Vector{Float64} — lower bound (quantile or mean - k*std)
  • high::Vector{Float64} — upper bound (quantile or mean + k*std)
Starsim.reduce!Function
reduce!(msim::MultiSim; quantiles=nothing, use_mean=false, bounds=2.0)

Combine multiple simulation results into summary statistics. Matches Python starsim's MultiSim.reduce().

Keyword arguments

  • use_mean::Bool — if true, use mean ± bounds×σ; if false (default), use median with quantile bounds
  • quantiles::Tuple{Float64,Float64} — lower and upper quantiles (default (0.1, 0.9))
  • bounds::Float64 — standard deviation multiplier when use_mean=true (default 2.0)

Example

msim = MultiSim(Sim(diseases=SIR(beta=0.05)), n_runs=20)
run!(msim)

# Default: median with 10th/90th percentile bounds
reduce!(msim)

# Mean with ±2σ bounds
reduce!(msim; use_mean=true, bounds=2.0)
Starsim.mean!Function
mean!(msim::MultiSim; bounds=2.0)

Alias for reduce!(msim; use_mean=true, bounds=bounds).

Starsim.mean_resultFunction
mean_result(msim::MultiSim, key::Symbol) → Vector{Float64}

Get the mean across runs for a raw result.

Starsim.quantile_resultFunction
quantile_result(msim::MultiSim, key::Symbol, q::Float64) → Vector{Float64}

Get a quantile across runs for a raw result.

Starsim.result_keysFunction
result_keys(msim::MultiSim) → Vector{Symbol}

List all available result keys.

Calibration

Starsim.CalibParType
CalibPar

Specification for a single calibration parameter.

Fields

  • name::Symbol — parameter name
  • low::Float64 — lower bound
  • high::Float64 — upper bound
  • initial::Float64 — starting value
  • module_name::Symbol — target module (e.g., :sir)
  • par_name::Symbol — parameter within the module (e.g., :beta)
Starsim.CalibComponentType
CalibComponent

A single likelihood/objective component for calibration.

Fields

  • name::Symbol — component name
  • target_data::Vector{Float64} — observed data
  • sim_result::Symbol — result key in the simulation
  • disease_name::Symbol — disease module name
  • weight::Float64 — weight in the composite objective
  • loss_fn::Function — loss(simulated, observed) → Float64
Starsim.CalibrationType
Calibration

Model calibration workflow. Fits simulation parameters to data using derivative-free or gradient-based optimization.

Keyword arguments

  • sim::Sim — base simulation
  • calib_pars::Vector{CalibPar} — parameters to calibrate
  • components::Vector{CalibComponent} — objective components
  • n_trials::Int — number of optimization trials (default 100)
  • n_runs::Int — runs per trial for averaging (default 1)

Example

calib = Calibration(
    sim = Sim(diseases=SIR(beta=0.05)),
    calib_pars = [CalibPar(:beta; low=0.01, high=0.2, module_name=:sir)],
    components = [CalibComponent(:prev; target_data=data, sim_result=:prevalence, disease_name=:sir)],
)
run!(calib)
best = calib.best_pars
Starsim.apply_pars!Function
apply_pars!(sim::Sim, pars::Dict{Symbol, Float64}, calib_pars::Vector{CalibPar})

Apply calibration parameters to a simulation.

Starsim.compute_objectiveFunction
compute_objective(sim::Sim, components::Vector{CalibComponent}) → Float64

Compute the total objective (loss) for a simulation run.

Settings

Starsim.OptionsType
Options

Global settings for Starsim.jl simulations. Controls CRN (Common Random Numbers), verbosity, and numeric precision.

Fields

  • verbose::Float64 — default verbosity level (0.0 = silent, 1.0 = normal)
  • single_rng::Bool — if true, use a single centralized RNG (not CRN-safe)
  • precision::Int — numeric precision (32 or 64)
  • slot_scale::Float64 — CRN slot scale factor; 0.0 = CRN disabled, >0 = enabled. Controls the range for newborn slot assignment: Uniform(N, slot_scale * N).

CRN overview

When slot_scale > 0, Common Random Numbers mode is active:

  • Each stochastic decision gets its own seeded PRNG stream.
  • Random draws are indexed by agent slot (not UID), ensuring that adding/removing agents doesn't shift other agents' draws.
  • Newborn slots are drawn from a wide range to avoid collisions.
  • Pairwise transmission uses XOR combining for CRN-safe edge randomness.

Example

# Enable CRN globally
Starsim.OPTIONS.slot_scale = 5.0

# Check if CRN is enabled
Starsim.crn_enabled()
Starsim.crn_enabledFunction
crn_enabled() → Bool

Return true if Common Random Numbers mode is active (slot_scale > 0).

Utilities

Starsim.rate_probFunction
rate_prob(rate::Real, dt::Real=1.0)

Convert a rate to a probability: p = 1 - exp(-rate * dt). Matches Python ss.rate_prob().

Starsim.prob_rateFunction
prob_rate(prob::Real, dt::Real=1.0)

Convert a probability to a rate: rate = -log(1 - p) / dt. Matches Python ss.prob_rate().

Starsim.time_probFunction
time_prob(prob::Real, dt_old::Real, dt_new::Real)

Convert a time-dependent probability from one timestep to another: p_new = 1 - (1 - p)^(dt_new / dt_old). Matches Python ss.time_prob().

Abstract type hierarchy

Starsim.AbstractModuleType
AbstractModule

Root abstract type for all Starsim modules. Every simulation component (disease, network, intervention, etc.) is a subtype of AbstractModule.

Starsim.AbstractInfectionType
AbstractInfection <: AbstractDisease

Infectious diseases with network-based transmission, directional beta, and susceptibility/infectiousness modifiers.

Starsim.AbstractNetworkType
AbstractNetwork <: AbstractRoute

Contact networks where agents form explicit pairwise edges.

Starsim.AbstractDemographicsType
AbstractDemographics <: AbstractModule

Demographics modules handle births, deaths, aging, and migration.

Starsim.AbstractRouteType
AbstractRoute <: AbstractModule

Base type for all transmission routes (contact networks, mixing pools, etc.).

Starsim.AbstractAnalyzerType
AbstractAnalyzer <: AbstractModule

Analyzers that track custom results during the simulation.

Starsim.AbstractConnectorType
AbstractConnector <: AbstractModule

Connectors that mediate interactions between modules (e.g., co-infection effects).

Extension stubs

These functions are defined in Starsim and implemented by package extensions.

ForwardDiff extension

Starsim.sensitivityFunction

Compute derivative of a summary result w.r.t. a parameter (ForwardDiff extension).

Optimization extension

Makie extension

Starsim.plot_simFunction

Plot simulation results using Makie (Makie extension).

Enzyme extension

Metal/GPU extension

Starsim.to_gpuFunction

Convert simulation state arrays to GPU using an available backend extension.

Starsim.to_cpuFunction

Convert simulation state arrays back to CPU (GPU extensions).

Catlab extension

Starsim.EpiNetFunction

Define an epidemiological network ACSet (Catlab extension).

Starsim.OpenEpiNetFunction

Create an open epidemiological network (structured cospan) for composition (Catlab extension).

Starsim.EpiSharerFunction

Wrap a Starsim module as an EpiSharer for categorical composition (Catlab extension).

Starsim.compose_epiFunction

Compose EpiSharers according to an undirected wiring diagram (Catlab extension).

Starsim.to_simFunction

Convert a composed EpiNet into a Starsim Sim (Catlab extension).

Starsim.epi_uwdFunction

Build an undirected wiring diagram for composing epidemiological modules (Catlab extension).