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.
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
# Observed plan markings from supplied Gaussian scenes
|
||||
|
||||
An isolated replacement candidate for ground-arrow analysis. The supplied
|
||||
Gaussian scene is immutable. The pipeline recovers visible XY plan objects;
|
||||
expected-depth continuity is recorded separately and is not a physical survey.
|
||||
The user clarified on 2026-10-16 that incoming scans must be consumed as-is and
|
||||
that the objective is at least 95% object recovery, allowing imperfect input.
|
||||
That percentage is an object-level evaluation target, not a pixel threshold.
|
||||
|
||||
The current production provider and its 357-file closure are unchanged. This
|
||||
candidate has not been published or selected as the production provider. Roads,
|
||||
sidewalks, curbs, signs, crosswalks and other classes are outside this arrow
|
||||
implementation's qualified scope.
|
||||
|
||||
## Data flow
|
||||
|
||||
1. Systematic top views use parallel rays for Gaussian SH colour and native
|
||||
depth/alpha. Camera/terrain planning is an existing input to this evaluation.
|
||||
2. A uniform 16 m survey with 8 m stride selects visible windows and records
|
||||
coverage. The pinned semantic model encodes each selected window once.
|
||||
3. One candidate registry retains the initial observations. An entity owns one
|
||||
immutable world-aligned paint frame, with a physical illumination-filter halo.
|
||||
No detector or renderer is invoked again during reconstruction.
|
||||
4. The search fits four-parameter similarity poses of fixed presets to original
|
||||
paint. Semantic proposals provide association and initialization, not a
|
||||
supposedly exact metric contour. A complete witness binds the semantic
|
||||
score, its own region and its own target; sources cannot be mixed by maxima.
|
||||
5. Search, final selection and independent remeasurement share one admission
|
||||
contract. The independent path measures the original pixels again.
|
||||
6. Reconciliation runs only after verification binds exact result bytes. It
|
||||
preserves previous object identities and unrelated features. Retained old
|
||||
geometry is explicitly separate from fresh reconstruction.
|
||||
|
||||
## Observation contract
|
||||
|
||||
`plan_marking_policy.py` explicitly versions the observed XY contract. Native
|
||||
4096px depth/alpha is not smoothed, repaired or downsampled to pass a check.
|
||||
Finite positive depths, alpha >= .85 and context/ground depth agreement <= .12 m
|
||||
still determine visibility. Primary complete coverage, >= .97 observed validity,
|
||||
original-pixel IoU >= .65, boundary mean <= .075 m and p90 <= .15 m remain gates.
|
||||
Whole-object support, parts, endpoints, negative paint and connectivity remain
|
||||
measured. Unknown pixels cannot become supporting paint.
|
||||
|
||||
The previous local expected-depth-span veto and maximum error at every ideal
|
||||
preset corner are now quality diagnostics. This is an explicit acceptance
|
||||
contract change, not a claim that the old contract passed. Individual corner
|
||||
wear is judged in the context of the complete boundary and observed parts.
|
||||
A semantic proposal must be associated with the same object (overlap coefficient
|
||||
>= .55); its old .78 template IoU is no longer treated as metric ground truth.
|
||||
The original-paint measurements still govern the reconstructed shape.
|
||||
|
||||
Two concrete shape/ownership faults were also corrected. White and yellow paint
|
||||
channels are disjoint; a yellow crossing cannot be joined to the white arrow's
|
||||
component merely because its saturation is modest. Both actual wings of the
|
||||
straight arrow head require real paint; their complete area requires >= .65
|
||||
direct support. Partial wear is measured over the head, not vetoed separately
|
||||
for each half. Head support and original-pixel IoU use exact intersections
|
||||
with the immutable .025 m pixel cells. This removes pose-dependent pixel-centre
|
||||
counting steps from the search/admission agreement; the .65 IoU gate is retained. The former last-20%-of-length probe covered only the
|
||||
narrowing tip for the long profile and could admit a plain stripe through
|
||||
morphological dilation. The new wing test does not use dilated stem support.
|
||||
|
||||
Output authority remains observation-only, route permission is unassigned, and
|
||||
standard compliance is not assessed. Two overlapping renders are observations
|
||||
of the same scan, not independent physical acquisitions. An absent second view
|
||||
remains explicitly unknown. Depth-quality fractions are retained on each object
|
||||
and remeasured by the verifier; they do not certify heights.
|
||||
|
||||
## Qualification and evidence
|
||||
|
||||
Quality baseline qualification: object version v22, observed XY contract v5. Session
|
||||
`topdown-plan-full-20261016074318` freshly rendered the supplied Maroseyka PLY and
|
||||
reran survey, semantic inference, all-group reconstruction and independent
|
||||
verification. It freshly recovered **20/21 confirmed arrows (95.24%)**, including
|
||||
arrow 8; **10/11 original misses** and all **16 previously fixed arrows** are
|
||||
recovered. The only unrecovered confirmed arrow is number 2 (group 5), with
|
||||
observed validity approximately .952-.954 against the retained .97 gate and
|
||||
insufficient head evidence. It is preserved with its previous geometry and
|
||||
never counted as fresh. No further tuning to force 100% is required by the
|
||||
owner's clarified target.
|
||||
|
||||
The fresh output has 21 independently verified arrows: 20 reference matches
|
||||
and one visually verified additional straight-right arrow (group 14). All 21
|
||||
accepted source/overlay crops were visually inspected; no false positives were
|
||||
observed. The prior stripe false positive (group 58) is rejected. The frozen
|
||||
reference denominator remains 21. Reconciliation preserves all 21 confirmed
|
||||
identities, adds the new arrow and produces 585 map objects, with one retained
|
||||
old arrow geometry, no conflicts/deletions and unrelated objects unchanged.
|
||||
|
||||
The negative Smolensk 6.3 scene used immutable saved renders but a NEW survey
|
||||
and semantic pass: 354 windows, zero proposals and zero accepted arrows.
|
||||
The 39 invariant tests passed on Worker006. Shared tested and executed source
|
||||
hashes match. Production's 357-file closure remains unchanged.
|
||||
|
||||
Full Maroseyka stage seconds: capture 976.219, survey 231.859, semantic 277.266,
|
||||
reconstruction 280.125, verification 100.312; total **1865.781 s (31:06)**.
|
||||
The earlier complete arrow run took 2047.657 s (34:08) and recovered 16/21.
|
||||
Observed full-time reduction is 8.88%; reconstruction decreases from 485.750
|
||||
to 280.125 s (42.33%). Both runs use the same PLY and pre-existing camera/terrain
|
||||
plan. All 136 RGB and 136 native depth/alpha files are byte-identical. The capture
|
||||
code is identical; runtime variation there is not an optimization claim. This
|
||||
is a single-run comparison of explicit different admission contracts, not an
|
||||
all-class production cold-start benchmark or a repeated performance estimate.
|
||||
|
||||
There are 557 systematic windows, 78 object groups and 67 distinct fit problems.
|
||||
Reconstruction invokes the detector zero times and requests zero new renders.
|
||||
All seven owned qualification sessions are cleaned up, reservations released,
|
||||
and canonical Core remains HTTP200/operational on port8000.
|
||||
Archive SHA-256: `3be3e487fe9d35299ca9f37d93f4be179cfa904b94abb31a9455e3abd64dce79`.
|
||||
|
||||
|
||||
The frozen 21-arrow development reference is used only by evaluation. Matching
|
||||
is same-class and one-to-one with identity IoU >= .5; its contours are not metric
|
||||
ground truth. Additional observed objects are reviewed separately and never used
|
||||
to change this denominator after a run. Development results do not establish a
|
||||
95% rate on arbitrary new scenes; holdouts remain sealed during development.
|
||||
|
||||
All heavy tests and rendering run on Worker006 through the versioned qualification
|
||||
builder/worker harness. It freezes the import closure, reserves Core's simulation
|
||||
resource, uses bounded owned containers and performs cleanup in finally. Source,
|
||||
input, result and collection hashes are retained with UTC and monotonic timings.
|
||||
No intermediate experiments are published in Ops.
|
||||
|
||||
## Causal evidence retained
|
||||
|
||||
For arrow 8, five of 21 tail samples failed the former .18 m depth-span gate.
|
||||
Their native neighborhoods span .187923-.189568 m despite high opacity. Independent
|
||||
Gaussian compositing reproduces those depths within .0000190735 m: this is not a
|
||||
rounding bug. Bright edge Gaussians and background Gaussians contribute displaced
|
||||
expected depths. The error was to use this composite-depth variation as proof
|
||||
that visible XY paint was absent. The input Gaussians remain byte-identical.
|
||||
|
||||
The audit modules are evaluation tools, not recovery stages. The unadopted
|
||||
conditional-depth and all-corner optimizer experiments remain in historical
|
||||
qualification evidence and are not part of the inference path. No blind pose
|
||||
sweep, historical pose or source-layer editing is used for admission.
|
||||
|
||||
## Performance qualification, 2026-10-16
|
||||
|
||||
The same v22/policy-v5 arrow path now uses an exact spatial index, a packaged
|
||||
upstream gsplat CUDA extension, at most two concurrent lossless observation
|
||||
writers, zero-copy alpha access and source-tile-grouped crop materialization.
|
||||
These changes do not alter point selection/order, cameras, native resolution,
|
||||
coverage, semantic inference, object fitting or acceptance thresholds.
|
||||
|
||||
Full measured Maroseyka times (fresh source capture through independent check):
|
||||
|
||||
| Stage | Baseline | One writer | Two writers |
|
||||
|---|---:|---:|---:|
|
||||
| orthographic-observations | 976.219 | 698.625 | 467.437 |
|
||||
| survey | 231.859 | 204.078 | 203.016 |
|
||||
| semantic | 277.266 | 277.328 | 279.313 |
|
||||
| reconstruct | 280.125 | 273.953 | 275.093 |
|
||||
| verify | 100.312 | 98.250 | 98.313 |
|
||||
| Total seconds | 1865.781 | 1552.234 | 1323.172 |
|
||||
|
||||
The final run `topdown-writer-queue-20261016101327` took 1323.172 seconds
|
||||
(22:03), versus 1865.781 (31:06): 29.08% less time. All 136 RGB files, 136
|
||||
native geometry files, 557 patch records, the coverage ledger and every recovered
|
||||
arrow's geometry are identical to baseline. Fresh known arrows remain 20/21;
|
||||
all 21 identities are preserved, with the same one retained previous geometry
|
||||
excluded from fresh recovery. The same additional true arrow remains separate.
|
||||
The first optimized full run rechecked the Smolensk negative (zero arrows).
|
||||
The second changes only writer concurrency; it does not repeat that negative.
|
||||
40 invariant tests and the synthetic orthographic camera check passed.
|
||||
|
||||
These are single-run measurements with pre-existing camera/terrain plans,
|
||||
pinned models and source files on Worker storage. OS cache/background load was
|
||||
not controlled. One-time CUDA compilation/build/tests are separate from per-scene
|
||||
timing. This is still the arrow candidate, not an all-class production switch.
|
||||
The production 357-file algorithm closure is unchanged. UI/queue changes are
|
||||
separate and documented in `simulation/ai-polygon/INFRASTRUCTURE_QUEUE.md`.
|
||||
|
||||
Final evidence archive SHA-256:
|
||||
`1e51d99dbfd245914cdde07349e126f3af51ad4bcb9bbecfa42ab15d7d1af2db`.
|
||||
The ready runtime is pinned to
|
||||
`sha256:0df53bf9a160cd04cdea47254948053bf3bcebb5ba0efc8dd61030540b65a763`.
|
||||
Two superseded compiler caches/binary duplicates were retired only after exact
|
||||
checksum agreement with the retained qualified runtime; logs/manifests remain.
|
||||
@@ -0,0 +1,84 @@
|
||||
"""One admission contract for search, final selection and independent remeasurement.
|
||||
|
||||
A proposal witness binds its semantic score, region and target. Existential
|
||||
support means one complete witness passes, never a maximum for each field.
|
||||
"""
|
||||
import numpy as np
|
||||
from shapely.geometry import shape
|
||||
from arrow_admission import POLICY
|
||||
from observation_checks import assess
|
||||
from object_evidence import evidence
|
||||
from observation_evaluator import ObservationEvaluator
|
||||
from registration_evaluator import RegistrationEvaluator
|
||||
from plan_registration import metrics
|
||||
from plan_marking_policy import registration_passes as passes, source_correspondence, MIN_SOURCE_CORRESPONDENCE, CONTRACT
|
||||
from standard_arrow_templates import dimensions
|
||||
from recall_extent import semantic_recall
|
||||
|
||||
VERSION='bound-observation-admission-v3'
|
||||
|
||||
|
||||
class ProposalPool:
|
||||
def __init__(self,rows):
|
||||
# Duplicate observations and their input order cannot affect search.
|
||||
unique={}
|
||||
for row in sorted(rows,key=lambda r:r['id']):
|
||||
region,target=shape(row['region']),shape(row['target'])
|
||||
key=(region.wkb,target.wkb,float(row['semantic_score']))
|
||||
if key not in unique:
|
||||
unique[key]=dict(row=row,region=region.buffer(.2),target=target)
|
||||
self.sources=sorted(unique.values(),key=lambda v:(v['target'].wkb,v['region'].wkb,v['row']['semantic_score'],v['row']['id']))
|
||||
if not self.sources:raise ValueError('Empty proposal pool')
|
||||
self.targets=[v['target'] for v in self.sources]
|
||||
|
||||
def measure(self,q,kind):
|
||||
semantic_limit=POLICY['bicycle_semantic_score' if kind=='bicycle' else 'arrow_semantic_score']
|
||||
records=[]
|
||||
for item in self.sources:
|
||||
row=item['row'];target=item['target']
|
||||
containment=q.intersection(item['region']).area/max(q.area,1e-9)
|
||||
overlap=q.intersection(target).area/max(q.union(target).area,1e-9)
|
||||
correspondence=source_correspondence(q,target)
|
||||
values=[row['semantic_score']-semantic_limit,containment-POLICY['min_semantic_fraction'],correspondence-MIN_SOURCE_CORRESPONDENCE]
|
||||
records.append(dict(candidate_id=row['id'],semantic_score=row['semantic_score'],
|
||||
containment=containment,target_iou=overlap,source_correspondence=correspondence,minimum_margin=min(values)))
|
||||
return min(records,key=lambda r:(-r['minimum_margin'],-r['target_iou'],r['candidate_id']))
|
||||
|
||||
|
||||
class AdmissionContract:
|
||||
def __init__(self,rows,extent,grid,whole_grid):
|
||||
self.pool=ProposalPool(rows);self.extent=extent;self.grid=grid;self.whole_grid=whole_grid
|
||||
self.object_evaluator=ObservationEvaluator(extent,whole_grid,head_grid=grid)
|
||||
self.registration=RegistrationEvaluator(grid)
|
||||
|
||||
def measure(self,q,kind,profile,pose,*,independent=False):
|
||||
witness=self.pool.measure(q,kind);parameters=dimensions(kind,profile,pose)
|
||||
if independent:
|
||||
self.grid['angle']=pose[2]
|
||||
registration=[metrics(q,self.grid,v) for v in self.grid['views']]
|
||||
whole=evidence(q,kind,parameters,self.extent,self.whole_grid,head_grid=self.grid)
|
||||
else:
|
||||
registration=self.registration.measure(q)
|
||||
whole=self.object_evaluator.evaluate(q,kind,parameters)
|
||||
decision=assess(whole,witness['semantic_score'],witness['containment'],witness['source_correspondence'],kind)
|
||||
recall=semantic_recall(q,self.extent)
|
||||
checks=self.registration.checks_from(registration)
|
||||
reg_values=[r['margin'] for r in checks]
|
||||
values=decision['constraint_values']+[recall-.85]+reg_values
|
||||
accepted=bool(decision['accepted'] and recall>=.85 and passes(registration))
|
||||
if accepted != (min(values)>=0):raise AssertionError('Admission/constraint mismatch')
|
||||
# Report the same complete decision that search and final admission
|
||||
# actually use. A corner-only rejection previously had failures=[] and
|
||||
# admission.accepted=True despite the full contract rejecting it.
|
||||
failures=list(decision['failures'])
|
||||
if recall<.85:failures.append(dict(check='semantic_recall',rank=None,value=recall,minimum=.85))
|
||||
failures.extend({k:v for k,v in r.items() if k not in ['active','margin']} for r in checks if r['margin']<0)
|
||||
names=decision['constraint_names']+['global/semantic_recall']+[str(r['rank'])+'/'+r['check'] for r in checks]
|
||||
decision=dict(decision,accepted=accepted,failures=failures,minimum_margin=min(values),constraint_values=values,constraint_names=names)
|
||||
assert accepted == (not failures)
|
||||
return dict(accepted=accepted,witness=witness,metrics=registration,evidence=whole,contract=CONTRACT,
|
||||
admission=decision,recall=recall,constraint_values=values,
|
||||
constraint_violation=float(np.maximum(-np.asarray(values),0).max()))
|
||||
|
||||
def constraints(self,q,kind,profile,pose):
|
||||
return self.measure(q,kind,profile,pose)['constraint_values']
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Assemble an explicitly reviewed prior state; never used by detection."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
from reconcile_objects import reconcile
|
||||
from preservation import compare
|
||||
|
||||
|
||||
def run():
|
||||
base=Path('/base-map.json').read_bytes();result=Path('/result/arrow-observations.json').read_bytes()
|
||||
verification=json.loads(Path('/verification/verification.json').read_text())
|
||||
assembled,ledger=reconcile(base,result,verification)
|
||||
out=Path('/out');(out/'map-preview.json').write_text(json.dumps(assembled,allow_nan=False))
|
||||
(out/'reconciliation.json').write_text(json.dumps(ledger,indent=2))
|
||||
if Path('/confirmed-reference.json').exists():
|
||||
report=compare(json.loads(Path('/confirmed-reference.json').read_text()),dict(features=[f for f in assembled['features'] if 'arrow' in f['properties'].get('subtype','')]))
|
||||
report['scope']='reviewed state including retained historical geometry; not fresh reconstruction'
|
||||
(out/'map-preservation.json').write_text(json.dumps(report,indent=2))
|
||||
print('REVIEWED_STATE',report['matched'],'/',report['reference_objects'],'conflicts',len(ledger['conflicts']),flush=True)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Evaluation-only falsification of search and observation-contract hypotheses.
|
||||
|
||||
Historical poses are never returned to reconstruction or used as search seeds.
|
||||
Every metric is remeasured; historical admission is not inherited.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import numpy as np
|
||||
import shapely
|
||||
from shapely.geometry import shape
|
||||
from ground_observations import GroundObservations, sha
|
||||
from standard_arrow_templates import polygon, dimensions
|
||||
from standard_arrow_evidence import metrics, passes
|
||||
from reconstruct_topdown import evidence
|
||||
from observation_checks import assess
|
||||
from recall_extent import semantic_recall
|
||||
from admission_contract import AdmissionContract
|
||||
from surface_audit import surface_audit
|
||||
|
||||
|
||||
def run(focus_groups=None):
|
||||
root=Path('/result');out=Path('/out')
|
||||
refs=json.loads(Path('/reference.json').read_text())['features']
|
||||
registry=json.loads((root/'candidates.json').read_text())['candidates']
|
||||
di={r['group']:r for r in json.loads((root/'diagnostics.json').read_text())}
|
||||
native=GroundObservations();coarse=GroundObservations();coarse.native=None
|
||||
records=[]
|
||||
for f in refs:
|
||||
if 'arrow' not in f['properties'].get('subtype',''):continue
|
||||
ref=shapely.force_2d(shape(f['geometry']))
|
||||
row=max(registry,key=lambda r:ref.intersection(shape(r['extent'])).area/max(ref.area,1e-9))
|
||||
if focus_groups is not None and row['group'] not in focus_groups:continue
|
||||
peers=[r for r in registry if r['group']==row['group']]
|
||||
extent=shape(row['extent']);d=di[row['group']]
|
||||
options=[o for o in d.get('options',[]) if o['kind']==f['properties']['subtype']]
|
||||
poses=[]
|
||||
if options:poses.append(('searched',max(options,key=lambda o:o['metrics'][0]['iou'])))
|
||||
for candidate in d.get('direct_options',[]):
|
||||
if candidate['kind']!=f['properties']['subtype']:continue
|
||||
if candidate.get('initial_pose'):poses.append(('initial_unconstrained',dict(candidate,pose=candidate['initial_pose'])))
|
||||
for v in candidate.get('start_diagnostics',[]):poses.append(('solver_start',dict(candidate,pose=v['pose'])))
|
||||
if f['properties'].get('preset'):poses.append(('historical_fixed',f['properties']['preset']))
|
||||
measured=[]
|
||||
for name,obs,context in [('native',native,1.2),('compatibility',coarse,1.2)]:
|
||||
grid=obs.grid(extent,context=context);whole=obs.grid(extent,cell=.04,context=context)
|
||||
for label,p in poses:
|
||||
q=polygon(p['kind'],p['profile'],p['pose']);grid['angle']=p['pose'][2]
|
||||
mm=[metrics(q,grid,v) for v in grid['views']]
|
||||
ev=evidence(q,p['kind'],dimensions(p['kind'],p['profile'],p['pose']),extent,whole)
|
||||
contract=AdmissionContract(peers,extent,grid,whole)
|
||||
decision=contract.measure(q,p['kind'],p['profile'],p['pose'],independent=True)
|
||||
proposal=decision['witness']['target_iou'];admission=decision['admission'];recall=decision['recall']
|
||||
measured.append(dict(observation=name,pose_source=label,pose=p,registration=mm,registration_passed=passes(mm),
|
||||
object_admission=admission,semantic_recall=recall,evidence=ev,proposal_overlap=proposal,
|
||||
passed=decision['accepted'],surface=surface_audit(obs,grid,q),witness=decision['witness']))
|
||||
records.append(dict(reference_id=f['id'],group=row['group'],measurements=measured))
|
||||
print('CONTRACT',row['group'],[(m['observation'],m['pose_source'],m['passed'],[x['check'] for x in m['object_admission']['failures']]) for m in measured],flush=True)
|
||||
(out/'contract-audit.json').write_text(json.dumps(dict(reference_sha256=sha('/reference.json'),records=records,
|
||||
evaluation_only=True,historical_pose_used_for_inference=False),indent=2))
|
||||
@@ -0,0 +1,95 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Vectorize semantic observations once; persist candidates before any fitting."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
import cv2
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from shapely.geometry import mapping
|
||||
from pixel_geometry import vector
|
||||
from paint_channels_fast import paint_mask
|
||||
from ground_observations import sha
|
||||
|
||||
VERSION = 'immutable-ground-candidates-object-observations-v9'
|
||||
|
||||
|
||||
def group_observations(pending):
|
||||
"""Associate entities without throwing away their initial measurements.
|
||||
|
||||
A group anchor is immutable: merging measurements does not union semantic
|
||||
masks into an invented object. Each source retains its own shape and score.
|
||||
"""
|
||||
groups=[]
|
||||
for row in sorted(pending,key=lambda x:(-x['semantic_score']*x['extent'].area,x['patch'],x['source'])):
|
||||
group=next((g for g in groups if row['extent'].intersection(g[0]['extent']).area/
|
||||
max(row['extent'].union(g[0]['extent']).area,1e-9)>.45),None)
|
||||
if group is None:groups.append([row])
|
||||
else:group.append(row)
|
||||
return groups
|
||||
|
||||
|
||||
def discover(root, out, observations=None):
|
||||
started = time.monotonic(); root = Path(root); out = Path(out)
|
||||
manifest = root/'symbol-patches.json'
|
||||
semantics_path = root/'symbol-semantics.json'
|
||||
semantics = json.loads(semantics_path.read_text())
|
||||
if semantics['patch_manifest_sha256'] != sha(manifest):
|
||||
raise ValueError('Semantic/patch provenance mismatch')
|
||||
patches = {p['id']: p for p in json.loads(manifest.read_text())['patches']}
|
||||
pending, inputs = [], {}
|
||||
for record in semantics['records']:
|
||||
if not record['detections'] or 1 not in record['classes']:
|
||||
continue
|
||||
patch = patches[record['id']]
|
||||
image_path = root/'symbol-patches'/(patch['id']+'.png')
|
||||
masks_path = root/'symbol-masks'/(patch['id']+'.npz')
|
||||
if sha(image_path) != patch['sha256'] or sha(masks_path) != record['sha256']:
|
||||
raise ValueError('Observation bytes changed')
|
||||
inputs[patch['id']] = dict(image_sha256=patch['sha256'], masks_sha256=record['sha256'])
|
||||
with np.load(masks_path) as z:
|
||||
for mask_id, (mask, score, category) in enumerate(zip(z['masks'], z['scores'], z['classes'])):
|
||||
if category != 1 or score < .50:
|
||||
continue
|
||||
region = vector(mask, patch)
|
||||
if region.is_empty or region.area < .25:
|
||||
continue
|
||||
length, width = sorted(cv2.minAreaRect(np.asarray(region.convex_hull.exterior.coords, 'float32'))[1], reverse=True)
|
||||
if not 1.0 <= length <= 10.5 or not .25 <= width <= 4.0:
|
||||
continue
|
||||
pending.append(dict(patch=patch['id'],masks=[mask_id],semantic_score=float(score),
|
||||
target=region,region=region,extent=region,source='semantic-silhouette'))
|
||||
groups = group_observations(pending)
|
||||
from ground_observations import GroundObservations, PHOTOMETRY
|
||||
from observed_fixed import grid_polygon
|
||||
observations=observations or GroundObservations()
|
||||
observations.prepare_paint([g[0]['extent'] for g in groups])
|
||||
raw_proposals=len(pending)
|
||||
rows = []
|
||||
for group_id, group in enumerate(groups):
|
||||
if group_id%10==0:print('OBSERVATION_GROUP',group_id,'/',len(groups),round(time.monotonic()-started,2),flush=True)
|
||||
anchor=group[0];grid=observations.grid(anchor['extent'])
|
||||
for rank,view in enumerate(grid['views']):
|
||||
target=grid_polygon(view['target'],grid)
|
||||
if target.is_empty or target.area<.08:continue
|
||||
group.append(dict(anchor,target=target,source='canonical-paint-view-'+str(rank)))
|
||||
for row in group:
|
||||
encoded = dict(row, group=group_id, observation_extent=mapping(row['extent']),
|
||||
**{k: mapping(row[k]) for k in ['target','region']},extent=mapping(group[0]['extent']))
|
||||
encoded['id'] = hashlib.sha256(json.dumps(encoded, sort_keys=True).encode()).hexdigest()[:24]
|
||||
rows.append(encoded)
|
||||
result = dict(version=VERSION, patch_manifest_sha256=sha(manifest), semantics_sha256=sha(semantics_path),
|
||||
inputs=inputs, candidates=rows, groups=len(groups), raw_proposals=raw_proposals, photometry=PHOTOMETRY,
|
||||
existing_map_input=False, seconds=time.monotonic()-started)
|
||||
(out/'candidates.json').write_text(json.dumps(result, indent=2))
|
||||
print('CANDIDATES', len(rows), 'GROUPS', len(groups), flush=True)
|
||||
return result
|
||||
|
||||
|
||||
def verify(root, registry):
|
||||
from ground_observations import PHOTOMETRY
|
||||
if registry.get('version')!=VERSION or registry.get('photometry')!=PHOTOMETRY:
|
||||
raise ValueError('Candidate observation contract changed')
|
||||
root = Path(root)
|
||||
for name, key in [('symbol-patches.json','patch_manifest_sha256'), ('symbol-semantics.json','semantics_sha256')]:
|
||||
if sha(root/name) != registry[key]:
|
||||
raise ValueError('Candidate source manifest changed')
|
||||
for pid, source in registry['inputs'].items():
|
||||
for folder, suffix, key in [('symbol-patches','.png','image_sha256'), ('symbol-masks','.npz','masks_sha256')]:
|
||||
if sha(root/folder/(pid+suffix)) != source[key]:
|
||||
raise ValueError('Candidate source artifact changed')
|
||||
return True
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Evaluate a new depth measurement; never publishes reconstructed objects."""
|
||||
from pathlib import Path
|
||||
from functools import lru_cache
|
||||
import json,time
|
||||
import numpy as np
|
||||
from shapely.geometry import shape
|
||||
from ground_observations import GroundObservations
|
||||
from admission_contract import AdmissionContract
|
||||
from candidate_registry import verify
|
||||
from observed_fixed import fit_grid
|
||||
from standard_arrow_templates import polygon
|
||||
from surface_audit import surface_audit
|
||||
|
||||
class AuditObservations(GroundObservations):
|
||||
@lru_cache(maxsize=12)
|
||||
def geometry(self,name,ground=False):
|
||||
p=Path('/depth_audit')/(name+('.ground.npz' if ground else '.context.npz'))
|
||||
if p.exists():
|
||||
with np.load(p) as z:return dict(z)
|
||||
return super().geometry(name,ground)
|
||||
|
||||
def run(focus_groups):
|
||||
root=Path('/result');out=Path('/out');begin=time.monotonic()
|
||||
registry=json.loads((root/'candidates.json').read_text());verify('/symbolplan',registry)
|
||||
trace=json.loads((root/'diagnostics.json').read_text());records=[];obs=AuditObservations()
|
||||
for d in trace:
|
||||
if d['group'] not in focus_groups:continue
|
||||
rows=[r for r in registry['candidates'] if r['group']==d['group']];extent=shape(rows[0]['extent'])
|
||||
fine=obs.grid(extent);whole=obs.grid(extent,cell=.04);contract=AdmissionContract(rows,extent,fine,whole)
|
||||
seeds=[]
|
||||
for candidate in d['direct_options']:
|
||||
if candidate['initial_score']<.65:continue
|
||||
for start in candidate.get('start_diagnostics',[]):
|
||||
pose=start['pose'];q=polygon(candidate['kind'],candidate['profile'],pose)
|
||||
seeds.append(dict(kind=candidate['kind'],profile=candidate['profile'],pose=pose,
|
||||
decision=contract.measure(q,candidate['kind'],candidate['profile'],pose,independent=True),
|
||||
surface=surface_audit(obs,fine,q)))
|
||||
fitted=fit_grid(fine,contract.pool.targets,contract.constraints);options=[]
|
||||
for c in fitted:
|
||||
options.append(dict(kind=c['kind'],profile=c['profile'],pose=c['pose'],
|
||||
decision=contract.measure(c['geometry'],c['kind'],c['profile'],c['pose'],independent=True)))
|
||||
records.append(dict(group=d['group'],seeds=seeds,options=options,accepted=any(o['decision']['accepted'] for o in options)))
|
||||
print('CONDITIONAL_CONTRACT',d['group'],records[-1]['accepted'],flush=True)
|
||||
(out/'conditional-contract.json').write_text(json.dumps(dict(records=records,evaluation_only=True,
|
||||
reference_input=False,published=False,source='original Gaussian covariance; no depth smoothing',seconds=time.monotonic()-begin)))
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Evaluation-only depth contract experiment, without historical geometry."""
|
||||
from pathlib import Path
|
||||
import gc,inspect,json,math,time
|
||||
import cv2
|
||||
import numpy as np
|
||||
import torch
|
||||
from gsplat import rasterization
|
||||
from plyfile import PlyData
|
||||
from mapping import camera,digest
|
||||
from coordinate_cache import transformed
|
||||
from ortho_terrain import sample
|
||||
from orthographic_colour import colours
|
||||
from orthographic_depth import coefficients,decode,VERSION
|
||||
|
||||
def synthetic():
|
||||
device='cuda';dtype=torch.float32
|
||||
view=torch.eye(4,device=device);n=512;k=torch.tensor([[128.,0,256.],[0,128.,256.],[0,0,1]],device=device)
|
||||
def render(means,quats,scales,opacity):
|
||||
coeff=coefficients(means,quats,scales,view,k)
|
||||
v,a,_=rasterization(means,quats,scales,opacity,coeff,view[None],k[None],n,n,
|
||||
camera_model='ortho',render_mode='RGB+ED',packed=True)
|
||||
alpha=a[0,:,:,0];return decode(v[0,:,:,:3],alpha,k),v[0,:,:,3],alpha
|
||||
rows=[]
|
||||
for name,slope,step in [('flat',0.,0.),('slope',.35,0.),('step',0.,.35)]:
|
||||
x=torch.tensor([-.6,0.,.6],device=device);z=5+slope*x+(x>0)*step
|
||||
means=torch.stack([x,torch.zeros_like(x),z],-1)
|
||||
angle=-math.atan(slope);q=torch.tensor([math.cos(angle/2),0.,math.sin(angle/2),0.],device=device).repeat(3,1)
|
||||
scales=torch.tensor([.42,.4,.001],device=device).repeat(3,1);opacity=torch.full((3,),.99,device=device)
|
||||
conditional,centroid,alpha=render(means,q,scales,opacity)
|
||||
xx=(torch.arange(n,device=device)+.5-256)/128
|
||||
expected=(5+slope*xx).repeat(n,1);known=(alpha>.85)&(torch.abs(xx)[None]<.7)
|
||||
record=dict(name=name,known_pixels=int(known.sum()),conditional_max_plane_error_m=float((conditional-expected)[known].abs().max()),
|
||||
centroid_max_plane_error_m=float((centroid-expected)[known].abs().max()),
|
||||
conditional_depth_range_m=float(conditional[known].max()-conditional[known].min()))
|
||||
if not step:assert record['conditional_max_plane_error_m']<.0001,record
|
||||
if step:assert record['conditional_depth_range_m']>.20,record
|
||||
rows.append(record)
|
||||
return rows
|
||||
|
||||
def run(tile_names):
|
||||
out=Path('/out');root=Path('/ortho');begin=time.monotonic()
|
||||
report=dict(version=VERSION,evaluation_only=True,reference_input=False,synthetic=synthetic(),
|
||||
rasterizer_signature=str(inspect.signature(rasterization)),records=[])
|
||||
(out/'depth-audit.json').write_text(json.dumps(report,indent=2))
|
||||
config=json.loads((root/'config.json').read_text());method=config['method'];n=method['render_pixels']
|
||||
request=json.loads((root/'survey/request.json').read_text());source=Path('/input')/request['source']['ply']
|
||||
assert digest(source)==request['source']['sha256']
|
||||
data=PlyData.read(source,mmap='r')['vertex'].data;transform=np.asarray(request['source']['source_to_world'])
|
||||
world=transformed(data,transform,str(source),str(out/'coordinate-cache-proof.json'))
|
||||
with np.load(root/'terrain-reference.npz') as z:field=dict(z)
|
||||
relative=np.empty(len(data),np.float32)
|
||||
for start in range(0,len(data),250000):
|
||||
xyz=world[start:start+250000];relative[start:start+len(xyz)]=xyz[:,2]-sample(field,xyz[:,:2])
|
||||
for name in tile_names:
|
||||
job=json.loads((root/'survey'/name/'job.json').read_text());top=next(v for v in job['views'] if v['id']=='top');top['size']=[n,n]
|
||||
bounds=np.asarray(job['bounds_xy']);indices=np.flatnonzero(((world[:,:2]>=bounds[0]-10)&(world[:,:2]<=bounds[1]+10)).all(1)&
|
||||
(relative>=method['lower_height_m'])&(relative<=method['context_height_m']))
|
||||
d=data[indices].copy();dz=relative[indices]
|
||||
for mode,upper in [('context',method['context_height_m']),('ground',method['ground_height_m'])]:
|
||||
selected=d[dz<=upper]
|
||||
def tensor(names):return torch.tensor(np.column_stack([selected[n] for n in names]),device='cuda',dtype=torch.float32)
|
||||
means=tensor(['x','y','z']);quats=tensor([f'rot_{i}' for i in range(4)]);scales=tensor([f'scale_{i}' for i in range(3)]).exp();opacity=tensor(['opacity']).squeeze(-1).sigmoid()
|
||||
view,k=camera(top);vmat=torch.tensor(view@transform,device='cuda',dtype=torch.float32);kt=torch.tensor(k,device='cuda',dtype=torch.float32)
|
||||
coeff=coefficients(means,quats,scales,vmat,kt)
|
||||
with torch.inference_mode():
|
||||
v,a,_=rasterization(means,quats,scales,opacity,coeff,vmat[None],kt[None],n,n,camera_model='ortho',render_mode='RGB+ED',packed=True)
|
||||
conditional=decode(v[0,:,:,:3],a[0,:,:,0],kt).cpu().numpy()
|
||||
alpha=a[0,:,:,0].cpu().numpy();centroid=v[0,:,:,3].cpu().numpy()
|
||||
with np.load(Path('/native_geometry')/(name+'.'+mode+'.npz')) as z:
|
||||
old=dict(z);depth_error=float(np.abs(centroid-old['depth']).max());alpha_error=float(np.abs(alpha-old['alpha']).max())
|
||||
assert depth_error<.001 and alpha_error<.0001,(depth_error,alpha_error)
|
||||
path=out/(name+'.'+mode+'.npz');np.savez_compressed(path,depth=conditional,alpha=alpha,view=view,intrinsics=k,compatibility_resolution=1200)
|
||||
report['records'].append(dict(tile=name,mode=mode,file=path.name,sha256=digest(path),
|
||||
centroid_reproduction_error_m=depth_error,alpha_reproduction_error=alpha_error,
|
||||
source_gaussians=len(means),depth_change_quantiles=np.quantile(np.abs(conditional-centroid)[alpha>=.85],[0,.5,.9,.99,1]).tolist()))
|
||||
print('DEPTH_AUDIT',name,mode,report['records'][-1],flush=True)
|
||||
del means,quats,scales,opacity,coeff,v,a,conditional,alpha,centroid,old;gc.collect();torch.cuda.empty_cache()
|
||||
report.update(seconds=time.monotonic()-begin,complete=True)
|
||||
(out/'depth-audit.json').write_text(json.dumps(report,indent=2))
|
||||
@@ -0,0 +1,229 @@
|
||||
"""Find a four-DOF preset pose directly from an observed whole-object target.
|
||||
|
||||
The raster is a search accelerator, never the output geometry. Every returned
|
||||
polygon is instantiated from immutable metric artwork. No flexible glyph fit
|
||||
or previously mapped arrow is an input.
|
||||
"""
|
||||
import cv2
|
||||
import time
|
||||
import numpy as np
|
||||
import shapely
|
||||
from scipy.optimize import minimize
|
||||
from standard_arrow_templates import KINDS, PROFILES, preset, polygon
|
||||
from registration import POLICY as GEOMETRY_POLICY
|
||||
|
||||
VERSION = 'topdown-direct-original-paint-v6'
|
||||
CELL = .05
|
||||
|
||||
|
||||
def observation_score(overlaps):
|
||||
"""Fit original paint. Semantic masks propose objects, not metric truth."""
|
||||
return float(np.asarray(overlaps,float)[0]/GEOMETRY_POLICY['min_iou'])
|
||||
|
||||
|
||||
def fit_target(target, *, max_options=4, evidence_penalty=None, geometric_constraints=None, object_constraints=None, preset_filter=None, evidence_seed=None, seed_targets=None):
|
||||
if target.is_empty or not target.is_valid or not .08 <= target.area <= 30:
|
||||
return []
|
||||
# All initial measurements are peers. A coarse ranking against only the
|
||||
# primary paint mask used to erase a pose supported by another source,
|
||||
# while final admission legitimately checked every retained source.
|
||||
sources=[]
|
||||
for source in [target]+list(seed_targets or []):
|
||||
if source.is_empty or not source.is_valid:continue
|
||||
if any(source.wkb==q.wkb for q in sources):continue
|
||||
sources.append(source)
|
||||
lo=np.min([q.bounds[:2] for q in sources],axis=0)-1.
|
||||
hi=np.max([q.bounds[2:] for q in sources],axis=0)+1.
|
||||
if np.max(hi-lo)>16:return []
|
||||
xx,yy=np.meshgrid(np.arange(lo[0],hi[0],CELL),np.arange(lo[1],hi[1],CELL))
|
||||
masks=np.stack([shapely.contains_xy(q,xx,yy) for q in sources]);mask=masks[0]
|
||||
if not mask.any():return []
|
||||
def raster_score(rendered):
|
||||
intersection=np.count_nonzero(masks&rendered[None],axis=(1,2))
|
||||
union=np.count_nonzero(masks|rendered[None],axis=(1,2))
|
||||
return observation_score(intersection/np.maximum(union,1))
|
||||
def overlaps(q):
|
||||
return [q.intersection(p).area/max(q.union(p).area,1e-9) for p in sources]
|
||||
def exact_score(q):
|
||||
return overlaps(q)[0]
|
||||
def search_score(q):
|
||||
return observation_score(overlaps(q))
|
||||
seed_shapes=[]
|
||||
for source in sources:
|
||||
if any(source.symmetric_difference(p).area/max(source.union(p).area,1e-9)<.02 for p in seed_shapes):continue
|
||||
seed_shapes.append(source)
|
||||
coarse = []
|
||||
for kind in KINDS:
|
||||
for profile, dimensions in PROFILES.items():
|
||||
template = preset(kind, profile)
|
||||
if preset_filter is not None and not preset_filter(template):continue
|
||||
unit = np.asarray(template.exterior.coords)
|
||||
centroid = np.asarray(template.centroid.coords[0])
|
||||
|
||||
def evaluate(p):
|
||||
x, y, a, s = p
|
||||
rotation = np.array([[np.cos(a), np.sin(a)],
|
||||
[-np.sin(a), np.cos(a)]])
|
||||
xy = unit @ rotation * s + [x, y]
|
||||
pixels = np.rint((xy-lo)/CELL).astype('int32')
|
||||
rendered = np.zeros(mask.shape, 'uint8')
|
||||
cv2.fillPoly(rendered, [pixels], 1)
|
||||
rendered = rendered.astype(bool)
|
||||
return raster_score(rendered)
|
||||
|
||||
angles = np.arange(24) * (2*np.pi/24)
|
||||
seeds = []
|
||||
for source in seed_shapes:
|
||||
center=np.asarray(source.centroid.coords[0]);coords=shapely.get_coordinates(source)
|
||||
for a in angles:
|
||||
axis = np.array([np.cos(a), np.sin(a)])
|
||||
factor = np.ptp(coords @ axis) / dimensions['L']
|
||||
if not .65 <= factor <= 1.40:
|
||||
continue
|
||||
factor = float(np.clip(factor, .75, 1.25))
|
||||
rotation = np.array([[np.cos(a), np.sin(a)],
|
||||
[-np.sin(a), np.cos(a)]])
|
||||
xy = center - centroid @ rotation * factor
|
||||
pose = np.r_[xy, a, factor]
|
||||
seeds.append((evaluate(pose), pose))
|
||||
# Retain competing classes until original-pixel verification.
|
||||
for score, pose in sorted(seeds, key=lambda x: -x[0])[:max(2,len(seed_shapes))]:
|
||||
coarse.append((score, kind, profile, pose))
|
||||
diverse=[]
|
||||
for entry in sorted(coarse,key=lambda x:-x[0]):
|
||||
_,kind,profile,pose=entry
|
||||
if any(kind==v[1] and profile==v[2] and np.linalg.norm(pose[:2]-v[3][:2])<.06
|
||||
and abs(pose[2]-v[3][2])<.02 and abs(pose[3]-v[3][3])<.015 for v in diverse):continue
|
||||
diverse.append(entry)
|
||||
# A cheap appearance score orders hypotheses; it cannot disprove a whole
|
||||
# semantic family. Repeated poses of one family must not evict another.
|
||||
family_counts={};family_seeds=[]
|
||||
for entry in diverse:
|
||||
key=entry[1:3]
|
||||
if family_counts.get(key,0)>=2:continue
|
||||
family_counts[key]=family_counts.get(key,0)+1;family_seeds.append(entry)
|
||||
candidates = []
|
||||
for _, kind, profile, pose in family_seeds:
|
||||
unit = np.asarray(preset(kind, profile).exterior.coords)
|
||||
|
||||
def objective(p):
|
||||
x, y, a, s = p
|
||||
rotation = np.array([[np.cos(a), np.sin(a)],
|
||||
[-np.sin(a), np.cos(a)]])
|
||||
pixels = np.rint((unit @ rotation*s + [x, y]-lo)/CELL).astype('int32')
|
||||
rendered = np.zeros(mask.shape, 'uint8')
|
||||
cv2.fillPoly(rendered, [pixels], 1)
|
||||
rendered = rendered.astype(bool)
|
||||
return -raster_score(rendered)
|
||||
|
||||
bounds = [(pose[0]-.7, pose[0]+.7), (pose[1]-.7, pose[1]+.7),
|
||||
(pose[2]-.30, pose[2]+.30), (.75, 1.25)]
|
||||
fitted = minimize(objective, pose, method='Powell', bounds=bounds,
|
||||
options=dict(maxiter=12, maxfev=300, xtol=.001, ftol=.001))
|
||||
best = min([pose, fitted.x], key=objective)
|
||||
q = polygon(kind, profile, best)
|
||||
exact = exact_score(q)
|
||||
# Preserve the original appearance prefilter. Other observations
|
||||
# contribute seeds, but cannot turn absent paint into a fit candidate.
|
||||
if overlaps(q)[0] < .35:
|
||||
continue
|
||||
if any(c['kind'] == kind and q.hausdorff_distance(c['geometry']) < .15
|
||||
for c in candidates):
|
||||
continue
|
||||
candidates.append(dict(kind=kind, profile=profile, pose=best.tolist(),
|
||||
score=float(exact), search_score=search_score(q), initial_pose=best.tolist(), initial_score=float(exact), geometry=q))
|
||||
# Remove coarse-raster bias before the original-pixel registration. Thin
|
||||
# stems are only a few pixels wide in the accelerator; its objective must
|
||||
# not determine final pose or throw away a valid shape's tips.
|
||||
refined = []
|
||||
family_counts={}
|
||||
for candidate in sorted(candidates, key=lambda x: -x['search_score']):
|
||||
family=(candidate['kind'],candidate['profile'])
|
||||
if family_counts.get(family,0)>=max_options:continue
|
||||
family_counts[family]=family_counts.get(family,0)+1
|
||||
kind, profile = candidate['kind'], candidate['profile']
|
||||
pose = np.asarray(candidate['pose'])
|
||||
def exact_loss(p):
|
||||
q = polygon(kind, profile, p)
|
||||
overlap = search_score(q)
|
||||
return -overlap + (evidence_penalty(q) if evidence_penalty is not None else 0.)
|
||||
bounds = [(pose[0]-.6, pose[0]+.6), (pose[1]-.6, pose[1]+.6),
|
||||
(pose[2]-.2, pose[2]+.2), (.75, 1.25)]
|
||||
if geometric_constraints is not None:
|
||||
# Solve the actual fixed-preset feasibility problem. The previous
|
||||
# weighted landmark penalty traded shape overlap for a tighter,
|
||||
# arbitrary 9 cm margin, then tested a different 12 cm constraint.
|
||||
# Work in local variables so absolute map coordinates do not set
|
||||
# finite-difference scales.
|
||||
scale=np.array([1.,1.,1./PROFILES[profile]['L'],1./PROFILES[profile]['L']])
|
||||
costs=dict(geometry_seconds=0.,object_seconds=0.,objective_seconds=0.,constraint_calls=0)
|
||||
lower,upper=np.asarray(bounds).T
|
||||
def physical(delta):
|
||||
# COBYLA may evaluate infeasible trial points; templates remain
|
||||
# inside their immutable scale envelope even during search.
|
||||
return np.clip(pose+delta*scale,lower,upper)
|
||||
def constraints(delta):
|
||||
p=physical(delta);q=polygon(kind,profile,p)
|
||||
begin=time.monotonic();values=list(geometric_constraints(q))
|
||||
costs['geometry_seconds']+=time.monotonic()-begin;costs['constraint_calls']+=1
|
||||
if object_constraints is not None:
|
||||
begin=time.monotonic();values.extend(np.atleast_1d(object_constraints(q,kind,profile,p)).tolist())
|
||||
costs['object_seconds']+=time.monotonic()-begin
|
||||
return np.asarray(values,float)
|
||||
local_bounds=[((a-p)/unit,(b-p)/unit) for (a,b),p,unit in zip(bounds,pose,scale)]
|
||||
def objective(delta):
|
||||
begin=time.monotonic();value=exact_loss(physical(delta))
|
||||
costs['objective_seconds']+=time.monotonic()-begin
|
||||
return value
|
||||
starts=[pose]
|
||||
if evidence_seed is not None:starts.append(evidence_seed(kind,profile,pose,bounds))
|
||||
def violation(p):return float(np.maximum(-constraints((p-pose)/scale),0.).max())
|
||||
legal_starts=[p for p in starts if violation(p)<=1e-12]
|
||||
if legal_starts:
|
||||
best=min(legal_starts,key=exact_loss);q=polygon(kind,profile,best)
|
||||
refined.append(dict(candidate,pose=best.tolist(),score=exact_score(q),
|
||||
objective=-float(exact_loss(best)),geometry=q,feasible=True,constraint_violation=0.,
|
||||
optimizer='boundary-least-squares-fixed-preset',optimizer_converged=True,optimizer_evaluations=0,search_cost=dict(costs)))
|
||||
if object_constraints is not None:break
|
||||
continue
|
||||
candidate['start_diagnostics']=[dict(pose=p.tolist(),violation=violation(p),loss=float(exact_loss(p))) for p in starts]
|
||||
start=min(starts,key=lambda p:(violation(p),exact_loss(p)))
|
||||
solved=minimize(objective,(start-pose)/scale,method='COBYLA',
|
||||
bounds=local_bounds,constraints=[dict(type='ineq',fun=constraints)],
|
||||
options=dict(maxiter=900,rhobeg=.15,tol=1e-4,catol=1e-8))
|
||||
alternatives=starts+[physical(solved.x)]
|
||||
def quality(p):
|
||||
violations=np.maximum(-constraints((p-pose)/scale),0.)
|
||||
return (float(violations.max()),exact_loss(p))
|
||||
feasible=[p for p in alternatives if quality(p)[0] <= 1e-5]
|
||||
best=min(feasible,key=exact_loss) if feasible else min(alternatives,key=quality)
|
||||
q=polygon(kind,profile,best)
|
||||
refined.append(dict(candidate,pose=best.tolist(),
|
||||
score=exact_score(q),
|
||||
objective=-float(exact_loss(best)),geometry=q,
|
||||
feasible=bool(quality(best)[0]<=1e-5),constraint_violation=quality(best)[0],
|
||||
optimizer='COBYLA-fixed-preset',optimizer_converged=bool(solved.success),
|
||||
optimizer_evaluations=int(solved.nfev),search_cost=dict(costs)))
|
||||
print('POSE',kind,profile,int(solved.nfev),{k:round(v,3) for k,v in costs.items()},flush=True)
|
||||
# This is a feasibility task: once the highest-ranked remaining
|
||||
# hypothesis passes every original-pixel and whole-object gate,
|
||||
# evaluating lower-ranked classes cannot make it more admissible.
|
||||
# The independent verifier still measures the returned geometry.
|
||||
if object_constraints is not None and quality(best)[0]<=1e-12:
|
||||
break
|
||||
continue
|
||||
result = minimize(exact_loss, pose, method='Powell', bounds=bounds,
|
||||
options=dict(maxiter=30, maxfev=1000, xtol=1e-5, ftol=1e-5))
|
||||
best = min([pose, result.x], key=exact_loss)
|
||||
# Translation and heading are coupled for a narrow stem. Coordinate
|
||||
# descent alone can stop at a slanted overlap ridge.
|
||||
simplex = np.vstack([best, best + np.diag([.04, .04, .01, .01])])
|
||||
joint = minimize(exact_loss, best, method='Nelder-Mead', bounds=bounds,
|
||||
options=dict(initial_simplex=simplex, maxfev=800,
|
||||
xatol=1e-5, fatol=1e-7))
|
||||
best = min([best, joint.x], key=exact_loss)
|
||||
q = polygon(kind, profile, best)
|
||||
refined.append(dict(candidate, pose=best.tolist(),
|
||||
score=exact_score(q),
|
||||
objective=-float(exact_loss(best)), geometry=q))
|
||||
return sorted(refined, key=lambda x: -x['objective'])
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Trace rejected endpoint pixels to native depth and original Gaussian weights.
|
||||
|
||||
Read-only diagnosis. It never changes a depth field, mask, pose, or admission.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import gc,json,time,math
|
||||
import cv2
|
||||
import numpy as np
|
||||
import shapely
|
||||
import torch
|
||||
from plyfile import PlyData
|
||||
from shapely.geometry import shape
|
||||
from ground_observations import GroundObservations,read,POLICY
|
||||
from standard_arrow_templates import polygon,dimensions
|
||||
from fit_scene import project,world as unproject
|
||||
from mapping import camera,digest
|
||||
from coordinate_cache import transformed
|
||||
from ortho_terrain import sample
|
||||
from candidate_registry import verify
|
||||
from orthographic_depth import coefficients
|
||||
|
||||
|
||||
def run(focus_group):
|
||||
begin=time.monotonic();out=Path('/out');root=Path('/ortho');obs=GroundObservations()
|
||||
reg=json.loads(Path('/result/candidates.json').read_text());verify('/symbolplan',reg)
|
||||
record=next(r for r in json.loads(Path('/pose_audit/pose-domain.json').read_text())['records'] if r['group']==focus_group)
|
||||
pose=record['best']['pose'];kind=record['kind'];profile=record['profile'];q=polygon(kind,profile,pose)
|
||||
extent=shape(next(r for r in reg['candidates'] if r['group']==focus_group)['extent']);grid=obs.grid(extent,cell=.04)
|
||||
points=grid['points'];inside=shapely.contains_xy(q,points[:,0],points[:,1]);axis=np.array([np.cos(pose[2]),np.sin(pose[2])]);t=(points-pose[:2])@axis
|
||||
endpoint=inside&(t<t[inside].min()+.20);tail=points[endpoint]
|
||||
names=grid['views'][0]['names'];assert len(names)==1,names;name=names[0]
|
||||
g=obs.geometry(name,True);context=obs.geometry(name);depth=g['depth'];alpha=g['alpha'];cam=obs.camera(name)
|
||||
uv=(project(tail,cam)+.5)*depth.shape[0]/1200-.5;pixels=np.rint(uv).astype(int)
|
||||
allowed=grid['views'][0]['allowed'].ravel()[endpoint];rows=[];queries={}
|
||||
ratio=depth.shape[0]/1200;radius=int(np.ceil((POLICY['local_window_px']-1)/2*ratio));mpp=1./float(g['intrinsics'][0,0])
|
||||
for xy,p,valid in zip(tail,pixels,allowed):
|
||||
x,y=map(int,p);patch=depth[y-radius:y+radius+1,x-radius:x+radius+1];yy,xx=np.indices(patch.shape);dx=(xx-radius)*mpp;dy=(yy-radius)*mpp
|
||||
design=np.c_[dx.ravel(),dy.ravel(),np.ones(patch.size)];coeff=np.linalg.lstsq(design,patch.ravel(),rcond=None)[0];residual=patch-design.reshape(*patch.shape,3)@coeff
|
||||
imin=np.unravel_index(patch.argmin(),patch.shape);imax=np.unravel_index(patch.argmax(),patch.shape)
|
||||
lowpixel=[x-radius+int(imin[1]),y-radius+int(imin[0])];highpixel=[x-radius+int(imax[1]),y-radius+int(imax[0])]
|
||||
row=dict(xy=xy.tolist(),pixel=p.tolist(),valid=bool(valid),depth=float(depth[y,x]),alpha=float(alpha[y,x]),
|
||||
span_m=float(np.ptp(patch)),min_pixel=lowpixel,max_pixel=highpixel,min_depth=float(patch.min()),max_depth=float(patch.max()),
|
||||
plane_slope=coeff[:2].tolist(),plane_residual_span=float(np.ptp(residual)),plane_residual_rms=float(np.sqrt(np.mean(residual**2))),
|
||||
neighbor_depth=patch.tolist())
|
||||
rows.append(row);queries[(x,y)]='endpoint'
|
||||
if not valid:queries[tuple(lowpixel)]='invalid-neighbour-min';queries[tuple(highpixel)]='invalid-neighbour-max'
|
||||
report=dict(group=focus_group,pose=pose,prior_map_input=False,pose_search=False,evaluation_only=True,tile=name,
|
||||
native_resolution=depth.shape[0],mpp=mpp,neighborhood_width=2*radius+1,neighborhood_center_span_m=2*radius*mpp,
|
||||
endpoint_pixels=len(rows),valid_pixels=int(allowed.sum()),samples=rows)
|
||||
(out/'endpoint-cause.json').write_text(json.dumps(report,indent=2));print('ENDPOINT',len(rows),int(allowed.sum()),flush=True)
|
||||
# Diagnostic figure preserves the native grid: no interpolation of depth.
|
||||
import matplotlib;matplotlib.use('Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
x0,y0=pixels.min(0)-25;x1,y1=pixels.max(0)+26;box=(slice(y0,y1),slice(x0,x1))
|
||||
rgb=obs.rgb(name)[box];patch=depth[box];kernel=np.ones((radius*2+1,)*2,'uint8');span=cv2.dilate(depth,kernel)-cv2.erode(depth,kernel)
|
||||
fig,axs=plt.subplots(1,3,figsize=(13,4))
|
||||
for ax,field,title in zip(axs,[rgb,patch,span[box]],['Original Gaussian RGB','Native depth (m)','Local depth span (m)']):
|
||||
im=ax.imshow(field,interpolation='nearest');ax.scatter(pixels[:,0]-x0,pixels[:,1]-y0,c=np.where(allowed,'lime','red'),s=16)
|
||||
ax.set_title(title);ax.set_xlabel('native pixel x');ax.set_ylabel('native pixel y')
|
||||
if field.ndim==2:fig.colorbar(im,ax=ax)
|
||||
fig.suptitle('Arrow 8: measured tail samples, '+str(int(allowed.sum()))+'/'+str(len(allowed))+' valid');fig.tight_layout();fig.savefig(out/'endpoint-cause.png',dpi=150);plt.close(fig)
|
||||
# Trace the same source selection and alpha compositing, not point-cloud fitting.
|
||||
method=json.loads((root/'config.json').read_text())['method'];request=json.loads((root/'survey/request.json').read_text())
|
||||
source=Path('/input')/request['source']['ply'];assert digest(source)==request['source']['sha256']
|
||||
data=PlyData.read(source,mmap='r')['vertex'].data;transform=np.asarray(request['source']['source_to_world'])
|
||||
xyz=transformed(data,transform,str(source),str(out/'coordinate-cache-proof.json'))
|
||||
job=json.loads((root/'survey'/name/'job.json').read_text());bounds=np.asarray(job['bounds_xy']);eligible=((xyz[:,:2]>=bounds[0]-10)&(xyz[:,:2]<=bounds[1]+10)).all(1)
|
||||
indices=np.flatnonzero(eligible)
|
||||
with np.load(root/'terrain-reference.npz') as z:field=dict(z)
|
||||
relative=xyz[indices,2]-sample(field,xyz[indices,:2]);indices=indices[(relative>=method['lower_height_m'])&(relative<=method['ground_height_m'])]
|
||||
selected=data[indices]
|
||||
def tensor(names):return torch.tensor(np.column_stack([selected[n] for n in names]),device='cuda',dtype=torch.float32)
|
||||
means=tensor(['x','y','z']);quats=tensor([f'rot_{i}' for i in range(4)]);scales=tensor([f'scale_{i}' for i in range(3)]).exp();opacity=tensor(['opacity']).ravel().sigmoid()
|
||||
view=torch.tensor(g['view']@transform,device='cuda',dtype=torch.float32);k=torch.tensor(g['intrinsics'],device='cuda',dtype=torch.float32)
|
||||
m=means@view[:3,:3].T+view[:3,3];quat=quats/torch.linalg.vector_norm(quats,dim=-1,keepdim=True);w,x,y,z=quat.unbind(-1)
|
||||
rot=torch.stack([1-2*(y*y+z*z),2*(x*y-w*z),2*(x*z+w*y),2*(x*y+w*z),1-2*(x*x+z*z),2*(y*z-w*x),2*(x*z-w*y),2*(y*z+w*x),1-2*(x*x+y*y)],-1).reshape(-1,3,3)
|
||||
projected=(view[:3,:3]@rot)*scales[:,None,:];cov=projected@projected.transpose(-1,-2)
|
||||
cov2=cov[:,:2,:2]*torch.diag(k)[:2][None,:,None]*torch.diag(k)[:2][None,None,:];cov2[:,0,0]+=.3;cov2[:,1,1]+=.3
|
||||
conic=torch.linalg.inv(cov2);screen=m[:,:2]*torch.diag(k)[:2]+k[:2,2];order=torch.argsort(m[:,2],stable=True)
|
||||
coeff=coefficients(means,quats,scales,view,k);traces=[]
|
||||
for (px,py),role in queries.items():
|
||||
delta=torch.tensor([px+.5,py+.5],device='cuda')-screen;power=.5*torch.einsum('ni,nij,nj->n',delta,conic,delta)
|
||||
a=torch.minimum(opacity*torch.exp(-power),torch.tensor(.999,device='cuda'));a=torch.where(a>=1./255,a,0.)[order]
|
||||
after=torch.cumprod(1-a,dim=0);before=torch.cat([torch.ones(1,device='cuda'),after[:-1]]);weights=before*a;weights=torch.where(after>1e-4,weights,0.)
|
||||
total=weights.sum();ed=(weights*m[order,2]).sum()/total;ray=torch.tensor([(px+.5-float(k[0,2]))/float(k[0,0]),(py+.5-float(k[1,2]))/float(k[1,1])],device='cuda')
|
||||
localdepth=coeff[:,0]+(coeff[:,1:]*ray).sum(-1);conditional=(weights*localdepth[order]).sum()/total
|
||||
cumulative=weights.cumsum(0)/total;quantile=[float(m[order[torch.searchsorted(cumulative,torch.tensor(v,device='cuda')).clamp_max(len(order)-1)],2]) for v in [.05,.5,.95]]
|
||||
best=torch.topk(weights,20);ids=order[best.indices];zmin=float((m[order,2])[weights>total*.001].min());zmax=float((m[order,2])[weights>total*.001].max())
|
||||
trace=dict(pixel=[px,py],role=role,native_depth=float(depth[py,px]),reproduced_depth=float(ed),native_alpha=float(alpha[py,px]),reproduced_alpha=float(total),conditional_depth=float(conditional),
|
||||
depth_quantiles_05_50_95=quantile,significant_depth_range=[zmin,zmax],contributors=[])
|
||||
for idx,weight in zip(ids.cpu().numpy(),best.values.cpu().numpy()):
|
||||
index=int(indices[idx]);s=np.exp(np.array([data[index]['scale_'+str(i)] for i in range(3)]));eig=np.sort(s)
|
||||
trace['contributors'].append(dict(index=index,weight=float(weight),source_world_xyz=xyz[index].tolist(),camera_depth=float(m[idx,2]),conditional_depth=float(localdepth[idx]),
|
||||
source_scale=s.tolist(),thickness_ratio=float(eig[0]/eig[-1]),opacity=float(opacity[idx])))
|
||||
traces.append(trace)
|
||||
report.update(traces=traces,source_gaussians=len(indices),source_sha256=request['source']['sha256'],
|
||||
max_depth_reproduction_error=max(abs(t['native_depth']-t['reproduced_depth']) for t in traces),
|
||||
max_alpha_reproduction_error=max(abs(t['native_alpha']-t['reproduced_alpha']) for t in traces),seconds=time.monotonic()-begin)
|
||||
(out/'endpoint-cause.json').write_text(json.dumps(report,indent=2));print('CAUSE_REPORT',report['max_depth_reproduction_error'],report['max_alpha_reproduction_error'],report['seconds'],flush=True)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Bounded feasibility experiment from image-derived poses only.
|
||||
|
||||
No prior map or reference contour is read. An exhausted search is not an
|
||||
infeasibility certificate. Successful poses still need a fresh normal run.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import json,time
|
||||
import numpy as np
|
||||
from scipy.optimize import differential_evolution
|
||||
from shapely.geometry import shape
|
||||
from ground_observations import GroundObservations,sha
|
||||
from candidate_registry import verify
|
||||
from admission_contract import AdmissionContract
|
||||
from standard_arrow_templates import polygon
|
||||
|
||||
|
||||
def run(focus_groups):
|
||||
root=Path('/result');out=Path('/out');obs=GroundObservations()
|
||||
registry=json.loads((root/'candidates.json').read_text());verify('/symbolplan',registry)
|
||||
diagnostics=json.loads((root/'diagnostics.json').read_text());records=[]
|
||||
for d in diagnostics:
|
||||
if d['group'] not in focus_groups:continue
|
||||
rows=[r for r in registry['candidates'] if r['group']==d['group']];extent=shape(rows[0]['extent'])
|
||||
contract=AdmissionContract(rows,extent,obs.grid(extent),obs.grid(extent,cell=.04))
|
||||
for c in sorted(d['direct_options'],key=lambda v:-v['initial_score']):
|
||||
if c['initial_score']<.65:continue
|
||||
kind,profile=c['kind'],c['profile'];starts=[np.array(c['initial_pose'])]
|
||||
starts.extend(np.array(v['pose']) for v in c.get('start_diagnostics',[]))
|
||||
values=np.array(starts);pad=np.array([.20,.15,.04,.06]);low=values.min(0)-pad;high=values.max(0)+pad
|
||||
low[3]=max(.75,low[3]);high[3]=min(1.25,high[3]);origin=values[0];scale=np.array([1.,1.,.2,.2])
|
||||
bounds=list(zip((low-origin)/scale,(high-origin)/scale));best=[None];calls=[0];begin=time.monotonic();generations=[0]
|
||||
def evaluate(delta):
|
||||
p=origin+np.asarray(delta)*scale;q=polygon(kind,profile,p)
|
||||
result=contract.measure(q,kind,profile,p);v=np.maximum(-np.asarray(result['constraint_values']),0)
|
||||
loss=-1.-result['witness']['target_iou']*.001 if result['accepted'] else float(v.max()+v.mean())
|
||||
calls[0]+=1
|
||||
if best[0] is None or loss<best[0]['loss']:
|
||||
best[0]=dict(loss=loss,pose=p.tolist(),decision=result)
|
||||
return loss
|
||||
def callback(xk,convergence):
|
||||
generations[0]+=1
|
||||
if generations[0]%10==0:print('FEASIBILITY',d['group'],kind,profile,generations[0],calls[0],best[0]['loss'],flush=True)
|
||||
return best[0]['decision']['accepted'] or time.monotonic()-begin>300
|
||||
solved=differential_evolution(evaluate,bounds,popsize=10,maxiter=120,tol=0.,atol=0.,
|
||||
seed=20261016,polish=False,updating='immediate',x0=(starts[0]-origin)/scale,callback=callback)
|
||||
bestpose=best[0]['pose'];q=polygon(kind,profile,bestpose)
|
||||
independent=contract.measure(q,kind,profile,bestpose,independent=True)
|
||||
record=dict(group=d['group'],kind=kind,profile=profile,pose=bestpose,decision=independent,
|
||||
calls=calls[0],generations=generations[0],seconds=time.monotonic()-begin,bounds=list(zip(low.tolist(),high.tolist())),
|
||||
initial_poses=[s.tolist() for s in starts],reference_input=False,exhaustion_is_not_infeasibility_proof=True)
|
||||
records.append(record);(out/'feasibility.json').write_text(json.dumps(dict(records=records,evaluation_only=True)))
|
||||
print('FEASIBILITY_RESULT',kind,profile,independent['accepted'],independent['constraint_violation'],record['seconds'],flush=True)
|
||||
if independent['accepted']:break
|
||||
(out/'feasibility.json').write_text(json.dumps(dict(records=records,evaluation_only=True,prior_map_used=False)))
|
||||
@@ -0,0 +1,346 @@
|
||||
"""Shared orthographic observations and explicit unknown/occluded ground.
|
||||
|
||||
Only the original systematic render tiles are used. A perspective road label
|
||||
is not an input. Context/ground depth agreement is a conservative observation
|
||||
test, not proof of pavement semantics or traversability.
|
||||
"""
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
import cv2
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from fit_scene import project, world
|
||||
from row_evidence import choose_owners
|
||||
from paint_channels_fast import paint_mask
|
||||
|
||||
VERSION = 'orthographic-ground-observations-v8'
|
||||
POLICY = dict(marking_domain='visible-plan-xy',local_depth_span_role='height-quality-only',alpha_min=.85, depth_agreement_m=.12, local_depth_span_m=.18,
|
||||
local_window_px=5, window_m=16., stride_m=8., core_fraction=.03)
|
||||
PHOTOMETRY = dict(cell_m=.025,context_m=1.2,calibration_observability='visible-plan-xy-v1',
|
||||
calibration='one immutable object observation frame, before pose search',
|
||||
threshold='Otsu, floor 15; exclusive declared white/yellow channels; brightness unchanged',
|
||||
query='same paint samples for proposal, placement and every verifier',
|
||||
anchor='first-pass semantic association; never fitted geometry',
|
||||
background='3m median illumination; no minimum propagation from dark cracks',
|
||||
filter_halo_m=1.5,calibration_scope='immutable object frame only; halo excluded')
|
||||
|
||||
|
||||
def sha(path):
|
||||
h = hashlib.sha256()
|
||||
with Path(path).open('rb') as f:
|
||||
for chunk in iter(lambda: f.read(1024*1024), b''):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def geometric_support(context, ground):
|
||||
if not (np.allclose(context['view'], ground['view']) and
|
||||
np.allclose(context['intrinsics'], ground['intrinsics'])):
|
||||
raise ValueError('Context/ground camera mismatch')
|
||||
a, b = context['depth'], ground['depth']
|
||||
finite = np.isfinite(a) & np.isfinite(b) & (a > 0) & (b > 0)
|
||||
# Opacity and depth have different domains. A low-opacity neighbour is
|
||||
# not a zero-metre surface. Keep all 25 finite geometric measurements for
|
||||
# the same span test; opacity still gates the evaluated point itself.
|
||||
# Missing/nonfinite geometry still invalidates its whole neighbourhood.
|
||||
safe = np.where(finite, b, 0).astype('float32')
|
||||
ratio=b.shape[0]/int(ground.get('compatibility_resolution',b.shape[0]))
|
||||
width=2*int(np.ceil((POLICY['local_window_px']-1)/2*ratio))+1
|
||||
kernel = np.ones((width,)*2, 'uint8')
|
||||
neighborhood = cv2.erode(finite.astype('uint8'), kernel) > 0
|
||||
span = cv2.dilate(safe, kernel) - cv2.erode(safe, kernel)
|
||||
return finite & neighborhood & (span <= POLICY['local_depth_span_m'])
|
||||
|
||||
|
||||
def ground_support(context, ground):
|
||||
return (geometric_support(context,ground) &
|
||||
(context['alpha'] >= POLICY['alpha_min']) & (ground['alpha'] >= POLICY['alpha_min']) &
|
||||
(np.abs(context['depth']-ground['depth']) <= POLICY['depth_agreement_m']))
|
||||
|
||||
|
||||
def read(array, uv, *, nearest=False):
|
||||
uv = np.asarray(uv, 'float32')
|
||||
return np.concatenate([
|
||||
cv2.remap(array, q[:, 0, None], q[:, 1, None],
|
||||
cv2.INTER_NEAREST if nearest else cv2.INTER_LINEAR,
|
||||
borderMode=cv2.BORDER_CONSTANT, borderValue=0).reshape(len(q), -1)
|
||||
for q in np.array_split(uv, max(1, int(np.ceil(len(uv)/20000))))])
|
||||
|
||||
|
||||
def sample_ground_support(context, ground, uv, geometry_mask=None):
|
||||
valid=geometric_support(context,ground) if geometry_mask is None else geometry_mask
|
||||
geometry=read(valid.astype('uint8'),uv,nearest=True).ravel()>0
|
||||
a=read(context['alpha'].astype('float32',copy=False),uv).ravel()
|
||||
b=read(ground['alpha'].astype('float32',copy=False),uv).ravel()
|
||||
gap=np.abs(read(context['depth'],uv).ravel()-read(ground['depth'],uv).ravel())
|
||||
return geometry & (a>=POLICY['alpha_min']) & (b>=POLICY['alpha_min']) & (gap<=POLICY['depth_agreement_m'])
|
||||
|
||||
|
||||
|
||||
|
||||
def sample_visible_support(context,ground,uv):
|
||||
"""Visibility of paint in XY, separate from continuity of expected depth."""
|
||||
if not (np.allclose(context['view'],ground['view']) and np.allclose(context['intrinsics'],ground['intrinsics'])):
|
||||
raise ValueError('Context/ground camera mismatch')
|
||||
a=read(context['alpha'].astype('float32',copy=False),uv).ravel();b=read(ground['alpha'].astype('float32',copy=False),uv).ravel()
|
||||
x=read(context['depth'],uv).ravel();y=read(ground['depth'],uv).ravel()
|
||||
return (np.isfinite(x)&np.isfinite(y)&(x>0)&(y>0)&(a>=POLICY['alpha_min'])&(b>=POLICY['alpha_min'])&
|
||||
(np.abs(x-y)<=POLICY['depth_agreement_m']))
|
||||
|
||||
|
||||
def surface_sample_evidence(context, ground, uv, geometry_mask=None):
|
||||
"""Explain the existing veto; never repair, smooth or replace a measurement.
|
||||
|
||||
RGB+ED is the alpha-weighted mean of Gaussian centre depths, not a measured
|
||||
opaque surface. A discontinuity here must remain unresolved unless another
|
||||
qualified geometric observation establishes the surface. High alpha alone
|
||||
cannot establish that geometry.
|
||||
"""
|
||||
uv=np.asarray(uv,'float32')
|
||||
if not len(uv):return []
|
||||
accepted=sample_ground_support(context,ground,uv,geometry_mask)
|
||||
ca=read(context['alpha'].astype('float32',copy=False),uv).ravel()
|
||||
ga=read(ground['alpha'].astype('float32',copy=False),uv).ravel()
|
||||
cd=read(context['depth'],uv).ravel();gd=read(ground['depth'],uv).ravel()
|
||||
a,b=context['depth'],ground['depth'];height,width=b.shape
|
||||
radius=int(np.ceil((POLICY['local_window_px']-1)/2*height/int(ground.get('compatibility_resolution',height))))
|
||||
rows=[]
|
||||
for i,(x,y) in enumerate(np.rint(uv).astype(int)):
|
||||
causes=[];span=None;finite=False
|
||||
if not (0<=x<width and 0<=y<height):causes.append('outside_native_depth')
|
||||
else:
|
||||
box=(slice(max(0,y-radius),min(height,y+radius+1)),slice(max(0,x-radius),min(width,x+radius+1)))
|
||||
aa,bb=a[box],b[box];valid=np.isfinite(aa)&np.isfinite(bb)&(aa>0)&(bb>0)
|
||||
finite=bool(valid.all())
|
||||
if not finite:causes.append('missing_or_nonpositive_depth')
|
||||
else:
|
||||
span=float(np.ptp(bb))
|
||||
if span>POLICY['local_depth_span_m']:causes.append('rendered_depth_span')
|
||||
if not ca[i]>=POLICY['alpha_min']:causes.append('context_opacity')
|
||||
if not ga[i]>=POLICY['alpha_min']:causes.append('ground_opacity')
|
||||
gap=float(abs(cd[i]-gd[i]))
|
||||
if not gap<=POLICY['depth_agreement_m']:causes.append('context_ground_disagreement')
|
||||
if bool(accepted[i]) != (not causes):raise AssertionError('Surface explanation changed the gate')
|
||||
rows.append(dict(pixel=[int(x),int(y)],accepted=bool(accepted[i]),causes=causes,
|
||||
context_alpha=float(ca[i]),ground_alpha=float(ga[i]),depth_gap_m=gap if np.isfinite(gap) else None,
|
||||
local_depth_span_m=span,finite_neighborhood=finite))
|
||||
return rows
|
||||
|
||||
|
||||
def metric_grid(region,cell,context):
|
||||
# Observation coordinates belong to the world lattice, not to a SAM
|
||||
# bounding box. A subpixel change of a proposal must not move the samples
|
||||
# used to judge the same physical paint.
|
||||
low=np.floor((np.asarray(region.bounds[:2])-context)/cell).astype('int64')
|
||||
high=np.ceil((np.asarray(region.bounds[2:])+context)/cell).astype('int64')
|
||||
if np.max((high-low)*cell)>20:raise ValueError('Object grid exceeds bounded footprint')
|
||||
x,y=np.meshgrid(np.arange(low[0],high[0])*cell,np.arange(low[1],high[1])*cell)
|
||||
return dict(lo=low*cell,points=np.c_[x.ravel(),y.ravel()],size=x.shape,cell=cell)
|
||||
|
||||
|
||||
class GroundObservations:
|
||||
def __init__(self, ortho='/ortho'):
|
||||
self.timings=dict(raw_view_seconds=0.)
|
||||
self.root = Path(ortho)
|
||||
self.native=Path('/native_geometry') if Path('/native_geometry/native-geometry.json').is_file() else None
|
||||
if self.native and not json.loads((self.native/'native-geometry.json').read_text())['complete']:
|
||||
raise ValueError('Native observation set is incomplete')
|
||||
self.tiles = [t for t in json.loads((self.root/'survey/tile-index.json').read_text())['tiles']
|
||||
if t['status'] == 'surveyed']
|
||||
if not self.tiles:
|
||||
raise ValueError('No orthographic observations')
|
||||
self.centers = np.array([np.mean(t['bounds_xy'], axis=0) for t in self.tiles])
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def camera(self, name):
|
||||
# Coverage needs 25 numbers, not two 1200x1200 raster planes. np.load
|
||||
# is lazy: loading only these entries avoids decompressing depth/alpha
|
||||
# for every tile again at every candidate and every grid cell.
|
||||
with np.load(self.root/'survey'/name/'top.geometry.npz') as z:
|
||||
return {key:z[key] for key in ['view','intrinsics']}
|
||||
|
||||
@lru_cache(maxsize=12)
|
||||
def geometry(self, name, ground=False):
|
||||
path = (self.root/'evidence'/(name+'.ground-dc.geometry.npz') if ground
|
||||
else self.root/'survey'/name/'top.geometry.npz')
|
||||
if self.native:
|
||||
path=self.native/(name+('.ground.npz' if ground else '.context.npz'))
|
||||
with np.load(path) as z:
|
||||
return dict(z)
|
||||
|
||||
@lru_cache(maxsize=12)
|
||||
def support(self, name):
|
||||
return geometric_support(self.geometry(name), self.geometry(name, True))
|
||||
|
||||
@lru_cache(maxsize=4)
|
||||
def rgb(self, name):
|
||||
with Image.open(self.root/'evidence'/(name+'.ground.png')) as im:
|
||||
return np.asarray(im.convert('RGB'))
|
||||
|
||||
def metric_surface(self, name, points):
|
||||
context=self.geometry(name);ground=self.geometry(name,True)
|
||||
uv=project(points,self.camera(name))
|
||||
if self.native:uv=(uv+.5)*context['depth'].shape[0]/1200-.5
|
||||
return sample_ground_support(context,ground,uv,self.support(name))
|
||||
|
||||
def surface(self,name,points):
|
||||
context=self.geometry(name);ground=self.geometry(name,True)
|
||||
uv=project(points,self.camera(name))
|
||||
if self.native:uv=(uv+.5)*context['depth'].shape[0]/1200-.5
|
||||
return sample_visible_support(context,ground,uv)
|
||||
|
||||
def depth_quality(self,grid,polygon):
|
||||
import shapely
|
||||
points=grid['points'];target=shapely.contains_xy(polygon,points[:,0],points[:,1]);records=[]
|
||||
for rank,view in enumerate(grid['views']):
|
||||
known=target&view['observed'].ravel();owners=view['tile_indices'].ravel();stable=0
|
||||
for owner in np.unique(owners[known]):
|
||||
selected=known&(owners==owner);name=self.tiles[int(owner)]['id']
|
||||
stable+=int(self.metric_surface(name,points[selected]).sum())
|
||||
records.append(dict(rank=rank,observed_samples=int(known.sum()),continuous_depth_samples=stable,
|
||||
continuous_depth_fraction=stable/int(known.sum()) if known.any() else None))
|
||||
return dict(domain='Gaussian expected-depth continuity; not physical survey',records=records,
|
||||
affects_xy_admission=False,height_field_certified=False)
|
||||
|
||||
def explain_object_surface(self, grid, polygon, pose):
|
||||
"""Bounded final diagnostics from the same pixels; not a search objective."""
|
||||
import collections
|
||||
import shapely
|
||||
points=grid['points'];inside=shapely.contains_xy(polygon,points[:,0],points[:,1])
|
||||
if not inside.any():return []
|
||||
t=(points-np.asarray(pose[:2]))@np.array([np.cos(pose[2]),np.sin(pose[2])])
|
||||
masks=dict(object=inside,tail=inside&(t<t[inside].min()+.20),head=inside&(t>t[inside].max()-.20))
|
||||
records=[]
|
||||
for rank,view in enumerate(grid['views']):
|
||||
owners=view['tile_indices'].ravel();known=view['observed'].ravel();allowed=view['allowed'].ravel()
|
||||
measurements={}
|
||||
indices=np.flatnonzero(inside&known&~allowed)
|
||||
for owner in np.unique(owners[indices]):
|
||||
selected=indices[owners[indices]==owner];name=self.tiles[int(owner)]['id']
|
||||
context=self.geometry(name);ground=self.geometry(name,True)
|
||||
uv=project(points[selected],self.camera(name))
|
||||
if self.native:uv=(uv+.5)*context['depth'].shape[0]/1200-.5
|
||||
rows=surface_sample_evidence(context,ground,uv,self.support(name))
|
||||
for index,row in zip(selected,rows):measurements[int(index)]=dict(row,tile=name,world_xy=points[index].tolist())
|
||||
for part,mask in masks.items():
|
||||
selected=mask&known;bad=np.flatnonzero(selected&~allowed)
|
||||
counts=collections.Counter(c for i in bad for c in measurements[int(i)]['causes'])
|
||||
spans=[measurements[int(i)]['local_depth_span_m'] for i in bad if measurements[int(i)]['local_depth_span_m'] is not None]
|
||||
records.append(dict(rank=rank,part=part,samples=int(mask.sum()),observed_samples=int(selected.sum()),valid_samples=int((selected&allowed).sum()),
|
||||
rejected_samples=len(bad),cause_counts=dict(counts),max_rejected_span_m=max(spans) if spans else None,
|
||||
examples=[measurements[int(i)] for i in bad[:8]],depth_semantics='alpha-weighted-Gaussian-centre-depth',
|
||||
physical_surface_cause='not_identified_from_rendered_depth_alone' if len(bad) else None,
|
||||
corrective_pose_search_authorized_by_diagnostic=False))
|
||||
return records
|
||||
|
||||
def inventory(self):
|
||||
paths = [self.root/'survey/tile-index.json']
|
||||
for t in self.tiles:
|
||||
n = t['id']
|
||||
paths.extend([self.root/'survey'/n/'top.geometry.npz',
|
||||
self.root/'evidence'/(n+'.ground-dc.geometry.npz'),
|
||||
self.root/'evidence'/(n+'.ground.png')])
|
||||
files = {p.relative_to(self.root).as_posix(): sha(p) for p in paths}
|
||||
if self.native:
|
||||
manifest=json.loads((self.native/'native-geometry.json').read_text())
|
||||
if manifest['tiles']!=len(self.tiles):raise ValueError('Native survey coverage mismatch')
|
||||
for r in manifest['records']:
|
||||
value=sha(self.native/r['file'])
|
||||
if value!=r['sha256']:raise ValueError('Native geometry bytes changed')
|
||||
files['native-geometry/'+r['file']]=value
|
||||
return dict(version=VERSION, policy=POLICY, photometry=PHOTOMETRY, files=files,
|
||||
snapshot=hashlib.sha256(json.dumps(files, sort_keys=True).encode()).hexdigest(),
|
||||
perspective_input=False, independent_acquisitions=False)
|
||||
|
||||
def raw_views(self,lattice):
|
||||
started=time.monotonic()
|
||||
points=lattice['points'];size=lattice['size']
|
||||
# Reject only cameras whose projected world rectangle cannot overlap.
|
||||
# This is a broad-phase geometric test, independent of image content.
|
||||
low=points.min(0);high=points.max(0)
|
||||
corners=np.array([low,[high[0],low[1]],high,[low[0],high[1]]])
|
||||
indices=[]
|
||||
for i,tile in enumerate(self.tiles):
|
||||
uv=project(corners,self.camera(tile['id']))
|
||||
if np.any(uv.max(0)<20) or np.any(uv.min(0)>=1180):continue
|
||||
indices.append(i)
|
||||
distance=np.linalg.norm(points[:,None]-self.centers[indices][None],axis=2)
|
||||
cover=np.zeros(distance.shape,bool)
|
||||
for j,i in enumerate(indices):
|
||||
uv=project(points,self.camera(self.tiles[i]['id']))
|
||||
cover[:,j]=(uv.min(1)>=20)&(uv.max(1)<1180)
|
||||
if indices:
|
||||
local_owners=choose_owners(distance,cover)
|
||||
owners=np.full(local_owners.shape,-1,int)
|
||||
present=local_owners>=0
|
||||
owners[present]=np.asarray(indices)[local_owners[present]]
|
||||
else:owners=np.full((len(points),2),-1,int)
|
||||
rows=[]
|
||||
for rank in range(2):
|
||||
rgb=np.zeros((len(points),3),'uint8');allowed=np.zeros(len(points),bool)
|
||||
observed=owners[:,rank]>=0;names=[]
|
||||
for i in np.unique(owners[:,rank]):
|
||||
if i<0:continue
|
||||
ix=np.flatnonzero(owners[:,rank]==i)
|
||||
name=self.tiles[i]['id'];names.append(name)
|
||||
raw=self.rgb(name);uv=project(points[ix],self.camera(name))
|
||||
native=(uv+.5)*np.array(raw.shape[1::-1])/1200-.5
|
||||
rgb[ix]=read(raw,native);allowed[ix]=self.surface(name,points[ix])
|
||||
rows.append(dict(rgb=rgb.reshape(*size,3),allowed=allowed.reshape(size),
|
||||
observed=observed.reshape(size),names=names,tile_indices=owners[:,rank].reshape(size)))
|
||||
if hasattr(self,'timings'):self.timings['raw_view_seconds']+=time.monotonic()-started
|
||||
return rows
|
||||
|
||||
@lru_cache(maxsize=128)
|
||||
def object_frame(self,wkb):
|
||||
import shapely
|
||||
region=shapely.from_wkb(wkb);cell=PHOTOMETRY['cell_m'];context=PHOTOMETRY['context_m']
|
||||
coarse=metric_grid(region,.04,context)
|
||||
low=coarse['points'].min(0);high=coarse['points'].max(0)
|
||||
fine=metric_grid(shapely.box(*low,*high),cell,cell)
|
||||
# A spatial filter must see its whole physical neighbourhood. Padding
|
||||
# belongs to acquisition, never to the object/calibration domain.
|
||||
pad=int(round(PHOTOMETRY['filter_halo_m']/cell));height,width=fine['size']
|
||||
start=np.rint(fine['lo']/cell).astype(int)-pad
|
||||
x,y=np.meshgrid(np.arange(start[0],start[0]+width+2*pad)*cell,
|
||||
np.arange(start[1],start[1]+height+2*pad)*cell)
|
||||
expanded=dict(lo=start*cell,points=np.c_[x.ravel(),y.ravel()],size=x.shape,cell=cell)
|
||||
surrounding=self.raw_views(expanded);views=[];crop=(slice(pad,pad+height),slice(pad,pad+width))
|
||||
scope=shapely.contains_xy(region.buffer(.2),fine['points'][:,0],fine['points'][:,1]).reshape(fine['size'])
|
||||
for raw in surrounding:
|
||||
calibration=np.zeros(expanded['size'],bool);calibration[crop]=raw['allowed'][crop]
|
||||
measured=paint_mask(raw['rgb'],cell=cell,observed=raw['observed'],calibration=calibration,background='median')
|
||||
view={key:raw[key][crop].copy() for key in ['rgb','allowed','observed','tile_indices'] if key in raw}
|
||||
paint=measured[crop].copy();view.update(paint=paint,target=paint&view['allowed']&scope,names=raw['names'])
|
||||
views.append(view)
|
||||
fine['views']=views
|
||||
coarse_views=self.raw_views(coarse)
|
||||
uv=np.rint((coarse['points']-fine['lo'])/cell).astype(int)
|
||||
inside=(uv>=0).all(1)&(uv<np.array(fine['size'][::-1])).all(1)
|
||||
# Fine observations enclose every coarse sample, including boundary
|
||||
# cells. Unmeasured pixels must never become observed background.
|
||||
assert inside.all(), 'Coarse sample outside immutable paint measurement'
|
||||
scope=shapely.contains_xy(region.buffer(.2),coarse['points'][:,0],coarse['points'][:,1]).reshape(coarse['size'])
|
||||
for rank,view in enumerate(coarse_views):
|
||||
paint=np.zeros(len(uv),bool)
|
||||
paint[inside]=views[rank]['paint'][uv[inside,1],uv[inside,0]]
|
||||
paint=paint.reshape(coarse['size'])&view['observed']
|
||||
view.update(paint=paint,target=paint&view['allowed']&scope)
|
||||
coarse['views']=coarse_views
|
||||
return {cell:fine,.04:coarse}
|
||||
|
||||
def prepare_paint(self,regions):
|
||||
for i,region in enumerate(sorted(regions,key=lambda q:q.bounds)):
|
||||
self.object_frame(region.wkb)
|
||||
if (i+1)%20==0:print('OBJECT_OBSERVATIONS',i+1,'/',len(regions),flush=True)
|
||||
|
||||
def statistics(self):
|
||||
return dict(**self.timings,object_frames=self.object_frame.cache_info()._asdict())
|
||||
|
||||
def grid(self,region,cell=.025,context=1.2):
|
||||
if context!=PHOTOMETRY['context_m'] or cell not in [.025,.04]:
|
||||
raise ValueError('Use the declared immutable object measurement frame')
|
||||
return dict(self.object_frame(region.wkb)[cell],photometry=PHOTOMETRY)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Direct head-wing support integrated over immutable original pixel cells.
|
||||
|
||||
Pixel-centre inclusion produces discontinuous area ratios on small wings.
|
||||
Intersecting pixel footprints preserves the actual observation and gives a
|
||||
continuous measurement as the four-parameter template moves. No dilation.
|
||||
"""
|
||||
import numpy as np
|
||||
from shapely.geometry import box
|
||||
from shapely.affinity import rotate,translate
|
||||
from pixel_geometry import vector
|
||||
from standard_arrow_templates import PROFILES
|
||||
|
||||
|
||||
def fields(grid):
|
||||
h,w=grid['size'];cell=grid['cell'];lo=grid.get('lo',grid['points'].min(0))
|
||||
patch=dict(width_px=w,height_px=h,world_corners=np.array([lo,lo+[w*cell,0],lo+[w*cell,h*cell],lo+[0,h*cell]]))
|
||||
return [dict(observed=vector(v['observed'],patch),
|
||||
known=vector(v['observed']&v['allowed'],patch),
|
||||
paint=vector(v['paint']&v['observed']&v['allowed'],patch),cell=cell) for v in grid['views']]
|
||||
|
||||
|
||||
def measure(field,q,kind,parameters):
|
||||
if kind not in ('straight_arrow','straight_left_arrow','straight_right_arrow'):return None
|
||||
x,y,a,length,width,stroke=parameters[:6];scale=stroke/.15
|
||||
head_lengths={v['L1'] for v in PROFILES.values()}
|
||||
if len(head_lengths)!=1:raise ValueError('Head measurement needs an explicit profile')
|
||||
start=length-next(iter(head_lengths))*scale;rows=[]
|
||||
for name,sign in [('left',1),('right',-1)]:
|
||||
local=box(start,stroke/2,length,width) if sign>0 else box(start,-width,length,-stroke/2)
|
||||
wing=q.intersection(translate(rotate(local,a,origin=(0,0),use_radians=True),xoff=x,yoff=y))
|
||||
covered=wing.intersection(field['observed']);known=wing.intersection(field['known'])
|
||||
rows.append(dict(wing=name,coverage=min(1.,covered.area/max(wing.area,1e-12)),
|
||||
valid=min(1.,known.area/max(covered.area,1e-12)),
|
||||
direct_support=min(1.,known.intersection(field['paint']).area/max(known.area,1e-12)),
|
||||
pixels=known.area/field['cell']**2,measurement='original-pixel-cell-area'))
|
||||
return rows
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Independent original-pixel whole-object measurements."""
|
||||
import cv2
|
||||
import numpy as np
|
||||
import shapely
|
||||
from arrow_evidence import directional_score
|
||||
import head_observation
|
||||
from observation_checks import branch_evidence
|
||||
|
||||
|
||||
def evidence(poly, kind, parameters, extent, grid, head_grid=None):
|
||||
records = []
|
||||
head_fields=head_observation.fields(grid if head_grid is None else head_grid)
|
||||
points = grid['points']; cell = grid['cell']
|
||||
target = shapely.contains_xy(poly, points[:, 0], points[:, 1]).reshape(grid['size'])
|
||||
for rank, view in enumerate(grid['views']):
|
||||
rgb, allowed, observed, paint = [view[k] for k in ['rgb','allowed','observed','paint']]
|
||||
score = directional_score(rgb, allowed, points, poly, cell=cell, kind=kind, parameters=parameters,
|
||||
observed=observed, paint_override=paint, semantic_extent=extent,
|
||||
alpha_good=allowed)
|
||||
score['branch_identity'] = branch_evidence(paint, allowed, observed, points, poly, kind, parameters)
|
||||
score['head_identity'] = head_observation.measure(head_fields[rank],poly,kind,parameters)
|
||||
near = cv2.dilate(paint.astype('uint8'), cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))) > 0
|
||||
known = target & allowed & observed
|
||||
score.update(observed_support=float(near[known].mean()) if known.any() else 0.,
|
||||
paint_valid=float(allowed[target].mean()) if target.any() else 0.,
|
||||
paint_coverage=float(observed[target].mean()) if target.any() else 0., rank=rank,
|
||||
surface_policy='visible-plan-xy; ED-span-is-quality-only', source_tiles=view['names'])
|
||||
records.append(score)
|
||||
return records
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
"""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']
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Compile invariant observation fields once for a four-parameter pose solve.
|
||||
|
||||
Independent final verification keeps using the original pixel evaluator. This
|
||||
accelerator changes neither masks nor gates; it removes repeated conversion,
|
||||
morphology and component labelling of the same immutable observation.
|
||||
"""
|
||||
import cv2
|
||||
import numpy as np
|
||||
import shapely
|
||||
from discovery_rules import POLICY
|
||||
import head_observation
|
||||
from observation_checks import branch_evidence
|
||||
|
||||
|
||||
class ObservationEvaluator:
|
||||
def __init__(self,extent,grid,head_grid=None):
|
||||
self.grid=grid;self.extent=extent;self.fields=[]
|
||||
self.head_fields=head_observation.fields(grid if head_grid is None else head_grid)
|
||||
points=grid['points'];size=grid['size']
|
||||
self.scope=shapely.contains_xy(extent.buffer(.20),points[:,0],points[:,1]).reshape(size)
|
||||
self.kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
|
||||
for view in grid['views']:
|
||||
paint,allowed,observed=[view[k] for k in ['paint','allowed','observed']]
|
||||
_,labels=cv2.connectedComponents((paint&allowed&observed).astype('uint8'),8)
|
||||
near=cv2.dilate(paint.astype('uint8'),self.kernel)>0
|
||||
self.fields.append(dict(view=view,labels=labels,near=near))
|
||||
|
||||
def evaluate(self,q,kind,parameters):
|
||||
grid=self.grid;points=grid['points'];size=grid['size']
|
||||
target=shapely.contains_xy(q,points[:,0],points[:,1]).reshape(size)
|
||||
wide=cv2.dilate(target.astype('uint8'),self.kernel)>0
|
||||
region=shapely.contains_xy(q.convex_hull.buffer(.15),points[:,0],points[:,1]).reshape(size)
|
||||
negative=region&~wide
|
||||
px,py,a,L,W,stroke=parameters[:6]
|
||||
u=np.array([np.cos(a),np.sin(a)]);n=np.array([-u[1],u[0]])
|
||||
local=points-[px,py];t=(local@u).reshape(size);side=(local@n).reshape(size)
|
||||
longitudinal=t[target];t0,t1=(float(longitudinal.min()),float(longitudinal.max())) if longitudinal.size else (0.,L)
|
||||
result=[]
|
||||
for rank,field in enumerate(self.fields):
|
||||
view=field['view'];paint,allowed,observed=[view[k] for k in ['paint','allowed','observed']]
|
||||
near=field['near'];labels=field['labels']
|
||||
owners=set(np.unique(labels[target&self.scope]))-{0}
|
||||
connected=np.isin(labels,list(owners))
|
||||
score=dict(valid=float(allowed[region&observed].mean()) if (region&observed).any() else 0.,
|
||||
support=float(near[target&observed].mean()) if (target&observed).any() else 0.,
|
||||
recall=float(wide[paint®ion&allowed].mean()) if (paint®ion&allowed).any() else 0.,
|
||||
negative_paint=float(paint[negative&allowed].mean()) if (negative&allowed).any() else 1.,
|
||||
connected_recall=float(wide[connected].mean()) if connected.any() else 0.,
|
||||
connected_at_window_edge=bool(connected[0].any() or connected[-1].any() or connected[:,0].any() or connected[:,-1].any()),
|
||||
connectivity_scope='whole-observed-paved-component-with-semantic-seed',parts=[],ends=[])
|
||||
regions=[('head',t>L*.80),('tail',t<L*.25)]
|
||||
if kind.startswith('straight_') and kind!='straight_arrow':regions.append(('branch',side*(1 if 'left' in kind else -1)>W*.24))
|
||||
for name,where in regions:
|
||||
select=target&where;coverage=float(observed[select].mean()) if select.any() else 0.;select &= observed
|
||||
score['parts'].append(dict(part=name,coverage=coverage,valid=float(allowed[select].mean()) if select.any() else 0.,support=float(near[select].mean()) if select.any() else 0.))
|
||||
for name,interior,exterior in [('tail',t<L*.20,(t<-POLICY['glyph_end_probe_start_m'])&(t>-POLICY['glyph_end_probe_stop_m'])),('head',t>L*.90,(t>L+POLICY['glyph_end_probe_start_m'])&(t<L+POLICY['glyph_end_probe_stop_m']))]:
|
||||
sides=side[target&interior];offset=float(np.median(sides)) if len(sides) else 0.
|
||||
select=exterior&(abs(side-offset)<max(.12,stroke*.6));known=select&observed
|
||||
endpoint=target&((t<t0+.20) if name=='tail' else (t>t1-.20))
|
||||
ids=set(np.unique(labels[endpoint]))-{0};continuation=np.isin(labels,list(ids))
|
||||
exterior_known=known&allowed
|
||||
score['ends'].append(dict(end=name,coverage=float(observed[endpoint].mean()) if endpoint.any() else 0.,
|
||||
valid=float(allowed[endpoint&observed].mean()) if (endpoint&observed).any() else 0.,
|
||||
paint_fraction=float(continuation[exterior_known].mean()) if exterior_known.any() else 0.,
|
||||
exterior_known_fraction=float(exterior_known[select].mean()) if select.any() else 0.,
|
||||
unconnected_paint_fraction=float((paint&allowed)[exterior_known].mean()) if exterior_known.any() else None,
|
||||
validity_scope='observed-symbol-endpoint',paint_scope='endpoint-connected-paved-paint'))
|
||||
if kind=='straight_arrow':
|
||||
flank=(t>L*.80)&(t<L*1.05)&(abs(side)<W*.55)&~wide&allowed&observed
|
||||
score['head_flank_paint']=float(paint[flank].mean()) if flank.any() else 1.
|
||||
score['branch_identity']=branch_evidence(paint,allowed,observed,points,q,kind,parameters,cell=grid['cell'])
|
||||
score['head_identity']=head_observation.measure(self.head_fields[rank],q,kind,parameters)
|
||||
known=target&allowed&observed
|
||||
score.update(observed_support=float(near[known].mean()) if known.any() else 0.,
|
||||
paint_valid=float(allowed[target].mean()) if target.any() else 0.,paint_coverage=float(observed[target].mean()) if target.any() else 0.,
|
||||
rank=rank,surface_policy='visible-plan-xy; ED-span-is-quality-only',source_tiles=view['names'])
|
||||
result.append(score)
|
||||
return result
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Fit one immutable preset under the same geometric constraints as admission."""
|
||||
import cv2
|
||||
import shapely
|
||||
import numpy as np
|
||||
from scipy.ndimage import map_coordinates
|
||||
from scipy.optimize import least_squares
|
||||
from standard_arrow_templates import preset
|
||||
from pixel_geometry import vector
|
||||
from direct_fixed import fit_target
|
||||
from registration import POLICY as GEOMETRY_POLICY
|
||||
from plan_marking_policy import source_correspondence, MIN_SOURCE_CORRESPONDENCE
|
||||
|
||||
VERSION = 'topdown-object-observation-v22'
|
||||
|
||||
|
||||
def grid_polygon(mask, grid):
|
||||
cell=grid['cell'];height,width=grid['size'];low=grid['lo']
|
||||
corners=np.array([low,low+[width*cell,0],low+[width*cell,height*cell],low+[0,height*cell]])
|
||||
patch=dict(world_corners=corners,width_px=width,height_px=height,mpp=cell)
|
||||
value=vector(mask,patch)
|
||||
return value
|
||||
|
||||
|
||||
def constraints_for(grid, proposal_targets=None):
|
||||
# Use the exact sampled registration contract. The former independent
|
||||
# polygon-area and interpolated-distance constraints could veto a pose
|
||||
# passing final checks. No admission threshold changes here.
|
||||
from registration_evaluator import RegistrationEvaluator
|
||||
if 'points' not in grid:
|
||||
y,x=np.indices(grid['size']);grid['points']=np.c_[x.ravel(),y.ravel()]*grid['cell']+grid['lo']
|
||||
evaluator=RegistrationEvaluator(grid)
|
||||
def constraints(q):
|
||||
values=evaluator.constraints(q)
|
||||
if proposal_targets:
|
||||
overlap=max(source_correspondence(q,p) for p in proposal_targets)
|
||||
values.append(overlap-MIN_SOURCE_CORRESPONDENCE)
|
||||
return values
|
||||
return constraints
|
||||
|
||||
|
||||
def boundary_seed(grid):
|
||||
cell=grid['cell'];low=grid['lo'];fields=[]
|
||||
for v in grid['views']:
|
||||
paint=v['target'].astype('uint8')
|
||||
if not paint.any():continue
|
||||
outside=cv2.distanceTransform(1-paint,cv2.DIST_L2,cv2.DIST_MASK_PRECISE)
|
||||
inside=cv2.distanceTransform(paint,cv2.DIST_L2,cv2.DIST_MASK_PRECISE)
|
||||
fields.append((((outside-inside)*cell).astype('float64'),v['observed']))
|
||||
def seed(kind,profile,pose,bounds):
|
||||
template=preset(kind,profile)
|
||||
distances=np.arange(0,template.length,.04)
|
||||
unit=shapely.get_coordinates(shapely.line_interpolate_point(template.boundary,distances))
|
||||
def residual(delta):
|
||||
x,y,a,factor=pose+delta;rotation=np.array([[np.cos(a),np.sin(a)],[-np.sin(a),np.cos(a)]])
|
||||
uv=(unit@rotation*factor+[x,y]-low)/cell;values=[]
|
||||
for field,observed in fields:
|
||||
error=map_coordinates(field,[uv[:,1],uv[:,0]],order=1,mode='constant',cval=1.,prefilter=False)
|
||||
known=map_coordinates(observed.astype('uint8'),[uv[:,1],uv[:,0]],order=0,mode='constant',cval=0,prefilter=False)>0
|
||||
values.extend(np.where(known,error,0.))
|
||||
return values
|
||||
lower,upper=np.asarray(bounds).T
|
||||
solved=least_squares(residual,np.zeros(4),bounds=(lower-pose,upper-pose),x_scale=[.2,.2,.03,.03],
|
||||
loss='soft_l1',f_scale=.05,max_nfev=80,
|
||||
ftol=1e-6,xtol=1e-6,gtol=1e-6)
|
||||
return pose+solved.x
|
||||
return seed
|
||||
|
||||
|
||||
def fit_grid(grid, proposal_targets=None, object_constraints=None):
|
||||
view=grid['views'][0]
|
||||
target=grid_polygon(view['target'] & view['allowed'] & view['observed'],grid)
|
||||
if target.is_empty:return []
|
||||
def possible(template):
|
||||
if not proposal_targets:return True
|
||||
minimum,maximum=template.area*.75**2,template.area*1.25**2
|
||||
# Intersection cannot exceed the smaller area; union cannot be less
|
||||
# than the larger. This proves some type/profile pairs infeasible
|
||||
# before evaluating expensive pixel evidence, without changing a gate.
|
||||
return min(maximum,target.area)/max(minimum,target.area)>=GEOMETRY_POLICY['min_iou']
|
||||
return fit_target(target,geometric_constraints=(lambda q: []) if object_constraints is not None else constraints_for(grid,proposal_targets),
|
||||
object_constraints=object_constraints,preset_filter=possible,evidence_seed=boundary_seed(grid),
|
||||
seed_targets=proposal_targets)
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Spherical-harmonic colour evaluation for parallel orthographic rays.
|
||||
|
||||
The renderer's projection and alpha/depth computation are unchanged. SH is
|
||||
sampled in the actual optical-axis direction, not a perspective direction from
|
||||
an arbitrary translated camera centre. Coefficients remain immutable.
|
||||
"""
|
||||
import torch
|
||||
from gsplat.cuda._wrapper import spherical_harmonics
|
||||
|
||||
|
||||
def colours(sh,source_to_camera,degree):
|
||||
inverse=torch.linalg.inv(source_to_camera)
|
||||
direction=inverse[:3,2]
|
||||
direction=direction/torch.linalg.norm(direction)
|
||||
directions=direction[None].expand(len(sh),3).contiguous()
|
||||
return torch.clamp_min(spherical_harmonics(degree,directions,sh)+.5,0.)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Orthographic conditional Gaussian depth; no spatial smoothing or surface fit.
|
||||
|
||||
For each original anisotropic Gaussian, condition its camera-space normal
|
||||
distribution on the pixel ray. Composite that conditional mean with the
|
||||
unchanged rasterizer weights. This is an experimental measurement, not a
|
||||
substitution for validating the source geometry.
|
||||
"""
|
||||
import torch
|
||||
|
||||
VERSION='orthographic-conditional-gaussian-depth-v1'
|
||||
EPS2D=.3
|
||||
|
||||
def coefficients(means,quats,scales,view,k):
|
||||
chunks=[]
|
||||
for start in range(0,len(means),200000):
|
||||
m=means[start:start+200000];q=quats[start:start+200000];s=scales[start:start+200000]
|
||||
q=q/torch.linalg.vector_norm(q,dim=-1,keepdim=True).clamp_min(1e-12)
|
||||
w,x,y,z=q.unbind(-1)
|
||||
r=torch.stack([1-2*(y*y+z*z),2*(x*y-w*z),2*(x*z+w*y),
|
||||
2*(x*y+w*z),1-2*(x*x+z*z),2*(y*z-w*x),
|
||||
2*(x*z-w*y),2*(y*z+w*x),1-2*(x*x+y*y)],-1).reshape(-1,3,3)
|
||||
rotated=view[:3,:3]@r
|
||||
cov=(rotated*s[:,None,:])@(rotated*s[:,None,:]).transpose(-1,-2)
|
||||
camera=m@view[:3,:3].T+view[:3,3]
|
||||
xy=cov[:,:2,:2].clone()
|
||||
xy[:,0,0]+=EPS2D/k[0,0]**2;xy[:,1,1]+=EPS2D/k[1,1]**2
|
||||
slope=torch.linalg.solve(xy,cov[:,:2,2,None]).squeeze(-1)
|
||||
offset=camera[:,2]-(slope*camera[:,:2]).sum(-1)
|
||||
chunks.append(torch.cat([offset[:,None],slope],-1))
|
||||
return torch.cat(chunks,0)
|
||||
|
||||
def decode(rendered,alpha,k):
|
||||
height,width=alpha.shape
|
||||
y,x=torch.meshgrid(torch.arange(height,device=alpha.device,dtype=alpha.dtype)+.5,
|
||||
torch.arange(width,device=alpha.device,dtype=alpha.dtype)+.5,indexing='ij')
|
||||
value=(rendered[:,:,0]+rendered[:,:,1]*(x-k[0,2])/k[0,0]+rendered[:,:,2]*(y-k[1,2])/k[1,1])
|
||||
return value/alpha.clamp_min(1e-10)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Bit-exact disk morphology using a union of separable rectangles.
|
||||
|
||||
The structuring element is exactly OpenCV's existing ellipse. The morphology
|
||||
acceleration is bit-exact. White/yellow ownership below is deliberately disjoint;
|
||||
brightness thresholds, calibration domain and physical filter scales are retained.
|
||||
"""
|
||||
from functools import lru_cache
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
|
||||
@lru_cache(maxsize=16)
|
||||
def rectangles(k):
|
||||
ellipse=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k,k));widths=ellipse.sum(axis=1)
|
||||
radius=k//2;parts=[];proof=np.zeros_like(ellipse)
|
||||
for width in np.unique(widths):
|
||||
if not width:continue
|
||||
half_height=int(np.max(np.abs(np.flatnonzero(widths==width)-radius)))
|
||||
width=int(width);height=2*half_height+1
|
||||
parts.append(np.ones((height,width),'uint8'))
|
||||
proof[radius-half_height:radius+half_height+1,radius-width//2:radius+width//2+1]=1
|
||||
if not np.array_equal(proof,ellipse):raise ValueError('Ellipse decomposition changed its support')
|
||||
return tuple(parts)
|
||||
|
||||
|
||||
def opening(gray,k):
|
||||
if k<=31:return cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k,k)))
|
||||
eroded=np.full_like(gray,255)
|
||||
for rectangle in rectangles(k):np.minimum(eroded,cv2.erode(gray,rectangle),out=eroded)
|
||||
opened=np.zeros_like(gray)
|
||||
for rectangle in rectangles(k):np.maximum(opened,cv2.dilate(eroded,rectangle),out=opened)
|
||||
return opened
|
||||
|
||||
|
||||
def paint_mask(rgb,channel='white',cell=.04,observed=None,calibration=None,background=None):
|
||||
if observed is not None and not observed.all():
|
||||
rgb=rgb.copy();rgb[~observed]=np.median(rgb[observed],axis=0).astype('uint8') if observed.any() else 0
|
||||
gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
|
||||
k=int((.72 if channel=='yellow' else 3.0)/cell)//2*2+1
|
||||
if background is None:base=opening(gray,k)
|
||||
elif background=='median':base=cv2.medianBlur(gray,k)
|
||||
else:raise ValueError('Unknown illumination measurement')
|
||||
ridge=cv2.subtract(gray,base)
|
||||
sample=ridge if observed is None else ridge[cv2.erode(observed.astype('uint8'),np.ones((k,k),np.uint8))>0]
|
||||
if calibration is not None:
|
||||
known=np.asarray(calibration,bool)&(np.ones(gray.shape,bool) if observed is None else observed)
|
||||
sample=ridge[known]
|
||||
threshold,_=cv2.threshold(sample,0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU) if sample.size else (15.,None)
|
||||
yellow=(hsv[:,:,0]>10)&(hsv[:,:,0]<38)&(hsv[:,:,1]>35)
|
||||
# Paint colours form disjoint observations. The old white gate also
|
||||
# admitted the low-saturation half of the declared yellow channel,
|
||||
# joining crossing yellow lines to white arrow components.
|
||||
color=yellow if channel=='yellow' else ((hsv[:,:,1]<100)&~yellow)
|
||||
return (True if observed is None else observed)&(ridge>max(15.,threshold))&(gray>100)&color
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Exact pixel-cell footprints in world coordinates, shared by proposal and fit.
|
||||
|
||||
OpenCV contour vertices mark centres of boundary pixels. Treating that line
|
||||
as the object's outside edge systematically removes a half pixel on each side
|
||||
of a thin stem. This module preserves the area of every observed pixel.
|
||||
"""
|
||||
import numpy as np
|
||||
import shapely
|
||||
from shapely.affinity import affine_transform
|
||||
from shapely.geometry import Polygon
|
||||
|
||||
|
||||
def vector(binary, patch):
|
||||
mask=np.asarray(binary,bool)
|
||||
if mask.shape!=(patch['height_px'],patch['width_px']):raise ValueError('Pixel shape mismatch')
|
||||
rectangles=[];active={}
|
||||
for y,row in enumerate(mask):
|
||||
changes=np.diff(np.r_[False,row,False].astype('int8'))
|
||||
runs=set(zip(np.flatnonzero(changes==1).tolist(),np.flatnonzero(changes==-1).tolist()))
|
||||
for run in set(active)-runs:
|
||||
rectangles.append((run[0]-.5,active.pop(run)-.5,run[1]-.5,y-.5))
|
||||
for run in runs-set(active):active[run]=y
|
||||
for run,start in active.items():rectangles.append((run[0]-.5,start-.5,run[1]-.5,len(mask)-.5))
|
||||
if not rectangles:return Polygon()
|
||||
bounds=np.asarray(rectangles,float)
|
||||
pixels=shapely.union_all(shapely.box(*bounds.T))
|
||||
corners=np.asarray(patch['world_corners'],float)
|
||||
if not np.allclose(corners[2],corners[1]+corners[3]-corners[0],atol=1e-7,rtol=0):
|
||||
raise ValueError('Pixel footprints require an affine orthographic patch')
|
||||
u=(corners[1]-corners[0])/patch['width_px'];v=(corners[3]-corners[0])/patch['height_px']
|
||||
return affine_transform(pixels,[u[0],v[0],u[1],v[1],*corners[0]])
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Observed XY plan markings from imperfect Gaussian scans.
|
||||
|
||||
Owner clarification 2026-10-16: consume the supplied Gaussian scene as-is;
|
||||
recover >=95% of confirmed objects, without requiring a perfect input scan.
|
||||
This is an explicit change from the former all-corner/ED-flatness contract.
|
||||
It neither changes the input scene nor certifies physical surface geometry.
|
||||
"""
|
||||
from registration import POLICY as REGISTRATION_POLICY
|
||||
|
||||
VERSION='observed-xy-markings-v5'
|
||||
MIN_SOURCE_CORRESPONDENCE=.55
|
||||
CONTRACT=dict(version=VERSION,geometry_domain='plan-xy',overlap_measurement='exact original pixel-cell area; .65 gate retained',
|
||||
local_expected_depth_span='quality-only; not a marking-presence veto',
|
||||
individual_template_corner_error='quality-only; shape judged by full original-pixel boundary and topology',
|
||||
semantic_proposal_shape='association and initialization, not a metric reference',
|
||||
source_correspondence_min=MIN_SOURCE_CORRESPONDENCE,head_identity='real paint in each wing; >=.65 direct area support over complete head wings',
|
||||
unknown_pixels='not paint; opacity and occlusion vetoes retained',
|
||||
observed_shape='original-pixel IoU, boundary mean/p90, whole-object parts, direct head-wing pixel area and same-colour connectivity',
|
||||
gaussian_input='immutable',prior_geometry_input=False,standard_compliance='not_assessed')
|
||||
|
||||
|
||||
def source_correspondence(q,target):
|
||||
return q.intersection(target).area/max(min(q.area,target.area),1e-9)
|
||||
|
||||
|
||||
def registration_passes(records):
|
||||
if records[0]['coverage']!=1. or records[0]['valid']<REGISTRATION_POLICY['min_valid']:return False
|
||||
for rank,m in enumerate(records):
|
||||
if rank and m['coverage']<.95:continue
|
||||
if m['valid']/max(m['coverage'],1e-9)<REGISTRATION_POLICY['min_valid']:return False
|
||||
if m['iou']<REGISTRATION_POLICY['min_iou']:return False
|
||||
if m['boundary_mean_m']>REGISTRATION_POLICY['max_boundary_mean_m'] or m['boundary_p90_m']>REGISTRATION_POLICY['max_boundary_p90_m']:return False
|
||||
return True
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Original-pixel area overlap for search and independent XY admission.
|
||||
|
||||
A pixel represents a cell, not a point. Exact cell intersections avoid the
|
||||
pose-dependent step function of classifying pixel centres inside a polygon.
|
||||
The .65 IoU gate is retained. Boundary and diagnostic corner metrics are kept.
|
||||
"""
|
||||
import numpy as np
|
||||
from pixel_geometry import vector
|
||||
from standard_arrow_evidence import metrics as legacy_metrics
|
||||
|
||||
|
||||
def fields(grid,view):
|
||||
h,w=grid['size'];cell=grid['cell'];lo=grid['lo']
|
||||
patch=dict(width_px=w,height_px=h,world_corners=np.array([lo,lo+[w*cell,0],lo+[w*cell,h*cell],lo+[0,h*cell]]))
|
||||
known=view['allowed']&view['observed']
|
||||
return dict(known=vector(known,patch),paint=vector(view['target']&known,patch))
|
||||
|
||||
|
||||
def area_iou(q,field):
|
||||
measured=q.intersection(field['known']);paint=field['paint']
|
||||
intersection=measured.intersection(paint).area
|
||||
return intersection/max(measured.area+paint.area-intersection,1e-12)
|
||||
|
||||
|
||||
def metrics(q,grid,view):
|
||||
result=legacy_metrics(q,grid,view)
|
||||
result['iou']=area_iou(q,fields(grid,view))
|
||||
return result
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Deterministic bounded pose-domain audit; image-derived endpoints only."""
|
||||
from pathlib import Path
|
||||
import json,time,collections
|
||||
import cv2
|
||||
import numpy as np
|
||||
import shapely
|
||||
from shapely.geometry import shape
|
||||
from scipy.stats import qmc
|
||||
from ground_observations import GroundObservations
|
||||
from admission_contract import AdmissionContract
|
||||
from candidate_registry import verify
|
||||
from standard_arrow_templates import preset,PROFILES,polygon
|
||||
from arrow_admission import POLICY
|
||||
from registration import POLICY as GEOMETRY
|
||||
|
||||
def run(focus_groups):
|
||||
root=Path('/result');out=Path('/out');registry=json.loads((root/'candidates.json').read_text());verify('/symbolplan',registry)
|
||||
trace=json.loads((root/'diagnostics.json').read_text());obs=GroundObservations();reports=[]
|
||||
for diag in trace:
|
||||
if diag['group'] not in focus_groups:continue
|
||||
rows=[r for r in registry['candidates'] if r['group']==diag['group']];extent=shape(rows[0]['extent'])
|
||||
grid=obs.grid(extent);contract=AdmissionContract(rows,extent,grid,obs.grid(extent,cell=.04))
|
||||
for c in sorted(diag['direct_options'],key=lambda v:-v['initial_score']):
|
||||
if c['initial_score']<.65:continue
|
||||
begin=time.monotonic();kind,profile=c['kind'],c['profile'];length=PROFILES[profile]['L'];unit=np.asarray(preset(kind,profile).exterior.coords)
|
||||
seeds=[c['initial_pose']]+[s['pose'] for s in c.get('start_diagnostics',[])]
|
||||
endpoints=np.array([p[:2]+[p[0]+length*p[3]*np.cos(p[2]),p[1]+length*p[3]*np.sin(p[2])] for p in seeds])
|
||||
padding=GEOMETRY['max_endpoint_error_m']+.04;low=endpoints.min(0)-padding;high=endpoints.max(0)+padding
|
||||
counts=collections.Counter();failures=collections.Counter();best=None;accepted=None;best_shape=None;best_surface=None
|
||||
domain=qmc.Sobol(4,scramble=False).random_base2(18)*(high-low)+low
|
||||
for values in np.array_split(domain,32):
|
||||
axis=values[:,2:]-values[:,:2];factor=np.linalg.norm(axis,axis=1)/length;angle=np.arctan2(axis[:,1],axis[:,0]);keep=(factor>=.75)&(factor<=1.25)
|
||||
poses=np.c_[values[:,:2],angle,factor][keep];counts['sampled']+=len(values)
|
||||
cos=np.cos(poses[:,2]);sin=np.sin(poses[:,2]);rotation=np.stack([cos,sin,-sin,cos],-1).reshape(-1,2,2)
|
||||
xy=(unit[None]@rotation)*poses[:,3,None,None]+poses[:,None,:2];polys=shapely.polygons(xy)
|
||||
witness=np.zeros(len(polys),bool)
|
||||
for src in contract.pool.sources:
|
||||
if src['row']['semantic_score']<POLICY['arrow_semantic_score']:continue
|
||||
overlap=shapely.area(shapely.intersection(polys,src['target']))/np.maximum(shapely.area(shapely.union(polys,src['target'])),1e-9)
|
||||
containment=shapely.area(shapely.intersection(polys,src['region']))/np.maximum(shapely.area(polys),1e-9)
|
||||
witness |= (overlap>=POLICY['arrow_fit_score'])&(containment>=POLICY['min_semantic_fraction'])
|
||||
counts['bound_witness_pass']+=int(witness.sum());poses=poses[witness];xy=xy[witness];polys=polys[witness]
|
||||
if not len(poses):continue
|
||||
uv=((xy[:,:-1]-grid['lo'])/grid['cell']).astype('float32');field=contract.registration.fields[0]['corners']
|
||||
ds=cv2.remap(field,uv[:,:,0],uv[:,:,1],cv2.INTER_LINEAR,borderMode=cv2.BORDER_CONSTANT,borderValue=1e6)
|
||||
keep=ds.max(1)<=GEOMETRY['max_endpoint_error_m'];counts['primary_corners_pass']+=int(keep.sum())
|
||||
for p,q in zip(poses[keep],polys[keep]):
|
||||
decision=contract.measure(q,kind,profile,p);counts['full_contract_calls']+=1
|
||||
fails=decision['admission']['failures'];failures.update(f['check'] for f in fails)
|
||||
costs=np.maximum(-np.asarray(decision['constraint_values']),0)
|
||||
record=dict(pose=p.tolist(),decision=decision)
|
||||
quality=(int((costs>0).sum()),float(costs.max()),-decision['witness']['target_iou'])
|
||||
if best is None or quality<best[0]:best=(quality,record)
|
||||
if decision['accepted']:accepted=record;break
|
||||
if accepted:break
|
||||
if time.monotonic()-begin>300:break
|
||||
if best:
|
||||
p=best[1]['pose'];best[1]['decision']=contract.measure(polygon(kind,profile,p),kind,profile,p,independent=True)
|
||||
report=dict(group=diag['group'],kind=kind,profile=profile,counts=dict(counts),failure_counts=dict(failures),
|
||||
accepted=bool(accepted),best=best[1] if best else None,endpoint_bounds=[low.tolist(),high.tolist()],
|
||||
reference_input=False,sampling_is_not_infeasibility_proof=True,seconds=time.monotonic()-begin)
|
||||
reports.append(report);print('POSE_DOMAIN',json.dumps({k:v for k,v in report.items() if k!='best'}),flush=True)
|
||||
(out/'pose-domain.json').write_text(json.dumps(dict(records=reports,evaluation_only=True)))
|
||||
if accepted:break
|
||||
(out/'pose-domain.json').write_text(json.dumps(dict(records=reports,evaluation_only=True,prior_map_input=False)))
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Plan one uniform survey over observed ground, with an explicit coverage ledger."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import time
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from fit_scene import project, world
|
||||
from ground_observations import GroundObservations, POLICY, VERSION, sha
|
||||
|
||||
|
||||
def prepare(out):
|
||||
started = time.monotonic()
|
||||
out = Path(out); out.mkdir(parents=True, exist_ok=True)
|
||||
folder = out/'symbol-patches'; folder.mkdir(exist_ok=True)
|
||||
observations = GroundObservations()
|
||||
inventory = observations.inventory()
|
||||
(out/'observations.json').write_text(json.dumps(inventory, indent=2))
|
||||
bounds = np.asarray([t['bounds_xy'] for t in observations.tiles])
|
||||
low, high = bounds[:, 0].min(0), bounds[:, 1].max(0)
|
||||
step, width = POLICY['stride_m'], POLICY['window_m']
|
||||
origin = np.floor(low/step)*step
|
||||
patches, ledger, scheduled = [], [], []
|
||||
offset = np.arange(-step/2+.25, step/2, .5)
|
||||
ox, oy = np.meshgrid(offset, offset)
|
||||
samples = np.c_[ox.ravel(), oy.ravel()]
|
||||
for ix in range(int(np.ceil((high[0]-origin[0])/step))):
|
||||
for iy in range(int(np.ceil((high[1]-origin[1])/step))):
|
||||
center = origin+(np.array([ix, iy])+.5)*step
|
||||
pid = f'ground-{ix:04d}-{iy:04d}'
|
||||
record = dict(id=pid, center=center.tolist(), reason='no-covering-observation')
|
||||
selected = None
|
||||
for k in np.argsort(np.linalg.norm(observations.centers-center, axis=1), kind='stable'):
|
||||
# A 60 m image cannot cover a 16 m window farther than 43 m.
|
||||
if np.linalg.norm(observations.centers[k]-center) > 43:
|
||||
continue
|
||||
name = observations.tiles[k]['id']; g = observations.camera(name)
|
||||
corners = center + np.array([[-1,-1],[1,-1],[1,1],[-1,1]])*width/2
|
||||
uv = project(corners, g)
|
||||
if uv.min() < 10 or uv.max() >= 1190:
|
||||
continue
|
||||
fraction = float(observations.surface(name, center+samples).mean())
|
||||
record.update(reason='insufficient-observed-ground', observed_core_fraction=fraction)
|
||||
if fraction < POLICY['core_fraction']:
|
||||
continue
|
||||
selected = name, g, uv, fraction
|
||||
break
|
||||
if selected is None:
|
||||
ledger.append(record); continue
|
||||
name, g, uv, fraction = selected
|
||||
scheduled.append((pid,name,g,uv,fraction))
|
||||
ledger.append(dict(record, reason='scheduled', observed_core_fraction=fraction, source_tile=name))
|
||||
# The same grid order determines identity. Only disk access order changes.
|
||||
materialized={}
|
||||
for pid,name,g,uv,fraction in sorted(scheduled,key=lambda row:row[1]):
|
||||
raw=observations.rgb(name);size=raw.shape[0]
|
||||
if raw.shape[1]!=size:raise ValueError('Expected square orthographic render')
|
||||
native=(uv+.5)*size/1200-.5
|
||||
x0,y0=np.floor(native.min(0)).astype(int);x1,y1=np.ceil(native.max(0)).astype(int)
|
||||
crop=raw[y0:y1,x0:x1];path=folder/(pid+'.png');Image.fromarray(crop).save(path)
|
||||
corners=np.array([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],float);xy=world((corners+.5)*1200/size-.5,g)
|
||||
materialized[pid]=dict(id=pid,source_tile=name,box_native=[int(x0),int(y0),int(x1),int(y1)],
|
||||
native_size=size,world_corners=xy.tolist(),width_px=crop.shape[1],height_px=crop.shape[0],mpp=60/size,sha256=sha(path))
|
||||
if len(materialized)%50==0:print('GROUND_WINDOWS',len(materialized),flush=True)
|
||||
patches=[materialized[row[0]] for row in scheduled]
|
||||
manifest = dict(version=VERSION, patches=patches, policy=POLICY, manual_rois=[],
|
||||
observation_snapshot=inventory['snapshot'], selection='observed-ground-uniform-grid',
|
||||
perspective_mask_input=False, seconds=time.monotonic()-started)
|
||||
(out/'symbol-patches.json').write_text(json.dumps(manifest, indent=2))
|
||||
(out/'coverage-ledger.json').write_text(json.dumps(dict(cells=ledger, policy=POLICY,
|
||||
inferred_coverage=False), indent=2))
|
||||
print('PREPARED', len(patches), 'CELLS', len(ledger), flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
prepare('/out')
|
||||
@@ -0,0 +1,32 @@
|
||||
"""One-to-one evaluation against reviewed object identities, never inference."""
|
||||
import numpy as np
|
||||
import shapely
|
||||
from shapely.geometry import shape
|
||||
from scipy.optimize import linear_sum_assignment
|
||||
|
||||
|
||||
def compare(reference, result, minimum_iou=.5):
|
||||
previous=reference['features'];current=result['features']
|
||||
matrix=np.zeros((len(previous),len(current)))
|
||||
for i,a in enumerate(previous):
|
||||
p=shapely.force_2d(shape(a['geometry']))
|
||||
for j,b in enumerate(current):
|
||||
if a['properties']['subtype']!=b['properties']['subtype']:continue
|
||||
q=shape(b['geometry']);matrix[i,j]=p.intersection(q).area/max(p.union(q).area,1e-9)
|
||||
eligible=matrix>=minimum_iou
|
||||
weights=eligible.astype(float)+matrix*eligible/(max(matrix.shape,default=0)+1)
|
||||
rows,columns=linear_sum_assignment(-weights)
|
||||
pairs=[];matched_before=set();matched_after=set()
|
||||
for i,j in zip(rows,columns):
|
||||
if matrix[i,j]<minimum_iou:continue
|
||||
matched_before.add(int(i));matched_after.add(int(j))
|
||||
pairs.append(dict(reference_id=previous[i]['id'],result_id=current[j]['id'],
|
||||
kind=current[j]['properties']['subtype'],iou=float(matrix[i,j])))
|
||||
missing=[f['id'] for i,f in enumerate(previous) if i not in matched_before]
|
||||
return dict(passed=not missing,reference_objects=len(previous),result_objects=len(current),
|
||||
matched=len(pairs),missing=missing,
|
||||
unmatched_results=[f['id'] for j,f in enumerate(current) if j not in matched_after],
|
||||
pairs=pairs,matching='one-to-one, same class',minimum_identity_iou=minimum_iou,
|
||||
reference_contours_are_metric_ground_truth=False,
|
||||
metric_quality='separate original-pixel and fixed-preset verification',
|
||||
independent_generalization_measured=False)
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Non-destructive map reconciliation, strictly after independent verification.
|
||||
|
||||
This is map-state assembly, never an inference input. A missing proposal is
|
||||
not evidence that a confirmed object disappeared. Unmatched old features are
|
||||
preserved byte-for-byte as JSON values; they do not count as freshly recovered.
|
||||
"""
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import shapely
|
||||
from shapely.geometry import shape
|
||||
from preservation import compare
|
||||
from component_conflicts import symbol_replacements, FRAGMENT_POLICY
|
||||
|
||||
|
||||
def reconcile(base_bytes,result_bytes,verification):
|
||||
base=json.loads(base_bytes);proposed=json.loads(result_bytes)
|
||||
digest=hashlib.sha256(result_bytes).hexdigest()
|
||||
features=proposed['features'];ids=[f['id'] for f in features]
|
||||
if len(set(ids))!=len(ids):raise ValueError('Duplicate proposal identity')
|
||||
if not (verification.get('passed') is True and verification.get('original_pixels_remeasured') is True
|
||||
and verification.get('immutable_presets') is True and verification.get('source_registry_verified') is True
|
||||
and verification.get('source_result_sha256')==digest and verification.get('accepted')==len(features)
|
||||
and sorted(v['id'] for v in verification.get('checks',[]))==sorted(ids)):
|
||||
raise ValueError('Independent verification does not bind these proposal bytes')
|
||||
prior=base['features'];old_ids=[f['id'] for f in prior]
|
||||
if len(set(old_ids))!=len(old_ids):raise ValueError('Duplicate base identity')
|
||||
arrows=[f for f in prior if 'arrow' in f['properties'].get('subtype','')]
|
||||
matches=compare(dict(features=arrows),proposed)
|
||||
old={f['id']:f for f in arrows};new={f['id']:f for f in features}
|
||||
output=copy.deepcopy(base);positions={f['id']:i for i,f in enumerate(output['features'])}
|
||||
replaced=[];added=[];unresolved=[];used=set();upgraded=[];absorbed=set()
|
||||
for pair in matches['pairs']:
|
||||
before=old[pair['reference_id']];after=new[pair['result_id']]
|
||||
# A proposal must not replace manual/authoritative map state. Such a
|
||||
# conflict needs its own review, independently of numeric fit quality.
|
||||
if before['properties'].get('authority')!='observation-only':
|
||||
unresolved.append(dict(proposal=after['id'],reason='protected-existing-authority'));used.add(after['id']);continue
|
||||
merged=copy.deepcopy(after);merged['id']=before['id']
|
||||
for key in ['authority','route_permission','review_status']:
|
||||
if key in before['properties']:merged['properties'][key]=copy.deepcopy(before['properties'][key])
|
||||
output['features'][positions[before['id']]]=merged
|
||||
replaced.append(dict(existing=before['id'],proposal=after['id'],identity_iou=pair['iou']))
|
||||
used.add(after['id'])
|
||||
for feature in features:
|
||||
if feature['id'] in used:continue
|
||||
q=shapely.force_2d(shape(feature['geometry']))
|
||||
current=output['features']
|
||||
fragments=symbol_replacements(q,feature['properties']['subtype'],current)
|
||||
if fragments is None:
|
||||
unresolved.append(dict(proposal=feature['id'],reason='existing-marking-conflict'));continue
|
||||
if any(f['properties'].get('authority')!='observation-only' or
|
||||
f['properties'].get('review_status') not in [None,'unreviewed'] for f in fragments):
|
||||
unresolved.append(dict(proposal=feature['id'],reason='protected-existing-fragment'));continue
|
||||
if fragments:
|
||||
# The existing fragment identity becomes the complete object. All
|
||||
# original records remain in provenance; extra fragments become
|
||||
# explicit aliases, never silently removed independent objects.
|
||||
fragments=sorted(fragments,key=lambda f:f['id'])
|
||||
identity=fragments[0]['id'];merged=copy.deepcopy(feature);merged['id']=identity
|
||||
for key in ['authority','route_permission','review_status']:
|
||||
if key in fragments[0]['properties']:merged['properties'][key]=copy.deepcopy(fragments[0]['properties'][key])
|
||||
merged['properties']['absorbed_fragments']=copy.deepcopy(fragments)
|
||||
fragment_ids={f['id'] for f in fragments}
|
||||
output['features']=[merged if f['id']==identity else f for f in current
|
||||
if f['id']==identity or f['id'] not in fragment_ids]
|
||||
absorbed.update(fragment_ids)
|
||||
upgraded.append(dict(existing=identity,proposal=feature['id'],fragment_ids=sorted(fragment_ids),
|
||||
retired_aliases=sorted(fragment_ids-{identity}),policy=FRAGMENT_POLICY,
|
||||
previous_records=copy.deepcopy(fragments)))
|
||||
positions={f['id']:i for i,f in enumerate(output['features'])}
|
||||
continue
|
||||
if feature['id'] in positions:raise ValueError('Proposal collides with unrelated existing ID')
|
||||
output['features'].append(copy.deepcopy(feature));added.append(feature['id'])
|
||||
replaced_ids={r['existing'] for r in replaced}
|
||||
retained=[f['id'] for f in arrows if f['id'] not in replaced_ids]
|
||||
actual={f['id']:f for f in output['features']}
|
||||
for f in prior:
|
||||
if f['id'] not in replaced_ids|absorbed and actual.get(f['id'])!=f:raise AssertionError('Untouched object changed')
|
||||
if not set(old_ids)-absorbed<=actual.keys():raise AssertionError('Existing object lost')
|
||||
ledger=dict(base_sha256=hashlib.sha256(base_bytes).hexdigest(),proposal_sha256=digest,
|
||||
input_objects=len(prior),output_objects=len(actual),freshly_verified=len(features),
|
||||
replaced=replaced,added=added,fragment_upgrades=upgraded,retained_previous_arrow_geometry=retained,conflicts=unresolved,
|
||||
deleted=[],other_objects_unchanged=True,prior_map_seen_by_inference=False,
|
||||
fresh_recovery_must_be_measured_separately=True,published=False)
|
||||
return output,ledger
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Standalone arrow reconstruction from observations, without a prior map.
|
||||
|
||||
Qualified output is a separate observation collection. No publication or
|
||||
transaction against an operator map is performed by this entrypoint.
|
||||
"""
|
||||
from pathlib import Path
|
||||
import collections
|
||||
import json
|
||||
import time
|
||||
import cv2
|
||||
import numpy as np
|
||||
import shapely
|
||||
from shapely.geometry import shape, mapping
|
||||
from ground_observations import GroundObservations, sha
|
||||
from candidate_registry import discover, verify
|
||||
from observed_fixed import fit_grid, VERSION
|
||||
from standard_arrow_templates import dimensions
|
||||
from standard_arrow_evidence import metrics
|
||||
from plan_marking_policy import registration_passes as passes, CONTRACT, source_correspondence
|
||||
from arrow_evidence import directional_score
|
||||
from observation_checks import branch_evidence, accept_symbol, assess
|
||||
from recall_extent import semantic_recall
|
||||
from layer_common import feature
|
||||
from object_evidence import evidence
|
||||
from admission_contract import AdmissionContract
|
||||
|
||||
|
||||
def run(root='/symbolplan', out='/out', registry_path=None, focus_groups=None):
|
||||
started = time.monotonic(); cv2.setNumThreads(2)
|
||||
out = Path(out); out.mkdir(parents=True, exist_ok=True)
|
||||
observations = GroundObservations()
|
||||
inventory = observations.inventory()
|
||||
inventory_seconds=time.monotonic()-started
|
||||
registry_started=time.monotonic()
|
||||
(out/'observations.json').write_text(json.dumps(inventory, indent=2))
|
||||
if registry_path is None:
|
||||
registry = discover(root, out, observations=observations)
|
||||
else:
|
||||
registry = json.loads(Path(registry_path).read_text())
|
||||
verify(root, registry)
|
||||
(out/'candidates.json').write_bytes(Path(registry_path).read_bytes())
|
||||
registry_seconds=time.monotonic()-registry_started
|
||||
source_manifest = json.loads((Path(root)/'symbol-patches.json').read_text())
|
||||
if source_manifest.get('observation_snapshot') != inventory['snapshot']:
|
||||
raise ValueError('Candidate observations do not belong to this ground survey')
|
||||
# Solve one immutable entity at a time. Source order is not search state.
|
||||
groups={}
|
||||
for row in registry['candidates']:groups.setdefault(row['group'],[]).append(row)
|
||||
features,diagnostics,seen=[],[],[]
|
||||
for group_id,group in sorted(groups.items()):
|
||||
if focus_groups is not None and group_id not in focus_groups:continue
|
||||
begin=time.monotonic();group=sorted(group,key=lambda r:r['id'])
|
||||
extent=shape(group[0]['extent'])
|
||||
if any(shape(r['extent']).wkb!=extent.wkb for r in group):raise ValueError('Entity anchor mismatch')
|
||||
diag=dict(candidate=group[0]['id'],group=group_id,patch=group[0]['patch'],options=[])
|
||||
diagnostics.append(diag)
|
||||
if any(extent.intersection(q).area/max(extent.area,1e-9)>.5 for q in seen):
|
||||
diag['reject']='same-observed-object';continue
|
||||
clock=time.monotonic();grid=observations.grid(extent);whole=observations.grid(extent,cell=.04)
|
||||
contract=AdmissionContract(group,extent,grid,whole)
|
||||
diag['grid_seconds']=time.monotonic()-clock;clock=time.monotonic()
|
||||
options=fit_grid(grid,contract.pool.targets,contract.constraints)
|
||||
diag['fit_seconds']=time.monotonic()-clock
|
||||
diag['direct_options']=[{k:v for k,v in option.items() if k!='geometry'} for option in options]
|
||||
if not options:diag['reject']='no-fixed-template-proposal'
|
||||
for candidate in options:
|
||||
kind=candidate['kind'];q=candidate['geometry']
|
||||
decision=contract.measure(q,kind,candidate['profile'],candidate['pose'],independent=True)
|
||||
option=dict(kind=kind,profile=candidate['profile'],pose=candidate['pose'],**decision)
|
||||
diag['options'].append(option)
|
||||
if not decision['accepted']:
|
||||
option['reject']='original-pixel-metrics' if not passes(decision['metrics']) else 'whole-object-evidence'
|
||||
continue
|
||||
witness=decision['witness'];row=next(r for r in group if r['id']==witness['candidate_id'])
|
||||
selected=feature(q,'road_marking',subtype=kind,method=VERSION,candidate_id=row['id'],
|
||||
semantic_score=witness['semantic_score'],template_fit_score=witness['target_iou'],
|
||||
standard_compliance='not_assessed',admission_contract=CONTRACT,geometry_domain='plan-xy',
|
||||
depth_quality=observations.depth_quality(whole,q),
|
||||
preset=dict(kind=kind,profile=candidate['profile'],pose=candidate['pose'],transform='similarity'),
|
||||
observation_snapshot=inventory['snapshot'],source_tiles=sorted(set(n for v in grid['views'] for n in v['names'])))
|
||||
features.append(selected);seen.append(q);diag.update(candidate=row['id'],patch=row['patch'],accepted=selected['id'])
|
||||
break
|
||||
if 'accepted' not in diag:
|
||||
diag.setdefault('reject','fixed-preset-evidence')
|
||||
if diag['options']:
|
||||
from standard_arrow_templates import polygon
|
||||
from registration import POLICY as registration_policy
|
||||
from arrow_admission import POLICY as admission_policy
|
||||
# Failed feasibility search can trade correct appearance for
|
||||
# lower vetoes in a wrong class. Explain the strongest fresh
|
||||
# image hypothesis, including its preserved initial seeds.
|
||||
trials=[]
|
||||
for option in options:
|
||||
poses=[option['pose'],option['initial_pose']]+[r['pose'] for r in option.get('start_diagnostics',[])]
|
||||
for pose in poses:
|
||||
q=polygon(option['kind'],option['profile'],pose)
|
||||
witness=contract.pool.measure(q,option['kind']);m=contract.registration.measure(q)[0]
|
||||
strength=min(witness['target_iou']/admission_policy['arrow_fit_score'],m['iou']/registration_policy['min_iou'])
|
||||
trials.append((strength,option['kind'],option['profile'],pose,q))
|
||||
_,kind,profile,pose,q=max(trials,key=lambda t:t[0])
|
||||
diag['surface_diagnosis']=observations.explain_object_surface(whole,q,pose)
|
||||
diag['surface_diagnosis_pose']=pose
|
||||
diag['surface_diagnosis_kind']=kind
|
||||
diag['surface_diagnosis_selection']='strongest joint appearance in fresh solver seeds/results; unqualified diagnostic only'
|
||||
diag['surface_diagnosis_decision']=contract.measure(q,kind,profile,pose,independent=True)
|
||||
diag['seconds']=time.monotonic()-begin
|
||||
print('ENTITY',group_id,'/',len(groups),diag.get('reject','accepted'),round(diag['seconds'],2),flush=True)
|
||||
verify(root, registry)
|
||||
(out/'arrow-observations.json').write_text(json.dumps(dict(type='FeatureCollection', features=features), allow_nan=False))
|
||||
(out/'diagnostics.json').write_text(json.dumps(diagnostics, indent=2, allow_nan=False))
|
||||
report = dict(version=VERSION, candidates=len(registry['candidates']), evaluated_groups=len(diagnostics), accepted=len(features),
|
||||
rejections=dict(collections.Counter(d.get('reject','accepted') for d in diagnostics)),
|
||||
seconds=time.monotonic()-started, candidate_registry_sha256=sha(out/'candidates.json'),
|
||||
observations_sha256=sha(out/'observations.json'), source_validation='passed',
|
||||
perspective_input=False, prior_map_input=False, published=False, evaluation_subset=focus_groups, candidate_registry_reused=registry_path is not None,
|
||||
recall_measured=False, cold_start_measured=False,
|
||||
initial_semantic_observations=registry['raw_proposals'],object_groups=registry['groups'],
|
||||
distinct_fit_problems=sum('fit_seconds' in d for d in diagnostics),
|
||||
pose_search_seconds=sum(d.get('fit_seconds',0) for d in diagnostics),
|
||||
inventory_seconds=inventory_seconds,registry_seconds=registry_seconds,
|
||||
observation_costs=observations.statistics(),
|
||||
detector_reinvocations_during_reconstruction=0,render_reinvocations_during_reconstruction=0)
|
||||
(out/'report.json').write_text(json.dumps(report, indent=2)); print('REPORT', json.dumps(report), flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run()
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Cached exact original-pixel registration constraints for the pose solver."""
|
||||
import cv2
|
||||
import numpy as np
|
||||
import shapely
|
||||
from registration import CELL,POLICY
|
||||
import plan_registration
|
||||
|
||||
|
||||
class RegistrationEvaluator:
|
||||
def __init__(self,grid):
|
||||
if grid['cell']!=CELL:raise ValueError('Registration pixel contract mismatch')
|
||||
self.grid=grid;self.fields=[]
|
||||
self.kernel=np.ones((3,3),'uint8')
|
||||
for view in grid['views']:
|
||||
valid=view['allowed']&view['observed'];paint=view['target']
|
||||
boundary=(paint&~(cv2.erode(paint.astype('uint8'),self.kernel)>0))&valid
|
||||
corners=view.get('paint',view['target'])&valid
|
||||
corners &= ~(cv2.erode(corners.astype('uint8'),self.kernel)>0)
|
||||
def distances(edge):
|
||||
return cv2.distanceTransform((~edge).astype('uint8'),cv2.DIST_L2,cv2.DIST_MASK_PRECISE)*CELL if edge.any() else None
|
||||
self.fields.append(dict(view=view,valid=valid,boundary=distances(boundary),corners=distances(corners),area=plan_registration.fields(grid,view)))
|
||||
|
||||
def measure(self,q):
|
||||
grid=self.grid;points=grid['points']
|
||||
mask=shapely.contains_xy(q,points[:,0],points[:,1]).reshape(grid['size'])
|
||||
edge=mask&~(cv2.erode(mask.astype('uint8'),self.kernel)>0)
|
||||
denom=max(int(mask.sum()),1);uv=((shapely.get_coordinates(q)[:-1]-grid['lo'])/CELL).astype('float32')
|
||||
result=[]
|
||||
for field in self.fields:
|
||||
view=field['view'];valid=field['valid'];paint=view['target'];boundary=field['boundary'];corners=field['corners']
|
||||
selected=edge&valid
|
||||
errors=boundary[selected] if boundary is not None and selected.any() else None
|
||||
ds=cv2.remap(corners,uv[:,0,None],uv[:,1,None],cv2.INTER_LINEAR,borderMode=cv2.BORDER_CONSTANT,borderValue=1e6).ravel() if corners is not None else np.array([1e6])
|
||||
result.append(dict(coverage=float((mask&view['observed']).sum()/denom),valid=float((mask&valid).sum()/denom),
|
||||
iou=plan_registration.area_iou(q,field['area']),
|
||||
boundary_mean_m=float(errors.mean()) if errors is not None else 1e6,
|
||||
boundary_p90_m=float(np.quantile(errors,.90)) if errors is not None else 1e6,
|
||||
landmark_max_error_m=float(ds.max())))
|
||||
return result
|
||||
|
||||
def constraints(self,q):
|
||||
return self.constraints_from(self.measure(q))
|
||||
|
||||
@staticmethod
|
||||
def checks_from(records):
|
||||
# Individual ideal corners are retained as diagnostics. Full boundary
|
||||
# and object topology gates decide an observed XY marking.
|
||||
checks=[]
|
||||
for rank,m in enumerate(records):
|
||||
active=not rank or m['coverage']>=.95
|
||||
values=[('registration_coverage',m['coverage'],1.,True,not rank),
|
||||
('registration_surface_validity',m['valid']/max(m['coverage'],1e-9),POLICY['min_valid'],True,active),
|
||||
('registration_iou',m['iou'],POLICY['min_iou'],True,active),
|
||||
('registration_boundary_mean',m['boundary_mean_m'],POLICY['max_boundary_mean_m'],False,active),
|
||||
('registration_boundary_p90',m['boundary_p90_m'],POLICY['max_boundary_p90_m'],False,active),
|
||||
('registration_corner_distance',m['landmark_max_error_m'],POLICY['max_endpoint_error_m']+(.04 if rank else 0.),False,False)]
|
||||
for name,value,limit,minimum,enabled in values:
|
||||
margin=(value-limit if minimum else limit-value) if enabled else 1.
|
||||
checks.append(dict(check=name,rank=rank,value=value,**{'minimum' if minimum else 'maximum':limit},active=enabled,margin=margin))
|
||||
return checks
|
||||
|
||||
@staticmethod
|
||||
def constraints_from(records):
|
||||
return [r['margin'] for r in RegistrationEvaluator.checks_from(records)]
|
||||
|
||||
def margin(self,q):return min(self.constraints(q))
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Reproduce the full systematic top survey, retaining native depth and opacity.
|
||||
|
||||
Every surveyed tile is processed. No detector result, rejected object or ROI
|
||||
selects a render. Existing RGB and 1200px geometry are immutable comparison
|
||||
inputs; native arrays remain separate evidence.
|
||||
"""
|
||||
from pathlib import Path
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from spatial_index import SpatialIndex
|
||||
import gc, json, math, time, shutil
|
||||
import cv2
|
||||
import numpy as np
|
||||
import torch
|
||||
from plyfile import PlyData
|
||||
from gsplat import rasterization
|
||||
from PIL import Image
|
||||
from mapping import camera,digest
|
||||
from coordinate_cache import transformed
|
||||
from ortho_terrain import sample
|
||||
from orthographic_colour import colours
|
||||
|
||||
|
||||
def run(parallel_rays=False):
|
||||
root=Path('/ortho');out=Path('/out');started=time.monotonic()
|
||||
config=json.loads((root/'config.json').read_text());method=config['method']
|
||||
native_out=out/'native-geometry' if parallel_rays else out
|
||||
native_out.mkdir(exist_ok=True)
|
||||
if parallel_rays:
|
||||
(out/'survey').mkdir();(out/'evidence').mkdir()
|
||||
for name in ['config.json','terrain-reference.npz','survey/request.json','survey/tile-index.json']:
|
||||
shutil.copyfile(root/name,out/name)
|
||||
config['orthographic_colour']='parallel optical-axis SH; translation invariant'
|
||||
(out/'config.json').write_text(json.dumps(config,indent=2))
|
||||
request=json.loads((root/'survey/request.json').read_text())
|
||||
source=Path('/input')/request['source']['ply']
|
||||
assert digest(source)==request['source']['sha256']
|
||||
with np.load(root/'terrain-reference.npz') as z:field=dict(z)
|
||||
transform=np.asarray(request['source']['source_to_world'])
|
||||
data=PlyData.read(source,mmap='r')['vertex'].data
|
||||
world=transformed(data,transform,str(source),str(out/'coordinate-cache-proof.json'))
|
||||
relative=np.empty(len(data),np.float32)
|
||||
for begin in range(0,len(data),250000):
|
||||
xyz=world[begin:begin+250000];relative[begin:begin+len(xyz)]=xyz[:,2]-sample(field,xyz[:,:2])
|
||||
tiles=[t for t in json.loads((root/'survey/tile-index.json').read_text())['tiles'] if t['status']=='surveyed']
|
||||
records=[];native_n=method['render_pixels']
|
||||
t=time.monotonic();spatial=SpatialIndex(world,relative,method['lower_height_m'],method['context_height_m'])
|
||||
setup=dict(spatial_index_seconds=time.monotonic()-t,source_gaussians=len(data))
|
||||
writer=ThreadPoolExecutor(max_workers=2,thread_name_prefix='observation-writer');pending=[]
|
||||
def finish_one():
|
||||
record=pending.pop(0).result();records.append(record)
|
||||
(native_out/'native-geometry.json').write_text(json.dumps(dict(version='native-systematic-geometry-v1',complete=False,records=records),indent=2))
|
||||
print('NATIVE',len(records),'/',len(tiles)*2,record['tile'],record['mode'],round(record['seconds'],2),flush=True)
|
||||
def persist(name,mode,a,v,view,k,begin,timings):
|
||||
t=time.monotonic()
|
||||
v[:,:,:3]+=1-a[:,:,None];image=np.uint8(np.clip(v[:,:,:3],0,1)*255)
|
||||
original_image=root/'evidence'/(name+'.'+mode+'.png')
|
||||
with Image.open(original_image) as im:original=np.asarray(im.convert('RGB'))
|
||||
rgb_max=int(np.abs(image.astype('int16')-original.astype('int16')).max())
|
||||
old_path=(root/'survey'/name/'top.geometry.npz' if mode=='context' else root/'evidence'/(name+'.ground-dc.geometry.npz'))
|
||||
with np.load(old_path) as z:
|
||||
depth_error=float(np.max(np.abs(cv2.resize(v[:,:,3],(1200,1200),interpolation=cv2.INTER_AREA)-z['depth'])))
|
||||
alpha_error=float(np.max(np.abs(cv2.resize(a,(1200,1200),interpolation=cv2.INTER_AREA)-z['alpha'])))
|
||||
assert (parallel_rays or rgb_max<=1) and depth_error<=.001 and alpha_error<=.0001,(name,mode,rgb_max,depth_error,alpha_error)
|
||||
timings['comparison_seconds']=time.monotonic()-t;t=time.monotonic()
|
||||
if parallel_rays:
|
||||
folder=out/'survey'/name;folder.mkdir(exist_ok=True)
|
||||
shutil.copyfile(root/'survey'/name/'job.json',folder/'job.json')
|
||||
Image.fromarray(image).save(out/'evidence'/(name+'.'+mode+'.png'))
|
||||
small=cv2.resize(image,(1200,1200),interpolation=cv2.INTER_AREA)
|
||||
ak=k.copy();ak[:2,:]*=1200/native_n
|
||||
compatibility=dict(depth=cv2.resize(v[:,:,3],(1200,1200),interpolation=cv2.INTER_AREA),
|
||||
alpha=cv2.resize(a,(1200,1200),interpolation=cv2.INTER_AREA),view=view,intrinsics=ak)
|
||||
if mode=='context':
|
||||
Image.fromarray(small).save(folder/'top.png');np.savez_compressed(folder/'top.geometry.npz',**compatibility)
|
||||
else:
|
||||
Image.fromarray(small).save(out/'evidence'/(name+'.ground-dc.png'))
|
||||
np.savez_compressed(out/'evidence'/(name+'.ground-dc.geometry.npz'),**compatibility)
|
||||
file=native_out/(name+'.'+mode+'.npz')
|
||||
np.savez_compressed(file,depth=v[:,:,3],alpha=a,view=view,intrinsics=k,compatibility_resolution=1200)
|
||||
timings['encoding_write_seconds']=time.monotonic()-t;t=time.monotonic()
|
||||
checksum=digest(file);rgb_checksum=digest(out/'evidence'/(name+'.'+mode+'.png')) if parallel_rays else digest(original_image)
|
||||
timings['hash_seconds']=time.monotonic()-t
|
||||
return dict(tile=name,mode=mode,file=file.name,sha256=checksum,native_size=native_n,
|
||||
rgb_sha256=rgb_checksum,rgb_max_difference=rgb_max,compatibility_depth_error_m=depth_error,
|
||||
compatibility_alpha_error=alpha_error,seconds=time.monotonic()-begin,timings=timings)
|
||||
|
||||
for tile in tiles:
|
||||
name=tile['id'];job=json.loads((root/'survey'/name/'job.json').read_text())
|
||||
top=next(v for v in job['views'] if v['id']=='top');top['size']=[native_n,native_n]
|
||||
bounds=np.asarray(job['bounds_xy'])
|
||||
selection_started=time.monotonic();indices=spatial.query([bounds[0]-10,bounds[1]+10])
|
||||
selection_seconds=time.monotonic()-selection_started
|
||||
d=data[indices].copy();dz=relative[indices];del indices
|
||||
for mode,upper in [('context',method['context_height_m']),('ground',method['ground_height_m'])]:
|
||||
# At most two native render results exist outside the GPU. Writer
|
||||
# failures stop acquisition; a partial set can never be marked complete.
|
||||
if len(pending)>=2:finish_one()
|
||||
begin=time.monotonic();selected=d[dz<=upper]
|
||||
timings=dict(selection_seconds=selection_seconds,selected_gaussians=len(selected))
|
||||
def tensor(names):return torch.tensor(np.column_stack([selected[n] for n in names]),device='cuda',dtype=torch.float32)
|
||||
means=tensor(['x','y','z']);quats=tensor([f'rot_{i}' for i in range(4)])
|
||||
scales=tensor([f'scale_{i}' for i in range(3)]).exp();opacity=tensor(['opacity']).squeeze(-1).sigmoid()
|
||||
dc=tensor([f'f_dc_{i}' for i in range(3)])[:,None,:]
|
||||
rest=sorted([n for n in d.dtype.names if n.startswith('f_rest_')],key=lambda n:int(n.split('_')[-1]))
|
||||
sh=torch.cat([dc,tensor(rest).reshape(len(selected),3,-1).transpose(1,2)],dim=1) if rest else dc
|
||||
degree=int(math.sqrt(sh.shape[1]))-1;view,k=camera(top)
|
||||
world_to_camera=torch.tensor(view@transform,device='cuda',dtype=torch.float32)
|
||||
rgb_input=colours(sh,world_to_camera,degree) if parallel_rays else sh
|
||||
torch.cuda.synchronize();timings['tensor_seconds']=time.monotonic()-begin;t=time.monotonic()
|
||||
with torch.inference_mode():
|
||||
rendered,alpha,_=rasterization(means,quats,scales,opacity,rgb_input,
|
||||
world_to_camera[None],torch.tensor(k,device='cuda')[None],
|
||||
native_n,native_n,sh_degree=None if parallel_rays else degree,camera_model='ortho',render_mode='RGB+ED',packed=True)
|
||||
torch.cuda.synchronize();timings['raster_seconds']=time.monotonic()-t;t=time.monotonic()
|
||||
a=alpha[0,:,:,0].cpu().numpy();v=rendered[0].cpu().numpy()
|
||||
timings['download_seconds']=time.monotonic()-t
|
||||
pending.append(writer.submit(persist,name,mode,a,v,view,k,begin,timings))
|
||||
del selected,means,quats,scales,opacity,dc,sh,rgb_input,rendered,alpha,a,v
|
||||
del d,dz;gc.collect()
|
||||
while pending:finish_one()
|
||||
writer.shutdown(wait=True)
|
||||
(native_out/'native-geometry.json').write_text(json.dumps(dict(setup=setup,writer_workers=2,writer_queue_limit=2,version='native-systematic-geometry-v1',complete=True,records=records,
|
||||
source_sha256=request['source']['sha256'],terrain_sha256=digest(root/'terrain-reference.npz'),
|
||||
tiles=len(tiles),manual_rois=[],selection='every surveyed systematic tile',seconds=time.monotonic()-started,
|
||||
photometry='parallel-optical-axis-SH' if parallel_rays else 'legacy-camera-centre-SH',
|
||||
legacy_rgb_used_by_downstream=not parallel_rays),indent=2))
|
||||
|
||||
|
||||
if __name__=='__main__':run()
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Exact spatial membership index. Original source order and height cuts retained."""
|
||||
import numpy as np
|
||||
|
||||
class SpatialIndex:
|
||||
def __init__(self, world, relative, lower, upper, cell=20.):
|
||||
self.world=world;self.cell=cell
|
||||
valid=np.flatnonzero((relative>=lower)&(relative<=upper)&np.isfinite(world[:,:2]).all(1))
|
||||
xy=np.floor(world[valid,:2]/cell).astype(np.int64)
|
||||
self.low=xy.min(0) if len(xy) else np.zeros(2,np.int64)
|
||||
self.width=int(np.ptp(xy[:,0])+1) if len(xy) else 1
|
||||
codes=(xy[:,1]-self.low[1])*self.width+xy[:,0]-self.low[0]
|
||||
order=np.argsort(codes,kind='stable');self.indices=valid[order];self.codes=codes[order]
|
||||
self.high=xy.max(0) if len(xy) else self.low-1
|
||||
def query(self, bounds):
|
||||
bounds=np.asarray(bounds);lo=np.maximum(np.floor(bounds[0]/self.cell).astype(np.int64),self.low)
|
||||
hi=np.minimum(np.floor(bounds[1]/self.cell).astype(np.int64),self.high)
|
||||
parts=[]
|
||||
for y in range(lo[1],hi[1]+1):
|
||||
if lo[0]>hi[0]:continue
|
||||
first=(y-self.low[1])*self.width+lo[0]-self.low[0]
|
||||
last=(y-self.low[1])*self.width+hi[0]-self.low[0]
|
||||
a,b=np.searchsorted(self.codes,[first,last],side='left');b=np.searchsorted(self.codes,last,side='right')
|
||||
parts.append(self.indices[a:b])
|
||||
ids=np.sort(np.concatenate(parts)) if parts else np.array([],dtype=np.int64)
|
||||
return ids[((self.world[ids,:2]>=bounds[0])&(self.world[ids,:2]<=bounds[1])).all(1)]
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Read-only decomposition of existing surface gates. No inference mutations."""
|
||||
import cv2
|
||||
import numpy as np
|
||||
import shapely
|
||||
from ground_observations import read,POLICY
|
||||
from fit_scene import project
|
||||
from row_evidence import choose_owners
|
||||
|
||||
|
||||
def surface_audit(obs,grid,q):
|
||||
points=grid['points'];inside=shapely.contains_xy(q,points[:,0],points[:,1]);pts=points[inside]
|
||||
distances=np.linalg.norm(pts[:,None]-obs.centers[None],axis=2)
|
||||
covered=np.zeros(distances.shape,bool)
|
||||
for i,t in enumerate(obs.tiles):
|
||||
uv=project(pts,obs.camera(t['id']));covered[:,i]=(uv.min(1)>=20)&(uv.max(1)<1180)
|
||||
owners=choose_owners(distances,covered);records=[]
|
||||
for rank in range(2):
|
||||
for i in np.unique(owners[:,rank]):
|
||||
if i<0:continue
|
||||
xy=pts[owners[:,rank]==i];name=obs.tiles[i]['id']
|
||||
c=obs.geometry(name);g=obs.geometry(name,True);uv=project(xy,obs.camera(name))
|
||||
if obs.native:uv=(uv+.5)*c['depth'].shape[0]/1200-.5
|
||||
a,b=c['depth'],g['depth'];finite=np.isfinite(a)&np.isfinite(b)&(a>0)&(b>0)
|
||||
safe=np.where(finite,b,0).astype('float32');ratio=b.shape[0]/int(g.get('compatibility_resolution',b.shape[0]))
|
||||
width=2*int(np.ceil((POLICY['local_window_px']-1)/2*ratio))+1;kernel=np.ones((width,width),'uint8')
|
||||
neighborhood=cv2.erode(finite.astype('uint8'),kernel)>0
|
||||
span=cv2.dilate(safe,kernel)-cv2.erode(safe,kernel)
|
||||
scalar=lambda array:read(array.astype('float32'),uv).ravel()
|
||||
span_at=read(span,uv,nearest=True).ravel();neighbor_at=read(neighborhood.astype('uint8'),uv,nearest=True).ravel()>0
|
||||
ca,ga=scalar(c['alpha']),scalar(g['alpha']);gap=np.abs(scalar(a)-scalar(b))
|
||||
rejected=dict(depth_span=span_at>POLICY['local_depth_span_m'],nonfinite_neighbourhood=~neighbor_at,
|
||||
context_opacity=ca<POLICY['alpha_min'],ground_opacity=ga<POLICY['alpha_min'],context_ground_gap=gap>POLICY['depth_agreement_m'])
|
||||
bad=np.logical_or.reduce(list(rejected.values()))
|
||||
records.append(dict(rank=rank,tile=name,pixels=len(xy),invalid=int(bad.sum()),
|
||||
reasons={k:int(v.sum()) for k,v in rejected.items()},span_quantiles=np.quantile(span_at,[0,.5,.9,.97,1]).tolist(),
|
||||
failed_samples=[dict(xy=p.tolist(),span=float(s),context_alpha=float(ac),ground_alpha=float(ag),gap=float(d))
|
||||
for p,s,ac,ag,d in zip(xy[bad],span_at[bad],ca[bad],ga[bad],gap[bad])]))
|
||||
return records
|
||||
@@ -0,0 +1,44 @@
|
||||
"""GPU camera-contract test in the pinned mapper image; no real-scene tuning."""
|
||||
from pathlib import Path
|
||||
import hashlib,inspect,json
|
||||
import torch
|
||||
import gsplat
|
||||
from gsplat import rasterization
|
||||
from orthographic_colour import colours
|
||||
|
||||
|
||||
def run():
|
||||
torch.manual_seed(73)
|
||||
device='cuda';n=6
|
||||
means=torch.tensor([[-1.,-.5,0.],[0.,-.5,0.],[1.,-.5,0.],[-1.,.5,0.],[0.,.5,0.],[1.,.5,0.]],device=device)
|
||||
quats=torch.tensor([[1.,0.,0.,0.]],device=device).repeat(n,1)
|
||||
scales=torch.tensor([[.25,.25,.02]],device=device).repeat(n,1)
|
||||
opacity=torch.full((n,),.9,device=device)
|
||||
sh=torch.randn((n,16,3),device=device)*.3
|
||||
first=torch.diag(torch.tensor([1.,-1.,-1.,1.],device=device));first[2,3]=10.
|
||||
second=first.clone();second[0,3]=-1.25
|
||||
k=torch.tensor([[8.,0.,32.],[0.,8.,32.],[0.,0.,1.]],device=device)
|
||||
def render(view,correct):
|
||||
c=colours(sh,view,3) if correct else sh
|
||||
with torch.inference_mode():
|
||||
image,a,_=rasterization(means,quats,scales,opacity,c,view[None],k[None],64,64,
|
||||
sh_degree=None if correct else 3,camera_model='ortho',render_mode='RGB+ED',packed=True)
|
||||
return image[0],a[0]
|
||||
legacy_a,alpha_a=render(first,False);legacy_b,alpha_b=render(second,False)
|
||||
fixed_a,fa=render(first,True);fixed_b,fb=render(second,True)
|
||||
# Translation by 1.25 m is exactly ten native pixels. The same Gaussian
|
||||
# rays have identical optical direction, alpha, depth and corrected colour.
|
||||
left=(slice(8,56),slice(12,52));right=(slice(8,56),slice(2,42))
|
||||
known=(alpha_a[left][...,0]>.05)&(alpha_b[right][...,0]>.05)
|
||||
def difference(a,b):return float((a[left][known]-b[right][known]).abs().max())
|
||||
report=dict(gsplat_version=gsplat.__version__,installed_rendering_sha256=hashlib.sha256(inspect.getsource(gsplat.rendering).encode()).hexdigest(),
|
||||
legacy_rgb_translation_error=difference(legacy_a[...,:3],legacy_b[...,:3]),
|
||||
corrected_rgb_translation_error=difference(fixed_a[...,:3],fixed_b[...,:3]),
|
||||
alpha_translation_error=difference(alpha_a,alpha_b),depth_translation_error=difference(legacy_a[...,3:],legacy_b[...,3:]),
|
||||
corrected_alpha_max_change=float((alpha_a-fa).abs().max()),corrected_depth_max_change=float((legacy_a[...,3]-fixed_a[...,3]).abs().max()),
|
||||
physical_camera='parallel rays, fixed optical axis, camera translation only')
|
||||
assert report['legacy_rgb_translation_error']>.001,report
|
||||
for key in ['corrected_rgb_translation_error','alpha_translation_error','depth_translation_error','corrected_alpha_max_change','corrected_depth_max_change']:
|
||||
assert report[key]<2e-5,(key,report)
|
||||
assert torch.equal(colours(sh,first,3),colours(sh,second,3))
|
||||
Path('/out/camera-contract.json').write_text(json.dumps(report,indent=2));print('ORTHOGRAPHIC_CAMERA',json.dumps(report),flush=True)
|
||||
@@ -0,0 +1,647 @@
|
||||
"""Scientific invariants for the isolated top-down reconstruction path."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
import numpy as np
|
||||
import shapely
|
||||
from shapely.geometry import box
|
||||
from direct_fixed import fit_target
|
||||
from standard_arrow_templates import polygon
|
||||
from ground_observations import ground_support, sha
|
||||
from candidate_registry import verify
|
||||
|
||||
|
||||
class TopDownTests(unittest.TestCase):
|
||||
|
||||
def test_registration_area_is_continuous_at_pixel_edges(self):
|
||||
from plan_registration import fields,area_iou
|
||||
# One observed painted 1 m pixel occupies [-.5,.5] in both axes.
|
||||
g=dict(size=(1,1),cell=1.,lo=np.array([0.,0.]))
|
||||
known=np.ones((1,1),bool);field=fields(g,dict(target=known,allowed=known,observed=known))
|
||||
for dx in [0.,.1,.49,.5,.51,.9]:
|
||||
q=box(-.5+dx,-.5,.5+dx,.5)
|
||||
# Only the known part contributes: no unseen cell becomes evidence.
|
||||
self.assertAlmostEqual(area_iou(q,field),1.-dx,12)
|
||||
# On a fully known larger field, translation has the analytic IoU.
|
||||
g=dict(size=(3,3),cell=1.,lo=np.array([-1.,-1.]));ink=np.zeros((3,3),bool);ink[1,1]=True
|
||||
field=fields(g,dict(target=ink,allowed=np.ones((3,3),bool),observed=np.ones((3,3),bool)))
|
||||
for dx in [.1,.49,.5,.51,.9]:
|
||||
self.assertAlmostEqual(area_iou(box(-.5+dx,-.5,.5+dx,.5),field),(1.-dx)/(1.+dx),12)
|
||||
|
||||
def test_straight_stripe_cannot_supply_an_arrow_head(self):
|
||||
from object_evidence import evidence
|
||||
from observation_checks import assess
|
||||
from standard_arrow_templates import dimensions
|
||||
from ground_observations import metric_grid
|
||||
for profile in ['short','long']:
|
||||
pose=[0.,0.,0.,.8];q=polygon('straight_arrow',profile,pose)
|
||||
params=dimensions('straight_arrow',profile,pose);g=metric_grid(q,.04,1.2)
|
||||
x,y=g['points'].T;ink=shapely.contains_xy(q,x,y).reshape(g['size'])
|
||||
known=np.ones(g['size'],bool)
|
||||
for label,paint in [('arrow',ink),('stripe',((x>0)&(x<params[3])&(abs(y)<params[5]/2)).reshape(g['size'])),('missing-wing',ink&(y.reshape(g['size'])<params[5]/2))]:
|
||||
v=dict(rgb=np.repeat((paint*255).astype('uint8')[:,:,None],3,axis=2),paint=paint,allowed=known,observed=known,names=['synthetic'])
|
||||
g['views']=[v,v];a=assess(evidence(q,'straight_arrow',params,q,g),1.,1.,1.,'straight_arrow')
|
||||
if label=='arrow':self.assertTrue(a['accepted'],a['failures'])
|
||||
else:
|
||||
self.assertFalse(a['accepted'])
|
||||
self.assertTrue(any(f['check'].startswith('head_support') for f in a['failures']))
|
||||
|
||||
def test_yellow_crossing_does_not_join_white_marking(self):
|
||||
from paint_channels_fast import paint_mask
|
||||
from paint_channels import paint_mask as previous
|
||||
import cv2
|
||||
x,y=np.meshgrid(np.arange(-1,7,.025),np.arange(-2,2,.025))
|
||||
rgb=np.full((*x.shape,3),90,'uint8');known=np.ones(x.shape,bool)
|
||||
yellow=(abs(y-(x-3)*.7)<.08)&(x>1)&(x<5)
|
||||
white=(abs(y)<.07)&(x>0)&(x<6)
|
||||
# This muted yellow lies in both old channel predicates.
|
||||
rgb[yellow]=[200,190,160];rgb[white]=225
|
||||
old=previous(rgb,cell=.025,observed=known,calibration=known)
|
||||
new=paint_mask(rgb,cell=.025,observed=known,calibration=known)
|
||||
self.assertGreater(float(old[yellow&~white].mean()),.9)
|
||||
self.assertEqual(int(new[yellow&~white].sum()),0)
|
||||
self.assertGreater(float(new[white].mean()),.99)
|
||||
yellow_pixels=paint_mask(rgb,'yellow',cell=.025,observed=known,calibration=known)
|
||||
self.assertFalse((new&yellow_pixels).any())
|
||||
def test_visible_marking_does_not_require_smooth_expected_depth(self):
|
||||
from ground_observations import sample_visible_support,sample_ground_support
|
||||
a=dict(view=np.eye(4),intrinsics=np.eye(3),depth=np.full((21,21),50.,'float32'),alpha=np.ones((21,21),'float32'))
|
||||
b={k:v.copy() for k,v in a.items()};a['depth'][10,10]=b['depth'][10,10]=50.3
|
||||
before=a['depth'].tobytes(),b['depth'].tobytes();uv=np.array([[10.,10.]])
|
||||
self.assertTrue(sample_visible_support(a,b,uv)[0]);self.assertFalse(sample_ground_support(a,b,uv)[0])
|
||||
self.assertEqual(before,(a['depth'].tobytes(),b['depth'].tobytes()))
|
||||
a['depth'][10,10]+= .3;self.assertFalse(sample_visible_support(a,b,uv)[0])
|
||||
a['depth'][10,10]=b['depth'][10,10];b['alpha'][10,10]=.5
|
||||
self.assertFalse(sample_visible_support(a,b,uv)[0]);b['alpha'][10,10]=1.;b['depth'][10,10]=np.nan
|
||||
self.assertFalse(sample_visible_support(a,b,uv)[0])
|
||||
|
||||
def test_ideal_corner_defect_is_diagnostic_but_wrong_boundary_rejects(self):
|
||||
from plan_marking_policy import registration_passes
|
||||
from registration_evaluator import RegistrationEvaluator
|
||||
m=dict(coverage=1.,valid=1.,iou=.9,boundary_mean_m=.01,boundary_p90_m=.025,landmark_max_error_m=.2)
|
||||
self.assertTrue(registration_passes([m,m]));self.assertGreaterEqual(min(RegistrationEvaluator.constraints_from([m,m])),0.)
|
||||
for key,value in [('iou',.4),('boundary_mean_m',.1),('boundary_p90_m',.2),('valid',.8),('coverage',.9)]:
|
||||
bad=dict(m,**{key:value});self.assertFalse(registration_passes([bad,m]))
|
||||
self.assertLess(min(RegistrationEvaluator.constraints_from([bad,m])),0.)
|
||||
|
||||
def test_boundary_only_failure_is_not_reported_as_admitted(self):
|
||||
from admission_contract import AdmissionContract
|
||||
from ground_observations import metric_grid
|
||||
from shapely.geometry import mapping
|
||||
q=polygon('straight_arrow','short',[0.,0.,0.,1.])
|
||||
def make_grid(cell):
|
||||
g=metric_grid(q,cell,1.2);x,y=g['points'].T;ink=shapely.contains_xy(q,x,y).reshape(g['size']);known=np.ones(g['size'],bool)
|
||||
g['views']=[dict(rgb=np.repeat((ink*255).astype('uint8')[:,:,None],3,axis=2),paint=ink,target=ink,observed=known,allowed=known,names=['synthetic']) for _ in range(2)]
|
||||
return g
|
||||
row=dict(id='same-source',semantic_score=.9,region=mapping(q),target=mapping(q))
|
||||
c=AdmissionContract([row],q,make_grid(.025),make_grid(.04));original=c.registration.measure
|
||||
def displaced_corner(poly):
|
||||
records=original(poly);records[0]['boundary_p90_m']=.16;return records
|
||||
c.registration.measure=displaced_corner
|
||||
result=c.measure(q,'straight_arrow','short',[0.,0.,0.,1.])
|
||||
self.assertFalse(result['accepted']);self.assertFalse(result['admission']['accepted'])
|
||||
self.assertEqual([r['check'] for r in result['admission']['failures']],['registration_boundary_p90'])
|
||||
self.assertEqual(result['constraint_values'],result['admission']['constraint_values'])
|
||||
self.assertEqual(len(result['constraint_values']),len(result['admission']['constraint_names']))
|
||||
|
||||
def test_surface_explanation_preserves_every_veto(self):
|
||||
from ground_observations import surface_sample_evidence, sample_ground_support
|
||||
a=dict(view=np.eye(4),intrinsics=np.eye(3),depth=np.full((31,31),50.,'float32'),alpha=np.ones((31,31),'float32'))
|
||||
b={k:v.copy() for k,v in a.items()}
|
||||
probes=np.array([[10.,10.],[10.25,10.],[9.,10.],[1.,1.],[-2.,-2.]])
|
||||
for case in ['flat','low-alpha','occlusion','ridge','missing']:
|
||||
with self.subTest(case=case):
|
||||
c={k:v.copy() for k,v in a.items()};g={k:v.copy() for k,v in b.items()}
|
||||
if case=='low-alpha':g['alpha'][10,10]=.5
|
||||
if case=='occlusion':c['depth'][10,10]+=.3
|
||||
if case=='ridge':c['depth'][10,10]+= .19;g['depth'][10,10]+=.19
|
||||
if case=='missing':g['depth'][10,10]=np.nan
|
||||
rows=surface_sample_evidence(c,g,probes)
|
||||
self.assertEqual([r['accepted'] for r in rows],sample_ground_support(c,g,probes).tolist())
|
||||
if case=='ridge':self.assertEqual(rows[0]['causes'],['rendered_depth_span'])
|
||||
if case=='low-alpha':self.assertIn('ground_opacity',rows[0]['causes'])
|
||||
if case=='occlusion':self.assertIn('context_ground_disagreement',rows[0]['causes'])
|
||||
if case=='missing':self.assertIn('missing_or_nonpositive_depth',rows[0]['causes'])
|
||||
self.assertEqual(surface_sample_evidence(a,b,np.empty((0,2))),[])
|
||||
|
||||
def test_proposal_witness_cannot_mix_sources(self):
|
||||
from admission_contract import ProposalPool
|
||||
from shapely.geometry import mapping
|
||||
q=box(0,0,1,1);far=box(5,0,6,1)
|
||||
def row(identity,region,target,score):
|
||||
return dict(id=identity,region=mapping(region),target=mapping(target),semantic_score=score)
|
||||
invalid=[row('region-only',q,far,.9),row('target-only',far,q,.9),row('low-score',q,q,.1)]
|
||||
self.assertLess(ProposalPool(invalid).measure(q,'straight_arrow')['minimum_margin'],0)
|
||||
good=row('complete',q,q,.9)
|
||||
for rows in [invalid+[good],[good]+invalid[::-1],invalid+[good,dict(good,id='duplicate')]]:
|
||||
result=ProposalPool(rows).measure(q,'straight_arrow')
|
||||
self.assertGreaterEqual(result['minimum_margin'],0)
|
||||
self.assertEqual(result['candidate_id'],'complete')
|
||||
self.assertEqual(result['target_iou'],1.)
|
||||
self.assertEqual(result['containment'],1.)
|
||||
|
||||
def test_search_and_independent_admission_agree_under_order_and_duplicates(self):
|
||||
from admission_contract import AdmissionContract
|
||||
from ground_observations import metric_grid
|
||||
from shapely.geometry import mapping
|
||||
from plan_marking_policy import registration_passes as passes
|
||||
q=polygon('straight_arrow','short',[0.,0.,0.,1.]);extent=q
|
||||
def grid(cell):
|
||||
g=metric_grid(q,cell,1.2);x,y=g['points'].T
|
||||
paint=shapely.contains_xy(q,x,y).reshape(g['size']);known=np.ones(g['size'],bool)
|
||||
g['views']=[dict(rgb=np.repeat((paint*255).astype('uint8')[:,:,None],3,axis=2),paint=paint,target=paint,
|
||||
observed=known,allowed=known,names=['synthetic']) for _ in range(2)]
|
||||
return g
|
||||
good=dict(id='complete',semantic_score=.9,region=mapping(q),target=mapping(q))
|
||||
bad=dict(id='unrelated',semantic_score=.99,region=mapping(box(10,10,11,11)),target=mapping(q))
|
||||
contracts=[AdmissionContract(rows,extent,grid(.025),grid(.04)) for rows in
|
||||
[[bad,good],[good,bad],[good,dict(good,id='duplicate'),bad]]]
|
||||
for dx in [0.,.015,.05,.2]:
|
||||
pose=[dx,0.,0.,1.];candidate=polygon('straight_arrow','short',pose)
|
||||
baseline=contracts[0].measure(candidate,'straight_arrow','short',pose)
|
||||
for contract in contracts:
|
||||
fast=contract.measure(candidate,'straight_arrow','short',pose)
|
||||
measured=contract.measure(candidate,'straight_arrow','short',pose,independent=True)
|
||||
self.assertEqual(fast['accepted'],measured['accepted'])
|
||||
self.assertEqual(min(fast['constraint_values'])>=0,measured['accepted'])
|
||||
self.assertTrue(np.allclose(fast['constraint_values'],measured['constraint_values'],atol=1e-7))
|
||||
self.assertTrue(np.array_equal(baseline['constraint_values'],fast['constraint_values']))
|
||||
self.assertEqual(measured['accepted'],passes(measured['metrics']) and measured['admission']['accepted'] and measured['recall']>=.85)
|
||||
|
||||
def test_fixed_geometry_from_unregistered_observations(self):
|
||||
for kind, angle in [('straight_arrow', .71), ('left_arrow', 1.91),
|
||||
('right_arrow', -2.51), ('straight_left_arrow', -.42),
|
||||
('straight_right_arrow', 2.87), ('merge_left_arrow', 1.2),
|
||||
('merge_right_arrow', -1.2)]:
|
||||
with self.subTest(kind=kind):
|
||||
target = polygon(kind, 'short', [13., -9., angle, 1.08])
|
||||
result = fit_target(target)
|
||||
matching = [r for r in result if r['kind'] == kind]
|
||||
self.assertTrue(matching, kind)
|
||||
self.assertGreater(matching[0]['score'], .65)
|
||||
self.assertLess(matching[0]['geometry'].hausdorff_distance(target), .20)
|
||||
# An output is exactly reproducible using four parameters.
|
||||
for r in result:
|
||||
expected = polygon(r['kind'], r['profile'], r['pose'])
|
||||
self.assertLess(expected.symmetric_difference(r['geometry']).area, 1e-12)
|
||||
|
||||
def test_long_profile_and_scale_limits(self):
|
||||
target = polygon('straight_arrow', 'long', [-3., 4., .2, .9])
|
||||
result = fit_target(target)
|
||||
self.assertTrue(result)
|
||||
self.assertGreater(result[0]['score'], .7)
|
||||
self.assertTrue(all(.75 <= r['pose'][3] <= 1.25 for r in result))
|
||||
|
||||
def test_non_symbol_does_not_become_a_proposal(self):
|
||||
self.assertFalse(fit_target(box(0, 0, 4., 4.)))
|
||||
self.assertFalse(fit_target(box(0, 0, 100., .1)))
|
||||
|
||||
def test_coverage_keeps_unknown_and_occlusion(self):
|
||||
geometry = dict(view=np.eye(4), intrinsics=np.eye(3),
|
||||
depth=np.full((21,21), 10., 'float32'), alpha=np.ones((21,21)))
|
||||
ground = {k:v.copy() for k,v in geometry.items()}
|
||||
self.assertTrue(ground_support(geometry, ground).all())
|
||||
ground['alpha'][10,10] = 0
|
||||
self.assertFalse(ground_support(geometry, ground)[10,10])
|
||||
ground['alpha'][10,10] = 1
|
||||
ground['depth'][8:13,8:13] = 11
|
||||
self.assertFalse(ground_support(geometry, ground)[10,10])
|
||||
ground['depth'][10,10] = np.nan
|
||||
self.assertFalse(ground_support(geometry, ground)[10,10])
|
||||
|
||||
def test_direct_fit_to_original_pixel_grid(self):
|
||||
from observed_fixed import fit_grid
|
||||
for kind, angle in [('straight_arrow', .71), ('left_arrow', -1.2),
|
||||
('straight_right_arrow', 2.1), ('merge_left_arrow', -.6)]:
|
||||
with self.subTest(kind=kind):
|
||||
q = polygon(kind, 'short', [0., 0., angle, 1.])
|
||||
lo = np.asarray(q.bounds[:2])-.5
|
||||
hi = np.asarray(q.bounds[2:])+.5
|
||||
x,y = np.meshgrid(np.arange(lo[0],hi[0],.025), np.arange(lo[1],hi[1],.025))
|
||||
paint = shapely.contains_xy(q,x,y)
|
||||
view = dict(target=paint, allowed=np.ones(x.shape,bool), observed=np.ones(x.shape,bool))
|
||||
grid = dict(lo=lo, size=x.shape, cell=.025, views=[view,view])
|
||||
results = [r for r in fit_grid(grid) if r['kind']==kind]
|
||||
self.assertTrue(results)
|
||||
self.assertLess(results[0]['geometry'].hausdorff_distance(q), .12)
|
||||
view['allowed'][:]=False
|
||||
self.assertEqual(fit_grid(grid), [])
|
||||
|
||||
def test_opacity_hole_is_not_a_zero_depth_cliff(self):
|
||||
a = dict(view=np.eye(4), intrinsics=np.eye(3),
|
||||
depth=np.full((21,21),50.,'float32'), alpha=np.ones((21,21)))
|
||||
b = {k:v.copy() for k,v in a.items()}
|
||||
b['alpha'][10,10] = .5
|
||||
supported = ground_support(a,b)
|
||||
self.assertFalse(supported[10,10])
|
||||
self.assertTrue(supported[10,9])
|
||||
self.assertEqual(int(supported.sum()), 21*21-1)
|
||||
# Real geometry discontinuities and absent depth remain vetoes even
|
||||
# when both renders agree about an elevated surface.
|
||||
a['depth'][10,10] = b['depth'][10,10] = 50.3
|
||||
self.assertFalse(ground_support(a,b)[10,9])
|
||||
a['depth'][10,10] = b['depth'][10,10] = np.nan
|
||||
self.assertFalse(ground_support(a,b)[10,9])
|
||||
|
||||
def test_named_object_constraints_are_fixed_and_preserve_admission(self):
|
||||
from observation_checks import assess
|
||||
from reconstruct_topdown import evidence
|
||||
from standard_arrow_templates import dimensions
|
||||
names=None
|
||||
for kind in ['straight_arrow','straight_right_arrow']:
|
||||
q=polygon(kind,'short',[0.,0.,0.,1.]);params=dimensions(kind,'short',[0.,0.,0.,1.])
|
||||
x,y=np.meshgrid(np.arange(-1,7,.04),np.arange(-2,2,.04));points=np.c_[x.ravel(),y.ravel()]
|
||||
paint=shapely.contains_xy(q,x,y);full=np.ones(x.shape,bool)
|
||||
def view(known,ink):return dict(rgb=np.zeros((*x.shape,3),'uint8'),paint=ink,allowed=known,observed=known,names=['synthetic'])
|
||||
for partial in [full,x>1.4,np.zeros(x.shape,bool)]:
|
||||
for ink in [paint,np.zeros(x.shape,bool)]:
|
||||
grid=dict(points=points,size=x.shape,cell=.04,views=[view(full,ink),view(partial,ink&partial)])
|
||||
score=assess(evidence(q,kind,params,q,grid),1.,1.,1.,kind)
|
||||
if names is None:names=score['constraint_names']
|
||||
self.assertEqual(score['constraint_names'],names)
|
||||
self.assertEqual(min(score['constraint_values'])>=0,score['accepted'])
|
||||
missing=assess([],1.,1.,1.,kind)
|
||||
self.assertEqual(names,missing['constraint_names']);self.assertLess(min(missing['constraint_values']),0)
|
||||
|
||||
def test_separable_disk_is_bit_exact_for_paint_observations(self):
|
||||
import cv2,time
|
||||
from paint_channels import paint_mask as original
|
||||
from paint_channels_fast import opening,paint_mask
|
||||
rng=np.random.default_rng(17);gray=rng.integers(0,256,(96,128),dtype='uint8')
|
||||
for k in [5,31,49,75,121,205]:
|
||||
expected=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k,k)))
|
||||
self.assertTrue(np.array_equal(opening(gray,k),expected))
|
||||
rgb=np.repeat(gray[:,:,None],3,axis=2);rgb[20:40,30:60]=[220,190,40]
|
||||
observed=rng.random(gray.shape)>.1;calibration=rng.random(gray.shape)>.2
|
||||
for channel in ['white','yellow']:
|
||||
for cell in [.015,.025,.04,.1]:
|
||||
for known in [None,observed]:
|
||||
self.assertTrue(np.array_equal(paint_mask(rgb,channel,cell,known,calibration),original(rgb,channel,cell,known,calibration)))
|
||||
large=rng.integers(0,256,(512,512),dtype='uint8');k=205
|
||||
start=time.monotonic();expected=cv2.morphologyEx(large,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k,k)));old=time.monotonic()-start
|
||||
start=time.monotonic();actual=opening(large,k);new=time.monotonic()-start
|
||||
self.assertTrue(np.array_equal(actual,expected));print('MORPHOLOGY_SECONDS',old,new,flush=True)
|
||||
|
||||
def test_observation_lattice_is_independent_of_proposal_bounds(self):
|
||||
from ground_observations import metric_grid
|
||||
for cell in [.025,.04]:
|
||||
a=metric_grid(box(13.003,-9.002,18.004,-7.001),cell,1.2)
|
||||
b=metric_grid(box(13.006,-9.005,18.007,-6.998),cell,1.2)
|
||||
def indexed(grid):return {tuple(np.rint(p/cell).astype(int)):tuple(p) for p in grid['points']}
|
||||
left,right=indexed(a),indexed(b);common=left.keys()&right.keys()
|
||||
self.assertGreater(len(common),len(left)*.95)
|
||||
self.assertTrue(all(left[k]==right[k] for k in common))
|
||||
|
||||
def test_native_geometry_keeps_physical_neighbourhood(self):
|
||||
a=dict(view=np.eye(4),intrinsics=np.eye(3),depth=np.full((84,84),50.,'float32'),
|
||||
alpha=np.ones((84,84),'float32'),compatibility_resolution=21)
|
||||
b={k:v.copy() if hasattr(v,'copy') else v for k,v in a.items()}
|
||||
a['depth'][42,42]=b['depth'][42,42]=50.3
|
||||
supported=ground_support(a,b)
|
||||
self.assertFalse(supported[42,50])
|
||||
self.assertTrue(supported[42,51])
|
||||
|
||||
def test_opacity_is_sampled_before_thresholding(self):
|
||||
from ground_observations import sample_ground_support
|
||||
a=dict(view=np.eye(4),intrinsics=np.eye(3),depth=np.full((21,21),50.,'float32'),alpha=np.ones((21,21),'float32'))
|
||||
b={k:v.copy() for k,v in a.items()};a['alpha'][10,10]=b['alpha'][10,10]=.8
|
||||
measured=sample_ground_support(a,b,np.array([[10.,10.],[10.1,10.],[10.4,10.]]))
|
||||
self.assertEqual(measured.tolist(),[False,False,True])
|
||||
a['depth'][10,10]=b['depth'][10,10]=50.4
|
||||
self.assertFalse(sample_ground_support(a,b,np.array([[10.4,10.]])).any())
|
||||
|
||||
def test_constraint_dimension_is_stable_across_view_boundary(self):
|
||||
from observed_fixed import constraints_for
|
||||
q=polygon('straight_arrow','short',[0.,0.,0.,1.])
|
||||
x,y=np.meshgrid(np.arange(-1,7,.025),np.arange(-2,2,.025))
|
||||
paint=shapely.contains_xy(q,x,y);observed=x>1.
|
||||
full=dict(paint=paint,target=paint,allowed=np.ones(x.shape,bool),observed=np.ones(x.shape,bool))
|
||||
partial=dict(paint=paint&observed,target=paint&observed,allowed=observed,observed=observed)
|
||||
grid=dict(lo=np.array([-1.,-2.]),size=x.shape,cell=.025,views=[full,partial])
|
||||
constraints=constraints_for(grid)
|
||||
values=[constraints(polygon('straight_arrow','short',[dx,0.,0.,1.])) for dx in [0.,.9,1.1]]
|
||||
self.assertEqual(len({len(v) for v in values}),1)
|
||||
self.assertTrue(all(np.isfinite(v).all() for v in values))
|
||||
|
||||
def test_partial_view_connection_is_unknown_not_broken(self):
|
||||
from observation_checks import branch_evidence, assess
|
||||
from reconstruct_topdown import evidence
|
||||
from standard_arrow_templates import dimensions
|
||||
q=polygon('straight_right_arrow','short',[0.,0.,0.,1.]);params=dimensions('straight_right_arrow','short',[0.,0.,0.,1.])
|
||||
x,y=np.meshgrid(np.arange(-1,6,.04),np.arange(-2,2,.04));points=np.c_[x.ravel(),y.ravel()]
|
||||
paint=shapely.contains_xy(q,x,y);all_known=np.ones(x.shape,bool)
|
||||
# The fixed short branch joins the stem by x=1.2 m. This crop
|
||||
# retains its tip and the straight head but hides that connection.
|
||||
partial=x>1.4
|
||||
full=branch_evidence(paint,all_known,all_known,points,q,'straight_right_arrow',params)
|
||||
clipped=branch_evidence(paint&partial,partial,partial,points,q,'straight_right_arrow',params)
|
||||
broken=branch_evidence(paint&partial,all_known,all_known,points,q,'straight_right_arrow',params)
|
||||
self.assertGreater(full['head_connected_support'],.85)
|
||||
self.assertGreater(clipped['connection_unobserved_pixels'],0)
|
||||
self.assertEqual(broken['connection_unobserved_pixels'],0)
|
||||
self.assertLess(broken['head_connected_support'],.85)
|
||||
rgb=np.zeros((*x.shape,3),'uint8')
|
||||
def view(known,ink):return dict(rgb=rgb,paint=ink,allowed=known,observed=known,names=['synthetic'])
|
||||
grid=dict(points=points,size=x.shape,cell=.04,views=[view(all_known,paint),view(partial,paint&partial)])
|
||||
ev=evidence(q,'straight_right_arrow',params,q,grid)
|
||||
self.assertTrue(assess(ev,1.,1.,1.,'straight_right_arrow')['accepted'])
|
||||
grid['views'][1]=view(all_known,paint&partial)
|
||||
self.assertFalse(assess(evidence(q,'straight_right_arrow',params,q,grid),1.,1.,1.,'straight_right_arrow')['accepted'])
|
||||
|
||||
def test_complete_view_admission_preserves_all_existing_limits(self):
|
||||
from observation_checks import assess
|
||||
from arrow_admission import accept_symbol as prior
|
||||
from reconstruct_topdown import evidence
|
||||
from standard_arrow_templates import dimensions
|
||||
import copy
|
||||
q=polygon('straight_arrow','short',[0.,0.,0.,1.]);params=dimensions('straight_arrow','short',[0.,0.,0.,1.])
|
||||
x,y=np.meshgrid(np.arange(-1,6,.04),np.arange(-1,1,.04));points=np.c_[x.ravel(),y.ravel()]
|
||||
paint=shapely.contains_xy(q,x,y);known=np.ones(x.shape,bool)
|
||||
v=dict(rgb=np.zeros((*x.shape,3),'uint8'),paint=paint,allowed=known,observed=known,names=['synthetic'])
|
||||
ev=evidence(q,'straight_arrow',params,q,dict(points=points,size=x.shape,cell=.04,views=[v,v]))
|
||||
self.assertTrue(prior(ev,1.,1.,1.,'straight_arrow'))
|
||||
for key in ['paint_valid','observed_support','negative_paint','recall','connected_recall','head_flank_paint']:
|
||||
for value in [0.,.1,.5,.79,.849,.949,.969,.97,1.]:
|
||||
for rank in [0,1]:
|
||||
data=copy.deepcopy(ev);data[rank][key]=value
|
||||
self.assertEqual(assess(data,1.,1.,1.,'straight_arrow')['accepted'],prior(data,1.,1.,1.,'straight_arrow'))
|
||||
|
||||
def test_camera_mismatch_fails_closed(self):
|
||||
a = dict(view=np.eye(4), intrinsics=np.eye(3), depth=np.ones((9,9)), alpha=np.ones((9,9)))
|
||||
b = {k:v.copy() for k,v in a.items()}; b['view'][0,3] = 1.
|
||||
with self.assertRaises(ValueError):
|
||||
ground_support(a, b)
|
||||
|
||||
def test_compiled_registration_matches_original_metrics(self):
|
||||
from registration_evaluator import RegistrationEvaluator
|
||||
from plan_registration import metrics
|
||||
from plan_marking_policy import registration_passes as passes
|
||||
from standard_arrow_templates import KINDS
|
||||
for kind in KINDS:
|
||||
q=polygon(kind,'short',[0.,0.,.1,1.]);x,y=np.meshgrid(np.arange(-1,7,.025),np.arange(-2,2,.025))
|
||||
points=np.c_[x.ravel(),y.ravel()];paint=shapely.contains_xy(q,x,y);allowed=np.ones(x.shape,bool);allowed[20:24,50:53]=False
|
||||
def view(obs):return dict(target=paint&obs,paint=paint&obs,allowed=allowed&obs,observed=obs)
|
||||
grid=dict(lo=np.array([-1.,-2.]),points=points,size=x.shape,cell=.025,views=[view(np.ones(x.shape,bool)),view(x>1.4)])
|
||||
fast=RegistrationEvaluator(grid)
|
||||
for delta in [0.,.03,-.17]:
|
||||
testq=polygon(kind,'short',[delta,delta,.1,1.]);slow=[metrics(testq,grid,v) for v in grid['views']]
|
||||
for a,b in zip(fast.measure(testq),slow):self.assertEqual(a,{k:b[k] for k in a})
|
||||
self.assertEqual(fast.margin(testq)>=0,passes(slow))
|
||||
|
||||
def test_compiled_evaluator_matches_independent_original_pixels(self):
|
||||
from observation_evaluator import ObservationEvaluator
|
||||
from reconstruct_topdown import evidence
|
||||
from standard_arrow_templates import KINDS,dimensions
|
||||
for kind in KINDS:
|
||||
params=dimensions(kind,'short',[0.,0.,.1,1.]);q=polygon(kind,'short',[0.,0.,.1,1.])
|
||||
x,y=np.meshgrid(np.arange(-1,7,.04),np.arange(-2,2,.04));points=np.c_[x.ravel(),y.ravel()]
|
||||
paint=shapely.contains_xy(q,x,y);allowed=np.ones(x.shape,bool);allowed[20:24,50:53]=False
|
||||
def view(obs):return dict(rgb=np.zeros((*x.shape,3),'uint8'),paint=paint&obs,allowed=allowed&obs,observed=obs,names=['synthetic'])
|
||||
grid=dict(points=points,size=x.shape,cell=.04,views=[view(np.ones(x.shape,bool)),view(x>1.4)])
|
||||
fast=ObservationEvaluator(q,grid)
|
||||
for delta in [0.,.03,-.07]:
|
||||
pose=[delta,delta,.1,1.];testq=polygon(kind,'short',pose);parameters=dimensions(kind,'short',pose)
|
||||
self.assertEqual(fast.evaluate(testq,kind,parameters),evidence(testq,kind,parameters,q,grid))
|
||||
|
||||
def test_pixel_geometry_preserves_cell_area_and_holes(self):
|
||||
from pixel_geometry import vector
|
||||
mask=np.ones((7,9),bool);mask[2:5,3:6]=False;mask[0,:]=False;mask[0,0]=True
|
||||
# A rotated world grid exercises axis orientation, origin, thin stems
|
||||
# and holes without fitting to a specific street or arrow.
|
||||
origin=np.array([1000.,-200.]);u=np.array([.02,.01]);v=np.array([-.01,.02])
|
||||
corners=np.array([origin,origin+9*u,origin+9*u+7*v,origin+7*v])
|
||||
q=vector(mask,dict(world_corners=corners,width_px=9,height_px=7))
|
||||
self.assertAlmostEqual(q.area,mask.sum()*abs(np.linalg.det(np.array([u,v]))),10)
|
||||
y,x=np.indices(mask.shape);points=origin+x[...,None]*u+y[...,None]*v
|
||||
self.assertTrue(np.array_equal(shapely.contains_xy(q,points[:,:,0],points[:,:,1]),mask))
|
||||
|
||||
def test_preservation_requires_unique_same_class_objects(self):
|
||||
from preservation import compare
|
||||
from shapely.geometry import mapping
|
||||
def f(identity,x,kind='straight_arrow'):
|
||||
return dict(id=identity,properties=dict(subtype=kind),geometry=mapping(box(x,0,x+1,1)))
|
||||
old=dict(features=[f('a',0),f('b',.1)])
|
||||
self.assertEqual(compare(old,dict(features=[f('one',0)]))['matched'],1)
|
||||
self.assertFalse(compare(old,dict(features=[f('wrong',0,'left_arrow')]))['passed'])
|
||||
self.assertTrue(compare(old,dict(features=[f('one',0),f('two',.1)]))['passed'])
|
||||
self.assertEqual(compare(old,dict(features=[]))['matched'],0)
|
||||
|
||||
def test_dark_crack_does_not_turn_adjacent_asphalt_into_paint(self):
|
||||
from paint_channels_fast import paint_mask
|
||||
x,y=np.meshgrid(np.arange(0,8,.025),np.arange(2.7,5.3,.025))
|
||||
gray=np.full(x.shape,125,'uint8');gray[abs(y-3.25)<.12]=70
|
||||
truth=(x>1)&(x<7)&(abs(y-4)<.12);gray[truth]=155
|
||||
rgb=np.repeat(gray[:,:,None],3,axis=2);known=np.ones(x.shape,bool)
|
||||
old=paint_mask(rgb,cell=.025,observed=known,calibration=known)
|
||||
measured=paint_mask(rgb,cell=.025,observed=known,calibration=known,background='median')
|
||||
# Both methods face the same 1% background-error limit: old must
|
||||
# demonstrate the failure, the replacement must actually pass it.
|
||||
self.assertGreater(float(old[~truth].mean()),.01)
|
||||
print('CRACK_BACKGROUND_FALSE_PAINT',float(old[~truth].mean()),float(measured[~truth].mean()),flush=True)
|
||||
self.assertGreater(float(measured[truth].mean()),.98)
|
||||
self.assertLess(float(measured[~truth].mean()),.01)
|
||||
|
||||
def test_competing_pose_family_cannot_erase_semantic_hypothesis(self):
|
||||
# The first appearance channel resembles a merge; another initial
|
||||
# observation supports a straight arrow. Only the latter class is
|
||||
# semantically admissible in this synthetic scene.
|
||||
straight=polygon('straight_arrow','short',[0.,0.,0.,1.])
|
||||
merge=polygon('merge_left_arrow','short',[0.,0.,0.,1.])
|
||||
target=merge.union(straight)
|
||||
results=fit_target(target,seed_targets=[straight],geometric_constraints=lambda q:[1.],
|
||||
object_constraints=lambda q,kind,profile,pose:[1. if kind=='straight_arrow' else -1.])
|
||||
self.assertTrue(any(r['kind']=='straight_arrow' for r in results))
|
||||
self.assertTrue(any(r['kind']=='straight_arrow' and r['feasible'] for r in results))
|
||||
|
||||
def test_semantic_overlap_cannot_compensate_for_missing_original_paint(self):
|
||||
from direct_fixed import observation_score
|
||||
from registration import POLICY as geometry
|
||||
from arrow_admission import POLICY as objects
|
||||
# A semantic-perfect unsupported pose must rank below one satisfying
|
||||
# both measured channels, regardless of duplicate semantic proposals.
|
||||
unsupported=[.4,1.,1.,1.]
|
||||
supported=[geometry['min_iou'],objects['arrow_fit_score']]
|
||||
self.assertLess(observation_score(unsupported),observation_score(supported))
|
||||
self.assertAlmostEqual(observation_score(supported),1.)
|
||||
self.assertEqual(observation_score([.7,.7]),observation_score([.7,1.,1.]))
|
||||
|
||||
def test_illumination_filter_has_real_halo_and_fixed_calibration_domain(self):
|
||||
from ground_observations import GroundObservations,metric_grid
|
||||
from paint_channels_fast import paint_mask
|
||||
class Synthetic(GroundObservations):
|
||||
def __init__(self):pass
|
||||
def raw_views(self,lattice):
|
||||
x=lattice['points'][:,0].reshape(lattice['size']);y=lattice['points'][:,1].reshape(lattice['size'])
|
||||
gray=125+30*np.sin(x*.9)+9*np.cos(y*.7)
|
||||
gray[(x>1)&(x<7)&(abs(y-4)<.12)]+=60
|
||||
rgb=np.repeat(np.clip(gray,0,255).astype('uint8')[:,:,None],3,axis=2);known=np.ones(x.shape,bool)
|
||||
return [dict(rgb=rgb,observed=known,allowed=known,names=['synthetic']) for _ in range(2)]
|
||||
obs=Synthetic();grid=obs.grid(box(1,3.88,7,4.12));low=grid['points'].min(0);high=grid['points'].max(0)
|
||||
parent=metric_grid(box(*low,*high),.025,2.);raw=obs.raw_views(parent)[0]
|
||||
indices=np.rint((grid['points']-parent['lo'])/.025).astype(int)
|
||||
calibration=np.zeros(parent['size'],bool);calibration[indices[:,1],indices[:,0]]=True
|
||||
full=paint_mask(raw['rgb'],cell=.025,observed=raw['observed'],calibration=calibration,background='median')
|
||||
self.assertTrue(np.array_equal(grid['views'][0]['paint'].ravel(),full[indices[:,1],indices[:,0]]))
|
||||
|
||||
def test_object_measurement_separates_paint_from_uneven_background(self):
|
||||
from ground_observations import GroundObservations
|
||||
class Synthetic(GroundObservations):
|
||||
def __init__(self):pass
|
||||
def raw_views(self,lattice):
|
||||
x=lattice['points'][:,0].reshape(lattice['size']);y=lattice['points'][:,1].reshape(lattice['size'])
|
||||
gray=125+12*np.sin(x*1.7)+9*np.cos(y*2.1)+3*np.sin(x*12+y*9)
|
||||
painted=(x>1)&(x<7)&(abs(y-4)<.12);gray[painted]=230
|
||||
rgb=np.repeat(np.clip(gray,0,255).astype('uint8')[:,:,None],3,axis=2);known=np.ones(x.shape,bool)
|
||||
return [dict(rgb=rgb,observed=known,allowed=known,names=['synthetic']) for _ in range(2)]
|
||||
grid=Synthetic().grid(box(1,3.88,7,4.12));x=grid['points'][:,0].reshape(grid['size']);y=grid['points'][:,1].reshape(grid['size'])
|
||||
truth=(x>1)&(x<7)&(abs(y-4)<.12);mask=grid['views'][0]['paint']
|
||||
self.assertGreater(float(mask[truth].mean()),.98)
|
||||
self.assertLess(float(mask[~truth].mean()),.01)
|
||||
|
||||
def test_camera_broad_phase_preserves_original_geometric_owners(self):
|
||||
from ground_observations import GroundObservations,metric_grid
|
||||
from fit_scene import project
|
||||
from row_evidence import choose_owners
|
||||
class Synthetic(GroundObservations):
|
||||
def __init__(self):
|
||||
self.tiles=[dict(id=str(i)) for i in range(4)]
|
||||
self.centers=np.array([[-80.,0.],[0.,0.],[40.,0.],[300.,0.]])
|
||||
def camera(self,name):
|
||||
view=np.eye(4);view[:2,3]=-self.centers[int(name)]
|
||||
return dict(view=view,intrinsics=np.array([[20.,0.,600.],[0.,20.,600.],[0.,0.,1.]]))
|
||||
def rgb(self,name):return np.full((32,32,3),30+int(name)*40,'uint8')
|
||||
def surface(self,name,points):return np.ones(len(points),bool)
|
||||
obs=Synthetic()
|
||||
for region in [box(-2,-1,15,1),box(180,-1,190,1)]:
|
||||
grid=metric_grid(region,.5,0);points=grid['points']
|
||||
distance=np.linalg.norm(points[:,None]-obs.centers[None],axis=2)
|
||||
cover=np.zeros(distance.shape,bool)
|
||||
for i,tile in enumerate(obs.tiles):
|
||||
uv=project(points,obs.camera(tile['id']));cover[:,i]=(uv.min(1)>=20)&(uv.max(1)<1180)
|
||||
expected=choose_owners(distance,cover);views=obs.raw_views(grid)
|
||||
for rank,view in enumerate(views):
|
||||
known=expected[:,rank]>=0
|
||||
self.assertTrue(np.array_equal(known,view['observed'].ravel()))
|
||||
self.assertTrue(np.array_equal(view['rgb'].reshape(-1,3)[known,0],30+expected[known,rank]*40))
|
||||
|
||||
def test_consumers_share_one_object_paint_measurement(self):
|
||||
from ground_observations import GroundObservations
|
||||
class Synthetic(GroundObservations):
|
||||
def __init__(self):self.calls=0
|
||||
def raw_views(self,lattice):
|
||||
self.calls+=1;points=lattice['points'];x=points[:,0];y=points[:,1]
|
||||
values=80+15*np.sin(x*4)+12*np.cos(y*5)
|
||||
values+=130*((abs(y-.3)<.13)&(x>1)&(x<6))
|
||||
gray=np.clip(values,0,255).astype('uint8').reshape(lattice['size'])
|
||||
rgb=np.repeat(gray[:,:,None],3,axis=2);known=np.ones(gray.shape,bool)
|
||||
return [dict(rgb=rgb,allowed=known,observed=known,names=['synthetic']) for _ in range(2)]
|
||||
obs=Synthetic();region=box(1,0,6,.6)
|
||||
fine=obs.grid(region);coarse=obs.grid(region,cell=.04)
|
||||
count=obs.calls;again=obs.grid(region)
|
||||
self.assertEqual(obs.calls,count)
|
||||
self.assertTrue(np.array_equal(fine['views'][0]['paint'],again['views'][0]['paint']))
|
||||
# Different consumers sample the same measured paint, never rerun Otsu.
|
||||
uv=np.rint((coarse['points']-fine['lo'])/.025).astype(int)
|
||||
inside=(uv>=0).all(1)&(uv<np.array(fine['size'][::-1])).all(1)
|
||||
self.assertTrue(inside.all())
|
||||
actual=coarse['views'][0]['paint'].ravel()[inside]
|
||||
expected=fine['views'][0]['paint'][uv[inside,1],uv[inside,0]]
|
||||
self.assertTrue(np.array_equal(actual,expected))
|
||||
|
||||
def test_object_association_retains_all_original_measurements(self):
|
||||
from candidate_registry import group_observations
|
||||
from shapely.affinity import translate
|
||||
q=polygon('straight_arrow','short',[0.,0.,0.,1.])
|
||||
observations=[dict(patch=str(i),source='semantic-silhouette',semantic_score=.9-i*.01,
|
||||
extent=translate(q,xoff=.01*i),region=q,target=q) for i in range(6)]
|
||||
groups=group_observations(observations)
|
||||
self.assertEqual(len(groups),1)
|
||||
self.assertEqual(len(groups[0]),6)
|
||||
self.assertEqual({id(v) for v in groups[0]},{id(v) for v in observations})
|
||||
other=dict(observations[0],patch='neighbor',extent=translate(q,yoff=3.))
|
||||
self.assertEqual(len(group_observations(observations+[other])),2)
|
||||
|
||||
def test_reconciliation_preserves_missing_and_unrelated_objects(self):
|
||||
from reconcile_objects import reconcile
|
||||
import hashlib,copy
|
||||
from shapely.geometry import mapping
|
||||
def f(identity,x,kind='straight_arrow'):
|
||||
return dict(id=identity,properties=dict(subtype=kind,authority='observation-only',route_permission='unassigned',review_status='unreviewed',**{'class':'road_marking'}),geometry=mapping(box(x,0,x+1,1)))
|
||||
base=dict(type='FeatureCollection',features=[f('old-a',0),f('old-b',3),f('stripe',10,'linear_marking')])
|
||||
result=dict(type='FeatureCollection',features=[f('new-a',.01),f('new-c',6)])
|
||||
bb=json.dumps(base).encode();rb=json.dumps(result).encode()
|
||||
receipt=dict(passed=True,original_pixels_remeasured=True,immutable_presets=True,source_registry_verified=True,
|
||||
source_result_sha256=hashlib.sha256(rb).hexdigest(),accepted=2,checks=[dict(id=v['id']) for v in result['features']])
|
||||
assembled,ledger=reconcile(bb,rb,receipt);byid={v['id']:v for v in assembled['features']}
|
||||
self.assertEqual(set(byid),{'old-a','old-b','stripe','new-c'})
|
||||
saved=json.loads(bb)
|
||||
self.assertEqual(byid['old-b'],saved['features'][1]);self.assertEqual(byid['stripe'],saved['features'][2])
|
||||
self.assertEqual(ledger['retained_previous_arrow_geometry'],['old-b']);self.assertEqual(ledger['deleted'],[])
|
||||
modified=copy.deepcopy(result);modified['features'][0]['geometry']=mapping(box(100,0,101,1))
|
||||
with self.assertRaises(ValueError):reconcile(bb,json.dumps(modified).encode(),receipt)
|
||||
bad=copy.deepcopy(receipt);bad['checks'].pop()
|
||||
with self.assertRaises(ValueError):reconcile(bb,rb,bad)
|
||||
|
||||
def test_reconciliation_upgrades_only_contained_unreviewed_fragments(self):
|
||||
from reconcile_objects import reconcile
|
||||
from shapely.geometry import mapping
|
||||
import hashlib
|
||||
def feature(identity,geometry,kind,authority='observation-only'):
|
||||
return dict(id=identity,geometry=mapping(geometry),properties=dict(subtype=kind,
|
||||
authority=authority,review_status='unreviewed',**{'class':'road_marking'}))
|
||||
arrow=polygon('straight_arrow','short',[0.,0.,0.,1.])
|
||||
proposal=feature('complete',arrow,'straight_arrow');rb=json.dumps(dict(features=[proposal])).encode()
|
||||
receipt=dict(passed=True,original_pixels_remeasured=True,immutable_presets=True,source_registry_verified=True,
|
||||
source_result_sha256=hashlib.sha256(rb).hexdigest(),accepted=1,checks=[dict(id='complete')])
|
||||
center=arrow.representative_point();contained=arrow.intersection(center.buffer(.2))
|
||||
self.assertGreater(contained.area,.005)
|
||||
for geometry,authority,allowed in [(contained,'observation-only',True),
|
||||
(box(-20,-.05,20,.05),'observation-only',False),(contained,'manual',False)]:
|
||||
old=feature('fragment',geometry,'linear_marking',authority);base=dict(features=[old])
|
||||
assembled,ledger=reconcile(json.dumps(base).encode(),rb,receipt)
|
||||
if allowed:
|
||||
self.assertEqual(len(assembled['features']),1)
|
||||
self.assertEqual(assembled['features'][0]['id'],'fragment')
|
||||
self.assertEqual(assembled['features'][0]['properties']['subtype'],'straight_arrow')
|
||||
self.assertEqual(ledger['fragment_upgrades'][0]['previous_records'],json.loads(json.dumps([old])))
|
||||
self.assertEqual(ledger['conflicts'],[])
|
||||
else:
|
||||
self.assertEqual(assembled,json.loads(json.dumps(base)))
|
||||
self.assertEqual(len(ledger['conflicts']),1)
|
||||
|
||||
def test_source_changes_invalidate_registry(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
for folder in ['symbol-patches','symbol-masks']:
|
||||
(root/folder).mkdir()
|
||||
files = ['symbol-patches.json','symbol-semantics.json','symbol-patches/a.png','symbol-masks/a.npz']
|
||||
for filename in files:
|
||||
(root/filename).write_bytes(b'original')
|
||||
from candidate_registry import VERSION
|
||||
from ground_observations import PHOTOMETRY
|
||||
registry = dict(version=VERSION,photometry=PHOTOMETRY,patch_manifest_sha256=sha(root/files[0]), semantics_sha256=sha(root/files[1]),
|
||||
inputs={'a':dict(image_sha256=sha(root/files[2]), masks_sha256=sha(root/files[3]))})
|
||||
self.assertTrue(verify(root, registry))
|
||||
(root/files[2]).write_bytes(b'changed')
|
||||
with self.assertRaises(ValueError):
|
||||
verify(root, registry)
|
||||
|
||||
|
||||
class SpatialMembershipTests(unittest.TestCase):
|
||||
def test_index_equals_full_scan(self):
|
||||
from spatial_index import SpatialIndex
|
||||
rng=np.random.default_rng(812);world=rng.uniform(-100,100,(10000,3));relative=rng.uniform(-2,8,len(world))
|
||||
world[:4,:2]=[[-20,-20],[0,0],[20,20],[20,20]];relative[:4]=[0,0,0,5]
|
||||
index=SpatialIndex(world,relative,-.6,4.)
|
||||
for bounds in [[[-20,-20],[20,20]],[[0,0],[0,0]],[[150,150],[180,180]]]+[
|
||||
[a,a+rng.uniform(1,70,2)] for a in rng.uniform(-120,100,(30,2))]:
|
||||
bounds=np.asarray(bounds)
|
||||
expected=np.flatnonzero(((world[:,:2]>=bounds[0])&(world[:,:2]<=bounds[1])).all(1)&(relative>=-.6)&(relative<=4.))
|
||||
np.testing.assert_array_equal(index.query(bounds),expected)
|
||||
empty=SpatialIndex(world,relative,20,30)
|
||||
self.assertEqual(len(empty.query([[-100,-100],[100,100]])),0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,199 @@
|
||||
"""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()
|
||||
Reference in New Issue
Block a user