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

146 lines
9.7 KiB
Python

"""Object-level XY evidence, with explicit partial-view observability."""
import cv2
import numpy as np
import shapely
from arrow_admission import POLICY
from plan_marking_policy import MIN_SOURCE_CORRESPONDENCE
def branch_evidence(paint, allowed, observed, points, polygon, kind, parameters, cell=.04):
if kind not in ('straight_left_arrow','straight_right_arrow'):
return None
px,py,angle,length,width,_ = parameters[:6]
axis=np.array([np.cos(angle),np.sin(angle)]);normal=np.array([-axis[1],axis[0]])
local=points-[px,py];longitudinal=(local@axis).reshape(paint.shape);lateral=(local@normal).reshape(paint.shape)
target=shapely.contains_xy(polygon,points[:,0],points[:,1]).reshape(paint.shape)
head=target&(longitudinal>length*.80)
branch=target&(lateral*(1 if 'left' in kind else -1)>width*.24)&(longitudinal<length*.80)
k=max(3,int(round(.08/cell))//2*2+1)
closed=cv2.morphologyEx((paint&allowed&observed).astype('uint8'),cv2.MORPH_CLOSE,
cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k,k)))
# Wear closing cannot manufacture a connection through an unseen image.
closed &= observed.astype('uint8')
_,labels=cv2.connectedComponents(closed,8)
ids,counts=np.unique(labels[head&paint&allowed&observed],return_counts=True);present=ids>0
owner=int(ids[present][np.argmax(counts[present])]) if present.any() else -1
connected=(labels==owner)&paint&allowed&observed
near=cv2.dilate(connected.astype('uint8'),np.ones((3,3),'uint8'))>0
valid=branch&allowed&observed
unresolved=np.zeros(paint.shape,bool)
if not observed.all():
_,unknown_labels=cv2.connectedComponents((~observed).astype('uint8'),8)
head_touch=cv2.dilate((labels==owner).astype('uint8'),np.ones((3,3),'uint8'))>0 if owner>0 else np.zeros(paint.shape,bool)
head_unknown=set(np.unique(unknown_labels[(head_touch|head)&~observed]))-{0}
for label in set(np.unique(labels[valid]))-{0}:
if label==owner:continue
component=labels==label
adjacent=cv2.dilate(component.astype('uint8'),np.ones((3,3),'uint8'))>0
if head_unknown.intersection(set(np.unique(unknown_labels[adjacent&~observed]))):
unresolved |= adjacent&valid&~near
resolvable=valid&~unresolved
return dict(coverage=float(observed[branch].mean()) if branch.any() else 0.,
valid=float(allowed[branch&observed].mean()) if (branch&observed).any() else 0.,
head_connected_support=float(near[resolvable].mean()) if resolvable.any() else 0.,
direct_support=float(paint[valid].mean()) if valid.any() else 0.,pixels=int(valid.sum()),
connection_resolvable_pixels=int(resolvable.sum()),
connection_unobserved_pixels=int(unresolved.sum()),
connection_domain='observed paths; shared unseen boundary remains unknown')
def assess(ev, score, containment, fit, kind):
failures=[];unknown=[];margins=[]
numeric=['surface_validity','paint_support','negative_paint','paint_recall','connected_recall',
'head_pixels:left','head_pixels:right','head_validity:left','head_validity:right','head_support',
'branch_pixels','branch_validity','branch_direct_support','branch_head_connection','head_flank_paint']
numeric += [prefix+':'+part for prefix in ['part_validity','part_support'] for part in ['head','tail','branch']]
numeric += [prefix+':'+end for prefix in ['endpoint_validity','endpoint_continuation'] for end in ['head','tail']]
structural_names=['primary_complete_coverage','coverage','object_at_window_edge','parts_and_ends','branch_evidence','head_evidence','primary_branch_connection_unobserved']
constraints={name:1. for name in ['global/semantic_score','global/semantic_containment','global/source_correspondence','global/two_view_records']}
constraints.update({str(rank)+'/'+name:1. for rank in range(2) for name in numeric+structural_names})
def record(name,value,rank):
key=('global' if rank is None else str(rank))+'/'+name
if key not in constraints:raise ValueError('Undeclared admission constraint '+key)
constraints[key]=float(value)
def encoded():return dict(constraint_names=sorted(constraints),constraint_values=[constraints[k] for k in sorted(constraints)])
def minimum(name,value,limit,rank=None):
margins.append(float(value-limit));record(name,value-limit,rank)
if value<limit:failures.append(dict(check=name,rank=rank,value=value,minimum=limit))
def maximum(name,value,limit,rank=None):
margins.append(float(limit-value));record(name,limit-value,rank)
if value>limit:failures.append(dict(check=name,rank=rank,value=value,maximum=limit))
minimum('semantic_score',score,POLICY['bicycle_semantic_score' if kind=='bicycle' else 'arrow_semantic_score'])
minimum('semantic_containment',containment,POLICY['min_semantic_fraction'])
minimum('source_correspondence',fit,MIN_SOURCE_CORRESPONDENCE)
if len(ev)!=2:
constraints['global/two_view_records']=-1.
return dict(accepted=False,failures=[dict(check='two_view_records')],unobserved=[],minimum_margin=-1.,**encoded())
for rank,e in enumerate(ev):
coverage=e['paint_coverage'];compound=kind in ('straight_left_arrow','straight_right_arrow')
if rank==0:
constraints['0/primary_complete_coverage']=coverage-1.
if coverage!=1.:failures.append(dict(check='primary_complete_coverage',rank=rank,value=coverage))
if rank and coverage==0.:continue
if coverage<=0:
failures.append(dict(check='coverage',rank=rank,value=coverage));continue
minimum('surface_validity',e['paint_valid']/coverage,POLICY['min_valid'],rank)
minimum('paint_support',e['observed_support'],POLICY['compound_support'] if compound else POLICY['min_observed_support'],rank)
maximum('negative_paint',e['negative_paint'],POLICY['max_negative_paint'],rank)
if rank==0:minimum('paint_recall',e['recall'],POLICY['min_recall'],rank)
if coverage==1.:
minimum('connected_recall',e.get('connected_recall',0),POLICY['min_connected_recall'],rank)
if e.get('connected_at_window_edge',True):failures.append(dict(check='object_at_window_edge',rank=rank))
if kind!='bicycle':
if not e.get('parts') or not e.get('ends'):failures.append(dict(check='parts_and_ends',rank=rank))
for p in e.get('parts',[]):
if rank and p.get('coverage',1)==0:continue
support=POLICY.get('compound_'+p['part']+'_support',.90) if compound else (.5 if p['part']=='tail' else .9)
minimum('part_validity:'+p['part'],p['valid'],POLICY['min_part_valid'],rank)
minimum('part_support:'+p['part'],p['support'],support,rank)
for p in e.get('ends',[]):
if rank and p.get('coverage',1)==0:continue
minimum('endpoint_validity:'+p['end'],p['valid'],.97,rank)
maximum('endpoint_continuation:'+p['end'],p['paint_fraction'],.25,rank)
if kind in ('straight_arrow','straight_left_arrow','straight_right_arrow'):
wings=e.get('head_identity')
if not wings or len(wings)!=2:
failures.append(dict(check='head_evidence',rank=rank))
else:
for wing in wings:
if rank and wing['coverage']==0:continue
suffix=':'+wing['wing']
minimum('head_pixels'+suffix,wing['pixels']*wing['direct_support'],5,rank)
minimum('head_validity'+suffix,wing['valid'],POLICY['min_part_valid'],rank)
# Both wings must contain real paint, while wear is measured
# over the complete distinguishing head area. Requiring each
# half independently to be pristine rejects asymmetric wear.
visible=[w for w in wings if w['coverage']>0]
total=sum(w['pixels'] for w in visible)
direct=sum(w['pixels']*w['direct_support'] for w in visible)/max(total,1e-12)
minimum('head_support',direct,POLICY['min_branch_direct_support'],rank)
if compound:
b=e.get('branch_identity')
if b is None:
failures.append(dict(check='branch_evidence',rank=rank));continue
if rank and b['coverage']==0:continue
minimum('branch_pixels',b['pixels'],5,rank)
minimum('branch_validity',b['valid'],POLICY['min_part_valid'],rank)
minimum('branch_direct_support',b['direct_support'],POLICY['min_branch_direct_support'],rank)
measurable=b.get('connection_resolvable_pixels',b['pixels'])
if measurable:
minimum('branch_head_connection',b['head_connected_support'],POLICY['min_branch_connected_support'],rank)
elif rank:
unknown.append(dict(check='branch_head_connection',rank=rank,reason='connection exits observation footprint'))
else:
failures.append(dict(check='primary_branch_connection_unobserved',rank=rank))
if kind=='straight_arrow':maximum('head_flank_paint',e.get('head_flank_paint',1),POLICY['max_head_flank_paint'],rank)
for failure in failures:
if 'minimum' not in failure and 'maximum' not in failure and failure['check']!='primary_complete_coverage':
constraints[str(failure.get('rank',0))+'/'+failure['check']]=-1.
structural=any('minimum' not in f and 'maximum' not in f for f in failures)
return dict(accepted=not failures,failures=failures,unobserved=unknown,
minimum_margin=-1. if structural else min(margins,default=1.),**encoded())
def accept_symbol(ev,score,containment,fit,kind):
return assess(ev,score,containment,fit,kind)['accepted']