| """Lightweight reader for T2 material-loading-memory HDF5 shards.""" |
|
|
| from __future__ import annotations |
|
|
| import json |
| from pathlib import Path |
| from typing import Iterator |
|
|
| import h5py |
| import numpy as np |
|
|
|
|
| def load_manifest(dataset_root: str | Path) -> dict[str, object]: |
| root = Path(dataset_root) |
| return json.loads((root / "manifest.json").read_text(encoding="utf-8")) |
|
|
|
|
| def _resolve_shard(root: Path, relative_path: str) -> Path: |
| candidate = root / "shards" / Path(relative_path).name |
| if candidate.exists(): |
| return candidate |
| return root.parents[1] / relative_path |
|
|
|
|
| def _group_to_sample(sample_id: str, group: h5py.Group) -> dict[str, object]: |
| return { |
| "id": sample_id, |
| "case_id": str(group.attrs["case_id"]), |
| "split": str(group.attrs["split"]), |
| "material_model": str(group.attrs["material_model"]), |
| "path_family": str(group.attrs["path_family"]), |
| "parameters": json.loads(str(group.attrs["parameters_json"])), |
| "metrics": json.loads(str(group.attrs["metrics_json"])), |
| "history": {name: np.asarray(group[name]) for name in group.keys()}, |
| } |
|
|
|
|
| def iter_trajectories( |
| dataset_root: str | Path, |
| *, |
| split: str | None = None, |
| material_model: str | None = None, |
| path_family: str | None = None, |
| ) -> Iterator[dict[str, object]]: |
| """Yield copied histories, optionally filtered by trajectory metadata.""" |
|
|
| root = Path(dataset_root) |
| manifest = load_manifest(root) |
| for shard in manifest["shards"]: |
| with h5py.File(_resolve_shard(root, shard["path"]), "r") as h5: |
| for sample_id in sorted(h5.keys()): |
| group = h5[sample_id] |
| if split is not None and str(group.attrs["split"]) != split: |
| continue |
| if ( |
| material_model is not None |
| and str(group.attrs["material_model"]) != material_model |
| ): |
| continue |
| if ( |
| path_family is not None |
| and str(group.attrs["path_family"]) != path_family |
| ): |
| continue |
| yield _group_to_sample(sample_id, group) |
|
|
|
|
| def load_trajectory( |
| dataset_root: str | Path, sample_id: str | int |
| ) -> dict[str, object]: |
| target = f"{int(sample_id):05d}" |
| root = Path(dataset_root) |
| manifest = load_manifest(root) |
| for shard in manifest["shards"]: |
| if shard["first_id"] <= target <= shard["last_id"]: |
| with h5py.File(_resolve_shard(root, shard["path"]), "r") as h5: |
| if target in h5: |
| return _group_to_sample(target, h5[target]) |
| raise KeyError(f"Unknown trajectory id: {target}") |
|
|