epymorph.compartment_model
The basis of the intra-population model (disease mechanics, aka IPM) system in epymorph. This represents disease mechanics using a compartmental model for tracking populations as groupings of integer-numbered individuals.
BIRTH
module-attribute
An IPM psuedo-compartment representing exogenous input of individuals. This is useful in defining IPM edges.
DEATH
module-attribute
An IPM psuedo-compartment representing exogenous removal of individuals. This is useful in defining IPM edges.
exogenous_states
module-attribute
The list of supported exogenous states.
TransitionDef
module-attribute
The ways to define a compartment model transition: either a single edge or a fork.
MetaEdgeBuilder
module-attribute
MetaEdgeBuilder = Callable[
[MultiStrataModelSymbols], Sequence[TransitionDef]
]
The type of a function for creating meta edges in a multistrata RUME.
Quantity
module-attribute
Quantity = CompartmentDef | EdgeDef
The type of quantity referenced by a QuantityStrategy
, either compartments or events.
QuantityAggMethod
module-attribute
QuantityAggMethod = Literal['sum']
The supported methods for aggregating IPM quantities.
CompartmentName
dataclass
The name of a compartment, which may have subscript and strata parts.
Parameters:
-
base
(str
) –The base name of the compartment.
-
subscript
(str | None
) –The optional subscript part of the name.
-
strata
(str | None
) –The optional strata part of the name.
full
class-attribute
instance-attribute
The full name as a string, with all parts combined with underscores.
with_subscript
with_strata
parse
classmethod
Parses a string as a CompartmentName
. If the name contains no underscores,
the entire name is the base name. If the name contains at least one underscore,
the part before the first underscore is the base name and everything after is
the subscript part. It is not possible to create a stratified name this way.
For example: in "E_phase_1", "E" is the base name and "phase_1" is the subscript.
Parameters:
-
name
(str
) –The string to parse.
Returns:
-
Self
–The parsed compartment name.
CompartmentDef
dataclass
CompartmentDef(
name: CompartmentName,
tags: list[str],
description: str | None = None,
)
Defines an IPM compartment.
Parameters:
-
name
(CompartmentName
) –The name of the compartment.
-
tags
(list[str]
) –Tags associated with the compartment.
-
description
(str | None
, default:None
) –An optional description of the compartment.
description
class-attribute
instance-attribute
An optional description of the compartment.
EdgeName
dataclass
EdgeName(
compartment_from: CompartmentName,
compartment_to: CompartmentName,
)
The name of a transition edge, from one compartment to another.
Parameters:
-
compartment_from
(CompartmentName
) –The source compartment for this edge.
-
compartment_to
(CompartmentName
) –The destination compartment for this edge.
compartment_from
instance-attribute
compartment_from: CompartmentName
The source compartment for this edge.
compartment_to
instance-attribute
compartment_to: CompartmentName
The destination compartment for this edge.
full
class-attribute
instance-attribute
The name of the edge as a string.
with_subscript
EdgeDef
dataclass
EdgeDef(
name: EdgeName,
rate: Expr,
compartment_from: Symbol,
compartment_to: Symbol,
)
Defines a single edge transition in a compartment model.
Parameters:
-
name
(EdgeName
) –The name of the edge.
-
rate
(Expr
) –The rate of flow along this edge.
-
compartment_from
(Symbol
) –The symbol describing the source compartment.
-
compartment_to
(Symbol
) –The symbol describing the destination compartment.
compartment_from
instance-attribute
The symbol describing the source compartment.
compartment_to
instance-attribute
The symbol describing the destination compartment.
ForkDef
dataclass
Defines a fork-style transition in a compartment model.
Parameters:
ModelSymbols
IPM symbols needed in defining the model's transition rate expressions.
Parameters:
-
compartments
(Sequence[tuple[str, str]]
) –The compartments of the IPM, as name/symbolic name pairs.
-
requirements
(Sequence[tuple[str, str]]
) –The requirements (data attributes) of the IPM, as name/symbolic name pairs.
all_compartments
instance-attribute
all_compartments: Sequence[Symbol] = [s for (_, s) in cs]
Compartment symbols in definition order.
all_requirements
instance-attribute
all_requirements: Sequence[Symbol] = [s for (_, s) in rs]
Requirements symbols in definition order.
compartments
BaseCompartmentModel
Bases: ABC
Shared base-class for compartment models.
See Also
In practice users will mostly use epymorph.compartment_model.CompartmentModel for single-strata IPMs, and construct multi-strata IPMs as a byproduct of constructing a multi-strata RUME.
compartments
class-attribute
instance-attribute
compartments: Sequence[CompartmentDef] = ()
The compartments of the model.
requirements
class-attribute
instance-attribute
requirements: Sequence[AttributeDef] = ()
The attributes required by the model.
quantities
property
quantities: Iterator[CompartmentDef | EdgeDef]
All quantities from the model, compartments then edges, in definition order.
symbols
abstractmethod
property
symbols: ModelSymbols
The symbols which represent parts of this model.
transitions
abstractmethod
property
transitions: Sequence[TransitionDef]
The transitions in the model.
requirements_dict
abstractmethod
property
requirements_dict: OrderedDict[AbsoluteName, AttributeDef]
The attributes required by this model.
strata
abstractmethod
property
The names of the strata involved in this compartment model.
is_multistrata
abstractmethod
property
is_multistrata: bool
True if this compartment model is multistrata, False for single-strata.
diagram
Render a diagram of this IPM, either by showing it with matplotlib (default)
or by saving it to file
as a png image.
Parameters:
-
file
(str | Path | None
, default:None
) –Provide a file path to save a png image of the diagram to this path. If
file
is None, we will instead use matplotlib to show the diagram. -
figsize
(tuple[float, float] | None
, default:None
) –The matplotlib figure size to use when displaying the diagram. Only used if
file
is not provided.
CompartmentModelClass
Bases: ABCMeta
The metaclass for CompartmentModel
classes; enforces proper implementation.
CompartmentModel
Bases: BaseCompartmentModel
, ABC
A compartment model definition and its corresponding metadata. Effectively, a collection of compartments, transitions between compartments, and the data parameters which are required to compute the transitions.
Examples:
To create a custom IPM, you will write an implementation of this class:
requirements_dict
property
requirements_dict: OrderedDict[AbsoluteName, AttributeDef]
The attributes required by this model.
is_multistrata
property
is_multistrata: bool
True if this compartment model is multistrata, False for single-strata.
edges
abstractmethod
edges(symbols: ModelSymbols) -> Sequence[TransitionDef]
When implementing a CompartmentModel
, override this method
to define the transition edges between compartments.
Parameters:
-
symbols
(ModelSymbols
) –An object containing the symbols in the model for use in declaring edges. These include compartments and data requirements.
Returns:
-
Sequence[TransitionDef]
–The transitions for the model.
MultiStrataModelSymbols
MultiStrataModelSymbols(
strata: Sequence[tuple[str, CompartmentModel]],
meta_requirements: Sequence[AttributeDef],
)
Bases: ModelSymbols
IPM symbols needed in defining the model's transition rate expressions.
Parameters:
-
strata
(Sequence[tuple[str, CompartmentModel]]
) –The strata and the compartment model for each.
-
meta_requirements
(Sequence[AttributeDef]
) –Additional requirements needed for the combined model's meta-transitions.
strata
instance-attribute
The strata names used in this model.
all_meta_requirements
instance-attribute
all_meta_requirements: Sequence[Symbol] = [
to_symbol(sym) for (_, _, sym) in ms
]
Meta-requirement symbols in definition order.
strata_compartments
Select compartment symbols by name in a particular strata.
If names
is non-empty, select those symbols by their original name.
If names
is empty, return all symbols.
Parameters:
-
strata
(str
) –The strata to select.
-
*names
(str
, default:()
) –The names of the model's compartments to select, or left empty to select all compartments in the strata.
Returns:
-
Sequence[Symbol]
–The symbols representing the compartments in the order in which they're named, or their definition order if selecting all. Ideal for unpacking into variables.
strata_requirements
Select requirement symbols by name in a particular strata.
If names
is non-empty, select those symbols by their original name.
If names
is empty, return all symbols.
Parameters:
-
strata
(str
) –The strata to select.
-
*names
(str
, default:()
) –The names of the model's requirements to select, or left empty to select all requirements for the strata.
Returns:
-
Sequence[Symbol]
–The symbols representing the attributes in the order in which they're named, or their definition order if selecting all. Ideal for unpacking into variables.
CombinedCompartmentModel
CombinedCompartmentModel(
strata: Sequence[tuple[str, CompartmentModel]],
meta_requirements: Sequence[AttributeDef],
meta_edges: MetaEdgeBuilder,
)
Bases: BaseCompartmentModel
A CompartmentModel
constructed by combining others for use in multi-strata models.
Typically you will not have to create a CombinedCompartmentModel
directly.
Building a MultiStrataRUME
will combine the models for you.
Parameters:
-
strata
(Sequence[tuple[str, CompartmentModel]]
) –A list of pairs mapping strata names to the IPM for the strata.
-
meta_requirements
(Sequence[AttributeDef]
) –Additional requirement definitions for use in the combined model's meta edges.
-
meta_edges
(MetaEdgeBuilder
) –A function which defines the combined model's meta edges.
compartments
instance-attribute
compartments: Sequence[CompartmentDef] = [
with_strata(strata_name)
for (strata_name, ipm) in strata
for comp in compartments
]
All compartments; renamed with strata.
requirements
instance-attribute
requirements: Sequence[AttributeDef] = [*r for (_, ipm) in strata for r in requirements, *_meta_requirements]
All requirements, including meta-requirements.
requirements_dict
property
requirements_dict: OrderedDict[AbsoluteName, AttributeDef]
The attributes required by this model.
is_multistrata
property
is_multistrata: bool
True if this compartment model is multistrata, False for single-strata.
QuantityGroupResult
QuantityGrouping
Bases: NamedTuple
Describes how to group simulation output quantities (events and compartments).
The default combines any quantity whose names match exactly. This is common in
multistrata models where events from several strata impact one transition.
You can also choose to group across strata and subscript differences.
Setting strata
or subscript
to True means those elements of quantity names
(if they exist) are ignored for the purposes of matching.
map
map(quantities: Sequence[Quantity]) -> QuantityGroupResult
QuantityStrategy
dataclass
QuantityStrategy(
ipm: BaseCompartmentModel,
selection: NDArray[bool_],
grouping: QuantityGrouping | None,
aggregation: QuantityAggMethod | None,
)
A strategy for dealing with the quantity axis, e.g., in processing results. Quantities here are an IPM's compartments and events. Strategies can include selection of a subset, grouping, and aggregation.
Typically you will create one of these by calling methods on a QuantitySelector
instance.
Parameters:
-
ipm
(BaseCompartmentModel
) –The original IPM quantity information.
-
selection
(NDArray[bool_]
) –A boolean mask for selection of a subset of quantities.
-
grouping
(QuantityGrouping | None
) –A method for grouping IPM quantities.
-
aggregation
(QuantityAggMethod | None
) –A method for aggregating the quantity groups.
selection
instance-attribute
A boolean mask for selection of a subset of quantities.
aggregation
instance-attribute
aggregation: QuantityAggMethod | None
A method for aggregating the quantity groups.
selected
property
The quantities from the IPM which are selected, prior to any grouping.
quantities
abstractmethod
property
The quantities in the result. If the strategy performs grouping these may be pseudo-quantities made by combining the quantities in the group.
labels
abstractmethod
property
Labels for the quantities in the result, after any grouping.
disambiguate
disambiguate() -> OrderedDict[str, str]
Creates a name mapping to disambiguate IPM quantities that have the same name. This happens commonly in multistrata IPMs with meta edges where multiple other strata influence a transmission rate in a single strata. The returned mapping includes only the selected IPM compartments and events, but definition order is maintained. Keys are the unique name and values are the original names (because the original names might contain duplicates); so you will have to map into unique names by position, but can map back using this mapping directly.
This function is intended for epymorph's internal use.
disambiguate_groups
disambiguate_groups() -> OrderedDict[str, str]
Like method disambiguate
but for working with quantities
after any grouping has been performed. If grouping is None,
this is equivalent to disambiguate
.
This function is intended for epymorph's internal use.
QuantitySelection
dataclass
QuantitySelection(
ipm: BaseCompartmentModel,
selection: NDArray[bool_],
grouping: QuantityGrouping | None,
aggregation: QuantityAggMethod | None,
)
Bases: QuantityStrategy
A kind of QuantityStrategy
describing a sub-selection of IPM quantities
(its events and compartments). A selection performs no grouping or aggregation.
Typically you will create one of these by calling methods on QuantitySelector
instance.
Parameters:
-
ipm
(BaseCompartmentModel
) –The original IPM quantities information.
-
selection
(NDArray[bool_]
) –A boolean mask for selection of a subset of IPM quantities.
selection
instance-attribute
A boolean mask for selection of a subset of IPM quantities.
grouping
class-attribute
instance-attribute
grouping: None = field(init=False, default=None)
A method for grouping IPM quantities.
aggregation
class-attribute
instance-attribute
aggregation: None = field(init=False, default=None)
A method for aggregating the quantity groups.
quantities
property
quantities: Sequence[CompartmentDef | EdgeDef]
The quantities in the result. If the strategy performs grouping these may be pseudo-quantities made by combining the quantities in the group.
compartment_index
property
compartment_index: int
The selected compartment index, if and only if there is exactly one compartment in the selection. Otherwise, raises ValueError.
See compartment_indices
if you want to select possibly multiple indices.
compartment_indices
property
The selected compartment indices. These indices may be useful
for instance to access a simulation output's compartments
result array.
May be an empty tuple.
event_index
property
event_index: int
The selected event index, if and only if there is exactly one event in the selection. Otherwise, raises ValueError.
See event_indices
if you want to select possibly multiple indices.
event_indices
property
The selected event indices. These indices may be useful
for instance to access a simulation output's events
result array.
May be an empty tuple.
group
group(
*, strata: bool = False, subscript: bool = False
) -> QuantityGroup
Groups quantities according to the given options.
By default, any quantities that directly match each other will be combined.
This generally only happens with events, where there may be multiple edges
between the same compartments like S->I
, perhaps due to meta edges in a
multistrata model.
With strata=True
, quantities that would match if you removed the strata name
will be combined. e.g., S_young
and S_old
;
or S_young->I_young
and S_old->I_old
.
With subscript=True
, quantities that would match if you removed subscript
names will be combined. e.g., I_asymptomatic_young
and I_symptomatic_young
belong to the same strata (young) but have different subscripts so they will
be combined.
And if both options are True, we consider matches after removing both strata and subscript names -- effectively matching on the base compartment and event names.
Parameters:
-
strata
(bool
, default:False
) –Whether or not to combine different strata.
-
subscript
(bool
, default:False
) –Whether or not the combine different subscripts.
Returns:
-
QuantityGroup
–A grouping strategy object.
QuantityGroup
dataclass
QuantityGroup(
ipm: BaseCompartmentModel,
selection: NDArray[bool_],
grouping: QuantityGrouping,
aggregation: QuantityAggMethod | None,
)
Bases: QuantityStrategy
A kind of QuantityStrategy
describing a group operation on IPM quantities, with
an optional sub-selection.
Typically you will create one of these by calling methods on a QuantitySelection
instance.
Parameters:
-
ipm
(BaseCompartmentModel
) –The original IPM quantity information.
-
selection
(NDArray[bool_]
) –A boolean mask for selection of a subset of quantities.
-
grouping
(QuantityGrouping
) –A method for grouping IPM quantities.
selection
instance-attribute
A boolean mask for selection of a subset of quantities.
aggregation
class-attribute
instance-attribute
aggregation: None = field(init=False, default=None)
A method for aggregating the quantity groups.
quantities
property
quantities: Sequence[CompartmentDef | EdgeDef]
The quantities in the result. If the strategy performs grouping these may be pseudo-quantities made by combining the quantities in the group.
agg
agg(agg: QuantityAggMethod) -> QuantityAggregation
Combine grouped quantities using the named aggregation.
Parameters:
-
agg
(QuantityAggMethod
) –The aggregation method to use.
Returns:
-
QuantityAggregation
–The aggregation strategy object.
sum
sum() -> QuantityAggregation
Combine grouped quantities by adding their values. Equivalent to agg("sum")
.
Returns:
-
QuantityAggregation
–The aggregation strategy object.
QuantityAggregation
dataclass
QuantityAggregation(
ipm: BaseCompartmentModel,
selection: NDArray[bool_],
grouping: QuantityGrouping,
aggregation: QuantityAggMethod,
)
Bases: QuantityStrategy
A kind of QuantityStrategy
describing a group-and-aggregate operation on IPM
quantities, with an optional sub-selection.
Typically you will create one of these by calling methods on a QuantitySelector
instance.
Parameters:
-
ipm
(BaseCompartmentModel
) –The original IPM quantity information.
-
selection
(NDArray[bool_]
) –A boolean mask for selection of a subset of quantities.
-
grouping
(QuantityGrouping
) –A method for grouping IPM quantities.
-
aggregation
(QuantityAggMethod
) –A method for aggregating the quantity groups.
selection
instance-attribute
A boolean mask for selection of a subset of quantities.
aggregation
instance-attribute
aggregation: QuantityAggMethod
A method for aggregating the quantity groups.
quantities
property
quantities: Sequence[CompartmentDef | EdgeDef]
The quantities in the result. If the strategy performs grouping these may be pseudo-quantities made by combining the quantities in the group.
QuantitySelector
QuantitySelector(ipm: BaseCompartmentModel)
A utility class for selecting a subset of IPM quantities. Most of the time you
obtain one of these using CompartmentModel
's select
property.
all
all() -> QuantitySelection
indices
indices(*indices: int) -> QuantitySelection
Select quantities by index (determined by IPM definition order: all IPM compartments, all IPM events, and then meta edge events if any).
Parameters:
-
*indices
(int
, default:()
) –The indices to select, as a var-arg.
Returns:
-
QuantitySelection
–The selection object.
by
by(
*,
compartments: str | Iterable[str] = (),
events: str | Iterable[str] = (),
) -> QuantitySelection
Select compartments and events by providing pattern strings for each.
Providing an empty sequence implies selecting none of that type. Multiple patterns are combined as though by boolean-or.
Parameters:
-
compartments
(str | Iterable[str]
, default:()
) –The compartment selection patterns.
-
events
(str | Iterable[str]
, default:()
) –The event selection patterns.
Returns:
-
QuantitySelection
–The selection object.
compartments
compartments(*patterns: str) -> QuantitySelection
Select compartments with zero or more pattern strings.
Specify no patterns to select all compartments. Pattern strings match against compartment names. Multiple patterns are combined as though by boolean-or. Pattern strings can use asterisk as a wildcard character to match any (non-empty) part of a name besides underscores. For example, "I_*" would match events "I_abc" and "I_def".
Parameters:
-
*patterns
(str
, default:()
) –The compartment selection patterns, as a var-arg.
Returns:
-
QuantitySelection
–The selection object.
events
events(*patterns: str) -> QuantitySelection
Select events with zero or more pattern strings.
Specify no patterns to select all events. Pattern strings match against event names which combine the source and destination compartment names with a separator. e.g., the event where individuals transition from "S" to "I" is called "S->I". You must provide both a source and destination pattern, but you can use "-", ">", or "->" as the separator. Multiple patterns are combined as though by boolean-or. Pattern strings can use asterisk as a wildcard character to match any (non-empty) part of a name besides underscores. For example, "S->*" would match events "S->A" and "S->B". "S->I_*" would match "S->I_abc" and "S->I_def".
Parameters:
-
*patterns
(str
, default:()
) –The event selection patterns, as a var-arg.
Returns:
-
QuantitySelection
–The selection object.
compartment
compartment(
name: str,
tags: list[str] | None = None,
description: str | None = None,
) -> CompartmentDef
Define an IPM compartment. Convenience constructor for CompartmentDef
.
Parameters:
-
name
(str
) –The name of the compartment. This will be converted to a
CompartmentName
using theparse
method. -
tags
(list[str] | None
, default:None
) –An optional list of tags to associate with this compartment.
-
description
(str | None
, default:None
) –An optional description of the compartment.
Returns:
-
CompartmentDef
–The compartment definition.
quick_compartments
quick_compartments(
symbol_names: str,
) -> list[CompartmentDef]
Define a number of IPM compartments from a space-delimited string.
This is just short-hand syntax for the compartment()
function.
Note: this does not allow you to set tags or descriptions for the
compartments.
Parameters:
-
symbol_names
(str
) –Compartment names in a single string separated by spaces. For example: "S I R".
Returns:
-
list[CompartmentDef]
–The corresponding list of compartment definitions.
edge
Define a transition edge from one compartment to another at the given rate.
Parameters:
-
compartment_from
(Symbol
) –The symbol describing the source compartment.
-
compartment_to
(Symbol
) –The symbol describing the destination compartment.
-
rate
(Expr | int | float
) –The rate of flow along this edge.
Returns:
-
EdgeDef
–The edge definition.
fork
Define a forked transition: a set of edges that come from the same compartment but go to different compartments. It is assumed the edges will share a "base rate"-- a common sub-expression among all edge rates -- and that each edge in the fork is given a proportion on that base rate.
Parameters:
-
*edges
(EdgeDef
, default:()
) –All edges that participate in the fork, as a var-arg.
Returns:
-
ForkDef
–The fork definition.
Examples:
Consider two edges with rates:
delta * EXPOSED * rho
delta * EXPOSED * (1 - rho)
delta * EXPOSED
is the base rate and rho
describes the proportional split for
each edge.
validate_compartment_model
validate_compartment_model(
model: BaseCompartmentModel,
) -> None
Validates an IPM definition.
Parameters:
-
model
(BaseCompartmentModel
) –The IPM to validate.
Raises:
-
IPMValidationError
–If there are structural issues in the IPM.