"""Offline RGB/depth ranking probe. Never substitutes production admission. Uses the existing four physical evidence terms, without learned masks or occluder fields (absent from the reviewed image pack). Consequently its fixed score is a diagnostic reference, NOT the production algorithm's full score. """ import argparse import hashlib import json import time from pathlib import Path import numpy as np from boundary_anchors import PhysicalFields, resample, sample from boundary_review import clipped_range, verify_pack from PIL import Image, ImageDraw from scipy.optimize import minimize PRIOR = np.array([0.65, 0.65, 0.25, 0.20], dtype=np.float64) TERMS = ["persistent_contrast_edge", "height_step", "oriented_edge", "side_texture"] def components(fields, uv, normal): """Same float32 arrays, interpolation and constants as PhysicalFields.measure.""" n = np.broadcast_to(normal, uv.shape) plus = uv + n * fields.policy.cross_section_m / fields.cell minus = uv - n * fields.policy.cross_section_m / fields.cell near = sample(fields.gray, plus) - sample(fields.gray, minus) far = sample(fields.gray, uv + n * 0.8 / fields.cell) - sample( fields.gray, uv - n * 0.8 / fields.cell ) contrast = np.clip(np.minimum(abs(near), abs(far)) / 18, 0, 1) * (near * far > 0) edge = np.clip( abs(sample(fields.gx, uv) * n[..., 0] + sample(fields.gy, uv) * n[..., 1]) / 55, 0, 1, ) dz = sample(fields.z, plus) - sample(fields.z, minus) step = np.exp(-(((dz - 0.12) / 0.12) ** 2)) * (dz > 0.025) * (dz < 0.35) texture = np.clip( (sample(fields.texture, plus) - sample(fields.texture, minus)) / 20, 0, 1 ) score, reliable = fields.measure(uv, normal) # The retained fixed score comes from production code, not a reordered sum. return np.stack([contrast * edge, step, edge, texture], axis=-1) * reliable[ ..., None ], score * reliable def fields_for(folder): rgb = np.array(Image.open(folder / "top.png").convert("RGB")) g = np.load(folder / "top.geometry.npz") z = g["view"][2, 3] - g["depth"] zero = np.zeros(z.shape, np.float32) cell = 1 / float(g["intrinsics"][0, 0]) return PhysicalFields(rgb, z, g["alpha"], zero, zero, zero, cell), g def project(points, g): xyz = np.asarray(points, dtype=np.float64) view, k = g["view"], g["intrinsics"] camera = xyz @ view[:3, :3].T + view[:3, 3] return camera[:, :2] * np.diag(k)[:2] + k[:2, 2] - 0.5 def describe(fields, path, rect, sidewalk_direction): chunks = [] lengths = [] baseline = [] sidewalk = np.asarray(sidewalk_direction, dtype=float) if ( sidewalk.shape != (2,) or not np.isfinite(sidewalk).all() or np.linalg.norm(sidewalk) == 0 ): raise ValueError("Explicit review orientation required") for a, b in zip(path, path[1:], strict=False): clip = clipped_range(a, b, rect) if clip is None: continue a, b = np.asarray(a), np.asarray(b) ends = np.array([a + t * (b - a) for t in clip]) length = float(np.linalg.norm(ends[1] - ends[0]) * fields.cell) if length < 1e-8: continue # Measurements only: never store these samples as replacement geometry. points = resample(ends * fields.cell, 0.20) / fields.cell tangent = (b - a) / np.linalg.norm(b - a) n = np.array([-tangent[1], tangent[0]]) if n @ sidewalk < 0: n = -n feature, score = components(fields, points, n) chunks.append(feature.mean(0)) baseline.append(float(score.mean())) lengths.append(length) if not chunks: raise ValueError("Candidate has no reviewed extent") return np.average(chunks, axis=0, weights=lengths), float( np.average(baseline, weights=lengths) ) def fit(differences, prior=PRIOR): d = np.asarray(differences, dtype=np.float64) if d.ndim != 2 or d.shape[1] != 4 or len(d) < 2 or not np.isfinite(d).all(): raise ValueError("Finite, reviewed candidate pairs required") # Fixed before held-out evaluation. No hyperparameter search on control. def objective(w): return np.logaddexp(0, -d @ w).mean() + 0.1 * np.square(w - prior).sum() result = minimize( objective, prior, method="L-BFGS-B", bounds=[(0, 2)] * 4, options={"maxiter": 100, "ftol": 1e-12, "gtol": 1e-8}, ) if not result.success or not np.isfinite(result.x).all(): raise ValueError("Ranking fit did not converge") return result.x def train(root, pack_name="expanded-pack", run_name="rank-probe"): start = time.monotonic() pack = root / pack_name verification = verify_pack(pack) review = json.loads((root / "control-review.json").read_text()) control = json.loads((root / "control.json").read_text()) train_world = json.loads((pack / "pack.json").read_text())["source"]["world_sha256"] if ( review["training_eligible"] is not False or not review["reviewed_before_fit"] or review["control_sha256"] != hashlib.sha256((root / "control.json").read_bytes()).hexdigest() or control["world_sha256"] == train_world ): raise ValueError("Frozen independent visual control required before fit") records = json.loads((pack / "records.json").read_text()) orientation = json.loads((root / "training-orientation.json").read_text()) rows = [] for r in records: if not r["ranking_trial_eligible"]: continue folder = pack / "observations" / Path(r["sample"]).parent labels = json.loads((folder / "labels.json").read_text()) fields, g = fields_for(folder) def candidate(key, labels=labels, r=r, fields=fields, g=g): f = next(f for f in labels[key] if f["id"] == r["feature_id"]) return describe( fields, project(f["geometry"]["coordinates"], g), r["rect_px"], orientation[r["id"]], ) positive, pb = candidate("proposed_element") negative, nb = candidate("original_element") rows.append( dict( id=r["id"], feature_id=r["feature_id"], sample=r["sample"], positive=positive.tolist(), negative=negative.tolist(), fixed_margin=pb - nb, ) ) preparation = time.monotonic() - start d = np.array([np.array(r["positive"]) - r["negative"] for r in rows]) training = time.monotonic() w = fit(d) training = time.monotonic() - training # Leave entire source feature out, including distant windows on that feature. loo = [] for fid in sorted({r["feature_id"] for r in rows}): hold = np.array([r["feature_id"] == fid for r in rows]) lw = fit(d[~hold]) loo.extend( dict(id=rows[i]["id"], margin=float(d[i] @ lw)) for i in np.flatnonzero(hold) ) for r, margin in zip(rows, d @ w, strict=True): r["learned_margin"] = float(margin) model = dict( schema_version="missioncore.boundary-rank-probe/v1", terms=TERMS, weights=w.tolist(), prior=PRIOR.tolist(), training_pack_sha256=verification["sha256"], training_world_sha256=json.loads((pack / "pack.json").read_text())["source"][ "world_sha256" ], control_sha256=hashlib.sha256((root / "control.json").read_bytes()).hexdigest(), acceptance_changed=False, production_eligible=False, missing_production_fields=["semantic_context", "occluder"], l2_to_prior=0.1, weight_bounds=[0, 2], sample_m=0.2, review_orientation=True, source_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), physical_fields_sha256=hashlib.sha256( (root / "boundary_anchors.py").read_bytes() ).hexdigest(), ) model["control_review_sha256"] = hashlib.sha256( (root / "control-review.json").read_bytes() ).hexdigest() target = root / run_name target.mkdir(exist_ok=False) (target / "model.json").write_text(json.dumps(model, indent=2, allow_nan=False)) report = dict( rows=rows, leave_feature_out=loo, preparation_seconds=preparation, training_seconds=training, pairs=len(rows), independent_source_features=len(set(r["feature_id"] for r in rows)), fixed_correct=sum(r["fixed_margin"] > 0 for r in rows), fit_correct=sum(r["learned_margin"] > 0 for r in rows), leave_feature_out_correct=sum(r["margin"] > 0 for r in loo), full_chain_run=False, ) (target / "training-report.json").write_text( json.dumps(report, indent=2, allow_nan=False) ) print(json.dumps(report, allow_nan=False)) def evaluate(root, run_name="rank-probe"): start = time.monotonic() target = root / run_name model = json.loads((target / "model.json").read_text()) review = json.loads((root / "control-review.json").read_text()) if ( model["control_review_sha256"] != hashlib.sha256((root / "control-review.json").read_bytes()).hexdigest() ): raise ValueError("Control review changed after fitting") if ( model["source_sha256"] != hashlib.sha256(Path(__file__).read_bytes()).hexdigest() ): raise ValueError("Probe implementation changed after fitting") observations = root / "control-observations" if ( review["observations_sha256"] != hashlib.sha256((observations / "manifest.json").read_bytes()).hexdigest() ): raise ValueError("Control observation identity changed") manifest = json.loads((observations / "manifest.json").read_text()) for name, spec in manifest["files"].items(): p = (observations / name).resolve() if ( not p.is_relative_to(observations.resolve()) or hashlib.sha256(p.read_bytes()).hexdigest() != spec["sha256"] ): raise ValueError("Control observation member changed") rows = [] for r in review["records"]: if not r["eligible"]: rows.append(dict(id=r["id"], status="unscored-unknown", reason=r["reason"])) continue folder = observations / r["id"] fields, g = fields_for(folder) path = np.array(r["path_px"], dtype=float) direction = np.array(r["sidewalk_direction"], dtype=float) direction /= np.linalg.norm(direction) choices = [] for offset in review["candidate_offsets_m"]: candidate = path + offset / fields.cell * direction feature, fixed = describe(fields, candidate, r["rect_px"], direction) choices.append( dict( offset_m=offset, fixed_score=fixed, learned_score=float(feature @ model["weights"]), ) ) fixed = max(choices, key=lambda x: x["fixed_score"]) learned = max(choices, key=lambda x: x["learned_score"]) row = dict( id=r["id"], status="diagnostic-only", fixed_offset_m=fixed["offset_m"], learned_offset_m=learned["offset_m"], fixed_abs_offset_m=abs(fixed["offset_m"]), learned_abs_offset_m=abs(learned["offset_m"]), choices=choices, ) rows.append(row) raw = Image.open(folder / "top.png").convert("RGB") over = raw.copy() draw = ImageDraw.Draw(over) for offset, color in [ (fixed["offset_m"], "#ff9750"), (learned["offset_m"], "#c77dff"), (0, "#55ff8b"), ]: p = path + offset / fields.cell * direction draw.line([tuple(x) for x in p], fill=color, width=3) sheet = Image.new("RGB", (1536, 800), "#161616") sheet.paste(raw, (0, 32)) sheet.paste(over, (768, 32)) ImageDraw.Draw(sheet).text( (12, 10), r["id"] + " | raw / green: visual reference; orange: fixed physical score; purple: learned", fill="white", ) sheet.save(target / (r["id"] + "-evaluation.jpg"), quality=94) report = dict( rows=rows, seconds=time.monotonic() - start, model_sha256=hashlib.sha256((target / "model.json").read_bytes()).hexdigest(), scored_windows=sum(r["eligible"] for r in review["records"]), unknown_windows=sum(not r["eligible"] for r in review["records"]), full_chain_run=False, production_eligible=False, acceptance_changed=False, limitation=("Two locally visible control segments. RGB/depth feature probe lacks " "production semantic context and occluder fields; approximate visual " "references. No deployment or general accuracy claim."), ) p = target / "evaluation.json" if p.exists(): raise ValueError("Do not overwrite frozen evaluation") p.write_text(json.dumps(report, indent=2, allow_nan=False)) print( json.dumps( { **report, "rows": [{k: v for k, v in r.items() if k != "choices"} for r in rows], } ) ) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=["train", "evaluate"]) parser.add_argument("--root", type=Path, default=Path("/experiment")) parser.add_argument("--pack", default="expanded-pack") parser.add_argument("--run", default="rank-probe") args = parser.parse_args() if any(Path(s).name != s or s in {".", ".."} for s in (args.pack, args.run)): parser.error("Pack/run must be direct child directory names") if args.action == "evaluate": evaluate(args.root, args.run) else: train(args.root, args.pack, args.run)