"""Download ECMWF SEAS5.1 data for the configured Asia-Pacific PCA domain. One initial month is one CDS request and one NetCDF file. This makes the 1981-2020 baseline restartable: a completed file is never requested again unless ``--overwrite`` is supplied. """ from __future__ import annotations import argparse import json from pathlib import Path from .config import PROJECT_ROOT from .download_ecmwf import DATASET, lead_hours_through_lt7_boundary def load_domain(path: str | Path = "config/ecmwf_domain.json") -> dict: source = Path(path) if not source.is_absolute(): source = PROJECT_ROOT / source with source.open(encoding="utf-8") as handle: return json.load(handle) def request_for(init: str, domain: dict, predictands_only: bool = False) -> dict: year, month = map(int, init.split("-")) groups = domain["variables"] variables = groups["predictands"] if predictands_only else groups["predictands"] + groups["predictors"] return { "originating_centre": domain["originating_centre"], "system": domain["system"], "variable": variables, "year": str(year), "month": f"{month:02d}", "day": "01", "leadtime_hour": lead_hours_through_lt7_boundary(year, month), "area": domain["area"], "data_format": "netcdf", } def retrieve(init: str, output: Path, domain: dict, predictands_only: bool, overwrite: bool) -> Path: if output.exists() and not overwrite: print(f"Already exists; skipped: {output}") return output try: import cdsapi except ImportError as exc: raise SystemExit("cdsapi is required in the active Python environment.") from exc output.parent.mkdir(parents=True, exist_ok=True) cdsapi.Client().retrieve(DATASET, request_for(init, domain, predictands_only), str(output)) return output def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--init", required=True, help="Initial month, formatted YYYY-MM") parser.add_argument("--predictands-only", action="store_true") parser.add_argument("--overwrite", action="store_true") parser.add_argument("--domain-config", default="config/ecmwf_domain.json") args = parser.parse_args() domain = load_domain(args.domain_config) suffix = "predictands" if args.predictands_only else "all" target = PROJECT_ROOT / "data/ecmwf/raw" / f"ecmwf_seas51_{args.init}_{suffix}.nc" print(retrieve(args.init, target, domain, args.predictands_only, args.overwrite)) if __name__ == "__main__": main()