MetaWards API Detail

Classes

Demographic([name, work_ratio, play_ratio, ...])

This class represents a single demographic

Demographics(demographics, random_seed, ...)

This class holds metadata about all of the demographics being modelled

Disease([name, stage, mapping, beta, ...])

This class holds the parameters about a single disease

Infections()

This class holds the arrays that record the infections as they are occuring during the outbreak

InputFiles([work, play, identifier, ...])

This class holds all of the input files that must be loaded from METAWARDSDATA to construct the network of wards and links between them

Interpret()

This is a static class that provides some routines for interpreting values from inputs (normally strings).

Link([ifrom, ito, weight, suscept, distance])

This is a link between nodes in the network

Links([N])

This is a container class for Links.

Network([name, nodes, links, play, nnodes, ...])

This class represents a network of wards.

Networks(overall, subnets, demographics)

This is a combination of Network objects which together represent an entire diverse population.

Node([label, begin_to, end_to, self_w, ...])

This class represents an electoral ward (node) in the network

Nodes([N])

This is a container class for Nodes.

OutputFiles(output_dir, check_empty, force_empty)

This is a class that manages all of the output files that are written to during a model outbreak.

Parameters(input_files, disease_params, ...)

The full set of Parameters that are used to control the model outbreak over a Network.

PersonType(value)

The type of individual in the network.

Population([initial, susceptibles, latent, ...])

This class holds information about the progress of the disease through the population

Populations([_trajectory])

This class holds the trajectory of Population objects recorded for every step (day) of a model outbreak

VariableSet([variables, repeat_index, ...])

This class holds a single set of adjustable variables that are used to adjust the variables as part of a model run

VariableSets()

This class holds the collection of all VariableSet objects that contain the set of adjustable variables that are used to control a single run of the model

Ward([id, name, code, authority, region, ...])

This class holds all of the information about a Ward.

WardID([home, commute, all_commute])

A simple class that identifies a Ward (or Wards), or a connection between Wards.

WardInfo(name, alternate_names, code, ...)

This class holds metadata about a ward, e.g.

WardInfos(wards, _index, int]] = None)

Simple class that holds a list of WardInfo objects, and provides useful search functions over that list.

Wards([wards])

This class holds an entire network of Ward objects

Workspace([n_inf_classes, nnodes, inf_tot, ...])

This class provides a workspace for the running calculation.

Functions

get_version_string()

Return a version string for metawards which can be printed into a file or written out to the screen

print_version_string()

input(prompt[, default])

Wrapper for 'input' that returns 'default' if it detected that this is being run from within a batch job or other service that doesn't have access to a tty

run([help, version, dry_run, silent, ...])

Run a MetaWards simulation

find_mw_exe()

Try to find the MetaWards executable.

find_mw_include()

Try to find the directory containing the MetaWards include files.

find_mw_lib()

Try to find the directory containing the MetaWards libraries (e.g.

get_reticulate_command()

Print the reticulate command that you need to type to be able to use the Python in which MetaWards is installed

class metawards.Demographic(name: Optional[str] = None, work_ratio: Optional[float] = None, play_ratio: Optional[float] = None, adjustment: Optional[metawards._variableset.VariableSet] = None, disease: Optional[Union[str, metawards._disease.Disease]] = None, network: Optional[Union[str, metawards._inputfiles.InputFiles]] = None)[source]

This class represents a single demographic

__eq__(other)

Return self==value.

__hash__ = None
__init__(name: Optional[str] = None, work_ratio: Optional[float] = None, play_ratio: Optional[float] = None, adjustment: Optional[metawards._variableset.VariableSet] = None, disease: Optional[Union[str, metawards._disease.Disease]] = None, network: Optional[Union[str, metawards._inputfiles.InputFiles]] = None)[source]

Construct the Demographics

__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

adjustment: metawards._variableset.VariableSet = None

How the parameters for this demographic should be changed compared to the parameters used for the whole population. This is currently changed to fixed values, but future developments in VariableSet will support rules for varying relative to the whole population. If this is None then this demographic will have the same parameters as the whole population

disease: metawards._disease.Disease = None

The Disease that should be used for this demographic. Is this is None, then the global Disease is used. Otherwise this demographic will follow this Disease

name: str = None

The name of this demographic. This will be used as a label, and should be unique within the Demographics

network: metawards._inputfiles.InputFiles = None

The network that describes the workers and player that are part of this demographic. If this is None then the entire population network will be used (scaled by “work_ratio” and “play_ratio”)

play_ratio: float = 0.0

The proportion of “play” (random movement) members in this demographic out of the entire population. This can also either be a single number, or a list with a value for every ward. Whichever way is used, the sum of “play_ratio” for each demographic must equal 1.0 in each ward (every member of the play population must be represented)

specialise(network: metawards._network.Network, profiler=None, nthreads: int = 1)[source]

Return a copy of the passed network that has been specialised for this demographic. The returned network will contain only members of this demographic, with the parameters of the network adjusted according to the rules of this demographic

Parameters

network (Network) – The network to be specialised

Returns

network – The specialised network

Return type

Network

work_ratio: float = 0.0

The proportion of “work” (fixed movement) members in this demographic out of the entire population. This can either be a single number, or a list with a value for every ward. Whichever way is used, the sum of “work_ratio” for each demographic must equal 1.0 in each ward (every member of the work population must be represented)

class metawards.Demographics(demographics: List[metawards._demographic.Demographic] = <factory>, random_seed: Optional[int] = None, interaction_matrix: Optional[List[List[int]]] = None, _names: Dict[str, int] = <factory>, _name: Optional[str] = None, _version: Optional[str] = None, _authors: Optional[str] = None, _contacts: Optional[str] = None, _references: Optional[str] = None, _filename: Optional[str] = None, _repository: Optional[str] = None, _repository_version: Optional[str] = None, _repository_branch: Optional[str] = None)[source]

This class holds metadata about all of the demographics being modelled

__eq__(other)[source]

Return self==value.

__hash__ = None
__init__(demographics: List[metawards._demographic.Demographic] = <factory>, random_seed: Optional[int] = None, interaction_matrix: Optional[List[List[int]]] = None, _names: Dict[str, int] = <factory>, _name: Optional[str] = None, _version: Optional[str] = None, _authors: Optional[str] = None, _contacts: Optional[str] = None, _references: Optional[str] = None, _filename: Optional[str] = None, _repository: Optional[str] = None, _repository_version: Optional[str] = None, _repository_branch: Optional[str] = None) None
__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

add(demographic: metawards._demographic.Demographic)[source]

Add a demographic to the set to be modelled

build(params: Parameters, population: Population = None, max_nodes: int = 16384, max_links: int = 4194304, nthreads: int = 1, profiler: Profiler = None) _Union[Network, Networks][source]

Build the set of networks described by these demographics and the passed parameters

Parameters
  • params (Parameters) – Parameters used to help build the model networks

  • max_nodes (int) – Initial guess for the maximum number of nodes(wards)

  • max_links (int) – Initial guess for the maximum number of links between wards

  • profiler (Profiler) – Profiler used to profile the specialisation

  • nthreads (int) – Number of threads over which to parallelise the work

Returns

The set of Networks that represent the model run over the full set of different demographics(or Network if there is just a single demographic)

Return type

Network or Networks

copy()[source]

Return a copy of this demographics object that should allow a safe reset between runs. This deepcopies things that may change, while shallow copying things that won’t

demographics: List[metawards._demographic.Demographic]

The list of individual Demographic objects, one for each demographic being modelled

static from_data(data, json_dir=None) metawards._demographics.Demographics[source]

Construct and return a Demographics object constructed from a (json-deserialised) data dictionary

static from_json(s: str)[source]

Construct and return Demographics loaded from the passed json file

get_index(item)[source]

Return the index of the passed item

get_name(item)[source]

Return the name of the demographic at ‘item’

interaction_matrix: List[List[int]] = None

The interaction matrix between demographics. This should be a list of lists that shows how demographic ‘i’ affects demographic ‘j’

is_multi_network()[source]

Return whether or not these demographics need to use multiple custom networks (e.g. refer to different network models)

static load(name: Optional[str] = None, repository: Optional[str] = None, folder: str = 'demographics', filename: Optional[str] = None)[source]

Load the parameters for the specified set of demographics. This will look for a file called f”{name}.json” in the directory f”{repository}/{folder}/{name}.json”

By default this will load nothing.

Alternatively you can provide the full path to the json file via the “filename” argument

Parameters
  • name (str) – The name of the demographics to load. This is the name that will be searched for in the METAWARDSDATA diseases directory

  • repository (str) – The location of the cloned METAWARDSDATA repository

  • folder (str) – The name of the folder within the METAWARDSDATA repository that contains the diseases

  • filename (str) – The name of the file to load the disease from - this directly loads this file without searching through the METAWARDSDATA repository

Returns

demographics – The constructed and validated demographics

Return type

Demographics

random_seed: int = None

The random seed to used when using any random number generator to resolve decisions needed when allocating individuals to demographics. This is set here so that the Demographics are uniquely determined and reproducible across runs

specialise(network: Network, profiler: Profiler = None, nthreads: int = 1)[source]

Build the set of networks that will model this set of demographics applied to the passed Network.

Parameters
  • network (Network) – The overall population model - this contains the base parameters, wards, work and play links that define the model outbreak

  • profiler (Profiler) – Profiler used to profile the specialisation

  • nthreads (int) – Number of threads over which to parallelise the work

Returns

networks – The set of Networks that represent the model run over the full set of different demographics

Return type

Networks

to_data()[source]

Return a data dictionary for this object that can be serialised to json

to_json(filename: Optional[str] = None, indent: Optional[int] = None, auto_bzip: bool = True) str[source]

Serialise the Demographics to JSON. This will write to a file if filename is set, otherwise it will return a JSON string.

Parameters
  • filename (str) – The name of the file to write the JSON to. The absolute path to the written file will be returned. If filename is None then this will serialise to a JSON string which will be returned.

  • indent (int) – The number of spaces of indent to use when writing the json

  • auto_bzip (bool) – Whether or not to automatically bzip2 the written json file

Returns

Returns either the absolute path to the written file, or the json-serialised string

Return type

str

uses_named_network()[source]

Return whether or not at least one of these demographics specifies the use of a named network model

class metawards.Disease(name: Optional[str] = None, stage: Optional[List[str]] = None, mapping: Optional[List[str]] = None, beta: Optional[List[float]] = None, progress: Optional[List[float]] = None, too_ill_to_move: Optional[List[float]] = None, contrib_foi: Optional[List[float]] = None, is_infected: Optional[List[bool]] = None, start_symptom: Optional[int] = None, _version: Optional[str] = None, _authors: Optional[str] = None, _contacts: Optional[str] = None, _references: Optional[str] = None, _filename: Optional[str] = None, _repository: Optional[str] = None, _repository_version: Optional[str] = None, _repository_branch: Optional[str] = None)[source]

This class holds the parameters about a single disease

A disease is characterised as a serious of stages, each with their own values of the beta, progress, too_ill_to_move and contrib_foi parameters. To load a disease use the Disease.load function, e.g.

Examples

>>> disease = Disease.load("ncov")
>>> print(disease)
Disease ncov
repository: https://github.com/metawards/MetaWardsData
repository_branch: main
repository_version: 0.2.0
beta = [0.0, 0.0, 0.95, 0.95, 0.0]
progress = [1.0, 0.1923, 0.909091, 0.909091, 0.0]
too_ill_to_move = [0.0, 0.0, 0.0, 0.0, 0.0]
contrib_foi = [1.0, 1.0, 1.0, 1.0, 0.0]
N_INF_CLASSES()[source]

Return the number of stages of the disease

__eq__(other)[source]

Return self==value.

__getitem__(index: int) Dict[str, Union[str, float, bool]][source]

Return the values of parameters of the stage as specified index

__hash__ = None
__init__(name: Optional[str] = None, stage: Optional[List[str]] = None, mapping: Optional[List[str]] = None, beta: Optional[List[float]] = None, progress: Optional[List[float]] = None, too_ill_to_move: Optional[List[float]] = None, contrib_foi: Optional[List[float]] = None, is_infected: Optional[List[bool]] = None, start_symptom: Optional[int] = None, _version: Optional[str] = None, _authors: Optional[str] = None, _contacts: Optional[str] = None, _references: Optional[str] = None, _filename: Optional[str] = None, _repository: Optional[str] = None, _repository_version: Optional[str] = None, _repository_branch: Optional[str] = None) None
__repr__()[source]

Return repr(self).

__setitem__(index: int, value: Dict[str, Union[str, float, bool]]) None[source]

Set the value of parameters at this index. The keys in the dictionary (and their values) match the arguments to the “insert” or “add” functions

__str__()[source]

Return str(self).

add(name: str, mapping: Optional[str] = None, beta: Optional[float] = None, progress: Optional[float] = None, too_ill_to_move: Optional[float] = None, contrib_foi: Optional[float] = None, is_start_symptom: Optional[bool] = None, is_infected: Optional[bool] = None) None[source]

Add a new stage to the disease. This will append a new stage onto the list of stages.

Parameters
  • name (str) – The name of the stage, e.g. “E”, “I”, “R” etc.

  • mapping (str) – Which main stage this stage should map to (if this is a sub-stage). This will be derived automatically if not set.

  • beta (float) – The beta (infectivity) parameter. This should be between 0.0 amd 1.0. If not set, then this will be set automatically.

  • progress (float) – The fraction of individuals at this stage who will move to the next stage. This should be between 0.0 amd 1.0. If this is not set, then this will be set automatically.

  • too_ill_to_move (float) – The proportion of workers at this stage who do not travel to work. This should be between 0.0 and 1.0. If this is not set, then this will be set automatically.

  • contrib_foi (float) – The contribution of individuals in this stage to the force-of-infection (foi) of the wards they visit. This should normally be 1.0 and will be set automatically if not set.

  • is_start_symptom (bool) – Whether this is the start symptom of the disease. This normally doesn’t need to be set as this will be worked out automatically by the code.

  • is_infected (bool) – Whether or not this stage is an infected stage. Infected stages are any where the individual is infected by the virus. Non-infected stages are thus “S” and “R”. If you don’t specify this then it will be guess based on the stage name. Note that “R” stages cannot be classed as infected. You typically don’t need to set this as the automatic guess is good. The only time you need to use this is if you want to add additional non-infected stages to “S” and “R”, e.g. “V” to represent vaccinated individuals

assert_sane()[source]

Assert that this disease is valid

beta: List[float] = None

Beta parameter for each stage of the disease

contrib_foi: List[float] = None

Contribution to the Force of Infection (FOI) parameter for each stage of the disease

static from_data(data) metawards._disease.Disease[source]

Return a new Disease constructed from the passed data dictionary (e.g. deserialised from json)

static from_json(s: str) metawards._disease.Disease[source]

Return the Disease constructed from the passed json. This will either load from a passed json string, or from json loaded from the passed file

get_index(idx)[source]

Return the index of disease stage ‘idx’ in this disease. Note that “S” is a special name that refers to the susceptibles. This will return -1

get_mapping_to(other)[source]

Return the mapping from stage index i of this disease to stage index j other the passed other disease. This returns ‘None’ if there is no need to map because the stages are the same.

The mapping will map the states according to their label, matching the ith labelled X state in this disease to the ith labelled X state in other (or to the highest labelled X state if we have more of these states than other).

Thus, is we have;

self = [“*”, “E”, “I”, “I”, “R”] other = [“*”, “E”, “I”, “I”, “I”, “R”]

then

self.get_mapping_to(other) = [0, 1, 2, 3, 5] other.get_mapping_to(self) = [0, 1, 2, 3, 3, 4]

If we can’t map a state, then we will try to map to “I”. If we still can’t map, then this is an error.

insert(index: int, name: str, mapping: Optional[str] = None, beta: Optional[float] = None, progress: Optional[float] = None, too_ill_to_move: Optional[float] = None, contrib_foi: Optional[float] = None, is_start_symptom: Optional[bool] = None, is_infected: Optional[bool] = None) None[source]

Insert a new stage into the disease. This will insert a new stage into the list of stages at index ‘index’

Parameters
  • index (str) – The index at which to insert the new stage

  • name (str) – The name of the stage, e.g. “E”, “I”, “R” etc.

  • mapping (str) – Which main stage this stage should map to (if this is a sub-stage). This will be derived automatically if not set.

  • beta (float) – The beta (infectivity) parameter. This should be between 0.0 amd 1.0. If not set, then this will be set automatically.

  • progress (float) – The fraction of individuals at this stage who will move to the next stage. This should be between 0.0 amd 1.0. If this is not set, then this will be set automatically.

  • too_ill_to_move (float) – The proportion of workers at this stage who do not travel to work. This should be between 0.0 and 1.0. If this is not set, then this will be set automatically.

  • contrib_foi (float) – The contribution of individuals in this stage to the force-of-infection (foi) of the wards they visit. This should normally be 1.0 and will be set automatically if not set.

  • is_start_symptom (bool) – Whether this is the start symptom of the disease. This normally doesn’t need to be set as this will be worked out automatically by the code.

  • is_infected (bool) – Whether or not this stage is an infected stage. Infected stages are any where the individual is infected by the virus. Non-infected stages are thus “S” and “R”. If you don’t specify this then it will be guess based on the stage name. Note that “R” stages cannot be classed as infected. You typically don’t need to set this as the automatic guess is good. The only time you need to use this is if you want to add additional non-infected stages to “S” and “R”, e.g. “V” to represent vaccinated individuals

is_infected: List[bool] = None

Whether or not this stage is an infected stage. By default all stages other than those mapped to “R” are classes as infected stages

static load(disease: Optional[str] = None, repository: Optional[str] = None, folder: Optional[str] = None, filename: Optional[str] = None)[source]

Load the disease parameters for the specified disease. This will look for a file called f”{disease}.json” in the directory f”{repository}/{folder}/{disease}.json”

By default this will load the ncov (SARS-Cov-2) parameters from $HOME/GitHub/model_data/diseases/ncov.json

Alternatively you can provide the full path to the json file via the “filename” argument

Parameters
  • disease (str) – The name of the disease to load. This is the name that will be searched for in the METAWARDSDATA diseases directory

  • repository (str) – The location of the cloned METAWARDSDATA repository

  • folder (str) – The name of the folder within the METAWARDSDATA repository that contains the diseases

  • filename (str) – The name of the file to load the disease from - this directly loads this file without searching through the METAWARDSDATA repository

Returns

disease – The constructed and validated disease

Return type

Disease

mapping: List[str] = None

Mapping label, e.g. “*”, “E”, “I” or “R”

name: str = None

Name of the disease

progress: List[float] = None

Progress parameter for each stage of the disease

stage: List[str] = None

Name of the stage, e.g. “H1”, “I2”, “E1” etc.

start_symptom: int = None

Index of the first symptomatic stage

to_data() Dict[str, any][source]

Return a data dictionary version of this disease, suitable for serialising to, e.g., json

to_json(filename: Optional[str] = None, indent: Optional[int] = None, auto_bzip: bool = True) str[source]

Serialise the Disease to JSON. This will write to a file if filename is set, otherwise it will return a JSON string.

Parameters
  • filename (str) – The name of the file to write the JSON to. The absolute path to the written file will be returned. If filename is None then this will serialise to a JSON string which will be returned.

  • indent (int) – The number of spaces of indent to use when writing the json

  • auto_bzip (bool) – Whether or not to automatically bzip2 the written json file

Returns

Returns either the absolute path to the written file, or the json-serialised string

Return type

str

too_ill_to_move: List[float] = None

TooIllToMove parameter for each stage of the disease

class metawards.Infections[source]

This class holds the arrays that record the infections as they are occuring during the outbreak

property N_INF_CLASSES: int

The total number of stages in the disease

__eq__(other)

Return self==value.

__hash__ = None
__init__() None
__repr__()

Return repr(self).

aggregate(profiler=None, nthreads: int = 1) None[source]

Aggregate all of the infection data from the demographic sub-networks

Parameters
  • network (Network) – Network that was used to initialise these infections

  • profiler (Profiler, optional) – Profiler used to profile the calculation, by default None

  • nthreads (int, optional) – Number of threads to use, by default 1

static build(network: Optional[Union[metawards._network.Network, metawards._networks.Networks]] = None, overall: Optional[metawards._network.Network] = None)[source]

Construct and return the Infections object that will track infections during a model run on the passed Network (or Networks)

Parameters
  • network (Network or Networks) – The network or networks that will be run

  • overall (Network) – The overall network to which this subnet belongs

Returns

infections – The space for the work and play infections for the network (including space for all of the demographics)

Return type

Infections

clear(nthreads: int = 1)[source]

Clear all of the infections (resets all to zero)

Parameters

nthreads (int) – Optionally parallelise this reset by specifying the number of threads to use

get_stage_mapping()[source]

Return the mapping from disease stages in this sub-network to disease stages in the overall network. This returns a list where mapping[i] gives the index of stage i in the subnetwork to stage j in the overall network

get_work_index()[source]

Return the mapping from the index in this sub-networks work matrix to the mapping in the overall network’s work matrix

has_different_stage_mapping()[source]

Return whether or not the sub-network disease stages are different to that of the overall network, and must thus be mapped

has_different_work_matrix()[source]

Return whether or not the sub-network work matrix is different to that of the overall network

Return the number of work links

property nnodes: int

The total number of nodes (wards)

property nsubnets: int

Return the number of demographic subnetworks

play = None

The infections caused by random (play) movements. This is a list of int arrays, size play[N_INF_CLASSES][nnodes+1]

subinfs = None

The infections for the multi-demographic subnets

work = None

The infections caused by fixed (work) movements. This is a list of int arrays, size work[N_INF_CLASSES][nlinks+1]

class metawards.InputFiles(work: Optional[str] = None, play: Optional[str] = None, identifier: Optional[str] = None, identifier2: Optional[str] = None, weekend: Optional[str] = None, work_size: Optional[str] = None, play_size: Optional[str] = None, position: Optional[str] = None, coordinates: Optional[str] = None, lookup: Optional[str] = None, lookup_columns: Optional[Dict[str, int]] = None, seed: Optional[str] = None, nodes_to_track: Optional[str] = None, uv: Optional[str] = None, is_single: bool = False, wards_data: Optional[str] = None, _filename: Optional[str] = None, _model_name: Optional[str] = None, _model_path: Optional[str] = None, _model_version: Optional[str] = None, _authors: Optional[str] = None, _contacts: Optional[str] = None, _references: Optional[str] = None, _repository: Optional[str] = None, _repository_version: Optional[str] = None, _repository_branch: Optional[str] = None)[source]

This class holds all of the input files that must be loaded from METAWARDSDATA to construct the network of wards and links between them

Load using the InputFiles.load function e.g.

Examples

>>> infiles = InputFiles.load("2011Data")
>>> print(infiles)
Model 2011Data version March 29 2020
repository: https://github.com/metawards/MetaWardsData
repository_branch: main
repository_version: 0.2.0
etc.
__eq__(other)

Return self==value.

__hash__()[source]

Return hash(self).

__init__(work: Optional[str] = None, play: Optional[str] = None, identifier: Optional[str] = None, identifier2: Optional[str] = None, weekend: Optional[str] = None, work_size: Optional[str] = None, play_size: Optional[str] = None, position: Optional[str] = None, coordinates: Optional[str] = None, lookup: Optional[str] = None, lookup_columns: Optional[Dict[str, int]] = None, seed: Optional[str] = None, nodes_to_track: Optional[str] = None, uv: Optional[str] = None, is_single: bool = False, wards_data: Optional[str] = None, _filename: Optional[str] = None, _model_name: Optional[str] = None, _model_path: Optional[str] = None, _model_version: Optional[str] = None, _authors: Optional[str] = None, _contacts: Optional[str] = None, _references: Optional[str] = None, _repository: Optional[str] = None, _repository_version: Optional[str] = None, _repository_branch: Optional[str] = None) None
__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

coordinates: str = None

Coordinates-system used for the positions. Should be ‘x/y’ or ‘lat/long’

identifier: str = None

File from which to read all of the ward names

identifier2: str = None

File from which to read all of the secondary ward IDs, (Communities, Counties, Districts, UA’s etc)

is_single: bool = False

Whether or not this is the special “single” ward model

static load(model: str = '2011Data', repository: Optional[str] = None, folder: Optional[str] = None, description: str = 'description.json', filename: Optional[str] = None)[source]

Load the parameters associated with the passed model. This will look for the parameters specified in the json file called f”{repository}/{folder}/{model}/{description}”

By default this will load the 2011Data parameters from $HOME/GitHub/model_data/2011Data/description.json

Alternatively you can provide the full path to the description json file usng the ‘filename’ argument. All files within this description will be searched for using the directory that contains that file as a base

Parameters
  • model (str) – The name of the model data to load. This is the name that will be searched for in the METAWARDSDATA model_data directory

  • repository (str) – The location of the cloned METAWARDSDATA repository

  • folder (str) – The name of the folder within the METAWARDSDATA repository that contains the model data

  • filename (str) – The name of the file to load the model data from - this directly loads this file without searching through the METAWARDSDATA repository

Returns

input_files – The constructed and validated set of input files

Return type

InputFiles

lookup: str = None

File to look up metadata about the wards (e.g. their names)

lookup_columns: Dict[str, int] = None

Which columns in this file have the data

model_name()[source]

Return the name of this model

model_path()[source]

Return the path to the directory containing this model

model_version()[source]

Return the version of the data in this model

nodes_to_track: str = None

File from which to read the list of nodes to track

play: str = None

File from which to read the play matrix of links

play_size: str = None

File from which to read the size of the population in the play file

position: str = None

File from which to read the positions (locations) of the wards (the centre of the bounding boxes)

seed: str = None

File from which to read the values to seed the wards

uv: str = None

UV file

wards_data: str = None

The json file containing the wards data if this is a ward_json

weekend: str = None

File from which to read the weekend matrix of links

work: str = None

File from which to read the work matrix of links

work_size: str = None

File from which to read the size of the population in the work file

class metawards.Interpret[source]

This is a static class that provides some routines for interpreting values from inputs (normally strings). This is used heavily by code that reads values from the user or from files

static boolean(s: any, rng=None) bool[source]

Interpret and return a boolean (True or False) using the passed random number generator if this is a request for a random boolean

static date(s: any, allow_fuzzy: bool = True)[source]

Return a Python datetime.date object from the passed ‘s’, allowing fuzzy dates if ‘allow_fuzzy’ is true

static day(s: any, rng=None, minval: Optional[int] = None, maxval: Optional[int] = None) int[source]

Return a day number (integer) from the passed ‘s’. This is a shorthand for ‘integer’, but may take on more meaning if the day needs to be more specialised

static day_or_date(s: any, rng=None, minval: Optional[int] = None, maxval: Optional[int] = None, allow_fuzzy: bool = True)[source]

Convenience function that matches a day or a date from the passed ‘s’

static integer(s: any, rng=None, minval: Optional[int] = None, maxval: Optional[int] = None) int[source]

Interpret and return an integer from ‘s’, using the passed random number generator if this is a request for a random integer, and within the specified bounds of ‘minval’ and ‘maxval’ if needed.

This can interpret ‘s’ as an expression, e.g. “6 / 3” etc.

static list(s: any)[source]

Interpret and return a list from the passed string ‘s’

static number(s: any, rng=None, minval: Optional[Union[int, float]] = None, maxval: Optional[Union[int, float]] = None) Union[int, float][source]

Interpret and return a number (integer or float) using the passed random number generator if this is a request for a random number, and within the specified bound of ‘minval’ and ‘maxval’ is needed

This can interpret ‘s’ as an expression, e.g. “2.4 * 3.6” etc.

static random_integer(s: Optional[str] = None, rng=None, minval: Optional[int] = None, maxval: Optional[int] = None) int[source]

Interpret a random integer from the passed string, specifying the random number generator to use, and optionally adding additional constraints on the minimum and maximum values

static random_number(s: Optional[str] = None, rng=None, minval: Optional[float] = None, maxval: Optional[float] = None) float[source]

Interpret a random number (float) from the passed string, specifying the random number generator to use, and optionally adding additional constraints on the minimum and maximum values

static string(s: any) str[source]

Interpret and return a string from ‘s’

This is a link between nodes in the network

__eq__(other)

Return self==value.

__hash__ = None
__init__(ifrom: Optional[int] = None, ito: Optional[int] = None, weight: Optional[float] = None, suscept: Optional[float] = None, distance: Optional[float] = None) None
__repr__()

Return repr(self).

distance: float = None

The distance between the two wards connected by this link

ifrom: int = None

Index of the origin node (ward)

ito: int = None

Index of the destination node (ward)

suscept: float = None

Number of susceptibles in the case of the work matrix. Used to save the weight of the play matrix

weight: float = None

Weight of the link, used to save the original number of susceptibles in the work matrix

This is a container class for Links. This uses arrays to store a list of Link objects as a “struct of arrays”. This should improve speed of loading and access.

__getitem__(i: int)[source]

Return the link at index ‘i’. Note that this is a deep copy of the link. Changing the link will not change the data in this container. To update the data in this container you need to use __setitem__, e.g. via the index operator (see __setitem__)

__init__(N: int = 0)[source]

Create a container for up to “N” Links

__len__()[source]

Return the number of links in this container

__setitem__(i: int, value: metawards._link.Link)[source]

Set the item as index ‘i’ equal to ‘value’. This deep-copies ‘value’ into this container

assert_not_null()[source]

Assert that this collection of links is not null

assert_valid_index(i)[source]

Assert that the passed index ‘i’ is valid for this collection. This will return the index with Python reverse indexing, so that “-1” refers to the last link in the collection

copy()[source]

Return a copy of these links, using a shallow copy for things that stay the same (e.g. ifrom, ito, distance) and a deep copy for things that are variable (e.g. weight and suscept)

distance

The distance between the two wards of this link

Return the index of the link from ward ifrom to ward ito. This raises an exception if there is no such link

ifrom

The index of the home ward

ito

The index of the commute ward

population() int[source]

Return the population of these links

resize(N: int)[source]

Resize this container to hold ‘N’ links. This will expand the container if ‘N’ is greater than len(self), or will contract the container (deleting excess links) if ‘N’ is less than len(self). This function is called typically when you pre-allocate a large Links container, and then want to reduce the size to fit the number of loaded links

scale_susceptibles(ratio: Optional[any] = None)[source]

Scale the number of susceptibles in these Links by the passed scale ratio. This can be a value, e.g. ratio = 2.0 will scale the total number of susceptibles by 2.0. This can also be lists of values, where ward[i] will be scaled by ratio[i]. They can also be dictionaries, e.g. ward[i] scaled by ratio[i]

Parameters

ratio (None, float, list or dict) – The amount by which to scale the total population of susceptibles - evenly scales the work and play populations

Returns

Return type

None

suscept

The number of susceptible workers in this link

weight

The number of workers in this link, or the weight if this is a player link

class metawards.Network(name: Optional[str] = None, nodes: Optional[metawards._nodes.Nodes] = None, links: Optional[metawards._links.Links] = None, play: Optional[metawards._links.Links] = None, nnodes: int = 0, nlinks: int = 0, nplay: int = 0, max_nodes: int = 16384, max_links: int = 4194304, info: metawards._wardinfo.WardInfos = WardInfos(wards=[], _index=None), to_seed: Optional[List[int]] = None, params: Optional[metawards._parameters.Parameters] = None, work_population: Optional[int] = None, play_population: Optional[int] = None)[source]

This class represents a network of wards. The network comprises nodes (representing wards), connected with links which represent work (predictable movements) and play (unpredictable movements)

__eq__(other)

Return self==value.

__hash__ = None
__init__(name: Optional[str] = None, nodes: Optional[metawards._nodes.Nodes] = None, links: Optional[metawards._links.Links] = None, play: Optional[metawards._links.Links] = None, nnodes: int = 0, nlinks: int = 0, nplay: int = 0, max_nodes: int = 16384, max_links: int = 4194304, info: metawards._wardinfo.WardInfos = WardInfos(wards=[], _index=None), to_seed: Optional[List[int]] = None, params: Optional[metawards._parameters.Parameters] = None, work_population: Optional[int] = None, play_population: Optional[int] = None) None
__repr__()

Return repr(self).

assert_sane(profiler: None)[source]

Assert that this network is sane. This checks that the network is laid out correctly in memory and that it doesn’t have anything unexpected. Checking here will prevent us from having to check every time the network is accessed

static build(params: metawards._parameters.Parameters, population: Optional[metawards._population.Population] = None, max_nodes: int = 16384, max_links: int = 4194304, nthreads: int = 1, profiler=None)[source]

Builds and returns a new Network that is described by the passed parameters.

The network is built in allocated memory, so you need to specify the maximum possible number of nodes and links. The memory buffers will be shrunk back after building.

copy()[source]

Return a copy of this Network. Use this to hold a copy of the network that you can use to reset between runs

static from_wards(wards, params: Optional[metawards._parameters.Parameters] = None, disease: Optional[metawards._disease.Disease] = None, profiler=None, nthreads: int = 1)[source]

Construct a Network from the passed Wards object(e.g. after editing, or restoring from JSON

get_index(id: metawards._wardid.WardID) Tuple[metawards._network.PersonType, int, int][source]

Return the index of the Node or Link(s) that corresponds to the passed WardID.

This returns a tuple of three values;

(PersonType, start_idx, end_idx)

If this is a worker, then it will either return the index of the Link for a specific work-link connection, or the range of indicies for all of the work links to this ward, so

(PersonType.WORKER, link_idx, link_idx+!) for a single link, or

(PersonType.WORKER, link.begin_to, link.end_to) for all links

If this is a player, then it will return the ID of the Node (which is the index of the Node in Nodes), and so

(PersonType.PLAYER, node_index, node_index+1)

This raises a KeyError if there is no ward or ward-link that matches the WardID

get_min_max_distances(nthreads: int = 1, profiler=None)[source]

Calculate and return the minimum and maximum distances between nodes in the network

get_node_index(index: Union[str, int])[source]

Return the index of the node in this network that matches ‘index’. This could be an integer, in which case this will directly look up the index of the node in the Nodes, or else it could be a string, in which case the WardInfo will be used to identify the node and look up the index from there.

get_work_index()[source]

Return the mapping from the index in this sub-networks work matrix to the mapping in the overall network’s work matrix

has_different_work_matrix()[source]

Return whether or not the sub-network work matrix is different to that of the overall network

info: metawards._wardinfo.WardInfos = WardInfos(wards=[], _index=None)

The metadata for all of the wards

initialise_infections(nthreads: int = 1)[source]

Initialise and return the space that will be used to track infections

The links between nodes (work)

The maximum allowable number of links in the network

max_nodes: int = 16384

The maximum allowable number of nodes in the network

move_from_play_to_work(nthreads: int = 1, profiler=None)[source]

Move the population from play to work

name: str = None

The name of the Network. This equals the name of the demographic if this is a multi-demographic sub-network

The number of links in the network

nnodes: int = 0

The number of nodes in the network

nodes: metawards._nodes.Nodes = None

The list of nodes (wards) in the network

nplay: int = 0

The number of play links in the network

num_demographics() int[source]

Return the number of demographics (always 1 for a Network). This function is added so that a single Network has the same functions as a multi-demographics Networks

params: metawards._parameters.Parameters = None

The parameters used to generate this network

play: metawards._links.Links = None

The links between nodes (play)

play_population: int = None

The number of players

property population: int

Return the total population in the network

recalculate_denominators(nthreads: int = 1, profiler=None)[source]

Recalculate the denominators used in the calculation. This should be called after you have changed the population of the network, e.g. during a move function

rescale_play_matrix(nthreads: int = 1, profiler=None)[source]

Rescale the play matrix

reset_everything(nthreads: int = 1, profiler=None)[source]

Resets the network ready for a new run of the model

run(population: metawards._population.Population, output_dir: metawards._outputfiles.OutputFiles, seed: Optional[int] = None, nsteps: Optional[int] = None, nthreads: Optional[int] = None, iterator=None, extractor=None, mixer=None, mover=None, profiler=None) metawards._population.Population[source]

Run the model simulation for the passed population. The random number seed is given in ‘seed’. If this is None, then a random seed is used.

All output files are written to ‘output_dir’

The simulation will continue until the infection has died out or until ‘nsteps’ has passed(keep as ‘None’ to prevent exiting early).

Parameters - ——— population: Population

The initial population at the start of the model outbreak. This is also used to set start date and day of the model outbreak

output_dir: OutputFiles

The directory to write all of the output into

seed: int

The random number seed used for this model run. If this is None then a very random random number seed will be used

nsteps: int

The maximum number of steps to run in the outbreak. If None then run until the outbreak has finished

profiler: Profiler

The profiler to use - a new one is created if one isn’t passed

nthreads: int

Number of threads over which to parallelise this model run

iterator: function

Function that is called at each iteration to get the functions that are used to advance the model

extractor: function

Function that is called at each iteration to get the functions that are used to extract data for analysis or writing to files

mixer: function

Function that is used to mix demographic data. Not used by a single Network(used by Networks)

mover: function

Function that is used to move the population between different demographics. Not used by a single Network(used by Networks)

scale_susceptibles(ratio: Optional[any] = None, work_ratio: Optional[any] = None, play_ratio: Optional[any] = None)[source]

Scale the number of susceptibles in this Network by the passed scale ratios. These can be values, e.g. ratio = 2.0 will scale the total number of susceptibles in each ward by 2.0. They can also be lists of values, where ward[i] will be scaled by ratio[i]. They can also be dictionaries, e.g. ward[i] scaled by ratio[i]

Parameters
  • ratio (None, float, list or dict) – The amount by which to scale the total population of susceptibles - evenly scales the work and play populations

  • work_ratio (None, float, list or dict) – Scale only the work population of susceptibles

  • play_ratio (None, float, list or dict) – Scale only the play population of susceptibles

Returns

Return type

None

static single(params: metawards._parameters.Parameters, population: metawards._population.Population, profiler=None)[source]

Builds and returns a new Network that contains just a single ward, in which ‘population’ individuals are resident.

specialise(demographic, profiler=None, nthreads: int = 1)[source]

Return a copy of this network that has been specialised for the passed demographic. The returned network will contain only members of that demographic, with the parameters of the network adjusted according to the rules of that demographic

Parameters

demographic (Demographic) – The demographic with which to specialise

Returns

network – The specialised network

Return type

Network

to_seed: List[int] = None

To seed provides additional seeding information

to_wards(profiler=None, nthreads: int = 1)[source]

Return the ward-level data in this network converted to a Wards object. This supports editing and save/restore to JSON

update(params: metawards._parameters.Parameters, demographics=None, population=None, nthreads: int = 1, profiler=None)[source]

Update this network with a new set of parameters ( and optionally demographics).

This is used to update the parameters for the network for a new run. The network will be reset and ready for a new run.

Parameters
  • params (Parameters) – The new parameters with which to update this Network

  • demographics (Demographics) – The new demographics with which to update this Network. Note that this will return a Network object that contains the specilisation of this Network

  • nthreads (int) – Number of threads over which to parallelise this update

  • profiler (Profiler) – The profiler used to profile this update

Returns

network – Either this Network after it has been updated, or the resulting Networks from specialising this Network using Demographics

Return type

Network or Networks

work_population: int = None

The number of workers

class metawards.Networks(overall: Optional[metawards._network.Network] = None, subnets: List[metawards._network.Network] = <factory>, demographics: Optional[metawards._demographics.Demographics] = None)[source]

This is a combination of Network objects which together represent an entire diverse population. Each individual Network is used to model the disease outbreak within a single demographic of the population. Multiple demographics are modelled by combining multiple networks. Special merge functions enable joint FOIs to be calculated, through which an outbreak in one network can cross-infect a demographic in another network.

The Networks can be very independent, and don’t necessarily need to have the same links. However, it is assumed (and checked) that each network will have the same nodes.

__eq__(other)

Return self==value.

__hash__ = None
__init__(overall: Optional[metawards._network.Network] = None, subnets: List[metawards._network.Network] = <factory>, demographics: Optional[metawards._demographics.Demographics] = None) None
__repr__()

Return repr(self).

aggregate(profiler=None, nthreads: int = 1)[source]

Aggregate all of the sub-network population infection data so that this is available in the overall network

assert_sane(profiler: None)[source]

Assert that the networks is sane. This checks that the networks and all of the demographic sub-networks are laid out correctly in memory and that they don’t have anything unexpected. Checking here will prevent us from having to check every time the networks are accessed

static build(network: metawards._network.Network, demographics: metawards._demographics.Demographics, profiler=None, nthreads: int = 1)[source]

Build the set of networks that will model the passed demographics based on the overall population model in the passed network

Parameters
  • network (Network) – The overall population model - this contains the base parameters, wards, work and play links that define the model outbreak

  • demographics (Demographics) – Information about each of the demographics to be modelled. Note that the sum of the “work” and “play” populations across all demographics must be 1.0 in all wards in the model

  • profiler (Profiler) – Optional profiler used to profile this build

  • nthreads (int) – Number of threads over which to distribute the work

Returns

networks – The set of Networks that represent the model run over the full set of different demographics

Return type

Networks

copy()[source]

Return a copy of this Networks. Use this to hold a copy of the networks that you can use to reset between runs

demographics: metawards._demographics.Demographics = None

Metadata about each of the demographics being modelled. This is None if only a single demographic is modelled

initialise_infections(nthreads: int = 1)[source]

Initialise and return the space that will be used to track infections

move_from_play_to_work(nthreads: int = 1, profiler=None)[source]

Move the population from play to work

num_demographics() int[source]

Return the number of demographics

overall: metawards._network.Network = None

The overall Network, which contains a combination of all of the sub-networks. This is used for summary analysis and also as a means of merging and distributing data between sub-networks

property params: int

The overall parameters that are then specialised for the different demographics. Note that this returns a copy, so changing this will not change any parameters in the networks

rescale_play_matrix(nthreads: int = 1, profiler=None)[source]

Rescale the play matrix

reset_everything(nthreads: int = 1, profiler=None)[source]

Resets the networks ready for a new run of the model

run(population: metawards._population.Population, output_dir: metawards._outputfiles.OutputFiles, seed: Optional[int] = None, nsteps: Optional[int] = None, nthreads: Optional[int] = None, iterator=None, extractor=None, mover=None, mixer=None, profiler=None) metawards._population.Population[source]

Run the model simulation for the passed population. The random number seed is given in ‘seed’. If this is None, then a random seed is used.

All output files are written to ‘output_dir’

The simulation will continue until the infection has died out or until ‘nsteps’ has passed (keep as ‘None’ to prevent exiting early).

Parameters
  • population (Population) – The initial population at the start of the model outbreak. This is also used to set start date and day of the model outbreak

  • output_dir (OutputFiles) – The directory to write all of the output into

  • seed (int) – The random number seed used for this model run. If this is None then a very random random number seed will be used

  • nsteps (int) – The maximum number of steps to run in the outbreak. If None then run until the outbreak has finished

  • profiler (Profiler) – The profiler to use - a new one is created if one isn’t passed

  • nthreads (int) – Number of threads over which to parallelise this model run

  • iterator (function) – Function that is called at each iteration to get the functions that are used to advance the model

  • extractor (function) – Function that is called at each iteration to get the functions that are used to extract data for analysis or writing to files

  • mixer (function) – Function that is called to mix the data calculated for each of the sub-networks for the different demographics and merge it together so that this is shared

  • mover (function) – Function that is called to move the population between different demographics

Returns

population – The final population at the end of the run

Return type

Population

subnets: List[metawards._network.Network]

The list of Networks, one for each demographic, ordered in the same order as the “Demographics” object. This is empty if only a single demographic is modelled

update(params: metawards._parameters.Parameters, demographics=None, population=None, nthreads: int = 1, profiler=None)[source]

Update this network with a new set of parameters (and optionally demographics).

This is used to update the parameters for the network for a new run. The network will be reset and ready for a new run.

Parameters
  • params (Parameters) – The new parameters with which to update this Network

  • demographics (Demographics) – The new demographics with which to update this Network. Note that this will return a Network object that contains the specilisation of this Network

  • nthreads (int) – Number of threads over which to parallelise this update

  • profiler (Profiler) – The profiler used to profile this update

Returns

network – Either this Network after it has been updated, or the resulting Networks from specialising this Network using Demographics

Return type

Network or Networks

class metawards.Node(label: Optional[int] = None, begin_to: Optional[int] = None, end_to: Optional[int] = None, self_w: Optional[int] = None, begin_p: Optional[int] = None, end_p: Optional[int] = None, self_p: Optional[int] = None, day_foi: float = 0.0, night_foi: float = 0.0, weekend_foi: float = 0.0, play_suscept: float = 0.0, save_play_suscept: float = 0.0, denominator_n: float = 0.0, denominator_d: float = 0.0, denominator_p: float = 0.0, denominator_pd: float = 0.0, x: float = 0.0, y: float = 0.0, scale_uv: float = 1.0, cutoff: float = 99999.99, bg_foi: float = 0.0)[source]

This class represents an electoral ward (node) in the network

__eq__(other)

Return self==value.

__hash__ = None
__init__(label: Optional[int] = None, begin_to: Optional[int] = None, end_to: Optional[int] = None, self_w: Optional[int] = None, begin_p: Optional[int] = None, end_p: Optional[int] = None, self_p: Optional[int] = None, day_foi: float = 0.0, night_foi: float = 0.0, weekend_foi: float = 0.0, play_suscept: float = 0.0, save_play_suscept: float = 0.0, denominator_n: float = 0.0, denominator_d: float = 0.0, denominator_p: float = 0.0, denominator_pd: float = 0.0, x: float = 0.0, y: float = 0.0, scale_uv: float = 1.0, cutoff: float = 99999.99, bg_foi: float = 0.0) None
__repr__()

Return repr(self).

begin_p: int = None

The index (int) of the first link for this node in the network play Links list (play)

begin_to: int = None

The index (int) of the first link for this node in the network Links list

bg_foi: float = 0.0

Per-ward background FOI (starting value for FOI calculations)

cutoff: float = 99999.99

The per-ward cutoff (restrict movement to below this distance in km)

end_p: int = None

The number (int) of links for this node in the Links play list

end_to: int = None

The number (int) of links for this node in the Links list

get_custom(key: str, default: float = 0.0) float[source]

Return the value of the custom parameter at key ‘key’, returning ‘default’ if this doesn’t exist

label: int = None

The node’s label (int). This is the index of the node, which must run from 1 up to len(nodes). A value of -1 implies a null node

play_suscept: float = 0.0

The number of susceptible players in this ward

scale_uv: float = 1.0

The per-ward scale_uv (amount to scale up or down the FOI

set_custom(key: str, value: float) None[source]

Set the value of the custom parameter at key ‘key’ to ‘value’. Note that this must be a floating point value, or something that can be converted to a float

x: float = 0.0

x coordinate of the ward (location)

y: float = 0.0

y coordinate of the ward (location)

class metawards.Nodes(N: int = 0)[source]

This is a container class for Nodes. This uses Python arrays to store a list of Node objects as a “struct of arrays”. This should improve speed of loading and access.

__getitem__(i: int)[source]

Return the node at index ‘i’. Note that this is a deep copy of the node. Changing the node will not change the data in this container. To update the data in this container you need to use __setitem__, e.g. via the index operator (see __setitem__)

__init__(N: int = 0)[source]

Create a container for up to “N” nodes

__len__()[source]

Return the number of nodes in this container

__setitem__(i: int, value: metawards._node.Node)[source]

Set the item as index ‘i’ equal to ‘value’. This deep-copies ‘value’ into this container

assert_not_null()[source]

Assert that this collection of nodes is not null

assert_valid_index(i)[source]

Assert that the passed index ‘i’ is valid for this collection. This will return the index with Python reverse indexing, so that “-1” refers to the last node in the collection

begin_p

The start index for play links

begin_to

The start index for work links

bg_foi

per-ward bg_foi value - this the starting FOI for the ward in the FOI calculation. This defaults to 0.0, but can be set to larger values if you want the ward to have a background FOI that drives infections

coordinates

Coordinate system used (x/y for X,Y in km, lat/long for latitude and longitude)

copy()[source]

Return a copy of this network, using deep copies for things which are variable, but shallow copies for things which should stay the same (e.g. x and y). This copy assumes that you are not changing the actual links between nodes, e.g. it shallow-copies label, begin_to, end_to, self_w, begin_p, end_p and self_p. If you are changing the links then you will need to recreate these arrays.

cutoff

per-ward cutoff value - default to a large number that is greater than any distance between points on Earth (distance in k)

day_foi

Dayime force of infection for each ward

day_inf_prob

Daytime infection probability for each ward

denominator_d

Day time work denominator for each ward

denominator_n

Night time work denominator for each ward

denominator_p

Night time play denominator for each ward

denominator_pd

Day time play denominator for each ward

end_p

The end index for play links

end_to

The end index for work links

get_custom(key: str, default: float = 0.0) array[float][source]

Return the array of custom parameters for the key called ‘key’. If these don’t exist then create them with the specified default value. Note that this returns a shallow copy of the array, meaning that you can modify this directly and it will change the value of the nodes. This is identical to the behaviour of the other arrays in this Nodes object (it is optimised for speed, not safety)

get_index(i)[source]

Return the mapped index for the ith node. This will raise an IndexError if this is an invalid index. If not, it will map a negative index into a canonical positive index

label

ID number for each node. This should equal the node index

night_foi

Nighttime force of infection for each ward

night_inf_prob

Nighttime infection probability for each ward

play_suscept

Number of susceptible players in each ward

population() int[source]

Return the total population of the nodes

Returns

Total population

Return type

int

resize(N: int)[source]

Resize this container to hold ‘N’ nodes. This will expand the container if ‘N’ is greater than len(self), or will contract the container (deleting excess nodes) if ‘N’ is less than len(self). This function is called typically when you pre-allocate a large Nodes container, and then want to reduce the size to fit the number of loaded nodes

save_play_suscept

Saved value of the number of susceptible players

scale_susceptibles(ratio: Optional[any] = None, work_ratio: Optional[any] = None, play_ratio: Optional[any] = None)[source]

Scale the number of susceptibles in these Nodes by the passed scale ratios. These can be values, e.g. ratio = 2.0 will scale the total number of susceptibles in each ward by 2.0. They can also be lists of values, where ward[i] will be scaled by ratio[i]. They can also be dictionaries, e.g. ward[i] scaled by ratio[i]

Parameters
  • ratio (None, float, list or dict) – The amount by which to scale the total population of susceptibles - evenly scales the work and play populations

  • work_ratio (None, float, list or dict) – Scale only the work population of susceptibles

  • play_ratio (None, float, list or dict) – Scale only the play population of susceptibles

Returns

Return type

None

scale_uv

per-ward UV scaling parameter

self_p

The index of the home player play link

self_w

The index of the home commuter work link

set_custom(key: str, value: _Union[float, array[float]], index: int = None) None[source]

Set the custom parameters for the key called ‘key’ to ‘value’. If the index is set then this just sets the value for that index. You pass in either an array of floats (thus setting all node parameters, or a single float, which is for the single ward, or will set all wards to have that value.

Note that custom parameters can only be floats!

x

X-coordinate of the center of each ward

y

Y-coordinate of the center of each ward

class metawards.OutputFiles(output_dir: str = 'output', check_empty: bool = True, force_empty: bool = False, prompt=<built-in function input>, auto_bzip: bool = False)[source]

This is a class that manages all of the output files that are written to during a model outbreak. This object is used to hold the ‘FILE’ objects for open files, and will ensure that these files are closed and written to disk as needed. It will also ensure that files are written to the correct output directory, and that they are only opened when they are needed (e.g. only the first call to open the file will actually open it - subsequent calls will return the already-open file handler)

Examples

>>> output = OutputFiles(output_dir="output", check_empty=True)
>>> FILE = output.open("output.txt")
>>> FILE.write("some output\n")
>>> FILE = output.open("something.csv.bz2", auto_bzip=True)
>>> FILE.write("something,else,is,here\n")
>>> output.flush()
>>> FILE = output.open("output.txt")
>>> FILE.write("some more output\n")
>>> output.close()

Note that you can also use OutputFiles in a contexthandler, to ensure that all output files are automatically closed, e.g.

>>> with OutputFiles(output_dir="output") as output:
>>>     FILE = output.open("output.txt")
>>>     FILE.write("something\n")
__init__(output_dir: str = 'output', check_empty: bool = True, force_empty: bool = False, prompt=<built-in function input>, auto_bzip: bool = False)[source]

Construct a set of OutputFiles. These will all be written to ‘output_dir’.

Parameters
  • output_dir (str) – The directory in which to create all of the output files. This directory will be created automatically if it doesn’t exist

  • check_empty (bool) – Whether or not to check if the directory is empty before continuing. If the directory is not empty, then the user will be prompted to make a decision to either keep going, choose a different directory, remove existing output or exit

  • force_empty (bool) – Force the output directory to be empty. BE CAREFUL as this will remove all files in that directory! There are checks to stop you doing something silly, but these are not fool-proof. The user will be prompted to confirm that the files should be removed

  • prompt – This is the function that should be called to prompt the user for input, e.g. to confirm whether or not files should be deleted. This defaults to input. Set this to None if you really want MetaWards to remove files silently (e.g. useful if you are running batch jobs on a cluster and you really know what you are doing)

  • auto_bzip (bool) – The default flag for auto_bzip when opening files. If this is true then all files will be automatically bzipped (compressed) as they are written, unless the code opening the file has explicitly asked otherwise

auto_bzip()[source]

Return whether the default is to automatically bzip2 files

close()[source]

Close all of the files and this directory

flush()[source]

Flush the contents of all files to disk

get_filename(filename)[source]

Return the full expanded filename for ‘filename’

get_path()[source]

Return the full expanded path to this directory

is_closed()[source]

Return whether or not the output files are closed

is_database(filename)[source]

Return whether or not ‘filename’ is an open database

is_open()[source]

Return whether or not the output files are open

open(filename: str, auto_bzip=None, mode='t', headers=None, sep=' ')[source]

Open the file called ‘filename’ in the output directory, returning a handle to that file. Note that this will open the file once, and will return the already-open file handle on all subsequent calls.

Parameters
  • filename (str) – The name of the file to open. This must be relative to the output directory, and within that directory. It is an error to try to open a file that is not contained within this directory.

  • auto_bzip (bool) – Whether or not to open the file in auto-bzip (compression) mode. If this is True then the file will be automatically compressed as it is written. The filename will have ‘.bz2’ automatically appended so that this is clear. If this is False then the file will be written uncompressed. If ‘None’ is passed (the default) then the value of auto_bzip that was passed to the constructor of this OutputFiles will be used. Note that this flag is ignored if the file is already open.

  • mode (str) – The mode of opening the file, e.g. ‘t’ for text mode, and ‘b’ for binary mode. The default is text mode

  • headers (list[str] or plain str or function) – The headers to add to the top of the file, e.g. if it will contain column data. This will be written to the first line when the file is opened. If a list is passed, then this will be written joined together using ‘sep’. If a plain string is passed then this will be written. If this is a function then this function will be called with “FILE” as the argument. If nothing is passed then no headers will be written.

  • sep (str) – The separator used for the headers (e.g. ” ” or “,” are good choices). By default things are space-separated

Returns

The handle to the open file

Return type

file

open_db(filename: str, auto_bzip=None, initialise=None)[source]
Open up a SQLite3 database connection to a file called

‘filename’ in the output directory, returning the SQLite3 connection to the database. Note that this will open the database one, and will return the already-made connection on all subsequence calls.

filename: str

The name of the file containing the database to open. This must be relative to the output directory, and within that directory. It is an error to try to open a database that is not contained in this directory.

auto_bzip: bool

Whether or not to automatically compress the file using bzip2 when it is closed. The filename will automatically have ‘.bz2’ appended so that this is clear. If ‘None’ is passed (the default) then the value of ‘auto_bzip’ that was passed to the constructor of this OutputFiles will be used. Note that this flag is ignored if the database is already open

initialise: function

A function that is called to initialise the database the first time that it is opened. The function is called with the argument “CONN” (representing the sqlite3 database connection). Use this to create the tables that you need

open_subdir(dirname)[source]

Create and open a sub-directory in this OutputFiles called ‘dirname’. This will inherit all properties, e.g. check_empty, auto_bzip etc from this OutputFiles

Parameters

dirname (str) – The name of the subdirectory to open

Returns

subdir – The open subdirectory

Return type

OutputFiles

output_dir()[source]

Return the absolute path of the directory to which the output files will be written

static remove(path, prompt=<built-in function input>)[source]

Remove the passed filename or directory

Parameters
  • path (str) – The path to the file or directory or remove

  • prompt – Prompt to use to ask the user - if None then no checks!

class metawards.Parameters(input_files: Optional[metawards._inputfiles.InputFiles] = None, disease_params: Optional[metawards._disease.Disease] = None, additional_seeds: Optional[List[str]] = None, length_day: float = 0.7, static_play_at_home: float = 0.0, dyn_play_at_home: float = 0.0, dyn_dist_cutoff: float = 10000000.0, play_to_work: float = 0.0, work_to_play: float = 0.0, daily_imports: float = 0.0, ward_seed_index: Optional[int] = None, initial_inf: int = 5, stage_0: str = 'R', UV: float = 0.0, UV_max: Optional[datetime.date] = None, scale_uv: float = 1.0, bg_foi: float = 0.0, user_params: Dict[str, float] = <factory>, adjustments: Optional[List[metawards._variableset.VariableSet]] = None, _name: Optional[str] = None, _version: Optional[str] = None, _authors: Optional[str] = None, _contacts: Optional[str] = None, _references: Optional[str] = None, _filename: Optional[str] = None, _repository: Optional[str] = None, _repository_version: Optional[str] = None, _repository_branch: Optional[str] = None, _repository_dir: Optional[str] = None)[source]

The full set of Parameters that are used to control the model outbreak over a Network. The combination of a Network and a Parameters defines the model outbreak.

Load the Parameters using the Parameters.load function, and then add extra data using the various “set” and “add” functions, e.g.

Examples

>>> params = Parameters.load("march29")
>>> params.set_disease("ncov")
>>> params.set_input_files("2011Data")
>>> params.add_seeds("ExtraSeedsBrighton.dat")
UV: float = 0.0

Seasonality parameter

UV_max: datetime.date = None

Date when transmission should be at a maximum

__eq__(other)

Return self==value.

__getitem__(demographic: str)[source]

Return the parameters that should be used for the demographic subnetwork called ‘demographic’. If these have not been set specifically then the parameters for the overall network are used

__hash__ = None
__init__(input_files: Optional[metawards._inputfiles.InputFiles] = None, disease_params: Optional[metawards._disease.Disease] = None, additional_seeds: Optional[List[str]] = None, length_day: float = 0.7, static_play_at_home: float = 0.0, dyn_play_at_home: float = 0.0, dyn_dist_cutoff: float = 10000000.0, play_to_work: float = 0.0, work_to_play: float = 0.0, daily_imports: float = 0.0, ward_seed_index: Optional[int] = None, initial_inf: int = 5, stage_0: str = 'R', UV: float = 0.0, UV_max: Optional[datetime.date] = None, scale_uv: float = 1.0, bg_foi: float = 0.0, user_params: Dict[str, float] = <factory>, adjustments: Optional[List[metawards._variableset.VariableSet]] = None, _name: Optional[str] = None, _version: Optional[str] = None, _authors: Optional[str] = None, _contacts: Optional[str] = None, _references: Optional[str] = None, _filename: Optional[str] = None, _repository: Optional[str] = None, _repository_version: Optional[str] = None, _repository_branch: Optional[str] = None, _repository_dir: Optional[str] = None) None
__repr__()

Return repr(self).

__str__()[source]

Return str(self).

add_seeds(filename: str)[source]

Add an ‘additional seeds’ file that can be used to seed wards with new infections at different times and locations. Several additional_seed files can be added

Parameters

filename (str) – Name of the file containing the additional seeds

additional_seeds: List[str] = None

The set of files that contain additional seeds that seed the outbreak during the model run

adjustments: List[metawards._variableset.VariableSet] = None

All of the VariableSet adjustments that have been applied to these parameters

bg_foi: float = 0.0

The global background force of infection (FOI). This is combined with the per-ward level bg_foi to give a single value

copy(include_subparams: bool = False)[source]

Return a safe copy of these parameters, which does not include any subnetwork parameters if ‘include_subparams’ is False

daily_imports: float = 0.0

proportion of daily imports if there are additional infections

static default()[source]

Return the default set of parameters

disease_params: metawards._disease.Disease = None

The set of parameters that define the disease

dyn_dist_cutoff: float = 10000000.0

The cutoff distance in km beyond which workers or players cannot move

static get_repository(repository: Optional[str] = None)[source]

Return the repository location and version information for the passed repository

Parameters

repository (str) – Location on the filesystem of the repository. If this is None then it will be searched for using first the environment variable METAWARDSDATA, then $HOME/GitHub/MetaWardsData, then ./METAWARDSDATA

Returns

(repository, version) – A tuple of the location on disk of the repository, plus the version information (git ID etc)

Return type

tuple

initial_inf: int = 5

The number of initial infections if there are daily imports

input_files: metawards._inputfiles.InputFiles = None

The set of input files that define the model Network

length_day: float = 0.7

The fraction of day considered “day” for work, e.g. 0.7 * 24 hours

static load(parameters: str = 'march29', repository: Optional[str] = None, folder: str = 'parameters', filename: Optional[str] = None)[source]

This will return a Parameters object containing all of the parameters loaded from the parameters found in file f”{repository}/{folder}/{parameters}.json”

By default this will load the march29 parameters from $HOME/GitHub/model_data/2011Data/parameters/march29.json

Alternatively, you can provide the exact path to the filename via the ‘filename’ argument

Parameters
  • parameters (str) – The name of the parameters to load. This is the name that will be searched for in the METAWARDSDATA parameters directory

  • repository (str) – The location of the cloned METAWARDSDATA repository

  • folder (str) – The name of the folder within the METAWARDSDATA repository that contains the parameters

  • filename (str) – The name of the file to load the parameters from - this directly loads this file without searching through the METAWARDSDATA repository

Returns

params – The constructed and validated parameters

Return type

Parameters

static read_variables(filename: str, line_numbers: List[int])[source]

Read in extra variable parameters from the specified line number(s) of the specified file, returning the list of the dictionaries of variables that have been read. You can then apply those variable parameters using the ‘set_variables’ function

Parameters
  • filename (str) – The file from which to read the adjustable variables

  • line_numbers (List[int]) – All of the line numbers from which to read. If this is None then all lines will be read.

Returns

variables – The VariableSets containing all of the adjustable variables

Return type

VariableSets

scale_uv: float = 1.0

The global scale_uv. This is combined with the population and per-ward level scale_uvs to give a single value

set_disease(disease: metawards._disease.Disease, silent: bool = True)[source]

“Set the disease that will be modelled

Parameters
  • disease – The disease to be modelled. If a string is passed

  • string (then the disease will be loaded using that) –

  • silent – Whether or not to suppress printing out the disease

set_input_files(input_files: metawards._inputfiles.InputFiles)[source]

Set the input files that are used to initialise the simulation

Parameters

input_files (InputFiles) – The set of input files that will be used to load the Network. If a string is passed then the InputFiles will be loaded based on that string.

set_variables(variables: metawards._variableset.VariableSet)[source]

This function sets the adjustable variable values to those specified in ‘variables’ in A COPY OF THIS PARAMETERS OBJECT. This returns the copy. It does not change this object

Parameters

variables (VariableSet) – The variables that will be adjusted before the model run. This adjusts the parameters and returns them in a deep copy

Returns

params – A copy of this set of parameters with the variables adjusted

Return type

Parameters

specialised_demographics() List[str][source]

Return the names of demographics that have specialised parameters that are different to those of the overall network

stage_0: str = 'R'

how to treat the * state (stage 0). This should be a string describing the method. Currently “R”, “E” and “disable” are supported. Not needed if the mapping is specified explicitly in the disease

user_params: Dict[str, float]

User parameters

ward_seed_index: int = None

The index of the seeding ward if there are daily imports

class metawards.Population(initial: int = 0, susceptibles: int = 0, latent: int = 0, total: int = 0, totals: Optional[Dict[str, int]] = None, other_totals: Optional[Dict[str, int]] = None, recovereds: int = 0, n_inf_wards: int = 0, scale_uv: float = 1.0, day: int = 0, date: Optional[datetime.date] = None)[source]

This class holds information about the progress of the disease through the population

__eq__(other)

Return self==value.

__hash__ = None
__init__(initial: int = 0, susceptibles: int = 0, latent: int = 0, total: int = 0, totals: Optional[Dict[str, int]] = None, other_totals: Optional[Dict[str, int]] = None, recovereds: int = 0, n_inf_wards: int = 0, scale_uv: float = 1.0, day: int = 0, date: Optional[datetime.date] = None) None
__repr__()

Return repr(self).

__str__()[source]

Return str(self).

assert_sane()[source]

Assert that this population is sane, i.e. the totals within this population and with the sub-populations all add up to the correct values

date: datetime.date = None

The date in the outbreak of this record

day: int = 0

The day in the outbreak of this record (e.g. day 0, day 10 etc.)

has_equal_SEIR(other)[source]

Return whether or not the SEIR values for this population equal ‘other’

headers()[source]

Return a list of the headers that should be used to report data from this population. This returns a list of headers, e.g. [“S”, “E”, “I”, “R”]

increment_day(ndays: int = 1) None[source]

Advance the day count by ‘ndays’ (default 1)

property infecteds: int

The number who are infected across all wards

initial: int = 0

The initial population loaded into the model

latent: int = 0

The number of latent infections (E)

n_inf_wards: int = 0

The number infected in all wards (IW)

other_totals: Dict[str, int] = None

The total number of individuals in other non-infected states (X)

property others: int

Return the number who are in the ‘other’ state, i.e. not classed as susceptible, latent, infected or recovered/removed. This is the sum of states that are set as “is_infected=False” in the disease model, e.g. V (vaccinated)

property population: int

The total population in all wards

recovereds: int = 0

The total number who are removed from the outbreak, either because they have recovered, or are otherwise no longer able to be infected (R)

scale_uv: float = 1.0

The scale_uv parameter that can be used to affect the foi calculation. A value of 1.0 means do nothing

specialise(network)[source]

Specialise this population for the passed Networks

subpops = None

The populations in each of the multi-demographic subnetworks

summary(demographics=None)[source]

Return a short summary string that is suitable to be printed out during a model run

Returns

summary – The short summary string

Return type

str

susceptibles: int = 0

The number of members who could be infected (S)

total: int = 0

The total number of infections (I)

totals: Dict[str, int] = None

The total number of infections in other infected states (X)

class metawards.Populations(_trajectory: Optional[List[metawards._population.Population]] = None)[source]

This class holds the trajectory of Population objects recorded for every step (day) of a model outbreak

__eq__(other)

Return self==value.

__getitem__(i: int)[source]

Return the ith Population in the trajectory

__hash__ = None
__init__(_trajectory: Optional[List[metawards._population.Population]] = None) None
__repr__()

Return repr(self).

__str__()[source]

Return str(self).

append(population: metawards._population.Population)[source]

Append the next step in the trajectory.

Parameters

population (Population) – The population to append to this list

strip_demographics()[source]

Remove the demographics information from this trajectory. This makes it much smaller and easier to transmit over a network

class metawards.VariableSet(variables: Optional[Dict[str, float]] = None, repeat_index: int = 1, names: Optional[List[str]] = None, values: Optional[List[float]] = None)[source]

This class holds a single set of adjustable variables that are used to adjust the variables as part of a model run

Examples

>>> v = VariableSet()
>>> v["beta[1]"] = 0.95
>>> v["beta[2]"] = 0.9
>>> print(v.fingerprint())
(beta[1]=0.95, beta[2]=0.9)[repeat 1]
>>> params = Parameters()
>>> params.set_disease("ncov")
>>> v.adjust(params)
>>> print(params.disease_params.beta[1],
>>>       params.disease_params.beta[2])
0.95 0.9
__eq__(other)[source]

Return self==value.

__hash__ = None
__init__(variables: Optional[Dict[str, float]] = None, repeat_index: int = 1, names: Optional[List[str]] = None, values: Optional[List[float]] = None)[source]

Construct a new VariableSet from the passed adjusted variable values.

Parameters
  • names (List[str]) – The list of the names of the variables to adjust

  • values (List[float]) – The values of the variables to adjust (same order as names)

  • variables (Dict[str, float]) – names and values of variables to adjust passed as a dictionary

  • repeat_index (int) – the index used to distinguish different repeats of the same VariableSet from one another

Examples

>>> v = VariableSet()
>>> v["beta[1]"] = 0.95
>>> v["beta[2]"] = 0.9
>>> print(v.fingerprint())
(beta[1]=0.95, beta[2]=0.9)[repeat 1]
__repr__()[source]

Return repr(self).

__str__()[source]

Return a printable representation of the variables to be adjusted

adjust(params)[source]

Use the variables in this set to adjust the passed parameters. Note that this directly modifies ‘params’

Parameters

params (Parameters) – The parameters whose variables will be adjusted

Returns

Return type

None

Examples

>>> v = VariableSet()
>>> v["beta[1]"] = 0.95
>>> v["beta[2]"] = 0.9
>>> print(v.fingerprint())
(beta[1]=0.95, beta[2]=0.9)[repeat 1]
>>> params = Parameters()
>>> params.set_disease("ncov")
>>> v.adjust(params)
>>> print(params.disease_params.beta[1],
>>>       params.disease_params.beta[2])
0.95 0.9
static adjustable_help()[source]

Return a string that contains some help that is useful for finding out which variables can be adjusted

static create_fingerprint(vals: List[float], index: Optional[int] = None, include_index: bool = False)[source]

Create the fingerprint for the passed values

static extract_values(fingerprint: str)[source]

Return the original values from the passed fingerprint or filename. This assumes that the fingerprint was created using the ‘fingerprint’ function, namely that any integers are actually 0.INTEGER

Parameters

fingerprint (str) – The fingerprint (or filename) to decode

Returns

(values, repeat) – The list of values of the variables and the repeat index. The repeat index is None if it wasn’t included in the fingerprint

Return type

(List[float], int)

fingerprint(include_index: bool = False)[source]

Return a fingerprint for this VariableSet. This can be used to quickly identify and distinguish the values of the variables in this set from the values in other VariableSets which have the same adjustable variables, but different parameters

Parameters

include_index (bool) – Whether or not to include the repeat_index in the fingerprint

Returns

fingerprint – The fingerprint for this VariableSet

Return type

str

static from_data(data)[source]

Build a VariableSet from the passed data dictionary (which may have been deserialised from json

static from_json(s: str)[source]

Construct and return VariableSet loaded from the passed json file

get_value(key)[source]

Return the value of ‘key’

is_empty()[source]

Return whether or not there is nothing to change

make_compatible_with(other)[source]

Return a copy of this VariableSet which has been made compatible with ‘other’. This means that it will change the same variables as ‘other’, e.g. by adding ‘None’ changes for missing variables. This will raise an error if it is not possible to make this set compatible

Parameters

other (VariableSet) – The passed VariableSet for which this should be made compatible

Returns

result – A copy of this VariableSet which is now compatible with ‘other’

Return type

VariableSet

Example

>>> v1 = VariableSet()
>>> v1["beta[1]"] = 0.9
>>> v1["beta[2]"] = 0.8
>>> v2 = VariableSet()
>>> v2["beta[1]"] = 0.6
>>> v2 = v2.make_compatible_with(v1)
>>> print(v2)
(beta[1]=0.6, beta[2]=0.8)[repeat 1]
output_dir()[source]

Return the output directory in which runs using this variable set should be placed. Normally this would be the fingerprint of the variable set, but users may prefer to specify their own naming scheme, which can be added via a design file

static read(filename: str)[source]

Read a single set of adjustable variables from the passed file. The file can either write the variables in horizontal or vertical mode, using space or comma separated values.

This is useful for when you want to set a global set of parameters at the start of a calculation and don’t want to use a large VariableSets

Parameters

filename (str) – The name of the file containing the VariableSet

Returns

variables – The VariableSet that has been read

Return type

VariableSet

repeat_index()[source]

Return the repeat index of this set. The repeat index is the ID of this set if the VariableSet is repeated. The index should range from 1 to nrepeats

Returns

index – The repeat index of this set

Return type

int

set_value(key, value)[source]

Set the value of ‘key’ to ‘value’

to_data()[source]

Return a data dictionary that can be serialised to json

to_json(filename: Optional[str] = None, indent: Optional[int] = None, auto_bzip: bool = True) str[source]

Serialise the VariableSet to JSON. This will write to a file if filename is set, otherwise it will return a JSON string.

Parameters
  • filename (str) – The name of the file to write the JSON to. The absolute path to the written file will be returned. If filename is None then this will serialise to a JSON string which will be returned.

  • indent (int) – The number of spaces of indent to use when writing the json

  • auto_bzip (bool) – Whether or not to automatically bzip2 the written json file

Returns

Returns either the absolute path to the written file, or the json-serialised string

Return type

str

variable_names()[source]

Return the names of the variables that will be adjusted by this VariableSet

Returns

names – The list of names of variables to be adjusted

Return type

List[str]

variable_values()[source]

Return the values that the variables will be adjusted to. Note that ‘None’ means that the variable won’t be adjusted from its default (original) value

Returns

values – The list of values for variables to be adjusted to

Return type

List[float]

variables()[source]

Return the variables (name and values) to be adjusted

Returns

variables – The dictionary mapping the names of the variables that with be adjusted to their desired values

Return type

Dict[str, float]

class metawards.VariableSets[source]

This class holds the collection of all VariableSet objects that contain the set of adjustable variables that are used to control a single run of the model

Examples

>>> v = VariableSets()
>>> v.append({"beta[2]": 0.95, "beta[3]": 0.9})
>>> v.append({"beta[1]": 0.86, "beta[2]": 0.89})
>>> print(v)
{(beta[2]=0.95, beta[3]=0.9)[repeat 1], (beta[1]=0.86,
beta[2]=0.89)[repeat 1]}
>>> v = v.repeat(2)
>>> print(v)
{(beta[2]=0.95, beta[3]=0.9)[repeat 1], (beta[1]=0.86,
beta[2]=0.89)[repeat 1], (beta[2]=0.95, beta[3]=0.9)[repeat 2],
(beta[1]=0.86, beta[2]=0.89)[repeat 2]}
__eq__(other)[source]

Return self==value.

__getitem__(i: int)[source]

Return the VariableSet at the specified index

__hash__ = None
__init__()[source]

Initialise an empty VariableSets object

Parameters

None

Returns

Return type

None

__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

append(variables: metawards._variableset.VariableSet)[source]

Append the passed set of variables to the set that will be used to run a model. If there are any existing VariableSet objects in this list, then the new VariableSet must adjust the same variables

Parameters

variables (VariableSet) – The VariableSet to append to this list. If you pass a dict of {str: float} values, then this will automatically be converted into a VariableSet. Note that all VariableSet objects in a VariableSets must adjust the same variables

Returns

Return type

None

static read(filename: str, line_numbers: Optional[List[int]] = None)[source]

Read and return collection of VariableSet objects from the specified line number(s) of the specified file

Parameters
  • filename (str) – The name of the file from which to read the VariableSets

  • line_numbers (List[int]) – The line numbers from the file to read. This is 0-indexed, meaning that the first line is line 0. If this is None, then all lines are read and used

Returns

variables – The collection of VariableSet objects that have been read, in the order they were read from the file

Return type

VariableSets

repeat(nrepeats: Union[List[int], int])[source]

Return a copy of this VariableSet in which all of the unique VaribleSet objects have been repeated ‘nrepeats’ times

Parameters

nrepeats (int or list[int]) – The number of repeats of the VariableSet objects to perform. If this is a list, then nrepeats[i] will be the number of times to repeat variables[i]

Returns

repeats – A new VariableSets object containing ‘nrepeats’ copies of the VariableSet objects from this set

Return type

VariableSets

set_outdir_from_number()[source]

This function resets the names of all of the output directories for each run so that they are numbered sequentially from one

set_outdir_from_uid()[source]

This function resets the names of all of the output directories for each run so that they all have a globally unique UID

class metawards.Ward(id: Optional[int] = None, name: Optional[str] = None, code: Optional[str] = None, authority: Optional[str] = None, region: Optional[str] = None, info: Optional[metawards._wardinfo.WardInfo] = None, auto_assign_players: bool = True)[source]

This class holds all of the information about a Ward. It is used to create and edit Networks

__eq__(other)[source]

Return self==value.

__hash__ = None
__imul__(scale: float) metawards._ward.Ward[source]

In-place multiply the number of workers and players by ‘scale’

__init__(id: Optional[int] = None, name: Optional[str] = None, code: Optional[str] = None, authority: Optional[str] = None, region: Optional[str] = None, info: Optional[metawards._wardinfo.WardInfo] = None, auto_assign_players: bool = True)[source]

Construct a new Ward, optionally supplying information about the ward

Parameters
  • id (int) – The identifier for the ward. This must be an integer that is greater or equal to 1. Every ward in a network must have a unique ID. Typically the IDs should be contiguous, as this ID is used as the index into the Network array

  • name (str) – The name of this ward. This can be used to find the ward.

  • code (str) – The code of this ward. This is used when wards are identified by codes, rather than names

  • authority (str) – The local authority name for this node

  • region (str) – The name of the region containing this ward

  • info (WardInfo) – The complete WardInfo used to identify this ward.

  • auto_assign_players (bool) – Whether or not to automatically ensure that all remaining player weight is assigned to players who play in their home ward

__mul__(scale: float) metawards._ward.Ward[source]

Scale the number of workers and players by ‘scale’

__repr__()[source]

Return repr(self).

__rmul__(scale: float) metawards._ward.Ward[source]

Scale the number of workers and players by ‘scale’

__str__()[source]

Return str(self).

add_player_weight(weight: float, destination: Optional[int] = None)[source]

Add the weight for players who will randomly move to the specified destination to play(or to play in the home ward if destination is not set). Note that the sum of player weights cannot be greater than 1.0.

add_workers(number: int, destination: Optional[Union[int, metawards._wardinfo.WardInfo]] = None)[source]

Add some workers to this ward, specifying their destination if they work out of ward

assert_sane()[source]

Assert that the data in this ward is sane

authority()[source]

Return the local authority of this ward

auto_assign_players() bool[source]

Return whether or not the remaining player weight is automatically added to the home-ward player weight

bg_foi() float[source]

Return the background force of infection (FOI). This is the starting value for ward FOI calculations. It defaults to 0.0. Positive values are used when you want the ward to have some background effect that drives infections independently of the number of infecteds. Negative values imply a background effect that reduces the risk of infection, regardless of the number of infecteds

code()[source]

Return the code of this ward

custom(key: str, default: float = 0.0) float[source]

Return the per-ward custom parameter at key ‘key’, returning ‘default’ if this has not been set. Note that all custom parameters are stored as floats

cutoff() float[source]

Return the cutoff parameter for this ward. This sets the maximum distance that residents (or travellers) to this ward can travel

depopulate(zero_player_weights: bool = False) metawards._ward.Ward[source]

Return a copy of this Ward with exact same details, but with zero population. If ‘zero_player_weights’ is True, then this will also zero the player weights for all connected wards

dereference(wards: Wards, _inplace: bool = False) Ward[source]

Dereference the IDs and convert those back to WardInfo objects. This is the opposite of self.resolve(wards). This will return the dereferenced ward.

static from_data(data)[source]

Return a Ward that has been created from the passed dictionary (e.g. which has been deserialised from JSON)

static from_json(s: str)[source]

Return the Ward constructed from the passed json. This will either load from a passed json string, or from json loaded from the passed file

get_player_lists(no_auto_assign: bool = False)[source]

Return a pair of arrays, containing the destination wards and player weights for this ward.

If ‘no_auto_assign’ is set then do not include any auto-assigned weights. This normally should be false, as it is only used when serialising

get_players(destination: Optional[int] = None)[source]

Return the fraction of players who will play in the specified destination ward (or who play in their home ward if destination is not set)

get_worker_lists()[source]

Return a pair of arrays, containing the destination wards and worker populations for this ward

get_workers(destination: Optional[int] = None)[source]

Return the number of workers who commute to the specified destination ward (or who commute to their home ward if destination is not set)

id()[source]

Return the ID of this ward

info()[source]

Return (a copy of) the WardInfo containing all ward identifying metadata

is_resolved()[source]

Return whether or not any of the worker or player links in this ward are unresolved, or whether the ID of this ward is None

merge(other) None[source]

Merge in the data from ‘other’ into this Ward. The ‘info’ and the ID numbers must match (or be None).

This will add the workers from ‘other’ to this ward, plus will average the player weights between the two

This will do nothing to the scale_uv, cutoff, bg_foi or custom parameters

name()[source]

Return the name of this ward

Return the total number of play links

num_players()[source]

Return the total number of players who make their home in this ward

Return the total number of work links

num_workers()[source]

Return the total number of workers who make their home in this ward

play_connections()[source]

Return the full list of play connections for this ward

population()[source]

Return the total population of this ward

position()[source]

Return the position of the center of this ward. This will return a dictionary containing either the {“x”, “y”} coordinates (in kilometers) or containing the {“lat”, “long”} coordinates, or an empty dictionary if cooordinates have not been set.

region()[source]

Return the region containing this ward

resolve(wards: Wards, _inplace: bool = None) Ward[source]

Resolve any unresolved links using the passed Wards object ‘wards’

scale(work_ratio: float = 1.0, play_ratio: float = 1.0, _inplace: bool = False) metawards._ward.Ward[source]

Return a copy of these wards where the number of workers and players have been scaled by ‘work_ratios’ and ‘play_ratios’ respectively. These can be greater than 1.0, e.g. if you want to scale up the number of workers and players

Parameters
  • work_ratio (float) – The scaling ratio for workers

  • play_ratio (float) – The scaling ratio for players

Returns

Wards

Return type

A copy of this Wards scaled by the requested amount

scale_uv() float[source]

Return the scale_uv parameter for this ward. This is the amount by which to scale the force of infection (FOI) during the FOI calculation

set_authority(authority: str)[source]

Set the local authority of this ward

set_auto_assign_players(auto_assign_players: bool = True)[source]

Return whether or not the remaining player weight is automatically assigned to the home-ward player weight

set_bg_foi(bg_foi: float)[source]

Set the background force of infection (FOI). This is the starting value for ward FOI calculations. It defaults to 0.0. Positive values are used when you want the ward to have some background effect that drives infections independently of the number of infecteds. Negative values imply a background effect that reduces the risk of infection, regardless of the number of infecteds

set_code(code: str)[source]

Set the code of this ward

set_custom(key: str, value: float)[source]

Set the value of the custom ward parameter to ‘value’. Note that this must be convertible to a float as all custom parameters are stored as floats

set_cutoff(cutoff: float)[source]

Set the cutoff distance (in km) for this ward. This is the maximum distance that residents (or travellers to) this ward are allowed to travel. This defaults to 99999.99, which is larger than any point to point distance on earth

set_id(id: int)[source]

Set the ID of this ward

set_info(info: metawards._wardinfo.WardInfo)[source]

Set the info of this ward

set_name(name: str)[source]

Set the name of this ward

set_num_players(number: int)[source]

Set the number of players in this ward

set_num_workers(number: int)[source]

Set the number of workers in this ward.

set_position(x: Optional[float] = None, y: Optional[float] = None, lat: Optional[float] = None, long: Optional[float] = None, units: str = 'm')[source]

Set the position of the centre of this ward. This can be set either as x/y coordinates or latitude/longitude coordinates.

Parameters
  • x (float) – The x coordinates if x/y are used. The units are set via the ‘units’ argument

  • y (float) – The y coordinates if x/y are used. The units are set via the ‘units’ argument

  • units (str) – The units for x/y coordinates. This should be “m” for meters or “km” for kilometers

  • lat (float) – The latitude if lat/long coordinates are used

  • long (float) – The longitude if lat/long coordinates are used

set_region(region: str)[source]

Set the region of this ward

set_scale_uv(scale_uv: float)[source]

Set the scale_uv parameter for this ward. This is the amount by which to scale the FOI when caclulating the FOI. This defaults to 1.0

subtract_player_weight(weight: float, destination: Optional[int] = None)[source]

Subtract the weight for players who will randomly move to the specified destination to play (or to play in the home ward if destination is not set).

subtract_workers(number: int, destination: Optional[int] = None)[source]

Remove some workers from this ward, specifying their destination if they work out of ward

to_data()[source]

Return a dictionary that can be serialised to JSON

to_json(filename: Optional[str] = None, indent: Optional[int] = None, auto_bzip: bool = True) str[source]

Serialise the ward to JSON. This will write to a file if filename is set, otherwise it will return a JSON string.

Parameters
  • filename (str) – The name of the file to write the JSON to. The absolute path to the written file will be returned. If filename is None then this will serialise to a JSON string which will be returned.

  • indent (int) – The number of spaces of indent to use when writing the json

  • auto_bzip (bool) – Whether or not to automatically bzip2 the written json file

Returns

Returns either the absolute path to the written file, or the json-serialised string

Return type

str

work_connections()[source]

Return the full list of work connections for this ward

class metawards.WardID(home: Optional[Union[metawards._wardid.WardID, str, int]] = None, commute: Optional[Union[metawards._wardid.WardID, str, int]] = None, all_commute: bool = False)[source]

A simple class that identifies a Ward (or Wards), or a connection between Wards. This could be used, e.g. to specify ward moves

__eq__(other)[source]

Return self==value.

__hash__ = None
__init__(home: Optional[Union[metawards._wardid.WardID, str, int]] = None, commute: Optional[Union[metawards._wardid.WardID, str, int]] = None, all_commute: bool = False)[source]

Construct a WardID that identifies the ‘home’ ward, and (optionally) the ‘commute’ ward if this is a ward-link (used to identify workers)

If “all_commute” is true then this identifies all connections that have ‘home’ as the home ward.

__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

commute()[source]

Return the commute ward is this is a ward connection

home()[source]

Return the home ward

is_all_commute()[source]

Return whether or not this refers to all commuter connections to a ward

is_null()[source]

Return whether or not this is null

is_ward()[source]

Return whether or not this specifies a single ward

is_ward_connection()[source]

Return whether or not this is a ward connection (has both a home and commute ward)

class metawards.WardInfo(name: str = '', alternate_names: List[str] = <factory>, code: str = '', alternate_codes: List[str] = <factory>, authority: str = '', authority_code: str = '', region: str = '', region_code: str = '')[source]

This class holds metadata about a ward, e.g. its name(s), any ID code(s), any information about the region or authority it is in etc.

__eq__(other)

Return self==value.

__hash__()[source]

Return hash(self).

__init__(name: str = '', alternate_names: List[str] = <factory>, code: str = '', alternate_codes: List[str] = <factory>, authority: str = '', authority_code: str = '', region: str = '', region_code: str = '') None
__repr__()

Return repr(self).

alternate_codes: List[str]

Any alternative ID codes of the ward

alternate_names: List[str]

Any alternative names of the ward

authority: str = ''

The name of the local authority it is in

authority_code: str = ''

The ID of the local authority it is in

code: str = ''

Official ID code of the ward

static from_data(data)[source]

Construct from the passed dictionary, which has, e.g. been deserialised from JSON

name: str = ''

Name of the ward

region: str = ''

The name of the region it is in

region_code: str = ''

The ID of the region it is in

summary()[source]

Return a summary string that identifies this WardInfo

to_data()[source]

Return a dictionary that contains all of this data, in a format that can be serialised to JSON

class metawards.WardInfos(wards: List[metawards._wardinfo.WardInfo] = <factory>, _index: Optional[Dict[metawards._wardinfo.WardInfo, int]] = None)[source]

Simple class that holds a list of WardInfo objects, and provides useful search functions over that list. This prevents me from cluttering up the interface of Network

__contains__(info: metawards._wardinfo.WardInfo) bool[source]

Return whether or not this contains the passed WardInfo

__eq__(other)

Return self==value.

__hash__ = None
__init__(wards: List[metawards._wardinfo.WardInfo] = <factory>, _index: Optional[Dict[metawards._wardinfo.WardInfo, int]] = None) None
__repr__()

Return repr(self).

__setitem__(i: int, info: metawards._wardinfo.WardInfo) None[source]

Set the ith WardInfo equal to ‘info’.

contains(info: metawards._wardinfo.WardInfo) bool[source]

Return whether or not this contains the passed WardInfo

find(name: Optional[str] = None, authority: Optional[str] = None, region: Optional[str] = None, match: bool = False, match_authority_and_region: bool = False, include_alternates: bool = True)[source]

Generic search function that will search using any or all of the terms provided. This returns a list of indicies of wards that match the search

Parameters
  • name (str or regexp) – Name or code of the ward to search. You can also include the authority adn region by separating usign “/”, e.g. “Clifton/Bristol”.

  • authority (str or regexp) – Name or code of the authority to search

  • region (str or regexp) – Name or code of the region to search

  • match (bool(False)) – Use a regular expression match for the ward rather than a search. This forces the match to be at the start of the string

  • match_authority_and_region (bool(False)) – Use a regular expression match for the authority and region rather than a search. This forces the match to be at the start of the string

  • include_alternates (bool(True)) – Whether or not to include alternative names and codes when searching for the ward

index(info: metawards._wardinfo.WardInfo) int[source]

Return the index of the passed ‘info’ object if it is in this list. If not, then a ValueError exception is raised. Note that only the first matching WardInfo will be returned

reindex()[source]

Rebuild the WardInfo index. You must call this function after you have modified the list of WardInfo objects, as otherwise this will fall out of date. Note that this will be automatically called the first time you use the “contains” or “index” functions

wards: List[metawards._wardinfo.WardInfo]

The list of WardInfo objects, one for each ward in order

class metawards.Wards(wards: Optional[List[metawards._ward.Ward]] = None)[source]

This class holds an entire network of Ward objects

__contains__(id: Union[int, str, metawards._wardinfo.WardInfo, metawards._ward.Ward]) bool[source]

Return whether or not the passed id - which can be an integer ID or WardInfo - is in this Wards object

__eq__(other)[source]

Return self==value.

__getitem__(id: Union[int, str, metawards._wardinfo.WardInfo]) metawards._ward.Ward[source]

Return the ward with specified id - this can be the integer ID of the ward, or the WardInfo of the ward. Note that this returns a copy of the Ward

__hash__ = None
__imul__(scale: float) metawards._wards.Wards[source]

In-place multiply the number of workers and players by ‘scale’

__init__(wards: Optional[List[metawards._ward.Ward]] = None)[source]

Construct, optionally from a list of Ward objects

__mul__(scale: float) metawards._wards.Wards[source]

Scale the number of workers and players by ‘scale’

__repr__()[source]

Return repr(self).

__rmul__(scale: float) metawards._wards.Wards[source]

Scale the number of workers and players by ‘scale’

__str__()[source]

Return str(self).

add(ward: metawards._ward.Ward) None[source]

Synonym for insert

assert_sane()[source]

Make sure that we don’t refer to any non-existent wards

contains(id: Union[int, str, metawards._wardinfo.WardInfo]) bool[source]

Return whether or not the passed id - which can be an integer ID or WardInfo - is in this Wards object

static from_data(data, profiler: Optional[metawards.utils._profiler.Profiler] = None)[source]

Return the Wards constructed from a data represnetation, which may have come from deserialised JSON

static from_json(s: str)[source]

Return the Wards constructed from the passed json. This will either load from a passed json string, or from json loaded from the passed file

get(id: Union[int, metawards._wardinfo.WardInfo], dereference: bool = True) metawards._ward.Ward[source]

Return the ward with the specified id - this can eb the integer ID of the ward or the WardInfo of the ward. If ‘dereference’ is True then this will dereference all of the IDs into WardInfo objects. This is useful if you want to use the resulting Ward with other Wards collections

getinfo(id: Union[int, str, metawards._wardinfo.WardInfo]) metawards._wardinfo.WardInfo[source]

Return the WardInfo matching the ward with the passed ID

static harmonise(wardss: List[Wards]) Tuple[Wards, List[Wards]][source]

Harmonise the passed list of wards, returning a tuple that contains the overall sum of all of these wards, plus a new list where all Wards use IDs that are correct and valid across the entire group

index(id: Union[int, str, metawards._wardinfo.WardInfo, metawards._ward.Ward]) int[source]

Return the index of the ward that matches the passed id - which can be the integer ID or WardInfo - in this Wards object. This raises a ValueError if the ward doens’t exist

insert(wards: List[metawards._ward.Ward], overwrite: bool = True, _need_deep_copy: bool = True) None[source]

Insert the passed wards onto this list. This will overwrite the existing ward if ‘overwrite’ is true, otherwise it will add the ward’s data to the existing ward

is_resolved() bool[source]

Return whether or not this is a fully resolved set of Wards (i.e. each ward only links to other wards in this set)

Return the total number of play links

num_players()[source]

Return the total number of players in this network

Return the total number of work links

num_workers()[source]

Return the total number of workers in this network

population()[source]

Return the total population in this network

scale(work_ratio: float = 1.0, play_ratio: float = 1.0, _inplace: bool = False) metawards._wards.Wards[source]

Return a copy of these wards where the number of workers and players have been scaled by ‘work_ratios’ and ‘play_ratios’ respectively. These can be greater than 1.0, e.g. if you want to scale up the number of workers and players

Parameters
  • work_ratio (float) – The scaling ratio for workers

  • play_ratio (float) – The scaling ratio for players

Returns

Wards

Return type

A copy of this Wards scaled by the requested amount

to_data(profiler: Optional[metawards.utils._profiler.Profiler] = None)[source]

Return a data representation of these wards that can be serialised to JSON

to_json(filename: Optional[str] = None, indent: Optional[int] = None, auto_bzip: bool = True) str[source]

Serialise the wards to JSON. This will write to a file if filename is set, otherwise it will return a JSON string.

Parameters
  • filename (str) – The name of the file to write the JSON to. The absolute path to the written file will be returned. If filename is None then this will serialise to a JSON string which will be returned.

  • indent (int) – The number of spaces of indent to use when writing the json

  • auto_bzip (bool) – Whether or not to automatically bzip2 the written json file

Returns

Returns either the absolute path to the written file, or the json-serialised string

Return type

str

unresolved_wards() List[int][source]

Return the list of IDs of unresolved wards

class metawards.Workspace(n_inf_classes: int = 0, nnodes: int = 0, inf_tot: Optional[List[int]] = None, pinf_tot: Optional[List[int]] = None, n_inf_wards: Optional[List[int]] = None, ward_inf_tot: Optional[List[List[int]]] = None, total_inf_ward: Optional[List[int]] = None, total_new_inf_ward: Optional[List[int]] = None, incidence: Optional[List[int]] = None, S_in_wards: Optional[List[int]] = None, E_in_wards: Optional[List[int]] = None, I_in_wards: Optional[List[int]] = None, R_in_wards: Optional[List[int]] = None, X_in_wards: Optional[Dict[str, List[int]]] = None)[source]

This class provides a workspace for the running calculation. This pre-allocates all of the memory into arrays, which can then be used via cython memory views

E_in_wards: List[int] = None

The size of the E population in each ward

I_in_wards: List[int] = None

The size of the I population in each ward

R_in_wards: List[int] = None

The size of the R population in each ward

S_in_wards: List[int] = None

The size of the S population in each ward

X_in_wards: Dict[str, List[int]] = None

The sizes of the X populations in each ward - this is for named disease stages that don’t fit into S, E, I or R

__eq__(other)

Return self==value.

__hash__ = None
__init__(n_inf_classes: int = 0, nnodes: int = 0, inf_tot: Optional[List[int]] = None, pinf_tot: Optional[List[int]] = None, n_inf_wards: Optional[List[int]] = None, ward_inf_tot: Optional[List[List[int]]] = None, total_inf_ward: Optional[List[int]] = None, total_new_inf_ward: Optional[List[int]] = None, incidence: Optional[List[int]] = None, S_in_wards: Optional[List[int]] = None, E_in_wards: Optional[List[int]] = None, I_in_wards: Optional[List[int]] = None, R_in_wards: Optional[List[int]] = None, X_in_wards: Optional[Dict[str, List[int]]] = None) None
__repr__()

Return repr(self).

static build(network: Union[metawards._network.Network, metawards._networks.Networks])[source]

Create the workspace needed to run the model for the passed network

incidence: List[int] = None

The incidence of the infection (sum of infections up to disease_class == I_start)

inf_tot: List[int] = None

Size of population in each disease stage for work infections

n_inf_classes: int = 0

Number of disease classes (stages)

n_inf_wards: List[int] = None

Number of wards with at least one individual in this disease stage

nnodes: int = 0

Number of wards (nodes)

pinf_tot: List[int] = None

Size of population in each disease stage for play infections

subspaces = None

The sub-workspaces used for the subnets of a multi-demographic Networks (list[Workspace])

total_inf_ward: List[int] = None

Total number of infections in each ward over the last day This is also equal to the prevalence

total_new_inf_ward: List[int] = None

Number of new infections in each ward over the last day

ward_inf_tot: List[List[int]] = None

Size of population in each disease stage in each ward

zero_all(zero_subspaces=True)[source]

Reset the values of all of the arrays to zero. By default we zero the subspace networks (change this by setting zero_subspaces to False)

metawards.get_version_string()[source]

Return a version string for metawards which can be printed into a file or written out to the screen

metawards.input(prompt: str, default='y')[source]

Wrapper for ‘input’ that returns ‘default’ if it detected that this is being run from within a batch job or other service that doesn’t have access to a tty