Files
2026-11-12 20:40:21 +08:00

281 lines
18 KiB
Python

"""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]
axial = [dot(p, cylinder["axis"]) for curve in on_cylinder for p in curve]
span = [min(axial), max(axial)] if axial else None
check(cylinder["role"]+"_absolute_boundary_interval", span is not None and max(abs(a-b) for a, b in zip(span, cylinder["interval"])) <= LINEAR_TOL,
{"interval": span, "actual_feet": len(axial)}, cylinder["interval"])
type_id = definition["type_id"]
if type_id == "hex-head-bolt":
af, top = expected["across_flats"], expected["head_z"][1]
lines = []
for batch in samples:
for curve in feet(batch):
if len(curve)<2 or max(abs(p[2]-top) 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])<LINEAR_TOL for old in lines):
lines.append((angle, distance))
lines.sort()
gaps = [(lines[(i+1)%len(lines)][0]-lines[i][0]) % (2*math.pi) for i in range(len(lines))] if lines else []
check("six_regular_hex_flats_at_requested_across_flats", len(lines)==6 and all(abs(d-af/2)<LINEAR_TOL for _, d in lines) and all(abs(g-math.pi/3)<0.001 for g in gaps), lines, af)
# Accept explicit reviewed semantic mappings, rather than requiring reference names.
# Native parameters carry the simplified-thread semantics; rendered grooves do not.
mapping = parameter_role_map or {"thread_length": "threadLength", "thread_pitch": "threadPitch"}
actual_params = {p["name"]: p for p in inspection.get("params", [])}
length_param = actual_params.get(mapping.get("thread_length"))
pitch_param = actual_params.get(mapping.get("thread_pitch"))
pitch_expression = next(expression for name, expression, unit in definition["parameters"] if name == "threadPitch")
target_pitch = float(pitch_expression.split()[0])
text = json.dumps([length_param, pitch_param], ensure_ascii=False)
check("native_simplified_thread_semantics_retained", length_param is not None and pitch_param is not None
and length_param.get("error") is None and pitch_param.get("error") is None
and abs(length_param.get("value", -1)-expected["thread_interval"][1]) <= LINEAR_TOL
and abs(pitch_param.get("value", -1)-target_pitch) <= LINEAR_TOL
and "简化" in text and ("圆柱" in text or "无真实牙型" in text or "不生成真实" in text),
{"mapping": mapping, "parameters": [length_param, pitch_param]},
{"thread_interval": expected["thread_interval"], "pitch_mm": target_pitch})
if type_id == "ribbed-bearing-housing":
rib = expected["rib_sections"]
for sx in (-1, 1):
for sy in (-1, 1):
selected = [p for p in all_points if sx*p[0]>=rib["side_x"]-LINEAR_TOL and abs(p[1]-sy*rib["thickness"]/2)<LINEAR_TOL
and abs(p[2]-(rib["base_z"]+rib["height"]*(1-(abs(p[0])-rib["side_x"])/rib["reach"])))<LINEAR_TOL]
check(f"rib_{sx}_{sy}_actual_sloping_edge", len(selected)>=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)<LINEAR_TOL and abs(p[2]-rib_top)<LINEAR_TOL
and min(cy, rib_y)-LINEAR_TOL<=p[1]<=max(cy, rib_y)+LINEAR_TOL]
check(f"boss_rib_{sx}_{sy}_reaches_y_wall", len(hits)>=3 and any(abs(p[1]-rib_y)<LINEAR_TOL for p in hits), {"actual_feet": len(hits)})
gear_details = None
if "gear" in expected:
gear = expected["gear"]
pitch, rb, ra, base_angle = gear["pitch_radius"], gear["base_radius"], gear["tip_radius"], gear["base_angle_rad"]
half, gap, width = gear["half_width"], gear["gap"], gear["width"]
rate = math.tan(math.radians(gear["beta_deg"]))/pitch
period = 2*math.pi/gear["teeth"]
flank_points = []
flank_curves = 0
for batch in samples:
for curve in feet(batch):
radii = [math.hypot(p[0], p[1]) for p in curve]
if not radii or min(radii)<rb-LINEAR_TOL or max(radii)>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 r<rb:
continue
roll = math.sqrt(max(0, (r/rb)**2-1))
tooth_half = base_angle-roll+math.atan(roll)
phase = z*rate if z<=half+LINEAR_TOL else half*rate-(z-half-gap)*rate
observations.append((r, wrap(math.atan2(y, x)-phase, period), tooth_half, z))
def errors(global_phase):
return [r*min(abs(wrap(angle-global_phase-h, period)), abs(wrap(angle-global_phase+h, period))) for r, angle, h, _ in observations]
phase = 0
if allow_global_phase and observations:
trial_points = observations[::max(1,len(observations)//200)]
candidates = [wrap(a-sign*h, period) for _, a, h, _ in trial_points for sign in (-1,1)]
def score(phi):
return sum(r*min(abs(wrap(a-phi-h, period)),abs(wrap(a-phi+h, period))) for r,a,h,_ in trial_points)
phase = min(candidates, key=score)
deviations = errors(phase)
z_groups = {"lower": sum(z<half-LINEAR_TOL for *_,z in observations),
"upper": sum(z>half+gap+LINEAR_TOL for *_,z in observations),
"lower_outer_end": sum(abs(z)<LINEAR_TOL for *_,z in observations),
"upper_outer_end": sum(abs(z-width)<LINEAR_TOL for *_,z in observations),
"lower_inner_end": sum(abs(z-half)<LINEAR_TOL for *_,z in observations),
"upper_inner_end": sum(abs(z-half-gap)<LINEAR_TOL for *_,z in observations)}
check("both_helical_hands_and_involute_final_edges", bool(deviations) and max(deviations)<=LINEAR_TOL,
{"max_error_mm": max(deviations, default=None), "actual_flank_feet": len(deviations), "curves": flank_curves, "global_phase_rad": phase})
check("both_arms_endplanes_and_inner_boundaries_sampled", all(count>=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<z<hi-0.1]
check(label+"_screw_motion_has_actual_interior_samples",len(interior)>=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)<LINEAR_TOL]
middle_points = [p for curve in core_curves for p in curve if half-LINEAR_TOL<=p[2]<=half+gap+LINEAR_TOL]
core_span = [min(p[2] for p in middle_points),max(p[2] for p in middle_points)] if middle_points else None
check("groove_root_boundary_absolute_interval", core_span is not None and max(abs(a-b) for a,b in zip(core_span,[half,half+gap]))<=LINEAR_TOL, core_span, [half,half+gap])
gear_details = {"finite_evaluation_only": True, "z_coverage": z_groups,
"not_verified": ["continuous full-surface bound", "conjugate contact", "manufacturing apex or groove root", "load capacity"]}
identity_source = directory/"design.sc" if (directory/"design.sc").exists() else directory/"document.json"
return {"type_id": type_id, "directory": str(directory.resolve()), "identity_source": identity_source.name,
"native_or_export_sha256": hashlib.sha256(identity_source.read_bytes()).hexdigest(),
"checks": checks, "passed": all(c["passed"] for c in checks), "passed_count": sum(c["passed"] for c in checks), "total": len(checks),
"body_role_mapping": [b["name"] if b else None for b in roles], "linear_tolerance_mm": LINEAR_TOL, "relative_volume_tolerance": VOLUME_REL_TOL,
"actual_edge_feet": len(all_points), "gear_sampling": gear_details,
"measurement_semantics": "smlib measures use corresponding surface integration/tight bounds. Face descriptors identify analytic axes/radii. Only combs[].teeth[][0] are actual finite curve evaluations; display mid/length are never precise curve measurements.",
"limitations": ["Finite boundary checks do not prove every interior surface or material point.", "Parameters and final geometry are not an edit-propagation test.", "No statistical benefit or manufacturing certification follows from a single case."]}
def cylinder(radius, origin, axis, interval, role):
return {"radius": radius, "origin": origin, "axis": axis, "interval": interval, "role": role}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("directory", type=Path)
parser.add_argument("definition", type=Path)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--allow-global-phase", action="store_true")
parser.add_argument("--parameter-role-map", type=Path, help="Explicit reviewed native parameter names for semantic roles")
args = parser.parse_args()
result = audit(args.directory, read(args.definition), args.allow_global_phase,
read(args.parameter_role_map) if args.parameter_role_map else None)
with args.output.open("x") as stream:
json.dump(result, stream, ensure_ascii=False, indent=2)
stream.write("\n")
print(json.dumps({"type_id":result["type_id"],"passed":result["passed"],"score":f'{result["passed_count"]}/{result["total"]}',"failed":[x["name"] for x in result["checks"] if not x["passed"]]}))
if __name__ == "__main__":
main()