diff --git a/conf/infer.yaml b/conf/infer.yaml index cad0c8a..4a97006 100644 --- a/conf/infer.yaml +++ b/conf/infer.yaml @@ -1,5 +1,6 @@ defaults: - _self_ + - paths - eval: gobabeb # --- required --- diff --git a/conf/paths.yaml b/conf/paths.yaml new file mode 100644 index 0000000..8f1b31b --- /dev/null +++ b/conf/paths.yaml @@ -0,0 +1,9 @@ +# @package paths +# Site paths shared by training, inference and asset generation. +# Use a separate preload cache when changing the common store root. +eozarr_root: /Net/Groups/BGI/work_5/scratch/WeatherGenerator/data/lowres_old +preload_cache_root: null +preload_cache_parent: /Net/Groups/BGI/tscratch + +# Only list modalities whose stores live under a different root. +store_roots: {} diff --git a/conf/statistics.yaml b/conf/statistics.yaml index 7ec06ad..4e86daf 100644 --- a/conf/statistics.yaml +++ b/conf/statistics.yaml @@ -1,6 +1,7 @@ defaults: - _self_ + - paths - sources: eozarr modality: ??? diff --git a/conf/train.yaml b/conf/train.yaml index a13662a..4d3d8d5 100644 --- a/conf/train.yaml +++ b/conf/train.yaml @@ -1,5 +1,6 @@ defaults: - _self_ # base applies first; groups below have higher priority + - paths - sources: eozarr - model: mlp - objective: rollout @@ -11,10 +12,6 @@ defaults: config_version: 2 -paths: - eozarr_root: null - preload_cache_root: null - # --- derived keys (resolved lazily by OmegaConf) --- _spatial: mtg_new _spatial_val: eval_mtg_new_val diff --git a/deep_lst/baselines/base.py b/deep_lst/baselines/base.py index fa6f863..49bf7a0 100644 --- a/deep_lst/baselines/base.py +++ b/deep_lst/baselines/base.py @@ -50,6 +50,8 @@ def output_path(self) -> Path: def run(self, shared: dict, config: dict, store_key: str) -> None: self.store_key = store_key self.config = config + if "paths" in config: + self.paths = ExperimentPaths.from_config(config["paths"]) if self.output_path().exists() and not self.overwrite: print(f"Output already exists for '{store_key}'. Pass overwrite=True to refresh.") return @@ -86,7 +88,10 @@ def _preload_series(self, shared: dict, modality: str, var_name: str): def _metadata_attrs(self, modality: str, store_name: str, var_name: str) -> dict: """Baseline attrs sourced from the store's own per-variable metadata scheme.""" - reader = get_data_reader(modality, store=str(self.paths.eozarr_store_path(store_name)), average_hourly=False) + store_root = self.paths.store_roots.get(modality, self.config["test_dataset"][modality].get("store_root")) + reader = get_data_reader( + modality, store=str(self.paths.eozarr_store_path(store_name, store_root)), average_hourly=False + ) variable_meta = reader.data_arr.attrs.get("metadata", {}).get(var_name, {}) return dict( variable=var_name, diff --git a/deep_lst/dataset/dataset.py b/deep_lst/dataset/dataset.py index bc96dce..b78650c 100644 --- a/deep_lst/dataset/dataset.py +++ b/deep_lst/dataset/dataset.py @@ -3,6 +3,7 @@ import json import os from concurrent.futures import ThreadPoolExecutor +from pathlib import Path import eodata import numpy as np @@ -242,11 +243,12 @@ def __getitem__(self, index): return leaves @classmethod - def from_config(cls, modality, store, spatial, anchor, temporal, workers=1): + def from_config(cls, modality, store, spatial, anchor, temporal, workers=1, store_root=None, paths=None): """Stream the MTG pixel selection (spatial) over the statistics timestep subset (temporal).""" - anchor_ids = _load_anchor_ids(spatial) + paths = paths or PATHS + anchor_ids = _load_anchor_ids(spatial, paths) rows = np.unique(map_to_store_rows(anchor_grid(anchor), anchor_ids, store_grid(modality))) - stat_hours = np.load(PATHS.temporal_indices_path(temporal))["time_indices"].astype(np.int64) + stat_hours = np.load(paths.temporal_indices_path(temporal))["time_indices"].astype(np.int64) stat_days = np.unique((stat_hours + STORE_EPOCH_OFFSET) // 24) # store days; each read in full (24 h) # Enable the full continuous leaves (data + data_daily + data_static), raw. Categoricals and @@ -260,7 +262,10 @@ def from_config(cls, modality, store, spatial, anchor, temporal, workers=1): } accepted = inspect.signature(get_data_reader_class(modality)).parameters reader_kwargs = {key: value for key, value in reader_kwargs.items() if key in accepted} - reader = eodata.get_data_reader(modality, store=str(PATHS.eozarr_store_path(store)), **reader_kwargs) + store_root = paths.store_roots.get(modality, store_root) + reader = eodata.get_data_reader( + modality, store=str(paths.eozarr_store_path(store, store_root)), **reader_kwargs + ) return cls(reader, rows, stat_days) @@ -388,6 +393,9 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs): anchor_ids = _load_anchor_ids(spatial_name, paths) src_grid = anchor_grid(kwargs.get("anchor", "mtg")) num_workers = kwargs.get("preload_workers", 8) + store_roots = { + modality: paths.store_roots.get(modality, kwargs[modality].get("store_root")) for modality in modality_ids + } # Disk cache: the preload is deterministic given the anchors, stores, load specs and # statistics, so later runs (restarts, HP/architecture sweeps) skip the store reads. @@ -406,6 +414,9 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs): }, } for modality in modality_ids: + store_root = store_roots[modality] + if store_root is not None: + fingerprint_spec["modalities"][modality]["store_root"] = str(Path(store_root).resolve()) transform = kwargs[modality].get("transform") if transform is not None: # only when set, so caches built before the key existed stay valid fingerprint_spec["modalities"][modality]["transform"] = transform @@ -433,7 +444,9 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs): accepted = inspect.signature(get_data_reader_class(modality)).parameters reader_kwargs = {key: value for key, value in reader_kwargs.items() if key in accepted} reader = eodata.get_data_reader( - modality, store=str(paths.eozarr_store_path(kwargs[modality]["store"])), **reader_kwargs + modality, + store=str(paths.eozarr_store_path(kwargs[modality]["store"], store_roots[modality])), + **reader_kwargs, ) normalizer = ModalityNormalizer.from_spec( diff --git a/deep_lst/finetune.py b/deep_lst/finetune.py index 4a587fd..f8e1481 100644 --- a/deep_lst/finetune.py +++ b/deep_lst/finetune.py @@ -82,7 +82,7 @@ def main(cfg: DictConfig) -> None: name = f"{name}_smoke" config["name"] = name - paths = ExperimentPaths() + paths = ExperimentPaths.from_config(config.get("paths")) from_parts = from_run.split("/") if len(from_parts) != 2: raise ValueError(f"from_run must be EXPERIMENT/VERSION, got: {from_run!r}") @@ -178,7 +178,7 @@ def main(cfg: DictConfig) -> None: check_stats_transform(paths.stats_zarr_path(modality, stats_tag), transform) data_module = LitDataModule( - **config, train_dataset=train_view, val_dataset=views["val"], test_dataset=views["test"] + experiment_paths=paths, **config, train_dataset=train_view, val_dataset=views["val"], test_dataset=views["test"] ) data_module.setup() diff --git a/deep_lst/sensitivity/forecast.py b/deep_lst/sensitivity/forecast.py index 8f4cfdc..941ca6a 100644 --- a/deep_lst/sensitivity/forecast.py +++ b/deep_lst/sensitivity/forecast.py @@ -36,7 +36,7 @@ def sensitivity_dir(paths, experiment, version, eval_name, method, block): class PerturbedInference: """Holds the loaded model and the preloaded dataset of one (experiment, eval).""" - def __init__(self, cfg, config): + def __init__(self, cfg, config, paths=None): self.cfg = cfg # hydra: experiment, version, best, land_water_mask self.config = config # resolved run config self.test_view = split_views(config)["test"] @@ -44,8 +44,10 @@ def __init__(self, cfg, config): self.model, self.device = load_model( config, self.td_keys, experiment=cfg.experiment, version=cfg.version, prefer_best=cfg.best ) - self.shared = MultimodalDataset.preload_shared(config["modality_ids"], **self.test_view) - self.dataset = MultimodalDataset.from_modalities(config["modality_ids"], self.shared, **self.test_view) + self.shared = MultimodalDataset.preload_shared(config["modality_ids"], paths=paths, **self.test_view) + self.dataset = MultimodalDataset.from_modalities( + config["modality_ids"], self.shared, paths=paths, **self.test_view + ) def forecast(self, path): """One pass over the dataset as it is now (perturbed or not) into a forecast store. diff --git a/deep_lst/train.py b/deep_lst/train.py index 00b169f..d64114d 100644 --- a/deep_lst/train.py +++ b/deep_lst/train.py @@ -48,7 +48,7 @@ def main(cfg: DictConfig) -> None: config = OmegaConf.to_container(cfg, resolve=True) choices = HydraConfig.get().runtime.choices validate_config(config) - paths = ExperimentPaths(**{key: Path(value) for key, value in config.get("paths", {}).items() if value is not None}) + paths = ExperimentPaths.from_config(config.get("paths")) pl.seed_everything(config["seed"], workers=True) smoke = config.pop("smoke", False) diff --git a/deep_lst/utils/full_store.py b/deep_lst/utils/full_store.py index 89b4e1d..7782f1a 100644 --- a/deep_lst/utils/full_store.py +++ b/deep_lst/utils/full_store.py @@ -38,7 +38,8 @@ def open_store_reader(modality, store, data_types): reader_kwargs[flag] = data_type in data_types accepted = inspect.signature(get_data_reader_class(modality)).parameters reader_kwargs = {key: value for key, value in reader_kwargs.items() if key in accepted} - return eodata.get_data_reader(modality, store=str(PATHS.eozarr_store_path(store)), **reader_kwargs) + store_path = PATHS.eozarr_store_path(store, PATHS.store_roots.get(modality)) + return eodata.get_data_reader(modality, store=str(store_path), **reader_kwargs) def load_store_columns(modality, store, spatial, load, anchor="mtg", day_range=None, num_workers=8): diff --git a/deep_lst/utils/io.py b/deep_lst/utils/io.py index 216a887..ec3b20a 100644 --- a/deep_lst/utils/io.py +++ b/deep_lst/utils/io.py @@ -2,8 +2,25 @@ import os import re from dataclasses import dataclass, field +from functools import cache from pathlib import Path +from omegaconf import OmegaConf + + +@cache +def _default_paths() -> dict: + return OmegaConf.to_container( + OmegaConf.load(Path(__file__).resolve().parents[2] / "conf" / "paths.yaml"), resolve=True + ) + + +def _preload_cache_root(settings: dict) -> Path: + root = settings["preload_cache_root"] or os.environ.get("DEEP_LST_CACHE_ROOT") + if root: + return Path(root) + return Path(settings["preload_cache_parent"]) / (os.environ.get("USER") or getpass.getuser()) / "tmp" + @dataclass class ExperimentPaths: @@ -12,17 +29,21 @@ class ExperimentPaths: experiment_root: Path = field(default_factory=lambda: Path("./experiments")) config_root: Path = field(default_factory=lambda: Path("./configs")) assets_root: Path = field(default_factory=lambda: Path("./assets")) - # Full eodata stores. Moved off tscratch (90-day purge) in October 2026. - eozarr_root: Path = field( - default_factory=lambda: Path("/Net/Groups/BGI/work_5/scratch/WeatherGenerator/data/lowres_old") - ) - preload_cache_root: Path = field( - default_factory=lambda: Path( - os.environ.get("DEEP_LST_CACHE_ROOT") - or f"/Net/Groups/BGI/tscratch/{os.environ.get('USER') or getpass.getuser()}/tmp" - ) + eozarr_root: Path = field(default_factory=lambda: Path(_default_paths()["eozarr_root"])) + preload_cache_root: Path = field(default_factory=lambda: _preload_cache_root(_default_paths())) + store_roots: dict[str, str | None] = field( + default_factory=lambda: dict(_default_paths()["store_roots"]), kw_only=True ) + @classmethod + def from_config(cls, config) -> "ExperimentPaths": + settings = {**_default_paths(), **{key: value for key, value in (config or {}).items() if value is not None}} + cache_root = _preload_cache_root(settings) + settings.pop("preload_cache_parent") + store_roots = dict(settings.pop("store_roots")) + settings["preload_cache_root"] = cache_root + return cls(store_roots=store_roots, **{key: Path(value) for key, value in settings.items()}) + def experiment_dir(self, experiment: str) -> Path: return self.experiment_root / experiment @@ -50,14 +71,15 @@ def config_path(self, experiment: str) -> Path: def statistics_path(self, modality, name) -> Path: return self.assets_root / modality / "statistics" / f"statistics_{name}.npz" - def eozarr_store_path(self, store_name: str) -> Path: + def eozarr_store_path(self, store_name: str, store_root: str | Path | None = None) -> Path: """Resolve a full eodata .eozarr store from its config-provided name. Prefers the directory store when it is readable and falls back to the .zip sibling: - under eozarr_root the era5, era5_land, glofas and swe stores exist only as zips, while + under the selected root the era5, era5_land, glofas and swe stores exist only as zips, while seviri is a directory store.""" - directory = self.eozarr_root / f"{store_name}.eozarr" - archive = self.eozarr_root / f"{store_name}.eozarr.zip" + root = self.eozarr_root if store_root is None else Path(store_root) + directory = root / f"{store_name}.eozarr" + archive = root / f"{store_name}.eozarr.zip" directory_is_readable = (directory / "data" / "zarr.json").exists() if not directory_is_readable and archive.exists(): return archive diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 3ab6c6d..9c4472b 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -56,27 +56,34 @@ be edited. ## 2. `conf/train.yaml` -### Training data and cache paths +### Data and cache paths -`paths.eozarr_root` and `paths.preload_cache_root` override the data-store and preload-cache -roots used by `deep_lst/train.py`, for all three training/validation/test splits. The defaults -are defined in `ExperimentPaths` in `deep_lst/utils/io.py`, also used by the `PATHS` singleton -in `deep_lst/dataset/dataset.py`. Both config values default to `null`, so these defaults apply. +`conf/paths.yaml` is the shared file for the data and preload-cache locations. Training, +fine-tuning, inference, sensitivity, statistics and baseline generation read it from the +current checkout. Set `eozarr_root` for the common store directory and add entries to +`store_roots` for modalities that live elsewhere: -The cache default uses `DEEP_LST_CACHE_ROOT` when it is nonempty; otherwise it uses -`/Net/Groups/BGI/tscratch/$USER/tmp` (the login name is used if `USER` is unset or empty). -An explicit `paths.preload_cache_root` takes priority over this default. Relative paths remain -relative to the repository working directory. The overrides are saved in the run's `config.yml`. +```yaml +store_roots: + seviri: /data/deep_lst +``` + +Here SEVIRI uses the separate directory and the other modalities use `eozarr_root`. +A null entry explicitly selects the common root. An older saved run can still provide +`sources..store_root` if the current paths file has no entry for that modality. + +If `preload_cache_root` is unset, the cache uses `DEEP_LST_CACHE_ROOT` when nonempty, +otherwise `//tmp`. The login name is used when `USER` is unset +or empty. Relative paths are resolved from the working directory. ``` uv run python deep_lst/train.py paths.eozarr_root=/data/eozarr paths.preload_cache_root=/scratch/deep_lst-cache +uv run python scripts/assets/compute_statistics.py modality=seviri +paths.store_roots.seviri=/data/deep_lst ``` -Cache keys are unchanged; use a separate cache root when the source data content differs. - -These Hydra overrides apply to training. Standalone inference, statistics and fine-tuning use -the shared `ExperimentPaths` defaults, including the cache default described above. -Model, loss and data-processing settings are unchanged. +Use `+` to add a modality to `store_roots` and leave it off to override an existing entry. +If you change the common `eozarr_root`, set a separate `preload_cache_root` to avoid reusing +a cache generated from the old stores. A modality-specific root is included in the cache key. ### 2.1 Selections and splits @@ -172,6 +179,9 @@ that training, inference, the baselines and the statistics script share. | `increment_vars` | variables for which the statistics script also computes the statistics of the 1-hour increment. Read by `scripts/assets/compute_statistics.py` only. Listing a variable here does not make it a prognostic of the model. | | `quality_mask` | optional and not set: `{field, se_max, target}` sets `target` to missing where the metadata variable `field` exceeds `se_max` | +The root comes from `conf/paths.yaml`. Each store is read from `.eozarr` or its ZIP sibling +under the selected root. + Data types under `load`: | Data type | Holds | @@ -197,6 +207,8 @@ only in the data options that name it. Changing `store`, `load` or `transform` changes the preload cache key, so the cache is rebuilt (`docs/RUNBOOK.md`, section 4.6). Changing the `data` option does not. +A modality-specific root from `paths.store_roots` is included in that key using its resolved path. +Without a modality-specific root, the existing cache key is preserved. ### 3.2 `data` diff --git a/docs/RUNBOOK.md b/docs/RUNBOOK.md index 081272d..a3c4a3c 100644 --- a/docs/RUNBOOK.md +++ b/docs/RUNBOOK.md @@ -108,15 +108,10 @@ assets/baselines//.nc persistence / climatology / ERA5(-Land Check these locations in a new clone: -1. `ExperimentPaths.preload_cache_root` in `deep_lst/utils/io.py` uses `DEEP_LST_CACHE_ROOT` - when it is nonempty, otherwise `/Net/Groups/BGI/tscratch/$USER/tmp` (using the login name if - `USER` is unset or empty). For training, `paths.preload_cache_root=` on the command - line or in the config file takes priority; `paths.eozarr_root` can also override the store - root. Other entry points use the shared `ExperimentPaths` defaults, including this cache - fallback. See `docs/CONFIGURATION.md`. - The data stores (`ExperimentPaths.eozarr_root`, - `/Net/Groups/BGI/work_5/scratch/WeatherGenerator/data/lowres_old`) are group-readable and - stay as they are. +1. Check `conf/paths.yaml` for the common store directory, any modality-specific directories + and the preload cache. The defaults keep the existing BGC store and scratch locations. + Set `preload_cache_root` explicitly or use `DEEP_LST_CACHE_ROOT` to choose another cache. + See `docs/CONFIGURATION.md` for precedence and examples. 2. The SLURM launchers under `scripts/` hard-code the path of the maintainer's clone, most of them as `WORKDIR=` near the top; replace it with the path of your clone. diff --git a/pyproject.toml b/pyproject.toml index be70173..4bdc65d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -83,5 +83,8 @@ quote-style = "double" [tool.setuptools.packages.find] where = ["."] -include = ["deep_lst*"] +include = ["deep_lst*", "conf"] exclude = ["plots*", "wandb*", "assets*", "configs*", "notebooks*", "checkpoints*", "experiments*"] + +[tool.setuptools.package-data] +conf = ["paths.yaml"] diff --git a/scripts/assets/compute_statistics.py b/scripts/assets/compute_statistics.py index 3637478..db1c171 100644 --- a/scripts/assets/compute_statistics.py +++ b/scripts/assets/compute_statistics.py @@ -24,8 +24,6 @@ from deep_lst.utils.io import ExperimentPaths from deep_lst.utils.spatial import store_grid -PATHS = ExperimentPaths() - # On-the-fly features that get statistics. The doy/hod cos/sin encodings are bounded in # [-1, 1] by construction and stay raw — z-scoring the components of a cyclic pair # separately would distort the encoding. @@ -92,6 +90,7 @@ def computed_feature_statistics(rows, stat_days, modality) -> ArrayStatistics: @hydra.main(config_path="../../conf", config_name="statistics", version_base="1.3") def main(cfg: DictConfig) -> None: config = OmegaConf.to_container(cfg, resolve=True) + paths = ExperimentPaths.from_config(config.get("paths")) modality = config["modality"] source = config["sources"][modality] # the same definition train.yaml composes increment_vars = source.get("increment_vars", []) @@ -101,6 +100,8 @@ def main(cfg: DictConfig) -> None: dataset = UnimodalDataset.from_config( modality=modality, store=source["store"], + store_root=source.get("store_root"), + paths=paths, spatial=config["spatial"], anchor=config["anchor"], temporal=config["temporal"], @@ -129,7 +130,7 @@ def _array_stats(stats): if increment_vars: modality_stats["increments"] = _array_stats(increment_stats) - out_path = PATHS.stats_zarr_path(modality, config["spatial"]) + out_path = paths.stats_zarr_path(modality, config["spatial"]) ModalityStatistics(modality_stats).to_zarr(str(out_path)) # Record variable names next to the positional statistics: base data types carry the diff --git a/scripts/assets/run_baselines.py b/scripts/assets/run_baselines.py index 67780fa..f83659b 100644 --- a/scripts/assets/run_baselines.py +++ b/scripts/assets/run_baselines.py @@ -15,9 +15,10 @@ from deep_lst.baselines import ClimatologyExtractor, Era5Extractor, Era5LandExtractor, PersistenceExtractor from deep_lst.dataset.dataset import MultimodalDataset +from deep_lst.utils import ExperimentPaths from deep_lst.utils.config import split_views -CONF_DIR = "/Net/Groups/BGI/people/mwessel/deep_lst/conf" +CONF_DIR = Path(__file__).resolve().parents[2] / "conf" REFERENCE_EXTRACTORS = {"era5": Era5Extractor, "era5_land": Era5LandExtractor} @@ -49,9 +50,9 @@ def build_config(region: str): """Full data config for a region: train.yaml's test split (stores/load) with the eval region's spatial/anchor/temporal overlaid — the same inputs preload_shared saw at inference. The test dataset dict the extractors read is attached as config["test_dataset"].""" - with initialize_config_dir(version_base=None, config_dir=CONF_DIR): + with initialize_config_dir(version_base=None, config_dir=str(CONF_DIR)): cfg = compose(config_name="train") - region_cfg = OmegaConf.load(Path(CONF_DIR) / "eval" / f"{region}.yaml") + region_cfg = OmegaConf.load(CONF_DIR / "eval" / f"{region}.yaml") cfg.splits.test = OmegaConf.merge(cfg.splits.test, region_cfg.splits.test) config = OmegaConf.to_container(cfg, resolve=True) config["test_dataset"] = split_views(config)["test"] @@ -63,7 +64,8 @@ def main(): config = build_config(args.region) store_key = args.out_key or config["test_dataset"]["spatial"] - shared = MultimodalDataset.preload_shared(config["modality_ids"], **config["test_dataset"]) + paths = ExperimentPaths.from_config(config.get("paths")) + shared = MultimodalDataset.preload_shared(config["modality_ids"], paths=paths, **config["test_dataset"]) persistence = PersistenceExtractor( var_name="LST", test_year=args.test_year, overwrite=args.overwrite, force_sparse=args.force_sparse diff --git a/scripts/inference/run_inference.py b/scripts/inference/run_inference.py index 59fa49e..047c270 100644 --- a/scripts/inference/run_inference.py +++ b/scripts/inference/run_inference.py @@ -25,7 +25,7 @@ @hydra.main(config_path="../../conf", config_name="infer", version_base="1.3") def run_inference(cfg: DictConfig) -> None: - paths = ExperimentPaths() + paths = ExperimentPaths.from_config(cfg.get("paths")) config = load_run_config(cfg, paths) test_view = split_views(config)["test"] td_keys = get_keys_from_config(test_view) @@ -46,8 +46,8 @@ def run_inference(cfg: DictConfig) -> None: ) modality_ids = config["modality_ids"] - shared = MultimodalDataset.preload_shared(modality_ids, **test_view) - dataset = MultimodalDataset.from_modalities(modality_ids, shared, **test_view) + shared = MultimodalDataset.preload_shared(modality_ids, paths=paths, **test_view) + dataset = MultimodalDataset.from_modalities(modality_ids, shared, paths=paths, **test_view) print(f"Experiment : {cfg.experiment} / {cfg.version}") print(f"Eval : {cfg.eval_name}") print(f"init_fill : {init_fill} (trained {trained_fill}, nowcast {nowcast})") diff --git a/scripts/sensitivity/run_sensitivity.py b/scripts/sensitivity/run_sensitivity.py index 7ec1a84..8e22ee4 100644 --- a/scripts/sensitivity/run_sensitivity.py +++ b/scripts/sensitivity/run_sensitivity.py @@ -31,12 +31,12 @@ @hydra.main(config_path="../../conf", config_name="sensitivity", version_base="1.3") def main(cfg: DictConfig) -> None: - paths = ExperimentPaths() + paths = ExperimentPaths.from_config(cfg.get("paths")) config = load_run_config(cfg, paths) settings = cfg.sensitivity out_dir = sensitivity_dir(paths, cfg.experiment, cfg.version, cfg.eval_name, settings.method, settings.block) - inference = PerturbedInference(cfg, config) + inference = PerturbedInference(cfg, config, paths=paths) if settings.variables is None: variables = stored_inputs(config, inference.shared["var_names"]) else: diff --git a/tests/test_config_golden.py b/tests/test_config_golden.py index e27d6be..d472e95 100644 --- a/tests/test_config_golden.py +++ b/tests/test_config_golden.py @@ -208,8 +208,19 @@ def test_training_path_overrides_leave_scientific_config_unchanged(): overridden = _compose( [*NEW_OVERRIDES["default"], "paths.eozarr_root=local-data", "paths.preload_cache_root=local-cache"] ) - assert default.pop("paths") == {"eozarr_root": None, "preload_cache_root": None} - assert overridden.pop("paths") == {"eozarr_root": "local-data", "preload_cache_root": "local-cache"} + expected_paths = default.pop("paths") | {"eozarr_root": "local-data", "preload_cache_root": "local-cache"} + assert overridden.pop("paths") == expected_paths + assert overridden == default + + +def test_modality_store_root_lives_only_in_shared_paths(): + default = _compose(NEW_OVERRIDES["default"]) + overridden = _compose([*NEW_OVERRIDES["default"], "+paths.store_roots.seviri=local-seviri"]) + for view in config_utils.split_views(overridden).values(): + assert "store_root" not in view["seviri"] + assert "store_root" not in view["era5"] + assert "store_root" not in view["era5_land"] + assert overridden["paths"]["store_roots"].pop("seviri") == "local-seviri" assert overridden == default diff --git a/tests/test_io.py b/tests/test_io.py index 560776b..4443550 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -4,10 +4,26 @@ hermetic — nothing depends on the real on-disk layout. """ +from pathlib import Path + import pytest +from hydra import compose, initialize_config_dir from deep_lst.utils.io import ExperimentPaths +CONF_DIR = Path(__file__).resolve().parents[1] / "conf" + + +@pytest.mark.parametrize("entrypoint", ["train", "finetune", "infer", "statistics", "sensitivity"]) +def test_entrypoints_use_the_shared_paths_file(entrypoint): + with initialize_config_dir(config_dir=str(CONF_DIR), version_base="1.3"): + default = compose(config_name=entrypoint) + cfg = compose(config_name=entrypoint, overrides=["+paths.store_roots.seviri=local-seviri"]) + assert ExperimentPaths.from_config(default.paths) == ExperimentPaths() + paths = ExperimentPaths.from_config(cfg.paths) + assert paths.store_roots == {"seviri": "local-seviri"} + assert paths.eozarr_root == ExperimentPaths().eozarr_root + @pytest.fixture def paths(tmp_path): @@ -49,6 +65,26 @@ def test_explicit_cache_root_overrides_environment(monkeypatch, tmp_path): ) +@pytest.mark.parametrize("root_kind", ["default", "string", "path", "relative"]) +def test_store_root_override_keeps_directory_and_zip_selection(tmp_path, monkeypatch, root_kind): + monkeypatch.chdir(tmp_path) + paths = ExperimentPaths(eozarr_root=tmp_path / "shared") + root = paths.eozarr_root if root_kind == "default" else tmp_path / "modality" + if root_kind == "relative": + root = Path("modality") + kwargs = {} if root_kind == "default" else {"store_root": str(root) if root_kind == "string" else root} + directory = root / "tiny.eozarr" + archive = root / "tiny.eozarr.zip" + root.mkdir(parents=True) + assert paths.eozarr_store_path("tiny", **kwargs) == directory + archive.touch() + assert paths.eozarr_store_path("tiny", **kwargs) == archive + (directory / "data").mkdir(parents=True) + (directory / "data" / "zarr.json").write_text("{}") + assert paths.eozarr_store_path("tiny", **kwargs) == directory + assert paths.eozarr_root == tmp_path / "shared" + + # ── directory resolution ────────────────────────────────────────────────────── diff --git a/tests/test_reader_store_roots.py b/tests/test_reader_store_roots.py new file mode 100644 index 0000000..55798b6 --- /dev/null +++ b/tests/test_reader_store_roots.py @@ -0,0 +1,97 @@ +"""Per-modality store roots for statistics and baseline metadata readers.""" + +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pytest +from omegaconf import OmegaConf + +pytest.importorskip("eodata") +from deep_lst.baselines import base # noqa: E402 +from deep_lst.baselines.era5land import Era5LandExtractor # noqa: E402 +from deep_lst.dataset import dataset # noqa: E402 +from deep_lst.utils.io import ExperimentPaths # noqa: E402 +from scripts.assets import compute_statistics # noqa: E402 + + +@pytest.mark.parametrize( + "store_roots, legacy", [({}, None), ({"seviri": "custom-store"}, "old-store"), ({}, "old-store")] +) +def test_statistics_dataset_uses_the_selected_store_root(tmp_path, monkeypatch, store_roots, legacy): + monkeypatch.chdir(tmp_path) + paths = ExperimentPaths( + assets_root=tmp_path / "assets", eozarr_root=tmp_path / "default-store", store_roots=store_roots + ) + for path, values in ( + (paths.spatial_indices_path("tiny"), {"src_indices": [0]}), + (paths.temporal_indices_path("tiny"), {"time_indices": [0, 24]}), + ): + path.parent.mkdir(parents=True, exist_ok=True) + np.savez(path, **values) + monkeypatch.setattr(dataset, "anchor_grid", lambda _: None) + monkeypatch.setattr(dataset, "store_grid", lambda _: None) + monkeypatch.setattr(dataset, "map_to_store_rows", lambda *args: np.array([4])) + monkeypatch.setattr(dataset, "get_data_reader_class", lambda _: lambda store, average_hourly: None) + stores = [] + reader = SimpleNamespace() + + def open_reader(modality, store, **kwargs): + stores.append(store) + return reader + + monkeypatch.setattr(dataset.eodata, "get_data_reader", open_reader) + result = dataset.UnimodalDataset.from_config( + "seviri", "tiny", "tiny", "mtg", "tiny", store_root=legacy, paths=paths + ) + store_root = store_roots.get("seviri", legacy) + expected_root = paths.eozarr_root if store_root is None else Path(store_root) + assert stores == [str(expected_root / "tiny.eozarr")] + assert result.reader is reader + np.testing.assert_array_equal(result.rows, [4]) + assert result.stat_days == [dataset.PRELOAD_START_DAY, dataset.PRELOAD_START_DAY + 1] + + +@pytest.mark.parametrize("store_root", [None, "custom-store"]) +def test_statistics_command_forwards_the_paths(monkeypatch, store_root): + cfg = OmegaConf.create( + dict( + modality="seviri", + sources={"seviri": {"store": "tiny"}}, + spatial="tiny", + anchor="mtg", + temporal="tiny", + paths={"eozarr_root": "shared", "store_roots": {"seviri": store_root}}, + ) + ) + + def stop_at_dataset(**kwargs): + assert kwargs["store"] == "tiny" + assert kwargs["paths"].store_roots["seviri"] == store_root + assert kwargs["paths"].eozarr_root == Path("shared") + raise RuntimeError("statistics dataset reached") + + monkeypatch.setattr(compute_statistics.UnimodalDataset, "from_config", staticmethod(stop_at_dataset)) + with pytest.raises(RuntimeError, match="statistics dataset reached"): + compute_statistics.main.__wrapped__(cfg) + + +@pytest.mark.parametrize("store_root", [None, "custom-store"]) +def test_baseline_metadata_uses_the_modality_store_root(tmp_path, monkeypatch, store_root): + monkeypatch.chdir(tmp_path) + extractor = Era5LandExtractor("skt", 2024) + extractor.paths = ExperimentPaths(eozarr_root=tmp_path / "default-store") + extractor.paths.store_roots["era5_land"] = store_root + extractor.config = {"test_dataset": {"era5_land": {"store": "tiny"}}} + stores = [] + + def open_reader(modality, store, **kwargs): + assert modality == "era5_land" + stores.append(store) + return SimpleNamespace(data_arr=SimpleNamespace(attrs={"metadata": {"skt": {"units": "K"}}})) + + monkeypatch.setattr(base, "get_data_reader", open_reader) + attrs = extractor._metadata_attrs("era5_land", "tiny", "skt") + expected_root = extractor.paths.eozarr_root if store_root is None else Path(store_root) + assert stores == [str(expected_root / "tiny.eozarr")] + assert attrs == dict(variable="skt", units="K", long_name="skt", description="", test_year="2024") diff --git a/tests/test_training_paths.py b/tests/test_training_paths.py index 9e2e052..d795a6f 100644 --- a/tests/test_training_paths.py +++ b/tests/test_training_paths.py @@ -63,6 +63,8 @@ def test_configured_reader_and_cache_preserve_samples_on_cold_and_warm_load(tmp_ monkeypatch.chdir(tmp_path) root = Path(".") if explicit_paths else tmp_path paths = ExperimentPaths(assets_root=root / "assets", eozarr_root=root / "data", preload_cache_root=root / "cache") + if explicit_paths: + paths.store_roots["seviri"] = "modality-data" spatial = paths.spatial_indices_path("tiny") spatial.parent.mkdir(parents=True) np.savez(spatial, src_indices=[0]) @@ -84,7 +86,7 @@ def test_configured_reader_and_cache_preserve_samples_on_cold_and_warm_load(tmp_ def reader(modality, store, **kwargs): stores.append(store) - return SimpleNamespace(schema={}, data_arr=np.empty(0, dtype=[("LST", "f4")])) + return SimpleNamespace(store=store, schema={}, data_arr=np.empty(0, dtype=[("LST", "f4")])) def normalizer(spec, schema): normalizers.append(spec) @@ -97,7 +99,13 @@ def computed_stats(path): column[0, 3] = float("nan") monkeypatch.setattr(dataset.eodata, "get_data_reader", reader) monkeypatch.setattr(dataset.ModalityNormalizer, "from_spec", staticmethod(normalizer)) - monkeypatch.setattr(dataset, "_preload_columns", lambda *args, **kwargs: {"data": column}) + monkeypatch.setattr( + dataset, + "_preload_columns", + lambda reader, *args, **kwargs: { + "data": column + (100 if Path(reader.store).parent.name == "changed-data" else 0) + }, + ) monkeypatch.setattr(dataset, "load_computed_stats", computed_stats) split = dict( spatial="tiny", @@ -118,8 +126,19 @@ def computed_stats(path): for data in (module.train_dataset, module.val_dataset, module.test_dataset): np.testing.assert_array_equal(data.indices[:, 1], dataset.STORE_EPOCH_OFFSET + np.array([2, 3])) torch.testing.assert_close(data[0]["seviri", "LST"].flatten(), column[0, :5, 0], equal_nan=True) - assert stores == [str(paths.eozarr_store_path("tiny"))] + expected_store = Path("modality-data/tiny.eozarr") if explicit_paths else paths.eozarr_store_path("tiny") + assert stores == [str(expected_store)] assert normalizers == [f"zscore:{stats}"] assert computed == [stats] * 6 assert len(list(paths.preload_cache_root.glob("preload_tiny_*.pt"))) == 1 assert dataset.PATHS is original_paths + if explicit_paths: + paths.store_roots["seviri"] = "changed-data" + changed = LitDataModule(experiment_paths=paths, **module.kwargs) + changed.setup() + torch.testing.assert_close( + changed.train_dataset[0]["seviri", "LST"].flatten(), column[0, :5, 0] + 100, equal_nan=True + ) + assert stores[-1] == str(Path("changed-data/tiny.eozarr")) + assert len(stores) == 2 + assert len(list(paths.preload_cache_root.glob("preload_tiny_*.pt"))) == 2