#!/usr/bin/python3 """Independent geometry, acquisition-time and specific-force acceptance, no truth into LIO.""" import argparse import hashlib import json import math import os from pathlib import Path import sys import time import xml.etree.ElementTree as ET import numpy as np import rclpy from livox_ros_driver2.msg import CustomMsg from sensor_msgs.msg import Imu from std_msgs.msg import String from rclpy.qos import qos_profile_sensor_data from check_omni_robot import Sim,sim_env, shutdown_probe from check_slope_drive import SlopeProbe ROOT=Path(__file__).resolve().parents[2] MOUNT=np.array([.015,0.,.33]) def json_value(value): if isinstance(value,np.generic):return value.item() raise TypeError('unsupported evidence value: '+type(value).__name__) def rotate(q,v): """Quaternion xyzw, row vectors, broadcasting allowed.""" return v+2*np.cross(q[..., :3],np.cross(q[..., :3],v)+q[...,3,None]*v) def interpolate(states,times): times=np.asarray(times) ts=np.array([s['stamp'] for s in states]) # Duplicate state samples are legal; select distinct independent query times. ts,idx=np.unique(ts,return_index=True);states=[states[i] for i in idx] if np.min(times)ts[-1]:raise ValueError('no bracketing independent truth') hi=np.clip(np.searchsorted(ts,times,side='right'),1,len(ts)-1);lo=hi-1 if np.max(ts[hi]-ts[lo])>.12:raise ValueError('truth gap exceeds 120 ms') w=(times-ts[lo])/(ts[hi]-ts[lo]) pos=np.array([s['pos'] for s in states]);q=np.array([s['quaternion'] for s in states]) qa,qb=q[lo],q[hi];qb=np.where(np.sum(qa*qb,axis=-1,keepdims=True)<0,-qb,qb) qq=qa+(qb-qa)*w[:,None];qq/=np.linalg.norm(qq,axis=-1,keepdims=True) return pos[lo]+(pos[hi]-pos[lo])*w[:,None],qq def scene_shapes(model_path=None): """Read authoritative static primitives and triangles; independent of ODE ray code.""" base=ROOT/'sim_ws/src/robocon_gazebo/models/robocon_ground_full' result=[] if model_path is not None:base=Path(model_path).parent for c in ET.parse(base/'model.sdf' if model_path is None else model_path).findall('.//collision'): p=np.fromstring(c.findtext('pose','0 0 0 0 0 0'),sep=' ') r,pitch,y=p[3:];cx,sx=np.cos(r),np.sin(r);cy,sy=np.cos(pitch),np.sin(pitch);cz,sz=np.cos(y),np.sin(y) R=np.array([[cz*cy,cz*sy*sx-sz*cx,cz*sy*cx+sz*sx], [sz*cy,sz*sy*sx+cz*cx,sz*sy*cx-cz*sx],[-sy,cy*sx,cy*cx]]) geom=c.find('geometry');box=geom.find('box');cylinder=geom.find('cylinder');mesh=geom.find('mesh') if box is not None:shape=('box',np.fromstring(box.findtext('size'),sep=' ')/2) elif cylinder is not None:shape=('cylinder',(float(cylinder.findtext('radius')),float(cylinder.findtext('length'))/2)) elif mesh is not None: path=base/'meshes'/Path(mesh.findtext('uri')).name vertices=[];faces=[] for line in path.read_text().splitlines(): if line.startswith('v '):vertices.append(list(map(float,line.split()[1:]))) if line.startswith('f '):faces.append([int(s.split('/')[0])-1 for s in line.split()[1:]]) vertices=np.array(vertices)*np.fromstring(mesh.findtext('scale','1 1 1'),sep=' ') shape=('mesh',vertices[np.array(faces)]) else:raise ValueError('unhandled scene geometry') result.append((p[:3],R,*shape)) return result def ray_ranges(origins,directions,shapes): best=np.full(len(origins),np.inf) for center,R,kind,value in shapes: o=(origins-center)@R;d=directions@R if kind=='box': safe=np.where(np.abs(d)>1e-12,d,1e-12) a=(-value-o)/safe;b=(value-o)/safe enter=np.max(np.minimum(a,b),axis=1);leave=np.min(np.maximum(a,b),axis=1) hit=np.where((leave>=np.maximum(enter,0))&(enter>0),enter,np.inf) elif kind=='cylinder': radius,height=value A=np.sum(d[:,:2]**2,axis=1);B=2*np.sum(o[:,:2]*d[:,:2],axis=1) C=np.sum(o[:,:2]**2,axis=1)-radius**2;disc=B*B-4*A*C hit=np.full(len(o),np.inf) for sign in (-1,1): t=(-B+sign*np.sqrt(np.maximum(disc,0)))/np.maximum(2*A,1e-20) good=(disc>=0)&(t>0)&(np.abs(o[:,2]+t*d[:,2])<=height) hit=np.minimum(hit,np.where(good,t,np.inf)) for z in (-height,height): t=(z-o[:,2])/np.where(np.abs(d[:,2])>1e-12,d[:,2],1e-12) xy=o[:,:2]+t[:,None]*d[:,:2] hit=np.minimum(hit,np.where((t>0)&(np.sum(xy**2,axis=1)<=radius**2),t,np.inf)) else: hit=np.full(len(o),np.inf) for a,b,c in value: e1,e2=b-a,c-a;h=np.cross(d,e2);det=h@e1 safe=np.where(np.abs(det)>1e-12,det,1e-12);s=o-a u=np.sum(s*h,axis=1)/safe;q=np.cross(s,e1);v=np.sum(d*q,axis=1)/safe t=q@e2/safe good=(np.abs(det)>1e-12)&(u>=0)&(v>=0)&(u+v<=1)&(t>0) hit=np.minimum(hit,np.where(good,t,np.inf)) best=np.minimum(best,hit) return best def vehicle_ranges(directions): """Independent local ray/box intersection, including physical roof returns. Measured roof=.41 m, retained base=.15 m, assumed body bottom=.07 m. Raw self hits are valid sensor observations, not outliers to hide. """ body=[(np.array([0.,0.,.09]),np.eye(3),'box',np.array([.4,.4,.17]))] return ray_ranges(np.broadcast_to(MOUNT,directions.shape),directions,body) class SensorProbe(SlopeProbe): def __init__(self): super().__init__();self.frames=[];self.imus=[];self.sensor_status=[] self.create_subscription(CustomMsg,'/sim/mid360/lidar',self.on_frame,qos_profile_sensor_data) self.create_subscription(Imu,'/sim/mid360/imu',self.on_imu,qos_profile_sensor_data) self.create_subscription(String,'/sim/mid360/status',lambda m:self.sensor_status.append(json.loads(m.data)),10) def on_frame(self,m): self.frames.append(dict(t=m.header.stamp.sec+m.header.stamp.nanosec*1e-9, timebase=int(m.timebase),frame=m.header.frame_id,point_num=m.point_num, xyz=np.array([[p.x,p.y,p.z] for p in m.points]), offsets=np.array([p.offset_time for p in m.points],dtype=np.uint32), line=np.array([p.line for p in m.points],dtype=np.uint8), tag=np.array([p.tag for p in m.points],dtype=np.uint8))) def on_imu(self,m): a=m.linear_acceleration;w=m.angular_velocity self.imus.append(dict(t=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,frame=m.header.frame_id, acc=[a.x,a.y,a.z],gyro=[w.x,w.y,w.z],orientation_covariance_0=m.orientation_covariance[0])) def phase(p,cmd,duration): t0=p.now();states=[p.get_state()];nxt=t0 def sample(): nonlocal nxt if p.now()states[0]['stamp']+.15 and f['t']+.1.98 and np.quantile(e,.95)<.005 and np.quantile(e,.99)<.02)) def main(): ap=argparse.ArgumentParser();ap.add_argument('--out',required=True) ap.add_argument('--case',choices=('flat','slope'),default='flat');args=ap.parse_args() out=Path(args.out).resolve();out.mkdir(parents=True,exist_ok=True) os.environ.update(sim_env());os.environ['ROS_LOG_DIR']=str(out/'ros') sim,p=Sim(str(out/'sim')),None source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source) result=dict(status='INVALID',case=args.case,checks={},collector_sha256=hashlib.sha256(source).hexdigest()) wall=time.monotonic() try: spawn=(1.4,3.5125,.6,0.) if args.case=='slope' else (-4.5,4.5,.17,0.) ok,why=sim.start(lidar=True,drive='contact',sensor_model='mid360',spawn=spawn) result['startup']=why if not ok:raise RuntimeError(why) rclpy.init();p=SensorProbe() if not p.wait_clock():raise RuntimeError('no clock') p.pump(1.5) if len(p.frames)<5 or len(p.imus)<100:raise RuntimeError('missing lidar or IMU stream') records={};shapes=scene_shapes() records['stationary']=phase(p,(0.,0.,0.),2.) for name,cmd,duration in ([] if args.case=='slope' else [ ('forward',(.3,0.,0.),2.5),('lateral',(0.,-.2,0.),1.5),('turn',(0.,0.,.3),2.)]): records[name]=phase(p,cmd,duration) records['stop']=phase(p,(0.,0.,0.),.5) # Finish live collection before CPU-heavy offline ray intersections. # Otherwise the probe's own analysis can overflow its IMU receive queue. if args.case=='flat': if not p.set_state(-4.5,4.5,1.2,0.):raise RuntimeError('drop set failed') drop=phase(p,(.3,0.,0.),.23) free=[m for m in p.imus if drop['t0']+.04500 for f in frames) checks['finite_fov']=all(np.isfinite(f['xyz']).all() and np.min(np.arctan2(f['xyz'][:,2],np.linalg.norm(f['xyz'][:,:2],axis=1)))>=math.radians(-7)-1e-6 and np.max(np.arctan2(f['xyz'][:,2],np.linalg.norm(f['xyz'][:,:2],axis=1)))<=math.radians(52)+1e-6 for f in frames) checks['timebase']=all(abs(f['t']*1e9-f['timebase'])<1 for f in frames) checks['actual_batch_times']=all(np.min(f['offsets'])>=0 and np.max(f['offsets'])<100000000 and len(np.unique(f['offsets']))>50 and np.all(f['offsets']%1000000==0) and np.all(np.diff(f['offsets'].astype(np.int64))>=0) for f in frames) checks['frame_rate']=len(frames)>5 and np.max(np.abs(np.diff([f['t'] for f in frames])-.1))<1e-6 checks['livox_flags']=all(np.max(f['line'])<4 and np.all(f['tag']==0x10) for f in frames) checks['ray_budget']=len(p.sensor_status)>5 and all(s['rays']==20000 and s['last_sample_ns']-s['first_sample_ns']==99000000 for s in p.sensor_status) checks['pattern_continues']=not np.allclose(frames[0]['xyz'][:100],frames[1]['xyz'][:100]) st=records['stationary'];imu=[m for m in p.imus if st['t0']+.20 and np.max(imu_intervals)<.02) if args.case=='flat': tr=records['turn'];moving=[m for m in p.imus if tr['t0']+.3100 and abs(np.median([m['gyro'][2] for m in moving])-.3)<.02 checks['real_scan_distortion']=max(geometry[n]['instantaneous_p95_error_m'] for n in ('forward','turn'))>.015 checks['free_fall_imu']=len(free)>20 and np.quantile([np.linalg.norm(m['acc']) for m in free],.95)<.05 else: checks['slope_physically_tilted']=abs(np.median([s['rpy'][1] for s in st['states']])-math.atan2(.597,3.5))<.02 result.update(geometry=geometry,records=records,imus=p.imus,sensor_status=p.sensor_status, stationary_imu_p95_error_m_s2=float(np.quantile(stationary_error,.95)), stationary_imu_mean=np.mean(acc,axis=0).tolist(),frame_returns=[len(f['xyz']) for f in frames], measured_imu_rate_hz=float(imu_rate),maximum_imu_interval_s=float(np.max(imu_intervals)), sim_duration_s=p.now()-records['stationary']['t0'],wall_duration_s=time.monotonic()-wall) result['status']='PASS' if all(checks.values()) else 'FAIL' print(json.dumps(dict(status=result['status'],checks=checks,geometry=geometry),indent=2,default=json_value),flush=True) except Exception as exc: result['status']='INVALID';result['error']=repr(exc);print(result['error'],flush=True) finally: result['ros_cleanup_errors'] = shutdown_probe(p) result['teardown']=sim.stop() (out/'result.json').write_text(json.dumps(result,indent=2,default=json_value)+'\n') return {'PASS':0,'FAIL':30,'INVALID':40}[result['status']] if __name__=='__main__':sys.exit(main())