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,81 @@
|
||||
Whole-map linear marking batch, 2026-10-12
|
||||
========================================
|
||||
|
||||
This offline research candidate processes the rows-pass-20261012 maps with a
|
||||
single common policy. It is not a live map deployment or a general urban-map
|
||||
acceptance. Roads, sidewalks, facades, crosswalks and symbols are preserved.
|
||||
|
||||
Stages in refine_beta.py
|
||||
-----------------------
|
||||
|
||||
1. All eligible existing linear objects seed a Gaussian image search, extending
|
||||
12 metres beyond each endpoint. Every profile uses two spatially selected
|
||||
evidence mosaics. Their sources are selected by coverage and distance before
|
||||
reading paint intensity. They are distinct renders of the same reconstruction.
|
||||
2. OpenCV transverse background removal, SciPy prominence/width measurements and
|
||||
the existing robust periodic-row fitter discover bounded short/long dash rows.
|
||||
Both views must contain actual stroke edges. Constant spacing cannot authorize
|
||||
a missing observation. Short rows need four strokes, long rows three. Rhythm
|
||||
changes and unknown observations bound accepted subsequences. A faint paint
|
||||
underlay requires an observed prominent peak sequence and contrast drop in
|
||||
both views. Output stroke width, phase and period come from the scene.
|
||||
3. Solid endpoints may move by 0.12 to 2 metres only with observed paint inside,
|
||||
a dark interval outside, and support throughout the edit in both views.
|
||||
The full transverse corridor is checked before shortening a line; sideways
|
||||
drift cannot be interpreted as a paint ending. Confirmed dark edge padding
|
||||
can absorb obsolete tiny end caps when replacing a periodic family.
|
||||
Missing alpha/road coverage, vehicles and protected symbols are unknown.
|
||||
4. The qualified whole-chain assembler joins compatible solid fragments only
|
||||
across image-supported seams, with known dashed objects acting as barriers.
|
||||
|
||||
No scene-specific coordinates, manually selected detector ROI, point cloud,
|
||||
collider, external road geometry, or street-specific threshold is used. The scene
|
||||
selector chooses paths only. Additional Gaussian rendering was not performed.
|
||||
|
||||
Geometry and audit
|
||||
------------------
|
||||
|
||||
Each transaction records exact input/output features, edit domain, image evidence
|
||||
and source tiles. Changes are limited to selected linear marking features.
|
||||
Longitudinal residuals retain original XY outside accepted intervals; output Z
|
||||
is sampled from the existing Gaussian-derived height field. All other features
|
||||
are preserved byte-for-byte as JSON objects. Newly added overlaps with neighboring
|
||||
markings are vetoed. Source IDs and transaction replay reconstruct the output.
|
||||
|
||||
The audit checks transaction replay, finite valid XYZ, unchanged other layers,
|
||||
protected paint, overlap growth, outside-interval preservation, common policy,
|
||||
and numerical evidence gates. Controlled tests include all prior line passes.
|
||||
The fourth stage can yield zero edits; execution is not a claim of additional
|
||||
assembly improvement on each scene.
|
||||
|
||||
Each accepted dash family retains a dimensional association with the existing
|
||||
GOST catalog; dimensions and phase are not forced to nominal values.
|
||||
The existing GOST crosswalk assessment is retained unchanged. Measurement remains
|
||||
authoritative; no legal compliance or surveying accuracy is claimed.
|
||||
|
||||
Reproduction
|
||||
------------
|
||||
|
||||
Use the canonical Mission Core checkout and the recorded Worker006 qualification
|
||||
runner. bundle.json references unchanged modules in their canonical locations;
|
||||
new modules live in beta_pass. The qualified staging snapshot contains all Python
|
||||
files and the pinned review font. The source ZIP excludes the external font.
|
||||
Private cached Gaussian RGB/geometry/vehicle masks, Gaussian-derived semantic and
|
||||
height fields, accepted baseline maps and the pinned Docker image are required.
|
||||
An identical frozen source bundle is evaluated on Maroseyka, Pokrovka and Smolensk.
|
||||
|
||||
Runner constraints: Worker006, 4 CPU, 20 GiB, network none, read-only root,
|
||||
1 GiB tmpfs, no capabilities, 1800-second stage bound, canonical queue reservation
|
||||
and explicit resource release. The Mac only orchestrates, copies and views results.
|
||||
Qualification receipts, input hashes, map audits, JPG comparisons and transaction
|
||||
JSON are retained with the result. The number of changed objects is not accuracy.
|
||||
|
||||
Limitations
|
||||
-----------
|
||||
|
||||
Discovery needs at least one existing approximately aligned linear seed. Curved
|
||||
rows, fully missed disconnected rows, symbols, arrows, road/facade reconstruction,
|
||||
and additional rendering are outside this batch. Two-view gating may retain a
|
||||
known defect where evidence is incomplete. This is conservative missing-evidence
|
||||
handling, not proof that the unchanged geometry is correct. Qualitative review of
|
||||
edits does not establish exhaustive detection recall on these or unseen scenes.
|
||||
@@ -0,0 +1,45 @@
|
||||
from pathlib import Path
|
||||
import json,hashlib,numpy as np,shapely
|
||||
from shapely.geometry import shape
|
||||
from beta_profiles import POLICY,VERSION,supported
|
||||
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/beta-rows.json').read_text());current={f['id']:f for f in old['features']};checks={}
|
||||
def poly(f):return shapely.force_2d(shape(f['geometry']))
|
||||
protected=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'])
|
||||
checks['transaction_replay']=True;checks['only_linear_objects_replaced']=True;checks['no_new_neighbor_overlap']=True;checks['protected_paint_preserved']=True;checks['evidence_passes']=True;checks['outside_edit_interval_preserved']=True
|
||||
for r in rows:
|
||||
before=r['before'];after=r['after'];ids=r['source_ids']
|
||||
checks['transaction_replay']&=all(current.get(f['id'])==f for f in before)and ids==[f['id']for f in before]and r['output_ids']==[f['id']for f in after]
|
||||
checks['only_linear_objects_replaced']&=all(f['properties'].get('subtype')=='linear_marking'for f in before+after)
|
||||
a=shapely.union_all([poly(f)for f in before]);b=shapely.union_all([poly(f)for f in after]);novel=b.difference(a)
|
||||
checks['protected_paint_preserved']&=novel.intersection(protected).area<=POLICY['max_new_neighbor_overlap_m2']
|
||||
checks['no_new_neighbor_overlap']&=all(novel.intersection(poly(f)).area<=POLICY['max_new_neighbor_overlap_m2']for i,f in current.items()if i not in ids and f['properties'].get('subtype')=='linear_marking')
|
||||
ev=r['evidence'];ok=len(r['source_views'])==2 and len(r['source_tiles'])>=2
|
||||
if r['kind']=='periodic-row':
|
||||
ok&=len(ev['paint'])==2*len(ev['observations'])and all(supported(e)for e in ev['paint'])
|
||||
ok&=len(ev['gaps'])==2*(len(ev['observations'])-1)
|
||||
ok&=all(supported(e,False)if ev['mode']=='intervals'else e['valid']>=.95 and e['contrast_drop']>=18 and e['contrast']<(e['contrast']+e['contrast_drop'])*.65 for e in ev['gaps'])
|
||||
ok&=all(len(e['edges'])==2 and max(abs(e['edges'][0][k]-e['edges'][1][k])for k in [0,1])<=POLICY['max_edge_disagreement_m']for e in ev['observations'])
|
||||
ok&=all(e['padding']<=POLICY['max_family_edge_padding_m']and len(e['views'])==2 and all(v.get('full_corridor')and supported(v,False)for v in e['views'])for e in ev['edges'])
|
||||
# The transverse replacement section is wider than the modeled stripe;
|
||||
# the outside longitudinal old contours must nevertheless be exact.
|
||||
from interval_profiles import rectangle
|
||||
d=shape(r['edit_domain']);o=np.array(r['origin']);u=np.array(r['axis']);tt=(np.asarray(d.exterior.coords)-o)@u;domain=rectangle(o,u,float(tt.min()),float(tt.max()),2.)
|
||||
checks['outside_edit_interval_preserved']&=a.difference(domain.buffer(1e-7)).symmetric_difference(b.difference(domain.buffer(1e-7))).area<1e-7
|
||||
elif r['kind']=='solid-endpoints':
|
||||
ok&=all(len(e['evidence'])==2 and POLICY['min_endpoint_change_m']<=abs(e['delta'])<=POLICY['max_endpoint_change_m']and all(supported(v['paint'])and supported(v['dark'],False)and supported(v['edit'],e['kind']=='extend-solid')for v in e['evidence'])for e in ev)
|
||||
ok&=all(v['dark'].get('full_corridor')and(e['kind']=='extend-solid'or v['edit'].get('full_corridor'))for e in ev for v in e['evidence'])
|
||||
domain=shape(r['edit_domain']);checks['outside_edit_interval_preserved']&=a.difference(domain.buffer(1e-7)).symmetric_difference(b.difference(domain.buffer(1e-7))).area<1e-7
|
||||
elif r['kind']=='assembled-row':
|
||||
ok&=len(ev)==2 and r['max_axis_displacement_m']<=.065 and all(v['local_evidence_passed']for v in ev)and any(v['passed']for v in ev)
|
||||
else:ok=False
|
||||
checks['evidence_passes']&=ok
|
||||
for i in ids:current.pop(i,None)
|
||||
for f in after:current[f['id']]=f
|
||||
features={f['id']:f for f in new['features']};checks['final_map_matches_replay']=features==current;checks['unique_ids']=len(features)==len(new['features'])
|
||||
checks['unchanged_other_layers']=all(features.get(f['id'])==f for f in old['features']if f['properties'].get('subtype')!='linear_marking')
|
||||
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['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes()
|
||||
report=json.loads(Path('/out/beta-report.json').read_text());checks['same_policy']=new['beta_refinement']==VERSION and report['policy']==POLICY
|
||||
checks['every_operation_counted']=report['changed_segments']==len(rows)and sum(report['stages'].values())==len(rows)
|
||||
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False)
|
||||
Path('/out/beta-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
|
||||
@@ -0,0 +1,181 @@
|
||||
"""Row-scale paint interpretation using shared, metric image-evidence rules.
|
||||
|
||||
OpenCV background subtraction, SciPy peaks/robust fitting and the existing
|
||||
periodic-row fitter are reused. Both geometrically selected Gaussian mosaics
|
||||
must support each edit. They are two renders, not independent physical scans.
|
||||
"""
|
||||
import numpy as np
|
||||
from scipy.ndimage import gaussian_filter1d
|
||||
from scipy.signal import find_peaks, peak_widths
|
||||
from interval_profiles import strip, runs, rectangle
|
||||
from line_reconstruction import observation, reconstruct
|
||||
|
||||
VERSION='paint-row-batch-v1'
|
||||
POLICY=dict(step_m=.025, extension_m=12., max_seed_length_m=70.,
|
||||
max_seed_width_m=.35, min_seed_length_m=.30, normal_half_width_m=.7,
|
||||
max_ridge_offset_m=.13, max_view_offset_disagreement_m=.05,
|
||||
min_valid=.95, min_bright=.82, min_contrast=22., min_dark=.85,
|
||||
max_edge_disagreement_m=.20, max_phase_error_m=.20,
|
||||
min_short_strokes=4,min_long_strokes=3,max_dash_length_m=10.5,
|
||||
min_dash_length_m=.26,max_crack_m=.125,min_gap_m=.12,
|
||||
max_endpoint_change_m=2.,min_endpoint_change_m=.12,
|
||||
max_new_neighbor_overlap_m2=.005,min_material_change_m2=.015,
|
||||
endpoint_dark_corridor_m=.20,max_endpoint_ridge_offset_m=.065,
|
||||
max_family_edge_padding_m=.20)
|
||||
|
||||
def describe(poly):
|
||||
if poly.geom_type!='Polygon':return None
|
||||
z=observation(np.asarray(poly.exterior.coords),'seed')
|
||||
if not POLICY['min_seed_length_m']<=z['L']<=POLICY['max_seed_length_m'] or z['W']>POLICY['max_seed_width_m']:return None
|
||||
u=z['axis'].astype(float);u/=np.linalg.norm(u)
|
||||
return dict(origin=z['center'].astype(float),axis=u,length=float(z['L']),width=float(z['W']))
|
||||
|
||||
def profiles(seed,readers,extension=None):
|
||||
if len(readers)!=2:return None
|
||||
o,u=seed['origin'],seed['axis'];step=POLICY['step_m'];ext=POLICY['extension_m']if extension is None else extension
|
||||
ts=np.arange(-seed['length']/2-ext,seed['length']/2+ext+step/2,step)
|
||||
ns=np.arange(-POLICY['normal_half_width_m'],POLICY['normal_half_width_m']+step/2,step)
|
||||
result=[]
|
||||
for read in readers:
|
||||
contrast,allowed=strip(o,u,ts,ns,read)
|
||||
central=abs(ts)<=max(seed['length']/2,1.)
|
||||
transverse=np.quantile(np.where(allowed[central],contrast[central],0),.8,axis=0)
|
||||
pk,_=find_peaks(transverse,height=18,prominence=8,distance=4)
|
||||
pk=[k for k in pk if abs(ns[k])<=POLICY['max_ridge_offset_m']]
|
||||
if not pk:return None
|
||||
k=min(pk,key=lambda k:abs(ns[k]));pw=peak_widths(transverse,[k],rel_height=.5)[0][0]*step
|
||||
if not .045<=pw<=.35:return None
|
||||
band=abs(ns-ns[k])<=.04
|
||||
sig=gaussian_filter1d(np.median(contrast[:,band],axis=1),1)
|
||||
valid=allowed[:,band].all(1)
|
||||
level=float(np.quantile(sig[central&valid],.8))if np.any(central&valid)else 0.
|
||||
if level<POLICY['min_contrast']:return None
|
||||
cut=max(15.,.35*level)
|
||||
paint=(sig>cut)&valid
|
||||
for a,b in runs(~paint):
|
||||
if a>0 and b<len(ts)and(b-a)*step<=POLICY['max_crack_m']and valid[a:b].all():paint[a:b]=True
|
||||
intervals=[(float(ts[a]-step/2),float(ts[b-1]+step/2))for a,b in runs(paint)if(b-a)*step>=POLICY['min_dash_length_m']]
|
||||
peaks,_=find_peaks(np.where(valid,sig,0),prominence=18,distance=int(.45/step))
|
||||
widths=peak_widths(np.where(valid,sig,0),peaks,rel_height=.5)
|
||||
peak_intervals=[(float(ts[0]+widths[2][j]*step),float(ts[0]+widths[3][j]*step))for j in range(len(peaks))if .26<widths[0][j]*step<1.4]
|
||||
result.append(dict(ts=ts,ns=ns,contrast=contrast,allowed=allowed,signal=sig,valid=valid,cut=cut,level=level,offset=float(ns[k]),width=float(pw),intervals=intervals,peak_intervals=peak_intervals))
|
||||
if abs(result[0]['offset']-result[1]['offset'])>POLICY['max_view_offset_disagreement_m']:return None
|
||||
return result
|
||||
|
||||
def section_evidence(v,lo,hi,bright=True):
|
||||
sel=(v['ts']>=lo)&(v['ts']<=hi)
|
||||
if sel.sum()<3:return dict(valid=0.,support=0.,contrast=0.)
|
||||
sig=v['signal'][sel]
|
||||
return dict(valid=float(v['valid'][sel].mean()),support=float((sig>v['cut']).mean()if bright else(sig<v['cut']).mean()),contrast=float(np.median(sig)))
|
||||
|
||||
def supported(ev,bright=True):
|
||||
return ev['valid']>=POLICY['min_valid'] and ev['support']>=(POLICY['min_bright']if bright else POLICY['min_dark']) and (ev['contrast']>=POLICY['min_contrast']if bright else True)
|
||||
|
||||
def corridor_dark(v,lo,hi):
|
||||
"""A bent/offset paint ridge is not an end: inspect the full local corridor."""
|
||||
sel=(v['ts']>=lo)&(v['ts']<=hi);band=abs(v['ns']-v['offset'])<=POLICY['endpoint_dark_corridor_m']
|
||||
if sel.sum()<3:return dict(valid=0.,support=0.,contrast=0.)
|
||||
c=v['contrast'][sel][:,band];valid=v['allowed'][sel][:,band].all(1);signal=c.max(1)
|
||||
return dict(valid=float(valid.mean()),support=float((signal<v['cut']).mean()),contrast=float(np.median(signal)),full_corridor=True)
|
||||
|
||||
def fit_series(intervals,seed,width,offset):
|
||||
"""Find bounded constant-rhythm subseries; never cross a rhythm change."""
|
||||
o,u=seed['origin'],seed['axis'];n=np.array([-u[1],u[0]]);out=[]
|
||||
for start in range(len(intervals)):
|
||||
for end in range(start+3,min(len(intervals),start+40)+1):
|
||||
seq=intervals[start:end];lengths=np.array([b-a for a,b in seq]);L=float(np.median(lengths))
|
||||
minimum=POLICY['min_short_strokes']if L<1.45 else POLICY['min_long_strokes']
|
||||
if len(seq)<minimum or not POLICY['min_dash_length_m']<L<=POLICY['max_dash_length_m']:continue
|
||||
if np.max(abs(lengths-L))>max(.15,.22*L):continue
|
||||
rs=[dict(center=o+((a+b)/2)*u+offset*n,axis=u,L=b-a,W=width,source_tile='two-gaussian-mosaics')for a,b in seq]
|
||||
fit=reconstruct(dict(records=rs,origin=o+offset*n,axis=u,points=np.array([r['center']for r in rs]),parallel=False),minimum_period_to_length=1.10)
|
||||
if fit is None or fit['kind']!='dashed' or fit['period_m']-L<POLICY['min_gap_m']:continue
|
||||
# A regular missing slot is a hypothesis, never an automatic output.
|
||||
fit.update(lo=seq[0][0],hi=seq[-1][1],intervals=seq,length=L,offset=offset)
|
||||
out.append(fit)
|
||||
# Image validation decides which subseries survives. Selecting a large
|
||||
# unverified model here would suppress valid shorter rows at occlusions.
|
||||
return sorted(out,key=lambda x:(-len(x['intervals']),-x['hi']+x['lo']))
|
||||
|
||||
def discover(seed,views):
|
||||
"""Measured dashes, regular spacing, observed gap and transition endpoints."""
|
||||
if views is None:return []
|
||||
o,u=seed['origin'],seed['axis'];offset=float(np.mean([v['offset']for v in views]));width=float(np.clip(np.median([v['width']for v in views]),.075,.27));candidates=[]
|
||||
for mode in ['intervals','peak_intervals']:
|
||||
for fit in fit_series(views[0][mode],seed,width,offset):
|
||||
# Both mosaics must locate actual stroke edges, including a worn
|
||||
# continuous underlay. A model alone cannot supply a missing run.
|
||||
observations=[];evidence=[];okay=True
|
||||
for p in fit['polygons']:
|
||||
c=float((np.array(p.centroid.coords[0])-o)@u);L=fit['length'];matched=[]
|
||||
for v in views:
|
||||
opts=[ab for ab in v[mode]if abs((ab[0]+ab[1])/2-c)<=POLICY['max_phase_error_m']and abs((ab[1]-ab[0])-L)<=max(.2,.22*L)]
|
||||
if not opts:okay=False;break
|
||||
ab=min(opts,key=lambda ab:abs((ab[0]+ab[1])/2-c));ev=section_evidence(v,c-L*.35,c+L*.35)
|
||||
if not supported(ev):okay=False;break
|
||||
matched.append(ab);evidence.append(ev)
|
||||
if not okay:break
|
||||
if max(abs(matched[0][i]-matched[1][i])for i in [0,1])>POLICY['max_edge_disagreement_m']:okay=False;break
|
||||
observations.append(dict(center=c,edges=matched))
|
||||
if not okay:continue
|
||||
centers=[r['center']for r in observations];gap_evidence=[]
|
||||
for a,b in zip(centers,centers[1:]):
|
||||
lo=a+fit['length']/2+.04;hi=b-fit['length']/2-.04
|
||||
for v in views:
|
||||
ev=section_evidence(v,lo,hi,False)
|
||||
# A visible low floor is allowed only with an independently
|
||||
# identified high-contrast peak rhythm in both images.
|
||||
if mode=='peak_intervals':
|
||||
paint=min(section_evidence(v,a-fit['length']*.3,a+fit['length']*.3)['contrast'],section_evidence(v,b-fit['length']*.3,b+fit['length']*.3)['contrast'])
|
||||
ev['contrast_drop']=paint-ev['contrast'];ok=ev['valid']>=POLICY['min_valid']and ev['contrast_drop']>=18 and ev['contrast']<paint*.65
|
||||
else:ok=supported(ev,False)
|
||||
if not ok:okay=False;break
|
||||
gap_evidence.append(ev)
|
||||
if not okay:break
|
||||
if not okay:continue
|
||||
# Only the observed first-to-last stroke span may replace old paint.
|
||||
# Exterior transitions are handled separately with their own evidence.
|
||||
lo=centers[0]-fit['length']/2;hi=centers[-1]+fit['length']/2
|
||||
# Include only positively dark exterior slivers. This avoids tiny
|
||||
# leftover caps while never erasing a real neighboring solid start.
|
||||
edges=[];limits=[lo,hi]
|
||||
for side,end in enumerate([lo,hi]):
|
||||
sign=-1 if side==0 else 1
|
||||
for pad in np.arange(POLICY['max_family_edge_padding_m'],.049,-.025):
|
||||
ev=[corridor_dark(v,*sorted([end+sign*.04,end+sign*float(pad)]))for v in views]
|
||||
if all(supported(e,False)for e in ev):
|
||||
limits[side]=end+sign*float(pad);edges.append(dict(side=side,padding=float(pad),views=ev));break
|
||||
domain=rectangle(o,u,limits[0],limits[1],width+.16,offset)
|
||||
candidates.append(dict(kind='periodic-row',mode=mode,polygons=fit['polygons'],domain=domain,origin=o,axis=u,width=width,offset=offset,period=fit['period_m'],length=fit['length'],observations=observations,paint_evidence=evidence,gap_evidence=gap_evidence,edge_evidence=edges,lo=lo,hi=hi))
|
||||
accepted=[]
|
||||
for r in sorted(candidates,key=lambda x:-len(x['polygons'])):
|
||||
if any(r['domain'].intersection(q['domain']).area>.01 for q in accepted):continue
|
||||
accepted.append(r)
|
||||
return accepted
|
||||
|
||||
def endpoints(seed,views):
|
||||
"""Correct a solid end only where both paint and its following gap exist."""
|
||||
if views is None or seed['length']<2.7:return []
|
||||
changes=[];L=seed['length'];o,u=seed['origin'],seed['axis']
|
||||
for sign in [-1,1]:
|
||||
edge=sign*L/2;inside=edge-sign*min(L*.4,2.5);options=[]
|
||||
for v in views:
|
||||
options.append([ab for ab in v['intervals']if ab[0]<inside<ab[1]])
|
||||
if any(len(x)!=1 for x in options):continue
|
||||
ab=[x[0]for x in options];ends=[x[0 if sign<0 else 1]for x in ab]
|
||||
if abs(ends[0]-ends[1])>POLICY['max_edge_disagreement_m']:continue
|
||||
end=float(np.mean(ends));delta=sign*(end-edge)
|
||||
if not POLICY['min_endpoint_change_m']<=abs(delta)<=POLICY['max_endpoint_change_m']:continue
|
||||
if any(abs(x[1]-x[0])<2.7 for x in ab):continue
|
||||
evs=[];okay=True
|
||||
for v in views:
|
||||
bright=section_evidence(v,*sorted([end-sign*.5,end-sign*.08]));dark=corridor_dark(v,*sorted([end+sign*.08,end+sign*.35]))
|
||||
if not supported(bright)or not supported(dark,False):okay=False;break
|
||||
if delta>0 and abs(v['offset'])>POLICY['max_endpoint_ridge_offset_m']:okay=False;break
|
||||
edited=section_evidence(v,*sorted([edge+sign*.03,end-sign*.06]))if delta>0 else corridor_dark(v,*sorted([end+sign*.06,edge-sign*.03]))
|
||||
if not supported(edited,delta>0):okay=False;break
|
||||
evs.append(dict(paint=bright,dark=dark,edit=edited))
|
||||
if not okay:continue
|
||||
lo,hi=sorted([edge,end]);domain=rectangle(o,u,lo,hi,2.)
|
||||
changes.append(dict(kind='extend-solid'if delta>0 else'trim-solid',sign=sign,delta=delta,lo=lo,hi=hi,domain=domain,polygon=rectangle(o,u,lo,hi,seed['width']),evidence=evs))
|
||||
return changes
|
||||
@@ -0,0 +1,96 @@
|
||||
{
|
||||
"schema": "missioncore.offline-plan-bundle/v1",
|
||||
"root": "simulation/urban-plan-research",
|
||||
"files": {
|
||||
"audit_beta.py": "beta_pass/audit_beta.py",
|
||||
"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",
|
||||
"beta_profiles.py": "beta_pass/beta_profiles.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_beta.py": "beta_pass/refine_beta.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_beta.py": "beta_pass/render_beta.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_beta.py": "beta_pass/test_beta.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": "beta-pass-20261012",
|
||||
"source_snapshot": "b6572b4a70c07ae8aece",
|
||||
"source_sha256": {
|
||||
"audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f",
|
||||
"audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2",
|
||||
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
|
||||
"audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01",
|
||||
"audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7",
|
||||
"audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a",
|
||||
"beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e",
|
||||
"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_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831",
|
||||
"refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36",
|
||||
"refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5",
|
||||
"refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8",
|
||||
"refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3",
|
||||
"refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b",
|
||||
"render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c",
|
||||
"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_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b",
|
||||
"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,118 @@
|
||||
from pathlib import Path
|
||||
import os,json,time,hashlib,collections
|
||||
import numpy as np,cv2,shapely
|
||||
from shapely.geometry import shape,mapping
|
||||
from shapely.ops import transform
|
||||
from layer_common import O,S,sample,feature,parts
|
||||
from beta_profiles import POLICY,VERSION,describe,profiles,discover,endpoints
|
||||
from row_evidence import GaussianViews
|
||||
from row_profiles import pair,fit_chain,check_chain
|
||||
from transition_profiles import residual_sections
|
||||
from gost_catalog import assess_dash
|
||||
|
||||
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']};current=dict(original)
|
||||
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']
|
||||
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'])
|
||||
views=GaussianViews(tiles,labels,low,high,protected);transactions=[];diagnostics=[];domains=[]
|
||||
def poly(f):return shapely.force_2d(shape(f['geometry']))
|
||||
def linear(f):return 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)
|
||||
def make(p,kind,ids,**kw):return feature(lift(p),'road_marking',subtype='linear_marking',line_kind=kind,method=VERSION,source_ids=ids,standard_compliance='not_assessed',**kw)
|
||||
def commit(kind,ids,new,domain,ev,used,extra=None):
|
||||
before=[current[i]for i in ids];new=[f for f in new if not poly(f).is_empty];newids=[f['id']for f in new]
|
||||
if len(set(newids))!=len(newids)or any(i in current and i not in ids for i in newids):return False
|
||||
a=shapely.union_all([poly(f)for f in before]);b=shapely.union_all([poly(f)for f in new]);novel=b.difference(a)
|
||||
if a.symmetric_difference(b).area<POLICY['min_material_change_m2']:return False
|
||||
if novel.intersection(protected).area>POLICY['max_new_neighbor_overlap_m2']:return False
|
||||
if any(novel.intersection(poly(f)).area>POLICY['max_new_neighbor_overlap_m2']for i,f in current.items()if i not in ids and linear(f)):return False
|
||||
for i in ids:current.pop(i)
|
||||
for f in new:current[f['id']]=f
|
||||
rec=dict(kind=kind,source_ids=ids,output_ids=newids,before=before,after=new,bounds_xy=(shapely.union_all([a,b])if kind=='assembled-row'else domain).bounds,edit_domain=mapping(domain),evidence=ev,source_views=used,source_tiles=sorted(set(used[0])|set(used[1])),added_area_m2=float(novel.area),removed_area_m2=float(a.difference(b).area))
|
||||
if extra:rec.update(extra)
|
||||
transactions.append(rec);print('EDIT',len(transactions),kind,len(ids),'->',len(new),flush=True);return True
|
||||
|
||||
# Stage 1: every eligible existing axis seeds a 24m wider image search. Spatial
|
||||
# neighborhoods already covered by an accepted periodic model are not reworked.
|
||||
seeds=[]
|
||||
for fid,f in original.items():
|
||||
if not linear(f):continue
|
||||
rec=describe(poly(f))
|
||||
if rec is not None:seeds.append((fid,rec))
|
||||
proposals=[]
|
||||
for index,(fid,seed)in enumerate(sorted(seeds,key=lambda x:-x[1]['length'])):
|
||||
readers,used=views.readers(seed['origin'],seed['axis']);pv=profiles(seed,readers)
|
||||
found=discover(seed,pv);diagnostics.append(dict(seed_id=fid,stage='discover',profile_valid=pv is not None,proposals=len(found)))
|
||||
for r in found:r.update(seed_id=fid,source_views=used);proposals.append(r)
|
||||
if index%25==0:print('PROFILE',index+1,'/',len(seeds),'PROPOSALS',len(proposals),flush=True)
|
||||
|
||||
# Stage 2: one normalized row replaces only its observed longitudinal section.
|
||||
for r in sorted(proposals,key=lambda x:(-len(x['polygons']),-x['hi']+x['lo'])):
|
||||
domain=r['domain'];u=r['axis'];o=r['origin'];n=np.array([-u[1],u[0]]);origin=o+r['offset']*n
|
||||
if any(domain.intersection(d).area>.01 for d in domains):continue
|
||||
ids=[];residual=[]
|
||||
for fid,f in current.items():
|
||||
if not linear(f):continue
|
||||
p=poly(f);d=describe(p)
|
||||
if d is None or p.intersection(domain).area<.005 or abs(d['axis']@u)<np.cos(np.deg2rad(3))or abs((d['origin']-origin)@n)>.13:continue
|
||||
# Old complete stroke centers must agree with the new ridge; crossings
|
||||
# and a genuine neighboring stripe are not part of this row.
|
||||
ids.append(fid)
|
||||
for pp in parts(residual_sections(p,domain,o,u)):
|
||||
if pp.area>.000001:residual.append(make(pp,f['properties'].get('line_kind','solid'),[fid],role='unchanged-section'))
|
||||
if not ids:continue
|
||||
generated=[make(p,'dashed',ids,period_m=r['period'],dash_length_m=r['length'],width_m=r['width'],standard_assessment=assess_dash(r['length'],r['period'],r['width']),observed_stroke=True)for p in r['polygons']]
|
||||
before=shapely.union_all([poly(current[i])for i in ids]);new_strokes=sum(p.intersection(before).area/max(p.area,1e-9)<.35 for p in r['polygons'])
|
||||
ev=dict(paint=r['paint_evidence'],gaps=r['gap_evidence'],edges=r['edge_evidence'],observations=r['observations'],mode=r['mode'])
|
||||
if commit('periodic-row',ids,residual+generated,domain,ev,r['source_views'],dict(period_m=r['period'],dash_length_m=r['length'],newly_captured_strokes=new_strokes,normalized_strokes=len(generated),axis=u.tolist(),origin=o.tolist())):domains.append(domain)
|
||||
|
||||
# Stage 3: false solid ends and missed tails. Each edit needs visible paint and
|
||||
# the following dark interval in both mosaics, including at existing transitions.
|
||||
for fid in list(current):
|
||||
f=current.get(fid)
|
||||
if f is None or not linear(f)or f['properties'].get('line_kind')=='dashed':continue
|
||||
p=poly(f);seed=describe(p)
|
||||
if seed is None or seed['length']<2.7:continue
|
||||
readers,used=views.readers(seed['origin'],seed['axis']);pv=profiles(seed,readers,extension=2.5);changes=endpoints(seed,pv)
|
||||
if not changes:continue
|
||||
output=p;edit=[];ev=[]
|
||||
for c in changes:
|
||||
output=output.union(c['polygon'])if c['kind']=='extend-solid'else output.difference(c['domain'])
|
||||
edit.append(c['domain']);ev.append({k:c[k]for k in ['kind','delta','evidence']})
|
||||
if output.geom_type!='Polygon' or not output.is_valid:continue
|
||||
commit('solid-endpoints',[fid],[make(output,'solid',[fid])],shapely.union_all(edit),ev,used)
|
||||
|
||||
# Stage 4: run the qualified whole-row assembly against the new graph. Known
|
||||
# dashes and symbols remain barriers. All original fragments are fitted jointly.
|
||||
barriers=shapely.union_all([protected]+[poly(f)for f in current.values()if linear(f)and f['properties'].get('line_kind')=='dashed'])
|
||||
joinviews=GaussianViews(tiles,labels,low,high,barriers);initial={fid:poly(f)for fid,f in current.items()if linear(f)and f['properties'].get('line_kind')!='dashed'}
|
||||
groups={fid:[fid]for fid in initial};considered=set()
|
||||
while True:
|
||||
choices=[];entries=sorted(groups)
|
||||
for i,aid in enumerate(entries):
|
||||
for bid in entries[:i]:
|
||||
identity=tuple(sorted(groups[aid]+groups[bid]))
|
||||
if identity in considered:continue
|
||||
a,b=poly(current[aid]),poly(current[bid])
|
||||
if a.distance(b)>.56:continue
|
||||
q=pair(a,b)
|
||||
if q is not None:choices.append((abs(q['gap_m']),identity,aid,bid))
|
||||
accepted=False
|
||||
for _,identity,aid,bid in sorted(choices):
|
||||
considered.add(identity);r=fit_chain([initial[i]for i in identity])
|
||||
if r is None or r['polygon'].intersection(barriers).area>.005:continue
|
||||
readers,used=joinviews.readers(r['origin'],r['axis']);okay,ev=check_chain(r,readers)
|
||||
if not okay:continue
|
||||
p=r['output_polygon']
|
||||
if p.intersection(barriers).area>.005:continue
|
||||
f=make(p,'solid',[aid,bid],assembly_operation=r['operation'])
|
||||
if commit('assembled-row',[aid,bid],[f],r['edit_domain'],ev,used,dict(assembly_operation=r['operation'],max_axis_displacement_m=r['max_axis_displacement_m'])):
|
||||
groups.pop(aid);groups.pop(bid);groups[f['id']]=list(identity);accepted=True;break
|
||||
if not accepted:break
|
||||
if len(transactions)>1500:raise RuntimeError('Unbounded edits')
|
||||
|
||||
result={**old,'features':list(current.values()),'beta_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False))
|
||||
(O/'beta-rows.json').write_text(json.dumps(transactions,indent=2,allow_nan=False));(O/'beta-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes())
|
||||
counts=collections.Counter(r['kind']for r in transactions)
|
||||
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(transactions),stages=dict(counts),profiled_axes=len(seeds),proposed_periodic_rows=len(proposals),newly_captured_strokes=sum(r.get('newly_captured_strokes',0)for r in transactions),normalized_strokes=sum(r.get('normalized_strokes',0)for r in transactions),endpoint_extensions=sum(e['kind']=='extend-solid'for r in transactions if r['kind']=='solid-endpoints'for e in r['evidence']),endpoint_trims=sum(e['kind']=='trim-solid'for r in transactions if r['kind']=='solid-endpoints'for e in r['evidence']),before_linear_objects=sum(linear(f)for f in original.values()),after_linear_objects=sum(linear(f)for f in current.values()),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
|
||||
(O/'beta-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/'beta-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('beta-*.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='beta-%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/('beta-proof-%03d.jpg'%(start//4+1)),quality=94)
|
||||
(O/'beta-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,67 @@
|
||||
import json,runpy,numpy as np
|
||||
from interval_profiles import rectangle
|
||||
from beta_profiles import describe,profiles,discover,endpoints,fit_series
|
||||
prior=runpy.run_path('/candidate/test_rows.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()}
|
||||
o=np.zeros(2);u=np.array([1.,0.])
|
||||
def reader(intervals,offset=0,missing=None,underlay=0):
|
||||
def read(xy):
|
||||
x,y=xy.T;on=np.zeros(len(x),bool)
|
||||
for a,b in intervals:on|=(x>=a)&(x<=b)
|
||||
sig=(underlay+140*on)*np.exp(-.5*((y-offset)/.045)**2)
|
||||
rgb=np.repeat(np.clip(65+sig,0,255)[:,None],3,1).astype('uint8');valid=np.ones(len(x),bool)
|
||||
if missing is not None:valid[(x>missing[0])&(x<missing[1])]=False
|
||||
return rgb,valid
|
||||
return read
|
||||
dash=[(i,i+.5)for i in range(-4,9)]
|
||||
seed=describe(rectangle(o,u,0,.5,.12));read=reader(dash)
|
||||
fit=discover(seed,profiles(seed,[read,read]))
|
||||
checks['one_stroke_seeds_whole_short_row']=bool(fit)and len(fit[0]['polygons'])>=10
|
||||
checks['every_new_stroke_has_two_observed_edges']=bool(fit)and all(len(x['edges'])==2 for x in fit[0]['observations'])
|
||||
checks['one_view_cannot_authorize_row']=not discover(seed,profiles(seed,[read]))
|
||||
unknown=reader(dash,missing=(2,4))
|
||||
checks['unknown_slot_not_invented']=all(not 2.1<float(p.centroid.x)<3.9 for r in discover(seed,profiles(seed,[read,unknown]))for p in r['polygons'])
|
||||
absent=reader([x for x in dash if x[0]!=3])
|
||||
checks['visible_absent_stroke_not_invented']=all(not 3<float(p.centroid.x)<3.5 for r in discover(seed,profiles(seed,[read,absent]))for p in r['polygons'])
|
||||
neighbor=reader(dash,offset=.3)
|
||||
checks['neighbor_line_not_captured_as_seed']=profiles(seed,[neighbor,neighbor])is None
|
||||
shifted=reader(dash,offset=.1)
|
||||
checks['disagreeing_ridges_rejected']=profiles(seed,[read,shifted])is None
|
||||
solid=reader([(-20,20)])
|
||||
checks['continuous_paint_not_periodic']=not discover(seed,profiles(seed,[solid,solid]))
|
||||
irregular=reader([(0,.5),(1,1.5),(2.6,3.1),(4,4.5),(6,6.5)])
|
||||
checks['irregular_peaks_not_normalized']=not discover(seed,profiles(seed,[irregular,irregular]))
|
||||
longseed=describe(rectangle(o,u,0,3,.12));longread=reader([(i,i+3)for i in [-8,-4,0,4,8,12]])
|
||||
longfit=discover(longseed,profiles(longseed,[longread,longread]))
|
||||
checks['long_dash_family_reconstructed']=bool(longfit)and abs(longfit[0]['period']-4)<.1
|
||||
checks['period_is_measured_not_forced_to_standard']=bool(fit)and abs(fit[0]['period']-1)<.1
|
||||
under=reader(dash,underlay=40)
|
||||
ufit=discover(seed,profiles(seed,[under,under]))
|
||||
checks['regular_short_peaks_survive_faint_underlay']=bool(ufit)
|
||||
s=describe(rectangle(o,u,0,8,.12));r=reader([(0,9)])
|
||||
e=endpoints(s,profiles(s,[r,r],extension=2.5))
|
||||
checks['visible_solid_tail_extended']=any(x['kind']=='extend-solid'and x['sign']==1 for x in e)
|
||||
r2=reader([(0,7)])
|
||||
e2=endpoints(s,profiles(s,[r2,r2],extension=2.5))
|
||||
checks['false_solid_tail_trimmed']=any(x['kind']=='trim-solid'and x['sign']==1 for x in e2)
|
||||
hidden=reader([(0,9)],missing=(8.8,9.5))
|
||||
checks['mask_edge_not_paint_endpoint']=not endpoints(s,profiles(s,[r,hidden],extension=2.5))
|
||||
checks['endpoint_disagreement_rejected']=not endpoints(s,profiles(s,[r,r2],extension=2.5))
|
||||
def bent(xy):
|
||||
x,y=xy.T;center=np.where(x<7,0,np.minimum(.14,(x-7)*.2));on=(x>=0)&(x<=9)
|
||||
signal=140*on*np.exp(-.5*((y-center)/.04)**2)
|
||||
return np.repeat((65+signal)[:,None],3,1).astype('uint8'),np.ones(len(x),bool)
|
||||
checks['bent_tail_not_mistaken_for_dark_end']=not endpoints(s,profiles(s,[bent,bent],extension=2.5))
|
||||
offsetread=reader([(0,9)],offset=.1)
|
||||
checks['offset_paint_cannot_extend_old_axis']=not endpoints(s,profiles(s,[offsetread,offsetread],extension=2.5))
|
||||
nonstandard=reader([(i*1.65,i*1.65+.55)for i in range(-4,6)])
|
||||
nf=discover(seed,profiles(seed,[nonstandard,nonstandard]))
|
||||
checks['nonstandard_period_retained']=bool(nf)and abs(nf[0]['period']-1.65)<.1
|
||||
verylong=reader([(0,20)])
|
||||
checks['long_extrapolation_bounded']=not endpoints(s,profiles(s,[verylong,verylong],extension=2.5))
|
||||
checks['wide_seed_not_lane_stripe']=describe(rectangle(o,u,0,5,.5))is None
|
||||
checks['tiny_seed_not_lane_stripe']=describe(rectangle(o,u,0,.2,.1))is None
|
||||
theta=.83;R=np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]]);shift=np.array([120.,-63.])
|
||||
from shapely.geometry import Polygon
|
||||
sr=describe(Polygon(np.asarray(rectangle(o,u,0,.5,.12).exterior.coords)@R.T+shift));rr=lambda xy:read((xy-shift)@R)
|
||||
fr=discover(sr,profiles(sr,[rr,rr]));checks['rigid_transform_preserves_detected_row']=bool(fr)and len(fr[0]['polygons'])==len(fit[0]['polygons'])
|
||||
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/beta-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(dict(passed=result['passed'],tests=len(checks),failed=[k for k,v in checks.items()if not v])));assert result['passed']
|
||||
Reference in New Issue
Block a user