From e84eb2419d38a3a0339f179fc809868668d649d0 Mon Sep 17 00:00:00 2001 From: ramin_yz Date: Fri, 13 Nov 2026 21:35:57 +0100 Subject: [PATCH 1/3] feat: allow a separate store root for each modality Read optional sources..store_root through the existing path resolver. Forward it to dataset, statistics and baseline metadata readers. Keep the shared-root fallback and directory/ZIP selection unchanged. Include explicit modality roots in preload cache keys so changing roots cannot return data cached from another location. Keep existing default cache keys and scientific settings unchanged. Add focused path, config, cache and reader-forwarding regressions. --- deep_lst/baselines/base.py | 5 +- deep_lst/dataset/dataset.py | 14 ++++- deep_lst/utils/io.py | 9 +-- scripts/assets/compute_statistics.py | 1 + tests/test_config_golden.py | 11 ++++ tests/test_io.py | 22 +++++++ tests/test_reader_store_roots.py | 89 ++++++++++++++++++++++++++++ tests/test_training_paths.py | 25 +++++++- 8 files changed, 165 insertions(+), 11 deletions(-) create mode 100644 tests/test_reader_store_roots.py diff --git a/deep_lst/baselines/base.py b/deep_lst/baselines/base.py index fa6f863..9ac0209 100644 --- a/deep_lst/baselines/base.py +++ b/deep_lst/baselines/base.py @@ -86,7 +86,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.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..1a38beb 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,7 +243,7 @@ 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): """Stream the MTG pixel selection (spatial) over the statistics timestep subset (temporal).""" anchor_ids = _load_anchor_ids(spatial) rows = np.unique(map_to_store_rows(anchor_grid(anchor), anchor_ids, store_grid(modality))) @@ -260,7 +261,9 @@ 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) + reader = eodata.get_data_reader( + modality, store=str(PATHS.eozarr_store_path(store, store_root)), **reader_kwargs + ) return cls(reader, rows, stat_days) @@ -406,6 +409,9 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs): }, } for modality in modality_ids: + store_root = kwargs[modality].get("store_root") + 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 +439,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"], kwargs[modality].get("store_root"))), + **reader_kwargs, ) normalizer = ModalityNormalizer.from_spec( diff --git a/deep_lst/utils/io.py b/deep_lst/utils/io.py index 216a887..f809499 100644 --- a/deep_lst/utils/io.py +++ b/deep_lst/utils/io.py @@ -50,14 +50,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/scripts/assets/compute_statistics.py b/scripts/assets/compute_statistics.py index 3637478..65c2c97 100644 --- a/scripts/assets/compute_statistics.py +++ b/scripts/assets/compute_statistics.py @@ -101,6 +101,7 @@ def main(cfg: DictConfig) -> None: dataset = UnimodalDataset.from_config( modality=modality, store=source["store"], + store_root=source.get("store_root"), spatial=config["spatial"], anchor=config["anchor"], temporal=config["temporal"], diff --git a/tests/test_config_golden.py b/tests/test_config_golden.py index e27d6be..d8e880c 100644 --- a/tests/test_config_golden.py +++ b/tests/test_config_golden.py @@ -213,6 +213,17 @@ def test_training_path_overrides_leave_scientific_config_unchanged(): assert overridden == default +def test_modality_store_root_reaches_each_split_without_changing_other_settings(): + default = _compose(NEW_OVERRIDES["default"]) + overridden = _compose([*NEW_OVERRIDES["default"], "+sources.seviri.store_root=local-seviri"]) + for view in config_utils.split_views(overridden).values(): + assert view["seviri"]["store_root"] == "local-seviri" + assert "store_root" not in view["era5"] + assert "store_root" not in view["era5_land"] + assert overridden["sources"]["seviri"].pop("store_root") == "local-seviri" + assert overridden == default + + @pytest.mark.parametrize("case", CASES) def test_migrated_fixture_equals_the_new_composition(case): migrated = config_utils.migrate_config(_fixture(case)) diff --git a/tests/test_io.py b/tests/test_io.py index 560776b..538591c 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -4,6 +4,8 @@ hermetic — nothing depends on the real on-disk layout. """ +from pathlib import Path + import pytest from deep_lst.utils.io import ExperimentPaths @@ -49,6 +51,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..5e88f02 --- /dev/null +++ b/tests/test_reader_store_roots.py @@ -0,0 +1,89 @@ +"""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_root", [None, "custom-store"]) +def test_statistics_dataset_uses_the_selected_store_root(tmp_path, monkeypatch, store_root): + monkeypatch.chdir(tmp_path) + paths = ExperimentPaths(assets_root=tmp_path / "assets", eozarr_root=tmp_path / "default-store") + 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, "PATHS", paths) + 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) + kwargs = {} if store_root is None else {"store_root": store_root} + result = dataset.UnimodalDataset.from_config("seviri", "tiny", "tiny", "mtg", "tiny", **kwargs) + 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_source_store_root(monkeypatch, store_root): + source = {"store": "tiny"} + if store_root is not None: + source["store_root"] = store_root + cfg = OmegaConf.create( + dict(modality="seviri", sources={"seviri": source}, spatial="tiny", anchor="mtg", temporal="tiny") + ) + + def stop_at_dataset(**kwargs): + assert kwargs["store"] == "tiny" + assert kwargs.get("store_root") == store_root + 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") + source = {"store": "tiny"} + if store_root is not None: + source["store_root"] = store_root + extractor.config = {"test_dataset": {"era5_land": source}} + 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..f96c6ce 100644 --- a/tests/test_training_paths.py +++ b/tests/test_training_paths.py @@ -84,7 +84,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 +97,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", @@ -105,6 +111,8 @@ def computed_stats(path): stats_spatial="mtg_new", seviri=dict(store="tiny", load={"data": ["LST"]}, lookback=2, horizon=2, prognostics=["LST"]), ) + if explicit_paths: + split["seviri"]["store_root"] = "modality-data" for _ in range(2): module = LitDataModule( experiment_paths=paths if explicit_paths else None, @@ -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: + split["seviri"]["store_root"] = "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 From f3ea9367be66246569def4315b62243ef1288cc8 Mon Sep 17 00:00:00 2001 From: ramin_yz Date: Fri, 13 Nov 2026 21:35:58 +0100 Subject: [PATCH 2/3] docs: explain per-modality store roots Document the optional source setting, its shared-root fallback and Hydra syntax. Explain when explicit modality roots separate preload caches. --- docs/CONFIGURATION.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 3ab6c6d..b32e4d4 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -72,7 +72,8 @@ relative to the repository working directory. The overrides are saved in the run uv run python deep_lst/train.py paths.eozarr_root=/data/eozarr paths.preload_cache_root=/scratch/deep_lst-cache ``` -Cache keys are unchanged; use a separate cache root when the source data content differs. +Changing only `paths.eozarr_root` does not change cache keys; 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. @@ -167,11 +168,24 @@ that training, inference, the baselines and the statistics script share. | Key under `sources.` | Meaning | |---|---| | `store` | name of the `.eozarr` store | +| `store_root` | optional; root directory for this modality's store. If omitted or `null`, use the shared `ExperimentPaths.eozarr_root` (`paths.eozarr_root` in training). | | `load` | variables read from the store, by data type (below). This is what reaches memory, not what the model sees; the model's variables are chosen in the `data` group and have to be listed here. | | `transform` | optional; a value transform applied before the normalisation. `signed_log1p` is sign(x) * log(1 + \|x\|), for variables that span orders of magnitude. The statistics have to be computed under the same transform; training checks this before it reads data. | | `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` | +For example, keep ERA5 in the shared root while reading SEVIRI from another directory: + +``` +uv run python deep_lst/train.py +sources.seviri.store_root=/data/deep_lst +uv run scripts/assets/compute_statistics.py modality=seviri +sources.seviri.store_root=/data/deep_lst +``` + +The `+` adds this optional field in Hydra; it can also be added to the modality's source YAML. +The selected root contains `.eozarr` or `.eozarr.zip`, with the existing directory/ZIP +selection unchanged. Relative roots stay relative to the working directory. The source setting +is saved with the run config and follows the modality through the existing split views. + Data types under `load`: | Data type | Holds | @@ -197,6 +211,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. +An explicit `store_root` is included in that key using its resolved path. Different roots use +separate caches; leaving `store_root` unset keeps the existing cache keys. ### 3.2 `data` From 456d884319eb00af41d18113f9cb299dcd9b4a30 Mon Sep 17 00:00:00 2001 From: ramin_yz Date: Sat, 21 Nov 2026 14:06:52 +0100 Subject: [PATCH 3/3] Keep store and cache roots in conf/paths.yaml Load the same paths for the existing reading commands, with an optional root per modality. Keep the previous BGC defaults and existing preload keys when the default stores are used. Keep reading older saved store_root overrides and ship paths.yaml in the wheel for callers outside the checkout. --- conf/infer.yaml | 1 + conf/paths.yaml | 9 +++++ conf/statistics.yaml | 1 + conf/train.yaml | 5 +-- deep_lst/baselines/base.py | 4 +- deep_lst/dataset/dataset.py | 17 +++++--- deep_lst/finetune.py | 4 +- deep_lst/sensitivity/forecast.py | 8 ++-- deep_lst/train.py | 2 +- deep_lst/utils/full_store.py | 3 +- deep_lst/utils/io.py | 39 ++++++++++++++----- docs/CONFIGURATION.md | 54 ++++++++++++-------------- docs/RUNBOOK.md | 13 ++----- pyproject.toml | 5 ++- scripts/assets/compute_statistics.py | 6 +-- scripts/assets/run_baselines.py | 10 +++-- scripts/inference/run_inference.py | 6 +-- scripts/sensitivity/run_sensitivity.py | 4 +- tests/test_config_golden.py | 12 +++--- tests/test_io.py | 14 +++++++ tests/test_reader_store_roots.py | 40 +++++++++++-------- tests/test_training_paths.py | 6 +-- 22 files changed, 160 insertions(+), 103 deletions(-) create mode 100644 conf/paths.yaml 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 9ac0209..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,7 @@ 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.""" - store_root = self.config["test_dataset"][modality].get("store_root") + 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 ) diff --git a/deep_lst/dataset/dataset.py b/deep_lst/dataset/dataset.py index 1a38beb..b78650c 100644 --- a/deep_lst/dataset/dataset.py +++ b/deep_lst/dataset/dataset.py @@ -243,11 +243,12 @@ def __getitem__(self, index): return leaves @classmethod - def from_config(cls, modality, store, spatial, anchor, temporal, workers=1, store_root=None): + 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 @@ -261,8 +262,9 @@ def from_config(cls, modality, store, spatial, anchor, temporal, workers=1, stor } accepted = inspect.signature(get_data_reader_class(modality)).parameters reader_kwargs = {key: value for key, value in reader_kwargs.items() if key in accepted} + 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 + modality, store=str(paths.eozarr_store_path(store, store_root)), **reader_kwargs ) return cls(reader, rows, stat_days) @@ -391,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. @@ -409,7 +414,7 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs): }, } for modality in modality_ids: - store_root = kwargs[modality].get("store_root") + 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") @@ -440,7 +445,7 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs): 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"], kwargs[modality].get("store_root"))), + store=str(paths.eozarr_store_path(kwargs[modality]["store"], store_roots[modality])), **reader_kwargs, ) 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 f809499..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 diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index b32e4d4..9c4472b 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -56,28 +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 ``` -Changing only `paths.eozarr_root` does not change cache keys; 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 @@ -168,23 +174,13 @@ that training, inference, the baselines and the statistics script share. | Key under `sources.` | Meaning | |---|---| | `store` | name of the `.eozarr` store | -| `store_root` | optional; root directory for this modality's store. If omitted or `null`, use the shared `ExperimentPaths.eozarr_root` (`paths.eozarr_root` in training). | | `load` | variables read from the store, by data type (below). This is what reaches memory, not what the model sees; the model's variables are chosen in the `data` group and have to be listed here. | | `transform` | optional; a value transform applied before the normalisation. `signed_log1p` is sign(x) * log(1 + \|x\|), for variables that span orders of magnitude. The statistics have to be computed under the same transform; training checks this before it reads data. | | `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` | -For example, keep ERA5 in the shared root while reading SEVIRI from another directory: - -``` -uv run python deep_lst/train.py +sources.seviri.store_root=/data/deep_lst -uv run scripts/assets/compute_statistics.py modality=seviri +sources.seviri.store_root=/data/deep_lst -``` - -The `+` adds this optional field in Hydra; it can also be added to the modality's source YAML. -The selected root contains `.eozarr` or `.eozarr.zip`, with the existing directory/ZIP -selection unchanged. Relative roots stay relative to the working directory. The source setting -is saved with the run config and follows the modality through the existing split views. +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`: @@ -211,8 +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. -An explicit `store_root` is included in that key using its resolved path. Different roots use -separate caches; leaving `store_root` unset keeps the existing cache keys. +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 65c2c97..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", []) @@ -102,6 +101,7 @@ def main(cfg: DictConfig) -> None: modality=modality, store=source["store"], store_root=source.get("store_root"), + paths=paths, spatial=config["spatial"], anchor=config["anchor"], temporal=config["temporal"], @@ -130,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 d8e880c..d472e95 100644 --- a/tests/test_config_golden.py +++ b/tests/test_config_golden.py @@ -208,19 +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_reaches_each_split_without_changing_other_settings(): +def test_modality_store_root_lives_only_in_shared_paths(): default = _compose(NEW_OVERRIDES["default"]) - overridden = _compose([*NEW_OVERRIDES["default"], "+sources.seviri.store_root=local-seviri"]) + overridden = _compose([*NEW_OVERRIDES["default"], "+paths.store_roots.seviri=local-seviri"]) for view in config_utils.split_views(overridden).values(): - assert view["seviri"]["store_root"] == "local-seviri" + assert "store_root" not in view["seviri"] assert "store_root" not in view["era5"] assert "store_root" not in view["era5_land"] - assert overridden["sources"]["seviri"].pop("store_root") == "local-seviri" + 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 538591c..4443550 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -7,9 +7,23 @@ 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): diff --git a/tests/test_reader_store_roots.py b/tests/test_reader_store_roots.py index 5e88f02..55798b6 100644 --- a/tests/test_reader_store_roots.py +++ b/tests/test_reader_store_roots.py @@ -15,17 +15,20 @@ from scripts.assets import compute_statistics # noqa: E402 -@pytest.mark.parametrize("store_root", [None, "custom-store"]) -def test_statistics_dataset_uses_the_selected_store_root(tmp_path, monkeypatch, store_root): +@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") + 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, "PATHS", paths) 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])) @@ -38,8 +41,10 @@ def open_reader(modality, store, **kwargs): return reader monkeypatch.setattr(dataset.eodata, "get_data_reader", open_reader) - kwargs = {} if store_root is None else {"store_root": store_root} - result = dataset.UnimodalDataset.from_config("seviri", "tiny", "tiny", "mtg", "tiny", **kwargs) + 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 @@ -48,17 +53,22 @@ def open_reader(modality, store, **kwargs): @pytest.mark.parametrize("store_root", [None, "custom-store"]) -def test_statistics_command_forwards_the_source_store_root(monkeypatch, store_root): - source = {"store": "tiny"} - if store_root is not None: - source["store_root"] = store_root +def test_statistics_command_forwards_the_paths(monkeypatch, store_root): cfg = OmegaConf.create( - dict(modality="seviri", sources={"seviri": source}, spatial="tiny", anchor="mtg", temporal="tiny") + 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.get("store_root") == store_root + 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)) @@ -71,10 +81,8 @@ def test_baseline_metadata_uses_the_modality_store_root(tmp_path, monkeypatch, s monkeypatch.chdir(tmp_path) extractor = Era5LandExtractor("skt", 2024) extractor.paths = ExperimentPaths(eozarr_root=tmp_path / "default-store") - source = {"store": "tiny"} - if store_root is not None: - source["store_root"] = store_root - extractor.config = {"test_dataset": {"era5_land": source}} + extractor.paths.store_roots["era5_land"] = store_root + extractor.config = {"test_dataset": {"era5_land": {"store": "tiny"}}} stores = [] def open_reader(modality, store, **kwargs): diff --git a/tests/test_training_paths.py b/tests/test_training_paths.py index f96c6ce..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]) @@ -111,8 +113,6 @@ def computed_stats(path): stats_spatial="mtg_new", seviri=dict(store="tiny", load={"data": ["LST"]}, lookback=2, horizon=2, prognostics=["LST"]), ) - if explicit_paths: - split["seviri"]["store_root"] = "modality-data" for _ in range(2): module = LitDataModule( experiment_paths=paths if explicit_paths else None, @@ -133,7 +133,7 @@ def computed_stats(path): assert len(list(paths.preload_cache_root.glob("preload_tiny_*.pt"))) == 1 assert dataset.PATHS is original_paths if explicit_paths: - split["seviri"]["store_root"] = "changed-data" + paths.store_roots["seviri"] = "changed-data" changed = LitDataModule(experiment_paths=paths, **module.kwargs) changed.setup() torch.testing.assert_close(