Files
NODEDC_MISSION_CORE/simulation/urban-plan-research/systematic/joint_assembly.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

107 lines
6.6 KiB
Python

"""Compile typed conflicts and fixed evidence for admitted whole families."""
from collections import defaultdict, Counter
import hashlib,json,time
import numpy as np,shapely
from shapely.geometry import shape
from marking_rules import isolated_addition,POLICY
from joint_choice import choose
CELL=.05
def geom(f):return shapely.force_2d(shape(f['geometry']))
def cells(p):
"""Fixed world lattice; sampling density cannot grow with hypothesis count."""
result=set()
for q in getattr(p,'geoms',[p]):
lo=np.floor(np.array(q.bounds[:2])/CELL).astype(int)
hi=np.ceil(np.array(q.bounds[2:])/CELL).astype(int)
xx=np.arange(lo[0],hi[0]+1)
for start in range(lo[1],hi[1]+1,32):
yy=np.arange(start,min(start+32,hi[1]+1));x,y=np.meshgrid(xx,yy)
mask=shapely.contains_xy(q,(x+.5)*CELL,(y+.5)*CELL)
result.update(zip(x[mask].tolist(),y[mask].tolist()))
return result
def select(old,configurations,appearance):
started=time.monotonic();base={f['id']:f for f in old['features']}
nodes=[];payload={};geometry={};domains={};atoms={}
for f in old['features']:
if f['properties'].get('subtype')!='linear_marking':continue
key='keep:'+f['id'];payload[key]=dict(after=[f],source_ids=[f['id']],atomic_family=False)
nodes.append(dict(id=key,sources=[f['id']],cost=0.,incumbent=True))
for transaction in configurations:
identity=dict(sources=sorted(transaction['source_ids']),after=sorted(f['id'] for f in transaction['after']),kind=transaction['kind'])
key=hashlib.sha256(json.dumps(identity,sort_keys=True).encode()).hexdigest()
if key in payload:continue
payload[key]=transaction
nodes.append(dict(id=key,sources=transaction['source_ids'],cost=0.,incumbent=False))
nodes.sort(key=lambda n:n['id'])
for n in nodes:
key=n['id'];t=payload[key]
geometry[key]=shapely.union_all([geom(f) for f in t['after']])
atoms[key]=cells(geometry[key])
if t.get('domain'):domains[key]=shape(t['domain'])
# Immutable observations from this run, before candidate assembly. Native
# source records identify a positive sample. This ranking never admits
# an object: all existing typed two-view gates ran before this function.
observations=[r for r in appearance if r['properties'].get('source_tile')]
polygons=[shape(r['geometry']) for r in observations]
tree=shapely.STRtree(polygons);all_cells=sorted(set().union(*atoms.values())) if atoms else []
positive=set()
for start in range(0,len(all_cells),10000):
chunk=all_cells[start:start+10000];xy=(np.asarray(chunk,float)+.5)*CELL
pairs=tree.query(shapely.points(xy),predicate='intersects');sources=defaultdict(set)
for pi,oi in zip(*pairs):sources[int(pi)].add(observations[int(oi)]['properties']['source_tile'])
positive.update(chunk[i] for i,names in sources.items() if names)
membership=defaultdict(list)
complexity_scale=.25/max(1.,sum(1.+.01*len(payload[n['id']]['after']) for n in nodes))
for n in nodes:
key=n['id'];a=atoms[key];supported=a&positive
for cell in supported:membership[cell].append(key)
# Missing primary-mask evidence is UNKNOWN, not observed dark road.
# Contradictions are enforced by the existing two-view admission gates.
# Complexity is only a small tie-breaker below one metric sample.
n['cost']=complexity_scale*(1.+.01*len(payload[key]['after']))
conflicts=[];types=Counter();keys=[n['id'] for n in nodes]
envelopes=[geometry[k].union(domains[k]) if k in domains else geometry[k] for k in keys]
spatial=shapely.STRtree([p.buffer(POLICY['max_join_gap_m']) for p in envelopes])
geometry_array=np.array([geometry[key] for key in keys],dtype=object)
for i,key in enumerate(keys):
neighbors=np.array([int(j) for j in spatial.query(envelopes[i]) if j>i],dtype=int)
# The same GEOS intersection/area test, batched to avoid hundreds of
# thousands of Python-to-GEOS calls on overlapping family subseries.
overlap={}
for start in range(0,len(neighbors),4096):
ids=neighbors[start:start+4096]
areas=shapely.area(shapely.intersection(geometry[key],geometry_array[ids]))
overlap.update(zip(ids.tolist(),(areas>POLICY['max_overlap_m2']).tolist()))
for j in neighbors:
j=int(j)
other=keys[j];a=payload[key];b=payload[other]
# Fresh incumbent may contain overlapping provisional fragments;
# retain it as a feasible fallback, never silently erase them.
if key.startswith('keep:') and other.startswith('keep:'):continue
reason=None
if set(a['source_ids'])&set(b['source_ids']):reason='alternative-explanation'
elif overlap[j]:reason='positive-paint-overlap'
elif key in domains and other in domains and domains[key].intersection(domains[other]).area>POLICY['max_overlap_m2']:reason='incompatible-family-domain'
elif key in domains and domains[key].intersection(geometry[other]).area>POLICY['max_overlap_m2']:reason='family-gap-ownership'
elif other in domains and domains[other].intersection(geometry[key]).area>POLICY['max_overlap_m2']:reason='family-gap-ownership'
elif not a.get('atomic_family') and not b.get('atomic_family'):
left=a.get('seam_members',a['after']);right=b.get('seam_members',b['after'])
if any(not isolated_addition(geom(f),{g['id']:g for g in right}) for f in left):reason='unresolved-line-seam'
if reason:conflicts.append((key,other));types[reason]+=1
selected,report=choose(nodes,conflicts,[(ids,1.) for ids in membership.values()])
chosen=set(selected);current={i:f for i,f in base.items() if f['properties'].get('subtype')!='linear_marking'};transactions=[]
for key in selected:
t=payload[key]
for f in t['after']:
assert f['id'] not in current,'Conflicting selected feature identifiers'
current[f['id']]=f
if not key.startswith('keep:'):transactions.append(t)
report.update(configurations=len(configurations),unique_configurations=len(nodes),selected_configurations=len(selected),fixed_positive_samples=len(positive),metric_cell_m=CELL,conflicts=dict(types),source='current-run-primary-observations',old_control_input=False,seconds_total=time.monotonic()-started)
report['choices']=[dict(id=n['id'],selected=n['id'] in chosen,source_ids=n['sources'],incumbent=n['incumbent'],positive_samples=len(atoms[n['id']]&positive),cost=n['cost']) for n in nodes]
return current,transactions,report