File size: 7,092 Bytes
f0652e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#!/usr/bin/env python3
"""Validate the standardized DeepMind CylinderFlow dataset package."""

from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path


EXPECTED_SPLITS = ["train", "valid", "test"]
EXPECTED_REQUIRED = {
    "data/cylinder_flow/meta.json",
    "data/cylinder_flow/train.tfrecord",
    "data/cylinder_flow/valid.tfrecord",
    "data/cylinder_flow/test.tfrecord",
    "data/cylinder_flow/stats/edge_stats.json",
    "data/cylinder_flow/stats/node_stats.json",
}


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 check_files(dataset_root: Path) -> dict:
    sizes = {}
    for rel_path in sorted(EXPECTED_REQUIRED):
        path = dataset_root / rel_path
        if not path.is_file():
            fail(f"missing required file: {rel_path}")
        if path.stat().st_size <= 0:
            fail(f"empty required file: {rel_path}")
        sizes[rel_path] = path.stat().st_size
    return sizes


def check_metadata(data_dir: Path) -> dict:
    meta = json.loads((data_dir / "meta.json").read_text(encoding="utf-8"))
    if meta.get("simulator") != "comsol":
        fail("meta.json simulator must be comsol")
    if meta.get("trajectory_length") != 600:
        fail("meta.json trajectory_length must be 600")
    expected_fields = ["cells", "mesh_pos", "node_type", "velocity", "pressure"]
    if meta.get("field_names") != expected_fields:
        fail("meta.json field_names mismatch")
    expected_shapes = {
        "cells": [1, -1, 3],
        "mesh_pos": [1, -1, 2],
        "node_type": [1, -1, 1],
        "velocity": [600, -1, 2],
        "pressure": [600, -1, 1],
    }
    expected_dtypes = {
        "cells": "int32",
        "mesh_pos": "float32",
        "node_type": "int32",
        "velocity": "float32",
        "pressure": "float32",
    }
    for key in expected_fields:
        feature = meta.get("features", {}).get(key)
        if not feature:
            fail(f"meta.json missing feature {key}")
        if feature.get("shape") != expected_shapes[key]:
            fail(f"meta.json feature {key} shape mismatch")
        if feature.get("dtype") != expected_dtypes[key]:
            fail(f"meta.json feature {key} dtype mismatch")
    return meta


def check_stats(stats_dir: Path) -> None:
    edge = json.loads((stats_dir / "edge_stats.json").read_text(encoding="utf-8"))
    node = json.loads((stats_dir / "node_stats.json").read_text(encoding="utf-8"))
    for key in ["edge_mean", "edge_std"]:
        if not isinstance(edge.get(key), list) or len(edge[key]) != 3:
            fail(f"edge_stats.json {key} must be length 3")
    for key in ["velocity_mean", "velocity_std", "velocity_diff_mean", "velocity_diff_std"]:
        if not isinstance(node.get(key), list) or len(node[key]) != 2:
            fail(f"node_stats.json {key} must be length 2")
    for key in ["pressure_mean", "pressure_std"]:
        if not isinstance(node.get(key), list) or len(node[key]) != 1:
            fail(f"node_stats.json {key} must be length 1")


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 rel_path in sizes and sizes[rel_path] != item["size"]:
            fail(f"required file size mismatch for {rel_path}")
        if verify_sha256 and sha256_file(path) != item["sha256"]:
            fail(f"sha256 mismatch for {rel_path}")
        seen[rel_path] = item
    missing = sorted(EXPECTED_REQUIRED - set(seen))
    if missing:
        fail(f"inventory missing required files: {missing}")


def check_tfrecord_first_record(data_dir: Path, meta: dict) -> None:
    try:
        import numpy as np
        import tensorflow.compat.v1 as tf
    except Exception as exc:  # pragma: no cover - optional runtime dependency
        print(f"[WARN] TensorFlow first-record check skipped: {exc}")
        return

    feature_dict = {k: tf.io.VarLenFeature(tf.string) for k in meta["field_names"]}
    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")
        features = tf.io.parse_single_example(raw, feature_dict)
        velocity = np.frombuffer(features["velocity"].values[0].numpy(), dtype=np.float32)
        pressure = np.frombuffer(features["pressure"].values[0].numpy(), dtype=np.float32)
        mesh_pos = np.frombuffer(features["mesh_pos"].values[0].numpy(), dtype=np.float32)
        cells = np.frombuffer(features["cells"].values[0].numpy(), dtype=np.int32)
        if velocity.size % (meta["trajectory_length"] * 2) != 0:
            fail(f"{split}.tfrecord velocity shape incompatible with metadata")
        nodes = velocity.size // (meta["trajectory_length"] * 2)
        if pressure.size != meta["trajectory_length"] * nodes:
            fail(f"{split}.tfrecord pressure node count mismatch")
        if mesh_pos.size != nodes * 2:
            fail(f"{split}.tfrecord mesh_pos node count mismatch")
        if cells.size % 3 != 0:
            fail(f"{split}.tfrecord cells are not triangular")
        print(f"[OK] {split}.tfrecord first record: nodes={nodes}, cells={cells.size // 3}")


def main() -> None:
    args = parse_args()
    dataset_root = Path(args.dataset_root).resolve()
    data_dir = dataset_root / "data" / "cylinder_flow"
    sizes = check_files(dataset_root)
    meta = check_metadata(data_dir)
    check_stats(data_dir / "stats")
    verify_inventory(dataset_root, sizes, args.verify_sha256)
    if not args.skip_tfrecord_read:
        check_tfrecord_first_record(data_dir, meta)
    print("[OK] CylinderFlow dataset validation passed")


if __name__ == "__main__":
    main()