File size: 4,718 Bytes
05cb22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#!/usr/bin/env python3
"""Validate the standardized BENO dataset package."""

from __future__ import annotations

import argparse
import hashlib
import json
import sys
from pathlib import Path

import numpy as np


REPO_ROOT = Path(__file__).resolve().parents[1]
DATA_ROOT = REPO_ROOT / "data"
CHECKSUM_PATH = REPO_ROOT / "files_sha256.jsonl"
BOUNDARIES = ("Dirichlet", "Neumann")
PREFIXES = ("N32_0c", "N32_1c", "N32_2c", "N32_3c", "N32_4c", "N32_mix")
KINDS = ("BC", "RHS", "SOL")
EXPECTED_SHAPES = {
    "BC": (1000, 128, 4),
    "RHS": (1000, 1024, 4),
    "SOL": (1000, 1024, 1),
}


def fail(message: str) -> None:
    print(f"[FAIL] {message}")
    raise SystemExit(1)


def ok(message: str) -> None:
    print(f"[OK] {message}")


def warn(message: str) -> None:
    print(f"[WARN] {message}")


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def expected_files() -> list[Path]:
    return [
        DATA_ROOT / boundary / f"{kind}_{prefix}_all.npy"
        for boundary in BOUNDARIES
        for prefix in PREFIXES
        for kind in KINDS
    ]


def validate_structure() -> None:
    if not DATA_ROOT.is_dir():
        fail(f"dataset data root does not exist: {DATA_ROOT}")
    missing = [str(path.relative_to(REPO_ROOT)) for path in expected_files() if not path.is_file()]
    if missing:
        fail("missing required NPY files: " + "; ".join(missing[:10]))
    actual = sorted(path for path in DATA_ROOT.glob("*/*.npy"))
    expected = sorted(expected_files())
    if [p.relative_to(REPO_ROOT) for p in actual] != [p.relative_to(REPO_ROOT) for p in expected]:
        fail(f"unexpected NPY file set: expected {len(expected)}, got {len(actual)}")
    ok("dataset file names and directory layout are valid")


def validate_arrays(sample_values: bool) -> None:
    for path in expected_files():
        kind = path.name.split("_", 1)[0]
        arr = np.load(path, mmap_mode="r")
        if tuple(arr.shape) != EXPECTED_SHAPES[kind]:
            fail(f"{path.relative_to(REPO_ROOT)} shape mismatch: expected {EXPECTED_SHAPES[kind]}, got {tuple(arr.shape)}")
        if arr.dtype != np.float64:
            fail(f"{path.relative_to(REPO_ROOT)} dtype mismatch: expected float64, got {arr.dtype}")
        if sample_values:
            probe = np.asarray(arr[0])
            if kind == "BC":
                required_channels = probe[:, :3]
                if not np.isfinite(required_channels).all():
                    fail(f"{path.relative_to(REPO_ROOT)} contains non-finite values in BC channels 0:3")
                optional_channel = probe[:, 3]
                nonfinite = optional_channel.size - int(np.isfinite(optional_channel).sum())
                if nonfinite:
                    warn(f"{path.relative_to(REPO_ROOT)} BC channel 3 contains {nonfinite} non-finite placeholder values in first sample")
            elif not np.isfinite(probe).all():
                fail(f"{path.relative_to(REPO_ROOT)} contains non-finite values in first sample")
    ok("dataset NPY files are readable and match expected shape/dtype")


def verify_checksums(full_hash: bool) -> None:
    if not CHECKSUM_PATH.exists():
        warn(f"checksum manifest is not present: {CHECKSUM_PATH}")
        return
    records = []
    for line in CHECKSUM_PATH.read_text(encoding="utf-8").splitlines():
        if line.strip():
            records.append(json.loads(line))
    if len(records) != 36:
        fail(f"checksum manifest must contain 36 records, got {len(records)}")
    for record in records:
        path = REPO_ROOT / record["path"]
        if not path.is_file():
            fail(f"checksum entry points to missing file: {path}")
        size = path.stat().st_size
        if size != record["size"]:
            fail(f"size mismatch for {path}: expected {record['size']}, got {size}")
        if full_hash:
            digest = sha256_file(path)
            if digest != record["sha256"]:
                fail(f"sha256 mismatch for {path}")
    mode = "size+sha256" if full_hash else "size"
    ok(f"checksum manifest verified in {mode} mode: {len(records)} files")


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--full-hash", action="store_true")
    parser.add_argument("--skip-value-sample", action="store_true")
    args = parser.parse_args()
    validate_structure()
    validate_arrays(sample_values=not args.skip_value_sample)
    verify_checksums(full_hash=args.full_hash)
    ok("dataset validation completed")
    return 0


if __name__ == "__main__":
    sys.exit(main())