mal_core

MalariaSentinel — stable core pipeline.

 1"""MalariaSentinel — stable core pipeline."""
 2
 3__version__ = "0.2.0"
 4
 5# Heavy submodules (training -> torch, server -> fastapi, prediction) are
 6# imported lazily so that `import mal_core` (and any subcommand such as
 7# `abm` / `download` / `ingest`) does not force torch/fastapi to load.
 8# `__getattr__` resolves them only when accessed, preserving the public
 9# names in `__all__` below.
10
11__all__ = [
12    "UNet", "combined_loss", "eval_dice",
13    "RolloutDataset", "get_dataloaders",
14    "train_unet", "UNetWrapper",
15    "make_aoi", "get_aggregator", "grid_shape",
16    "RegionalAggregator", "NationalAggregator", "ContinentalAggregator",
17    "ScenarioConfig", "InterventionConfig", "ClimateConfig",
18    "load_scenario", "interventions_to_params",
19    "ModelRegistry", "ModelManifest", "DummyModel",
20    "run_prediction", "get_latest_prediction", "get_prediction_metadata",
21    "fastapi_app", "cli_main",
22]
23
24_LAZY = {
25    # name -> (module_path, attribute_name)
26    "UNet": (".training.model", "UNet"),
27    "combined_loss": (".training.model", "combined_loss"),
28    "eval_dice": (".training.model", "eval_dice"),
29    "RolloutDataset": (".training.dataset", "RolloutDataset"),
30    "get_dataloaders": (".training.dataset", "get_dataloaders"),
31    "train_unet": (".training.trainer", "train_unet"),
32    "UNetWrapper": (".training.wrapper", "UNetWrapper"),
33    "make_aoi": (".prediction.aggregator", "make_aoi"),
34    "get_aggregator": (".prediction.aggregator", "get_aggregator"),
35    "grid_shape": (".prediction.aggregator", "grid_shape"),
36    "RegionalAggregator": (".prediction.aggregator", "RegionalAggregator"),
37    "NationalAggregator": (".prediction.aggregator", "NationalAggregator"),
38    "ContinentalAggregator": (".prediction.aggregator", "ContinentalAggregator"),
39    "ModelRegistry": (".prediction.registry", "ModelRegistry"),
40    "ModelManifest": (".prediction.registry", "ModelManifest"),
41    "DummyModel": (".prediction.registry", "DummyModel"),
42    "run_prediction": (".prediction.predictor", "run_prediction"),
43    "get_latest_prediction": (".prediction.predictor", "get_latest_prediction"),
44    "get_prediction_metadata": (".prediction.predictor", "get_prediction_metadata"),
45    "ScenarioConfig": (".scenario", "ScenarioConfig"),
46    "InterventionConfig": (".scenario", "InterventionConfig"),
47    "ClimateConfig": (".scenario", "ClimateConfig"),
48    "load_scenario": (".scenario", "load_scenario"),
49    "interventions_to_params": (".scenario", "interventions_to_params"),
50    "fastapi_app": (".server", "app"),
51}
52
53# Lightweight import kept eager: the CLI entrypoint is always needed.
54from .cli import main as cli_main  # noqa: E402
55
56
57def __getattr__(name: str):
58    """Resolve a lazily-exported public name by importing its module on demand.
59
60    Heavy submodules (torch, fastapi) are only imported when one of the
61    names listed in ``__all__`` is first accessed; the resolved object is
62    then cached in the module globals. Raises AttributeError for any name
63    that is not part of the lazy export table.
64    """
65    entry = _LAZY.get(name)
66    if entry is None:
67        raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
68    mod_path, attr = entry
69    import importlib
70
71    mod = importlib.import_module(mod_path, __name__)
72    value = getattr(mod, attr)
73    globals()[name] = value
74    return value
75
76
77def __dir__():
78    """List the module's attributes, including the not-yet-imported lazy names."""
79    return sorted(set(globals()) | set(__all__))
class UNet(torch.nn.modules.module.Module):
37class UNet(nn.Module):
38    """Encoder-decoder network that predicts the next state of a patch.
39
40    Four encoder stages with max-pooling between them, a bottleneck at
41    twice the deepest width, and a mirrored decoder that concatenates the
42    skip connections. The head is a 1x1 convolution producing the output
43    channels.
44    """
45
46    def __init__(self, in_channels=6, out_channels=2,
47                 channels=(32, 64, 128, 256)):
48        """Build the network.
49
50        Args:
51            in_channels: channels of the input tensor (state plus environment).
52            out_channels: channels of the predicted next state.
53            channels: width of each encoder stage, deepest last.
54        """
55        super().__init__()
56        c = channels
57        self.enc = nn.ModuleList()
58        prev = in_channels
59        for ch in c:
60            self.enc.append(DoubleConv(prev, ch)); prev = ch
61        self.pool = nn.MaxPool2d(2)
62        self.bottleneck = DoubleConv(c[-1], c[-1] * 2)
63        self.upconvs = nn.ModuleList()
64        self.dec = nn.ModuleList()
65        prev = c[-1] * 2
66        for ch in reversed(c):
67            self.upconvs.append(nn.ConvTranspose2d(prev, ch, 2, stride=2))
68            self.dec.append(DoubleConv(ch * 2, ch))
69            prev = ch
70        self.head = nn.Conv2d(c[0], out_channels, 1)
71
72    def forward(self, x):
73        """Predict the next state from a (N, in_channels, H, W) tensor."""
74        skips = []
75        for enc in self.enc:
76            x = enc(x); skips.append(x); x = self.pool(x)
77        x = self.bottleneck(x)
78        for upc, dec in zip(self.upconvs, self.dec):
79            x = upc(x)
80            skip = skips.pop()
81            if x.shape[-1] != skip.shape[-1]:
82                x = F.interpolate(x, size=skip.shape[-2:], mode="bilinear", align_corners=False)
83            x = torch.cat([x, skip], dim=1)
84            x = dec(x)
85        return self.head(x)

Encoder-decoder network that predicts the next state of a patch.

Four encoder stages with max-pooling between them, a bottleneck at twice the deepest width, and a mirrored decoder that concatenates the skip connections. The head is a 1x1 convolution producing the output channels.

UNet(in_channels=6, out_channels=2, channels=(32, 64, 128, 256))
46    def __init__(self, in_channels=6, out_channels=2,
47                 channels=(32, 64, 128, 256)):
48        """Build the network.
49
50        Args:
51            in_channels: channels of the input tensor (state plus environment).
52            out_channels: channels of the predicted next state.
53            channels: width of each encoder stage, deepest last.
54        """
55        super().__init__()
56        c = channels
57        self.enc = nn.ModuleList()
58        prev = in_channels
59        for ch in c:
60            self.enc.append(DoubleConv(prev, ch)); prev = ch
61        self.pool = nn.MaxPool2d(2)
62        self.bottleneck = DoubleConv(c[-1], c[-1] * 2)
63        self.upconvs = nn.ModuleList()
64        self.dec = nn.ModuleList()
65        prev = c[-1] * 2
66        for ch in reversed(c):
67            self.upconvs.append(nn.ConvTranspose2d(prev, ch, 2, stride=2))
68            self.dec.append(DoubleConv(ch * 2, ch))
69            prev = ch
70        self.head = nn.Conv2d(c[0], out_channels, 1)

Build the network.

Args: in_channels: channels of the input tensor (state plus environment). out_channels: channels of the predicted next state. channels: width of each encoder stage, deepest last.

enc
pool
bottleneck
upconvs
dec
head
def forward(self, x):
72    def forward(self, x):
73        """Predict the next state from a (N, in_channels, H, W) tensor."""
74        skips = []
75        for enc in self.enc:
76            x = enc(x); skips.append(x); x = self.pool(x)
77        x = self.bottleneck(x)
78        for upc, dec in zip(self.upconvs, self.dec):
79            x = upc(x)
80            skip = skips.pop()
81            if x.shape[-1] != skip.shape[-1]:
82                x = F.interpolate(x, size=skip.shape[-2:], mode="bilinear", align_corners=False)
83            x = torch.cat([x, skip], dim=1)
84            x = dec(x)
85        return self.head(x)

Predict the next state from a (N, in_channels, H, W) tensor.

def combined_loss( pred: torch.Tensor, target: torch.Tensor) -> tuple[torch.Tensor, float, float]:
102def combined_loss(pred: torch.Tensor, target: torch.Tensor) -> tuple[torch.Tensor, float, float]:
103    """Combined MSE + Soft-Dice loss for multi-channel epidemiological state."""
104    mse = F.mse_loss(pred, target)
105    sd = soft_dice_loss(pred[:, :1], target[:, :1])  # focus Dice on density/sparse channel
106    loss = mse + 0.5 * sd
107    return loss, float(mse.item()), float(sd.item())

Combined MSE + Soft-Dice loss for multi-channel epidemiological state.

@torch.no_grad()
def eval_dice(pred: torch.Tensor, target: torch.Tensor, thresh: float = 0.5) -> float:
110@torch.no_grad()
111def eval_dice(pred: torch.Tensor, target: torch.Tensor, thresh: float = 0.5) -> float:
112    """Evaluate hard Dice score on the primary channel (vector density).
113
114    thresh is in adult counts (contract 4.0): 0.5 ⇒ >= 1 adult.
115    """
116    p = (pred[:, :1] > thresh).float()
117    t = (target[:, :1] > thresh).float()
118    inter = (p * t).sum()
119    union = p.sum() + t.sum()
120    return float((2 * inter + 1e-6) / (union + 1e-6))

Evaluate hard Dice score on the primary channel (vector density).

thresh is in adult counts (contract 4.0): 0.5 ⇒ >= 1 adult.

class RolloutDataset(typing.Generic[+_T_co]):
 39class RolloutDataset(Dataset):
 40    """Patches of consecutive ABM state snapshots for surrogate training.
 41
 42    Reads the ``*_dayNNN`` state snapshots of a run directory, tiles them
 43    into square patches and pairs each patch with the same patch one day
 44    later, so the dataset yields ``(state_t + env, state_{t+1})`` samples.
 45    The spatial split is fixed: patches whose left column is east of the
 46    raster mid-line belong to the validation split, the rest to training.
 47    """
 48
 49    def __init__(
 50        self,
 51        run_dir: str | Path,
 52        split: Literal["train", "val"] = "train",
 53        patch_size: int = PATCH_SIZE,
 54        subsample: float = 1.0,
 55        preload: bool = False,
 56        include_transmission: bool = True,
 57        env_path: str | Path | None = None,
 58    ):
 59        """Index the patches of a run directory for one spatial split.
 60
 61        Args:
 62            run_dir: directory holding the ``*_dayNNN.tif`` (or ``.npy``)
 63                state snapshots and, optionally, the transmission snapshots.
 64            split: ``"train"`` (west of the raster mid-line) or ``"val"``.
 65            patch_size: side of the square patch in cells.
 66            subsample: fraction of the selected patches to keep, in [0, 1].
 67            preload: read every referenced raster into memory up front.
 68            include_transmission: append the transmission channels when
 69                matching snapshots exist.
 70            env_path: optional NetCDF or GeoTIFF of environmental planes
 71                whose channels are concatenated to the input.
 72
 73        Raises:
 74            FileNotFoundError: no state snapshot files in ``run_dir``.
 75        """
 76        self.run_dir = Path(run_dir)
 77        self.split = split
 78        self.patch_size = patch_size
 79        self.subsample = subsample
 80        self.preload = preload
 81        self.include_transmission = include_transmission
 82        self.env_path = Path(env_path) if env_path else None
 83
 84        self.patches: list[dict] = []
 85        self._data_cache: dict[str, np.ndarray] = {}
 86        self._env_cache: np.ndarray | None = None
 87
 88        self._load_env_if_available()
 89        self._build_patches()
 90        if preload:
 91            self._preload_data()
 92
 93    def _load_env_if_available(self) -> None:
 94        """Load the environmental planes into ``_env_cache``, if any.
 95
 96        Reads the first ``ENV_CHANNELS`` variables of a NetCDF (or bands of
 97        a GeoTIFF) as float32 arrays of shape (channels, height, width);
 98        missing channels are zero-padded. Any failure (unreadable file,
 99        wrong shape) leaves the cache at None, i.e. the environmental input
100        is silently all-zero for that dataset.
101        """
102        if self.env_path and self.env_path.exists():
103            try:
104                if self.env_path.suffix in (".nc", ".nc4"):
105                    import xarray as xr
106                    with xr.open_dataset(self.env_path) as ds:
107                        vars_to_use = [v for v in ["rainfall", "air_temp_c", "jrc_persistent", "lc_built", "lc_wetland", "lc_open_plus_water", "lc_crop"] if v in ds]
108                        arrs = [ds[v].values.squeeze() for v in vars_to_use[:ENV_CHANNELS]]
109                        if len(arrs) < ENV_CHANNELS:
110                            H, W = arrs[0].shape[-2:]
111                            while len(arrs) < ENV_CHANNELS:
112                                arrs.append(np.zeros((H, W), dtype=np.float32))
113                        self._env_cache = np.stack(arrs[:ENV_CHANNELS], axis=0).astype(np.float32)
114                elif self.env_path.suffix in (".tif", ".tiff"):
115                    with rasterio.open(self.env_path) as src:
116                        data = src.read().astype(np.float32)
117                        if data.shape[0] < ENV_CHANNELS:
118                            padded = np.zeros((ENV_CHANNELS, data.shape[1], data.shape[2]), dtype=np.float32)
119                            padded[:data.shape[0]] = data
120                            data = padded
121                        self._env_cache = data[:ENV_CHANNELS]
122            except Exception:
123                self._env_cache = None
124
125    def _build_patches(self) -> None:
126        """Enumerate the (day t, day t+1) patch pairs of the selected split.
127
128        Groups the state snapshots by rollout seed and simulation day, pairs
129        consecutive days, and cuts each raster into patches of
130        ``patch_size`` cells, keeping only the patches of the requested
131        spatial split. A random subsample is drawn when ``subsample`` is
132        below 1. Raises FileNotFoundError when the run directory holds no
133        state snapshot.
134        """
135        # 1. Discover all state snapshot files (excluding transmission files)
136        candidate_tifs = sorted(self.run_dir.glob("*.tif"))
137        state_tifs = [p for p in candidate_tifs if "_day" in p.name and "transmission" not in p.name]
138        state_npys = sorted(self.run_dir.glob("*_day*.npy"))
139
140        use_tiff = len(state_tifs) >= len(state_npys)
141        state_files = state_tifs if use_tiff else state_npys
142
143        if not state_files:
144            raise FileNotFoundError(f"No ABM state snapshot files (*_day*.tif/npy) found in {self.run_dir}")
145
146        # Group by seed/rollout
147        series_by_seed: dict[int, dict[int, Path]] = {}
148        for p in state_files:
149            seed, day = _extract_seed_and_day(p)
150            if seed not in series_by_seed:
151                series_by_seed[seed] = {}
152            series_by_seed[seed][day] = p
153
154        # Check for matching transmission snapshots
155        trans_by_seed: dict[int, dict[int, Path]] = {}
156        if self.include_transmission:
157            trans_files = [p for p in candidate_tifs if "_day" in p.name and "transmission" in p.name]
158            for p in trans_files:
159                seed, day = _extract_seed_and_day(p)
160                if seed not in trans_by_seed:
161                    trans_by_seed[seed] = {}
162                trans_by_seed[seed][day] = p
163
164        # Get raster dimensions
165        first_file = state_files[0]
166        if use_tiff:
167            with rasterio.open(first_file) as src:
168                H, W = src.shape
169        else:
170            sample = np.load(first_file)
171            H, W = sample.shape[-2], sample.shape[-1]
172
173        n_patches_h = max(1, H // self.patch_size)
174        n_patches_w = max(1, W // self.patch_size)
175        mid_col = W // 2
176
177        # Build consecutive temporal pairs (day_t, day_{t+1})
178        for seed, days_dict in series_by_seed.items():
179            sorted_days = sorted(days_dict.keys())
180            for i in range(len(sorted_days) - 1):
181                day_cur = sorted_days[i]
182                day_next = sorted_days[i + 1]
183
184                state_cur = days_dict[day_cur]
185                state_next = days_dict[day_next]
186
187                trans_cur = trans_by_seed.get(seed, {}).get(day_cur)
188                trans_next = trans_by_seed.get(seed, {}).get(day_next)
189
190                has_trans = bool(self.include_transmission and trans_cur and trans_next)
191
192                for r in range(n_patches_h):
193                    for c in range(n_patches_w):
194                        is_east = (c * self.patch_size) >= mid_col
195                        patch_split = "val" if is_east else "train"
196
197                        if patch_split != self.split:
198                            continue
199
200                        self.patches.append({
201                            "state_path": state_cur,
202                            "next_path": state_next,
203                            "trans_path": trans_cur if has_trans else None,
204                            "trans_next_path": trans_next if has_trans else None,
205                            "row": r * self.patch_size,
206                            "col": c * self.patch_size,
207                            "use_tiff": use_tiff,
208                        })
209
210        if self.subsample < 1.0 and self.patches:
211            np.random.seed(42)
212            n_keep = max(1, int(len(self.patches) * self.subsample))
213            indices = np.random.choice(len(self.patches), n_keep, replace=False)
214            self.patches = [self.patches[i] for i in indices]
215
216    def _read_raster(self, path: Path | str, is_tiff: bool) -> np.ndarray:
217        """Read one snapshot as a float32 array of shape (channels, H, W).
218
219        GeoTIFF nodata cells are replaced by 0.0. When ``preload`` is set the
220        array is cached in ``_data_cache`` and returned again on later calls.
221        """
222        p_str = str(path)
223        if p_str in self._data_cache:
224            return self._data_cache[p_str]
225
226        if is_tiff:
227            with rasterio.open(path) as src:
228                arr = src.read().astype(np.float32)
229                nodata = src.nodata
230                if nodata is not None:
231                    arr[arr == nodata] = 0.0
232        else:
233            arr = np.load(path).astype(np.float32)
234            if arr.ndim == 2:
235                arr = arr[np.newaxis]
236
237        if self.preload:
238            self._data_cache[p_str] = arr
239        return arr
240
241    def _preload_data(self) -> None:
242        """Read every raster referenced by the patch index into the cache."""
243        for patch in self.patches:
244            self._read_raster(patch["state_path"], patch["use_tiff"])
245            self._read_raster(patch["next_path"], patch["use_tiff"])
246            if patch["trans_path"]:
247                self._read_raster(patch["trans_path"], True)
248            if patch["trans_next_path"]:
249                self._read_raster(patch["trans_next_path"], True)
250
251    def __len__(self) -> int:
252        """Number of patches in this split."""
253        return len(self.patches)
254
255    def __getitem__(self, idx: int) -> tuple[torch.Tensor, torch.Tensor]:
256        """Return the (input, target) pair of one patch.
257
258        The input stacks the state channels, the transmission channels and
259        the environmental channels of the patch; the target is the same
260        patch one day later. Edge patches smaller than ``patch_size`` are
261        zero-padded. Both tensors are float32.
262        """
263        patch = self.patches[idx]
264        use_tiff = patch["use_tiff"]
265        r, c = patch["row"], patch["col"]
266        ps = self.patch_size
267
268        state_full = self._read_raster(patch["state_path"], use_tiff)
269        next_full = self._read_raster(patch["next_path"], use_tiff)
270
271        state_patch = state_full[:, r:r+ps, c:c+ps]
272        next_patch = next_full[:, r:r+ps, c:c+ps]
273
274        # Pad if edge patch is smaller than patch_size
275        if state_patch.shape[-2] != ps or state_patch.shape[-1] != ps:
276            ch = state_patch.shape[0]
277            padded_s = np.zeros((ch, ps, ps), dtype=np.float32)
278            padded_s[:, :state_patch.shape[-2], :state_patch.shape[-1]] = state_patch
279            state_patch = padded_s
280
281            padded_n = np.zeros((next_patch.shape[0], ps, ps), dtype=np.float32)
282            padded_n[:, :next_patch.shape[-2], :next_patch.shape[-1]] = next_patch
283            next_patch = padded_n
284
285        # Append transmission channels if available
286        if patch["trans_path"] and patch["trans_next_path"]:
287            trans_cur = self._read_raster(patch["trans_path"], True)[:, r:r+ps, c:c+ps]
288            trans_nxt = self._read_raster(patch["trans_next_path"], True)[:, r:r+ps, c:c+ps]
289
290            if trans_cur.shape[-2] != ps or trans_cur.shape[-1] != ps:
291                tch = trans_cur.shape[0]
292                pt_c = np.zeros((tch, ps, ps), dtype=np.float32)
293                pt_c[:, :trans_cur.shape[-2], :trans_cur.shape[-1]] = trans_cur
294                trans_cur = pt_c
295
296                pt_n = np.zeros((trans_nxt.shape[0], ps, ps), dtype=np.float32)
297                pt_n[:, :trans_nxt.shape[-2], :trans_nxt.shape[-1]] = trans_nxt
298                trans_nxt = pt_n
299
300            state_patch = np.concatenate([state_patch, trans_cur], axis=0)
301            next_patch = np.concatenate([next_patch, trans_nxt], axis=0)
302
303        # Environmental channels
304        if self._env_cache is not None and self._env_cache.shape[-2] >= r+ps and self._env_cache.shape[-1] >= c+ps:
305            env_patch = self._env_cache[:, r:r+ps, c:c+ps]
306        else:
307            env_patch = np.zeros((ENV_CHANNELS, ps, ps), dtype=np.float32)
308
309        x = np.concatenate([state_patch, env_patch], axis=0)
310        return torch.from_numpy(x), torch.from_numpy(next_patch)

Patches of consecutive ABM state snapshots for surrogate training.

Reads the *_dayNNN state snapshots of a run directory, tiles them into square patches and pairs each patch with the same patch one day later, so the dataset yields (state_t + env, state_{t+1}) samples. The spatial split is fixed: patches whose left column is east of the raster mid-line belong to the validation split, the rest to training.

RolloutDataset( run_dir: str | pathlib.Path, split: Literal['train', 'val'] = 'train', patch_size: int = 128, subsample: float = 1.0, preload: bool = False, include_transmission: bool = True, env_path: str | pathlib.Path | None = None)
49    def __init__(
50        self,
51        run_dir: str | Path,
52        split: Literal["train", "val"] = "train",
53        patch_size: int = PATCH_SIZE,
54        subsample: float = 1.0,
55        preload: bool = False,
56        include_transmission: bool = True,
57        env_path: str | Path | None = None,
58    ):
59        """Index the patches of a run directory for one spatial split.
60
61        Args:
62            run_dir: directory holding the ``*_dayNNN.tif`` (or ``.npy``)
63                state snapshots and, optionally, the transmission snapshots.
64            split: ``"train"`` (west of the raster mid-line) or ``"val"``.
65            patch_size: side of the square patch in cells.
66            subsample: fraction of the selected patches to keep, in [0, 1].
67            preload: read every referenced raster into memory up front.
68            include_transmission: append the transmission channels when
69                matching snapshots exist.
70            env_path: optional NetCDF or GeoTIFF of environmental planes
71                whose channels are concatenated to the input.
72
73        Raises:
74            FileNotFoundError: no state snapshot files in ``run_dir``.
75        """
76        self.run_dir = Path(run_dir)
77        self.split = split
78        self.patch_size = patch_size
79        self.subsample = subsample
80        self.preload = preload
81        self.include_transmission = include_transmission
82        self.env_path = Path(env_path) if env_path else None
83
84        self.patches: list[dict] = []
85        self._data_cache: dict[str, np.ndarray] = {}
86        self._env_cache: np.ndarray | None = None
87
88        self._load_env_if_available()
89        self._build_patches()
90        if preload:
91            self._preload_data()

Index the patches of a run directory for one spatial split.

Args: run_dir: directory holding the *_dayNNN.tif (or .npy) state snapshots and, optionally, the transmission snapshots. split: "train" (west of the raster mid-line) or "val". patch_size: side of the square patch in cells. subsample: fraction of the selected patches to keep, in [0, 1]. preload: read every referenced raster into memory up front. include_transmission: append the transmission channels when matching snapshots exist. env_path: optional NetCDF or GeoTIFF of environmental planes whose channels are concatenated to the input.

Raises: FileNotFoundError: no state snapshot files in run_dir.

run_dir
split
patch_size
subsample
preload
include_transmission
env_path
patches: list[dict]
def get_dataloaders( run_dir: str | pathlib.Path, batch_size: int = 16, num_workers: int = 0, subsample: float = 1.0, preload: bool = False, include_transmission: bool = True, env_path: str | pathlib.Path | None = None) -> tuple[torch.utils.data.dataloader.DataLoader, torch.utils.data.dataloader.DataLoader]:
313def get_dataloaders(
314    run_dir: str | Path,
315    batch_size: int = 16,
316    num_workers: int = 0,
317    subsample: float = 1.0,
318    preload: bool = False,
319    include_transmission: bool = True,
320    env_path: str | Path | None = None,
321) -> tuple[torch.utils.data.DataLoader, torch.utils.data.DataLoader]:
322    """Build the training and validation data loaders of a run directory.
323
324    The two loaders share the same options; only the spatial split
325    differs. The training loader shuffles its batches, the validation
326    loader does not.
327    """
328    train_ds = RolloutDataset(
329        run_dir,
330        split="train",
331        subsample=subsample,
332        preload=preload,
333        include_transmission=include_transmission,
334        env_path=env_path,
335    )
336    val_ds = RolloutDataset(
337        run_dir,
338        split="val",
339        subsample=subsample,
340        preload=preload,
341        include_transmission=include_transmission,
342        env_path=env_path,
343    )
344
345    train_loader = torch.utils.data.DataLoader(
346        train_ds, batch_size=batch_size, shuffle=True, num_workers=num_workers
347    )
348    val_loader = torch.utils.data.DataLoader(
349        val_ds, batch_size=batch_size, shuffle=False, num_workers=num_workers
350    )
351
352    return train_loader, val_loader

Build the training and validation data loaders of a run directory.

The two loaders share the same options; only the spatial split differs. The training loader shuffles its batches, the validation loader does not.

def train_unet( run_dir: str | pathlib.Path, output_dir: str | pathlib.Path, epochs: int = 50, batch_size: int = 16, lr: float = 0.001, device: str | None = None, subsample: float = 1.0, preload: bool = False, include_transmission: bool = True, env_path: str | pathlib.Path | None = None) -> float:
 15def train_unet(
 16    run_dir: str | Path,
 17    output_dir: str | Path,
 18    epochs: int = 50,
 19    batch_size: int = 16,
 20    lr: float = 1e-3,
 21    device: str | None = None,
 22    subsample: float = 1.0,
 23    preload: bool = False,
 24    include_transmission: bool = True,
 25    env_path: str | Path | None = None,
 26) -> float:
 27    """Train the U-Net surrogate on the rollouts of a run directory.
 28
 29    The input and output channel counts are inferred from the first sample
 30    of the training set. Checkpoints are written to ``output_dir``: the
 31    best validation Dice score as ``best_model.pt``, a checkpoint every
 32    ten epochs and the last epoch as ``final_model.pt``; a ``model.yaml``
 33    manifest describing the model is written last.
 34
 35    Returns:
 36        The best validation Dice score reached (hard Dice on the primary
 37        channel, thresholds expressed in adult counts).
 38    """
 39    output_dir = Path(output_dir)
 40    output_dir.mkdir(parents=True, exist_ok=True)
 41
 42    if device is None:
 43        if torch.cuda.is_available():
 44            device = "cuda"
 45        elif torch.backends.mps.is_available():
 46            device = "mps"
 47        else:
 48            device = "cpu"
 49
 50    train_loader, val_loader = get_dataloaders(
 51        run_dir,
 52        batch_size=batch_size,
 53        subsample=subsample,
 54        preload=preload,
 55        include_transmission=include_transmission,
 56        env_path=env_path,
 57    )
 58
 59    if len(train_loader.dataset) == 0:
 60        raise ValueError(f"Train dataset in {run_dir} is empty. Check snapshot file paths.")
 61
 62    # Determine input / target channels from a sample
 63    sample_x, sample_y = train_loader.dataset[0]
 64    in_channels = sample_x.shape[0]
 65    out_channels = sample_y.shape[0]
 66
 67    model = UNet(in_channels=in_channels, out_channels=out_channels).to(device)
 68    optimizer = Adam(model.parameters(), lr=lr)
 69
 70    best_dice = 0.0
 71    for epoch in range(epochs):
 72        model.train()
 73        train_loss = 0.0
 74        for x, y in train_loader:
 75            x, y = x.to(device), y.to(device)
 76            pred = model(x)
 77            loss, mse_val, dice_val = combined_loss(pred, y)
 78
 79            optimizer.zero_grad()
 80            loss.backward()
 81            optimizer.step()
 82
 83            train_loss += loss.item()
 84
 85        train_loss /= max(1, len(train_loader))
 86
 87        model.eval()
 88        val_dice = 0.0
 89        if len(val_loader) > 0:
 90            with torch.no_grad():
 91                for x, y in val_loader:
 92                    x, y = x.to(device), y.to(device)
 93                    pred = model(x)
 94                    val_dice += eval_dice(pred, y)
 95            val_dice /= len(val_loader)
 96
 97        print(f"Epoch {epoch+1}/{epochs} - train_loss: {train_loss:.4f} - val_dice: {val_dice:.4f}")
 98
 99        if val_dice >= best_dice or epoch == 0:
100            best_dice = val_dice
101            torch.save(model.state_dict(), output_dir / "best_model.pt")
102
103        if (epoch + 1) % 10 == 0:
104            torch.save(model.state_dict(), output_dir / f"model_epoch_{epoch+1}.pt")
105
106    torch.save(model.state_dict(), output_dir / "final_model.pt")
107
108    # Generate model.yaml manifest for ModelRegistry compatibility
109    model_manifest = {
110        "name": output_dir.name or "unet_surrogate",
111        "version": "1.0",
112        "contract_version": "1.1",
113        "in_channels": in_channels,
114        "out_channels": out_channels,
115        "checkpoint": "best_model.pt",
116        "description": f"U-Net surrogate model trained on {run_dir} (in_ch={in_channels}, out_ch={out_channels})",
117    }
118    with open(output_dir / "model.yaml", "w") as f:
119        yaml.safe_dump(model_manifest, f)
120
121    print(f"Training complete. Best val_dice: {best_dice:.4f}. Manifest saved -> {output_dir / 'model.yaml'}")
122    return best_dice

Train the U-Net surrogate on the rollouts of a run directory.

The input and output channel counts are inferred from the first sample of the training set. Checkpoints are written to output_dir: the best validation Dice score as best_model.pt, a checkpoint every ten epochs and the last epoch as final_model.pt; a model.yaml manifest describing the model is written last.

Returns: The best validation Dice score reached (hard Dice on the primary channel, thresholds expressed in adult counts).

class UNetWrapper:
 19class UNetWrapper:
 20    """Wraps the U-Net to implement ModelProtocol for SDSS inference."""
 21
 22    def __init__(
 23        self,
 24        checkpoint_path: str | Path,
 25        device: str | None = None,
 26        in_channels: int | None = None,
 27        out_channels: int | None = None,
 28    ):
 29        """Load a trained checkpoint into a ready-to-predict U-Net.
 30
 31        The channel counts are taken from the arguments, else from the
 32        ``model.yaml`` manifest next to the checkpoint, else inferred from
 33        the shapes of the stored convolution weights. The device defaults to
 34        CUDA, then Apple MPS, then CPU.
 35        """
 36        self.checkpoint_path = Path(checkpoint_path)
 37        if device is None:
 38            if torch.cuda.is_available():
 39                self.device = "cuda"
 40            elif torch.backends.mps.is_available():
 41                self.device = "mps"
 42            else:
 43                self.device = "cpu"
 44        else:
 45            self.device = device
 46
 47        # 1. Try reading manifest model.yaml in the checkpoint directory
 48        manifest_path = self.checkpoint_path.parent / "model.yaml"
 49        if manifest_path.exists():
 50            try:
 51                with open(manifest_path) as f:
 52                    meta = yaml.safe_load(f)
 53                in_channels = in_channels or meta.get("in_channels")
 54                out_channels = out_channels or meta.get("out_channels")
 55            except Exception:
 56                pass
 57
 58        # 2. Load state dict and infer shapes if not provided
 59        state_dict = torch.load(self.checkpoint_path, map_location=self.device, weights_only=True)
 60        if in_channels is None:
 61            # enc.0.block.0.weight shape: (channels, in_channels, 3, 3)
 62            first_w = state_dict.get("enc.0.block.0.weight")
 63            in_channels = first_w.shape[1] if first_w is not None else 6
 64        if out_channels is None:
 65            # head.weight shape: (out_channels, channels, 1, 1)
 66            head_w = state_dict.get("head.weight")
 67            out_channels = head_w.shape[0] if head_w is not None else 2
 68
 69        self.in_channels = in_channels
 70        self.out_channels = out_channels
 71
 72        self.model = UNet(in_channels=in_channels, out_channels=out_channels).to(self.device)
 73        self.model.load_state_dict(state_dict)
 74        self.model.eval()
 75
 76    @torch.no_grad()
 77    def predict(self, state: np.ndarray, env: np.ndarray) -> np.ndarray:
 78        """Predict state_{t+1} from state_t + env.
 79
 80        Args:
 81            state: (C_state, H, W) float32
 82            env: (C_env, H, W) float32
 83
 84        Returns:
 85            prediction: (C_out, H, W) float32
 86        """
 87        # Ensure correct channel alignment
 88        total_ch = state.shape[0] + env.shape[0]
 89        if total_ch < self.in_channels:
 90            missing = self.in_channels - total_ch
 91            pad_ch = np.zeros((missing, state.shape[1], state.shape[2]), dtype=np.float32)
 92            x = np.concatenate([state, env, pad_ch], axis=0)
 93        elif total_ch > self.in_channels:
 94            x = np.concatenate([state, env], axis=0)[:self.in_channels]
 95        else:
 96            x = np.concatenate([state, env], axis=0)
 97
 98        orig_h, orig_w = x.shape[-2], x.shape[-1]
 99
100        # Pad to multiple of 16 for UNet 4-stage pooling
101        pad_h = (16 - (orig_h % 16)) % 16
102        pad_w = (16 - (orig_w % 16)) % 16
103
104        x_tensor = torch.from_numpy(x).unsqueeze(0).to(self.device)
105        if pad_h > 0 or pad_w > 0:
106            x_tensor = F.pad(x_tensor, (0, pad_w, 0, pad_h), mode="replicate")
107
108        pred = self.model(x_tensor)
109
110        # Crop back to original dimensions
111        if pad_h > 0 or pad_w > 0:
112            pred = pred[:, :, :orig_h, :orig_w]
113
114        return pred.squeeze(0).cpu().numpy().astype(np.float32)

Wraps the U-Net to implement ModelProtocol for SDSS inference.

UNetWrapper( checkpoint_path: str | pathlib.Path, device: str | None = None, in_channels: int | None = None, out_channels: int | None = None)
22    def __init__(
23        self,
24        checkpoint_path: str | Path,
25        device: str | None = None,
26        in_channels: int | None = None,
27        out_channels: int | None = None,
28    ):
29        """Load a trained checkpoint into a ready-to-predict U-Net.
30
31        The channel counts are taken from the arguments, else from the
32        ``model.yaml`` manifest next to the checkpoint, else inferred from
33        the shapes of the stored convolution weights. The device defaults to
34        CUDA, then Apple MPS, then CPU.
35        """
36        self.checkpoint_path = Path(checkpoint_path)
37        if device is None:
38            if torch.cuda.is_available():
39                self.device = "cuda"
40            elif torch.backends.mps.is_available():
41                self.device = "mps"
42            else:
43                self.device = "cpu"
44        else:
45            self.device = device
46
47        # 1. Try reading manifest model.yaml in the checkpoint directory
48        manifest_path = self.checkpoint_path.parent / "model.yaml"
49        if manifest_path.exists():
50            try:
51                with open(manifest_path) as f:
52                    meta = yaml.safe_load(f)
53                in_channels = in_channels or meta.get("in_channels")
54                out_channels = out_channels or meta.get("out_channels")
55            except Exception:
56                pass
57
58        # 2. Load state dict and infer shapes if not provided
59        state_dict = torch.load(self.checkpoint_path, map_location=self.device, weights_only=True)
60        if in_channels is None:
61            # enc.0.block.0.weight shape: (channels, in_channels, 3, 3)
62            first_w = state_dict.get("enc.0.block.0.weight")
63            in_channels = first_w.shape[1] if first_w is not None else 6
64        if out_channels is None:
65            # head.weight shape: (out_channels, channels, 1, 1)
66            head_w = state_dict.get("head.weight")
67            out_channels = head_w.shape[0] if head_w is not None else 2
68
69        self.in_channels = in_channels
70        self.out_channels = out_channels
71
72        self.model = UNet(in_channels=in_channels, out_channels=out_channels).to(self.device)
73        self.model.load_state_dict(state_dict)
74        self.model.eval()

Load a trained checkpoint into a ready-to-predict U-Net.

The channel counts are taken from the arguments, else from the model.yaml manifest next to the checkpoint, else inferred from the shapes of the stored convolution weights. The device defaults to CUDA, then Apple MPS, then CPU.

checkpoint_path
in_channels
out_channels
model
@torch.no_grad()
def predict(self, state: numpy.ndarray, env: numpy.ndarray) -> numpy.ndarray:
 76    @torch.no_grad()
 77    def predict(self, state: np.ndarray, env: np.ndarray) -> np.ndarray:
 78        """Predict state_{t+1} from state_t + env.
 79
 80        Args:
 81            state: (C_state, H, W) float32
 82            env: (C_env, H, W) float32
 83
 84        Returns:
 85            prediction: (C_out, H, W) float32
 86        """
 87        # Ensure correct channel alignment
 88        total_ch = state.shape[0] + env.shape[0]
 89        if total_ch < self.in_channels:
 90            missing = self.in_channels - total_ch
 91            pad_ch = np.zeros((missing, state.shape[1], state.shape[2]), dtype=np.float32)
 92            x = np.concatenate([state, env, pad_ch], axis=0)
 93        elif total_ch > self.in_channels:
 94            x = np.concatenate([state, env], axis=0)[:self.in_channels]
 95        else:
 96            x = np.concatenate([state, env], axis=0)
 97
 98        orig_h, orig_w = x.shape[-2], x.shape[-1]
 99
100        # Pad to multiple of 16 for UNet 4-stage pooling
101        pad_h = (16 - (orig_h % 16)) % 16
102        pad_w = (16 - (orig_w % 16)) % 16
103
104        x_tensor = torch.from_numpy(x).unsqueeze(0).to(self.device)
105        if pad_h > 0 or pad_w > 0:
106            x_tensor = F.pad(x_tensor, (0, pad_w, 0, pad_h), mode="replicate")
107
108        pred = self.model(x_tensor)
109
110        # Crop back to original dimensions
111        if pad_h > 0 or pad_w > 0:
112            pred = pred[:, :, :orig_h, :orig_w]
113
114        return pred.squeeze(0).cpu().numpy().astype(np.float32)

Predict state_{t+1} from state_t + env.

Args: state: (C_state, H, W) float32 env: (C_env, H, W) float32

Returns: prediction: (C_out, H, W) float32

def make_aoi(slug: str, scale: mal_commonlib.Scale) -> mal_commonlib.AOI:
34def make_aoi(slug: str, scale: Scale) -> AOI:
35    """Build an AOI from the YAML registry, overriding resolution for the scale."""
36    aoi = AOI.from_slug(slug)
37    grid = SCALE_GRIDS[scale]
38    return AOI(
39        slug=aoi.slug,
40        name=aoi.name,
41        bbox=aoi.bbox,
42        crs=aoi.crs,
43        resolution_m=grid.resolution_m,
44        scale=scale,
45        gadm_id=aoi.gadm_id,
46    )

Build an AOI from the YAML registry, overriding resolution for the scale.

def get_aggregator( scale: mal_commonlib.Scale) -> mal_core.prediction.aggregator.Aggregator:
85def get_aggregator(scale: Scale) -> Aggregator:
86    """The aggregator that belongs to a scale."""
87    return {
88        Scale.REGIONAL: RegionalAggregator(),
89        Scale.NATIONAL: NationalAggregator(),
90        Scale.CONTINENTAL: ContinentalAggregator(),
91    }[scale]

The aggregator that belongs to a scale.

def grid_shape(aoi: mal_commonlib.AOI) -> tuple[int, int]:
94def grid_shape(aoi: AOI) -> tuple[int, int]:
95    """The height and width in cells of an AOI's grid."""
96    h, w = aoi.cells_per_side()
97    return h, w

The height and width in cells of an AOI's grid.

class RegionalAggregator:
56class RegionalAggregator:
57    """The regional scale's aggregator: the raster is kept at its cell resolution."""
58    def aggregate(self, raster: np.ndarray, aoi: AOI) -> np.ndarray:
59        """Return the raster unchanged, keeping one value per cell."""
60        return raster

The regional scale's aggregator: the raster is kept at its cell resolution.

def aggregate(self, raster: numpy.ndarray, aoi: mal_commonlib.AOI) -> numpy.ndarray:
58    def aggregate(self, raster: np.ndarray, aoi: AOI) -> np.ndarray:
59        """Return the raster unchanged, keeping one value per cell."""
60        return raster

Return the raster unchanged, keeping one value per cell.

class NationalAggregator:
63class NationalAggregator:
64    """The national scale's aggregator: the raster is mean-pooled into coarse blocks."""
65    def aggregate(self, raster: np.ndarray, aoi: AOI) -> np.ndarray:
66        """Mean-pool the raster into blocks of ten by ten cells, dropping the trailing rows and columns that do not fill a block."""
67        h, w = raster.shape[-2:]
68        n_rows, n_cols = max(1, h // 10), max(1, w // 10)
69        block_h = h // n_rows
70        block_w = w // n_cols
71        trimmed = raster[..., : block_h * n_rows, : block_w * n_cols]
72        reshaped = trimmed.reshape(
73            *raster.shape[:-2], n_rows, block_h, n_cols, block_w
74        )
75        return reshaped.mean(axis=(-3, -1))

The national scale's aggregator: the raster is mean-pooled into coarse blocks.

def aggregate(self, raster: numpy.ndarray, aoi: mal_commonlib.AOI) -> numpy.ndarray:
65    def aggregate(self, raster: np.ndarray, aoi: AOI) -> np.ndarray:
66        """Mean-pool the raster into blocks of ten by ten cells, dropping the trailing rows and columns that do not fill a block."""
67        h, w = raster.shape[-2:]
68        n_rows, n_cols = max(1, h // 10), max(1, w // 10)
69        block_h = h // n_rows
70        block_w = w // n_cols
71        trimmed = raster[..., : block_h * n_rows, : block_w * n_cols]
72        reshaped = trimmed.reshape(
73            *raster.shape[:-2], n_rows, block_h, n_cols, block_w
74        )
75        return reshaped.mean(axis=(-3, -1))

Mean-pool the raster into blocks of ten by ten cells, dropping the trailing rows and columns that do not fill a block.

class ContinentalAggregator:
78class ContinentalAggregator:
79    """The continental scale's aggregator: the raster is reduced to a country-level scalar."""
80    def aggregate(self, raster: np.ndarray, aoi: AOI) -> np.ndarray:
81        """Reduce the whole raster to a single country-level value."""
82        return np.array([float(raster.mean())])

The continental scale's aggregator: the raster is reduced to a country-level scalar.

def aggregate(self, raster: numpy.ndarray, aoi: mal_commonlib.AOI) -> numpy.ndarray:
80    def aggregate(self, raster: np.ndarray, aoi: AOI) -> np.ndarray:
81        """Reduce the whole raster to a single country-level value."""
82        return np.array([float(raster.mean())])

Reduce the whole raster to a single country-level value.

class ScenarioConfig(pydantic.main.BaseModel):
42class ScenarioConfig(BaseModel):
43    """A complete what-if scenario: the AOI and scale, the year and month, the interventions and the climate perturbations."""
44    aoi: str
45    scale: Scale = Scale.REGIONAL
46    year: int = Field(ge=2000, le=2100)
47    month: int = Field(default=1, ge=1, le=12)
48    interventions: list[InterventionConfig] = Field(default_factory=list)
49    climate: ClimateConfig = Field(default_factory=ClimateConfig)

A complete what-if scenario: the AOI and scale, the year and month, the interventions and the climate perturbations.

aoi: str = PydanticUndefined
scale: mal_commonlib.Scale = <Scale.REGIONAL: 'regional'>
year: int = PydanticUndefined
month: int = 1
interventions: list[InterventionConfig] = PydanticUndefined
climate: ClimateConfig = PydanticUndefined
class InterventionConfig(pydantic.main.BaseModel):
19class InterventionConfig(BaseModel):
20    """One public-health intervention in a scenario: its type and the population coverage it reaches, a fraction in [0, 1]."""
21    type: str
22    coverage: float = Field(ge=0.0, le=1.0)
23
24    @field_validator("type")
25    @classmethod
26    def _valid_type(cls, v: str) -> str:
27        """Accept only the intervention types the engine implements."""
28        allowed = {"bednets", "irs", "larviciding", "drug_campaign", "vaccine"}
29        if v not in allowed:
30            raise ValueError(f"intervention type must be one of {allowed}; got {v!r}")
31        return v

One public-health intervention in a scenario: its type and the population coverage it reaches, a fraction in [0, 1].

type: str = PydanticUndefined
coverage: float = PydanticUndefined
class ClimateConfig(pydantic.main.BaseModel):
34class ClimateConfig(BaseModel):
35    """The climate perturbations of a scenario: rainfall and temperature anomalies and multipliers for evaporation and washout."""
36    rainfall_anomaly: float = Field(default=0.0, ge=-1.0, le=1.0)
37    temperature_anomaly: float = Field(default=0.0, ge=-5.0, le=5.0)
38    evaporation_multiplier: float = Field(default=1.0, ge=0.0, le=2.0)
39    washout_multiplier: float = Field(default=1.0, ge=0.0, le=2.0)

The climate perturbations of a scenario: rainfall and temperature anomalies and multipliers for evaporation and washout.

rainfall_anomaly: float = 0.0
temperature_anomaly: float = 0.0
evaporation_multiplier: float = 1.0
washout_multiplier: float = 1.0
def load_scenario(path: pathlib.Path | str) -> ScenarioConfig:
61def load_scenario(path: Path | str) -> ScenarioConfig:
62    """Read and validate a scenario YAML file, accepting either a bare scenario block or one nested under a ``scenario`` key."""
63    p = Path(path)
64    raw = yaml.safe_load(p.read_text())
65    if "scenario" in raw:
66        raw = raw["scenario"]
67    return ScenarioConfig.model_validate(raw)

Read and validate a scenario YAML file, accepting either a bare scenario block or one nested under a scenario key.

def interventions_to_params(scenario: ScenarioConfig) -> dict[str, typing.Any]:
70def interventions_to_params(scenario: ScenarioConfig) -> dict[str, Any]:
71    """Translate a scenario into the multiplier parameters the engine consumes: intervention effects scaled by coverage, plus the climate terms."""
72    params: dict[str, Any] = {}
73    for iv in scenario.interventions:
74        effects = INTERVENTION_EFFECTS.get(iv.type, {})
75        for key, value in effects.items():
76            params[key] = params.get(key, 1.0) * (1.0 - iv.coverage * (1.0 - value))
77    params["rainfall_multiplier"] = 1.0 + scenario.climate.rainfall_anomaly
78    params["temperature_offset"] = scenario.climate.temperature_anomaly
79    params["evaporation_multiplier"] = scenario.climate.evaporation_multiplier
80    params["washout_multiplier"] = scenario.climate.washout_multiplier
81    return params

Translate a scenario into the multiplier parameters the engine consumes: intervention effects scaled by coverage, plus the climate terms.

class ModelRegistry:
 56class ModelRegistry:
 57    """Catalogue of the models available on disk, discovered from the ``model.yaml`` manifests of their directories."""
 58    def __init__(self, models_dir: Path | None = None):
 59        """Create a registry over the given models directory, defaulting to the runs directory."""
 60        self.models_dir = models_dir or (RUNS_DIR / "models")
 61        self._entries: dict[str, RegistryEntry] = {}
 62
 63    def scan(self) -> list[str]:
 64        """Search the model directories for manifests and return the keys found, as ``name@version``."""
 65        self._entries.clear()
 66        search_dirs = [self.models_dir, RUNS_DIR]
 67        found = []
 68
 69        for base in search_dirs:
 70            if not base.exists():
 71                continue
 72            for manifest_path in sorted(base.rglob("model.yaml")):
 73                try:
 74                    raw = yaml.safe_load(manifest_path.read_text())
 75                    manifest = ModelManifest.model_validate(raw)
 76                    key = f"{manifest.name}@{manifest.version}"
 77                    if key not in self._entries:
 78                        self._entries[key] = RegistryEntry(manifest=manifest, path=manifest_path.parent)
 79                        found.append(key)
 80                except Exception:
 81                    continue
 82
 83        return found
 84
 85    def get(self, name: str, version: str | None = None) -> RegistryEntry:
 86        """The registry entry for a model name and, optionally, a version; raises ``KeyError`` when no such model is registered."""
 87        if not self._entries:
 88            self.scan()
 89
 90        if version:
 91            key = f"{name}@{version}"
 92        else:
 93            matches = [k for k in self._entries if k.startswith(f"{name}@")]
 94            if not matches:
 95                # Try fallback matching name directly
 96                if name in self._entries:
 97                    key = name
 98                else:
 99                    raise KeyError(f"Model {name!r} not found in {self.models_dir} or {RUNS_DIR}")
100            else:
101                key = matches[-1]
102
103        if key not in self._entries:
104            raise KeyError(f"Model {key!r} not found in {self.models_dir}")
105        return self._entries[key]
106
107    def load(self, name: str, version: str | None = None) -> ModelProtocol:
108        """The runnable model for a name and version, loading its checkpoint on first use; raises ``FileNotFoundError`` when the checkpoint is missing."""
109        if name == "dummy":
110            return DummyModel()
111
112        entry = self.get(name, version)
113        if entry.model is not None:
114            return entry.model
115
116        if entry.manifest.checkpoint:
117            from ..training.wrapper import UNetWrapper
118            ckpt = entry.path / entry.manifest.checkpoint
119            if not ckpt.exists():
120                raise FileNotFoundError(
121                    f"Checkpoint not found: {ckpt} (model {name}@{entry.manifest.version})"
122                )
123            entry.model = UNetWrapper(
124                ckpt,
125                in_channels=entry.manifest.in_channels,
126                out_channels=entry.manifest.out_channels,
127            )
128        else:
129            entry.model = DummyModel()
130        return entry.model
131
132    def list_models(self) -> list[dict[str, str]]:
133        """The catalogue as a list of dicts holding each model's name, version and directory."""
134        if not self._entries:
135            self.scan()
136        return [
137            {"name": e.manifest.name, "version": e.manifest.version, "path": str(e.path)}
138            for e in self._entries.values()
139        ]

Catalogue of the models available on disk, discovered from the model.yaml manifests of their directories.

ModelRegistry(models_dir: pathlib.Path | None = None)
58    def __init__(self, models_dir: Path | None = None):
59        """Create a registry over the given models directory, defaulting to the runs directory."""
60        self.models_dir = models_dir or (RUNS_DIR / "models")
61        self._entries: dict[str, RegistryEntry] = {}

Create a registry over the given models directory, defaulting to the runs directory.

models_dir
def scan(self) -> list[str]:
63    def scan(self) -> list[str]:
64        """Search the model directories for manifests and return the keys found, as ``name@version``."""
65        self._entries.clear()
66        search_dirs = [self.models_dir, RUNS_DIR]
67        found = []
68
69        for base in search_dirs:
70            if not base.exists():
71                continue
72            for manifest_path in sorted(base.rglob("model.yaml")):
73                try:
74                    raw = yaml.safe_load(manifest_path.read_text())
75                    manifest = ModelManifest.model_validate(raw)
76                    key = f"{manifest.name}@{manifest.version}"
77                    if key not in self._entries:
78                        self._entries[key] = RegistryEntry(manifest=manifest, path=manifest_path.parent)
79                        found.append(key)
80                except Exception:
81                    continue
82
83        return found

Search the model directories for manifests and return the keys found, as name@version.

def get( self, name: str, version: str | None = None) -> mal_core.prediction.registry.RegistryEntry:
 85    def get(self, name: str, version: str | None = None) -> RegistryEntry:
 86        """The registry entry for a model name and, optionally, a version; raises ``KeyError`` when no such model is registered."""
 87        if not self._entries:
 88            self.scan()
 89
 90        if version:
 91            key = f"{name}@{version}"
 92        else:
 93            matches = [k for k in self._entries if k.startswith(f"{name}@")]
 94            if not matches:
 95                # Try fallback matching name directly
 96                if name in self._entries:
 97                    key = name
 98                else:
 99                    raise KeyError(f"Model {name!r} not found in {self.models_dir} or {RUNS_DIR}")
100            else:
101                key = matches[-1]
102
103        if key not in self._entries:
104            raise KeyError(f"Model {key!r} not found in {self.models_dir}")
105        return self._entries[key]

The registry entry for a model name and, optionally, a version; raises KeyError when no such model is registered.

def load( self, name: str, version: str | None = None) -> mal_core.prediction.registry.ModelProtocol:
107    def load(self, name: str, version: str | None = None) -> ModelProtocol:
108        """The runnable model for a name and version, loading its checkpoint on first use; raises ``FileNotFoundError`` when the checkpoint is missing."""
109        if name == "dummy":
110            return DummyModel()
111
112        entry = self.get(name, version)
113        if entry.model is not None:
114            return entry.model
115
116        if entry.manifest.checkpoint:
117            from ..training.wrapper import UNetWrapper
118            ckpt = entry.path / entry.manifest.checkpoint
119            if not ckpt.exists():
120                raise FileNotFoundError(
121                    f"Checkpoint not found: {ckpt} (model {name}@{entry.manifest.version})"
122                )
123            entry.model = UNetWrapper(
124                ckpt,
125                in_channels=entry.manifest.in_channels,
126                out_channels=entry.manifest.out_channels,
127            )
128        else:
129            entry.model = DummyModel()
130        return entry.model

The runnable model for a name and version, loading its checkpoint on first use; raises FileNotFoundError when the checkpoint is missing.

def list_models(self) -> list[dict[str, str]]:
132    def list_models(self) -> list[dict[str, str]]:
133        """The catalogue as a list of dicts holding each model's name, version and directory."""
134        if not self._entries:
135            self.scan()
136        return [
137            {"name": e.manifest.name, "version": e.manifest.version, "path": str(e.path)}
138            for e in self._entries.values()
139        ]

The catalogue as a list of dicts holding each model's name, version and directory.

class ModelManifest(pydantic.main.BaseModel):
28class ModelManifest(BaseModel):
29    """The contents of a model directory's ``model.yaml``: its identity, its channel counts and the checkpoint it uses."""
30    name: str
31    version: str = "1.0"
32    contract_version: str = "1.1"
33    in_channels: int = 10
34    out_channels: int = 6
35    checkpoint: str = ""
36    description: str = ""

The contents of a model directory's model.yaml: its identity, its channel counts and the checkpoint it uses.

name: str = PydanticUndefined
version: str = '1.0'
contract_version: str = '1.1'
in_channels: int = 10
out_channels: int = 6
checkpoint: str = ''
description: str = ''
class DummyModel:
47class DummyModel:
48    """Placeholder model used when no trained checkpoint is available."""
49    def predict(self, state: np.ndarray, env: np.ndarray) -> np.ndarray:
50        """Return an all-zero raster with one band per state channel."""
51        out_ch = state.shape[0]
52        h, w = state.shape[-2:]
53        return np.zeros((out_ch, h, w), dtype=np.float32)

Placeholder model used when no trained checkpoint is available.

def predict(self, state: numpy.ndarray, env: numpy.ndarray) -> numpy.ndarray:
49    def predict(self, state: np.ndarray, env: np.ndarray) -> np.ndarray:
50        """Return an all-zero raster with one band per state channel."""
51        out_ch = state.shape[0]
52        h, w = state.shape[-2:]
53        return np.zeros((out_ch, h, w), dtype=np.float32)

Return an all-zero raster with one band per state channel.

def run_prediction( aoi_slug: str, scale: mal_commonlib.Scale = <Scale.REGIONAL: 'regional'>, year: int = 2026, month: int = 1, model_name: str = 'dummy', model_version: str | None = None, scenario: ScenarioConfig | None = None, output_dir: pathlib.Path | None = None, rollout_dir: pathlib.Path | None = None) -> pathlib.Path:
 68def run_prediction(
 69    aoi_slug: str,
 70    scale: Scale = Scale.REGIONAL,
 71    year: int = 2026,
 72    month: int = 1,
 73    model_name: str = "dummy",
 74    model_version: str | None = None,
 75    scenario: ScenarioConfig | None = None,
 76    output_dir: Path | None = None,
 77    rollout_dir: Path | None = None,
 78) -> Path:
 79    """Run the prediction for one AOI and month and write the result as a GeoTIFF with its sidecar, returning the GeoTIFF's path."""
 80    aoi = make_aoi(aoi_slug, scale)
 81    h, w = grid_shape(aoi)
 82
 83    registry = ModelRegistry()
 84    model = registry.load(model_name, model_version)
 85
 86    # Use real ABM state + env stack; fall back to zeros if unavailable
 87    state, env = _load_real_inputs(aoi, month, rollout_dir=rollout_dir)
 88
 89    if scenario is not None:
 90        params = interventions_to_params(scenario)
 91
 92    prediction = model.predict(state, env)
 93
 94    aggregator = get_aggregator(scale)
 95    aggregated = aggregator.aggregate(prediction, aoi)
 96
 97    out_dir = output_dir or (RUNS_DIR / "predictions")
 98    out_dir.mkdir(parents=True, exist_ok=True)
 99
100    fname = f"{aoi_slug}_{scale.value}_{year}_{month:02d}_risk.tif"
101    out_path = out_dir / fname
102
103    transform = from_bounds(aoi.bbox[0], aoi.bbox[1], aoi.bbox[2], aoi.bbox[3], w, h)
104
105    if aggregated.ndim == 0:
106        aggregated = aggregated.reshape(1, 1, 1)
107    elif aggregated.ndim == 1:
108        side = int(np.ceil(np.sqrt(aggregated.size)))
109        padded = np.zeros((1, side, side), dtype=np.float32)
110        padded.flat[: aggregated.size] = aggregated
111        aggregated = padded
112    elif aggregated.ndim == 2:
113        aggregated = aggregated[np.newaxis]
114
115    n_bands = aggregated.shape[0]
116    profile = {
117        "driver": "GTiff",
118        "dtype": "float32",
119        "count": n_bands,
120        "height": aggregated.shape[-2],
121        "width": aggregated.shape[-1],
122        "crs": aoi.crs,
123        "transform": transform,
124        "nodata": float(CONFIG["ingest"]["nodata_sentinel"]),
125        "tiled": True,
126        "compress": "deflate",
127        "blockxsize": 128,
128        "blockysize": 128,
129    }
130    with rasterio.open(str(out_path), "w", **profile) as dst:
131        dst.write(aggregated.astype(np.float32))
132        band_names = BAND_NAMES_MAP.get(n_bands, [f"band_{i+1}" for i in range(n_bands)])
133        for b_idx, b_name in enumerate(band_names, start=1):
134            if b_idx <= n_bands:
135                dst.set_band_description(b_idx, b_name)
136
137    sidecar = {
138        "crs": aoi.crs,
139        "transform": list(transform)[:6],
140        "aoi_slug": aoi_slug,
141        "scale": scale.value,
142        "year": year,
143        "month": month,
144        "bands": band_names[:n_bands],
145        "model_name": model_name,
146        "model_version": model_version or "latest",
147        "contract_version": "1.1",
148        "generator_version": "mal-execution-0.1.0",
149    }
150    sidecar_path = out_path.with_suffix(".tif.json")
151    sidecar_path.write_text(json.dumps(sidecar, indent=2))
152
153    return out_path

Run the prediction for one AOI and month and write the result as a GeoTIFF with its sidecar, returning the GeoTIFF's path.

def get_latest_prediction(aoi_slug: str) -> pathlib.Path | None:
156def get_latest_prediction(aoi_slug: str) -> Path | None:
157    """Path of the most recent prediction GeoTIFF for an AOI, or ``None`` when it has none."""
158    pred_dir = RUNS_DIR / "predictions"
159    if not pred_dir.exists():
160        return None
161    matches = sorted(pred_dir.glob(f"{aoi_slug}_*_risk.tif"))
162    return matches[-1] if matches else None

Path of the most recent prediction GeoTIFF for an AOI, or None when it has none.

def get_prediction_metadata(aoi_slug: str) -> dict | None:
165def get_prediction_metadata(aoi_slug: str) -> dict | None:
166    """The sidecar metadata of the most recent prediction for an AOI, or ``None`` when it has none."""
167    latest = get_latest_prediction(aoi_slug)
168    if latest is None:
169        return None
170    sidecar_path = latest.with_suffix(".tif.json")
171    if sidecar_path.exists():
172        return json.loads(sidecar_path.read_text())
173    return {"path": str(latest)}

The sidecar metadata of the most recent prediction for an AOI, or None when it has none.

fastapi_app = <fastapi.applications.FastAPI object>
def cli_main() -> None:
896def main() -> None:
897    """Entry point of the ``malariasim`` console script: runs the Typer application."""
898    app()

Entry point of the malariasim console script: runs the Typer application.