simcronomicon.compartmental_models package
Core Building Blocks
The most important building blocks for defining compartmental models in simcronomicon are the abstract model classes and the step event system.
Abstract Models The abstract_model module provides the abstract base classes that define the required structure and interface for all compartmental models. Every specific model (such as SEIR, SEIQRDV, etc.) is built on top of these abstract classes, specifying their own rules for agent status transitions and model-specific logic. If you want to create a new model, you will subclass these abstract classes and implement your own conversion rules and behaviors.
Step Events The step_event module defines the event system that controls agent activities and movement during each simulation step. Step events are a key user input to each model: you can use the default events provided in the abstract model, or define your own custom events. The sequence and logic of step events dictate how agents move, interact, and progress through the simulation.
Together, these modules form the foundation for all other compartmental models in simcronomicon. Understanding and extending them is essential for advanced model customization.
Submodules
simcronomicon.compartmental_models.abstract_model module
- class simcronomicon.compartmental_models.abstract_model.AbstractCompartmentalModel(model_params)
Bases:
object
Abstract base class for all compartmental epidemic models.
This class provides the foundation for implementing compartmental models (e.g., SIR, SEIR, SEIQRDV) in agent-based simulations. It handles agent creation, step event management, population initialization, and defines the interface that all compartmental models must implement.
- Parameters:
model_params (AbstractModelParameters) – Model-specific parameters object containing simulation configuration.
- model_params
Configuration parameters for the model.
- Type:
- infected_statuses
List of status strings considered infectious (must be defined by subclasses).
- Type:
list
- all_statuses
Complete list of all possible agent statuses (must be defined by subclasses).
- Type:
list
- required_place_types
Set of place types required by the model (includes ‘accommodation’, ‘commercial’).
- Type:
set
- folk_class
The Folk class or subclass used to create agents (must be defined by subclasses).
- Type:
class
Notes
Subclasses must define ‘infected_statuses’, ‘all_statuses’, and ‘folk_class’ before calling the parent constructor.
An ‘end_day’ event is automatically appended to step_events if not provided.
Default step_events include neighborhood greeting and commercial activities.
- create_folk(*args, **kwargs)
Create a new AbstractFolk agent using the model’s folk_class.
- Returns:
A new AbstractFolk agent instance of a given folk_class.
- Return type:
- initialize_sim_population(town)
Initialize simulation population data structures and validate spreader configuration.
This method sets up the basic data structures needed for population initialization and validates that the spreader configuration is valid. It prepares containers for agent creation and household assignment.
- Parameters:
town (Town) – The town network where agents will be placed.
- Returns:
Contains (num_pop, num_init_spreader, num_init_spreader_rd, folks, household_node_indices, assignments) where: - num_pop : int - Total population size - num_init_spreader : int - Total number of initial spreaders - num_init_spreader_rd : int - Number of randomly placed spreaders - folks : list - Empty list for agent objects - household_node_indices : set - Empty set for household node tracking - assignments : list - Empty list for agent assignments
- Return type:
tuple
Notes
This method only initializes data structures and validates configuration. Actual agent creation and placement is handled by the Simulation class.
- update_population(folks, town, household_node_indices, status_dict_t)
Update the simulation population (e.g., add or remove agents).
This method is called at the end of each day. By default, it does nothing. Subclasses can override this method to implement population growth, death, or migration.
- Parameters:
folks (list of AbstractFolk) – The current list of AbstractFolk agent objects in the simulation.
town (Town) – The Town object representing the simulation environment.
status_dict_t (dict) – Dictionary tracking the count of each status at the current timestep.
- Returns:
An updated number of overall population
- Return type:
int
- class simcronomicon.compartmental_models.abstract_model.AbstractFolk(id, home_address, max_energy, status)
Bases:
object
Agent class representing individuals in the simulation.
AbstractFolk objects represent individual agents that move through the town network, interact with other agents, and undergo status transitions according to compartmental model rules. Each agent has energy, status, location, and behavioral attributes that influence their participation in simulation events.
- Parameters:
id (int) – Unique identifier for the agent.
home_address (int) – Node index of the agent’s home location in the town network.
max_energy (int) – Maximum social energy. Limits the number of events an agent can attend daily.
status (str) – Initial compartmental status of the agent (e.g., ‘S’, ‘I’, ‘R’).
- id
Unique agent identifier.
- Type:
int
- home_address
Home node index in the town network.
- Type:
int
- address
Current location node index (initially set to home_address).
- Type:
int
- max_energy
Maximum daily social energy.
- Type:
int
- energy
Current social energy (randomly initialized between 0 and max_energy).
- Type:
int
- status
Current compartmental status.
- Type:
str
- status_step_streak
Number of consecutive timesteps in current status.
- Type:
int
- movement_restricted
Whether agent movement is restricted (e.g., quarantine).
- Type:
bool
- alive
Whether the agent is alive and active in the simulation.
- Type:
bool
- priority_place_type
List of place types the agent prioritizes for visits.
- Type:
list
- clear_previous_event_effect()
Reset or update agent attributes following step events.
This method is called at the end of each simulation step to clean up temporary state changes caused by events and ensure the agent is properly prepared for the next step. Subclasses should implement this method to handle model-specific attribute resets.
- Return type:
None
- convert(new_stat, status_dict_t)
Change the agent’s status and update the status counts.
- Parameters:
new_stat (str) – The new status to assign.
status_dict_t (dict) – Dictionary tracking the count of each status at the current timestep.
- inverse_bernoulli(contact_possibility, conversion_prob)
Calculate the probability of status transition given contact possibility and conversion probability.
This function is adapted from section 2.2 of Eden, M., Castonguay, R., Munkhbat, B., Balasubramanian, H., & Gopalappa, C. (2021). Agent-based evolving network modeling: A new simulation method for modeling low prevalence infectious diseases. Health Care Management Science, 24, 623–639. https://link.springer.com/article/10.1007/s10729-021-09558-0
- Parameters:
contact_possibility (int) – Number of possible contacts.
conversion_prob (float) – Probability of conversion per contact.
- Returns:
Probability of at least one successful conversion.
- Return type:
float
- sleep()
Reset the agent’s energy and increment the status streak (called at the end of a day).
- class simcronomicon.compartmental_models.abstract_model.AbstractModelParameters(max_energy)
Bases:
object
Base class for compartmental model parameters.
This abstract class defines the common interface for all compartmental model parameter classes. It provides basic energy management and requires subclasses to implement metadata serialization for simulation persistence.
- Parameters:
max_energy (int) – The maximum energy for an agent. This number limits the maximum number of events an agent can attend in a day.
- max_energy
Maximum social energy value for agents in the simulation.
- Type:
int
- to_metadata_dict()
Convert model parameters to a dictionary for metadata serialization.
This abstract method must be implemented by subclasses to enable saving and loading of simulation configurations. The returned dictionary should contain all parameter values needed to reconstruct the model.
- Raises:
NotImplementedError – Always raised in the base class. Subclasses must override this method.
simcronomicon.compartmental_models.step_event module
- class simcronomicon.compartmental_models.step_event.EventType(*values)
Bases:
Enum
Step events are classified into two types.
DISPERSE is the type of event
that send agents around the town graph to specific locations in a given range and allow them to interact with other agents who are in the same nodes..
SEND_HOME is the type of event that every agents in the simulation back to their home address without any interaction.
SEND_HOME can represent the end of the day where everybody go home and sleep or an emergency announcement that sends everyone around town straight back home.
- DISPERSE = 'disperse'
- SEND_HOME = 'send_home'
- class simcronomicon.compartmental_models.step_event.StepEvent(name, folk_action, event_type=EventType.SEND_HOME, max_distance=0, place_types=[], probability_func=None)
Bases:
object
Defines agent activities and movement patterns during simulation timesteps.
StepEvent objects represent discrete activities that agents perform during simulation timesteps. Each event specifies how agents move through the town network, what types of locations they visit, and what actions they perform when they arrive at destinations.
Purpose
Agent Movement Control: Define where and how far agents travel during specific activities (work, shopping, healthcare visits, etc.).
Location Targeting: Specify which types of places agents visit for different activities using place type filters.
Mobility Modeling: Apply realistic human mobility patterns through customizable probability functions based on distance and agent characteristics.
Agent-Dependent Behavior: Enable mobility patterns that adapt to individual agent properties such as energy levels, status, or other attributes.
Event Types
DISPERSE: Agents move to locations within specified distance and place type constraints. Enables agent-to-agent interactions at destinations.
SEND_HOME: All agents return directly to their home addresses without movement or interaction. Represents end-of-day or emergency scenarios.
Probability Functions
Custom probability functions must:
Accept exactly 2 non-default arguments: (distances, agent)
Return probabilities between 0 and 1 (will be normalized automatically)
Handle numpy arrays for distances
Be robust to edge cases (empty arrays, zero distances)
Built-in mobility functions include: - log_normal_mobility: Human mobility based on log-normal distance
energy_exponential_mobility: Agent energy-dependent exponential decay
- name
Event identifier.
- Type:
str
- max_distance
Maximum travel distance in meters.
- Type:
int
- place_types
Allowed destination place types.
- Type:
list
- folk_action
Agent interaction function.
- Type:
callable
- probability_func
Distance and agent-based mobility probability function.
- Type:
callable or None
Examples
>>> # End of day event >>> end_day = StepEvent("end_day", folk_class.sleep) >>> >>> # Work event with distance constraints >>> work = StepEvent("work", folk_class.interact, EventType.DISPERSE, ... max_distance=10000, place_types=['workplace']) >>> >>> # Shopping with log-normal mobility >>> shopping = StepEvent("shopping", folk_class.interact, EventType.DISPERSE, ... max_distance=5000, place_types=['commercial'], ... probability_func=log_normal_mobility) >>> >>> # Energy-dependent movement >>> leisure = StepEvent("leisure", folk_class.interact, EventType.DISPERSE, ... max_distance=8000, place_types=['commercial', 'religious'], ... probability_func=energy_exponential_mobility) >>> >>> # Custom agent-dependent mobility >>> def age_based_mobility(distances, agent): ... import numpy as np ... distances = np.array(distances) ... # Older agents prefer shorter distances ... age_factor = getattr(agent, 'age', 30) / 100.0 # Normalize age ... decay_rate = 0.0001 * (1 + age_factor) # Higher decay for older agents ... probs = np.exp(-decay_rate * distances) ... return probs / probs.sum() if probs.sum() > 0 else np.ones_like(probs) / len(probs) >>> >>> custom_event = StepEvent("age_sensitive", folk_class.interact, EventType.DISPERSE, ... max_distance=15000, place_types=['healthcare'], ... probability_func=age_based_mobility)
- simcronomicon.compartmental_models.step_event.energy_exponential_mobility(distances, folk, distance_scale=1000)
Return probabilities proportional to exponential PDF of distances. With lam = inverse of normalized energy as a rate parameter - higher energy = lower decay rate = more willing to travel far.
- Parameters:
distance_scale (float) – Scale factor for distances to control decay rate. Higher values = slower decay. Default 1000 means distances are scaled to kilometers.
- simcronomicon.compartmental_models.step_event.log_normal_mobility(distances, folk, median_distance=2000, sigma=1.0)
Return probabilities inversely proportional to log-normal PDF of distances. Log-normal PDF has been studied to model the human mobility pattern in this following literature and its predecessor: Wang, W., & Osaragi, T. (2024). Lognormal distribution of daily travel time and a utility model for its emergence. Transportation Research Part A: Policy and Practice, 181, 104058. https://doi.org/10.1016/j.tra.2024.104058
- Parameters:
median_distance (float) – Median travel distance in meters. This is where the distribution peaks. Default 1100m (1.1km) for typical neighborhood activities. Common values: - 400m → local/walking activities - 1100m → neighborhood activities - 3000m → city-wide activities - 8000m → regional activities
sigma (float) – Shape parameter controlling spread around median. - sigma=0.5 → narrow distribution, consistent travel patterns - sigma=1.0 → moderate distribution (default) - sigma=1.5 → wide distribution, highly variable travel patterns
simcronomicon.compartmental_models.SEIQRDV_model module
- class simcronomicon.compartmental_models.SEIQRDV_model.FolkSEIQRDV(id, home_address, max_energy, status)
Bases:
AbstractFolk
Agent class for the SEIQRDV compartmental model with vaccination and mortality dynamics. FolkSEIQRDV agents extend the basic AbstractFolk with two critical attributes for epidemic modeling: will_die and want_vaccine. The will_die attribute is probabilistically set when an agent enters quarantine and determines their eventual outcome (recovery or death), reflecting the stochastic nature of disease severity. The want_vaccine attribute models vaccination-seeking behavior, where susceptible agents can spontaneously decide to seek vaccination based on the model’s alpha parameter, creating realistic vaccine demand patterns. These agents exhibit complex behavioral dynamics including healthcare-seeking movement (prioritizing healthcare facilities when want_vaccine is True), quarantine compliance (restricted movement when infectious), and status-dependent interaction patterns. The vaccination system implements a queue-based mechanism at healthcare facilities with capacity constraints, ensuring fair vaccine distribution while maintaining epidemiological realism. Additionally, agents undergo natural aging and mortality processes independent of disease status, allowing for comprehensive population dynamics that include births, deaths, migration, and demographic changes throughout the simulation period.
- clear_previous_event_effect()
Reset vaccination-related attributes following step events.
This method updates vaccination-seeking behavior attributes after events to maintain consistent state. It performs two key functions:
1. For vaccinated agents: Clears the ‘want_vaccine’ flag since they’ve already received vaccination
2. For other agents seeking vaccination: Ensures ‘healthcare_facility’ remains in their priority places for the next day’s movement
The method specifically handles: - Resetting vaccination desire for already-vaccinated agents (status ‘V’) - Maintaining healthcare facility priority for agents still seeking vaccination (except those in recovered, dead, or quarantined states who cannot benefit)
- Return type:
None
- interact(folks_here, current_place_type, status_dict_t, model_params, dice)
Perform interaction with other agents in the area and the environment for this agent.
Transition Rules
If the agent is Susceptible (‘S’):
If the agent comes into contact with at least one Infectious (‘I’) agent at the same node,
the probability of becoming Exposed (‘E’) is calculated using the inverse Bernoulli formula with the transmission probability (beta). If this probability exceeds the random value dice, the agent transitions to Exposed (‘E’).
If the agent is Susceptible (‘S’), wants a vaccine, and is at a healthcare facility:
If the number of agents at the facility wanting a vaccine is less than the hospital capacity,
the agent transitions to Vaccinated (‘V’) and want_vaccine is set to False.
- param folks_here:
List of FolkSEIQRDV agents present at the same node.
- type folks_here:
list of FolkSEIQRDV
- param current_place_type:
The type of place where the interaction occurs.
- type current_place_type:
str
- param status_dict_t:
Dictionary tracking the count of each status at the current timestep.
- type status_dict_t:
dict
- param model_params:
Model parameters for the simulation.
- type model_params:
SEIQRDVModelParameters
- param dice:
Random float for stochastic transitions.
- type dice:
float
- rtype:
None
- inverse_bernoulli(folks_here, conversion_prob, stats)
Calculate the probability of status transition given contact with specific statuses.
- Parameters:
folks_here (list of FolkSEIQRDV) – List of FolkSEIQRDV agents present at the same node.
conversion_prob (float) – Probability of conversion per contact.
stats (list of str) – List of statuses to consider as infectious.
- Returns:
Probability of at least one successful conversion.
- Return type:
float
- sleep(folks_here, current_place_type, status_dict_t, model_params, dice)
Perform end-of-day updates and state transitions for this agent.
This method handles all status progressions and transitions that occur at the end of a simulation day, including quarantine outcomes, recovery, death, infection progression, and vaccination planning.
Transition Rules
If the agent is in Quarantine (‘Q’):
If will_die is True and the agent has been in quarantine for rho days,
the agent transitions to Dead (‘D’), is marked as not alive, and want_vaccine is set to False.
If will_die is False and the agent has been in quarantine for lam days,
the agent transitions to Recovered (‘R’) and their movement restriction is lifted.
If the agent is Exposed (‘E’) and has been exposed for gamma days,
they transition to Infectious (‘I’).
If the agent is Infectious (‘I’) and has been infectious for delta days,
their symptoms are confirmed and they must quarantine. They transition to Quarantine (‘Q’), their movement is restricted, want_vaccine is set to False, and with probability kappa they are marked to die (will_die = True).
If the agent is Susceptible (‘S’) and a random draw is less than alpha,
they plan to get vaccinated by setting want_vaccine to True.
If the agent is Vaccinated (‘V’), their want_vaccine attribute is reset to False
at the end of the day to ensure correct vaccine queue handling during the next day’s events.
For any agent with `want_vaccine = True`, ‘healthcare_facility’ is added to their
priority place types to guide movement toward vaccination sites.
- param folks_here:
List of agents present at the same node (not used in this method, for interface compatibility).
- type folks_here:
list of FolkSEIQRDV
- param current_place_type:
Type of place where the agent is sleeping (not used in this method, for interface compatibility).
- type current_place_type:
str
- param status_dict_t:
Dictionary tracking the count of each status at the current timestep.
- type status_dict_t:
dict
- param model_params:
Model parameters for the simulation.
- type model_params:
SEIQRDVModelParameters
- param dice:
Random float for stochastic transitions.
- type dice:
float
- rtype:
None
Notes
The want_vaccine attribute is reset to False in sleep() rather than immediately after vaccination in interact() to maintain queue integrity. If reset during interact(), it would modify the vaccination queue while agents are still being processed, potentially causing some agents to be skipped or processed incorrectly. Deferring the reset ensures fair and consistent vaccination queue processing.
- class simcronomicon.compartmental_models.SEIQRDV_model.SEIQRDVModel(model_params, step_events=None)
Bases:
AbstractCompartmentalModel
SEIQRDV compartmental model implementation for epidemic simulation with vaccination.
The SEIQRDV model extends the classic SEIR model by adding three additional compartments: Quarantine (Q), Death (D), and Vaccination (V). This model is particularly suited for simulating disease outbreaks where quarantine measures, vaccination campaigns, and mortality are important factors.
- initialize_sim_population(town)
Initialize the simulation population and their assignments.
This method assigns initial statuses and home locations to all agents in the simulation, including initial spreaders (both randomly assigned and those at specified nodes) and susceptible agents. It also creates agent objects, updates the town graph with agent assignments, and tracks household nodes.
- Parameters:
town (Town) – The Town object representing the simulation environment.
- Returns:
(folks, household_node_indices, status_dict_t0)
- folkslist of FolkSEIQRDV
List of all agent objects created for the simulation.
- household_node_indicesset
Set of node indices where households are tracked.
- status_dict_t0dict
Dictionary with the initial count of each status at timestep 0.
- Return type:
tuple
- update_population(folks, town, household_node_indices, status_dict_t)
Update the simulation population at the end of each day.
This function performs two main operations: 1. Natural Deaths: Iterates through all currently alive agents and, with probability mu (the natural death rate), transitions them to the ‘D’ (Dead) status and marks them as not alive.
- Population Growth: Calculates the number of possible new agents to add based on the current alive population and the parameter lam_cap (birth/migration rate). For each new agent:
Randomly selects an accommodation node as their home.
Randomly assigns a status from all possible statuses except ‘D’ (Dead) and ‘Q’ (Quarantine).
Adds the new agent to the simulation, updates the status count, and tracks their household node.
- Parameters:
folks (list of FolkSEIQRDV) – The current list of FolkSEIQRDV agent objects in the simulation.
town (Town) – The Town object representing the simulation environment.
household_node_indices (set) – Set of node indices where households are tracked.
status_dict_t (dict) – Dictionary tracking the count of each status at the current timestep.
- Returns:
The updated total number of agents in the simulation after deaths and births/migration.
- Return type:
int
- class simcronomicon.compartmental_models.SEIQRDV_model.SEIQRDVModelParameters(max_energy, lam_cap, beta, alpha, gamma, delta, lam, rho, kappa, mu, hospital_capacity=inf)
Bases:
AbstractModelParameters
Model parameters for the SEIQRDV compartmental model.
This class encapsulates all tunable parameters required for the SEIQRDV compartmental model, including epidemiological rates, probabilities, and healthcare system constraints. It validates parameter types and ranges upon initialization.
Ghostine, R., Gharamti, M., Hassrouny, S., & Hoteit, I. (2021). An extended SEIR model with vaccination for forecasting the COVID-19 pandemic in Saudi Arabia using an ensemble Kalman filter. Mathematics, 9(6), 636. https://doi.org/10.3390/math9060636
- to_metadata_dict()
Convert SEIQRDV model parameters to a dictionary for metadata serialization.
- Returns:
Dictionary containing all model parameters as key-value pairs.
- Return type:
dict
simcronomicon.compartmental_models.SEIR_model module
- class simcronomicon.compartmental_models.SEIR_model.FolkSEIR(id, home_address, max_energy, status)
Bases:
AbstractFolk
Agent class for the SEIR model.
This class represents individual agents in the SEIR compartmental model, handling transitions between Susceptible (S), Exposed (E), Infectious (I), and Recovered (R) states based on contact with infectious agents and time-based progression rules.
- interact(folks_here, current_place_type, status_dict_t, model_params, dice)
Perform interactions with other agents and handle potential disease transmission.
Transition Rules
If the agent is Susceptible (‘S’) and comes into contact with at least one Infectious (‘I’) agent, the probability of becoming Exposed (‘E’) is calculated using the inverse Bernoulli formula with transmission probability (beta). If this probability exceeds the random value dice, the agent transitions to Exposed.
- param folks_here:
List of agents present at the same node.
- type folks_here:
list of FolkSEIR
- param current_place_type:
Type of place where the interaction occurs.
- type current_place_type:
str
- param status_dict_t:
Dictionary tracking the count of each status at the current timestep.
- type status_dict_t:
dict
- param model_params:
Model parameters for the simulation.
- type model_params:
SEIRModelParameters
- param dice:
Random float for stochastic transitions.
- type dice:
float
- rtype:
None
- inverse_bernoulli(folks_here, conversion_prob, stats)
Calculate the probability of status transition given contact with infectious agents.
This method implements the inverse Bernoulli probability calculation used in agent-based modeling to approximate the continuous ODE dynamics of compartmental models. It calculates the probability of infection based on the number of infectious contacts and transmission probability.
- Parameters:
folks_here (list of FolkSEIR) – List of agents present at the same node.
conversion_prob (float) – Base transmission probability per contact.
stats (list of str) – List of infectious status types to consider.
- Returns:
Probability of at least one successful transmission event.
- Return type:
float
- sleep(folks_here, current_place_type, status_dict_t, model_params, dice)
Perform end-of-day status transitions based on disease progression.
This method handles the deterministic time-based transitions between compartmental states at the end of each simulation day.
Transition Rules
If the agent is Exposed (‘E’) and has been exposed for sigma days, they transition to Infectious (‘I’).
If the agent is Infectious (‘I’) and has been infectious for gamma days, they transition to Recovered (‘R’).
If the agent is Recovered (‘R’) and has been recovered for xi days, they transition back to Susceptible (‘S’) (waning immunity).
- param folks_here:
List of agents present at the same node (not used, for interface compatibility).
- type folks_here:
list of FolkSEIR
- param current_place_type:
Type of place where the agent is sleeping (not used, for interface compatibility).
- type current_place_type:
str
- param status_dict_t:
Dictionary tracking the count of each status at the current timestep.
- type status_dict_t:
dict
- param model_params:
Model parameters for the simulation.
- type model_params:
SEIRModelParameters
- param dice:
Random float for stochastic transitions (not used for deterministic transitions).
- type dice:
float
- rtype:
None
- class simcronomicon.compartmental_models.SEIR_model.SEIRModel(model_params, step_events=None)
Bases:
AbstractCompartmentalModel
SEIR compartmental model implementation.
This class implements the Susceptible-Exposed-Infectious-Recovered model for epidemic simulation. It includes waning immunity where recovered individuals return to susceptible status after a specified duration.
- initialize_sim_population(town)
Initialize the simulation population and their initial status assignments.
This method assigns initial statuses and home locations to all agents in the simulation, including initial spreaders (both randomly assigned and those at specified nodes) and susceptible agents. It creates agent objects, updates the town graph with agent assignments, and tracks household nodes.
- Parameters:
town (Town) – The Town object representing the simulation environment.
- Returns:
(folks, household_node_indices, status_dict_t0)
- folkslist of FolkSEIR
List of all agent objects created for the simulation.
- household_node_indicesset
Set of node indices where households are tracked.
- status_dict_t0dict
Dictionary with the initial count of each status at timestep 0.
- Return type:
tuple
- class simcronomicon.compartmental_models.SEIR_model.SEIRModelParameters(max_energy, beta, sigma, gamma, xi)
Bases:
AbstractModelParameters
Model parameters for the SEIR compartmental model.
This class encapsulates all tunable parameters required for the SEIR compartmental model, including transmission rates and duration parameters. It validates parameter types and ranges upon initialization.
- to_metadata_dict()
Convert SEIR model parameters to a dictionary for metadata serialization.
- Returns:
Dictionary containing all model parameters as key-value pairs.
- Return type:
dict
simcronomicon.compartmental_models.SEIsIrR_model module
This module implements rumor spreading dynamics with considerations for credibility, correlation, and crowd personality-based classification.
The implementation is based on:
Chen, X., & Wang, N. (2020). Rumor spreading model considering rumor credibility, correlation and crowd classification based on personality. Scientific Reports, 10, 5887. https://doi.org/10.1038/s41598-020-62585-9
- class simcronomicon.compartmental_models.SEIsIrR_model.FolkSEIsIrR(id, home_address, max_energy, status)
Bases:
AbstractFolk
Agent class for the SEIsIrR rumor spreading model.
This class represents individual agents in the SEIsIrR compartmental model, handling transitions between Susceptible (S), Exposed (E), Ignorant spreaders (Is), Intelligent spreaders (Ir), and Recovered/Stifler (R) states based on rumor credibility, literacy levels, and social interactions.
- interact(folks_here, current_place_type, status_dict_t, model_params, dice)
Perform interactions with other agents and handle rumor spreading dynamics.
Transition Rules
Rule 1: If the agent is Intelligent spreader (‘Ir’) and contacts Susceptible (‘S’) agents, they may transition to Susceptible (‘S’) based on Ir2S probability.
Rule 2: If the agent is Ignorant spreader (‘Is’) and contacts Susceptible (‘S’) agents, they may transition to either Exposed (‘E’) or Susceptible (‘S’) based on Is2E and Is2S probabilities respectively. The transition with higher probability is evaluated first.
Rule 3: If the agent is Exposed (‘E’), they may transition to either Susceptible (‘S’) or Recovered (‘R’) based on E2S and E2R probabilities respectively. The transition with higher probability is evaluated first.
Rule 4.1: If the agent is Susceptible (‘S’), they may transition to Recovered (‘R’) when contacting any other agents (‘S’, ‘E’, ‘R’) based on S2R probability.
- param folks_here:
List of agents present at the same node.
- type folks_here:
list of FolkSEIsIrR
- param current_place_type:
Type of place where the interaction occurs.
- type current_place_type:
str
- param status_dict_t:
Dictionary tracking the count of each status at the current timestep.
- type status_dict_t:
dict
- param model_params:
Model parameters for the simulation.
- type model_params:
SEIsIrRModelParameters
- param dice:
Random float for stochastic transitions.
- type dice:
float
- rtype:
None
- inverse_bernoulli(folks_here, conversion_prob, stats)
Calculate the probability of status transition given contact with specific statuses.
This method implements an energy-weighted inverse Bernoulli probability calculation for rumor spreading dynamics. The probability is scaled by the agent’s current energy relative to their maximum energy, representing decreased social influence when tired.
- Parameters:
folks_here (list of FolkSEIsIrR) – List of agents present at the same node.
conversion_prob (float) – Base transition probability per contact.
stats (list of str) – List of status types to consider for contact counting.
- Returns:
Probability of at least one successful transition event.
- Return type:
float
- sleep(folks_here, current_place_type, status_dict_t, model_params, dice)
Perform end-of-day status transitions and forgetting mechanisms.
This method handles the forgetting mechanism for Susceptible agents, representing the natural tendency to lose interest in rumors over time.
Transition Rules
Rule 4.2: If the agent is Susceptible (‘S’), they may transition to Recovered (‘R’) through forgetting if either: - They have been in ‘S’ status for longer than mem_span days, OR - A random draw is less than the forgetting probability forget
- param folks_here:
List of agents present at the same node (not used, for interface compatibility).
- type folks_here:
list of FolkSEIsIrR
- param current_place_type:
Type of place where the agent is sleeping (not used, for interface compatibility).
- type current_place_type:
str
- param status_dict_t:
Dictionary tracking the count of each status at the current timestep.
- type status_dict_t:
dict
- param model_params:
Model parameters for the simulation.
- type model_params:
SEIsIrRModelParameters
- param dice:
Random float for stochastic transitions.
- type dice:
float
- rtype:
None
- class simcronomicon.compartmental_models.SEIsIrR_model.SEIsIrRModel(model_params, step_events=None)
Bases:
AbstractCompartmentalModel
SEIsIrR rumor spreading model implementation.
This class implements the Susceptible-Exposed-Ignorant spreader-Intelligent spreader-Recovered model for rumor spreading dynamics. The model considers rumor credibility, population literacy, and personality-based classification of spreaders.
- initialize_sim_population(town)
Initialize the simulation population and their initial status assignments.
This method assigns initial statuses and home locations to all agents in the simulation. The population is divided between Ignorant spreaders (Is) and Intelligent spreaders (Ir) based on the literacy parameter, with initial rumor spreaders assigned to ‘S’ status.
- Parameters:
town (Town) – The Town object representing the simulation environment.
- Returns:
(folks, household_node_indices, status_dict_t0
- folkslist of FolkSEIsIrR
List of all agent objects created for the simulation.
- household_node_indicesset
Set of node indices where households are tracked.
- status_dict_t0dict
Dictionary with the initial count of each status at timestep 0.
- Return type:
tuple
- class simcronomicon.compartmental_models.SEIsIrR_model.SEIsIrRModelParameters(max_energy, literacy, gamma, alpha, lam, phi, theta, mu, eta1, eta2, mem_span=10)
Bases:
AbstractModelParameters
Model parameters for the SEIsIrR rumor spreading model.
This class encapsulates all tunable parameters required for the SEIsIrR rumor spreading model, including rumor credibility, spreading probabilities, and population literacy characteristics. It validates parameter types and ranges upon initialization.
- to_metadata_dict()
Convert SEIsIrR model parameters to a dictionary for metadata serialization.
- Returns:
Dictionary containing all model parameters as key-value pairs.
- Return type:
dict
Define Your Own Model
You can create your own compartmental model by subclassing AbstractCompartmentalModel and following the structure of the provided models.
Note
Add your new model module here for documentation!