"""Measured axis and paint-preserving ownership contracts.""" from pathlib import Path import json import numpy as np from shapely.geometry import mapping from interval_profiles import rectangle from stroke_axis import measure from finite_strokes import replacement from marking_rules import check_strip def image(angle=0,missing=False,extra=False,half_length=.45,sigma=.055): axis=np.array([np.cos(angle),np.sin(angle)]);normal=np.array([-axis[1],axis[0]]) def read(xy): t=xy@axis;n=xy@normal signal=100*np.exp(-.5*(n/sigma)**2)/(1+np.exp(np.clip((abs(t)-half_length)/.015,-50,50))) if extra:signal=np.maximum(signal,90*((abs(xy[:,0])<.15)&(xy[:,1]>.12)&(xy[:,1]<.25))) rgb=np.repeat(np.clip(70+signal[:,None],0,255),3,axis=1).astype('uint8') return rgb,np.full(len(xy),not missing,dtype=bool) return read def run(): seed=dict(origin=np.zeros(2),axis=np.array([1.,0.]),length=.9,width=.12) angle=np.deg2rad(11) corrected,report=measure(seed,[image(angle),image(angle)]) assert report['reason']=='measured' and abs(report['angle_change_degrees']-11)<1 assert np.array_equal(seed['axis'],[1.,0.]) rejected,reason=measure(seed,[image(angle),image(angle,missing=True)]) assert rejected is seed and reason['reason']!='measured' p=rectangle(np.zeros(2),np.array([1.,0.]),-.45,.45,.12) candidate=dict(polygons=[p],origin=np.zeros(2),axis=np.array([1.,0.])) feature=lambda poly:dict(id='fragment',geometry=mapping(poly),properties=dict(**{'class':'road_marking'},subtype='linear_marking')) current={'fragment':feature(rectangle(np.zeros(2),np.array([1.,0.]),-.3,.3,.12))} okay,ev=check_strip(p,[image(),image()]);assert okay ids,positive=replacement(candidate,current,[image(),image()]);assert ids==['fragment'] protruding=rectangle(np.zeros(2),np.array([1.,0.]),-.15,.15,.12,offset=.19) old=p.union(protruding);current={'fragment':feature(old)} ids,negative=replacement(candidate,current,[image(extra=True),image(extra=True)]) assert ids is None and negative['reason']=='positive-or-unobserved-removed-paint' ids,unknown=replacement(candidate,current,[image(missing=True),image(missing=True)]) assert ids is None from measured_rows import measured_rows lengths=[.35,.55,.75];centers=[0.,1.2,2.4] row=dict(kind='periodic-row',mode='intervals',domain=rectangle(np.zeros(2),np.array([1.,0.]),-.5,3.,.3),origin=np.zeros(2),axis=np.array([1.,0.]),width=.12,offset=0., polygons=[rectangle(np.zeros(2),np.array([1.,0.]),c-.25,c+.25,.12)for c in centers], observations=[dict(edges=[[c-L/2,c+L/2],[c-L/2,c+L/2]])for c,L in zip(centers,lengths)]) def measured_image(missing=False): def read(xy): bright=np.zeros(len(xy),bool) for c,L in zip(centers,lengths):bright|=(abs(xy[:,0]-c)<=L/2)&(abs(xy[:,1])<=.06) rgb=np.repeat(np.where(bright,200,50).astype('uint8')[:,None],3,axis=1) valid=np.ones(len(xy),bool) if missing:valid[abs(xy[:,0]-centers[1])<.15]=False return rgb,valid return read from beta_profiles import profiles row_seed=dict(origin=np.zeros(2),axis=np.array([1.,0.]),length=6.,width=.12) actual=measured_rows([row],profiles(row_seed,[measured_image()]*2)) assert len(actual)==1 and len(actual[0]['polygons'])==3 np.testing.assert_allclose([p.bounds[2]-p.bounds[0]for p in actual[0]['polygons']],lengths) rejected=measured_rows([row],profiles(row_seed,[measured_image(),measured_image(missing=True)])) assert not rejected,'A missing second view entered the measured family' from paint_conservation import PaintConservation geometry=lambda f:__import__('shapely').geometry.shape(f['geometry']) proof=dict(origin=np.zeros(2),axis=np.array([1.,0.])) readers=[image(half_length=.8),image(half_length=.8)] from marking_rules import validate_removed # Three permitted local shifts cannot accumulate beyond the original # positive paint footprint, even though each last-to-next check passes. wide=lambda x:rectangle(np.zeros(2),np.array([1.,0.]),-.8+x,.8+x,.3) conservation=PaintConservation();objects={'first':dict(id='first',geometry=mapping(wide(0)),properties={})} successor=dict(id='second',geometry=mapping(wide(.05)),properties={}) conservation.committed(['first'],objects,geometry,[successor]);objects={'second':successor} third=dict(id='third',geometry=mapping(wide(.10)),properties={}) conservation.committed(['second'],objects,geometry,[third]);objects={'third':third} assert validate_removed(wide(.10),wide(.15),proof,readers)[0] assert not conservation.validate(['third'],objects,geometry,wide(.15),proof,readers)[0] from stroke_seeds import from_component broad=rectangle(np.zeros(2),np.array([1.,0.]),-1.5,1.5,.8) proposal=from_component(broad);assert proposal is not None and proposal['width']>.35 assert from_component(rectangle(np.zeros(2),np.array([1.,0.]),-.4,.4,.8))is None import stroke_observations as measurement import shapely class Views: def __init__(self,read):self.read=read def readers(self,origin,axis):return [self.read,self.read],[{},{}] measurement.protected=shapely.GeometryCollection() measurement.views=Views(image(half_length=1.4)) small={**seed,'length':1.7} measured=measurement.observe(small) runs=[r for r in measured['candidates']if r['kind']=='observed-continuous'] assert any(r['polygons'][0].length>5.4 for r in runs),'Observed body was clipped to its seed' assert any(check_strip(r['polygons'][0],[image(half_length=1.4)]*2)[0]for r in runs) measurement.views=Views(image(half_length=1.4,sigma=.3)) assert not measurement.observe(proposal)['candidates'],'Broad paint was admitted as a thin line' measurement.views=Views(image(missing=True,half_length=1.4)) assert not measurement.observe(small)['candidates'] from stroke_inventory import deduplicate from line_reconstruction import observation short=rectangle(np.zeros(2),np.array([1.,0.]),-.3,.3,.12) long=rectangle(np.zeros(2),np.array([1.,0.]),-2.,2.,.12) inputs=[observation(np.asarray(p.exterior.coords),str(i))for i,p in enumerate([short,long,short])] kept=deduplicate(inputs) assert len(kept)==2 and any(r['L']<1 for r in kept)and any(r['L']>3 for r in kept) evidence=dict(passed=True,axis=report,retained_fragment=positive,positive_removed=negative,missing_view=unknown,whole_body_unclipped=True,broad_proposal_not_admitted=True) Path('/out/stroke-contract.json').write_text(json.dumps(evidence,indent=2)) print('STROKE_CONTRACT_OK',json.dumps(evidence),flush=True) if __name__=='__main__':run() from qualify_family_ownership import run as qualify_family_ownership qualify_family_ownership()