File size: 2,726 Bytes
e4fd72a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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())