epydemix package
Subpackages
- epydemix.calibration package
- Submodules
- epydemix.calibration.abc module
- epydemix.calibration.calibration_results module
CalibrationResultsCalibrationResults.calibration_strategyCalibrationResults.posterior_distributionsCalibrationResults.selected_trajectoriesCalibrationResults.observed_dataCalibrationResults.priorsCalibrationResults.calibration_paramsCalibrationResults.distancesCalibrationResults.weightsCalibrationResults.projectionsCalibrationResults.projection_parametersCalibrationResults.calibration_paramsCalibrationResults.calibration_strategyCalibrationResults.distancesCalibrationResults.get_calibration_quantiles()CalibrationResults.get_calibration_trajectories()CalibrationResults.get_distances()CalibrationResults.get_posterior_distribution()CalibrationResults.get_projection_quantiles()CalibrationResults.get_projection_trajectories()CalibrationResults.get_selected_trajectories()CalibrationResults.get_weights()CalibrationResults.observed_dataCalibrationResults.posterior_distributionsCalibrationResults.priorsCalibrationResults.projection_parametersCalibrationResults.projectionsCalibrationResults.selected_trajectoriesCalibrationResults.weights
- epydemix.calibration.metrics module
- Module contents
ABCSamplerCalibrationResultsCalibrationResults.calibration_strategyCalibrationResults.posterior_distributionsCalibrationResults.selected_trajectoriesCalibrationResults.observed_dataCalibrationResults.priorsCalibrationResults.calibration_paramsCalibrationResults.distancesCalibrationResults.weightsCalibrationResults.projectionsCalibrationResults.projection_parametersCalibrationResults.calibration_paramsCalibrationResults.calibration_strategyCalibrationResults.distancesCalibrationResults.get_calibration_quantiles()CalibrationResults.get_calibration_trajectories()CalibrationResults.get_distances()CalibrationResults.get_posterior_distribution()CalibrationResults.get_projection_quantiles()CalibrationResults.get_projection_trajectories()CalibrationResults.get_selected_trajectories()CalibrationResults.get_weights()CalibrationResults.observed_dataCalibrationResults.posterior_distributionsCalibrationResults.priorsCalibrationResults.projection_parametersCalibrationResults.projectionsCalibrationResults.selected_trajectoriesCalibrationResults.weights
ae()mae()mape()rmse()wmape()
- epydemix.model package
- Submodules
- epydemix.model.epimodel module
EpiModelEpiModel.add_compartments()EpiModel.add_intervention()EpiModel.add_parameter()EpiModel.add_transition()EpiModel.apply_intervention()EpiModel.clear_compartments()EpiModel.clear_interventions()EpiModel.clear_overrides()EpiModel.clear_parameters()EpiModel.clear_transitions()EpiModel.compute_contact_reductions()EpiModel.create_default_initial_conditions()EpiModel.delete_override()EpiModel.delete_parameter()EpiModel.get_parameter()EpiModel.import_epydemix_population()EpiModel.n_compartmentsEpiModel.n_transitionsEpiModel.override_parameter()EpiModel.register_transition_kind()EpiModel.run_simulations()EpiModel.set_population()
compute_mediated_transition_rate()compute_spontaneous_transition_rate()simulate()stochastic_simulation()validate_transition_function()
- epydemix.model.predefined_models module
- epydemix.model.simulation_output module
TrajectoryTrajectory.compartmentsTrajectory.transitionsTrajectory.datesTrajectory.compartment_idxTrajectory.transitions_idxTrajectory.parametersTrajectory.compartment_idxTrajectory.compartmentsTrajectory.datesTrajectory.parametersTrajectory.resample()Trajectory.transitionsTrajectory.transitions_idx
- epydemix.model.simulation_results module
SimulationResultsSimulationResults.trajectoriesSimulationResults.parametersSimulationResults.NsimSimulationResults.compartment_idxSimulationResults.datesSimulationResults.get_quantiles()SimulationResults.get_quantiles_compartments()SimulationResults.get_quantiles_transitions()SimulationResults.get_stacked_compartments()SimulationResults.get_stacked_transitions()SimulationResults.parametersSimulationResults.resample()SimulationResults.trajectories
- epydemix.model.transition module
- Module contents
EpiModelEpiModel.add_compartments()EpiModel.add_intervention()EpiModel.add_parameter()EpiModel.add_transition()EpiModel.apply_intervention()EpiModel.clear_compartments()EpiModel.clear_interventions()EpiModel.clear_overrides()EpiModel.clear_parameters()EpiModel.clear_transitions()EpiModel.compute_contact_reductions()EpiModel.create_default_initial_conditions()EpiModel.delete_override()EpiModel.delete_parameter()EpiModel.get_parameter()EpiModel.import_epydemix_population()EpiModel.n_compartmentsEpiModel.n_transitionsEpiModel.override_parameter()EpiModel.register_transition_kind()EpiModel.run_simulations()EpiModel.set_population()
SimulationResultsSimulationResults.trajectoriesSimulationResults.parametersSimulationResults.NsimSimulationResults.compartment_idxSimulationResults.datesSimulationResults.get_quantiles()SimulationResults.get_quantiles_compartments()SimulationResults.get_quantiles_transitions()SimulationResults.get_stacked_compartments()SimulationResults.get_stacked_transitions()SimulationResults.parametersSimulationResults.resample()SimulationResults.trajectories
Transitionload_predefined_model()simulate()
- epydemix.population package
- Submodules
- epydemix.population.population module
- Module contents
- epydemix.utils package
- Submodules
- epydemix.utils.abc_smc_utils module
- epydemix.utils.utils module
apply_initial_conditions()apply_overrides()combine_simulation_outputs()compute_days()compute_simulation_dates()convert_to_2Darray()create_definitions()evaluate()format_simulation_output()generate_unique_string()get_initial_conditions_dict()is_iterable()is_scalar()multinomial()njit()resize_parameter()str_to_date()validate_parameter_shape()
- Module contents
- epydemix.visualization package
Module contents
- class epydemix.EpiModel(name: str = 'EpiModel', compartments: List | None = None, parameters: Dict | None = None, population_name: str = 'epydemix_population', population_data_path: str | None = None, contact_layers: List | None = None, contacts_source: str | None = None, age_group_mapping: Dict | None = None, supported_contacts_sources: Dict | None = None, use_default_population: bool = True, default_population_size: int = 100000, data_version: str = 'v1.2.0', attribute: str = 'age')[source]
Bases:
objectEpiModel: A compartmental epidemic model simulator
Example
>>> model = EpiModel(compartments=["S", "I", "R"], parameters={"beta": 0.3, "gamma": 0.1}) >>> model.add_transition(source="S", target="I", params=("beta", "I")) >>> model.add_transition(source="I", target="R", params="gamma") >>> results = model.run_simulations( ... start_date="2020-01-01", ... end_date="2020-12-31", ... Nsim=100 ... )
- add_compartments(compartments: List | object) None[source]
Adds compartments to the epidemic model.
- Parameters:
compartments (list or object) – A list of compartments or a single compartment to be added.
- Returns:
None
- add_intervention(layer_name: str, start_date: str | Timestamp, end_date: str | Timestamp, reduction_factor: float | None = None, new_matrix: ndarray | None = None, name: str = '') None[source]
Adds an intervention to the epidemic model.
- Parameters:
layer_name (str) – The name of the layer to which the intervention applies.
start_date (str or datetime) – The start date of the intervention.
end_date (str or datetime) – The end date of the intervention.
reduction_factor (float, optional) – The factor by which to reduce the contact matrix. Default is None.
new_matrix (np.ndarray, optional) – A new contact matrix to use during the intervention. Default is None.
name (str, optional) – The name of the intervention. Default is an empty string.
- Raises:
ValueError – If neither reduction_factor nor new_matrix is provided.
- Returns:
None
- add_parameter(parameter_name: str | None = None, value: Any = None, parameters_dict: Dict | None = None) None[source]
Adds new parameters to the model.
- Parameters:
parameter_name (str, optional) – The name of the parameter to add. Ignored if parameters_dict is provided.
value (any, optional) – The value of the parameter to add. Ignored if parameters_dict is provided.
parameters_dict (dict, optional) – A dictionary of parameter names and values. If provided, parameter_name and value are ignored and the parameters are updated using this dictionary.
- Raises:
ValueError – If neither parameter_name/value nor parameters_dict is provided.
- Returns:
None
- add_transition(source: str, target: str, kind: str, params: Any) None[source]
Adds a transition to the epidemic model.
- Parameters:
source (str) – The source compartment of the transition.
target (str) – The target compartment of the transition.
kind (str) – The kind of transition (e.g., spontaneous or mediated).
params (Any) – The parameters involved in the transition.
- Raises:
ValueError – If the source or target is not in the compartments list.
- Returns:
None
- apply_intervention(intervention: Dict, simulation_dates: List[Timestamp]) None[source]
Applies an intervention to the contact matrices for specified simulation dates.
- Parameters:
intervention (dict) – A dictionary containing intervention details with the following keys: - “layer” (str): The name of the layer to which the intervention applies. - “start_date” (pd.Timestamp): The start date of the intervention. - “end_date” (pd.Timestamp): The end date of the intervention. - “reduction_factor” (float, optional): The factor by which to reduce the contact matrix. - “new_matrix” (np.ndarray, optional): A new contact matrix to use during the intervention.
simulation_dates (list of pd.Timestamp) – A list of dates for which the simulation is run.
- Raises:
ValueError – If neither reduction_factor nor new_matrix is provided in the intervention.
- Returns:
None
- clear_compartments() None[source]
This method resets the compartments list and clears the compartments_idx dictionary.
- Returns:
None
- clear_interventions() None[source]
Clears all interventions from the model.
This method resets the interventions list, removing all existing interventions.
- Returns:
None
- clear_parameters() None[source]
Clears all parameters from the model’s parameters dictionary.
- Returns:
None
- clear_transitions() None[source]
Clears all transitions from the model.
This method resets the transitions_list and reinitializes the transitions dictionary, clearing all existing transitions while keeping the structure intact for each compartment.
- Returns:
None
- compute_contact_reductions(simulation_dates: List[Timestamp]) None[source]
Computes the contact reductions for a population over the given simulation dates.
This function applies interventions to the contact matrices and computes the overall contact matrix for each date in the simulation period.
- Parameters:
simulation_dates (list of pd.Timestamp) – A list of dates over which the simulation is run.
- Returns:
- The function updates the instance variable self.Cs with the contact matrices for each date,
including the overall contact matrix after applying interventions.
- Return type:
None
- create_default_initial_conditions(percentage_in_agents: float = 0.0005) Dict[str, ndarray][source]
Creates default initial conditions for the epidemic model. If initial conditions are not provided, assigns a percentage of the population to agent compartments and the rest to source compartments, considering different age groups.
- Parameters:
percentage_in_agents (float) – Percentage of population to place in agent compartments. Defaults to 0.05%.
initial_conditions (dict, optional) – A dictionary specifying initial conditions. If None, this function creates default conditions.
- Returns:
A dictionary with initial conditions for each compartment, with values as arrays representing different age groups.
- Return type:
dict
- delete_override(parameter_name: str) None[source]
Deletes overrides for a specific parameter.
- Parameters:
parameter_name (str) – The name of the parameter whose overrides are to be deleted.
- Returns:
None
- delete_parameter(parameter_name: str) Any[source]
Deletes a parameter from the dictionary of the model’s parameters.
- Parameters:
parameter_name (str) – The name of the parameter to delete.
- Returns:
The value of the deleted parameter.
- Return type:
any
- Raises:
KeyError – If the parameter with the given name is not found.
- get_parameter(parameter_name: str) Any[source]
Retrieves the value of a specified parameter.
- Parameters:
parameter_name (str) – The name of the parameter to retrieve.
- Returns:
The value of the specified parameter.
- Return type:
any
- Raises:
KeyError – If the parameter with the given name is not found.
- import_epydemix_population(population_name: str, population_data_path: str | None = None, contact_layers: List | None = None, contacts_source: str | None = None, age_group_mapping: Dict | None = None, supported_contacts_sources: Dict | None = None, data_version: str = 'v1.2.0', attribute: str = 'age') None[source]
Sets or updates the population for the model.
- Parameters:
population_name (str) – The name of the population to set.
population_data_path (str or None, optional) – The path to the population data file. If None, data may be fetched online.
contact_layers (list or None, optional) – A list of contact layers to load for the population. Defaults to [“school”, “work”, “home”, “community”] if None.
contacts_source (str or None, optional) – The source of contact data. If None, the function will attempt to determine the source automatically.
age_group_mapping (dict or None, optional) – A mapping for age groups. If None, a default mapping is used.
supported_contacts_sources (list or None, optional) – A list of supported contact data sources (e.g., “prem_2017”, “prem_2021”). Defaults to [“prem_2017”, “prem_2021”, “mistry_2021”, “litvinova_2025”] for age, [“litvinova_2025”] for sex and race_ethnicity if None.
data_version (str, optional) – The git tag/version of the epydemix-data repository. Defaults to “v1.2.0”.
attribute (str, optional) – The demographic attribute layer. Defaults to “age”.
- Returns:
None
- property n_compartments: int
Get total number of compartments.
- property n_transitions: int
Get total number of transitions.
- override_parameter(start_date: str, end_date: str, parameter_name: str, value: Any) None[source]
Adds an override for a parameter with the specified name.
- Parameters:
start_date (str) – The start date for the override period.
end_date (str) – The end date for the override period.
parameter_name (str) – The name of the parameter to override.
value (any) – The value to override the parameter with.
- Returns:
None
- register_transition_kind(kind: str, function: Callable)[source]
Registers a new transition kind providing a function to compute the rate of the transition.
- Parameters:
kind (str) – The kind of transition (e.g., spontaneous or mediated).
function (Callable) – The function to register.
- Returns:
None
- run_simulations(start_date: str | Timestamp = '2020-01-01', end_date: str | Timestamp = '2020-12-31', initial_conditions_dict: Dict[str, ndarray] | None = None, Nsim: int = 100, percentage_in_agents: float = 0.0005, dt: float | None = 1.0, resample_frequency: str | None = 'D', resample_aggregation_compartments: str | dict | None = 'last', resample_aggregation_transitions: str | dict | None = 'sum', fill_method: str | None = 'ffill', apply_linear_approximation: bool = False, rng: Generator | None = None) SimulationResults[source]
Simulates the epidemic model multiple times over the given time period.
- Parameters:
start_date (str or pd.Timestamp) – The start date of the simulation. Default is “2020-01-01”.
end_date (str or pd.Timestamp) – The end date of the simulation. Default is “2020-12-31”.
initial_conditions_dict (dict, optional) – A dictionary of initial conditions for the simulation.
Nsim (int, optional) – The number of simulation runs to perform (default is 100).
percentage_in_agents (float, optional) – The percentage of the population to initialize in the agents compartment.
dt (float, optional) – The time step for the simulation, expressed in days. Default is 1 (day).
resample_frequency (str, optional) – The frequency at which to resample the simulation results. Default is “D” (daily).
resample_aggregation_compartments (str, optional) – The aggregation method to use when resampling the compartments. Default is “last”.
resample_aggregation_transitions (str, optional) – The aggregation method to use when resampling the transitions. Default is “sum”.
fill_method (str, optional) – Method to fill NaN values after resampling. Default is “ffill”.
apply_linear_approximation (bool, optional) – Whether to use linear approximation to the probabilities. Default is False.
rng (np.random.Generator, optional) – Random number generator. Default is None.
- Returns:
An object containing all simulation trajectories.
- Return type:
- Raises:
RuntimeError – If the simulation fails.
- set_population(population: Population) None[source]
Sets the population for the epidemic model.
- Parameters:
population (Population) – The population object to set.
- Returns:
None
- epydemix.load_predefined_model(model_name: str, transmission_rate: float = 0.3, recovery_rate: float = 0.1, incubation_rate: float = 0.2, asymptomatic_fraction: float = 0.4, asymptomatic_recovery_rate: float = 0.14, asymptomatic_relative_infectivity: float = 0.5, waning_immunity: bool = False, waning_rate: float = 0.0027397260273972603, vaccination: bool = False, vaccination_rate: float = 0.01, vaccine_efficacy: float = 0.9, outcome: str = None, mortality_rate: float = 0.01, hospitalization_rate: float = 0.01, hospitalization_recovery_rate: float = 0.1) EpiModel[source]
Load a predefined epidemic model with optional modular extensions.
- Parameters:
model_name (str) – Backbone model. One of “SIR”, “SEIR”, “SIS”, “SEIAR”.
transmission_rate (float) – Rate of transmission. Default 0.3.
recovery_rate (float) – Rate of recovery from Infected. Default 0.1.
incubation_rate (float) – Rate of progression from Exposed to Infected (SEIR, SEIAR). Default 0.2.
asymptomatic_fraction (float) – Fraction of exposed who become asymptomatic (SEIAR only). Default 0.4.
asymptomatic_recovery_rate (float) – Recovery rate for asymptomatic individuals (SEIAR only). Default 0.14.
asymptomatic_relative_infectivity (float) – Infectivity of asymptomatics relative to symptomatics (SEIAR only). Default 0.5.
waning_immunity (bool) – Add waning immunity (R → S). Not compatible with SIS. Default False.
waning_rate (float) – Rate of immunity waning. Default 1/365 (~1 year). Interpreted as the inverse of the average immunity duration in days.
vaccination (bool) – Add vaccination compartment (S → Vaccinated → Infected at reduced rate). Default False.
vaccination_rate (float) – Rate of vaccination from Susceptible. Default 0.01.
vaccine_efficacy (float) – Fraction by which vaccine reduces transmission. Default 0.9.
outcome (str or None) – Track a disease outcome. One of None, “deaths”, “hospitalization”. Default None.
mortality_rate (float) – Rate of death from Infected. Used when outcome=”deaths”. Default 0.01.
hospitalization_rate (float) – Rate of hospitalization from Infected. Used when outcome=”hospitalization”. Default 0.01.
hospitalization_recovery_rate (float) – Rate of recovery from Hospitalized. Used when outcome=”hospitalization”. Default 0.1.
All rate parameters accept scalars, 1D arrays of shape (T,) for time-varying values, or 2D arrays of shape (T, G) for age-stratified values, consistent with the rest of the epydemix parameter system.
- Returns:
Configured epidemic model.
- Return type:
- Raises:
ValueError – If model_name is not recognised, or a module is incompatible with the chosen backbone.
Examples
SIRS: load_predefined_model(“SIR”, waning_immunity=True) SEIRS: load_predefined_model(“SEIR”, waning_immunity=True) SEIR-V: load_predefined_model(“SEIR”, vaccination=True) SIRD: load_predefined_model(“SIR”, outcome=”deaths”) SEIRD: load_predefined_model(“SEIR”, outcome=”deaths”) SEIRH: load_predefined_model(“SEIR”, outcome=”hospitalization”)
- epydemix.simulate(epimodel, start_date: str | Timestamp = '2020-01-01', end_date: str | Timestamp = '2020-12-31', initial_conditions_dict: Dict[str, ndarray] | None = None, percentage_in_agents: float = 0.0005, dt: float | None = 1.0, resample_frequency: str | None = 'D', resample_aggregation_compartments: str | dict | None = 'last', resample_aggregation_transitions: str | dict | None = 'sum', fill_method: str | None = 'ffill', apply_linear_approximation: bool = False, rng: Generator | None = None, contact_matrices: List[Dict[str, ndarray]] | None = None, simulation_dates: List[Timestamp] | None = None, **kwargs) Trajectory[source]
Runs a simulation of the epidemic model over the specified simulation dates.
- Parameters:
epimodel (EpiModel) – The epidemic model instance to simulate.
start_date (str or pd.Timestamp) – The start date of the simulation. Default is “2020-01-01”.
end_date (str or pd.Timestamp) – The end date of the simulation. Default is “2020-12-31”.
initial_conditions_dict (dict, optional) – A dictionary of initial conditions for the simulation.
percentage_in_agents (float, optional) – The percentage of the population to initialize in the agents compartment.
dt (float, optional) – The time step for the simulation, expressed in days. Default is 1 (day).
resample_frequency (str, optional) – The frequency at which to resample the simulation results. Default is “D” (daily).
resample_aggregation_compartments (str, optional) – The aggregation method to use when resampling the compartments. Default is “last”.
resample_aggregation_transitions (str, optional) – The aggregation method to use when resampling the transitions. Default is “sum”.
fill_method (str, optional) – The method to use when filling NaN values after resampling. Default is “ffill”.
apply_linear_approximation (bool, optional) – Whether to use linear approximation to the probabilities. Default is False.
rng (np.random.Generator, optional) – Random number generator. Default is None.
contact_matrices (list, optional) – A list of contact matrices for the simulation. Default is None.
simulation_dates (list, optional) – A list of simulation dates. Default is None.
**kwargs – Additional parameters to overwrite model parameters during the simulation.
- Returns:
The trajectory of the simulation
- Return type:
- Raises:
ValueError – If the model has no transitions defined.