File size: 8,544 Bytes
b14abf6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from ._base_task import Base_Task
from .utils import *
import sapien
import math
import numpy as np


class adjust_bottle(Base_Task):

    def setup_demo(self, **kwags):
        self._forced_qpose_tag = kwags.get("forced_qpose_tag")
        self._forced_model_id = kwags.get("forced_model_id")
        super()._init_task_env_(**kwags)

    def load_actors(self):

        self.qpose_tag = np.random.randint(0, 2)
        qposes = [[0.707, 0.0, 0.0, -0.707], [0.707, 0.0, 0.0, 0.707]]
        xlims = [[-0.12, -0.08], [0.08, 0.12]]

        self.model_id = np.random.choice([13, 16])
        # Optional dataset-balancing controls.  Draw the normal random values
        # first so the remaining scene RNG stream is unchanged; default task
        # behavior therefore stays byte-for-byte compatible.
        if self._forced_qpose_tag is not None:
            forced_qpose_tag = int(self._forced_qpose_tag)
            if forced_qpose_tag not in (0, 1):
                raise ValueError("forced_qpose_tag must be 0 (left) or 1 (right)")
            self.qpose_tag = forced_qpose_tag
        if self._forced_model_id is not None:
            forced_model_id = int(self._forced_model_id)
            if forced_model_id not in (13, 16):
                raise ValueError("forced_model_id must be 13 or 16")
            self.model_id = forced_model_id

        self.bottle = rand_create_actor(
            self,
            xlim=xlims[self.qpose_tag],
            ylim=[-0.13, -0.08],
            zlim=[0.752],
            rotate_rand=True,
            qpos=qposes[self.qpose_tag],
            modelname="001_bottle",
            convex=True,
            rotate_lim=(0, 0, 0.4),
            model_id=self.model_id,
        )

        if self.use_dynamic:
            self.bottle.set_mass(0.01)
            for component in self.bottle.actor.get_components():
                if isinstance(component, sapien.physx.PhysxRigidDynamicComponent):
                    component.set_linear_damping(10.0)
                    component.set_angular_damping(10.0)

        self.delay(4)
        self.add_prohibit_area(self.bottle, padding=0.15)
        self.left_target_pose = [-0.25, -0.12, 0.95, 0, 1, 0, 0]
        self.right_target_pose = [0.25, -0.12, 0.95, 0, 1, 0, 0]

    def play_once(self):
        if self.use_dynamic:
            return self._play_once_dynamic()
        else:
            return self._play_once_static()

    def _play_once_static(self):
        arm_tag = ArmTag("right" if self.qpose_tag == 1 else "left")
        target_pose = (self.right_target_pose if self.qpose_tag == 1 else self.left_target_pose)

        # Grasp -> Lift
        self.move(self.grasp_actor(self.bottle, arm_tag=arm_tag, pre_grasp_dis=0.1))
        self.move(self.move_by_displacement(arm_tag=arm_tag, z=0.1, move_axis="arm"))

        # Place
        self.move(
            self.place_actor(
                self.bottle,
                target_pose=target_pose,
                arm_tag=arm_tag,
                functional_point_id=0,
                pre_dis=0.0,
                is_open=False,
            ))

        self.info["info"] = {
            "{A}": f"001_bottle/base{self.model_id}",
            "{a}": str(arm_tag),
        }
        return self.info

    def _play_once_dynamic(self):
        arm_tag = ArmTag("right" if self.qpose_tag == 1 else "left")
        target_pose = (self.right_target_pose if self.qpose_tag == 1 else self.left_target_pose)

        current_bottle_pose = self.bottle.get_pose()
        end_position = np.array([current_bottle_pose.p[0], current_bottle_pose.p[1], current_bottle_pose.p[2]])

        self._intercept_position = end_position.copy()

        def robot_action_sequence_sync(need_plan_mode):
            grasp_result = self.grasp_actor(self.bottle, arm_tag=arm_tag, pre_grasp_dis=0.1)
            if not grasp_result or grasp_result[1] is None or len(grasp_result[1]) == 0:
                return
            self.move(grasp_result)

        table_bounds = (-0.35, 0.35, -0.25, 0.15)
        success, start_pos = self.execute_dynamic_workflow(
            target_actor=self.bottle,
            end_position=end_position,
            robot_action_sequence=robot_action_sequence_sync,
            table_bounds=table_bounds,
        )

        if not success:
            raise RuntimeError("Failed to generate dynamic trajectory")

        for component in self.bottle.actor.get_components():
            if isinstance(component, sapien.physx.PhysxRigidDynamicComponent):
                try:
                    component.set_linear_velocity(np.zeros(3))
                    component.set_angular_velocity(np.zeros(3))
                    component.set_linear_damping(10.0)
                    component.set_angular_damping(10.0)
                except Exception:
                    pass

        self.move(self.move_by_displacement(arm_tag=arm_tag, z=0.1, move_axis="arm"))

        self.move(
            self.place_actor(
                self.bottle,
                target_pose=target_pose,
                arm_tag=arm_tag,
                functional_point_id=0,
                pre_dis=0.0,
                is_open=False,
            ))

        self.info["info"] = {
            "{A}": f"001_bottle/base{self.model_id}",
            "{a}": str(arm_tag),
        }
        return self.info

    def get_dynamic_motion_config(self) -> dict:
        if not self.use_dynamic:
            return None
        current_bottle_pose = self.bottle.get_pose()
        end_position = np.array([current_bottle_pose.p[0], current_bottle_pose.p[1], current_bottle_pose.p[2]])
        
        return {
            'target_actor': self.bottle,
            'end_position': end_position,
            'table_bounds': (-0.35, 0.35, -0.15, 0.25),
        }
    
    def check_success(self):
        target_hight = 0.9
        bottle_pose = self.bottle.get_functional_point(0)
        basic_check= ((self.qpose_tag == 0 and bottle_pose[0] < -0.15) or
                (self.qpose_tag == 1 and bottle_pose[0] > 0.15)) and bottle_pose[2] > target_hight
        if (not self.use_dynamic) or getattr(self, 'eval_mode', False):
            return basic_check
        
        intercept_pos = getattr(self, '_intercept_position', None)
        if intercept_pos is None:
            return basic_check

        current_center = self.bottle.get_pose().p
        displacement = np.linalg.norm(current_center - intercept_pos)
        displacement_threshold = 0.1
        displacement_check = displacement > displacement_threshold

        left_ee_pose = self.robot.get_left_ee_pose()
        right_ee_pose = self.robot.get_right_ee_pose()
        left_ee_pos = np.array(left_ee_pose[:3])
        right_ee_pos = np.array(right_ee_pose[:3])
        
        dist_to_left = np.linalg.norm(current_center[:2] - left_ee_pos[:2])
        dist_to_right = np.linalg.norm(current_center[:2] - right_ee_pos[:2])
        proximity_threshold = 0.15
        proximity_check = (dist_to_left < proximity_threshold) or (dist_to_right < proximity_threshold)

        return basic_check and displacement_check and proximity_check

    def check_stable(self):
        if not self.use_dynamic:
            return super().check_stable()

        from .utils import cal_quat_dis
        actors_list, actors_pose_list = [], []
        dynamic_name = self.bottle.get_name()

        for actor in self.scene.get_all_actors():
            if actor.get_name() != dynamic_name:
                actors_list.append(actor)

        def get_sim(p1, p2):
            return np.abs(cal_quat_dis(p1.q, p2.q) * 180)

        is_stable, unstable_list = True, []

        def check(times):
            nonlocal is_stable
            for _ in range(times):
                self._update_kinematic_tasks()
                self.scene.step()
                for idx, actor in enumerate(actors_list):
                    actors_pose_list[idx].append(actor.get_pose())

            for idx, actor in enumerate(actors_list):
                final_pose = actors_pose_list[idx][-1]
                for pose in actors_pose_list[idx][-200:]:
                    if get_sim(final_pose, pose) > 3.0:
                        is_stable = False
                        unstable_list.append(actor.get_name())
                        break

        for _ in range(2000):
            self._update_kinematic_tasks()
            self.scene.step()
        for actor in actors_list:
            actors_pose_list.append([actor.get_pose()])
        check(500)
        return is_stable, unstable_list