File size: 3,404 Bytes
9e2cba1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate the standardized ERA5 HDF5 dataset package."""

from __future__ import annotations

import argparse
from pathlib import Path

import h5py


def read_variables(fields) -> list[str]:
    return [
        v.decode() if isinstance(v, bytes) else str(v)
        for v in fields.attrs.get("variables", [])
    ]


def check_file(path: Path, expected_variables: list[str] | None) -> list[str]:
    with h5py.File(path, "r") as f:
        for name in ("fields", "global_means", "global_stds"):
            if name not in f:
                raise RuntimeError(f"{path}: missing dataset {name}")
        fields = f["fields"]
        if fields.dtype.name != "float32":
            raise RuntimeError(f"{path}: fields dtype is {fields.dtype}, expected float32")
        if len(fields.shape) != 4:
            raise RuntimeError(f"{path}: fields shape is {fields.shape}, expected [T, C, H, W]")
        if fields.shape[1:] != (243, 721, 1440):
            raise RuntimeError(f"{path}: fields shape {fields.shape}, expected [T, 243, 721, 1440]")
        if f["global_means"].shape != (1, 243, 1, 1):
            raise RuntimeError(f"{path}: global_means shape is {f['global_means'].shape}")
        if f["global_stds"].shape != (1, 243, 1, 1):
            raise RuntimeError(f"{path}: global_stds shape is {f['global_stds'].shape}")
        variables = read_variables(fields)
        if len(variables) != 243:
            raise RuntimeError(f"{path}: variables length is {len(variables)}, expected 243")
        if expected_variables is not None and variables != expected_variables:
            raise RuntimeError(f"{path}: variables attr differs from first checked file")
        if int(fields.attrs.get("time_step", -1)) != 6:
            raise RuntimeError(f"{path}: time_step is {fields.attrs.get('time_step')}, expected 6")
        _ = fields[0, 0, 0, 0]
        _ = f["global_means"][0, 0, 0, 0]
        _ = f["global_stds"][0, 0, 0, 0]
        return variables


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--data-dir", default="data", help="directory containing yearly *.h5 files")
    parser.add_argument("--expected-start-year", type=int, default=1979)
    parser.add_argument("--expected-end-year", type=int, default=2025)
    parser.add_argument("--check-all", action="store_true", help="inspect every yearly file")
    args = parser.parse_args()

    data_dir = Path(args.data_dir).resolve()
    files = sorted(data_dir.glob("*.h5"))
    if not files:
        raise FileNotFoundError(f"no HDF5 files found under {data_dir}")

    expected_names = [f"{year}.h5" for year in range(args.expected_start_year, args.expected_end_year + 1)]
    actual_names = [p.name for p in files]
    missing = [name for name in expected_names if name not in actual_names]
    if missing:
        raise FileNotFoundError(f"missing expected yearly files: {missing[:10]}")

    to_check = files if args.check_all else [data_dir / expected_names[0], data_dir / expected_names[-1]]
    variables = None
    for path in to_check:
        variables = check_file(path, variables)

    print("ERA5 dataset validation passed")
    print(f"data_dir: {data_dir}")
    print(f"files: {len(files)}")
    print(f"checked_files: {len(to_check)}")
    print(f"variables: {len(variables or [])}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())