File size: 11,213 Bytes
1cd8661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19e4922
 
1cd8661
 
 
 
 
 
 
 
 
c0a6da9
 
1cd8661
 
 
 
 
 
 
 
 
 
 
 
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
#!/usr/bin/env python3
"""Validate the complete automotive-impact release package."""

from __future__ import annotations

import argparse
import csv
import hashlib
import json
import sys
import time
import zipfile
from collections import Counter
from pathlib import Path

import numpy as np
import torch

from load_case import (
    canonical_case_id,
    load_case,
    load_case_bytes,
    load_mesh,
    load_split,
    shard_name,
)


SPECS = {
    "floorfrontdriver": {"nodes": 7408, "edges": 29572, "elements": 7374},
    "floorfrontR": {"nodes": 12011, "edges": 48138, "elements": 12055},
    "trunkfloor": {"nodes": 14440, "edges": 58074, "elements": 14589},
}


def sha256_bytes(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()


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


def fail(errors: list[str], message: str) -> None:
    errors.append(message)
    print(f"ERROR: {message}", file=sys.stderr)


def validate_split(root: Path, errors: list[str]) -> dict:
    split = load_split(root)
    expected_sizes = {"train": 400, "val": 50, "test": 50}
    for name, expected in expected_sizes.items():
        values = split.get(name)
        if not isinstance(values, list) or len(values) != expected:
            fail(errors, f"split {name!r}: expected {expected} entries")
            continue
        canonical = [canonical_case_id(value) for value in values]
        if canonical != values:
            fail(errors, f"split {name!r} contains non-canonical case IDs")
        if len(set(values)) != len(values):
            fail(errors, f"split {name!r} contains duplicates")
    union = set().union(*(set(split.get(key, [])) for key in expected_sizes))
    if union != {f"case{index:03d}" for index in range(1, 501)}:
        fail(errors, "split union is not exactly case001..case500")
    names = list(expected_sizes)
    for left_index, left in enumerate(names):
        for right in names[left_index + 1 :]:
            if set(split.get(left, [])) & set(split.get(right, [])):
                fail(errors, f"split overlap: {left} and {right}")
    return split


def validate_mesh(root: Path, geometry: str, spec: dict, errors: list[str]) -> dict:
    mesh = load_mesh(root, geometry)
    expected = {
        "node_pos": (spec["nodes"], 3),
        "edge_index": (2, spec["edges"]),
        "element_node_index": (spec["elements"], 4),
        "element_node_count": (spec["elements"],),
        "boundary_mask": (spec["nodes"],),
    }
    for key, shape in expected.items():
        if key not in mesh:
            fail(errors, f"{geometry} mesh missing {key}")
        elif mesh[key].shape != shape:
            fail(errors, f"{geometry} mesh {key}: {mesh[key].shape} != {shape}")
    if "node_pos" in mesh and not np.isfinite(mesh["node_pos"]).all():
        fail(errors, f"{geometry} mesh node_pos is non-finite")
    if "edge_index" in mesh:
        edges = mesh["edge_index"]
        if edges.min() < 0 or edges.max() >= spec["nodes"]:
            fail(errors, f"{geometry} edge_index is out of range")
    if "element_node_index" in mesh:
        connectivity = mesh["element_node_index"]
        if connectivity.min() < 0 or connectivity.max() >= spec["nodes"]:
            fail(errors, f"{geometry} element_node_index is out of range")
    if "element_node_count" in mesh and not np.isin(
        mesh["element_node_count"], [3, 4]
    ).all():
        fail(errors, f"{geometry} element_node_count contains values outside 3/4")
    return {
        "nodes": spec["nodes"],
        "edges": spec["edges"],
        "elements": spec["elements"],
    }


def validate_case(
    root: Path,
    geometry: str,
    case_id: str,
    spec: dict,
    expected_digest: str | None,
    errors: list[str],
) -> dict:
    payload = load_case_bytes(root, geometry, case_id)
    digest = sha256_bytes(payload)
    if expected_digest and digest != expected_digest:
        fail(errors, f"{geometry}/{case_id}: SHA-256 mismatch")
    data = torch.load(
        __import__("io").BytesIO(payload), map_location="cpu", weights_only=True
    )
    if data.get("case") != case_id:
        fail(errors, f"{geometry}/{case_id}: stored case identifier mismatch")
    expected_shapes = {
        "disp": (spec["nodes"], 17, 3),
        "effective_stress": (spec["elements"], 17),
        "time": (17,),
        "element_time": (17,),
        "valid_node_mask": (spec["nodes"],),
        "boundary_mask": (spec["nodes"],),
        "impact_xyz": (3,),
        "velocity_xyz": (3,),
    }
    for key, shape in expected_shapes.items():
        value = data.get(key)
        if not torch.is_tensor(value) or tuple(value.shape) != shape:
            actual = None if value is None else getattr(value, "shape", type(value))
            fail(errors, f"{geometry}/{case_id} {key}: {actual} != {shape}")
    for key in ("disp", "effective_stress", "time", "element_time"):
        value = data.get(key)
        if torch.is_tensor(value) and not torch.isfinite(value).all():
            fail(errors, f"{geometry}/{case_id}: {key} is non-finite")
    time_values = data.get("time")
    element_time = data.get("element_time")
    if torch.is_tensor(time_values) and time_values.numel() == 17:
        if not torch.all(time_values[1:] >= time_values[:-1]):
            fail(errors, f"{geometry}/{case_id}: time is not monotonic")
    if torch.is_tensor(element_time) and element_time.numel() == 17:
        if not torch.all(element_time[1:] >= element_time[:-1]):
            fail(errors, f"{geometry}/{case_id}: element_time is not monotonic")
    if (
        torch.is_tensor(time_values)
        and torch.is_tensor(element_time)
        and tuple(time_values.shape) == (17,)
        and tuple(element_time.shape) == (17,)
        and not torch.allclose(time_values, element_time, rtol=0.0, atol=1.0e-8)
    ):
        fail(errors, f"{geometry}/{case_id}: displacement/stress time arrays differ")
    return {
        "bytes": len(payload),
        "sha256": digest,
        "material": str(data.get("material_name", "")),
    }


def load_manifest(root: Path, errors: list[str]) -> dict[tuple[str, str], dict]:
    path = root / "manifest.csv"
    rows = {}
    with path.open(encoding="utf-8", newline="") as handle:
        for row in csv.DictReader(handle):
            key = (row["geometry"], row["case"])
            if key in rows:
                fail(errors, f"duplicate manifest row: {key}")
            rows[key] = row
    if len(rows) != 1500:
        fail(errors, f"manifest has {len(rows)} rows, expected 1500")
    return rows


def validate_archives(root: Path, errors: list[str]) -> dict:
    archive_count = 0
    total_bytes = 0
    for geometry in SPECS:
        for start in range(1, 501, 100):
            end = start + 99
            path = root / "data" / geometry / f"cases_{start:03d}_{end:03d}.zip"
            if not path.is_file():
                fail(errors, f"missing archive: {path.relative_to(root)}")
                continue
            archive_count += 1
            total_bytes += path.stat().st_size
            with zipfile.ZipFile(path) as archive:
                bad_member = archive.testzip()
                if bad_member:
                    fail(errors, f"CRC failure in {path.name}: {bad_member}")
                expected = {
                    f"cases/case{index:03d}.pt" for index in range(start, end + 1)
                }
                if set(archive.namelist()) != expected:
                    fail(errors, f"unexpected members in {path.relative_to(root)}")
    return {"archives": archive_count, "archive_bytes": total_bytes}


def validate_checksums(root: Path, errors: list[str]) -> dict:
    path = root / "checksums.sha256"
    checked = 0
    with path.open(encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, start=1):
            line = line.rstrip("\n")
            if not line:
                continue
            try:
                expected, relative = line.split("  ", 1)
            except ValueError:
                fail(errors, f"invalid checksum line {line_number}")
                continue
            target = root / relative
            if not target.is_file():
                fail(errors, f"checksummed file missing: {relative}")
                continue
            if sha256_file(target) != expected:
                fail(errors, f"file checksum mismatch: {relative}")
            checked += 1
            if target.suffix == ".zip":
                print(f"[file checksum] {relative}")
    return {"checked_files": checked}


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dataset-root", type=Path, default=Path("."))
    parser.add_argument("--verify-checksums", action="store_true")
    parser.add_argument("--report", type=Path)
    args = parser.parse_args()

    root = args.dataset_root.resolve()
    started = time.time()
    errors: list[str] = []
    split = validate_split(root, errors)
    archives = validate_archives(root, errors)
    manifest = load_manifest(root, errors)
    geometry_reports = {}

    for geometry, spec in SPECS.items():
        mesh_report = validate_mesh(root, geometry, spec, errors)
        materials: Counter[str] = Counter()
        total_bytes = 0
        for index in range(1, 501):
            case_id = f"case{index:03d}"
            row = manifest.get((geometry, case_id))
            expected_digest = row["source_sha256"] if row else None
            case_report = validate_case(
                root, geometry, case_id, spec, expected_digest, errors
            )
            total_bytes += case_report["bytes"]
            materials[case_report["material"]] += 1
            if index % 50 == 0:
                print(f"[{geometry}] validated {index}/500")
        geometry_reports[geometry] = {
            **mesh_report,
            "cases": 500,
            "source_case_bytes": total_bytes,
            "materials": dict(sorted(materials.items())),
        }

    checksum_report = (
        validate_checksums(root, errors) if args.verify_checksums else {"skipped": True}
    )
    report = {
        "dataset": "Automotive Underbody Panel Impact Dataset",
        "version": "1.1.1",
        "status": "passed" if not errors else "failed",
        "cases_validated": 1500,
        "split_sizes": {key: len(value) for key, value in split.items()},
        "archives": archives,
        "geometries": geometry_reports,
        "checksums": checksum_report,
        "elapsed_seconds": time.time() - started,
        "errors": errors,
        "scope_note": (
            "Technical package validation only; provenance and remaining "
            "configuration limitations are documented in the release metadata."
        ),
    }
    rendered = json.dumps(report, indent=2, ensure_ascii=False) + "\n"
    print(rendered)
    if args.report:
        args.report.write_text(rendered, encoding="utf-8")
    if errors:
        raise SystemExit(1)


if __name__ == "__main__":
    main()