mal_core.prediction
Prediction subpackage — model inference, registry, data loaders.
1"""Prediction subpackage — model inference, registry, data loaders.""" 2from .predictor import run_prediction, get_latest_prediction, get_prediction_metadata 3from .registry import ModelRegistry, ModelManifest, DummyModel 4from .aggregator import make_aoi, get_aggregator, grid_shape, RegionalAggregator, NationalAggregator, ContinentalAggregator 5 6__all__ = ["run_prediction", "get_latest_prediction", "get_prediction_metadata", "ModelRegistry", "ModelManifest", "DummyModel", "make_aoi", "get_aggregator", "grid_shape", "RegionalAggregator", "NationalAggregator", "ContinentalAggregator"]
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.