File size: 7,144 Bytes
0a3f650
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""StackPyramid expert that picks A and places it next to B instead of dragging it.

The native expert (and lim.expert_stack_pyramid) drags A along the table by
friction under closed fingers pressed on its top. Executed by the keypose rule
the press is the vertical part of a capped straight step toward the push
endpoint, so on long pushes it is small and A slips from under the fingers
(lim.expert_stack_pyramid executed online: 265 of 1,294 attempts pushed short).
Here A is picked and placed, as in the StackCube expert:

- A is moved when it is more than MOVE_IF_M (xy) from B. Its placement is
  PLACE_GAP_M from B's centre along the one of B's four face normals that
  points most towards A among those leaving at least C_CLEARANCE_M to C; A is
  turned about the vertical so its faces line up with B's.
- A's grasp and placement are chosen together, lexicographically: open
  fingers landing at least FINGER_CLEARANCE_M from B and C; closing axis,
  after the turn, perpendicular to the placement direction, so no finger is
  lowered or opened in the gap between A and B; the spot at least
  C_CLEARANCE_M from C; the direction pointing most towards A. The first
  choice whose grasp is reachable (native +-angle order) is taken.
- C is grasped on the face pair whose open-finger footprints keep the larger
  clearance from A and B first; for reachability the native order of
  +-angles is kept.
- After releasing A the TCP rises straight up to LIFT_Z_M.
C is then grasped, lifted and placed over the midpoint of A's and B's tops
exactly as in the native expert.
"""

import numpy as np
import sapien
from mani_skill.examples.motionplanning.base_motionplanner.utils import compute_grasp_info_by_obb, get_actor_obb
from mani_skill.examples.motionplanning.panda.motionplanner import PandaArmMotionPlanningSolver
from transforms3d.euler import euler2quat

from lim.expert_stack_pyramid import clearance, yaw_of

MOVE_IF_M = 0.055
PLACE_GAP_M = 0.05
C_CLEARANCE_M = 0.06
FINGER_CLEARANCE_M = 0.01
LIFT_Z_M = 0.10
FINGER_LENGTH = 0.025
APPROACHING = np.array([0, 0, -1])


def wrap_quarter(angle):
    """Angle wrapped to [-pi/4, pi/4) (cube symmetry about the vertical)."""
    return (angle + np.pi / 4) % (np.pi / 2) - np.pi / 4


def grasp_pose_for(env, planner, actor, others):
    """Top grasp of `actor`, face pair ranked by finger clearance from `others`, first reachable angle."""
    target_closing = env.agent.tcp.pose.to_transformation_matrix()[0, :3, 1].cpu().numpy()
    info = compute_grasp_info_by_obb(get_actor_obb(actor), approaching=APPROACHING,
                                     target_closing=target_closing, depth=FINGER_LENGTH)
    base = env.agent.build_grasp_pose(APPROACHING, info["closing"], info["center"])
    neighbours = [(o.pose.sp.p[:2], yaw_of(o)) for o in others]
    order = sorted((0.0, np.pi / 2), key=lambda angle: -clearance(
        info["center"][:2], (base * sapien.Pose(q=euler2quat(0, 0, angle))).to_transformation_matrix()[:3, 1], neighbours))
    for angle in [x for first in order for x in (first, -first)]:
        candidate = base * sapien.Pose(q=euler2quat(0, 0, angle))
        if planner.move_to_pose_with_screw(candidate, dry_run=True) != -1:
            return candidate
    print("Fail to find a valid grasp pose")
    return base


def pick_and_place_a(env, planner):
    """Grasp pose of A, A's placement spot next to B, and the turn about the vertical that aligns A with B."""
    a, b, c = env.cubeA.pose.sp.p, env.cubeB.pose.sp.p, env.cubeC.pose.sp.p
    b_yaw = yaw_of(env.cubeB)
    turn = wrap_quarter(b_yaw - yaw_of(env.cubeA))
    target_closing = env.agent.tcp.pose.to_transformation_matrix()[0, :3, 1].cpu().numpy()
    info = compute_grasp_info_by_obb(get_actor_obb(env.cubeA), approaching=APPROACHING,
                                     target_closing=target_closing, depth=FINGER_LENGTH)
    base = env.agent.build_grasp_pose(APPROACHING, info["closing"], info["center"])
    neighbours = [(o.pose.sp.p[:2], yaw_of(o)) for o in (env.cubeB, env.cubeC)]
    side = (a - b)[:2] / np.linalg.norm((a - b)[:2])
    rotate = np.array([[np.cos(turn), -np.sin(turn)], [np.sin(turn), np.cos(turn)]])
    options = []
    for angle in (0.0, np.pi / 2):
        closing = (base * sapien.Pose(q=euler2quat(0, 0, angle))).to_transformation_matrix()[:3, 1]
        clear = clearance(info["center"][:2], closing, neighbours) >= FINGER_CLEARANCE_M
        turned = rotate @ closing[:2]
        for k in range(4):
            normal = np.array([np.cos(b_yaw + k * np.pi / 2), np.sin(b_yaw + k * np.pi / 2)])
            spot = b[:2] + PLACE_GAP_M * normal
            key = (clear, abs(turned @ normal) < 0.5 * np.linalg.norm(turned),
                   np.linalg.norm(spot - c[:2]) >= C_CLEARANCE_M, float(normal @ side))
            options.append((key, angle, spot))
    options.sort(key=lambda o: o[0], reverse=True)
    for _, angle, spot in options:
        for signed in (angle, -angle):
            candidate = base * sapien.Pose(q=euler2quat(0, 0, signed))
            if planner.move_to_pose_with_screw(candidate, dry_run=True) != -1:
                return candidate, spot, turn
    print("Fail to find a valid grasp pose")
    return base, options[0][2], turn


def solve(env, seed=None, debug=False, vis=False):
    env.reset(seed=seed)
    assert env.unwrapped.control_mode in ["pd_joint_pos", "pd_joint_pos_vel"], env.unwrapped.control_mode
    planner = PandaArmMotionPlanningSolver(
        env, debug=debug, vis=vis, base_pose=env.unwrapped.agent.robot.pose,
        visualize_target_grasp_pose=vis, print_env_info=False,
    )
    env = env.unwrapped
    a, b = env.cubeA.pose.sp.p, env.cubeB.pose.sp.p
    if np.linalg.norm((a - b)[:2]) > MOVE_IF_M:
        grasp, spot, angle = pick_and_place_a(env, planner)
        planner.move_to_pose_with_screw(grasp * sapien.Pose([0, 0, -0.05]))
        planner.move_to_pose_with_screw(grasp)
        planner.close_gripper()
        planner.move_to_pose_with_screw(sapien.Pose(np.r_[grasp.p[:2], LIFT_Z_M], grasp.q))
        q = (sapien.Pose(q=euler2quat(0, 0, angle)) * sapien.Pose(q=grasp.q)).q
        planner.move_to_pose_with_screw(sapien.Pose(np.r_[spot, LIFT_Z_M], q))
        planner.move_to_pose_with_screw(sapien.Pose(np.r_[spot, grasp.p[2] + 0.005], q))
        planner.open_gripper()
        planner.move_to_pose_with_screw(sapien.Pose(np.r_[spot, LIFT_Z_M], q))
    grasp = grasp_pose_for(env, planner, env.cubeC, (env.cubeA, env.cubeB))
    planner.move_to_pose_with_screw(grasp * sapien.Pose([0, 0, -0.05]))
    planner.move_to_pose_with_screw(grasp)
    planner.close_gripper()
    lift_pose = sapien.Pose([0, 0, 0.1]) * grasp
    planner.move_to_pose_with_screw(lift_pose)
    goal_pose_A = env.cubeA.pose * sapien.Pose([0, 0, env.cube_half_size[2] * 2])
    goal_pose_B = env.cubeB.pose * sapien.Pose([0, 0, env.cube_half_size[2] * 2])
    goal_pose_p = (goal_pose_A.p + goal_pose_B.p) / 2
    offset = (goal_pose_p - env.cubeC.pose.p).cpu().numpy()[0]
    planner.move_to_pose_with_screw(sapien.Pose(lift_pose.p + offset, lift_pose.q))
    res = planner.open_gripper()
    planner.close()
    return res