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,77 @@
|
||||
Two-view bounded sections qualification
|
||||
======================================
|
||||
|
||||
This offline pass takes the accepted consensus-pass-20261012 vector map and
|
||||
its pinned Gaussian ground render evidence. It adds no paint. Common rules,
|
||||
identical parameters and one frozen source execute on all three scenes.
|
||||
|
||||
Components and evidence
|
||||
-----------------------
|
||||
OpenCV minAreaRect, remap and grayscale morphology propose straight common
|
||||
sections and measure local paint contrast. SciPy peak detection distinguishes
|
||||
one physical ridge from a second genuine row, including intermittent paint.
|
||||
Shapely clips only the confirmed longitudinal interval. The existing
|
||||
consensus_profiles module supplies the two-view evidence gate unchanged.
|
||||
|
||||
A source can be partly overlapped, unlike the previous 75% whole-object rule.
|
||||
The common interval must be at least 0.60 m. Source length is 0.60--70 m,
|
||||
source width <=0.60 m; keeper length 1.45--70 m, width <=0.40 m. Direction
|
||||
agreement is <=4 degrees and lateral distance <=0.65 m. Two nearest covering
|
||||
views are fixed before signal checks; no positive-view cherry-picking.
|
||||
|
||||
Both views need >=95% valid samples and >=85% bright keeper support, keeper
|
||||
median contrast >=22. The inherited single-ridge, empty-offset or containment
|
||||
criteria and second-ridge veto decide a cut. Vehicles, low alpha, non-road
|
||||
labels and protected markings are unknown/protected rather than dark asphalt.
|
||||
The views are two renders of one reconstruction, not independent observations.
|
||||
|
||||
Multiple cuts of one source are unioned. Every nominated keeper survives
|
||||
unchanged. Unselected features remain byte-equivalent as JSON objects. For
|
||||
selected sources, the old boundary outside confirmed sections is preserved;
|
||||
new endpoints interpolate existing Z through Shapely's 3D polygon operation.
|
||||
No global snap, coordinate patch, per-street threshold or manual ROI is used.
|
||||
Tiny numerical polygons of area <=1e-9 m2 are omitted; this is not a cosmetic
|
||||
length filter. No uncertain remaining tail is deleted just for appearance.
|
||||
|
||||
Gap safeguard
|
||||
-------------
|
||||
Two existing observed long dashes with matching period and direction may
|
||||
nominate a gap. Each anchor must be visible and bright in both views. The
|
||||
whole lateral corridor of the old source must show empty, valid asphalt:
|
||||
>=95% validity, >=90% dark samples, 90th percentile contrast <8. Real paint,
|
||||
unknown pixels, a different rhythm or one view veto the cut. A GOST rhythm is
|
||||
not permission to erase paint. If no candidate clears these requirements,
|
||||
no gap edit is made. Real-map acceptance and controlled examples are reported
|
||||
separately; the gap rule is not claimed as effective on scenes with zero hits.
|
||||
|
||||
Qualification and replay
|
||||
------------------------
|
||||
Use the canonical Mission Core repository and its existing private cache.
|
||||
Worker006 performs every numeric computation, test and raster render in the
|
||||
pinned CPU image sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0.
|
||||
The recorded-job queue reserves simulation and releases after container
|
||||
cleanup. Read-only root, no network, 4 CPUs, 20 GiB RAM, 1 GiB tmpfs and a
|
||||
1800-second stage timeout apply. Mac orchestration does not run image math.
|
||||
|
||||
Canonical research entry: simulation/urban-plan-research/sections_pass/bundle.json.
|
||||
The manifest maps unchanged modules to previous canonical stages and new files
|
||||
to this stage. algorithm-source.zip contains a flat Python source bundle.
|
||||
The review font is external and pinned by SHA; its qualified copy remains in
|
||||
the qualification source directory. Existing registry paths, SSH configuration,
|
||||
Gaussian caches and repository environment are required for replay.
|
||||
|
||||
Qualification root: .runtime/simulation-qualifications/sections-pass-20261012/operator.
|
||||
The replay directory contains runner, collector, verifier, scene registry and
|
||||
frozen-source manifest. Set URBAN_SOURCE_BUNDLE to the fully assembled pinned
|
||||
source directory. Run test_sections on one scene, then refine_sections,
|
||||
audit_sections, render_sections and render_plan sequentially for each scene.
|
||||
The stage runner resolves input by registry, not a scene-specific algorithm.
|
||||
collect_sections verifies all transferred files; verify_sections checks all
|
||||
source hashes, identical policy, map audits, baseline hashes, input hashes,
|
||||
released resources and live-map preservation.
|
||||
|
||||
Output includes before/after JPGs, complete vector maps, replacements and
|
||||
per-cut evidence, audits, tests, input hashes and execution receipts. Prior
|
||||
GOST dimensional assessment and crosswalk audit are retained unchanged. No
|
||||
geodetic accuracy, complete recall or legal compliance is established. This
|
||||
is a research candidate; no live map deployment, Ops publication or commit.
|
||||
@@ -0,0 +1,33 @@
|
||||
from pathlib import Path
|
||||
import json,hashlib,numpy as np,shapely
|
||||
from shapely.geometry import shape
|
||||
from section_profiles import POLICY,VERSION
|
||||
old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/sections-rows.json').read_text());repl=json.loads(Path('/out/sections-replacements.json').read_text())
|
||||
original={f['id']:f for f in old['features']};features={f['id']:f for f in new['features']};checks={}
|
||||
checks['unique_ids']=len(features)==len(new['features'])
|
||||
checks['untouched_features_identical']=all(features.get(fid)==f for fid,f in original.items()if fid not in repl)
|
||||
checks['only_linear_replaced']=all(original[fid]['properties'].get('subtype')=='linear_marking'for fid in repl)
|
||||
checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features'])
|
||||
checks['keepers_unchanged']=all(all(features.get(fid)==original[fid]for fid in r['output_ids'])for r in rows)
|
||||
checks['every_source_traced']=set(repl)==set(r['source_id']for r in rows)
|
||||
checks['all_new_objects_traced']=set(features)-set(original)==set(fid for r in repl.values()for fid in r['output_ids'])
|
||||
checks['two_distinct_views']=all(len(set(r['source_tiles']))==2 and len(r['views'])==2 for r in rows)
|
||||
checks['residuals_preserve_xy']=all(shapely.force_2d(shape(original[sid]['geometry'])).difference(shape(r['cut_geometry'])).symmetric_difference(shapely.union_all([shapely.force_2d(shape(features[fid]['geometry']))for fid in r['output_ids']])).area<1e-8 for sid,r in repl.items())
|
||||
checks['each_cut_from_recorded_evidence']=all(shape(r['cut_geometry']).symmetric_difference(shapely.union_all([shape(x['cut_geometry'])for x in rows if x['source_id']==sid])).area<1e-8 for sid,r in repl.items())
|
||||
checks['no_new_paint_area']=all(shapely.union_all([shape(features[fid]['geometry'])for fid in r['output_ids']]).difference(shape(original[sid]['geometry'])).area<1e-8 for sid,r in repl.items())
|
||||
def evidence(r):
|
||||
if r['kind']=='confirmed_dash_gap':return all(v['valid']>=.95 and v['dark_fraction']>=.9 and v['q90']<8 and all(a['valid']>=.95 and a['support']>=.85 and a['median']>=22 for a in v['anchors'])for v in r['views'])
|
||||
if not all(v['source_valid']>=.95 and v['target_valid']>=.95 and v['target_support']>=.85 and v['target_median']>=22 for v in r['views']):return False
|
||||
if not all(x['valid_fraction']>=.95 and x['two_ridge_fraction']<=.1 and x['longest_two_ridge_m']<.25 for x in r['ridges']):return False
|
||||
if r['kind']=='overlapping_duplicate':return r['geometry']['contained_fraction']>=.90
|
||||
if r['kind']=='unsupported_offset_duplicate':return all(v['source_support']<=.15 and v['source_q75']<8 for v in r['views'])
|
||||
if r['kind']!='one_ridge_two_vectors':return False
|
||||
xs=r['ridges']
|
||||
if not all(len(x['peaks'])==1 for x in xs):return False
|
||||
ds=[x['peaks'][0]['offset']for x in xs]
|
||||
return max(ds)-min(ds)<=.05 and all(abs(d)>=.10 and abs(d-x['target_offset'])<=.08 and abs(d)-abs(d-x['target_offset'])>=.06 for d,x in zip(ds,xs))
|
||||
checks['each_cut_has_image_evidence']=all(evidence(r)for r in rows)
|
||||
checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes()
|
||||
checks['same_policy']=new['section_refinement']==VERSION and json.loads(Path('/out/sections-report.json').read_text())['policy']==POLICY
|
||||
result=dict(passed=all(checks.values()),checks=checks,full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False)
|
||||
Path('/out/sections-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"schema": "missioncore.offline-plan-bundle/v1",
|
||||
"root": "simulation/urban-plan-research",
|
||||
"files": {
|
||||
"audit_consensus.py": "consensus_pass/audit_consensus.py",
|
||||
"audit_norms.py": "norms_pass/audit_norms.py",
|
||||
"audit_sections.py": "sections_pass/audit_sections.py",
|
||||
"audit_transitions.py": "transitions_pass/audit_transitions.py",
|
||||
"consensus_profiles.py": "consensus_pass/consensus_profiles.py",
|
||||
"fit_scene.py": "full_plan/fit_scene.py",
|
||||
"gost_catalog.py": "norms_pass/gost_catalog.py",
|
||||
"image_profiles.py": "lines_pass/image_profiles.py",
|
||||
"interval_profiles.py": "intervals_pass/interval_profiles.py",
|
||||
"layer_common.py": "full_plan/layer_common.py",
|
||||
"line_reconstruction.py": "intervals_pass/line_reconstruction.py",
|
||||
"norm_profiles.py": "norms_pass/norm_profiles.py",
|
||||
"refine_consensus.py": "consensus_pass/refine_consensus.py",
|
||||
"refine_norms.py": "norms_pass/refine_norms.py",
|
||||
"refine_sections.py": "sections_pass/refine_sections.py",
|
||||
"refine_transitions.py": "transitions_pass/refine_transitions.py",
|
||||
"render_consensus.py": "consensus_pass/render_consensus.py",
|
||||
"render_norms.py": "norms_pass/render_norms.py",
|
||||
"render_plan.py": "continuation_pass/render_plan.py",
|
||||
"render_sections.py": "sections_pass/render_sections.py",
|
||||
"render_transitions.py": "transitions_pass/render_transitions.py",
|
||||
"section_profiles.py": "sections_pass/section_profiles.py",
|
||||
"test_consensus.py": "consensus_pass/test_consensus.py",
|
||||
"test_intervals.py": "intervals_pass/test_intervals.py",
|
||||
"test_lines.py": "lines_pass/test_lines.py",
|
||||
"test_norms.py": "norms_pass/test_norms.py",
|
||||
"test_sections.py": "sections_pass/test_sections.py",
|
||||
"test_transitions.py": "transitions_pass/test_transitions.py",
|
||||
"transition_profiles.py": "transitions_pass/transition_profiles.py"
|
||||
},
|
||||
"reference_qualification": "sections-pass-20261012",
|
||||
"source_snapshot": "0f1f127fb90a571e5e92",
|
||||
"source_sha256": {
|
||||
"audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2",
|
||||
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
|
||||
"audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7",
|
||||
"audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a",
|
||||
"consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091",
|
||||
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
|
||||
"gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537",
|
||||
"image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8",
|
||||
"interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345",
|
||||
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
|
||||
"line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738",
|
||||
"norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7",
|
||||
"refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36",
|
||||
"refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5",
|
||||
"refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3",
|
||||
"refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b",
|
||||
"render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682",
|
||||
"render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d",
|
||||
"render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064",
|
||||
"render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c",
|
||||
"render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d",
|
||||
"section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de",
|
||||
"test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7",
|
||||
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
|
||||
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a",
|
||||
"test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f",
|
||||
"test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f",
|
||||
"test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438",
|
||||
"transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e"
|
||||
},
|
||||
"external_review_font": {
|
||||
"name": "review-font.ttf",
|
||||
"sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9",
|
||||
"purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP"
|
||||
},
|
||||
"deployment": false
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
from pathlib import Path
|
||||
from functools import lru_cache
|
||||
import os,json,time,hashlib
|
||||
import numpy as np,cv2,shapely
|
||||
from PIL import Image
|
||||
from shapely.geometry import shape,mapping
|
||||
from layer_common import O,S,sample,parts
|
||||
from fit_scene import project
|
||||
from section_profiles import POLICY,VERSION,common_section,check_section,gap_geometry,gap_source,check_gap
|
||||
cv2.setNumThreads(3);started=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text())
|
||||
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
|
||||
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];low,high=z['bounds']
|
||||
protected=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'])
|
||||
@lru_cache(maxsize=4)
|
||||
def inputs(name):
|
||||
geom=geometry(name);rgb=np.asarray(Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB'))
|
||||
with np.load(Path('/ortho/evidence')/(name+'.normal.npz'))as z:vehicle=z['vehicle'].astype('float32')
|
||||
return geom,rgb,vehicle
|
||||
|
||||
@lru_cache(maxsize=90)
|
||||
def geometry(name):return dict(np.load(S/name/'top.geometry.npz'))
|
||||
|
||||
def sampler(name):
|
||||
def read(points):
|
||||
geom,rgb,vehicle=inputs(name);uv=project(points,geom).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5;chunks=max(1,int(np.ceil(len(uv)/20000)))
|
||||
colors=np.concatenate([cv2.remap(rgb,q[:,0,None],q[:,1,None],cv2.INTER_LINEAR).reshape(-1,3)for q in np.array_split(native,chunks)])
|
||||
veh=np.concatenate([cv2.remap(vehicle,q[:,0,None],q[:,1,None],cv2.INTER_LINEAR).ravel()for q in np.array_split(uv,chunks)])
|
||||
alpha=np.concatenate([cv2.remap(geom['alpha'].astype('float32'),q[:,0,None],q[:,1,None],cv2.INTER_LINEAR).ravel()for q in np.array_split(uv,chunks)])
|
||||
valid=(uv[:,0]>=0)&(uv[:,1]>=0)&(uv[:,0]<1199)&(uv[:,1]<1199)
|
||||
allowed=valid&(alpha>=.65)&(sample(labels,points,low,high)==1)&(veh<.20)&~shapely.contains_xy(protected,points[:,0],points[:,1])
|
||||
return colors,allowed
|
||||
return read
|
||||
original={f['id']:f for f in old['features']}
|
||||
linear={f['id']:shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties'].get('subtype')=='linear_marking'and f['geometry']['type']=='Polygon'}
|
||||
def covering(polygons):
|
||||
center=np.mean([np.array(p.centroid.coords[0])for p in polygons],axis=0);vertices=np.concatenate([np.asarray(p.exterior.coords)for p in polygons]);names=[]
|
||||
for tile in sorted(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center)):
|
||||
uv=project(vertices,geometry(tile['id']))
|
||||
if uv.min()>=20 and uv.max()<1180:names.append(tile['id'])
|
||||
if len(names)==2:break
|
||||
return names
|
||||
pairs=[]
|
||||
for sid,p in linear.items():
|
||||
for tid,q in linear.items():
|
||||
if sid==tid:continue
|
||||
section=common_section(p,q)
|
||||
if section is not None:pairs.append((sid,tid,section))
|
||||
pairs.sort(key=lambda x:(tuple(linear[x[0]].centroid.coords[0]),x[0],x[1]))
|
||||
proposals=[];diagnostics=[]
|
||||
for k,(sid,tid,section)in enumerate(pairs):
|
||||
names=covering([section['source'],section['target']]);kind,views,ridges=check_section(section,[sampler(n)for n in names])
|
||||
rec=dict(source_id=sid,target_id=tid,source_tiles=names,geometry=section['geometry'],views=views,ridges=ridges,kind=kind)
|
||||
diagnostics.append(rec)
|
||||
if kind:proposals.append({**rec,'cutter':section['cutter']})
|
||||
if k%50==0:print('PAIR',k,len(pairs),'CANDIDATES',len(proposals),flush=True)
|
||||
# Protect nominated keepers for this transaction. Multiple independent cuts on
|
||||
# the same source are unioned; no removed object can serve as evidence keeper.
|
||||
cuts={};keepers=set();accepted=[]
|
||||
for rec in sorted(proposals,key=lambda r:(r['kind']!='unsupported_offset_duplicate',max(v['source_support']for v in r['views']),-min(v['target_support']for v in r['views']),r['source_id'],r['target_id'])):
|
||||
sid,tid=rec['source_id'],rec['target_id']
|
||||
if sid in keepers or tid in cuts:continue
|
||||
prior=shapely.union_all(cuts.get(sid,[]));effective=linear[sid].intersection(rec['cutter']).difference(prior)
|
||||
if effective.area<.005:continue
|
||||
cuts.setdefault(sid,[]).append(rec['cutter']);keepers.add(tid)
|
||||
accepted.append({k:v for k,v in rec.items()if k!='cutter'}|dict(source_ids=[sid],output_ids=[tid],source_tile=rec['source_tiles'][0],bounds_xy=effective.union(linear[tid]).bounds,cut_geometry=mapping(rec['cutter']),removed_area_m2=effective.area))
|
||||
# A regular row nominates gaps only. Check the old vector's whole lateral
|
||||
# corridor for empty, visible asphalt. Real adjacent paint vetoes the cut.
|
||||
anchors={fid:f for fid,f in original.items()if fid in linear and f['properties'].get('line_kind')=='dashed'and f['properties'].get('dash_length_m',0)>1.45 and f['properties'].get('period_m')}
|
||||
gap_candidates=0
|
||||
for aid,a in anchors.items():
|
||||
for bid,b in anchors.items():
|
||||
if aid==bid or aid in cuts or bid in cuts:continue
|
||||
pa,pb=a['properties']['period_m'],b['properties']['period_m']
|
||||
if abs(pa-pb)>.30:continue
|
||||
gap=gap_geometry(linear[aid],linear[bid],(pa+pb)/2)
|
||||
if gap is None:continue
|
||||
for sid,p in linear.items():
|
||||
if sid in anchors or sid in keepers:continue
|
||||
cut=gap_source(p,gap)
|
||||
if cut is None:continue
|
||||
prior=shapely.union_all(cuts.get(sid,[]));effective=p.intersection(cut).difference(prior)
|
||||
if effective.area<.005:continue
|
||||
gap_candidates+=1;names=covering([linear[aid],linear[bid],p.intersection(cut)])
|
||||
okay,evidence=check_gap(p,gap,[sampler(n)for n in names]);diagnostics.append(dict(kind='gap-candidate',source_id=sid,anchor_ids=[aid,bid],source_tiles=names,accepted=okay,views=evidence))
|
||||
if not okay:continue
|
||||
cuts.setdefault(sid,[]).append(cut);keepers.update([aid,bid])
|
||||
accepted.append(dict(kind='confirmed_dash_gap',source_id=sid,target_id=aid,source_ids=[sid],output_ids=[aid,bid],anchor_ids=[aid,bid],source_tiles=names,source_tile=names[0],bounds_xy=effective.union(linear[aid]).union(linear[bid]).bounds,views=evidence,cut_geometry=mapping(cut),removed_area_m2=effective.area,period=gap['period'],gap_length=gap['hi']-gap['lo']))
|
||||
working={fid:f for fid,f in original.items()if fid not in cuts};replacements={}
|
||||
for sid,domains in cuts.items():
|
||||
cut=shapely.union_all(domains);p=shape(original[sid]['geometry']);remaining=p.difference(cut);ids=[]
|
||||
for part in parts(remaining):
|
||||
if part.area<=1e-9:continue
|
||||
fid='plan-'+hashlib.sha256((sid+part.wkt+VERSION).encode()).hexdigest()[:20]
|
||||
f={**original[sid],'id':fid,'geometry':mapping(part),'properties':{**original[sid]['properties'],'method':VERSION,'parent_id':sid,'operation':'preserved-outside-confirmed-sections'}}
|
||||
working[fid]=f;ids.append(fid)
|
||||
replacements[sid]=dict(output_ids=ids,cut_geometry=mapping(cut))
|
||||
for rec in accepted:rec['residual_ids']=replacements[rec['source_id']]['output_ids']
|
||||
result={**old,'features':list(working.values()),'section_refinement':VERSION}
|
||||
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'sections-rows.json').write_text(json.dumps(accepted,indent=2));(O/'sections-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'sections-replacements.json').write_text(json.dumps(replacements,indent=2))
|
||||
(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes())
|
||||
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(accepted),changed_objects=len(cuts),partial_objects=sum(bool(r['output_ids'])for r in replacements.values()),removed_objects=sum(not r['output_ids']for r in replacements.values()),duplicate_sections=sum(r['kind']!='confirmed_dash_gap'for r in accepted),confirmed_gap_sections=sum(r['kind']=='confirmed_dash_gap'for r in accepted),removed_area_m2=sum(r['removed_area_m2']for r in accepted),candidate_pairs=len(pairs),gap_candidates=gap_candidates,before_linear_objects=len(linear),after_linear_objects=sum(f['properties'].get('subtype')=='linear_marking'for f in working.values()),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
|
||||
(O/'sections-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
|
||||
@@ -0,0 +1,41 @@
|
||||
from pathlib import Path
|
||||
import os,json,shutil
|
||||
from datetime import datetime,timezone
|
||||
import numpy as np,shapely
|
||||
from PIL import Image,ImageDraw,ImageFont
|
||||
from shapely.geometry import shape
|
||||
from layer_common import O,S
|
||||
from fit_scene import project
|
||||
old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'sections-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23)
|
||||
for p in O.glob('rows-*.jpg'):
|
||||
h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name)
|
||||
def draw(im,g,features):
|
||||
im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200
|
||||
for f in features:
|
||||
if f['properties'].get('subtype')not in ['linear_marking','crosswalk']:continue
|
||||
for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2)))
|
||||
return im
|
||||
frames=[];manifest=[];loaded={}
|
||||
for gi,rec in enumerate(groups):
|
||||
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id']
|
||||
if name not in loaded:
|
||||
g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))}
|
||||
g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame)
|
||||
for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]):
|
||||
frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640')
|
||||
fn='rows-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects']))
|
||||
for start in range(0,len(frames),4):
|
||||
part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white')
|
||||
for k,im in enumerate(part):sheet.paste(im,(0,k*655))
|
||||
sheet.save(O/('rows-proof-%03d.jpg'%(start//4+1)),quality=94)
|
||||
(O/'rows-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True)
|
||||
# Revisit every short-dash family shown in the prior delivery, using its stored
|
||||
# bounds only for review framing; these bounds never enter the detector.
|
||||
references=json.loads(Path('/families/line-families.json').read_text());ref_manifest=[]
|
||||
for gi,rec in enumerate(references):
|
||||
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200
|
||||
uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*8/60,raw.width*18/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(2400,855),'white');d=ImageDraw.Draw(frame)
|
||||
for j,(im,label)in enumerate([(raw,'Гауссы'),(draw(raw,g,old['features']),'До'),(draw(raw,g,new['features']),'После')]):
|
||||
frame.paste(im.crop(bbox).resize((800,800),Image.Resampling.LANCZOS),(800*j,55));d.text((800*j+10,12),label,font=font,fill='#263640')
|
||||
fn='reference-%02d.jpg'%gi;frame.save(O/fn,quality=96);ref_manifest.append(dict(group=gi,file=fn,source_tile=name,bounds_source='prior line-families.json; review framing only'))
|
||||
(O/'reference-visual-manifest.json').write_text(json.dumps(ref_manifest,indent=2))
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Bounded paint-object surgery; geometry proposes, two Gaussian views decide.
|
||||
|
||||
Only common longitudinal sections are considered duplicates. The remainder
|
||||
retains its original boundary. Periodic anchors may also nominate a gap, but
|
||||
only observed empty asphalt in both views permits clearing old vector paint.
|
||||
"""
|
||||
import numpy as np
|
||||
from interval_profiles import rectangle,strip
|
||||
from line_reconstruction import observation
|
||||
from consensus_profiles import POLICY as CONSENSUS_POLICY,observe_track,decision,shared_ridge
|
||||
|
||||
POLICY={**CONSENSUS_POLICY,'min_common_length_m':.60,'min_source_length_m':.60,
|
||||
'max_source_length_m':70.,'max_source_width_m':.60,'min_anchor_length_m':1.45,
|
||||
'max_anchor_width_m':.40,'max_gap_axis_angle_deg':1.5,'max_gap_anchor_offset_m':.12,
|
||||
'max_gap_source_offset_m':.20,'max_period_error_m':.30,'gap_edge_margin_m':.12,
|
||||
'min_gap_core_m':.30,'max_gap_q90':8.,'min_gap_dark_fraction':.90}
|
||||
POLICY.pop('min_overlap') # A common interval replaces the whole-object overlap gate.
|
||||
VERSION='two-view-bounded-sections-v1'
|
||||
|
||||
def obs(poly):return observation(np.asarray(poly.exterior.coords)[:,:2],'vector')
|
||||
|
||||
def common_section(source,target):
|
||||
a,b=obs(source),obs(target)
|
||||
if not(POLICY['min_source_length_m']<a['L']<POLICY['max_source_length_m'] and
|
||||
POLICY['min_anchor_length_m']<b['L']<70 and a['W']<=POLICY['max_source_width_m'] and b['W']<=POLICY['max_anchor_width_m']):return None
|
||||
u=a['axis'].astype(float);u/=np.linalg.norm(u);n=np.array([-u[1],u[0]])
|
||||
if abs(u@b['axis'])<np.cos(np.deg2rad(POLICY['max_angle_deg'])):return None
|
||||
lateral=float(abs((b['center']-a['center'])@n))
|
||||
if lateral>POLICY['max_lateral_m']:return None
|
||||
tt=(np.asarray(target.exterior.coords)[:,:2]-a['center'])@u
|
||||
ss=(np.asarray(source.exterior.coords)[:,:2]-a['center'])@u
|
||||
lo=max(float(ss.min()),float(tt.min()));hi=min(float(ss.max()),float(tt.max()))
|
||||
if hi-lo<POLICY['min_common_length_m']:return None
|
||||
cutter=rectangle(a['center'],u,lo,hi,4.)
|
||||
p,q=source.intersection(cutter),target.intersection(cutter)
|
||||
if p.geom_type!='Polygon' or q.geom_type!='Polygon':return None
|
||||
contained=p.intersection(q).area/max(p.area,1e-9)
|
||||
return dict(source=p,target=q,cutter=cutter,origin=a['center'],axis=u,lo=lo,hi=hi,
|
||||
geometry=dict(lateral_m=lateral,overlap_fraction=float((hi-lo)/a['L']),contained_fraction=float(contained)))
|
||||
|
||||
def check_section(section,samplers):
|
||||
p,q=section['source'],section['target']
|
||||
views=[(observe_track(p,read),observe_track(q,read))for read in samplers]
|
||||
ridges=[shared_ridge(p,q,read)for read in samplers]
|
||||
kind,evidence=decision(section['geometry'],views,ridges)
|
||||
return kind,evidence,ridges
|
||||
|
||||
def gap_geometry(left,right,period):
|
||||
a,b=obs(left),obs(right);u=a['axis'].astype(float);u/=np.linalg.norm(u);n=np.array([-u[1],u[0]])
|
||||
if min(a['L'],b['L'])<=1.45 or max(a['L'],b['L'])>=10.5 or max(a['W'],b['W'])>.4:return None
|
||||
if abs(u@b['axis'])<np.cos(np.deg2rad(POLICY['max_gap_axis_angle_deg'])):return None
|
||||
d=b['center']-a['center'];along=float(d@u)
|
||||
if along<=0 or abs(along-period)>POLICY['max_period_error_m'] or abs(d@n)>POLICY['max_gap_anchor_offset_m']:return None
|
||||
if abs(a['L']-b['L'])>max(.35,.2*a['L']):return None
|
||||
tt=(np.asarray(right.exterior.coords)[:,:2]-a['center'])@u
|
||||
lo=float(a['L']/2);hi=float(tt.min())
|
||||
if hi-lo<2*POLICY['gap_edge_margin_m']+POLICY['min_gap_core_m']:return None
|
||||
return dict(origin=a['center'],axis=u,lo=lo,hi=hi,left=left,right=right,period=float(period))
|
||||
|
||||
def gap_source(source,gap):
|
||||
a=obs(source);o,u=gap['origin'],gap['axis'];n=np.array([-u[1],u[0]])
|
||||
if a['W']>.6 or abs(a['axis']@u)<np.cos(np.deg2rad(POLICY['max_angle_deg'])):return None
|
||||
if abs((a['center']-o)@n)>POLICY['max_gap_source_offset_m']:return None
|
||||
cut=rectangle(o,u,gap['lo'],gap['hi'],4.)
|
||||
part=source.intersection(cut)
|
||||
if part.is_empty or part.area<.01:return None
|
||||
return cut
|
||||
|
||||
def check_gap(source,gap,samplers):
|
||||
records=[];o,u=gap['origin'],gap['axis'];n=np.array([-u[1],u[0]])
|
||||
vertices=np.asarray(source.exterior.coords)[:,:2];normal=(vertices-o)@n
|
||||
ns=np.arange(-.8,.801,.025);ts=np.arange(gap['lo']+POLICY['gap_edge_margin_m'],gap['hi']-POLICY['gap_edge_margin_m'],.025)
|
||||
corridor=(ns>=min(-.04,float(normal.min())))&(ns<=max(.04,float(normal.max())))
|
||||
for read in samplers:
|
||||
anchors=[]
|
||||
for p in [gap['left'],gap['right']]:
|
||||
q=observe_track(p,read);s,v=q['signal'],q['valid'];level=float(np.median(s[v]))if v.any()else 0
|
||||
anchors.append(dict(valid=float(v.mean()),support=float(((s>max(15,.35*level))&v).mean()),median=level))
|
||||
c,allowed=strip(o,u,ts,ns,read);signal=c[:,corridor].max(1);valid=allowed[:,corridor].all(1)
|
||||
records.append(dict(anchors=anchors,valid=float(valid.mean()),dark_fraction=float(((signal<15)&valid).mean()),q90=float(np.quantile(signal[valid],.90))if valid.any()else 999.))
|
||||
okay=len(records)>=POLICY['min_views'] and all(r['valid']>=POLICY['min_valid'] and r['dark_fraction']>=POLICY['min_gap_dark_fraction'] and r['q90']<POLICY['max_gap_q90'] and all(a['valid']>=.95 and a['support']>=.85 and a['median']>=22 for a in r['anchors'])for r in records)
|
||||
return bool(okay),records
|
||||
@@ -0,0 +1,67 @@
|
||||
import json,runpy,numpy as np,shapely
|
||||
from shapely.geometry import Polygon
|
||||
from shapely.affinity import rotate,translate
|
||||
from interval_profiles import rectangle
|
||||
from section_profiles import common_section,check_section,gap_geometry,gap_source,check_gap
|
||||
prior=runpy.run_path('/candidate/test_consensus.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()}
|
||||
o=np.array([0.,0.]);u=np.array([1.,0.])
|
||||
a=rectangle(o,u,-3,9,.15,.15);b=rectangle(o,u,0,6,.15)
|
||||
def one(xy):
|
||||
v=65+140*np.exp(-.5*(xy[:,1]/.085)**2)
|
||||
return np.repeat(v[:,None],3,1).astype('uint8'),np.ones(len(xy),bool)
|
||||
sec=common_section(a,b);kind,_,_=check_section(sec,[one,one])
|
||||
checks['partial_overlap_accepted']=kind=='one_ridge_two_vectors'
|
||||
res=a.difference(sec['cutter'])
|
||||
checks['both_outside_tails_preserved']=abs(res.area-a.area/2)<1e-6 and len(res.geoms)==2
|
||||
checks['keeper_geometry_unchanged']=b.equals(sec['target'])
|
||||
checks['no_cut_outside_common_span']=sec['cutter'].intersection(a).difference(rectangle(o,u,0,6,4)).area<1e-8
|
||||
checks['single_view_retains_partial']=check_section(sec,[one])[0]is None
|
||||
def hidden(xy):
|
||||
rgb,v=one(xy);return rgb,np.zeros_like(v)
|
||||
checks['unknown_view_retains_partial']=check_section(sec,[one,hidden])[0]is None
|
||||
def twin(xy):
|
||||
v=65+130*np.exp(-.5*(xy[:,1]/.028)**2)+110*np.exp(-.5*((xy[:,1]-.2)/.028)**2)
|
||||
return np.repeat(v[:,None],3,1).astype('uint8'),np.ones(len(xy),bool)
|
||||
c=rectangle(o,u,-3,9,.10,.2);d=rectangle(o,u,0,6,.10)
|
||||
checks['real_neighbor_survives_partial']=check_section(common_section(c,d),[twin,twin])[0]is None
|
||||
checks['short_common_interval_rejected']=common_section(a,rectangle(o,u,8.6,12,.15))is None
|
||||
checks['crossing_line_not_partial_duplicate']=common_section(a,rectangle(o,np.array([0.,1.]),0,6,.15))is None
|
||||
checks['adjacent_lane_not_partial_duplicate']=common_section(a,rectangle(o,u,0,6,.15,3))is None
|
||||
inside=rectangle(np.array([125.123,-71.456]),u,0,3,.15);outside=rectangle(np.array([125.123,-71.456]),u,-1,4,.15)
|
||||
checks['fully_covered_source_has_no_roundoff_tail']=inside.difference(common_section(inside,outside)['cutter']).area<1e-9
|
||||
# Rotating and translating the map must not alter the decision.
|
||||
theta=.87;rot=np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]]);shift=np.array([125.,-71.])
|
||||
ar=Polygon(np.asarray(a.exterior.coords)@rot.T+shift);br=Polygon(np.asarray(b.exterior.coords)@rot.T+shift)
|
||||
read=lambda xy:one((xy-shift)@rot)
|
||||
checks['partial_rigid_transform_invariant']=check_section(common_section(ar,br),[read,read])[0]==kind
|
||||
# Two observed long strokes nominate their intervening gap.
|
||||
left=rectangle(o,u,0,3,.15);right=rectangle(o,u,4,7,.15);source=rectangle(o,u,0,7,.15)
|
||||
gap=gap_geometry(left,right,4.)
|
||||
def dashed(xy):
|
||||
on=((xy[:,0]>=0)&(xy[:,0]<=3))|((xy[:,0]>=4)&(xy[:,0]<=7))
|
||||
v=65+140*np.exp(-.5*(xy[:,1]/.035)**2)*on
|
||||
return np.repeat(v[:,None],3,1).astype('uint8'),np.ones(len(xy),bool)
|
||||
checks['observed_dark_gap_cleared']=check_gap(source,gap,[dashed,dashed])[0]
|
||||
checks['solid_paint_not_cleared']=not check_gap(source,gap,[one,one])[0]
|
||||
checks['gap_views_must_agree']=not check_gap(source,gap,[dashed,one])[0]
|
||||
checks['gap_needs_two_views']=not check_gap(source,gap,[dashed])[0]
|
||||
checks['unknown_gap_not_cleared']=not check_gap(source,gap,[dashed,hidden])[0]
|
||||
checks['different_rhythm_no_gap']=gap_geometry(left,right,5.)is None
|
||||
checks['neighbor_row_no_gap']=gap_geometry(left,rectangle(o,u,4,7,.15,.4),4.)is None
|
||||
checks['crossing_source_gap_protected']=gap_source(rectangle(o,np.array([0.,1.]),0,7,.15),gap)is None
|
||||
checks['far_parallel_gap_protected']=gap_source(rectangle(o,u,0,7,.15,.4),gap)is None
|
||||
cut=gap_source(source,gap);remaining=source.difference(cut)
|
||||
checks['gap_cut_keeps_anchor_spans']=remaining.equals(left.union(right))
|
||||
def weak(xy):
|
||||
rgb,v=dashed(xy);inside=(xy[:,0]>3)&(xy[:,0]<4);extra=12*np.exp(-.5*(xy[:,1]/.035)**2)*inside
|
||||
return (rgb+extra[:,None]).astype('uint8'),v
|
||||
checks['weak_paint_in_gap_protected']=not check_gap(source,gap,[weak,weak])[0]
|
||||
def hidden_gap(xy):
|
||||
rgb,v=dashed(xy);v[(xy[:,0]>3.4)&(xy[:,0]<3.7)]=False;return rgb,v
|
||||
checks['local_occlusion_not_dark_gap']=not check_gap(source,gap,[hidden_gap,hidden_gap])[0]
|
||||
# Shapely preserves/interpolates the old 3D boundary through a 2D cutter.
|
||||
a3=Polygon([(x,y,x*.1+2)for x,y in a.exterior.coords]);r3=a3.difference(sec['cutter']);xyz=shapely.get_coordinates(r3,include_z=True)
|
||||
checks['residual_xyz_finite']=bool(np.isfinite(xyz).all())
|
||||
checks['residual_height_interpolated']=bool(np.allclose(xyz[:,2],xyz[:,0]*.1+2))
|
||||
checks['area_partition_exact']=abs(a.area-res.area-a.intersection(sec['cutter']).area)<1e-9
|
||||
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/sections-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
|
||||
Reference in New Issue
Block a user