Skip to content
Merged
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
2 changes: 1 addition & 1 deletion conf/infer.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
defaults:
- _self_
- paths
- paths: bgc
- eval: gobabeb

# --- required ---
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.
product_root: /Net/Groups/BGI/work_5/scratch/WeatherGenerator/data/deep_lst
preload_cache_root: null
preload_cache_parent: /Net/Groups/BGI/tscratch
preload_cache_root: ./cache

# Only list stores that live under a different root: <store name>: <folder>.
store_roots: {}
2 changes: 2 additions & 0 deletions conf/paths/bgc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
defaults:
- /paths
4 changes: 4 additions & 0 deletions conf/paths/local.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Use a different cache from the BGC profile.
product_root: ./data
preload_cache_root: ./cache/local
store_roots: {}
2 changes: 1 addition & 1 deletion conf/statistics.yaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

defaults:
- _self_
- paths
- paths: bgc
- sources: product

modality: ???
Expand Down
2 changes: 1 addition & 1 deletion conf/train.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
defaults:
- _self_ # base applies first; groups below have higher priority
- paths
- paths: bgc
- sources: product
- model: mlp
- objective: rollout
Expand Down
8 changes: 3 additions & 5 deletions deep_lst/dataset/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@
# Modality carrying the global time features (doy/hod); the finest / target grid.
_ANCHOR_MODALITY = "seviri"

PATHS = ExperimentPaths()

# time_indices_*.npz are hours since the data start (2016-01-01); the 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 @@ -55,7 +53,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 @@ -210,7 +208,7 @@ def preload_shared(cls, modality_ids, paths=None, **kwargs):
read (deep_lst/dataset/preload.py). Columns depend only on (anchors, stores), 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 @@ -265,7 +263,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
23 changes: 13 additions & 10 deletions deep_lst/utils/full_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,21 @@

import numpy as np

from deep_lst.dataset.dataset import PATHS, _load_anchor_ids
from deep_lst.dataset.dataset import _load_anchor_ids
from deep_lst.dataset.preload import open_readers, preload_modality
from deep_lst.utils.io import default_sources
from deep_lst.utils.io import ExperimentPaths, default_sources
from deep_lst.utils.spatial import store_grid


def stores_of(modality, load):
def stores_of(modality, load, *, paths=None):
"""{store name: [variables]} for the variables of `load`.

A variable is taken from the first store of the modality (in the order of
conf/sources/product.yaml) that holds it. It does not have to be listed there, so an
analysis can read variables that training does not load.
"""
readers = open_readers(default_sources()[modality], PATHS)
paths = paths or ExperimentPaths()
readers = open_readers(default_sources()[modality], paths)
stores = {}
for variables in load.values():
for variable in variables:
Expand All @@ -31,7 +32,7 @@ def stores_of(modality, load):
return stores


def load_store_columns(modality, spatial, load, anchor="mtg", day_range=None, num_workers=8):
def load_store_columns(modality, spatial, load, anchor="mtg", day_range=None, num_workers=8, *, paths=None):
"""Raw store columns of one modality for one spatial selection.

Args:
Expand All @@ -42,6 +43,7 @@ def load_store_columns(modality, spatial, load, anchor="mtg", day_range=None, nu
anchor: "mtg", or the modality whose grid rows the anchor ids are.
day_range: (start_day, end_day) in days since 1970, end exclusive. Default: 2016 to 2025.
num_workers: Threads that read time blocks in parallel.
paths: Paths for the selection, product stores and their grids.

Returns:
columns: {leaf: tensor}; leaves on the hourly axis (n_unique, n_days * 24, C), static
Expand All @@ -52,11 +54,12 @@ def load_store_columns(modality, spatial, load, anchor="mtg", day_range=None, nu
to per-anchor order.
anchor_ids: The anchor ids of the selection.
"""
anchor_ids = _load_anchor_ids(spatial)
source = {"stores": stores_of(modality, load), "load": load}
anchor_grid = None if anchor == "mtg" else store_grid(anchor)
paths = paths or ExperimentPaths()
anchor_ids = _load_anchor_ids(spatial, paths)
source = {"stores": stores_of(modality, load, paths=paths), "load": load}
anchor_grid = None if anchor == "mtg" else store_grid(anchor, paths)
columns, inverse, cell_lonlat = preload_modality(
source, anchor, anchor_ids, PATHS, anchor_grid=anchor_grid, day_range=day_range, num_workers=num_workers
source, anchor, anchor_ids, paths, anchor_grid=anchor_grid, day_range=day_range, num_workers=num_workers
)
unique_rows = store_grid(modality).nearest_rows(cell_lonlat[:, 0], cell_lonlat[:, 1])
unique_rows = store_grid(modality, paths).nearest_rows(cell_lonlat[:, 0], cell_lonlat[:, 1])
return columns, np.asarray(unique_rows), inverse, anchor_ids
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 @@ -21,21 +19,14 @@ def default_sources() -> dict:
return OmegaConf.to_container(OmegaConf.load(CONF_DIR / "sources" / "product.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:
"""Centralised path resolution for experiment artifacts."""

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"))
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"]))
product_root: Path = field(default_factory=lambda: Path(_default_paths()["product_root"]))
store_roots: dict[str, str | None] = field(
default_factory=lambda: dict(_default_paths()["store_roots"]), kw_only=True
Expand All @@ -45,10 +36,8 @@ class ExperimentPaths:
def from_config(cls, config) -> "ExperimentPaths":
settings = {**_default_paths(), **{key: value for key, value in (config or {}).items() if value is not None}}
settings.pop("eozarr_root", None) # root of the .eozarr stores, in configs saved before the product stores
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
18 changes: 12 additions & 6 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,12 @@ be edited.

### Data and cache paths

`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. `product_root` is the common directory of the stores; every store is read
Training, fine-tuning, inference, sensitivity, statistics and baseline generation select
a paths profile. The default `paths=bgc` reads the site settings from `conf/paths.yaml`.
Use `paths=local` for stores under `./data` and a separate cache at `./cache/local`.
The baseline script uses `--paths local`.

`product_root` is the common directory of the stores; every store is read
from `<product_root>/<store name>.zarr`. Add an entry to `store_roots` for a store that lives
elsewhere:

Expand All @@ -73,11 +76,14 @@ Here the LST store is read from the separate directory and all other stores from
`product_root`. A null entry explicitly selects the common root. The store names of every
modality are in `conf/sources/product.yaml` (section 3.1).

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` in the paths config or override it on the command line.
The BGC default is `./cache`. The previous per-user scratch directory and
`DEEP_LST_CACHE_ROOT` are no longer selected automatically. To keep using an existing
product-store cache, set `preload_cache_root` to its directory. Relative paths start at
the working directory.

```
uv run python deep_lst/train.py paths=local
uv run python deep_lst/train.py paths.product_root=/data/stores paths.preload_cache_root=/scratch/deep_lst-cache
uv run python scripts/assets/compute_statistics.py modality=seviri +paths.store_roots.seviri_product_hourly_lst=/data/other
```
Expand Down
6 changes: 3 additions & 3 deletions docs/RUNBOOK.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,9 @@ 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.
1. Check `conf/paths.yaml` for the common store directory, any store-specific directories
and the preload cache. The BGC cache defaults to `./cache`. On the cluster, set
`preload_cache_root` to your scratch directory to keep using your existing product-store 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
7 changes: 4 additions & 3 deletions scripts/assets/run_baselines.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def parse_args():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--region", type=str, required=True, help="Eval config name, e.g. passage, dahra, train_mtg.")
p.add_argument("--test_year", type=int, required=True, help="Year the baselines forecast (train years precede it).")
p.add_argument("--paths", choices=("bgc", "local"), default="bgc", help="Site paths profile.")
p.add_argument("--window_days", type=int, default=7, help="Circular DOY window for the smoothed climatology.")
p.add_argument(
"--reference_modality",
Expand All @@ -46,12 +47,12 @@ def parse_args():
return p.parse_args()


def build_config(region: str):
def build_config(region: str, paths_profile: str = "bgc"):
"""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=str(CONF_DIR)):
cfg = compose(config_name="train")
cfg = compose(config_name="train", overrides=[f"paths={paths_profile}"])
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)
Expand All @@ -61,7 +62,7 @@ def build_config(region: str):

def main():
args = parse_args()
config = build_config(args.region)
config = build_config(args.region, args.paths)
store_key = args.out_key or config["test_dataset"]["spatial"]

paths = ExperimentPaths.from_config(config.get("paths"))
Expand Down
52 changes: 25 additions & 27 deletions tests/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,19 @@ def test_entrypoints_use_the_shared_paths_file(entrypoint):
assert paths.product_root == ExperimentPaths().product_root


@pytest.mark.parametrize("entrypoint", ["train", "finetune", "infer", "statistics", "sensitivity"])
def test_local_paths_profile_uses_a_separate_cache(entrypoint):
with initialize_config_dir(config_dir=str(CONF_DIR), version_base="1.3"):
cfg = compose(
config_name=entrypoint,
overrides=["paths=local", "+paths.store_roots.seviri_product_hourly_lst=local-lst"],
)
paths = ExperimentPaths.from_config(cfg.paths)
assert paths.product_root == Path("data")
assert paths.preload_cache_root == Path("cache/local")
assert paths.store_roots == {"seviri_product_hourly_lst": "local-lst"}


@pytest.fixture
def paths(tmp_path):
return ExperimentPaths(
Expand All @@ -34,35 +47,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_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_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_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", "null", "string", "path", "relative"])
Expand Down
41 changes: 39 additions & 2 deletions tests/test_reader_store_roots.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
"""The statistics script and the baselines with the configured stores and store roots."""

from pathlib import Path

import numpy as np
import pytest
from omegaconf import OmegaConf

from deep_lst import stores
from deep_lst.baselines.era5land import Era5LandExtractor
from deep_lst.stores import T1H, CubeReader
from deep_lst.stores import T1D, T1H, CubeReader
from deep_lst.utils import full_store, spatial
from deep_lst.utils.io import ExperimentPaths, load_computed_stats, load_inc_variances
from deep_lst.utils.statistics import read_variable_statistics
from scripts.assets import compute_statistics
from scripts.assets import compute_statistics, run_baselines


class TinyLSTReader(CubeReader):
Expand Down Expand Up @@ -95,3 +98,37 @@ def test_baseline_attributes_come_from_the_variable_table():
assert extractor._metadata_attrs("unlisted") == dict(
variable="unlisted", units="", long_name="unlisted", test_year="2024"
)


def test_baselines_read_the_selected_paths_profile():
config = run_baselines.build_config("gobabeb", "local")
paths = ExperimentPaths.from_config(config["paths"])
assert paths.product_root == Path("data")
assert paths.preload_cache_root == Path("cache/local")
assert config["test_dataset"]["spatial"] == "eval_gobabeb"


def test_full_store_reads_the_selection_stores_and_grids_from_the_same_paths(tmp_path, monkeypatch, hourly_store):
monkeypatch.setitem(stores.READERS, "synthetic_hourly", TinyLSTReader)
sources = {"seviri": {"stores": {"synthetic_hourly": ["LST"]}}}
monkeypatch.setattr(full_store, "default_sources", lambda: sources)
monkeypatch.setattr(spatial, "default_sources", lambda: sources)
paths = ExperimentPaths(
assets_root=tmp_path / "chosen-assets",
product_root=tmp_path / "unused-root",
store_roots={"synthetic_hourly": str(hourly_store.path.parent)},
)
rows = [3, 19]
selection = paths.spatial_indices_path("tiny")
selection.parent.mkdir(parents=True)
np.savez(selection, src_indices=rows)
day = T1D.date_to_index("2016-01-01")

columns, unique_rows, inverse, anchors = full_store.load_store_columns(
"seviri", "tiny", {"data": ["LST"]}, anchor="seviri", day_range=(day, day + 1), num_workers=1, paths=paths
)
expected = hourly_store.values["LST"][:24].reshape(24, -1)[:, rows].T
np.testing.assert_array_equal(columns["data"][:, :, 0].numpy(), expected)
np.testing.assert_array_equal(unique_rows, rows)
np.testing.assert_array_equal(inverse, [0, 1])
np.testing.assert_array_equal(anchors, rows)
Loading
Loading