from __future__ import annotations import argparse import sys from pathlib import Path from typing import Any import h5py import numpy as np def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( description=( "Check every HDF5 file in the script directory and verify that all " "numeric datasets and numeric attributes are real-valued and finite." ) ) parser.add_argument( "--pattern", default="*.h5", help="Glob pattern used inside the script directory. Default: %(default)s.", ) return parser def iter_datasets(group: h5py.Group, prefix: str = ""): for name, item in group.items(): path = f"{prefix}/{name}" if prefix else name if isinstance(item, h5py.Dataset): yield path, item elif isinstance(item, h5py.Group): yield from iter_datasets(item, path) def validate_numeric_array(values: np.ndarray[Any, Any], *, label: str) -> None: if np.iscomplexobj(values): raise ValueError(f"{label} contains complex values.") if np.issubdtype(values.dtype, np.number) and not np.isfinite(values).all(): raise ValueError(f"{label} contains non-finite values.") def validate_attr_value(value: Any, *, label: str) -> None: array = np.asarray(value) if array.dtype.kind not in {"b", "i", "u", "f", "c"}: return validate_numeric_array(array, label=label) def validate_h5_file(h5_path: Path) -> None: print(f"Checking {h5_path}", flush=True) with h5py.File(h5_path, "r") as handle: for attr_name, attr_value in handle.attrs.items(): validate_attr_value(attr_value, label=f"{h5_path} attr {attr_name!r}") for dataset_path, dataset in iter_datasets(handle): values = np.asarray(dataset) validate_numeric_array(values, label=f"{h5_path}:{dataset_path}") for attr_name, attr_value in dataset.attrs.items(): validate_attr_value( attr_value, label=f"{h5_path}:{dataset_path} attr {attr_name!r}", ) def main() -> int: args = build_parser().parse_args() script_dir = Path(__file__).resolve().parent h5_paths = sorted(path for path in script_dir.glob(args.pattern) if path.is_file()) if not h5_paths: print( f"No HDF5 files found in {script_dir} matching {args.pattern!r}.", file=sys.stderr, ) return 1 for h5_path in h5_paths: validate_h5_file(h5_path) print(f"Validated {len(h5_paths)} file(s) in {script_dir}.", flush=True) return 0 if __name__ == "__main__": raise SystemExit(main())