"""Offline, frozen object-proposal comparison; never publishes map features. The production proposal generator is reused. Downstream family fitting and the full mapping pipeline are deliberately outside this admission-stage experiment. """ import hashlib import json import sys import time from datetime import UTC, datetime from pathlib import Path import cv2 import numpy as np from paint_hypothesis_study import fit_classifier, probability from paint_observations import collect from PIL import Image from scipy.optimize import linear_sum_assignment from shapely import affinity from shapely.geometry import Polygon, mapping, shape from shapely.ops import unary_union SHAPE = ["area", "length", "width", "aspect", "fill", "solidity", "holes", "compactness"] APPEARANCE = ["gray_mean", "gray_p10", "saturation", "contrast", "yellow", "white"] CONTEXT = ["road", "roadway", "sidewalk", "marking", "crosswalk"] VARIANTS = {"shape": 8, "shape_appearance": 14, "shape_appearance_context": 19} def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def save_new(path, value): with Path(path).open("x") as f: json.dump(value, f, indent=2, allow_nan=False) def timestamp(): return dict(utc=datetime.now(UTC).isoformat(), monotonic=time.monotonic()) def masks(poly, size=512): mask = np.zeros((size, size), np.uint8) cv2.fillPoly(mask, [np.rint(poly.exterior.coords).astype(np.int32)], 1) for hole in poly.interiors: cv2.fillPoly(mask, [np.rint(hole.coords).astype(np.int32)], 0) return mask.astype(bool) def to_pixel(poly): return affinity.translate(affinity.scale(poly, 512 / 12, -512 / 12, origin=(0, 0)), -0.5, 511.5) def deduplicate(items): out = [] for p, props in sorted(items, key=lambda x: (-x[0].area, x[0].wkt)): if any(p.intersection(q).area / p.union(q).area > 0.85 for q, _ in out): continue out.append((p, props)) return out def descriptors(poly, rgb, fields): mask = masks(poly) if not mask.any(): raise ValueError("Empty rasterized candidate") hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV) gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32) contrast = gray - cv2.GaussianBlur(gray, (0, 0), 0.35 * 512 / 12) short, long = sorted(cv2.minAreaRect(np.asarray(poly.exterior.coords, np.float32))[1]) area = poly.area values = [ area * (12 / 512) ** 2, long * 12 / 512, short * 12 / 512, long / max(short, 1e-8), area / max(short * long, 1e-8), area / max(poly.convex_hull.area, 1e-8), len(poly.interiors), 4 * np.pi * area / max(poly.length**2, 1e-8), gray[mask].mean() / 255, np.quantile(gray[mask], 0.1) / 255, hsv[..., 1][mask].mean() / 255, contrast[mask].mean() / 255, np.mean(((hsv[..., 0] > 12) & (hsv[..., 0] < 36) & (hsv[..., 1] > 55))[mask]), np.mean(((hsv[..., 1] < 85) & (gray > 115))[mask]), ] values.extend( float(np.mean(fields[k][mask])) for k in ["road", "roadway", "sidewalk", "road marking", "crosswalk"] ) return [float(v) for v in values] def propose(root): records = json.loads((root / "inputs.json").read_text())["records"] for name, digest in json.loads((root / "input-hashes.json").read_text()).items(): if sha(root / name) != digest: raise ValueError("Changed frozen input: " + name) g = dict( view=np.array([[1, 0, 0, -6], [0, -1, 0, 6], [0, 0, -1, 10], [0, 0, 0, 1]], float), intrinsics=np.array([[100, 0, 600], [0, 100, 600], [0, 0, 1]], float), ) results = [] for a in records: rgb = np.asarray(Image.open(root / "data" / (a["id"] + ".png")).convert("RGB")) z = dict(np.load(root / "data" / (a["id"] + ".npz"))) road = cv2.resize( z["road"].astype(np.uint8), (120, 120), interpolation=cv2.INTER_NEAREST ).astype(bool) distance = cv2.resize(z["road_dist"].astype(np.float32), (120, 120)) variants = {} for mode in ["hard", "retained"]: paint, cross = collect( rgb, z["vehicle"], g, z["road marking"], z["crosswalk"], road, [0, 0], [12, 12], {"id": a["id"]}, distance, span_m=12, retain_uncertain=mode == "retained", valid=z["alpha"], ) candidates = [] for i, (poly, props) in enumerate(deduplicate(paint + cross)): pp = to_pixel(poly) # Fixed comparator stops at candidate admission; no family fitting. admitted = ( props.get("subtype") == "crosswalk" or props.get("proposal_contract") == "semantic-paint-v1" or ( props.get("semantic_support", 0) >= 0.10 and props.get("semantic_peak", 0) >= 0.3 ) ) candidates.append( dict( id=f"{mode}-{i}", geometry=mapping(pp), properties=props, features=descriptors(pp, rgb, z), fixed_admitted=bool(admitted), ) ) variants[mode] = candidates results.append(dict(id=a["id"], street=a["street"], split=a["split"], variants=variants)) save_new( root / "candidates.json", dict( **timestamp(), records=results, feature_names=SHAPE + APPEARANCE + CONTEXT, generator_sha256=sha(Path(__file__).with_name("paint_observations.py")), ), ) print( json.dumps( { "windows": len(results), "candidates": { mode: sum(len(a["variants"][mode]) for a in results) for mode in ["hard", "retained"] }, } ) ) def overlap(a, b): return a.intersection(b).area / max(a.union(b).area, 1e-9) def labels(candidates, reviewed): truth = [shape(o["geometry"]) for o in reviewed["objects"]] negative = unary_union([Polygon(p) for p in reviewed["negative"]]) out = [] for c in candidates: p = shape(c["geometry"]) best = max([overlap(p, t) for t in truth], default=0) if best >= 0.5: out.append(1) elif not negative.is_empty and p.intersection(negative).area / p.area >= 0.90: out.append(0) else: out.append(-1) return np.array(out) def matched(candidates, reviewed, complete=True): truth = [o for o in reviewed["objects"] if o["complete"] == complete] ious = np.array( [[overlap(shape(c["geometry"]), shape(t["geometry"])) for t in truth] for c in candidates] ) best = np.max(ious, axis=0).tolist() if candidates and truth else [0.0] * len(truth) found = set() if candidates and truth: rows, cols = linear_sum_assignment(-2 * (ious >= 0.5).astype(float) - 0.001 * ious) found = {int(j) for i, j in zip(rows, cols, strict=True) if ious[i, j] >= 0.5} return dict( total=len(truth), found=len(found), recall=len(found) / len(truth) if truth else None, objects=[ dict(id=t["id"], family=t["family"], best_iou=best[i], matched=i in found) for i, t in enumerate(truth) ], ) def score(candidates, reviewed): result = matched(candidates, reviewed) result["unsupported"] = int(np.sum(labels(candidates, reviewed) == 0)) result["accepted"] = len(candidates) result["clipped_components"] = matched(candidates, reviewed, complete=False) return result def aggregate(rows): total = sum(r["total"] for r in rows) found = sum(r["found"] for r in rows) return dict( total=total, found=found, recall=found / total if total else None, unsupported=sum(r["unsupported"] for r in rows), accepted=sum(r["accepted"] for r in rows), ) def fit_models(records, review, thresholds): train = [a for a in records if a["split"] == "train"] val = [a for a in records if a["split"] == "validation"] baseline = aggregate( [ score([c for c in a["variants"]["hard"] if c["fixed_admitted"]], review[a["id"]]) for a in val ] ) x, y = [], [] for a in train: cs = a["variants"]["retained"] ls = labels(cs, review[a["id"]]) for c, label in zip(cs, ls, strict=True): if label >= 0: x.append(c["features"]) y.append(label) x, y = np.asarray(x), np.asarray(y) if min(np.sum(y == 0), np.sum(y == 1)) < 2: raise ValueError("Insufficient independent training candidates") models, choices = {}, [] for variant, count in VARIANTS.items(): model = fit_classifier(x[:, :count], y, 0.01, 500) rows = [] for threshold in thresholds: scores = [] for a in val: cs = a["variants"]["retained"] ps = probability(np.array([c["features"][:count] for c in cs]), model) if cs else [] scores.append( score( [c for c, p in zip(cs, ps, strict=True) if p >= threshold], review[a["id"]] ) ) summary = aggregate(scores) rows.append(dict(threshold=threshold, **summary)) feasible = [v for v in rows if v["unsupported"] <= baseline["unsupported"]] selected = ( min(feasible, key=lambda v: (-v["found"], v["unsupported"], v["threshold"])) if feasible else None ) models[variant] = dict(model=model, validation=rows, selected=selected) if selected: choices.append(dict(variant=variant, **selected)) chosen = ( min(choices, key=lambda v: (-v["found"], v["unsupported"], v["variant"])) if choices else None ) return dict( models=models, chosen=chosen, baseline_validation=baseline, training=dict(positive=int(sum(y == 1)), negative=int(sum(y == 0)), windows=len(train)), ) def train(root): records = json.loads((root / "candidates.json").read_text())["records"] review = json.loads((root / "review-frozen.json").read_text())["records"] # Never pass heldout labels to fitting or selection. usable = [a for a in records if a["split"] != "heldout"] limited_review = {a["id"]: review[a["id"]] for a in usable} protocol = json.loads((root / "protocol.json").read_text()) result = fit_models(usable, limited_review, protocol["fixed_design"]["threshold_grid"]) result.update(timestamp()) result["source_sha256"] = sha(__file__) result["input_sha256"] = { n: sha(root / n) for n in ["candidates.json", "review-frozen.json", "protocol.json", "input-hashes.json"] } save_new(root / "models-frozen.json", result) print(json.dumps({k: result[k] for k in ["chosen", "baseline_validation", "training"]})) def evaluate(root): frozen = json.loads((root / "models-frozen.json").read_text()) if frozen["source_sha256"] != sha(__file__): raise ValueError("Source changed after model freeze") for name, digest in frozen["input_sha256"].items(): if sha(root / name) != digest: raise ValueError("Input changed after model freeze: " + name) records = json.loads((root / "candidates.json").read_text())["records"] review = json.loads((root / "review-frozen.json").read_text())["records"] result = [] for a in records: sets = { "hard_proposals": a["variants"]["hard"], "retained_proposals": a["variants"]["retained"], "fixed_admission": [c for c in a["variants"]["hard"] if c["fixed_admitted"]], } for variant, count in VARIANTS.items(): item = frozen["models"][variant] cs = a["variants"]["retained"] ps = ( probability(np.array([c["features"][:count] for c in cs]), item["model"]) if cs else [] ) threshold = item["selected"]["threshold"] if item["selected"] else 2 sets[variant] = [ dict(c, probability=float(p)) for c, p in zip(cs, ps, strict=True) if p >= threshold ] result.append( dict( id=a["id"], street=a["street"], split=a["split"], scores={k: score(cs, review[a["id"]]) for k, cs in sets.items()}, accepted_ids={k: [c["id"] for c in cs] for k, cs in sets.items()}, ) ) streets = { street: { mode: aggregate([a["scores"][mode] for a in result if a["street"] == street]) for mode in result[0]["scores"] } for street in sorted({a["street"] for a in result}) } save_new( root / "results.json", dict( **timestamp(), chosen=frozen["chosen"], streets=streets, windows=result, scope=( "Object proposal/admission stage only; " "no downstream fit or full-pipeline acceptance." ), ), ) print(json.dumps(streets)) if __name__ == "__main__": cv2.setNumThreads(3) {"propose": propose, "train": train, "evaluate": evaluate}[sys.argv[1]](Path(sys.argv[2]))