mal_core.habitat.capacity

Species-indexed habitat capacity S[i,s,t] and Beverton-Holt scale K[i,s,t].

S[i,s,t] = clip(sum_g w[s,g] * H[i,g] * A[i,k(g),t], 0, 1)
K[i,s,t] = K_ref[s] * cell_area_km2[i] * S[i,s,t]
  • The shared temporal responses A and the static potentials H are species-independent; only w[s,g] carries species preferences.
  • The returned K is an ABSOLUTE per-cell aquatic capacity (individuals per day) — it replaced the retired per-cell multiplier k_capacity_mult (contract 3.0), and the retired global K_MAX fallback was removed with contract 4.0 (plan 03-retirada-k-max): the Beverton-Holt consumer uses exactly this grid, with K=0 meaning explicit zero larval survival.
  • cell_area_km2 accounts for the true ground area of each grid row (resolution_m x resolution_m x cos(lat)). Edge cells clipped by the AOI bbox are NOT area-corrected in the MVP (all rows are regular), but the factor is documented; plan 02 §8 lists row-accurate edge de-limitation as a sensitivity extension.
  1"""Species-indexed habitat capacity S[i,s,t] and Beverton-Holt scale K[i,s,t].
  2
  3    S[i,s,t] = clip(sum_g w[s,g] * H[i,g] * A[i,k(g),t], 0, 1)
  4    K[i,s,t] = K_ref[s] * cell_area_km2[i] * S[i,s,t]
  5
  6* The shared temporal responses A and the static potentials H are
  7  species-independent; only ``w[s,g]`` carries species preferences.
  8* The returned K is an ABSOLUTE per-cell aquatic capacity (individuals per
  9  day) — it replaced the retired per-cell multiplier `k_capacity_mult`
 10  (contract 3.0), and the retired global K_MAX fallback was removed with
 11  contract 4.0 (plan 03-retirada-k-max): the Beverton-Holt consumer uses
 12  exactly this grid, with K=0 meaning explicit zero larval survival.
 13* cell_area_km2 accounts for the true ground area of each grid row
 14  (resolution_m x resolution_m x cos(lat)). Edge cells clipped by the AOI
 15  bbox are NOT area-corrected in the MVP (all rows are regular), but the
 16  factor is documented; plan 02 §8 lists row-accurate edge de-limitation
 17  as a sensitivity extension.
 18"""
 19from __future__ import annotations
 20
 21from typing import Mapping
 22
 23import numpy as np
 24
 25from .config import CONFIG
 26# Emergency-adult scaling constant for the py DIAGNOSTIC capacity path
 27# (renamed from the retired K_REF_DAILY_PER_KM2 .py constant; it is NOT a
 28# model_constants.yaml key — the engine's k_ref is a different
 29# concept; plan constants-yaml §9.1: dies here without conversion).
 30K_REF_DIAG_PER_KM2: float = 0.143 * 9.3 * 1.0e6  # [ind·km⁻²·d⁻¹ diagnostic]
 31from .potential import total_potential
 32
 33_DEFAULT_SPECIES = str(CONFIG["species"]["default_species"])
 34_PLUVIAL_TYPES = frozenset(
 35    g for g, k in CONFIG["habitat_types"]["dynamics"].items()
 36    if k == "pluvial")
 37
 38
 39def cell_area_km2(lat_deg: np.ndarray | float, resolution_m: float) -> np.ndarray | float:
 40    """Ground area of one AOI cell (approximation: constant width within
 41    the row's latitude). ``lat_deg`` may be scalar or a per-row array
 42    (height = number of rows); returns array of the same broadcast shape."""
 43    lat = np.asarray(lat_deg, dtype=np.float64)
 44    width_m = resolution_m * np.cos(np.deg2rad(lat))
 45    height_m = float(resolution_m)
 46    return width_m * height_m / 1.0e6
 47
 48
 49def species_accuracy(
 50    h: Mapping[str, np.ndarray],
 51    z_pluvial: np.ndarray,
 52    weights: Mapping[str, float] | None = None,
 53) -> np.ndarray:
 54    """Sum_g w[g] * H[g] * (1 if persistent else z). Applied per cell.
 55
 56    Args:
 57        h: mapping habitat type -> per-cell potential in [0, 1].
 58        z_pluvial: per-cell pluvial availability in [0, 1] for today.
 59        weights: species affinity w[s, g]; defaults to the coluzzii
 60            profile when ``species`` was default; the plan's contract is
 61            that neither H nor z are species-dependent.
 62    Returns:
 63        per-cell S in [0, 1].
 64    """
 65    w = weights if weights is not None else dict(
 66        CONFIG["species"][_DEFAULT_SPECIES]["weights"])
 67    acc = np.zeros_like(z_pluvial, dtype=np.float64)
 68    for g, val in h.items():
 69        weight = float(w.get(g, 0.0))
 70        if weight <= 0.0:
 71            continue
 72        avail = (z_pluvial if g in _PLUVIAL_TYPES
 73                 else float(CONFIG["capacity"]["persistent_availability"]))
 74        c = np.asarray(val, dtype=np.float64)
 75        acc += weight * c * avail
 76    return np.clip(acc, 0.0, 1.0)
 77
 78
 79def k_habitat(
 80    s: np.ndarray,
 81    lat: np.ndarray,
 82    resolution_m: float,
 83    K_ref: float | None = None,
 84) -> np.ndarray:
 85    """Beverton-Holt per-cell capacity K[i,s,t] in larval-equivalents."""
 86    k_ref = K_ref if K_ref is not None else K_REF_DIAG_PER_KM2
 87    area = np.asarray(cell_area_km2(lat, resolution_m), dtype=np.float64)
 88    if area.shape != s.shape:
 89        # Broadcast per-row scalars down a 2-D S: rows all share the same
 90        # latitude-derived ground area.
 91        if area.ndim == 1 and s.ndim == 2 and area.shape[0] == s.shape[0]:
 92            area = area[:, None]
 93        else:
 94            area = np.broadcast_to(area, s.shape)
 95    return k_ref * area * np.asarray(s, dtype=np.float64)
 96
 97
 98def accuracy_amplitude(h: Mapping[str, np.ndarray]) -> np.ndarray:
 99    """H_total alias used for patch seeding weights / diagnostics."""
100    return np.asarray(total_potential(h), dtype=np.float64)
101
102
103__all__ = [
104    "cell_area_km2",
105    "k_habitat",
106    "species_accuracy",
107    "accuracy_amplitude",
108]
def cell_area_km2( lat_deg: numpy.ndarray | float, resolution_m: float) -> numpy.ndarray | float:
40def cell_area_km2(lat_deg: np.ndarray | float, resolution_m: float) -> np.ndarray | float:
41    """Ground area of one AOI cell (approximation: constant width within
42    the row's latitude). ``lat_deg`` may be scalar or a per-row array
43    (height = number of rows); returns array of the same broadcast shape."""
44    lat = np.asarray(lat_deg, dtype=np.float64)
45    width_m = resolution_m * np.cos(np.deg2rad(lat))
46    height_m = float(resolution_m)
47    return width_m * height_m / 1.0e6

Ground area of one AOI cell (approximation: constant width within the row's latitude). lat_deg may be scalar or a per-row array (height = number of rows); returns array of the same broadcast shape.

def k_habitat( s: numpy.ndarray, lat: numpy.ndarray, resolution_m: float, K_ref: float | None = None) -> numpy.ndarray:
80def k_habitat(
81    s: np.ndarray,
82    lat: np.ndarray,
83    resolution_m: float,
84    K_ref: float | None = None,
85) -> np.ndarray:
86    """Beverton-Holt per-cell capacity K[i,s,t] in larval-equivalents."""
87    k_ref = K_ref if K_ref is not None else K_REF_DIAG_PER_KM2
88    area = np.asarray(cell_area_km2(lat, resolution_m), dtype=np.float64)
89    if area.shape != s.shape:
90        # Broadcast per-row scalars down a 2-D S: rows all share the same
91        # latitude-derived ground area.
92        if area.ndim == 1 and s.ndim == 2 and area.shape[0] == s.shape[0]:
93            area = area[:, None]
94        else:
95            area = np.broadcast_to(area, s.shape)
96    return k_ref * area * np.asarray(s, dtype=np.float64)

Beverton-Holt per-cell capacity K[i,s,t] in larval-equivalents.

def species_accuracy( h: Mapping[str, numpy.ndarray], z_pluvial: numpy.ndarray, weights: Optional[Mapping[str, float]] = None) -> numpy.ndarray:
50def species_accuracy(
51    h: Mapping[str, np.ndarray],
52    z_pluvial: np.ndarray,
53    weights: Mapping[str, float] | None = None,
54) -> np.ndarray:
55    """Sum_g w[g] * H[g] * (1 if persistent else z). Applied per cell.
56
57    Args:
58        h: mapping habitat type -> per-cell potential in [0, 1].
59        z_pluvial: per-cell pluvial availability in [0, 1] for today.
60        weights: species affinity w[s, g]; defaults to the coluzzii
61            profile when ``species`` was default; the plan's contract is
62            that neither H nor z are species-dependent.
63    Returns:
64        per-cell S in [0, 1].
65    """
66    w = weights if weights is not None else dict(
67        CONFIG["species"][_DEFAULT_SPECIES]["weights"])
68    acc = np.zeros_like(z_pluvial, dtype=np.float64)
69    for g, val in h.items():
70        weight = float(w.get(g, 0.0))
71        if weight <= 0.0:
72            continue
73        avail = (z_pluvial if g in _PLUVIAL_TYPES
74                 else float(CONFIG["capacity"]["persistent_availability"]))
75        c = np.asarray(val, dtype=np.float64)
76        acc += weight * c * avail
77    return np.clip(acc, 0.0, 1.0)

Sum_g w[g] * H[g] * (1 if persistent else z). Applied per cell.

Args: h: mapping habitat type -> per-cell potential in [0, 1]. z_pluvial: per-cell pluvial availability in [0, 1] for today. weights: species affinity w[s, g]; defaults to the coluzzii profile when species was default; the plan's contract is that neither H nor z are species-dependent. Returns: per-cell S in [0, 1].

def accuracy_amplitude(h: Mapping[str, numpy.ndarray]) -> numpy.ndarray:
 99def accuracy_amplitude(h: Mapping[str, np.ndarray]) -> np.ndarray:
100    """H_total alias used for patch seeding weights / diagnostics."""
101    return np.asarray(total_potential(h), dtype=np.float64)

H_total alias used for patch seeding weights / diagnostics.