"""Lightweight API for the 64x64 PDE benchmark release. The dataset on disk is organized as: Data//{train,val,test}/.npy Each npy array has shape: (num_trajectories, 100, channels, 64, 64) This API constructs the benchmark's mixed train/validation distributions and its 5x5 test grid. It returns NumPy arrays and can be wrapped by PyTorch DataLoader directly because the dataset implements __len__ and __getitem__. """ from __future__ import annotations import argparse import json from dataclasses import dataclass from pathlib import Path from typing import Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np IC_TEST: Tuple[str, ...] = ( "IC-OOD-simple", "IC-simple", "IC-medium", "IC-complex", "IC-OOD-complex", ) DYNAMIC_TEST: Tuple[str, ...] = ( "Dynamic-OOD-small", "Dynamic-small", "Dynamic-medium", "Dynamic-large", "Dynamic-OOD-large", ) DYNAMIC_STRIDES: Mapping[str, int] = { "Dynamic-OOD-small": 1, "Dynamic-small": 2, "Dynamic-medium": 3, "Dynamic-large": 4, "Dynamic-OOD-large": 5, } COMPLEXITY_SOURCES: Mapping[str, Tuple[str, str]] = { "simple": ("Dynamic-small", "IC-simple"), "medium": ("Dynamic-medium", "IC-medium"), "complex": ("Dynamic-large", "IC-complex"), } TRAIN_RECIPES: Mapping[str, Mapping[str, int]] = { "Mix-simple": {"simple": 200, "medium": 50, "complex": 50}, "Mix-balance": {"simple": 100, "medium": 100, "complex": 100}, "Mix-complex": {"simple": 50, "medium": 50, "complex": 200}, } VAL_RECIPES: Mapping[str, Mapping[str, int]] = { "Mix-simple": {"simple": 50, "medium": 15, "complex": 15}, "Mix-balance": {"simple": 25, "medium": 25, "complex": 25}, "Mix-complex": {"simple": 15, "medium": 15, "complex": 50}, } @dataclass(frozen=True) class Entry: path: Path sample_index: int ic_name: str dynamic_name: str def available_pdes(data_root: str | Path = "Data") -> List[str]: root = Path(data_root) return sorted(p.name for p in root.iterdir() if (p / "metadata.json").exists()) def load_metadata(data_root: str | Path, pde: str) -> dict: path = Path(data_root) / pde / "metadata.json" with path.open("r", encoding="utf-8") as f: return json.load(f) def dynamic_indices(dynamic: str, n_frames: int = 20, total_frames: int = 100) -> np.ndarray: """Return frame indices used to build a 20-frame dynamic sequence.""" if dynamic not in DYNAMIC_STRIDES: raise ValueError(f"Unknown dynamic={dynamic!r}; choose from {tuple(DYNAMIC_STRIDES)}") idx = np.arange(n_frames, dtype=np.int64) * int(DYNAMIC_STRIDES[dynamic]) if int(idx[-1]) >= total_frames: raise ValueError(f"{dynamic} needs frame {idx[-1]}, but trajectory has only {total_frames} frames") return idx def window_starts( input_frames: int = 5, target_frames: int = 1, context_frames: Optional[int] = 15, window_stride: int = 1, ) -> List[int]: """Start offsets for supervised windows inside the first context_frames. The benchmark training protocol uses context_frames=15 by default, so a model never trains on the final 5 frames of the 20-frame dynamic sequence. With input_frames=5 and target_frames=1 this yields 10 one-step windows. """ if context_frames is None: return [0] if window_stride <= 0: raise ValueError("window_stride must be positive") if context_frames < input_frames + target_frames: raise ValueError("context_frames must be >= input_frames + target_frames") max_start = context_frames - input_frames - target_frames return list(range(0, max_start + 1, window_stride)) def _entries_from_recipe(data_root: Path, pde: str, split: str, recipe: Mapping[str, int]) -> List[Entry]: entries: List[Entry] = [] for source, count in recipe.items(): dynamic_name, ic_name = COMPLEXITY_SOURCES[source] path = data_root / pde / split / f"{ic_name}.npy" arr = np.load(path, mmap_mode="r") if count > arr.shape[0]: raise ValueError(f"{path} has {arr.shape[0]} trajectories, requested {count}") entries.extend(Entry(path, i, ic_name, dynamic_name) for i in range(count)) return entries def _entries_fixed(data_root: Path, pde: str, split: str, dynamic: str, ic: str, count: Optional[int]) -> List[Entry]: path = data_root / pde / split / f"{ic}.npy" arr = np.load(path, mmap_mode="r") n = arr.shape[0] if count is None else min(count, arr.shape[0]) return [Entry(path, i, ic, dynamic) for i in range(n)] class PDEWindowDataset: """Windowed dataset returning x/y pairs or full 20-frame sequences. Returned dictionary keys: - x: input window, shape (input_frames, C, H, W) - y: target window, shape (target_frames, C, H, W) - sequence: optional full dynamic sequence, shape (20, C, H, W) - ic_name, dynamic_name, sample_index, window_start """ def __init__( self, entries: Sequence[Entry], input_frames: int = 5, target_frames: int = 1, context_frames: Optional[int] = 15, window_stride: int = 1, n_dynamic_frames: int = 20, return_sequence: bool = False, ) -> None: self.entries = list(entries) self.input_frames = int(input_frames) self.target_frames = int(target_frames) self.context_frames = context_frames self.window_stride = int(window_stride) self.n_dynamic_frames = int(n_dynamic_frames) self.return_sequence = bool(return_sequence) self.starts = window_starts(input_frames, target_frames, context_frames, window_stride) self._arrays: Dict[Path, np.memmap] = {} def __len__(self) -> int: return len(self.entries) * len(self.starts) def _array(self, path: Path) -> np.memmap: arr = self._arrays.get(path) if arr is None: arr = np.load(path, mmap_mode="r") self._arrays[path] = arr return arr def __getitem__(self, index: int) -> dict: entry_i = index // len(self.starts) start = self.starts[index % len(self.starts)] entry = self.entries[entry_i] arr = self._array(entry.path) seq_idx = dynamic_indices(entry.dynamic_name, self.n_dynamic_frames, arr.shape[1]) sequence = np.asarray(arr[entry.sample_index, seq_idx], dtype=np.float32) x = sequence[start : start + self.input_frames] y0 = start + self.input_frames y = sequence[y0 : y0 + self.target_frames] item = { "x": x, "y": y, "ic_name": entry.ic_name, "dynamic_name": entry.dynamic_name, "sample_index": entry.sample_index, "window_start": start, } if self.return_sequence: item["sequence"] = sequence return item def make_train_val_datasets( data_root: str | Path, pde: str, mix: str = "Mix-balance", input_frames: int = 5, target_frames: int = 1, train_context_frames: int = 15, window_stride: int = 1, ) -> Tuple[PDEWindowDataset, PDEWindowDataset]: """Build train/val datasets for Mix-simple, Mix-balance, or Mix-complex.""" if mix not in TRAIN_RECIPES: raise ValueError(f"Unknown mix={mix!r}; choose from {tuple(TRAIN_RECIPES)}") root = Path(data_root) train_entries = _entries_from_recipe(root, pde, "train", TRAIN_RECIPES[mix]) val_entries = _entries_from_recipe(root, pde, "val", VAL_RECIPES[mix]) kwargs = dict( input_frames=input_frames, target_frames=target_frames, context_frames=train_context_frames, window_stride=window_stride, ) return PDEWindowDataset(train_entries, **kwargs), PDEWindowDataset(val_entries, **kwargs) def make_test_dataset( data_root: str | Path, pde: str, dynamic: str, ic: str, input_frames: int = 5, target_frames: int = 15, count: Optional[int] = None, return_sequence: bool = True, ) -> PDEWindowDataset: """Build one test dataset from the 5x5 dynamic x IC grid. By default this returns x=first 5 frames and y=remaining 15 frames from a 20-frame dynamic sequence, i.e. the rollout-OOD evaluation target. """ if dynamic not in DYNAMIC_TEST: raise ValueError(f"Unknown dynamic={dynamic!r}; choose from {DYNAMIC_TEST}") if ic not in IC_TEST: raise ValueError(f"Unknown ic={ic!r}; choose from {IC_TEST}") entries = _entries_fixed(Path(data_root), pde, "test", dynamic, ic, count) return PDEWindowDataset( entries, input_frames=input_frames, target_frames=target_frames, context_frames=input_frames + target_frames, window_stride=1, return_sequence=return_sequence, ) def iter_test_grid( data_root: str | Path, pde: str, input_frames: int = 5, target_frames: int = 15, count: Optional[int] = None, ) -> Iterator[Tuple[str, str, PDEWindowDataset]]: """Yield all 25 test datasets as (dynamic, ic, dataset).""" for dynamic in DYNAMIC_TEST: for ic in IC_TEST: yield dynamic, ic, make_test_dataset(data_root, pde, dynamic, ic, input_frames, target_frames, count) def summarize(data_root: str | Path = "Data") -> None: root = Path(data_root) print(f"data_root: {root.resolve()}") print(f"PDEs: {', '.join(available_pdes(root))}") print("train recipes:") for name, recipe in TRAIN_RECIPES.items(): print(f" {name}: {dict(recipe)}") print("validation recipes:") for name, recipe in VAL_RECIPES.items(): print(f" {name}: {dict(recipe)}") print("test grid:") print(f" dynamics: {DYNAMIC_TEST}") print(f" ICs: {IC_TEST}") def _main() -> None: parser = argparse.ArgumentParser(description="Inspect and construct PDE benchmark splits.") parser.add_argument("--data-root", default="Data") parser.add_argument("--pde", default=None) parser.add_argument("--mix", default="Mix-balance", choices=tuple(TRAIN_RECIPES)) parser.add_argument("--count-test", type=int, default=2, help="Number of trajectories per test cell for smoke check") args = parser.parse_args() summarize(args.data_root) if args.pde is None: return train_ds, val_ds = make_train_val_datasets(args.data_root, args.pde, args.mix) print(f"\n{args.pde} / {args.mix}: train windows={len(train_ds)}, val windows={len(val_ds)}") item = train_ds[0] print(f"first train item: x={item['x'].shape}, y={item['y'].shape}, ic={item['ic_name']}, dynamic={item['dynamic_name']}") print("test grid smoke check:") for dynamic, ic, ds in iter_test_grid(args.data_root, args.pde, count=args.count_test): item = ds[0] print(f" {dynamic:17s} {ic:15s}: n={len(ds):3d}, x={item['x'].shape}, y={item['y'].shape}") if __name__ == "__main__": _main()