File size: 5,932 Bytes
483ae68 | 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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | #!/usr/bin/env python3
"""Validate the standardized DeepMind Lagrangian Water dataset package."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
EXPECTED_SPLITS = {
"train": 1000,
"valid": 30,
"test": 30,
}
def fail(message: str) -> None:
raise SystemExit(f"[FAIL] {message}")
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--dataset-root", default=".", help="dataset package root")
parser.add_argument(
"--verify-sha256",
action="store_true",
help="recompute and verify SHA256 values from files_sha256.jsonl",
)
parser.add_argument(
"--skip-tfrecord-read",
action="store_true",
help="skip optional TensorFlow first-record readability check",
)
return parser.parse_args()
def load_metadata(data_dir: Path) -> dict:
meta_path = data_dir / "metadata.json"
if not meta_path.is_file():
fail(f"missing metadata file: {meta_path}")
metadata = json.loads(meta_path.read_text(encoding="utf-8"))
if metadata.get("dim") != 2:
fail(f"expected metadata dim=2, got {metadata.get('dim')}")
if metadata.get("sequence_length") != 1000:
fail(f"expected sequence_length=1000, got {metadata.get('sequence_length')}")
for key in ["vel_mean", "vel_std", "acc_mean", "acc_std"]:
value = metadata.get(key)
if not isinstance(value, list) or len(value) != 2:
fail(f"metadata {key} must be a length-2 list")
return metadata
def check_files(dataset_root: Path) -> dict:
data_dir = dataset_root / "data" / "Water"
if not data_dir.is_dir():
fail(f"missing data directory: {data_dir}")
sizes = {}
for split in EXPECTED_SPLITS:
path = data_dir / f"{split}.tfrecord"
if not path.is_file():
fail(f"missing TFRecord split: {path}")
size = path.stat().st_size
if size <= 0:
fail(f"empty TFRecord split: {path}")
sizes[str(path.relative_to(dataset_root))] = size
if not (data_dir / "metadata.json").is_file():
fail("missing data/Water/metadata.json")
sizes["data/Water/metadata.json"] = (data_dir / "metadata.json").stat().st_size
return sizes
def verify_inventory(dataset_root: Path, sizes: dict, verify_sha256: bool) -> None:
inventory_path = dataset_root / "files_sha256.jsonl"
if not inventory_path.is_file():
fail("missing files_sha256.jsonl")
seen = {}
for line in inventory_path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
item = json.loads(line)
rel_path = item["path"]
path = dataset_root / rel_path
if not path.is_file():
fail(f"inventory path missing on disk: {rel_path}")
if path.stat().st_size != item["size"]:
fail(f"size mismatch for {rel_path}")
if sizes.get(rel_path) != item["size"]:
fail(f"required file size mismatch for {rel_path}")
if verify_sha256:
actual = sha256_file(path)
if actual != item["sha256"]:
fail(f"sha256 mismatch for {rel_path}")
seen[rel_path] = item
missing = sorted(set(sizes) - set(seen))
if missing:
fail(f"inventory missing required files: {missing}")
def check_tfrecord_first_record(data_dir: Path, metadata: dict) -> None:
try:
import numpy as np
import tensorflow.compat.v1 as tf
except Exception as exc: # pragma: no cover - depends on runtime env
print(f"[WARN] TensorFlow first-record check skipped: {exc}")
return
feature_description = {"position": tf.io.VarLenFeature(tf.string)}
context_features = {
"key": tf.io.FixedLenFeature([], tf.int64, default_value=0),
"particle_type": tf.io.VarLenFeature(tf.string),
}
expected_steps = metadata["sequence_length"] + 1
dim = metadata["dim"]
for split in EXPECTED_SPLITS:
record_iter = iter(tf.data.TFRecordDataset(str(data_dir / f"{split}.tfrecord")).take(1))
try:
raw = next(record_iter)
except StopIteration:
fail(f"{split}.tfrecord contains no records")
context, features = tf.io.parse_single_sequence_example(
raw,
context_features=context_features,
sequence_features=feature_description,
)
position = np.frombuffer(features["position"].values[0].numpy(), dtype=np.float32)
if position.size % (expected_steps * dim) != 0:
fail(f"{split}.tfrecord first record position shape is incompatible with metadata")
particle_type = np.frombuffer(context["particle_type"].values[0].numpy(), dtype=np.int64)
num_particles = position.size // (expected_steps * dim)
if particle_type.shape[0] != num_particles:
fail(f"{split}.tfrecord particle_type length does not match position particles")
print(
f"[OK] {split}.tfrecord first record: "
f"position_shape=({expected_steps}, {num_particles}, {dim}), "
"position_dtype=float32, particle_type_dtype=int64"
)
def main() -> None:
args = parse_args()
dataset_root = Path(args.dataset_root).resolve()
data_dir = dataset_root / "data" / "Water"
sizes = check_files(dataset_root)
metadata = load_metadata(data_dir)
verify_inventory(dataset_root, sizes, args.verify_sha256)
if not args.skip_tfrecord_read:
check_tfrecord_first_record(data_dir, metadata)
print("[OK] Lagrangian Water dataset validation passed")
if __name__ == "__main__":
main()
|