"""Read-only object forensics. Reference geometry is evaluation input only.""" from pathlib import Path import json import cv2 import numpy as np import shapely from shapely.geometry import shape from ground_observations import GroundObservations, read, POLICY, sha from fit_scene import project from row_evidence import choose_owners from standard_arrow_templates import polygon from standard_arrow_evidence import metrics def audit(): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt out=Path('/out'); result=Path('/result') registry=json.loads((result/'candidates.json').read_text()) di=json.loads((result/'diagnostics.json').read_text()) byid={d['candidate']:d for d in di} refs=[f for f in json.loads(Path('/reference.json').read_text())['features'] if 'arrow' in f['properties'].get('subtype','')] objects=[dict(feature=f,source='historical') for f in refs] for file,label in [(result/'arrow-observations.json','current'),(Path('/previous.json'),'first-prototype')]: if not file.is_file():continue for f in json.loads(file.read_text())['features']: q=shapely.force_2d(shape(f['geometry'])) if not any(q.intersection(shapely.force_2d(shape(o['feature']['geometry']))).area/ max(q.union(shapely.force_2d(shape(o['feature']['geometry']))).area,1e-9)>.1 for o in objects): objects.append(dict(feature=f,source=label)) obs=GroundObservations(); compatibility=GroundObservations();compatibility.native=None;reports=[] for index,item in enumerate(objects): f=item['feature']; ref=shapely.force_2d(shape(f['geometry'])) row=max(registry['candidates'],key=lambda r:ref.intersection(shape(r['extent'])).area/max(ref.area,1e-9)) d=byid[row['id']]; extent=shape(row['extent']); grid=obs.grid(extent) options=d.get('options',[]) matching=[o for o in options if o['kind']==f['properties']['subtype']] best=max(matching or options,key=lambda o:o['metrics'][0]['iou']) if options else None q=polygon(best['kind'],best['profile'],best['pose']) if best else ref pts=grid['points']; size=grid['size']; mask=shapely.contains_xy(q,pts[:,0],pts[:,1]).reshape(size) rmask=shapely.contains_xy(ref,pts[:,0],pts[:,1]).reshape(size) distance=np.linalg.norm(pts[:,None]-obs.centers[None],axis=2); cover=np.zeros(distance.shape,bool) for k,tile in enumerate(obs.tiles): uv=project(pts,obs.camera(tile['id']));cover[:,k]=(uv.min(1)>=20)&(uv.max(1)<1180) owners=choose_owners(distance,cover) fields={k:np.zeros(len(pts),float) for k in ['context_alpha','ground_alpha','gap','span','finite','known','agree','neighborhood','flat']} for k in np.unique(owners[:,0]): if k<0:continue ix=np.flatnonzero(owners[:,0]==k);name=obs.tiles[k]['id'];a=obs.geometry(name);b=obs.geometry(name,True) uv=project(pts[ix],a);finite=np.isfinite(a['depth'])&np.isfinite(b['depth'])&(a['depth']>0)&(b['depth']>0) ratio=b['depth'].shape[0]/int(b.get('compatibility_resolution',b['depth'].shape[0])) width=2*int(np.ceil((POLICY['local_window_px']-1)/2*ratio))+1 kernel=np.ones((width,)*2,'uint8');safe=np.where(finite,b['depth'],0).astype('float32') span=cv2.dilate(safe,kernel)-cv2.erode(safe,kernel) arrays=dict(context_alpha=a['alpha'],ground_alpha=b['alpha'],gap=np.abs(a['depth']-b['depth']),span=span, finite=finite,known=finite&(a['alpha']>=POLICY['alpha_min'])&(b['alpha']>=POLICY['alpha_min']),agree=np.abs(a['depth']-b['depth'])<=POLICY['depth_agreement_m'], neighborhood=cv2.erode(finite.astype('uint8'),kernel)>0,flat=span<=POLICY['local_depth_span_m']) for key,value in arrays.items():fields[key][ix]=read(value.astype('float32'),uv,nearest=key not in ['context_alpha','ground_alpha','gap']).ravel() fields['gap'][ix]=np.abs(read(a['depth'],uv).ravel()-read(b['depth'],uv).ravel()) fields['known'][ix]=(fields['finite'][ix]>0)&(fields['context_alpha'][ix]>=POLICY['alpha_min'])&(fields['ground_alpha'][ix]>=POLICY['alpha_min']) fields['agree'][ix]=fields['gap'][ix]<=POLICY['depth_agreement_m'] fields={k:v.reshape(size) for k,v in fields.items()} stats={} for scope,m in [('reference',rmask),('fixed_proposal',mask)]: stats[scope]={k:float(v[m].mean()) for k,v in fields.items() if k in ['finite','known','agree','neighborhood','flat']} stats[scope].update({k:np.quantile(v[m],[0,.01,.05,.5,.95,.99,1]).tolist() for k,v in fields.items() if k in ['context_alpha','ground_alpha','gap','span']}) stats[scope]['allowed']=float(grid['views'][0]['allowed'][m].mean()) old_grid=compatibility.grid(extent);old_grid['angle']=best['pose'][2] if best else 0 grid['angle']=best['pose'][2] if best else 0 reports.append(dict(index=index+1,reference_id=f['id'],reference_kind=f['properties']['subtype'],source=item['source'], candidate=row['id'],group=row['group'],patch=row['patch'],diagnostic=d, reference_geometry=ref.__geo_interface__,surface=stats, historical_on_current_surface=metrics(ref,grid,grid['views'][0]), proposal_on_compatibility_surface=metrics(q,old_grid,old_grid['views'][0]), proposal_on_current_surface=metrics(q,grid,grid['views'][0]),native_geometry=bool(obs.native),source_tiles=grid['views'][0]['names'])) fig,axes=plt.subplots(1,5,figsize=(18,4)) rgb=grid['views'][0]['rgb'];axes[0].imshow(rgb);axes[0].set_title('Original top view') axes[1].imshow(rgb);axes[1].set_title('Reference / fixed proposal / semantic') for poly,col in [(ref,'yellow'),(q,'cyan'),(extent,'magenta')]: uv=(shapely.get_coordinates(poly)-grid['lo'])/grid['cell'];axes[1].plot(uv[:,0],uv[:,1],color=col,linewidth=.8) axes[2].imshow(rgb);bad=~grid['views'][0]['allowed'];red=np.zeros((*size,4));red[bad]=[1,0,0,.65];axes[2].imshow(red);axes[2].set_title('Rejected surface (red)') axes[3].imshow(fields['gap'],vmin=0,vmax=.3,cmap='magma');axes[3].set_title('Context-ground gap (0..0.3m)') axes[4].imshow(fields['span'],vmin=0,vmax=.4,cmap='magma');axes[4].set_title('Metric neighbourhood depth span (0..0.4m)') for ax in axes:ax.axis('off') fig.suptitle(f'{index+1}: {item["source"]} {f["id"]} group {row["group"]} {d.get("reject","accepted")}') fig.tight_layout();fig.savefig(out/f'object-{index+1:02d}.png',dpi=130);plt.close(fig) print('AUDITED',index+1,row['group'],stats['reference']['allowed'],flush=True) (out/'object-audit.json').write_text(json.dumps(dict(objects=reports,reference_sha256=sha('/reference.json'), result_sha256=sha(result/'arrow-observations.json'),geometry_mutated=False),indent=2)) if __name__=='__main__':audit()