Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
200 lines
12 KiB
Python
200 lines
12 KiB
Python
"""Remeasure accepted presets from immutable raw observations, then render review."""
|
|
from pathlib import Path
|
|
import json
|
|
import cv2
|
|
import numpy as np
|
|
import shapely
|
|
from shapely.geometry import shape
|
|
from ground_observations import GroundObservations, sha
|
|
from candidate_registry import verify
|
|
from standard_arrow_templates import polygon, dimensions
|
|
from standard_arrow_evidence import metrics
|
|
from plan_marking_policy import registration_passes as passes, CONTRACT, source_correspondence
|
|
from observation_checks import accept_symbol
|
|
from recall_extent import semantic_recall
|
|
from object_evidence import evidence
|
|
from admission_contract import AdmissionContract
|
|
from preservation import compare
|
|
from reconcile_objects import reconcile
|
|
|
|
|
|
def verify_result(result='/result', symbols='/symbolplan', out='/out'):
|
|
result, symbols, out = map(Path, [result, symbols, out])
|
|
obs = GroundObservations()
|
|
inventory = json.loads((result/'observations.json').read_text())
|
|
if obs.inventory() != inventory:
|
|
raise ValueError('Raw orthographic observations changed')
|
|
registry = json.loads((result/'candidates.json').read_text())
|
|
verify(symbols, registry)
|
|
rows = {r['id']:r for r in registry['candidates']}
|
|
features = json.loads((result/'arrow-observations.json').read_text())['features']
|
|
checks = []
|
|
for f in features:
|
|
props = f['properties']; spec = props['preset']; row = rows[props['candidate_id']]
|
|
q = shape(f['geometry']); extent, region, target = [shape(row[k]) for k in ['extent','region','target']]
|
|
clean = polygon(spec['kind'], spec['profile'], spec['pose'])
|
|
assert spec['transform'] == 'similarity' and len(spec['pose']) == 4
|
|
assert q.is_valid and np.isfinite(shapely.get_coordinates(q)).all()
|
|
assert clean.symmetric_difference(q).area < 1e-8
|
|
assert props['authority'] == 'observation-only' and props['route_permission'] == 'unassigned'
|
|
assert props['admission_contract']==CONTRACT and props['geometry_domain']=='plan-xy'
|
|
assert props['depth_quality']==obs.depth_quality(obs.grid(extent,cell=.04),q)
|
|
peers=[r for r in registry['candidates'] if r['group']==row['group']]
|
|
contract=AdmissionContract(peers,extent,obs.grid(extent),obs.grid(extent,cell=.04))
|
|
measured=contract.measure(q,spec['kind'],spec['profile'],spec['pose'],independent=True)
|
|
assert measured['accepted']
|
|
# Independently bind the exact recorded witness as well as the pool.
|
|
# Sharing contract definitions never substitutes for remeasurement.
|
|
contain=q.intersection(region.buffer(.2)).area/max(q.area,1e-9)
|
|
fit_score=source_correspondence(q,target)
|
|
assert accept_symbol(measured['evidence'],row['semantic_score'],contain,fit_score,spec['kind'])
|
|
checks.append(dict(id=f['id'],metrics=measured['metrics'],evidence=measured['evidence'],witness=measured['witness']))
|
|
output = dict(passed=True, accepted=len(features), original_pixels_remeasured=True,
|
|
immutable_presets=True, unchanged_observation_snapshot=inventory['snapshot'],
|
|
source_registry_verified=True, source_result_sha256=sha(result/'arrow-observations.json'),
|
|
checks=checks, recall_measured=False, published=False)
|
|
(out/'verification.json').write_text(json.dumps(output, indent=2))
|
|
reference = Path('/reference.json')
|
|
if reference.is_file():
|
|
old = [f for f in json.loads(reference.read_text())['features']
|
|
if 'arrow' in f['properties'].get('subtype','')]
|
|
pairs = []
|
|
for f in features:
|
|
q = shape(f['geometry']); matches = []
|
|
for previous in old:
|
|
p = shapely.force_2d(shape(previous['geometry']))
|
|
overlap = q.intersection(p).area/max(q.union(p).area, 1e-9)
|
|
if overlap > .1:
|
|
matches.append(dict(reference_id=previous['id'], iou=overlap,
|
|
hausdorff_m=q.hausdorff_distance(p),
|
|
reference_kind=previous['properties']['subtype']))
|
|
pairs.append(dict(candidate_id=f['id'], candidate_kind=f['properties']['subtype'],
|
|
matches=sorted(matches, key=lambda x:-x['iou'])))
|
|
matched = {m['reference_id'] for row in pairs for m in row['matches']}
|
|
candidate_coverage = []
|
|
for previous in old:
|
|
p = shapely.force_2d(shape(previous['geometry']))
|
|
proposals = []
|
|
for row in registry['candidates']:
|
|
extent = shape(row['extent'])
|
|
fraction = p.intersection(extent).area/max(p.area, 1e-9)
|
|
if fraction >= .5:
|
|
proposals.append(dict(candidate=row['id'], fraction=fraction, patch=row['patch']))
|
|
candidate_coverage.append(dict(reference_id=previous['id'], proposals=proposals))
|
|
(out/'comparison.json').write_text(json.dumps(dict(reference_sha256=sha(reference),
|
|
reference_arrows=len(old), reconstructed_arrows=len(features), pairs=pairs,
|
|
candidate_coverage=candidate_coverage, reference_seen_by_candidates=sum(bool(r['proposals']) for r in candidate_coverage),
|
|
unmatched_reference=[f['id'] for f in old if f['id'] not in matched],
|
|
reference_is_ground_truth=False, recall_measured=False), indent=2))
|
|
confirmed=Path('/confirmed-reference.json')
|
|
if confirmed.is_file():
|
|
preservation=compare(json.loads(confirmed.read_text()),dict(features=features))
|
|
preservation['reference_sha256']=sha(confirmed)
|
|
(out/'preservation.json').write_text(json.dumps(preservation,indent=2))
|
|
render_unresolved(obs,result,out,json.loads(confirmed.read_text()),registry,preservation)
|
|
if reference.is_file():
|
|
assembled,ledger=reconcile(reference.read_bytes(),(result/'arrow-observations.json').read_bytes(),output)
|
|
(out/'map-preview.json').write_text(json.dumps(assembled,allow_nan=False))
|
|
(out/'reconciliation.json').write_text(json.dumps(ledger,indent=2))
|
|
if confirmed.is_file():
|
|
retained=compare(json.loads(confirmed.read_text()),dict(features=[f for f in assembled['features'] if 'arrow' in f['properties'].get('subtype','')]))
|
|
retained['scope']='assembled map including explicitly retained previous geometry; NOT fresh reconstruction'
|
|
(out/'map-preservation.json').write_text(json.dumps(retained,indent=2))
|
|
render_review(result, symbols, out, features, rows)
|
|
print('VERIFIED', len(features), flush=True)
|
|
|
|
|
|
def render_unresolved(obs,result,out,confirmed,registry,preservation):
|
|
import matplotlib
|
|
matplotlib.use('Agg')
|
|
import matplotlib.pyplot as plt
|
|
from observation_checks import assess
|
|
diagnostics=json.loads((result/'diagnostics.json').read_text());records=[]
|
|
for f in confirmed['features']:
|
|
if f['id'] not in preservation['missing']:continue
|
|
reference=shapely.force_2d(shape(f['geometry']))
|
|
row=max(registry['candidates'],key=lambda r:reference.intersection(shape(r['extent'])).area/max(reference.area,1e-9))
|
|
peers=[r for r in registry['candidates'] if r['group']==row['group']]
|
|
options=[o for d in diagnostics if d['group']==row['group'] for o in d.get('options',[]) if o['kind']==f['properties']['subtype']]
|
|
if not options:
|
|
records.append(dict(reference_id=f['id'],group=row['group'],reason='no same-class pose hypothesis'));continue
|
|
extent=shape(row['extent'])
|
|
contract=AdmissionContract(peers,extent,obs.grid(extent),obs.grid(extent,cell=.04))
|
|
evaluated=[]
|
|
for option in options:
|
|
q=polygon(option['kind'],option['profile'],option['pose'])
|
|
measured=contract.measure(q,option['kind'],option['profile'],option['pose'],independent=True)
|
|
evaluated.append((measured['constraint_violation'],-option['metrics'][0]['iou'],option,measured))
|
|
_,_,option,measured=min(evaluated,key=lambda v:v[:2])
|
|
q=polygon(option['kind'],option['profile'],option['pose']);grid=obs.grid(extent,cell=.04)
|
|
admitted=measured['admission']
|
|
filename='unresolved-'+str(row['group'])+'.png'
|
|
records.append(dict(reference_id=f['id'],group=row['group'],image=filename,proposal=option,
|
|
admission=admitted,witness=measured['witness'],constraint_violation=measured['constraint_violation'],semantic_recall=measured['recall'],evaluation_only=True))
|
|
fig,axes=plt.subplots(2,2,figsize=(13,7))
|
|
for rank,view in enumerate(grid['views']):
|
|
axes[rank,0].imshow(view['rgb']);axes[rank,0].set_title('Original RGB / view '+str(rank))
|
|
shown=np.zeros((*grid['size'],3));shown[view['paint']]=[1,1,1];shown[~view['allowed']&view['observed']]=[.6,0,0]
|
|
axes[rank,1].imshow(shown);axes[rank,1].set_title('Shared paint; uncertain surface in red')
|
|
for ax in axes[rank]:
|
|
for poly,col in [(reference,'yellow'),(q,'cyan')]:
|
|
uv=(shapely.get_coordinates(poly)-grid['lo'])/grid['cell'];ax.plot(uv[:,0],uv[:,1],color=col,linewidth=.8)
|
|
ax.axis('off')
|
|
fig.suptitle(f['id']+' / '+option['kind']+' / group '+str(row['group']))
|
|
fig.tight_layout();fig.savefig(out/filename,dpi=115);plt.close(fig)
|
|
(out/'unresolved-review.json').write_text(json.dumps(records,indent=2))
|
|
|
|
|
|
def render_review(result, symbols, out, features, rows):
|
|
from PIL import Image
|
|
import matplotlib
|
|
matplotlib.use('Agg')
|
|
import matplotlib.pyplot as plt
|
|
patches = {p['id']:p for p in json.loads((symbols/'symbol-patches.json').read_text())['patches']}
|
|
diagnostics = json.loads((result/'diagnostics.json').read_text())
|
|
feature_by_candidate = {f['properties']['candidate_id']:f for f in features}
|
|
selected = [d for d in diagnostics if 'accepted' in d]
|
|
rejects = sorted([d for d in diagnostics if d.get('direct_options') and 'accepted' not in d],
|
|
key=lambda d:-max(x['score'] for x in d['direct_options']))
|
|
selected += rejects[:max(0, 8-len(selected))]
|
|
selected = selected[:24]
|
|
review = []
|
|
for offset in range(0, len(selected), 4):
|
|
group = selected[offset:offset+4]
|
|
figure, axes = plt.subplots(len(group), 2, figsize=(12, 5*len(group)), squeeze=False)
|
|
for i, diagnostic in enumerate(group):
|
|
row = rows[diagnostic['candidate']]; patch = patches[row['patch']]
|
|
image_path = symbols/'symbol-patches'/(row['patch']+'.png')
|
|
with Image.open(image_path) as im:
|
|
image = np.asarray(im.convert('RGB'))
|
|
h, w = image.shape[:2]
|
|
matrix = cv2.getPerspectiveTransform(np.asarray(patch['world_corners'], 'float32'),
|
|
np.asarray([[0,0],[w,0],[w,h],[0,h]], 'float32'))
|
|
def draw(ax, geometry, color, label):
|
|
xy = shapely.get_coordinates(geometry)
|
|
uv = cv2.perspectiveTransform(xy.astype('float32')[None], matrix)[0]
|
|
ax.plot(uv[:,0], uv[:,1], color=color, linewidth=1., label=label)
|
|
f = feature_by_candidate.get(row['id'])
|
|
focus=shape(row['extent']).buffer(.6)
|
|
uv=cv2.perspectiveTransform(shapely.get_coordinates(focus).astype('float32')[None],matrix)[0]
|
|
low=np.maximum(uv.min(0),[0,0]);high=np.minimum(uv.max(0),[w,h])
|
|
for ax in axes[i]:
|
|
ax.imshow(image); ax.set_xlim(low[0],high[0]); ax.set_ylim(high[1],low[1]); ax.axis('off')
|
|
axes[i,0].set_title('Original Gaussian top-view crop: '+row['patch'])
|
|
draw(axes[i,1], shape(row['extent']), '#ffd43b', 'semantic extent')
|
|
if f:
|
|
draw(axes[i,1], shape(f['geometry']), '#00e5ff', 'accepted fixed preset')
|
|
title = 'ACCEPTED: '+f['properties']['subtype']
|
|
else:
|
|
option = diagnostic['direct_options'][0]
|
|
draw(axes[i,1], polygon(option['kind'], option['profile'], option['pose']), '#ff6969', 'rejected proposal')
|
|
title = 'REJECTED: '+diagnostic.get('reject','unknown')
|
|
axes[i,1].set_title(title); axes[i,1].legend(loc='lower right')
|
|
review.append(dict(candidate=row['id'], patch=row['patch'], accepted=bool(f), source_sha256=sha(image_path)))
|
|
figure.tight_layout(); figure.savefig(out/f'review-{offset//4:02d}.png', dpi=120); plt.close(figure)
|
|
(out/'review.json').write_text(json.dumps(review, indent=2))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
verify_result()
|