Files
NODEDC_MISSION_CORE/simulation/urban-plan-research/plan_scene.py
T
DCCONSTRUCTIONS 69dc566665 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.
2026-10-29 09:10:00 +03:00

203 lines
12 KiB
Python

"""Assemble local curb replacements by source-chain station, never tile edges.
An accepted patch consumes explicit intervals of immutable parent curves.
Unconsumed intervals survive once. Artificial cuts reconnect only to the same
parent/station, so nearby opposite curbs cannot become seam neighbours.
"""
from copy import deepcopy
import hashlib
import numpy as np
from shapely.geometry import LineString,Point,mapping,shape
from shapely.ops import substring
from plan_junctions import bridge_short_seam
EPS=1e-5
def merge_intervals(intervals,length):
output=[]
for a,b in sorted(intervals):
if not np.isfinite([a,b]).all()or a<-EPS or b>length+EPS or b<=a:
raise ValueError('Invalid source interval')
a,b=max(0.,float(a)),min(float(length),float(b))
if output and a<=output[-1][1]+EPS:output[-1][1]=max(output[-1][1],b)
else:output.append([a,b])
return output
def complement(intervals,length):
output=[];cursor=0.
for a,b in merge_intervals(intervals,length):
if a-cursor>EPS:output.append([cursor,a])
cursor=b
if length-cursor>EPS:output.append([cursor,length])
return output
def overlap(a,b):return max(0.,min(a[1],b[1])-max(a[0],b[0]))
def select_patches(patches):
"""Input order defines review priority; a patch is an atomic replacement."""
consumed={};accepted=[];rejected=[]
for patch in patches:
segments=[s for f in patch['features']for s in f['parent_segments']]+patch.get('quarantine',[])
conflicts=sorted({s['id']for s in segments for old in consumed.get(s['id'],[])if overlap(s['interval_m'],old)>EPS})
if conflicts:
rejected.append(dict(id=patch['id'],reason='source-interval-already-owned',parents=conflicts));continue
accepted.append(patch)
for s in segments:consumed.setdefault(s['id'],[]).append(s['interval_m'])
return accepted,rejected
def assemble(source,patches):
parents={f['id']:f for f in source['features']if f['properties']['class']=='road_boundary'}
parent_lines={i:LineString(f['geometry']['coordinates'])for i,f in parents.items()}
cuts={};pieces=[];quarantine=[]
for patch in patches:
for f in patch['features']:
for s in f['parent_segments']:
if s['id']not in parents:raise ValueError('Unknown parent chain')
cuts.setdefault(s['id'],[]).append(s['interval_m'])
p=np.asarray(f['geometry']['coordinates'],float);bindings=[]
for endpoint in p[[0,-1]]:
options=[]
for s in f['parent_segments']:
line=parent_lines[s['id']]
for station in s['interval_m']:
distance=np.linalg.norm(np.asarray(line.interpolate(station).coords[0])[:2]-endpoint[:2])
if distance<=.8:options.append((distance,s['id'],station))
bindings.append(None if not options else tuple(min(options)[1:]))
pieces.append(dict(id=f['id'],p=p,bindings=bindings,patch=patch['id'],parents=deepcopy(f['parent_segments']),properties=deepcopy(f['properties'])))
for s in patch.get('quarantine',[]):
line=parent_lines[s['id']]
if s['interval_m'][0]>EPS or line.length-s['interval_m'][1]>EPS:
raise ValueError('Partial-chain quarantine could create a hole')
cuts.setdefault(s['id'],[]).append(s['interval_m']);quarantine.append(s['id'])
for identity,f in parents.items():
line=parent_lines[identity]
for ordinal,(a,b)in enumerate(complement(cuts.get(identity,[]),line.length)):
part=substring(line,a,b);p=np.asarray(part.coords)
pieces.append(dict(id=identity+'-residual-'+str(ordinal),p=p,bindings=[(identity,a),(identity,b)],patch=None,parents=[dict(id=identity,interval_m=[a,b])],properties=deepcopy(f['properties'])))
index={}
for i,piece in enumerate(pieces):
for end,binding in enumerate(piece['bindings']):
if binding is not None:index.setdefault((binding[0],round(binding[1],5)),[]).append((i,end))
links={};seams=[];failures=[];graph_nodes=[]
for key,ends in sorted(index.items()):
parent,station=key;length=parent_lines[parent].length
internal=EPS<station<length-EPS
if len(ends)==1:
if internal:failures.append(dict(reason='unmatched-internal-station',parent=parent,station_m=station,patches=[pieces[ends[0][0]]['patch']]))
continue
if len(ends)!=2:
failures.append(dict(reason='ambiguous-station-degree',parent=parent,station_m=station,patches=[pieces[i]['patch']for i,_ in ends]));continue
(i,ei),(j,ej)=ends
if i==j:continue
a=pieces[i]['p']if ei else pieces[i]['p'][::-1];b=pieces[j]['p'][::-1]if ej else pieces[j]['p']
gap=float(np.linalg.norm(a[-1,:2]-b[0,:2]))
if gap<.01:
middle=(a[-1]+b[0])/2;a[-1]=middle;b[0]=middle
curve=np.stack([middle,middle]);trim_a=trim_b=0
else:
result=bridge_short_seam(a,b,max_gap=.8)
if result is None:
failures.append(dict(reason='seam-not-compatible',parent=parent,station_m=station,gap_m=gap,patches=[pieces[i]['patch'],pieces[j]['patch']]));continue
_,curve,_=result
# Convert the trimmed curve endpoints back to each original polyline.
trim_a=float(LineString(a[:,:2]).project(Point(curve[0,:2])))
trim_b=float(LineString(b[:,:2]).project(Point(curve[-1,:2])))
trim_a=LineString(a[:,:2]).length-trim_a
links[i,ei]=(j,ej,curve,trim_a,trim_b)
links[j,ej]=(i,ei,curve[::-1],trim_b,trim_a)
seams.append(dict(parent=parent,station_m=station,gap_m=gap,source_pieces=[pieces[i]['id'],pieces[j]['id']],method='shared-anchor'if gap<.01 else'local-hermite'))
graph_nodes.append(dict(id=parent+'@'+str(station),source_parent=parent,source_station_m=station,degree=2,incident_pieces=[pieces[i]['id'],pieces[j]['id']]))
out=[];visited=set()
for seed in range(len(pieces)):
if seed in visited:continue
# Find a component and its exterior end before walking it once.
component=set();pending=[seed]
while pending:
i=pending.pop()
if i in component:continue
component.add(i)
for end in (0,1):
if(i,end)in links:pending.append(links[i,end][0])
starts=[(i,end)for i in component for end in(0,1)if(i,end)not in links]
if not starts:raise ValueError('Patch seam assembly would close a curb')
i,entry=min(starts);first=(i,entry);points=[];ids=[];construction=[];owned=set();inferred=[]
while True:
if i in visited:raise ValueError('Cyclic seam links')
visited.add(i);piece=pieces[i];p=piece['p']if entry==0 else piece['p'][::-1];line=LineString(p)
low=links[i,entry][3]if(i,entry)in links else 0.
high=line.length-(links[i,1-entry][3]if(i,1-entry)in links else 0.)
if high<=low:raise ValueError('Seam trims overlap')
p=np.asarray(substring(line,low,high).coords)
points.extend(p if not points else p[1:]);ids.append(piece['id']);construction.append(dict(id=piece['id'],patch=piece['patch'],parents=piece['parents'],source_properties=deepcopy(piece['properties'])))
inferred.extend(collect_inferred(piece['properties']))
if piece['patch']:owned.add(piece['patch'])
if(i,1-entry)not in links:last=(i,1-entry);break
j,end,curve,_,_=links[i,1-entry];points.extend(curve[1:])
if LineString(curve).length>.01:inferred.append(dict(status='inferred',method='assembly-local-hermite',coordinates=curve.tolist()))
i,entry=j,end
line=LineString(points)
if not line.is_simple:failures.append(dict(reason='assembled-self-intersection',patches=sorted(owned)))
identity='scene-curb-'+hashlib.sha256('|'.join(sorted(ids)).encode()).hexdigest()[:16]
out.append(dict(type='Feature',id=identity,geometry=mapping(line),properties=dict(class_='road_boundary',method='source-station-assembly',construction=construction,patch_ids=sorted(owned),route_permission='unassigned',height_status='inherited-not-refitted',review_status='candidate-unreviewed',length_m=line.length)))
out[-1]['properties']['class']=out[-1]['properties'].pop('class_')
out[-1]['properties'].update(inferred_spans=clip_inferred(inferred,line),start_reason=pieces[first[0]]['properties'].get(('start_reason','end_reason')[first[1]],'input-end'),end_reason=pieces[last[0]]['properties'].get(('start_reason','end_reason')[last[1]],'input-end'))
untouched=[deepcopy(f)for f in source['features']if f['properties']['class']!='road_boundary']
result=deepcopy(source);result.update(features=untouched+out,review_status='candidate-unreviewed',scope='whole-source-scene',geometry_scope='schematic-xy',route_permission='unassigned')
audit=dict(schema='missioncore.source-station-assembly/v1',input_curbs=len(parents),output_curbs=len(out),patches=[p['id']for p in patches],quarantined_parent_ids=quarantine,seams=seams,failures=failures,graph_nodes=graph_nodes,non_curbs_preserved=len(untouched))
return result,audit
def collect_inferred(value):
"""Read uncertainty through nested construction without treating it as observation."""
if isinstance(value,list):return [s for v in value for s in collect_inferred(v)]
if not isinstance(value,dict):return []
out=[]
for key,v in value.items():
if key in ('inferred_spans','local_seams'):out.extend(deepcopy(v))
elif isinstance(v,(dict,list)):out.extend(collect_inferred(v))
return out
def clip_inferred(spans,line):
"""Keep uncertainty on the final XY chain, clipped to its actual extent."""
xy=LineString(np.asarray(line.coords)[:,:2]);buffer=xy.buffer(.05);out=[];seen=set()
for span in spans:
if not span.get('coordinates'):continue
raw=LineString(np.asarray(span['coordinates'])[:,:2]);clipped=raw.intersection(buffer)
parts=[clipped]if clipped.geom_type=='LineString'else [g for g in getattr(clipped,'geoms',[])if g.geom_type=='LineString']
for part in parts:
if part.length<.03:continue
a,b=sorted(xy.project(Point(p))for p in np.asarray(part.coords)[[0,-1]])
if b-a<.03:continue
key=(round(a,2),round(b,2))
if key in seen:continue
seen.add(key);item=deepcopy(span);curve=substring(line,a,b)
item.update(coordinates=list(curve.coords),length_m=curve.length,status='inferred',station_interval_m=[a,b]);out.append(item)
return out
def assemble_checked(source, patches):
"""Reject whole replacement proposals that introduce geometry conflicts.
Original parent chains are restored atomically. No point is moved or erased
to hide a conflict, and no scene identity participates in this decision.
"""
active=list(patches);rejected=[]
while True:
result,audit=assemble(source,active)
curbs=[f for f in result['features'] if f['properties']['class']=='road_boundary']
bad=set();unowned=False
for i,f in enumerate(curbs):
line=shape(f['geometry']);owners=set(f['properties']['patch_ids'])
if not line.is_simple:
bad.update(owners);unowned|=not owners
for g in curbs[i+1:]:
if line.intersects(shape(g['geometry'])):
owners_pair=owners|set(g['properties']['patch_ids'])
bad.update(owners_pair);unowned|=not owners_pair
if unowned:
raise ValueError('Source curb geometry has an unresolved conflict')
if not bad:
audit['rejected_geometry']=rejected
return result,audit
rejected.extend(dict(id=p['id'],reason='assembled-geometry-conflict') for p in active if p['id'] in bad)
active=[p for p in active if p['id'] not in bad]