mal_commonlib
MalariaSentinel — shared utilities, config, and paths.
65class AOI(BaseModel): 66 """Area of Interest — region-agnostic from M1. 67 68 The AOI is a typed parameter; the data layer and the ABM consume 69 bbox + CRS + scale + slug. No hardcoded Ghana logic. 70 71 Attributes: 72 slug: stable identifier used in file naming (e.g. "ghana", "mozambique"). 73 Lowercase, [a-z0-9-], no leading/trailing hyphens, no consecutive hyphens. 74 name: human-readable name (e.g. "Ghana NMCP AOI"). 75 bbox: (west, south, east, north) in CRS units. For EPSG:4326, west<east and south<north. 76 crs: EPSG code or WKT. Must be parseable by pyproj.CRS.from_user_input. 77 resolution_m: cell size in metres on the ground. For EPSG:4326, used to 78 derive degree-per-cell via the AOI centroid latitude. 79 scale: REGIONAL/NATIONAL/CONTINENTAL — see ``Scale`` enum. 80 gadm_id: optional GADM identifier (e.g. "GHA" for Ghana, "GHA.1_1" for region). 81 When set, ``from_gadm()`` can be used to populate bbox from GADM boundaries. 82 iso3: ISO 3166-1 alpha-3 country code (e.g. "GHA"). Required for country-scoped 83 data loaders (WorldPop, GADM, livestock); raises ValueError if absent when 84 needed. Always lowercase, exactly 3 letters. 85 """ 86 87 slug: str = Field(..., min_length=1, max_length=64) 88 name: str 89 bbox: tuple[float, float, float, float] 90 crs: str 91 resolution_m: int = Field(..., gt=0) 92 scale: Scale = Scale.REGIONAL 93 gadm_id: str | None = None 94 iso3: str | None = None 95 96 model_config = {"frozen": True} 97 98 # -- validators ----------------------------------------------------------- 99 100 @field_validator("slug") 101 @classmethod 102 def _slug_format(cls, v: str) -> str: 103 """Reject slugs that are not lowercase alphanumeric words joined by single hyphens.""" 104 if not re.fullmatch(r"[a-z0-9]+(-[a-z0-9]+)*", v): 105 raise ValueError( 106 f"slug must be lowercase [a-z0-9-], no leading/trailing/consecutive hyphens; got {v!r}" 107 ) 108 return v 109 110 @field_validator("iso3") 111 @classmethod 112 def _iso3_format(cls, v: str | None) -> str | None: 113 """Normalise an ISO 3166-1 alpha-3 code to uppercase and reject codes that are not three letters.""" 114 if v is None: 115 return v 116 v = v.strip().upper() 117 if not re.fullmatch(r"[A-Z]{3}", v): 118 raise ValueError( 119 f"iso3 must be 3 letters (ISO 3166-1 alpha-3); got {v!r}" 120 ) 121 return v 122 123 @field_validator("bbox") 124 @classmethod 125 def _bbox_order(cls, v: tuple[float, float, float, float]) -> tuple[float, float, float, float]: 126 """Reject a bbox whose west/east or south/north edges are not strictly increasing.""" 127 w, s, e, n = v 128 if not (w < e and s < n): 129 raise ValueError(f"bbox must satisfy west<east and south<north; got {v!r}") 130 return v 131 132 @field_validator("crs") 133 @classmethod 134 def _crs_parseable(cls, v: str) -> str: 135 """Reject a CRS string that pyproj cannot parse into a CRS.""" 136 try: 137 pyproj.CRS.from_user_input(v) 138 except Exception as e: 139 raise ValueError(f"crs not parseable by pyproj: {v!r} ({e})") from e 140 return v 141 142 # -- geometry helpers ---------------------------------------------------- 143 144 @property 145 def crs_obj(self) -> pyproj.CRS: 146 """Parsed CRS as a ``pyproj.CRS`` object.""" 147 return pyproj.CRS.from_user_input(self.crs) 148 149 @property 150 def _is_geographic(self) -> bool: 151 """True when the AOI CRS is geographic (units in degrees), False when it is projected.""" 152 return self.crs_obj.is_geographic 153 154 @property 155 def _centroid_lat(self) -> float: 156 """Centroid latitude in degrees (geographic CRS) or None for projected.""" 157 _, s, _, n = self.bbox 158 return 0.5 * (s + n) 159 160 def _m_per_unit(self) -> tuple[float, float]: 161 """Approximate (m_per_unit_x, m_per_unit_y) at the AOI centroid. 162 163 Geographic CRS → great-circle metres per degree. Projected CRS → CRS linear units. 164 """ 165 if self._is_geographic: 166 lat_rad = math.radians(self._centroid_lat) 167 m_per_deg_lat = (math.pi * _EARTH_R) / 180.0 168 m_per_deg_lon = m_per_deg_lat * math.cos(lat_rad) 169 return m_per_deg_lon, m_per_deg_lat 170 # Projected: assume linear units are metres (UTM, etc.). The CRS conversion factor 171 # is reported by pyproj; fall back to 1.0 if unknown. 172 cf = self.crs_obj.coordinate_system 173 try: 174 unit_m = float(cf.unit_conversion_factor) if cf is not None and cf.unit_conversion_factor else 1.0 175 except (AttributeError, TypeError): 176 unit_m = 1.0 177 return unit_m, unit_m 178 179 @property 180 def width_m(self) -> float: 181 """East-west extent of the bounding box in metres.""" 182 w, _, e, _ = self.bbox 183 m_per_x, _ = self._m_per_unit() 184 return abs(e - w) * m_per_x 185 186 @property 187 def height_m(self) -> float: 188 """North-south extent of the bounding box in metres.""" 189 _, s, _, n = self.bbox 190 _, m_per_y = self._m_per_unit() 191 return abs(n - s) * m_per_y 192 193 @property 194 def area_km2(self) -> float: 195 """Area of the bounding box in square kilometres, from width_m times height_m.""" 196 return (self.width_m * self.height_m) / 1_000_000.0 197 198 @property 199 def geom(self) -> shapely.geometry.Polygon: 200 """Bounding box as a shapely Polygon in ``self.crs``.""" 201 w, s, e, n = self.bbox 202 return shapely.geometry.box(w, s, e, n) 203 204 def cells_per_side(self) -> tuple[int, int]: 205 """(H, W) cells needed to cover the bbox at ``resolution_m`` (rounded up).""" 206 h = int(math.ceil(self.height_m / self.resolution_m)) 207 w = int(math.ceil(self.width_m / self.resolution_m)) 208 return h, w 209 210 def to_geoseries(self, crs: str | None = None) -> gpd.GeoSeries: 211 """Bounding box as a ``GeoSeries``. ``crs`` defaults to ``self.crs``.""" 212 return gpd.GeoSeries([self.geom], crs=crs if crs is not None else self.crs) 213 214 # -- I/O ----------------------------------------------------------------- 215 216 def to_file(self, path: Path | str) -> Path: 217 """Serialize to JSON. Returns the written path.""" 218 p = Path(path) 219 payload = { 220 "slug": self.slug, 221 "name": self.name, 222 "bbox": list(self.bbox), 223 "crs": self.crs, 224 "resolution_m": self.resolution_m, 225 "scale": self.scale.value, 226 "gadm_id": self.gadm_id, 227 "iso3": self.iso3, 228 } 229 p.parent.mkdir(parents=True, exist_ok=True) 230 p.write_text(json.dumps(payload, indent=2)) 231 return p 232 233 @classmethod 234 def from_file(cls, path: Path | str) -> "AOI": 235 """Inverse of ``to_file``.""" 236 p = Path(path) 237 payload = json.loads(p.read_text()) 238 return cls( 239 slug=payload["slug"], 240 name=payload["name"], 241 bbox=tuple(payload["bbox"]), 242 crs=payload["crs"], 243 resolution_m=int(payload["resolution_m"]), 244 scale=Scale(payload["scale"]), 245 gadm_id=payload.get("gadm_id"), 246 iso3=payload.get("iso3"), 247 ) 248 249 # -- constructors -------------------------------------------------------- 250 251 @classmethod 252 def from_bbox( 253 cls, 254 west: float, south: float, east: float, north: float, 255 crs: str, slug: str, resolution_m: int, 256 *, 257 name: str | None = None, 258 scale: Scale = Scale.REGIONAL, 259 iso3: str | None = None, 260 gadm_id: str | None = None, 261 ) -> "AOI": 262 """Build an AOI from an explicit bbox. 263 264 Args: 265 iso3: ISO 3166-1 alpha-3 country code (e.g. "GHA"). Required to use 266 country-scoped loaders (WorldPop, GADM, livestock); can be set 267 later via ``with_iso3()``. 268 gadm_id: optional GADM identifier for subnational AOIs. 269 """ 270 return cls( 271 slug=slug, 272 name=name if name is not None else slug, 273 bbox=(float(west), float(south), float(east), float(north)), 274 crs=crs, 275 resolution_m=resolution_m, 276 scale=scale, 277 gadm_id=gadm_id, 278 iso3=iso3, 279 ) 280 281 # -- slug registry (reads from aois.yaml) -------------------------------- 282 283 @classmethod 284 def from_slug(cls, slug: str) -> "AOI": 285 """Build an AOI from a slug key (e.g. ``'ghana'``). 286 287 Reads ``aois.yaml`` bundled alongside this module. Raises 288 ``ValueError`` if the slug is not in the registry. 289 """ 290 registry = _load_aois_yaml() 291 if slug not in registry: 292 raise ValueError( 293 f"Unknown AOI slug {slug!r}; available: {sorted(registry)}" 294 ) 295 cfg = registry[slug] 296 return cls( 297 slug=slug, 298 name=cfg.get("name", slug), 299 bbox=tuple(cfg["bbox"]), 300 crs=cfg["crs"], 301 resolution_m=cfg["resolution_m"], 302 scale=Scale(cfg.get("scale", "regional")), 303 gadm_id=cfg.get("gadm_id"), 304 iso3=cfg.get("iso3"), 305 ) 306 307 @classmethod 308 def from_gadm( 309 cls, 310 gadm_id: str, crs: str, slug: str, resolution_m: int, 311 *, 312 gadm_path: Path | str | None = None, 313 name: str | None = None, 314 scale: Scale = Scale.REGIONAL, 315 iso3: str | None = None, 316 ) -> "AOI": 317 """Load an AOI from a GADM file. 318 319 Looks up ``gadm_id`` in the GADM shapefile and computes the bbox from the 320 matching geometry. The GADM path resolves in this order: 321 1. explicit ``gadm_path`` argument 322 2. ``MAL_GADM_PATH`` environment variable 323 3. otherwise: ``FileNotFoundError`` with a clear message. 324 325 The id is matched against any ``GID_<n>`` column (GADM-0..GADM-5). 326 For country-level ids (e.g. "GHA"), pass ``iso3="GHA"`` so country-scoped 327 data loaders work; if omitted, it is inferred from the first three chars 328 of the GADM id (uppercased). 329 """ 330 if gadm_path is None: 331 env = os.environ.get("MAL_GADM_PATH") 332 if not env: 333 raise FileNotFoundError( 334 "GADM path not provided: pass gadm_path=... or set MAL_GADM_PATH" 335 ) 336 gadm_path = env 337 338 gdf = gpd.read_file(str(gadm_path)) 339 gid_col = None 340 for col in gdf.columns: 341 if col.startswith("GID_") and col[4:].isdigit(): 342 if gid_col is None or int(col[4:]) > int(gid_col[4:]): 343 gid_col = col 344 if gid_col is None: 345 raise ValueError( 346 f"No GID_<n> column found in {gadm_path}; columns={list(gdf.columns)}" 347 ) 348 349 match = gdf[gdf[gid_col] == gadm_id] 350 if match.empty: 351 raise KeyError( 352 f"gadm_id {gadm_id!r} not found in {gadm_path} (column {gid_col})" 353 ) 354 355 geom = match.geometry 356 # Reproject if needed so the bbox is in the requested CRS. 357 if str(gdf.crs) != str(pyproj.CRS.from_user_input(crs)): 358 geom = geom.to_crs(crs) 359 minx, miny, maxx, maxy = geom.total_bounds 360 361 # Infer ISO-3 from the first three chars of the GADM id when not given. 362 if iso3 is None and re.fullmatch(r"[A-Z]{3}", gadm_id[:3]): 363 iso3 = gadm_id[:3] 364 365 return cls( 366 slug=slug, 367 name=name if name is not None else f"{slug} ({gadm_id})", 368 bbox=(float(minx), float(miny), float(maxx), float(maxy)), 369 crs=crs, 370 resolution_m=resolution_m, 371 scale=scale, 372 gadm_id=gadm_id, 373 iso3=iso3, 374 ) 375 376 def require_iso3(self) -> str: 377 """Return ``iso3`` or raise ``ValueError`` if missing. 378 379 Country-scoped data loaders (WorldPop, GADM, livestock) need the ISO-3 380 country code to build download URLs. Call this at the top of any 381 loader that requires a country-level identifier. 382 """ 383 if not self.iso3: 384 raise ValueError( 385 f"AOI {self.slug!r} has no iso3; pass iso3='XXX' to " 386 f"from_bbox/from_slug/from_gadm or set it in aois.yaml" 387 ) 388 return self.iso3
Area of Interest — region-agnostic from M1.
The AOI is a typed parameter; the data layer and the ABM consume bbox + CRS + scale + slug. No hardcoded Ghana logic.
Attributes:
slug: stable identifier used in file naming (e.g. "ghana", "mozambique").
Lowercase, [a-z0-9-], no leading/trailing hyphens, no consecutive hyphens.
name: human-readable name (e.g. "Ghana NMCP AOI").
bbox: (west, south, east, north) in CRS units. For EPSG:4326, westfrom_gadm() can be used to populate bbox from GADM boundaries.
iso3: ISO 3166-1 alpha-3 country code (e.g. "GHA"). Required for country-scoped
data loaders (WorldPop, GADM, livestock); raises ValueError if absent when
needed. Always lowercase, exactly 3 letters.
144 @property 145 def crs_obj(self) -> pyproj.CRS: 146 """Parsed CRS as a ``pyproj.CRS`` object.""" 147 return pyproj.CRS.from_user_input(self.crs)
Parsed CRS as a pyproj.CRS object.
179 @property 180 def width_m(self) -> float: 181 """East-west extent of the bounding box in metres.""" 182 w, _, e, _ = self.bbox 183 m_per_x, _ = self._m_per_unit() 184 return abs(e - w) * m_per_x
East-west extent of the bounding box in metres.
186 @property 187 def height_m(self) -> float: 188 """North-south extent of the bounding box in metres.""" 189 _, s, _, n = self.bbox 190 _, m_per_y = self._m_per_unit() 191 return abs(n - s) * m_per_y
North-south extent of the bounding box in metres.
193 @property 194 def area_km2(self) -> float: 195 """Area of the bounding box in square kilometres, from width_m times height_m.""" 196 return (self.width_m * self.height_m) / 1_000_000.0
Area of the bounding box in square kilometres, from width_m times height_m.
198 @property 199 def geom(self) -> shapely.geometry.Polygon: 200 """Bounding box as a shapely Polygon in ``self.crs``.""" 201 w, s, e, n = self.bbox 202 return shapely.geometry.box(w, s, e, n)
Bounding box as a shapely Polygon in self.crs.
204 def cells_per_side(self) -> tuple[int, int]: 205 """(H, W) cells needed to cover the bbox at ``resolution_m`` (rounded up).""" 206 h = int(math.ceil(self.height_m / self.resolution_m)) 207 w = int(math.ceil(self.width_m / self.resolution_m)) 208 return h, w
(H, W) cells needed to cover the bbox at resolution_m (rounded up).
210 def to_geoseries(self, crs: str | None = None) -> gpd.GeoSeries: 211 """Bounding box as a ``GeoSeries``. ``crs`` defaults to ``self.crs``.""" 212 return gpd.GeoSeries([self.geom], crs=crs if crs is not None else self.crs)
Bounding box as a GeoSeries. crs defaults to self.crs.
216 def to_file(self, path: Path | str) -> Path: 217 """Serialize to JSON. Returns the written path.""" 218 p = Path(path) 219 payload = { 220 "slug": self.slug, 221 "name": self.name, 222 "bbox": list(self.bbox), 223 "crs": self.crs, 224 "resolution_m": self.resolution_m, 225 "scale": self.scale.value, 226 "gadm_id": self.gadm_id, 227 "iso3": self.iso3, 228 } 229 p.parent.mkdir(parents=True, exist_ok=True) 230 p.write_text(json.dumps(payload, indent=2)) 231 return p
Serialize to JSON. Returns the written path.
233 @classmethod 234 def from_file(cls, path: Path | str) -> "AOI": 235 """Inverse of ``to_file``.""" 236 p = Path(path) 237 payload = json.loads(p.read_text()) 238 return cls( 239 slug=payload["slug"], 240 name=payload["name"], 241 bbox=tuple(payload["bbox"]), 242 crs=payload["crs"], 243 resolution_m=int(payload["resolution_m"]), 244 scale=Scale(payload["scale"]), 245 gadm_id=payload.get("gadm_id"), 246 iso3=payload.get("iso3"), 247 )
Inverse of to_file.
251 @classmethod 252 def from_bbox( 253 cls, 254 west: float, south: float, east: float, north: float, 255 crs: str, slug: str, resolution_m: int, 256 *, 257 name: str | None = None, 258 scale: Scale = Scale.REGIONAL, 259 iso3: str | None = None, 260 gadm_id: str | None = None, 261 ) -> "AOI": 262 """Build an AOI from an explicit bbox. 263 264 Args: 265 iso3: ISO 3166-1 alpha-3 country code (e.g. "GHA"). Required to use 266 country-scoped loaders (WorldPop, GADM, livestock); can be set 267 later via ``with_iso3()``. 268 gadm_id: optional GADM identifier for subnational AOIs. 269 """ 270 return cls( 271 slug=slug, 272 name=name if name is not None else slug, 273 bbox=(float(west), float(south), float(east), float(north)), 274 crs=crs, 275 resolution_m=resolution_m, 276 scale=scale, 277 gadm_id=gadm_id, 278 iso3=iso3, 279 )
Build an AOI from an explicit bbox.
Args:
iso3: ISO 3166-1 alpha-3 country code (e.g. "GHA"). Required to use
country-scoped loaders (WorldPop, GADM, livestock); can be set
later via with_iso3().
gadm_id: optional GADM identifier for subnational AOIs.
283 @classmethod 284 def from_slug(cls, slug: str) -> "AOI": 285 """Build an AOI from a slug key (e.g. ``'ghana'``). 286 287 Reads ``aois.yaml`` bundled alongside this module. Raises 288 ``ValueError`` if the slug is not in the registry. 289 """ 290 registry = _load_aois_yaml() 291 if slug not in registry: 292 raise ValueError( 293 f"Unknown AOI slug {slug!r}; available: {sorted(registry)}" 294 ) 295 cfg = registry[slug] 296 return cls( 297 slug=slug, 298 name=cfg.get("name", slug), 299 bbox=tuple(cfg["bbox"]), 300 crs=cfg["crs"], 301 resolution_m=cfg["resolution_m"], 302 scale=Scale(cfg.get("scale", "regional")), 303 gadm_id=cfg.get("gadm_id"), 304 iso3=cfg.get("iso3"), 305 )
Build an AOI from a slug key (e.g. 'ghana').
Reads aois.yaml bundled alongside this module. Raises
ValueError if the slug is not in the registry.
307 @classmethod 308 def from_gadm( 309 cls, 310 gadm_id: str, crs: str, slug: str, resolution_m: int, 311 *, 312 gadm_path: Path | str | None = None, 313 name: str | None = None, 314 scale: Scale = Scale.REGIONAL, 315 iso3: str | None = None, 316 ) -> "AOI": 317 """Load an AOI from a GADM file. 318 319 Looks up ``gadm_id`` in the GADM shapefile and computes the bbox from the 320 matching geometry. The GADM path resolves in this order: 321 1. explicit ``gadm_path`` argument 322 2. ``MAL_GADM_PATH`` environment variable 323 3. otherwise: ``FileNotFoundError`` with a clear message. 324 325 The id is matched against any ``GID_<n>`` column (GADM-0..GADM-5). 326 For country-level ids (e.g. "GHA"), pass ``iso3="GHA"`` so country-scoped 327 data loaders work; if omitted, it is inferred from the first three chars 328 of the GADM id (uppercased). 329 """ 330 if gadm_path is None: 331 env = os.environ.get("MAL_GADM_PATH") 332 if not env: 333 raise FileNotFoundError( 334 "GADM path not provided: pass gadm_path=... or set MAL_GADM_PATH" 335 ) 336 gadm_path = env 337 338 gdf = gpd.read_file(str(gadm_path)) 339 gid_col = None 340 for col in gdf.columns: 341 if col.startswith("GID_") and col[4:].isdigit(): 342 if gid_col is None or int(col[4:]) > int(gid_col[4:]): 343 gid_col = col 344 if gid_col is None: 345 raise ValueError( 346 f"No GID_<n> column found in {gadm_path}; columns={list(gdf.columns)}" 347 ) 348 349 match = gdf[gdf[gid_col] == gadm_id] 350 if match.empty: 351 raise KeyError( 352 f"gadm_id {gadm_id!r} not found in {gadm_path} (column {gid_col})" 353 ) 354 355 geom = match.geometry 356 # Reproject if needed so the bbox is in the requested CRS. 357 if str(gdf.crs) != str(pyproj.CRS.from_user_input(crs)): 358 geom = geom.to_crs(crs) 359 minx, miny, maxx, maxy = geom.total_bounds 360 361 # Infer ISO-3 from the first three chars of the GADM id when not given. 362 if iso3 is None and re.fullmatch(r"[A-Z]{3}", gadm_id[:3]): 363 iso3 = gadm_id[:3] 364 365 return cls( 366 slug=slug, 367 name=name if name is not None else f"{slug} ({gadm_id})", 368 bbox=(float(minx), float(miny), float(maxx), float(maxy)), 369 crs=crs, 370 resolution_m=resolution_m, 371 scale=scale, 372 gadm_id=gadm_id, 373 iso3=iso3, 374 )
Load an AOI from a GADM file.
Looks up gadm_id in the GADM shapefile and computes the bbox from the
matching geometry. The GADM path resolves in this order:
1. explicit gadm_path argument
2. MAL_GADM_PATH environment variable
3. otherwise: FileNotFoundError with a clear message.
The id is matched against any GID_<n> column (GADM-0..GADM-5).
For country-level ids (e.g. "GHA"), pass iso3="GHA" so country-scoped
data loaders work; if omitted, it is inferred from the first three chars
of the GADM id (uppercased).
376 def require_iso3(self) -> str: 377 """Return ``iso3`` or raise ``ValueError`` if missing. 378 379 Country-scoped data loaders (WorldPop, GADM, livestock) need the ISO-3 380 country code to build download URLs. Call this at the top of any 381 loader that requires a country-level identifier. 382 """ 383 if not self.iso3: 384 raise ValueError( 385 f"AOI {self.slug!r} has no iso3; pass iso3='XXX' to " 386 f"from_bbox/from_slug/from_gadm or set it in aois.yaml" 387 ) 388 return self.iso3
Return iso3 or raise ValueError if missing.
Country-scoped data loaders (WorldPop, GADM, livestock) need the ISO-3 country code to build download URLs. Call this at the top of any loader that requires a country-level identifier.
33class Scale(str, Enum): 34 """Multi-scale levels per the design doc.""" 35 36 REGIONAL = "regional" # 1 km grid, no aggregation, raw raster 37 NATIONAL = "national" # GADM-2 mean-pool 38 CONTINENTAL = "continental" # 5 km grid + GADM-0 mean-pool, U-Net only
Multi-scale levels per the design doc.
59def clear_aoi_cache() -> None: 60 """Reset the cached YAML registry (useful for testing).""" 61 global _registry_cache 62 _registry_cache = None
Reset the cached YAML registry (useful for testing).