| |
| from __future__ import annotations |
|
|
| import argparse |
| import hashlib |
| import json |
| import math |
| import sys |
| from pathlib import Path |
| from typing import Any |
|
|
| import numpy as np |
|
|
|
|
| DATASET_ROOT = Path(__file__).resolve().parents[1] |
| DEFAULT_DATA_FILE = DATASET_ROOT / "kf_2d_re1000_256_120seed.npy" |
| EXPECTED_SHAPE = (120, 320, 256, 256) |
| EXPECTED_DTYPE = np.dtype("float32") |
| EXPECTED_SHA256 = "8eff8260ad2fbcd26c17461b2e2d1f1681e05ef7dc70ef9779142269ed814ca5" |
| SAMPLE_INDICES = ((0, 0), (0, 319), (60, 160), (119, 0), (119, 319)) |
|
|
|
|
| def human_size(size: int) -> str: |
| value = float(size) |
| for unit in ("B", "KiB", "MiB", "GiB", "TiB"): |
| if value < 1024.0 or unit == "TiB": |
| return f"{value:.2f} {unit}" |
| value /= 1024.0 |
| raise AssertionError("unreachable") |
|
|
|
|
| def file_sha256(path: Path, chunk_size: int) -> str: |
| digest = hashlib.sha256() |
| with path.open("rb") as stream: |
| while chunk := stream.read(chunk_size): |
| digest.update(chunk) |
| return digest.hexdigest() |
|
|
|
|
| def frame_statistics(frame: np.ndarray) -> dict[str, Any]: |
| return { |
| "shape": list(frame.shape), |
| "finite": bool(np.isfinite(frame).all()), |
| "min": float(frame.min()), |
| "max": float(frame.max()), |
| "mean": float(frame.mean(dtype=np.float64)), |
| "std": float(frame.std(dtype=np.float64)), |
| } |
|
|
|
|
| def full_scan(array: np.ndarray) -> dict[str, Any]: |
| count = 0 |
| total = 0.0 |
| total_square = 0.0 |
| global_min = math.inf |
| global_max = -math.inf |
|
|
| for trajectory in range(array.shape[0]): |
| block = np.asarray(array[trajectory]) |
| if not np.isfinite(block).all(): |
| bad_count = int(block.size - np.count_nonzero(np.isfinite(block))) |
| raise ValueError( |
| f"trajectory {trajectory} contains {bad_count} NaN or Inf values" |
| ) |
| global_min = min(global_min, float(block.min())) |
| global_max = max(global_max, float(block.max())) |
| total += float(block.sum(dtype=np.float64)) |
| total_square += float(np.square(block).sum(dtype=np.float64)) |
| count += block.size |
| if (trajectory + 1) % 10 == 0 or trajectory + 1 == array.shape[0]: |
| print(f" full scan: {trajectory + 1}/{array.shape[0]} trajectories") |
|
|
| mean = total / count |
| variance = max(total_square / count - mean * mean, 0.0) |
| return { |
| "finite": True, |
| "count": count, |
| "min": global_min, |
| "max": global_max, |
| "mean": mean, |
| "std": math.sqrt(variance), |
| } |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser( |
| description="Validate the published 2D Kolmogorov Flow NumPy dataset." |
| ) |
| parser.add_argument( |
| "--data", |
| type=Path, |
| default=DEFAULT_DATA_FILE, |
| help="Path to kf_2d_re1000_256_120seed.npy", |
| ) |
| parser.add_argument( |
| "--full-scan", |
| action="store_true", |
| help="Scan all 9.38 GiB for NaN/Inf and compute global statistics", |
| ) |
| parser.add_argument( |
| "--sha256", |
| action="store_true", |
| help="Calculate and compare the full-file SHA256 checksum", |
| ) |
| parser.add_argument( |
| "--expected-sha256", |
| default=EXPECTED_SHA256, |
| help="Expected checksum used with --sha256", |
| ) |
| parser.add_argument( |
| "--hash-chunk-mib", |
| type=int, |
| default=32, |
| help="SHA256 read chunk size in MiB", |
| ) |
| parser.add_argument( |
| "--report-json", |
| type=Path, |
| help="Optional path for a machine-readable validation report", |
| ) |
| return parser.parse_args() |
|
|
|
|
| def main() -> int: |
| args = parse_args() |
| data_path = args.data.expanduser().resolve() |
| errors: list[str] = [] |
| report: dict[str, Any] = { |
| "dataset": "Kolmogorov_flow_2d", |
| "data_file": str(data_path), |
| "expected_shape": list(EXPECTED_SHAPE), |
| "expected_dtype": str(EXPECTED_DTYPE), |
| } |
|
|
| if not data_path.is_file(): |
| print(f"ERROR: data file not found: {data_path}", file=sys.stderr) |
| return 1 |
| if args.hash_chunk_mib < 1: |
| print("ERROR: --hash-chunk-mib must be positive", file=sys.stderr) |
| return 1 |
|
|
| print(f"Data file: {data_path}") |
| print(f"File size: {human_size(data_path.stat().st_size)}") |
| try: |
| array = np.load(data_path, mmap_mode="r", allow_pickle=False) |
| except Exception as error: |
| print(f"ERROR: failed to load NumPy header: {error}", file=sys.stderr) |
| return 1 |
|
|
| report.update( |
| { |
| "file_size_bytes": data_path.stat().st_size, |
| "array_nbytes": int(array.nbytes), |
| "shape": list(array.shape), |
| "dtype": str(array.dtype), |
| "ndim": array.ndim, |
| } |
| ) |
| print(f"Shape: {array.shape}") |
| print(f"Dtype: {array.dtype}") |
| print(f"Array payload: {human_size(array.nbytes)}") |
|
|
| if tuple(array.shape) != EXPECTED_SHAPE: |
| errors.append(f"shape is {array.shape}, expected {EXPECTED_SHAPE}") |
| if array.dtype != EXPECTED_DTYPE: |
| errors.append(f"dtype is {array.dtype}, expected {EXPECTED_DTYPE}") |
| if array.ndim != 4: |
| errors.append(f"ndim is {array.ndim}, expected 4") |
|
|
| samples: dict[str, Any] = {} |
| if array.ndim == 4: |
| for trajectory, time_step in SAMPLE_INDICES: |
| if trajectory >= array.shape[0] or time_step >= array.shape[1]: |
| continue |
| key = f"trajectory_{trajectory}_time_{time_step}" |
| stats = frame_statistics(np.asarray(array[trajectory, time_step])) |
| samples[key] = stats |
| print( |
| f"Sample ({trajectory:3d}, {time_step:3d}): " |
| f"finite={stats['finite']} min={stats['min']:.6g} " |
| f"max={stats['max']:.6g} mean={stats['mean']:.6g} " |
| f"std={stats['std']:.6g}" |
| ) |
| if not stats["finite"]: |
| errors.append(f"sample ({trajectory}, {time_step}) contains NaN or Inf") |
| report["samples"] = samples |
|
|
| if args.full_scan and not errors: |
| print("Running full finite-value and statistics scan...") |
| try: |
| report["full_scan"] = full_scan(array) |
| except ValueError as error: |
| errors.append(str(error)) |
|
|
| if args.sha256: |
| print("Calculating SHA256...") |
| checksum = file_sha256(data_path, args.hash_chunk_mib * 1024 * 1024) |
| expected = args.expected_sha256.strip().lower() |
| report["sha256"] = checksum |
| report["expected_sha256"] = expected |
| print(f"SHA256: {checksum}") |
| if expected and checksum != expected: |
| errors.append(f"SHA256 is {checksum}, expected {expected}") |
|
|
| report["errors"] = errors |
| report["valid"] = not errors |
| if args.report_json: |
| report_path = args.report_json.expanduser().resolve() |
| report_path.parent.mkdir(parents=True, exist_ok=True) |
| report_path.write_text( |
| json.dumps(report, indent=2, ensure_ascii=False) + "\n", |
| encoding="utf-8", |
| ) |
| print(f"JSON report: {report_path}") |
|
|
| if errors: |
| for error in errors: |
| print(f"ERROR: {error}", file=sys.stderr) |
| print(f"Validation failed with {len(errors)} error(s).", file=sys.stderr) |
| return 1 |
|
|
| print("Validation passed.") |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|