mal_core.ingest

Ingest stage — build ABM-ready environmental tensors for an AOI.

 1"""Ingest stage — build ABM-ready environmental tensors for an AOI."""
 2from .env import build_env_tensor
 3from .hosts import build_host_dataset
 4from .mobility import build_mobility_dataset
 5
 6__all__ = [
 7    "build_env_tensor",
 8    "build_host_dataset",
 9    "build_mobility_dataset",
10]
def build_env_tensor( aoi, year: int, month: int, output_dir: pathlib.Path, *, data_root: pathlib.Path | None = None) -> dict:
113def build_env_tensor(
114    aoi,
115    year: int,
116    month: int,
117    output_dir: pathlib.Path,
118    *,
119    data_root: pathlib.Path | None = None,
120) -> dict:
121    """Build the daily env NC + static habitat patches for an AOI.
122
123    Delegates the NC build to the canonical builder in daily_nc.py, then
124    derives the static candidate-cell gpkg from the statics the NC carry.
125
126    Args:
127        aoi: the AOI object or a string slug.
128        year: year (metadata; the NC is multi-year daily).
129        month: month 1-12 (metadata only).
130        output_dir: directory containing the downloaded raw inputs; the NC
131            and habitat patches are written here too.
132        data_root: optional root for manifest registration (default: the
133            conventional ``data/`` layout).
134
135    Returns:
136        dict with 'env_path', 'habitat_path', and other metadata.
137    """
138    if isinstance(aoi, str):
139        aoi = AOI.from_slug(aoi)
140
141    from .daily_nc import build_daily_env_nc
142    from ..download.catalog import INGEST_ARTIFACTS
143
144    nc_result = build_daily_env_nc(
145        aoi=aoi.slug,
146        data_dir=output_dir,
147    )
148    register_dataset(
149        aoi.slug, INGEST_ARTIFACTS["env"].key, year,
150        pathlib.Path(nc_result["env_path"]).name,
151        type="time-series",
152        variables=nc_result["variables"],
153        format="nc",
154        license="CHIRPS-Cite+Copernicus-Cite+CC-BY-4.0",
155        attribution=(
156            "Derived from CHIRPS v2 (Funk et al. 2014), JRC GSW v1.4 "
157            "(© EU/JRC, CC BY 4.0), ERA5-Land (Contains modified Copernicus "
158            "Climate Change Service information [Year]) and Google Dynamic "
159            "World V1 (© Google, CC BY 4.0; contains modified Copernicus "
160            "Sentinel data [Year])."
161        ),
162        data_root=data_root,
163    )
164
165    env_path = pathlib.Path(nc_result["env_path"])
166    statics = {
167        "jrc_persistent": _read_static(env_path, aoi, "jrc_persistent"),
168        "lc_built": _read_static(env_path, aoi, "lc_built"),
169        "lc_wetland": _read_static(env_path, aoi, "lc_wetland"),
170        "lc_open_plus_water": _read_static(env_path, aoi, "lc_open_plus_water"),
171        "lc_crop": _read_static(env_path, aoi, "lc_crop"),
172    }
173    habitat_path = output_dir / f"{aoi.slug}_habitat_patches.gpkg"
174    _write_habitat_patches_gpkg(habitat_path, statics, aoi)
175    register_dataset(
176        aoi.slug, INGEST_ARTIFACTS["habitat"].key, year, habitat_path.name,
177        type="time-series", format="gpkg",
178        license="CC-BY-4.0",
179        attribution=(
180            "Derived from JRC GSW v1.4 (© EU/JRC, CC BY 4.0) and Google "
181            "Dynamic World V1 (© Google, CC BY 4.0; contains modified "
182            "Copernicus Sentinel data [Year])."
183        ),
184        variables=[
185            "hab_type", "habitat_potential", "row", "col",
186        ] + [f"hab_{g}" for g in statics],
187        data_root=data_root,
188    )
189    nc_result["habitat_path"] = str(habitat_path)
190    try:
191        from mal_commonlib.data.licenses import warn_manifest_limits
192
193        warn_manifest_limits(aoi.slug, data_root)
194    except Exception as e:  # never break ingest over a warning
195        logging.getLogger(__name__).debug("license warning skipped: %s", e)
196    return nc_result

Build the daily env NC + static habitat patches for an AOI.

Delegates the NC build to the canonical builder in daily_nc.py, then derives the static candidate-cell gpkg from the statics the NC carry.

Args: aoi: the AOI object or a string slug. year: year (metadata; the NC is multi-year daily). month: month 1-12 (metadata only). output_dir: directory containing the downloaded raw inputs; the NC and habitat patches are written here too. data_root: optional root for manifest registration (default: the conventional data/ layout).

Returns: dict with 'env_path', 'habitat_path', and other metadata.

def build_host_dataset( aoi: mal_commonlib.AOI, *, output_dir: pathlib.Path, worldpop_year: int = 2019, cache_dir: pathlib.Path | None = None, skip_buildings: bool = False, skip_wildlife: bool = False) -> dict:
 38def build_host_dataset(
 39    aoi: AOI,
 40    *,
 41    output_dir: pathlib.Path,
 42    worldpop_year: int = 2019,
 43    cache_dir: pathlib.Path | None = None,
 44    skip_buildings: bool = False,
 45    skip_wildlife: bool = False,
 46) -> dict:
 47    """Build static host density NetCDF for the ABM engine.
 48
 49    Args:
 50        aoi: the AOI object.
 51        output_dir: directory for host_static.nc + manifest.
 52        worldpop_year: WorldPop product year.
 53        cache_dir: local cache for downloads.
 54        skip_buildings: skip Overture buildings (use urban_class heuristic).
 55        skip_wildlife: skip wildlife host proxy (use the neutral constant
 56            applied in this module).
 57
 58    Returns:
 59        dict with 'nc_path', 'manifest_path', and stats.
 60    """
 61    h, w = aoi.cells_per_side()
 62    target_transform = from_bounds(*aoi.bbox, w, h)
 63    grid_spec = {
 64        "crs": aoi.crs,
 65        "transform": target_transform,
 66        "height": h,
 67        "width": w,
 68    }
 69
 70    results: dict = {
 71        "aoi_slug": aoi.slug,
 72        "grid": f"{h}x{w}",
 73    }
 74
 75    # 1. Human population (WorldPop, ~100m) — sum-preserving aggregation
 76    pop_da = load_worldpop_population(aoi, year=worldpop_year, cache_dir=cache_dir)
 77    human = aggregate_to_grid(
 78        pop_da.values,
 79        pop_da.rio.transform(),
 80        pop_da.rio.crs,
 81        target_transform,
 82        aoi.crs_obj,
 83        (h, w),
 84        method="sum",
 85    )
 86    _NODATA = _ingest_nodata()
 87    human_total = float(human[human != _NODATA].sum()) if (human == _NODATA).any() else float(human.sum())
 88    results["human_total"] = human_total
 89
 90    # 2. Livestock (GLW4, ~10km) — sum-preserving aggregation
 91    livestock_totals: dict[str, np.ndarray] = {}
 92
 93    for species in LIVESTOCK_SPECIES:
 94        livestock_da = load_glw_livestock(aoi, species=species, cache_dir=cache_dir)
 95        livestock_arr = aggregate_to_grid(
 96            livestock_da.values,
 97            livestock_da.rio.transform(),
 98            livestock_da.rio.crs,
 99            target_transform,
100            aoi.crs_obj,
101            (h, w),
102            method="sum",
103        )
104        livestock_totals[species] = livestock_arr
105
106    livestock_total = sum(
107        float(arr[arr != _NODATA].sum()) for arr in livestock_totals.values()
108    )
109    results["livestock_total"] = livestock_total
110
111    # 3. Urban/rural classification (GHSL, 250m) — nearest-neighbour
112    try:
113        smod_da = load_ghsl_urban_class(aoi, cache_dir=cache_dir)
114        urban_class = aggregate_to_grid(
115            smod_da.values.astype(np.float32),
116            smod_da.rio.transform(),
117            smod_da.rio.crs,
118            target_transform,
119            aoi.crs_obj,
120            (h, w),
121            method="nearest",
122        )
123        urban_class = urban_class.astype(np.int32)
124        # Reclassify GHSL SMOD R2023A classes:
125        #   30 → 30 (urban), 20-29 → 50 (rural), 0-19 → 20 (water)
126        reclassified = np.where(urban_class == 30, 30, np.where(
127            (urban_class >= 20) & (urban_class < 30), 50,
128            np.where((urban_class >= 0) & (urban_class < 20), 20, 50)
129        )).astype(np.int32)
130        urban_class = reclassified
131        n_urban = int((urban_class == 30).sum())
132        n_rural = int((urban_class == 50).sum())
133        results["urban_cells"] = n_urban
134        results["rural_cells"] = n_rural
135    except Exception as exc:
136        print(f"  WARNING: GHSL load failed: {exc}", file=sys.stderr)
137        print("  Filling urban_class with rural default (50).", file=sys.stderr)
138        urban_class = np.full((h, w), 50, dtype=np.int32)
139
140    # 4. Building fraction (Overture Maps, ~1m) — conservative aggregation
141    building_frac = None
142    if skip_buildings:
143        building_frac = np.where(urban_class == 30, 0.6, 0.1).astype(np.float32)
144    else:
145        try:
146            from mal_commonlib.data.loaders.buildings import load_buildings_fraction
147
148            bld_da = load_buildings_fraction(aoi, cache_dir=cache_dir)
149            building_frac = aggregate_to_grid(
150                bld_da.values,
151                bld_da.rio.transform(),
152                bld_da.rio.crs,
153                target_transform,
154                aoi.crs_obj,
155                (h, w),
156                method="sum",
157            )
158        except Exception as exc:
159            print(f"  WARNING: Building loader failed: {exc}", file=sys.stderr)
160            print("  Falling back to urban_class heuristic.", file=sys.stderr)
161            building_frac = np.where(urban_class == 30, 0.6, 0.1).astype(np.float32)
162
163    # 5. Wildlife host proxy (WorldCover + JRC GSW + buildings)
164    wildlife_proxy = None
165    if skip_wildlife:
166        wildlife_proxy = np.full((h, w), 0.3, dtype=np.float32)
167    else:
168        try:
169            from mal_commonlib.data.loaders.wildlife import load_wildlife_host_proxy
170
171            wl_da = load_wildlife_host_proxy(aoi, cache_dir=cache_dir)
172            wildlife_proxy = aggregate_to_grid(
173                wl_da.values,
174                wl_da.rio.transform(),
175                wl_da.rio.crs,
176                target_transform,
177                aoi.crs_obj,
178                (h, w),
179                method="nearest",
180            )
181        except Exception as exc:
182            print(f"  WARNING: Wildlife loader failed: {exc}", file=sys.stderr)
183            print("  Using constant 0.3.", file=sys.stderr)
184            wildlife_proxy = np.full((h, w), 0.3, dtype=np.float32)
185
186    # 6. Write NetCDF + manifest
187    output_dir.mkdir(parents=True, exist_ok=True)
188    nc_path = output_dir / f"{aoi.slug}_host_static.nc"
189    build_host_static_nc(
190        human=human,
191        cattle=livestock_totals["cattle"],
192        goats=livestock_totals["goats"],
193        sheep=livestock_totals["sheep"],
194        urban_class=urban_class,
195        output_path=nc_path,
196        grid_spec=grid_spec,
197        pigs=livestock_totals.get("pigs"),
198        chickens=livestock_totals.get("chickens"),
199        building_fraction=building_frac,
200        wildlife_host_proxy=wildlife_proxy,
201    )
202    manifest_path = write_manifest(
203        output_path=nc_path,
204        human=human,
205        cattle=livestock_totals["cattle"],
206        goats=livestock_totals["goats"],
207        sheep=livestock_totals["sheep"],
208        urban_class=urban_class,
209        grid_spec=grid_spec,
210        pigs=livestock_totals.get("pigs"),
211        chickens=livestock_totals.get("chickens"),
212        building_fraction=building_frac,
213        wildlife_host_proxy=wildlife_proxy,
214    )
215
216    results["nc_path"] = str(nc_path)
217    results["manifest_path"] = str(manifest_path)
218
219    # Register in manifest
220    from ..download.catalog import INGEST_ARTIFACTS
221    register_dataset(
222        aoi.slug, INGEST_ARTIFACTS["host_static"].key, None,
223        str(nc_path.name),
224        required_for_abm=True,
225        variables=["human", "cattle", "goats", "sheep", "pigs",
226                    "chickens", "urban_class", "building_fraction",
227                    "wildlife_host_proxy"],
228        format="nc",
229        license="CC-BY-4.0+ODbL-1.0+NASA-Cite",
230        attribution=(
231            "Derived from WorldPop (CC BY 4.0), FAO GLW4 (CC BY 4.0), "
232            "GHS-SMOD (© EU/JRC, CC BY 4.0), Overture buildings "
233            "(© OpenStreetMap contributors, Overture Maps Foundation, "
234            "ODbL 1.0) and ESA WorldCover (© ESA WorldCover project [2021] "
235            "/ Contains modified Copernicus Sentinel data (2021) processed "
236            "by ESA WorldCover consortium)."
237        ),
238    )
239    register_dataset(
240        aoi.slug, INGEST_ARTIFACTS["host_manifest"].key, None,
241        str(manifest_path.name),
242    )
243    try:
244        from mal_commonlib.data.licenses import warn_manifest_limits
245
246        warn_manifest_limits(aoi.slug)
247    except Exception as e:  # never break ingest over a warning
248        logging.getLogger(__name__).debug("license warning skipped: %s", e)
249
250    return results

Build static host density NetCDF for the ABM engine.

Args: aoi: the AOI object. output_dir: directory for host_static.nc + manifest. worldpop_year: WorldPop product year. cache_dir: local cache for downloads. skip_buildings: skip Overture buildings (use urban_class heuristic). skip_wildlife: skip wildlife host proxy (use the neutral constant applied in this module).

Returns: dict with 'nc_path', 'manifest_path', and stats.

def build_mobility_dataset( hosts_path: pathlib.Path, *, output_dir: pathlib.Path, aoi_slug: str = 'ghana', cell_size_km: float = 1.0, beta_day: float = 0.05, beta_night: float = 0.5, beta_livestock: float = 0.1, max_distance_km: float = 50.0, sparsity_threshold: float = 0.0005) -> dict:
 38def build_mobility_dataset(
 39    hosts_path: pathlib.Path,
 40    *,
 41    output_dir: pathlib.Path,
 42    aoi_slug: str = "ghana",
 43    cell_size_km: float = 1.0,
 44    beta_day: float = 0.05,
 45    beta_night: float = 0.5,
 46    beta_livestock: float = 0.1,
 47    max_distance_km: float = 50.0,
 48    sparsity_threshold: float = 5e-4,
 49) -> dict:
 50    """Build gravity-model mobility OD matrices from host_static.nc.
 51
 52    Matrices are built and written one at a time so peak RAM stays at
 53    ~one matrix (the livestock matrix dominates at 1km Ghana resolution).
 54
 55    Args:
 56        hosts_path: path to host_static.nc.
 57        output_dir: directory for CSR files.
 58        aoi_slug: AOI identifier for manifest registration.
 59        cell_size_km: grid cell size in km.
 60        beta_day: friction for human daytime mobility.
 61        beta_night: friction for human nighttime mobility.
 62        beta_livestock: friction for livestock mobility.
 63        max_distance_km: maximum mobility distance.
 64        sparsity_threshold: minimum normalised probability kept per entry.
 65
 66    Returns:
 67        dict with 'files', 'manifest_path', and stats.
 68    """
 69    if not hosts_path.exists():
 70        raise FileNotFoundError(f"host_static.nc not found: {hosts_path}")
 71
 72    host_data = _load_host_data(hosts_path)
 73    shape = next(iter(host_data.values())).shape
 74    H, W = shape
 75    n_cells = H * W
 76
 77    # Human attractiveness = human population (nodata -> 0)
 78    human = host_data.get("human", np.zeros(shape, dtype=np.float32))
 79    human = np.where(human == NODATA_SENTINEL, 0.0, human)
 80    human_total = float(human.sum())
 81
 82    # Livestock attractiveness = sum of livestock species
 83    livestock_vars = ["cattle", "goats", "sheep", "pigs", "chickens"]
 84    livestock = np.zeros(shape, dtype=np.float32)
 85    for var in livestock_vars:
 86        if var in host_data:
 87            arr = host_data[var]
 88            livestock += np.where(arr == NODATA_SENTINEL, 0.0, arr)
 89    livestock_total = float(livestock.sum())
 90
 91    # Build + write each OD matrix, freeing memory between matrices
 92    output_dir.mkdir(parents=True, exist_ok=True)
 93    t0 = time.time()
 94    nnz_by_file: dict[str, int] = {}
 95
 96    def _build_write(name: str, grid: np.ndarray, beta: float) -> str:
 97        """Build one gravity OD matrix and write it as a CSR file.
 98
 99        Returns the path of the written file.
100        """
101        rp, ci, vl, nr, nc = build_gravity_od(
102            grid, cell_size_km, beta, max_distance_km, sparsity_threshold,
103        )
104        p = write_csr(rp, ci, vl, nr, nc, output_dir / name)
105        nnz_by_file[name] = int(ci.shape[0])
106        del rp, ci, vl
107        return str(p)
108
109    written_paths = [
110        _build_write(f"{aoi_slug}_mobility_day.csr", human, beta_day),
111        _build_write(f"{aoi_slug}_mobility_night.csr", human, beta_night),
112    ]
113    if livestock_total > 0:
114        written_paths.append(
115            _build_write(f"{aoi_slug}_livestock_mobility.csr", livestock, beta_livestock)
116        )
117    else:
118        rp_live, ci_live, v_live, nr_live, nc_live = build_identity_od(n_cells)
119        p = write_csr(rp_live, ci_live, v_live, nr_live, nc_live,
120                      output_dir / f"{aoi_slug}_livestock_mobility.csr")
121        nnz_by_file[f"{aoi_slug}_livestock_mobility.csr"] = int(ci_live.shape[0])
122        written_paths.append(str(p))
123
124    elapsed = time.time() - t0
125
126    # Write manifest
127    manifest = {
128        "n_cells": n_cells,
129        "grid_height": H,
130        "grid_width": W,
131        "cell_size_km": cell_size_km,
132        "beta_day": beta_day,
133        "beta_night": beta_night,
134        "beta_livestock": beta_livestock,
135        "max_distance_km": max_distance_km,
136        "sparsity_threshold": sparsity_threshold,
137        "nnz_by_file": nnz_by_file,
138        "human_total": human_total,
139        "livestock_total": livestock_total,
140        "build_time_s": round(elapsed, 2),
141    }
142    manifest_path = output_dir / "mobility_manifest.json"
143    manifest_path.write_text(json.dumps(manifest, indent=2) + "\n")
144
145    # Register in central manifest
146    manifest_keys = {
147        f"{aoi_slug}_mobility_day.csr": "mobility_day",
148        f"{aoi_slug}_mobility_night.csr": "mobility_night",
149        f"{aoi_slug}_livestock_mobility.csr": "livestock_mobility",
150    }
151    from ..download.catalog import INGEST_ARTIFACTS
152    for csr_name, manifest_key in manifest_keys.items():
153        register_dataset(
154            aoi_slug, INGEST_ARTIFACTS[manifest_key].key, None,
155            csr_name,
156            required_for_abm=True,
157            license="CC-BY-4.0+ODbL-1.0+NASA-Cite",
158            attribution=(
159                "Mobility graph derived from host_static.nc — inherits "
160                "WorldPop/GLW4/GHS-SMOD (CC BY 4.0), Overture buildings "
161                "(ODbL 1.0) and ESA WorldCover/Copernicus attributions."
162            ),
163        )
164    register_dataset(
165        aoi_slug, INGEST_ARTIFACTS["mobility_manifest"].key, None,
166        str(manifest_path.name),
167    )
168
169    return {
170        "files": written_paths,
171        "manifest_path": str(manifest_path),
172        "n_cells": n_cells,
173        "human_total": human_total,
174        "livestock_total": livestock_total,
175        "build_time_s": round(elapsed, 2),
176    }

Build gravity-model mobility OD matrices from host_static.nc.

Matrices are built and written one at a time so peak RAM stays at ~one matrix (the livestock matrix dominates at 1km Ghana resolution).

Args: hosts_path: path to host_static.nc. output_dir: directory for CSR files. aoi_slug: AOI identifier for manifest registration. cell_size_km: grid cell size in km. beta_day: friction for human daytime mobility. beta_night: friction for human nighttime mobility. beta_livestock: friction for livestock mobility. max_distance_km: maximum mobility distance. sparsity_threshold: minimum normalised probability kept per entry.

Returns: dict with 'files', 'manifest_path', and stats.