File size: 8,944 Bytes
3ea69ef | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | # plan: [stages 1-3] card held; card aligned above slot; card seated and released
# origin=fresh
"""A state-feedback program for the registered Franka/OSC GPU-install task.
Only env.step(action) changes the world. No dataset, checkpoint, reset, state
restoration, controller replacement, or scene-parameter writes are used.
"""
import json
import math
from pathlib import Path
DART_SIGMA = 0.03
SOLVE_PARAMS = {'DART_SIGMA': None}
ENTRIES = {'start': 'unassembled card upright in holder, hand free',
'preinsert': 'card genuinely held, above front entry, clear of all contacts'}
def solve(env, entry=None, stop_after=None) -> None:
import torch
from isaaclab.utils.math import (
axis_angle_from_quat, quat_apply, quat_conjugate, quat_mul,
)
params = json.loads(Path(__file__).with_name('parameters.json').read_text())
scene, robot = env.scene, env.robot
art = robot.articulation
dev, n = env.device, env.num_envs
assert n == 1, 'This initial phase-1 delivery handles one environment per process'
osc = robot.controller.controllers[0]
assert type(osc).__name__ == 'OperationalSpaceController'
assert robot.action_dim == 8
hand = art.body_names.index('panda_hand')
dt = env.dt * robot.control_period
offset = float(scene.GRASP_PINCH_OFFSET)
zero = torch.zeros(3, device=dev)
integral_p, integral_r = zero.clone(), zero.clone()
steps = 0
active_phase = 'start'
if entry not in (None, 'start', 'preinsert'): raise ValueError(entry)
def v(values): return torch.tensor(values, device=dev, dtype=torch.float32)
def mul(a,b): return quat_mul(a[None],b[None])[0]
def inv(q): return quat_conjugate(q[None])[0]
def rotate(q,x): return quat_apply(q[None],x[None])[0]
def orientation_error(goal,current):
if float(torch.dot(goal,current)) < 0: goal = -goal
return axis_angle_from_quat(mul(goal, inv(current))[None])[0]
def hp(): return art.data.body_pos_w[0,hand].clone()
def hq(): return art.data.body_quat_w[0,hand].clone()
def cp(): return scene.card.data.root_pos_w[0].clone()
def cq(): return scene.card.data.root_quat_w[0].clone()
def held(): return bool(scene.grasp_held[0].any())
def pinch(): return hp() + rotate(hq(),v([0,0,offset]))
def band(): return cp()+rotate(cq(),v([-.020,sum(scene.CARD_BODY_Y)/2,.1005]))
def log(phase,**extra):
print('PHASE1 '+json.dumps(dict(phase=phase,steps=steps,seconds=steps*dt,
held=held(),card=cp().tolist(),hand=hp().tolist(),
offset=scene._card_offset_in_case()[0].tolist(),
depth=float(scene.engaged()[0]),integral_position=integral_p.tolist(),
integral_rotation=integral_r.tolist(),**extra)),flush=True)
def tick(goal,quat,finger):
nonlocal integral_p, integral_r, steps
ep, er = goal-hp(), orientation_error(quat,hq())
integral_p=(integral_p+ep*dt).clamp(-.10,.10)
integral_r=(integral_r+er*dt).clamp(-4.0,4.0)
dp=ep+params['integral_position']*integral_p
dr=er+params['integral_rotation']*integral_r
dr=dr*min(1,2.5/max(float(dr.norm()),1e-9))
action=torch.zeros((1,8),device=dev)
action[0,:3]=(dp/osc.cfg.pos_scale).clamp(-6,6)
action[0,3:6]=(dr/osc.cfg.rot_scale).clamp(-20,20)
action[0,6:]=finger
# The preset smooths pose DELTAS, rather than absolute targets. Account
# for its documented filter in the command; never write controller state.
if params.get('compensate_action_filter',False) and osc._prev_action is not None:
alpha=float(osc.cfg.ema_factor)
action[0,:6]=(action[0,:6]-(1-alpha)*osc._prev_action[0])/alpha
assert torch.isfinite(action).all()
# Noise offered independently of noise_scale. Recorder keeps labels clean.
disturbance = torch.zeros_like(action)
if active_phase in ('lift_clear', 'transport_waypoint', 'above_case') and float(hp()[2]) > .38:
disturbance[0, :3] = DART_SIGMA * torch.randn(3, device=dev)
env.step(action, noise=disturbance)
steps+=1
def move(goal_fn,grip,timeout,tag,tol=.002,rot_tol=.035,card_check=None):
nonlocal active_phase
active_phase = tag
ref=hp(); good=0
for _ in range(max(1,math.ceil(timeout/dt))):
goal,quat=goal_fn()
delta=goal-ref; length=float(delta.norm())
ref=ref+delta*min(1,params['speed']*dt/max(length,1e-9))
tick(ref,quat,grip)
goal,quat=goal_fn()
ok=float((hp()-goal).norm())<tol and float(orientation_error(quat,hq()).norm())<rot_tol
if card_check is not None:ok=ok and card_check()
good=good+1 if ok else 0
if good>=8:log(tag,result='reached');return
log(tag,result='timeout',position_error=float((hp()-goal).norm()),rotation_error=float(orientation_error(quat,hq()).norm()))
raise RuntimeError('Stage did not reach its measured gate: '+tag)
def hold(goal_fn,finger,seconds):
nonlocal active_phase
active_phase = 'hold'
for _ in range(math.ceil(seconds/dt)):
goal,quat=goal_fn();tick(goal,quat,finger)
log('start')
if entry != 'preinsert':
# Stage 1: acquire the top band and verify a real grasp.
down=[mul(cq(),v([0,0,1,0])),mul(cq(),v([0,1,0,0]))]
pick_q=max(down,key=lambda q:abs(float(torch.dot(q,hq())))).clone()
def pick_goal(height=0):
return band()-rotate(pick_q,v([0,0,offset]))+v([0,0,height]),pick_q
move(lambda:pick_goal(.10),.04,18,'above_card',tol=.004,rot_tol=.05)
move(pick_goal,.04,16,'pinch_aligned',tol=.0025)
for k in range(math.ceil(2/dt)):
goal,quat=pick_goal()
tick(goal,quat,.04+(.0172-.04)*min(1,(k+1)*dt/1.5))
hold(pick_goal,.0172,1)
if not held():log('grasp_failed');raise RuntimeError('No grasp after controlled closure')
log('card_held')
elif not held():
raise RuntimeError('preinsert entry requires an actual grasp')
rel_p=rotate(inv(hq()),cp()-hp())
rel_q=mul(inv(hq()),cq())
def card_goal(position,quat):
# The grasp joint fixes this measured card-in-hand transform. A fixed
# world-frame hand goal avoids moving the goal in response to its own lag.
target_q=mul(quat,inv(rel_q))
return position-rotate(target_q,rel_p),target_q
def case_point(local):
return scene.case.data.root_pos_w[0]+rotate(scene.case.data.root_quat_w[0],v(local))
case_q=scene.case.data.root_quat_w[0].clone()
seat=list(scene.cfg.seat_pos)
forward=seat[0]+params['forward_clearance']
if entry != 'preinsert':
lift=cp();lift[2]=float(scene.cfg.surface_z)+params['carry_height']
move(lambda:card_goal(lift,case_q),.0172,25,'lift_clear',tol=.003)
if not held():raise RuntimeError('Grasp lost during lift')
# Different plan: side staging stop, then transfer to the case entry.
waypoint=cp(); waypoint[0]=.34; waypoint[1]=-.14
waypoint[2]=float(scene.cfg.surface_z)+params['carry_height']
move(lambda:card_goal(waypoint,case_q),.0172,30,'transport_waypoint',tol=.003)
# Stage 2: enter forward of the rear panel, then slide through its cutout.
high=[forward,seat[1],params['carry_height']-float(scene.cfg.case_lift)]
move(lambda:card_goal(case_point(high),case_q),.0172,40,'above_case',tol=.003)
if stop_after == 'above_case': return
above=[forward,seat[1],float(scene.cfg.slot_mouth_z)+params['slide_height']]
move(lambda:card_goal(case_point(above),case_q),.0172,20,'inside_case',tol=.002)
aligned=[seat[0],seat[1],above[2]]
def card_aligned():
return float((cp()-case_point(aligned)).norm())<.0007 and float(orientation_error(case_q,cq()).norm())<.004
move(lambda:card_goal(case_point(aligned),case_q),.0172,30,'slot_aligned',tol=.0004,rot_tol=.003,card_check=card_aligned)
# Stage 3: press, release, retract, then leave the installed card unsupported.
pressed=[seat[0],seat[1],seat[2]-.001]
active_phase='press'
press_z=aligned[2]
for _ in range(math.ceil(25/dt)):
press_z=max(pressed[2],press_z-params['press_speed']*dt)
target,quat=card_goal(case_point([seat[0],seat[1],press_z]),case_q)
tick(target,quat,.0172)
if bool(scene.seated()[0]):break
if not bool(scene.seated()[0]):log('press_failed');raise RuntimeError('Card did not seat')
log('seated_before_release')
keep=hp(); keep_q=hq()
hold(lambda:(keep,keep_q),.04,2)
up=keep+v([0,0,.14])
move(lambda:(up,keep_q),.04,16,'hand_clear',tol=.004,rot_tol=.06)
hold(lambda:(up,keep_q),.04,5)
log('finished',seated=bool(scene.seated()[0]))
if held() or not bool(scene.seated()[0]):raise RuntimeError('Card did not remain seated after release')
|