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:
@@ -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
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Re-use normal-strip DP and minimum-curvature fitting around joined seams.
|
||||
|
||||
The visible sidewalk interface supplies broad context; physical Gaussian edges
|
||||
locate the anchors. Occluded samples have zero observation weight. The remainder
|
||||
of each accepted chain and its original scan terminals remain fixed.
|
||||
"""
|
||||
import numpy as np
|
||||
from shapely.geometry import LineString,Point
|
||||
from scipy.ndimage import gaussian_filter1d
|
||||
from dataclasses import replace
|
||||
from boundary_anchors import sample,smooth_anchors,AnchorPolicy
|
||||
from object_solver import sample_chain,stations
|
||||
from continuations import regularize
|
||||
|
||||
def snap(record,f):
|
||||
if not record.get('spans'):return record,dict(changed=False)
|
||||
side=f.side.astype('float32',copy=False);road=f.road_mask.astype('float32',copy=False)
|
||||
original=np.asarray(record['points']);line=LineString(original[:,:2]);p=sample_chain(original[:,:2],.4);st=stations(p)
|
||||
active=np.zeros(len(p),bool);centers=[]
|
||||
for span in record['spans']:
|
||||
a,b=sorted(line.project(Point(np.asarray(q)[:2]))for q in [span[0],span[-1]])
|
||||
centers.append((a+b)/2)
|
||||
active|=(st>max(0,a-10))&(st<min(st[-1],b+10))
|
||||
active[[0,-1]]=False
|
||||
core=gaussian_filter1d(p,1.5,axis=0,mode='nearest');t=np.gradient(core,axis=0);t/=np.maximum(np.linalg.norm(t,axis=1)[:,None],1e-8);n=np.c_[-t[:,1],t[:,0]]
|
||||
def pix(x):return np.stack([(x[...,0]-f.low[0])/f.cell-.5,(f.high[1]-x[...,1])/f.cell-.5],axis=-1)
|
||||
direction=np.sign(np.mean(sample(side,pix(p+n))-sample(side,pix(p-n))))or 1;n*=direction
|
||||
offsets=np.arange(-3.,3.001,.1);xy=p[:,None]+n[:,None]*offsets[None,:,None];uv=pix(xy);normal=n[:,None]*np.array([1,-1])
|
||||
physical,valid=f.fields.measure(uv,normal)
|
||||
contrast=sample(side,pix(xy+n[:,None]*.7))-sample(side,pix(xy-n[:,None]*.7))
|
||||
road_outside=sample(road,pix(xy-n[:,None]*.8))
|
||||
# The building-side edge of a sidewalk has the same walk/background
|
||||
# contrast. It cannot anchor a road curb without exterior road evidence.
|
||||
valid*=road_outside>.5
|
||||
reward=(physical+1.25*np.maximum(contrast,0))*valid
|
||||
cost=-reward+.10*offsets[None,:]**2
|
||||
center=len(offsets)//2;cost[~active]=1e5;cost[~active,center]=0
|
||||
transition=.5*((offsets[:,None]-offsets[None,:])/.4)**2
|
||||
previous=cost[0];back=np.zeros(cost.shape,np.int16)
|
||||
for i in range(1,len(p)):
|
||||
total=previous[:,None]+transition;back[i]=np.argmin(total,axis=0);previous=cost[i]+total.min(0)
|
||||
ix=np.zeros(len(p),int);ix[-1]=np.argmin(previous)
|
||||
for i in range(len(p)-1,0,-1):ix[i-1]=back[i,ix[i]]
|
||||
rows=np.arange(len(p));chosen=xy[rows,ix];supported=(physical[rows,ix]>.45)&(contrast[rows,ix]>.5)&(valid[rows,ix]>.5)
|
||||
confidence=supported.astype(float);confidence[~active]=100.;chosen[~active]=p[~active]
|
||||
if np.count_nonzero(supported&active)<5:return record,dict(changed=False,reason='insufficient-new-anchors')
|
||||
q=smooth_anchors(chosen,confidence,replace(AnchorPolicy(),sample_m=.4,smooth_lambda_m4=.8))
|
||||
q[~active]=p[~active];q[[0,-1]]=original[[0,-1],:2]
|
||||
if not LineString(q).is_simple or np.max(np.linalg.norm(q-p,axis=1))>3.1:return record,dict(changed=False,reason='geometry-guard')
|
||||
# The new path must actually increase physical/context agreement.
|
||||
nn=n*np.array([1,-1]);score0,valid0=f.fields.measure(pix(p),nn);score1,valid1=f.fields.measure(pix(q),nn)
|
||||
contrast0=sample(side,pix(p+n*.7))-sample(side,pix(p-n*.7))
|
||||
contrast1=sample(side,pix(q+n*.7))-sample(side,pix(q-n*.7))
|
||||
valid0*=sample(road,pix(p-n*.8))>.5;valid1*=sample(road,pix(q-n*.8))>.5
|
||||
before=float(np.mean((score0+1.25*np.maximum(contrast0,0))[active]*valid0[active]));after=float(np.mean((score1+1.25*np.maximum(contrast1,0))[active]*valid1[active]))
|
||||
# Each join is judged independently, including overlapping neighbourhoods.
|
||||
# Under occlusion, better image agreement cannot justify a new geometric
|
||||
# wiggle: the data do not establish the extra turning of a curb.
|
||||
occluded_station=np.max(sample(f.fields.occluder,uv),axis=1)>.25
|
||||
e0=(score0+1.25*np.maximum(contrast0,0))*valid0;e1=(score1+1.25*np.maximum(contrast1,0))*valid1
|
||||
groups=np.argmin(abs(st[:,None]-np.asarray(centers)[None,:]),axis=1);decisions=[]
|
||||
def turning(x):
|
||||
t=np.diff(gaussian_filter1d(x,1.,axis=0,mode='nearest'),axis=0)
|
||||
angle=np.unwrap(np.arctan2(t[:,1],t[:,0]));return float(np.sum(abs(np.diff(angle))))
|
||||
for group in range(len(centers)):
|
||||
window=(groups==group)&active
|
||||
if not window.any():continue
|
||||
b=float(np.mean(e0[window]));a=float(np.mean(e1[window]));old_turn=turning(p[window]);new_turn=turning(q[window]);occluded=float(np.mean(occluded_station[window]))
|
||||
complexity_veto=occluded>.15 and new_turn>old_turn+.25
|
||||
accept=np.count_nonzero(supported&window)>=5 and a>b+.1 and not complexity_veto
|
||||
decisions.append(dict(station_range_m=[float(st[window][0]),float(st[window][-1])],accepted=bool(accept),before=b,after=a,old_turn_radians=old_turn,new_turn_radians=new_turn,occluded_fraction=occluded,complexity_veto=bool(complexity_veto)))
|
||||
if not accept:q[window]=p[window]
|
||||
else:
|
||||
# Adjacent accepted/rejected windows must join continuously. Fade
|
||||
# only inside the accepted window; rejected geometry stays fixed.
|
||||
sw=st[window];weight=np.clip(np.minimum(sw-sw[0],sw[-1]-sw)/3.,0,1)
|
||||
weight=weight*weight*(3-2*weight)
|
||||
q[window]=p[window]+weight[:,None]*(q[window]-p[window])
|
||||
if not any(x['accepted']for x in decisions):return record,dict(changed=False,reason='no-admissible-local-correction',before=before,after=after,windows=decisions)
|
||||
if not LineString(q).is_simple:return record,dict(changed=False,reason='local-admission-geometry-guard',windows=decisions)
|
||||
if original.shape[1]>2:q=np.c_[q,np.interp(st,stations(original[:,:2]),original[:,2])]
|
||||
q,_=regularize(q)
|
||||
return {**record,'points':q},dict(changed=True,before=before,after=after,maximum_change_m=float(np.max(np.linalg.norm(xy[rows,ix]-p,axis=1))),observed_new_anchor_samples=int(np.count_nonzero(supported&active)),windows=decisions)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Recover missing street-side interfaces of measured sidewalk regions.
|
||||
|
||||
One-sided Gaussian support is valid when the road side is degraded. Building,
|
||||
terrain and survey frontiers remain vetoes. Existing boundaries are protected.
|
||||
"""
|
||||
import numpy as np,cv2,shapely,hashlib
|
||||
from shapely.geometry import shape,LineString
|
||||
from scipy.ndimage import gaussian_filter1d,binary_closing,binary_opening
|
||||
from object_solver import sample_chain,fit_chain,Policy
|
||||
from dataclasses import replace
|
||||
from continuations import regularize
|
||||
from boundary_anchors import sample
|
||||
|
||||
def recover(f,old,roads):
|
||||
road_geom=shapely.union_all([LineString(r['points'][:,:2])for r in roads])
|
||||
facade_geom=shapely.union_all([shapely.force_2d(shape(x['geometry']))for x in old['features']if x['properties']['class']=='building_facade'])
|
||||
known_walk=shapely.union_all([shapely.force_2d(shape(x['geometry']))for x in old['features']if x['properties']['class']=='pedestrian_boundary'])
|
||||
result=[];audit=[]
|
||||
def pix(p):return np.c_[(p[:,0]-f.low[0])/f.cell-.5,(f.high[1]-p[:,1])/f.cell-.5]
|
||||
def at(field,p):return sample(field,pix(p))
|
||||
contours,_=cv2.findContours(f.side.astype('uint8'),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
|
||||
for c in contours:
|
||||
p=c[:,0];xy=np.c_[f.low[0]+(p[:,0]+.5)*f.cell,f.high[1]-(p[:,1]+.5)*f.cell]
|
||||
if len(xy)<30:continue
|
||||
q=sample_chain(np.vstack([xy,xy[0]]),.4)[:-1]
|
||||
smooth=gaussian_filter1d(q,1.5,axis=0,mode='wrap');t=np.roll(smooth,-1,axis=0)-np.roll(smooth,1,axis=0);t/=np.maximum(np.linalg.norm(t,axis=1)[:,None],1e-8);n=np.c_[-t[:,1],t[:,0]]
|
||||
n*=np.sign(np.mean(at(f.walk,q+n*.8)-at(f.walk,q-n*.8)))or 1
|
||||
inside=q+n*.7;outside=q-n*.9
|
||||
own=at(f.walk,inside);other=at(f.walk,outside);road=at(f.road,outside)
|
||||
structures=at(f.structure,outside);terrain=at(f.terrain,outside)
|
||||
wall=(structures>.32)|((at(f.fields.z,outside)-at(f.fields.z,inside)>.7)&(at(f.alpha,outside)>.7)&(at(f.vehicle,outside)<.25))
|
||||
facade=shapely.distance(shapely.points(q),facade_geom)<1.2
|
||||
veto=wall|facade|(terrain>.4)|(at(f.alpha,q)<.3)
|
||||
support=(own>.35)&(other<.4)&(at(f.alpha,inside)>.7)&~veto
|
||||
# Only internal drops are filled, without crossing a positive wall/terrain.
|
||||
flags=binary_closing(np.tile(support,3),structure=np.ones(13))[len(q):2*len(q)]&~veto
|
||||
# Exclude already reconstructed geometry, including garden interfaces.
|
||||
covered=(shapely.distance(shapely.points(q),road_geom)<.8)|(shapely.distance(shapely.points(q),known_walk)<.8)
|
||||
flags&=~covered
|
||||
flags=binary_opening(np.tile(flags,3),structure=np.ones(4))[len(q):2*len(q)]
|
||||
if flags.all()or not flags.any():continue
|
||||
k=int(np.flatnonzero(~flags)[0]);order=np.roll(np.arange(len(q)),-k);ff=flags[order];cuts=np.r_[0,np.flatnonzero(np.diff(ff.astype(int)))+1,len(q)]
|
||||
for a,b in zip(cuts[:-1],cuts[1:]):
|
||||
if not ff[a]or(b-a)*.4<8:continue
|
||||
ix=order[a:b];p=q[ix];ro=float(np.mean(road[ix]));near=float(LineString(p).distance(road_geom))
|
||||
# Street evidence may be sparse, but must exist along this interface
|
||||
# or meet a previously identified street edge at both ends.
|
||||
end_near=[shapely.Point(e).distance(road_geom)for e in p[[0,-1]]]
|
||||
if ro<.08 and not(max(end_near)<8 and near<3):continue
|
||||
# A recovered observation has not passed the v8 shape stage. Fit a
|
||||
# compact primitive chain; never emit a failed raw raster contour.
|
||||
fit=fit_chain(p,np.ones(len(p)),replace(Policy(),residual_scale_m=.32,reliable_residual_limit_m=.55),complexity_scale=3.)
|
||||
if fit is None or len(fit['primitives'])>max(2,LineString(p).length/6):continue
|
||||
new=np.c_[fit['points'],at(f.fields.z,fit['points'])]
|
||||
if not LineString(new[:,:2]).is_simple:continue
|
||||
# Never add a duplicate parallel trace over the known road edge.
|
||||
novel=LineString(new[:,:2]).difference(road_geom.buffer(1.0)).length
|
||||
if novel<LineString(new[:,:2]).length*.7:continue
|
||||
if LineString(new[:,:2]).crosses(road_geom)or any(LineString(new[:,:2]).crosses(LineString(r['points'][:,:2]))for r in result):continue
|
||||
ident='recovered-'+hashlib.sha256(new.round(4).tobytes()).hexdigest()[:12]
|
||||
result.append(dict(id=ident,points=new,**{'class':'road_boundary'},source_ids=[ident],reasons=['inferred-interface-terminal']*2))
|
||||
audit.append(dict(id=ident,length_m=float(LineString(new[:,:2]).length),outside_road_score=ro,nearest_known_edge_m=near,endpoint_distances_m=end_near,one_sided_support=True,inferred_class=True))
|
||||
return result,audit
|
||||
@@ -0,0 +1,128 @@
|
||||
from pathlib import Path
|
||||
from dataclasses import asdict,replace
|
||||
from copy import deepcopy
|
||||
import json,os,time,hashlib
|
||||
import numpy as np,shapely
|
||||
from shapely.geometry import LineString,Point,shape,mapping
|
||||
from scipy.ndimage import binary_fill_holes
|
||||
from continuations import ContinuationPolicy,regularize,connect,observed_crossing_length
|
||||
from object_solver import sample_chain
|
||||
from boundary_anchors import sample
|
||||
import evidence_fields as f
|
||||
|
||||
O=Path('/out');B=Path('/base');policy=ContinuationPolicy();t0=time.monotonic()
|
||||
np.savez_compressed(O/'occluder-field.npz',vehicle=(f.vehicle>.25).astype('uint8'),bounds=np.array([f.low,f.high]),cell=f.cell)
|
||||
def pix(p):
|
||||
p=np.asarray(p);return np.c_[(p[:,0]-f.low[0])/f.cell-.5,(f.high[1]-p[:,1])/f.cell-.5]
|
||||
def at(field,p):return sample(field,pix(p))
|
||||
domain=binary_fill_holes((f.alpha>.3)|((f.walk+f.road)>.5)).astype('float32')
|
||||
def sides(p):
|
||||
p=sample_chain(np.asarray(p)[:,:2],.4);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]]
|
||||
return p,n,at(f.walk,p+n)-at(f.walk,p-n)+at(f.road,p-n)-at(f.road,p+n)
|
||||
def evaluate(curve,left,right):
|
||||
p,n,contrast=sides(curve)
|
||||
if np.mean(at(domain,p)>.5)<.95:return dict(allowed=False,reason='outside-survey-domain')
|
||||
crossing=observed_crossing_length(curve,lambda q:at(f.transport,q),lambda q:at(f.alpha,q),lambda q:at(f.vehicle,q))
|
||||
if crossing>=.6:return dict(allowed=False,reason='visible-transport-corridor',visible_crossing_m=crossing)
|
||||
a,_,sa=sides(left[-min(len(left),30):]);b,_,sb=sides(right[:min(len(right),30)])
|
||||
aa=float(np.mean(sa));bb=float(np.mean(sb));orientation=np.sign(aa+bb)
|
||||
if aa*bb<0 and min(abs(aa),abs(bb))>.25:return dict(allowed=False,reason='opposite-surface-sides')
|
||||
if not orientation:return dict(allowed=False,reason='unestablished-adjacency')
|
||||
nr=n*orientation;inside=at(f.walk,p+nr);outside=at(f.walk,p-nr)
|
||||
bothroad=(at(f.road,p+n)>.65)&(at(f.road,p-n)>.65)
|
||||
if np.count_nonzero(bothroad[2:-2])*.4>max(.8,LineString(p).length*.25):return dict(allowed=False,reason='road-crossing-cap')
|
||||
if np.mean((inside>.55)&(outside>.55))>.6:return dict(allowed=False,reason='cuts-pedestrian-interior')
|
||||
uv=pix(p);normal=np.c_[nr[:,0],-nr[:,1]]
|
||||
score,valid=f.fields.measure(uv,normal)
|
||||
occ=at(f.vehicle,p)
|
||||
context=float(np.mean(inside-outside))
|
||||
if context<-.2:return dict(allowed=False,reason='wrong-surface-side')
|
||||
evidence=float(np.mean(score*valid));reward=evidence+.4*max(0,context)
|
||||
return dict(allowed=True,reward=reward,physical_score=evidence,pedestrian_contrast=context,occluded_fraction=float(np.mean(occ>.25)),visible_crossing_m=crossing,inferred=True)
|
||||
|
||||
base_bytes=(B/'whole-map.json').read_bytes();base=json.loads(base_bytes)
|
||||
fs=[x for x in base['features']if x['properties']['class']=='road_boundary']
|
||||
raw=[dict(id=x['id'],points=np.asarray(x['geometry']['coordinates']),reasons=[x['properties'].get('start_reason'),x['properties'].get('end_reason')],**{'class':'road_boundary'})for x in fs]
|
||||
fitted=[];shape_audit=[]
|
||||
for r in raw:
|
||||
q,rec=regularize(r['points'],policy);fitted.append({**r,'points':q});shape_audit.append(dict(id=r['id'],changed=rec is not None,fit=rec))
|
||||
# Retain both complete parents if regularization introduces a crossing.
|
||||
for i,a in enumerate(fitted):
|
||||
for j,b in enumerate(fitted[:i]):
|
||||
if LineString(a['points'][:,:2]).crosses(LineString(b['points'][:,:2])):
|
||||
a['points']=raw[i]['points'];b['points']=raw[j]['points'];shape_audit[i]['reverted']='crossing';shape_audit[j]['reverted']='crossing'
|
||||
variants={'regularized':(fitted,{})}
|
||||
variants['connected']=connect(raw,evaluate,policy)
|
||||
variants['combined']=connect(fitted,evaluate,policy)
|
||||
# Fit only after connectivity has been chosen, so smoothing does not move the
|
||||
# candidate attachment stations before the endpoint graph is evaluated.
|
||||
post=[]
|
||||
for r in variants['connected'][0]:
|
||||
q,fit=regularize(r['points'],policy);post.append({**r,'points':q})
|
||||
# A individually simple fit can still collide with another complete chain.
|
||||
for i,a in enumerate(post):
|
||||
for j,b in enumerate(post[:i]):
|
||||
if LineString(a['points'][:,:2]).crosses(LineString(b['points'][:,:2])):
|
||||
a['points']=variants['connected'][0][i]['points'];b['points']=variants['connected'][0][j]['points']
|
||||
variants['connected_then_fit']=(post,variants['connected'][1])
|
||||
from reanchor import snap
|
||||
snapped=[];snap_audit=[]
|
||||
for r in post:
|
||||
new,audit=snap(r,f);snapped.append(new);snap_audit.append(dict(source_ids=r.get('source_ids',[r['id']]),**audit))
|
||||
# Roll back the neighborhood of a conflicting move, not an entire long street.
|
||||
# This guard is geometric and identical at every scene/chain position.
|
||||
from object_solver import stations
|
||||
snapped=[{**r,'points':r['points'].copy()}for r in snapped]
|
||||
for attempt in range(3):
|
||||
collisions=[]
|
||||
for i,a in enumerate(snapped):
|
||||
for j,b in enumerate(snapped[:i]):
|
||||
ga=LineString(a['points'][:,:2]);gb=LineString(b['points'][:,:2])
|
||||
if ga.crosses(gb):collisions.append((i,j,shapely.get_coordinates(ga.intersection(gb))))
|
||||
if not collisions:break
|
||||
for i,j,xy in collisions:
|
||||
for k in [i,j]:
|
||||
if not snap_audit[k]['changed']:continue
|
||||
parent_points=post[k]['points'];g=LineString(parent_points[:,:2]);p=sample_chain(snapped[k]['points'][:,:2],.25)
|
||||
st=shapely.line_locate_point(g,shapely.points(p));targets=shapely.line_locate_point(g,shapely.points(xy));delta=np.min(abs(st[:,None]-targets[None,:]),axis=1)
|
||||
weight=np.clip((delta-4*(attempt+1))/4,0,1);oldst=stations(parent_points[:,:2]);fallback=np.stack([np.interp(st,oldst,parent_points[:,d])for d in range(parent_points.shape[1])],axis=1)
|
||||
fallback[:,:2]=weight[:,None]*p+(1-weight[:,None])*fallback[:,:2]
|
||||
snapped[k]['points']=fallback;snap_audit[k]['local_conflict_rollbacks']=snap_audit[k].get('local_conflict_rollbacks',0)+1
|
||||
for i,a in enumerate(snapped):
|
||||
for j,b in enumerate(snapped[:i]):
|
||||
if LineString(a['points'][:,:2]).crosses(LineString(b['points'][:,:2]))or not LineString(a['points'][:,:2]).is_simple:
|
||||
a['points']=post[i]['points'];b['points']=post[j]['points'];snap_audit[i]['reverted']='unresolved-crossing';snap_audit[j]['reverted']='unresolved-crossing'
|
||||
variants['reanchored']=(snapped,variants['connected'][1]);post=snapped
|
||||
(O/'reanchor-audit.json').write_text(json.dumps(snap_audit,allow_nan=False))
|
||||
from recover_interfaces import recover
|
||||
old_full=json.loads(Path('/fullplan/full-map.json').read_text())
|
||||
extra,recovery_audit=recover(f,old_full,post)
|
||||
joined_extra,extra_audit=connect(extra,evaluate,replace(policy,max_heading_degrees=25.,maximum_terminal_revision_m=2.))
|
||||
protected=shapely.union_all([LineString(r['points'][:,:2])for r in post])
|
||||
joined_extra=[r for r in joined_extra if not LineString(r['points'][:,:2]).crosses(protected)]
|
||||
for r in joined_extra:r['inferred_class']=True
|
||||
variants['recovered']=(post+joined_extra,extra_audit)
|
||||
(O/'recovery-audit.json').write_text(json.dumps(recovery_audit,allow_nan=False))
|
||||
for name,(records,audit)in variants.items():
|
||||
features=[]
|
||||
for r in records:
|
||||
identity='refined-'+hashlib.sha256(r['points'].round(4).tobytes()).hexdigest()[:14]
|
||||
props=dict(**{'class':r['class']},method='v8-seeds-common-primitive-and-endpoint-graph',source_ids=r.get('source_ids',[r['id']]),inferred_spans=[dict(status='inferred',coordinates=s,method='evidence-validated-endpoint-graph')for s in r.get('spans',[])],route_permission='unassigned',review_status='unreviewed',height_status='inherited-not-qualified')
|
||||
# Report actual final geometry, after the bounded primitive fit, for inferred
|
||||
# intervals. The raw candidate curves remain in the separate selection audit.
|
||||
line=LineString(r['points'][:,:2]);st=np.r_[0,np.cumsum(np.linalg.norm(np.diff(r['points'][:,:2],axis=0),axis=1))]
|
||||
for span in props['inferred_spans']:
|
||||
a,b=sorted(line.project(Point(np.asarray(s)[:2]))for s in [span['coordinates'][0],span['coordinates'][-1]])
|
||||
stations=np.r_[a,st[(st>a)&(st<b)],b]
|
||||
span['station_interval_m']=[a,b];span['coordinates']=np.stack([np.interp(stations,st,r['points'][:,d])for d in range(r['points'].shape[1])],axis=1).tolist()
|
||||
if r.get('inferred_class'):
|
||||
props.update(method='one-sided-sidewalk-interface',class_status='inferred-road-adjacency',boundary_support='gaussian-sidewalk-edge')
|
||||
features.append(dict(type='Feature',id=identity,geometry=mapping(LineString(r['points'])),properties=props))
|
||||
doc=dict(type='FeatureCollection',features=features,variant=name,manual_geometry=False,point_clouds=False,baseline_role='retained-universal-v8-seed-stage',inferred_spans_scope='new-infill-only; inherited v8 inference remains referenced by source_ids',review_status='unreviewed')
|
||||
(O/(name+'.json')).write_text(json.dumps(doc,allow_nan=False))
|
||||
(O/(name+'-audit.json')).write_text(json.dumps(audit,allow_nan=False))
|
||||
print('VARIANT',name,'chains',len(records),'bridges',len(audit.get('selected',[])),flush=True)
|
||||
if name=='reanchored':(O/'whole-map.json').write_text(json.dumps(doc,allow_nan=False))
|
||||
assert (B/'whole-map.json').read_bytes()==base_bytes
|
||||
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-t0,policy=asdict(policy),baseline_sha256=hashlib.sha256(base_bytes).hexdigest(),baseline_role='retained seed algorithm, not ground truth',source_inputs_sha256=f.inputs,baseline_chains=len(raw),selected_variant='reanchored',recovery_admitted=False,variants={name:dict(chains=len(records),bridges=len(audit.get('selected',[])),inferred_added_m=sum(x['gap_m']for x in audit.get('selected',[])),selection_audit=name+'-audit.json')for name,(records,audit)in variants.items()},shape_audit=shape_audit,metric_accuracy_measured=False,manual_rois=[],manual_geometry=False)
|
||||
(O/'report.json').write_text(json.dumps(report,allow_nan=False));print('REPORT',json.dumps({k:v for k,v in report.items()if k not in ['source_inputs_sha256','shape_audit']}),flush=True)
|
||||
@@ -0,0 +1,105 @@
|
||||
"""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 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'
|
||||
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)
|
||||
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=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');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,58 @@
|
||||
"""Unaltered Gaussian evidence with computed vector overlays, full-scene review."""
|
||||
from pathlib import Path
|
||||
import os,json,numpy as np
|
||||
from PIL import Image,ImageDraw,ImageFont
|
||||
from shapely.geometry import shape,box
|
||||
from fit_scene import project
|
||||
B=Path('/base');O=Path('/out');S=Path('/survey')
|
||||
v=json.loads((B/'viewer-data.json').read_text());low,high=np.asarray(v['bounds_xy']);res=v['resolution_m']
|
||||
current=json.loads((O/'whole-map.json').read_text())['features'];old=json.loads(Path('/fullplan/full-map.json').read_text())['features'];old=[f for f in old if f['properties']['class']=='road_boundary']
|
||||
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',22);small=ImageFont.truetype('/candidate/review-font.ttf',17)
|
||||
def overlay(im,features,convert,width=3):
|
||||
out=im.convert('RGB').copy();d=ImageDraw.Draw(out)
|
||||
for f in features:
|
||||
pts=convert(np.asarray(f['geometry']['coordinates']));color='#ed821e'if f['properties']['class']=='road_boundary'else'#009b80'
|
||||
d.line([tuple(p)for p in pts],fill=color,width=width,joint='curve')
|
||||
return out
|
||||
def title(im,txt):
|
||||
out=Image.new('RGB',(im.width,im.height+64),'white');out.paste(im,(0,64));d=ImageDraw.Draw(out);d.text((12,7),txt,font=font,fill='#263540');d.text((12,36),'Оранжевый: дорожный край · зелёный: граница пешеходной зоны с неустановленной поверхностью',font=small,fill='#435761');return out
|
||||
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 tiles:
|
||||
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)
|
||||
world=lambda p:np.c_[(p[:,0]-low[0])/res,(high[1]-p[:,1])/res]
|
||||
scene={'maroseyka':'Маросейка','pokrovka':'Покровка','smolensk':'Смоленский бульвар'}[os.environ['SCENE']]
|
||||
rendered=[]
|
||||
for features,name in [(old,'Предыдущая сборка'),(current,'Новый проход — кандидат')]:
|
||||
im=overlay(base,features,world);im.thumbnail((2300,1400));rendered.append(title(im,scene+' · '+name))
|
||||
sheet=Image.new('RGB',(max(i.width for i in rendered),sum(i.height for i in rendered)+12),'white');y=0
|
||||
for im in rendered:sheet.paste(im,(0,y));y+=im.height+12
|
||||
sheet.save(O/'comparison.jpg',quality=95);rendered[-1].save(O/'road-overview.jpg',quality=95)
|
||||
plan=Image.new('RGB',base.size,'#f5f5f2');plan=overlay(plan,current,world);plan.thumbnail((2300,1400));title(plan,scene+' · только границы').save(O/'vector-plan.jpg',quality=95)
|
||||
scores=[]
|
||||
for tile in tiles:
|
||||
domain=box(*tile['bounds_xy'][0],*tile['bounds_xy'][1]);a=[shape(f['geometry']).intersection(domain)for f in old if shape(f['geometry']).intersects(domain)];b=[shape(f['geometry']).intersection(domain)for f in current if shape(f['geometry']).intersects(domain)]
|
||||
import shapely
|
||||
ga=shapely.union_all(a);gb=shapely.union_all(b)
|
||||
delta=ga.difference(gb.buffer(.15)).length+gb.difference(ga.buffer(.15)).length
|
||||
scores.append((delta,tile))
|
||||
chosen=[]
|
||||
for score,tile in sorted(scores,key=lambda x:-x[0]):
|
||||
center=np.mean(tile['bounds_xy'],axis=0)
|
||||
if any(np.linalg.norm(center-np.mean(t['bounds_xy'],axis=0))<70 for t in chosen):continue
|
||||
chosen.append(tile)
|
||||
if len(chosen)==3:break
|
||||
sheet=Image.new('RGB',(2400,len(chosen)*865),'white');d=ImageDraw.Draw(sheet)
|
||||
for row,tile in enumerate(chosen):
|
||||
name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(S/name/'top.png').convert('RGB')
|
||||
for col,(features,label)in enumerate([(None,'Гауссы'),(old,'Предыдущая сборка'),(current,'Новый проход')]):
|
||||
im=raw if features is None else overlay(raw,features,lambda p:project(p,g))
|
||||
im=im.resize((800,800),Image.Resampling.LANCZOS);sheet.paste(im,(col*800,row*865+60));d.text((col*800+12,row*865+12),name+' · '+label,font=font,fill='#263540')
|
||||
sheet.save(O/'road-details.jpg',quality=95)
|
||||
(O/'road-visual-manifest.json').write_text(json.dumps(dict(selected=[t['id']for t in chosen],selection='largest geometry disagreement with baseline plus spatial spacing; review only',manual_rois=[],all_tile_scores=[dict(tile=t['id'],difference_m=float(s))for s,t in scores]),indent=2))
|
||||
print('RENDERED',len(current),[t['id']for t in chosen])
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Reusable arrow artwork adapted from the CC BY-SA 4.0 SVG by Major Alexey.
|
||||
Source: https://commons.wikimedia.org/wiki/File:1.18_Russian_road_marking.svg
|
||||
License: https://creativecommons.org/licenses/by-sa/4.0/
|
||||
Changes: curve sampling, coordinate normalization, metric scaling and stroke fit.
|
||||
This attribution/license concerns the arrow artwork in this module.
|
||||
"""
|
||||
import re
|
||||
import numpy as np
|
||||
from shapely.geometry import Polygon
|
||||
from shapely.affinity import scale
|
||||
SOURCE_SHA256='b76f40ee8d1603ddfeb3cd430f397dcc509684f0a0aa38c61bbd8a2cba554ea8'
|
||||
PATHS={'straight_arrow': 'M38.4,168.5 23.2,123.5 10,169 20,168.9 20,273 28,273 28,168.7 Z', 'right_arrow': 'M83,149.8c0,0-15.1-26.4-15.1-25.6l-0.1,19.2l-24.4,19.2l0.6,0.8V273h7V171.7l16.8-13.2l-0.1,17.1\n\t\t\t\tL83,149.8z', 'left_arrow': 'M124.8,162l-23.9-18.7l-0.1-19c0-0.8-15.1,25.6-15.1,25.6l15.3,25.6l-0.1-17.1l17.1,13.4V273h8V162H124.8z\n\t\t\t\t', 'straight_right_arrow': 'M179.4,206.5c0,0-15.1-26.4-15.1-25.6l-0.1,19.2L146,214.4v-45.7l11.7-0.2l-15.2-45L129.2,169l9.8-0.2V273\n\t\t\t\th7v-45.8l1.1,1.4l17.1-13.4l-0.1,17L179.4,206.5z', 'straight_left_arrow': 'M231.9,169l-13.3-45.5l-15.2,45l10.6,0.2v44.9l-17.1-13.5l-0.1-19.2c0-0.8-15.1,25.6-15.1,25.6l15.3,25.6\n\t\t\t\tl-0.1-16.9l17,13.4l0.1-0.1V273h8V168.9L231.9,169z'}
|
||||
|
||||
def parse_path(path):
|
||||
tokens=re.findall(r'[MLHVClmhvcZz]|[-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?',path)
|
||||
points=[];p=np.zeros(2);i=0;command=None
|
||||
while i<len(tokens):
|
||||
if tokens[i].isalpha():command=tokens[i];i+=1
|
||||
if command in 'Zz':break
|
||||
relative=command.islower();kind=command.upper();count={'M':2,'L':2,'H':1,'V':1,'C':6}[kind]
|
||||
v=np.array([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':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:
|
||||
control=v.reshape(3,2)+(p if relative else 0);a=p.copy();b,c,d=control
|
||||
for t in np.linspace(0,1,9)[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()
|
||||
xy=np.array(points);xy=np.c_[-xy[:,1],-xy[:,0]];low=xy.min(0);high=xy.max(0)
|
||||
xy=(xy-low)/(high-low);xy[:,1]-=.5
|
||||
poly=Polygon(xy)
|
||||
assert poly.is_valid
|
||||
return poly
|
||||
UNIT={name:parse_path(path)for name,path in PATHS.items()}
|
||||
def arrow(kind,length,width,stroke):
|
||||
g=scale(UNIT[kind],length,width,origin=(0,0))
|
||||
# Shape is reusable; only metric dimensions and a small paint thickness vary.
|
||||
delta=(stroke-.16)*.3
|
||||
if abs(delta)>.001:g=g.buffer(delta,join_style=2)
|
||||
return g
|
||||
@@ -0,0 +1,81 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import numpy as np,shapely
|
||||
from shapely.geometry import LineString
|
||||
from continuations import connect,regularize,ContinuationPolicy,observed_crossing_length
|
||||
from object_solver import sample_chain
|
||||
|
||||
def record(name,p,**kwargs):return dict(id=name,points=sample_chain(p,.25),**{'class':'road_boundary'},**kwargs)
|
||||
checks=[]
|
||||
def check(name,passed,**details):checks.append(dict(name=name,passed=bool(passed),**details));assert passed,(name,details)
|
||||
a=record('left',[[0,0],[12,0]]);b=record('right',[[18,0],[32,0]])
|
||||
out,audit=connect([a,b]);check('six-metre-occlusion',len(out)==1 and len(audit['selected'])==1 and LineString(out[0]['points']).hausdorff_distance(LineString([[0,0],[32,0]]))<.01)
|
||||
out,audit=connect([a,{**b,'reasons':['survey-exterior',None]}]);check('explicit-survey-exit-remains-open',len(out)==2)
|
||||
out,audit=connect([record('north',[[0,5],[12,5]]),record('south',[[0,-5],[12,-5]])]);check('opposite-parallel-sides-not-capped',len(out)==2)
|
||||
out,audit=connect([a,b],lambda *_:dict(allowed=False,reason='road-crossing-cap'));check('observed-opening-veto',len(out)==2)
|
||||
c=record('branch',[[18,2],[28,3]])
|
||||
out,audit=connect([a,b,c]);check('global-endpoint-choice-selects-straight',len(audit['selected'])==1 and set(audit['selected'][0]['source_ids'])=={'left','right'})
|
||||
p=sample_chain([[0,0],[12,0],[12,-2],[20,-2],[20,0],[35,0]],.2);q,_=regularize(p);check('square-parking-pocket-preserved',LineString(p).hausdorff_distance(LineString(q))<.45)
|
||||
theta=np.linspace(-np.pi/2,0,50);p=sample_chain(np.vstack([[[0,0],[12,0]],np.c_[12+8*np.cos(theta),8+8*np.sin(theta)],[[20,22]]]),.2);q,_=regularize(p);check('round-turn-preserved',LineString(p).hausdorff_distance(LineString(q))<.45)
|
||||
# Rotation/translation change no topology or metric policy.
|
||||
angle=.73;R=np.array([[np.cos(angle),-np.sin(angle)],[np.sin(angle),np.cos(angle)]]);offset=np.array([350,-480])
|
||||
out2,audit2=connect([{**x,'points':x['points']@R.T+offset}for x in [a,b,c]])
|
||||
check('rigid-transform-transfer',len(audit2['selected'])==1 and set(audit2['selected'][0]['source_ids'])=={'left','right'})
|
||||
# Object-level checks exercise missing evidence and rejection, not just output shape.
|
||||
from shapely.geometry import box,Polygon
|
||||
from paint_families import normalize
|
||||
from paint_templates import fit_symbol,template
|
||||
from layer_common import feature
|
||||
from frontage_chains import join_planes
|
||||
features=[feature(box(x,-.08,x+2,.08),'road_marking',subtype='linear_marking')for x in [0,5,15,20]]
|
||||
out,audit=normalize(features,lambda g:g,lambda g:True)
|
||||
check('periodic-family-fills-internal-slot',len(out)==5 and len(audit)==1 and audit[0]['added_internal_m_or_slots']==1)
|
||||
geometries=[shapely.geometry.shape(x['geometry'])for x in out]
|
||||
check('periodic-family-no-extrapolation',min(g.bounds[0]for g in geometries)>-.01 and max(g.bounds[2]for g in geometries)<22.01)
|
||||
parallel=[feature(box(x,y,x+7,y+.12),'road_marking',subtype='linear_marking')for x in [0,7.5]for y in [0,1]]
|
||||
out,audit=normalize(parallel,lambda g:g,lambda g:True)
|
||||
check('parallel-paint-families-stay-separate',len(out)==2 and len(audit)==2)
|
||||
planes=[LineString([[0,0],[8,0]]),LineString([[13,0],[21,0]])]
|
||||
out=join_planes(planes,gap=8,bridge_validator=lambda line,sources:not line.intersects(box(9,-1,12,1)))
|
||||
check('facade-gap-does-not-bridge-street',len(out)==2)
|
||||
out=join_planes(planes,gap=8,bridge_validator=lambda *_:True)
|
||||
check('facade-occlusion-interpolated',len(out)==1 and len(out[0][1])==2)
|
||||
a=template('letter_A',4,1.2,.18)
|
||||
# A small loss at one foot is permitted; the distinguishing open counter remains.
|
||||
worn=a.difference(box(-.3,-.8,.25,-.4));fit=fit_symbol(worn)
|
||||
check('worn-A-recognized',fit is not None and fit[2]=='letter_A')
|
||||
solid=Polygon([[0,-.6],[4,0],[0,.6]])
|
||||
fit=fit_symbol(solid)
|
||||
check('filled-triangle-not-A',fit is None or fit[2]!='letter_A')
|
||||
turn=template('straight_left_arrow',5,1.7,.16);diagnostics=[];fit=fit_symbol(turn,heading=[1,0],diagnostics=diagnostics)
|
||||
if fit is None:print(json.dumps(diagnostics),flush=True)
|
||||
check('compound-arrow-not-A',fit is not None and fit[2]=='straight_left_arrow',result=None if fit is None else fit[2])
|
||||
# A physical curb with an occluded middle must overrule a spurious sidewalk bow.
|
||||
from types import SimpleNamespace
|
||||
from boundary_anchors import PhysicalFields
|
||||
from reanchor import snap
|
||||
xx,yy=np.meshgrid(np.arange(400)*.1-5+.05,5-(np.arange(100)*.1+.05))
|
||||
side=(yy>0).astype('float32');rgb=np.repeat((90+80*side).astype('uint8')[:,:,None],3,axis=2);z=side*.12;alpha=np.ones_like(side)
|
||||
vehicle=((xx>10)&(xx<18)&(abs(yy)<2)).astype('float32')
|
||||
fields=PhysicalFields(rgb,z,alpha,vehicle,1-side,side,.1)
|
||||
f=SimpleNamespace(low=np.array([-5.,-5.]),high=np.array([35.,5.]),cell=.1,side=side.astype(bool),road_mask=1-side,fields=fields)
|
||||
x=np.linspace(0,30,151);points=np.c_[x,1.2*np.sin(np.pi*x/30)**2,np.zeros(len(x))]
|
||||
r=dict(id='occluded-curb',points=points,spans=[points[(x>=8)&(x<=22)].tolist()],**{'class':'road_boundary'})
|
||||
q,audit=snap(r,f)
|
||||
check('physical-curb-corrects-interior-bow',audit['changed'] and np.mean(abs(q['points'][:,1]))<.2,audit=audit)
|
||||
check('reanchor-preserves-scan-terminals',np.allclose(q['points'][[0,-1]],points[[0,-1]]))
|
||||
straight=np.array([[0.,0.],[18.,0.]])
|
||||
road=lambda p:((p[:,0]>8)&(p[:,0]<9.5)).astype(float)
|
||||
ones=lambda p:np.ones(len(p));zeros=lambda p:np.zeros(len(p))
|
||||
check('narrow-visible-road-not-diluted-by-long-gap',observed_crossing_length(straight,road,ones,zeros)>.6)
|
||||
check('vehicle-occlusion-is-not-observed-opening',observed_crossing_length(straight,road,ones,ones)==0)
|
||||
check('along-curb-is-not-a-road-cap',observed_crossing_length(straight,lambda p:(p[:,1]<.1).astype(float),ones,zeros)==0)
|
||||
from paint_dedup import deduplicate_glyphs
|
||||
from shapely.affinity import translate,scale
|
||||
g=template('letter_A',4,1.2,.18)
|
||||
glyphs=[feature(p,'road_marking',subtype='letter_A',method='symbol-template',template_fit_score=s)for p,s in [(g,.94),(translate(scale(g,xfact=1.04,yfact=.96),.03,.02),.91),(translate(g,7,0),.92)]]
|
||||
out,duplicates=deduplicate_glyphs(glyphs)
|
||||
check('overlapping-glyph-fits-merged',len(out)==2 and len(duplicates)==1 and glyphs[0]['id']in [f['id']for f in out])
|
||||
check('nearby-independent-glyph-retained',glyphs[2]['id']in [f['id']for f in out])
|
||||
report=dict(passed=all(x['passed']for x in checks),checks=checks,real_scene_accuracy=False)
|
||||
Path('/out/tests.json').write_text(json.dumps(report,indent=2));print(json.dumps(report))
|
||||
Reference in New Issue
Block a user