File size: 15,553 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
"""SDK IK and native motor targets for staged contact-only manipulation."""
import math
import numpy as np
import torch
from scipy.spatial.transform import Rotation, Slerp
from packages.sim2real.native.approach_motion import raised_wrist,convergence_status
from packages.sim2real.reach.grasp_geometry import pose_errors
from packages.sim2real.reach.solver_profile import arm_solver,CARRY_WRIST_XYZ,CARRY_WRIST_YAW_DEG,hand_targets,validate_plan_profile,posture_reference,seed_configuration
from packages.sim2real.native.joint_motion import joint_path
from packages.sim2real.native.arm_control import nominal_torso_target,limited_arm_position
from packages.sim2real.native.contact_closure import ContactClosure,CLOSURE_PROFILE
from isaaclab_arena_g1.g1_whole_body_controller.wbc_policy.g1_wbc_upperbody_ik.g1_wbc_upperbody_controller import G1WBCUpperbodyController


def tensor(value): return value if isinstance(value,torch.Tensor) else value.torch


class Manipulation:
    def __init__(self,robot,model,plan,target,robot_usd):
        validate_plan_profile(plan)
        if plan.get('contact_closure')!=CLOSURE_PROFILE or not plan.get('orient_after_alignment'):
            raise ValueError('Missing screened world alignment and contact closure profile')
        self.robot,self.model,self.plan,self.target=robot,model,plan,target
        self.robot_usd=robot_usd;self.entry_seed_q=None
        self.side=plan['pick']['side']
        self.frame=self.side+'_wrist_yaw_link'
        self.wrist_index=robot.body_names.index(self.frame)
        self.torso_index=robot.body_names.index('torso_link')
        model.cache_forward_kinematics(model.q_default,auto_clip=False)
        self.nominal_torso=model.frame_placement('torso_link').homogeneous.copy()
        from packages.sim2real.native.torso_frame import source_torso_frame
        self.torso_body_to_model,self.torso_frame_protocol=source_torso_frame(
            robot_usd,robot_usd.parent/'wbc_robot_model/g1_29dof_with_hand.urdf')
        self.solver=arm_solver(model)
        self.phase=None;self.started=0.;self.failed=None;self.held_transform=None
        self.pick_target=None;self.pick_target_started=None;self.closure=None;self.held_hand_targets=None
        self.grasp_control=None
        self.last_error=None
        self.desired_world=None;self.tracking_error=None;self.converged_since=None
        self.pre_step_torso=None;self.pre_step_torso_body=None;self.nominal_ik_target=None
        self.joint_path_control=None
        self.native_velocity_limits=tensor(robot.data.joint_vel_limits)[0].cpu().numpy().copy()
        self.arm_names=[name for name in model.joint_names if name.startswith(self.side+'_') and '_hand_' not in name
                        and any(j in name for j in ('shoulder','elbow','wrist'))]

    def pose(self,xyz,quat):
        result=np.eye(4);result[:3,3]=xyz;result[:3,:3]=Rotation.from_quat(quat).as_matrix()
        return result

    def wrist_world(self):
        return self.pose(tensor(self.robot.data.body_pos_w)[0,self.wrist_index].cpu().numpy(),
                         tensor(self.robot.data.body_quat_w)[0,self.wrist_index].cpu().numpy())

    def object_world(self):
        return self.pose(tensor(self.target.data.root_pos_w)[0].cpu().numpy(),
                         tensor(self.target.data.root_quat_w)[0].cpu().numpy())

    def enter(self,phase,now):
        if phase=='pregrasp' and self.phase is None: phase='raise_hand'
        if phase=='orient_hand':
            self.pick_target=self.endpoint_pose('pick').copy();self.pick_target_started=now
        self.phase,self.started=phase,now
        self.converged_since=None
        self.initial=self.wrist_world()
        if phase=='raise_hand' and self.plan.get('entry_self_collision_barrier'):
            from packages.sim2real.reach.barrier_solver import add_self_barrier
            actual=tensor(self.robot.data.joint_pos)[0].cpu().numpy()
            seed=self.model.q_default.copy()
            for name,value in zip(self.robot.joint_names,actual):
                seed[self.model.joint_to_dof_index[name]]=value
            seed_configuration(self.solver,seed)
            self.solver=add_self_barrier(self.solver,self.robot_usd,self.side)
            if self.solver.body_ik_solver.profile!=self.plan['entry_self_collision_barrier']:
                raise ValueError('Entry barrier differs from screened profile')
            self.entry_seed_q=seed.tolist()
        if phase=='orient_hand' and self.plan.get('entry_self_collision_barrier'):
            self.solver=arm_solver(self.model)
        if phase==self.plan.get('posture_reference_phase','pregrasp') and self.plan.get('posture_reference_q') is not None:
            posture_reference(self.solver,np.asarray(self.plan['posture_reference_q']))
        if phase=='descend' and self.plan.get('descent_posture_reference_q') is not None:
            posture_reference(self.solver,np.asarray(self.plan['descent_posture_reference_q']))
        if phase in {'retract','align_branch','orient_hand','descend'}:
            self.retract_start=self.model.q_default.copy()
            actual=tensor(self.robot.data.joint_pos)[0].cpu().numpy()
            for name,value in zip(self.robot.joint_names,actual):
                if name in self.arm_names:
                    self.retract_start[self.model.joint_to_dof_index[name]]=value
            if phase in {'orient_hand','descend'} and self.plan.get('align_branch'):
                seed_configuration(self.solver,self.retract_start)
            elif phase=='retract':
                self.solver=arm_solver(self.model)
        if phase=='close':
            self.closure=ContactClosure(self.side,now,self.object_world(),self.wrist_world())

    def endpoint_pose(self,endpoint):
        item=self.plan[endpoint]
        rotation=Rotation.from_euler('z',item['hand_yaw_rad']).as_matrix()
        result=np.eye(4);result[:3,:3]=rotation
        if endpoint=='pick':
            if self.pick_target is not None: return self.pick_target.copy()
            center=self.object_world()[:3,3]
            result[:3,3]=center-rotation@np.asarray(item['wrist_to_object_xyz_m'])
        elif self.held_transform is not None:
            obj=np.eye(4)
            obj[:3,:3]=Rotation.from_euler('z',item['hand_yaw_rad']-self.plan['pick']['hand_yaw_rad']).as_matrix()
            obj[:3,3]=self.plan['target_position_xyz_m']
            result=obj@np.linalg.inv(self.held_transform)
        else: raise ValueError('Placement requires measured held transform')
        return result

    def command(self,now,actions,contact_links,contact_vectors):
        if self.phase is None: return None
        elapsed=now-self.started
        root=self.pose(tensor(self.robot.data.root_pos_w)[0].cpu().numpy(),
                       tensor(self.robot.data.root_quat_w)[0].cpu().numpy())
        torso_body=self.pose(tensor(self.robot.data.body_pos_w)[0,self.torso_index].cpu().numpy(),
                        tensor(self.robot.data.body_quat_w)[0,self.torso_index].cpu().numpy())
        torso=torso_body@self.torso_body_to_model
        phase=self.phase;closed=phase not in {'raise_hand','orient_hand','pregrasp','align_branch','descend','release','retreat','place_hold'}
        durations={'raise_hand':4.,'orient_hand':3.,'pregrasp':4.,'align_branch':2.,'descend':3.,'close':2.,'lift':3.,'lift_hold':2.04,
                   'retract':3.,'carry_settle':4.,'lower_body':4.,'place_above':4.,'place_lower':3.,
                   'release':2.,'retreat':3.,'place_hold':2.04}
        desired=self.initial.copy()
        if phase=='raise_hand':
            desired=raised_wrist(self.initial,self.plan['source_support_z_m'])
        elif phase=='orient_hand':
            desired=self.endpoint_pose('pick')
            desired[:3,3]+=np.asarray(self.plan['pregrasp_offset_world_m'])
        elif phase in {'pregrasp','descend','close'}:
            desired=self.endpoint_pose('pick')
            if phase=='pregrasp': desired[:3,3]+=np.asarray(self.plan['pregrasp_offset_world_m'])
        elif phase in {'lift','lift_hold'}:
            desired=self.lift_target.copy()
        elif phase in {'retract','carry_settle','carry','lower_body'}:
            local=np.eye(4);local[:3,:3]=Rotation.from_euler('z',math.radians(CARRY_WRIST_YAW_DEG)).as_matrix()
            local[:3,3]=CARRY_WRIST_XYZ
            desired=root@local
        elif phase in {'place_above','place_lower','release'}:
            desired=self.endpoint_pose('place')
            if phase=='place_above': desired[2,3]+=.12
            elif phase=='place_lower': desired[2,3]+=.003
        elif phase in {'retreat','place_hold'}:
            desired=self.release_target.copy();desired[2,3]+=.15
            desired[:2,3]-=desired[:2,0]*.12
        duration=durations.get(phase,1.)
        alpha=min(1.,elapsed/duration)
        if phase not in {'close','lift_hold','carry','release','place_hold'}:
            desired[:3,3]=self.initial[:3,3]*(1-alpha)+desired[:3,3]*alpha
            desired[:3,:3]=Slerp([0,1],Rotation.from_matrix([self.initial[:3,:3],desired[:3,:3]]))([alpha]).as_matrix()[0]
        target_local=nominal_torso_target(self.nominal_torso,torso,desired)
        retract_q=None
        self.joint_path_control=None
        if phase in {'retract','align_branch'}:
            if phase=='retract' and self.plan.get('retract_motion')!='native_joint_interpolation':
                raise ValueError('Missing screened joint retraction')
            endpoint=self.retract_start.copy()
            for name in self.arm_names:
                index=self.model.joint_to_dof_index[name]
                endpoint[index]=self.plan['carry_q' if phase=='retract' else 'posture_reference_q'][index]
            native=self.model.pinocchio_wrapper.model
            retract_q=joint_path(self.retract_start,endpoint,alpha,native.lowerPositionLimit,native.upperPositionLimit)
            self.joint_path_control=dict(phase=phase,alpha=alpha,start_q=self.retract_start.tolist(),
                endpoint_q=endpoint.tolist(),requested_q=retract_q.tolist(),joint_names=list(self.model.joint_names))
            self.model.cache_forward_kinematics(retract_q,auto_clip=False)
            target_local=self.model.frame_placement(self.frame).homogeneous.copy()
            desired=torso@np.linalg.inv(self.nominal_torso)@target_local
        self.desired_world=desired.copy()
        self.pre_step_torso=torso.copy();self.pre_step_torso_body=torso_body.copy()
        self.nominal_ik_target=target_local.copy()
        self.tracking_error=pose_errors(self.wrist_world(),desired)
        q=retract_q if retract_q is not None else self.solver.inverse_kinematics(
            {self.frame:target_local},int(closed and self.side=='left'),int(closed and self.side=='right'))
        self.model.cache_forward_kinematics(q,auto_clip=False)
        error=float(np.linalg.norm(self.model.frame_placement(self.frame).translation-target_local[:3,3]))
        self.last_error=error
        for name in self.arm_names:
            index=self.robot.joint_names.index(name)
            requested=float(q[self.model.joint_to_dof_index[name]])
            current=float(actions[0,index])
            actions[0,index]=limited_arm_position(current,requested,.02,self.native_velocity_limits[index])
        closure_status=None
        for side in ('left','right'):
            values=hand_targets(side,closed and side==self.side)
            names=self.model.supplemental_info.left_hand_actuated_joints if side=='left' else self.model.supplemental_info.right_hand_actuated_joints
            if side==self.side and phase=='close':
                current=np.asarray([float(actions[0,self.robot.joint_names.index(name)]) for name in names])
                values,closure_status=self.closure.step(now,current,contact_links,self.object_world(),self.wrist_world(),self.tracking_error['passed'],contact_vectors)
            elif side==self.side and closed and self.held_hand_targets is not None:
                values=self.held_hand_targets
            for name,value in zip(names,values):
                index=self.robot.joint_names.index(name)
                current=float(actions[0,index]);actions[0,index]=max(current-.04,min(current+.04,float(value)))
        height=.75
        if phase in {'lower_body','place_above','place_lower','release','retreat','place_hold'}:
            target_height=self.plan['place']['geometry']['pelvis_height_m']
            height=.75+(target_height-.75)*(alpha if phase=='lower_body' else 1.)
        actions[0,-4]=height
        if phase=='close':
            if closure_status not in {'ready','waiting'}:
                self.failed='contact_closure_'+closure_status;return 'failed'
            if closure_status!='ready': return None
            self.held_hand_targets=np.asarray([float(actions[0,self.robot.joint_names.index(name)])
                for name in getattr(self.model.supplemental_info,self.side+'_hand_actuated_joints')])
            self.lift_target=self.wrist_world();self.lift_target[2,3]+=self.plan['lift_height_m']
            self.enter('lift',now);return None
        if elapsed+1e-8<duration or phase=='carry': return None
        if phase in {'raise_hand','orient_hand','pregrasp','align_branch','descend','lift','retract','carry_settle','place_above','place_lower','retreat'}:
            status,self.converged_since=convergence_status(now,self.started+duration+5.,
                self.tracking_error['passed'],self.converged_since)
            if status!='ready':
                if status=='failed':
                    self.failed='measured_wrist_tracking_timeout:'+phase
                    return 'failed'
                return None
        transitions={'raise_hand':'pregrasp','orient_hand':'descend','pregrasp':'align_branch' if self.plan.get('align_branch') else 'orient_hand',
                     'align_branch':'orient_hand','descend':'close','lift':'lift_hold',
                     'lift_hold':'retract','retract':'carry_settle','carry_settle':'carry','lower_body':'place_above',
                     'place_above':'place_lower','place_lower':'release','release':'retreat','retreat':'place_hold'}
        if phase=='lift_hold':
            displacement=self.object_world()[2,3]-self.plan['pick_position_xyz_m'][2]
            if displacement<.05 or sum(v>.1 for v in contact_links.values())<2:
                self.failed='physical_lift_or_finger_contact_gate';return 'failed'
            self.held_transform=np.linalg.inv(self.wrist_world())@self.object_world()
        if phase=='place_lower': self.release_target=self.wrist_world()
        if phase=='place_hold': return 'placed'
        self.enter(transitions[phase],now)
        return 'carry_ready' if self.phase=='carry' else None

    def grasp_control_record(self):
        return dict(pick_target_world_matrix=None if self.pick_target is None else self.pick_target.tolist(),
            pick_target_started_s=self.pick_target_started,
            closure_started_s=None if self.closure is None else self.closure.started,
            closure_ready_since_s=None if self.closure is None else self.closure.ready_since,
            closure_status=None if self.closure is None else self.closure.last_status,
            closure_force_diagnostics=None if self.closure is None else self.closure.force_diagnostics,
            closure_initial_object_matrix=None if self.closure is None else self.closure.object_initial.tolist(),
            held_hand_targets_rad=None if self.held_hand_targets is None else self.held_hand_targets.tolist())