"""PyTorch Dataset for the LANSCE surrogate training data. Reads `index.parquet` to enumerate runs, then lazily opens each run's `fields.h5` on `__getitem__`. Returns a dict so the caller can ignore modalities they don't want for a given training phase: Phase 1 (scalar regression): only use `params` + `metrics` Phase 2 (+ 1D histograms): also read the reducedfiles via `load_reduced(run_dir)` Phase 3 (full field surrogate): use `early` + `full` Usage: from torch.utils.data import DataLoader from loader import LansceFieldsDataset ds = LansceFieldsDataset("surrogate_model_dataset", phase="scalar") for sample in DataLoader(ds, batch_size=8, num_workers=4): ... `phase` gates which tensors are returned to keep I/O minimal: "scalar" -> {"params", "metrics"} only "histogram" -> adds {"hist_uz", "hist_x", "hist_y"} "field" -> adds {"early", "full"} read from fields.h5 "all" -> everything HDF5 opens are per-sample (one file per run), so num_workers>0 is safe. """ from __future__ import annotations from pathlib import Path from typing import Literal import h5py import numpy as np import pandas as pd import torch from torch.utils.data import Dataset PARAM_COLUMNS = [ "beam_energy", "source_density", "puller_offset", "T_eV", "r_exit", "r_entrance", "r_puller", ] METRIC_COLUMNS = [ "envelope_x_m", "envelope_y_m", "emit_x_norm_mmmrad", "emit_y_norm_mmmrad", "energy_mean_kev", "energy_std_kev", "theta_x_rms_mrad", "theta_y_rms_mrad", "transmission", ] HIST_BASENAMES = { "hist_uz": "reducedfilesbeam_uz_hist.txt", "hist_x": "reducedfilesbeam_x_hist.txt", "hist_y": "reducedfilesbeam_y_hist.txt", } Phase = Literal["scalar", "histogram", "field", "all"] def _load_hist_tensor(path: Path) -> torch.Tensor: """Parse a WarpX ParticleHistogram reducedfile into a (T, bins) tensor.""" if not path.exists() or path.stat().st_size == 0: return torch.empty(0, 0) arr = np.loadtxt(path) if arr.ndim == 1: arr = arr[None, :] # Columns 0 and 1 are step and time; the rest are bin counts. return torch.from_numpy(arr[:, 2:].astype(np.float32)) class LansceFieldsDataset(Dataset): def __init__( self, root: str | Path, phase: Phase = "scalar", index_path: str | Path | None = None, drop_failed: bool = True, ): self.root = Path(root) self.phase = phase # Prefer index.parquet (fast column projection); fall back to # manifest.csv if pyarrow/fastparquet wasn't installed when the # sweep ran. if index_path is not None: index_path = Path(index_path) df = (pd.read_parquet(index_path) if index_path.suffix == ".parquet" else pd.read_csv(index_path)) else: pq = self.root / "index.parquet" csv = self.root / "manifest.csv" if pq.exists(): df = pd.read_parquet(pq) elif csv.exists(): df = pd.read_csv(csv) df["run_dir"] = df["run_id"].map(lambda i: f"runs/run_{int(i):04d}") df["fields_h5"] = df["run_dir"] + "/fields.h5" else: raise FileNotFoundError( f"neither index.parquet nor manifest.csv found under {self.root}" ) if drop_failed: df = df[df["status"].fillna("") == "ok"].reset_index(drop=True) self.df = df def __len__(self) -> int: return len(self.df) def __getitem__(self, idx: int) -> dict[str, torch.Tensor]: row = self.df.iloc[idx] run_dir = self.root / row["run_dir"] sample: dict[str, torch.Tensor] = { "run_id": torch.tensor(int(row["run_id"]), dtype=torch.int64), "params": torch.tensor( [float(row[c]) for c in PARAM_COLUMNS], dtype=torch.float32 ), "metrics": torch.tensor( [float(row[c]) for c in METRIC_COLUMNS], dtype=torch.float32 ), } if self.phase in ("histogram", "all"): for key, fname in HIST_BASENAMES.items(): sample[key] = _load_hist_tensor(run_dir / "diags" / fname) if self.phase in ("field", "all"): fields_h5 = run_dir / "fields.h5" if not fields_h5.exists(): raise FileNotFoundError(f"{fields_h5} not packed yet") with h5py.File(fields_h5, "r") as h5: if "early" in h5: sample["early"] = torch.from_numpy(h5["early/fields"][()]) sample["early_times"] = torch.from_numpy(h5["early/times"][()]) if "full" in h5: sample["full"] = torch.from_numpy(h5["full/fields"][()]) sample["full_times"] = torch.from_numpy(h5["full/times"][()]) return sample def load_reduced(run_dir: Path) -> dict[str, np.ndarray]: """Read scalar reduced diagnostics (beam_number, beam_jz, eb_charge). Returns time-series as raw numpy arrays with shape (T, n_cols). """ d = Path(run_dir) / "diags" out = {} for basename in ("beam_number", "beam_jz", "eb_charge"): p = d / f"reducedfiles{basename}.txt" if p.exists() and p.stat().st_size > 0: out[basename] = np.loadtxt(p) return out