#!/usr/bin/python3 """Validate noise against independently interpolated physics; no fabricated time or IMU truth input.""" import argparse,json,os,sys,time,hashlib from pathlib import Path import numpy as np import yaml import rclpy from check_omni_robot import Sim,sim_env, shutdown_probe from check_mid360 import SensorProbe,phase,interpolate,rotate,scene_shapes,ray_ranges,json_value def main(): ap=argparse.ArgumentParser();ap.add_argument('--out',required=True);ap.add_argument('--profile',choices=('mild','stress'),default='stress');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') config=Path(__file__).resolve().parents[1]/'src/r2027_robot_description/config/sensor_profiles.yaml' profile=yaml.safe_load(config.read_text())[args.profile] (out/'sensor_profiles.yaml').write_bytes(config.read_bytes());(out/'collector_snapshot.py').write_bytes(Path(__file__).read_bytes()) report=dict(status='INVALID',profile=args.profile,parameters=profile);sim=Sim(str(out/'sim'));p=None try: ok,why=sim.start(lidar=True,drive='contact',sensor_model='mid360',sensor_profile=args.profile,spawn=(-4.5,4.5,.15,0.));report['startup']=why if not ok:raise RuntimeError(why) rclpy.init();p=SensorProbe() if not p.wait_clock():raise RuntimeError('no clock') p.pump(2.);stationary=phase(p,(0.,0.,0.),3.);moving=phase(p,(.2,0.,0.),2.);final=phase(p,(0.,0.,0.),1.) records=dict(stationary=stationary,moving=moving,final=final) (out/'physics.json').write_text(json.dumps(records,indent=2)+'\n') imus=[m for m in p.imus if stationary['t0']+.2.1)&(expected_range<40) residuals.extend((distance-expected_range)[valid]);saved['xyz_%d'%j]=xyz;saved['expected_%d'%j]=expected_range errors=np.array(residuals) statuses=[s for s in p.sensor_status if 'candidate_hits' in s];candidates=sum(s['candidate_hits'] for s in statuses);dropped=sum(s['dropped'] for s in statuses) times=np.array([m['t'] for m in imus]);std=profile['range_stddev'];checks=dict( physical_excitation=moving['states'][-1]['pos'][0]-moving['states'][0]['pos'][0]>.3, imu_bias=np.all(abs(accel.mean(axis=0)-profile['accel_bias'])<5*profile['accel_stddev']/np.sqrt(len(accel))+.002) and np.all(abs(gyro.mean(axis=0)-profile['gyro_bias'])<5*profile['gyro_stddev']/np.sqrt(len(gyro))+.00005), imu_stddev=np.all(abs(accel.std(axis=0)/profile['accel_stddev']-1)<.2) and np.all(abs(gyro.std(axis=0)/profile['gyro_stddev']-1)<.2), range_noise=len(errors)>2000 and abs(errors.mean())<.1*std and .85000 and abs(dropped/candidates-profile['dropout'])<5*np.sqrt(profile['dropout']*(1-profile['dropout'])/candidates), packet_accounting=bool(statuses) and all(s['candidate_hits']==s['returns']+s['dropped']+s['range_rejected'] and s['rays']==20000 for s in statuses), acquisition_times=all(np.all(f['offsets']%1000000==0) and max(f['offsets'])<=99000000 and f['timebase']==round(f['t']*1e9) for f in frames), imu_times=np.min(np.diff(times))>0 and np.max(np.diff(times))<.02 and abs((len(times)-1)/(times[-1]-times[0])-200)<2, no_attitude_oracle=all(m['orientation_covariance_0']==-1 for m in imus)) report.update(checks=checks,accel_mean=accel.mean(axis=0).tolist(),accel_stddev=accel.std(axis=0).tolist(),gyro_mean=gyro.mean(axis=0).tolist(),gyro_stddev=gyro.std(axis=0).tolist(), range_residual_mean_m=float(errors.mean()),range_residual_stddev_m=float(errors.std()),sampled_range_returns=len(errors),dropped=dropped,candidates=candidates,dropout_fraction=dropped/candidates,sensor_status=statuses) report.update(imu_mean_rate_hz=float((len(times)-1)/(times[-1]-times[0])),imu_interval_range_s=[float(np.diff(times).min()),float(np.diff(times).max())]) np.savez_compressed(out/'observations.npz',imu_times=times,accel_residual=accel,gyro=gyro,range_residual=errors,**saved) report['status']='PASS' if all(checks.values()) else 'FAIL';print(report['status'],checks,flush=True) except Exception as e:report['error']=repr(e);print(report['error'],flush=True) finally: report['ros_cleanup_errors'] = shutdown_probe(p) report['teardown']=sim.stop();(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n') return dict(PASS=0,FAIL=30,INVALID=40)[report['status']] if __name__=='__main__':sys.exit(main())