Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ wheels/
# experiments
outputs/
/data/
/cache/
*.ckpt
.ipynb_checkpoints/
__pycache__/
Expand Down
3 changes: 1 addition & 2 deletions conf/paths.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
# 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
preload_cache_root: ./cache

# Only list modalities whose stores live under a different root.
store_roots: {}
10 changes: 4 additions & 6 deletions deep_lst/dataset/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@
"data_static_categorical": "data_static_categorical_arr",
}

PATHS = ExperimentPaths()

# time_indices_*.npz are hours since the data start (2016-01-01); the new full stores are indexed
# on the 1970 epoch, so a time index must be shifted by this offset to address the store.
# FLAGGED for later: cleaner to regenerate the indices as absolute T1H (see migration notes).
Expand Down Expand Up @@ -79,7 +77,7 @@ def load_samples(
def _load_anchor_ids(spatial_name, paths=None):
"""Anchor cell ids for a split: global MTG ids for training, seviri equiangular pixels
for an eval holdout region."""
paths = paths or PATHS
paths = paths or ExperimentPaths()
return np.sort(np.load(paths.spatial_indices_path(spatial_name))["src_indices"].astype(np.int64))


Expand Down Expand Up @@ -245,7 +243,7 @@ def __getitem__(self, index):
@classmethod
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)."""
paths = paths or PATHS
paths = paths or ExperimentPaths()
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)
Expand Down Expand Up @@ -387,7 +385,7 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs):
are read. Columns depend only on (anchors, store), not the temporal split, so this runs
once — a full-axis cache per split would not fit in RAM.
"""
paths = paths or PATHS
paths = paths or ExperimentPaths()
spatial_name = kwargs["spatial"]
stats_tag = stats_spatial(kwargs)
anchor_ids = _load_anchor_ids(spatial_name, paths)
Expand Down Expand Up @@ -479,7 +477,7 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs):
@classmethod
def from_modalities(cls, modality_ids, shared, paths=None, **kwargs):
"""Build one split's dataset from the shared preloaded columns + this split's anchors."""
paths = paths or PATHS
paths = paths or ExperimentPaths()
stats_tag = stats_spatial(kwargs)
computed_stats = {m: load_computed_stats(paths.stats_zarr_path(m, stats_tag)) for m in modality_ids}

Expand Down
14 changes: 8 additions & 6 deletions deep_lst/utils/full_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@
from deep_lst.dataset.dataset import (
DATA_TYPES,
DATA_TYPES_ENABLE,
PATHS,
_load_anchor_ids,
_preload_columns,
)
from deep_lst.utils.io import ExperimentPaths
from deep_lst.utils.spatial import anchor_grid, map_to_store_rows, store_grid

# Full-store names, mirroring the data version pinned in conf/train.yaml.
Expand All @@ -27,7 +27,7 @@
ERA5_LAND_STORE = "era5_land_2016_2025"


def open_store_reader(modality, store, data_types):
def open_store_reader(modality, store, data_types, *, paths=None):
"""Full-store reader with exactly the `data_types` enabled (data is always read).

Enable-flags for data types this modality's reader doesn't accept (ERA5 has no
Expand All @@ -38,11 +38,12 @@ 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}
store_path = PATHS.eozarr_store_path(store, PATHS.store_roots.get(modality))
paths = paths or ExperimentPaths()
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):
def load_store_columns(modality, store, spatial, load, anchor="mtg", day_range=None, num_workers=8, *, paths=None):
"""Raw full-store columns for one spatial selection.

Anchor ids from indices_{spatial}.npz are mapped to the modality's native store
Expand All @@ -56,10 +57,11 @@ def load_store_columns(modality, store, spatial, load, anchor="mtg", day_range=N
columns[data_type][inverse] expands back to per-anchor order. Cell lon/lat:
store_grid(modality).centers[unique_rows].
"""
anchor_ids = _load_anchor_ids(spatial)
paths = paths or ExperimentPaths()
anchor_ids = _load_anchor_ids(spatial, paths)
rows = map_to_store_rows(anchor_grid(anchor), anchor_ids, store_grid(modality))
unique_rows, inverse = np.unique(rows, return_inverse=True)
reader = open_store_reader(modality, store, load)
reader = open_store_reader(modality, store, load, paths=paths)
select = {
data_type: [list(getattr(reader, DATA_TYPES[data_type]).dtype.fields).index(var) for var in names]
for data_type, names in load.items()
Expand Down
15 changes: 2 additions & 13 deletions deep_lst/utils/io.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import getpass
import os
import re
from dataclasses import dataclass, field
from functools import cache
Expand All @@ -15,13 +13,6 @@ def _default_paths() -> dict:
)


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:
"""Centralised path resolution for experiment artifacts."""
Expand All @@ -30,18 +21,16 @@ class ExperimentPaths:
config_root: Path = field(default_factory=lambda: Path("./configs"))
assets_root: Path = field(default_factory=lambda: Path("./assets"))
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()))
preload_cache_root: Path = field(default_factory=lambda: Path(_default_paths()["preload_cache_root"]))
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")
settings.pop("preload_cache_parent", None) # old saved configs
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:
Expand Down
7 changes: 4 additions & 3 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,10 @@ Here SEVIRI uses the separate directory and the other modalities use `eozarr_roo
A null entry explicitly selects the common root. An older saved run can still provide
`sources.<modality>.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 `<preload_cache_parent>/<user>/tmp`. The login name is used when `USER` is unset
or empty. Relative paths are resolved from the working directory.
Set `preload_cache_root` directly in `conf/paths.yaml` or override it on the command line.
The default is `./cache`. The previous per-user scratch directory and
`DEEP_LST_CACHE_ROOT` are no longer selected automatically. To keep using an existing
cache, set `preload_cache_root` to its directory. Relative paths start at the working directory.

```
uv run python deep_lst/train.py paths.eozarr_root=/data/eozarr paths.preload_cache_root=/scratch/deep_lst-cache
Expand Down
4 changes: 2 additions & 2 deletions docs/RUNBOOK.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@ assets/baselines/<kind>/<name>.nc persistence / climatology / ERA5(-Land
Check these locations in a new clone:

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.
and the preload cache. The cache defaults to `./cache`. On the cluster, set
`preload_cache_root` to your scratch directory to keep using your existing 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.
Expand Down
43 changes: 14 additions & 29 deletions tests/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,35 +34,20 @@ def paths(tmp_path):
)


def test_cache_root_uses_environment_without_user(monkeypatch, tmp_path):
monkeypatch.setenv("DEEP_LST_CACHE_ROOT", str(tmp_path / "cache"))
monkeypatch.delenv("USER", raising=False)
assert ExperimentPaths().preload_cache_root == tmp_path / "cache"


@pytest.mark.parametrize("cache_root", [None, ""])
def test_cache_root_defaults_to_current_user(monkeypatch, cache_root):
if cache_root is None:
monkeypatch.delenv("DEEP_LST_CACHE_ROOT", raising=False)
else:
monkeypatch.setenv("DEEP_LST_CACHE_ROOT", cache_root)
monkeypatch.setenv("USER", "test-user")
assert ExperimentPaths().preload_cache_root.as_posix() == "/Net/Groups/BGI/tscratch/test-user/tmp"


def test_cache_root_uses_account_name_when_user_is_unset(monkeypatch):
monkeypatch.delenv("DEEP_LST_CACHE_ROOT", raising=False)
monkeypatch.delenv("USER", raising=False)
monkeypatch.setattr("getpass.getuser", lambda: "test-user")
assert ExperimentPaths().preload_cache_root.as_posix() == "/Net/Groups/BGI/tscratch/test-user/tmp"


def test_explicit_cache_root_overrides_environment(monkeypatch, tmp_path):
monkeypatch.setenv("DEEP_LST_CACHE_ROOT", str(tmp_path / "environment-cache"))
assert (
ExperimentPaths(preload_cache_root=tmp_path / "explicit-cache").preload_cache_root
== tmp_path / "explicit-cache"
)
def test_cache_root_uses_the_configured_directory(monkeypatch, tmp_path):
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("DEEP_LST_CACHE_ROOT", str(tmp_path / "old-env-cache"))
with initialize_config_dir(config_dir=str(CONF_DIR), version_base="1.3"):
cfg = compose(config_name="train", overrides=["paths.preload_cache_root=chosen-cache"])
assert ExperimentPaths().preload_cache_root == Path("cache")
paths = ExperimentPaths.from_config(cfg.paths)
assert paths.preload_cache_path("fingerprint").resolve() == tmp_path / "chosen-cache/preload_fingerprint.pt"
assert not (tmp_path / "old-env-cache").exists()


def test_legacy_cache_parent_uses_the_yaml_default():
paths = ExperimentPaths.from_config({"preload_cache_root": None, "preload_cache_parent": "/old/scratch"})
assert paths.preload_cache_root == Path("cache")


@pytest.mark.parametrize("root_kind", ["default", "string", "path", "relative"])
Expand Down
28 changes: 27 additions & 1 deletion tests/test_reader_store_roots.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Per-modality store roots for statistics and baseline metadata readers."""
"""Per-modality store roots for statistics, baselines and full-store readers."""

from pathlib import Path
from types import SimpleNamespace
Expand All @@ -11,10 +11,36 @@
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 import full_store # noqa: E402
from deep_lst.utils.io import ExperimentPaths # noqa: E402
from scripts.assets import compute_statistics # noqa: E402


def test_full_store_reads_indices_and_columns_with_the_same_paths(tmp_path, monkeypatch):
paths = ExperimentPaths(assets_root=tmp_path / "assets", store_roots={"seviri": str(tmp_path / "seviri")})
indices = paths.spatial_indices_path("tiny")
indices.parent.mkdir(parents=True)
np.savez(indices, src_indices=[0])
monkeypatch.setattr(full_store, "anchor_grid", lambda _: None)
monkeypatch.setattr(full_store, "store_grid", lambda _: None)
monkeypatch.setattr(full_store, "map_to_store_rows", lambda *args: np.array([4]))
monkeypatch.setattr(full_store, "get_data_reader_class", lambda _: lambda store, average_hourly: None)

def open_reader(modality, store, **kwargs):
assert store == str(tmp_path / "seviri/tiny.eozarr")
return SimpleNamespace(data_arr=np.empty(0, dtype=[("LST", "f4")]))

monkeypatch.setattr(full_store.eodata, "get_data_reader", open_reader)
monkeypatch.setattr(full_store, "_preload_columns", lambda *args, **kwargs: {"data": np.array([[281.0]])})
columns, rows, inverse, anchors = full_store.load_store_columns(
"seviri", "tiny", "tiny", {"data": ["LST"]}, paths=paths
)
np.testing.assert_array_equal(columns["data"], [[281.0]])
np.testing.assert_array_equal(rows, [4])
np.testing.assert_array_equal(inverse, [0])
np.testing.assert_array_equal(anchors, [0])


@pytest.mark.parametrize(
"store_roots, legacy", [({}, None), ({"seviri": "custom-store"}, "old-store"), ({}, "old-store")]
)
Expand Down
5 changes: 1 addition & 4 deletions tests/test_training_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ def test_training_passes_paths_to_data_module_and_saves_overrides(tmp_path, monk
config_name="train", overrides=["wandb_logger=false", *[f"paths.{k}={v}" for k, v in overrides.items()]]
)
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("DEEP_LST_CACHE_ROOT", str(tmp_path / "environment-cache"))
choices = dict(model="mlp", objective="rollout", loss="smoothl1", horizon="h24", data="full")
monkeypatch.setattr(train.HydraConfig, "get", lambda: SimpleNamespace(runtime=SimpleNamespace(choices=choices)))
monkeypatch.setattr(train, "check_stats_transform", lambda *args: None)
Expand Down Expand Up @@ -75,8 +74,7 @@ def test_configured_reader_and_cache_preserve_samples_on_cold_and_warm_load(tmp_
stats.mkdir(parents=True)
(stats / "zarr.json").write_text("{}")
if not explicit_paths:
monkeypatch.setattr(dataset, "PATHS", paths)
original_paths = dataset.PATHS
monkeypatch.setattr(dataset, "ExperimentPaths", lambda: paths)
grid = SimpleNamespace(centers=np.array([[20.0, 10.0]]))
monkeypatch.setattr(dataset, "anchor_grid", lambda _: grid)
monkeypatch.setattr(dataset, "store_grid", lambda _: grid)
Expand Down Expand Up @@ -131,7 +129,6 @@ def computed_stats(path):
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)
Expand Down
Loading