mal_core.download

 1from .registry import discover_downloaders, list_downloaders
 2from .runner import run_download
 3from .manifest import (
 4    update_dataset,
 5    read_manifest,
 6    validate_completeness,
 7    get_dataset_files,
 8    resolve_dataset_file,
 9)
10from .catalog import (
11    INGEST_ARTIFACTS,
12    IngestArtifact,
13    Slot,
14    catalog_status,
15    downloadable_datasets,
16    load_local_manifest,
17    register_existing,
18    resolve,
19    resolve_inputs,
20)
21
22__all__ = [
23    "discover_downloaders", "list_downloaders",
24    "run_download",
25    "update_dataset", "read_manifest",
26    "validate_completeness", "get_dataset_files",
27]
def discover_downloaders() -> dict[str, mal_core.download.registry.DownloaderSpec]:
 56def discover_downloaders() -> dict[str, DownloaderSpec]:
 57    """Collect the downloader plugins exported by the loader modules.
 58
 59    Every module of ``mal_commonlib.data.loaders`` is imported and its
 60    ``DOWNLOADER`` dict, if present, is turned into a DownloaderSpec keyed
 61    by dataset name. Modules without a ``DOWNLOADER`` and modules that
 62    fail to import are skipped with a warning.
 63
 64    Returns:
 65        Mapping of dataset name to its spec.
 66    """
 67    registry: dict[str, DownloaderSpec] = {}
 68    for mod_name in _loader_module_names():
 69        try:
 70            mod = importlib.import_module(f"mal_commonlib.data.loaders.{mod_name}")
 71            raw = getattr(mod, "DOWNLOADER", None)
 72            if raw is None:
 73                continue
 74            profile_defaults = {
 75                # --- env tensor (ingest/daily_nc.py, contract v3.0) ---
 76                "chirps": ["rainfall_daily"],
 77                "era5": ["air_temp_daily", "wind_6hourly"],
 78                "jrc_gsw": ["habitat_features"],
 79                "dynamic_world": ["class_fractions"],
 80                # --- static habitat gpkg (ingest/env.py) ---
 81                # dem/modis retired: no terrain or NDVI consumer in the
 82                # redesign's contract (plan 01 §6-§7).
 83                # --- host density (ingest/hosts.py) ---
 84                "worldpop": ["population"],
 85                "glw": ["cattle", "goats", "sheep", "pigs", "chickens"],
 86                "ghsl": ["urban_class"],
 87                "buildings": ["building_fraction"],
 88                "wildlife": ["wildlife_host_proxy"],
 89                # --- saltwater filter (ingest/daily_nc.py) ---
 90                "coastline": ["land_mask"],
 91                # --- explicitly excluded (not ABM defaults) ---
 92                "hydrorivers": [],
 93                "smap": [],
 94            }
 95            profile_formats = {
 96                "era5": {"air_temp_daily": "daily", "wind_6hourly": "daily"},
 97                "chirps": {"rainfall_daily": "daily"},
 98                # "daily" here only selects the runner's multi-year-NC
 99                # writer: DW class_fractions is one frame per run year.
100                "dynamic_world": {"class_fractions": "daily"},
101            }
102            spec = DownloaderSpec(
103                name=raw["name"],
104                description=raw.get("description", ""),
105                requires_auth=raw.get("requires_auth", []),
106                outputs=raw.get("outputs", {}),
107                manifest_keys=raw.get("manifest_keys", {}),
108                module_name=mod_name,
109                is_time_series=raw.get("is_time_series", False),
110                formats=raw.get("formats", profile_formats.get(raw["name"])),
111                abm_default_outputs=raw.get(
112                    "abm_default_outputs", profile_defaults.get(raw["name"])
113                ),
114                required_for_abm=raw.get("required_for_abm", None),
115                reductions=raw.get("reductions", None),
116                license=raw.get("license", None),
117                attribution=raw.get("attribution", None),
118            )
119            registry[spec.name] = spec
120            log.debug(
121                "Registered downloader: %s (%d outputs)", spec.name, len(spec.outputs)
122            )
123        except Exception as e:
124            log.warning("Failed to load downloader from %s: %s", mod_name, e)
125    return registry

Collect the downloader plugins exported by the loader modules.

Every module of mal_commonlib.data.loaders is imported and its DOWNLOADER dict, if present, is turned into a DownloaderSpec keyed by dataset name. Modules without a DOWNLOADER and modules that fail to import are skipped with a warning.

Returns: Mapping of dataset name to its spec.

def list_downloaders() -> list[dict[str, typing.Any]]:
128def list_downloaders() -> list[dict[str, Any]]:
129    """Summarise the available downloaders as name, description and outputs."""
130    registry = discover_downloaders()
131    return [
132        {
133            "name": spec.name,
134            "description": spec.description,
135            "outputs": list(spec.outputs.keys()),
136        }
137        for spec in registry.values()
138    ]

Summarise the available downloaders as name, description and outputs.

def run_download( aoi: str, datasets: list[str] | None = None, outputs: list[str] | None = None, years: list[int] | None = None, months: list[int] | None = None, output_dir: str | pathlib.Path | None = None, cache_dir: str | pathlib.Path | None = None, **kwargs) -> dict[str, typing.Any]:
 80def run_download(
 81    aoi: str,
 82    datasets: list[str] | None = None,
 83    outputs: list[str] | None = None,
 84    years: list[int] | None = None,
 85    months: list[int] | None = None,
 86    output_dir: str | Path | None = None,
 87    cache_dir: str | Path | None = None,
 88    **kwargs,
 89) -> dict[str, Any]:
 90    """Download datasets for an AOI, using standard naming + manifest registration."""
 91    from mal_commonlib.aoi import AOI
 92
 93    aoi_obj = AOI.from_slug(aoi)
 94    registry = discover_downloaders()
 95    if not registry:
 96        return {"error": "No downloaders registered"}
 97
 98    if datasets:
 99        selected = {k: v for k, v in registry.items() if k in datasets}
100    else:
101        selected = registry
102
103    out_dir = Path(output_dir) if output_dir else (_REPO_ROOT / "data" / aoi)
104    out_dir.mkdir(parents=True, exist_ok=True)
105
106    cache = Path(cache_dir) if cache_dir else None
107
108    results: dict[str, Any] = {}
109    use_abm_profile = datasets is None and outputs is None
110    for name, spec in selected.items():
111        log.info("Downloading: %s", name)
112        if not _check_auth(spec):
113            results[name] = {"status": "skipped", "reason": "auth missing"}
114            continue
115
116        try:
117            for output_name, func in spec.outputs.items():
118                if outputs and output_name not in outputs:
119                    continue
120                if use_abm_profile and spec.abm_default_outputs is not None and output_name not in spec.abm_default_outputs:
121                    continue
122
123                log.info("  %s.%s", name, output_name)
124                is_ts = spec.is_time_series
125                required_for_abm = bool(spec.required_for_abm and spec.required_for_abm.get(output_name, False))
126
127                if is_ts:
128                    if not years:
129                        log.warning("    %s is time-series but no years specified — skipping", output_name)
130                        continue
131
132                    # Determine format for this output (default: "monthly" for backward compat)
133                    output_format = "monthly"
134                    if spec.formats and output_name in spec.formats:
135                        output_format = spec.formats[output_name]
136
137                    if output_format == "daily":
138                        # Daily path: write entire 3D time-series as ONE multi-year NC
139                        result = func(aoi=aoi_obj, years=years, months=months, cache_dir=cache)
140                        if result is None:
141                            continue
142                        # 3D DataArray → NC via xarray.to_netcdf()
143                        # Variable name: the loader's own DataArray name is
144                        # the contract channel (e.g. air_temp_c) — fall back
145                        # to output_name minus "_daily" for legacy output.
146                        nc_var_name = (
147                            output_name.removesuffix("_daily")
148                            if getattr(result, "name", None) is None
149                            else result.name
150                        )
151                        path = _standard_path_daily(aoi, output_name, min(years), max(years), data_dir=out_dir)
152                        path.parent.mkdir(parents=True, exist_ok=True)
153                        save_product(result, path, format="nc", var_name=nc_var_name)
154                        # Register with period metadata
155                        time_dim = "time" if "time" in result.dims else "valid_time"
156                        t0 = str(result[time_dim].values[0])[:10]
157                        t1 = str(result[time_dim].values[-1])[:10]
158                        update_dataset(
159                            aoi,
160                            spec.manifest_keys[output_name],
161                            None,  # year=None for multi-year NC
162                            path.name,
163                            type="time-series",
164                            required_for_abm=required_for_abm,
165                            format="nc",
166                            period={"start": t0, "end": t1},
167                            license=spec.license,
168                            attribution=spec.attribution,
169                            data_root=out_dir.parent,
170                        )
171                        log.info("    daily NC → %s (period %s to %s)", path.name, t0, t1)
172                    elif output_format == "monthly_nc":
173                        # Monthly NC path: write entire 3D monthly time-series
174                        # as ONE multi-year NetCDF with MONTHLY time steps,
175                        # preserving per-month resolution (e.g. SMAP salinity).
176                        result = func(aoi=aoi_obj, years=years, months=months, cache_dir=cache)
177                        if result is None:
178                            continue
179                        # Variable name: strip "_salinity" suffix for ABM/ingest
180                        # compatibility (e.g. "salinity" stays "salinity").
181                        nc_var_name = output_name.removesuffix("_salinity")
182                        path = _standard_path_monthly_nc(aoi, output_name, min(years), max(years), data_dir=out_dir)
183                        path.parent.mkdir(parents=True, exist_ok=True)
184                        save_product(result, path, format="nc", var_name=nc_var_name)
185                        # Register with period metadata (same shape as daily)
186                        time_dim = "time" if "time" in result.dims else "valid_time"
187                        t0 = str(result[time_dim].values[0])[:10]
188                        t1 = str(result[time_dim].values[-1])[:10]
189                        update_dataset(
190                            aoi,
191                            spec.manifest_keys[output_name],
192                            None,  # year=None for multi-year NC
193                            path.name,
194                            type="time-series",
195                            required_for_abm=required_for_abm,
196                            format="nc",
197                            period={"start": t0, "end": t1},
198                            license=spec.license,
199                            attribution=spec.attribution,
200                            data_root=out_dir.parent,
201                        )
202                        log.info("    monthly NC → %s (period %s to %s)", path.name, t0, t1)
203                    else:
204                        # Monthly path: existing M11 logic (per-month TIF slicing)
205                        result = func(aoi=aoi_obj, years=years, months=months, cache_dir=cache)
206                        if result is None:
207                            continue
208
209                        has_time = "time" in result.dims or "valid_time" in result.dims
210                        if has_time:
211                            time_dim = "valid_time" if "valid_time" in result.dims else "time"
212                            for yr in years:
213                                sel = result.sel({time_dim: result[time_dim].dt.year == yr})
214                                reduction = (spec.reductions or {}).get(output_name, "mean")
215                                if reduction == "sum":
216                                    slc = sel.sum(time_dim, keep_attrs=True)
217                                elif reduction == "first":
218                                    slc = sel.isel({time_dim: 0}, drop=True)
219                                else:
220                                    slc = sel.mean(time_dim, keep_attrs=True)
221                                path = _standard_path(aoi, output_name, yr, "tif", data_dir=out_dir)
222                                save_product(slc, path, format="tif")
223                                update_dataset(
224                                    aoi,
225                                    spec.manifest_keys[output_name],
226                                    yr,
227                                    path.name,
228                                    type="time-series",
229                                    required_for_abm=required_for_abm,
230                                    format="tif",
231                                    license=spec.license,
232                                    attribution=spec.attribution,
233                                    data_root=out_dir.parent,
234                                )
235                                log.info("    %s aggregate (%s) → %s", yr, reduction, path.name)
236                        else:
237                            # Single (year, month) — 2D result, no time dim
238                            yr = years[0]
239                            path = _standard_path(aoi, output_name, yr, "tif", data_dir=out_dir)
240                            save_product(result, path, format="tif")
241                            update_dataset(
242                                aoi,
243                                spec.manifest_keys[output_name],
244                                yr,
245                                path.name,
246                                type="time-series",
247                                required_for_abm=required_for_abm,
248                                format="tif",
249                                license=spec.license,
250                                attribution=spec.attribution,
251                                data_root=out_dir.parent,
252                            )
253                            log.info("    %s → %s", yr, path.name)
254                else:
255                    result = func(aoi=aoi_obj, cache_dir=cache)
256
257                    if result is None:
258                        continue
259
260                    ext = ".nc" if isinstance(result, xr.Dataset) else ".tif"
261                    path = _standard_path(aoi, output_name, None, ext.lstrip("."), data_dir=out_dir)
262                    save_product(result, path)
263                    update_dataset(
264                        aoi,
265                        spec.manifest_keys[output_name],
266                        None,
267                        path.name,
268                        type="static",
269                        required_for_abm=required_for_abm,
270                        license=spec.license,
271                        attribution=spec.attribution,
272                        data_root=out_dir.parent,
273                    )
274                    log.info("    → %s", path.name)
275
276            results[name] = {"status": "ok"}
277        except Exception as e:
278            log.error("Download failed for %s: %s", name, e)
279            results[name] = {"status": "error", "error": str(e)}
280
281    # One aggregated usage-limit warning per run (docs/licenses.md)
282    try:
283        from mal_commonlib.data.licenses import warn_manifest_limits
284
285        warn_manifest_limits(aoi)
286    except Exception as e:  # never break a download over a warning
287        log.debug("license warning skipped: %s", e)
288
289    return results

Download datasets for an AOI, using standard naming + manifest registration.

def update_dataset( aoi: str, dataset_name: str, year: int | str | None, filename: str, *, type: str = 'time-series', required_for_abm: bool = False, variables: list[str] | None = None, format: str | None = None, period: dict[str, str] | None = None, license: str | None = None, attribution: str | None = None, data_root: pathlib.Path | None = None) -> pathlib.Path:
120def update_dataset(
121    aoi: str,
122    dataset_name: str,
123    year: int | str | None,
124    filename: str,
125    *,
126    type: str = "time-series",
127    required_for_abm: bool = False,
128    variables: list[str] | None = None,
129    format: str | None = None,
130    period: dict[str, str] | None = None,
131    license: str | None = None,
132    attribution: str | None = None,
133    data_root: Path | None = None,
134) -> Path:
135    """Update a specific dataset entry in the manifest.
136
137    Args:
138        aoi: AOI slug.
139        dataset_name: dataset key (e.g. "chirps_rainfall_daily").
140        year: year for per-year entries, or None for multi-year NC.
141        filename: output filename.
142        type: "static" | "time-series".
143        required_for_abm: whether this dataset is required for ABM runs.
144        variables: list of variable names in the file.
145        format: file format ("tif" | "nc" | "gpkg" | "csr").
146        period: for multi-year NC, {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}.
147        license: upstream license id(s) from
148            ``mal_commonlib.data.licenses.KNOWN_LICENSES`` ('+'-joined for
149            derived products). None leaves the existing value untouched.
150        attribution: literal credit line (docs/licenses.md). None leaves
151            the existing value untouched.
152    """
153    root = data_root or DATA_ROOT
154    path = root / aoi / "manifest.json"
155    manifest = read_manifest(aoi, root)
156    if dataset_name not in manifest.get("datasets", {}):
157        manifest.setdefault("datasets", {})[dataset_name] = {
158            "type": type,
159            "format": format or filename.rsplit(".", 1)[-1],
160            "required_for_abm": required_for_abm,
161            "files": {},
162        }
163    ds = manifest["datasets"][dataset_name]
164    # Update metadata fields
165    ds["type"] = type
166    if format:
167        ds["format"] = format
168    ds["required_for_abm"] = required_for_abm
169    if variables:
170        ds["variables"] = variables
171    if period:
172        ds["period"] = period
173    if license:
174        ds["license"] = license
175    if attribution:
176        ds["attribution"] = attribution
177
178    if year:
179        ds.setdefault("files", {})[str(year)] = filename
180    else:
181        ds.setdefault("files", {})[dataset_name] = filename
182
183    all_files = []
184    for d in manifest.get("datasets", {}).values():
185        all_files.extend(d.get("files", {}).values())
186    manifest["expected_files"] = sorted(set(all_files))
187    path.parent.mkdir(parents=True, exist_ok=True)
188    with open(path, "w") as f:
189        json.dump(manifest, f, indent=2)
190    log.info("Manifest updated: %s[%s] = %s", aoi, dataset_name, filename)
191    return path

Update a specific dataset entry in the manifest.

Args: aoi: AOI slug. dataset_name: dataset key (e.g. "chirps_rainfall_daily"). year: year for per-year entries, or None for multi-year NC. filename: output filename. type: "static" | "time-series". required_for_abm: whether this dataset is required for ABM runs. variables: list of variable names in the file. format: file format ("tif" | "nc" | "gpkg" | "csr"). period: for multi-year NC, {"start": "YYYY-MM-DD", "end": "YYYY-MM-DD"}. license: upstream license id(s) from mal_commonlib.data.licenses.KNOWN_LICENSES ('+'-joined for derived products). None leaves the existing value untouched. attribution: literal credit line (docs/licenses.md). None leaves the existing value untouched.

def read_manifest(aoi: str, data_root: pathlib.Path | None = None) -> dict:
32def read_manifest(aoi: str, data_root: Path | None = None) -> dict:
33    """Read the v3.1 datasets-block manifest. Empty skeleton if file missing."""
34    path = (data_root or DATA_ROOT) / aoi / "manifest.json"
35    if not path.exists():
36        return {"aoi": aoi, "datasets": {}, "expected_files": []}
37    with open(path) as f:
38        return json.load(f)

Read the v3.1 datasets-block manifest. Empty skeleton if file missing.

def validate_completeness( aoi: str, *, years: list[int] | None = None, data_root: pathlib.Path | None = None) -> list[str]:
194def validate_completeness(
195    aoi: str, *, years: list[int] | None = None, data_root: Path | None = None
196) -> list[str]:
197    """Return list of missing expected files. Empty = complete.
198
199    For daily NC entries with a ``period`` field, checks that the
200    period covers the requested years rather than individual file existence.
201    """
202    root = data_root or DATA_ROOT
203    manifest = read_manifest(aoi, root)
204    data_dir = root / aoi
205    missing = []
206
207    for ds_name, ds in manifest.get("datasets", {}).items():
208        period = ds.get("period")
209        if period and years:
210            # Daily NC entry: check period covers requested years
211            period_start = period.get("start", "")
212            period_end = period.get("end", "")
213            if period_start and period_end:
214                start_year = int(period_start[:4])
215                end_year = int(period_end[:4])
216                for y in years:
217                    if y < start_year or y > end_year:
218                        missing.append(
219                            f"{ds_name}: period {period_start}..{period_end} "
220                            f"does not cover year {y}"
221                        )
222                # Also check that at least one file exists
223                files = ds.get("files", {})
224                if not any((data_dir / f).exists() for f in files.values()):
225                    for f in files.values():
226                        if not (data_dir / f).exists():
227                            missing.append(f)
228            else:
229                # Incomplete period metadata
230                for f in ds.get("files", {}).values():
231                    if not (data_dir / f).exists():
232                        missing.append(f)
233        else:
234            # Standard per-file check
235            for f in ds.get("files", {}).values():
236                if not (data_dir / f).exists():
237                    missing.append(f)
238
239    # Also check the top-level expected_files union
240    for f in manifest.get("expected_files", []):
241        if f not in missing and not (data_dir / f).exists():
242            missing.append(f)
243
244    return sorted(set(missing))

Return list of missing expected files. Empty = complete.

For daily NC entries with a period field, checks that the period covers the requested years rather than individual file existence.

def get_dataset_files( aoi: str, dataset_name: str, year: int | str | None = None) -> list[pathlib.Path]:
247def get_dataset_files(
248    aoi: str, dataset_name: str, year: int | str | None = None
249) -> list[Path]:
250    """Get file paths for a dataset, optionally filtered by year."""
251    manifest = read_manifest(aoi)
252    ds = manifest.get("datasets", {}).get(dataset_name)
253    if not ds:
254        return []
255    data_dir = DATA_ROOT / aoi
256    if year:
257        fname = ds.get("files", {}).get(str(year))
258        return [data_dir / fname] if fname else []
259    return [data_dir / f for f in ds.get("files", {}).values()]

Get file paths for a dataset, optionally filtered by year.