"""Exact, offline observed-paint geometry; no inference, fitting or map publication. Input is a discrete 0=background, 1=paint, 255=unknown grid. Coordinates refer to pixel EDGES, not centres. A connected component is an observation, not a semantic instance. Raw geometry remains 2-D until an explicit height provider is supplied. """ import copy import hashlib import json import numpy as np from shapely import affinity, normalize from shapely.geometry import box, mapping, shape from shapely.ops import unary_union SCHEMA = "missioncore.paint-geometry/v1" MAX_CELLS = 1024 * 1024 MAX_RUNS = 32768 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() ).hexdigest() def _runs(mask): padded = np.pad(mask.astype(np.int8), ((0, 0), (1, 1))) rows, starts = np.where(np.diff(padded, axis=1) == 1) end_rows, ends = np.where(np.diff(padded, axis=1) == -1) if not np.array_equal(rows, end_rows): raise ValueError("Unpaired raster runs") if len(rows) > MAX_RUNS: raise ValueError("Raster run budget exceeded; no lossy fallback") return list(zip(rows.tolist(), starts.tolist(), ends.tolist(), strict=True)) def _cells_geometry(runs): return unary_union([box(start, row, end, row + 1) for row, start, end in runs]) def vectorize(labels, *, pixel_to_scene, source_id): """Return a bounded 2-D proposal, with exact cells and explicit unknown support. pixel_to_scene is Shapely's [a,b,d,e,xoff,yoff] affine: x=a*col+b*row+xoff. Source identity is caller-owned (tile/revision); the complete label bytes and transform are additionally bound into the proposal hash. """ labels = np.asarray(labels) matrix = np.asarray(pixel_to_scene, dtype=float) if ( labels.ndim != 2 or not labels.size or labels.size > MAX_CELLS or labels.dtype.kind not in "biu" or not np.isin(labels, [0, 1, 255]).all() ): raise ValueError("Expected bounded integer 0/1/255 grid") if ( matrix.shape != (6,) or not np.isfinite(matrix).all() or abs(matrix[0] * matrix[3] - matrix[1] * matrix[2]) < 1e-12 ): raise ValueError("Finite non-singular pixel-edge affine required") if not isinstance(source_id, str) or not 1 <= len(source_id) <= 256: raise ValueError("Source identity required") label_sha = hashlib.sha256(labels.astype(np.uint8).tobytes()).hexdigest() identity = dict( source_id=source_id, labels_sha256=label_sha, shape=list(labels.shape), pixel_to_scene=matrix.tolist(), ) source_sha = digest(identity) paint = _cells_geometry(_runs(labels == 1)) unknown = _cells_geometry(_runs(labels == 255)) height, width = labels.shape edge = box(0, 0, width, height).boundary polygons = [] if paint.is_empty else ( [paint] if paint.geom_type == "Polygon" else list(paint.geoms) ) # Zero tolerance only removes collinear run endpoints; assert no area change. features = [] for poly in polygons: if poly.geom_type != "Polygon" or not poly.is_valid: raise ValueError("Unsupported raster topology; no automatic repair") compact = poly.simplify(0, preserve_topology=True) if not compact.equals(poly): raise ValueError("Polygon compaction changed observed paint") world = normalize(affinity.affine_transform(compact, matrix)) if not world.is_valid or world.is_empty: raise ValueError("Invalid transformed geometry") geometry = json.loads(json.dumps(mapping(world))) flags = [] if poly.intersects(edge): flags.append("tile-edge") if not unknown.is_empty and poly.intersects(unknown): flags.append("unknown-support") features.append(dict( type="Feature", id="paint-" + digest([source_sha, geometry])[:24], geometry=geometry, properties=dict( observation_role="observed-paint-component", source_id=source_id, source_sha256=source_sha, support_boundary=flags, instance_completeness="not-assessed", review_status="unreviewed", ), )) features.sort(key=lambda f: f["id"]) result = dict( schema_version=SCHEMA, source=identity, source_sha256=source_sha, counts=dict(paint=int(np.count_nonzero(labels == 1)), background=int(np.count_nonzero(labels == 0)), unknown=int(np.count_nonzero(labels == 255))), features=features, ) result["proposal_sha256"] = digest(result) return result 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" ): raise ValueError("Changed or unsupported geometry proposal") if not isinstance(height_source, str) or not 1 <= len(height_source) <= 256: raise ValueError("Explicit height provenance required") # Existing editor validators have quadratic segment/ring comparisons. # Budget the WHOLE proposal before any geometry validator or height callback. work = 0 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": raise ValueError("Unsupported editor geometry") rings = geo["coordinates"] if not rings or len(rings) > MAX_EDITOR_RINGS: raise ValueError("Editor ring budget exceeded; no lossy fallback") if any(not 4 <= len(ring) <= 4096 for ring in rings): raise ValueError("Editor path budget exceeded") edges = sum(len(ring) - 1 for ring in rings) vertices += sum(len(ring) for ring in rings) 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 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),): 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][:]) try: validate_path(points, True) except ValueError as error: raise ComponentRefusal(str(error)) from error rings.append(points) 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", "route_permission": "unassigned", "confidence": None, "confidence_status": "not-assessed", "annotation_origin": "mask-observation", "height_source": 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", )