feat(research): preserve urban geometry pipelines and qualification suites

Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:00 +03:00
parent 5d56237124
commit 69dc566665
611 changed files with 52016 additions and 28 deletions
+85
View File
@@ -63,3 +63,88 @@ In planning, the infrastructure toggle is independent of Gaussian/collision laye
Contours do not enter picking, collision or rover control. Hiding the layer leaves
the original scene and route unchanged. Delete only a map's `latest.json` pointer
to unpublish it; immutable previous versions remain available for rollback.
## Whole-location command and shared storage
The planning header command **Проанализировать инфраструктуру** creates one durable
job for the current world/collider/provider identities. The existing Worker coordinator
reserves the shared GPU using the same admission mechanism as simulation, reads the
verified complete-scene source, and launches two separate bounded containers in order:
Gaussian rendering / Mask2Former survey, then VMA object vectorization. Gaussian Pipeline
remains an independently owned module; no service is merged or restarted for this job.
The input is the existing prepared `state/project-packages/<world-sha>/` directory
(resolved through the worker's shared-cache link). Both stages bind the exact existing
files read-only. No downloads, `copy`, new PLY conversions, or source-scene files are
allowed in the analysis output. Output under `runtime/urban-mapping/jobs/<job-key>/`
contains only request/progress metadata and derived images, atlases and vectors.
Sources and receipts are checksum-verified before use. Repeated identical requests
reuse the job; retries validate and resume completed tile receipts.
The first supported source contract is an already prepared complete-scene PLY plus
its calibrated decoded collider. An imported project that exists only as native SOG
has **not** yet qualified for this command: it must not silently invoke another scene
copy or conversion. Missing shared artifacts are reported as preparation failure.
Native-source reading is a separate provider extension, not a claim of this release.
`whole_scene.py` tiles the complete collider XY bounds, independent of route A/B:
40 m core plus 10 m overlap, 60 m / 1200 px orthographic views, and up to four
800×600 perspective views per tile. The supported envelope is 256 tiles. Camera
candidates come from measured near-horizontal geometry. This is a heuristic survey;
roofs, missing ground and occlusion require inspection. All processed tiles and gaps
are recorded. “Whole-scene” describes the requested extent, not complete recognition.
`vector/whole_vectors.py` runs the pinned VMA models, uses semantic/depth evidence to
admit objects, assigns overlapping polygons to one core tile and clips lines in XYZ.
The final v2 map remains unreviewed and observation-only. It is published only when
world/collider/provider/job identities match; a failed analysis preserves the previous
map. Worker restarts reconcile exactly labelled containers before releasing the GPU.
The planning UI has independent Gaussian and collision switches, one infrastructure
switch, and a memory dropdown. Memory contains accumulated visits/attempts across
runs for a scene/collider/robot revision; the dropdown currently displays the latest
robot configuration's accumulated history. Fresh sensing remains authoritative.
## Contour consolidation
After tile assembly, **Согласование контуров** runs in the vector container.
It reads the original survey in place and retains `urban-map.raw.json` before
publishing `urban-map.json`. `contour-refinement.json` records dropped observation
IDs, overlap removal and individual joins. The map stores source IDs, inferred gap
coordinates, spline knots/control points and runtime library versions. Original
observations remain recoverable; this stage never changes the collider or route
permissions.
The geometric engine is GEOS through pinned Shapely 1.8.5.post1 (STRtree,
intersection/difference and linemerge), NetworkX connected components and SciPy
1.13.1 FITPACK cubic B-splines. There is no custom line-merging implementation.
Application policy restricts inputs to matching classes, compatible endpoint
directions/heights, unambiguous junctions and non-crossing geometry. Default
maximum gaps are 1.25 m for curbs, 0.5 m for lane paint, 0.2 m for stop lines;
gaps over 0.12 m additionally require source alpha/depth and oriented image
contrast. These are provisional metric engineering thresholds, not measurement
accuracy or autonomous-driving tolerances. Large missing sections stay open.
Duplicate overlap uses 0.15 m tolerance. Isolated weak fragments below 1.5 m are
removed only with negative image evidence on observed ground. B-spline fitting
preserves structural corners/endpoints and checks rendered XY Hausdorff deviation
<=0.12 m, height deviation <=0.08 m, length and new intersections. Height inside
an inferred bridge is explicitly labelled endpoint interpolation. Crossing areas
and zebra paint polygons are unchanged. Geometric refinement cannot establish
that every VMA classification is correct; dubious long detections are not erased
just because their image contrast is low.
Alternatives reviewed: GRASS `v.clean`/`v.generalize`, CartAGen smoothing,
momepy COINS and neatnet preprocessing. Their generic network simplification
must not collapse distinct curbs/lanes or remove legitimate dead ends. COINS
also expects non-overlapping input. For this stage the existing GEOS/SciPy
runtime avoids introducing another GIS dependency stack into legacy VMA CUDA.
Primary references:
- https://shapely.readthedocs.io/en/1.8.5/manual.html#shapely.ops.linemerge
- https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splprep.html
- https://grass.osgeo.org/grass-stable/manuals/v.clean.html
- https://cartagen.readthedocs.io/en/latest/manual.html
- https://docs.momepy.org/stable/api/momepy.COINS.html
- https://uscuni.org/neatnet/
+2
View File
@@ -63,6 +63,8 @@ def fuse(job, output, unproject, classes, write_json):
z[~accepted.reshape(height, width)] = np.nan
np.savez_compressed(output / 'surface-atlas.npz', labels=labels, z=z, views=observed.reshape(height, width),
confidence=strength.reshape(height, width), bounds=bounds, cell_m=cell)
if job.get('atlas_only'):
return {'accepted_cells': int(accepted.sum())}
rgb = np.full((height, width, 3), [25, 28, 32], np.uint8)
features = []
import rasterio.features
+55 -18
View File
@@ -69,13 +69,43 @@ def unproject(pixels, depth, view, intrinsics, projection):
return (local @ np.linalg.inv(view).T)[:, :3]
def render(job, output):
def prepare_crops(jobs):
"""One source walk per bounded batch; retain source row order and numeric operations."""
from plyfile import PlyData
if not 1 <= len(jobs) <= 4 or any(j['source'] != jobs[0]['source'] for j in jobs):
raise ValueError('A crop batch requires one source and at most four windows')
source = Path('/input') / jobs[0]['source']['ply']
transform = np.asarray(jobs[0]['source']['source_to_world'], dtype=np.float64)
data = PlyData.read(source, mmap='r')['vertex'].data
rows = [[] for _ in jobs]
for start in range(0, len(data), 250000):
d = data[start:start + 250000]
xyz = np.column_stack([d[n] for n in ['x', 'y', 'z']])
world = xyz @ transform[:3, :3].T + transform[:3, 3]
for job, selected in zip(jobs, rows):
bounds = np.asarray(job['bounds_xy'], dtype=float)
mask = ((world[:, :2] >= bounds[0] - job.get('halo_m', 15)) &
(world[:, :2] <= bounds[1] + job.get('halo_m', 15))).all(axis=1)
selected.append(d[mask].copy())
for selected in rows:
result = np.concatenate(selected)
selected.clear()
yield result
def render(job, output, prepared_rows=None):
import torch
from gsplat import rasterization
from plyfile import PlyData
source = Path('/input') / job['source']['ply']
if digest(source) != job['source']['sha256']:
raise ValueError('Gaussian source checksum mismatch')
global _verified_sources
if '_verified_sources' not in globals(): _verified_sources = set()
stat = source.stat()
identity = (str(source), stat.st_size, stat.st_mtime_ns, job['source']['sha256'])
if identity not in _verified_sources:
if digest(source) != job['source']['sha256']:
raise ValueError('Gaussian source checksum mismatch')
_verified_sources.add(identity)
transform = np.asarray(job['source']['source_to_world'], dtype=np.float64)
if (transform.shape != (4, 4) or not np.isfinite(transform).all()
or not np.allclose(transform[3], [0, 0, 0, 1])
@@ -83,18 +113,21 @@ def render(job, output):
or not np.isclose(np.linalg.det(transform[:3, :3]), 1)):
raise ValueError('Only rigid source transforms are supported; bake scale into the source')
data = PlyData.read(source, mmap='r')['vertex'].data
rows = []
bounds = np.asarray(job['bounds_xy'], dtype=float)
# Chunk filtering bounds RAM while retaining every source splat in the requested tile + halo.
for start in range(0, len(data), 250000):
d = data[start:start + 250000]
xyz = np.column_stack([d[n] for n in ['x', 'y', 'z']])
world = xyz @ transform[:3, :3].T + transform[:3, 3]
mask = ((world[:, :2] >= bounds[0] - job.get('halo_m', 15)) &
(world[:, :2] <= bounds[1] + job.get('halo_m', 15))).all(axis=1)
rows.append(d[mask].copy())
d = np.concatenate(rows)
del rows
if prepared_rows is None:
rows = []
bounds = np.asarray(job['bounds_xy'], dtype=float)
# Chunk filtering bounds RAM while retaining every source splat in the requested tile + halo.
for start in range(0, len(data), 250000):
d = data[start:start + 250000]
xyz = np.column_stack([d[n] for n in ['x', 'y', 'z']])
world = xyz @ transform[:3, :3].T + transform[:3, 3]
mask = ((world[:, :2] >= bounds[0] - job.get('halo_m', 15)) &
(world[:, :2] <= bounds[1] + job.get('halo_m', 15))).all(axis=1)
rows.append(d[mask].copy())
d = np.concatenate(rows)
del rows
else:
d = prepared_rows
if not len(d):
raise ValueError('No Gaussians in the requested tile')
def tensor(names):
@@ -130,11 +163,15 @@ def infer(job, output):
import torch
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
model_path = Path('/model')
for name, expected in job['model']['files'].items():
global _semantic_cache
if '_semantic_cache' not in globals(): _semantic_cache = None
for name, expected in (job['model']['files'].items() if _semantic_cache is None else []):
if digest(model_path / name) != expected:
raise ValueError('Model asset checksum mismatch: ' + name)
processor = AutoImageProcessor.from_pretrained(model_path, local_files_only=True)
model = Mask2FormerForUniversalSegmentation.from_pretrained(model_path, local_files_only=True).cuda().eval()
if _semantic_cache is None:
_semantic_cache = (AutoImageProcessor.from_pretrained(model_path, local_files_only=True),
Mask2FormerForUniversalSegmentation.from_pretrained(model_path, local_files_only=True).cuda().eval())
processor, model = _semantic_cache
for spec in job['views']:
if spec.get('projection', 'pinhole') != 'pinhole':
continue # Mapillary is a street-view model; orthographic views are review only.
@@ -0,0 +1,67 @@
"""Read existing orthographic survey tiles in place; bounded four-tile cache."""
import json
from collections import OrderedDict
from pathlib import Path
import cv2
import numpy as np
from PIL import Image
class SurveyEvidence:
def __init__(self, root):
self.root = Path(root)
self.tiles = [t for t in json.loads((self.root/'tile-index.json').read_text())['tiles'] if t['status']=='surveyed']
self.cache = OrderedDict()
def load(self, tile):
key = tile['id']
if key not in self.cache:
folder = self.root/key
with np.load(folder/'top.geometry.npz') as g:
data = {k:g[k] for k in ('view','intrinsics','alpha','depth')}
rgb = np.asarray(Image.open(folder/'top.png').convert('RGB'))
data['gray'] = cv2.GaussianBlur(cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32), (3,3), .6)
self.cache[key] = data
if len(self.cache)>4:self.cache.popitem(last=False)
self.cache.move_to_end(key)
return self.cache[key]
def support(self, points, key):
"""Return observed-ground and oriented image support for each XYZ sample.
Paint needs a bright ridge, a boundary needs cross-line contrast. Image
contrast alone never proves ground: depth and alpha must also agree.
"""
p = np.asarray(points, float); n = len(p)
ground, signal = np.zeros(n, bool), np.zeros(n, bool)
tangent = np.gradient(p[:, :2], axis=0)
normal = np.column_stack([-tangent[:,1], tangent[:,0]])
normal /= np.maximum(np.linalg.norm(normal, axis=1)[:,None], 1e-9)
for tile in self.tiles:
low, high = np.asarray(tile['core_bounds'])
ids = np.flatnonzero(((p[:,:2]>=low-.1)&(p[:,:2]<=high+.1)).all(1))
if not len(ids):continue
g = self.load(tile); k = g['intrinsics']; view = g['view']; gray = g['gray']
q = p[ids]; cam = np.c_[q, np.ones(len(q))]@view.T
uv = cam[:,:2]*np.diag(k)[:2]+k[:2,2]-.5
h,w = gray.shape
valid = ((uv>6)&(uv<[w-7,h-7])).all(1)
c,r = np.rint(uv).astype(int).T; c=np.clip(c,0,w-1);r=np.clip(r,0,h-1)
valid &= (g['alpha'][r,c]>=.65)&np.isfinite(g['depth'][r,c])&(np.abs(cam[:,2]-g['depth'][r,c])<=.5)
def at(offset):
shifted = q.copy(); shifted[:,:2] += normal[ids]*offset
xy = (np.c_[shifted,np.ones(len(q))]@view.T)[:,:2]*np.diag(k)[:2]+k[:2,2]-.5
return cv2.remap(gray, xy[:,0].astype(np.float32)[None], xy[:,1].astype(np.float32)[None], cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)[0]
center = np.maximum.reduce([at(x) for x in (-.05,0,.05)])
left,right = at(-.25),at(.25)
if key[0]=='road_marking':
supported = (center > np.maximum(left,right)+7)&(center>75)
else:
supported = np.maximum.reduce([np.abs(left-right), np.abs(center-left), np.abs(center-right)])>8
ground[ids] |= valid; signal[ids] |= valid&supported
return ground, signal
def bridge(self, points, key):
ground, signal = self.support(points, key)
required = .9 if key[0]=='road_marking' else .7
return bool(ground.all() and signal.mean()>=required)
@@ -0,0 +1,83 @@
"""Metric curve operations; no projection, classification or route authority."""
import warnings
import numpy as np
from scipy.interpolate import splprep, splev
from shapely.geometry import LineString, Point
def distance(points):
return np.r_[0., np.cumsum(np.linalg.norm(np.diff(points[:, :2], axis=0), axis=1))]
def sample(points, step=.15):
points = np.asarray(points, float)
d = distance(points)
keep = np.r_[True, np.diff(d) > 1e-7]
points, d = points[keep], d[keep]
if len(d) < 2:
return points
at = np.linspace(0, d[-1], max(2, int(np.ceil(d[-1] / step)) + 1))
return np.column_stack([np.interp(at, d, points[:, i]) for i in range(3)])
def lift_piece(piece, original):
"""Keep Z from the original metric curve after a planar overlap operation."""
line = LineString(original[:, :2]); d = distance(original)
xy = np.asarray(piece.coords)[:, :2]
at = [line.project(Point(p)) for p in xy]
return np.column_stack([xy, np.interp(at, d, original[:, 2])])
def end_direction(points, end):
p = sample(points if end == 0 else points[::-1], .2)
delta = p[0, :2] - p[min(4, len(p)-1), :2]
return delta / max(np.linalg.norm(delta), 1e-9)
def smooth(points, tolerance=.12):
"""Piecewise cubic B-splines, fixed endpoints/corners, bounded XYZ deviation.
The renderer consumes sampled XYZ. The actual knots/controls are retained
for CAD consumers, including linear spans where fitting is inappropriate.
"""
points = np.asarray(points, float)
line = LineString(points[:, :2])
if line.length < .3 or not line.is_simple:
return points, []
# Detect structural corners on a simplified curve, not on pixel noise.
skeleton = np.asarray(line.simplify(.12).coords)
corners = []
for i in range(1, len(skeleton)-1):
a, b = skeleton[i]-skeleton[i-1], skeleton[i+1]-skeleton[i]
if np.dot(a, b) < .766 * np.linalg.norm(a) * np.linalg.norm(b):
corners.append(int(np.argmin(np.linalg.norm(points[:, :2]-skeleton[i], axis=1))))
cuts = sorted(set([0, *corners, len(points)-1]))
result, curves = [], []
for low, high in zip(cuts, cuts[1:]):
original = points[low:high+1]
p = sample(original, .25)
reference = LineString(original[:, :2])
output = original; curve = dict(degree=1, controls=original.round(5).tolist())
if len(p) >= 4:
weights = np.ones(len(p)); weights[[0, -1]] = 1e6
for factor in (1., .25, .0625):
with warnings.catch_warnings():
warnings.simplefilter('error', RuntimeWarning)
try:
tck, _ = splprep(p.T, w=weights, s=len(p)*(.07**2)*factor, k=3)
candidate = np.asarray(splev(np.linspace(0, 1, max(4, int(reference.length/.15)+1)), tck)).T
except (ValueError, RuntimeWarning):
continue
candidate[[0, -1]] = original[[0, -1]]
fitted = LineString(candidate[:, :2])
at = distance(candidate); expected_z = np.interp(at / max(at[-1], 1e-9), distance(p)/distance(p)[-1], p[:, 2])
if (fitted.is_simple and fitted.hausdorff_distance(reference) <= tolerance
and .94 <= fitted.length/reference.length <= 1.06
and np.max(np.abs(candidate[:, 2]-expected_z)) <= .08):
output = candidate
curve = dict(degree=3, knots=np.asarray(tck[0]).round(8).tolist(),
controls=np.asarray(tck[1]).T.round(5).tolist())
break
result.extend(output if not result else output[1:])
curves.append(curve)
return np.asarray(result), curves
@@ -37,15 +37,21 @@ def main():
predictions=[];timings={}
for kind in args.kinds:
weights=args.assets/('sd_'+kind+'.pth')
assert sha(weights)==manifest[weights.name]['sha256'],'Checkpoint hash mismatch'
cfg=mmcv.Config.fromfile('projects/configs/vma_res152_e80_'+kind+'.py')
cfg.model.pretrained=None;cfg.model.train_cfg=None
# Upstream coder relaxes its threshold until it finds a detection. Keep
# all native top-k scores and enforce a FIXED threshold after decoding.
cfg.model.pts_bbox_head.bbox_coder.score_threshold=None
model=build_model(cfg.model,test_cfg=cfg.get('test_cfg')).eval()
load_checkpoint(model,str(weights),map_location='cpu',strict=True)
model.cuda();start=time.monotonic()
global _models
if '_models' not in globals(): _models = {}
stat = weights.stat()
key = (str(weights), stat.st_size, stat.st_mtime_ns)
if key not in _models:
assert sha(weights)==manifest[weights.name]['sha256'],'Checkpoint hash mismatch'
cfg=mmcv.Config.fromfile('projects/configs/vma_res152_e80_'+kind+'.py')
cfg.model.pretrained=None;cfg.model.train_cfg=None
# Fixed threshold: never relax until a detection appears.
cfg.model.pts_bbox_head.bbox_coder.score_threshold=None
model=build_model(cfg.model,test_cfg=cfg.get('test_cfg')).eval()
load_checkpoint(model,str(weights),map_location='cpu',strict=True)
_models[key] = (cfg, model.cuda())
cfg, model = _models[key]
start=time.monotonic()
for x,y in positions:
crop=rgb[y:y+1000,x:x+1000]
image=torch.from_numpy(crop.copy()).permute(2,0,1).float().cuda()/255.
@@ -62,7 +68,7 @@ def main():
points=points,tile_xy=[x,y]))
print(json.dumps(dict(kind=kind,tile=[x,y],detections=int((result['scores_3d']>=args.threshold).sum()))),flush=True)
timings[kind]=time.monotonic()-start
del model;torch.cuda.empty_cache()
doc=dict(schema_version='missioncore.vector-candidates/v1',source_image_sha256=sha(args.image),
vma_commit='a6e98e8f704e72499b33da84715ba39e8705e02e',weights=manifest,
input_size=[w,h],native_crop_size=1000,threshold=args.threshold,
@@ -0,0 +1,188 @@
"""Whole-location contour consolidation, independent of inference and navigation.
native detections -> same-class overlap removal -> unambiguous endpoint
graph with image-checked bridges -> corner-preserving cubic B-splines
All thresholds are metric. Missing coverage, branching, road-marking gaps and
different heights are never joined just to produce a more attractive drawing.
"""
import argparse
import hashlib
import json
from collections import defaultdict
from pathlib import Path
import numpy as np
import networkx as nx
import warnings
from scipy.spatial import cKDTree
from shapely.geometry import LineString, shape
from shapely.ops import unary_union, linemerge
from shapely.strtree import STRtree
from shapely.errors import ShapelyDeprecationWarning
from contour_geometry import distance, end_direction, lift_piece, sample, smooth
VERSION = 'missioncore.contour-consolidation/v1'
def semantic(f):
p=f['properties']
return p['class'], p.get('source_class'), p.get('geometry_role')
class SpatialLines:
"""GEOS spatial index; the pinned Shapely 1.8 returns geometry objects."""
def __init__(self, records):
self.records={id(a['line']):a for a in records}
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=ShapelyDeprecationWarning)
self.tree=STRtree([a['line'] for a in records])
def near(self, line, radius=.2):
return sorted((self.records[id(g)] for g in self.tree.query(line.buffer(radius))),
key=lambda a:(a['ids'],a['line'].wkt))
def consolidate(document, evidence=None, progress=lambda done,total:None):
"""Pure input contract: returns a new document and an auditable edit receipt."""
features=document['features']
if len(features)>20000:raise ValueError('Contour refinement exceeds feature budget')
report=dict(schema_version=VERSION, input_features=len(features),
duplicates=[], removed_noise=[], trimmed_overlap_m=0., joins=[], smoothed_curves=0)
lines=[]; other=[]; progress(0,4)
for f in features:
if f['geometry']['type']!='LineString' or f['properties']['class'] not in ('curb','road_marking'):
other.append(f);continue
p=np.asarray(f['geometry']['coordinates'],float)
p=p[np.r_[True,np.linalg.norm(np.diff(p[:,:2],axis=0),axis=1)>1e-7]]
if len(p)<2:continue
lines.append(dict(f=f,p=p,key=semantic(f),line=LineString(p[:,:2]),ids=[f['id']],gaps=[]))
# Prefer the stronger observation; remove only close, same-height overlap.
spatial=SpatialLines(lines); accepted=set(); records=[]
for a in sorted(lines,key=lambda a:(-a['f']['properties']['confidence'],-a['line'].length,a['f']['id'])):
masks=[]
for b in spatial.near(a['line']):
if id(b) not in accepted or a['key']!=b['key'] or a['line'].distance(b['line'])>.15:continue
if min(a['line'].length,b['line'].length)<1. and abs(np.dot(end_direction(a['p'],0),end_direction(b['p'],0)))<.94:continue
if abs(np.median(a['p'][:,2])-np.median(b['p'][:,2]))>.15:continue
mask=b['line'].buffer(.15,cap_style=2)
overlap=a['line'].intersection(mask).length
# A transverse crossing only occupies a tiny part of a line.
if overlap>=min(1.,.8*a['line'].length):masks.append(mask)
uncovered=a['line'].difference(unary_union(masks)) if masks else a['line']
if uncovered.length<.2*a['line'].length:
report['duplicates'].append(a['f']['id']);continue
accepted.add(id(a))
pieces=[uncovered] if uncovered.geom_type=='LineString' else list(getattr(uncovered,'geoms',[]))
report['trimmed_overlap_m']+=a['line'].length-uncovered.length
for piece in pieces:
if piece.geom_type!='LineString' or piece.length<.25:continue
p=lift_piece(piece,a['p'])
records.append({**a,'p':p,'line':LineString(p[:,:2])})
progress(1,4)
endpoints=np.array([a['p'][e] for a in records for e in (0,-1)])
tree=cKDTree(endpoints[:,:2]) if len(endpoints) else None
# Remove isolated, short, weak fragments only when the survey also rejects them.
keep=[]
for i,a in enumerate(records):
neighbours=set(tree.query_ball_point(endpoints[2*i,:2],1.))|set(tree.query_ball_point(endpoints[2*i+1,:2],1.))
isolated=all(j//2==i for j in neighbours)
if evidence and isolated and a['line'].length<1.5 and a['f']['properties']['confidence']<.5:
ground,signal=evidence.support(sample(a['p'],.1),a['key'])
if ground.mean()>.8 and signal.mean()<.25:
report['removed_noise'].append(a['f']['id']);continue
keep.append(a)
records=keep
endpoints=np.array([a['p'][e] for a in records for e in (0,-1)])
tree=cKDTree(endpoints[:,:2]) if len(endpoints) else None
candidates=defaultdict(list); blockers=SpatialLines(records)
openings=[shape(f['geometry']) for f in other if f['properties']['class']=='curb_cut']
for i,q in enumerate(endpoints):
a=records[i//2];va=end_direction(a['p'],i%2)
junction=[j for j in tree.query_ball_point(q[:2],.18) if records[j//2]['key']==a['key']]
if len(set(j//2 for j in junction))>2:continue
maximum=1.25 if a['key'][0]=='curb' else (.2 if a['key'][1]=='stopline' else .5)
for j in tree.query_ball_point(q[:2],maximum):
if j<=i or i//2==j//2:continue
b=records[j//2]
if a['key']!=b['key']:continue
other_junction=[k for k in tree.query_ball_point(endpoints[j,:2],.18) if records[k//2]['key']==a['key']]
if len(set(k//2 for k in other_junction))>2:continue
delta=endpoints[j,:2]-q[:2];gap=float(np.linalg.norm(delta));vb=end_direction(b['p'],j%2)
if np.dot(va,-vb)<.94 or abs(q[2]-endpoints[j,2])>.12+.12*gap:continue
if gap>.02 and min(np.dot(va,delta/gap),np.dot(-vb,delta/gap))<.85:continue
bridge=LineString([q[:2],endpoints[j,:2]])
if any(bridge.intersects(o) for o in openings):continue
if gap>.02 and any(c is not a and c is not b and bridge.crosses(c['line']) for c in blockers.near(bridge)):continue
bridge_points=sample(np.array([q,endpoints[j]]),.05) if gap>.02 else np.array([q,endpoints[j]])
if gap>.12 and (evidence is None or not evidence.bridge(bridge_points,a['key'])):continue
cost=gap+1-np.dot(va,-vb)
candidates[i].append((cost,j));candidates[j].append((cost,i))
# Mutual, separated best matches: no greedy choice at a branching/ambiguous end.
best={}
for i,options in candidates.items():
options.sort()
if len(options)==1 or options[1][0]-options[0][0]>.15:best[i]=options[0][1]
links={i:j for i,j in best.items() if best.get(j)==i}
# NetworkX identifies components; GEOS owns line assembly and orientation.
graph=nx.Graph();graph.add_nodes_from(range(len(records)))
for i,j in links.items():
if i<j:graph.add_edge(i//2,j//2,ends=(i,j))
chains=[]
for component in nx.connected_components(graph):
members=[records[i] for i in sorted(component)]
segments=[LineString(a['p']) for a in members]; gaps=[]; joins=[]
for _,_,edge in graph.subgraph(component).edges(data=True):
i,j=edge['ends'];q,p=endpoints[i],endpoints[j]
gap=float(np.linalg.norm(q[:2]-p[:2]))
if gap>1e-7:
segments.append(LineString([q,p]))
gaps.append(dict(from_xyz=q.round(4).tolist(),to_xyz=p.round(4).tolist(),length_m=round(gap,4),
evidence='image-and-ground' if gap>.12 else 'endpoint-tolerance',height_source='endpoint-interpolation'))
joins.append(dict(sources=[records[i//2]['ids'][0],records[j//2]['ids'][0]],gap_m=round(gap,4)))
merged=linemerge(segments)
if merged.geom_type!='LineString' or not merged.is_simple:
chains.extend(members);continue
report['joins'].extend(joins)
chains.append({**members[0],'p':np.asarray(merged.coords),'ids':sorted({i for a in members for i in a['ids']}),'gaps':gaps})
progress(2,4)
output=list(other)
for a in chains:
p,curves=smooth(a['p'])
original=LineString(a['p'][:,:2]); fitted=LineString(p[:,:2])
if any(fitted.crosses(b['line']) and not original.crosses(b['line']) for b in blockers.near(fitted) if not set(a['ids'])&set(b['ids'])):
p=a['p'];curves=[]
report['smoothed_curves']+=sum(c['degree']==3 for c in curves)
coordinates=p.round(4).tolist()
ident=hashlib.sha256(json.dumps([a['key'],coordinates],sort_keys=True).encode()).hexdigest()[:20]
props={**a['f']['properties'],'review_status':'unreviewed','consolidation':dict(version=VERSION,
source_ids=a['ids'],inferred_gaps=a['gaps'],max_fit_deviation_m=.12,splines=curves)}
output.append(dict(type='Feature',id='contour-'+ident,properties=props,geometry=dict(type='LineString',coordinates=coordinates)))
progress(3,4)
report.update(output_features=len(output),input_lines=len(lines),output_lines=len(output)-len(other),
inferred_gap_m=round(sum(g['length_m'] for a in chains for g in a['gaps']),4),
trimmed_overlap_m=round(report['trimmed_overlap_m'],3))
result={**document,'features':output,'analysis':{**document.get('analysis',{}),'contour_refinement':{k:v for k,v in report.items() if k not in ('duplicates','removed_noise','joins')}}}
progress(4,4)
return result,report
def refine_file(source, survey, output):
from contour_evidence import SurveyEvidence
output.mkdir(parents=True,exist_ok=True)
def progress(done,total):
p=output/'progress.json.tmp';p.write_text(json.dumps(dict(phase='refining',completed=done,total=total)));p.replace(output/'progress.json')
import scipy, shapely
payload=source.read_bytes()
result,report=consolidate(json.loads(payload),SurveyEvidence(survey),progress)
provenance=dict(raw_map_sha256=hashlib.sha256(payload).hexdigest(),
libraries=dict(shapely=shapely.__version__,scipy=scipy.__version__,networkx=nx.__version__))
report.update(provenance)
result['analysis']['contour_refinement'].update(provenance)
(output/'urban-map.json').write_text(json.dumps(result,ensure_ascii=False,allow_nan=False))
(output/'contour-refinement.json').write_text(json.dumps(report,ensure_ascii=False,indent=2))
print(json.dumps({k:v for k,v in report.items() if k not in ('duplicates','removed_noise','joins')}),flush=True)
if __name__=='__main__':
p=argparse.ArgumentParser()
for name in ('source','survey','output'):p.add_argument('--'+name,type=Path,required=True)
a=p.parse_args();refine_file(a.source,a.survey,a.output)
@@ -0,0 +1,75 @@
"""Run native VMA over the surveyed tiles, then assemble one metric map."""
import argparse
import json
import sys
from pathlib import Path
from types import SimpleNamespace
from vector_map import assemble, digest
def merge(index, documents, request):
# Load geometry after the VMA runtime; this pinned GEOS/CUDA stack is order-sensitive.
from shapely.geometry import box, shape, mapping
features=[]
for tile,document in documents:
low,high=tile['core_bounds'];core=box(*low,*high)
for f in document['features']:
geom=shape(f['geometry'])
if geom.geom_type=='Polygon':
centre=geom.centroid
if not low[0]<=centre.x<high[0] or not low[1]<=centre.y<high[1]:continue
pieces=[geom]
else:
clipped=geom.intersection(core)
pieces=[clipped] if clipped.geom_type=='LineString' else list(getattr(clipped,'geoms',[]))
for j,piece in enumerate(pieces):
if piece.is_empty or piece.geom_type not in ('Polygon','LineString'):continue
if piece.geom_type=='LineString' and piece.length<.25:continue
features.append({**f,'id':f"{tile['id']}-{f['id']}-{j}", 'geometry':json.loads(json.dumps(mapping(piece)))})
if len(features)>20000:raise ValueError('Infrastructure result exceeds feature budget')
# Known gaps are retained as coverage facts; they never become inferred roads.
return dict(schema_version='missioncore.urban-map/v2',type='FeatureCollection',
coordinate_system=dict(frame='scene-local',units='metres',up='Z',georeferenced=False),
source={**request['source'], 'vma_commit':'a6e98e8f704e72499b33da84715ba39e8705e02e', 'weights':__import__('assets').WEIGHTS},coverage=dict(kind='objects-only',cell_m=.05,accepted_cells=0,extent_xy=index['bounds_xy']),
analysis=dict(job_key=request['key'],provider_sha256=request['identity']['provider_sha256'],scope='whole-scene',
tiles_total=len(index['tiles']),tiles_mapped=len(documents),tiles_without_ground=len(index['tiles'])-len(documents),
tiles=[{k:v for k,v in t.items() if k!='job'} for t in index['tiles']]),
review_status='unreviewed',features=features)
def run(root,assets,package,survey=None):
survey=survey or root
request=json.loads((root/'request.json').read_text());index=json.loads((survey/'tile-index.json').read_text())
from infer_vectors import main as infer
documents=[]
for i,tile in enumerate(index['tiles']):
(root/'progress.json.tmp').write_text(json.dumps(dict(phase='vectorizing',completed=i,total=len(index['tiles']))))
(root/'progress.json.tmp').replace(root/'progress.json')
if tile['status']!='surveyed':continue
folder=survey/tile['id'];out=root/tile['id']/'vectors';out.mkdir(parents=True,exist_ok=True)
receipt=out/'vector-receipt.json'
valid=False
if receipt.exists():
old=json.loads(receipt.read_text())
valid=old['source']==digest(folder/'survey-receipt.json') and digest(out/'urban-map.json')==old['result']
if not valid:
sys.argv=['infer_vectors','--image',str(folder/'top.png'),'--assets',str(assets),'--output',str(out)]
infer()
assemble(SimpleNamespace(candidates=out/'candidates.json',job=folder/'job.json',image=folder/'top.png',
geometry=folder/'top.geometry.npz',atlas=folder/'surface-atlas.npz',package=package,output=out))
receipt.write_text(json.dumps(dict(source=digest(folder/'survey-receipt.json'),result=digest(out/'urban-map.json'))))
documents.append((tile,json.loads((out/'urban-map.json').read_text())))
result=merge(index,documents,request)
raw=root/'urban-map.raw.json'
raw.write_text(json.dumps(result,ensure_ascii=False,allow_nan=False))
from refine_contours import refine_file
refine_file(raw,survey,root)
(root/'progress.json.tmp').write_text(json.dumps(dict(phase='assembling',completed=len(index['tiles']),total=len(index['tiles']))))
(root/'progress.json.tmp').replace(root/'progress.json')
result=json.loads((root/'urban-map.json').read_text())
print(json.dumps(dict(features=len(result['features']),tiles=len(index['tiles']),mapped=len(documents))),flush=True)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--assets',type=Path,required=True);p.add_argument('--package',type=Path,required=True)
p.add_argument('--survey',type=Path)
a=p.parse_args();run(a.root,a.assets,a.package,a.survey)
+92
View File
@@ -0,0 +1,92 @@
"""Bounded whole-scene survey. Tile cameras come from measured geometry, never A/B."""
import argparse
import json
import math
from pathlib import Path
import numpy as np
from mapping import render, infer, write_json, digest, unproject, CLASSES
from atlas import fuse
from terrain import load_glb
def plan_tiles(request, vertices, faces):
triangles = vertices[faces]
normals = np.cross(triangles[:,1]-triangles[:,0], triangles[:,2]-triangles[:,0])
flat = np.abs(normals[:,2]) > np.linalg.norm(normals, axis=1)*math.cos(math.radians(25))
samples = np.concatenate([triangles[flat].reshape(-1,3), triangles[flat].mean(1)])
if not len(samples):
raise ValueError('No measured near-horizontal surface in this scene')
bounds = np.array([vertices[:,:2].min(0), vertices[:,:2].max(0)])
origin = np.floor(bounds[0]/40)*40
shape = np.ceil((bounds[1]-origin)/40).astype(int)
if int(np.prod(shape)) > 256:
raise ValueError('Scene exceeds the supported 256-tile analysis envelope')
tiles=[]
for ix in range(shape[0]):
for iy in range(shape[1]):
low=origin+[ix*40,iy*40]; high=low+40; centre=(low+high)/2
local=samples[((samples[:,:2]>=low-10)&(samples[:,:2]<=high+10)).all(1)]
item=dict(id=f'tile-{ix:03d}-{iy:03d}',core_bounds=[low.tolist(),high.tolist()],bounds_xy=[(low-10).tolist(),(high+10).tolist()])
if len(local)<100:
tiles.append(dict(item,status='no-surface'));continue
# Lowest measured flat surface per 2m cell supplies camera candidates.
cells=np.floor((local[:,:2]-(low-10))/2).astype(int)
order=np.argsort(local[:,2]);_,indices=np.unique(cells[order],axis=0,return_index=True)
ground=local[order[indices]]
if len(ground)<8:
tiles.append(dict(item,status='no-surface'));continue
cameras=[];used=set()
for offset in [(-12,-12),(-12,12),(12,-12),(12,12)]:
anchor=centre+offset; index=int(np.argmin(np.linalg.norm(ground[:,:2]-anchor,axis=1)))
eye=ground[index].copy()
if index in used or np.linalg.norm(eye[:2]-anchor)>12:continue
used.add(index)
direction=centre-eye[:2]
if np.linalg.norm(direction)<1:direction=np.array([1.,0.])
direction/=np.linalg.norm(direction)
target_xy=eye[:2]+direction*12
target=ground[np.argmin(np.linalg.norm(ground[:,:2]-target_xy,axis=1))].copy()
target[:2]=target_xy;eye[2]+=1.8
cameras.append(dict(id=f'view-{len(cameras)}',projection='pinhole',size=[800,600],eye=eye.tolist(),target=target.tolist(),fov_degrees=100))
if not cameras:
tiles.append(dict(item,status='no-surface'));continue
top_z=float(local[:,2].max()+25)
top=dict(id='top',projection='ortho',size=[1200,1200],width_m=60,eye=[*centre,top_z],target=[*centre,top_z-1],up=[0,1,0])
job=dict(schema_version='missioncore.urban-mapping-job/v1',source=request['source'],model=request['model'],
bounds_xy=item['bounds_xy'],cell_m=.1,halo_m=25,min_confidence=.65,atlas_only=True,views=[top,*cameras])
tiles.append(dict(item,status='pending',job=job))
return dict(bounds_xy=bounds.tolist(),tiles=tiles)
def run(request, package, output):
terrain=json.loads((package/'terrain.json').read_text())
collider=package/(request['source']['collider_sha256']+'.decoded.glb')
meta=json.loads(collider.with_suffix('.json').read_text())
if meta['source_sha256']!=request['source']['collider_sha256'] or digest(collider)!=meta['sha256']:
raise ValueError('Collider source mismatch')
vertices,faces=load_glb(collider,terrain['collision_rotation'])
index=plan_tiles(request,vertices,faces);del vertices,faces
for i,tile in enumerate(index['tiles']):
write_json(output/'progress.json',dict(phase='survey',completed=i,total=len(index['tiles'])))
if tile['status']!='pending':continue
folder=output/tile['id'];folder.mkdir(exist_ok=True)
job=tile.pop('job');write_json(folder/'job.json',job)
receipt=folder/'survey-receipt.json'
if receipt.exists():
old=json.loads(receipt.read_text())
if old['job_sha256']==digest(folder/'job.json') and all((folder/n).exists() and digest(folder/n)==h for n,h in old['files'].items()):
tile['status']=old['status'];continue
render(job,folder)
infer(job,folder)
fuse(job,folder,unproject,CLASSES,write_json)
atlas=np.load(folder/'surface-atlas.npz',allow_pickle=False)
tile['status']='surveyed' if np.count_nonzero(np.isfinite(atlas['z']))>=100 else 'unobserved-ground'
names=['top.png','top.geometry.npz','surface-atlas.npz']
write_json(receipt,dict(job_sha256=digest(folder/'job.json'),status=tile['status'],files={n:digest(folder/n) for n in names}))
write_json(output/'tile-index.json',index)
write_json(output/'tile-index.json',index)
write_json(output/'progress.json',dict(phase='survey',completed=len(index['tiles']),total=len(index['tiles'])))
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--request',type=Path,required=True);p.add_argument('--package',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
a=p.parse_args();run(json.loads(a.request.read_text()),a.package,a.output)
@@ -0,0 +1,10 @@
{
"schema_version": "missioncore.infrastructure-worker/v1",
"platform": "windows-docker-linux-cuda",
"mapper_image": "sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0",
"vector_image": "sha256:4b5ca7b8b082e469aaffaafa34eef0595de56a3ace6bca120430438c3636ca16",
"semantic_model": "assets/mask2former-mapillary/2cc022513f0012ff47d4438516284fd0946a196a",
"vector_assets": "../urban-mapping/vma-assets",
"maximum_seconds": 21600,
"minimum_free_gib": 12
}
+534
View File
@@ -0,0 +1,534 @@
Urban plan geometry qualification
================================
Offline geometric engines for four observed classes: carriageway, pedestrian
area, building facade, and road marking. Not the installed infrastructure-job
provider. Keep this module outside the production provider identity until the
complete semantic input lifecycle and new map contract are integrated.
plan_coverage.py
Three-label Potts alpha expansion using SciPy integer maximum-flow, followed
by shared GEOS coverage simplification. All adjacent classes use one planar
coverage; no independently rounded polygons or mismatched tile borders.
plan_primitives.py
Exposed frontage envelope from observed first-floor planes, bounded collinear
joining that cannot create facade crossings, and constant-width paint fitting.
Arbitrary symbols keep their observed polygon and holes when a strip model
does not fit. No unseen building footprint closure is generated.
plan_acceptance.py
Executable checks for four classes, finite valid XYZ, shared coverage, facade
crossings and facade/road conflicts. Open partial paint footprints are allowed
only when explicitly typed as such. Route authority remains unassigned.
test_plan_geometry.py
Eleven synthetic checks: all unary label changes, noise versus real obstacles,
passage preservation, shared T junctions and holes, invalid input rejection,
exposed versus recessed planes, unsupported gaps, paint widths, unknown symbols,
false facade joins and spatial conflicts. Run on the qualified mapping image:
python3 -B test_plan_geometry.py
The runtime qualification uses Shapely 2.1.2 / GEOS 3.13.1, rasterio, SciPy,
NumPy and OpenCV. Whole-scene evidence, exact source/runtime hashes, alternative
methods, exports and visual acceptance stay in private simulation qualification
storage. Do not commit private scene data or mistake model agreement for a
surveyed accuracy result. Sampling resolution and fitting tolerances do not
certify physical positioning accuracy or safe rover passage.
Observed-boundary revision (2026-10-11)
--------------------------------------
plan_boundaries.py separates physical interfaces from scan coverage boundaries
and semantic frontiers inside visible data. A missing class is not a physical
street end. It emits open chains and preserves a closed loop only when the
entire loop has physical edge support (for example, an observed traffic island).
It never extrapolates a street or closes the extent of an observation.
frontage_chains.py joins compatible observed facade planes and nearby measured
corners, retaining source plane indices. It does not create building backs.
paint_templates.py qualifies bounded metric A/arrow hypotheses against actual
paint geometry. Narrow lane dashes cannot be accepted as arrow templates.
Model object masks nominate regions; they must not be used as exact paint
footprints, since that fills letter holes and widens lines.
test_observed_plan.py adds eight synthetic regressions for false caps, visible
but unclassified continuations, real islands, facade crossings/gaps and false
arrow classifications. All eight passed in the mapping qualification image.
The whole-scene output is still NOT visually accepted or activated in the
application. Specific open side streets remain under-recognised. Unconstrained
LSD/edge continuation, material-classifier continuation and the SAM2 trials did
not meet visual acceptance; none of those extrapolations is a production
method. Geometry invariants and model confidence do not establish curb accuracy
or complete intersection coverage. Automatic SAM3 geometric re-query of visible
frontiers is under qualification separately from these geometry utilities.
Intersection continuation qualification (2026-10-11)
--------------------------------------------------
The private qualification additionally compared automatic SAM3 visual exemplars,
text-only local windows, direct curb prompts, neighbouring overlapping windows,
longitudinal contour filtering and a joint two-boundary street model. None met
whole-scene visual acceptance. Two junctions gained longer observed branches,
but gaps, class ambiguity and a third incomplete junction remain. Relaxing
Gaussian depth gates introduced false curves and was rejected. Visual box
prompts condition the segmentation; they are not a restriction to an image ROI.
Do not copy these private experiments into the production provider or treat
longer contours, interpolated metres, model scores or passing geometry tests as
intersection acceptance. The installed application map remains unchanged.
Schematic continuity policy (owner correction, 2026-10-11)
---------------------------------------------------------
Internal quality gaps between compatible observed curb anchors are eligible for
interpolation even when the gap itself has no Gaussian evidence. This supersedes
an observation-only interpretation of internal coverage frontiers. External
survey ends remain open; opposite street sides must never be capped together.
Known openings can be protected explicitly; automatic driveway detection is
outside this first pass.
plan_continuity.py composes existing FITPACK smoothing, CubicHermiteSpline,
cKDTree endpoint lookup and GEOS topology checks. It retains source IDs and
explicit inferred spans, pins observed endpoints, and keeps route authority
unassigned. Road evidence is asymmetric: missing evidence permits a hypothesis,
but positive road evidence on both sides, or opposite material sides at the two
anchors, rejects the join. Pass the road_occupancy callback for scene qualification;
geometry-only endpoint compatibility does not establish same-edge identity.
The external scan_domain should exclude unscanned extensions while allowing
internal quality holes. Explicit survey-exterior, scan-limit and known-opening
endpoint tags remain protected. Six metres is the initial configurable join
budget, not a certified range or an owner-imposed permanent limit. The fitting
bound measures displacement from input vectors, not physical survey accuracy.
Run test_plan_continuity.py on Worker. qualify_continuity.py is the offline
adapter for the existing Gaussian render cache. It is not called by the installed
provider. Exact inputs, runtime/source hashes, visual review and execution
receipts belong in private simulation qualification storage. This pass is not
a semantic detector: it cannot repair a falsely identified curb merely by
smoothing or joining it. Whole-scene acceptance remains outstanding.
Shape review after owner feedback (2026-10-11)
--------------------------------------------
The owner identified incorrect turn extents, rounded square entries, unresolved
vehicle/scooter occlusions and missing visible side-street continuations in six
review windows. Continuity counts and displacement from old vectors do not
qualify those shapes. The old two-sided hard semantic/alpha extraction drops
visible interfaces when a neighbouring class is missing; subsequent local
refinement and smoothing inherit that omission and the original radius bias.
plan_shapes.py is an offline primitive utility only. Five synthetic cases in
test_plan_shapes.py passed on Worker: short line, noisy straight, square corner,
local tangent arc between straights, and coordinate translation. This does not
qualify scene boundary detection or independently moved primitive junctions.
Three private Gaussian-image adaptations were visually rejected: pixel-path
edge following; whole-primitive raster scoring; and collinear-LSD continuation.
The last recovered a long continuation candidate but not a reliable curb and
introduced connector steps. They are archived under the private qualification
plan-shape-20261011, not installed as a provider. One adaptation also changed
partition tolerance, so the comparison is not a one-variable ablation.
The next bounded qualification must reconstruct a junction jointly from long
approach supports, paired side-street boundaries, sharp-corner / local-arc /
parking-pocket alternatives and occlusion-aware evidence weights. Coincident
junction positions must be shared parameters, and G1 tangency applies only to
smooth joins. Missing classes are uncertainty, not proof of an opening. Preserve
external open street ends and the owner's internal-gap interpolation policy.
Before whole-scene use, qualify all six feedback cases, including a previously
better case as a regression control, then check overlap seams. No alternative
from this review is accepted or activated. The existing live map is unchanged.
Joint junction qualification (2026-10-11)
----------------------------------------
plan_junctions.py adds analytic line/circular-fillet chains with shared endpoints
and G1 tangency, exact radius-zero corners, bounded local Hermite seam repair,
and a nomination test for detached competing fragments. Fragment nomination is
an ambiguity layer, not semantic deletion: a real narrow island may share that
2D signature. The original geometry must remain available for review.
test_plan_junctions.py has 18 synthetic regressions. They passed on Worker 006,
including left/right normals, overlap rejection, pocket geometry, coordinate
invariance, opposite-curb rejection, anchored local seams, and preservation of
collinear continuations and closed islands during fragment nomination.
qualify_junctions.py is an offline six-window adapter using the existing Gaussian
orthographic render cache, known projections, prior Gaussian-derived vector
proposals and soft material/vehicle masks. It fits paired approaches and local
turns jointly with bounded SciPy Powell searches, multiple initial radii, vehicle
weights and soft road/sidewalk contrast. OpenCV and GEOS supply existing image
and topology operations. No point-cloud input or new trained model is used.
Long reliable approach directions have tighter bounds than incomplete branches.
A short opening is a zero-radius hypothesis; this is not a qualified general
classifier of courtyard entrances. The parallel-pair model also does not cover
all possible street tapers or asymmetric geometry.
The final private qualification is plan-junctions-20261011/f6720ad1c874365f.
It improved the six feedback windows: paired visible continuation at 009,
square entry at 007, local junctions and a repaired pocket seam at 012, a 5.09 m
vehicle-occluded pocket gap at 014, and an 8.08 m scooter-area gap at 022; 023
remained the regression control. Three competing fragments were preserved in a
separate review layer, including two beside the 012 pocket. Every output chain
is simple; there are no inter-chain crossings or closed ends in these windows.
The sole overlap, 022/023, differs by 0.0047909 m in Hausdorff distance. This is
vector consistency, not physical survey accuracy or a test against ground truth.
A hard LSD radius cap and contrast-dominant alternatives were rejected visually.
The final source and output hashes match the Worker receipt; 31 input files are
hashed. The final bounded CPU container took about 10.5 seconds on existing
caches, excluding cache preparation and earlier trials, and was removed with
its reservation released. Keep exact evidence and private scene coordinates in
.runtime/simulation-qualifications, not Git or Ops experiment diaries.
This is still a review candidate, not an installed provider or a complete
whole-scene map. The six outputs overlap and must not simply be concatenated
into a production map. Heights are inherited/interpolated, not refitted, and
route authority remains unassigned. Before integration, construct a common
whole-scene boundary graph with shared junction ownership, qualify remaining
junctions/overlap seams and refit height evidence. Facades and paint templates
were outside this increment. The live map remains unchanged.
Whole-scene curb assembly (2026-10-11)
------------------------------------
plan_scene.py and qualify_scene_assembly.py compose the reviewed local shapes
into one map. qualify_scene_junctions.py enumerates all 27 cache windows with
both road and native semantic masks, preserving the parent curve and its XY
station intervals through clipping, pocket absorption and local joins. Accepted
patches own explicit source intervals; duplicate overlapping window proposals
are rejected, and unconsumed source continuations survive once. Artificial cuts
reconnect only by the same parent/station. No tiled feature concatenation is
used. Previously reviewed windows have precedence; the review ordering carries
no geometric corrections.
A scene-wide continuation pass then resolves short compatible seams and
occluded gaps, retaining source coordinates outside the local seam trims. The
continuity helper's preserve_input option avoids regularizing the accepted
geometry again. Optional bridge validation admits long gaps only with positive
road/sidewalk contrast; unknown short spans remain eligible between compatible
anchors. Four competing fragments remain in separate evidence layers. Source
construction, inherited uncertainty and newly inferred spans survive assembly.
The boundary graph indexes open curb ends and edges, with construction seam
provenance separately; it is not a traversability or rover route graph.
Final private qualification: plan-scene-20261011/1d64edcfeeb7466b. The common map
contains 13 curb chains, 1864.579 m in XY, and preserves all 723 non-curb features
unchanged (736 features total). There are 17 source-interval seams, a further
0.722 m endpoint gap reconciled locally, and global inferred spans totalling
83.444 m (a 7.669 m parking gap and a 75.775 m missing section). The latter has
81% positive road/sidewalk edge samples; this is mask support, not accuracy or
probability. A competing 41.6 m connection across a side-street region was
rejected. All final chains are simple, with no inter-chain crossings or rings.
Fifty focused tests passed on Worker 006: 18 junction, 18 continuity and 14
scene assembly tests. All 10 Worker source hashes and 206 output hashes were
verified after transfer. The input manifest hashes 259 files, including all 68
render windows used in the overview and masks for the 27 fitting windows.
The final bounded CPU run took 43.735 seconds on existing caches; container and
reservation cleanup were confirmed. Reprojection views use identical final
geometry in every window. The canonical service and its 605-feature live map
were preserved.
This increment qualifies common XY assembly, not a complete urban plan. Some
side-street branches remain absent in the input detector; the 017 street taper
is approximated by the paired-direction model, and old long-edge wiggles remain.
Unmatched ends are not automatically evidence of survey limits. Heights remain
inherited/interpolated, route permission unassigned, and facades/paint templates
unqualified by this increment. Direct overlay inspection and static HTML/JS
checks passed; interactive HTML browser QA was unavailable because the browser
policy rejects local file URLs. Exact images, results, receipts and notes live
under .runtime/simulation-qualifications/plan-scene-20261011, not in Git or Ops.
The separate qualify_scene_invariants.py acceptance pass independently verified
source-interval accounting for all 29 parents, no pairwise contacts or overlaps,
26 endpoint nodes / 13 graph edges, unchanged non-curb objects and all 69
inferred spans lying on final geometry. Its receipt is the private
plan-scene-20261011/48773e74e8e8b82f qualification. This script reads the accepted
candidate from /final and its immutable parent map from /continuity; it does not
refit geometry. The reviewed map SHA-256 is
0a78cd9bda60429bd2ea62dba7b2065aef1cc466799c3807bbd93e3885591eb8.
Reviewed-region evidence refinement (2026-10-11)
----------------------------------------------
plan_refinement.py follows image-normal evidence profiles with dynamic
programming, then fits a robust cubic B-spline with pinned endpoint positions
and tangent directions. long_edge_refinement.py uses OpenCV LSD, coherent
line consensus and a Huber fit for long near-straight runs; short bright splat
borders cannot introduce independent local bends into that model.
refinement_evidence.py samples the most central available Gaussian render and
its derived road/sidewalk/vehicle masks across overlapping windows.
For an explicitly owner-confirmed opening, driveway_refinement.py selects a
parallel pair of LSD side anchors using asphalt/paving texture contrast. It
intersects those sides with the existing curb and bounds their visible extent
by a supported transverse frontier. It removes the old cross-opening frontier,
retains two open branch ends, and records the intentional removed interval.
This is not a qualified automatic driveway detector. Missing side support is
an error, not permission to invent an opening.
qualify_refinement.py reads a private review-hints.json from /candidate and
selects relevant cached windows by their bounds. Hints select review regions;
target vertices come from the evidence. It consumes the immutable assembled
baseline at /baseline, Gaussian renders at /survey, and derived masks at
/evidence; outputs go to /out. All scene computation runs on Worker 006.
The qualification refreshes the whole map and endpoint graph, accounts for
baseline curb intervals, preserves prior construction separately, and marks
all newly fitted or extrapolated geometry as inferred. Heights are inherited.
Private qualified candidate: plan-refinement-20261011/5acb71dd0e07276c.
The four owner-marked regions now contain a square-sided driveway, adjusted
parking-pocket transitions and a corrected long curb bow. It has 14 curb
chains (1877.133 m XY), with all 723 non-curb features preserved. All 26 prior
open endpoints survive; the new access adds two. No geometry outside the four
review regions changed, to the 1 micrometre numerical comparison tolerance.
That tolerance measures preservation, not physical accuracy.
61 focused tests passed: 11 refinement and 50 existing geometry/assembly tests.
audit_refinement.py independently checks saved JSON for finite simple curves,
no pair contacts/rings, source-interval accounting including the known opening,
unchanged exterior geometry, graph endpoint/status consistency, and complete
inferred labeling of changed geometry. It verified 28 nodes / 14 edges and 74
inferred spans on the final curves. Source and delivery hashes are verified
against the Worker receipt. Final map SHA-256:
bbbbb647126fe9f4a96c43149acfb97891bd771e4e81b6a1676daf645cc4a18d.
This is a local visual-review candidate. Accuracy against independent ground
truth, general driveway discovery, heights, facades and marking templates are
not qualified here. The unnumbered minor review circles were not individually
refitted. Route permission remains unassigned and the canonical live map was
not replaced. Private images, review coordinates, receipts and intermediate
trials remain under .runtime/simulation-qualifications/plan-refinement-20261011.
Shared physical-boundary qualification (2026-10-11)
--------------------------------------------------
boundary_anchors.py adds scene-independent physical evidence to the existing
Gaussian-derived semantic boundary candidates. It combines OpenCV image
derivatives with height/alpha/vehicle validity, follows normal-profile
candidates with dynamic programming, and uses SciPy sparse weighted smoothing
between supported runs. Missing internal observations are explicitly inferred;
unsupported exterior tails are not extrapolated. The public input interface
contains arrays and metric resolution, with no scene names or review regions.
Multiscale material contrast requires a central oriented edge. Junction fits
use evidence_cost over all samples, so a short visible fragment cannot win by
discarding unsupported samples. plan_continuity.regularize checks the complete
joined chain for simplicity. plan_scene.assemble_checked rejects conflicting
replacement proposals atomically, restoring their complete parent geometry;
conflicts in source geometry fail instead of receiving a clean audit.
The private anchor-pass-20261011 v3 qualification ran the same source hashes
and parameters on all 88 Pokrovka and 68 Maroseyka windows. It reuses the prior
read-only multiview Mapillary evidence and Gaussian render products, without
manual review hints or previous vectors as computation inputs. Both runs
passed the same 92 tests and independent final geometry checks with no pair
contacts or self-intersections. Two internal assembly stations remain unresolved
on Maroseyka. Geometry took about 355 seconds combined, excluding cached rendering
and inference. Canonical live maps were unchanged.
This is NOT a qualified complete urban plan. Full visual review still finds
missing/internal fragments, paint-related false boundaries, car/pocket ambiguity
and false side-entry arcs. Shared execution is demonstrated on two scenes;
accuracy or generalisation to arbitrary streets is not. Review addresses and
all imagery/receipts remain private qualification artifacts, not algorithm
configuration. Do not promote either candidate based on test counts or zero
intersections alone.
Automatic material-context qualification (2026-10-11)
-----------------------------------------------------
material_regions.py uses OpenCV GrabCut with automatic road/sidewalk core
seeds. Its colour mixtures are initialised from definite cores only, then
frozen for the spatial pass. Insufficient seeds explicitly return no material
decision. Enclosed paint holes do not become independent boundary proposals;
observed sidewalk cores protect islands. The boundary_anchors material input
is optional and only ranks candidates; physical anchor confirmation remains
separate. No scene identity, manual ROI or review coordinates enter this API.
The private anchor-pass-20261011 v5 qualification uses the same 50 source-file
hashes and parameters across all 88 Pokrovka and 68 Maroseyka windows. Both
passed the same 98 tests and independent geometry audits, with zero pair
contacts/self-intersections. Geometry took about 371 seconds combined on
cached Gaussian renders and multiview Mapillary scores; rendering/inference
are excluded. All 156 windows were visually reviewed. Live maps are unchanged.
This is an optional research candidate, NOT an accepted replacement for v3
or a complete plan. A preceding hard material gate (v4) was rejected because
it removed valid branches. Soft ranking restores those branches and removes
some false paint/U-shaped fragments, but still leaves internal gaps and can
worsen junction radii. Pokrovka has three unresolved assembly stations;
Maroseyka has zero, which does not imply complete curb coverage. Whole-scene
visual improvement is mixed and independent geometric accuracy is unmeasured.
The integration runner, inputs, images, reviews and receipts remain private
under .runtime/simulation-qualifications/anchor-pass-20261011.
Visibility-aware remaining-gap qualification (2026-10-11)
--------------------------------------------------------
plan_continuity.py optionally limits equivalent cubic Bezier control handles
of SciPy Hermite interpolation. gap_evidence.py treats low-opacity Gaussian
coverage, vehicles and uncertain classes as unknown; observed road/sidewalk
contradictions remain vetoes. It requires two material-separated, directionally
compatible parent approaches. gap_observations.py samples immutable Gaussian
render/class fields. Explicit exterior/opening endpoints, survey-domain,
intersection and reciprocal-choice checks remain in force. All additions are
labelled inferred; endpoint and pair decisions are auditable.
The private v6 qualification adds this pass after unchanged v3 extraction,
junction fitting and assembly. It does not combine the optional v5 GrabCut
experiment. The identical source hashes and parameters were used for both
full scenes, without manual region hints, review priorities or baseline
vectors as computation inputs. Both runs passed 104 tests and independent
no-intersection/full-control-preservation checks. Maroseyka gained three
bridges totalling 69.782 m, reducing 25 chains to 22. Pokrovka stayed at 30
chains with unchanged geometry. Live maps and service 8000 were unchanged.
Visual review covered the new spans and both overview projections; unchanged
control geometry was checked programmatically rather than claiming a fresh
visual pass over every old window. A long scan dropout is now connected, but
an existing parallel parking fragment and a separate vehicle-adjacent gap
remain. This is an improvement to continuity, not a qualified complete plan,
independent accuracy result or proof of arbitrary-scene generalisation.
Private runners, source snapshots, reports and images stay under
.runtime/simulation-qualifications/anchor-pass-20261011.
Evidence-backed parallel-fragment qualification (2026-10-11)
------------------------------------------------------------
boundary_competition.py compares complete detached road-boundary hypotheses
with longer overlapping alternatives. Suppression requires directional overlap
and observed same-material evidence on both sides at 0.25 m and 1 m offsets,
while the retained alternative separates road and sidewalk. Unknown/occluded
observations cannot certify removal. Attached branches, unmatched extensions,
rings and opposite island faces are excluded. Full removed features and all
decisions remain in competition-audit.json. The API accepts metric geometry
and a field sampler, without scene identifiers, manual regions or priorities.
The private anchor-pass-20261011 v8 qualification ran identical source hashes
and parameters over all 88 Pokrovka and 68 Maroseyka windows on Worker006.
Both runs passed 112 tests and independent no-contact/no-self-intersection
audits. Pokrovka retained all v6 geometry; Maroseyka removed one false detached
24.155 m sidewalk fragment. A separate set-difference audit verifies that no
geometry outside the recorded quarantine changed. Visual review covered the
removed fragment and both scene overviews; unchanged areas were verified by
geometry comparison, not presented as a new exhaustive visual review.
The preceding v7 radius-support experiment is rejected as a replacement:
Huber fitting to provisional source curves sharpened some actual rounded
corners and enlarged another. Tests and clean topology did not imply visual
improvement. v8 retains the v6 radius objective and search. All v7 source,
receipts and comparison images remain private for diagnosis; they are not
an accepted radius upgrade.
This accepted increment is limited to detached competing hypotheses. False
segments embedded in longer chains, existing corner errors and remaining
occlusion gaps are unresolved. Existing earlier geometric quarantine passes
are not newly certified by the tests for this module. Generalisation beyond
the two scenes, independent accuracy and height accuracy remain unmeasured.
Research source snapshots, exact cached-input mounts, source hashes, resource
receipts and replay scripts remain under .runtime/simulation-qualifications/
anchor-pass-20261011/operator/reviews/v8. Product runtime/live maps are unchanged.
Resolution and local-shape ablations (2026-10-11/12)
--------------------------------------------------
Two bounded experiments retained the accepted v8 control and used identical
source/configuration hashes across both developed-on scenes. Neither candidate
is promoted. Exact snapshots, receipts, failures and decisions remain under
``.runtime/simulation-qualifications/anchor-pass-20261011/operator/reviews``.
v9 sampled native 4096-pixel Gaussian RGB instead of the existing reduced
RGB fields, retaining the same metric filters. Depth, alpha and semantic
resolution were unchanged. Pokrovka passed 117 tests and topology checks,
but acquired a new assembly failure and visibly enlarged a junction. Maroseyka
stopped on an unresolved source-geometry conflict; it has no accepted final
map. This rejects this RGB-only ablation, not every high-resolution approach.
v10 reobserved physical edge targets around each initial junction, then
compared a corner, circular arc and convex cubic using the same targets.
Straight approaches and terminal extent remained fixed. Both scenes passed
119 tests and topology checks. Pokrovka's assembled map is byte-identical to
v8: local changed proposals did not survive existing assembly checks. Maroseyka
changed 126.645 metres of boundary but retained two old unmatched stations.
All 13 changed Maroseyka windows were reviewed. Some turns improved, while
branch offsets, parking ambiguities and gaps remained; no overall replacement
was accepted. The experimental fitter is retained privately, not published
as the default geometry implementation.
An evaluation-only set of 116 manually marked visible-curb points covers
13 sections in five source windows. It was marked before inspecting v9
outputs and is forbidden as fitting input. It is a regression reference with
approximately 0.20 m annotation uncertainty, not independent surveying or a
complete-map precision/recall benchmark. On Pokrovka, median/p90 distance
changed from 0.268/0.779 m (v8) to 0.501/3.775 m (v9). On Maroseyka it changed
from 0.439/1.495 m (v8) to 0.347/1.474 m (v10), below the predeclared 0.20 m
meaningful-gain threshold. These numbers do not certify map-wide accuracy.
The accepted control remains v8. Altering radius shape alone cannot repair
incorrect branch approaches, and clean topology cannot establish correct
curb placement. A separate held-out scene is required for transfer evidence.
Held-out scan transfer: Smolensk (2026-10-12)
--------------------------------------------
The private ``blind-smolensk-20261011`` qualification completed an offline
Gaussian-only pass from a third registered source package and its original
20,496 scanner poses. The old 490,355-splat cache covered only a small fragment;
the test instead converted the complete registered LOD1 payload (10,243,765
Gaussians). A pose-only uniform survey adapter bootstrapped Gaussian expected
depth, followed by unchanged terrain admission, orthographic observation,
SAM3 occluder masks, multiview Mapillary fusion and frozen v8 geometry.
No collider, point-cloud surface, manual geometry or map-specific ROI was used.
All common v8 source files except the historical-baseline audit are identical.
The observation configuration differs only in source paths/scene identity.
The run processed 39 orthographic windows, 73 stations and 292 street-level
views. All 112 primary geometry tests passed; the final map contains 16 open
chains, 180.278 m total XY length, no self-intersections or pair contacts.
These execution/topology results are supplemented by direct owner review on
2026-10-12. The initial assistant review incorrectly treated degraded roadway
as a reliably visible missing boundary. The owner clarified that the broad
green region is pedestrian space and is correctly segmented; the roadway
above/left of it is poorly visible, and extraction where roadway is visible
is reasonably correct. The blanket transfer-failure conclusion is withdrawn.
This supports limited qualitative transfer to the third scene, not measured
accuracy, complete-road recall or arbitrary-scene acceptance. The initial
review is retained in private review-history, superseded by owner-review.json.
A diagnostic replay produced byte-identical initial geometry and measured
203.880 m of semantic-interface candidates entering physical refinement,
141.368 m surviving that refinement, and 180.278 m after existing continuity.
These are stage-retention lengths, not ground-truth recall. They cannot
establish excessive rejection without a reference limited to genuinely visible
curbs. The owner's visibility clarification removes the basis for diagnosing
this scene as a general extraction failure. Evaluate missing observations
separately from recognition errors. Keep the same algorithm across scenes,
interpolate internal gaps between supported anchors, and leave genuinely
unscanned exterior branches open. No new threshold tuning follows from this
review correction.
The first fusion attempt exposed a missing orchestration dependency on cached
orthographic vehicle masks. It was corrected by running the unchanged pinned
orthographic segmentation stage, then replaying fusion. Both failed and
successful receipts are retained. No semantic or geometry parameters were
tuned after seeing this scan. The original transfer harness retains historical
``parameters_changed`` flags; the independent final-verification record and
source comparison establish that this transfer used frozen v8 parameters.
The private qualification retains complete inputs, source snapshots, runners,
stage receipts, review and unqualified vector output. Native RGB files that
were temporarily archived are restored to all 312 original Worker paths with
SHA-256 verification. Worker containers and reservations are released;
canonical service 8000 and its prior live maps remain unchanged. Nothing from
this qualification has been promoted to the product runtime.
@@ -0,0 +1,66 @@
Gaussian marking pose, pattern extraction and line assembly
=========================================================
Offline continuation of catalog-pass-20261014. One algorithm and metric policy
for all three scenes; Gaussian renders only, no manual processing areas or map
identity in the algorithm. Every computation, test and image render runs on
Worker006. No live deployment, rover command, Git commit or Ops publication.
Changes
-------
* Bicycle registration uses the existing attributed SVG. OpenCV raster scoring
evaluates 24 initial angles, retaining six separated orientations. SciPy
Powell refines centre, angle, dimensions and stroke offset. Rotation is about
the centre rather than the template tail. Image-admission thresholds remain
those of the previous catalogue pass. The expanded pose search requires a
stronger shape score of 0.80: image overlap alone can fit random road texture.
This is a shared class rule, not a location-specific rejection list.
* A native-image chromatic paint channel supplements existing general proposals.
Yellow zigzags can separate from adjacent white lines or letters. Existing
white/general candidates remain available. Colour alone admits nothing:
scikit-image skeleton, OpenCV simplification, regular-leg fit and calibrated
image checks still apply.
* Per-leg negative-space checks exclude other legs of the same complete model.
They still check positive paint and off-pattern pixels. The complete pattern
keeps its original negative-space check. Geometry selects image ownership;
brightness does not choose a favourable view.
* A regular zigzag may continue only while each next leg has complete strong
primary evidence and agrees with every available secondary portion. Unknown,
contradictory and dark continuation stops growth. Existing accepted paint
is preserved during an extension; new neighbor overlaps are forbidden.
* Long lines use the existing two-mosaic chain assembly implementation and its
original thresholds. OpenCV Huber fitting operates on original fragments.
Every edited seam needs two views; real dashed gaps and protected symbols
are barriers. Original non-marking layers remain byte-for-byte identical.
Qualification
-------------
All transactions replay against the accepted catalogue map. Symbol changes and
line joins have separate audits plus a combined audit. Native chromatic
extraction can be reused only when its transitive local import hashes, image
digest and accepted baseline match. Final classification, joins, audit and
rendering use one frozen source bundle across every scene. Containers use the
official recorded-job reservation, no network, a read-only root, bounded CPU,
memory and runtime. Pinned wheels load only into disposable tmpfs.
Limits
------
Real visible symbols may still fail proposal extraction or registration.
These are known-scene regressions, not a holdout generalization benchmark.
Full recall, false-positive rate, geodetic accuracy and GOST compliance are not
measured. Two views of one Gaussian reconstruction are correlated. Old road,
facade and pedestrian-contour errors are outside this marking pass.
Attribution
-----------
Bicycle artwork: Major Alexey, CC BY-SA 4.0. Adaptation: polygon construction,
coordinate normalization and metric registration.
https://commons.wikimedia.org/wiki/File:1.23.3_Russian_road_marking.svg
https://creativecommons.org/licenses/by-sa/4.0/
Original SHA-256: 53f95d4e93d98c2d32a18d407e3189c721e252e5e7912365afdfda6313a78c59
Existing arrow artwork:
https://commons.wikimedia.org/wiki/File:1.18_Russian_road_marking.svg
OpenCV, SciPy, Shapely and scikit-image remain the implementation components.
Exact outcomes and visual limitations are in verification.json and
visual-review.json. Source exports carry pinned wheels and their licences.
@@ -0,0 +1,45 @@
"""Two geometry-selected image mosaics for every point of a finite object.
No demand that both complete camera rectangles contain a long polygon's bbox.
Unknown paint pixels remain unknown; different ranks never use the same tile.
"""
import numpy as np,cv2,shapely
from fit_scene import project
from layer_common import sample
from row_evidence import choose_owners
from discovery_rules import glyph_score
def mosaic_views(p,views,kind=None,parameters=None,negative_context=None):
lo=np.asarray(p.bounds[:2])-1.;hi=np.asarray(p.bounds[2:])+1.;cell=.04
xx=np.arange(lo[0],hi[0],cell);yy=np.arange(lo[1],hi[1],cell);x,y=np.meshgrid(xx,yy);points=np.c_[x.ravel(),y.ravel()]
distance=np.linalg.norm(points[:,None,:]-views.centers[None,:,:],axis=2);coverage=np.zeros(distance.shape,bool)
for i,tile in enumerate(views.tiles):
uv=project(points,views.geometry(tile['id']));coverage[:,i]=(uv.min(1)>=20)&(uv.max(1)<1180)
owners=choose_owners(distance,coverage);ev=[];names=set();target=shapely.contains_xy(p,points[:,0],points[:,1])
for rank in [0,1]:
colors=np.zeros((len(points),3),'uint8');allowed=np.zeros(len(points),bool);covered=np.zeros(len(points),bool);source_counts={}
for i in np.unique(owners[:,rank]):
if i<0:continue
select=np.flatnonzero(owners[:,rank]==i);name=views.tiles[i]['id'];g=views.geometry(name);rgb,vehicle=views.inputs(name);uv=project(points[select],g).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5
def read(a,q):return np.concatenate([cv2.remap(a,b[:,0,None],b[:,1,None],cv2.INTER_LINEAR).reshape(len(b),-1)for b in np.array_split(q,max(1,int(np.ceil(len(q)/20000))))])
colors[select]=read(rgb,native);allowed[select]=(read(g['alpha'].astype('float32'),uv).ravel()>=.65)&(read(vehicle,uv).ravel()<.2)&(sample(views.labels,points[select],views.low,views.high)==1);covered[select]=True
if target[select].any():names.add(name);source_counts[name]=int(target[select].sum())
score=glyph_score(colors.reshape(len(yy),len(xx),3),allowed.reshape(len(yy),len(xx)),points,p,kind=None,parameters=None)
rgb=colors.reshape(len(yy),len(xx),3);gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
bg=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(31,31)))
paint=((gray.astype(float)-bg>15)&(gray>100)&((hsv[:,:,1]<100)|((hsv[:,:,0]>12)&(hsv[:,:,0]<36))))
near=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))).ravel()>0
if negative_context is not None:
# Adjacent legs belong to the same known pattern; they are not
# unexplained paint in this leg's background. The whole pattern
# still receives its original negative-space check.
context=shapely.contains_xy(negative_context.buffer(.08),points[:,0],points[:,1])
region=shapely.contains_xy(p.convex_hull.buffer(.15),points[:,0],points[:,1])
negative=region&~context&allowed&covered
score['negative_paint']=float(paint.ravel()[negative].mean())if negative.any()else 0.
score['negative_space_scope']='exclude-other-legs-of-same-pattern'
known=target&allowed&covered
score['observed_support']=float(near[known].mean())if known.any()else 0.
score.update(paint_valid=float(allowed[target].mean())if target.any()else 0.,paint_coverage=float(covered[target].mean())if target.any()else 0.,source_counts=source_counts,ownership='nearest-covering-geometry-per-pixel',rank=rank)
ev.append(score)
return ev,sorted(names)
@@ -0,0 +1,17 @@
"""Shared assembly policy, with unchanged catalogue image thresholds."""
from catalog_rules import POLICY as CATALOG_POLICY,accept_bicycle as catalogue_bicycle,accept_zigzag
VERSION='marking-assembly-v1'
POLICY={**CATALOG_POLICY,'bicycle_fit_score':.80,'bicycle_initializer':'24-angle-centred-multistart','zigzag_max_added_legs_per_end':12,'zigzag_extension_support':.95,'zigzag_extension_valid':.97,'zigzag_junction_radius_m':.20}
def accept_bicycle(ev,score):
# Wider pose search raises the risk of fitting random road texture.
# Image overlap alone is not a substitute for strong class-shape evidence.
return catalogue_bicycle(ev,score)if score>=POLICY['bicycle_fit_score']else None
def extension_supported(ev):
if len(ev)!=2:return False
first,second=ev
def good(e):
coverage=e['paint_coverage']
return coverage>0 and e['paint_valid']/coverage>=POLICY['zigzag_extension_valid']and e['observed_support']>=POLICY['zigzag_extension_support']and e['negative_paint']<=POLICY['strong_negative_paint']
return first['paint_coverage']==1. and good(first)and(second['paint_coverage']==0. or good(second))
@@ -0,0 +1,52 @@
"""OpenCV raster / SciPy registration with global orientation initialization."""
import numpy as np, cv2, shapely
from shapely.geometry import Polygon
from scipy.optimize import minimize
from catalog_templates import bicycle
def fit_bicycle(p,all_hypotheses=False):
if p.is_empty or p.area<.10:return None
rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);corners=cv2.boxPoints(rect);edges=np.roll(corners,-1,axis=0)-corners;k=np.argmax(np.linalg.norm(edges,axis=1));L=float(np.linalg.norm(edges[k]));W=float(min(rect[1]));u=edges[k]/L;ang=np.arctan2(u[1],u[0]);origin=np.asarray(rect[0]);fill=p.area/max(L*W,1e-6)
if not(1.<L<4.5 and .4<W<2.2 and 1.1<L/W<4 and .10<fill<.70):return None
closed=p.buffer(.04).buffer(-.04)
holes=[Polygon(h)for q in ([closed]if closed.geom_type=='Polygon'else getattr(closed,'geoms',[]))if q.geom_type=='Polygon'for h in q.interiors]
if sum(h.area>.015 for h in holes)<2:return None
cell=.02;lo=np.asarray(p.bounds[:2])-.4;hi=np.asarray(p.bounds[2:])+.4;size=np.ceil((hi-lo)/cell).astype(int)[::-1]
def draw(poly):
m=np.zeros(size,np.uint8)
for q in ([poly]if poly.geom_type=='Polygon'else getattr(poly,'geoms',[])):
if q.is_empty or q.geom_type!='Polygon':continue
cv2.fillPoly(m,[np.rint((np.asarray(q.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1)
for h in q.interiors:cv2.fillPoly(m,[np.rint((np.asarray(h.coords)[:,:2]-lo)/cell).astype('int32')],0)
return m
target=draw(p);kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5));near=cv2.dilate(target,kernel);best=None
def quality(x):
m=draw(bicycle(x,fast=True));wide=cv2.dilate(m,kernel);cover=float((m&near).sum()/max(m.sum(),1));recall=float((wide&target).sum()/max(target.sum(),1));iou=float((m&target).sum()/max((m|target).sum(),1));return cover,recall,.6*2*cover*recall/max(cover+recall,1e-6)+.4*iou
coordinates=shapely.get_coordinates(p)
seeds=[]
# Global orientation search, rotated around the symbol centre. The final
# parameters still use the shared SVG base-point convention.
def from_center(x):
cx,cy,a,ll,ww,b=x
return np.r_[np.array([cx,cy])-ll/2*np.array([np.cos(a),np.sin(a)]),a,ll,ww,b]
for a in np.arange(24)*np.pi/12:
axis=np.array([np.cos(a),np.sin(a)]);normal=np.array([-axis[1],axis[0]])
uv=np.c_[coordinates@axis,coordinates@normal]
for trim in [0.,.02]:
low,high=np.quantile(uv,[trim,1-trim],axis=0);ll,ww=high-low
if min(ll,ww)<.3:continue
center=((low+high)/2)[0]*axis+((low+high)/2)[1]*normal
x=np.r_[center,a,ll,ww,0.];seeds.append((quality(from_center(x))[2],x))
starts=[]
for score,x in sorted(seeds,key=lambda v:-v[0]):
if any(abs(np.arctan2(np.sin(x[2]-q[2]),np.cos(x[2]-q[2])))<np.deg2rad(25)for q in starts):continue
starts.append(x)
if len(starts)==6:break
hypotheses=[]
for x in starts:
cx,cy,a,ll,ww,_=x
bounds=[(cx-.30,cx+.30),(cy-.30,cy+.30),(a-.26,a+.26),(ll*.80,ll*1.20),(ww*.75,ww*1.25),(-.02,.025)]
opt=minimize(lambda z:1-quality(from_center(z))[2],x,method='Powell',bounds=bounds,options=dict(maxiter=40,xtol=.002,ftol=.002))
z=from_center(opt.x if quality(from_center(opt.x))[2]>=quality(from_center(x))[2]else x);q=quality(z)
hypothesis=dict(polygon=bicycle(z),score=q[2],support=q[0],recall=q[1],parameters=z.tolist());hypotheses.append(hypothesis)
return sorted(hypotheses,key=lambda x:-x['score'])if all_hypotheses else max(hypotheses,key=lambda x:x['score'],default=None)
@@ -0,0 +1,18 @@
"""Extend a regular seed only while each additional leg is observed."""
import numpy as np
from shapely.geometry import LineString
from assembly_rules import POLICY
def extend(vertices,width,check):
q=np.asarray(vertices,float);k=np.arange(len(q));X=np.c_[k,(-1.)**k,np.ones(len(k))];coef=np.linalg.lstsq(X,q,rcond=None)[0]
if np.linalg.norm(X@coef-q,axis=1).max()>.01:return dict(vertices=q.tolist(),evidence=[],legs_added=0)
def point(k):return np.array([k,(-1.)**k,1.])@coef
accepted=[];left=[];right=[]
for direction in [-1,1]:
current=q[0]if direction==-1 else q[-1]
for step in range(1,POLICY['zigzag_max_added_legs_per_end']+1):
index=-step if direction==-1 else len(q)-1+step;endpoint=point(index);p=LineString([current,endpoint]).buffer(width/2,cap_style=2,join_style=2)
okay,ev,names=check(p)
if not okay:break
(left if direction==-1 else right).append(endpoint.tolist());accepted.append(dict(direction=direction,step=step,vertices=[current.tolist(),endpoint.tolist()],evidence=ev,source_tiles=names));current=endpoint
return dict(vertices=list(reversed(left))+q.tolist()+right,evidence=accepted,legs_added=len(left)+len(right))
@@ -0,0 +1,42 @@
from pathlib import Path
import json,hashlib,runpy,numpy as np,shapely
from shapely.geometry import shape,LineString
from assembly_rules import POLICY,VERSION,accept_bicycle,accept_zigzag,extension_supported
from assembly_zigzag import extend
from discovery_rules import uncovered
old=json.loads(Path('/fullplan/full-map.json').read_text());intermediate=json.loads(Path('/out/assembly-map.json').read_text());new=json.loads(Path('/out/full-map.json').read_text());rows=json.loads(Path('/out/assembly-additions.json').read_text());current={f['id']:f for f in old['features']}
def poly(f):return shapely.force_2d(shape(f['geometry']))
checks=dict(additions_replay=True,only_paint_changed=True,evidence_passes=True,neighbors_preserved=True)
for r in rows:
ids=r['source_ids'];before=r['before'];after=r['after'];q=poly(after[0]);existing=shapely.union_all([poly(f)for f in current.values()if f['properties']['class']=='road_marking'])
checks['additions_replay']&=r['output_ids']==[f['id']for f in after]and len(after)==1 and all(current.get(f['id'])==f for f in before)and ids==[f['id']for f in before]and all(f['id']not in current for f in after)
checks['only_paint_changed']&=all(f['properties']['class']=='road_marking'for f in before+after)
okay=True;ev=r['evidence']
if r['kind']=='preset-bicycle':
okay=not before and r['lane_context']['passed']and r['lane_context']['supporting_length_m']>=POLICY['bicycle_context_length_m']and accept_bicycle(ev,r['template_fit_score'])==r['evidence_mode']
checks['neighbors_preserved']&=uncovered(q,existing)
elif r['kind']=='regularized-zigzag':
fit=dict(legs=r['leg_count'],fit_residual_m=r['fit_residual_m'],proposal_recall=r['proposal_recall']);okay=not before and accept_zigzag(ev['whole'],ev['legs'],fit)==r['evidence_mode'];checks['neighbors_preserved']&=uncovered(q,existing)
elif r['kind']=='observed-zigzag-extension':
okay=len(before)==1 and before[0]['properties']['subtype']=='zigzag'and len(ev)==r['legs_added']and all(extension_supported(e['evidence'])for e in ev)and extension_supported(r['whole_evidence'])
original=poly(before[0]);params=before[0]['properties'];afterprops=after[0]['properties']
def check(p):
match=next((e for e in ev if p.symmetric_difference(LineString(e['vertices']).buffer(r['width_m']/2,cap_style=2,join_style=2)).area<1e-7),None)
return (bool(match)and extension_supported(match['evidence']),match['evidence']if match else[],match['source_tiles']if match else[])
replay=extend(params['vertices'],params['width_m'],check)
okay&=replay['legs_added']==r['legs_added']and np.allclose(replay['vertices'],afterprops['vertices'])
expected=shapely.union_all([original,LineString(replay['vertices']).buffer(r['width_m']/2,cap_style=2,join_style=2)])
okay&=q.symmetric_difference(expected).area<1e-7 and original.difference(q).area<1e-8
other=shapely.union_all([poly(f)for fid,f in current.items()if fid not in ids and f['properties']['class']=='road_marking']);checks['neighbors_preserved']&=q.difference(original).intersection(other).area<=.005
else:okay=False
checks['evidence_passes']&=bool(okay)
for fid in ids:del current[fid]
for f in after:current[f['id']]=f
checks['intermediate_matches_replay']=current=={f['id']:f for f in intermediate['features']}
joined=runpy.run_path('/candidate/audit_assembly_joins.py')['result'];checks['join_audit_passed']=joined['passed']
features={f['id']:f for f in new['features']};checks['original_nonpaint_unchanged']=all(features.get(f['id'])==f for f in old['features']if f['properties']['class']!='road_marking')
report=json.loads(Path('/out/assembly-report.json').read_text());checks['policy_pinned']=report['policy']==POLICY and report['policy_version']==VERSION
checks['proposal_caches_pinned']=report['proposal_cache_sha256']==hashlib.sha256(Path('/searchplan/search-proposals.json').read_bytes()).hexdigest()and report['catalog_proposals_sha256']==hashlib.sha256(Path('/fullplan/catalog-proposals.json').read_bytes()).hexdigest()and report['chromatic_proposals_sha256']==hashlib.sha256(Path('/out/assembly-proposals.json').read_bytes()).hexdigest()
checks['all_operations_counted']=report['symbol_transactions']==len(rows)and report['changed_segments']==len(json.loads(Path('/out/assembly-rows.json').read_text()))
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=hashlib.sha256(Path('/out/full-map.json').read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False)
Path('/out/assembly-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,33 @@
from pathlib import Path
import json,hashlib,numpy as np,shapely
from shapely.geometry import shape
from row_profiles import POLICY,VERSION,fit_chain
old=json.loads(Path('/out/assembly-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/rows-rows.json').read_text());removed=set(json.loads(Path('/out/rows-replacements.json').read_text())['removed_ids']);original={f['id']:f for f in old['features']};features={f['id']:f for f in new['features']};checks={}
checks['unique_ids']=len(features)==len(new['features'])
checks['unchanged_features_identical']=all(features.get(fid)==f for fid,f in original.items()if fid not in removed)
checks['only_nondashed_linear_replaced']=all(original[fid]['properties'].get('subtype')=='linear_marking'and original[fid]['properties'].get('line_kind')!='dashed'for fid in removed)
checks['every_source_traced']=removed==set(fid for r in rows for fid in r['source_ids'])
checks['disjoint_source_groups']=sum(len(r['source_ids'])for r in rows)==len(removed)
checks['new_outputs_traced']=set(features)-set(original)==set(fid for r in rows for fid in r['output_ids'])
checks['objects_count_closes']=len(features)==len(original)-len(removed)+len(rows)
checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features'])
protected=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties']['class']=='road_marking'and(f['properties'].get('subtype')!='linear_marking' or f['properties'].get('line_kind')=='dashed')])
checks['protected_markings_avoided']=all(shape(features[r['output_ids'][0]]['geometry']).intersection(protected).area<=.005 for r in rows)
def geometry_check(r):
inputs=[shapely.force_2d(shape(original[fid]['geometry']))for fid in r['source_ids']];rec=fit_chain(inputs)
if rec is None or rec['max_axis_displacement_m']>POLICY['max_axis_displacement_m']:return False
p=shapely.force_2d(shape(features[r['output_ids'][0]]['geometry']))
if r['kind']=='whole-row-fit':return p.symmetric_difference(rec['polygon']).area<1e-8
before=shapely.union_all(inputs);domain=shape(r['edit_domain'])
return r['kind']=='preserved-contour-union'and p.symmetric_difference(shapely.union_all([before,domain])).area<1e-8 and p.difference(domain).symmetric_difference(before.difference(domain)).area<1e-8
checks['every_chain_geometry_bounded']=all(geometry_check(r)for r in rows)
def image_evidence(r):
if len(r['views'])!=2 or len(set(r['source_tiles']))<2:return False
def local(v):return v['median_contrast']>=22 and v['longest_visible_dark_run_m']<=.20 and v['ridge_median_offset_m']<=.065 and v['ridge_q90_offset_m']<=.10 and all(s['valid']>=.95 and s['support']>=.9 for s in v['seams'])
full=[local(v)and v['valid']>=.95 and v['support']>=.85 for v in r['views']]
return all(local(v)for v in r['views'])and (all(full)if r['kind']=='whole-row-fit'else any(full))
checks['two_evidence_mosaics_pass_every_seam']=all(image_evidence(r)for r in rows)
checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes()
checks['same_policy']=new['row_refinement']==VERSION and json.loads(Path('/out/rows-report.json').read_text())['policy']==POLICY
result=dict(passed=all(checks.values()),checks=checks,full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False)
Path('/out/rows-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,230 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"root": "simulation/urban-plan-research",
"files": {
"assembly_evidence.py": "assembly_pass/assembly_evidence.py",
"assembly_rules.py": "assembly_pass/assembly_rules.py",
"assembly_templates.py": "assembly_pass/assembly_templates.py",
"assembly_zigzag.py": "assembly_pass/assembly_zigzag.py",
"audit_assembly.py": "assembly_pass/audit_assembly.py",
"audit_assembly_joins.py": "assembly_pass/audit_assembly_joins.py",
"audit_beta.py": "beta_pass/audit_beta.py",
"audit_catalog.py": "catalog_pass/audit_catalog.py",
"audit_completion.py": "completion_pass/audit_completion.py",
"audit_consensus.py": "consensus_pass/audit_consensus.py",
"audit_corridor.py": "corridor_pass/audit_corridor.py",
"audit_discovery.py": "discovery_pass/audit_discovery.py",
"audit_norms.py": "norms_pass/audit_norms.py",
"audit_rows.py": "rows_pass/audit_rows.py",
"audit_search.py": "search_pass/audit_search.py",
"audit_sections.py": "sections_pass/audit_sections.py",
"audit_transitions.py": "transitions_pass/audit_transitions.py",
"beta_profiles.py": "beta_pass/beta_profiles.py",
"bicycle_artwork.py": "catalog_pass/bicycle_artwork.py",
"catalog_context.py": "catalog_pass/catalog_context.py",
"catalog_dependencies.py": "catalog_pass/catalog_dependencies.py",
"catalog_dependency_pins.py": "catalog_pass/catalog_dependency_pins.py",
"catalog_evidence.py": "catalog_pass/catalog_evidence.py",
"catalog_rules.py": "catalog_pass/catalog_rules.py",
"catalog_templates.py": "catalog_pass/catalog_templates.py",
"catalog_zigzag.py": "catalog_pass/catalog_zigzag.py",
"completion_profiles.py": "completion_pass/completion_profiles.py",
"consensus_profiles.py": "consensus_pass/consensus_profiles.py",
"coordinate_cache.py": "orthophoto/coordinate_cache.py",
"corridor_profiles.py": "search_pass/corridor_profiles.py",
"coverage_evidence.py": "corridor_pass/coverage_evidence.py",
"coverage_plan.py": "corridor_pass/coverage_plan.py",
"diagnose_assembly.py": "assembly_pass/diagnose_assembly.py",
"diagnose_corridor.py": "corridor_pass/diagnose_corridor.py",
"diagnose_coverage.py": "corridor_pass/diagnose_coverage.py",
"discovery_evidence.py": "discovery_pass/discovery_evidence.py",
"discovery_rules.py": "discovery_pass/discovery_rules.py",
"extract_assembly.py": "assembly_pass/extract_assembly.py",
"extract_catalog.py": "catalog_pass/extract_catalog.py",
"extract_discovery.py": "discovery_pass/extract_discovery.py",
"extract_search.py": "search_pass/extract_search.py",
"fit_scene.py": "full_plan/fit_scene.py",
"fragment_templates.py": "discovery_pass/fragment_templates.py",
"gost_catalog.py": "norms_pass/gost_catalog.py",
"image_profiles.py": "lines_pass/image_profiles.py",
"inspect_bicycles.py": "catalog_pass/inspect_bicycles.py",
"inspect_catalog.py": "catalog_pass/inspect_catalog.py",
"interval_profiles.py": "intervals_pass/interval_profiles.py",
"join_assembly.py": "assembly_pass/join_assembly.py",
"layer_common.py": "full_plan/layer_common.py",
"line_reconstruction.py": "intervals_pass/line_reconstruction.py",
"mapping.py": "corridor_pass/mapping.py",
"norm_profiles.py": "norms_pass/norm_profiles.py",
"ortho_terrain.py": "orthophoto/ortho_terrain.py",
"paint_templates.py": "continuation_pass/paint_templates.py",
"refine_assembly.py": "assembly_pass/refine_assembly.py",
"refine_beta.py": "beta_pass/refine_beta.py",
"refine_catalog.py": "catalog_pass/refine_catalog.py",
"refine_completion.py": "completion_pass/refine_completion.py",
"refine_consensus.py": "consensus_pass/refine_consensus.py",
"refine_corridor.py": "corridor_pass/refine_corridor.py",
"refine_discovery.py": "discovery_pass/refine_discovery.py",
"refine_norms.py": "norms_pass/refine_norms.py",
"refine_rows.py": "rows_pass/refine_rows.py",
"refine_search.py": "search_pass/refine_search.py",
"refine_sections.py": "sections_pass/refine_sections.py",
"refine_transitions.py": "transitions_pass/refine_transitions.py",
"render_assembly.py": "assembly_pass/render_assembly.py",
"render_beta.py": "beta_pass/render_beta.py",
"render_catalog.py": "catalog_pass/render_catalog.py",
"render_completion.py": "completion_pass/render_completion.py",
"render_consensus.py": "consensus_pass/render_consensus.py",
"render_corridor.py": "corridor_pass/render_corridor.py",
"render_coverage.py": "corridor_pass/render_coverage.py",
"render_discovery.py": "discovery_pass/render_discovery.py",
"render_norms.py": "norms_pass/render_norms.py",
"render_plan.py": "catalog_pass/render_plan.py",
"render_rows.py": "rows_pass/render_rows.py",
"render_search.py": "search_pass/render_search.py",
"render_sections.py": "sections_pass/render_sections.py",
"render_transitions.py": "transitions_pass/render_transitions.py",
"road_glyph_presets.py": "continuation_pass/road_glyph_presets.py",
"row_evidence.py": "corridor_pass/row_evidence.py",
"row_profiles.py": "rows_pass/row_profiles.py",
"search_rules.py": "search_pass/search_rules.py",
"search_views.py": "search_pass/search_views.py",
"section_profiles.py": "sections_pass/section_profiles.py",
"test_assembly.py": "assembly_pass/test_assembly.py",
"test_beta.py": "beta_pass/test_beta.py",
"test_catalog.py": "catalog_pass/test_catalog.py",
"test_completion.py": "completion_pass/test_completion.py",
"test_consensus.py": "consensus_pass/test_consensus.py",
"test_corridor.py": "corridor_pass/test_corridor.py",
"test_discovery.py": "discovery_pass/test_discovery.py",
"test_intervals.py": "intervals_pass/test_intervals.py",
"test_lines.py": "lines_pass/test_lines.py",
"test_norms.py": "norms_pass/test_norms.py",
"test_rows.py": "rows_pass/test_rows.py",
"test_search.py": "search_pass/test_search.py",
"test_sections.py": "sections_pass/test_sections.py",
"test_transitions.py": "transitions_pass/test_transitions.py",
"transition_profiles.py": "transitions_pass/transition_profiles.py",
"validation.py": "corridor_pass/validation.py"
},
"reference_qualification": "assembly-pass-20261014",
"source_snapshot": "696ffe52ca7aecc01171",
"source_sha256": {
"assembly_evidence.py": "0fda82c403f9734ea0b0267504ac82437092d410882dc21417a492de9509c09b",
"assembly_rules.py": "04798c28e0daccc8be5fb045cc736160721308f7c41189f287b97a509999ddbf",
"assembly_templates.py": "41ec0428032ae328d5f46c34702d5b0be43f724e5821278e745554c72326d402",
"assembly_zigzag.py": "dbee99c505381fbdccbecec0817e0ec4e028ac1eb475124829cd58811251b9ca",
"audit_assembly.py": "8defc22e391c330962c503b27c49b9d13cecee90b0170dab1b8372858bda3638",
"audit_assembly_joins.py": "e8a3ded181b69961c8a0a5f88e171ff5ada82f0a43e55c217bb40734e411c094",
"audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f",
"audit_catalog.py": "19d5f0f156c0f90d2e1e2548fee99eee521b76e7152f0b53ae12b43ed48553b2",
"audit_completion.py": "ef6adcfec3e1a4bd894b54a150fe3b8559bf73e94665bb9da6bd68007e90575d",
"audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2",
"audit_corridor.py": "3f792b1830e9097644dd66c38eb2cf7efa11d75a0fda928ffa0a7780afb85bfe",
"audit_discovery.py": "9e5f1bdd0d752d82a52121fe86d4e6fb00068a6af9330a072fe7311a909bc974",
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
"audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01",
"audit_search.py": "0de9929d983c97045444131b9255ec4c256ae652b6adb82551e42b94c4bec0eb",
"audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7",
"audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a",
"beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e",
"bicycle_artwork.py": "2e5220e6e82024c683b65c81695b53fa3070d58eed89d61f5cbda41f6c3c554f",
"catalog_context.py": "f2e654ea068a758be1f929299786559f02672898047893cdc20e6f1cb204bb80",
"catalog_dependencies.py": "d6407445db28f6f15201f4ec09e3401141fca90e11a9cef52392f88175634fca",
"catalog_dependency_pins.py": "93ed9007288440620b8339043f1d5ae74684e39e7c3bd50d94d24f6cf29c9f3a",
"catalog_evidence.py": "6eeb6f18e9dc2fef6f490ba5a09eba64c2021c16dbdf0594921ed5a563d23868",
"catalog_rules.py": "ed0f8e838908bcea9ac1ee15fe13d1b23ac29981428ea6a4bdc097c0226db3cb",
"catalog_templates.py": "05577c611ce5ffa2c21d0f608e728eca13009c994e26913b29f39fdcf584c092",
"catalog_zigzag.py": "2e6a804cd14440afaf27bd0f0c2123afc7bf3ea1c58cd0d49293049f1f3b498f",
"completion_profiles.py": "b01cb280a265f170c2f3823d59d423c0cf11472050678cc4dad716c1f90ff786",
"consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091",
"coordinate_cache.py": "930f8f521ef13c02b589d0c182ab4cf337acc4c213354808d32178bbbea3edf4",
"corridor_profiles.py": "967902dae9137ceddb05708acbb6a7cc1e06977c6d064787a1a651422d2e5672",
"coverage_evidence.py": "1b9c1e4b0c518047ad1eacc6e314132144ae05dcad8cc82dd88b9e1340513497",
"coverage_plan.py": "48e28d6781d5d04e83645ba0a9aa7f0398ae904d26bf2e81caa8d8e741bccdda",
"diagnose_assembly.py": "44ef17e6bdecc9285ae8150ccb5c4dd397006381b34b013ebd3e2ed6c2b34bbc",
"diagnose_corridor.py": "cff89f2a78ff315906b7d40ba1855f0f842afe1f7f74d1d38b7366e2959bcfd6",
"diagnose_coverage.py": "f5305f0c429aea3ba5f18e4261abd64fe8254e53db24323ffcebc152734864b7",
"discovery_evidence.py": "dc7e0594b77f6d3723a965216164427835aa5ae2ff736b5599774c4efbc626eb",
"discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491",
"extract_assembly.py": "d2f1cd5a1fc03b95496b32e024452c3e8ba489a06299a6cba967d4d18a5c3b33",
"extract_catalog.py": "7c3b7de0291f52d9f37590b438d1abb7e37b36665cfb5e9ba4698b78a8f42574",
"extract_discovery.py": "5d2835cde2b9d4d895609ea39be2a94a22e894d0996d525dcc3df7046c33e681",
"extract_search.py": "09b3c0c65d33fdd5025e3436fb1bd5df67d1e359b507f4fae74a7e61754fc92c",
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
"fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7",
"gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537",
"image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8",
"inspect_bicycles.py": "e12964f244645b7a4b2bdb0da5d2bb90e7d49dc35bf2f66c4a8466fabc6836bb",
"inspect_catalog.py": "322aec8f233009eb42703132b220e1e216f8dc8b59aa6bbd27244067e651727d",
"interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345",
"join_assembly.py": "293fd78d10f0ba13b1339a69d737c3f96ef003ea3f6dd63fdf02d14c40fa324f",
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
"line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738",
"mapping.py": "1c6ba0cc111250d73bc0bc282e9cbb7a602921bca931da6441bc9a6daf88b4f4",
"norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7",
"ortho_terrain.py": "9c9cab9d7086144fd1a108db28f796e9d267375d7135d50d5cb3f054eae75213",
"paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6",
"refine_assembly.py": "0da00d12e4bda06760a3fc78fcddb6875012edc046e9f83a00074846031b4939",
"refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831",
"refine_catalog.py": "eeeee4d59066579c1fa8708a1be9d999a481f8f8daf05ec01704897252cc66cb",
"refine_completion.py": "12f424d39a687e8b94823f2e2f7b2f2c95538f3504260b4373c47cc21b29c6e1",
"refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36",
"refine_corridor.py": "fd1c4d4e028a037e32538c26a66f876425088b8b5b2c7ffc8d5dc807eba3290f",
"refine_discovery.py": "6272ca1f5052259fb3c6cfd1f1079e4e5864e1e067d12de7ff36d95857219d7b",
"refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5",
"refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8",
"refine_search.py": "113e8cee4f26d1f6b0bcce516388d046ced0523598ddf7f6f4e4dc365a0d9859",
"refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3",
"refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b",
"render_assembly.py": "b8471dceb42be102eeb1918eb7950e038d3fc9e0ebab0a3b01b3aaea8be710fa",
"render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c",
"render_catalog.py": "58ecb30ac8ddffd1489c93361dc6678c82e4dbbfbe8a6e851a1be395ee40db1b",
"render_completion.py": "5e76d2a6ce41a6be8013f98df33951fe17fc209c078376ebfafe7c60ed0b14a7",
"render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682",
"render_corridor.py": "f6355e3761834fcf811c0cae9dc3ce602e7221afea4f674178d6c29085e87e9f",
"render_coverage.py": "2cba12c09333c242841b174f201c89ffce9e715b78b26b472117ae140ff4157c",
"render_discovery.py": "868ad8eb712f5880e944b0899205a2c0fd6dd0713eb727b1c49dda92b897fa20",
"render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d",
"render_plan.py": "9e702d51c6be09caa456d8e528bd62bc9ec238ca3689a99f38b414dafc193f66",
"render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e",
"render_search.py": "5655641df20c2e4f0849bb35ff4029d806554cc7d3b696d26378ad9d880d0491",
"render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c",
"render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d",
"road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322",
"row_evidence.py": "fec784ab795470d96e48c7022e59d5206b0c07b40d84843cbc058fcc4de896c0",
"row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df",
"search_rules.py": "ca3cab6d24f31460d9912c351c166d89fb1c3b21df620ba1d847543bd7a71f41",
"search_views.py": "8a123558dbef184fc85a92c9547c19644d14681329dbbd0cfeac0032bbd102be",
"section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de",
"test_assembly.py": "80510625a71ea9fc04add883d9a7e40a3bfdcac4251bd702b5507ce76f9bba8f",
"test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b",
"test_catalog.py": "91a8fdbc330cecd5bc354406012852cc46245baf99ba8befdaac164f6b79c1c4",
"test_completion.py": "a3a6a283221ae48ade8fd0cca2f145509fd6bedf8e808967c13438791654a7f1",
"test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7",
"test_corridor.py": "42788835ec88e91a3b92ec7ead4e4c489b01ddf11256b46b7b3722c6b4770703",
"test_discovery.py": "a75ffc22d065201f7023d8e6cfb6dc09204a80f9be607599b85479628a301538",
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a",
"test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f",
"test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449",
"test_search.py": "fc3d874c8a6639bfa007eb8fa4a869e270bddafe317868bed29450c6024f8756",
"test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f",
"test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438",
"transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e",
"validation.py": "ee004220db3cdf2429af2a0e875cd9a63526587422881692ce56fe9d77f5cc2c"
},
"external_dependencies": {
"packaging-24.2-py3-none-any.whl": "09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759",
"scikit_image-0.24.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl": "8579bda9c3f78cb3b3ed8b9425213c53a25fa7e994b7ac01f2440b395babf660",
"imageio-2.36.1-py3-none-any.whl": "20abd2cae58e55ca1af8a8dcf43293336a59adf0391f1917bf8518633cfc2cdf",
"networkx-3.4.2-py3-none-any.whl": "df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5f",
"lazy_loader-0.4-py3-none-any.whl": "342aa8e14d543a154047afb4ba8ef17f5563baad3fc610d7b15b213b0f119efc",
"tifffile-2024.9.20-py3-none-any.whl": "c54dc85bc1065d972cb8a6ffb3181389d597876aa80177933459733e4ed243dd"
},
"external_review_font": {
"name": "review-font.ttf",
"sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9",
"purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP"
},
"deployment": false
}
@@ -0,0 +1,29 @@
"""Exhaustive geometric zigzag proposal review; no manually selected ROI."""
from pathlib import Path
import json,numpy as np,cv2,shapely
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape
from layer_common import O,S,parts
from search_views import SearchViews
from fit_scene import project
from catalog_zigzag import fit_zigzag
proposals=json.loads(Path('/fullplan/catalog-proposals.json').read_text())['glyphs']
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,None,None,None,None);font=ImageFont.truetype('/candidate/review-font.ttf',18);rows=[];frames=[]
for i,r in enumerate(proposals):
p=shape(r['geometry']);rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);L,W=sorted(rect[1],reverse=True)
if not(3<L<60 and .45<W<5 and .03<p.area/(L*W)<.4):continue
fits=[]
for opening in [0.,.025,.04]:
for q in parts(p.buffer(-opening).buffer(opening)if opening else p):
f=fit_zigzag(q)
if f:fits.append(dict(opening_m=opening,**{k:v for k,v in f.items()if k!='polygon'}))
rows.append(dict(proposal=i,source_tile=r['source_tile'],length=L,width=W,fits=fits))
name=r['source_tile'];g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);factor=raw.width/1200;uv=project(shapely.get_coordinates(p),g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(uv.max(0)-uv.min(0))+raw.width*1/60;bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));over=raw.copy();draw=ImageDraw.Draw(over)
for q in parts(p):
for ring in [q.exterior]+list(q.interiors):draw.line([tuple(x)for x in project(ring.coords,g)*factor],fill='#00a9dc',width=2)
frame=Image.new('RGB',(600,340),'white');d=ImageDraw.Draw(frame);frame.paste(raw.crop(bbox).resize((295,295)),(0,40));frame.paste(over.crop(bbox).resize((295,295)),(300,40));d.text((4,4),f'{i} {name} fits={len(fits)}',font=font,fill='black');frames.append(frame)
for start in range(0,len(frames),9):
batch=frames[start:start+9];sheet=Image.new('RGB',(1800,340*int(np.ceil(len(batch)/3))),'white')
for k,im in enumerate(batch):sheet.paste(im,((k%3)*600,(k//3)*340))
sheet.save(O/('zig-review-%03d.jpg'%start),quality=94)
(O/'zig-diagnosis.json').write_text(json.dumps(rows,indent=2));print('ZIG CANDIDATES',len(rows),'FITS',sum(bool(r['fits'])for r in rows),flush=True)
@@ -0,0 +1,54 @@
"""Additional chromatic paint channel, preventing white symbols from joining yellow zigzag seeds."""
from pathlib import Path
import json,time,hashlib
import numpy as np,cv2,shapely
from shapely.geometry import Polygon,mapping,shape
from layer_common import O,S,sample,parts
from fit_scene import world,project
from search_views import SearchViews
cv2.setNumThreads(3);start=time.monotonic()
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];low,high=z['bounds']
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,labels,low,high,None)
def eligible(p):
if p.is_empty or p.area<.08:return False
rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);L,W=sorted(rect[1],reverse=True)
if W<=0:return False
fill=p.area/(L*W)
return (3<L<60 and .45<W<5 and .03<fill<.40)
glyphs=[];reports=[]
for tile in views.tiles:
name=tile['id'];g=views.geometry(name);rgb,raw_vehicle=views.inputs(name);size=rgb.shape[0];mpp=60/size
def xy(uv):return world((np.asarray(uv)+.5)*1200/size-.5,g)
# Sample the road field on the calibrated 1200px grid, then upsample its
# categorical gate. No semantic marking confidence is an admission gate.
yy,xx=np.mgrid[:1200,:1200];points=world(np.c_[xx.ravel(),yy.ravel()],g)
road=(sample(labels,points,low,high)==1).reshape(1200,1200)
allowed=cv2.resize((road&(raw_vehicle<.2)&(g['alpha']>.65)).astype('uint8'),(size,size),interpolation=cv2.INTER_NEAREST)>0
gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV);kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(int(.7/mpp)//2*2+1,)*2)
ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,kernel);binary=((ridge>12)&(gray>90)&(hsv[:,:,1]>35)&(hsv[:,:,0]>10)&(hsv[:,:,0]<38)&allowed).astype('uint8')
cc,hier=cv2.findContours(binary,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE);components=[]
if hier is not None:
for i,c in enumerate(cc):
if hier[0,i,3]>=0 or cv2.contourArea(c)*mpp*mpp<.008:continue
holes=[];j=hier[0,i,2]
while j>=0:
if cv2.contourArea(cc[j])*mpp*mpp>.003:holes.append(xy(cc[j][:,0]))
j=hier[0,j,0]
components.extend(parts(shapely.make_valid(Polygon(xy(c[:,0]),holes))))
union=shapely.union_all(components);candidates=list(components)
for radius in [.08,.16]:
for region in parts(union.buffer(radius).buffer(-radius)):
if eligible(region):candidates.append(union.intersection(region.buffer(.015)))
accepted=[]
for p in candidates:
if not eligible(p):continue
if any(p.intersection(q).area/min(p.area,q.area)>.85 for q in accepted):continue
accepted.append(p);glyphs.append(dict(geometry=mapping(p),source_tile=name))
reports.append(dict(tile=name,proposal_pixels=size,candidates=len(accepted)));print('TILE',name,'CANDIDATES',len(accepted),flush=True)
candidates=[];ordered=sorted([(r,shape(r['geometry']))for r in glyphs],key=lambda v:-v[1].area)
geometries=[p for _,p in ordered];tree=shapely.STRtree(geometries);accepted=set()
for i,(r,p) in enumerate(ordered):
if any(j in accepted and p.intersection(geometries[j]).area/min(p.area,geometries[j].area)>.85 for j in tree.query(p,predicate='intersects')):continue
candidates.append(r);accepted.add(i)
(O/'assembly-proposals.json').write_text(json.dumps(dict(glyphs=candidates,tile_reports=reports,seconds=time.monotonic()-start,baseline_sha256=hashlib.sha256(Path('/fullplan/full-map.json').read_bytes()).hexdigest(),source='all native Gaussian frames; additional yellow channel; no manual regions'),allow_nan=False))
print('PROPOSALS',len(candidates),'SECONDS',time.monotonic()-start,flush=True)
@@ -0,0 +1,62 @@
from pathlib import Path
import os,json,time,hashlib,numpy as np,cv2,shapely
from shapely.geometry import shape
from shapely.ops import transform
from layer_common import O,S,sample,feature
from row_profiles import POLICY,VERSION,pair,fit_chain,check_chain
from search_views import SearchViews
cv2.setNumThreads(3);started=time.monotonic();baseline=O/'assembly-map.json';old=json.loads(baseline.read_text());original={f['id']:f for f in old['features']}
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds']
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
# A known dashed feature is an explicit transition barrier. Existing crosswalks
# and symbols are also protected, as in prior passes.
protected=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties']['class']=='road_marking'and(f['properties'].get('subtype')!='linear_marking' or f['properties'].get('line_kind')=='dashed')])
linear={f['id']:shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties'].get('subtype')=='linear_marking'and f['properties'].get('line_kind')!='dashed'and f['geometry']['type']=='Polygon'}
views=SearchViews(tiles,labels,low,high,protected);current={fid:dict(polygon=p,source_ids=[fid])for fid,p in linear.items()};considered=set();history=[];diagnostics=[]
def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
while True:
candidates=[];entries=sorted(current.items())
for i,(aid,a)in enumerate(entries):
for bid,b in entries[:i]:
identity=tuple(sorted(a['source_ids']+b['source_ids']))
if identity in considered or a['polygon'].distance(b['polygon'])>.56:continue
candidate=pair(a['polygon'],b['polygon'])
if candidate is not None:candidates.append((abs(candidate['gap_m']),identity,aid,bid))
accepted=False
for _,identity,aid,bid in sorted(candidates):
considered.add(identity);rec=fit_chain([linear[fid]for fid in identity])
if rec is None:diagnostics.append(dict(source_ids=identity,reason='whole-chain-geometry'));continue
p=rec['polygon']
if p.intersection(protected).area>.005:diagnostics.append(dict(source_ids=identity,reason='protected-marking'));continue
# Do not make a new overlap with an unselected line. Old overlaps can
# remain for a later evidence-based cleanup; this pass cannot grow them.
before=shapely.union_all([linear[fid]for fid in identity]);novel=p.difference(before)
if any(novel.intersection(q).area>.005 for fid,q in linear.items()if fid not in identity):diagnostics.append(dict(source_ids=identity,reason='new-neighbor-overlap'));continue
readers,used=views.readers(rec['origin'],rec['axis']);okay,ev=check_chain(rec,readers)
diagnostics.append(dict(source_ids=identity,reason='accepted'if okay else 'image-veto',views=ev,source_views=used))
if not okay:continue
p=rec['output_polygon'];novel=p.difference(before)
if p.intersection(protected).area>.005 or any(novel.intersection(q).area>.005 for fid,q in linear.items()if fid not in identity):continue
fid='chain-'+hashlib.sha256('|'.join(identity).encode()).hexdigest()[:20]
current.pop(aid);current.pop(bid);current[fid]=dict(polygon=p,source_ids=list(identity),record=rec,views=ev,source_views=used)
history.append(dict(source_ids=list(identity),chain_id=fid));accepted=True;print('JOIN',len(history),'FRAGMENTS',len(identity),'LENGTH',round(rec['length'],2),flush=True);break
if not accepted:break
if len(history)>1000:raise RuntimeError('Unbounded chain growth')
removed=set();generated=[];rows=[]
for fid,g in current.items():
if len(g['source_ids'])<2:continue
rec=g['record'];ids=g['source_ids'];p=g['polygon'];source_tiles=sorted(set(g['source_views'][0])|set(g['source_views'][1]));removed.update(ids)
f=feature(lift(p),'road_marking',subtype='linear_marking',line_kind='solid',method=VERSION,source_ids=ids,source_tiles=source_tiles,template_width_m=rec['width'],whole_chain_refit=True,assembly_operation=rec['operation'],standard_compliance='not_assessed');generated.append(f)
rows.append(dict(kind=rec['operation'],edit_domain=shapely.geometry.mapping(rec['edit_domain']),source_ids=ids,output_ids=[f['id']],source_tile=source_tiles[0],source_tiles=source_tiles,source_views=g['source_views'],bounds_xy=p.bounds,axis=rec['axis'].tolist(),origin=rec['origin'].tolist(),length_m=rec['length'],width_m=rec['width'],max_axis_displacement_m=rec['max_axis_displacement_m'],seams=rec['seams'],views=g['views'],added_area_m2=p.difference(shapely.union_all([linear[i]for i in ids])).area))
result={**old,'features':[f for f in old['features']if f['id']not in removed]+generated,'row_refinement':VERSION}
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'rows-rows.json').write_text(json.dumps(rows,indent=2));(O/'rows-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'rows-replacements.json').write_text(json.dumps(dict(removed_ids=sorted(removed)),indent=2));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes())
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(rows),merged_fragments=len(removed),final_rows=len(rows),accepted_joins=len(history),whole_row_fits=sum(r['kind']=='whole-row-fit'for r in rows),preserved_contour_unions=sum(r['kind']=='preserved-contour-union'for r in rows),candidate_chains=len(considered),before_linear_objects=sum(f['properties'].get('subtype')=='linear_marking'for f in old['features']),after_linear_objects=sum(f['properties'].get('subtype')=='linear_marking'for f in result['features']),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
(O/'rows-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
combined=json.loads((O/'assembly-additions.json').read_text())
for row in rows:
row['before']=[original[fid]for fid in row['source_ids']];row['after']=[f for f in generated if f['id']in row['output_ids']]
combined+=rows
(O/'assembly-rows.json').write_text(json.dumps(combined,indent=2))
r=json.loads((O/'assembly-report.json').read_text());r.update(symbol_transactions=len(json.loads((O/'assembly-additions.json').read_text())),changed_segments=len(combined),merged_fragments=len(removed),joined_lines=len(rows),join_policy=POLICY,join_policy_version=VERSION);(O/'assembly-report.json').write_text(json.dumps(r,indent=2))
@@ -0,0 +1,97 @@
from pathlib import Path
import os,json,time,hashlib,collections
import numpy as np,cv2,shapely
from shapely.geometry import shape,mapping,LineString,Point
from shapely.ops import transform
from layer_common import O,S,sample,feature,parts
from search_views import SearchViews
from discovery_rules import unpack,uncovered,glyph_context
from discovery_evidence import glyph_views
from assembly_evidence import mosaic_views
from line_reconstruction import rows
from beta_profiles import describe,profiles,section_evidence
from interval_profiles import rectangle
from corridor_profiles import missing_sections
from assembly_templates import fit_bicycle
from catalog_zigzag import fit_zigzag
from assembly_rules import VERSION,POLICY,accept_bicycle,accept_zigzag,extension_supported
from assembly_zigzag import extend
from catalog_context import bicycle_context
cv2.setNumThreads(3);started=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());current={f['id']:f for f in old['features']}
proposal_path=Path('/searchplan/search-proposals.json');proposals=json.loads(proposal_path.read_text())
fresh_path=Path('/fullplan/catalog-proposals.json');fresh=json.loads(fresh_path.read_text())
proposals['glyphs']=fresh['glyphs']
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds']
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
def poly(f):return shapely.force_2d(shape(f['geometry']))
def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
existing=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'])
protected=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'])
views=SearchViews(tiles,labels,low,high,protected);transactions=[];diagnostics=[]
def admit(p,subtype,kind,evidence,names,**extra):
global existing
if not uncovered(p,existing):return False
f=feature(lift(p),'road_marking',subtype=subtype,method=VERSION,source_tile=names[0],source_tiles=names,standard_compliance='not_assessed',**extra)
if f['id']in current:return False
current[f['id']]=f;existing=shapely.union_all([existing,p]);transactions.append(dict(kind=kind,source_ids=[],output_ids=[f['id']],before=[],after=[f],bounds_xy=p.bounds,evidence=evidence,source_tiles=names,**extra));print('ADMIT',len(transactions),subtype,kind,flush=True);return True
for i,r in enumerate(proposals['glyphs']):
p=shape(r['geometry']);fits=fit_bicycle(p,all_hypotheses=True)
if not fits:continue
for fit in fits:
diag={k:v for k,v in fit.items()if k!='polygon'};diag.update(kind='bicycle',proposal=i);diagnostics.append(diag)
if fit['score']<POLICY['bicycle_fit_score']or fit['support']<POLICY['bicycle_fit_support']or fit['recall']<POLICY['bicycle_fit_recall']:continue
p=fit['polygon'];context=bicycle_context(p,fit['parameters'],[unpack(r)for r in proposals['lines']]);diag['lane_context']=context
if not context['passed']:continue
ev,names=mosaic_views(p,views);diag.update(evidence=ev,source_tiles=names)
mode=accept_bicycle(ev,fit['score']);diag['passed']=bool(mode);diag['evidence_mode']=mode
if mode and admit(p,'bicycle','preset-bicycle',ev,names,evidence_mode=mode,template_parameters=fit['parameters'],template_fit_score=fit['score'],lane_context=context,artwork='1.23.3 Russian road marking / Major Alexey / CC BY-SA 4.0'):break
print('BICYCLES DONE',len(diagnostics),flush=True)
# Existing full-image proposals supply connected paint components. A small
# closing joins overlapping proposals, not unknown road segments.
records=[unpack(r)for r in proposals['lines']]
chromatic_path=O/'assembly-proposals.json';chromatic=json.loads(chromatic_path.read_text());assert chromatic['baseline_sha256']==hashlib.sha256(baseline.read_bytes()).hexdigest()
components=[shape(r['geometry'])for r in proposals['glyphs']+chromatic['glyphs']]
components += [r['polygon']for r in records if .6<r['L']<5.5 and .045<r['W']<.30]
groups=parts(shapely.union_all(components).buffer(.055,join_style=2).buffer(-.055,join_style=2))
groups += [p for component in components for p in parts(component)]
for i,p in enumerate(groups):
fit=fit_zigzag(p)
if fit is None:continue
q=fit['polygon'];ev,names=mosaic_views(q,views);leg_ev=[]
for a,b in zip(fit['vertices'],fit['vertices'][1:]):
ee,nn=mosaic_views(LineString([a,b]).buffer(fit['width_m']/2,cap_style=2),views,negative_context=q);leg_ev.append(ee)
mode=accept_zigzag(ev,leg_ev,fit)
diagnostics.append(dict(kind='zigzag',group=i,passed=bool(mode),evidence_mode=mode,evidence=ev,leg_evidence=leg_ev,**{k:v for k,v in fit.items()if k!='polygon'}))
if mode:admit(q,'zigzag','regularized-zigzag',dict(whole=ev,legs=leg_ev),names,evidence_mode=mode,vertices=fit['vertices'],leg_count=fit['legs'],width_m=fit['width_m'],fit_residual_m=fit['fit_residual_m'],proposal_recall=fit['proposal_recall'])
print('ZIGZAGS DONE',len(transactions),flush=True)
# Extend every accepted regular zigzag, including seeds from this pass.
for fid,f in list(current.items()):
props=f['properties']
if props.get('subtype')!='zigzag' or not props.get('vertices'):continue
def check(p):
# End junctions may meet another leg of this same pattern.
d=describe(p)
if d is None:return False,[],[]
ends=[Point(d['origin']+sign*d['length']/2*d['axis']).buffer(POLICY['zigzag_junction_radius_m'])for sign in [-1,1]]
context=shapely.union_all([poly(f),p]+ends)
ev,names=mosaic_views(p,views,negative_context=context);return extension_supported(ev),ev,names
growth=extend(props['vertices'],props['width_m'],check)
if not growth['legs_added']:continue
before=poly(f);q=LineString(growth['vertices']).buffer(props['width_m']/2,cap_style=2,join_style=2);q=shapely.union_all([before,q])
if q.geom_type!='Polygon' or not q.is_valid:continue
whole_evidence,whole_names=mosaic_views(q,views)
if not extension_supported(whole_evidence):continue
novel=q.difference(before);other=shapely.union_all([poly(v)for key,v in current.items()if key!=fid and v['properties']['class']=='road_marking'])
if novel.intersection(other).area>.005:continue
names=sorted(set(props.get('source_tiles',[]))|{n for e in growth['evidence']for n in e['source_tiles']})
metadata={k:v for k,v in props.items()if k not in ['class','method','source_tile','source_tiles','vertices','leg_count','source_ids','extension_evidence','extended_from']}
out=feature(lift(q),'road_marking',method=VERSION,source_tile=names[0],source_tiles=names,vertices=growth['vertices'],leg_count=len(growth['vertices'])-1,source_ids=[fid],extended_from=fid,**metadata)
del current[fid];current[out['id']]=out
transactions.append(dict(kind='observed-zigzag-extension',source_ids=[fid],output_ids=[out['id']],before=[f],after=[out],bounds_xy=q.bounds,source_tiles=names,evidence=growth['evidence'],whole_evidence=whole_evidence,legs_added=growth['legs_added'],width_m=props['width_m']))
existing=shapely.union_all([existing,q]);print('EXTENDED',growth['legs_added'],'LEGS',flush=True)
result={**old,'features':list(current.values()),'assembly_refinement':VERSION};(O/'assembly-map.json').write_text(json.dumps(result,allow_nan=False));(O/'assembly-additions.json').write_text(json.dumps(transactions,indent=2,allow_nan=False));(O/'assembly-diagnostics.json').write_text(json.dumps(diagnostics,indent=2,allow_nan=False));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes())
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),proposal_cache_sha256=hashlib.sha256(proposal_path.read_bytes()).hexdigest(),catalog_proposals_sha256=hashlib.sha256(fresh_path.read_bytes()).hexdigest(),chromatic_proposals_sha256=hashlib.sha256(chromatic_path.read_bytes()).hexdigest(),proposal_cache_baseline_sha256=proposals['baseline_sha256'],changed_segments=len(transactions),added_objects=sum(not r['before']for r in transactions),added_subtypes=dict(collections.Counter(r['after'][0]['properties']['subtype']for r in transactions if not r['before'])),stages=dict(collections.Counter(r['kind']for r in transactions)),zigzag_legs_added=sum(r.get('legs_added',0)for r in transactions),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
(O/'assembly-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
@@ -0,0 +1,33 @@
from pathlib import Path
import os,json,shutil
from datetime import datetime,timezone
import numpy as np,shapely
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape
from layer_common import O,S
from search_views import SearchViews
from fit_scene import project
old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'assembly-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23)
for p in O.glob('assembly-*.jpg'):
h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name)
def draw(im,g,features):
im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200
for f in features:
if f['properties'].get('class')!='road_marking':continue
for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2)))
return im
views=SearchViews(tiles,None,None,None,None);tiles=views.tiles
frames=[];manifest=[];loaded={}
for gi,rec in enumerate(groups):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id']
if name not in loaded:
g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))}
g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]):
frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640')
fn='assembly-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects']))
for start in range(0,len(frames),4):
part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white')
for k,im in enumerate(part):sheet.paste(im,(0,k*655))
sheet.save(O/('assembly-proof-%03d.jpg'%(start//4+1)),quality=94)
(O/'assembly-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True)
@@ -0,0 +1,38 @@
import runpy,json,numpy as np,shapely
from shapely.geometry import box,LineString
from shapely.affinity import rotate,translate
from catalog_templates import bicycle
from assembly_templates import fit_bicycle
from assembly_zigzag import extend
from assembly_rules import extension_supported
catalog_scope=runpy.run_path('/candidate/test_catalog.py');prior=catalog_scope['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()}
for angle,L,W in [(0.41,.75,1.4),(1.13,1.5,.85),(2.85,.85,1.6)]:
p=bicycle([24,-17,angle,L,W,0]);fit=fit_bicycle(p)
checks['global_bicycle_pose_'+str(angle)]=fit is not None and fit['score']>.85 and fit['polygon'].symmetric_difference(p).area/p.area<.30
q=np.array([(0,0),(2,2),(4,0),(6,2),(8,0)],float)
strong=dict(paint_coverage=1.,paint_valid=1.,observed_support=.99,negative_paint=.02)
absent=dict(paint_coverage=0.,paint_valid=0.,observed_support=0.,negative_paint=1.)
checks['zig_extension_strong_complete_view']=extension_supported([strong,absent])
checks['zig_extension_incomplete_primary_rejected']=not extension_supported([{**strong,'paint_coverage':.9},absent])
checks['zig_extension_contradiction_rejected']=not extension_supported([strong,{**strong,'observed_support':.3}])
checks['zig_extension_unknown_primary_rejected']=not extension_supported([{**strong,'paint_valid':.5},absent])
observed=LineString([(-4,0),(-2,2)]+q.tolist()+[(10,2),(12,0)]).buffer(.075,cap_style=2,join_style=2)
def check(p):return p.difference(observed).area<1e-7,[strong,absent],['synthetic']
g=extend(q,.12,check);checks['zig_extension_stops_at_observed_ends']=g['legs_added']==4 and np.allclose(g['vertices'][0],[-4,0])and np.allclose(g['vertices'][-1],[12,0])
g=extend(q,.12,lambda p:(False,[],[]));checks['zig_extension_no_evidence_no_growth']=g['legs_added']==0 and g['vertices']==q.tolist()
rotated=rotate(observed,37,origin=(0,0));a=np.deg2rad(37);R=np.array([[np.cos(a),-np.sin(a)],[np.sin(a),np.cos(a)]]);g=extend(q@R.T,.12,lambda p:(p.difference(rotated).area<1e-7,[strong,absent],['synthetic']));checks['zig_extension_rotation_invariant']=g['legs_added']==4
from assembly_evidence import mosaic_views
fv=catalog_scope['FakeViews']([0,5]);leg=box(-.5,-.06,.5,.06);context=box(-5,-.06,5,.06)
plain,_=mosaic_views(leg,fv);aware,_=mosaic_views(leg,fv,negative_context=context)
checks['adjacent_known_pattern_is_not_background_error']=all(b['negative_paint']<a['negative_paint']for a,b in zip(plain,aware))
checks['pattern_context_does_not_relax_positive_support']=all(a['support']==b['support']and a['paint_valid']==b['paint_valid']for a,b in zip(plain,aware))
original=fv.inputs
def dirty(name):
rgb,vehicle=original(name);rgb[603:605]=225;return rgb,vehicle
fv.inputs=dirty;noise,_=mosaic_views(leg,fv,negative_context=context)
checks['off_pattern_paint_remains_negative_evidence']=all(n['negative_paint']>a['negative_paint']for n,a in zip(noise,aware))
from assembly_rules import accept_bicycle
complete={**strong,'support':1.,'recall':1.}
checks['bicycle_image_support_cannot_rescue_weak_shape']=accept_bicycle([complete,complete],.75)is None
checks['bicycle_strong_shape_and_image_can_pass']=accept_bicycle([complete,complete],.85)is not None
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/assembly-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(dict(passed=result['passed'],tests=len(checks),failed=[k for k,v in checks.items()if not v])));assert result['passed']
@@ -0,0 +1,54 @@
"""Independent checks of the saved candidate; never refits geometry."""
import numpy as np
from shapely.geometry import shape,box,LineString
from shapely.ops import unary_union
def audit(base,result,hints,reports,graph):
old=[f for f in base['features']if f['properties']['class']=='road_boundary']
new=[f for f in result['features']if f['properties']['class']=='road_boundary']
other=lambda doc:[f for f in doc['features']if f['properties']['class']!='road_boundary']
assert other(base)==other(result)
assert base['source']==result['source']and base['coordinate_system']==result['coordinate_system']
geoms=[shape(f['geometry'])for f in new]
assert all(g.is_simple and not g.is_ring and np.isfinite(g.coords).all()for g in geoms)
contacts=[(new[i]['id'],new[j]['id'])for i,a in enumerate(geoms)for j in range(i+1,len(geoms))if a.intersects(geoms[j])]
assert not contacts,contacts
reviewed=unary_union([box(*h['bounds'])for h in hints['cases']])
before=unary_union([shape(f['geometry'])for f in old]);after=unary_union(geoms)
outside_before=before.difference(reviewed);outside_after=after.difference(reviewed)
lost=outside_before.difference(outside_after.buffer(1e-6)).length;added=outside_after.difference(outside_before.buffer(1e-6)).length
assert lost<1e-5 and added<1e-5,(lost,added)
oldends=[f['geometry']['coordinates'][i]for f in old for i in(0,-1)]
newends=[f['geometry']['coordinates'][i]for f in new for i in(0,-1)]
assert all(p in newends for p in oldends)
assert len(newends)==len(oldends)+2
accounting=[]
for f in old:
intervals=[]
for n in new:
for part in n['properties']['construction']:
intervals.extend(p['interval_m']for p in part['parents']if p['id']==f['id'])
openings=[r['opening']['source_interval_m']for r in reports if r['feature_id']==f['id']and'opening'in r]
cursor=0.;overlap=0.;gap=0.
for a,b in sorted(intervals+openings):
overlap+=max(0.,cursor-a);gap+=max(0.,a-cursor);cursor=max(cursor,b)
gap+=max(0.,shape(f['geometry']).length-cursor)
assert gap<1e-5 and overlap<1e-5,(f['id'],gap,overlap)
accounting.append(dict(id=f['id'],unaccounted_m=gap,duplicate_m=overlap,retained_intervals=intervals,known_opening_intervals=openings))
spans=[]
for f,g in zip(new,geoms):
for span in f['properties'].get('inferred_spans',[]):
s=LineString(span['coordinates']);assert s.difference(g.buffer(1e-6)).length<1e-5,(f['id'],span['method']);spans.append(s)
changed=after.difference(before.buffer(1e-6));unmarked=changed.difference(unary_union(spans).buffer(2e-6)).length
assert unmarked<1e-4,unmarked
nodes={n['id']:n for n in graph['nodes']};assert len(graph['edges'])==len(new)
features={f['id']:f for f in new}
for e in graph['edges']:
assert e['geometry']==features[e['id']]['geometry']
assert nodes[e['start_node']]['coordinates']==e['geometry']['coordinates'][0]
assert nodes[e['end_node']]['coordinates']==e['geometry']['coordinates'][-1]
props=features[e['id']]['properties']
assert nodes[e['start_node']]['status']==props.get('start_reason','open-curb-end')
assert nodes[e['end_node']]['status']==props.get('end_reason','open-curb-end')
assert graph['route_permission']==result['route_permission']=='unassigned'
return dict(status='passed',curb_chains=len(new),total_features=len(result['features']),length_xy_m=sum(g.length for g in geoms),non_curbs_unchanged=len(other(base)),self_intersections=0,pair_contacts=0,rings=0,prior_endpoints_preserved=len(oldends),new_open_access_ends=2,changed_outside_review_m=lost+added,unmarked_new_geometry_m=unmarked,inferred_spans=len(spans),graph_nodes=len(nodes),graph_edges=len(graph['edges']),source_accounting=accounting)
@@ -0,0 +1,81 @@
Whole-map linear marking batch, 2026-10-12
========================================
This offline research candidate processes the rows-pass-20261012 maps with a
single common policy. It is not a live map deployment or a general urban-map
acceptance. Roads, sidewalks, facades, crosswalks and symbols are preserved.
Stages in refine_beta.py
-----------------------
1. All eligible existing linear objects seed a Gaussian image search, extending
12 metres beyond each endpoint. Every profile uses two spatially selected
evidence mosaics. Their sources are selected by coverage and distance before
reading paint intensity. They are distinct renders of the same reconstruction.
2. OpenCV transverse background removal, SciPy prominence/width measurements and
the existing robust periodic-row fitter discover bounded short/long dash rows.
Both views must contain actual stroke edges. Constant spacing cannot authorize
a missing observation. Short rows need four strokes, long rows three. Rhythm
changes and unknown observations bound accepted subsequences. A faint paint
underlay requires an observed prominent peak sequence and contrast drop in
both views. Output stroke width, phase and period come from the scene.
3. Solid endpoints may move by 0.12 to 2 metres only with observed paint inside,
a dark interval outside, and support throughout the edit in both views.
The full transverse corridor is checked before shortening a line; sideways
drift cannot be interpreted as a paint ending. Confirmed dark edge padding
can absorb obsolete tiny end caps when replacing a periodic family.
Missing alpha/road coverage, vehicles and protected symbols are unknown.
4. The qualified whole-chain assembler joins compatible solid fragments only
across image-supported seams, with known dashed objects acting as barriers.
No scene-specific coordinates, manually selected detector ROI, point cloud,
collider, external road geometry, or street-specific threshold is used. The scene
selector chooses paths only. Additional Gaussian rendering was not performed.
Geometry and audit
------------------
Each transaction records exact input/output features, edit domain, image evidence
and source tiles. Changes are limited to selected linear marking features.
Longitudinal residuals retain original XY outside accepted intervals; output Z
is sampled from the existing Gaussian-derived height field. All other features
are preserved byte-for-byte as JSON objects. Newly added overlaps with neighboring
markings are vetoed. Source IDs and transaction replay reconstruct the output.
The audit checks transaction replay, finite valid XYZ, unchanged other layers,
protected paint, overlap growth, outside-interval preservation, common policy,
and numerical evidence gates. Controlled tests include all prior line passes.
The fourth stage can yield zero edits; execution is not a claim of additional
assembly improvement on each scene.
Each accepted dash family retains a dimensional association with the existing
GOST catalog; dimensions and phase are not forced to nominal values.
The existing GOST crosswalk assessment is retained unchanged. Measurement remains
authoritative; no legal compliance or surveying accuracy is claimed.
Reproduction
------------
Use the canonical Mission Core checkout and the recorded Worker006 qualification
runner. bundle.json references unchanged modules in their canonical locations;
new modules live in beta_pass. The qualified staging snapshot contains all Python
files and the pinned review font. The source ZIP excludes the external font.
Private cached Gaussian RGB/geometry/vehicle masks, Gaussian-derived semantic and
height fields, accepted baseline maps and the pinned Docker image are required.
An identical frozen source bundle is evaluated on Maroseyka, Pokrovka and Smolensk.
Runner constraints: Worker006, 4 CPU, 20 GiB, network none, read-only root,
1 GiB tmpfs, no capabilities, 1800-second stage bound, canonical queue reservation
and explicit resource release. The Mac only orchestrates, copies and views results.
Qualification receipts, input hashes, map audits, JPG comparisons and transaction
JSON are retained with the result. The number of changed objects is not accuracy.
Limitations
-----------
Discovery needs at least one existing approximately aligned linear seed. Curved
rows, fully missed disconnected rows, symbols, arrows, road/facade reconstruction,
and additional rendering are outside this batch. Two-view gating may retain a
known defect where evidence is incomplete. This is conservative missing-evidence
handling, not proof that the unchanged geometry is correct. Qualitative review of
edits does not establish exhaustive detection recall on these or unseen scenes.
@@ -0,0 +1,45 @@
from pathlib import Path
import json,hashlib,numpy as np,shapely
from shapely.geometry import shape
from beta_profiles import POLICY,VERSION,supported
old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/beta-rows.json').read_text());current={f['id']:f for f in old['features']};checks={}
def poly(f):return shapely.force_2d(shape(f['geometry']))
protected=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'])
checks['transaction_replay']=True;checks['only_linear_objects_replaced']=True;checks['no_new_neighbor_overlap']=True;checks['protected_paint_preserved']=True;checks['evidence_passes']=True;checks['outside_edit_interval_preserved']=True
for r in rows:
before=r['before'];after=r['after'];ids=r['source_ids']
checks['transaction_replay']&=all(current.get(f['id'])==f for f in before)and ids==[f['id']for f in before]and r['output_ids']==[f['id']for f in after]
checks['only_linear_objects_replaced']&=all(f['properties'].get('subtype')=='linear_marking'for f in before+after)
a=shapely.union_all([poly(f)for f in before]);b=shapely.union_all([poly(f)for f in after]);novel=b.difference(a)
checks['protected_paint_preserved']&=novel.intersection(protected).area<=POLICY['max_new_neighbor_overlap_m2']
checks['no_new_neighbor_overlap']&=all(novel.intersection(poly(f)).area<=POLICY['max_new_neighbor_overlap_m2']for i,f in current.items()if i not in ids and f['properties'].get('subtype')=='linear_marking')
ev=r['evidence'];ok=len(r['source_views'])==2 and len(r['source_tiles'])>=2
if r['kind']=='periodic-row':
ok&=len(ev['paint'])==2*len(ev['observations'])and all(supported(e)for e in ev['paint'])
ok&=len(ev['gaps'])==2*(len(ev['observations'])-1)
ok&=all(supported(e,False)if ev['mode']=='intervals'else e['valid']>=.95 and e['contrast_drop']>=18 and e['contrast']<(e['contrast']+e['contrast_drop'])*.65 for e in ev['gaps'])
ok&=all(len(e['edges'])==2 and max(abs(e['edges'][0][k]-e['edges'][1][k])for k in [0,1])<=POLICY['max_edge_disagreement_m']for e in ev['observations'])
ok&=all(e['padding']<=POLICY['max_family_edge_padding_m']and len(e['views'])==2 and all(v.get('full_corridor')and supported(v,False)for v in e['views'])for e in ev['edges'])
# The transverse replacement section is wider than the modeled stripe;
# the outside longitudinal old contours must nevertheless be exact.
from interval_profiles import rectangle
d=shape(r['edit_domain']);o=np.array(r['origin']);u=np.array(r['axis']);tt=(np.asarray(d.exterior.coords)-o)@u;domain=rectangle(o,u,float(tt.min()),float(tt.max()),2.)
checks['outside_edit_interval_preserved']&=a.difference(domain.buffer(1e-7)).symmetric_difference(b.difference(domain.buffer(1e-7))).area<1e-7
elif r['kind']=='solid-endpoints':
ok&=all(len(e['evidence'])==2 and POLICY['min_endpoint_change_m']<=abs(e['delta'])<=POLICY['max_endpoint_change_m']and all(supported(v['paint'])and supported(v['dark'],False)and supported(v['edit'],e['kind']=='extend-solid')for v in e['evidence'])for e in ev)
ok&=all(v['dark'].get('full_corridor')and(e['kind']=='extend-solid'or v['edit'].get('full_corridor'))for e in ev for v in e['evidence'])
domain=shape(r['edit_domain']);checks['outside_edit_interval_preserved']&=a.difference(domain.buffer(1e-7)).symmetric_difference(b.difference(domain.buffer(1e-7))).area<1e-7
elif r['kind']=='assembled-row':
ok&=len(ev)==2 and r['max_axis_displacement_m']<=.065 and all(v['local_evidence_passed']for v in ev)and any(v['passed']for v in ev)
else:ok=False
checks['evidence_passes']&=ok
for i in ids:current.pop(i,None)
for f in after:current[f['id']]=f
features={f['id']:f for f in new['features']};checks['final_map_matches_replay']=features==current;checks['unique_ids']=len(features)==len(new['features'])
checks['unchanged_other_layers']=all(features.get(f['id'])==f for f in old['features']if f['properties'].get('subtype')!='linear_marking')
checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features'])
checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes()
report=json.loads(Path('/out/beta-report.json').read_text());checks['same_policy']=new['beta_refinement']==VERSION and report['policy']==POLICY
checks['every_operation_counted']=report['changed_segments']==len(rows)and sum(report['stages'].values())==len(rows)
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False)
Path('/out/beta-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,181 @@
"""Row-scale paint interpretation using shared, metric image-evidence rules.
OpenCV background subtraction, SciPy peaks/robust fitting and the existing
periodic-row fitter are reused. Both geometrically selected Gaussian mosaics
must support each edit. They are two renders, not independent physical scans.
"""
import numpy as np
from scipy.ndimage import gaussian_filter1d
from scipy.signal import find_peaks, peak_widths
from interval_profiles import strip, runs, rectangle
from line_reconstruction import observation, reconstruct
VERSION='paint-row-batch-v1'
POLICY=dict(step_m=.025, extension_m=12., max_seed_length_m=70.,
max_seed_width_m=.35, min_seed_length_m=.30, normal_half_width_m=.7,
max_ridge_offset_m=.13, max_view_offset_disagreement_m=.05,
min_valid=.95, min_bright=.82, min_contrast=22., min_dark=.85,
max_edge_disagreement_m=.20, max_phase_error_m=.20,
min_short_strokes=4,min_long_strokes=3,max_dash_length_m=10.5,
min_dash_length_m=.26,max_crack_m=.125,min_gap_m=.12,
max_endpoint_change_m=2.,min_endpoint_change_m=.12,
max_new_neighbor_overlap_m2=.005,min_material_change_m2=.015,
endpoint_dark_corridor_m=.20,max_endpoint_ridge_offset_m=.065,
max_family_edge_padding_m=.20)
def describe(poly):
if poly.geom_type!='Polygon':return None
z=observation(np.asarray(poly.exterior.coords),'seed')
if not POLICY['min_seed_length_m']<=z['L']<=POLICY['max_seed_length_m'] or z['W']>POLICY['max_seed_width_m']:return None
u=z['axis'].astype(float);u/=np.linalg.norm(u)
return dict(origin=z['center'].astype(float),axis=u,length=float(z['L']),width=float(z['W']))
def profiles(seed,readers,extension=None):
if len(readers)!=2:return None
o,u=seed['origin'],seed['axis'];step=POLICY['step_m'];ext=POLICY['extension_m']if extension is None else extension
ts=np.arange(-seed['length']/2-ext,seed['length']/2+ext+step/2,step)
ns=np.arange(-POLICY['normal_half_width_m'],POLICY['normal_half_width_m']+step/2,step)
result=[]
for read in readers:
contrast,allowed=strip(o,u,ts,ns,read)
central=abs(ts)<=max(seed['length']/2,1.)
transverse=np.quantile(np.where(allowed[central],contrast[central],0),.8,axis=0)
pk,_=find_peaks(transverse,height=18,prominence=8,distance=4)
pk=[k for k in pk if abs(ns[k])<=POLICY['max_ridge_offset_m']]
if not pk:return None
k=min(pk,key=lambda k:abs(ns[k]));pw=peak_widths(transverse,[k],rel_height=.5)[0][0]*step
if not .045<=pw<=.35:return None
band=abs(ns-ns[k])<=.04
sig=gaussian_filter1d(np.median(contrast[:,band],axis=1),1)
valid=allowed[:,band].all(1)
level=float(np.quantile(sig[central&valid],.8))if np.any(central&valid)else 0.
if level<POLICY['min_contrast']:return None
cut=max(15.,.35*level)
paint=(sig>cut)&valid
for a,b in runs(~paint):
if a>0 and b<len(ts)and(b-a)*step<=POLICY['max_crack_m']and valid[a:b].all():paint[a:b]=True
intervals=[(float(ts[a]-step/2),float(ts[b-1]+step/2))for a,b in runs(paint)if(b-a)*step>=POLICY['min_dash_length_m']]
peaks,_=find_peaks(np.where(valid,sig,0),prominence=18,distance=int(.45/step))
widths=peak_widths(np.where(valid,sig,0),peaks,rel_height=.5)
peak_intervals=[(float(ts[0]+widths[2][j]*step),float(ts[0]+widths[3][j]*step))for j in range(len(peaks))if .26<widths[0][j]*step<1.4]
result.append(dict(ts=ts,ns=ns,contrast=contrast,allowed=allowed,signal=sig,valid=valid,cut=cut,level=level,offset=float(ns[k]),width=float(pw),intervals=intervals,peak_intervals=peak_intervals))
if abs(result[0]['offset']-result[1]['offset'])>POLICY['max_view_offset_disagreement_m']:return None
return result
def section_evidence(v,lo,hi,bright=True):
sel=(v['ts']>=lo)&(v['ts']<=hi)
if sel.sum()<3:return dict(valid=0.,support=0.,contrast=0.)
sig=v['signal'][sel]
return dict(valid=float(v['valid'][sel].mean()),support=float((sig>v['cut']).mean()if bright else(sig<v['cut']).mean()),contrast=float(np.median(sig)))
def supported(ev,bright=True):
return ev['valid']>=POLICY['min_valid'] and ev['support']>=(POLICY['min_bright']if bright else POLICY['min_dark']) and (ev['contrast']>=POLICY['min_contrast']if bright else True)
def corridor_dark(v,lo,hi):
"""A bent/offset paint ridge is not an end: inspect the full local corridor."""
sel=(v['ts']>=lo)&(v['ts']<=hi);band=abs(v['ns']-v['offset'])<=POLICY['endpoint_dark_corridor_m']
if sel.sum()<3:return dict(valid=0.,support=0.,contrast=0.)
c=v['contrast'][sel][:,band];valid=v['allowed'][sel][:,band].all(1);signal=c.max(1)
return dict(valid=float(valid.mean()),support=float((signal<v['cut']).mean()),contrast=float(np.median(signal)),full_corridor=True)
def fit_series(intervals,seed,width,offset):
"""Find bounded constant-rhythm subseries; never cross a rhythm change."""
o,u=seed['origin'],seed['axis'];n=np.array([-u[1],u[0]]);out=[]
for start in range(len(intervals)):
for end in range(start+3,min(len(intervals),start+40)+1):
seq=intervals[start:end];lengths=np.array([b-a for a,b in seq]);L=float(np.median(lengths))
minimum=POLICY['min_short_strokes']if L<1.45 else POLICY['min_long_strokes']
if len(seq)<minimum or not POLICY['min_dash_length_m']<L<=POLICY['max_dash_length_m']:continue
if np.max(abs(lengths-L))>max(.15,.22*L):continue
rs=[dict(center=o+((a+b)/2)*u+offset*n,axis=u,L=b-a,W=width,source_tile='two-gaussian-mosaics')for a,b in seq]
fit=reconstruct(dict(records=rs,origin=o+offset*n,axis=u,points=np.array([r['center']for r in rs]),parallel=False),minimum_period_to_length=1.10)
if fit is None or fit['kind']!='dashed' or fit['period_m']-L<POLICY['min_gap_m']:continue
# A regular missing slot is a hypothesis, never an automatic output.
fit.update(lo=seq[0][0],hi=seq[-1][1],intervals=seq,length=L,offset=offset)
out.append(fit)
# Image validation decides which subseries survives. Selecting a large
# unverified model here would suppress valid shorter rows at occlusions.
return sorted(out,key=lambda x:(-len(x['intervals']),-x['hi']+x['lo']))
def discover(seed,views):
"""Measured dashes, regular spacing, observed gap and transition endpoints."""
if views is None:return []
o,u=seed['origin'],seed['axis'];offset=float(np.mean([v['offset']for v in views]));width=float(np.clip(np.median([v['width']for v in views]),.075,.27));candidates=[]
for mode in ['intervals','peak_intervals']:
for fit in fit_series(views[0][mode],seed,width,offset):
# Both mosaics must locate actual stroke edges, including a worn
# continuous underlay. A model alone cannot supply a missing run.
observations=[];evidence=[];okay=True
for p in fit['polygons']:
c=float((np.array(p.centroid.coords[0])-o)@u);L=fit['length'];matched=[]
for v in views:
opts=[ab for ab in v[mode]if abs((ab[0]+ab[1])/2-c)<=POLICY['max_phase_error_m']and abs((ab[1]-ab[0])-L)<=max(.2,.22*L)]
if not opts:okay=False;break
ab=min(opts,key=lambda ab:abs((ab[0]+ab[1])/2-c));ev=section_evidence(v,c-L*.35,c+L*.35)
if not supported(ev):okay=False;break
matched.append(ab);evidence.append(ev)
if not okay:break
if max(abs(matched[0][i]-matched[1][i])for i in [0,1])>POLICY['max_edge_disagreement_m']:okay=False;break
observations.append(dict(center=c,edges=matched))
if not okay:continue
centers=[r['center']for r in observations];gap_evidence=[]
for a,b in zip(centers,centers[1:]):
lo=a+fit['length']/2+.04;hi=b-fit['length']/2-.04
for v in views:
ev=section_evidence(v,lo,hi,False)
# A visible low floor is allowed only with an independently
# identified high-contrast peak rhythm in both images.
if mode=='peak_intervals':
paint=min(section_evidence(v,a-fit['length']*.3,a+fit['length']*.3)['contrast'],section_evidence(v,b-fit['length']*.3,b+fit['length']*.3)['contrast'])
ev['contrast_drop']=paint-ev['contrast'];ok=ev['valid']>=POLICY['min_valid']and ev['contrast_drop']>=18 and ev['contrast']<paint*.65
else:ok=supported(ev,False)
if not ok:okay=False;break
gap_evidence.append(ev)
if not okay:break
if not okay:continue
# Only the observed first-to-last stroke span may replace old paint.
# Exterior transitions are handled separately with their own evidence.
lo=centers[0]-fit['length']/2;hi=centers[-1]+fit['length']/2
# Include only positively dark exterior slivers. This avoids tiny
# leftover caps while never erasing a real neighboring solid start.
edges=[];limits=[lo,hi]
for side,end in enumerate([lo,hi]):
sign=-1 if side==0 else 1
for pad in np.arange(POLICY['max_family_edge_padding_m'],.049,-.025):
ev=[corridor_dark(v,*sorted([end+sign*.04,end+sign*float(pad)]))for v in views]
if all(supported(e,False)for e in ev):
limits[side]=end+sign*float(pad);edges.append(dict(side=side,padding=float(pad),views=ev));break
domain=rectangle(o,u,limits[0],limits[1],width+.16,offset)
candidates.append(dict(kind='periodic-row',mode=mode,polygons=fit['polygons'],domain=domain,origin=o,axis=u,width=width,offset=offset,period=fit['period_m'],length=fit['length'],observations=observations,paint_evidence=evidence,gap_evidence=gap_evidence,edge_evidence=edges,lo=lo,hi=hi))
accepted=[]
for r in sorted(candidates,key=lambda x:-len(x['polygons'])):
if any(r['domain'].intersection(q['domain']).area>.01 for q in accepted):continue
accepted.append(r)
return accepted
def endpoints(seed,views):
"""Correct a solid end only where both paint and its following gap exist."""
if views is None or seed['length']<2.7:return []
changes=[];L=seed['length'];o,u=seed['origin'],seed['axis']
for sign in [-1,1]:
edge=sign*L/2;inside=edge-sign*min(L*.4,2.5);options=[]
for v in views:
options.append([ab for ab in v['intervals']if ab[0]<inside<ab[1]])
if any(len(x)!=1 for x in options):continue
ab=[x[0]for x in options];ends=[x[0 if sign<0 else 1]for x in ab]
if abs(ends[0]-ends[1])>POLICY['max_edge_disagreement_m']:continue
end=float(np.mean(ends));delta=sign*(end-edge)
if not POLICY['min_endpoint_change_m']<=abs(delta)<=POLICY['max_endpoint_change_m']:continue
if any(abs(x[1]-x[0])<2.7 for x in ab):continue
evs=[];okay=True
for v in views:
bright=section_evidence(v,*sorted([end-sign*.5,end-sign*.08]));dark=corridor_dark(v,*sorted([end+sign*.08,end+sign*.35]))
if not supported(bright)or not supported(dark,False):okay=False;break
if delta>0 and abs(v['offset'])>POLICY['max_endpoint_ridge_offset_m']:okay=False;break
edited=section_evidence(v,*sorted([edge+sign*.03,end-sign*.06]))if delta>0 else corridor_dark(v,*sorted([end+sign*.06,edge-sign*.03]))
if not supported(edited,delta>0):okay=False;break
evs.append(dict(paint=bright,dark=dark,edit=edited))
if not okay:continue
lo,hi=sorted([edge,end]);domain=rectangle(o,u,lo,hi,2.)
changes.append(dict(kind='extend-solid'if delta>0 else'trim-solid',sign=sign,delta=delta,lo=lo,hi=hi,domain=domain,polygon=rectangle(o,u,lo,hi,seed['width']),evidence=evs))
return changes
@@ -0,0 +1,96 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"root": "simulation/urban-plan-research",
"files": {
"audit_beta.py": "beta_pass/audit_beta.py",
"audit_consensus.py": "consensus_pass/audit_consensus.py",
"audit_norms.py": "norms_pass/audit_norms.py",
"audit_rows.py": "rows_pass/audit_rows.py",
"audit_sections.py": "sections_pass/audit_sections.py",
"audit_transitions.py": "transitions_pass/audit_transitions.py",
"beta_profiles.py": "beta_pass/beta_profiles.py",
"consensus_profiles.py": "consensus_pass/consensus_profiles.py",
"fit_scene.py": "full_plan/fit_scene.py",
"gost_catalog.py": "norms_pass/gost_catalog.py",
"image_profiles.py": "lines_pass/image_profiles.py",
"interval_profiles.py": "intervals_pass/interval_profiles.py",
"layer_common.py": "full_plan/layer_common.py",
"line_reconstruction.py": "intervals_pass/line_reconstruction.py",
"norm_profiles.py": "norms_pass/norm_profiles.py",
"refine_beta.py": "beta_pass/refine_beta.py",
"refine_consensus.py": "consensus_pass/refine_consensus.py",
"refine_norms.py": "norms_pass/refine_norms.py",
"refine_rows.py": "rows_pass/refine_rows.py",
"refine_sections.py": "sections_pass/refine_sections.py",
"refine_transitions.py": "transitions_pass/refine_transitions.py",
"render_beta.py": "beta_pass/render_beta.py",
"render_consensus.py": "consensus_pass/render_consensus.py",
"render_norms.py": "norms_pass/render_norms.py",
"render_plan.py": "continuation_pass/render_plan.py",
"render_rows.py": "rows_pass/render_rows.py",
"render_sections.py": "sections_pass/render_sections.py",
"render_transitions.py": "transitions_pass/render_transitions.py",
"row_evidence.py": "rows_pass/row_evidence.py",
"row_profiles.py": "rows_pass/row_profiles.py",
"section_profiles.py": "sections_pass/section_profiles.py",
"test_beta.py": "beta_pass/test_beta.py",
"test_consensus.py": "consensus_pass/test_consensus.py",
"test_intervals.py": "intervals_pass/test_intervals.py",
"test_lines.py": "lines_pass/test_lines.py",
"test_norms.py": "norms_pass/test_norms.py",
"test_rows.py": "rows_pass/test_rows.py",
"test_sections.py": "sections_pass/test_sections.py",
"test_transitions.py": "transitions_pass/test_transitions.py",
"transition_profiles.py": "transitions_pass/transition_profiles.py"
},
"reference_qualification": "beta-pass-20261012",
"source_snapshot": "b6572b4a70c07ae8aece",
"source_sha256": {
"audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f",
"audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2",
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
"audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01",
"audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7",
"audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a",
"beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e",
"consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091",
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
"gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537",
"image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8",
"interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345",
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
"line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738",
"norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7",
"refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831",
"refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36",
"refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5",
"refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8",
"refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3",
"refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b",
"render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c",
"render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682",
"render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d",
"render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064",
"render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e",
"render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c",
"render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d",
"row_evidence.py": "fc6a390faa97fb4cf6213dd6b841a94de9c6e78e0b68e6715aa06f2de565f28c",
"row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df",
"section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de",
"test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b",
"test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7",
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a",
"test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f",
"test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449",
"test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f",
"test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438",
"transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e"
},
"external_review_font": {
"name": "review-font.ttf",
"sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9",
"purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP"
},
"deployment": false
}
@@ -0,0 +1,118 @@
from pathlib import Path
import os,json,time,hashlib,collections
import numpy as np,cv2,shapely
from shapely.geometry import shape,mapping
from shapely.ops import transform
from layer_common import O,S,sample,feature,parts
from beta_profiles import POLICY,VERSION,describe,profiles,discover,endpoints
from row_evidence import GaussianViews
from row_profiles import pair,fit_chain,check_chain
from transition_profiles import residual_sections
from gost_catalog import assess_dash
cv2.setNumThreads(3);started=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());original={f['id']:f for f in old['features']};current=dict(original)
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds']
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
protected=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'])
views=GaussianViews(tiles,labels,low,high,protected);transactions=[];diagnostics=[];domains=[]
def poly(f):return shapely.force_2d(shape(f['geometry']))
def linear(f):return f['properties'].get('subtype')=='linear_marking'
def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
def make(p,kind,ids,**kw):return feature(lift(p),'road_marking',subtype='linear_marking',line_kind=kind,method=VERSION,source_ids=ids,standard_compliance='not_assessed',**kw)
def commit(kind,ids,new,domain,ev,used,extra=None):
before=[current[i]for i in ids];new=[f for f in new if not poly(f).is_empty];newids=[f['id']for f in new]
if len(set(newids))!=len(newids)or any(i in current and i not in ids for i in newids):return False
a=shapely.union_all([poly(f)for f in before]);b=shapely.union_all([poly(f)for f in new]);novel=b.difference(a)
if a.symmetric_difference(b).area<POLICY['min_material_change_m2']:return False
if novel.intersection(protected).area>POLICY['max_new_neighbor_overlap_m2']:return False
if any(novel.intersection(poly(f)).area>POLICY['max_new_neighbor_overlap_m2']for i,f in current.items()if i not in ids and linear(f)):return False
for i in ids:current.pop(i)
for f in new:current[f['id']]=f
rec=dict(kind=kind,source_ids=ids,output_ids=newids,before=before,after=new,bounds_xy=(shapely.union_all([a,b])if kind=='assembled-row'else domain).bounds,edit_domain=mapping(domain),evidence=ev,source_views=used,source_tiles=sorted(set(used[0])|set(used[1])),added_area_m2=float(novel.area),removed_area_m2=float(a.difference(b).area))
if extra:rec.update(extra)
transactions.append(rec);print('EDIT',len(transactions),kind,len(ids),'->',len(new),flush=True);return True
# Stage 1: every eligible existing axis seeds a 24m wider image search. Spatial
# neighborhoods already covered by an accepted periodic model are not reworked.
seeds=[]
for fid,f in original.items():
if not linear(f):continue
rec=describe(poly(f))
if rec is not None:seeds.append((fid,rec))
proposals=[]
for index,(fid,seed)in enumerate(sorted(seeds,key=lambda x:-x[1]['length'])):
readers,used=views.readers(seed['origin'],seed['axis']);pv=profiles(seed,readers)
found=discover(seed,pv);diagnostics.append(dict(seed_id=fid,stage='discover',profile_valid=pv is not None,proposals=len(found)))
for r in found:r.update(seed_id=fid,source_views=used);proposals.append(r)
if index%25==0:print('PROFILE',index+1,'/',len(seeds),'PROPOSALS',len(proposals),flush=True)
# Stage 2: one normalized row replaces only its observed longitudinal section.
for r in sorted(proposals,key=lambda x:(-len(x['polygons']),-x['hi']+x['lo'])):
domain=r['domain'];u=r['axis'];o=r['origin'];n=np.array([-u[1],u[0]]);origin=o+r['offset']*n
if any(domain.intersection(d).area>.01 for d in domains):continue
ids=[];residual=[]
for fid,f in current.items():
if not linear(f):continue
p=poly(f);d=describe(p)
if d is None or p.intersection(domain).area<.005 or abs(d['axis']@u)<np.cos(np.deg2rad(3))or abs((d['origin']-origin)@n)>.13:continue
# Old complete stroke centers must agree with the new ridge; crossings
# and a genuine neighboring stripe are not part of this row.
ids.append(fid)
for pp in parts(residual_sections(p,domain,o,u)):
if pp.area>.000001:residual.append(make(pp,f['properties'].get('line_kind','solid'),[fid],role='unchanged-section'))
if not ids:continue
generated=[make(p,'dashed',ids,period_m=r['period'],dash_length_m=r['length'],width_m=r['width'],standard_assessment=assess_dash(r['length'],r['period'],r['width']),observed_stroke=True)for p in r['polygons']]
before=shapely.union_all([poly(current[i])for i in ids]);new_strokes=sum(p.intersection(before).area/max(p.area,1e-9)<.35 for p in r['polygons'])
ev=dict(paint=r['paint_evidence'],gaps=r['gap_evidence'],edges=r['edge_evidence'],observations=r['observations'],mode=r['mode'])
if commit('periodic-row',ids,residual+generated,domain,ev,r['source_views'],dict(period_m=r['period'],dash_length_m=r['length'],newly_captured_strokes=new_strokes,normalized_strokes=len(generated),axis=u.tolist(),origin=o.tolist())):domains.append(domain)
# Stage 3: false solid ends and missed tails. Each edit needs visible paint and
# the following dark interval in both mosaics, including at existing transitions.
for fid in list(current):
f=current.get(fid)
if f is None or not linear(f)or f['properties'].get('line_kind')=='dashed':continue
p=poly(f);seed=describe(p)
if seed is None or seed['length']<2.7:continue
readers,used=views.readers(seed['origin'],seed['axis']);pv=profiles(seed,readers,extension=2.5);changes=endpoints(seed,pv)
if not changes:continue
output=p;edit=[];ev=[]
for c in changes:
output=output.union(c['polygon'])if c['kind']=='extend-solid'else output.difference(c['domain'])
edit.append(c['domain']);ev.append({k:c[k]for k in ['kind','delta','evidence']})
if output.geom_type!='Polygon' or not output.is_valid:continue
commit('solid-endpoints',[fid],[make(output,'solid',[fid])],shapely.union_all(edit),ev,used)
# Stage 4: run the qualified whole-row assembly against the new graph. Known
# dashes and symbols remain barriers. All original fragments are fitted jointly.
barriers=shapely.union_all([protected]+[poly(f)for f in current.values()if linear(f)and f['properties'].get('line_kind')=='dashed'])
joinviews=GaussianViews(tiles,labels,low,high,barriers);initial={fid:poly(f)for fid,f in current.items()if linear(f)and f['properties'].get('line_kind')!='dashed'}
groups={fid:[fid]for fid in initial};considered=set()
while True:
choices=[];entries=sorted(groups)
for i,aid in enumerate(entries):
for bid in entries[:i]:
identity=tuple(sorted(groups[aid]+groups[bid]))
if identity in considered:continue
a,b=poly(current[aid]),poly(current[bid])
if a.distance(b)>.56:continue
q=pair(a,b)
if q is not None:choices.append((abs(q['gap_m']),identity,aid,bid))
accepted=False
for _,identity,aid,bid in sorted(choices):
considered.add(identity);r=fit_chain([initial[i]for i in identity])
if r is None or r['polygon'].intersection(barriers).area>.005:continue
readers,used=joinviews.readers(r['origin'],r['axis']);okay,ev=check_chain(r,readers)
if not okay:continue
p=r['output_polygon']
if p.intersection(barriers).area>.005:continue
f=make(p,'solid',[aid,bid],assembly_operation=r['operation'])
if commit('assembled-row',[aid,bid],[f],r['edit_domain'],ev,used,dict(assembly_operation=r['operation'],max_axis_displacement_m=r['max_axis_displacement_m'])):
groups.pop(aid);groups.pop(bid);groups[f['id']]=list(identity);accepted=True;break
if not accepted:break
if len(transactions)>1500:raise RuntimeError('Unbounded edits')
result={**old,'features':list(current.values()),'beta_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False))
(O/'beta-rows.json').write_text(json.dumps(transactions,indent=2,allow_nan=False));(O/'beta-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes())
counts=collections.Counter(r['kind']for r in transactions)
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(transactions),stages=dict(counts),profiled_axes=len(seeds),proposed_periodic_rows=len(proposals),newly_captured_strokes=sum(r.get('newly_captured_strokes',0)for r in transactions),normalized_strokes=sum(r.get('normalized_strokes',0)for r in transactions),endpoint_extensions=sum(e['kind']=='extend-solid'for r in transactions if r['kind']=='solid-endpoints'for e in r['evidence']),endpoint_trims=sum(e['kind']=='trim-solid'for r in transactions if r['kind']=='solid-endpoints'for e in r['evidence']),before_linear_objects=sum(linear(f)for f in original.values()),after_linear_objects=sum(linear(f)for f in current.values()),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
(O/'beta-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
@@ -0,0 +1,41 @@
from pathlib import Path
import os,json,shutil
from datetime import datetime,timezone
import numpy as np,shapely
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape
from layer_common import O,S
from fit_scene import project
old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'beta-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23)
for p in O.glob('beta-*.jpg'):
h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name)
def draw(im,g,features):
im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200
for f in features:
if f['properties'].get('subtype')not in ['linear_marking','crosswalk']:continue
for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2)))
return im
frames=[];manifest=[];loaded={}
for gi,rec in enumerate(groups):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id']
if name not in loaded:
g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))}
g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]):
frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640')
fn='beta-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects']))
for start in range(0,len(frames),4):
part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white')
for k,im in enumerate(part):sheet.paste(im,(0,k*655))
sheet.save(O/('beta-proof-%03d.jpg'%(start//4+1)),quality=94)
(O/'beta-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True)
# Revisit every short-dash family shown in the prior delivery, using its stored
# bounds only for review framing; these bounds never enter the detector.
references=json.loads(Path('/families/line-families.json').read_text());ref_manifest=[]
for gi,rec in enumerate(references):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200
uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*8/60,raw.width*18/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(2400,855),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(draw(raw,g,old['features']),'До'),(draw(raw,g,new['features']),'После')]):
frame.paste(im.crop(bbox).resize((800,800),Image.Resampling.LANCZOS),(800*j,55));d.text((800*j+10,12),label,font=font,fill='#263640')
fn='reference-%02d.jpg'%gi;frame.save(O/fn,quality=96);ref_manifest.append(dict(group=gi,file=fn,source_tile=name,bounds_source='prior line-families.json; review framing only'))
(O/'reference-visual-manifest.json').write_text(json.dumps(ref_manifest,indent=2))
@@ -0,0 +1,67 @@
import json,runpy,numpy as np
from interval_profiles import rectangle
from beta_profiles import describe,profiles,discover,endpoints,fit_series
prior=runpy.run_path('/candidate/test_rows.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()}
o=np.zeros(2);u=np.array([1.,0.])
def reader(intervals,offset=0,missing=None,underlay=0):
def read(xy):
x,y=xy.T;on=np.zeros(len(x),bool)
for a,b in intervals:on|=(x>=a)&(x<=b)
sig=(underlay+140*on)*np.exp(-.5*((y-offset)/.045)**2)
rgb=np.repeat(np.clip(65+sig,0,255)[:,None],3,1).astype('uint8');valid=np.ones(len(x),bool)
if missing is not None:valid[(x>missing[0])&(x<missing[1])]=False
return rgb,valid
return read
dash=[(i,i+.5)for i in range(-4,9)]
seed=describe(rectangle(o,u,0,.5,.12));read=reader(dash)
fit=discover(seed,profiles(seed,[read,read]))
checks['one_stroke_seeds_whole_short_row']=bool(fit)and len(fit[0]['polygons'])>=10
checks['every_new_stroke_has_two_observed_edges']=bool(fit)and all(len(x['edges'])==2 for x in fit[0]['observations'])
checks['one_view_cannot_authorize_row']=not discover(seed,profiles(seed,[read]))
unknown=reader(dash,missing=(2,4))
checks['unknown_slot_not_invented']=all(not 2.1<float(p.centroid.x)<3.9 for r in discover(seed,profiles(seed,[read,unknown]))for p in r['polygons'])
absent=reader([x for x in dash if x[0]!=3])
checks['visible_absent_stroke_not_invented']=all(not 3<float(p.centroid.x)<3.5 for r in discover(seed,profiles(seed,[read,absent]))for p in r['polygons'])
neighbor=reader(dash,offset=.3)
checks['neighbor_line_not_captured_as_seed']=profiles(seed,[neighbor,neighbor])is None
shifted=reader(dash,offset=.1)
checks['disagreeing_ridges_rejected']=profiles(seed,[read,shifted])is None
solid=reader([(-20,20)])
checks['continuous_paint_not_periodic']=not discover(seed,profiles(seed,[solid,solid]))
irregular=reader([(0,.5),(1,1.5),(2.6,3.1),(4,4.5),(6,6.5)])
checks['irregular_peaks_not_normalized']=not discover(seed,profiles(seed,[irregular,irregular]))
longseed=describe(rectangle(o,u,0,3,.12));longread=reader([(i,i+3)for i in [-8,-4,0,4,8,12]])
longfit=discover(longseed,profiles(longseed,[longread,longread]))
checks['long_dash_family_reconstructed']=bool(longfit)and abs(longfit[0]['period']-4)<.1
checks['period_is_measured_not_forced_to_standard']=bool(fit)and abs(fit[0]['period']-1)<.1
under=reader(dash,underlay=40)
ufit=discover(seed,profiles(seed,[under,under]))
checks['regular_short_peaks_survive_faint_underlay']=bool(ufit)
s=describe(rectangle(o,u,0,8,.12));r=reader([(0,9)])
e=endpoints(s,profiles(s,[r,r],extension=2.5))
checks['visible_solid_tail_extended']=any(x['kind']=='extend-solid'and x['sign']==1 for x in e)
r2=reader([(0,7)])
e2=endpoints(s,profiles(s,[r2,r2],extension=2.5))
checks['false_solid_tail_trimmed']=any(x['kind']=='trim-solid'and x['sign']==1 for x in e2)
hidden=reader([(0,9)],missing=(8.8,9.5))
checks['mask_edge_not_paint_endpoint']=not endpoints(s,profiles(s,[r,hidden],extension=2.5))
checks['endpoint_disagreement_rejected']=not endpoints(s,profiles(s,[r,r2],extension=2.5))
def bent(xy):
x,y=xy.T;center=np.where(x<7,0,np.minimum(.14,(x-7)*.2));on=(x>=0)&(x<=9)
signal=140*on*np.exp(-.5*((y-center)/.04)**2)
return np.repeat((65+signal)[:,None],3,1).astype('uint8'),np.ones(len(x),bool)
checks['bent_tail_not_mistaken_for_dark_end']=not endpoints(s,profiles(s,[bent,bent],extension=2.5))
offsetread=reader([(0,9)],offset=.1)
checks['offset_paint_cannot_extend_old_axis']=not endpoints(s,profiles(s,[offsetread,offsetread],extension=2.5))
nonstandard=reader([(i*1.65,i*1.65+.55)for i in range(-4,6)])
nf=discover(seed,profiles(seed,[nonstandard,nonstandard]))
checks['nonstandard_period_retained']=bool(nf)and abs(nf[0]['period']-1.65)<.1
verylong=reader([(0,20)])
checks['long_extrapolation_bounded']=not endpoints(s,profiles(s,[verylong,verylong],extension=2.5))
checks['wide_seed_not_lane_stripe']=describe(rectangle(o,u,0,5,.5))is None
checks['tiny_seed_not_lane_stripe']=describe(rectangle(o,u,0,.2,.1))is None
theta=.83;R=np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]]);shift=np.array([120.,-63.])
from shapely.geometry import Polygon
sr=describe(Polygon(np.asarray(rectangle(o,u,0,.5,.12).exterior.coords)@R.T+shift));rr=lambda xy:read((xy-shift)@R)
fr=discover(sr,profiles(sr,[rr,rr]));checks['rigid_transform_preserves_detected_row']=bool(fr)and len(fr[0]['polygons'])==len(fit[0]['polygons'])
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/beta-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(dict(passed=result['passed'],tests=len(checks),failed=[k for k,v in checks.items()if not v])));assert result['passed']
@@ -0,0 +1,241 @@
"""Metric physical-edge anchors, followed by weighted minimum-curvature fitting.
OpenCV derivatives, SciPy sampling/Viterbi costs and a sparse smoothing solve.
Semantic masks locate a search corridor, never certify an observed curb.
No scene names, route coordinates, tile IDs or model-specific parameters.
"""
from dataclasses import dataclass, asdict
import numpy as np
import cv2
from scipy.ndimage import gaussian_filter, gaussian_filter1d, map_coordinates, maximum_filter
from scipy.sparse import diags
from scipy.sparse.linalg import spsolve
from shapely.geometry import LineString
@dataclass(frozen=True)
class AnchorPolicy:
sample_m: float = .20
search_m: float = 3.0
search_step_m: float = .10
cross_section_m: float = .35
occluder_margin_m: float = .35
alpha_min: float = .80
minimum_support_m: float = 1.0
minimum_chain_m: float = 2.0
maximum_internal_gap_m: float = 6.0
anchor_score: float = .65
smooth_lambda_m4: float = .045
material_ranking_weight: float = .5
def sample(array, p):
return map_coordinates(array, [p[..., 1], p[..., 0]], order=1,
mode='constant', cval=0)
def arclength(p):
return np.r_[0., np.cumsum(np.linalg.norm(np.diff(p, axis=0), axis=1))]
def resample(p, step):
d = arclength(p)
keep = np.r_[True, np.diff(d) > 1e-8]
p, d = p[keep], d[keep]
if len(p) < 2:
return p
t = np.linspace(0, d[-1], max(2, int(np.ceil(d[-1]/step))+1))
return np.c_[np.interp(t, d, p[:, 0]), np.interp(t, d, p[:, 1])]
class PhysicalFields:
def __init__(self, rgb, z, alpha, occluder, road, side, cell_m,
policy=AnchorPolicy()):
self.cell = float(cell_m)
self.policy = policy
self.gray = gaussian_filter(cv2.cvtColor(rgb, cv2.COLOR_RGB2LAB)[:, :, 0].astype('float32'), .10/self.cell)
self.gx = cv2.Sobel(self.gray, cv2.CV_32F, 1, 0, ksize=3)/(8*self.cell)
self.gy = cv2.Sobel(self.gray, cv2.CV_32F, 0, 1, ksize=3)/(8*self.cell)
self.texture = np.sqrt(gaussian_filter(self.gx**2+self.gy**2, .35/self.cell))
self.alpha = np.minimum(alpha, np.isfinite(z)).astype('float32')
self.z = np.nan_to_num(z).astype('float32')
self.occluder = maximum_filter(np.asarray(occluder, 'float32'),
size=2*int(np.ceil(policy.occluder_margin_m/self.cell))+1)
self.road = np.asarray(road, 'float32')
self.side = np.asarray(side, 'float32')
self.material = None
self.material_valid = None
def measure(self, uv, normal):
"""Normal points from road to sidewalk. Return reward and reliability."""
n = np.broadcast_to(normal, uv.shape)
plus = uv+n*self.policy.cross_section_m/self.cell
minus = uv-n*self.policy.cross_section_m/self.cell
near = sample(self.gray, plus)-sample(self.gray, minus)
far = sample(self.gray, uv+n*.8/self.cell)-sample(self.gray, uv-n*.8/self.cell)
# A material boundary persists across scales; a narrow paint ridge does not.
gray_contrast = np.clip(np.minimum(abs(near), abs(far))/18, 0, 1)*(near*far>0)
oriented_edge = np.clip(abs(sample(self.gx, uv)*n[..., 0]+sample(self.gy, uv)*n[..., 1])/55, 0, 1)
dz = sample(self.z, plus)-sample(self.z, minus)
step = np.exp(-((dz-.12)/.12)**2)*(dz>.025)*(dz<.35)
texture = np.clip((sample(self.texture, plus)-sample(self.texture, minus))/20, 0, 1)
score = .65*gray_contrast*oriented_edge+.65*step+.25*oriented_edge+.20*texture
# Broad semantics are a weak context term; no hard mask constraint.
context = .5*(sample(self.side, plus)-sample(self.side, minus)+
sample(self.road, minus)-sample(self.road, plus))
score += .10*np.clip(context, -1, 1)
alpha = np.minimum.reduce([sample(self.alpha, uv), sample(self.alpha, plus), sample(self.alpha, minus)])
blocked = np.maximum.reduce([sample(self.occluder, uv), sample(self.occluder, plus), sample(self.occluder, minus)])
reliable = (alpha >= self.policy.alpha_min)*(blocked < .25)*(abs(dz) < .45)
return score.astype('float32'), reliable.astype('float32')
def road_side_interface(self, uv, normal):
"""A moved candidate retains road/sidewalk adjacency at its own position.
A physical edge inside one material (paving, parking paint or a ramp)
cannot inherit the interface identity of a nearby semantic seed.
This is search eligibility; the physical score and its threshold stay
independent and are never increased by semantic agreement.
"""
n = np.broadcast_to(normal, uv.shape)
road_inside = sample(self.road, uv-n*.8/self.cell) > .5
side_outside = sample(self.side, uv+n*.8/self.cell) > .5
return road_inside & side_outside
def ranked_score(self, score, uv, normal):
"""Appearance ranks candidates but cannot invalidate physical evidence."""
if self.material is None:
return score
n = np.broadcast_to(normal, uv.shape)
inside = sample(self.material, uv-n*.8/self.cell)
outside = sample(self.material, uv+n*.8/self.cell)
contrast = inside-outside
if self.material_valid is not None:
contrast *= sample(self.material_valid, uv) >= .5
return score+self.policy.material_ranking_weight*contrast
def evidence_cost(scores, reliability):
"""Reward supported extent, without renormalizing away missing observations."""
scores, reliability = np.asarray(scores), np.asarray(reliability)
if not scores.size or scores.shape != reliability.shape:
raise ValueError('Matching nonempty evidence arrays required')
return -float(np.mean(np.clip(scores, -1, 1.7)*reliability))
def smooth_anchors(points, confidence, policy=AnchorPolicy(), corners=()):
"""Weighted least squares + second derivative penalty; zero weight = missing.
The positive-weight endpoint requirement prevents unsupported extrapolation.
Interior missing samples are reconstructed by the same variational spline.
Structural corners relax curvature only at their vertex, not over a radius.
"""
p = np.asarray(points, float)
w = np.asarray(confidence, float)
if len(p) < 4 or w.shape != (len(p),) or not(w[0]>0 and w[-1]>0):
raise ValueError('At least four samples and observed terminal anchors required')
ds = max(float(np.median(np.diff(arclength(p)))), policy.sample_m*.5)
D = diags([np.ones(len(p)-2), -2*np.ones(len(p)-2), np.ones(len(p)-2)],
[0, 1, 2], shape=(len(p)-2, len(p)), format='csr')
bend = np.ones(len(p)-2)
for i in corners:
if 0<i<len(p)-1:
bend[i-1] = 0
W = diags(w)
A = W+policy.smooth_lambda_m4/ds**4*(D.T@diags(bend)@D)
return spsolve(A.tocsc(), w[:, None]*p)
def mask_runs(mask):
cuts = np.r_[0, np.flatnonzero(np.diff(mask.astype(int)))+1, len(mask)]
return [(a,b) for a,b in zip(cuts[:-1], cuts[1:]) if mask[a]]
def refine_chain(seed_pixels, fields, policy=AnchorPolicy()):
"""Return supported chains, with all bounded internal interpolation recorded."""
p = resample(np.asarray(seed_pixels)*fields.cell, policy.sample_m)/fields.cell
if len(p)<12:
return []
ring = np.linalg.norm(p[0]-p[-1])*fields.cell < .05
if ring:
core=gaussian_filter1d(p[:-1],.45/policy.sample_m,axis=0,mode='wrap')
t=np.roll(core,-1,axis=0)-np.roll(core,1,axis=0)
seed=np.vstack([core,core[0]]);tangent=np.vstack([t,t[0]])
else:
seed = gaussian_filter1d(p, .45/policy.sample_m, axis=0, mode='nearest')
tangent = np.gradient(seed, axis=0)
tangent /= np.maximum(np.linalg.norm(tangent, axis=1)[:, None], 1e-8)
normal = np.c_[-tangent[:, 1], tangent[:, 0]]
orient = np.sign(np.mean(sample(fields.side, seed+normal*.6/fields.cell)-
sample(fields.side, seed-normal*.6/fields.cell))) or 1
normal *= orient
offsets = np.arange(-policy.search_m, policy.search_m+policy.search_step_m/2, policy.search_step_m)
uv = seed[:, None, :]+normal[:, None, :]*offsets[None, :, None]/fields.cell
# Seed normals define the search strip, not the identity of either side.
# A displaced/curved seed may have the same material on both sides, so its
# fallback sign cannot establish the orientation of an observed curb.
forward = fields.road_side_interface(uv, normal[:, None, :])
reverse = fields.road_side_interface(uv, -normal[:, None, :])
directed = np.where(forward[..., None], normal[:, None, :], -normal[:, None, :])
score, reliable = fields.measure(uv, directed)
reliable = reliable*(forward | reverse)
reward = score*reliable
# Standard first-order dynamic programming. Missing evidence has no attraction.
ranked = fields.ranked_score(score, uv, directed)*reliable
cost = -ranked+.015*(offsets[None, :]/policy.search_m)**2
trans = 1.2*((offsets[:, None]-offsets[None, :])/.25)**2
prev = cost[0].copy()
back = np.zeros(cost.shape, np.int16)
for i in range(1, len(p)):
total = prev[:, None]+trans
back[i] = np.argmin(total, axis=0)
prev = cost[i]+total.min(0)
ix = np.zeros(len(p), int);ix[-1] = np.argmin(prev)
for i in range(len(p)-1, 0, -1):
ix[i-1] = back[i, ix[i]]
chosen = uv[np.arange(len(p)), ix]*fields.cell
evidence = reward[np.arange(len(p)), ix]
confirmed = evidence >= policy.anchor_score
# Isolated high-contrast pixels do not qualify an anchor segment.
for a,b in mask_runs(confirmed):
if (b-a)*policy.sample_m < policy.minimum_support_m:
confirmed[a:b] = False
if not confirmed.any():
return []
first,last = np.flatnonzero(confirmed)[[0,-1]]
allowed = confirmed.copy()
for a,b in mask_runs(~confirmed):
if a>first and b<=last and (b-a)*policy.sample_m <= policy.maximum_internal_gap_m:
allowed[a:b] = True
outputs=[]
for a,b in mask_runs(allowed):
if (b-a)*policy.sample_m < policy.minimum_chain_m:
continue
obs = chosen[a:b];conf = confirmed[a:b].astype(float)
# Preserve supported sharp corners indicated by metre-scale straight arms.
approx = np.asarray(LineString(obs).simplify(.35).coords)
corners=[]
for j in range(1,len(approx)-1):
v=approx[j]-approx[j-1];u=approx[j+1]-approx[j]
if min(np.linalg.norm(v),np.linalg.norm(u))<2:
continue
if v@u < .65*np.linalg.norm(v)*np.linalg.norm(u):
k=int(np.argmin(np.linalg.norm(obs-approx[j],axis=1)))
if conf[k]>0:corners.append(k)
q=smooth_anchors(obs, conf, policy, corners)
if ring and a==0 and b==len(p) and np.linalg.norm(q[0]-q[-1])<.5:
q[-1]=q[0]
if not LineString(q).is_simple:
continue
spans=[]
for i,j in mask_runs(~confirmed[a:b]):
span=q[max(0,i-1):min(len(q),j+1)]
spans.append(dict(status='inferred',method='weighted-minimum-curvature',
pixels=(span/fields.cell).tolist(),length_m=LineString(span).length))
outputs.append((q/fields.cell,dict(length_m=LineString(q).length,
anchor_fraction=float(conf.mean()),observed_anchor_length_m=float(conf.sum()*policy.sample_m),
mean_offset_m=float(np.mean(offsets[ix[a:b]])),image_edge_support=float(conf.mean()),
inferred_pixel_spans=spans,anchor_policy=asdict(policy),
terminal_extrapolation=False)))
return outputs
@@ -0,0 +1,77 @@
"""Evidence-backed non-maximum suppression of overlapping curb hypotheses.
Only complete detached fragments are eligible. Opposite faces, unmatched
extensions and uncertain alternatives survive. This module accepts metric
geometry and observations, never a scene identity or review rectangle.
"""
from dataclasses import dataclass,asdict
from copy import deepcopy
import numpy as np
from shapely.geometry import LineString,Point
from plan_continuity import resample,distances
from gap_evidence import known_material
@dataclass(frozen=True)
class CompetitionPolicy:
sample_m: float = .4
corridor_m: float = 4.0
min_overlap_fraction: float = .80
min_parallel_fraction: float = .70
max_fragment_m: float = 40.0
min_reference_ratio: float = 1.5
material_offset_m: float = 1.0
near_offset_m: float = .25
contradiction_fraction: float = .45
separation_fraction: float = .25
minimum_known_fraction: float = .4
def oriented_samples(raw,step=.4):
p=resample(np.asarray(raw,float),step)[:,:2];t=np.gradient(p,axis=0);t/=np.maximum(np.linalg.norm(t,axis=1)[:,None],1e-9)
return p,t,np.c_[-t[:,1],t[:,0]]
def material_summary(p,n,sample,offset=1.):
left=known_material(sample(p+n*offset));right=known_material(sample(p-n*offset))
split=left*right==-1;known=(left!=0)&(right!=0)
return dict(known_fraction=float(known.mean()),separation_fraction=float(split.mean()),
road_inside_fraction=float(np.mean((left==1)&(right==1))),sidewalk_inside_fraction=float(np.mean((left==-1)&(right==-1))),
signed_side=float(np.mean(np.where(split,left,0))))
def suppress(document,sample,policy=CompetitionPolicy(),diagnostic=False):
fs=[f for f in document['features']if f.get('properties',{}).get('class')=='road_boundary'and f['geometry']['type']=='LineString']
lines=[LineString(np.asarray(f['geometry']['coordinates'])[:,:2])for f in fs];checks=[];proposals=[]
for i,(f,line)in enumerate(zip(fs,lines)):
if line.is_ring or not 1.<line.length<=policy.max_fragment_m:continue
# Do not detach a connected edge from its neighbours.
if any(line.distance(g)<.10 for j,g in enumerate(lines)if i!=j):continue
p,t,n=oriented_samples(f['geometry']['coordinates'],policy.sample_m)
for j,(g,ref)in enumerate(zip(fs,lines)):
if i==j or ref.length<line.length*policy.min_reference_ratio or line.distance(ref)>policy.corridor_m:continue
stations=np.array([ref.project(Point(v))for v in p]);matched=np.array([ref.interpolate(s).coords[0]for s in stations])
delta=matched-p;separation=np.linalg.norm(delta,axis=1);overlap=(stations>.15)&(stations<ref.length-.15)&(separation<=policy.corridor_m)
rt=np.array([np.array(ref.interpolate(min(ref.length,s+.3)).coords[0])-np.array(ref.interpolate(max(0,s-.3)).coords[0])for s in stations]);rt/=np.maximum(np.linalg.norm(rt,axis=1)[:,None],1e-9)
alignment=np.sum(rt*t,axis=1);parallel=abs(alignment)>.90
if overlap.mean()<policy.min_overlap_fraction or parallel.mean()<policy.min_parallel_fraction:continue
# Projected progress must be one-to-one, not around a U turn.
progress=np.diff(stations);direction=1 if np.median(alignment)>=0 else -1
if np.mean(progress*direction>=-.10)<.9:continue
rn=np.c_[-rt[:,1],rt[:,0]]*direction
a=material_summary(p,n,sample,policy.material_offset_m);b=material_summary(matched,rn,sample,policy.material_offset_m)
opposite=a['signed_side']*b['signed_side']<0 and min(abs(a['signed_side']),abs(b['signed_side']))>.15
near=material_summary(p,n,sample,policy.near_offset_m)
contradiction=min(max(a['road_inside_fraction'],a['sidewalk_inside_fraction']),max(near['road_inside_fraction'],near['sidewalk_inside_fraction']))
accepted=(not opposite and a['known_fraction']>=policy.minimum_known_fraction and contradiction>=policy.contradiction_fraction and b['separation_fraction']>=policy.separation_fraction and b['separation_fraction']>=a['separation_fraction']+.20)
check=dict(fragment_id=f['id'],reference_id=g['id'],length_m=line.length,reference_length_m=ref.length,overlap_fraction=float(overlap.mean()),parallel_fraction=float(parallel.mean()),median_distance_m=float(np.median(separation)),fragment=a,near_fragment=near,reference=b,opposite_faces=bool(opposite),accepted=bool(accepted),reason='contradicted-parallel-alternative'if accepted else'opposite-faces'if opposite else'insufficient-material-separation')
checks.append(check)
if accepted:proposals.append((contradiction+b['separation_fraction'],i,j))
removed=set();winners=set()
for _,i,j in sorted(proposals,reverse=True):
if i in winners or j in removed:continue
removed.add(i);winners.add(j)
ids={fs[i]['id']for i in removed};out=deepcopy(document)
if not diagnostic:out['features']=[f for f in out['features']if f['id']not in ids]
audit=dict(policy=asdict(policy),checks=checks,removed_ids=sorted(ids),removed_m=sum(lines[i].length for i in removed),diagnostic_only=diagnostic,quarantined=[deepcopy(fs[i])for i in sorted(removed)])
return out,audit
@@ -0,0 +1,80 @@
Gaussian marking catalogue and continuous observed stripes
=========================================================
Offline continuation of search-pass-20261013. All image processing, tests and
renders run on Worker006. The operator Mac only edits sources and copies/views
evidence. No point clouds, colliders, manual processing ROIs, address-specific
parameters, live deployment or rover commands.
Method
------
* Search every native Gaussian ground-render image for compact bicycle paint
components and longer zigzag components. Keep calibrated road, vehicle and
alpha gates. Preserve small negative spaces in the component geometry.
* Fit the attributed bicycle vector artwork using OpenCV raster overlap and
bounded SciPy Powell registration. SVG vertical is road-longitudinal, as
with the existing arrow templates. Require wheel/frame negative topology,
agreement with nearby lane direction and paint support in geometrically
selected image mosaics under the two-view or stronger primary-view rules below.
Lane context is measured as the union length of projected stripe intervals,
so one continuous stripe and its fragments supply the same evidence and
duplicate observations cannot inflate the length. Both longitudinal/lateral artwork orientations are
considered: a real bicycle symbol can be wider across the lane than along it. Artwork is reused, not traced from worn paint.
* Propose repeating zigzag legs with scikit-image skeletonize, graph paths,
OpenCV Douglas-Peucker simplification and least-squares regularization.
Repetition alone is never sufficient to add an object. Two complete
mosaics use the usual checks. Where a second rendered view is absent or
partial, a stricter full primary view, tighter pattern fit and agreement
with every available secondary portion are required. These renders are
correlated samples of one Gaussian scene, not independent physical scans.
* Reuse the hash-pinned full-frame line proposals of the previous pass. A long
continuous painted stripe need not have its physical end inside the same
image. Emit only measured, two-view-supported portions, explicitly labelled
as observation-window-bounded, not physical endpoints. Subtract occupied
longitudinal intervals to avoid thin parallel duplicate slivers.
* Preserve every previous feature exactly. This addition-only pass cannot
repair old road contours, facade topology, old symbols or missing dashes.
Qualified changes are replayable transactions with source/evidence pins.
* Geometry chooses two covering frames independently at each object pixel.
The complete object need not fit inside two individual frame rectangles.
Paint coverage must be complete in the primary rank; road/alpha/vehicle validity
is measured on the painted shape instead of a surrounding convex hull.
Execution
---------
The replay helpers require the canonical checkout, official recorded-job queue,
accepted Worker caches, pinned container image and source bundle. Containers
have no network, a read-only root, 4 CPUs, 20 GiB RAM and bounded runtime.
Pinned Linux wheels are SHA-verified and extracted into disposable container
tmpfs with library execution enabled. No packages are installed on the host.
The source export contains those exact wheels and their bundled licences.
The review-only font remains in the private qualification cache. Extraction
may be reused only if every candidate-local module in its transitive import
closure, the container image and the accepted baseline match their receipt.
Classification and image rendering use the final frozen bundle in every scene.
Limits
------
Two renders of the same Gaussian reconstruction are correlated evidence.
More raster pixels do not establish higher physical accuracy. Cached road and
vehicle masks can still reject real paint. Existing missing proposal classes
and scene coverage remain limitations. Known-scene regression is not unseen-map
generalization. No full detection recall, absolute accuracy or legal GOST
compliance is claimed. GOST associations from earlier passes remain unchanged.
Reuse and attribution
---------------------
OpenCV, SciPy, Shapely and scikit-image are used as existing components.
https://scikit-image.org/docs/0.24.x/api/skimage.morphology.html#skimage.morphology.skeletonize
Bicycle artwork by Major Alexey, CC BY-SA 4.0. Adaptation: cubic-curve sampling,
even-odd polygon construction, coordinate normalization and metric registration.
https://commons.wikimedia.org/wiki/File:1.23.3_Russian_road_marking.svg
https://creativecommons.org/licenses/by-sa/4.0/
Original SVG SHA-256:
53f95d4e93d98c2d32a18d407e3189c721e252e5e7912365afdfda6313a78c59
Existing arrow artwork by the same author under the same licence:
https://commons.wikimedia.org/wiki/File:1.18_Russian_road_marking.svg
Qualified results are recorded in verification.json and visual-review.json.
@@ -0,0 +1,34 @@
from pathlib import Path
import json,hashlib,numpy as np,shapely
from shapely.geometry import shape
from catalog_rules import POLICY,VERSION,accept_bicycle,accept_zigzag
from discovery_rules import uncovered
old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/catalog-rows.json').read_text());current={f['id']:f for f in old['features']}
def poly(f):return shapely.force_2d(shape(f['geometry']))
existing=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'])
checks=dict(transaction_replay=True,only_paint_added=True,no_new_neighbor_overlap=True,evidence_passes=True)
for r in rows:
checks['transaction_replay']&=not r['before']and not r['source_ids']and r['output_ids']==[f['id']for f in r['after']]and all(f['id']not in current for f in r['after'])
checks['only_paint_added']&=all(f['properties']['class']=='road_marking'and f['properties']['method']==VERSION for f in r['after'])
okay=len(set(r['source_tiles']))>=1;ev=r['evidence']
if r['kind']=='preset-bicycle':
okay&=r['lane_context']['passed']and r['lane_context']['supporting_length_m']>=POLICY['bicycle_context_length_m']and r['lane_context']['length_measure']=='union-of-longitudinal-intervals'and r['template_fit_score']>=POLICY['bicycle_fit_score']and accept_bicycle(ev,r['template_fit_score'])==r['evidence_mode']
elif r['kind']=='regularized-zigzag':
fit=dict(legs=r['leg_count'],fit_residual_m=r['fit_residual_m'],proposal_recall=r['proposal_recall'])
okay&=r['leg_count']>=POLICY['min_zigzag_legs']and len(ev['legs'])==r['leg_count']and accept_zigzag(ev['whole'],ev['legs'],fit)==r['evidence_mode']
elif r['kind']=='observed-continuous-section':
okay&=len(set(r['source_tiles']))>=2
okay&=len(ev['profile'])==2 and all(e['valid']>=POLICY['min_line_valid']and e['support']>=POLICY['min_line_support']and e['contrast']>=POLICY['min_line_contrast']for e in ev['profile'])
okay&=len(ev['section'])==2 and all(e['valid']>=POLICY['min_line_valid']and e['support']>=POLICY['min_line_support']for e in ev['section'])
parent=shape(ev['parent_geometry']);okay&=all(poly(f).difference(parent.buffer(.001)).area<.001 for f in r['after'])and r['endpoint_authority']=='observed_window_not_physical_end'
else:okay=False
checks['evidence_passes']&=okay
for f in r['after']:
checks['no_new_neighbor_overlap']&=uncovered(poly(f),existing);existing=shapely.union_all([existing,poly(f)]);current[f['id']]=f
features={f['id']:f for f in new['features']};checks['final_map_matches_replay']=features==current;checks['unique_ids']=len(features)==len(new['features']);checks['all_baseline_objects_unchanged']=all(features.get(f['id'])==f for f in old['features']);checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features'])
checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes()
report=json.loads(Path('/out/catalog-report.json').read_text());checks['same_policy']=new['catalog_refinement']==VERSION and report['policy']==POLICY;checks['every_operation_counted']=report['changed_segments']==len(rows)and report['added_objects']==sum(len(r['after'])for r in rows)
checks['proposal_cache_pinned']=report['proposal_cache_sha256']==hashlib.sha256(Path('/fullplan/search-proposals.json').read_bytes()).hexdigest()
checks['new_full_frame_proposals_pinned']=report['catalog_proposals_sha256']==hashlib.sha256(Path('/out/catalog-proposals.json').read_bytes()).hexdigest()
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False)
Path('/out/catalog-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,7 @@
"""Bicycle artwork by Major Alexey, CC BY-SA 4.0.
Source: https://commons.wikimedia.org/wiki/File:1.23.3_Russian_road_marking.svg
License: https://creativecommons.org/licenses/by-sa/4.0/
Adaptation: curve sampling, even-odd geometry, metric scaling.
"""
SOURCE_SHA256="53f95d4e93d98c2d32a18d407e3189c721e252e5e7912365afdfda6313a78c59"
PATH='M140.5,170c-1.2,3.8-2.5,6.6-3,9.6c-0.2,1,1.4,2.9,2.5,3.5c14.6,7.8,24,19.6,27.8,35.7\n\tc7,30.2-13.5,60-44.2,64.6c-30.4,4.5-58.5-17.5-61.2-48c-3-33.9,25.7-61.7,59.6-57.7c1,0.1,2.1,0.1,3.5,0.2\n\tc3.1-10.2,6.1-20.4,9.3-30.5c2.1-6.7,4.5-13.4,7.1-19.9c2.8-7,8-11.2,15.8-11.4c6.6-0.2,13.3,0,20.2,0c0,3,0,6.3,0,10.2\n\tc-2.5,0-4.9,0-7.4,0c-1.6,0-3.2,0-4.8,0c-11.2,0.1-13,1.5-16,12.1c-0.7,2.4-1.3,4.9-2.1,7.8c1.3,0.1,2.4,0.3,3.6,0.3\n\tc28.5,0,57.1,0,85.6,0.1c2.5,0,4-0.6,4.6-3.2c0.5-2.2,1.5-4.3,2.4-6.9c-4.9-1.1-9.7-2.1-14.4-3.2c-2.5-0.6-4.9-1.2-7.2-2.2\n\tc-0.9-0.4-1.7-2-1.7-3c0-0.7,1.6-1.9,2.4-1.9c15-0.1,30-0.1,45.3-0.1c0,3.5,0,6.7,0,10.7c-3.1,0-6.3-0.3-9.3,0.1\n\tc-1.3,0.2-3,1.4-3.7,2.6c-2.6,4.5-2.6,8.9,0,13.8c4,7.4,7.1,15.2,10.4,22.9c1,2.5,2.1,2.9,4.8,2.3c30.5-7.7,60,10.6,66.2,41.2\n\tc7,33.8-20.8,65.7-55.2,63.5c-23.7-1.5-42.4-16.5-48.8-39.3c-0.7-2.4-1.5-3.3-4-3.2c-4.7,0.2-9.4-0.2-14,0.1\n\tc-7.6,0.5-13.4-2.3-18.3-7.9c-10.7-12.4-21.5-24.8-32.4-37C156.5,187.1,148.7,178.9,140.5,170z M121.5,190.5\n\tc-21-3.5-41.8,11.4-45.8,32c-4.2,21.9,9.7,43.3,31.4,47.9c21.6,4.6,43.3-9,48.3-30.3c4.5-19-6.7-41.9-22.6-46\n\tc-0.2,0.5-0.4,1-0.5,1.5c-3.7,11.6-7.4,23.3-11.2,34.9c-1,3.1-2.8,5.6-6.7,4.7c-3.3-0.8-4.9-3.9-4.1-8c0.6-3,1.5-5.9,2.4-8.8\n\tC115.6,209.3,118.5,200.1,121.5,190.5z M245.4,240.6c1,12.1,15.2,25.6,30.3,28.9c17.4,3.8,35.6-4.5,44.4-20.4\n\tc8.6-15.6,5.9-35.2-6.7-47.9c-10.9-11-29.9-15.8-40.6-10c2.3,5.1,4.6,10.1,6.9,15.2c3.8,8.5,7.7,17,11.3,25.5c2.2,5.2,0.4,8-5.1,8.4\n\tc-2.8,0.2-5.6,0.2-8.4,0.2C266.7,240.6,256.1,240.6,245.4,240.6z M209.3,227.9c8.8-23.7,17.4-46.7,26-69.8c-30.2,0-59.8,0-90.2,0\n\tC166.8,181.6,187.8,204.5,209.3,227.9z M261.9,196c-11.5,6.8-20,22.8-18,33.3c10.8,0,21.6,0,33,0C271.8,217.9,266.9,207.1,261.9,196\n\tz M230.6,229.1c0.9-19.5,9.5-34.4,25.9-45.2c-3.2-7-6.3-13.9-9.8-21.7c-8.7,22.9-17.1,44.7-25.5,66.8\n\tC224.6,229.1,227.5,229.1,230.6,229.1z'
@@ -0,0 +1,206 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"root": "simulation/urban-plan-research",
"files": {
"audit_beta.py": "beta_pass/audit_beta.py",
"audit_catalog.py": "catalog_pass/audit_catalog.py",
"audit_completion.py": "completion_pass/audit_completion.py",
"audit_consensus.py": "consensus_pass/audit_consensus.py",
"audit_corridor.py": "corridor_pass/audit_corridor.py",
"audit_discovery.py": "discovery_pass/audit_discovery.py",
"audit_norms.py": "norms_pass/audit_norms.py",
"audit_rows.py": "rows_pass/audit_rows.py",
"audit_search.py": "search_pass/audit_search.py",
"audit_sections.py": "sections_pass/audit_sections.py",
"audit_transitions.py": "transitions_pass/audit_transitions.py",
"beta_profiles.py": "beta_pass/beta_profiles.py",
"bicycle_artwork.py": "catalog_pass/bicycle_artwork.py",
"catalog_context.py": "catalog_pass/catalog_context.py",
"catalog_dependencies.py": "catalog_pass/catalog_dependencies.py",
"catalog_dependency_pins.py": "catalog_pass/catalog_dependency_pins.py",
"catalog_evidence.py": "catalog_pass/catalog_evidence.py",
"catalog_rules.py": "catalog_pass/catalog_rules.py",
"catalog_templates.py": "catalog_pass/catalog_templates.py",
"catalog_zigzag.py": "catalog_pass/catalog_zigzag.py",
"completion_profiles.py": "completion_pass/completion_profiles.py",
"consensus_profiles.py": "consensus_pass/consensus_profiles.py",
"coordinate_cache.py": "orthophoto/coordinate_cache.py",
"corridor_profiles.py": "search_pass/corridor_profiles.py",
"coverage_evidence.py": "corridor_pass/coverage_evidence.py",
"coverage_plan.py": "corridor_pass/coverage_plan.py",
"diagnose_corridor.py": "corridor_pass/diagnose_corridor.py",
"diagnose_coverage.py": "corridor_pass/diagnose_coverage.py",
"discovery_evidence.py": "discovery_pass/discovery_evidence.py",
"discovery_rules.py": "discovery_pass/discovery_rules.py",
"extract_catalog.py": "catalog_pass/extract_catalog.py",
"extract_discovery.py": "discovery_pass/extract_discovery.py",
"extract_search.py": "search_pass/extract_search.py",
"fit_scene.py": "full_plan/fit_scene.py",
"fragment_templates.py": "discovery_pass/fragment_templates.py",
"gost_catalog.py": "norms_pass/gost_catalog.py",
"image_profiles.py": "lines_pass/image_profiles.py",
"inspect_bicycles.py": "catalog_pass/inspect_bicycles.py",
"inspect_catalog.py": "catalog_pass/inspect_catalog.py",
"interval_profiles.py": "intervals_pass/interval_profiles.py",
"layer_common.py": "full_plan/layer_common.py",
"line_reconstruction.py": "intervals_pass/line_reconstruction.py",
"mapping.py": "corridor_pass/mapping.py",
"norm_profiles.py": "norms_pass/norm_profiles.py",
"ortho_terrain.py": "orthophoto/ortho_terrain.py",
"paint_templates.py": "continuation_pass/paint_templates.py",
"refine_beta.py": "beta_pass/refine_beta.py",
"refine_catalog.py": "catalog_pass/refine_catalog.py",
"refine_completion.py": "completion_pass/refine_completion.py",
"refine_consensus.py": "consensus_pass/refine_consensus.py",
"refine_corridor.py": "corridor_pass/refine_corridor.py",
"refine_discovery.py": "discovery_pass/refine_discovery.py",
"refine_norms.py": "norms_pass/refine_norms.py",
"refine_rows.py": "rows_pass/refine_rows.py",
"refine_search.py": "search_pass/refine_search.py",
"refine_sections.py": "sections_pass/refine_sections.py",
"refine_transitions.py": "transitions_pass/refine_transitions.py",
"render_beta.py": "beta_pass/render_beta.py",
"render_catalog.py": "catalog_pass/render_catalog.py",
"render_completion.py": "completion_pass/render_completion.py",
"render_consensus.py": "consensus_pass/render_consensus.py",
"render_corridor.py": "corridor_pass/render_corridor.py",
"render_coverage.py": "corridor_pass/render_coverage.py",
"render_discovery.py": "discovery_pass/render_discovery.py",
"render_norms.py": "norms_pass/render_norms.py",
"render_plan.py": "catalog_pass/render_plan.py",
"render_rows.py": "rows_pass/render_rows.py",
"render_search.py": "search_pass/render_search.py",
"render_sections.py": "sections_pass/render_sections.py",
"render_transitions.py": "transitions_pass/render_transitions.py",
"road_glyph_presets.py": "continuation_pass/road_glyph_presets.py",
"row_evidence.py": "corridor_pass/row_evidence.py",
"row_profiles.py": "rows_pass/row_profiles.py",
"search_rules.py": "search_pass/search_rules.py",
"search_views.py": "search_pass/search_views.py",
"section_profiles.py": "sections_pass/section_profiles.py",
"test_beta.py": "beta_pass/test_beta.py",
"test_catalog.py": "catalog_pass/test_catalog.py",
"test_completion.py": "completion_pass/test_completion.py",
"test_consensus.py": "consensus_pass/test_consensus.py",
"test_corridor.py": "corridor_pass/test_corridor.py",
"test_discovery.py": "discovery_pass/test_discovery.py",
"test_intervals.py": "intervals_pass/test_intervals.py",
"test_lines.py": "lines_pass/test_lines.py",
"test_norms.py": "norms_pass/test_norms.py",
"test_rows.py": "rows_pass/test_rows.py",
"test_search.py": "search_pass/test_search.py",
"test_sections.py": "sections_pass/test_sections.py",
"test_transitions.py": "transitions_pass/test_transitions.py",
"transition_profiles.py": "transitions_pass/transition_profiles.py",
"validation.py": "corridor_pass/validation.py"
},
"reference_qualification": "catalog-pass-20261014",
"source_snapshot": "c0fe1a6d698212c9d404",
"source_sha256": {
"audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f",
"audit_catalog.py": "19d5f0f156c0f90d2e1e2548fee99eee521b76e7152f0b53ae12b43ed48553b2",
"audit_completion.py": "ef6adcfec3e1a4bd894b54a150fe3b8559bf73e94665bb9da6bd68007e90575d",
"audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2",
"audit_corridor.py": "3f792b1830e9097644dd66c38eb2cf7efa11d75a0fda928ffa0a7780afb85bfe",
"audit_discovery.py": "9e5f1bdd0d752d82a52121fe86d4e6fb00068a6af9330a072fe7311a909bc974",
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
"audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01",
"audit_search.py": "0de9929d983c97045444131b9255ec4c256ae652b6adb82551e42b94c4bec0eb",
"audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7",
"audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a",
"beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e",
"bicycle_artwork.py": "2e5220e6e82024c683b65c81695b53fa3070d58eed89d61f5cbda41f6c3c554f",
"catalog_context.py": "f2e654ea068a758be1f929299786559f02672898047893cdc20e6f1cb204bb80",
"catalog_dependencies.py": "d6407445db28f6f15201f4ec09e3401141fca90e11a9cef52392f88175634fca",
"catalog_dependency_pins.py": "93ed9007288440620b8339043f1d5ae74684e39e7c3bd50d94d24f6cf29c9f3a",
"catalog_evidence.py": "6eeb6f18e9dc2fef6f490ba5a09eba64c2021c16dbdf0594921ed5a563d23868",
"catalog_rules.py": "ed0f8e838908bcea9ac1ee15fe13d1b23ac29981428ea6a4bdc097c0226db3cb",
"catalog_templates.py": "05577c611ce5ffa2c21d0f608e728eca13009c994e26913b29f39fdcf584c092",
"catalog_zigzag.py": "2e6a804cd14440afaf27bd0f0c2123afc7bf3ea1c58cd0d49293049f1f3b498f",
"completion_profiles.py": "b01cb280a265f170c2f3823d59d423c0cf11472050678cc4dad716c1f90ff786",
"consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091",
"coordinate_cache.py": "930f8f521ef13c02b589d0c182ab4cf337acc4c213354808d32178bbbea3edf4",
"corridor_profiles.py": "967902dae9137ceddb05708acbb6a7cc1e06977c6d064787a1a651422d2e5672",
"coverage_evidence.py": "1b9c1e4b0c518047ad1eacc6e314132144ae05dcad8cc82dd88b9e1340513497",
"coverage_plan.py": "48e28d6781d5d04e83645ba0a9aa7f0398ae904d26bf2e81caa8d8e741bccdda",
"diagnose_corridor.py": "cff89f2a78ff315906b7d40ba1855f0f842afe1f7f74d1d38b7366e2959bcfd6",
"diagnose_coverage.py": "f5305f0c429aea3ba5f18e4261abd64fe8254e53db24323ffcebc152734864b7",
"discovery_evidence.py": "dc7e0594b77f6d3723a965216164427835aa5ae2ff736b5599774c4efbc626eb",
"discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491",
"extract_catalog.py": "7c3b7de0291f52d9f37590b438d1abb7e37b36665cfb5e9ba4698b78a8f42574",
"extract_discovery.py": "5d2835cde2b9d4d895609ea39be2a94a22e894d0996d525dcc3df7046c33e681",
"extract_search.py": "09b3c0c65d33fdd5025e3436fb1bd5df67d1e359b507f4fae74a7e61754fc92c",
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
"fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7",
"gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537",
"image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8",
"inspect_bicycles.py": "e12964f244645b7a4b2bdb0da5d2bb90e7d49dc35bf2f66c4a8466fabc6836bb",
"inspect_catalog.py": "322aec8f233009eb42703132b220e1e216f8dc8b59aa6bbd27244067e651727d",
"interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345",
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
"line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738",
"mapping.py": "1c6ba0cc111250d73bc0bc282e9cbb7a602921bca931da6441bc9a6daf88b4f4",
"norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7",
"ortho_terrain.py": "9c9cab9d7086144fd1a108db28f796e9d267375d7135d50d5cb3f054eae75213",
"paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6",
"refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831",
"refine_catalog.py": "eeeee4d59066579c1fa8708a1be9d999a481f8f8daf05ec01704897252cc66cb",
"refine_completion.py": "12f424d39a687e8b94823f2e2f7b2f2c95538f3504260b4373c47cc21b29c6e1",
"refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36",
"refine_corridor.py": "fd1c4d4e028a037e32538c26a66f876425088b8b5b2c7ffc8d5dc807eba3290f",
"refine_discovery.py": "6272ca1f5052259fb3c6cfd1f1079e4e5864e1e067d12de7ff36d95857219d7b",
"refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5",
"refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8",
"refine_search.py": "113e8cee4f26d1f6b0bcce516388d046ced0523598ddf7f6f4e4dc365a0d9859",
"refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3",
"refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b",
"render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c",
"render_catalog.py": "58ecb30ac8ddffd1489c93361dc6678c82e4dbbfbe8a6e851a1be395ee40db1b",
"render_completion.py": "5e76d2a6ce41a6be8013f98df33951fe17fc209c078376ebfafe7c60ed0b14a7",
"render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682",
"render_corridor.py": "f6355e3761834fcf811c0cae9dc3ce602e7221afea4f674178d6c29085e87e9f",
"render_coverage.py": "2cba12c09333c242841b174f201c89ffce9e715b78b26b472117ae140ff4157c",
"render_discovery.py": "868ad8eb712f5880e944b0899205a2c0fd6dd0713eb727b1c49dda92b897fa20",
"render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d",
"render_plan.py": "9e702d51c6be09caa456d8e528bd62bc9ec238ca3689a99f38b414dafc193f66",
"render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e",
"render_search.py": "5655641df20c2e4f0849bb35ff4029d806554cc7d3b696d26378ad9d880d0491",
"render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c",
"render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d",
"road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322",
"row_evidence.py": "fec784ab795470d96e48c7022e59d5206b0c07b40d84843cbc058fcc4de896c0",
"row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df",
"search_rules.py": "ca3cab6d24f31460d9912c351c166d89fb1c3b21df620ba1d847543bd7a71f41",
"search_views.py": "8a123558dbef184fc85a92c9547c19644d14681329dbbd0cfeac0032bbd102be",
"section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de",
"test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b",
"test_catalog.py": "91a8fdbc330cecd5bc354406012852cc46245baf99ba8befdaac164f6b79c1c4",
"test_completion.py": "a3a6a283221ae48ade8fd0cca2f145509fd6bedf8e808967c13438791654a7f1",
"test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7",
"test_corridor.py": "42788835ec88e91a3b92ec7ead4e4c489b01ddf11256b46b7b3722c6b4770703",
"test_discovery.py": "a75ffc22d065201f7023d8e6cfb6dc09204a80f9be607599b85479628a301538",
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a",
"test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f",
"test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449",
"test_search.py": "fc3d874c8a6639bfa007eb8fa4a869e270bddafe317868bed29450c6024f8756",
"test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f",
"test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438",
"transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e",
"validation.py": "ee004220db3cdf2429af2a0e875cd9a63526587422881692ce56fe9d77f5cc2c"
},
"external_dependencies": {
"packaging-24.2-py3-none-any.whl": "09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759",
"scikit_image-0.24.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl": "8579bda9c3f78cb3b3ed8b9425213c53a25fa7e994b7ac01f2440b395babf660",
"imageio-2.36.1-py3-none-any.whl": "20abd2cae58e55ca1af8a8dcf43293336a59adf0391f1917bf8518633cfc2cdf",
"networkx-3.4.2-py3-none-any.whl": "df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5f",
"lazy_loader-0.4-py3-none-any.whl": "342aa8e14d543a154047afb4ba8ef17f5563baad3fc610d7b15b213b0f119efc",
"tifffile-2024.9.20-py3-none-any.whl": "c54dc85bc1065d972cb8a6ffb3181389d597876aa80177933459733e4ed243dd"
},
"external_review_font": {
"name": "review-font.ttf",
"sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9",
"purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP"
},
"deployment": false
}
@@ -0,0 +1,17 @@
"""Lane evidence measured in metres, independent of proposal fragmentation."""
import numpy as np
from catalog_rules import POLICY
def bicycle_context(p,parameters,records):
u=np.array([np.cos(parameters[2]),np.sin(parameters[2])]);origin=np.asarray(parameters[:2]);support=[];intervals=[]
for r in records:
alignment=abs(r['axis']@u)
if r['W']>.35 or not(.3<r['polygon'].distance(p)<POLICY['bicycle_context_radius_m'])or alignment<np.cos(np.deg2rad(POLICY['bicycle_context_angle_deg'])):continue
center=(r['center']-origin)@u;half=r['L']*alignment/2
intervals.append((center-half,center+half));support.append(r)
merged=[]
for a,b in sorted(intervals):
if merged and a<=merged[-1][1]:merged[-1][1]=max(merged[-1][1],b)
else:merged.append([a,b])
length=sum(b-a for a,b in merged)
return dict(passed=bool(length>=POLICY['bicycle_context_length_m']),supporting_strips=len(support),supporting_length_m=float(length),length_measure='union-of-longitudinal-intervals',source_tiles=sorted(set(r['source_tile']for r in support)))
@@ -0,0 +1,12 @@
"""Load pinned Linux wheels only into the disposable qualification container."""
from pathlib import Path
import sys,zipfile,hashlib,json
from catalog_dependency_pins import PINS
root=Path('/candidate');target=Path('/tmp/catalog-dependencies');target.mkdir(exist_ok=True)
for pin in PINS:
path=root/pin['file'];assert hashlib.sha256(path.read_bytes()).hexdigest()==pin['sha256']
with zipfile.ZipFile(path)as z:
assert all(not Path(n).is_absolute()and '..'not in Path(n).parts for n in z.namelist())
z.extractall(target)
sys.path.insert(0,str(target))
Path('/out/catalog-dependencies.json').write_text(json.dumps(PINS,indent=2))
File diff suppressed because one or more lines are too long
@@ -0,0 +1,36 @@
"""Two geometry-selected image mosaics for every point of a finite object.
No demand that both complete camera rectangles contain a long polygon's bbox.
Unknown paint pixels remain unknown; different ranks never use the same tile.
"""
import numpy as np,cv2,shapely
from fit_scene import project
from layer_common import sample
from row_evidence import choose_owners
from discovery_rules import glyph_score
def mosaic_views(p,views,kind=None,parameters=None):
lo=np.asarray(p.bounds[:2])-1.;hi=np.asarray(p.bounds[2:])+1.;cell=.04
xx=np.arange(lo[0],hi[0],cell);yy=np.arange(lo[1],hi[1],cell);x,y=np.meshgrid(xx,yy);points=np.c_[x.ravel(),y.ravel()]
distance=np.linalg.norm(points[:,None,:]-views.centers[None,:,:],axis=2);coverage=np.zeros(distance.shape,bool)
for i,tile in enumerate(views.tiles):
uv=project(points,views.geometry(tile['id']));coverage[:,i]=(uv.min(1)>=20)&(uv.max(1)<1180)
owners=choose_owners(distance,coverage);ev=[];names=set();target=shapely.contains_xy(p,points[:,0],points[:,1])
for rank in [0,1]:
colors=np.zeros((len(points),3),'uint8');allowed=np.zeros(len(points),bool);covered=np.zeros(len(points),bool);source_counts={}
for i in np.unique(owners[:,rank]):
if i<0:continue
select=np.flatnonzero(owners[:,rank]==i);name=views.tiles[i]['id'];g=views.geometry(name);rgb,vehicle=views.inputs(name);uv=project(points[select],g).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5
def read(a,q):return np.concatenate([cv2.remap(a,b[:,0,None],b[:,1,None],cv2.INTER_LINEAR).reshape(len(b),-1)for b in np.array_split(q,max(1,int(np.ceil(len(q)/20000))))])
colors[select]=read(rgb,native);allowed[select]=(read(g['alpha'].astype('float32'),uv).ravel()>=.65)&(read(vehicle,uv).ravel()<.2)&(sample(views.labels,points[select],views.low,views.high)==1);covered[select]=True
if target[select].any():names.add(name);source_counts[name]=int(target[select].sum())
score=glyph_score(colors.reshape(len(yy),len(xx),3),allowed.reshape(len(yy),len(xx)),points,p,kind=None,parameters=None)
rgb=colors.reshape(len(yy),len(xx),3);gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
bg=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(31,31)))
paint=((gray.astype(float)-bg>15)&(gray>100)&((hsv[:,:,1]<100)|((hsv[:,:,0]>12)&(hsv[:,:,0]<36))))
near=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))).ravel()>0
known=target&allowed&covered
score['observed_support']=float(near[known].mean())if known.any()else 0.
score.update(paint_valid=float(allowed[target].mean())if target.any()else 0.,paint_coverage=float(covered[target].mean())if target.any()else 0.,source_counts=source_counts,ownership='nearest-covering-geometry-per-pixel',rank=rank)
ev.append(score)
return ev,sorted(names)
@@ -0,0 +1,37 @@
"""One metric policy shared by every scene; observation windows are explicit."""
VERSION='marking-catalog-v1'
POLICY=dict(bicycle_fit_score=.65,bicycle_fit_support=.78,bicycle_fit_recall=.75,
bicycle_view_support=.78,bicycle_view_recall=.75,bicycle_view_valid=.97,
bicycle_negative_paint=.15,min_line_length_m=3.,min_line_valid=.98,
min_line_support=.93,min_line_contrast=22.,max_line_width_m=.30,
min_zigzag_legs=3,max_zigzag_joint_m=.30,max_zigzag_angle_error_deg=10.,
min_zigzag_leg_support=.85,min_zigzag_valid=.97,
strong_bicycle_fit=.72,strong_bicycle_support=.93,strong_bicycle_recall=.90,
strong_negative_paint=.12,strong_zigzag_support=.97,strong_zigzag_leg_support=.95,
strong_zigzag_min_legs=4,strong_zigzag_max_residual_m=.10,
strong_zigzag_proposal_recall=.85,additional_view_min_valid=.95,
bicycle_context_length_m=6.,bicycle_context_radius_m=10.,bicycle_context_angle_deg=15.,
manual_rois=[],point_cloud_input=False)
def two_supported(ev,valid,support,recall=0.,negative=1.):
return len(ev)==2 and all(e['paint_coverage']==1. and e['paint_valid']>=valid and e['support']>=support and e['recall']>=recall and e['negative_paint']<=negative for e in ev)
def additional_agrees(e,support):
coverage=e['paint_coverage']
return coverage==0. or(e['paint_valid']/coverage>=POLICY['additional_view_min_valid']and e['observed_support']>=support and e['negative_paint']<=POLICY['strong_negative_paint'])
def accept_bicycle(ev,score):
if two_supported(ev,POLICY['bicycle_view_valid'],POLICY['bicycle_view_support'],POLICY['bicycle_view_recall'],POLICY['bicycle_negative_paint']):return 'two-mosaics'
if len(ev)!=2 or score<POLICY['strong_bicycle_fit']:return None
e=ev[0]
if e['paint_coverage']==1. and e['paint_valid']>=POLICY['bicycle_view_valid']and e['support']>=POLICY['strong_bicycle_support']and e['recall']>=POLICY['strong_bicycle_recall']and e['negative_paint']<=POLICY['strong_negative_paint']and additional_agrees(ev[1],POLICY['strong_bicycle_support']):return 'strong-complete-view-plus-available-consistency'
return None
def accept_zigzag(ev,legs,fit):
if two_supported(ev,POLICY['min_zigzag_valid'],POLICY['min_zigzag_leg_support'])and all(two_supported(ee,POLICY['min_zigzag_valid'],POLICY['min_zigzag_leg_support'])for ee in legs):return 'two-mosaics'
if len(ev)!=2 or fit['legs']<POLICY['strong_zigzag_min_legs']or fit['fit_residual_m']>POLICY['strong_zigzag_max_residual_m']or fit['proposal_recall']<POLICY['strong_zigzag_proposal_recall']:return None
for ee,support in [(ev,POLICY['strong_zigzag_support'])]+[(ee,POLICY['strong_zigzag_leg_support'])for ee in legs]:
if len(ee)!=2:return None
e=ee[0]
if not(e['paint_coverage']==1. and e['paint_valid']>=POLICY['min_zigzag_valid']and e['support']>=support and e['negative_paint']<=POLICY['strong_negative_paint']and additional_agrees(ee[1],support)):return None
return 'strong-complete-view-plus-available-consistency'
@@ -0,0 +1,79 @@
"""Attributed bicycle artwork and OpenCV/SciPy template registration.
No map identity, review crop or world-coordinate exceptions are inputs.
"""
import re
import numpy as np, cv2, shapely
from shapely.geometry import Polygon
from shapely.affinity import affine_transform
from scipy.optimize import minimize
from bicycle_artwork import PATH
def svg_rings(path):
tokens=re.findall(r'[MLHVClmhvcZz]|[-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?',path)
rings=[];points=[];p=np.zeros(2);start=p.copy();i=0;command=None
while i<len(tokens):
if tokens[i].isalpha():command=tokens[i];i+=1
if command in 'Zz':
if points:rings.append(np.asarray(points))
points=[];p=start.copy();command=None;continue
relative=command.islower();kind=command.upper();count={'M':2,'L':2,'H':1,'V':1,'C':6}[kind]
v=np.asarray([float(t)for t in tokens[i:i+count]]);i+=count
if kind in ['M','L']:
p=v+p if relative else v;points.append(p.copy())
if kind=='M':start=p.copy();command='l'if relative else'L'
elif kind in ['H','V']:
k=0 if kind=='H'else 1;p[k]=p[k]+v[0]if relative else v[0];points.append(p.copy())
else:
b,c,d=v.reshape(3,2)+(p if relative else 0);a=p.copy()
for t in np.linspace(0,1,17)[1:]:points.append((1-t)**3*a+3*(1-t)**2*t*b+3*(1-t)*t*t*c+t**3*d)
p=d.copy()
return rings
def bicycle_unit():
rings=svg_rings(PATH);xy=np.concatenate(rings);lo=xy.min(0);span=xy.max(0)-lo
result=Polygon()
for r in rings:
normalized=(r-lo)/span
# As for the arrow artwork, road-longitudinal is SVG vertical.
# The two wheels sit across the road-marking symbol's lateral axis.
q=np.c_[1-normalized[:,1],.5-normalized[:,0]]
result=result.symmetric_difference(shapely.make_valid(Polygon(q)))
assert result.is_valid
return result
UNIT=bicycle_unit()
RASTER_UNIT=UNIT.simplify(.001,preserve_topology=True)
def bicycle(x,fast=False):
px,py,a,L,W=x[:5];c,s=np.cos(a),np.sin(a)
p=affine_transform(RASTER_UNIT if fast else UNIT,[L*c,-W*s,L*s,W*c,px,py])
return p.buffer(x[5],join_style=1)if len(x)>5 and abs(x[5])>.001 else p
def fit_bicycle(p,all_hypotheses=False):
if p.is_empty or p.area<.10:return None
rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);corners=cv2.boxPoints(rect);edges=np.roll(corners,-1,axis=0)-corners;k=np.argmax(np.linalg.norm(edges,axis=1));L=float(np.linalg.norm(edges[k]));W=float(min(rect[1]));u=edges[k]/L;ang=np.arctan2(u[1],u[0]);origin=np.asarray(rect[0]);fill=p.area/max(L*W,1e-6)
if not(1.<L<4.5 and .4<W<2.2 and 1.1<L/W<4 and .10<fill<.70):return None
closed=p.buffer(.04).buffer(-.04)
holes=[Polygon(h)for q in ([closed]if closed.geom_type=='Polygon'else getattr(closed,'geoms',[]))if q.geom_type=='Polygon'for h in q.interiors]
if sum(h.area>.015 for h in holes)<2:return None
cell=.02;lo=np.asarray(p.bounds[:2])-.4;hi=np.asarray(p.bounds[2:])+.4;size=np.ceil((hi-lo)/cell).astype(int)[::-1]
def draw(poly):
m=np.zeros(size,np.uint8)
for q in ([poly]if poly.geom_type=='Polygon'else getattr(poly,'geoms',[])):
if q.is_empty or q.geom_type!='Polygon':continue
cv2.fillPoly(m,[np.rint((np.asarray(q.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1)
for h in q.interiors:cv2.fillPoly(m,[np.rint((np.asarray(h.coords)[:,:2]-lo)/cell).astype('int32')],0)
return m
target=draw(p);kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5));near=cv2.dilate(target,kernel);best=None
def quality(x):
m=draw(bicycle(x,fast=True));wide=cv2.dilate(m,kernel);cover=float((m&near).sum()/max(m.sum(),1));recall=float((wide&target).sum()/max(target.sum(),1));iou=float((m&target).sum()/max((m|target).sum(),1));return cover,recall,.6*2*cover*recall/max(cover+recall,1e-6)+.4*iou
hypotheses=[]
for flip in [0,np.pi,np.pi/2,3*np.pi/2]:
along,across=(L,W)if flip in [0,np.pi]else(W,L)
a=ang+flip;u=np.array([np.cos(a),np.sin(a)]);base=origin-u*along/2;x=np.r_[base,a,along,across,0.]
bounds=[(base[0]-.25,base[0]+.25),(base[1]-.25,base[1]+.25),(a-.3,a+.3),(along*.85,along*1.15),(across*.75,across*1.25),(-.02,.025)]
opt=minimize(lambda x:1-quality(x)[2],x,method='Powell',bounds=bounds,options=dict(maxiter=35,xtol=.002,ftol=.002));q=quality(opt.x)
hypothesis=dict(polygon=bicycle(opt.x),score=q[2],support=q[0],recall=q[1],parameters=opt.x.tolist());hypotheses.append(hypothesis)
if best is None or q[2]>best['score']:best=hypothesis
return sorted(hypotheses,key=lambda x:-x['score'])if all_hypotheses else best
@@ -0,0 +1,54 @@
"""Raster skeleton + Douglas-Peucker + repeated-leg least-squares model.
The skeleton is only a proposal. Two original Gaussian render footprints must
support every regularized leg before anything is added to the map.
"""
import numpy as np,cv2,shapely
from shapely.geometry import Polygon,LineString
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import dijkstra
import catalog_dependencies
from skimage.morphology import skeletonize
def fit_zigzag(p):
if p.is_empty or p.geom_type!='Polygon':return None
rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);L,W=sorted(rect[1],reverse=True)
if not(3<L<60 and .45<W<5 and .03<p.area/(L*W)<.40):return None
cell=.025;lo=np.asarray(p.bounds[:2])-.1;hi=np.asarray(p.bounds[2:])+.1;size=np.ceil((hi-lo)/cell).astype(int)[::-1]
if np.prod(size)>1200000:return None
mask=np.zeros(size,np.uint8)
cv2.fillPoly(mask,[np.rint((np.asarray(p.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1)
for h in p.interiors:cv2.fillPoly(mask,[np.rint((np.asarray(h.coords)[:,:2]-lo)/cell).astype('int32')],0)
sk=skeletonize(mask>0);yy,xx=np.nonzero(sk)
if len(xx)<50:return None
lookup=np.full(mask.shape,-1,int);lookup[yy,xx]=np.arange(len(xx));aa=[];bb=[];dd=[]
for dy,dx in [(0,1),(1,0),(1,1),(1,-1)]:
y=yy+dy;x=xx+dx;valid=(y>=0)&(y<size[0])&(x>=0)&(x<size[1]);ids=np.flatnonzero(valid);other=lookup[y[valid],x[valid]];ok=other>=0;a=ids[ok];b=other[ok]
aa.extend(a);bb.extend(b);dd.extend([np.hypot(dx,dy)]*len(a));aa.extend(b);bb.extend(a);dd.extend([np.hypot(dx,dy)]*len(a))
graph=coo_matrix((dd,(aa,bb)),shape=(len(xx),len(xx))).tocsr();degree=np.diff(graph.indptr);ends=np.flatnonzero(degree==1)
if not 2<=len(ends)<=8:return None
dist,pred=dijkstra(graph,indices=ends,return_predecessors=True);dist[~np.isfinite(dist)]=-1;k,j=np.unravel_index(np.argmax(dist[:,ends]),(len(ends),len(ends)));a=int(ends[k]);b=int(ends[j]);ids=[b]
while ids[-1]!=a:
node=int(pred[k,ids[-1]])
if node<0:return None
ids.append(node)
xy=np.c_[xx[ids],yy[ids]]*cell+lo;curve=LineString(xy)
width=p.area/max(curve.length,1e-6)
if not .045<width<.30:return None
vertices=cv2.approxPolyDP(xy.astype('float32'),.10,False)[:,0,:].astype(float)
best=None
for begin in range(len(vertices)-3):
for end in range(begin+4,len(vertices)+1):
q=vertices[begin:end];legs=np.diff(q,axis=0);length=np.linalg.norm(legs,axis=1)
if length.min()<.55 or length.max()>5.5 or np.std(length)/np.mean(length)>.25:continue
u=legs/length[:,None];turn=np.arctan2(u[:-1,0]*u[1:,1]-u[:-1,1]*u[1:,0],(u[:-1]*u[1:]).sum(1))
if np.any(turn[:-1]*turn[1:]>=0)or np.min(abs(turn))<np.deg2rad(25)or np.max(abs(turn))>np.deg2rad(150)or np.std(abs(turn))>np.deg2rad(10):continue
idx=np.arange(len(q));X=np.c_[idx,(-1.)**idx,np.ones(len(q))];coef=np.linalg.lstsq(X,q,rcond=None)[0];fitted=X@coef;axis,amp=coef[:2]
if abs(axis@amp)/max(np.linalg.norm(axis)*np.linalg.norm(amp),1e-9)>.25:continue
residual=np.linalg.norm(fitted-q,axis=1)
if residual.max()>.16:continue
line=LineString(fitted);poly=line.buffer(width/2,cap_style=2,join_style=2)
score=p.intersection(poly.buffer(.04)).area/max(p.area,1e-6)
if score<.60:continue
if best is None or len(q)>len(best['vertices']):best=dict(polygon=poly,vertices=fitted.tolist(),width_m=float(width),legs=len(q)-1,fit_residual_m=float(residual.max()),proposal_recall=float(score))
return best
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="834.116" height="734.423" version="1.1">
<title>1.23 Дети</title>
<path style="fill:#ffffff;" d="m 0,689.423 c 0,24.853 20.147,45 45,45 l 744.116,0 c 24.853,0 45,-20.147 45,-45 c 0,-7.899 -2.079,-15.659 -6.029,-22.5 l -372.058,-644.423 c -8.038,-13.923 -22.894,-22.5 -38.971,-22.5 c -16.077,0 -30.933,8.577 -38.971,22.5 l -372.058,644.423 c -3.950,6.841 -6.029,14.601 -6.029,22.5 z"/>
<path style="fill:none;stroke:#000000;stroke-width:2px;" d="m 1,689.423 c 0,24.301 19.699,44 44,44 l 744.116,0 c 24.301,0 44,-19.699 44,-44 c 0,-7.724 -2.033,-15.311 -5.895,-22.0 l -372.058,-644.423 c -7.860,-13.614 -22.385,-22.0 -38.105,-22.0 c -15.720,0 -30.245,8.386 -38.105,22.0 l -372.058,644.423 c -3.862,6.689 -5.895,14.276 -5.895,22.0 z"/>
<path style="fill:#ff0000;" d="m 10,689.423 c 0,19.330 15.670,35 35,35 l 744.116,0 c 19.330,0 35,-15.670 35,-35 c 0,-6.144 -1.617,-12.179 -4.689,-17.5 l -372.058,-644.423 c -6.252,-10.829 -17.807,-17.5 -30.311,-17.5 c -12.504,0 -24.059,6.671 -30.311,17.5 l -372.058,644.423 c -3.072,5.321 -4.689,11.357 -4.689,17.5 z m 83.634,-33.852 c 0,-1.755 0.462,-3.480 1.340,-5.000 l 313.424,-542.866 c 1.786,-3.094 5.087,-5 8.660,-5.000 c 3.573,0 6.873,1.906 8.660,5.000 l 313.424,542.866 c 0.878,1.520 1.340,3.245 1.340,5.000 c 0,5.523 -4.477,10 -10,10 l -626.848,0 c -5.523,0 -10,-4.477 -10,-10 z"/>
<path style="fill:#000000;" d="m 251.135,593.850 c -1.511,2.617 -2.306,5.585 -2.306,8.607 c 0,9.507 7.707,17.213 17.213,17.213 c 6.150,0 11.832,-3.281 14.907,-8.607 l 47.413,-82.121 l 49.584,-29.793 c 4.144,-2.490 6.678,-6.970 6.678,-11.804 c 0,-2.417 -0.636,-4.792 -1.845,-6.885 l -31.705,-54.915 c -1.209,-2.093 -1.845,-4.468 -1.845,-6.885 c 0,-2.417 0.636,-4.792 1.845,-6.885 l 44.478,-77.038 c 1.309,-2.268 1.999,-4.840 1.999,-7.459 c 0,-8.239 -6.679,-14.918 -14.918,-14.918 c -5.330,0 -10.254,2.843 -12.919,7.459 l -65.016,112.612 c -1.209,2.093 -1.845,4.468 -1.845,6.885 c 0,2.417 0.636,4.792 1.845,6.885 l 22.997,39.831 l -21.518,15.067 c -1.647,1.153 -3.022,2.653 -4.027,4.395 z"/>
<path style="fill:#000000;" d="m 351.625,527.013 l 29.313,50.772 c 2.460,4.261 7.006,6.885 11.926,6.885 l 31.080,0 l 0,-34.426 l -19.154,0 l -23.651,-40.964 z"/>
<path style="fill:#000000;" d="m 295.830,449.204 l -24.766,14.299 l -17.233,-29.849 c -2.665,-4.616 -7.590,-7.459 -12.919,-7.459 c -8.239,0 -14.918,6.679 -14.918,14.918 c 0,2.619 0.689,5.191 1.999,7.459 l 25.266,43.762 c 2.460,4.261 7.006,6.885 11.926,6.885 c 2.417,0 4.792,-0.636 6.885,-1.845 l 38.679,-22.331 z"/>
<path style="fill:#000000;" d="m 266.042,380.638 c 0,17.901 14.918,31.672 29.262,31.672 c 22.033,0 30.869,-38.902 30.869,-46.475 c 0,-14.459 -7.229,-26.164 -22.492,-26.164 c -15.606,0 -37.639,20.770 -37.639,40.967 z"/>
<path style="fill:#000000;" d="m 433.124,601.309 c 0,10.140 8.220,18.361 18.361,18.361 c 10.140,0 18.361,-8.220 18.361,-18.361 l 0,-97.122 l 80.673,-46.577 c 7.101,-4.100 11.475,-11.676 11.475,-19.876 c 0,-4.029 -1.060,-7.986 -3.075,-11.475 l -39.391,-68.228 l 40.779,0 l -18.541,-32.131 l -53.705,0 c -4.493,0 -8.703,2.192 -11.280,5.872 l -14.708,21.006 c -1.621,2.315 -2.490,5.072 -2.490,7.898 c 0,2.417 0.636,4.792 1.845,6.885 l 42.904,74.312 l -64.322,37.137 c -4.261,2.460 -6.885,7.006 -6.885,11.926 z"/>
<path style="fill:#000000;" d="m 528.184,483.755 l 36.442,63.119 c 2.050,3.550 5.838,5.738 9.938,5.738 c 2.014,0 3.993,-0.530 5.738,-1.537 l 68.615,-39.566 l -18.361,-31.801 l -46.730,26.979 l -23.840,-41.292 z"/>
<path style="fill:#000000;" d="m 453.184,373.939 l -24.905,43.137 l -38.647,-22.313 c -2.617,-1.511 -5.585,-2.306 -8.607,-2.306 c -9.507,0 -17.213,7.707 -17.213,17.213 c 0,6.150 3.281,11.832 8.607,14.907 l 56.535,32.641 c 1.744,1.007 3.723,1.537 5.738,1.537 c 4.100,0 7.888,-2.187 9.938,-5.738 l 27.105,-46.947 z"/>
<path style="fill:#000000;" d="m 416.599,305.015 c 0,23.639 21.918,36.262 32.820,36.262 c 16.754,0 35.458,-35.114 35.458,-54.622 c -0.459,-16.181 -9.754,-26.967 -23.983,-26.967 c -19.393,0 -44.295,21.458 -44.295,45.327 z"/>
</svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

@@ -0,0 +1,54 @@
"""Native full-frame paint proposals for compact bicycles and long zigzags."""
from pathlib import Path
import json,time,hashlib
import numpy as np,cv2,shapely
from shapely.geometry import Polygon,mapping,shape
from layer_common import O,S,sample,parts
from fit_scene import world,project
from search_views import SearchViews
cv2.setNumThreads(3);start=time.monotonic()
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];low,high=z['bounds']
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,labels,low,high,None)
def eligible(p):
if p.is_empty or p.area<.08:return False
rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);L,W=sorted(rect[1],reverse=True)
if W<=0:return False
fill=p.area/(L*W)
return (1.<L<4.5 and .4<W<2.2 and 1.1<L/W<4 and .10<fill<.70)or(3<L<60 and .45<W<5 and .03<fill<.40)
glyphs=[];reports=[]
for tile in views.tiles:
name=tile['id'];g=views.geometry(name);rgb,raw_vehicle=views.inputs(name);size=rgb.shape[0];mpp=60/size
def xy(uv):return world((np.asarray(uv)+.5)*1200/size-.5,g)
# Sample the road field on the calibrated 1200px grid, then upsample its
# categorical gate. No semantic marking confidence is an admission gate.
yy,xx=np.mgrid[:1200,:1200];points=world(np.c_[xx.ravel(),yy.ravel()],g)
road=(sample(labels,points,low,high)==1).reshape(1200,1200)
allowed=cv2.resize((road&(raw_vehicle<.2)&(g['alpha']>.65)).astype('uint8'),(size,size),interpolation=cv2.INTER_NEAREST)>0
gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV);kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(int(.7/mpp)//2*2+1,)*2)
ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,kernel);binary=((ridge>12)&(gray>100)&((hsv[:,:,1]<100)|((hsv[:,:,0]>12)&(hsv[:,:,0]<36)))&allowed).astype('uint8')
cc,hier=cv2.findContours(binary,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE);components=[]
if hier is not None:
for i,c in enumerate(cc):
if hier[0,i,3]>=0 or cv2.contourArea(c)*mpp*mpp<.008:continue
holes=[];j=hier[0,i,2]
while j>=0:
if cv2.contourArea(cc[j])*mpp*mpp>.003:holes.append(xy(cc[j][:,0]))
j=hier[0,j,0]
components.extend(parts(shapely.make_valid(Polygon(xy(c[:,0]),holes))))
union=shapely.union_all(components);candidates=list(components)
for radius in [.08,.16]:
for region in parts(union.buffer(radius).buffer(-radius)):
if eligible(region):candidates.append(union.intersection(region.buffer(.015)))
accepted=[]
for p in candidates:
if not eligible(p):continue
if any(p.intersection(q).area/min(p.area,q.area)>.85 for q in accepted):continue
accepted.append(p);glyphs.append(dict(geometry=mapping(p),source_tile=name))
reports.append(dict(tile=name,proposal_pixels=size,candidates=len(accepted)));print('TILE',name,'CANDIDATES',len(accepted),flush=True)
candidates=[];ordered=sorted([(r,shape(r['geometry']))for r in glyphs],key=lambda v:-v[1].area)
geometries=[p for _,p in ordered];tree=shapely.STRtree(geometries);accepted=set()
for i,(r,p) in enumerate(ordered):
if any(j in accepted and p.intersection(geometries[j]).area/min(p.area,geometries[j].area)>.85 for j in tree.query(p,predicate='intersects')):continue
candidates.append(r);accepted.add(i)
(O/'catalog-proposals.json').write_text(json.dumps(dict(glyphs=candidates,tile_reports=reports,seconds=time.monotonic()-start,baseline_sha256=hashlib.sha256(Path('/fullplan/full-map.json').read_bytes()).hexdigest(),source='all native Gaussian frames; class-specific size ranges; no manual regions'),allow_nan=False))
print('PROPOSALS',len(candidates),'SECONDS',time.monotonic()-start,flush=True)
@@ -0,0 +1,24 @@
"""Exhaustive visual QA of every fitted bicycle proposal; no processing ROI."""
import json,numpy as np,shapely
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape
from layer_common import O,S,parts
from search_views import SearchViews
from fit_scene import project
from catalog_templates import bicycle
proposals=json.loads((O/'catalog-proposals.json').read_text())['glyphs'];diag=json.loads((O/'catalog-diagnostics.json').read_text());best={}
for r in diag:
if r['kind']!='bicycle':continue
i=r['proposal']
if i not in best or r['score']>best[i]['score']:best[i]=r
rows=sorted(best.values(),key=lambda r:-r['score']);tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,None,None,None,None);font=ImageFont.truetype('/candidate/review-font.ttf',18)
for start in range(0,len(rows),12):
batch=rows[start:start+12];sheet=Image.new('RGB',(1800,340*int(np.ceil(len(batch)/3))),'white');d=ImageDraw.Draw(sheet)
for k,r in enumerate(batch):
item=proposals[r['proposal']];name=item['source_tile'];p=shape(item['geometry']);fit=bicycle(r['parameters']);g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);factor=raw.width/1200;coords=shapely.get_coordinates(p.union(fit));uv=project(coords,g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(uv.max(0)-uv.min(0))+raw.width*.5/60;bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));over=raw.copy();draw=ImageDraw.Draw(over)
for poly in parts(fit):
for ring in [poly.exterior]+list(poly.interiors):draw.line([tuple(x)for x in project(ring.coords,g)*factor],fill='#efc400',width=2)
x=(k%3)*600;y=(k//3)*340
sheet.paste(raw.crop(bbox).resize((295,295)),(x,y+40));sheet.paste(over.crop(bbox).resize((295,295)),(x+300,y+40));d.text((x+4,y+5),str(r['proposal'])+' score '+str(round(r['score'],3))+' '+name,font=font,fill='black')
sheet.save(O/('bike-review-%03d.jpg'%start),quality=95)
print('BICYCLE PROPOSALS REVIEWED',len(rows),flush=True)
@@ -0,0 +1,27 @@
"""Exhaustive review of existing image proposals; no processing ROI selection."""
from pathlib import Path
import json, numpy as np
from PIL import Image, ImageDraw, ImageFont
from shapely.geometry import shape
from layer_common import O,S
from search_views import SearchViews
from fit_scene import project
import sys,cv2,importlib.util
print('ENV',sys.version,'CV',cv2.__version__,'XIMGPROC',hasattr(cv2,'ximgproc'),'SCIPY',importlib.util.find_spec('scipy')is not None,flush=True)
p=json.loads(Path('/fullplan/search-proposals.json').read_text())
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
views=SearchViews(tiles,None,None,None,None)
font=ImageFont.truetype('/candidate/review-font.ttf',18)
stats=[]
for start in range(0,len(p['glyphs']),20):
group=p['glyphs'][start:start+20];sheet=Image.new('RGB',(1600,260*int(np.ceil(len(group)/5))),'white');d=ImageDraw.Draw(sheet)
for k,r in enumerate(group):
poly=shape(r['geometry']);name=r['source_tile'];g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);factor=raw.width/1200
coords=np.array(poly.convex_hull.exterior.coords);uv=project(coords,g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(uv.max(0)-uv.min(0))+factor*12
bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));sheet.paste(raw.crop(bbox).resize((240,240)),((k%5)*320,(k//5)*260+20))
d.text(((k%5)*320,(k//5)*260),str(start+k)+' '+name,font=font,fill='black')
stats.append(dict(index=start+k,tile=name,area=poly.area,bounds=poly.bounds))
sheet.save(O/('proposals-%03d.jpg'%start),quality=95)
(O/'proposal-inspection.json').write_text(json.dumps(stats,indent=2))
print('PROPOSALS',len(stats),flush=True)
@@ -0,0 +1,107 @@
from pathlib import Path
import os,json,time,hashlib,collections
import numpy as np,cv2,shapely
from shapely.geometry import shape,mapping,LineString
from shapely.ops import transform
from layer_common import O,S,sample,feature,parts
from search_views import SearchViews
from discovery_rules import unpack,uncovered,glyph_context
from discovery_evidence import glyph_views
from catalog_evidence import mosaic_views
from line_reconstruction import rows
from beta_profiles import describe,profiles,section_evidence
from interval_profiles import rectangle
from corridor_profiles import missing_sections
from catalog_templates import fit_bicycle
from catalog_zigzag import fit_zigzag
from catalog_rules import VERSION,POLICY,accept_bicycle,accept_zigzag
from catalog_context import bicycle_context
cv2.setNumThreads(3);started=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());current={f['id']:f for f in old['features']}
proposal_path=Path('/fullplan/search-proposals.json');proposals=json.loads(proposal_path.read_text())
fresh_path=O/'catalog-proposals.json';fresh=json.loads(fresh_path.read_text());assert fresh['baseline_sha256']==hashlib.sha256(baseline.read_bytes()).hexdigest()
proposals['glyphs']=fresh['glyphs']
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds']
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
def poly(f):return shapely.force_2d(shape(f['geometry']))
def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
existing=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'])
protected=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'])
views=SearchViews(tiles,labels,low,high,protected);transactions=[];diagnostics=[]
def admit(p,subtype,kind,evidence,names,**extra):
global existing
if not uncovered(p,existing):return False
f=feature(lift(p),'road_marking',subtype=subtype,method=VERSION,source_tile=names[0],source_tiles=names,standard_compliance='not_assessed',**extra)
if f['id']in current:return False
current[f['id']]=f;existing=shapely.union_all([existing,p]);transactions.append(dict(kind=kind,source_ids=[],output_ids=[f['id']],before=[],after=[f],bounds_xy=p.bounds,evidence=evidence,source_tiles=names,**extra));print('ADMIT',len(transactions),subtype,kind,flush=True);return True
for i,r in enumerate(proposals['glyphs']):
p=shape(r['geometry']);fits=fit_bicycle(p,all_hypotheses=True)
if not fits:continue
for fit in fits:
diag={k:v for k,v in fit.items()if k!='polygon'};diag.update(kind='bicycle',proposal=i);diagnostics.append(diag)
if fit['score']<POLICY['bicycle_fit_score']or fit['support']<POLICY['bicycle_fit_support']or fit['recall']<POLICY['bicycle_fit_recall']:continue
p=fit['polygon'];context=bicycle_context(p,fit['parameters'],[unpack(r)for r in proposals['lines']]);diag['lane_context']=context
if not context['passed']:continue
ev,names=mosaic_views(p,views);diag.update(evidence=ev,source_tiles=names)
mode=accept_bicycle(ev,fit['score']);diag['passed']=bool(mode);diag['evidence_mode']=mode
if mode and admit(p,'bicycle','preset-bicycle',ev,names,evidence_mode=mode,template_parameters=fit['parameters'],template_fit_score=fit['score'],lane_context=context,artwork='1.23.3 Russian road marking / Major Alexey / CC BY-SA 4.0'):break
print('BICYCLES DONE',len(diagnostics),flush=True)
# Existing full-image proposals supply connected paint components. A small
# closing joins overlapping proposals, not unknown road segments.
records=[unpack(r)for r in proposals['lines']]
components=[shape(r['geometry'])for r in proposals['glyphs']]
components += [r['polygon']for r in records if .6<r['L']<5.5 and .045<r['W']<.30]
groups=parts(shapely.union_all(components).buffer(.055,join_style=2).buffer(-.055,join_style=2))
groups += [p for component in components for p in parts(component)]
for i,p in enumerate(groups):
fit=fit_zigzag(p)
if fit is None:continue
q=fit['polygon'];ev,names=mosaic_views(q,views);leg_ev=[]
for a,b in zip(fit['vertices'],fit['vertices'][1:]):
ee,nn=mosaic_views(LineString([a,b]).buffer(fit['width_m']/2,cap_style=2),views);leg_ev.append(ee)
mode=accept_zigzag(ev,leg_ev,fit)
diagnostics.append(dict(kind='zigzag',group=i,passed=bool(mode),evidence_mode=mode,evidence=ev,leg_evidence=leg_ev,**{k:v for k,v in fit.items()if k!='polygon'}))
if mode:admit(q,'zigzag','regularized-zigzag',dict(whole=ev,legs=leg_ev),names,evidence_mode=mode,vertices=fit['vertices'],leg_count=fit['legs'],width_m=fit['width_m'],fit_residual_m=fit['fit_residual_m'],proposal_recall=fit['proposal_recall'])
print('ZIGZAGS DONE',len(transactions),flush=True)
# Visible portions of a long stripe do not need a dark physical end inside the
# same camera. They remain explicitly observation-window-bounded segments.
# Every admitted portion is positively supported in BOTH Gaussian mosaics.
views.protected=shapely.union_all([protected]+[poly(f).convex_hull for f in current.values()if f['properties'].get('method')==VERSION])
seeds=[]
for r in records:
if r['L']>=3 and r['W']<=POLICY['max_line_width_m']:
s=describe(r['polygon'])
if s is not None:seeds.append(s)
for rr in rows(records):
if len(rr['records'])<2:continue
u=rr['axis'];o=rr['origin'];ranges=sorted([[(r['center']-o)@u-r['L']/2,(r['center']-o)@u+r['L']/2]for r in rr['records']]);chunks=[]
for a,b in ranges:
if chunks and a-chunks[-1][1]<=.30:chunks[-1][1]=max(chunks[-1][1],b)
else:chunks.append([a,b])
for a,b in chunks:
if 3<b-a<55:seeds.append(dict(origin=o+(a+b)/2*u,axis=u,length=b-a,width=.12))
seen=[];stats=collections.Counter()
for i,seed in enumerate(sorted(seeds,key=lambda s:-s['length'])):
domain=rectangle(seed['origin'],seed['axis'],-seed['length']/2,seed['length']/2,.14)
if domain.intersection(existing.buffer(.10)).area/domain.area>.97:continue
if any(domain.intersection(q).area/domain.area>.85 for q in seen):continue
seen.append(domain);readers,used=views.readers(seed['origin'],seed['axis']);pv=profiles(seed,readers,extension=.5)
if pv is None:stats['no_profile']+=1;continue
width=float(np.clip(np.median([v['width']for v in pv]),.075,.27));offset=float(np.mean([v['offset']for v in pv]))
for a,b in pv[0]['intervals']:
for c,d in pv[1]['intervals']:
lo=max(a,c,-seed['length']/2);hi=min(b,d,seed['length']/2)
if hi-lo<POLICY['min_line_length_m']:continue
ev=[section_evidence(v,lo+.05,hi-.05)for v in pv]
if not all(e['valid']>=POLICY['min_line_valid']and e['support']>=POLICY['min_line_support']and e['contrast']>=POLICY['min_line_contrast']for e in ev):stats['weak_paint']+=1;continue
parent=rectangle(seed['origin'],seed['axis'],lo,hi,width,offset)
for section in missing_sections(parent,existing):
scores,names=glyph_views(section,views,None,None)
if len(scores)!=2 or not all(e['valid']>=POLICY['min_line_valid']and e['support']>=POLICY['min_line_support']for e in scores):stats['section_views_rejected']+=1;continue
admit(section,'linear_marking','observed-continuous-section',dict(profile=ev,section=scores,parent_geometry=mapping(parent)),names,line_kind='observed-continuous',endpoint_authority='observed_window_not_physical_end',width_m=width)
if i%50==0:print('LINES',i,'/',len(seeds),'ADMITTED',len(transactions),flush=True)
result={**old,'features':list(current.values()),'catalog_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'catalog-rows.json').write_text(json.dumps(transactions,indent=2,allow_nan=False));(O/'catalog-diagnostics.json').write_text(json.dumps(diagnostics,indent=2,allow_nan=False));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes())
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),proposal_cache_sha256=hashlib.sha256(proposal_path.read_bytes()).hexdigest(),catalog_proposals_sha256=hashlib.sha256(fresh_path.read_bytes()).hexdigest(),proposal_cache_baseline_sha256=proposals['baseline_sha256'],changed_segments=len(transactions),added_objects=len(transactions),added_subtypes=dict(collections.Counter(r['after'][0]['properties']['subtype']for r in transactions)),stages=dict(collections.Counter(r['kind']for r in transactions)),diagnostics=dict(stats),profiled_axes=len(seen),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
(O/'catalog-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
@@ -0,0 +1,33 @@
from pathlib import Path
import os,json,shutil
from datetime import datetime,timezone
import numpy as np,shapely
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape
from layer_common import O,S
from search_views import SearchViews
from fit_scene import project
old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'catalog-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23)
for p in O.glob('catalog-*.jpg'):
h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name)
def draw(im,g,features):
im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200
for f in features:
if f['properties'].get('class')!='road_marking':continue
for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2)))
return im
views=SearchViews(tiles,None,None,None,None);tiles=views.tiles
frames=[];manifest=[];loaded={}
for gi,rec in enumerate(groups):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id']
if name not in loaded:
g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))}
g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]):
frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640')
fn='catalog-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects']))
for start in range(0,len(frames),4):
part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white')
for k,im in enumerate(part):sheet.paste(im,(0,k*655))
sheet.save(O/('catalog-proof-%03d.jpg'%(start//4+1)),quality=94)
(O/'catalog-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True)
@@ -0,0 +1,109 @@
"""Evidence images from metric vectors, not AI-generated imagery."""
from pathlib import Path
import json,os,shapely
from datetime import datetime,timezone
import shutil
import numpy as np
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape,box
from fit_scene import project
from search_views import SearchViews
from layer_common import B,O,S
D=json.loads((O/'full-map.json').read_text());v=json.loads((B/'viewer-data.json').read_text());low,high=np.asarray(v['bounds_xy']);res=v['resolution_m'];fontpath='/candidate/review-font.ttf'
from collections import Counter
(O/'catalog-inventory.json').write_text(json.dumps(dict(scene=os.environ['SCENE'],classes=dict(Counter(f['properties']['class']for f in D['features'])),marking_features=dict(Counter(f['properties'].get('subtype','unknown')for f in D['features']if f['properties']['class']=='road_marking')),crosswalk_count_unit='individual painted bars, not crossings',coverage_recall_measured=False),indent=2))
prior=set(O.glob('bridge-*.jpg'))|{O/'glyph-proof.jpg'}
for p in prior:
if p.exists():
history=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));history.mkdir(parents=True,exist_ok=True);shutil.move(p,history/p.name)
try:font=ImageFont.truetype(fontpath,20)
except OSError:font=ImageFont.load_default()
colors={'road_boundary':(236,124,25),'pedestrian_boundary':(18,165,92),'building_facade':(0,151,224),'road_marking':(241,195,0)}
def draw_plan(im,projector,features,width=3):
rgba=im.convert('RGBA');fill=Image.new('RGBA',im.size);df=ImageDraw.Draw(fill)
for f in features:
if f['properties']['class']!='pedestrian_area':continue
rings=f['geometry']['coordinates']
df.polygon([tuple(q)for q in projector(rings[0])],fill=(25,193,120,58))
for ring in rings[1:]:df.polygon([tuple(q)for q in projector(ring)],fill=(0,0,0,0))
rgba=Image.alpha_composite(rgba,fill);draw=ImageDraw.Draw(rgba)
for cls in ['pedestrian_boundary','building_facade','road_marking','road_boundary']:
for f in features:
if f['properties']['class']!=cls:continue
rings=f['geometry']['coordinates']if f['geometry']['type']=='Polygon'else[f['geometry']['coordinates']]
for ring in rings:
pts=[tuple(q)for q in projector(ring)];draw.line(pts,fill=colors[cls],width=width,joint='curve')
return rgba.convert('RGB')
def title(im,name):
result=Image.new('RGB',(im.width,im.height+68),'white');result.paste(im,(0,68));d=ImageDraw.Draw(result);d.text((15,7),name,font=font,fill='#263640')
x=15
for text,clr in [('Дороги',(236,124,25)),('Пешеходные зоны',(18,165,92)),('Фасады',(0,151,224)),('Разметка',(200,155,0))]:
d.rectangle((x,42,x+20,57),fill=clr);d.text((x+29,37),text,font=font,fill='#263640');x+=int(d.textlength(text,font=font))+64
return result
world=lambda p:np.c_[(np.asarray(p)[:,0]-low[0])/res,(high[1]-np.asarray(p)[:,1])/res]
if (B/'whole-gaussians.jpg').exists():base=Image.open(B/'whole-gaussians.jpg').convert('RGB')
else:
width,height=v['size'];mosaic=np.full((height,width,3),255,np.uint8);weights=np.zeros((height,width),np.float32)
for tile in json.loads((S/'tile-index.json').read_text())['tiles']:
if tile['status']!='surveyed':continue
lo,hi=np.asarray(tile['bounds_xy']);tw,th=np.rint((hi-lo)/res).astype(int);x,y=np.rint([(lo[0]-low[0])/res,(high[1]-hi[1])/res]).astype(int)
im=np.asarray(Image.open(S/tile['id']/'top.png').convert('RGB').resize((tw,th),Image.Resampling.LANCZOS));g=np.load(S/tile['id']/'top.geometry.npz');alpha=np.asarray(Image.fromarray(g['alpha'].astype('float32')).resize((tw,th),Image.Resampling.BILINEAR));g.close()
yy,xx=np.mgrid[:th,:tw];score=(.01+np.minimum.reduce([xx+1,yy+1,tw-xx,th-yy])/max(tw,th))*np.clip(alpha,0,1);sl=np.s_[y:y+th,x:x+tw];take=score>weights[sl];mosaic[sl][take]=im[take];weights[sl][take]=score[take]
base=Image.fromarray(mosaic)
whole=draw_plan(base,world,D['features']);whole.save(O/'whole-overlay.jpg',quality=96)
plan=draw_plan(Image.new('RGB',base.size,'#f5f5f2'),world,D['features']);title(plan,{'smolensk':'Смоленский бульвар','maroseyka':'Маросейка','pokrovka':'Покровка'}.get(os.environ['SCENE'],os.environ['SCENE'])+' · инженерные слои').save(O/'whole-plan.jpg',quality=96)
preview=whole.copy();preview.thumbnail((2300,1500));title(preview,{'smolensk':'Смоленский бульвар','maroseyka':'Маросейка','pokrovka':'Покровка'}.get(os.environ['SCENE'],os.environ['SCENE'])+' · четыре слоя поверх гауссов').save(O/'overview.jpg',quality=96)
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];scores=[];records=[]
for tile in tiles:
name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));domain=box(*tile['bounds_xy'][0],*tile['bounds_xy'][1]);features=[f for f in D['features']if shape(f['geometry']).intersects(domain)];counts={c:sum(f['properties']['class']==c for f in features)for c in ['building_facade','road_marking','pedestrian_area','road_boundary']}
image=Image.open(S/name/'top.png').convert('RGB');overlay=draw_plan(image,lambda p:project(p,g),features)
overlay.save(O/(name+'.overlay.jpg'),quality=95);image.save(O/(name+'.source.jpg'),quality=95)
score=sum(v>0 for v in counts.values())*100+min(counts['building_facade'],10)*3+min(counts['road_marking'],20)
scores.append((score,name));records.append(dict(tile=name,counts=counts))
chosen=[]
for score,name in sorted(scores,reverse=True):
if any(abs(int(name.split('-')[1])-int(n.split('-')[1]))<2 for n in chosen):continue
chosen.append(name)
if len(chosen)==3:break
sheet=Image.new('RGB',(1800,950*len(chosen)),'white');draw=ImageDraw.Draw(sheet)
for row,name in enumerate(chosen):
for col,suffix in enumerate(['source','overlay']):
im=Image.open(O/(name+'.'+suffix+'.jpg')).resize((900,900),Image.Resampling.LANCZOS);sheet.paste(im,(900*col,950*row+50));draw.text((900*col+12,950*row+12),name+' · '+('Гауссы'if col==0 else'Все слои'),font=font,fill='#263640')
sheet.save(O/'details.jpg',quality=96)
(O/'visual-manifest.json').write_text(json.dumps(dict(review_only_selection='automatic class diversity with spatial separation',selected=chosen,all_tiles=records,manual_processing_rois=[]),indent=2));print('PICTURES',chosen,flush=True)
# Whole-scene before/after comparison and an exhaustive glyph evidence sheet.
old=json.loads(Path('/fullplan/full-map.json').read_text())
before=draw_plan(base,world,old['features']);before.thumbnail((2300,1500))
after=whole.copy();after.thumbnail((2300,1500))
rows=[title(before,os.environ['SCENE']+' · предыдущая сборка'),title(after,os.environ['SCENE']+' · уточнение')]
comparison=Image.new('RGB',(max(x.width for x in rows),sum(x.height for x in rows)+12),'white');y=0
for row in rows:comparison.paste(row,(0,y));y+=row.height+12
comparison.save(O/'comparison-full.jpg',quality=95)
search_views=SearchViews(tiles,None,None,None,None)
glyphs=[f for f in D['features']if f['properties'].get('subtype')not in [None,'linear_marking','crosswalk']]
if glyphs:
sheet=Image.new('RGB',(1600,270*int(np.ceil(len(glyphs)/4))),'white');d=ImageDraw.Draw(sheet)
for k,item in enumerate(glyphs):
prop=item['properties'];name=prop.get('source_tile')
if not name:continue
g=search_views.geometry(name);raw=Image.fromarray(search_views.inputs(name)[0]);factor=raw.width/1200
xy=shapely.get_coordinates(shape(item['geometry']));uv=project(xy,g)*factor;lo=uv.min(0)-25;hi=uv.max(0)+25;center=(lo+hi)/2;extent=max(hi-lo);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int))
overlay=draw_plan(raw,lambda p:project(p,g)*factor,[item],width=3)
for j,im in enumerate([raw,overlay]):sheet.paste(im.crop(bbox).resize((195,195),Image.Resampling.LANCZOS),((k%4)*400+j*200,(k//4)*270+65))
d.text(((k%4)*400+5,(k//4)*270+8),str(k+1)+' '+prop['subtype'],font=font,fill='#263640');d.text(((k%4)*400+5,(k//4)*270+34),name,font=font,fill='#263640')
sheet.save(O/'glyph-proof.jpg',quality=96)
# Inspect every admitted road interpolation, not a hand-picked success crop.
spans=[(f,s)for f in D['features']if f['properties']['class']=='road_boundary'for s in f['properties'].get('inferred_spans',[])]
if spans:
sheet=Image.new('RGB',(1800,645*len(spans)),'white');d=ImageDraw.Draw(sheet)
for k,(owner,span)in enumerate(spans):
coords=np.array(span['coordinates']);center=coords[:,:2].mean(0)
tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'))
raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200
uv=project(coords,g)*factor;middle=(uv.min(0)+uv.max(0))/2;extent=max(uv.max(0)-uv.min(0))+raw.width*8/60;extent=max(extent,raw.width*18/60)
bbox=tuple(np.r_[middle-extent/2,middle+extent/2].astype(int))
for col,(fs,label)in enumerate([(None,'Гауссы'),(old['features'],'До'),(D['features'],'После')]):
im=raw if fs is None else draw_plan(raw,lambda p:project(p,g)*factor,fs,width=max(2,int(factor*2)))
patch=im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS);sheet.paste(patch,(col*600,k*645+45));d.text((col*600+10,k*645+10),str(k+1)+' · '+label,font=font,fill='#263640')
sheet.save(O/'bridge-proof.jpg',quality=95)
for k in range(len(spans)):sheet.crop((0,k*645,1800,(k+1)*645)).save(O/('bridge-%02d.jpg'%(k+1)),quality=96)
@@ -0,0 +1,69 @@
import runpy,json,numpy as np,cv2,shapely
from shapely.geometry import LineString,box
from shapely.affinity import rotate,translate,scale
from catalog_templates import bicycle,fit_bicycle,UNIT
from catalog_zigzag import fit_zigzag
from fragment_templates import template
from beta_profiles import profiles,section_evidence
from catalog_rules import POLICY
prior=runpy.run_path('/candidate/test_search.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()}
checks['bicycle_artwork_preserves_wheel_voids']=UNIT.is_valid and len(UNIT.interiors)>=3
for name,angle,L,W in [('upright',0.,1.7,.9),('rotated',.8,2.3,1.1),('reverse',3.4,1.6,.75),('wider_than_long',.2,.9,1.7)]:
source=bicycle([12,-7,angle,L,W,0]);fit=fit_bicycle(source)
checks['bicycle_'+name+'_registration']=fit is not None and fit['score']>.85 and fit['polygon'].symmetric_difference(source).area/source.area<.30
for kind in ['letter_A','straight_arrow','right_arrow','straight_left_arrow']:
p=template(kind,2.5,1.,.16);fit=fit_bicycle(p)
checks[kind+'_not_a_bicycle']=fit is None or fit['score']<POLICY['bicycle_fit_score']or fit['support']<POLICY['bicycle_fit_support']or fit['recall']<POLICY['bicycle_fit_recall']
zig=LineString([(0,0),(2,1.8),(4,0),(6,1.8),(8,0),(10,1.8)]).buffer(.06,cap_style=2,join_style=2)
for angle in [0,37,121]:
p=translate(rotate(zig,angle,origin=(0,0)),24,-18);fit=fit_zigzag(p)
checks['zigzag_rotation_'+str(angle)]=fit is not None and fit['legs']>=4 and fit['fit_residual_m']<.16
for name,p in [('straight',box(0,0,12,.15)),('rectangle',box(0,0,5,2).exterior.buffer(.06)),('erratic',LineString([(0,0),(2,1.8),(3,0),(7,1.8),(8,0)]).buffer(.06)),('single_v',LineString([(0,0),(2,2),(4,0)]).buffer(.06))]:
checks[name+'_not_regular_zigzag']=fit_zigzag(p)is None
seed=dict(origin=np.array([0.,0.]),axis=np.array([1.,0.]),length=8.,width=.12)
def read(points):
on=abs(points[:,1])<.07;gray=np.where(on,225,65).astype('uint8');return np.repeat(gray[:,None],3,axis=1),np.ones(len(points),bool)
pv=profiles(seed,[read,read],extension=.5)
checks['long_line_crossing_both_window_edges_measured']=pv is not None and all(section_evidence(v,-3.95,3.95)['support']>.99 for v in pv)
def missing(points):
rgb,valid=read(points);valid[abs(points[:,0])<1]=False;return rgb,valid
pv=profiles(seed,[read,missing],extension=.5)
checks['unknown_long_line_gap_not_filled']=pv is not None and section_evidence(pv[1],-3.95,3.95)['valid']<POLICY['min_line_valid']
from catalog_evidence import mosaic_views
from discovery_evidence import glyph_views
class FakeViews:
def __init__(self,centers):
self.centers=np.c_[centers,np.zeros(len(centers))];self.tiles=[dict(id=str(i))for i in range(len(centers))];self.labels=np.ones((800,1400),np.uint8);self.low=np.array([-60.,-40.]);self.high=np.array([80.,40.])
def geometry(self,name):
view=np.eye(4);view[0,3]=-self.centers[int(name),0];return dict(view=view,intrinsics=np.array([[20,0,600],[0,20,600],[0,0,1.]]),alpha=np.ones((1200,1200),'float32'))
def inputs(self,name):
rgb=np.full((1200,1200,3),65,np.uint8);rgb[598:602]=225;return rgb,np.zeros((1200,1200),'float32')
stripe=box(-12,-.06,42,.06);fv=FakeViews([-5,15,35]);ev,names=mosaic_views(stripe,fv)
checks['whole_bbox_gate_really_loses_spanning_object']=not glyph_views(stripe,fv,None,None)[0]
checks['two_mosaics_cover_spanning_object']=len(names)==3 and all(e['paint_coverage']==1 and e['paint_valid']==1 and e['support']>.93 for e in ev)
ev,_=mosaic_views(stripe,FakeViews([15]));checks['one_camera_does_not_become_two']=ev[1]['paint_coverage']==0
fv.labels[:,690:730]=0;ev,_=mosaic_views(stripe,fv);checks['road_unknown_veto_remains_in_mosaic']=all(e['paint_valid']<.97 for e in ev)
from catalog_rules import accept_bicycle,accept_zigzag
strong=dict(paint_coverage=1.,paint_valid=1.,support=.99,recall=.98,negative_paint=.02,observed_support=.99)
absent=dict(paint_coverage=0.,paint_valid=0.,support=0.,recall=0.,negative_paint=1.,observed_support=0.)
checks['strong_single_native_view_can_identify_bicycle']=accept_bicycle([strong,absent],.85)=='strong-complete-view-plus-available-consistency'
checks['weak_template_cannot_use_missing_view_fallback']=accept_bicycle([strong,absent],.68)is None
checks['conflicting_available_view_vetoes_bicycle']=accept_bicycle([strong,{**strong,'support':.5,'observed_support':.5}],.85)is None
checks['incomplete_primary_cannot_use_fallback']=accept_bicycle([{**strong,'paint_coverage':.9},absent],.85)is None
fit=dict(legs=4,fit_residual_m=.04,proposal_recall=.95);partial={**strong,'paint_coverage':.5,'paint_valid':.5,'support':.5}
checks['strong_zigzag_uses_available_partial_consistency']=accept_zigzag([strong,partial],[[strong,partial]]*4,fit)=='strong-complete-view-plus-available-consistency'
checks['single_bad_zigzag_leg_vetoes_pattern']=accept_zigzag([strong,partial],[[strong,partial]]*3+[[{**strong,'support':.4},partial]],fit)is None
checks['weak_zigzag_fit_cannot_use_missing_view']=accept_zigzag([strong,absent],[[strong,absent]]*4,{**fit,'fit_residual_m':.2})is None
from catalog_context import bicycle_context
def strip(a,b,y=2.,axis=(1.,0.)):
return dict(center=np.array([(a+b)/2,y]),L=b-a,W=.12,axis=np.array(axis),polygon=box(a,y-.06,b,y+.06),source_tile='synthetic')
p=box(0,0,1,.5);parameters=[0,0,0,1,.5,0]
whole=bicycle_context(p,parameters,[strip(-3,7)])
split=bicycle_context(p,parameters,[strip(-3,0),strip(0,3),strip(3,7)])
checks['one_continuous_lane_strip_is_context']=whole['passed']
checks['lane_context_invariant_to_strip_fragmentation']=split['passed']and split['supporting_length_m']==whole['supporting_length_m']
checks['duplicate_short_strips_cannot_inflate_context']=not bicycle_context(p,parameters,[strip(0,2)]*5)['passed']
checks['perpendicular_strip_is_not_lane_context']=not bicycle_context(p,parameters,[strip(-3,7,axis=(0.,1.))])['passed']
checks['isolated_symbol_has_no_lane_context']=not bicycle_context(p,parameters,[])['passed']
checks['lane_context_is_json_serializable']=json.loads(json.dumps(whole))==whole
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/catalog-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(dict(passed=result['passed'],tests=len(checks),failed=[k for k,v in checks.items()if not v])));assert result['passed']
@@ -0,0 +1,85 @@
Mission Core: bounded completion of observed paint rows
======================================================
Offline qualification only. The input is discovery-pass-20261012. No live map
replacement, deployment, point-cloud input, per-scene threshold or manual ROI.
The same frozen Python source and policy run on Maroseyka, Pokrovka and Smolensk.
All three scenes have been inspected during development; none is an untouched
holdout. Controlled tests and operation counts do not measure real-world recall
or metric accuracy.
Pipeline
--------
1. Cluster compatible existing dashed vectors by metric direction, spacing,
phase and transverse residual. Huber fitting supplies a common row axis.
2. Reobserve at least three anchors in two geometrically selected Gaussian
mosaics. The source images represent one reconstruction, not independent
physical observations. Search bounded missing slots and row ends. Each new
stroke requires visible paint, observed edges, valid dark neighboring gaps,
compatible transverse width and agreement between the two mosaics. Period
alone never authorizes a stroke. Existing symbols and neighboring lines are
protected. No output fills an unobserved/occluded paint slot.
3. Reuse the qualified beta periodic fitter for existing axes. Avoid repeated
renormalization of already dashed rows without added strokes or an old
non-dashed overlap. Preserve geometry outside the proven longitudinal edit.
4. Reuse qualified full-corridor endpoint checks. A sideways bend is not proof
that paint ends. Blank masks and vehicle occlusion are not dark asphalt.
5. Reuse the qualified partial-duplicate classifier with continuous evidence
mosaics, retaining the observed keeper and exact XY outside the common span.
Two physical paint ridges veto removal. Reuse whole-row assembly at the end.
OpenCV, SciPy, Shapely and existing research modules implement these stages.
No training, new model download or alternate per-location pipeline is required.
The output remains observation-only, route_permission unassigned, unreviewed.
Z comes from the existing Gaussian-derived field. Existing GOST dimensional
assessments remain soft checks; no legal compliance conclusion is made.
Execution and evidence
----------------------
Use bundle.json to resolve canonical source. The private qualification retains
runner/collector/verifier, scene registry, execution receipts, input hashes,
replayable transactions, controlled checks, JPGs and visual review. A frozen
source ZIP accompanies delivery. Review font is external, hash-pinned and omitted
from that ZIP. Private scene caches are required to reproduce the run.
Worker006 only: pinned image
sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0;
4 CPU, 20 GiB, network none, read-only root, 1800 seconds per stage.
Mac orchestration uses the canonical Observatory recorded-job reservation.
All output replacements are isolated in qualification; accepted input is read-only.
Regression source contains attributed arrow artwork: MajorAlexey,
https://commons.wikimedia.org/wiki/File:1.18_Russian_road_marking.svg,
CC BY-SA 4.0, https://creativecommons.org/licenses/by-sa/4.0/.
Adaptation: normalized parametric polygons; original source SHA-256
b76f40ee8d1603ddfeb3cd430f397dcc509684f0a0aa38c61bbd8a2cba554ea8.
This pass does not modify glyphs, roads, pedestrian zones, facades or crosswalks.
Additional acceptance details
-----------------------------
Short strokes above a worn continuous underlay may use a bounded prominent peak.
The gap still needs a contrast drop of at least 22 and its 80th percentile must
stay below 60 percent of the stroke contrast in each view. Absolute dark-gap
acceptance remains available. A uniform stripe cannot pass this peak rule.
The generated common axis itself must stay within max(0.04 m, 0.3*width) of each
observed ridge. Local endpoint context is limited to the nearest four metres.
A sixth stage checks a generic thin-line object parallel to an existing zebra
bar. Only a geometrically contained common span is eligible. Both full-object
renders must support the retained bar (valid >=0.98, support >=0.85).
Crossing longitudinal lane lines are ineligible. A 0.025 m boundary tolerance
accounts for pixel-scale geometry; it is not a standards tolerance. The zebra
feature is retained unchanged; only the duplicate linear span is removed.
Novelty counts use the complete current paint map, including a 0.1 m clearance.
A shifted outline is not a newly discovered stroke. Existing periodic geometry
is rebuilt only for genuinely absent strokes or >=0.03 m2 of old vector paint
inside verified gaps. Candidates leaving tiny residual fragments are rejected.
These gates were added after visual review rejected ineffective re-fitting.
Bar deduplication uses positive coverage of the retained bar. Paint outside that
bar is not edited and does not veto an internal duplicate through a recall test.
@@ -0,0 +1,68 @@
from pathlib import Path
import json,hashlib,numpy as np,shapely
from shapely.geometry import shape
from completion_profiles import POLICY,VERSION,supported,gap_supported,bar_supported,bar_overlap
old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/completion-rows.json').read_text());current={f['id']:f for f in old['features']};checks={}
def poly(f):return shapely.force_2d(shape(f['geometry']))
protected=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'])
checks['transaction_replay']=True;checks['only_linear_objects_replaced']=True;checks['no_new_neighbor_overlap']=True;checks['protected_paint_preserved']=True;checks['evidence_passes']=True;checks['outside_edit_interval_preserved']=True
def duplicate_evidence(r):
if r['kind']=='confirmed_dash_gap':return all(v['valid']>=.95 and v['dark_fraction']>=.9 and v['q90']<8 and all(a['valid']>=.95 and a['support']>=.85 and a['median']>=22 for a in v['anchors'])for v in r['views'])
if not all(v['source_valid']>=.95 and v['target_valid']>=.95 and v['target_support']>=.85 and v['target_median']>=22 for v in r['views']):return False
if not all(x['valid_fraction']>=.95 and x['two_ridge_fraction']<=.1 and x['longest_two_ridge_m']<.25 for x in r['ridges']):return False
if r['kind']=='overlapping_duplicate':return r['geometry']['contained_fraction']>=.90
if r['kind']=='unsupported_offset_duplicate':return all(v['source_support']<=.15 and v['source_q75']<8 for v in r['views'])
if r['kind']!='one_ridge_two_vectors':return False
xs=r['ridges']
if not all(len(x['peaks'])==1 for x in xs):return False
ds=[x['peaks'][0]['offset']for x in xs]
return max(ds)-min(ds)<=.05 and all(abs(d)>=.10 and abs(d-x['target_offset'])<=.08 and abs(d)-abs(d-x['target_offset'])>=.06 for d,x in zip(ds,xs))
for r in rows:
before=r['before'];after=r['after'];ids=r['source_ids']
checks['transaction_replay']&=all(current.get(f['id'])==f for f in before)and ids==[f['id']for f in before]and r['output_ids']==[f['id']for f in after]
checks['only_linear_objects_replaced']&=all(f['properties'].get('subtype')=='linear_marking'for f in before+after)
a=shapely.union_all([poly(f)for f in before]);b=shapely.union_all([poly(f)for f in after]);novel=b.difference(a)
checks['protected_paint_preserved']&=novel.intersection(protected).area<=POLICY['max_new_neighbor_overlap_m2']
checks['no_new_neighbor_overlap']&=all(novel.intersection(poly(f)).area<=POLICY['max_new_neighbor_overlap_m2']for i,f in current.items()if i not in ids and f['properties'].get('subtype')=='linear_marking')
ev=r['evidence'];ok=len(r['source_views'])==2 and len(r['source_tiles'])>=2
if r['kind']=='row-completion':
ok&=not before and len(ev['anchors'])>=POLICY['min_anchor_reobserved']and len(ev['slots'])==len(after)
ok&=all(len(q['views'])==2 and all(supported(v['paint'])and len(v['gaps'])==2 and all(e.get('full_corridor')and gap_supported(e,v['paint'])for e in v['gaps'])for v in q['views'])for q in ev['anchors']+ev['slots'])
ok&=all(max(abs(q['views'][0]['edges'][j]-q['views'][1]['edges'][j])for j in [0,1])<=POLICY['max_slot_edge_error_m']for q in ev['anchors']+ev['slots'])
elif r['kind']=='periodic-row':
ok&=len(ev['paint'])==2*len(ev['observations'])and all(supported(e)for e in ev['paint'])
ok&=len(ev['gaps'])==2*(len(ev['observations'])-1)
ok&=all(supported(e,False)if ev['mode']=='intervals'else e['valid']>=.95 and e['contrast_drop']>=18 and e['contrast']<(e['contrast']+e['contrast_drop'])*.65 for e in ev['gaps'])
ok&=all(len(e['edges'])==2 and max(abs(e['edges'][0][k]-e['edges'][1][k])for k in [0,1])<=POLICY['max_edge_disagreement_m']for e in ev['observations'])
ok&=all(e['padding']<=POLICY['max_family_edge_padding_m']and len(e['views'])==2 and all(v.get('full_corridor')and supported(v,False)for v in e['views'])for e in ev['edges'])
# The transverse replacement section is wider than the modeled stripe;
# the outside longitudinal old contours must nevertheless be exact.
from interval_profiles import rectangle
d=shape(r['edit_domain']);o=np.array(r['origin']);u=np.array(r['axis']);tt=(np.asarray(d.exterior.coords)-o)@u;domain=rectangle(o,u,float(tt.min()),float(tt.max()),2.)
checks['outside_edit_interval_preserved']&=a.difference(domain.buffer(1e-7)).symmetric_difference(b.difference(domain.buffer(1e-7))).area<1e-7
elif r['kind']=='solid-endpoints':
ok&=all(len(e['evidence'])==2 and POLICY['min_endpoint_change_m']<=abs(e['delta'])<=POLICY['max_endpoint_change_m']and all(supported(v['paint'])and supported(v['dark'],False)and supported(v['edit'],e['kind']=='extend-solid')for v in e['evidence'])for e in ev)
ok&=all(v['dark'].get('full_corridor')and(e['kind']=='extend-solid'or v['edit'].get('full_corridor'))for e in ev for v in e['evidence'])
domain=shape(r['edit_domain']);checks['outside_edit_interval_preserved']&=a.difference(domain.buffer(1e-7)).symmetric_difference(b.difference(domain.buffer(1e-7))).area<1e-7
elif r['kind']=='duplicate-section':
ok&=len(ev['views'])==2 and duplicate_evidence(ev) and r['keeper_id']in current and r['keeper_id']not in ids
domain=shape(r['edit_domain']);checks['outside_edit_interval_preserved']&=a.difference(domain).symmetric_difference(b).area<1e-7
elif r['kind']=='crosswalk-line-duplicate':
keeper=current.get(r['keeper_id']);ok&=bool(keeper)and keeper['properties'].get('subtype')=='crosswalk'and bar_supported(ev)
domain=shape(r['edit_domain']);ok&=len(before)==1 and bar_overlap(poly(before[0]),poly(keeper)).symmetric_difference(domain).area<1e-8
checks['outside_edit_interval_preserved']&=a.difference(domain).symmetric_difference(b).area<1e-7
elif r['kind']=='assembled-row':
ok&=len(ev)==2 and r['max_axis_displacement_m']<=.065 and all(v['local_evidence_passed']for v in ev)and any(v['passed']for v in ev)
else:ok=False
checks['evidence_passes']&=ok
for i in ids:current.pop(i,None)
for f in after:current[f['id']]=f
features={f['id']:f for f in new['features']};checks['final_map_matches_replay']=features==current;checks['unique_ids']=len(features)==len(new['features'])
checks['unchanged_other_layers']=all(features.get(f['id'])==f for f in old['features']if f['properties'].get('subtype')!='linear_marking')
checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features'])
checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes()
report=json.loads(Path('/out/completion-report.json').read_text());checks['same_policy']=new['completion_refinement']==VERSION and report['policy']==POLICY
checks['every_operation_counted']=report['changed_segments']==len(rows)and sum(report['stages'].values())==len(rows)
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False)
Path('/out/completion-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,126 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"root": "simulation/urban-plan-research",
"files": {
"audit_beta.py": "beta_pass/audit_beta.py",
"audit_completion.py": "completion_pass/audit_completion.py",
"audit_consensus.py": "consensus_pass/audit_consensus.py",
"audit_discovery.py": "discovery_pass/audit_discovery.py",
"audit_norms.py": "norms_pass/audit_norms.py",
"audit_rows.py": "rows_pass/audit_rows.py",
"audit_sections.py": "sections_pass/audit_sections.py",
"audit_transitions.py": "transitions_pass/audit_transitions.py",
"beta_profiles.py": "beta_pass/beta_profiles.py",
"completion_profiles.py": "completion_pass/completion_profiles.py",
"consensus_profiles.py": "consensus_pass/consensus_profiles.py",
"discovery_evidence.py": "discovery_pass/discovery_evidence.py",
"discovery_rules.py": "discovery_pass/discovery_rules.py",
"extract_discovery.py": "discovery_pass/extract_discovery.py",
"fit_scene.py": "full_plan/fit_scene.py",
"fragment_templates.py": "discovery_pass/fragment_templates.py",
"gost_catalog.py": "norms_pass/gost_catalog.py",
"image_profiles.py": "lines_pass/image_profiles.py",
"interval_profiles.py": "intervals_pass/interval_profiles.py",
"layer_common.py": "full_plan/layer_common.py",
"line_reconstruction.py": "intervals_pass/line_reconstruction.py",
"norm_profiles.py": "norms_pass/norm_profiles.py",
"paint_templates.py": "continuation_pass/paint_templates.py",
"refine_beta.py": "beta_pass/refine_beta.py",
"refine_completion.py": "completion_pass/refine_completion.py",
"refine_consensus.py": "consensus_pass/refine_consensus.py",
"refine_discovery.py": "discovery_pass/refine_discovery.py",
"refine_norms.py": "norms_pass/refine_norms.py",
"refine_rows.py": "rows_pass/refine_rows.py",
"refine_sections.py": "sections_pass/refine_sections.py",
"refine_transitions.py": "transitions_pass/refine_transitions.py",
"render_beta.py": "beta_pass/render_beta.py",
"render_completion.py": "completion_pass/render_completion.py",
"render_consensus.py": "consensus_pass/render_consensus.py",
"render_discovery.py": "discovery_pass/render_discovery.py",
"render_norms.py": "norms_pass/render_norms.py",
"render_plan.py": "continuation_pass/render_plan.py",
"render_rows.py": "rows_pass/render_rows.py",
"render_sections.py": "sections_pass/render_sections.py",
"render_transitions.py": "transitions_pass/render_transitions.py",
"road_glyph_presets.py": "continuation_pass/road_glyph_presets.py",
"row_evidence.py": "rows_pass/row_evidence.py",
"row_profiles.py": "rows_pass/row_profiles.py",
"section_profiles.py": "sections_pass/section_profiles.py",
"test_beta.py": "beta_pass/test_beta.py",
"test_completion.py": "completion_pass/test_completion.py",
"test_consensus.py": "consensus_pass/test_consensus.py",
"test_discovery.py": "discovery_pass/test_discovery.py",
"test_intervals.py": "intervals_pass/test_intervals.py",
"test_lines.py": "lines_pass/test_lines.py",
"test_norms.py": "norms_pass/test_norms.py",
"test_rows.py": "rows_pass/test_rows.py",
"test_sections.py": "sections_pass/test_sections.py",
"test_transitions.py": "transitions_pass/test_transitions.py",
"transition_profiles.py": "transitions_pass/transition_profiles.py"
},
"reference_qualification": "completion-pass-20261012",
"source_snapshot": "9eed93a977bcb32571d4",
"source_sha256": {
"audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f",
"audit_completion.py": "ef6adcfec3e1a4bd894b54a150fe3b8559bf73e94665bb9da6bd68007e90575d",
"audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2",
"audit_discovery.py": "9e5f1bdd0d752d82a52121fe86d4e6fb00068a6af9330a072fe7311a909bc974",
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
"audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01",
"audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7",
"audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a",
"beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e",
"completion_profiles.py": "b01cb280a265f170c2f3823d59d423c0cf11472050678cc4dad716c1f90ff786",
"consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091",
"discovery_evidence.py": "dc7e0594b77f6d3723a965216164427835aa5ae2ff736b5599774c4efbc626eb",
"discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491",
"extract_discovery.py": "5d2835cde2b9d4d895609ea39be2a94a22e894d0996d525dcc3df7046c33e681",
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
"fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7",
"gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537",
"image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8",
"interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345",
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
"line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738",
"norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7",
"paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6",
"refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831",
"refine_completion.py": "12f424d39a687e8b94823f2e2f7b2f2c95538f3504260b4373c47cc21b29c6e1",
"refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36",
"refine_discovery.py": "6272ca1f5052259fb3c6cfd1f1079e4e5864e1e067d12de7ff36d95857219d7b",
"refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5",
"refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8",
"refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3",
"refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b",
"render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c",
"render_completion.py": "5e76d2a6ce41a6be8013f98df33951fe17fc209c078376ebfafe7c60ed0b14a7",
"render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682",
"render_discovery.py": "868ad8eb712f5880e944b0899205a2c0fd6dd0713eb727b1c49dda92b897fa20",
"render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d",
"render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064",
"render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e",
"render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c",
"render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d",
"road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322",
"row_evidence.py": "fc6a390faa97fb4cf6213dd6b841a94de9c6e78e0b68e6715aa06f2de565f28c",
"row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df",
"section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de",
"test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b",
"test_completion.py": "a3a6a283221ae48ade8fd0cca2f145509fd6bedf8e808967c13438791654a7f1",
"test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7",
"test_discovery.py": "a75ffc22d065201f7023d8e6cfb6dc09204a80f9be607599b85479628a301538",
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a",
"test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f",
"test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449",
"test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f",
"test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438",
"transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e"
},
"external_review_font": {
"name": "review-font.ttf",
"sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9",
"purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP"
},
"deployment": false
}
@@ -0,0 +1,142 @@
"""Existing periodic rows nominate bounded slots; two Gaussian mosaics decide.
No phase-only fill: known anchors are re-observed, each new slot needs measured
paint edges and dark neighboring gaps. Missing/occluded slots remain unpainted.
Uses OpenCV Huber lines and the existing metric paint-profile components.
"""
import numpy as np,cv2
from scipy.signal import find_peaks,peak_widths
from scipy.ndimage import gaussian_filter1d
from interval_profiles import rectangle,strip,runs
from section_profiles import POLICY as SECTION_POLICY
from beta_profiles import describe,profiles,discover,endpoints,POLICY as BASE,supported
VERSION='paint-row-completion-v1'
POLICY={**BASE,'min_family_anchors':3,'max_family_axis_deg':3.,'max_family_lateral_m':.15,
'max_family_phase_m':.20,'max_slot_offset_m':.10,'max_slot_edge_error_m':.20,
'max_extension_slots':6,'max_extension_distance_m':12.,'min_anchor_reobserved':3,
'max_consecutive_unobserved_slots':2,'slot_length_relative_error':.25,
'slot_length_absolute_error_m':.18,'min_slot_dark':.85,'min_slot_valid':.95,'min_gap_contrast_drop':22.,'max_gap_paint_ratio':.60,'duplicate_policy':SECTION_POLICY}
def families(records):
"""Deterministic clustering of compatible periodic vectors, not scene IDs."""
recs=[]
for fid,p,prop in records:
if prop.get('line_kind')!='dashed':continue
P=prop.get('period_m');L=prop.get('dash_length_m');d=describe(p)
if not d or not P or not L or not .26<L<=10.5 or not 1.1*L<P<8*L:continue
if abs(d['length']-L)>max(.25,.3*L):continue
recs.append(dict(id=fid,period=float(P),dash=float(L),**d))
groups=[];seen=set()
for a in sorted(recs,key=lambda r:r['id']):
o,u=a['origin'],a['axis'];n=np.array([-u[1],u[0]]);P=a['period'];L=a['dash']
candidates=[b for b in recs if abs(b['axis']@u)>=np.cos(np.deg2rad(POLICY['max_family_axis_deg']))and abs((b['origin']-o)@n)<=POLICY['max_family_lateral_m']and abs(b['period']-P)<.15*P and abs(b['dash']-L)<.25*L and abs((b['origin']-o)@u)<70]
candidates.sort(key=lambda b:float((b['origin']-o)@u))
chunks=[]
for b in candidates:
if not chunks or float((b['origin']-chunks[-1][-1]['origin'])@u)>3.2*P:chunks.append([])
chunks[-1].append(b)
for c in chunks:
ids=tuple(sorted(r['id']for r in c))
if len(c)<POLICY['min_family_anchors']or ids in seen:continue
seen.add(ids);xy=np.array([r['origin']for r in c]);line=cv2.fitLine(xy.astype('float32'),cv2.DIST_HUBER,0,.001,.001).ravel();v=line[:2].astype(float);v/=np.linalg.norm(v)
if v@u<0:v=-v
o=xy.mean(0);n=np.array([-v[1],v[0]]);t=(xy-o)@v
if np.max(abs((xy-o)@n))>.10 or abs(v@u)<np.cos(np.deg2rad(3))or np.ptp(t)>70:continue
period=float(np.median([r['period']for r in c]));ix=np.rint((t-t.min())/period).astype(int)
if len(set(ix))!=len(ix):continue
fitted,phase=np.polyfit(ix,t,1)
if abs(fitted-period)>.10*period or max(abs(t-(phase+fitted*ix)))>POLICY['max_family_phase_m']:continue
groups.append(dict(origin=o+phase*v,axis=v,period=float(fitted),length=float(np.median([r['dash']for r in c])),width=float(np.median([r['width']for r in c])),indices=ix.tolist(),source_ids=list(ids),max_index=int(ix.max())))
accepted=[]
for g in sorted(groups,key=lambda g:-len(g['source_ids'])):
if any(len(set(g['source_ids'])&set(q['source_ids']))>=2 for q in accepted):continue
accepted.append(g)
return accepted
def gap_supported(g,paint):
return supported(g,False)or(g['valid']>=POLICY['min_slot_valid']and paint['contrast']-g['contrast']>=POLICY['min_gap_contrast_drop']and g['q80']<paint['contrast']*POLICY['max_gap_paint_ratio'])
def slot(seed,index,readers,debug=None):
if len(readers)!=2:return None
o,u=seed['origin'],seed['axis'];P,L,W=seed['period'],seed['length'],seed['width'];c=index*P;step=POLICY['step_m'];ext=min(P/2,L/2+max(.4,.25*L));ts=np.arange(c-ext,c+ext+step/2,step);ns=np.arange(-.70,.701,step);ev=[]
for read in readers:
contrast,allowed=strip(o,u,ts,ns,read);core=abs(ts-c)<.3*L
transverse=np.median(np.where(allowed[core],contrast[core],0),axis=0)
peaks,_=find_peaks(transverse,height=22,prominence=10,distance=4);peaks=[k for k in peaks if abs(ns[k])<=POLICY['max_slot_offset_m']]
if not peaks:
if debug is not None:debug.update(reason='no-ridge',peak=float(transverse.max()))
return None
k=min(peaks,key=lambda k:abs(ns[k]));width=float(peak_widths(transverse,[k],rel_height=.5)[0][0]*step)
if not .045<=width<=.35:return None
band=abs(ns-ns[k])<=.04;sig=gaussian_filter1d(np.median(contrast[:,band],axis=1),1);valid=allowed[:,band].all(1);level=float(np.median(sig[core]));cut=max(15.,.35*level);paint=(sig>cut)&valid
for a,b in runs(~paint):
if a>0 and b<len(ts)and(b-a)*step<=.125 and valid[a:b].all():paint[a:b]=True
options=[(a,b)for a,b in runs(paint)if a>0 and b<len(ts)and abs((ts[a]+ts[b-1])/2-c)<=POLICY['max_family_phase_m']and abs((b-a)*step-L)<=max(POLICY['slot_length_absolute_error_m'],POLICY['slot_length_relative_error']*L)]
# A short dash may sit above worn paint. Reuse measured peak widths;
# a continuous line without a prominent bounded peak still fails.
if not options and L<1.45:
pk,_=find_peaks(np.where(valid,sig,0),prominence=22,distance=max(1,int(.45/step)))
ws=peak_widths(np.where(valid,sig,0),pk,rel_height=.5)
options=[(int(round(ws[2][j])),int(round(ws[3][j]))+1)for j,kp in enumerate(pk)if abs(ts[kp]-c)<=POLICY['max_family_phase_m']and abs(ws[0][j]*step-L)<=max(POLICY['slot_length_absolute_error_m'],POLICY['slot_length_relative_error']*L)]
options=[(a,b)for a,b in options if a>0 and b<len(ts)]
if not options:
if debug is not None:debug.update(reason='no-bounded-stroke',level=level,intervals=[(float(ts[a]-c),float(ts[b-1]-c))for a,b in runs(paint)])
return None
a,b=min(options,key=lambda ab:abs((ts[ab[0]]+ts[ab[1]-1])/2-c));lo,hi=float(ts[a]-step/2),float(ts[b-1]+step/2);center=(lo+hi)/2
inside=(ts>=center-.35*L)&(ts<=center+.35*L);positive=dict(valid=float(valid[inside].mean()),support=float((sig[inside]>cut).mean()),contrast=float(np.median(sig[inside])))
gaps=[]
for left,right in [(c-ext,lo-.05),(hi+.05,c+ext)]:
sel=(ts>=left)&(ts<=right)
if sel.sum()<3:return None
# Full width surrounding the ridge, including the predicted vector.
corridor=abs(ns)<=max(.12,W/2+.06);vv=allowed[sel][:,corridor].all(1);ss=contrast[sel][:,corridor].max(1)
gaps.append(dict(valid=float(vv.mean()),support=float((ss<cut).mean()),contrast=float(np.median(ss)),q80=float(np.quantile(ss,.8)),full_corridor=True))
if not supported(positive)or not all(gap_supported(g,positive)for g in gaps):
if debug is not None:debug.update(reason='paint-or-gap-evidence',paint=positive,gaps=gaps)
return None
ev.append(dict(edges=[lo,hi],offset=float(ns[k]),width=width,paint=positive,gaps=gaps))
if abs(ev[0]['offset']-ev[1]['offset'])>.05 or max(abs(ev[0]['edges'][j]-ev[1]['edges'][j])for j in [0,1])>POLICY['max_slot_edge_error_m']:return None
# The predicted vector itself must intersect the ridge, not merely find
# some bright neighboring pixels in its search corridor.
if any(abs(e['offset'])>max(.04,.3*W)for e in ev):
if debug is not None:debug.update(reason='ridge-outside-output-axis',offsets=[e['offset']for e in ev])
return None
# Keep the family's common axis/length/phase, subject to measured edge fit.
if any(max(abs(e['edges'][0]-(c-L/2)),abs(e['edges'][1]-(c+L/2)))>max(.20,.15*L)for e in ev):return None
p=rectangle(o,u,c-L/2,c+L/2,W)
return dict(polygon=p,evidence=ev,index=int(index))
def local_endpoints(seed,readers):
"""Use bounded endpoint context so a far ridge cannot select the local axis."""
if seed['length']<2.7:return []
changes=[];window=min(4.,seed['length'])
for sign in [-1,1]:
local={**seed,'origin':seed['origin']+sign*(seed['length']-window)/2*seed['axis'],'length':window}
pv=profiles(local,readers,extension=2.5)
changes.extend(c for c in endpoints(local,pv)if c['sign']==sign)
return changes
def bar_overlap(source,bar):
"""Same-paint semantic overlap: a thin stripe follows an accepted zebra bar.
A real longitudinal lane line crossing the bar is deliberately ineligible.
Only a parallel common span with strong geometric containment is nominated.
"""
from line_reconstruction import observation
if source.geom_type!='Polygon'or bar.geom_type!='Polygon':return None
a=observation(np.asarray(source.exterior.coords),'vector');b=observation(np.asarray(bar.exterior.coords),'bar')
if not .3<=b['W']<=1.2 or not 1.5<=b['L']<=20 or a['W']>.35 or a['L']<.6:return None
if abs(a['axis']@b['axis'])<np.cos(np.deg2rad(4)):return None
# Tolerance is geometric pixel-scale uncertainty, not a traffic standard.
cut=bar.buffer(.025,join_style=2);part=source.intersection(cut)
if part.is_empty or part.area<.06:return None
tt=(np.asarray(bar.exterior.coords)-a['center'])@a['axis'];lo=max(-a['L']/2,float(tt.min()));hi=min(a['L']/2,float(tt.max()))
if hi-lo<.6:return None
common=source.intersection(rectangle(a['center'],a['axis'],lo,hi,4))
if common.is_empty or common.intersection(bar).area/common.area<.9:return None
return cut
def bar_supported(evidence):
# Paint outside the retained bar is not removed by this operation. Its
# unexplained-paint recall must not veto removal of an internal duplicate.
return len(evidence)==2 and all(e['valid']>=.98 and e['support']>=.85 for e in evidence)
@@ -0,0 +1,205 @@
from pathlib import Path
import os,json,time,hashlib,collections
import numpy as np,cv2,shapely
from shapely.geometry import shape,mapping
from shapely.ops import transform
from layer_common import O,S,sample,feature,parts
from completion_profiles import POLICY,VERSION,describe,profiles,discover,endpoints
from discovery_evidence import DiscoveryViews as GaussianViews
from row_profiles import pair,fit_chain,check_chain
from transition_profiles import residual_sections
from gost_catalog import assess_dash
cv2.setNumThreads(3);started=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());original={f['id']:f for f in old['features']};current=dict(original)
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds']
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
protected=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'])
views=GaussianViews(tiles,labels,low,high,protected);transactions=[];diagnostics=[];domains=[]
def poly(f):return shapely.force_2d(shape(f['geometry']))
def linear(f):return f['properties'].get('subtype')=='linear_marking'
def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
def make(p,kind,ids,**kw):return feature(lift(p),'road_marking',subtype='linear_marking',line_kind=kind,method=VERSION,source_ids=ids,standard_compliance='not_assessed',**kw)
def commit(kind,ids,new,domain,ev,used,extra=None):
before=[current[i]for i in ids];new=[f for f in new if not poly(f).is_empty];newids=[f['id']for f in new]
if len(set(newids))!=len(newids)or any(i in current and i not in ids for i in newids):return False
a=shapely.union_all([poly(f)for f in before]);b=shapely.union_all([poly(f)for f in new]);novel=b.difference(a)
if a.symmetric_difference(b).area<POLICY['min_material_change_m2']:return False
if novel.intersection(protected).area>POLICY['max_new_neighbor_overlap_m2']:return False
if any(novel.intersection(poly(f)).area>POLICY['max_new_neighbor_overlap_m2']for i,f in current.items()if i not in ids and linear(f)):return False
for i in ids:current.pop(i)
for f in new:current[f['id']]=f
rec=dict(kind=kind,source_ids=ids,output_ids=newids,before=before,after=new,bounds_xy=(shapely.union_all([a,b])if kind=='assembled-row'else domain).bounds,edit_domain=mapping(domain),evidence=ev,source_views=used,source_tiles=sorted(set(used[0])|set(used[1])),added_area_m2=float(novel.area),removed_area_m2=float(a.difference(b).area))
if extra:rec.update(extra)
transactions.append(rec);print('EDIT',len(transactions),kind,len(ids),'->',len(new),flush=True);return True
# Revalidate vector-derived periodic families before using them to nominate slots.
from completion_profiles import families,slot,local_endpoints
family_rows=families([(fid,poly(f),f['properties'])for fid,f in original.items()if linear(f)])
for fi,g in enumerate(family_rows):
readers,used=views.readers(g['origin'],g['axis']);anchor_evidence=[]
for index in g['indices']:
ad={};r=slot(g,index,readers,ad)
diagnostics.append(dict(stage='anchor',family=fi,index=index,passed=r is not None,**ad))
if r is not None:anchor_evidence.append(dict(index=index,views=r['evidence']))
diagnostics.append(dict(stage='family',family=fi,anchors=len(g['indices']),observed=len(anchor_evidence)))
if len(anchor_evidence)<POLICY['min_anchor_reobserved']:continue
extension=min(POLICY['max_extension_slots'],int(POLICY['max_extension_distance_m']/g['period']))
targets=[list(range(0,g['max_index']+1)),list(range(-1,-extension-1,-1)),list(range(g['max_index']+1,g['max_index']+extension+1))]
additions=[];evidence=[]
for sequence in targets:
missed=0
for index in sequence:
debug={};r=slot(g,index,readers,debug)
diagnostics.append(dict(stage='slot',family=fi,index=index,passed=r is not None,**debug))
if r is None:
missed+=1
if sequence is not targets[0]and missed>=POLICY['max_consecutive_unobserved_slots']:break
continue
missed=0;p=r['polygon']
from discovery_rules import uncovered
existing=shapely.union_all([poly(f)for f in current.values()if f['properties']['class']=='road_marking'])
if not uncovered(p,existing):continue
additions.append(make(p,'dashed',g['source_ids'],period_m=g['period'],dash_length_m=g['length'],width_m=g['width'],standard_assessment=assess_dash(g['length'],g['period'],g['width']),observed_stroke=True))
evidence.append(dict(index=index,views=r['evidence']))
if additions:
domain=shapely.union_all([poly(f)for f in additions]);commit('row-completion',[],additions,domain,dict(anchors=anchor_evidence,slots=evidence),used,dict(family_source_ids=g['source_ids'],period_m=g['period'],dash_length_m=g['length'],newly_captured_strokes=len(additions)))
print('FAMILY',fi+1,'/',len(family_rows),'ADDITIONS',len(additions),flush=True)
# Stage 1: every eligible existing axis seeds a 24m wider image search. Spatial
# neighborhoods already covered by an accepted periodic model are not reworked.
seeds=[]
for fid,f in original.items():
if not linear(f):continue
rec=describe(poly(f))
if rec is not None:seeds.append((fid,rec))
proposals=[]
for index,(fid,seed)in enumerate(sorted(seeds,key=lambda x:(int(np.argmin(np.linalg.norm(views.centers-x[1]['origin'],axis=1))),-x[1]['length']))):
readers,used=views.readers(seed['origin'],seed['axis']);pv=profiles(seed,readers)
found=discover(seed,pv);diagnostics.append(dict(seed_id=fid,stage='discover',profile_valid=pv is not None,proposals=len(found)))
for r in found:r.update(seed_id=fid,source_views=used);proposals.append(r)
if index%25==0:print('PROFILE',index+1,'/',len(seeds),'PROPOSALS',len(proposals),flush=True)
# Stage 2: one normalized row replaces only its observed longitudinal section.
for r in sorted(proposals,key=lambda x:(-len(x['polygons']),-x['hi']+x['lo'])):
domain=r['domain'];u=r['axis'];o=r['origin'];n=np.array([-u[1],u[0]]);origin=o+r['offset']*n
if any(domain.intersection(d).area>.01 for d in domains):continue
ids=[];residual=[]
for fid,f in current.items():
if not linear(f):continue
p=poly(f);d=describe(p)
if d is None or p.intersection(domain).area<.005 or abs(d['axis']@u)<np.cos(np.deg2rad(3))or abs((d['origin']-origin)@n)>.13:continue
# Old complete stroke centers must agree with the new ridge; crossings
# and a genuine neighboring stripe are not part of this row.
ids.append(fid)
for pp in parts(residual_sections(p,domain,o,u)):
if pp.area>.000001:residual.append(make(pp,f['properties'].get('line_kind','solid'),[fid],role='unchanged-section'))
if not ids:continue
generated=[make(p,'dashed',ids,period_m=r['period'],dash_length_m=r['length'],width_m=r['width'],standard_assessment=assess_dash(r['length'],r['period'],r['width']),observed_stroke=True)for p in r['polygons']]
before=shapely.union_all([poly(current[i])for i in ids])
from discovery_rules import uncovered
all_paint=shapely.union_all([poly(f)for f in current.values()if f['properties']['class']=='road_marking'])
new_strokes=sum(uncovered(p,all_paint)for p in r['polygons'])
from interval_profiles import rectangle
centers=[e['center']for e in r['observations']]
gaps=shapely.union_all([rectangle(o,u,a+r['length']/2+.06,b-r['length']/2-.06,r['width'],r['offset'])for a,b in zip(centers,centers[1:])if b-a-r['length']>.12])
false_gap_area=before.intersection(gaps).area
# Existing individual strokes are not 'new' merely because the latest fit
# shifted their outlines. Rebuild only actual missing paint or a proven
# vector connection across observed inter-stroke asphalt.
if not new_strokes and false_gap_area<.03:continue
if any(describe(poly(f))is None or describe(poly(f))['length']<.25 for f in residual):continue
ev=dict(paint=r['paint_evidence'],gaps=r['gap_evidence'],edges=r['edge_evidence'],observations=r['observations'],mode=r['mode'])
if commit('periodic-row',ids,residual+generated,domain,ev,r['source_views'],dict(period_m=r['period'],dash_length_m=r['length'],newly_captured_strokes=new_strokes,normalized_strokes=len(generated),axis=u.tolist(),origin=o.tolist())):domains.append(domain)
# Stage 3: false solid ends and missed tails. Each edit needs visible paint and
# the following dark interval in both mosaics, including at existing transitions.
for fid in list(current):
f=current.get(fid)
if f is None or not linear(f)or f['properties'].get('line_kind')=='dashed':continue
p=poly(f);seed=describe(p)
if seed is None or seed['length']<2.7:continue
readers,used=views.readers(seed['origin'],seed['axis']);changes=local_endpoints(seed,readers)
if not changes:continue
output=p;edit=[];ev=[]
for c in changes:
output=output.union(c['polygon'])if c['kind']=='extend-solid'else output.difference(c['domain'])
edit.append(c['domain']);ev.append({k:c[k]for k in ['kind','delta','evidence']})
if output.geom_type!='Polygon' or not output.is_valid:continue
commit('solid-endpoints',[fid],[make(output,'solid',[fid])],shapely.union_all(edit),ev,used)
# Reuse the qualified bounded duplicate detector with continuous mosaics.
# Only the common interval is removed; real twin paint ridges veto the cut.
from section_profiles import common_section,check_section
keepers=set();duplicate_candidates=0
linear_ids=[fid for fid,f in current.items()if linear(f)]
for sid in sorted(linear_ids):
if sid not in current or sid in keepers:continue
for tid in sorted(linear_ids):
if sid==tid or sid not in current or tid not in current:continue
p,q=poly(current[sid]),poly(current[tid])
if p.distance(q)>.66:continue
section=common_section(p,q)
if section is None:continue
duplicate_candidates+=1;readers,used=views.readers(section['origin'],section['axis']);kind,ev,ridges=check_section(section,readers)
diagnostics.append(dict(stage='duplicate',source_id=sid,target_id=tid,passed=kind is not None,kind=kind))
if kind is None:continue
output=p.difference(section['cutter']);remaining=[make(pp,current[sid]['properties'].get('line_kind','solid'),[sid],role='unchanged-section')for pp in parts(output)if pp.area>1e-9]
proof=dict(kind=kind,views=ev,ridges=ridges,geometry=section['geometry'])
if commit('duplicate-section',[sid],remaining,section['cutter'],proof,used,dict(keeper_id=tid)):
keepers.add(tid);break
# A zebra bar may also have been emitted as a narrow generic line. Reuse
# full-object two-view paint validation before removing its duplicate linear span.
from completion_profiles import bar_overlap,bar_supported
from discovery_evidence import glyph_views
bars={fid:f for fid,f in current.items()if f['properties'].get('subtype')=='crosswalk'}
bar_checks={};bar_candidates=0
for sid in [fid for fid,f in current.items()if linear(f)]:
if sid not in current:continue
for bid,b in bars.items():
p=poly(current[sid]);bp=poly(b)
if not p.intersects(bp):continue
cut=bar_overlap(p,bp)
if cut is None:continue
bar_candidates+=1
if bid not in bar_checks:bar_checks[bid]=glyph_views(bp,views,None,None)
ev,names=bar_checks[bid];okay=bar_supported(ev)
diagnostics.append(dict(stage='bar-overlap',source_id=sid,bar_id=bid,passed=okay,views=ev))
if not okay:continue
output=p.difference(cut);remaining=[make(pp,current[sid]['properties'].get('line_kind','solid'),[sid],role='unchanged-section')for pp in parts(output)if pp.area>1e-9]
if commit('crosswalk-line-duplicate',[sid],remaining,cut,ev,[{names[0]:1},{names[1]:1}],dict(keeper_id=bid)) :break
# Stage 4: run the qualified whole-row assembly against the new graph. Known
# dashes and symbols remain barriers. All original fragments are fitted jointly.
barriers=shapely.union_all([protected]+[poly(f)for f in current.values()if linear(f)and f['properties'].get('line_kind')=='dashed'])
joinviews=GaussianViews(tiles,labels,low,high,barriers);initial={fid:poly(f)for fid,f in current.items()if linear(f)and f['properties'].get('line_kind')!='dashed'}
groups={fid:[fid]for fid in initial};considered=set()
while True:
choices=[];entries=sorted(groups)
for i,aid in enumerate(entries):
for bid in entries[:i]:
identity=tuple(sorted(groups[aid]+groups[bid]))
if identity in considered:continue
a,b=poly(current[aid]),poly(current[bid])
if a.distance(b)>.56:continue
q=pair(a,b)
if q is not None:choices.append((abs(q['gap_m']),identity,aid,bid))
accepted=False
for _,identity,aid,bid in sorted(choices):
considered.add(identity);r=fit_chain([initial[i]for i in identity])
if r is None or r['polygon'].intersection(barriers).area>.005:continue
readers,used=joinviews.readers(r['origin'],r['axis']);okay,ev=check_chain(r,readers)
if not okay:continue
p=r['output_polygon']
if p.intersection(barriers).area>.005:continue
f=make(p,'solid',[aid,bid],assembly_operation=r['operation'])
if commit('assembled-row',[aid,bid],[f],r['edit_domain'],ev,used,dict(assembly_operation=r['operation'],max_axis_displacement_m=r['max_axis_displacement_m'])):
groups.pop(aid);groups.pop(bid);groups[f['id']]=list(identity);accepted=True;break
if not accepted:break
if len(transactions)>1500:raise RuntimeError('Unbounded edits')
result={**old,'features':list(current.values()),'completion_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False))
(O/'completion-rows.json').write_text(json.dumps(transactions,indent=2,allow_nan=False));(O/'completion-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes())
counts=collections.Counter(r['kind']for r in transactions)
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(transactions),stages=dict(counts),profiled_axes=len(seeds),periodic_families=len(family_rows),duplicate_candidates=duplicate_candidates,bar_candidates=bar_candidates,proposed_periodic_rows=len(proposals),newly_captured_strokes=sum(r.get('newly_captured_strokes',0)for r in transactions),normalized_strokes=sum(r.get('normalized_strokes',0)for r in transactions),endpoint_extensions=sum(e['kind']=='extend-solid'for r in transactions if r['kind']=='solid-endpoints'for e in r['evidence']),endpoint_trims=sum(e['kind']=='trim-solid'for r in transactions if r['kind']=='solid-endpoints'for e in r['evidence']),before_linear_objects=sum(linear(f)for f in original.values()),after_linear_objects=sum(linear(f)for f in current.values()),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
(O/'completion-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
@@ -0,0 +1,41 @@
from pathlib import Path
import os,json,shutil
from datetime import datetime,timezone
import numpy as np,shapely
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape
from layer_common import O,S
from fit_scene import project
old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'completion-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23)
for p in O.glob('completion-*.jpg'):
h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name)
def draw(im,g,features):
im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200
for f in features:
if f['properties'].get('class')!='road_marking':continue
for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2)))
return im
frames=[];manifest=[];loaded={}
for gi,rec in enumerate(groups):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id']
if name not in loaded:
g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))}
g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]):
frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640')
fn='completion-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects']))
for start in range(0,len(frames),4):
part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white')
for k,im in enumerate(part):sheet.paste(im,(0,k*655))
sheet.save(O/('completion-proof-%03d.jpg'%(start//4+1)),quality=94)
(O/'completion-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True)
# Revisit every short-dash family shown in the prior delivery, using its stored
# bounds only for review framing; these bounds never enter the detector.
references=json.loads(Path('/families/line-families.json').read_text());ref_manifest=[]
for gi,rec in enumerate(references):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200
uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*8/60,raw.width*18/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(2400,855),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(draw(raw,g,old['features']),'До'),(draw(raw,g,new['features']),'После')]):
frame.paste(im.crop(bbox).resize((800,800),Image.Resampling.LANCZOS),(800*j,55));d.text((800*j+10,12),label,font=font,fill='#263640')
fn='reference-%02d.jpg'%gi;frame.save(O/fn,quality=96);ref_manifest.append(dict(group=gi,file=fn,source_tile=name,bounds_source='prior line-families.json; review framing only'))
(O/'reference-visual-manifest.json').write_text(json.dumps(ref_manifest,indent=2))
@@ -0,0 +1,48 @@
import runpy,json,numpy as np
from completion_profiles import families,slot,local_endpoints,describe,bar_overlap,bar_supported
from interval_profiles import rectangle
prior=runpy.run_path('/candidate/test_discovery.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()}
o=np.zeros(2);u=np.array([1.,0.]);seed=dict(origin=o,axis=u,period=1.,length=.5,width=.12)
def reader(centers,missing=None,offset=0,solid=False,underlay=0):
def read(xy):
x,y=xy.T;on=np.ones(len(x),bool)if solid else np.zeros(len(x),bool)
for c in centers:on|=abs(x-c)<=.25
sig=(underlay+140*on)*np.exp(-.5*((y-offset)/.045)**2);rgb=np.repeat(np.clip(65+sig,0,255)[:,None],3,1).astype('uint8');valid=np.ones(len(x),bool)
if missing is not None:valid[(x>missing[0])&(x<missing[1])]=False
return rgb,valid
return read
read=reader(range(-5,6));r=slot(seed,4,[read,read]);checks['single_outside_slot_observed']=r is not None
checks['row_axis_and_dimensions_preserved']=r is not None and r['polygon'].symmetric_difference(rectangle(o,u,3.75,4.25,.12)).area<1e-9
checks['one_view_not_enough']=slot(seed,4,[read])is None
absent=reader([0,1,2]);checks['period_does_not_invent_paint']=slot(seed,4,[read,absent])is None
unknown=reader(range(-5,6),missing=(3.8,4.1));checks['occluded_slot_not_filled']=slot(seed,4,[read,unknown])is None
boundary=reader(range(-5,6),missing=(4.3,4.6));checks['unknown_gap_not_dark_asphalt']=slot(seed,4,[read,boundary])is None
solid=reader([],solid=True);checks['solid_not_cut_into_dashes']=slot(seed,4,[solid,solid])is None
neighbor=reader(range(-5,6),offset=.3);checks['nearby_lane_not_claimed']=slot(seed,4,[neighbor,neighbor])is None
shifted=reader(range(-5,6),offset=.08);checks['two_view_ridge_disagreement_rejected']=slot(seed,4,[read,shifted])is None
records=[(str(i),rectangle(o,u,i-.25,i+.25,.12),dict(line_kind='dashed',period_m=1.,dash_length_m=.5))for i in [0,1,3,4]]
g=families(records);checks['missing_internal_slot_keeps_family']=len(g)==1 and g[0]['max_index']==4
checks['two_anchors_insufficient']=not families(records[:2])
checks['neighbor_parallel_rows_separate']=len(families(records+[(f'b{i}',rectangle(np.array([0,.8]),u,i-.25,i+.25,.12),p)for i,(_,_,p)in enumerate(records)]))==2
checks['two_views_same_offset_cannot_draw_wrong_axis']=slot(seed,4,[shifted,shifted])is None
worn=reader(range(-5,6),underlay=40);checks['bounded_peaks_over_worn_underlay']=slot(seed,4,[worn,worn])is not None
checks['underlay_alone_is_not_dash']=slot(seed,4,[reader([],underlay=40),reader([],underlay=40)])is None
from shapely.geometry import Polygon
ang=.72;R=np.array([[np.cos(ang),-np.sin(ang)],[np.sin(ang),np.cos(ang)]]);shift=np.array([100,-70]);sr={**seed,'origin':shift,'axis':R@u};rr=lambda xy:read((xy-shift)@R)
rot=slot(sr,4,[rr,rr]);checks['rigid_transform_equivalent']=rot is not None and abs(rot['polygon'].area-r['polygon'].area)<1e-8
long=describe(rectangle(o,u,0,20,.12))
def tail(xy):
x,y=xy.T;center=np.where(x<15,-.1,0);on=(x>=0)&(x<=19.3);sig=140*on*np.exp(-.5*((y-center)/.045)**2)
return np.repeat(np.clip(65+sig,0,255)[:,None],3,1).astype('uint8'),np.ones(len(x),bool)
checks['local_end_ignores_distant_ridge']=any(c['sign']==1 and c['kind']=='trim-solid'for c in local_endpoints(long,[tail,tail]))
checks['local_endpoint_single_view_not_enough']=not local_endpoints(long,[tail])
bar=rectangle(o,u,0,5,.5);line=rectangle(o,u,-2,7,.12);cut=bar_overlap(line,bar)
checks['same_paint_bar_duplicate_nominated']=cut is not None
checks['bar_cleanup_keeps_outer_line']=cut is not None and abs(line.difference(cut).area-(4-.05)*.12)<1e-8
checks['crossing_lane_not_bar_duplicate']=bar_overlap(rectangle(np.array([2.,0]),np.array([0.,1.]),-2,2,.12),bar)is None
checks['adjacent_parallel_lane_not_bar_duplicate']=bar_overlap(rectangle(np.array([0.,.5]),u,0,5,.12),bar)is None
checks['uncertain_bar_cannot_remove_line']=not bar_supported([dict(valid=.9,support=1.,recall=1.)]*2)
checks['unpainted_bar_cannot_remove_line']=not bar_supported([dict(valid=1.,support=.3,recall=1.)]*2)
checks['single_bar_render_insufficient']=not bar_supported([dict(valid=1.,support=1.,recall=1.)])
checks['outside_bar_paint_does_not_veto_internal_dedup']=bar_supported([dict(valid=1.,support=1.,recall=.3)]*2)
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/completion-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(dict(passed=result['passed'],tests=len(checks),failed=[k for k,v in checks.items()if not v])));assert result['passed']
@@ -0,0 +1,83 @@
# Whole-symbol component pass
Offline Gaussian-only refinement of bicycles, arrow symbols and yellow zigzags.
This module adds evidence-supported presets to an accepted full-map artifact.
It does not replace the road, pedestrian, façade, crosswalk or linear-marking
passes. Input review decisions remain part of the baseline provenance.
## Method
1. Reuse the hashed, whole-scene SAM3 symbol masks and registered Gaussian
orthophoto patches from `symbol_pass`. Model masks supply a class and search
region; they are not the final outline.
2. Extract white-paint components at two metric scales with OpenCV morphology.
Fit the existing licensed SVG presets with SciPy multistart optimization;
evaluate straight, turning and compound arrows and bicycle symbols.
3. Check the complete preset against two mosaics whose source tiles are selected
geometrically, never by favorable paint score. Test positive paint, negative
space, head/tail/branch support and continuation beyond both ends. Every
completely observed view must explain the connected paint object: a head
detached by weak contrast in one view cannot pass if another view shows the
remaining curved arrow. Missing coverage is explicitly unknown.
4. For bicycle paint only, a vehicle segmentation label can be overridden when
the original context render agrees with its matching ground render in
expected depth (0.12 m tolerance), with strong alpha in both. This is Gaussian
surface evidence; no point cloud supplies observations or geometry.
5. Fit zigzags from the cached whole-scene chromatic proposals. Verify yellow
paint separately from white arrows. A finite three-leg pattern requires
strong support on every leg, low background paint and consistent available
views. Extend a pattern only where additional legs have image support.
6. Lift accepted clean presets onto the Gaussian-derived height field. Replay
every transaction, retain input hashes, and verify all unreplaced features
byte-for-byte as JSON records. A fully verified arrow can replace old linear
fragments contained in its outline (98% within a 0.12 m tolerance, at least
50% actual overlap). A crossing line, neighboring stripe or other symbol
vetoes replacement; every removed fragment is recorded and replayed. Preserve prior observation-review provenance.
`component_rules.py` and `component_zigzag_rules.py` hold shared thresholds.
The refinement code accepts no scene-specific polygon, coordinate exemption,
manual ROI or geographic identity. Scene identity in reports is descriptive.
Parameters were developed and regression-tested on three available scenes;
performance on an unseen scan is not yet established.
## Execution and dependencies
`bundle.json` maps the complete flat execution directory back to canonical
source files and pins their SHA-256 values, inherited wheels and the reference
execution snapshot. Existing runtime libraries include NumPy, OpenCV, SciPy,
Shapely, Pillow and scikit-image. Existing SAM3 outputs and model provenance
come from `symbol_pass`; no additional model weights are introduced here.
`bicycle_artwork.py` and `road_glyph_presets.py` retain their original artwork
attribution and licence metadata (MajorAlexey, CC BY-SA 4.0).
Execute on Worker 006, using the existing simulation resource reservation and
bounded container runner. This is an offline refinement package; the default
interactive recalculation button does not yet reproduce this entire research
chain. The qualified resulting maps are imported through the canonical
`publish_qualified_urban_maps.py` plan/apply/readback path.
Required mounts follow the preceding research passes: `/candidate`, `/out`,
`/fullplan` (current accepted baseline), `/symbolplan`, `/assemblyplan`,
`/catalogplan`, `/searchplan`, `/coverage_base`, `/evidence_plan`, `/ortho`,
`/survey`, `/input` and `/multiview`. Read the qualification runner for exact
input paths and receipts. Do not substitute a historical baseline when a later
review has rejected a feature.
Order: `test_components.py`, `refine_components.py`, `refine_zigzags.py`,
`audit_components.py`, `render_components.py`, `render_plan.py`. Freeze the
entire bundle once before processing all scenes. Human visual review is an
acceptance gate, not a coordinate-dependent processing input. Review every
addition before publication, including rejected intermediate versions.
Private receipts, raw inputs and visual evidence are under
`.runtime/simulation-qualifications/component-pass-20261014/operator`.
The final `verification.json` and publication receipts define delivered counts;
intermediate hypotheses must not be presented as accepted results.
## Limits
The class catalogue and cached semantic proposals still limit recall. Strongly
worn paint, occlusion and incomplete Gaussian coverage can leave symbols
unresolved. Presets regularize shape; neither this fit nor its support scores
establish survey accuracy or GOST compliance. Published objects remain
`observation-only`, with route permission unassigned and confidence unassessed.
@@ -0,0 +1,34 @@
from pathlib import Path
import json,hashlib,numpy as np,shapely
from shapely.geometry import shape,LineString
from shapely.affinity import rotate,translate
from catalog_templates import bicycle
from fragment_templates import template
from component_rules import VERSION,POLICY,accept_symbol
from component_conflicts import symbol_replacements,FRAGMENT_POLICY
from component_zigzag_rules import accept_zigzag
from discovery_rules import uncovered
O=Path('/out');I=Path('/symbolplan');sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest();base=Path('/fullplan/full-map.json');old=json.loads(base.read_text());new=json.loads((O/'full-map.json').read_text());rows=json.loads((O/'component-rows.json').read_text());report=json.loads((O/'component-report.json').read_text());semantic=json.loads((I/'symbol-semantics.json').read_text());patches=json.loads((I/'symbol-patches.json').read_text());current={f['id']:f for f in old['features']}
poly=lambda f:shapely.force_2d(shape(f['geometry']))
checks=dict(transaction_replay=True,semantic_trace=True,image_support=True,clean_preset_geometry=True,no_foreign_overlap=True,contained_fragment_replacement=True)
for r in rows:
checks['transaction_replay']&=r['source_ids']==[f['id']for f in r['before']]and len(r['after'])==1 and r['output_ids']==[r['after'][0]['id']]
for f in r['before']:checks['transaction_replay']&=current.pop(f['id'],None)==f
f=r['after'][0];p=f['properties'];q=poly(f);kind=p['subtype'];checks['transaction_replay']&=f['id']not in current and p['class']=='road_marking'and p['method']==VERSION
if r['kind']=='assembled-symbol':
replacements=symbol_replacements(q,kind,[*current.values(),*r['before']])
checks['contained_fragment_replacement']&=replacements is not None and {v['id']for v in replacements}==set(r['source_ids'])
x=p['template_parameters'];sem=next(s for s in semantic['records']if s['id']==r['patch']);path=I/'symbol-masks'/(r['patch']+'.npz');checks['semantic_trace']&=sha(path)==sem['sha256']
with np.load(path)as z:score=max(float(z['scores'][i])for i in r['masks']);classes={int(z['classes'][i])for i in r['masks']}
checks['semantic_trace']&=score==r['semantic_score']==p['semantic_score']and classes==({0}if kind=='bicycle'else{1})
checks['image_support']&=accept_symbol(r['evidence'],score,r['semantic_containment'],r['fit_score'],kind)and p['lane_context']['passed']
expected=bicycle(x)if kind=='bicycle'else translate(rotate(template(kind,x[3],x[4],x[5]),x[2],origin=(0,0),use_radians=True),x[0],x[1])
else:
checks['transaction_replay']&=r['kind']=='assembled-zigzag'and all(v['properties'].get('subtype')=='zigzag'for v in r['before'])
checks['image_support']&=bool(accept_zigzag(r['evidence']['whole'],r['evidence']['legs'],r['fit']))
expected=LineString(p['vertices']).buffer(p['width_m']/2,cap_style=2,join_style=2)
checks['clean_preset_geometry']&=q.symmetric_difference(expected).area<1e-7
existing=shapely.union_all([poly(v)for v in current.values()if v['properties']['class']=='road_marking']);checks['no_foreign_overlap']&=q.intersection(existing).area<=.005;current[f['id']]=f
features={f['id']:f for f in new['features']};removed={i for row in rows for i in row['source_ids']};checks['unreplaced_features_identical']=all(features.get(f['id'])==f for f in old['features']if f['id']not in removed);checks['replay_matches_map']=features==current;checks['unique_ids']=len(features)==len(new['features']);checks['finite_valid_geometry']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features']);checks['same_policy']=report['fragment_policy']==FRAGMENT_POLICY and report['policy']==POLICY and report['policy_version']==new['component_refinement']==VERSION;checks['all_operations_counted']=len(rows)==report['changed_segments'];checks['baseline_pinned']=sha(base)==report['baseline_sha256'];checks['semantic_inputs_pinned']=sha(I/'symbol-patches.json')==semantic['patch_manifest_sha256']==report['patch_manifest_sha256']and sha(I/'symbol-semantics.json')==report['semantic_sha256'];checks['crosswalk_audit_preserved']=(O/'crosswalk-standard-check.json').read_bytes()==(I/'crosswalk-standard-check.json').read_bytes();checks['prior_observation_review_preserved']=old.get('observation_review')==new.get('observation_review')
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=sha(O/'full-map.json'),complete_recall_measured=False,metric_accuracy_measured=False)
(O/'component-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,422 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"files": {
"assembly_evidence.py": "assembly_pass/assembly_evidence.py",
"assembly_rules.py": "assembly_pass/assembly_rules.py",
"assembly_templates.py": "assembly_pass/assembly_templates.py",
"assembly_zigzag.py": "assembly_pass/assembly_zigzag.py",
"audit_assembly.py": "assembly_pass/audit_assembly.py",
"audit_assembly_joins.py": "assembly_pass/audit_assembly_joins.py",
"audit_beta.py": "beta_pass/audit_beta.py",
"audit_catalog.py": "catalog_pass/audit_catalog.py",
"audit_completion.py": "completion_pass/audit_completion.py",
"audit_components.py": "component_pass/audit_components.py",
"audit_consensus.py": "consensus_pass/audit_consensus.py",
"audit_corridor.py": "corridor_pass/audit_corridor.py",
"audit_discovery.py": "discovery_pass/audit_discovery.py",
"audit_norms.py": "norms_pass/audit_norms.py",
"audit_rows.py": "rows_pass/audit_rows.py",
"audit_search.py": "search_pass/audit_search.py",
"audit_sections.py": "sections_pass/audit_sections.py",
"audit_symbols.py": "symbol_pass/audit_symbols.py",
"audit_transitions.py": "transitions_pass/audit_transitions.py",
"beta_profiles.py": "beta_pass/beta_profiles.py",
"bicycle_artwork.py": "catalog_pass/bicycle_artwork.py",
"catalog_context.py": "catalog_pass/catalog_context.py",
"catalog_dependencies.py": "catalog_pass/catalog_dependencies.py",
"catalog_dependency_pins.py": "catalog_pass/catalog_dependency_pins.py",
"catalog_evidence.py": "symbol_pass/catalog_evidence.py",
"catalog_rules.py": "catalog_pass/catalog_rules.py",
"catalog_templates.py": "catalog_pass/catalog_templates.py",
"catalog_zigzag.py": "catalog_pass/catalog_zigzag.py",
"completion_profiles.py": "completion_pass/completion_profiles.py",
"component_arrows.py": "component_pass/component_arrows.py",
"component_bicycle.py": "component_pass/component_bicycle.py",
"component_conflicts.py": "component_pass/component_conflicts.py",
"component_evidence.py": "component_pass/component_evidence.py",
"component_mosaics.py": "component_pass/component_mosaics.py",
"component_rules.py": "component_pass/component_rules.py",
"component_surface.py": "component_pass/component_surface.py",
"component_targets.py": "component_pass/component_targets.py",
"component_zigzag_rules.py": "component_pass/component_zigzag_rules.py",
"consensus_profiles.py": "consensus_pass/consensus_profiles.py",
"coordinate_cache.py": "orthophoto/coordinate_cache.py",
"corridor_profiles.py": "search_pass/corridor_profiles.py",
"coverage_evidence.py": "corridor_pass/coverage_evidence.py",
"coverage_plan.py": "corridor_pass/coverage_plan.py",
"diagnose_assembly.py": "assembly_pass/diagnose_assembly.py",
"diagnose_components.py": "component_pass/diagnose_components.py",
"diagnose_corridor.py": "corridor_pass/diagnose_corridor.py",
"diagnose_coverage.py": "corridor_pass/diagnose_coverage.py",
"discovery_evidence.py": "discovery_pass/discovery_evidence.py",
"discovery_rules.py": "discovery_pass/discovery_rules.py",
"extract_assembly.py": "assembly_pass/extract_assembly.py",
"extract_catalog.py": "catalog_pass/extract_catalog.py",
"extract_discovery.py": "discovery_pass/extract_discovery.py",
"extract_search.py": "search_pass/extract_search.py",
"fit_scene.py": "full_plan/fit_scene.py",
"fragment_templates.py": "discovery_pass/fragment_templates.py",
"gost_catalog.py": "norms_pass/gost_catalog.py",
"image_profiles.py": "lines_pass/image_profiles.py",
"inspect_bicycles.py": "catalog_pass/inspect_bicycles.py",
"inspect_catalog.py": "catalog_pass/inspect_catalog.py",
"interval_profiles.py": "intervals_pass/interval_profiles.py",
"join_assembly.py": "assembly_pass/join_assembly.py",
"layer_common.py": "full_plan/layer_common.py",
"line_reconstruction.py": "intervals_pass/line_reconstruction.py",
"mapping.py": "corridor_pass/mapping.py",
"norm_profiles.py": "norms_pass/norm_profiles.py",
"ortho_terrain.py": "orthophoto/ortho_terrain.py",
"paint_channels.py": "component_pass/paint_channels.py",
"paint_templates.py": "continuation_pass/paint_templates.py",
"prepare_symbols.py": "symbol_pass/prepare_symbols.py",
"refine_assembly.py": "assembly_pass/refine_assembly.py",
"refine_beta.py": "beta_pass/refine_beta.py",
"refine_catalog.py": "catalog_pass/refine_catalog.py",
"refine_completion.py": "completion_pass/refine_completion.py",
"refine_components.py": "component_pass/refine_components.py",
"refine_consensus.py": "consensus_pass/refine_consensus.py",
"refine_corridor.py": "corridor_pass/refine_corridor.py",
"refine_discovery.py": "discovery_pass/refine_discovery.py",
"refine_norms.py": "norms_pass/refine_norms.py",
"refine_rows.py": "rows_pass/refine_rows.py",
"refine_search.py": "search_pass/refine_search.py",
"refine_sections.py": "sections_pass/refine_sections.py",
"refine_symbols.py": "symbol_pass/refine_symbols.py",
"refine_transitions.py": "transitions_pass/refine_transitions.py",
"refine_zigzags.py": "component_pass/refine_zigzags.py",
"render_assembly.py": "assembly_pass/render_assembly.py",
"render_beta.py": "beta_pass/render_beta.py",
"render_catalog.py": "catalog_pass/render_catalog.py",
"render_completion.py": "completion_pass/render_completion.py",
"render_components.py": "component_pass/render_components.py",
"render_consensus.py": "consensus_pass/render_consensus.py",
"render_corridor.py": "corridor_pass/render_corridor.py",
"render_coverage.py": "corridor_pass/render_coverage.py",
"render_discovery.py": "discovery_pass/render_discovery.py",
"render_hypotheses.py": "component_pass/render_hypotheses.py",
"render_norms.py": "norms_pass/render_norms.py",
"render_plan.py": "catalog_pass/render_plan.py",
"render_rows.py": "rows_pass/render_rows.py",
"render_search.py": "search_pass/render_search.py",
"render_sections.py": "sections_pass/render_sections.py",
"render_symbols.py": "symbol_pass/render_symbols.py",
"render_transitions.py": "transitions_pass/render_transitions.py",
"review_symbols.py": "symbol_pass/review_symbols.py",
"road_glyph_presets.py": "continuation_pass/road_glyph_presets.py",
"row_evidence.py": "corridor_pass/row_evidence.py",
"row_profiles.py": "rows_pass/row_profiles.py",
"search_rules.py": "search_pass/search_rules.py",
"search_views.py": "search_pass/search_views.py",
"section_profiles.py": "sections_pass/section_profiles.py",
"semantic_symbols.py": "symbol_pass/semantic_symbols.py",
"symbol_evidence.py": "symbol_pass/symbol_evidence.py",
"symbol_rules.py": "symbol_pass/symbol_rules.py",
"test_assembly.py": "assembly_pass/test_assembly.py",
"test_beta.py": "beta_pass/test_beta.py",
"test_catalog.py": "catalog_pass/test_catalog.py",
"test_completion.py": "completion_pass/test_completion.py",
"test_components.py": "component_pass/test_components.py",
"test_consensus.py": "consensus_pass/test_consensus.py",
"test_corridor.py": "corridor_pass/test_corridor.py",
"test_discovery.py": "discovery_pass/test_discovery.py",
"test_intervals.py": "intervals_pass/test_intervals.py",
"test_lines.py": "lines_pass/test_lines.py",
"test_norms.py": "norms_pass/test_norms.py",
"test_rows.py": "rows_pass/test_rows.py",
"test_search.py": "search_pass/test_search.py",
"test_sections.py": "sections_pass/test_sections.py",
"test_symbols.py": "symbol_pass/test_symbols.py",
"test_transitions.py": "transitions_pass/test_transitions.py",
"transition_profiles.py": "transitions_pass/transition_profiles.py",
"validation.py": "corridor_pass/validation.py",
"zigzag_evidence.py": "component_pass/zigzag_evidence.py",
"zigzag_mosaics.py": "component_pass/zigzag_mosaics.py"
},
"reference_qualification": "component-pass-20261014",
"source_snapshot": "702597dcd1d61ecbb53d",
"source_sha256": {
"assembly_evidence.py": "0fda82c403f9734ea0b0267504ac82437092d410882dc21417a492de9509c09b",
"assembly_rules.py": "04798c28e0daccc8be5fb045cc736160721308f7c41189f287b97a509999ddbf",
"assembly_templates.py": "41ec0428032ae328d5f46c34702d5b0be43f724e5821278e745554c72326d402",
"assembly_zigzag.py": "dbee99c505381fbdccbecec0817e0ec4e028ac1eb475124829cd58811251b9ca",
"audit_assembly.py": "8defc22e391c330962c503b27c49b9d13cecee90b0170dab1b8372858bda3638",
"audit_assembly_joins.py": "e8a3ded181b69961c8a0a5f88e171ff5ada82f0a43e55c217bb40734e411c094",
"audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f",
"audit_catalog.py": "19d5f0f156c0f90d2e1e2548fee99eee521b76e7152f0b53ae12b43ed48553b2",
"audit_completion.py": "ef6adcfec3e1a4bd894b54a150fe3b8559bf73e94665bb9da6bd68007e90575d",
"audit_components.py": "b472856305839483fcf806eb76a29b46650f2188b1e0cf0f94afdc250eb1fa28",
"audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2",
"audit_corridor.py": "3f792b1830e9097644dd66c38eb2cf7efa11d75a0fda928ffa0a7780afb85bfe",
"audit_discovery.py": "9e5f1bdd0d752d82a52121fe86d4e6fb00068a6af9330a072fe7311a909bc974",
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
"audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01",
"audit_search.py": "0de9929d983c97045444131b9255ec4c256ae652b6adb82551e42b94c4bec0eb",
"audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7",
"audit_symbols.py": "105c7a7939c43643299e071d94f5b1e4acc45a29d8b45482a3d7fabc9508ecea",
"audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a",
"beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e",
"bicycle_artwork.py": "2e5220e6e82024c683b65c81695b53fa3070d58eed89d61f5cbda41f6c3c554f",
"catalog_context.py": "f2e654ea068a758be1f929299786559f02672898047893cdc20e6f1cb204bb80",
"catalog_dependencies.py": "d6407445db28f6f15201f4ec09e3401141fca90e11a9cef52392f88175634fca",
"catalog_dependency_pins.py": "93ed9007288440620b8339043f1d5ae74684e39e7c3bd50d94d24f6cf29c9f3a",
"catalog_evidence.py": "7f9fb171776faf1181705826bec206882aea13eded8664d8e3e6dfd09031ec95",
"catalog_rules.py": "ed0f8e838908bcea9ac1ee15fe13d1b23ac29981428ea6a4bdc097c0226db3cb",
"catalog_templates.py": "05577c611ce5ffa2c21d0f608e728eca13009c994e26913b29f39fdcf584c092",
"catalog_zigzag.py": "2e6a804cd14440afaf27bd0f0c2123afc7bf3ea1c58cd0d49293049f1f3b498f",
"completion_profiles.py": "b01cb280a265f170c2f3823d59d423c0cf11472050678cc4dad716c1f90ff786",
"component_arrows.py": "cb6cfe2f2007e5de430352138d8973959bc2d903a3cd74a984d9f4a10adbb5be",
"component_bicycle.py": "854388ce45520abb82d8f61d1195a50525e6326c315feee5bcb84b66163dc2fe",
"component_conflicts.py": "dccc333197b47bbbf211212b38d5a0018c8bae5f403fed1cbe3e22be0a81967e",
"component_evidence.py": "cd2360a061fd340f257da917d4c9d16c95a188604f72a347ea25b5cbc6e76566",
"component_mosaics.py": "06140a2682448b14cebd30989944537c2412cffa3ae5fae5c0549e4baf11dd53",
"component_rules.py": "910be55c56c3b406e1727339b1054ee0693a5d7c4ec46cb3cfa8015a34eb0553",
"component_surface.py": "e425be65d184d474c5485160547f122291529622244da73ca484469ffd994d69",
"component_targets.py": "1719de92d38ff15377276e7b471501cf5ed21392a14113d90537eafea735e6c2",
"component_zigzag_rules.py": "76566a1ec3b90c7d3abe7dd96054351e3fbb41ac1117f2b1eb09ce33c716da98",
"consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091",
"coordinate_cache.py": "930f8f521ef13c02b589d0c182ab4cf337acc4c213354808d32178bbbea3edf4",
"corridor_profiles.py": "967902dae9137ceddb05708acbb6a7cc1e06977c6d064787a1a651422d2e5672",
"coverage_evidence.py": "1b9c1e4b0c518047ad1eacc6e314132144ae05dcad8cc82dd88b9e1340513497",
"coverage_plan.py": "48e28d6781d5d04e83645ba0a9aa7f0398ae904d26bf2e81caa8d8e741bccdda",
"diagnose_assembly.py": "44ef17e6bdecc9285ae8150ccb5c4dd397006381b34b013ebd3e2ed6c2b34bbc",
"diagnose_components.py": "b9653a2b642c1399dd3b6388cd40a148cb4cb81f665fad3bf993d950a64579f8",
"diagnose_corridor.py": "cff89f2a78ff315906b7d40ba1855f0f842afe1f7f74d1d38b7366e2959bcfd6",
"diagnose_coverage.py": "f5305f0c429aea3ba5f18e4261abd64fe8254e53db24323ffcebc152734864b7",
"discovery_evidence.py": "dc7e0594b77f6d3723a965216164427835aa5ae2ff736b5599774c4efbc626eb",
"discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491",
"extract_assembly.py": "d2f1cd5a1fc03b95496b32e024452c3e8ba489a06299a6cba967d4d18a5c3b33",
"extract_catalog.py": "7c3b7de0291f52d9f37590b438d1abb7e37b36665cfb5e9ba4698b78a8f42574",
"extract_discovery.py": "5d2835cde2b9d4d895609ea39be2a94a22e894d0996d525dcc3df7046c33e681",
"extract_search.py": "09b3c0c65d33fdd5025e3436fb1bd5df67d1e359b507f4fae74a7e61754fc92c",
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
"fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7",
"gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537",
"image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8",
"inspect_bicycles.py": "e12964f244645b7a4b2bdb0da5d2bb90e7d49dc35bf2f66c4a8466fabc6836bb",
"inspect_catalog.py": "322aec8f233009eb42703132b220e1e216f8dc8b59aa6bbd27244067e651727d",
"interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345",
"join_assembly.py": "293fd78d10f0ba13b1339a69d737c3f96ef003ea3f6dd63fdf02d14c40fa324f",
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
"line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738",
"mapping.py": "1c6ba0cc111250d73bc0bc282e9cbb7a602921bca931da6441bc9a6daf88b4f4",
"norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7",
"ortho_terrain.py": "9c9cab9d7086144fd1a108db28f796e9d267375d7135d50d5cb3f054eae75213",
"paint_channels.py": "95895f19638835c9e9564633fc0dacdd6aeae12a5786d6a44f046c91c2d16917",
"paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6",
"prepare_symbols.py": "59d0f7da37f4f119b0bfa996dfe4638999bf1bce575415db087fdb55d64a144a",
"refine_assembly.py": "0da00d12e4bda06760a3fc78fcddb6875012edc046e9f83a00074846031b4939",
"refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831",
"refine_catalog.py": "eeeee4d59066579c1fa8708a1be9d999a481f8f8daf05ec01704897252cc66cb",
"refine_completion.py": "12f424d39a687e8b94823f2e2f7b2f2c95538f3504260b4373c47cc21b29c6e1",
"refine_components.py": "57eeb116e3c61ee42d30d3d6bc557e33d2b2d8ee24910584487bec5d34b69ef5",
"refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36",
"refine_corridor.py": "fd1c4d4e028a037e32538c26a66f876425088b8b5b2c7ffc8d5dc807eba3290f",
"refine_discovery.py": "6272ca1f5052259fb3c6cfd1f1079e4e5864e1e067d12de7ff36d95857219d7b",
"refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5",
"refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8",
"refine_search.py": "113e8cee4f26d1f6b0bcce516388d046ced0523598ddf7f6f4e4dc365a0d9859",
"refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3",
"refine_symbols.py": "c210c825edb1d2469b27afac6292f911df8351e92c8f47d0b5d05f99a229a95a",
"refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b",
"refine_zigzags.py": "8fad49227ca4fdaf72fa46a9050aaa39d699aa2620ffc765ea829e2ecb77d967",
"render_assembly.py": "b8471dceb42be102eeb1918eb7950e038d3fc9e0ebab0a3b01b3aaea8be710fa",
"render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c",
"render_catalog.py": "58ecb30ac8ddffd1489c93361dc6678c82e4dbbfbe8a6e851a1be395ee40db1b",
"render_completion.py": "5e76d2a6ce41a6be8013f98df33951fe17fc209c078376ebfafe7c60ed0b14a7",
"render_components.py": "2115f348228ffcbb21ac1a80c1e8c37b082af8be09ca2a182028aa1ea0a7a222",
"render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682",
"render_corridor.py": "f6355e3761834fcf811c0cae9dc3ce602e7221afea4f674178d6c29085e87e9f",
"render_coverage.py": "2cba12c09333c242841b174f201c89ffce9e715b78b26b472117ae140ff4157c",
"render_discovery.py": "868ad8eb712f5880e944b0899205a2c0fd6dd0713eb727b1c49dda92b897fa20",
"render_hypotheses.py": "d7ea4b19409a7b5c78c8a01ed9c190069cc109e4bfa854c77672ed1d1e64ba56",
"render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d",
"render_plan.py": "9e702d51c6be09caa456d8e528bd62bc9ec238ca3689a99f38b414dafc193f66",
"render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e",
"render_search.py": "5655641df20c2e4f0849bb35ff4029d806554cc7d3b696d26378ad9d880d0491",
"render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c",
"render_symbols.py": "ae3bd83870aa435d2051282b65fd3015eee8c11e92831062328e39482de76d5b",
"render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d",
"review_symbols.py": "264c92625648cf1930753add51496c28ef645a481e5cf13993ae0cf758d5df30",
"road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322",
"row_evidence.py": "fec784ab795470d96e48c7022e59d5206b0c07b40d84843cbc058fcc4de896c0",
"row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df",
"search_rules.py": "ca3cab6d24f31460d9912c351c166d89fb1c3b21df620ba1d847543bd7a71f41",
"search_views.py": "8a123558dbef184fc85a92c9547c19644d14681329dbbd0cfeac0032bbd102be",
"section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de",
"semantic_symbols.py": "0665fa1ba0dd08bd29b762a09fb2d03b31a1894ff0731353c2f847fb170c5658",
"symbol_evidence.py": "2d643c9756660bd33ad208ffbe960283feb3aa12352399b6df6f81c0b507e3a2",
"symbol_rules.py": "c349ee11f5c33da7310dcf6e530d988858243c5e99ad8072818d78802ea59527",
"test_assembly.py": "80510625a71ea9fc04add883d9a7e40a3bfdcac4251bd702b5507ce76f9bba8f",
"test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b",
"test_catalog.py": "91a8fdbc330cecd5bc354406012852cc46245baf99ba8befdaac164f6b79c1c4",
"test_completion.py": "a3a6a283221ae48ade8fd0cca2f145509fd6bedf8e808967c13438791654a7f1",
"test_components.py": "71c48f0b6afda80713aef4ee6547acc1995f0dd07d901ee84a4254bee0cc1168",
"test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7",
"test_corridor.py": "42788835ec88e91a3b92ec7ead4e4c489b01ddf11256b46b7b3722c6b4770703",
"test_discovery.py": "a75ffc22d065201f7023d8e6cfb6dc09204a80f9be607599b85479628a301538",
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a",
"test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f",
"test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449",
"test_search.py": "fc3d874c8a6639bfa007eb8fa4a869e270bddafe317868bed29450c6024f8756",
"test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f",
"test_symbols.py": "63a429e8d3324b87075bcb2a2c9902f35c45f1aceff5b46c260aec9bed666481",
"test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438",
"transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e",
"validation.py": "ee004220db3cdf2429af2a0e875cd9a63526587422881692ce56fe9d77f5cc2c",
"zigzag_evidence.py": "978bda848dc7dc85268e2696b918eb6f86c7377c7e9da7c5e4b875815daefa0d",
"zigzag_mosaics.py": "b2703eb159e92680df15d4ed80cd47e55a9168ab3f1703f50faf843eca5262b5"
},
"external_dependencies": {
"packaging-24.2-py3-none-any.whl": "09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759",
"scikit_image-0.24.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl": "8579bda9c3f78cb3b3ed8b9425213c53a25fa7e994b7ac01f2440b395babf660",
"imageio-2.36.1-py3-none-any.whl": "20abd2cae58e55ca1af8a8dcf43293336a59adf0391f1917bf8518633cfc2cdf",
"networkx-3.4.2-py3-none-any.whl": "df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5f",
"lazy_loader-0.4-py3-none-any.whl": "342aa8e14d543a154047afb4ba8ef17f5563baad3fc610d7b15b213b0f119efc",
"tifffile-2024.9.20-py3-none-any.whl": "c54dc85bc1065d972cb8a6ffb3181389d597876aa80177933459733e4ed243dd"
},
"external_evidence_assets": {
"review-font.ttf": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9"
},
"execution_snapshot_sha256": {
"audit_components.py": "b472856305839483fcf806eb76a29b46650f2188b1e0cf0f94afdc250eb1fa28",
"render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d",
"coverage_plan.py": "48e28d6781d5d04e83645ba0a9aa7f0398ae904d26bf2e81caa8d8e741bccdda",
"paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6",
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a",
"packaging-24.2-py3-none-any.whl": "09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759",
"catalog_dependency_pins.py": "93ed9007288440620b8339043f1d5ae74684e39e7c3bd50d94d24f6cf29c9f3a",
"assembly_rules.py": "04798c28e0daccc8be5fb045cc736160721308f7c41189f287b97a509999ddbf",
"test_components.py": "71c48f0b6afda80713aef4ee6547acc1995f0dd07d901ee84a4254bee0cc1168",
"catalog_rules.py": "ed0f8e838908bcea9ac1ee15fe13d1b23ac29981428ea6a4bdc097c0226db3cb",
"render_hypotheses.py": "d7ea4b19409a7b5c78c8a01ed9c190069cc109e4bfa854c77672ed1d1e64ba56",
"render_discovery.py": "868ad8eb712f5880e944b0899205a2c0fd6dd0713eb727b1c49dda92b897fa20",
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
"search_rules.py": "ca3cab6d24f31460d9912c351c166d89fb1c3b21df620ba1d847543bd7a71f41",
"component_zigzag_rules.py": "76566a1ec3b90c7d3abe7dd96054351e3fbb41ac1117f2b1eb09ce33c716da98",
"render_catalog.py": "58ecb30ac8ddffd1489c93361dc6678c82e4dbbfbe8a6e851a1be395ee40db1b",
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
"prepare_symbols.py": "59d0f7da37f4f119b0bfa996dfe4638999bf1bce575415db087fdb55d64a144a",
"test_catalog.py": "91a8fdbc330cecd5bc354406012852cc46245baf99ba8befdaac164f6b79c1c4",
"render_coverage.py": "2cba12c09333c242841b174f201c89ffce9e715b78b26b472117ae140ff4157c",
"test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7",
"audit_symbols.py": "105c7a7939c43643299e071d94f5b1e4acc45a29d8b45482a3d7fabc9508ecea",
"catalog_zigzag.py": "2e6a804cd14440afaf27bd0f0c2123afc7bf3ea1c58cd0d49293049f1f3b498f",
"refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8",
"refine_symbols.py": "c210c825edb1d2469b27afac6292f911df8351e92c8f47d0b5d05f99a229a95a",
"coverage_evidence.py": "1b9c1e4b0c518047ad1eacc6e314132144ae05dcad8cc82dd88b9e1340513497",
"audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f",
"component_targets.py": "1719de92d38ff15377276e7b471501cf5ed21392a14113d90537eafea735e6c2",
"refine_completion.py": "12f424d39a687e8b94823f2e2f7b2f2c95538f3504260b4373c47cc21b29c6e1",
"zigzag_mosaics.py": "b2703eb159e92680df15d4ed80cd47e55a9168ab3f1703f50faf843eca5262b5",
"test_search.py": "fc3d874c8a6639bfa007eb8fa4a869e270bddafe317868bed29450c6024f8756",
"audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7",
"scikit_image-0.24.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl": "8579bda9c3f78cb3b3ed8b9425213c53a25fa7e994b7ac01f2440b395babf660",
"render_corridor.py": "f6355e3761834fcf811c0cae9dc3ce602e7221afea4f674178d6c29085e87e9f",
"bicycle_artwork.py": "2e5220e6e82024c683b65c81695b53fa3070d58eed89d61f5cbda41f6c3c554f",
"beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e",
"component_mosaics.py": "06140a2682448b14cebd30989944537c2412cffa3ae5fae5c0549e4baf11dd53",
"refine_discovery.py": "6272ca1f5052259fb3c6cfd1f1079e4e5864e1e067d12de7ff36d95857219d7b",
"test_corridor.py": "42788835ec88e91a3b92ec7ead4e4c489b01ddf11256b46b7b3722c6b4770703",
"render_components.py": "2115f348228ffcbb21ac1a80c1e8c37b082af8be09ca2a182028aa1ea0a7a222",
"audit_search.py": "0de9929d983c97045444131b9255ec4c256ae652b6adb82551e42b94c4bec0eb",
"audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2",
"imageio-2.36.1-py3-none-any.whl": "20abd2cae58e55ca1af8a8dcf43293336a59adf0391f1917bf8518633cfc2cdf",
"refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b",
"line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738",
"norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7",
"refine_assembly.py": "0da00d12e4bda06760a3fc78fcddb6875012edc046e9f83a00074846031b4939",
"test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f",
"row_evidence.py": "fec784ab795470d96e48c7022e59d5206b0c07b40d84843cbc058fcc4de896c0",
"transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e",
"component_rules.py": "910be55c56c3b406e1727339b1054ee0693a5d7c4ec46cb3cfa8015a34eb0553",
"test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f",
"render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c",
"semantic_symbols.py": "0665fa1ba0dd08bd29b762a09fb2d03b31a1894ff0731353c2f847fb170c5658",
"audit_corridor.py": "3f792b1830e9097644dd66c38eb2cf7efa11d75a0fda928ffa0a7780afb85bfe",
"row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df",
"audit_assembly_joins.py": "e8a3ded181b69961c8a0a5f88e171ff5ada82f0a43e55c217bb40734e411c094",
"diagnose_assembly.py": "44ef17e6bdecc9285ae8150ccb5c4dd397006381b34b013ebd3e2ed6c2b34bbc",
"render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e",
"extract_search.py": "09b3c0c65d33fdd5025e3436fb1bd5df67d1e359b507f4fae74a7e61754fc92c",
"refine_zigzags.py": "8fad49227ca4fdaf72fa46a9050aaa39d699aa2620ffc765ea829e2ecb77d967",
"test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b",
"assembly_evidence.py": "0fda82c403f9734ea0b0267504ac82437092d410882dc21417a492de9509c09b",
"search_views.py": "8a123558dbef184fc85a92c9547c19644d14681329dbbd0cfeac0032bbd102be",
"inspect_bicycles.py": "e12964f244645b7a4b2bdb0da5d2bb90e7d49dc35bf2f66c4a8466fabc6836bb",
"paint_channels.py": "95895f19638835c9e9564633fc0dacdd6aeae12a5786d6a44f046c91c2d16917",
"completion_profiles.py": "b01cb280a265f170c2f3823d59d423c0cf11472050678cc4dad716c1f90ff786",
"diagnose_coverage.py": "f5305f0c429aea3ba5f18e4261abd64fe8254e53db24323ffcebc152734864b7",
"test_discovery.py": "a75ffc22d065201f7023d8e6cfb6dc09204a80f9be607599b85479628a301538",
"component_conflicts.py": "dccc333197b47bbbf211212b38d5a0018c8bae5f403fed1cbe3e22be0a81967e",
"component_arrows.py": "cb6cfe2f2007e5de430352138d8973959bc2d903a3cd74a984d9f4a10adbb5be",
"gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537",
"symbol_rules.py": "c349ee11f5c33da7310dcf6e530d988858243c5e99ad8072818d78802ea59527",
"catalog_dependencies.py": "d6407445db28f6f15201f4ec09e3401141fca90e11a9cef52392f88175634fca",
"render_search.py": "5655641df20c2e4f0849bb35ff4029d806554cc7d3b696d26378ad9d880d0491",
"component_evidence.py": "cd2360a061fd340f257da917d4c9d16c95a188604f72a347ea25b5cbc6e76566",
"audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01",
"networkx-3.4.2-py3-none-any.whl": "df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5f",
"coordinate_cache.py": "930f8f521ef13c02b589d0c182ab4cf337acc4c213354808d32178bbbea3edf4",
"refine_catalog.py": "eeeee4d59066579c1fa8708a1be9d999a481f8f8daf05ec01704897252cc66cb",
"refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831",
"review_symbols.py": "264c92625648cf1930753add51496c28ef645a481e5cf13993ae0cf758d5df30",
"discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491",
"catalog_templates.py": "05577c611ce5ffa2c21d0f608e728eca13009c994e26913b29f39fdcf584c092",
"render_completion.py": "5e76d2a6ce41a6be8013f98df33951fe17fc209c078376ebfafe7c60ed0b14a7",
"render_symbols.py": "ae3bd83870aa435d2051282b65fd3015eee8c11e92831062328e39482de76d5b",
"test_symbols.py": "63a429e8d3324b87075bcb2a2c9902f35c45f1aceff5b46c260aec9bed666481",
"render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682",
"section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de",
"render_plan.py": "9e702d51c6be09caa456d8e528bd62bc9ec238ca3689a99f38b414dafc193f66",
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
"image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8",
"audit_catalog.py": "19d5f0f156c0f90d2e1e2548fee99eee521b76e7152f0b53ae12b43ed48553b2",
"extract_assembly.py": "d2f1cd5a1fc03b95496b32e024452c3e8ba489a06299a6cba967d4d18a5c3b33",
"inspect_catalog.py": "322aec8f233009eb42703132b220e1e216f8dc8b59aa6bbd27244067e651727d",
"refine_components.py": "57eeb116e3c61ee42d30d3d6bc557e33d2b2d8ee24910584487bec5d34b69ef5",
"zigzag_evidence.py": "978bda848dc7dc85268e2696b918eb6f86c7377c7e9da7c5e4b875815daefa0d",
"assembly_templates.py": "41ec0428032ae328d5f46c34702d5b0be43f724e5821278e745554c72326d402",
"assembly_zigzag.py": "dbee99c505381fbdccbecec0817e0ec4e028ac1eb475124829cd58811251b9ca",
"ortho_terrain.py": "9c9cab9d7086144fd1a108db28f796e9d267375d7135d50d5cb3f054eae75213",
"audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a",
"consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091",
"render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d",
"test_assembly.py": "80510625a71ea9fc04add883d9a7e40a3bfdcac4251bd702b5507ce76f9bba8f",
"refine_search.py": "113e8cee4f26d1f6b0bcce516388d046ced0523598ddf7f6f4e4dc365a0d9859",
"refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3",
"road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322",
"refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5",
"catalog_evidence.py": "7f9fb171776faf1181705826bec206882aea13eded8664d8e3e6dfd09031ec95",
"render_assembly.py": "b8471dceb42be102eeb1918eb7950e038d3fc9e0ebab0a3b01b3aaea8be710fa",
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
"fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7",
"mapping.py": "1c6ba0cc111250d73bc0bc282e9cbb7a602921bca931da6441bc9a6daf88b4f4",
"discovery_evidence.py": "dc7e0594b77f6d3723a965216164427835aa5ae2ff736b5599774c4efbc626eb",
"review-font.ttf": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9",
"test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438",
"render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c",
"extract_catalog.py": "7c3b7de0291f52d9f37590b438d1abb7e37b36665cfb5e9ba4698b78a8f42574",
"extract_discovery.py": "5d2835cde2b9d4d895609ea39be2a94a22e894d0996d525dcc3df7046c33e681",
"interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345",
"refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36",
"lazy_loader-0.4-py3-none-any.whl": "342aa8e14d543a154047afb4ba8ef17f5563baad3fc610d7b15b213b0f119efc",
"test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449",
"test_completion.py": "a3a6a283221ae48ade8fd0cca2f145509fd6bedf8e808967c13438791654a7f1",
"diagnose_corridor.py": "cff89f2a78ff315906b7d40ba1855f0f842afe1f7f74d1d38b7366e2959bcfd6",
"diagnose_components.py": "b9653a2b642c1399dd3b6388cd40a148cb4cb81f665fad3bf993d950a64579f8",
"catalog_context.py": "f2e654ea068a758be1f929299786559f02672898047893cdc20e6f1cb204bb80",
"join_assembly.py": "293fd78d10f0ba13b1339a69d737c3f96ef003ea3f6dd63fdf02d14c40fa324f",
"component_surface.py": "e425be65d184d474c5485160547f122291529622244da73ca484469ffd994d69",
"corridor_profiles.py": "967902dae9137ceddb05708acbb6a7cc1e06977c6d064787a1a651422d2e5672",
"audit_assembly.py": "8defc22e391c330962c503b27c49b9d13cecee90b0170dab1b8372858bda3638",
"audit_discovery.py": "9e5f1bdd0d752d82a52121fe86d4e6fb00068a6af9330a072fe7311a909bc974",
"symbol_evidence.py": "2d643c9756660bd33ad208ffbe960283feb3aa12352399b6df6f81c0b507e3a2",
"component_bicycle.py": "854388ce45520abb82d8f61d1195a50525e6326c315feee5bcb84b66163dc2fe",
"audit_completion.py": "ef6adcfec3e1a4bd894b54a150fe3b8559bf73e94665bb9da6bd68007e90575d",
"tifffile-2024.9.20-py3-none-any.whl": "c54dc85bc1065d972cb8a6ffb3181389d597876aa80177933459733e4ed243dd",
"validation.py": "ee004220db3cdf2429af2a0e875cd9a63526587422881692ce56fe9d77f5cc2c",
"refine_corridor.py": "fd1c4d4e028a037e32538c26a66f876425088b8b5b2c7ffc8d5dc807eba3290f"
}
}
@@ -0,0 +1,41 @@
"""Multi-start registration of existing arrow artwork, with whole-object fit."""
import numpy as np,cv2,shapely
from shapely.affinity import rotate,translate
from scipy.optimize import minimize
from fragment_templates import template
def fit_arrows(p, *, kinds=None, template_fn=template):
if p.is_empty or p.area<.25:return []
xy=shapely.get_coordinates(p);rect=cv2.minAreaRect(xy.astype('float32'));L,W=sorted(rect[1],reverse=True)
if not(1.2<L<9 and .40<W<3.2 and .08<p.area/(L*W)<.75):return []
cell=.035;lo=np.asarray(p.bounds[:2])-.6;hi=np.asarray(p.bounds[2:])+.6;size=np.ceil((hi-lo)/cell).astype(int)[::-1]
def draw(poly):
m=np.zeros(size,np.uint8)
for q in ([poly]if poly.geom_type=='Polygon'else getattr(poly,'geoms',[])):
if q.geom_type!='Polygon' or q.is_empty:continue
cv2.fillPoly(m,[np.rint((np.asarray(q.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1)
return m
target=draw(p);kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5));near=cv2.dilate(target,kernel);fits=[]
for kind in (kinds if kinds is not None else ['straight_arrow','left_arrow','right_arrow','straight_left_arrow','straight_right_arrow']):
def from_center(x):
cx,cy,a,ll,ww,stroke=x
return np.r_[np.array([cx,cy])-ll/2*np.array([np.cos(a),np.sin(a)]),a,ll,ww,stroke]
def polygon(x):
z=from_center(x);return translate(rotate(template_fn(kind,z[3],z[4],z[5]),z[2],origin=(0,0),use_radians=True),z[0],z[1])
def quality(x):
m=draw(polygon(x));wide=cv2.dilate(m,kernel);cover=float((m&near).sum()/max(m.sum(),1));recall=float((wide&target).sum()/max(target.sum(),1));iou=float((m&target).sum()/max((m|target).sum(),1));return cover,recall,.6*2*cover*recall/max(cover+recall,1e-6)+.4*iou
seeds=[]
for a in np.arange(24)*np.pi/12:
axis=np.array([np.cos(a),np.sin(a)]);normal=np.array([-axis[1],axis[0]]);uv=np.c_[xy@axis,xy@normal];low,high=np.quantile(uv,[0,.99],axis=0);ll,ww=high-low
if ll/ww<1.2:continue
center=((low+high)/2)[0]*axis+((low+high)/2)[1]*normal;x=np.r_[center,a,ll,ww,.16];seeds.append((quality(x)[2],x))
starts=[]
for score,x in sorted(seeds,key=lambda v:-v[0]):
if score<.32 or any(abs(np.arctan2(np.sin(x[2]-q[2]),np.cos(x[2]-q[2])))<.35 for q in starts):continue
starts.append(x)
if len(starts)==3:break
for x in starts:
cx,cy,a,ll,ww,_=x;bounds=[(cx-.35,cx+.35),(cy-.35,cy+.35),(a-.30,a+.30),(ll*.8,ll*1.2),(ww*.75,ww*1.25),(.08,.30)]
opt=minimize(lambda z:1-quality(z)[2],x,method='Powell',bounds=bounds,options=dict(maxiter=25,xtol=.003,ftol=.003));z=opt.x if quality(opt.x)[2]>=quality(x)[2]else x;q=quality(z)
if q[0]>=.80 and q[1]>=.80 and q[2]>=.76:fits.append(dict(polygon=polygon(z),kind=kind,parameters=from_center(z).tolist(),support=q[0],recall=q[1],score=q[2]))
return sorted(fits,key=lambda x:-x['score'])
@@ -0,0 +1,52 @@
"""OpenCV raster / SciPy registration with global orientation initialization."""
import numpy as np, cv2, shapely
from shapely.geometry import Polygon
from scipy.optimize import minimize
from catalog_templates import bicycle
def fit_bicycle(p,all_hypotheses=False):
if p.is_empty or p.area<.10:return None
rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);corners=cv2.boxPoints(rect);edges=np.roll(corners,-1,axis=0)-corners;k=np.argmax(np.linalg.norm(edges,axis=1));L=float(np.linalg.norm(edges[k]));W=float(min(rect[1]));u=edges[k]/L;ang=np.arctan2(u[1],u[0]);origin=np.asarray(rect[0]);fill=p.area/max(L*W,1e-6)
if not(1.<L<4.5 and .4<W<2.2 and 1.1<L/W<4 and .10<fill<.70):return None
closed=p.buffer(.04).buffer(-.04)
holes=[Polygon(h)for q in ([closed]if closed.geom_type=='Polygon'else getattr(closed,'geoms',[]))if q.geom_type=='Polygon'for h in q.interiors]
# Semantic seeding supplies class identity; holes are checked in the fitted preset negative space.
cell=.02;lo=np.asarray(p.bounds[:2])-.4;hi=np.asarray(p.bounds[2:])+.4;size=np.ceil((hi-lo)/cell).astype(int)[::-1]
def draw(poly):
m=np.zeros(size,np.uint8)
for q in ([poly]if poly.geom_type=='Polygon'else getattr(poly,'geoms',[])):
if q.is_empty or q.geom_type!='Polygon':continue
cv2.fillPoly(m,[np.rint((np.asarray(q.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1)
for h in q.interiors:cv2.fillPoly(m,[np.rint((np.asarray(h.coords)[:,:2]-lo)/cell).astype('int32')],0)
return m
target=draw(p);kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5));near=cv2.dilate(target,kernel);best=None
def quality(x):
m=draw(bicycle(x,fast=True));wide=cv2.dilate(m,kernel);cover=float((m&near).sum()/max(m.sum(),1));recall=float((wide&target).sum()/max(target.sum(),1));iou=float((m&target).sum()/max((m|target).sum(),1));return cover,recall,.6*2*cover*recall/max(cover+recall,1e-6)+.4*iou
coordinates=shapely.get_coordinates(p)
seeds=[]
# Global orientation search, rotated around the symbol centre. The final
# parameters still use the shared SVG base-point convention.
def from_center(x):
cx,cy,a,ll,ww,b=x
return np.r_[np.array([cx,cy])-ll/2*np.array([np.cos(a),np.sin(a)]),a,ll,ww,b]
for a in np.arange(24)*np.pi/12:
axis=np.array([np.cos(a),np.sin(a)]);normal=np.array([-axis[1],axis[0]])
uv=np.c_[coordinates@axis,coordinates@normal]
for trim in [0.,.02]:
low,high=np.quantile(uv,[trim,1-trim],axis=0);ll,ww=high-low
if min(ll,ww)<.3:continue
center=((low+high)/2)[0]*axis+((low+high)/2)[1]*normal
x=np.r_[center,a,ll,ww,0.];seeds.append((quality(from_center(x))[2],x))
starts=[]
for score,x in sorted(seeds,key=lambda v:-v[0]):
if any(abs(np.arctan2(np.sin(x[2]-q[2]),np.cos(x[2]-q[2])))<np.deg2rad(25)for q in starts):continue
starts.append(x)
if len(starts)==6:break
hypotheses=[]
for x in starts:
cx,cy,a,ll,ww,_=x
bounds=[(cx-.30,cx+.30),(cy-.30,cy+.30),(a-.26,a+.26),(ll*.80,ll*1.20),(ww*.75,ww*1.25),(-.02,.025)]
opt=minimize(lambda z:1-quality(from_center(z))[2],x,method='Powell',bounds=bounds,options=dict(maxiter=40,xtol=.002,ftol=.002))
z=from_center(opt.x if quality(from_center(opt.x))[2]>=quality(from_center(x))[2]else x);q=quality(z)
hypothesis=dict(polygon=bicycle(z),score=q[2],support=q[0],recall=q[1],parameters=z.tolist());hypotheses.append(hypothesis)
return sorted(hypotheses,key=lambda x:-x['score'])if all_hypotheses else max(hypotheses,key=lambda x:x['score'],default=None)
@@ -0,0 +1,30 @@
"""Whole symbols may replace their own previously extracted linear fragments.
A neighboring line, crossing stripe or existing symbol must never be consumed.
This rule is applied only after the complete symbol passed image evidence.
"""
import shapely
from shapely.geometry import shape
FRAGMENT_POLICY = dict(min_inside_fraction=.98, min_overlap_fraction=.50,
containment_tolerance_m=.12, overlap_area_tolerance_m2=.005)
def symbol_replacements(polygon, kind, features):
replacements = []
for feature in features:
props = feature['properties']
if props['class'] != 'road_marking':
continue
geometry = shapely.force_2d(shape(feature['geometry']))
intersection = polygon.intersection(geometry).area
if intersection <= FRAGMENT_POLICY['overlap_area_tolerance_m2']:
continue
if kind == 'bicycle' or props.get('subtype') != 'linear_marking':
return None
if geometry.area <= 0 or intersection / geometry.area < FRAGMENT_POLICY['min_overlap_fraction']:
return None
inside = polygon.buffer(FRAGMENT_POLICY['containment_tolerance_m']).intersection(geometry).area / geometry.area
if inside < FRAGMENT_POLICY['min_inside_fraction']:
return None
replacements.append(feature)
return replacements
@@ -0,0 +1,61 @@
from paint_channels import paint_mask
import numpy as np,cv2,shapely
from discovery_rules import POLICY
def glyph_score(rgb,allowed,points,polygon,cell=.04,kind=None,parameters=None,observed=None,paint_override=None,connectivity_open_m=0.):
"""Check positive paint, unpainted negative space, and unexplained pixels."""
h,w=allowed.shape;observed=np.ones((h,w),bool)if observed is None else observed;gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY)
bg=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(19,19)))
hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
paint=paint_mask(rgb,channel='white',observed=observed)if paint_override is None else paint_override
target=shapely.contains_xy(polygon,points[:,0],points[:,1]).reshape(h,w)
near=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))>0
wide=cv2.dilate(target.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))>0
region=shapely.contains_xy(polygon.convex_hull.buffer(.15),points[:,0],points[:,1]).reshape(h,w)
negative=region&~wide
result=dict(valid=float(allowed[region&observed].mean())if (region&observed).any()else 0.,
support=float(near[target&observed].mean())if (target&observed).any()else 0.,
recall=float(wide[paint&region&allowed].mean())if (paint&region&allowed).any()else 0.,
negative_paint=float(paint[negative&allowed].mean())if (negative&allowed).any()else 1.)
# A complete template must explain the connected paint object, not just
# one head cut out of a longer curved arrow. Unfinished image edges veto it.
connectivity=paint.astype('uint8')
if connectivity_open_m>0:
k=max(3,int(round(connectivity_open_m/cell))//2*2+1)
connectivity=cv2.morphologyEx(connectivity,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k,k)))
count,components=cv2.connectedComponents(connectivity,8)
touching=set(np.unique(components[target&near]))-{0}
connected=np.isin(components,list(touching))&observed
result['connected_recall']=float(wide[connected].mean())if connected.any()else 0.
result['connected_at_window_edge']=bool(connected[0].any()or connected[-1].any()or connected[:,0].any()or connected[:,-1].any())
if kind is not None and parameters is not None:
px,py,a,L,W,stroke=parameters;u=np.array([np.cos(a),np.sin(a)]);n=np.array([-u[1],u[0]]);local=points-[px,py];t=(local@u).reshape(h,w);side=(local@n).reshape(h,w)
regions=[('head',t>L*.80),('tail',t<L*.25)]
if kind.startswith('straight_')and kind!='straight_arrow':regions.append(('branch',side*(1 if 'left'in kind else -1)>W*.24))
result['parts']=[]
for name,where in regions:
select=target&where;coverage=float(observed[select].mean())if select.any()else 0.;select=select&observed
result['parts'].append(dict(part=name,coverage=coverage,valid=float(allowed[select].mean())if select.any()else 0.,support=float(near[select].mean())if select.any()else 0.))
result['ends']=[]
for name,interior,exterior in [('tail',t<L*.20,(t<-POLICY['glyph_end_probe_start_m'])&(t>-POLICY['glyph_end_probe_stop_m'])),('head',t>L*.90,(t>L+POLICY['glyph_end_probe_start_m'])&(t<L+POLICY['glyph_end_probe_stop_m']))]:
observed_side=side[target&interior]
offset=float(np.median(observed_side))if len(observed_side)else 0.
select=exterior&(abs(side-offset)<max(.12,stroke*.6));coverage=float(observed[select].mean())if select.any()else 0.;select=select&observed
result['ends'].append(dict(end=name,coverage=coverage,valid=float(allowed[select].mean())if select.any()else 0.,paint_fraction=float(paint[select].mean())if select.any()else 1.))
return result
def directional_score(rgb,allowed,points,polygon,cell=.04,kind=None,parameters=None,observed=None,paint_override=None,connectivity_open_m=0.):
result=glyph_score(rgb,allowed,points,polygon,cell,kind,parameters,observed,paint_override,connectivity_open_m)
if kind!='straight_arrow' or parameters is None:return result
# A reversed template on a detached triangular head can have good positive
# overlap and clear axial end probes. Its tip flanks still contain broad paint.
h,w=allowed.shape;observed=np.ones((h,w),bool)if observed is None else observed;gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
bg=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(19,19)))
paint=paint_mask(rgb,channel='white',observed=observed)if paint_override is None else paint_override
target=shapely.contains_xy(polygon,points[:,0],points[:,1]).reshape(h,w)
wide=cv2.dilate(target.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))>0
px,py,a,L,W,stroke=parameters;u=np.array([np.cos(a),np.sin(a)]);n=np.array([-u[1],u[0]]);local=points-[px,py];t=(local@u).reshape(h,w);side=(local@n).reshape(h,w)
flank=(t>L*.80)&(t<L*1.05)&(abs(side)<W*.55)&~wide&allowed&observed
result['head_flank_paint']=float(paint[flank].mean())if flank.any()else 1.
return result
base_score=glyph_score
@@ -0,0 +1,40 @@
from paint_channels import paint_mask
from component_surface import planar_vehicle_clearance
"""Two geometry-selected image mosaics for every point of a finite object.
No demand that both complete camera rectangles contain a long polygon's bbox.
Unknown paint pixels remain unknown; different ranks never use the same tile.
"""
import numpy as np,cv2,shapely
from fit_scene import project
from layer_common import sample
from row_evidence import choose_owners
from component_evidence import directional_score as glyph_score
def mosaic_views(p,views,kind=None,parameters=None,allow_pedestrian=False,calibrate_ground=False,connectivity_open_m=0.):
lo=np.asarray(p.bounds[:2])-1.;hi=np.asarray(p.bounds[2:])+1.;cell=.04
xx=np.arange(lo[0],hi[0],cell);yy=np.arange(lo[1],hi[1],cell);x,y=np.meshgrid(xx,yy);points=np.c_[x.ravel(),y.ravel()]
distance=np.linalg.norm(points[:,None,:]-views.centers[None,:,:],axis=2);coverage=np.zeros(distance.shape,bool)
for i,tile in enumerate(views.tiles):
uv=project(points,views.geometry(tile['id']));coverage[:,i]=(uv.min(1)>=20)&(uv.max(1)<1180)
planar=planar_vehicle_clearance(points,views)if allow_pedestrian else np.zeros(len(points),bool)
owners=choose_owners(distance,coverage);ev=[];names=set();target=shapely.contains_xy(p,points[:,0],points[:,1])
for rank in [0,1]:
colors=np.zeros((len(points),3),'uint8');allowed=np.zeros(len(points),bool);covered=np.zeros(len(points),bool);source_counts={};alpha_good=np.zeros(len(points),bool);vehicle_good=alpha_good.copy();surface_good=alpha_good.copy()
for i in np.unique(owners[:,rank]):
if i<0:continue
select=np.flatnonzero(owners[:,rank]==i);name=views.tiles[i]['id'];g=views.geometry(name);rgb,vehicle=views.inputs(name);uv=project(points[select],g).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5
def read(a,q):return np.concatenate([cv2.remap(a,b[:,0,None],b[:,1,None],cv2.INTER_LINEAR).reshape(len(b),-1)for b in np.array_split(q,max(1,int(np.ceil(len(q)/20000))))])
colors[select]=read(rgb,native);allowed[select]=(read(g['alpha'].astype('float32'),uv).ravel()>=.65)&((read(vehicle,uv).ravel()<.2)|planar[select])&(np.isin(sample(views.labels,points[select],views.low,views.high),[1,2]if allow_pedestrian else[1]));covered[select]=True;alpha_good[select]=read(g['alpha'].astype('float32'),uv).ravel()>=.65;vehicle_good[select]=read(vehicle,uv).ravel()<.2;surface_good[select]=np.isin(sample(views.labels,points[select],views.low,views.high),[1,2]if allow_pedestrian else[1])
if target[select].any():names.add(name);source_counts[name]=int(target[select].sum())
rgb=colors.reshape(len(yy),len(xx),3)
paint=paint_mask(rgb,channel='white',observed=covered.reshape(len(yy),len(xx)),calibration=allowed.reshape(len(yy),len(xx))if calibrate_ground else None)
score=glyph_score(rgb,allowed.reshape(len(yy),len(xx)),points,p,kind=kind,parameters=parameters,observed=covered.reshape(len(yy),len(xx)),paint_override=paint,connectivity_open_m=connectivity_open_m)
rgb=colors.reshape(len(yy),len(xx),3);gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
bg=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(19,19)))
near=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))).ravel()>0
known=target&allowed&covered
score['observed_support']=float(near[known].mean())if known.any()else 0.
score.update(paint_valid=float(allowed[target].mean())if target.any()else 0.,paint_coverage=float(covered[target].mean())if target.any()else 0.,source_counts=source_counts,ownership='nearest-covering-geometry-per-pixel',rank=rank)
score['planar_vehicle_override']=float((planar&~vehicle_good)[target].mean())if target.any()else 0.;score['surface_checks']={key:float(a[target].mean())if target.any()else 0. for key,a in [('alpha',alpha_good),('vehicle',vehicle_good),('paved',surface_good)]};ev.append(score)
return ev,sorted(names)
@@ -0,0 +1,29 @@
from discovery_rules import glyph_pass
VERSION='whole-symbol-components-v8'
POLICY=dict(bicycle_semantic_score=.30,arrow_semantic_score=.50,min_semantic_fraction=.55,
bicycle_fit_score=.80,arrow_fit_score=.78,min_observed_support=.90,min_recall=.85,
min_valid=.97,max_negative_paint=.12,max_head_flank_paint=.10,
max_fragment_gap_m=.18,semantic_join_gap_m=.35,point_cloud_input=False,paint_threshold="observed-local-otsu-contrast",proposal_windows_m=[.72,3.0],paint_window_m=3.0,zigzag_paint_window_m=.72,bicycle_surface_classes=[1,2],manual_rois=[],vehicle_flatness_tolerance_m=.12,min_connected_recall=.85,compound_support=.80,compound_branch_support=.85,compound_head_support=.85,compound_tail_support=.50)
def accept_symbol(ev,score,containment,fit,kind):
if score<POLICY['bicycle_semantic_score'if kind=='bicycle'else'arrow_semantic_score']:return False
if containment<POLICY['min_semantic_fraction']or fit<POLICY['bicycle_fit_score'if kind=='bicycle'else'arrow_fit_score']:return False
if len(ev)!=2:return False
for rank,e in enumerate(ev):
c=e['paint_coverage']
if rank==0 and c!=1.:return False
if rank==1 and c==0.:continue
compound=kind in ['straight_left_arrow','straight_right_arrow']
if c<=0 or e['paint_valid']/c<POLICY['min_valid']or e['observed_support']<(POLICY['compound_support']if compound else POLICY['min_observed_support'])or e['negative_paint']>POLICY['max_negative_paint']:return False
if rank==0 and e['recall']<POLICY['min_recall']:return False
if c==1. and (e.get('connected_recall',0)<POLICY['min_connected_recall']or e.get('connected_at_window_edge',True)):return False
if kind!='bicycle':
if not e.get('parts')or not e.get('ends'):return False
for p in e['parts']:
if rank==1 and p.get('coverage',1)==0:continue
support=POLICY.get('compound_'+p['part']+'_support',.90)if compound else(.5 if p['part']=='tail'else .9)
if p['valid']<.97 or p['support']<support:return False
for p in e['ends']:
if rank==1 and p.get('coverage',1)==0:continue
if p['valid']<.97 or p['paint_fraction']>.25:return False
if kind=='straight_arrow'and e.get('head_flank_paint',1)>POLICY['max_head_flank_paint']:return False
return True
@@ -0,0 +1,22 @@
"""A 2-D vehicle label cannot veto paint when Gaussian depth proves flatness."""
from pathlib import Path
from functools import lru_cache
import numpy as np,cv2
from fit_scene import project
@lru_cache(maxsize=12)
def ground_geometry(name):
with np.load(Path('/ortho/evidence')/(name+'.ground-dc.geometry.npz'))as z:return dict(z)
def depth_agrees(context_depth,ground_depth,context_alpha,ground_alpha):
return np.isfinite(context_depth)&np.isfinite(ground_depth)&(context_alpha>=.85)&(ground_alpha>=.85)&(abs(context_depth-ground_depth)<=.12)
def planar_vehicle_clearance(points,views):
centers=np.array([np.mean(t['bounds_xy'],axis=0)for t in views.original]);dist=np.linalg.norm(points[:,None,:]-centers[None,:,:],axis=2);eligible=np.zeros(dist.shape,bool)
for i,t in enumerate(views.original):
uv=project(points,views.geometry(t['id']));eligible[:,i]=(uv.min(1)>=20)&(uv.max(1)<1180)
owners=np.argmin(np.where(eligible,dist,np.inf),axis=1);okay=np.zeros(len(points),bool)
for i in np.unique(owners):
ids=np.flatnonzero((owners==i)&eligible[:,i]);name=views.original[i]['id'];a=views.geometry(name);b=ground_geometry(name);uv=project(points[ids],a).astype('float32')
if not len(ids):continue
assert np.allclose(a['view'],b['view'])and np.allclose(a['intrinsics'],b['intrinsics'])
def read(x):return np.concatenate([cv2.remap(x.astype('float32'),q[:,0,None],q[:,1,None],cv2.INTER_LINEAR).ravel()for q in np.array_split(uv,max(1,int(np.ceil(len(uv)/20000))))])
okay[ids]=depth_agrees(read(a['depth']),read(b['depth']),read(a['alpha']),read(b['alpha']))
return okay
@@ -0,0 +1,55 @@
"""Bounded component assembly, using semantic seeds and observed paint only."""
import numpy as np,cv2,shapely
from shapely.geometry import Polygon
from layer_common import parts
from paint_channels import paint_mask
def vector(binary,p):
corners=np.asarray(p['world_corners']);H=cv2.getPerspectiveTransform(np.array([[0,0],[p['width_px'],0],[p['width_px'],p['height_px']],[0,p['height_px']]],'float32'),corners.astype('float32'))
def xy(c):return cv2.perspectiveTransform(c.astype('float32'),H)[:,0]
cc,hier=cv2.findContours(binary.astype('uint8'),cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE);pp=[]
if hier is None:return Polygon()
for i,c in enumerate(cc):
if hier[0,i,3]>=0 or len(c)<3 or cv2.contourArea(c)*p['mpp']**2<.002:continue
holes=[];j=hier[0,i,2]
while j>=0:
if len(cc[j])>=3 and cv2.contourArea(cc[j])*p['mpp']**2>.002:holes.append(xy(cc[j]))
j=hier[0,j,0]
pp.extend(parts(shapely.make_valid(Polygon(xy(c),holes))))
return shapely.union_all(pp)
def _targets(image,p,masks,scores,classes,scale):
gray=cv2.cvtColor(image,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(image,cv2.COLOR_RGB2HSV);radius=int(scale/p['mpp'])//2*2+1
ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(radius,radius)))
yellow=(hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>65)
white=(ridge>12)&(gray>100)&(hsv[:,:,1]<100)&~yellow
components=parts(vector(white,p));result=[]
for ci in [0,1]:
seeds=[dict(region=vector(m,p),score=float(s),masks=[i])for i,(m,s,c)in enumerate(zip(masks,scores,classes))if c==ci and s>=(.30 if ci==0 else .50)]
groups=list(seeds)
for seed in seeds:
nearby=[s for s in seeds if s['region'].distance(seed['region'])<.35]
if len(nearby)>1:groups.append(dict(region=shapely.union_all([s['region']for s in nearby]),score=max(s['score']for s in nearby),masks=sorted({i for s in nearby for i in s['masks']})))
for seed in groups:
region=seed['region'];limit=region.convex_hull.buffer(.45)
# Keep entire connected paint pieces intersecting the semantic seed; do
# not truncate them at a model's arbitrary instance boundary.
selected=[c for c in components if c.intersection(region.buffer(.10)).area>.01 and c.intersection(limit).area/c.area>.80]
if not selected:continue
whole=shapely.union_all(selected)
for _ in range(2):
near=[c for c in components if c.distance(whole)<.18 and c.intersection(limit).area/c.area>.85]
whole=shapely.union_all([whole]+near)
for target in [whole,vector(white & (cv2.dilate(masks[seed['masks'][0]].astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7)))>0),p)]:
if target.is_empty or target.area<.08:continue
if any(ci==r['ci']and target.symmetric_difference(r['target']).area<.02 for r in result):continue
result.append(dict(target=target,ci=ci,**seed))
return result
def targets(image,p,masks,scores,classes):
result=[]
for scale in [.72,3.0]:
for r in _targets(image,p,masks,scores,classes,scale):
if any(r['ci']==s['ci']and r['target'].symmetric_difference(s['target']).area<.02 for s in result):continue
result.append(dict(r,paint_scale_m=scale))
return result
@@ -0,0 +1,16 @@
"""Color-specific admission for finite zigzag sequences, including 3 legs."""
from catalog_rules import accept_zigzag as legacy_accept
POLICY=dict(short_legs=3,max_residual_m=.06,min_proposal_recall=.90,
min_valid=.97,min_support=.98,max_negative=.04,secondary_support=.95)
def accept_zigzag(ev,legs,fit):
mode=legacy_accept(ev,legs,fit)
if mode:return mode
if fit['legs']!=POLICY['short_legs']or fit['fit_residual_m']>POLICY['max_residual_m']or fit['proposal_recall']<POLICY['min_proposal_recall']:return None
if len(legs)!=3:return None
for ee in [ev]+legs:
if len(ee)!=2:return None
a,b=ee
if a['paint_coverage']!=1. or a['paint_valid']<POLICY['min_valid']or a['support']<POLICY['min_support']or a['negative_paint']>POLICY['max_negative']:return None
c=b['paint_coverage']
if c and(b['paint_valid']/c<.95 or b['observed_support']<POLICY['secondary_support']or b['negative_paint']>.12):return None
return 'three-observed-yellow-legs'
@@ -0,0 +1,26 @@
from pathlib import Path
import json,collections
import numpy as np,cv2,shapely
from shapely.geometry import shape
from PIL import Image,ImageDraw,ImageFont
O=Path('/out');I=Path('/symbolplan');font=ImageFont.truetype('/candidate/review-font.ttf',16)
patches={p['id']:p for p in json.loads((I/'symbol-patches.json').read_text())['patches']}
sem=json.loads((I/'symbol-semantics.json').read_text());diag=json.loads((I/'symbol-diagnostics.json').read_text())
baseline=json.loads(Path('/fullplan/full-map.json').read_text());existing=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in baseline['features']if f['properties'].get('subtype')in ['bicycle','straight_arrow','left_arrow','right_arrow','straight_left_arrow','straight_right_arrow']])
selection={r['id'] for r in sem['records']if 0 in r['classes']}
selection.update(d['patch']for d in diag if d.get('fits')and not d.get('covered_by_baseline')and max(x['score']for x in d['fits'])>.78)
panels=[]
for pid in sorted(selection):
p=patches[pid];im=Image.open(I/'symbol-patches'/(pid+'.png')).convert('RGB');rec=next(r for r in sem['records']if r['id']==pid)
frame=Image.new('RGB',(800,450),'white');im.thumbnail((400,400));frame.paste(im,(0,50));overlay=im.copy();d=ImageDraw.Draw(overlay)
corners=np.array(p['world_corners']);H=cv2.getPerspectiveTransform(corners.astype('float32'),np.array([[0,0],[im.width,0],[im.width,im.height],[0,im.height]],'float32'))
for f in baseline['features']:
if f['properties']['class']!='road_marking':continue
for ring in f['geometry']['coordinates']:
xy=cv2.perspectiveTransform(np.array(ring,'float32')[:,:2,None].transpose(0,2,1),H)[:,0];d.line([tuple(x)for x in xy],fill='#f1c300',width=2)
frame.paste(overlay,(400,50));d=ImageDraw.Draw(frame);d.text((4,4),pid+' '+p['source_tile'],font=font,fill='black');d.text((4,26),str([(int(c),round(s,2))for c,s in zip(rec['classes'],rec['scores'])]),font=font,fill='black');panels.append(frame)
for i in range(0,len(panels),8):
group=panels[i:i+8];sheet=Image.new('RGB',(1600,450*((len(group)+1)//2)),'white')
for j,f in enumerate(group):sheet.paste(f,((j%2)*800,(j//2)*450))
sheet.save(O/('diagnostic-%02d.jpg'%(i//8)),quality=94)
print('DIAGNOSTIC PATCHES',len(panels))
@@ -0,0 +1,16 @@
"""Local Otsu contrast threshold in a metric window, OpenCV only."""
import cv2,numpy as np
def paint_mask(rgb,channel='white',cell=.04,observed=None,calibration=None):
if observed is not None and not observed.all():
rgb=rgb.copy();rgb[~observed]=np.median(rgb[observed],axis=0).astype('uint8')if observed.any()else 0
gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV);k=int((.72 if channel=='yellow'else 3.0)/cell)//2*2+1
ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k,k)))
sample=ridge if observed is None else ridge[cv2.erode(observed.astype('uint8'),np.ones((k,k),np.uint8))>0]
# Calibrate on observed ground, never on the fitted symbol or white void.
if calibration is not None:
known=np.asarray(calibration,bool)&(np.ones(gray.shape,bool)if observed is None else observed)
sample=ridge[known]
threshold,_=cv2.threshold(sample,0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)if sample.size else(15.,None)
yellow=(hsv[:,:,0]>10)&(hsv[:,:,0]<38)&(hsv[:,:,1]>35)
color=yellow if channel=='yellow'else((hsv[:,:,1]<100)&~((hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>65)))
return (True if observed is None else observed)&(ridge>max(15.,threshold))&(gray>100)&color
@@ -0,0 +1,57 @@
from pathlib import Path
import json,time,hashlib,os,collections
import numpy as np,cv2,shapely
from shapely.geometry import shape,mapping
from shapely.ops import transform
from PIL import Image
from layer_common import O,S,sample,parts,feature
from search_views import SearchViews
from discovery_rules import uncovered,unpack
from catalog_context import bicycle_context
from component_mosaics import mosaic_views
from component_bicycle import fit_bicycle
from component_arrows import fit_arrows
from component_targets import targets
from component_rules import VERSION,POLICY,accept_symbol
from component_conflicts import symbol_replacements,FRAGMENT_POLICY
sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
start=time.monotonic();cv2.setNumThreads(3);baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());current={f['id']:f for f in old['features']}
I=Path('/symbolplan');patch_file=I/'symbol-patches.json';patch_doc=json.loads(patch_file.read_text());semantic_file=I/'symbol-semantics.json';semantic=json.loads(semantic_file.read_text())
assert semantic['patch_manifest_sha256']==sha(patch_file)
patches={p['id']:p for p in patch_doc['patches']}
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds']
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,labels,low,high,None)
lines=[unpack(r)for r in json.loads(Path('/searchplan/search-proposals.json').read_text())['lines']]
poly=lambda f:shapely.force_2d(shape(f['geometry']))
existing=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking']);transactions=[];diagnostics=[];seen=[]
def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
for rec in semantic['records']:
if not rec['detections']:continue
p=patches[rec['id']];path=I/'symbol-patches'/(p['id']+'.png');assert sha(path)==p['sha256'];image=np.asarray(Image.open(path).convert('RGB'));npz=I/'symbol-masks'/(p['id']+'.npz');assert sha(npz)==rec['sha256']
with np.load(npz)as z:proposals=targets(image,p,z['masks'],z['scores'],z['classes'])
for proposal in proposals:
target=proposal['target'];region=proposal['region'];ci=proposal['ci'];score=proposal['score']
if target.intersection(existing.buffer(.1)).area/target.area>.50:continue
if any(ci==c and target.symmetric_difference(q).area/max(target.area,q.area)<.08 for c,q in seen):continue
seen.append((ci,target));diag=dict(patch=p['id'],masks=proposal['masks'],semantic_score=score,semantic_class=ci,target=mapping(target));diagnostics.append(diag)
fits=fit_bicycle(target,all_hypotheses=True)or[] if ci==0 else fit_arrows(target)
if ci==0:fits=[dict(f,kind='bicycle')for f in fits]
diag['fits']=[{k:v for k,v in f.items()if k!='polygon'}for f in fits];diag['evaluated']=[]
for f in fits:
kind=f['kind'];q=f['polygon'];containment=q.intersection(region.buffer(.20)).area/max(q.area,1e-9)
if f['score']<POLICY['bicycle_fit_score'if ci==0 else'arrow_fit_score']or containment<POLICY['min_semantic_fraction']:continue
context=bicycle_context(q,f['parameters'],lines)
if not context['passed']:continue
ev,names=mosaic_views(q,views,kind=kind if ci!=0 else None,parameters=f['parameters']if ci!=0 else None,allow_pedestrian=ci==0);passed=accept_symbol(ev,score,containment,f['score'],kind)
diag['evaluated'].append(dict(kind=kind,parameters=f['parameters'],evidence=ev,semantic_containment=containment,passed=passed,covered=not uncovered(q,existing)))
if not passed:continue
replacements=symbol_replacements(q,kind,current.values())
if replacements is None:continue
out=feature(lift(q),'road_marking',subtype=kind,method=VERSION,source_tile=p['source_tile'],source_tiles=names,standard_compliance='not_assessed',template_parameters=f['parameters'],template_fit_score=f['score'],semantic_score=score,semantic_patch=p['id'],semantic_masks=proposal['masks'],lane_context=context)
if out['id']in current:continue
for replaced in replacements:del current[replaced['id']]
current[out['id']]=out;existing=shapely.union_all([poly(v)for v in current.values()if v['properties']['class']=='road_marking']);transactions.append(dict(kind='assembled-symbol',source_ids=[v['id']for v in replacements],output_ids=[out['id']],before=replacements,after=[out],bounds_xy=q.bounds,source_tiles=names,evidence=ev,semantic_containment=containment,semantic_score=score,fit_score=f['score'],patch=p['id'],masks=proposal['masks']));print('ADMIT',len(transactions),kind,p['id'],flush=True);break
print('PATCH',p['id'],'CANDIDATES',len(diagnostics),'ADMITTED',len(transactions),flush=True)
result={**old,'features':list(current.values()),'component_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'component-rows.json').write_text(json.dumps(transactions,indent=2));(O/'component-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'crosswalk-standard-check.json').write_bytes(Path('/symbolplan/crosswalk-standard-check.json').read_bytes())
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-start,baseline_sha256=sha(baseline),semantic_sha256=sha(semantic_file),patch_manifest_sha256=sha(patch_file),changed_segments=len(transactions),added_objects=len(transactions),added_subtypes=dict(collections.Counter(t['after'][0]['properties']['subtype']for t in transactions)),removed_fragments=sum(len(t['before'])for t in transactions),fragment_policy=FRAGMENT_POLICY,policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
(O/'component-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
@@ -0,0 +1,55 @@
"""Reconnect color-separated observed pieces; validate every periodic leg."""
from pathlib import Path
import json,hashlib,time,os,collections
import numpy as np,cv2,shapely
from shapely.geometry import shape,LineString,Point
from shapely.ops import transform
from layer_common import O,S,parts,sample,feature
from search_views import SearchViews
from catalog_zigzag import fit_zigzag
from component_zigzag_rules import accept_zigzag,POLICY as ZIGZAG_POLICY
from zigzag_mosaics import mosaic_views
from assembly_zigzag import extend
from assembly_rules import extension_supported
from beta_profiles import describe
from component_rules import VERSION
cv2.setNumThreads(3);start=time.monotonic();old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());current={f['id']:f for f in new['features']};transactions=json.loads((O/'component-rows.json').read_text());diagnostics=[]
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds']
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,labels,low,high,None)
poly=lambda f:shapely.force_2d(shape(f['geometry']))
def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
path=Path('/assemblyplan/assembly-proposals.json');raw=json.loads(path.read_text());components=[shape(x['geometry'])for x in raw['glyphs']];groups=[]
for c in components:
for radius in [.055,.16,.25]:
groups.extend(parts(c.buffer(radius,join_style=2).buffer(-radius,join_style=2)))
seen=[]
for gi,p in enumerate(groups):
fit=fit_zigzag(p)
if fit is None:continue
q=fit['polygon']
# Grow an observed seed before requiring four legs; validate each new leg.
def check_leg(candidate):
d=describe(candidate)
if d is None:return False,[],[]
ends=[Point(d['origin']+sign*d['length']/2*d['axis']).buffer(.20)for sign in [-1,1]]
ee,nn=mosaic_views(candidate,views,negative_context=shapely.union_all([q,candidate]+ends))
return extension_supported(ee),ee,nn
growth=extend(fit['vertices'],fit['width_m'],check_leg)
if growth['legs_added']:
fit['vertices']=growth['vertices'];fit['legs']=len(growth['vertices'])-1;q=LineString(fit['vertices']).buffer(fit['width_m']/2,cap_style=2,join_style=2);fit['polygon']=q
fit['observed_extension']=growth
if any(q.intersection(x).area/min(q.area,x.area)>.85 for x in seen):continue
seen.append(q);ev,names=mosaic_views(q,views);legs=[]
for a,b in zip(fit['vertices'],fit['vertices'][1:]):
ee,nn=mosaic_views(LineString([a,b]).buffer(fit['width_m']/2,cap_style=2),views,negative_context=q);legs.append(ee)
mode=accept_zigzag(ev,legs,fit);diag=dict(group=gi,evidence=ev,leg_evidence=legs,passed=bool(mode),**{k:v for k,v in fit.items()if k!='polygon'});diagnostics.append(diag)
if not mode:continue
# Whole-pattern replacement is allowed only for the same existing zigzag;
# other kinds, including prior reviewed strips, are not edited here.
overlaps=[f for f in current.values()if f['properties']['class']=='road_marking'and poly(f).intersection(q).area>.005]
if any(f['properties'].get('subtype')!='zigzag'for f in overlaps):continue
if overlaps and (any(poly(f).difference(q.buffer(.12)).area/poly(f).area>.10 for f in overlaps)or q.area<1.15*sum(poly(f).area for f in overlaps)):continue
f=feature(lift(q),'road_marking',subtype='zigzag',method=VERSION,source_tile=names[0],source_tiles=names,vertices=fit['vertices'],leg_count=fit['legs'],width_m=fit['width_m'],fit_residual_m=fit['fit_residual_m'],standard_compliance='not_assessed',source_ids=[v['id']for v in overlaps])
for v in overlaps:del current[v['id']]
current[f['id']]=f;transactions.append(dict(kind='assembled-zigzag',source_ids=[v['id']for v in overlaps],output_ids=[f['id']],before=overlaps,after=[f],bounds_xy=q.bounds,source_tiles=names,evidence=dict(whole=ev,legs=legs),fit=diag));print('ADMIT ZIGZAG',gi,fit['legs'],flush=True)
new['features']=list(current.values());(O/'full-map.json').write_text(json.dumps(new,allow_nan=False));(O/'component-rows.json').write_text(json.dumps(transactions,indent=2));(O/'zigzag-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));report=json.loads((O/'component-report.json').read_text());report.update(changed_segments=len(transactions),added_objects=sum(not t['before']for t in transactions),added_subtypes=dict(collections.Counter(t['after'][0]['properties']['subtype']for t in transactions if not t['before'])),zigzag_proposals_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),zigzag_seconds=time.monotonic()-start,zigzag_policy=ZIGZAG_POLICY,reconstructed_subtypes=dict(collections.Counter(t['after'][0]['properties']['subtype']for t in transactions)),replaced_fragments=sum(len(t['before'])for t in transactions));(O/'component-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report))
@@ -0,0 +1,33 @@
from pathlib import Path
import os,json,shutil
from datetime import datetime,timezone
import numpy as np,shapely
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape
from layer_common import O,S
from search_views import SearchViews
from fit_scene import project
old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'component-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23)
for p in O.glob('component-*.jpg'):
h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name)
def draw(im,g,features):
im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200
for f in features:
if f['properties'].get('class')!='road_marking':continue
for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2)))
return im
views=SearchViews(tiles,None,None,None,None);tiles=views.tiles
frames=[];manifest=[];loaded={}
for gi,rec in enumerate(groups):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id']
if name not in loaded:
g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))}
g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]):
frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640')
fn='component-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects']))
for start in range(0,len(frames),4):
part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white')
for k,im in enumerate(part):sheet.paste(im,(0,k*655))
sheet.save(O/('component-proof-%03d.jpg'%(start//4+1)),quality=94)
(O/'component-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True)
@@ -0,0 +1,43 @@
from pathlib import Path
import json,shapely
from shapely.affinity import rotate,translate
from shapely.geometry import mapping
from fragment_templates import template
from catalog_templates import bicycle
O=Path('/out');debug_groups=[];debug_features=[];seen=set()
for d in json.loads((O/'component-diagnostics.json').read_text()):
if not d['evaluated'] or d['patch']in seen:continue
seen.add(d['patch']);e=d['evaluated'][0];x=e['parameters'];kind=e['kind'];q=bicycle(x)if kind=='bicycle'else translate(rotate(template(kind,*x[3:]),x[2],origin=(0,0),use_radians=True),x[0],x[1]);f=dict(id=d['patch'],properties=dict(**{'class':'road_marking'},subtype=kind),geometry=mapping(q));debug_features.append(f);debug_groups.append(dict(bounds_xy=q.bounds,kind=kind,baseline_objects=0,output_objects=1))
from pathlib import Path
import os,json,shutil
from datetime import datetime,timezone
import numpy as np,shapely
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape
from layer_common import O,S
from search_views import SearchViews
from fit_scene import project
old=json.loads(Path('/fullplan/full-map.json').read_text());new={'features':debug_features};groups=debug_groups;tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23)
for p in O.glob('hypothesis-*.jpg'):
h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name)
def draw(im,g,features):
im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200
for f in features:
if f['properties'].get('class')!='road_marking':continue
for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2)))
return im
views=SearchViews(tiles,None,None,None,None);tiles=views.tiles
frames=[];manifest=[];loaded={}
for gi,rec in enumerate(groups):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id']
if name not in loaded:
g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))}
g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]):
frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640')
fn='hypothesis-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects']))
for start in range(0,len(frames),4):
part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white')
for k,im in enumerate(part):sheet.paste(im,(0,k*655))
sheet.save(O/('hypothesis-proof-%03d.jpg'%(start//4+1)),quality=94)
(O/'hypothesis-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True)
@@ -0,0 +1,77 @@
import json,runpy
import numpy as np,cv2,shapely
from shapely.geometry import Polygon,LineString
from shapely.affinity import rotate,translate
from component_rules import accept_symbol
from component_evidence import directional_score
from component_targets import targets
from component_arrows import fit_arrows
from component_bicycle import fit_bicycle
from paint_channels import paint_mask
from road_glyph_presets import arrow
from catalog_zigzag import fit_zigzag
prior=runpy.run_path('/candidate/test_symbols.py')['result'];checks={}
e=dict(connected_recall=.98,connected_at_window_edge=False,paint_coverage=1.,paint_valid=1.,observed_support=.98,negative_paint=.01,recall=.95)
checks['weak_model_requires_strong_bicycle_shape']=accept_symbol([e,e],.35,.95,.86,'bicycle')and not accept_symbol([e,e],.35,.95,.70,'bicycle')
checks['class_absence_rejected']=not accept_symbol([e,e],.2,.95,.99,'bicycle')
checks['missing_primary_rejected']=not accept_symbol([{**e,'paint_coverage':.5},e],.9,.95,.99,'bicycle')
checks['contradicting_second_view_rejected']=not accept_symbol([e,{**e,'observed_support':.1}],.9,.95,.99,'bicycle')
checks['unknown_surface_rejected']=not accept_symbol([{**e,'paint_valid':.1},e],.9,.95,.99,'bicycle')
checks['noisy_negative_space_rejected']=not accept_symbol([{**e,'negative_paint':.5},e],.9,.95,.99,'bicycle')
checks['foreign_class_seed_rejected']=not accept_symbol([e,e],.9,.2,.99,'bicycle')
cell=.04;x,y=np.meshgrid(np.arange(-1,7,cell),np.arange(-2,2,cell));points=np.c_[x.ravel(),y.ravel()];valid=np.ones(x.shape,bool)
def picture(p):return np.repeat(np.where(shapely.contains_xy(p,points[:,0],points[:,1]).reshape(x.shape),220,65)[:,:,None],3,axis=2).astype('uint8')
p=arrow('straight_arrow',4,1.2,.16);rgb=picture(p);g=directional_score(rgb,valid,points,p,kind='straight_arrow',parameters=[0,0,0,4,1.2,.16]);g.update(paint_coverage=1.,paint_valid=1.,observed_support=g['support'])
checks['whole_arrow_supported']=accept_symbol([g,g],.95,.99,.95,'straight_arrow')
through=rgb.copy();through[abs(y)<.08]=220;bad=directional_score(through,valid,points,p,kind='straight_arrow',parameters=[0,0,0,4,1.2,.16]);bad.update(paint_coverage=1.,paint_valid=1.,observed_support=bad['support'])
checks['continued_stripe_cannot_be_arrow']=not accept_symbol([bad,bad],.99,.99,.99,'straight_arrow')
tri=Polygon([(4,-.6),(4,.6),(6,0)]);reverse=translate(rotate(arrow('straight_arrow',2,1.2,.16),180,origin=(0,0)),6,0);bad=directional_score(picture(tri),valid,points,reverse,kind='straight_arrow',parameters=[6,0,np.pi,2,1.2,.16]);bad.update(paint_coverage=1.,paint_valid=1.,observed_support=bad['support'])
checks['reversed_head_cannot_be_arrow']=not accept_symbol([bad,bad],.99,.99,.99,'straight_arrow')
checks['line_cannot_be_bicycle']=not fit_bicycle(LineString([(0,0),(4,0)]).buffer(.08),all_hypotheses=True)
checks['bent_strip_cannot_be_zigzag']=fit_zigzag(LineString([(0,0),(2,.2),(3,0),(4,.1)]).buffer(.05))is None
checks['one_corner_cannot_be_zigzag']=fit_zigzag(LineString([(0,0),(2,1),(4,0)]).buffer(.06))is None
# A clean complex arrow is recoverable after a rotation and translation, with
# the same fitter and no geographic identity supplied.
q=translate(rotate(arrow('straight_left_arrow',5,1.7,.16),33,origin=(0,0)),12,-7);fits=fit_arrows(q)
checks['rotated_complex_preset_recognized']=bool(fits)and fits[0]['kind']=='straight_left_arrow'and fits[0]['score']>.85
# Color channels must not turn an adjacent pattern into support for a symbol.
yellow=rgb.copy();yellow[(rgb[:,:,0]>200)]=[220,170,30]
checks['white_evidence_excludes_yellow']=paint_mask(yellow,'white').sum()==0
checks['yellow_channel_retains_yellow']=paint_mask(yellow,'yellow').sum()>50
checks['blank_surface_has_no_paint']=not paint_mask(np.full_like(rgb,130)).any()
from component_zigzag_rules import accept_zigzag as accept_short
ze=dict(recall=1.,connected_recall=.98,connected_at_window_edge=False,paint_coverage=1.,paint_valid=1.,support=1.,observed_support=1.,negative_paint=0.)
unknown=dict(recall=0.,paint_coverage=0.,paint_valid=0.,support=0.,observed_support=0.,negative_paint=1.)
zz=dict(legs=3,fit_residual_m=.02,proposal_recall=.96)
checks['three_yellow_legs_with_clear_background'] = bool(accept_short([ze,unknown],[[ze,unknown]]*3,zz))
checks['short_zigzag_missing_leg_rejected'] = not accept_short([ze,unknown],[[ze,unknown]]*2,zz)
checks['short_zigzag_partial_observation_rejected'] = not accept_short([{**ze,'paint_coverage':.9},unknown],[[ze,unknown]]*3,zz)
checks['short_zigzag_noise_rejected'] = not accept_short([{**ze,'negative_paint':.2},unknown],[[ze,unknown]]*3,zz)
checks['short_zigzag_conflicting_view_rejected'] = not accept_short([ze,{**ze,'observed_support':.3}],[[ze,unknown]]*3,zz)
checks['short_zigzag_bad_geometry_rejected'] = not accept_short([ze,unknown],[[ze,unknown]]*3,{**zz,'fit_residual_m':.3})
from component_surface import depth_agrees
checks['flat_vehicle_label_can_be_overridden']=bool(depth_agrees(np.array([10.]),np.array([10.02]),np.array([1.]),np.array([1.]))[0])
checks['raised_vehicle_stays_excluded']=not bool(depth_agrees(np.array([9.]),np.array([10.]),np.array([1.]),np.array([1.]))[0])
checks['unknown_depth_stays_excluded']=not bool(depth_agrees(np.array([float('nan')]),np.array([10.]),np.array([1.]),np.array([1.]))[0])
checks['weak_alpha_cannot_override_vehicle']=not bool(depth_agrees(np.array([10.]),np.array([10.]),np.array([.3]),np.array([1.]))[0])
checks['partial_connected_object_rejected']=not accept_symbol([{**e,'connected_recall':.4},e],.99,.99,.99,'bicycle')
checks['truncated_at_image_edge_rejected']=not accept_symbol([{**e,'connected_at_window_edge':True},e],.99,.99,.99,'bicycle')
# A second complete view can reveal a continuation missing in the first.
checks['second_view_partial_connected_object_rejected']=not accept_symbol([e,{**e,'connected_recall':.6}],.99,.99,.99,'bicycle')
checks['second_view_truncated_object_rejected']=not accept_symbol([g,{**g,'connected_at_window_edge':True}],.99,.99,.99,'straight_arrow')
compound={**g,'parts':[dict(part='head',coverage=1.,valid=1.,support=.87),dict(part='tail',coverage=1.,valid=1.,support=.7),dict(part='branch',coverage=1.,valid=1.,support=.95)]}
checks['worn_compound_head_with_supported_branch']=accept_symbol([compound,compound],.95,.99,.95,'straight_left_arrow')
checks['compound_without_branch_rejected']=not accept_symbol([{**compound,'parts':[dict(part='branch',coverage=1.,valid=1.,support=.2)]},compound],.95,.99,.95,'straight_left_arrow')
from component_conflicts import symbol_replacements
from shapely.geometry import mapping
def fragment(geometry,subtype='linear_marking'):
return dict(id='synthetic',geometry=mapping(geometry),properties=dict(class_name='road_marking',**{'class':'road_marking'},subtype=subtype))
inside=fragment(LineString([(0.5,0),(2.,0)]).buffer(.06))
checks['arrow_owns_contained_stem_fragment']=symbol_replacements(p,'straight_arrow',[inside])==[inside]
checks['arrow_does_not_consume_crossing_line']=symbol_replacements(p,'straight_arrow',[fragment(LineString([(1,-2),(1,2)]).buffer(.06))])is None
checks['arrow_does_not_consume_adjacent_line']=symbol_replacements(p,'straight_arrow',[fragment(LineString([(0,1),(4,1)]).buffer(.06))])==[]
checks['arrow_does_not_consume_another_symbol']=symbol_replacements(p,'straight_arrow',[fragment(p,'straight_arrow')])is None
checks['bicycle_does_not_replace_lane_line']=symbol_replacements(p,'bicycle',[inside])is None
result=dict(passed=all(checks.values())and prior['passed'],checks={k:bool(v)for k,v in checks.items()},prior_checks=len(prior['checks']),prior_passed=prior['passed'])
open('/out/component-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,33 @@
from paint_channels import paint_mask
import numpy as np,cv2,shapely
from discovery_rules import POLICY
def glyph_score(rgb,allowed,points,polygon,cell=.04,kind=None,parameters=None):
"""Check positive paint, unpainted negative space, and unexplained pixels."""
h,w=allowed.shape;gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY)
bg=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(19,19)))
hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
paint=paint_mask(rgb,channel='yellow')
target=shapely.contains_xy(polygon,points[:,0],points[:,1]).reshape(h,w)
near=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))>0
wide=cv2.dilate(target.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))>0
region=shapely.contains_xy(polygon.convex_hull.buffer(.15),points[:,0],points[:,1]).reshape(h,w)
negative=region&~wide
result=dict(valid=float(allowed[region].mean())if region.any()else 0.,
support=float(near[target].mean())if target.any()else 0.,
recall=float(wide[paint&region&allowed].mean())if (paint&region&allowed).any()else 0.,
negative_paint=float(paint[negative&allowed].mean())if (negative&allowed).any()else 1.)
if kind is not None and parameters is not None:
px,py,a,L,W,stroke=parameters;u=np.array([np.cos(a),np.sin(a)]);n=np.array([-u[1],u[0]]);local=points-[px,py];t=(local@u).reshape(h,w);side=(local@n).reshape(h,w)
regions=[('head',t>L*.80),('tail',t<L*.25)]
if kind.startswith('straight_')and kind!='straight_arrow':regions.append(('branch',side*(1 if 'left'in kind else -1)>W*.24))
result['parts']=[]
for name,where in regions:
select=target&where
result['parts'].append(dict(part=name,valid=float(allowed[select].mean())if select.any()else 0.,support=float(near[select].mean())if select.any()else 0.))
result['ends']=[]
for name,interior,exterior in [('tail',t<L*.20,(t<-POLICY['glyph_end_probe_start_m'])&(t>-POLICY['glyph_end_probe_stop_m'])),('head',t>L*.90,(t>L+POLICY['glyph_end_probe_start_m'])&(t<L+POLICY['glyph_end_probe_stop_m']))]:
observed_side=side[target&interior]
offset=float(np.median(observed_side))if len(observed_side)else 0.
select=exterior&(abs(side-offset)<max(.12,stroke*.6))
result['ends'].append(dict(end=name,valid=float(allowed[select].mean())if select.any()else 0.,paint_fraction=float(paint[select].mean())if select.any()else 1.))
return result
@@ -0,0 +1,46 @@
from paint_channels import paint_mask
"""Two geometry-selected image mosaics for every point of a finite object.
No demand that both complete camera rectangles contain a long polygon's bbox.
Unknown paint pixels remain unknown; different ranks never use the same tile.
"""
import numpy as np,cv2,shapely
from fit_scene import project
from layer_common import sample
from row_evidence import choose_owners
from zigzag_evidence import glyph_score
def mosaic_views(p,views,kind=None,parameters=None,negative_context=None):
lo=np.asarray(p.bounds[:2])-1.;hi=np.asarray(p.bounds[2:])+1.;cell=.04
xx=np.arange(lo[0],hi[0],cell);yy=np.arange(lo[1],hi[1],cell);x,y=np.meshgrid(xx,yy);points=np.c_[x.ravel(),y.ravel()]
distance=np.linalg.norm(points[:,None,:]-views.centers[None,:,:],axis=2);coverage=np.zeros(distance.shape,bool)
for i,tile in enumerate(views.tiles):
uv=project(points,views.geometry(tile['id']));coverage[:,i]=(uv.min(1)>=20)&(uv.max(1)<1180)
owners=choose_owners(distance,coverage);ev=[];names=set();target=shapely.contains_xy(p,points[:,0],points[:,1])
for rank in [0,1]:
colors=np.zeros((len(points),3),'uint8');allowed=np.zeros(len(points),bool);covered=np.zeros(len(points),bool);source_counts={}
for i in np.unique(owners[:,rank]):
if i<0:continue
select=np.flatnonzero(owners[:,rank]==i);name=views.tiles[i]['id'];g=views.geometry(name);rgb,vehicle=views.inputs(name);uv=project(points[select],g).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5
def read(a,q):return np.concatenate([cv2.remap(a,b[:,0,None],b[:,1,None],cv2.INTER_LINEAR).reshape(len(b),-1)for b in np.array_split(q,max(1,int(np.ceil(len(q)/20000))))])
colors[select]=read(rgb,native);allowed[select]=(read(g['alpha'].astype('float32'),uv).ravel()>=.65)&(read(vehicle,uv).ravel()<.2)&(sample(views.labels,points[select],views.low,views.high)==1);covered[select]=True
if target[select].any():names.add(name);source_counts[name]=int(target[select].sum())
score=glyph_score(colors.reshape(len(yy),len(xx),3),allowed.reshape(len(yy),len(xx)),points,p,kind=None,parameters=None)
rgb=colors.reshape(len(yy),len(xx),3);gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
bg=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(19,19)))
paint=paint_mask(rgb,channel='yellow')
near=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))).ravel()>0
if negative_context is not None:
# Adjacent legs belong to the same known pattern; they are not
# unexplained paint in this leg's background. The whole pattern
# still receives its original negative-space check.
context=shapely.contains_xy(negative_context.buffer(.08),points[:,0],points[:,1])
region=shapely.contains_xy(p.convex_hull.buffer(.15),points[:,0],points[:,1])
negative=region&~context&allowed&covered
score['negative_paint']=float(paint.ravel()[negative].mean())if negative.any()else 0.
score['negative_space_scope']='exclude-other-legs-of-same-pattern'
known=target&allowed&covered
score['observed_support']=float(near[known].mean())if known.any()else 0.
score.update(paint_valid=float(allowed[target].mean())if target.any()else 0.,paint_coverage=float(covered[target].mean())if target.any()else 0.,source_counts=source_counts,ownership='nearest-covering-geometry-per-pixel',rank=rank)
ev.append(score)
return ev,sorted(names)
@@ -0,0 +1,80 @@
Two-view verification of redundant road-marking vectors
======================================================
Scope
-----
Offline Gaussian-only increment over transitions-pass-20261012. One immutable
source and one policy across Maroseyka, Pokrovka and Smolensk. The code never
branches on scene names, world coordinates, manually chosen regions or IDs.
Worker006 performs all computation, tests and rendering. Mac operations are
limited to orchestration, source/document editing, hashes, copies and viewing.
Reusable components and policy
------------------------------
OpenCV minAreaRect/remap/morphology measure metric image strips; SciPy filtering
and find_peaks/peak_widths resolve paint ridges; Shapely handles overlap. The new
wrapper expresses acceptance and preservation rules, not a map-specific model.
POLICY is saved in each scene report. Parameters have metric or photometric
meaning and are identical for all maps; none are selected from street identity.
Candidate pairs are thin linear-marking polygons with compatible directions
(<=4 degrees), lateral distance <=0.65 m and >=75% longitudinal overlap of the
source. Each candidate is evaluated in two nearest render tiles that fully
cover both polygons with an image margin. Render views share the same Gaussian
reconstruction: agreement is not independent ground-truth evidence.
Valid samples require actual image coverage, top-view alpha >=0.65, road surface,
vehicle score <0.20 and exclusion of protected symbols/crosswalks. Both objects
need >=95% valid samples in both views. The retained stroke needs >=85% bright
support and median local contrast >=22. Unknown or masked pixels cannot justify
removal. Neighboring rows are not duplicates merely because they are close.
Deletion can be justified by:
* >=90% geometric containment in an image-supported keeper;
* <=15% bright support and source contrast q75 <8, beside a supported keeper;
* one common physical paint ridge represented by two vectors. The keeper must
be <=8 cm from the ridge, the rejected vector >=10 cm away and at least 6 cm
farther from it. Both views must agree on the ridge within 5 cm.
For every reason, an observed second ridge vetoes deletion. Transverse profiles
are inspected both as a median and along individual stations. A second ridge
present at >10% of stations or continuously for >=0.25 m protects intermittent
parallel paint, even if it disappears from the median profile. The transverse
corridor also needs >=95% valid evidence. All these are reconstruction rules,
not GOST application tolerances. Earlier normative dimensional checks remain.
The deterministic selection keeps each named keeper and prevents deletion cycles.
No vector coordinates are moved or newly drawn by this pass; all surviving
features are byte-for-byte identical JSON objects. Each removal records source,
keeper, views, profiles and acceptance metrics. Old anchor/source IDs remain
historical provenance; consumers needing current IDs can resolve the explicit
source_id -> target_id records in consensus-rows.json.
Verification and limits
-----------------------
The controlled suite reuses all preceding 57 checks and adds tests for visible
parallel lines, faint paint, occlusion, missing/disagreeing views, overlap,
perpendicular/distant neighbors, rotation/translation, one blurred ridge,
real double ridges, intermittent short paint and invalid transverse coverage.
Each accepted edit has an exhaustive source/before/after frame. Existing short
punctuation reference frames and whole-map overviews support visual regression
review; unchanged-feature audits cover all unmodified objects.
This pass removes only evidence-confirmed whole-object duplicates. It does not
repair false solid continuations lacking a suitable neighboring keeper, perform
partial duplicate trimming, resolve single-view cases, redraw curved rows or
find missing symbols. Some pairs that look duplicated at overview scale are
actual double paint ridges and intentionally remain. Whole-map recall/precision,
geodetic accuracy and legal marking compliance are not established. Unchanged
scenes are regression controls, not proof of universal performance on all scans.
Replay
------
Pinned image sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0.
4 CPU, 20 GiB RAM, 1 GiB tmpfs, read-only root, no network, 1800s per stage.
Stages: test_consensus, refine_consensus, audit_consensus, render_consensus,
render_plan. Private scene caches, canonical queue and SSH configuration are
required external inputs. Qualified hashes and execution receipts accompany
outputs. bundle.json resolves unchanged canonical modules; review-font.ttf is
separately pinned and omitted from source ZIP. No live deployment, Ops post or
commit. Technical artifacts and intermediate attempts stay in qualification.
@@ -0,0 +1,30 @@
from pathlib import Path
import json,hashlib,numpy as np,shapely
from shapely.geometry import shape
old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/consensus-rows.json').read_text())
removed=set(json.loads(Path('/out/consensus-replacements.json').read_text())['removed_ids']);features={f['id']:f for f in new['features']};checks={}
checks['unique_ids']=len(features)==len(new['features'])
checks['all_surviving_features_identical']=all(features.get(f['id'])==f for f in old['features']if f['id']not in removed)
checks['only_linear_removed']=all(f['properties'].get('subtype')=='linear_marking'for f in old['features']if f['id']in removed)
checks['no_new_or_moved_geometry']=len(features)+len(removed)==len(old['features'])and all(f['id']in {x['id']for x in old['features']}for f in new['features'])
checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features'])
checks['keeper_survives']=all(r['target_id']in features and r['source_id']not in features for r in rows)
checks['each_removal_traced']=removed==set(r['source_id']for r in rows)
checks['two_distinct_views']=all(len(set(r['source_tiles']))>=2 and len(r['views'])>=2 for r in rows)
checks['image_supported_keepers']=all(all(v['source_valid']>=.95 and v['target_valid']>=.95 and v['target_support']>=.85 and v['target_median']>=22 for v in r['views'])for r in rows)
def reason_supported(r):
if r['kind']=='overlapping_duplicate':return r['geometry']['contained_fraction']>=.9
if r['kind']=='unsupported_offset_duplicate':return all(v['source_support']<=.15 and v['source_q75']<8 for v in r['views'])
if r['kind']!='one_ridge_two_vectors':return False
offsets=[]
for x in r['ridges']:
if len(x['peaks'])!=1 or x['valid_fraction']<.95 or x['two_ridge_fraction']>.1 or x['longest_two_ridge_m']>=.25:return False
d=x['peaks'][0]['offset'];offsets.append(d)
if abs(d)<.10 or abs(d-x['target_offset'])>.08 or abs(d)-abs(d-x['target_offset'])<.06:return False
return len(offsets)>=2 and max(offsets)-min(offsets)<=.05
checks['no_observed_second_ridge_removed']=all(all(x['valid_fraction']>=.95 and x['two_ridge_fraction']<=.1 and x['longest_two_ridge_m']<.25 for x in r['ridges'])for r in rows)
checks['each_reason_has_evidence']=all(reason_supported(r)for r in rows)
checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes()
checks['same_policy']=new['consensus_refinement']=='two-view-redundant-paint-v1'
result=dict(passed=all(checks.values()),checks=checks,full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False)
Path('/out/consensus-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,64 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"root": "simulation/urban-plan-research",
"files": {
"audit_consensus.py": "consensus_pass/audit_consensus.py",
"audit_norms.py": "norms_pass/audit_norms.py",
"audit_transitions.py": "transitions_pass/audit_transitions.py",
"consensus_profiles.py": "consensus_pass/consensus_profiles.py",
"fit_scene.py": "full_plan/fit_scene.py",
"gost_catalog.py": "norms_pass/gost_catalog.py",
"image_profiles.py": "lines_pass/image_profiles.py",
"interval_profiles.py": "intervals_pass/interval_profiles.py",
"layer_common.py": "full_plan/layer_common.py",
"line_reconstruction.py": "intervals_pass/line_reconstruction.py",
"norm_profiles.py": "norms_pass/norm_profiles.py",
"refine_consensus.py": "consensus_pass/refine_consensus.py",
"refine_norms.py": "norms_pass/refine_norms.py",
"refine_transitions.py": "transitions_pass/refine_transitions.py",
"render_consensus.py": "consensus_pass/render_consensus.py",
"render_norms.py": "norms_pass/render_norms.py",
"render_plan.py": "continuation_pass/render_plan.py",
"render_transitions.py": "transitions_pass/render_transitions.py",
"test_consensus.py": "consensus_pass/test_consensus.py",
"test_intervals.py": "intervals_pass/test_intervals.py",
"test_lines.py": "lines_pass/test_lines.py",
"test_norms.py": "norms_pass/test_norms.py",
"test_transitions.py": "transitions_pass/test_transitions.py",
"transition_profiles.py": "transitions_pass/transition_profiles.py"
},
"reference_qualification": "consensus-pass-20261012",
"source_snapshot": "430fd320ec10ad4ea212",
"source_sha256": {
"audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2",
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
"audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a",
"consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091",
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
"gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537",
"image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8",
"interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345",
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
"line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738",
"norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7",
"refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36",
"refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5",
"refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b",
"render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682",
"render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d",
"render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064",
"render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d",
"test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7",
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a",
"test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f",
"test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438",
"transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e"
},
"external_review_font": {
"name": "review-font.ttf",
"sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9",
"purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP"
},
"deployment": false
}
@@ -0,0 +1,97 @@
"""Image-supported suppression of redundant thin vector paint objects.
Nearby vectors nominate pairs only. Two render views must independently pass
the same evidence gates; they are views of the same reconstruction, not two
independent measurements of the real road.
"""
import numpy as np
from scipy.signal import find_peaks,peak_widths
from interval_profiles import strip,runs
from line_reconstruction import observation
POLICY=dict(max_angle_deg=4.,max_lateral_m=.65,min_overlap=.75,
min_valid=.95,min_keeper_support=.85,min_keeper_median=22.,
max_ghost_support=.15,max_ghost_q75=8.,min_views=2,
max_keeper_ridge_offset_m=.08,min_source_ridge_offset_m=.10,
min_ridge_offset_advantage_m=.06,max_two_ridge_fraction=.10,
max_two_ridge_run_m=.25,max_view_ridge_disagreement_m=.05)
def pair_geometry(source,target):
a,b=[observation(np.asarray(p.exterior.coords),'vector')for p in [source,target]]
if not (1.45<a['L']<70 and 1.45<b['L']<70 and a['W']<=.6 and b['W']<=.4):return None
if abs(a['axis']@b['axis'])<np.cos(np.deg2rad(POLICY['max_angle_deg'])):return None
u=a['axis'];n=np.array([-u[1],u[0]]);d=b['center']-a['center'];lateral=float(abs(d@n))
if lateral>POLICY['max_lateral_m']:return None
tt=(np.asarray(target.exterior.coords)-a['center'])@u
overlap=max(0.,min(a['L']/2,tt.max())-max(-a['L']/2,tt.min()))/a['L']
if overlap<POLICY['min_overlap']:return None
contained=source.intersection(target).area/max(source.area,1e-9)
return dict(lateral_m=lateral,overlap_fraction=float(overlap),contained_fraction=float(contained))
def shared_ridge(source,target,sampler):
"""Inspect one common transverse profile to distinguish one/two paint ridges."""
a,b=[observation(np.asarray(p.exterior.coords),'vector')for p in [source,target]]
u=a['axis'].astype(float);u/=np.linalg.norm(u);n=np.array([-u[1],u[0]])
tt=(np.asarray(target.exterior.coords)-a['center'])@u
lo=max(-a['L']/2,tt.min())+.15;hi=min(a['L']/2,tt.max())-.15
ts=np.arange(lo,hi,.05);ns=np.arange(-.9,.901,.025)
contrast,allowed=strip(a['center'],u,ts,ns,sampler)
profile=np.median(contrast,axis=0);offset=float((b['center']-a['center'])@n)
corridor=(ns>=min(0,offset)-.12)&(ns<=max(0,offset)+.12)
pk,_=find_peaks(profile,height=18,prominence=max(8.,float(profile.max())*.20),distance=4)
pw=peak_widths(profile,pk,rel_height=.5)[0]*.025
peaks=[dict(offset=float(ns[k]),width=float(w),height=float(profile[k]))for k,w in zip(pk,pw)if corridor[k]and .05<w<.50]
two=[]
for row in contrast:
rr,_=find_peaks(row,height=12,prominence=max(8.,float(row.max())*.18),distance=4)
left=[j for j in rr if abs(ns[j])<=.08]
right=[j for j in rr if abs(ns[j]-offset)<=.08]
two.append(any(i!=j and abs(ns[i]-ns[j])>=.10 for i in left for j in right))
longest=max([(b-a)*.05 for a,b in runs(np.array(two))]or[0.])
return dict(peaks=peaks,target_offset=offset,valid_fraction=float(allowed[:,corridor].mean()),
two_ridge_fraction=float(np.mean(two)),longest_two_ridge_m=longest,
offsets=ns.tolist(),profile=profile.tolist())
def observe_track(poly,sampler):
o=observation(np.asarray(poly.exterior.coords),'vector');u=o['axis'].astype(float);u/=np.linalg.norm(u)
trim=min(.15,o['L']*.08);ts=np.arange(-o['L']/2+trim,o['L']/2-trim,.05);ns=np.arange(-.80,.801,.025)
contrast,allowed=strip(o['center'],u,ts,ns,sampler)
band=abs(ns)<=max(.025,min(.05,o['W']*.25))
signal=np.median(contrast[:,band],axis=1);valid=allowed[:,band].mean(1)>.85
return dict(signal=signal,valid=valid)
def decision(geometry,views,ridges=None):
records=[]
for source,target in views:
s,v=source['signal'],source['valid'];t,w=target['signal'],target['valid']
if not len(s)or not len(t):return None,records
level=float(np.median(t[w]))if w.any()else 0.;cut=max(15.,.35*level)
rec=dict(source_valid=float(v.mean()),target_valid=float(w.mean()),
source_support=float(((s>cut)&v).mean()),target_support=float(((t>cut)&w).mean()),
source_q75=float(np.quantile(s[v],.75))if v.any()else 0.,target_median=level,cut=cut)
records.append(rec)
if len(records)<POLICY['min_views']:return None,records
if any(r['source_valid']<POLICY['min_valid'] or r['target_valid']<POLICY['min_valid']or
r['target_support']<POLICY['min_keeper_support'] or r['target_median']<POLICY['min_keeper_median']for r in records):return None,records
# A real intermittent second row vetoes every suppression reason, including
# containment. A wide old vector must not erase a valid nested narrow row.
if ridges and any(r['valid_fraction']<POLICY['min_valid'] or
r['two_ridge_fraction']>POLICY['max_two_ridge_fraction'] or
r['longest_two_ridge_m']>=POLICY['max_two_ridge_run_m']for r in ridges):return None,records
# Strong containment is a geometric duplicate even if both sample paint.
# The retained full stroke must itself be image-supported in every view.
if geometry['contained_fraction']>=.90:return 'overlapping_duplicate',records
if ridges and len(ridges)>=POLICY['min_views']:
single=all(len(r['peaks'])==1 and r['valid_fraction']>=POLICY['min_valid']and
r['two_ridge_fraction']<=POLICY['max_two_ridge_fraction']and
r['longest_two_ridge_m']<POLICY['max_two_ridge_run_m']for r in ridges)
if single:
offsets=[r['peaks'][0]['offset']for r in ridges]
aligned=all(abs(r['peaks'][0]['offset']-r['target_offset'])<=POLICY['max_keeper_ridge_offset_m']and
abs(r['peaks'][0]['offset'])>=POLICY['min_source_ridge_offset_m']and
abs(r['peaks'][0]['offset'])-abs(r['peaks'][0]['offset']-r['target_offset'])>=POLICY['min_ridge_offset_advantage_m']for r in ridges)
if aligned and max(offsets)-min(offsets)<=POLICY['max_view_ridge_disagreement_m']:
return 'one_ridge_two_vectors',records
if all(r['source_support']<=POLICY['max_ghost_support']and r['source_q75']<POLICY['max_ghost_q75']for r in records):
return 'unsupported_offset_duplicate',records
return None,records
@@ -0,0 +1,70 @@
from pathlib import Path
from functools import lru_cache
import os,json,time,hashlib
import numpy as np,cv2,shapely
from PIL import Image
from shapely.geometry import shape
from layer_common import O,S,sample
from fit_scene import project
from consensus_profiles import POLICY,pair_geometry,observe_track,decision,shared_ridge
cv2.setNumThreads(3);started=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text())
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];low,high=z['bounds']
protected=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'])
@lru_cache(maxsize=4)
def inputs(name):
geom=geometry(name);rgb=np.asarray(Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB'))
with np.load(Path('/ortho/evidence')/(name+'.normal.npz'))as z:vehicle=z['vehicle'].astype('float32')
return geom,rgb,vehicle
@lru_cache(maxsize=90)
def geometry(name):return dict(np.load(S/name/'top.geometry.npz'))
def sampler(name):
def read(points):
geom,rgb,vehicle=inputs(name);uv=project(points,geom).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5;chunks=max(1,int(np.ceil(len(uv)/20000)))
colors=np.concatenate([cv2.remap(rgb,q[:,0,None],q[:,1,None],cv2.INTER_LINEAR).reshape(-1,3)for q in np.array_split(native,chunks)])
veh=np.concatenate([cv2.remap(vehicle,q[:,0,None],q[:,1,None],cv2.INTER_LINEAR).ravel()for q in np.array_split(uv,chunks)])
alpha=np.concatenate([cv2.remap(geom['alpha'].astype('float32'),q[:,0,None],q[:,1,None],cv2.INTER_LINEAR).ravel()for q in np.array_split(uv,chunks)])
valid=(uv[:,0]>=0)&(uv[:,1]>=0)&(uv[:,0]<1199)&(uv[:,1]<1199)
allowed=valid&(alpha>=.65)&(sample(labels,points,low,high)==1)&(veh<.20)&~shapely.contains_xy(protected,points[:,0],points[:,1])
return colors,allowed
return read
linear={f['id']:shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties'].get('subtype')=='linear_marking'and f['geometry']['type']=='Polygon'}
@lru_cache(maxsize=1500)
def observed(fid,name):return observe_track(linear[fid],sampler(name))
pairs=[]
for sid,p in linear.items():
for tid,q in linear.items():
if sid==tid:continue
geom=pair_geometry(p,q)
if geom is not None:pairs.append((sid,tid,geom))
# Nearby pairs share decoded tile images. Stable tie-breaking does not depend
# on street names, route distance or hard-coded coordinates.
pairs.sort(key=lambda x:(tuple(linear[x[0]].centroid.coords[0]),x[0],x[1]))
proposals=[];diagnostics=[]
for k,(sid,tid,geom)in enumerate(pairs):
center=np.array(linear[sid].centroid.coords[0]);ranked=sorted(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center))
names=[];vertices=np.concatenate([np.asarray(linear[fid].exterior.coords)for fid in [sid,tid]])
for tile in ranked:
uv=project(vertices,geometry(tile['id']))
if uv.min()>=20 and uv.max()<1180:names.append(tile['id'])
if len(names)==2:break
views=[(observed(sid,name),observed(tid,name))for name in names]
ridges=[shared_ridge(linear[sid],linear[tid],sampler(name))for name in names]
kind,evidence=decision(geom,views,ridges);rec=dict(source_id=sid,target_id=tid,source_tiles=names,geometry=geom,views=evidence,ridges=ridges,kind=kind)
diagnostics.append(rec)
if kind:proposals.append(rec)
if k%50==0:print('PAIR',k,len(pairs),'CANDIDATES',len(proposals),flush=True)
# Greedy selection keeps every nominated keeper. A keeper can never later be
# removed, which avoids deletion cycles for coincident copies.
removed=set();keepers=set();accepted=[]
for rec in sorted(proposals,key=lambda r:(r['kind']!='unsupported_offset_duplicate',max(v['source_support']for v in r['views']),-min(v['target_support']for v in r['views']),r['source_id'])):
sid,tid=rec['source_id'],rec['target_id']
if sid in removed or sid in keepers or tid in removed:continue
removed.add(sid);keepers.add(tid);p=linear[sid].union(linear[tid]);accepted.append({**rec,'bounds_xy':p.bounds,'source_ids':[sid],'output_ids':[tid],'source_tile':rec['source_tiles'][0]})
result={**old,'features':[f for f in old['features']if f['id']not in removed],'consensus_refinement':'two-view-redundant-paint-v1'}
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'consensus-rows.json').write_text(json.dumps(accepted,indent=2));(O/'consensus-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'consensus-replacements.json').write_text(json.dumps(dict(removed_ids=sorted(removed))))
(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes())
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(accepted),removed_duplicates=len(removed),offset_duplicates=sum(r['kind']=='unsupported_offset_duplicate'for r in accepted),overlapping_duplicates=sum(r['kind']=='overlapping_duplicate'for r in accepted),single_ridge_duplicates=sum(r['kind']=='one_ridge_two_vectors'for r in accepted),candidate_pairs=len(pairs),before_linear_objects=len(linear),after_linear_objects=len(linear)-len(removed),policy=POLICY,policy_version='two-view-redundant-paint-v1',manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
(O/'consensus-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
@@ -0,0 +1,41 @@
from pathlib import Path
import os,json,shutil
from datetime import datetime,timezone
import numpy as np,shapely
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape
from layer_common import O,S
from fit_scene import project
old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'consensus-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23)
for p in O.glob('rows-*.jpg'):
h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name)
def draw(im,g,features):
im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200
for f in features:
if f['properties'].get('subtype')not in ['linear_marking','crosswalk']:continue
for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2)))
return im
frames=[];manifest=[];loaded={}
for gi,rec in enumerate(groups):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id']
if name not in loaded:
g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))}
g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]):
frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640')
fn='rows-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects']))
for start in range(0,len(frames),4):
part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white')
for k,im in enumerate(part):sheet.paste(im,(0,k*655))
sheet.save(O/('rows-proof-%03d.jpg'%(start//4+1)),quality=94)
(O/'rows-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True)
# Revisit every short-dash family shown in the prior delivery, using its stored
# bounds only for review framing; these bounds never enter the detector.
references=json.loads(Path('/families/line-families.json').read_text());ref_manifest=[]
for gi,rec in enumerate(references):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200
uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*8/60,raw.width*18/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(2400,855),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(draw(raw,g,old['features']),'До'),(draw(raw,g,new['features']),'После')]):
frame.paste(im.crop(bbox).resize((800,800),Image.Resampling.LANCZOS),(800*j,55));d.text((800*j+10,12),label,font=font,fill='#263640')
fn='reference-%02d.jpg'%gi;frame.save(O/fn,quality=96);ref_manifest.append(dict(group=gi,file=fn,source_tile=name,bounds_source='prior line-families.json; review framing only'))
(O/'reference-visual-manifest.json').write_text(json.dumps(ref_manifest,indent=2))
@@ -0,0 +1,54 @@
import json,runpy,numpy as np
from consensus_profiles import pair_geometry,observe_track,decision,shared_ridge
from interval_profiles import rectangle
from shapely.geometry import Polygon
prior=runpy.run_path('/candidate/test_transitions.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()}
def obs(signal=80.,valid=True):return dict(signal=np.full(80,signal),valid=np.full(80,valid))
g=dict(contained_fraction=0.,overlap_fraction=1.,lateral_m=.3)
checks['ghost_requires_supported_keeper']=decision(g,[(obs(0),obs())]*2)[0]=='unsupported_offset_duplicate'
checks['true_parallel_pair_retained']=decision(g,[(obs(),obs())]*2)[0]is None
checks['worn_parallel_paint_retained']=decision(g,[(obs(12),obs())]*2)[0]is None
checks['occluded_source_retained']=decision(g,[(obs(0,False),obs())]*2)[0]is None
checks['occluded_keeper_no_deletion']=decision(g,[(obs(0),obs(80,False))]*2)[0]is None
checks['disagreeing_views_no_deletion']=decision(g,[(obs(0),obs()),(obs(),obs())])[0]is None
checks['missing_second_view_no_deletion']=decision(g,[(obs(0),obs())])[0]is None
checks['blank_pair_retained']=decision(g,[(obs(0),obs(0))]*2)[0]is None
checks['overlapping_copies_resolved']=decision({**g,'contained_fraction':.97},[(obs(),obs())]*2)[0]=='overlapping_duplicate'
checks['overlap_alone_not_evidence']=decision({**g,'contained_fraction':.97},[(obs(0),obs(0))]*2)[0]is None
o=np.array([0.,0.]);u=np.array([1.,0.]);a=rectangle(o,u,0,6,.15,.35);b=rectangle(o,u,0,6,.15)
checks['parallel_geometry_candidate']=pair_geometry(a,b)is not None
checks['perpendicular_not_duplicate']=pair_geometry(a,rectangle(o,np.array([0.,1.]),0,6,.15))is None
checks['neighbor_lane_not_duplicate']=pair_geometry(a,rectangle(o,u,0,6,.15,3.5))is None
checks['short_overlap_not_duplicate']=pair_geometry(a,rectangle(o,u,5,11,.15))is None
def sampler(xy):
paint=(abs(xy[:,1])<.075)&(xy[:,0]>-.1)&(xy[:,0]<6.1)
return np.repeat(np.where(paint,210,65)[:,None],3,1).astype('uint8'),np.ones(len(xy),bool)
s,t=observe_track(a,sampler),observe_track(b,sampler);reason,_=decision(pair_geometry(a,b),[(s,t)]*2)
checks['image_profile_rejects_offset_ghost']=reason=='unsupported_offset_duplicate'
theta=.87;rot=np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]]);shift=np.array([125.,-71.]);ar=Polygon(np.asarray(a.exterior.coords)@rot.T+shift);br=Polygon(np.asarray(b.exterior.coords)@rot.T+shift)
read=lambda xy:sampler((xy-shift)@rot);sr,tr=observe_track(ar,read),observe_track(br,read)
checks['rigid_transform_invariance']=decision(pair_geometry(ar,br),[(sr,tr)]*2)[0]==reason
def blurred_sampler(xy):
value=65+140*np.exp(-.5*(xy[:,1]/.085)**2)
return np.repeat(value[:,None],3,1).astype('uint8'),np.ones(len(xy),bool)
a=rectangle(o,u,0,6,.15,.15);b=rectangle(o,u,0,6,.15)
s,t=observe_track(a,blurred_sampler),observe_track(b,blurred_sampler);ridge=shared_ridge(a,b,blurred_sampler)
checks['one_blurred_ridge_not_two_lines']=decision(pair_geometry(a,b),[(s,t)]*2,[ridge]*2)[0]=='one_ridge_two_vectors'
def dual_sampler(xy):
value=65+130*np.exp(-.5*(xy[:,1]/.028)**2)+110*np.exp(-.5*((xy[:,1]-.20)/.028)**2)
return np.repeat(value[:,None],3,1).astype('uint8'),np.ones(len(xy),bool)
a=rectangle(o,u,0,6,.10,.20);b=rectangle(o,u,0,6,.10)
s,t=observe_track(a,dual_sampler),observe_track(b,dual_sampler);ridge=shared_ridge(a,b,dual_sampler)
checks['two_physical_ridges_preserved']=decision(pair_geometry(a,b),[(s,t)]*2,[ridge]*2)[0]is None
checks['transverse_profile_resolves_two_ridges']=len(ridge['peaks'])==2
# Intermittent neighbor paint must survive even if it vanishes in the median.
def intermittent(xy):
value=65+130*np.exp(-.5*(xy[:,1]/.028)**2)+110*np.exp(-.5*((xy[:,1]-.20)/.028)**2)*((xy[:,0]%1.5)<.4)
return np.repeat(value[:,None],3,1).astype('uint8'),np.ones(len(xy),bool)
s,t=observe_track(a,intermittent),observe_track(b,intermittent);ridge=shared_ridge(a,b,intermittent)
checks['intermittent_second_ridge_preserved']=decision(pair_geometry(a,b),[(s,t)]*2,[ridge]*2)[0]is None
checks['short_parallel_runs_detected']=ridge['longest_two_ridge_m']>=.25
checks['real_second_ridge_vetoes_containment']=decision({**g,'contained_fraction':.97},[(obs(),obs())]*2,[ridge]*2)[0]is None
invalid={**ridge,'valid_fraction':.4,'two_ridge_fraction':0.,'longest_two_ridge_m':0.}
checks['unknown_transverse_corridor_preserved']=decision({**g,'contained_fraction':.97},[(obs(),obs())]*2,[invalid]*2)[0]is None
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/consensus-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,108 @@
Urban infrastructure continuation pass — offline research
=========================================================
This increment consumes the Gaussian-only v8 seed stage and the four-layer
Gaussian evidence bundle. It is a reusable downstream stage; it does not replace
or re-train the upstream Gaussian renderer, SAM3 paint proposals, Mapillary class
fusion or covariance-based first-floor facade observations.
Uniform pipeline
----------------
1. Retain v8 object chains. Propose bounded line/arc simplification with a 0.45 m
maximum change from the seed, not a ground-truth accuracy claim.
2. Generate endpoint and trimmed-terminal alternatives. SciPy Hermite splines
interpolate candidate curves; HiGHS selects mutually exclusive continuations.
Explicit survey exits and known openings remain open. Scan support, road caps,
opposite surface sides, intersections and inferred loops are guarded.
A locally visible, unoccluded transport corridor vetoes a proposed cap even
when it occupies a small fraction of a long connection. Vehicle occlusion
is treated separately from observed open road. A 0.7 m morphological closing
removes sub-metre semantic pinholes for this veto only; it never draws curves.
3. Re-anchor the neighborhoods of selected connections. The existing normal-strip
dynamic program and weighted minimum-curvature fit use Gaussian appearance,
height, opacity, vehicle occlusion and sidewalk-side context. Missing evidence
receives zero observation weight. Other chain sections and scan terminals
remain fixed before the bounded final primitive fit.
Exterior road support is required for new curb anchors; a sidewalk/building
interface cannot attract a road curb.
Each automatic gap neighbourhood is admitted independently, even where
neighbourhoods overlap. A correction must improve its own evidence. Under
substantial vehicle occlusion it must not introduce extra curb turning.
Rejected corrections retain the joined parent geometry. Accepted corrections
fade over 3 m at their boundaries to avoid a seam with unchanged neighbours.
4. Diagnostic experiment only (not included in the selected result): propose
missing interfaces from one-sided observed sidewalk support. Exclude
measured facades, terrain, existing edges and crossing geometry. These carry
inferred-road-adjacency status and are not ground-truth road classifications. Cross-scene review found false plaza edges;
the same global decision excludes this addition on every scene.
5. Join measured frontage planes using OpenCV Huber fits, bounded gap/offset and
a veto for connecting through observed road surfaces. Short vertical planes
substantially supported by vehicle masks are rejected with their source IDs.
Hidden backs remain
unknown; the result is frontage lines, not closed building footprints.
6. Extract appearance components from native Gaussian ground renders. Semantic
proposals nominate objects, then whole components are tested. Counter topology
distinguishes A from arrows; arrow direction is conditioned on nearby road
orientation. OpenCV/SciPy fit reusable attributed SVG arrow presets and an
original parametric A. Unsupported candidates stay in a rejection record.
Object NMS after fitting removes duplicate glyphs from overlapping fragments;
nearby distinct glyphs remain separate.
7. Fit collinear paint as continuous or periodic families with common width and
period. Only bounded interior gaps are filled. Crosswalks and road-domain
checks constrain reconstruction. Previous admitted paint is retained unless
replaced. The pedestrian coverage layer is retained with refreshed curb IDs.
Run contract
------------
All geometry/rendering/tests run in a reserved Worker006 container. Read-only
mounts: /base, /fullplan, /ortho, /survey, /multiview, /input; writable: /out.
The selected road variant is reanchored; recovered.json is rejected diagnostic
output. Run test_refine.py, refine_scene.py, assemble_plan.py, render_scene.py,
render_plan.py and audit_scene.py. The operator qualification harness records
an immutable source snapshot, image digest, timestamps, hashes and cleanup.
There are no scene-specific parameters, processing ROIs, station coordinates or
manual vector patches. Scene names only label the review images.
The flat replay bundle is described by bundle.json. Review-font.ttf is a separate
optional Cyrillic-capable font used only by image rendering. Private scans and
renders are not included in source. No point cloud or collider is used.
Evidence and limits
-------------------
The independent audit checks finite valid XYZ, unique IDs, simple road chains,
road-chain crossings, new inferred intervals on the final geometry, protected open
ends, retained sidewalk coverage, curb references and accounting for every retained/rejected facade parent.
New inferred_spans describe this pass only. Inherited v8 inference and uncertainty
remain in the referenced source IDs and immutable seed/full-plan bundles; the
rest of a line is not certified as wholly observed.
Controlled tests include known occlusions, real openings, sharp/rounded shapes,
rigid-coordinate transfer, repeated paint, symbol ambiguity and physical-edge
re-anchoring. These checks do not establish survey accuracy or detection recall.
Whole-scene before/after images, all surveyed tiles, automatically chosen details,
every accepted road interpolation and every accepted glyph are retained for
visual review. Successful geometry checks alone are not visual acceptance.
The three existing development scenes are regression tests, not a new blind
holdout. A single common policy is an implementation property, not proof of
universal quality on arbitrary future scans.
Known omissions: closed hidden building footprints; complete bicycle/parking
symbol vocabulary; guaranteed recovery of every line or crossing; independent
position-accuracy measurements. Retained pedestrian coverage silhouettes are
not resnapped to the engineering curves. Gaussian covariance candidates may also
include walls/fences rather than independently verified building identities.
No navigation permission or product/live-map publication is assigned.
Artwork attribution
-------------------
road_glyph_presets.py contains adapted arrow artwork by Major Alexey, 2015:
https://commons.wikimedia.org/wiki/File:1.18_Russian_road_marking.svg
License: CC BY-SA 4.0, https://creativecommons.org/licenses/by-sa/4.0/
Changes: SVG curve sampling, coordinate normalization, metric scaling and stroke
fitting. The attribution and share-alike license apply to this arrow artwork;
the normalized geometry and source strings are kept together in that module.
@@ -0,0 +1,157 @@
from pathlib import Path
from collections import Counter
import json,os,time,hashlib
import numpy as np,cv2,shapely
from shapely.geometry import shape,Polygon,LineString,mapping
from shapely.ops import transform
from scipy.ndimage import distance_transform_edt
from layer_common import O,S,B,feature,parts,sample
from fit_scene import world
from plan_primitives import regularize_paint
from frontage_chains import join_planes
from paint_templates import fit_symbol
from crosswalk_family import rectangle_info,joint_rectangles
cv2.setNumThreads(3);start=time.monotonic();old=json.loads(Path('/fullplan/full-map.json').read_text());base=json.loads((O/'whole-map.json').read_text());tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
with np.load('/fullplan/fields.npz')as f:labels=f['labels'];height=f['z'];low,high=f['bounds'];cell=float(f['cell'])
road=labels==1
# Reuse measured pedestrian coverage. Shared curb references are refreshed.
walk=[f for f in old['features']if f['properties']['class']in ['pedestrian_area','pedestrian_boundary']]
for item in walk:
if item['properties']['class']=='pedestrian_area':item['properties']['physical_boundary_ids']=[f['id']for f in base['features']if shape(f['geometry']).distance(shape(item['geometry']))<.6]
def lift(g):
def project(x,y,z=None):return x,y,sample(height,np.c_[x,y],low,high)
return transform(project,g)
allfacades=[f for f in old['features']if f['properties']['class']=='building_facade'];rawfacades=[];rejected_facades=[]
with np.load(O/'occluder-field.npz')as occ:vehicle_field=occ['vehicle']
for item in allfacades:
line=shapely.force_2d(shape(item['geometry']));p=np.array([line.interpolate(t).coords[0]for t in np.linspace(0,line.length,max(3,int(line.length/.2)))])
fraction=float(np.mean(sample(vehicle_field,p,low,high)>.5))
if line.length<12 and fraction>.35:rejected_facades.append(dict(source_id=item['id'],reason='vehicle-supported-vertical-plane',vehicle_fraction=fraction));continue
rawfacades.append(item)
(O/'rejected-facades.json').write_text(json.dumps(rejected_facades,indent=2))
planes=[shapely.force_2d(shape(f['geometry']))for f in rawfacades]
def facade_bridge_allowed(line,sources):
novel=line.difference(shapely.union_all(sources).buffer(.2))
for segment in parts(novel,'LineString'):
if segment.length<.4:continue
p=np.array([segment.interpolate(t).coords[0]for t in np.linspace(0,segment.length,max(3,int(segment.length/.2)))])
if np.mean(sample(labels,p,low,high)==1)>.2:return False
return True
joined=join_planes(planes,offset=.45,gap=8.,bridge_validator=facade_bridge_allowed);facades=[]
for p,ids in joined:
facades.append(feature(lift(LineString(p)),'building_facade',method='huber-frontage-chain-with-bounded-infill',source_ids=[rawfacades[i]['id']for i in ids],closed_footprint=False,hidden_backs_invented=False,schematic_join=True))
# Detect paint in the detailed Gaussian ground image, then fit reusable geometry.
paint_candidates=[];rejected=[];cross_candidates=[]
road_dist=distance_transform_edt(~road)*cell
for tile in tiles:
name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));m=np.load(Path('/fullplan/evidence')/(name+'.npz'));veh=np.load(Path('/ortho/evidence')/(name+'.normal.npz'))['vehicle'];path=Path('/ortho/evidence')/(name+'.ground.png')
from PIL import Image
im=np.asarray(Image.open(path).convert('RGB'));size=im.shape[0];mpp=60/size;small=lambda a:cv2.resize(a.astype('float32'),(size,size),interpolation=cv2.INTER_LINEAR)
marking=small(m['road marking']);cross=small(m['crosswalk']);vehicles=cv2.dilate((small(veh)>.25).astype('uint8'),np.ones((max(3,int(.25/mpp)),)*2,np.uint8))>0
hsv=cv2.cvtColor(im,cv2.COLOR_RGB2HSV);gray=cv2.cvtColor(im,cv2.COLOR_RGB2GRAY);contrast=gray.astype('float32')-cv2.GaussianBlur(gray.astype('float32'),(0,0),.35/mpp)
paint=((hsv[:,:,1]<85)&(gray>115)&(contrast>9))|((hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>55)&(gray>100)&(contrast>5))
yy,xx=np.mgrid[:size,:size];lo,hi=np.asarray(tile['bounds_xy'])
road_patch=cv2.resize(road[max(0,int(round((high[1]-hi[1])/.1))):int(round((high[1]-lo[1])/.1)),max(0,int(round((lo[0]-low[0])/.1))):int(round((hi[0]-low[0])/.1))].astype('uint8'),(size,size),interpolation=cv2.INTER_NEAREST)>0
candidate=paint&road_patch&~vehicles
candidate=cv2.morphologyEx(candidate.astype('uint8'),cv2.MORPH_CLOSE,np.ones((max(3,int(.04/mpp)),)*2,np.uint8))
contours,hier=cv2.findContours(candidate,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
if hier is None:continue
def xy_native(p):return world((np.asarray(p)+.5)*1200/size-.5,g)
for i,c in enumerate(contours):
if hier[0,i,3]>=0 or cv2.contourArea(c)*mpp*mpp<.06:continue
rect=cv2.minAreaRect(c);short,long=sorted(rect[1]);short*=mpp;long*=mpp
if short<.045 or long<.35 or short>5:continue
ring=cv2.approxPolyDP(c,.035/mpp,True)[:,0];holes=[];j=hier[0,i,2]
while j>=0:
if cv2.contourArea(contours[j])*mpp*mpp>.03:holes.append(xy_native(cv2.approxPolyDP(contours[j],.035/mpp,True)[:,0]))
j=hier[0,j,0]
poly=shapely.make_valid(Polygon(xy_native(ring),holes))
if poly.geom_type!='Polygon':continue
coords=np.array(poly.exterior.coords);supported=np.mean(sample(road_dist,coords,low,high)<.75)
if supported<.5:continue
rxy=np.rint(rect[0]).astype(int);rxy=np.clip(rxy,0,size-1);is_cross=cross[rxy[1],rxy[0]]>.3
if is_cross and .18<short<1.2 and 1.0<long<12 and long/short>2 and poly.area/(short*long)>.55:
box=Polygon(xy_native(cv2.boxPoints(rect)));cross_candidates.append((box,dict(source_tile=name,subtype='crosswalk',method='parametric-rectangle')))
else:
x,y,bw,bh=cv2.boundingRect(c);patch=np.zeros((bh,bw),np.uint8);cv2.drawContours(patch,[c-np.array([[[x,y]]])],-1,1,-1)
values=marking[y:y+bh,x:x+bw][patch>0]
paint_candidates.append((poly,dict(source_tile=name,semantic_support=float(np.mean(values)),semantic_peak=float(np.quantile(values,.9)))))
m.close();print('PAINT',name,len(paint_candidates),len(cross_candidates),flush=True)
def dedup(records):
result=[]
for p,props in sorted(records,key=lambda x:-x[0].area):
if any(p.intersection(q).area/min(p.area,q.area)>.5 for q,_ in result):continue
result.append((p,props))
return result
cross_candidates=dedup(cross_candidates);paint_candidates=dedup(paint_candidates);paint=[]
# Group neighboring parallel stripes without fixture coordinates, then run existing joint fit.
obs=[]
for i,(p,props)in enumerate(cross_candidates):
points=np.asarray(p.exterior.coords);box,center,u,v=rectangle_info(points);obs.append(dict(id=str(i),points=points,box=box,center=center,u=u,v=v))
parent=list(range(len(obs)))
def root(i):
while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i]
return i
for i,a in enumerate(obs):
for j,b in enumerate(obs[:i]):
delta=a['center']-b['center']
if abs(a['u']@b['u'])>np.cos(np.deg2rad(12))and abs(delta@a['u'])<1 and abs(delta@a['v'])<2:parent[root(i)]=root(j)
groups={}
for i in range(len(obs)):groups.setdefault(root(i),[]).append(i)
for ids in groups.values():
if len(ids)<3:rejected.extend(dict(kind='crosswalk',reason='insufficient-family-support')for i in ids);continue
fitted,rec=joint_rectangles([obs[i]for i in ids])
if not rec['optimizer_success']or rec['boundary_residual_p95_m']>.15:rejected.append(dict(kind='crosswalk',reason='joint-fit-disagreement',stripes=len(ids)));continue
for f,i in zip(fitted,ids):paint.append(feature(lift(Polygon(f['points'])),'road_marking',**cross_candidates[i][1],family_size=len(ids),fit_p95_m=f['fit_p95_m']))
for p,props in paint_candidates:
if any(p.intersection(q).area>.2*p.area for q,_ in cross_candidates):continue
if props.get('semantic_support',0)<.10 or props.get('semantic_peak',0)<.3:
rejected.append(dict(kind='paint',reason='appearance-without-object-support',geometry=mapping(p),**props));continue
fitted,method=regularize_paint(p)
if method=='parametric-paint-strip':
paint.append(feature(lift(fitted),'road_marking',subtype='linear_marking',method=method,**props));continue
rect=cv2.minAreaRect(np.asarray(p.exterior.coords,np.float32));a,b=sorted(rect[1]);iou=p.area/max(a*b,1e-8)
if a>.045 and a<.5 and b>.5 and b/a>3 and iou>.72 and not p.interiors:
paint.append(feature(lift(Polygon(cv2.boxPoints(rect))),'road_marking',subtype='linear_marking',method='rectangle-template',**props));continue
# Recognize a whole appearance component; model support may cover only part
# of a worn glyph. It must still locate the object, preventing symbols on noise.
if props.get('semantic_support',0)<.14 or props.get('semantic_peak',0)<.35:
rejected.append(dict(kind='symbol',reason='no-object-semantic-support',geometry=mapping(p),**props));continue
center=p.centroid;nearest=min((shapely.force_2d(shape(x['geometry']))for x in base['features']),key=lambda x:x.distance(center))
station=nearest.project(center);head=np.asarray(nearest.interpolate(min(nearest.length,station+5)).coords[0])-np.asarray(nearest.interpolate(max(0,station-5)).coords[0])
f=fit_symbol(p,heading=head if np.linalg.norm(head)>1 else None)
if f is not None:
fitted,iou,kind,recall,params=f
axis=np.array([np.cos(params[2]),np.sin(params[2])]);center=fitted.centroid;aligned=False
for boundary in base['features']:
line=shapely.force_2d(shape(boundary['geometry']))
if line.distance(center)>12:continue
station=line.project(center);a=np.asarray(line.interpolate(max(0,station-3)).coords[0]);b=np.asarray(line.interpolate(min(line.length,station+3)).coords[0]);t=b-a;t/=max(np.linalg.norm(t),1e-8)
if abs(t@axis)>.88:aligned=True;break
if aligned:paint.append(feature(lift(fitted),'road_marking',subtype=kind,method='symbol-template',template_fit_score=iou,fit_recall=recall,template_parameters=params,**props))
else:rejected.append(dict(kind='symbol',reason='incompatible-street-direction',geometry=mapping(p),**props))
else:rejected.append(dict(kind='symbol',reason='no-template-admitted',geometry=mapping(p),**props))
from paint_dedup import deduplicate_glyphs
paint,glyph_dedup_audit=deduplicate_glyphs(paint)
(O/'glyph-dedup.json').write_text(json.dumps(glyph_dedup_audit,allow_nan=False))
# Preserve previous admitted paint if the new appearance pass has no replacement.
oldpaint=[f for f in old['features']if f['properties']['class']=='road_marking']
newpaint=list(paint)
for prior in oldpaint:
p=shape(prior['geometry'])
if not any(p.intersection(shape(f['geometry'])).area/max(min(p.area,shape(f['geometry']).area),1e-8)>.45 for f in paint):newpaint.append(prior)
from paint_families import normalize
crossing_geometry=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in newpaint if f['properties'].get('subtype')=='crosswalk'])
def admit_family(poly):
if poly.intersection(crossing_geometry).area>.04:return False
line=LineString(np.asarray(poly.exterior.coords)[:,:2]);p=np.array([line.interpolate(s).coords[0]for s in np.linspace(0,line.length,max(5,int(line.length/.3)))])
return np.mean(sample(labels,p,low,high)==1)>.8
retained_old_paint=len(newpaint)-len(paint)
newpaint,family_audit=normalize(newpaint,lift,admit_family)
(O/'paint-families.json').write_text(json.dumps(family_audit,allow_nan=False))
result={**base,'schema_version':'missioncore.refined-full-plan-research/v1','features':base['features']+walk+facades+newpaint,'logical_layers':['roads','pedestrian_zones','buildings','road_markings'],'review_status':'unreviewed'}
assert all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in result['features'])
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'unresolved-markings.json').write_text(json.dumps(rejected,allow_nan=False))
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-start,counts=dict(Counter(f['properties']['class']for f in result['features'])),paint_subtypes=dict(Counter(f['properties'].get('subtype')for f in newpaint)),old_counts=dict(Counter(f['properties']['class']for f in old['features'])),new_detected_paint=len(paint),retained_old_paint=retained_old_paint,normalized_paint_count=len(newpaint),facade_parents=len(planes),rejected_vehicle_facades=len(rejected_facades),facade_chains=len(facades),manual_geometry=False,metric_accuracy_measured=False,source_fullplan_sha256=hashlib.sha256(Path('/fullplan/full-map.json').read_bytes()).hexdigest())
(O/'full-plan-report.json').write_text(json.dumps(report,indent=2));print('FULL-PLAN',json.dumps(report),flush=True)
@@ -0,0 +1,49 @@
"""Independent geometry/provenance audit. Not a substitute for labelled truth."""
from pathlib import Path
from collections import Counter
import json,hashlib,numpy as np,shapely
from shapely.geometry import shape,LineString,Point
from scipy.spatial import cKDTree
O=Path('/out')
doc=json.loads((O/'full-map.json').read_text());old=json.loads(Path('/fullplan/full-map.json').read_text())
features=doc['features'];checks={};warnings=[]
checks['unique_feature_ids']=len({f['id']for f in features})==len(features)
checks['finite_valid_3d']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in features)
roads=[f for f in features if f['properties']['class']=='road_boundary'];geom=[shapely.force_2d(shape(f['geometry']))for f in roads]
checks['all_road_chains_simple']=all(g.is_simple for g in geom)
crossings=[[roads[i]['id'],roads[j]['id']]for i,a in enumerate(geom)for j,b in enumerate(geom[:i])if a.crosses(b)]
checks['no_road_chain_crossings']=not crossings
span_lengths=[]
for f,g in zip(roads,geom):
for span in f['properties'].get('inferred_spans',[]):
a,b=span['station_interval_m'];h=LineString(np.array(span['coordinates'])[:,:2])
assert 0<=a<=b<=g.length+1e-5
assert h.difference(g.buffer(.0001)).length<.001
span_lengths.append(b-a)
checks['inferred_spans_on_final_geometry']=True
base=json.loads(Path('/base/whole-map.json').read_text())
protected=[]
for f in base['features']:
if f['properties']['class']!='road_boundary':continue
for key,idx in [('start_reason',0),('end_reason',-1)]:
if f['properties'].get(key)in ['scan-limit','known-opening','survey-exterior']:protected.append(f['geometry']['coordinates'][idx][:2])
endpoints=np.array([p for g in geom for p in [g.coords[0],g.coords[-1]]])
checks['explicit_open_ends_preserved']=not protected or bool(np.max(cKDTree(endpoints).query(protected)[0])<.001)
oldwalk={f['id']:f['geometry']for f in old['features']if f['properties']['class'].startswith('pedestrian_')}
newwalk={f['id']:f['geometry']for f in features if f['properties']['class'].startswith('pedestrian_')}
checks['pedestrian_coverage_retained']=oldwalk==newwalk
roadids={f['id']for f in roads}
checks['pedestrian_curb_references_exist']=all(set(f['properties'].get('physical_boundary_ids',[]))<=roadids for f in features if f['properties']['class']=='pedestrian_area')
facades=[f for f in features if f['properties']['class']=='building_facade']
parents={f['id']for f in old['features']if f['properties']['class']=='building_facade'}
rejected_facades=json.loads((O/'rejected-facades.json').read_text());rejected_ids={r['source_id']for r in rejected_facades}
retained_ids=set(p for f in facades for p in f['properties']['source_ids'])
checks['every_facade_parent_accounted']=retained_ids|rejected_ids==parents and not(retained_ids&rejected_ids)
checks['no_invented_closed_building_backs']=all(f['properties']['closed_footprint']is False for f in facades)
glyphs=[shapely.force_2d(shape(f['geometry'])).convex_hull for f in features if f['properties'].get('method')=='symbol-template']
checks['no_duplicate_fitted_symbols']=not any(a.intersection(b).area/max(a.union(b).area,1e-9)>.6 for i,a in enumerate(glyphs)for b in glyphs[:i])
families=json.loads((O/'paint-families.json').read_text())
stats=dict(road_chains=len(roads),inferred_road_span_m=sum(span_lengths),recovered_interface_chains=sum(f['properties'].get('class_status')=='inferred-road-adjacency'for f in roads),facade_chains=len(facades),facade_parents=len(parents),paint_family_count=len(families),filled_dash_slots=sum(x['added_internal_m_or_slots']for x in families if x['method']=='periodic-dash-family'),filled_continuous_paint_m=sum(x['added_internal_m_or_slots']for x in families if x['method']=='continuous-paint-family'),counts=dict(Counter(f['properties']['class']for f in features)))
report=dict(passed=all(checks.values()),checks=checks,stats=stats,road_crossings=crossings,full_map_sha256=hashlib.sha256((O/'full-map.json').read_bytes()).hexdigest(),accuracy_measured=False,completeness_measured=False,warnings=['Reference scenes are regression cases, not independent unseen acceptance scenes.','Schematic facade lines do not reconstruct unseen building backs.','Object counts are not precision or recall.'])
(O/'geometry-audit.json').write_text(json.dumps(report,indent=2));print(json.dumps(report),flush=True)
assert report['passed'],checks
@@ -0,0 +1,57 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"root": "simulation/urban-plan-research",
"files": {
"assemble_plan.py": "continuation_pass/assemble_plan.py",
"audit_scene.py": "continuation_pass/audit_scene.py",
"boundary_anchors.py": "boundary_anchors.py",
"continuations.py": "continuation_pass/continuations.py",
"crosswalk_family.py": "full_plan/crosswalk_family.py",
"evidence_fields.py": "continuation_pass/evidence_fields.py",
"fit_scene.py": "full_plan/fit_scene.py",
"frontage_chains.py": "continuation_pass/frontage_chains.py",
"layer_common.py": "full_plan/layer_common.py",
"object_solver.py": "continuation_pass/object_solver.py",
"paint_dedup.py": "continuation_pass/paint_dedup.py",
"paint_families.py": "continuation_pass/paint_families.py",
"paint_templates.py": "continuation_pass/paint_templates.py",
"plan_continuity.py": "plan_continuity.py",
"plan_primitives.py": "plan_primitives.py",
"plan_shapes.py": "plan_shapes.py",
"reanchor.py": "continuation_pass/reanchor.py",
"recover_interfaces.py": "continuation_pass/recover_interfaces.py",
"refine_scene.py": "continuation_pass/refine_scene.py",
"render_plan.py": "continuation_pass/render_plan.py",
"render_scene.py": "continuation_pass/render_scene.py",
"road_glyph_presets.py": "continuation_pass/road_glyph_presets.py",
"test_refine.py": "continuation_pass/test_refine.py"
},
"reference_qualification": "continuation-pass-20261012",
"source_sha256": {
"assemble_plan.py": "779623e96ef76e9342bfff4bd65d6c82374a86596fe2d24189545d78d5262da1",
"audit_scene.py": "68606475be2906b0636db510f5016d8e7a2eb2d067d606351e266b98273a77e7",
"boundary_anchors.py": "312a5501efaacc166df291dff6146f71d29a7745c6192db0d06233ed4f11c8de",
"continuations.py": "d4637fc054b8bec765892659a252380abb903bc49c0b829add168babbc42aa7f",
"crosswalk_family.py": "68ee6327a7a24ab74e77bdbbc9c504562f6997cfb7f0e6082095b3e2eb32fc2d",
"evidence_fields.py": "66b5e019e386bcedabf64c62e0346dc7cd181b127d41eebdbfeb63a0e1d8a61e",
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
"frontage_chains.py": "e1be517d92686b36489dd7fe2f2448ad8274a07a1be069d166dd7218d2c9d4ad",
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
"object_solver.py": "b7969ce51887642c844a60e2ffc178a6b7cb0b5aa8d0a286a540e912c1ce197d",
"paint_dedup.py": "eb943e240f3077639f6dc9a4f4fa00646bb4ddf9a0630360516f5880fc8787a1",
"paint_families.py": "71bc387773377b7029acd092bbd7f705e73a61e8d1aa9ae17c10974cd754b16d",
"paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6",
"plan_continuity.py": "f4b2754e84b7d2d9ffe670cc9f069cb3e889061c7dd883bf01def4b921dc24be",
"plan_primitives.py": "7dbf29048a095cc8378e0f07817222b670009bb82018bbaa85f8aa80ab9a67b8",
"plan_shapes.py": "3b7a6b4520e8efc8afbdb44158eb7a74478f9c586dea63fd0af46e50894d6d4f",
"reanchor.py": "0836d631a1b04d2663d7a14bfa5e75bc69d9f737a41764338c4bd9f94ff1b695",
"recover_interfaces.py": "e743844b5f3b4484df2b7f4e244b955c7ecd13d610143c0f694a31419b53ceff",
"refine_scene.py": "d98595a6f4becea37790130498543df862d7369601fcdf440db55f1e24aac946",
"render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064",
"render_scene.py": "c03dd6d2fdcfa0ab4cd71cd4e457531558bae2d4f008e0682e7467e036364c86",
"road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322",
"test_refine.py": "fa5a9470a1782e621b686be34b7c7454503410b97f5584cfa785da8041066b46"
},
"external_review_font": "review-font.ttf (Cyrillic-capable; rendering only)",
"deployment": false
}
@@ -0,0 +1,187 @@
"""Conservative primitive fitting and endpoint-graph completion of accepted seeds.
All distances are metric. SciPy splines/HiGHS and GEOS implement interpolation,
joint endpoint assignment and geometric checks. No scene-specific coordinates.
"""
from dataclasses import dataclass,asdict,replace
import numpy as np,shapely
from shapely.geometry import LineString
from scipy.spatial import cKDTree
from scipy.interpolate import CubicHermiteSpline
from scipy.optimize import milp,Bounds,LinearConstraint
from scipy.sparse import coo_matrix
from object_solver import fit_chain,sample_chain,Policy,stations
@dataclass(frozen=True)
class ContinuationPolicy:
sample_m:float=.4
max_gap_m:float=18.
max_heading_degrees:float=65.
min_support_m:float=2.
fit_max_deviation_m:float=.45
fit_residual_m:float=.24
unresolved_cost:float=2.5
maximum_terminal_revision_m:float=6.
def observed_crossing_length(curve,road_at,alpha_at,vehicle_at,step=.2):
"""Longest unoccluded road strip crossed by a proposed boundary.
An absolute local run matters: a narrow side street must not be diluted by
the length of a much longer proposed bridge. Vehicle occlusion is unknown,
not evidence for an open transport corridor.
"""
p=sample_chain(np.asarray(curve)[:,:2],step)
t=np.gradient(p,axis=0);t/=np.maximum(np.linalg.norm(t,axis=1)[:,None],1e-8)
n=np.c_[-t[:,1],t[:,0]]
exposed=np.ones(len(p),bool)
for offset in [-1.,0.,1.]:
q=p+offset*n
exposed&=(road_at(q)>.65)&(alpha_at(q)>.7)&(vehicle_at(q)<.25)
longest=run=0.
for visible in exposed:
run=run+step if visible else 0.
longest=max(longest,run)
return float(longest)
def regularize(points,policy=ContinuationPolicy()):
raw=np.asarray(points,float);p=sample_chain(raw[:,:2],policy.sample_m)
if len(p)<5 or LineString(p).is_ring:return raw,None
fit=fit_chain(p,np.ones(len(p)),replace(Policy(),residual_scale_m=policy.fit_residual_m,reliable_residual_limit_m=policy.fit_max_deviation_m),complexity_scale=1.3)
if fit is None:return raw,None
q=fit['points'].copy();q[[0,-1]]=raw[[0,-1],:2]
g=LineString(q);old=LineString(raw[:,:2]);deviation=float(shapely.hausdorff_distance(g,old,densify=.2))
if not g.is_simple or deviation>policy.fit_max_deviation_m or g.length>old.length*1.01:return raw,None
# Preserve Z only by the source station; this is schematic XY regularization.
if raw.shape[1]>2:
st=np.array(shapely.line_locate_point(old,shapely.points(q)));old_s=stations(raw[:,:2]);q=np.c_[q,np.interp(st,old_s,raw[:,2])]
return q,dict(primitives=fit['primitives'],maximum_change_m=deviation)
def endpoint_tangents(p,end):
q=sample_chain(np.asarray(p)[::1 if end==0 else -1,:2],.25)
s=stations(q);result=[]
for reach in [1.5,3.,6.]:
sub=q[s<=reach]
if len(sub)<5:continue
origin=sub.mean(0);_,_,v=np.linalg.svd(sub-origin,full_matrices=False);u=v[0]
if u@(sub[0]-sub[-1])<0:u=-u
n=np.array([-u[1],u[0]]);error=float(np.quantile(abs((sub-origin)@n),.9))
if error>.25:continue
if not any(u@x[0]>.995 for x in result):result.append((u,error,reach))
return result
def connect(records,evaluate=None,policy=ContinuationPolicy()):
"""Return joined chains plus all admissible/rejected endpoint alternatives.
evaluate(curve, left_arm, right_arm) provides observation evidence and rejection.
Endpoint membership is globally optimized; no assumed contour walk is used.
"""
ends=[];checks=[];options=[]
for i,r in enumerate(records):
p=np.asarray(r['points'])
if LineString(p[:,:2]).is_ring:continue
for e in [0,1]:
if r.get('reasons',[None,None])[e]in ['scan-limit','known-opening','survey-exterior']:continue
# A seam may end in an erroneous hook. Propose alternatives from
# earlier supported stations, with an explicit cost for removed tail.
s=stations(p[:,:2]);length=s[-1]
for trim in [0.,1.,2.,4.,6.]:
if trim>policy.maximum_terminal_revision_m or length-trim<max(2.,2*trim):continue
if trim==0:sub=p
else:
cut=int(np.argmin(abs(s-(trim if e==0 else length-trim))))
sub=p[cut:]if e==0 else p[:cut+1]
ts=endpoint_tangents(sub,e)
if ts:ends.append(dict(record=i,end=e,slot=2*i+e,point=sub[0 if e==0 else -1],tangents=ts,trim_m=trim,sub=sub))
if not ends:return records,dict(candidates=[],selected=[],reason='no-endpoint-support')
geometries=[LineString(r['points'][:,:2])for r in records]
pairs=sorted(cKDTree([e['point'][:2]for e in ends]).query_pairs(policy.max_gap_m))
for a,b in pairs:
ea,eb=ends[a],ends[b];i,j=ea['record'],eb['record']
if i==j:continue
ra,rb=records[i],records[j]
if ra.get('class')!=rb.get('class'):continue
pa,pb=ea['point'],eb['point'];gap=np.linalg.norm(pb[:2]-pa[:2]);check=dict(source_ids=[ra['id'],rb['id']],ends=[ea['end'],eb['end']],gap_m=float(gap),status='heading')
checks.append(check)
if gap<.03:continue
direction=(pb[:2]-pa[:2])/gap;curve_options=[]
left=ea['sub'][::1 if ea['end']==1 else -1];right=eb['sub'][::1 if eb['end']==0 else -1]
for ta,err_a,reach_a in ea['tangents']:
for tb,err_b,reach_b in eb['tangents']:
cos=np.cos(np.deg2rad(policy.max_heading_degrees))
if ta@direction<cos or -tb@direction<cos or ta@(-tb)<-.2:continue
if len(pa)>2 and abs(pa[2]-pb[2])>.5+.12*gap:continue
for factor in [.35,.7,1.]:
t=np.linspace(0,1,max(5,int(gap/.2)+1))
xy=CubicHermiteSpline([0,1],np.stack([pa[:2],pb[:2]]),np.stack([ta,-tb])*gap*factor)(t)
curve=np.c_[xy,pa[2]+t*(pb[2]-pa[2])]if len(pa)>2 else xy
line=LineString(xy);check['status']='shape'
if not line.is_simple or line.length>gap*1.2:continue
if not LineString(np.vstack([left[:,:2],xy[1:],right[1:,:2]])).is_simple:continue
if any(line.intersects(g)for k,g in enumerate(geometries)if k not in [i,j]):continue
check['status']='evidence'
ev=evaluate(curve,left,right)if evaluate else dict(allowed=True,reward=0.)
if not ev['allowed']:
check['rejection']=ev.get('reason');continue
bend=float(np.sum(np.linalg.norm(np.diff(np.diff(xy,axis=0),axis=0),axis=1)))
cost=gap/policy.max_gap_m+1.3*(2-ta@direction+tb@direction)+.2*bend-.7*ev.get('reward',0.)+.18*(ea['trim_m']+eb['trim_m'])
curve_options.append(dict(a=a,b=b,i=i,j=j,slots=[ea['slot'],eb['slot']],curve=curve,cost=float(cost),gap_m=float(gap),evidence=ev,tangent_reaches=[reach_a,reach_b]))
if not curve_options:continue
# Keep genuinely different geometric options, with the same data objective.
kept=[]
for c in sorted(curve_options,key=lambda x:x['cost']):
if any(LineString(c['curve'][:,:2]).hausdorff_distance(LineString(k['curve'][:,:2]))<.12 for k in kept):continue
kept.append(c)
if len(kept)==3:break
check.update(status='candidate',alternatives=len(kept));options.extend(kept)
if not options:return records,dict(candidates=checks,selected=[],reason='no-admissible-continuation')
rows=[];cols=[];vals=[];lb=[];ub=[]
slots=sorted(set(e['slot']for e in ends))
for slot_index,endpoint in enumerate(slots):
row=len(lb);lb.append(1);ub.append(1)
for k,o in enumerate(options):
if endpoint in o['slots']:rows.append(row);cols.append(k);vals.append(1)
rows.append(row);cols.append(len(options)+slot_index);vals.append(1)
for i,a in enumerate(options):
ga=LineString(a['curve'][:,:2])
for j,b in enumerate(options[:i]):
if set(a['slots'])&set(b['slots']):continue
if ga.intersects(LineString(b['curve'][:,:2])):
row=len(lb);lb.append(-np.inf);ub.append(1);rows.extend([row,row]);cols.extend([i,j]);vals.extend([1,1])
costs=[x['cost']for x in options]+[policy.unresolved_cost]*len(slots)
A=coo_matrix((vals,(rows,cols)),shape=(len(lb),len(costs))).tocsc()
fit=milp(costs,integrality=np.ones(len(costs)),bounds=Bounds(0,1),constraints=LinearConstraint(A,lb,ub),options={'time_limit':30,'mip_rel_gap':.001})
if fit.x is None:raise RuntimeError(fit.message)
chosen=[options[i]for i in np.flatnonzero(fit.x[:len(options)]>.5)]
# No inferred road loop closure. Preserve the lowest cost forest explicitly.
parent=list(range(len(records)));links={};selected=[];cycles=[];trimmed={}
def root(i):
while parent[i]!=i:i=parent[i]
return i
for c in sorted(chosen,key=lambda x:x['cost']):
i,j=c['i'],c['j']
if root(i)==root(j):cycles.append([records[i]['id'],records[j]['id']]);continue
parent[root(i)]=root(j);ea,eb=ends[c['a']],ends[c['b']]
links[i,ea['end']]=(j,eb['end'],c['curve']);links[j,eb['end']]=(i,ea['end'],c['curve'][::-1]);selected.append(c)
trimmed[i,ea['end']]=ea['point'];trimmed[j,eb['end']]=eb['point']
out=[];seen=set();reverted=set()
for seed in range(len(records)):
if seed in seen:continue
members=[i for i in range(len(records))if root(i)==root(seed)]
start=next(((i,e)for i in members for e in [0,1]if(i,e)not in links),None)
if start is None:
out.extend(records[i]for i in members);seen.update(members);continue
i,entry=start;pts=[];source_ids=[];spans=[]
while i not in seen:
seen.add(i);rec=records[i];p=rec['points']
lo=int(np.argmin(np.linalg.norm(p[:,:2]-trimmed[i,0][:2],axis=1)))if(i,0)in trimmed else 0
hi=int(np.argmin(np.linalg.norm(p[:,:2]-trimmed[i,1][:2],axis=1)))if(i,1)in trimmed else len(p)-1
assert lo<hi,(i,lo,hi)
p=p[lo:hi+1][::1 if entry==0 else -1]
pts.extend(p if not pts else p[1:]);source_ids.extend(rec.get('source_ids',[rec['id']]));spans.extend(rec.get('spans',[]))
if(i,1-entry)not in links:break
j,other,curve=links[i,1-entry];spans.append(curve.tolist());pts.extend(curve[1:]);i,entry=j,other
if not LineString(np.asarray(pts)[:,:2]).is_simple:
out.extend(records[j]for j in members);reverted.update(members)
else:out.append(dict(id='joined-'+'-'.join(source_ids),points=np.asarray(pts),source_ids=source_ids,spans=spans,**{'class':records[seed]['class']}))
assert all(LineString(r['points'][:,:2]).is_simple for r in out)
return out,dict(candidates=checks,selected=[dict(source_ids=[records[x['i']]['id'],records[x['j']]['id']],gap_m=x['gap_m'],terminal_revision_m=[ends[x['a']]['trim_m'],ends[x['b']]['trim_m']],coordinates=x['curve'].tolist(),evidence=x['evidence'],cost=x['cost'])for x in selected if x['i']not in reverted and x['j']not in reverted],reverted_parent_ids=[records[i]['id']for i in sorted(reverted)],cycles_rejected=cycles,solver_status=int(fit.status),solver_message=fit.message)
@@ -0,0 +1,39 @@
from pathlib import Path
import json,hashlib,time,os
import numpy as np,cv2
from PIL import Image
from boundary_anchors import PhysicalFields,AnchorPolicy,sample
from object_solver import Policy
cv2.setNumThreads(3);T=time.monotonic();O=Path('/out');B=Path('/base');S=Path('/survey');E=Path('/ortho/evidence')
policy=Policy();cell=.1
def digest(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
inputs={p:digest(p)for p in ['/base/observed-lines-v1/fields.npz','/multiview/mapillary/atlas-sparse.npz','/survey/tile-index.json']}
with np.load(B/'observed-lines-v1/fields.npz')as f:
side=f['side'];road_mask=f['road']>.5;low,high=f['bounds'];h,w=side.shape
with np.load('/multiview/mapillary/atlas-sparse.npz')as f:
assert np.allclose(f['bounds'],[low,high]);assert np.isclose(f['cell_m'],cell)
rows,cols=f['rows'],f['cols'];post=f['posterior'];raw=[]
for i in range(6):
a=np.zeros((h,w),np.float32);a[rows,cols]=post[i].astype('float32');raw.append(a)
del rows,cols,post
road,walk,occ,structure,terrain,other=raw
# Close only sub-metre class-mask pinholes, such as paint and rail artefacts.
# This stable transport support is a topology veto, never generated road geometry.
transport=cv2.morphologyEx((road>.5).astype('uint8'),cv2.MORPH_CLOSE,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7))).astype('float32')
rgb=np.full((h,w,3),255,np.uint8);z=np.full((h,w),np.nan,np.float32);alpha=np.zeros((h,w),np.float32);best=alpha.copy();vehicle=alpha.copy()
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
for tile in tiles:
name=tile['id'];lo,hi=np.asarray(tile['bounds_xy']);tw,th=np.rint((hi-lo)/cell).astype(int)
x,y=np.rint([(lo[0]-low[0])/cell,(high[1]-hi[1])/cell]).astype(int);sl=np.s_[y:y+th,x:x+tw]
small=lambda a:cv2.resize(a.astype('float32'),(tw,th),interpolation=cv2.INTER_AREA)
with np.load(E/(name+'.ground-dc.geometry.npz'))as g:
aa=small(g['alpha']);zz=small(g['view'][2,3]-g['depth'])
with np.load(E/(name+'.normal.npz'))as g:vehicle[sl]=np.maximum(vehicle[sl],small(g['vehicle']))
im=np.asarray(Image.open(E/(name+'.ground.png')).convert('RGB').resize((tw,th),Image.Resampling.LANCZOS))
yy,xx=np.mgrid[:th,:tw];central=np.minimum.reduce([xx+1,yy+1,tw-xx,th-yy]);score=(.05+central/max(tw,th))*aa
take=score>best[sl];rgb[sl][take]=im[take];z[sl][take]=zz[take];alpha[sl][take]=aa[take];best[sl][take]=score[take]
inputs[str(E/(name+'.ground.png'))]=digest(E/(name+'.ground.png'))
inputs[str(E/(name+'.ground-dc.geometry.npz'))]=digest(E/(name+'.ground-dc.geometry.npz'))
inputs[str(E/(name+'.normal.npz'))]=digest(E/(name+'.normal.npz'))
print('OBSERVATIONS',h,w,len(tiles),'seconds',round(time.monotonic()-T,1),flush=True)
fields=PhysicalFields(rgb,z,alpha,np.maximum(vehicle,occ),road,walk,cell,AnchorPolicy())
@@ -0,0 +1,41 @@
"""Joint frontage-plane fitting. No footprint, area fill or hidden building back."""
import numpy as np,cv2
from shapely.geometry import LineString,Point
def join_planes(lines,offset=.3,gap=2.,bridge_validator=None):
records=[(np.asarray(x.coords)[:,:2],[i]) for i,x in enumerate(lines)];changed=True
while changed:
changed=False
for i,(a,ids) in enumerate(records):
u=a[-1]-a[0];u/=np.linalg.norm(u);n=np.array([-u[1],u[0]])
for j in range(i+1,len(records)):
b,jds=records[j];v=b[-1]-b[0];v/=np.linalg.norm(v)
if abs(u@v)<np.cos(np.deg2rad(4)) or abs((b-a[0])@n).max()>offset:continue
tb=(b-a[0])@u;span=max(0,float(tb.min())-np.linalg.norm(a[-1]-a[0]),-float(tb.max()))
if span>gap:continue
samples=[]
for idx in ids+jds:
old=lines[idx];samples.extend([old.interpolate(t).coords[0][:2] for t in np.linspace(0,old.length,max(2,int(old.length/.2)))])
p=np.asarray(samples);fit=cv2.fitLine(p.astype('float32'),cv2.DIST_HUBER,0,.0001,.0001).ravel();axis=fit[:2];o=fit[2:];normal=np.array([-axis[1],axis[0]])
if abs((p-o)@normal).max()>offset:continue
t=(p-o)@axis;q=o+np.array([t.min(),t.max()])[:,None]*axis;l=LineString(q)
if bridge_validator is not None and not bridge_validator(l,[lines[k]for k in ids+jds]):continue
if any(l.crosses(LineString(c)) for k,(c,_) in enumerate(records) if k not in [i,j]):continue
records[i]=(q,ids+jds);records.pop(j);changed=True;break
if changed:break
# Intersect only measured adjacent planes, within a bounded endpoint gap.
for i,(a,ids) in enumerate(records):
for j in range(i+1,len(records)):
b,jds=records[j];u=a[-1]-a[0];v=b[-1]-b[0];u/=np.linalg.norm(u);v/=np.linalg.norm(v)
if abs(u@v)>np.cos(np.deg2rad(25)):continue
distances=np.linalg.norm(a[:,None,:]-b[None,:,:],axis=2);ia,ib=np.unravel_index(np.argmin(distances),distances.shape)
if distances[ia,ib]>.8:continue
coef=np.linalg.solve(np.c_[u,-v],b[ib]-a[ia]);p=a[ia]+coef[0]*u
if np.linalg.norm(p-a[ia])>.7 or np.linalg.norm(p-b[ib])>.7:continue
na=a.copy();nb=b.copy();na[ia]=p;nb[ib]=p
if LineString(na).length<1 or LineString(nb).length<1:continue
la,lb=LineString(na),LineString(nb)
if bridge_validator is not None and (not bridge_validator(la,[lines[k]for k in ids]) or not bridge_validator(lb,[lines[k]for k in jds])):continue
if any(la.crosses(LineString(c))or lb.crosses(LineString(c))for k,(c,_)in enumerate(records)if k not in [i,j]):continue
records[i]=(na,ids);records[j]=(nb,jds);a=na
return records
@@ -0,0 +1,149 @@
"""Evidence-weighted whole-chain shortest path and joint candidate selection.
The order of observations is an input hypothesis, NOT guaranteed topology.
v8 vectors, scene names and operator review coordinates are not inputs.
Uses existing line/arc assembly, SciPy HiGHS and GEOS; no trained model.
"""
from dataclasses import dataclass, asdict
import numpy as np
import cv2
from scipy.optimize import milp, Bounds, LinearConstraint
from scipy.sparse import coo_matrix
from shapely.geometry import LineString
import shapely
from plan_shapes import assemble
@dataclass(frozen=True)
class Policy:
station_m: float = .4
node_spacing_m: float = 1.6
maximum_primitive_m: float = 100.
residual_scale_m: float = .22
line_complexity: float = 1.8
arc_complexity: float = 3.2
reliable_residual_limit_m: float = .65
minimum_observed_m: float = 2.
milp_seconds: float = 30.
def stations(p):
return np.r_[0.,np.cumsum(np.linalg.norm(np.diff(p,axis=0),axis=1))]
def sample_chain(p, step=.4):
p=np.asarray(p,float);s=stations(p);keep=np.r_[True,np.diff(s)>1e-7];p,s=p[keep],s[keep]
if len(p)<2:return p
t=np.linspace(0,s[-1],max(2,int(np.ceil(s[-1]/step))+1))
return np.c_[np.interp(t,s,p[:,0]),np.interp(t,s,p[:,1])]
def fit_line(p,w):
total=w.sum()
if total<1e-8:return None
origin=(p*w[:,None]).sum(0)/total
q=p-origin;cov=(q*w[:,None]).T@q
_,v=np.linalg.eigh(cov);u=v[:,-1]
if u@(p[-1]-p[0])<0:u=-u
n=np.array([-u[1],u[0]]);res=q@n
ends=origin+((p[[0,-1]]-origin)@u)[:,None]*u
return dict(kind='line',origin=origin,axis=u,error=res,ends=ends,p=p[w>.25])
def fit_arc(p,w):
choose=w>.25
if choose.sum()<8:return None
origin=(p*w[:,None]).sum(0)/w.sum();q=p-origin
sw=np.sqrt(w);a=np.c_[2*q,np.ones(len(q))]
c=np.linalg.lstsq(a*sw[:,None],(q*q).sum(1)*sw,rcond=None)[0]
center=c[:2]+origin;r=np.linalg.norm(p-center,axis=1);radius=np.sum(r*w)/w.sum()
if not 1.<radius<100:return None
ang=np.unwrap(np.arctan2(p[:,1]-center[1],p[:,0]-center[0]));sweep=ang[-1]-ang[0]
if not .15<abs(sweep)<np.pi*.95:return None
if np.sum(np.diff(ang)*np.sign(sweep)<-.025)>max(1,len(p)*.05):return None
v=p[[0,-1]]-center;v/=np.maximum(np.linalg.norm(v,axis=1)[:,None],1e-8)
return dict(kind='arc',center=center,radius=radius,error=r-radius,ends=center+radius*v,p=p[choose])
def fit_chain(points,weights,policy=Policy(), complexity_scale=1.):
p=np.asarray(points,float);w=np.clip(np.asarray(weights,float),0,1)
if len(p)!=len(w)or len(p)<3 or not np.isfinite(p).all():raise ValueError('Finite aligned evidence required')
supported=np.flatnonzero(w>.25)
if len(supported)<3:return None
a,b=int(supported[0]),int(supported[-1]);p,w=p[a:b+1],w[a:b+1];s=stations(p)
if w.sum()*policy.station_m<policy.minimum_observed_m:return None
# Graph nodes from uniform stations plus geometry-derived corners, no ROIs.
cuts=np.searchsorted(s,np.arange(0,s[-1],policy.node_spacing_m))
simple=cv2.approxPolyDP(p.astype('float32'),.35,False)[:,0]
corner_indices=[int(np.argmin(np.sum((p-q)**2,axis=1)))for q in simple]
cuts=np.unique(np.r_[0,cuts,corner_indices,len(p)-1]);N=len(cuts)
costs=np.full(N,np.inf);costs[0]=0;back={};models={};edges=0
for j in range(1,N):
for i in range(j-1,-1,-1):
if s[cuts[j]]-s[cuts[i]]>policy.maximum_primitive_m:break
if not np.isfinite(costs[i]):continue
q=p[cuts[i]:cuts[j]+1];ww=w[cuts[i]:cuts[j]+1]
if len(q)<3:continue
line=fit_line(q,ww)
if line is None:continue
options=[line]
if len(q)>=8 and s[cuts[j]]-s[cuts[i]]<40 and np.max(abs(line['error'])*ww)>.1:
arc=fit_arc(q,ww)
if arc is not None:options.append(arc)
for m in options:
e=abs(m['error']);strong=ww>.65
if strong.any() and np.quantile(e[strong],.95)>policy.reliable_residual_limit_m:continue
# Huber data term plus explicit primitive description length.
rr=e/policy.residual_scale_m;rho=np.where(rr<=1,rr**2,2*rr-1)
loss=float(np.sum(ww*rho)*policy.station_m)+(policy.line_complexity if m['kind']=='line' else policy.arc_complexity)*complexity_scale
edges+=1
if costs[i]+loss<costs[j]:
costs[j]=costs[i]+loss;back[j]=i;models[j]=m
if N-1 not in back:return None
chosen=[];j=N-1
while j:
chosen.append(models[j]);j=back[j]
chosen.reverse();curve,primitives=assemble(chosen)
if len(curve)<2 or not LineString(curve).is_simple:return None
geom=LineString(curve)
residual=shapely.distance(shapely.points(p),geom)
strong=w>.65
# Assembly is rechecked; tangent fitting must not invalidate the chosen path.
if strong.any() and np.quantile(residual[strong],.95)>policy.reliable_residual_limit_m:return None
# Alternatives use different search penalties to propose geometry, but must
# be compared under one common objective after line/arc junction assembly.
rr=residual/policy.residual_scale_m
rho=np.where(rr<=1,rr**2,2*rr-1)
common_cost=float(np.sum(w*rho)*policy.station_m)+sum(
policy.line_complexity if m['kind']=='line' else policy.arc_complexity for m in chosen)
return dict(points=curve,primitives=primitives,cost=common_cost,search_cost=float(costs[-1]),trim=[a,b],
evidence_length_m=float(w.sum()*policy.station_m),p95_m=float(np.quantile(residual[strong],.95))if strong.any()else None,
graph_nodes=N,admissible_edges=edges,complexity_scale=complexity_scale)
def select_candidates(groups,policy=Policy()):
"""One alternative or explicit unresolved choice per evidence chain.
Joint geometric exclusion is solved by HiGHS; cannot invent missing options.
"""
options=[];group_ids=[];c=[];geoms=[]
for i,g in enumerate(groups):
for candidate in g:
group_ids.append(i);options.append(candidate);geoms.append(LineString(candidate['points']))
c.append(candidate['cost'])
group_ids.append(i);options.append(None);geoms.append(None)
c.append(max([x['cost']for x in g]+[1.])+max([x.get('evidence_length_m',1)for x in g]+[1.])*4+20)
if not options:return [],dict(conflicts=0,solver_status=0,unresolved=[])
rows=[];cols=[];vals=[];lb=[];ub=[]
for i in range(len(groups)):
row=len(lb);lb.append(1.);ub.append(1.)
for j,gi in enumerate(group_ids):
if gi==i:rows.append(row);cols.append(j);vals.append(1.)
conflicts=[]
for i,a in enumerate(geoms):
if a is None:continue
for j in range(i):
b=geoms[j]
if b is None or group_ids[i]==group_ids[j]:continue
if a.crosses(b) or a.intersection(b).length>.5:
conflicts.append([i,j]);row=len(lb);lb.append(-np.inf);ub.append(1.)
rows.extend([row,row]);cols.extend([i,j]);vals.extend([1.,1.])
A=coo_matrix((vals,(rows,cols)),shape=(len(lb),len(options))).tocsc()
fit=milp(np.asarray(c),integrality=np.ones(len(c)),bounds=Bounds(0,1),constraints=LinearConstraint(A,lb,ub),options={'time_limit':policy.milp_seconds,'mip_rel_gap':.001})
if fit.x is None:raise RuntimeError('No feasible whole-chain selection: '+fit.message)
indices=np.flatnonzero(fit.x>.5);selected=[(group_ids[j],options[j])for j in indices if options[j]is not None]
unresolved=[group_ids[j]for j in indices if options[j]is None]
return selected,dict(conflicts=len(conflicts),solver_status=int(fit.status),solver_message=fit.message,mip_gap=float(fit.mip_gap),unresolved=unresolved,objective=float(fit.fun))
@@ -0,0 +1,15 @@
"""Object NMS after fitting; overlapping tile fragments may fit the same glyph."""
from shapely.geometry import shape
def deduplicate_glyphs(features):
symbols=[f for f in features if f['properties'].get('method')=='symbol-template']
others=[f for f in features if f['properties'].get('method')!='symbol-template']
kept=[];audit=[]
for f in sorted(symbols,key=lambda f:(-f['properties'].get('template_fit_score',0),f['id'])):
footprint=shape(f['geometry']).convex_hull;duplicate=None
for prior,g in kept:
if footprint.intersection(g).area/max(footprint.union(g).area,1e-9)>.6:
duplicate=prior;break
if duplicate is None:kept.append((f,footprint))
else:audit.append(dict(rejected_id=f['id'],kept_id=duplicate['id'],reason='overlapping-fitted-symbol'))
return others+[f for f,_ in kept],audit
@@ -0,0 +1,63 @@
"""Fit collinear paint as line/dash families, keeping the observed extent.
OpenCV robust line fits and median period/width estimates; no site constants.
Only bounded internal slots may be reconstructed, never a new exterior lane.
"""
import numpy as np,cv2,shapely
from shapely.geometry import shape,Polygon,LineString
from layer_common import feature
def normalize(features,lift,admit):
records=[];untouched=[]
for f in features:
g=shapely.force_2d(shape(f['geometry']))
if f['properties'].get('subtype')!='linear_marking' or g.geom_type!='Polygon':untouched.append(f);continue
rect=cv2.minAreaRect(np.asarray(g.exterior.coords,np.float32));box=cv2.boxPoints(rect);edges=np.roll(box,-1,axis=0)-box;k=np.argmax(np.linalg.norm(edges,axis=1));L=np.linalg.norm(edges[k]);W=min(rect[1]);u=edges[k]/L
if not(1.2<L<40 and .06<W<.45 and L/W>7 and g.area/(L*W)>.68):untouched.append(f);continue
records.append(dict(f=f,g=g,center=np.array(rect[0]),axis=u,L=L,W=W))
parent=list(range(len(records)))
def root(i):
while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i]
return i
for i,a in enumerate(records):
u=a['axis'];n=np.array([-u[1],u[0]])
for j,b in enumerate(records[:i]):
delta=b['center']-a['center']
if abs(u@b['axis'])<np.cos(np.deg2rad(3))or abs(delta@n)>.18:continue
gap=abs(delta@u)-(a['L']+b['L'])/2
if gap>12 or abs(delta@u)>55:continue
parent[root(i)]=root(j)
groups={}
for i in range(len(records)):groups.setdefault(root(i),[]).append(i)
output=list(untouched);audit=[]
for ids in groups.values():
originals=[records[i]['f']for i in ids]
if len(ids)<2:output.extend(originals);continue
samples=np.concatenate([records[i]['center']+np.linspace(-records[i]['L']/2,records[i]['L']/2,max(3,int(records[i]['L']/.5)))[:,None]*records[i]['axis']for i in ids])
fit=cv2.fitLine(samples.astype('float32'),cv2.DIST_HUBER,0,.0001,.0001).ravel();u=fit[:2];o=fit[2:];n=np.array([-u[1],u[0]])
if np.max(abs((samples-o)@n))>.24:output.extend(originals);continue
ranges=sorted([((records[i]['center']-o)@u-records[i]['L']/2,(records[i]['center']-o)@u+records[i]['L']/2)for i in ids]);merged=[]
for a,b in ranges:
if merged and a<=merged[-1][1]+.15:merged[-1][1]=max(b,merged[-1][1])
else:merged.append([a,b])
widths=[records[i]['W']for i in ids];width=float(np.median(widths));lengths=np.array([b-a for a,b in merged]);centers=np.array([(a+b)/2 for a,b in merged]);gaps=np.array([b[0]-a[1]for a,b in zip(merged[:-1],merged[1:])])
intervals=None;mode=None;added=0
if len(merged)==1:intervals=merged;mode='continuous-paint-family'
elif np.max(gaps)<.85 or(np.median(lengths)>4 and np.max(gaps)<2.5):
intervals=[[merged[0][0],merged[-1][1]]];mode='continuous-paint-family';added=float(np.sum(gaps))
elif len(merged)>=3 and np.std(lengths)/np.mean(lengths)<.4:
deltas=np.diff(centers);period=float(np.median(deltas[deltas<=np.quantile(deltas,.65)]));L=float(np.median(lengths))
if period>L*1.3 and period<15:
slots=np.rint((centers-centers[0])/period).astype(int);phase=float(np.median(centers-slots*period))
residual=np.max(abs(centers-(phase+slots*period)))
if residual<.35 and np.max(np.diff(slots))<=2:
targets=np.arange(slots[0],slots[-1]+1);intervals=[[phase+t*period-L/2,phase+t*period+L/2]for t in targets];mode='periodic-dash-family';added=int(len(targets)-len(slots))
if intervals is None:output.extend(originals);continue
polygons=[]
for a,b in intervals:
xy=o+np.array([[a,-width/2],[b,-width/2],[b,width/2],[a,width/2],[a,-width/2]])@np.stack([u,n]);polygons.append(Polygon(xy))
if not all(admit(p)for p in polygons):output.extend(originals);continue
ids_source=[r['id']for r in originals]
for p in polygons:output.append(feature(lift(p),'road_marking',subtype='linear_marking',method=mode,source_ids=ids_source,inferred_internal_completion=bool(added),template_width_m=width))
audit.append(dict(method=mode,input_objects=len(ids),output_objects=len(polygons),width_m=width,added_internal_m_or_slots=added,source_ids=ids_source))
return output,audit
@@ -0,0 +1,85 @@
"""Template hypotheses in metric object coordinates; never site coordinates."""
import numpy as np,cv2,shapely
from shapely.geometry import Polygon,LineString
from shapely.ops import unary_union
from shapely.affinity import rotate,translate
from scipy.optimize import minimize
from road_glyph_presets import arrow
def template(kind,L,W,stroke):
if kind!='letter_A':return arrow(kind,L,W,stroke)
# A is an original parametric preset. Arrows use the attributed SVG library.
outer=LineString([(0,-W/2),(L,0),(0,W/2)]).buffer(stroke/2,cap_style=2,join_style=3)
bar=LineString([(L*.3,-W*.35),(L*.3,W*.35)]).buffer(stroke/2,cap_style=2)
return unary_union([outer,bar])
def fit_symbol(p,heading=None,diagnostics=None):
if p.geom_type!='Polygon' or p.area<.25:return None
points=np.array(p.exterior.coords)[:,:2];rect=cv2.minAreaRect(points.astype('float32'));corners=cv2.boxPoints(rect);edges=np.roll(corners,-1,axis=0)-corners;k=np.argmax(np.linalg.norm(edges,axis=1));u=edges[k]/np.linalg.norm(edges[k]);L=np.linalg.norm(edges[k]);W=min(rect[1]);origin=np.array(rect[0]);ang=np.arctan2(u[1],u[0]);fill=p.area/(L*W)
if not (1.2<L<9 and .35<W<3 and L/W>1.2 and .09<fill<.75):return None
# A fixed-resolution local evidence patch avoids manipulating full scene pixels.
cell=.04;lo=np.array(p.bounds[:2])-.6;hi=np.array(p.bounds[2:])+.6;shape=np.ceil((hi-lo)/cell).astype(int)[::-1]
if max(shape)>350:return None
target=np.zeros(shape,np.uint8)
def draw(poly):
out=np.zeros(shape,np.uint8)
for part in ([poly] if poly.geom_type=='Polygon' else getattr(poly,'geoms',[])):
if part.geom_type!='Polygon' or part.is_empty:continue
cv2.fillPoly(out,[np.rint((np.array(part.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1)
for hole in part.interiors:cv2.fillPoly(out,[np.rint((np.array(hole.coords)[:,:2]-lo)/cell).astype('int32')],0)
return out
target=draw(p);expanded=cv2.dilate(target,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))
# The counter supplies a strong object identity cue, independent of a noisy
# semantic mask. A bounded 8 cm closing tolerates small wear breaks.
closed=p.buffer(.08).buffer(-.08)
counters=[Polygon(h)for part in ([closed]if closed.geom_type=='Polygon'else getattr(closed,'geoms',[]))if part.geom_type=='Polygon'for h in part.interiors]
has_counter=any(h.area>.05*L*W for h in counters)
variants=['letter_A']if has_counter else ['straight_arrow','left_arrow','right_arrow','straight_left_arrow','straight_right_arrow'];best=None
if heading is not None:ang=float(np.arctan2(heading[1],heading[0]))
for kind in variants:
for flip in [0,np.pi]:
a=ang+flip;uu=np.array([np.cos(a),np.sin(a)]);base=origin-uu*L/2
x0=np.array([base[0],base[1],a,L,W,.16]);bounds=[(base[0]-.4,base[0]+.4),(base[1]-.4,base[1]+.4),(a-.16,a+.16),(L*.85,L*1.15),(W*.75,W*1.25),(.08,.32)]
def polygon(x):
m=template(kind,x[3],x[4],x[5]);m=rotate(m,x[2],origin=(0,0),use_radians=True);return translate(m,x[0],x[1])
def loss(x):
m=draw(polygon(x));wide=cv2.dilate(m,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))
coverage=(m&expanded).sum()/max(m.sum(),1);recall=(wide&target).sum()/max(target.sum(),1)
overlap=(m&target).sum()/max((m|target).sum(),1)
return 1-(.6*2*coverage*recall/max(coverage+recall,1e-6)+.4*overlap)+.03*abs(x[3]/L-1)
score=loss(x0)
if kind!='letter_A' and (W<.60 or W/x0[5]<3.5):continue
# A worn letter may have an open counter; missing topology is not a veto.
if score>.8:continue
fit=minimize(loss,x0,method='Powell',bounds=bounds,options=dict(maxiter=25,xtol=.004,ftol=.004));m=polygon(fit.x);r=draw(m)
coverage=float((r&expanded).sum()/max(r.sum(),1));recall=float((cv2.dilate(r,np.ones((5,5),np.uint8))&target).sum()/max(target.sum(),1));f1=2*coverage*recall/max(coverage+recall,1e-6);overlap=float((r&target).sum()/max((r|target).sum(),1));score=.6*f1+.4*overlap
if diagnostics is not None:diagnostics.append(dict(kind=kind,coverage=coverage,recall=recall,score=score,overlap=overlap,counter=has_counter,parameters=fit.x.tolist()))
if kind=='letter_A':
x=fit.x;bar=LineString([(x[3]*.3,-x[4]*.30),(x[3]*.3,x[4]*.30)]).buffer(x[5]/2,cap_style=2)
bar=translate(rotate(bar,x[2],origin=(0,0),use_radians=True),x[0],x[1]);support=draw(bar)
if (support&expanded).sum()/max(support.sum(),1)<.6:continue
# Positive shape overlap alone confuses arrow heads and triangular signs
# with A. Its counter is negative evidence and must stay largely unpainted.
holes=unary_union([Polygon(h)for part in ([m]if m.geom_type=='Polygon'else m.geoms)if part.geom_type=='Polygon'for h in part.interiors])
core=holes.buffer(-.08)
mask=draw(core)
if mask.sum()<8 or (mask&expanded).sum()/mask.sum()>.15:continue
elif kind.startswith('straight_') and kind!='straight_arrow':
# A compound arrow needs its lateral branch, even if a straight arrow
# alone matches most of the template area.
x=fit.x;u=np.array([np.cos(x[2]),np.sin(x[2])]);n=np.array([-u[1],u[0]])
yy,xx=np.mgrid[:r.shape[0],:r.shape[1]];xy=np.stack([lo[0]+xx*cell-x[0],lo[1]+yy*cell-x[1]],axis=-1);side=xy@n
# Artwork is bbox-centered; use the outer quarter on the branch side.
sign=1 if 'left'in kind else -1
branch=(r>0)&(side*sign>x[4]*.24)
if branch.sum()<5 or (branch&expanded).sum()/branch.sum()<.8:continue
longitudinal=xy@u;head=(r>0)&(longitudinal>x[3]*.8)
if head.sum()<5 or (head&expanded).sum()/head.sum()<.85:continue
elif kind in ['left_arrow','right_arrow']:
x=fit.x;u=np.array([np.cos(x[2]),np.sin(x[2])]);n=np.array([-u[1],u[0]])
yy,xx=np.nonzero(target);xy=np.c_[lo[0]+xx*cell-x[0],lo[1]+yy*cell-x[1]];longitudinal=xy@u;side=xy@n
front=side[longitudinal>x[3]*.72];tail=side[longitudinal<x[3]*.32];sign=1 if kind=='left_arrow'else -1
if len(front)<5 or len(tail)<5 or sign*(np.mean(front)-np.mean(tail))<.22*x[4]:continue
if coverage>=.72 and recall>=.86 and (best is None or score>best[1]):best=(m,score,kind,recall,fit.x.tolist())
if best and best[1]>=.80:return best
return None

Some files were not shown because too many files have changed in this diff Show More