feat(semantics): version scene edits and refine paint geometry

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:42:55 +03:00
parent 7a3c3c00b3
commit b7b5ac9cf0
34 changed files with 3014 additions and 138 deletions
@@ -0,0 +1,281 @@
"""Conservative second-pass strip admission using frozen strict automatic seeds.
Seeds are machine output from the SAME observations, never manual geometry.
New candidates cannot become seeds. Existing primitives are retained verbatim.
"""
import copy
import math
import numpy as np
import paint_objects as po
from paint_geometry import digest
from shapely.geometry import LineString, mapping, shape
from shapely.ops import unary_union
def strip_contrast(parameters, rgb, matrix):
"""Measure paint against EACH lateral flank; a bright-region edge is insufficient.
All samples belong to the novel fitted part. Missing flank coverage abstains.
Coordinates follow the same pixel-centre affine as observation extraction.
"""
q = np.asarray(parameters["centerline"], dtype=float)
if q.shape != (2, 2):
return None
u = q[1] - q[0]
length = np.linalg.norm(u)
if length < 0.35:
return None
u /= length
n = np.array([-u[1], u[0]])
half = float(parameters["width_m"]) / 2
a, b, d, e, x0, y0 = matrix
inverse = np.linalg.inv([[a, b], [d, e]])
corners = np.array([point + sign * (half + 0.18) * n for point in q for sign in [-1, 1]])
uv = (corners - [x0, y0]) @ inverse.T
left, top = np.floor(uv.min(0)).astype(int)
right, bottom = np.ceil(uv.max(0)).astype(int)
if left < 0 or top < 0 or right > rgb.shape[1] or bottom > rgb.shape[0]:
return None
yy, xx = np.mgrid[top:bottom, left:right]
X = a * (xx + 0.5) + b * (yy + 0.5) + x0 - q[0, 0]
Y = d * (xx + 0.5) + e * (yy + 0.5) + y0 - q[0, 1]
along = X * u[0] + Y * u[1]
across = X * n[0] + Y * n[1]
interior = (along > 0.05) & (along < length - 0.05)
masks = [
interior & (np.abs(across) < half),
interior & (across > half + 0.06) & (across < half + 0.18),
interior & (across < -half - 0.06) & (across > -half - 0.18),
]
if any(mask.sum() < 4 for mask in masks):
return None
lum = rgb[top:bottom, left:right].astype(float).mean(axis=2) / 255
values = [float(np.median(lum[mask])) for mask in masks]
contrasts = [values[0] - v for v in values[1:]]
return dict(
contrast=min(contrasts),
flank_contrasts=contrasts,
sample_counts=[int(m.sum()) for m in masks],
)
def line_relation(candidate, seed):
a = np.asarray(candidate["parameters"]["centerline"], dtype=float)
b = np.asarray(seed["parameters"]["centerline"], dtype=float)
if len(a) != 2 or len(b) != 2:
return False
u = a[1] - a[0]
v = b[1] - b[0]
length = np.linalg.norm(u)
other = np.linalg.norm(v)
if min(length, other) < 1e-6:
return False
u /= length
v /= other
if abs(u @ v) < math.cos(math.radians(5)):
return False
width = candidate["parameters"]["width_m"]
sw = seed["parameters"]["width_m"]
if not 0.75 <= width / sw <= 1.333:
return False
n = np.array([-v[1], v[0]])
if np.max(np.abs((a - b[0]) @ n)) > max(0.08, 0.5 * sw):
return False
# Classification may continue only the same observed paint, not a nearby
# parallel stripe or a chain across an unobserved interval.
observed = shape(candidate["observation_geometry"])
seed_observed = shape(seed["observation_geometry"])
if observed.intersection(seed_observed).area <= 1e-6:
return False
projected = (a - b[0]) @ v
return projected.min() < -0.1 or projected.max() > other + 0.1
def crosswalk_support(candidate, groups):
q = np.asarray(candidate["parameters"]["centerline"], dtype=float)
if len(q) != 2:
return []
length = np.linalg.norm(q[1] - q[0])
width = candidate["parameters"]["width_m"]
if length < 1e-6:
return []
direction = (q[1] - q[0]) / length
center = q.mean(0)
for g in groups:
bars = g["bars"]
u = g["direction"]
n = g["normal"]
offsets = g["offsets"]
step = g["step_m"]
if abs(direction @ u) < math.cos(math.radians(8)):
continue
if not 0.8 < length / np.median([b[3] for b in bars]) < 1.25:
continue
if not 0.7 < width / np.median([b[0]["parameters"]["width_m"] for b in bars]) < 1.43:
continue
if abs(center @ u - np.median([b[1] @ u for b in bars])) >= 0.5:
continue
across = center @ n
if not offsets.min() - step * 1.18 <= across <= offsets.max() + step * 1.18:
continue
if abs((across - offsets[0]) / step - round((across - offsets[0]) / step)) > 0.18:
continue
return [b[0]["id"] for b in bars]
return []
def contextual_additions(
strict_objects, candidates, *, contrast_fn, experimental_continuations=False
):
"""Return additions + decisions. Does not edit, replace or reclassify seeds.
Both input lists are automatically normalized proposals with RGB/surface
checks already performed. The qualified default only recovers observed
crosswalk bars. Continuation is an explicit research branch: geometric/RGB
checks cannot yet distinguish road paint from bright curbs reliably.
"""
seeds = [
o
for o in strict_objects
if o["placement_status"] == "placed" and o["representation"] == "strip"
]
catalog = [
shape(o["geometry"])
for o in strict_objects
if o["placement_status"] == "placed" and o["representation"] == "catalog"
]
groups = po.crosswalk_groups(seeds)
seed_by_id = {o["id"]: o for o in seeds}
occupied = unary_union(
[shape(o["geometry"]) for o in strict_objects if o["placement_status"] == "placed"]
)
additions = []
decisions = []
eligible = [
o
for o in candidates
if o["placement_status"] == "placed" and o["representation"] == "strip"
]
direct = {o["id"]: [s["id"] for s in seeds if line_relation(o, s)] for o in eligible}
junction_anchors = [o for o in eligible if direct[o["id"]] and o.get("junction_components")]
for original in sorted(candidates, key=lambda o: (-o["fit"]["score"], o["id"])):
if original["placement_status"] != "placed" or original["representation"] != "strip":
continue
q = np.asarray(original["parameters"]["centerline"], dtype=float)
if len(q) != 2:
continue
g = shape(original["geometry"])
if g.difference(occupied.buffer(0.04)).area < 0.05 * g.area:
continue
crossing = crosswalk_support(original, groups)
group_id = None
if crossing:
group_ids = {seed_by_id[i].get("group_id") for i in crossing}
if len(group_ids) != 1 or None in group_ids:
decisions.append(
dict(
id=original["id"], accepted=False, reason="ambiguous-strict-crosswalk-group"
)
)
continue
group_id = next(iter(group_ids))
supporting = direct[original["id"]]
junction = []
if not crossing and not supporting and original.get("junction_components"):
components = set(original["junction_components"])
for anchor in junction_anchors:
if (
components.intersection(anchor["junction_components"])
and shape(anchor["geometry"]).distance(g) <= 0.08
):
junction.extend(direct[anchor["id"]])
reason = (
"crosswalk-group"
if crossing
else "observed-continuation"
if supporting
else "anchored-junction"
if junction
else None
)
if reason is not None and reason != "crosswalk-group" and not experimental_continuations:
decisions.append(
dict(id=original["id"], accepted=False, reason="unqualified-continuation-disabled")
)
continue
if reason is None:
decisions.append(
dict(id=original["id"], accepted=False, reason="no-independent-strict-context")
)
continue
if any(g.intersection(c).area > 0.05 * g.area for c in catalog):
decisions.append(dict(id=original["id"], accepted=False, reason="catalog-conflict"))
continue
# Keep existing seed geometry exactly. Only the observed, non-overlapping
# part of a proposed continuation is added; never extend across a gap.
remaining = LineString(q).difference(occupied.buffer(0.02))
segments = (
[remaining]
if remaining.geom_type == "LineString"
else list(getattr(remaining, "geoms", []))
)
accepted = []
for segment in segments:
if segment.geom_type != "LineString" or segment.length < 0.35:
continue
params = dict(
centerline=[list(segment.coords[0]), list(segment.coords[-1])],
width_m=original["parameters"]["width_m"],
)
fitted = po.strip_geometry(params["centerline"], params["width_m"])
if fitted.difference(g.buffer(1e-8)).area > 1e-6:
continue
support = shape(original["observation_geometry"]).intersection(fitted.buffer(0.06))
if support.is_empty:
continue
metrics = po.agreement(support, fitted, 0.06)
immediate = support.intersection(fitted).area / fitted.area
if (
metrics["score"] < 0.78
or metrics["precision"] < 0.85
or metrics["recall"] < 0.85
or immediate < 0.70
):
continue
rgb = contrast_fn(original, fitted)
if rgb is None or rgb["contrast"] < po.Policy().min_luminance_contrast:
continue
o = copy.deepcopy(original)
for key in ("group_id", "observed_bar_count", "crosswalk_parameters"):
o.pop(key, None)
if crossing:
o["group_id"] = group_id
o["luminance_contrast"] = rgb["contrast"]
o["novel_rgb_evidence"] = rgb
o["parameters"] = params
o["geometry"] = mapping(fitted)
o["observation_geometry"] = mapping(support)
o["fit"] = metrics
o["novel_unbuffered_support"] = immediate
o["context_admission"] = dict(
method=reason,
seed_ids=sorted(set(crossing or supporting or junction)),
candidate_id=original["id"],
seeds_frozen=True,
)
o["id"] = (
"object-"
+ digest(["contextual-strip-v1", original["id"], params, o["context_admission"]])[
:24
]
)
o["kind"] = "crosswalk_bar" if crossing else "linear_marking"
additions.append(o)
accepted.append(o["id"])
occupied = unary_union([occupied, fitted])
decisions.append(
dict(id=original["id"], accepted=bool(accepted), reason=reason, additions=accepted)
)
return additions, decisions
+65 -14
View File
@@ -20,6 +20,10 @@ MAX_EDITOR_RINGS = 128
MAX_EDITOR_WORK = 2_000_000
class ComponentRefusal(ValueError):
"""Expected local geometry/support failure; never a sampler/source exception."""
def digest(value):
return hashlib.sha256(
json.dumps(value, sort_keys=True, allow_nan=False, separators=(",", ":")).encode()
@@ -114,15 +118,7 @@ def vectorize(labels, *, pixel_to_scene, source_id):
return result
def editor_features(proposal, *, height_at, height_source):
"""Validate and lift exact components, WITHOUT inferring a subtype/template/group.
Caller supplies observed surface heights at the returned XY vertices. There
is no flat/nearest-height fallback. This creates features only: the caller
must independently verify scene identity/admission before any map import.
"""
from k1link.simulation.ai_polygon.semantic_edits import validate_holes, validate_path
def _editor_preflight(proposal, height_source):
payload = {k: v for k, v in proposal.items() if k != "proposal_sha256"}
if proposal.get("schema_version") != SCHEMA or digest(payload) != proposal.get(
"proposal_sha256"
@@ -136,6 +132,11 @@ def editor_features(proposal, *, height_at, height_source):
vertices = 0
if len(proposal["features"]) > 20000:
raise ValueError("Editor feature budget exceeded")
identifiers = [f.get("id") for f in proposal["features"]]
if any(not isinstance(i, str) or not i for i in identifiers) or len(
set(identifiers)
) != len(identifiers):
raise ValueError("Missing or duplicate component identity")
for raw in proposal["features"]:
geo = raw["geometry"]
if geo["type"] != "Polygon":
@@ -150,23 +151,43 @@ def editor_features(proposal, *, height_at, height_source):
work += edges * edges
if vertices > 300000 or work > MAX_EDITOR_WORK:
raise ValueError("Editor validation work budget exceeded; no lossy fallback")
def editor_features(proposal, *, height_at, height_source):
"""Strict all-or-nothing lift, WITHOUT inferring a subtype/template/group.
Caller supplies observed surface heights at the returned XY vertices. There
is no flat/nearest-height fallback. This creates features only: the caller
must independently verify scene identity/admission before any map import.
"""
from k1link.simulation.ai_polygon.semantic_edits import validate_holes, validate_path
_editor_preflight(proposal, height_source)
result = []
for raw in proposal["features"]:
feature = copy.deepcopy(raw)
geometry = feature["geometry"]
if geometry["type"] != "Polygon" or not shape(geometry).is_valid:
raise ValueError("Unsupported editor geometry")
raise ComponentRefusal("Unsupported editor geometry")
rings = []
for ring in geometry["coordinates"]:
xy = np.asarray(ring[:-1], dtype=float)
z = np.asarray(height_at(xy.copy()), dtype=float)
if z.shape != (len(xy),) or not np.isfinite(z).all():
raise ValueError("Missing observed height support")
if z.shape != (len(xy),):
raise ValueError("Height callback returned an invalid shape")
if not np.isfinite(z).all():
raise ComponentRefusal("Missing observed height support")
points = np.column_stack([xy, z]).tolist()
points.append(points[0][:])
validate_path(points, True)
try:
validate_path(points, True)
except ValueError as error:
raise ComponentRefusal(str(error)) from error
rings.append(points)
validate_holes(rings)
try:
validate_holes(rings)
except ValueError as error:
raise ComponentRefusal(str(error)) from error
feature["geometry"]["coordinates"] = rings
feature["properties"].update({
"class": "road_marking", "authority": "observation-only",
@@ -176,3 +197,33 @@ def editor_features(proposal, *, height_at, height_source):
})
result.append(feature)
return result
def editor_components(proposal, *, height_at, height_source):
"""Explicit partial lift; every original component is admitted OR deferred.
Integrity and total resource bounds remain atomic, before any sampling.
A component-level geometry/height refusal keeps the exact original 2-D
feature and reason. No vertex removal, repair, height inference or semantic
class inference occurs. Admission is NOT confirmation of road paint.
The caller must retain/display deferred data alongside admitted features.
"""
_editor_preflight(proposal, height_source)
admitted, deferred = [], []
for raw in proposal["features"]:
single = {k: v for k, v in proposal.items() if k != "proposal_sha256"}
single["features"] = [raw]
single["proposal_sha256"] = digest(single)
try:
admitted.extend(editor_features(
single, height_at=height_at, height_source=height_source
))
except ComponentRefusal as error:
deferred.append(dict(feature=copy.deepcopy(raw), reason=str(error)))
return dict(
schema_version="missioncore.paint-editor-admission/v1",
proposal_sha256=proposal["proposal_sha256"],
source_sha256=proposal["source_sha256"], height_source=height_source,
features=admitted, deferred=deferred,
complete=not deferred, review_status="unreviewed",
)
@@ -0,0 +1,855 @@
"""Bounded paint observations -> editable primitives and catalog instances.
No map, annotation, street name, or world position is a recognition feature.
Fit scores measure agreement, not calibrated semantic confidence. Unsupported
observations stay unresolved; raw contours are never an output fallback.
"""
import json
import math
from dataclasses import asdict, dataclass
import numpy as np
from paint_geometry import digest, vectorize
from scipy.ndimage import binary_closing
from scipy.optimize import minimize
from shapely import affinity, intersects_xy
from shapely.geometry import LineString, Polygon, box, mapping, shape
from shapely.ops import transform, unary_union
from shapely.strtree import STRtree
@dataclass(frozen=True)
class Policy:
min_area_m2: float = 0.035
min_length_m: float = 0.35
min_width_m: float = 0.06
max_strip_width_m: float = 1.0
rectangle_fill: float = 0.72
shape_tolerance_m: float = 0.06
min_symbol_score: float = 0.68
min_symbol_precision: float = 0.65
min_symbol_recall: float = 0.65
min_class_margin: float = 0.035
min_luminance_contrast: float = 0.025
max_candidates: int = 512
max_symbol_fits: int = 48
max_strip_hole_fraction: float = 0.10
min_unanchored_wear_length_m: float = 3.0
def parts(geometry):
return [geometry] if geometry.geom_type == "Polygon" else list(geometry.geoms)
def rectangle(geometry):
q = np.asarray(geometry.minimum_rotated_rectangle.exterior.coords)[:4, :2]
edges = np.roll(q, -1, axis=0) - q
lengths = np.linalg.norm(edges, axis=1)
i = int(np.argmax(lengths))
u = edges[i] / lengths[i]
return q.mean(0), float(math.atan2(u[1], u[0])), float(max(lengths)), float(min(lengths))
def strip_geometry(centerline, width):
return LineString(centerline).buffer(width / 2, cap_style=2, join_style=2)
def catalog_geometry(template, center, angle, scale):
g = unary_union([Polygon(p[0], p[1:]) for p in template["polygons"]])
lo, bottom, hi, top = g.bounds
g = affinity.translate(g, -(lo + hi) / 2, -(bottom + top) / 2)
g = affinity.scale(g, xfact=scale, yfact=scale, origin=(0, 0))
g = affinity.rotate(g, angle, origin=(0, 0), use_radians=True)
return affinity.translate(g, *center)
def reconstruct(obj, catalog):
"""Regenerate product geometry from compact parameters, never raw vertices."""
p = obj["parameters"]
if obj["representation"] == "strip":
return strip_geometry(p["centerline"], p["width_m"])
template = next(t for t in catalog["templates"] if t["id"] == p["template_id"])
return catalog_geometry(template, p["center"], p["angle_radians"], p["scale"])
def agreement(observed, fitted, tolerance, *, observed_buffer=None):
# Pure geometry reuse: identical observed polygon and tolerance throughout a fit.
buffered = observed.buffer(tolerance) if observed_buffer is None else observed_buffer
precision = fitted.intersection(buffered).area / max(fitted.area, 1e-9)
recall = observed.intersection(fitted.buffer(tolerance)).area / max(observed.area, 1e-9)
overlap = observed.intersection(fitted).area / max(observed.union(fitted).area, 1e-9)
f1 = 2 * precision * recall / max(precision + recall, 1e-9)
return dict(precision=precision, recall=recall, overlap=overlap, score=0.6 * f1 + 0.4 * overlap)
def contrast(geometry, rgb, matrix):
"""Local RGB evidence, not a claim that all bright rectangles are road paint."""
a, b, d, e, x0, y0 = matrix
inverse = np.linalg.inv([[a, b], [d, e]])
q = np.asarray(geometry.envelope.exterior.coords)[:, :2]
uv = (q - [x0, y0]) @ inverse.T
padding = int(math.ceil(0.18 / min(np.hypot(a, d), np.hypot(b, e)))) + 2
left, top = np.maximum(np.floor(uv.min(0)).astype(int) - padding, 0)
right, bottom = np.minimum(np.ceil(uv.max(0)).astype(int) + padding, rgb.shape[1::-1])
if right <= left or bottom <= top:
return None
yy, xx = np.mgrid[top:bottom, left:right]
X = a * (xx + 0.5) + b * (yy + 0.5) + x0
Y = d * (xx + 0.5) + e * (yy + 0.5) + y0
inside = intersects_xy(geometry, X, Y)
outside = intersects_xy(geometry.buffer(0.18).difference(geometry.buffer(0.06)), X, Y)
if inside.sum() < 4 or outside.sum() < 4:
return None
lum = rgb[top:bottom, left:right].astype(float).mean(axis=2) / 255
return float(np.median(lum[inside]) - np.median(lum[outside]))
def fit_strip(p, policy):
center, angle, length, width = rectangle(p)
if length < policy.min_length_m or width < policy.min_width_m:
return None
# Wear is a shape hypothesis only: retain the original observation for all
# agreement checks. Large/elongated negative spaces remain real structure.
shell = Polygon(p.exterior)
if p.interiors and (
(shell.area - p.area) / max(shell.area, 1e-9) > policy.max_strip_hole_fraction
or any(rectangle(Polygon(h))[2] > width for h in p.interiors)
):
return None
u = np.array([math.cos(angle), math.sin(angle)])
if (
width <= policy.max_strip_width_m
and length / width >= 3
and p.area / (length * width) >= policy.rectangle_fill
):
line = [center - u * length / 2, center + u * length / 2]
return dict(centerline=np.asarray(line).tolist(), width_m=width)
# Reuse the existing centreline/cross-section approach. Explicit refusal
# replaces its historical raw-polygon fallback; real bends need few knots.
if length < 1.5 or length / max(width, 0.01) < 3:
return None
n = np.array([-u[1], u[0]])
stations = np.linspace(
-length / 2 + 0.03, length / 2 - 0.03, max(8, min(256, int(length / 0.10)))
)
centers, widths = [], []
for t in stations:
cross = shell.intersection(
LineString(center + t * u + np.array([-width - 1, width + 1])[:, None] * n)
)
if cross.geom_type != "LineString" or cross.length < 0.025:
continue
centers.append(cross.interpolate(0.5, normalized=True).coords[0][:2])
widths.append(cross.length)
if len(centers) < max(8, 0.9 * len(stations)):
return None
points = np.asarray(centers)
tangent = np.gradient(points, axis=0)
tangent /= np.maximum(np.linalg.norm(tangent, axis=1)[:, None], 1e-9)
widths = np.asarray(widths) * np.abs(tangent @ u)
w = float(np.median(widths))
if not policy.min_width_m <= w <= 0.65:
return None
variable_width = np.ptp(np.quantile(widths, [0.1, 0.9])) > 0.5 * w
# Prefer a rectangle when the observed strip supports one. Boundary nicks
# must not force needless bends into an otherwise straight crossing bar.
offset = float(np.median((points - center) @ n))
straight = [center + offset * n - u * length / 2, center + offset * n + u * length / 2]
rectangle_fit = strip_geometry(straight, w)
if (
(not variable_width or length >= policy.min_unanchored_wear_length_m)
and agreement(p, rectangle_fit, policy.shape_tolerance_m)["score"] >= 0.78
and p.hausdorff_distance(rectangle_fit) <= 0.25
):
return dict(centerline=np.asarray(straight).tolist(), width_m=w)
# A worn straight stripe can have variable cross-sections while its full
# rectangular explanation is strong. Width consistency constrains the bent
# fallback, not the already verified straight candidate above.
if variable_width:
return None
line = LineString(points).simplify(policy.shape_tolerance_m)
if not line.is_simple or len(line.coords) > 12:
return None
g = strip_geometry(list(line.coords), w)
if agreement(p, g, policy.shape_tolerance_m)["score"] < 0.78 or p.hausdorff_distance(g) > 0.25:
return None
return dict(centerline=[list(q) for q in line.coords], width_m=w)
def fit_junction_strips(p, policy):
"""Explain thin, near-orthogonal junctions with a few observed rectangles.
Long boundary directions propose axes, not coordinates or road rules.
Require local support for every arm AND agreement of the complete union.
A shaft alone cannot explain a missing arrow head or other residual shape.
"""
if p.area < .3 or len(p.interiors) > 8:
return []
_, _, length, width = rectangle(p)
if width < 1 or p.area / max(length * width, 1e-9) > .6:
return []
q = np.asarray(p.simplify(.08, preserve_topology=True).exterior.coords)[:, :2]
edges = np.diff(q, axis=0)
modes = []
for v in sorted(edges, key=lambda v: -float(np.linalg.norm(v))):
length = float(np.linalg.norm(v))
if length < 1.5:
continue
u = v / length
if not any(abs(u @ old) > math.cos(math.radians(10)) for old in modes):
modes.append(u)
if len(modes) == 4:
break
pairs = [(u, v) for i, u in enumerate(modes) for v in modes[i+1:]
if abs(u @ v) < math.sin(math.radians(10))]
if not pairs:
return []
for axes in pairs:
proposals = []
directions = []
for axis_index, u in enumerate(axes):
n = np.array([-u[1], u[0]])
coords = np.asarray(p.exterior.coords)[:, :2]
along, across = coords @ u, coords @ n
low, high = float(along.min()), float(along.max())
count = max(20, min(512, int((high-low)/.08)))
step = (high-low) / count
samples = []
for t in np.linspace(low+step/2, high-step/2, count):
cross = p.intersection(LineString([u*t+n*(across.min()-1),
u*t+n*(across.max()+1)]))
segments = ([cross] if cross.geom_type == "LineString"
else getattr(cross, "geoms", []))
for segment in segments:
if (segment.geom_type != "LineString"
or not policy.min_width_m <= segment.length <= .65):
continue
mid = np.asarray(segment.interpolate(.5, normalized=True).coords[0])[:2]
samples.append((float(mid @ n), t, segment.length))
samples.sort()
clusters = []
for sample in samples:
if not clusters or sample[0]-clusters[-1][-1][0] > .10:
clusters.append([])
clusters[-1].append(sample)
for cluster in clusters:
c = np.asarray(cluster)
if len(c) < 16:
continue
offset, width = float(np.median(c[:, 0])), float(np.median(c[:, 2]))
if np.ptp(np.quantile(c[:, 0], [.1,.9])) > width/2:
continue
ordered = c[np.argsort(c[:, 1])]
# A wide junction may omit a few cross-sections, not a real gap.
splits = np.where(np.diff(ordered[:, 1]) > max(.25, 2*width))[0]+1
for run in np.split(ordered, splits):
lo, hi = float(run[:,1].min()-step/2), float(run[:,1].max()+step/2)
if len(run) < 16 or hi-lo < 1.5 or hi-lo < 4*width:
continue
line = [u*lo+n*offset, u*hi+n*offset]
fitted = strip_geometry(line,width)
holes = [Polygon(h) for h in p.interiors if Polygon(h).intersects(fitted)]
if (any(rectangle(h)[2] > width for h in holes)
or sum(h.intersection(fitted).area for h in holes)
> policy.max_strip_hole_fraction * fitted.area):
continue
# Every interior longitudinal interval needs observed paint.
# A wide junction has support; a true gap stays an interval
# gap even when the enclosing component is connected elsewhere.
intervals = []
for piece in parts(p.intersection(fitted)):
if piece.geom_type == "Polygon" and piece.area > 0:
projections = np.asarray(piece.exterior.coords)[:, :2] @ u
intervals.append((float(projections.min()),float(projections.max())))
end = lo+step
continuous = True
for begin, finish in sorted(intervals):
if finish < end:
continue
if begin > end+1e-6:
continuous = False
break
end = max(end,finish)
if not continuous or end < hi-step:
continue
if fitted.intersection(p).area/fitted.area < .70:
continue
local = p.intersection(fitted.buffer(policy.shape_tolerance_m))
if agreement(local,fitted,policy.shape_tolerance_m)["score"] < .78:
continue
proposals.append(dict(centerline=np.asarray(line).tolist(),width_m=width))
directions.append(axis_index)
if not 2 <= len(proposals) <= 4 or len(set(directions)) != 2:
continue
shapes = [strip_geometry(x["centerline"],x["width_m"]) for x in proposals]
fitted = unary_union(shapes)
if not fitted.is_valid or not all(any(i != j and a.intersects(b.buffer(.08))
for j,b in enumerate(shapes)) for i,a in enumerate(shapes)):
continue
metrics = agreement(p,fitted,policy.shape_tolerance_m)
if (metrics["score"] >= .78 and metrics["recall"] >= .90
and metrics["precision"] >= .85 and p.hausdorff_distance(fitted) <= .25):
return proposals
return []
def fit_strips(p, policy):
params = fit_strip(p, policy)
return [params] if params is not None else fit_junction_strips(p, policy)
def fit_symbol(p, templates, policy, budget):
center, angle, length, width = rectangle(p)
if not (0.6 < length < 9 and 0.25 < width < 4 and 0.07 < p.area / (length * width) < 0.8):
return None, "not-symbol-shaped"
observed_buffer = p.buffer(policy.shape_tolerance_m)
def metrics_for(g):
return agreement(p, g, policy.shape_tolerance_m, observed_buffer=observed_buffer)
hypotheses = []
for template in templates:
base = catalog_geometry(template, [0, 0], 0, 1)
_, _, L, W = rectangle(base)
if not 0.65 < (length / width) / (L / W) < 1.5:
continue
scale = math.sqrt(length * width / (L * W))
for flip in (0, math.pi):
x0 = [center[0], center[1], angle + flip, scale]
g = catalog_geometry(template, x0[:2], x0[2], x0[3])
score = metrics_for(g)["score"]
hypotheses.append((score, template, x0))
# Bound optimization work per frame and per object, including bad inputs.
fits = []
for initial, template, x0 in sorted(hypotheses, key=lambda h: -h[0])[:4]:
if initial < 0.35:
continue
if budget[0] >= policy.max_symbol_fits:
return None, "symbol-fit-budget"
budget[0] += 1
bounds = [
(x0[0] - 0.25, x0[0] + 0.25),
(x0[1] - 0.25, x0[1] + 0.25),
(x0[2] - 0.20, x0[2] + 0.20),
(x0[3] * 0.8, x0[3] * 1.2),
]
def objective(x, template=template):
return 1 - metrics_for(catalog_geometry(template, x[:2], x[2], x[3]))["score"]
result = minimize(
objective,
x0,
method="Powell",
bounds=bounds,
options=dict(maxiter=12, maxfev=240, xtol=0.002, ftol=0.002),
)
# The initial candidate remains admissible when the bounded optimizer
# terminates early; the final measured evidence gates still apply.
x = result.x if result.fun < objective(x0) else x0
g = catalog_geometry(template, x[:2], x[2], x[3])
metrics = metrics_for(g)
fits.append((metrics["score"], template, list(x), metrics))
fits.sort(key=lambda f: -f[0])
if not fits:
return None, "no-template-supported"
_, template, x, metrics = fits[0]
runner = next((f[0] for f in fits[1:] if f[1]["id"] != template["id"]), 0)
if (
metrics["score"] < policy.min_symbol_score
or metrics["precision"] < policy.min_symbol_precision
or metrics["recall"] < policy.min_symbol_recall
):
return None, "insufficient-template-support"
if metrics["score"] - runner < policy.min_class_margin:
return None, "ambiguous-template-class"
g = catalog_geometry(template, x[:2], x[2], x[3])
holes = unary_union([Polygon(h) for part in parts(g) for h in part.interiors])
if not holes.is_empty and holes.intersection(p).area / max(holes.area, 1e-9) > 0.25:
return None, "template-negative-space-conflict"
params = dict(template_id=template["id"], center=x[:2], angle_radians=x[2], scale=x[3])
return (params, metrics), None
def arbitrate_symbol(observed, fitted, policy, *, center, angle, rgb, pixel_to_scene):
"""Compare on identical evidence; every local template part needs actual paint.
The 3x3 partition lives in the fitted template frame, never scene coordinates.
Local precision permits at most half a native pixel diagonal of uncertainty.
Each part also needs an unbuffered witness, so that uncertainty cannot conceal
a wholly absent small arrowhead. Existing global tolerance remains unchanged.
No per-class, per-scale, per-location, or learned acceptance threshold is used.
"""
local = affinity.rotate(
affinity.translate(fitted, -center[0], -center[1]),
-angle,
origin=(0, 0),
use_radians=True,
)
xs = np.linspace(local.bounds[0], local.bounds[2], 4)
ys = np.linspace(local.bounds[1], local.bounds[3], 4)
a, b, d, e, _, _ = pixel_to_scene
pixel_radius = 0.5 * max(np.hypot(a + b, d + e), np.hypot(a - b, d - e))
local_tolerance = min(policy.shape_tolerance_m, pixel_radius)
# Intersect in the normalized frame: rotating clipped fragments back into
# world space can create degenerate hole/shell contacts through roundoff.
local_observed = affinity.rotate(
affinity.translate(observed, -center[0], -center[1]),
-angle, origin=(0, 0), use_radians=True,
)
supported = local_observed.buffer(local_tolerance)
support = []
for iy in range(3):
for ix in range(3):
piece = local.intersection(box(xs[ix], ys[iy], xs[ix + 1], ys[iy + 1]))
if piece.area <= 1e-12:
continue
support.append(
dict(cell=[ix, iy], area_m2=piece.area,
precision=piece.intersection(supported).area / piece.area,
unbuffered_precision=piece.intersection(local_observed).area / piece.area)
)
strips = []
for component in parts(observed):
params = fit_strip(component, policy) if component.area >= policy.min_area_m2 else None
if params is None:
continue
g = strip_geometry(params["centerline"], params["width_m"])
delta = contrast(g, rgb, pixel_to_scene)
if delta is not None and delta >= policy.min_luminance_contrast:
strips.append(g)
symbol_score = agreement(observed, fitted, policy.shape_tolerance_m)["score"]
competitor = (
agreement(observed, unary_union(strips), policy.shape_tolerance_m) if strips else None
)
audit = dict(
template_partition="3x3-in-template-frame",
local_support_buffer_m=local_tolerance,
unbuffered_witness_required=True,
min_required_precision=policy.min_symbol_precision,
parts=support,
symbol_score=symbol_score,
strip_competitor=competitor,
min_required_margin=policy.min_class_margin,
)
if not support or any(
p["precision"] < policy.min_symbol_precision or p["unbuffered_precision"] <= 1e-12
for p in support
):
return audit, "unsupported-template-part"
if competitor is not None and symbol_score - competitor["score"] < policy.min_class_margin:
return audit, "strip-competitor-not-beaten"
return audit, None
def crosswalk_groups(objects):
"""Deterministic groups of independent, parallel observed bars.
Compare direction/length against an anchor, not a transitive angle chain.
Overlapping windows of one bar cannot supply independent votes.
"""
bars = []
for obj in sorted(objects, key=lambda o: o["id"]):
if obj["representation"] != "strip" or len(obj["parameters"]["centerline"]) != 2:
continue
p = obj["parameters"]
q = np.asarray(p["centerline"])
length = np.linalg.norm(q[1] - q[0])
if 0.28 <= p["width_m"] <= 1 and 1.5 <= length <= 8:
bars.append((obj, q.mean(0), (q[1] - q[0]) / length, length))
remaining = set(range(len(bars)))
groups = []
while remaining:
seed = min(remaining)
remaining.remove(seed)
first, center, u, length = bars[seed]
n = np.array([-u[1], u[0]])
aligned = [seed] + [j for j in sorted(remaining) if
abs(u @ bars[j][2]) > math.cos(math.radians(8))
and abs((bars[j][1] - center) @ u) < 0.5
and 0.8 < bars[j][3] / length < 1.25
and 0.7 < bars[j][0]["parameters"]["width_m"] / first["parameters"]["width_m"] < 1.43]
aligned.sort(key=lambda j: float(bars[j][1] @ n))
clusters, current = [], []
for j in aligned:
if current and float((bars[j][1] - bars[current[-1]][1]) @ n) > 2 + 1e-6:
clusters.append(current)
current = []
# Duplicate support or nearly coincident bars never count twice.
if current and (float((bars[j][1] - bars[current[-1]][1]) @ n) <= .45
or any(set(bars[j][0]["observation_ids"]) & set(bars[i][0]["observation_ids"])
for i in current)):
continue
current.append(j)
if current:
clusters.append(current)
for cluster in clusters:
if len(cluster) < 3:
continue
offsets = np.array([bars[j][1] @ n for j in cluster])
gaps = np.diff(offsets)
step = float(np.median(gaps[gaps <= np.median(gaps)]))
multiples = np.maximum(1, np.rint(gaps / step))
if (multiples > 2).any() or (np.abs(gaps - multiples * step) > .18 * step).any():
continue
remaining.difference_update(cluster)
groups.append(dict(bars=[bars[j] for j in cluster], direction=u,
normal=n, step_m=step, offsets=offsets))
return groups
def group_crosswalks(objects):
"""Classify actual bars after reconciliation; no fixed six-bar template."""
for obj in objects:
for key in ("group_id", "observed_bar_count", "crosswalk_parameters"):
obj.pop(key, None)
if obj["kind"] == "crosswalk_bar":
obj["kind"] = "linear_marking"
for group in crosswalk_groups(objects):
bars = group["bars"]
gid = "crossing-" + digest(sorted(b[0]["id"] for b in bars))[:20]
parameters = dict(direction=group["direction"].tolist(), step_m=group["step_m"],
median_width_m=float(np.median(
[b[0]["parameters"]["width_m"] for b in bars])),
median_length_m=float(np.median([b[3] for b in bars])))
for obj, *_ in bars:
obj.update(kind="crosswalk_bar", group_id=gid, observed_bar_count=len(bars),
crosswalk_parameters=parameters)
def recover_crosswalks(objects, observations, *, rgb, pixel_to_scene, policy):
"""Recheck rejected observations in an independently supported group frame.
No synthetic slots: a candidate needs its own area, full observed extent,
width, bounded holes, whole-shape agreement and RGB contrast. Recovered
candidates do not seed further recovery in this pass.
"""
groups = crosswalk_groups(objects)
used = {i for o in objects for i in o["observation_ids"]}
recovered = []
for feature in sorted(observations, key=lambda f: f["id"]):
if feature["id"] in used:
continue
p = shape(feature["geometry"])
if p.area < policy.min_area_m2:
continue
for group in groups:
u, n, bars = group["direction"], group["normal"], group["bars"]
q = np.asarray(p.exterior.coords)[:, :2]
along, across = q @ u, q @ n
lo, hi = float(along.min()), float(along.max())
mid = float((across.min() + across.max()) / 2)
length = hi - lo
width = float(np.median([b[0]["parameters"]["width_m"] for b in bars]))
reference_length = float(np.median([b[3] for b in bars]))
offsets, step = group["offsets"], group["step_m"]
# Only observed intervals near the demonstrated sequence, never
# arbitrary continuation or a tiny spot promoted to a full bar.
if not (offsets.min() - step * 1.18 <= mid <= offsets.max() + step * 1.18
and .8 < length / reference_length < 1.25
and .7 < p.area / max(length * width, 1e-9) < 1.43
and np.min(np.abs(offsets - mid)) > .45
and abs((mid - offsets[0]) / step - round((mid - offsets[0]) / step)) <= .18
and abs((lo + hi) / 2 - np.median([b[1] @ u for b in bars])) < .5):
continue
shell = Polygon(p.exterior)
if p.interiors and ((shell.area - p.area) / shell.area > policy.max_strip_hole_fraction
or any(rectangle(Polygon(h))[2] > min(width, rectangle(p)[3])
for h in p.interiors)):
continue
line = [u * lo + n * mid, u * hi + n * mid]
fitted = strip_geometry(line, width)
metrics = agreement(p, fitted, policy.shape_tolerance_m)
if metrics["score"] < .78 or p.hausdorff_distance(fitted) > .25:
continue
delta = contrast(fitted, rgb, pixel_to_scene)
if delta is None or delta < policy.min_luminance_contrast:
continue
obj = dict(representation="strip", kind="linear_marking",
parameters=dict(centerline=np.asarray(line).tolist(), width_m=width),
observation_ids=[feature["id"]], fit=metrics, luminance_contrast=delta,
support_boundary=feature["properties"]["support_boundary"],
recovery=dict(method="observed-crosswalk-group",
seed_ids=sorted(b[0]["id"] for b in bars),
slot=int(round((mid-offsets[0])/step))))
obj["id"] = "object-" + digest(obj)[:24]
recovered.append(obj)
used.add(feature["id"])
break
conflicts = set()
for i,a in enumerate(recovered):
ga = strip_geometry(a["parameters"]["centerline"],a["parameters"]["width_m"])
for j,b in enumerate(recovered[:i]):
same_slot = (a["recovery"]["seed_ids"] == b["recovery"]["seed_ids"]
and a["recovery"]["slot"] == b["recovery"]["slot"])
gb = strip_geometry(b["parameters"]["centerline"],b["parameters"]["width_m"])
if same_slot or ga.intersection(gb).area > 1e-6:
conflicts.update((i,j))
return [o for i,o in enumerate(recovered) if i not in conflicts]
def assemble(mask, rgb, *, pixel_to_scene, source_id, catalog, policy=None):
policy = policy or Policy()
mask = np.asarray(mask)
rgb = np.asarray(rgb)
if mask.ndim != 2 or mask.dtype.kind not in "biu" or not np.isin(mask, [0, 1]).all():
raise ValueError("Binary automatic prediction required; targets/unknown are not inputs")
if rgb.shape != mask.shape + (3,) or rgb.dtype != np.uint8:
raise ValueError("Matching uint8 RGB evidence required")
raw = vectorize(mask, pixel_to_scene=pixel_to_scene, source_id=source_id)
if len(raw["features"]) > policy.max_candidates:
raise ValueError("Candidate budget exceeded")
catalog_sha = digest(catalog)
templates = [
t
for t in catalog["templates"]
if not t.get("hidden") and t["id"] not in ("linear_marking", "zebra")
]
objects, rejected, budget = [], [], [0]
# Only symbol proposals may join small wear gaps. Strip intervals use the
# original components so neighboring dashes are not closed into one line.
cell = min(
np.linalg.norm(np.asarray(pixel_to_scene)[[0, 2]]),
np.linalg.norm(np.asarray(pixel_to_scene)[[1, 3]]),
)
radius = max(1, min(8, int(round(0.04 / cell))))
closed = binary_closing(mask, iterations=radius, border_value=0)
proposals = vectorize(
closed.astype(np.uint8),
pixel_to_scene=pixel_to_scene,
source_id=source_id + "-symbol-proposals",
)
raw_geometries = [shape(r["geometry"]) for r in raw["features"]]
spatial = STRtree(raw_geometries)
consumed = set()
for f in sorted(proposals["features"], key=lambda f: -shape(f["geometry"]).area):
p = shape(f["geometry"])
if p.area < 0.20:
continue
# Bounding-box pruning only; preserve original component order and predicate.
members = [
raw["features"][i]
for i in sorted(int(index) for index in spatial.query(p))
if raw_geometries[i].intersection(p).area > 0.5 * raw_geometries[i].area
]
if not members:
continue
observed = unary_union([shape(r["geometry"]) for r in members])
# A component grouping is a hypothesis, not a replacement for evidence.
result, reason = fit_symbol(observed, templates, policy, budget)
if result is None:
continue
params, metrics = result
g = catalog_geometry(
next(t for t in templates if t["id"] == params["template_id"]),
params["center"],
params["angle_radians"],
params["scale"],
)
delta = contrast(g, rgb, pixel_to_scene)
if delta is None or delta < policy.min_luminance_contrast:
continue
arbitration, reason = arbitrate_symbol(
observed, g, policy, center=params["center"], angle=params["angle_radians"],
rgb=rgb, pixel_to_scene=pixel_to_scene,
)
if reason is not None:
continue
ids = sorted(r["id"] for r in members)
obj = dict(
representation="catalog",
arbitration=arbitration,
kind=params["template_id"],
parameters=params,
observation_ids=ids,
fit=metrics,
luminance_contrast=delta,
)
obj["support_boundary"] = sorted(
{flag for member in members for flag in member["properties"]["support_boundary"]}
)
obj["id"] = "object-" + digest([raw["source_sha256"], catalog_sha, obj])[:24]
objects.append(obj)
consumed.update(ids)
for f in raw["features"]:
if f["id"] in consumed:
continue
p = shape(f["geometry"])
proposals = fit_strips(p, policy) if p.area >= policy.min_area_m2 else []
reason = "too-small" if p.area < policy.min_area_m2 else "unsupported-shape"
candidates = []
for params in proposals:
g = strip_geometry(params["centerline"], params["width_m"])
delta = contrast(g, rgb, pixel_to_scene)
if delta is None or delta < policy.min_luminance_contrast:
reason = "insufficient-rgb-contrast"
break
support = (p if len(proposals) == 1
else p.intersection(g.buffer(policy.shape_tolerance_m)))
obj = dict(representation="strip", kind="linear_marking", parameters=params,
observation_ids=[f["id"]], fit=agreement(support,g,policy.shape_tolerance_m),
luminance_contrast=delta,
support_boundary=f["properties"]["support_boundary"])
if len(proposals) > 1:
obj["decomposition"] = "observed-orthogonal-junction"
obj["id"] = "object-" + digest([raw["source_sha256"],obj])[:24]
candidates.append(obj)
if proposals and len(candidates) == len(proposals):
objects.extend(candidates)
continue
rejected.append(
dict(observation_id=f["id"], reason=reason, status="unresolved-not-background")
)
recovered = recover_crosswalks(objects, raw["features"], rgb=rgb,
pixel_to_scene=pixel_to_scene, policy=policy)
recovered_ids = {i for o in recovered for i in o["observation_ids"]}
rejected = [r for r in rejected if r["observation_id"] not in recovered_ids]
objects.extend(recovered)
group_crosswalks(objects)
for obj in objects:
obj["instance_completeness"] = "not-assessed"
obj["geometry"] = mapping(reconstruct(obj, catalog))
return dict(
schema="missioncore.paint-objects/v1",
source=raw["source"],
catalog_sha256=catalog_sha,
policy=asdict(policy),
objects=objects,
rejected=rejected,
symbol_fits=budget[0],
raw_components=len(raw["features"]),
labels_used=False,
human_geometry_used=False,
)
def surface_plane(obj, *, depth, alpha, camera_eye_z, pixel_to_scene, catalog):
"""Fit observed interior surface, then place a compact object on that plane.
This is Gaussian-derived placement, not surveyed height. No zero-height or
camera-target fallback. Unreliable support preserves the entire 2-D object.
"""
return surface_geometry_plane(
reconstruct(obj, catalog), depth=depth, alpha=alpha,
camera_eye_z=camera_eye_z, pixel_to_scene=pixel_to_scene,
)
def surface_geometry_plane(g, *, depth, alpha, camera_eye_z, pixel_to_scene):
"""Observed surface estimate for arbitrary geometry, without catalog input."""
depth, alpha = np.asarray(depth), np.asarray(alpha)
if (
depth.ndim != 2
or alpha.shape != depth.shape
or not np.isfinite(camera_eye_z)
or not np.isfinite(pixel_to_scene).all()
):
raise ValueError("Invalid surface inputs")
a, b, d, e, x0, y0 = pixel_to_scene
yy, xx = np.indices(depth.shape)
X = a * (xx + 0.5) + b * (yy + 0.5) + x0
Y = d * (xx + 0.5) + e * (yy + 0.5) + y0
support = (
intersects_xy(g, X, Y)
& np.isfinite(depth)
& (depth > 0)
& np.isfinite(alpha)
& (alpha >= 0.95)
)
if support.sum() < 24:
return None, dict(reason="insufficient-surface-support", samples=int(support.sum()))
xy = np.column_stack([X[support], Y[support]])
z = camera_eye_z - depth[support]
stride = max(1, math.ceil(len(xy) / 4096))
xy = xy[::stride]
z = z[::stride]
origin = xy.mean(0)
design = np.column_stack([xy - origin, np.ones(len(xy))])
keep = np.ones(len(xy), bool)
for _ in range(4):
coeff = np.linalg.lstsq(design[keep], z[keep], rcond=None)[0]
residual = np.abs(design @ coeff - z)
keep = residual <= max(0.03, 3 * np.median(residual))
if keep.sum() < 24:
return None, dict(reason="unstable-surface-fit")
center, angle, length, width = rectangle(g)
u = np.array([math.cos(angle), math.sin(angle)])
n = np.array([-u[1], u[0]])
q = xy[keep]
spans = [float(np.ptp(q @ u) / length), float(np.ptp(q @ n) / width)]
p95 = float(np.quantile(np.abs(design[keep] @ coeff - z[keep]), 0.95))
info = dict(
samples=int(keep.sum()),
support_spans=spans,
residual_p95_m=p95,
slopes=coeff[:2].tolist(),
origin=origin.tolist(),
intercept=float(coeff[2]),
source="gaussian-interior-plane",
survey_verified=False,
)
if min(spans) < 0.7 or p95 > 0.15 or np.linalg.norm(coeff[:2]) > 0.5 or keep.mean() < 0.6:
return None, dict(info, reason="unreliable-surface-fit")
def height(x, y):
return (
coeff[0] * (np.asarray(x) - origin[0])
+ coeff[1] * (np.asarray(y) - origin[1])
+ coeff[2]
)
return height, info
def editor_features(obj, *, catalog, height, surface, height_source, observation_source):
"""Materialize an immutable automatic proposal for the existing editor.
Editable geometry is authoritative after a user operation. Recognition
parameters are explicitly an immutable SOURCE snapshot, never current
editable parameters or a reconstruction command for a human revision.
"""
if height is None:
return []
g = transform(lambda x, y, z=None: (x, y, height(x, y)), reconstruct(obj, catalog))
coordinates = [q for p in parts(g) for ring in [p.exterior, *p.interiors] for q in ring.coords]
if not np.isfinite(coordinates).all():
raise ValueError("Invalid materialized height")
props = dict(
subtype=obj["kind"],
authority="observation-only",
route_permission="unassigned",
confidence=None,
confidence_status="not-assessed",
review_status="unreviewed",
annotation_origin="automatic-primitive-assembly",
method="catalog-and-strip-fit-v1",
semantic_element_id=obj.get("group_id", obj["id"]),
support_boundary=obj.get("support_boundary", []),
instance_completeness="not-assessed",
source_observation_sha256=observation_source,
height_source=height_source,
catalog_sha256=digest(catalog),
recognition_snapshot=dict(
role="immutable-automatic-source-not-current-edited-geometry",
representation=obj["representation"],
parameters=obj["parameters"],
surface_model=surface,
),
)
props["class"] = "road_marking"
if obj["representation"] == "catalog":
template = next(
t for t in catalog["templates"] if t["id"] == obj["parameters"]["template_id"]
)
props.update(template_id=template["id"], template_source=template.get("source"))
if "observed_bar_count" in obj:
props["observed_bar_count"] = obj["observed_bar_count"]
features = [
dict(type="Feature", id=obj["id"] + "-" + str(i), geometry=mapping(p), properties=props)
for i, p in enumerate(parts(g))
]
# Core's editing operations mutate coordinate lists. Return the actual JSON
# contract even before disk serialization, with no shared caller metadata.
return json.loads(json.dumps(features, allow_nan=False))
@@ -0,0 +1,82 @@
"""Observed XY contours -> qualified Gaussian heights; never reconstruct paint."""
import numpy as np
from paint_objects import surface_geometry_plane
from shapely.ops import transform
class HeightRefusal(ValueError):
"""Expected missing height evidence, not a malformed input or code error."""
def _inputs(depth, alpha, camera_eye_z, matrix):
depth, alpha = np.asarray(depth), np.asarray(alpha)
m = np.asarray(matrix, dtype=float)
if (depth.ndim != 2 or depth.shape != alpha.shape or not depth.size
or m.shape != (6,) or not np.isfinite(m).all()
or not np.isfinite(camera_eye_z)
or abs(m[0] * m[3] - m[1] * m[2]) < 1e-12):
raise ValueError("Invalid projection inputs")
return depth, alpha, m
def bilinear_geometry(g, *, depth, alpha, camera_eye_z, pixel_to_scene):
"""Require each contributing sample; ignore only exactly zero weights."""
depth, alpha, m = _inputs(depth, alpha, camera_eye_z, pixel_to_scene)
inverse = np.linalg.inv([[m[0], m[1]], [m[2], m[3]]])
def lift(x, y, z=None):
uv = (np.column_stack([x, y]) - m[4:]) @ inverse.T - 0.5
base = np.floor(uv).astype(int)
fraction = uv - base
height = np.zeros(len(uv))
for dx, dy in ((0, 0), (1, 0), (0, 1), (1, 1)):
weight = ((fraction[:, 0] if dx else 1 - fraction[:, 0])
* (fraction[:, 1] if dy else 1 - fraction[:, 1]))
needed = weight > 0
ix, iy = base[needed, 0] + dx, base[needed, 1] + dy
if (np.any(ix < 0) or np.any(iy < 0)
or np.any(ix >= depth.shape[1]) or np.any(iy >= depth.shape[0])):
raise HeightRefusal("outside-depth")
dd, aa = depth[iy, ix], alpha[iy, ix]
if not (np.isfinite(dd) & (dd > 0) & np.isfinite(aa) & (aa >= 0.95)).all():
raise HeightRefusal("missing-observed-vertex-height")
height[needed] += weight[needed] * (camera_eye_z - dd)
return x, y, height
return transform(lift, g)
def project_observation(g, *, depth, alpha, camera_eye_z, pixel_to_scene):
"""Preserve every XY ring. Return explicit 2D-only refusal without fake Z.
A local plane is estimated from the original contour's interior evidence,
never from a catalog template. The existing surface acceptance guards apply.
"""
depth, alpha, m = _inputs(depth, alpha, camera_eye_z, pixel_to_scene)
if g.is_empty or not g.is_valid or g.geom_type != "Polygon":
raise ValueError("A valid observation Polygon is required")
try:
placed = bilinear_geometry(g, depth=depth, alpha=alpha,
camera_eye_z=camera_eye_z, pixel_to_scene=m)
return placed, dict(method="observed-bilinear", placement_status="placed")
except HeightRefusal as error:
direct_refusal = str(error)
# Crop by an inverse affine of the envelope. This bounds per-object work
# without changing the support pixels (works for rotated grids as well).
inverse = np.linalg.inv([[m[0], m[1]], [m[2], m[3]]])
uv = (np.asarray(g.envelope.exterior.coords)[:, :2] - m[4:]) @ inverse.T
x0, y0 = np.maximum(np.floor(uv.min(0)).astype(int) - 2, 0)
x1, y1 = np.minimum(np.ceil(uv.max(0)).astype(int) + 2, depth.shape[1::-1])
if x1 <= x0 or y1 <= y0:
return None, dict(placement_status="2d-only", reason="outside-depth")
cropped = [*m[:4], m[4] + m[0] * x0 + m[1] * y0,
m[5] + m[2] * x0 + m[3] * y0]
height, info = surface_geometry_plane(
g, depth=depth[y0:y1, x0:x1], alpha=alpha[y0:y1, x0:x1],
camera_eye_z=camera_eye_z, pixel_to_scene=cropped,
)
info = dict(info, direct_refusal=direct_refusal)
if height is None:
return None, dict(info, placement_status="2d-only")
placed = transform(lambda x, y, z=None: (x, y, height(x, y)), g)
return placed, dict(info, method="observed-interior-plane", placement_status="placed")