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,73 @@
|
||||
Observed continuation of dashed road-marking rows
|
||||
================================================
|
||||
|
||||
Scope and inputs
|
||||
----------------
|
||||
Offline increment over norms-pass-20261012. Same code and metric thresholds on
|
||||
Maroseyka, Pokrovka and Smolensk. Gaussian ground RGB, calibrated top-view
|
||||
geometry, previously pinned surface labels and vehicle masks. No point clouds,
|
||||
colliders, street names in detector logic, hand-set geometry or processing ROIs.
|
||||
All image computation, tests and rendering execute on Worker006. The Mac only
|
||||
orchestrates, edits text, verifies hashes, copies and displays outputs.
|
||||
|
||||
Method
|
||||
------
|
||||
A previously verified long-dash family supplies direction, phase, length, width
|
||||
and period. The sampler uses the spatially nearest render-tile center for each
|
||||
world-space query, permitting continuation across tile boundaries. It retains
|
||||
that tile's actual image coverage, road mask, vehicle veto and protected symbols.
|
||||
Nearest-tile ownership is not multi-view consensus; camera/scan inconsistency
|
||||
can still stop a row or bias evidence. There is no new Gaussian rendering.
|
||||
|
||||
OpenCV background morphology and SciPy filtering provide the same metric paint
|
||||
profile as previous passes. In each direction a bounded walk visits at most
|
||||
12 slots and 60 m. A predicted slot is accepted only with a real paint run,
|
||||
observed edges, a dark gap, and sufficient valid road evidence. Gap support is
|
||||
>=90% valid, >=75% dark and contrast >=15. Stroke support is >=90% valid,
|
||||
>=80% bright and median contrast >=22. Maximum phase residual is 0.28 m;
|
||||
length deviation is <=max(0.35 m, 20%). A lateral-ridge veto prevents stepping
|
||||
onto a neighboring track. Small cracks <=0.15 m can close within observed paint.
|
||||
Unknown coverage, a vehicle/protected region, continuous paint, a changed rhythm
|
||||
or weak paint stops further continuation in that direction. No hidden slot is
|
||||
filled merely from a GOST rhythm.
|
||||
|
||||
An accepted stroke uses its family's common length, width and direction. The
|
||||
intervening observed gap is cleared of associated older paint. Old fragments
|
||||
are cut over their full transverse section, within the longitudinal interval,
|
||||
so narrowing a wavy vector does not leave parallel slivers. Association still
|
||||
requires a thin, direction-compatible nearby source object. Existing accepted
|
||||
norm-family anchors, crosswalks, symbols, roads, sidewalks and facades remain
|
||||
identical. Each new object links its anchors, evidence tiles and replaced IDs.
|
||||
|
||||
The preceding GOST geometric assessment is retained, including the distinction
|
||||
between nominal dimensions, measured dimensions and legal compliance, which is
|
||||
not assessed. This pass does not remeasure or resize crosswalks.
|
||||
|
||||
Verification and limits
|
||||
-----------------------
|
||||
The controlled suite includes all 42 preceding checks, both-direction extension,
|
||||
solid boundaries, blank/unknown/occluded gaps, changed phase/period, masked run
|
||||
edges, small paint cracks, rigid-transform invariance, bounded continuation,
|
||||
full-section replacement and preservation outside the edited interval.
|
||||
Output audit checks original object identity, anchor preservation, finite valid
|
||||
XYZ, paint/gap evidence, phase, lineage and an empty central corridor through
|
||||
every newly confirmed gap. All changed segments have source/before/after JPGs;
|
||||
prior short-dash review frames are revisited separately.
|
||||
|
||||
This is continuation of known straight long-dash families, not full lane-marking
|
||||
recall. It does not discover wholly unseeded families or rebuild curved rows.
|
||||
It stops at suspected solid transitions; it does not yet reconstruct their full
|
||||
solid/dashed topology. Pre-existing duplicates, false solids outside the accepted
|
||||
intervals, incomplete symbols and imperfect other layers remain. No geodetic
|
||||
accuracy, full precision/recall or road-code compliance claim follows.
|
||||
|
||||
Reproduction
|
||||
------------
|
||||
Pinned image sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0.
|
||||
4 CPU, 20 GiB RAM, 1 GiB tmpfs, read-only root, network none, 1800s per stage.
|
||||
Stages: test_transitions, refine_transitions, audit_transitions,
|
||||
render_transitions, render_plan. See the frozen source hashes and execution
|
||||
receipts for each scene. Private caches, SSH and canonical queue configuration
|
||||
are external dependencies. bundle.json resolves reused canonical modules.
|
||||
The rendering font is hashed separately and excluded from the source ZIP.
|
||||
No live-map deployment, Ops publication or commit.
|
||||
@@ -0,0 +1,26 @@
|
||||
from pathlib import Path
|
||||
import json,hashlib,numpy as np,shapely
|
||||
from shapely.geometry import shape,LineString
|
||||
old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text())
|
||||
removed=set(json.loads(Path('/out/transitions-replacements.json').read_text())['removed_ids']);features={f['id']:f for f in new['features']};rows=json.loads(Path('/out/transitions-rows.json').read_text());checks={}
|
||||
checks['unique_ids']=len(features)==len(new['features'])
|
||||
checks['untouched_identical']=all(features.get(f['id'])==f for f in old['features']if f['id']not in removed)
|
||||
checks['only_linear_paint_replaced']=all(f['properties'].get('subtype')=='linear_marking'for f in old['features']if f['id']in removed)
|
||||
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['output_lineage']=all(fid in features for r in rows for fid in r['output_ids']+r['anchor_ids'])
|
||||
checks['real_gaps_required']=all(r['gap']['valid_fraction']>=.9 and r['gap']['support_fraction']>=.75 and r['gap']['contrast']>=15 for r in rows)
|
||||
checks['real_paint_required']=all(r['paint']['valid_fraction']>=.9 and r['paint']['support_fraction']>=.8 and r['paint']['contrast']>=22 for r in rows)
|
||||
checks['phase_observed']=all(r['phase_residual_m']<=.28 for r in rows)
|
||||
linear=[shapely.force_2d(shape(f['geometry']))for f in new['features']if f['properties'].get('subtype')=='linear_marking']
|
||||
paint=shapely.union_all(linear)
|
||||
gap_overlaps=[]
|
||||
for r in rows:
|
||||
a,b=np.array(r['world_gap_start']),np.array(r['world_gap_end']);u=(b-a)/np.linalg.norm(b-a)
|
||||
gap=LineString([a+.10*u,b-.10*u]).buffer(r['width']*.20,cap_style='flat')
|
||||
gap_overlaps.append(gap.intersection(paint).area/max(gap.area,1e-9))
|
||||
checks['confirmed_gaps_open_in_output']=all(v<.05 for v in gap_overlaps)
|
||||
checks['anchor_geometry_preserved']=all(features.get(f['id'])==f for f in old['features']if f['properties'].get('method')=='observed-long-dash-family-v1')
|
||||
checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes()
|
||||
checks['same_policy']=new['transition_refinement']=='observed-row-continuation-v1'
|
||||
result=dict(passed=all(checks.values()),checks=checks,gap_paint_overlap_fractions=gap_overlaps,full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False)
|
||||
Path('/out/transitions-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"schema": "missioncore.offline-plan-bundle/v1",
|
||||
"root": "simulation/urban-plan-research",
|
||||
"files": {
|
||||
"audit_norms.py": "norms_pass/audit_norms.py",
|
||||
"audit_transitions.py": "transitions_pass/audit_transitions.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_norms.py": "norms_pass/refine_norms.py",
|
||||
"refine_transitions.py": "transitions_pass/refine_transitions.py",
|
||||
"render_norms.py": "norms_pass/render_norms.py",
|
||||
"render_plan.py": "continuation_pass/render_plan.py",
|
||||
"render_transitions.py": "transitions_pass/render_transitions.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_transitions.py": "transitions_pass/test_transitions.py",
|
||||
"transition_profiles.py": "transitions_pass/transition_profiles.py"
|
||||
},
|
||||
"reference_qualification": "transitions-pass-20261012",
|
||||
"source_snapshot": "5e683dba805251e6408d",
|
||||
"source_sha256": {
|
||||
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
|
||||
"audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a",
|
||||
"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_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5",
|
||||
"refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b",
|
||||
"render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d",
|
||||
"render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064",
|
||||
"render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d",
|
||||
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
|
||||
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a",
|
||||
"test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f",
|
||||
"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,77 @@
|
||||
from pathlib import Path
|
||||
from functools import lru_cache
|
||||
import os,json,time,hashlib
|
||||
import numpy as np,cv2,shapely
|
||||
from scipy.spatial import cKDTree
|
||||
from PIL import Image
|
||||
from shapely.geometry import shape
|
||||
from shapely.ops import transform
|
||||
from layer_common import O,S,feature,sample,parts
|
||||
from fit_scene import project
|
||||
from line_reconstruction import observation
|
||||
from transition_profiles import continue_row,residual_sections
|
||||
cv2.setNumThreads(3);started=time.monotonic()
|
||||
baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text())
|
||||
rows=json.loads(Path('/fullplan/norm-rows.json').read_text())
|
||||
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
|
||||
tree=cKDTree([np.mean(t['bounds_xy'],axis=0)for t in tiles])
|
||||
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];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'])
|
||||
def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
|
||||
@lru_cache(maxsize=3)
|
||||
def inputs(name):
|
||||
geom=dict(np.load(S/name/'top.geometry.npz'))
|
||||
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
|
||||
used=set()
|
||||
def sampler(points):
|
||||
# Pixel ownership is chosen spatially, independently of the seed. A row can
|
||||
# cross a render tile boundary without extrapolating past image coverage.
|
||||
owner=tree.query(points)[1];colors=np.zeros((len(points),3),dtype='uint8');allowed=np.zeros(len(points),bool)
|
||||
for index in np.unique(owner):
|
||||
select=np.flatnonzero(owner==index);xy=points[select];name=tiles[index]['id'];used.add(name);geom,rgb,vehicle=inputs(name)
|
||||
uv=project(xy,geom).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5
|
||||
chunks=max(1,int(np.ceil(len(uv)/20000)))
|
||||
colors[select]=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)])
|
||||
valid=(uv[:,0]>=0)&(uv[:,1]>=0)&(uv[:,0]<1199)&(uv[:,1]<1199)
|
||||
allowed[select]=valid&(sample(labels,xy,low,high)==1)&(veh<.20)&~shapely.contains_xy(protected,xy[:,0],xy[:,1])
|
||||
return colors,allowed
|
||||
original={f['id']:f for f in old['features']};working=dict(original);accepted=[];diagnostics=[];removed=set()
|
||||
anchor_ids=set(fid for r in rows for fid in r['output_ids'])
|
||||
for row_index,row in enumerate(rows):
|
||||
points=[shapely.force_2d(shape(original[fid]['geometry'])).centroid.coords[0]for fid in row['output_ids']]
|
||||
used.clear();proposals,debug=continue_row(points,row['axis'],row['length'],row['period'],row['width'],sampler)
|
||||
debug.update(row=row_index,source_tiles=sorted(used));diagnostics.append(debug)
|
||||
for rec in proposals:
|
||||
p=rec['polygon'];domain=rec['domain'];u=rec['axis'];n=np.array([-u[1],u[0]]);o=rec['origin'];source_ids=[];residual=[]
|
||||
# Do not overwrite already accepted anchor families or earlier extensions.
|
||||
anchors=[shapely.force_2d(shape(working[fid]['geometry']))for fid in anchor_ids if fid in working]
|
||||
if p.intersection(protected).area>.005 or any(p.intersection(a).area>.01 for a in anchors):continue
|
||||
for fid,f in list(working.items()):
|
||||
if f['properties'].get('subtype')!='linear_marking' or fid in anchor_ids:continue
|
||||
q=shapely.force_2d(shape(f['geometry']))
|
||||
if q.geom_type!='Polygon' or q.intersection(domain).area<.005:continue
|
||||
obs=observation(np.asarray(q.exterior.coords),'source')
|
||||
if obs['W']>.6 or abs(obs['axis']@u)<np.cos(np.deg2rad(5)) or abs((obs['center']-o)@n)>max(.16,row['width']*.7):continue
|
||||
source_ids.append(fid)
|
||||
# For an associated old stroke, replace its entire transverse section.
|
||||
# Cutting by the new stroke's narrower width leaves thin parallel slivers.
|
||||
for part in parts(residual_sections(q,domain,o,u)):
|
||||
if part.area>.025:residual.append(feature(lift(part),'road_marking',subtype='linear_marking',method='transitions-domain-residual',source_ids=f['properties'].get('source_ids',[fid])))
|
||||
for fid in source_ids:
|
||||
if fid in original:removed.add(fid)
|
||||
del working[fid]
|
||||
for f in residual:working[f['id']]=f
|
||||
item=feature(lift(p),'road_marking',subtype='linear_marking',line_kind='dashed',method='observed-row-continuation-v1',source_ids=source_ids,anchor_ids=row['output_ids'],source_tiles=sorted(used),period_m=row['period'],dash_length_m=row['length'],width_m=row['width'],standard_assessment=row['norm'],observed_stroke=True)
|
||||
working[item['id']]=item;anchor_ids.add(item['id'])
|
||||
accepted.append(dict(row=row_index,direction=rec['direction'],slot=rec['slot'],bounds_xy=rec['bounds_xy'],source_ids=source_ids,output_ids=[item['id']],anchor_ids=row['output_ids'],source_tiles=sorted(used),source_tile=row['source_tile'],period=row['period'],length=row['length'],width=row['width'],observed_length=rec['observed_length'],phase_residual_m=abs(rec['observed_center']-rec['center']),gap=rec['gap'],paint=rec['paint'],edges=rec['edges'],world_gap_start=rec['world_gap_start'],world_gap_end=rec['world_gap_end']))
|
||||
print('ROW',row_index,'PROPOSED',len(proposals),'TOTAL',len(accepted),'STOPS',debug.get('stops'),flush=True)
|
||||
result={**old,'features':list(working.values()),'transition_refinement':'observed-row-continuation-v1'}
|
||||
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False))
|
||||
(O/'transitions-rows.json').write_text(json.dumps(accepted,indent=2));(O/'transitions-diagnostics.json').write_text(json.dumps(diagnostics));(O/'transitions-replacements.json').write_text(json.dumps(dict(removed_ids=sorted(removed))))
|
||||
# Retain the measured standard audit; this pass neither changes nor remeasures zebras.
|
||||
(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),extended_ends=len(set((r['row'],r['direction'])for r in accepted)),extended_rows=len(set(r['row']for r in accepted)),observed_dashes=len(accepted),replaced_objects=len(removed),profiled_rows=len(rows),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 working.values()),manual_geometry=False,manual_rois=[],policy_version='observed-row-continuation-v1',legal_compliance_assessed=False)
|
||||
(O/'transitions-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,kind='observed-row-endpoint',baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'transitions-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,30 @@
|
||||
import json,runpy,numpy as np
|
||||
from transition_profiles import walk_profile,continue_row,residual_sections
|
||||
from interval_profiles import rectangle
|
||||
prior=runpy.run_path('/candidate/test_norms.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()}
|
||||
ts=np.arange(-14,30,.025);valid=np.ones(len(ts),bool);anchors=[1.5,5.5,9.5]
|
||||
def wave():return np.where(ts%4<3,80.,0.)
|
||||
def run(s,v=valid):return walk_profile(ts,s,v,anchors,3,4)
|
||||
a,d=run(wave());checks['extends_both_ends']=any(r['direction']==-1 for r in a)and any(r['direction']==1 for r in a)
|
||||
s=wave();s[ts>12]=80;a,d=run(s);checks['solid_transition_stops']=not any(r['direction']==1 for r in a)
|
||||
s=wave();s[ts<0]=80;a,d=run(s);checks['solid_before_family_stops']=not any(r['direction']==-1 for r in a)
|
||||
s=wave();s[ts>11]=0;a,d=run(s);checks['blank_end_not_extrapolated']=not any(r['direction']==1 for r in a)
|
||||
v=valid.copy();v[ts>11]=False;a,d=run(wave(),v);checks['unknown_end_not_extrapolated']=not any(r['direction']==1 for r in a)
|
||||
v=valid.copy();v[(ts>11)&(ts<12)]=False;a,d=run(wave(),v);checks['hidden_gap_stops_walk']=not any(r['direction']==1 for r in a)
|
||||
s=wave();s[(ts>15.3)&(ts<15.5)]=80;a,d=run(s);checks['small_artifact_not_full_stroke']=all(abs(r['observed_length']-3)<.35 for r in a)
|
||||
s=wave();s[ts>12]=np.where((ts[ts>12]-.6)%4<3,80.,0.);a,d=run(s);checks['wrong_phase_stops']=not any(r['direction']==1 for r in a)
|
||||
s=wave();s[ts>12]=np.where(ts[ts>12]%6<3,80.,0.);a,d=run(s);checks['changed_period_stops_without_jump']=max([r['slot']for r in a if r['direction']==1]or[0])<=1
|
||||
v=valid.copy();v[(ts>14.9)&(ts<15.2)]=False;a,d=run(wave(),v);checks['mask_boundary_not_paint_edge']=not any(r['direction']==1 for r in a)
|
||||
s=wave();s[(ts>12.5)&(ts<12.6)]=0;a,d=run(s);checks['tiny_crack_preserves_stroke']=any(r['direction']==1 for r in a)
|
||||
def sampler(xy):
|
||||
paint=(xy[:,0]%4<3)&(abs(xy[:,1])<.075)
|
||||
return np.repeat(np.where(paint,210,65)[:,None],3,1).astype('uint8'),np.ones(len(xy),bool)
|
||||
points=np.c_[anchors,np.zeros(3)];a,_=continue_row(points,[1,0],3,4,.15,sampler)
|
||||
theta=.72;rot=np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]]);shift=np.array([140.,-35.]);b,_=continue_row(points@rot.T+shift,rot[:,0],3,4,.15,lambda xy:sampler((xy-shift)@rot))
|
||||
checks['row_continuation_rigid_transform_invariant']=len(a)==len(b)and len(a)>0
|
||||
checks['bounded_search']=all(r['slot']<=12 for r in a)
|
||||
o=np.array([0.,0.]);u=np.array([1.,0.]);old=rectangle(o,u,0,20,.30,.06);domain=rectangle(o,u,5,12,.22)
|
||||
res=residual_sections(old,domain,o,u)
|
||||
checks['replacement_has_no_parallel_side_sliver']=res.intersection(rectangle(o,u,5.001,11.999,1.)).area<1e-9
|
||||
checks['replacement_keeps_outside_longitudinal_interval']=abs(res.area-old.area+7*.30)<1e-8
|
||||
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/transitions-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Bounded continuation of an already observed straight dashed family.
|
||||
|
||||
The family supplies a search phase, not permission to invent paint. Every new
|
||||
stroke and intervening gap needs its own valid image evidence. Unknown pixels
|
||||
and genuine continuous paint stop the walk in that direction.
|
||||
"""
|
||||
import numpy as np
|
||||
from scipy.ndimage import gaussian_filter1d
|
||||
from interval_profiles import runs,strip,rectangle
|
||||
|
||||
def residual_sections(poly,domain,origin,axis):
|
||||
"""Keep the old row outside longitudinal limits, without side slivers."""
|
||||
tt=(np.asarray(domain.exterior.coords)-origin)@axis
|
||||
return poly.difference(rectangle(origin,axis,float(tt.min()),float(tt.max()),2.))
|
||||
|
||||
def walk_profile(ts,signal,valid,centers,length,period,step=.025):
|
||||
ts=np.asarray(ts);centers=np.sort(centers)
|
||||
inner=np.zeros(len(ts),bool)
|
||||
for c in centers:inner|=abs(ts-c)<length*.32
|
||||
usable=inner&valid
|
||||
if usable.sum()<20:return [],dict(reason='anchor_unobserved')
|
||||
level=float(np.median(signal[usable]));cut=max(15.,.4*level)
|
||||
if level<22:return [],dict(reason='anchor_low_contrast')
|
||||
paint=(signal>cut)&valid
|
||||
for a,b in runs(~paint):
|
||||
if a>0 and b<len(paint)and(b-a)*step<=.15 and valid[a:b].all():paint[a:b]=True
|
||||
intervals=[(float(ts[a]-step/2),float(ts[b-1]+step/2),a,b)for a,b in runs(paint)]
|
||||
def evidence(lo,hi,bright):
|
||||
select=(ts>=lo)&(ts<=hi)
|
||||
if select.sum()<3:return dict(valid_fraction=0.,support_fraction=0.,contrast=0.)
|
||||
return dict(valid_fraction=float(valid[select].mean()),
|
||||
support_fraction=float(((signal[select]>cut)if bright else(signal[select]<cut)).mean()),
|
||||
contrast=float(np.median(signal[select])if bright else level-np.median(signal[select])))
|
||||
accepted=[];stops=[]
|
||||
for sign,edge in [(-1,centers[0]),(1,centers[-1])]:
|
||||
previous=float(edge);count=0
|
||||
for slot in range(1,min(12,int(60/period))+1):
|
||||
target=float(edge+sign*slot*period)
|
||||
if target-length/2<ts[0] or target+length/2>ts[-1]:reason='coverage_end';break
|
||||
# Search only a small phase error around the same row/slot.
|
||||
options=[x for x in intervals if x[0]-.10<=target<=x[1]+.10]
|
||||
if not options:reason='no_observed_stroke';break
|
||||
lo,hi,a,b=min(options,key=lambda x:abs((x[0]+x[1])/2-target))
|
||||
measured=hi-lo;center=(lo+hi)/2
|
||||
gaplo,gaphi=sorted([previous+sign*length/2,target-sign*length/2])
|
||||
gap=evidence(gaplo+.07,gaphi-.07,False)
|
||||
core=evidence(target-length*.38,target+length*.38,True)
|
||||
if gap['valid_fraction']<.9 or core['valid_fraction']<.9:reason='unknown_or_protected';break
|
||||
if gap['support_fraction']<.75 or gap['contrast']<15:reason='no_dark_gap_or_solid';break
|
||||
if core['support_fraction']<.8 or core['contrast']<22:reason='weak_paint';break
|
||||
if abs(measured-length)>max(.35,length*.20) or abs(center-target)>.28:
|
||||
reason='solid_transition_or_changed_rhythm';break
|
||||
# Both visible run edges are needed; a mask edge is not a paint end.
|
||||
edges=[evidence(lo-.10,lo-.03,False),evidence(hi+.03,hi+.10,False)]
|
||||
if any(x['valid_fraction']<.9 or x['support_fraction']<.65 for x in edges):reason='unobserved_stroke_edge';break
|
||||
accepted.append(dict(direction=sign,slot=slot,center=target,observed_center=center,
|
||||
observed_length=measured,length=length,gap_lo=gaplo,gap_hi=gaphi,
|
||||
gap=gap,paint=core,edges=edges))
|
||||
previous=target;count+=1
|
||||
else:reason='bounded_walk_limit'
|
||||
stops.append(dict(direction=sign,accepted=count,reason=reason))
|
||||
return accepted,dict(level=level,cut=cut,stops=stops)
|
||||
|
||||
def continue_row(points,axis,length,period,width,sampler):
|
||||
points=np.asarray(points);u=np.asarray(axis,float);u/=np.linalg.norm(u)
|
||||
o=points.mean(0);centers=np.sort((points-o)@u)
|
||||
extension=min(60.,12*period);step=.025
|
||||
ts=np.arange(centers[0]-extension-length,centers[-1]+extension+length,step)
|
||||
ns=np.arange(-.60,.601,step)
|
||||
contrast,allowed=strip(o,u,ts,ns,sampler)
|
||||
band=abs(ns)<=max(.035,min(.07,width*.3))
|
||||
signal=gaussian_filter1d(np.median(contrast[:,band],axis=1),1)
|
||||
valid=allowed[:,band].mean(1)>.85
|
||||
recs,debug=walk_profile(ts,signal,valid,centers,length,period,step)
|
||||
n=np.array([-u[1],u[0]]);accepted=[]
|
||||
for r in recs:
|
||||
# A crossing line or neighboring track must not masquerade as a dash.
|
||||
core=abs(ts-r['center'])<length*.32
|
||||
normal=np.median(contrast[core],axis=0)
|
||||
near=abs(ns)<.22;peak=int(np.argmax(np.where(near,normal,0)))
|
||||
if abs(ns[peak])>.10:
|
||||
# Stop this direction: later slots cannot jump over this rejection.
|
||||
debug.setdefault('lateral_rejections',[]).append(r['direction']);continue
|
||||
if r['direction']in debug.get('lateral_rejections',[]):continue
|
||||
c=r['center'];p=rectangle(o,u,c-length/2,c+length/2,width)
|
||||
lo=min(r['gap_lo'],c-length/2);hi=max(r['gap_hi'],c+length/2)
|
||||
r.update(polygon=p,domain=rectangle(o,u,lo,hi,width+.14),axis=u,
|
||||
origin=o,bounds_xy=rectangle(o,u,lo,hi,width+.14).bounds,
|
||||
world_gap_start=(o+r['gap_lo']*u).tolist(),world_gap_end=(o+r['gap_hi']*u).tolist())
|
||||
accepted.append(r)
|
||||
debug.update(ts=ts[::4].tolist(),signal=signal[::4].tolist(),valid=valid[::4].tolist())
|
||||
return accepted,debug
|
||||
Reference in New Issue
Block a user