File size: 3,606 Bytes
f1564a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Verify a downloaded T2 release without importing AgentFEM."""

from __future__ import annotations

import argparse
import hashlib
import json
from collections import Counter
from pathlib import Path

import h5py
import numpy as np


EXPECTED_SPLITS = {"train": 768, "validation": 120, "test": 120}
EXPECTED_MODELS = {"j2_linear_isotropic": 504, "chaboche_combined": 504}
EXPECTED_PATH_COUNT = 168


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


def resolve_shard(root: Path, relative_path: str) -> Path:
    local = root / "shards" / Path(relative_path).name
    if local.exists():
        return local
    packaged = root.parents[1] / relative_path
    if packaged.exists():
        return packaged
    raise FileNotFoundError(f"Missing shard: {relative_path}")


def verify(root: Path) -> dict[str, object]:
    manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
    ids: list[str] = []
    splits: Counter[str] = Counter()
    models: Counter[str] = Counter()
    paths: Counter[str] = Counter()

    for shard in manifest["shards"]:
        path = resolve_shard(root, shard["path"])
        observed_hash = sha256(path)
        if observed_hash != shard["sha256"]:
            raise RuntimeError(f"SHA-256 mismatch: {path}")
        with h5py.File(path, "r") as h5:
            shard_ids = sorted(h5.keys())
            if len(shard_ids) != shard["sample_count"]:
                raise RuntimeError(f"Sample-count mismatch: {path}")
            if shard_ids[0] != shard["first_id"] or shard_ids[-1] != shard["last_id"]:
                raise RuntimeError(f"ID-range mismatch: {path}")
            for sample_id in shard_ids:
                group = h5[sample_id]
                ids.append(sample_id)
                splits[str(group.attrs["split"])] += 1
                models[str(group.attrs["material_model"])] += 1
                paths[str(group.attrs["path_family"])] += 1
                for name in group.keys():
                    if not np.isfinite(group[name][:]).all():
                        raise RuntimeError(f"Non-finite values: {path}:{sample_id}/{name}")

    expected_ids = [f"{index:05d}" for index in range(manifest["sample_count"])]
    if ids != expected_ids:
        raise RuntimeError("Trajectory IDs are incomplete, duplicated or out of order.")
    if dict(splits) != EXPECTED_SPLITS:
        raise RuntimeError(f"Unexpected split counts: {dict(splits)}")
    if dict(models) != EXPECTED_MODELS:
        raise RuntimeError(f"Unexpected material-model counts: {dict(models)}")
    if set(paths.values()) != {EXPECTED_PATH_COUNT} or len(paths) != 6:
        raise RuntimeError(f"Unexpected path-family counts: {dict(paths)}")

    result = {
        "status": "verified",
        "sample_count": len(ids),
        "shard_count": len(manifest["shards"]),
        "splits": dict(sorted(splits.items())),
        "material_models": dict(sorted(models.items())),
        "path_families": dict(sorted(paths.items())),
        "agentfem_commit": manifest["agentfem_commit"],
    }
    print(json.dumps(result, indent=2, sort_keys=True))
    return result


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "dataset_root",
        nargs="?",
        default="data/t2_material_loading_memory_v1",
    )
    args = parser.parse_args()
    verify(Path(args.dataset_root))


if __name__ == "__main__":
    main()