Files
a7l20-hug-sim/scripts/elbow_raise_preflight.py

111 lines
5.8 KiB
Python

"""Fail-closed elbow-raise preflight and timing preview. NO motion interface.
--read-current subscribes to LEFT arm feedback only. Time parameterization is
an offline reference, not a claim that MoveJ follows the same trajectory.
"""
import argparse
import hashlib
import json
import math
import tempfile
import time
from pathlib import Path
import numpy as np
ROOT=Path(__file__).resolve().parents[1]
DEFAULT_PLAN=ROOT/'data/start_evidence_20260927T053837893105Z/elbow_raise_proposal.json'
def timing_preview(waypoints, speed=.03, acceleration=.05):
q=np.asarray(waypoints,float)
if q.ndim!=2 or q.shape[1]!=7 or len(q)<2 or not np.isfinite(q).all():
raise ValueError('Expected finite Nx7 path with at least two points')
if not 0<speed<=.03 or not 0<acceleration<=.05:
raise ValueError('Preview ceilings: 0.03rad/s and 0.05rad/s^2')
delta=np.abs(np.diff(q,axis=0)).max(axis=1)
if delta.max()>.00500001:raise ValueError('Waypoint step exceeds0.005rad')
# q(s)=q0+(3s²-2s³)dq. Starts/ends at rest; not jerk-limited.
duration=np.maximum.reduce([1.5*delta/speed,np.sqrt(6*delta/acceleration),np.full(len(delta),.1)])
return dict(interpolation='cubic smoothstep per segment; zero endpoint velocity',
time_from_start_s=np.r_[0,np.cumsum(duration)].tolist(),
maximum_speed_rad_s=float((1.5*delta/duration).max()),
maximum_acceleration_rad_s2=float((6*delta/duration**2).max()),
controller_interpolation_verified=False)
def check_start(samples,planned_start,now):
if len(samples)<10:raise ValueError('Fewer than10 fresh samples')
if now-samples[-1]['received']>.2 or now<samples[-1]['received']:
raise ValueError('Feedback stale or invalid receive time')
if samples[-1]['received']-samples[0]['received']<.5:
raise ValueError('Stationarity observation shorter than0.5s')
angles=[];stamps=[]
for row in samples:
js=row['state']['joint_state']
if js['name']!=[f'L{i}_joint' for i in range(1,8)]:raise ValueError('Wrong arm/joint order')
angles.append(js['position']);stamps.append(json.dumps(js['header']['stamp'],sort_keys=True))
q=np.asarray(angles,float);start=np.asarray(planned_start,float)
if q.shape!=(len(samples),7) or start.shape!=(7,) or not np.isfinite(q).all() or not np.isfinite(start).all():
raise ValueError('Invalid joints')
if len(set(stamps))<2:raise ValueError('Controller timestamps did not advance')
span=float(np.ptp(q,axis=0).max());error=float(np.abs(q-start).max())
if span>.002:raise ValueError(f'Arm not stationary: joint span {span:.6f}rad')
if error>.002:raise ValueError(f'Current start differs from plan by {error:.6f}rad')
return dict(status='arm_start_matches_only',max_joint_span_rad=span,max_start_error_rad=error,
latest_joints=q[-1].tolist(),samples=len(samples),controller_cache_excluded=False)
def read_samples():
import roslibpy
import threading
ros=roslibpy.Ros(host='192.168.10.21',port=9090);topic=None;samples=[];lock=threading.Lock()
def receive(message):
with lock:samples.append(dict(received=time.monotonic(),state=message))
try:
ros.run(timeout=8)
topic=roslibpy.Topic(ros,'/left/arm_state','lbot_arm_interfaces/msg/ArmState')
topic.subscribe(receive);deadline=time.monotonic()+3
while time.monotonic()<deadline:
with lock:
if len(samples)>=10 and samples[-1]['received']-samples[0]['received']>=.8:
return list(samples)
time.sleep(.02)
raise RuntimeError('Timed out waiting for fresh arm observations')
finally:
if topic is not None:topic.unsubscribe()
ros.terminate()
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--plan',type=Path,default=DEFAULT_PLAN)
parser.add_argument('--read-current',action='store_true')
args=parser.parse_args();payload=args.plan.read_bytes();plan=json.loads(payload)
from audit_finite_table_path import audit,JsonHandGeometry
spec=json.loads((ROOT/'config/finite_table_geometry.json').read_text())
geometry=None
if spec.get('evidence_verified') is True and all(spec.get(k) is not None for k in ['top_center_base_m','rotation_table_to_base','size_xyz_m','uncertainty_m']):
raw=json.loads((ROOT/'data/left_hand_open_q10r1mak/result.json').read_text())['final_feedback']
geometry=JsonHandGeometry(raw)
table_audit=audit(plan,spec,geometry)
report=dict(executable=False,motion_sent=False,plan=str(args.plan.resolve()),
finite_table_check=table_audit,
plan_sha256=hashlib.sha256(payload).hexdigest(),timing=timing_preview(plan['waypoints']),
start_check={'status':'not_requested'},
blockers=[f"Finite table path status: {table_audit['status']} (not a physical collision assertion).",
'Controller trajectory interpolation and stop/timeout behavior not verified.',
'Live hand posture has not been checked against the fixed-hand plan.',
'No hardware execution adapter is provided; do not send preview waypoints as MoveJ commands.'])
if args.read_current:
try:
samples=read_samples();report['raw_arm_samples']=samples
report['start_check']=check_start(samples,plan['waypoints'][0],time.monotonic())
except Exception as exc:report['start_check']={'status':'rejected','reason':str(exc)}
output=Path(tempfile.mkdtemp(prefix='elbow_raise_preflight_',dir=ROOT/'data'))/'report.json'
output.write_text(json.dumps(report,indent=2))
print(json.dumps({k:report[k] for k in ['executable','timing','start_check','blockers']},indent=2))
print(output)
if __name__=='__main__':main()