mal_commonlib.data.host_utils

Host density utilities: grid aggregation and static NetCDF writer (M7).

Public surface

aggregate_to_grid(source, source_transform, target_grid_spec, method="sum") Conservatively aggregate a high-res source raster to a coarser ABM grid.

build_host_static_nc(...) Write the static host density NetCDF for the ABM engine.

Resampling rules: * Population / livestock: sum-preserving (conservative) aggregation. * Urban/rural classification: nearest-neighbour (categorical).

The target_grid_spec is a dict with keys crs, transform, height, width describing the ABM grid.

  1"""Host density utilities: grid aggregation and static NetCDF writer (M7).
  2
  3Public surface
  4--------------
  5``aggregate_to_grid(source, source_transform, target_grid_spec, method="sum")``
  6    Conservatively aggregate a high-res source raster to a coarser ABM grid.
  7
  8``build_host_static_nc(...)``
  9    Write the static host density NetCDF for the ABM engine.
 10
 11Resampling rules:
 12    * Population / livestock: sum-preserving (conservative) aggregation.
 13    * Urban/rural classification: nearest-neighbour (categorical).
 14
 15The ``target_grid_spec`` is a dict with keys ``crs``, ``transform``,
 16``height``, ``width`` describing the ABM grid.
 17"""
 18from __future__ import annotations
 19
 20import json
 21import pathlib
 22from typing import Any
 23
 24import numpy as np
 25import xarray as xr
 26
 27from mal_commonlib.model_constants import model_constant
 28
 29_NODATA = float(model_constant("ingest", "nodata_sentinel"))
 30_NODATA_INT = int(model_constant("ingest", "nodata_sentinel_int"))
 31
 32
 33def aggregate_to_grid(
 34    source: np.ndarray,
 35    source_transform: Any,
 36    source_crs: Any,
 37    target_transform: Any,
 38    target_crs: Any,
 39    target_shape: tuple[int, int],
 40    method: str = "sum",
 41    nodata: float = _NODATA,
 42) -> np.ndarray:
 43    """Aggregate a source raster to a target grid.
 44
 45    Uses ``rasterio.warp.reproject`` under the hood. For ``method="sum"``
 46    the resampling is ``Resampling.sum`` (conservative / area-weighted).
 47    For ``method="nearest"`` it is ``Resampling.nearest`` (categorical).
 48
 49    Args:
 50        source: (H_src, W_src) numpy array.
 51        source_transform: affine transform of the source.
 52        source_crs: CRS of the source (anything rasterio accepts).
 53        target_transform: affine transform of the target grid.
 54        target_crs: CRS of the target grid.
 55        target_shape: (H_dst, W_dst) of the target grid.
 56        method: "sum" (conservative) or "nearest" (categorical).
 57        nodata: sentinel value to mask before summing (default: the NoData sentinel).
 58
 59    Returns:
 60        (H_dst, W_dst) numpy array (float32).
 61    """
 62    from rasterio.warp import Resampling, reproject
 63
 64    h_dst, w_dst = target_shape
 65
 66    # Mask nodata before reproject to avoid summing sentinel values.
 67    source_masked = np.where(source == nodata, 0.0, source).astype(np.float32)
 68    dst = np.zeros((h_dst, w_dst), dtype=np.float32)
 69
 70    resampling = Resampling.sum if method == "sum" else Resampling.nearest
 71
 72    reproject(
 73        source=source_masked,
 74        destination=dst,
 75        src_transform=source_transform,
 76        src_crs=source_crs,
 77        dst_transform=target_transform,
 78        dst_crs=target_crs,
 79        resampling=resampling,
 80    )
 81    return dst
 82
 83
 84def build_host_static_nc(
 85    human: np.ndarray,
 86    cattle: np.ndarray,
 87    goats: np.ndarray,
 88    sheep: np.ndarray,
 89    urban_class: np.ndarray,
 90    output_path: pathlib.Path,
 91    grid_spec: dict,
 92    *,
 93    nodata: float = _NODATA,
 94    pigs: np.ndarray | None = None,
 95    chickens: np.ndarray | None = None,
 96    building_fraction: np.ndarray | None = None,
 97    wildlife_host_proxy: np.ndarray | None = None,
 98) -> pathlib.Path:
 99    """Write the static host density NetCDF for the ABM engine.
100
101    The NetCDF has 5 core data variables on (y, x), plus up to 4 optional:
102        * ``human``               — persons per ABM cell (float32)
103        * ``cattle``              — cattle per ABM cell (float32)
104        * ``goats``               — goats per ABM cell (float32)
105        * ``sheep``               — sheep per ABM cell (float32)
106        * ``urban_class``         — settlement class code (int32: 30/50)
107        * ``pigs``                — pigs per ABM cell (float32, optional)
108        * ``chickens``            — chickens per ABM cell (float32, optional)
109        * ``building_fraction``   — building footprint fraction [0,1] (float32, optional)
110        * ``wildlife_host_proxy`` — wildlife host suitability [0,1] (float32, optional)
111
112    Global attributes include CRS WKT, grid transform, and nodata sentinel.
113
114    Args:
115        human: (H, W) human population count per cell.
116        cattle: (H, W) cattle count per cell.
117        goats: (H, W) goats count per cell.
118        sheep: (H, W) sheep count per cell.
119        urban_class: (H, W) GHS-SMOD class (30=urban, 50=rural).
120        output_path: path to write the NetCDF.
121        grid_spec: dict with ``crs`` (WKT/str), ``transform`` (affine),
122                   ``height``, ``width``.
123        nodata: sentinel for missing values.
124
125    Returns:
126        Path to the written NetCDF file.
127    """
128    output_path.parent.mkdir(parents=True, exist_ok=True)
129
130    H, W = human.shape
131    assert cattle.shape == (H, W), f"cattle shape {cattle.shape} != ({H}, {W})"
132    assert goats.shape == (H, W), f"goats shape {goats.shape} != ({H}, {W})"
133    assert sheep.shape == (H, W), f"sheep shape {sheep.shape} != ({H}, {W})"
134    assert urban_class.shape == (H, W), f"urban_class shape {urban_class.shape} != ({H}, {W})"
135
136    # Build coordinate arrays from the transform
137    transform = grid_spec["transform"]
138    xs = np.array([transform.c + i * transform.a for i in range(W)], dtype=np.float64)
139    ys = np.array([transform.f + j * transform.e for j in range(H)], dtype=np.float64)
140
141    ds = xr.Dataset(
142        {
143            "human": xr.DataArray(
144                human.astype(np.float32),
145                dims=("y", "x"),
146                attrs={"long_name": "Human population count", "units": "persons/cell", "nodata": nodata},
147            ),
148            "cattle": xr.DataArray(
149                cattle.astype(np.float32),
150                dims=("y", "x"),
151                attrs={"long_name": "Cattle count", "units": "animals/cell", "nodata": nodata},
152            ),
153            "goats": xr.DataArray(
154                goats.astype(np.float32),
155                dims=("y", "x"),
156                attrs={"long_name": "Goat count", "units": "animals/cell", "nodata": nodata},
157            ),
158            "sheep": xr.DataArray(
159                sheep.astype(np.float32),
160                dims=("y", "x"),
161                attrs={"long_name": "Sheep count", "units": "animals/cell", "nodata": nodata},
162            ),
163            "urban_class": xr.DataArray(
164                urban_class.astype(np.int32),
165                dims=("y", "x"),
166                attrs={
167                    "long_name": "GHS-SMOD settlement class",
168                    "units": "class code (30=urban, 50=rural)",
169                    "nodata": _NODATA_INT,
170                },
171            ),
172        },
173        coords={
174            "x": xr.DataArray(xs, dims="x", attrs={"axis": "X", "standard_name": "longitude", "units": "degrees_east"}),
175            "y": xr.DataArray(ys, dims="y", attrs={"axis": "Y", "standard_name": "latitude", "units": "degrees_north"}),
176        },
177        attrs={
178            "Conventions": "CF-1.8",
179            "title": "MalariaSentinel static host density",
180            "source_crs": str(grid_spec["crs"]),
181            "grid_height": H,
182            "grid_width": W,
183            "nodata": nodata,
184            "generated_by": "mal-commonlib build_hosts",
185        },
186    )
187
188    # Optional variables
189    all_vars = ["human", "cattle", "goats", "sheep", "urban_class"]
190    if pigs is not None:
191        assert pigs.shape == (H, W), f"pigs shape {pigs.shape} != ({H}, {W})"
192        ds["pigs"] = xr.DataArray(
193            pigs.astype(np.float32), dims=("y", "x"),
194            attrs={"long_name": "Pig count", "units": "animals/cell", "nodata": nodata},
195        )
196        all_vars.append("pigs")
197    if chickens is not None:
198        assert chickens.shape == (H, W), f"chickens shape {chickens.shape} != ({H}, {W})"
199        ds["chickens"] = xr.DataArray(
200            chickens.astype(np.float32), dims=("y", "x"),
201            attrs={"long_name": "Chicken count", "units": "animals/cell", "nodata": nodata},
202        )
203        all_vars.append("chickens")
204    if building_fraction is not None:
205        assert building_fraction.shape == (H, W), f"building_fraction shape {building_fraction.shape} != ({H}, {W})"
206        ds["building_fraction"] = xr.DataArray(
207            building_fraction.astype(np.float32), dims=("y", "x"),
208            attrs={"long_name": "Building footprint fraction", "units": "fraction [0,1]", "nodata": nodata},
209        )
210        all_vars.append("building_fraction")
211    if wildlife_host_proxy is not None:
212        assert wildlife_host_proxy.shape == (H, W), f"wildlife_host_proxy shape {wildlife_host_proxy.shape} != ({H}, {W})"
213        ds["wildlife_host_proxy"] = xr.DataArray(
214            wildlife_host_proxy.astype(np.float32), dims=("y", "x"),
215            attrs={"long_name": "Wildlife host proxy suitability", "units": "suitability [0,1]", "nodata": nodata},
216        )
217        all_vars.append("wildlife_host_proxy")
218
219    # Write CRS as a coordinate variable (CF convention)
220    crs_var = xr.DataArray(
221        np.int32(0),
222        attrs={
223            "grid_mapping_name": "transverse_mercator",
224            "crs_wkt": str(grid_spec["crs"]),
225        },
226    )
227    ds["crs"] = crs_var
228    for var_name in all_vars:
229        ds[var_name].attrs["grid_mapping"] = "crs"
230
231    ds.to_netcdf(str(output_path), engine="netcdf4")
232    return output_path
233
234
235def write_manifest(
236    output_path: pathlib.Path,
237    human: np.ndarray,
238    cattle: np.ndarray,
239    goats: np.ndarray,
240    sheep: np.ndarray,
241    urban_class: np.ndarray,
242    grid_spec: dict,
243    *,
244    pigs: np.ndarray | None = None,
245    chickens: np.ndarray | None = None,
246    building_fraction: np.ndarray | None = None,
247    wildlife_host_proxy: np.ndarray | None = None,
248) -> pathlib.Path:
249    """Write a JSON manifest describing the host static NetCDF.
250
251    The manifest records summary statistics and grid metadata so that
252    the ABM engine can validate inputs before reading the NetCDF.
253    """
254    manifest_path = output_path.parent / "host_manifest.json"
255    H, W = human.shape
256
257    def _stats(arr: np.ndarray, name: str) -> dict:
258        """Summary statistics of one array (min, max, mean, total, nodata count), ignoring NoData cells."""
259        valid = arr[arr != _NODATA]
260        return {
261            "variable": name,
262            "shape": list(arr.shape),
263            "min": float(valid.min()) if valid.size > 0 else 0.0,
264            "max": float(valid.max()) if valid.size > 0 else 0.0,
265            "mean": float(valid.mean()) if valid.size > 0 else 0.0,
266            "total": float(valid.sum()) if valid.size > 0 else 0.0,
267            "nodata_count": int((arr == _NODATA).sum()),
268        }
269
270    manifest = {
271        "netcdf_path": str(output_path.name),
272        "grid": {
273            "crs": str(grid_spec["crs"]),
274            "height": H,
275            "width": W,
276        },
277        "variables": [
278            _stats(human, "human"),
279            _stats(cattle, "cattle"),
280            _stats(goats, "goats"),
281            _stats(sheep, "sheep"),
282            _stats(urban_class.astype(np.float32), "urban_class"),
283        ],
284    }
285
286    # Optional variables
287    if pigs is not None:
288        manifest["variables"].append(_stats(pigs, "pigs"))
289    if chickens is not None:
290        manifest["variables"].append(_stats(chickens, "chickens"))
291    if building_fraction is not None:
292        manifest["variables"].append(_stats(building_fraction, "building_fraction"))
293    if wildlife_host_proxy is not None:
294        manifest["variables"].append(_stats(wildlife_host_proxy, "wildlife_host_proxy"))
295
296    manifest_path.parent.mkdir(parents=True, exist_ok=True)
297    manifest_path.write_text(json.dumps(manifest, indent=2))
298    return manifest_path
def aggregate_to_grid( source: numpy.ndarray, source_transform: Any, source_crs: Any, target_transform: Any, target_crs: Any, target_shape: tuple[int, int], method: str = 'sum', nodata: float = -9999.0) -> numpy.ndarray:
34def aggregate_to_grid(
35    source: np.ndarray,
36    source_transform: Any,
37    source_crs: Any,
38    target_transform: Any,
39    target_crs: Any,
40    target_shape: tuple[int, int],
41    method: str = "sum",
42    nodata: float = _NODATA,
43) -> np.ndarray:
44    """Aggregate a source raster to a target grid.
45
46    Uses ``rasterio.warp.reproject`` under the hood. For ``method="sum"``
47    the resampling is ``Resampling.sum`` (conservative / area-weighted).
48    For ``method="nearest"`` it is ``Resampling.nearest`` (categorical).
49
50    Args:
51        source: (H_src, W_src) numpy array.
52        source_transform: affine transform of the source.
53        source_crs: CRS of the source (anything rasterio accepts).
54        target_transform: affine transform of the target grid.
55        target_crs: CRS of the target grid.
56        target_shape: (H_dst, W_dst) of the target grid.
57        method: "sum" (conservative) or "nearest" (categorical).
58        nodata: sentinel value to mask before summing (default: the NoData sentinel).
59
60    Returns:
61        (H_dst, W_dst) numpy array (float32).
62    """
63    from rasterio.warp import Resampling, reproject
64
65    h_dst, w_dst = target_shape
66
67    # Mask nodata before reproject to avoid summing sentinel values.
68    source_masked = np.where(source == nodata, 0.0, source).astype(np.float32)
69    dst = np.zeros((h_dst, w_dst), dtype=np.float32)
70
71    resampling = Resampling.sum if method == "sum" else Resampling.nearest
72
73    reproject(
74        source=source_masked,
75        destination=dst,
76        src_transform=source_transform,
77        src_crs=source_crs,
78        dst_transform=target_transform,
79        dst_crs=target_crs,
80        resampling=resampling,
81    )
82    return dst

Aggregate a source raster to a target grid.

Uses rasterio.warp.reproject under the hood. For method="sum" the resampling is Resampling.sum (conservative / area-weighted). For method="nearest" it is Resampling.nearest (categorical).

Args: source: (H_src, W_src) numpy array. source_transform: affine transform of the source. source_crs: CRS of the source (anything rasterio accepts). target_transform: affine transform of the target grid. target_crs: CRS of the target grid. target_shape: (H_dst, W_dst) of the target grid. method: "sum" (conservative) or "nearest" (categorical). nodata: sentinel value to mask before summing (default: the NoData sentinel).

Returns: (H_dst, W_dst) numpy array (float32).

def build_host_static_nc( human: numpy.ndarray, cattle: numpy.ndarray, goats: numpy.ndarray, sheep: numpy.ndarray, urban_class: numpy.ndarray, output_path: pathlib.Path, grid_spec: dict, *, nodata: float = -9999.0, pigs: numpy.ndarray | None = None, chickens: numpy.ndarray | None = None, building_fraction: numpy.ndarray | None = None, wildlife_host_proxy: numpy.ndarray | None = None) -> pathlib.Path:
 85def build_host_static_nc(
 86    human: np.ndarray,
 87    cattle: np.ndarray,
 88    goats: np.ndarray,
 89    sheep: np.ndarray,
 90    urban_class: np.ndarray,
 91    output_path: pathlib.Path,
 92    grid_spec: dict,
 93    *,
 94    nodata: float = _NODATA,
 95    pigs: np.ndarray | None = None,
 96    chickens: np.ndarray | None = None,
 97    building_fraction: np.ndarray | None = None,
 98    wildlife_host_proxy: np.ndarray | None = None,
 99) -> pathlib.Path:
100    """Write the static host density NetCDF for the ABM engine.
101
102    The NetCDF has 5 core data variables on (y, x), plus up to 4 optional:
103        * ``human``               — persons per ABM cell (float32)
104        * ``cattle``              — cattle per ABM cell (float32)
105        * ``goats``               — goats per ABM cell (float32)
106        * ``sheep``               — sheep per ABM cell (float32)
107        * ``urban_class``         — settlement class code (int32: 30/50)
108        * ``pigs``                — pigs per ABM cell (float32, optional)
109        * ``chickens``            — chickens per ABM cell (float32, optional)
110        * ``building_fraction``   — building footprint fraction [0,1] (float32, optional)
111        * ``wildlife_host_proxy`` — wildlife host suitability [0,1] (float32, optional)
112
113    Global attributes include CRS WKT, grid transform, and nodata sentinel.
114
115    Args:
116        human: (H, W) human population count per cell.
117        cattle: (H, W) cattle count per cell.
118        goats: (H, W) goats count per cell.
119        sheep: (H, W) sheep count per cell.
120        urban_class: (H, W) GHS-SMOD class (30=urban, 50=rural).
121        output_path: path to write the NetCDF.
122        grid_spec: dict with ``crs`` (WKT/str), ``transform`` (affine),
123                   ``height``, ``width``.
124        nodata: sentinel for missing values.
125
126    Returns:
127        Path to the written NetCDF file.
128    """
129    output_path.parent.mkdir(parents=True, exist_ok=True)
130
131    H, W = human.shape
132    assert cattle.shape == (H, W), f"cattle shape {cattle.shape} != ({H}, {W})"
133    assert goats.shape == (H, W), f"goats shape {goats.shape} != ({H}, {W})"
134    assert sheep.shape == (H, W), f"sheep shape {sheep.shape} != ({H}, {W})"
135    assert urban_class.shape == (H, W), f"urban_class shape {urban_class.shape} != ({H}, {W})"
136
137    # Build coordinate arrays from the transform
138    transform = grid_spec["transform"]
139    xs = np.array([transform.c + i * transform.a for i in range(W)], dtype=np.float64)
140    ys = np.array([transform.f + j * transform.e for j in range(H)], dtype=np.float64)
141
142    ds = xr.Dataset(
143        {
144            "human": xr.DataArray(
145                human.astype(np.float32),
146                dims=("y", "x"),
147                attrs={"long_name": "Human population count", "units": "persons/cell", "nodata": nodata},
148            ),
149            "cattle": xr.DataArray(
150                cattle.astype(np.float32),
151                dims=("y", "x"),
152                attrs={"long_name": "Cattle count", "units": "animals/cell", "nodata": nodata},
153            ),
154            "goats": xr.DataArray(
155                goats.astype(np.float32),
156                dims=("y", "x"),
157                attrs={"long_name": "Goat count", "units": "animals/cell", "nodata": nodata},
158            ),
159            "sheep": xr.DataArray(
160                sheep.astype(np.float32),
161                dims=("y", "x"),
162                attrs={"long_name": "Sheep count", "units": "animals/cell", "nodata": nodata},
163            ),
164            "urban_class": xr.DataArray(
165                urban_class.astype(np.int32),
166                dims=("y", "x"),
167                attrs={
168                    "long_name": "GHS-SMOD settlement class",
169                    "units": "class code (30=urban, 50=rural)",
170                    "nodata": _NODATA_INT,
171                },
172            ),
173        },
174        coords={
175            "x": xr.DataArray(xs, dims="x", attrs={"axis": "X", "standard_name": "longitude", "units": "degrees_east"}),
176            "y": xr.DataArray(ys, dims="y", attrs={"axis": "Y", "standard_name": "latitude", "units": "degrees_north"}),
177        },
178        attrs={
179            "Conventions": "CF-1.8",
180            "title": "MalariaSentinel static host density",
181            "source_crs": str(grid_spec["crs"]),
182            "grid_height": H,
183            "grid_width": W,
184            "nodata": nodata,
185            "generated_by": "mal-commonlib build_hosts",
186        },
187    )
188
189    # Optional variables
190    all_vars = ["human", "cattle", "goats", "sheep", "urban_class"]
191    if pigs is not None:
192        assert pigs.shape == (H, W), f"pigs shape {pigs.shape} != ({H}, {W})"
193        ds["pigs"] = xr.DataArray(
194            pigs.astype(np.float32), dims=("y", "x"),
195            attrs={"long_name": "Pig count", "units": "animals/cell", "nodata": nodata},
196        )
197        all_vars.append("pigs")
198    if chickens is not None:
199        assert chickens.shape == (H, W), f"chickens shape {chickens.shape} != ({H}, {W})"
200        ds["chickens"] = xr.DataArray(
201            chickens.astype(np.float32), dims=("y", "x"),
202            attrs={"long_name": "Chicken count", "units": "animals/cell", "nodata": nodata},
203        )
204        all_vars.append("chickens")
205    if building_fraction is not None:
206        assert building_fraction.shape == (H, W), f"building_fraction shape {building_fraction.shape} != ({H}, {W})"
207        ds["building_fraction"] = xr.DataArray(
208            building_fraction.astype(np.float32), dims=("y", "x"),
209            attrs={"long_name": "Building footprint fraction", "units": "fraction [0,1]", "nodata": nodata},
210        )
211        all_vars.append("building_fraction")
212    if wildlife_host_proxy is not None:
213        assert wildlife_host_proxy.shape == (H, W), f"wildlife_host_proxy shape {wildlife_host_proxy.shape} != ({H}, {W})"
214        ds["wildlife_host_proxy"] = xr.DataArray(
215            wildlife_host_proxy.astype(np.float32), dims=("y", "x"),
216            attrs={"long_name": "Wildlife host proxy suitability", "units": "suitability [0,1]", "nodata": nodata},
217        )
218        all_vars.append("wildlife_host_proxy")
219
220    # Write CRS as a coordinate variable (CF convention)
221    crs_var = xr.DataArray(
222        np.int32(0),
223        attrs={
224            "grid_mapping_name": "transverse_mercator",
225            "crs_wkt": str(grid_spec["crs"]),
226        },
227    )
228    ds["crs"] = crs_var
229    for var_name in all_vars:
230        ds[var_name].attrs["grid_mapping"] = "crs"
231
232    ds.to_netcdf(str(output_path), engine="netcdf4")
233    return output_path

Write the static host density NetCDF for the ABM engine.

The NetCDF has 5 core data variables on (y, x), plus up to 4 optional: * human — persons per ABM cell (float32) * cattle — cattle per ABM cell (float32) * goats — goats per ABM cell (float32) * sheep — sheep per ABM cell (float32) * urban_class — settlement class code (int32: 30/50) * pigs — pigs per ABM cell (float32, optional) * chickens — chickens per ABM cell (float32, optional) * building_fraction — building footprint fraction [0,1] (float32, optional) * wildlife_host_proxy — wildlife host suitability [0,1] (float32, optional)

Global attributes include CRS WKT, grid transform, and nodata sentinel.

Args: human: (H, W) human population count per cell. cattle: (H, W) cattle count per cell. goats: (H, W) goats count per cell. sheep: (H, W) sheep count per cell. urban_class: (H, W) GHS-SMOD class (30=urban, 50=rural). output_path: path to write the NetCDF. grid_spec: dict with crs (WKT/str), transform (affine), height, width. nodata: sentinel for missing values.

Returns: Path to the written NetCDF file.

def write_manifest( output_path: pathlib.Path, human: numpy.ndarray, cattle: numpy.ndarray, goats: numpy.ndarray, sheep: numpy.ndarray, urban_class: numpy.ndarray, grid_spec: dict, *, pigs: numpy.ndarray | None = None, chickens: numpy.ndarray | None = None, building_fraction: numpy.ndarray | None = None, wildlife_host_proxy: numpy.ndarray | None = None) -> pathlib.Path:
236def write_manifest(
237    output_path: pathlib.Path,
238    human: np.ndarray,
239    cattle: np.ndarray,
240    goats: np.ndarray,
241    sheep: np.ndarray,
242    urban_class: np.ndarray,
243    grid_spec: dict,
244    *,
245    pigs: np.ndarray | None = None,
246    chickens: np.ndarray | None = None,
247    building_fraction: np.ndarray | None = None,
248    wildlife_host_proxy: np.ndarray | None = None,
249) -> pathlib.Path:
250    """Write a JSON manifest describing the host static NetCDF.
251
252    The manifest records summary statistics and grid metadata so that
253    the ABM engine can validate inputs before reading the NetCDF.
254    """
255    manifest_path = output_path.parent / "host_manifest.json"
256    H, W = human.shape
257
258    def _stats(arr: np.ndarray, name: str) -> dict:
259        """Summary statistics of one array (min, max, mean, total, nodata count), ignoring NoData cells."""
260        valid = arr[arr != _NODATA]
261        return {
262            "variable": name,
263            "shape": list(arr.shape),
264            "min": float(valid.min()) if valid.size > 0 else 0.0,
265            "max": float(valid.max()) if valid.size > 0 else 0.0,
266            "mean": float(valid.mean()) if valid.size > 0 else 0.0,
267            "total": float(valid.sum()) if valid.size > 0 else 0.0,
268            "nodata_count": int((arr == _NODATA).sum()),
269        }
270
271    manifest = {
272        "netcdf_path": str(output_path.name),
273        "grid": {
274            "crs": str(grid_spec["crs"]),
275            "height": H,
276            "width": W,
277        },
278        "variables": [
279            _stats(human, "human"),
280            _stats(cattle, "cattle"),
281            _stats(goats, "goats"),
282            _stats(sheep, "sheep"),
283            _stats(urban_class.astype(np.float32), "urban_class"),
284        ],
285    }
286
287    # Optional variables
288    if pigs is not None:
289        manifest["variables"].append(_stats(pigs, "pigs"))
290    if chickens is not None:
291        manifest["variables"].append(_stats(chickens, "chickens"))
292    if building_fraction is not None:
293        manifest["variables"].append(_stats(building_fraction, "building_fraction"))
294    if wildlife_host_proxy is not None:
295        manifest["variables"].append(_stats(wildlife_host_proxy, "wildlife_host_proxy"))
296
297    manifest_path.parent.mkdir(parents=True, exist_ok=True)
298    manifest_path.write_text(json.dumps(manifest, indent=2))
299    return manifest_path

Write a JSON manifest describing the host static NetCDF.

The manifest records summary statistics and grid metadata so that the ABM engine can validate inputs before reading the NetCDF.