File size: 5,706 Bytes
3ba2635
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

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

DT = 0.1
G = 9.81

FAMILIES = {
    "gravity_fall",
    "projectile_motion",
    "elastic_collision_1d",
    "inelastic_collision_1d",
    "friction_slide",
    "bounce",
    "constant_velocity_occlusion",
    "support_removal",
    "containment",
    "momentum_transfer",
}


def canon(x):
    return json.dumps(x, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def sha(x):
    return hashlib.sha256(canon(x).encode()).hexdigest()


def close(a,b,tol=2e-5):
    return abs(float(a)-float(b)) <= tol


def truth(row):
    s = row["state_t0"]
    a = row["action"]
    fam = row["family"]

    if fam == "gravity_fall":
        y = max(0.0, s["y"] + s["vy"]*DT - .5*G*DT*DT)
        vy = 0.0 if y == 0 else s["vy"]-G*DT
        return {"y":y,"vy":vy}

    if fam == "projectile_motion":
        y = max(0.0, s["y"] + s["vy"]*DT - .5*G*DT*DT)
        return {
            "x":s["x"]+s["vx"]*DT,
            "y":y,
            "vx":s["vx"],
            "vy":0.0 if y == 0 else s["vy"]-G*DT
        }

    if fam == "elastic_collision_1d":
        m1,m2,u1,u2 = s["m1"],s["m2"],s["u1"],s["u2"]
        return {
            "v1":((m1-m2)/(m1+m2))*u1 + ((2*m2)/(m1+m2))*u2,
            "v2":((2*m1)/(m1+m2))*u1 + ((m2-m1)/(m1+m2))*u2
        }

    if fam == "inelastic_collision_1d":
        m1,m2,u1,u2 = s["m1"],s["m2"],s["u1"],s["u2"]
        v=(m1*u1+m2*u2)/(m1+m2)
        return {"v1":v,"v2":v}

    if fam == "friction_slide":
        v=s["velocity"]
        decel=s["mu"]*G*DT
        nv=0.0 if abs(v)<=decel else math.copysign(abs(v)-decel,v)
        return {"velocity":nv}

    if fam == "bounce":
        return {
            "y":0.0,
            "vy":-s["vy"]*s["restitution"]
        }

    if fam == "constant_velocity_occlusion":
        return {
            "x":s["x"]+s["vx"]*s["frames_hidden"]*DT,
            "vx":s["vx"],
            "visible":False
        }

    if fam == "support_removal":
        return {
            "y":max(0.0,s["y"]-.5*G*DT*DT),
            "vy":-G*DT
        }

    if fam == "containment":
        nx=s["x"]+a["dx"]
        ny=s["y"]+a["dy"]

        cx=s["container_x"]
        cy=s["container_y"]
        radius=s["radius"]

        d=math.hypot(nx-cx,ny-cy)

        if d>radius:
            scale=radius/d
            nx=cx+(nx-cx)*scale
            ny=cy+(ny-cy)*scale

        return {"x":nx,"y":ny,"contained":True}

    if fam == "momentum_transfer":
        m1,m2=s["m1"],s["m2"]
        u1,u2=s["u1"],s["u2"]
        e=s["restitution"]

        return {
            "v1":(m1*u1+m2*u2-m2*e*(u1-u2))/(m1+m2),
            "v2":(m1*u1+m2*u2+m1*e*(u1-u2))/(m1+m2)
        }

    raise ValueError(fam)


def compare(calc, stored):
    if set(calc) != set(stored):
        return False

    for k,v in calc.items():
        sv=stored[k]

        if isinstance(v,bool):
            if v is not sv:
                return False
        elif not close(v,sv):
            return False

    return True


def validate(path):
    ids=set()
    fps=set()
    families=Counter()
    splits=Counter()
    count=0

    with path.open("r",encoding="utf-8") as f:
        for line in f:
            if not line.strip():
                continue

            r=json.loads(line)
            count += 1

            if r["family"] not in FAMILIES:
                raise ValueError("unknown family")

            if r["id"] in ids:
                raise ValueError("duplicate id")

            if r["fingerprint_sha256"] in fps:
                raise ValueError("duplicate fingerprint")

            ids.add(r["id"])
            fps.add(r["fingerprint_sha256"])

            body={
                k:v for k,v in r.items()
                if k not in {"id","fingerprint_sha256"}
            }

            if sha(body)[:32] != r["id"]:
                raise ValueError(f"id mismatch {r['id']}")

            with_id=dict(body)
            with_id["id"]=r["id"]

            if sha(with_id) != r["fingerprint_sha256"]:
                raise ValueError(f"fingerprint mismatch {r['id']}")

            calc=truth(r)

            if not compare(calc,r["expected_state_t1"]):
                raise ValueError(f"oracle mismatch {r['id']}")

            changed=[
                k for k in r["expected_state_t1"]
                if r["expected_state_t1"][k] != r["counterfactual_state_t1"][k]
            ]

            if changed != [r["counterfactual_changed_field"]]:
                raise ValueError(f"counterfactual mismatch {r['id']}")

            if compare(calc,r["counterfactual_state_t1"]):
                raise ValueError(f"counterfactual accidentally valid {r['id']}")

            p=r["provenance"]

            if not p["synthetic"] or p["copied_records"] != 0 or p["contains_pii"]:
                raise ValueError("provenance")

            if p["llm_generated_ground_truth"]:
                raise ValueError("ground truth provenance")

            families[r["family"]] += 1
            splits[r["split"]] += 1

    return {
        "status":"PASS",
        "validated":count,
        "unique_ids":len(ids),
        "unique_fingerprints":len(fps),
        "families":dict(families),
        "splits":dict(splits)
    }


def main():
    ap=argparse.ArgumentParser()
    ap.add_argument("dataset",type=Path)
    ap.add_argument("--report",type=Path)
    a=ap.parse_args()

    report=validate(a.dataset)

    if a.report:
        a.report.write_text(
            json.dumps(report,indent=2),
            encoding="utf-8"
        )

    print(json.dumps(report))


if __name__=="__main__":
    main()