"""Audit saved final geometry using scalar measures and actual comb evaluation feet. Display edge midpoints are pick locations only. No model is generated or repaired. An absent measurement fails the corresponding check rather than being inferred. """ import argparse import copy import hashlib import json import math from pathlib import Path LINEAR_TOL = 0.03 VOLUME_REL_TOL = 0.002 def read(path): return json.loads(path.read_text()) def feet(batch): return [[tooth[0] for tooth in comb.get("teeth", []) if len(tooth) == 2 and len(tooth[0]) == 3] for comb in batch.get("value", {}).get("combs", [])] def dot(a, b): return sum(x*y for x, y in zip(a, b)) def radial(point, origin, axis): v = [a-b for a, b in zip(point, origin)] along = dot(v, axis) return math.sqrt(max(0, dot(v, v)-along*along)) def cylinder_axis_matches(actual, expected): axis, target = actual.get("axis", []), expected["axis"] if len(axis) != 3 or abs(abs(dot(axis, target))-1) > 1e-6: return False if abs(actual.get("radius", -1)-expected["radius"]) > LINEAR_TOL: return False return radial(actual.get("origin", [math.inf]*3), expected["origin"], target) <= LINEAR_TOL def wrap(angle, period): return (angle+period/2) % period-period/2 def audit(directory, definition, allow_global_phase=False, parameter_role_map=None): inspection = read(directory/"inspection.json") expected = definition["expected"] native = read(directory/"native-inventory.json") samples = read(directory/"actual-edge-samples.json") for supplement_path in sorted(directory.glob("actual-edge-samples-verified-*.json")): supplement = read(supplement_path) digest = hashlib.sha256((directory/"design.sc").read_bytes()).hexdigest() if supplement.get("identity", {}).get("passed") is not True or supplement.get("source_native_sha256") != digest: raise ValueError("Supplement does not verify the unchanged saved native design") samples += supplement["batches"] checks = [] def check(name, passed, actual=None, target=None): checks.append({"name": name, "passed": bool(passed), "actual": actual, "expected": target}) bodies = inspection.get("bodies", []) check("body_count", len(bodies) == len(expected["bodies"]), len(bodies), len(expected["bodies"])) errors = [entry for entry in inspection.get("timeline", []) if entry.get("error") or entry.get("rolled_back")] execution_path = directory/"reference-execution.json" if execution_path.exists(): errors += [entry["value"]["failed"] for entry in read(execution_path) if entry.get("value", {}).get("failed")] check("no_failed_features_or_batches", not errors, errors) model_result = directory/"reference-result.json" if model_result.exists(): check("deterministic_reference_sent_no_model_request", read(model_result).get("model_requests") == 0) sampling_errors = [batch["value"] for batch in samples if batch.get("value", {}).get("error") or batch.get("value", {}).get("ok") is False] check("actual_sample_tools_succeeded", not sampling_errors, sampling_errors) # Roles come from actual geometry, never from reference body names. remaining = list(bodies) roles = [] for target in expected["bodies"]: if not remaining: roles.append(None) continue body = min(remaining, key=lambda b: abs(b["bbox"]["min"][2]-target["bbox"][0][2])+abs(b["bbox"]["max"][2]-target["bbox"][1][2])) remaining.remove(body) roles.append(body) all_points = [] for role_index, (body, target) in enumerate(zip(roles, expected["bodies"])): if body is None: check(f"body{role_index}_present", False) continue name = body["name"] curves = [curve for batch in samples if batch.get("body") == name for curve in feet(batch) if curve] points = [p for curve in curves for p in curve] all_points += points faces = [face for entry in native if entry["command"] == "model.faces" and entry["body"] == name for face in entry["value"].get("faces", [])] check(f"body{role_index}_closed_single_shell", body.get("closed") and body.get("volume_mm3", 0)>0 and body.get("kernel", {}).get("shells") == 1, {k: body.get(k) for k in ("closed", "volume_mm3", "kernel")}) actual_box = [body["bbox"]["min"], body["bbox"]["max"]] if "gear" in expected or definition["type_id"] == "hex-head-bolt": # A legal Z rotation need not match the reference's X/Y extrema. box_error = max(abs(actual_box[i][2]-target["bbox"][i][2]) for i in range(2)) else: box_error = max(abs(a-b) for row_a, row_b in zip(actual_box, target["bbox"]) for a, b in zip(row_a, row_b)) check(f"body{role_index}_absolute_bounds", box_error <= LINEAR_TOL, actual_box, target["bbox"]) volume_error = abs(body.get("volume_mm3", 0)-target["volume"])/target["volume"] check(f"body{role_index}_independent_volume", volume_error <= VOLUME_REL_TOL, {"value": body.get("volume_mm3"), "relative_error": volume_error, "measured_by": body.get("measured_by")}, target["volume"]) for cylinder in target.get("cylinders", []): matched = [face for face in faces if face.get("cylinder") and cylinder_axis_matches(face["cylinder"], cylinder)] check(cylinder["role"]+"_analytic_axis_radius", bool(matched), [f["cylinder"] for f in matched], cylinder) on_cylinder = [curve for curve in curves if len(curve)>1 and max(abs(radial(p, cylinder["origin"], cylinder["axis"])-cylinder["radius"]) for p in curve)LINEAR_TOL: continue a, b = curve[0], curve[-1] length = math.hypot(b[0]-a[0], b[1]-a[1]) if length<0.1: continue nx, ny = -(b[1]-a[1])/length, (b[0]-a[0])/length distance = nx*a[0]+ny*a[1] if max(abs(nx*p[0]+ny*p[1]-distance) for p in curve)>LINEAR_TOL: continue if distance<0: nx, ny, distance = -nx, -ny, -distance angle = math.atan2(ny, nx) % (2*math.pi) if not any(abs(wrap(angle-old[0], 2*math.pi))<1e-5 and abs(distance-old[1])=rib["side_x"]-LINEAR_TOL and abs(p[1]-sy*rib["thickness"]/2)=3 and max(abs(p[0]) for p in selected)>=rib["side_x"]+rib["reach"]-LINEAR_TOL, {"feet": len(selected), "x_range": [min((p[0] for p in selected), default=None), max((p[0] for p in selected), default=None)]}) if type_id == "covered-thin-wall-enclosure" and len(roles)==2 and all(roles): gap = roles[1]["bbox"]["min"][2]-roles[0]["bbox"]["max"][2] check("lid_case_absolute_plane_gap", abs(gap-expected["gap"])<=LINEAR_TOL, gap, expected["gap"]) values = {n: float(e.split()[0]) for n, e, u in definition["parameters"] if u=="mm" and e.split()[0].replace('.', '', 1).replace('-', '', 1).isdigit()} for sx in (-1, 1): for sy in (-1, 1): cx, cy = sx*expected["shared_fastener_xy"][0], sy*expected["shared_fastener_xy"][1] rib_y = sy*(values["caseWidth"]/2-values["wallThickness"]) rib_top = values["bottomThickness"]+values["ribHeight"] hits = [p for p in all_points if abs(abs(p[0]-cx)-values["ribThickness"]/2)=3 and any(abs(p[1]-rib_y)ra+LINEAR_TOL: continue if max(radii)-min(radii)<0.005 and max(p[2] for p in curve)-min(p[2] for p in curve)<0.1: continue flank_curves += 1 flank_points.extend(curve) observations = [] for x, y, z in flank_points: r = math.hypot(x, y) if rhalf+gap+LINEAR_TOL for *_,z in observations), "lower_outer_end": sum(abs(z)=4 for count in z_groups.values()), z_groups) for label, level in (("lower_outer",0),("upper_outer",width),("lower_inner",half),("upper_inner",half+gap)): markers = {} boundary_points = [p for p in flank_points if abs(p[2]-level)<=LINEAR_TOL] transport = level*rate if level<=half+LINEAR_TOL else half*rate-(level-half-gap)*rate for x,y,z in boundary_points: r=math.hypot(x,y) roll=math.sqrt(max(0,(r/rb)**2-1)) h=base_angle-roll+math.atan(roll) angle=math.atan2(y,x)-transport-phase sign=min((-1,1),key=lambda sign:abs(wrap(angle-sign*h,period))) tooth=round((angle-sign*h)/period)%gear["teeth"] markers.setdefault((tooth,sign),[]).append(r) complete=sum(min(radii)<=rb+LINEAR_TOL and max(radii)>=ra-LINEAR_TOL for radii in markers.values()) check(label+"_all_final_involute_flanks_span_base_to_tip",complete==2*gear["teeth"],complete,2*gear["teeth"]) for label,lo,hi in (("lower",0,half),("upper",half+gap,width)): interior=[z for *_,z in observations if lo+0.1=gear["teeth"]*4,len(interior)) if gap>0: faces = [f for entry in native if entry["command"]=="model.faces" for f in entry["value"].get("faces", [])] core = {"radius": gear["root_radius"], "origin": [0,0,0], "axis": [0,0,1], "interval": [half,half+gap]} check("groove_has_analytic_root_core_cylinder", any(f.get("cylinder") and cylinder_axis_matches(f["cylinder"],core) for f in faces)) core_curves = [curve for batch in samples for curve in feet(batch) if curve and max(abs(math.hypot(p[0],p[1])-gear["root_radius"]) for p in curve)