"""Bounded single-view assembly/learning experiment, never a map publisher. Inputs, annotation, policy, model selection and held-out evaluation are separate. The retained two-view downstream row fitter is NOT qualified by this experiment. """ import json import sys from pathlib import Path import cv2 import numpy as np from object_proposal_study import ( aggregate, descriptors, labels, masks, overlap, save_new, score, sha, timestamp, ) from object_proposal_study import ( propose as base_propose, ) from paint_hypothesis_study import fit_classifier, probability from PIL import Image from shapely.geometry import mapping, shape from shapely.ops import unary_union MODEL_SIZES = {"expanded_shape_appearance": 14, "expanded_texture": 22} def rectangle(poly, mpp): box = np.asarray(poly.minimum_rotated_rectangle.exterior.coords)[:4] edges = np.roll(box, -1, axis=0) - box lengths = np.linalg.norm(edges, axis=1) k = int(np.argmax(lengths)) axis = edges[k] / max(lengths[k], 1e-9) if axis[0] < 0 or (axis[0] == 0 and axis[1] < 0): axis = -axis return dict( center=box.mean(axis=0), axis=axis, length=float(lengths.max() * mpp), width=float(lengths.min() * mpp), fill=poly.area / max(poly.minimum_rotated_rectangle.area, 1e-9), ) def texture(poly, rgb): mask = masks(poly.minimum_rotated_rectangle) gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32) residual = gray - cv2.GaussianBlur(gray, (0, 0), 0.35 * 512 / 12) gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0) gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1) mag = np.hypot(gx, gy)[mask] xx, yy, xy = np.mean(gx[mask] ** 2), np.mean(gy[mask] ** 2), np.mean(gx[mask] * gy[mask]) coherence = np.hypot(xx - yy, 2 * xy) / max(xx + yy, 1e-9) values = [ gray[mask].std() / 255, residual[mask].std() / 255, (np.quantile(gray[mask], 0.9) - np.quantile(gray[mask], 0.1)) / 255, np.mean(gray[mask] < 75), mag.mean() / 1020, np.quantile(mag, 0.9) / 1020, coherence, np.mean(cv2.Canny(gray.astype(np.uint8), 40, 100)[mask] > 0), ] return [float(v) for v in values] def evidence_masks(rgb, fields, policy): gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32) hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV) contrast = gray - cv2.GaussianBlur(gray, (0, 0), 0.35 / policy["mpp"]) white = (gray > 80) & (hsv[..., 1] < 100) & (contrast > 3) yellow = ( (hsv[..., 0] > 12) & (hsv[..., 0] < 40) & (hsv[..., 1] > 40) & (gray > 70) & (contrast > 2) ) size = max(3, int(0.25 / policy["mpp"])) vehicles = cv2.dilate( (fields["vehicle"] > 0.25).astype(np.uint8), np.ones((size, size), np.uint8) ) return white | yellow, (fields["alpha"] > 0.65) & (vehicles == 0) def linear_descriptor(poly, policy): d = rectangle(poly, policy["mpp"]) if ( policy["min_length"] <= d["length"] <= policy["max_length"] and policy["min_width"] <= d["width"] <= policy["max_width"] and d["length"] / max(d["width"], 1e-9) >= policy["min_aspect"] and d["fill"] >= policy["min_fill"] ): return d return None def pair_allowed(p, q, a, b, policy): if abs(a["axis"] @ b["axis"]) < np.cos(np.deg2rad(policy["max_pair_angle_deg"])): return False if max(a["width"], b["width"]) / min(a["width"], b["width"]) > policy["max_pair_width_ratio"]: return False normal = np.array([-a["axis"][1], a["axis"][0]]) lateral = abs((b["center"] - a["center"]) @ normal) * policy["mpp"] if lateral > policy["max_pair_lateral_fraction"] * min(a["width"], b["width"]): return False return p.distance(q) * policy["mpp"] <= policy["max_join_gap"] def supported_envelope(source, weak, physical, policy): # Convex-envelope intersection cannot extrapolate beyond original observations. proposed = source.minimum_rotated_rectangle.intersection(source.convex_hull) if proposed.geom_type != "Polygon" or proposed.area <= 0: return None, "non_polygon" desc = linear_descriptor(proposed, policy) if desc is None or source.area / proposed.area < policy["min_group_fill"]: return None, "geometry" mask = masks(proposed) original = np.zeros_like(mask) for p in [source] if source.geom_type == "Polygon" else source.geoms: original |= masks(p) added = mask & ~original if np.mean(physical[mask]) < policy["min_physical_valid"]: return None, "physical" if np.mean(weak[mask]) < policy["min_total_weak_paint"]: return None, "total_paint" if added.any() and np.mean(weak[added]) < policy["min_added_weak_paint"]: return None, "added_paint" return proposed, "supported" def assemble(candidates, rgb, fields, policy): out = [ dict(c, features=c["features"][:14] + texture(shape(c["geometry"]), rgb)) for c in candidates ] polys = [shape(c["geometry"]) for c in candidates] desc = [linear_descriptor(p, policy) for p in polys] parent = list(range(len(polys))) def find(i): while parent[i] != i: i = parent[i] return i for i in range(len(polys)): for j in range(i): if desc[i] and desc[j] and pair_allowed(polys[i], polys[j], desc[i], desc[j], policy): a, b = find(i), find(j) parent[max(a, b)] = min(a, b) groups = {} for i, d in enumerate(desc): if d: groups.setdefault(find(i), []).append(i) weak, physical = evidence_masks(rgb, fields, policy) audit = [] def append(poly, members, kind): if any(overlap(poly, shape(c["geometry"])) > 0.95 for c in out): return out.append( dict( id="assembled-" + str(len(out)), geometry=mapping(poly), properties=dict(kind=kind, parent_ids=[candidates[i]["id"] for i in members]), features=descriptors(poly, rgb, fields)[:14] + texture(poly, rgb), fixed_admitted=any(candidates[i]["fixed_admitted"] for i in members), ) ) for ids in groups.values(): if len(ids) > policy["max_group"]: audit.append(dict(parents=ids, verdict="group_limit")) continue union = unary_union([polys[i] for i in ids]) if len(ids) > 1: for p in [union] if union.geom_type == "Polygon" else union.geoms: if p.geom_type == "Polygon": append(p, ids, "exact_union") fitted, verdict = supported_envelope(union, weak, physical, policy) audit.append(dict(parents=ids, verdict=verdict)) if fitted is not None: append(fitted, ids, "supported_envelope") return out, audit def merged_count(candidates, reviewed): truth = [shape(o["geometry"]) for o in reviewed["objects"] if o["complete"]] return sum( sum(shape(c["geometry"]).intersection(t).area / max(t.area, 1e-9) >= 0.2 for t in truth) >= 2 for c in candidates ) def measured(candidates, reviewed): result = score(candidates, reviewed) result["merged"] = int(merged_count(candidates, reviewed)) return result def pooled(rows): result = aggregate(rows) result["merged"] = sum(r["merged"] for r in rows) return result def admitted(record, assembly, scorer, model=None, threshold=0): channel = "hard" if scorer == "fixed_admission" else "retained" cs = record["variants"][channel + "_" + assembly] if scorer == "fixed_admission": return [c for c in cs if c["fixed_admitted"]] count = 14 if scorer == "previous_shape_appearance" else MODEL_SIZES[scorer] ps = probability(np.array([c["features"][:count] for c in cs]), model) if cs else [] return [c for c, p in zip(cs, ps, strict=True) if p >= threshold] 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"] x, y = [], [] for a in train: cs = a["variants"]["retained_on"] for c, label in zip(cs, labels(cs, review[a["id"]]), 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 reviewed training examples") baselines = { arm: pooled([measured(admitted(a, arm, "fixed_admission"), review[a["id"]]) for a in val]) for arm in ["off", "on"] } models, choices = {}, [] for name, count in MODEL_SIZES.items(): model = fit_classifier(x[:, :count], y, 0.01, 500) arms = {} for arm in ["off", "on"]: rows = [] for threshold in thresholds: result = pooled( [ measured(admitted(a, arm, name, model, threshold), review[a["id"]]) for a in val ] ) rows.append(dict(threshold=threshold, **result)) feasible = [ v for v in rows if v["unsupported"] <= baselines[arm]["unsupported"] and v["merged"] <= baselines[arm]["merged"] ] selected = ( min(feasible, key=lambda v: (-v["found"], v["unsupported"], -v["threshold"])) if feasible else None ) arms[arm] = dict(selected=selected, grid=rows) if selected: choices.append(dict(scorer=name, assembly=arm, feature_count=count, **selected)) models[name] = dict(model=model, arms=arms) chosen = ( min( choices, key=lambda v: ( -v["found"], v["unsupported"], v["feature_count"], v["assembly"] != "off", ), ) if choices else None ) return dict( models=models, chosen=chosen, validation_fixed=baselines, training=dict(positive=int(sum(y == 1)), negative=int(sum(y == 0)), windows=len(train)), ) def propose(root): base_propose(root) original = json.loads((root / "candidates.json").read_text()) policy = json.loads((root / "assembly-policy.json").read_text()) out = [] for a in original["records"]: rgb = np.asarray(Image.open(root / "data" / (a["id"] + ".png")).convert("RGB")) z = dict(np.load(root / "data" / (a["id"] + ".npz"))) variants, audit = {}, {} for mode in ["hard", "retained"]: cs, log = assemble(a["variants"][mode], rgb, z, policy) variants[mode + "_off"] = cs[: len(a["variants"][mode])] variants[mode + "_on"] = cs audit[mode] = log out.append( dict( id=a["id"], street=a["street"], split=a["split"], variants=variants, assembly_audit=audit, ) ) save_new( root / "assembled-candidates.json", dict(**timestamp(), records=out, policy_sha256=sha(root / "assembly-policy.json")), ) print(json.dumps({k: sum(len(a["variants"][k]) for a in out) for k in out[0]["variants"]})) def train(root): records = json.loads((root / "assembled-candidates.json").read_text())["records"] review = json.loads((root / "review-frozen.json").read_text())["records"] usable = [a for a in records if a["split"] != "heldout"] result = fit_models( usable, {a["id"]: review[a["id"]] for a in usable}, [i / 20 for i in range(1, 20)] ) previous = json.loads(Path("/objectstudy/models-frozen.json").read_text())["models"][ "shape_appearance" ] result["previous"] = dict(model=previous["model"], threshold=previous["selected"]["threshold"]) result.update(timestamp()) names = [ "assembled-candidates.json", "review-frozen.json", "protocol.json", "assembly-policy.json", "input-hashes.json", "object_assembly_study.py", "object_proposal_study.py", "paint_observations.py", "paint_hypothesis_study.py", "paint_evidence_probe.py", "layer_common.py", "fit_scene.py", ] result["frozen_sha256"] = {name: sha(root / name) for name in names} save_new(root / "models-frozen.json", result) print(json.dumps({k: result[k] for k in ["chosen", "training", "validation_fixed"]})) def evaluate(root): frozen = json.loads((root / "models-frozen.json").read_text()) for name, digest in frozen["frozen_sha256"].items(): if sha(root / name) != digest: raise ValueError("Frozen dependency changed: " + name) for name, digest in json.loads((root / "input-hashes.json").read_text()).items(): if sha(root / name) != digest: raise ValueError("Frozen input changed: " + name) records = json.loads((root / "assembled-candidates.json").read_text())["records"] review = json.loads((root / "review-frozen.json").read_text())["records"] results = [] for a in records: sets = {} for arm in ["off", "on"]: sets["proposals_" + arm] = a["variants"]["retained_" + arm] sets["fixed_admission_" + arm] = admitted(a, arm, "fixed_admission") sets["previous_shape_appearance_" + arm] = admitted( a, arm, "previous_shape_appearance", **frozen["previous"] ) for name, info in frozen["models"].items(): selected = info["arms"][arm]["selected"] sets[name + "_" + arm] = admitted( a, arm, name, info["model"], selected["threshold"] if selected else 2 ) results.append( dict( id=a["id"], street=a["street"], split=a["split"], scores={k: measured(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 = { s: { k: pooled([a["scores"][k] for a in results if a["street"] == s]) for k in results[0]["scores"] } for s in sorted({a["street"] for a in results}) } control = { k: pooled([a["scores"][k] for a in results if a["split"] == "heldout"]) for k in results[0]["scores"] } save_new( root / "results.json", dict( **timestamp(), chosen=frozen["chosen"], streets=streets, control=control, windows=results, promotion=False, ), ) print( json.dumps( dict( control=control, streets={ k: v for k, v in streets.items() if k in ["pokrovka", "sadovaya-karetnaya"] }, ) ) ) if __name__ == "__main__": cv2.setNumThreads(3) {"propose": propose, "train": train, "evaluate": evaluate}[sys.argv[1]](Path(sys.argv[2]))