Skip to content

recovered

laser.cholera.metapop.recovered

Recovered compartment — natural-immunity population that wanes back to susceptible.

Allocates model.people.R (shape (nticks + 1, npatches)), seeds it from params.R_j_initial, and on each tick applies non-disease mortality (d_jt) and waning immunity (epsilon). Waned individuals are funneled directly into S[tick + 1]. Recovery inflows into R are managed by Infectious via the gamma_1 / gamma_2 rates.

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