simcronomicon package

Town network

class simcronomicon.town.Town

Bases: object

Spatial network representation for agent-based epidemic modeling.

The Town class represents a spatial network derived from OpenStreetMap data, where nodes correspond to places of interest (POIs) and edges represent walkable paths between locations. This network serves as the environment where agents move, interact, and undergo state transitions during simulation.

Purpose

  1. Spatial Network Creation: Build a graph representation of urban areas from OpenStreetMap data, including roads, buildings, and points of interest.

  2. Place Classification: Categorize locations into functional types (accommodation, workplace, healthcare, etc.) that influence agent behavior.

  3. Agent Housing: Provide accommodation nodes where agents reside and return to after each simulation timestep.

  4. Distance Calculation: Maintain shortest-path distances between all locations to enable realistic agent movement patterns.

  5. Data Persistence: Save and load town networks to/from compressed files for reuse across multiple simulations.

Network Structure

  • Nodes: Represent places of interest with attributes including:

    • place_type: Functional category of the location

    • x, y: Projected coordinates in the town’s coordinate system

    • folks: List of agents currently at this location

  • Edges: Represent walkable connections with attributes:

    • weight: Shortest-path distance in meters between connected nodes

Place Types

The default classification system recognizes: - accommodation: Residential buildings where agents live

  • healthcare_facility: Hospitals, clinics, pharmacies

  • commercial: Shops, restaurants, banks

  • workplace: Offices, factories, industrial areas

  • education: Schools, universities

  • religious: Churches, mosques, temples

  • other: Unclassified locations (filtered out by default)

town_graph

The spatial network with nodes representing locations and edges representing shortest paths between them.

Type:

networkx.Graph

town_params

Configuration parameters including population size and initial spreader locations.

Type:

TownParameters

epsg_code

EPSG coordinate reference system code for spatial projections.

Type:

int

point

Origin point [latitude, longitude] used to center the network.

Type:

tuple

dist

Radius in meters defining the network extent from the origin point.

Type:

float

all_place_types

Complete list of possible place type categories.

Type:

list

found_place_types

Place types actually present in this town network.

Type:

set

accommodation_node_ids

Node IDs of all accommodation locations where agents can reside.

Type:

list

Examples

>>> # Create town from geographic coordinates (Aachen, Germany)
>>> town_params = TownParameters(num_pop=1000, num_init_spreader=10)
>>> town = Town.from_point(
...     point=[50.7753, 6.0839],  # Aachen Dom coordinates
...     dist=1000,  # 1km radius
...     town_params=town_params
... )
>>>
>>> # Load previously saved town
>>> town = Town.from_files(
...     config_path="town_config.json",
...     town_graph_path="town_graph.graphmlz",
...     town_params=town_params
... )
>>>
>>> # Examine town properties
>>> print(f"Town has {len(town.town_graph.nodes)} locations")
>>> print(f"Place types found: {town.found_place_types}")
>>> print(f"Accommodation nodes: {len(town.accommodation_node_ids)}")

Notes

  • The town network uses shortest-path distances calculated from road network edges rather than Euclidean distances to provide realistic travel times between locations. These distances are computed by finding the shortest route along actual roads and pathways connecting places.

  • All shortest paths between every pair of places are pre-calculated during town creation, and the resulting simplified graph stores these distances as direct edge weights. This optimization dramatically reduces computational overhead during simulation steps, as agent movement only requires looking up neighboring edge weights rather than performing path searches.

  • This pre-computation approach is especially beneficial when running multiple simulations in the same location or simulations with many agents and timesteps, as the expensive shortest-path calculations are done once during town creation.

  • Building centroids are mapped to nearest road network nodes to ensure all locations are accessible via the street network.

  • Custom place classification functions can be provided to adapt the categorization system to specific research needs.

  • Town networks are automatically saved in compressed GraphMLZ format along with JSON config_data for efficient storage and reuse. These output files serve as input files for the Simulation class, enabling rapid simulation setup without re-downloading or re-processing OpenStreetMap data.

raises ValueError:

If the specified point coordinates are invalid, if no relevant locations remain after filtering, or if initial spreader nodes don’t exist in the network.

raises TypeError:

If the place classification function is not callable or if required parameters are missing when using custom classification.

classmethod from_files(config_path, town_graph_path, town_params)

Load a previously saved town network from compressed files.

Reconstructs a Town object from GraphMLZ and JSON configuration files created by a previous call to from_point(). This method enables rapid simulation setup without re-downloading or re-processing OpenStreetMap data.

Parameters:
  • config_path (str) – Path to the JSON configuration file containing town configuration and place type information.

  • town_graph_path (str) – Path to the compressed GraphMLZ file containing the spatial network.

  • town_params (TownParameters) – Configuration object containing population size, initial spreader count, and spreader node locations for the simulation.

Returns:

Town object with loaded spatial network and config_data.

Return type:

Town

Raises:
  • ValueError – If spreader nodes specified in town_params don’t exist in the loaded network.

  • FileNotFoundError – If the specified files don’t exist.

Examples

>>> town_params = TownParameters(num_pop=1000, num_init_spreader=5)
>>> town = Town.from_files(
...     config_path="./data/aachen_dom_config.json",
...     town_graph_path="./data/aachen_dom.graphmlz",
...     town_params=town_params
... )
classmethod from_point(point, dist, town_params, classify_place_func=<function classify_place>, all_place_types=None, file_prefix='town_graph', save_dir='.')

Create a town network from OpenStreetMap data centered on a geographic point.

Downloads road network and building data from OpenStreetMap, processes building geometries, classifies places by type, and constructs a simplified graph with pre-computed shortest-path distances between all locations.

Parameters:
  • point (list or tuple) – Geographic coordinates [latitude, longitude] defining the center point for data extraction.

  • dist (float) – Radius in meters around the point to extract data. Defines the spatial extent of the town network.

  • town_params (TownParameters) – Configuration object containing population size, initial spreader count, and spreader node locations.

  • classify_place_func (callable, optional) – Function to classify building types into place categories. Must accept a pandas row and return a place type string (default: classify_place).

  • all_place_types (list, optional) – List of all possible place type categories. Required when using custom classify_place_func (default: None).

  • file_prefix (str, optional) – Prefix for output files (default: “town_graph”).

  • save_dir (str, optional) – Directory to save compressed graph and configuration files (default: “.”).

Returns:

Town object with populated spatial network and config_data.

Return type:

Town

Raises:
  • ValueError – If point coordinates are invalid, no relevant nodes remain after filtering, or spreader nodes don’t exist in the network.

  • TypeError – If classify_place_func is not callable or required parameters are missing.

Examples

>>> town_params = TownParameters(num_pop=1000, num_init_spreader=5)
>>> town = Town.from_point(
...     point=[50.7753, 6.0839],  # Aachen Dom
...     dist=1000,
...     town_params=town_params,
...     file_prefix="aachen_dom",
...     save_dir="./data"
... )
save_to_files(file_prefix, overwrite=False)

Save this Town object to GraphML and config files.

Parameters:
  • file_prefix (str) – Prefix for the output files (will create {prefix}.graphmlz and {prefix}_config.json)

  • overwrite (bool, default False) – Whether to overwrite existing files

Returns:

(graphml_path, config_path) - paths to the created files

Return type:

tuple[str, str]

class simcronomicon.town.TownParameters(num_pop, num_init_spreader, spreader_initial_nodes=[])

Bases: object

Parameters for town network initialization and agent placement.

Validates and stores population size, initial spreader count, and optional spreader node locations for the simulation set up.

Parameters:
  • num_pop (int) – Total population size for the simulation. Must be a positive integer (> 0). Determines the number of agents that will be created and distributed across accommodation nodes in the town network.

  • num_init_spreader (int) – Number of initial disease spreaders at simulation start. Must be a positive integer (> 0) and cannot exceed num_pop. These agents begin the simulation in an infected state to seed the epidemic spread.

  • spreader_initial_nodes (list of int, optional) –

    Specific node IDs where initial spreaders should be placed. This list can be:

    • Empty (default): All spreaders will be randomly assigned to accommodation nodes

    • Partial: Contains fewer nodes than num_init_spreader; remaining spreaders will be randomly assigned to accommodation nodes

    • Complete: Contains exactly num_init_spreader nodes for full control

    • With duplicates: Same node ID can appear multiple times to place multiple spreaders at the same location

    Node IDs must be integers or convertible to integers. The list length must not exceed num_init_spreader (len(spreader_initial_nodes) ≤ num_init_spreader).

num_pop

Validated total population size.

Type:

int

num_init_spreader

Validated number of initial spreaders.

Type:

int

spreader_initial_nodes

Validated list of spreader node locations.

Type:

list

Raises:
  • TypeError – If parameters are not of expected types or nodes not convertible to int.

  • ValueError – If values are non-positive, spreaders exceed population, or too many node locations specified.

Examples

>>> # Basic configuration
>>> params = TownParameters(num_pop=1000, num_init_spreader=10)
>>> # With specific spreader locations
>>> params = TownParameters(
...     num_pop=1000,
...     num_init_spreader=3,
...     spreader_initial_nodes=[5, 12, 47]
... )
>>> # Partial specification with duplicates
>>> params = TownParameters(
...     num_pop=1000,
...     num_init_spreader=5,
...     spreader_initial_nodes=[10, 10, 25]  # 3 of 5 spreaders specified
... )
simcronomicon.town.classify_place(row)

Compartmental models

Simulation structure

class simcronomicon.sim.Simulation(town, compartmental_model, timesteps, seed=True, seed_value=5710)

Bases: object

Agent-based simulation engine for epidemic modeling in spatial networks.

The Simulation class implements an agent-based modeling (ABM) framework that applies transition rules according to user-defined compartmental models. Agents move through a spatial town network, interact with each other and their environment, and undergo state transitions based on the rules defined in the chosen compartmental model.

Purpose

  1. Initialize Population: Distribute agents across the town network according to user-specified parameters, including initial spreader locations and population size.

  2. Agent Movement: Move agents through the city during simulation timesteps based on step events that define mobility patterns and destination preferences.

  3. Agent Interactions: Enable agent-to-agent and agent-to-environment interactions at each location according to the rules defined in the compartmental model.

  4. State Transitions: Apply compartmental model transition rules (e.g., S→E→I→R) based on agent interactions, environmental factors, and time-dependent processes.

  5. Temporal Dynamics: Execute simulation in discrete timesteps, where each step consists of multiple events, and agents return home after each complete step.

Simulation Workflow

Each simulation timestep follows this pattern:

  1. Event Execution: For each step event in the current timestep: - Reset agent locations (clear previous positions) - Execute event-specific movement (DISPERSE) or actions (SEND_HOME) - Apply compartmental model rules for agent interactions - Record population status and individual agent states

  2. Agent Movement: During DISPERSE events: - Agents move to locations within their travel distance - Movement considers place type preferences and priority destinations - Probability functions can influence destination selection

  3. Interactions: At each active location: - Agents interact according to compartmental model rules - Environmental factors (place type) influence interaction outcomes - State transitions occur based on model-specific probabilities

  4. Home Reset: After all events, agents return to their home addresses

param town:

The Town object representing the spatial network with nodes (locations) and edges (travel routes) where the simulation takes place.

type town:

Town

param compartmental_model:

The compartmental model instance (e.g., SEIRModel, SEIQRDVModel) that defines agent states, transition rules, and interaction behaviors.

type compartmental_model:

AbstractCompartmentalModel

param timesteps:

Number of discrete timesteps to run the simulation.

type timesteps:

int

param seed:

Whether to set random seeds for reproducible results (default: True).

type seed:

bool, optional

param seed_value:

Random seed value for reproducibility (default: 5710).

type seed_value:

int, optional

folks

List of AbstractFolk (agent) objects representing the population.

Type:

list

town

The spatial network where agents live and move.

Type:

Town

model

The compartmental model governing agent behavior and transitions.

Type:

AbstractCompartmentalModel

step_events

Sequence of events that occur in each timestep.

Type:

list

active_node_indices

Set of town nodes currently occupied by agents.

Type:

set

status_dicts

Historical record of population status counts at each timestep.

Type:

list

raises ValueError:

If required place types for the chosen compartmental model are missing in the town data. This ensures model-specific locations (e.g., healthcare facilities for medical models) are available in the spatial network.

Examples

>>> # Create town and model
>>> town = Town.from_point(point=[50.7753, 6.0839], dist=1000,
...                        town_params=TownParameters(num_pop=1000, num_init_spreader=10))
>>> model_params = SEIRModelParameters(max_energy=10, beta=0.3, sigma=5, gamma=7, xi=100)
>>> model = SEIRModel(model_params)
>>>
>>> # Run simulation
>>> sim = Simulation(town, model, timesteps=100)
>>> sim.run(hdf5_path="epidemic_simulation.h5")

Notes

  • The simulation saves detailed results to HDF5 format, including population summaries and individual agent trajectories.

  • Agent energy levels affect movement capability and interaction potential.

  • Movement restrictions (e.g., quarantine) can limit agent mobility while still allowing interactions with visiting agents.

  • The simulation automatically terminates early if no infected agents remain.

run(hdf5_path='simulation_output.h5', silent=False)

Run the simulation for the specified number of timesteps.

The simulation results are saved to an HDF5 file with the following structure:

simulation_output.h5
├── metadata
│   ├── simulation_metadata   (JSON-encoded simulation metadata)
│   └── town_metadata         (JSON-encoded town metadata)
├── status_summary
│   └── summary               (dataset: structured array with timestep, current_event, and statuses)
└── individual_logs
    └── log                   (dataset: structured array with timestep, event, folk_id, status, address)
Parameters:

hdf5_path (str) – Path to the output HDF5 file.

Return type:

None

Visualization