mxk1998 commited on
Commit
2d9a8f6
·
verified ·
1 Parent(s): e428337

Publish sealed evaluation sources, batch 26

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. third_party/robosuite/robosuite/models/objects/primitive/cylinder.py +95 -0
  2. third_party/robosuite/robosuite/models/objects/xml_objects.py +299 -0
  3. third_party/robosuite/robosuite/models/robots/__init__.py +15 -0
  4. third_party/robosuite/robosuite/models/robots/compositional.py +104 -0
  5. third_party/robosuite/robosuite/models/robots/manipulators/__init__.py +11 -0
  6. third_party/robosuite/robosuite/models/robots/manipulators/baxter_robot.py +91 -0
  7. third_party/robosuite/robosuite/models/robots/manipulators/gr1_robot.py +195 -0
  8. third_party/robosuite/robosuite/models/robots/manipulators/humanoid_model.py +171 -0
  9. third_party/robosuite/robosuite/models/robots/manipulators/humanoid_upperbody_model.py +171 -0
  10. third_party/robosuite/robosuite/models/robots/manipulators/iiwa_robot.py +54 -0
  11. third_party/robosuite/robosuite/models/robots/manipulators/jaco_robot.py +54 -0
  12. third_party/robosuite/robosuite/models/robots/manipulators/kinova3_robot.py +54 -0
  13. third_party/robosuite/robosuite/models/robots/manipulators/legged_manipulator_model.py +64 -0
  14. third_party/robosuite/robosuite/models/robots/manipulators/manipulator_model.py +376 -0
  15. third_party/robosuite/robosuite/models/robots/manipulators/panda_robot.py +57 -0
  16. third_party/robosuite/robosuite/models/robots/manipulators/sawyer_robot.py +54 -0
  17. third_party/robosuite/robosuite/models/robots/manipulators/spot_arm.py +57 -0
  18. third_party/robosuite/robosuite/models/robots/manipulators/tiago_robot.py +112 -0
  19. third_party/robosuite/robosuite/models/robots/manipulators/ur5e_robot.py +54 -0
  20. third_party/robosuite/robosuite/models/robots/robot_model.py +457 -0
  21. third_party/robosuite/robosuite/models/tasks/__init__.py +2 -0
  22. third_party/robosuite/robosuite/models/tasks/manipulation_task.py +7 -0
  23. third_party/robosuite/robosuite/models/tasks/task.py +191 -0
  24. third_party/robosuite/robosuite/models/world.py +13 -0
  25. third_party/robosuite/robosuite/renderers/__init__.py +1 -0
  26. third_party/robosuite/robosuite/renderers/base.py +64 -0
  27. third_party/robosuite/robosuite/renderers/base_parser.py +55 -0
  28. third_party/robosuite/robosuite/renderers/context/__init__.py +0 -0
  29. third_party/robosuite/robosuite/renderers/context/egl_context.py +159 -0
  30. third_party/robosuite/robosuite/renderers/context/glfw_context.py +24 -0
  31. third_party/robosuite/robosuite/renderers/context/osmesa_context.py +26 -0
  32. third_party/robosuite/robosuite/renderers/mjviewer/__init__.py +0 -0
  33. third_party/robosuite/robosuite/renderers/mjviewer/mjviewer_renderer.py +63 -0
  34. third_party/robosuite/robosuite/robots/__init__.py +50 -0
  35. third_party/robosuite/robosuite/robots/fixed_base_robot.py +216 -0
  36. third_party/robosuite/robosuite/robots/legged_robot.py +253 -0
  37. third_party/robosuite/robosuite/robots/mobile_robot.py +464 -0
  38. third_party/robosuite/robosuite/robots/robot.py +1007 -0
  39. third_party/robosuite/robosuite/robots/wheeled_robot.py +182 -0
  40. third_party/robosuite/robosuite/scripts/browse_mjcf_model.py +67 -0
  41. third_party/robosuite/robosuite/scripts/check_custom_robot_model.py +108 -0
  42. third_party/robosuite/robosuite/scripts/collect_human_demonstrations.py +318 -0
  43. third_party/robosuite/robosuite/scripts/compile_mjcf_model.py +39 -0
  44. third_party/robosuite/robosuite/scripts/internal/view_robot_initialization.py +74 -0
  45. third_party/robosuite/robosuite/scripts/make_reset_video.py +93 -0
  46. third_party/robosuite/robosuite/scripts/playback_demonstrations_from_hdf5.py +110 -0
  47. third_party/robosuite/robosuite/scripts/print_robosuite_info.py +52 -0
  48. third_party/robosuite/robosuite/scripts/print_robot_action_info.py +58 -0
  49. third_party/robosuite/robosuite/scripts/render_dataset_with_omniverse.py +735 -0
  50. third_party/robosuite/robosuite/scripts/setup_macros.py +31 -0
third_party/robosuite/robosuite/models/objects/primitive/cylinder.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.objects import MujocoGeneratedObject, PrimitiveObject
4
+ from robosuite.utils.mjcf_utils import get_size
5
+
6
+
7
+ class CylinderObject(PrimitiveObject):
8
+ """
9
+ A cylinder object.
10
+
11
+ Args:
12
+ size (2-tuple of float): (radius, half-length) size parameters for this cylinder object
13
+ """
14
+
15
+ def __init__(
16
+ self,
17
+ name,
18
+ size=None,
19
+ size_max=None,
20
+ size_min=None,
21
+ density=None,
22
+ friction=None,
23
+ rgba=None,
24
+ solref=None,
25
+ solimp=None,
26
+ material=None,
27
+ joints="default",
28
+ obj_type="all",
29
+ duplicate_collision_geoms=True,
30
+ ):
31
+ size = get_size(size, size_max, size_min, [0.07, 0.07], [0.03, 0.03])
32
+
33
+ # We override solref, solimp, and joint default values for better stability
34
+ if friction is None:
35
+ friction = [1, 0.01, 0.001]
36
+ if solref is None:
37
+ solref = [0.01, 0.5]
38
+ if joints == "default":
39
+ joints = [{"type": "free", "damping": "0.0001"}]
40
+
41
+ super().__init__(
42
+ name=name,
43
+ size=size,
44
+ rgba=rgba,
45
+ density=density,
46
+ friction=friction,
47
+ solref=solref,
48
+ solimp=solimp,
49
+ material=material,
50
+ joints=joints,
51
+ obj_type=obj_type,
52
+ duplicate_collision_geoms=duplicate_collision_geoms,
53
+ )
54
+
55
+ def sanity_check(self):
56
+ """
57
+ Checks to make sure inputted size is of correct length
58
+
59
+ Raises:
60
+ AssertionError: [Invalid size length]
61
+ """
62
+ assert len(self.size) == 2, "cylinder size should have length 2"
63
+
64
+ def _get_object_subtree(self):
65
+ return self._get_object_subtree_(ob_type="cylinder")
66
+
67
+ @staticmethod
68
+ def get_collision_attrib_template():
69
+ """
70
+ Generates template with collision attributes for a given geom
71
+
72
+ Extends super method for better stability for contacts
73
+
74
+ Returns:
75
+ dict: Initial template with `'pos'` and `'group'` already specified
76
+ """
77
+ template = MujocoGeneratedObject.get_collision_attrib_template()
78
+ # Add condim value
79
+ template["margin"] = "0.001"
80
+ return template
81
+
82
+ @property
83
+ def bottom_offset(self):
84
+ return np.array([0, 0, -1 * self.size[1]])
85
+
86
+ @property
87
+ def top_offset(self):
88
+ return np.array([0, 0, self.size[1]])
89
+
90
+ @property
91
+ def horizontal_radius(self):
92
+ return self.size[0]
93
+
94
+ def get_bounding_box_half_size(self):
95
+ return np.array([self.size[0], self.size[0], self.size[1]])
third_party/robosuite/robosuite/models/objects/xml_objects.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.objects import MujocoXMLObject
4
+ from robosuite.utils.mjcf_utils import array_to_string, find_elements, xml_path_completion
5
+
6
+
7
+ class BottleObject(MujocoXMLObject):
8
+ """
9
+ Bottle object
10
+ """
11
+
12
+ def __init__(self, name):
13
+ super().__init__(
14
+ xml_path_completion("objects/bottle.xml"),
15
+ name=name,
16
+ joints=[dict(type="free", damping="0.0005")],
17
+ obj_type="all",
18
+ duplicate_collision_geoms=True,
19
+ )
20
+
21
+
22
+ class CanObject(MujocoXMLObject):
23
+ """
24
+ Coke can object (used in PickPlace)
25
+ """
26
+
27
+ def __init__(self, name):
28
+ super().__init__(
29
+ xml_path_completion("objects/can.xml"),
30
+ name=name,
31
+ joints=[dict(type="free", damping="0.0005")],
32
+ obj_type="all",
33
+ duplicate_collision_geoms=True,
34
+ )
35
+
36
+
37
+ class LemonObject(MujocoXMLObject):
38
+ """
39
+ Lemon object
40
+ """
41
+
42
+ def __init__(self, name):
43
+ super().__init__(
44
+ xml_path_completion("objects/lemon.xml"), name=name, obj_type="all", duplicate_collision_geoms=True
45
+ )
46
+
47
+
48
+ class MilkObject(MujocoXMLObject):
49
+ """
50
+ Milk carton object (used in PickPlace)
51
+ """
52
+
53
+ def __init__(self, name):
54
+ super().__init__(
55
+ xml_path_completion("objects/milk.xml"),
56
+ name=name,
57
+ joints=[dict(type="free", damping="0.0005")],
58
+ obj_type="all",
59
+ duplicate_collision_geoms=True,
60
+ )
61
+
62
+
63
+ class BreadObject(MujocoXMLObject):
64
+ """
65
+ Bread loaf object (used in PickPlace)
66
+ """
67
+
68
+ def __init__(self, name):
69
+ super().__init__(
70
+ xml_path_completion("objects/bread.xml"),
71
+ name=name,
72
+ joints=[dict(type="free", damping="0.0005")],
73
+ obj_type="all",
74
+ duplicate_collision_geoms=True,
75
+ )
76
+
77
+
78
+ class CerealObject(MujocoXMLObject):
79
+ """
80
+ Cereal box object (used in PickPlace)
81
+ """
82
+
83
+ def __init__(self, name):
84
+ super().__init__(
85
+ xml_path_completion("objects/cereal.xml"),
86
+ name=name,
87
+ joints=[dict(type="free", damping="0.0005")],
88
+ obj_type="all",
89
+ duplicate_collision_geoms=True,
90
+ )
91
+
92
+
93
+ class SquareNutObject(MujocoXMLObject):
94
+ """
95
+ Square nut object (used in NutAssembly)
96
+ """
97
+
98
+ def __init__(self, name):
99
+ super().__init__(
100
+ xml_path_completion("objects/square-nut.xml"),
101
+ name=name,
102
+ joints=[dict(type="free", damping="0.0005")],
103
+ obj_type="all",
104
+ duplicate_collision_geoms=True,
105
+ )
106
+
107
+ @property
108
+ def important_sites(self):
109
+ """
110
+ Returns:
111
+ dict: In addition to any default sites for this object, also provides the following entries
112
+
113
+ :`'handle'`: Name of nut handle location site
114
+ """
115
+ # Get dict from super call and add to it
116
+ dic = super().important_sites
117
+ dic.update({"handle": self.naming_prefix + "handle_site"})
118
+ return dic
119
+
120
+
121
+ class RoundNutObject(MujocoXMLObject):
122
+ """
123
+ Round nut (used in NutAssembly)
124
+ """
125
+
126
+ def __init__(self, name):
127
+ super().__init__(
128
+ xml_path_completion("objects/round-nut.xml"),
129
+ name=name,
130
+ joints=[dict(type="free", damping="0.0005")],
131
+ obj_type="all",
132
+ duplicate_collision_geoms=True,
133
+ )
134
+
135
+ @property
136
+ def important_sites(self):
137
+ """
138
+ Returns:
139
+ dict: In addition to any default sites for this object, also provides the following entries
140
+
141
+ :`'handle'`: Name of nut handle location site
142
+ """
143
+ # Get dict from super call and add to it
144
+ dic = super().important_sites
145
+ dic.update({"handle": self.naming_prefix + "handle_site"})
146
+ return dic
147
+
148
+
149
+ class MilkVisualObject(MujocoXMLObject):
150
+ """
151
+ Visual fiducial of milk carton (used in PickPlace).
152
+
153
+ Fiducial objects are not involved in collision physics.
154
+ They provide a point of reference to indicate a position.
155
+ """
156
+
157
+ def __init__(self, name):
158
+ super().__init__(
159
+ xml_path_completion("objects/milk-visual.xml"),
160
+ name=name,
161
+ joints=None,
162
+ obj_type="visual",
163
+ duplicate_collision_geoms=True,
164
+ )
165
+
166
+
167
+ class BreadVisualObject(MujocoXMLObject):
168
+ """
169
+ Visual fiducial of bread loaf (used in PickPlace)
170
+
171
+ Fiducial objects are not involved in collision physics.
172
+ They provide a point of reference to indicate a position.
173
+ """
174
+
175
+ def __init__(self, name):
176
+ super().__init__(
177
+ xml_path_completion("objects/bread-visual.xml"),
178
+ name=name,
179
+ joints=None,
180
+ obj_type="visual",
181
+ duplicate_collision_geoms=True,
182
+ )
183
+
184
+
185
+ class CerealVisualObject(MujocoXMLObject):
186
+ """
187
+ Visual fiducial of cereal box (used in PickPlace)
188
+
189
+ Fiducial objects are not involved in collision physics.
190
+ They provide a point of reference to indicate a position.
191
+ """
192
+
193
+ def __init__(self, name):
194
+ super().__init__(
195
+ xml_path_completion("objects/cereal-visual.xml"),
196
+ name=name,
197
+ joints=None,
198
+ obj_type="visual",
199
+ duplicate_collision_geoms=True,
200
+ )
201
+
202
+
203
+ class CanVisualObject(MujocoXMLObject):
204
+ """
205
+ Visual fiducial of coke can (used in PickPlace)
206
+
207
+ Fiducial objects are not involved in collision physics.
208
+ They provide a point of reference to indicate a position.
209
+ """
210
+
211
+ def __init__(self, name):
212
+ super().__init__(
213
+ xml_path_completion("objects/can-visual.xml"),
214
+ name=name,
215
+ joints=None,
216
+ obj_type="visual",
217
+ duplicate_collision_geoms=True,
218
+ )
219
+
220
+
221
+ class PlateWithHoleObject(MujocoXMLObject):
222
+ """
223
+ Square plate with a hole in the center (used in PegInHole)
224
+ """
225
+
226
+ def __init__(self, name):
227
+ super().__init__(
228
+ xml_path_completion("objects/plate-with-hole.xml"),
229
+ name=name,
230
+ joints=None,
231
+ obj_type="all",
232
+ duplicate_collision_geoms=True,
233
+ )
234
+
235
+
236
+ class DoorObject(MujocoXMLObject):
237
+ """
238
+ Door with handle (used in Door)
239
+
240
+ Args:
241
+ friction (3-tuple of float): friction parameters to override the ones specified in the XML
242
+ damping (float): damping parameter to override the ones specified in the XML
243
+ lock (bool): Whether to use the locked door variation object or not
244
+ """
245
+
246
+ def __init__(self, name, friction=None, damping=None, lock=False):
247
+ xml_path = "objects/door.xml"
248
+ if lock:
249
+ xml_path = "objects/door_lock.xml"
250
+ super().__init__(
251
+ xml_path_completion(xml_path), name=name, joints=None, obj_type="all", duplicate_collision_geoms=True
252
+ )
253
+
254
+ # Set relevant body names
255
+ self.door_body = self.naming_prefix + "door"
256
+ self.frame_body = self.naming_prefix + "frame"
257
+ self.latch_body = self.naming_prefix + "latch"
258
+ self.hinge_joint = self.naming_prefix + "hinge"
259
+
260
+ self.lock = lock
261
+ self.friction = friction
262
+ self.damping = damping
263
+ if self.friction is not None:
264
+ self._set_door_friction(self.friction)
265
+ if self.damping is not None:
266
+ self._set_door_damping(self.damping)
267
+
268
+ def _set_door_friction(self, friction):
269
+ """
270
+ Helper function to override the door friction directly in the XML
271
+
272
+ Args:
273
+ friction (3-tuple of float): friction parameters to override the ones specified in the XML
274
+ """
275
+ hinge = find_elements(root=self.worldbody, tags="joint", attribs={"name": self.hinge_joint}, return_first=True)
276
+ hinge.set("frictionloss", array_to_string(np.array([friction])))
277
+
278
+ def _set_door_damping(self, damping):
279
+ """
280
+ Helper function to override the door friction directly in the XML
281
+
282
+ Args:
283
+ damping (float): damping parameter to override the ones specified in the XML
284
+ """
285
+ hinge = find_elements(root=self.worldbody, tags="joint", attribs={"name": self.hinge_joint}, return_first=True)
286
+ hinge.set("damping", array_to_string(np.array([damping])))
287
+
288
+ @property
289
+ def important_sites(self):
290
+ """
291
+ Returns:
292
+ dict: In addition to any default sites for this object, also provides the following entries
293
+
294
+ :`'handle'`: Name of door handle location site
295
+ """
296
+ # Get dict from super call and add to it
297
+ dic = super().important_sites
298
+ dic.update({"handle": self.naming_prefix + "handle"})
299
+ return dic
third_party/robosuite/robosuite/models/robots/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .robot_model import RobotModel, create_robot
2
+ from .manipulators import *
3
+ from .compositional import *
4
+
5
+
6
+ def is_robosuite_robot(robot: str) -> bool:
7
+ """
8
+ robot is robosuite repo robot if can import robot class from robosuite.models.robots
9
+ """
10
+ try:
11
+ module = __import__("robosuite.models.robots", fromlist=[robot])
12
+ getattr(module, robot)
13
+ return True
14
+ except (ImportError, AttributeError):
15
+ return False
third_party/robosuite/robosuite/models/robots/compositional.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.robots import *
4
+
5
+
6
+ class PandaOmron(Panda):
7
+ @property
8
+ def default_base(self):
9
+ return "OmronMobileBase"
10
+
11
+ @property
12
+ def default_arms(self):
13
+ return {"right": "Panda"}
14
+
15
+ @property
16
+ def init_qpos(self):
17
+ return np.array([0, np.pi / 16.0 - 0.2, 0.00, -np.pi / 2.0 - np.pi / 3.0, 0.00, np.pi - 0.4, np.pi / 4])
18
+
19
+ @property
20
+ def init_torso_qpos(self):
21
+ return np.array([0.2])
22
+
23
+ @property
24
+ def base_xpos_offset(self):
25
+ return {
26
+ "bins": (-0.6, -0.1, 0),
27
+ "empty": (-0.6, 0, 0),
28
+ "table": lambda table_length: (-0.16 - table_length / 2, 0, 0),
29
+ }
30
+
31
+
32
+ class SpotWithArm(SpotArm):
33
+ @property
34
+ def default_base(self):
35
+ return "Spot"
36
+
37
+ @property
38
+ def default_arms(self):
39
+ return {"right": "SpotArm"}
40
+
41
+ @property
42
+ def init_qpos(self):
43
+ return np.array([0.0, -2, 1.26, -0.335, 0.862, 0.0])
44
+
45
+ @property
46
+ def base_xpos_offset(self):
47
+ return {
48
+ "bins": (-1.05, -0.1, -0.22),
49
+ "empty": (-1.1, 0, -0.22),
50
+ "table": lambda table_length: (-0.5 - table_length / 2, 0.0, -0.22),
51
+ }
52
+
53
+
54
+ class SpotWithArmFloating(SpotArm):
55
+ def __init__(self, idn=0):
56
+ super().__init__(idn=idn)
57
+
58
+ @property
59
+ def init_qpos(self):
60
+ return np.array([0.0, -2, 1.26, -0.335, 0.862, 0.0])
61
+
62
+ @property
63
+ def default_base(self):
64
+ return "SpotFloating"
65
+
66
+ @property
67
+ def default_arms(self):
68
+ return {"right": "SpotArm"}
69
+
70
+ @property
71
+ def base_xpos_offset(self):
72
+ return {
73
+ "bins": (-0.7, -0.1, 0.0),
74
+ "empty": (-0.6, 0, 0.0),
75
+ "table": lambda table_length: (-0.5 - table_length / 2, 0.0, 0.0),
76
+ }
77
+
78
+
79
+ class PandaDexRH(Panda):
80
+ @property
81
+ def default_gripper(self):
82
+ return {"right": "InspireRightHand"}
83
+
84
+ @property
85
+ def gripper_mount_pos_offset(self):
86
+ return {"right": [0.0, 0.0, 0.0]}
87
+
88
+ @property
89
+ def gripper_mount_quat_offset(self):
90
+ return {"right": [-0.5, 0.5, 0.5, -0.5]}
91
+
92
+
93
+ class PandaDexLH(Panda):
94
+ @property
95
+ def default_gripper(self):
96
+ return {"right": "InspireLeftHand"}
97
+
98
+ @property
99
+ def gripper_mount_pos_offset(self):
100
+ return {"right": [0.0, 0.0, 0.0]}
101
+
102
+ @property
103
+ def gripper_mount_quat_offset(self):
104
+ return {"right": [0.5, -0.5, 0.5, -0.5]}
third_party/robosuite/robosuite/models/robots/manipulators/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .manipulator_model import ManipulatorModel
2
+ from .sawyer_robot import Sawyer
3
+ from .baxter_robot import Baxter
4
+ from .panda_robot import Panda
5
+ from .jaco_robot import Jaco
6
+ from .kinova3_robot import Kinova3
7
+ from .iiwa_robot import IIWA
8
+ from .ur5e_robot import UR5e
9
+ from .spot_arm import SpotArm
10
+ from .tiago_robot import Tiago
11
+ from .gr1_robot import GR1, GR1FixedLowerBody, GR1ArmsOnly, GR1FloatingBody
third_party/robosuite/robosuite/models/robots/manipulators/baxter_robot.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel
4
+ from robosuite.utils.mjcf_utils import xml_path_completion
5
+
6
+
7
+ class Baxter(ManipulatorModel):
8
+ """
9
+ Baxter is a hunky bimanual robot designed by Rethink Robotics.
10
+
11
+ Args:
12
+ idn (int or str): Number or some other unique identification string for this robot instance
13
+ """
14
+
15
+ arms = ["right", "left"]
16
+
17
+ def __init__(self, idn=0):
18
+ super().__init__(xml_path_completion("robots/baxter/robot.xml"), idn=idn)
19
+
20
+ @property
21
+ def default_base(self):
22
+ return "RethinkMinimalMount"
23
+
24
+ @property
25
+ def default_gripper(self):
26
+ """
27
+ Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective
28
+ values
29
+
30
+ Returns:
31
+ dict: Dictionary containing arm-specific gripper names
32
+ """
33
+ return {"right": "RethinkGripper", "left": "RethinkGripper"}
34
+
35
+ @property
36
+ def default_controller_config(self):
37
+ """
38
+ Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective
39
+ values
40
+
41
+ Returns:
42
+ dict: Dictionary containing arm-specific default controller config names
43
+ """
44
+ return {"right": "osc_pose", "left": "osc_pose"}
45
+
46
+ @property
47
+ def init_qpos(self):
48
+ """
49
+ Since this is bimanual robot, returns [right, left] array corresponding to respective values
50
+
51
+ Note that this is a pose such that the arms are half extended
52
+
53
+ Returns:
54
+ np.array: default initial qpos for the right, left arms
55
+ """
56
+ # [right, left]
57
+ # Arms half extended
58
+ return np.array(
59
+ [0.403, -0.636, 0.114, 1.432, 0.735, 1.205, -0.269, -0.403, -0.636, -0.114, 1.432, -0.735, 1.205, 0.269]
60
+ )
61
+
62
+ @property
63
+ def base_xpos_offset(self):
64
+ return {
65
+ "bins": (-0.5, -0.1, 0),
66
+ "empty": (-0.29, 0, 0),
67
+ "table": lambda table_length: (-0.26 - table_length / 2, 0, 0),
68
+ }
69
+
70
+ @property
71
+ def top_offset(self):
72
+ return np.array((0, 0, 1.0))
73
+
74
+ @property
75
+ def _horizontal_radius(self):
76
+ return 0.5
77
+
78
+ @property
79
+ def arm_type(self):
80
+ return "bimanual"
81
+
82
+ @property
83
+ def _eef_name(self):
84
+ """
85
+ Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective
86
+ values
87
+
88
+ Returns:
89
+ dict: Dictionary containing arm-specific eef names
90
+ """
91
+ return {"right": "right_hand", "left": "left_hand"}
third_party/robosuite/robosuite/models/robots/manipulators/gr1_robot.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.robots.manipulators.legged_manipulator_model import LeggedManipulatorModel
4
+ from robosuite.utils.mjcf_utils import find_parent, xml_path_completion
5
+
6
+
7
+ class GR1(LeggedManipulatorModel):
8
+ """
9
+ Tiago is a mobile manipulator robot created by PAL Robotics.
10
+
11
+ Args:
12
+ idn (int or str): Number or some other unique identification string for this robot instance
13
+ """
14
+
15
+ arms = ["right", "left"]
16
+
17
+ def __init__(self, idn=0):
18
+ super().__init__(xml_path_completion("robots/gr1/robot.xml"), idn=idn)
19
+
20
+ @property
21
+ def default_base(self):
22
+ return "NoActuationBase"
23
+
24
+ @property
25
+ def default_gripper(self):
26
+ """
27
+ Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective
28
+ values
29
+
30
+ Returns:
31
+ dict: Dictionary containing arm-specific gripper names
32
+ """
33
+ return {"right": "FourierRightHand", "left": "FourierLeftHand"}
34
+
35
+ @property
36
+ def default_controller_config(self):
37
+ """
38
+ Since this is bimanual robot, returns dict with `'right'`, `'left'`, `'head'`, `'torso'` keywords corresponding to their respective
39
+ values
40
+
41
+ Returns:
42
+ dict: Dictionary containing arm,head,torso-specific default controller config names
43
+ """
44
+ return {
45
+ "right": "default_gr1",
46
+ "left": "default_gr1",
47
+ "head": "default_gr1_head",
48
+ "torso": "default_gr1_torso",
49
+ "right_leg": "default_gr1",
50
+ "left_leg": "default_gr1",
51
+ }
52
+
53
+ @property
54
+ def init_qpos(self):
55
+ """
56
+ Since this is bimanual robot, returns [right, left] array corresponding to respective values
57
+
58
+ Note that this is a pose such that the arms are half extended
59
+
60
+ Returns:
61
+ np.array: default initial qpos for the right, left arms
62
+ """
63
+ init_qpos = np.array([0.0] * 32)
64
+ right_arm_init = np.array([0.0, -0.1, 0.0, -1.57, 0.0, 0.0, 0.0])
65
+ init_qpos[6:13] = right_arm_init
66
+ left_arm_init = np.array([0.0, 0.1, 0.0, -1.57, 0.0, 0.0, 0.0])
67
+ init_qpos[13:20] = left_arm_init
68
+ return init_qpos
69
+
70
+ @property
71
+ def base_xpos_offset(self):
72
+ return {
73
+ "bins": (-0.30, -0.1, 0.95),
74
+ "empty": (-0.29, 0, 0.95),
75
+ "table": lambda table_length: (-0.15 - table_length / 2, 0, 0.95),
76
+ }
77
+
78
+ @property
79
+ def top_offset(self):
80
+ return np.array((0, 0, 1.0))
81
+
82
+ @property
83
+ def _horizontal_radius(self):
84
+ return 0.5
85
+
86
+ @property
87
+ def arm_type(self):
88
+ return "bimanual"
89
+
90
+ @property
91
+ def _eef_name(self):
92
+ """
93
+ Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective
94
+ values
95
+
96
+ Returns:
97
+ dict: Dictionary containing arm-specific eef names
98
+ """
99
+ return {"right": "right_eef", "left": "left_eef"}
100
+
101
+
102
+ class GR1FixedLowerBody(GR1):
103
+ def __init__(self, idn=0):
104
+ super().__init__(idn=idn)
105
+
106
+ # fix lower body
107
+ self._remove_joint_actuation("leg")
108
+ self._remove_free_joint()
109
+
110
+ @property
111
+ def init_qpos(self):
112
+ """
113
+ Since this is bimanual robot, returns [right, left] array corresponding to respective values
114
+
115
+ Note that this is a pose such that the arms are half extended
116
+
117
+ Returns:
118
+ np.array: default initial qpos for the right, left arms
119
+ """
120
+ init_qpos = np.array([0.0] * 20)
121
+ right_arm_init = np.array([0.0, -0.1, 0.0, -1.57, 0.0, 0.0, 0.0])
122
+ init_qpos[6:13] = right_arm_init
123
+ left_arm_init = np.array([0.0, 0.1, 0.0, -1.57, 0.0, 0.0, 0.0])
124
+ init_qpos[13:20] = left_arm_init
125
+ return init_qpos
126
+
127
+ @property
128
+ def default_base(self):
129
+ return "NoActuationBase"
130
+
131
+
132
+ class GR1FloatingBody(GR1):
133
+ def __init__(self, idn=0):
134
+ super().__init__(idn=idn)
135
+
136
+ # fix lower body
137
+ self._remove_joint_actuation("leg")
138
+ self._remove_free_joint()
139
+
140
+ @property
141
+ def init_qpos(self):
142
+ """
143
+ Since this is bimanual robot, returns [right, left] array corresponding to respective values
144
+
145
+ Note that this is a pose such that the arms are half extended
146
+
147
+ Returns:
148
+ np.array: default initial qpos for the right, left arms
149
+ """
150
+ init_qpos = np.array([0.0] * 20)
151
+ right_arm_init = np.array([0.0, -0.1, 0.0, -1.57, 0.0, 0.0, 0.0])
152
+ init_qpos[6:13] = right_arm_init
153
+ left_arm_init = np.array([0.0, 0.1, 0.0, -1.57, 0.0, 0.0, 0.0])
154
+ init_qpos[13:20] = left_arm_init
155
+ return init_qpos
156
+
157
+ @property
158
+ def default_base(self):
159
+ return "FloatingLeggedBase"
160
+
161
+ @property
162
+ def base_xpos_offset(self):
163
+ return {
164
+ "bins": (-0.30, -0.1, 0.97),
165
+ "empty": (-0.29, 0, 0.97),
166
+ "table": lambda table_length: (-0.15 - table_length / 2, 0, 0.97),
167
+ }
168
+
169
+
170
+ class GR1ArmsOnly(GR1):
171
+ def __init__(self, idn=0):
172
+ super().__init__(idn=idn)
173
+
174
+ # fix lower body
175
+ self._remove_joint_actuation("leg")
176
+ self._remove_joint_actuation("head")
177
+ self._remove_joint_actuation("torso")
178
+ self._remove_free_joint()
179
+
180
+ @property
181
+ def init_qpos(self):
182
+ """
183
+ Since this is bimanual robot, returns [right, left] array corresponding to respective values
184
+
185
+ Note that this is a pose such that the arms are half extended
186
+
187
+ Returns:
188
+ np.array: default initial qpos for the right, left arms
189
+ """
190
+ init_qpos = np.array([0.0] * 14)
191
+ right_arm_init = np.array([0.0, -0.1, 0.0, -1.57, 0.0, 0.0, 0.0])
192
+ left_arm_init = np.array([0.0, 0.1, 0.0, -1.57, 0.0, 0.0, 0.0])
193
+ init_qpos[0:7] = right_arm_init
194
+ init_qpos[7:14] = left_arm_init
195
+ return init_qpos
third_party/robosuite/robosuite/models/robots/manipulators/humanoid_model.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+
3
+ import numpy as np
4
+
5
+ from robosuite.models.robots import RobotModel
6
+ from robosuite.utils.mjcf_utils import find_elements, string_to_array
7
+
8
+
9
+ class HumanoidModel(RobotModel):
10
+ """
11
+ Base class for all humanoid models.
12
+
13
+ Args:
14
+ fname (str): Path to relevant xml file from which to create this robot instance
15
+ idn (int or str): Number or some other unique identification string for this robot instance
16
+ """
17
+
18
+ def __init__(self, fname, idn=0):
19
+ # Always run super init first
20
+ super().__init__(fname, idn=idn)
21
+
22
+ # key: gripper name and value: gripper model
23
+ self.grippers = OrderedDict()
24
+
25
+ # Grab hand's offset from final robot link (string -> np.array -> elements [1, 2, 3, 0] (x, y, z, w))
26
+ # We're dealing with bimanual armed robot
27
+ self.hand_rotation_offset = {}
28
+ for arm in ("right", "left"):
29
+ hand_element = find_elements(
30
+ root=self.root, tags="body", attribs={"name": self.eef_name[arm]}, return_first=True
31
+ )
32
+ self.hand_rotation_offset[arm] = string_to_array(hand_element.get("quat", "1 0 0 0"))[[1, 2, 3, 0]]
33
+
34
+ # Get camera names for this robot
35
+ self.cameras = self.get_element_names(self.worldbody, "camera")
36
+
37
+ def add_gripper(self, gripper, arm_name=None):
38
+ """
39
+ Mounts @gripper to arm.
40
+
41
+ Throws error if robot already has a gripper or gripper type is incorrect.
42
+
43
+ Args:
44
+ gripper (GripperModel): gripper MJCF model
45
+ arm_name (str): name of arm mount -- defaults to self.eef_name if not specified
46
+
47
+ Raises:
48
+ ValueError: [Multiple grippers]
49
+ """
50
+ if arm_name is None:
51
+ arm_name = self.eef_name
52
+ if arm_name in self.grippers:
53
+ raise ValueError("Attempts to add multiple grippers to one body")
54
+
55
+ self.merge(gripper, merge_body=arm_name)
56
+
57
+ self.grippers[arm_name] = gripper
58
+
59
+ # Update cameras in this model
60
+ self.cameras = self.get_element_names(self.worldbody, "camera")
61
+
62
+ # -------------------------------------------------------------------------------------- #
63
+ # Public Properties: In general, these are the name-adjusted versions from the private #
64
+ # attributes pulled from their respective raw xml files #
65
+ # -------------------------------------------------------------------------------------- #
66
+
67
+ @property
68
+ def eef_name(self):
69
+ """
70
+ Returns:
71
+ str or dict of str: Prefix-adjusted eef name for this robot. If bimanual robot, returns {"left", "right"}
72
+ keyword-mapped eef names
73
+ """
74
+ return self.correct_naming(self._eef_name)
75
+
76
+ @property
77
+ def models(self):
78
+ """
79
+ Returns a list of all m(sub-)models owned by this robot model. By default, this includes the gripper model,
80
+ if specified
81
+
82
+ Returns:
83
+ list: models owned by this object
84
+ """
85
+ models = super().models
86
+ return models + list(self.grippers.values())
87
+
88
+ # -------------------------------------------------------------------------------------- #
89
+ # -------------------------- Private Properties ---------------------------------------- #
90
+ # -------------------------------------------------------------------------------------- #
91
+
92
+ @property
93
+ def _important_sites(self):
94
+ """
95
+ Returns:
96
+ dict: (Default is no important sites; i.e.: empty dict)
97
+ """
98
+ return {}
99
+
100
+ @property
101
+ def _eef_name(self):
102
+ """
103
+ XML eef name for this robot to which grippers can be attached. Note that these should be the raw
104
+ string names directly pulled from a robot's corresponding XML file, NOT the adjusted name with an
105
+ auto-generated naming prefix
106
+
107
+ Returns:
108
+ str: Raw XML eef name for this robot (default is "right_hand")
109
+ """
110
+ return "right_hand"
111
+
112
+ # -------------------------------------------------------------------------------------- #
113
+ # All subclasses must implement the following properties #
114
+ # -------------------------------------------------------------------------------------- #
115
+
116
+ @property
117
+ def default_gripper(self):
118
+ """
119
+ Defines the default gripper type for this robot that gets added to end effector
120
+
121
+ Returns:
122
+ str: Default gripper name to add to this robot
123
+ """
124
+ raise NotImplementedError
125
+
126
+ @property
127
+ def arm_type(self):
128
+ """
129
+ Type of robot arm. Should be either "bimanual" or "single" (or something else if it gets added in the future)
130
+
131
+ Returns:
132
+ str: Type of robot
133
+ """
134
+ raise NotImplementedError
135
+
136
+ @property
137
+ def base_xpos_offset(self):
138
+ """
139
+ Defines the dict of various (x,y,z) tuple offsets relative to specific arenas placed at (0,0,0)
140
+ Assumes robot is facing forwards (in the +x direction) when determining offset. Should have entries for each
141
+ manipulator arena case; i.e.: "bins", "empty", and "table")
142
+
143
+ Returns:
144
+ dict:
145
+
146
+ :`'bins'`: (x,y,z) robot offset if placed in bins arena
147
+ :`'empty'`: (x,y,z) robot offset if placed in the empty arena
148
+ :`'table'`: lambda function that takes in table_length and returns corresponding (x,y,z) offset
149
+ if placed in the table arena
150
+ """
151
+ raise NotImplementedError
152
+
153
+ @property
154
+ def top_offset(self):
155
+ raise NotImplementedError
156
+
157
+ @property
158
+ def _horizontal_radius(self):
159
+ raise NotImplementedError
160
+
161
+ @property
162
+ def default_mount(self):
163
+ return "HumanoidFreeMount"
164
+
165
+ @property
166
+ def default_controller_config(self):
167
+ raise NotImplementedError
168
+
169
+ @property
170
+ def init_qpos(self):
171
+ raise NotImplementedError
third_party/robosuite/robosuite/models/robots/manipulators/humanoid_upperbody_model.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+
3
+ import numpy as np
4
+
5
+ from robosuite.models.robots import RobotModel
6
+ from robosuite.utils.mjcf_utils import find_elements, string_to_array
7
+
8
+
9
+ class HumanoidUpperBodyModel(RobotModel):
10
+ """
11
+ Base class for all humanoid upper models (base can be any, bimanual upper body of humanoids).
12
+
13
+ Args:
14
+ fname (str): Path to relevant xml file from which to create this robot instance
15
+ idn (int or str): Number or some other unique identification string for this robot instance
16
+ """
17
+
18
+ def __init__(self, fname, idn=0):
19
+ # Always run super init first
20
+ super().__init__(fname, idn=idn)
21
+
22
+ # key: gripper name and value: gripper model
23
+ self.grippers = OrderedDict()
24
+
25
+ # Grab hand's offset from final robot link (string -> np.array -> elements [1, 2, 3, 0] (x, y, z, w))
26
+ # We're dealing with bimanual armed robot
27
+ self.hand_rotation_offset = {}
28
+ for arm in ("right", "left"):
29
+ hand_element = find_elements(
30
+ root=self.root, tags="body", attribs={"name": self.eef_name[arm]}, return_first=True
31
+ )
32
+ self.hand_rotation_offset[arm] = string_to_array(hand_element.get("quat", "1 0 0 0"))[[1, 2, 3, 0]]
33
+
34
+ # Get camera names for this robot
35
+ self.cameras = self.get_element_names(self.worldbody, "camera")
36
+
37
+ def add_gripper(self, gripper, arm_name=None):
38
+ """
39
+ Mounts @gripper to arm.
40
+
41
+ Throws error if robot already has a gripper or gripper type is incorrect.
42
+
43
+ Args:
44
+ gripper (GripperModel): gripper MJCF model
45
+ arm_name (str): name of arm mount -- defaults to self.eef_name if not specified
46
+
47
+ Raises:
48
+ ValueError: [Multiple grippers]
49
+ """
50
+ if arm_name is None:
51
+ arm_name = self.eef_name
52
+ if arm_name in self.grippers:
53
+ raise ValueError("Attempts to add multiple grippers to one body")
54
+
55
+ self.merge(gripper, merge_body=arm_name)
56
+
57
+ self.grippers[arm_name] = gripper
58
+
59
+ # Update cameras in this model
60
+ self.cameras = self.get_element_names(self.worldbody, "camera")
61
+
62
+ # -------------------------------------------------------------------------------------- #
63
+ # Public Properties: In general, these are the name-adjusted versions from the private #
64
+ # attributes pulled from their respective raw xml files #
65
+ # -------------------------------------------------------------------------------------- #
66
+
67
+ @property
68
+ def eef_name(self):
69
+ """
70
+ Returns:
71
+ str or dict of str: Prefix-adjusted eef name for this robot. If bimanual robot, returns {"left", "right"}
72
+ keyword-mapped eef names
73
+ """
74
+ return self.correct_naming(self._eef_name)
75
+
76
+ @property
77
+ def models(self):
78
+ """
79
+ Returns a list of all m(sub-)models owned by this robot model. By default, this includes the gripper model,
80
+ if specified
81
+
82
+ Returns:
83
+ list: models owned by this object
84
+ """
85
+ models = super().models
86
+ return models + list(self.grippers.values())
87
+
88
+ # -------------------------------------------------------------------------------------- #
89
+ # -------------------------- Private Properties ---------------------------------------- #
90
+ # -------------------------------------------------------------------------------------- #
91
+
92
+ @property
93
+ def _important_sites(self):
94
+ """
95
+ Returns:
96
+ dict: (Default is no important sites; i.e.: empty dict)
97
+ """
98
+ return {}
99
+
100
+ @property
101
+ def _eef_name(self):
102
+ """
103
+ XML eef name for this robot to which grippers can be attached. Note that these should be the raw
104
+ string names directly pulled from a robot's corresponding XML file, NOT the adjusted name with an
105
+ auto-generated naming prefix
106
+
107
+ Returns:
108
+ str: Raw XML eef name for this robot (default is "right_hand")
109
+ """
110
+ return "right_hand"
111
+
112
+ # -------------------------------------------------------------------------------------- #
113
+ # All subclasses must implement the following properties #
114
+ # -------------------------------------------------------------------------------------- #
115
+
116
+ @property
117
+ def default_gripper(self):
118
+ """
119
+ Defines the default gripper type for this robot that gets added to end effector
120
+
121
+ Returns:
122
+ str: Default gripper name to add to this robot
123
+ """
124
+ raise NotImplementedError
125
+
126
+ @property
127
+ def arm_type(self):
128
+ """
129
+ Type of robot arm. Should be either "bimanual" or "single" (or something else if it gets added in the future)
130
+
131
+ Returns:
132
+ str: Type of robot
133
+ """
134
+ raise NotImplementedError
135
+
136
+ @property
137
+ def base_xpos_offset(self):
138
+ """
139
+ Defines the dict of various (x,y,z) tuple offsets relative to specific arenas placed at (0,0,0)
140
+ Assumes robot is facing forwards (in the +x direction) when determining offset. Should have entries for each
141
+ manipulator arena case; i.e.: "bins", "empty", and "table")
142
+
143
+ Returns:
144
+ dict:
145
+
146
+ :`'bins'`: (x,y,z) robot offset if placed in bins arena
147
+ :`'empty'`: (x,y,z) robot offset if placed in the empty arena
148
+ :`'table'`: lambda function that takes in table_length and returns corresponding (x,y,z) offset
149
+ if placed in the table arena
150
+ """
151
+ raise NotImplementedError
152
+
153
+ @property
154
+ def top_offset(self):
155
+ raise NotImplementedError
156
+
157
+ @property
158
+ def _horizontal_radius(self):
159
+ raise NotImplementedError
160
+
161
+ @property
162
+ def default_mount(self):
163
+ raise NotImplementedError
164
+
165
+ @property
166
+ def default_controller_config(self):
167
+ raise NotImplementedError
168
+
169
+ @property
170
+ def init_qpos(self):
171
+ raise NotImplementedError
third_party/robosuite/robosuite/models/robots/manipulators/iiwa_robot.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel
4
+ from robosuite.utils.mjcf_utils import xml_path_completion
5
+
6
+
7
+ class IIWA(ManipulatorModel):
8
+ """
9
+ IIWA is a bright and spunky robot created by KUKA
10
+
11
+ Args:
12
+ idn (int or str): Number or some other unique identification string for this robot instance
13
+ """
14
+
15
+ arms = ["right"]
16
+
17
+ def __init__(self, idn=0):
18
+ super().__init__(xml_path_completion("robots/iiwa/robot.xml"), idn=idn)
19
+
20
+ @property
21
+ def default_base(self):
22
+ return "RethinkMount"
23
+
24
+ @property
25
+ def default_gripper(self):
26
+ return {"right": "Robotiq140Gripper"}
27
+
28
+ @property
29
+ def default_controller_config(self):
30
+ return {"right": "default_iiwa"}
31
+
32
+ @property
33
+ def init_qpos(self):
34
+ return np.array([0.000, 0.650, 0.000, -1.890, 0.000, 0.600, 0.000])
35
+
36
+ @property
37
+ def base_xpos_offset(self):
38
+ return {
39
+ "bins": (-0.5, -0.1, 0),
40
+ "empty": (-0.6, 0, 0),
41
+ "table": lambda table_length: (-0.16 - table_length / 2, 0, 0),
42
+ }
43
+
44
+ @property
45
+ def top_offset(self):
46
+ return np.array((0, 0, 1.0))
47
+
48
+ @property
49
+ def _horizontal_radius(self):
50
+ return 0.5
51
+
52
+ @property
53
+ def arm_type(self):
54
+ return "single"
third_party/robosuite/robosuite/models/robots/manipulators/jaco_robot.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel
4
+ from robosuite.utils.mjcf_utils import xml_path_completion
5
+
6
+
7
+ class Jaco(ManipulatorModel):
8
+ """
9
+ Jaco is a kind and assistive robot created by Kinova
10
+
11
+ Args:
12
+ idn (int or str): Number or some other unique identification string for this robot instance
13
+ """
14
+
15
+ arms = ["right"]
16
+
17
+ def __init__(self, idn=0):
18
+ super().__init__(xml_path_completion("robots/jaco/robot.xml"), idn=idn)
19
+
20
+ @property
21
+ def default_base(self):
22
+ return "RethinkMount"
23
+
24
+ @property
25
+ def default_gripper(self):
26
+ return {"right": "JacoThreeFingerGripper"}
27
+
28
+ @property
29
+ def default_controller_config(self):
30
+ return {"right": "default_jaco"}
31
+
32
+ @property
33
+ def init_qpos(self):
34
+ return np.array([3.192, 3.680, -0.000, 1.170, 0.050, 3.760, 3.142])
35
+
36
+ @property
37
+ def base_xpos_offset(self):
38
+ return {
39
+ "bins": (-0.5, -0.1, 0),
40
+ "empty": (-0.6, 0, 0),
41
+ "table": lambda table_length: (-0.16 - table_length / 2, 0, 0),
42
+ }
43
+
44
+ @property
45
+ def top_offset(self):
46
+ return np.array((0, 0, 1.0))
47
+
48
+ @property
49
+ def _horizontal_radius(self):
50
+ return 0.5
51
+
52
+ @property
53
+ def arm_type(self):
54
+ return "single"
third_party/robosuite/robosuite/models/robots/manipulators/kinova3_robot.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel
4
+ from robosuite.utils.mjcf_utils import xml_path_completion
5
+
6
+
7
+ class Kinova3(ManipulatorModel):
8
+ """
9
+ The Gen3 robot is the sparkly newest addition to the Kinova line
10
+
11
+ Args:
12
+ idn (int or str): Number or some other unique identification string for this robot instance
13
+ """
14
+
15
+ arms = ["right"]
16
+
17
+ def __init__(self, idn=0):
18
+ super().__init__(xml_path_completion("robots/kinova3/robot.xml"), idn=idn)
19
+
20
+ @property
21
+ def default_base(self):
22
+ return "RethinkMount"
23
+
24
+ @property
25
+ def default_gripper(self):
26
+ return {"right": "Robotiq85Gripper"}
27
+
28
+ @property
29
+ def default_controller_config(self):
30
+ return {"right": "osc_pose"}
31
+
32
+ @property
33
+ def init_qpos(self):
34
+ return np.array([0.000, 0.650, 0.000, 1.890, 0.000, 0.600, -np.pi / 2])
35
+
36
+ @property
37
+ def base_xpos_offset(self):
38
+ return {
39
+ "bins": (-0.5, -0.1, 0),
40
+ "empty": (-0.6, 0, 0),
41
+ "table": lambda table_length: (-0.16 - table_length / 2, 0, 0),
42
+ }
43
+
44
+ @property
45
+ def top_offset(self):
46
+ return np.array((0, 0, 1.0))
47
+
48
+ @property
49
+ def _horizontal_radius(self):
50
+ return 0.5
51
+
52
+ @property
53
+ def arm_type(self):
54
+ return "single"
third_party/robosuite/robosuite/models/robots/manipulators/legged_manipulator_model.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+
3
+ import numpy as np
4
+
5
+ from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel
6
+ from robosuite.utils.mjcf_utils import find_parent
7
+
8
+
9
+ class LeggedManipulatorModel(ManipulatorModel):
10
+ """
11
+ Base class for all manipulator models (robot arm(s) with gripper(s)).
12
+
13
+ Args:
14
+ fname (str): Path to relevant xml file from which to create this robot instance
15
+ idn (int or str): Number or some other unique identification string for this robot instance
16
+ """
17
+
18
+ def __init__(self, fname, idn=0):
19
+ # Always run super init first
20
+ super().__init__(fname, idn=idn)
21
+
22
+ def _remove_joint_actuation(self, part_name):
23
+ for joint in self.worldbody.findall(".//joint"):
24
+ if part_name in joint.get("name"):
25
+ parent_body = find_parent(self.worldbody, joint)
26
+ parent_body.remove(joint)
27
+ self._joints.remove(joint.get("name").replace(self.naming_prefix, ""))
28
+ for motor in self.actuator.findall(".//motor"):
29
+ if part_name in motor.get("name"):
30
+ parent_body = find_parent(self.actuator, motor)
31
+ parent_body.remove(motor)
32
+ self._actuators.remove(motor.get("name").replace(self.naming_prefix, ""))
33
+ for motor in self.actuator.findall(".//position"):
34
+ if part_name in motor.get("name"):
35
+ parent_body = find_parent(self.actuator, motor)
36
+ parent_body.remove(motor)
37
+ self._actuators.remove(motor.get("name").replace(self.naming_prefix, ""))
38
+ for fixed in self.tendon.findall(".//fixed"):
39
+ for joint in fixed.findall(".//joint"):
40
+ if part_name in joint.get("joint"):
41
+ parent_body = find_parent(self.tendon, fixed)
42
+ parent_body.remove(fixed)
43
+ break
44
+ # remove joint in equality
45
+ for equality in self.equality.findall(".//joint"):
46
+ # If either joint1 or joint2 is the joint we want to remove
47
+ if part_name in equality.get("joint1") or part_name in equality.get("joint2"):
48
+ parent_body = find_parent(self.equality, equality)
49
+ parent_body.remove(equality)
50
+
51
+ def _remove_free_joint(self):
52
+ # remove freejoint
53
+ for freejoint in self.worldbody.findall(".//freejoint"):
54
+ find_parent(self.worldbody, freejoint).remove(freejoint)
55
+
56
+ @property
57
+ def legs_joints(self):
58
+ """
59
+ No need for name correcting because the prefix has been added during creation.
60
+
61
+ Returns:
62
+ list: (Default is no joints; i.e.: empty dict)
63
+ """
64
+ return self._legs_joints
third_party/robosuite/robosuite/models/robots/manipulators/manipulator_model.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import Dict, List, Optional, Union
3
+
4
+ import numpy as np
5
+
6
+ from robosuite.models.grippers.gripper_model import GripperModel
7
+ from robosuite.models.robots import RobotModel
8
+ from robosuite.utils.mjcf_utils import find_elements, find_elements_by_substring, string_to_array
9
+
10
+
11
+ class ManipulatorModel(RobotModel):
12
+ """
13
+ Base class for all manipulator models (robot arm(s) with gripper(s)).
14
+
15
+ Args:
16
+ fname (str): Path to relevant xml file from which to create this robot instance
17
+ idn (int or str): Number or some other unique identification string for this robot instance
18
+ """
19
+
20
+ def __init__(self, fname: str, idn=0):
21
+ # Always run super init first
22
+ super().__init__(fname, idn=idn)
23
+
24
+ # key: gripper name and value: gripper model
25
+ self.grippers = OrderedDict()
26
+
27
+ # # Grab hand's offset from final robot link (string -> np.array -> elements [1, 2, 3, 0] (x, y, z, w))
28
+ # # Different case based on whether we're dealing with single or bimanual armed robot
29
+ # if self.arm_type == "single":
30
+ # hand_element = find_elements(
31
+ # root=self.root, tags="body", attribs={"name": self.eef_name}, return_first=True
32
+ # )
33
+ # self.hand_rotation_offset = string_to_array(hand_element.get("quat", "1 0 0 0"))[[1, 2, 3, 0]]
34
+ # else: # "bimanual" case
35
+ if self.arm_type == "single":
36
+ arms = ["right"]
37
+ elif self.arm_type == "bimanual":
38
+ arms = ["right", "left"]
39
+ self.hand_rotation_offset = {}
40
+ for arm in arms:
41
+ hand_element = find_elements(
42
+ root=self.root, tags="body", attribs={"name": self.eef_name[arm]}, return_first=True
43
+ )
44
+ self.hand_rotation_offset[arm] = string_to_array(hand_element.get("quat", "1 0 0 0"))[[1, 2, 3, 0]]
45
+
46
+ # Get camera names for this robot
47
+ self.cameras = self.get_element_names(self.worldbody, "camera")
48
+
49
+ self._base_actuators = []
50
+ self._torso_actuators = []
51
+ self._head_actuators = []
52
+ self._legs_actuators = []
53
+
54
+ self._arms_actuators = []
55
+ # specify arm actuators by excluding overallpy actuators from previous ones
56
+
57
+ self._base_joints = []
58
+ self._torso_joints = []
59
+ self._head_joints = []
60
+ self._legs_joints = []
61
+
62
+ self._arms_joints = []
63
+
64
+ def add_gripper(self, gripper: GripperModel, arm_name: Optional[str] = None):
65
+ """
66
+ Mounts @gripper to arm.
67
+
68
+ Throws error if robot already has a gripper or gripper type is incorrect.
69
+
70
+ Args:
71
+ gripper (GripperModel): gripper MJCF model
72
+ arm_name (str): name of arm mount --
73
+ defaults add to all self.eef_name if not specified
74
+
75
+ Raises:
76
+ ValueError: [Multiple grippers]
77
+ """
78
+ if arm_name is None:
79
+ assert isinstance(self.eef_name, dict), "only support single insertion of gripper now"
80
+ arm_names = list(self.eef_name.values())
81
+ else:
82
+ arm_names = [arm_name]
83
+
84
+ for arm_name in arm_names:
85
+ if arm_name in self.grippers:
86
+ raise ValueError("Attempts to add multiple grippers to one body")
87
+
88
+ self.merge(gripper, merge_body=arm_name)
89
+
90
+ self.grippers[arm_name] = gripper
91
+
92
+ # Update cameras in this model
93
+ self.cameras = self.get_element_names(self.worldbody, "camera")
94
+
95
+ def update_joints(self):
96
+ """internal function to update joint lists"""
97
+ for joint in self.all_joints:
98
+ if "torso" in joint:
99
+ self.torso_joints.append(joint)
100
+ elif "mobile" in joint:
101
+ self.base_joints.append(joint)
102
+ elif "head" in joint:
103
+ self.head_joints.append(joint)
104
+ elif "leg" in joint:
105
+ self.legs_joints.append(joint)
106
+
107
+ for joint in self.all_joints:
108
+ if (
109
+ joint not in self._base_joints
110
+ and joint not in self._torso_joints
111
+ and joint not in self._head_joints
112
+ and joint not in self._legs_joints
113
+ ):
114
+ self._arms_joints.append(joint)
115
+
116
+ def update_actuators(self):
117
+ """internal function to update actuator lists"""
118
+ for actuator in self.all_actuators:
119
+ if "torso" in actuator:
120
+ self.torso_actuators.append(actuator)
121
+ elif "mobile" in actuator:
122
+ self.base_actuators.append(actuator)
123
+ elif "head" in actuator:
124
+ self.head_actuators.append(actuator)
125
+ elif "leg" in actuator:
126
+ self.legs_actuators.append(actuator)
127
+
128
+ for actuator in self.all_actuators:
129
+ if (
130
+ actuator not in self._base_actuators
131
+ and actuator not in self._torso_actuators
132
+ and actuator not in self._head_actuators
133
+ and actuator not in self._legs_actuators
134
+ ):
135
+ self._arms_actuators.append(actuator)
136
+
137
+ # -------------------------------------------------------------------------------------- #
138
+ # Public Properties: In general, these are the name-adjusted versions from the private #
139
+ # attributes pulled from their respective raw xml files #
140
+ # -------------------------------------------------------------------------------------- #
141
+
142
+ @property
143
+ def eef_name(self) -> Dict[str, str]:
144
+ """
145
+ Returns:
146
+ dict of str: Prefix-adjusted eef name for this robot. If bimanual robot, returns {"left", "right"}
147
+ keyword-mapped eef names
148
+ """
149
+ return self.correct_naming(self._eef_name)
150
+
151
+ @property
152
+ def models(self) -> List[Union[GripperModel, RobotModel]]:
153
+ """
154
+ Returns a list of all m(sub-)models owned by this robot model. By default, this includes the gripper model,
155
+ if specified
156
+
157
+ Returns:
158
+ list: models owned by this object
159
+ """
160
+ models = super().models
161
+ return models + list(self.grippers.values())
162
+
163
+ # -------------------------------------------------------------------------------------- #
164
+ # -------------------------- Private Properties ---------------------------------------- #
165
+ # -------------------------------------------------------------------------------------- #
166
+
167
+ @property
168
+ def _important_sites(self) -> Dict[str, str]:
169
+ """
170
+ Returns:
171
+ dict: (Default is no important sites; i.e.: empty dict)
172
+ """
173
+ return {}
174
+
175
+ @property
176
+ def _eef_name(self) -> Dict[str, str]:
177
+ """
178
+ XML eef name for this robot to which grippers can be attached. Note that these should be the raw
179
+ string names directly pulled from a robot's corresponding XML file, NOT the adjusted name with an
180
+ auto-generated naming prefix
181
+
182
+ Returns:
183
+ dict of str: eef name of this robot.
184
+ If bimanual robot, returns {"left", "right"} keyword-mapped eef names
185
+ """
186
+ return {"right": "right_hand"}
187
+
188
+ # -------------------------------------------------------------------------------------- #
189
+ # All subclasses must implement the following properties #
190
+ # -------------------------------------------------------------------------------------- #
191
+
192
+ @property
193
+ def default_gripper(self) -> Dict[str, str]:
194
+ """
195
+ Defines the default gripper type for this robot that gets added to end effector
196
+
197
+ Returns:
198
+ dict: (Default is no gripper; i.e.: empty dict)
199
+ """
200
+ raise NotImplementedError
201
+
202
+ @property
203
+ def gripper_mount_pos_offset(self):
204
+ """
205
+ Define the custom offset of the gripper that is different from the one defined in xml.
206
+ The offset will applied to the first body in the gripper definition file.
207
+
208
+ Returns:
209
+ Empty dictionary unless specified.
210
+ """
211
+ return {}
212
+
213
+ @property
214
+ def gripper_mount_quat_offset(self):
215
+ """
216
+ Define the custom orientation offset of the gripper with respect to the arm.
217
+ The offset will applied to the first body in the gripper definition file.
218
+ Return empty dict by default unless specified.
219
+ The quaternion is in the (w, x, y, z) format to match the mjcf format.
220
+ """
221
+ return {}
222
+
223
+ @property
224
+ def arm_type(self) -> str:
225
+ """
226
+ Type of robot arm. Should be either "bimanual" or "single" (or something else if it gets added in the future)
227
+
228
+ Returns:
229
+ str: Type of robot
230
+ """
231
+ raise NotImplementedError
232
+
233
+ @property
234
+ def base_xpos_offset(self) -> Dict[str, Union[tuple, dict]]:
235
+ """
236
+ Defines the dict of various (x,y,z) tuple offsets relative to specific arenas placed at (0,0,0)
237
+ Assumes robot is facing forwards (in the +x direction) when determining offset. Should have entries for each
238
+ manipulator arena case; i.e.: "bins", "empty", and "table")
239
+
240
+ Returns:
241
+ dict:
242
+
243
+ :`'bins'`: (x,y,z) robot offset if placed in bins arena
244
+ :`'empty'`: (x,y,z) robot offset if placed in the empty arena
245
+ :`'table'`: lambda function that takes in table_length and returns corresponding (x,y,z) offset
246
+ if placed in the table arena
247
+ """
248
+ raise NotImplementedError
249
+
250
+ @property
251
+ def top_offset(self) -> np.array:
252
+ raise NotImplementedError
253
+
254
+ @property
255
+ def _horizontal_radius(self):
256
+ raise NotImplementedError
257
+
258
+ @property
259
+ def default_base(self):
260
+ raise NotImplementedError
261
+
262
+ @property
263
+ def default_controller_config(self):
264
+ raise NotImplementedError
265
+
266
+ @property
267
+ def init_qpos(self):
268
+ raise NotImplementedError
269
+
270
+ @property
271
+ def init_base_qpos(self):
272
+ return None
273
+
274
+ @property
275
+ def init_torso_qpos(self):
276
+ return None
277
+
278
+ @property
279
+ def arm_actuators(self):
280
+ """
281
+ No need for name correcting because the prefix has been added during creation.
282
+
283
+ Returns:
284
+ list: (Default is no actuators; i.e.: empty dict)
285
+ """
286
+ return self._arms_actuators
287
+
288
+ @property
289
+ def base_actuators(self):
290
+ """
291
+ No need for name correcting because the prefix has been added during creation.
292
+
293
+ Returns:
294
+ list: (Default is no actuators; i.e.: empty dict)
295
+ """
296
+ return self._base_actuators
297
+
298
+ @property
299
+ def torso_actuators(self):
300
+ """
301
+ No need for name correcting because the prefix has been added during creation.
302
+
303
+ Returns:
304
+ list: (Default is no actuators; i.e.: empty dict)
305
+ """
306
+ return self._torso_actuators
307
+
308
+ @property
309
+ def head_actuators(self):
310
+ """
311
+ No need for name correcting because the prefix has been added during creation.
312
+
313
+ Returns:
314
+ list: (Default is no actuators; i.e.: empty dict)
315
+ """
316
+ return self._head_actuators
317
+
318
+ @property
319
+ def legs_actuators(self):
320
+ """
321
+ No need for name correcting because the prefix has been added during creation.
322
+
323
+ Returns:
324
+ list: (Default is no actuators; i.e.: empty dict)
325
+ """
326
+ return self._legs_actuators
327
+
328
+ @property
329
+ def arm_joints(self):
330
+ """
331
+ No need for name correcting because the prefix has been added during creation.
332
+
333
+ Returns:
334
+ list: (Default is no joints; i.e.: empty dict)
335
+ """
336
+ return self._arms_joints
337
+
338
+ @property
339
+ def base_joints(self):
340
+ """
341
+ No need for name correcting because the prefix has been added during creation.
342
+
343
+ Returns:
344
+ list: (Default is no joints; i.e.: empty dict)
345
+ """
346
+ return self._base_joints
347
+
348
+ @property
349
+ def torso_joints(self):
350
+ """
351
+ No need for name correcting because the prefix has been added during creation.
352
+
353
+ Returns:
354
+ list: (Default is no joints; i.e.: empty dict)
355
+ """
356
+ return self._torso_joints
357
+
358
+ @property
359
+ def head_joints(self):
360
+ """
361
+ No need for name correcting because the prefix has been added during creation.
362
+
363
+ Returns:
364
+ list: (Default is no joints; i.e.: empty dict)
365
+ """
366
+ return self._head_joints
367
+
368
+ @property
369
+ def legs_joints(self):
370
+ """
371
+ No need for name correcting because the prefix has been added during creation.
372
+
373
+ Returns:
374
+ list: (Default is no joints; i.e.: empty dict)
375
+ """
376
+ return self._legs_joints
third_party/robosuite/robosuite/models/robots/manipulators/panda_robot.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel
4
+ from robosuite.utils.mjcf_utils import xml_path_completion
5
+
6
+
7
+ class Panda(ManipulatorModel):
8
+ """
9
+ Panda is a sensitive single-arm robot designed by Franka.
10
+
11
+ Args:
12
+ idn (int or str): Number or some other unique identification string for this robot instance
13
+ """
14
+
15
+ arms = ["right"]
16
+
17
+ def __init__(self, idn=0):
18
+ super().__init__(xml_path_completion("robots/panda/robot.xml"), idn=idn)
19
+
20
+ # Set joint damping
21
+ self.set_joint_attribute(attrib="damping", values=np.array((0.1, 0.1, 0.1, 0.1, 0.1, 0.01, 0.01)))
22
+
23
+ @property
24
+ def default_base(self):
25
+ return "RethinkMount"
26
+
27
+ @property
28
+ def default_gripper(self):
29
+ return {"right": "PandaGripper"}
30
+
31
+ @property
32
+ def default_controller_config(self):
33
+ return {"right": "default_panda"}
34
+
35
+ @property
36
+ def init_qpos(self):
37
+ return np.array([0, np.pi / 16.0, 0.00, -np.pi / 2.0 - np.pi / 3.0, 0.00, np.pi - 0.2, np.pi / 4])
38
+
39
+ @property
40
+ def base_xpos_offset(self):
41
+ return {
42
+ "bins": (-0.5, -0.1, 0),
43
+ "empty": (-0.6, 0, 0),
44
+ "table": lambda table_length: (-0.16 - table_length / 2, 0, 0),
45
+ }
46
+
47
+ @property
48
+ def top_offset(self):
49
+ return np.array((0, 0, 1.0))
50
+
51
+ @property
52
+ def _horizontal_radius(self):
53
+ return 0.5
54
+
55
+ @property
56
+ def arm_type(self):
57
+ return "single"
third_party/robosuite/robosuite/models/robots/manipulators/sawyer_robot.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel
4
+ from robosuite.utils.mjcf_utils import xml_path_completion
5
+
6
+
7
+ class Sawyer(ManipulatorModel):
8
+ """
9
+ Sawyer is a witty single-arm robot designed by Rethink Robotics.
10
+
11
+ Args:
12
+ idn (int or str): Number or some other unique identification string for this robot instance
13
+ """
14
+
15
+ arms = ["right"]
16
+
17
+ def __init__(self, idn=0):
18
+ super().__init__(xml_path_completion("robots/sawyer/robot.xml"), idn=idn)
19
+
20
+ @property
21
+ def default_base(self):
22
+ return "RethinkMount"
23
+
24
+ @property
25
+ def default_gripper(self):
26
+ return {"right": "RethinkGripper"}
27
+
28
+ @property
29
+ def default_controller_config(self):
30
+ return {"right": "default_sawyer"}
31
+
32
+ @property
33
+ def init_qpos(self):
34
+ return np.array([0, -1.18, 0.00, 2.18, 0.00, 0.57, -1.57])
35
+
36
+ @property
37
+ def base_xpos_offset(self):
38
+ return {
39
+ "bins": (-0.5, -0.1, 0),
40
+ "empty": (-0.6, 0, 0),
41
+ "table": lambda table_length: (-0.16 - table_length / 2, 0, 0),
42
+ }
43
+
44
+ @property
45
+ def top_offset(self):
46
+ return np.array((0, 0, 1.0))
47
+
48
+ @property
49
+ def _horizontal_radius(self):
50
+ return 0.5
51
+
52
+ @property
53
+ def arm_type(self):
54
+ return "single"
third_party/robosuite/robosuite/models/robots/manipulators/spot_arm.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel
4
+ from robosuite.utils.mjcf_utils import xml_path_completion
5
+
6
+
7
+ class SpotArm(ManipulatorModel):
8
+ """
9
+ Spot Arm is a single-arm robot for mouting on the spot robot.
10
+
11
+ Args:
12
+ idn (int or str): Number or some other unique identification string for this robot instance
13
+ """
14
+
15
+ arms = ["right"]
16
+
17
+ def __init__(self, idn=0):
18
+ super().__init__(xml_path_completion("robots/spot_arm/robot.xml"), idn=idn)
19
+
20
+ # Set joint damping
21
+ self.set_joint_attribute(attrib="damping", values=np.array((0.1, 0.1, 0.1, 0.1, 0.1, 0.01)))
22
+
23
+ @property
24
+ def default_base(self):
25
+ return "RethinkMount"
26
+
27
+ @property
28
+ def default_gripper(self):
29
+ return {"right": "BDGripper"}
30
+
31
+ @property
32
+ def default_controller_config(self):
33
+ return {"right": "default_spot"}
34
+
35
+ @property
36
+ def init_qpos(self):
37
+ return np.array([0.0, -1.2, 1.85, 0.0, 0.862, 0.0])
38
+
39
+ @property
40
+ def base_xpos_offset(self):
41
+ return {
42
+ "bins": (-0.5, -0.1, 0),
43
+ "empty": (-0.6, 0, 0),
44
+ "table": lambda table_length: (-0.16 - 0.9 - table_length / 2, 0.0, 0.0),
45
+ }
46
+
47
+ @property
48
+ def top_offset(self):
49
+ return np.array((0, 0, 1.0))
50
+
51
+ @property
52
+ def _horizontal_radius(self):
53
+ return 0.5
54
+
55
+ @property
56
+ def arm_type(self):
57
+ return "single"
third_party/robosuite/robosuite/models/robots/manipulators/tiago_robot.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel
4
+ from robosuite.utils.mjcf_utils import xml_path_completion
5
+
6
+
7
+ class Tiago(ManipulatorModel):
8
+ """
9
+ Tiago is a mobile manipulator robot created by PAL Robotics.
10
+
11
+ Args:
12
+ idn (int or str): Number or some other unique identification string for this robot instance
13
+ """
14
+
15
+ arms = ["right", "left"]
16
+
17
+ def __init__(self, idn=0):
18
+ super().__init__(xml_path_completion("robots/tiago/robot.xml"), idn=idn)
19
+
20
+ @property
21
+ def default_base(self):
22
+ return "NullMobileBase"
23
+
24
+ @property
25
+ def default_gripper(self):
26
+ """
27
+ Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective
28
+ values
29
+
30
+ Returns:
31
+ dict: Dictionary containing arm-specific gripper names
32
+ """
33
+ return {"right": "Robotiq85Gripper", "left": "Robotiq85Gripper"}
34
+
35
+ @property
36
+ def default_controller_config(self):
37
+ """
38
+ Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective
39
+ values
40
+
41
+ Returns:
42
+ dict: Dictionary containing arm-specific default controller config names
43
+ """
44
+ return {
45
+ "right": "joint_position",
46
+ "left": "joint_position",
47
+ "head": "joint_position",
48
+ "torso": "joint_position",
49
+ }
50
+
51
+ @property
52
+ def init_qpos(self):
53
+ """
54
+ Since this is bimanual robot, returns [right, left] array corresponding to respective values
55
+
56
+ Note that this is a pose such that the arms are half extended
57
+
58
+ Returns:
59
+ np.array: default initial qpos for the right, left arms
60
+ """
61
+ # [right, left]
62
+ # Arms half extended
63
+ return np.array(
64
+ [
65
+ 0.1,
66
+ 0,
67
+ 0,
68
+ 0,
69
+ -0.9,
70
+ 1.45,
71
+ 1.7,
72
+ -1.5,
73
+ 0.5,
74
+ 0,
75
+ -0.9,
76
+ 1.45,
77
+ 1.7,
78
+ -1.5,
79
+ 0.5,
80
+ ]
81
+ )
82
+
83
+ @property
84
+ def base_xpos_offset(self):
85
+ return {
86
+ "bins": (-0.5, -0.1, 0),
87
+ "empty": (-0.29, 0, 0),
88
+ "table": lambda table_length: (-0.20 - table_length / 2, 0, 0),
89
+ }
90
+
91
+ @property
92
+ def top_offset(self):
93
+ return np.array((0, 0, 1.0))
94
+
95
+ @property
96
+ def _horizontal_radius(self):
97
+ return 0.5
98
+
99
+ @property
100
+ def arm_type(self):
101
+ return "bimanual"
102
+
103
+ @property
104
+ def _eef_name(self):
105
+ """
106
+ Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective
107
+ values
108
+
109
+ Returns:
110
+ dict: Dictionary containing arm-specific eef names
111
+ """
112
+ return {"right": "right_hand", "left": "left_hand"}
third_party/robosuite/robosuite/models/robots/manipulators/ur5e_robot.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel
4
+ from robosuite.utils.mjcf_utils import xml_path_completion
5
+
6
+
7
+ class UR5e(ManipulatorModel):
8
+ """
9
+ UR5e is a sleek and elegant new robot created by Universal Robots
10
+
11
+ Args:
12
+ idn (int or str): Number or some other unique identification string for this robot instance
13
+ """
14
+
15
+ arms = ["right"]
16
+
17
+ def __init__(self, idn=0):
18
+ super().__init__(xml_path_completion("robots/ur5e/robot.xml"), idn=idn)
19
+
20
+ @property
21
+ def default_base(self):
22
+ return "RethinkMount"
23
+
24
+ @property
25
+ def default_gripper(self):
26
+ return {"right": "Robotiq85Gripper"}
27
+
28
+ @property
29
+ def default_controller_config(self):
30
+ return {"right": "default_ur5e"}
31
+
32
+ @property
33
+ def init_qpos(self):
34
+ return np.array([-0.470, -1.735, 2.480, -2.275, -1.590, -1.991])
35
+
36
+ @property
37
+ def base_xpos_offset(self):
38
+ return {
39
+ "bins": (-0.5, -0.1, 0),
40
+ "empty": (-0.6, 0, 0),
41
+ "table": lambda table_length: (-0.16 - table_length / 2, 0, 0),
42
+ }
43
+
44
+ @property
45
+ def top_offset(self):
46
+ return np.array((0, 0, 1.0))
47
+
48
+ @property
49
+ def _horizontal_radius(self):
50
+ return 0.5
51
+
52
+ @property
53
+ def arm_type(self):
54
+ return "single"
third_party/robosuite/robosuite/models/robots/robot_model.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from copy import deepcopy
2
+ from typing import Dict, List, Optional
3
+
4
+ import mujoco
5
+ import numpy as np
6
+
7
+ from robosuite.models.base import MujocoXMLModel
8
+ from robosuite.models.bases import LegBaseModel, MobileBaseModel, MountModel, RobotBaseModel
9
+ from robosuite.utils.mjcf_utils import ROBOT_COLLISION_COLOR, array_to_string, find_elements, find_parent
10
+ from robosuite.utils.transform_utils import euler2mat, mat2quat
11
+
12
+ REGISTERED_ROBOTS = {}
13
+
14
+
15
+ def register_robot(target_class):
16
+ REGISTERED_ROBOTS[target_class.__name__] = target_class
17
+
18
+
19
+ def create_robot(robot_name, *args, **kwargs):
20
+ """
21
+ Instantiates a Robot object.
22
+
23
+ Args:
24
+ robot_name (str): Name of the robot to initialize
25
+ *args: Additional arguments to pass to the specific Robot class initializer
26
+ **kwargs: Additional arguments to pass to the specific Robot class initializer
27
+
28
+ Returns:
29
+ Robot: Desired robot
30
+
31
+ Raises:
32
+ Exception: [Invalid robot name]
33
+ """
34
+ if robot_name not in REGISTERED_ROBOTS:
35
+ raise Exception(
36
+ "Robot {} not found. Make sure it is a registered robot among: {}".format(
37
+ robot_name, ", ".join(REGISTERED_ROBOTS)
38
+ )
39
+ )
40
+ return REGISTERED_ROBOTS[robot_name](*args, **kwargs)
41
+
42
+
43
+ class RobotModelMeta(type):
44
+ """Metaclass for registering robot arms"""
45
+
46
+ def __new__(meta, name, bases, class_dict):
47
+ cls = super().__new__(meta, name, bases, class_dict)
48
+
49
+ # List all environments that should not be registered here.
50
+ _unregistered_envs = ["RobotModel", "ManipulatorModel"]
51
+
52
+ if cls.__name__ not in _unregistered_envs:
53
+ register_robot(cls)
54
+ return cls
55
+
56
+
57
+ class RobotModel(MujocoXMLModel, metaclass=RobotModelMeta):
58
+ """
59
+ Base class for all robot models.
60
+
61
+ Args:
62
+ fname (str): Path to relevant xml file from which to create this robot instance
63
+ idn (int or str): Number or some other unique identification string for this robot instance
64
+ """
65
+
66
+ def __init__(self, fname: str, idn=0):
67
+ super().__init__(fname, idn=idn)
68
+
69
+ # Define other variables that get filled later
70
+ self.base = None
71
+
72
+ # Get camera names for this robot
73
+ self.cameras = self.get_element_names(self.worldbody, "camera")
74
+
75
+ # By default, set small frictionloss and armature values
76
+ self.set_joint_attribute(attrib="frictionloss", values=0.1 * np.ones(self.dof), force=False)
77
+ self.set_joint_attribute(attrib="damping", values=0.1 * np.ones(self.dof), force=False)
78
+ self.set_joint_attribute(
79
+ attrib="armature", values=np.array([5.0 / (i + 1) for i in range(self.dof)]), force=False
80
+ )
81
+ self.mujoco_model: Optional[mujoco.MjModel] = None
82
+
83
+ def set_mujoco_model(self, mujoco_model: Optional[mujoco.MjModel] = None):
84
+ if mujoco_model is not None:
85
+ self.mujoco_model = mujoco_model
86
+ else:
87
+ self.mujoco_model = self.get_model()
88
+
89
+ def set_base_xpos(self, pos: np.ndarray):
90
+ """
91
+ Places the robot on position @pos.
92
+
93
+ Args:
94
+ pos (3-array): (x,y,z) position to place robot base
95
+ """
96
+ self._elements["root_body"].set("pos", array_to_string(pos - self.bottom_offset))
97
+
98
+ def set_base_ori(self, rot: np.ndarray):
99
+ """
100
+ Rotates robot by rotation @rot from its original orientation.
101
+
102
+ Args:
103
+ rot (3-array): (r,p,y) euler angles specifying the orientation for the robot base
104
+ """
105
+ # xml quat assumes w,x,y,z so we need to convert to this format from outputted x,y,z,w format from fcn
106
+ rot = mat2quat(euler2mat(rot))[[3, 0, 1, 2]]
107
+ self._elements["root_body"].set("quat", array_to_string(rot))
108
+
109
+ def set_joint_attribute(self, attrib: str, values: np.ndarray, force=True):
110
+ """
111
+ Sets joint attributes, e.g.: friction loss, damping, etc.
112
+
113
+ Args:
114
+ attrib (str): Attribute to set for all joints
115
+ values (n-array): Values to set for each joint
116
+ force (bool): If True, will automatically override any pre-existing value. Otherwise, if a value already
117
+ exists for this value, it will be skipped
118
+
119
+ Raises:
120
+ AssertionError: [Inconsistent dimension sizes]
121
+ """
122
+ assert values.size == len(self._elements["joints"]), (
123
+ "Error setting joint attributes: "
124
+ + "Values must be same size as joint dimension. Got {}, expected {}!".format(values.size, self.dof)
125
+ )
126
+ for i, joint in enumerate(self._elements["joints"]):
127
+ if force or joint.get(attrib, None) is None:
128
+ joint.set(attrib, array_to_string(np.array([values[i]])))
129
+
130
+ def add_base(self, base: RobotBaseModel):
131
+ """
132
+ Mounts a base to the robot. Bases are defined in robosuite.models.bases
133
+ """
134
+ if isinstance(base, MountModel):
135
+ self.add_mount(base)
136
+ elif isinstance(base, MobileBaseModel):
137
+ self.add_mobile_base(base)
138
+ elif isinstance(base, LegBaseModel):
139
+ self.add_leg_base(base)
140
+ else:
141
+ raise ValueError("Invalid base type to add to robot!")
142
+
143
+ def add_mount(self, mount: MountModel):
144
+ """
145
+ Mounts @mount to arm.
146
+
147
+ Throws error if robot already has a mount or if mount type i\s incorrect.
148
+
149
+ Args:
150
+ mount (MountModel): mount MJCF model
151
+
152
+ Raises:
153
+ ValueError: [mount already added]
154
+ """
155
+ if self.base is not None:
156
+ raise ValueError("Mount already added for this robot!")
157
+
158
+ # First adjust mount's base position
159
+ offset = self.base_offset - mount.top_offset
160
+ mount._elements["root_body"].set("pos", array_to_string(offset))
161
+
162
+ self.merge(mount, merge_body=self.root_body)
163
+
164
+ self.base = mount
165
+
166
+ # Update cameras in this model
167
+ self.cameras = self.get_element_names(self.worldbody, "camera")
168
+
169
+ def add_mobile_base(self, mobile_base: MobileBaseModel):
170
+ """
171
+ Mounts @mobile_base to arm.
172
+
173
+ Throws error if robot already has a mobile base or if mobile base type is incorrect.
174
+
175
+ Args:
176
+ mobile base (MobileBaseModel): mount MJCF model
177
+
178
+ Raises:
179
+ ValueError: [mobile base already added]
180
+ """
181
+ if self.base is not None:
182
+ raise ValueError("Mobile base already added for this robot!")
183
+
184
+ # First adjust mount's base position
185
+ offset = self.base_offset - mobile_base.top_offset
186
+ mobile_base._elements["root_body"].set("pos", array_to_string(offset))
187
+
188
+ # if the mount is mobile, the robot should be "merged" into the mount,
189
+ # so that when the mount moves the robot moves along with it
190
+ merge_body = self.root_body
191
+ root = find_elements(root=self.worldbody, tags="body", attribs={"name": merge_body}, return_first=True)
192
+ for body in mobile_base.worldbody:
193
+ root.append(body)
194
+ arm_root = find_elements(root=self.worldbody, tags="body", return_first=False)[1]
195
+
196
+ mount_support = find_elements(
197
+ root=self.worldbody, tags="body", attribs={"name": mobile_base.correct_naming("support")}, return_first=True
198
+ )
199
+ mount_support.append(deepcopy(arm_root))
200
+ root.remove(arm_root)
201
+ self.merge_assets(mobile_base)
202
+ for one_actuator in mobile_base.actuator:
203
+ self.actuator.append(one_actuator)
204
+ for one_sensor in mobile_base.sensor:
205
+ self.sensor.append(one_sensor)
206
+ for one_tendon in mobile_base.tendon:
207
+ self.tendon.append(one_tendon)
208
+ for one_equality in mobile_base.equality:
209
+ self.equality.append(one_equality)
210
+ for one_contact in mobile_base.contact:
211
+ self.contact.append(one_contact)
212
+
213
+ self.base = mobile_base
214
+
215
+ # Update cameras in this model
216
+ self.cameras = self.get_element_names(self.worldbody, "camera")
217
+
218
+ def add_leg_base(self, leg_base: LegBaseModel):
219
+ """
220
+ Mounts @mobile_base to arm.
221
+
222
+ Throws error if robot already has a mobile base or if mobile base type is incorrect.
223
+
224
+ Args:
225
+ mobile base (MobileBaseModel): mount MJCF model
226
+
227
+ Raises:
228
+ ValueError: [mobile base already added]
229
+ """
230
+ if self.base is not None:
231
+ raise ValueError("Mobile base already added for this robot!")
232
+
233
+ # First adjust mount's base position
234
+ offset = self.base_offset - leg_base.top_offset
235
+ leg_base._elements["root_body"].set("pos", array_to_string(offset))
236
+
237
+ # if the mount is mobile, the robot should be "merged" into the mount,
238
+ # so that when the mount moves the robot moves along with it
239
+ merge_body = self.root_body
240
+ root = find_elements(root=self.worldbody, tags="body", return_first=True)
241
+ for body in leg_base.worldbody:
242
+ root.append(body)
243
+ # import pdb; pdb.set_trace()
244
+
245
+ arm_root = find_elements(root=self.worldbody, tags="body", return_first=False)[1]
246
+
247
+ mount_support = find_elements(
248
+ root=leg_base.worldbody,
249
+ tags="body",
250
+ attribs={"name": leg_base.correct_naming("support")},
251
+ return_first=True,
252
+ )
253
+
254
+ free_joint = find_elements(root=leg_base.worldbody, tags="freejoint", return_first=True)
255
+ if free_joint is not None:
256
+ root.append(deepcopy(free_joint))
257
+ free_joint_parent = find_parent(leg_base.worldbody, free_joint)
258
+ free_joint_parent.remove(free_joint)
259
+ mount_support.append(deepcopy(arm_root))
260
+ root.remove(arm_root)
261
+ self.merge_assets(leg_base)
262
+ for one_actuator in leg_base.actuator:
263
+ self.actuator.append(one_actuator)
264
+ for one_sensor in leg_base.sensor:
265
+ self.sensor.append(one_sensor)
266
+ for one_tendon in leg_base.tendon:
267
+ self.tendon.append(one_tendon)
268
+ for one_equality in leg_base.equality:
269
+ self.equality.append(one_equality)
270
+ for one_contact in leg_base.contact:
271
+ self.contact.append(one_contact)
272
+
273
+ self.base = leg_base
274
+
275
+ # Update cameras in this model
276
+ self.cameras = self.get_element_names(self.worldbody, "camera")
277
+
278
+ # -------------------------------------------------------------------------------------- #
279
+ # Public Properties: In general, these are the name-adjusted versions from the private #
280
+ # attributes pulled from their respective raw xml files #
281
+ # -------------------------------------------------------------------------------------- #
282
+
283
+ @property
284
+ def naming_prefix(self) -> str:
285
+ return "robot{}_".format(self.idn)
286
+
287
+ @property
288
+ def dof(self) -> int:
289
+ """
290
+ Defines the number of DOF of the robot
291
+
292
+ Returns:
293
+ int: robot DOF
294
+ """
295
+ return len(self._joints)
296
+
297
+ @property
298
+ def bottom_offset(self) -> np.ndarray:
299
+ """
300
+ Returns vector from model root body to model bottom.
301
+ By default, this is equivalent to this robot's mount's (bottom_offset - top_offset) + this robot's base offset
302
+
303
+ Returns:
304
+ np.array: (dx, dy, dz) offset vector
305
+ """
306
+ return (
307
+ (self.base.bottom_offset - self.base.top_offset) + self._base_offset
308
+ if self.base is not None
309
+ else self._base_offset
310
+ )
311
+
312
+ @property
313
+ def horizontal_radius(self) -> float:
314
+ """
315
+ Returns maximum distance from model root body to any radial point of the model. This method takes into
316
+ account the mount horizontal radius as well
317
+
318
+ Returns:
319
+ float: radius
320
+ """
321
+ return max(self._horizontal_radius, self.base.horizontal_radius)
322
+
323
+ @property
324
+ def models(self) -> List[MujocoXMLModel]:
325
+ """
326
+ Returns a list of all m(sub-)models owned by this robot model. By default, this includes the mount model,
327
+ if specified
328
+
329
+ Returns:
330
+ list: models owned by this object
331
+ """
332
+ return [self.base] if self.base is not None else []
333
+
334
+ @property
335
+ def contact_geom_rgba(self):
336
+ return ROBOT_COLLISION_COLOR
337
+
338
+ # -------------------------------------------------------------------------------------- #
339
+ # All subclasses must implement the following properties #
340
+ # -------------------------------------------------------------------------------------- #
341
+
342
+ @property
343
+ def default_base(self) -> str:
344
+ """
345
+ Defines the default mount type for this robot that gets added to root body (base)
346
+
347
+ Returns:
348
+ str: Default base name to add to this robot
349
+ """
350
+ raise NotImplementedError
351
+
352
+ @property
353
+ def default_controller_config(self) -> Dict[str, str]:
354
+ """
355
+ Defines the name of default controller config file in the controllers/config directory for this robot.
356
+
357
+ Returns:
358
+ dict: Dictionary containing arm-specific default controller config names
359
+ e.g.: {"right": "default_panda", "left": "default_panda"}
360
+ """
361
+ raise NotImplementedError
362
+
363
+ @property
364
+ def init_qpos(self) -> np.ndarray:
365
+ """
366
+ Defines the default rest qpos of this robot
367
+
368
+ Returns:
369
+ np.array: Default init qpos of this robot
370
+ """
371
+ raise NotImplementedError
372
+
373
+ @property
374
+ def base_xpos_offset(self) -> Dict[str, np.ndarray]:
375
+ """
376
+ Defines the dict of various (x,y,z) tuple offsets relative to specific arenas placed at (0,0,0)
377
+ Assumes robot is facing forwards (in the +x direction) when determining offset. Should have entries for each
378
+ arena case; i.e.: "bins", "empty", and "table")
379
+
380
+ Returns:
381
+ dict: Dict mapping arena names to robot offsets from the global origin (dict entries may also be lambdas
382
+ for variable offsets)
383
+ """
384
+ raise NotImplementedError
385
+
386
+ @property
387
+ def top_offset(self) -> np.ndarray:
388
+ """
389
+ Returns vector from model root body to model top.
390
+ Useful for, e.g. placing models on a surface.
391
+ Must be defined by subclass.
392
+
393
+ Returns:
394
+ np.array: (dx, dy, dz) offset vector
395
+ """
396
+ raise NotImplementedError
397
+
398
+ @property
399
+ def _horizontal_radius(self) -> float:
400
+ """
401
+ Returns maximum distance from model root body to any radial point of the model.
402
+
403
+ Helps us put models programmatically without them flying away due to a huge initial contact force.
404
+ Must be defined by subclass.
405
+
406
+ Returns:
407
+ float: radius
408
+ """
409
+ raise NotImplementedError
410
+
411
+ @property
412
+ def _important_sites(self) -> Dict[str, str]:
413
+ """
414
+ Returns:
415
+ dict: (Default is no important sites; i.e.: empty dict)
416
+ """
417
+ return {}
418
+
419
+ @property
420
+ def _important_geoms(self) -> Dict[str, List[str]]:
421
+ """
422
+ Returns:
423
+ dict: (Default is no important geoms; i.e.: empty dict)
424
+ """
425
+ return {}
426
+
427
+ @property
428
+ def _important_sensors(self) -> Dict[str, str]:
429
+ """
430
+ Returns:
431
+ dict: (Default is no sensors; i.e.: empty dict)
432
+ """
433
+ return {}
434
+
435
+ @property
436
+ def all_joints(self) -> List:
437
+ """
438
+ Returns:
439
+ list: (Default is no joints; i.e.: empty list)
440
+ """
441
+ all_joints = []
442
+ all_joints += self.joints
443
+ if self.base is not None:
444
+ all_joints += self.base.joints
445
+ return all_joints
446
+
447
+ @property
448
+ def all_actuators(self) -> List:
449
+ """
450
+ Returns:
451
+ list: (Default is no actuators; i.e.: empty list)
452
+ """
453
+ all_actuators = []
454
+ all_actuators += self.actuators
455
+ if self.base is not None:
456
+ all_actuators += self.base.actuators
457
+ return all_actuators
third_party/robosuite/robosuite/models/tasks/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .task import Task
2
+ from .manipulation_task import ManipulationTask
third_party/robosuite/robosuite/models/tasks/manipulation_task.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from robosuite.models.tasks.task import Task
2
+
3
+
4
+ class ManipulationTask(Task):
5
+ """
6
+ A manipulation-specific task. This is currently a future-proofing placeholder.
7
+ """
third_party/robosuite/robosuite/models/tasks/task.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from copy import deepcopy
2
+
3
+ from robosuite.models.objects import MujocoObject
4
+ from robosuite.models.robots import RobotModel
5
+ from robosuite.models.world import MujocoWorldBase
6
+ from robosuite.utils.mjcf_utils import get_ids
7
+
8
+
9
+ class Task(MujocoWorldBase):
10
+ """
11
+ Creates MJCF model for a task performed.
12
+
13
+ A task consists of one or more robots interacting with a variable number of
14
+ objects. This class combines the robot(s), the arena, and the objects
15
+ into a single MJCF model.
16
+
17
+ Args:
18
+ mujoco_arena (Arena): MJCF model of robot workspace
19
+
20
+ mujoco_robots (RobotModel or list of RobotModel): MJCF model of robot model(s) (list)
21
+
22
+ mujoco_objects (None or MujocoObject or list of MujocoObject): a list of MJCF models of physical objects
23
+
24
+ Raises:
25
+ AssertionError: [Invalid input object type]
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ mujoco_arena,
31
+ mujoco_robots,
32
+ mujoco_objects=None,
33
+ ):
34
+ super().__init__()
35
+
36
+ # Store references to all models
37
+ self.mujoco_arena = mujoco_arena
38
+ self.mujoco_robots = [mujoco_robots] if isinstance(mujoco_robots, RobotModel) else mujoco_robots
39
+ if mujoco_objects is None:
40
+ self.mujoco_objects = []
41
+ else:
42
+ self.mujoco_objects = [mujoco_objects] if isinstance(mujoco_objects, MujocoObject) else mujoco_objects
43
+
44
+ # Merge all models
45
+ self.merge_arena(self.mujoco_arena)
46
+ for mujoco_robot in self.mujoco_robots:
47
+ self.merge_robot(mujoco_robot)
48
+ self.merge_objects(self.mujoco_objects)
49
+
50
+ self._instances_to_ids = None
51
+ self._geom_ids_to_instances = None
52
+ self._site_ids_to_instances = None
53
+ self._classes_to_ids = None
54
+ self._geom_ids_to_classes = None
55
+ self._site_ids_to_classes = None
56
+
57
+ def merge_robot(self, mujoco_robot):
58
+ """
59
+ Adds robot model to the MJCF model.
60
+
61
+ Args:
62
+ mujoco_robot (RobotModel): robot to merge into this MJCF model
63
+ """
64
+ self.merge(mujoco_robot)
65
+
66
+ def merge_arena(self, mujoco_arena):
67
+ """
68
+ Adds arena model to the MJCF model.
69
+
70
+ Args:
71
+ mujoco_arena (Arena): arena to merge into this MJCF model
72
+ """
73
+ self.merge(mujoco_arena)
74
+
75
+ def merge_objects(self, mujoco_objects):
76
+ """
77
+ Adds object models to the MJCF model.
78
+
79
+ Args:
80
+ mujoco_objects (list of MujocoObject): objects to merge into this MJCF model
81
+ """
82
+ for mujoco_obj in mujoco_objects:
83
+ # Make sure we actually got a MujocoObject
84
+ assert isinstance(mujoco_obj, MujocoObject), "Tried to merge non-MujocoObject! Got type: {}".format(
85
+ type(mujoco_obj)
86
+ )
87
+ # Merge this object
88
+ self.merge_assets(mujoco_obj)
89
+ self.worldbody.append(mujoco_obj.get_obj())
90
+
91
+ def generate_id_mappings(self, sim):
92
+ """
93
+ Generates IDs mapping class instances to set of (visual) geom IDs corresponding to that class instance
94
+
95
+ Args:
96
+ sim (MjSim): Current active mujoco simulation object
97
+ """
98
+ self._instances_to_ids = {}
99
+ self._geom_ids_to_instances = {}
100
+ self._site_ids_to_instances = {}
101
+ self._classes_to_ids = {}
102
+ self._geom_ids_to_classes = {}
103
+ self._site_ids_to_classes = {}
104
+
105
+ models = [model for model in self.mujoco_objects]
106
+ for robot in self.mujoco_robots:
107
+ models += [robot] + robot.models
108
+
109
+ # Parse all mujoco models from robots and objects
110
+ for model in models:
111
+ # Grab model class name and visual IDs
112
+ cls = str(type(model)).split("'")[1].split(".")[-1]
113
+ inst = model.name
114
+ id_groups = [
115
+ get_ids(sim=sim, elements=model.visual_geoms + model.contact_geoms, element_type="geom"),
116
+ get_ids(sim=sim, elements=model.sites, element_type="site"),
117
+ ]
118
+ group_types = ("geom", "site")
119
+ ids_to_instances = (self._geom_ids_to_instances, self._site_ids_to_instances)
120
+ ids_to_classes = (self._geom_ids_to_classes, self._site_ids_to_classes)
121
+
122
+ # Add entry to mapping dicts
123
+
124
+ # Instances should be unique
125
+ assert inst not in self._instances_to_ids, f"Instance {inst} already registered; should be unique"
126
+ self._instances_to_ids[inst] = {}
127
+
128
+ # Classes may not be unique
129
+ if cls not in self._classes_to_ids:
130
+ self._classes_to_ids[cls] = {group_type: [] for group_type in group_types}
131
+
132
+ for ids, group_type, ids_to_inst, ids_to_cls in zip(
133
+ id_groups, group_types, ids_to_instances, ids_to_classes
134
+ ):
135
+ # Add geom, site ids
136
+ self._instances_to_ids[inst][group_type] = ids
137
+ self._classes_to_ids[cls][group_type] += ids
138
+
139
+ # Add reverse mappings as well
140
+ for idn in ids:
141
+ assert idn not in ids_to_inst, f"ID {idn} already registered; should be unique"
142
+ ids_to_inst[idn] = inst
143
+ ids_to_cls[idn] = cls
144
+
145
+ @property
146
+ def geom_ids_to_instances(self):
147
+ """
148
+ Returns:
149
+ dict: Mapping from geom IDs in sim to specific class instance names
150
+ """
151
+ return deepcopy(self._geom_ids_to_instances)
152
+
153
+ @property
154
+ def site_ids_to_instances(self):
155
+ """
156
+ Returns:
157
+ dict: Mapping from site IDs in sim to specific class instance names
158
+ """
159
+ return deepcopy(self._site_ids_to_instances)
160
+
161
+ @property
162
+ def instances_to_ids(self):
163
+ """
164
+ Returns:
165
+ dict: Mapping from specific class instance names to {geom, site} IDs in sim
166
+ """
167
+ return deepcopy(self._instances_to_ids)
168
+
169
+ @property
170
+ def geom_ids_to_classes(self):
171
+ """
172
+ Returns:
173
+ dict: Mapping from geom IDs in sim to specific classes
174
+ """
175
+ return deepcopy(self._geom_ids_to_classes)
176
+
177
+ @property
178
+ def site_ids_to_classes(self):
179
+ """
180
+ Returns:
181
+ dict: Mapping from site IDs in sim to specific classes
182
+ """
183
+ return deepcopy(self._site_ids_to_classes)
184
+
185
+ @property
186
+ def classes_to_ids(self):
187
+ """
188
+ Returns:
189
+ dict: Mapping from specific classes to {geom, site} IDs in sim
190
+ """
191
+ return deepcopy(self._classes_to_ids)
third_party/robosuite/robosuite/models/world.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import robosuite.macros as macros
2
+ from robosuite.models.base import MujocoXML
3
+ from robosuite.utils.mjcf_utils import convert_to_string, find_elements, xml_path_completion
4
+
5
+
6
+ class MujocoWorldBase(MujocoXML):
7
+ """Base class to inherit all mujoco worlds from."""
8
+
9
+ def __init__(self):
10
+ super().__init__(xml_path_completion("base.xml"))
11
+ # Modify the simulation timestep to be the requested value
12
+ options = find_elements(root=self.root, tags="option", attribs=None, return_first=True)
13
+ options.set("timestep", convert_to_string(macros.SIMULATION_TIMESTEP))
third_party/robosuite/robosuite/renderers/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .base import load_renderer_config
third_party/robosuite/robosuite/renderers/base.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file contains the base renderer class for Mujoco environments.
3
+ """
4
+
5
+ import abc
6
+ import json
7
+ import os
8
+
9
+
10
+ def load_renderer_config(renderer):
11
+ """Loads the config of the specified renderer.
12
+ Modify the dictionary returned by this function
13
+ according to reuirements.
14
+
15
+ Args:
16
+ renderer (str): Name of the renderer to use.
17
+
18
+ Returns:
19
+ dict: renderer default config.
20
+ """
21
+ return {}
22
+
23
+
24
+ class Renderer:
25
+ """
26
+ Base class for all robosuite renderers
27
+ Defines basic interface for all renderers to adhere to
28
+ """
29
+
30
+ def __init__(self, env, renderer_type="mujoco"):
31
+ self.env = env
32
+ self.renderer_type = renderer_type
33
+
34
+ def __str__(self):
35
+ """Prints the renderer type in a formatted way
36
+
37
+ Returns:
38
+ str: string representing the renderer
39
+ """
40
+ return f'<RendererObject renderer_type="{self.renderer_type}">'
41
+
42
+ @abc.abstractmethod
43
+ def render(self, **kwargs):
44
+ """Renders the current state with the specified renderer"""
45
+ raise NotImplementedError
46
+
47
+ @abc.abstractmethod
48
+ def close(self):
49
+ """Closes the renderer objects"""
50
+ raise NotImplementedError
51
+
52
+ @abc.abstractmethod
53
+ def reset(self):
54
+ """Reset the renderer with initial states for environment"""
55
+ raise NotImplementedError
56
+
57
+ @abc.abstractmethod
58
+ def get_pixel_obs(self):
59
+ """Get the pixel observations from the given renderer
60
+
61
+ Returns:
62
+ numpyarr: numpy array representing pixels of renderer
63
+ """
64
+ raise NotImplementedError
third_party/robosuite/robosuite/renderers/base_parser.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import xml.etree.ElementTree as ET
3
+
4
+
5
+ class BaseParser(object):
6
+ """
7
+ Base class for Parser objects used by renderers.
8
+ """
9
+
10
+ def __init__(self, renderer, env):
11
+ """
12
+ Parse the mujoco xml and initialize iG renderer objects.
13
+
14
+ Args:
15
+ renderer: the renderer
16
+ env : Mujoco env
17
+ """
18
+
19
+ self.renderer = renderer
20
+ self.env = env
21
+ self.xml_root = ET.fromstring(self.env.sim.model.get_xml())
22
+ self.parent_map = {c: p for p in self.xml_root.iter() for c in p}
23
+ self.visual_objects = {}
24
+
25
+ @abc.abstractmethod
26
+ def parse_textures(self):
27
+ """
28
+ Parse and load all textures and store them
29
+ """
30
+ raise NotImplementedError
31
+
32
+ @abc.abstractmethod
33
+ def parse_materials(self):
34
+ """
35
+ Parse all materials and use texture mapping to initialize materials
36
+ """
37
+ raise NotImplementedError
38
+
39
+ def parse_cameras(self):
40
+ """
41
+ Parse cameras and initialize the cameras.
42
+ """
43
+ raise NotImplementedError
44
+
45
+ def parse_meshes(self):
46
+ """
47
+ Create mapping of meshes.
48
+ """
49
+ raise NotImplementedError
50
+
51
+ def parse_geometries(self):
52
+ """
53
+ Iterate through each geometry and load it in the renderer.
54
+ """
55
+ raise NotImplementedError
third_party/robosuite/robosuite/renderers/context/__init__.py ADDED
File without changes
third_party/robosuite/robosuite/renderers/context/egl_context.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Modifications Copyright 2025 The robosuite Authors
2
+ # Original Copyright 2018 The dm_control Authors
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ # ==============================================================================
16
+
17
+ import atexit
18
+ import ctypes
19
+ import os
20
+
21
+ PYOPENGL_PLATFORM = os.environ.get("PYOPENGL_PLATFORM")
22
+
23
+ if not PYOPENGL_PLATFORM:
24
+ os.environ["PYOPENGL_PLATFORM"] = "egl"
25
+ elif PYOPENGL_PLATFORM.lower() != "egl":
26
+ raise ImportError(
27
+ "Cannot use EGL rendering platform. "
28
+ "The PYOPENGL_PLATFORM environment variable is set to {!r} "
29
+ "(should be either unset or 'egl')."
30
+ )
31
+
32
+ from mujoco.egl import egl_ext as EGL
33
+ from OpenGL import error
34
+
35
+
36
+ def create_initialized_egl_device_display(device_id=0):
37
+ """Creates an initialized EGL display directly on a device."""
38
+ all_devices = EGL.eglQueryDevicesEXT()
39
+ selected_device = (
40
+ os.environ.get("CUDA_VISIBLE_DEVICES", None)
41
+ if os.environ.get("MUJOCO_EGL_DEVICE_ID", None) is None
42
+ else os.environ.get("MUJOCO_EGL_DEVICE_ID", None)
43
+ )
44
+ if selected_device is None:
45
+ candidates = all_devices
46
+ if device_id == -1:
47
+ device_idx = 0
48
+ else:
49
+ device_idx = device_id
50
+ else:
51
+ if not selected_device.isdigit():
52
+ device_inds = [int(x) for x in selected_device.split(",")]
53
+ if device_id == -1:
54
+ device_idx = device_inds[0]
55
+ else:
56
+ assert device_id in device_inds, "specified device id is not made visible in environment variables."
57
+ device_idx = device_id
58
+ else:
59
+ device_idx = int(selected_device)
60
+ if not 0 <= device_idx < len(all_devices):
61
+ raise RuntimeError(
62
+ f"The MUJOCO_EGL_DEVICE_ID environment variable must be an integer "
63
+ f"between 0 and {len(all_devices)-1} (inclusive), got {device_idx}."
64
+ )
65
+ candidates = all_devices[device_idx : device_idx + 1]
66
+ for device in candidates:
67
+ display = EGL.eglGetPlatformDisplayEXT(EGL.EGL_PLATFORM_DEVICE_EXT, device, None)
68
+ if display != EGL.EGL_NO_DISPLAY and EGL.eglGetError() == EGL.EGL_SUCCESS:
69
+ # `eglInitialize` may or may not raise an exception on failure depending
70
+ # on how PyOpenGL is configured. We therefore catch a `GLError` and also
71
+ # manually check the output of `eglGetError()` here.
72
+ try:
73
+ initialized = EGL.eglInitialize(display, None, None)
74
+ except error.GLError:
75
+ pass
76
+ else:
77
+ if initialized == EGL.EGL_TRUE and EGL.eglGetError() == EGL.EGL_SUCCESS:
78
+ return display
79
+ return EGL.EGL_NO_DISPLAY
80
+
81
+
82
+ global EGL_DISPLAY
83
+ EGL_DISPLAY = None
84
+
85
+ EGL_ATTRIBUTES = (
86
+ EGL.EGL_RED_SIZE,
87
+ 8,
88
+ EGL.EGL_GREEN_SIZE,
89
+ 8,
90
+ EGL.EGL_BLUE_SIZE,
91
+ 8,
92
+ EGL.EGL_ALPHA_SIZE,
93
+ 8,
94
+ EGL.EGL_DEPTH_SIZE,
95
+ 24,
96
+ EGL.EGL_STENCIL_SIZE,
97
+ 8,
98
+ EGL.EGL_COLOR_BUFFER_TYPE,
99
+ EGL.EGL_RGB_BUFFER,
100
+ EGL.EGL_SURFACE_TYPE,
101
+ EGL.EGL_PBUFFER_BIT,
102
+ EGL.EGL_RENDERABLE_TYPE,
103
+ EGL.EGL_OPENGL_BIT,
104
+ EGL.EGL_NONE,
105
+ )
106
+
107
+
108
+ class EGLGLContext:
109
+ """An EGL context for headless accelerated OpenGL rendering on GPU devices."""
110
+
111
+ def __init__(self, max_width, max_height, device_id=0):
112
+
113
+ del max_width, max_height # unused
114
+ num_configs = ctypes.c_long()
115
+ config_size = 1
116
+ config_ptr = EGL.EGLConfig() # Makes an opaque pointer
117
+ EGL.eglReleaseThread()
118
+ global EGL_DISPLAY
119
+ if EGL_DISPLAY is None:
120
+ # only initialize for the first time
121
+ EGL_DISPLAY = create_initialized_egl_device_display(device_id=device_id)
122
+ if EGL_DISPLAY == EGL.EGL_NO_DISPLAY:
123
+ raise ImportError(
124
+ "Cannot initialize a EGL device display. This likely means that your EGL "
125
+ "driver does not support the PLATFORM_DEVICE extension, which is "
126
+ "required for creating a headless rendering context."
127
+ )
128
+ atexit.register(EGL.eglTerminate, EGL_DISPLAY)
129
+ EGL.eglChooseConfig(EGL_DISPLAY, EGL_ATTRIBUTES, config_ptr, config_size, num_configs)
130
+ if num_configs.value < 1:
131
+ raise RuntimeError(
132
+ "EGL failed to find a framebuffer configuration that matches the "
133
+ "desired attributes: {}".format(EGL_ATTRIBUTES)
134
+ )
135
+ EGL.eglBindAPI(EGL.EGL_OPENGL_API)
136
+ self._context = EGL.eglCreateContext(EGL_DISPLAY, config_ptr, EGL.EGL_NO_CONTEXT, None)
137
+ if not self._context:
138
+ raise RuntimeError("Cannot create an EGL context.")
139
+
140
+ def make_current(self):
141
+ if not EGL.eglMakeCurrent(EGL_DISPLAY, EGL.EGL_NO_SURFACE, EGL.EGL_NO_SURFACE, self._context):
142
+ raise RuntimeError("Failed to make the EGL context current.")
143
+
144
+ def free(self):
145
+ """Frees resources associated with this context."""
146
+ if self._context:
147
+ current_context = EGL.eglGetCurrentContext()
148
+ if current_context and self._context.address == current_context.address:
149
+ EGL.eglMakeCurrent(EGL_DISPLAY, EGL.EGL_NO_SURFACE, EGL.EGL_NO_SURFACE, EGL.EGL_NO_CONTEXT)
150
+ EGL.eglDestroyContext(EGL_DISPLAY, self._context)
151
+ EGL.eglReleaseThread()
152
+ self._context = None
153
+
154
+ def __del__(self):
155
+ try:
156
+ self.free()
157
+ except Exception:
158
+ # avoid getting OpenGL.error.GLError
159
+ pass
third_party/robosuite/robosuite/renderers/context/glfw_context.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The dm_control Authors
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """An OpenGL context created via GLFW."""
16
+
17
+ from mujoco.glfw import GLContext
18
+
19
+
20
+ class GLFWGLContext(GLContext):
21
+ """An OpenGL context created via GLFW."""
22
+
23
+ def __init__(self, max_width, max_height, device_id=0):
24
+ super().__init__(max_width, max_height)
third_party/robosuite/robosuite/renderers/context/osmesa_context.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The dm_control Authors
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ==============================================================================
15
+ """An OSMesa context for software-based OpenGL rendering."""
16
+
17
+ import os
18
+
19
+ from mujoco.osmesa import GLContext
20
+
21
+
22
+ class OSMesaGLContext(GLContext):
23
+ """An OSMesa context for software-based OpenGL rendering."""
24
+
25
+ def __init__(self, max_width, max_height, device_id=-1):
26
+ super().__init__(max_width, max_height)
third_party/robosuite/robosuite/renderers/mjviewer/__init__.py ADDED
File without changes
third_party/robosuite/robosuite/renderers/mjviewer/mjviewer_renderer.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from mujoco import viewer
2
+
3
+ DEFAULT_FREE_CAM = {
4
+ "lookat": [0, 0, 1],
5
+ "distance": 2,
6
+ "azimuth": 180,
7
+ "elevation": -20,
8
+ }
9
+
10
+
11
+ class MjviewerRenderer:
12
+ def __init__(self, env, camera_id=None, cam_config=None):
13
+ if cam_config is None:
14
+ cam_config = DEFAULT_FREE_CAM
15
+ self.env = env
16
+ self.camera_id = camera_id
17
+ self.viewer = None
18
+ self.camera_config = cam_config
19
+
20
+ def render(self):
21
+ pass
22
+
23
+ def set_camera(self, camera_id):
24
+ self.camera_id = camera_id
25
+
26
+ def update(self):
27
+ if self.viewer is None:
28
+ self.viewer = viewer.launch_passive(
29
+ self.env.sim.model._model,
30
+ self.env.sim.data._data,
31
+ show_left_ui=False,
32
+ show_right_ui=False,
33
+ )
34
+
35
+ self.viewer.opt.geomgroup[0] = 0
36
+
37
+ if self.camera_config is not None:
38
+ self.viewer.cam.lookat = self.camera_config["lookat"]
39
+ self.viewer.cam.distance = self.camera_config["distance"]
40
+ self.viewer.cam.azimuth = self.camera_config["azimuth"]
41
+ self.viewer.cam.elevation = self.camera_config["elevation"]
42
+
43
+ if self.camera_id is not None:
44
+ if self.camera_id >= 0:
45
+ self.viewer.cam.type = 2
46
+ self.viewer.cam.fixedcamid = self.camera_id
47
+ else:
48
+ self.viewer.cam.type = 0
49
+
50
+ self.viewer.sync()
51
+
52
+ def reset(self):
53
+ pass
54
+
55
+ def close(self):
56
+
57
+ self.sim = None
58
+ if self.viewer is not None:
59
+ self.viewer.close()
60
+ self.viewer = None
61
+
62
+ def add_keypress_callback(self, keypress_callback):
63
+ self.keypress_callback = keypress_callback
third_party/robosuite/robosuite/robots/__init__.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .fixed_base_robot import FixedBaseRobot
2
+ from .mobile_robot import MobileRobot
3
+ from .wheeled_robot import WheeledRobot
4
+ from .legged_robot import LeggedRobot
5
+
6
+ from robosuite.models.robots.robot_model import REGISTERED_ROBOTS
7
+
8
+ from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER
9
+
10
+ ALL_ROBOTS = REGISTERED_ROBOTS.keys()
11
+
12
+ # Robot class mappings -- must be maintained manually
13
+ # These are the main robot used. Remaining robots are located in
14
+ # https://github.com/ARISE-Initiative/robosuite_models
15
+ ROBOT_CLASS_MAPPING = {
16
+ "Baxter": FixedBaseRobot,
17
+ "IIWA": FixedBaseRobot,
18
+ "Jaco": FixedBaseRobot,
19
+ "Kinova3": FixedBaseRobot,
20
+ "Panda": FixedBaseRobot,
21
+ "Sawyer": FixedBaseRobot,
22
+ "UR5e": FixedBaseRobot,
23
+ "SpotWithArm": LeggedRobot,
24
+ "SpotWithArmFloating": LeggedRobot,
25
+ "PandaOmron": WheeledRobot,
26
+ "Tiago": WheeledRobot,
27
+ "GR1": LeggedRobot,
28
+ "GR1FixedLowerBody": LeggedRobot,
29
+ "GR1ArmsOnly": LeggedRobot,
30
+ "GR1FloatingBody": LeggedRobot,
31
+ "PandaDexRH": FixedBaseRobot,
32
+ "PandaDexLH": FixedBaseRobot,
33
+ }
34
+
35
+ target_type_mapping = {
36
+ "FixedBaseRobot": FixedBaseRobot,
37
+ "MobileRobot": MobileRobot,
38
+ "WheeledRobot": WheeledRobot,
39
+ "LeggedRobot": LeggedRobot,
40
+ }
41
+
42
+
43
+ def register_robot_class(target_type, **kwargs):
44
+ def decorator(target_class):
45
+ # Store the class in the registry with additional arguments
46
+ ROBOT_CLASS_MAPPING.update({target_class.__name__: target_type_mapping[target_type]})
47
+
48
+ return target_class # Return the class itself
49
+
50
+ return decorator
third_party/robosuite/robosuite/robots/fixed_base_robot.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import os
3
+ from collections import OrderedDict
4
+
5
+ import numpy as np
6
+
7
+ import robosuite.utils.transform_utils as T
8
+ from robosuite.controllers import composite_controller_factory
9
+ from robosuite.robots.robot import Robot
10
+
11
+
12
+ class FixedBaseRobot(Robot):
13
+ """
14
+ Initializes a robot with a fixed base.
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ robot_type: str,
20
+ idn=0,
21
+ composite_controller_config=None,
22
+ initial_qpos=None,
23
+ initialization_noise=None,
24
+ base_type="default",
25
+ gripper_type="default",
26
+ control_freq=20,
27
+ lite_physics=True,
28
+ ):
29
+ super().__init__(
30
+ robot_type=robot_type,
31
+ idn=idn,
32
+ composite_controller_config=composite_controller_config,
33
+ initial_qpos=initial_qpos,
34
+ initialization_noise=initialization_noise,
35
+ base_type=base_type,
36
+ gripper_type=gripper_type,
37
+ control_freq=control_freq,
38
+ lite_physics=lite_physics,
39
+ )
40
+
41
+ def _load_controller(self):
42
+ """
43
+ Loads controller to be used for dynamic trajectories
44
+ """
45
+ # Flag for loading urdf once (only applicable for IK controllers)
46
+ self.composite_controller = composite_controller_factory(
47
+ type=self.composite_controller_config.get("type", "BASIC"),
48
+ sim=self.sim,
49
+ robot_model=self.robot_model,
50
+ grippers={self.get_gripper_name(arm): self.gripper[arm] for arm in self.arms},
51
+ )
52
+ self._load_arm_controllers()
53
+
54
+ self._postprocess_part_controller_config()
55
+ self.composite_controller.load_controller_config(
56
+ self.part_controller_config,
57
+ self.composite_controller_config.get("composite_controller_specific_configs", {}),
58
+ )
59
+
60
+ self.enable_parts()
61
+
62
+ def load_model(self):
63
+ """
64
+ Loads robot and optionally add grippers.
65
+ """
66
+ # First, run the superclass method to load the relevant model
67
+ super().load_model()
68
+
69
+ def reset(self, deterministic=False):
70
+ """
71
+ Sets initial pose of arm and grippers. Overrides gripper joint configuration if we're using a
72
+ deterministic reset (e.g.: hard reset from xml file)
73
+
74
+ Args:
75
+ deterministic (bool): If true, will not randomize initializations within the sim
76
+ """
77
+ # First, run the superclass method to reset the position and controller
78
+ super().reset(deterministic)
79
+
80
+ def setup_references(self):
81
+ """
82
+ Sets up necessary reference for robots, grippers, and objects.
83
+
84
+ Note that this should get called during every reset from the environment
85
+ """
86
+ # First, run the superclass method to setup references for joint-related values / indexes
87
+ super().setup_references()
88
+
89
+ # Now, add references to gripper if necessary
90
+ # indices for grippers in qpos, qvel
91
+ for arm in self.arms:
92
+ (start, end) = (None, self._joint_split_idx) if arm == "right" else (self._joint_split_idx, None)
93
+ self._ref_joints_indexes_dict[arm] = [
94
+ self.sim.model.joint_name2id(joint) for joint in self.robot_model.arm_joints[start:end]
95
+ ]
96
+ self._ref_actuators_indexes_dict[arm] = [
97
+ self.sim.model.actuator_name2id(joint) for joint in self.robot_model.arm_actuators[start:end]
98
+ ]
99
+ if self.has_gripper[arm]:
100
+ self.gripper_joints[arm] = list(self.gripper[arm].joints)
101
+ self._ref_gripper_joint_pos_indexes[arm] = [
102
+ self.sim.model.get_joint_qpos_addr(x) for x in self.gripper_joints[arm]
103
+ ]
104
+ self._ref_gripper_joint_vel_indexes[arm] = [
105
+ self.sim.model.get_joint_qvel_addr(x) for x in self.gripper_joints[arm]
106
+ ]
107
+ self._ref_joint_gripper_actuator_indexes[arm] = [
108
+ self.sim.model.actuator_name2id(actuator) for actuator in self.gripper[arm].actuators
109
+ ]
110
+ self._ref_joints_indexes_dict[self.get_gripper_name(arm)] = [
111
+ self.sim.model.joint_name2id(joint) for joint in self.gripper_joints[arm]
112
+ ]
113
+ self._ref_actuators_indexes_dict[self.get_gripper_name(arm)] = self._ref_joint_gripper_actuator_indexes[
114
+ arm
115
+ ]
116
+
117
+ # IDs of sites for eef visualization
118
+ self.eef_site_id[arm] = self.sim.model.site_name2id(self.gripper[arm].important_sites["grip_site"])
119
+ self.eef_cylinder_id[arm] = self.sim.model.site_name2id(self.gripper[arm].important_sites["grip_cylinder"])
120
+
121
+ def control(self, action, policy_step=False):
122
+ """
123
+ Actuate the robot with the
124
+ passed joint velocities and gripper control.
125
+
126
+ Args:
127
+ action (np.array): The control to apply to the robot. The first @self.robot_model.dof dimensions should
128
+ be the desired normalized joint velocities and if the robot has a gripper, the next @self.gripper.dof
129
+ dimensions should be actuation controls for the gripper.
130
+
131
+ :NOTE: Assumes inputted actions are of form:
132
+ [right_arm_control, right_gripper_control, left_arm_control, left_gripper_control]
133
+
134
+ policy_step (bool): Whether a new policy step (action) is being taken
135
+
136
+ Raises:
137
+ AssertionError: [Invalid action dimension]
138
+ """
139
+ # clip actions into valid range
140
+ assert len(action) == self.action_dim, "environment got invalid action dimension -- expected {}, got {}".format(
141
+ self.action_dim, len(action)
142
+ )
143
+
144
+ self.composite_controller.update_state()
145
+ if policy_step:
146
+ self.composite_controller.set_goal(action)
147
+
148
+ applied_action_dict = self.composite_controller.run_controller(self._enabled_parts)
149
+ for part_name, applied_action in applied_action_dict.items():
150
+ applied_action_low = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[part_name], 0]
151
+ applied_action_high = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[part_name], 1]
152
+ applied_action = np.clip(applied_action, applied_action_low, applied_action_high)
153
+ self.sim.data.ctrl[self._ref_actuators_indexes_dict[part_name]] = applied_action
154
+
155
+ if policy_step:
156
+ # Update proprioceptive values
157
+ self.recent_qpos.push(self._joint_positions)
158
+ self.recent_actions.push(action)
159
+ self.recent_torques.push(self.torques)
160
+
161
+ for arm in self.arms:
162
+ controller = self.part_controllers[arm]
163
+ # Update arm-specific proprioceptive values
164
+ self.recent_ee_forcetorques[arm].push(np.concatenate((self.ee_force[arm], self.ee_torque[arm])))
165
+ self.recent_ee_pose[arm].push(np.concatenate((controller.ref_pos, T.mat2quat(controller.ref_ori_mat))))
166
+ self.recent_ee_vel[arm].push(np.concatenate((controller.ref_pos_vel, controller.ref_ori_vel)))
167
+
168
+ # Estimation of eef acceleration (averaged derivative of recent velocities)
169
+ self.recent_ee_vel_buffer[arm].push(np.concatenate((controller.ref_pos_vel, controller.ref_ori_vel)))
170
+ diffs = np.vstack(
171
+ [
172
+ self.recent_ee_acc[arm].current,
173
+ self.control_freq * np.diff(self.recent_ee_vel_buffer[arm].buf, axis=0),
174
+ ]
175
+ )
176
+ ee_acc = np.array([np.convolve(col, np.ones(10) / 10.0, mode="valid")[0] for col in diffs.transpose()])
177
+ self.recent_ee_acc[arm].push(ee_acc)
178
+
179
+ def setup_observables(self):
180
+ """
181
+ Sets up observables to be used for this robot
182
+
183
+ Returns:
184
+ OrderedDict: Dictionary mapping observable names to its corresponding Observable object
185
+ """
186
+ # Get general robot observables first
187
+ observables = super().setup_observables()
188
+
189
+ return observables
190
+
191
+ @property
192
+ def action_limits(self):
193
+ """
194
+ Action lower/upper limits per dimension.
195
+
196
+ Returns:
197
+ 2-tuple:
198
+
199
+ - (np.array) minimum (low) action values
200
+ - (np.array) maximum (high) action values
201
+ """
202
+ return self.composite_controller.action_limits
203
+
204
+ @property
205
+ def is_mobile(self):
206
+ return False
207
+
208
+ @property
209
+ def _action_split_indexes(self):
210
+ """
211
+ Dictionary of split indexes for each part of the robot
212
+
213
+ Returns:
214
+ dict: Dictionary of split indexes for each part of the robot
215
+ """
216
+ return self.composite_controller._action_split_indexes
third_party/robosuite/robosuite/robots/legged_robot.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import os
3
+ import time
4
+ from collections import OrderedDict
5
+ from typing import Dict, List
6
+
7
+ import numpy as np
8
+
9
+ import robosuite.utils.transform_utils as T
10
+ from robosuite.controllers import composite_controller_factory, load_part_controller_config
11
+ from robosuite.models.bases.leg_base_model import LegBaseModel
12
+ from robosuite.robots.mobile_robot import MobileRobot
13
+ from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER
14
+ from robosuite.utils.observables import sensor
15
+
16
+
17
+ class LeggedRobot(MobileRobot):
18
+ """
19
+ Initializes a robot with a wheeled base.
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ robot_type: str,
25
+ idn=0,
26
+ composite_controller_config=None,
27
+ initial_qpos=None,
28
+ initialization_noise=None,
29
+ base_type="default",
30
+ gripper_type="default",
31
+ control_freq=20,
32
+ lite_physics=True,
33
+ ):
34
+ super().__init__(
35
+ robot_type=robot_type,
36
+ idn=idn,
37
+ composite_controller_config=composite_controller_config,
38
+ initial_qpos=initial_qpos,
39
+ initialization_noise=initialization_noise,
40
+ base_type=base_type,
41
+ gripper_type=gripper_type,
42
+ control_freq=control_freq,
43
+ lite_physics=lite_physics,
44
+ )
45
+
46
+ def _load_leg_controllers(self):
47
+ if len(self._ref_actuators_indexes_dict[self.legs]) == 0:
48
+ return None
49
+
50
+ assert self.legs is not None, (
51
+ "Legs must be defined for legged robots in part_controller_config. "
52
+ "Please specify legs in controller configs."
53
+ )
54
+ assert (
55
+ type(self.part_controller_config[self.legs]) == dict
56
+ ), "Inputted controller config must be a dict! Instead, got type: {}".format(
57
+ type(self.part_controller_config[self.legs])
58
+ )
59
+ self.part_controller_config[self.legs] = {}
60
+ self.part_controller_config[self.legs]["ramp_ratio"] = 1.0
61
+ self.part_controller_config[self.legs]["robot_name"] = self.name
62
+
63
+ self.part_controller_config[self.legs]["sim"] = self.sim
64
+ self.part_controller_config[self.legs]["part_name"] = self.legs
65
+ self.part_controller_config[self.legs]["naming_prefix"] = self.robot_model.base.naming_prefix
66
+ self.part_controller_config[self.legs]["ndim"] = self.num_leg_joints
67
+ self.part_controller_config[self.legs]["policy_freq"] = self.control_freq
68
+
69
+ ref_legs_joint_indexes = [self.sim.model.joint_name2id(x) for x in self.robot_model.legs_joints]
70
+ ref_legs_joint_pos_indexes = [self.sim.model.get_joint_qpos_addr(x) for x in self.robot_model.legs_joints]
71
+ ref_legs_joint_vel_indexes = [self.sim.model.get_joint_qvel_addr(x) for x in self.robot_model.legs_joints]
72
+ self.part_controller_config[self.legs]["joint_indexes"] = {
73
+ "joints": ref_legs_joint_indexes,
74
+ "qpos": ref_legs_joint_pos_indexes,
75
+ "qvel": ref_legs_joint_vel_indexes,
76
+ }
77
+
78
+ low = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.legs], 0]
79
+ high = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.legs], 1]
80
+
81
+ self.part_controller_config[self.legs]["actuator_range"] = (low, high)
82
+
83
+ def _load_controller(self):
84
+ """
85
+ Loads controller to be used for dynamic trajectories
86
+ """
87
+ # Flag for loading urdf once (only applicable for IK controllers)
88
+ self.composite_controller = composite_controller_factory(
89
+ type=self.composite_controller_config.get("type", "BASIC"),
90
+ sim=self.sim,
91
+ robot_model=self.robot_model,
92
+ grippers={self.get_gripper_name(arm): self.gripper[arm] for arm in self.arms},
93
+ )
94
+
95
+ self._load_arm_controllers()
96
+
97
+ # default base, torso, and head controllers are inherited from MobileRobot
98
+ self._load_base_controller()
99
+
100
+ if self.is_legs_actuated:
101
+ self._load_leg_controllers()
102
+
103
+ self._load_head_controller()
104
+ self._load_torso_controller()
105
+ self._postprocess_part_controller_config()
106
+
107
+ self.composite_controller.load_controller_config(
108
+ self.part_controller_config,
109
+ self.composite_controller_config.get("composite_controller_specific_configs", {}),
110
+ )
111
+ self.enable_parts()
112
+
113
+ def load_model(self):
114
+ """
115
+ Loads robot and optionally add grippers.
116
+ """
117
+ # First, run the superclass method to load the relevant model
118
+ super().load_model()
119
+
120
+ def reset(self, deterministic=False):
121
+ """
122
+ Sets initial pose of arm and grippers. Overrides gripper joint configuration if we're using a
123
+ deterministic reset (e.g.: hard reset from xml file)
124
+
125
+ Args:
126
+ deterministic (bool): If true, will not randomize initializations within the sim
127
+ """
128
+ # First, run the superclass method to reset the position and controller
129
+ super().reset(deterministic)
130
+
131
+ # Set initial q pos of the legged base
132
+ if isinstance(self.robot_model.base, LegBaseModel):
133
+ # Set the initial joint positions of the legged base
134
+ self.sim.data.qpos[self._ref_legs_joint_pos_indexes] = self.robot_model.base.init_qpos
135
+
136
+ def setup_references(self):
137
+ """
138
+ Sets up necessary reference for robots, grippers, and objects.
139
+
140
+ Note that this should get called during every reset from the environment
141
+ """
142
+ # First, run the superclass method to setup references for joint-related values / indexes
143
+ super().setup_references()
144
+
145
+ # Now, add references to gripper if necessary
146
+ # indices for grippers in qpos, qvel
147
+ self._ref_actuators_indexes_dict[self.legs] = [
148
+ self.sim.model.actuator_name2id(actuator) for actuator in self.robot_model.legs_actuators
149
+ ]
150
+
151
+ self._ref_joints_indexes_dict[self.legs] = [
152
+ self.sim.model.joint_name2id(joint) for joint in self.robot_model.legs_joints
153
+ ]
154
+
155
+ self._ref_legs_joint_pos_indexes = [self.sim.model.get_joint_qpos_addr(x) for x in self.robot_model.legs_joints]
156
+ self._ref_legs_joint_vel_indexes = [self.sim.model.get_joint_qvel_addr(x) for x in self.robot_model.legs_joints]
157
+
158
+ def control(self, action, policy_step=False):
159
+ """
160
+ Actuate the robot with the
161
+ passed joint velocities and gripper control.
162
+
163
+ Args:
164
+ action (np.array): The control to apply to the robot. The first @self.robot_model.dof dimensions should
165
+ be the desired normalized joint velocities and if the robot has a gripper, the next @self.gripper.dof
166
+ dimensions should be actuation controls for the gripper.
167
+
168
+ :NOTE: Assumes inputted actions are of form:
169
+ [right_arm_control, right_gripper_control, left_arm_control, left_gripper_control]
170
+
171
+ policy_step (bool): Whether a new policy step (action) is being taken
172
+
173
+ Raises:
174
+ AssertionError: [Invalid action dimension]
175
+ """
176
+ # clip actions into valid range
177
+ assert len(action) == self.action_dim, "environment got invalid action dimension -- expected {}, got {}".format(
178
+ self.action_dim, len(action)
179
+ )
180
+
181
+ self.composite_controller.update_state()
182
+ if policy_step:
183
+ self.composite_controller.set_goal(action)
184
+
185
+ applied_action_dict = self.composite_controller.run_controller(self._enabled_parts)
186
+ for part_name, applied_action in applied_action_dict.items():
187
+ applied_action_low = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[part_name], 0]
188
+ applied_action_high = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[part_name], 1]
189
+ actuator_indexes = self._ref_actuators_indexes_dict[part_name]
190
+ actuator_gears = self.sim.model.actuator_gear[actuator_indexes, 0]
191
+ applied_action = np.clip(applied_action / actuator_gears, applied_action_low, applied_action_high)
192
+ self.sim.data.ctrl[actuator_indexes] = applied_action
193
+
194
+ # If this is a policy step, also update buffers holding recent values of interest
195
+ if policy_step:
196
+ # Update proprioceptive values
197
+ self.recent_qpos.push(self._joint_positions)
198
+ self.recent_actions.push(action)
199
+ self.recent_torques.push(self.torques)
200
+
201
+ for arm in self.arms:
202
+ controller = self.part_controllers.get(arm, None)
203
+ if controller is None:
204
+ # TODO: enable buffer update for whole body controllers not using individual arm controllers
205
+ continue
206
+ # Update arm-specific proprioceptive values
207
+ self.recent_ee_forcetorques[arm].push(np.concatenate((self.ee_force[arm], self.ee_torque[arm])))
208
+ self.recent_ee_pose[arm].push(np.concatenate((controller.ref_pos, T.mat2quat(controller.ref_ori_mat))))
209
+ self.recent_ee_vel[arm].push(np.concatenate((controller.ref_pos_vel, controller.ref_ori_vel)))
210
+
211
+ # Estimation of eef acceleration (averaged derivative of recent velocities)
212
+ self.recent_ee_vel_buffer[arm].push(np.concatenate((controller.ref_pos_vel, controller.ref_ori_vel)))
213
+ diffs = np.vstack(
214
+ [
215
+ self.recent_ee_acc[arm].current,
216
+ self.control_freq * np.diff(self.recent_ee_vel_buffer[arm].buf, axis=0),
217
+ ]
218
+ )
219
+ ee_acc = np.array([np.convolve(col, np.ones(10) / 10.0, mode="valid")[0] for col in diffs.transpose()])
220
+ self.recent_ee_acc[arm].push(ee_acc)
221
+
222
+ def setup_observables(self):
223
+ """
224
+ Sets up observables to be used for this robot
225
+
226
+ Returns:
227
+ OrderedDict: Dictionary mapping observable names to its corresponding Observable object
228
+ """
229
+ # Get general robot observables first
230
+ observables = super().setup_observables()
231
+
232
+ return observables
233
+
234
+ @property
235
+ def action_limits(self):
236
+ """
237
+ Action lower/upper limits per dimension.
238
+
239
+ Returns:
240
+ 2-tuple:
241
+
242
+ - (np.array) minimum (low) action values
243
+ - (np.array) maximum (high) action values
244
+ """
245
+ return self.composite_controller.action_limits
246
+
247
+ @property
248
+ def is_legs_actuated(self):
249
+ return len(self.robot_model.legs_actuators) > 0
250
+
251
+ @property
252
+ def num_leg_joints(self):
253
+ return len(self.robot_model.legs_joints)
third_party/robosuite/robosuite/robots/mobile_robot.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import os
3
+ from collections import OrderedDict
4
+
5
+ import numpy as np
6
+
7
+ import robosuite.utils.transform_utils as T
8
+ from robosuite.controllers import load_part_controller_config
9
+ from robosuite.robots.robot import Robot
10
+ from robosuite.utils.observables import Observable, sensor
11
+
12
+
13
+ class MobileRobot(Robot):
14
+ """
15
+ Initializes a robot with a fixed base.
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ robot_type: str,
21
+ idn=0,
22
+ composite_controller_config=None,
23
+ initial_qpos=None,
24
+ initialization_noise=None,
25
+ base_type="default",
26
+ gripper_type="default",
27
+ control_freq=20,
28
+ lite_physics=True,
29
+ ):
30
+ super().__init__(
31
+ robot_type=robot_type,
32
+ idn=idn,
33
+ composite_controller_config=composite_controller_config,
34
+ initial_qpos=initial_qpos,
35
+ initialization_noise=initialization_noise,
36
+ base_type=base_type,
37
+ gripper_type=gripper_type,
38
+ control_freq=control_freq,
39
+ lite_physics=lite_physics,
40
+ )
41
+
42
+ def _load_controller(self):
43
+ """
44
+ Loads controller to be used for dynamic trajectories
45
+ """
46
+ pass
47
+
48
+ def _load_base_controller(self):
49
+ """
50
+ Load base controller
51
+ """
52
+ if len(self._ref_actuators_indexes_dict[self.base]) == 0:
53
+ return None
54
+ if self.part_controller_config.get(self.base) is None:
55
+ controller_path = os.path.join(
56
+ os.path.dirname(__file__),
57
+ "..",
58
+ "controllers/config/{}.json".format(self.robot_model.default_controller_config[self.base]),
59
+ )
60
+ self.part_controller_config[self.base] = load_part_controller_config(custom_fpath=controller_path)
61
+
62
+ # Assert that the controller config is a dict file:
63
+ # NOTE: "type" must be one of: {JOINT_POSITION, JOINT_TORQUE, JOINT_VELOCITY,
64
+ # OSC_POSITION, OSC_POSE, IK_POSE}
65
+ assert (
66
+ type(self.part_controller_config[self.base]) == dict
67
+ ), "Inputted controller config must be a dict! Instead, got type: {}".format(
68
+ type(self.part_controller_config[self.base])
69
+ )
70
+
71
+ self.part_controller_config[self.base]["ramp_ratio"] = 1.0
72
+ self.part_controller_config[self.base]["robot_name"] = self.name
73
+
74
+ self.part_controller_config[self.base]["sim"] = self.sim
75
+ self.part_controller_config[self.base]["part_name"] = self.base
76
+ self.part_controller_config[self.base]["naming_prefix"] = self.robot_model.base.naming_prefix
77
+ self.part_controller_config[self.base]["ndim"] = self._joint_split_idx
78
+ self.part_controller_config[self.base]["policy_freq"] = self.control_freq
79
+ self.part_controller_config[self.base]["lite_physics"] = self.lite_physics
80
+
81
+ ref_base_joint_indexes = [self.sim.model.joint_name2id(x) for x in self.robot_model.base_joints]
82
+ ref_base_joint_pos_indexes = [self.sim.model.get_joint_qpos_addr(x) for x in self.robot_model.base_joints]
83
+ ref_base_joint_vel_indexes = [self.sim.model.get_joint_qvel_addr(x) for x in self.robot_model.base_joints]
84
+ self.part_controller_config[self.base]["joint_indexes"] = {
85
+ "joints": ref_base_joint_indexes,
86
+ "qpos": ref_base_joint_pos_indexes,
87
+ "qvel": ref_base_joint_vel_indexes,
88
+ }
89
+
90
+ low = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.base], 0]
91
+ high = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.base], 1]
92
+
93
+ self.part_controller_config[self.base]["actuator_range"] = (low, high)
94
+
95
+ def _load_torso_controller(self):
96
+ """
97
+ Load torso controller
98
+ """
99
+ if len(self._ref_actuators_indexes_dict[self.torso]) == 0:
100
+ return None
101
+
102
+ if self.part_controller_config.get(self.torso) is None:
103
+ controller_path = os.path.join(
104
+ os.path.dirname(__file__),
105
+ "..",
106
+ "controllers/config/{}.json".format(self.robot_model.default_controller_config[self.torso]),
107
+ )
108
+ self.part_controller_config[self.torso] = load_part_controller_config(custom_fpath=controller_path)
109
+
110
+ # Assert that the controller config is a dict file:
111
+ # NOTE: "type" must be one of: {JOINT_POSITION, JOINT_TORQUE, JOINT_VELOCITY,
112
+ # OSC_POSITION, OSC_POSE, IK_POSE}
113
+ assert (
114
+ type(self.part_controller_config[self.torso]) == dict
115
+ ), "Inputted controller config must be a dict! Instead, got type: {}".format(
116
+ type(self.part_controller_config[self.torso])
117
+ )
118
+
119
+ # TODO: Add a default controller config for torso
120
+ self.part_controller_config[self.torso]["robot_name"] = self.name
121
+ self.part_controller_config[self.torso]["sim"] = self.sim
122
+ self.part_controller_config[self.torso]["part_name"] = self.torso
123
+ self.part_controller_config[self.torso]["naming_prefix"] = self.robot_model.naming_prefix
124
+ self.part_controller_config[self.torso]["ndim"] = self._joint_split_idx
125
+ self.part_controller_config[self.torso]["policy_freq"] = self.control_freq
126
+ self.part_controller_config[self.torso]["lite_physics"] = self.lite_physics
127
+
128
+ ref_torso_joint_indexes = [self.sim.model.joint_name2id(x) for x in self.robot_model.torso_joints]
129
+ ref_torso_joint_pos_indexes = [self.sim.model.get_joint_qpos_addr(x) for x in self.robot_model.torso_joints]
130
+ ref_torso_joint_vel_indexes = [self.sim.model.get_joint_qvel_addr(x) for x in self.robot_model.torso_joints]
131
+ self.part_controller_config[self.torso]["joint_indexes"] = {
132
+ "joints": ref_torso_joint_indexes,
133
+ "qpos": ref_torso_joint_pos_indexes,
134
+ "qvel": ref_torso_joint_vel_indexes,
135
+ }
136
+
137
+ low = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.torso], 0]
138
+ high = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.torso], 1]
139
+
140
+ self.part_controller_config[self.torso]["actuator_range"] = (low, high)
141
+
142
+ def _load_head_controller(self):
143
+ """
144
+ Load head controller
145
+ """
146
+ if len(self._ref_actuators_indexes_dict[self.head]) == 0:
147
+ return None
148
+ if self.part_controller_config.get(self.head) is None:
149
+ controller_path = os.path.join(
150
+ os.path.dirname(__file__),
151
+ "..",
152
+ "controllers/config/{}.json".format(self.robot_model.default_controller_config[self.head]),
153
+ )
154
+ self.part_controller_config[self.head] = load_part_controller_config(custom_fpath=controller_path)
155
+
156
+ # Assert that the controller config is a dict file:
157
+ # NOTE: "type" must be one of: {JOINT_POSITION, JOINT_TORQUE, JOINT_VELOCITY,
158
+ # OSC_POSITION, OSC_POSE, IK_POSE}
159
+ assert (
160
+ type(self.part_controller_config[self.head]) == dict
161
+ ), "Inputted controller config must be a dict! Instead, got type: {}".format(
162
+ type(self.part_controller_config[self.head])
163
+ )
164
+
165
+ self.part_controller_config[self.head]["robot_name"] = self.name
166
+ self.part_controller_config[self.head]["sim"] = self.sim
167
+
168
+ self.part_controller_config[self.head]["part_name"] = self.head
169
+ self.part_controller_config[self.head]["naming_prefix"] = self.robot_model.naming_prefix
170
+ self.part_controller_config[self.head]["ndim"] = self._joint_split_idx
171
+ self.part_controller_config[self.head]["policy_freq"] = self.control_freq
172
+ self.part_controller_config[self.head]["lite_physics"] = self.lite_physics
173
+
174
+ ref_head_joint_indexes = [self.sim.model.joint_name2id(x) for x in self.robot_model.head_joints]
175
+ ref_head_joint_pos_indexes = [self.sim.model.get_joint_qpos_addr(x) for x in self.robot_model.head_joints]
176
+ ref_head_joint_vel_indexes = [self.sim.model.get_joint_qvel_addr(x) for x in self.robot_model.head_joints]
177
+ self.part_controller_config[self.head]["joint_indexes"] = {
178
+ "joints": ref_head_joint_indexes,
179
+ "qpos": ref_head_joint_pos_indexes,
180
+ "qvel": ref_head_joint_vel_indexes,
181
+ }
182
+
183
+ low = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.head], 0]
184
+ high = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.head], 1]
185
+
186
+ self.part_controller_config[self.head]["actuator_range"] = (low, high)
187
+
188
+ def load_model(self):
189
+ """
190
+ Loads robot and optionally add grippers.
191
+ """
192
+ # First, run the superclass method to load the relevant model
193
+ super().load_model()
194
+
195
+ def reset(self, deterministic=False):
196
+ """
197
+ Sets initial pose of arm and grippers. Overrides gripper joint configuration if we're using a
198
+ deterministic reset (e.g.: hard reset from xml file)
199
+
200
+ Args:
201
+ deterministic (bool): If true, will not randomize initializations within the sim
202
+ """
203
+ # First, run the superclass method to reset the position and controller
204
+ super().reset(deterministic)
205
+
206
+ def setup_references(self):
207
+ """
208
+ Sets up necessary reference for robots, grippers, and objects.
209
+
210
+ Note that this should get called during every reset from the environment
211
+ """
212
+ # First, run the superclass method to setup references for joint-related values / indexes
213
+ super().setup_references()
214
+ for arm in self.arms:
215
+ (start, end) = (None, self._joint_split_idx) if arm == "right" else (self._joint_split_idx, None)
216
+ self._ref_joints_indexes_dict[arm] = [
217
+ self.sim.model.joint_name2id(joint) for joint in self.robot_model.arm_joints[start:end]
218
+ ]
219
+ self._ref_actuators_indexes_dict[arm] = [
220
+ self.sim.model.actuator_name2id(joint) for joint in self.robot_model.arm_actuators[start:end]
221
+ ]
222
+
223
+ if self.has_gripper[arm]:
224
+ self.gripper_joints[arm] = list(self.gripper[arm].joints)
225
+ self._ref_gripper_joint_pos_indexes[arm] = [
226
+ self.sim.model.get_joint_qpos_addr(x) for x in self.gripper_joints[arm]
227
+ ]
228
+ self._ref_gripper_joint_vel_indexes[arm] = [
229
+ self.sim.model.get_joint_qvel_addr(x) for x in self.gripper_joints[arm]
230
+ ]
231
+ self._ref_joint_gripper_actuator_indexes[arm] = [
232
+ self.sim.model.actuator_name2id(actuator) for actuator in self.gripper[arm].actuators
233
+ ]
234
+ self._ref_joints_indexes_dict[self.get_gripper_name(arm)] = [
235
+ self.sim.model.joint_name2id(joint) for joint in self.gripper_joints[arm]
236
+ ]
237
+ self._ref_actuators_indexes_dict[self.get_gripper_name(arm)] = self._ref_joint_gripper_actuator_indexes[
238
+ arm
239
+ ]
240
+
241
+ # IDs of sites for eef visualization
242
+ self.eef_site_id[arm] = self.sim.model.site_name2id(self.gripper[arm].important_sites["grip_site"])
243
+ self.eef_cylinder_id[arm] = self.sim.model.site_name2id(self.gripper[arm].important_sites["grip_cylinder"])
244
+
245
+ self._ref_actuators_indexes_dict[self.base] = [
246
+ self.sim.model.actuator_name2id(actuator) for actuator in self.robot_model.base_actuators
247
+ ]
248
+
249
+ self._ref_actuators_indexes_dict[self.torso] = [
250
+ self.sim.model.actuator_name2id(actuator) for actuator in self.robot_model.torso_actuators
251
+ ]
252
+
253
+ self._ref_actuators_indexes_dict[self.head] = [
254
+ self.sim.model.actuator_name2id(actuator) for actuator in self.robot_model.head_actuators
255
+ ]
256
+
257
+ self._ref_joints_indexes_dict[self.base] = [
258
+ self.sim.model.joint_name2id(joint) for joint in self.robot_model.base_joints
259
+ ]
260
+
261
+ self._ref_joints_indexes_dict[self.torso] = [
262
+ self.sim.model.joint_name2id(joint) for joint in self.robot_model.torso_joints
263
+ ]
264
+
265
+ self._ref_joints_indexes_dict[self.head] = [
266
+ self.sim.model.joint_name2id(joint) for joint in self.robot_model.head_joints
267
+ ]
268
+
269
+ def control(self, action, policy_step=False):
270
+ """
271
+ Actuate the robot with the
272
+ passed joint velocities and gripper control.
273
+
274
+ Args:
275
+ action (np.array): The control to apply to the robot. The first @self.robot_model.dof dimensions should
276
+ be the desired normalized joint velocities and if the robot has a gripper, the next @self.gripper.dof
277
+ dimensions should be actuation controls for the gripper.
278
+
279
+ :NOTE: Assumes inputted actions are of form:
280
+ [right_arm_control, right_gripper_control, left_arm_control, left_gripper_control]
281
+
282
+ policy_step (bool): Whether a new policy step (action) is being taken
283
+
284
+ Raises:
285
+ AssertionError: [Invalid action dimension]
286
+ """
287
+ raise NotImplementedError
288
+
289
+ def setup_observables(self):
290
+ """
291
+ Sets up observables to be used for this robot
292
+
293
+ Returns:
294
+ OrderedDict: Dictionary mapping observable names to its corresponding Observable object
295
+ """
296
+ # Get general robot observables first
297
+ observables = super().setup_observables()
298
+
299
+ return observables
300
+
301
+ def _create_base_sensors(self, modality):
302
+ """
303
+ Creates base sensors for the robot.
304
+
305
+ Args:
306
+ modality (str): Type/modality of the created sensor
307
+ """
308
+
309
+ @sensor(modality=modality)
310
+ def base_pos(obs_cache):
311
+ return np.array(
312
+ self.sim.data.site_xpos[self.sim.model.site_name2id(self.robot_model.base.correct_naming("center"))]
313
+ )
314
+
315
+ @sensor(modality=modality)
316
+ def base_quat(obs_cache):
317
+ return T.mat2quat(self.sim.data.get_site_xmat(self.robot_model.base.correct_naming("center")))
318
+
319
+ sensors = [base_pos, base_quat]
320
+ names = ["base_pos", "base_quat"]
321
+
322
+ for arm in self.arms:
323
+
324
+ @sensor(modality=modality)
325
+ def base_to_eef_pos(obs_cache):
326
+ eef_pos = np.array(self.sim.data.site_xpos[self.eef_site_id[arm]])
327
+ base_pos = np.array(
328
+ self.sim.data.site_xpos[self.sim.model.site_name2id(self.robot_model.base.correct_naming("center"))]
329
+ )
330
+
331
+ eef_quat = T.convert_quat(self.sim.data.get_body_xquat(self.robot_model.eef_name[arm]), to="xyzw")
332
+ eef_mat = T.quat2mat(eef_quat)
333
+ base_mat = self.sim.data.get_site_xmat(self.robot_model.base.correct_naming("center"))
334
+
335
+ T_WA = np.vstack((np.hstack((base_mat, base_pos[:, None])), [0, 0, 0, 1]))
336
+ T_WB = np.vstack((np.hstack((eef_mat, eef_pos[:, None])), [0, 0, 0, 1]))
337
+ T_AB = np.matmul(np.linalg.inv(T_WA), T_WB)
338
+ base_to_eef_pos = T_AB[:3, 3]
339
+ return base_to_eef_pos
340
+
341
+ @sensor(modality=modality)
342
+ def base_to_eef_quat(obs_cache):
343
+ """
344
+ Args:
345
+ obs_cache (dict): A dictionary containing cached observations.
346
+
347
+ Returns:
348
+ numpy.ndarray: The quaternion representing the orientation of the end effector *body*
349
+ in the robot base coordinate frame.
350
+
351
+ Note:
352
+ In robosuite<=1.5, eef_quat has been queried from the body instead
353
+ of the site and has thus been inconsistent with base_to_eef_pos, which queries the position
354
+ from the site. This inconsistency has been raised in issue
355
+ https://github.com/ARISE-Initiative/robosuite/issues/298
356
+
357
+ Datasets collected with robosuite<=1.4 have use the eef_quat queried from the body, so we keep this key.
358
+ New datasets should ideally use the logic in base_to_eef_quat_site.
359
+
360
+ In a later robosuite release, we will directly update base_to_eef_quat to query
361
+ the orientation from the site.
362
+ """
363
+ eef_pos = np.array(self.sim.data.site_xpos[self.eef_site_id[arm]])
364
+ base_pos = np.array(
365
+ self.sim.data.site_xpos[self.sim.model.site_name2id(self.robot_model.base.correct_naming("center"))]
366
+ )
367
+
368
+ eef_quat = T.convert_quat(self.sim.data.get_body_xquat(self.robot_model.eef_name[arm]), to="xyzw")
369
+ eef_mat = T.quat2mat(eef_quat)
370
+ base_mat = self.sim.data.get_site_xmat(self.robot_model.base.correct_naming("center"))
371
+
372
+ T_WA = np.vstack((np.hstack((base_mat, base_pos[:, None])), [0, 0, 0, 1]))
373
+ T_WB = np.vstack((np.hstack((eef_mat, eef_pos[:, None])), [0, 0, 0, 1]))
374
+ T_AB = np.matmul(np.linalg.inv(T_WA), T_WB)
375
+ base_to_eef_mat = T_AB[:3, :3]
376
+ return T.mat2quat(base_to_eef_mat)
377
+
378
+ @sensor(modality=modality)
379
+ def base_to_eef_quat_site(obs_cache):
380
+ """
381
+ Args:
382
+ obs_cache (dict): A dictionary containing cached observations.
383
+
384
+ Returns:
385
+ numpy.ndarray: The quaternion representing the orientation of the end effector *site*
386
+ in the robot base coordinate frame.
387
+
388
+ Note:
389
+ In robosuite<=1.5, eef_quat has been queried from the body instead
390
+ of the site and has thus been inconsistent with base_to_eef_pos, which queries the position
391
+ from the site. This inconsistency has been raised in issue
392
+ https://github.com/ARISE-Initiative/robosuite/issues/298
393
+
394
+ Datasets collected with robosuite<=1.4 have use the eef_quat queried from the body,
395
+ so we keep this key. New datasets should ideally use the logic in base_to_eef_quat_site.
396
+
397
+ In a later robosuite release, we will directly update base_to_eef_quat to query
398
+ the orientation from the site, and then remove this base_to_eef_quat_site key.
399
+ """
400
+ eef_pos = np.array(self.sim.data.site_xpos[self.eef_site_id[arm]])
401
+ base_pos = np.array(
402
+ self.sim.data.site_xpos[self.sim.model.site_name2id(self.robot_model.base.correct_naming("center"))]
403
+ )
404
+
405
+ eef_mat_site = self.sim.data.site_xmat[self.eef_site_id[arm]].reshape((3, 3))
406
+ base_mat = self.sim.data.get_site_xmat(self.robot_model.base.correct_naming("center"))
407
+
408
+ T_WA = np.vstack((np.hstack((base_mat, base_pos[:, None])), [0, 0, 0, 1]))
409
+ T_WB = np.vstack((np.hstack((eef_mat_site, eef_pos[:, None])), [0, 0, 0, 1]))
410
+ T_AB = np.matmul(np.linalg.inv(T_WA), T_WB)
411
+ base_to_eef_mat_site = T_AB[:3, :3]
412
+
413
+ return T.mat2quat(base_to_eef_mat_site)
414
+
415
+ # only consider prefix if there is more than one arm
416
+ pf = f"{arm}_" if len(self.arms) > 1 else ""
417
+
418
+ sensors += [base_to_eef_pos, base_to_eef_quat, base_to_eef_quat_site]
419
+ names += [f"base_to_{pf}eef_pos", f"base_to_{pf}eef_quat", f"base_to_{pf}eef_quat_site"]
420
+
421
+ return sensors, names
422
+
423
+ def enable_parts(self, right=True, left=True, torso=True, head=True, base=True, legs=True):
424
+
425
+ self._enabled_parts = {
426
+ "right": right,
427
+ "right_gripper": right,
428
+ "left": left,
429
+ "left_gripper": left,
430
+ self.torso: torso,
431
+ self.head: head,
432
+ self.base: base,
433
+ self.legs: legs,
434
+ }
435
+
436
+ @property
437
+ def is_mobile(self):
438
+ return True
439
+
440
+ @property
441
+ def base(self):
442
+ return "base"
443
+
444
+ @property
445
+ def torso(self):
446
+ return "torso"
447
+
448
+ @property
449
+ def head(self):
450
+ return "head"
451
+
452
+ @property
453
+ def legs(self):
454
+ return "legs"
455
+
456
+ @property
457
+ def _action_split_indexes(self):
458
+ """
459
+ Dictionary of split indexes for each part of the robot
460
+
461
+ Returns:
462
+ dict: Dictionary of split indexes for each part of the robot
463
+ """
464
+ return self.composite_controller._action_split_indexes
third_party/robosuite/robosuite/robots/robot.py ADDED
@@ -0,0 +1,1007 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import json
3
+ import os
4
+ from collections import OrderedDict
5
+ from typing import Optional
6
+
7
+ import numpy as np
8
+
9
+ import robosuite.utils.transform_utils as T
10
+ from robosuite.controllers import load_composite_controller_config, load_part_controller_config
11
+ from robosuite.models.bases import robot_base_factory
12
+ from robosuite.models.grippers import gripper_factory
13
+ from robosuite.models.robots import create_robot
14
+ from robosuite.models.robots.robot_model import REGISTERED_ROBOTS
15
+ from robosuite.utils.binding_utils import MjSim
16
+ from robosuite.utils.buffers import DeltaBuffer, RingBuffer
17
+ from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER
18
+ from robosuite.utils.mjcf_utils import array_to_string
19
+ from robosuite.utils.observables import Observable, sensor
20
+
21
+
22
+ class Robot(object):
23
+ """
24
+ Initializes a robot simulation object, as defined by a single corresponding robot XML
25
+
26
+ Args:
27
+ robot_type (str): Specification for specific robot arm to be instantiated within this env (e.g: "Panda")
28
+
29
+ idn (int or str): Unique ID of this robot. Should be different from others
30
+
31
+ initial_qpos (sequence of float): If set, determines the initial joint positions of the robot to be
32
+ instantiated for the task
33
+
34
+ initialization_noise (dict): Dict containing the initialization noise parameters. The expected keys and
35
+ corresponding value types are specified below:
36
+
37
+ :`'magnitude'`: The scale factor of uni-variate random noise applied to each of a robot's given initial
38
+ joint positions. Setting this value to "None" or 0.0 results in no noise being applied.
39
+ If "gaussian" type of noise is applied then this magnitude scales the standard deviation applied,
40
+ If "uniform" type of noise is applied then this magnitude sets the bounds of the sampling range
41
+ :`'type'`: Type of noise to apply. Can either specify "gaussian" or "uniform"
42
+
43
+ :Note: Specifying None will automatically create the required dict with "magnitude" set to 0.0
44
+
45
+ base_type (str): type of base, used to instantiate base models from base factory.
46
+ Default is "default", which is the default base associated with this robot's corresponding model.
47
+ None results in no base, and any other (valid) model overrides the default base.
48
+
49
+ control_freq (float): how many control signals to receive
50
+ in every second. This sets the amount of simulation time
51
+ that passes between every action input.
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ robot_type: str,
57
+ idn=0,
58
+ composite_controller_config=None,
59
+ initial_qpos=None,
60
+ initialization_noise=None,
61
+ base_type="default",
62
+ gripper_type="default",
63
+ control_freq=20,
64
+ lite_physics=True,
65
+ ):
66
+ self.arms = REGISTERED_ROBOTS[robot_type].arms
67
+
68
+ # TODO: Merge self.part_controller_config and self.composite_controller_config into one
69
+ if composite_controller_config is not None:
70
+ self.composite_controller_config = composite_controller_config
71
+ else:
72
+ self.composite_controller_config = load_composite_controller_config(robot=robot_type)
73
+
74
+ self.part_controller_config = copy.deepcopy(self.composite_controller_config.get("body_parts", {}))
75
+
76
+ self.gripper = self._input2dict(None)
77
+ self.gripper_type = self._input2dict(gripper_type)
78
+ self.has_gripper = self._input2dict([gripper_type is not None for _, gripper_type in self.gripper_type.items()])
79
+
80
+ self.gripper_joints = self._input2dict(None) # xml joint names for gripper
81
+ self._ref_gripper_joint_pos_indexes = self._input2dict(None) # xml gripper joint position indexes in mjsim
82
+ self._ref_gripper_joint_vel_indexes = self._input2dict(None) # xml gripper joint velocity indexes in mjsim
83
+ self._ref_joint_gripper_actuator_indexes = self._input2dict(
84
+ None
85
+ ) # xml gripper (pos) actuator indexes for robot in mjsim
86
+ self.eef_rot_offset = self._input2dict(None) # rotation offsets from final arm link to gripper (quat)
87
+ self.eef_site_id = self._input2dict(None) # xml element id for eef in mjsim
88
+ self.eef_cylinder_id = self._input2dict(None) # xml element id for eef cylinder in mjsim
89
+ self.torques = None # Current torques being applied
90
+
91
+ self.recent_ee_forcetorques = self._input2dict(None) # Current and last forces / torques sensed at eef
92
+ self.recent_ee_pose = self._input2dict(None) # Current and last eef pose (pos + ori (quat))
93
+ self.recent_ee_vel = self._input2dict(None) # Current and last eef velocity
94
+ self.recent_ee_vel_buffer = self._input2dict(None) # RingBuffer holding prior 10 values of velocity values
95
+ self.recent_ee_acc = self._input2dict(None) # Current and last eef acceleration
96
+
97
+ # Set relevant attributes
98
+ self.sim = None # MjSim this robot is tied to
99
+ self.name = robot_type # Specific robot to instantiate
100
+ self.idn = idn # Unique ID of this robot
101
+ self.robot_model = None # object holding robot model-specific info
102
+ self.control_freq = control_freq # controller Hz
103
+ self.lite_physics = lite_physics
104
+ self.base_type = base_type # Type of robot base to use
105
+
106
+ # Scaling of Gaussian initial noise applied to robot joints
107
+ self.initialization_noise = initialization_noise
108
+ if self.initialization_noise is None:
109
+ self.initialization_noise = {"magnitude": 0.0, "type": "gaussian"} # no noise conditions
110
+ elif self.initialization_noise == "default":
111
+ self.initialization_noise = {"magnitude": 0.02, "type": "gaussian"}
112
+ self.initialization_noise["magnitude"] = (
113
+ self.initialization_noise["magnitude"] if self.initialization_noise["magnitude"] else 0.0
114
+ )
115
+
116
+ self.init_qpos = initial_qpos # n-dim list / array of robot joints
117
+ self.init_torso_qpos = None
118
+
119
+ self.robot_joints = None # xml joint names for robot
120
+ self.base_pos = None # Base position in world coordinates (x,y,z)
121
+ self.base_ori = None # Base rotation in world coordinates (x,y,z,w quat)
122
+ self._ref_joint_indexes = None # xml joint indexes for robot in mjsim
123
+ self._ref_joint_pos_indexes = None # xml joint position indexes in mjsim
124
+ self._ref_joint_vel_indexes = None # xml joint velocity indexes in mjsim
125
+ self._ref_arm_joint_actuator_indexes = None # xml joint (torq) actuator indexes for robot in mjsim
126
+
127
+ self.recent_qpos = None # Current and last robot arm qpos
128
+ self.recent_actions = None # Current and last action applied
129
+ self.recent_torques = None # Current and last torques applied
130
+
131
+ self._ref_actuators_indexes_dict = {}
132
+ self._ref_joints_indexes_dict = {}
133
+
134
+ self._enabled_parts = {}
135
+ self.composite_controller = None
136
+
137
+ def _load_controller(self):
138
+ """
139
+ Loads controller to be used for dynamic trajectories.
140
+ """
141
+ raise NotImplementedError
142
+
143
+ def _postprocess_part_controller_config(self):
144
+ """
145
+ Update part_controller_config with values from composite_controller_config for each body part.
146
+ Remove unused parts that are not in the controller.
147
+ Called by _load_controller() function
148
+ """
149
+ for part_name, controller_config in self.composite_controller_config.get("body_parts", {}).items():
150
+ if not self.has_part(part_name):
151
+ ROBOSUITE_DEFAULT_LOGGER.warning(
152
+ f'The config has defined for the controller "{part_name}", '
153
+ "but the robot does not have this component. Skipping, but make sure this is intended."
154
+ f"Removing the controller config for {part_name} from self.part_controller_config."
155
+ )
156
+ self.part_controller_config.pop(part_name, None)
157
+ continue
158
+ if part_name in self.part_controller_config:
159
+ self.part_controller_config[part_name].update(controller_config)
160
+
161
+ def load_model(self):
162
+ """
163
+ Loads robot and optionally add grippers.
164
+ """
165
+ self.robot_model = create_robot(self.name, idn=self.idn)
166
+
167
+ # Add base if specified
168
+ if self.base_type == "default":
169
+ self.robot_model.add_base(base=robot_base_factory(self.robot_model.default_base, idn=self.idn))
170
+ else:
171
+ self.robot_model.add_base(base=robot_base_factory(self.base_type, idn=self.idn))
172
+
173
+ self.robot_model.update_joints()
174
+ self.robot_model.update_actuators()
175
+ # Use default from robot model for initial joint positions if not specified
176
+ if self.init_qpos is None:
177
+ self.init_qpos = self.robot_model.init_qpos
178
+
179
+ # Now, load the gripper if necessary
180
+ for arm in self.arms:
181
+ if self.has_gripper[arm]:
182
+ if self.gripper_type[arm] == "default":
183
+ # Load the default gripper from the robot file
184
+ idn = "_".join((str(self.idn), arm))
185
+ self.gripper[arm] = gripper_factory(self.robot_model.default_gripper[arm], idn=idn)
186
+ else:
187
+ # Load user-specified gripper
188
+ self.gripper[arm] = gripper_factory(self.gripper_type[arm], idn="_".join((str(self.idn), arm)))
189
+ else:
190
+ # Load null gripper
191
+ self.gripper[arm] = gripper_factory(None, idn="_".join((str(self.idn), arm)))
192
+ # Grab eef rotation offset
193
+ self.eef_rot_offset[arm] = T.quat_multiply(
194
+ self.robot_model.hand_rotation_offset[arm], self.gripper[arm].rotation_offset
195
+ )
196
+
197
+ # Adjust gripper mount offset and quaternion if users specify custom values. This part is essential to support more flexible composition of new robots.
198
+ custom_gripper_mount_pos_offset = self.robot_model.gripper_mount_pos_offset.get(arm, None)
199
+ custom_gripper_mount_quat_offset = self.robot_model.gripper_mount_quat_offset.get(arm, None)
200
+
201
+ # The offset of position and oriientation (quaternion) is assumed to be the very first body in the gripper xml.
202
+ if custom_gripper_mount_pos_offset is not None:
203
+ assert len(custom_gripper_mount_pos_offset) == 3
204
+ # update an attribute inside an xml object
205
+ self.gripper[arm].worldbody.find("body").attrib["pos"] = array_to_string(
206
+ custom_gripper_mount_pos_offset
207
+ )
208
+ if custom_gripper_mount_quat_offset is not None:
209
+ assert len(custom_gripper_mount_quat_offset) == 4
210
+ self.gripper[arm].worldbody.find("body").attrib["quat"] = array_to_string(
211
+ custom_gripper_mount_quat_offset
212
+ )
213
+
214
+ # Add this gripper to the robot model
215
+ self.robot_model.add_gripper(self.gripper[arm], self.robot_model.eef_name[arm])
216
+
217
+ # calling `mujoco.MjModel.from_xml_path()` resets mujoco's internal XML model and thus
218
+ # affects get_xml() used in calls in binding_utils.py
219
+ # https://mujoco.readthedocs.io/en/stable/APIreference/APIfunctions.html#mj-savelastxml
220
+ # https://mujoco.readthedocs.io/en/stable/APIreference/APIfunctions.html#mj-freelastxml
221
+ # our solution to requiring robot-only mujoco MjModels is to load the robot MjModels once first
222
+ # then using this mujoco MjModel herein
223
+ self.robot_model.set_mujoco_model()
224
+
225
+ def reset_sim(self, sim: MjSim):
226
+ """
227
+ Replaces current sim with a new sim
228
+
229
+ Args:
230
+ sim (MjSim): New simulation being instantiated to replace the old one
231
+ """
232
+ self.sim = sim
233
+
234
+ def reset(self, deterministic=False):
235
+ """
236
+ Sets initial pose of arm and grippers. Overrides robot joint configuration if we're using a
237
+ deterministic reset (e.g.: hard reset from xml file)
238
+
239
+ Args:
240
+ deterministic (bool): If true, will not randomize initializations within the sim
241
+
242
+ Raises:
243
+ ValueError: [Invalid noise type]
244
+ """
245
+ init_qpos = np.array(self.init_qpos)
246
+ if not deterministic:
247
+ # Determine noise
248
+ if self.initialization_noise["type"] == "gaussian":
249
+ noise = np.random.randn(len(self.init_qpos)) * self.initialization_noise["magnitude"]
250
+ elif self.initialization_noise["type"] == "uniform":
251
+ noise = np.random.uniform(-1.0, 1.0, len(self.init_qpos)) * self.initialization_noise["magnitude"]
252
+ else:
253
+ raise ValueError("Error: Invalid noise type specified. Options are 'gaussian' or 'uniform'.")
254
+ init_qpos += noise
255
+
256
+ # Set initial position in sim
257
+ self.sim.data.qpos[self._ref_joint_pos_indexes] = init_qpos
258
+
259
+ if self.robot_model.init_base_qpos is not None:
260
+ self.sim.data.qpos[self._ref_base_joint_pos_indexes] = self.robot_model.init_base_qpos
261
+
262
+ init_torso_qpos = self.init_torso_qpos
263
+ if self.init_torso_qpos is None:
264
+ init_torso_qpos = self.robot_model.init_torso_qpos
265
+ if init_torso_qpos is not None:
266
+ self.sim.data.qpos[self._ref_torso_joint_pos_indexes] = init_torso_qpos
267
+
268
+ # Load controllers
269
+ self._load_controller()
270
+
271
+ # Update base pos / ori references
272
+ self.base_pos = self.sim.data.get_body_xpos(self.robot_model.root_body)
273
+ self.base_ori = self.sim.data.get_body_xmat(self.robot_model.root_body).reshape((3, 3))
274
+
275
+ # Setup buffers to hold recent values
276
+ self.recent_qpos = DeltaBuffer(dim=len(self.joint_indexes))
277
+ self.recent_actions = DeltaBuffer(dim=self.action_dim)
278
+ self.recent_torques = DeltaBuffer(dim=len(self.joint_indexes))
279
+
280
+ # Setup arm-specific values
281
+ for arm in self.arms:
282
+ # Now, reset the grippers if necessary
283
+ if self.has_gripper[arm]:
284
+ if not deterministic:
285
+ self.sim.data.qpos[self._ref_gripper_joint_pos_indexes[arm]] = self.gripper[arm].init_qpos
286
+
287
+ self.gripper[arm].current_action = np.zeros(self.gripper[arm].dof)
288
+
289
+ # Setup buffers for eef values
290
+ self.recent_ee_forcetorques[arm] = DeltaBuffer(dim=6)
291
+ self.recent_ee_pose[arm] = DeltaBuffer(dim=7)
292
+ self.recent_ee_vel[arm] = DeltaBuffer(dim=6)
293
+ self.recent_ee_vel_buffer[arm] = RingBuffer(dim=6, length=10)
294
+ self.recent_ee_acc[arm] = DeltaBuffer(dim=6)
295
+
296
+ # reset internal variables for composite controller
297
+ self.composite_controller.update_state()
298
+ self.composite_controller.reset()
299
+
300
+ def setup_references(self):
301
+ """
302
+ Sets up necessary reference for robots, bases, grippers, and objects.
303
+ """
304
+ # indices for joints in qpos, qvel
305
+ self.robot_joints = self.robot_model.joints
306
+ self._ref_joint_pos_indexes = [self.sim.model.get_joint_qpos_addr(x) for x in self.robot_joints]
307
+ self._ref_joint_vel_indexes = [self.sim.model.get_joint_qvel_addr(x) for x in self.robot_joints]
308
+
309
+ # indices for joint indexes
310
+ self._ref_joint_indexes = [self.sim.model.joint_name2id(joint) for joint in self.robot_joints]
311
+
312
+ # indices for joint pos actuation, joint vel actuation, gripper actuation
313
+ self._ref_arm_joint_actuator_indexes = [
314
+ self.sim.model.actuator_name2id(actuator) for actuator in self.robot_model.arm_actuators
315
+ ]
316
+
317
+ self.robot_arm_joints = self.robot_model.arm_joints
318
+ self._ref_arm_joint_indexes = [self.sim.model.joint_name2id(joint) for joint in self.robot_arm_joints]
319
+ self._ref_arm_joint_pos_indexes = [self.sim.model.get_joint_qpos_addr(x) for x in self.robot_arm_joints]
320
+ self._ref_arm_joint_vel_indexes = [self.sim.model.get_joint_qvel_addr(x) for x in self.robot_arm_joints]
321
+
322
+ # indices for base joints
323
+ self._ref_base_joint_pos_indexes = [
324
+ self.sim.model.get_joint_qpos_addr(x) for x in self.robot_model._base_joints
325
+ ]
326
+ self._ref_torso_joint_pos_indexes = [
327
+ self.sim.model.get_joint_qpos_addr(x) for x in self.robot_model._torso_joints
328
+ ]
329
+
330
+ def setup_observables(self):
331
+ """
332
+ Sets up observables to be used for this robot
333
+
334
+ Returns:
335
+ OrderedDict: Dictionary mapping observable names to its corresponding Observable object
336
+ """
337
+ # Get prefix from robot model to avoid naming clashes for multiple robots and define observables modality
338
+ pf = self.robot_model.naming_prefix
339
+ pre_compute = f"{pf}joint_pos"
340
+ modality = f"{pf}proprio"
341
+
342
+ # proprioceptive features
343
+ @sensor(modality=modality)
344
+ def joint_pos(obs_cache):
345
+ return np.array([self.sim.data.qpos[x] for x in self._ref_joint_pos_indexes])
346
+
347
+ @sensor(modality=modality)
348
+ def joint_pos_cos(obs_cache):
349
+ return np.cos(obs_cache[pre_compute]) if pre_compute in obs_cache else np.zeros(self.robot_model.dof)
350
+
351
+ @sensor(modality=modality)
352
+ def joint_pos_sin(obs_cache):
353
+ return np.sin(obs_cache[pre_compute]) if pre_compute in obs_cache else np.zeros(self.robot_model.dof)
354
+
355
+ @sensor(modality=modality)
356
+ def joint_vel(obs_cache):
357
+ return np.array([self.sim.data.qvel[x] for x in self._ref_joint_vel_indexes])
358
+
359
+ sensors = [joint_pos, joint_pos_cos, joint_pos_sin, joint_vel]
360
+ names = ["joint_pos", "joint_pos_cos", "joint_pos_sin", "joint_vel"]
361
+ # We don't want to include the direct joint pos sensor outputs
362
+ actives = [True, True, True, True]
363
+
364
+ for arm in self.arms:
365
+ arm_sensors, arm_sensor_names = self._create_arm_sensors(arm, modality=modality)
366
+ sensors += arm_sensors
367
+ names += arm_sensor_names
368
+ actives += [True] * len(arm_sensors)
369
+
370
+ base_sensors, base_sensor_names = self._create_base_sensors(modality=modality)
371
+ sensors += base_sensors
372
+ names += base_sensor_names
373
+ actives += [True] * len(base_sensors)
374
+
375
+ # Create observables for this robot
376
+ observables = OrderedDict()
377
+ for name, s, active in zip(names, sensors, actives):
378
+ obs_name = pf + name
379
+ observables[obs_name] = Observable(
380
+ name=obs_name,
381
+ sensor=s,
382
+ sampling_rate=self.control_freq,
383
+ active=active,
384
+ )
385
+
386
+ return observables
387
+
388
+ def _create_arm_sensors(self, arm, modality):
389
+ """
390
+ Helper function to create sensors for a given arm. This is abstracted in a separate function call so that we
391
+ don't have local function naming collisions during the _setup_observables() call.
392
+
393
+ Args:
394
+ arm (str): Arm to create sensors for
395
+ modality (str): Modality to assign to all sensors
396
+
397
+ Returns:
398
+ 2-tuple:
399
+ sensors (list): Array of sensors for the given arm
400
+ names (list): array of corresponding observable names
401
+ """
402
+
403
+ # eef features
404
+ @sensor(modality=modality)
405
+ def eef_pos(obs_cache):
406
+ return np.array(self.sim.data.site_xpos[self.eef_site_id[arm]])
407
+
408
+ @sensor(modality=modality)
409
+ def eef_quat(obs_cache):
410
+ """
411
+ Args:
412
+ obs_cache (dict): A dictionary containing cached observations.
413
+
414
+ Returns:
415
+ numpy.ndarray: The quaternion representing the orientation of the end effector *body*
416
+ in the mujoco world coordinate frame.
417
+
418
+ Note:
419
+ In robosuite<=1.5, eef_quat has been queried from the body instead
420
+ of the site and has thus been inconsistent with the eef_pos, which queries from the site.
421
+
422
+ This inconsistency has been raised in issue https://github.com/ARISE-Initiative/robosuite/issues/298.
423
+
424
+ Datasets collected with robosuite<=1.4 have use the eef_quat queried from the body, so we keep this key.
425
+ New datasets should ideally use the logic in eef_quat_site.
426
+
427
+ In a later robosuite release, we will directly update eef_quat to query
428
+ the orientation from the site.
429
+ """
430
+ return T.convert_quat(self.sim.data.get_body_xquat(self.robot_model.eef_name[arm]), to="xyzw")
431
+
432
+ @sensor(modality=modality)
433
+ def eef_quat_site(obs_cache):
434
+ """
435
+ Args:
436
+ obs_cache (dict): A dictionary containing cached observations.
437
+
438
+ Returns:
439
+ numpy.ndarray: The quaternion representing the orientation of the end effector *site*
440
+ in the mujoco world coordinate frame.
441
+
442
+ Note:
443
+ In robosuite<=1.5, eef_quat_site has been queried from the body instead
444
+ of the site and has thus been inconsistent with the eef_pos, which queries from the site.
445
+
446
+ This inconsistency has been raised in issue https://github.com/ARISE-Initiative/robosuite/issues/298
447
+
448
+ Datasets collected with robosuite<=1.4 have use the eef_quat queried from the body, so we keep this key.
449
+ New datasets should ideally use the logic in eef_quat_site.
450
+
451
+ In a later robosuite release, we will directly update eef_quat to query
452
+ the orientation from the site, and then remove this eef_quat_site key.
453
+ """
454
+ return T.mat2quat(self.sim.data.site_xmat[self.eef_site_id[arm]].reshape((3, 3)))
455
+
456
+ # only consider prefix if there is more than one arm
457
+ pf = f"{arm}_" if len(self.arms) > 1 else ""
458
+
459
+ sensors = [eef_pos, eef_quat, eef_quat_site]
460
+ names = [f"{pf}eef_pos", f"{pf}eef_quat", f"{pf}eef_quat_site"]
461
+
462
+ # add in gripper sensors if this robot has a gripper
463
+ if self.has_gripper[arm]:
464
+
465
+ @sensor(modality=modality)
466
+ def gripper_qpos(obs_cache):
467
+ return np.array([self.sim.data.qpos[x] for x in self._ref_gripper_joint_pos_indexes[arm]])
468
+
469
+ @sensor(modality=modality)
470
+ def gripper_qvel(obs_cache):
471
+ return np.array([self.sim.data.qvel[x] for x in self._ref_gripper_joint_vel_indexes[arm]])
472
+
473
+ sensors += [gripper_qpos, gripper_qvel]
474
+ names += [f"{pf}gripper_qpos", f"{pf}gripper_qvel"]
475
+
476
+ return sensors, names
477
+
478
+ def _create_base_sensors(self, modality):
479
+ """
480
+ Helper function to create sensors for the robot base. This will be
481
+ overriden by subclasses.
482
+
483
+ Args:
484
+ modality (str): Type/modality of the created sensor
485
+ """
486
+ return [], []
487
+
488
+ def control(self, action, policy_step=False):
489
+ """
490
+ Actuate the robot with the
491
+ passed joint velocities and gripper control.
492
+
493
+ Args:
494
+ action (np.array): The control to apply to the robot. The first @self.robot_model.dof dimensions should
495
+ be the desired normalized joint velocities and if the robot has a gripper, the next @self.gripper.dof
496
+ dimensions should be actuation controls for the gripper.
497
+ policy_step (bool): Whether a new policy step (action) is being taken
498
+ """
499
+ raise NotImplementedError
500
+
501
+ def check_q_limits(self):
502
+ """
503
+ Check if this robot is either very close or at the joint limits
504
+
505
+ Returns:
506
+ bool: True if this arm is near its joint limits
507
+ """
508
+ tolerance = 0.1
509
+ for qidx, (q, q_limits) in enumerate(
510
+ zip(self.sim.data.qpos[self._ref_joint_pos_indexes], self.sim.model.jnt_range[self._ref_joint_indexes])
511
+ ):
512
+ if q_limits[0] != q_limits[1] and not (q_limits[0] + tolerance < q < q_limits[1] - tolerance):
513
+ ROBOSUITE_DEFAULT_LOGGER.warning("Joint limit reached in joint " + str(qidx))
514
+ return True
515
+ return False
516
+
517
+ @property
518
+ def is_mobile(self):
519
+ return False
520
+
521
+ @property
522
+ def action_limits(self):
523
+ """
524
+ Action lower/upper limits per dimension.
525
+
526
+ Returns:
527
+ 2-tuple:
528
+
529
+ - (np.array) minimum (low) action values
530
+ - (np.array) maximum (high) action values
531
+ """
532
+ raise NotImplementedError
533
+
534
+ def _input2dict(self, inp):
535
+ """
536
+ Helper function that converts an input that is either a single value or a list into a dict with keys for
537
+ each arm: "right", "left"
538
+
539
+ Args:
540
+ inp (str or list or None): Input value to be converted to dict
541
+
542
+ :Note: If inp is a list, then assumes format is [right, left]
543
+
544
+ Returns:
545
+ dict: Inputs mapped for each robot arm
546
+ """
547
+ # First, convert to list if necessary
548
+ if type(inp) is not list:
549
+ inp = [inp for _ in range(2)]
550
+ # Now, convert list to dict and return
551
+ return {key: copy.deepcopy(value) for key, value in zip(self.arms, inp)}
552
+
553
+ @property
554
+ def torque_limits(self):
555
+ """
556
+ Torque lower/upper limits per dimension.
557
+
558
+ Returns:
559
+ 2-tuple:
560
+
561
+ - (np.array) minimum (low) torque values
562
+ - (np.array) maximum (high) torque values
563
+ """
564
+ # Torque limit values pulled from relevant robot.xml file
565
+ low = self.sim.model.actuator_ctrlrange[self._ref_arm_joint_actuator_indexes, 0]
566
+ high = self.sim.model.actuator_ctrlrange[self._ref_arm_joint_actuator_indexes, 1]
567
+ return low, high
568
+
569
+ @property
570
+ def action_dim(self):
571
+ """
572
+ Action space dimension for this robot
573
+ """
574
+ return self.action_limits[0].shape[0]
575
+
576
+ @property
577
+ def dof(self):
578
+ """
579
+ Returns:
580
+ int: the active DoF of the robot (Number of robot joints + active gripper DoF).
581
+ """
582
+ return self.robot_model.dof
583
+
584
+ def pose_in_base_from_name(self, name):
585
+ """
586
+ A helper function that takes in a named data field and returns the pose
587
+ of that object in the base frame.
588
+
589
+ Args:
590
+ name (str): Name of body in sim to grab pose
591
+
592
+ Returns:
593
+ np.array: (4,4) array corresponding to the pose of @name in the base frame
594
+ """
595
+
596
+ pos_in_world = self.sim.data.get_body_xpos(name)
597
+ rot_in_world = self.sim.data.get_body_xmat(name).reshape((3, 3))
598
+ pose_in_world = T.make_pose(pos_in_world, rot_in_world)
599
+
600
+ base_pos_in_world = self.sim.data.get_body_xpos(self.robot_model.root_body)
601
+ base_rot_in_world = self.sim.data.get_body_xmat(self.robot_model.root_body).reshape((3, 3))
602
+ base_pose_in_world = T.make_pose(base_pos_in_world, base_rot_in_world)
603
+ world_pose_in_base = T.pose_inv(base_pose_in_world)
604
+
605
+ pose_in_base = T.pose_in_A_to_pose_in_B(pose_in_world, world_pose_in_base)
606
+ return pose_in_base
607
+
608
+ def set_robot_joint_positions(self, jpos):
609
+ """
610
+ Helper method to force robot joint positions to the passed values.
611
+
612
+ Args:
613
+ jpos (np.array): Joint positions to manually set the robot to
614
+ """
615
+ self.sim.data.qpos[self._ref_joint_pos_indexes] = jpos
616
+ self.sim.forward()
617
+
618
+ def set_gripper_joint_positions(self, jpos: np.ndarray, gripper_arm: Optional[str] = None):
619
+ """
620
+ Helper method to force gripper joint positions to the passed values.
621
+
622
+ Args:
623
+ jpos (np.array): Joint jpos to manually set the gripper to
624
+ gripper_arm: arm corresponding to the gripper for which to set the gripper joint jpos.
625
+ If None, use default arm.
626
+ """
627
+ if gripper_arm is None:
628
+ gripper_arm = self.arms[0]
629
+ if self.has_gripper[gripper_arm]:
630
+ self.sim.data.qpos[self._ref_gripper_joint_pos_indexes[gripper_arm]] = jpos
631
+ self.sim.forward()
632
+ else:
633
+ raise ValueError(f"No gripper found for arm {gripper_arm}")
634
+
635
+ @property
636
+ def js_energy(self):
637
+ """
638
+ Returns:
639
+ np.array: the energy consumed by each joint between previous and current steps
640
+ """
641
+ # We assume in the motors torque is proportional to current (and voltage is constant)
642
+ # In that case the amount of power scales proportional to the torque and the energy is the
643
+ # time integral of that
644
+ # Note that we use mean torque
645
+ return np.abs((1.0 / self.control_freq) * self.recent_torques.average)
646
+
647
+ @property
648
+ def _joint_positions(self):
649
+ """
650
+ Returns:
651
+ np.array: joint positions (in angles / radians)
652
+ """
653
+ return self.sim.data.qpos[self._ref_joint_pos_indexes]
654
+
655
+ @property
656
+ def _joint_velocities(self):
657
+ """
658
+ Returns:
659
+ np.array: joint velocities (angular velocity)
660
+ """
661
+ return self.sim.data.qvel[self._ref_joint_vel_indexes]
662
+
663
+ @property
664
+ def joint_indexes(self):
665
+ """
666
+ Returns:
667
+ list: mujoco internal indexes for the robot joints
668
+ """
669
+ return self._ref_joint_indexes
670
+
671
+ @property
672
+ def arm_joint_indexes(self):
673
+ """
674
+ Returns:
675
+ list: mujoco internal indexes for the robot arm joints
676
+ """
677
+ return self._ref_arm_joint_indexes
678
+
679
+ def get_sensor_measurement(self, sensor_name):
680
+ """
681
+ Grabs relevant sensor data from the sim object
682
+
683
+ Args:
684
+ sensor_name (str): name of the sensor
685
+
686
+ Returns:
687
+ np.array: sensor values
688
+ """
689
+ sensor_idx = np.sum(self.sim.model.sensor_dim[: self.sim.model.sensor_name2id(sensor_name)])
690
+ sensor_dim = self.sim.model.sensor_dim[self.sim.model.sensor_name2id(sensor_name)]
691
+ return np.array(self.sim.data.sensordata[sensor_idx : sensor_idx + sensor_dim])
692
+
693
+ def visualize(self, vis_settings):
694
+ """
695
+ Do any necessary visualization for this manipulator
696
+
697
+ Args:
698
+ vis_settings (dict): Visualization keywords mapped to T/F, determining whether that specific
699
+ component should be visualized. Should have "robots" and "grippers" keyword as well as any other
700
+ robot-specific options specified.
701
+ """
702
+ self.robot_model.set_sites_visibility(sim=self.sim, visible=vis_settings["robots"])
703
+ self._visualize_grippers(visible=vis_settings["grippers"])
704
+
705
+ def _visualize_grippers(self, visible):
706
+ """
707
+ Visualizes the gripper site(s) if applicable.
708
+
709
+ Args:
710
+ visible (bool): True if visualizing the gripper for this arm.
711
+ """
712
+ for arm in self.arms:
713
+ self.gripper[arm].set_sites_visibility(sim=self.sim, visible=visible)
714
+
715
+ @property
716
+ def action_limits(self):
717
+ raise NotImplementedError
718
+
719
+ @property
720
+ def is_mobile(self):
721
+ return NotImplementedError
722
+
723
+ @property
724
+ def ee_ft_integral(self):
725
+ """
726
+ Returns:
727
+ dict: each arm-specific entry specifies the integral over time of the applied ee force-torque for that arm
728
+ """
729
+ vals = {}
730
+ for arm in self.arms:
731
+ vals[arm] = np.abs((1.0 / self.control_freq) * self.recent_ee_forcetorques[arm].average)
732
+ return vals
733
+
734
+ @property
735
+ def ee_force(self):
736
+ """
737
+ Returns:
738
+ dict: each arm-specific entry specifies the force applied at the force sensor at the robot arm's eef
739
+ """
740
+ vals = {}
741
+ for arm in self.arms:
742
+ vals[arm] = self.get_sensor_measurement(self.gripper[arm].important_sensors["force_ee"])
743
+ return vals
744
+
745
+ @property
746
+ def ee_torque(self):
747
+ """
748
+ Returns:
749
+ dict: each arm-specific entry specifies the torque applied at the torque sensor at the robot arm's eef
750
+ """
751
+ vals = {}
752
+ for arm in self.arms:
753
+ vals[arm] = self.get_sensor_measurement(self.gripper[arm].important_sensors["torque_ee"])
754
+ return vals
755
+
756
+ @property
757
+ def _hand_pose(self):
758
+ """
759
+ Returns:
760
+ dict: each arm-specific entry specifies the eef pose in base frame of robot.
761
+ """
762
+ vals = {}
763
+ for arm in self.arms:
764
+ vals[arm] = self.pose_in_base_from_name(self.robot_model.eef_name[arm])
765
+ return vals
766
+
767
+ @property
768
+ def _hand_quat(self):
769
+ """
770
+ Returns:
771
+ dict: each arm-specific entry specifies the eef quaternion in base frame of robot.
772
+ """
773
+ vals = {}
774
+ orns = self._hand_orn
775
+ for arm in self.arms:
776
+ vals[arm] = T.mat2quat(orns[arm])
777
+ return vals
778
+
779
+ @property
780
+ def _hand_total_velocity(self):
781
+ """
782
+ Returns:
783
+ dict: each arm-specific entry specifies the total eef velocity (linear + angular) in the base frame
784
+ as a numpy array of shape (6,)
785
+ """
786
+ vals = {}
787
+ for arm in self.arms:
788
+ # Determine correct start, end points based on arm
789
+ (start, end) = (None, self._joint_split_idx) if arm == "right" else (self._joint_split_idx, None)
790
+
791
+ # Use jacobian to translate joint velocities to end effector velocities.
792
+ Jp = self.sim.data.get_body_jacp(self.robot_model.eef_name[arm]).reshape((3, -1))
793
+ Jp_joint = Jp[:, self._ref_joint_vel_indexes[start:end]]
794
+
795
+ Jr = self.sim.data.get_body_jacr(self.robot_model.eef_name[arm]).reshape((3, -1))
796
+ Jr_joint = Jr[:, self._ref_joint_vel_indexes[start:end]]
797
+
798
+ eef_lin_vel = Jp_joint.dot(self._joint_velocities)
799
+ eef_rot_vel = Jr_joint.dot(self._joint_velocities)
800
+ vals[arm] = np.concatenate([eef_lin_vel, eef_rot_vel])
801
+ return vals
802
+
803
+ @property
804
+ def _hand_pos(self):
805
+ """
806
+ Returns:
807
+ dict: each arm-specific entry specifies the position of eef in base frame of robot.
808
+ """
809
+ vals = {}
810
+ poses = self._hand_pose
811
+ for arm in self.arms:
812
+ eef_pose_in_base = poses[arm]
813
+ vals[arm] = eef_pose_in_base[:3, 3]
814
+ return vals
815
+
816
+ @property
817
+ def _hand_orn(self):
818
+ """
819
+ Returns:
820
+ dict: each arm-specific entry specifies the orientation of eef in base frame of robot as a rotation matrix.
821
+ """
822
+ vals = {}
823
+ poses = self._hand_pose
824
+ for arm in self.arms:
825
+ eef_pose_in_base = poses[arm]
826
+ vals[arm] = eef_pose_in_base[:3, :3]
827
+ return vals
828
+
829
+ @property
830
+ def _hand_vel(self):
831
+ """
832
+ Returns:
833
+ dict: each arm-specific entry specifies the velocity of eef in base frame of robot.
834
+ """
835
+ vels = self._hand_total_velocity
836
+ for arm in self.arms:
837
+ vels[arm] = vels[arm][:3]
838
+ return vels
839
+
840
+ @property
841
+ def _hand_ang_vel(self):
842
+ """
843
+ Returns:
844
+ dict: each arm-specific entry specifies the angular velocity of eef in base frame of robot.
845
+ """
846
+ vels = self._hand_total_velocity
847
+ for arm in self.arms:
848
+ vels[arm] = vels[arm][3:]
849
+ return vels
850
+
851
+ def _load_arm_controllers(self):
852
+ urdf_loaded = False
853
+ # Load composite controller configs for both left and right arm
854
+ for arm in self.arms:
855
+ # Assert that the controller config is a dict file:
856
+ # NOTE: "type" must be one of: {JOINT_POSITION, JOINT_TORQUE, JOINT_VELOCITY,
857
+ # OSC_POSITION, OSC_POSE, IK_POSE}
858
+ assert (
859
+ type(self.part_controller_config[arm]) == dict
860
+ ), "Inputted controller config must be a dict! Instead, got type: {}".format(
861
+ type(self.part_controller_config[arm])
862
+ )
863
+
864
+ # Add to the controller dict additional relevant params:
865
+ # the robot name, mujoco sim, eef_name, actuator_range, joint_indexes, timestep (model) freq,
866
+ # policy (control) freq, and ndim (# joints)
867
+ self.part_controller_config[arm]["robot_name"] = self.name
868
+ self.part_controller_config[arm]["sim"] = self.sim
869
+ self.part_controller_config[arm]["ref_name"] = self.gripper[arm].important_sites["grip_site"]
870
+ self.part_controller_config[arm]["part_name"] = arm
871
+ self.part_controller_config[arm]["naming_prefix"] = self.robot_model.naming_prefix
872
+
873
+ self.part_controller_config[arm]["eef_rot_offset"] = self.eef_rot_offset[arm]
874
+ self.part_controller_config[arm]["ndim"] = self._joint_split_idx
875
+ self.part_controller_config[arm]["policy_freq"] = self.control_freq
876
+ self.part_controller_config[arm]["lite_physics"] = self.lite_physics
877
+ (start, end) = (None, self._joint_split_idx) if arm == "right" else (self._joint_split_idx, None)
878
+ self.part_controller_config[arm]["joint_indexes"] = {
879
+ "joints": self.arm_joint_indexes[start:end],
880
+ "qpos": self._ref_arm_joint_pos_indexes[start:end],
881
+ "qvel": self._ref_arm_joint_vel_indexes[start:end],
882
+ }
883
+ self.part_controller_config[arm]["actuator_range"] = (
884
+ self.torque_limits[0][start:end],
885
+ self.torque_limits[1][start:end],
886
+ )
887
+
888
+ # Only load urdf the first time this controller gets called
889
+ self.part_controller_config[arm]["load_urdf"] = True if not urdf_loaded else False
890
+ urdf_loaded = True
891
+
892
+ # # Instantiate the relevant controller
893
+
894
+ if self.has_gripper[arm]:
895
+ # Load gripper controllers
896
+ assert "gripper" in self.part_controller_config[arm], "Gripper controller config not found!"
897
+ gripper_name = self.get_gripper_name(arm)
898
+ self.part_controller_config[gripper_name] = {}
899
+ self.part_controller_config[gripper_name]["type"] = self.part_controller_config[arm]["gripper"]["type"]
900
+ self.part_controller_config[gripper_name]["use_action_scaling"] = self.part_controller_config[arm][
901
+ "gripper"
902
+ ].get("use_action_scaling", True)
903
+ self.part_controller_config[gripper_name]["robot_name"] = self.name
904
+ self.part_controller_config[gripper_name]["sim"] = self.sim
905
+ self.part_controller_config[gripper_name]["eef_name"] = self.gripper[arm].important_sites["grip_site"]
906
+ self.part_controller_config[gripper_name]["part_name"] = gripper_name
907
+ self.part_controller_config[gripper_name]["naming_prefix"] = self.robot_model.naming_prefix
908
+ self.part_controller_config[gripper_name]["ndim"] = self.gripper[arm].dof
909
+ self.part_controller_config[gripper_name]["policy_freq"] = self.control_freq
910
+ self.part_controller_config[gripper_name]["joint_indexes"] = {
911
+ "joints": self.gripper_joints[arm],
912
+ "actuators": self._ref_joint_gripper_actuator_indexes[arm],
913
+ "qpos": self._ref_gripper_joint_pos_indexes[arm],
914
+ "qvel": self._ref_gripper_joint_vel_indexes[arm],
915
+ }
916
+ low = self.sim.model.actuator_ctrlrange[self._ref_joint_gripper_actuator_indexes[arm], 0]
917
+ high = self.sim.model.actuator_ctrlrange[self._ref_joint_gripper_actuator_indexes[arm], 1]
918
+
919
+ self.part_controller_config[gripper_name]["actuator_range"] = (low, high)
920
+
921
+ def enable_parts(self, right=True, left=True):
922
+ self._enabled_parts = {
923
+ "right": right,
924
+ "right_gripper": right,
925
+ "left": left,
926
+ "left_gripper": left,
927
+ }
928
+
929
+ def enabled(self, part_name):
930
+ return self._enabled_parts[part_name]
931
+
932
+ def create_action_vector(self, action_dict):
933
+ """
934
+ A helper function that creates the action vector given a dictionary
935
+ """
936
+ # check if there's a composite controller and if the controller has a create_action_vector method
937
+ if self.composite_controller is not None and hasattr(self.composite_controller, "create_action_vector"):
938
+ return self.composite_controller.create_action_vector(action_dict)
939
+ else:
940
+ full_action_vector = np.zeros(self.action_dim)
941
+ for part_name, action_vector in action_dict.items():
942
+ if part_name not in self._action_split_indexes:
943
+ ROBOSUITE_DEFAULT_LOGGER.debug(f"{part_name} is not specified in the action space")
944
+ continue
945
+ start_idx, end_idx = self._action_split_indexes[part_name]
946
+ if end_idx - start_idx == 0:
947
+ # skipping not controlling actions
948
+ continue
949
+ assert len(action_vector) == (end_idx - start_idx), ROBOSUITE_DEFAULT_LOGGER.error(
950
+ f"Action vector for {part_name} is not the correct size. Expected {end_idx - start_idx} for {part_name}, got {len(action_vector)}"
951
+ )
952
+ full_action_vector[start_idx:end_idx] = action_vector
953
+ return full_action_vector
954
+
955
+ def print_action_info(self):
956
+ if self.composite_controller is not None and hasattr(self.composite_controller, "print_action_info"):
957
+ self.composite_controller.print_action_info()
958
+ return
959
+ action_index_info = []
960
+ action_dim_info = []
961
+ for part_name, (start_idx, end_idx) in self._action_split_indexes.items():
962
+ action_dim_info.append(f"{part_name}: {(end_idx - start_idx)} dim")
963
+ action_index_info.append(f"{part_name}: {start_idx}:{end_idx}")
964
+
965
+ action_dim_info_str = ", ".join(action_dim_info)
966
+ ROBOSUITE_DEFAULT_LOGGER.info(f"Action Dimensions: [{action_dim_info_str}]")
967
+
968
+ action_index_info_str = ", ".join(action_index_info)
969
+ ROBOSUITE_DEFAULT_LOGGER.info(f"Action Indices: [{action_index_info_str}]")
970
+
971
+ def print_action_info_dict(self):
972
+ if self.composite_controller is not None and hasattr(self.composite_controller, "print_action_info_dict"):
973
+ self.composite_controller.print_action_info_dict(name=self.name)
974
+ return
975
+ info_dict = {}
976
+ info_dict["Action Dimension"] = self.action_dim
977
+ info_dict.update(dict(self._action_split_indexes))
978
+
979
+ info_dict_str = f"\nAction Info for {self.name}:\n\n{json.dumps(dict(info_dict), indent=4)}"
980
+ ROBOSUITE_DEFAULT_LOGGER.info(info_dict_str)
981
+
982
+ def get_gripper_name(self, arm):
983
+ return f"{arm}_gripper"
984
+
985
+ def has_part(self, part_name):
986
+ if part_name in self._ref_joints_indexes_dict.keys() and len(self._ref_joints_indexes_dict[part_name]) > 0:
987
+ return True
988
+ else:
989
+ return False
990
+
991
+ @property
992
+ def _joint_split_idx(self):
993
+ """
994
+ Returns:
995
+ int: the index that correctly splits the right arm from the left arm joints
996
+ """
997
+ return int(len(self.robot_arm_joints) / len(self.arms))
998
+
999
+ @property
1000
+ def part_controllers(self):
1001
+ """
1002
+ Controller dictionary for the robot
1003
+
1004
+ Returns:
1005
+ dict: Controller dictionary for the robot
1006
+ """
1007
+ return self.composite_controller.part_controllers
third_party/robosuite/robosuite/robots/wheeled_robot.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import os
3
+ from collections import OrderedDict
4
+
5
+ import numpy as np
6
+
7
+ import robosuite.utils.transform_utils as T
8
+ from robosuite.controllers import composite_controller_factory
9
+ from robosuite.robots.mobile_robot import MobileRobot
10
+ from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER
11
+
12
+
13
+ class WheeledRobot(MobileRobot):
14
+ """
15
+ Initializes a robot with a wheeled base.
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ robot_type: str,
21
+ idn=0,
22
+ composite_controller_config=None,
23
+ initial_qpos=None,
24
+ initialization_noise=None,
25
+ base_type="default",
26
+ gripper_type="default",
27
+ control_freq=20,
28
+ lite_physics=True,
29
+ ):
30
+ super().__init__(
31
+ robot_type=robot_type,
32
+ idn=idn,
33
+ composite_controller_config=composite_controller_config,
34
+ initial_qpos=initial_qpos,
35
+ initialization_noise=initialization_noise,
36
+ base_type=base_type,
37
+ gripper_type=gripper_type,
38
+ control_freq=control_freq,
39
+ lite_physics=lite_physics,
40
+ )
41
+
42
+ def _load_controller(self):
43
+ """
44
+ Loads controller to be used for dynamic trajectories
45
+ """
46
+ # Flag for loading urdf once (only applicable for IK controllers)
47
+ self.composite_controller = composite_controller_factory(
48
+ type=self.composite_controller_config.get("type", "BASIC"),
49
+ sim=self.sim,
50
+ robot_model=self.robot_model,
51
+ grippers={self.get_gripper_name(arm): self.gripper[arm] for arm in self.arms},
52
+ )
53
+
54
+ self._load_arm_controllers()
55
+
56
+ # default base, torso, and head controllers are inherited from MobileRobot
57
+ self._load_base_controller()
58
+
59
+ self._load_head_controller()
60
+ self._load_torso_controller()
61
+
62
+ self._postprocess_part_controller_config()
63
+ self.composite_controller.load_controller_config(
64
+ self.part_controller_config,
65
+ self.composite_controller_config.get("composite_controller_specific_configs", {}),
66
+ )
67
+ self.enable_parts()
68
+
69
+ def load_model(self):
70
+ """
71
+ Loads robot and optionally add grippers.
72
+ """
73
+ # First, run the superclass method to load the relevant model
74
+ super().load_model()
75
+
76
+ def reset(self, deterministic=False):
77
+ """
78
+ Sets initial pose of arm and grippers. Overrides gripper joint configuration if we're using a
79
+ deterministic reset (e.g.: hard reset from xml file)
80
+
81
+ Args:
82
+ deterministic (bool): If true, will not randomize initializations within the sim
83
+ """
84
+ # First, run the superclass method to reset the position and controller
85
+ super().reset(deterministic)
86
+
87
+ def setup_references(self):
88
+ """
89
+ Sets up necessary reference for robots, grippers, and objects.
90
+
91
+ Note that this should get called during every reset from the environment
92
+ """
93
+ # All the references are by default set up in the superclass method
94
+ super().setup_references()
95
+
96
+ def control(self, action, policy_step=False):
97
+ """
98
+ Actuate the robot with the
99
+ passed joint velocities and gripper control.
100
+
101
+ Args:
102
+ action (np.array): The control to apply to the robot. The first @self.robot_model.dof dimensions should
103
+ be the desired normalized joint velocities and if the robot has a gripper, the next @self.gripper.dof
104
+ dimensions should be actuation controls for the gripper.
105
+
106
+ :NOTE: Assumes inputted actions are of form:
107
+ [right_arm_control, right_gripper_control, left_arm_control, left_gripper_control]
108
+
109
+ policy_step (bool): Whether a new policy step (action) is being taken
110
+
111
+ Raises:
112
+ AssertionError: [Invalid action dimension]
113
+ """
114
+ # clip actions into valid range
115
+ assert len(action) == self.action_dim, "environment got invalid action dimension -- expected {}, got {}".format(
116
+ self.action_dim, len(action)
117
+ )
118
+
119
+ # self.composite_controller.update_state() # remove this for now, messes up base velocity calculation
120
+ if policy_step:
121
+ self.composite_controller.set_goal(action)
122
+
123
+ applied_action_dict = self.composite_controller.run_controller(self._enabled_parts)
124
+ for part_name, applied_action in applied_action_dict.items():
125
+ applied_action_low = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[part_name], 0]
126
+ applied_action_high = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[part_name], 1]
127
+ applied_action = np.clip(applied_action, applied_action_low, applied_action_high)
128
+ self.sim.data.ctrl[self._ref_actuators_indexes_dict[part_name]] = applied_action
129
+
130
+ # If this is a policy step, also update buffers holding recent values of interest
131
+ if policy_step:
132
+ # Update proprioceptive values
133
+ self.recent_qpos.push(self._joint_positions)
134
+ self.recent_actions.push(action)
135
+ self.recent_torques.push(self.torques)
136
+
137
+ for arm in self.arms:
138
+ controller = self.part_controllers.get(arm, None)
139
+ if controller is None:
140
+ # TODO: enable buffer update for whole body controllers not using individual arm controllers
141
+ continue
142
+
143
+ # Update arm-specific proprioceptive values
144
+ self.recent_ee_forcetorques[arm].push(np.concatenate((self.ee_force[arm], self.ee_torque[arm])))
145
+ self.recent_ee_pose[arm].push(np.concatenate((controller.ref_pos, T.mat2quat(controller.ref_ori_mat))))
146
+ self.recent_ee_vel[arm].push(np.concatenate((controller.ref_pos_vel, controller.ref_ori_vel)))
147
+
148
+ # Estimation of eef acceleration (averaged derivative of recent velocities)
149
+ self.recent_ee_vel_buffer[arm].push(np.concatenate((controller.ref_pos_vel, controller.ref_ori_vel)))
150
+ diffs = np.vstack(
151
+ [
152
+ self.recent_ee_acc[arm].current,
153
+ self.control_freq * np.diff(self.recent_ee_vel_buffer[arm].buf, axis=0),
154
+ ]
155
+ )
156
+ ee_acc = np.array([np.convolve(col, np.ones(10) / 10.0, mode="valid")[0] for col in diffs.transpose()])
157
+ self.recent_ee_acc[arm].push(ee_acc)
158
+
159
+ def setup_observables(self):
160
+ """
161
+ Sets up observables to be used for this robot
162
+
163
+ Returns:
164
+ OrderedDict: Dictionary mapping observable names to its corresponding Observable object
165
+ """
166
+ # Get general robot observables first
167
+ observables = super().setup_observables()
168
+
169
+ return observables
170
+
171
+ @property
172
+ def action_limits(self):
173
+ """
174
+ Action lower/upper limits per dimension.
175
+
176
+ Returns:
177
+ 2-tuple:
178
+
179
+ - (np.array) minimum (low) action values
180
+ - (np.array) maximum (high) action values
181
+ """
182
+ return self.composite_controller.action_limits
third_party/robosuite/robosuite/scripts/browse_mjcf_model.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Visualize MJCF models.
2
+
3
+ Loads MJCF XML models from file and renders it on screen.
4
+
5
+ Example:
6
+ $ python browse_mjcf_model.py --filepath ../models/assets/arenas/table_arena.xml
7
+ """
8
+
9
+ import argparse
10
+ import os
11
+
12
+ import mujoco
13
+ from mujoco import viewer
14
+ from pynput import keyboard
15
+
16
+ import robosuite as suite
17
+ from robosuite.utils.binding_utils import MjSim
18
+
19
+ DEFAULT_FREE_CAM = {
20
+ "lookat": [0, 0, 0.7],
21
+ "distance": 1.5,
22
+ "azimuth": 180,
23
+ "elevation": -20,
24
+ }
25
+
26
+ continue_running = True
27
+
28
+
29
+ def on_press(key):
30
+ global continue_running
31
+ try:
32
+ if key == keyboard.Key.esc:
33
+ continue_running = False
34
+ except AttributeError:
35
+ pass
36
+
37
+
38
+ if __name__ == "__main__":
39
+
40
+ arena_file = os.path.join(suite.models.assets_root, "arenas/pegs_arena.xml")
41
+
42
+ parser = argparse.ArgumentParser()
43
+ parser.add_argument("--filepath", type=str, default=arena_file)
44
+ args = parser.parse_args()
45
+
46
+ print("Loading model from: {}".format(args.filepath))
47
+ model = mujoco.MjModel.from_xml_path(args.filepath)
48
+ sim = MjSim(model)
49
+
50
+ vwr = viewer.launch_passive(sim.model._model, sim.data._data, show_left_ui=False, show_right_ui=False)
51
+ vwr.cam.lookat = DEFAULT_FREE_CAM["lookat"]
52
+ vwr.cam.distance = DEFAULT_FREE_CAM["distance"]
53
+ vwr.cam.azimuth = DEFAULT_FREE_CAM["azimuth"]
54
+ vwr.cam.elevation = DEFAULT_FREE_CAM["elevation"]
55
+
56
+ vwr.sync()
57
+
58
+ listener = keyboard.Listener(on_press=on_press)
59
+ listener.start()
60
+ print("Press 'ESC' to exit.")
61
+
62
+ while continue_running:
63
+ pass
64
+
65
+ vwr.close()
66
+ listener.stop()
67
+ listener.join()
third_party/robosuite/robosuite/scripts/check_custom_robot_model.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from xml.etree import ElementTree as ET
3
+
4
+ from robosuite.controllers.composite.composite_controller_factory import load_composite_controller_config
5
+ from robosuite.robots.robot import Robot
6
+ from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER as logger
7
+
8
+
9
+ def check_xml_definition(root):
10
+ logger.info(f"Successfully loaded the xml file of robot model.")
11
+
12
+ # get all joints
13
+ world_body = root.find(".//worldbody")
14
+ parts_dict = {}
15
+ added_joints = []
16
+ for part_name in ["torso", "head", "leg", "gripper", "base"]:
17
+ parts_dict[part_name] = []
18
+ for joint in world_body.findall(".//joint"):
19
+ if part_name in joint.attrib["name"] and joint.attrib["name"] not in added_joints:
20
+ parts_dict[part_name].append(joint.attrib["name"])
21
+ added_joints.append(joint.attrib["name"])
22
+ parts_dict["arm"] = []
23
+
24
+ print(len(world_body.findall(".//joint")))
25
+ for joint in world_body.findall(".//joint"):
26
+ is_non_arm_part = False
27
+ for non_arm_part_name in ["torso", "head", "leg", "gripper", "base"]:
28
+ if non_arm_part_name in joint.attrib["name"]:
29
+ is_non_arm_part = True
30
+ break
31
+ if not is_non_arm_part:
32
+ parts_dict["arm"].append(joint.attrib["name"])
33
+ total_counted_joints = sum([len(parts_dict[part_name]) for part_name in parts_dict.keys()])
34
+ if total_counted_joints != len(world_body.findall(".//joint")):
35
+ logger.error(f"Counted {total_counted_joints} joints, but found {len(world_body.findall('.//joint'))} joints")
36
+ else:
37
+ logger.info(f"Your joint definition aligns with robosuite convention.")
38
+ # remove empty list entries
39
+ parts_dict = {part_name: joints for part_name, joints in parts_dict.items() if joints}
40
+ print(f" • Robosuite will be able to detect the following body parts: {list(parts_dict.keys())}")
41
+ print(" • For each body part, you have defined the following joints:")
42
+ for part_name in parts_dict.keys():
43
+ print(f" • {part_name} - {len(parts_dict[part_name])} joints: {parts_dict[part_name]}")
44
+ return parts_dict
45
+
46
+
47
+ def check_registered_robot(robot_name):
48
+
49
+ print(f"Loading {robot_name} ...")
50
+ controller_config = load_composite_controller_config("BASIC")
51
+ robot = Robot(robot_type=robot_name, composite_controller_config=controller_config, gripper_type=None)
52
+ logger.info(f"Succcessfully found the defined robot")
53
+
54
+ robot.load_model()
55
+ robot_model = robot.robot_model
56
+
57
+ root = robot_model.tree.getroot()
58
+ parts_dict = check_xml_definition(root)
59
+
60
+ if parts_dict.get("arm") is not None and parts_dict["arm"] != []:
61
+ # checking the order of arm joints defined.
62
+ arm_joint_names = parts_dict["arm"]
63
+ first_arm_joint_name = arm_joint_names[0]
64
+ if "l_" in first_arm_joint_name or "left" in first_arm_joint_name:
65
+ logger.warning(
66
+ "Incorrect order of the arm joints. THe arm joints needs to be defined first for the right arm and then for the left arm."
67
+ )
68
+
69
+ # check if the body for mounting exists
70
+ num_arms = len(robot.arms)
71
+
72
+ mount_names = [robot.robot_model._eef_name[name] for name in robot.robot_model._eef_name]
73
+ world_body = root.find(".//worldbody")
74
+ for mount_name in mount_names[:num_arms]:
75
+ # find the body name of mount_name in the worldbody
76
+ mount_body = world_body.find(f".//body[@name='robot0_{mount_name}']")
77
+ if mount_body is None:
78
+ logger.error(
79
+ f"Error: No body named '{mount_name}' found in the worldbody. Please make sure you have defined the body for mounting the arm."
80
+ )
81
+ exit(1)
82
+ print(" • Grippers will be mounted on the following bodies ", mount_names[:num_arms])
83
+
84
+ logger.warning(
85
+ "Attention!!! Make sure your definition of the motors for arms are in the same order as the joints defined. This program does not check on this item."
86
+ )
87
+
88
+
89
+ if __name__ == "__main__":
90
+ parser = argparse.ArgumentParser()
91
+ parser.add_argument("--robot", type=str, default=None)
92
+ parser.add_argument("--robot-xml-file", type=str, default=None)
93
+ args = parser.parse_args()
94
+ if args.robot is None and args.robot_xml_file is None:
95
+ logger.error("Please provide either the robot name or the robot xml file.")
96
+ exit(1)
97
+ if args.robot is not None:
98
+ check_registered_robot(args.robot)
99
+
100
+ if args.robot_xml_file is not None:
101
+ etree_root = ET.parse(args.robot_xml_file)
102
+ parts_dict = check_xml_definition(etree_root)
103
+ arm_joint_names = parts_dict["arm"]
104
+ first_arm_joint_name = arm_joint_names[0]
105
+ if "l_" in first_arm_joint_name or "left" in first_arm_joint_name:
106
+ logger.warning(
107
+ "Incorrect order of the arm joints. THe arm joints needs to be defined first for the right arm and then for the left arm."
108
+ )
third_party/robosuite/robosuite/scripts/collect_human_demonstrations.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A script to collect a batch of human demonstrations.
3
+
4
+ The demonstrations can be played back using the `playback_demonstrations_from_hdf5.py` script.
5
+ """
6
+
7
+ import argparse
8
+ import datetime
9
+ import json
10
+ import os
11
+ import time
12
+ from glob import glob
13
+
14
+ import h5py
15
+ import numpy as np
16
+
17
+ import robosuite as suite
18
+ from robosuite.controllers import load_composite_controller_config
19
+ from robosuite.controllers.composite.composite_controller import WholeBody
20
+ from robosuite.wrappers import DataCollectionWrapper, VisualizationWrapper
21
+
22
+
23
+ def collect_human_trajectory(env, device, arm, max_fr):
24
+ """
25
+ Use the device (keyboard or SpaceNav 3D mouse) to collect a demonstration.
26
+ The rollout trajectory is saved to files in npz format.
27
+ Modify the DataCollectionWrapper wrapper to add new fields or change data formats.
28
+
29
+ Args:
30
+ env (MujocoEnv): environment to control
31
+ device (Device): to receive controls from the device
32
+ arms (str): which arm to control (eg bimanual) 'right' or 'left'
33
+ max_fr (int): if specified, pause the simulation whenever simulation runs faster than max_fr
34
+ """
35
+
36
+ env.reset()
37
+ env.render()
38
+
39
+ task_completion_hold_count = -1 # counter to collect 10 timesteps after reaching goal
40
+ device.start_control()
41
+
42
+ for robot in env.robots:
43
+ robot.print_action_info_dict()
44
+
45
+ # Keep track of prev gripper actions when using since they are position-based and must be maintained when arms switched
46
+ all_prev_gripper_actions = [
47
+ {
48
+ f"{robot_arm}_gripper": np.repeat([0], robot.gripper[robot_arm].dof)
49
+ for robot_arm in robot.arms
50
+ if robot.gripper[robot_arm].dof > 0
51
+ }
52
+ for robot in env.robots
53
+ ]
54
+
55
+ # Loop until we get a reset from the input or the task completes
56
+ while True:
57
+ start = time.time()
58
+
59
+ # Set active robot
60
+ active_robot = env.robots[device.active_robot]
61
+
62
+ # Get the newest action
63
+ input_ac_dict = device.input2action()
64
+
65
+ # If action is none, then this a reset so we should break
66
+ if input_ac_dict is None:
67
+ break
68
+
69
+ from copy import deepcopy
70
+
71
+ action_dict = deepcopy(input_ac_dict) # {}
72
+ # set arm actions
73
+ for arm in active_robot.arms:
74
+ if isinstance(active_robot.composite_controller, WholeBody): # input type passed to joint_action_policy
75
+ controller_input_type = active_robot.composite_controller.joint_action_policy.input_type
76
+ else:
77
+ controller_input_type = active_robot.part_controllers[arm].input_type
78
+
79
+ if controller_input_type == "delta":
80
+ action_dict[arm] = input_ac_dict[f"{arm}_delta"]
81
+ elif controller_input_type == "absolute":
82
+ action_dict[arm] = input_ac_dict[f"{arm}_abs"]
83
+ else:
84
+ raise ValueError
85
+
86
+ # Maintain gripper state for each robot but only update the active robot with action
87
+ env_action = [robot.create_action_vector(all_prev_gripper_actions[i]) for i, robot in enumerate(env.robots)]
88
+ env_action[device.active_robot] = active_robot.create_action_vector(action_dict)
89
+ env_action = np.concatenate(env_action)
90
+ for gripper_ac in all_prev_gripper_actions[device.active_robot]:
91
+ all_prev_gripper_actions[device.active_robot][gripper_ac] = action_dict[gripper_ac]
92
+
93
+ env.step(env_action)
94
+ env.render()
95
+
96
+ # Also break if we complete the task
97
+ if task_completion_hold_count == 0:
98
+ break
99
+
100
+ # state machine to check for having a success for 10 consecutive timesteps
101
+ if env._check_success():
102
+ if task_completion_hold_count > 0:
103
+ task_completion_hold_count -= 1 # latched state, decrement count
104
+ else:
105
+ task_completion_hold_count = 10 # reset count on first success timestep
106
+ else:
107
+ task_completion_hold_count = -1 # null the counter if there's no success
108
+
109
+ # limit frame rate if necessary
110
+ if max_fr is not None:
111
+ elapsed = time.time() - start
112
+ diff = 1 / max_fr - elapsed
113
+ if diff > 0:
114
+ time.sleep(diff)
115
+
116
+ # cleanup for end of data collection episodes
117
+ env.close()
118
+
119
+
120
+ def gather_demonstrations_as_hdf5(directory, out_dir, env_info):
121
+ """
122
+ Gathers the demonstrations saved in @directory into a
123
+ single hdf5 file.
124
+
125
+ The strucure of the hdf5 file is as follows.
126
+
127
+ data (group)
128
+ date (attribute) - date of collection
129
+ time (attribute) - time of collection
130
+ repository_version (attribute) - repository version used during collection
131
+ env (attribute) - environment name on which demos were collected
132
+
133
+ demo1 (group) - every demonstration has a group
134
+ model_file (attribute) - model xml string for demonstration
135
+ states (dataset) - flattened mujoco states
136
+ actions (dataset) - actions applied during demonstration
137
+
138
+ demo2 (group)
139
+ ...
140
+
141
+ Args:
142
+ directory (str): Path to the directory containing raw demonstrations.
143
+ out_dir (str): Path to where to store the hdf5 file.
144
+ env_info (str): JSON-encoded string containing environment information,
145
+ including controller and robot info
146
+ """
147
+
148
+ hdf5_path = os.path.join(out_dir, "demo.hdf5")
149
+ f = h5py.File(hdf5_path, "w")
150
+
151
+ # store some metadata in the attributes of one group
152
+ grp = f.create_group("data")
153
+
154
+ num_eps = 0
155
+ env_name = None # will get populated at some point
156
+
157
+ for ep_directory in os.listdir(directory):
158
+
159
+ state_paths = os.path.join(directory, ep_directory, "state_*.npz")
160
+ states = []
161
+ actions = []
162
+ success = False
163
+
164
+ for state_file in sorted(glob(state_paths)):
165
+ dic = np.load(state_file, allow_pickle=True)
166
+ env_name = str(dic["env"])
167
+
168
+ states.extend(dic["states"])
169
+ for ai in dic["action_infos"]:
170
+ actions.append(ai["actions"])
171
+ success = success or dic["successful"]
172
+
173
+ if len(states) == 0:
174
+ continue
175
+
176
+ # Add only the successful demonstration to dataset
177
+ if success:
178
+ print("Demonstration is successful and has been saved")
179
+ # Delete the last state. This is because when the DataCollector wrapper
180
+ # recorded the states and actions, the states were recorded AFTER playing that action,
181
+ # so we end up with an extra state at the end.
182
+ del states[-1]
183
+ assert len(states) == len(actions)
184
+
185
+ num_eps += 1
186
+ ep_data_grp = grp.create_group("demo_{}".format(num_eps))
187
+
188
+ # store model xml as an attribute
189
+ xml_path = os.path.join(directory, ep_directory, "model.xml")
190
+ with open(xml_path, "r") as f:
191
+ xml_str = f.read()
192
+ ep_data_grp.attrs["model_file"] = xml_str
193
+
194
+ # write datasets for states and actions
195
+ ep_data_grp.create_dataset("states", data=np.array(states))
196
+ ep_data_grp.create_dataset("actions", data=np.array(actions))
197
+ else:
198
+ print("Demonstration is unsuccessful and has NOT been saved")
199
+
200
+ # write dataset attributes (metadata)
201
+ now = datetime.datetime.now()
202
+ grp.attrs["date"] = "{}-{}-{}".format(now.month, now.day, now.year)
203
+ grp.attrs["time"] = "{}:{}:{}".format(now.hour, now.minute, now.second)
204
+ grp.attrs["repository_version"] = suite.__version__
205
+ grp.attrs["env"] = env_name
206
+ grp.attrs["env_info"] = env_info
207
+
208
+ f.close()
209
+
210
+
211
+ if __name__ == "__main__":
212
+ # Arguments
213
+ parser = argparse.ArgumentParser()
214
+ parser.add_argument(
215
+ "--directory",
216
+ type=str,
217
+ default=os.path.join(suite.models.assets_root, "demonstrations_private"),
218
+ )
219
+ parser.add_argument("--environment", type=str, default="Lift")
220
+ parser.add_argument("--robots", nargs="+", type=str, default="Panda", help="Which robot(s) to use in the env")
221
+ parser.add_argument(
222
+ "--config", type=str, default="default", help="Specified environment configuration if necessary"
223
+ )
224
+ parser.add_argument("--arm", type=str, default="right", help="Which arm to control (eg bimanual) 'right' or 'left'")
225
+ parser.add_argument("--camera", type=str, default="agentview", help="Which camera to use for collecting demos")
226
+ parser.add_argument(
227
+ "--controller",
228
+ type=str,
229
+ default=None,
230
+ help="Choice of controller. Can be generic (eg. 'BASIC' or 'WHOLE_BODY_MINK_IK') or json file (see robosuite/controllers/config for examples)",
231
+ )
232
+ parser.add_argument("--device", type=str, default="keyboard")
233
+ parser.add_argument("--pos-sensitivity", type=float, default=1.0, help="How much to scale position user inputs")
234
+ parser.add_argument("--rot-sensitivity", type=float, default=1.0, help="How much to scale rotation user inputs")
235
+ parser.add_argument(
236
+ "--renderer",
237
+ type=str,
238
+ default="mjviewer",
239
+ help="Use Mujoco's builtin interactive viewer (mjviewer) or OpenCV viewer (mujoco)",
240
+ )
241
+ parser.add_argument(
242
+ "--max_fr",
243
+ default=20,
244
+ type=int,
245
+ help="Sleep when simluation runs faster than specified frame rate; 20 fps is real time.",
246
+ )
247
+ args = parser.parse_args()
248
+
249
+ # Get controller config
250
+ controller_config = load_composite_controller_config(
251
+ controller=args.controller,
252
+ robot=args.robots[0],
253
+ )
254
+
255
+ if controller_config["type"] == "WHOLE_BODY_MINK_IK":
256
+ # mink-speicific import. requires installing mink
257
+ from robosuite.examples.third_party_controller.mink_controller import WholeBodyMinkIK
258
+
259
+ # Create argument configuration
260
+ config = {
261
+ "env_name": args.environment,
262
+ "robots": args.robots,
263
+ "controller_configs": controller_config,
264
+ }
265
+
266
+ # Check if we're using a multi-armed environment and use env_configuration argument if so
267
+ if "TwoArm" in args.environment:
268
+ config["env_configuration"] = args.config
269
+
270
+ # Create environment
271
+ env = suite.make(
272
+ **config,
273
+ has_renderer=True,
274
+ renderer=args.renderer,
275
+ has_offscreen_renderer=False,
276
+ render_camera=args.camera,
277
+ ignore_done=True,
278
+ use_camera_obs=False,
279
+ reward_shaping=True,
280
+ control_freq=20,
281
+ )
282
+
283
+ # Wrap this with visualization wrapper
284
+ env = VisualizationWrapper(env)
285
+
286
+ # Grab reference to controller config and convert it to json-encoded string
287
+ env_info = json.dumps(config)
288
+
289
+ # wrap the environment with data collection wrapper
290
+ tmp_directory = "/tmp/{}".format(str(time.time()).replace(".", "_"))
291
+ env = DataCollectionWrapper(env, tmp_directory)
292
+
293
+ # initialize device
294
+ if args.device == "keyboard":
295
+ from robosuite.devices import Keyboard
296
+
297
+ device = Keyboard(env=env, pos_sensitivity=args.pos_sensitivity, rot_sensitivity=args.rot_sensitivity)
298
+ elif args.device == "spacemouse":
299
+ from robosuite.devices import SpaceMouse
300
+
301
+ device = SpaceMouse(env=env, pos_sensitivity=args.pos_sensitivity, rot_sensitivity=args.rot_sensitivity)
302
+ elif args.device == "mjgui":
303
+ assert args.renderer == "mjviewer", "Mocap is only supported with the mjviewer renderer"
304
+ from robosuite.devices.mjgui import MJGUI
305
+
306
+ device = MJGUI(env=env)
307
+ else:
308
+ raise Exception("Invalid device choice: choose either 'keyboard' or 'spacemouse'.")
309
+
310
+ # make a new timestamped directory
311
+ t1, t2 = str(time.time()).split(".")
312
+ new_dir = os.path.join(args.directory, "{}_{}".format(t1, t2))
313
+ os.makedirs(new_dir)
314
+
315
+ # collect demonstrations
316
+ while True:
317
+ collect_human_trajectory(env, device, args.arm, args.max_fr)
318
+ gather_demonstrations_as_hdf5(tmp_directory, new_dir, env_info)
third_party/robosuite/robosuite/scripts/compile_mjcf_model.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Loads a raw mjcf file and saves a compiled mjcf file.
2
+
3
+ This avoids mujoco-py from complaining about .urdf extension.
4
+ Also allows assets to be compiled properly.
5
+
6
+ Example:
7
+ $ python compile_mjcf_model.py source_mjcf.xml target_mjcf.xml
8
+ """
9
+
10
+ import os
11
+ import sys
12
+ from shutil import copyfile
13
+
14
+ import mujoco
15
+
16
+
17
+ def print_usage():
18
+ print("""python compile_mjcf_model.py input_file output_file""")
19
+
20
+
21
+ if __name__ == "__main__":
22
+
23
+ if len(sys.argv) != 3:
24
+ print_usage()
25
+ exit(0)
26
+
27
+ input_file = sys.argv[1]
28
+ output_file = sys.argv[2]
29
+ input_folder = os.path.dirname(input_file)
30
+
31
+ tempfile = os.path.join(input_folder, ".robosuite_temp_model.xml")
32
+ copyfile(input_file, tempfile)
33
+
34
+ model = mujoco.MjModel.from_xml_path(tempfile)
35
+ xml_string = model.get_xml()
36
+ with open(output_file, "w") as f:
37
+ f.write(xml_string)
38
+
39
+ os.remove(tempfile)
third_party/robosuite/robosuite/scripts/internal/view_robot_initialization.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ import numpy as np
4
+
5
+ import robosuite as suite
6
+ from robosuite.controllers import load_composite_controller_config
7
+ from robosuite.robots import ROBOT_CLASS_MAPPING
8
+ from robosuite.wrappers import VisualizationWrapper
9
+
10
+
11
+ def bimanual_check(robot):
12
+ bimanual_robots = ["Baxter", "Tiago", "GR1", "G1", "H1", "PR2", "Yumi", "Aloha"]
13
+ for br in bimanual_robots:
14
+ if br in robot:
15
+ return True
16
+ return False
17
+
18
+
19
+ if __name__ == "__main__":
20
+
21
+ parser = argparse.ArgumentParser()
22
+ parser.add_argument("--environment", type=str, default="Lift")
23
+ parser.add_argument("--robots", type=str, nargs="+", default=ROBOT_CLASS_MAPPING.keys())
24
+ parser.add_argument("--controller", type=str, default="BASIC", help="Choice of controller. Can be 'ik' or 'osc'")
25
+ args = parser.parse_args()
26
+
27
+ for robot in args.robots:
28
+ print(f"{robot} demo...")
29
+
30
+ # Check if we're using a multi-armed environment
31
+ if "TwoArm" in args.environment and not bimanual_check(robot):
32
+ robots = [robot, robot]
33
+ else:
34
+ robots = [robot]
35
+
36
+ # Get controller config
37
+ controller_config = load_composite_controller_config(
38
+ controller=args.controller,
39
+ robot=robot,
40
+ )
41
+
42
+ # Create argument configuration
43
+ config = {
44
+ "env_name": args.environment,
45
+ "robots": robots,
46
+ "controller_configs": controller_config,
47
+ }
48
+
49
+ # Create environment
50
+ env = suite.make(
51
+ **config,
52
+ has_renderer=True,
53
+ has_offscreen_renderer=False,
54
+ renderer="mjviewer",
55
+ render_camera="free",
56
+ ignore_done=True,
57
+ use_camera_obs=False,
58
+ reward_shaping=True,
59
+ control_freq=20,
60
+ hard_reset=False,
61
+ )
62
+
63
+ # Wrap this environment in a visualization wrapper
64
+ env = VisualizationWrapper(env, indicator_configs=None)
65
+
66
+ env.reset()
67
+ low, high = env.action_spec
68
+
69
+ for i in range(200):
70
+ action = np.zeros(len(low))
71
+ env.step(action)
72
+ env.render()
73
+
74
+ env.close()
third_party/robosuite/robosuite/scripts/make_reset_video.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Convenience script to make a video out of initial environment
3
+ configurations. This can be a useful debugging tool to understand
4
+ what different sampled environment configurations look like.
5
+ """
6
+
7
+ import argparse
8
+
9
+ import imageio
10
+ import numpy as np
11
+
12
+ import robosuite as suite
13
+ from robosuite.utils.input_utils import *
14
+
15
+ if __name__ == "__main__":
16
+ parser = argparse.ArgumentParser()
17
+
18
+ # camera to use for generating frames
19
+ parser.add_argument(
20
+ "--camera",
21
+ type=str,
22
+ default="agentview",
23
+ )
24
+
25
+ # number of frames in output video
26
+ parser.add_argument(
27
+ "--frames",
28
+ type=int,
29
+ default=10,
30
+ )
31
+
32
+ # path to output video
33
+ parser.add_argument(
34
+ "--output",
35
+ type=str,
36
+ default="reset.mp4",
37
+ )
38
+
39
+ args = parser.parse_args()
40
+ camera_name = args.camera
41
+ num_frames = args.frames
42
+ output_path = args.output
43
+
44
+ # Create dict to hold options that will be passed to env creation call
45
+ options = {}
46
+
47
+ # print welcome info
48
+ print("Welcome to robosuite v{}!".format(suite.__version__))
49
+ print(suite.__logo__)
50
+
51
+ # Choose environment and add it to options
52
+ options["env_name"] = choose_environment()
53
+
54
+ # If a multi-arm environment has been chosen, choose configuration and appropriate robot(s)
55
+ if "TwoArm" in options["env_name"]:
56
+ # Choose env config and add it to options
57
+ options["env_configuration"] = choose_multi_arm_config()
58
+
59
+ # If chosen configuration was bimanual, the corresponding robot must be Baxter. Else, have user choose robots
60
+ if options["env_configuration"] == "bimanual":
61
+ options["robots"] = "Baxter"
62
+ else:
63
+ options["robots"] = []
64
+
65
+ # Have user choose two robots
66
+ print("A multiple single-arm configuration was chosen.\n")
67
+
68
+ for i in range(2):
69
+ print("Please choose Robot {}...\n".format(i))
70
+ options["robots"].append(choose_robots(exclude_bimanual=True))
71
+
72
+ # Else, we simply choose a single (single-armed) robot to instantiate in the environment
73
+ else:
74
+ options["robots"] = choose_robots(exclude_bimanual=True)
75
+
76
+ # initialize the task
77
+ env = suite.make(
78
+ **options,
79
+ has_renderer=False,
80
+ has_offscreen_renderer=True,
81
+ ignore_done=True,
82
+ use_camera_obs=False,
83
+ control_freq=20,
84
+ )
85
+
86
+ # write a video
87
+ video_writer = imageio.get_writer(output_path, fps=5)
88
+ for i in range(num_frames):
89
+ env.reset()
90
+ video_img = env.sim.render(height=512, width=512, camera_name=camera_name)[::-1]
91
+ env.step(np.zeros_like(env.action_spec[0]))
92
+ video_writer.append_data(video_img)
93
+ video_writer.close()
third_party/robosuite/robosuite/scripts/playback_demonstrations_from_hdf5.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A convenience script to playback random demonstrations from
3
+ a set of demonstrations stored in a hdf5 file.
4
+
5
+ Arguments:
6
+ --folder (str): Path to demonstrations
7
+ --use-actions (optional): If this flag is provided, the actions are played back
8
+ through the MuJoCo simulator, instead of loading the simulator states
9
+ one by one.
10
+ --visualize-gripper (optional): If set, will visualize the gripper site
11
+
12
+ Example:
13
+ $ python playback_demonstrations_from_hdf5.py --folder ../models/assets/demonstrations/lift/
14
+ """
15
+
16
+ import argparse
17
+ import json
18
+ import os
19
+ import random
20
+
21
+ import h5py
22
+ import numpy as np
23
+
24
+ import robosuite
25
+
26
+ if __name__ == "__main__":
27
+ parser = argparse.ArgumentParser()
28
+ parser.add_argument(
29
+ "--folder",
30
+ type=str,
31
+ required=True,
32
+ help="Path to your demonstration folder that contains the demo.hdf5 file, e.g.: "
33
+ "'path_to_assets_dir/demonstrations/YOUR_DEMONSTRATION'",
34
+ ),
35
+ parser.add_argument(
36
+ "--use-actions",
37
+ action="store_true",
38
+ )
39
+ args = parser.parse_args()
40
+
41
+ demo_path = args.folder
42
+ hdf5_path = os.path.join(demo_path, "demo.hdf5")
43
+
44
+ f = h5py.File(hdf5_path, "r")
45
+ env_name = f["data"].attrs["env"]
46
+ env_info = json.loads(f["data"].attrs["env_info"])
47
+
48
+ env = robosuite.make(
49
+ **env_info,
50
+ has_renderer=True,
51
+ has_offscreen_renderer=False,
52
+ ignore_done=True,
53
+ use_camera_obs=False,
54
+ reward_shaping=True,
55
+ control_freq=20,
56
+ )
57
+
58
+ # list of all demonstrations episodes
59
+ demos = list(f["data"].keys())
60
+
61
+ while True:
62
+ print("Playing back random episode... (press ESC to quit)")
63
+
64
+ # select an episode randomly
65
+ ep = random.choice(demos)
66
+
67
+ # read the model xml, using the metadata stored in the attribute for this episode
68
+ model_xml = f["data/{}".format(ep)].attrs["model_file"]
69
+
70
+ env.reset()
71
+ xml = env.edit_model_xml(model_xml)
72
+ env.reset_from_xml_string(xml)
73
+ env.sim.reset()
74
+ env.viewer.set_camera(0)
75
+
76
+ # load the flattened mujoco states
77
+ states = f["data/{}/states".format(ep)][()]
78
+
79
+ if args.use_actions:
80
+
81
+ # load the initial state
82
+ env.sim.set_state_from_flattened(states[0])
83
+ env.sim.forward()
84
+
85
+ # load the actions and play them back open-loop
86
+ actions = np.array(f["data/{}/actions".format(ep)][()])
87
+ num_actions = actions.shape[0]
88
+
89
+ for j, action in enumerate(actions):
90
+ env.step(action)
91
+ env.render()
92
+
93
+ if j < num_actions - 1:
94
+ # ensure that the actions deterministically lead to the same recorded states
95
+ state_playback = env.sim.get_state().flatten()
96
+ if not np.all(np.equal(states[j + 1], state_playback)):
97
+ err = np.linalg.norm(states[j + 1] - state_playback)
98
+ print(f"[warning] playback diverged by {err:.2f} for ep {ep} at step {j}")
99
+
100
+ else:
101
+
102
+ # force the sequence of internal mujoco states one by one
103
+ for state in states:
104
+ env.sim.set_state_from_flattened(state)
105
+ env.sim.forward()
106
+ if env.renderer == "mjviewer":
107
+ env.viewer.update()
108
+ env.render()
109
+
110
+ f.close()
third_party/robosuite/robosuite/scripts/print_robosuite_info.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+
3
+ from robosuite.environments.base import REGISTERED_ENVS
4
+ from robosuite.models.bases import BASE_MAPPING
5
+ from robosuite.models.robots.robot_model import REGISTERED_ROBOTS
6
+ from robosuite.robots import ROBOT_CLASS_MAPPING
7
+
8
+
9
+ def bold_green_text(text):
10
+ return f"\033[1m\033[32m{text}\033[0m"
11
+
12
+
13
+ def get_base_type(robot):
14
+ return ROBOT_CLASS_MAPPING[robot].__name__ if robot in ROBOT_CLASS_MAPPING else "N/A"
15
+
16
+
17
+ def get_robot_info_dict():
18
+ info = {}
19
+ for i, key in enumerate(REGISTERED_ROBOTS):
20
+ try:
21
+ info[key] = {}
22
+ robot = REGISTERED_ROBOTS[key](idn=i)
23
+ base_type = get_base_type(key)
24
+ robot_base_model = robot.default_base
25
+ arm_type = robot.arm_type
26
+ gripper = robot.default_gripper
27
+ info[key]["Base_Type"] = base_type
28
+ info[key]["Robot_Base_Model"] = robot_base_model
29
+ info[key]["Arm_Type"] = arm_type
30
+ info[key]["Gripper_Model"] = gripper
31
+ except Exception as e:
32
+ # could not instantiate the class on its own
33
+ pass
34
+ return info
35
+
36
+
37
+ print("Available environments/tasks:\n")
38
+ for i, env in enumerate(REGISTERED_ENVS):
39
+ print(f"{i}. {bold_green_text(env)}")
40
+
41
+
42
+ info = get_robot_info_dict()
43
+ info_sorted = dict(sorted(info.items(), key=lambda item: item[1].get("Base_Type", "zzz")))
44
+
45
+ print("\n\n\nAvailable Robots:\n")
46
+
47
+ for i, key in enumerate(info_sorted):
48
+ print(f"{i}. {bold_green_text(key)}")
49
+ for k, item in info[key].items():
50
+ k = k.replace("_", " ")
51
+ print(f"\t{k}: {item}")
52
+ print("\n")
third_party/robosuite/robosuite/scripts/print_robot_action_info.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+
4
+ import robosuite as suite
5
+ from robosuite.controllers import load_composite_controller_config
6
+
7
+ parser = argparse.ArgumentParser()
8
+
9
+ parser.add_argument("--environment", type=str, default="Lift")
10
+ parser.add_argument("--robots", nargs="+", type=str, default="Panda", help="Which robot(s) to use in the env")
11
+ parser.add_argument("--config", type=str, default="opposed", help="Specified environment configuration if necessary")
12
+ parser.add_argument(
13
+ "--controller",
14
+ type=str,
15
+ default=None,
16
+ help="Choice of controller. Can be generic (eg. 'BASIC' or 'WHOLE_BODY_IK') or json file (see robosuite/controllers/config for examples)",
17
+ )
18
+
19
+ args = parser.parse_args()
20
+
21
+ controller_config = load_composite_controller_config(
22
+ controller=args.controller,
23
+ robot=args.robots[0],
24
+ )
25
+
26
+ config = {
27
+ "env_name": args.environment,
28
+ "robots": args.robots,
29
+ "controller_configs": controller_config,
30
+ }
31
+
32
+ # Check if we're using a multi-armed environment and use env_configuration argument if so
33
+ if "TwoArm" in args.environment:
34
+ config["env_configuration"] = args.config
35
+
36
+ # Create environment
37
+ env = suite.make(
38
+ **config,
39
+ has_renderer=True,
40
+ ignore_done=True,
41
+ use_camera_obs=False,
42
+ reward_shaping=True,
43
+ control_freq=20,
44
+ )
45
+ env.reset()
46
+
47
+ print(f"Action info for {args.environment}")
48
+ for robot in env.robots:
49
+ print(f"Action info for {robot.name}")
50
+ print(json.dumps(robot._action_split_indexes, indent=4))
51
+ print()
52
+
53
+
54
+ env.close()
55
+
56
+ print(
57
+ "Actions can created by calling robot.create_action_vector, and passing in a dictionary with the above keys and desired values."
58
+ )
third_party/robosuite/robosuite/scripts/render_dataset_with_omniverse.py ADDED
@@ -0,0 +1,735 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ from omni.isaac.lab.app import AppLauncher
4
+
5
+ parser = argparse.ArgumentParser(description="Settings for SimulationApp")
6
+
7
+ # General arguments for robocasa script
8
+ parser.add_argument("--dataset", type=str, required=True, help="the hdf5 dataset")
9
+
10
+ parser.add_argument(
11
+ "--ds_format", type=str, default="robomimic", help="the format of the dataset. Can be robosuite or robomimic"
12
+ )
13
+
14
+ # episode is a list
15
+ parser.add_argument(
16
+ "--episode",
17
+ type=int,
18
+ nargs="+",
19
+ default=[],
20
+ help="(optional) episode number(s) to render. Default is all episodes in the dataset",
21
+ )
22
+
23
+ parser.add_argument(
24
+ "--output_directory", type=str, default=None, help="(optional) directory to store outputs of USD rendering pipeline"
25
+ )
26
+
27
+ parser.add_argument(
28
+ "--cameras",
29
+ type=str,
30
+ nargs="+",
31
+ default=["agentview"],
32
+ help="(optional) camera name(s) / image observation(s) to use for rendering on-screen or to video. Default is"
33
+ "None, which corresponds to a predefined camera for each env type",
34
+ )
35
+
36
+ # Arguments to set up simulation app
37
+ parser.add_argument(
38
+ "--width", type=int, default=1280, help="(optional) width of the viewport and generated images. Defaults to 1280"
39
+ )
40
+
41
+ parser.add_argument(
42
+ "--height", type=int, default=720, help="(optional) height of the viewport and generated images. Defaults to 720"
43
+ )
44
+
45
+ parser.add_argument(
46
+ "--renderer",
47
+ type=str,
48
+ default="RayTracedLighting",
49
+ help="(optional) rendering mode, can be RayTracedLighting or PathTracing. Defaults to RayTracedLighting",
50
+ )
51
+
52
+ parser.add_argument(
53
+ "--save_video", action="store_true", default=False, help="(optional) save the rendered frames to a video file"
54
+ )
55
+
56
+ parser.add_argument(
57
+ "--online",
58
+ action="store_true",
59
+ default=False,
60
+ help="(optional) enable online rendering, will not save the usd file in this mode",
61
+ )
62
+
63
+ parser.add_argument("--skip_frames", type=int, default=1, help="(optional) render every nth frame. Defaults to 1")
64
+
65
+ parser.add_argument("--hide_sites", action="store_true", default=False, help="(optional) hide all sites in the scene")
66
+
67
+ parser.add_argument(
68
+ "--reload_model",
69
+ action="store_true",
70
+ default=False,
71
+ )
72
+
73
+ parser.add_argument(
74
+ "--keep_models", type=str, nargs="+", default=[], help="(optional) keep the model from the Mujoco XML file"
75
+ )
76
+
77
+ # adding rendering types
78
+ parser.add_argument(
79
+ "--rgb",
80
+ action="store_true",
81
+ default=False,
82
+ )
83
+ parser.add_argument(
84
+ "--normals",
85
+ action="store_true",
86
+ default=False,
87
+ )
88
+ parser.add_argument(
89
+ "--semantic_segmentation",
90
+ action="store_true",
91
+ default=False,
92
+ )
93
+
94
+ # Add arguments for launch
95
+ AppLauncher.add_app_launcher_args(parser)
96
+ # Parse the arguments
97
+ args = parser.parse_args()
98
+ # args.headless = True
99
+ args.enable_cameras = True
100
+ # Launch the Omniverse app
101
+ app_launcher = AppLauncher(args)
102
+ simulation_app = app_launcher.app
103
+
104
+
105
+ import json
106
+ import os
107
+ import re
108
+ import shutil
109
+ from enum import Enum
110
+
111
+ import carb.settings
112
+ import cv2
113
+ import h5py
114
+ import lxml.etree as ET
115
+ import numpy as np
116
+ import omni
117
+ import omni.isaac.core.utils.stage as stage_utils
118
+ import omni.kit.app
119
+ import omni.replicator.core as rep
120
+ import omni.timeline
121
+ from pxr import Semantics
122
+ from termcolor import colored
123
+ from tqdm import tqdm
124
+
125
+ # Robocasa imports
126
+ try:
127
+ import robocasa
128
+ except ImportError:
129
+ print("Warning: Robocasa not found.")
130
+
131
+ try:
132
+ import dexmimicgen_environments
133
+ import mimicgen
134
+ except ImportError:
135
+ print("Warning: MimicGen not found.")
136
+
137
+ # USD imports
138
+ import mujoco
139
+
140
+ import robosuite
141
+ import robosuite.utils.usd.exporter as exporter
142
+
143
+ scene_option = mujoco.MjvOption()
144
+ scene_option.geomgroup = [0, 1, 0, 0, 0, 0]
145
+
146
+ render_modalities = {"rgb": args.rgb, "normals": args.normals, "semantic_segmentation": args.semantic_segmentation}
147
+
148
+
149
+ def make_sites_invisible(mujoco_xml):
150
+ """
151
+ Makes all site elements in a Mujoco XML string invisible by setting their rgba attribute to fully transparent.
152
+ """
153
+ # Parse the Mujoco XML string
154
+ root = ET.fromstring(mujoco_xml)
155
+
156
+ # Find all site elements
157
+ site_elements = root.findall(".//site")
158
+
159
+ # Make all site elements invisible by setting rgba attribute
160
+ for site in site_elements:
161
+ site.set("rgba", "0 0 0 0") # Set rgba to fully transparent
162
+
163
+ # Return the modified XML string
164
+ return ET.tostring(root, encoding="unicode")
165
+
166
+
167
+ def reset_to(env, state):
168
+ """
169
+ Reset to a specific simulator state.
170
+
171
+ Args:
172
+ state (dict): current simulator state that contains one or more of:
173
+ - states (np.ndarray): initial state of the mujoco environment
174
+ - model (str): mujoco scene xml
175
+
176
+ Returns:
177
+ observation (dict): observation dictionary after setting the simulator state (only
178
+ if "states" is in @state)
179
+ """
180
+ should_ret = False
181
+ if "model" in state:
182
+ if state.get("ep_meta", None) is not None:
183
+ # set relevant episode information
184
+ ep_meta = json.loads(state["ep_meta"])
185
+ else:
186
+ ep_meta = {}
187
+ if hasattr(env, "set_attrs_from_ep_meta"): # older versions had this function
188
+ env.set_attrs_from_ep_meta(ep_meta)
189
+ elif hasattr(env, "set_ep_meta"): # newer versions
190
+ env.set_ep_meta(ep_meta)
191
+ # this reset is necessary.
192
+ # while the call to env.reset_from_xml_string does call reset,
193
+ # that is only a "soft" reset that doesn't actually reload the model.
194
+ env.reset()
195
+ robosuite_version_id = int(robosuite.__version__.split(".")[1])
196
+ if robosuite_version_id <= 3:
197
+ from robosuite.utils.mjcf_utils import postprocess_model_xml
198
+
199
+ xml = postprocess_model_xml(state["model"])
200
+ else:
201
+ # v1.4 and above use the class-based edit_model_xml function
202
+ xml = env.edit_model_xml(state["model"])
203
+
204
+ env.reset_from_xml_string(xml)
205
+ env.sim.reset()
206
+ # hide teleop visualization after restoring from model
207
+ # env.sim.model.site_rgba[env.eef_site_id] = np.array([0., 0., 0., 0.])
208
+ # env.sim.model.site_rgba[env.eef_cylinder_id] = np.array([0., 0., 0., 0.])
209
+ if hasattr(env, "unset_ep_meta"): # unset the ep meta after reset complete
210
+ env.unset_ep_meta()
211
+ if "states" in state:
212
+ env.sim.set_state_from_flattened(state["states"])
213
+ env.sim.forward()
214
+ should_ret = True
215
+
216
+ # update state as needed
217
+ if hasattr(env, "update_sites"):
218
+ # older versions of environment had update_sites function
219
+ env.update_sites()
220
+ if hasattr(env, "update_state"):
221
+ # later versions renamed this to update_state
222
+ env.update_state()
223
+
224
+ # if should_ret:
225
+ # # only return obs if we've done a forward call - otherwise the observations will be garbage
226
+ # return get_observation()
227
+ return None
228
+
229
+
230
+ def get_env_metadata_from_dataset(dataset_path, ds_format="robomimic"):
231
+ """
232
+ Retrieves env metadata from dataset.
233
+
234
+ Args:
235
+ dataset_path (str): path to dataset
236
+
237
+ Returns:
238
+ env_meta (dict): environment metadata. Contains 3 keys:
239
+
240
+ :`'env_name'`: name of environment
241
+ :`'type'`: type of environment, should be a value in EB.EnvType
242
+ :`'env_kwargs'`: dictionary of keyword arguments to pass to environment constructor
243
+ """
244
+ dataset_path = os.path.expanduser(dataset_path)
245
+ f = h5py.File(dataset_path, "r")
246
+ if ds_format == "robomimic":
247
+ env_meta = json.loads(f["data"].attrs["env_args"])
248
+ elif ds_format == "robosuite":
249
+ env_name = f["data"].attrs["env"]
250
+ env_info = json.loads(f["data"].attrs["env_info"])
251
+ env_meta = dict(
252
+ env_name=env_name,
253
+ env_version=f["data"].attrs["repository_version"],
254
+ env_kwargs=env_info,
255
+ )
256
+ else:
257
+ raise ValueError
258
+ f.close()
259
+ return env_meta
260
+
261
+
262
+ class RobosuiteEnvInterface:
263
+ """
264
+ Env wrapper to load a robosuite demonstration
265
+ """
266
+
267
+ def __init__(
268
+ self, dataset, episode, output_directory, cameras="agentview", reload_model=False, keep_models=[]
269
+ ) -> None:
270
+ self.dataset = dataset
271
+ self.episode = episode
272
+ self.output_directory = output_directory
273
+ self.cameras = cameras
274
+ self.reload_model = reload_model
275
+ self.keep_models = keep_models
276
+ self.env = self.load_robosuite_environment()
277
+ initial_state, self.states = self.get_states()
278
+ reset_to(self.env, initial_state)
279
+ self.exp = self.link_env_with_ov()
280
+ self.traj_len = self.states.shape[0]
281
+
282
+ def load_robosuite_environment(self):
283
+ """
284
+ Loads the specified robosuite demonstration and
285
+ """
286
+ env_meta = get_env_metadata_from_dataset(dataset_path=self.dataset, ds_format=args.ds_format)
287
+ env_kwargs = env_meta["env_kwargs"]
288
+ env_kwargs["env_name"] = env_meta["env_name"]
289
+ env_kwargs["has_renderer"] = False
290
+ env_kwargs["has_offscreen_renderer"] = False
291
+ env_kwargs["use_camera_obs"] = False
292
+ # for robosuite compatibility, remove robocasa specific arguments
293
+ if "env_lang" in env_kwargs:
294
+ del env_kwargs["env_lang"]
295
+ # temporary fix for backward compatibility here to load the correct config if version is less than v1.5.0
296
+ # assume all version number is single digit
297
+ if env_meta["env_version"] < "v1.5.0":
298
+ from robosuite.controllers import load_composite_controller_config
299
+
300
+ if "composite_controller_configs" in env_kwargs:
301
+ del env_kwargs["composite_controller_configs"]
302
+ robot = env_kwargs["robots"][0] if isinstance(env_kwargs["robots"], list) else env_kwargs["robots"]
303
+ if robot == "PandaMobile":
304
+ robot = "PandaOmron"
305
+ composite_controller_config = load_composite_controller_config(controller=None, robot=robot)
306
+ # breakpoint()
307
+ env_kwargs["controller_configs"] = composite_controller_config
308
+ print(colored("Initializing environment for {}...".format(env_kwargs["env_name"]), "yellow"))
309
+ env = robosuite.make(**env_kwargs)
310
+
311
+ return env
312
+
313
+ def get_states(self):
314
+ """
315
+ Gets the initial state of the robosuite demonstration
316
+ """
317
+ f = h5py.File(self.dataset, "r+")
318
+ ep = "demo_" + str(self.episode)
319
+ states = f["data/{}/states".format(ep)][()][:: args.skip_frames]
320
+ initial_state = dict(states=states[0])
321
+ model_xml = f["data/{}".format(ep)].attrs["model_file"]
322
+ if self.reload_model:
323
+ env_xml = self.env.sim.model.get_xml()
324
+ for name in self.keep_models:
325
+ root_model = ET.fromstring(model_xml)
326
+ root_env = ET.fromstring(env_xml)
327
+ body_model = root_model.find(".//body[@name='{}']".format(name))
328
+ body_env = root_env.find(".//body[@name='{}']".format(name))
329
+ # change the properties of the body in env to match the model
330
+ if body_model is not None and body_env is not None:
331
+ for attr_name, attr_value in body_model.attrib.items():
332
+ body_env.set(attr_name, attr_value)
333
+ env_xml = ET.tostring(root_env, encoding="unicode")
334
+ model_xml = env_xml
335
+
336
+ if args.hide_sites:
337
+ model_xml = make_sites_invisible(model_xml)
338
+
339
+ initial_state["model"] = model_xml
340
+ initial_state["ep_meta"] = f["data/{}".format(ep)].attrs.get("ep_meta", None)
341
+
342
+ return initial_state, states
343
+
344
+ def link_env_with_ov(self):
345
+ """
346
+ Loads the initial state of a robosuite scene into simulation
347
+ """
348
+ model = self.env.sim.model._model
349
+ data = self.env.sim.data._data
350
+
351
+ # Create a USD exporter instance with the current stage
352
+ stage = None
353
+ if args.online:
354
+ stage = stage_utils.get_current_stage()
355
+
356
+ exp = exporter.USDExporter(
357
+ model=model,
358
+ output_directory_name=self.output_directory,
359
+ camera_names=args.cameras,
360
+ online=args.online,
361
+ shareable=not args.online,
362
+ framerate=20,
363
+ stage=stage,
364
+ )
365
+ exp.update_scene(data=data, scene_option=scene_option)
366
+ exp.add_light(pos=[0, 0, 0], intensity=1500, light_type="dome", light_name="dome_1")
367
+
368
+ # adds semantic information to objects in the scene
369
+ if args.semantic_segmentation:
370
+ for geom in exp.scene.geoms:
371
+ geom_id = geom.objid
372
+ geom_name = exp._get_geom_name(geom)
373
+ if geom_id in self.env.model._geom_ids_to_classes:
374
+ semantic_value = self.env.model._geom_ids_to_classes[geom_id]
375
+ if "site" in geom_name or "None" in geom_name:
376
+ continue
377
+ prim = exp.geom_refs[geom_name].usd_prim
378
+ instance_name = f"class_{semantic_value}"
379
+ sem = Semantics.SemanticsAPI.Apply(prim, instance_name)
380
+ sem.CreateSemanticTypeAttr()
381
+ sem.CreateSemanticDataAttr()
382
+ sem.GetSemanticTypeAttr().Set("class")
383
+ sem.GetSemanticDataAttr().Set(semantic_value)
384
+
385
+ return exp
386
+
387
+ def update_simulation(self, index):
388
+ """
389
+ Renders a robosuite trajectory given the state at a given frame
390
+ """
391
+ state = self.states[index]
392
+ reset_to(self.env, {"states": state})
393
+ data = self.env.sim.data._data
394
+ self.exp.update_scene(data=data, scene_option=scene_option)
395
+
396
+ def close(self):
397
+ if not args.online:
398
+ self.exp.save_scene(filetype="usd")
399
+ self.env.close()
400
+
401
+
402
+ __version__ = "0.0.2"
403
+
404
+
405
+ class RobosuiteWriter(rep.Writer):
406
+ def __init__(
407
+ self,
408
+ output_dir: str = None,
409
+ image_output_format: str = "png",
410
+ rgb: bool = False,
411
+ normals: bool = False,
412
+ semantic_segmentation: bool = False,
413
+ frame_padding: int = 4,
414
+ ):
415
+ self._output_dir = output_dir
416
+ if output_dir:
417
+ self._backend = rep.BackendDispatch(output_dir=output_dir)
418
+
419
+ self._frame_id = 0
420
+ self._frame_padding = frame_padding
421
+ self._sequence_id = 0
422
+ self._image_output_format = image_output_format
423
+ self._output_data_format = {}
424
+ self.annotators = []
425
+ self.version = __version__
426
+ self.data_structure = "annotator"
427
+ self.write_ready = False
428
+
429
+ self.rgb = rgb
430
+ self.normals = normals
431
+ self.semantic_segmentation = semantic_segmentation
432
+
433
+ if rgb:
434
+ self.annotators.append(rep.AnnotatorRegistry.get_annotator("rgb"))
435
+ if normals:
436
+ self.annotators.append(rep.AnnotatorRegistry.get_annotator("normals"))
437
+ if semantic_segmentation:
438
+ self.annotators.append(rep.AnnotatorRegistry.get_annotator("semantic_segmentation", {"colorize": True}))
439
+
440
+ def write(self, data: dict):
441
+ """Write function called from the OgnWriter node on every frame to process annotator output.
442
+
443
+ Args:
444
+ data: A dictionary containing the annotator data for the current frame.
445
+ """
446
+ if self.write_ready:
447
+ for annotator_name, annotator_data in data["annotators"].items():
448
+ for idx, (render_product_name, anno_rp_data) in enumerate(annotator_data.items()):
449
+ if annotator_name == "rgb":
450
+ filepath = os.path.join(
451
+ args.cameras[idx], "rgb", f"rgb_{self._frame_id}.{self._image_output_format}"
452
+ )
453
+ self._backend.write_image(filepath, anno_rp_data["data"])
454
+ elif annotator_name == "normals":
455
+ normals = anno_rp_data["data"][..., :3]
456
+ norm_lengths = np.linalg.norm(normals, axis=-1, keepdims=True)
457
+ normals_normalized = normals / np.clip(norm_lengths, 1e-8, None)
458
+ img = ((normals_normalized + 1) / 2 * 255).astype(np.uint8)
459
+ filepath = os.path.join(
460
+ args.cameras[idx], "normals", f"normals_{self._frame_id}.{self._image_output_format}"
461
+ )
462
+ self._backend.write_image(filepath, img)
463
+ elif annotator_name == "semantic_segmentation":
464
+ filepath = os.path.join(
465
+ args.cameras[idx],
466
+ "semantic_segmentation",
467
+ f"semantic_segmentation_{self._frame_id}.{self._image_output_format}",
468
+ )
469
+ self._backend.write_image(filepath, anno_rp_data["data"])
470
+
471
+ self._frame_id += 1
472
+
473
+
474
+ rep.WriterRegistry.register(RobosuiteWriter)
475
+
476
+
477
+ class RecorderState(Enum):
478
+ READY = 0
479
+ RUNNING = 1
480
+ COMPLETED = 2
481
+
482
+
483
+ class DataGenerator:
484
+ def __init__(self, robosuite_env) -> None:
485
+ # State variables
486
+ self.recorder_state = RecorderState.READY
487
+ self.writer = None
488
+ self.render_products = []
489
+ self.current_frame = 0
490
+ self.robosuite_env = robosuite_env
491
+
492
+ # Define writer format
493
+ self.writer_name = "RobosuiteWriter"
494
+
495
+ self.num_frames = self.robosuite_env.traj_len
496
+ self.rt_subframes = 1
497
+ # skip 5 frames at the beginning to allow the scene to settle
498
+ self.initial_skip = 5
499
+
500
+ self.output_dir = os.path.abspath(self.robosuite_env.output_directory)
501
+
502
+ def _check_if_valid_camera(self, path):
503
+ context = omni.usd.get_context()
504
+ stage = context.get_stage()
505
+ prim = stage.GetPrimAtPath(path)
506
+
507
+ if not prim.IsValid():
508
+ print(f"{path} is not a valid prim path.")
509
+ return False
510
+
511
+ if prim.GetTypeName() == "Camera":
512
+ return True
513
+ else:
514
+ print(f"{prim} is not a 'Camera' type.")
515
+ return False
516
+
517
+ def _check_if_valid_resolution(self, resolution):
518
+ width, height = resolution[0], resolution[1]
519
+ MAX_RESOLUTION = (16000, 8000) # 16K
520
+ if 0 <= width <= MAX_RESOLUTION[0] and 0 <= height <= MAX_RESOLUTION[1]:
521
+ return True
522
+ else:
523
+ print(
524
+ f"Invalid resolution: {width}x{height}. Must be between 1x1 and {MAX_RESOLUTION[0]}x{MAX_RESOLUTION[1]}."
525
+ )
526
+ return False
527
+
528
+ def load_stage(self):
529
+ usd_path = os.path.join(self.output_dir, f"frames/frame_{self.num_frames + 1}.usd")
530
+ print(f"Opening stage {usd_path}")
531
+ stage_utils.open_stage(usd_path)
532
+ print("Stage loaded")
533
+
534
+ def init_recorder(self):
535
+ # Open USD stage
536
+ if not args.online:
537
+ self.load_stage()
538
+
539
+ if carb.settings.get_settings().get("/omni/replicator/captureOnPlay"):
540
+ carb.settings.get_settings().set_bool("/omni/replicator/captureOnPlay", False)
541
+
542
+ carb.settings.get_settings().set_bool("/app/renderer/waitIdle", False)
543
+ carb.settings.get_settings().set_bool("/app/hydraEngine/waitIdle", False)
544
+ carb.settings.get_settings().set_bool("/app/asyncRendering", True)
545
+ carb.settings.get_settings().set("/rtx/pathtracing/spp", 30)
546
+ carb.settings.get_settings().set_bool("/exts/omni.replicator.core/Orchestrator/enabled", True)
547
+
548
+ # Create writer for capturing generated data
549
+ self.writer = rep.WriterRegistry.get(self.writer_name)
550
+ self.writer.initialize(
551
+ output_dir=self.output_dir,
552
+ rgb=args.rgb,
553
+ normals=args.normals,
554
+ semantic_segmentation=args.semantic_segmentation,
555
+ )
556
+
557
+ print("Writer Initiazed")
558
+
559
+ # Create render products
560
+ for camera_name in args.cameras:
561
+ resolution = (args.width, args.height)
562
+ camera_path = f"/World/Camera_Xform_{camera_name}/Camera_{camera_name}"
563
+ if self._check_if_valid_camera(camera_path) and self._check_if_valid_resolution(resolution):
564
+ rp = rep.create.render_product(camera_path, (resolution[0], resolution[1]), force_new=True)
565
+ self.render_products.append(rp)
566
+ else:
567
+ print(f"Invalid render product entry: {camera_path}")
568
+
569
+ print("Render products created")
570
+
571
+ # Attach render products to writers
572
+ if self.render_products:
573
+ self.writer.attach(self.render_products)
574
+ else:
575
+ print("No valid render products found to initialize the writer.")
576
+ return False
577
+
578
+ print("Render products attached")
579
+ return True
580
+
581
+ def start_recorder(self):
582
+ if self.recorder_state == RecorderState.READY and self.init_recorder():
583
+ self.recorder_state = RecorderState.RUNNING
584
+ self.run_recording_loop()
585
+ else:
586
+ self.finish_recording()
587
+
588
+ def run_recording_loop(self):
589
+ max_frames = self.num_frames if self.num_frames > 0 else 200 # Testing
590
+ print(f"Recording {max_frames} frames to: {self.output_dir}")
591
+
592
+ for _ in range(self.initial_skip):
593
+ rep.orchestrator.step(rt_subframes=1, delta_time=None, pause_timeline=False)
594
+
595
+ self.writer.write_ready = True
596
+ if not args.online:
597
+ timeline = omni.timeline.get_timeline_interface()
598
+ timeline.set_end_time(max_frames)
599
+ with tqdm(total=max_frames) as pbar:
600
+ while self.current_frame < max_frames:
601
+ if self.recorder_state != RecorderState.RUNNING:
602
+ break
603
+ if args.online:
604
+ self.robosuite_env.update_simulation(self.current_frame)
605
+ else:
606
+ timeline.forward_one_frame()
607
+ rep.orchestrator.step(rt_subframes=self.rt_subframes, delta_time=None, pause_timeline=True)
608
+ self.current_frame += 1
609
+ pbar.update(1)
610
+
611
+ if self.recorder_state == RecorderState.RUNNING:
612
+ self.finish_recording()
613
+
614
+ def finish_recording(self):
615
+ if not args.online:
616
+ timeline = omni.timeline.get_timeline_interface()
617
+ timeline.stop()
618
+ rep.orchestrator.wait_until_complete()
619
+ print(f"[SDR] Finished;\tWrote {self.current_frame} frames to: {self.output_dir};")
620
+ self.clear_recorder()
621
+ self.recorder_state = RecorderState.COMPLETED
622
+
623
+ def clear_recorder(self):
624
+ if self.recorder_state != RecorderState.COMPLETED:
625
+ self.recorder_state = RecorderState.COMPLETED
626
+ if self.writer:
627
+ self.writer.detach()
628
+ self.writer = None
629
+ for rp in self.render_products:
630
+ rp.destroy()
631
+ self.render_products.clear()
632
+ stage_utils.clear_stage()
633
+ if args.online:
634
+ stage_utils.close_stage()
635
+ stage_utils.create_new_stage()
636
+ stage_utils.update_stage()
637
+
638
+ def natural_sort_key(self, s):
639
+ return [int(c) if c.isdigit() else c.lower() for c in re.split(r"(\d+)", s)]
640
+
641
+ def create_video_from_frames(self, frame_folder, output_path, fps=30):
642
+ frames = [f for f in os.listdir(frame_folder) if f.endswith(".png")]
643
+ frames.sort(key=self.natural_sort_key)
644
+ assert (
645
+ len(frames) == self.current_frame
646
+ ), f"Number of frames in folder ({len(frames)}) does not match number of frames rendered ({self.current_frame})"
647
+ if not frames:
648
+ print(f"No frames found in {frame_folder}")
649
+ return
650
+
651
+ first_frame = cv2.imread(os.path.join(frame_folder, frames[0]))
652
+ height, width, layers = first_frame.shape
653
+
654
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
655
+ video = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
656
+
657
+ for frame in frames:
658
+ video.write(cv2.imread(os.path.join(frame_folder, frame)))
659
+
660
+ video.release()
661
+ print(f"Video saved: {output_path}")
662
+
663
+ def create_video(self, videos_folder, camera, data_type):
664
+ camera_folder_path = os.path.join(self.output_dir, camera, data_type) # temp, change to render type
665
+ if not os.path.isdir(camera_folder_path):
666
+ return
667
+
668
+ # Construct output filename and path
669
+ output_filename = f"{camera}_{data_type}.mp4"
670
+ output_path = os.path.join(videos_folder, output_filename)
671
+
672
+ # Create the video from the frames in the camera folder
673
+ self.create_video_from_frames(camera_folder_path, output_path)
674
+
675
+ def process_folders(self):
676
+ videos_folder = os.path.join(self.output_dir, "videos")
677
+ os.makedirs(videos_folder, exist_ok=True)
678
+
679
+ # Iterate over each camera folder in the output directory
680
+ for camera in args.cameras:
681
+ for render_modality, selected in render_modalities.items():
682
+ if selected:
683
+ self.create_video(videos_folder=videos_folder, camera=camera, data_type=render_modality)
684
+
685
+
686
+ def main():
687
+ f = h5py.File(args.dataset, "r")
688
+ total_episodes = args.episode
689
+ if not total_episodes:
690
+ # get all the int keys
691
+ total_episodes = [int(k.split("_")[1]) for k in f["data"].keys()]
692
+ f.close()
693
+ print(f"Total episodes: {total_episodes}")
694
+ dataset_name = "_".join(args.dataset.split("/")[-1].split(".")[:-1])
695
+ if args.output_directory is None:
696
+ # use the dataset directory
697
+ args.output_directory = os.path.dirname(args.dataset)
698
+
699
+ for episode in total_episodes:
700
+ output_directory = os.path.join(args.output_directory, dataset_name, "demo_" + str(episode))
701
+ robosuite_env = RobosuiteEnvInterface(
702
+ dataset=args.dataset,
703
+ episode=episode,
704
+ output_directory=output_directory,
705
+ cameras=args.cameras,
706
+ reload_model=args.reload_model,
707
+ keep_models=args.keep_models,
708
+ )
709
+ if not args.online:
710
+ # generate the usd first, and close the env to save the usd
711
+ for i in tqdm(range(robosuite_env.traj_len)):
712
+ robosuite_env.update_simulation(i)
713
+ robosuite_env.close()
714
+
715
+ data_generator = DataGenerator(robosuite_env)
716
+ data_generator.start_recorder()
717
+
718
+ while data_generator.recorder_state != RecorderState.COMPLETED:
719
+ stage_utils.update_stage()
720
+
721
+ if args.save_video:
722
+ data_generator.process_folders()
723
+
724
+ # remove all image frames
725
+ for camera in args.cameras:
726
+ camera_folder_path = os.path.join(output_directory, camera)
727
+ if os.path.isdir(camera_folder_path):
728
+ shutil.rmtree(camera_folder_path)
729
+
730
+ print("Recording complete")
731
+
732
+
733
+ if __name__ == "__main__":
734
+ main()
735
+ print("Script execution completed.")
third_party/robosuite/robosuite/scripts/setup_macros.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This script sets up a private macros file.
3
+ The private macros file (macros_private.py) is not tracked by git,
4
+ allowing user-specific settings that are not tracked by git.
5
+ This script checks if macros_private.py exists.
6
+ If applicable, it creates the private macros at robosuite/macros_private.py
7
+ """
8
+
9
+ import os
10
+ import shutil
11
+
12
+ import robosuite
13
+
14
+ if __name__ == "__main__":
15
+ base_path = robosuite.__path__[0]
16
+ macros_path = os.path.join(base_path, "macros.py")
17
+ macros_private_path = os.path.join(base_path, "macros_private.py")
18
+
19
+ if not os.path.exists(macros_path):
20
+ print("{} does not exist! Aborting...".format(macros_path))
21
+
22
+ if os.path.exists(macros_private_path):
23
+ ans = input("{} already exists! \noverwrite? (y/n)\n".format(macros_private_path))
24
+
25
+ if ans == "y":
26
+ print("REMOVING")
27
+ else:
28
+ exit()
29
+
30
+ shutil.copyfile(macros_path, macros_private_path)
31
+ print("copied {}\nto {}".format(macros_path, macros_private_path))