simple_network_sim package¶
Simple network sim is a network-based model for disease outbreak modeling. This package was writing specially for the COVID-19 pandemic of 2019/2020.
The main model is the network_of_populations, which connects regions. The network_of_individuals model is not completed and, currently, it’s entirely commented out. However, its goal would be to connect people instead of regions.
Submodules¶
simple_network_sim.common module¶
Assortment of useful functions
-
class
simple_network_sim.common.
IssueSeverity
(value)¶ Bases:
enum.Enum
This class defines the severity levels for issues found while running the model or loading data.
-
HIGH
= 10¶
-
LOW
= 1¶
-
MEDIUM
= 5¶
-
-
class
simple_network_sim.common.
Lazy
(f: Callable[], Any])¶ Bases:
object
This class allows lazy evaluation of logging expressions. The idiom to accomplish that can be better explained in the example below:
logger.info("The value of z is: %s", lazy(lambda: x + y))
that will cause
x + y
to only be evaluated if the log level is info.- Parameters
f – A function which takes no parameters and which will only be evaluated when str is called in the returning object
-
class
simple_network_sim.common.
RepoInfo
(git_sha: str, uri: str, is_dirty: bool)¶ Bases:
tuple
The info needed by the data pipeline API
-
property
git_sha
¶ Alias for field number 0
-
property
is_dirty
¶ Alias for field number 2
-
property
uri
¶ Alias for field number 1
-
property
-
simple_network_sim.common.
generateMeanPlot
(listOfPlots)¶ From a list of disease evolution timeseries, compute the average evolution.
- Parameters
listOfPlots (list) – List of disease evolutions
- Returns
The average evolution
- Return type
list
-
simple_network_sim.common.
get_repo_info
() → simple_network_sim.common.RepoInfo¶ Retrieves the current git sha and uri for the current git repo
- Returns
A RepoInfo object. If not inside a git repo, is_dirty will be True, git_sha empty and uri will be a default value
-
simple_network_sim.common.
log_issue
(logger: logging.Logger, description: str, severity: simple_network_sim.common.IssueSeverity, issues: List[data_pipeline_api.standard_api.Issue]) → List[data_pipeline_api.standard_api.Issue]¶ Appends issue to the issues list whilst logging its description at the appropriate log level
- Parameters
logger – a python logger object
description – an explanation of the issue found
severity – the severity of the issue, from an enum of severities
issues – list of issues, it will be modified in-place
- Returns
Returns the same list of issues passed as a parameter for convenience
simple_network_sim.loaders module¶
This module contains functions and classes to read and check input files.
-
class
simple_network_sim.loaders.
AgeRange
(age_group: str)¶ Bases:
object
A helper class for an age range.
The age_group parameter can be any string, but it is usually in the format [a,b) or 70+
-
class
simple_network_sim.loaders.
MixingMatrix
(mixing_table: Union[pandas.core.frame.DataFrame, Dict[str, Dict[str, float]]])¶ Bases:
object
Stores expected numbers of interactions between people of different ages.
Stores expected number of interactions per day a given person will have with some other person, based on the ages of the two people, or given age-ranges.
Examples:
mm = MixingMatrix(api.read_table("human/mixing-matrix")) print(mm[28][57]) # Prints the expected number of interactions a 28 year old
would have with a 57 year old in a day
print(mm["[30,40)"]["70+"]); print(mm[(30,40)]["70+"])
prints the expected number of interactions someone in the age range [30-40) would have with someone aged 70 or older in any given day.
- Parameters
mixing_table – Raw DataFrame from the data API. The expected columns are: source, target and mixing (value).
-
class
simple_network_sim.loaders.
MixingRow
(ages: List[str], interactions: List[str])¶ Bases:
object
One row of a mixing table.
This is a helper class. A row represents a given population, and can return the expected number of interactions (per unit time) a member of this population will have with some other target.
- Parameters
ages (list) – Ages
interactions (list) – Interactions / person / day
Both lists must be the same length.
Upon initialization, the property self._entries is set to a dictionary mapping AgeRange objects to numbers of interactions / person / day.
-
class
simple_network_sim.loaders.
Multiplier
(movement: float, contact: float)¶ Bases:
tuple
Factors used to dampen or heighten the movement of people between nodes and contact of people within nodes
-
property
contact
¶ Alias for field number 1
-
property
movement
¶ Alias for field number 0
-
property
-
simple_network_sim.loaders.
genGraphFromContactFile
(commutes: pandas.core.frame.DataFrame) → networkx.classes.digraph.DiGraph¶ Read a file containing edge weights between nodes.
Pairs of nodes are listed in the file by source, destination, weight and adjustment.
- Parameters
commutes – Weighted edge list.
- Returns
networkx.classes.digraph.DiGraph object representing the graph.
-
simple_network_sim.loaders.
readABCSMCParameters
(parameters: pandas.core.frame.DataFrame) → Dict¶ Transforms the API output of parameters into the internal representation: a dict :param parameters: pandas DataFrame with the raw data from the API :return: a dict of inference parameters
-
simple_network_sim.loaders.
readCompartmentRatesByAge
(table: pandas.core.frame.DataFrame) → Dict[str, Dict[str, Dict[str, float]]]¶ Read a file containing a list of age-specific epidemiological parameters.
Epidemiological parameters are transition rates between or out of epidemiological compartments, here they differ by age group.
- Parameters
table – Age transition data
- Returns
nested dictionary with progression rates
-
simple_network_sim.loaders.
readHistoricalDeaths
(historical_deaths: pandas.core.frame.DataFrame) → pandas.core.frame.DataFrame¶ Transforms the API output of target into the internal representation: a pd.DataFrame :param historical_deaths: pandas DataFrame with the raw data from the API :return: a pd.DataFrame of historical deaths by HB
-
simple_network_sim.loaders.
readInfectionProbability
(df: pandas.core.frame.DataFrame) → Dict[datetime.date, float]¶ Transforms the dataframe from the data API into a dict usable inside the model
- Parameters
df – a timeseries of infection probabilities
- Returns
a timeseries of infection probabilities in the dict format
-
simple_network_sim.loaders.
readInfectiousStates
(infectious_states: pandas.core.frame.DataFrame) → List[str]¶ Transforms the API output of infectious_states into the internal representation: a list of strings :param infectious_states: pandas DataFrame with the raw data from the API :return: a list of strings of infectious compartments
-
simple_network_sim.loaders.
readInitialInfections
(df: pandas.core.frame.DataFrame) → Dict[str, Dict[str, float]]¶ Read initial numbers of infected individuals by health board and age.
- Parameters
df – raw data to be loaded
- Returns
nested dict with number of infected per age per node
-
simple_network_sim.loaders.
readMovementMultipliers
(table: pandas.core.frame.DataFrame) → Dict[datetime.date, simple_network_sim.loaders.Multiplier]¶ Read file containing movement multipliers by time.
- Parameters
table – pandas DataFrame containing movement multipliers
- Returns
A dict of ints (time) pointing to a (named)tuple (contact=float, movement=float). Contact will alter how the disease spreads inside of a node, whereas movement will change how it spread across nodes
-
simple_network_sim.loaders.
readNodeAttributesJSON
(filename)¶ Read a file containing node (health board) attributes.
This might include health board name and geographic co-ordinates.
- Parameters
filename (file-like object) – Health board attributes in json format.
- Returns
Dictionary of health board attributes.
-
simple_network_sim.loaders.
readPopulationAgeStructured
(table: pandas.core.frame.DataFrame) → Dict[str, Dict[str, int]]¶ Read a file containing population data.
Population is labelled by node ID, sex and age. Sex is currently ignored.
- Parameters
table – Population data
- Returns
Nested dict with age-stratified population in each node
-
simple_network_sim.loaders.
readRandomSeed
(df: pandas.core.frame.DataFrame) → int¶ Transforms the dataframe from the data API into a bool usable inside the model
- Parameters
df – a dataframe containing the random seed
- Returns
a value of using the random seed as an int
-
simple_network_sim.loaders.
readStartEndDate
(df: pandas.core.frame.DataFrame) → Tuple[datetime.date, datetime.date]¶ Transforms the dataframe from the data API into a bool int inside the model :param df: The dataframe containing the starting date of the model :return: The starting date of the model
-
simple_network_sim.loaders.
readStochasticMode
(df: pandas.core.frame.DataFrame) → bool¶ Transforms the dataframe from the data API into a bool usable inside the model
- Parameters
df – a dataframe with the stochastic mode
- Returns
a value of using the stochastic mode as a bool
-
simple_network_sim.loaders.
readTrials
(df: pandas.core.frame.DataFrame) → int¶ Transforms the dataframe from the data API into a bool int inside the model
- Parameters
df – The dataframe containing the number of trials
- Returns
the number of trials to run
simple_network_sim.network_of_individuals module¶
simple_network_sim.network_of_populations module¶
This package implements the network of populations simulation. This models regions as nodes with intra node rules and different inter node transmission rules. The end result of the model is a timeseries of the number of people in each node, compartment and age.
The compartments and age groups are defined in the inputs for the model. The only hardcoded compartment are:
Susceptibles (S) – people who are not immune to the disease and can catch it at any moment.
Exposed (E) – people who already have the disease, whoever do not yet show symptoms and do not yet infectious.
The main type of this module is the NetworkOfPopulation class, which is a data object with all the data needed to run
the model. The main entrypoint function for the simulation is basicSimulationInternalAgeStructure()
. That function
will run a simulation based on the data in the NetworkOfPopulation instance and it will output a pandas DataFrame
with disease progression over time. Just like most public functions in this module, it does not make changes to the
objects passed as inputs.
-
class
simple_network_sim.network_of_populations.
NetworkOfPopulation
(progression: Dict[str, Dict[str, Dict[str, float]]], initialState: Dict[str, Dict[Tuple[str, str], float]], graph: networkx.classes.digraph.DiGraph, mixingMatrix: simple_network_sim.loaders.MixingMatrix, movementMultipliers: Dict[datetime.date, simple_network_sim.loaders.Multiplier], infectiousStates: List[str], infectionProb: Dict[datetime.date, float], initialInfections: Dict[str, Dict[str, float]], trials: int, startDate: datetime.date, endDate: datetime.date, stochastic: bool)¶ Bases:
tuple
This type has all the internal data used by this model
-
property
endDate
¶ Alias for field number 10
-
property
graph
¶ Alias for field number 2
-
property
infectionProb
¶ Alias for field number 6
-
property
infectiousStates
¶ Alias for field number 5
-
property
initialInfections
¶ Alias for field number 7
-
property
initialState
¶ Alias for field number 1
-
property
mixingMatrix
¶ Alias for field number 3
-
property
movementMultipliers
¶ Alias for field number 4
-
property
progression
¶ Alias for field number 0
-
property
startDate
¶ Alias for field number 9
-
property
stochastic
¶ Alias for field number 11
-
property
trials
¶ Alias for field number 8
-
property
-
simple_network_sim.network_of_populations.
basicSimulationInternalAgeStructure
(network: simple_network_sim.network_of_populations.NetworkOfPopulation, initialInfections: Dict[str, Dict[str, float]], generator: numpy.random._generator.Generator) → Tuple[pandas.core.frame.DataFrame, List[data_pipeline_api.standard_api.Issue]]¶ Run the simulation of a disease progressing through a network of regions.
- Parameters
network – This is a NetworkOfPopulation instance which will have the states field modified by this function.
initialInfections – Initial infections of the disease
generator – Seeded random number generated to use in this simulation
- Returns
A time series of the size of the infectious population.
-
simple_network_sim.network_of_populations.
calculateExposed
(susceptible: float, contacts: float, infectionProb: float, stochastic: bool, random_state: Optional[numpy.random._generator.Generator])¶ From the number of contacts (between infectious and susceptible) people, compute the number of actual infectious contacts. Two modes:
Deterministic (
stochastic=False
) – Adjusts the contacts (see explanation below), then multiply by infection probabilityStochastic (
stochastic=True
) – Adjusts the contacts (see explanation below), then sample from a binomial distribution with \(n=\text{adjusted contacts}\), \(p=\text{infection probability}\).
When using \(k\) contacts from a susceptible population of size \(n\), we sample these \(k\) people with replacement, as in several infections can target the same person. This will decrease the exposed number for small values of \(k\), \(n\). This is not sampled stochastically as it seems no such distribution exists.
\(N\) = Number of different people chosen when picking k in a population of size n, with replacement
\[\begin{split}E[N] &= \sum_{i=1,...,n} P(\text{person i is chosen at least once}) \\ &= \sum_{i=1,...,n} (1 - P(\text{person i is never chosen in k samples})) \\ &= \sum_{i=1,...,n} (1 - P(\text{person i is not chosen once})^k) \\ &= \sum_{i=1,...,n} (1 - (1 - P(\text{person i is chosen once}))^k) \\ &= \sum_{i=1,...,n} (1 - (1 - P(\text{person i is chosen once}))^k) \\ &= n * (1 - (1 - 1 / n)^k)\end{split}\]- Parameters
susceptible – number (float) of susceptible individuals
contacts – number (float) of exposed individuals
infectionProb – probability (float) that a given contact will result in infection
stochastic – Whether to run the model in a stochastic or deterministic mode
random_state – Random number generator used for the model
-
simple_network_sim.network_of_populations.
createExposedRegions
(infections: Dict[str, Dict[str, float]], states: Dict[str, Dict[Tuple[str, str], float]]) → Dict[str, Dict[Tuple[str, str], float]]¶ Creates a new the state of a region, adding the new infections.
- Parameters
infections – The number of infections per region per age
states – The current state for every region is not modified
- Returns
A dictionary containing the merged number of exposed
-
simple_network_sim.network_of_populations.
createNetworkOfPopulation
(compartment_transition_table: pandas.core.frame.DataFrame, population_table: pandas.core.frame.DataFrame, commutes_table: pandas.core.frame.DataFrame, mixing_matrix_table: pandas.core.frame.DataFrame, infectious_states: pandas.core.frame.DataFrame, infection_prob: pandas.core.frame.DataFrame, initial_infections: pandas.core.frame.DataFrame, trials: pandas.core.frame.DataFrame, start_end_date: pandas.core.frame.DataFrame, movement_multipliers_table: pandas.core.frame.DataFrame = None, stochastic_mode: pandas.core.frame.DataFrame = None) → Tuple[simple_network_sim.network_of_populations.NetworkOfPopulation, List[data_pipeline_api.standard_api.Issue]]¶ Create the network of the population, loading data from files.
- Parameters
compartment_transition_table – pd.Dataframe specifying the transition rates between infected compartments.
population_table – pd.Dataframe with the population size in each region by gender and age.
commutes_table – pd.Dataframe with the movements between regions.
mixing_matrix_table – pd.Dataframe with the age infection matrix.
infectious_states – States that are considered infectious
infection_prob – Probability that a given contact will result in an infection
initial_infections – Initial infections of the population at time 0
trials – Number of trials for the model
start_end_date – Starting and ending dates of the model
movement_multipliers_table – pd.Dataframe with the movement multipliers. This may be None, in which case no multipliers are applied to the movements.
stochastic_mode – Use stochastic mode for the model
- Returns
A tuple with the constructed network and a list of any issues found. Although it may look convenient, storing this list inside of NetworkOfPopulation is not a good idea, as that may give the functions that receive it the false impression they can just append new issues there
-
simple_network_sim.network_of_populations.
createNextStep
(progression: Dict[str, Dict[Tuple[str, str], float]], infectiousContacts: Dict[str, Dict[str, float]], currState: Dict[str, Dict[Tuple[str, str], float]], infectionProb: float, stochastic: bool, random_state: Optional[numpy.random._generator.Generator]) → Dict[str, Dict[Tuple[str, str], float]]¶ Update the current state of each regions population by allowing infected individuals to progress to the next infection stage and infecting susceptible individuals. The state is not modified in this function, rather the updated details are returned.
See the documentation for
calculateExposed()
for an explanation of how new people are exposed from one step into the next.- Parameters
progression – The number of individuals that have progressed into each exposed stage, stratified by region and age.
infectiousContacts – The number of contacts per region per age.
currState – The current state for every region.
infectionProb – the expected rate at which contacts will transmit the diseases
stochastic – Whether to run the model in a stochastic or deterministic mode
random_state – Random number generator used for the model
- Returns
The new state of the regions.
-
simple_network_sim.network_of_populations.
dateRange
(startDate: datetime.date, endDate: datetime.date) → Iterable[datetime.date]¶ Generator of day and time from start date and end date
- Parameters
startDate – Start date of the network
endDate – End date of the network
- Returns
Generator of days as datetime.date
-
simple_network_sim.network_of_populations.
distributeContactsOverAges
(nodeState: Dict[Tuple[str, str], float], newContacts: float, stochastic: bool, random_state: Optional[numpy.random._generator.Generator], issues: Optional[List[data_pipeline_api.standard_api.Issue]] = None) → Dict[str, float]¶ Distribute the number of new contacts across a region. There are two possible implementations:
Deterministic (
stochastic=False
) – We simply allocate newContacts by proportion of people in each age groupsStochastic (
stochastic=True
) – newContacts are sampled randomly from the population from a Multinomial distribution, with: \(k=\text{new contacts}\), \(p=\text{proportion of people in age groups}\)
Note: fractional people will come out of this.
- Parameters
nodeState – The disease status of the population stratified by age.
newContacts – The number of new contacts to be distributed across age ranges.
stochastic – Whether to run the model in a stochastic or deterministic mode
random_state – Random number generator used for the model
issues – if any issues are found and a list is passed as this parameter, append the issues to it. Logging will happen regardless.
- Returns
The number of new infections in each age group.
-
simple_network_sim.network_of_populations.
expose
(age: str, exposed: float, region: Dict[Tuple[str, str], float])¶ Update the region in place, moving people from susceptible to exposed.
- Parameters
age – age group that will be exposed.
exposed – The number of exposed individuals.
region – A region, with all the (age, state) tuples.
-
simple_network_sim.network_of_populations.
getAges
(node: Dict[Tuple[str, str], float]) → List[str]¶ Get the set of ages from the node.
- Parameters
node – The disease states of the population stratified by age.
- Returns
The unique collection of ages.
-
simple_network_sim.network_of_populations.
getExternalInfectiousContacts
(graph: networkx.classes.digraph.DiGraph, nodes: Dict[str, Dict[Tuple[str, str], float]], movementMultiplier: float, infectiousStates: List[str], stochastic: bool, random_state: Optional[numpy.random._generator.Generator], issues: Optional[List[data_pipeline_api.standard_api.Issue]] = None) → Dict[str, Dict[str, float]]¶ Calculate the number of new infections in each region. The infections are distributed proportionally to the number of susceptibles in the destination node and infected in the origin node. The infections are distributed to each age group according to the number of susceptible people in them.
- Parameters
graph – A graph with each region as a node and the weights corresponding to the movements between regions. Edges must contain weight and delta_adjustment attributes (assumed 1.0)
nodes – The disease status in each region stratified by age.
movementMultiplier – A multiplier applied to each edge (movement between nodes) in the network.
infectiousStates – States that are considered infectious
stochastic – Whether to run the model in a stochastic or deterministic mode
random_state – Random number generator used for the model
issues – if any issues are found and a list is passed as this parameter, append the issues to it.
- Returns
The number of new infections in each region stratified by age.
-
simple_network_sim.network_of_populations.
getIncomingInfectiousContactsByNode
(graph: networkx.classes.digraph.DiGraph, currentState: Dict[str, Dict[Tuple[str, str], float]], movementMultiplier: float, infectiousStates: List[str], stochastic: bool, random_state: Optional[numpy.random._generator.Generator]) → Dict[str, float]¶ Determine the number of new infections at each node of a graph based on incoming people from neighbouring nodes. The stochastic parameter can be used to select between the two modes of operation:
Deterministic (
stochastic=False
) – We multiply the commute by the proportion of infectious people in giving node, and by the proportion of susceptible people in receiving age group.Stochastic (
stochastic=True
) – We assume commutes are randomly distributed across people. We sample the weight (movements between nodes) from a binomial distribution with \(p = \frac{\text{totalSusceptibleInNode}}{\text{totalPeopleInNode}}\). This gives the number of commutes that target susceptible people. Then we sample the result into another binomial distribution with \(p = \frac{\text{totalInfectiousInNeighbor}}{\text{totalPeopleInNeighbor}}\). This gives the number of commutes that target susceptible people, and originate from infectious people. That calculation is done for each pair of connected nodes
- Parameters
graph – A graph with each region as a node and the weights corresponding to the movements between regions. Edges must contain weight and delta_adjustment attributes (assumed 1.0)
currentState – The current state for every region.
movementMultiplier – a multiplier applied to each edge (movement) in the network.
infectiousStates – States that are considered infectious
stochastic – Whether to run the model in a stochastic or deterministic mode
random_state – Random number generator used for the model
- Returns
the number of new infections in each region.
-
simple_network_sim.network_of_populations.
getInfectious
(age: str, currentInternalStateDict: Dict[Tuple[str, str], float], infectiousStates: List[str]) → float¶ Calculate the total number of individuals in infectious states in an age range.
- Parameters
age – The age (range)
currentInternalStateDict – The disease status of the population stratified by age.
infectiousStates – States that are considered infectious
- Returns
The number of individuals in an infectious state and age range.
-
simple_network_sim.network_of_populations.
getInitialParameter
(startDate: datetime.date, timeSeries: Dict[datetime.date, Any], default: Any, raise_on_missing: bool = False)¶ Queries the timeSeries at the most recent date before (and including) model start date. If no such date is found returns the default value if raise_on_missing == False, otherwise returns ValueError.
- Parameters
startDate – Start date of the network
timeSeries – dict of parameters indexed by dates
default – default value to use if not date before or at startDate is found
raise_on_missing – If not date before or at startDate is found, raise or return default
- Returns
Multipliers for initial day
-
simple_network_sim.network_of_populations.
getInternalInfectiousContacts
(nodes: Dict[str, Dict[Tuple[str, str], float]], mixingMatrix: simple_network_sim.loaders.MixingMatrix, contactsMultiplier: float, infectiousStates, stochastic: bool, random_state: Optional[numpy.random._generator.Generator]) → Dict[str, Dict[str, float]]¶ Calculate the new infections and stratify them by region and age.
- Parameters
nodes – The disease status in each region stratified by age.
mixingMatrix – Stores expected numbers of interactions between people of different ages.
contactsMultiplier – Multiplier applied to the number of infectious contacts.
infectiousStates – States that are considered infectious
stochastic – Whether to run the model in a stochastic or deterministic mode
random_state – Random number generator used for the model
- Returns
The number of exposed in each region stratified by age.
-
simple_network_sim.network_of_populations.
getInternalInfectiousContactsInNode
(currentInternalStateDict: Dict[Tuple[str, str], float], mixingMatrix: simple_network_sim.loaders.MixingMatrix, contactsMultiplier: float, infectiousStates: List[str], stochastic: bool, random_state: Optional[numpy.random._generator.Generator]) → Dict[str, float]¶ Calculate the new infections due to mixing within the region and stratify them by age. The stochastic parameter can be used to select between two modes:
Deterministic (
stochastic=False
) – We simply multiply the contacts by number of infectious, and by proportion of susceptiblesStochastic (
stochastic=True
) – For each infectious individual we sample from a Poisson distribution with mean the number of contacts. Then the output k (number of contacts for one particular person), is inputted in a Hypergeometric distribution, where we sample k individuals with replacement in the population of susceptibles. This provides potentially infectious contacts, which are summed.
- Parameters
currentInternalStateDict – The disease status of the population stratified by age.
mixingMatrix – Stores expected numbers of interactions between people of different ages.
contactsMultiplier – Multiplier applied to the number of infectious contacts.
infectiousStates – States that are considered infectious
stochastic – Whether to run the model in a stochastic or deterministic mode
random_state – Random number generator used for the model
- Returns
The number of new infections stratified by age.
-
simple_network_sim.network_of_populations.
getInternalProgressionAllNodes
(currStates: Dict[str, Dict[Tuple[str, str], float]], diseaseProgressionProbs: Dict[str, Dict[str, Dict[str, float]]], stochastic: bool, random_state: Optional[numpy.random._generator.Generator]) → Dict[str, Dict[Tuple[str, str], float]]¶ Given the size of the population in each exposed state, calculate the numbers that progress the next disease state based on the progression matrix.
- Parameters
currStates – The current state for every region is not modified.
diseaseProgressionProbs – A matrix with the probabilities if progressing from one state to the next.
stochastic – Whether to run the model in a stochastic or deterministic mode
random_state – Random number generator used for the model
- Returns
The number of individuals that have progressed into each exposed stage, stratified by region and age.
-
simple_network_sim.network_of_populations.
getSusceptibles
(age: str, currentInternalStateDict: Dict[Tuple[str, str], float]) → float¶ Calculate the total number of individuals in a susceptible state in an age range within a region.
- Parameters
age – The age (range)
currentInternalStateDict – The disease status of the population in a region stratified by age.
- Returns
The number of individuals in a susceptible state and age range.
-
simple_network_sim.network_of_populations.
getTotalInAge
(nodeState: Dict[Tuple[str, str], float], ageTest: str) → float¶ Get the size of the population within an age group.
- Parameters
nodeState – The disease states of the population stratified by age.
ageTest – The age range of the population.
- Returns
The population size within the age range.
-
simple_network_sim.network_of_populations.
getTotalInfectious
(node: Dict[Tuple[str, str], float], infectiousStates: List[str]) → float¶ Get the total number of infectious individuals regardless of age in the node.
- Parameters
node – The disease status of the population stratified by age.
infectiousStates – States that are considered infectious
- Returns
The total number of infectious individuals.
-
simple_network_sim.network_of_populations.
getTotalSuscept
(nodeState: Dict[Tuple[str, str], float]) → float¶ Get the total number of susceptible individuals regardless of age in the node
- Parameters
nodeState – The disease status of the population stratified by age.
- Returns
The total number of susceptible individuals.
-
simple_network_sim.network_of_populations.
getWeight
(graph: networkx.classes.digraph.DiGraph, orig: str, dest: str, multiplier: float) → float¶ Get the weight of the edge from orig to dest in the graph. This weight is expected to be proportional to the movement between nodes. If the edge doesn’t have a weight, 1.0 is assumed and the returned weight is adjusted by the multiplier and any delta_adjustment on the edge.
- Parameters
graph – A graph with each region as a node and the weights corresponding to the commutes between regions. Edges must contain weight and delta_adjustment attributes (assumed 1.0)
orig – The vertex people are coming from.
dest – The vertex people are going to.
multiplier – Value that will dampen or heighten movements between nodes.
- Returns
The final weight value
-
simple_network_sim.network_of_populations.
internalStateDiseaseUpdate
(currentInternalStateDict: Dict[Tuple[str, str], float], diseaseProgressionProbs: Dict[str, Dict[str, Dict[str, float]]], stochastic: bool, random_state: Optional[numpy.random._generator.Generator]) → Dict[Tuple[str, str], float]¶ Returns the status of exposed individuals, moving them into the next disease state with a probability defined in the given progression matrix. The stochastic parameters selects between two modes:
Deterministic (
stochastic=False
) – The people in the given state are transferred into the next available states by multiplying by the probability of going to each state.Stochastic (
stochastic=True
) – We sample from a multinomial distribution with parameters: \(k=\text{people in state}\), \(p=\text{state transition probability}\).
- Parameters
currentInternalStateDict – The disease status of the population stratified by age.
diseaseProgressionProbs – A matrix with the probabilities if progressing from one state to the next.
stochastic – Whether to run the model in a stochastic or deterministic mode
random_state – Random number generator used for the model
- Returns
the numbers in each exposed state stratified by age
-
simple_network_sim.network_of_populations.
mergeContacts
(*args) → Dict[str, Dict[str, float]]¶ From a list of exposed cases stratified by age and region, merge them into a single collection
- Parameters
args (A variable list of dictionaries that have a region as a key and the value is a dictionary of {age:number of exposed}.) – A variable list of regional exposure numbers by age.
- Returns
A dictionary containing the merged number of exposed.
-
simple_network_sim.network_of_populations.
nodesToPandas
(date: datetime.date, nodes: Dict[str, Dict[Tuple[str, str], float]]) → pandas.core.frame.DataFrame¶ Converts a dict of nodes into a pandas DataFrame
>>> nodesToPandas(dt.date(2020, 1, 1), {"nodea": {("70+", "S"): 10.0, ("70+", "E"): 15.0}, "nodeb": {("[17,70", "S"): 15.0}}) date node age state total 0 2020-01-01 nodea 70+ S 10.0 1 2020-01-01 nodea 70+ E 15.0 2 2020-01-01 nodeb [17,70 S 15.0 >>> nodesToPandas(dt.date(2020, 1, 1), {}) Empty DataFrame Columns: [date, node, age, state, total] Index: []
- Parameters
date – date that will be inserted into every row
nodes – a dict of nodes
- Returns
a pandas dataframe representation of the nodes
-
simple_network_sim.network_of_populations.
randomlyInfectRegions
(network: simple_network_sim.network_of_populations.NetworkOfPopulation, regions: int, age_groups: List[str], infected: float, random_state: numpy.random._generator.Generator) → Dict[str, Dict[str, float]]¶ Randomly infect regions to initialize the random simulation
- Parameters
network – object representing the network of populations
regions – The number of regions to expose.
age_groups – Age groups to infect
infected – People to infect
random_state – Random state for random number generation
- Returns
Structure of initially infected regions with number
-
simple_network_sim.network_of_populations.
totalIndividuals
(nodeState: Dict[Tuple[str, str], float]) → float¶ This function takes a node (region) and counts individuals from every age and state.
- Parameters
nodeState – The disease status of a node (or region) stratified by age.
- Returns
The total number of individuals.
simple_network_sim.sampleUseOfModel module¶
This is the main module used to run simulations based on network of populations
-
class
simple_network_sim.sampleUseOfModel.
Result
(output: pandas.core.frame.DataFrame, issues: List[data_pipeline_api.standard_api.Issue], description: str = 'A dataframe of the number of people in each node, compartment and age over time')¶ Bases:
tuple
This object contains the results of a simulation and a small description
-
property
description
¶ Alias for field number 2
-
property
issues
¶ Alias for field number 1
-
property
output
¶ Alias for field number 0
-
property
-
simple_network_sim.sampleUseOfModel.
aggregateResults
(results: List[simple_network_sim.sampleUseOfModel.Result]) → simple_network_sim.sampleUseOfModel.Result¶ Aggregate results from runs
- Parameters
results – result runs from runSimulation
- Returns
Averaged number of infection through time, for all trial
-
simple_network_sim.sampleUseOfModel.
build_args
(argv)¶ Return parsed CLI arguments as argparse.Namespace.
- Parameters
argv (list) – CLI arguments
-
simple_network_sim.sampleUseOfModel.
main
(argv)¶ Main function to run the network of populations simulation
-
simple_network_sim.sampleUseOfModel.
runSimulation
(network: simple_network_sim.network_of_populations.NetworkOfPopulation, random_seed: int, issues: List[data_pipeline_api.standard_api.Issue], max_workers: Optional[int] = None) → List[simple_network_sim.sampleUseOfModel.Result]¶ Run pre-created network
- Parameters
network – object representing the network of populations
random_seed – seed to use when instantiating the SeedSequence object
issues – list of issues to report to the pipeline
max_workers – maximum number of processes to spawn when running multiple simulations
- Returns
Result runs for all trials of the simulation
-
simple_network_sim.sampleUseOfModel.
setup_logger
(args: Optional[argparse.Namespace] = None) → None¶ Configure package-level logger instance.
- Parameters
args – argparse.Namespace args.logfile (pathlib.Path) is used to create a logfile if present args.quiet and args.debug control logging level to sys.stderr
This function can be called without args, in which case it configures the package logger to write WARNING and above to STDERR.
When called with args, it uses args.logfile to determine if logs (by default, INFO and above) should be written to a file, and the path of that file. args.quiet and args.debug are used to control reporting level.