mal_commonlib.data.loaders

Data loaders for the env channels, habitat statics, hosts and mobility.

Plugin modules — each exports a public load_* function and a DOWNLOADER dict consumed by mal_core.download.registry (pkgutil scan, no manual list). Contract v3.0: the four land-cover statics (lc_built/lc_wetland/lc_open_plus_water/lc_crop) come from Google Dynamic World V1 (per-year modal label composites on Earth Engine); the persistent-water plane stays JRC GSW. The WorldCover/DEM/annual-ERA5 loaders are retired (git history).

 1"""Data loaders for the env channels, habitat statics, hosts and mobility.
 2
 3Plugin modules — each exports a public ``load_*`` function and a
 4``DOWNLOADER`` dict consumed by ``mal_core.download.registry`` (pkgutil
 5scan, no manual list). Contract v3.0: the four land-cover statics
 6(``lc_built/lc_wetland/lc_open_plus_water/lc_crop``) come from Google
 7Dynamic World V1 (per-year modal label composites on Earth Engine); the
 8persistent-water plane stays JRC GSW. The WorldCover/DEM/annual-ERA5
 9loaders are retired (git history).
10"""
11from .era5 import load_era5_air_temp_daily, load_era5_wind_6hourly
12from .jrc_gsw import load_jrc_gsw_habitat_features
13from .dynamic_world import load_dw_class_fractions
14from .dynamic_world import load_dw_label_mode  # shared utility (wildlife)
15from .chirps import load_chirps_rainfall_daily
16from .coastline import (
17    distance_to_land_m,
18    load_coastline_land_mask,
19    sea_mask,
20)
21from .worldpop import load_worldpop_population
22from .glw import load_glw_livestock
23from .ghsl import load_ghsl_urban_class
24from .buildings import load_buildings_fraction
25from .wildlife import load_wildlife_host_proxy
26from .smap import load_smap_salinity
27
28__all__ = [
29    "load_era5_air_temp_daily",
30    "load_era5_wind_6hourly",
31    "load_jrc_gsw_habitat_features",
32    "load_dw_class_fractions",
33    "load_dw_label_mode",
34    "load_chirps_rainfall_daily",
35    "load_coastline_land_mask",
36    "sea_mask",
37    "distance_to_land_m",
38    "load_worldpop_population",
39    "load_glw_livestock",
40    "load_ghsl_urban_class",
41    "load_buildings_fraction",
42    "load_wildlife_host_proxy",
43    "load_smap_salinity",
44]
def load_era5_air_temp_daily( aoi: mal_commonlib.AOI, *, years: Sequence[int], months: Sequence[int] | None = None, cache_dir: pathlib.Path | None = None) -> xarray.core.dataarray.DataArray:
300def load_era5_air_temp_daily(
301    aoi: AOI,
302    *,
303    years: Sequence[int],
304    months: Sequence[int] | None = None,
305    cache_dir: pathlib.Path | None = None,
306) -> xr.DataArray:
307    """Load ERA5-Land daily 2 m air temperature in °C for year(s) × month(s).
308
309    Args:
310        aoi: the AOI.
311        years: sequence of years to load.
312        months: sequence of 1-indexed months. None = all 12.
313        cache_dir: optional local cache for downloaded NetCDFs.
314
315    Returns:
316        xr.DataArray with dims (time, y, x), dtype float32, CRS = aoi.crs.
317        Values in degrees Celsius. ``NODATA_SENTINEL()`` for NoData.
318    """
319    if months is None:
320        months = list(range(1, 13))
321
322    cdir = cache_dir if cache_dir is not None else _default_cache_dir()
323    cdir.mkdir(parents=True, exist_ok=True)
324
325    all_arrays: list[xr.DataArray] = []
326
327    for year in sorted(years):
328        for month in sorted(months):
329            if not (1 <= month <= 12):
330                raise ValueError(f"month must be in 1..12; got {month}")
331            if year < 1950:
332                raise ValueError(f"ERA5 starts in 1950; got year={year}")
333            da = _load_era5_air_temp_single(aoi, year, month, cdir)
334            all_arrays.append(da)
335
336    if len(all_arrays) == 1:
337        # Contract var name: the daily channel the ABM env NC consumes.
338        return all_arrays[0].rename("air_temp_c")
339
340    merged = xr.concat(all_arrays, dim="time").rename("air_temp_c")
341    merged.attrs.update({
342        "long_name": "ERA5-Land 2m temperature (daily mean)",
343        "units": "degC",
344        "source": f"ERA5-Land daily stats {ERA5_VARIABLE} {ERA5_DAILY_STATISTIC}",
345        "aoi_slug": aoi.slug,
346        "nodata": ERA5_NODATA,
347    })
348    merged.rio.write_crs(aoi.crs_obj, inplace=True)
349    return merged

Load ERA5-Land daily 2 m air temperature in °C for year(s) × month(s).

Args: aoi: the AOI. years: sequence of years to load. months: sequence of 1-indexed months. None = all 12. cache_dir: optional local cache for downloaded NetCDFs.

Returns: xr.DataArray with dims (time, y, x), dtype float32, CRS = aoi.crs. Values in degrees Celsius. NODATA_SENTINEL() for NoData.

def load_era5_wind_6hourly( aoi: mal_commonlib.AOI, *, years: Sequence[int], months: Sequence[int] | None = None, cache_dir: pathlib.Path | None = None) -> xarray.core.dataset.Dataset:
450def load_era5_wind_6hourly(
451    aoi: AOI,
452    *,
453    years: Sequence[int],
454    months: Sequence[int] | None = None,
455    cache_dir: pathlib.Path | None = None,
456) -> xr.Dataset:
457    """Load-or-download ERA5 6-hourly 100m wind data.
458
459    Args:
460        aoi: AOI object (used for grid reprojection).
461        years: sequence of years.
462        months: sequence of 1-indexed months. None = all 12.
463        cache_dir: cache directory. Default ``~/.cache/mal_commonlib/era5``.
464
465    Returns:
466        ``xr.Dataset`` with merged 6-hourly wind data.
467    """
468    if not years:
469        raise ValueError("years must not be empty")
470
471    cdir = cache_dir or _default_cache_dir()
472    cdir.mkdir(parents=True, exist_ok=True)
473    year_str = "_".join(str(y) for y in sorted(years))
474    merged_path = cdir / f"wind_6hourly_{year_str}.nc"
475
476    if merged_path.exists() and merged_path.stat().st_size > 0:
477        return xr.open_dataset(merged_path)
478
479    ds = _download_era5_wind(years, months=months, cache_dir=cache_dir)
480    ds.to_netcdf(merged_path)
481    return ds

Load-or-download ERA5 6-hourly 100m wind data.

Args: aoi: AOI object (used for grid reprojection). years: sequence of years. months: sequence of 1-indexed months. None = all 12. cache_dir: cache directory. Default ~/.cache/mal_commonlib/era5.

Returns: xr.Dataset with merged 6-hourly wind data.

def load_jrc_gsw_habitat_features( aoi: mal_commonlib.AOI, *, year: int = 2021, cache_dir: pathlib.Path | None = None) -> xarray.core.dataset.Dataset:
265def load_jrc_gsw_habitat_features(
266    aoi: AOI,
267    *,
268    year: int = 2021,
269    cache_dir: pathlib.Path | None = None,
270) -> xr.Dataset:
271    """Load the contract v3.0 static habitat features derived from the JRC
272    Global Surface Water (GSW) 30 m ``occurrence`` band.
273
274    Single channel retained from the retired binary water/seasonal split
275    (plan docs/plans/in-process/redesign/01-retirada-hidrologia-dem-escorrentia.md
276    §6): the per-cell FRACTION of water pixels with occurrence >= 80 %,
277    coastline-masking excluded, as the only static surface-water signal the
278    redesign consumes (``jrc_persistent`` feature column). The old
279    threshold-80 binary mask (a whole-country binary raster with ~5 525
280    cells, useless for a relative habitat index) is NOT produced anymore;
281    the fraction IS the feature.
282
283    The loader goes through the Microsoft Planetary Computer STAC catalog
284    (``jrc-gsw`` collection) and reads only the AOI bbox window from
285    each intersecting tile.
286
287    Args:
288        aoi: the AOI.
289        year: JRC GSW product year (snapshot selector). The annual
290            ``occurrence`` band is available for 1984-2021 inclusive.
291            Default is 2021 (the latest available year).
292        cache_dir: optional local cache (currently unused — the STAC
293            signed URLs stream directly).
294
295    Returns:
296        ``xr.Dataset`` with one variable ``jrc_persistent`` of dims
297        (y, x), dtype float32, CRS = ``aoi.crs``, in [0, 1];
298        ``NODATA_SENTINEL()`` for NoData.
299    """
300    if not (_MIN_YEAR <= int(year) <= _MAX_YEAR):
301        raise ValueError(
302            f"JRC GSW year must be in [{_MIN_YEAR}, {_MAX_YEAR}]; got {year}"
303        )
304
305    bbox = _aoi_bbox_wgs84(aoi)
306    if not all(np.isfinite(b) for b in bbox):
307        raise ValueError(f"AOI bbox has non-finite values: {bbox}")
308
309    # The feature needs NO 80 % binarisation: the per-cell mean of the
310    # binary "occurrence >= threshold" mask directly IS the fraction of
311    # the cell covered by >=80 %-permanent water pixels. The retired code
312    # multiplied the resulting fraction into a separate 0.8 binary step —
313    # dropped; the mean at threshold_pct = PERMANENT_THRESHOLD_PCT.
314    arr, profile = _load_jrc_gsw_pc(
315        aoi, int(year), int(PERMANENT_THRESHOLD_PCT)
316    )
317
318    values = arr.astype(np.float32)
319    values = np.where(values == _NODATA_OUT_SCALAR, values,
320                      np.clip(values, 0.0, 1.0))
321
322    out = xr.DataArray(
323        values,
324        dims=("y", "x"),
325        name="jrc_persistent",
326        attrs={
327            "long_name": "JRC GSW fraction of >=80%-occurrence water pixels",
328            "source": f"JRC Global Surface Water {year} (Planetary Computer STAC)",
329            "units": "fraction of cell area [0, 1]",
330            "threshold_pct": int(PERMANENT_THRESHOLD_PCT),
331            "asset": _PC_ASSET,
332            "nodata": _NODATA_OUT_SCALAR,
333        },
334    )
335    out.rio.write_crs(profile["crs"], inplace=True)
336    if str(profile["crs"]) != str(aoi.crs_obj):
337        ref = _make_reference_grid(aoi)
338        out = out.rio.reproject_match(ref, resampling=Resampling.average)
339        out = out.astype(np.float32)
340    ds = out.to_dataset(name="jrc_persistent")
341    ds.rio.write_crs(aoi.crs, inplace=True)
342    ds.rio.write_transform(from_bounds(*aoi.bbox, *aoi.cells_per_side()), inplace=True)
343    ds["jrc_persistent"].rio.write_nodata(_NODATA_OUT_SCALAR, inplace=True)
344    ds.attrs = {
345        "contract": "habitat-v3.0-statics",
346        "source": f"JRC Global Surface Water {year} (Planetary Computer STAC)",
347        "asset": _PC_ASSET,
348        "year_used": int(profile["jrc_gsw_year"]),
349        "nodata": _NODATA_OUT_SCALAR,
350    }
351    return ds

Load the contract v3.0 static habitat features derived from the JRC Global Surface Water (GSW) 30 m occurrence band.

Single channel retained from the retired binary water/seasonal split (plan docs/plans/in-process/redesign/01-retirada-hidrologia-dem-escorrentia.md §6): the per-cell FRACTION of water pixels with occurrence >= 80 %, coastline-masking excluded, as the only static surface-water signal the redesign consumes (jrc_persistent feature column). The old threshold-80 binary mask (a whole-country binary raster with ~5 525 cells, useless for a relative habitat index) is NOT produced anymore; the fraction IS the feature.

The loader goes through the Microsoft Planetary Computer STAC catalog (jrc-gsw collection) and reads only the AOI bbox window from each intersecting tile.

Args: aoi: the AOI. year: JRC GSW product year (snapshot selector). The annual occurrence band is available for 1984-2021 inclusive. Default is 2021 (the latest available year). cache_dir: optional local cache (currently unused — the STAC signed URLs stream directly).

Returns: xr.Dataset with one variable jrc_persistent of dims (y, x), dtype float32, CRS = aoi.crs, in [0, 1]; NODATA_SENTINEL() for NoData.

def load_dw_class_fractions( aoi: mal_commonlib.AOI, *, years: Sequence[int], months: Optional[Sequence[int]] = None, cache_dir: pathlib.Path | None = None) -> xarray.core.dataset.Dataset:
340def load_dw_class_fractions(
341    aoi: "AOI",
342    *,
343    years: Sequence[int],
344    months: Sequence[int] | None = None,  # runner kwarg; ignored (annual mode)
345    cache_dir: Path | None = None,
346) -> xr.Dataset:
347    """Per-year Dynamic World modal-label fractions on the AOI grid.
348
349    Args:
350        aoi: the AOI.
351        years: run years to composite (one modal-label composite each).
352            The returned dataset has a ``time`` dim with one frame per year
353            (Jan 1 of that year); the ingest averages the frames into the
354            single static plane of the contract.
355        cache_dir: local cache root for the modal-label tiles (default
356            ``~/.cache/mal_commonlib/dynamic_world``).
357
358    Returns:
359        ``xr.Dataset`` dims (time, y, x) with variables ``lc_built``,
360        ``lc_wetland``, ``lc_crop``, ``lc_open_plus_water`` (float32,
361        [0,1], ``ingest.nodata_sentinel`` NoData), CRS = aoi.crs.
362    """
363    if not years:
364        raise ValueError("load_dw_class_fractions needs at least one year")
365    if min(years) < MIN_YEAR:
366        raise ValueError(
367            f"Dynamic World record starts {MIN_YEAR}-06-27; got {min(years)}"
368        )
369
370    bbox = _aoi_bbox_wgs84(aoi)
371    if not all(np.isfinite(b) for b in bbox):
372        raise ValueError(f"AOI bbox has non-finite values: {bbox}")
373
374    cache = _ensure_cache_dir(cache_dir)
375    H, W = aoi.cells_per_side()
376    ref_transform = from_bounds(*aoi.bbox, int(W), int(H))
377
378    frames: list[xr.Dataset] = []
379    for year in sorted(set(int(y) for y in years)):
380        data, _ = _year_fraction_planes(
381            year, bbox, ref_transform, aoi.crs_obj, (int(H), int(W)), cache
382        )
383        ds = xr.Dataset(
384            {name: xr.DataArray(arr, dims=("y", "x"), name=name)
385             for name, arr in data.items()},
386            attrs={
387                "contract": "habitat-v3.0-statics",
388                "source": f"Dynamic World V1 modal label, year {year} (GEE)",
389                "resolution_m": _REQUEST_SCALE_M,
390                # netCDF attrs cannot hold dicts — serialize as JSON.
391                "class_map": json.dumps(
392                    {k: list(v) for k, v in FEATURE_CLASSES.items()}
393                ),
394                "attribution": ATTRIBUTION.replace("[Year]", str(year)),
395                "nodata": NODATA_OUT,
396            },
397        )
398        ds = ds.assign_coords(time=np.datetime64(f"{year}-01-01", "D"))
399        ds.rio.write_crs(aoi.crs_obj, inplace=True)
400        ds.rio.write_transform(
401            from_bounds(*aoi.bbox, *aoi.cells_per_side()), inplace=True
402        )
403        for name in data:
404            ds[name].rio.write_nodata(NODATA_OUT, inplace=True)
405        frames.append(ds)
406
407    out = xr.concat(frames, dim="time")
408    out.attrs.update(frames[0].attrs)
409    out.attrs["source"] = (
410        "Dynamic World V1 modal label per year, averaged over "
411        f"{[int(y) for y in sorted(set(int(y) for y in years))]} (GEE)"
412    )
413    return out

Per-year Dynamic World modal-label fractions on the AOI grid.

Args: aoi: the AOI. years: run years to composite (one modal-label composite each). The returned dataset has a time dim with one frame per year (Jan 1 of that year); the ingest averages the frames into the single static plane of the contract. cache_dir: local cache root for the modal-label tiles (default ~/.cache/mal_commonlib/dynamic_world).

Returns: xr.Dataset dims (time, y, x) with variables lc_built, lc_wetland, lc_crop, lc_open_plus_water (float32, [0,1], ingest.nodata_sentinel NoData), CRS = aoi.crs.

def load_dw_label_mode( aoi: mal_commonlib.AOI, *, year: int, cache_dir: pathlib.Path | None = None) -> xarray.core.dataarray.DataArray:
416def load_dw_label_mode(
417    aoi: "AOI",
418    *,
419    year: int,
420    cache_dir: Path | None = None,
421) -> xr.DataArray:
422    """Dominant-class Dynamic World raster on the AOI grid (shared utility).
423
424    Same role the retired ``load_worldcover_landcover`` had for independent
425    consumers (the wildlife host proxy loader maps the label raster through
426    a suitability table). NOT part of the habitat contract — the habitat
427    ingest consumes ``load_dw_class_fractions`` only.
428
429    Returns:
430        xr.DataArray dims (y, x), dtype int32, CRS = aoi.crs, values are
431        Dynamic World label codes 0-8. ``ingest.nodata_sentinel_int`` NoData.
432    """
433    bbox = _aoi_bbox_wgs84(aoi)
434    if not all(np.isfinite(b) for b in bbox):
435        raise ValueError(f"AOI bbox has non-finite values: {bbox}")
436
437    cache = _ensure_cache_dir(cache_dir)
438    H, W = aoi.cells_per_side()
439    ref_transform = from_bounds(*aoi.bbox, int(W), int(H))
440
441    vote = np.full((H, W), -1, dtype=np.int32)
442    votes_acc = np.zeros((H, W, 9), dtype=np.float32)
443    valid = np.zeros((H, W), dtype=np.float32)
444    for path in _year_mode_label_tifs(year, bbox, cache):
445        raw, win_transform, src_crs = _read_tile(path)
446        h, w = raw.shape
447        tile_valid = np.zeros((H, W), dtype=np.float32)
448        reproject(
449            source=np.ones((h, w), dtype=np.float32),
450            destination=tile_valid,
451            src_transform=win_transform,
452            src_crs=src_crs,
453            dst_transform=ref_transform,
454            dst_crs=aoi.crs_obj,
455            resampling=Resampling.nearest,
456        )
457        for code in range(9):
458            layer = (raw == code).astype(np.float32)
459            plane = np.zeros((H, W), dtype=np.float32)
460            reproject(
461                source=layer,
462                destination=plane,
463                src_transform=win_transform,
464                src_crs=src_crs,
465                dst_transform=ref_transform,
466                dst_crs=aoi.crs_obj,
467                resampling=Resampling.average,
468            )
469            votes_acc[:, :, code] = np.maximum(
470                votes_acc[:, :, code], plane * (tile_valid > 0)
471            )
472        valid = np.maximum(valid, tile_valid)
473
474    covered = valid > 0
475    if covered.any():
476        vote[covered] = np.argmax(votes_acc[covered], axis=-1).astype(np.int32)
477    vote[~covered] = NODATA_OUT_INT
478
479    da = xr.DataArray(vote, dims=("y", "x"), name="label")
480    da.rio.write_crs(aoi.crs_obj, inplace=True)
481    da.rio.write_transform(
482        from_bounds(*aoi.bbox, *aoi.cells_per_side()), inplace=True
483    )
484    da.rio.write_nodata(NODATA_OUT_INT, inplace=True)
485    da.attrs["source"] = f"Dynamic World V1 modal label {year} (GEE)"
486    da.attrs["attribution"] = ATTRIBUTION.replace("[Year]", str(year))
487    return da

Dominant-class Dynamic World raster on the AOI grid (shared utility).

Same role the retired load_worldcover_landcover had for independent consumers (the wildlife host proxy loader maps the label raster through a suitability table). NOT part of the habitat contract — the habitat ingest consumes load_dw_class_fractions only.

Returns: xr.DataArray dims (y, x), dtype int32, CRS = aoi.crs, values are Dynamic World label codes 0-8. ingest.nodata_sentinel_int NoData.

def load_chirps_rainfall_daily( aoi: mal_commonlib.AOI, *, years: Sequence[int], months: Sequence[int] | None = None, cache_dir: pathlib.Path | None = None, _fetch_daily: Optional[Callable[[int, int, int], xarray.core.dataarray.DataArray]] = None) -> xarray.core.dataarray.DataArray:
251def load_chirps_rainfall_daily(
252    aoi: AOI,
253    *,
254    years: Sequence[int],
255    months: Sequence[int] | None = None,
256    cache_dir: pathlib.Path | None = None,
257    _fetch_daily: Callable[[int, int, int], xr.DataArray] | None = None,
258) -> xr.DataArray:
259    """Load CHIRPS v2.0 daily precipitation as a 3-D (time, y, x) array.
260
261    This is the canonical CHIRPS interface: per-day values written into a
262    daily NetCDF env file. The historical monthly-total loader
263    (``load_chirps_rainfall``) has been deleted; daily rainfall is what the
264    ABM's pluvial availability response needs. Each day's values are
265    reprojected to the AOI's grid independently.
266
267    Args:
268        aoi: the AOI (bbox, CRS, resolution_m, slug).
269        years: sequence of years to load.
270        months: sequence of 1-indexed months. None = all 12.
271        cache_dir: optional local cache for downloaded GeoTIFFs.
272        _fetch_daily: testing hook (kw-only).
273
274    Returns:
275        xr.DataArray with dims (time, y, x), dtype float32, CRS = aoi.crs.
276        Values in mm/day. Time coordinate uses ``np.datetime64`` for each
277        day across all requested year x month combinations.
278    """
279    if months is None:
280        months = list(range(1, 13))
281
282    if _fetch_daily is None:
283        cdir = cache_dir if cache_dir is not None else _default_cache_dir()
284
285        def _default_fetch(y: int, m: int, d: int) -> xr.DataArray:
286            """Download one CHIRPS day and clip it to the AOI, caching the clipped GeoTIFF."""
287            url = _daily_url_for(y, m, d)
288            dest = _cache_path_aoi(cdir, aoi.slug, y, m, d)
289            return _download_and_clip_to_aoi(url, aoi, dest)
290
291        fetch = _default_fetch
292    else:
293        fetch = _fetch_daily
294
295    daily_arrays: list[xr.DataArray] = []
296    time_coords: list[np.datetime64] = []
297
298    for year in sorted(years):
299        for month in sorted(months):
300            if not (1 <= month <= 12):
301                raise ValueError(f"month must be in 1..12; got {month}")
302            if year < 1981:
303                raise ValueError(f"CHIRPS starts in 1981; got year={year}")
304
305            days = _days_in_month(year, month)
306            for d in days:
307                raw = fetch(year, month, d)
308                reproj = _reproject_to_aoi_grid(raw, aoi)
309                nodata_mask = (~np.isfinite(reproj)) | (reproj == CHIRPS_NODATA)
310                reproj = np.where(
311                    nodata_mask, np.float32(CHIRPS_NODATA), reproj.astype(np.float32)
312                )
313                da = xr.DataArray(
314                    reproj.astype(np.float32)[np.newaxis, :, :],  # (1, y, x)
315                    dims=("time", "y", "x"),
316                )
317                daily_arrays.append(da)
318                time_coords.append(
319                    np.datetime64(f"{year:04d}-{month:02d}-{d:02d}")
320                )
321
322    stacked = xr.concat(daily_arrays, dim="time")
323    stacked = stacked.assign_coords(time=time_coords)
324    stacked.attrs.update({
325        "long_name": "CHIRPS v2.0 daily precipitation",
326        "units": "mm/day",
327        "source": "CHIRPS v2.0 daily 0.05°",
328        "aoi_slug": aoi.slug,
329        "nodata": CHIRPS_NODATA,
330    })
331    stacked.rio.write_crs(aoi.crs_obj, inplace=True)
332    return stacked

Load CHIRPS v2.0 daily precipitation as a 3-D (time, y, x) array.

This is the canonical CHIRPS interface: per-day values written into a daily NetCDF env file. The historical monthly-total loader (load_chirps_rainfall) has been deleted; daily rainfall is what the ABM's pluvial availability response needs. Each day's values are reprojected to the AOI's grid independently.

Args: aoi: the AOI (bbox, CRS, resolution_m, slug). years: sequence of years to load. months: sequence of 1-indexed months. None = all 12. cache_dir: optional local cache for downloaded GeoTIFFs. _fetch_daily: testing hook (kw-only).

Returns: xr.DataArray with dims (time, y, x), dtype float32, CRS = aoi.crs. Values in mm/day. Time coordinate uses np.datetime64 for each day across all requested year x month combinations.

def load_coastline_land_mask( aoi: mal_commonlib.AOI, *, resolution: str | None = None, coast_band_m: float | None = None, buffer_m: float | None = None, cache_dir: pathlib.Path | None = None, sub_pixel_m: float = 30.0) -> xarray.core.dataarray.DataArray:
301def load_coastline_land_mask(
302    aoi: "AOI",
303    *,
304    resolution: str | None = None,
305    coast_band_m: float | None = None,
306    buffer_m: float | None = None,
307    cache_dir: pathlib.Path | None = None,
308    sub_pixel_m: float = _SUB_PIXEL_M,
309) -> xr.DataArray:
310    """Load a per-cell land *fraction* for the AOI using GSHHG.
311
312    Args:
313        aoi: the AOI.
314        resolution: GSHHG resolution code (``"c"`` crude, ``"l"`` low,
315            ``"i"`` intermediate, ``"h"`` high, ``"f"`` full). Defaults to
316            ``ingest.coastline_resolution`` (``"f"``): at a 1 km grid the
317            crude polygons are off by several km.
318        coast_band_m: width of the coastal band in metres, used by
319            ``sea_mask`` downstream (daily_nc.py). Recorded in the attrs;
320            the loader itself no longer dilates anything. Defaults to
321            ``ingest.coastline_buffer_m``.
322        buffer_m: DEPRECATED alias for ``coast_band_m`` (old manifests and
323            call sites). Passing it raises no error, it just forwards.
324        cache_dir: local cache for the GSHHG archive. Defaults to
325            ``~/.cache/malaria_sentinel/gshhg/``.
326        sub_pixel_m: sub-cell rasterisation step (metres) used to build the
327            fraction. Default 30 m (the native GSHHG full scale).
328
329    Returns:
330        xr.DataArray with dims (y, x), dtype ``float32``, CRS = ``aoi.crs``,
331        values in [0, 1]: the fraction of each AOI cell covered by land
332        (1.0 = fully land, 0.0 = fully water). The variable name stays
333        ``land_mask`` so the manifest/registry contract is unchanged; the
334        values and attrs are no longer binary.
335    """
336    if resolution is None:
337        resolution = default_resolution()
338    if resolution not in {"c", "l", "i", "h", "f"}:
339        raise ValueError(
340            f"GSHHG resolution must be one of c/l/i/h/f; got {resolution!r}"
341        )
342    if buffer_m is not None and coast_band_m is None:
343        coast_band_m = float(buffer_m)
344    if coast_band_m is None:
345        coast_band_m = default_coast_band_m()
346    coast_band_m = float(coast_band_m)
347
348    cache_dir = _ensure_cache_dir(cache_dir)
349    shp_path = _ensure_gshhg_shapefile(cache_dir, resolution)
350
351    H, W = aoi.cells_per_side()
352    H = int(H)
353    W = int(W)
354    ref_transform = from_bounds(*aoi.bbox, W, H)
355
356    bbox = _aoi_bbox_wgs84(aoi)
357    bbox_gdf = gpd.GeoDataFrame(geometry=[box(*bbox)], crs="EPSG:4326")
358    coast = gpd.read_file(shp_path)
359    if coast.crs is None:
360        coast = coast.set_crs("EPSG:4326")
361    elif str(coast.crs).upper() not in {"EPSG:4326", "WGS84", "4326"}:
362        coast = coast.to_crs("EPSG:4326")
363
364    clipped = gpd.clip(coast, bbox_gdf)
365    land_frac = _land_fraction(clipped, aoi, H, W, sub_pixel_m)
366
367    floor = default_sea_water_floor()
368    da = xr.DataArray(
369        land_frac.astype(np.float32),
370        dims=("y", "x"),
371        name="land_mask",
372        attrs={
373            "long_name": (
374                "GSHHG land fraction per AOI cell (0 = open water, "
375                "1 = fully land)"
376            ),
377            "units": "1",
378            "source": (
379                f"GSHHG {_GSHHG_VERSION} resolution={resolution} "
380                f"L{_LEVEL_LAND}"
381            ),
382            "variable": "land_frac",
383            "sub_pixel_m": float(sub_pixel_m),
384            "coast_band_m": float(coast_band_m),
385            "sea_water_floor": float(floor),
386            "sea_rule": (
387                "sea <=> land_frac < sea_water_floor and "
388                "distance_to_land > coast_band_m"
389            ),
390            "resolution_m": float(aoi.resolution_m),
391            "nodata": _NODATA_OUT_SCALAR,
392        },
393    )
394    da.rio.write_crs(aoi.crs, inplace=True)
395    da.rio.write_transform(ref_transform, inplace=True)
396    return da

Load a per-cell land fraction for the AOI using GSHHG.

Args: aoi: the AOI. resolution: GSHHG resolution code ("c" crude, "l" low, "i" intermediate, "h" high, "f" full). Defaults to ingest.coastline_resolution ("f"): at a 1 km grid the crude polygons are off by several km. coast_band_m: width of the coastal band in metres, used by sea_mask downstream (daily_nc.py). Recorded in the attrs; the loader itself no longer dilates anything. Defaults to ingest.coastline_buffer_m. buffer_m: DEPRECATED alias for coast_band_m (old manifests and call sites). Passing it raises no error, it just forwards. cache_dir: local cache for the GSHHG archive. Defaults to ~/.cache/malaria_sentinel/gshhg/. sub_pixel_m: sub-cell rasterisation step (metres) used to build the fraction. Default 30 m (the native GSHHG full scale).

Returns: xr.DataArray with dims (y, x), dtype float32, CRS = aoi.crs, values in [0, 1]: the fraction of each AOI cell covered by land (1.0 = fully land, 0.0 = fully water). The variable name stays land_mask so the manifest/registry contract is unchanged; the values and attrs are no longer binary.

def sea_mask( land_frac: numpy.ndarray, distance_to_land_m: numpy.ndarray, coast_band_m: float, water_floor: float | None = None) -> numpy.ndarray:
268def sea_mask(
269    land_frac: np.ndarray, distance_to_land_m: np.ndarray,
270    coast_band_m: float, water_floor: float | None = None,
271) -> np.ndarray:
272    """Boolean "open sea" mask.
273
274    Rule (documented contract): a cell is open sea when
275
276        ``land_frac < water_floor``  AND  ``distance_to_land > coast_band_m``
277
278    i.e. it is water rather than land, and it is farther than the coastal band
279    from the nearest land. Inside the band (lagoons, estuaries, the surf zone,
280    the shallow plume visible in satellite imagery) the cell is *coastal
281    water*: it keeps its JRC permanent-water signal and its rainfall.
282
283    Args:
284        land_frac: per-cell land fraction in [0, 1].
285        distance_to_land_m: per-cell distance to nearest land, metres
286            (``distance_to_land_m``).
287        coast_band_m: width of the coastal band in metres. ``<= 0`` disables
288            the band (only land-fraction decides).
289        water_floor: land-fraction threshold below which a cell is water.
290            Defaults to ``ingest.sea_water_floor``.
291    """
292    lf = np.asarray(land_frac, dtype=np.float64)
293    dist = np.asarray(distance_to_land_m, dtype=np.float64)
294    floor = default_sea_water_floor() if water_floor is None else float(water_floor)
295    water = lf < floor
296    if coast_band_m is None or float(coast_band_m) <= 0:
297        return water
298    return water & (dist > float(coast_band_m))

Boolean "open sea" mask.

Rule (documented contract): a cell is open sea when

``land_frac < water_floor``  AND  ``distance_to_land > coast_band_m``

i.e. it is water rather than land, and it is farther than the coastal band from the nearest land. Inside the band (lagoons, estuaries, the surf zone, the shallow plume visible in satellite imagery) the cell is coastal water: it keeps its JRC permanent-water signal and its rainfall.

Args: land_frac: per-cell land fraction in [0, 1]. distance_to_land_m: per-cell distance to nearest land, metres (distance_to_land_m). coast_band_m: width of the coastal band in metres. <= 0 disables the band (only land-fraction decides). water_floor: land-fraction threshold below which a cell is water. Defaults to ingest.sea_water_floor.

def distance_to_land_m( land_frac: numpy.ndarray, resolution_m: float, water_floor: float | None = None) -> numpy.ndarray:
250def distance_to_land_m(
251    land_frac: np.ndarray, resolution_m: float,
252    water_floor: float | None = None,
253) -> np.ndarray:
254    """Euclidean distance (m) from each cell to the nearest land cell.
255
256    Land = ``land_frac >= water_floor`` (default ``ingest.sea_water_floor``).
257    Computed on the AOI grid with ``scipy.ndimage.distance_transform_edt``;
258    one cell unit equals ``resolution_m``.
259    """
260    lf = np.asarray(land_frac, dtype=np.float64)
261    floor = default_sea_water_floor() if water_floor is None else float(water_floor)
262    land = lf >= floor
263    if not land.any():
264        return np.full(lf.shape, np.inf, dtype=np.float64)
265    return ndimage.distance_transform_edt(~land) * float(resolution_m)

Euclidean distance (m) from each cell to the nearest land cell.

Land = land_frac >= water_floor (default ingest.sea_water_floor). Computed on the AOI grid with scipy.ndimage.distance_transform_edt; one cell unit equals resolution_m.

def load_worldpop_population( aoi: mal_commonlib.AOI | str, *, year: int = 2019, release: str = 'Global1', cache_dir: pathlib.Path | None = None) -> xarray.core.dataarray.DataArray:
411def load_worldpop_population(
412    aoi: "AOI | str",
413    *,
414    year: int = 2019,
415    release: str = "Global1",
416    cache_dir: pathlib.Path | None = None,
417) -> xr.DataArray:
418    """Load WorldPop constrained population density for the AOI.
419
420    Args:
421        aoi: the AOI (bbox, CRS, resolution_m, slug, iso3) or a slug string.
422            ``aoi.iso3`` is required — country-scoped loaders cannot guess
423            the ISO code from a bbox alone.
424        year: target year (default 2019). Valid range depends on ``release``.
425        release: WorldPop release identifier:
426            - ``"Global1"`` (default): legacy 2000–2020, per-country GeoTIFFs.
427            - ``"R2025A"``: Global2 / R2025A v1, 2015–2030. **Not yet served
428              per-country** — will raise ``HTTPError`` until WorldPop
429              publishes per-country files.
430        cache_dir: local cache for downloaded GeoTIFFs.
431
432    Returns:
433        ``xr.DataArray`` with dims ``(y, x)``, dtype float32, CRS = ``aoi.crs``.
434        Values are **population count per AOI cell** (sum-preserving across
435        the source raster). ``NODATA_SENTINEL()`` for cells with no source coverage.
436
437    Raises:
438        ValueError: if ``aoi.iso3`` is missing or ``year`` is outside the
439            valid range for the chosen release.
440        requests.HTTPError: on download failure (e.g. R2025A per-country
441            file not published yet).
442    """
443    if isinstance(aoi, str):
444        from mal_commonlib.aoi import AOI
445
446        aoi = AOI.from_slug(aoi)
447
448    iso3 = aoi.require_iso3()  # raises ValueError if missing
449    iso3_lower = iso3.lower()
450
451    cache = cache_dir if cache_dir is not None else _default_cache_dir()
452    cache = pathlib.Path(cache)
453    cache.mkdir(parents=True, exist_ok=True)
454
455    file_name = _cache_filename(iso3_lower, year, release)
456    tif_path = cache / file_name
457    url = _resolve_url(year, iso3, release=release)
458    _download_to(url, tif_path)
459    return _read_clip(aoi, tif_path, year)

Load WorldPop constrained population density for the AOI.

Args: aoi: the AOI (bbox, CRS, resolution_m, slug, iso3) or a slug string. aoi.iso3 is required — country-scoped loaders cannot guess the ISO code from a bbox alone. year: target year (default 2019). Valid range depends on release. release: WorldPop release identifier: - "Global1" (default): legacy 2000–2020, per-country GeoTIFFs. - "R2025A": Global2 / R2025A v1, 2015–2030. Not yet served per-country — will raise HTTPError until WorldPop publishes per-country files. cache_dir: local cache for downloaded GeoTIFFs.

Returns: xr.DataArray with dims (y, x), dtype float32, CRS = aoi.crs. Values are population count per AOI cell (sum-preserving across the source raster). NODATA_SENTINEL() for cells with no source coverage.

Raises: ValueError: if aoi.iso3 is missing or year is outside the valid range for the chosen release. requests.HTTPError: on download failure (e.g. R2025A per-country file not published yet).

def load_glw_livestock( aoi: mal_commonlib.AOI | str, *, species: str = 'cattle', cache_dir: pathlib.Path | None = None) -> xarray.core.dataarray.DataArray:
213def load_glw_livestock(
214    aoi: AOI | str,
215    *,
216    species: str = "cattle",
217    cache_dir: pathlib.Path | None = None,
218) -> xr.DataArray:
219    """Load FAO GLW4 livestock density for the AOI.
220
221    Args:
222        aoi: the AOI (bbox, CRS, resolution_m, slug) or a string slug.
223        species: one of "cattle", "goats", "sheep", "pigs", "chickens".
224        cache_dir: local cache for downloaded GeoTIFFs.
225
226    Returns:
227        xr.DataArray with dims (y, x), dtype float32, CRS = aoi.crs.
228        Values are livestock DENSITY in heads/km² (for km²-scale ABM
229        cells this equals heads per cell). ``NODATA_SENTINEL()`` for cells with no data.
230    """
231    from mal_commonlib.aoi import AOI as AOIType
232
233    if isinstance(aoi, str):
234        from mal_commonlib.aoi import AOI
235
236        aoi = AOI.from_slug(aoi)
237
238    species = species.lower()
239    if species not in _SPECIES_CONFIG:
240        raise ValueError(
241            f"Unknown species {species!r}; supported: {SUPPORTED_SPECIES}"
242        )
243
244    cfg = _SPECIES_CONFIG[species]
245    cdir = cache_dir if cache_dir is not None else _default_cache_dir()
246    tif_path = pathlib.Path(cdir) / cfg["file_name"]
247    _download_to(cfg["url"], tif_path)
248
249    da = _read_clip(aoi, tif_path, species, cfg["long_name"])
250    return da

Load FAO GLW4 livestock density for the AOI.

Args: aoi: the AOI (bbox, CRS, resolution_m, slug) or a string slug. species: one of "cattle", "goats", "sheep", "pigs", "chickens". cache_dir: local cache for downloaded GeoTIFFs.

Returns: xr.DataArray with dims (y, x), dtype float32, CRS = aoi.crs. Values are livestock DENSITY in heads/km² (for km²-scale ABM cells this equals heads per cell). NODATA_SENTINEL() for cells with no data.

def load_ghsl_urban_class( aoi: mal_commonlib.AOI | str, *, cache_dir: pathlib.Path | None = None) -> xarray.core.dataarray.DataArray:
235def load_ghsl_urban_class(
236    aoi: AOI | str,
237    *,
238    cache_dir: pathlib.Path | None = None,
239) -> xr.DataArray:
240    """Load GHSL settlement classification (SMOD) for the AOI.
241
242    Downloads the ZIP from JRC FTP, extracts the TIF, and clips
243    to the AOI bounding box.  The source raster is in EPSG:54009
244    (World Mollweide) at ~1 km; it is reprojected on-the-fly to
245    the AOI's CRS via nearest-neighbour resampling (categorical data).
246
247    Args:
248        aoi: the AOI (bbox, CRS, resolution_m, slug) or a string slug.
249        cache_dir: local cache for the downloaded/extracted raster.
250
251    Returns:
252        xr.DataArray with dims (y, x), dtype int32, CRS = aoi.crs.
253        Values are integer class codes: 30 (urban), 50 (rural), 20 (water).
254    """
255    from mal_commonlib.aoi import AOI as AOIType
256    if isinstance(aoi, str):
257        from mal_commonlib.aoi import AOI
258        aoi = AOI.from_slug(aoi)
259
260    cdir = pathlib.Path(cache_dir) if cache_dir is not None else _default_cache_dir()
261    cdir.mkdir(parents=True, exist_ok=True)
262    zip_path = cdir / "GHS_SMOD_E2030_R2023A_54009_1000.zip"
263    tif_path = cdir / _GHSL_CACHE_TIF
264
265    # Step 1: download ZIP (cached)
266    _download_zip(_GHSL_ZIP_URL, zip_path)
267
268    # Step 2: extract TIF from ZIP (cached)
269    _extract_tif_from_zip(zip_path, _GHSL_TIF_NAME, tif_path)
270
271    # Step 3: read, reproject, clip
272    da = _read_clip(aoi, tif_path)
273    return da

Load GHSL settlement classification (SMOD) for the AOI.

Downloads the ZIP from JRC FTP, extracts the TIF, and clips to the AOI bounding box. The source raster is in EPSG:54009 (World Mollweide) at ~1 km; it is reprojected on-the-fly to the AOI's CRS via nearest-neighbour resampling (categorical data).

Args: aoi: the AOI (bbox, CRS, resolution_m, slug) or a string slug. cache_dir: local cache for the downloaded/extracted raster.

Returns: xr.DataArray with dims (y, x), dtype int32, CRS = aoi.crs. Values are integer class codes: 30 (urban), 50 (rural), 20 (water).

def load_buildings_fraction( aoi: mal_commonlib.AOI | str, *, cache_dir: pathlib.Path | None = None) -> xarray.core.dataarray.DataArray:
178def load_buildings_fraction(
179    aoi: AOI | str,
180    *,
181    cache_dir: pathlib.Path | None = None,
182) -> xr.DataArray:
183    """Load building footprint fraction for the AOI.
184
185    Args:
186        aoi: the AOI (bbox, CRS, resolution_m, slug) or string slug.
187        cache_dir: local cache for downloaded data.
188
189    Returns:
190        xr.DataArray with dims (y, x), dtype float32, CRS = aoi.crs.
191        Values in [0, 1] (1.0 = building centroid present in cell).
192        ``NODATA_SENTINEL()`` for cells with no data.
193    """
194    if isinstance(aoi, str):
195        from mal_commonlib.aoi import AOI
196        aoi = AOI.from_slug(aoi)
197
198    cdir = pathlib.Path(cache_dir) if cache_dir is not None else _default_cache_dir()
199
200    # Cached raster for this AOI + latest release?
201    release = _resolve_latest_release()
202    cache_path = cdir / f"buildings_{aoi.slug}_{release}.npz"
203    if cache_path.exists():
204        with np.load(cache_path) as z:
205            fraction = z["fraction"].astype(np.float32, copy=False)
206    else:
207        bbox_wgs84 = _aoi_to_src_bbox(aoi)
208        fraction = _download_and_rasterize(bbox_wgs84, aoi, cdir)
209
210    da = xr.DataArray(
211        fraction,
212        dims=("y", "x"),
213        name="building_fraction",
214        attrs={
215            "long_name": "Building footprint fraction",
216            "units": "fraction [0, 1]",
217            "source": "Overture Maps Foundation",
218            "overture_release": release,
219            "nodata": _NODATA,
220        },
221    )
222    da.rio.write_crs(aoi.crs_obj, inplace=True)
223    da.rio.write_transform(from_bounds(*aoi.bbox, *aoi.cells_per_side()[::-1]), inplace=True)
224    da.rio.write_nodata(_NODATA, inplace=True)
225    return da

Load building footprint fraction for the AOI.

Args: aoi: the AOI (bbox, CRS, resolution_m, slug) or string slug. cache_dir: local cache for downloaded data.

Returns: xr.DataArray with dims (y, x), dtype float32, CRS = aoi.crs. Values in [0, 1] (1.0 = building centroid present in cell). NODATA_SENTINEL() for cells with no data.

def load_wildlife_host_proxy( aoi: mal_commonlib.AOI | str, *, year: int = 2021, cache_dir: pathlib.Path | None = None) -> xarray.core.dataarray.DataArray:
169def load_wildlife_host_proxy(
170    aoi: AOI | str,
171    *,
172    year: int = 2021,
173    cache_dir: pathlib.Path | None = None,
174) -> xr.DataArray:
175    """Load wildlife host proxy suitability for the AOI.
176
177    Computes a [0,1] suitability score from ESA WorldCover habitat
178    classes, JRC GSW water presence, and building remoteness.
179
180    Args:
181        aoi: the AOI (bbox, CRS, resolution_m, slug).
182        year: Dynamic World composite year (2015 → today).
183        cache_dir: optional local cache for downloaded data.
184
185    Returns:
186        xr.DataArray with dims (y, x), dtype float32, CRS = aoi.crs.
187        Values in [0, 1]. ``NODATA_SENTINEL()`` for NoData.
188    """
189    if isinstance(aoi, str):
190        aoi = AOI.from_slug(aoi)
191
192    # Model parameters are read before any I/O: a missing/invalid key must be
193    # a loud error, never a silently neutral component.
194    suitability = _class_suitability()
195    weights = _component_weights()
196
197    H, W = aoi.cells_per_side()
198    H, W = int(H), int(W)
199
200    # --- 1. Habitat suitability from Dynamic World --------------------
201    try:
202        habitat = _load_dw_habitat_pc(aoi, year, suitability=suitability)
203        log.info("wildlife: Dynamic World habitat loaded successfully")
204    except Exception as exc:
205        log.warning("wildlife: Dynamic World failed (%s), using neutral 0.5", exc)
206        habitat = np.full((H, W), 0.5, dtype=np.float32)
207
208    # --- 2. Water proximity from JRC GSW -----------------------------
209    try:
210        from mal_commonlib.data.loaders.jrc_gsw import (
211            load_jrc_gsw_habitat_features,
212        )
213
214        jrc = load_jrc_gsw_habitat_features(aoi, cache_dir=cache_dir)
215        water_frac = jrc["jrc_persistent"].values.astype(np.float32)
216        log.info("wildlife: JRC persistent-water surface loaded successfully")
217    except Exception as exc:
218        log.warning("wildlife: JRC GSW failed (%s), using neutral 0.5", exc)
219        water_frac = np.full((H, W), 0.5 / 3.0, dtype=np.float32)
220
221    water = _water_presence(water_frac)
222
223    # --- 3. Remoteness from buildings ---------------------------------
224    try:
225        from mal_commonlib.data.loaders.buildings import load_buildings_fraction
226
227        bld_da = load_buildings_fraction(aoi, cache_dir=cache_dir)
228        bld_frac = bld_da.values.astype(np.float32)
229        # Replace nodata with 0 (no buildings → remote)
230        bld_frac[bld_frac == _NODATA_OUT_SCALAR] = 0.0
231        log.info("wildlife: Buildings loaded successfully")
232    except Exception as exc:
233        log.warning("wildlife: Buildings failed (%s), assuming remote", exc)
234        bld_frac = np.zeros((H, W), dtype=np.float32)
235
236    remote = _remoteness(bld_frac)
237
238    # --- 4. Compute composite ----------------------------------------
239    proxy = (weights["habitat"] * habitat
240             + weights["water"] * water
241             + weights["remoteness"] * remote)
242    proxy = np.clip(proxy, 0.0, 1.0).astype(np.float32)
243
244    # Propagate nodata: cells where WorldCover had no data
245    nodata_mask = habitat == _NODATA_OUT_SCALAR
246    proxy[nodata_mask] = _NODATA_OUT_SCALAR
247
248    # --- 5. Wrap and return -------------------------------------------
249    da = xr.DataArray(
250        proxy,
251        dims=("y", "x"),
252        name="wildlife_host_proxy",
253        attrs={
254            "long_name": "Wildlife host proxy suitability",
255            "units": "suitability [0, 1]",
256            "source": (
257                f"ESA WorldCover {year} + JRC GSW + Overture Maps buildings"
258            ),
259            "formula": (
260                "weighted combination of habitat_suitability, "
261                "water_presence and remoteness (weights from "
262                "model_constants.yaml wildlife.weights)"
263            ),
264            "nodata": _NODATA_OUT_SCALAR,
265        },
266    )
267    da.rio.write_crs(aoi.crs_obj, inplace=True)
268    da.rio.write_transform(
269        from_bounds(*aoi.bbox, W, H),
270        inplace=True,
271    )
272    da.rio.write_nodata(_NODATA_OUT_SCALAR, inplace=True)
273    return da

Load wildlife host proxy suitability for the AOI.

Computes a [0,1] suitability score from ESA WorldCover habitat classes, JRC GSW water presence, and building remoteness.

Args: aoi: the AOI (bbox, CRS, resolution_m, slug). year: Dynamic World composite year (2015 → today). cache_dir: optional local cache for downloaded data.

Returns: xr.DataArray with dims (y, x), dtype float32, CRS = aoi.crs. Values in [0, 1]. NODATA_SENTINEL() for NoData.

def load_smap_salinity( aoi: mal_commonlib.AOI, *, years: Sequence[int], months: Sequence[int] | None = None, cache_dir: pathlib.Path | None = None, _fetch_monthly: "'callable | None'" = None) -> xarray.core.dataarray.DataArray:
288def load_smap_salinity(
289    aoi: AOI,
290    *,
291    years: Sequence[int],
292    months: Sequence[int] | None = None,
293    cache_dir: pathlib.Path | None = None,
294    _fetch_monthly: "callable | None" = None,
295) -> xr.DataArray:
296    """Load SMAP RSS L3 SSS monthly sea surface salinity for the AOI.
297
298    Args:
299        aoi: the AOI.
300        years: sequence of years to load.
301        months: 1-indexed months. None = all 12.
302        cache_dir: optional local cache for downloaded granules.
303        _fetch_monthly: testing hook (kw-only). ``(year, month) ->
304            xr.Dataset | None`` returning a raw SMAP granule, or None for a
305            month with no data.
306
307    Returns:
308        xr.DataArray dims ``(time, y, x)``; ``(y, x)`` if a single month.
309        Values in PSU on the AOI-clipped SMAP 0.25° grid, CRS EPSG:4326.
310        NaN for land / fill / missing months.
311    """
312    if months is None:
313        months = list(range(1, 13))
314
315    cache = _ensure_cache_dir(cache_dir)
316
317    if _fetch_monthly is None:
318
319        def _default_fetch(y: int, m: int) -> xr.Dataset | None:
320            """Fetch one month of raw SMAP granules through earthaccess."""
321            return _fetch_monthly_via_earthaccess(aoi, y, m, cache)
322
323        fetch = _default_fetch
324    else:
325        fetch = _fetch_monthly
326
327    y_canon, x_canon = _aoi_native_grid(aoi)
328    results: list[xr.DataArray] = []
329    time_coords: list[np.datetime64] = []
330
331    for year in sorted(years):
332        for month in sorted(months):
333            if not (1 <= month <= 12):
334                raise ValueError(f"month must be in 1..12; got {month}")
335
336            raw = fetch(year, month)
337            da = _postprocess_smap_ds(raw, aoi) if raw is not None else _empty_month(aoi)
338            da = da.reindex(y=y_canon, x=x_canon)
339            results.append(da)
340            time_coords.append(np.datetime64(f"{year:04d}-{month:02d}-01"))
341
342    if len(results) == 1:
343        out = results[0]
344        out.attrs.update(_BASE_ATTRS)
345        return out
346
347    stacked = xr.concat(results, dim="time")
348    stacked = stacked.assign_coords(time=time_coords)
349    stacked.attrs.update(_BASE_ATTRS)
350    stacked.rio.write_crs("EPSG:4326", inplace=True)
351    return stacked

Load SMAP RSS L3 SSS monthly sea surface salinity for the AOI.

Args: aoi: the AOI. years: sequence of years to load. months: 1-indexed months. None = all 12. cache_dir: optional local cache for downloaded granules. _fetch_monthly: testing hook (kw-only). (year, month) -> xr.Dataset | None returning a raw SMAP granule, or None for a month with no data.

Returns: xr.DataArray dims (time, y, x); (y, x) if a single month. Values in PSU on the AOI-clipped SMAP 0.25° grid, CRS EPSG:4326. NaN for land / fill / missing months.