Files
NODEDC_MISSION_CORE/simulation/urban-plan-research/systematic/refine_markings.py
T
DCCONSTRUCTIONS 69dc566665 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.
2026-10-29 09:10:00 +03:00

249 lines
18 KiB
Python

"""Resolve finite image strokes before fitting complete repeated marking rows."""
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
from search_views import SearchViews
from discovery_rules import unpack,uncovered
from beta_profiles import describe,discover,section_evidence,profiles,corridor_dark,supported
from beta_profiles import POLICY as PROFILE_POLICY
from marking_profiles import diagnose_profiles
from line_reconstruction import rows
from interval_profiles import rectangle,runs
from marking_rules import VERSION,POLICY,plan_replacement,validate_removed,join_continuous,isolated_addition
from gost_catalog import assess_dash
from paired_markings import proposal as paired_proposal
from finite_strokes import replacement as finite_replacement
from observed_geometry import missing_parts
from stroke_seeds import from_component
from paint_conservation import PaintConservation
from family_ownership import FamilyOwnership,admitted_domain,unowned_bodies
def measured_width(p):
# Metadata describes the admitted polygon, including short legitimate dashes.
# Proposal-size predicates must never be reused as a metadata parser.
coordinates=np.asarray(shapely.force_2d(p).minimum_rotated_rectangle.exterior.coords)
return float(np.min(np.linalg.norm(np.diff(coordinates,axis=0),axis=1)))
def main():
cv2.setNumThreads(3);start=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());current={f['id']:f for f in old['features']}
poly=lambda f:shapely.force_2d(shape(f['geometry']))
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([poly(f).convex_hull for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'])
views=SearchViews(tiles,labels,low,high,protected)
proposal_path=Path('/searchplan/search-proposals.json');proposals=json.loads(proposal_path.read_text());records=[unpack(r)for r in proposals['lines']]
def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
joint_mode=os.environ.get('STROKE_ASSEMBLY','joint')=='joint'
existing_geometry=None;existing_calls=0;existing_builds=0
def existing():
nonlocal existing_geometry,existing_calls,existing_builds
existing_calls+=1
# Joint configuration collection keeps current immutable until select().
# Reuse that exact ordered union, with no refit, rounding or reordering.
# Greedy control can mutate current, so it retains the original evaluation.
if not joint_mode or existing_geometry is None:
existing_geometry=shapely.union_all([poly(f)for f in current.values()if f['properties']['class']=='road_marking'])
existing_builds+=1
return existing_geometry
conservation=PaintConservation();ownership=FamilyOwnership()
transactions=[];accepted_domains=[];candidates=[];paired=[];stats=collections.Counter();seen=[];admission_trace=[]
seeds=[from_component(r['polygon'])for r in records]
seeds +=[from_component(poly(f))for f in old['features']if f['properties'].get('subtype')=='linear_marking']
for row in rows(records):
if len(row['records'])<3:continue
o,u=row['origin'],row['axis'];ts=(row['points']-o)@u;L=float(np.ptp(ts))
if 1<L<70:seeds.append(dict(origin=o+(ts.min()+ts.max())/2*u,axis=u,length=L,width=.12))
# Every primary appearance component can propose a thin stroke. Proposal
# selection cannot discard a candidate merely because a larger unverified
# outline overlaps it. The existing evidence gates still decide admission.
appearance=json.loads(Path('/primary/observations.json').read_text())['paint']
# One canonical axis per raw component. The expanded two-estimator bank
# remains archived for causal evaluation, not a second production search.
from primary_components import collect as primary_components
appearance_seeds,axis_plan=primary_components(appearance)
seeds += appearance_seeds
(O/'primary-axis-plan.json').write_text(json.dumps(axis_plan,indent=2))
print('PRIMARY_AXES',axis_plan,flush=True)
seeds=[s for s in seeds if s is not None]
for s in seeds:s['original_seed']=True
unique={}
for seed in seeds:
u=seed['axis'];u=u if u[0]>0 or (u[0]==0 and u[1]>=0) else -u
key=tuple(np.round(np.r_[seed['origin'],u,seed['length'],seed['width']],6))
unique.setdefault(key,seed)
seeds=list(unique.values())
from stroke_observations import ordered
ordered_seeds=sorted(seeds,key=lambda r:(int(np.argmin(np.linalg.norm(views.centers-r['origin'],axis=1))),not r.get('original_seed',True),-r['length']))
import gzip,pickle
identity_paths=[baseline,proposal_path,Path('/primary/observations.json'),Path('/evidence_plan/fields.npz'),S/'tile-index.json',Path('/ortho/observation-coverage.json'),Path('/ortho/native-geometry/native-geometry.json')]
observation_identity={str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in identity_paths if p.is_file()}
measurement_modules=['stroke_observations.py','row_discovery.py','stroke_seeds.py','component_axis.py','primary_components.py','measured_rows.py','measured_row_graph.py','body_profiles.py','beta_profiles.py','marking_profiles.py','interval_profiles.py','measurement_reads.py','observation_cache.py','row_evidence.py','search_views.py','fit_scene.py','layer_common.py','discovery_evidence.py','paired_markings.py','marking_rules.py']
observation_identity['measurement_sources']={name:hashlib.sha256(Path(__file__).with_name(name).read_bytes()).hexdigest() for name in measurement_modules}
seed_plan=[dict(origin=r['origin'].tolist(),axis=r['axis'].tolist(),length=r['length'],width=r['width'],original=r.get('original_seed',True)) for r in ordered_seeds]
observation_identity['seed_plan']=hashlib.sha256(json.dumps(seed_plan,sort_keys=True,allow_nan=False).encode()).hexdigest()
bank_identity=hashlib.sha256(json.dumps(observation_identity,sort_keys=True).encode()).hexdigest()
bank_path=os.environ.get('STROKE_BANK_INPUT')
if bank_path:
# Internal frozen observation artifact from this Gaussian run only.
bank=pickle.loads(gzip.decompress(Path(bank_path).read_bytes()))
assert bank['baseline_sha256']==hashlib.sha256(baseline.read_bytes()).hexdigest()
assert bank['observation_identity']==bank_identity, 'Observation bank belongs to different inputs'
paired,candidates,seen,stats=bank['paired'],bank['candidates'],bank['seen'],collections.Counter(bank['stats'])
else:
for si,observation in enumerate(ordered(ordered_seeds,int(os.environ.get('STROKE_WORKERS','4')))):
stats.update(observation['stats']);domain=observation['domain']
if domain is None:continue
seen.append(domain)
legacy_suppressed=any(domain.intersection(shapely.union_all(r['polygons'])).area>=domain.area*.98 for r in paired if r.get('original_bank',True))
for pair in observation['paired']:
pair['original_bank']=pair.get('original_bank',True) and not legacy_suppressed
paired.append(pair)
candidates.extend(observation['candidates'])
if si%80==0:print('PROFILE',si+1,len(seeds),'CANDIDATES',len(candidates),flush=True)
bank=dict(observation_identity=bank_identity,observation_inputs=observation_identity,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),paired=paired,candidates=candidates,seen=seen,stats=dict(stats))
(O/'measured-bank.pkl.gz').write_bytes(gzip.compress(pickle.dumps(bank,protocol=5),compresslevel=1))
if os.environ.get('STROKE_BANK_ONLY')=='1':return
if os.environ.get('STROKE_BANK','expanded')=='original':
candidates=[r for r in candidates if r.get('original_bank',True)]
paired=[r for r in paired if r.get('original_bank',True)]
configurations=[]
# Measurement workers have exited; reuse immutable pixels during ordered
# admission without repeatedly decoding distant tiles after each candidate.
from observation_cache import ObservationCache
admission_pixels=ObservationCache(views.inputs,6*1024**3)
views.inputs=admission_pixels
from measurement_reads import FrameReads
admission_frames=FrameReads(views.readers)
views.readers=admission_frames
def commit(r,ids,polys,operation,evidence):
if not polys:return False
if not ownership.allows(ids):stats['partial-measured-family-veto']+=1;return False
before=[current[i]for i in ids];a=shapely.union_all([poly(f)for f in before]);b=shapely.union_all(polys)
if b.intersection(protected).area>.005:return False
if a.symmetric_difference(b).area<.015:return False
if ids:
readers,_=views.readers(r['origin'],r['axis'])
retained,lineage=conservation.validate(ids,current,poly,b,r,readers)
if not retained:stats['ancestral-positive-paint-veto']+=1;return False
evidence={**evidence,'conservation':lineage}
rest=existing() if not ids else shapely.union_all([poly(f)for i,f in current.items()if i not in ids and f['properties']['class']=='road_marking'])
if b.intersection(rest).area>.005:return False
fs=[]
family_hash=hashlib.sha256(b.wkb).hexdigest()[:20]
for p in polys:
body_width=measured_width(p)
props=dict(subtype='linear_marking',line_kind='dashed'if r['kind']=='periodic-row'else'observed-continuous',method=VERSION,source_ids=ids,source_tiles=r['source_tiles'],width_m=body_width,family_id=family_hash,standard_compliance='not_assessed',observed_paint=True)
if r['kind']=='periodic-row':
measured_length=float(np.ptp((shapely.get_coordinates(p)-r['origin'])@r['axis']))
props.update(period_m=r['period'],dash_length_m=measured_length,family_dash_length_m=r['length'],standard_assessment=assess_dash(measured_length,r['period'],body_width))
else:props['endpoint_authority']='two-view-dark-endpoints' if r['kind']=='observed-finite' else 'observed_window_not_physical_end'
fs.append(feature(lift(p),'road_marking',**props))
if len(set(f['id']for f in fs))!=len(fs)or any(f['id']in current and f['id']not in ids for f in fs):return False
if joint_mode:
configurations.append(dict(kind=operation,source_ids=list(ids),output_ids=[f['id'] for f in fs],before=before,after=fs,
evidence=evidence,source_tiles=r['source_tiles'],source_views=r['source_views'],profile_mode=r['profile_mode'],family_id=family_hash,
bounds_xy=b.union(a).bounds,domain=mapping(admitted_domain(r,polys)) if r['kind']=='periodic-row' else None,
atomic_family=r['kind'] in {'periodic-row','observed-pair'}))
return True
conservation.committed(ids,current,poly,fs)
ownership.committed(ids,fs,r['kind']in {'periodic-row','observed-pair'})
for i in ids:del current[i]
for f in fs:current[f['id']]=f
transactions.append(dict(kind=operation,source_ids=ids,output_ids=[f['id']for f in fs],before=before,after=fs,bounds_xy=b.union(a).bounds,evidence=evidence,source_tiles=r['source_tiles'],source_views=r['source_views'],profile_mode=r['profile_mode'],family_id=family_hash))
if r['kind']=='periodic-row':accepted_domains.append(admitted_domain(r,polys))
print('EDIT',len(transactions),operation,len(ids),'->',len(fs),flush=True);return True
# Admit complete adjacent tracks as a joint object. A measured companion is
# checked with its dark separator and outer edge, never mistaken for asphalt.
for r in sorted(paired,key=lambda r:-sum(p.area for p in r['polygons'])):
plan=plan_replacement(r,current)
if plan is not None:
ids,polys=plan;readers,used=views.readers(r['origin'],r['axis'])
retained,removed=validate_removed(shapely.union_all([poly(current[i])for i in ids]),shapely.union_all(polys),r,readers)
if retained and commit(r,ids,polys,'whole-observed-pair',dict(pair=r['evidence'],removed=removed)):continue
commit(r,[],[p for p in r['polygons']if uncovered(p,existing())],'observed-pair-additions',dict(pair=r['evidence']))
# Prefer complete measured families. A family may replace old fragments only
# when every removed paint sample is either retained or visibly dark in both views.
for r in sorted(candidates,key=lambda r:(r['kind']!='periodic-row',-len(r['polygons']))):
if r['kind']!='periodic-row':continue
overlaps_measured_family=any(r['domain'].intersection(d).area>.005 for d in accepted_domains)
ev=dict(paint=r['paint_evidence'],gaps=r['gap_evidence'],observations=r['observations'],measured_bodies=r['measured_body_evidence'],measured_gaps=r['measured_gap_evidence'])
plan=None if overlaps_measured_family else plan_replacement(r,current)
if plan is not None:
ids,polys=plan;readers,used=views.readers(r['origin'],r['axis']);okay,removed=validate_removed(shapely.union_all([poly(current[i])for i in ids]),shapely.union_all(polys),r,readers)
if okay and commit(r,ids,polys,'whole-periodic-family',{**ev,'removed':removed}):continue
stats['family-replacement-veto']+=1
# Keep positive additions even when a pre-existing erroneous outline cannot
# safely be removed. Protected or overlapping paint is never stacked twice.
polygons=[p for p in unowned_bodies(r['polygons'],accepted_domains)if uncovered(p,existing())]
commit(r,[],polygons,'observed-periodic-additions',ev)
# Finite measured objects replace fragments atomically after the same strip
# checks and explicit conservation of all removed positive paint.
from marking_rules import check_strip
for r in sorted(candidates,key=lambda r:-sum(p.area for p in r['polygons'])):
if r['kind']!='observed-finite':continue
p=r['polygons'][0]
readers,used=views.readers(r['origin'],r['axis']);okay,ev=check_strip(p,readers)
trace=dict(geometry=mapping(p),strip_passed=okay,strip=ev,source_tiles=r['source_tiles'])
admission_trace.append(trace)
if not okay:stats['finite-strip-veto']+=1;trace['reason']='strip';continue
evidence=dict(profile=r['paint_evidence'],strip=ev,endpoints=r['edge_evidence'])
if p.intersection(existing()).area>.005:
ids,removed=finite_replacement(r,current,readers);trace['replacement']=removed
if ids is not None and commit(r,ids,[p],'whole-observed-finite-stroke',{**evidence,'removed':removed}):trace['reason']='replaced';continue
trace['reason']='ownership';stats['finite-ownership-veto']+=1;continue
if isolated_addition(p,current):
trace['reason']='added'if commit(r,[],[p],'observed-finite-stroke',evidence)else'transaction'
else:stats['finite-seam-veto']+=1;trace['reason']='seam'
for r in sorted(candidates,key=lambda r:-sum(p.area for p in r['polygons'])):
if r['kind']!='observed-continuous':continue
whole=r['polygons'][0]
if whole.intersection(existing()).area>.005:
readers,used=views.readers(r['origin'],r['axis']);whole_ok,whole_ev=check_strip(whole,readers)
if whole_ok:
ids,removed=finite_replacement(r,current,readers)
if ids is not None and commit(r,ids,[whole],'whole-observed-continuous-stroke',dict(profile=r['paint_evidence'],strip=whole_ev,removed=removed)):continue
for p in missing_parts(whole,existing()):
# Recheck the entire admitted strip, with dark flanks, in two per-point mosaics.
from marking_rules import check_strip
readers,used=views.readers(r['origin'],r['axis']);okay,ev=check_strip(p,readers)
if okay:
ids,joined=join_continuous(p,current)
if ids:
joined_ok,joined_ev=check_strip(joined,readers);a=shapely.union_all([poly(current[i])for i in ids]);retained,removed=validate_removed(a,joined,r,readers)
if joined_ok and retained:commit(r,ids,[joined],'observed-continuous-extension',dict(profile=r['paint_evidence'],strip=joined_ev,removed=removed))
else:stats['continuous-join-veto']+=1
elif isolated_addition(p,current):commit(r,[],[p],'observed-continuous-addition',dict(profile=r['paint_evidence'],strip=ev))
else:stats['unresolved-seam-veto']+=1
else:stats['strip-veto']+=1
joint_report=None
if joint_mode:
from joint_assembly import select
from primary_evidence import collect as primary_evidence
from connected_configurations import compose
junctions,junction_report=compose(configurations,lift)
configurations.extend(junctions)
current,transactions,joint_report=select(old,configurations,primary_evidence(appearance,proposals['lines']))
joint_report['connected_junctions']=junction_report
(O/'configuration-bank.json').write_text(json.dumps(configurations,allow_nan=False))
(O/'joint-selection.json').write_text(json.dumps(joint_report,indent=2,allow_nan=False))
result={**old,'features':list(current.values()),'marking_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'marking-rows.json').write_text(json.dumps(transactions,indent=2,allow_nan=False))
report=dict(scene=os.environ['SCENE'],baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),proposal_sha256=hashlib.sha256(proposal_path.read_bytes()).hexdigest(),policy=POLICY,policy_version=VERSION,manual_rois=[],point_clouds=False,seconds=time.monotonic()-start,profiled_axes=len(seen),profile_stats=dict(stats),candidate_pairs=len(paired),candidate_families=sum(r['kind']=='periodic-row'for r in candidates),transactions=len(transactions),stages=dict(collections.Counter(r['kind']for r in transactions)),removed_objects=sum(len(r['before'])for r in transactions),output_objects=sum(len(r['after'])for r in transactions),net_objects=len(result['features'])-len(old['features']))
report['assembly_contract']=dict(version='immutable-measured-configurations-v1',mode='joint' if joint_mode else 'greedy-control',bank=os.environ.get('STROKE_BANK','expanded'),source_observations_immutable=True,old_control_as_input=False)
report['existing_geometry_reuse']=dict(calls=existing_calls,builds=existing_builds,maximum_retained_unions=1,joint_only=True)
report['admission_pixel_cache']=admission_pixels.report()
report['admission_frames']=admission_frames.report()
(O/'finite-stroke-admission.json').write_text(json.dumps(admission_trace,allow_nan=False))
(O/'marking-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
if __name__=='__main__':main()