#!/usr/bin/python3 """Independent regression for dual-lidar self-occlusion and clearance evidence. Analytic intersections inspect the generated collision SDF, rather than treating missing self returns (which are filtered downstream) as proof of clear sight. Gazebo navigation remains a separate runtime check. """ import math from pathlib import Path import unittest import xml.etree.ElementTree as ET import numpy as np import xacro from check_dual_lidar import rectangle_gap,swept_clearance MODEL=Path(__file__).resolve().parents[1]/'src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro' def rotation(rpy): r,p,y=rpy;cr,sr=math.cos(r),math.sin(r);cp,sp=math.cos(p),math.sin(p);cy,sy=math.cos(y),math.sin(y) return np.array([[cy*cp,cy*sp*sr-sy*cr,cy*sp*cr+sy*sr], [sy*cp,sy*sp*sr+cy*cr,sy*sp*cr-cy*sr],[-sp,cp*sr,cp*cr]]) def collision_parts(root): # The supported proxy is one rigid body with primitive collisions. links=root.findall('.//model/link') if len(links)!=1 or not np.allclose(np.fromstring(links[0].findtext('pose','0 0 0 0 0 0'),sep=' '),0.): raise ValueError('ray acceptance must be extended for changed link transforms') parts=[] for collision in links[0].findall('collision'): pose=np.fromstring(collision.findtext('pose','0 0 0 0 0 0'),sep=' ') geometry=collision.find('geometry');shape=next(iter(geometry)) if shape.tag not in ('box','cylinder'):raise ValueError('unsupported collision shape '+shape.tag) parts.append((pose[:3],rotation(pose[3:]),shape)) return parts def first_hit(parts,origin,direction): candidates=[] for center,R,shape in parts: p=R.T@(origin-center);v=R.T@direction if shape.tag=='box': half=np.fromstring(shape.findtext('size'),sep=' ')/2;lo,hi=-float('inf'),float('inf') for j in range(3): if abs(v[j])<1e-12: if abs(p[j])>half[j]:hi=-float('inf');break else: bounds=sorted(((-half[j]-p[j])/v[j],(half[j]-p[j])/v[j])) lo=max(lo,bounds[0]);hi=min(hi,bounds[1]) if hi>=max(lo,0.):candidates.append(max(lo,0.)) else: radius=float(shape.findtext('radius'));half=float(shape.findtext('length'))/2 a=float(v[:2]@v[:2]);b=2*float(p[:2]@v[:2]);c=float(p[:2]@p[:2])-radius**2 discriminant=b*b-4*a*c if a>1e-14 and discriminant>=0: for t in ((-b-math.sqrt(discriminant))/(2*a),(-b+math.sqrt(discriminant))/(2*a)): if t>=0 and abs(p[2]+t*v[2])<=half+1e-12:candidates.append(t) if abs(v[2])>1e-12: for z in (-half,half): t=(z-p[2])/v[2] if t>=0 and np.linalg.norm(p[:2]+t*v[:2])<=radius+1e-12:candidates.append(t) return min(candidates,default=float('inf')) class ModelSightTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.text=xacro.process_file(str(MODEL),mappings={'dual_lidar':'true','lidar':'true','sensor_model':'mid360','drive':'contact'}).toxml() cls.root=ET.fromstring(cls.text);cls.parts=collision_parts(cls.root) cls.origin=np.fromstring(cls.root.findtext(".//plugin[@name='mid360_low_sensor']/lidar_position"),sep=' ') def test_forward_horizontal_and_downward_rays_clear_proxy(self): # Low-obstacle returns lie below the optical plane. Test the complete # -7..0 degree band at 0.5 degree elevation / 0.25 degree azimuth steps. blocked=[] for elevation in np.deg2rad(np.linspace(-7.,0.,15)): for azimuth in np.linspace(-math.pi/2,math.pi/2,721): v=np.array([math.cos(elevation)*math.cos(azimuth),math.cos(elevation)*math.sin(azimuth),math.sin(elevation)]) if first_hit(self.parts,self.origin,v)<2.:blocked.append((azimuth,elevation)) self.assertEqual(blocked,[]) def test_rear_stays_physically_occluded(self): self.assertAlmostEqual(first_hit(self.parts,self.origin,np.array([-1.,0.,0.])),.705,places=9) def test_historical_wheels_reproduce_front_occlusion(self): root=ET.fromstring(self.text) for collision in root.findall('.//collision'): if 'wheel' in collision.attrib['name']: pose=np.fromstring(collision.findtext('pose'),sep=' ');pose[0]=math.copysign(.30,pose[0]) collision.find('pose').text=' '.join(map(str,pose)) parts=collision_parts(root);blocked=[] for azimuth in np.linspace(-math.pi/2,math.pi/2,721): v=np.array([math.cos(azimuth),math.sin(azimuth),0.]) if first_hit(parts,self.origin,v)<2.:blocked.append(azimuth) self.assertGreater(len(blocked),0) class ClearanceTests(unittest.TestCase): def test_known_axis_aligned_gaps_and_overlap(self): self.assertAlmostEqual(rectangle_gap([.7,0.],0.,[0.,0.]),.175) self.assertAlmostEqual(rectangle_gap([.5,0.],0.,[0.,0.]),-.025) self.assertAlmostEqual(rectangle_gap([.525,0.],0.,[0.,0.]),0.) def test_rotated_rectangle_does_not_use_enclosing_aabb(self): self.assertGreater(rectangle_gap([.65,.65],math.pi/4,[0.,0.]),.17) self.assertLess(.65-.125-.4*math.sqrt(2),0.) # AABB would falsely overlap. def test_between_sample_collision_cannot_hide_behind_clear_endpoints(self): states=[dict(stamp=t,pos=[x,0.,.15],yaw=0.) for t,x in ((0.,-1.),(.1,1.))] self.assertGreater(rectangle_gap(states[0]['pos'],0.,[0.,0.]),0.) self.assertGreater(rectangle_gap(states[1]['pos'],0.,[0.,0.]),0.) result=swept_clearance(states,[0.,0.]);self.assertLess(result['min_gap_bound_m'],0.) def test_clearance_covers_rotation_corners(self): states=[dict(stamp=t,pos=[0.,0.,.15],yaw=y) for t,y in ((0.,0.),(.1,math.pi/2))] self.assertGreater(rectangle_gap([0.,0.],0.,[.65,0.]),0.) self.assertLess(swept_clearance(states,[.65,0.])['min_gap_bound_m'],0.) if __name__=='__main__':unittest.main()