API Reference
Simulation
Core
Starsim.Sim — Type
SimThe 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.SimPars — Type
SimParsStandard 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.Pars — Type
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.demo — Function
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:
- Initialize people
- init_pre! all modules (registers states, sets up timelines)
- init_post! all modules (seed infections, etc.)
- Build integration loop
- 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 levelbackend::Symbol— execution backend::cpu(default) — standard CPU execution:gpu/:auto— use the single loaded GPU backend extension:metal— Apple Silicon GPU backend (requiresusing Metal):cuda— NVIDIA GPU backend (requiresusing CUDA):amdgpu— AMD GPU backend (requiresusing 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_dataframe — Function
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_result — Function
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_modules — Function
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.summarize — Function
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 timenew_*→ mean over timecum_*→ last valueprevalence→ 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_sim — Function
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 (.jlsextension 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_sim — Function
load_sim(filename::AbstractString) → SimLoad a simulation from disk. Inverse of save_sim.
Example
sim = load_sim("my_sim.jls")Starsim.to_json — Function
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 fileStarsim.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_sims — Function
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_diffStarsim.check_sims_match — Function
check_sims_match(sim1::Sim, sim2::Sim; rtol=0.01, atol=1e-8) → BoolCheck if two simulations match within tolerance. Prints mismatches and returns true if all shared results match.
Starsim.mock_sim — Function
mock_sim(; n_agents=100, kwargs...) → SimCreate a minimal SIR simulation for testing purposes.
Example
sim = mock_sim()
run!(sim; verbose=0)People
Starsim.People — Type
PeopleThe agent population. Stores all agent states and manages the active UID set. Parametric design allows different array backends.
Built-in states
uid— unique agent identifiersslot— RNG slot indicesalive— life statusage— agent age in yearsfemale— biological sexti_dead— scheduled death timeti_removed— removal timescale— per-agent scaling factorparent— 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 TExtend 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 agentsnew_vals— optional values to assign (otherwise usesdefault)
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.UIDs — Type
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 rangeStarsim.uids_cat — Function
Concatenate any number of UIDs.
State vectors
Starsim.StateVector — Type
StateVector{T, A<:AbstractVector{T}} <: AbstractStateWraps 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 labeldefault— default value for new agents (scalar, functionn -> values, or Distribution)nan_val— sentinel for missing dataraw::A— underlying array (all agents, including dead)len_used::Int— number of populated slotslen_tot::Int— total allocated capacityauids_ref::Ref— reference to the active UIDs (shared with People)initialized::Bool
Indexing
state[i::Int]— index intovalues(active agents)state[u::UIDs]— index intorawby UIDstate[b::BoolState]— index by boolean mask → UIDs
Starsim.FloatState — Function
FloatState(name; label, default, nan_val)Create a floating-point state array.
Example
age = FloatState(:age; default=0.0, label="Age")Starsim.IntState — Function
IntState(name; label, default, nan_val)Create an integer state array.
Example
n_contacts = IntState(:n_contacts; default=0)Starsim.BoolState — Function
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.IndexState — Function
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.set_state! — Function
Set state to scalar for given UIDs.
Starsim.mul_state! — Function
Element-wise multiply state for given UIDs.
Starsim.uids — Function
uids(s::StateVector{Bool})Return UIDs of agents where the boolean state is true (active agents only).
Starsim.false_uids — Function
false_uids(s::StateVector{Bool})Return UIDs of active agents where the boolean state is false.
Starsim.state_gt — Function
UIDs where state .> val.
Starsim.state_lt — Function
UIDs where state .< val.
Starsim.state_gte — Function
UIDs where state .>= val.
Starsim.state_lte — Function
UIDs where state .<= val.
Starsim.state_eq — Function
UIDs where state .== val.
Starsim.state_neq — Function
UIDs where state .!= val.
Starsim.state_and_cmp — Function
UIDs where bool state is true AND comparison holds.
Time
Duration
Starsim.Duration — Type
Duration{U} <: AbstractDurationA 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 unitunit::Symbol— one of:days,:weeks,:months,:years
Starsim.days — Function
Duration in days.
Starsim.weeks — Function
Duration in weeks.
Starsim.months — Function
Duration in months (1 month = 1/12 year).
Starsim.years — Function
Duration in years.
Starsim.to_years — Function
to_years(d::Duration)Convert a duration to years.
Starsim.to_days — Function
to_days(d::Duration)Convert a duration to days.
Starsim.to_dt — Function
to_dt(d::Duration, dt::Float64)Convert a duration to simulation timestep units. dt is the simulation timestep in years.
Rate
Starsim.Rate — Type
Rate <: AbstractRateA rate parameter with time units. Rates can be converted to per-timestep probabilities via to_prob.
Fields
value::Float64— rate valueunit::Symbol— time unit (:perday,:perweek,:permonth,:peryear)
Starsim.perday — Function
Rate per day.
Starsim.perweek — Function
Rate per week.
Starsim.permonth — Function
Rate per month.
Starsim.peryear — Function
Rate per year.
Starsim.to_peryear — Function
to_peryear(r::Rate)Convert a rate to per-year.
Starsim.to_prob — Function
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.Timeline — Type
TimelineTracks 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 timepointstvec::Vector{Float64}— time vectorti::Int— current time index (1-based)
Starsim.now — Function
Current simulation time.
Starsim.advance! — Function
Advance the timeline by one step.
Starsim.is_done — Function
Check if the simulation is complete.
Diseases
Data containers
Starsim.DiseaseData — Type
DiseaseDataCommon mutable data for all diseases.
Starsim.InfectionData — Type
InfectionDataAdditional mutable data for infections (diseases with transmission).
Disease models
Starsim.SIR — Type
SIR <: AbstractInfectionStandard 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.SIS — Type
SIS <: AbstractInfectionSIS 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.SEIR — Type
SEIR <: AbstractInfectionSEIR 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-likeDisease 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.
Starsim.validate_beta! — Function
Compute per-dt betas from the rate-based beta parameter.
Networks
Edge storage
Starsim.Edges — Type
EdgesStores 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 UIDsp2::Vector{Int}— target agent UIDsbeta::Vector{Float64}— per-edge transmission multiplieracts::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.
Starsim.remove_edges! — Function
Remove edges at given indices.
Starsim.clear_edges! — Function
Clear all edges.
Starsim.find_contacts — Function
Find contact UIDs for a given set of source UIDs.
Network data
Starsim.NetworkData — Type
NetworkDataCommon mutable data for network modules.
Starsim.network_data — Function
network_data(net::AbstractNetwork) -> NetworkDataReturn the NetworkData for a network. Concrete networks must implement this.
Starsim.network_edges — Function
network_edges(net::AbstractNetwork) -> EdgesReturn the Edges container for network net.
Starsim.net_beta — Function
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.RandomNet — Type
RandomNet <: AbstractNetworkRandom 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, orAbstractStarsimDist
Example
net = RandomNet(n_contacts=10)Starsim.MFNet — Type
MFNet <: AbstractNetworkHeterosexual partnership network (male-female pairs).
Keyword arguments
name::Symbol— default:mfmean_dur::Float64— mean partnership duration (default 5.0)participation_rate::Float64— fraction of adults in partnerships (default 0.5)
Starsim.MaternalNet — Type
MaternalNet <: AbstractNetworkMother-child contact network for vertical transmission.
Starsim.MixingPool — Type
MixingPool <: AbstractNetworkWell-mixed population contact model. All agents can potentially infect all others, weighted by a contact rate.
Keyword arguments
name::Symbol— default:mixingcontact_rate::Float64— effective contacts per agent per dt (default 10.0)
Starsim.StaticNet — Type
StaticNet <: AbstractNetworkStatic 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:staticgraph_fn— function(n, rng) → SimpleGraphthat creates the networkn_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.MSMNet — Type
MSMNet <: AbstractNetworkMen-who-have-sex-with-men partnership network. Pairs only male agents.
Keyword arguments
name::Symbol— default:msmparticipation_rate::Float64— fraction of males in partnerships (default 0.3)
Starsim.PrenatalNet — Type
PrenatalNet <: AbstractNetworkNetwork 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.PostnatalNet — Type
PostnatalNet <: AbstractNetworkNetwork 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:postnataldur::Union{Nothing, Float64}— edge duration in timesteps.nothingmeans edges persist indefinitely.
Starsim.BreastfeedingNet — Type
BreastfeedingNet <: AbstractNetworkNetwork 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.HouseholdNet — Type
HouseholdNet <: AbstractNetworkA 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 identifierages— comma-separated age strings (e.g. "72, 17, 30")sexes(optional) — comma-separated sex codes (1=male, 2=female)
Keyword arguments
name::Symbol— default:householdhh_data::Union{Nothing, DataFrame}— household survey datadynamic::Bool— whether households evolve over time (defaultfalse)
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_graph — Function
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_digraph — Function
to_digraph(e::Edges) -> SimpleDiGraph{Int}Create a directed graph from edges (p1 → p2).
Starsim.to_adjacency_matrix — Function
to_adjacency_matrix(e::Edges; n::Int=0, weighted::Bool=false) -> SparseMatrixCSCCreate 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_matrix — Function
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.
Starsim.contact_degrees — Function
Convenience: get contact degrees from edges via Graphs.jl.
Starsim.network_components — Function
Convenience: connected components via Graphs.jl.
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.form_partnerships! — Function
Form male-female partnerships.
Starsim.form_msm_partnerships! — Function
Form male-male partnerships.
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.Births — Type
Births <: AbstractDemographicsBirth 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.Deaths — Type
Deaths <: AbstractDemographicsBackground 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.Pregnancy — Type
Pregnancy <: AbstractDemographicsPregnancy module — tracks pregnant status and delivery. (Simplified version; full version in FPsim.jl extension.)
Interventions
Products
Starsim.Vx — Type
Vx <: AbstractProductVaccination product — reduces susceptibility.
Keyword arguments
name::Symbol— product name (default:vx)efficacy::Float64— vaccine efficacy (default 0.9)
Starsim.Dx — Type
Dx <: AbstractProductDiagnostic 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.Tx — Type
Tx <: AbstractProductTreatment 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::UIDsApply diagnostic to agents. Returns UIDs of agents who test positive.
administer!(tx::Tx, uids::UIDs, disease) → treated::UIDsApply treatment. Returns UIDs of successfully treated agents.
administer!(vx::Vx, uids::UIDs, disease) → vaccinated::UIDsApply vaccine. Reduces rel_sus for susceptible agents.
Delivery mechanisms
Starsim.RoutineDelivery — Type
RoutineDelivery <: AbstractInterventionRoutine 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 deliverdisease_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.CampaignDelivery — Type
CampaignDelivery <: AbstractInterventionCampaign 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 deliverdisease_name::Symbol— target disease (default:sir)years::Vector{Float64}— years to conduct campaignscoverage::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.FunctionIntervention — Type
FunctionIntervention <: AbstractInterventionA 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_vx — Function
Create a routine vaccination delivery. Matches Python ss.routine_vx().
Starsim.campaign_vx — Function
Create a campaign vaccination delivery. Matches Python ss.campaign_vx().
Starsim.simple_vx — Function
Alias for routine_vx. Matches Python ss.simple_vx().
Starsim.routine_screening — Function
Create a routine screening delivery. Matches Python ss.routine_screening().
Starsim.campaign_screening — Function
Create a campaign screening delivery. Matches Python ss.campaign_screening().
Intervention data
Starsim.InterventionData — Type
InterventionDataCommon mutable data for intervention modules.
Starsim.intervention_data — Function
intervention_data(iv::AbstractIntervention) → InterventionDataReturn the InterventionData. Concrete intervention types must implement this.
Connectors
Starsim.ConnectorData — Type
ConnectorDataCommon mutable data for connector modules.
Starsim.connector_data — Function
connector_data(c::AbstractConnector) → ConnectorDataReturn the ConnectorData. Concrete connectors must implement this.
Starsim.Seasonality — Type
Seasonality <: AbstractConnectorModulates 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.seasonal_factor — Function
Compute seasonal multiplier for the current time.
Starsim.CoinfectionConnector — Type
CoinfectionConnector <: AbstractConnectorModifies susceptibility or transmissibility based on coinfection status.
Keyword arguments
name::Symbol— connector namedisease1::Symbol— first diseasedisease2::Symbol— second diseaserel_sus_if_infected::Float64— multiplier on disease2 susceptibility if infected with disease1rel_trans_if_infected::Float64— multiplier on disease1 transmissibility if infected with disease2
Analyzers
Starsim.AnalyzerData — Type
AnalyzerDataCommon mutable data for analyzer modules.
Starsim.analyzer_data — Function
analyzer_data(a::AbstractAnalyzer) → AnalyzerDataReturn the AnalyzerData. Concrete analyzers must implement this.
Starsim.FunctionAnalyzer — Type
FunctionAnalyzer <: AbstractAnalyzerAnalyzer 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.Snapshot — Type
Snapshot <: AbstractAnalyzerCaptures 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.InfectionLog — Type
InfectionLog <: AbstractAnalyzerRecord 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 columnsStarsim.TransmissionEvent — Type
TransmissionEventA single transmission event recorded in the infection log.
Fields
source::Int— UID of infecting agent (0 for seed infections)target::Int— UID of infected agentt::Int— timestep of infectiondata::Dict{Symbol, Any}— optional extra data (network, etc.)
Distributions
Base types
Starsim.StarsimDist — Type
StarsimDist{D<:Distribution} <: AbstractStarsimDistWraps a Distributions.jl distribution with Starsim-specific RNG management.
Fields
dist::D— the underlying distributionname::Symbol— unique name for seedingrng::StableRNG— deterministic RNGseed::UInt64— seed derived from name + base seedslots::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 samplesStarsim.BernoulliDist — Type
BernoulliDist <: AbstractStarsimDistBernoulli 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.ConstantDist — Type
ss_constant(; value)Constant "distribution" — always returns the same value. Matches Python ss.constant().
Starsim.ChoiceDist — Type
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.rvs — Function
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.MultiRandom — Type
MultiRandom <: AbstractStarsimDistGenerates 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— identifierseed::UInt64— base seedinitialized::Bool
Example
mr = MultiRandom(:transmission)
init_dist!(mr, base_seed=42)
probs = multi_rvs(mr, source_uids, target_uids)Starsim.combine_rvs — Function
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:
- Reinterpret each float64 as UInt64 (bit-level)
- Compute
xor(a * b, a - b)in unsigned integer arithmetic (wrapping) - 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_rvs — Function
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 dimensionuid_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.bernoulli — Function
Create a Bernoulli distribution for prevalence seeding.
Starsim.ss_random — Function
ss_random()Uniform(0, 1) random distribution. Matches Python ss.random().
Starsim.ss_normal — Function
ss_normal(; loc, scale)Normal distribution wrapper. loc can be Real or Duration.
Starsim.ss_lognormal — Function
ss_lognormal(; mean, sigma)Lognormal distribution (explicit parameterization via mean and sigma).
Starsim.ss_lognormal_im — Function
ss_lognormal_im(; loc, scale)Lognormal distribution (implicit parameterization: log-space μ and σ). Matches Python ss.lognorm_im().
Starsim.ss_uniform — Function
Uniform distribution.
Distribution container
Starsim.DistsContainer — Type
DistsContainerCollects 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.Result — Type
Result <: AbstractResultA single time-series result from a simulation module.
Fields
name::Symbol— result name (e.g.,:new_infections)label::String— human-readable labelmodule_name::Symbol— owning modulevalues::Vector{Float64}— time-series datascale::Bool— whether to scale bypop_scaleduring finalizationauto_plot::Bool— include in default plotssummarize_by::Symbol— aggregation method (:sum,:mean,:last)
Starsim.Results — Type
ResultsOrdered dictionary of Result objects for a module or simulation.
Example
res = Results()
push!(res, Result(:prevalence; npts=100, scale=false))
res[:prevalence][1] = 0.05Starsim.scale_results! — Function
scale_results!(res::Results, factor::Float64)Scale results that have scale=true by the given factor.
Module system
Module data
Starsim.ModuleData — Type
ModuleDataCommon 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 namelabel::String— human-readable labelpars::Pars— module parameterst::Timeline— module-specific timeline (may differ from sim)results::Results— module resultsstates::Vector{StateVector}— registered agent statesdists::Vector{AbstractStarsimDist}— registered distributionsinitialized::Bool
Starsim.module_data — Function
module_data(mod::AbstractModule) → ModuleDataReturn the ModuleData for a module. Every concrete module must implement this.
Starsim.module_name — Function
module_name(mod::AbstractModule) → SymbolReturn the module's name.
Starsim.module_pars — Function
module_pars(mod::AbstractModule) → ParsReturn the module's parameters.
Starsim.module_results — Function
module_results(mod::AbstractModule) → ResultsReturn the module's results.
Starsim.module_states — Function
module_states(mod::AbstractModule) → Vector{StateVector}Return the module's registered states.
Starsim.module_timeline — Function
module_timeline(mod::AbstractModule) → TimelineReturn the module's timeline.
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.Loop — Type
LoopThe 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:
- sim.start_step
- all modules.start_step
- custom.step
- demographics.step
- diseases.step_state
- connectors.step
- networks.step
- interventions.step
- diseases.step (transmission)
- people.step_die
- people.update_results
- all modules.update_results
- analyzers.step
- all modules.finish_step
- people.finish_step
- sim.finish_step
Starsim.StepEntry — Type
StepEntryA 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.MultiSim — Type
MultiSimRun multiple simulations and aggregate results. Uses Julia's native multi-threading for true parallelism (no GIL limitation).
Fields
base_sim::Sim— the template simulationsims::Vector{Sim}— vector of individual simulationsn_runs::Int— number of runsresults::Dict{Symbol, Matrix{Float64}}— raw results (name → npts × n_runs)reduced::Dict{Symbol, ReducedResult}— reduced results (afterreduce!)which::Union{Nothing, Symbol}—:reducedafterreduce!, nothing otherwisecomplete::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.Scenarios — Type
ScenariosRun 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.ReducedResult — Type
ReducedResultA single result reduced across multiple simulation runs. Stores the central value (median or mean) and lower/upper bounds.
Fields
name::Symbol— result namevalues::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— iftrue, use mean ±bounds×σ; iffalse(default), use median with quantile boundsquantiles::Tuple{Float64,Float64}— lower and upper quantiles (default(0.1, 0.9))bounds::Float64— standard deviation multiplier whenuse_mean=true(default2.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_result — Function
mean_result(msim::MultiSim, key::Symbol) → Vector{Float64}Get the mean across runs for a raw result.
Starsim.quantile_result — Function
quantile_result(msim::MultiSim, key::Symbol, q::Float64) → Vector{Float64}Get a quantile across runs for a raw result.
Starsim.result_keys — Function
result_keys(msim::MultiSim) → Vector{Symbol}List all available result keys.
Calibration
Starsim.CalibPar — Type
CalibParSpecification for a single calibration parameter.
Fields
name::Symbol— parameter namelow::Float64— lower boundhigh::Float64— upper boundinitial::Float64— starting valuemodule_name::Symbol— target module (e.g.,:sir)par_name::Symbol— parameter within the module (e.g.,:beta)
Starsim.CalibComponent — Type
CalibComponentA single likelihood/objective component for calibration.
Fields
name::Symbol— component nametarget_data::Vector{Float64}— observed datasim_result::Symbol— result key in the simulationdisease_name::Symbol— disease module nameweight::Float64— weight in the composite objectiveloss_fn::Function— loss(simulated, observed) → Float64
Starsim.Calibration — Type
CalibrationModel calibration workflow. Fits simulation parameters to data using derivative-free or gradient-based optimization.
Keyword arguments
sim::Sim— base simulationcalib_pars::Vector{CalibPar}— parameters to calibratecomponents::Vector{CalibComponent}— objective componentsn_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_parsStarsim.apply_pars! — Function
apply_pars!(sim::Sim, pars::Dict{Symbol, Float64}, calib_pars::Vector{CalibPar})Apply calibration parameters to a simulation.
Starsim.compute_objective — Function
compute_objective(sim::Sim, components::Vector{CalibComponent}) → Float64Compute the total objective (loss) for a simulation run.
Starsim.mse_loss — Function
Default MSE loss function.
Starsim.normal_loss — Function
Negative log-likelihood under Normal distribution.
Settings
Starsim.Options — Type
OptionsGlobal 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— iftrue, 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.OPTIONS — Constant
Global simulation options singleton.
Starsim.crn_enabled — Function
crn_enabled() → BoolReturn true if Common Random Numbers mode is active (slot_scale > 0).
Starsim.get_slot_scale — Function
get_slot_scale() → Float64Return the current CRN slot scale factor.
Utilities
Starsim.rate_prob — Function
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_rate — Function
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_prob — Function
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().
Starsim.standardize_netkey — Function
standardize_netkey(key)Standardize a network key by stripping common suffixes.
Starsim.warn_starsim — Function
warn_starsim(msg::String)Issue a warning with a Starsim prefix.
Abstract type hierarchy
Starsim.AbstractModule — Type
AbstractModuleRoot abstract type for all Starsim modules. Every simulation component (disease, network, intervention, etc.) is a subtype of AbstractModule.
Starsim.AbstractInfection — Type
AbstractInfection <: AbstractDiseaseInfectious diseases with network-based transmission, directional beta, and susceptibility/infectiousness modifiers.
Starsim.AbstractNetwork — Type
AbstractNetwork <: AbstractRouteContact networks where agents form explicit pairwise edges.
Starsim.AbstractDemographics — Type
AbstractDemographics <: AbstractModuleDemographics modules handle births, deaths, aging, and migration.
Starsim.AbstractRoute — Type
AbstractRoute <: AbstractModuleBase type for all transmission routes (contact networks, mixing pools, etc.).
Starsim.AbstractAnalyzer — Type
AbstractAnalyzer <: AbstractModuleAnalyzers that track custom results during the simulation.
Starsim.AbstractConnector — Type
AbstractConnector <: AbstractModuleConnectors that mediate interactions between modules (e.g., co-infection effects).
Starsim.AbstractStarsimDist — Type
AbstractStarsimDistBase type for Starsim distribution wrappers around Distributions.jl.
Extension stubs
These functions are defined in Starsim and implemented by package extensions.
ForwardDiff extension
Starsim.sensitivity — Function
Compute derivative of a summary result w.r.t. a parameter (ForwardDiff extension).
Starsim.sensitivity_timeseries — Function
Compute per-timestep derivatives of a result w.r.t. a parameter (ForwardDiff extension).
Starsim.gradient_objective — Function
Compute objective and gradient for calibration (ForwardDiff extension).
Optimization extension
Starsim.build_optproblem — Function
Build an Optimization.jl problem from a Calibration (Optimization extension).
Starsim.run_optimization! — Function
Run calibration via Optimization.jl solvers (Optimization extension).
Makie extension
Starsim.plot_sim — Function
Plot simulation results using Makie (Makie extension).
Starsim.plot_disease — Function
Plot a single disease's results using Makie (Makie extension).
Starsim.plot_comparison — Function
Plot comparison of multiple simulations using Makie (Makie extension).
Enzyme extension
Starsim.enzyme_sensitivity — Function
Compute sensitivity via Enzyme reverse-mode AD (Enzyme extension).
Metal/GPU extension
Starsim.to_gpu — Function
Convert simulation state arrays to GPU using an available backend extension.
Starsim.to_cpu — Function
Convert simulation state arrays back to CPU (GPU extensions).
Catlab extension
Starsim.EpiNet — Function
Define an epidemiological network ACSet (Catlab extension).
Starsim.OpenEpiNet — Function
Create an open epidemiological network (structured cospan) for composition (Catlab extension).
Starsim.EpiSharer — Function
Wrap a Starsim module as an EpiSharer for categorical composition (Catlab extension).
Starsim.compose_epi — Function
Compose EpiSharers according to an undirected wiring diagram (Catlab extension).
Starsim.to_sim — Function
Convert a composed EpiNet into a Starsim Sim (Catlab extension).
Starsim.epi_uwd — Function
Build an undirected wiring diagram for composing epidemiological modules (Catlab extension).