Skip to content

Overview

laser.cholera.metapop

laser.cholera.metapop — metapopulation cholera simulation pipeline.

Re-exports the canonical component classes and get_parameters / scenario helpers as a flat namespace, so user code can write from laser.cholera.metapop import Susceptible, Exposed, ... instead of importing from each submodule. Importing this package also triggers logsetup which configures the laser.cholera logger and reserves a timestamped log file path.

The default component pipeline (Susceptible -> Exposed -> Recovered -> Infectious -> Vaccinated -> Census -> HumanToHuman -> EnvToHuman -> Environmental -> DerivedValues -> Analyzer -> Recorder -> Parameters) is wired up by run_model.

__all__ module-attribute

__all__ = [
    "Analyzer",
    "Census",
    "DerivedValues",
    "EnvToHuman",
    "Environmental",
    "Exposed",
    "HumanToHuman",
    "Infectious",
    "Parameters",
    "Recorder",
    "Recovered",
    "Susceptible",
    "Vaccinated",
    "get_parameters",
    "scenario",
]

Analyzer

Final-tick likelihood evaluator for calibration / scoring workflows.

Attributes:

Name Type Description
model

The parent Model instance.

Source code in src/laser/cholera/metapop/analyzer.py
class Analyzer:
    """Final-tick likelihood evaluator for calibration / scoring workflows.

    Attributes:
        model: The parent `Model` instance.
    """

    def __init__(self, model: "Model") -> None:
        """Register the analyzer on the model (no state is allocated).

        Args:
            model: The `Model` instance.
        """
        self.model = model

        return

    def check(self):
        """No-op: `Analyzer` has no prerequisites that need pre-tick validation.

        The likelihood call validates its own inputs on the final tick.
        """
        return

    def __call__(self, model: "Model", tick: int) -> None:
        """Calculate log likelihood on the final tick."""
        # If model.params.calc_likelihood is True, calculate the log likelihood on the final tick.
        if tick == model.params.nticks - 1:
            if ("calc_likelihood" in model.params) and model.params.calc_likelihood:
                # Use the smaller of reported cases or the number of timesteps (not including the initial state)
                nreports = min(model.params.reported_cases.shape[1], model.patches.incidence.shape[0] - 1)
                try:
                    optional = {
                        key: model.params[key]
                        for key in [
                            "weight_cases",
                            "weight_deaths",
                            "weights_time",
                            "weights_location",
                            "nb_k_min_cases",
                            "nb_k_min_deaths",
                            "weight_peak_timing",
                            "weight_peak_magnitude",
                            "weight_cumulative_total",
                            "weight_wis",
                            "sigma_peak_time",
                            "sigma_peak_log",
                            "epidemic_peaks",
                            "date_start",
                            "date_stop",
                        ]
                        if key in model.params
                    }

                    model.log_likelihood = calc_model_likelihood(
                        obs_cases=model.params.reported_cases[:, :nreports],
                        est_cases=model.results.reported_cases[:, :nreports],
                        obs_deaths=model.params.reported_deaths[:, :nreports],
                        est_deaths=model.results.reported_deaths[:, :nreports],
                        **optional,
                    )
                except ValueError as e:
                    print(f"Error calculating log likelihood: {e}")
                    model.log_likelihood = -np.inf
            else:
                model.log_likelihood = np.nan

        return

    def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
        """Yield one Matplotlib figure overlaying every SEIRV channel for the largest patch.

        Pulls the R-transposed series from `model.results` (so channels
        are indexed `[patch, tick]`) and plots all of `S`, `Isym`,
        `Iasym`, `R`, `V1`, `V2` for the single largest-by-initial-S
        patch.

        Args:
            fig: Optional existing Matplotlib `Figure` to draw into.

        Yields:
            The string label `"SIRV Trajectories (Largest Patch)"`.
        """
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="SIRV Trajectories (Largest Patch)") if fig is None else fig

        for ipatch in np.argsort(self.model.params.S_j_initial)[-1:]:
            for channel in ["S", "Isym", "Iasym", "R", "V1", "V2"]:
                # Transpose ticks (:) and location since results are transposed for R users.
                plt.plot(getattr(self.model.results, channel)[ipatch, :], label=f"{channel}")

        plt.xlabel("Tick")
        plt.ylabel("Population")
        plt.legend()

        yield "SIRV Trajectories (Largest Patch)"
        return

model instance-attribute

model = model

__init__

__init__(model: Model) -> None

Register the analyzer on the model (no state is allocated).

Parameters:

Name Type Description Default
model Model

The Model instance.

required
Source code in src/laser/cholera/metapop/analyzer.py
def __init__(self, model: "Model") -> None:
    """Register the analyzer on the model (no state is allocated).

    Args:
        model: The `Model` instance.
    """
    self.model = model

    return

check

check()

No-op: Analyzer has no prerequisites that need pre-tick validation.

The likelihood call validates its own inputs on the final tick.

Source code in src/laser/cholera/metapop/analyzer.py
def check(self):
    """No-op: `Analyzer` has no prerequisites that need pre-tick validation.

    The likelihood call validates its own inputs on the final tick.
    """
    return

__call__

__call__(model: Model, tick: int) -> None

Calculate log likelihood on the final tick.

Source code in src/laser/cholera/metapop/analyzer.py
def __call__(self, model: "Model", tick: int) -> None:
    """Calculate log likelihood on the final tick."""
    # If model.params.calc_likelihood is True, calculate the log likelihood on the final tick.
    if tick == model.params.nticks - 1:
        if ("calc_likelihood" in model.params) and model.params.calc_likelihood:
            # Use the smaller of reported cases or the number of timesteps (not including the initial state)
            nreports = min(model.params.reported_cases.shape[1], model.patches.incidence.shape[0] - 1)
            try:
                optional = {
                    key: model.params[key]
                    for key in [
                        "weight_cases",
                        "weight_deaths",
                        "weights_time",
                        "weights_location",
                        "nb_k_min_cases",
                        "nb_k_min_deaths",
                        "weight_peak_timing",
                        "weight_peak_magnitude",
                        "weight_cumulative_total",
                        "weight_wis",
                        "sigma_peak_time",
                        "sigma_peak_log",
                        "epidemic_peaks",
                        "date_start",
                        "date_stop",
                    ]
                    if key in model.params
                }

                model.log_likelihood = calc_model_likelihood(
                    obs_cases=model.params.reported_cases[:, :nreports],
                    est_cases=model.results.reported_cases[:, :nreports],
                    obs_deaths=model.params.reported_deaths[:, :nreports],
                    est_deaths=model.results.reported_deaths[:, :nreports],
                    **optional,
                )
            except ValueError as e:
                print(f"Error calculating log likelihood: {e}")
                model.log_likelihood = -np.inf
        else:
            model.log_likelihood = np.nan

    return

plot

plot(fig: Figure = None) -> Iterator[str]

Yield one Matplotlib figure overlaying every SEIRV channel for the largest patch.

Pulls the R-transposed series from model.results (so channels are indexed [patch, tick]) and plots all of S, Isym, Iasym, R, V1, V2 for the single largest-by-initial-S patch.

Parameters:

Name Type Description Default
fig Figure

Optional existing Matplotlib Figure to draw into.

None

Yields:

Type Description
str

The string label "SIRV Trajectories (Largest Patch)".

Source code in src/laser/cholera/metapop/analyzer.py
def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
    """Yield one Matplotlib figure overlaying every SEIRV channel for the largest patch.

    Pulls the R-transposed series from `model.results` (so channels
    are indexed `[patch, tick]`) and plots all of `S`, `Isym`,
    `Iasym`, `R`, `V1`, `V2` for the single largest-by-initial-S
    patch.

    Args:
        fig: Optional existing Matplotlib `Figure` to draw into.

    Yields:
        The string label `"SIRV Trajectories (Largest Patch)"`.
    """
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="SIRV Trajectories (Largest Patch)") if fig is None else fig

    for ipatch in np.argsort(self.model.params.S_j_initial)[-1:]:
        for channel in ["S", "Isym", "Iasym", "R", "V1", "V2"]:
            # Transpose ticks (:) and location since results are transposed for R users.
            plt.plot(getattr(self.model.results, channel)[ipatch, :], label=f"{channel}")

    plt.xlabel("Tick")
    plt.ylabel("Population")
    plt.legend()

    yield "SIRV Trajectories (Largest Patch)"
    return

Census

Population-census component: maintains patches.N as the sum of all SEIRV compartments.

Attributes:

Name Type Description
model

The parent Model instance.

Source code in src/laser/cholera/metapop/census.py
class Census:
    """Population-census component: maintains `patches.N` as the sum of all SEIRV compartments.

    Attributes:
        model: The parent `Model` instance.
    """

    def __init__(self, model: "Model") -> None:
        """Allocate the `N` per-patch population vector.

        Args:
            model: The `Model` instance. Must have `patches` and
                `params` set up.

        Raises:
            AttributeError: When `model.patches` or `model.params` is
                missing.
        """
        self.model = model

        check_attr(model, "patches", "Census: model needs to have a 'patches' attribute.")
        model.patches.add_vector_property("N", length=model.params.nticks + 1, dtype=np.int32, default=0)
        check_attr(self.model, "params", "Census: model needs to have a 'params' attribute.")

        return

    def check(self):
        """Seed `N[0]` by running `__call__` with `tick=-1`.

        Slightly hacky: `__call__` writes into `N[tick + 1]`, so
        `tick=-1` ends up writing the initial population from the
        compartments that have already been seeded by their own
        `__init__` methods. Avoids duplicating the sum logic.
        """
        self(self.model, -1)  # a little hacky, but we need to set the initial population size

        return

    def __call__(self, model: "Model", tick: int) -> None:
        """Sum the SEIRV compartments at `tick + 1` into `patches.N[tick + 1]`.

        Compartments that are not present on `model.people` (e.g.
        `V1` / `V2` if `Vaccinated` was excluded) are silently skipped,
        making the component robust to alternative pipelines.

        Args:
            model: The parent `Model` instance.
            tick: Current simulation tick.

        Raises:
            AssertionError: When the resulting per-patch total is
                negative (indicates an upstream compartment underflowed).
        """
        for compartment in ["S", "E", "Isym", "Iasym", "R", "V1", "V2"]:
            if hasattr(model.people, compartment):
                model.patches.N[tick + 1] += getattr(model.people, compartment)[tick + 1]

        assert np.all(model.patches.N[tick + 1] >= 0), "N' should not go negative"

        return

    def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
        """Yield one Matplotlib figure of `N(t)` for the ten largest patches.

        Args:
            fig: Optional existing Matplotlib `Figure` to draw into.

        Yields:
            The string label `"Census (Total Population)"`.
        """
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Census (Total Population)") if fig is None else fig

        for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
            plt.plot(self.model.patches.N[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
        plt.xlabel("Tick")
        plt.ylabel("Total Population")
        plt.legend()

        yield "Census (Total Population)"
        return

model instance-attribute

model = model

__init__

__init__(model: Model) -> None

Allocate the N per-patch population vector.

Parameters:

Name Type Description Default
model Model

The Model instance. Must have patches and params set up.

required

Raises:

Type Description
AttributeError

When model.patches or model.params is missing.

Source code in src/laser/cholera/metapop/census.py
def __init__(self, model: "Model") -> None:
    """Allocate the `N` per-patch population vector.

    Args:
        model: The `Model` instance. Must have `patches` and
            `params` set up.

    Raises:
        AttributeError: When `model.patches` or `model.params` is
            missing.
    """
    self.model = model

    check_attr(model, "patches", "Census: model needs to have a 'patches' attribute.")
    model.patches.add_vector_property("N", length=model.params.nticks + 1, dtype=np.int32, default=0)
    check_attr(self.model, "params", "Census: model needs to have a 'params' attribute.")

    return

check

check()

Seed N[0] by running __call__ with tick=-1.

Slightly hacky: __call__ writes into N[tick + 1], so tick=-1 ends up writing the initial population from the compartments that have already been seeded by their own __init__ methods. Avoids duplicating the sum logic.

Source code in src/laser/cholera/metapop/census.py
def check(self):
    """Seed `N[0]` by running `__call__` with `tick=-1`.

    Slightly hacky: `__call__` writes into `N[tick + 1]`, so
    `tick=-1` ends up writing the initial population from the
    compartments that have already been seeded by their own
    `__init__` methods. Avoids duplicating the sum logic.
    """
    self(self.model, -1)  # a little hacky, but we need to set the initial population size

    return

__call__

__call__(model: Model, tick: int) -> None

Sum the SEIRV compartments at tick + 1 into patches.N[tick + 1].

Compartments that are not present on model.people (e.g. V1 / V2 if Vaccinated was excluded) are silently skipped, making the component robust to alternative pipelines.

Parameters:

Name Type Description Default
model Model

The parent Model instance.

required
tick int

Current simulation tick.

required

Raises:

Type Description
AssertionError

When the resulting per-patch total is negative (indicates an upstream compartment underflowed).

Source code in src/laser/cholera/metapop/census.py
def __call__(self, model: "Model", tick: int) -> None:
    """Sum the SEIRV compartments at `tick + 1` into `patches.N[tick + 1]`.

    Compartments that are not present on `model.people` (e.g.
    `V1` / `V2` if `Vaccinated` was excluded) are silently skipped,
    making the component robust to alternative pipelines.

    Args:
        model: The parent `Model` instance.
        tick: Current simulation tick.

    Raises:
        AssertionError: When the resulting per-patch total is
            negative (indicates an upstream compartment underflowed).
    """
    for compartment in ["S", "E", "Isym", "Iasym", "R", "V1", "V2"]:
        if hasattr(model.people, compartment):
            model.patches.N[tick + 1] += getattr(model.people, compartment)[tick + 1]

    assert np.all(model.patches.N[tick + 1] >= 0), "N' should not go negative"

    return

plot

plot(fig: Figure = None) -> Iterator[str]

Yield one Matplotlib figure of N(t) for the ten largest patches.

Parameters:

Name Type Description Default
fig Figure

Optional existing Matplotlib Figure to draw into.

None

Yields:

Type Description
str

The string label "Census (Total Population)".

Source code in src/laser/cholera/metapop/census.py
def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
    """Yield one Matplotlib figure of `N(t)` for the ten largest patches.

    Args:
        fig: Optional existing Matplotlib `Figure` to draw into.

    Yields:
        The string label `"Census (Total Population)"`.
    """
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Census (Total Population)") if fig is None else fig

    for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
        plt.plot(self.model.patches.N[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
    plt.xlabel("Tick")
    plt.ylabel("Total Population")
    plt.legend()

    yield "Census (Total Population)"
    return

DerivedValues

Computes end-of-run diagnostics: spatial hazard and coupling matrix.

Attributes:

Name Type Description
model

The parent Model instance.

Source code in src/laser/cholera/metapop/derivedvalues.py
class DerivedValues:
    """Computes end-of-run diagnostics: spatial hazard and coupling matrix.

    Attributes:
        model: The parent `Model` instance.
    """

    def __init__(self, model: "Model") -> None:
        """Allocate `spatial_hazard` and `coupling` arrays on `model.patches`.

        Args:
            model: The `Model` instance. Must have `patches` and
                `params` set up.

        Raises:
            AttributeError: When `model.patches` or `model.params` is
                missing.
        """
        self.model = model

        check_attr(model, "patches", "DerivedValues: model needs to have a 'patches' attribute.")
        check_attr(model, "params", "DerivedValues: model needs to have a 'params' attribute.")

        # There's no spatial hazard calculation at the start of the simulation, but we will allocate nticks + 1 to match other outputs.
        model.patches.add_vector_property("spatial_hazard", length=model.params.nticks + 1, dtype=np.float32, default=0.0)
        model.patches.add_array_property("coupling", shape=(model.patches.count, model.patches.count), dtype=np.float32, default=0.0)

        return

    def check(self):
        """Validate every upstream attribute and parameter the final-tick math needs.

        Verifies `model.people` has `S`/`Isym`/`Iasym`; `model.patches`
        has `N`/`beta_jt_human`/`pi_ij`; and `params` provides
        `beta_j0_hum`, `p`, and `tau_i`. These are populated by
        [`Susceptible`][laser.cholera.metapop.susceptible.Susceptible],
        [`Infectious`][laser.cholera.metapop.infectious.Infectious],
        [`Census`][laser.cholera.metapop.census.Census], and
        [`HumanToHuman`][laser.cholera.metapop.humantohuman.HumanToHuman]
        earlier in the pipeline.

        Raises:
            AttributeError: When `model.people` (with `S` / `Isym` /
                `Iasym`) or `model.patches` (with `N` / `beta_jt_human` /
                `pi_ij`) is missing.
            ValueError: When `params.beta_j0_hum`, `params.p`, or
                `params.tau_i` is missing.
        """
        check_attr(self.model, "people", "DerivedValues: model needs to have an 'people' attribute.")
        check_attr(self.model.people, "S", "DerivedValues: model.people needs to have 'S' attribute.")
        check_attr(self.model.people, "Isym", "DerivedValues: model.people needs to have 'Isym' attribute.")
        check_attr(self.model.people, "Iasym", "DerivedValues: model.people needs to have 'Iasym' attribute.")

        check_attr(self.model, "patches", "DerivedValues: model needs to have a 'patches' attribute.")
        check_attr(self.model.patches, "N", "DerivedValues: model.patches needs to have 'N' attribute.")
        check_attr(self.model.patches, "beta_jt_human", "DerivedValues: model.patches needs to have 'beta_jt_human' attribute.")
        check_attr(self.model.patches, "pi_ij", "DerivedValues: model.patches needs to have 'pi_ij' attribute.")

        check_key(self.model.params, "beta_j0_hum", "DerivedValues: model.params needs to have 'beta_j0_hum' attribute.")
        check_key(self.model.params, "p", "DerivedValues: model.params needs to have 'p' attribute.")
        check_key(self.model.params, "tau_i", "DerivedValues: model.params needs to have 'tau_i' attribute.")

        return

    def __call__(self, model: "Model", tick: int) -> None:
        r"""Calculate derived values for the model.

        Spatial hazard and coupling are calculated at the end of the
        simulation.

        Spatial hazard per location and tick:

        $$
        h(j,t) = \frac {\beta^{hum}_{jt} (1 - e^{-((1 - \tau_j) (S_{jt} / N_{jt})) \sum_{\forall i \ne j} \pi_{ij} \tau_i ((I^{sym}_{it} + I^{asym}_{it}) / N_{it})})} {1/(1 + \beta^{hum}_{jt}(1 - \tau_j) S_{jt})}
        $$

        Prevalence fraction and its time-average per location:

        $$
        y_{it} = \frac {I^{sym}_{it} + I^{asym}_{it}} {N_{it}}
        $$

        $$
        \bar y_{i} = \frac 1 T \sum_{t=1}^{T} y_{it}
        $$

        Inter-location coupling — Pearson correlation between prevalence
        fractions:

        $$
        C_{ij} = \frac { \sum_{t=1}^T {(y_{it} - \bar y_i) (y_{jt} - \bar y_j)} } { \sqrt {\sum_{t=1}^T {(y_{it} - \bar y_i)}^2} \sqrt {\sum_{t=1}^T {(y_{jt} - \bar y_j)}^2} }
        $$

        Equivalently:

        $$
        C_{ij} = \frac {(y_{it} - \bar y_{i}) (y_{jt} - \bar y_{j})} { \sqrt {\text{var}(y_{i}) \text{var}(y_{j})} }
        $$

        Args:
            model: The parent `Model` instance.
            tick: Current simulation tick. The computation is a no-op
                for every tick except the last
                (`model.params.nticks - 1`).
        """
        if tick == model.params.nticks - 1:
            calculate_spatial_hazard(
                model.params.nticks,
                model.patches.beta_jt_human.T,
                model.params.tau_i,
                model.people.S[1:, :].T,
                model.patches.N[1:, :].T,
                model.patches.pi_ij,
                model.people.Iasym[1:, :].T,
                model.people.Isym[1:, :].T,
                model.patches.spatial_hazard[1:, :].T,
            )

            calculate_coupling(model.people.Isym, model.people.Iasym, model.patches.N, model.patches.coupling)

        return

    def plot(self, fig: Figure | None = None) -> Iterator[str]:  # pragma: no cover
        """Yield one Matplotlib heatmap of `spatial_hazard` (patch × tick).

        Args:
            fig: Optional existing Matplotlib `Figure` to draw into.

        Yields:
            The string label `"Spatial Hazard by Location Over Time"`.
        """
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Spatial Hazard by Location Over Time") if fig is None else fig

        plt.imshow(self.model.patches.spatial_hazard.T, aspect="auto", cmap="Reds", interpolation="nearest")
        plt.colorbar(label="Spatial Hazard")
        plt.xlabel("Time (Days)")
        plt.ylabel("Location")
        plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

        yield "Spatial Hazard by Location Over Time"

        return

model instance-attribute

model = model

__init__

__init__(model: Model) -> None

Allocate spatial_hazard and coupling arrays on model.patches.

Parameters:

Name Type Description Default
model Model

The Model instance. Must have patches and params set up.

required

Raises:

Type Description
AttributeError

When model.patches or model.params is missing.

Source code in src/laser/cholera/metapop/derivedvalues.py
def __init__(self, model: "Model") -> None:
    """Allocate `spatial_hazard` and `coupling` arrays on `model.patches`.

    Args:
        model: The `Model` instance. Must have `patches` and
            `params` set up.

    Raises:
        AttributeError: When `model.patches` or `model.params` is
            missing.
    """
    self.model = model

    check_attr(model, "patches", "DerivedValues: model needs to have a 'patches' attribute.")
    check_attr(model, "params", "DerivedValues: model needs to have a 'params' attribute.")

    # There's no spatial hazard calculation at the start of the simulation, but we will allocate nticks + 1 to match other outputs.
    model.patches.add_vector_property("spatial_hazard", length=model.params.nticks + 1, dtype=np.float32, default=0.0)
    model.patches.add_array_property("coupling", shape=(model.patches.count, model.patches.count), dtype=np.float32, default=0.0)

    return

check

check()

Validate every upstream attribute and parameter the final-tick math needs.

Verifies model.people has S/Isym/Iasym; model.patches has N/beta_jt_human/pi_ij; and params provides beta_j0_hum, p, and tau_i. These are populated by Susceptible, Infectious, Census, and HumanToHuman earlier in the pipeline.

Raises:

Type Description
AttributeError

When model.people (with S / Isym / Iasym) or model.patches (with N / beta_jt_human / pi_ij) is missing.

ValueError

When params.beta_j0_hum, params.p, or params.tau_i is missing.

Source code in src/laser/cholera/metapop/derivedvalues.py
def check(self):
    """Validate every upstream attribute and parameter the final-tick math needs.

    Verifies `model.people` has `S`/`Isym`/`Iasym`; `model.patches`
    has `N`/`beta_jt_human`/`pi_ij`; and `params` provides
    `beta_j0_hum`, `p`, and `tau_i`. These are populated by
    [`Susceptible`][laser.cholera.metapop.susceptible.Susceptible],
    [`Infectious`][laser.cholera.metapop.infectious.Infectious],
    [`Census`][laser.cholera.metapop.census.Census], and
    [`HumanToHuman`][laser.cholera.metapop.humantohuman.HumanToHuman]
    earlier in the pipeline.

    Raises:
        AttributeError: When `model.people` (with `S` / `Isym` /
            `Iasym`) or `model.patches` (with `N` / `beta_jt_human` /
            `pi_ij`) is missing.
        ValueError: When `params.beta_j0_hum`, `params.p`, or
            `params.tau_i` is missing.
    """
    check_attr(self.model, "people", "DerivedValues: model needs to have an 'people' attribute.")
    check_attr(self.model.people, "S", "DerivedValues: model.people needs to have 'S' attribute.")
    check_attr(self.model.people, "Isym", "DerivedValues: model.people needs to have 'Isym' attribute.")
    check_attr(self.model.people, "Iasym", "DerivedValues: model.people needs to have 'Iasym' attribute.")

    check_attr(self.model, "patches", "DerivedValues: model needs to have a 'patches' attribute.")
    check_attr(self.model.patches, "N", "DerivedValues: model.patches needs to have 'N' attribute.")
    check_attr(self.model.patches, "beta_jt_human", "DerivedValues: model.patches needs to have 'beta_jt_human' attribute.")
    check_attr(self.model.patches, "pi_ij", "DerivedValues: model.patches needs to have 'pi_ij' attribute.")

    check_key(self.model.params, "beta_j0_hum", "DerivedValues: model.params needs to have 'beta_j0_hum' attribute.")
    check_key(self.model.params, "p", "DerivedValues: model.params needs to have 'p' attribute.")
    check_key(self.model.params, "tau_i", "DerivedValues: model.params needs to have 'tau_i' attribute.")

    return

__call__

__call__(model: Model, tick: int) -> None

Calculate derived values for the model.

Spatial hazard and coupling are calculated at the end of the simulation.

Spatial hazard per location and tick:

\[ h(j,t) = \frac {\beta^{hum}_{jt} (1 - e^{-((1 - \tau_j) (S_{jt} / N_{jt})) \sum_{\forall i \ne j} \pi_{ij} \tau_i ((I^{sym}_{it} + I^{asym}_{it}) / N_{it})})} {1/(1 + \beta^{hum}_{jt}(1 - \tau_j) S_{jt})} \]

Prevalence fraction and its time-average per location:

\[ y_{it} = \frac {I^{sym}_{it} + I^{asym}_{it}} {N_{it}} \]
\[ \bar y_{i} = \frac 1 T \sum_{t=1}^{T} y_{it} \]

Inter-location coupling — Pearson correlation between prevalence fractions:

\[ C_{ij} = \frac { \sum_{t=1}^T {(y_{it} - \bar y_i) (y_{jt} - \bar y_j)} } { \sqrt {\sum_{t=1}^T {(y_{it} - \bar y_i)}^2} \sqrt {\sum_{t=1}^T {(y_{jt} - \bar y_j)}^2} } \]

Equivalently:

\[ C_{ij} = \frac {(y_{it} - \bar y_{i}) (y_{jt} - \bar y_{j})} { \sqrt {\text{var}(y_{i}) \text{var}(y_{j})} } \]

Parameters:

Name Type Description Default
model Model

The parent Model instance.

required
tick int

Current simulation tick. The computation is a no-op for every tick except the last (model.params.nticks - 1).

required
Source code in src/laser/cholera/metapop/derivedvalues.py
def __call__(self, model: "Model", tick: int) -> None:
    r"""Calculate derived values for the model.

    Spatial hazard and coupling are calculated at the end of the
    simulation.

    Spatial hazard per location and tick:

    $$
    h(j,t) = \frac {\beta^{hum}_{jt} (1 - e^{-((1 - \tau_j) (S_{jt} / N_{jt})) \sum_{\forall i \ne j} \pi_{ij} \tau_i ((I^{sym}_{it} + I^{asym}_{it}) / N_{it})})} {1/(1 + \beta^{hum}_{jt}(1 - \tau_j) S_{jt})}
    $$

    Prevalence fraction and its time-average per location:

    $$
    y_{it} = \frac {I^{sym}_{it} + I^{asym}_{it}} {N_{it}}
    $$

    $$
    \bar y_{i} = \frac 1 T \sum_{t=1}^{T} y_{it}
    $$

    Inter-location coupling — Pearson correlation between prevalence
    fractions:

    $$
    C_{ij} = \frac { \sum_{t=1}^T {(y_{it} - \bar y_i) (y_{jt} - \bar y_j)} } { \sqrt {\sum_{t=1}^T {(y_{it} - \bar y_i)}^2} \sqrt {\sum_{t=1}^T {(y_{jt} - \bar y_j)}^2} }
    $$

    Equivalently:

    $$
    C_{ij} = \frac {(y_{it} - \bar y_{i}) (y_{jt} - \bar y_{j})} { \sqrt {\text{var}(y_{i}) \text{var}(y_{j})} }
    $$

    Args:
        model: The parent `Model` instance.
        tick: Current simulation tick. The computation is a no-op
            for every tick except the last
            (`model.params.nticks - 1`).
    """
    if tick == model.params.nticks - 1:
        calculate_spatial_hazard(
            model.params.nticks,
            model.patches.beta_jt_human.T,
            model.params.tau_i,
            model.people.S[1:, :].T,
            model.patches.N[1:, :].T,
            model.patches.pi_ij,
            model.people.Iasym[1:, :].T,
            model.people.Isym[1:, :].T,
            model.patches.spatial_hazard[1:, :].T,
        )

        calculate_coupling(model.people.Isym, model.people.Iasym, model.patches.N, model.patches.coupling)

    return

plot

plot(fig: Figure | None = None) -> Iterator[str]

Yield one Matplotlib heatmap of spatial_hazard (patch × tick).

Parameters:

Name Type Description Default
fig Figure | None

Optional existing Matplotlib Figure to draw into.

None

Yields:

Type Description
str

The string label "Spatial Hazard by Location Over Time".

Source code in src/laser/cholera/metapop/derivedvalues.py
def plot(self, fig: Figure | None = None) -> Iterator[str]:  # pragma: no cover
    """Yield one Matplotlib heatmap of `spatial_hazard` (patch × tick).

    Args:
        fig: Optional existing Matplotlib `Figure` to draw into.

    Yields:
        The string label `"Spatial Hazard by Location Over Time"`.
    """
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Spatial Hazard by Location Over Time") if fig is None else fig

    plt.imshow(self.model.patches.spatial_hazard.T, aspect="auto", cmap="Reds", interpolation="nearest")
    plt.colorbar(label="Spatial Hazard")
    plt.xlabel("Time (Days)")
    plt.ylabel("Location")
    plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

    yield "Spatial Hazard by Location Over Time"

    return

Environmental

Environmental-reservoir component: maintains patches.W per tick.

Attributes:

Name Type Description
model

The parent Model instance.

Source code in src/laser/cholera/metapop/environmental.py
class Environmental:
    """Environmental-reservoir component: maintains `patches.W` per tick.

    Attributes:
        model: The parent `Model` instance.
    """

    def __init__(self, model: "Model") -> None:
        """Allocate `W` / `delta_jt` and pre-compute the suitability-to-decay map.

        `delta_jt` is built once from `params.psi_jt` via
        [`map_suitability_to_decay`][laser.cholera.metapop.environmental.map_suitability_to_decay]
        (a Beta-CDF interpolator between `decay_days_short` and
        `decay_days_long`).

        Args:
            model: The `Model` instance. Must have `patches` and
                `params` with `psi_jt`, `decay_days_short`,
                `decay_days_long`, `decay_shape_1`, and `decay_shape_2`
                populated.

        Raises:
            AttributeError: When `model.patches` or `model.params` is
                missing.
            ValueError: When any of `params.psi_jt`, `decay_days_short`,
                `decay_days_long`, `decay_shape_1`, `decay_shape_2` is
                missing.
        """
        self.model = model

        check_attr(model, "patches", "Environmental: model needs to have a 'patches' attribute.")

        model.patches.add_vector_property("W", length=model.params.nticks + 1, dtype=np.float32, default=0.0)
        check_attr(model, "params", "Environmental: model needs to have a 'params' attribute.")
        check_key(model.params, "psi_jt", "Environmental: model params needs to have a 'psi_jt' (environmental contagion rate) parameter.")
        psi = model.params.psi_jt  # convenience
        # TODO - use newer laser_core with add_array_property and psi.shape
        model.patches.add_vector_property("delta_jt", length=psi.shape[0], dtype=np.float32, default=0.0)

        check_key(
            model.params,
            "decay_days_short",
            "Environmental: model params needs to have a 'decay_days_short' (maximum environmental decay) parameter.",
        )
        check_key(
            model.params, "decay_days_long", "Environmental: model params needs to have a 'decay_days_long' (minimum environmental decay) parameter."
        )
        check_key(
            self.model.params, "decay_shape_1", "Environmental: model params needs to have a 'decay_shape_1' (beta function parameter 1) parameter."
        )
        check_key(
            self.model.params, "decay_shape_2", "Environmental: model params needs to have a 'decay_shape_2' (beta function parameter 2) parameter."
        )

        model.patches.delta_jt[:, :] = map_suitability_to_decay(
            fast=model.params.decay_days_short,
            slow=model.params.decay_days_long,
            suitability=model.params.psi_jt,
            beta_a=model.params.decay_shape_1,
            beta_b=model.params.decay_shape_2,
        )

        return

    def check(self):
        """Validate `Isym` / `Iasym` are available and shedding parameters are present.

        Raises:
            AttributeError: When `model.people.Isym` or `.Iasym` is
                missing.
            ValueError: When `params.zeta_1`, `params.zeta_2`, or
                `params.theta_j` is missing.
        """
        check_attr(self.model, "people", "Environmental: model needs to have a 'people' attribute.")
        check_attr(self.model.people, "Isym", "Environmental: model people needs to have a 'Isym' (symptomatic) attribute.")
        check_attr(self.model.people, "Iasym", "Environmental: model people needs to have a 'Iasym' (asymptomatic) attribute.")
        check_key(self.model.params, "zeta_1", "Environmental: model params needs to have a 'zeta_1' (symptomatic shedding rate) parameter.")
        check_key(self.model.params, "zeta_2", "Environmental: model params needs to have a 'zeta_2' (asymptomatic shedding rate) parameter.")
        check_key(self.model.params, "theta_j", "Environmental: model params needs to have a 'theta_j' (fraction of population with WASH) attribute.")

        return

    def __call__(self, model: "Model", tick: int) -> None:
        """Advance `W` one tick: carry forward, decay, then shed from infectious cohorts.

        Decay is clamped not to exceed `W` so the reservoir never goes
        negative even on extreme Poisson draws. WASH coverage
        (`1 - theta_j`) attenuates the shed amount entering the reservoir.

        Args:
            model: The parent `Model` instance.
            tick: Current simulation tick.
        """
        W = model.patches.W[tick]
        W_next = model.patches.W[tick + 1]
        W_next[:] = W

        Isym = model.people.Isym[tick]
        Iasym = model.people.Iasym[tick]

        # -decay
        # Use np.minimum() to make sure we don't go negative
        decay = np.minimum(model.prng.poisson(model.patches.delta_jt[tick] * W), W).astype(W_next.dtype)
        W_next -= decay

        # +shedding from Isymptomatic
        shedding_sym = model.prng.poisson(model.params.zeta_1 * Isym).astype(W_next.dtype)
        W_next += (1 - model.params.theta_j) * shedding_sym

        # +shedding from Iasymptomatic
        shedding_asym = model.prng.poisson(model.params.zeta_2 * Iasym).astype(W_next.dtype)
        W_next += (1 - model.params.theta_j) * shedding_asym

        return

    def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
        """Yield three Matplotlib figures: reservoir trajectory, decay heatmap, suitability map.

        Args:
            fig: Optional existing Matplotlib `Figure` to draw into.

        Yields:
            Three labels in order: `"Environmental Reservoir"`,
            `"Environmental Decay Rate"`, `"Suitability to Decay Mapping"`.
        """
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Environmental Reservoir") if fig is None else fig

        for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
            plt.plot(self.model.patches.W[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
        plt.xlabel("Tick")
        plt.ylabel("Environmental Reservoir")
        plt.legend()

        yield "Environmental Reservoir"

        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Environmental Decay Rate") if fig is None else fig

        plt.imshow(self.model.patches.delta_jt.T, aspect="auto", cmap="viridis", interpolation="nearest")
        plt.colorbar(label="Environmental Decay Rate")
        plt.xlabel("Tick")
        plt.ylabel("Patch")
        plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

        yield "Environmental Decay Rate"

        title = "Suitability to Decay Mapping"
        _fig = plt.figure(figsize=(12, 9), dpi=128, num=title) if fig is None else fig

        x = np.linspace(0, 1, self.model.params.psi_jt.shape[0])
        y = map_suitability_to_decay(
            self.model.params.decay_days_short,
            self.model.params.decay_days_long,
            x,
            self.model.params.decay_shape_1,
            self.model.params.decay_shape_2,
        )
        plt.plot(x, y, label=f"{self.model.params.location_name[ipatch]}")
        plt.xlabel("psi_jt - suitability")
        plt.ylabel("delta_jt - decay rate")

        yield title
        return

model instance-attribute

model = model

__init__

__init__(model: Model) -> None

Allocate W / delta_jt and pre-compute the suitability-to-decay map.

delta_jt is built once from params.psi_jt via map_suitability_to_decay (a Beta-CDF interpolator between decay_days_short and decay_days_long).

Parameters:

Name Type Description Default
model Model

The Model instance. Must have patches and params with psi_jt, decay_days_short, decay_days_long, decay_shape_1, and decay_shape_2 populated.

required

Raises:

Type Description
AttributeError

When model.patches or model.params is missing.

ValueError

When any of params.psi_jt, decay_days_short, decay_days_long, decay_shape_1, decay_shape_2 is missing.

Source code in src/laser/cholera/metapop/environmental.py
def __init__(self, model: "Model") -> None:
    """Allocate `W` / `delta_jt` and pre-compute the suitability-to-decay map.

    `delta_jt` is built once from `params.psi_jt` via
    [`map_suitability_to_decay`][laser.cholera.metapop.environmental.map_suitability_to_decay]
    (a Beta-CDF interpolator between `decay_days_short` and
    `decay_days_long`).

    Args:
        model: The `Model` instance. Must have `patches` and
            `params` with `psi_jt`, `decay_days_short`,
            `decay_days_long`, `decay_shape_1`, and `decay_shape_2`
            populated.

    Raises:
        AttributeError: When `model.patches` or `model.params` is
            missing.
        ValueError: When any of `params.psi_jt`, `decay_days_short`,
            `decay_days_long`, `decay_shape_1`, `decay_shape_2` is
            missing.
    """
    self.model = model

    check_attr(model, "patches", "Environmental: model needs to have a 'patches' attribute.")

    model.patches.add_vector_property("W", length=model.params.nticks + 1, dtype=np.float32, default=0.0)
    check_attr(model, "params", "Environmental: model needs to have a 'params' attribute.")
    check_key(model.params, "psi_jt", "Environmental: model params needs to have a 'psi_jt' (environmental contagion rate) parameter.")
    psi = model.params.psi_jt  # convenience
    # TODO - use newer laser_core with add_array_property and psi.shape
    model.patches.add_vector_property("delta_jt", length=psi.shape[0], dtype=np.float32, default=0.0)

    check_key(
        model.params,
        "decay_days_short",
        "Environmental: model params needs to have a 'decay_days_short' (maximum environmental decay) parameter.",
    )
    check_key(
        model.params, "decay_days_long", "Environmental: model params needs to have a 'decay_days_long' (minimum environmental decay) parameter."
    )
    check_key(
        self.model.params, "decay_shape_1", "Environmental: model params needs to have a 'decay_shape_1' (beta function parameter 1) parameter."
    )
    check_key(
        self.model.params, "decay_shape_2", "Environmental: model params needs to have a 'decay_shape_2' (beta function parameter 2) parameter."
    )

    model.patches.delta_jt[:, :] = map_suitability_to_decay(
        fast=model.params.decay_days_short,
        slow=model.params.decay_days_long,
        suitability=model.params.psi_jt,
        beta_a=model.params.decay_shape_1,
        beta_b=model.params.decay_shape_2,
    )

    return

check

check()

Validate Isym / Iasym are available and shedding parameters are present.

Raises:

Type Description
AttributeError

When model.people.Isym or .Iasym is missing.

ValueError

When params.zeta_1, params.zeta_2, or params.theta_j is missing.

Source code in src/laser/cholera/metapop/environmental.py
def check(self):
    """Validate `Isym` / `Iasym` are available and shedding parameters are present.

    Raises:
        AttributeError: When `model.people.Isym` or `.Iasym` is
            missing.
        ValueError: When `params.zeta_1`, `params.zeta_2`, or
            `params.theta_j` is missing.
    """
    check_attr(self.model, "people", "Environmental: model needs to have a 'people' attribute.")
    check_attr(self.model.people, "Isym", "Environmental: model people needs to have a 'Isym' (symptomatic) attribute.")
    check_attr(self.model.people, "Iasym", "Environmental: model people needs to have a 'Iasym' (asymptomatic) attribute.")
    check_key(self.model.params, "zeta_1", "Environmental: model params needs to have a 'zeta_1' (symptomatic shedding rate) parameter.")
    check_key(self.model.params, "zeta_2", "Environmental: model params needs to have a 'zeta_2' (asymptomatic shedding rate) parameter.")
    check_key(self.model.params, "theta_j", "Environmental: model params needs to have a 'theta_j' (fraction of population with WASH) attribute.")

    return

__call__

__call__(model: Model, tick: int) -> None

Advance W one tick: carry forward, decay, then shed from infectious cohorts.

Decay is clamped not to exceed W so the reservoir never goes negative even on extreme Poisson draws. WASH coverage (1 - theta_j) attenuates the shed amount entering the reservoir.

Parameters:

Name Type Description Default
model Model

The parent Model instance.

required
tick int

Current simulation tick.

required
Source code in src/laser/cholera/metapop/environmental.py
def __call__(self, model: "Model", tick: int) -> None:
    """Advance `W` one tick: carry forward, decay, then shed from infectious cohorts.

    Decay is clamped not to exceed `W` so the reservoir never goes
    negative even on extreme Poisson draws. WASH coverage
    (`1 - theta_j`) attenuates the shed amount entering the reservoir.

    Args:
        model: The parent `Model` instance.
        tick: Current simulation tick.
    """
    W = model.patches.W[tick]
    W_next = model.patches.W[tick + 1]
    W_next[:] = W

    Isym = model.people.Isym[tick]
    Iasym = model.people.Iasym[tick]

    # -decay
    # Use np.minimum() to make sure we don't go negative
    decay = np.minimum(model.prng.poisson(model.patches.delta_jt[tick] * W), W).astype(W_next.dtype)
    W_next -= decay

    # +shedding from Isymptomatic
    shedding_sym = model.prng.poisson(model.params.zeta_1 * Isym).astype(W_next.dtype)
    W_next += (1 - model.params.theta_j) * shedding_sym

    # +shedding from Iasymptomatic
    shedding_asym = model.prng.poisson(model.params.zeta_2 * Iasym).astype(W_next.dtype)
    W_next += (1 - model.params.theta_j) * shedding_asym

    return

plot

plot(fig: Figure = None) -> Iterator[str]

Yield three Matplotlib figures: reservoir trajectory, decay heatmap, suitability map.

Parameters:

Name Type Description Default
fig Figure

Optional existing Matplotlib Figure to draw into.

None

Yields:

Type Description
str

Three labels in order: "Environmental Reservoir",

str

"Environmental Decay Rate", "Suitability to Decay Mapping".

Source code in src/laser/cholera/metapop/environmental.py
def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
    """Yield three Matplotlib figures: reservoir trajectory, decay heatmap, suitability map.

    Args:
        fig: Optional existing Matplotlib `Figure` to draw into.

    Yields:
        Three labels in order: `"Environmental Reservoir"`,
        `"Environmental Decay Rate"`, `"Suitability to Decay Mapping"`.
    """
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Environmental Reservoir") if fig is None else fig

    for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
        plt.plot(self.model.patches.W[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
    plt.xlabel("Tick")
    plt.ylabel("Environmental Reservoir")
    plt.legend()

    yield "Environmental Reservoir"

    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Environmental Decay Rate") if fig is None else fig

    plt.imshow(self.model.patches.delta_jt.T, aspect="auto", cmap="viridis", interpolation="nearest")
    plt.colorbar(label="Environmental Decay Rate")
    plt.xlabel("Tick")
    plt.ylabel("Patch")
    plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

    yield "Environmental Decay Rate"

    title = "Suitability to Decay Mapping"
    _fig = plt.figure(figsize=(12, 9), dpi=128, num=title) if fig is None else fig

    x = np.linspace(0, 1, self.model.params.psi_jt.shape[0])
    y = map_suitability_to_decay(
        self.model.params.decay_days_short,
        self.model.params.decay_days_long,
        x,
        self.model.params.decay_shape_1,
        self.model.params.decay_shape_2,
    )
    plt.plot(x, y, label=f"{self.model.params.location_name[ipatch]}")
    plt.xlabel("psi_jt - suitability")
    plt.ylabel("delta_jt - decay rate")

    yield title
    return

EnvToHuman

Environmental transmission component: turns reservoir W into new S -> E infections.

Attributes:

Name Type Description
model

The parent Model instance.

Source code in src/laser/cholera/metapop/envtohuman.py
class EnvToHuman:
    """Environmental transmission component: turns reservoir `W` into new `S -> E` infections.

    Attributes:
        model: The parent `Model` instance.
    """

    def __init__(self, model: "Model") -> None:
        """Allocate `Psi` and bake the `beta_jt_env` seasonality matrix.

        `beta_jt_env` is computed once at construction time from
        `params.psi_jt` (deviation-from-mean suitability) and
        `params.beta_j0_env` (baseline) and is constant across the run.

        Args:
            model: The `Model` instance. Must have `people`, `patches`,
                and `params` with `psi_jt`, `beta_j0_env` populated.

        Raises:
            AttributeError: When `model.people` or `model.params` is
                missing.
            ValueError: When `params.psi_jt` is missing.
            AssertionError: When the allocated `beta_jt_env` shape
                disagrees with the provided `psi_jt` / `beta_j0_env`
                shapes (these are invariant checks that remain).
        """
        self.model = model

        check_attr(model, "people", "EnvToHuman: model needs to have a 'people' attribute.")
        model.patches.add_vector_property("Psi", length=model.params.nticks + 1, dtype=np.float32, default=np.float32(0.0))

        check_attr(model, "params", "EnvToHuman: model needs to have a 'params' attribute.")
        check_key(model.params, "psi_jt", "EnvToHuman: model params needs to have a 'psi_jt' (environmental contamination rate) parameter.")

        psi = model.params.psi_jt  # convenience
        # TODO - use newer laser_core with add_array_property and psi.shape
        model.patches.add_vector_property("beta_jt_env", length=psi.shape[0], dtype=np.float32, default=0.0)
        assert model.patches.beta_jt_env.shape == model.params.psi_jt.shape
        assert model.params.beta_j0_env.shape[0] == model.patches.beta_jt_env.shape[1]
        psi_bar = psi.mean(axis=0, keepdims=True)
        model.patches.beta_jt_env[:, :] = model.params.beta_j0_env.T * (1.0 + (psi - psi_bar) / psi_bar)

        model.patches.add_vector_property("incidence_env", length=model.params.nticks + 1, dtype=np.int32, default=0)

        if not hasattr(model.patches, "incidence"):
            model.patches.add_vector_property("incidence", length=model.params.nticks + 1, dtype=np.int32, default=0)

        return

    def check(self):
        """Validate the consumer-side state and transmission parameters.

        Asserts that `model.people.S` and `.E` exist, that
        `model.patches.W` exists (allocated by `Environmental`), and
        that `params` provides `tau_i`, `theta_j`, and `kappa`.

        Raises:
            AttributeError: When `model.people.S`, `.E`, `model.patches`,
                or `model.patches.W` is missing.
            ValueError: When `params.tau_i`, `theta_j`, or `kappa` is
                missing.
        """
        check_attr(self.model.people, "S", "EnvToHuman: model people needs to have a 'S' (susceptible) attribute.")
        check_attr(self.model.people, "E", "EnvToHuman: model people needs to have a 'E' (exposed) attribute.")

        check_attr(self.model, "patches", "EnvToHuman: model needs to have a 'patches' attribute.")
        check_attr(self.model.patches, "W", "EnvToHuman: model patches needs to have a 'W' (environmental) attribute.")

        check_key(self.model.params, "tau_i", "EnvToHuman: model params needs to have a 'tau_i' (emmigration probability) parameter.")
        check_key(self.model.params, "theta_j", "EnvToHuman: model params needs to have a 'theta_j' (fraction of population with WASH) attribute.")
        check_key(self.model.params, "kappa", "EnvToHuman: model params needs to have a 'kappa' (environmental transmission rate) parameter.")

        return

    def __call__(self, model: "Model", tick: int) -> None:
        """Compute environmental force-of-infection `Psi` and convert `S -> E`.

        `Psi[tick + 1] = beta_jt_env[tick] * (1 - theta_j) * W /
        (kappa + W)`. New infections drawn from `Binomial(S_next,
        1 - exp(-Psi))`, where `S_next` is the susceptible count *after*
        natural mortality and any human-to-human force-of-infection has
        already been applied earlier in the tick.

        Args:
            model: The parent `Model` instance.
            tick: Current simulation tick.

        Raises:
            AssertionError: When the post-infection susceptible
                population goes negative.
        """
        Psi = model.patches.Psi[tick + 1]
        W = model.patches.W[tick]
        tau_i = model.params.tau_i
        local_frac = 1 - tau_i

        non_wash = (1 - model.params.theta_j) * W
        seasonal = model.patches.beta_jt_env[tick] * non_wash
        denominator = model.params.kappa + W
        normalized = seasonal / denominator
        Psi[:] = normalized

        # PsiS
        S_next = model.people.S[tick + 1]
        E_next = model.people.E[tick + 1]
        # Use S_next here since some S will have been removed by natural mortality and by human-to-human transmission
        local_s = np.round(local_frac * S_next).astype(S_next.dtype)
        new_infections = model.prng.binomial(local_s, -np.expm1(-Psi)).astype(S_next.dtype)
        S_next -= new_infections
        E_next += new_infections
        model.patches.incidence_env[tick + 1] += new_infections
        model.patches.incidence[tick + 1] += new_infections

        assert np.all(S_next >= 0), f"Negative susceptible populations at tick {tick + 1}.\n\t{S_next=}"

        return

    def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
        """Yield one Matplotlib figure of `Psi(t)` for the ten largest patches.

        Args:
            fig: Optional existing Matplotlib `Figure` to draw into.

        Yields:
            The string label `"Environmental Transmission Rate"`.
        """
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Environmental Transmission Rate") if fig is None else fig

        for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
            plt.plot(self.model.patches.Psi[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
        plt.xlabel("Tick")
        plt.ylabel("Environmental Transmission Rate")
        plt.legend()

        yield "Environmental Transmission Rate"
        return

model instance-attribute

model = model

__init__

__init__(model: Model) -> None

Allocate Psi and bake the beta_jt_env seasonality matrix.

beta_jt_env is computed once at construction time from params.psi_jt (deviation-from-mean suitability) and params.beta_j0_env (baseline) and is constant across the run.

Parameters:

Name Type Description Default
model Model

The Model instance. Must have people, patches, and params with psi_jt, beta_j0_env populated.

required

Raises:

Type Description
AttributeError

When model.people or model.params is missing.

ValueError

When params.psi_jt is missing.

AssertionError

When the allocated beta_jt_env shape disagrees with the provided psi_jt / beta_j0_env shapes (these are invariant checks that remain).

Source code in src/laser/cholera/metapop/envtohuman.py
def __init__(self, model: "Model") -> None:
    """Allocate `Psi` and bake the `beta_jt_env` seasonality matrix.

    `beta_jt_env` is computed once at construction time from
    `params.psi_jt` (deviation-from-mean suitability) and
    `params.beta_j0_env` (baseline) and is constant across the run.

    Args:
        model: The `Model` instance. Must have `people`, `patches`,
            and `params` with `psi_jt`, `beta_j0_env` populated.

    Raises:
        AttributeError: When `model.people` or `model.params` is
            missing.
        ValueError: When `params.psi_jt` is missing.
        AssertionError: When the allocated `beta_jt_env` shape
            disagrees with the provided `psi_jt` / `beta_j0_env`
            shapes (these are invariant checks that remain).
    """
    self.model = model

    check_attr(model, "people", "EnvToHuman: model needs to have a 'people' attribute.")
    model.patches.add_vector_property("Psi", length=model.params.nticks + 1, dtype=np.float32, default=np.float32(0.0))

    check_attr(model, "params", "EnvToHuman: model needs to have a 'params' attribute.")
    check_key(model.params, "psi_jt", "EnvToHuman: model params needs to have a 'psi_jt' (environmental contamination rate) parameter.")

    psi = model.params.psi_jt  # convenience
    # TODO - use newer laser_core with add_array_property and psi.shape
    model.patches.add_vector_property("beta_jt_env", length=psi.shape[0], dtype=np.float32, default=0.0)
    assert model.patches.beta_jt_env.shape == model.params.psi_jt.shape
    assert model.params.beta_j0_env.shape[0] == model.patches.beta_jt_env.shape[1]
    psi_bar = psi.mean(axis=0, keepdims=True)
    model.patches.beta_jt_env[:, :] = model.params.beta_j0_env.T * (1.0 + (psi - psi_bar) / psi_bar)

    model.patches.add_vector_property("incidence_env", length=model.params.nticks + 1, dtype=np.int32, default=0)

    if not hasattr(model.patches, "incidence"):
        model.patches.add_vector_property("incidence", length=model.params.nticks + 1, dtype=np.int32, default=0)

    return

check

check()

Validate the consumer-side state and transmission parameters.

Asserts that model.people.S and .E exist, that model.patches.W exists (allocated by Environmental), and that params provides tau_i, theta_j, and kappa.

Raises:

Type Description
AttributeError

When model.people.S, .E, model.patches, or model.patches.W is missing.

ValueError

When params.tau_i, theta_j, or kappa is missing.

Source code in src/laser/cholera/metapop/envtohuman.py
def check(self):
    """Validate the consumer-side state and transmission parameters.

    Asserts that `model.people.S` and `.E` exist, that
    `model.patches.W` exists (allocated by `Environmental`), and
    that `params` provides `tau_i`, `theta_j`, and `kappa`.

    Raises:
        AttributeError: When `model.people.S`, `.E`, `model.patches`,
            or `model.patches.W` is missing.
        ValueError: When `params.tau_i`, `theta_j`, or `kappa` is
            missing.
    """
    check_attr(self.model.people, "S", "EnvToHuman: model people needs to have a 'S' (susceptible) attribute.")
    check_attr(self.model.people, "E", "EnvToHuman: model people needs to have a 'E' (exposed) attribute.")

    check_attr(self.model, "patches", "EnvToHuman: model needs to have a 'patches' attribute.")
    check_attr(self.model.patches, "W", "EnvToHuman: model patches needs to have a 'W' (environmental) attribute.")

    check_key(self.model.params, "tau_i", "EnvToHuman: model params needs to have a 'tau_i' (emmigration probability) parameter.")
    check_key(self.model.params, "theta_j", "EnvToHuman: model params needs to have a 'theta_j' (fraction of population with WASH) attribute.")
    check_key(self.model.params, "kappa", "EnvToHuman: model params needs to have a 'kappa' (environmental transmission rate) parameter.")

    return

__call__

__call__(model: Model, tick: int) -> None

Compute environmental force-of-infection Psi and convert S -> E.

Psi[tick + 1] = beta_jt_env[tick] * (1 - theta_j) * W / (kappa + W). New infections drawn from Binomial(S_next, 1 - exp(-Psi)), where S_next is the susceptible count after natural mortality and any human-to-human force-of-infection has already been applied earlier in the tick.

Parameters:

Name Type Description Default
model Model

The parent Model instance.

required
tick int

Current simulation tick.

required

Raises:

Type Description
AssertionError

When the post-infection susceptible population goes negative.

Source code in src/laser/cholera/metapop/envtohuman.py
def __call__(self, model: "Model", tick: int) -> None:
    """Compute environmental force-of-infection `Psi` and convert `S -> E`.

    `Psi[tick + 1] = beta_jt_env[tick] * (1 - theta_j) * W /
    (kappa + W)`. New infections drawn from `Binomial(S_next,
    1 - exp(-Psi))`, where `S_next` is the susceptible count *after*
    natural mortality and any human-to-human force-of-infection has
    already been applied earlier in the tick.

    Args:
        model: The parent `Model` instance.
        tick: Current simulation tick.

    Raises:
        AssertionError: When the post-infection susceptible
            population goes negative.
    """
    Psi = model.patches.Psi[tick + 1]
    W = model.patches.W[tick]
    tau_i = model.params.tau_i
    local_frac = 1 - tau_i

    non_wash = (1 - model.params.theta_j) * W
    seasonal = model.patches.beta_jt_env[tick] * non_wash
    denominator = model.params.kappa + W
    normalized = seasonal / denominator
    Psi[:] = normalized

    # PsiS
    S_next = model.people.S[tick + 1]
    E_next = model.people.E[tick + 1]
    # Use S_next here since some S will have been removed by natural mortality and by human-to-human transmission
    local_s = np.round(local_frac * S_next).astype(S_next.dtype)
    new_infections = model.prng.binomial(local_s, -np.expm1(-Psi)).astype(S_next.dtype)
    S_next -= new_infections
    E_next += new_infections
    model.patches.incidence_env[tick + 1] += new_infections
    model.patches.incidence[tick + 1] += new_infections

    assert np.all(S_next >= 0), f"Negative susceptible populations at tick {tick + 1}.\n\t{S_next=}"

    return

plot

plot(fig: Figure = None) -> Iterator[str]

Yield one Matplotlib figure of Psi(t) for the ten largest patches.

Parameters:

Name Type Description Default
fig Figure

Optional existing Matplotlib Figure to draw into.

None

Yields:

Type Description
str

The string label "Environmental Transmission Rate".

Source code in src/laser/cholera/metapop/envtohuman.py
def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
    """Yield one Matplotlib figure of `Psi(t)` for the ten largest patches.

    Args:
        fig: Optional existing Matplotlib `Figure` to draw into.

    Yields:
        The string label `"Environmental Transmission Rate"`.
    """
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Environmental Transmission Rate") if fig is None else fig

    for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
        plt.plot(self.model.patches.Psi[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
    plt.xlabel("Tick")
    plt.ylabel("Environmental Transmission Rate")
    plt.legend()

    yield "Environmental Transmission Rate"
    return

Exposed

Exposed compartment: tracks E_j(t) and bleeds off non-disease deaths each tick.

Attributes:

Name Type Description
model

The parent Model instance.

Source code in src/laser/cholera/metapop/exposed.py
class Exposed:
    """Exposed compartment: tracks `E_j(t)` and bleeds off non-disease deaths each tick.

    Attributes:
        model: The parent `Model` instance.
    """

    def __init__(self, model: "Model"):
        """Allocate the `E` state vector and seed it from `E_j_initial`.

        Args:
            model: The `Model` instance. Must already have `people` and
                `params` set up, with `params.E_j_initial` populated.

        Raises:
            AttributeError: When `model` is missing `people` or
                `params`.
            ValueError: When `params.E_j_initial` is missing.
        """
        self.model = model

        check_attr(model, "people", "Exposed: model needs to have a 'people' attribute.")
        model.people.add_vector_property("E", length=model.params.nticks + 1, dtype=np.int32, default=0)

        check_attr(self.model, "params", "Exposed: model needs to have a 'params' attribute.")
        check_key(self.model.params, "E_j_initial", "Exposed: model params needs to have a 'E_j_initial' parameter.")

        model.people.E[0] = model.params.E_j_initial

        return

    def check(self):
        """Validate the `iota` progression-rate parameter and ensure shared bookkeeping is allocated.

        Raises:
            ValueError: When `params.iota` is missing.
        """
        # Don't bother checking for model.params, we did that in __init__()
        check_key(self.model.params, "iota", "Exposed: model params needs to have a 'iota' (progression rate) parameter.")
        if not hasattr(self.model.patches, "non_disease_deaths"):
            self.model.patches.add_vector_property("non_disease_deaths", length=self.model.params.nticks + 1, dtype=np.int32, default=0)
        # PERF: install `model.patches.non_disease_death_prob_jt` (the
        # `1 - exp(-d_jt)` cache) idempotently if no earlier component has.
        # Lets each consumer be exercised in isolation; the cache is built
        # exactly once across the pipeline.
        if not hasattr(self.model.patches, "non_disease_death_prob_jt"):
            self.model.patches.add_vector_property("non_disease_death_prob_jt", length=self.model.params.d_jt.shape[0], dtype=np.float32, default=0.0)
            self.model.patches.non_disease_death_prob_jt[:] = -np.expm1(-self.model.params.d_jt)

        return

    def __call__(self, model: "Model", tick: int) -> None:
        """Advance `E` from `tick` to `tick + 1`: carry forward, then remove non-disease deaths.

        Progression `E -> Isym / Iasym` (governed by `iota` and `sigma`)
        is handled by [`Infectious`][laser.cholera.metapop.infectious.Infectious];
        this method only applies natural mortality from `d_jt`.

        Args:
            model: The parent `Model` instance.
            tick: Current simulation tick.
        """
        E_next = model.people.E[tick + 1]
        E = model.people.E[tick]
        E_next[:] = E

        # Do non-disease mortality first
        # PERF: `model.patches.non_disease_death_prob_jt[tick]` is the pre-computed
        # and cached `-np.expm1(-model.params.d_jt[tick])`.
        # non_disease_deaths = model.prng.binomial(E, -np.expm1(-model.params.d_jt[tick])).astype(E_next.dtype)
        non_disease_deaths = model.prng.binomial(E, model.patches.non_disease_death_prob_jt[tick]).astype(E_next.dtype)
        E_next -= non_disease_deaths
        model.patches.non_disease_deaths[tick] += non_disease_deaths

        return

    def plot(self, fig: Figure | None = None) -> Iterator[str]:  # pragma: no cover
        """Yield a single Matplotlib figure of `E(t)` for the ten largest patches.

        Args:
            fig: Optional existing Matplotlib `Figure` to draw into.

        Yields:
            The string label `"Exposed"`.
        """
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Exposed") if fig is None else fig

        for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
            plt.plot(self.model.people.E[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
        plt.xlabel("Tick")
        plt.ylabel("Exposed")
        plt.legend()

        yield "Exposed"
        return

model instance-attribute

model = model

__init__

__init__(model: Model)

Allocate the E state vector and seed it from E_j_initial.

Parameters:

Name Type Description Default
model Model

The Model instance. Must already have people and params set up, with params.E_j_initial populated.

required

Raises:

Type Description
AttributeError

When model is missing people or params.

ValueError

When params.E_j_initial is missing.

Source code in src/laser/cholera/metapop/exposed.py
def __init__(self, model: "Model"):
    """Allocate the `E` state vector and seed it from `E_j_initial`.

    Args:
        model: The `Model` instance. Must already have `people` and
            `params` set up, with `params.E_j_initial` populated.

    Raises:
        AttributeError: When `model` is missing `people` or
            `params`.
        ValueError: When `params.E_j_initial` is missing.
    """
    self.model = model

    check_attr(model, "people", "Exposed: model needs to have a 'people' attribute.")
    model.people.add_vector_property("E", length=model.params.nticks + 1, dtype=np.int32, default=0)

    check_attr(self.model, "params", "Exposed: model needs to have a 'params' attribute.")
    check_key(self.model.params, "E_j_initial", "Exposed: model params needs to have a 'E_j_initial' parameter.")

    model.people.E[0] = model.params.E_j_initial

    return

check

check()

Validate the iota progression-rate parameter and ensure shared bookkeeping is allocated.

Raises:

Type Description
ValueError

When params.iota is missing.

Source code in src/laser/cholera/metapop/exposed.py
def check(self):
    """Validate the `iota` progression-rate parameter and ensure shared bookkeeping is allocated.

    Raises:
        ValueError: When `params.iota` is missing.
    """
    # Don't bother checking for model.params, we did that in __init__()
    check_key(self.model.params, "iota", "Exposed: model params needs to have a 'iota' (progression rate) parameter.")
    if not hasattr(self.model.patches, "non_disease_deaths"):
        self.model.patches.add_vector_property("non_disease_deaths", length=self.model.params.nticks + 1, dtype=np.int32, default=0)
    # PERF: install `model.patches.non_disease_death_prob_jt` (the
    # `1 - exp(-d_jt)` cache) idempotently if no earlier component has.
    # Lets each consumer be exercised in isolation; the cache is built
    # exactly once across the pipeline.
    if not hasattr(self.model.patches, "non_disease_death_prob_jt"):
        self.model.patches.add_vector_property("non_disease_death_prob_jt", length=self.model.params.d_jt.shape[0], dtype=np.float32, default=0.0)
        self.model.patches.non_disease_death_prob_jt[:] = -np.expm1(-self.model.params.d_jt)

    return

__call__

__call__(model: Model, tick: int) -> None

Advance E from tick to tick + 1: carry forward, then remove non-disease deaths.

Progression E -> Isym / Iasym (governed by iota and sigma) is handled by Infectious; this method only applies natural mortality from d_jt.

Parameters:

Name Type Description Default
model Model

The parent Model instance.

required
tick int

Current simulation tick.

required
Source code in src/laser/cholera/metapop/exposed.py
def __call__(self, model: "Model", tick: int) -> None:
    """Advance `E` from `tick` to `tick + 1`: carry forward, then remove non-disease deaths.

    Progression `E -> Isym / Iasym` (governed by `iota` and `sigma`)
    is handled by [`Infectious`][laser.cholera.metapop.infectious.Infectious];
    this method only applies natural mortality from `d_jt`.

    Args:
        model: The parent `Model` instance.
        tick: Current simulation tick.
    """
    E_next = model.people.E[tick + 1]
    E = model.people.E[tick]
    E_next[:] = E

    # Do non-disease mortality first
    # PERF: `model.patches.non_disease_death_prob_jt[tick]` is the pre-computed
    # and cached `-np.expm1(-model.params.d_jt[tick])`.
    # non_disease_deaths = model.prng.binomial(E, -np.expm1(-model.params.d_jt[tick])).astype(E_next.dtype)
    non_disease_deaths = model.prng.binomial(E, model.patches.non_disease_death_prob_jt[tick]).astype(E_next.dtype)
    E_next -= non_disease_deaths
    model.patches.non_disease_deaths[tick] += non_disease_deaths

    return

plot

plot(fig: Figure | None = None) -> Iterator[str]

Yield a single Matplotlib figure of E(t) for the ten largest patches.

Parameters:

Name Type Description Default
fig Figure | None

Optional existing Matplotlib Figure to draw into.

None

Yields:

Type Description
str

The string label "Exposed".

Source code in src/laser/cholera/metapop/exposed.py
def plot(self, fig: Figure | None = None) -> Iterator[str]:  # pragma: no cover
    """Yield a single Matplotlib figure of `E(t)` for the ten largest patches.

    Args:
        fig: Optional existing Matplotlib `Figure` to draw into.

    Yields:
        The string label `"Exposed"`.
    """
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Exposed") if fig is None else fig

    for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
        plt.plot(self.model.people.E[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
    plt.xlabel("Tick")
    plt.ylabel("Exposed")
    plt.legend()

    yield "Exposed"
    return

HumanToHuman

Direct (human-to-human) transmission component for the metapop pipeline.

Owns the per-patch force-of-infection vector patches.Lambda, the spatial-connectivity matrix patches.pi_ij, and the seasonality matrix patches.beta_jt_human.

Attributes:

Name Type Description
model

The parent Model instance.

Source code in src/laser/cholera/metapop/humantohuman.py
class HumanToHuman:
    """Direct (human-to-human) transmission component for the metapop pipeline.

    Owns the per-patch force-of-infection vector `patches.Lambda`, the
    spatial-connectivity matrix `patches.pi_ij`, and the seasonality
    matrix `patches.beta_jt_human`.

    Attributes:
        model: The parent `Model` instance.
    """

    def __init__(self, model: "Model") -> None:
        """Allocate `Lambda`, build `pi_ij` from lat/long, and bake the seasonality matrix.

        `pi_ij` is computed once via
        [`get_pi_from_lat_long`][laser.cholera.metapop.utils.get_pi_from_lat_long]
        (gravity model), and `beta_jt_human` once via
        [`get_daily_seasonality`][laser.cholera.metapop.utils.get_daily_seasonality]
        (Fourier sum) — neither changes during the run.

        Args:
            model: The `Model` instance. Must have `patches`, `people`,
                and `params` set up, with `latitude`, `longitude`, the
                seasonality coefficients (`a_*_j`, `b_*_j`, `p`), and
                the mobility parameters (`mobility_omega`,
                `mobility_gamma`) populated.

        Raises:
            AttributeError: When `model.patches` is missing.
            ValueError: When any of the seasonality / mobility parameters
                (`latitude`, `longitude`, `mobility_omega`,
                `mobility_gamma`, `a_*_j`, `b_*_j`, `p`) is missing.
        """
        self.model = model

        check_attr(model, "patches", "HumanToHuman: model needs to have a 'patches' attribute.")
        model.patches.add_vector_property("Lambda", length=model.params.nticks + 1, dtype=np.float32, default=0.0)

        check_key(self.model.params, "latitude", "HumanToHuman: model params needs to have a 'latitude' (location latitude) parameter.")
        check_key(self.model.params, "longitude", "HumanToHuman: model params needs to have a 'longitude' (location longitude) parameter.")
        check_key(self.model.params, "mobility_omega", "HumanToHuman: model params needs to have a 'mobility_omega' (mobility) parameter.")
        check_key(self.model.params, "mobility_gamma", "HumanToHuman: model params needs to have a 'mobility_gamma' (mobility) parameter.")

        model.patches.add_array_property("pi_ij", (model.patches.count, model.patches.count), dtype=np.float32, default=0.0)
        model.patches.pi_ij[:, :] = get_pi_from_lat_long(model.params)

        check_key(self.model.params, "a_1_j", "HumanToHuman: model params needs to have a 'a_1_j' (seasonality) parameter.")
        check_key(self.model.params, "b_1_j", "HumanToHuman: model params needs to have a 'b_1_j' (seasonality) parameter.")
        check_key(self.model.params, "a_2_j", "HumanToHuman: model params needs to have a 'a_2_j' (seasonality) parameter.")
        check_key(self.model.params, "b_2_j", "HumanToHuman: model params needs to have a 'b_2_j' (seasonality) parameter.")
        check_key(self.model.params, "p", "HumanToHuman: model params needs to have a 'p' (seasonality pahse) parameter.")

        model.patches.add_array_property("beta_jt_human", (model.params.nticks, model.patches.count), dtype=np.float32, default=0.0)
        model.patches.beta_jt_human[:, :] = get_daily_seasonality(model.params)

        model.patches.add_vector_property("incidence_human", length=model.params.nticks + 1, dtype=np.int32, default=0)

        if not hasattr(model.patches, "incidence"):
            model.patches.add_vector_property("incidence", length=model.params.nticks + 1, dtype=np.int32, default=0)

        return

    def check(self):
        """Validate the consumer-side compartments and transmission parameters.

        Asserts that `model.people` has `Isym`, `Iasym`, `S`, `E`;
        `model.patches.N` exists; and `params` provides `tau_i`,
        `beta_j0_hum`, `alpha_1`, and `alpha_2`.

        Raises:
            AttributeError: When `model`, `model.people` (with `Isym` /
                `Iasym` / `S` / `E`), or `model.patches.N` is missing.
            ValueError: When `params.tau_i`, `beta_j0_hum`, `alpha_1`, or
                `alpha_2` is missing.
        """
        check_attr(self.model, "people", "HumanToHuman: model needs to have a 'people' attribute.")
        check_attr(self.model.people, "Isym", "HumanToHuman: model people needs to have a 'Isym' (symptomatic) attribute.")
        check_attr(self.model.people, "Iasym", "HumanToHuman: model people needs to have a 'Iasym' (asymptomatic) attribute.")
        check_attr(self.model.people, "S", "HumanToHuman: model people needs to have a 'S' (susceptible) attribute.")
        check_attr(self.model.people, "E", "HumanToHuman: model people needs to have a 'E' (exposed) attribute.")

        check_attr(self.model.patches, "N", "HumanToHuman: model people needs to have a 'N' (current people) attribute.")

        check_attr(self.model, "params", "HumanToHuman: model needs to have a 'params' attribute.")
        check_key(self.model.params, "tau_i", "HumanToHuman: model params needs to have a 'tau_i' (emmigration probability) parameter.")
        check_key(
            self.model.params, "beta_j0_hum", "HumanToHuman: model params needs to have a 'beta_j0_hum' (baseline transmission rate) parameter."
        )

        check_key(self.model.params, "alpha_1", "HumanToHuman: model params needs to have an 'alpha_1' (numerator power) parameter.")
        check_key(self.model.params, "alpha_2", "HumanToHuman: model params needs to have an 'alpha_2' (denominator power) parameter.")

        return

    def __call__(self, model: "Model", tick: int) -> None:
        r"""Calculate the current human-to-human transmission rate per patch.

        $$
        \Lambda_{j,t+1} = \frac {\beta^{hum}_{jt}((S_{jt}(1 - \tau_j))(I_{jt}(1 - \tau_j) + \sum_{\forall i \neq j (\pi_{ij} \tau_j I_{it})}))^{\alpha_1}} {N^{\alpha_2}_{jt}}
        $$
        """

        # LambdaS
        Lambda = model.patches.Lambda[tick + 1]
        Isym = model.people.Isym[tick]
        Iasym = model.people.Iasym[tick]
        N = model.patches.N[tick]
        S_next = model.people.S[tick + 1]
        E_next = model.people.E[tick + 1]

        total_i = Isym + Iasym
        local_frac = 1 - model.params.tau_i
        local_i = (local_frac * total_i).astype(Lambda.dtype)
        # This odd formulation (vector * matrix.T).T ensures that the result is indexed [src, dst] just like the matrix pi_ij
        immigrating_i = ((model.params.tau_i * total_i) * model.patches.pi_ij.T).T.sum(axis=0).astype(Lambda.dtype)
        effective_i = local_i + immigrating_i
        power_adjusted = np.power(effective_i, model.params.alpha_1).astype(Lambda.dtype)
        seasonality = (model.patches.beta_jt_human[tick, :]).astype(Lambda.dtype)
        adjusted = seasonality * power_adjusted
        denominator = np.power(N, model.params.alpha_2).astype(Lambda.dtype)
        rate = (adjusted / denominator).astype(Lambda.dtype)

        # TODO - check seasonality and power_adjusted for negative values so we don't have to do this
        if np.any(rate < 0.0):
            logger.debug(f"Negative transmission rate at tick {tick + 1}.\n\t{rate=}")
            rate = np.maximum(rate, 0.0)

        Lambda[:] = rate
        # Use S_next here since some S will have been removed by natural mortality and by environmental transmission
        local = np.round(local_frac * S_next).astype(S_next.dtype)
        if np.any(np.isnan(rate)):
            logger.debug(f"NaN transmission rate at tick {tick + 1}.\n\t{rate=}")
        new_infections = model.prng.binomial(local, -np.expm1(-rate)).astype(S_next.dtype)
        S_next -= new_infections
        E_next += new_infections
        model.patches.incidence_human[tick + 1] += new_infections
        model.patches.incidence[tick + 1] += new_infections

        assert np.all(S_next >= 0), f"Negative susceptible populations at tick {tick + 1}.\n\t{S_next=}"

        return

    def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
        """Yield three Matplotlib figures: transmission rate, `pi_ij` heatmap, seasonality heatmap.

        Args:
            fig: Optional existing Matplotlib `Figure` to draw into.

        Yields:
            Three labels in order:
            `"Human-to-Human Transmission Rate"`,
            `"Spatial Connectivity Matrix (pi_ij)"`,
            `"Seasonal Human-Human Transmission Factor by Location Over Time"`.
        """
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Human-to-Human Transmission Rate") if fig is None else fig

        for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
            plt.plot(self.model.patches.Lambda[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
        plt.xlabel("Tick")
        plt.ylabel("Transmission Rate")
        plt.legend()

        yield "Human-to-Human Transmission Rate"

        # Spatial connectivity matrix
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Spatial Connectivity Matrix (pi_ij)") if fig is None else fig

        plt.imshow(self.model.patches.pi_ij, aspect="auto", cmap="viridis", interpolation="nearest")
        plt.colorbar(label="Connectivity")
        plt.xlabel("Destination Location Index")
        plt.xticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)
        plt.xticks(rotation=45, ha="right")
        plt.ylabel("Source Location Index")
        plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)
        plt.yticks(rotation=45, ha="right")

        yield "Spatial Connectivity Matrix (pi_ij)"

        # Seasonality factor by location over time
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Seasonal Human-Human Transmission Factor by Location Over Time") if fig is None else fig

        indices = np.argsort(self.model.params.latitude)[::-1]
        plt.imshow(self.model.patches.beta_jt_human[:, indices].T, aspect="auto", cmap="Blues", interpolation="nearest")
        plt.colorbar(label="Seasonal Factor")
        plt.xlabel("Time (Days)")
        plt.ylabel("Location")
        plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=[self.model.params.location_name[i] for i in indices])

        yield "Seasonal Human-Human Transmission Factor by Location Over Time"

        return

model instance-attribute

model = model

__init__

__init__(model: Model) -> None

Allocate Lambda, build pi_ij from lat/long, and bake the seasonality matrix.

pi_ij is computed once via get_pi_from_lat_long (gravity model), and beta_jt_human once via get_daily_seasonality (Fourier sum) — neither changes during the run.

Parameters:

Name Type Description Default
model Model

The Model instance. Must have patches, people, and params set up, with latitude, longitude, the seasonality coefficients (a_*_j, b_*_j, p), and the mobility parameters (mobility_omega, mobility_gamma) populated.

required

Raises:

Type Description
AttributeError

When model.patches is missing.

ValueError

When any of the seasonality / mobility parameters (latitude, longitude, mobility_omega, mobility_gamma, a_*_j, b_*_j, p) is missing.

Source code in src/laser/cholera/metapop/humantohuman.py
def __init__(self, model: "Model") -> None:
    """Allocate `Lambda`, build `pi_ij` from lat/long, and bake the seasonality matrix.

    `pi_ij` is computed once via
    [`get_pi_from_lat_long`][laser.cholera.metapop.utils.get_pi_from_lat_long]
    (gravity model), and `beta_jt_human` once via
    [`get_daily_seasonality`][laser.cholera.metapop.utils.get_daily_seasonality]
    (Fourier sum) — neither changes during the run.

    Args:
        model: The `Model` instance. Must have `patches`, `people`,
            and `params` set up, with `latitude`, `longitude`, the
            seasonality coefficients (`a_*_j`, `b_*_j`, `p`), and
            the mobility parameters (`mobility_omega`,
            `mobility_gamma`) populated.

    Raises:
        AttributeError: When `model.patches` is missing.
        ValueError: When any of the seasonality / mobility parameters
            (`latitude`, `longitude`, `mobility_omega`,
            `mobility_gamma`, `a_*_j`, `b_*_j`, `p`) is missing.
    """
    self.model = model

    check_attr(model, "patches", "HumanToHuman: model needs to have a 'patches' attribute.")
    model.patches.add_vector_property("Lambda", length=model.params.nticks + 1, dtype=np.float32, default=0.0)

    check_key(self.model.params, "latitude", "HumanToHuman: model params needs to have a 'latitude' (location latitude) parameter.")
    check_key(self.model.params, "longitude", "HumanToHuman: model params needs to have a 'longitude' (location longitude) parameter.")
    check_key(self.model.params, "mobility_omega", "HumanToHuman: model params needs to have a 'mobility_omega' (mobility) parameter.")
    check_key(self.model.params, "mobility_gamma", "HumanToHuman: model params needs to have a 'mobility_gamma' (mobility) parameter.")

    model.patches.add_array_property("pi_ij", (model.patches.count, model.patches.count), dtype=np.float32, default=0.0)
    model.patches.pi_ij[:, :] = get_pi_from_lat_long(model.params)

    check_key(self.model.params, "a_1_j", "HumanToHuman: model params needs to have a 'a_1_j' (seasonality) parameter.")
    check_key(self.model.params, "b_1_j", "HumanToHuman: model params needs to have a 'b_1_j' (seasonality) parameter.")
    check_key(self.model.params, "a_2_j", "HumanToHuman: model params needs to have a 'a_2_j' (seasonality) parameter.")
    check_key(self.model.params, "b_2_j", "HumanToHuman: model params needs to have a 'b_2_j' (seasonality) parameter.")
    check_key(self.model.params, "p", "HumanToHuman: model params needs to have a 'p' (seasonality pahse) parameter.")

    model.patches.add_array_property("beta_jt_human", (model.params.nticks, model.patches.count), dtype=np.float32, default=0.0)
    model.patches.beta_jt_human[:, :] = get_daily_seasonality(model.params)

    model.patches.add_vector_property("incidence_human", length=model.params.nticks + 1, dtype=np.int32, default=0)

    if not hasattr(model.patches, "incidence"):
        model.patches.add_vector_property("incidence", length=model.params.nticks + 1, dtype=np.int32, default=0)

    return

check

check()

Validate the consumer-side compartments and transmission parameters.

Asserts that model.people has Isym, Iasym, S, E; model.patches.N exists; and params provides tau_i, beta_j0_hum, alpha_1, and alpha_2.

Raises:

Type Description
AttributeError

When model, model.people (with Isym / Iasym / S / E), or model.patches.N is missing.

ValueError

When params.tau_i, beta_j0_hum, alpha_1, or alpha_2 is missing.

Source code in src/laser/cholera/metapop/humantohuman.py
def check(self):
    """Validate the consumer-side compartments and transmission parameters.

    Asserts that `model.people` has `Isym`, `Iasym`, `S`, `E`;
    `model.patches.N` exists; and `params` provides `tau_i`,
    `beta_j0_hum`, `alpha_1`, and `alpha_2`.

    Raises:
        AttributeError: When `model`, `model.people` (with `Isym` /
            `Iasym` / `S` / `E`), or `model.patches.N` is missing.
        ValueError: When `params.tau_i`, `beta_j0_hum`, `alpha_1`, or
            `alpha_2` is missing.
    """
    check_attr(self.model, "people", "HumanToHuman: model needs to have a 'people' attribute.")
    check_attr(self.model.people, "Isym", "HumanToHuman: model people needs to have a 'Isym' (symptomatic) attribute.")
    check_attr(self.model.people, "Iasym", "HumanToHuman: model people needs to have a 'Iasym' (asymptomatic) attribute.")
    check_attr(self.model.people, "S", "HumanToHuman: model people needs to have a 'S' (susceptible) attribute.")
    check_attr(self.model.people, "E", "HumanToHuman: model people needs to have a 'E' (exposed) attribute.")

    check_attr(self.model.patches, "N", "HumanToHuman: model people needs to have a 'N' (current people) attribute.")

    check_attr(self.model, "params", "HumanToHuman: model needs to have a 'params' attribute.")
    check_key(self.model.params, "tau_i", "HumanToHuman: model params needs to have a 'tau_i' (emmigration probability) parameter.")
    check_key(
        self.model.params, "beta_j0_hum", "HumanToHuman: model params needs to have a 'beta_j0_hum' (baseline transmission rate) parameter."
    )

    check_key(self.model.params, "alpha_1", "HumanToHuman: model params needs to have an 'alpha_1' (numerator power) parameter.")
    check_key(self.model.params, "alpha_2", "HumanToHuman: model params needs to have an 'alpha_2' (denominator power) parameter.")

    return

__call__

__call__(model: Model, tick: int) -> None

Calculate the current human-to-human transmission rate per patch.

\[ \Lambda_{j,t+1} = \frac {\beta^{hum}_{jt}((S_{jt}(1 - \tau_j))(I_{jt}(1 - \tau_j) + \sum_{\forall i \neq j (\pi_{ij} \tau_j I_{it})}))^{\alpha_1}} {N^{\alpha_2}_{jt}} \]
Source code in src/laser/cholera/metapop/humantohuman.py
def __call__(self, model: "Model", tick: int) -> None:
    r"""Calculate the current human-to-human transmission rate per patch.

    $$
    \Lambda_{j,t+1} = \frac {\beta^{hum}_{jt}((S_{jt}(1 - \tau_j))(I_{jt}(1 - \tau_j) + \sum_{\forall i \neq j (\pi_{ij} \tau_j I_{it})}))^{\alpha_1}} {N^{\alpha_2}_{jt}}
    $$
    """

    # LambdaS
    Lambda = model.patches.Lambda[tick + 1]
    Isym = model.people.Isym[tick]
    Iasym = model.people.Iasym[tick]
    N = model.patches.N[tick]
    S_next = model.people.S[tick + 1]
    E_next = model.people.E[tick + 1]

    total_i = Isym + Iasym
    local_frac = 1 - model.params.tau_i
    local_i = (local_frac * total_i).astype(Lambda.dtype)
    # This odd formulation (vector * matrix.T).T ensures that the result is indexed [src, dst] just like the matrix pi_ij
    immigrating_i = ((model.params.tau_i * total_i) * model.patches.pi_ij.T).T.sum(axis=0).astype(Lambda.dtype)
    effective_i = local_i + immigrating_i
    power_adjusted = np.power(effective_i, model.params.alpha_1).astype(Lambda.dtype)
    seasonality = (model.patches.beta_jt_human[tick, :]).astype(Lambda.dtype)
    adjusted = seasonality * power_adjusted
    denominator = np.power(N, model.params.alpha_2).astype(Lambda.dtype)
    rate = (adjusted / denominator).astype(Lambda.dtype)

    # TODO - check seasonality and power_adjusted for negative values so we don't have to do this
    if np.any(rate < 0.0):
        logger.debug(f"Negative transmission rate at tick {tick + 1}.\n\t{rate=}")
        rate = np.maximum(rate, 0.0)

    Lambda[:] = rate
    # Use S_next here since some S will have been removed by natural mortality and by environmental transmission
    local = np.round(local_frac * S_next).astype(S_next.dtype)
    if np.any(np.isnan(rate)):
        logger.debug(f"NaN transmission rate at tick {tick + 1}.\n\t{rate=}")
    new_infections = model.prng.binomial(local, -np.expm1(-rate)).astype(S_next.dtype)
    S_next -= new_infections
    E_next += new_infections
    model.patches.incidence_human[tick + 1] += new_infections
    model.patches.incidence[tick + 1] += new_infections

    assert np.all(S_next >= 0), f"Negative susceptible populations at tick {tick + 1}.\n\t{S_next=}"

    return

plot

plot(fig: Figure = None) -> Iterator[str]

Yield three Matplotlib figures: transmission rate, pi_ij heatmap, seasonality heatmap.

Parameters:

Name Type Description Default
fig Figure

Optional existing Matplotlib Figure to draw into.

None

Yields:

Type Description
str

Three labels in order:

str

"Human-to-Human Transmission Rate",

str

"Spatial Connectivity Matrix (pi_ij)",

str

"Seasonal Human-Human Transmission Factor by Location Over Time".

Source code in src/laser/cholera/metapop/humantohuman.py
def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
    """Yield three Matplotlib figures: transmission rate, `pi_ij` heatmap, seasonality heatmap.

    Args:
        fig: Optional existing Matplotlib `Figure` to draw into.

    Yields:
        Three labels in order:
        `"Human-to-Human Transmission Rate"`,
        `"Spatial Connectivity Matrix (pi_ij)"`,
        `"Seasonal Human-Human Transmission Factor by Location Over Time"`.
    """
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Human-to-Human Transmission Rate") if fig is None else fig

    for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
        plt.plot(self.model.patches.Lambda[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
    plt.xlabel("Tick")
    plt.ylabel("Transmission Rate")
    plt.legend()

    yield "Human-to-Human Transmission Rate"

    # Spatial connectivity matrix
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Spatial Connectivity Matrix (pi_ij)") if fig is None else fig

    plt.imshow(self.model.patches.pi_ij, aspect="auto", cmap="viridis", interpolation="nearest")
    plt.colorbar(label="Connectivity")
    plt.xlabel("Destination Location Index")
    plt.xticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)
    plt.xticks(rotation=45, ha="right")
    plt.ylabel("Source Location Index")
    plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)
    plt.yticks(rotation=45, ha="right")

    yield "Spatial Connectivity Matrix (pi_ij)"

    # Seasonality factor by location over time
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Seasonal Human-Human Transmission Factor by Location Over Time") if fig is None else fig

    indices = np.argsort(self.model.params.latitude)[::-1]
    plt.imshow(self.model.patches.beta_jt_human[:, indices].T, aspect="auto", cmap="Blues", interpolation="nearest")
    plt.colorbar(label="Seasonal Factor")
    plt.xlabel("Time (Days)")
    plt.ylabel("Location")
    plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=[self.model.params.location_name[i] for i in indices])

    yield "Seasonal Human-Human Transmission Factor by Location Over Time"

    return

Infectious

Infectious compartment: tracks Isym(t), Iasym(t), disease deaths, and reported cases.

Attributes:

Name Type Description
model

The parent Model instance.

Source code in src/laser/cholera/metapop/infectious.py
class Infectious:
    """Infectious compartment: tracks `Isym(t)`, `Iasym(t)`, disease deaths, and reported cases.

    Attributes:
        model: The parent `Model` instance.
    """

    def __init__(self, model: "Model") -> None:
        """Allocate `Isym` / `Iasym` and the disease-deaths / reporting bookkeeping vectors.

        Splits `params.I_j_initial` into symptomatic and asymptomatic
        seed populations using the symptomatic fraction `params.sigma`.

        Args:
            model: The `Model` instance. Must have `people`, `patches`,
                and `params` set up, with `params.I_j_initial` and
                `params.sigma` populated.

        Raises:
            AttributeError: When `model` is missing `people`, `patches`,
                or `params`.
            ValueError: When a required `params` key is missing (e.g.
                `I_j_initial`, `sigma`).
        """
        self.model = model

        check_attr(model, "people", "Infectious: model needs to have a 'people' attribute.")
        model.people.add_vector_property("Isym", length=model.params.nticks + 1, dtype=np.int32, default=0)
        model.people.add_vector_property("Iasym", length=model.params.nticks + 1, dtype=np.int32, default=0)
        check_attr(model, "patches", "Infectious: model needs to have a 'patches' attribute.")
        model.patches.add_vector_property("disease_deaths", length=model.params.nticks + 1, dtype=np.int32, default=0)
        model.patches.add_vector_property("new_symptomatic", length=model.params.nticks + 1, dtype=np.int32, default=0)
        model.patches.add_vector_property("reported_cases", length=model.params.nticks + 1, dtype=np.int32, default=0)
        model.patches.add_vector_property("reported_deaths", length=model.params.nticks + 1, dtype=np.int32, default=0)
        check_attr(model, "params", "Infectious: model needs to have a 'params' attribute.")
        check_key(model.params, "I_j_initial", "Infectious: model params needs to have a 'I_j_initial' (initial infectious population) parameter.")
        check_key(self.model.params, "sigma", "Infectious: model params needs to have a 'sigma' (symptomatic fraction) parameter.")
        model.people.Isym[0] = np.round(model.params.sigma * model.params.I_j_initial).astype(model.people.Isym.dtype)
        model.people.Iasym[0] = model.params.I_j_initial - model.people.Isym[0]

        return

    def check(self):
        """Validate every parameter and prerequisite attribute used by `__call__`.

        Asserts that `model.people.R` exists (so recovery can route into
        it) and that `params` contains `d_jt`, `mu_j_baseline`,
        `mu_j_slope`, `mu_j_epidemic_factor`, `epidemic_threshold`,
        `gamma_1`, `gamma_2`, `iota`, `sigma`, `rho`, and `rho_deaths`.

        Raises:
            AttributeError: When `model.people.R` is missing.
            ValueError: When any of the required `params` keys is missing
                (`d_jt`, `mu_j_baseline`, `mu_j_slope`,
                `mu_j_epidemic_factor`, `epidemic_threshold`, `gamma_1`,
                `gamma_2`, `iota`, `sigma`, `rho`, `rho_deaths`).
        """
        check_attr(self.model.people, "R", "Infectious: model.people needs to have a 'R' attribute.")
        check_key(self.model.params, "d_jt", "Infectious: model params needs to have a 'd_jt' (mortality rate) parameter.")

        check_key(
            self.model.params,
            "mu_j_baseline",
            "Infectious: model params needs to have a 'mu_j_baseline' (baseline disease mortality rate) parameter.",
        )
        check_key(self.model.params, "mu_j_slope", "Infectious: model params needs to have a 'mu_j_slope' (disease mortality rate slope) parameter.")
        check_key(
            self.model.params,
            "mu_j_epidemic_factor",
            "Infectious: model params needs to have a 'mu_j_epidemic_factor' (disease mortality rate epidemic factor) parameter.",
        )
        check_key(
            self.model.params,
            "epidemic_threshold",
            "Infectious: model params needs to have a 'epidemic_threshold' (disease mortality rate epidemic threshold) parameter.",
        )

        check_key(self.model.params, "gamma_1", "Infectious: model params needs to have a 'gamma_1' (recovery rate) parameter.")
        check_key(self.model.params, "gamma_2", "Infectious: model params needs to have a 'gamma_2' (recovery rate) parameter.")
        check_key(self.model.params, "iota", "Infectious: model params needs to have a 'iota' (progression rate) parameter.")
        check_key(self.model.params, "sigma", "Infectious: model params needs to have a 'sigma' (symptomatic fraction) parameter.")
        check_key(self.model.params, "rho", "Infectious: model params needs to have a 'rho' (detected/expected cases) parameter.")
        check_key(self.model.params, "rho_deaths", "Infectious: model params needs to have a 'rho_deaths' (detected/expected deaths) parameter.")
        if not hasattr(self.model.patches, "non_disease_deaths"):
            self.model.patches.add_vector_property("non_disease_deaths", length=self.model.params.nticks + 1, dtype=np.int32, default=0)
        # PERF: install `model.patches.non_disease_death_prob_jt` (the
        # `1 - exp(-d_jt)` cache) idempotently if no earlier component has.
        # Lets each consumer be exercised in isolation; the cache is built
        # exactly once across the pipeline.
        if not hasattr(self.model.patches, "non_disease_death_prob_jt"):
            self.model.patches.add_vector_property("non_disease_death_prob_jt", length=self.model.params.d_jt.shape[0], dtype=np.float32, default=0.0)
            self.model.patches.non_disease_death_prob_jt[:] = -np.expm1(-self.model.params.d_jt)

        # PERF: cache `1 - exp(-rate)` for the three scalar rates that
        # otherwise get exponentiated every tick.
        self._iota_prob = -np.expm1(-self.model.params.iota)
        self._gamma_1_prob = -np.expm1(-self.model.params.gamma_1)
        self._gamma_2_prob = -np.expm1(-self.model.params.gamma_2)

        return

    def __call__(self, model: "Model", tick: int) -> None:
        """Advance `Isym` / `Iasym` one tick: deaths, recoveries, then `E -> I` progression.

        For each patch and within each of `Isym` and `Iasym`:

        1. Carry forward; subtract non-disease deaths (`d_jt`).
        2. For `Isym` only: compute `mu_jt = mu_baseline * (1 + slope *
            t_factor) * (1 + epidemic_factor * epidemic_flag)`, sample
            disease deaths from `Binomial(Isym, 1 - exp(-mu_jt))`, and
            update `patches.disease_deaths` and lagged `reported_deaths`.
        3. Sample recoveries (`gamma_1` for symptomatic, `gamma_2` for
            asymptomatic) and add to `R[tick + 1]`.
        4. Sample `E -> I` progression from `Binomial(E_next, 1 -
            exp(-iota))`, split by `sigma`, and add into `Isym` / `Iasym`.
        5. Update lagged `reported_cases` using `rho` and the
            `chi_endemic` / `chi_epidemic` healthcare-access modifier.

        Args:
            model: The parent `Model` instance.
            tick: Current simulation tick.

        Raises:
            AssertionError: When any compartment goes negative after a
                draw (indicates the implementation's invariants have
                regressed).
        """
        # Symptomatic
        Isym = model.people.Isym[tick]
        Is_next = model.people.Isym[tick + 1]
        Is_next[:] = Isym

        ## natural deaths (d_jt)
        # PERF: pre-computed `-np.expm1(-d_jt)` cached as model.patches.non_disease_death_prob_jt.
        # non_disease_deaths = model.prng.binomial(Is_next, -np.expm1(-model.params.d_jt[tick])).astype(Is_next.dtype)
        non_disease_deaths = model.prng.binomial(Is_next, model.patches.non_disease_death_prob_jt[tick]).astype(Is_next.dtype)
        Is_next -= non_disease_deaths
        ndd_next = model.patches.non_disease_deaths[tick]
        ndd_next += non_disease_deaths
        assert np.all(Is_next >= 0), f"Is_next should not go negative ({tick=}\n\t{Is_next=})"

        ## disease deaths (mu)

        t_factor = tick / model.params.nticks  # 0 <= t_factor <= 1.0
        N = model.people.S[tick] + model.people.E[tick] + model.people.Isym[tick] + model.people.Iasym[tick] + model.people.R[tick]
        if hasattr(model.people, "V1"):
            N += model.people.V1[tick]
        if hasattr(model.people, "V2"):
            N += model.people.V2[tick]
        # Don't include V1inf or V2inf above, they're not "real" - just bookkeeping
        if (treport := int(tick - model.params.delta_reporting_cases)) >= 0:
            Ireported = model.people.Isym[treport]
            epidemic_flag = (Ireported > (model.params.epidemic_threshold * N)).astype(np.int32)
        else:
            epidemic_flag = np.zeros_like(N, dtype=np.int32)
        mu_jt = model.params.mu_j_baseline * (1 + model.params.mu_j_slope * t_factor) * (1 + model.params.mu_j_epidemic_factor * epidemic_flag)

        disease_deaths = model.prng.binomial(Is_next, -np.expm1(-mu_jt)).astype(Is_next.dtype)
        model.patches.disease_deaths[tick] = disease_deaths
        Is_next -= disease_deaths
        assert np.all(Is_next >= 0), f"Is_next should not go negative ({tick=}\n\t{Is_next=})"

        idx_death_report = int(tick - model.params.delta_reporting_deaths)
        if idx_death_report >= 0:
            model.patches.reported_deaths[tick] += model.prng.binomial(
                model.patches.disease_deaths[idx_death_report], model.params.rho_deaths
            ).astype(model.patches.reported_deaths.dtype)

        ## recovery (gamma)
        # PERF: pre-computed `-np.expm1(-gamma_1)` cached as self._gamma_1_prob.
        # recovered = model.prng.binomial(Is_next, -np.expm1(-model.params.gamma_1)).astype(Is_next.dtype)
        recovered = model.prng.binomial(Is_next, self._gamma_1_prob).astype(Is_next.dtype)
        Is_next -= recovered
        R_next = model.people.R[tick + 1]
        R_next += recovered
        assert np.all(Is_next >= 0), f"Is_next should not go negative ({tick=}\n\t{Is_next=})"

        # Asymptomatic
        Iasym = model.people.Iasym[tick]
        Ia_next = model.people.Iasym[tick + 1]
        Ia_next[:] = Iasym

        ## natural deaths (d_jt)
        # PERF: pre-computed `-np.expm1(-d_jt)` cached as model.patches.non_disease_death_prob_jt.
        # non_disease_deaths = model.prng.binomial(Ia_next, -np.expm1(-model.params.d_jt[tick])).astype(Ia_next.dtype)
        non_disease_deaths = model.prng.binomial(Ia_next, model.patches.non_disease_death_prob_jt[tick]).astype(Ia_next.dtype)
        Ia_next -= non_disease_deaths
        ndd_next += non_disease_deaths
        assert np.all(Ia_next >= 0), f"Ia_next should not go negative ({tick=}\n\t{Ia_next=})"

        ## recovery
        # PERF: pre-computed `-np.expm1(-gamma_2)` cached as self._gamma_2_prob.
        # recovered = model.prng.binomial(Ia_next, -np.expm1(-model.params.gamma_2)).astype(Ia_next.dtype)
        recovered = model.prng.binomial(Ia_next, self._gamma_2_prob).astype(Ia_next.dtype)
        Ia_next -= recovered
        # R_next = model.people.R[tick + 1]
        R_next += recovered
        assert np.all(Ia_next >= 0), f"Ia_next should not go negative ({tick=}\n\t{Ia_next=})"

        # Use E_next here, can't progress deceased individuals
        E_next = model.people.E[tick + 1]
        # PERF: pre-computed `-np.expm1(-iota)` cached as self._iota_prob.
        # progressing = model.prng.binomial(E_next, -np.expm1(-model.params.iota)).astype(E_next.dtype)
        progressing = model.prng.binomial(E_next, self._iota_prob).astype(E_next.dtype)
        E_next -= progressing
        assert np.all(E_next >= 0), f"E_next should not go negative ({tick=}\n\t{E_next=})"

        ## new symptomatic infections
        new_symptomatic = np.round(model.params.sigma * progressing).astype(Is_next.dtype)
        new_asymptomatic = progressing - new_symptomatic
        Is_next += new_symptomatic
        Ia_next += new_asymptomatic
        model.patches.new_symptomatic[tick + 1] = new_symptomatic

        # Update reported cases
        idx_probe = tick - model.params.delta_reporting_cases
        if idx_probe >= 0:
            infected_fraction = model.people.Isym[idx_probe] / model.patches.N[idx_probe]
            # Use chi_endemic or chi_epidemic depending on local infected fraction.
            chi_eff = np.where(infected_fraction < model.params.epidemic_threshold, model.params.chi_endemic, model.params.chi_epidemic)
            model.patches.reported_cases[tick] += np.round(
                model.prng.binomial(model.patches.new_symptomatic[idx_probe], model.params.rho) / chi_eff
            ).astype(model.patches.reported_cases.dtype)

        # human-to-human infection in humantohuman.py
        # environmental infection in envtohuman.py
        # recovery from infection in recovered.py

        return

    def plot(self, fig: Figure | None = None) -> Iterator[str]:  # pragma: no cover
        """Yield four Matplotlib figures: symptomatic, asymptomatic, total, and reported-vs-actual cases.

        Args:
            fig: Optional existing Matplotlib `Figure` to draw into.

        Yields:
            Four labels in order: `"Infectious (Symptomatic)"`,
            `"Infectious (Asymptomatic)"`, `"Infectious (Total)"`,
            `"Reported Cases"`.
        """
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Infectious (Symptomatic)") if fig is None else fig

        for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
            plt.plot(self.model.people.Isym[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
        plt.xlabel("Tick")
        plt.ylabel("Symptomatic")
        plt.legend()

        yield "Infectious (Symptomatic)"

        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Infectious (Asymptomatic)") if fig is None else fig

        for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
            plt.plot(self.model.people.Iasym[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
        plt.xlabel("Tick")
        plt.ylabel("Asymptomatic")
        plt.legend()

        yield "Infectious (Asymptomatic)"

        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Infectious (Total)") if fig is None else fig

        for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
            plt.plot(self.model.people.Isym[:, ipatch] + self.model.people.Iasym[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
        plt.xlabel("Tick")
        plt.ylabel("Total Infectious")
        plt.legend()

        yield "Infectious (Total)"

        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Reported vs. Actual Cases") if fig is None else fig

        plt.plot(self.model.patches.reported_cases.sum(axis=1), color="blue", label="Reported")
        plt.plot(self.model.people.Isym.sum(axis=1), color="red", label="Actual")
        plt.xlabel("Tick")
        plt.ylabel("Cases")
        plt.legend()

        yield "Reported Cases"
        return

model instance-attribute

model = model

__init__

__init__(model: Model) -> None

Allocate Isym / Iasym and the disease-deaths / reporting bookkeeping vectors.

Splits params.I_j_initial into symptomatic and asymptomatic seed populations using the symptomatic fraction params.sigma.

Parameters:

Name Type Description Default
model Model

The Model instance. Must have people, patches, and params set up, with params.I_j_initial and params.sigma populated.

required

Raises:

Type Description
AttributeError

When model is missing people, patches, or params.

ValueError

When a required params key is missing (e.g. I_j_initial, sigma).

Source code in src/laser/cholera/metapop/infectious.py
def __init__(self, model: "Model") -> None:
    """Allocate `Isym` / `Iasym` and the disease-deaths / reporting bookkeeping vectors.

    Splits `params.I_j_initial` into symptomatic and asymptomatic
    seed populations using the symptomatic fraction `params.sigma`.

    Args:
        model: The `Model` instance. Must have `people`, `patches`,
            and `params` set up, with `params.I_j_initial` and
            `params.sigma` populated.

    Raises:
        AttributeError: When `model` is missing `people`, `patches`,
            or `params`.
        ValueError: When a required `params` key is missing (e.g.
            `I_j_initial`, `sigma`).
    """
    self.model = model

    check_attr(model, "people", "Infectious: model needs to have a 'people' attribute.")
    model.people.add_vector_property("Isym", length=model.params.nticks + 1, dtype=np.int32, default=0)
    model.people.add_vector_property("Iasym", length=model.params.nticks + 1, dtype=np.int32, default=0)
    check_attr(model, "patches", "Infectious: model needs to have a 'patches' attribute.")
    model.patches.add_vector_property("disease_deaths", length=model.params.nticks + 1, dtype=np.int32, default=0)
    model.patches.add_vector_property("new_symptomatic", length=model.params.nticks + 1, dtype=np.int32, default=0)
    model.patches.add_vector_property("reported_cases", length=model.params.nticks + 1, dtype=np.int32, default=0)
    model.patches.add_vector_property("reported_deaths", length=model.params.nticks + 1, dtype=np.int32, default=0)
    check_attr(model, "params", "Infectious: model needs to have a 'params' attribute.")
    check_key(model.params, "I_j_initial", "Infectious: model params needs to have a 'I_j_initial' (initial infectious population) parameter.")
    check_key(self.model.params, "sigma", "Infectious: model params needs to have a 'sigma' (symptomatic fraction) parameter.")
    model.people.Isym[0] = np.round(model.params.sigma * model.params.I_j_initial).astype(model.people.Isym.dtype)
    model.people.Iasym[0] = model.params.I_j_initial - model.people.Isym[0]

    return

check

check()

Validate every parameter and prerequisite attribute used by __call__.

Asserts that model.people.R exists (so recovery can route into it) and that params contains d_jt, mu_j_baseline, mu_j_slope, mu_j_epidemic_factor, epidemic_threshold, gamma_1, gamma_2, iota, sigma, rho, and rho_deaths.

Raises:

Type Description
AttributeError

When model.people.R is missing.

ValueError

When any of the required params keys is missing (d_jt, mu_j_baseline, mu_j_slope, mu_j_epidemic_factor, epidemic_threshold, gamma_1, gamma_2, iota, sigma, rho, rho_deaths).

Source code in src/laser/cholera/metapop/infectious.py
def check(self):
    """Validate every parameter and prerequisite attribute used by `__call__`.

    Asserts that `model.people.R` exists (so recovery can route into
    it) and that `params` contains `d_jt`, `mu_j_baseline`,
    `mu_j_slope`, `mu_j_epidemic_factor`, `epidemic_threshold`,
    `gamma_1`, `gamma_2`, `iota`, `sigma`, `rho`, and `rho_deaths`.

    Raises:
        AttributeError: When `model.people.R` is missing.
        ValueError: When any of the required `params` keys is missing
            (`d_jt`, `mu_j_baseline`, `mu_j_slope`,
            `mu_j_epidemic_factor`, `epidemic_threshold`, `gamma_1`,
            `gamma_2`, `iota`, `sigma`, `rho`, `rho_deaths`).
    """
    check_attr(self.model.people, "R", "Infectious: model.people needs to have a 'R' attribute.")
    check_key(self.model.params, "d_jt", "Infectious: model params needs to have a 'd_jt' (mortality rate) parameter.")

    check_key(
        self.model.params,
        "mu_j_baseline",
        "Infectious: model params needs to have a 'mu_j_baseline' (baseline disease mortality rate) parameter.",
    )
    check_key(self.model.params, "mu_j_slope", "Infectious: model params needs to have a 'mu_j_slope' (disease mortality rate slope) parameter.")
    check_key(
        self.model.params,
        "mu_j_epidemic_factor",
        "Infectious: model params needs to have a 'mu_j_epidemic_factor' (disease mortality rate epidemic factor) parameter.",
    )
    check_key(
        self.model.params,
        "epidemic_threshold",
        "Infectious: model params needs to have a 'epidemic_threshold' (disease mortality rate epidemic threshold) parameter.",
    )

    check_key(self.model.params, "gamma_1", "Infectious: model params needs to have a 'gamma_1' (recovery rate) parameter.")
    check_key(self.model.params, "gamma_2", "Infectious: model params needs to have a 'gamma_2' (recovery rate) parameter.")
    check_key(self.model.params, "iota", "Infectious: model params needs to have a 'iota' (progression rate) parameter.")
    check_key(self.model.params, "sigma", "Infectious: model params needs to have a 'sigma' (symptomatic fraction) parameter.")
    check_key(self.model.params, "rho", "Infectious: model params needs to have a 'rho' (detected/expected cases) parameter.")
    check_key(self.model.params, "rho_deaths", "Infectious: model params needs to have a 'rho_deaths' (detected/expected deaths) parameter.")
    if not hasattr(self.model.patches, "non_disease_deaths"):
        self.model.patches.add_vector_property("non_disease_deaths", length=self.model.params.nticks + 1, dtype=np.int32, default=0)
    # PERF: install `model.patches.non_disease_death_prob_jt` (the
    # `1 - exp(-d_jt)` cache) idempotently if no earlier component has.
    # Lets each consumer be exercised in isolation; the cache is built
    # exactly once across the pipeline.
    if not hasattr(self.model.patches, "non_disease_death_prob_jt"):
        self.model.patches.add_vector_property("non_disease_death_prob_jt", length=self.model.params.d_jt.shape[0], dtype=np.float32, default=0.0)
        self.model.patches.non_disease_death_prob_jt[:] = -np.expm1(-self.model.params.d_jt)

    # PERF: cache `1 - exp(-rate)` for the three scalar rates that
    # otherwise get exponentiated every tick.
    self._iota_prob = -np.expm1(-self.model.params.iota)
    self._gamma_1_prob = -np.expm1(-self.model.params.gamma_1)
    self._gamma_2_prob = -np.expm1(-self.model.params.gamma_2)

    return

__call__

__call__(model: Model, tick: int) -> None

Advance Isym / Iasym one tick: deaths, recoveries, then E -> I progression.

For each patch and within each of Isym and Iasym:

  1. Carry forward; subtract non-disease deaths (d_jt).
  2. For Isym only: compute mu_jt = mu_baseline * (1 + slope * t_factor) * (1 + epidemic_factor * epidemic_flag), sample disease deaths from Binomial(Isym, 1 - exp(-mu_jt)), and update patches.disease_deaths and lagged reported_deaths.
  3. Sample recoveries (gamma_1 for symptomatic, gamma_2 for asymptomatic) and add to R[tick + 1].
  4. Sample E -> I progression from Binomial(E_next, 1 - exp(-iota)), split by sigma, and add into Isym / Iasym.
  5. Update lagged reported_cases using rho and the chi_endemic / chi_epidemic healthcare-access modifier.

Parameters:

Name Type Description Default
model Model

The parent Model instance.

required
tick int

Current simulation tick.

required

Raises:

Type Description
AssertionError

When any compartment goes negative after a draw (indicates the implementation's invariants have regressed).

Source code in src/laser/cholera/metapop/infectious.py
def __call__(self, model: "Model", tick: int) -> None:
    """Advance `Isym` / `Iasym` one tick: deaths, recoveries, then `E -> I` progression.

    For each patch and within each of `Isym` and `Iasym`:

    1. Carry forward; subtract non-disease deaths (`d_jt`).
    2. For `Isym` only: compute `mu_jt = mu_baseline * (1 + slope *
        t_factor) * (1 + epidemic_factor * epidemic_flag)`, sample
        disease deaths from `Binomial(Isym, 1 - exp(-mu_jt))`, and
        update `patches.disease_deaths` and lagged `reported_deaths`.
    3. Sample recoveries (`gamma_1` for symptomatic, `gamma_2` for
        asymptomatic) and add to `R[tick + 1]`.
    4. Sample `E -> I` progression from `Binomial(E_next, 1 -
        exp(-iota))`, split by `sigma`, and add into `Isym` / `Iasym`.
    5. Update lagged `reported_cases` using `rho` and the
        `chi_endemic` / `chi_epidemic` healthcare-access modifier.

    Args:
        model: The parent `Model` instance.
        tick: Current simulation tick.

    Raises:
        AssertionError: When any compartment goes negative after a
            draw (indicates the implementation's invariants have
            regressed).
    """
    # Symptomatic
    Isym = model.people.Isym[tick]
    Is_next = model.people.Isym[tick + 1]
    Is_next[:] = Isym

    ## natural deaths (d_jt)
    # PERF: pre-computed `-np.expm1(-d_jt)` cached as model.patches.non_disease_death_prob_jt.
    # non_disease_deaths = model.prng.binomial(Is_next, -np.expm1(-model.params.d_jt[tick])).astype(Is_next.dtype)
    non_disease_deaths = model.prng.binomial(Is_next, model.patches.non_disease_death_prob_jt[tick]).astype(Is_next.dtype)
    Is_next -= non_disease_deaths
    ndd_next = model.patches.non_disease_deaths[tick]
    ndd_next += non_disease_deaths
    assert np.all(Is_next >= 0), f"Is_next should not go negative ({tick=}\n\t{Is_next=})"

    ## disease deaths (mu)

    t_factor = tick / model.params.nticks  # 0 <= t_factor <= 1.0
    N = model.people.S[tick] + model.people.E[tick] + model.people.Isym[tick] + model.people.Iasym[tick] + model.people.R[tick]
    if hasattr(model.people, "V1"):
        N += model.people.V1[tick]
    if hasattr(model.people, "V2"):
        N += model.people.V2[tick]
    # Don't include V1inf or V2inf above, they're not "real" - just bookkeeping
    if (treport := int(tick - model.params.delta_reporting_cases)) >= 0:
        Ireported = model.people.Isym[treport]
        epidemic_flag = (Ireported > (model.params.epidemic_threshold * N)).astype(np.int32)
    else:
        epidemic_flag = np.zeros_like(N, dtype=np.int32)
    mu_jt = model.params.mu_j_baseline * (1 + model.params.mu_j_slope * t_factor) * (1 + model.params.mu_j_epidemic_factor * epidemic_flag)

    disease_deaths = model.prng.binomial(Is_next, -np.expm1(-mu_jt)).astype(Is_next.dtype)
    model.patches.disease_deaths[tick] = disease_deaths
    Is_next -= disease_deaths
    assert np.all(Is_next >= 0), f"Is_next should not go negative ({tick=}\n\t{Is_next=})"

    idx_death_report = int(tick - model.params.delta_reporting_deaths)
    if idx_death_report >= 0:
        model.patches.reported_deaths[tick] += model.prng.binomial(
            model.patches.disease_deaths[idx_death_report], model.params.rho_deaths
        ).astype(model.patches.reported_deaths.dtype)

    ## recovery (gamma)
    # PERF: pre-computed `-np.expm1(-gamma_1)` cached as self._gamma_1_prob.
    # recovered = model.prng.binomial(Is_next, -np.expm1(-model.params.gamma_1)).astype(Is_next.dtype)
    recovered = model.prng.binomial(Is_next, self._gamma_1_prob).astype(Is_next.dtype)
    Is_next -= recovered
    R_next = model.people.R[tick + 1]
    R_next += recovered
    assert np.all(Is_next >= 0), f"Is_next should not go negative ({tick=}\n\t{Is_next=})"

    # Asymptomatic
    Iasym = model.people.Iasym[tick]
    Ia_next = model.people.Iasym[tick + 1]
    Ia_next[:] = Iasym

    ## natural deaths (d_jt)
    # PERF: pre-computed `-np.expm1(-d_jt)` cached as model.patches.non_disease_death_prob_jt.
    # non_disease_deaths = model.prng.binomial(Ia_next, -np.expm1(-model.params.d_jt[tick])).astype(Ia_next.dtype)
    non_disease_deaths = model.prng.binomial(Ia_next, model.patches.non_disease_death_prob_jt[tick]).astype(Ia_next.dtype)
    Ia_next -= non_disease_deaths
    ndd_next += non_disease_deaths
    assert np.all(Ia_next >= 0), f"Ia_next should not go negative ({tick=}\n\t{Ia_next=})"

    ## recovery
    # PERF: pre-computed `-np.expm1(-gamma_2)` cached as self._gamma_2_prob.
    # recovered = model.prng.binomial(Ia_next, -np.expm1(-model.params.gamma_2)).astype(Ia_next.dtype)
    recovered = model.prng.binomial(Ia_next, self._gamma_2_prob).astype(Ia_next.dtype)
    Ia_next -= recovered
    # R_next = model.people.R[tick + 1]
    R_next += recovered
    assert np.all(Ia_next >= 0), f"Ia_next should not go negative ({tick=}\n\t{Ia_next=})"

    # Use E_next here, can't progress deceased individuals
    E_next = model.people.E[tick + 1]
    # PERF: pre-computed `-np.expm1(-iota)` cached as self._iota_prob.
    # progressing = model.prng.binomial(E_next, -np.expm1(-model.params.iota)).astype(E_next.dtype)
    progressing = model.prng.binomial(E_next, self._iota_prob).astype(E_next.dtype)
    E_next -= progressing
    assert np.all(E_next >= 0), f"E_next should not go negative ({tick=}\n\t{E_next=})"

    ## new symptomatic infections
    new_symptomatic = np.round(model.params.sigma * progressing).astype(Is_next.dtype)
    new_asymptomatic = progressing - new_symptomatic
    Is_next += new_symptomatic
    Ia_next += new_asymptomatic
    model.patches.new_symptomatic[tick + 1] = new_symptomatic

    # Update reported cases
    idx_probe = tick - model.params.delta_reporting_cases
    if idx_probe >= 0:
        infected_fraction = model.people.Isym[idx_probe] / model.patches.N[idx_probe]
        # Use chi_endemic or chi_epidemic depending on local infected fraction.
        chi_eff = np.where(infected_fraction < model.params.epidemic_threshold, model.params.chi_endemic, model.params.chi_epidemic)
        model.patches.reported_cases[tick] += np.round(
            model.prng.binomial(model.patches.new_symptomatic[idx_probe], model.params.rho) / chi_eff
        ).astype(model.patches.reported_cases.dtype)

    # human-to-human infection in humantohuman.py
    # environmental infection in envtohuman.py
    # recovery from infection in recovered.py

    return

plot

plot(fig: Figure | None = None) -> Iterator[str]

Yield four Matplotlib figures: symptomatic, asymptomatic, total, and reported-vs-actual cases.

Parameters:

Name Type Description Default
fig Figure | None

Optional existing Matplotlib Figure to draw into.

None

Yields:

Type Description
str

Four labels in order: "Infectious (Symptomatic)",

str

"Infectious (Asymptomatic)", "Infectious (Total)",

str

"Reported Cases".

Source code in src/laser/cholera/metapop/infectious.py
def plot(self, fig: Figure | None = None) -> Iterator[str]:  # pragma: no cover
    """Yield four Matplotlib figures: symptomatic, asymptomatic, total, and reported-vs-actual cases.

    Args:
        fig: Optional existing Matplotlib `Figure` to draw into.

    Yields:
        Four labels in order: `"Infectious (Symptomatic)"`,
        `"Infectious (Asymptomatic)"`, `"Infectious (Total)"`,
        `"Reported Cases"`.
    """
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Infectious (Symptomatic)") if fig is None else fig

    for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
        plt.plot(self.model.people.Isym[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
    plt.xlabel("Tick")
    plt.ylabel("Symptomatic")
    plt.legend()

    yield "Infectious (Symptomatic)"

    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Infectious (Asymptomatic)") if fig is None else fig

    for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
        plt.plot(self.model.people.Iasym[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
    plt.xlabel("Tick")
    plt.ylabel("Asymptomatic")
    plt.legend()

    yield "Infectious (Asymptomatic)"

    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Infectious (Total)") if fig is None else fig

    for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
        plt.plot(self.model.people.Isym[:, ipatch] + self.model.people.Iasym[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
    plt.xlabel("Tick")
    plt.ylabel("Total Infectious")
    plt.legend()

    yield "Infectious (Total)"

    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Reported vs. Actual Cases") if fig is None else fig

    plt.plot(self.model.patches.reported_cases.sum(axis=1), color="blue", label="Reported")
    plt.plot(self.model.people.Isym.sum(axis=1), color="red", label="Actual")
    plt.xlabel("Tick")
    plt.ylabel("Cases")
    plt.legend()

    yield "Reported Cases"
    return

Parameters

Pipeline component whose only job is to render an extensive parameter overview.

Has no per-tick work — __call__ is a no-op. The plot generator yields nine figures (initial populations, four rate heatmaps, emigration/WASH scatters, mortality and suitability heatmaps) that surface the input parameters for human review.

Attributes:

Name Type Description
model

The parent Model instance.

Source code in src/laser/cholera/metapop/params.py
class Parameters:
    """Pipeline component whose only job is to render an extensive parameter overview.

    Has no per-tick work — `__call__` is a no-op. The
    [`plot`][laser.cholera.metapop.params.Parameters.plot] generator
    yields nine figures (initial populations, four rate heatmaps,
    emigration/WASH scatters, mortality and suitability heatmaps) that
    surface the input parameters for human review.

    Attributes:
        model: The parent `Model` instance.
    """

    def __init__(self, model: "Model") -> None:
        """Register the component on `model` (no state is allocated).

        Args:
            model: The `Model` instance.
        """
        self.model = model

        return

    def check(self):
        """Validate that `model.params` is attached.

        Raises:
            AssertionError: When `model.params` is missing.
        """
        # assert hasattr(self.model, "patches"), "Parameters: model needs to have a 'patches' attribute."
        # assert hasattr(self.model, "people"), "Parameters: model needs to have a 'people' attribute."
        assert hasattr(self.model, "params"), "Parameters: model needs to have a 'params' attribute."

        return

    def __call__(self, _model, _tick):
        """No-op per-tick callable; the component only contributes to the post-run plot."""

    def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
        """Yield nine Matplotlib figures summarizing the input parameters.

        Generates (in order): initial-population stacked bar; `b_jt` /
        `d_jt` / `nu_1_jt` / `nu_2_jt` / `mu_jt` per-patch-per-tick
        heatmaps; `tau_i` and `theta_j` per-patch scatter; `psi_jt`
        suitability heatmap.

        Args:
            fig: Optional existing Matplotlib `Figure` to draw into.

        Yields:
            Nine labels in order: `"Initial Populations by Category"`,
            `"Birth Rates by Location Over Time"`,
            `"Non-Disease Mortality Rates by Location Over Time"`,
            `"First Dose Vaccination Counts by Location Over Time"`,
            `"Second Dose Vaccination Counts by Location Over Time"`,
            `"Disease Mortality Rate by Location Over Time"`,
            `"Emigration Probabilities by Location"`,
            `"WASH Coverage by Location"`,
            `"Environmental Suitability Factor by Location Over Time"`.
        """
        # Stacked bar chart of initial populations
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Initial Populations by Category") if fig is None else fig

        categories = ["S_j_initial", "E_j_initial", "I_j_initial", "R_j_initial", "V1_j_initial", "V2_j_initial"]
        data = [getattr(self.model.params, category) for category in categories]

        x = np.arange(len(self.model.params.location_name))
        bottom = np.zeros(len(self.model.params.location_name))

        for category, values in zip(categories, data, strict=True):
            plt.bar(x, values, bottom=bottom, label=category)
            bottom += values

        plt.xticks(x, self.model.params.location_name, rotation=45, ha="right")
        plt.xlabel("Location Name")
        plt.ylabel("Population")
        plt.legend()

        yield "Initial Populations by Category"

        # Birth rates by location over time
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Birth Rates by Location Over Time") if fig is None else fig

        plt.imshow(self.model.params.b_jt.T, aspect="auto", cmap="Blues", interpolation="nearest")
        plt.colorbar(label="Birth Rate")
        plt.xlabel("Time (Days)")
        plt.ylabel("Location")
        plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

        yield "Birth Rates by Location Over Time"

        # Mortality rates by location over time
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Non-Disease Mortality Rates by Location Over Time") if fig is None else fig

        plt.imshow(self.model.params.d_jt.T, aspect="auto", cmap="Reds", interpolation="nearest")
        plt.colorbar(label="Mortality Rate")
        plt.xlabel("Time (Days)")
        plt.ylabel("Location")
        plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

        yield "Non-Disease Mortality Rates by Location Over Time"

        # Vaccination (first dose) rates by location over time
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="First Dose Vaccination Counts by Location Over Time") if fig is None else fig

        plt.imshow(self.model.params.nu_1_jt.T, aspect="auto", cmap="Greens", interpolation="nearest")
        plt.colorbar(label="Vaccination Count")
        plt.xlabel("Time (Days)")
        plt.ylabel("Location")
        plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

        yield "First Dose Vaccination Counts by Location Over Time"

        # Vaccination (second dose) rates by location over time
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Second Dose Vaccination Counts by Location Over Time") if fig is None else fig

        plt.imshow(self.model.params.nu_2_jt.T, aspect="auto", cmap="Greens", interpolation="nearest")
        plt.colorbar(label="Vaccination Count")
        plt.xlabel("Time (Days)")
        plt.ylabel("Location")
        plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

        yield "Second Dose Vaccination Counts by Location Over Time"

        # Disease mortality rate over time
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Disease Mortality Rate by Location Over Time") if fig is None else fig

        plt.imshow(self.model.params.mu_jt.T, aspect="auto", cmap="Reds", interpolation="nearest")
        plt.colorbar(label="Disease Mortality Rate")
        plt.xlabel("Time (Days)")
        plt.ylabel("Location")
        plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

        yield "Disease Mortality Rate by Location Over Time"

        # Emmigration probability rates by location
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Emigration Probabilities by Location") if fig is None else fig

        plt.scatter(self.model.params.location_name, self.model.params.tau_i, marker="x", color="purple")
        plt.xlabel("Location Name")
        plt.ylabel("Emigration Probability")
        plt.xticks(rotation=45, ha="right")

        yield "Emigration Probabilities by Location"

        # WASH fraction by location
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="WASH Coverage by Location") if fig is None else fig

        plt.scatter(self.model.params.location_name, self.model.params.theta_j, marker="x", color="purple")
        plt.xlabel("Location Name")
        plt.ylabel("WASH Coverage")
        plt.xticks(rotation=45, ha="right")

        yield "WASH Coverage by Location"

        # Environmental suitability factor by location over time
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Environmental Suitability Factor by Location Over Time") if fig is None else fig

        plt.imshow(self.model.params.psi_jt.T, aspect="auto", cmap="Blues", interpolation="nearest")
        plt.colorbar(label="Environmental Suitability Factor")
        plt.xlabel("Time (Days)")
        plt.ylabel("Location")
        plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

        yield "Environmental Suitability Factor by Location Over Time"

        return

model instance-attribute

model = model

__init__

__init__(model: Model) -> None

Register the component on model (no state is allocated).

Parameters:

Name Type Description Default
model Model

The Model instance.

required
Source code in src/laser/cholera/metapop/params.py
def __init__(self, model: "Model") -> None:
    """Register the component on `model` (no state is allocated).

    Args:
        model: The `Model` instance.
    """
    self.model = model

    return

check

check()

Validate that model.params is attached.

Raises:

Type Description
AssertionError

When model.params is missing.

Source code in src/laser/cholera/metapop/params.py
def check(self):
    """Validate that `model.params` is attached.

    Raises:
        AssertionError: When `model.params` is missing.
    """
    # assert hasattr(self.model, "patches"), "Parameters: model needs to have a 'patches' attribute."
    # assert hasattr(self.model, "people"), "Parameters: model needs to have a 'people' attribute."
    assert hasattr(self.model, "params"), "Parameters: model needs to have a 'params' attribute."

    return

__call__

__call__(_model, _tick)

No-op per-tick callable; the component only contributes to the post-run plot.

Source code in src/laser/cholera/metapop/params.py
def __call__(self, _model, _tick):
    """No-op per-tick callable; the component only contributes to the post-run plot."""

plot

plot(fig: Figure = None) -> Iterator[str]

Yield nine Matplotlib figures summarizing the input parameters.

Generates (in order): initial-population stacked bar; b_jt / d_jt / nu_1_jt / nu_2_jt / mu_jt per-patch-per-tick heatmaps; tau_i and theta_j per-patch scatter; psi_jt suitability heatmap.

Parameters:

Name Type Description Default
fig Figure

Optional existing Matplotlib Figure to draw into.

None

Yields:

Type Description
str

Nine labels in order: "Initial Populations by Category",

str

"Birth Rates by Location Over Time",

str

"Non-Disease Mortality Rates by Location Over Time",

str

"First Dose Vaccination Counts by Location Over Time",

str

"Second Dose Vaccination Counts by Location Over Time",

str

"Disease Mortality Rate by Location Over Time",

str

"Emigration Probabilities by Location",

str

"WASH Coverage by Location",

str

"Environmental Suitability Factor by Location Over Time".

Source code in src/laser/cholera/metapop/params.py
def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
    """Yield nine Matplotlib figures summarizing the input parameters.

    Generates (in order): initial-population stacked bar; `b_jt` /
    `d_jt` / `nu_1_jt` / `nu_2_jt` / `mu_jt` per-patch-per-tick
    heatmaps; `tau_i` and `theta_j` per-patch scatter; `psi_jt`
    suitability heatmap.

    Args:
        fig: Optional existing Matplotlib `Figure` to draw into.

    Yields:
        Nine labels in order: `"Initial Populations by Category"`,
        `"Birth Rates by Location Over Time"`,
        `"Non-Disease Mortality Rates by Location Over Time"`,
        `"First Dose Vaccination Counts by Location Over Time"`,
        `"Second Dose Vaccination Counts by Location Over Time"`,
        `"Disease Mortality Rate by Location Over Time"`,
        `"Emigration Probabilities by Location"`,
        `"WASH Coverage by Location"`,
        `"Environmental Suitability Factor by Location Over Time"`.
    """
    # Stacked bar chart of initial populations
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Initial Populations by Category") if fig is None else fig

    categories = ["S_j_initial", "E_j_initial", "I_j_initial", "R_j_initial", "V1_j_initial", "V2_j_initial"]
    data = [getattr(self.model.params, category) for category in categories]

    x = np.arange(len(self.model.params.location_name))
    bottom = np.zeros(len(self.model.params.location_name))

    for category, values in zip(categories, data, strict=True):
        plt.bar(x, values, bottom=bottom, label=category)
        bottom += values

    plt.xticks(x, self.model.params.location_name, rotation=45, ha="right")
    plt.xlabel("Location Name")
    plt.ylabel("Population")
    plt.legend()

    yield "Initial Populations by Category"

    # Birth rates by location over time
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Birth Rates by Location Over Time") if fig is None else fig

    plt.imshow(self.model.params.b_jt.T, aspect="auto", cmap="Blues", interpolation="nearest")
    plt.colorbar(label="Birth Rate")
    plt.xlabel("Time (Days)")
    plt.ylabel("Location")
    plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

    yield "Birth Rates by Location Over Time"

    # Mortality rates by location over time
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Non-Disease Mortality Rates by Location Over Time") if fig is None else fig

    plt.imshow(self.model.params.d_jt.T, aspect="auto", cmap="Reds", interpolation="nearest")
    plt.colorbar(label="Mortality Rate")
    plt.xlabel("Time (Days)")
    plt.ylabel("Location")
    plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

    yield "Non-Disease Mortality Rates by Location Over Time"

    # Vaccination (first dose) rates by location over time
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="First Dose Vaccination Counts by Location Over Time") if fig is None else fig

    plt.imshow(self.model.params.nu_1_jt.T, aspect="auto", cmap="Greens", interpolation="nearest")
    plt.colorbar(label="Vaccination Count")
    plt.xlabel("Time (Days)")
    plt.ylabel("Location")
    plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

    yield "First Dose Vaccination Counts by Location Over Time"

    # Vaccination (second dose) rates by location over time
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Second Dose Vaccination Counts by Location Over Time") if fig is None else fig

    plt.imshow(self.model.params.nu_2_jt.T, aspect="auto", cmap="Greens", interpolation="nearest")
    plt.colorbar(label="Vaccination Count")
    plt.xlabel("Time (Days)")
    plt.ylabel("Location")
    plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

    yield "Second Dose Vaccination Counts by Location Over Time"

    # Disease mortality rate over time
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Disease Mortality Rate by Location Over Time") if fig is None else fig

    plt.imshow(self.model.params.mu_jt.T, aspect="auto", cmap="Reds", interpolation="nearest")
    plt.colorbar(label="Disease Mortality Rate")
    plt.xlabel("Time (Days)")
    plt.ylabel("Location")
    plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

    yield "Disease Mortality Rate by Location Over Time"

    # Emmigration probability rates by location
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Emigration Probabilities by Location") if fig is None else fig

    plt.scatter(self.model.params.location_name, self.model.params.tau_i, marker="x", color="purple")
    plt.xlabel("Location Name")
    plt.ylabel("Emigration Probability")
    plt.xticks(rotation=45, ha="right")

    yield "Emigration Probabilities by Location"

    # WASH fraction by location
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="WASH Coverage by Location") if fig is None else fig

    plt.scatter(self.model.params.location_name, self.model.params.theta_j, marker="x", color="purple")
    plt.xlabel("Location Name")
    plt.ylabel("WASH Coverage")
    plt.xticks(rotation=45, ha="right")

    yield "WASH Coverage by Location"

    # Environmental suitability factor by location over time
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Environmental Suitability Factor by Location Over Time") if fig is None else fig

    plt.imshow(self.model.params.psi_jt.T, aspect="auto", cmap="Blues", interpolation="nearest")
    plt.colorbar(label="Environmental Suitability Factor")
    plt.xlabel("Time (Days)")
    plt.ylabel("Location")
    plt.yticks(ticks=np.arange(len(self.model.params.location_name)), labels=self.model.params.location_name)

    yield "Environmental Suitability Factor by Location Over Time"

    return

Recorder

Pipeline component that dumps a configurable HDF5 snapshot on the final tick.

No per-tick work until the last tick; gated by params.hdf5_output and the params.return property whitelist.

Attributes:

Name Type Description
model

The parent Model instance.

Source code in src/laser/cholera/metapop/recorder.py
class Recorder:
    """Pipeline component that dumps a configurable HDF5 snapshot on the final tick.

    No per-tick work until the last tick; gated by `params.hdf5_output`
    and the `params.return` property whitelist.

    Attributes:
        model: The parent `Model` instance.
    """

    def __init__(self, model: "Model") -> None:
        """Register the component on `model` (no state is allocated).

        Args:
            model: The `Model` instance.
        """
        self.model = model
        return

    def check(self):
        """Warn (but do not fail) if expected `people` / `patches` frames are missing.

        Uses `warnings.warn` rather than `assert` so a recorder
        configured against an unusual minimal model still lets the
        run complete; the final-tick dump will then simply have no
        groups to write.
        """
        if not hasattr(self.model, "people"):
            warnings.warn("Recorder: model expected to have a 'people' attribute.", stacklevel=1)
        if not hasattr(self.model, "patches"):
            warnings.warn("Recorder: model expected to have a 'patches' attribute.", stacklevel=1)

        return

    def __call__(self, model: "Model", tick: int) -> None:
        """On the final tick, write whitelisted state to HDF5 if `hdf5_output` is set.

        Quietly returns (with an info-level log explaining which gate
        was unmet) when either `params.hdf5_output` is false or
        `params.return` is unset / empty. When both are present and
        truthy, dispatches to
        [`save_hdf5_parameters`][laser.cholera.metapop.recorder.save_hdf5_parameters]
        or
        [`save_compressed_hdf5_parameters`][laser.cholera.metapop.recorder.save_compressed_hdf5_parameters]
        based on `params.compress`.

        Args:
            model: The parent `Model` instance.
            tick: Current simulation tick.
        """
        # write the current state of the model to an HDF5 file if it is the last tick of the simulation
        if tick == (model.params.nticks - 1):
            # To get output must a) specify hdf5_output = true in the params file and b) specify properties to return
            write_output = ("hdf5_output" in model.params) and model.params.hdf5_output and ("return" in model.params) and model.params["return"]

            if write_output:
                root = Path(model.params.outdir) if "outdir" in model.params and model.params.outdir else Path.cwd()
                root.mkdir(parents=True, exist_ok=True)
                filename = root / f"{datetime.now().strftime('%Y%m%d%H%M%S')}.h5"  # noqa: DTZ005

                if ("compress" in model.params) and model.params.compress:
                    filename = save_compressed_hdf5_parameters(model, filename)
                else:
                    filename = save_hdf5_parameters(model, filename)

                logger.info(f"Recorder: model state saved to {filename}")
            else:
                logger.info("Recorder: model state not saved to HDF5 file.")
                logger.info(
                    f"\t'hdf5_output' {'is' if 'hdf5_output' in model.params else 'is not'} in the params file."
                    + (f" hdf5_output = {model.params.hdf5_output}" if "hdf5_output" in model.params else "")
                )
                logger.info(
                    f"\t'return' {'is' if 'return' in model.params else 'is not'} in the params file."
                    + (f" return = {model.params['return']}" if "return" in model.params else "")
                )

        return

model instance-attribute

model = model

__init__

__init__(model: Model) -> None

Register the component on model (no state is allocated).

Parameters:

Name Type Description Default
model Model

The Model instance.

required
Source code in src/laser/cholera/metapop/recorder.py
def __init__(self, model: "Model") -> None:
    """Register the component on `model` (no state is allocated).

    Args:
        model: The `Model` instance.
    """
    self.model = model
    return

check

check()

Warn (but do not fail) if expected people / patches frames are missing.

Uses warnings.warn rather than assert so a recorder configured against an unusual minimal model still lets the run complete; the final-tick dump will then simply have no groups to write.

Source code in src/laser/cholera/metapop/recorder.py
def check(self):
    """Warn (but do not fail) if expected `people` / `patches` frames are missing.

    Uses `warnings.warn` rather than `assert` so a recorder
    configured against an unusual minimal model still lets the
    run complete; the final-tick dump will then simply have no
    groups to write.
    """
    if not hasattr(self.model, "people"):
        warnings.warn("Recorder: model expected to have a 'people' attribute.", stacklevel=1)
    if not hasattr(self.model, "patches"):
        warnings.warn("Recorder: model expected to have a 'patches' attribute.", stacklevel=1)

    return

__call__

__call__(model: Model, tick: int) -> None

On the final tick, write whitelisted state to HDF5 if hdf5_output is set.

Quietly returns (with an info-level log explaining which gate was unmet) when either params.hdf5_output is false or params.return is unset / empty. When both are present and truthy, dispatches to save_hdf5_parameters or save_compressed_hdf5_parameters based on params.compress.

Parameters:

Name Type Description Default
model Model

The parent Model instance.

required
tick int

Current simulation tick.

required
Source code in src/laser/cholera/metapop/recorder.py
def __call__(self, model: "Model", tick: int) -> None:
    """On the final tick, write whitelisted state to HDF5 if `hdf5_output` is set.

    Quietly returns (with an info-level log explaining which gate
    was unmet) when either `params.hdf5_output` is false or
    `params.return` is unset / empty. When both are present and
    truthy, dispatches to
    [`save_hdf5_parameters`][laser.cholera.metapop.recorder.save_hdf5_parameters]
    or
    [`save_compressed_hdf5_parameters`][laser.cholera.metapop.recorder.save_compressed_hdf5_parameters]
    based on `params.compress`.

    Args:
        model: The parent `Model` instance.
        tick: Current simulation tick.
    """
    # write the current state of the model to an HDF5 file if it is the last tick of the simulation
    if tick == (model.params.nticks - 1):
        # To get output must a) specify hdf5_output = true in the params file and b) specify properties to return
        write_output = ("hdf5_output" in model.params) and model.params.hdf5_output and ("return" in model.params) and model.params["return"]

        if write_output:
            root = Path(model.params.outdir) if "outdir" in model.params and model.params.outdir else Path.cwd()
            root.mkdir(parents=True, exist_ok=True)
            filename = root / f"{datetime.now().strftime('%Y%m%d%H%M%S')}.h5"  # noqa: DTZ005

            if ("compress" in model.params) and model.params.compress:
                filename = save_compressed_hdf5_parameters(model, filename)
            else:
                filename = save_hdf5_parameters(model, filename)

            logger.info(f"Recorder: model state saved to {filename}")
        else:
            logger.info("Recorder: model state not saved to HDF5 file.")
            logger.info(
                f"\t'hdf5_output' {'is' if 'hdf5_output' in model.params else 'is not'} in the params file."
                + (f" hdf5_output = {model.params.hdf5_output}" if "hdf5_output" in model.params else "")
            )
            logger.info(
                f"\t'return' {'is' if 'return' in model.params else 'is not'} in the params file."
                + (f" return = {model.params['return']}" if "return" in model.params else "")
            )

    return

Recovered

Recovered compartment: tracks R_j(t) and lets natural immunity wane back to S.

Attributes:

Name Type Description
model

The parent Model instance.

Source code in src/laser/cholera/metapop/recovered.py
class Recovered:
    """Recovered compartment: tracks `R_j(t)` and lets natural immunity wane back to `S`.

    Attributes:
        model: The parent `Model` instance.
    """

    def __init__(self, model: "Model") -> None:
        """Allocate the `R` state vector and seed it from `R_j_initial`.

        Args:
            model: The `Model` instance. Must have `people` and `params`
                set up, with `params.R_j_initial` populated.

        Raises:
            AttributeError: When `model` is missing `people` or
                `params`.
            ValueError: When `params.R_j_initial` is missing.
        """
        self.model = model

        check_attr(model, "people", "Recovered: model needs to have a 'people' attribute.")
        model.people.add_vector_property("R", length=model.params.nticks + 1, dtype=np.int32, default=0)
        check_attr(model, "params", "Recovered: model needs to have a 'params' attribute.")
        check_key(model.params, "R_j_initial", "Recovered: model params needs to have a 'R_j_initial' (initial recovered population) parameter.")

        model.people.R[0] = model.params.R_j_initial

        return

    def check(self):
        """Validate that `S` (waning destination), `d_jt`, and `epsilon` are available.

        Raises:
            AttributeError: When `model.people.S` is missing.
            ValueError: When `params.d_jt` or `params.epsilon` is missing.
        """
        check_attr(self.model.people, "S", "Recovered: model people needs to have a 'S' (susceptible) attribute.")
        check_key(self.model.params, "d_jt", "Recovered: model params needs to have a 'd_jt' (mortality rate) parameter.")
        check_key(self.model.params, "epsilon", "Recovered: model params needs to have a 'epsilon' (waning immunity rate) parameter.")
        if not hasattr(self.model.patches, "non_disease_deaths"):
            self.model.patches.add_vector_property("non_disease_deaths", length=self.model.params.nticks + 1, dtype=np.int32, default=0)
        # PERF: install `model.patches.non_disease_death_prob_jt` (the
        # `1 - exp(-d_jt)` cache) idempotently if no earlier component has.
        # Lets each consumer be exercised in isolation; the cache is built
        # exactly once across the pipeline.
        if not hasattr(self.model.patches, "non_disease_death_prob_jt"):
            self.model.patches.add_vector_property("non_disease_death_prob_jt", length=self.model.params.d_jt.shape[0], dtype=np.float32, default=0.0)
            self.model.patches.non_disease_death_prob_jt[:] = -np.expm1(-self.model.params.d_jt)

        # PERF: cache `1 - exp(-epsilon)` so the per-tick waning probability
        # is not recomputed every call.
        self._waning_prob = -np.expm1(-self.model.params.epsilon)

        return

    def __call__(self, model: "Model", tick: int) -> None:
        """Advance `R` from `tick` to `tick + 1`: carry forward, subtract deaths, wane to `S`.

        Waning is computed against the post-deaths cohort so dying-then-
        waning individuals are not counted twice.

        Args:
            model: The parent `Model` instance.
            tick: Current simulation tick.

        Raises:
            AssertionError: When the post-deaths-and-waning recovered
                population goes negative.
        """
        R = model.people.R[tick]
        R_next = model.people.R[tick + 1]
        S_next = model.people.S[tick + 1]

        R_next += R

        # natural mortality
        # PERF: pre-computed `-np.expm1(-d_jt)` cached as model.patches.non_disease_death_prob_jt.
        # non_disease_deaths = model.prng.binomial(R, -np.expm1(-model.params.d_jt[tick])).astype(R_next.dtype)
        non_disease_deaths = model.prng.binomial(R, model.patches.non_disease_death_prob_jt[tick]).astype(R_next.dtype)
        R_next -= non_disease_deaths
        model.patches.non_disease_deaths[tick] += non_disease_deaths

        # waning natural immunity - don't include those removed by natural mortality
        # PERF: pre-computed `-np.expm1(-epsilon)` cached as self._waning_prob.
        # waned = model.prng.binomial(R - non_disease_deaths, -np.expm1(-model.params.epsilon)).astype(R_next.dtype)
        waned = model.prng.binomial(R - non_disease_deaths, self._waning_prob).astype(R_next.dtype)
        R_next -= waned
        S_next += waned

        assert np.all(R_next >= 0), f"Negative recovered populations at tick {tick + 1}.\n\t{R_next=}"

        return

    def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
        """Yield one Matplotlib figure of `R(t)` for the ten largest patches.

        Args:
            fig: Optional existing Matplotlib `Figure` to draw into.

        Yields:
            The string label `"Recovered"`.
        """
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Recovered") if fig is None else fig

        for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
            plt.plot(self.model.people.R[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
        plt.xlabel("Tick")
        plt.ylabel("Recovered")
        plt.legend()

        yield "Recovered"
        return

model instance-attribute

model = model

__init__

__init__(model: Model) -> None

Allocate the R state vector and seed it from R_j_initial.

Parameters:

Name Type Description Default
model Model

The Model instance. Must have people and params set up, with params.R_j_initial populated.

required

Raises:

Type Description
AttributeError

When model is missing people or params.

ValueError

When params.R_j_initial is missing.

Source code in src/laser/cholera/metapop/recovered.py
def __init__(self, model: "Model") -> None:
    """Allocate the `R` state vector and seed it from `R_j_initial`.

    Args:
        model: The `Model` instance. Must have `people` and `params`
            set up, with `params.R_j_initial` populated.

    Raises:
        AttributeError: When `model` is missing `people` or
            `params`.
        ValueError: When `params.R_j_initial` is missing.
    """
    self.model = model

    check_attr(model, "people", "Recovered: model needs to have a 'people' attribute.")
    model.people.add_vector_property("R", length=model.params.nticks + 1, dtype=np.int32, default=0)
    check_attr(model, "params", "Recovered: model needs to have a 'params' attribute.")
    check_key(model.params, "R_j_initial", "Recovered: model params needs to have a 'R_j_initial' (initial recovered population) parameter.")

    model.people.R[0] = model.params.R_j_initial

    return

check

check()

Validate that S (waning destination), d_jt, and epsilon are available.

Raises:

Type Description
AttributeError

When model.people.S is missing.

ValueError

When params.d_jt or params.epsilon is missing.

Source code in src/laser/cholera/metapop/recovered.py
def check(self):
    """Validate that `S` (waning destination), `d_jt`, and `epsilon` are available.

    Raises:
        AttributeError: When `model.people.S` is missing.
        ValueError: When `params.d_jt` or `params.epsilon` is missing.
    """
    check_attr(self.model.people, "S", "Recovered: model people needs to have a 'S' (susceptible) attribute.")
    check_key(self.model.params, "d_jt", "Recovered: model params needs to have a 'd_jt' (mortality rate) parameter.")
    check_key(self.model.params, "epsilon", "Recovered: model params needs to have a 'epsilon' (waning immunity rate) parameter.")
    if not hasattr(self.model.patches, "non_disease_deaths"):
        self.model.patches.add_vector_property("non_disease_deaths", length=self.model.params.nticks + 1, dtype=np.int32, default=0)
    # PERF: install `model.patches.non_disease_death_prob_jt` (the
    # `1 - exp(-d_jt)` cache) idempotently if no earlier component has.
    # Lets each consumer be exercised in isolation; the cache is built
    # exactly once across the pipeline.
    if not hasattr(self.model.patches, "non_disease_death_prob_jt"):
        self.model.patches.add_vector_property("non_disease_death_prob_jt", length=self.model.params.d_jt.shape[0], dtype=np.float32, default=0.0)
        self.model.patches.non_disease_death_prob_jt[:] = -np.expm1(-self.model.params.d_jt)

    # PERF: cache `1 - exp(-epsilon)` so the per-tick waning probability
    # is not recomputed every call.
    self._waning_prob = -np.expm1(-self.model.params.epsilon)

    return

__call__

__call__(model: Model, tick: int) -> None

Advance R from tick to tick + 1: carry forward, subtract deaths, wane to S.

Waning is computed against the post-deaths cohort so dying-then- waning individuals are not counted twice.

Parameters:

Name Type Description Default
model Model

The parent Model instance.

required
tick int

Current simulation tick.

required

Raises:

Type Description
AssertionError

When the post-deaths-and-waning recovered population goes negative.

Source code in src/laser/cholera/metapop/recovered.py
def __call__(self, model: "Model", tick: int) -> None:
    """Advance `R` from `tick` to `tick + 1`: carry forward, subtract deaths, wane to `S`.

    Waning is computed against the post-deaths cohort so dying-then-
    waning individuals are not counted twice.

    Args:
        model: The parent `Model` instance.
        tick: Current simulation tick.

    Raises:
        AssertionError: When the post-deaths-and-waning recovered
            population goes negative.
    """
    R = model.people.R[tick]
    R_next = model.people.R[tick + 1]
    S_next = model.people.S[tick + 1]

    R_next += R

    # natural mortality
    # PERF: pre-computed `-np.expm1(-d_jt)` cached as model.patches.non_disease_death_prob_jt.
    # non_disease_deaths = model.prng.binomial(R, -np.expm1(-model.params.d_jt[tick])).astype(R_next.dtype)
    non_disease_deaths = model.prng.binomial(R, model.patches.non_disease_death_prob_jt[tick]).astype(R_next.dtype)
    R_next -= non_disease_deaths
    model.patches.non_disease_deaths[tick] += non_disease_deaths

    # waning natural immunity - don't include those removed by natural mortality
    # PERF: pre-computed `-np.expm1(-epsilon)` cached as self._waning_prob.
    # waned = model.prng.binomial(R - non_disease_deaths, -np.expm1(-model.params.epsilon)).astype(R_next.dtype)
    waned = model.prng.binomial(R - non_disease_deaths, self._waning_prob).astype(R_next.dtype)
    R_next -= waned
    S_next += waned

    assert np.all(R_next >= 0), f"Negative recovered populations at tick {tick + 1}.\n\t{R_next=}"

    return

plot

plot(fig: Figure = None) -> Iterator[str]

Yield one Matplotlib figure of R(t) for the ten largest patches.

Parameters:

Name Type Description Default
fig Figure

Optional existing Matplotlib Figure to draw into.

None

Yields:

Type Description
str

The string label "Recovered".

Source code in src/laser/cholera/metapop/recovered.py
def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
    """Yield one Matplotlib figure of `R(t)` for the ten largest patches.

    Args:
        fig: Optional existing Matplotlib `Figure` to draw into.

    Yields:
        The string label `"Recovered"`.
    """
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Recovered") if fig is None else fig

    for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
        plt.plot(self.model.people.R[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
    plt.xlabel("Tick")
    plt.ylabel("Recovered")
    plt.legend()

    yield "Recovered"
    return

Susceptible

Bases: Component

Susceptible compartment: tracks S_j(t) and runs births / non-disease deaths each tick.

Attributes:

Name Type Description
model

The parent Model instance; used to access people, patches, params, and the PRNG.

Source code in src/laser/cholera/metapop/susceptible.py
class Susceptible(Component):
    """Susceptible compartment: tracks `S_j(t)` and runs births / non-disease deaths each tick.

    Attributes:
        model: The parent `Model` instance; used to access `people`,
            `patches`, `params`, and the PRNG.
    """

    def __init__(self, model: "Model"):
        """Allocate the `S` state vector and seed it from `S_j_initial`.

        Adds `model.people.S` (shape `(nticks + 1, npatches)`) and
        `model.patches.births` (per-tick birth counts) as `int32` vector
        properties, then writes the initial susceptible counts from
        `params.S_j_initial` into `S[0]`.

        Args:
            model: The `Model` instance. Must already have `people`,
                `patches`, and `params` set up, and `params.S_j_initial`
                populated.

        Raises:
            AttributeError: When `model` is missing `people`, `patches`,
                or `params`.
            ValueError: When `params.S_j_initial` is missing.
        """
        self.model = model

        check_attr(model, "people", "Susceptible: model needs to have an 'people' attribute.")
        model.people.add_vector_property("S", length=model.params.nticks + 1, dtype=np.int32, default=0)
        check_attr(model, "patches", "Susceptible: model needs to have a 'patches' attribute.")
        model.patches.add_vector_property("births", length=model.params.nticks + 1, dtype=np.int32, default=0)
        check_attr(self.model, "params", "Susceptible: model needs to have a 'params' attribute.")
        check_key(self.model.params, "S_j_initial", "Susceptible: model params needs to have a 'S_j_initial' parameter.")
        model.people.S[0] = model.params.S_j_initial

        return

    def check(self):
        """Validate prerequisites that other components are expected to set up.

        Confirms `model.patches.N` (population census, set up by
        [`Census`][laser.cholera.metapop.census.Census]) and
        `params.b_jt` / `params.d_jt` (birth / non-disease-mortality
        matrices) are present. Lazily allocates
        `model.patches.non_disease_deaths` if no earlier component has
        already done so.

        Raises:
            AttributeError: When `model.patches.N` is missing.
            ValueError: When `params.b_jt` or `params.d_jt` is missing.
        """
        check_attr(self.model.patches, "N", "Susceptible: model.patches needs to have a 'N' attribute.")
        check_attr(self.model.params, "b_jt", "Susceptible: model.params needs to have a 'b_jt' attribute.")
        check_attr(self.model.params, "d_jt", "Susceptible: model.params needs to have a 'd_jt' attribute.")
        if not hasattr(self.model.patches, "non_disease_deaths"):
            self.model.patches.add_vector_property("non_disease_deaths", length=self.model.params.nticks + 1, dtype=np.int32, default=0)

        # PERF: pre-compute the per-tick non-disease-death probability matrix
        # once here. `d_jt` is a static `(nticks, npatches)` parameter, so
        # `1 - exp(-d_jt)` is also static. Without this cache, seven sites
        # (Susceptible / Exposed / Recovered / Infectious x2 / Vaccinated x2)
        # would each recompute `-np.expm1(-d_jt[tick])` every tick.
        if not hasattr(self.model.patches, "non_disease_death_prob_jt"):
            self.model.patches.add_vector_property("non_disease_death_prob_jt", length=self.model.params.d_jt.shape[0], dtype=np.float32, default=0.0)
            self.model.patches.non_disease_death_prob_jt[:] = -np.expm1(-self.model.params.d_jt)

        return

    def __call__(self, model: "Model", tick: int) -> None:
        """Advance `S` from `tick` to `tick + 1`: carry forward, kill, then birth.

        For each patch:

        1. `S[tick + 1] := S[tick]` (carry forward).
        2. Sample non-disease deaths from `Binomial(S, 1 - exp(-d_jt))`
            and subtract; bank into `patches.non_disease_deaths[tick]`.
        3. Sample births from `Poisson(N * b_jt[tick])` (where `N` is
            the current total patch population from `Census`) and add;
            record into `patches.births[tick]`.

        Args:
            model: The parent `Model` instance.
            tick: Current simulation tick (0-indexed); `S[tick + 1]` is
                the slice this method writes to.

        Raises:
            AssertionError: When the post-deaths susceptible population
                goes negative (indicates a draw exceeded the population,
                which should be impossible for a `Binomial(S, p)` draw).
        """
        S_next = model.people.S[tick + 1]
        S_next[:] = model.people.S[tick]

        # natural mortality
        # PERF: `model.patches.non_disease_death_prob_jt[tick]` is the pre-computed
        # `-np.expm1(-model.params.d_jt[tick])` cached at check() time.
        # non_disease_deaths = model.prng.binomial(S_next, -np.expm1(-model.params.d_jt[tick])).astype(S_next.dtype)
        non_disease_deaths = model.prng.binomial(S_next, model.patches.non_disease_death_prob_jt[tick]).astype(S_next.dtype)
        S_next -= non_disease_deaths
        model.patches.non_disease_deaths[tick] += non_disease_deaths

        assert np.all(S_next >= 0), f"Negative susceptible populations at tick {tick + 1}.\n\t{S_next=}"

        # births
        N = model.patches.N[tick]
        births = model.prng.poisson(N * model.params.b_jt[tick]).astype(S_next.dtype)
        S_next[:] += births
        model.patches.births[tick] = births

        return

    def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
        """Yield one Matplotlib figure showing `S(t)` for the ten largest patches.

        Patches are ranked by `params.S_j_initial` so the largest
        initial-susceptible populations are surfaced. Used by
        [`Model.visualize`][laser.cholera.metapop.model.Model] to
        generate the per-component PDF / on-screen plots.

        Args:
            fig: Optional existing Matplotlib `Figure` to draw into. If
                omitted, a fresh `(12, 9)` figure is created.

        Yields:
            The string label `"Susceptible"` (used by the visualizer as
            the figure title / PDF section heading).
        """
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Susceptible") if fig is None else fig

        for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
            plt.plot(self.model.people.S[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
        plt.xlabel("Tick")
        plt.ylabel("Susceptible")
        plt.legend()

        yield "Susceptible"

        return

model instance-attribute

model = model

__init__

__init__(model: Model)

Allocate the S state vector and seed it from S_j_initial.

Adds model.people.S (shape (nticks + 1, npatches)) and model.patches.births (per-tick birth counts) as int32 vector properties, then writes the initial susceptible counts from params.S_j_initial into S[0].

Parameters:

Name Type Description Default
model Model

The Model instance. Must already have people, patches, and params set up, and params.S_j_initial populated.

required

Raises:

Type Description
AttributeError

When model is missing people, patches, or params.

ValueError

When params.S_j_initial is missing.

Source code in src/laser/cholera/metapop/susceptible.py
def __init__(self, model: "Model"):
    """Allocate the `S` state vector and seed it from `S_j_initial`.

    Adds `model.people.S` (shape `(nticks + 1, npatches)`) and
    `model.patches.births` (per-tick birth counts) as `int32` vector
    properties, then writes the initial susceptible counts from
    `params.S_j_initial` into `S[0]`.

    Args:
        model: The `Model` instance. Must already have `people`,
            `patches`, and `params` set up, and `params.S_j_initial`
            populated.

    Raises:
        AttributeError: When `model` is missing `people`, `patches`,
            or `params`.
        ValueError: When `params.S_j_initial` is missing.
    """
    self.model = model

    check_attr(model, "people", "Susceptible: model needs to have an 'people' attribute.")
    model.people.add_vector_property("S", length=model.params.nticks + 1, dtype=np.int32, default=0)
    check_attr(model, "patches", "Susceptible: model needs to have a 'patches' attribute.")
    model.patches.add_vector_property("births", length=model.params.nticks + 1, dtype=np.int32, default=0)
    check_attr(self.model, "params", "Susceptible: model needs to have a 'params' attribute.")
    check_key(self.model.params, "S_j_initial", "Susceptible: model params needs to have a 'S_j_initial' parameter.")
    model.people.S[0] = model.params.S_j_initial

    return

check

check()

Validate prerequisites that other components are expected to set up.

Confirms model.patches.N (population census, set up by Census) and params.b_jt / params.d_jt (birth / non-disease-mortality matrices) are present. Lazily allocates model.patches.non_disease_deaths if no earlier component has already done so.

Raises:

Type Description
AttributeError

When model.patches.N is missing.

ValueError

When params.b_jt or params.d_jt is missing.

Source code in src/laser/cholera/metapop/susceptible.py
def check(self):
    """Validate prerequisites that other components are expected to set up.

    Confirms `model.patches.N` (population census, set up by
    [`Census`][laser.cholera.metapop.census.Census]) and
    `params.b_jt` / `params.d_jt` (birth / non-disease-mortality
    matrices) are present. Lazily allocates
    `model.patches.non_disease_deaths` if no earlier component has
    already done so.

    Raises:
        AttributeError: When `model.patches.N` is missing.
        ValueError: When `params.b_jt` or `params.d_jt` is missing.
    """
    check_attr(self.model.patches, "N", "Susceptible: model.patches needs to have a 'N' attribute.")
    check_attr(self.model.params, "b_jt", "Susceptible: model.params needs to have a 'b_jt' attribute.")
    check_attr(self.model.params, "d_jt", "Susceptible: model.params needs to have a 'd_jt' attribute.")
    if not hasattr(self.model.patches, "non_disease_deaths"):
        self.model.patches.add_vector_property("non_disease_deaths", length=self.model.params.nticks + 1, dtype=np.int32, default=0)

    # PERF: pre-compute the per-tick non-disease-death probability matrix
    # once here. `d_jt` is a static `(nticks, npatches)` parameter, so
    # `1 - exp(-d_jt)` is also static. Without this cache, seven sites
    # (Susceptible / Exposed / Recovered / Infectious x2 / Vaccinated x2)
    # would each recompute `-np.expm1(-d_jt[tick])` every tick.
    if not hasattr(self.model.patches, "non_disease_death_prob_jt"):
        self.model.patches.add_vector_property("non_disease_death_prob_jt", length=self.model.params.d_jt.shape[0], dtype=np.float32, default=0.0)
        self.model.patches.non_disease_death_prob_jt[:] = -np.expm1(-self.model.params.d_jt)

    return

__call__

__call__(model: Model, tick: int) -> None

Advance S from tick to tick + 1: carry forward, kill, then birth.

For each patch:

  1. S[tick + 1] := S[tick] (carry forward).
  2. Sample non-disease deaths from Binomial(S, 1 - exp(-d_jt)) and subtract; bank into patches.non_disease_deaths[tick].
  3. Sample births from Poisson(N * b_jt[tick]) (where N is the current total patch population from Census) and add; record into patches.births[tick].

Parameters:

Name Type Description Default
model Model

The parent Model instance.

required
tick int

Current simulation tick (0-indexed); S[tick + 1] is the slice this method writes to.

required

Raises:

Type Description
AssertionError

When the post-deaths susceptible population goes negative (indicates a draw exceeded the population, which should be impossible for a Binomial(S, p) draw).

Source code in src/laser/cholera/metapop/susceptible.py
def __call__(self, model: "Model", tick: int) -> None:
    """Advance `S` from `tick` to `tick + 1`: carry forward, kill, then birth.

    For each patch:

    1. `S[tick + 1] := S[tick]` (carry forward).
    2. Sample non-disease deaths from `Binomial(S, 1 - exp(-d_jt))`
        and subtract; bank into `patches.non_disease_deaths[tick]`.
    3. Sample births from `Poisson(N * b_jt[tick])` (where `N` is
        the current total patch population from `Census`) and add;
        record into `patches.births[tick]`.

    Args:
        model: The parent `Model` instance.
        tick: Current simulation tick (0-indexed); `S[tick + 1]` is
            the slice this method writes to.

    Raises:
        AssertionError: When the post-deaths susceptible population
            goes negative (indicates a draw exceeded the population,
            which should be impossible for a `Binomial(S, p)` draw).
    """
    S_next = model.people.S[tick + 1]
    S_next[:] = model.people.S[tick]

    # natural mortality
    # PERF: `model.patches.non_disease_death_prob_jt[tick]` is the pre-computed
    # `-np.expm1(-model.params.d_jt[tick])` cached at check() time.
    # non_disease_deaths = model.prng.binomial(S_next, -np.expm1(-model.params.d_jt[tick])).astype(S_next.dtype)
    non_disease_deaths = model.prng.binomial(S_next, model.patches.non_disease_death_prob_jt[tick]).astype(S_next.dtype)
    S_next -= non_disease_deaths
    model.patches.non_disease_deaths[tick] += non_disease_deaths

    assert np.all(S_next >= 0), f"Negative susceptible populations at tick {tick + 1}.\n\t{S_next=}"

    # births
    N = model.patches.N[tick]
    births = model.prng.poisson(N * model.params.b_jt[tick]).astype(S_next.dtype)
    S_next[:] += births
    model.patches.births[tick] = births

    return

plot

plot(fig: Figure = None) -> Iterator[str]

Yield one Matplotlib figure showing S(t) for the ten largest patches.

Patches are ranked by params.S_j_initial so the largest initial-susceptible populations are surfaced. Used by Model.visualize to generate the per-component PDF / on-screen plots.

Parameters:

Name Type Description Default
fig Figure

Optional existing Matplotlib Figure to draw into. If omitted, a fresh (12, 9) figure is created.

None

Yields:

Type Description
str

The string label "Susceptible" (used by the visualizer as

str

the figure title / PDF section heading).

Source code in src/laser/cholera/metapop/susceptible.py
def plot(self, fig: Figure = None) -> Iterator[str]:  # pragma: no cover
    """Yield one Matplotlib figure showing `S(t)` for the ten largest patches.

    Patches are ranked by `params.S_j_initial` so the largest
    initial-susceptible populations are surfaced. Used by
    [`Model.visualize`][laser.cholera.metapop.model.Model] to
    generate the per-component PDF / on-screen plots.

    Args:
        fig: Optional existing Matplotlib `Figure` to draw into. If
            omitted, a fresh `(12, 9)` figure is created.

    Yields:
        The string label `"Susceptible"` (used by the visualizer as
        the figure title / PDF section heading).
    """
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Susceptible") if fig is None else fig

    for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
        plt.plot(self.model.people.S[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
    plt.xlabel("Tick")
    plt.ylabel("Susceptible")
    plt.legend()

    yield "Susceptible"

    return

Vaccinated

Vaccinated compartment: tracks V1(t) / V2(t) and the per-tick dose flows.

Attributes:

Name Type Description
model

The parent Model instance.

sources

Names of model.people compartments eligible to draw first doses from (default ["S", "E", "Isym", "Iasym", "R"], overridable via params.nu_jt_sources).

Source code in src/laser/cholera/metapop/vaccinated.py
class Vaccinated:
    """Vaccinated compartment: tracks `V1(t)` / `V2(t)` and the per-tick dose flows.

    Attributes:
        model: The parent `Model` instance.
        sources: Names of `model.people` compartments eligible to draw
            first doses from (default `["S", "E", "Isym", "Iasym", "R"]`,
            overridable via `params.nu_jt_sources`).
    """

    def __init__(self, model: "Model") -> None:
        """Allocate `V1` / `V2` and the dose-bookkeeping vectors; seed from `V*_j_initial`.

        Args:
            model: The `Model` instance. Must have `people`, `patches`,
                and `params`, with `params.V1_j_initial` and
                `params.V2_j_initial` populated.

        Raises:
            AttributeError: When `model` is missing `people` or
                `patches`.
            ValueError: When `params.V1_j_initial` or
                `params.V2_j_initial` is missing.
        """
        self.model = model

        check_attr(model, "people", "Vaccinated: model needs to have a 'people' attribute.")
        model.people.add_vector_property("V1", length=model.params.nticks + 1, dtype=np.int32, default=0)
        model.people.add_vector_property("V2", length=model.params.nticks + 1, dtype=np.int32, default=0)
        # We will track doses on the date (tick) given to more easily match nu_1_jt and nu_2_jt.
        model.patches.add_vector_property("dose_one_doses", length=model.params.nticks, dtype=np.int32, default=0)
        model.patches.add_vector_property("dose_two_doses", length=model.params.nticks, dtype=np.int32, default=0)
        check_key(
            model.params,
            "V1_j_initial",
            "Vaccinated: model params needs to have a 'V1_j_initial' (initial one dose vaccinated population) parameter.",
        )
        check_key(
            model.params,
            "V2_j_initial",
            "Vaccinated: model params needs to have a 'V2_j_initial' (initial two dose vaccinated population) parameter.",
        )
        model.people.V1[0] = model.params.V1_j_initial
        model.people.V2[0] = model.params.V2_j_initial

        self.sources = model.params.nu_jt_sources if "nu_jt_sources" in model.params else ["S", "E", "Isym", "Iasym", "R"]

        return

    def check(self):
        """Validate dose-related parameters and the source compartments.

        Asserts that `model.people.S` and `model.people.E` exist and
        that `params` provides `phi_1`, `phi_2`, `omega_1`, `omega_2`,
        `nu_1_jt`, `nu_2_jt`, and `d_jt`.

        Raises:
            AttributeError: When `model.people.S` or `.E` is missing.
            ValueError: When any of `params.phi_1`, `phi_2`, `omega_1`,
                `omega_2`, `nu_1_jt`, `nu_2_jt`, `d_jt` is missing.
        """
        check_attr(self.model.people, "S", "Vaccinated: model people needs to have a 'S' (susceptible) attribute.")
        check_attr(self.model.people, "E", "Vaccinated: model people needs to have a 'E' (exposed) attribute.")

        check_key(self.model.params, "phi_1", "Vaccinated: model params needs to have a 'phi_1' parameter.")
        check_key(self.model.params, "phi_2", "Vaccinated: model params needs to have a 'phi_2' parameter.")
        check_key(self.model.params, "omega_1", "Vaccinated: model params needs to have a 'omega_1' parameter.")
        check_key(self.model.params, "omega_2", "Vaccinated: model params needs to have a 'omega_2' parameter.")
        check_key(self.model.params, "nu_1_jt", "Vaccinated: model params needs to have a 'nu_1_jt' parameter.")
        check_key(self.model.params, "nu_2_jt", "Vaccinated: model params needs to have a 'nu_2_jt' parameter.")

        check_key(self.model.params, "d_jt", "Vaccinated: model.params needs to have a 'd_jt' attribute.")

        if not hasattr(self.model.patches, "non_disease_deaths"):
            self.model.patches.add_vector_property("non_disease_deaths", length=self.model.params.nticks + 1, dtype=np.int32, default=0)
        # PERF: install `model.patches.non_disease_death_prob_jt` (the
        # `1 - exp(-d_jt)` cache) idempotently if no earlier component has.
        # Lets each consumer be exercised in isolation; the cache is built
        # exactly once across the pipeline.
        if not hasattr(self.model.patches, "non_disease_death_prob_jt"):
            self.model.patches.add_vector_property("non_disease_death_prob_jt", length=self.model.params.d_jt.shape[0], dtype=np.float32, default=0.0)
            self.model.patches.non_disease_death_prob_jt[:] = -np.expm1(-self.model.params.d_jt)

        # PERF: cache `1 - exp(-omega_{1,2})` so the per-tick waning
        # probabilities are not recomputed every call.
        self._omega_1_prob = -np.expm1(-self.model.params.omega_1)
        self._omega_2_prob = -np.expm1(-self.model.params.omega_2)

        return

    def __call__(self, model: "Model", tick: int) -> None:
        """Advance `V1` / `V2` one tick: deaths, waning, then dose deliveries.

        Doses scheduled for this tick are clamped against the available
        donor population (warning logged at `DEBUG` if the schedule
        exceeds capacity). Only the `phi_*`-effective fraction transits
        to the vaccinated compartment; ineffective doses leave the
        recipient in their original compartment.

        Args:
            model: The parent `Model` instance.
            tick: Current simulation tick.
        """
        V1 = model.people.V1[tick]
        V1_next = model.people.V1[tick + 1]
        V2 = model.people.V2[tick]
        V2_next = model.people.V2[tick + 1]
        S_next = model.people.S[tick + 1]

        # propagate the current values forward (V(t+1) = V(t) + ∆V)
        V1_next[:] = V1
        V2_next[:] = V2

        # -natural mortality
        # PERF: pre-computed `-np.expm1(-d_jt)` cached as model.patches.non_disease_death_prob_jt.
        # non_disease_deaths = model.prng.binomial(V1_next, -np.expm1(-model.params.d_jt[tick])).astype(V1_next.dtype)
        non_disease_deaths = model.prng.binomial(V1_next, model.patches.non_disease_death_prob_jt[tick]).astype(V1_next.dtype)
        V1_next -= non_disease_deaths
        ndd_next = model.patches.non_disease_deaths[tick]
        ndd_next += non_disease_deaths

        # non_disease_deaths = model.prng.binomial(V2_next, -np.expm1(-model.params.d_jt[tick])).astype(V2_next.dtype)
        non_disease_deaths = model.prng.binomial(V2_next, model.patches.non_disease_death_prob_jt[tick]).astype(V2_next.dtype)
        V2_next -= non_disease_deaths
        ndd_next += non_disease_deaths

        # -waning immunity
        # PERF: pre-computed `-np.expm1(-omega_{1,2})` cached as self._omega_{1,2}_prob.
        # waned = model.prng.binomial(V1_next, -np.expm1(-model.params.omega_1)).astype(V1_next.dtype)
        waned = model.prng.binomial(V1_next, self._omega_1_prob).astype(V1_next.dtype)
        V1_next -= waned
        S_next += waned  # waned return to Susceptible

        # waned = model.prng.binomial(V2_next, -np.expm1(-model.params.omega_2)).astype(V2_next.dtype)
        waned = model.prng.binomial(V2_next, self._omega_2_prob).astype(V2_next.dtype)
        V2_next -= waned
        S_next += waned  # waned return to Susceptible

        # We will do _second_ dose distribution first so we don't vaccine people
        # "twice on the same day", i.e. move from S -> V1 -> V2 in a single tick
        # -second dose recipients
        if any(model.params.nu_2_jt[tick]):
            new_second_doses_delivered = np.round(model.params.nu_2_jt[tick]).astype(V2_next.dtype)
            if np.any(new_second_doses_delivered > V1_next):
                logger.debug(f"WARNING: new_second_doses_delivered > V1 ({tick=}\n\t{new_second_doses_delivered=}\n\t{V1=})")
                new_second_doses_delivered = np.minimum(new_second_doses_delivered, V1_next)
            model.patches.dose_two_doses[tick] = new_second_doses_delivered

            # effective doses
            newly_immunized = np.round(model.params.phi_2 * new_second_doses_delivered).astype(V2_next.dtype)
            # just move the effective doses, leave ineffective doses in V1
            V1_next -= newly_immunized
            V2_next += newly_immunized

        # +newly vaccinated (successful take)
        if any(model.params.nu_1_jt[tick]):
            new_first_doses_delivered = np.round(model.params.nu_1_jt[tick]).astype(V1_next.dtype)

            # Create a "matrix" of columns from model.people S, E, Isym, Iasym, and R with a row for each node
            compartments_next = [getattr(model.people, compartment)[tick + 1] for compartment in self.sources if hasattr(model.people, compartment)]
            pop_matrix = np.column_stack(compartments_next)

            # Sum each row by column to determine the available population for vaccination
            available_pop = pop_matrix.sum(axis=1)

            # Limit actual doses delivered to the available population by node
            if np.any(new_first_doses_delivered > available_pop):
                logger.debug(f"WARNING: new_first_doses_delivered > available_pop ({tick=})")
                for index in np.nonzero(new_first_doses_delivered > available_pop)[0]:
                    logger.debug(
                        f"\t{model.params.location_name[index]}: doses {new_first_doses_delivered[index]} > {available_pop[index]} available"
                    )
                new_first_doses_delivered = np.minimum(new_first_doses_delivered, available_pop)
            model.patches.dose_one_doses[tick] = new_first_doses_delivered

            # make sure available_pop is at least 1 to prevent divide by zero below
            np.maximum(available_pop, 1, out=available_pop)

            # Determine doses delivered to each sub-population by its fractional part of the total node population
            # Attenuate actual doses delivered by model.params.phi_1
            # Decrement each source sub-population by the effectively delivered doses
            # Increment V1_next by the total number of effectively delivered doses for each node
            total_newly_immunized = np.zeros_like(V1_next)
            for col_idx, compartment_next in enumerate(compartments_next):
                fraction = pop_matrix[:, col_idx] / available_pop
                compartment_doses = np.round(new_first_doses_delivered * fraction).astype(V1_next.dtype)
                effective_doses = np.round(model.params.phi_1 * compartment_doses).astype(V1_next.dtype)
                compartment_next -= effective_doses
                total_newly_immunized += effective_doses
            V1_next += total_newly_immunized

        return

    def plot(self, fig: Figure | None = None) -> Iterator[str]:  # pragma: no cover
        """Yield two Matplotlib figures: `V1(t)` and `V2(t)` for the ten largest patches.

        Args:
            fig: Optional existing Matplotlib `Figure` to draw into.

        Yields:
            Two labels in order: `"Vaccinated (One Dose)"`,
            `"Vaccinated (Two Doses)"`.
        """
        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Vaccinated (One Dose)") if fig is None else fig

        for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
            plt.plot(self.model.people.V1[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
        plt.xlabel("Tick")
        plt.ylabel("Vaccinated (One Dose)")
        plt.legend()

        yield "Vaccinated (One Dose)"

        _fig = plt.figure(figsize=(12, 9), dpi=128, num="Vaccinated (Two Doses)") if fig is None else fig

        for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
            plt.plot(self.model.people.V2[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
        plt.xlabel("Tick")
        plt.ylabel("Vaccinated (Two Doses)")
        plt.legend()

        yield "Vaccinated (Two Doses)"
        return

model instance-attribute

model = model

sources instance-attribute

sources = (
    nu_jt_sources
    if "nu_jt_sources" in params
    else ["S", "E", "Isym", "Iasym", "R"]
)

__init__

__init__(model: Model) -> None

Allocate V1 / V2 and the dose-bookkeeping vectors; seed from V*_j_initial.

Parameters:

Name Type Description Default
model Model

The Model instance. Must have people, patches, and params, with params.V1_j_initial and params.V2_j_initial populated.

required

Raises:

Type Description
AttributeError

When model is missing people or patches.

ValueError

When params.V1_j_initial or params.V2_j_initial is missing.

Source code in src/laser/cholera/metapop/vaccinated.py
def __init__(self, model: "Model") -> None:
    """Allocate `V1` / `V2` and the dose-bookkeeping vectors; seed from `V*_j_initial`.

    Args:
        model: The `Model` instance. Must have `people`, `patches`,
            and `params`, with `params.V1_j_initial` and
            `params.V2_j_initial` populated.

    Raises:
        AttributeError: When `model` is missing `people` or
            `patches`.
        ValueError: When `params.V1_j_initial` or
            `params.V2_j_initial` is missing.
    """
    self.model = model

    check_attr(model, "people", "Vaccinated: model needs to have a 'people' attribute.")
    model.people.add_vector_property("V1", length=model.params.nticks + 1, dtype=np.int32, default=0)
    model.people.add_vector_property("V2", length=model.params.nticks + 1, dtype=np.int32, default=0)
    # We will track doses on the date (tick) given to more easily match nu_1_jt and nu_2_jt.
    model.patches.add_vector_property("dose_one_doses", length=model.params.nticks, dtype=np.int32, default=0)
    model.patches.add_vector_property("dose_two_doses", length=model.params.nticks, dtype=np.int32, default=0)
    check_key(
        model.params,
        "V1_j_initial",
        "Vaccinated: model params needs to have a 'V1_j_initial' (initial one dose vaccinated population) parameter.",
    )
    check_key(
        model.params,
        "V2_j_initial",
        "Vaccinated: model params needs to have a 'V2_j_initial' (initial two dose vaccinated population) parameter.",
    )
    model.people.V1[0] = model.params.V1_j_initial
    model.people.V2[0] = model.params.V2_j_initial

    self.sources = model.params.nu_jt_sources if "nu_jt_sources" in model.params else ["S", "E", "Isym", "Iasym", "R"]

    return

check

check()

Validate dose-related parameters and the source compartments.

Asserts that model.people.S and model.people.E exist and that params provides phi_1, phi_2, omega_1, omega_2, nu_1_jt, nu_2_jt, and d_jt.

Raises:

Type Description
AttributeError

When model.people.S or .E is missing.

ValueError

When any of params.phi_1, phi_2, omega_1, omega_2, nu_1_jt, nu_2_jt, d_jt is missing.

Source code in src/laser/cholera/metapop/vaccinated.py
def check(self):
    """Validate dose-related parameters and the source compartments.

    Asserts that `model.people.S` and `model.people.E` exist and
    that `params` provides `phi_1`, `phi_2`, `omega_1`, `omega_2`,
    `nu_1_jt`, `nu_2_jt`, and `d_jt`.

    Raises:
        AttributeError: When `model.people.S` or `.E` is missing.
        ValueError: When any of `params.phi_1`, `phi_2`, `omega_1`,
            `omega_2`, `nu_1_jt`, `nu_2_jt`, `d_jt` is missing.
    """
    check_attr(self.model.people, "S", "Vaccinated: model people needs to have a 'S' (susceptible) attribute.")
    check_attr(self.model.people, "E", "Vaccinated: model people needs to have a 'E' (exposed) attribute.")

    check_key(self.model.params, "phi_1", "Vaccinated: model params needs to have a 'phi_1' parameter.")
    check_key(self.model.params, "phi_2", "Vaccinated: model params needs to have a 'phi_2' parameter.")
    check_key(self.model.params, "omega_1", "Vaccinated: model params needs to have a 'omega_1' parameter.")
    check_key(self.model.params, "omega_2", "Vaccinated: model params needs to have a 'omega_2' parameter.")
    check_key(self.model.params, "nu_1_jt", "Vaccinated: model params needs to have a 'nu_1_jt' parameter.")
    check_key(self.model.params, "nu_2_jt", "Vaccinated: model params needs to have a 'nu_2_jt' parameter.")

    check_key(self.model.params, "d_jt", "Vaccinated: model.params needs to have a 'd_jt' attribute.")

    if not hasattr(self.model.patches, "non_disease_deaths"):
        self.model.patches.add_vector_property("non_disease_deaths", length=self.model.params.nticks + 1, dtype=np.int32, default=0)
    # PERF: install `model.patches.non_disease_death_prob_jt` (the
    # `1 - exp(-d_jt)` cache) idempotently if no earlier component has.
    # Lets each consumer be exercised in isolation; the cache is built
    # exactly once across the pipeline.
    if not hasattr(self.model.patches, "non_disease_death_prob_jt"):
        self.model.patches.add_vector_property("non_disease_death_prob_jt", length=self.model.params.d_jt.shape[0], dtype=np.float32, default=0.0)
        self.model.patches.non_disease_death_prob_jt[:] = -np.expm1(-self.model.params.d_jt)

    # PERF: cache `1 - exp(-omega_{1,2})` so the per-tick waning
    # probabilities are not recomputed every call.
    self._omega_1_prob = -np.expm1(-self.model.params.omega_1)
    self._omega_2_prob = -np.expm1(-self.model.params.omega_2)

    return

__call__

__call__(model: Model, tick: int) -> None

Advance V1 / V2 one tick: deaths, waning, then dose deliveries.

Doses scheduled for this tick are clamped against the available donor population (warning logged at DEBUG if the schedule exceeds capacity). Only the phi_*-effective fraction transits to the vaccinated compartment; ineffective doses leave the recipient in their original compartment.

Parameters:

Name Type Description Default
model Model

The parent Model instance.

required
tick int

Current simulation tick.

required
Source code in src/laser/cholera/metapop/vaccinated.py
def __call__(self, model: "Model", tick: int) -> None:
    """Advance `V1` / `V2` one tick: deaths, waning, then dose deliveries.

    Doses scheduled for this tick are clamped against the available
    donor population (warning logged at `DEBUG` if the schedule
    exceeds capacity). Only the `phi_*`-effective fraction transits
    to the vaccinated compartment; ineffective doses leave the
    recipient in their original compartment.

    Args:
        model: The parent `Model` instance.
        tick: Current simulation tick.
    """
    V1 = model.people.V1[tick]
    V1_next = model.people.V1[tick + 1]
    V2 = model.people.V2[tick]
    V2_next = model.people.V2[tick + 1]
    S_next = model.people.S[tick + 1]

    # propagate the current values forward (V(t+1) = V(t) + ∆V)
    V1_next[:] = V1
    V2_next[:] = V2

    # -natural mortality
    # PERF: pre-computed `-np.expm1(-d_jt)` cached as model.patches.non_disease_death_prob_jt.
    # non_disease_deaths = model.prng.binomial(V1_next, -np.expm1(-model.params.d_jt[tick])).astype(V1_next.dtype)
    non_disease_deaths = model.prng.binomial(V1_next, model.patches.non_disease_death_prob_jt[tick]).astype(V1_next.dtype)
    V1_next -= non_disease_deaths
    ndd_next = model.patches.non_disease_deaths[tick]
    ndd_next += non_disease_deaths

    # non_disease_deaths = model.prng.binomial(V2_next, -np.expm1(-model.params.d_jt[tick])).astype(V2_next.dtype)
    non_disease_deaths = model.prng.binomial(V2_next, model.patches.non_disease_death_prob_jt[tick]).astype(V2_next.dtype)
    V2_next -= non_disease_deaths
    ndd_next += non_disease_deaths

    # -waning immunity
    # PERF: pre-computed `-np.expm1(-omega_{1,2})` cached as self._omega_{1,2}_prob.
    # waned = model.prng.binomial(V1_next, -np.expm1(-model.params.omega_1)).astype(V1_next.dtype)
    waned = model.prng.binomial(V1_next, self._omega_1_prob).astype(V1_next.dtype)
    V1_next -= waned
    S_next += waned  # waned return to Susceptible

    # waned = model.prng.binomial(V2_next, -np.expm1(-model.params.omega_2)).astype(V2_next.dtype)
    waned = model.prng.binomial(V2_next, self._omega_2_prob).astype(V2_next.dtype)
    V2_next -= waned
    S_next += waned  # waned return to Susceptible

    # We will do _second_ dose distribution first so we don't vaccine people
    # "twice on the same day", i.e. move from S -> V1 -> V2 in a single tick
    # -second dose recipients
    if any(model.params.nu_2_jt[tick]):
        new_second_doses_delivered = np.round(model.params.nu_2_jt[tick]).astype(V2_next.dtype)
        if np.any(new_second_doses_delivered > V1_next):
            logger.debug(f"WARNING: new_second_doses_delivered > V1 ({tick=}\n\t{new_second_doses_delivered=}\n\t{V1=})")
            new_second_doses_delivered = np.minimum(new_second_doses_delivered, V1_next)
        model.patches.dose_two_doses[tick] = new_second_doses_delivered

        # effective doses
        newly_immunized = np.round(model.params.phi_2 * new_second_doses_delivered).astype(V2_next.dtype)
        # just move the effective doses, leave ineffective doses in V1
        V1_next -= newly_immunized
        V2_next += newly_immunized

    # +newly vaccinated (successful take)
    if any(model.params.nu_1_jt[tick]):
        new_first_doses_delivered = np.round(model.params.nu_1_jt[tick]).astype(V1_next.dtype)

        # Create a "matrix" of columns from model.people S, E, Isym, Iasym, and R with a row for each node
        compartments_next = [getattr(model.people, compartment)[tick + 1] for compartment in self.sources if hasattr(model.people, compartment)]
        pop_matrix = np.column_stack(compartments_next)

        # Sum each row by column to determine the available population for vaccination
        available_pop = pop_matrix.sum(axis=1)

        # Limit actual doses delivered to the available population by node
        if np.any(new_first_doses_delivered > available_pop):
            logger.debug(f"WARNING: new_first_doses_delivered > available_pop ({tick=})")
            for index in np.nonzero(new_first_doses_delivered > available_pop)[0]:
                logger.debug(
                    f"\t{model.params.location_name[index]}: doses {new_first_doses_delivered[index]} > {available_pop[index]} available"
                )
            new_first_doses_delivered = np.minimum(new_first_doses_delivered, available_pop)
        model.patches.dose_one_doses[tick] = new_first_doses_delivered

        # make sure available_pop is at least 1 to prevent divide by zero below
        np.maximum(available_pop, 1, out=available_pop)

        # Determine doses delivered to each sub-population by its fractional part of the total node population
        # Attenuate actual doses delivered by model.params.phi_1
        # Decrement each source sub-population by the effectively delivered doses
        # Increment V1_next by the total number of effectively delivered doses for each node
        total_newly_immunized = np.zeros_like(V1_next)
        for col_idx, compartment_next in enumerate(compartments_next):
            fraction = pop_matrix[:, col_idx] / available_pop
            compartment_doses = np.round(new_first_doses_delivered * fraction).astype(V1_next.dtype)
            effective_doses = np.round(model.params.phi_1 * compartment_doses).astype(V1_next.dtype)
            compartment_next -= effective_doses
            total_newly_immunized += effective_doses
        V1_next += total_newly_immunized

    return

plot

plot(fig: Figure | None = None) -> Iterator[str]

Yield two Matplotlib figures: V1(t) and V2(t) for the ten largest patches.

Parameters:

Name Type Description Default
fig Figure | None

Optional existing Matplotlib Figure to draw into.

None

Yields:

Type Description
str

Two labels in order: "Vaccinated (One Dose)",

str

"Vaccinated (Two Doses)".

Source code in src/laser/cholera/metapop/vaccinated.py
def plot(self, fig: Figure | None = None) -> Iterator[str]:  # pragma: no cover
    """Yield two Matplotlib figures: `V1(t)` and `V2(t)` for the ten largest patches.

    Args:
        fig: Optional existing Matplotlib `Figure` to draw into.

    Yields:
        Two labels in order: `"Vaccinated (One Dose)"`,
        `"Vaccinated (Two Doses)"`.
    """
    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Vaccinated (One Dose)") if fig is None else fig

    for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
        plt.plot(self.model.people.V1[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
    plt.xlabel("Tick")
    plt.ylabel("Vaccinated (One Dose)")
    plt.legend()

    yield "Vaccinated (One Dose)"

    _fig = plt.figure(figsize=(12, 9), dpi=128, num="Vaccinated (Two Doses)") if fig is None else fig

    for ipatch in np.argsort(self.model.params.S_j_initial)[-10:]:
        plt.plot(self.model.people.V2[:, ipatch], label=f"{self.model.params.location_name[ipatch]}")
    plt.xlabel("Tick")
    plt.ylabel("Vaccinated (Two Doses)")
    plt.legend()

    yield "Vaccinated (Two Doses)"
    return

get_parameters

get_parameters(
    paramsource: str | Path | dict | None = None,
    do_validation: bool = True,
    mods: dict | None = None,
) -> PropertySetEx

Load parameters from disk or memory and return a typed PropertySetEx.

The canonical entry point for assembling a simulation parameter set. Accepts a parameter source in any of four forms:

  • None → loads src/laser/cholera/metapop/data/default_parameters.json (the bundled defaults).
  • str or pathlib.Path → loaded from that filesystem path. Supported suffixes are .json and .json.gz; HDF5 sources are no longer supported.
  • dict → ingested in-memory via dict_to_propertysetex.

Any of those is then optionally merged with caller-supplied mods: overrides of existing keys are applied first (logged at INFO level), additions of new keys follow. After merge, validate_parameters is called unless do_validation=False. Finally, default values for the visualization/output flags (visualize, pdf, quiet) are filled in if absent so downstream code can read them unconditionally.

Parameters:

Name Type Description Default
paramsource str | Path | dict | None

None for the bundled defaults, a filesystem path (str or Path) to a JSON/JSON.gz file, or an already- built parameter dict.

None
do_validation bool

When True (default), run validate_parameters on the assembled result. Set to False for tests that deliberately construct partial or invariant-violating configurations.

True
mods dict | None

Optional dict of overrides/additions to merge after loading the base parameters. Typed via override_helper on the CLI path; passed verbatim from Python callers.

None

Returns:

Type Description
PropertySetEx

A populated PropertySetEx

PropertySetEx

with all known fields coerced to their working dtypes and

PropertySetEx

(when do_validation=True) verified against the model's

PropertySetEx

invariants.

Raises:

Type Description
KeyError

If paramsource is a path whose suffix is not in the dispatch table (e.g., a .h5 file after the HDF5 ingest path was removed).

ValueError

If paramsource is not None, str, Path, or dict — including the historically-supported HDF5 paths.

ValueError

From validate_parameters if the resulting parameter set violates the model's invariants and do_validation=True.

Example

Load the bundled defaults with a one-month simulation window:

from laser.cholera.metapop.params import get_parameters from laser.cholera.utils import sim_duration from datetime import datetime params = get_parameters(mods=sim_duration(datetime(2024, 1, 1), datetime(2024, 1, 31))) params.nticks 31

Source code in src/laser/cholera/metapop/params.py
def get_parameters(
    paramsource: str | Path | dict | None = None,
    do_validation: bool = True,
    mods: dict | None = None,
) -> PropertySetEx:
    """Load parameters from disk or memory and return a typed ``PropertySetEx``.

    The canonical entry point for assembling a simulation parameter set.
    Accepts a parameter source in any of four forms:

    - ``None`` → loads ``src/laser/cholera/metapop/data/default_parameters.json``
      (the bundled defaults).
    - ``str`` or ``pathlib.Path`` → loaded from that filesystem path.
      Supported suffixes are ``.json`` and ``.json.gz``; HDF5 sources are
      no longer supported.
    - ``dict`` → ingested in-memory via
      [`dict_to_propertysetex`][laser.cholera.metapop.params.dict_to_propertysetex].

    Any of those is then optionally merged with caller-supplied ``mods``:
    overrides of existing keys are applied first (logged at INFO level),
    additions of new keys follow. After merge, ``validate_parameters`` is
    called unless ``do_validation=False``. Finally, default values for
    the visualization/output flags (``visualize``, ``pdf``, ``quiet``)
    are filled in if absent so downstream code can read them
    unconditionally.

    Args:
        paramsource: ``None`` for the bundled defaults, a filesystem
            path (str or Path) to a JSON/JSON.gz file, or an already-
            built parameter dict.
        do_validation: When True (default), run
            [`validate_parameters`][laser.cholera.metapop.params.validate_parameters]
            on the assembled result. Set to ``False`` for tests that
            deliberately construct partial or invariant-violating
            configurations.
        mods: Optional dict of overrides/additions to merge after loading
            the base parameters. Typed via
            [`override_helper`][laser.cholera.metapop.utils.override_helper]
            on the CLI path; passed verbatim from Python callers.

    Returns:
        A populated [`PropertySetEx`][laser.cholera.metapop.params.PropertySetEx]
        with all known fields coerced to their working dtypes and
        (when ``do_validation=True``) verified against the model's
        invariants.

    Raises:
        KeyError: If ``paramsource`` is a path whose suffix is not in the
            dispatch table (e.g., a ``.h5`` file after the HDF5 ingest
            path was removed).
        ValueError: If ``paramsource`` is not None, str, Path, or dict —
            including the historically-supported HDF5 paths.
        ValueError: From ``validate_parameters`` if the resulting
            parameter set violates the model's invariants and
            ``do_validation=True``.

    Example:
        Load the bundled defaults with a one-month simulation window:

        >>> from laser.cholera.metapop.params import get_parameters
        >>> from laser.cholera.utils import sim_duration
        >>> from datetime import datetime
        >>> params = get_parameters(mods=sim_duration(datetime(2024, 1, 1), datetime(2024, 1, 31)))
        >>> params.nticks
        31
    """
    fn_map = {
        (".json",): load_json_parameters,
        (".json", ".gz"): load_compressed_json_parameters,
    }

    if isinstance(paramsource, (str, Path, type(None))):
        file_path = Path(paramsource) if paramsource is not None else Path(__file__).parent / "data" / "default_parameters.json"
        suffixes = [suffix.lower() for suffix in file_path.suffixes]
        load_fn = fn_map[tuple(suffixes)]

        logger.info(f"Loading parameters from `{file_path}`…")
        params = load_fn(file_path)

    elif isinstance(paramsource, dict):
        params = dict_to_propertysetex(paramsource)

    else:
        raise ValueError(f"Invalid parameter source type: {type(paramsource)}")

    if mods is not None:
        overrides = {k: v for k, v in mods.items() if k in params}
        additions = {k: v for k, v in mods.items() if k not in params}

        if overrides:
            # Update the parameters with the overrides
            params <<= overrides

            logger.info("Updated/overrode file parameters with overrides:")
            for k, v in overrides.items():
                logger.info(f"  '{k}': {v}")

        if additions:
            # Add the additional parameters
            params += additions

            logger.info("Parameters added to file parameters:")
            for k, v in additions.items():
                logger.info(f"  '{k}': {v}")

    if do_validation:
        validate_parameters(params)

    if "visualize" not in params:
        params.visualize = False
    if "pdf" not in params:
        params.pdf = False
    if "quiet" not in params:
        params.quiet = True

    return params