Skip to content

Persistency metrics

The operational outputs of a fitted intensity λ(t): the expected wait until the next event, the probability of an event in a horizon and the expected count, with posterior_metric turning any of them into posterior samples and quantiles. Needs the population extra for kernels without a closed-form compensator. Tier V.

persistency

Persistency metrics (implementation in plumax.population._src.persistency).

conditional_occurrence_probability

conditional_occurrence_probability(process: Module, event_times: Float[ArrayLike, ' event'], mask: Bool[ArrayLike, ' event'], t: ArrayLike, horizon: ArrayLike) -> Float[Array, '']

Probability of an event in the horizon given the event history.

P(N(t, t + h] ≥ 1 | H_t) = 1 − exp(−∫ₜ^(t+h) λ(s | H_t) ds), with λ(s | H_t) the intensity at s > t if no event happens in (t, s]. Until the next event λ is a deterministic function of s, so the first event after t has hazard λ and the integral is closed-form:

  • exponential Hawkes, λ*(s | H_t) = μ + Σ_{tᵢ ≤ t} α e^(−β(s − tᵢ)), gives μh + Σ_{tᵢ ≤ t} (α/β)(e^(−β(t − tᵢ)) − e^(−β(t + h − tᵢ)));
  • a renewal process with gap survival S and last event t_last gives 1 − S(t + h − t_last) / S(t − t_last).

event_times must be the complete history H_t, every event up to t, not thinned detections: an undetected event still excites a Hawkes intensity or resets a renewal age, so detection times give the wrong λ*. Events after t in the buffer are ignored. A renewal process with no event before t takes its age from the time origin 0, where pyrox-xtreme starts the first gap.

Parameters:

Name Type Description Default
process Module

A pyrox-xtreme ExponentialHawkes or RenewalProcess, or a :class:~plumax.population.intensity.WeibullRenewalIntensity (a renewal process with Weibull gaps).

required
event_times Float[ArrayLike, ' event']

Event times tᵢ, padded, on the process's time axis [days].

required
mask Bool[ArrayLike, ' event']

True for the real events of the buffer.

required
t ArrayLike

Time t of the outlook [days].

required
horizon ArrayLike

Horizon h ≥ 0 [days].

required

Returns:

Type Description
Float[Array, '']

The probability.

Raises:

Type Description
TypeError

For any other process.

ImportError

Without the population extra.

Examples:

A Hawkes process with α = 0 is a Poisson process of rate μ:

>>> import jax.numpy as jnp
>>> from pyrox_xtreme.point_processes.operators import ExponentialHawkes
>>> process = ExponentialHawkes(mu=0.5, alpha=0.0, beta=1.0, observation_window=10.0)
>>> times, mask = jnp.array([1.0, 3.0]), jnp.array([True, True])
>>> probability = conditional_occurrence_probability(process, times, mask, 4.0, 2.0)
>>> bool(jnp.allclose(probability, 1.0 - jnp.exp(-1.0)))
True

A recharging Weibull source (k > 1) is likelier to vent the longer it waits:

>>> from plumax.population.intensity import WeibullRenewalIntensity
>>> source = WeibullRenewalIntensity(scale=1.0, shape=3.0)
>>> soon = conditional_occurrence_probability(source, times, mask, 3.1, 0.1)
>>> late = conditional_occurrence_probability(source, times, mask, 4.0, 0.1)
>>> bool(soon < late)
True
Source code in src/plumax/population/_src/persistency.py
def conditional_occurrence_probability(
    process: eqx.Module,
    event_times: Float[ArrayLike, " event"],
    mask: Bool[ArrayLike, " event"],
    t: ArrayLike,
    horizon: ArrayLike,
) -> Float[Array, ""]:
    """Probability of an event in the horizon given the event history.

    P(N(t, t + h] ≥ 1 | H_t) = 1 − exp(−∫ₜ^(t+h) λ*(s | H_t) ds), with λ*(s | H_t)
    the intensity at s > t if no event happens in (t, s]. Until the next event λ* is
    a deterministic function of s, so the first event after t has hazard λ* and the
    integral is closed-form:

    * exponential Hawkes, λ*(s | H_t) = μ + Σ_{tᵢ ≤ t} α e^(−β(s − tᵢ)), gives
      μh + Σ_{tᵢ ≤ t} (α/β)(e^(−β(t − tᵢ)) − e^(−β(t + h − tᵢ)));
    * a renewal process with gap survival S and last event t_last gives
      1 − S(t + h − t_last) / S(t − t_last).

    ``event_times`` must be the complete history H_t, every event up to t, not
    thinned detections: an undetected event still excites a Hawkes intensity or
    resets a renewal age, so detection times give the wrong λ*. Events after t in
    the buffer are ignored. A renewal process with no event before t takes its age
    from the time origin 0, where pyrox-xtreme starts the first gap.

    Args:
        process: A pyrox-xtreme ``ExponentialHawkes`` or ``RenewalProcess``, or a
            :class:`~plumax.population.intensity.WeibullRenewalIntensity` (a
            renewal process with Weibull gaps).
        event_times: Event times tᵢ, padded, on the process's time axis [days].
        mask: True for the real events of the buffer.
        t: Time t of the outlook [days].
        horizon: Horizon h ≥ 0 [days].

    Returns:
        The probability.

    Raises:
        TypeError: For any other process.
        ImportError: Without the ``population`` extra.

    Examples:
        A Hawkes process with α = 0 is a Poisson process of rate μ:

        >>> import jax.numpy as jnp
        >>> from pyrox_xtreme.point_processes.operators import ExponentialHawkes
        >>> process = ExponentialHawkes(mu=0.5, alpha=0.0, beta=1.0, observation_window=10.0)
        >>> times, mask = jnp.array([1.0, 3.0]), jnp.array([True, True])
        >>> probability = conditional_occurrence_probability(process, times, mask, 4.0, 2.0)
        >>> bool(jnp.allclose(probability, 1.0 - jnp.exp(-1.0)))
        True

        A recharging Weibull source (k > 1) is likelier to vent the longer it waits:

        >>> from plumax.population.intensity import WeibullRenewalIntensity
        >>> source = WeibullRenewalIntensity(scale=1.0, shape=3.0)
        >>> soon = conditional_occurrence_probability(source, times, mask, 3.1, 0.1)
        >>> late = conditional_occurrence_probability(source, times, mask, 4.0, 0.1)
        >>> bool(soon < late)
        True
    """
    intensity = _no_event_intensity(
        process, event_times, mask, t, caller="conditional_occurrence_probability"
    )
    start = jnp.asarray(t, dtype=float)
    # ∫ₜ^(t+h) λ*(s | H_t) ds
    count = intensity.integrate(start, start + horizon)
    # 1 − exp(−Λ*), accurate for small Λ*
    return -jnp.expm1(-count)

conditional_wait_time

conditional_wait_time(process: Module, event_times: Float[ArrayLike, ' event'], mask: Bool[ArrayLike, ' event'], t: ArrayLike, *, n_cells: int = 2048) -> Float[Array, '']

Expected wait until the next event given the event history.

E[Δt | H_t] = ∫₀^∞ exp(−∫ₜ^(t+u) λ(s | H_t) ds) du, with λ(s | H_t) the intensity at s > t if no event happens in (t, s] (see :func:conditional_occurrence_probability for its closed-form integral). For Weibull gaps it is closed-form too, E[G − a | G > a] = η Γ(1 + 1/k) Q(1/k, x) eˣ with age a = t − t_last and x = (a/η)^k; otherwise the outer integral runs on the log-spaced survival grid of :func:expected_wait_time, with each cell's compensator exact.

event_times must be the complete history H_t, every event up to t, not thinned detections: an undetected event still excites a Hawkes intensity or resets a renewal age, so detection times give the wrong λ*.

Parameters:

Name Type Description Default
process Module

A pyrox-xtreme ExponentialHawkes or RenewalProcess, or a :class:~plumax.population.intensity.WeibullRenewalIntensity.

required
event_times Float[ArrayLike, ' event']

Event times tᵢ, padded, on the process's time axis [days].

required
mask Bool[ArrayLike, ' event']

True for the real events of the buffer.

required
t ArrayLike

Time t of the outlook [days].

required
n_cells int

Log-spaced cells of the survival grid (unused for Weibull gaps).

2048

Returns:

Type Description
Float[Array, '']

The expected wait [days].

Raises:

Type Description
TypeError

For any other process.

ImportError

Without the population extra.

Notes

Weibull and exponential gap laws use their exact cumulative hazard, and Weibull gaps their exact residual mean. Any other gap law of a RenewalProcess goes through pyrox-xtreme's −log(1 − F), which saturates where S falls below 1e-30; if that happens within the grid's MAX_WAIT the tail estimate divides by a zero rate and the wait comes out infinite.

Examples:

Right after an event a Hawkes source is excited, so the wait is shorter than its baseline 1/μ:

>>> import jax.numpy as jnp
>>> from pyrox_xtreme.point_processes.operators import ExponentialHawkes
>>> process = ExponentialHawkes(mu=0.5, alpha=1.0, beta=2.0, observation_window=10.0)
>>> times, mask = jnp.array([3.0]), jnp.array([True])
>>> wait = conditional_wait_time(process, times, mask, 3.0)
>>> bool(wait < 2.0)
True
Source code in src/plumax/population/_src/persistency.py
def conditional_wait_time(
    process: eqx.Module,
    event_times: Float[ArrayLike, " event"],
    mask: Bool[ArrayLike, " event"],
    t: ArrayLike,
    *,
    n_cells: int = 2048,
) -> Float[Array, ""]:
    """Expected wait until the next event given the event history.

    E[Δt | H_t] = ∫₀^∞ exp(−∫ₜ^(t+u) λ*(s | H_t) ds) du, with λ*(s | H_t) the
    intensity at s > t if no event happens in (t, s] (see
    :func:`conditional_occurrence_probability` for its closed-form integral). For
    Weibull gaps it is closed-form too, E[G − a | G > a] = η Γ(1 + 1/k) Q(1/k, x) eˣ
    with age a = t − t_last and x = (a/η)^k; otherwise the outer integral runs on
    the log-spaced survival grid of :func:`expected_wait_time`, with each cell's
    compensator exact.

    ``event_times`` must be the complete history H_t, every event up to t, not
    thinned detections: an undetected event still excites a Hawkes intensity or
    resets a renewal age, so detection times give the wrong λ*.

    Args:
        process: A pyrox-xtreme ``ExponentialHawkes`` or ``RenewalProcess``, or a
            :class:`~plumax.population.intensity.WeibullRenewalIntensity`.
        event_times: Event times tᵢ, padded, on the process's time axis [days].
        mask: True for the real events of the buffer.
        t: Time t of the outlook [days].
        n_cells: Log-spaced cells of the survival grid (unused for Weibull gaps).

    Returns:
        The expected wait [days].

    Raises:
        TypeError: For any other process.
        ImportError: Without the ``population`` extra.

    Notes:
        Weibull and exponential gap laws use their exact cumulative hazard, and
        Weibull gaps their exact residual mean. Any other
        gap law of a ``RenewalProcess`` goes through pyrox-xtreme's −log(1 − F), which
        saturates where S falls below 1e-30; if that happens within the grid's
        ``MAX_WAIT`` the tail estimate divides by a zero rate and the wait comes out
        infinite.

    Examples:
        Right after an event a Hawkes source is excited, so the wait is shorter
        than its baseline 1/μ:

        >>> import jax.numpy as jnp
        >>> from pyrox_xtreme.point_processes.operators import ExponentialHawkes
        >>> process = ExponentialHawkes(mu=0.5, alpha=1.0, beta=2.0, observation_window=10.0)
        >>> times, mask = jnp.array([3.0]), jnp.array([True])
        >>> wait = conditional_wait_time(process, times, mask, 3.0)
        >>> bool(wait < 2.0)
        True
    """
    intensity = _no_event_intensity(
        process, event_times, mask, t, caller="conditional_wait_time"
    )
    start = jnp.asarray(t, dtype=float)
    if isinstance(intensity, _RenewalNoEventIntensity) and _is_weibull(
        intensity.inter_event
    ):
        return _weibull_residual_mean(
            intensity.inter_event, start - intensity.last_event
        )
    # each cell's compensator is closed-form, so one node per cell end is enough
    return _survival_wait(intensity, start, n_cells=n_cells, nodes_per_cell=3)

expected_count

expected_count(intensity: str | Module, t: ArrayLike, horizon: float, *, nodes_per_day: int = NODES_PER_DAY, **theta: Any) -> Float[Array, '']

Expected number of events in the horizon, E[N(t, t + h)] = Λ(t, t + h).

Parameters:

Name Type Description Default
intensity str | Module

A registry name or a kernel instance.

required
t ArrayLike

Start time t [days].

required
horizon float

Horizon h > 0 [days], a concrete number since it sets the node count.

required
nodes_per_day int

Quadrature density for kernels without a closed form.

NODES_PER_DAY
**theta Any

Kernel parameters, when intensity is a name.

{}

Returns:

Type Description
Float[Array, '']

The expected count.

Raises:

Type Description
ValueError

For a renewal or Hawkes process (see the conditional_ functions), or parameters with an instance.

Examples:

>>> import jax.numpy as jnp
>>> count = expected_count("constant", 3.0, 2.0, lambda_0=1.5)
>>> bool(jnp.allclose(count, 3.0))
True

A diurnal cycle integrates to its mean over a whole day:

>>> count = expected_count(
...     "diurnal", 0.0, 1.0, lambda_0=2.0, amplitude=0.5, phase_hours=14.0
... )
>>> bool(jnp.allclose(count, 2.0))
True
Source code in src/plumax/population/_src/persistency.py
def expected_count(
    intensity: str | eqx.Module,
    t: ArrayLike,
    horizon: float,
    *,
    nodes_per_day: int = NODES_PER_DAY,
    **theta: Any,
) -> Float[Array, ""]:
    """Expected number of events in the horizon, E[N(t, t + h)] = Λ(t, t + h).

    Args:
        intensity: A registry name or a kernel instance.
        t: Start time t [days].
        horizon: Horizon h > 0 [days], a concrete number since it sets the node count.
        nodes_per_day: Quadrature density for kernels without a closed form.
        **theta: Kernel parameters, when ``intensity`` is a name.

    Returns:
        The expected count.

    Raises:
        ValueError: For a renewal or Hawkes process (see the ``conditional_``
            functions), or parameters with an instance.

    Examples:
        >>> import jax.numpy as jnp
        >>> count = expected_count("constant", 3.0, 2.0, lambda_0=1.5)
        >>> bool(jnp.allclose(count, 3.0))
        True

        A diurnal cycle integrates to its mean over a whole day:

        >>> count = expected_count(
        ...     "diurnal", 0.0, 1.0, lambda_0=2.0, amplitude=0.5, phase_hours=14.0
        ... )
        >>> bool(jnp.allclose(count, 2.0))
        True
    """
    kernel = _metric_kernel(intensity, theta, caller="expected_count")
    num_points = _quadrature_points(float(horizon), nodes_per_day)
    start = jnp.asarray(t, dtype=float)
    return expected_events(kernel, start, start + horizon, num_points=num_points)

expected_wait_time

expected_wait_time(intensity: str | Module, t: ArrayLike, *, n_cells: int = 2048, nodes_per_cell: int = 9, **theta: Any) -> Float[Array, '']

Expected wait until the next event, E[Δt | t] = ∫₀^∞ exp(−Λ(t, t + s)) ds.

Exactly 1/λ₀ for :class:~plumax.population.intensity.ConstantIntensity, whatever t is.

Algorithm
  1. Lay out a survival grid: s = 0, then n_cells log-spaced cells up to MAX_WAIT, so the first cells resolve short waits and the last ones long waits at a fixed cost.
  2. Accumulate Λ(t, t + s) cell by cell with Simpson's rule.
  3. Trapezoid the survival function S(s) = exp(−Λ(t, t + s)) over the grid.
  4. Close the tail beyond s_max with the mean rate λ̄ of the last decade, ∫ S ds ≈ S(s_max) / λ̄, which is exact for a constant rate.

Late cells outgrow a diurnal cycle, which is safe because S only has weight out there when λ is small enough that the ripple in Λ is small too.

Parameters:

Name Type Description Default
intensity str | Module

A registry name or a kernel instance.

required
t ArrayLike

Start time t [days].

required
n_cells int

Log-spaced cells of the survival grid.

2048
nodes_per_cell int

Simpson nodes of Λ inside one cell (odd).

9
**theta Any

Kernel parameters, when intensity is a name.

{}

Returns:

Type Description
Float[Array, '']

The expected wait [days]; infinite for λ ≡ 0.

Raises:

Type Description
ValueError

For a renewal or Hawkes process (see the conditional_ functions), or parameters with an instance.

Examples:

The memoryless wait of a constant rate:

>>> import jax.numpy as jnp
>>> wait = expected_wait_time("constant", 7.0, lambda_0=4.0)
>>> bool(jnp.allclose(wait, 0.25))
True

A diurnal source is quicker to emit near its 14:00 peak than at 02:00:

>>> diurnal = dict(lambda_0=4.0, amplitude=3.6, phase_hours=14.0)
>>> at_peak = expected_wait_time("diurnal", 14.0 / 24.0, **diurnal)
>>> at_trough = expected_wait_time("diurnal", 2.0 / 24.0, **diurnal)
>>> bool(at_peak < at_trough)
True
Source code in src/plumax/population/_src/persistency.py
def expected_wait_time(
    intensity: str | eqx.Module,
    t: ArrayLike,
    *,
    n_cells: int = 2048,
    nodes_per_cell: int = 9,
    **theta: Any,
) -> Float[Array, ""]:
    """Expected wait until the next event, E[Δt | t] = ∫₀^∞ exp(−Λ(t, t + s)) ds.

    Exactly 1/λ₀ for :class:`~plumax.population.intensity.ConstantIntensity`, whatever
    t is.

    Algorithm:
        1. Lay out a survival grid: s = 0, then ``n_cells`` log-spaced cells up to
           ``MAX_WAIT``, so the first cells resolve short waits and the last ones long
           waits at a fixed cost.
        2. Accumulate Λ(t, t + s) cell by cell with Simpson's rule.
        3. Trapezoid the survival function S(s) = exp(−Λ(t, t + s)) over the grid.
        4. Close the tail beyond s_max with the mean rate λ̄ of the last decade,
           ∫ S ds ≈ S(s_max) / λ̄, which is exact for a constant rate.

    Late cells outgrow a diurnal cycle, which is safe because S only has weight out
    there when λ is small enough that the ripple in Λ is small too.

    Args:
        intensity: A registry name or a kernel instance.
        t: Start time t [days].
        n_cells: Log-spaced cells of the survival grid.
        nodes_per_cell: Simpson nodes of Λ inside one cell (odd).
        **theta: Kernel parameters, when ``intensity`` is a name.

    Returns:
        The expected wait [days]; infinite for λ ≡ 0.

    Raises:
        ValueError: For a renewal or Hawkes process (see the ``conditional_``
            functions), or parameters with an instance.

    Examples:
        The memoryless wait of a constant rate:

        >>> import jax.numpy as jnp
        >>> wait = expected_wait_time("constant", 7.0, lambda_0=4.0)
        >>> bool(jnp.allclose(wait, 0.25))
        True

        A diurnal source is quicker to emit near its 14:00 peak than at 02:00:

        >>> diurnal = dict(lambda_0=4.0, amplitude=3.6, phase_hours=14.0)
        >>> at_peak = expected_wait_time("diurnal", 14.0 / 24.0, **diurnal)
        >>> at_trough = expected_wait_time("diurnal", 2.0 / 24.0, **diurnal)
        >>> bool(at_peak < at_trough)
        True
    """
    kernel = _metric_kernel(intensity, theta, caller="expected_wait_time")
    start = jnp.asarray(t, dtype=float)
    if isinstance(kernel, ConstantIntensity):
        # E[Δt] = 1 / λ₀
        return 1.0 / jnp.asarray(kernel.lambda_0, dtype=start.dtype)
    return _survival_wait(kernel, start, n_cells=n_cells, nodes_per_cell=nodes_per_cell)

occurrence_probability

occurrence_probability(intensity: str | Module, t: ArrayLike, horizon: float, *, nodes_per_day: int = NODES_PER_DAY, **theta: Any) -> Float[Array, '']

Probability of at least one event, P(N(t, t + h) ≥ 1) = 1 − exp(−Λ(t, t + h)).

Parameters:

Name Type Description Default
intensity str | Module

A registry name or a kernel instance.

required
t ArrayLike

Start time t [days].

required
horizon float

Horizon h > 0 [days], a concrete number since it sets the node count.

required
nodes_per_day int

Quadrature density for kernels without a closed form.

NODES_PER_DAY
**theta Any

Kernel parameters, when intensity is a name.

{}

Returns:

Type Description
Float[Array, '']

The probability.

Raises:

Type Description
ValueError

For a renewal or Hawkes process (see the conditional_ functions), or parameters with an instance.

Examples:

>>> import jax.numpy as jnp
>>> probability = occurrence_probability("constant", 0.0, 2.0, lambda_0=0.5)
>>> bool(jnp.allclose(probability, 1.0 - jnp.exp(-1.0)))
True
Source code in src/plumax/population/_src/persistency.py
def occurrence_probability(
    intensity: str | eqx.Module,
    t: ArrayLike,
    horizon: float,
    *,
    nodes_per_day: int = NODES_PER_DAY,
    **theta: Any,
) -> Float[Array, ""]:
    """Probability of at least one event, P(N(t, t + h) ≥ 1) = 1 − exp(−Λ(t, t + h)).

    Args:
        intensity: A registry name or a kernel instance.
        t: Start time t [days].
        horizon: Horizon h > 0 [days], a concrete number since it sets the node count.
        nodes_per_day: Quadrature density for kernels without a closed form.
        **theta: Kernel parameters, when ``intensity`` is a name.

    Returns:
        The probability.

    Raises:
        ValueError: For a renewal or Hawkes process (see the ``conditional_``
            functions), or parameters with an instance.

    Examples:
        >>> import jax.numpy as jnp
        >>> probability = occurrence_probability("constant", 0.0, 2.0, lambda_0=0.5)
        >>> bool(jnp.allclose(probability, 1.0 - jnp.exp(-1.0)))
        True
    """
    count = expected_count(intensity, t, horizon, nodes_per_day=nodes_per_day, **theta)
    # 1 − exp(−Λ), accurate for small Λ
    return -jnp.expm1(-count)

posterior_conditional_occurrence_probability

posterior_conditional_occurrence_probability(posterior: Module, event_times: Float[ArrayLike, ' event'], mask: Bool[ArrayLike, ' event'], t: ArrayLike, horizon: ArrayLike, *, quantiles: Sequence[float] = (0.05, 0.5, 0.95)) -> dict[str, Array]

Posterior samples of :func:conditional_occurrence_probability.

m⁽ᵉ⁾ = P(N(t, t + h] ≥ 1 | H_t, θ⁽ᵉ⁾) for each draw θ⁽ᵉ⁾ of the process, through :func:posterior_metric. event_times must be the complete history H_t, not thinned detections.

Parameters:

Name Type Description Default
posterior Module

A process whose parameters carry a leading draw axis, such as ExponentialHawkes(mu=μ⁽ᵉ⁾, alpha=α⁽ᵉ⁾, beta=β⁽ᵉ⁾, observation_window=T).

required
event_times Float[ArrayLike, ' event']

Event times tᵢ, padded [days].

required
mask Bool[ArrayLike, ' event']

True for the real events of the buffer.

required
t ArrayLike

Time t of the outlook [days].

required
horizon ArrayLike

Horizon h ≥ 0 [days].

required
quantiles Sequence[float]

Quantile levels to report.

(0.05, 0.5, 0.95)

Returns:

Type Description
dict[str, Array]

{"samples": m⁽ᵉ⁾, "levels": the quantile levels, "quantiles": their values}.

Examples:

>>> import jax.numpy as jnp
>>> from pyrox_xtreme.point_processes.operators import ExponentialHawkes
>>> draws = ExponentialHawkes(
...     mu=jnp.array([0.4, 0.5, 0.6]), alpha=0.5, beta=2.0, observation_window=10.0
... )
>>> times, mask = jnp.array([3.0]), jnp.array([True])
>>> result = posterior_conditional_occurrence_probability(
...     draws, times, mask, 3.5, 1.0
... )
>>> result["samples"].shape
(3,)
Source code in src/plumax/population/_src/persistency.py
def posterior_conditional_occurrence_probability(
    posterior: eqx.Module,
    event_times: Float[ArrayLike, " event"],
    mask: Bool[ArrayLike, " event"],
    t: ArrayLike,
    horizon: ArrayLike,
    *,
    quantiles: Sequence[float] = (0.05, 0.5, 0.95),
) -> dict[str, Array]:
    """Posterior samples of :func:`conditional_occurrence_probability`.

    m⁽ᵉ⁾ = P(N(t, t + h] ≥ 1 | H_t, θ⁽ᵉ⁾) for each draw θ⁽ᵉ⁾ of the process, through
    :func:`posterior_metric`. ``event_times`` must be the complete history H_t, not
    thinned detections.

    Args:
        posterior: A process whose parameters carry a leading draw axis, such as
            ``ExponentialHawkes(mu=μ⁽ᵉ⁾, alpha=α⁽ᵉ⁾, beta=β⁽ᵉ⁾, observation_window=T)``.
        event_times: Event times tᵢ, padded [days].
        mask: True for the real events of the buffer.
        t: Time t of the outlook [days].
        horizon: Horizon h ≥ 0 [days].
        quantiles: Quantile levels to report.

    Returns:
        ``{"samples": m⁽ᵉ⁾, "levels": the quantile levels, "quantiles": their values}``.

    Examples:
        >>> import jax.numpy as jnp
        >>> from pyrox_xtreme.point_processes.operators import ExponentialHawkes
        >>> draws = ExponentialHawkes(
        ...     mu=jnp.array([0.4, 0.5, 0.6]), alpha=0.5, beta=2.0, observation_window=10.0
        ... )
        >>> times, mask = jnp.array([3.0]), jnp.array([True])
        >>> result = posterior_conditional_occurrence_probability(
        ...     draws, times, mask, 3.5, 1.0
        ... )
        >>> result["samples"].shape
        (3,)
    """
    return posterior_metric(
        conditional_occurrence_probability,
        posterior,
        event_times,
        mask,
        t,
        horizon,
        quantiles=quantiles,
    )

posterior_conditional_wait_time

posterior_conditional_wait_time(posterior: Module, event_times: Float[ArrayLike, ' event'], mask: Bool[ArrayLike, ' event'], t: ArrayLike, *, quantiles: Sequence[float] = (0.05, 0.5, 0.95), n_cells: int = 2048) -> dict[str, Array]

Posterior samples of :func:conditional_wait_time.

m⁽ᵉ⁾ = E[Δt | H_t, θ⁽ᵉ⁾] for each draw θ⁽ᵉ⁾ of the process, through :func:posterior_metric. event_times must be the complete history H_t, not thinned detections.

Parameters:

Name Type Description Default
posterior Module

A process whose parameters carry a leading draw axis, such as RenewalProcess(Weibull(η⁽ᵉ⁾, k⁽ᵉ⁾), observation_window=T).

required
event_times Float[ArrayLike, ' event']

Event times tᵢ, padded [days].

required
mask Bool[ArrayLike, ' event']

True for the real events of the buffer.

required
t ArrayLike

Time t of the outlook [days].

required
quantiles Sequence[float]

Quantile levels to report.

(0.05, 0.5, 0.95)
n_cells int

Log-spaced cells of the survival grid.

2048

Returns:

Type Description
dict[str, Array]

{"samples": m⁽ᵉ⁾, "levels": the quantile levels, "quantiles": their values}.

Examples:

>>> import jax.numpy as jnp
>>> import numpyro.distributions as dist
>>> from pyrox_xtreme.point_processes.operators import RenewalProcess
>>> gaps = dist.Weibull(jnp.array([0.8, 1.0, 1.2]), jnp.full(3, 2.0))
>>> draws = RenewalProcess(gaps, observation_window=10.0)
>>> times, mask = jnp.array([3.0]), jnp.array([True])
>>> result = posterior_conditional_wait_time(draws, times, mask, 3.2)
>>> bool(jnp.all(jnp.diff(result["samples"]) > 0))
True
Source code in src/plumax/population/_src/persistency.py
def posterior_conditional_wait_time(
    posterior: eqx.Module,
    event_times: Float[ArrayLike, " event"],
    mask: Bool[ArrayLike, " event"],
    t: ArrayLike,
    *,
    quantiles: Sequence[float] = (0.05, 0.5, 0.95),
    n_cells: int = 2048,
) -> dict[str, Array]:
    """Posterior samples of :func:`conditional_wait_time`.

    m⁽ᵉ⁾ = E[Δt | H_t, θ⁽ᵉ⁾] for each draw θ⁽ᵉ⁾ of the process, through
    :func:`posterior_metric`. ``event_times`` must be the complete history H_t, not
    thinned detections.

    Args:
        posterior: A process whose parameters carry a leading draw axis, such as
            ``RenewalProcess(Weibull(η⁽ᵉ⁾, k⁽ᵉ⁾), observation_window=T)``.
        event_times: Event times tᵢ, padded [days].
        mask: True for the real events of the buffer.
        t: Time t of the outlook [days].
        quantiles: Quantile levels to report.
        n_cells: Log-spaced cells of the survival grid.

    Returns:
        ``{"samples": m⁽ᵉ⁾, "levels": the quantile levels, "quantiles": their values}``.

    Examples:
        >>> import jax.numpy as jnp
        >>> import numpyro.distributions as dist
        >>> from pyrox_xtreme.point_processes.operators import RenewalProcess
        >>> gaps = dist.Weibull(jnp.array([0.8, 1.0, 1.2]), jnp.full(3, 2.0))
        >>> draws = RenewalProcess(gaps, observation_window=10.0)
        >>> times, mask = jnp.array([3.0]), jnp.array([True])
        >>> result = posterior_conditional_wait_time(draws, times, mask, 3.2)
        >>> bool(jnp.all(jnp.diff(result["samples"]) > 0))
        True
    """
    return posterior_metric(
        conditional_wait_time,
        posterior,
        event_times,
        mask,
        t,
        quantiles=quantiles,
        n_cells=n_cells,
    )

posterior_metric

posterior_metric(metric: Callable[..., Array], posterior: PoissonRatePosterior | InhomogeneousIntensityPosterior | TMTPPPosterior | Module, *args: Any, quantiles: Sequence[float] = (0.05, 0.5, 0.95), rate_scale: float = 1.0, covariates: Callable[[Array], Array] | None = None, num_samples: int = 1000, key: PRNGKeyArray | None = None, **metric_kwargs: Any) -> dict[str, Array]

Posterior samples of a persistency metric, and their quantiles.

m⁽ᵉ⁾ = m(λ⁽ᵉ⁾, …) for each draw λ⁽ᵉ⁾ of the intensity, vmapped over the draws.

The two rate posteriors of :mod:~plumax.population.point_process are per unit of their exposure, and their time and area units are the caller's, so rate_scale turns them into events day⁻¹ (the area, times the time unit per day, when the exposure was area × duration).

A process posterior, for the conditional_ metrics, is the process itself with a leading draw axis on its parameters (ExponentialHawkes(mu=μ⁽ᵉ⁾, …)); its scalar leaves, such as the observation window, are shared by every draw.

Parameters:

Name Type Description Default
metric Callable[..., Array]

metric(kernel, *args, **metric_kwargs), such as :func:expected_wait_time.

required
posterior PoissonRatePosterior | InhomogeneousIntensityPosterior | TMTPPPosterior | Module

The fitted posterior, or a process with a leading draw axis on its parameters.

required
*args Any

The metric's positional arguments after the intensity.

()
quantiles Sequence[float]

Quantile levels to report.

(0.05, 0.5, 0.95)
rate_scale float

Multiplier from the posterior's rate to events day⁻¹, for :class:~plumax.population.point_process.PoissonRatePosterior and :class:~plumax.population.point_process.InhomogeneousIntensityPosterior.

1.0
covariates Callable[[Array], Array] | None

z(t), the covariates of an :class:~plumax.population.point_process.InhomogeneousIntensityPosterior at time t, with a trailing covariate axis.

None
num_samples int

Draws from a Gamma posterior (the others carry their draws, so they ignore it).

1000
key PRNGKeyArray | None

PRNG key of a Gamma posterior.

None
**metric_kwargs Any

The metric's keyword arguments.

{}

Returns:

Type Description
dict[str, Array]

{"samples": m⁽ᵉ⁾, "levels": the quantile levels, "quantiles": their values}.

Raises:

Type Description
ValueError

Without key for a Gamma posterior, without covariates for a log-linear one, or for a process posterior given key, covariates or rate_scale, or with no draw axis.

Examples:

Wait time under a Gamma posterior on a constant rate:

>>> import jax
>>> from plumax.population.point_process import PoissonRatePosterior
>>> posterior = PoissonRatePosterior(
...     alpha=201.0, beta=100.0, n_events=200, exposure=100.0
... )
>>> result = posterior_metric(
...     expected_wait_time, posterior, 0.0, key=jax.random.PRNGKey(0)
... )
>>> result["samples"].shape
(1000,)
>>> bool(result["quantiles"][0] < 0.5 < result["quantiles"][2])
True
Source code in src/plumax/population/_src/persistency.py
def posterior_metric(
    metric: Callable[..., Array],
    posterior: PoissonRatePosterior
    | InhomogeneousIntensityPosterior
    | TMTPPPosterior
    | eqx.Module,
    *args: Any,
    quantiles: Sequence[float] = (0.05, 0.5, 0.95),
    rate_scale: float = 1.0,
    covariates: Callable[[Array], Array] | None = None,
    num_samples: int = 1000,
    key: PRNGKeyArray | None = None,
    **metric_kwargs: Any,
) -> dict[str, Array]:
    """Posterior samples of a persistency metric, and their quantiles.

    m⁽ᵉ⁾ = m(λ⁽ᵉ⁾, …) for each draw λ⁽ᵉ⁾ of the intensity, vmapped over the draws.

    The two rate posteriors of :mod:`~plumax.population.point_process` are per unit of
    their exposure, and their time and area units are the caller's, so ``rate_scale``
    turns them into events day⁻¹ (the area, times the time unit per day, when the
    exposure was area × duration).

    A process posterior, for the ``conditional_`` metrics, is the process itself with
    a leading draw axis on its parameters (``ExponentialHawkes(mu=μ⁽ᵉ⁾, …)``); its
    scalar leaves, such as the observation window, are shared by every draw.

    Args:
        metric: ``metric(kernel, *args, **metric_kwargs)``, such as
            :func:`expected_wait_time`.
        posterior: The fitted posterior, or a process with a leading draw axis on
            its parameters.
        *args: The metric's positional arguments after the intensity.
        quantiles: Quantile levels to report.
        rate_scale: Multiplier from the posterior's rate to events day⁻¹, for
            :class:`~plumax.population.point_process.PoissonRatePosterior` and
            :class:`~plumax.population.point_process.InhomogeneousIntensityPosterior`.
        covariates: z(t), the covariates of an
            :class:`~plumax.population.point_process.InhomogeneousIntensityPosterior`
            at time t, with a trailing covariate axis.
        num_samples: Draws from a Gamma posterior (the others carry their draws, so
            they ignore it).
        key: PRNG key of a Gamma posterior.
        **metric_kwargs: The metric's keyword arguments.

    Returns:
        ``{"samples": m⁽ᵉ⁾, "levels": the quantile levels, "quantiles": their values}``.

    Raises:
        ValueError: Without ``key`` for a Gamma posterior, without ``covariates``
            for a log-linear one, or for a process posterior given ``key``,
            ``covariates`` or ``rate_scale``, or with no draw axis.

    Examples:
        Wait time under a Gamma posterior on a constant rate:

        >>> import jax
        >>> from plumax.population.point_process import PoissonRatePosterior
        >>> posterior = PoissonRatePosterior(
        ...     alpha=201.0, beta=100.0, n_events=200, exposure=100.0
        ... )
        >>> result = posterior_metric(
        ...     expected_wait_time, posterior, 0.0, key=jax.random.PRNGKey(0)
        ... )
        >>> result["samples"].shape
        (1000,)
        >>> bool(result["quantiles"][0] < 0.5 < result["quantiles"][2])
        True
    """
    in_axes: Any = 0
    if isinstance(posterior, PoissonRatePosterior):
        draws = _poisson_draws(
            posterior, key=key, num_samples=num_samples, rate_scale=rate_scale
        )

        def member(draw: Array) -> Array:
            kernel = ConstantIntensity(lambda_0=draw)
            return metric(kernel, *args, **metric_kwargs)

    elif isinstance(posterior, InhomogeneousIntensityPosterior):
        if covariates is None:
            raise ValueError(
                "posterior_metric: a log-linear posterior needs covariates z(t)."
            )
        draws = (
            jnp.asarray(posterior.beta0_samples),
            jnp.asarray(posterior.beta_samples),
        )

        def member(draw: Any) -> Array:
            intercept, coefficients = draw
            kernel = _LogLinearIntensity(
                intercept, coefficients, covariates, rate_scale
            )
            return metric(kernel, *args, **metric_kwargs)

    elif isinstance(posterior, TMTPPPosterior):
        draws = {name: jnp.asarray(value) for name, value in posterior.samples.items()}

        def member(draw: Any) -> Array:
            return metric(posterior.kernel(draw), *args, **metric_kwargs)

    else:
        if key is not None or covariates is not None or rate_scale != 1.0:
            raise ValueError(
                "posterior_metric: a process posterior carries its own draws, so it "
                "takes no key, covariates or rate_scale."
            )
        draws = posterior
        # the draw axis leads every non-scalar leaf; scalar leaves are shared
        in_axes = jax.tree.map(lambda leaf: 0 if jnp.ndim(leaf) > 0 else None, draws)
        if all(axis is None for axis in jax.tree.leaves(in_axes, is_leaf=_is_none)):
            raise ValueError(
                "posterior_metric: a process posterior needs a leading draw axis on "
                "its parameters; every leaf of this one is a scalar."
            )

        def member(draw: Any) -> Array:
            return metric(draw, *args, **metric_kwargs)

    samples = jax.vmap(member, in_axes=(in_axes,))(draws)
    levels = jnp.asarray(quantiles, dtype=samples.dtype)
    return {
        "samples": samples,
        "levels": levels,
        "quantiles": jnp.quantile(samples, levels),
    }