AlgebraicEpiMech API¶
Reference for the exported API of AlgebraicEpiMech, generated from docstrings.
AlgebraicEpiMech.AtCompartment — Type.
Sample a SPECIES: prevalence. Every species whose (flattened) name begins with species gains a catalytic tap X -> X + O, carrying its own detection rate — whoever is in the compartment is currently detectable (although detection does not cause removal)
Fields
species::Symbol
AlgebraicEpiMech.AtEvent — Type.
AtEvent(transition::Symbol; group = identity)
AtEvent(transitions::Tuple; source = first(transitions), group = identity)
Record a TRANSITION: incidence. Every transition whose (flattened) name begins with one of transitions gains an output arc into an accumulator, so it fires at that transition's own rate and counts exactly one observation per occurrence. Chains are named after source.
AtEvent(:transmission) counts infections as they happen, which is what decouples a reporting delay from the latent period — the delay is then whatever the chain adds and nothing else. AtEvent((:transmission, :importation); source = :infection) counts local and imported infections together.
group maps the label of the species an event nets to the label its chain is keyed on, so several products can share one chain. Dropping a stratum from the label, such as the immune class, merges those chains; this is exact because every chain is linear with the same delay rates.
Fields
transitions::Tuple{Vararg{Symbol}}source::Symbolgroup::Any
AlgebraicEpiMech.CompartmentalModel — Type.
Abstract base type for compartmental epidemiological models.
Compartmental models define the specific disease dynamics and transitions between epidemiological states (e.g., S→I→R) as undirected wiring diagrams.
Every concrete model also takes the Demography keywords, naming compartments, for example SIR(births = [:S], deaths = [:I], importation = true).
Fields
AlgebraicEpiMech.CompleteCrossImmunity — Type.
Complete cross-immunity multistrain model.
In the complete cross-immunity model:
- All strains share a common susceptible pool
- Infection by any strain confers immunity to all strains
- Typing: UninfectedInfectedTyping (typed S vs I/R compartments)
- Composition: Strains compete for susceptibles via shared S depletion
Fields
number_of_strains::Int: Number of competing strains in the modelstrain_names::Vector{Symbol}: Names for each strain (e.g., [:h1n1, :h3n2])
Examples
# Create a 2-strain model with custom names
multistrain = CompleteCrossImmunity([:wild_type, :variant])
# Create a 3-strain model with auto-generated names
multistrain = CompleteCrossImmunity(3) # Creates [:strain_1, :strain_2, :strain_3]
# Compose to create competing strain SIR
typing = UninfectedInfectedTyping()
strain_typed = create_model(typing, multistrain)
sir_typed = create_model(typing, SIR())
combined = typed_product(sir_typed, strain_typed)
Fields
number_of_strains::Int64strain_names::Vector{Symbol}
AlgebraicEpiMech.ContactStratification — Type.
ContactStratification(stratum_names, label; transitions = Pair{Symbol, Symbol}[], births = (), deaths = ())
Strata with a full contact matrix between every pair (age groups, geographic regions, risk groups), and an optional directed graph of movement between them (ageing, migration). Movement keeps the disease state and is independent of contact-based infection.
Multiple contact stratifications can be stacked via compose_stratifications to create product strata (e.g., age × geography).
Fields
stratum_names::Vector{Symbol}: Names of strata (e.g., [:child, :adult] or [:urban, :rural])label::Symbol: Semantic label for the stratification (e.g., :age, :geography, :risk)transitions::Vector{Pair{Symbol, Symbol}}: Directed movement edges between distinct declared strata. Each edge becomes one movement box per population type, namedsource_to_target. With no edges the stratification is static and a product with it has no movement.demography::Demography: the strata that births enter and deaths leave, from thebirthsanddeathskeywords (seeDemography). A factor declaring no births drops them from atyped_product.
Reflexive boxes for the types a factor does not implement are controlled via the include_reflexives keyword on create_model, not on the struct itself.
Examples
age = ContactStratification([:child, :adult], :age)
aging = ContactStratification([:child, :adult], :age; transitions = [:child => :adult])
geo = ContactStratification([:urban, :rural], :geography)
# Compose to create age × geography strata
typing = OnePopulationTyping()
sir = create_model(typing, SIR())
age_sir = typed_product(sir, create_model(typing, age))
age_geo_sir = typed_product(age_sir, create_model(typing, geo))
# Result: 4 strata (childxurban, childxrural, adultxurban, adultxrural)
# Ageing: the disease model must carry reflexive movement boxes for the pullback to keep it
sir = create_model(typing, SIR(); include_reflexives = :strata)
aging_sir = dom(typed_product(sir, create_model(typing, aging)))
# Transitions include S_child_to_adult, I_child_to_adult, R_child_to_adult
# Births into the youngest group, deaths out of the oldest
demography = ContactStratification(
[:child, :adult], :age; transitions = [:child => :adult], births = [:child], deaths = [:adult],
)
See also: AgeStratification, GeographicStratification
Fields
stratum_names::Vector{Symbol}label::Symboltransitions::Vector{Pair{Symbol, Symbol}}demography::Demography
AlgebraicEpiMech.Demography — Type.
The open-population part of a model specification: the names (compartments, or strata of a ContactStratification) that births enter and that deaths leave. Each birth becomes one :birth box and each death one death box per junction of that name; a stratum's births enter its uninfected junction. importation = true adds an :importation box from S into a compartmental model's first infected stage.
In a typed_product a transition type survives only if every factor has it. A factor that declares no deaths can still be passive for them through include_reflexives = :death on create_model, and a stratification factor is passive for importation through :importation; births cannot be passive, because a newborn must be placed in every factor.
Fields
births::Tuple{Vararg{Symbol}}deaths::Tuple{Vararg{Symbol}}importation::Bool
AlgebraicEpiMech.EpiMechModel — Type.
Abstract base type for all epidemiological-mechanical models in the AlgebraicEpiMech framework.
All concrete epidemiological-mechanical model types should be subtypes of EpiMechModel. This abstract type serves as the root of the type hierarchy for models that combine epidemiological dynamics with mechanical or algebraic structures.
Extended help
Subtypes of EpiMechModel should implement the necessary interface methods for their specific model formulation.
See also
- Related concrete model types (define as needed)
Fields
AlgebraicEpiMech.EpidemiologicalTyping — Type.
Abstract base type for epidemiological typing strategies.
An EpidemiologicalTyping describes how populations and transitions are typed when constructing epidemiological models. type_system materializes the strategy as the LabelledPetriNet used as the codomain of a typed Petri net.
Reference
Libkind et al. (2023) An algebraic framework for structured epidemic modelling
Fields
AlgebraicEpiMech.FullHistory — Type.
Full (unordered) immune history: uninfected individuals are indexed by the set of strains they are immune to (2^n classes). Immunity accumulates — reversion routes to h ∪ {i}.
Fields
AlgebraicEpiMech.ImmuneHistory — Type.
Immune-history combination of the available strain/subtype names and ImmuneHistoryMode.
Fields
strain_names::Vector{Symbol}: strain names (e.g.[:current, :invader])mode::M:FullHistory()orLatestInfection()waning::Bool: whentrue, the factor implements loss of immunity as:waningedgesU_h → U_{h∖{i}}for every strainiin each classh, one strain forgotten at a time (underLatestInfectionevery class returns to naive). Each edge is namedwane_<i>_<h>, so a per-strain waning rate is keyed by thewane_<i>_prefix. The disease model must then list:waningininclude_reflexivesfor the pullback to keep those edges. Defaultfalse::waningis reflexive on each class.
Listing :importation in include_reflexives adds one :importation box U_h → (h, i) for every strain i that class h is susceptible to, named import_<i>_<h>, so a disease model declaring importation = true keeps its importation per class and strain.
Examples
typing = UninfectedInfectedTyping()
seirs = create_model(typing, SEIRS())
history = create_model(typing, ImmuneHistory([:current, :invader]))
model = typed_product(seirs, history) # immune-history-resolved SEIRS
# States: S_naive, S_current, …, E_invader_from_current, I_…, R_…
# Waning immunity
sir = create_model(typing, SIR(); include_reflexives = :waning)
waning = create_model(typing, ImmuneHistory([:current, :invader]; waning = true))
model = typed_product(sir, waning) # adds waning_S_wane_current_current, …
Fields
strain_names::Vector{Symbol}mode::ImmuneHistoryModewaning::Bool
AlgebraicEpiMech.ImmuneHistory — Method.
Auto-name n strains as strain_1 … strain_n.
AlgebraicEpiMech.ImmuneHistoryMode — Type.
Abstract base type for selections of how much immune history is retained.
Fields
AlgebraicEpiMech.KineticStructure — Type.
The mass-action kinetics of a Petri net in factored form, as built by kinetic_structure and evaluated by vectorfield_factored.
With x the state and p the rates by key, the field is
Fields
species: flattened species names, in net order.rate_keys: the keyspmust supply, in order of first appearance.fixed_keys: the keys whose rate was folded into the constants.zero_order:b, asZeroOrderTerms.first_order:A x, asFirstOrderTerms.catalysed: the factored second-order part, asCatalysedTerms.residual: transitions kept as they are (uncatalysed second order, and third order and above), asReactions.report: counts from the analysis, as aKineticReport.
Each of these types is documented under its own name, for example ?AlgebraicEpiMech.Reaction.
A key index of 0 in any of these stands for the fixed rates.
Fields
species::Vector{Symbol}rate_keys::Vector{Symbol}fixed_keys::Vector{Symbol}zero_order::AlgebraicEpiMech.ZeroOrderTermsfirst_order::AlgebraicEpiMech.FirstOrderTermscatalysed::AlgebraicEpiMech.CatalysedTermsresidual::Vector{AlgebraicEpiMech.Reaction}report::AlgebraicEpiMech.KineticReport
AlgebraicEpiMech.LatestInfection — Type.
Latest-infection status: uninfected individuals are indexed by their most recent infection (n + 1 classes). Reversion overwrites immune status — routes to {i}.
Fields
AlgebraicEpiMech.MultiStrainModel — Type.
Abstract base type for multistrain epidemiological models.
Multistrain models define how multiple pathogen strains interact through different assumptions about cross-immunity. These compose with compartmental models via typed_product to create strain-structured disease dynamics.
Fields
AlgebraicEpiMech.NoCrossImmunity — Type.
No cross-immunity multistrain model.
In the no cross-immunity model:
- Each strain operates independently with no interaction
- Strains act as independent strata (similar to age groups)
- Typing: OnePopulationTyping (all compartments have the same type)
- Composition: Creates parallel disease dynamics per strain via typed_product
Fields
number_of_strains::Int: Number of independent strains in the modelstrain_names::Vector{Symbol}: Names for each strain (e.g., [:h1n1, :h3n2, :b])
Examples
# Create a 3-strain model with custom names
multistrain = NoCrossImmunity([:h1n1, :h3n2, :b])
# Create a 2-strain model with auto-generated names
multistrain = NoCrossImmunity(2) # Creates [:strain_1, :strain_2]
# Compose to create strain-structured SIR
typing = OnePopulationTyping()
strain_typed = create_model(typing, multistrain)
sir_typed = create_model(typing, SIR())
combined = typed_product(sir_typed, strain_typed)
Fields
number_of_strains::Int64strain_names::Vector{Symbol}
AlgebraicEpiMech.ObservationChainLayout — Type.
Metadata for one observation chain.
Fields
source_name: Flattened name of the event or compartment being observedobs_names: Observation-state names in stage ordercumulative_name: Terminal observation-state name, derived fromobs_names
Fields
source_name::Symbolobs_names::NTuple{N, Symbol} where Ncumulative_name::Symbol
AlgebraicEpiMech.ObservationLayout — Type.
Metadata for all observation chains in an augmented Petri net.
Fields
obs_names: All flattened observation-state names in Petri-net orderchains: Observation chains in first-encounter ordercumulative_names: Terminal state of each chain, derived fromchains
Fields
obs_names::NTuple{N, Symbol} where Nchains::Tuplecumulative_names::NTuple{M, Symbol} where M
AlgebraicEpiMech.ObservationTarget — Type.
What an observation attaches to. AtEvent records a transition (incidence); AtCompartment samples a species (prevalence).
Fields
AlgebraicEpiMech.OnePopulationTyping — Type.
Typing strategy in which every compartment belongs to one population type and therefore has the same available stratifications.
Examples
Fields
population_type::Symbol: The symbolic name for the population type.
Susceptible-Exposed-Infected (SEI) compartmental model.
The SEI model extends SI with an exposed compartment:
- Susceptible (S): Individuals who can become infected
- Exposed (E): Individuals who are infected but not yet infectious
- Infected (I): Individuals who are infectious
Transitions:
- S + I → E + I (exposure/transmission)
- E → I (progression to infectious)
The SEI model represents diseases with an incubation period but no recovery.
Fields
number_E_stages::Int64number_I_stages::Int64number_of_states::Int64demography::Demography
Susceptible-Exposed-Infected-Recovered (SEIR) compartmental model.
The SEIR model extends SEI with recovery:
- Susceptible (S): Individuals who can become infected
- Exposed (E): Individuals who are infected but not yet infectious
- Infected (I): Individuals who are infectious
- Recovered (R): Individuals who have recovered and gained immunity
Transitions:
- S + I → E + I (exposure/transmission) [from SEI]
- E → I (progression to infectious) [from SEI]
- I → R (recovery) [extension]
Built by extending SEI model with recovery transition.
Fields
number_E_stages::Int64number_I_stages::Int64number_of_states::Int64demography::Demography
AlgebraicEpiMech.SEIRS — Type.
Susceptible-Exposed-Infected-Recovered-Susceptible (SEIRS) compartmental model.
The SEIRS model extends SEIR with waning immunity:
- Susceptible (S): Individuals who can become infected
- Exposed (E): Individuals who are infected but not yet infectious
- Infected (I): Individuals who are infectious
- Recovered (R): Individuals who have recovered but may lose immunity
Transitions:
- S + I → E + I (exposure/transmission) [from SEIR]
- E → I (progression to infectious) [from SEIR]
- I → R (recovery) [from SEIR]
- R → S (waning immunity) [extension]
Built by extending SEIR model with waning transition.
Fields
number_E_stages::Int64number_I_stages::Int64number_of_states::Int64demography::Demography
Susceptible-Exposed-Infected-Susceptible (SEIS) compartmental model.
The SEIS model extends SEI with waning immunity (reversion):
- Susceptible (S): Individuals who can become infected
- Exposed (E): Individuals who are infected but not yet infectious
- Infected (I): Individuals who are infectious
Transitions:
- S + I → E + I (exposure/transmission) [from SEI]
- E → I (progression to infectious) [from SEI]
- I → S (waning immunity/reversion) [extension]
The SEIS model represents diseases with incubation period but no lasting immunity.
Fields
number_E_stages::Int64number_I_stages::Int64number_of_states::Int64demography::Demography
Susceptible-Infected (SI) compartmental model.
The SI model includes:
- Susceptible (S): Individuals who can become infected
- Infected (I): Individuals who are infectious
Transitions:
- S + I → I + I (infection/transmission)
The SI model represents endemic diseases with no recovery.
Fields
number_I_stages::Int64number_of_states::Int64demography::Demography
Susceptible-Infected-Recovered (SIR) compartmental model.
The SIR model extends SI with recovery:
- Susceptible (S): Individuals who can become infected
- Infected (I): Individuals who are infectious
- Recovered (R): Individuals who have recovered and gained immunity
Transitions:
- S + I → I + I (infection/transmission) [from SI]
- I → R (recovery) [extension]
Built by extending SI model with recovery transition.
Fields
number_I_stages::Int64number_of_states::Int64demography::Demography
Susceptible-Infected-Susceptible (SIS) compartmental model.
The SIS model extends SI with waning immunity (reversion):
- Susceptible (S): Individuals who can become infected
- Infected (I): Individuals who are infectious
Transitions:
- S + I → I + I (infection/transmission) [from SI]
- I → S (waning immunity/reversion) [extension]
The SIS model represents diseases with no lasting immunity.
Fields
number_I_stages::Int64number_of_states::Int64demography::Demography
AlgebraicEpiMech.Stratification — Type.
Represents a stratification structure for epidemiological models.
Fields
AlgebraicEpiMech.UninfectedInfectedTyping — Type.
Typing strategy that distinguishes uninfected and infected populations. The two populations may have different stratifications.
Examples
typing = UninfectedInfectedTyping()
typing = UninfectedInfectedTyping(
uninfected_type = :Susceptible,
infected_type = :Infectious,
)
See also: type_system, OnePopulationTyping
Fields
uninfected_type::Symbol: The symbolic name for the uninfected population.infected_type::Symbol: The symbolic name for the infected population.
AlgebraicEpiMech.AgeStratification — Method.
AgeStratification(age_group_names::Vector{Symbol}; kwargs...)
AgeStratification(names...; kwargs...)
A ContactStratification with label :age; transitions declares ageing between age groups, and births and deaths the groups newborns enter and deaths leave.
Examples
age = AgeStratification([:child, :adult, :elderly])
age = AgeStratification(:child, :adult, :elderly) # splatting syntax
aging = AgeStratification([:child, :adult]; transitions = [:child => :adult])
AlgebraicEpiMech.GeographicStratification — Method.
GeographicStratification(location_names::Vector{Symbol}; kwargs...)
GeographicStratification(names...; kwargs...)
A ContactStratification with label :geography; transitions declares movement between regions, and births and deaths the regions with demography.
Examples
geo = GeographicStratification([:urban, :suburban, :rural])
geo = GeographicStratification(:urban, :suburban, :rural) # splatting syntax
AlgebraicEpiMech.add_birth! — Method.
Add a :birth box, an entry into junction with no source, so its mass-action rate is zero-order (births per unit time). The junction must have the uninfected population type. Returns the new box.
AlgebraicEpiMech.add_death! — Method.
Add a death box, an exit from junction with no target, typed :death (or :death_U / :death_I under the uninfected/infected split). The mass-action rate is per capita. Returns the new box.
AlgebraicEpiMech.add_disease_progression! — Method.
Add disease progression mechanism: fromcompartment → tocompartment
Used for transitions like E→I, I→R, etc. (infected → infected transitions)
AlgebraicEpiMech.add_importation! — Method.
add_importation!(
uwd,
from_junction::Integer,
to_junction::Integer,
typing::EpidemiologicalTyping
) -> Any
Add an :importation box: from_junction (uninfected) becomes to_junction (infected) with no infector, so the mass-action rate is per capita. Returns the new box.
AlgebraicEpiMech.add_infection! — Method.
add_infection!(
uwd,
infectee_junction,
infector_junction,
first_infected_junction,
typing::OnePopulationTyping
) -> Any
Add infection mechanism: Infectee + Infector → first_infected + Infector
General infection mechanism where an infectee (typically S) interacts with an infector (typically I) to produce a newly infected individual that enters the first*infected compartment, while the infector remains unchanged. The first*infected_junction can be:
- An I stage for SIR-like models (direct infection)
- An E stage for SEIR-like models (exposure before infectiousness)
The typing argument determines the population types used.
AlgebraicEpiMech.add_reversion_progression! — Method.
Add reversion progression mechanism: e.g. R → S (infected → uninfected transitions)
Used for transitions from infected compartments back to uninfected compartments.
AlgebraicEpiMech.add_strata_transition! — Method.
add_strata_transition!(
uwd,
from_junction::Integer,
to_junction::Integer,
typing::EpidemiologicalTyping
) -> Any
Add a movement box between two junctions of the same population type, typed by that population's movement type (:strata, or :strata_U / :strata_I under the uninfected/infected split). Movement changes an individual's stratum and keeps its disease state; in a typed_product it pairs with the reflexive movement boxes of the other factors (see include_reflexives on create_model). The mass-action rate is per capita. Returns the new box.
AlgebraicEpiMech.add_uninfected_density_progression! — Method.
add_uninfected_density_progression!(
uwd,
from_junction,
to_junction,
typing::OnePopulationTyping
) -> Any
Add uninfected density progression mechanisms. This is useful for transitions like waning partial immunity (uninfected → uninfected transitions, e.g., V → S).
AlgebraicEpiMech.attach_observation — Method.
Attach an observation chain to pn, returning a new net. The result is the colimit described at the top of this file, materialized in one direct pass (see the note there for why it is not built by pushout).
n_stages Erlang delay stages are added per chain: the first receives the observation, each subsequent one takes flow from the last, and the final stage is cumulative (no outflow), i.e. the accumulator the observation model reads.
Reapplying the same target, prefix, and stage count is idempotent. Reusing a target and prefix for an incompatible chain shape throws an ArgumentError; choose a different prefix when both observation layouts are required.
Chains are grouped by stratum. For AtEvent the group is the transition's net product — for infection routes S_x + I_y -> E_x + I_y that is E_x, so all routes infecting x count into x's chain. A transition with no output (a death) is grouped by the species it leaves, and the target's group can merge these groups further. For AtCompartment each matched species gets its own chain.
Apply this after all typed_product composition so chains are grouped over the final strata.
AlgebraicEpiMech.compose_stratifications — Method.
compose_stratifications(
a::ContactStratification,
b::ContactStratification
) -> ContactStratification
The Cartesian product of two contact stratifications, with combined stratum names and the label a_x_b. Movement graphs multiply: every edge of one factor pairs with every edge of the other, and a static factor contributes the identity on its strata, so ageing × static geography ages within each location. Two static factors give a static product. Births and deaths multiply the same way, a factor that declares none contributing all of its strata.
Examples
age = ContactStratification([:child, :adult], :age; transitions = [:child => :adult])
geo = ContactStratification([:urban, :rural], :geography)
age_geo = compose_stratifications(age, geo)
# Resulting stratum names: [:childxurban, :childxrural, :adultxurban, :adultxrural]
# Resulting label: :age_x_geography
# Resulting transitions: [:childxurban => :adultxurban, :childxrural => :adultxrural]
AlgebraicEpiMech.create_model — Method.
create_model(
typing::EpidemiologicalTyping,
model::EpiMechModel;
include_reflexives
) -> Catlab.CategoricalAlgebra.Pointwise.ACSetTransformations.StructACSetTransformation{ACSets.Schemas.TypeLevelBasicSchema{Symbol, Tuple{:T, :S, :I, :O}, Tuple{(:it, :I, :T), (:is, :I, :S), (:ot, :O, :T), (:os, :O, :S)}, Tuple{:Name}, Tuple{(:tname, :T, :Name), (:sname, :S, :Name)}, Tuple{}}, Comp, AlgebraicPetri.LabelledPetriNet, AlgebraicPetri.LabelledPetriNet} where Comp<:NamedTuple
Create a typed Petri net model from an epidemiological typing strategy and model specification.
This is the unified entry point for creating all model types in AlgebraicEpiMech. Through multiple dispatch on the model parameter, it supports any subtype of EpiMechModel. The undirected wiring diagram (UWD) provides an intermediate structural representation, recording how compartments and mechanisms connect independently of the final typed Petri net constructed by oapply_typed.
The resulting typed Petri net can be used directly for ODE simulation or composed with other typed Petri nets via typed_product to build complex hierarchical models.
Arguments
typing::EpidemiologicalTyping: The strategy defining possible compartment and transition types.model::EpiMechModel: The model specification (uses dispatch for different types)
Keyword Arguments
include_reflexives = true: the transition types this factor is passive for. Atyped_productkeeps a transition type only if every factor has a box of that type, so a factor carries a reflexive box, on each junction of the matching population type, for every listed type it does not implement. Acceptstrue(the defaults ofdefault_reflexives),false(none, for standalone use), or a transition type name or collection of them, such as:strataor(:disease, :strata).:stratastands for every movement type of the typing (:strata_Uand:strata_Iunder the uninfected/infected split), and:deathfor every death type. Listed types the factor already implements are skipped.:birthcannot be passive: declarebirthson the model specification. Stratification factors list:importationto keep a disease model's importation per stratum; a compartmental model cannot, and declaresimportation = trueinstead.
Returns
-
ACSetTransformation: A typed Petri net with two components accessible via:dom(typed_model): Extract the underlyingLabelledPetriNetfor ODE solvingcodom(typed_model): Access the Petri-net type system
Model-Specific Transition Naming
Transition names are generated automatically based on model type:
- Compartmental:
transmission_S_I,E_to_I,I_to_R(describes flow between compartments) - Age Stratification:
child_child,child_adult,adult_child(infectee_infector pattern) - Multistrain: Strain identifiers like
h1n1,h3n2(enables clean composition) - Movement (
transitionson aContactStratification):child_to_adult - Reflexive boxes: the junction's variable (
child,child_U); on a compartmental modelS,I,Rfor movement types and the type-prefixedwaning_Sfor any other - Births and deaths:
birth_S,death_S; composites readbirth_S_child,death_I_adult - Importation:
importation_S_to_E; withImmuneHistory,importation_S_to_E_import_a_naive
These names become ODE parameters and differ from box names (:transmission, :density) used for composition.
Examples
# Basic compartmental model
typing = OnePopulationTyping()
seir = create_model(typing, SEIR())
seir_pn = dom(seir) # Extract for ODE solving
# Transitions: :transmission_S_I, :E_to_I, :I_to_R
# Multi-stage compartments (gamma-distributed delays)
si_multi = create_model(typing, SI(number_I_stages=3))
# Transitions: :transmission_S_I1, :transmission_S_I2, :transmission_S_I3, :I1_to_I2, :I2_to_I3
# Age-structured model
age_strat = AgeStratification([:child, :adult, :elderly])
age_model = create_model(typing, age_strat)
# Transitions: :child_child, :child_adult, :child_elderly, :adult_child, ...
# Multistrain model (no cross-immunity)
strains = NoCrossImmunity([:h1n1, :h3n2, :seasonal_b])
strain_model = create_model(typing, strains)
# Compose models via typed_product
sir = create_model(typing, SIR())
age = create_model(typing, AgeStratification([:child, :adult]))
age_sir = typed_product(sir, age)
age_sir_pn = dom(age_sir)
# Result: S_child, I_child, R_child, S_adult, I_adult, R_adult compartments
# Transition names become tuples: (:transmission_S_I, :child_adult)
# Ageing: the age factor implements movement, the disease model is passive for it
sir = create_model(typing, SIR(); include_reflexives = :strata)
aging = create_model(typing, AgeStratification([:child, :adult]; transitions = [:child => :adult]))
aging_sir = dom(typed_product(sir, aging))
# Adds S_child_to_adult, I_child_to_adult, R_child_to_adult
# Births into children, deaths out of adults
sir = create_model(typing, SIR(births = [:S]); include_reflexives = (:strata, :death))
age = AgeStratification([:child, :adult]; transitions = [:child => :adult], births = [:child], deaths = [:adult])
open_sir = dom(typed_product(sir, create_model(typing, age)))
# Adds birth_S_child, death_S_adult, death_I_adult, death_R_adult
Compositional Design
Models expressed as typed Petri nets compose via typed_product using their common type-system codomain when box names match. The vectorfield_flat function automatically handles tuple transition names in composed models for ODE parameter assignment.
See also: create_model_uwd, generate_transition_names, type_system, default_reflexives, typed_product (from AlgebraicPetri.TypedPetri), vectorfield_flat
AlgebraicEpiMech.create_model_uwd — Method.
The undirected wiring diagram (UWD) of a compartmental model under typing: one junction per compartment, typed by the typing's population types, and one box per transition, plus the births, deaths and importation declared by the model's Demography. Importation enters the first infected stage (E1 or I1). The UWD declares no outer ports; oapply_typed derives the boundary from its junctions.
Multi-stage compartments (number_E_stages, number_I_stages) are chained, and recovery or reversion always leaves the last infectious stage.
Examples
sir_uwd = create_model_uwd(OnePopulationTyping(population_type = :Individual), SIR())
typing = UninfectedInfectedTyping(uninfected_type = :Susceptible, infected_type = :Infectious)
seir_uwd = create_model_uwd(typing, SEIR(births = [:S])) # S::Susceptible, E, I, R::Infectious
AlgebraicEpiMech.create_model_uwd — Method.
create_model_uwd(
typing::EpidemiologicalTyping,
model::ContactStratification;
include_reflexives
) -> Catlab.WiringDiagrams.RelationDiagrams.TypedUnnamedRelationDiagram{Symbol, Symbol, Symbol}
Construct an undirected wiring diagram (UWD) for contact strata.
Creates an UWD where transmission boxes represent contact patterns between different strata. Example strata include age groups, risk levels, or demographic divisions, but only covers instantaneous transmission dynamics, e.g. movement between geographic regions would require additional demographic modeling.
The UWD structure depends on the typing:
OnePopulationTyping: Single junction per age group (combined susceptible/infected)UninfectedInfectedTyping: Two junctions per age group (uninfected and infected)
All transmission boxes are created with the :transmission name, enabling composition with compartmental models that have :transmission boxes (SI, SIR, SEIR, etc.).
Arguments
typing::EpidemiologicalTyping: The population typing defining type systemmodel::ContactStratification: The contact stratification configuration with stratum names
Returns
- Undirected wiring diagram with stratum junctions and transmission boxes for composition
Mathematical Structure
For n strata, creates n² transmission boxes representing the contact matrix:
- Diagonal boxes (i→i): within-stratum transmission
- Off-diagonal boxes (i→j, i≠j): between-stratum transmission
Composition Behavior
When composed with a compartmental model UWD via typed_product, the transmission boxes will align based on the :transmission name, allowing the contact structure to modulate the disease dynamics defined in the compartmental model.
The movement graph (model.transitions) adds one movement box per edge and population type through add_strata_transition!. Declared births enter a stratum's uninfected junction (add_birth!) and declared deaths leave each of its junctions (add_death!).
Keyword Arguments
include_reflexives = true: the transition types this factor is passive for (seecreate_model). The per-stratum:disease,:reversion,:waningand:importationboxes are added when listed; any other listed type is added bycreate_model.:importationis not a default: list it to keep a disease model's importation within each stratum.
AlgebraicEpiMech.create_model_uwd — Method.
Immune-history stratification requires the uninfected/infected type split.
AlgebraicEpiMech.create_model_uwd — Method.
create_model_uwd(
typing::OnePopulationTyping,
multistrain::NoCrossImmunity
) -> Catlab.WiringDiagrams.RelationDiagrams.TypedUnnamedRelationDiagram{Symbol, Symbol, Symbol}
Construct an undirected wiring diagram (UWD) for a no cross-immunity multistrain model.
Creates a strain-stratified UWD where each strain operates independently. The strains are represented as separate junctions, and each strain has its own set of disease transition boxes (:transmission, :disease, :reversion) that will compose with corresponding boxes from a compartmental model via typed_product.
All box types are always included; typed_product will only compose boxes that exist in both UWDs, naturally filtering out non-matching transitions. That filtering is silent — a transition present in one factor and absent from the other is dropped without error — which is why each factor carries a reflexive box per transition type it wants preserved.
There is deliberately no reflexive observation box. Observation is attached to the COMPOSED net by attach_observation, so a stratification factor never has to know it exists.
Arguments
typing::OnePopulationTyping: The required single-population typingmultistrain::NoCrossImmunity: The multistrain model configuration with strain names
Returns
- Undirected wiring diagram with strain junctions and transition boxes for composition
Examples
# Create a 3-strain model with custom names
typing = OnePopulationTyping()
multistrain = NoCrossImmunity([:h1n1, :h3n2, :b])
strain_uwd = create_model_uwd(typing, multistrain)
# Compose with compartmental model
sir_typed = create_model(typing, SIR())
strain_typed = create_model(typing, multistrain)
combined = typed_product(sir_typed, strain_typed)
AlgebraicEpiMech.create_model_uwd — Method.
create_model_uwd(
typing::UninfectedInfectedTyping,
multistrain::CompleteCrossImmunity
) -> Catlab.WiringDiagrams.RelationDiagrams.TypedUnnamedRelationDiagram{Symbol, Symbol, Symbol}
Construct an undirected wiring diagram (UWD) for a complete cross-immunity multistrain model.
Creates a strain-structured UWD where all strains share a common susceptible pool but have separate infected compartments. Infection by any strain depletes the shared susceptible pool and confers immunity to all strains.
The UWD has:
- One shared uninfected/susceptible junction
- N infected strain junctions
- Transmission boxes connecting shared susceptible to each strain's infected
- Disease progression boxes for each strain's infected compartments
- Reversion boxes to return to shared susceptible pool
Arguments
typing::UninfectedInfectedTyping: The required uninfected/infected typingmultistrain::CompleteCrossImmunity: The multistrain model configuration with strain names
Returns
- Undirected wiring diagram with shared susceptible and strain-specific infected junctions
Examples
# Create a 2-strain competing model
typing = UninfectedInfectedTyping()
multistrain = CompleteCrossImmunity([:wild_type, :variant])
strain_uwd = create_model_uwd(typing, multistrain)
# Compose with compartmental model
sir_typed = create_model(typing, SIR())
strain_typed = create_model(typing, multistrain)
combined = typed_product(sir_typed, strain_typed)
AlgebraicEpiMech.create_model_uwd — Method.
create_model_uwd(
typing::UninfectedInfectedTyping,
model::ImmuneHistory;
include_reflexives
) -> Catlab.WiringDiagrams.RelationDiagrams.TypedUnnamedRelationDiagram{Symbol, Symbol, Symbol}
Construct the UWD for the ImmuneHistory stratification factor over a UninfectedInfectedTyping.
This is a stratification factor (like ContactStratification), meant to be typed_product-composed with a disease model — the disease model supplies S→E→I→R, while this factor supplies the immune-status structure.
- Uninfected junctions
U_h, one per immune-history class. - Infected junctions
(h,i)= "historyh, currently fighting straini", one per (class, susceptible-strain) pair. :transmission(escape-selective):U_h + (h',i) → (h,i)for every susceptible classh(i ∉ h) and every infector(h',i). A class immune toisimply has no such box, so the pullback drops that infection — the escape.:diseaseis reflexive on each(h,i), so the base model's progression runs inside a fixed(h,i).:reversionis off-diagonal:(h,i) → U_{recover}withrecover = h∪{i}(FullHistory) or{i}(LatestInfection). This is the one stratum-changing move — recovering fromifolds it into the immune history.:waning: withwaning = true, edgesU_h → U_{h∖{i}}for every strainiinh, namedwane_<i>_<h>(wane_b_a_bforU_a_b → U_a); the disease model then needsinclude_reflexives = :waningso the pullback keeps them. Otherwise:waningis reflexive on eachU_h(inert with SEIRS; lets a waning-bearing base compose).:importation:U_h → (h,i)for every susceptible pair, namedimport_<i>_<h>.
The :disease, :waning and :importation boxes are added when listed in include_reflexives (see create_model); :disease and :waning are by default.
Examples
typing = UninfectedInfectedTyping()
history = create_model(typing, ImmuneHistory([:current, :invader]))
model = typed_product(create_model(typing, SEIRS()), history)
# Waning immunity, independent of the disease model's own dynamics
waning = create_model(typing, ImmuneHistory([:current, :invader]; waning = true))
model = typed_product(create_model(typing, SIR(); include_reflexives = :waning), waning)
# adds waning_S_wane_invader_current_invader, …
AlgebraicEpiMech.default_reflexives — Method.
The transition types a factor is passive for under include_reflexives = true.
| Model | Default |
|---|---|
CompartmentalModel, MultiStrainModel |
none; pass :strata to compose with a moving stratification, :death with one that has deaths |
ContactStratification |
:disease, :reversion, :waning |
ImmuneHistory |
:disease, :waning |
Extend a default rather than restating it: include_reflexives = (default_reflexives(typing, model)..., :strata).
AlgebraicEpiMech.flatten_symbols — Method.
Recursively flatten a tuple of symbols and join them with underscores.
Examples
flatten_symbols((:x, :y, :z)) # returns :x_y_z
flatten_symbols(((:x, :y), :z)) # returns :x_y_z
flatten_symbols((((:a, :b), :c), :d)) # returns :a_b_c_d
AlgebraicEpiMech.generate_transition_names — Method.
Generate transition names from UWD structure for compartmental models.
For boxes with 2 ports (one input, one output), generates names in the format input_to_output. For boxes with 4 ports (two inputs, two outputs), generates names in the format box_name_input1_input2 where inputs are sorted in reverse alphabetical order for consistency (e.g., transmission_S_I). Birth and death boxes have one port and are named birth_S, death_I. An importation box is named importation_S_to_E.
Arguments
uwd: The undirected wiring diagram with species names in junction :variable attributesmodel::CompartmentalModel: The compartmental model (used for dispatch)
Returns
Vector{Symbol}: Vector of unique transition names, one per box in the UWD
Examples
# Used internally by create_model
typing = OnePopulationTyping()
uwd = create_model_uwd(typing, SEIR())
names = generate_transition_names(uwd, SEIR())
# Returns: [:transmission_S_I, :E_to_I, :I_to_R]
See also: create_model
AlgebraicEpiMech.generate_transition_names — Method.
Generate transition names for a ContactStratification UWD.
- Transmission boxes are named
infectee_infector, e.g.child_adultfor a child infected by an adult. - Movement boxes are named
source_to_target, e.g.child_to_adultorchild_U_to_adult_U. - Reflexive, birth and death boxes take their stratum's junction variable, e.g.
child, so a composite readsI_to_R_childorbirth_S_child.
Examples
age = AgeStratification([:child, :adult])
uwd = create_model_uwd(OnePopulationTyping(), age; include_reflexives = false)
generate_transition_names(uwd, age) # [:child_child, :child_adult, :adult_child, :adult_adult]
See also: create_model, ContactStratification, AgeStratification
AlgebraicEpiMech.generate_transition_names — Method.
Generate transition names for the ImmuneHistory stratification factor. These become the second component of the composed typed_product transition names.
:transmission(4-port) →infect_<strain>_<susceptible-class>_by_<infector-class>, exposing the infecting strain (recovered from the infector junction) so the composed name stays keyable per strain.:waningedges (waning = true) →wane_<strain>_<class>: the strain forgotten, then the class it is forgotten from, e.g.wane_b_a_bforU_a_b → U_a.:importation(U_h → (h,i)) →import_<strain>_<class>, e.g.import_b_naive.- reflexive / reversion boxes (2–3 port) → the first junction's variable, mirroring
ContactStratification— e.g. the:diseasereflexives and the off-diagonal:reversionon(h,i)are named by that(h,i), and a reflexive:waningby itsU_h. Composition with the base disambiguates them (base name differs).
Every name that changes stratum starts with its strain, so a per-strain rate is keyed by prefix in the composed name.
Examples
factor = create_model_uwd(UninfectedInfectedTyping(), ImmuneHistory([:current, :invader]))
names = generate_transition_names(factor, ImmuneHistory([:current, :invader]))
# transmission names begin `infect_current…` / `infect_invader…`
AlgebraicEpiMech.kinetic_structure — Method.
kinetic_structure(
pn::AlgebraicPetri.AbstractPetriNet;
rate_class,
fixed,
sigdigits
) -> KineticStructure
Analyse the mass-action kinetics of pn once, from its arcs and its rate classes, into the factored form vectorfield_factored evaluates.
Arguments
rate_class: a function from a transition's name (astnamegives it, so a tuple for a typed product) to(key, weight)orkey => weight. The transition's rate isweight * p[key], andkeyis flattened withflatten_symbols. By default every transition is its own class with weight one and the keys are the flattened transition names, which is the contract ofvectorfield_flat.fixed: rates by key (aNamedTupleor a dictionary) that never change. They are folded into the constants andpmust not supply them.sigdigits: weight vectors that agree to this many significant digits once scaled share a factor.
Analysis
- Zero-order and first-order transitions become a constant vector and sparse linear operators, one per key, with the fixed keys summed into a single constant operator.
- A second-order transition with an input that is also an output is catalysed. Such transitions are grouped into classes by substrate and net stoichiometry, so a class's flux is
x[substrate] * Σ_c B[class, c] x[c]. - Each key's part of
Bis split by row direction: rows proportional to one another share a right factor, so a rank-one part costs one inner product and anything else keeps its rows. - Right factors, and the left factors that carry them back to classes, are merged across keys.
- Every other transition is kept in a flat loop.
The report field holds the counts; see KineticReport.
AlgebraicEpiMech.observation_layout — Method.
Return deterministic observation-chain metadata for an augmented Petri net.
The result is an ObservationLayout with fields:
obs_names: all flattened observation state names in Petri-net orderchains: orderedObservationChainLayoutvaluescumulative_names: flattened terminal observation state for each chain
This centralizes the observation naming/ordering contract, so downstream packages do not each re-implement observation-state parsing. prefix must match the prefix passed to attach_observation. The function recognises the <prefix>_<source>_<stage> leaf that attach_observation produces; a chain named otherwise is not recognised as one.
AlgebraicEpiMech.type_system — Method.
The LabelledPetriNet that a typed Petri net built under typing maps into: one species per population type and these transition types.
| Transition type | OnePopulationTyping |
UninfectedInfectedTyping |
|---|---|---|
:transmission |
(P, P) → (P, P) |
(U, I) → (I, I) |
:disease |
P → P |
I → I |
:reversion |
P → P |
I → U |
:waning |
P → P |
U → U |
:strata (movement) |
P → P |
:strata_U: U → U, :strata_I: I → I |
:birth |
∅ → P |
∅ → U |
:death |
P → ∅ |
:death_U: U → ∅, :death_I: I → ∅ |
:importation |
P → P |
U → I |
A birth has no input, so its mass-action rate is zero-order (births per unit time); a death has no output and a per-capita rate. Importation is infection from outside the modelled population: it has no infector, so its rate is per capita.
extras are further name => (inputs => outputs) transition types, appended for Petri-level experiments; create_model uses only the standard ones.
Examples
type_system(OnePopulationTyping(population_type = :Individual))
type_system(UninfectedInfectedTyping(), :vaccination => (:Uninfected => :Uninfected))
AlgebraicEpiMech.vectorfield_factored — Method.
vectorfield_factored(
structure::KineticStructure
) -> AlgebraicEpiMech.var"#vectorfield!#vectorfield_factored##0"{KineticStructure, AlgebraicEpiMech._NamePositions, AlgebraicEpiMech._NamePositions, AlgebraicEpiMech._NamePositions, Int64}
vectorfield_factored(structure::KineticStructure) -> vectorfield!(du, u, p, t)
vectorfield_factored(pn; kwargs...)
The mass-action vector field of a Petri net from its kinetic_structure. u and du are indexed by flattened species name as for vectorfield_flat, and p holds one rate per key of structure.rate_keys, by name. A rate may be a function of (u, t).
The two fields agree to rounding, not bit for bit, because the factored form sums in a different order. With the default rate classes p is keyed by transition name and the call is interchangeable with vectorfield_flat.
AlgebraicEpiMech.vectorfield_flat — Method.
vectorfield_flat(
pn::AlgebraicPetri.AbstractPetriNet
) -> AlgebraicEpiMech.var"#vectorfield!#vectorfield_flat##8"{AlgebraicEpiMech._NamePositions, AlgebraicEpiMech._NamePositions, AlgebraicEpiMech._NamePositions, Vector{Vector{Tuple{Int64, Int64}}}, Vector{Vector{Tuple{Int64, Int64}}}, Vector{T}, Vector{T1}, Int64, Int64} where {T, T1}
Generate an ODE vectorfield function from a Petri net using mass action kinetics as per AlgebraicPetri.vectorfield. The only difference is that species and transition names are flattened using flatten_symbols, converting nested tuples into single symbols joined by underscores.
Arguments
pn::AbstractPetriNet: A Petri net representing the reaction network
Returns
A function (du, u, p, t) -> du where:
du: Array/Dict to store computed derivativesu: Current state (species concentrations), indexed by flattened species namesp: Parameters (rate constants), indexed by flattened transition namest: Current time
This function complies with SciML conventions for in-place ODE vectorfields.
Performance
Everything that can be resolved from the net alone — flattened names, the mass-action input lists, the nonzero stoichiometry — is resolved once at build time, and the right-hand side is a sparse loop over arcs rather than a dense loop over transitions × species. Name lookup into the arguments is also done once per concrete argument type: u, du and p may be anything whose propertynames lists the flattened names in the same order as its integer indexing (LVector, NamedTuple, ...), and that position map is cached on first sight of the type; an AbstractDict is looked up by name on every call.