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:
DCCONSTRUCTIONS
2026-10-29 09:10:00 +03:00
parent 5d56237124
commit 69dc566665
611 changed files with 52016 additions and 28 deletions
@@ -0,0 +1,84 @@
Continuous row assembly from Gaussian evidence
==============================================
This research pass consumes the accepted sections-pass-20261012 map. It joins
nearby non-dashed linear fragments using OpenCV Huber fitting, Shapely unions
and Gaussian image profiles. One frozen source and one POLICY apply to every
scene. There are no address branches, coordinate exceptions or manual ROIs.
Geometry and image decisions
----------------------------
Candidate fragments are 0.60--90 m long and 0.045--0.35 m wide. End separation
is at most 0.55 m, overlap at most 0.20 m, direction difference at most 2 degrees,
lateral offset at most 0.09 m, width ratio at most 1.8. A whole-chain Huber axis
is fitted from all original source centerline samples. Maximum displacement
is 0.065 m. A growing chain never uses a previous fitted line as its raw input.
The geometric cap is 24 fragments and 90 m per chain.
Two spatially continuous evidence views are assembled from overlapping cached
Gaussian renders. For each longitudinal station, the two nearest footprints
covering the entire +/-0.85 m transverse strip with 20-pixel margin are selected
before inspecting paint. Stable geometric ownership never selects a brighter
view. Each rank uses a different tile at that station. Missing coverage stays
unknown. Alpha >=0.65, road label, vehicle score <0.20 and protected marking masks
control sample validity. Both views derive from the same Gaussian reconstruction;
they are not independent surveys or two new camera captures.
Profiles sampled every 0.025 m require median local contrast >=22. The bright
cut is max(15, 0.35*median); whole-row validity >=95%, bright support >=85%, and
no visible dark run longer than 0.20 m. Median absolute ridge offset <=0.065 m
and q90 <=0.10 m prevent snapping to an adjacent line. Each joint, including
0.10 m context at both ends, must have >=95% valid and >=90% bright samples in
both views. Existing known dashes, symbols and crosswalks are protected.
Two explicit operations exist:
* Whole-row fit: every whole-row gate passes in both evidence views. The
original fragment chain becomes one straight, constant-width rectangle.
* Preserved-contour union: at least one whole-row view passes, both views pass
all local joint gates and no observed dark/offset evidence contradicts the
chain. Shapely unions the exact original XY polygons and bounded joint
patches. Outside those patches the old XY boundary remains exact. This
permits joining without redrawing an outer section missing its second view.
No changed joint is authorized by a single view. Neither operation joins an
observed dash gap, an occluded joint, a known dashed object or a protected
symbol. Global fit is not used as a fallback for insufficient coverage. Output
Z uses the existing Gaussian-derived height field, as in previous row passes;
exact preservation outside joint patches refers specifically to XY geometry.
All unselected feature objects and the existing crosswalk audit remain identical.
Qualification
-------------
Canonical module: simulation/urban-plan-research/rows_pass/bundle.json.
New modules: row_profiles.py, row_evidence.py, refine_rows.py, audit_rows.py,
test_rows.py, render_rows.py. All unchanged modules are reused by hash.
Qualification: .runtime/simulation-qualifications/rows-pass-20261012/operator.
Worker path: C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/rows-pass-20261012.
All computation, tests and image rendering run on Worker006 in pinned image
sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0.
The recorded-job queue reserves simulation. Container limits: 4 CPUs, 20 GiB,
1 GiB tmpfs, read-only root, no network, 1800-second stage timeout. Cleanup
confirmation precedes reservation release. Mac handles text, orchestration,
file copies, hashes and viewing only.
The replay folder contains runner, collector, verifier, scene registry and
frozen-source manifest. Assemble the canonical bundle and pinned external
review-font.ttf, set URBAN_SOURCE_BUNDLE to that directory, run test_rows once,
then refine_rows, audit_rows, render_rows and render_plan sequentially for
each scene. The existing canonical repository environment, private Gaussian
caches and SSH setup are required. The ZIP provides flat Python sources but
omits private inputs and the externally pinned review font.
Reports distinguish the two operations and candidates rejected by geometry,
protected objects, novel neighbor overlap or image evidence. Audits check
original source membership, unchanged features, exact external XY preservation
for local unions, bounded whole-row fits, finite XYZ, protected paint and
per-joint evidence. Input hashes, baseline hashes, source hashes, identical
policy and released resources are verified across all three scenes.
This is not complete map acceptance: missing symbols, false solid continuations,
curved rows, unobserved joints and metric ground-truth accuracy remain separate
work. Standard dimension assessments are inherited unchanged; there is no new
GOST compliance conclusion. No live 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 row_profiles import POLICY,VERSION,fit_chain
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/rows-rows.json').read_text());removed=set(json.loads(Path('/out/rows-replacements.json').read_text())['removed_ids']);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['unchanged_features_identical']=all(features.get(fid)==f for fid,f in original.items()if fid not in removed)
checks['only_nondashed_linear_replaced']=all(original[fid]['properties'].get('subtype')=='linear_marking'and original[fid]['properties'].get('line_kind')!='dashed'for fid in removed)
checks['every_source_traced']=removed==set(fid for r in rows for fid in r['source_ids'])
checks['disjoint_source_groups']=sum(len(r['source_ids'])for r in rows)==len(removed)
checks['new_outputs_traced']=set(features)-set(original)==set(fid for r in rows for fid in r['output_ids'])
checks['objects_count_closes']=len(features)==len(original)-len(removed)+len(rows)
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'])
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' or f['properties'].get('line_kind')=='dashed')])
checks['protected_markings_avoided']=all(shape(features[r['output_ids'][0]]['geometry']).intersection(protected).area<=.005 for r in rows)
def geometry_check(r):
inputs=[shapely.force_2d(shape(original[fid]['geometry']))for fid in r['source_ids']];rec=fit_chain(inputs)
if rec is None or rec['max_axis_displacement_m']>POLICY['max_axis_displacement_m']:return False
p=shapely.force_2d(shape(features[r['output_ids'][0]]['geometry']))
if r['kind']=='whole-row-fit':return p.symmetric_difference(rec['polygon']).area<1e-8
before=shapely.union_all(inputs);domain=shape(r['edit_domain'])
return r['kind']=='preserved-contour-union'and p.symmetric_difference(shapely.union_all([before,domain])).area<1e-8 and p.difference(domain).symmetric_difference(before.difference(domain)).area<1e-8
checks['every_chain_geometry_bounded']=all(geometry_check(r)for r in rows)
def image_evidence(r):
if len(r['views'])!=2 or len(set(r['source_tiles']))<2:return False
def local(v):return v['median_contrast']>=22 and v['longest_visible_dark_run_m']<=.20 and v['ridge_median_offset_m']<=.065 and v['ridge_q90_offset_m']<=.10 and all(s['valid']>=.95 and s['support']>=.9 for s in v['seams'])
full=[local(v)and v['valid']>=.95 and v['support']>=.85 for v in r['views']]
return all(local(v)for v in r['views'])and (all(full)if r['kind']=='whole-row-fit'else any(full))
checks['two_evidence_mosaics_pass_every_seam']=all(image_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['row_refinement']==VERSION and json.loads(Path('/out/rows-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/rows-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,86 @@
{
"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_rows.py": "rows_pass/audit_rows.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_rows.py": "rows_pass/refine_rows.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_rows.py": "rows_pass/render_rows.py",
"render_sections.py": "sections_pass/render_sections.py",
"render_transitions.py": "transitions_pass/render_transitions.py",
"row_evidence.py": "rows_pass/row_evidence.py",
"row_profiles.py": "rows_pass/row_profiles.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_rows.py": "rows_pass/test_rows.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": "rows-pass-20261012",
"source_snapshot": "4e80bce03fad11a0c32e",
"source_sha256": {
"audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2",
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
"audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01",
"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_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8",
"refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3",
"refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b",
"render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682",
"render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d",
"render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064",
"render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e",
"render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c",
"render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d",
"row_evidence.py": "fc6a390faa97fb4cf6213dd6b841a94de9c6e78e0b68e6715aa06f2de565f28c",
"row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df",
"section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de",
"test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7",
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a",
"test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f",
"test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449",
"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,54 @@
from pathlib import Path
import os,json,time,hashlib,numpy as np,cv2,shapely
from shapely.geometry import shape
from shapely.ops import transform
from layer_common import O,S,sample,feature
from row_profiles import POLICY,VERSION,pair,fit_chain,check_chain
from row_evidence import GaussianViews
cv2.setNumThreads(3);started=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());original={f['id']:f for f in old['features']}
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds']
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
# A known dashed feature is an explicit transition barrier. Existing crosswalks
# and symbols are also protected, as in prior passes.
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' or f['properties'].get('line_kind')=='dashed')])
linear={f['id']:shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties'].get('subtype')=='linear_marking'and f['properties'].get('line_kind')!='dashed'and f['geometry']['type']=='Polygon'}
views=GaussianViews(tiles,labels,low,high,protected);current={fid:dict(polygon=p,source_ids=[fid])for fid,p in linear.items()};considered=set();history=[];diagnostics=[]
def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
while True:
candidates=[];entries=sorted(current.items())
for i,(aid,a)in enumerate(entries):
for bid,b in entries[:i]:
identity=tuple(sorted(a['source_ids']+b['source_ids']))
if identity in considered or a['polygon'].distance(b['polygon'])>.56:continue
candidate=pair(a['polygon'],b['polygon'])
if candidate is not None:candidates.append((abs(candidate['gap_m']),identity,aid,bid))
accepted=False
for _,identity,aid,bid in sorted(candidates):
considered.add(identity);rec=fit_chain([linear[fid]for fid in identity])
if rec is None:diagnostics.append(dict(source_ids=identity,reason='whole-chain-geometry'));continue
p=rec['polygon']
if p.intersection(protected).area>.005:diagnostics.append(dict(source_ids=identity,reason='protected-marking'));continue
# Do not make a new overlap with an unselected line. Old overlaps can
# remain for a later evidence-based cleanup; this pass cannot grow them.
before=shapely.union_all([linear[fid]for fid in identity]);novel=p.difference(before)
if any(novel.intersection(q).area>.005 for fid,q in linear.items()if fid not in identity):diagnostics.append(dict(source_ids=identity,reason='new-neighbor-overlap'));continue
readers,used=views.readers(rec['origin'],rec['axis']);okay,ev=check_chain(rec,readers)
diagnostics.append(dict(source_ids=identity,reason='accepted'if okay else 'image-veto',views=ev,source_views=used))
if not okay:continue
p=rec['output_polygon'];novel=p.difference(before)
if p.intersection(protected).area>.005 or any(novel.intersection(q).area>.005 for fid,q in linear.items()if fid not in identity):continue
fid='chain-'+hashlib.sha256('|'.join(identity).encode()).hexdigest()[:20]
current.pop(aid);current.pop(bid);current[fid]=dict(polygon=p,source_ids=list(identity),record=rec,views=ev,source_views=used)
history.append(dict(source_ids=list(identity),chain_id=fid));accepted=True;print('JOIN',len(history),'FRAGMENTS',len(identity),'LENGTH',round(rec['length'],2),flush=True);break
if not accepted:break
if len(history)>1000:raise RuntimeError('Unbounded chain growth')
removed=set();generated=[];rows=[]
for fid,g in current.items():
if len(g['source_ids'])<2:continue
rec=g['record'];ids=g['source_ids'];p=g['polygon'];source_tiles=sorted(set(g['source_views'][0])|set(g['source_views'][1]));removed.update(ids)
f=feature(lift(p),'road_marking',subtype='linear_marking',line_kind='solid',method=VERSION,source_ids=ids,source_tiles=source_tiles,template_width_m=rec['width'],whole_chain_refit=True,assembly_operation=rec['operation'],standard_compliance='not_assessed');generated.append(f)
rows.append(dict(kind=rec['operation'],edit_domain=shapely.geometry.mapping(rec['edit_domain']),source_ids=ids,output_ids=[f['id']],source_tile=source_tiles[0],source_tiles=source_tiles,source_views=g['source_views'],bounds_xy=p.bounds,axis=rec['axis'].tolist(),origin=rec['origin'].tolist(),length_m=rec['length'],width_m=rec['width'],max_axis_displacement_m=rec['max_axis_displacement_m'],seams=rec['seams'],views=g['views'],added_area_m2=p.difference(shapely.union_all([linear[i]for i in ids])).area))
result={**old,'features':[f for f in old['features']if f['id']not in removed]+generated,'row_refinement':VERSION}
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'rows-rows.json').write_text(json.dumps(rows,indent=2));(O/'rows-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'rows-replacements.json').write_text(json.dumps(dict(removed_ids=sorted(removed)),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(rows),merged_fragments=len(removed),final_rows=len(rows),accepted_joins=len(history),whole_row_fits=sum(r['kind']=='whole-row-fit'for r in rows),preserved_contour_unions=sum(r['kind']=='preserved-contour-union'for r in rows),candidate_chains=len(considered),before_linear_objects=sum(f['properties'].get('subtype')=='linear_marking'for f in old['features']),after_linear_objects=sum(f['properties'].get('subtype')=='linear_marking'for f in result['features']),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
(O/'rows-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/'rows-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,56 @@
"""Geometry-only ownership for two continuous Gaussian evidence mosaics."""
from pathlib import Path
from functools import lru_cache
import numpy as np,cv2,shapely
from PIL import Image
from fit_scene import project
from layer_common import S,sample
from row_profiles import POLICY
def choose_owners(distances,coverage):
# Stable order is geometry then tile index, never paint intensity/confidence.
if distances.shape[1]==0:return np.full((len(distances),2),-1,dtype=int)
order=np.argsort(np.where(coverage,distances,np.inf),axis=1,kind='stable')[:,:2]
if order.shape[1]<2:order=np.pad(order,((0,0),(0,2-order.shape[1])),constant_values=-1)
for j in range(2):
okay=(order[:,j]>=0)&coverage[np.arange(len(order)),np.maximum(order[:,j],0)]
order[~okay,j]=-1
return order
class GaussianViews:
def __init__(self,tiles,labels,low,high,protected):
self.tiles=tiles;self.labels=labels;self.low=low;self.high=high;self.protected=protected
self.centers=np.array([np.mean(t['bounds_xy'],axis=0)for t in tiles])
@lru_cache(maxsize=90)
def geometry(self,name):return dict(np.load(S/name/'top.geometry.npz'))
@lru_cache(maxsize=4)
def inputs(self,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 rgb,vehicle
def readers(self,origin,axis):
o=np.asarray(origin);u=np.asarray(axis);n=np.array([-u[1],u[0]]);used=[{},{}];cache={}
def ownership(points):
ts,inverse=np.unique(np.round((points-o)@u,6),return_inverse=True)
key=ts.tobytes()
if key not in cache:
centers=o+ts[:,None]*u;distance=np.linalg.norm(centers[:,None,:]-self.centers[None,:,:],axis=2);coverage=np.zeros(distance.shape,bool)
for i,tile in enumerate(self.tiles):
# Require the whole transverse evidence strip, not only its
# center, to fit inside each selected image footprint.
a=project(centers-POLICY['coverage_half_width_m']*n,self.geometry(tile['id']));b=project(centers+POLICY['coverage_half_width_m']*n,self.geometry(tile['id']))
uv=np.concatenate([a,b],axis=1);m=POLICY['coverage_margin_px'];coverage[:,i]=(uv.min(1)>=m)&(uv.max(1)<1200-m)
cache[key]=choose_owners(distance,coverage)
return cache[key][inverse]
def reader(rank):
def read(points):
owners=ownership(points)[:,rank];colors=np.zeros((len(points),3),'uint8');allowed=np.zeros(len(points),bool)
for i in np.unique(owners):
if i<0:continue
select=np.flatnonzero(owners==i);xy=points[select];name=self.tiles[i]['id'];used[rank][name]=used[rank].get(name,0)+len(select);g=self.geometry(name);rgb,vehicle=self.inputs(name)
uv=project(xy,g).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5
def remap(a,q):return np.concatenate([cv2.remap(a,part[:,0,None],part[:,1,None],cv2.INTER_LINEAR).reshape(len(part),-1)for part in np.array_split(q,max(1,int(np.ceil(len(q)/20000))))])
colors[select]=remap(rgb,native);veh=remap(vehicle,uv).ravel();alpha=remap(g['alpha'].astype('float32'),uv).ravel()
allowed[select]=(alpha>=.65)&(sample(self.labels,xy,self.low,self.high)==1)&(veh<.20)&~shapely.contains_xy(self.protected,xy[:,0],xy[:,1])
return colors,allowed
return read
return [reader(0),reader(1)],used
@@ -0,0 +1,85 @@
"""Whole-chain straight line fitting and two-view validation of observed paint.
OpenCV Huber fitting regularizes a chain only within a bounded displacement.
Every growing chain is refit from its original fragments, never from a previous
fit. Visible dark gaps and dashed features are barriers, not missing paint.
"""
import numpy as np,cv2,shapely
from scipy.signal import find_peaks
from interval_profiles import rectangle,strip,runs
from line_reconstruction import observation
POLICY=dict(min_length_m=.60,max_length_m=90.,max_width_m=.35,min_width_m=.045,
max_join_gap_m=.55,max_overlap_m=.20,max_angle_deg=2.,max_lateral_m=.09,
max_width_ratio=1.8,max_axis_displacement_m=.065,min_valid=.95,
min_paint_support=.85,min_median_contrast=22.,max_visible_dark_run_m=.20,
max_ridge_median_offset_m=.065,max_ridge_q90_offset_m=.10,
min_seam_support=.90,min_seam_valid=.95,min_views=2,
step_m=.025,max_chain_fragments=24,coverage_margin_px=20.,coverage_half_width_m=.85,joint_padding_m=.10)
VERSION='two-view-continuous-row-v1'
def obs(p):return observation(np.asarray(p.exterior.coords)[:,:2],'source')
def pair(a,b):
x,y=obs(a),obs(b)
if min(x['L'],y['L'])<POLICY['min_length_m'] or max(x['L'],y['L'])>POLICY['max_length_m']:return None
if min(x['W'],y['W'])<POLICY['min_width_m'] or max(x['W'],y['W'])>POLICY['max_width_m']:return None
if max(x['W'],y['W'])/min(x['W'],y['W'])>POLICY['max_width_ratio']:return None
if abs(x['axis']@y['axis'])<np.cos(np.deg2rad(POLICY['max_angle_deg'])):return None
u=x['axis'];n=np.array([-u[1],u[0]]);d=y['center']-x['center']
if abs(d@n)>POLICY['max_lateral_m']:return None
ranges=sorted([(float(((np.asarray(p.exterior.coords)[:,:2]-x['center'])@u).min()),float(((np.asarray(p.exterior.coords)[:,:2]-x['center'])@u).max()))for p in [a,b]])
gap=ranges[1][0]-ranges[0][1]
if gap<-POLICY['max_overlap_m'] or gap>POLICY['max_join_gap_m']:return None
return dict(gap_m=float(gap))
def fit_chain(polygons):
if len(polygons)<2 or len(polygons)>POLICY['max_chain_fragments']:return None
observations=[obs(p)for p in polygons]
if min(x['L']for x in observations)<POLICY['min_length_m']:return None
if min(x['W']for x in observations)<POLICY['min_width_m'] or max(x['W']for x in observations)>POLICY['max_width_m']:return None
if max(x['W']for x in observations)/min(x['W']for x in observations)>POLICY['max_width_ratio']:return None
points=np.concatenate([x['center']+np.linspace(-x['L']/2,x['L']/2,max(3,int(x['L']/.25)))[:,None]*x['axis']for x in observations])
fit=cv2.fitLine(points.astype('float32'),cv2.DIST_HUBER,0,.00001,.00001).ravel();u=fit[:2].astype(float);u/=np.linalg.norm(u);u*=1 if u[0]>=0 else -1;o=fit[2:].astype(float);n=np.array([-u[1],u[0]])
displacement=float(abs((points-o)@n).max())
if displacement>POLICY['max_axis_displacement_m']:return None
if any(abs(x['axis']@u)<np.cos(np.deg2rad(POLICY['max_angle_deg']))for x in observations):return None
ranges=sorted([(float(((np.asarray(p.exterior.coords)[:,:2]-o)@u).min()),float(((np.asarray(p.exterior.coords)[:,:2]-o)@u).max()))for p in polygons]);lo=min(x[0]for x in ranges);hi=max(x[1]for x in ranges)
if hi-lo>POLICY['max_length_m']:return None
intervals=[list(ranges[0])];seams=[]
for a,b in ranges[1:]:
gap=a-intervals[-1][1]
if gap>POLICY['max_join_gap_m'] or gap<-POLICY['max_overlap_m']:return None
seams.append((min(a,intervals[-1][1]),max(a,intervals[-1][1])))
intervals[-1][1]=max(b,intervals[-1][1])
widths=np.array([x['W']for x in observations]);lengths=np.array([x['L']for x in observations]);order=np.argsort(widths);width=float(widths[order[np.searchsorted(np.cumsum(lengths[order]),lengths.sum()/2)]])
p=rectangle(o,u,lo,hi,width)
return dict(polygon=p,source_polygons=polygons,origin=o,axis=u,lo=lo,hi=hi,width=width,seams=seams,max_axis_displacement_m=displacement,length=hi-lo)
def evidence(rec,read):
step=POLICY['step_m'];ts=np.arange(rec['lo']+.10,rec['hi']-.10,step);ns=np.arange(-.8,.801,.025)
c,allowed=strip(rec['origin'],rec['axis'],ts,ns,read);band=abs(ns)<=max(.025,min(.05,rec['width']*.25));signal=np.median(c[:,band],axis=1);valid=allowed[:,band].all(1)
level=float(np.median(signal[valid]))if valid.any()else 0.;cut=max(15.,.35*level);paint=(signal>cut)&valid
dark=(signal<=cut)&valid;longest=max([(b-a)*step for a,b in runs(dark)]or[0.])
offsets=[]
for row,v in zip(c,valid):
if not v:continue
pk,_=find_peaks(row,height=18,prominence=8,distance=4);near=[k for k in pk if abs(ns[k])<=.20]
if near:offsets.append(float(ns[min(near,key=lambda k:abs(ns[k]))]))
offsets=np.array(offsets);median=float(np.median(abs(offsets)))if len(offsets)else 999.;q90=float(np.quantile(abs(offsets),.90))if len(offsets)else 999.
seams=[]
for a,b in rec['seams']:
sel=(ts>=a-.10)&(ts<=b+.10)
seams.append(dict(lo=float(a),hi=float(b),valid=float(valid[sel].mean())if sel.any()else 0.,support=float(paint[sel].mean())if sel.any()else 0.))
result=dict(valid=float(valid.mean()),support=float(paint.mean()),median_contrast=level,cut=cut,longest_visible_dark_run_m=longest,ridge_median_offset_m=median,ridge_q90_offset_m=q90,ridge_samples=len(offsets),seams=seams)
result['local_evidence_passed']=bool(level>=POLICY['min_median_contrast'] and longest<=POLICY['max_visible_dark_run_m'] and median<=POLICY['max_ridge_median_offset_m'] and q90<=POLICY['max_ridge_q90_offset_m'] and all(s['valid']>=POLICY['min_seam_valid'] and s['support']>=POLICY['min_seam_support']for s in seams))
result['passed']=bool(result['valid']>=POLICY['min_valid'] and result['support']>=POLICY['min_paint_support'] and level>=POLICY['min_median_contrast'] and longest<=POLICY['max_visible_dark_run_m'] and median<=POLICY['max_ridge_median_offset_m'] and q90<=POLICY['max_ridge_q90_offset_m'] and all(s['valid']>=POLICY['min_seam_valid'] and s['support']>=POLICY['min_seam_support']for s in seams))
return result
def check_chain(rec,readers):
ev=[evidence(rec,r)for r in readers]
if len(ev)<POLICY['min_views']:return False,ev
if all(e['passed']for e in ev):
rec['output_polygon']=rec['polygon'];rec['operation']='whole-row-fit';rec['edit_domain']=rec['polygon'];return True,ev
# Two views are mandatory at every edited joint. Outside those local joints,
# only exact old geometry may survive when the second view is unavailable.
if not(any(e['passed']for e in ev)and all(e['local_evidence_passed']for e in ev)):return False,ev
patches=[rectangle(rec['origin'],rec['axis'],a-POLICY['joint_padding_m'],b+POLICY['joint_padding_m'],rec['width'])for a,b in rec['seams']]
domain=shapely.union_all(patches);p=shapely.union_all(rec['source_polygons']+patches)
if p.geom_type!='Polygon' or not p.is_valid:return False,ev
rec['output_polygon']=p;rec['operation']='preserved-contour-union';rec['edit_domain']=domain
return True,ev
@@ -0,0 +1,65 @@
import json,runpy,numpy as np
from shapely.geometry import Polygon
from interval_profiles import rectangle
from row_profiles import pair,fit_chain,check_chain
from row_evidence import choose_owners
prior=runpy.run_path('/candidate/test_sections.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()}
o=np.zeros(2);u=np.array([1.,0.]);a=rectangle(o,u,0,4,.15);b=rectangle(o,u,4.18,8,.15)
def bright(xy):
v=65+140*np.exp(-.5*(xy[:,1]/.035)**2)
return np.repeat(v[:,None],3,1).astype('uint8'),np.ones(len(xy),bool)
r=fit_chain([a,b]);okay,ev=check_chain(r,[bright,bright])
checks['supported_seam_becomes_one_row']=okay
checks['new_row_spans_original_endpoints']=abs(r['length']-8)<1e-5
checks['two_views_required']=not check_chain(r,[bright])[0]
def darkgap(xy):
rgb,v=bright(xy);rgb[(xy[:,0]>3.98)&(xy[:,0]<4.20)]=65;return rgb,v
checks['actual_gap_never_joined']=not check_chain(r,[darkgap,darkgap])[0]
checks['disagreeing_views_reject_join']=not check_chain(r,[bright,darkgap])[0]
def covered(xy):
rgb,v=bright(xy);v[(xy[:,0]>3.98)&(xy[:,0]<4.20)]=False;return rgb,v
checks['occluded_seam_not_bright']=not check_chain(r,[covered,covered])[0]
def long_dark(xy):
rgb,v=bright(xy);rgb[(xy[:,0]>1)&(xy[:,0]<1.5)]=65;return rgb,v
checks['whole_row_dark_gap_veto']=not check_chain(r,[long_dark,long_dark])[0]
def weak(xy):
v=65+12*np.exp(-.5*(xy[:,1]/.035)**2)
return np.repeat(v[:,None],3,1).astype('uint8'),np.ones(len(xy),bool)
checks['weak_entire_row_not_rebuilt']=not check_chain(r,[weak,weak])[0]
checks['far_endpoints_not_joined']=pair(a,rectangle(o,u,5,9,.15))is None
checks['parallel_neighbor_not_joined']=pair(a,rectangle(o,u,4,8,.15,.25))is None
checks['different_widths_not_joined']=pair(a,rectangle(o,u,4,8,.32))is None
checks['nested_duplicate_not_end_join']=pair(a,rectangle(o,u,1,3,.15))is None
checks['short_residual_below_limit_retained']=pair(a,rectangle(o,u,4,4.4,.15))is None
# Narrow, supported touching source intervals produce one consistent-width row.
checks['touching_intervals_join']=check_chain(fit_chain([a,rectangle(o,u,4,8,.15)]),[bright,bright])[0]
checks['three_fragments_fit_original_geometry']=check_chain(fit_chain([a,b,rectangle(o,u,8.1,12,.15)]),[bright,bright])[0]
checks['diverging_chain_rejected']=fit_chain([a,rectangle(o,u,4,8,.15,.06),rectangle(o,u,8,12,.15,-.12)])is None
checks['wide_chain_rejected']=fit_chain([a,rectangle(o,u,4,8,.4)])is None
checks['distant_gap_in_chain_rejected']=fit_chain([a,rectangle(o,u,6,10,.15)])is None
# Rigidly transforming the scene cannot change row acceptance.
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:bright((xy-shift)@rot)
checks['whole_row_rigid_transform_invariance']=check_chain(fit_chain([ar,br]),[read,read])[0]==okay
# Missing a second view away from the joint permits exact contour assembly,
# not global refitting of the unobserved outer boundary.
def second_at_joint(xy):
rgb,v=bright(xy);v[(xy[:,0]<3.5)|(xy[:,0]>4.6)]=False;return rgb,v
rr=fit_chain([a,b]);ok,_=check_chain(rr,[bright,second_at_joint])
checks['local_two_view_joint_preserves_old_contours']=ok and rr['operation']=='preserved-contour-union'
before=a.union(b);domain=rr['edit_domain'];after=rr['output_polygon']
checks['outer_geometry_exactly_unchanged']=after.difference(domain).symmetric_difference(before.difference(domain)).area<1e-8
checks['one_view_at_joint_still_rejected']=not check_chain(fit_chain([a,b]),[bright,covered])[0]
checks['both_views_incomplete_no_global_join']=not check_chain(fit_chain([a,b]),[second_at_joint,second_at_joint])[0]
checks['empty_tile_inventory_is_unknown']=np.all(choose_owners(np.zeros((2,0)),np.zeros((2,0),bool))==-1)
# Views switch spatially; intensity does not participate in ownership.
d=np.array([[1.,2.,3.],[2.,1.,3.],[3.,2.,1.]]);cover=np.ones((3,3),bool)
checks['two_nearest_geometric_owners']=np.array_equal(choose_owners(d,cover),[[0,1],[1,0],[2,1]])
cover[1,1]=False
checks['noncovering_nearest_skipped']=np.array_equal(choose_owners(d,cover)[1],[0,2])
checks['one_view_yields_missing_second']=np.array_equal(choose_owners(np.ones((2,1)),np.ones((2,1),bool)),[[0,-1],[0,-1]])
checks['no_coverage_yields_unknown']=np.all(choose_owners(d,np.zeros((3,3),bool))==-1)
checks['view_ranks_never_same']=np.all(np.diff(choose_owners(d,np.ones((3,3),bool)),axis=1)!=0)
checks['ownership_ties_stable']=np.array_equal(choose_owners(np.ones((1,3)),np.ones((1,3),bool)),[[0,1]])
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/rows-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']