diff --git a/third_party/robocasa/robocasa/models/fixtures/fixture_utils.py b/third_party/robocasa/robocasa/models/fixtures/fixture_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0b24a85788bf037ba42831061debafec875db15d --- /dev/null +++ b/third_party/robocasa/robocasa/models/fixtures/fixture_utils.py @@ -0,0 +1,106 @@ +from robocasa.models.fixtures import * + + +def fixture_is_type(fixture, fixture_type): + """ + Check if a fixture is of a certain type + + Args: + fixture (Fixture): The fixture to check + + fixture_type (FixtureType): The type to check against + """ + if fixture_type == FixtureType.COUNTER: + return isinstance(fixture, Counter) + elif fixture_type == FixtureType.DINING_COUNTER: + cls_check = any([isinstance(fixture, cls) for cls in [Counter]]) + if not cls_check: + return False + return fixture.width >= 2 or fixture.depth >= 2 + elif fixture_type == FixtureType.CABINET: + return isinstance(fixture, Cabinet) + elif fixture_type == FixtureType.DRAWER: + return isinstance(fixture, Drawer) + elif fixture_type == FixtureType.SINK: + return isinstance(fixture, Sink) + elif fixture_type == FixtureType.STOVE: + return isinstance(fixture, Stove) + elif fixture_type == FixtureType.CABINET_TOP: + cls_check = any( + [ + isinstance(fixture, cls) + for cls in [SingleCabinet, HingeCabinet, OpenCabinet] + ] + ) + if not cls_check: + return False + if "stack" in fixture.name: # wall stack cabinets not valid + return False + # check the height of the cabinet to see if it is a top cabinet + fxtr_bottom_z = fixture.pos[2] + fixture.bottom_offset[2] + height_check = 1.0 <= fxtr_bottom_z <= 1.60 + return height_check + elif fixture_type == FixtureType.MICROWAVE: + return isinstance(fixture, Microwave) + elif fixture_type in [FixtureType.DOOR_HINGE, FixtureType.DOOR_TOP_HINGE]: + cls_check = any( + [ + isinstance(fixture, cls) + for cls in [SingleCabinet, HingeCabinet, Microwave] + ] + ) + if not cls_check: + return False + if fixture_type == FixtureType.DOOR_TOP_HINGE: + if "stack" in fixture.name: # wall stack cabinets not valid + return False + fxtr_bottom_z = fixture.pos[2] + fixture.bottom_offset[2] + height_check = 1.0 <= fxtr_bottom_z <= 1.60 + if not height_check: + return False + return True + elif fixture_type in [ + FixtureType.DOOR_HINGE_SINGLE, + FixtureType.DOOR_TOP_HINGE_SINGLE, + ]: + cls_check = any( + [isinstance(fixture, cls) for cls in [SingleCabinet, Microwave]] + ) + if not cls_check: + return False + if fixture_type == FixtureType.DOOR_TOP_HINGE_SINGLE: + if "stack" in fixture.name: # wall stack cabinets not valid + return False + fxtr_bottom_z = fixture.pos[2] + fixture.bottom_offset[2] + height_check = 1.0 <= fxtr_bottom_z <= 1.60 + if not height_check: + return False + return True + elif fixture_type in [ + FixtureType.DOOR_HINGE_DOUBLE, + FixtureType.DOOR_TOP_HINGE_DOUBLE, + ]: + cls_check = any([isinstance(fixture, cls) for cls in [HingeCabinet]]) + if not cls_check: + return False + if fixture_type == FixtureType.DOOR_TOP_HINGE_DOUBLE: + if "stack" in fixture.name: # wall stack cabinets not valid + return False + fxtr_bottom_z = fixture.pos[2] + fixture.bottom_offset[2] + height_check = 1.0 <= fxtr_bottom_z <= 1.60 + if not height_check: + return False + return True + elif fixture_type == FixtureType.TOASTER: + return isinstance(fixture, Toaster) + elif fixture_type == FixtureType.TOP_DRAWER: + height_check = 0.7 <= fixture.pos[2] <= 0.9 + return height_check and isinstance(fixture, Drawer) + elif fixture_type == FixtureType.STOOL: + return isinstance(fixture, Stool) + elif fixture_type == FixtureType.ISLAND: + return isinstance(fixture, Counter) and "island" in fixture.name + elif fixture_type == FixtureType.COUNTER_NON_CORNER: + return isinstance(fixture, Counter) and "corner" not in fixture.name + else: + raise ValueError diff --git a/third_party/robocasa/robocasa/models/fixtures/handles.py b/third_party/robocasa/robocasa/models/fixtures/handles.py new file mode 100644 index 0000000000000000000000000000000000000000..78fdf3763e4724df050b24ab78d437c5f6bd2646 --- /dev/null +++ b/third_party/robocasa/robocasa/models/fixtures/handles.py @@ -0,0 +1,316 @@ +import abc +import os +from xml.etree import ElementTree as ET + +import numpy as np +from robosuite.utils.mjcf_utils import array_to_string as a2s +from robosuite.utils.mjcf_utils import find_elements, xml_path_completion + +import robocasa +from robocasa.models.objects import MujocoXMLObject +from robocasa.models.fixtures.fixture import get_texture_name_from_file + + +class Handle(MujocoXMLObject): + """ + Base class for all handles attached to cabinet/drawer panels + + Args: + name (str): Name of the handle + + xml (str): Path to the xml file of the handle + + panel_w (float): Width of the panel to attach the handle to + + panel_h (float): Height of the panel to attach the handle to + + texture (str): Path to the texture file of the handle + + orientation (str): Orientation of the handle. Can be either "horizontal" (for drawers) or "vertical" + + length (float): Length of the handle + """ + + def __init__( + self, + name, + xml, + panel_w, + panel_h, + texture="textures/metals/bright_metal.png", + orientation="vertical", + length=None, + ): + super().__init__( + xml_path_completion(xml, root=robocasa.models.assets_root), + name=name, + joints=None, + duplicate_collision_geoms=True, + ) + + self.length = length + self.orientation = orientation + self.texture = xml_path_completion(texture, root=robocasa.models.assets_root) + self.panel_w = panel_w + self.panel_h = panel_h + + # for hinge cabinets + self.side = None + + self._create_handle() + self._set_texture() + + @abc.abstractmethod + def _get_components(self): + raise NotImplementedError + + @abc.abstractmethod + def _create_handle(self, positions, sizes): + raise NotImplementedError + + def exclude_from_prefixing(self, inp): + """ + Exclude all shared materials and their associated names from being prefixed. + + Args: + inp (ET.Element or str): Element or its attribute to check for prefixing. + + Returns: + bool: True if we should exclude the associated name(s) with @inp from being prefixed with naming_prefix + """ + if "tex" in inp: + return True + + if isinstance(inp, ET.Element): + return inp.tag in ["texture"] + + return False + + def _set_texture(self): + """ + Set the texture of the handle + """ + # set texture + texture = find_elements( + self.root, tags="texture", attribs={"name": "tex"}, return_first=True + ) + tex_name = get_texture_name_from_file(self.texture) + texture.set("file", self.texture) + texture.set("name", tex_name) + + material = find_elements( + self.root, + tags="material", + attribs={"name": "{}_mat".format(self.name)}, + return_first=True, + ) + material.set("texture", tex_name) + + +class BarHandle(Handle): + """ + Creates a bar handle + + Args: + length (float): Length of the handle + + handle_pad (float): A minimum difference between handle length and cabinet panel height + """ + + def __init__( + self, + length=0.24, + # connector_pad=0.05, + handle_pad=0.04, + *args, + **kwargs + ): + # z-direction padding for top and bottom connectors + # self.connector_pad = connector_pad + # assert length > connector_pad * 2 + # z-direction padding for handle from sides of cabinet + self.handle_pad = handle_pad + + super().__init__( + xml="fixtures/handles/bar_handle.xml", length=length, *args, **kwargs + ) + + def _get_components(self): + """ + Get the geoms of the handle + """ + geom_names = ["handle", "handle_connector_top", "handle_connector_bottom"] + body_names = [] + joint_names = [] + return self._get_elements_by_name(geom_names, body_names, joint_names) + + def _create_handle(self): + """ + Calculates and sets and positions and sizes of each component of the handles + Treats the three types of cabinets separately + """ + + # adjust handle size if necessary + if self.panel_h < self.length + 2 * self.handle_pad: + self.length = self.panel_h - 2 * self.handle_pad + # if self.length < 3 * self.connector_pad: + # raise ValueError("Cabinet size {:.3f} is too small for " \ + # "bar handles.".format(self.panel_h)) + + offset = self.length / 2 * 0.60 # - self.connector_pad + # distance between main handle and door + conn_len = 0.05 + + # calculate positions for each component + positions = { + "handle": np.array([0, -conn_len, 0]), + "handle_connector_top": np.array([0, -conn_len / 2, offset]), + "handle_connector_bottom": np.array([0, -conn_len / 2, -offset]), + } + sizes = { + "handle": [0.013, self.length / 2], + "handle_connector_top": [0.008, conn_len / 2], + "handle_connector_bottom": [0.008, conn_len / 2], + } + eulers = {} + + if self.orientation == "horizontal": + positions["handle_connector_top"][[0, 2]] = positions[ + "handle_connector_top" + ][[2, 0]] + positions["handle_connector_bottom"][[0, 2]] = positions[ + "handle_connector_bottom" + ][[2, 0]] + eulers["handle"] = [0, 1.5708, 0] + + geoms, bodies, joints = self._get_components() + for side in positions.keys(): + for geom in geoms[side]: + if geom is None: + continue + geom.set("pos", a2s(positions[side])) + geom.set("size", a2s(sizes[side])) + + if eulers.get(side) is not None: + geom.set("euler", a2s(eulers[side])) + + +class BoxedHandle(Handle): + """ + Creates a boxed handle + + Args: + length (float): Length of the handle + + handle_pad (float): A minimum difference between handle length and cabinet panel height + """ + + def __init__(self, length=0.24, handle_pad=0.04, *args, **kwargs): + self.handle_pad = handle_pad + super().__init__( + xml="fixtures/handles/boxed_handle.xml", length=length, *args, **kwargs + ) + + def _get_components(self): + """ + Get the geoms of the handle + """ + geom_names = ["handle", "handle_connector_top", "handle_connector_bottom"] + body_names = [] + joint_names = [] + return self._get_elements_by_name(geom_names, body_names, joint_names) + + def _create_handle(self): + """ + Calculates and sets and positions and sizes of each component of the handles + Treats the three types of cabinets separately + """ + + # adjust handle size if necessary + if self.panel_h < self.length + 2 * self.handle_pad: + self.length = self.panel_h - 2 * self.handle_pad + + conn_len = 0.05 + connector_depth = (conn_len / 2) - 0.01 + connector_zpos = (self.length / 2) - 0.01 + + # calculate positions for each component + positions = { + "handle": np.array([0, -conn_len, 0]), + "handle_connector_top": np.array([0, -conn_len / 2, connector_zpos]), + "handle_connector_bottom": np.array([0, -conn_len / 2, -connector_zpos]), + } + sizes = { + "handle": [0.01, 0.01, self.length / 2], + "handle_connector_top": [0.01, 0.01, connector_depth], + "handle_connector_bottom": [0.01, 0.01, connector_depth], + } + eulers = {} + + if self.orientation == "horizontal": + positions["handle_connector_top"][[0, 2]] = positions[ + "handle_connector_top" + ][[2, 0]] + positions["handle_connector_bottom"][[0, 2]] = positions[ + "handle_connector_bottom" + ][[2, 0]] + eulers["handle"] = [0, 1.5708, 0] + + geoms, bodies, joints = self._get_components() + for side in positions.keys(): + for geom in geoms[side]: + if geom is None: + continue + geom.set("pos", a2s(positions[side])) + geom.set("size", a2s(sizes[side])) + + if eulers.get(side) is not None: + geom.set("euler", a2s(eulers[side])) + + +class KnobHandle(Handle): + """ + Creates a knob handle + """ + + def __init__(self, handle_pad=0.07, *args, **kwargs): + super().__init__( + xml="fixtures/handles/knob_handle.xml", + # length=length, + *args, + **kwargs + ) + + # z-direction padding for handle from sides of cabinet + self.handle_pad = handle_pad + + def _get_components(self): + """ + Get the geoms of the handle + """ + geom_names = ["handle"] + body_names = [] + joint_names = [] + return self._get_elements_by_name(geom_names, body_names, joint_names) + + def _create_handle(self): + """ + Calculates and sets and positions and sizes of each component of the handles + """ + + # calculate positions for each component + positions = { + "handle": np.array([0, -0.017, 0]), + } + # radius, depth + sizes = { + "handle": [0.015, 0.017], + } + + geoms, bodies, joints = self._get_components() + for side in positions.keys(): + for geom in geoms[side]: + if geom is None: + continue + geom.set("pos", a2s(positions[side])) + geom.set("size", a2s(sizes[side])) diff --git a/third_party/robocasa/robocasa/models/fixtures/microwave.py b/third_party/robocasa/robocasa/models/fixtures/microwave.py new file mode 100644 index 0000000000000000000000000000000000000000..30a74ec1730fc968230101402a7278f991b026fd --- /dev/null +++ b/third_party/robocasa/robocasa/models/fixtures/microwave.py @@ -0,0 +1,151 @@ +import numpy as np + +import robocasa.utils.object_utils as OU +from robocasa.models.fixtures import Fixture + + +class Microwave(Fixture): + """ + Microwave fixture class. Supports turning on and off the microwave, and opening and closing the door + + Args: + xml (str): path to mjcf xml file + + name (str): name of the object + """ + + def __init__( + self, + xml="fixtures/microwaves/orig_microwave", + name="microwave", + *args, + **kwargs, + ): + super().__init__( + xml=xml, name=name, duplicate_collision_geoms=False, *args, **kwargs + ) + self._turned_on = False + + def set_door_state(self, min, max, env, rng): + """ + Sets how open the door is. Chooses a random amount between min and max. + Min and max are percentages of how open the door is + + Args: + min (float): minimum percentage of how open the door is + + max (float): maximum percentage of how open the door is + + env (MujocoEnv): environment + + rng (np.random.Generator): random number generator + + """ + assert 0 <= min <= 1 and 0 <= max <= 1 and min <= max + + joint_min = 0 + joint_max = np.pi / 2 + + desired_min = joint_min + (joint_max - joint_min) * min + desired_max = joint_min + (joint_max - joint_min) * max + + sign = -1 + + env.sim.data.set_joint_qpos( + "{}_microjoint".format(self.name), + sign * rng.uniform(desired_min, desired_max), + ) + + def get_door_state(self, env): + """ + Args: + env (MujocoEnv): environment + + Returns: + dict: maps door name to a percentage of how open the door is + """ + sim = env.sim + hinge_qpos = sim.data.qpos[sim.model.joint_name2id(f"{self.name}_microjoint")] + hinge_qpos = -hinge_qpos # negate as micro joints are left door hinges + + # convert to percentages + door = OU.normalize_joint_value(hinge_qpos, joint_min=0, joint_max=np.pi / 2) + + return { + "door": door, + } + + def get_state(self): + """ + Returns: + dict: maps turned_on to whether the microwave is turned on + """ + state = dict( + turned_on=self._turned_on, + ) + return state + + @property + def handle_name(self): + return "{}_door_handle".format(self.name) + + @property + def door_name(self): + return "{}_door".format(self.name) + + def update_state(self, env): + """ + If the microwave is open, the state is set to off. Otherwise, if the gripper + is pressing the start button, the microwave will stay/turn on. If the gripper is + pressing the stop button, the microwave will stay/turn off. + + Args: + env (MujocoEnv): The environment to check the state of the microwave in + + """ + start_button_pressed = env.check_contact( + env.robots[0].gripper["right"], "{}_start_button".format(self.name) + ) + stop_button_pressed = env.check_contact( + env.robots[0].gripper["right"], "{}_stop_button".format(self.name) + ) + + door_state = self.get_door_state(env)["door"] + door_open = door_state > 0.005 + + if door_open: + self._turned_on = False + else: + if self._turned_on is True and stop_button_pressed: + self._turned_on = False + elif self._turned_on is False and start_button_pressed: + self._turned_on = True + + def gripper_button_far(self, env, button, th=0.15): + """ + check whether gripper is far from the start button + + Args: + env (MujocoEnv): The environment to check the state of the microwave in + + button (str): button to check + + th (float): threshold for distance between gripper and button + + Returns: + bool: True if gripper is far from the button, False otherwise + """ + assert button in ["start_button", "stop_button"] + button_id = env.sim.model.geom_name2id( + "{}{}".format(self.naming_prefix, button) + ) + button_pos = env.sim.data.geom_xpos[button_id] + gripper_site_pos = env.sim.data.site_xpos[env.robots[0].eef_site_id["right"]] + + gripper_button_far = np.linalg.norm(gripper_site_pos - button_pos) > th + + return gripper_button_far + + @property + def nat_lang(self): + return "microwave" diff --git a/third_party/robocasa/robocasa/models/fixtures/others.py b/third_party/robocasa/robocasa/models/fixtures/others.py new file mode 100644 index 0000000000000000000000000000000000000000..5397a03c54507b570029ccc3879f760f68d2877f --- /dev/null +++ b/third_party/robocasa/robocasa/models/fixtures/others.py @@ -0,0 +1,287 @@ +import xml.etree.ElementTree as ET +from copy import deepcopy + +import numpy as np +from robosuite.models.objects import BoxObject +from robosuite.utils.mjcf_utils import CustomMaterial +from robosuite.utils.mjcf_utils import array_to_string as a2s +from robosuite.utils.mjcf_utils import string_to_array as s2a +from robosuite.utils.mjcf_utils import xml_path_completion + +import robocasa +from robocasa.models.fixtures import Fixture + + +class Box(BoxObject): + """ + Initializes a box object. Mainly used for filling in gaps in the environment like in corners or beneath bottom cabinets + + Args: + pos (list): position of the object + + size (list): size of the object + + name (str): name of the object + + texture (str): path to texture file + + mat_attrib (dict): material attributes + + tex_attrib (dict): texture attributes + """ + + def __init__( + self, + pos, + size, + name="box", + texture="textures/wood/dark_wood_parquet.png", + mat_attrib={"shininess": "0.1"}, + tex_attrib={"type": "cube"}, + rng=None, + *args, + **kwargs + ): + texture = xml_path_completion(texture, root=robocasa.models.assets_root) + material = CustomMaterial( + texture=texture, + tex_name="box", + mat_name="box_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + shared=True, + ) + + super().__init__( + name=name, + material=material, + joints=None, + # divide by 2 per mujoco convention + size=[x / 2 for x in size], + ) + + self.size = size + self.pos = pos + if pos is not None: + self._obj.set("pos", a2s(pos)) + + # for relative positioning + self.origin_offset = np.array([0, 0, 0]) + self.scale = 1 + + if rng is not None: + self.rng = rng + else: + self.rng = np.random.default_rng() + + def set_pos(self, pos): + """ + Set the position of the object + + Args: + pos (list): position of the object + """ + self.pos = pos + self._obj.set("pos", a2s(pos)) + + def update_state(self, env): + pass + + @property + def rot(self): + """ + Returns the rotation of the object only on the z-axis + + Returns: + float: rotation + """ + rot = s2a(self._obj.get("euler", "0.0 0.0 0.0")) + return rot[2] + + +class Wall(BoxObject): + """ + Initializes a wall object. Used for creating walls in the environment + + Args: + name (str): name of the object + + texture (str): path to texture file + + pos (list): position of the object + + quat (list): quaternion of the object + + size (list): size of the object + + wall_side (str): which side the wall is on (back, front, left, right, floor) + + mat_attrib (dict): material attributes + + tex_attrib (dict): texture attributes + + backing (bool): whether this is a backing wall + + backing_extended (list): whether the backing is extended on the left and right + + default_wall_th (float): default thickness of the wall + + default_backing_th (float): default thickness of the backing + """ + + def __init__( + self, + name="wall", + texture="textures/bricks/white_bricks.png", + pos=None, + quat=None, + size=None, + wall_side="back", + mat_attrib={ + "texrepeat": "3 3", + "reflectance": "0.1", + "shininess": "0.1", + "texuniform": "true", + }, + tex_attrib={"type": "2d"}, + # parameters used for alignment + backing=False, + backing_extended=[False, False], + default_wall_th=0.02, + default_backing_th=0.1, + rng=None, + *args, + **kwargs + ): + # change texture if used for backing + if backing: + texture = "textures/flat/light_gray.png" + texture = xml_path_completion(texture, root=robocasa.models.assets_root) + material = CustomMaterial( + texture=texture, + tex_name="wall", + mat_name="wall_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + + self.wall_side = wall_side + # set the rotation according to which side the wall is on + if self.wall_side is not None: + quat = self.get_quat() + + # align everything to account for thickness & backing + if self.wall_side == "floor": + size[0] += default_wall_th * 2 + size[1] += default_wall_th * 2 + pos[2] -= size[2] + if backing: + pos[2] -= default_wall_th * 2 + else: + size[0] += default_wall_th * 2 + shift = size[2] if not backing else size[2] + default_wall_th * 2 + if self.wall_side == "left": + pos[0] -= shift + elif self.wall_side == "right": + pos[0] += shift + elif self.wall_side == "back": + pos[1] += shift + elif self.wall_side == "front": + pos[1] -= shift + + if backing: + size[1] += default_wall_th + default_backing_th + pos[2] -= default_wall_th + default_backing_th + + # extend left/right side to form a perfect box + if backing_extended[0]: + size[0] += default_backing_th + if self.wall_side in ["left", "right"]: + pos[1] += default_backing_th + else: + pos[0] -= default_backing_th + if backing_extended[1]: + size[0] += default_backing_th + if self.wall_side in ["left", "right"]: + pos[1] -= default_backing_th + else: + pos[0] += default_backing_th + + super().__init__( + name=name, material=material, joints=None, size=size, *args, **kwargs + ) + + self.pos = pos + if pos is not None: + self._obj.set("pos", a2s(pos)) + if quat is not None: + self._obj.set("quat", a2s(quat)) + + if rng is not None: + self.rng = rng + else: + self.rng = np.random.default_rng() + + def set_pos(self, pos): + """ + Set the position of the object + + Args: + pos (list): position of the object + """ + self.pos = pos + self._obj.set("pos", a2s(pos)) + + def get_quat(self): + """ + Returns the quaternion of the object based on the wall side + + Returns: + list: quaternion + """ + side_rots = { + "back": [-0.707, 0.707, 0, 0], + "front": [0, 0, 0.707, -0.707], + "left": [0.5, 0.5, -0.5, -0.5], + "right": [0.5, -0.5, -0.5, 0.5], + "floor": [0.707, 0, 0, 0.707], + } + if self.wall_side not in side_rots: + raise ValueError() + return side_rots[self.wall_side] + + def update_state(self, env): + pass + + +class Floor(Wall): + def __init__( + self, + size, + name="wall", + texture="textures/bricks/red_bricks.png", + mat_attrib={ + "texrepeat": "2 2", + "texuniform": "true", + "reflectance": "0.1", + "shininess": "0.1", + }, + *args, + **kwargs + ): + # swap x, y axes due to rotation + size = [size[1], size[0], size[2]] + + texture = xml_path_completion(texture, root=robocasa.models.assets_root) + + # everything is the same except the plane is rotated to be horizontal + super().__init__( + name, + texture, + # horizontal plane + wall_side="floor", + size=size, + mat_attrib=mat_attrib, + *args, + **kwargs + ) diff --git a/third_party/robocasa/robocasa/models/objects/__init__.py b/third_party/robocasa/robocasa/models/objects/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6e58d64f52731abfe20fb3bd9fdfce135861dd58 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/__init__.py @@ -0,0 +1,13 @@ +from robosuite.models.objects import * +from robosuite.utils import * + +from .xml_objects import ( + CoffeeMachinePodObject, + CoffeeMachineBodyObject, + CoffeeMachineLidObject, + CoffeeMachineBaseObject, + DrawerObject, + LongDrawerObject, +) +from .composite import * +from .composite_body import * diff --git a/third_party/robocasa/robocasa/models/objects/composite/__init__.py b/third_party/robocasa/robocasa/models/objects/composite/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1ac011def690701e1ba67ab06200f8a40600d8cc --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite/__init__.py @@ -0,0 +1,6 @@ +from .box_pattern_object import BoxPatternObject +from .needle import NeedleObject +from .ring_tripod import RingTripodObject +from .bin import Bin +from .lid import Lid +from .pot_with_handles import PotWithHandlesObject diff --git a/third_party/robocasa/robocasa/models/objects/composite/bin.py b/third_party/robocasa/robocasa/models/objects/composite/bin.py new file mode 100644 index 0000000000000000000000000000000000000000..777ba77ff1bf1942635711c475c7404a99af3a1c --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite/bin.py @@ -0,0 +1,211 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import CustomMaterial, add_to_dict + + +class Bin(CompositeObject): + """ + Generates a four-walled bin container with an open top. + Args: + name (str): Name of this Bin object + bin_size (3-array): (x,y,z) full size of bin + wall_thickness (float): How thick to make walls of bin + transparent_walls (bool): If True, walls will be semi-translucent + friction (3-array or None): If specified, sets friction values for this bin. None results in default values + density (float): Density value to use for all geoms. Defaults to 1000 + use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored + rgba (4-array or None): If specified, sets rgba values for all geoms. None results in default values + material: If specified, use this material + upside_down (bool): if True, construct and initialize the Bin so the bottom geom is at the top + """ + + def __init__( + self, + name, + bin_size=(0.3, 0.3, 0.15), + wall_thickness=0.01, + transparent_walls=True, + friction=None, + density=1000.0, + use_texture=True, + rgba=(0.2, 0.1, 0.0, 1.0), + material=None, + upside_down=False, + add_second_base=False, + transparent_base=False, + ): + # Set name + self._name = name + + # Set object attributes + self.bin_size = np.array(bin_size) + self.wall_thickness = wall_thickness + self.transparent_walls = transparent_walls + self.friction = friction if friction is None else np.array(friction) + self.density = density + self.use_texture = use_texture + self.rgba = rgba + self.bin_mat_name = "dark_wood_mat" + + # if box should be constructed and initialized upside down + self.upside_down = upside_down + + # if box should have a second base (so it will be a closed box) + self.add_second_base = add_second_base + if self.add_second_base: + assert not self.upside_down + + # if base(s) should be transparent + self.transparent_base = transparent_base + + self.has_material = material is not None + if self.has_material: + assert isinstance(material, CustomMaterial) + self.material = material + self.bin_mat_name = self.material.mat_attrib["name"] + else: + # default material + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "3 3", + "specular": "0.4", + "shininess": "0.1", + } + bin_mat = CustomMaterial( + texture="WoodDark", + tex_name="dark_wood", + mat_name=self.bin_mat_name, + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.material = bin_mat + + # Element references + self._base_geom = "base" + if self.add_second_base: + self._second_base_geom = "base2" + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + self.append_material(self.material) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": self.bin_size / 2.0, + "name": self.name, + "locations_relative_to_center": True, + "obj_types": "all", + "density": self.density, + } + obj_args = {} + + # Base(s) + base_geom_loc = (0, 0, -(self.bin_size[2] - self.wall_thickness) / 2) + if self.upside_down: + base_geom_loc = ( + base_geom_loc[0], + base_geom_loc[1], + -1.0 * base_geom_loc[2], + ) + if self.transparent_base: + base_rgba = (1.0, 1.0, 1.0, 0.3) + base_mat = None + else: + base_rgba = None if self.use_texture else self.rgba + base_mat = self.bin_mat_name if self.use_texture else None + + base_geom_names = [self._base_geom] + base_geom_locs = [base_geom_loc] + if self.add_second_base: + base_geom_names.append(self._second_base_geom) + base_geom_locs.append( + (base_geom_loc[0], base_geom_loc[1], -1.0 * base_geom_loc[2]) + ) + + for base_g_name, base_g_loc in zip(base_geom_names, base_geom_locs): + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=base_g_loc, + geom_quats=(1, 0, 0, 0), + geom_sizes=( + np.array((self.bin_size[0], self.bin_size[1], self.wall_thickness)) + - np.array((self.wall_thickness, self.wall_thickness, 0)) + ) + / 2, + geom_names=base_g_name, + geom_rgbas=base_rgba, + geom_materials=base_mat, + geom_frictions=self.friction, + ) + + # Walls + x_vals = np.array( + [ + 0, + -(self.bin_size[0] - self.wall_thickness) / 2, + 0, + (self.bin_size[0] - self.wall_thickness) / 2, + ] + ) + y_vals = np.array( + [ + -(self.bin_size[1] - self.wall_thickness) / 2, + 0, + (self.bin_size[1] - self.wall_thickness) / 2, + 0, + ] + ) + w_vals = np.array( + [self.bin_size[0], self.bin_size[1], self.bin_size[0], self.bin_size[1]] + ) + r_vals = np.array([np.pi / 2, 0, -np.pi / 2, np.pi]) + if self.transparent_walls: + wall_rgba = (1.0, 1.0, 1.0, 0.3) + wall_mat = None + else: + wall_rgba = None if self.use_texture else self.rgba + wall_mat = self.bin_mat_name if self.use_texture else None + for i, (x, y, w, r) in enumerate(zip(x_vals, y_vals, w_vals, r_vals)): + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(x, y, 0), + geom_quats=T.convert_quat( + T.axisangle2quat(np.array([0, 0, r])), to="wxyz" + ), + geom_sizes=(self.wall_thickness / 2, w / 2, self.bin_size[2] / 2), + geom_names=f"wall{i}", + geom_rgbas=wall_rgba, + geom_materials=wall_mat, + geom_frictions=self.friction, + ) + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args + + @property + def base_geoms(self): + """ + Returns: + list of str: geom names corresponding to bin base + """ + return [self.correct_naming(self._base_geom)] diff --git a/third_party/robocasa/robocasa/models/objects/composite/box_pattern_object.py b/third_party/robocasa/robocasa/models/objects/composite/box_pattern_object.py new file mode 100644 index 0000000000000000000000000000000000000000..7affdf6c057c36545c09dbae48e673fe5c5a919d --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite/box_pattern_object.py @@ -0,0 +1,126 @@ +import numpy as np + +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import add_to_dict +import robosuite.utils.transform_utils as T + + +class BoxPatternObject(CompositeObject): + """ + Generates shapes by using a pattern of unit-size boxes. + + Args: + name (str): Name of this Needle object + """ + + def __init__( + self, + name, + unit_size, + pattern, + rgba=None, + material=None, + density=100.0, + # solref=[0.02, 1.], + # solimp=[0.9, 0.95, 0.001], + friction=None, + ): + """ + Args: + unit_size (3d array / list): size of each unit block in each dimension + + pattern (3d array / list): array of normalized sizes specifying the + geometry of the shape. A "0" indicates the absence of a cube and + a "1" indicates the presence of a full unit block. The dimensions + correspond to z, x, and y respectively. + """ + self._name = name + self.rgba = rgba + self.material = material + self.density = density + self.friction = friction + + # number of blocks in z, x, and y + self.pattern = np.array(pattern) + self.nz, self.nx, self.ny = self.pattern.shape + self.unit_size = unit_size + self.total_size = [ + self.nx * unit_size[0], + self.ny * unit_size[1], + self.nz * unit_size[2], + ] + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + if self.material is not None: + self.append_material(self.material) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": self.total_size, + "name": self.name, + "locations_relative_to_center": False, + "obj_types": "all", + "density": self.density, + } + obj_args = {} + + geom_locations = [] + geom_sizes = [] + geom_names = [] + nz, nx, ny = self.pattern.shape + for k in range(nz): + for i in range(nx): + for j in range(ny): + if self.pattern[k, i, j] > 0: + geom_sizes.append( + [ + self.unit_size[0], + self.unit_size[1], + self.unit_size[2], + ] + ) + geom_locations.append( + [ + i * 2.0 * self.unit_size[0], + j * 2.0 * self.unit_size[1], + k * 2.0 * self.unit_size[2], + ] + ) + geom_names.append("{}_{}_{}".format(k, i, j)) + + # geom_rgbas = [rgba for _ in geom_locations] + # geom_frictions = [friction for _ in geom_locations] + for i in range(len(geom_locations)): + add_to_dict( + dic=obj_args, + geom_types="box", + # needle geom needs to be offset from boundary in (x, z) + geom_locations=tuple(geom_locations[i]), + geom_quats=(1, 0, 0, 0), + geom_sizes=tuple(geom_sizes[i]), + geom_names=geom_names[i], + geom_rgbas=self.rgba, + geom_materials=self.material.name + if self.material is not None + else None, + geom_frictions=None, + ) + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args diff --git a/third_party/robocasa/robocasa/models/objects/composite/lid.py b/third_party/robocasa/robocasa/models/objects/composite/lid.py new file mode 100644 index 0000000000000000000000000000000000000000..3eb602bd9308bbe387e4648939d61c00c32f5520 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite/lid.py @@ -0,0 +1,136 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import CustomMaterial, add_to_dict + + +class Lid(CompositeObject): + """ + Generates a square lid with a simple handle. + Args: + name (str): Name of this Lid object + lid_size (3-array): (length, width, thickness) of lid + handle_size (3-array): (thickness, length, height) of handle + transparent (bool): If True, lid will be semi-translucent + friction (3-array or None): If specified, sets friction values for this lid. None results in default values + density (float): Density value to use for all geoms. Defaults to 1000 + use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored + rgba (4-array or None): If specified, sets rgba values for all geoms. None results in default values + """ + + def __init__( + self, + name, + lid_size=(0.3, 0.3, 0.01), + handle_size=(0.02, 0.08, 0.03), + transparent=True, + friction=None, + density=250.0, + use_texture=True, + rgba=(0.2, 0.1, 0.0, 1.0), + ): + # Set name + self._name = name + + # Set object attributes + self.lid_size = np.array(lid_size) + self.handle_size = np.array(handle_size) + self.transparent = transparent + self.friction = friction if friction is None else np.array(friction) + self.density = density + self.use_texture = use_texture + self.rgba = rgba + self.lid_mat_name = "dark_wood_mat" + + # Element references + self._handle_geom = "handle" + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "3 3", + "specular": "0.4", + "shininess": "0.1", + } + lid_mat = CustomMaterial( + texture="WoodDark", + tex_name="dark_wood", + mat_name=self.lid_mat_name, + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(lid_mat) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + full_height = self.lid_size[2] + self.handle_size[2] + full_size = np.array([self.lid_size[0], self.lid_size[1], full_height]) + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": full_size / 2.0, + "name": self.name, + "locations_relative_to_center": True, + "obj_types": "all", + } + obj_args = {} + + # Top + if self.transparent: + top_rgba = (1.0, 1.0, 1.0, 0.3) + top_mat = None + else: + top_rgba = None if self.use_texture else self.rgba + top_mat = self.lid_mat_name if self.use_texture else None + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(0, 0, (-full_size[2] + self.lid_size[2]) / 2), + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array((full_size[0], full_size[1], self.lid_size[2])) / 2, + geom_names="top", + geom_rgbas=top_rgba, + geom_materials=top_mat, + geom_frictions=self.friction, + density=self.density, + ) + + # Handle + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(0, 0, (full_size[2] - self.handle_size[2]) / 2), + geom_quats=(1, 0, 0, 0), + geom_sizes=self.handle_size / 2, + geom_names=self._handle_geom, + geom_rgbas=None if self.use_texture else self.rgba, + geom_materials=self.lid_mat_name if self.use_texture else None, + geom_frictions=self.friction, + density=self.density * 2, + ) + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args + + @property + def handle_geoms(self): + """ + Returns: + list of str: geom names corresponding to lid handle + """ + return [self.correct_naming(self._handle_geom)] diff --git a/third_party/robocasa/robocasa/models/objects/composite/needle.py b/third_party/robocasa/robocasa/models/objects/composite/needle.py new file mode 100644 index 0000000000000000000000000000000000000000..9dc6bb1fea50a76ba8c681643354596a7676e797 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite/needle.py @@ -0,0 +1,109 @@ +import numpy as np + +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import add_to_dict, CustomMaterial +import robosuite.utils.transform_utils as T + + +class NeedleObject(CompositeObject): + """ + Generates a needle with a handle (used in Threading task) + + Args: + name (str): Name of this Needle object + """ + + def __init__( + self, + name, + ): + + ### TODO: make this object more general (with more args and configuration options) later ### + + # Set object attributes + self._name = name + self.needle_mat_name = "darkwood_mat" + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "1 1", + "specular": "0.4", + "shininess": "0.1", + } + needle_mat = CustomMaterial( + texture="WoodDark", + tex_name="darkwood", + mat_name="darkwood_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(needle_mat) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": [0.02, 0.08, 0.02], + "name": self.name, + "locations_relative_to_center": False, + "obj_types": "all", + "density": 100.0, + } + obj_args = {} + + # make a skinny needle object with a large handle + needle_size = [0.005, 0.06, 0.005] + handle_size = [0.02, 0.02, 0.02] + + # Needle + add_to_dict( + dic=obj_args, + geom_types="box", + # needle geom needs to be offset from boundary in (x, z) + geom_locations=( + (handle_size[0] - needle_size[0]), + 0.0, + (handle_size[2] - needle_size[2]), + ), + geom_quats=(1, 0, 0, 0), + geom_sizes=tuple(needle_size), + geom_names="needle", + geom_rgbas=None, + geom_materials=self.needle_mat_name, + # make the needle low friction to ensure easy insertion + geom_frictions=(0.3, 5e-3, 1e-4), + ) + + # Handle + add_to_dict( + dic=obj_args, + geom_types="box", + # handle geom needs to be offset in y + geom_locations=(0.0, 2.0 * needle_size[1], 0.0), + geom_quats=(1, 0, 0, 0), + geom_sizes=tuple(handle_size), + geom_names="handle", + geom_rgbas=None, + geom_materials=self.needle_mat_name, + geom_frictions=None, + ) + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args diff --git a/third_party/robocasa/robocasa/models/objects/composite/pot_with_handles.py b/third_party/robocasa/robocasa/models/objects/composite/pot_with_handles.py new file mode 100644 index 0000000000000000000000000000000000000000..d097cb515a2eddb0197fddc136418b60157ea448 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite/pot_with_handles.py @@ -0,0 +1,404 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import ( + BLUE, + GREEN, + RED, + CustomMaterial, + add_to_dict, + array_to_string, +) + + +class PotWithHandlesObject(CompositeObject): + """ + Generates the Pot object with side handles (used in TwoArmLift) + + Args: + name (str): Name of this Pot object + + body_half_size (3-array of float): If specified, defines the (x,y,z) half-dimensions of the main pot + body. Otherwise, defaults to [0.07, 0.07, 0.07] + + handle_radius (float): Determines the pot handle radius + + handle_length (float): Determines the pot handle length + + handle_width (float): Determines the pot handle width + + handle_friction (float): Friction value to use for pot handles. Defauls to 1.0 + + density (float): Density value to use for all geoms. Defaults to 1000 + + use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored + + rgba_body (4-array or None): If specified, sets pot body rgba values + + rgba_handle_0 (4-array or None): If specified, sets handle 0 rgba values + + rgba_handle_1 (4-array or None): If specified, sets handle 1 rgba values + + solid_handle (bool): If true, uses a single geom to represent the handle + + thickness (float): How thick to make the pot body walls + """ + + def __init__( + self, + name, + body_half_size=(0.07, 0.07, 0.07), + handle_radius=0.01, + handle_length=0.09, + handle_width=0.09, + handle_friction=1.0, + density=1000, + use_texture=True, + rgba_body=None, + rgba_handle_0=None, + rgba_handle_1=None, + solid_handle=False, + thickness=0.01, # For body + ): + # Set name + self._name = name + + # Set object attributes + self.body_half_size = np.array(body_half_size) + self.thickness = thickness + self.handle_radius = handle_radius + self.handle_length = handle_length + self.handle_width = handle_width + self.handle_friction = handle_friction + self.density = density + self.use_texture = use_texture + self.rgba_body = np.array(rgba_body) if rgba_body else RED + self.rgba_handle_0 = np.array(rgba_handle_0) if rgba_handle_0 else GREEN + self.rgba_handle_1 = np.array(rgba_handle_1) if rgba_handle_1 else BLUE + self.solid_handle = solid_handle + + # Element references to be filled when generated + self._handle0_geoms = None + self._handle1_geoms = None + self.pot_base = None + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "1 1", + "specular": "0.4", + "shininess": "0.1", + } + redwood = CustomMaterial( + texture="WoodRed", + tex_name="redwood", + mat_name="pot_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + greenwood = CustomMaterial( + texture="WoodGreen", + tex_name="greenwood", + mat_name="handle0_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + bluewood = CustomMaterial( + texture="WoodBlue", + tex_name="bluewood", + mat_name="handle1_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(redwood) + self.append_material(greenwood) + self.append_material(bluewood) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + full_size = np.array( + ( + self.body_half_size, + self.body_half_size + self.handle_length * 2, + self.body_half_size, + ) + ) + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": full_size / 2.0, + "name": self.name, + "locations_relative_to_center": True, + "obj_types": "all", + } + site_attrs = [] + obj_args = {} + + # Initialize geom lists + self._handle0_geoms = [] + self._handle1_geoms = [] + + # Add main pot body + # Base geom + name = f"base" + self.pot_base = [name] + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(0, 0, -self.body_half_size[2] + self.thickness / 2), + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array( + [self.body_half_size[0], self.body_half_size[1], self.thickness / 2] + ), + geom_names=name, + geom_rgbas=None if self.use_texture else self.rgba_body, + geom_materials="pot_mat" if self.use_texture else None, + geom_frictions=None, + density=self.density, + ) + + # Walls + x_off = np.array( + [ + 0, + -(self.body_half_size[0] - self.thickness / 2), + 0, + self.body_half_size[0] - self.thickness / 2, + ] + ) + y_off = np.array( + [ + -(self.body_half_size[1] - self.thickness / 2), + 0, + self.body_half_size[1] - self.thickness / 2, + 0, + ] + ) + w_vals = np.array( + [ + self.body_half_size[0], + self.body_half_size[1], + self.body_half_size[0], + self.body_half_size[1], + ] + ) + r_vals = np.array([np.pi / 2, 0, -np.pi / 2, np.pi]) + for i, (x, y, w, r) in enumerate(zip(x_off, y_off, w_vals, r_vals)): + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(x, y, 0), + geom_quats=T.convert_quat( + T.axisangle2quat(np.array([0, 0, r])), to="wxyz" + ), + geom_sizes=np.array([self.thickness / 2, w, self.body_half_size[2]]), + geom_names=f"body{i}", + geom_rgbas=None if self.use_texture else self.rgba_body, + geom_materials="pot_mat" if self.use_texture else None, + geom_frictions=None, + density=self.density, + ) + + # Add handles + main_bar_size = np.array( + [ + self.handle_width / 2 + self.handle_radius, + self.handle_radius, + self.handle_radius, + ] + ) + side_bar_size = np.array( + [self.handle_radius, self.handle_length / 2, self.handle_radius] + ) + handle_z = self.body_half_size[2] - self.handle_radius + for i, (g_list, handle_side, rgba) in enumerate( + zip( + [self._handle0_geoms, self._handle1_geoms], + [1.0, -1.0], + [self.rgba_handle_0, self.rgba_handle_1], + ) + ): + handle_center = np.array( + ( + 0, + handle_side * (self.body_half_size[1] + self.handle_length), + handle_z, + ) + ) + # Solid handle case + if self.solid_handle: + handle_center = np.array( + ( + 0, + handle_side * (self.body_half_size[1] + self.handle_length / 2), + handle_z, + ) + ) + name = f"handle{i}" + g_list.append(name) + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=handle_center, + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array( + [ + self.handle_width / 2, + self.handle_length / 2, + self.handle_radius, + ] + ), + geom_names=name, + geom_rgbas=None if self.use_texture else rgba, + geom_materials=f"handle{i}_mat" if self.use_texture else None, + geom_frictions=(self.handle_friction, 0.005, 0.0001), + density=self.density, + ) + # Hollow handle case + else: + # Center bar + name = f"handle{i}_c" + g_list.append(name) + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=handle_center, + geom_quats=(1, 0, 0, 0), + geom_sizes=main_bar_size, + geom_names=name, + geom_rgbas=None if self.use_texture else rgba, + geom_materials=f"handle{i}_mat" if self.use_texture else None, + geom_frictions=(self.handle_friction, 0.005, 0.0001), + density=self.density, + ) + # Side bars + for bar_side, suffix in zip([-1.0, 1.0], ["-", "+"]): + name = f"handle{i}_{suffix}" + g_list.append(name) + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=( + bar_side * self.handle_width / 2, + handle_side + * (self.body_half_size[1] + self.handle_length / 2), + handle_z, + ), + geom_quats=(1, 0, 0, 0), + geom_sizes=side_bar_size, + geom_names=name, + geom_rgbas=None if self.use_texture else rgba, + geom_materials=f"handle{i}_mat" if self.use_texture else None, + geom_frictions=(self.handle_friction, 0.005, 0.0001), + density=self.density, + ) + # Add relevant site + handle_site = self.get_site_attrib_template() + handle_name = f"handle{i}" + handle_site.update( + { + "name": handle_name, + "pos": array_to_string( + handle_center - handle_side * np.array([0, 0.005, 0]) + ), + "size": "0.005", + "rgba": rgba, + } + ) + site_attrs.append(handle_site) + # Add to important sites + self._important_sites[f"handle{i}"] = self.naming_prefix + handle_name + + # Add pot body site + pot_site = self.get_site_attrib_template() + center_name = "center" + pot_site.update( + { + "name": center_name, + "size": "0.005", + } + ) + site_attrs.append(pot_site) + # Add to important sites + self._important_sites["center"] = self.naming_prefix + center_name + + # Add back in base args and site args + obj_args.update(base_args) + obj_args["sites"] = site_attrs # All sites are part of main (top) body + + # Return this dict + return obj_args + + @property + def handle_distance(self): + + """ + Calculates how far apart the handles are + + Returns: + float: handle distance + """ + return self.body_half_size[1] * 2 + self.handle_length * 2 + + @property + def handle0_geoms(self): + """ + Returns: + list of str: geom names corresponding to handle0 (green handle) + """ + return self.correct_naming(self._handle0_geoms) + + @property + def handle1_geoms(self): + """ + Returns: + list of str: geom names corresponding to handle1 (blue handle) + """ + return self.correct_naming(self._handle1_geoms) + + @property + def handle_geoms(self): + """ + Returns: + list of str: geom names corresponding to both handles + """ + return self.handle0_geoms + self.handle1_geoms + + @property + def important_sites(self): + """ + Returns: + dict: In addition to any default sites for this object, also provides the following entries + + :`'handle0'`: Name of handle0 location site + :`'handle1'`: Name of handle1 location site + """ + # Get dict from super call and add to it + dic = super().important_sites + dic.update(self._important_sites) + return dic + + @property + def bottom_offset(self): + return np.array([0, 0, -1 * self.body_half_size[2]]) + + @property + def top_offset(self): + return np.array([0, 0, self.body_half_size[2]]) + + @property + def horizontal_radius(self): + return np.sqrt(2) * (max(self.body_half_size) + self.handle_length) diff --git a/third_party/robocasa/robocasa/models/objects/composite/ring_tripod.py b/third_party/robocasa/robocasa/models/objects/composite/ring_tripod.py new file mode 100644 index 0000000000000000000000000000000000000000..11c9079b752d02c7f4ba3f9dd9fc9dbb7cbf33ef --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite/ring_tripod.py @@ -0,0 +1,200 @@ +import numpy as np + +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import add_to_dict +from robosuite.utils.mjcf_utils import CustomMaterial +import robosuite.utils.transform_utils as T + + +class RingTripodObject(CompositeObject): + """ + Generates a tripod base with a small ring for threading a needle through it (used in Threading task) + + Args: + name (str): Name of this RingTripod object + """ + + def __init__( + self, + name, + ): + + ### TODO: make this object more general (with more args and configuration options) later ### + + # Set object attributes + self._name = name + self.tripod_mat_name = "lightwood_mat" + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "1 1", + "specular": "0.4", + "shininess": "0.1", + } + tripod_mat = CustomMaterial( + texture="WoodLight", + tex_name="lightwood", + mat_name="lightwood_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(tripod_mat) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + total_size = (0.05, 0.05, 0.1) + base_args = { + "total_size": total_size, + "name": self.name, + "locations_relative_to_center": False, + "obj_types": "all", + "density": 100.0, + # NOTE: this lower value of solref allows the thin hole wall to avoid penetration through it + "solref": (0.02, 1.0), + "solimp": (0.9, 0.95, 0.001), + } + obj_args = {} + + # pattern for threading ring + unit_size = [0.005, 0.002, 0.002] + pattern = np.ones((6, 1, 6)) + for i in range(1, 5): + pattern[i][0][1:5] = np.zeros(4) + ring_size = [ + unit_size[0] * pattern.shape[1], + unit_size[1] * pattern.shape[2], + unit_size[2] * pattern.shape[0], + ] + self.ring_size = np.array(ring_size) + + # ring offset for where the ring is located relative to the (0, 0, 0) corner + ring_offset = [ + total_size[0] - ring_size[0], + total_size[1] - ring_size[1], + 2.0 * (total_size[2] - ring_size[2]), + ] + + # RING-GEOMS: use the pattern to instantiate geoms corresponding to the threading ring + nz, nx, ny = pattern.shape + self.num_ring_geoms = 0 + for k in range(nz): + for i in range(nx): + for j in range(ny): + if pattern[k, i, j] > 0: + add_to_dict( + dic=obj_args, + geom_types="box", + # needle geom needs to be offset from boundary in (x, z) + geom_locations=( + (i * 2.0 * unit_size[0]) + ring_offset[0], + (j * 2.0 * unit_size[1]) + ring_offset[1], + (k * 2.0 * unit_size[2]) + ring_offset[2], + ), + geom_quats=(1, 0, 0, 0), + geom_sizes=tuple(unit_size), + geom_names="ring_{}".format(self.num_ring_geoms), + geom_rgbas=None, + geom_materials=self.tripod_mat_name, + # make the ring low friction to ensure easy insertion + geom_frictions=(0.3, 5e-3, 1e-4), + ) + self.num_ring_geoms += 1 + + # TRIPOD-GEOMS: legs of the tripod + tripod_capsule_r = 0.01 + tripod_capsule_h = 0.03 + tripod_geom_locations = [ + (0.0, 0.0, 0.0), + (0.0, 2.0 * total_size[1] - 2.0 * tripod_capsule_r, 0.0), + ( + 2.0 * total_size[0] - 2.0 * tripod_capsule_r, + total_size[1] - tripod_capsule_r, + 0.0, + ), + ] + # rotate the legs to resemble a tripod + tripod_center = np.array([total_size[0], total_size[1], 0.0]) + xy_offset = np.array([tripod_capsule_r, tripod_capsule_r, 0.0]) + rotation_angle = -np.pi / 6.0 # 30 degrees + tripod_geom_quats = [] + for i in range(3): + capsule_loc = np.array(tripod_geom_locations[i]) + xy_offset + capsule_loc[2] = 0.0 # only care about location in x-y plane + vec_to_center = tripod_center - capsule_loc + vec_to_center = vec_to_center / np.linalg.norm(vec_to_center) + # cross-product with z unit vector to get vector to rotate about + rot_vec = np.cross(vec_to_center, np.array([0.0, 0.0, 1.0])) + rot_quat = T.mat2quat( + T.rotation_matrix(angle=rotation_angle, direction=rot_vec) + ) + tripod_geom_quats.append(T.convert_quat(rot_quat, to="wxyz")) + + for i in range(3): + add_to_dict( + dic=obj_args, + geom_types="capsule", + geom_locations=tripod_geom_locations[i], + geom_quats=tripod_geom_quats[i], + geom_sizes=(tripod_capsule_r, tripod_capsule_h), + geom_names="tripod_{}".format(i), + geom_rgbas=None, + geom_materials=self.tripod_mat_name, + geom_frictions=None, + ) + + # POST-GEOMS: mounted base + post + base_thickness = 0.005 + post_size = 0.005 + post_geom_sizes = [ + (total_size[0], total_size[1], base_thickness), + ( + post_size, + post_size, + total_size[2] + - ring_size[2] + - base_thickness + - tripod_capsule_r + - tripod_capsule_h, + ), + ] + post_geom_locations = [ + (0.0, 0.0, 2.0 * (tripod_capsule_r + tripod_capsule_h)), + ( + total_size[0] - post_size, + total_size[1] - post_size, + 2.0 * (tripod_capsule_r + tripod_capsule_h + base_thickness), + ), + ] + for i in range(2): + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=post_geom_locations[i], + geom_quats=(1, 0, 0, 0), + geom_sizes=post_geom_sizes[i], + geom_names="post_{}".format(i), + geom_rgbas=None, + geom_materials=self.tripod_mat_name, + geom_frictions=None, + ) + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args diff --git a/third_party/robocasa/robocasa/models/objects/composite_body/__init__.py b/third_party/robocasa/robocasa/models/objects/composite_body/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dcea55930782409ac0c9dc2ba09a1b4432fd5e58 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite_body/__init__.py @@ -0,0 +1,8 @@ +from .cup import CupObject +from .coffee_machine import CoffeeMachineObject +from .stacked_cylinder import StackedCylinderObject +from .inverse_stacked_cylinder import InverseStackedCylinderObject +from .stacked_box import StackedBoxObject +from .sliding_box import SlidingBoxObject +from .bin_with_handles import BinWithHandles +from .spray_bottle import SprayBottleObject diff --git a/third_party/robocasa/robocasa/models/objects/composite_body/bin_with_handles.py b/third_party/robocasa/robocasa/models/objects/composite_body/bin_with_handles.py new file mode 100644 index 0000000000000000000000000000000000000000..ef35b5e9f2f0a3e1615572596b399f9c1d6c6cdd --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite_body/bin_with_handles.py @@ -0,0 +1,162 @@ +from robosuite.models.objects import CompositeBodyObject, BoxObject, Bin +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial + + +class BinWithHandles(CompositeBodyObject): + """ + Bin with simple square handles on each side. + """ + + def __init__( + self, + name, + bin_size, + bin_wall_thickness, + bin_transparent_walls, + bin_upside_down, + center_handle_size, + adjacent_handle_size, + joints="default", + rgba=(0.2, 0.1, 0.0, 1.0), + material=None, + density=1000.0, + friction=None, + ): + + # Object properties + + # FULL size of bin + self.bin_size = list(bin_size) + self.bin_wall_thickness = bin_wall_thickness + self.bin_transparent_walls = bin_transparent_walls + self.bin_upside_down = bin_upside_down + + # half-sizes of box geom used for center part of handle (which you grab) + self.center_handle_size = list(center_handle_size) + + # half-sizes of box geoms used for adjacent parts of handle (not grabbed) + self.adjacent_handle_size = list(adjacent_handle_size) + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + + # bin + self.bin = Bin( + name="bin", + bin_size=self.bin_size, + wall_thickness=self.bin_wall_thickness, + transparent_walls=self.bin_transparent_walls, + rgba=rgba, + material=material, + density=density, + friction=friction, + upside_down=bin_upside_down, + ) + objects.append(self.bin) + object_locations.append([0.0, 0.0, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # handles on each side + + left_handle_1_loc = [ + 0.0, + -( + self.bin_size[1] / 2.0 + + 2.0 * self.adjacent_handle_size[1] + + self.center_handle_size[1] + ), + 0.0, + ] + left_handle_1_size = self.center_handle_size + + left_handle_2_loc = [ + (self.center_handle_size[0] - self.adjacent_handle_size[0]), + -(self.bin_size[1] / 2.0 + self.adjacent_handle_size[1]), + 0.0, + ] + left_handle_2_size = self.adjacent_handle_size + + left_handle_3_loc = [ + -(self.center_handle_size[0] - self.adjacent_handle_size[0]), + -(self.bin_size[1] / 2.0 + self.adjacent_handle_size[1]), + 0.0, + ] + left_handle_3_size = self.adjacent_handle_size + + right_handle_1_loc = [ + 0.0, + ( + self.bin_size[1] / 2.0 + + 2.0 * self.adjacent_handle_size[1] + + self.center_handle_size[1] + ), + 0.0, + ] + right_handle_1_size = self.center_handle_size + + right_handle_2_loc = [ + (self.center_handle_size[0] - self.adjacent_handle_size[0]), + (self.bin_size[1] / 2.0 + self.adjacent_handle_size[1]), + 0.0, + ] + right_handle_2_size = self.adjacent_handle_size + + right_handle_3_loc = [ + -(self.center_handle_size[0] - self.adjacent_handle_size[0]), + (self.bin_size[1] / 2.0 + self.adjacent_handle_size[1]), + 0.0, + ] + right_handle_3_size = self.adjacent_handle_size + + handle_locs = [ + left_handle_1_loc, + left_handle_2_loc, + left_handle_3_loc, + right_handle_1_loc, + right_handle_2_loc, + right_handle_3_loc, + ] + handle_sizes = [ + left_handle_1_size, + left_handle_2_size, + left_handle_3_size, + right_handle_1_size, + right_handle_2_size, + right_handle_3_size, + ] + handle_ind = 1 + for b_loc, b_size in zip(handle_locs, handle_sizes): + this_handle = BoxObject( + name="handle_{}".format(handle_ind), + size=b_size, + rgba=rgba, + material=material, + density=density, + friction=friction, + joints=None, + ) + objects.append(this_handle) + object_locations.append(b_loc) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + handle_ind += 1 + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + # total_size=body_total_size, + # locations_relative_to_corner=True, + ) diff --git a/third_party/robocasa/robocasa/models/objects/composite_body/coffee_machine.py b/third_party/robocasa/robocasa/models/objects/composite_body/coffee_machine.py new file mode 100644 index 0000000000000000000000000000000000000000..a2f73d0373f5595e7cdfe96342b8f44bc646b905 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite_body/coffee_machine.py @@ -0,0 +1,246 @@ +from robosuite.models.objects import CompositeBodyObject, BoxObject +from robocasa.models.objects.composite_body.cup import ( + CupObject, +) +from robocasa.models.objects.xml_objects import ( + CoffeeMachineBodyObject, + CoffeeMachineLidObject, + CoffeeMachineBaseObject, +) +import numpy as np + +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial + + +class CoffeeMachineObject(CompositeBodyObject): + """ + Coffee machine object with a lid fixed on a hinge joint. + """ + + def __init__( + self, + name, + add_cup=True, + pod_holder_friction=None, + joints="default", + density=1000.0, + ): + + # pieces of the coffee machine + body = CoffeeMachineBodyObject(name="body") + body_size = body.get_bounding_box_half_size() + body_location = [0.0, 0.0, 0.0] + + lid = CoffeeMachineLidObject(name="lid") + lid_size = self.lid_size = lid.get_bounding_box_half_size() + # add tolerance to allow lid to open fully + lid_location = [ + body_size[0] - lid_size[0], + 2.0 * body_size[1] + 0.01, + 2.0 * (body_size[2] - lid_size[2]) + 0.005, + ] + + # add in hinge joint to lid + hinge_pos = [0.0, -lid_size[1], 0.0] + hinge_joint = dict( + type="hinge", + axis="1 0 0", + pos=array_to_string(hinge_pos), + limited="true", + range="{} {}".format(0, 2.0 * np.pi / 3.0), + damping="0.005", + ) + body_joints = dict( + lid_main=[hinge_joint] + ) # note: "main" gets appended to body name + lid = CoffeeMachineLidObject(name="lid") + + base = CoffeeMachineBaseObject(name="base") + base_size = base.get_bounding_box_half_size() + base_location = [body_size[0] - base_size[0], 2.0 * body_size[1], 0.0] + + pod_holder_holder = BoxObject( + name="pod_holder_holder", + size=[ + 0.01, + # tolerance for having the lid stick out a little from the holder + 0.9 * (lid_size[1] - lid_size[0]), + 0.005, + ], + rgba=[0.839, 0.839, 0.839, 1], # silver + joints=None, + ) + pod_holder_holder_size = pod_holder_holder.get_bounding_box_half_size() + pod_holder_holder_location = [ + body_size[0] - pod_holder_holder_size[0], + 2.0 * body_size[1], + # put right underneath lid + 2.0 * (body_size[2] - lid_size[2] - pod_holder_holder_size[2]), + ] + + pod_holder = CupObject( + name="pod_holder", + outer_cup_radius=lid_size[0], + inner_cup_radius=0.028, + cup_height=0.028, + cup_ngeoms=64, # 8, + cup_base_height=0.005, + cup_base_offset=0.002, + add_handle=False, + rgba=[1, 0, 0, 1], + density=density, + joints=None, + friction=pod_holder_friction, + ) + pod_holder_size = self.pod_holder_size = pod_holder.get_bounding_box_half_size() + # pod_holder_size = self.pod_holder_size = np.array([0.0295, 0.0295, 0.028 ]) + pod_holder_location = [ + body_size[0] - pod_holder_size[0], + 2.0 * (body_size[1] + pod_holder_holder_size[1]), + # put right underneath lid + 2.0 * (body_size[2] - lid_size[2] - pod_holder_size[2]), + ] + + total_size = [ + body_size[0], + body_size[1] + base_size[1], + body_size[2], + ] + + objects = [ + body, + lid, + base, + pod_holder_holder, + pod_holder, + ] + + object_locations = [ + body_location, + lid_location, + base_location, + pod_holder_holder_location, + pod_holder_location, + ] + + object_quats = [ + [0.0, 0.0, 0.0, 1.0], # z-rotate body and base by 180 + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + [1.0, 0.0, 0.0, 0.0], + [1.0, 0.0, 0.0, 0.0], + ] + + # add a rigidly mounted cup to the base + self.add_cup = add_cup + if self.add_cup: + cup = CupObject( + name="cupppp", + outer_cup_radius=0.03, + inner_cup_radius=0.025, + cup_height=0.025, + cup_ngeoms=64, # 8, + cup_base_height=0.005, + cup_base_offset=0.005, + add_handle=True, + handle_outer_radius=0.015, + handle_inner_radius=0.010, + handle_thickness=0.003, + handle_ngeoms=64, + rgba=[0.839, 0.839, 0.839, 1], + density=1000.0, + joints=None, + ) + cup_total_size = cup.get_bounding_box_half_size() + # cup_total_size = np.array([0.03 , 0.045, 0.025]) + objects.append(cup) + object_locations.append( + [ + body_size[0] - cup_total_size[0], + 2.0 * (body_size[1] + pod_holder_holder_size[1]) + + pod_holder_size[1] + - cup_total_size[1], + 2.0 * base_size[2], + ] + ) + rot_angle = -np.pi / 2.0 + object_quats.append([np.cos(rot_angle / 2), 0, 0, np.sin(rot_angle / 2)]) + + object_parents = [None] * len(objects) + + """ + Variables to compare: + + objects + [, + , + , + , + , + ] + + object_locations + [[0.0, 0.0, 0.0], + [0.056999999999999995, 0.21100000000000002, 0.20700000000000002], + [0.04449999999999999, 0.201, 0.0], + [0.0765, 0.201, 0.192], + [0.056999999999999995, 0.22710000000000002, 0.14600000000000002], + [0.056499999999999995, 0.21160000000000007, 0.01]] + + object_quats + [[0.0, 0.0, 0.0, 1.0], + [1.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + [1.0, 0.0, 0.0, 0.0], + [1.0, 0.0, 0.0, 0.0], + [0.7071067811865476, 0, 0, -0.7071067811865475]] + + body_size + array([0.0865, 0.1005, 0.1105]) + + lid_size + array([0.0295, 0.044 , 0.0095]) + + lid_location + [0.056999999999999995, 0.21100000000000002, 0.20700000000000002] + + base_size + array([0.042, 0.05 , 0.005]) + + base_location + [0.04449999999999999, 0.201, 0.0] + + pod_holder_holder_size + array([0.01 , 0.01305, 0.005 ]) + + pod_holder_holder_location + [0.0765, 0.201, 0.192] + + pod_holder_size + array([0.0295, 0.0295, 0.028 ]) + + pod_holder_location + [0.056999999999999995, 0.22710000000000002, 0.14600000000000002] + + total_size + [0.0865, 0.15050000000000002, 0.1105] + + cup.total_size + array([0.03 , 0.045, 0.025]) + """ + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + body_joints=body_joints, # make sure hinge joint is added + joints=joints, + # joints="default", # coffee machine can move + # joints=None, # coffee machine does not move + total_size=total_size, + locations_relative_to_corner=True, + ) diff --git a/third_party/robocasa/robocasa/models/objects/composite_body/cup.py b/third_party/robocasa/robocasa/models/objects/composite_body/cup.py new file mode 100644 index 0000000000000000000000000000000000000000..ba7bdda3e22f5048f2ce21fff3bea3c6386cfbf9 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite_body/cup.py @@ -0,0 +1,187 @@ +from robosuite.models.objects import ( + CompositeBodyObject, + BoxObject, + CylinderObject, + HollowCylinderObject, +) +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial + + +class CupObject(CompositeBodyObject): + """ + Cup object with optional handle. + """ + + def __init__( + self, + name, + outer_cup_radius=0.0425, + inner_cup_radius=0.03, + cup_height=0.05, + cup_ngeoms=8, + cup_base_height=0.01, + cup_base_offset=0.005, + add_handle=False, + handle_outer_radius=0.03, + handle_inner_radius=0.015, + handle_thickness=0.005, + handle_ngeoms=8, + joints="default", + rgba=None, + material=None, + density=100.0, + friction=None, + ): + + # Object properties + + # radius of the inner cup hole and entire cup + self.r1 = inner_cup_radius + self.r2 = outer_cup_radius + + # number of geoms used to approximate the cylindrical shell + self.n = cup_ngeoms + + # cup half-height + self.cup_height = cup_height + + # cup base args + self.cup_base_height = cup_base_height + self.cup_base_offset = cup_base_offset + + # handle args + self.add_handle = add_handle + self.handle_outer_radius = handle_outer_radius + self.handle_inner_radius = handle_inner_radius + self.handle_thickness = handle_thickness + self.handle_ngeoms = handle_ngeoms + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + + # cup body + self.cup_body = HollowCylinderObject( + name="cup_body", + outer_radius=self.r2, + inner_radius=self.r1, + height=self.cup_height, + ngeoms=self.n, + rgba=rgba, + material=material, + density=density, + friction=friction, + ) + objects.append(self.cup_body) + object_locations.append([0.0, 0.0, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # cup base + self.cup_base = CylinderObject( + name="cup_base", + size=[self.cup_body.int_r, self.cup_base_height], + rgba=rgba, + material=material, + density=density, + solref=[0.02, 1.0], + solimp=[0.998, 0.998, 0.001], + joints=None, + ) + objects.append(self.cup_base) + object_locations.append( + [0.0, 0.0, -self.cup_height + self.cup_base_height + self.cup_base_offset] + ) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + if self.add_handle: + # cup handle is a hollow half-cylinder + self.cup_handle = HollowCylinderObject( + name="cup_handle", + outer_radius=self.handle_outer_radius, + inner_radius=self.handle_inner_radius, + height=self.handle_thickness, + ngeoms=self.handle_ngeoms, + rgba=rgba, + material=material, + density=density, + make_half=True, + friction=friction, + ) + # translate handle to right side of cup body, and rotate by +90 degrees about y-axis + # to orient the handle geoms on the cup body + objects.append(self.cup_handle) + object_locations.append( + [0.0, (self.cup_body.r2 + self.cup_handle.unit_box_width), 0.0] + ) + object_quats.append( + T.convert_quat( + T.mat2quat( + T.rotation_matrix(angle=np.pi / 2.0, direction=[0.0, 1.0, 0.0])[ + :3, :3 + ] + ), + to="wxyz", + ) + ) + object_parents.append(None) + + # total size of cup + body_total_size = [self.r2, self.r2, self.cup_height] + if self.add_handle: + body_total_size[1] += self.handle_outer_radius + + """ + To match on cup 1: + + objects + [, + ] + + body_total_size + [0.0295, 0.0295, 0.028] + + object_locations + [[0.0, 0.0, 0.0], [0.0, 0.0, -0.020999999999999998]] + + object_quats + [[1.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0]] + + + To match on cup 2: + + objects + [, + , + ] + + body_total_size + [0.03, 0.045, 0.025] + + object_locations + [[0.0, 0.0, 0.0], [0.0, 0.0, -0.015], [0.0, 0.03073601511491127, 0.0]] + + object_quats + [[1.0, 0.0, 0.0, 0.0], + [1.0, 0.0, 0.0, 0.0], + array([ 0.70710677, -0. , 0.70710677, -0. ], dtype=float32)] + """ + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + total_size=body_total_size, + # locations_relative_to_corner=True, + ) diff --git a/third_party/robocasa/robocasa/models/objects/composite_body/inverse_stacked_cylinder.py b/third_party/robocasa/robocasa/models/objects/composite_body/inverse_stacked_cylinder.py new file mode 100644 index 0000000000000000000000000000000000000000..8cf95041d00a480ab01aa51800fc503fc6206e05 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite_body/inverse_stacked_cylinder.py @@ -0,0 +1,141 @@ +from robosuite.models.objects import ( + CompositeBodyObject, + BoxObject, + CylinderObject, + HollowCylinderObject, +) +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial + + +class InverseStackedCylinderObject(CompositeBodyObject): + """ + Inverse of stacked cylinder object, where the top piece is a hollow cylinder object + and the bottom piece is a cylinder object. Optionally add a square base for stability. + """ + + def __init__( + self, + name, + radius_1, + radius_2, + height_1, + height_2, + ngeoms=64, + joints="default", + rgba=None, + material=None, + density=100.0, + friction=None, + square_base_width=None, + square_base_height=None, + ): + + # Object properties + + # radius of first (bottom) cylinder and inner radius of second (top) hollow cylinder + self.r1 = radius_1 + self.r2 = radius_2 + + # half-height of first (bottom) cylinder and second (top) hollow cylinder + self.h1 = height_1 + self.h2 = height_2 + + # num geoms to approximate the hollow cylinder + self.ngeoms = ngeoms + + # whether to add square base + self.add_square_base = (square_base_width is not None) and ( + square_base_height is not None + ) + + # half-width and half-height for square base + self.square_base_width = square_base_width + self.square_base_height = square_base_height + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + + # NOTE: we will place the object frame at the vertical center of the two stacked cylinders + z_center = (self.h1 + self.h2) / 2.0 + c1_offset = self.h1 - z_center + c2_offset = 2.0 * self.h1 + self.h2 - z_center + + # first (bottom) cylinder + self.cylinder_1 = CylinderObject( + name="cylinder_1", + size=[self.r1, self.h1], + rgba=rgba, + material=material, + density=density, + friction=friction, + solref=[0.02, 1.0], + # solimp=[0.998, 0.998, 0.001], + solimp=[0.9, 0.95, 0.001], + joints=None, + ) + objects.append(self.cylinder_1) + object_locations.append([0.0, 0.0, c1_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # second (top) hollow cylinder + self.cylinder_2 = HollowCylinderObject( + name="cylinder_2", + outer_radius=self.r1, # match radius of first cylinder + inner_radius=self.r2, + height=self.h2, + ngeoms=self.ngeoms, + rgba=rgba, + material=material, + density=density, + friction=friction, + # TODO: maybe tune solimp and try (0.998, 0.998, 0.001) + solref=[0.02, 1.0], + solimp=[0.9, 0.95, 0.001], + # solimp=(0.998, 0.998, 0.001), + ) + objects.append(self.cylinder_2) + object_locations.append([0.0, 0.0, c2_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # # total size of object + # max_r = max(self.r1, self.r2) + # body_total_size = [max_r, max_r, self.h1 + self.h2] + + if self.add_square_base: + # add square base underneath bottom cylinder + s1_offset = c1_offset - (self.square_base_height + self.h1) + self.square_base = BoxObject( + name="square_base", + size=[ + self.square_base_width, + self.square_base_width, + self.square_base_height, + ], + rgba=rgba, + material=material, + ) + objects.append(self.square_base) + object_locations.append([0.0, 0.0, s1_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + # total_size=body_total_size, + # locations_relative_to_corner=True, + ) diff --git a/third_party/robocasa/robocasa/models/objects/composite_body/lightbulb.py b/third_party/robocasa/robocasa/models/objects/composite_body/lightbulb.py new file mode 100644 index 0000000000000000000000000000000000000000..43ce8056200d0ac8ab73943c7b1b66ce1db44cf5 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite_body/lightbulb.py @@ -0,0 +1,155 @@ +from robosuite.models.objects import ( + CompositeBodyObject, + BoxObject, + CylinderObject, + BallObject, +) +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string, new_site +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial + + +class BallObjectWithSite(BallObject): + """ + A ball object with a inner site (used for the bulb). + """ + + def _get_object_subtree(self): + # tree = super()._get_object_subtree() + tree = self._get_object_subtree_(ob_type="sphere") + site_element_attr = self.get_site_attrib_template() + + site_element_attr["pos"] = "0 0 0.1" + site_element_attr["name"] = "center_site" + site_element_attr["size"] = "{} {} {}".format( + 2.0 * self.size[0], 2.0 * self.size[0], 2.0 * self.size[0] + ) + site_element_attr["rgba"] = "1.0 0.0 0.0 1.0" + site_element_attr["group"] = "1" + # site_element_attr["rgba"] = "1.0 0.976 0.839 0.9" + # site_element_attr["rgba"] = "1.0 0.976 0.839 0.0" + tree.append(new_site(**site_element_attr)) + return tree + + +class LightbulbObject(CompositeBodyObject): + """ + A simple lightbulb constructed out of a base of alternating radius cylinders + and a sphere on top. + """ + + def __init__( + self, + name, + radius_low, + radius_high, + cylinder_height, + num_cylinders, + sphere_radius, + joints="default", + density=100.0, + friction=None, + ): + + # Object properties + + # radii of alternating cylinders for base + self.radius_low = radius_low + self.radius_high = radius_high + + # half-height of each cylinder + self.cylinder_height = cylinder_height + + # number of cylinders for base + self.num_cylinders = num_cylinders + + # radius of sphere at top + self.sphere_radius = sphere_radius + + # toggle between translucent and yellow + self.translucent_rgba = (1.0, 1.0, 1.0, 0.3) + self.yellow_rgba = (1.0, 0.976, 0.839, 0.7) + # self.yellow_rgba = (0.0, 0.0, 0.0, 0.0) + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + + # NOTE: we will place the object frame at the vertical center of all the stacked objects + self.z_center = ( + (2.0 * self.cylinder_height) * self.num_cylinders + 2.0 * self.sphere_radius + ) / 2.0 + + metal = CustomMaterial( + texture="Metal", + tex_name="metal", + mat_name="MatMetal", + tex_attrib={"type": "cube"}, + mat_attrib={"specular": "1", "shininess": "0.3", "rgba": "0.9 0.9 0.9 1"}, + ) + + # we will define all objects relative to the bottom of the object, and then subtract the z_center value + for cylinder_ind in range(self.num_cylinders): + r = self.radius_low if ((cylinder_ind % 2) == 0) else self.radius_high + cyl_obj = CylinderObject( + name="cylinder_{}".format(cylinder_ind), + size=[r, self.cylinder_height], + rgba=None, + material=metal, + density=density, + friction=friction, + solref=[0.02, 1.0], + solimp=[0.9, 0.95, 0.001], + joints=None, + ) + objects.append(cyl_obj) + z_cyl = (2.0 * cylinder_ind + 1) * self.cylinder_height + object_locations.append([0.0, 0.0, z_cyl]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # then add translucent sphere at top + self.bulb = BallObject( + name="bulb", + size=[self.sphere_radius], + density=density, + friction=friction, + rgba=self.translucent_rgba, + material=None, + joints=None, + ) + objects.append(self.bulb) + z_bulb = object_locations[-1][2] + self.cylinder_height + self.sphere_radius + object_locations.append([0.0, 0.0, z_bulb]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # do frame conversion from bottom of object to z_center + object_locations = [ + [loc[0], loc[1], loc[2] - self.z_center] for loc in object_locations + ] + + # add site that can be toggled to turn lightbulb on + sites = [ + dict( + name="bulb_on", + pos=array_to_string(object_locations[-1]), + size="{}".format(0.95 * self.sphere_radius), + rgba=array_to_string(self.yellow_rgba), + ) + ] + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + sites=sites, + ) diff --git a/third_party/robocasa/robocasa/models/objects/composite_body/sliding_box.py b/third_party/robocasa/robocasa/models/objects/composite_body/sliding_box.py new file mode 100644 index 0000000000000000000000000000000000000000..0e6542b615457918a9ab869b62f54eb1923db5d5 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite_body/sliding_box.py @@ -0,0 +1,132 @@ +import numpy as np + +from robosuite.models.objects import BoxObject, CompositeBodyObject, CylinderObject +from robosuite.utils.mjcf_utils import BLUE, RED, CustomMaterial, array_to_string + + +class SlidingBoxObject(CompositeBodyObject): + """ + An example object that demonstrates the CompositeBodyObject functionality. This object consists of two cube bodies + joined together by a slide joint allowing one box to slide on top of the other. + + Args: + name (str): Name of this object + + box1_size (3-array): (L, W, H) half-sizes for the first box + + box2_size (3-array): (L, W, H) half-sizes for the second box + + use_texture (bool): set True if using wood textures for the blocks + """ + + def __init__( + self, + name, + box1_size=(0.1, 0.1, 0.02), + box2_size=(0.02, 0.02, 0.02), + use_texture=True, + ): + # Set box sizes + self.box1_size = np.array(box1_size) + self.box2_size = np.array(box2_size) + + # Set box densities + self.box1_density = 10000.0 + self.box2_density = 100.0 + + # Set texture attributes + self.use_texture = use_texture + self.box1_material = None + self.box2_material = None + self.box1_rgba = RED + self.box2_rgba = BLUE + + # Define materials we want to use for this object + if self.use_texture: + # Remove RGBAs + self.box1_rgba = None + self.box2_rgba = None + + # Set materials for each box + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "3 3", + "specular": "0.4", + "shininess": "0.1", + } + self.box1_material = CustomMaterial( + texture="WoodRed", + tex_name="box1_tex", + mat_name="box1_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.box2_material = CustomMaterial( + texture="WoodBlue", + tex_name="box2_tex", + mat_name="box2_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + + # Create objects + objects = [] + for i, (size, mat, rgba, density) in enumerate( + zip( + (self.box1_size, self.box2_size), + (self.box1_material, self.box2_material), + (self.box1_rgba, self.box2_rgba), + (self.box1_density, self.box2_density), + ) + ): + objects.append( + BoxObject( + name=f"box{i + 1}", + size=size, + rgba=rgba, + material=mat, + ) + ) + + # Define slide joint + rel_joint_pos = [0, 0, 0] # at second box + joint_lim = self.box1_size[1] - self.box2_size[1] + slide_joint = { + "name": "box_slide", + "type": "slide", + "axis": "0 1 0", # y-axis slide + "pos": array_to_string(rel_joint_pos), + "springref": "0", + "springdamper": "0.1 1.0", # mass-spring system with 0.1 time constant, 1.0 damping ratio + "limited": "true", + "range": "{} {}".format(-joint_lim, joint_lim), + } + + # Define positions -- second box should lie on top of first box + positions = [ + np.zeros(3), # First box is centered at top-level body anyways + np.array([0, 0, self.box1_size[2] + self.box2_size[2]]), + ] + + quats = [ + None, # Default quaternion for box 1 + None, # Default quaternion for box 2 + ] + + # Define parents -- which body each is aligned to + parents = [ + None, # box 1 attached to top-level body + objects[0].root_body, # box 2 attached to box 1 + ] + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=positions, + object_quats=quats, + object_parents=parents, + body_joints={objects[1].root_body: [slide_joint]}, + ) diff --git a/third_party/robocasa/robocasa/models/objects/composite_body/socket.py b/third_party/robocasa/robocasa/models/objects/composite_body/socket.py new file mode 100644 index 0000000000000000000000000000000000000000..21dadbe7af0d0cf9e9d2a52dfc7d56a9beea3ac0 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite_body/socket.py @@ -0,0 +1,339 @@ +from robosuite.models.objects import CompositeBodyObject, BoxObject, CylinderObject +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial +from .stacked_cylinder import StackedCylinderObject + + +class SocketObject(CompositeBodyObject): + """ + Box geom connected to series of geoms with ball joints (wire) and connected to + cylinder representing plug. + """ + + def __init__( + self, + name, + joints="default", + rgba=None, + material=None, + density=100.0, + friction=None, + socket_base_size=(0.02, 0.02, 0.03), + wire_box_geom_size=(0.02, 0.005, 0.005), + wire_box_geom_rgba=(0.0, 0.0, 0.0, 1.0), + num_box_geoms_up=6, + num_box_geoms_left=2, + num_box_geoms_down=9, + merge_box_geoms=False, + merge_size=1, + cylinder_args=None, + ): + + # Object properties + + # box geom used for socket base + self.socket_base_size = socket_base_size + + # box geoms used for wire + self.wire_box_geom_size = wire_box_geom_size + self.wire_box_geom_rgba = wire_box_geom_rgba + + # wire parameters - number of geoms to use for up, left, and down portions + self.num_box_geoms_up = num_box_geoms_up + self.num_box_geoms_left = num_box_geoms_left + self.num_box_geoms_down = num_box_geoms_down + + # if true, merge the box geoms along each direction of the wire into a single box geom + self.merge_box_geoms = merge_box_geoms + + # number of box geoms to use for each merged size (set to higher than 1 to merge the geoms into more + # than one box geom) + self.merge_size = merge_size + + if cylinder_args is None: + # default cylinder args + cylinder_args = dict( + # bottom cylinder radius and half-height + radius_1=0.03, + height_1=0.075, + # top cylinder radius and half-height + radius_2=0.02, + height_2=0.025, + rgba=[0.839, 0.839, 0.839, 1], + density=1000.0, + # add square base + square_base_width=0.03, + square_base_height=0.005, + ) + self.cylinder_args = dict(cylinder_args) + self.cylinder_args["joints"] = None + + # materials + box_geom_material = CustomMaterial( + texture="Metal", + tex_name="metal", + mat_name="MatMetal", + tex_attrib={"type": "cube"}, + mat_attrib={"specular": "1", "shininess": "0.3", "rgba": "0.9 0.9 0.9 1"}, + ) + socket_material = CustomMaterial( + texture="WoodLight", + tex_name="lightwood", + mat_name="lightwood_mat", + tex_attrib={"type": "cube"}, + mat_attrib={"texrepeat": "1 1", "specular": "0.4", "shininess": "0.1"}, + ) + + # params for ball joints used + + # + ball_joint_spec = { + "type": "ball", + "pos": "{} 0 0".format(self.wire_box_geom_size[0]), + "springref": "0", + "springdamper": "0.1 1.0", # mass-spring system with 0.1 time constant, 1.0 damping ratio + "limited": "true", + "range": "0 {}".format(np.pi / 4), + } + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + object_joints = dict() + + # NOTE: For absolute object locations (objects not defined relative to parent) we will use the socket base frame + # as a frame of reference, and add an offset from the center of the object (approximated via full width) + # to it. + + # get an approximate x-y bounding box below, and place the center there, and define offset relative to stove base center + approx_full_width = self.num_box_geoms_left * ( + 2.0 * self.wire_box_geom_size[0] + ) + (2.0 * self.socket_base_size[1]) + approx_full_height = (self.num_box_geoms_down + 2) * ( + 2.0 * self.wire_box_geom_size[0] + ) + + base_x_off = ( + self.socket_base_size[0] + + (self.num_box_geoms_up) * (2.0 * self.wire_box_geom_size[0]) + ) - (approx_full_height / 2.0) + base_y_off = ( + self.num_box_geoms_left * self.wire_box_geom_size[0] + ) + self.socket_base_size[1] + + # base of socket + self.socket_base = BoxObject( + name="stove_base", + size=list(self.socket_base_size), + rgba=rgba, + material=socket_material, + joints=None, + ) + objects.append(self.socket_base) + object_locations.append([base_x_off, base_y_off, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # chain above base + chain_ind = 0 + up_chain_size = list(self.wire_box_geom_size) + num_geoms_iter = self.num_box_geoms_up - 1 + if self.merge_box_geoms: + # only one big geom instead of chain of geoms + up_chain_size[0] *= self.num_box_geoms_up + up_chain_size[0] /= self.merge_size + # number of additional geoms to add + num_geoms_iter = self.merge_size - 1 + chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(up_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + objects.append(chain_obj) + object_locations.append( + [ + base_x_off - (self.socket_base_size[0] + up_chain_size[0]), + base_y_off, + 0.0, + ] + ) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + if self.merge_box_geoms: + # add ball joint and make sure to place it at the edge of the geom + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "{} 0 0".format(up_chain_size[0]) + object_joints[chain_obj.root_body] = [ball_joint] + + for i in range(num_geoms_iter): + chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(up_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(chain_obj) + object_locations.append([-2.0 * up_chain_size[0], 0.0, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + # add ball joint and make sure to place it at the edge of the geom + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "{} 0 0".format(up_chain_size[0]) + object_joints[chain_obj.root_body] = [ball_joint] + + # add chain in left direction + rot_quat = T.convert_quat( + T.axisangle2quat(np.array([0.0, 0.0, 1.0]) * (np.pi / 2.0)), to="wxyz" + ) + left_chain_size = list(self.wire_box_geom_size) + num_geoms_iter = self.num_box_geoms_left - 1 + if self.merge_box_geoms: + # only one big geom instead of chain of geoms + left_chain_size[0] *= self.num_box_geoms_left + # HACK: merge entire left chain since this side is small + left_merge_size = 1 + left_chain_size[0] /= left_merge_size + # number of additional geoms to add + num_geoms_iter = left_merge_size - 1 + chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(left_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(chain_obj) + object_locations.append([-up_chain_size[0], -left_chain_size[0], 0.0]) + object_quats.append(rot_quat) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "{} 0 0".format(left_chain_size[0]) + object_joints[chain_obj.root_body] = [ball_joint] + + for i in range(num_geoms_iter): + chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(left_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(chain_obj) + object_locations.append([-2.0 * left_chain_size[0], 0.0, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "{} 0 0".format(left_chain_size[0]) + object_joints[chain_obj.root_body] = [ball_joint] + + # add chain in downward direction + rot_quat = T.convert_quat( + T.axisangle2quat(np.array([0.0, 0.0, 1.0]) * (np.pi / 2.0)), to="wxyz" + ) + down_chain_size = list(self.wire_box_geom_size) + num_geoms_iter = self.num_box_geoms_down - 1 + if self.merge_box_geoms: + # only one big geom instead of chain of geoms + down_chain_size[0] *= self.num_box_geoms_down + down_chain_size[0] /= self.merge_size + # number of additional geoms to add + num_geoms_iter = self.merge_size - 1 + chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(down_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(chain_obj) + object_locations.append([-left_chain_size[0], -down_chain_size[0], 0.0]) + object_quats.append(rot_quat) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "{} 0 0".format(down_chain_size[0]) + object_joints[chain_obj.root_body] = [ball_joint] + + for i in range(num_geoms_iter): + chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(down_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(chain_obj) + object_locations.append([-2.0 * down_chain_size[0], 0.0, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "{} 0 0".format(down_chain_size[0]) + object_joints[chain_obj.root_body] = [ball_joint] + + # add cylinder object + self.cylinder_obj = StackedCylinderObject( + name="cylinder_obj", + **self.cylinder_args, + ) + + x_off = -(down_chain_size[0] + self.cylinder_obj.square_base_width) + y_off = 0.0 + z_off = ((self.cylinder_obj.h1 + self.cylinder_obj.h2) / 2.0) - down_chain_size[ + 2 + ] + parent = objects[-1].root_body + objects.append(self.cylinder_obj) + object_locations.append([x_off, y_off, z_off]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + # # add debug site to see object center + # sites = [ + # dict( + # name="TMP", + # pos=array_to_string([0., 0., 0.]), + # size="{}".format(0.1), + # rgba=array_to_string([1., 0., 0., 1.]), + # ) + # ] + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + body_joints=object_joints, + # sites=sites, + ) diff --git a/third_party/robocasa/robocasa/models/objects/composite_body/spray_bottle.py b/third_party/robocasa/robocasa/models/objects/composite_body/spray_bottle.py new file mode 100644 index 0000000000000000000000000000000000000000..56537ffdeb3fec3cfb7402b2a7f6ff32f7fd5d4d --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite_body/spray_bottle.py @@ -0,0 +1,213 @@ +import numpy as np + +from robosuite.models.objects import ( + BoxObject, + CompositeBodyObject, + CylinderObject, + ConeObject, +) +from robosuite.utils.mjcf_utils import BLUE, RED, CustomMaterial, array_to_string + + +class SprayBottleObject(CompositeBodyObject): + """ + A spray bottle object where the trigger is modeled via a slide joint. + """ + + def __init__( + self, + name, + base_cylinder_radius, + base_cylinder_height, + cone_outer_radius, + cone_inner_radius, + cone_height, + cone_ngeoms, + neck_height, + top_length, + top_thickness, + trigger_height, + trigger_width, + trigger_length, + joints="default", + rgba=None, + material=None, + density=100.0, + friction=None, + square_base_width=None, + square_base_height=None, + ): + # Sizes + self.base_cylinder_radius = base_cylinder_radius + self.base_cylinder_height = base_cylinder_height + self.cone_outer_radius = cone_outer_radius + self.cone_inner_radius = cone_inner_radius + self.cone_height = cone_height + self.cone_ngeoms = cone_ngeoms + self.neck_height = neck_height + self.top_length = top_length + self.top_thickness = top_thickness + self.trigger_height = trigger_height + self.trigger_width = trigger_width + self.trigger_length = trigger_length + + # whether to add square base + self.add_square_base = (square_base_width is not None) and ( + square_base_height is not None + ) + + # half-width and half-height for square base + self.square_base_width = square_base_width + self.square_base_height = square_base_height + + assert ( + self.top_length > self.cone_inner_radius + ), "top needs to stick out past neck" + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + + # base cylinder + self.base_cylinder = CylinderObject( + name="base_cylinder", + size=[self.base_cylinder_radius, self.base_cylinder_height], + rgba=rgba, + material=material, + density=density, + friction=friction, + solref=[0.02, 1.0], + # solimp=[0.998, 0.998, 0.001], + solimp=[0.9, 0.95, 0.001], + joints=None, + ) + objects.append(self.base_cylinder) + object_locations.append([0.0, 0.0, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # cone that is part of neck + # z_cone = self.base_cylinder_height # cone frame is bottom center of cone + z_cone = self.base_cylinder_height + (self.cone_height / 2.0) + self.neck_cone = ConeObject( + name="neck_cone", + outer_radius=self.cone_outer_radius, + inner_radius=self.cone_inner_radius, + height=self.cone_height, # full height, not half-height + ngeoms=self.cone_ngeoms, + use_box=False, + rgba=rgba, + material=material, + density=density, + solref=(0.02, 1.0), + # solimp=[0.998, 0.998, 0.001], + solimp=(0.9, 0.95, 0.001), + friction=friction, + ) + objects.append(self.neck_cone) + object_locations.append([0.0, 0.0, z_cone]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # cylinder that is part of neck + z_cyl = self.base_cylinder_height + self.cone_height + self.neck_height + self.neck_cylinder = CylinderObject( + name="neck_cylinder", + size=[self.cone_inner_radius, self.neck_height], # match cone radius + rgba=rgba, + material=material, + density=density, + friction=friction, + solref=[0.02, 1.0], + # solimp=[0.998, 0.998, 0.001], + solimp=[0.9, 0.95, 0.001], + joints=None, + ) + objects.append(self.neck_cylinder) + object_locations.append([0.0, 0.0, z_cyl]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # top box object + box_x_off = -(self.top_length - self.cone_inner_radius) + box_z_off = z_cyl + self.neck_height + self.top_thickness + self.top_box = BoxObject( + name="top_box", + size=[self.top_length, self.cone_inner_radius, self.top_thickness], + density=density, + friction=friction, + rgba=rgba, + material=material, + joints=None, + ) + objects.append(self.top_box) + object_locations.append([box_x_off, 0.0, box_z_off]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # trigger object, which is defined relative to top box object + trigger_x_off = -( + 0.5 * self.top_length + ) # place halfway along length of top object + trigger_z_off = -(self.top_thickness + self.trigger_height) + self.trigger = BoxObject( + name="trigger", + size=[self.trigger_length, self.trigger_width, self.trigger_height], + density=density, + friction=friction, + rgba=rgba, + material=material, + joints=None, + ) + objects.append(self.trigger) + object_locations.append([trigger_x_off, 0.0, trigger_z_off]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(objects[-2].root_body) # NOTE: relative to top box object + + # define slide joint for trigger + rel_joint_pos = [0, 0, 0] # at trigger + joint_lim_min = 0.0 + joint_lim_max = ( + self.top_length + ) # trigger was shifted to left by 0.5 * top_length, so allow it to go to right by top_length + slide_joint = { + "name": "trigger_slide", + "type": "slide", + "axis": "1 0 0", # x-axis slide + "pos": array_to_string(rel_joint_pos), + "springref": "0", + "springdamper": "0.1 1.0", # mass-spring system with 0.1 time constant, 1.0 damping ratio + "limited": "true", + "range": "{} {}".format(joint_lim_min, joint_lim_max), + } + + if self.add_square_base: + # add square base underneath bottom cylinder + s1_offset = -(self.square_base_height + self.base_cylinder_height) + self.square_base = BoxObject( + name="square_base", + size=[ + self.square_base_width, + self.square_base_width, + self.square_base_height, + ], + rgba=rgba, + material=material, + ) + objects.append(self.square_base) + object_locations.append([0.0, 0.0, s1_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + body_joints={objects[-1].root_body: [slide_joint]}, + ) diff --git a/third_party/robocasa/robocasa/models/objects/composite_body/stacked_box.py b/third_party/robocasa/robocasa/models/objects/composite_body/stacked_box.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c7991c3a6056531e7758586df1f6a5538e3d45 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite_body/stacked_box.py @@ -0,0 +1,111 @@ +from robosuite.models.objects import CompositeBodyObject, BoxObject, CylinderObject, Bin +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial + + +class StackedBoxObject(CompositeBodyObject): + """ + Two boxes - one stacked on top of the other. + """ + + def __init__( + self, + name, + box_1_size, + box_2_size, + joints="default", + box_1_rgba=None, + box_2_rgba=None, + box_1_material=None, + box_2_material=None, + density=100.0, + friction=None, + make_box_2_transparent=False, + ): + + # Object properties + + # half-sizes of first (bottom) box + self.box_1_size = list(box_1_size) + + # half-sizes of second (top) box + self.box_2_size = list(box_2_size) + + # maybe make box 2 have transparent top and bottom walls + self.make_box_2_transparent = make_box_2_transparent + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + + # NOTE: we will place the object frame at the vertical center of the two stacked boxes + z_center = (self.box_1_size[2] + self.box_2_size[2]) / 2.0 + b1_offset = self.box_1_size[2] - z_center + b2_offset = 2.0 * self.box_1_size[2] + self.box_2_size[2] - z_center + + # first (bottom) box + self.box_1 = BoxObject( + name="box_1", + size=self.box_1_size, + rgba=box_1_rgba, + material=box_1_material, + density=density, + friction=friction, + joints=None, + ) + objects.append(self.box_1) + object_locations.append([0.0, 0.0, b1_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # second (top) box + if self.make_box_2_transparent: + self.box_2 = Bin( + name="box_2", + bin_size=( + 2.0 * self.box_2_size[0], + 2.0 * self.box_2_size[1], + 2.0 * self.box_2_size[2], + ), + wall_thickness=0.01, + transparent_walls=False, + friction=friction, + density=density, + use_texture=True, + rgba=box_2_rgba, + material=box_2_material, + upside_down=False, + add_second_base=True, + transparent_base=True, + ) + else: + self.box_2 = BoxObject( + name="box_2", + size=self.box_2_size, + rgba=box_2_rgba, + material=box_2_material, + density=density, + friction=friction, + joints=None, + ) + objects.append(self.box_2) + object_locations.append([0.0, 0.0, b2_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + # total_size=body_total_size, + # locations_relative_to_corner=True, + ) diff --git a/third_party/robocasa/robocasa/models/objects/composite_body/stacked_cylinder.py b/third_party/robocasa/robocasa/models/objects/composite_body/stacked_cylinder.py new file mode 100644 index 0000000000000000000000000000000000000000..047bc46f39fb8b1bdc9bb01ebf872b9be6f929e5 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite_body/stacked_cylinder.py @@ -0,0 +1,129 @@ +from robosuite.models.objects import CompositeBodyObject, BoxObject, CylinderObject +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial + + +class StackedCylinderObject(CompositeBodyObject): + """ + Two cylinders - one stacked on top of the other. + Optionally add a square base for stability. + """ + + def __init__( + self, + name, + radius_1, + radius_2, + height_1, + height_2, + joints="default", + rgba=None, + material=None, + density=100.0, + friction=None, + square_base_width=None, + square_base_height=None, + ): + + # Object properties + + # radius of first (bottom) cylinder and second (top) cylinder + self.r1 = radius_1 + self.r2 = radius_2 + + # half-height of first (bottom) cylinder and second (top) cylinder + self.h1 = height_1 + self.h2 = height_2 + + # whether to add square base + self.add_square_base = (square_base_width is not None) and ( + square_base_height is not None + ) + + # half-width and half-height for square base + self.square_base_width = square_base_width + self.square_base_height = square_base_height + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + + # NOTE: we will place the object frame at the vertical center of the two stacked cylinders + z_center = (self.h1 + self.h2) / 2.0 + c1_offset = self.h1 - z_center + c2_offset = 2.0 * self.h1 + self.h2 - z_center + + # first (bottom) cylinder + self.cylinder_1 = CylinderObject( + name="cylinder_1", + size=[self.r1, self.h1], + rgba=rgba, + material=material, + density=density, + friction=friction, + solref=[0.02, 1.0], + solimp=[0.9, 0.95, 0.001], + # solimp=[0.998, 0.998, 0.001], + joints=None, + ) + objects.append(self.cylinder_1) + object_locations.append([0.0, 0.0, c1_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # second (top) cylinder + self.cylinder_2 = CylinderObject( + name="cylinder_2", + size=[self.r2, self.h2], + rgba=rgba, + material=material, + density=density, + friction=friction, + solref=[0.02, 1.0], + # solimp=[0.998, 0.998, 0.001], + solimp=[0.9, 0.95, 0.001], + joints=None, + ) + objects.append(self.cylinder_2) + object_locations.append([0.0, 0.0, c2_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # # total size of object + # max_r = max(self.r1, self.r2) + # body_total_size = [max_r, max_r, self.h1 + self.h2] + + if self.add_square_base: + # add square base underneath bottom cylinder + s1_offset = c1_offset - (self.square_base_height + self.h1) + self.square_base = BoxObject( + name="square_base", + size=[ + self.square_base_width, + self.square_base_width, + self.square_base_height, + ], + rgba=rgba, + material=material, + ) + objects.append(self.square_base) + object_locations.append([0.0, 0.0, s1_offset]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + # total_size=body_total_size, + # locations_relative_to_corner=True, + ) diff --git a/third_party/robocasa/robocasa/models/objects/composite_body/stove_plug.py b/third_party/robocasa/robocasa/models/objects/composite_body/stove_plug.py new file mode 100644 index 0000000000000000000000000000000000000000..088d7be31aa4d1a76602e25a01e9e5e002f4ea64 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/composite_body/stove_plug.py @@ -0,0 +1,400 @@ +from robosuite.models.objects import CompositeBodyObject, BoxObject, CylinderObject +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial +from .inverse_stacked_cylinder import InverseStackedCylinderObject +from .lightbulb import LightbulbObject + +import robosuite_task_zoo +from robosuite_task_zoo.models.kitchen import StoveObject + + +class StoveObjectNew(StoveObject): + """ + Override some offsets for placement sampler. + """ + + @property + def bottom_offset(self): + # unused since we directly hardcode z + return np.array([0, 0, -0.02]) + + @property + def top_offset(self): + # unused since we directly hardcode z + return np.array([0, 0, 0.02]) + + @property + def horizontal_radius(self): + return 0.1 + + +class StovePlugObject(CompositeBodyObject): + """ + Stove on wooden block with chain (plug) connected. Optionally replace the stove + with a lightbulb if @lightbulb_args is provided. + """ + + def __init__( + self, + name, + joints="default", + rgba=None, + material=None, + density=100.0, + friction=None, + stove_base_size=(0.12, 0.12, 0.01), + stove_z_half_size=0.025, + wire_box_geom_size=(0.005, 0.02, 0.005), + wire_box_geom_rgba=(0.0, 0.0, 0.0, 1.0), + num_box_geoms_left=5, + num_box_geoms_vert=8, + num_box_geoms_right=8, + merge_box_geoms=False, + merge_size=1, + cylinder_args=None, + lightbulb_args=None, + ): + + # Object properties + + # half sizes for stove base box object + # self.stove_base_size = (0.1, 0.1, 0.02) + self.stove_base_size = stove_base_size + self.stove_z_half_size = stove_z_half_size # note: estimated approximately + + # box geoms used for wire + self.wire_box_geom_size = wire_box_geom_size + self.wire_box_geom_rgba = wire_box_geom_rgba + + # wire parameters - number of geoms to use for left, down, and right portions + self.num_box_geoms_left = num_box_geoms_left + self.num_box_geoms_vert = num_box_geoms_vert + self.num_box_geoms_right = num_box_geoms_right + + # if true, merge the box geoms along each direction of the wire into a single box geom + self.merge_box_geoms = merge_box_geoms + + # number of box geoms to use for each merged size (set to higher than 1 to merge the geoms into more + # than one box geom) + self.merge_size = merge_size + + if cylinder_args is None: + # default cylinder args + cylinder_args = dict( + # bottom cylinder radius and half-height + radius_1=0.03, + height_1=0.01, + # top hollow cylinder inner radius and half-height + radius_2=0.025, + height_2=0.025, + # NOTE: reduce to 8 geoms if desired + ngeoms=64, + rgba=[0.839, 0.839, 0.839, 1], + density=1000.0, + # add square base + square_base_width=0.03, + square_base_height=0.005, + ) + self.cylinder_args = dict(cylinder_args) + self.cylinder_args["joints"] = None + + self.use_lightbulb = lightbulb_args is not None + if self.use_lightbulb: + self.lightbulb_args = dict(lightbulb_args) + self.lightbulb_args["joints"] = None + + # materials + box_geom_material = CustomMaterial( + texture="Metal", + tex_name="metal", + mat_name="MatMetal", + tex_attrib={"type": "cube"}, + mat_attrib={"specular": "1", "shininess": "0.3", "rgba": "0.9 0.9 0.9 1"}, + ) + stove_base_material = CustomMaterial( + texture="WoodLight", + tex_name="lightwood", + mat_name="lightwood_mat", + tex_attrib={"type": "cube"}, + mat_attrib={"texrepeat": "1 1", "specular": "0.4", "shininess": "0.1"}, + ) + + # params for ball joints used + + # + ball_joint_spec = { + "type": "ball", + "pos": "0 {} 0".format(self.wire_box_geom_size[1]), + "springref": "0", + "springdamper": "0.1 1.0", # mass-spring system with 0.1 time constant, 1.0 damping ratio + "limited": "true", + "range": "0 {}".format(np.pi / 4), + } + + # Create objects + objects = [] + object_locations = [] + object_quats = [] + object_parents = [] + object_joints = dict() + + # NOTE: For absolute object locations (objects not defined relative to parent) we will use the stove base frame + # as a frame of reference, and add an offset from the center of the object (approximated via full width) + # to it. + + # get an approximate x-y bounding box below, and place the center there, and define offset relative to stove base cente + approx_full_width = self.num_box_geoms_left * ( + 2.0 * self.wire_box_geom_size[1] + ) + (2.0 * self.stove_base_size[1]) + approx_full_height = (self.num_box_geoms_vert + 2) * ( + 2.0 * self.wire_box_geom_size[1] + ) + + stove_base_x_off = -(approx_full_height / 2.0) + self.stove_base_size[0] + stove_base_y_off = (approx_full_width / 2.0) - self.stove_base_size[1] + + # base of stove + self.stove_base = BoxObject( + name="stove_base", + size=list(self.stove_base_size), + rgba=rgba, + material=stove_base_material, + joints=None, + ) + objects.append(self.stove_base) + object_locations.append([stove_base_x_off, stove_base_y_off, 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + if self.use_lightbulb: + # lightbulb + self.lightbulb = LightbulbObject( + name="lightbulb", + **self.lightbulb_args, + ) + objects.append(self.lightbulb) + object_locations.append( + [ + stove_base_x_off, + stove_base_y_off, + (self.stove_base_size[2] + self.lightbulb.z_center), + ] + ) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + else: + # stove + self.stove = StoveObjectNew( + name="new_stove", + joints=None, + ) + objects.append(self.stove) + object_locations.append( + [ + stove_base_x_off, + stove_base_y_off, + (self.stove_base_size[2] + self.stove_z_half_size), + ] + ) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + + # chain to the left of stove base + chain_ind = 0 + left_chain_size = list(self.wire_box_geom_size) + num_geoms_iter = self.num_box_geoms_left - 1 + if self.merge_box_geoms: + # only one big geom instead of chain of geoms + left_chain_size[1] *= self.num_box_geoms_left + left_chain_size[1] /= self.merge_size + # number of additional geoms to add + num_geoms_iter = self.merge_size - 1 + left_chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(left_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + objects.append(left_chain_obj) + object_locations.append( + [ + stove_base_x_off - 0.75 * self.stove_base_size[0], + stove_base_y_off - (self.stove_base_size[1] + left_chain_size[1]), + 0.0, + ] + ) + # object_locations.append([0., -(self.stove_base_size[1] + left_chain_size[1]), 0.]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(None) + if self.merge_box_geoms: + # add ball joint and make sure to place it at the edge of the geom + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "0 {} 0".format(left_chain_size[1]) + object_joints[left_chain_obj.root_body] = [ball_joint] + for i in range(num_geoms_iter): + left_chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(left_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(left_chain_obj) + object_locations.append([0.0, -2.0 * left_chain_size[1], 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + # add ball joint and make sure to place it at the edge of the geom + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "0 {} 0".format(left_chain_size[1]) + object_joints[left_chain_obj.root_body] = [ball_joint] + + # add chain in downward direction + rot_quat = T.convert_quat( + T.axisangle2quat(np.array([0.0, 0.0, 1.0]) * (np.pi / 2.0)), to="wxyz" + ) + vert_chain_size = list(self.wire_box_geom_size) + num_geoms_iter = self.num_box_geoms_vert - 1 + if self.merge_box_geoms: + # only one big geom instead of chain of geoms + vert_chain_size[1] *= self.num_box_geoms_vert + vert_chain_size[1] /= self.merge_size + # number of additional geoms to add + num_geoms_iter = self.merge_size - 1 + vert_chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(vert_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(vert_chain_obj) + object_locations.append([vert_chain_size[1], -left_chain_size[1], 0.0]) + object_quats.append(rot_quat) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "0 {} 0".format(vert_chain_size[1]) + object_joints[vert_chain_obj.root_body] = [ball_joint] + + for i in range(num_geoms_iter): + vert_chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(vert_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(vert_chain_obj) + object_locations.append([0.0, -2.0 * vert_chain_size[1], 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "0 {} 0".format(vert_chain_size[1]) + object_joints[vert_chain_obj.root_body] = [ball_joint] + + # add chain in rightward direction + rot_quat = T.convert_quat( + T.axisangle2quat(np.array([0.0, 0.0, 1.0]) * (np.pi / 2.0)), to="wxyz" + ) + right_chain_size = list(self.wire_box_geom_size) + num_geoms_iter = self.num_box_geoms_right - 1 + if self.merge_box_geoms: + # only one big geom instead of chain of geoms + right_chain_size[1] *= self.num_box_geoms_right + right_chain_size[1] /= self.merge_size + # number of additional geoms to add + num_geoms_iter = self.merge_size - 1 + right_chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(right_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(right_chain_obj) + object_locations.append([right_chain_size[1], -vert_chain_size[1], 0.0]) + object_quats.append(rot_quat) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "0 {} 0".format(right_chain_size[1]) + object_joints[right_chain_obj.root_body] = [ball_joint] + + for i in range(num_geoms_iter): + right_chain_obj = BoxObject( + name="chain_{}".format(chain_ind), + size=list(right_chain_size), + rgba=list(self.wire_box_geom_rgba), + material=box_geom_material, + joints=None, + ) + chain_ind += 1 + parent = objects[-1].root_body + objects.append(right_chain_obj) + object_locations.append([0.0, -2.0 * right_chain_size[1], 0.0]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + ball_joint = dict(ball_joint_spec) + ball_joint["name"] = "ball_joint_{}".format(chain_ind) + ball_joint["pos"] = "0 {} 0".format(right_chain_size[1]) + object_joints[right_chain_obj.root_body] = [ball_joint] + + # add cylinder object + self.cylinder_obj = InverseStackedCylinderObject( + name="cylinder_obj", + **self.cylinder_args, + ) + + x_off = 0.0 + y_off = -(right_chain_size[1] + self.cylinder_obj.square_base_width) + z_off = ( + (self.cylinder_obj.h1 + self.cylinder_obj.h2) / 2.0 + ) - right_chain_size[2] + parent = objects[-1].root_body + objects.append(self.cylinder_obj) + object_locations.append([x_off, y_off, z_off]) + object_quats.append([1.0, 0.0, 0.0, 0.0]) + object_parents.append(parent) + + # # add debug site to see object center + # sites = [ + # dict( + # name="TMP", + # pos=array_to_string([0., 0., 0.]), + # size="{}".format(0.1), + # rgba=array_to_string([1., 0., 0., 1.]), + # ) + # ] + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=object_locations, + object_quats=object_quats, + object_parents=object_parents, + joints=joints, + body_joints=object_joints, + # sites=sites, + ) diff --git a/third_party/robocasa/robocasa/models/objects/kitchen_object_utils.py b/third_party/robocasa/robocasa/models/objects/kitchen_object_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..aad294c085f48052e409b5def43b9835a548b126 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/kitchen_object_utils.py @@ -0,0 +1,551 @@ +import math +import os +import xml.etree.ElementTree as ET +from copy import deepcopy + +import numpy as np +from robosuite.utils.mjcf_utils import find_elements, string_to_array + +import robocasa +from robocasa.models.objects.kitchen_objects import OBJ_CATEGORIES, OBJ_GROUPS +from robosuite.utils.mjcf_utils import xml_path_completion + +BASE_ASSET_ZOO_PATH = os.path.join(robocasa.models.assets_root, "objects") +OBJ_REGISTRIES = ["objaverse", "aigen", "infinigen", "sketchfab", "lightwheel"] + + +class ObjCat: + """ + Class that encapsulates data for an object category. + + Args: + name (str): name of the object category + + types (tuple) or (str): type(s)/categories the object belongs to. Examples include meat, sweets, fruit, etc. + + model_folders (list): list of folders containing the MJCF models for the object category + + exclude (list): list of model names to exclude + + graspable (bool): whether the object is graspable + + washable (bool): whether the object is washable + + microwavable (bool): whether the object is microwavable + + cookable (bool): whether the object is cookable + + freezable (bool): whether the object is freezable + + scale (float): scale of the object meshes/geoms + + solimp (tuple): solimp values for the object meshes/geoms + + solref (tuple): solref values for the object meshes/geoms + + density (float): density of the object meshes/geoms + + friction (tuple): friction values for the object meshes/geoms + + priority: priority of the object + + aigen_cat (bool): True if the object is an AI-generated object otherwise use obj_registry. Kept for backwards compatibility + + obj_registry (str): the object registry the category belongs to, one of ["objaverse", "aigen", "infinigen", "sketchfab", "lightwheel"] + """ + + def __init__( + self, + name, + types, + model_folders=None, + exclude=None, + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + scale=1.0, + solimp=(0.998, 0.998, 0.001), + solref=(0.001, 2), + margin=0, + density=100, + friction=(0.95, 0.3, 0.1), + priority=None, + aigen_cat=False, + obj_registry="objaverse", + ): + self.name = name + if not isinstance(types, tuple): + types = (types,) + self.types = types + + self.obj_registry = "aigen" if aigen_cat else obj_registry + self.graspable = graspable + self.washable = washable + self.microwavable = microwavable + self.cookable = cookable + self.freezable = freezable + + self.scale = scale + self.solimp = solimp + self.solref = solref + self.margin = margin + self.density = density + self.friction = friction + self.priority = priority + self.exclude = exclude or [] + + if model_folders is None: + if self.obj_registry == "aigen": + subf = "aigen_objs" + else: + subf = self.obj_registry + model_folders = ["{}/{}".format(subf, name)] + cat_mjcf_paths = [] + for folder in model_folders: + cat_path = os.path.join(BASE_ASSET_ZOO_PATH, folder) + for root, _, files in os.walk(cat_path): + if "model.xml" in files: + model_name = os.path.basename(root) + if model_name in self.exclude: + continue + cat_mjcf_paths.append(os.path.join(root, "model.xml")) + self.mjcf_paths = sorted(cat_mjcf_paths) + + def get_mjcf_kwargs(self): + """ + returns relevant data to apply to the MJCF model for the object category + """ + return deepcopy( + dict( + scale=self.scale, + solimp=self.solimp, + solref=self.solref, + density=self.density, + friction=self.friction, + priority=self.priority, + margin=self.margin, + ) + ) + + +# update OBJ_CATEGORIES with ObjCat instances. Maps name to the different registries it can belong to +# and then maps the registry to the ObjCat instance +for name, kwargs in OBJ_CATEGORIES.items(): + + # get the properties that are common across registries + common_properties = deepcopy(kwargs) + valid_properties = [ + "graspable", + "washable", + "microwavable", + "cookable", + "freezable", + "types", + ] + list(OBJ_REGISTRIES) + + for k in common_properties.keys(): + assert k in valid_properties + + # extract registry-specific kwargs + registry_kwargs = {} + for registry in OBJ_REGISTRIES: + registry_kwargs[registry] = common_properties.pop(registry, None) + + assert "scale" not in kwargs + OBJ_CATEGORIES[name] = {} + + # create instances for each registry + for registry in OBJ_REGISTRIES: + if registry_kwargs[registry] is not None: + registry_kwargs[registry].update(common_properties) + OBJ_CATEGORIES[name][registry] = ObjCat( + name=name, obj_registry=registry, **registry_kwargs[registry] + ) + + +def sample_kitchen_object( + groups, + exclude_groups=None, + exclude_cat=None, + graspable=None, + washable=None, + microwavable=None, + cookable=None, + freezable=None, + rng=None, + obj_registries=None, + prefer_leading_registry=False, + prefer_leading_category=False, + prefer_leading_object=False, + split=None, + max_size=(None, None, None), + object_scale=None, +): + """ + Sample a kitchen object from the specified groups and within max_size bounds. + + Args: + groups (list or str): groups to sample from or the exact xml path of the object to spawn + + exclude_groups (str or list): groups to exclude + + exclude_cat (str or list): categories to exclude + + graspable (bool): whether the sampled object must be graspable + + washable (bool): whether the sampled object must be washable + + microwavable (bool): whether the sampled object must be microwavable + + cookable (bool): whether the sampled object must be cookable + + freezable (bool): whether the sampled object must be freezable + + rng (np.random.Generator): random number object + + obj_registries (tuple): registries to sample from + + prefer_leading_registry (bool): sample obj_registries in order instead of random + + prefer_leading_category (bool): sample categories in order instead of random + + prefer_leading_object (bool): sample objects in order instead of random + + split (str): split to sample from. Split "A" specifies all but the last 3 object instances + (or the first half - whichever is larger), "B" specifies the rest, and None specifies all. + + max_size (tuple): max size of the object. If the sampled object is not within bounds of max size, function will resample + + object_scale (float or dict): scale of the object. If set will multiply the scale of the sampled object by this value + + + Returns: + dict: kwargs to apply to the MJCF model for the sampled object + + dict: info about the sampled object - the path of the mjcf, groups which the object's category belongs to, the category of the object + the sampling split the object came from, and the groups the object was sampled from + """ + for obj_registry in obj_registries: + subf = obj_registry if obj_registry != "aigen" else "aigen_objs" + if not os.path.exists(os.path.join(BASE_ASSET_ZOO_PATH, subf)): + script = ( + "download_kitchen_assets.py" + if obj_registry in ("objaverse", "aigen") + else "download_groot_assets.py" + ) + raise FileNotFoundError( + f"Object registry {obj_registry} directory not found at {os.path.join(BASE_ASSET_ZOO_PATH, subf)}. Try running {script}." + ) + + valid_object_sampled = False + while valid_object_sampled is False: + mjcf_kwargs, info = sample_kitchen_object_helper( + groups=groups, + exclude_groups=exclude_groups, + exclude_cat=exclude_cat, + graspable=graspable, + washable=washable, + microwavable=microwavable, + cookable=cookable, + freezable=freezable, + rng=rng, + obj_registries=obj_registries, + prefer_leading_registry=prefer_leading_registry, + prefer_leading_category=prefer_leading_category, + prefer_leading_object=prefer_leading_object, + split=split, + object_scale=object_scale, + ) + + # check if object size is within bounds + mjcf_path = info["mjcf_path"] + tree = ET.parse(mjcf_path) + root = tree.getroot() + bottom = string_to_array( + find_elements(root=root, tags="site", attribs={"name": "bottom_site"}).get( + "pos" + ) + ) + top = string_to_array( + find_elements(root=root, tags="site", attribs={"name": "top_site"}).get( + "pos" + ) + ) + horizontal_radius = string_to_array( + find_elements( + root=root, tags="site", attribs={"name": "horizontal_radius_site"} + ).get("pos") + ) + scale = mjcf_kwargs["scale"] + obj_size = ( + np.array( + [horizontal_radius[0] * 2, horizontal_radius[1] * 2, top[2] - bottom[2]] + ) + * scale + ) + valid_object_sampled = True + for i in range(3): + if max_size[i] is not None and obj_size[i] > max_size[i]: + valid_object_sampled = False + + return mjcf_kwargs, info + + +def sample_kitchen_object_helper( + groups, + exclude_groups=None, + exclude_cat=None, + graspable=None, + washable=None, + microwavable=None, + cookable=None, + freezable=None, + rng=None, + obj_registries=None, + prefer_leading_registry=False, + prefer_leading_category=False, + prefer_leading_object=False, + split=None, + object_scale=None, +): + """ + Helper function to sample a kitchen object. + + Args: + groups (list or str): groups to sample from or the exact xml path of the object to spawn + + exclude_groups (str or list): groups to exclude + + exclude_cat (str or list): categories to exclude + + graspable (bool): whether the sampled object must be graspable + + washable (bool): whether the sampled object must be washable + + microwavable (bool): whether the sampled object must be microwavable + + cookable (bool): whether whether the sampled object must be cookable + + freezable (bool): whether whether the sampled object must be freezable + + rng (np.random.Generator): random number object + + obj_registries (tuple): registries to sample from + + prefer_leading_registry (bool): sample obj_registries in order instead of random + + prefer_leading_category (bool): sample categories in order instead of random + + prefer_leading_object (bool): sample objects in order instead of random + + split (str): split to sample from. Split "A" specifies all but the last 3 object instances + (or the first half - whichever is larger), "B" specifies the rest, and None specifies all. + + object_scale (float): scale of the object. If set will multiply the scale of the sampled object by this value + + + Returns: + dict: kwargs to apply to the MJCF model for the sampled object + + dict: info about the sampled object - the path of the mjcf, groups which the object's category belongs to, the category of the object + the sampling split the object came from, and the groups the object was sampled from + """ + if rng is None: + rng = np.random.default_rng() + + # If all groups are xml paths, randomly select one + if isinstance(groups, (list, tuple)) and all( + isinstance(g, str) and g.endswith(".xml") for g in groups + ): + groups = rng.choice(groups) + + # option to spawn specific object instead of sampling from a group + if isinstance(groups, str) and groups.endswith(".xml"): + mjcf_path = xml_path_completion(groups, root=robocasa.models.assets_root) + # reverse look up mjcf_path to category + mjcf_kwargs = dict() + cat = None + obj_found = False + for cand_cat in OBJ_CATEGORIES: + for reg in obj_registries: + if ( + reg in OBJ_CATEGORIES[cand_cat] + and mjcf_path in OBJ_CATEGORIES[cand_cat][reg].mjcf_paths + ): + mjcf_kwargs = OBJ_CATEGORIES[cand_cat][reg].get_mjcf_kwargs() + cat = cand_cat + obj_found = True + break + if obj_found: + break + if obj_found is False: + raise ValueError( + f"Could not find object with MJCF path: {mjcf_path} in any registered category" + ) + mjcf_kwargs["mjcf_path"] = mjcf_path + else: + if not isinstance(groups, tuple) and not isinstance(groups, list): + groups = [groups] + + if exclude_groups is None: + exclude_groups = [] + if not isinstance(exclude_groups, tuple) and not isinstance( + exclude_groups, list + ): + exclude_groups = [exclude_groups] + + invalid_categories = [] + for g in exclude_groups: + for cat in OBJ_GROUPS[g]: + invalid_categories.append(cat) + + if exclude_cat is None: + exclude_cat = [] + if not isinstance(exclude_cat, tuple) and not isinstance(exclude_cat, list): + exclude_cat = [exclude_cat] + + for cat in exclude_cat: + invalid_categories.append(cat) + + valid_categories = [] + for g in groups: + for cat in OBJ_GROUPS[g]: + # don't repeat if already added + if cat in valid_categories: + continue + if cat in invalid_categories: + continue + + # don't include if category not represented in any registry + # don't include if category has no valid mjcf files + cat_in_any_reg = False + for reg in obj_registries: + if reg in OBJ_CATEGORIES[cat]: + if len(OBJ_CATEGORIES[cat][reg].mjcf_paths) > 0: + cat_in_any_reg = True + else: + print( + f"WARNING: No object files found for category '{cat}' in registry '{reg}'. Check if registry is installed and up to date." + ) + + if not cat_in_any_reg: + continue + + invalid = False + for reg in obj_registries: + if reg not in OBJ_CATEGORIES[cat]: + continue + cat_meta = OBJ_CATEGORIES[cat][reg] + if graspable is True and cat_meta.graspable is not True: + invalid = True + if washable is True and cat_meta.washable is not True: + invalid = True + if microwavable is True and cat_meta.microwavable is not True: + invalid = True + if cookable is True and cat_meta.cookable is not True: + invalid = True + if freezable is True and cat_meta.freezable is not True: + invalid = True + + if invalid: + continue + + valid_categories.append(cat) + + if len(valid_categories) == 0: + raise ValueError( + f"No valid categories found for sampling from groups: {groups}. Check if the object registry is installed and up to date." + ) + + if prefer_leading_category: + cat = valid_categories[0] + else: + cat = rng.choice(valid_categories) + + choices = {reg: [] for reg in obj_registries} + + for reg in obj_registries: + if reg not in OBJ_CATEGORIES[cat]: + choices[reg] = [] + continue + reg_choices = deepcopy(OBJ_CATEGORIES[cat][reg].mjcf_paths) + + if len(reg_choices) == 0: + print( + f"WARNING: Registry '{reg}' is enabled and category '{cat}' claims to support this registry, but no actual object files were found. Is your object registry downloaded and up to date?" + ) + + # exclude out objects based on split + if split is not None: + split_th = max(len(choices) - 3, int(math.ceil(len(reg_choices) / 2))) + if split == "A": + reg_choices = reg_choices[:split_th] + elif split == "B": + reg_choices = reg_choices[split_th:] + else: + raise ValueError + choices[reg] = reg_choices + + if sum(len(choices[reg]) for reg in obj_registries) == 0: + raise ValueError( + f"No valid object files found for category '{cat}' in any enabled registries." + ) + + if prefer_leading_registry: + chosen_reg = next(reg for reg in obj_registries if len(choices[reg]) > 0) + else: + chosen_reg = rng.choice( + obj_registries, + p=np.array([len(choices[reg]) for reg in obj_registries]) + / sum(len(choices[reg]) for reg in obj_registries), + ) + if prefer_leading_object: + mjcf_path = choices[chosen_reg][0] + else: + mjcf_path = rng.choice(choices[chosen_reg]) + mjcf_kwargs = OBJ_CATEGORIES[cat][chosen_reg].get_mjcf_kwargs() + mjcf_kwargs["mjcf_path"] = mjcf_path + + if object_scale is not None: + scale_value = ( + object_scale.get(cat, 1.0) + if isinstance(object_scale, dict) + else object_scale + ) + mjcf_kwargs["scale"] = (np.array(mjcf_kwargs["scale"]) * scale_value).tolist() + + groups_containing_sampled_obj = [] + for group, group_cats in OBJ_GROUPS.items(): + if cat in group_cats: + groups_containing_sampled_obj.append(group) + + info = { + "groups_containing_sampled_obj": groups_containing_sampled_obj, + "groups": groups, + "cat": cat, + "split": split, + "mjcf_path": mjcf_path, + } + + return mjcf_kwargs, info + + +def search_kitchen_object( + groups, + obj_registries=None, +): + mjcf_paths = [] + valid_categories = [] + if not isinstance(groups, tuple) and not isinstance(groups, list): + groups = [groups] + for g in groups: + for cat in OBJ_GROUPS[g]: + if cat in valid_categories: + continue + valid_categories.append(cat) + for reg in obj_registries: + if reg in OBJ_CATEGORIES[cat]: + mjcf_paths.extend(OBJ_CATEGORIES[cat][reg].mjcf_paths) + return mjcf_paths diff --git a/third_party/robocasa/robocasa/models/objects/kitchen_objects.py b/third_party/robocasa/robocasa/models/objects/kitchen_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..c548ad79353088110ac3e34473cc272611f0d347 --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/kitchen_objects.py @@ -0,0 +1,2509 @@ +from typing import List +import os +import robocasa + +BASE_ASSET_ZOO_PATH = os.path.join(robocasa.models.assets_root, "objects") + + +# Constant that contains information about each object category. These will be used to generate the ObjCat classes for each category +OBJ_CATEGORIES = dict( + liquor=dict( + types=("drink", "alcohol"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + model_folders=["aigen_objs/alcohol"], + scale=1.50, + ), + objaverse=dict( + model_folders=["objaverse/alcohol"], + scale=1.35, + ), + ), + apple=dict( + types=("fruit"), + graspable=True, + washable=True, + microwavable=False, + cookable=True, + freezable=False, + aigen=dict( + scale=1.0, + ), + objaverse=dict( + scale=0.90, + ), + ), + avocado=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=0.90, + ), + objaverse=dict( + scale=0.90, + ), + ), + bagel=dict( + types=("bread_food"), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.2, + ), + objaverse=dict( + exclude=[ + "bagel_8", + ], + ), + ), + bagged_food=dict( + types=("packaged_food"), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=1.1, + ), + objaverse=dict( + exclude=[ + "bagged_food_12", + ], + ), + ), + baguette=dict( + types=("bread_food"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=1.35, + ), + objaverse=dict( + exclude=[ + "baguette_3", # small holes on ends + ], + ), + ), + banana=dict( + types=("fruit"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.10, + ), + objaverse=dict( + scale=0.95, + ), + ), + bar=dict( + types=("packaged_food"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=[1.25, 1.25, 1.75], + ), + objaverse=dict( + scale=[0.75, 0.75, 1.2], + exclude=[ + "bar_1", # small holes scattered + ], + ), + ), + bar_soap=dict( + types=("cleaner"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=[1.25, 1.25, 1.40], + ), + objaverse=dict( + scale=[0.95, 0.95, 1.05], + exclude=["bar_soap_2"], + ), + ), + beer=dict( + types=("drink", "alcohol"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.30, + ), + objaverse=dict(scale=1.15), + ), + bell_pepper=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + aigen=dict( + scale=1.0, + ), + objaverse=dict( + scale=0.75, + ), + ), + book=dict( + types=("book"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + sketchfab=dict( + scale=1.0, + ), + ), + bookshelf=dict( + types=("furniture"), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + sketchfab=dict( + scale=1.0, + density=5000, + solimp=(0.95, 0.98, 0.001), + solref=(0.004, 1), + ), + ), + bottled_drink=dict( + types=("drink"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=1.25, + ), + infinigen=dict( + scale=1.25, + ), + objaverse=dict(), + ), + bottled_water=dict( + types=("drink"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=1.30, + ), + objaverse=dict( + scale=1.10, + exclude=[ + "bottled_water_0", # minor hole at top + "bottled_water_5", # causing error. eigenvalues of mesh inertia violate A + B >= C + ], + ), + ), + bowl=dict( + types=("receptacle", "stackable"), + graspable=True, + washable=True, + microwavable=True, + cookable=False, + freezable=False, + aigen=dict( + scale=1.75, + ), + infinigen=dict( + scale=1.0, + ), + objaverse=dict( + scale=2.0, + exclude=[ + "bowl_21", # can see through from bottom of bowl + ], + ), + ), + boxed_drink=dict( + types=("drink"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=1.1, + ), + objaverse=dict( + scale=0.80, + exclude=[ + "boxed_drink_9", # hole on bottom + "boxed_drink_6", # hole on bottom + "boxed_drink_8", # hole on bottom + ], + ), + ), + boxed_food=dict( + types=("packaged_food"), + graspable=True, + washable=False, + microwavable=True, + cookable=False, + freezable=True, + aigen=dict( + scale=1.25, + ), + objaverse=dict( + scale=1.1, + exclude=[ + "boxed_food_5", # causing error. eigenvalues of mesh inertia violate A + B >= C + ], + # exclude=[ + # "boxed_food_5", + # "boxed_food_3", "boxed_food_1", "boxed_food_6", "boxed_food_11", "boxed_food_10", "boxed_food_8", "boxed_food_9", "boxed_food_7", "boxed_food_2", # self turning due to single collision geom + # ], + ), + ), + bread=dict( + types=("bread_food"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=[0.80, 0.80, 1.0], + ), + objaverse=dict( + scale=[0.70, 0.70, 1.0], + exclude=["bread_22"], # hole on bottom + ), + ), + broccoli=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + aigen=dict( + scale=1.35, + ), + objaverse=dict( + scale=1.25, + exclude=[ + "broccoli_2", # holes on one part + ], + ), + ), + cake=dict( + types=("sweets"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=0.8, + ), + objaverse=dict( + scale=0.8, + ), + ), + can=dict( + types=("drink"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict(), + objaverse=dict( + exclude=[ + "can_10", # hole on bottom + "can_5", # causing error: faces of mesh have inconsistent orientation. + ], + ), + infinigen=dict( + scale=1.00, + ), + ), + candle=dict( + types=("decoration"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.5, + ), + objaverse=dict( + exclude=[ + "candle_11", # hole at bottom + # "candle_2", # can't see from bottom view angle + # "candle_15", # can't see from bottom view angle + ], + ), + ), + canned_food=dict( + types=("packaged_food"), + graspable=True, + washable=True, + microwavable=True, + cookable=False, + freezable=True, + aigen=dict( + scale=1.15, + ), + objaverse=dict( + scale=0.90, + exclude=[ + "canned_food_7", # holes at top and bottom + ], + ), + ), + cardboard_box=dict( + types=("receptacle"), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + lightwheel=dict( + exclude=[ + "CardboardBox018", # odd shape + "CardboardBox023", # odd shape + "CardboardBox024", # odd shape + "CardboardBox030", # odd shape + ], + ), + ), + carrot=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + aigen=dict( + scale=1.25, + ), + objaverse=dict(), + ), + cereal=dict( + types=("packaged_food"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.15, + ), + objaverse=dict( + # exclude=[ + # "cereal_2", "cereal_5", "cereal_13", "cereal_3", "cereal_9", "cereal_0", "cereal_7", "cereal_4", "cereal_8", "cereal_12", "cereal_11", "cereal_1", "cereal_6", "cereal_10", # self turning due to single collision geom + # ] + ), + ), + cheese=dict( + types=("dairy"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + aigen=dict( + scale=1.0, + ), + objaverse=dict( + scale=0.85, + ), + ), + chips=dict( + types=("packaged_food"), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.5, + ), + objaverse=dict( + exclude=[ + "chips_12", # minor hole at bottom of bag + # "chips_2", # a weird texture at top/bottom but keeping this + ] + ), + ), + chocolate=dict( + types=("sweets"), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=[1.0, 1.0, 1.35], + ), + objaverse=dict( + scale=[0.80, 0.80, 1.20], + exclude=[ + # "chocolate_2", # self turning due to single collision geom + ], + ), + ), + coffee_cup=dict( + types=("drink"), + graspable=True, + washable=False, + microwavable=True, + cookable=False, + freezable=False, + aigen=dict( + scale=1.35, + ), + objaverse=dict( + exclude=[ + "coffee_cup_18", # can see thru top + "coffee_cup_5", # can see thru from bottom side + "coffee_cup_19", # can see thru from bottom side + ], + ), + ), + coffee_pod=dict( + types=("packaged_food"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + sketchfab=dict( + scale=1.0, + ), + ), + clock=dict( + types=("decoration"), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + sketchfab=dict( + scale=1.0, + ), + ), + condiment_bottle=dict( + types=("condiment"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.35, + model_folders=["aigen_objs/condiment"], + ), + objaverse=dict( + scale=1.05, + model_folders=["objaverse/condiment"], + ), + ), + corn=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + aigen=dict( + scale=1.5, + ), + objaverse=dict(scale=1.05), + ), + croissant=dict( + types=("pastry"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=0.90, + ), + objaverse=dict( + scale=0.90, + ), + ), + cucumber=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=1.1, + ), + objaverse=dict(), + ), + cup=dict( + types=("receptacle", "stackable"), + graspable=True, + washable=True, + microwavable=True, + cookable=False, + freezable=False, + aigen=dict( + scale=1.35, + solimp=(0.95, 0.98, 0.001), + solref=(0.004, 1), + margin=0.004, + ), + infinigen=dict( + scale=1.0, + solimp=(0.95, 0.98, 0.001), + solref=(0.004, 1), + margin=0.004, + ), + objaverse=dict( + solimp=(0.95, 0.98, 0.001), + solref=(0.004, 1), + margin=0.004, + ), + ), + cupcake=dict( + types=("sweets"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=0.90, + ), + objaverse=dict( + exclude=[ + "cupcake_0", # can see thru bottom + "cupcake_10", # can see thru bottom, + "cupcake_1", # very small hole at bottom + ] + ), + ), + cutting_board=dict( + types=("receptacle"), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=2.0, + ), + objaverse=dict( + scale=1.35, + exclude=[ + "cutting_board_14", + "cutting_board_3", + "cutting_board_10", + "cutting_board_6", # these models still modeled with meshes which should work most of the time, but excluding them for safety + ], + ), + ), + dish_rack=dict( + types=("receptacle"), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + sketchfab=dict( + scale=0.8, + ), + lightwheel=dict(), + ), + donut=dict( + types=("sweets", "pastry"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=1.5, + ), + objaverse=dict( + scale=1.15, + ), + ), + egg=dict( + types=("dairy"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + aigen=dict( + scale=1.15, + ), + objaverse=dict( + scale=0.85, + ), + ), + eggplant=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + aigen=dict( + scale=1.30, + ), + objaverse=dict(scale=0.95), + ), + fish=dict( + types=("meat"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + aigen=dict( + scale=[1.35, 1.35, 2.0], + ), + objaverse=dict( + scale=[1.0, 1.0, 1.5], + ), + ), + fork=dict( + types=("utensil"), + graspable=False, + washable=True, + microwavable=True, + cookable=True, + freezable=False, + aigen=dict( + scale=1.75, + ), + infinigen=dict( + scale=1.75, + ), + objaverse=dict(), + ), + garlic=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + aigen=dict( + scale=1.3, + ), + objaverse=dict(scale=1.10, exclude=["garlic_3"]), # has hole on side + ), + glasses=dict( + types=("glasses"), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + sketchfab=dict(scale=1.0), + ), + hot_dog=dict( + types=("cooked_food"), + graspable=True, + washable=False, + microwavable=True, + cookable=False, + freezable=True, + aigen=dict( + scale=1.4, + ), + objaverse=dict(), + ), + jam=dict( + types=("packaged_food"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=1.05, + ), + objaverse=dict( + scale=0.90, + ), + ), + jug=dict( + types=("receptacle"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.5, + ), + objaverse=dict( + scale=1.5, + ), + ), + ketchup=dict( + types=("condiment"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.35, + ), + objaverse=dict( + exclude=[ + "ketchup_5" # causing error: faces of mesh have inconsistent orientation. + ] + ), + ), + kettle_electric=dict( + types=("receptacle"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + objaverse=dict( + scale=1.35, + model_folders=["objaverse/kettle"], + exclude=[ + f"kettle_{i}" + for i in range(29) + if i not in [0, 7, 9, 12, 13, 17, 24, 25, 26, 27] + ], + ), + aigen=dict( + scale=1.5, + model_folders=["aigen_objs/kettle"], + exclude=[f"kettle_{i}" for i in range(11) if i not in [0, 2, 6, 9, 10, 11]], + ), + ), + kettle_non_electric=dict( + types=("receptacle"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + objaverse=dict( + scale=1.35, + model_folders=["objaverse/kettle"], + exclude=[ + f"kettle_{i}" + for i in range(29) + if i in [0, 7, 9, 12, 13, 17, 24, 25, 26, 27] + ], + ), + aigen=dict( + scale=1.5, + model_folders=["aigen_objs/kettle"], + exclude=[f"kettle_{i}" for i in range(11) if i in [0, 2, 6, 9, 10, 11]], + ), + lightwheel=dict(), + ), + kiwi=dict( + types=("fruit"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=0.90, + ), + objaverse=dict( + scale=0.90, + ), + ), + knife=dict( + types=("utensil"), + graspable=False, + washable=True, + microwavable=True, + cookable=True, + freezable=False, + aigen=dict( + scale=1.35, + ), + infinigen=dict( + scale=1.35, + ), + objaverse=dict( + scale=1.20, + ), + ), + ladle=dict( + types=("utensil"), + graspable=True, + washable=True, + microwavable=False, + cookable=True, + freezable=False, + aigen=dict( + scale=1.5, + ), + objaverse=dict( + scale=1.10, + ), + ), + lemon=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=False, + cookable=True, + freezable=True, + aigen=dict( + scale=1.1, + ), + objaverse=dict(), + ), + lime=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=False, + cookable=True, + freezable=True, + objaverse=dict( + scale=1.0, + ), + aigen=dict( + scale=0.90, + ), + ), + mango=dict( + types=("fruit"), + graspable=True, + washable=True, + microwavable=False, + cookable=True, + freezable=True, + aigen=dict( + scale=1.0, + ), + objaverse=dict( + scale=0.85, + exclude=[ + "mango_3", # one half is pitch dark + ], + ), + ), + milk=dict( + types=("dairy", "drink"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.35, + ), + objaverse=dict( + exclude=[ + "milk_6" # causing error: eigenvalues of mesh inertia violate A + B >= C + ] + ), + ), + mug=dict( + types=("receptacle", "stackable"), + graspable=True, + washable=True, + microwavable=True, + cookable=False, + freezable=False, + aigen=dict( + scale=1.0, + ), + objaverse=dict(), + ), + mug_tree=dict( + types=("mug_tree"), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + sketchfab=dict( + scale=1.0, + ), + lightwheel=dict(), + ), + mushroom=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + aigen=dict( + scale=1.35, + ), + objaverse=dict( + scale=1.20, + exclude=[ + # "mushroom_16", # very very small holes. keeping anyway + ], + ), + ), + onion=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=False, + aigen=dict( + scale=1.1, + ), + objaverse=dict(), + ), + orange=dict( + types=("fruit"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.05, + ), + objaverse=dict( + exclude=[ + # "orange_11", # bottom half is dark. keeping anyway + ] + ), + ), + pan=dict( + types=("receptacle"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=2.25, + ), + infinigen=dict( + scale=2.25, + ), + objaverse=dict( + scale=1.70, + exclude=[ + "pan_16", # causing error. faces of mesh have inconsistent orientation, + "pan_0", + "pan_12", + "pan_17", + "pan_22", # these are technically what we consider "pots" + ], + ), + ), + pot=dict( + types=("receptacle"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=2.25, + ), + infinigen=dict( + scale=1.3, + ), + objaverse=dict( + model_folders=["objaverse/pan"], + scale=1.70, + exclude=list( + set([f"pan_{i}" for i in range(25)]) + - set(["pan_0", "pan_12", "pan_17", "pan_22"]) + ), + ), + lightwheel=dict(), + ), + peach=dict( + types=("fruit"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.05, + ), + objaverse=dict(), + ), + pear=dict( + types=("fruit"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict(), + objaverse=dict( + exclude=[ + "pear_4", # has big hole. excluding + ] + ), + ), + pen_holder=dict( + types=("pen_holder"), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + sketchfab=dict( + scale=1.0, + ), + ), + plate=dict( + types=("receptacle"), + graspable=False, + washable=True, + microwavable=True, + cookable=False, + freezable=False, + aigen=dict( + scale=1.65, + ), + infinigen=dict( + scale=1.65, + ), + objaverse=dict( + scale=1.35, + exclude=[ + "plate_6", # causing error: faces of mesh have inconsistent orientation. + ], + ), + ), + placemat=dict( + types=("receptacle"), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + sketchfab=dict( + scale=1.0, + exclude=[ + "placemat_1", # unstable + ], + ), + lightwheel=dict( + scale=0.7, + exclude=["placemat025"], # too long + ), + ), + potato=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + aigen=dict( + scale=1.10, + ), + objaverse=dict(), + ), + rolling_pin=dict( + types=("tool"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.6, + ), + objaverse=dict( + scale=1.25, + exclude=[ + # "rolling_pin_5", # can see thru side handle edges, keeping anyway + # "rolling_pin_1", # can see thru side handle edges, keeping anyway + ], + ), + ), + rubix_cube=dict( + types=("toy"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + sketchfab=dict(scale=1.0), + lightwheel=dict(), + ), + scissors=dict( + types=("tool"), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.35, + ), + objaverse=dict( + scale=1.15, + ), + ), + shaker=dict( + types=("condiment"), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.25, + ), + objaverse=dict(), + ), + soap_dispenser=dict( + types=("cleaner"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.7, + ), + objaverse=dict( + exclude=[ + # "soap_dispenser_4", # can see thru body but that's fine if this is glass + ] + ), + ), + spatula=dict( + types=("utensil"), + graspable=False, + washable=True, + microwavable=False, + cookable=True, + freezable=False, + aigen=dict( + scale=1.30, + ), + objaverse=dict( + scale=1.10, + ), + ), + sponge=dict( + types=("cleaner"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.20, + ), + objaverse=dict( + scale=0.90, + # exclude=[ + # "sponge_7", "sponge_1", # self turning due to single collision geom + # ] + ), + ), + spoon=dict( + types=("utensil"), + graspable=False, + washable=True, + microwavable=True, + cookable=True, + freezable=False, + aigen=dict( + scale=1.5, + ), + infinigen=dict( + scale=1.5, + ), + objaverse=dict(), + ), + spray=dict( + types=("cleaner"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.75, + ), + objaverse=dict( + scale=1.75, + ), + ), + spray_bottle=dict( + types=("cleaner"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + sketchfab=dict( + scale=1.0, + ), + ), + squash=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + aigen=dict( + scale=1.15, + ), + objaverse=dict( + exclude=[ + "squash_10", # hole at bottom + ], + ), + ), + steak=dict( + types=("meat"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + aigen=dict( + scale=[1.0, 1.0, 2.0], + ), + objaverse=dict( + scale=[1.0, 1.0, 2.0], + exclude=[ + "steak_13", # bottom texture completely messed up + "steak_1", # bottom texture completely messed up + # "steak_9", # bottom with some minor issues, keeping anyway + ], + ), + ), + stapler=dict( + types=("tool"), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + sketchfab=dict(scale=1.0), + ), + sweet_potato=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + aigen=dict(), + objaverse=dict(), + ), + tangerine=dict( + types=("fruit"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict(), + objaverse=dict(), + ), + teapot=dict( + types=("receptacle"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.25, + ), + objaverse=dict( + scale=1.25, + exclude=[ + "teapot_9", # hole on bottom + ], + ), + ), + tomato=dict( + types=("vegetable"), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=False, + aigen=dict( + scale=1.25, + ), + objaverse=dict(), + ), + tray=dict( + types=("receptacle"), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict(scale=2.0), + objaverse=dict( + scale=1.80, + ), + lightwheel=dict(), + ), + tupperware=dict( + types=("receptacle"), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + lightwheel=dict(), + ), + waffle=dict( + types=("sweets"), + graspable=False, + washable=False, + microwavable=True, + cookable=False, + freezable=True, + aigen=dict( + scale=1.75, + ), + objaverse=dict( + exclude=[ + "waffle_2", # bottom completely messed up + ] + ), + ), + water_bottle=dict( + types=("drink"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=1.6, + ), + objaverse=dict( + scale=1.5, + exclude=[ + "water_bottle_11", # sides and bottom see thru, but ok if glass. keeping anyway + ], + ), + ), + wine=dict( + types=("drink", "alcohol"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + aigen=dict( + scale=1.9, + ), + objaverse=dict( + scale=1.6, + exclude=[ + "wine_7", # causing error. faces of mesh have inconsistent orientation + ], + ), + ), + yogurt=dict( + types=("dairy", "packaged_food"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + aigen=dict( + scale=1.0, + ), + objaverse=dict( + scale=0.95, + ), + ), + dates=dict( + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + types=("fruit"), + aigen=dict(), + ), + lemonade=dict( + aigen=dict( + scale=1.5, + ), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + types=("drink"), + ), + walnut=dict( + aigen=dict( + scale=1.15, + ), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + types=(), + ), + cheese_grater=dict( + aigen=dict( + scale=2.15, + ), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + types=("tool"), + ), + syrup_bottle=dict( + aigen=dict( + scale=1.35, + ), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + types=("condiment"), + ), + scallops=dict( + aigen=dict( + scale=1.25, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("meat"), + ), + candy=dict( + aigen=dict(), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + types=("sweets"), + ), + whisk=dict( + aigen=dict( + scale=1.8, + ), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + types=("utensil"), + ), + pitcher=dict( + aigen=dict( + scale=1.75, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=False, + freezable=False, + types=("receptacle"), + ), + ice_cream=dict( + aigen=dict( + scale=1.25, + ), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + types=("sweets"), + ), + cherry=dict( + aigen=dict(), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + types=("fruit"), + ), + peanut_butter=dict( + aigen=dict( + scale=1.25, + model_folders=["aigen_objs/peanut_butter_jar"], + ), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + types=("packaged_food"), + ), + thermos=dict( + aigen=dict( + scale=1.75, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=False, + freezable=True, + types=("drink"), + ), + ham=dict( + aigen=dict( + scale=1.5, + ), + graspable=False, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("meat"), + ), + dumpling=dict( + aigen=dict( + scale=1.15, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("meat", "cooked_food"), + ), + cabbage=dict( + aigen=dict( + scale=2.0, + ), + graspable=False, + washable=True, + microwavable=False, + cookable=True, + freezable=True, + types=("vegetable"), + ), + lettuce=dict( + aigen=dict( + scale=2.0, + ), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + types=("vegetable"), + ), + tongs=dict( + aigen=dict( + scale=1.5, + ), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + types=("tool"), + ), + ginger=dict( + aigen=dict( + scale=1.35, + ), + graspable=True, + washable=True, + microwavable=False, + cookable=True, + freezable=True, + types=("vegetable"), + ), + ice_cube_tray=dict( + aigen=dict( + scale=2.0, + ), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + types=("receptacle"), + ), + shrimp=dict( + aigen=dict( + scale=1.15, + ), + graspable=False, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("meat"), + ), + cantaloupe=dict( + aigen=dict( + scale=1.5, + ), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + types=("fruit"), + ), + honey_bottle=dict( + aigen=dict( + scale=1.10, + ), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + types=("packaged_food"), + ), + grapes=dict( + aigen=dict( + scale=1.5, + ), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + types=("fruit"), + ), + spaghetti_box=dict( + aigen=dict( + scale=1.25, + ), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + types=("packaged_food"), + ), + chili_pepper=dict( + aigen=dict( + scale=1.10, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("vegetable"), + ), + celery=dict( + aigen=dict( + scale=2.0, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("vegetable"), + ), + burrito=dict( + aigen=dict( + scale=1.35, + ), + graspable=True, + washable=False, + microwavable=True, + cookable=False, + freezable=True, + types=("cooked_food"), + ), + olive_oil_bottle=dict( + aigen=dict( + scale=1.5, + ), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + types=("packaged_food"), + ), + kebabs=dict( + aigen=dict( + scale=1.65, + ), + graspable=True, + washable=False, + microwavable=True, + cookable=True, + freezable=True, + types=("cooked_food"), + ), + bottle_opener=dict( + aigen=dict(), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + types=("tool"), + ), + chicken_breast=dict( + aigen=dict( + scale=1.35, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("meat"), + ), + jello_cup=dict( + aigen=dict( + scale=1.15, + ), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + types=("packaged_food"), + ), + lobster=dict( + aigen=dict( + scale=1.15, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("meat"), + ), + brussel_sprout=dict( + aigen=dict(), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("vegetable"), + ), + sushi=dict( + aigen=dict( + scale=0.90, + ), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + types=("meat"), + ), + baking_sheet=dict( + aigen=dict( + scale=1.75, + ), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + types=("receptacle"), + ), + wine_glass=dict( + aigen=dict( + scale=1.5, + ), + infinigen=dict( + scale=1.0, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=False, + freezable=True, + types=("receptacle"), + ), + asparagus=dict( + aigen=dict( + scale=1.35, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("vegetable"), + ), + lamb_chop=dict( + aigen=dict( + scale=1.15, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("meat"), + ), + pickle=dict( + aigen=dict( + scale=1.0, + ), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + types=("vegetable"), + ), + bacon=dict( + aigen=dict( + scale=1.35, + ), + graspable=False, + washable=False, + microwavable=True, + cookable=True, + freezable=False, + types=("meat"), + ), + canola_oil=dict( + aigen=dict( + scale=1.75, + ), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + types=("packaged_food"), + ), + strawberry=dict( + aigen=dict( + scale=0.9, + ), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + types=("fruit"), + ), + watermelon=dict( + aigen=dict( + scale=2.5, + ), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + types=("fruit"), + ), + pizza_cutter=dict( + aigen=dict( + scale=1.4, + ), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + types=("tool"), + ), + pomegranate=dict( + aigen=dict( + scale=1.25, + ), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + types=("fruit"), + ), + apricot=dict( + aigen=dict( + scale=0.7, + ), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + types=("fruit"), + ), + beet=dict( + aigen=dict(), + graspable=True, + washable=True, + microwavable=False, + cookable=True, + freezable=False, + types=("vegetable"), + ), + radish=dict( + aigen=dict( + scale=1.0, + ), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + types=("vegetable"), + ), + salsa=dict( + aigen=dict( + scale=1.15, + ), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + types=("packaged_food"), + ), + artichoke=dict( + aigen=dict( + scale=1.35, + ), + graspable=True, + washable=True, + microwavable=False, + cookable=True, + freezable=False, + types=("vegetable"), + ), + scone=dict( + aigen=dict( + scale=1.35, + ), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + types=("pastry", "bread_food"), + ), + hamburger=dict( + aigen=dict( + scale=1.35, + ), + graspable=True, + washable=False, + microwavable=True, + cookable=False, + freezable=False, + types=("cooked_food"), + ), + raspberry=dict( + aigen=dict( + scale=0.85, + ), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + types=("fruit"), + ), + tacos=dict( + aigen=dict( + scale=1.0, + ), + graspable=True, + washable=False, + microwavable=True, + cookable=False, + freezable=False, + types=("cooked_food"), + ), + vinegar=dict( + aigen=dict( + scale=1.4, + ), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + types=("packaged_food", "condiment"), + ), + zucchini=dict( + aigen=dict( + scale=1.35, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("vegetable"), + ), + pork_loin=dict( + aigen=dict(), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("meat"), + ), + pork_chop=dict( + aigen=dict( + scale=1.25, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("meat"), + ), + sausage=dict( + aigen=dict( + scale=1.45, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("meat"), + ), + coconut=dict( + aigen=dict( + scale=2.0, + ), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + types=("fruit"), + ), + cauliflower=dict( + aigen=dict( + scale=1.5, + ), + graspable=False, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("vegetable"), + ), + lollipop=dict( + aigen=dict(), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + types=("sweets"), + ), + salami=dict( + aigen=dict( + scale=1.5, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=True, + types=("meat"), + ), + butter_stick=dict( + aigen=dict( + scale=1.3, + ), + graspable=True, + washable=False, + microwavable=True, + cookable=True, + freezable=True, + types=("dairy"), + ), + can_opener=dict( + aigen=dict( + scale=1.5, + ), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + types=("tool"), + ), + tofu=dict( + aigen=dict(), + graspable=True, + washable=True, + microwavable=False, + cookable=True, + freezable=True, + types=(), + ), + pineapple=dict( + aigen=dict( + scale=2.0, + ), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=True, + types=("fruit"), + ), + skewers=dict( + aigen=dict( + scale=1.75, + ), + graspable=True, + washable=True, + microwavable=True, + cookable=True, + freezable=False, + types=("meat", "cooked_food"), + ), + lid=dict( + types=("receptacle"), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + infinigen=dict( + scale=1.80, + ), + ), + jar=dict( + infinigen=dict( + scale=1.00, + ), + graspable=True, + washable=False, + microwavable=False, + cookable=False, + freezable=True, + types=("packaged_food"), + ), + chopstick=dict( + types=("utensil"), + graspable=False, + washable=True, + microwavable=True, + cookable=True, + freezable=False, + infinigen=dict( + scale=1.75, + ), + ), + basket=dict( + types=("receptacle"), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + infinigen=dict( + scale=2.0, + ), + sketchfab=dict( + scale=0.7, + exclude=[ + "basket_5", # too narrow + ], + ), + lightwheel=dict( + exclude=[ + "Basket038", # odd shape + ], + ), + ), + tiered_basket=dict( + types=("tiered_basket"), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + sketchfab=dict( + scale=1.0, + density=5000, + solimp=(0.95, 0.98, 0.001), + solref=(0.004, 1), + ), + lightwheel=dict( + density=5000, + solimp=(0.95, 0.98, 0.001), + solref=(0.004, 1), + exclude=[ + "TieredBasket008", # too complicated spawn region + "TieredBasket011", # no space on the top layer + "TieredBasket023", # no space on the top layer + ], + ), + ), + tiered_shelf=dict( + types=("tiered_shelf"), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + # sketchfab=dict( + # scale=1.0, + # exclude=[ + # "tiered_shelf_0", # unstable + # "tiered_shelf_1", # too high + # "tiered_shelf_2", # too high + # "tiered_shelf_3", # missing texture + # "tiered_shelf_4", # too high + # ], + # density=5000, + # solimp=(0.95, 0.98, 0.001), + # solref=(0.004, 1), + # ), + lightwheel=dict( + density=5000, + solimp=(0.95, 0.98, 0.001), + solref=(0.004, 1), + exclude=[ + "TieredShelf004", # too high + ], + ), + ), + plate_rack=dict( + types=("receptacle"), + graspable=False, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + infinigen=dict( + scale=1.50, + ), + ), + large_shelf=dict( + types=("receptacle"), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + infinigen=dict( + scale=6.0, + ), + ), + cell_shelf=dict( + types=("receptacle"), + graspable=False, + washable=False, + microwavable=False, + cookable=False, + freezable=False, + infinigen=dict( + scale=6.0, + ), + ), + laptop=dict( + types=("laptop"), + graspable=True, + washable=True, + microwavable=False, + cookable=False, + freezable=False, + sketchfab=dict( + scale=1.0, + ), + ), +) + + +def get_cats_by_type(types, obj_registries=None): + """ + Retrieves a list of item keys from the global `OBJ_CATEGORIES` dictionary based on the specified types. + + Args: + types (list): A list of valid types to filter items by. Only items with a matching type will be included. + obj_registries (list): only consider categories belonging to these object registries + + Returns: + list: A list of keys from `OBJ_CATEGORIES` where the item's types intersect with the provided `types`. + """ + types = set(types) + + res = [] + for key, val in OBJ_CATEGORIES.items(): + # check if category is in one of valid object registries + if obj_registries is not None: + if isinstance(obj_registries, str): + obj_registries = [obj_registries] + if any([reg in val for reg in obj_registries]) is False: + continue + + if "types" in val: + cat_types = val["types"] + else: + cat_types = list(val.values())[0].types + if isinstance(cat_types, str): + cat_types = [cat_types] + cat_types = set(cat_types) + # Access the "types" key in the dictionary using the correct syntax + if len(cat_types.intersection(types)) > 0: + res.append(key) + + return res + + +### define all object categories ### +OBJ_GROUPS = dict( + all=list(OBJ_CATEGORIES.keys()), +) + +for k in OBJ_CATEGORIES: + OBJ_GROUPS[k] = [k] + +all_types = set() +# populate all_types +for cat, cat_meta_dict in OBJ_CATEGORIES.items(): + # types are common to both so we only need to examine one + cat_types = cat_meta_dict["types"] + if isinstance(cat_types, str): + cat_types = [cat_types] + all_types = all_types.union(cat_types) + +for t in all_types: + OBJ_GROUPS[t] = get_cats_by_type(types=[t]) + +OBJ_GROUPS["food"] = get_cats_by_type( + [ + "vegetable", + "fruit", + "sweets", + "dairy", + "meat", + "bread_food", + "pastry", + "cooked_food", + ] +) +OBJ_GROUPS["in_container"] = get_cats_by_type( + [ + "toy", + "vegetable", + "fruit", + "sweets", + "dairy", + "meat", + "bread_food", + "pastry", + "cooked_food", + "drink", + ] +) + +# custom groups +OBJ_GROUPS["container"] = ["plate"] # , "bowl"] +OBJ_GROUPS["kettle"] = ["kettle_electric", "kettle_non_electric"] +OBJ_GROUPS["cookware"] = ["pan", "pot", "kettle_non_electric"] +OBJ_GROUPS["pots_and_pans"] = ["pan", "pot"] +OBJ_GROUPS["food_set1"] = [ + "apple", + "baguette", + "banana", + "carrot", + "cheese", + "cucumber", + "egg", + "lemon", + "orange", + "potato", +] +OBJ_GROUPS["group1"] = ["apple", "carrot", "banana", "bowl", "can"] +OBJ_GROUPS["container_set2"] = ["plate", "bowl"] + + +def get_all_obj_cats( + groups: List[str] = None, registries: List[str] = None, attrs: List[str] = None +) -> List[str]: + """Get all object categories for given groups, registries, and attributes.""" + if groups is None: + groups = OBJ_GROUPS.keys() + if registries is None: + registries = {"objaverse", "sketchfab", "lightwheel"} + if attrs is None: + attrs = [] + + res = [] + for group in groups: + for obj_cat in OBJ_GROUPS[group]: + if any( + registry in OBJ_CATEGORIES[obj_cat] + and len(OBJ_CATEGORIES[obj_cat][registry].mjcf_paths) > 0 + and all( + getattr(OBJ_CATEGORIES[obj_cat][registry], attr, False) + for attr in attrs + ) + for registry in registries + ): + res.append(obj_cat) + return res diff --git a/third_party/robocasa/robocasa/models/objects/objects.py b/third_party/robocasa/robocasa/models/objects/objects.py new file mode 100644 index 0000000000000000000000000000000000000000..6f0bd2af9eee000ed2ec68fae5c82b349704f26e --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/objects.py @@ -0,0 +1,290 @@ +import os +import time +import xml.etree.ElementTree as ET + +import mujoco +import numpy as np +import robosuite +import robosuite.utils.transform_utils as T +from robosuite.models.objects import MujocoXMLObject +from robosuite.utils.mjcf_utils import array_to_string, string_to_array +from robosuite.environments.robot_env import RobotEnv + + +class MJCFObject(MujocoXMLObject): + """ + Blender object with support for changing the scaling + """ + + def __init__( + self, + name, + mjcf_path, + scale=1.0, + solimp=(0.998, 0.998, 0.001), + solref=(0.001, 1), + density=100, + friction=(0.95, 0.3, 0.1), + margin=None, + rgba=None, + priority=None, + static=False, + ): + # get scale in x, y, z + if isinstance(scale, float): + scale = [scale, scale, scale] + elif isinstance(scale, tuple) or isinstance(scale, list): + assert len(scale) == 3 + scale = tuple(scale) + else: + raise Exception("got invalid scale: {}".format(scale)) + scale = np.array(scale) + + self.solimp = solimp + self.solref = solref + self.density = density + self.friction = friction + self.margin = margin + + self.priority = priority + + self.rgba = rgba + + # read default xml + xml_path = mjcf_path + folder = os.path.dirname(xml_path) + tree = ET.parse(xml_path) + root = tree.getroot() + + # write modified xml (and make sure to postprocess any paths just in case) + xml_str = ET.tostring(root, encoding="utf8").decode("utf8") + xml_str = self.postprocess_model_xml(xml_str) + time_str = str(time.time()).replace(".", "_") + new_xml_path = os.path.join(folder, "{}_{}.xml".format(time_str, os.getpid())) + f = open(new_xml_path, "w") + f.write(xml_str) + f.close() + + # initialize object with new xml we wrote + super().__init__( + fname=new_xml_path, + name=name, + joints=None if static else [dict(type="free", damping="0.0005")], + obj_type="all", + duplicate_collision_geoms=False, + scale=scale, + ) + + self.spawns = [] + self._disabled_spawns = set() + for s in self.worldbody.findall("./body/body/geom"): + geom_name = s.get("name") + if geom_name and geom_name.startswith( + "{}spawn_".format(self.naming_prefix) + ): + self.spawns.append(s) + + # clean up xml - we don't need it anymore + if os.path.exists(new_xml_path): + os.remove(new_xml_path) + + def postprocess_model_xml(self, xml_str): + """ + New version of postprocess model xml that only replaces robosuite file paths if necessary (otherwise + there is an error with the "max" operation) + """ + + path = os.path.split(robosuite.__file__)[0] + path_split = path.split("/") + + # replace mesh and texture file paths + tree = ET.fromstring(xml_str) + root = tree + asset = root.find("asset") + meshes = asset.findall("mesh") + textures = asset.findall("texture") + all_elements = meshes + textures + + for elem in all_elements: + old_path = elem.get("file") + if old_path is None: + continue + + old_path_split = old_path.split("/") + # maybe replace all paths to robosuite assets + check_lst = [ + loc for loc, val in enumerate(old_path_split) if val == "robosuite" + ] + if len(check_lst) > 0: + ind = max(check_lst) # last occurrence index + new_path_split = path_split + old_path_split[ind + 1 :] + new_path = "/".join(new_path_split) + elem.set("file", new_path) + + return ET.tostring(root, encoding="utf8").decode("utf8") + + def _get_geoms(self, root, _parent=None): + """ + Helper function to recursively search through element tree starting at @root and returns + a list of (parent, child) tuples where the child is a geom element + + Args: + root (ET.Element): Root of xml element tree to start recursively searching through + + _parent (ET.Element): Parent of the root element tree. Should not be used externally; only set + during the recursive call + + Returns: + list: array of (parent, child) tuples where the child element is a geom type + """ + geom_pairs = super(MJCFObject, self)._get_geoms(root=root, _parent=_parent) + + # modify geoms according to the attributes + for i, (parent, element) in enumerate(geom_pairs): + element.set("solref", array_to_string(self.solref)) + element.set("solimp", array_to_string(self.solimp)) + element.set("density", str(self.density)) + element.set("friction", array_to_string(self.friction)) + if self.margin is not None: + element.set("margin", str(self.margin)) + + if (self.rgba is not None) and (element.get("group") == "1"): + element.set("rgba", array_to_string(self.rgba)) + + if self.priority is not None: + # set high priorit + element.set("priority", str(self.priority)) + + return geom_pairs + + def get_joint(self, joint_name: str): + _, _, joints = self._get_elements_by_name( + geom_names=[], body_names=[], joint_names=[joint_name] + ) + return joints[joint_name] + + @property + def horizontal_radius(self): + horizontal_radius_site = self.worldbody.find( + "./body/site[@name='{}horizontal_radius_site']".format(self.naming_prefix) + ) + site_values = string_to_array(horizontal_radius_site.get("pos")) + return np.linalg.norm(site_values[0:2]) + + def get_bbox_points(self, trans=None, rot=None) -> list[np.ndarray]: + """ + Get the full 8 bounding box points of the object + rot: a rotation matrix + """ + bottom_offset = self.bottom_offset + top_offset = self.top_offset + horizontal_radius_site = self.worldbody.find( + "./body/site[@name='{}horizontal_radius_site']".format(self.naming_prefix) + ) + horiz_radius = string_to_array(horizontal_radius_site.get("pos"))[:2] + return self._get_bbox_points( + bottom_offset=bottom_offset, + top_offset=top_offset, + radius=horiz_radius, + trans=trans, + rot=rot, + ) + + @staticmethod + def _get_bbox_points( + bottom_offset, top_offset, radius, trans=None, rot=None + ) -> list[np.ndarray]: + """ + Helper function to get the full 8 bounding box points of the object. + """ + center = np.mean([bottom_offset, top_offset], axis=0) + half_size = [radius[0], radius[1], top_offset[2] - center[2]] + + bbox_offsets = [ + center + half_size * np.array([-1, -1, -1]), # p0 + center + half_size * np.array([1, -1, -1]), # px + center + half_size * np.array([-1, 1, -1]), # py + center + half_size * np.array([-1, -1, 1]), # pz + center + half_size * np.array([1, 1, 1]), + center + half_size * np.array([-1, 1, 1]), + center + half_size * np.array([1, -1, 1]), + center + half_size * np.array([1, 1, -1]), + ] + + if trans is None: + trans = np.array([0, 0, 0]) + if rot is not None: + rot = T.quat2mat(rot) + else: + rot = np.eye(3) + + points = [(np.matmul(rot, p) + trans) for p in bbox_offsets] + return points + + @staticmethod + def get_spawn_bottom_offset(site: ET.Element) -> np.array: + """ + Get bottom offset of the spawn zone. + """ + site_pos = string_to_array(site.get("pos")) + site_size = ( + string_to_array(site.get("size")) + if site.get("type") == "box" + else np.zeros(3) + ) + return site_pos - np.array([0, 0, site_size[-1]]) + + def get_random_spawn( + self, rng, exclude_disabled: bool = False + ) -> tuple[int, ET.Element]: + """ + Get random spawn site. + """ + options = [o for o in range(0, len(self.spawns))] + if exclude_disabled: + options = [o for o in options if o not in self._disabled_spawns] + spawn_id = rng.choice(options) + return spawn_id, self.spawns[spawn_id] + + def set_spawn_active(self, spawn_id: int, active: bool): + """ + Update the activity state of a spawn site. Disabled sites are excluded from random sampling. + """ + if active and spawn_id in self._disabled_spawns: + self._disabled_spawns.remove(spawn_id) + elif not active: + self._disabled_spawns.add(spawn_id) + + def closest_spawn_id( + self, env: RobotEnv, obj: "MJCFObject", max_distance: float = 1.0 + ) -> int: + if len(self.spawns) == 0: + return -1 + if not env.check_contact(self, obj): + return -1 + obj_pos = env.sim.data.body_xpos[env.sim.model.body_name2id(obj.root_body)] + distances = [] + for spawn_id in range(len(self.spawns)): + spawn_pos = env.sim.data.get_geom_xpos(self.spawns[spawn_id].get("name")) + distance = np.linalg.norm(spawn_pos - obj_pos) + distances.append((spawn_id, distance)) + distances = sorted(distances, key=lambda item: item[1]) + obj_geom_ids = [env.sim.model.geom_name2id(g) for g in obj.contact_geoms] + for spawn_id, distance in distances: + spawn_geom_id = env.sim.model.geom_name2id( + self.spawns[spawn_id].get("name") + ) + for obj_geom_id in obj_geom_ids: + real_distance = mujoco.mj_geomDistance( + m=env.sim.model._model, + d=env.sim.data._data, + geom1=spawn_geom_id, + geom2=obj_geom_id, + distmax=max_distance, + fromto=None, + ) + if real_distance <= 0: + return spawn_id + if real_distance >= max_distance: + return -1 + return -1 diff --git a/third_party/robocasa/robocasa/models/objects/xml_objects.py b/third_party/robocasa/robocasa/models/objects/xml_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..4700675e5c2bc1cefe3a39317c4197a11a351b2a --- /dev/null +++ b/third_party/robocasa/robocasa/models/objects/xml_objects.py @@ -0,0 +1,271 @@ +import os +import time +import xml.etree.ElementTree as ET +import numpy as np +from robosuite.models.objects import MujocoXMLObject +from robosuite.utils.mjcf_utils import array_to_string, find_elements, string_to_array +import robocasa + +XML_ASSETS_BASE_PATH = os.path.join(robocasa.__path__[0], "models/assets/gear_kitchen") + + +class BlenderObject(MujocoXMLObject): + """ + Blender object with support for changing the scaling + """ + + def __init__( + self, + name, + mjcf_path, + scale=1.0, + solimp=(0.998, 0.998, 0.001), + solref=(0.001, 1), + density=100, + friction=(0.95, 0.3, 0.1), + margin=None, + rgba=None, + ): + # get scale in x, y, z + if isinstance(scale, float): + scale = [scale, scale, scale] + elif isinstance(scale, tuple) or isinstance(scale, list): + assert len(scale) == 3 + scale = tuple(scale) + else: + raise Exception("got invalid scale: {}".format(scale)) + scale = np.array(scale) + + self.solimp = solimp + self.solref = solref + self.density = density + self.friction = friction + self.margin = margin + + self.rgba = rgba + + # read default xml + xml_path = mjcf_path + folder = os.path.dirname(xml_path) + tree = ET.parse(xml_path) + root = tree.getroot() + + # modify mesh scales + asset = root.find("asset") + meshes = asset.findall("mesh") + for mesh in meshes: + # if a scale already exists, multiply the scales + scale_to_set = scale + existing_scale = mesh.get("scale") + if existing_scale is not None: + scale_to_set = string_to_array(existing_scale) * scale + mesh.set("scale", array_to_string(scale_to_set)) + + # modify sites for collision (assumes we can just scale up the locations - may or may not work) + for n in ["bottom_site", "top_site", "horizontal_radius_site"]: + site = root.find("worldbody/body/site[@name='{}']".format(n)) + pos = string_to_array(site.get("pos")) + pos = scale * pos + site.set("pos", array_to_string(pos)) + + # write modified xml (and make sure to postprocess any paths just in case) + xml_str = ET.tostring(root, encoding="utf8").decode("utf8") + # xml_str = postprocess_model_xml(xml_str) + time_str = str(time.time()).replace(".", "_") + new_xml_path = os.path.join(folder, "{}_{}.xml".format(time_str, os.getpid())) + f = open(new_xml_path, "w") + f.write(xml_str) + f.close() + # print(f"Write to {new_xml_path}") + + # initialize object with new xml we wrote + super().__init__( + fname=new_xml_path, + name=name, + joints=[dict(type="free", damping="0.0005")], + obj_type="all", + duplicate_collision_geoms=False, + ) + + # clean up xml - we don't need it anymore + if os.path.exists(new_xml_path): + os.remove(new_xml_path) + + def _get_geoms(self, root, _parent=None): + """ + Helper function to recursively search through element tree starting at @root and returns + a list of (parent, child) tuples where the child is a geom element + + Args: + root (ET.Element): Root of xml element tree to start recursively searching through + _parent (ET.Element): Parent of the root element tree. Should not be used externally; only set + during the recursive call + + Returns: + list: array of (parent, child) tuples where the child element is a geom type + """ + geom_pairs = super(BlenderObject, self)._get_geoms(root=root, _parent=_parent) + + # modify geoms according to the attributes + for i, (parent, element) in enumerate(geom_pairs): + element.set("solref", array_to_string(self.solref)) + element.set("solimp", array_to_string(self.solimp)) + element.set("density", str(self.density)) + element.set("friction", array_to_string(self.friction)) + if self.margin is not None: + element.set("margin", str(self.margin)) + + if (self.rgba is not None) and (element.get("group") == "1"): + element.set("rgba", array_to_string(self.rgba)) + + return geom_pairs + + +class CoffeeMachinePodObject(MujocoXMLObject): + """ + Coffee pod object (used in Coffee task). + """ + + def __init__(self, name, margin=1.0): + self._horizontal_radius_margin = margin + super().__init__( + os.path.join(XML_ASSETS_BASE_PATH, "objects/coffee_pod.xml"), + # name=name, joints=[dict(type="free", damping="0.0005")], + name=name, + joints=[dict(type="free")], + obj_type="all", + duplicate_collision_geoms=True, + ) + + @property + def horizontal_radius(self): + horizontal_radius_site = self.worldbody.find( + "./body/site[@name='{}horizontal_radius_site']".format(self.naming_prefix) + ) + return ( + self._horizontal_radius_margin + * string_to_array(horizontal_radius_site.get("pos"))[0] + ) + + +class CoffeeMachineBodyObject(MujocoXMLObject): + """ + Coffee machine body piece (used in Coffee task). Note that the piece is rigid (no joint is added). + """ + + def __init__(self, name): + super().__init__( + os.path.join(XML_ASSETS_BASE_PATH, "objects/coffee_body.xml"), + name=name, + joints=None, + obj_type="all", + duplicate_collision_geoms=True, + ) + + +class CoffeeMachineLidObject(MujocoXMLObject): + """ + Coffee machine lid piece (used in Coffee task). + """ + + def __init__(self, name): + super().__init__( + os.path.join(XML_ASSETS_BASE_PATH, "objects/coffee_lid.xml"), + name=name, + joints=None, + obj_type="all", + duplicate_collision_geoms=True, + ) + + +class CoffeeMachineBaseObject(MujocoXMLObject): + """ + Coffee machine base piece (used in Coffee task). Note that the piece is rigid (no joint is added). + """ + + def __init__(self, name): + super().__init__( + os.path.join(XML_ASSETS_BASE_PATH, "objects/coffee_base.xml"), + name=name, + joints=None, + obj_type="all", + duplicate_collision_geoms=True, + ) + + +class DrawerObject(MujocoXMLObject): + """ + Custom version of cabinet object that differs from BUDs. It has manually specified top, bottom, and horizontal sites. + """ + + def __init__(self, name, joints=None): + + # original cabinet xml + # path_to_cabinet_xml = os.path.join(robosuite_task_zoo.__path__[0], "models/hammer_place/cabinet.xml") + + # our custom cabinet xml - names the drawer bottom geom for easy contact checking + # path_to_cabinet_xml = os.path.join(mimicgen.__path__[0], "envs/robosuite/assets/cabinet.xml") + path_to_cabinet_xml = os.path.join(XML_ASSETS_BASE_PATH, "objects/cabinet.xml") + + # path to modified xml from Danfei's student + # path_to_cabinet_xml = os.path.join(XML_ASSETS_BASE_PATH, "objects/cabinet1.xml") + + super().__init__( + path_to_cabinet_xml, + name=name, + joints=None, + obj_type="all", + duplicate_collision_geoms=True, + ) + + # NOTE: had to manually set these to get placement sampler working okay + @property + def bottom_offset(self): + return np.array([0, 0, -0.065]) + + @property + def top_offset(self): + return np.array([0, 0, 0.065]) + + @property + def horizontal_radius(self): + return 0.15 + + @property + def body_size(self): + return (0.5, 0.4, 0.3) + + +class LongDrawerObject(MujocoXMLObject): + """ + Drawer that has longer platform for easier grasping of objects inside. + """ + + def __init__(self, name, joints=None): + + # our custom cabinet xml - has some longer geoms for the drawer platform + path_to_cabinet_xml = os.path.join( + XML_ASSETS_BASE_PATH, "objects/drawer_long.xml" + ) + + super().__init__( + path_to_cabinet_xml, + name=name, + joints=None, + obj_type="all", + duplicate_collision_geoms=True, + ) + + # NOTE: had to manually set these to get placement sampler working okay + @property + def bottom_offset(self): + return np.array([0, 0, -0.065]) + + @property + def top_offset(self): + return np.array([0, 0, 0.065]) + + @property + def horizontal_radius(self): + # TODO: this might need to change now + return 0.15 diff --git a/third_party/robocasa/robocasa/models/robots/__init__.py b/third_party/robocasa/robocasa/models/robots/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f87a0cc9efe5384c813e3eafd74e99ddf8e411df --- /dev/null +++ b/third_party/robocasa/robocasa/models/robots/__init__.py @@ -0,0 +1,748 @@ +import mujoco +import numpy as np + +from robosuite.controllers.parts.generic.joint_pos import JointPositionController +from robosuite.controllers.parts.arm.osc import OperationalSpaceController +from robosuite.controllers.parts.gripper.simple_grip import SimpleGripController +from robosuite.controllers.composite.composite_controller import HybridMobileBase +from robosuite.models.grippers import ( + PandaGripper, + InspireLeftHand, + InspireRightHand, + FourierLeftHand, + FourierRightHand, +) + +from .manipulators import * + + +# This function returns in the order of the gripper XML's joints. +def unformat_gripper_space(gripper, formatted_action): + formatted_action = np.array(formatted_action) + if isinstance(gripper, InspireLeftHand) or isinstance(gripper, InspireRightHand): + action = formatted_action[[0, 2, 4, 6, 8, 11]] + elif isinstance(gripper, FourierLeftHand) or isinstance(gripper, FourierRightHand): + action = formatted_action[[0, 1, 4, 6, 8, 10]] + elif isinstance(gripper, PandaGripper): + action = formatted_action + else: + raise TypeError + return action + + +def _reconstruct_latest_action_gr1_impl(robot, verbose=False): + action_dict = {} + cc = robot.composite_controller + pf = robot.robot_model.naming_prefix + + for part_name, controller in cc.part_controllers.items(): + if isinstance(controller, JointPositionController): + assert controller.input_type == "absolute" + act = controller.goal_qpos + elif isinstance(controller, SimpleGripController): + assert not controller.use_action_scaling + act = unformat_gripper_space(cc.grippers[part_name], controller.goal_qvel) + else: + raise TypeError + action_dict[f"{pf}{part_name}"] = act + + if verbose: + print("Actions:", [(k, len(action_dict[k])) for k in action_dict]) + + return action_dict + + +def _reconstruct_latest_action_panda_impl(robot, action, verbose=False): + action_dict = {} + cc = robot.composite_controller + pf = robot.robot_model.naming_prefix + + for part_name, controller in cc.part_controllers.items(): + start_idx, end_idx = cc._action_split_indexes[part_name] + act = action[start_idx:end_idx] + # split action deeper for OSC + action_dict[f"{pf}{part_name}"] = act + + if verbose: + print("Actions:", [(k, len(action_dict[k])) for k in action_dict]) + + return action_dict + + +# This function tries to get all joints value, but sometimes we want to keep original action +# The function must be called after robot.control() +def reconstruct_latest_actions(env, actions=None, verbose=False): + if actions is None: + actions = np.zeros(env.action_dim) + action_dict = {} + cutoff = 0 + for robot in env.robots: + cc = robot.composite_controller + pf = robot.robot_model.naming_prefix + robot_action = actions[cutoff : cutoff + robot.action_dim] + cutoff += robot.action_dim + if "GR1" in robot.name: + action_dict.update(_reconstruct_latest_action_gr1_impl(robot)) + elif "Panda" in robot.name: + action_dict.update( + _reconstruct_latest_action_panda_impl(robot, robot_action) + ) + else: + raise ValueError(f"Unknown robot name: {robot.name}") + if isinstance(cc, HybridMobileBase): + action_dict[f"{pf}base_mode"] = robot_action[-1] + + if verbose: + print("Actions:", [(k, len(action_dict[k])) for k in action_dict]) + + return action_dict + + +def gather_robot_observations(env, verbose=False): + observations = {} + + for robot_id, robot in enumerate(env.robots): + sim = robot.sim + gripper_names = { + robot.get_gripper_name(arm): robot.gripper[arm] for arm in robot.arms + } + for part_name, indexes in robot._ref_joints_indexes_dict.items(): + qpos_values = [] + for joint_id in indexes: + qpos_addr = sim.model.jnt_qposadr[joint_id] + # https://mujoco.readthedocs.io/en/stable/APIreference/APItypes.html#mjtjoint + joint_type = sim.model.jnt_type[joint_id] + if joint_type == mujoco.mjtJoint.mjJNT_FREE: + qpos_size = 7 # Free joint has 7 DOFs + elif joint_type == mujoco.mjtJoint.mjJNT_BALL: + qpos_size = 4 # Ball joint has 4 DOFs (quaternion) + else: + qpos_size = 1 # Revolute or prismatic joint has 1 DOF + qpos_values = np.append( + qpos_values, sim.data.qpos[qpos_addr : qpos_addr + qpos_size] + ) + if part_name in gripper_names.keys(): + gripper = gripper_names[part_name] + # Reverse the order to match the real robot + qpos_values = unformat_gripper_space(gripper, qpos_values)[::-1] + if len(qpos_values) > 0: + observations[f"robot{robot_id}_{part_name}"] = qpos_values + + if verbose: + print("States:", [(k, len(observations[k])) for k in observations]) + + return observations + + +from gymnasium import spaces + + +class RobotKeyConverter: + @classmethod + def get_camera_config(cls): + raise NotImplementedError + + @classmethod + def map_obs(cls, input_obs): + raise NotImplementedError + + @classmethod + def map_action(cls, input_action): + raise NotImplementedError + + @classmethod + def unmap_action(cls, input_action): + raise NotImplementedError + + @classmethod + def get_metadata(cls, name): + raise NotImplementedError + + @classmethod + def map_obs_in_eval(cls, input_obs): + output_obs = {} + mapped_obs = cls.map_obs(input_obs) + for k, v in mapped_obs.items(): + assert k.startswith("hand.") or k.startswith("body.") + output_obs["state." + k[5:]] = v + return output_obs + + @classmethod + def get_missing_keys_in_dumping_dataset(cls): + return {} + + @classmethod + def convert_to_float64(cls, input): + for k, v in input.items(): + if isinstance(v, np.ndarray) and v.dtype == np.float32: + input[k] = v.astype(np.float64) + return input + + @classmethod + def deduce_observation_space(cls, env): + obs = ( + env.viewer._get_observations(force_update=True) + if env.viewer_get_obs + else env._get_observations(force_update=True) + ) + obs.update(gather_robot_observations(env)) + obs = cls.map_obs(obs) + observation_space = spaces.Dict() + + for k, v in obs.items(): + if k.startswith("hand.") or k.startswith("body."): + observation_space["state." + k[5:]] = spaces.Box( + low=-1, high=1, shape=(len(v),), dtype=np.float32 + ) + else: + raise ValueError(f"Unknown key: {k}") + + return observation_space + + @classmethod + def deduce_action_space(cls, env): + action = cls.map_action(reconstruct_latest_actions(env)) + action_space = spaces.Dict() + for k, v in action.items(): + if isinstance(v, np.int64): + action_space["action." + k[5:]] = spaces.Discrete(2) + elif isinstance(v, np.ndarray): + action_space["action." + k[5:]] = spaces.Box( + low=-1, high=1, shape=(len(v),), dtype=np.float32 + ) + else: + raise ValueError(f"Unknown type: {type(v)}") + return action_space + + +class GR1ArmsOnlyKeyConverter(RobotKeyConverter): + @classmethod + def get_camera_config(cls): + mapped_names = ["video.ego_view_pad_res256_freq20"] + camera_names = [ + "egoview", + ] + camera_widths, camera_heights = 1280, 800 + return mapped_names, camera_names, camera_widths, camera_heights + + @classmethod + def map_obs(cls, input_obs): + output_obs = type(input_obs)() + output_obs = { + "hand.right_hand": input_obs["robot0_right_gripper"], + "hand.left_hand": input_obs["robot0_left_gripper"], + "body.right_arm": input_obs["robot0_right"], + "body.left_arm": input_obs["robot0_left"], + } + return output_obs + + @classmethod + def map_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "hand.left_hand": input_action["robot0_left_gripper"], + "hand.right_hand": input_action["robot0_right_gripper"], + "body.left_arm": input_action["robot0_left"], + "body.right_arm": input_action["robot0_right"], + } + return output_action + + @classmethod + def unmap_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "robot0_left_gripper": input_action["action.left_hand"], + "robot0_right_gripper": input_action["action.right_hand"], + "robot0_left": input_action["action.left_arm"], + "robot0_right": input_action["action.right_arm"], + } + return output_action + + @classmethod + def get_missing_keys_in_dumping_dataset(cls): + return { + "body.waist": np.zeros(3, dtype=np.float64), + "body.neck": np.zeros(3, dtype=np.float64), + "body.right_leg": np.zeros(6, dtype=np.float64), + "body.left_leg": np.zeros(6, dtype=np.float64), + } + + @classmethod + def get_metadata(cls, name): + return { + "absolute": True, + "rotation_type": None, + } + + +class GR1ArmsAndWaistKeyConverter(RobotKeyConverter): + @classmethod + def get_camera_config(cls): + mapped_names = ["video.ego_view_pad_res256_freq20"] + camera_names = [ + "egoview", + ] + camera_widths, camera_heights = 1280, 800 + return mapped_names, camera_names, camera_widths, camera_heights + + @classmethod + def map_obs(cls, input_obs): + output_obs = type(input_obs)() + output_obs = { + "hand.right_hand": input_obs["robot0_right_gripper"], + "hand.left_hand": input_obs["robot0_left_gripper"], + "body.right_arm": input_obs["robot0_right"], + "body.left_arm": input_obs["robot0_left"], + "body.waist": input_obs["robot0_torso"], + } + return output_obs + + @classmethod + def map_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "hand.left_hand": input_action["robot0_left_gripper"], + "hand.right_hand": input_action["robot0_right_gripper"], + "body.left_arm": input_action["robot0_left"], + "body.right_arm": input_action["robot0_right"], + "body.waist": input_action["robot0_torso"], + } + return output_action + + @classmethod + def unmap_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "robot0_left_gripper": input_action["action.left_hand"], + "robot0_right_gripper": input_action["action.right_hand"], + "robot0_left": input_action["action.left_arm"], + "robot0_right": input_action["action.right_arm"], + "robot0_torso": input_action["action.waist"], + } + return output_action + + @classmethod + def get_missing_keys_in_dumping_dataset(cls): + return { + "body.neck": np.zeros(3, dtype=np.float64), + "body.right_leg": np.zeros(6, dtype=np.float64), + "body.left_leg": np.zeros(6, dtype=np.float64), + } + + @classmethod + def get_metadata(cls, name): + return { + "absolute": True, + "rotation_type": None, + } + + +class GR1FixedLowerBodyKeyConverter(RobotKeyConverter): + @classmethod + def get_camera_config(cls): + mapped_names = ["video.agentview_pad_res256_freq20"] + camera_names = [ + "agentview", + ] + camera_widths, camera_heights = 1280, 800 + return mapped_names, camera_names, camera_widths, camera_heights + + @classmethod + def map_obs(cls, input_obs): + output_obs = type(input_obs)() + output_obs = { + "hand.right_hand": input_obs["robot0_right_gripper"], + "hand.left_hand": input_obs["robot0_left_gripper"], + "body.right_arm": input_obs["robot0_right"], + "body.left_arm": input_obs["robot0_left"], + "body.waist": input_obs["robot0_torso"], + "body.neck": input_obs["robot0_head"], + } + return output_obs + + @classmethod + def map_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "hand.left_hand": input_action["robot0_left_gripper"], + "hand.right_hand": input_action["robot0_right_gripper"], + "body.left_arm": input_action["robot0_left"], + "body.right_arm": input_action["robot0_right"], + "body.waist": input_action["robot0_torso"], + "body.neck": input_action["robot0_head"], + } + return output_action + + @classmethod + def unmap_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "robot0_left_gripper": input_action["action.left_hand"], + "robot0_right_gripper": input_action["action.right_hand"], + "robot0_left": input_action["action.left_arm"], + "robot0_right": input_action["action.right_arm"], + "robot0_torso": input_action["action.waist"], + "robot0_head": input_action["action.neck"], + } + return output_action + + @classmethod + def get_missing_keys_in_dumping_dataset(cls): + return { + "body.right_leg": np.zeros(6, dtype=np.float64), + "body.left_leg": np.zeros(6, dtype=np.float64), + } + + @classmethod + def get_metadata(cls, name): + return { + "absolute": True, + "rotation_type": None, + } + + +class PandaOmronKeyConverter(RobotKeyConverter): + @classmethod + def get_camera_config(cls): + mapped_names = [ + "video.res256_image_side_0", + "video.res256_image_side_1", + "video.res256_image_wrist_0", + ] + camera_names = [ + "robot0_agentview_left", + "robot0_agentview_right", + "robot0_eye_in_hand", + ] + camera_widths, camera_heights = 512, 512 + return mapped_names, camera_names, camera_widths, camera_heights + + @classmethod + def map_obs(cls, input_obs): + output_obs = type(input_obs)() + output_obs = { + "hand.gripper_qpos": input_obs["robot0_gripper_qpos"], + "body.base_position": input_obs["robot0_base_pos"], + "body.base_rotation": input_obs["robot0_base_quat"], + "body.end_effector_position_relative": input_obs["robot0_base_to_eef_pos"], + "body.end_effector_rotation_relative": input_obs["robot0_base_to_eef_quat"], + } + return output_obs + + @classmethod + def map_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "hand.gripper_close": ( + np.int64(0) if input_action["robot0_right_gripper"] < 0 else np.int64(1) + ), + "body.end_effector_position": input_action["robot0_right"][..., 0:3], + "body.end_effector_rotation": input_action["robot0_right"][..., 3:6], + "body.base_motion": np.concatenate( + ( + input_action["robot0_base"], + input_action["robot0_torso"], + ), + axis=-1, + ), + "body.control_mode": ( + np.int64(0) if input_action["robot0_base_mode"] < 0 else np.int64(1) + ), + } + return output_action + + @classmethod + def unmap_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "robot0_right_gripper": ( + -1.0 if input_action["action.gripper_close"] < 0.5 else 1.0 + ), + "robot0_right": np.concatenate( + ( + input_action["action.end_effector_position"], + input_action["action.end_effector_rotation"], + ), + axis=-1, + ), + "robot0_base": input_action["action.base_motion"][..., 0:3], + "robot0_torso": input_action["action.base_motion"][..., 3:4], + "robot0_base_mode": ( + -1.0 if input_action["action.control_mode"] < 0.5 else 1.0 + ), + } + return output_action + + @classmethod + def get_metadata(cls, name): + from gr00t.data.schema import RotationType + + if name in [ + "body.base_position", + "body.end_effector_position_relative", + "body.end_effector_position", + ]: + return { + "absolute": False, + "rotation_type": None, + } + elif name in ["body.base_rotation", "body.end_effector_rotation_relative"]: + return { + "absolute": False, + "rotation_type": RotationType.QUATERNION, + } + elif name in ["body.end_effector_rotation"]: + return { + "absolute": False, + "rotation_type": RotationType.AXIS_ANGLE, + } + else: + return { + "absolute": True, + "rotation_type": None, + } + + +class PandaPandaKeyConverter(RobotKeyConverter): + @classmethod + def get_camera_config(cls): + mapped_names = [ + "video.agentview_pad_res256_freq20", + "video.robot0_eye_in_hand_pad_res256_freq20", + "video.robot1_eye_in_hand_pad_res256_freq20", + ] + camera_names = [ + "agentview", + "robot0_eye_in_hand", + "robot1_eye_in_hand", + ] + camera_widths, camera_heights = 1280, 800 + return mapped_names, camera_names, camera_widths, camera_heights + + @classmethod + def map_obs(cls, input_obs): + output_obs = type(input_obs)() + output_obs = { + "hand.right_gripper_qpos": input_obs["robot0_right_gripper"], + "hand.left_gripper_qpos": input_obs["robot1_right_gripper"], + "body.right_arm_eef_pos": input_obs["robot0_eef_pos"], + "body.right_arm_eef_quat": input_obs["robot0_eef_quat"], + "body.right_arm_joint_pos": input_obs["robot0_joint_pos"], + "body.left_arm_eef_pos": input_obs["robot1_eef_pos"], + "body.left_arm_eef_quat": input_obs["robot1_eef_quat"], + "body.left_arm_joint_pos": input_obs["robot1_joint_pos"], + } + return output_obs + + @classmethod + def map_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "hand.right_gripper_close": ( + np.int64(0) if input_action["robot0_right_gripper"] < 0 else np.int64(1) + ), + "hand.left_gripper_close": ( + np.int64(0) if input_action["robot1_right_gripper"] < 0 else np.int64(1) + ), + "body.right_arm_eef_pos": input_action["robot0_right"][..., 0:3], + "body.right_arm_eef_rot": input_action["robot0_right"][..., 3:6], + "body.left_arm_eef_pos": input_action["robot1_right"][..., 0:3], + "body.left_arm_eef_rot": input_action["robot1_right"][..., 3:6], + } + return output_action + + @classmethod + def unmap_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "robot0_right_gripper": ( + -1.0 if input_action["action.right_gripper_close"] < 0.5 else 1.0 + ), + "robot1_right_gripper": ( + -1.0 if input_action["action.left_gripper_close"] < 0.5 else 1.0 + ), + "robot0_right": np.concatenate( + ( + input_action["action.right_arm_eef_pos"], + input_action["action.right_arm_eef_rot"], + ), + axis=-1, + ), + "robot1_right": np.concatenate( + ( + input_action["action.left_arm_eef_pos"], + input_action["action.left_arm_eef_rot"], + ), + axis=-1, + ), + } + return output_action + + @classmethod + def get_metadata(cls, name): + from gr00t.data.schema import RotationType + + if name in ["body.right_arm_eef_pos", "body.left_arm_eef_pos"]: + return { + "absolute": False, + "rotation_type": None, + } + elif name in ["body.right_arm_eef_quat", "body.right_arm_eef_quat"]: + return { + "absolute": False, + "rotation_type": RotationType.QUATERNION, + } + elif name in ["body.right_arm_eef_rot", "body.left_arm_eef_rot"]: + return { + "absolute": False, + "rotation_type": RotationType.AXIS_ANGLE, + } + else: + return { + "absolute": True, + "rotation_type": None, + } + + +class PandaDexRHPandaDexRHKeyConverter(RobotKeyConverter): + @classmethod + def get_camera_config(cls): + mapped_names = [ + "video.agentview_pad_res256_freq20", + "video.robot0_eye_in_hand_pad_res256_freq20", + "video.robot1_eye_in_hand_pad_res256_freq20", + ] + camera_names = [ + "agentview", + "robot0_eye_in_hand", + "robot1_eye_in_hand", + ] + camera_widths, camera_heights = 1280, 800 + return mapped_names, camera_names, camera_widths, camera_heights + + @classmethod + def map_obs(cls, input_obs): + output_obs = type(input_obs)() + output_obs = { + "hand.right_hand": input_obs["robot0_right_gripper"], + "hand.left_hand": input_obs["robot1_right_gripper"], + "body.right_arm_eef_pos": input_obs["robot0_eef_pos"], + "body.right_arm_eef_quat": input_obs["robot0_eef_quat"], + "body.right_arm_joint_pos": input_obs["robot0_joint_pos"], + "body.left_arm_eef_pos": input_obs["robot1_eef_pos"], + "body.left_arm_eef_quat": input_obs["robot1_eef_quat"], + "body.left_arm_joint_pos": input_obs["robot1_joint_pos"], + } + return output_obs + + @classmethod + def map_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "hand.right_hand": input_action["robot0_right_gripper"], + "hand.left_hand": input_action["robot1_right_gripper"], + "body.right_arm_eef_pos": input_action["robot0_right"][0:3], + "body.right_arm_eef_rot": input_action["robot0_right"][3:6], + "body.left_arm_eef_pos": input_action["robot1_right"][0:3], + "body.left_arm_eef_rot": input_action["robot1_right"][3:6], + } + return output_action + + @classmethod + def unmap_action(cls, input_action): + output_action = type(input_action)() + output_action = { + "robot0_right_gripper": input_action["action.right_hand"], + "robot1_right_gripper": input_action["action.left_hand"], + "robot0_right": np.concatenate( + ( + input_action["action.right_arm_eef_pos"], + input_action["action.right_arm_eef_rot"], + ), + axis=-1, + ), + "robot1_right": np.concatenate( + ( + input_action["action.left_arm_eef_pos"], + input_action["action.left_arm_eef_rot"], + ), + axis=-1, + ), + } + return output_action + + @classmethod + def get_metadata(cls, name): + from gr00t.data.schema import RotationType + + if name in ["body.right_arm_eef_pos", "body.left_arm_eef_pos"]: + return { + "absolute": False, + "rotation_type": None, + } + elif name in ["body.right_arm_eef_quat", "body.right_arm_eef_quat"]: + return { + "absolute": False, + "rotation_type": RotationType.QUATERNION, + } + elif name in ["body.right_arm_eef_rot", "body.left_arm_eef_rot"]: + return { + "absolute": False, + "rotation_type": RotationType.AXIS_ANGLE, + } + else: + return { + "absolute": True, + "rotation_type": None, + } + + +# The values are only used in groot dataset embodiment tag and env name +GROOT_ROBOCASA_ENVS_GR1_ARMS_ONLY = { + "GR1ArmsOnly": "gr1_arms_only_fourier_hands", + "GR1ArmsOnlyInspireHands": "gr1_arms_only_inspire_hands", + "GR1ArmsOnlyFourierHands": "gr1_arms_only_fourier_hands", +} +GROOT_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST = { + "GR1ArmsAndWaistFourierHands": "gr1_arms_waist_fourier_hands", +} +GROOT_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY = { + "GR1FixedLowerBody": "gr1_fixed_lower_body_fourier_hands", + "GR1FixedLowerBodyInspireHands": "gr1_fixed_lower_body_inspire_hands", + "GR1FixedLowerBodyFourierHands": "gr1_fixed_lower_body_fourier_hands", +} +GROOT_ROBOCASA_ENVS_PANDA = { + "PandaMobile": "panda_mobile", + "PandaOmron": "panda_omron", +} +GROOT_ROBOCASA_ENVS_BIMANUAL_GRIPPER = { + "Panda_Panda": "bimanual_panda_parallel_gripper", +} +GROOT_ROBOCASA_ENVS_BIMANUAL_HAND = { + "PandaDexRH_PandaDexLH": "bimanual_panda_inspire_hand", +} +GROOT_ROBOCASA_ENVS_ROBOTS = { + **GROOT_ROBOCASA_ENVS_GR1_ARMS_ONLY, + **GROOT_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST, + **GROOT_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY, + **GROOT_ROBOCASA_ENVS_PANDA, + **GROOT_ROBOCASA_ENVS_BIMANUAL_GRIPPER, + **GROOT_ROBOCASA_ENVS_BIMANUAL_HAND, +} + + +def make_key_converter(robots_name): + if robots_name in GROOT_ROBOCASA_ENVS_GR1_ARMS_ONLY: + return GR1ArmsOnlyKeyConverter + elif robots_name in GROOT_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST: + return GR1ArmsAndWaistKeyConverter + elif robots_name in GROOT_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY: + return GR1FixedLowerBodyKeyConverter + elif robots_name in GROOT_ROBOCASA_ENVS_PANDA: + return PandaOmronKeyConverter + elif robots_name in GROOT_ROBOCASA_ENVS_BIMANUAL_GRIPPER: + return PandaPandaKeyConverter + elif robots_name in GROOT_ROBOCASA_ENVS_BIMANUAL_HAND: + return PandaDexRHPandaDexRHKeyConverter + else: + raise ValueError(f"Unknown robot name: {robots_name}") diff --git a/third_party/robocasa/robocasa/models/robots/manipulators/README.md b/third_party/robocasa/robocasa/models/robots/manipulators/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4728e8f5cf8fa5ba431014d5848175f9ca97cad4 --- /dev/null +++ b/third_party/robocasa/robocasa/models/robots/manipulators/README.md @@ -0,0 +1,40 @@ +# Robot Integration Guide + +This guide explains how to integrate a new robot into the Robocasa framework. + +## MJCF File Requirements +Location: [`robocasa/models/assets/robots/`](robocasa/models/robots) + +### MJCF Structure Requirements +- The MJCF file must have a single root element containing all other elements (``, ``, etc.) +- The robot's kinematic tree must start from a `` element that contains a freejoint and is placed directly under `` +- Joint definitions for the right arm must precede those of the left arm in the XML structure +- End effector attachments (grippers) are only supported on bodies named `` + +### Base Mounting Configuration +When operating in fixed-base mode, the body connected to the base joint will be anchored to the world frame. So choose this mounting point carefully, typically at the robot's pelvis/torso, to ensure proper fixed-base behavior. + +## Controller Configuration +Location: [`robocasa/examples/third_party_controllers/`](robocasa/examples/third_party_controllers/) + + +### Configuration Requirements +1. Implement whole-body control configuration (excluding leg components for now) +2. Configure and tune `ik_posture_weight` + - Remember to add "robot0_" prefix to all parameters + + +## Robot Registry Updates +Location: [`robocasa/models/robots/manipulators/`](robocasa/models/robots/manipulators/) + +### Required Function Updates +Take a look at the existing robot class definitions for examples. +Remember to update the following functions with new robot's specifications: +1. `update_joints()` + - Add joint names in correct order + - Maintain right-before-left convention + +2. `update_actuators()` + - Add actuator names + - Ensure order matches joint configuration + diff --git a/third_party/robocasa/robocasa/models/robots/manipulators/__init__.py b/third_party/robocasa/robocasa/models/robots/manipulators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7334258ba440f8cfd33b135e517071bc5f31fc1f --- /dev/null +++ b/third_party/robocasa/robocasa/models/robots/manipulators/__init__.py @@ -0,0 +1,7 @@ +from .gr1_robot import ( + GR1FixedLowerBodyInspireHands, + GR1FixedLowerBodyFourierHands, + GR1ArmsOnlyInspireHands, + GR1ArmsOnlyFourierHands, + GR1ArmsAndWaistFourierHands, +) diff --git a/third_party/robocasa/robocasa/models/robots/manipulators/gr1_robot.py b/third_party/robocasa/robocasa/models/robots/manipulators/gr1_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..6910fa8ba5a343aabfe13d617cef61202d2ed58e --- /dev/null +++ b/third_party/robocasa/robocasa/models/robots/manipulators/gr1_robot.py @@ -0,0 +1,59 @@ +import numpy as np + +from robosuite.robots import register_robot_class +from robosuite.models.robots import GR1 +from robosuite.models.robots.manipulators.gr1_robot import ( + GR1FixedLowerBody, + GR1ArmsOnly, +) + + +@register_robot_class("LeggedRobot") +class GR1FixedLowerBodyInspireHands(GR1FixedLowerBody): + @property + def default_gripper(self): + return {"right": "InspireRightHand", "left": "InspireLeftHand"} + + +@register_robot_class("LeggedRobot") +class GR1FixedLowerBodyFourierHands(GR1FixedLowerBody): + @property + def default_gripper(self): + return {"right": "FourierRightHand", "left": "FourierLeftHand"} + + +@register_robot_class("LeggedRobot") +class GR1ArmsOnlyInspireHands(GR1ArmsOnly): + @property + def default_gripper(self): + return {"right": "InspireRightHand", "left": "InspireLeftHand"} + + +@register_robot_class("LeggedRobot") +class GR1ArmsOnlyFourierHands(GR1ArmsOnly): + @property + def default_gripper(self): + return {"right": "FourierRightHand", "left": "FourierLeftHand"} + + +@register_robot_class("LeggedRobot") +class GR1ArmsAndWaist(GR1): + def __init__(self, idn=0): + super().__init__(idn=idn) + self._remove_joint_actuation("leg") + self._remove_joint_actuation("head") + self._remove_free_joint() + + @property + def init_qpos(self): + init_qpos = np.array([0.0] * 17) + right_arm_init = np.array([0.0, -0.1, 0.0, -1.57, 0.0, 0.0, 0.0]) + left_arm_init = np.array([0.0, 0.1, 0.0, -1.57, 0.0, 0.0, 0.0]) + init_qpos[3:10] = right_arm_init + init_qpos[10:17] = left_arm_init + return init_qpos + + +@register_robot_class("LeggedRobot") +class GR1ArmsAndWaistFourierHands(GR1ArmsAndWaist): + pass diff --git a/third_party/robocasa/robocasa/models/scenes/__init__.py b/third_party/robocasa/robocasa/models/scenes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..251d5fdb8870bc53167888bad4f4270b508b1ae5 --- /dev/null +++ b/third_party/robocasa/robocasa/models/scenes/__init__.py @@ -0,0 +1 @@ +from .tabletop_arena import TabletopArena diff --git a/third_party/robocasa/robocasa/models/scenes/scene_builder.py b/third_party/robocasa/robocasa/models/scenes/scene_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..aa61c9b0f8d479f47c0a4b3f70d42045c91b7c88 --- /dev/null +++ b/third_party/robocasa/robocasa/models/scenes/scene_builder.py @@ -0,0 +1,289 @@ +import numpy as np +import yaml +from robosuite.utils.mjcf_utils import array_to_string as a2s +from robosuite.utils.mjcf_utils import string_to_array as s2a + +from robocasa.models.scenes.scene_registry import ( + get_tabletop_layout_path, + get_style_path, +) +from robocasa.models.scenes.scene_utils import * +from robocasa.models.fixtures import * + +# fixture string to class +FIXTURES = dict( + single_cabinet=SingleCabinet, + drawer=Drawer, + counter=Counter, + microwave=Microwave, + wall=Wall, + floor=Floor, + paper_towel=Accessory, + plant=Accessory, + toaster=Toaster, + # needs some additional work + # slide_cabinet=SlideCabinet, +) +# fixtures that are attached to other fixtures, disables positioning system in this script +FIXTURES_INTERIOR = dict( +) + +ALL_SIDES = ["left", "right", "front", "back", "bottom", "top"] + + +def check_syntax(fixture): + """ + Checks that specifications of a fixture follows syntax rules + """ + + if fixture["type"] != "stack" and fixture["type"] not in FIXTURES: + raise ValueError( + 'Invalid value for fixture type: "{}".'.format(fixture["type"]) + ) + + if "config_name" in fixture and "default_config_name" in fixture: + raise ValueError('Cannot specify both "config_name" and "default_config_name"') + + if "align_to" in fixture or "side" in fixture or "alignment" in fixture: + if not ("align_to" in fixture and "side" in fixture): + raise ValueError( + 'Both or neither of "align_to" and ' '"side" need to be specified.' + ) + if "pos" in fixture: + raise ValueError("Cannot specify both relative and absolute positions.") + + # check alignment and side arguments are compatible + if "alignment" in fixture: + for keywords in AXES_KEYWORDS.values(): + if fixture["side"] in keywords: + # check that neither keyword is used for alignment + if ( + keywords[0] in fixture["alignment"] + or keywords[1] in fixture["alignment"] + ): + raise ValueError( + 'Cannot set alignment to "{}" when aligning to the "{}" side'.format( + fixture["alignment"], fixture["side"] + ) + ) + + # check if side is valid + if fixture["side"] not in ALL_SIDES: + raise ValueError( + '"{}" is not a valid side for alignment'.format(fixture["side"]) + ) + + +def create_tabletop_fixtures(layout_id, style_id, rng=None): + """ + Initializes fixtures based on the given layout yaml file and style type + + Args: + layout_id (int or TabletopLayoutType): layout of the tabletop to load + + style_id (int or StyleType): style of the tabletop to load + + rng (np.random.Generator): random number generator used for initializing fixture state + """ + + try: + style = int(style) + except: + pass + + return create_fixtures_from_yaml( + get_tabletop_layout_path(layout_id), get_style_path(style_id), rng + ) + + +def create_fixtures_from_yaml(layout_yaml_path, style_yaml_path, rng=None): + """ + Initializes fixtures based on the given layout yaml file and style type + + Args: + layout_yaml_path (str): path to the layout yaml file + + style_yaml_path (str): path to the style yaml file + + rng (np.random.Generator): random number generator used for initializing fixture state + """ + + # load style + with open(style_yaml_path, "r") as f: + style = yaml.safe_load(f) + + # load arena + with open(layout_yaml_path, "r") as f: + arena_config = yaml.safe_load(f) + + # contains all fixtures with updated configs + arena = list() + + # Update each fixture config. First iterate through groups: subparts of the arena that can be + # rotated and displaced together. example: island group, right group, room group, etc + for group_name, group_config in arena_config.items(): + group_fixtures = list() + # each group is further divded into similar subcollections of fixtures + # ex: main group counter accessories, main group top cabinets, etc + for k, fixture_list in group_config.items(): + # these values are rotations/displacements that are applied to all fixtures in the group + if k in ["group_origin", "group_z_rot", "group_pos"]: + continue + elif type(fixture_list) != list: + raise ValueError('"{}" is not a valid argument for groups'.format(k)) + + # add suffix to support different groups + for fxtr_config in fixture_list: + fxtr_config["name"] += "_" + group_name + # update fixture names for alignment, interior objects, etc. + for k in ATTACH_ARGS + ["align_to", "stack_fixtures", "size"]: + if k in fxtr_config: + if isinstance(fxtr_config[k], list): + for i in range(len(fxtr_config[k])): + if isinstance(fxtr_config[k][i], str): + fxtr_config[k][i] += "_" + group_name + else: + if isinstance(fxtr_config[k], str): + fxtr_config[k] += "_" + group_name + + group_fixtures.extend(fixture_list) + + # update group rotation/displacement if necessary + if "group_origin" in group_config: + for fxtr_config in group_fixtures: + # do not update the rotation of the walls/floor + if fxtr_config["type"] in ["wall", "floor"]: + continue + fxtr_config["group_origin"] = group_config["group_origin"] + fxtr_config["group_pos"] = group_config["group_pos"] + fxtr_config["group_z_rot"] = group_config["group_z_rot"] + + # addto overall fixture list + arena.extend(group_fixtures) + + # maps each fixture name to its object class + fixtures = dict() + # maps each fixture name to its configuration + configs = dict() + # names of composites, delete from fixtures before returning + composites = list() + + # initialize each fixture in the arena by processing config + for fixture_config in arena: + check_syntax(fixture_config) + fixture_name = fixture_config["name"] + + # stack of fixtures, handled separately + if fixture_config["type"] == "stack": + stack = FixtureStack( + fixture_config, + fixtures, + configs, + style, + default_texture=None, + rng=rng, + ) + fixtures[fixture_name] = stack + configs[fixture_name] = fixture_config + composites.append(fixture_name) + continue + + # load style information and update config to include it + default_config = load_style_config(style, fixture_config) + if default_config is not None: + for k, v in fixture_config.items(): + default_config[k] = v + fixture_config = default_config + + # set fixture type + fixture_config["type"] = FIXTURES[fixture_config["type"]] + + # pre-processing for fixture size + size = fixture_config.get("size", None) + if isinstance(size, list): + for i in range(len(size)): + elem = size[i] + if isinstance(elem, str): + ref_fxtr = fixtures[elem] + size[i] = ref_fxtr.size[i] + + # initialize fixture + fixture = initialize_fixture(fixture_config, fixtures, rng=rng) + fixtures[fixture_name] = fixture + configs[fixture_name] = fixture_config + + # update fixture position + if fixture_config["type"] not in FIXTURES_INTERIOR.values(): + # relative positioning + if "align_to" in fixture_config: + pos = get_relative_position( + fixture, + fixture_config, + fixtures[fixture_config["align_to"]], + configs[fixture_config["align_to"]], + ) + + elif "stack_on" in fixture_config: + stack_on = fixtures[fixture_config["stack_on"]] + + # account for off-centered objects + stack_on_center = stack_on.center + + # infer unspecified axes of position + pos = fixture_config["pos"] + if pos[0] is None: + pos[0] = stack_on.pos[0] + stack_on_center[0] + if pos[1] is None: + pos[1] = stack_on.pos[1] + stack_on_center[1] + + # calculate height of fixture + pos[2] = stack_on.pos[2] + stack_on.size[2] / 2 + fixture.size[2] / 2 + pos[2] += stack_on_center[2] + else: + # absolute position + pos = fixture_config.get("pos", None) + if pos is not None and type(fixture) not in [Wall, Floor]: + fixture.set_pos(pos) + + # composites are non-MujocoObjects, must remove + for composite in composites: + del fixtures[composite] + + # update the rotation and postion of each fixture based on their group + for name, fixture in fixtures.items(): + # check if updates are necessary + config = configs[name] + if "group_origin" not in config: + continue + + # TODO: add default for group origin? + # rotate about this coordinate (around the z-axis) + origin = config["group_origin"] + pos = config["group_pos"] + z_rot = config["group_z_rot"] + displacement = [pos[0] - origin[0], pos[1] - origin[1]] + + if type(fixture) not in [Wall, Floor]: + dx = fixture.pos[0] - origin[0] + dy = fixture.pos[1] - origin[1] + dx_rot = dx * np.cos(z_rot) - dy * np.sin(z_rot) + dy_rot = dx * np.sin(z_rot) + dy * np.cos(z_rot) + + x_rot = origin[0] + dx_rot + y_rot = origin[1] + dy_rot + z = fixture.pos[2] + pos_new = [x_rot + displacement[0], y_rot + displacement[1], z] + + # account for previous z-axis rotation + rot_prev = fixture._obj.get("euler") + if rot_prev is not None: + # TODO: switch to quaternion since euler rotations are ambiguous + rot_new = s2a(rot_prev) + rot_new[2] += z_rot + else: + rot_new = [0, 0, z_rot] + + fixture._obj.set("pos", a2s(pos_new)) + fixture._obj.set("euler", a2s(rot_new)) + + return fixtures diff --git a/third_party/robocasa/robocasa/models/scenes/scene_registry.py b/third_party/robocasa/robocasa/models/scenes/scene_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..af33f856f50d12e691eb37adbd82da792b68be42 --- /dev/null +++ b/third_party/robocasa/robocasa/models/scenes/scene_registry.py @@ -0,0 +1,144 @@ +from collections import OrderedDict +from enum import IntEnum +from robosuite.utils.mjcf_utils import xml_path_completion +import robocasa + + +class TabletopLayoutType(IntEnum): + """ + Enum for available tabletop layouts in RoboCasa environment + """ + + TABLETOP = 0 + CLUTTERED_TABLETOP = 1 + TABLETOP_WITH_MICROWAVE = 2 + TABLETOP_COTRAIN = 3 + TABLETOP_WITH_DRAWER = 4 + TABLETOP_WITH_CABINET = 5 + + # negative values correspond to groups (see TABLETOP_LAYOUT_GROUPS_TO_IDS) + ALL = -1 + + +TABLETOP_LAYOUT_GROUPS_TO_IDS = { + -1: list(range(len(TabletopLayoutType) - 1)), # all +} + + +class StyleType(IntEnum): + """ + Enums for available styles in RoboCasa environment + """ + + INDUSTRIAL = 0 + SCANDANAVIAN = 1 + COASTAL = 2 + MODERN_1 = 3 + MODERN_2 = 4 + TRADITIONAL_1 = 5 + TRADITIONAL_2 = 6 + FARMHOUSE = 7 + RUSTIC = 8 + MEDITERRANEAN = 9 + TRANSITIONAL_1 = 10 + TRANSITIONAL_2 = 11 + + # negative values correspond to groups + ALL = -1 + + +STYLE_GROUPS_TO_IDS = { + -1: list(range(12)), # all +} + + +def get_tabletop_layout_path(layout_id): + """ + Get corresponding blueprint filepath (yaml) for a layout + + Args: + layout_id (int or TabletopLayoutType): layout id (int or enum) + + Return: + str: yaml path for specified layout + """ + if isinstance(layout_id, int): + layout_int_to_name = dict( + map(lambda item: (item.value, item.name.lower()), TabletopLayoutType) + ) + layout_name = layout_int_to_name[layout_id] + elif isinstance(layout_id, TabletopLayoutType): + layout_name = layout_id.name.lower() + else: + raise ValueError + + # special case: if name starts with one letter, capitalize it + if layout_name[1] == "_": + layout_name = layout_name.capitalize() + + return xml_path_completion( + f"scenes/tabletop_layouts/{layout_name}.yaml", + root=robocasa.models.assets_root, + ) + + +def get_style_path(style_id): + """ + Get corresponding blueprint filepath (yaml) for a style + + Args: + style_id (int or StyleType): style id (int or enum) + + Return: + str: yaml path for specified style + """ + if isinstance(style_id, int): + style_int_to_name = dict( + map(lambda item: (item.value, item.name.lower()), StyleType) + ) + style_name = style_int_to_name[style_id] + elif isinstance(style_id, StyleType): + style_name = style_id.name.lower() + else: + raise ValueError + + return xml_path_completion( + f"scenes/kitchen_styles/{style_name}.yaml", + root=robocasa.models.assets_root, + ) + + +def unpack_tabletop_layout_ids(layout_ids): + if layout_ids is None: + layout_ids = TabletopLayoutType.ALL + + if not isinstance(layout_ids, list): + layout_ids = [layout_ids] + + layout_ids = [int(id) for id in layout_ids] + + all_layout_ids = [] + for id in layout_ids: + if id < 0: + all_layout_ids += TABLETOP_LAYOUT_GROUPS_TO_IDS[id] + else: + all_layout_ids.append(id) + return list(OrderedDict.fromkeys(all_layout_ids)) + + +def unpack_style_ids(style_ids): + if style_ids is None: + style_ids = StyleType.ALL + + if not isinstance(style_ids, list): + style_ids = [style_ids] + + style_ids = [int(id) for id in style_ids] + + all_style_ids = [] + for id in style_ids: + if id < 0: + all_style_ids += STYLE_GROUPS_TO_IDS[id] + else: + all_style_ids.append(id) + return list(OrderedDict.fromkeys(all_style_ids)) diff --git a/third_party/robocasa/robocasa/models/scenes/scene_utils.py b/third_party/robocasa/robocasa/models/scenes/scene_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..98dcced8de6c15209527c21a809f593ad81fc159 --- /dev/null +++ b/third_party/robocasa/robocasa/models/scenes/scene_utils.py @@ -0,0 +1,180 @@ +from collections import OrderedDict +from copy import deepcopy +import yaml +from robosuite.utils.mjcf_utils import xml_path_completion + +import robocasa + + +# second keyword corresponds to positive end of axis +AXES_KEYWORDS = {0: ["left", "right"], 1: ["front", "back"], 2: ["bottom", "top"]} + +# arguments not to be passed into fixture classes when initializing +IGNORE_ARGS = [ + "name", + "align_to", + "side", + "alignment", + "type", + "center", + "offset", + "group_origin", + "group_pos", + "group_z_rot", + "stack_height", + "stack_fixtures", +] + +# arguments used to point to other fixtures +ATTACH_ARGS = ["interior_obj", "stack_on", "attach_to"] + + +def initialize_fixture(config, cur_fixtures, rng=None): + """ + initializes a fixture object based on the given configuration + ignores positional arguments as it is changed later + + Args: + config (dict): dictionary containing the fixture configuration. + Serves as the arguments to initialize the fixture + + cur_fixtures (dict): dictionary containing the current fixtures + """ + + config = deepcopy(config) + name, class_type = config["name"], config["type"] + + # set size if stack_height is specified: + if config.get("stack_height", None) is not None: + stack_height = config["stack_height"] + stack_fixtures = config["stack_fixtures"] + curr_height = 0 + for fxtr in stack_fixtures: + curr_height += cur_fixtures[fxtr].size[2] + config["size"][2] = stack_height - curr_height + + # these fields should not be passed in when initializing the fixture + for field in IGNORE_ARGS: + if field in config: + del config[field] + + if "pos" not in config: + # need position to initialize fixture, adjusted later fo relative positioning + config["pos"] = [0.0, 0.0, 0.0] + + # update fixture pointers + for k in ATTACH_ARGS: + if k in config: + config[k] = cur_fixtures[config[k]] + + config["rng"] = rng + fixture = class_type(name=name, **config) + # print(class_type, name, type(fixture)) + return fixture + + +def load_style_config(style, fixture_config): + """ + Loads the style information for a given fixture. Style information can consist of + which xml to use if there are multiple instances of a fixture, which texture to apply, + which subcomponents to apply (panels/handles for a cab), etc. + + Args: + style (dict): dictionary containing the style information for each fixture type + + fixture_config (dict): dictionary containing the fixture configuration + """ + # accounts for the different types of cabinets + fixture_type = fixture_config["type"] + + # cabinets, shelves, drawers, and boxes use the same default configurations + if "cabinet" in fixture_type or "drawer" in fixture_type or "box" in fixture_type: + fixture_type = "cabinet" + + # if fixture_type not in style: + # raise ValueError("Did not specify fixture type \"{}\" in chosen style".format(fixture_type)) + fixture_style = style.get(fixture_type, "default") + + yaml_path = xml_path_completion( + f"fixtures/fixture_registry/{fixture_type}.yaml", + root=robocasa.models.assets_root, + ) + with open(yaml_path, "r") as f: + default_configs = yaml.safe_load(f) + + # find which configuration to use + if type(fixture_style) == dict and "config_name" not in fixture_config: + if "default_config_name" in fixture_config: + config_ids = fixture_style.get( + fixture_config["default_config_name"], fixture_style["default"] + ) + del fixture_config["default_config_name"] + else: + config_ids = fixture_style["default"] + elif "default_config_name" in fixture_config: + raise ValueError('Specified "default_config_name" but no default config found') + + elif "config_name" in fixture_config: + config_ids = fixture_config["config_name"] + del fixture_config["config_name"] + else: + config_ids = fixture_style + + # search for config by name + config = default_configs["default"] + if not isinstance(config_ids, list): + config_ids = [config_ids] + for cfg_id in config_ids: + if cfg_id in default_configs: + # add additional arguments based on default config + additional_config = default_configs[cfg_id] + for k, v in additional_config.items(): + config[k] = v + else: + raise ValueError( + 'Did not find style that matches "{}" for ' + 'fixture type "{}"'.format(cfg_id, fixture_type) + ) + return config + + +def get_relative_position(fixture, config, prev_fxtr, prev_fxtr_config): + """ + Calculates the position of `fixture` based on a specified side + and alignment relative to `prev_fixture` + + This assumes that the fixtures are properly centered! + """ + + side = config["side"].lower() + alignment = config["alignment"].lower() if "alignment" in config else "center" + size = fixture.size + prev_pos, prev_size = prev_fxtr.pos, prev_fxtr.size + + # for fixtures that are not perfectly centered (e.g. stoves) + prev_pos += prev_fxtr.origin_offset + + # place fixtures next to each others + for axis, keywords in AXES_KEYWORDS.items(): + if side not in keywords: + continue + pos = deepcopy(prev_pos) + if side == keywords[1]: + pos[axis] = prev_pos[axis] + prev_size[axis] / 2 + size[axis] / 2 + elif side == keywords[0]: + pos[axis] = prev_pos[axis] - prev_size[axis] / 2 - size[axis] / 2 + + # align such that the specified faces are flush + # alignment - side compatibility is checked in check_syntax() + for axis, keywords in AXES_KEYWORDS.items(): + if keywords[0] in alignment: + pos[axis] = prev_pos[axis] - prev_size[axis] / 2 + size[axis] / 2 + elif keywords[1] in alignment: + pos[axis] = prev_pos[axis] + prev_size[axis] / 2 - size[axis] / 2 + + if "offset" in config: + pos += config["offset"] + + # for fixtures that are not perfectly centered (e.g. stoves) + pos -= fixture.origin_offset + return pos diff --git a/third_party/robocasa/robocasa/models/scenes/tabletop_arena.py b/third_party/robocasa/robocasa/models/scenes/tabletop_arena.py new file mode 100644 index 0000000000000000000000000000000000000000..766d9e6ed3741489e54f60d9728cceb610dd1d98 --- /dev/null +++ b/third_party/robocasa/robocasa/models/scenes/tabletop_arena.py @@ -0,0 +1,52 @@ +from robosuite.models.arenas import Arena +from robosuite.utils.mjcf_utils import xml_path_completion + +import robocasa +from robocasa.models.scenes.scene_builder import create_tabletop_fixtures + + +# base class for tabletop scenes +class TabletopArena(Arena): + """ + Tabletop arena class holding all of the fixtures + + Args: + layout_id (int or TabletopLayoutType): layout of the tabletop to load + + style_id (int or StyleType): style of the tabletop to load + + rng (np.random.Generator): random number generator used for initializing + fixture state in the TabletopArena + """ + + def __init__(self, layout_id, style_id, rng=None): + super().__init__( + xml_path_completion( + "arenas/empty_tabletop_arena.xml", root=robocasa.models.assets_root + ) + ) + self.fixtures = create_tabletop_fixtures( + layout_id=layout_id, + style_id=style_id, + rng=rng, + ) + + def get_fixture_cfgs(self): + """ + Returns config data for all fixtures in the arena + + Returns: + list: list of fixture configurations + """ + fixture_cfgs = [] + for name, fxtr in self.fixtures.items(): + cfg = {} + cfg["name"] = name + cfg["model"] = fxtr + cfg["type"] = "fixture" + if hasattr(fxtr, "_placement"): + cfg["placement"] = fxtr._placement + + fixture_cfgs.append(cfg) + + return fixture_cfgs diff --git a/third_party/robocasa/robocasa/scripts/demo_task.py b/third_party/robocasa/robocasa/scripts/demo_task.py new file mode 100644 index 0000000000000000000000000000000000000000..6cb16641fc97a68751de223fe29dbe348e783645 --- /dev/null +++ b/third_party/robocasa/robocasa/scripts/demo_task.py @@ -0,0 +1,47 @@ +import os +import sys +import gymnasium as gym +import numpy as np +import pytest +from pathlib import Path +from gymnasium import spaces + +import robocasa # noqa: F401 +import robosuite # noqa: F401 +from robocasa.utils.gym_utils import GrootRoboCasaEnv # noqa: F401 +from gr00t.eval.wrappers.video_recording_wrapper import ( + VideoRecorder, + VideoRecordingWrapper, +) + + +def demo_robocasa_digital_cousin_env(env_id, video_dir): + env = gym.make(env_id, enable_render=True) + video_recorder = VideoRecorder.create_h264( + fps=10, + codec="h264", + input_pix_fmt="rgb24", + crf=22, + thread_type="FRAME", + thread_count=1, + ) + env = VideoRecordingWrapper( + env, + video_recorder, + video_dir=Path(video_dir), + ) + + # raw obs from env is in float64, convert to float32 + obs, _ = env.reset() + for _ in range(20): + action = env.action_space.sample() + obs, _, _, _, _ = env.step(action) + env.render() + env.close() + + +if __name__ == "__main__": + env_id = sys.argv[1] + video_dir = os.path.join(os.getcwd(), "video") + os.makedirs(video_dir, exist_ok=True) + demo_robocasa_digital_cousin_env(env_id, video_dir=video_dir) diff --git a/third_party/robocasa/robocasa/scripts/download_groot_assets.py b/third_party/robocasa/robocasa/scripts/download_groot_assets.py new file mode 100644 index 0000000000000000000000000000000000000000..0dd6385d0d4757173b6376759cc42eba405466c6 --- /dev/null +++ b/third_party/robocasa/robocasa/scripts/download_groot_assets.py @@ -0,0 +1,135 @@ +import argparse +import dataclasses +import enum +import json +import logging +import os +from pathlib import Path +from typing import Optional +import urllib.request + +from download_kitchen_assets import download_kitchen_assets as download + +DEFAULT_ASSETS_VERSION = "1b018839a6da865dffecd3185fe054211bc71270" +REPO_ID = "nvidia/PhysicalAI-DigitalCousin-Assets" +API_URL = f"https://huggingface.co/api/datasets/{REPO_ID}" +SOURCE_URL = f"https://huggingface.co/datasets/{REPO_ID}" + + +class Registry(enum.Enum): + SKETCHFAB = "sketchfab" + LIGHTWHEEL = "lightwheel" + + +@dataclasses.dataclass(frozen=True) +class DownloadConfig: + registries: set[Registry] + + @classmethod + def from_args(cls, registry_names: Optional[list[str]] = None) -> "DownloadConfig": + valid_registries = ( + {r for r in Registry if r.value in registry_names} + if registry_names + else set(Registry) + ) + return cls(registries=valid_registries) + + +def get_available_registries(revision: str) -> set[Registry]: + url = f"{API_URL}?revision={revision}" + with urllib.request.urlopen(url) as resp: + resp = json.load(resp) + tree = resp["siblings"] + stems = {Path(item["rfilename"]).stem for item in tree} + return {r for r in Registry if r.value in stems} + + +def get_groot_asset_registry( + download_config: DownloadConfig, version: Optional[str] +) -> dict: + logging.info( + f"Initiating download for the specified assets: {', '.join(r.value for r in download_config.registries)}..." + ) + + if version: + logging.info(f"Initiating download for assets at revision '{version}'...") + else: + version = DEFAULT_ASSETS_VERSION + logging.info( + f"No revision specified; proceeding with the default version '{version}'..." + ) + + available_registries = get_available_registries(version) + registry = {} + for r in download_config.registries: + if r not in available_registries: + logging.warning( + f"Requested registry '{r.value}' is not available at revision '{version}', skipping..." + ) + continue + registry[r.value] = dict( + message=f"Downloading {r.value} assets", + url=f"{SOURCE_URL}/resolve/{version}/{r.value}.zip", + folder=os.path.join( + os.path.dirname(__file__), f"../models/assets/objects/{r.value}" + ), + check_folder_exists=False, + ) + return registry + + +def download_groot_assets( + download_config: DownloadConfig, + version: str, + bypass: bool, + update_registry: bool = False, +): + import download_kitchen_assets + + groot_asset_registry = get_groot_asset_registry( + download_config=download_config, version=version + ) + if update_registry: + download_kitchen_assets.DOWNLOAD_ASSET_REGISTRY.update(groot_asset_registry) + else: + download_kitchen_assets.DOWNLOAD_ASSET_REGISTRY = groot_asset_registry + download(bypass=bypass) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "-y", + "--yes", + action="store_true", + help="Download assets directly without prompting to screen", + ) + parser.add_argument( + "-a", + "--assets", + nargs="*", + help="Specify a list of asset names to download (leave empty to download all assets)", + ) + parser.add_argument( + "-r", + "--revision", + help="Specify the release tag or revision number of the assets to download", + ) + parser.add_argument( + "-v", + "--verbose", + action="store_true", + help="Print verbose output", + ) + args = parser.parse_args() + + if args.verbose: + logging.getLogger().setLevel(logging.INFO) + cfg = DownloadConfig.from_args(args.assets) + + download_groot_assets( + download_config=cfg, + version=args.revision, + bypass=args.yes, + update_registry=False, + ) diff --git a/third_party/robocasa/robocasa/scripts/download_kitchen_assets.py b/third_party/robocasa/robocasa/scripts/download_kitchen_assets.py new file mode 100644 index 0000000000000000000000000000000000000000..f1cea67f3d54f59ab31eb8afc0d40b825eb1e2e9 --- /dev/null +++ b/third_party/robocasa/robocasa/scripts/download_kitchen_assets.py @@ -0,0 +1,218 @@ +import argparse +import os +import sys +import time +import urllib.request +from pathlib import Path +from zipfile import ZipFile + +from termcolor import colored +from tqdm import tqdm + +DOWNLOAD_ASSET_REGISTRY = dict( + textures=dict( + message="Downloading environment textures", + url="https://utexas.box.com/shared/static/otdsyfjontk17jdp24bkhy2hgalofbh4.zip", + folder=os.path.join(os.path.dirname(__file__), "../models/assets/textures"), + check_folder_exists=False, + ), + fixtures=dict( + message="Downloading fixtures", + url="https://utexas.box.com/shared/static/pobhbsjyacahg2mx8x4rm5fkz3wlmyzp.zip", + folder=os.path.join(os.path.dirname(__file__), "../models/assets/fixtures"), + check_folder_exists=False, + ), + objaverse=dict( + message="Downloading objaverse objects", + url="https://utexas.box.com/shared/static/ejt1kc2v5vhae1rl4k5697i4xvpbjcox.zip", + folder=os.path.join( + os.path.dirname(__file__), "../models/assets/objects/objaverse" + ), + check_folder_exists=False, + ), + aigen_objs=dict( + message="Downloading AI-generated objects", + url="https://utexas.box.com/shared/static/os3hrui06lasnuvwqpmwn0wcrduh6jg3.zip", + folder=os.path.join( + os.path.dirname(__file__), "../models/assets/objects/aigen_objs" + ), + check_folder_exists=False, + ), + generative_textures=dict( + message="Downloading AI-generated environment textures", + url="https://utexas.box.com/shared/static/gf9nkadvfrowkb9lmkcx58jwt4d6c1g3.zip", + folder=os.path.join( + os.path.dirname(__file__), "../models/assets/generative_textures" + ), + check_folder_exists=False, + ), +) + + +class DownloadProgressBar(tqdm): + def update_to(self, b=1, bsize=1, tsize=None): + if tsize is not None: + self.total = tsize + self.update(b * bsize - self.n) + + +def url_is_alive(url): + """ + Checks that a given URL is reachable. + From https://gist.github.com/dehowell/884204. + + Args: + url (str): url string + + Returns: + is_alive (bool): True if url is reachable, False otherwise + """ + request = urllib.request.Request(url) + request.get_method = lambda: "HEAD" + + try: + urllib.request.urlopen(request) + return True + except urllib.request.HTTPError: + return False + + +def download_url(url, download_dir, fname=None, check_overwrite=True): + """ + First checks that @url is reachable, then downloads the file + at that url into the directory specified by @download_dir. + Prints a progress bar during the download using tqdm. + + Modified from https://github.com/tqdm/tqdm#hooks-and-callbacks, and + https://stackoverflow.com/a/53877507. + + Args: + url (str): url string + download_dir (str): path to directory where file should be downloaded + check_overwrite (bool): if True, will sanity check the download fpath to make sure a file of that name + doesn't already exist there + """ + + # check if url is reachable. We need the sleep to make sure server doesn't reject subsequent requests + # assert url_is_alive(url), "@download_url got unreachable url: {}".format(url) + # time.sleep(0.5) + + if fname is None: + # infer filename from url link + fname = url.split("/")[-1] + file_to_write = os.path.join(download_dir, fname) + + # If we're checking overwrite and the path already exists, + # we ask the user to verify that they want to overwrite the file + if check_overwrite and os.path.exists(file_to_write): + user_response = input( + f"Warning: file {file_to_write} already exists. Overwrite? y/n " + ) + assert user_response.lower() in { + "yes", + "y", + }, f"Did not receive confirmation. Aborting download." + + print(colored(f"Downloading to {file_to_write}", "yellow")) + + with DownloadProgressBar(unit="B", unit_scale=True, miniters=1, desc=fname) as t: + urllib.request.urlretrieve(url, filename=file_to_write, reporthook=t.update_to) + + +def download_and_extract_zip( + url, + folder, + check_folder_exists=True, + prompt_before_download=False, + message="Downloading...", +): + assert url.endswith(".zip") + + download_dir = os.path.abspath(os.path.join(folder, os.pardir)) + Path(download_dir).mkdir(parents=True, exist_ok=True) + + download_path = os.path.join( + download_dir, "{}.zip".format(os.path.basename(folder)) + ) + + print(colored(message, "yellow")) + + # extract files + if check_folder_exists and os.path.exists(folder): + ans = input("{} already exists! \noverwrite? (y/n) ".format(folder)) + + if ans == "y": + print(colored("Proceeding.", "yellow")) + else: + print(colored("Skipping.\n", "yellow")) + return + + if prompt_before_download: + ans = input( + "Assets to be downloaded may be a few Gb. Proceed? (y/n) ".format(folder) + ) + + if ans == "y": + print(colored("Proceeding.", "yellow")) + else: + print(colored("Skipping.\n", "yellow")) + return + + download_success = False + for i in range(3): + try: + download_url( + url=url, + download_dir=download_dir, + fname=os.path.basename(download_path), + check_overwrite=False, + ) + download_success = True + break + except: + print("Error downloading after try #{}".format(i + 1)) + + if download_success is False: + print("Failed to download. Try again...") + return + + print(colored("Extracting...", "yellow")) + with ZipFile(download_path, "r") as zip_ref: + # Extracting all the members of the zip + # into a specific location. + zip_ref.extractall(path=download_dir) + + # delete zip file + os.remove(download_path) + + print(colored("Done.\n", "yellow")) + + +def download_kitchen_assets(bypass=False): + if bypass: + ans = "y" + else: + ans = input("The script will download ~5 Gb of data. Proceed? (y/n) ") + if ans == "y": + print("Proceeding...") + else: + print("Aborting.") + return + + for ds_name, config in DOWNLOAD_ASSET_REGISTRY.items(): + if ds_name == "aigen_objs": + continue # skip for now, too large to download initially + download_and_extract_zip(**config) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "-y", + "--yes", + action="store_true", + help="Download assets directly without prompting to screen", + ) + args = parser.parse_args() + + download_kitchen_assets(args.yes) diff --git a/third_party/robocasa/robocasa/scripts/download_tabletop_assets.py b/third_party/robocasa/robocasa/scripts/download_tabletop_assets.py new file mode 100644 index 0000000000000000000000000000000000000000..396f8d15a44a2236b0d1b1b3b863aa9e9023200b --- /dev/null +++ b/third_party/robocasa/robocasa/scripts/download_tabletop_assets.py @@ -0,0 +1,30 @@ +import argparse + +from download_groot_assets import ( + download_groot_assets, + DownloadConfig, + DEFAULT_ASSETS_VERSION, + Registry, +) + + +def download_dc_assets(bypass: bool): + cfg = DownloadConfig(registries={Registry.SKETCHFAB, Registry.LIGHTWHEEL}) + download_groot_assets( + download_config=cfg, + version=DEFAULT_ASSETS_VERSION, + bypass=bypass, + update_registry=True, + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "-y", + "--yes", + action="store_true", + help="Download assets directly without prompting to screen", + ) + args = parser.parse_args() + download_dc_assets(args.yes) diff --git a/third_party/robocasa/robocasa/scripts/playback_dataset.py b/third_party/robocasa/robocasa/scripts/playback_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..8c252ae73ecb4227ed0d80b316d514cb0fde7057 --- /dev/null +++ b/third_party/robocasa/robocasa/scripts/playback_dataset.py @@ -0,0 +1,643 @@ +import argparse +import cv2 +import datetime +import json +import os +import hashlib +import random +import shutil +import sys +import time + +import h5py +import imageio +import numpy as np +import robocasa +import robosuite +import robosuite.utils.transform_utils as T +from concurrent.futures import ProcessPoolExecutor, as_completed +from functools import partial +from itertools import product +from termcolor import colored +from tqdm import tqdm + + +def playback_trajectory_with_env( + args, + f, + ep, + env, + initial_state, + states, + actions=None, + render=False, + video_writer=None, + video_skip=5, + camera_names=None, + first=False, + verbose=False, +): + """ + Helper function to playback a single trajectory using the simulator environment. + If @actions are not None, it will play them open-loop after loading the initial state. + Otherwise, @states are loaded one by one. + + Args: + args (argparse.Namespace): command line arguments + f (hdf5 file): hdf5 file object + ep (str): episode name + env (instance of EnvBase): environment + initial_state (dict): initial simulation state to load + states (np.array): array of simulation states to load + actions (np.array): if provided, play actions back open-loop instead of using @states + render (bool): if True, render on-screen + video_writer (imageio writer): video writer + video_skip (int): determines rate at which environment frames are written to video + camera_names (list): determines which camera(s) are used for rendering. Pass more than + one to output a video with multiple camera views concatenated horizontally. + first (bool): if True, only use the first frame of each episode. + verbose (bool): if True, print additional information + """ + write_video = video_writer is not None + video_count = 0 + assert not (render and write_video) + + # load the initial state + ## this reset call doesn't seem necessary. + ## seems ok to remove but haven't fully tested it. + ## removing for now + # env.reset() + + if verbose: + ep_meta = json.loads(initial_state["ep_meta"]) + lang = ep_meta.get("lang", None) + if lang is not None: + print(colored(f"Instruction: {lang}", "green")) + print(colored("Spawning environment...", "yellow")) + reset_to(env, initial_state) + + traj_len = states.shape[0] + action_playback = actions is not None + if action_playback: + assert states.shape[0] == actions.shape[0] + + if render is False: + print(colored("Running episode...", "yellow")) + + if args.num_frames is None: + start_frame = 0 + end_frame = traj_len + else: + start_frame = random.randrange(traj_len - min(args.num_frames, traj_len) + 1) + end_frame = start_frame + min(args.num_frames, traj_len) + for i in tqdm(range(start_frame, end_frame)): + start = time.time() + + if action_playback: + env.step(actions[i]) + if i < traj_len - 1: + # check whether the actions deterministically lead to the same recorded states + state_playback = np.array(env.sim.get_state().flatten()) + if not np.all(np.equal(states[i + 1], state_playback)): + err = np.linalg.norm(states[i + 1] - state_playback) + if verbose or i == traj_len - 2: + print( + colored( + "warning: playback diverged by {} at step {}".format( + err, i + ), + "yellow", + ) + ) + else: + reset_to(env, {"states": states[i]}) + + # on-screen render + if render: + if env.viewer is None: + env.initialize_renderer() + + # so that mujoco viewer renders + env.viewer.update() + + max_fr = 60 + elapsed = time.time() - start + diff = 1 / max_fr - elapsed + if diff > 0: + time.sleep(diff) + + # video render + if write_video: + if video_count % video_skip == 0: + video_img = [] + for cam_name in camera_names: + im = env.sim.render( + height=args.render_height, + width=args.render_width, + camera_name=cam_name, + )[::-1] + video_img.append(im) + video_img = np.concatenate( + video_img, axis=1 + ) # concatenate horizontally + video_writer.append_data(video_img) + video_count += 1 + + if first: + break + + if render: + env.viewer.close() + env.viewer = None + + +def playback_trajectory_with_obs( + traj_grp, + video_writer, + video_skip=5, + image_names=None, + first=False, +): + """ + This function reads all "rgb" observations in the dataset trajectory and + writes them into a video. + + Args: + traj_grp (hdf5 file group): hdf5 group which corresponds to the dataset trajectory to playback + video_writer (imageio writer): video writer + video_skip (int): determines rate at which environment frames are written to video + image_names (list): determines which image observations are used for rendering. Pass more than + one to output a video with multiple image observations concatenated horizontally. + first (bool): if True, only use the first frame of each episode. + """ + assert ( + image_names is not None + ), "error: must specify at least one image observation to use in @image_names" + video_count = 0 + + traj_len = traj_grp["obs/{}".format(image_names[0] + "_image")].shape[0] + for i in range(traj_len): + if video_count % video_skip == 0: + # concatenate image obs together + im = [traj_grp["obs/{}".format(k + "_image")][i] for k in image_names] + frame = np.concatenate(im, axis=1) + video_writer.append_data(frame) + video_count += 1 + + if first: + break + + +def get_env_metadata_from_dataset(dataset_path, ds_format="robomimic"): + """ + Retrieves env metadata from dataset. + + Args: + dataset_path (str): path to dataset + + Returns: + env_meta (dict): environment metadata. Contains 3 keys: + + :`'env_name'`: name of environment + :`'type'`: type of environment, should be a value in EB.EnvType + :`'env_kwargs'`: dictionary of keyword arguments to pass to environment constructor + """ + dataset_path = os.path.expanduser(dataset_path) + try: + f = h5py.File(dataset_path, "r") + except Exception as e: + print(f"Error opening file {args.dataset}: {e}") + sys.exit(1) + if ds_format == "robomimic": + env_meta = json.loads(f["data"].attrs["env_args"]) + else: + raise ValueError + f.close() + return env_meta + + +class ObservationKeyToModalityDict(dict): + """ + Custom dictionary class with the sole additional purpose of automatically registering new "keys" at runtime + without breaking. This is mainly for backwards compatibility, where certain keys such as "latent", "actions", etc. + are used automatically by certain models (e.g.: VAEs) but were never specified by the user externally in their + config. Thus, this dictionary will automatically handle those keys by implicitly associating them with the low_dim + modality. + """ + + def __getitem__(self, item): + # If a key doesn't already exist, warn the user and add default mapping + if item not in self.keys(): + print( + f"ObservationKeyToModalityDict: {item} not found," + f" adding {item} to mapping with assumed low_dim modality!" + ) + self.__setitem__(item, "low_dim") + return super(ObservationKeyToModalityDict, self).__getitem__(item) + + +def reset_to(env, state): + """ + Reset to a specific simulator state. + + Args: + state (dict): current simulator state that contains one or more of: + - states (np.ndarray): initial state of the mujoco environment + - model (str): mujoco scene xml + + Returns: + observation (dict): observation dictionary after setting the simulator state (only + if "states" is in @state) + """ + should_ret = False + if "model" in state: + if state.get("ep_meta", None) is not None: + # set relevant episode information + ep_meta = json.loads(state["ep_meta"]) + else: + ep_meta = {} + if hasattr(env, "set_attrs_from_ep_meta"): # older versions had this function + env.set_attrs_from_ep_meta(ep_meta) + elif hasattr(env, "set_ep_meta"): # newer versions + env.set_ep_meta(ep_meta) + # this reset is necessary. + # while the call to env.reset_from_xml_string does call reset, + # that is only a "soft" reset that doesn't actually reload the model. + env.reset() + robosuite_version_id = int(robosuite.__version__.split(".")[1]) + if robosuite_version_id <= 3: + from robosuite.utils.mjcf_utils import postprocess_model_xml + + xml = postprocess_model_xml(state["model"]) + else: + # v1.4 and above use the class-based edit_model_xml function + xml = env.edit_model_xml(state["model"]) + + env.reset_from_xml_string(xml) + env.sim.reset() + # hide teleop visualization after restoring from model + # env.sim.model.site_rgba[env.eef_site_id] = np.array([0., 0., 0., 0.]) + # env.sim.model.site_rgba[env.eef_cylinder_id] = np.array([0., 0., 0., 0.]) + if "states" in state: + env.sim.set_state_from_flattened(state["states"]) + env.sim.forward() + should_ret = True + + # update state as needed + if hasattr(env, "update_sites"): + # older versions of environment had update_sites function + env.update_sites() + if hasattr(env, "update_state"): + # later versions renamed this to update_state + env.update_state() + + # if should_ret: + # # only return obs if we've done a forward call - otherwise the observations will be garbage + # return get_observation() + return None + + +def make_env_from_args(args): + # # need to make sure ObsUtils knows which observations are images, but it doesn't matter + # # for playback since observations are unused. Pass a dummy spec here. + # dummy_spec = dict( + # obs=dict( + # low_dim=["robot0_eef_pos"], + # rgb=[], + # ), + # ) + # initialize_obs_utils_with_obs_specs(obs_modality_specs=dummy_spec) + + env_meta = get_env_metadata_from_dataset(dataset_path=args.dataset) + if args.use_abs_actions: + env_meta["env_kwargs"]["controller_configs"][ + "control_delta" + ] = False # absolute action space + + env_kwargs = env_meta["env_kwargs"] + env_kwargs["env_name"] = env_meta["env_name"] + env_kwargs["has_renderer"] = False + env_kwargs["renderer"] = "mjviewer" + env_kwargs["has_offscreen_renderer"] = not args.render + env_kwargs["use_camera_obs"] = False + + if args.verbose: + print( + colored( + "Initializing environment for {}...".format(env_kwargs["env_name"]), + "yellow", + ) + ) + if "env_lang" in env_kwargs: + env_kwargs.pop("env_lang") + env = robosuite.make(**env_kwargs) + return env + + +# Three components when processing a demo: +# 1. Load the dataset into the variable `f`: This step ensures that the necessary data for the demo, +# such as states, actions, and metadata, is available for playback. +# 2. Initialize a video writer: If video output is required, this step sets up the writer to save +# the playback as a video file. +# 3. Create the environment `env` (optional): This step initializes the simulation environment, which +# is essential for rendering and interacting with the demo data. +def process_demo(args, ep): + print(colored("\nPlaying back episode: {}".format(ep), "yellow")) + + # maybe dump video + write_video = args.render is not True + video_writer = None + if write_video: + ep_path = args.video_path[:-4] + "_" + ep + ".mp4" + video_writer = imageio.get_writer(ep_path, fps=20) + + try: + f = h5py.File(args.dataset, "r") + except Exception as e: + print(f"Error opening file {args.dataset}: {e}") + sys.exit(1) + + if args.use_obs: + playback_trajectory_with_obs( + traj_grp=f["data/{}".format(ep)], + video_writer=video_writer, + video_skip=args.video_skip, + image_names=args.render_image_names, + first=args.first, + ) + if write_video: + print(colored(f"Saved video to {ep_path}", "green")) + video_writer.close() + f.close() + return + + # create environment only if not playing back with observations + env = make_env_from_args(args) + + def make_ik_indicator_invisible(str_xml): + import xml.etree.ElementTree as ET + + raw_xml = ET.fromstring(str_xml) + for site in raw_xml.findall(".//site"): + name = site.get("name", "") + if "pinch_spheres" in name: + print( + colored( + "make site invisible: {}".format(name), + "yellow", + ) + ) + site.set("rgba", "0 0 0 0") + return ET.tostring(raw_xml) + + # prepare initial state to reload from + states = f["data/{}/states".format(ep)][()] + initial_state = dict(states=states[0]) + initial_state["model"] = make_ik_indicator_invisible( + f["data/{}".format(ep)].attrs["model_file"] + ) + if args.use_current_env_model: + initial_state["model"] = env.sim.model.get_xml() + initial_state["ep_meta"] = f["data/{}".format(ep)].attrs.get("ep_meta", None) + + if args.extend_states: + states = np.concatenate((states, [states[-1]] * 50)) + + # supply actions if using open-loop action playback + actions = None + assert not ( + args.use_actions and args.use_abs_actions + ) # cannot use both relative and absolute actions + if args.use_actions: + actions = f["data/{}/actions".format(ep)][()] + elif args.use_abs_actions: + actions = f["data/{}/actions_abs".format(ep)][()] # absolute actions + + playback_trajectory_with_env( + args=args, + f=f, + ep=ep, + env=env, + initial_state=initial_state, + states=states, + actions=actions, + render=args.render, + video_writer=video_writer, + video_skip=args.video_skip, + camera_names=args.render_image_names, + first=args.first, + verbose=args.verbose, + ) + + if write_video: + print(colored(f"Saved video to {ep_path}", "green")) + video_writer.close() + + f.close() + env.close() + + +def playback_dataset(args): + # some arg checking + write_video = args.render is not True + if args.video_path is None: + args.video_path = args.dataset.split(".hdf5")[0] + ".mp4" + if args.use_actions: + args.video_path = args.dataset.split(".hdf5")[0] + "_use_actions.mp4" + elif args.use_abs_actions: + args.video_path = args.dataset.split(".hdf5")[0] + "_use_abs_actions.mp4" + assert not (args.render and write_video) # either on-screen or video but not both + + # Auto-fill camera rendering info if not specified + if args.render_image_names is None: + # We fill in the automatic values + env_meta = get_env_metadata_from_dataset(dataset_path=args.dataset) + args.render_image_names = "robot0_agentview_center" + + if args.render: + # on-screen rendering can only support one camera + assert len(args.render_image_names) == 1 + + if args.use_obs: + assert write_video, "playback with observations can only write to video" + assert ( + not args.use_actions and not args.use_abs_actions + ), "playback with observations is offline and does not support action playback" + + try: + f = h5py.File(args.dataset, "r") + except Exception as e: + print(f"Error opening file {args.dataset}: {e}") + sys.exit(1) + + # list of all demonstration episodes (sorted in increasing number order) + if args.filter_key is not None: + print("using filter key: {}".format(args.filter_key)) + demos = [ + elem.decode("utf-8") + for elem in np.array(f["mask/{}".format(args.filter_key)]) + ] + elif "data" in f.keys(): + demos = list(f["data"].keys()) + + inds = np.argsort([int(elem[5:]) for elem in demos]) + demos = [demos[i] for i in inds] + + # maybe reduce the number of demonstrations to playback + if args.n is not None: + random.shuffle(demos) + demos = demos[: args.n] + + if args.num_parallel_jobs == 1: + # reuse the same environment for all demos + for ep in tqdm(demos): + process_demo(args, ep) + else: + with ProcessPoolExecutor(max_workers=args.num_parallel_jobs) as executor: + process_demo_with_args = partial(process_demo, args) + futures = {executor.submit(process_demo_with_args, ep): ep for ep in demos} + for future in tqdm(as_completed(futures), total=len(futures)): + ep = futures[future] + try: + result = ( + future.result() + ) # Raises any exception that occurred during execution + except Exception as e: + print(f"[ERROR] Episode {ep}: {e}") + + f.close() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--dataset", + type=str, + help="path to hdf5 dataset", + ) + parser.add_argument( + "--filter_key", + type=str, + default=None, + help="(optional) filter key, to select a subset of trajectories in the file", + ) + + # number of trajectories to playback. If omitted, playback all of them. + parser.add_argument( + "--n", + type=int, + default=None, + help="(optional) stop after n trajectories are played", + ) + + parser.add_argument( + "--num_parallel_jobs", + type=int, + default=1, + help="(optional) number of parallel jobs to use for playback", + ) + + parser.add_argument( + "--num_frames", + type=int, + default=None, + help="(optional) number of frames to playback", + ) + + # Use image observations instead of doing playback using the simulator env. + parser.add_argument( + "--use-obs", + action="store_true", + help="visualize trajectories with dataset image observations instead of simulator", + ) + + # Playback stored dataset actions open-loop instead of loading from simulation states. + parser.add_argument( + "--use-actions", + action="store_true", + help="use open-loop action playback instead of loading sim states", + ) + + # Playback stored dataset absolute actions open-loop instead of loading from simulation states. + parser.add_argument( + "--use-abs-actions", + action="store_true", + help="use open-loop action playback with absolute position actions instead of loading sim states", + ) + + # Whether to render playback to screen + parser.add_argument( + "--render", + action="store_true", + help="on-screen rendering", + ) + + # Dump a video of the dataset playback to the specified path + parser.add_argument( + "--video_path", + type=str, + default=None, + help="(optional) render trajectories to this video file path", + ) + + # How often to write video frames during the playback + parser.add_argument( + "--video_skip", + type=int, + default=1, + help="render frames to video every n steps", + ) + + # camera names to render, or image observations to use for writing to video + parser.add_argument( + "--render_image_names", + type=str, + nargs="+", + default=[ + "egoview", + ], + help="(optional) camera name(s) / image observation(s) to use for rendering on-screen or to video. Default is" + "None, which corresponds to a predefined camera for each env type", + ) + + parser.add_argument( + "--render_height", + type=int, + default=512, + help="(optional) height of rendered video frames", + ) + + parser.add_argument( + "--render_width", + type=int, + default=512, + help="(optional) width of rendered video frames", + ) + + # Only use the first frame of each episode + parser.add_argument( + "--first", + action="store_true", + help="use first frame of each episode", + ) + + parser.add_argument( + "--extend_states", + action="store_true", + help="play last step of episodes for 50 extra frames", + ) + + parser.add_argument( + "--verbose", + action="store_true", + help="log additional information", + ) + + parser.add_argument( + "--use_current_env_model", + action="store_true", + help="use the current environment model instead of the one stored in the dataset", + ) + + args = parser.parse_args() + playback_dataset(args) diff --git a/third_party/robocasa/robocasa/utils/camera_utils.py b/third_party/robocasa/robocasa/utils/camera_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3dcd3b325a9d21c5b25ce36cf1cd4f3365c0f676 --- /dev/null +++ b/third_party/robocasa/robocasa/utils/camera_utils.py @@ -0,0 +1,91 @@ +""" +Collection of constants for cameras / robots / etc +in kitchen environments +""" + +# default free cameras for different kitchen layouts +LAYOUT_CAMS = { + 0: dict( + lookat=[2.26593463, -1.00037131, 1.38769295], + distance=3.0505089839567323, + azimuth=90.71563812375285, + elevation=-12.63948837207208, + ), + 1: dict( + lookat=[2.66147999, -1.00162429, 1.2425155], + distance=3.7958766287746255, + azimuth=89.75784013699234, + elevation=-15.177406642875091, + ), + 2: dict( + lookat=[3.02344359, -1.48874618, 1.2412914], + distance=3.6684844368165512, + azimuth=51.67880851867874, + elevation=-13.302619131542388, + ), + # 3: dict( + # lookat=[11.44842548, -11.47664723, 11.24115989], + # distance=43.923271794728187, + # azimuth=227.12928449329333, + # elevation=-16.495686334624907, + # ), + 4: dict( + lookat=[1.6, -1.0, 1.0], + distance=5, + azimuth=89.70301806083651, + elevation=-18.02177994296577, + ), +} + +DEFAULT_LAYOUT_CAM = { + "lookat": [2.25, -1, 1.05312667], + "distance": 5, + "azimuth": 89.70301806083651, + "elevation": -18.02177994296577, +} + +CAM_CONFIGS = dict( + robot0_agentview_center=dict( + pos=[-0.6, 0.0, 1.15], + quat=[ + 0.636945903301239, + 0.3325185477733612, + -0.3199238181114197, + -0.6175596117973328, + ], + parent_body="mobilebase0_support", + ), + robot0_agentview_left=dict( + pos=[-0.5, 0.35, 1.05], + quat=[0.55623853, 0.29935253, -0.37678665, -0.6775092], + camera_attribs=dict(fovy="60"), + parent_body="mobilebase0_support", + ), + robot0_agentview_right=dict( + pos=[-0.5, -0.35, 1.05], + quat=[ + 0.6775091886520386, + 0.3767866790294647, + -0.2993525564670563, + -0.55623859167099, + ], + camera_attribs=dict(fovy="60"), + parent_body="mobilebase0_support", + ), + robot0_frontview=dict( + pos=[-0.50, 0, 0.95], + quat=[ + 0.6088936924934387, + 0.3814677894115448, + -0.3673907518386841, + -0.5905545353889465, + ], + camera_attribs=dict(fovy="60"), + parent_body="mobilebase0_support", + ), + robot0_eye_in_hand=dict( + pos=[0.05, 0, 0], + quat=[0, 0.707107, 0.707107, 0], + parent_body="robot0_right_hand", + ), +) diff --git a/third_party/robocasa/robocasa/utils/config_utils.py b/third_party/robocasa/robocasa/utils/config_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bbb5faf04fbc0f37967b7c99b124f5c80307cb1b --- /dev/null +++ b/third_party/robocasa/robocasa/utils/config_utils.py @@ -0,0 +1,63 @@ +import copy +import os +import pathlib +import robosuite +from robosuite.controllers import load_composite_controller_config + + +def is_stale_controller_config(config: dict): + """ + Checks if a controller config is in the format from robosuite versions <= 1.4.1. + Does not check for config validity, only the format type. + Args: + config (dict): Controller configuration + Returns: + bool: True if the config is in the old format, False otherwise + """ + + OLD_CONTROLLER_TYPES = [ + "JOINT_VELOCITY", + "JOINT_TORQUE", + "JOINT_POSITION", + "OSC_POSITION", + "OSC_POSE", + "IK_POSE", + ] + if ( + "body_parts" not in config or "body_parts_controller_configs" not in config + ) and "type" in config: + return config["type"] in OLD_CONTROLLER_TYPES + return False + + +def refactor_composite_controller_config(controller_config, robot_type, arms): + """ + Checks if a controller config is in the format from robosuite versions <= 1.4.1. + If this is the case, converts the controller config to the new composite controller + config format in robosuite versions >= 1.5. If the robot has a default + controller config use that and override the arms with the old controller config. + If not just use the old controller config for arms. + Args: + old_controller_config (dict): Old controller config + Returns: + dict: New controller config + """ + if not is_stale_controller_config(controller_config): + return controller_config + + config_dir = pathlib.Path(robosuite.__file__).parent / "controllers/config/robots/" + name = robot_type.lower() + configs = os.listdir(config_dir) + if f"default_{name}.json" in configs: + new_controller_config = load_composite_controller_config(robot=name) + else: + new_controller_config = {} + new_controller_config["type"] = "BASIC" + new_controller_config["body_parts"] = {} + + for arm in arms: + new_arm_config = copy.deepcopy(controller_config) + if "gripper" not in new_arm_config: + new_arm_config["gripper"] = {"type": "GRIP"} + new_controller_config["body_parts"][arm] = new_arm_config + return new_controller_config diff --git a/third_party/robocasa/robocasa/utils/cotrain_utils.py b/third_party/robocasa/robocasa/utils/cotrain_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8d0a57c126d5e72209c3728cd6fcb01b65f38b4f --- /dev/null +++ b/third_party/robocasa/robocasa/utils/cotrain_utils.py @@ -0,0 +1,24 @@ +""" +Utility functions and constants for co-training with real robot. +""" +from robosuite.models.robots.manipulators.gr1_robot import GR1 + +# Initial pose configuration for co-training with real robot +COTRAIN_REAL_MATCHED_ROBOT_INITIAL_POSE = { + GR1: { + "robot0_r_shoulder_pitch": -0.22963779, + "robot0_r_shoulder_roll": -0.38363408, + "robot0_r_shoulder_yaw": 0.14360377, + "robot0_r_elbow_pitch": -1.5289252, + "robot0_r_wrist_yaw": -0.2897802, + "robot0_r_wrist_roll": -0.07134621, + "robot0_r_wrist_pitch": -0.04550289, + "robot0_l_shoulder_pitch": -0.10933163, + "robot0_l_shoulder_roll": 0.43292055, + "robot0_l_shoulder_yaw": -0.15983289, + "robot0_l_elbow_pitch": -1.48233023, + "robot0_l_wrist_yaw": 0.2359135, + "robot0_l_wrist_roll": 0.26184522, + "robot0_l_wrist_pitch": 0.00830735, + } +} diff --git a/third_party/robocasa/robocasa/utils/dexmg_utils.py b/third_party/robocasa/robocasa/utils/dexmg_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e1e3e9e0bf6ed5a04487617a656754c3fcaff78e --- /dev/null +++ b/third_party/robocasa/robocasa/utils/dexmg_utils.py @@ -0,0 +1,105 @@ +class DexMGConfigHelper: + """ + Helper class for multi-inheritance scenarios, specifically designed to support task configuration + and environment interaction in robotic manipulation tasks. + + Example Usage: + This class is intended to be used in multi-inheritance cases such as: + class PnPCounterToSink(Kitchen, DexMGConfigHelper) + which will automatically generate a new configuration class: + class PnPCounterToSink_Config(MG_Config) + + Behavior: + 1. In the implementation of the MG_RoboSuiteHumanoidGeneric class: + - `self.env` will be an instance of PnPCounterToSink, enabling access to: + - `self.env.get_object()` to retrieve key objects. + - `self.env.get_subtask_term_signals()` to obtain signal information. + 2. In the implementation of PnPCounterToSink_Config: + - `self.task_config()` delegates to `PnPCounterToSink.task_config`, which defines + subtask divisions based on objects and signals. + + Attributes: + subclasses (list): A list storing tuples of subclass names and their respective classes. + """ + + class AttrDict(dict): + def __getattr__(self, key): + if key not in self: + self[ + key + ] = ( + DexMGConfigHelper.AttrDict() + ) # Create a new AttrDict if key doesn't exist + return self[key] + + def __setattr__(self, key, value): + self[key] = value + + def to_dict(self): + """Recursively converts AttrDict to a normal dictionary""" + return { + key: ( + value.to_dict() + if isinstance(value, DexMGConfigHelper.AttrDict) + else value + ) + for key, value in self.items() + } + + subclasses = [] + + def __init_subclass__(cls, **kwargs): + """ + Automatically registers each subclass of DexMGConfigHelper. + + Args: + cls: The subclass being registered. + kwargs: Additional keyword arguments. + """ + super().__init_subclass__(**kwargs) + DexMGConfigHelper.subclasses.append((cls.__name__, cls)) + + def __init__(self): + """ + Initialize a DexMGConfigHelper instance. + Note: This is an abstract class and should not be instantiated directly. + """ + pass + + # Misc functions copied from dexmimicgen.mimicgen.env_interfaces.robosuite_humanoid + def get_grippers(self): + """ + Get grippers for the environment. + """ + return self.robots[0].gripper["right"], self.robots[0].gripper["left"] + + def get_object(self): + """ + Retrieve a key object required for the task. + This method must be implemented in subclasses. + + Raises: + NotImplementedError: If the method is not overridden in a subclass. + """ + raise NotImplementedError + + def get_subtask_term_signals(self): + """ + Retrieve signals used to define subtask termination conditions. + This method must be implemented in subclasses. + + Raises: + NotImplementedError: If the method is not overridden in a subclass. + """ + raise NotImplementedError + + @staticmethod + def task_config(): + """ + Define the configuration for dividing a task into subtasks. + This method must be implemented in subclasses. + + Raises: + NotImplementedError: If the method is not overridden in a subclass. + """ + raise NotImplementedError diff --git a/third_party/robocasa/robocasa/utils/gym_utils/__init__.py b/third_party/robocasa/robocasa/utils/gym_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03d3d426d6f296b0ca406cf8cc5ec2605a9bbb73 --- /dev/null +++ b/third_party/robocasa/robocasa/utils/gym_utils/__init__.py @@ -0,0 +1,4 @@ +from .gymnasium_basic import RoboCasaEnv # noqa: F401 +from .gymnasium_groot import GrootRoboCasaEnv # noqa: F401 + +# from .gymnasium_gearbc import GearBCRoboCasaEnv # noqa: F401 diff --git a/third_party/robocasa/robocasa/utils/gym_utils/gymnasium_basic.py b/third_party/robocasa/robocasa/utils/gym_utils/gymnasium_basic.py new file mode 100644 index 0000000000000000000000000000000000000000..91b11039c490b9e2aac2c4d2a5db1fc116660e3f --- /dev/null +++ b/third_party/robocasa/robocasa/utils/gym_utils/gymnasium_basic.py @@ -0,0 +1,261 @@ +import datetime, uuid +from copy import deepcopy +import gymnasium as gym +import numpy as np +import os +import robocasa # we need this to register environments # noqa: F401 +import robosuite +from gymnasium import spaces +from robocasa.environments.tabletop.tabletop import Tabletop +from robocasa.models.robots import ( + GROOT_ROBOCASA_ENVS_GR1_ARMS_ONLY, + GROOT_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST, + GROOT_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY, + gather_robot_observations, + make_key_converter, +) +from robosuite.controllers import load_composite_controller_config +from robosuite.controllers.parts.arm.osc import OperationalSpaceController +from robosuite.controllers.composite.composite_controller import HybridMobileBase +from robosuite.environments.base import REGISTERED_ENVS + + +ALLOWED_LANGUAGE_CHARSET = ( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,.\n\t[]{}()!?'_:" +) + + +def create_env_robosuite( + env_name, + # robosuite-related configs + robots="PandaOmron", + controller_configs=None, + camera_names=[ + "egoview", + "robot0_eye_in_left_hand", + "robot0_eye_in_right_hand", + ], + camera_widths=128, + camera_heights=128, + enable_render=True, + seed=None, + # robocasa-related configs + obj_instance_split=None, + generative_textures=None, + randomize_cameras=False, + layout_and_style_ids=None, + layout_ids=None, + style_ids=None, +): + if controller_configs is None: + controller_configs = load_composite_controller_config( + controller=None, + robot=robots if isinstance(robots, str) else robots[0], + ) + env_kwargs = dict( + env_name=env_name, + robots=robots, + controller_configs=controller_configs, + camera_names=camera_names, + camera_widths=camera_widths, + camera_heights=camera_heights, + has_renderer=False, + has_offscreen_renderer=enable_render, + ignore_done=True, + use_object_obs=True, + use_camera_obs=enable_render, + camera_depths=False, + seed=seed, + translucent_robot=False, + ) + env_class = REGISTERED_ENVS[env_name] + + env = robosuite.make(**env_kwargs) + return env, env_kwargs + + +class RoboCasaEnv(gym.Env): + def __init__( + self, + env_name=None, + robots_name=None, + camera_names=None, + camera_widths=None, + camera_heights=None, + enable_render=True, + dump_rollout_dataset_dir=None, + **kwargs, # Accept additional kwargs + ): + self.key_converter = make_key_converter(robots_name) + ( + _, + camera_names, + default_camera_widths, + default_camera_heights, + ) = self.key_converter.get_camera_config() + + if camera_widths is None: + camera_widths = default_camera_widths + if camera_heights is None: + camera_heights = default_camera_heights + + controller_configs = load_composite_controller_config( + controller=None, + robot=robots_name.split("_")[0], + ) + if ( + robots_name in GROOT_ROBOCASA_ENVS_GR1_ARMS_ONLY + or robots_name in GROOT_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST + or robots_name in GROOT_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY + ): + controller_configs["type"] = "BASIC" + controller_configs["composite_controller_specific_configs"] = {} + controller_configs["control_delta"] = False + + self.env, self.env_kwargs = create_env_robosuite( + env_name=env_name, + robots=robots_name.split("_"), + controller_configs=controller_configs, + camera_names=camera_names, + camera_widths=camera_widths, + camera_heights=camera_heights, + enable_render=enable_render, + **kwargs, # Forward kwargs to create_env_robosuite + ) + + # TODO: the following info should be output by grootrobocasa + self.camera_names = camera_names + self.camera_widths = camera_widths + self.camera_heights = camera_heights + self.enable_render = enable_render + self.render_obs_key = f"{camera_names[0]}_image" + self.render_cache = None + + # setup spaces + action_space = spaces.Dict() + for robot in self.env.robots: + cc = robot.composite_controller + pf = robot.robot_model.naming_prefix + for part_name, controller in cc.part_controllers.items(): + min_value, max_value = -1, 1 + start_idx, end_idx = cc._action_split_indexes[part_name] + shape = [end_idx - start_idx] + this_space = spaces.Box( + low=min_value, high=max_value, shape=shape, dtype=np.float32 + ) + action_space[f"{pf}{part_name}"] = this_space + if isinstance(cc, HybridMobileBase): + this_space = spaces.Discrete(2) + action_space[f"{pf}base_mode"] = this_space + + action_space = spaces.Dict(action_space) + self.action_space = action_space + + obs = ( + self.env.viewer._get_observations(force_update=True) + if self.env.viewer_get_obs + else self.env._get_observations(force_update=True) + ) + obs.update(gather_robot_observations(self.env)) + observation_space = spaces.Dict() + for obs_name, obs_value in obs.items(): + shape = list(obs_value.shape) + if obs_name.endswith("_image"): + continue + min_value, max_value = -1, 1 + this_space = spaces.Box( + low=min_value, high=max_value, shape=shape, dtype=np.float32 + ) + observation_space[obs_name] = this_space + + for camera_name in camera_names: + shape = [camera_heights, camera_widths, 3] + this_space = spaces.Box(low=0, high=255, shape=shape, dtype=np.uint8) + observation_space[f"{camera_name}_image"] = this_space + + observation_space["language"] = spaces.Text( + max_length=256, charset=ALLOWED_LANGUAGE_CHARSET + ) + + self.observation_space = observation_space + + self.dump_rollout_dataset_dir = dump_rollout_dataset_dir + self.groot_exporter = None + self.np_exporter = None + + def get_basic_observation(self, raw_obs): + raw_obs.update(gather_robot_observations(self.env)) + + # Image are in (H, W, C), flip it upside down + def process_img(img): + return np.copy(img[::-1, :, :]) + + for obs_name, obs_value in raw_obs.items(): + if obs_name.endswith("_image"): + # image observations + raw_obs[obs_name] = process_img(obs_value) + else: + # non-image observations + raw_obs[obs_name] = obs_value.astype(np.float32) + + # Return black image if rendering is disabled + if not self.enable_render: + for name in self.camera_names: + raw_obs[f"{name}_image"] = np.zeros( + (self.camera_heights, self.camera_widths, 3), dtype=np.uint8 + ) + + self.render_cache = raw_obs[self.render_obs_key] + raw_obs["language"] = self.env.get_ep_meta().get("lang", "") + + return raw_obs + + def reset(self, seed=None, options=None): + np.random.seed(seed) + raw_obs = self.env.reset() + # return obs + obs = self.get_basic_observation(raw_obs) + + info = {} + info["success"] = False + info["grasp_distractor_obj"] = False + + return obs, info + + def step(self, action_dict): + env_action = [] + for robot in self.env.robots: + cc = robot.composite_controller + pf = robot.robot_model.naming_prefix + action = np.zeros(cc.action_limits[0].shape) + for part_name, controller in cc.part_controllers.items(): + start_idx, end_idx = cc._action_split_indexes[part_name] + act = action_dict.pop(f"{pf}{part_name}") + action[start_idx:end_idx] = act + if isinstance(cc, HybridMobileBase): + action[-1] = action_dict.pop(f"{pf}base_mode") + env_action.append(action) + + assert len(action_dict) == 0, f"Unprocessed actions: {action_dict}" + env_action = np.concatenate(env_action) + + raw_obs, reward, done, info = self.env.step(env_action) + + obs = self.get_basic_observation(raw_obs) + + truncated = False + + info["success"] = reward > 0 + info["grasp_distractor_obj"] = False + if hasattr(self, "_check_grasp_distractor_obj"): + info["grasp_distractor_obj"] = self._check_grasp_distractor_obj() + + return obs, reward, done, truncated, info + + def render(self): + if self.render_cache is None: + raise RuntimeError("Must run reset or step before render.") + return self.render_cache + + def close(self): + self.env.close() diff --git a/third_party/robocasa/robocasa/utils/gym_utils/gymnasium_gearbc.py b/third_party/robocasa/robocasa/utils/gym_utils/gymnasium_gearbc.py new file mode 100644 index 0000000000000000000000000000000000000000..cde78f11489242044d32d4d01feefc452d1f1146 --- /dev/null +++ b/third_party/robocasa/robocasa/utils/gym_utils/gymnasium_gearbc.py @@ -0,0 +1,184 @@ +import sys +from typing import Any, Dict + +import cv2 +import numpy as np +from gymnasium import spaces +from gymnasium.envs.registration import register + +from robocasa.models.robots import GROOT_ROBOCASA_ENVS_ROBOTS +from .gymnasium_basic import ( + REGISTERED_ENVS, + RoboCasaEnv, +) + +ALLOWED_LANGUAGE_CHARSET = ( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,.\n\t[]{}()!?'_:" +) +FINAL_IMAGE_RESOLUTION = (224, 224) + + +class GearBCRoboCasaEnv(RoboCasaEnv): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + temp_observation_space = self.key_converter.deduce_observation_space(self.env) + self.observation_space = spaces.Dict() + for k, v in temp_observation_space.items(): + assert k.startswith("state.") + self.observation_space[k[6:] + "_state"] = v + mapped_names, camera_names, _, _ = self.key_converter.get_camera_config() + for camera_name in camera_names: + self.observation_space[camera_name + "_image"] = spaces.Box( + low=0, high=1, shape=(3, *FINAL_IMAGE_RESOLUTION), dtype=np.float32 + ) + # self.observation_space[ + # "annotation.human.action.task_description" + # ] = spaces.Text(max_length=256, charset=ALLOWED_LANGUAGE_CHARSET) + + temp_action_space = self.key_converter.deduce_action_space(self.env) + self.action_space = spaces.Dict() + for k, v in temp_action_space.items(): + assert k.startswith("action.") + if isinstance(v, spaces.Box): + self.action_space[k[7:] + "_action"] = v + else: + self.action_space[k[7:] + "_action"] = spaces.Box( + low=-1, high=1, shape=(1,), dtype=np.float32 + ) + + self.verbose = True + for k, v in self.observation_space.items(): + self.verbose and print("{OBS}", k, v) + for k, v in self.action_space.items(): + self.verbose and print("{ACTION}", k, v) + + @staticmethod + def process_img(img): + h, w, _ = img.shape + if h != w: + dim = max(h, w) + y_offset = (dim - h) // 2 + x_offset = (dim - w) // 2 + img = np.pad(img, ((y_offset, y_offset), (x_offset, x_offset), (0, 0))) + h, w = dim, dim + if (h, w) != FINAL_IMAGE_RESOLUTION: + img = cv2.resize(img, FINAL_IMAGE_RESOLUTION, cv2.INTER_AREA) + # Convert from (H, W, C) to (C, H, W) + img = np.copy( + (np.transpose(img, (2, 0, 1)).astype(np.float32) / 255.0).clip(0.0, 1.0) + ) + return np.copy(img) + + def get_gearbc_observation(self, raw_obs): + obs = {} + temp_obs = self.key_converter.map_obs(raw_obs) + for k, v in temp_obs.items(): + if k.startswith("hand.") or k.startswith("body."): + obs[k[5:] + "_state"] = v + else: + raise ValueError(f"Unknown key: {k}") + mapped_names, camera_names, _, _ = self.key_converter.get_camera_config() + for mapped_name, camera_name in zip(mapped_names, camera_names): + obs[camera_name + "_image"] = GearBCRoboCasaEnv.process_img( + raw_obs[camera_name + "_image"] + ) + self.render_cache = np.copy( + (np.transpose(obs[self.render_obs_key], (1, 2, 0)) * 255.0).astype(np.uint8) + ) + font = cv2.FONT_HERSHEY_SIMPLEX + font_scale = max(FINAL_IMAGE_RESOLUTION) / 1000 + color = (255, 255, 0) # Yellow text + thickness = 1 + + # Split text into lines of max 50 characters + text = self.env.get_ep_meta().get("lang", "") + words = text.split() + lines = [] + current_line = [] + current_length = 0 + + for word in words: + if current_length + len(word) + 1 <= 50: # +1 for space + current_line.append(word) + current_length += len(word) + 1 + else: + lines.append(" ".join(current_line)) + current_line = [word] + current_length = len(word) + if current_line: + lines.append(" ".join(current_line)) + + # Draw each line + y_position = int(FINAL_IMAGE_RESOLUTION[0] * 0.9) + x_position = int(FINAL_IMAGE_RESOLUTION[1] * 0.1) + line_spacing = int(30 * font_scale) # Adjust spacing between lines + + for line in lines: + cv2.putText( + self.render_cache, + line, + (x_position, y_position), + font, + font_scale, + color, + thickness, + cv2.LINE_AA, + ) + y_position += line_spacing # Move down for next line + + # obs["annotation.human.action.task_description"] = raw_obs["language"] + return obs + + def reset(self, seed=None, options=None): + raw_obs, info = super().reset(seed=seed, options=options) + obs = self.get_gearbc_observation(raw_obs) + return obs, info + + def step(self, action): + temp_action = action.copy() + action = {} + for k, v in temp_action.items(): + assert k.endswith("_action") + action["action." + k[:-7]] = v + for k, v in action.items(): + self.verbose and print("", k, v) + + action = self.key_converter.unmap_action(action) + raw_obs, reward, terminated, truncated, info = super().step(action) + obs = self.get_gearbc_observation(raw_obs) + + for k, v in obs.items(): + self.verbose and print("", k, v.shape if k.endswith("image") else v) + self.verbose = False + + return obs, reward, terminated, truncated, info + + +def create_gearbcrobocasa_env_class(env, robot, robot_alias): + class_name = f"{env}_{robot}_Env" + id_name = f"gearbc/{class_name}" + + env_class_type = type( + class_name, + (GearBCRoboCasaEnv,), + { + "__init__": lambda self, **kwargs: super(self.__class__, self).__init__( + env_name=env, + robots_name=robot, + **kwargs, + ) + }, + ) + + current_module = sys.modules["robocasa.utils.gym_utils.gymnasium_gearbc"] + setattr(current_module, class_name, env_class_type) + register( + id=id_name, # Unique ID for the environment + entry_point=f"robocasa.utils.gym_utils.gymnasium_gearbc:{class_name}", # Path to your environment class + ) + + +for ENV in REGISTERED_ENVS: + for ROBOT, ROBOT_ALIAS in GROOT_ROBOCASA_ENVS_ROBOTS.items(): + create_gearbcrobocasa_env_class(ENV, ROBOT, ROBOT_ALIAS) diff --git a/third_party/robocasa/robocasa/utils/gym_utils/gymnasium_groot.py b/third_party/robocasa/robocasa/utils/gym_utils/gymnasium_groot.py new file mode 100644 index 0000000000000000000000000000000000000000..07c5892076945f1a9948d29ba061816588e06868 --- /dev/null +++ b/third_party/robocasa/robocasa/utils/gym_utils/gymnasium_groot.py @@ -0,0 +1,173 @@ +import sys +from typing import Any, Dict + +import cv2 +import numpy as np +from gymnasium import spaces +from gymnasium.envs.registration import register + +from robocasa.models.robots import GROOT_ROBOCASA_ENVS_ROBOTS +from robocasa.models.robots.manipulators.gr1_robot import GR1ArmsOnly, GR1ArmsAndWaist +from .gymnasium_basic import ( + REGISTERED_ENVS, + RoboCasaEnv, +) + +ALLOWED_LANGUAGE_CHARSET = ( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,.\n\t[]{}()!?'_:" +) +FINAL_IMAGE_RESOLUTION = (256, 256) + + +class GrootRoboCasaEnv(RoboCasaEnv): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.observation_space = self.key_converter.deduce_observation_space(self.env) + mapped_names, _, _, _ = self.key_converter.get_camera_config() + for mapped_name in mapped_names: + self.observation_space[mapped_name] = spaces.Box( + low=0, high=255, shape=(*FINAL_IMAGE_RESOLUTION, 3), dtype=np.uint8 + ) + if mapped_name == "video.ego_view_pad_res256_freq20": + self.observation_space[ + "video.ego_view_bg_crop_pad_res256_freq20" + ] = spaces.Box( + low=0, high=255, shape=(*FINAL_IMAGE_RESOLUTION, 3), dtype=np.uint8 + ) + if isinstance(self.env.robots[0].robot_model, GR1ArmsOnly): + self.observation_space["annotation.human.coarse_action"] = spaces.Text( + max_length=256, charset=ALLOWED_LANGUAGE_CHARSET + ) + elif isinstance(self.env.robots[0].robot_model, GR1ArmsAndWaist): + self.observation_space["annotation.human.coarse_action"] = spaces.Text( + max_length=256, charset=ALLOWED_LANGUAGE_CHARSET + ) + else: + self.observation_space[ + "annotation.human.action.task_description" + ] = spaces.Text(max_length=256, charset=ALLOWED_LANGUAGE_CHARSET) + self.action_space = self.key_converter.deduce_action_space(self.env) + + self.verbose = False + for k, v in self.observation_space.items(): + self.verbose and print("{OBS}", k, v) + for k, v in self.action_space.items(): + self.verbose and print("{ACTION}", k, v) + + @staticmethod + def process_img(img): + h, w, _ = img.shape + if h != w: + dim = max(h, w) + y_offset = (dim - h) // 2 + x_offset = (dim - w) // 2 + img = np.pad(img, ((y_offset, y_offset), (x_offset, x_offset), (0, 0))) + h, w = dim, dim + if (h, w) != FINAL_IMAGE_RESOLUTION: + img = cv2.resize(img, FINAL_IMAGE_RESOLUTION, cv2.INTER_AREA) + return np.copy(img) + + @staticmethod + def process_img_cotrain(img): + assert img.shape[0] == 800 and img.shape[1] == 1280 + + oh, ow = 256, 256 + crop = (310, 770, 110, 1130) + img = img[crop[0] : crop[1], crop[2] : crop[3]] + + img_resized = cv2.resize(img, (720, 480), cv2.INTER_AREA) + width_pad = (img_resized.shape[1] - img_resized.shape[0]) // 2 + img_pad = np.pad( + img_resized, + ((width_pad, width_pad), (0, 0), (0, 0)), + mode="constant", + constant_values=0, + ) + img_resized = cv2.resize(img_pad, (oh, ow), cv2.INTER_AREA) + return img_resized + + def get_groot_observation(self, raw_obs): + obs = {} + temp_obs = self.key_converter.map_obs(raw_obs) + for k, v in temp_obs.items(): + if k.startswith("hand.") or k.startswith("body."): + obs["state." + k[5:]] = v + else: + raise ValueError(f"Unknown key: {k}") + mapped_names, camera_names, _, _ = self.key_converter.get_camera_config() + for mapped_name, camera_name in zip(mapped_names, camera_names): + obs[mapped_name] = GrootRoboCasaEnv.process_img( + raw_obs[camera_name + "_image"] + ) + if mapped_name == "video.ego_view_pad_res256_freq20": + obs[ + "video.ego_view_bg_crop_pad_res256_freq20" + ] = GrootRoboCasaEnv.process_img_cotrain( + raw_obs[camera_name + "_image"] + ) + if isinstance(self.env.robots[0].robot_model, GR1ArmsOnly): + obs[ + "annotation.human.coarse_action" + ] = f"locked_waist: {raw_obs['language']}" + elif isinstance(self.env.robots[0].robot_model, GR1ArmsAndWaist): + obs[ + "annotation.human.coarse_action" + ] = f"unlocked_waist: {raw_obs['language']}" + else: + obs["annotation.human.action.task_description"] = raw_obs["language"] + return obs + + def reset(self, seed=None, options=None): + raw_obs, info = super().reset(seed=seed, options=options) + obs = self.get_groot_observation(raw_obs) + return obs, info + + def step(self, action): + for k, v in action.items(): + self.verbose and print("", k, v) + + action = self.key_converter.unmap_action(action) + raw_obs, reward, terminated, truncated, info = super().step(action) + obs = self.get_groot_observation(raw_obs) + + for k, v in obs.items(): + self.verbose and print("", k, v.shape if k.startswith("video.") else v) + self.verbose = False + + return obs, reward, terminated, truncated, info + + +def create_grootrobocasa_env_class(env, robot, robot_alias): + class_name = f"{env}_{robot}_Env" + id_name = f"robocasa_{robot_alias}/{class_name}" + + env_class_type = type( + class_name, + (GrootRoboCasaEnv,), + { + "__init__": lambda self, **kwargs: super(self.__class__, self).__init__( + env_name=env, + robots_name=robot, + **kwargs, + ) + }, + ) + + current_module = sys.modules["robocasa.utils.gym_utils.gymnasium_groot"] + setattr(current_module, class_name, env_class_type) + register( + id=id_name, # Unique ID for the environment + entry_point=f"robocasa.utils.gym_utils.gymnasium_groot:{class_name}", # Path to your environment class + ) + + if robot_alias == "gr1_arms_waist_fourier_hands": + id_name = f"gr1_unified/{class_name}" + register( + id=id_name, # Unique ID for the environment + entry_point=f"robocasa.utils.gym_utils.gymnasium_groot:{class_name}", # Path to your environment class + ) + + +for ENV in REGISTERED_ENVS: + for ROBOT, ROBOT_ALIAS in GROOT_ROBOCASA_ENVS_ROBOTS.items(): + create_grootrobocasa_env_class(ENV, ROBOT, ROBOT_ALIAS) diff --git a/third_party/robocasa/robocasa/utils/object_utils.py b/third_party/robocasa/robocasa/utils/object_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..98e42e62ac13f37d49b2de050395e75f733cddb9 --- /dev/null +++ b/third_party/robocasa/robocasa/utils/object_utils.py @@ -0,0 +1,641 @@ +import numpy as np +import mujoco as mj +import robosuite.utils.transform_utils as T +from robosuite.utils.mjcf_utils import array_to_string + +from robocasa.models.objects.objects import MJCFObject + + +def obj_inside_of(env, obj_name, fixture_id, partial_check=False): + """ + whether an object (another mujoco object) is inside of fixture. applies for most fixtures + """ + from robocasa.models.fixtures import Fixture + + obj = env.objects[obj_name] + fixture = env.get_fixture(fixture_id) + assert isinstance(obj, MJCFObject) + assert isinstance(fixture, Fixture) + + # step 1: calculate fxiture points + fixtr_p0, fixtr_px, fixtr_py, fixtr_pz = fixture.get_int_sites(relative=False) + u = fixtr_px - fixtr_p0 + v = fixtr_py - fixtr_p0 + w = fixtr_pz - fixtr_p0 + + # get the position and quaternion of object + obj_pos = np.array(env.sim.data.body_xpos[env.obj_body_id[obj.name]]) + obj_quat = T.convert_quat( + env.sim.data.body_xquat[env.obj_body_id[obj.name]], to="xyzw" + ) + + if partial_check: + obj_points_to_check = [obj_pos] + th = 0.0 + else: + # calculate 8 boundary points of object + obj_points_to_check = obj.get_bbox_points(trans=obj_pos, rot=obj_quat) + # threshold to mitigate false negatives: even if the bounding box point is out of bounds, + th = 0.05 + + inside_of = True + for obj_p in obj_points_to_check: + check1 = ( + np.dot(u, fixtr_p0) - th <= np.dot(u, obj_p) <= np.dot(u, fixtr_px) + th + ) + check2 = ( + np.dot(v, fixtr_p0) - th <= np.dot(v, obj_p) <= np.dot(v, fixtr_py) + th + ) + check3 = ( + np.dot(w, fixtr_p0) - th <= np.dot(w, obj_p) <= np.dot(w, fixtr_pz) + th + ) + + if not (check1 and check2 and check3): + inside_of = False + break + + return inside_of + + +# used for cabinets, cabinet panels, counters, etc. +def set_geom_dimensions(sizes, positions, geoms, rotated=False): + """ + set the dimensions of geoms in a fixture + + Args: + sizes (dict): dictionary of sizes for each side + + positions (dict): dictionary of positions for each side + + geoms (dict): dictionary of geoms for each side + + rotated (bool): whether the fixture is rotated. Fixture may be rotated to make texture appear uniform + due to mujoco texture conventions + """ + if rotated: + # rotation trick to make texture appear uniform + # see .xml file + for side in sizes.keys(): + # not the best detection method, TODO: check euler + if "door" in side or "trim" in side: + sizes[side] = [sizes[side][i] for i in [0, 2, 1]] + + # set sizes and positions of all geoms + for side in positions.keys(): + for geom in geoms[side]: + if geom is None: + raise ValueError("Did not find geom:", side) + geom.set("pos", array_to_string(positions[side])) + geom.set("size", array_to_string(sizes[side])) + + +def get_rel_transform(fixture_A, fixture_B): + """ + Gets fixture_B's position and rotation relative to fixture_A's frame + """ + A_trans = np.array(fixture_A.pos) + B_trans = np.array(fixture_B.pos) + + A_rot = np.array([0, 0, fixture_A.rot]) + B_rot = np.array([0, 0, fixture_B.rot]) + + A_mat = T.euler2mat(A_rot) + B_mat = T.euler2mat(B_rot) + + T_WA = np.vstack((np.hstack((A_mat, A_trans[:, None])), [0, 0, 0, 1])) + T_WB = np.vstack((np.hstack((B_mat, B_trans[:, None])), [0, 0, 0, 1])) + + T_AB = np.matmul(np.linalg.inv(T_WA), T_WB) + + return T_AB[:3, 3], T_AB[:3, :3] + + +def compute_rel_transform(A_pos, A_mat, B_pos, B_mat): + """ + Gets B's position and rotation relative to A's frame + """ + T_WA = np.vstack((np.hstack((A_mat, A_pos[:, None])), [0, 0, 0, 1])) + T_WB = np.vstack((np.hstack((B_mat, B_pos[:, None])), [0, 0, 0, 1])) + + T_AB = np.matmul(np.linalg.inv(T_WA), T_WB) + + return T_AB[:3, 3], T_AB[:3, :3] + + +def get_fixture_to_point_rel_offset(fixture, point): + """ + get offset relative to fixture's frame, given a global point + """ + global_offset = point - fixture.pos + T_WF = T.euler2mat([0, 0, fixture.rot]) + rel_offset = np.matmul(np.linalg.inv(T_WF), global_offset) + return rel_offset + + +def get_pos_after_rel_offset(fixture, offset): + """ + get global position of a fixture, after applying offset relative to center of fixture + """ + fixture_rot = np.array([0, 0, fixture.rot]) + fixture_mat = T.euler2mat(fixture_rot) + + return fixture.pos + np.dot(fixture_mat, offset) + + +def project_point_to_line(P, A, B): + """ + logic copied from here: https://stackoverflow.com/a/61342198 + """ + AP = P - A + AB = B - A + result = A + np.dot(AP, AB) / np.dot(AB, AB) * AB + + return result + + +def point_in_fixture(point, fixture, only_2d=False): + """ + check if point is inside of the exterior bounding boxes of the fixture + + Args: + point (np.array): point to check + + fixture (Fixture): fixture object + + only_2d (bool): whether to check only in 2D + """ + p0, px, py, pz = fixture.get_ext_sites(relative=False) + th = 0.00 + u = px - p0 + v = py - p0 + w = pz - p0 + check1 = np.dot(u, p0) - th <= np.dot(u, point) <= np.dot(u, px) + th + check2 = np.dot(v, p0) - th <= np.dot(v, point) <= np.dot(v, py) + th + check3 = np.dot(w, p0) - th <= np.dot(w, point) <= np.dot(w, pz) + th + + if only_2d: + return check1 and check2 + else: + return check1 and check2 and check3 + + +def obj_in_region( + obj, + obj_pos, + obj_quat, + p0, + px, + py, + pz=None, +): + """ + check if object is in the region defined by the points. + Uses either the objects bounding box or the object's horizontal radius + """ + from robocasa.models.fixtures import Fixture + + if isinstance(obj, MJCFObject) or isinstance(obj, Fixture): + obj_points = obj.get_bbox_points(trans=obj_pos, rot=obj_quat) + else: + radius = obj.horizontal_radius + obj_points = obj_pos + np.array( + [ + [radius, 0, 0], + [-radius, 0, 0], + [0, radius, 0], + [0, -radius, 0], + ] + ) + + u = px - p0 + v = py - p0 + w = pz - p0 if pz is not None else None + + for point in obj_points: + check1 = np.dot(u, p0) <= np.dot(u, point) <= np.dot(u, px) + check2 = np.dot(v, p0) <= np.dot(v, point) <= np.dot(v, py) + + if not check1 or not check2: + return False + + if w is not None: + check3 = np.dot(w, p0) <= np.dot(w, point) <= np.dot(w, pz) + if not check3: + return False + + return True + + +def obj_in_region_with_keypoints( + obj, obj_pos, obj_quat, region_points, min_num_points=3, region_type="box" +): + """ + check if object is in the region defined by the keypoints. Only min_num_points points need to be in the region to return True. + Keypoints include the points of the object's bounding box and the center of the object. + region can be a box or a cylinder or a sphere + TODO: support plane region + """ + from robocasa.models.fixtures import Fixture + + if isinstance(obj, MJCFObject) or isinstance(obj, Fixture): + obj_points = obj.get_bbox_points(trans=obj_pos, rot=obj_quat) + else: + radius = obj.horizontal_radius + obj_points = obj_pos + np.array( + [ + [radius, 0, 0], + [-radius, 0, 0], + [0, radius, 0], + [0, -radius, 0], + ] + ) + + # center points of object for each plane + obj_u = obj_points[1] - obj_points[0] + obj_v = obj_points[2] - obj_points[0] + obj_w = obj_points[3] - obj_points[0] + centers = [] + + # Front and back XY planes + center_xy_front = obj_points[0] + 0.5 * obj_u + 0.5 * obj_v + center_xy_back = center_xy_front + obj_w + centers.extend([center_xy_front, center_xy_back]) + + if obj_w is not None: + # Left and right XZ planes + center_xz_left = obj_points[0] + 0.5 * obj_u + 0.5 * obj_w + center_xz_right = center_xz_left + obj_v + centers.extend([center_xz_left, center_xz_right]) + + # Top and bottom YZ planes + center_yz_top = obj_points[0] + 0.5 * obj_v + 0.5 * obj_w + center_yz_bottom = center_yz_top + obj_u + centers.extend([center_yz_top, center_yz_bottom]) + + center_point = np.mean(obj_points, axis=0) + centers.append(center_point) + obj_points = np.concatenate([obj_points, centers]) + + # Erode the bounding box by pulling points 10% closer to the center + # Avoids false negatives when object is near the edge of the region + obj_points = obj_points * 0.8 + center_point * 0.2 + + if region_type == "box": + if len(region_points) == 4: + p0, px, py, pz = region_points + elif len(region_points) == 3: + p0, px, py = region_points + pz = None + else: + raise ValueError(f"Invalid number of region points: {len(region_points)}") + return obj_in_box_region(obj_points, p0, px, py, pz, min_num_points) + elif region_type == "cylinder": + p0, axis_vector, radius = region_points + return obj_in_cylinder_region( + obj_points, p0, axis_vector, radius, min_num_points + ) + elif region_type == "sphere": + p0, radius = region_points + return obj_in_sphere_region(obj_points, p0, radius, min_num_points) + + +def fixture_pairwise_dist(f1, f2): + """ + Gets the distance between two fixtures by finding the minimum distance between their exterior bounding box points + """ + f1_points = f1.get_ext_sites(all_points=True, relative=False) + f2_points = f2.get_ext_sites(all_points=True, relative=False) + + all_dists = [np.linalg.norm(p1 - p2) for p1 in f1_points for p2 in f2_points] + return np.min(all_dists) + + +def objs_intersect( + obj, + obj_pos, + obj_quat, + other_obj, + other_obj_pos, + other_obj_quat, +): + """ + check if two objects intersect + """ + from robocasa.models.fixtures import Fixture + + bbox_check = (isinstance(obj, MJCFObject) or isinstance(obj, Fixture)) and ( + isinstance(other_obj, MJCFObject) or isinstance(other_obj, Fixture) + ) + if bbox_check: + obj_points = obj.get_bbox_points(trans=obj_pos, rot=obj_quat) + other_obj_points = other_obj.get_bbox_points( + trans=other_obj_pos, rot=other_obj_quat + ) + + face_normals = [ + obj_points[1] - obj_points[0], + obj_points[2] - obj_points[0], + obj_points[3] - obj_points[0], + other_obj_points[1] - other_obj_points[0], + other_obj_points[2] - other_obj_points[0], + other_obj_points[3] - other_obj_points[0], + ] + + intersect = True + + # noramlize length of normals + for normal in face_normals: + normal = np.array(normal) / np.linalg.norm(normal) + + obj_projs = [np.dot(p, normal) for p in obj_points] + other_obj_projs = [np.dot(p, normal) for p in other_obj_points] + + # see if gap detected + if np.min(other_obj_projs) > np.max(obj_projs) or np.min( + obj_projs + ) > np.max(other_obj_projs): + intersect = False + break + else: + """ + old code from placement_samplers.py + """ + obj_x, obj_y, obj_z = obj_pos + other_obj_x, other_obj_y, other_obj_z = other_obj_pos + xy_collision = ( + np.linalg.norm((obj_x - other_obj_x, obj_y - other_obj_y)) + <= other_obj.horizontal_radius + obj.horizontal_radius + ) + if obj_z > other_obj_z: + z_collision = ( + obj_z - other_obj_z <= other_obj.top_offset[-1] - obj.bottom_offset[-1] + ) + else: + z_collision = ( + other_obj_z - obj_z <= obj.top_offset[-1] - other_obj.bottom_offset[-1] + ) + + if xy_collision and z_collision: + intersect = True + else: + intersect = False + + return intersect + + +def normalize_joint_value(raw, joint_min, joint_max): + """ + normalize raw value to be between 0 and 1 + """ + return (raw - joint_min) / (joint_max - joint_min) + + +def get_highest_spawn_region(env, receptacle): + """ + Get the highest spawn region of a receptacle. + """ + return max( + receptacle.spawns, + key=lambda x: env.sim.data.geom_xpos[env.sim.model.geom_name2id(x.get("name"))][ + 2 + ], + ) + + +def calculate_spawn_region(env, spawn): + """ + Calculates the corner points of the spawn region. + + Parameters: + env: The simulation/environment object. + spawn: The spawn geom. + + Returns: + For box: (p0, px, py, pz) + For cylinder: (p0, axis_vector, radius) + For sphere: (center, radius) + """ + # Get spawn parameters from the simulation. + spawn_name = spawn.get("name") + spawn_id = env.sim.model.geom_name2id(spawn_name) + + spawn_pos = env.sim.data.get_geom_xpos(spawn_name) + spawn_xmat = env.sim.data.get_geom_xmat(spawn_name) + spawn_size = env.sim.model.geom_size[spawn_id] + spawn_type = env.sim.model.geom_type[spawn_id] + assert spawn_type in [ + mj.mjtGeom.mjGEOM_BOX, + mj.mjtGeom.mjGEOM_CYLINDER, + mj.mjtGeom.mjGEOM_SPHERE, + ], "Spawn region only supports box, cylinder and sphere geometries." + + if spawn_type == mj.mjtGeom.mjGEOM_BOX: + # Box geometry - return corners as before + p0 = ( + spawn_pos + - spawn_size[0] * spawn_xmat[:, 0] + - spawn_size[1] * spawn_xmat[:, 1] + - spawn_size[2] * spawn_xmat[:, 2] + ) + px = p0 + 2 * spawn_size[0] * spawn_xmat[:, 0] + py = p0 + 2 * spawn_size[1] * spawn_xmat[:, 1] + pz = p0 + 2 * spawn_size[2] * spawn_xmat[:, 2] + return p0, px, py, pz + elif spawn_type == mj.mjtGeom.mjGEOM_CYLINDER: + # Cylinder geometry - return (base_center, axis_vector, radius) + height = spawn_size[1] * 2 + radius = spawn_size[0] + axis_vector = height * spawn_xmat[:, 2] + return spawn_pos, axis_vector, radius + elif spawn_type == mj.mjtGeom.mjGEOM_SPHERE: + # Sphere geometry - return (center, radius) + radius = spawn_size[0] + return spawn_pos, radius + else: + raise ValueError(f"Invalid spawn type: {spawn_type}") + + +def check_obj_in_receptacle( + env, obj_name, receptacle_name, th=None, spawn_check=True, spawn_regions=None +): + """ + check if object is in receptacle object based on spawn regions or threshold + """ + obj = env.objects[obj_name] + recep = env.objects[receptacle_name] + obj_pos = np.array(env.sim.data.body_xpos[env.obj_body_id[obj_name]]) + obj_quat = T.convert_quat( + np.array(env.sim.data.body_xquat[env.obj_body_id[obj_name]]), to="xyzw" + ) + recep_pos = np.array(env.sim.data.body_xpos[env.obj_body_id[receptacle_name]]) + + if len(recep.spawns) > 0 and spawn_check: + if spawn_regions is None: + spawn_regions = recep.spawns + + for spawn in spawn_regions: + region_points = calculate_spawn_region(env, spawn) + + if obj_in_region_with_keypoints( + obj, + obj_pos, + obj_quat, + region_points, + min_num_points=2, + region_type=spawn.get("type"), + ): + return True + return False + else: + if th is None: + th = recep.horizontal_radius * 0.7 + obj_in_recep = ( + env.check_contact(obj, recep) + and np.linalg.norm(obj_pos[:2] - recep_pos[:2]) < th + ) + return obj_in_recep + + +def check_obj_fixture_contact(env, obj_name, fixture_name): + """ + check if object is in contact with fixture + """ + obj = env.objects[obj_name] + fixture = env.get_fixture(fixture_name) + return env.check_contact(obj, fixture) + + +def gripper_obj_far(env, obj_name="obj", th=0.25): + """ + check if gripper is far from object based on distance defined by threshold + """ + return gripper_obj_far_by_side( + env=env, obj_name=obj_name, gripper_side="right", th=th + ) + + +def any_gripper_obj_far(env, obj_name="obj", th=0.25): + """ + check if all grippers are far from object based on distance defined by threshold + """ + left_is_far = gripper_obj_far_by_side( + env=env, obj_name=obj_name, gripper_side="left", th=th + ) + right_is_far = gripper_obj_far_by_side( + env=env, obj_name=obj_name, gripper_side="right", th=th + ) + return left_is_far and right_is_far + + +def gripper_obj_far_by_side(env, obj_name: str, gripper_side: str, th: float = 0.25): + """ + check if gripper is far from object based on distance defined by threshold + """ + obj_pos = env.sim.data.body_xpos[env.obj_body_id[obj_name]] + gripper_site_pos = env.sim.data.site_xpos[env.robots[0].eef_site_id[gripper_side]] + return np.linalg.norm(gripper_site_pos - obj_pos) > th + + +def obj_cos(env, obj_name="obj", ref=(0, 0, 1)): + def cos(u, v): + return np.dot(u, v) / max(np.linalg.norm(u) * np.linalg.norm(v), 1e-10) + + obj_id = env.obj_body_id[obj_name] + obj_quat = T.convert_quat(np.array(env.sim.data.body_xquat[obj_id]), to="xyzw") + obj_mat = T.quat2mat(obj_quat) + + return cos(obj_mat[:, 2], np.array(ref)) + + +def check_obj_upright(env, obj_name, threshold=0.8): + """ + Check if an object is upright based on its z-axis orientation + """ + obj_id = env.obj_body_id[obj_name] + obj_quat = T.convert_quat(np.array(env.sim.data.body_xquat[obj_id]), to="xyzw") + obj_mat = T.quat2mat(obj_quat) + return obj_mat[:, 2][2] > threshold + + +def obj_in_box_region(obj_points, p0, px, py, pz, min_num_points): + """ + Check if enough object points are inside a box region defined by corner points. + + Args: + obj_points (np.array): Points to check + p0 (np.array): Origin corner point + px (np.array): X-axis corner point + py (np.array): Y-axis corner point + pz (np.array): Z-axis corner point (optional) + min_num_points (int): Minimum number of points that need to be in region + + Returns: + bool: True if enough points are inside the region + """ + u = px - p0 + v = py - p0 + w = pz - p0 if pz is not None else None + + num_points_in_region = 0 + for point in obj_points: + check1 = np.dot(u, p0) <= np.dot(u, point) <= np.dot(u, px) + check2 = np.dot(v, p0) <= np.dot(v, point) <= np.dot(v, py) + + if w is not None: + check3 = np.dot(w, p0) <= np.dot(w, point) <= np.dot(w, pz) + if check1 and check2 and check3: + num_points_in_region += 1 + else: + if check1 and check2: + num_points_in_region += 1 + + return num_points_in_region >= min_num_points + + +def obj_in_cylinder_region(obj_points, p0, axis_vector, radius, min_num_points): + """ + Check if enough object points are inside a cylinder region defined by base point, height vector and radius + + Args: + obj_points (np.array): Points to check + p0 (np.array): Base center point of cylinder + axis_vector (np.array): Vector from base center to top center, defines cylinder axis and height + radius (float): Radius of cylinder + min_num_points (int): Minimum number of points that need to be in region + """ + num_points_in_region = 0 + # Normalize height vector to get axis direction + axis = axis_vector / np.linalg.norm(axis_vector) + height_magnitude = np.linalg.norm(axis_vector) + + for point in obj_points: + # Project point onto cylinder axis + point_rel = point - p0 + height_proj = np.dot(point_rel, axis) + + # Check height bounds + if 0 <= height_proj <= height_magnitude: + # Check radius by removing height component + radius_vec = point_rel - height_proj * axis + if np.linalg.norm(radius_vec) <= radius: + num_points_in_region += 1 + + return num_points_in_region >= min_num_points + + +def obj_in_sphere_region(obj_points, p0, radius, min_num_points): + """ + Check if enough object points are inside a sphere region defined by center and radius + + Args: + obj_points (np.array): Points to check + p0 (np.array): Center point of sphere + radius (float): Radius of sphere + min_num_points (int): Minimum number of points that need to be in region + """ + num_points_in_region = 0 + for point in obj_points: + if np.linalg.norm(point - p0) <= radius: + num_points_in_region += 1 + + return num_points_in_region >= min_num_points diff --git a/third_party/robocasa/robocasa/utils/placement_samplers.py b/third_party/robocasa/robocasa/utils/placement_samplers.py new file mode 100644 index 0000000000000000000000000000000000000000..82be73d55e691f84b3d8cd5eee27596f43dc85e7 --- /dev/null +++ b/third_party/robocasa/robocasa/utils/placement_samplers.py @@ -0,0 +1,738 @@ +import collections +from copy import copy + +import numpy as np + +from robocasa.models.objects.objects import MJCFObject +from robosuite.models.objects import MujocoObject +from robosuite.utils import RandomizationError +from robosuite.utils.transform_utils import ( + convert_quat, + euler2mat, + mat2quat, + quat_multiply, + rotate_2d_point, +) + +from robocasa.utils.object_utils import ( + obj_in_region, + objs_intersect, + obj_in_region_with_keypoints, +) + + +class ObjectPositionSampler: + """ + Base class of object placement sampler. + + Args: + name (str): Name of this sampler. + + mujoco_objects (None or MujocoObject or list of MujocoObject): single model or list of MJCF object models + + ensure_object_boundary_in_range (bool): If True, will ensure that the object is enclosed within a given boundary + (should be implemented by subclass) + + ensure_valid_placement (bool): If True, will check for correct (valid) object placements + + reference_pos (3-array): global (x,y,z) position relative to which sampling will occur + + z_offset (float): Add a small z-offset to placements. This is useful for fixed objects + that do not move (i.e. no free joint) to place them above the table. + """ + + def __init__( + self, + name, + mujoco_objects=None, + ensure_object_boundary_in_range=True, + ensure_valid_placement=True, + reference_pos=(0, 0, 0), + reference_rot=0, + z_offset=0.0, + rng=None, + ): + if rng is None: + rng = np.random.default_rng() + self.rng = rng + + # Setup attributes + self.name = name + if mujoco_objects is None: + self.mujoco_objects = [] + else: + # Shallow copy the list so we don't modify the inputted list but still keep the object references + self.mujoco_objects = ( + [mujoco_objects] + if isinstance(mujoco_objects, MujocoObject) + else copy(mujoco_objects) + ) + self.ensure_object_boundary_in_range = ensure_object_boundary_in_range + self.ensure_valid_placement = ensure_valid_placement + self.reference_pos = reference_pos + self.reference_rot = reference_rot + self.z_offset = z_offset + + def add_objects(self, mujoco_objects): + """ + Add additional objects to this sampler. Checks to make sure there's no identical objects already stored. + + Args: + mujoco_objects (MujocoObject or list of MujocoObject): single model or list of MJCF object models + """ + mujoco_objects = ( + [mujoco_objects] + if isinstance(mujoco_objects, MujocoObject) + else mujoco_objects + ) + for obj in mujoco_objects: + assert ( + obj not in self.mujoco_objects + ), "Object '{}' already in sampler!".format(obj.name) + self.mujoco_objects.append(obj) + + def reset(self): + """ + Resets this sampler. Removes all mujoco objects from this sampler. + """ + self.mujoco_objects = [] + + def sample(self, fixtures=None, reference=None, on_top=True): + """ + Uniformly sample on a surface (not necessarily table surface). + + Args: + fixtures (dict): dictionary of current object placements in the scene as well as any other relevant + obstacles that should not be in contact with newly sampled objects. Used to make sure newly + generated placements are valid. Should be object names mapped to (pos, quat, MujocoObject) + + reference (str or 3-tuple or None): if provided, sample relative placement. Can either be a string, which + corresponds to an existing object found in @fixtures, or a direct (x,y,z) value. If None, will sample + relative to this sampler's `'reference_pos'` value. + + on_top (bool): if True, sample placement on top of the reference object. + + Return: + dict: dictionary of all object placements, mapping object_names to (pos, quat, obj), including the + placements specified in @fixtures. Note quat is in (w,x,y,z) form + """ + raise NotImplementedError + + @property + def sides_combinations(self): + return { + "left": ["front_left", "back_left"], + "right": ["front_right", "back_right"], + "front": ["front_left", "front_right"], + "back": ["back_left", "back_right"], + "all": ["front_left", "front_right", "back_left", "back_right"], + } + + @property + def valid_sides(self): + return set( + [ + "left", + "right", + "front", + "back", + "all", + "front_left", + "front_right", + "back_left", + "back_right", + ] + ) + + +class UniformRandomSampler(ObjectPositionSampler): + """ + Places all objects within the table uniformly random. + + Args: + name (str): Name of this sampler. + + mujoco_objects (None or MujocoObject or list of MujocoObject): single model or list of MJCF object models + + x_range (2-array of float): Specify the (min, max) relative x_range used to uniformly place objects + + y_range (2-array of float): Specify the (min, max) relative y_range used to uniformly place objects + + rotation (None or float or Iterable): + :`None`: Add uniform random random rotation + :`Iterable (a,b)`: Uniformly randomize rotation angle between a and b (in radians) + :`value`: Add fixed angle rotation + + rotation_axis (str): Can be 'x', 'y', or 'z'. Axis about which to apply the requested rotation + + ensure_object_boundary_in_range (bool): + :`True`: The center of object is at position: + [uniform(min x_range + radius, max x_range - radius)], [uniform(min x_range + radius, max x_range - radius)] + :`False`: + [uniform(min x_range, max x_range)], [uniform(min x_range, max x_range)] + + ensure_valid_placement (bool): If True, will check for correct (valid) object placements + + reference_pos (3-array): global (x,y,z) position relative to which sampling will occur + + z_offset (float): Add a small z-offset to placements. This is useful for fixed objects + that do not move (i.e. no free joint) to place them above the table. + + num_attempts (int): Number of attempts to sample an object before giving up. + """ + + def __init__( + self, + name, + mujoco_objects=None, + x_range=(0, 0), + y_range=(0, 0), + rotation=None, + rotation_axis="z", + ensure_object_boundary_in_range=True, + ensure_valid_placement=True, + ensure_object_in_ref_region=False, + ensure_object_out_of_ref_region=False, + reference_pos=(0, 0, 0), + reference_rot=0, + z_offset=0.0, + rng=None, + side="all", + num_attempts=5000, + ): + """Uniformly sample the position of the object. + + Args: + ensure_object_in_ref_region (bool, optional): + If True, we need to ensure the object be placed within the reference region. Not need to be fully in the region, but at least the center of the object. + ensure_object_out_of_ref_region (bool, optional): + If True, we need to ensure the object be placed outside the reference region. Need to be fully outside the region. + """ + self.x_range = x_range + self.y_range = y_range + self.rotation = rotation + self.rotation_axis = rotation_axis + self.num_attempts = num_attempts + if side not in self.valid_sides: + raise ValueError( + "Invalid value for side, must be one of:", self.valid_sides + ) + + super().__init__( + name=name, + mujoco_objects=mujoco_objects, + ensure_object_boundary_in_range=ensure_object_boundary_in_range, + ensure_valid_placement=ensure_valid_placement, + reference_pos=reference_pos, + reference_rot=reference_rot, + z_offset=z_offset, + rng=rng, + ) + self.ensure_object_in_ref_region = ensure_object_in_ref_region + self.ensure_object_out_of_ref_region = ensure_object_out_of_ref_region + + def _sample_x(self): + """ + Samples the x location for a given object + + Returns: + float: sampled x position + """ + minimum, maximum = self.x_range + return self.rng.uniform(high=maximum, low=minimum) + + def _sample_y(self): + """ + Samples the y location for a given object + + Returns: + float: sampled y position + """ + minimum, maximum = self.y_range + return self.rng.uniform(high=maximum, low=minimum) + + def _sample_quat(self): + """ + Samples the orientation for a given object + + Returns: + np.array: sampled object quaternion in (w,x,y,z) form + + Raises: + ValueError: [Invalid rotation axis] + """ + if self.rotation is None: + rot_angle = self.rng.uniform(high=2 * np.pi, low=0) + elif isinstance(self.rotation, collections.abc.Iterable): + if isinstance(self.rotation[0], collections.abc.Iterable): + rotation = self.rng.choice(self.rotation) + else: + rotation = self.rotation + rot_angle = self.rng.uniform(high=max(rotation), low=min(rotation)) + else: + rot_angle = self.rotation + + # Return angle based on axis requested + if self.rotation_axis == "x": + return np.array([np.cos(rot_angle / 2), np.sin(rot_angle / 2), 0, 0]) + elif self.rotation_axis == "y": + return np.array([np.cos(rot_angle / 2), 0, np.sin(rot_angle / 2), 0]) + elif self.rotation_axis == "z": + return np.array([np.cos(rot_angle / 2), 0, 0, np.sin(rot_angle / 2)]) + else: + # Invalid axis specified, raise error + raise ValueError( + "Invalid rotation axis specified. Must be 'x', 'y', or 'z'. Got: {}".format( + self.rotation_axis + ) + ) + + def sample( + self, placed_objects=None, reference=None, neg_reference=None, on_top=True + ): + """ + Uniformly sample relative to this sampler's reference_pos or @reference (if specified). + + Args: + placed_objects (dict): dictionary of current object placements in the scene as well as any other relevant + obstacles that should not be in contact with newly sampled objects. Used to make sure newly + generated placements are valid. Should be object names mapped to (pos, quat, MujocoObject) + + reference (str, tuple, or None, optional): Defines the reference for relative placement. It can be an object + name found in `fixtures`, a tuple specifying an object and its site ID, or a direct (x, y, z) coordinate. + If not provided, placement is sampled relative to this sampler's `reference_pos`. + + on_top (bool): if True, sample placement on top of the reference object. This corresponds to a sampled + z-offset of the current sampled object's bottom_offset + the reference object's top_offset + (if specified) + + Return: + dict: dictionary of all object placements, mapping object_names to (pos, quat, obj), including the + placements specified in @fixtures. Note quat is in (w,x,y,z) form + + Raises: + RandomizationError: [Cannot place all objects] + AssertionError: [Reference object name does not exist, invalid inputs] + """ + # Standardize inputs + placed_objects = {} if placed_objects is None else copy(placed_objects) + spawn_ref_obj = None + + if reference is None: + base_offset = self.reference_pos + elif type(reference) is str: + assert ( + reference in placed_objects + ), "Invalid reference received. Current options are: {}, requested: {}".format( + placed_objects.keys(), reference + ) + ref_pos, _, ref_obj = placed_objects[reference] + base_offset = np.array(ref_pos) + if on_top: + base_offset += np.array((0, 0, ref_obj.top_offset[-1])) + # Handle shelf object references + # If the reference is provided as a tuple (object_key: str, spawn_id: int), + # then we treat it as a reference to a specific shelf level + elif type(reference) is tuple and len(reference) == 2: + (reference, spawn_id) = reference + assert ( + reference in placed_objects + ), "Invalid reference received. Current options are: {}, requested: {}".format( + placed_objects.keys(), reference + ) + ref_pos, _, ref_obj = placed_objects[reference] + assert isinstance( + ref_obj, MJCFObject + ), "Invalid reference received. Should be of type MJCFObject" + if spawn_id == -1: + spawn_id, site = ref_obj.get_random_spawn( + self.rng, exclude_disabled=True + ) + else: + site = ref_obj.spawns[spawn_id] + ref_obj.set_spawn_active(spawn_id, False) + + base_offset = np.array(ref_pos) + base_offset += ref_obj.get_spawn_bottom_offset(site) + spawn_ref_obj = ref_obj + else: + base_offset = np.array(reference) + assert ( + base_offset.shape[0] == 3 + ), "Invalid reference received. Should be (x,y,z) 3-tuple, but got: {}".format( + base_offset + ) + + # Sample pos and quat for all objects assigned to this sampler + for obj in self.mujoco_objects: + # First make sure the currently sampled object hasn't already been sampled + assert ( + obj.name not in placed_objects + ), "Object '{}' has already been sampled!".format(obj.name) + + success = False + + # get reference rotation + ref_quat = convert_quat( + mat2quat(euler2mat([0, 0, self.reference_rot])), to="wxyz" + ) + + ### get boundary points ### + region_points = np.array( + [ + [self.x_range[0], self.y_range[0], 0], + [self.x_range[1], self.y_range[0], 0], + [self.x_range[0], self.y_range[1], 0], + ] + ) + for i in range(len(region_points)): + region_points[i][0:2] = rotate_2d_point( + region_points[i][0:2], rot=self.reference_rot + ) + region_points += base_offset + + for i in range(self.num_attempts): + # sample object coordinates + relative_x = self._sample_x() + relative_y = self._sample_y() + + # apply rotation + object_x, object_y = rotate_2d_point( + [relative_x, relative_y], rot=self.reference_rot + ) + + object_x = object_x + base_offset[0] + object_y = object_y + base_offset[1] + object_z = self.z_offset + base_offset[2] + if on_top: + object_z -= obj.bottom_offset[-1] + + # random rotation + quat = self._sample_quat() + # multiply this quat by the object's initial rotation if it has the attribute specified + if hasattr(obj, "init_quat"): + quat = quat_multiply(quat, obj.init_quat) + quat = convert_quat( + quat_multiply( + convert_quat(ref_quat, to="xyzw"), + convert_quat(quat, to="xyzw"), + ), + to="wxyz", + ) + + location_valid = True + + # ensure object placed fully in region + if self.ensure_object_boundary_in_range and not obj_in_region( + obj, + obj_pos=[object_x, object_y, object_z], + obj_quat=convert_quat(quat, to="xyzw"), + p0=region_points[0], + px=region_points[1], + py=region_points[2], + ): + location_valid = False + continue + + # objects cannot overlap + if self.ensure_valid_placement: + for (x, y, z), other_quat, other_obj in placed_objects.values(): + if spawn_ref_obj and other_obj == spawn_ref_obj: + if not objs_intersect( + obj=obj, + obj_pos=[object_x, object_y, object_z], + obj_quat=convert_quat(quat, to="xyzw"), + other_obj=other_obj, + other_obj_pos=[x, y, z], + other_obj_quat=convert_quat(other_quat, to="xyzw"), + ): + location_valid = False + break + else: + if objs_intersect( + obj=obj, + obj_pos=[object_x, object_y, object_z], + obj_quat=convert_quat(quat, to="xyzw"), + other_obj=other_obj, + other_obj_pos=[x, y, z], + other_obj_quat=convert_quat(other_quat, to="xyzw"), + ): + location_valid = False + break + + # ensure at least one point of the object should be in the region + if self.ensure_object_in_ref_region and reference is not None: + _ref_pos, _ref_quat, _ref_obj = placed_objects[reference] + if not obj_in_region_with_keypoints( + obj=obj, + obj_pos=[object_x, object_y, object_z], + obj_quat=convert_quat(quat, to="xyzw"), + region_points=_ref_obj.get_bbox_points( + trans=_ref_pos, rot=_ref_quat + )[:3], + min_num_points=3, + ): + location_valid = False + break + + if self.ensure_object_out_of_ref_region and neg_reference is not None: + for nf in neg_reference: + assert ( + nf in placed_objects + ), "Invalid negative reference received. Current options are: {}, requested: {}".format( + placed_objects.keys(), nf + ) + _ref_pos, _ref_quat, _ref_obj = placed_objects[nf] + if obj_in_region( + obj=obj, + obj_pos=[object_x, object_y, object_z], + obj_quat=convert_quat(quat, to="xyzw"), + p0=_ref_obj.get_bbox_points(trans=_ref_pos, rot=_ref_quat)[ + 0 + ], + px=_ref_obj.get_bbox_points(trans=_ref_pos, rot=_ref_quat)[ + 1 + ], + py=_ref_obj.get_bbox_points(trans=_ref_pos, rot=_ref_quat)[ + 2 + ], + ): + location_valid = False + break + + if location_valid: + # location is valid, put the object down + pos = (object_x, object_y, object_z) + placed_objects[obj.name] = (pos, quat, obj) + success = True + break + + if not success: + raise RandomizationError(f"Cannot place object: {obj.name}") + + return placed_objects + + +class SequentialCompositeSampler(ObjectPositionSampler): + """ + Samples position for each object sequentially. Allows chaining + multiple placement initializers together - so that object locations can + be sampled on top of other objects or relative to other object placements. + + Args: + name (str): Name of this sampler. + """ + + def __init__(self, name, rng=None): + # Samplers / args will be filled in later + self.samplers = collections.OrderedDict() + self.sample_args = collections.OrderedDict() + self.sampler_optional = collections.OrderedDict() + + super().__init__(name=name, rng=rng) + + def append_sampler(self, sampler, sample_args=None, optional=False): + """ + Adds a new placement initializer with corresponding @sampler and arguments + + Args: + sampler (ObjectPositionSampler): sampler to add + sample_args (None or dict): If specified, should be additional arguments to pass to @sampler's sample() + call. Should map corresponding sampler's arguments to values (excluding @fixtures argument) + optional (bool): If True, do not raise an error if the sampler fails to place all objects. This parameter + is for handling optional clutter generation. When True, clutter objects that can't be placed due to + space constraints are silently skipped. + + Raises: + AssertionError: [Object name in samplers] + """ + # Verify that all added mujoco objects haven't already been added, and add to this sampler's objects dict + for obj in sampler.mujoco_objects: + assert ( + obj not in self.mujoco_objects + ), f"Object '{obj.name}' already has sampler associated with it!" + self.mujoco_objects.append(obj) + self.samplers[sampler.name] = sampler + self.sample_args[sampler.name] = sample_args + self.sampler_optional[sampler.name] = optional + + def hide(self, mujoco_objects): + """ + Helper method to remove an object from the workspace. + + Args: + mujoco_objects (MujocoObject or list of MujocoObject): Object(s) to hide + """ + sampler = UniformRandomSampler( + name="HideSampler", + mujoco_objects=mujoco_objects, + x_range=[-10, -20], + y_range=[-10, -20], + rotation=[0, 0], + rotation_axis="z", + z_offset=10, + ensure_object_boundary_in_range=False, + ensure_valid_placement=False, + rng=self.rng, + ) + self.append_sampler(sampler=sampler) + + def add_objects(self, mujoco_objects): + """ + Override super method to make sure user doesn't call this (all objects should implicitly belong to sub-samplers) + """ + raise AttributeError( + "add_objects() should not be called for SequentialCompsiteSamplers!" + ) + + def add_objects_to_sampler(self, sampler_name, mujoco_objects): + """ + Adds specified @mujoco_objects to sub-sampler with specified @sampler_name. + + Args: + sampler_name (str): Existing sub-sampler name + mujoco_objects (MujocoObject or list of MujocoObject): Object(s) to add + """ + # First verify that all mujoco objects haven't already been added, and add to this sampler's objects dict + mujoco_objects = ( + [mujoco_objects] + if isinstance(mujoco_objects, MujocoObject) + else mujoco_objects + ) + for obj in mujoco_objects: + assert ( + obj not in self.mujoco_objects + ), f"Object '{obj.name}' already has sampler associated with it!" + self.mujoco_objects.append(obj) + # Make sure sampler_name exists + assert sampler_name in self.samplers.keys(), ( + "Invalid sub-sampler specified, valid options are: {}, " + "requested: {}".format(self.samplers.keys(), sampler_name) + ) + # Add the mujoco objects to the requested sub-sampler + self.samplers[sampler_name].add_objects(mujoco_objects) + + def reset(self): + """ + Resets this sampler. In addition to base method, iterates over all sub-samplers and resets them + """ + super().reset() + for sampler in self.samplers.values(): + sampler.reset() + + def sample(self, placed_objects=None, reference=None, on_top=True): + """ + Sample from each placement initializer sequentially, in the order + that they were appended. + + Args: + placed_objects (dict): dictionary of current object placements in the scene as well as any other relevant + obstacles that should not be in contact with newly sampled objects. Used to make sure newly + generated placements are valid. Should be object names mapped to (pos, quat, MujocoObject) + + reference (str or 3-tuple or None): if provided, sample relative placement. This will override each + sampler's @reference argument if not already specified. Can either be a string, which + corresponds to an existing object found in @fixtures, or a direct (x,y,z) value. If None, will sample + relative to this sampler's `'reference_pos'` value. + + on_top (bool): if True, sample placement on top of the reference object. This will override each + sampler's @on_top argument if not already specified. This corresponds to a sampled + z-offset of the current sampled object's bottom_offset + the reference object's top_offset + (if specified) + + Return: + dict: dictionary of all object placements, mapping object_names to (pos, quat, obj), including the + placements specified in @fixtures. Note quat is in (w,x,y,z) form + + Raises: + RandomizationError: [Cannot place all objects] + """ + # Standardize inputs + placed_objects = {} if placed_objects is None else copy(placed_objects) + + # Iterate through all samplers to sample + for sampler, s_args in zip(self.samplers.values(), self.sample_args.values()): + # Pre-process sampler args + if s_args is None: + s_args = {} + for arg_name, arg in zip(("reference", "on_top"), (reference, on_top)): + if arg_name not in s_args: + s_args[arg_name] = arg + # Run sampler + try: + new_placements = sampler.sample( + placed_objects=placed_objects or s_args.pop("placed_objects", {}), + **s_args, + ) + except RandomizationError: + if self.sampler_optional[sampler.name]: + continue + else: + raise + # Update placements + placed_objects.update(new_placements) + + # only return placements for newly placed objects + sampled_obj_names = [ + obj.name + for sampler in self.samplers.values() + for obj in sampler.mujoco_objects + ] + return {k: v for (k, v) in placed_objects.items() if k in sampled_obj_names} + + +class MultiRegionSampler(ObjectPositionSampler): + def __init__( + self, + name, + regions, + side="all", + mujoco_objects=None, + rotation=None, + rotation_axis="z", + ensure_object_boundary_in_range=True, + ensure_valid_placement=True, + ensure_object_in_ref_region=False, + rng=None, + z_offset=0.0, + ): + if len(regions) != 4: + raise ValueError( + "Exactly four sites (one for each quadrant) must be provided." + ) + if side not in self.valid_sides: + raise ValueError( + "Invalid value for side, must be one of:", self.valid_sides + ) + + # initialize sides and regions + if side in self.sides_combinations: + self.sides = self.sides_combinations[side] + else: + self.sides = [side] + self.regions = regions + + # create a list of uniform samplers (one for each site) + self.samplers = list() + for s in self.sides: + site = self.regions[s] + sampler = UniformRandomSampler( + name=name, + mujoco_objects=mujoco_objects, + reference_pos=site["pos"], + x_range=site["x_range"], + y_range=site["y_range"], + rotation=rotation, + rotation_axis=rotation_axis, + ensure_object_boundary_in_range=ensure_object_boundary_in_range, + ensure_valid_placement=ensure_valid_placement, + ensure_object_in_ref_region=ensure_object_in_ref_region, + z_offset=z_offset, + rng=rng, + ) + self.samplers.append(sampler) + + def sample(self, fixtures=None, reference=None, on_top=True): + # randomly picks a sampler and calls its sample function + sampler = self.rng.choice(self.samplers) + return sampler.sample(fixtures=fixtures, reference=reference, on_top=on_top) diff --git a/third_party/robocasa/robocasa/utils/texture_swap.py b/third_party/robocasa/robocasa/utils/texture_swap.py new file mode 100644 index 0000000000000000000000000000000000000000..420e6f1264340d6c819465050c0a933c4db05304 --- /dev/null +++ b/third_party/robocasa/robocasa/utils/texture_swap.py @@ -0,0 +1,676 @@ +import inspect +import os +import random +from copy import deepcopy +from pathlib import Path + +import numpy as np +from lxml import etree as ET +from robosuite.utils.mjcf_utils import find_elements + +import robocasa + +TEXTURES_DIR = ( + Path(inspect.getfile(robocasa)).parent / "models" / "assets" / "generative_textures" +) + +CABINET_TEX_NAMES = [ + "flat copy 26.png", + "196415a6-3c0f-4a1f-a644-fc54a6801223.png", + "2a310e7f-8005-4dba-8dea-edb1484e1e28.png", + "flat copy 37.png", + "1fb8c016-b655-48ab-ad53-d6238a745065.png", + "f80067c5-9967-4607-880f-1c4002d400cb.png", + "00846c84-f900-4bdd-897f-3928e7d87dce.png", + "flat copy 38.png", + "54c4d59e-c0b1-4608-a953-568e9ae13409.png", + "flat copy 2.png", + "flat copy 23.png", + "flat copy 16.png", + "251695ed-d413-48fe-817e-c3e02b3ee117.png", + "18338c06-57fc-4882-ad44-b5f3b3846806.png", + "flat copy 40.png", + "36a1e6cb-98a1-4ada-a14e-8c04f135c5ee.png", + "f06bca10-a7ce-4a4a-92f6-973d7400fe8a.png", + "flat copy 41.png", + "397c17e0-e91b-4fa6-98d9-97e6d2f009ed.png", + "532a9660-8c7a-488b-8930-9134a9479afa.png", + "flat copy 33.png", + "d0299fe2-026b-4727-85e1-cb5de303e315.png", + "68a933bc-df0c-4891-bd41-2c05e4fde504.png", + "6698bb80-52f7-4e5b-ad6a-4a8122504f9a.png", + "99f0113d-8cb4-40b6-9670-b4be4c1fc475.png", + "flat copy 32.png", + "flat copy 34.png", + "c1ad279c-9093-469e-aa20-b73af0fc8db4.png", + "518ddc39-55c2-4b18-8bf6-e9c4f0806760.png", + "flat copy 8.png", + "860cab10-089c-4d99-ae89-3e4f87df5d9c.png", + "f29d41e9-d285-47e4-ad29-f04423533802.png", + "flat copy 13.png", + "flat copy 12.png", + "e6420ee4-14f0-404f-9cd7-abc9a69da621.png", + "flat copy 4.png", + "de7f86d5-56c9-4331-a9aa-655687dc354b.png", + "flat copy 35.png", + "flat.png", + "b6abcb20-8b90-42d3-9175-ba6b4d53a7a9.png", + "d29a6530-28d6-4dbe-bce5-9014d613ae5e.png", + "992f49b2-3f7c-4c54-a4d6-75af4693353b.png", + "flat copy 27.png", + "fd195b15-b98c-47c9-b608-de4157f6ceba.png", + "flat copy 10.png", + "flat copy 15.png", + "af993127-4ec6-4fa3-9a27-018af985a4a0.png", + "8de5fd51-b7b5-4014-a892-f0498c35fec2.png", + "flat copy 3.png", + "flat copy 11.png", + "flat copy 30.png", + "edc5b189-60a3-4aa0-a68d-cc35009f3648.png", + "flat copy 20.png", + "flat copy 19.png", + "9fe8882d-3aa9-4d2b-8de3-d9d220ea526c.png", + "flat copy 7.png", + "flat copy 46.png", + "flat copy 9.png", + "230e3f37-02d7-4be9-b6a8-1e4fb3acd368.png", + "flat copy 45.png", + "7f426b18-12ee-492b-9c69-dfa8ccbc42cc.png", + "flat copy 49.png", + "flat copy 22.png", + "7fe6e2dc-615f-432e-92d4-0a4f17a9ac49.png", + "flat copy 47.png", + "flat copy 42.png", + "34c9cf7b-5b5d-4c81-bb95-6d5743d25a18.png", + "aae9ec57-7df1-4af7-8e40-62962b90cce4.png", + "flat copy 36.png", + "flat copy 25.png", + "5a34b72d-3b7e-4a9a-9a0f-f73f2230fe28.png", + "e2e0160d-9809-48d2-b018-416ee0254fc0.png", + "a6bb714e-0f35-46d6-b7e8-3c18232a4801.png", + "a86a130e-04a3-44b0-99b7-44ce0a63cc2b.png", + "01f783e0-38de-497d-8ebe-c8d8a47e520a.png", + "flat copy 44.png", + "e0e2d63e-900b-4ecb-8df9-28115a58c3a2.png", + "flat copy 50.png", + "flat copy 5.png", + "flat copy 18.png", + "1aac54cf-8bf3-428c-93cd-1d3c258ff6b4.png", + "flat copy 14.png", + "11717454-440d-4b32-85c3-bf0013c66c61.png", + "67d50012-cba6-4525-8e00-b71124861f7e.png", + "25436e21-3140-4875-89a9-d14c5ce20f31.png", + "e4a28073-2252-4603-8c4b-75527a8c5ae9.png", + "flat copy 17.png", + "flat copy 48.png", + "flat copy 6.png", + "28d31de4-53f8-434a-ac57-4d5d27f5ab2f.png", + "flat copy.png", + "flat copy 39.png", + "flat copy 43.png", + "flat copy 24.png", + "6a13b80d-83c7-4fe1-8412-4fc07eefaa35.png", + "43a60b06-97b9-4119-b416-c7fc6783aa81.png", + "flat copy 21.png", + "flat copy 28.png", + "flat copy 31.png", + "flat copy 29.png", +] + +COUNTER_TOP_TEX_NAMES = [ + "5065776e-1fbc-4a70-a786-9a2ec6ee5aa0.png", + "e7f151aa-2354-48d0-94e8-071462f16ca7.png", + "b6618923-8455-44c3-8ae6-b766f34267cc.png", + "71d72043-3d97-4ea6-82f0-3ccbb53e0534.png", + "deb1e565-5c29-4285-aef8-f904c2b41dfb.png", + "ecf23b20-3db2-476a-bc06-442754ba5e76.png", + "39be4639-f28b-4bfa-8c1e-4b37e40395be.png", + "8bafdd4c-a44c-4bc0-8978-e7bc0abcedb4.png", + "3b958a28-0807-484a-92e7-f17b4c6dcbeb.png", + "ecd3c3fb-c4f2-4021-86d8-665e92b2735e.png", + "014ac251-0435-41c2-9dee-c664ee268327.png", + "0171bbba-6293-4117-b0ad-bc4b98d1c20e.png", + "0bd64a61-e098-4d06-ba3f-0a12269d3584.png", + "d5db5c5c-779b-4de0-ac66-31856239d488.png", + "9c47a3ac-2e56-47c1-86d4-006f98e21987.png", + "133b4eaf-bb93-4655-844c-a02278dfc032.png", + "58bcfa8c-6e11-494f-8fc5-d5a32ac7b3de.png", + "276de88a-374b-4dde-ac45-c52d651044b3.png", + "f52f1aaa-c061-42c0-8bdd-d2edb4af8736.png", + "1ccd1303-2e23-44c4-bb21-0dd474b0d899.png", + "761d55a2-5858-4d02-ab13-0bb272a67eed.png", + "c9d714cd-b00b-4d96-b6a6-cdc9e01c1b71.png", + "06da7e0e-c12c-4da7-a56b-9a3c82d87809.png", + "e5d1c208-34ad-49a7-8151-c0d55ecff952.png", + "9ccbd07a-887c-48c8-a806-0fac93606bb0.png", + "3d48ef42-02d9-41ed-bef6-f5c0dd47cdfa.png", + "9e1fd142-1d1c-4a82-a961-681db31b343f.png", + "5259cbe7-d956-4a0a-99d1-d7c7d391488f.png", + "94bdb3c5-faa2-4274-9337-ca5b9fabce88.png", + "e572f3d8-9ef2-4cd2-83c1-8acb766dbc4b.png", + "956782b3-ca4b-49e8-8939-6c50e87b9609.png", + "258270ae-3af4-4644-a031-176efac2c3f9.png", + "1fa52c2f-7474-4aa9-9ff9-0e411a78daac.png", + "f1299a54-59e5-42ea-9f53-e9f11fd6ca3c.png", + "6a6a86a2-bbba-422a-9620-5b90adaaf7a3.png", + "771c03d6-f0c8-4e3e-b734-0a07fff03c22.png", + "8c6ed656-6d1c-4707-82a2-cbff87a589f7.png", + "6a4f994f-293f-4a8a-8f8d-ac99f8e58adf.png", + "da90fb4d-3dfb-4a17-8ecc-95e82ab69b32.png", + "1563c9ee-30ab-44cc-b21f-fab5ad8df99d.png", + "932f5612-9058-4923-820d-894d630190cb.png", + "5e2958ab-c27d-41c8-8167-de9053f79038.png", + "2408cfed-ad91-43e2-9295-fdafafb76c8d.png", + "8549466d-50fe-4cb9-9001-e93532e7938c.png", + "00e4b598-2dd0-4ff9-b0a4-46e223a9296e.png", + "0666bf9a-4625-4132-bd7f-0079dace8c8c.png", + "ceb18b7d-1dcf-4aa2-adae-0e0aae1c5eeb.png", + "a4903060-7bfd-4bd5-b8d6-b916d172a82b.png", + "f5f4cf81-db71-42c7-b889-c25c145132c6.png", + "bf277536-38a6-41cd-a278-bd68e25816fd.png", + "a1cfe2ab-12cd-4d43-9ffc-77d48d0493f3.png", + "1c72f7db-374f-47db-8424-9526d4e7fa7a.png", + "3dc423ca-b351-429f-9842-1bd17e3ce360.png", + "2a8aea9d-218c-4601-8e8d-b98eb93fa461.png", + "451b6b8b-5d86-44ad-853b-e99153ba48e1.png", + "25d4c91a-c831-4249-b78e-a4b25d0b1ea1.png", + "b4f0036f-f2e7-4167-bbc4-708ee783052f.png", + "db04923e-96ac-41db-a16c-901f10a41bf0.png", + "65e832aa-974a-4ca8-9dd8-e90a96d75b6c.png", + "f66bf802-8273-4df7-a58a-faa8ba6ed46f.png", + "827976d2-dbab-47a3-905f-602e945a6b30.png", + "124bd263-2b8a-4057-9211-b36869047fd2.png", + "f69e2027-7163-4a53-8361-6050e5679242.png", + "d366b33d-335e-4a76-91f5-a5ce14266c89.png", + "adcb6ab3-7ecf-47f9-a11e-6a505ad23d98.png", + "2cea6a36-7053-4808-be22-fc5cc76b5531.png", + "ac3491a2-e817-4f5e-8453-ce34cb78a8a9.png", + "a875270b-fd82-409d-9bed-1d567657ff8e.png", + "f29cfb8b-d640-48a4-ae5e-02395ed7c6db.png", + "8c165058-abec-4ea9-9990-19b7eff4df4f.png", + "1c6ea15c-1cad-4a0c-838a-5eee8f99cfc9.png", + "897d7c04-f1bd-4bb1-bffb-bfada23a5b58.png", + "1b23c19f-7e79-4b96-a744-42615a72d722.png", + "f921b606-5363-41c2-aa93-dc8ec1475fda.png", + "efca4079-dd9f-4d54-8943-216d6c02e70a.png", + "040ff758-026f-4313-b390-ec86d3690f9d.png", + "0104c474-6473-4e05-b789-6bdb59f55da7.png", + "f73ed4a7-c1b1-4660-9eba-00f2ba25977b.png", + "0b184f66-ba4f-4fcd-9556-bea9f58dc9c6.png", + "7f638e9b-10e8-448c-a2f9-a75ae414dcfa.png", + "e563fd4b-656f-45f1-b803-df0d6dcb8bd3.png", + "0ed8ccf8-33e5-45a2-9200-4dc1a5565494.png", + "1ab263d2-ea24-4fe7-9383-f227aadc8c47.png", + "561d2d94-ec96-4246-974a-d9abc6f2297a.png", + "9af6ae6e-a842-4baa-a01e-cec57045c367.png", + "1c6fc0f3-d4ef-423b-9bba-d4a5d59c05df.png", + "76a72b39-24ec-4044-aad8-49f381939063.png", + "08ca0b3f-17e9-476e-9c17-ff81616c6bd7.png", + "9b637968-8173-44da-8f41-3943c4d182f9.png", + "725eb22a-2c4b-44b0-8aaf-bef282232601.png", + "3e81b87f-10ee-4f74-8ba8-1b724df383fb.png", + "fc9c7e5a-7abb-4ff6-84f2-9fce43bc200f.png", + "a8f33495-cd01-4b66-9c7e-3ba5edec6565.png", + "8585099d-cf7f-4c1c-8f36-937939dba42e.png", + "fe8afe85-5153-48cb-80e0-88de2a577f0c.png", + "46c59505-7dec-48f2-a0d1-c36ac213890e.png", + "95b636b0-8afb-4430-8f6a-1f4e0f4eb808.png", + "5ab4d96a-5401-45d8-977c-b3fef4e55ca9.png", + "8c8dd1cd-6c84-4fa8-b51b-ac736fda7a6c.png", + "76c7b19f-b375-48db-a1df-d79485a86d94.png", +] + +FLOOR_TEX_NAMES = [ + "8e4ea598-7170-4d24-ad12-42d45ef17a3b.png", + "9d7e7eac-9d81-4b04-8a07-ec35f9e7b58d.png", + "83c7c8bf-9277-4f59-88bd-1a4f428262ef.png", + "28359684-bb12-4b99-86b2-8c0998ee8fec.png", + "8ebc0bbe-1656-465e-b31e-766d1aceaec2.png", + "ada4e736-880d-4372-b148-218dc114c7fe.png", + "8a12dcf7-fc25-4341-9ea0-e583f1cc3d71.png", + "28f34ad5-b4f1-4b81-99cc-b04ed28d653b.png", + "b5350f4e-9521-4af1-a03f-a39e5d8b1796.png", + "14b4a5c3-69e0-425c-b8c5-ce495ab87409.png", + "022ec5c1-324e-4217-9f03-92b0e2f9c74f.png", + "9f345d0f-a768-4def-bebf-b818cf0c68dc.png", + "49de13f1-9488-4893-8398-48b0a5f27453.png", + "a938167f-6cb2-4e87-94f5-185eac06ff21.png", + "2aa2a926-fe72-4221-bd30-16e0a0cc9324.png", + "1671701f-60d2-4c71-95cc-8bdbb9f57ff9.png", + "8b24233c-7658-4d52-809d-a6fc71f37554.png", + "9582e8cc-89f5-464f-b183-2f21b8f0f267.png", + "8184ce85-7db2-4b23-908b-1170cc6830cf.png", + "32a18f41-8e7c-4a9d-b5ac-a7ba19a9ed35.png", + "56c9fb44-a8ee-469d-85d4-6d419f9dcba3.png", + "7ff039e9-7563-4ef0-b2ec-ce3d0d259a99.png", + "dbdd0778-8700-4967-bb52-75bbfa7eb29c.png", + "50578da0-60d8-4e12-800e-3df2fbf1bd5a.png", + "cedd99bd-8f8f-4d60-98e8-75e0af9b7e4f.png", + "b6c12637-3bd8-41d4-a787-3c2c271f4221.png", + "22c6be8e-a027-47dc-b2a1-3284cf5baad0.png", + "ed301cb6-fc33-4a6a-a2fd-4ce27a1f5bac.png", + "fc6bffaf-b9fd-4d51-a795-cb95d280dcab.png", + "310661bb-e74a-4b55-b999-ae1e2855990f.png", + "c327867a-02ea-4629-8059-181d3f341dc2.png", + "67a6f678-5f4b-4999-88fd-d0587299eb90.png", + "c65c9338-2903-4c6a-8015-dc606d24e659.png", + "e584ce4a-ff4d-461f-989e-5e4d21da42de.png", + "8776902b-74c1-4a54-94f2-320b4e89b5df.png", + "b588fa60-819c-4ae7-84bb-8f3de009ee1b.png", + "bdddfbd0-acc5-4e73-becb-c91f69986201.png", + "1f13ee23-d3f8-4fe4-b24d-97c4dece35c5.png", + "447fc81b-73c3-4502-8de7-9db654e62902.png", + "f78f9be1-385c-43ed-a89b-a4f11d45695f.png", + "c82d1a06-f78d-4e79-9b3e-23c4756d555d.png", + "573d34d2-a045-455c-b525-34a8571808eb.png", + "07f74135-07ab-4e29-bb00-4782f15ab59f.png", + "bec253e6-b2f0-48f2-afba-9207388a7937.png", + "0139f959-a4a8-4504-b6d2-f9351afd5941.png", + "8373a547-a792-438e-b941-f01ca1f0fb5d.png", + "b37ff2ac-f755-42f1-bdd4-a3a0f30fbfc6.png", + "f068688f-4b20-4d2f-b33a-9732b5050f72.png", + "c707d14d-3089-4a3e-a5b2-1088eda621bc.png", + "81ea9eea-29ea-4516-9e0d-e7ed0df98f5d.png", + "9aa36664-4ac6-4a50-b0e0-05c96f52c58e.png", + "c85db92d-b5a4-4fc8-aabd-9d4c82f3f444.png", + "df431f5c-699e-47ff-9161-b6e264a82163.png", + "4d8ea3e7-4a0b-4015-802c-cbbd0b12ba2e.png", + "3a34566d-b31f-4d3d-a86a-8038fde33b8c.png", + "83c6fd2f-caa2-4d53-b4d2-e19a7f12e6b4.png", + "ef044eea-9ebe-475e-bc05-d4e9d9255e39.png", + "02b897ed-2381-403a-aef1-095096993039.png", + "bb9ea1a0-7bfb-4aa2-85ee-0dbdb5001fa3.png", + "2afa8673-57cc-4953-b178-b57eedd9ad0a.png", + "2066e385-7798-47b3-89cc-1eaad15c75c4.png", + "45639cb9-7ac7-4d8c-a8a1-719d3a53d531.png", + "8f7fabcb-6875-4437-9d9c-27a2552c10dd.png", + "ce8ccc5f-20b9-4d06-aee6-fe85a6c02eaa.png", + "11fa953e-c11d-4dad-8e51-47cc6dc67aeb.png", + "8f51e06a-7bd0-4d2f-9a20-7821a975559a.png", + "1ef4cfa4-cf52-4efd-9fb3-6698650ee239.png", + "4d974231-cd17-4da5-ad9a-7faf83c2d683.png", + "cadaada3-e8f1-4bc7-af71-342215edbbb1.png", + "fb9b36a4-d87a-4c7f-a06c-a1e94869b96b.png", + "5daabcbd-0ce4-4dba-9342-c74d3da4fadf.png", + "612b00d2-819f-46ac-a599-38672184c842.png", + "0b5b5a9a-1435-4dfe-b6f4-19f4dbae1e8e.png", + "11f6a3bb-c36c-45c2-a429-501ac0cabc02.png", + "cf96c697-41f0-4d3c-a1d4-17d0d82719d0.png", + "81d9e9f2-8ff4-4d45-b1dd-d3afd3c62fb0.png", + "82036c07-5321-47c8-974c-27d58e526ba1.png", + "e793023f-7e5f-4211-9724-9022d3c8f920.png", + "0c01c256-4779-4093-a0b9-3347c31ef53f.png", + "9db099e2-56cb-4bec-becc-eb69c298866e.png", + "05f75518-7b70-4098-8983-aca459f33ddb.png", + "7c935010-badd-4fa4-8089-4fc9728dfe96.png", + "f9d057b1-5843-4b68-a58b-9fe87291a72f.png", + "9354be03-5a87-4ce8-85bc-8b0157abeb1c.png", + "9bfe963b-6d17-4704-8a9f-c2de48491b70.png", + "3b70d093-e264-4550-b5e5-f750ba577b78.png", + "67837bbb-05ae-4665-90e5-572130b7fc86.png", + "d339c422-36d0-40f3-8393-24076abb279c.png", + "5ccc395f-efd5-44af-b5f9-885789e26661.png", + "6d58d55a-34cc-455f-8b4c-004fabef6e11.png", + "5729f1d0-0796-4d82-99f7-76a171266fae.png", + "1e6da165-23cb-4426-91cf-450b3ac74e49.png", + "86ae5f3b-1a9c-4895-87eb-b526b403f332.png", + "4e53b13b-317a-484c-9b8b-7417453e45ff.png", + "8ddb08c1-facb-4fb1-841b-bde4e47fe584.png", + "41c3dbec-db54-4417-bb76-f51a4349943e.png", + "a2881fcf-1af3-46e9-87b0-c198fad703d1.png", + "808ec0fb-fcf8-4629-9296-38530521a95e.png", + "7c411449-a3c6-48e4-ab30-d08bca5938d6.png", + "0df28fee-6cef-48ae-9e8e-c0f0f3482412.png", +] + +WALL_TEX_NAMES = [ + "plain copy 49.png", + "18a6abbd-8ca1-43d9-9a0a-8424a7d1e016.png", + "plain copy 2.png", + "0882d081-d8be-49c0-aad6-3f5eff92265b.png", + "plain copy 39.png", + "7a19bf00-4f43-4e39-8fe6-977df7c6d147.png", + "plain copy 8.png", + "9b6f9830-a89d-4a42-965f-581dd0a12617.png", + "bcf9bf9b-ac75-408e-ab2e-516391c39d8e.png", + "plain copy 51.png", + "845424a1-4603-47d7-892c-426c2d427f0d.png", + "6e961263-5c90-41f9-87d3-b9e132c9583a.png", + "c72ea705-e088-4665-9683-6a8685758aef.png", + "plain copy 22.png", + "plain copy 44.png", + "plain copy 10.png", + "df17f0f3-68bb-46e2-ae9f-86cf84f48b04.png", + "plain copy 53.png", + "0906d773-7c22-4173-9edc-efc6e2da88e0.png", + "8995f82f-2435-4395-8ecd-a00824edd923.png", + "0adf5feb-6a2f-4417-811a-b7d70d42fb34.png", + "plain copy 5.png", + "536410ee-0460-43b0-9e8e-799e96439a0d.png", + "plain copy 11.png", + "plain copy 19.png", + "plain copy 17.png", + "plain copy.png", + "plain copy 31.png", + "Lance_Z._white_square_tiles_texture_image_ikea_high_quality_rea_f41b5937-af3e-4df8-b19d-ae4fa942f741.png", + "f6353155-1a10-41a1-be1d-149368938757.png", + "b1a7c75f-6b03-4b10-99cd-3299d7b6beb5.png", + "plain copy 52.png", + "7844f4b6-7d34-46b4-8ea4-19ab954ca58f.png", + "0dd40625-0cf8-4523-92cd-063c96108a23.png", + "plain copy 40.png", + "plain copy 21.png", + "plain copy 36.png", + "plain copy 37.png", + "plain copy 41.png", + "plain copy 23.png", + "1b8b8a44-ce4e-4156-978b-ad66bf4a6f45.png", + "plain copy 46.png", + "d208d65f-4d99-4963-8140-d54180844c8c.png", + "0aa2c331-8025-4417-a157-91467143c85b.png", + "d4775c13-15ea-496d-b5fc-19d2a9cab128.png", + "11760e4b-5f86-46cb-82ae-c87cc6f434d1.png", + "plain copy 3.png", + "plain copy 30.png", + "plain copy 9.png", + "0af727bd-14b4-4f7d-9fee-19f7f001ad34.png", + "67d1229f-7689-4dd6-ab2b-d003e0cd3cb7.png", + "plain copy 33.png", + "plain copy 4.png", + "2149f068-ca27-40ed-b53d-07e53210e678.png", + "plain copy 38.png", + "6b215002-fd31-4f1a-859a-d5d98a2a0c52.png", + "4fe97e2e-ae88-4dc9-8321-3529a2108508.png", + "Lance_Z._white_square_tiles_ikea_high_quality_realistic_ec4bd31e-d76d-4512-8b0d-a86dd8dd6aad.png", + "plain copy 6.png", + "plain copy 13.png", + "0d7afefe-58c8-4161-bf56-0974c7e806a2.png", + "plain copy 28.png", + "314f4070-0b2f-4433-98e7-dbdf18a8bff2.png", + "plain copy 18.png", + "dae6863d-b653-4998-8239-c6a6bb24362c.png", + "497cbc0b-a80a-42b3-8f5e-3bc97c145255.png", + "plain copy 20.png", + "4874a0d3-f5f2-46ea-a1d3-824b2f56f8ce.png", + "plain copy 50.png", + "plain copy 12.png", + "7c7c9950-576a-45fd-b3d1-74cca30f6fe7.png", + "8474c563-65b7-408b-976f-b19b38a44f90.png", + "Lance_Z._white_square_tiles_texture_image_ikea_high_quality_rea_ce2dcd92-29d7-4176-b7fa-79d91dab133b.png", + "738a1240-97f3-4fa6-97df-0ecc4b7aac26.png", + "plain copy 32.png", + "plain copy 29.png", + "a4046f8f-a2d6-4ef4-aa39-2ec541cbd246.png", + "plain copy 25.png", + "cbf05cdc-5d1c-472b-9891-0e4802553359.png", + "plain copy 16.png", + "plain copy 47.png", + "4bb0ad30-b60a-44a6-a259-058fab19b422.png", + "77abb443-a1b8-4b02-96de-1a7bc68d4f3f.png", + "plain copy 27.png", + "plain copy 24.png", + "plain copy 43.png", + "35ded0fe-73a7-4e82-8c01-32f79f5214a3.png", + "4b9d5219-38a0-4303-8837-29c4c51eed54.png", + "8949ad7c-2b89-444c-a758-b513f25937e1.png", + "plain copy 48.png", + "plain copy 45.png", + "plain copy 35.png", + "plain copy 26.png", + "plain copy 42.png", + "f7c0d850-4b56-484f-85ce-e9c4bd01ec22.png", + "9ec0b130-598a-4471-99ee-f68ee49a4a9f.png", + "b1dcb5d2-434e-4bd1-9329-eb1c2a6c039d.png", + "cf0d9763-3596-48de-af34-5f3647d812df.png", + "plain copy 14.png", + "fda88519-7a09-466d-84a2-19b216562dcb.png", +] + + +def get_random_textures(rng, frac=1.0): + """ + This function returns a dictionary of random textures for cabinet, counter top, floor, and wall. + + Args: + rng (np.random.Generator): Random number generator used for texture selection + + frac (float): Fraction of textures to select from the list of available textures + Default: 1.0 (select from all textures) + + Returns: + textures (dict): Dictionary of texture paths + """ + + end_ind = int(frac * 100) + ind = rng.integers(0, end_ind) + + textures = dict( + cab_tex=os.path.join(TEXTURES_DIR, "cabinet", CABINET_TEX_NAMES[ind]), + counter_tex=os.path.join(TEXTURES_DIR, "counter", COUNTER_TOP_TEX_NAMES[ind]), + floor_tex=os.path.join(TEXTURES_DIR, "floor", FLOOR_TEX_NAMES[ind]), + wall_tex=os.path.join(TEXTURES_DIR, "wall", WALL_TEX_NAMES[ind]), + ) + + return textures + + +def replace_counter_top_texture( + rng, initial_state: str, new_counter_top_texture_file: str = None +): + """ + This function replaces the counter top textures during playback. + + Args: + rng (np.random.Generator): Random number generator used for texture selection + + initial_state (str): Initial env XML string + + new_counter_top_texture_file (str): New texture file for counter top: i.e "marble/dark_marble.png" + If None (default), will replace with a random texture from marble directory + """ + + root = ET.fromstring(initial_state) + asset = root.find("asset") + + if new_counter_top_texture_file is None: + new_counter_top_texture_file = get_random_textures(rng)["counter_tex"] + else: + new_counter_top_texture_file = os.path.join( + TEXTURES_DIR, new_counter_top_texture_file + ) + + # step 1: find the name of texture that will be replaced + counter_tex_name = None + for mat in asset.findall("material"): + name = mat.get("name") + if "counter_top" in name: + counter_tex_name = mat.get("texture") + break + assert counter_tex_name is not None + + # step 2: find and replace texture element + CTOP_TEX_NAME = "counter_top_replacement_texture" + for tex in asset.findall("texture"): + name = tex.get("name") + if name == counter_tex_name: + tex.set("name", CTOP_TEX_NAME) + tex.set("file", str(new_counter_top_texture_file)) + + # step 3: reference new textures in materials + for mat in asset.findall("material"): + name = mat.get("name") + if "counter_top" in name: + mat.set("texture", CTOP_TEX_NAME) + + return ET.tostring(root).decode("utf-8") + + +def replace_cab_textures(rng, initial_state: str, new_cab_texture_file: str = None): + """ + This function replaces the cabinet and counter base textures during playback. + + Args: + rng (np.random.Generator): Random number generator used for texture selection + + initial_state (str): Initial env XML string + + new_cab_texture_file (str): New texture file for counter base and cabinets: i.e "cabinet/..." + If None (default), will replace with a random texture from flat or wood directories + """ + + root = ET.fromstring(initial_state) + asset = root.find("asset") + + if new_cab_texture_file is None: + new_cab_texture_file = get_random_textures(rng)["cab_tex"] + else: + new_cab_texture_file = os.path.join(TEXTURES_DIR, new_cab_texture_file) + + CAB_TEX_NAME_2D = "cab_replacement_texture_2d" + tex_2d = find_elements( + asset, tags="texture", attribs={"name": CAB_TEX_NAME_2D}, return_first=True + ) + if tex_2d is not None: + tex_2d.set("file", str(new_cab_texture_file)) + else: + tex_2d = ET.Element( + "texture", type="2d", name=CAB_TEX_NAME_2D, file=str(new_cab_texture_file) + ) + asset.append(tex_2d) + + CAB_TEX_NAME_CUBE = "cab_replacement_texture_cube" + tex_cube = find_elements( + asset, tags="texture", attribs={"name": CAB_TEX_NAME_CUBE}, return_first=True + ) + if tex_cube is not None: + tex_cube.set("file", str(new_cab_texture_file)) + else: + tex_cube = ET.Element( + "texture", + type="cube", + name=CAB_TEX_NAME_CUBE, + file=str(new_cab_texture_file), + ) + asset.append(tex_cube) + + for mat in asset.findall("material"): + name = mat.get("name") + if "counter_base" in name: + mat.set("texture", CAB_TEX_NAME_CUBE) + elif "housing" in name: + mat.set("texture", CAB_TEX_NAME_CUBE) + elif ( + "stack" in name + or "cab" in name + or "shelves" in name + or "bottom" in name + or ("top" in name and "counter" not in name and "stove" not in name) + ): + if "handle" in name or "transparent" in name: + continue + elif "door" in name: + mat.set("texture", CAB_TEX_NAME_2D) + elif "shelves" in name: + mat.set("texture", CAB_TEX_NAME_2D) + else: + mat.set("texture", CAB_TEX_NAME_CUBE) + + return ET.tostring(root).decode("utf-8") + + +def replace_floor_texture(rng, initial_state: str, new_floor_texture_file: str = None): + """ + This function replaces the counter top textures during playback. + + Args: + rng (np.random.Generator): Random number generator used for texture selection + + initial_state (str): Initial env XML string + + new_floor_texture_file (str): New texture file for counter top: i.e "wood/dark_wood_planks_2.png" + If None (default), will replace with a random texture from wood directory + """ + + root = ET.fromstring(initial_state) + asset = root.find("asset") + + if new_floor_texture_file is None: + new_floor_texture_file = get_random_textures(rng)["floor_tex"] + else: + new_floor_texture_file = os.path.join(TEXTURES_DIR, new_floor_texture_file) + + # step 1: find the name of texture that will be replaced + floor_tex_name = None + for mat in asset.findall("material"): + name = mat.get("name") + if "floor" in name and "backing" not in name: + floor_tex_name = mat.get("texture") + break + assert floor_tex_name is not None + + # step 2: find and replace texture element + FLOOR_TEX_NAME = "floor_replacement_texture" + for tex in asset.findall("texture"): + name = tex.get("name") + if name == floor_tex_name: + tex.set("name", FLOOR_TEX_NAME) + tex.set("file", str(new_floor_texture_file)) + tex.set("type", "2d") + + # step 3: reference new textures in materials + for mat in asset.findall("material"): + name = mat.get("name") + if "floor" in name and "backing" not in name: + mat.set("texture", FLOOR_TEX_NAME) + mat.set("texrepeat", "2 2") + + return ET.tostring(root).decode("utf-8") + + +def replace_wall_texture(rng, initial_state: str, new_wall_texture_file: str = None): + """ + This function replaces the counter top textures during playback. + + Args: + rng (np.random.Generator): Random number generator used for texture selection + + initial_state (str): Initial env XML string + + new_wall_texture_file (str): New texture file for counter top: i.e "wood/dark_wood_planks_2.png" + If None (default), will replace with a random texture from wood directory + """ + + root = ET.fromstring(initial_state) + asset = root.find("asset") + + if new_wall_texture_file is None: + new_wall_texture_file = get_random_textures(rng)["wall_tex"] + else: + new_wall_texture_file = os.path.join(TEXTURES_DIR, new_wall_texture_file) + + # step 1: find the name of texture that will be replaced + wall_tex_name = None + for mat in asset.findall("material"): + name = mat.get("name") + if "wall" in name and "floor" not in name and "backing" not in name: + wall_tex_name = mat.get("texture") + break + assert wall_tex_name is not None + + # step 2: add new texture element + WALL_TEX_NAME = "wall_replacement_texture" + for tex in asset.findall("texture"): + name = tex.get("name") + if name == wall_tex_name: + tex.set("name", WALL_TEX_NAME) + tex.set("file", str(new_wall_texture_file)) + tex.set("type", "2d") + + # step 3: reference new textures in materials + for mat in asset.findall("material"): + name = mat.get("name") + if "wall" in name and "floor" not in name and "backing" not in name: + mat.set("texture", WALL_TEX_NAME) + mat.set("texrepeat", "3 3") + + return ET.tostring(root).decode("utf-8") diff --git a/third_party/robocasa/setup.py b/third_party/robocasa/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..ed419096e63f91280decf6633cd896840fb265a8 --- /dev/null +++ b/third_party/robocasa/setup.py @@ -0,0 +1,45 @@ +# read the contents of your README file +from os import path + +from setuptools import find_packages, setup + +this_directory = path.abspath(path.dirname(__file__)) +with open(path.join(this_directory, "README.md"), encoding="utf-8") as f: + lines = f.readlines() + +# remove images from README +lines = [x for x in lines if ".png" not in x] +long_description = "".join(lines) + +setup( + name="robocasa", + packages=[package for package in find_packages() if package.startswith("robocasa")], + install_requires=[ + "numpy==1.26.4", + "numba==0.61.2", + "scipy>=1.2.3", + "mujoco==3.2.6", + "pygame", + "Pillow", + "opencv-python", + "pyyaml", + "pynput", + "tqdm", + "termcolor", + "imageio", + "h5py", + "lxml", + "hidapi", + "tianshou==0.5.1", + ], + eager_resources=["*"], + include_package_data=True, + python_requires=">=3", + description="RoboCasa: Large-Scale Simulation of Household Tasks for Generalist Robots", + author="Soroush Nasiriany, Abhiram Maddukuri, Lance Zhang, Adeet Parikh, Aaron Lo, Abhishek Joshi, Ajay Mandlekar, Yuke Zhu", + url="https://github.com/robocasa/robocasa", + author_email="soroush@cs.utexas.edu", + version="0.2.0", + long_description=long_description, + long_description_content_type="text/markdown", +) diff --git a/third_party/robocasa/tools/robocasa_usd/convert_robocasa_objects_to_usd.py b/third_party/robocasa/tools/robocasa_usd/convert_robocasa_objects_to_usd.py new file mode 100644 index 0000000000000000000000000000000000000000..0788215241a22ac0d2745605edecca34bb109770 --- /dev/null +++ b/third_party/robocasa/tools/robocasa_usd/convert_robocasa_objects_to_usd.py @@ -0,0 +1,570 @@ +#!/usr/bin/env python3 +"""Normalize RoboCasa object assets and convert them to USD with Isaac Sim. + +Each input asset is expected to contain a MuJoCo ``model.xml`` that references +visual and collision OBJ meshes. The script writes one output directory per +asset with this shape by default: + + .obj + .mtl + .usd + collision.obj + maps/ + textures/ + +The visual and collision OBJ files have mesh ``scale`` and ``refquat`` baked in +from the MJCF asset declarations so Isaac Sim's OBJ converter sees the same +geometry size as MuJoCo. +""" + +from __future__ import annotations + +import argparse +import asyncio +import json +import math +import os +import re +import shutil +import sys +import xml.etree.ElementTree as ET +from dataclasses import dataclass +from pathlib import Path +from typing import Iterable + + +DEFAULT_INPUT_ROOT = Path( + "/mnt/workspace/users/liao/envs/robocasa-gr1-tabletop-tasks/" + "robocasa/models/assets/objects" +) +DEFAULT_OUTPUT_ROOT = Path( + "/mnt/workspace/users/liao/envs/robocasa-gr1-tabletop-tasks/" + "robocasa/models/assets/objects_usd_aligned" +) + + +@dataclass(frozen=True) +class MeshAsset: + name: str + file: Path + scale: tuple[float, float, float] + refquat: tuple[float, float, float, float] + + +@dataclass(frozen=True) +class TextureAsset: + name: str + file: Path + + +@dataclass(frozen=True) +class MaterialAsset: + name: str + texture: str | None + rgba: tuple[float, float, float, float] | None + specular: float | None + shininess: float | None + + +@dataclass(frozen=True) +class Geom: + mesh_name: str + material_name: str | None + visual: bool + density: float | None + friction: tuple[float, ...] | None + + +def parse_vec(text: str | None, default: tuple[float, ...]) -> tuple[float, ...]: + if not text: + return default + return tuple(float(v) for v in text.split()) + + +def sanitize_name(name: str) -> str: + cleaned = re.sub(r"[^0-9A-Za-z_]+", "_", name).strip("_") + return cleaned or "material" + + +def unique_name(name: str, used: set[str]) -> str: + base = sanitize_name(name) + candidate = base + index = 1 + while candidate in used: + candidate = f"{base}_{index}" + index += 1 + used.add(candidate) + return candidate + + +def unique_file_name(name: str, used: set[str]) -> str: + path = Path(name) + stem = sanitize_name(path.stem) + suffix = re.sub(r"[^0-9A-Za-z.]+", "_", path.suffix) + candidate = f"{stem}{suffix}" + index = 1 + while candidate in used: + candidate = f"{stem}_{index}{suffix}" + index += 1 + used.add(candidate) + return candidate + + +def quat_rotate( + quat: tuple[float, float, float, float], + vec: tuple[float, float, float], +) -> tuple[float, float, float]: + """Rotate ``vec`` by a MuJoCo-style wxyz quaternion.""" + w, x, y, z = quat + vx, vy, vz = vec + tx = 2.0 * (y * vz - z * vy) + ty = 2.0 * (z * vx - x * vz) + tz = 2.0 * (x * vy - y * vx) + rx = vx + w * tx + (y * tz - z * ty) + ry = vy + w * ty + (z * tx - x * tz) + rz = vz + w * tz + (x * ty - y * tx) + return rx, ry, rz + + +def normalize_quat(quat: tuple[float, float, float, float]) -> tuple[float, float, float, float]: + mag = math.sqrt(sum(v * v for v in quat)) + if mag <= 0: + return 1.0, 0.0, 0.0, 0.0 + return tuple(v / mag for v in quat) # type: ignore[return-value] + + +def resolve_default_mesh_scale(root: ET.Element) -> tuple[float, float, float]: + mesh = root.find(".//default/mesh") + if mesh is None: + return 1.0, 1.0, 1.0 + return parse_vec(mesh.get("scale"), (1.0, 1.0, 1.0))[:3] # type: ignore[return-value] + + +def collect_defaults(root: ET.Element) -> dict[str, dict[str, str]]: + defaults: dict[str, dict[str, str]] = {} + for default in root.findall(".//default/default"): + class_name = default.get("class") + geom = default.find("geom") + if class_name and geom is not None: + defaults[class_name] = dict(geom.attrib) + return defaults + + +def merged_geom_attr(geom: ET.Element, defaults: dict[str, dict[str, str]], key: str) -> str | None: + if key in geom.attrib: + return geom.get(key) + class_name = geom.get("class") + if class_name and class_name in defaults: + return defaults[class_name].get(key) + return None + + +def parse_model_xml(xml_path: Path) -> tuple[dict[str, MeshAsset], dict[str, TextureAsset], dict[str, MaterialAsset], list[Geom]]: + root = ET.parse(xml_path).getroot() + asset_dir = xml_path.parent + default_scale = resolve_default_mesh_scale(root) + defaults = collect_defaults(root) + + meshes: dict[str, MeshAsset] = {} + for mesh in root.findall(".//asset/mesh"): + name = mesh.get("name") + file_name = mesh.get("file") + if not name or not file_name: + continue + scale = parse_vec(mesh.get("scale"), default_scale)[:3] + refquat = parse_vec(mesh.get("refquat"), (1.0, 0.0, 0.0, 0.0))[:4] + meshes[name] = MeshAsset( + name=name, + file=(asset_dir / file_name).resolve(), + scale=scale, # type: ignore[arg-type] + refquat=normalize_quat(refquat), # type: ignore[arg-type] + ) + + textures: dict[str, TextureAsset] = {} + for texture in root.findall(".//asset/texture"): + name = texture.get("name") + file_name = texture.get("file") + if name and file_name: + textures[name] = TextureAsset(name=name, file=(asset_dir / file_name).resolve()) + + materials: dict[str, MaterialAsset] = {} + for material in root.findall(".//asset/material"): + name = material.get("name") + if not name: + continue + rgba = parse_vec(material.get("rgba"), (1.0, 1.0, 1.0, 1.0)) + materials[name] = MaterialAsset( + name=name, + texture=material.get("texture"), + rgba=rgba[:4] if rgba else None, # type: ignore[arg-type] + specular=float(material.get("specular")) if material.get("specular") else None, + shininess=float(material.get("shininess")) if material.get("shininess") else None, + ) + + geoms: list[Geom] = [] + for geom in root.findall(".//geom"): + mesh_name = geom.get("mesh") + if not mesh_name: + continue + class_name = geom.get("class") + group = merged_geom_attr(geom, defaults, "group") + contype = merged_geom_attr(geom, defaults, "contype") + conaffinity = merged_geom_attr(geom, defaults, "conaffinity") + visual = class_name == "visual" or group == "1" or (contype == "0" and conaffinity == "0") + density = merged_geom_attr(geom, defaults, "density") + friction = merged_geom_attr(geom, defaults, "friction") + geoms.append( + Geom( + mesh_name=mesh_name, + material_name=geom.get("material"), + visual=visual, + density=float(density) if density else None, + friction=parse_vec(friction, ()) if friction else None, + ) + ) + return meshes, textures, materials, geoms + + +def transform_vertex(line: str, mesh: MeshAsset) -> str: + _, x, y, z, *rest = line.split() + vx = float(x) * mesh.scale[0] + vy = float(y) * mesh.scale[1] + vz = float(z) * mesh.scale[2] + rx, ry, rz = quat_rotate(mesh.refquat, (vx, vy, vz)) + suffix = " " + " ".join(rest) if rest else "" + return f"v {rx:.9g} {ry:.9g} {rz:.9g}{suffix}\n" + + +def transform_normal(line: str, mesh: MeshAsset) -> str: + _, x, y, z, *rest = line.split() + rx, ry, rz = quat_rotate(mesh.refquat, (float(x), float(y), float(z))) + suffix = " " + " ".join(rest) if rest else "" + return f"vn {rx:.9g} {ry:.9g} {rz:.9g}{suffix}\n" + + +def rewrite_face_token(token: str, v_offset: int, vt_offset: int, vn_offset: int) -> str: + parts = token.split("/") + if parts[0]: + value = int(parts[0]) + if value > 0: + parts[0] = str(value + v_offset) + if len(parts) > 1 and parts[1]: + value = int(parts[1]) + if value > 0: + parts[1] = str(value + vt_offset) + if len(parts) > 2 and parts[2]: + value = int(parts[2]) + if value > 0: + parts[2] = str(value + vn_offset) + return "/".join(parts) + + +def append_obj( + out, + mesh: MeshAsset, + object_name: str, + material_name: str | None, + offsets: tuple[int, int, int], +) -> tuple[int, int, int]: + v_offset, vt_offset, vn_offset = offsets + v_count = vt_count = vn_count = 0 + out.write(f"\no {sanitize_name(object_name)}\n") + if material_name: + out.write(f"usemtl {sanitize_name(material_name)}\n") + + with mesh.file.open("r", encoding="utf-8", errors="ignore") as src: + for line in src: + if line.startswith("v "): + out.write(transform_vertex(line, mesh)) + v_count += 1 + elif line.startswith("vt "): + out.write(line) + vt_count += 1 + elif line.startswith("vn "): + out.write(transform_normal(line, mesh)) + vn_count += 1 + elif line.startswith("f "): + tokens = [rewrite_face_token(t, v_offset, vt_offset, vn_offset) for t in line.split()[1:]] + out.write("f " + " ".join(tokens) + "\n") + elif line.startswith(("s ", "g ")): + out.write(line) + elif line.startswith(("mtllib ", "usemtl ")): + continue + elif line.startswith("#"): + continue + + return v_offset + v_count, vt_offset + vt_count, vn_offset + vn_count + + +def copy_texture(src: Path, output_dir: Path, used: set[str]) -> str: + if not src.exists(): + return src.name + name = unique_file_name(src.name, used) + for folder_name in ("textures", "maps"): + folder = output_dir / folder_name + folder.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, folder / name) + return name + + +def write_mtl( + output_dir: Path, + textures: dict[str, TextureAsset], + materials: dict[str, MaterialAsset], + used_texture_names: set[str], +) -> dict[str, str]: + material_name_map: dict[str, str] = {} + with (output_dir / "Aligned.mtl").open("w", encoding="utf-8") as out: + if not materials: + out.write("newmtl default\nKd 0.8 0.8 0.8\nKa 1 1 1\nKs 0.2 0.2 0.2\nNs 50\n") + return material_name_map + + for material in materials.values(): + safe_name = sanitize_name(material.name) + material_name_map[material.name] = safe_name + rgba = material.rgba or (1.0, 1.0, 1.0, 1.0) + kd = rgba[:3] + ks = material.specular if material.specular is not None else 0.2 + ns = material.shininess * 1000.0 if material.shininess is not None and material.shininess <= 1 else material.shininess + out.write(f"newmtl {safe_name}\n") + out.write("Ka 1 1 1\n") + out.write(f"Kd {kd[0]:.6g} {kd[1]:.6g} {kd[2]:.6g}\n") + out.write(f"Ks {ks:.6g} {ks:.6g} {ks:.6g}\n") + out.write(f"Ns {(ns if ns is not None else 50):.6g}\n") + if rgba[3] < 1.0: + out.write(f"d {rgba[3]:.6g}\n") + if material.texture and material.texture in textures: + tex_name = copy_texture(textures[material.texture].file, output_dir, used_texture_names) + out.write(f"map_Kd textures/{tex_name}\n") + out.write("\n") + return material_name_map + + +def copy_extra_mtl_textures(meshes: Iterable[MeshAsset], output_dir: Path, used_texture_names: set[str]) -> None: + """Copy texture files referenced by source MTL files even if XML skipped them.""" + for mesh in meshes: + try: + with mesh.file.open("r", encoding="utf-8", errors="ignore") as src: + mtllibs = [line.split(maxsplit=1)[1].strip() for line in src if line.startswith("mtllib ")] + except FileNotFoundError: + continue + for mtllib in mtllibs: + mtl_path = mesh.file.parent / mtllib + if not mtl_path.exists(): + mtl_path = mesh.file.parent.parent / mtllib + if not mtl_path.exists(): + continue + with mtl_path.open("r", encoding="utf-8", errors="ignore") as mtl: + for line in mtl: + if line.startswith(("map_Kd ", "map_Bump ", "bump ", "map_Ks ", "map_Ns ", "map_d ")): + texture_ref = line.split(maxsplit=1)[1].strip() + texture_ref = texture_ref.split()[-1] + texture_path = (mtl_path.parent / texture_ref).resolve() + copy_texture(texture_path, output_dir, used_texture_names) + + +def find_models(input_root: Path) -> list[Path]: + ignored_parts = {"__MACOSX"} + models = [] + for xml_path in input_root.rglob("model.xml"): + if any(part in ignored_parts for part in xml_path.parts): + continue + models.append(xml_path) + return sorted(models) + + +def output_dir_for(input_root: Path, output_root: Path, xml_path: Path) -> Path: + rel = xml_path.parent.relative_to(input_root) + return output_root / rel + + +def asset_basename(xml_path: Path, basename: str | None) -> str: + return sanitize_name(basename or xml_path.parent.name) + + +def clean_output_dir(path: Path, basename: str) -> None: + if not path.exists(): + return + for name in ( + f"{basename}.obj", + f"{basename}.mtl", + f"{basename}.usd", + "Aligned.obj", + "Aligned.mtl", + "Aligned.usd", + "collision.obj", + "metadata.json", + ): + target = path / name + if target.exists(): + target.unlink() + for name in ("textures", "maps"): + target = path / name + if target.exists(): + shutil.rmtree(target) + + +def prepare_asset( + input_root: Path, + output_root: Path, + xml_path: Path, + overwrite: bool, + basename_arg: str | None, +) -> Path | None: + output_dir = output_dir_for(input_root, output_root, xml_path) + basename = asset_basename(xml_path, basename_arg) + if (output_dir / f"{basename}.obj").exists() and (output_dir / f"{basename}.usd").exists() and not overwrite: + return output_dir + + meshes, textures, materials, geoms = parse_model_xml(xml_path) + visual_geoms = [geom for geom in geoms if geom.visual and geom.mesh_name in meshes] + collision_geoms = [geom for geom in geoms if not geom.visual and geom.mesh_name in meshes] + if not visual_geoms: + print(f"[WARN] no visual mesh in {xml_path}", flush=True) + return None + + output_dir.mkdir(parents=True, exist_ok=True) + if overwrite: + clean_output_dir(output_dir, basename) + output_dir.mkdir(parents=True, exist_ok=True) + + used_texture_names: set[str] = set() + material_name_map = write_mtl(output_dir, textures, materials, used_texture_names) + copy_extra_mtl_textures((meshes[g.mesh_name] for g in visual_geoms), output_dir, used_texture_names) + + offsets = (0, 0, 0) + with (output_dir / f"{basename}.obj").open("w", encoding="utf-8") as out: + out.write(f"mtllib {basename}.mtl\n") + for index, geom in enumerate(visual_geoms): + material_name = material_name_map.get(geom.material_name or "", geom.material_name or "default") + offsets = append_obj(out, meshes[geom.mesh_name], f"visual_{index}_{geom.mesh_name}", material_name, offsets) + + generated_mtl = output_dir / "Aligned.mtl" + target_mtl = output_dir / f"{basename}.mtl" + if generated_mtl != target_mtl: + generated_mtl.replace(target_mtl) + + if collision_geoms: + offsets = (0, 0, 0) + with (output_dir / "collision.obj").open("w", encoding="utf-8") as out: + for index, geom in enumerate(collision_geoms): + offsets = append_obj(out, meshes[geom.mesh_name], f"collision_{index}_{geom.mesh_name}", None, offsets) + + metadata = { + "source_model_xml": str(xml_path), + "source_asset_dir": str(xml_path.parent), + "visual_meshes": [meshes[g.mesh_name].file.name for g in visual_geoms], + "collision_mesh_count": len(collision_geoms), + "friction": next((g.friction for g in collision_geoms if g.friction), None), + "density": next((g.density for g in collision_geoms if g.density), None), + "basename": basename, + } + (output_dir / "metadata.json").write_text(json.dumps(metadata, indent=2), encoding="utf-8") + return output_dir + + +async def convert_one(converter, input_obj: Path, output_usd: Path, load_materials: bool, overwrite: bool) -> bool: + if output_usd.exists() and not overwrite: + return True + + import omni.kit.asset_converter + + context = omni.kit.asset_converter.AssetConverterContext() + context.ignore_materials = not load_materials + context.ignore_animation = True + context.ignore_cameras = True + context.ignore_lights = True + context.smooth_normals = True + context.embed_textures = False + context.use_meter_as_world_unit = True + context.create_world_as_default_root_prim = False + context.merge_all_meshes = False + + def progress_callback(progress, total_steps): + return None + + task = converter.create_converter_task(str(input_obj), str(output_usd), progress_callback, context) + while True: + success = await task.wait_until_finished() + if success: + return True + await asyncio.sleep(0.1) + + +async def convert_outputs(output_dirs: list[Path], load_materials: bool, overwrite: bool) -> int: + import omni.kit.asset_converter + + converter = omni.kit.asset_converter.get_instance() + failures = 0 + for index, output_dir in enumerate(output_dirs, 1): + metadata_path = output_dir / "metadata.json" + basename = json.loads(metadata_path.read_text(encoding="utf-8")).get("basename", output_dir.name) + input_obj = output_dir / f"{basename}.obj" + output_usd = output_dir / f"{basename}.usd" + print(f"[USD {index}/{len(output_dirs)}] {output_usd}", flush=True) + try: + ok = await convert_one(converter, input_obj, output_usd, load_materials, overwrite) + except Exception as exc: + ok = False + print(f"[ERROR] converter exception for {input_obj}: {exc}", flush=True) + if not ok or not output_usd.exists(): + failures += 1 + print(f"[ERROR] failed to convert {input_obj}", flush=True) + return failures + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--input-root", type=Path, default=DEFAULT_INPUT_ROOT) + parser.add_argument("--output-root", type=Path, default=DEFAULT_OUTPUT_ROOT) + parser.add_argument("--limit", type=int, default=None) + parser.add_argument("--only", type=str, default=None, help="Only process model.xml paths containing this substring.") + parser.add_argument("--overwrite", action="store_true") + parser.add_argument("--basename", type=str, default="Aligned", help="Use this fixed basename instead of each asset dir name.") + parser.add_argument("--prepare-only", action="store_true") + parser.add_argument("--skip-convert", action="store_true") + parser.add_argument("--headless", action="store_true", default=True) + parser.add_argument("--no-materials", action="store_true") + args, unknown = parser.parse_known_args() + + models = find_models(args.input_root) + if args.only: + models = [path for path in models if args.only in str(path)] + if args.limit is not None: + models = models[: args.limit] + + print(f"[INFO] found {len(models)} assets", flush=True) + prepared: list[Path] = [] + for index, xml_path in enumerate(models, 1): + print(f"[PREP {index}/{len(models)}] {xml_path}", flush=True) + try: + output_dir = prepare_asset(args.input_root, args.output_root, xml_path, args.overwrite, args.basename) + except Exception as exc: + print(f"[ERROR] prepare failed for {xml_path}: {exc}", flush=True) + continue + if output_dir is not None: + prepared.append(output_dir) + + if args.prepare_only or args.skip_convert: + print(f"[DONE] prepared {len(prepared)} assets under {args.output_root}", flush=True) + return 0 + + from isaacsim import SimulationApp + + kit = SimulationApp({"headless": args.headless}) + try: + from isaacsim.core.utils.extensions import enable_extension + + enable_extension("omni.kit.asset_converter") + failures = asyncio.get_event_loop().run_until_complete( + convert_outputs(prepared, load_materials=not args.no_materials, overwrite=args.overwrite) + ) + finally: + kit.close() + + print(f"[DONE] prepared={len(prepared)} failed_usd={failures} output_root={args.output_root}", flush=True) + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/third_party/robocasa/tools/robocasa_usd/run_convert_robocasa_objects.sh b/third_party/robocasa/tools/robocasa_usd/run_convert_robocasa_objects.sh new file mode 100644 index 0000000000000000000000000000000000000000..057145ca11f40e1f0488c6f9a4557634063e7446 --- /dev/null +++ b/third_party/robocasa/tools/robocasa_usd/run_convert_robocasa_objects.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail + +ISAAC_SIM_ROOT="${ISAAC_SIM_ROOT:-/mnt/workspace/users/liao/isaac-sim}" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +export OMNI_KIT_ALLOW_ROOT="${OMNI_KIT_ALLOW_ROOT:-1}" + +"${ISAAC_SIM_ROOT}/python.sh" "${SCRIPT_DIR}/convert_robocasa_objects_to_usd.py" "$@" diff --git a/third_party/robosuite/LICENSE b/third_party/robosuite/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e20189628cc282626830a7855edf722de38dc700 --- /dev/null +++ b/third_party/robosuite/LICENSE @@ -0,0 +1,28 @@ +MIT License + +Copyright (c) 2022 Stanford Vision and Learning Lab and UT Robot Perception and Learning Lab + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +This software includes the partial implementation of Deepmind Mujoco https://github.com/deepmind/mujoco. +Deepmind Mujoco is licensed under the Apache License, Version 2.0 (the "License"); +you may not use the files except in compliance with the License. + +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 diff --git a/third_party/robosuite/robosuite/__init__.py b/third_party/robosuite/robosuite/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9cf1965bb725bdcd5022098e26a133cfe52525fc --- /dev/null +++ b/third_party/robosuite/robosuite/__init__.py @@ -0,0 +1,50 @@ +from robosuite.environments.base import make + +# Manipulation environments +from robosuite.environments.manipulation.lift import Lift +from robosuite.environments.manipulation.stack import Stack +from robosuite.environments.manipulation.nut_assembly import NutAssembly +from robosuite.environments.manipulation.pick_place import PickPlace +from robosuite.environments.manipulation.door import Door +from robosuite.environments.manipulation.wipe import Wipe +from robosuite.environments.manipulation.tool_hang import ToolHang +from robosuite.environments.manipulation.two_arm_lift import TwoArmLift +from robosuite.environments.manipulation.two_arm_peg_in_hole import TwoArmPegInHole +from robosuite.environments.manipulation.two_arm_handover import TwoArmHandover +from robosuite.environments.manipulation.two_arm_transport import TwoArmTransport + +from robosuite.environments import ALL_ENVIRONMENTS +from robosuite.controllers import ( + ALL_PART_CONTROLLERS, + load_part_controller_config, + ALL_COMPOSITE_CONTROLLERS, + load_composite_controller_config, +) +from robosuite.robots import ALL_ROBOTS +from robosuite.models.grippers import ALL_GRIPPERS +from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER + +try: + import robosuite_models +except: + ROBOSUITE_DEFAULT_LOGGER.warning( + "Could not import robosuite_models. Some robots may not be available. " + "If you want to use these robots, please install robosuite_models from " + "source (https://github.com/ARISE-Initiative/robosuite_models) or through pip install." + ) + +try: + from robosuite.examples.third_party_controller.mink_controller import WholeBodyMinkIK + +except: + ROBOSUITE_DEFAULT_LOGGER.warning( + "Could not load the mink-based whole-body IK. Make sure you install related import properly, otherwise you will not be able to use the default IK controller setting for GR1 robot." + ) + +__version__ = "1.5.1" +__logo__ = """ + ; / ,--. + ["] ["] ,< |__**| + /[_]\ [~]\/ |// | + ] [ OOO /o|__| +""" diff --git a/third_party/robosuite/robosuite/controllers/__init__.py b/third_party/robosuite/robosuite/controllers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b7817371cc869043f5ec7cd50975c0d5213399b8 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/__init__.py @@ -0,0 +1,15 @@ +from .parts.controller_factory import controller_factory, load_part_controller_config +from .composite import composite_controller_factory, ALL_COMPOSITE_CONTROLLERS +from .composite.composite_controller_factory import load_composite_controller_config + + +PART_CONTROLLER_INFO = { + "JOINT_VELOCITY": "Joint Velocity", + "JOINT_TORQUE": "Joint Torque", + "JOINT_POSITION": "Joint Position", + "OSC_POSITION": "Operational Space Control (Position Only)", + "OSC_POSE": "Operational Space Control (Position + Orientation)", + "IK_POSE": "Inverse Kinematics Control (Position + Orientation) (Note: must have PyBullet installed)", +} + +ALL_PART_CONTROLLERS = PART_CONTROLLER_INFO.keys() diff --git a/third_party/robosuite/robosuite/controllers/composite/__init__.py b/third_party/robosuite/robosuite/controllers/composite/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..84173bb274b326ed0a91294caa04f89da0c827f2 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/composite/__init__.py @@ -0,0 +1,19 @@ +from .composite_controller import CompositeController, HybridMobileBase, WholeBodyIK +from .composite_controller import REGISTERED_COMPOSITE_CONTROLLERS_DICT + +ALL_COMPOSITE_CONTROLLERS = REGISTERED_COMPOSITE_CONTROLLERS_DICT.keys() + + +def composite_controller_factory(type, sim, robot_model, grippers): + assert type in REGISTERED_COMPOSITE_CONTROLLERS_DICT, f"{type} controller is specified, but not imported or loaded" + # Note: Currently we assume that the init arguments are same for all composite controllers. The situation might change given new controllers in the future, and we will adjust accodingly. + + # The default composite controllers are explicitly initialized without using the COMPOSITE_CONTORLLERS + if type == "BASIC": + return CompositeController(sim, robot_model, grippers) + elif type == "HYBRID_MOBILE_BASE": + return HybridMobileBase(sim, robot_model, grippers) + elif type == "WHOLE_BODY_IK": + return WholeBodyIK(sim, robot_model, grippers) + else: + return REGISTERED_COMPOSITE_CONTROLLERS_DICT[type](sim, robot_model, grippers) diff --git a/third_party/robosuite/robosuite/controllers/composite/composite_controller.py b/third_party/robosuite/robosuite/controllers/composite/composite_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..b832827c386ec3499427409e142f46416f723bc1 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/composite/composite_controller.py @@ -0,0 +1,461 @@ +import json +import re +from collections import OrderedDict +from typing import Dict, Optional, Tuple + +import numpy as np + +from robosuite.controllers import controller_factory +from robosuite.models.grippers.gripper_model import GripperModel +from robosuite.models.robots.robot_model import RobotModel +from robosuite.utils.binding_utils import MjSim +from robosuite.utils.ik_utils import IKSolver, get_nullspace_gains +from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER + +REGISTERED_COMPOSITE_CONTROLLERS_DICT = {} + + +def register_composite_controller(target_class): + if not hasattr(target_class, "name"): + ROBOSUITE_DEFAULT_LOGGER.warning( + "The name of the composite controller is not specified. Using the class name as the key." + ) + key = "_".join(re.sub(r"([A-Z0-9])", r" \1", target_class.__name__).split()).upper() + else: + key = target_class.name + REGISTERED_COMPOSITE_CONTROLLERS_DICT[key] = target_class + return target_class + + +@register_composite_controller +class CompositeController: + """This is the parent class for all composite controllers. If you want to develop an advanced version of your controller, you should subclass from this composite controller.""" + + name = "BASIC" + + def __init__(self, sim: MjSim, robot_model: RobotModel, grippers: Dict[str, GripperModel]): + # TODO: grippers repeat with members inside robot_model. Currently having this additioanl field to make naming query easy. + self.sim = sim + self.robot_model = robot_model + + self.grippers = grippers + + self.part_controllers = OrderedDict() + + self._action_split_indexes = OrderedDict() + + self.part_controller_config = None + + self.arms = self.robot_model.arms + + self._applied_action_dict = {} + + def load_controller_config( + self, part_controller_config, composite_controller_specific_config: Optional[Dict] = None + ): + self.composite_controller_specific_config = composite_controller_specific_config + body_part_ordering = self.composite_controller_specific_config.get("body_part_ordering", None) + if body_part_ordering is not None: + self.part_controller_config = OrderedDict() + assert len(body_part_ordering) == len(part_controller_config) + for part_name in body_part_ordering: + self.part_controller_config[part_name] = part_controller_config[part_name] + else: + self.part_controller_config = part_controller_config + + self.part_controllers.clear() + self._action_split_indexes.clear() + self._init_controllers() + self._validate_composite_controller_specific_config() + self.setup_action_split_idx() + + def _init_controllers(self): + for part_name in self.part_controller_config.keys(): + controller_params = self.part_controller_config[part_name] + self.part_controllers[part_name] = controller_factory( + part_name=part_name, + controller_type=self.part_controller_config[part_name]["type"], + controller_params=controller_params, + ) + + def _validate_composite_controller_specific_config(self): + """Some aspects of composite controller specific configs, if they exist, + may only be verified once the part controller are initialized.""" + pass + + def setup_action_split_idx(self): + previous_idx = 0 + last_idx = 0 + for part_name, controller in self.part_controllers.items(): + if part_name in self.grippers.keys(): + last_idx += self.grippers[part_name].dof + else: + last_idx += controller.control_dim + self._action_split_indexes[part_name] = (previous_idx, last_idx) + previous_idx = last_idx + + def set_goal(self, all_action): + for part_name, controller in self.part_controllers.items(): + start_idx, end_idx = self._action_split_indexes[part_name] + action = all_action[start_idx:end_idx] + if part_name in self.grippers.keys(): + action = self.grippers[part_name].format_action(action) + controller.set_goal(action) + + def reset(self): + for part_name, controller in self.part_controllers.items(): + controller.reset_goal() + + def run_controller(self, enabled_parts): + self.update_state() + self._applied_action_dict.clear() + for part_name, controller in self.part_controllers.items(): + if enabled_parts.get(part_name, False): + self._applied_action_dict[part_name] = controller.run_controller() + + return self._applied_action_dict + + def get_control_dim(self, part_name): + if part_name not in self.part_controllers: + return 0 + else: + return self.part_controllers[part_name].control_dim + + def get_controller_base_pose(self, controller_name): + naming_prefix = self.part_controllers[controller_name].naming_prefix + part_name = self.part_controllers[controller_name].part_name + base_pos = np.array(self.sim.data.site_xpos[self.sim.model.site_name2id(f"{naming_prefix}{part_name}_center")]) + base_ori = np.array( + self.sim.data.site_xmat[self.sim.model.site_name2id(f"{naming_prefix}{part_name}_center")].reshape([3, 3]) + ) + return base_pos, base_ori + + def update_state(self): + for arm in self.arms: + base_pos, base_ori = self.get_controller_base_pose(controller_name=arm) + self.part_controllers[arm].update_origin(base_pos, base_ori) + + def get_controller(self, part_name): + return self.part_controllers[part_name] + + @property + def action_limits(self): + low, high = [], [] + for part_name, controller in self.part_controllers.items(): + if part_name not in self.arms: + if part_name in self.grippers.keys(): + low_g, high_g = ([-1] * self.grippers[part_name].dof, [1] * self.grippers[part_name].dof) + low, high = np.concatenate([low, low_g]), np.concatenate([high, high_g]) + else: + control_dim = controller.control_dim + low_c, high_c = ([-1] * control_dim, [1] * control_dim) + low, high = np.concatenate([low, low_c]), np.concatenate([high, high_c]) + else: + low_c, high_c = controller.control_limits + low, high = np.concatenate([low, low_c]), np.concatenate([high, high_c]) + return low, high + + +@register_composite_controller +class HybridMobileBase(CompositeController): + name = "HYBRID_MOBILE_BASE" + + def set_goal(self, all_action): + action_mode = all_action[-1] + if action_mode > 0: + update_wrt_origin = True + else: + update_wrt_origin = False + + for part_name, controller in self.part_controllers.items(): + start_idx, end_idx = self._action_split_indexes[part_name] + action = all_action[start_idx:end_idx] + if part_name in self.grippers.keys(): + action = self.grippers[part_name].format_action(action) + + if part_name in self.arms and hasattr(controller, "set_goal_update_mode"): + """ + Query the last action dimension to determine if using + base mode (value > 0) or arm mode (value < 1). + If in base mode, update the new arm goal based on current desired goal, + to have the arm tracking with the reset of the moving base + as closely as possible without lagging or overshooting. + """ + action_mode = all_action[-1] + if action_mode > 0: + goal_update_mode = "desired" + else: + goal_update_mode = "achieved" + controller.set_goal_update_mode(goal_update_mode) + + controller.set_goal(action) + + @property + def action_limits(self): + low, high = super().action_limits + return np.concatenate((low, [-1])), np.concatenate((high, [1])) + + def create_action_vector(self, action_dict): + """ + A helper function that creates the action vector given a dictionary + """ + full_action_vector = np.zeros(self.action_limits[0].shape) + for (part_name, action_vector) in action_dict.items(): + if part_name not in self._action_split_indexes: + ROBOSUITE_DEFAULT_LOGGER.debug(f"{part_name} is not specified in the action space") + continue + start_idx, end_idx = self._action_split_indexes[part_name] + if end_idx - start_idx == 0: + # skipping not controlling actions + continue + assert len(action_vector) == (end_idx - start_idx), ROBOSUITE_DEFAULT_LOGGER.error( + f"Action vector for {part_name} is not the correct size. Expected {end_idx - start_idx} for {part_name}, got {len(action_vector)}" + ) + full_action_vector[start_idx:end_idx] = action_vector + full_action_vector[-1] = action_dict.get("base_mode", -1) + return full_action_vector + + +@register_composite_controller +class WholeBody(CompositeController): + name = "WHOLE_BODY_COMPOSITE" + + def __init__(self, sim: MjSim, robot_model: RobotModel, grippers: Dict[str, GripperModel]): + super().__init__(sim, robot_model, grippers) + + self.joint_action_policy: IKSolver = None + # TODO: handle different types of joint action policies; joint_action_policy maps + # task space actions (such as end effector poses) to joint actions (such as joint angles or joint torques) + + self._whole_body_controller_action_split_indexes: OrderedDict = OrderedDict() + + def _init_controllers(self): + for part_name in self.part_controller_config.keys(): + controller_params = self.part_controller_config[part_name] + self.part_controllers[part_name] = controller_factory( + part_name=part_name, + controller_type=self.part_controller_config[part_name]["type"], + controller_params=controller_params, + ) + # for whole body composite controller, validate before init_joint_action_policy + self._validate_composite_controller_specific_config() + self._init_joint_action_policy() + + def _init_joint_action_policy(self): + """Joint action policy initialization. + + Joint action policy converts input targets (such as end-effector poses, head poses) to joint actions + (such as joint angles or joint torques). + + Examples of joint_action_policy could be an IK policy, a neural network policy, a model predictive controller, etc. + """ + raise NotImplementedError("WholeBody CompositeController requires a joint action policy") + + def setup_action_split_idx(self): + """ + Action split indices for the underlying factorized controllers. + + WholeBody controller takes in a different action space from the + underlying factorized controllers for individual body parts. + """ + previous_idx = 0 + last_idx = 0 + # add joint_action_policy related body parts' action split index first + for part_name in self.composite_controller_specific_config["actuation_part_names"]: + try: + last_idx += self.part_controllers[part_name].control_dim + except KeyError as e: + import ipdb + + ipdb.set_trace() + raise KeyError(f"Part name '{part_name}' not found in part_controllers: {e}") + self._action_split_indexes[part_name] = (previous_idx, last_idx) + previous_idx = last_idx + + for part_name, controller in self.part_controllers.items(): + if part_name not in self.composite_controller_specific_config["actuation_part_names"]: + if part_name in self.grippers.keys(): + last_idx += self.grippers[part_name].dof + else: + last_idx += controller.control_dim + self._action_split_indexes[part_name] = (previous_idx, last_idx) + previous_idx = last_idx + + self.setup_whole_body_controller_action_split_idx() + + def setup_whole_body_controller_action_split_idx(self): + """ + Action split indices for the composite controller's input action space. + + WholeBodyIK composite controller takes in a different action space from the + underlying factorized controllers. + """ + # add joint_action_policy's action split indexes first + self._whole_body_controller_action_split_indexes.update(self.joint_action_policy.action_split_indexes()) + + # prev and last index correspond to the IK solver indexes' last index + previous_idx = last_idx = list(self._whole_body_controller_action_split_indexes.values())[-1][-1] + for part_name, controller in self.part_controllers.items(): + if part_name in self.composite_controller_specific_config["actuation_part_names"]: + continue + if part_name in self.grippers.keys(): + last_idx += self.grippers[part_name].dof + else: + last_idx += controller.control_dim + self._whole_body_controller_action_split_indexes[part_name] = (previous_idx, last_idx) + previous_idx = last_idx + + def set_goal(self, all_action): + target_qpos = self.joint_action_policy.solve(all_action[: self.joint_action_policy.control_dim]) + # create new all_action vector with the IK solver's actions first + all_action = np.concatenate([target_qpos, all_action[self.joint_action_policy.control_dim :]]) + for part_name, controller in self.part_controllers.items(): + start_idx, end_idx = self._action_split_indexes[part_name] + action = all_action[start_idx:end_idx] + if part_name in self.grippers.keys(): + action = self.grippers[part_name].format_action(action) + controller.set_goal(action) + + def update_state(self): + # no need for extra update state here, since Jacobians are computed inside the controllers of individual body parts + return + + @property + def action_limits(self): + """ + Returns the action limits for the whole body controller. + Corresponds to each term in the action vector passed to env.step(). + """ + low, high = [], [] + # assumption: IK solver's actions come first + low_c, high_c = self.joint_action_policy.control_limits + low, high = np.concatenate([low, low_c]), np.concatenate([high, high_c]) + for part_name, controller in self.part_controllers.items(): + # Exclude terms that the IK solver handles + if part_name in self.composite_controller_specific_config["actuation_part_names"]: + continue + if part_name not in self.arms: + if part_name in self.grippers.keys(): + low_g, high_g = ([-1] * self.grippers[part_name].dof, [1] * self.grippers[part_name].dof) + low, high = np.concatenate([low, low_g]), np.concatenate([high, high_g]) + else: + control_dim = controller.control_dim + low_c, high_c = ([-1] * control_dim, [1] * control_dim) + low, high = np.concatenate([low, low_c]), np.concatenate([high, high_c]) + else: + low_c, high_c = controller.control_limits + low, high = np.concatenate([low, low_c]), np.concatenate([high, high_c]) + return low, high + + def create_action_vector(self, action_dict: Dict[str, np.ndarray]) -> np.ndarray: + full_action_vector = np.zeros(self.action_limits[0].shape) + for (part_name, action_vector) in action_dict.items(): + if part_name not in self._whole_body_controller_action_split_indexes: + ROBOSUITE_DEFAULT_LOGGER.debug(f"{part_name} is not specified in the action space") + continue + start_idx, end_idx = self._whole_body_controller_action_split_indexes[part_name] + if end_idx - start_idx == 0: + # skipping not controlling actions + continue + assert len(action_vector) == (end_idx - start_idx), ROBOSUITE_DEFAULT_LOGGER.error( + f"Action vector for {part_name} is not the correct size. Expected {end_idx - start_idx} for {part_name}, got {len(action_vector)}" + ) + full_action_vector[start_idx:end_idx] = action_vector + return full_action_vector + + def print_action_info(self): + action_index_info = [] + action_dim_info = [] + for part_name, (start_idx, end_idx) in self._whole_body_controller_action_split_indexes.items(): + action_dim_info.append(f"{part_name}: {(end_idx - start_idx)} dim") + action_index_info.append(f"{part_name}: {start_idx}:{end_idx}") + + action_dim_info_str = ", ".join(action_dim_info) + ROBOSUITE_DEFAULT_LOGGER.info(f"Action Dimensions: [{action_dim_info_str}]") + + action_index_info_str = ", ".join(action_index_info) + ROBOSUITE_DEFAULT_LOGGER.info(f"Action Indices: [{action_index_info_str}]") + + def print_action_info_dict(self, name: str = ""): + info_dict = {} + info_dict["Action Dimension"] = self.action_limits[0].shape + info_dict.update(dict(self._whole_body_controller_action_split_indexes)) + + info_dict_str = f"\nAction Info for {name}:\n\n{json.dumps(dict(info_dict), indent=4)}" + ROBOSUITE_DEFAULT_LOGGER.info(info_dict_str) + + +@register_composite_controller +class WholeBodyIK(WholeBody): + name = "WHOLE_BODY_IK" + + def __init__(self, sim: MjSim, robot_model: RobotModel, grippers: Dict[str, GripperModel]): + super().__init__(sim, robot_model, grippers) + + def _validate_composite_controller_specific_config(self) -> None: + # Check that all actuation_part_names exist in part_controllers + original_ik_controlled_parts = self.composite_controller_specific_config["actuation_part_names"] + self.valid_ik_controlled_parts = [] + valid_ref_names = [] + + assert ( + "ref_name" in self.composite_controller_specific_config + ), "The 'ref_name' key is missing from composite_controller_specific_config." + + for part in original_ik_controlled_parts: + if part in self.part_controllers: + self.valid_ik_controlled_parts.append(part) + else: + ROBOSUITE_DEFAULT_LOGGER.warning( + f"Part '{part}' specified in 'actuation_part_names' " + "does not exist in part_controllers. Removing ..." + ) + + # Update the configuration with only the valid parts + self.composite_controller_specific_config["actuation_part_names"] = self.valid_ik_controlled_parts + + # Loop through ref_names and validate against mujoco model + original_ref_names = self.composite_controller_specific_config.get("ref_name", []) + for ref_name in original_ref_names: + if ref_name in self.sim.model.site_names: # Check if the site exists in the mujoco model + valid_ref_names.append(ref_name) + else: + ROBOSUITE_DEFAULT_LOGGER.warning( + f"Reference name '{ref_name}' specified in configuration" + " does not exist in the mujoco model. Removing ..." + ) + + # Update the configuration with only the valid reference names + self.composite_controller_specific_config["ref_name"] = valid_ref_names + + def _init_joint_action_policy(self): + joint_names: str = [] + for part_name in self.composite_controller_specific_config["actuation_part_names"]: + if part_name in self.part_controllers: + joint_names += self.part_controllers[part_name].joint_names + else: + ROBOSUITE_DEFAULT_LOGGER.warning( + f"{part_name} is not a valid part name in part_controllers." " Skipping this part for IK control." + ) + + # Compute nullspace gains, Kn. + Kn = get_nullspace_gains(joint_names, self.composite_controller_specific_config["nullspace_joint_weights"]) + mocap_bodies = [] + robot_config = { + "end_effector_sites": self.composite_controller_specific_config["ref_name"], + "joint_names": joint_names, + "mocap_bodies": mocap_bodies, + "nullspace_gains": Kn, + } + self.joint_action_policy = IKSolver( + model=self.sim.model._model, + data=self.sim.data._data, + robot_config=robot_config, + damping=self.composite_controller_specific_config.get("ik_pseudo_inverse_damping", 5e-2), + integration_dt=self.composite_controller_specific_config.get("ik_integration_dt", 0.1), + max_dq=self.composite_controller_specific_config.get("ik_max_dq", 4), + max_dq_torso=self.composite_controller_specific_config.get("ik_max_dq_torso", 0.2), + input_rotation_repr=self.composite_controller_specific_config.get("ik_input_rotation_repr", "axis_angle"), + input_type=self.composite_controller_specific_config.get("ik_input_type", "axis_angle"), + debug=self.composite_controller_specific_config.get("verbose", False), + ) diff --git a/third_party/robosuite/robosuite/controllers/composite/composite_controller_factory.py b/third_party/robosuite/robosuite/controllers/composite/composite_controller_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..cdb4bc27acde0356556e9f7da578a64bdd698bcc --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/composite/composite_controller_factory.py @@ -0,0 +1,156 @@ +import copy +import json +import os +import pathlib +from typing import Dict, Literal, Optional + +import robosuite +from robosuite.controllers.composite.composite_controller import REGISTERED_COMPOSITE_CONTROLLERS_DICT +from robosuite.controllers.parts.controller_factory import load_part_controller_config +from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER + + +def validate_composite_controller_config(config: dict): + # Check top-level keys + required_keys = ["type", "body_parts"] + for key in required_keys: + if key not in config: + ROBOSUITE_DEFAULT_LOGGER.error(f"Missing top-level key: {key}") + raise ValueError + + +def is_part_controller_config(config: Dict): + """ + Checks if a controller config is a part config as a opposed to a composite + controller config. + + Args: + config (dict): Controller configuration + + Returns: + bool: True if the config is in the for the arm-only, False otherwise + """ + + PART_CONTROLLER_TYPES = ["JOINT_VELOCITY", "JOINT_TORQUE", "JOINT_POSITION", "OSC_POSITION", "OSC_POSE", "IK_POSE"] + if "body_parts" not in config and "type" in config: + return config["type"] in PART_CONTROLLER_TYPES + return False + + +def refactor_composite_controller_config(controller_config, robot_type, arms): + """ + Checks if a controller config is in the format from robosuite versions <= 1.4.1. + If this is the case, converts the controller config to the new composite controller + config format in robosuite versions >= 1.5. If the robot has a default + controller config use that and override the arms with the old controller config. + If not just use the old controller config for arms. + + Args: + old_controller_config (dict): Old controller config + + Returns: + dict: New controller config + """ + if not is_part_controller_config(controller_config): + return controller_config + + config_dir = pathlib.Path(robosuite.__file__).parent / "controllers/config/robots/" + name = robot_type.lower() + configs = os.listdir(config_dir) + if f"default_{name}.json" in configs: + new_controller_config = load_composite_controller_config(robot=name) + else: + new_controller_config = {} + new_controller_config["type"] = "BASIC" + new_controller_config["body_parts"] = {} + + for arm in arms: + new_controller_config["body_parts"][arm] = copy.deepcopy(controller_config) + new_controller_config["body_parts"][arm]["gripper"] = {"type": "GRIP"} + return new_controller_config + + +def load_composite_controller_config(controller: Optional[str] = None, robot: Optional[str] = None) -> Optional[Dict]: + """ + Utility function that loads the desired composite controller and returns the loaded configuration as a dict + + Args: + controller: Name or path of the controller to load. + If None, robot must be specified and we load the robot's default controller in controllers/config/robots/. + If specified, must be a valid controller name or path to a controller config file. + robot: Name of the robot to load the controller for. + + Returns: + dict: Controller configuration + + Raises: + FileNotFoundError: If the controller file is not found + """ + # Determine the controller file path + if controller is None: + assert robot is not None, "If controller is None, robot must be specified." + # Load robot's controller + robot_name = _get_robot_name(robot) + controller_fpath = ( + pathlib.Path(robosuite.__file__).parent / f"controllers/config/robots/default_{robot_name}.json" + ) + if not os.path.exists(controller_fpath): + controller_fpath = ( + pathlib.Path(robosuite.__file__).parent / "controllers/config/default/composite/basic.json" + ) + elif isinstance(controller, str): + if controller.endswith(".json"): + # Use the specified path directly + controller_fpath = controller + else: + assert ( + controller in REGISTERED_COMPOSITE_CONTROLLERS_DICT + ), f"Controller {controller} not found in COMPOSITE_CONTROLLERS_DICT" + # Load from robosuite/controllers/config/default/composite/ + controller_name = controller.lower() + controller_fpath = ( + pathlib.Path(robosuite.__file__).parent / f"controllers/config/default/composite/{controller_name}.json" + ) + else: + raise ValueError("Controller must be None or a string.") + + # Attempt to load the controller + try: + with open(controller_fpath) as f: + composite_controller_config = json.load(f) + ROBOSUITE_DEFAULT_LOGGER.info(f"Loading controller configuration from: {controller_fpath}") + except FileNotFoundError: + ROBOSUITE_DEFAULT_LOGGER.error( + f"Error opening controller filepath at: {controller_fpath}. Please check filepath and try again." + ) + raise + + validate_composite_controller_config(composite_controller_config) + body_parts_controller_configs = composite_controller_config.pop("body_parts", {}) + composite_controller_config["body_parts"] = {} + for part_name, part_config in body_parts_controller_configs.items(): + if part_name == "arms": + for arm_name, arm_config in part_config.items(): + composite_controller_config["body_parts"][arm_name] = arm_config + else: + composite_controller_config["body_parts"][part_name] = part_config + + return composite_controller_config + + +def _get_robot_name(robot: str) -> str: + """Helper function to get the standardized robot name.""" + if "GR1FloatingBody" in robot: + return "gr1_floating_body" + elif "GR1FixedLowerBody" in robot: + return "gr1_fixed_lower_body" + elif "GR1" in robot: + return "gr1" + elif "G1" in robot: + return "g1" + elif "H1" in robot: + return "h1" + elif "PandaDex" in robot: + return "panda_dex" + else: + return robot.lower() diff --git a/third_party/robosuite/robosuite/controllers/config/default/composite/basic.json b/third_party/robosuite/robosuite/controllers/config/default/composite/basic.json new file mode 100644 index 0000000000000000000000000000000000000000..90b9debb5fbb59a3d8ce70e3c68b69efdd63aa24 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/default/composite/basic.json @@ -0,0 +1,97 @@ +{ + "type": "BASIC", + "body_parts": { + "arms": { + "right": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + }, + "left": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + } + }, + "torso": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + }, + "head": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + }, + "base": { + "type": "JOINT_VELOCITY", + "interpolation": "null" + }, + "legs": { + "type": "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/default/composite/hybrid_mobile_base.json b/third_party/robosuite/robosuite/controllers/config/default/composite/hybrid_mobile_base.json new file mode 100644 index 0000000000000000000000000000000000000000..9cd02317a1c07d20cf3232892ed065993e4c1ba1 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/default/composite/hybrid_mobile_base.json @@ -0,0 +1,97 @@ +{ + "type": "HYBRID_MOBILE_BASE", + "body_parts": { + "arms": { + "right": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + }, + "left": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + } + }, + "torso": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + }, + "head": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + }, + "base": { + "type": "JOINT_VELOCITY", + "interpolation": "null" + }, + "legs": { + "type": "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/default/composite/whole_body_ik.json b/third_party/robosuite/robosuite/controllers/config/default/composite/whole_body_ik.json new file mode 100644 index 0000000000000000000000000000000000000000..2a8219fc42231d322340fe3dd41a12b2f247c3dc --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/default/composite/whole_body_ik.json @@ -0,0 +1,115 @@ +{ + "type": "WHOLE_BODY_IK", + "composite_controller_specific_configs": { + "ref_name": ["gripper0_right_grip_site", "gripper0_left_grip_site"], + "interpolation": null, + "actuation_part_names": ["torso", "head", "right", "left", "base", "legs"], + "max_dq": 4, + "nullspace_joint_weights": { + "robot0_torso_waist_yaw": 100.0, + "robot0_torso_waist_pitch": 100.0, + "robot0_torso_waist_roll": 500.0, + "robot0_l_shoulder_pitch": 4.0, + "robot0_r_shoulder_pitch": 4.0, + "robot0_l_shoulder_roll": 3.0, + "robot0_r_shoulder_roll": 3.0, + "robot0_l_shoulder_yaw": 2.0, + "robot0_r_shoulder_yaw": 2.0 + }, + "ik_pseudo_inverse_damping": 5e-2, + "ik_integration_dt": 1e-1, + "ik_max_dq": 4.0, + "ik_max_dq_torso": 0.2, + "ik_input_type": "absolute", + "ik_input_rotation_repr": "axis_angle", + "verbose": false + }, + "body_parts": { + "arms": { + "right": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + }, + "left": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + } + }, + "torso": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + }, + "head": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + }, + "base": { + "type" : "JOINT_VELOCITY", + "interpolation": null + }, + "legs": { + "type": "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/default/composite/whole_body_mink_ik.json b/third_party/robosuite/robosuite/controllers/config/default/composite/whole_body_mink_ik.json new file mode 100644 index 0000000000000000000000000000000000000000..1090ab3cb83f705decf23c1a0351846adf9bd936 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/default/composite/whole_body_mink_ik.json @@ -0,0 +1,101 @@ +{ + "type": "WHOLE_BODY_MINK_IK", + "composite_controller_specific_configs": { + "ref_name": ["gripper0_right_grip_site", "gripper0_left_grip_site"], + "interpolation": null, + "actuation_part_names": ["torso", "head", "right", "left"], + "max_dq": 4, + "ik_pseudo_inverse_damping": 5e-2, + "ik_integration_dt": 1e-1, + "ik_input_type": "absolute", + "ik_input_ref_frame": "world", + "ik_input_rotation_repr": "axis_angle", + "verbose": false, + "ik_posture_weights": { + "robot0_torso_waist_yaw": 10.0, + "robot0_torso_waist_pitch": 10.0, + "robot0_torso_waist_roll": 200.0, + "robot0_l_shoulder_pitch": 4.0, + "robot0_r_shoulder_pitch": 4.0, + "robot0_l_shoulder_roll": 3.0, + "robot0_r_shoulder_roll": 3.0, + "robot0_l_shoulder_yaw": 2.0, + "robot0_r_shoulder_yaw": 2.0 + }, + "ik_hand_pos_cost": 1.0, + "ik_hand_ori_cost": 0.5, + "use_joint_angle_action_input": false + }, + "body_parts": { + "arms": { + "right": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP", + "use_action_scaling": false + } + }, + "left": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP", + "use_action_scaling": false + } + } + }, + "torso": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + }, + "head": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + } + } +} diff --git a/third_party/robosuite/robosuite/controllers/config/default/parts/ik_pose.json b/third_party/robosuite/robosuite/controllers/config/default/parts/ik_pose.json new file mode 100644 index 0000000000000000000000000000000000000000..39c4346c6de1bc01ec8828497be3602a6f80b6b8 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/default/parts/ik_pose.json @@ -0,0 +1,7 @@ +{ + "type" : "IK_POSE", + "ik_pos_limit": 0.02, + "ik_ori_limit": 0.05, + "interpolation": null, + "ramp_ratio": 0.2 + } diff --git a/third_party/robosuite/robosuite/controllers/config/default/parts/joint_position.json b/third_party/robosuite/robosuite/controllers/config/default/parts/joint_position.json new file mode 100644 index 0000000000000000000000000000000000000000..e0539cc5aeb1a2d22b36c87d801792582350af14 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/default/parts/joint_position.json @@ -0,0 +1,15 @@ +{ + "type": "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "output_max": 0.05, + "output_min": -0.05, + "kp": 50, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "qpos_limits": null, + "interpolation": null, + "ramp_ratio": 0.2 + } diff --git a/third_party/robosuite/robosuite/controllers/config/default/parts/joint_torque.json b/third_party/robosuite/robosuite/controllers/config/default/parts/joint_torque.json new file mode 100644 index 0000000000000000000000000000000000000000..320c808af045d22a8748a4a6f4d02467e2a5c7ae --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/default/parts/joint_torque.json @@ -0,0 +1,10 @@ +{ + "type": "JOINT_TORQUE", + "input_max": 1, + "input_min": -1, + "output_max": 0.1, + "output_min": -0.1, + "torque_limits": null, + "interpolation": null, + "ramp_ratio": 0.2 + } diff --git a/third_party/robosuite/robosuite/controllers/config/default/parts/joint_velocity.json b/third_party/robosuite/robosuite/controllers/config/default/parts/joint_velocity.json new file mode 100644 index 0000000000000000000000000000000000000000..1b06e82f639871990d4d8d529cb1d6d78b00605a --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/default/parts/joint_velocity.json @@ -0,0 +1,11 @@ +{ + "type" : "JOINT_VELOCITY", + "input_max": 1, + "input_min": -1, + "output_max": 0.5, + "output_min": -0.5, + "kp": 3.0, + "velocity_limits": [-1,1], + "interpolation": null, + "ramp_ratio": 0.2 + } diff --git a/third_party/robosuite/robosuite/controllers/config/default/parts/osc_pose.json b/third_party/robosuite/robosuite/controllers/config/default/parts/osc_pose.json new file mode 100644 index 0000000000000000000000000000000000000000..8cd29dfaec3c5410ea3701690d3545a80371aecc --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/default/parts/osc_pose.json @@ -0,0 +1,19 @@ +{ + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2 + } diff --git a/third_party/robosuite/robosuite/controllers/config/default/parts/osc_position.json b/third_party/robosuite/robosuite/controllers/config/default/parts/osc_position.json new file mode 100644 index 0000000000000000000000000000000000000000..42b314a792250b1312fcbae7bd1aff6c91a8b4b4 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/default/parts/osc_position.json @@ -0,0 +1,17 @@ +{ + "type": "OSC_POSITION", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05], + "output_min": [-0.05, -0.05, -0.05], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2 + } diff --git a/third_party/robosuite/robosuite/controllers/config/robots/default_baxter.json b/third_party/robosuite/robosuite/controllers/config/robots/default_baxter.json new file mode 100644 index 0000000000000000000000000000000000000000..d4aabf808084a28c768652cb9dd865e24175521a --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/robots/default_baxter.json @@ -0,0 +1,51 @@ +{ + "type": "BASIC", + "body_parts": { + "arms": { + "right": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + }, + "left": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + } + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/robots/default_gr1.json b/third_party/robosuite/robosuite/controllers/config/robots/default_gr1.json new file mode 100644 index 0000000000000000000000000000000000000000..7172e1fc952c0bb5dc2982ecdc5f9fe7093d864c --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/robots/default_gr1.json @@ -0,0 +1,118 @@ +{ + "type": "WHOLE_BODY_IK", + "composite_controller_specific_configs": { + "ref_name": ["gripper0_right_grip_site", "gripper0_left_grip_site"], + "interpolation": null, + "actuation_part_names": ["torso", "head", "right", "left", "base", "legs"], + "max_dq": 4, + "nullspace_joint_weights": { + "robot0_torso_waist_yaw": 100.0, + "robot0_torso_waist_pitch": 100.0, + "robot0_torso_waist_roll": 500.0, + "robot0_l_shoulder_pitch": 4.0, + "robot0_r_shoulder_pitch": 4.0, + "robot0_l_shoulder_roll": 3.0, + "robot0_r_shoulder_roll": 3.0, + "robot0_l_shoulder_yaw": 2.0, + "robot0_r_shoulder_yaw": 2.0 + }, + "ik_pseudo_inverse_damping": 5e-2, + "ik_integration_dt": 1e-1, + "ik_max_dq": 4.0, + "ik_max_dq_torso": 0.2, + "ik_input_type": "absolute", + "ik_input_ref_frame": "base", + "ik_input_rotation_repr": "axis_angle", + "ik_verbose": true + }, + "body_parts": { + "arms": { + "right": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP", + "use_action_scaling": false + } + }, + "left": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP", + "use_action_scaling": false + } + } + }, + "torso": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + }, + "head": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + }, + "base": { + "type": "JOINT_VELOCITY", + "interpolation": "null" + }, + "legs": { + "type": "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/robots/default_gr1_fixed_lower_body.json b/third_party/robosuite/robosuite/controllers/config/robots/default_gr1_fixed_lower_body.json new file mode 100644 index 0000000000000000000000000000000000000000..eefa6c95096eeeb5b8ed8000b5eb9baf2a9de8c9 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/robots/default_gr1_fixed_lower_body.json @@ -0,0 +1,101 @@ +{ + "type": "WHOLE_BODY_MINK_IK", + "composite_controller_specific_configs": { + "ref_name": ["gripper0_right_grip_site", "gripper0_left_grip_site"], + "interpolation": null, + "actuation_part_names": ["torso", "head", "right", "left"], + "max_dq": 4, + "ik_pseudo_inverse_damping": 5e-2, + "ik_integration_dt": 1e-1, + "ik_input_type": "absolute", + "ik_input_ref_frame": "base", + "ik_input_rotation_repr": "axis_angle", + "verbose": false, + "ik_posture_weights": { + "robot0_torso_waist_yaw": 10.0, + "robot0_torso_waist_pitch": 10.0, + "robot0_torso_waist_roll": 200.0, + "robot0_l_shoulder_pitch": 4.0, + "robot0_r_shoulder_pitch": 4.0, + "robot0_l_shoulder_roll": 3.0, + "robot0_r_shoulder_roll": 3.0, + "robot0_l_shoulder_yaw": 2.0, + "robot0_r_shoulder_yaw": 2.0 + }, + "ik_hand_pos_cost": 1.0, + "ik_hand_ori_cost": 0.5, + "use_joint_angle_action_input": false + }, + "body_parts": { + "arms": { + "right": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP", + "use_action_scaling": false + } + }, + "left": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP", + "use_action_scaling": false + } + } + }, + "torso": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + }, + "head": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + } + } +} diff --git a/third_party/robosuite/robosuite/controllers/config/robots/default_gr1_floating_body.json b/third_party/robosuite/robosuite/controllers/config/robots/default_gr1_floating_body.json new file mode 100644 index 0000000000000000000000000000000000000000..ec94e0069220ac069fed5f45f9ca0bdad50d5277 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/robots/default_gr1_floating_body.json @@ -0,0 +1,65 @@ +{ + "type": "HYBRID_MOBILE_BASE", + "body_parts": { + "arms": { + "right": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP", + "use_action_scaling": false + } + }, + "left": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP", + "use_action_scaling": false + } + } + }, + "torso": { + "type": "JOINT_POSITION", + "interpolation": "null" + }, + "head": { + "type": "JOINT_POSITION", + "interpolation": "null" + }, + "base": { + "type": "JOINT_VELOCITY", + "interpolation": "null" + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/robots/default_iiwa.json b/third_party/robosuite/robosuite/controllers/config/robots/default_iiwa.json new file mode 100644 index 0000000000000000000000000000000000000000..1369e01a423e446f10ff81ee5801e0dae4bf0456 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/robots/default_iiwa.json @@ -0,0 +1,29 @@ +{ + "type": "BASIC", + "body_parts": { + "arms": { + "right": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + } + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/robots/default_kinova3.json b/third_party/robosuite/robosuite/controllers/config/robots/default_kinova3.json new file mode 100644 index 0000000000000000000000000000000000000000..1369e01a423e446f10ff81ee5801e0dae4bf0456 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/robots/default_kinova3.json @@ -0,0 +1,29 @@ +{ + "type": "BASIC", + "body_parts": { + "arms": { + "right": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + } + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/robots/default_panda.json b/third_party/robosuite/robosuite/controllers/config/robots/default_panda.json new file mode 100644 index 0000000000000000000000000000000000000000..1369e01a423e446f10ff81ee5801e0dae4bf0456 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/robots/default_panda.json @@ -0,0 +1,29 @@ +{ + "type": "BASIC", + "body_parts": { + "arms": { + "right": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + } + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/robots/default_panda_dex.json b/third_party/robosuite/robosuite/controllers/config/robots/default_panda_dex.json new file mode 100644 index 0000000000000000000000000000000000000000..4655e30e1fba865fff8948eeab1a752b69e5b354 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/robots/default_panda_dex.json @@ -0,0 +1,30 @@ +{ + "type": "BASIC", + "body_parts": { + "arms": { + "right": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP", + "use_action_scaling": false + } + } + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/robots/default_pandaomron.json b/third_party/robosuite/robosuite/controllers/config/robots/default_pandaomron.json new file mode 100644 index 0000000000000000000000000000000000000000..bbe7ed9effebf21df3338b85d213fdcd9789d6c5 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/robots/default_pandaomron.json @@ -0,0 +1,38 @@ +{ + "type": "HYBRID_MOBILE_BASE", + "body_parts": { + "arms": { + "right": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + } + }, + "torso": { + "type": "JOINT_POSITION", + "interpolation": "null", + "kp": 2000 + }, + "base": { + "type": "JOINT_VELOCITY", + "interpolation": "null" + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/robots/default_sawyer.json b/third_party/robosuite/robosuite/controllers/config/robots/default_sawyer.json new file mode 100644 index 0000000000000000000000000000000000000000..1369e01a423e446f10ff81ee5801e0dae4bf0456 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/robots/default_sawyer.json @@ -0,0 +1,29 @@ +{ + "type": "BASIC", + "body_parts": { + "arms": { + "right": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + } + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/robots/default_spotwitharm.json b/third_party/robosuite/robosuite/controllers/config/robots/default_spotwitharm.json new file mode 100644 index 0000000000000000000000000000000000000000..25438e5d414d5fb8b1536456ee9233292711626b --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/robots/default_spotwitharm.json @@ -0,0 +1,43 @@ +{ + "type": "BASIC", + "body_parts": { + "arms": { + "right": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + } + }, + "legs": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/robots/default_tiago.json b/third_party/robosuite/robosuite/controllers/config/robots/default_tiago.json new file mode 100644 index 0000000000000000000000000000000000000000..d2bfe8a804bc83c86c968349d4c8bf37519ec13b --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/robots/default_tiago.json @@ -0,0 +1,101 @@ +{ + "type": "BASIC", + "composite_controller_specific_configs": { + "ref_name": ["gripper0_right_grip_site", "gripper0_left_grip_site"], + "interpolation": null, + "max_dq": 4, + "nullspace_joint_weights": { + "robot0_torso_lift_joint": 100.0 + }, + "ik_pseudo_inverse_damping": 5e-2, + "ik_integration_dt": 1e-1, + "ik_max_dq": 4.0, + "ik_max_dq_torso": 0.2, + "ik_input_type": "absolute", + "ik_input_ref_frame": "base", + "ik_input_rotation_repr": "axis_angle", + "verbose": false + }, + "body_parts": { + "arms": { + "right": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + }, + "left": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + } + }, + "torso": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + }, + "head": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + }, + "base": { + "type": "JOINT_VELOCITY", + "interpolation": "null" + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/robots/default_tiago_whole_body_ik.json b/third_party/robosuite/robosuite/controllers/config/robots/default_tiago_whole_body_ik.json new file mode 100644 index 0000000000000000000000000000000000000000..354e9f1851332f58e7165fbd59b156a98ab62653 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/robots/default_tiago_whole_body_ik.json @@ -0,0 +1,92 @@ +{ + "type": "WHOLE_BODY_IK", + "composite_controller_specific_configs": { + "ref_name": ["gripper0_right_grip_site", "gripper0_left_grip_site"], + "interpolation": null, + "actuation_part_names": ["torso", "head", "right", "left"], + "max_dq": 4, + "nullspace_joint_weights": { + "robot0_torso_lift_joint": 100.0 + }, + "ik_pseudo_inverse_damping": 5e-2, + "ik_integration_dt": 1e-1, + "ik_max_dq": 4.0, + "ik_max_dq_torso": 0.2, + "ik_input_rotation_repr": "axis_angle", + "verbose": false + }, + "body_parts": { + "arms": { + "right": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + }, + "left": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + } + }, + "torso": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + }, + "head": { + "type" : "JOINT_POSITION", + "input_max": 1, + "input_min": -1, + "input_type": "absolute", + "output_max": 0.5, + "output_min": -0.5, + "kd": 200, + "kv": 200, + "kp": 1000, + "velocity_limits": [-1,1], + "kp_limits": [0, 1000], + "interpolation": null, + "ramp_ratio": 0.2 + }, + "base": { + "type": "JOINT_VELOCITY", + "interpolation": "null" + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/config/robots/default_ur5e.json b/third_party/robosuite/robosuite/controllers/config/robots/default_ur5e.json new file mode 100644 index 0000000000000000000000000000000000000000..1369e01a423e446f10ff81ee5801e0dae4bf0456 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/config/robots/default_ur5e.json @@ -0,0 +1,29 @@ +{ + "type": "BASIC", + "body_parts": { + "arms": { + "right": { + "type": "OSC_POSE", + "input_max": 1, + "input_min": -1, + "output_max": [0.05, 0.05, 0.05, 0.5, 0.5, 0.5], + "output_min": [-0.05, -0.05, -0.05, -0.5, -0.5, -0.5], + "kp": 150, + "damping_ratio": 1, + "impedance_mode": "fixed", + "kp_limits": [0, 300], + "damping_ratio_limits": [0, 10], + "position_limits": null, + "orientation_limits": null, + "uncouple_pos_ori": true, + "input_type": "delta", + "input_ref_frame": "base", + "interpolation": null, + "ramp_ratio": 0.2, + "gripper": { + "type": "GRIP" + } + } + } + } +} \ No newline at end of file diff --git a/third_party/robosuite/robosuite/controllers/parts/__init__.py b/third_party/robosuite/robosuite/controllers/parts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third_party/robosuite/robosuite/controllers/parts/arm/__init__.py b/third_party/robosuite/robosuite/controllers/parts/arm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e2c6539e8bf4eca295da3cd5b9286a5d8423dd0 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/arm/__init__.py @@ -0,0 +1,2 @@ +from .osc import OperationalSpaceController +from .ik import InverseKinematicsController diff --git a/third_party/robosuite/robosuite/controllers/parts/arm/ik.py b/third_party/robosuite/robosuite/controllers/parts/arm/ik.py new file mode 100644 index 0000000000000000000000000000000000000000..d38026697757a6992c4efd2629d33f73173b1cdc --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/arm/ik.py @@ -0,0 +1,584 @@ +""" +*********************************************************************************** + + +NOTE: IK is only supported for the following robots: + +:Baxter: +:Sawyer: +:Panda: + +Attempting to run IK with any other robot will raise an error! + +*********************************************************************************** +""" + +from dataclasses import field +from typing import Dict, List, Optional, Union + +import mujoco +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.controllers.parts.generic.joint_pos import JointPositionController +from robosuite.utils.binding_utils import MjSim +from robosuite.utils.control_utils import * +from robosuite.utils.ik_utils import IKSolver, get_nullspace_gains + +# Dict of supported ik robots +SUPPORTED_IK_ROBOTS = {"Baxter", "Sawyer", "Panda", "GR1FixedLowerBody"} + + +class InverseKinematicsController(JointPositionController): + """ + Controller for controlling robot arm via inverse kinematics. Allows position and orientation control of the + robot's end effector. + + We use differential inverse kinematics with posture control in the null space + to generate joint positions (see https://github.com/kevinzakka/mjctrl) which are fed to the JointPositionController. + + NOTE: Control input actions are assumed to be relative to the current position / orientation of the end effector + and are taken as the array (x_dpos, y_dpos, z_dpos, x_rot, y_rot, z_rot). + + However, confusingly, x_dpos, y_dpos, z_dpos are relative to the mujoco world frame, while x_rot, y_rot, z_rot are + relative to the current end effector frame. + + Args: + sim (MjSim): Simulator instance this controller will pull robot state updates from + + ref_name: Name of controlled robot arm's end effector (from robot XML) + + joint_indexes (dict): Each key contains sim reference indexes to relevant robot joint information, namely: + + :`'joints'`: list of indexes to relevant robot joints + :`'qpos'`: list of indexes to relevant robot joint positions + :`'qvel'`: list of indexes to relevant robot joint velocities + + robot_name (str): Name of robot being controlled. Can be {"Sawyer", "Panda", or "Baxter"} + + actuator_range (2-tuple of array of float): 2-Tuple (low, high) representing the robot joint actuator range + + eef_rot_offset (4-array): Quaternion (x,y,z,w) representing rotational offset between the final + robot arm link coordinate system and the end effector coordinate system (i.e: the gripper) + + policy_freq (int): Frequency at which actions from the robot policy are fed into this controller + + ik_pos_limit (float): Limit (meters) above which the magnitude of a given action's + positional inputs will be clipped + + ik_ori_limit (float): Limit (radians) above which the magnitude of a given action's + orientation inputs will be clipped + + interpolator (Interpolator): Interpolator object to be used for interpolating from the current state to + the goal state during each timestep between inputted actions + + converge_steps (int): How many iterations to run the inverse kinematics solver to converge to a + solution + + **kwargs: Does nothing; placeholder to "sink" any additional arguments so that instantiating this controller + via an argument dict that has additional extraneous arguments won't raise an error + + Raises: + AssertionError: [Unsupported robot] + """ + + def __init__( + self, + sim, + ref_name: Union[List[str], str], + joint_indexes, + robot_name, + actuator_range, + eef_rot_offset=None, + bullet_server_id=0, + policy_freq=20, + load_urdf=True, + ik_pos_limit=None, + ik_ori_limit=None, + interpolator_pos=None, + interpolator_ori=None, + converge_steps=5, + kp: int = 100, + kv: int = 10, + control_delta: bool = True, + **kwargs, + ): + # Run sueprclass inits + super().__init__( + sim=sim, + ref_name=ref_name, + joint_indexes=joint_indexes, + actuator_range=actuator_range, + input_max=1, + input_min=-1, + output_max=1, + output_min=-1, + kp=kp, + kv=kv, + policy_freq=policy_freq, + velocity_limits=[-1, 1], + **kwargs, + ) + + # Verify robot is supported by IK + assert robot_name in SUPPORTED_IK_ROBOTS, ( + "Error: Tried to instantiate IK controller for unsupported robot! " + "Inputted robot: {}, Supported robots: {}".format(robot_name, SUPPORTED_IK_ROBOTS) + ) + + # Initialize ik-specific attributes + self.robot_name = robot_name # Name of robot (e.g.: "Panda", "Sawyer", etc.) + + self.rest_poses = None + + self.num_ref_sites = 1 if isinstance(ref_name, str) else len(ref_name) + # Set the reference robot target pos / orientation (to prevent drift / weird ik numerical behavior over time) + if self.num_ref_sites == 1: + self.reference_target_pos = self.ref_pos + self.reference_target_orn = T.mat2quat(self.ref_ori_mat) + else: + self.reference_target_pos = self.ref_pos + self.reference_target_orn = np.array([T.mat2quat(self.ref_ori_mat[i]) for i in range(self.num_ref_sites)]) + + # Override underlying control dim + self.control_dim = 6 * self.num_ref_sites # assuming 6dof control of end effectors; TODO: handle head + + # Interpolator + self.interpolator_pos = interpolator_pos + self.interpolator_ori = interpolator_ori + + # Interpolator-related attributes + self.ori_ref = None + self.relative_ori = None + + self.use_delta = control_delta + + # Set ik limits and override internal min / max + self.ik_pos_limit = ik_pos_limit + self.ik_ori_limit = ik_ori_limit + + # Should be in (0, 1], smaller values mean less sensitivity. + self.user_sensitivity = 0.3 + + self.nullspace_joint_weights = kwargs.get("nullspace_joint_weights", {}) + self.joint_names = [sim.model.joint_id2name(i) for i in joint_indexes["joints"]] + self.integration_dt = kwargs.get("ik_integration_dt", 0.1) + self.damping = kwargs.get("ik_pseudo_inverse_damping", 5e-1) + self.max_dq = kwargs.get("ik_max_dq", 4.0) # currently only used for multi-site ik + + self.i = 0 + + def get_control(self, dpos=None, rotation=None, update_targets=False): + """ + Returns joint positions to control the robot after the target end effector + position and orientation are updated from arguments @dpos and @rotation. + If no arguments are provided, joint positions will be computed based + on the previously recorded target. + + Args: + dpos (np.array): a 3 dimensional array corresponding to the desired + change in x, y, and z end effector position. + rotation (np.array): a rotation matrix of shape (3, 3) corresponding + to the desired rotation from the current orientation of the end effector. + update_targets (bool): whether to update ik target pos / ori attributes or not + + Returns: + np.array: a flat array of joint position commands to apply to try and achieve the desired input control. + """ + positions = InverseKinematicsController.compute_joint_positions( + self.sim, + self.initial_joint, + self.joint_index, + self.ref_name, + self.control_freq, + [-1, 1], # hardcoded velocity limits; unused + use_delta=self.use_delta, + dpos=dpos, + drot=rotation, + jac=self.J_full, + joint_names=self.joint_names, + nullspace_joint_weights=self.nullspace_joint_weights, + damping=self.damping, + integration_dt=self.integration_dt, + max_dq=self.max_dq, + ) + + return positions + + @staticmethod + def compute_joint_positions( + sim: MjSim, + initial_joint: np.ndarray, + joint_indices: np.ndarray, + ref_name: Union[List[str], str], + control_freq: float, + velocity_limits: Optional[np.ndarray] = None, + use_delta: bool = True, + dpos: Optional[np.ndarray] = None, + drot: Optional[np.ndarray] = None, + Kn: Optional[np.ndarray] = np.array([10.0, 10.0, 10.0, 10.0, 5.0, 5.0, 5.0]), + damping_pseudo_inv: float = 0.05, + Kpos: float = 0.95, + Kori: float = 0.95, + jac: Optional[np.ndarray] = None, + joint_names: Optional[List[str]] = None, + nullspace_joint_weights: Dict[str, float] = field(default_factory=dict), + integration_dt: float = 0.1, + damping: float = 5e-1, + max_dq: int = 4, # TODO: should be derived from velocity_limits + ) -> np.ndarray: + """ + Returns joint positions to control the robot after the target end effector + position and orientation are updated from arguments @dpos and @drot. + If no arguments are provided, joint positions will be set as zero. + + Args: + sim (MjSim): The simulation object. + initial_joint (np.array): Initial joint positions. + joint_indices (np.array): Indices of the joints. + ref_name: Reference site name. + control_freq (float): Control frequency. + velocity_limits (np.array): Limits on joint velocities. + use_delta: Whether or not to use delta commands. If so, use dpos, drot to compute joint positions. + If not, assume dpos, drot are absolute commands (in mujoco world frame). + dpos (Optional[np.array]): Desired change in end-effector position + if use_delta=True, otherwise desired end-effector position. + drot (Optional[np.array]): Desired change in orientation for the reference site (e.g end effector) + if use_delta=True, otherwise desired end-effector orientation. + update_targets (bool): Whether to update ik target pos / ori attributes or not. + Kpos (float): Position gain. Between 0 and 1. + 0 means no movement, 1 means move end effector to desired position in one integration step. + Kori (float): Orientation gain. Between 0 and 1. + jac (Optional[np.array]): Precomputed jacobian matrix. + + Returns: + np.array: A flat array of joint position commands to apply to try and achieve the desired input control. + """ + if (dpos is not None) and (drot is not None): + max_angvel = velocity_limits[1] if velocity_limits is not None else 0.7 + + q0 = initial_joint + dof_ids = joint_indices + + num_ref_sites = 1 if isinstance(ref_name, str) else len(ref_name) + if num_ref_sites == 1: + assert use_delta, "Currently, only delta commands are supported. Please set use_delta=True." + # TODO: support absolute commands by using solve() from diffik_nullspace.py + twist = np.zeros(6) + error_quat = np.zeros(4) + diag = damping_pseudo_inv**2 * np.eye(len(twist)) + eye = np.eye(len(joint_indices)) + + jac = np.zeros((6, sim.model.nv), dtype=np.float64) + twist = np.zeros(6) + error_quat = np.zeros(4) + + twist[:3] = Kpos * dpos / integration_dt + mujoco.mju_mat2Quat(error_quat, drot.reshape(-1)) + mujoco.mju_quat2Vel(twist[3:], error_quat, 1.0) + twist[3:] *= Kori / integration_dt + + mujoco.mj_jacSite( + sim.model._model, + sim.data._data, + jac[:3], + jac[3:], + sim.data.site(ref_name).id, + ) + + jac = jac[:, dof_ids] + + dq = jac.T @ np.linalg.solve(jac @ jac.T + diag, twist) + dq += (eye - np.linalg.pinv(jac) @ jac) @ (Kn * (q0 - sim.data.qpos[dof_ids])) + + dq_abs_max = np.abs(dq).max() + if dq_abs_max > max_angvel: + dq *= max_angvel / dq_abs_max + + q_des = sim.data.qpos[dof_ids] + dq * integration_dt + dq = q_des # hack for now + return dq + else: + model = sim.model._model + data = sim.data._data + joint_names = [ + model.joint(i).name + for i in range(model.njnt) + if model.joint(i).type != 0 and ("gripper0" not in model.joint(i).name) + ] # Exclude fixed joints + nullspace_gains = get_nullspace_gains(joint_names, nullspace_joint_weights) + robot_config = { + "end_effector_sites": ref_name, + "joint_names": joint_names, + "mocap_bodies": [], + "nullspace_gains": nullspace_gains, + } + ik_solver = IKSolver( + model, + data, + robot_config, + damping=damping, + integration_dt=integration_dt, + max_dq=max_dq, + input_type="mocap", + input_rotation_repr="quat_wxyz", + ) + if use_delta: + target_ori_mat = np.array([ik_solver.data.site(site_id).xmat for site_id in ik_solver.site_ids]) + target_ori = np.array([np.ones(4) for _ in range(len(ik_solver.site_ids))]) + [mujoco.mju_mat2Quat(target_ori[i], target_ori_mat[i]) for i in range(len(ik_solver.site_ids))] + target_pos = np.array([ik_solver.data.site(site_id).xpos for site_id in ik_solver.site_ids]) + if dpos.ndim == 1: + target_pos[0] += dpos + target_ori[0] = T.quat_multiply(target_ori[0], T.mat2quat(drot)) + else: + target_pos += dpos + target_ori = np.array( + [ + T.quat_multiply(target_ori[i], T.mat2quat(drot[i])) + for i in range(len(ik_solver.site_ids)) + ] + ) + else: + target_pos = dpos + target_ori = np.array([np.ones(4) for _ in range(len(ik_solver.site_ids))]) + # convert drot (3x3) to quaternion + [mujoco.mju_mat2Quat(target_ori[i], drot[i].flatten()) for i in range(len(ik_solver.site_ids))] + + ori_dim = target_ori.shape[1] + pos_dim = target_pos.shape[1] + target_action = np.empty(target_pos.shape[0] * (target_pos.shape[1] + target_ori.shape[1])) + for i in range(target_pos.shape[0]): + target_action[i * (pos_dim + ori_dim) : (i + 1) * (pos_dim + ori_dim)] = np.concatenate( + (target_pos[i], target_ori[i]) + ) + + return ik_solver.solve( + target_pos=target_pos, + target_ori=target_ori, + Kpos=Kpos, + Kori=Kori, + ) + + return sim.data.qpos[joint_indices] + + def set_goal(self, delta, set_ik=None): + """ + Sets the internal goal state of this controller based on @delta + + Note that this controller wraps a PositionController, and so determines the desired positions + to achieve the inputted pose, and sets its internal setpoint in terms of joint positions + + TODO: Add feature so that using @set_ik automatically sets the target values to these absolute values + + Args: + delta (Iterable): Desired relative position / orientation goal state + set_ik (Iterable): If set, overrides @delta and sets the desired global position / orientation goal state + """ + # Update state + self.update(force=True) # force because new_update = True only set in super().run_controller() + + if self.num_ref_sites > 1: + delta = np.array(delta).reshape(self.num_ref_sites, 6) + + # hardcoding to assumes 6D delta input for now + (dpos, dquat) = self._clip_ik_input(delta[..., :3], delta[..., 3:6]) + + # Set interpolated goals if necessary + if self.interpolator_pos is not None: + # Absolute position goal + self.interpolator_pos.set_goal(dpos * self.user_sensitivity + self.reference_target_pos) + + if self.interpolator_ori is not None: + # Relative orientation goal + self.interpolator_ori.set_goal(dquat) # goal is the relative change in orientation + self.ori_ref = np.array(self.ref_ori_mat) # reference is the current orientation at start + self.relative_ori = np.zeros(3) # relative orientation always starts at 0 + + # Run ik prepropressing to convert pos, quat ori to desired positions + requested_control = self._make_input(delta, self.reference_target_orn) + + # Compute desired (absolute) joint positions to achieve eef pos / ori + positions = self.get_control(**requested_control, update_targets=True) + + # Set the goal positions for the underlying position controller + super().set_goal(positions) + + def run_controller(self): + """ + Calculates the torques required to reach the desired setpoint + + Returns: + np.array: Command torques + """ + # Update state + self.update() # force because new_update = True only set in super().run_controller() + + # Update interpolated action if necessary + desired_pos = None + rotation = None + update_position_goal = False + + # Update interpolated goals if active + if self.interpolator_pos is not None: + # Linear case + if self.interpolator_pos.order == 1: + desired_pos = self.interpolator_pos.get_interpolated_goal() + else: + # Nonlinear case not currently supported + pass + update_position_goal = True + else: + desired_pos = self.reference_target_pos + + if self.interpolator_ori is not None: + # Linear case + if self.interpolator_ori.order == 1: + # relative orientation based on difference between current ori and ref + self.relative_ori = orientation_error(self.ref_ori_mat, self.ori_ref) + ori_error = self.interpolator_ori.get_interpolated_goal() + rotation = T.quat2mat(ori_error) + else: + # Nonlinear case not currently supported + pass + update_position_goal = True + else: + if self.num_ref_sites == 1: + rotation = T.mat2quat(self.ref_ori_mat) + else: + rotation = np.array([T.mat2quat(self.ref_ori_mat[i]) for i in range(self.num_ref_sites)]) + + # Only update the position goals if we're interpolating + if update_position_goal: + velocities = self.get_control(dpos=(desired_pos - self.ref_pos), rotation=rotation) + super().set_goal(velocities) + + return super().run_controller() + + def update_initial_joints(self, initial_joints): + # First, update from the superclass method + super().update_initial_joints(initial_joints) + + # Then, update the rest pose from the initial joints + self.rest_poses = list(self.initial_joint) + + def reset_goal(self): + """ + Resets the goal to the current pose of the robot + """ + if self.num_ref_sites == 1: + self.reference_target_pos = self.ref_pos + self.reference_target_orn = T.mat2quat(self.ref_ori_mat) + else: + self.reference_target_pos = self.ref_pos + self.reference_target_orn = np.array([T.mat2quat(self.ref_ori_mat[i]) for i in range(self.num_ref_sites)]) + + def _clip_ik_input(self, dpos, rotation): + """ + Helper function that clips desired ik input deltas into a valid range. + + Args: + dpos (np.array): a 3 dimensional array corresponding to the desired + change in x, y, and z end effector position. + rotation (np.array): relative rotation in scaled axis angle form (ax, ay, az) + corresponding to the (relative) desired orientation of the end effector. + + Returns: + 2-tuple: + + - (np.array) clipped dpos + - (np.array) clipped rotation + """ + # scale input range to desired magnitude + if dpos.any() and self.ik_pos_limit is not None: + dpos, _ = T.clip_translation(dpos, self.ik_pos_limit) + + if self.num_ref_sites == 1: + # Map input to quaternion + rotation = T.axisangle2quat(rotation) + else: + rotation = [T.axisangle2quat(rotation[i]) for i in range(self.num_ref_sites)] + + if self.ik_ori_limit is not None: + # Clip orientation to desired magnitude + rotation, _ = T.clip_rotation(rotation, self.ik_ori_limit) + + return dpos, rotation + + def _make_input(self, action, old_quat): + """ + Helper function that returns a dictionary with keys dpos, rotation from a raw input + array. The first three elements are taken to be displacement in position, and a + quaternion indicating the change in rotation with respect to @old_quat. Additionally clips @action as well + + Args: + action (np.array) should have form: [dx, dy, dz, ax, ay, az] (orientation in + scaled axis-angle form) + old_quat (np.array) the old target quaternion that will be updated with the relative change in @action + """ + if self.num_ref_sites > 1: + action = np.array(action).reshape(self.num_ref_sites, 6) + + # Clip action appropriately + dpos, rotation = self._clip_ik_input( + action[..., :3], action[..., 3:6] + ) # hardcoded to assume 6dof control for now + + if self.use_delta: + if self.num_ref_sites == 1: + # Update reference targets + self.reference_target_pos += dpos * self.user_sensitivity + self.reference_target_orn = T.quat_multiply(old_quat, rotation) + else: + # Update reference targets + self.reference_target_pos += dpos * self.user_sensitivity + self.reference_target_orn = np.array( + [T.quat_multiply(old_quat[i], rotation[i]) for i in range(self.num_ref_sites)] + ) + else: + # Update reference targets + self.reference_target_pos = dpos + self.reference_target_orn = rotation + + if self.num_ref_sites == 1: + rotation = T.quat2mat(rotation) + else: + dpos = dpos + rotation = np.array([T.quat2mat(rotation[i]) for i in range(self.num_ref_sites)]) + + return {"dpos": dpos, "rotation": rotation} + + @staticmethod + def _get_current_error(current, set_point): + """ + Returns an array of differences between the desired joint positions and current + joint positions. Useful for PID control. + + Args: + current (np.array): the current joint positions + set_point (np.array): the joint positions that are desired as a numpy array + + Returns: + np.array: the current error in the joint positions + """ + error = current - set_point + return error + + @property + def control_limits(self): + """ + The limits over this controller's action space, as specified by self.ik_pos_limit and self.ik_ori_limit + and overriding the superclass method + + Returns: + 2-tuple: + + - (np.array) minimum control values + - (np.array) maximum control values + """ + max_limit = np.concatenate([self.ik_pos_limit * np.ones(3), self.ik_ori_limit * np.ones(3)]) + return -max_limit, max_limit + + @property + def name(self): + return "IK_POSE" diff --git a/third_party/robosuite/robosuite/controllers/parts/arm/osc.py b/third_party/robosuite/robosuite/controllers/parts/arm/osc.py new file mode 100644 index 0000000000000000000000000000000000000000..6197b6d34a67aa8514eace5cf4122eedf44c74a4 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/arm/osc.py @@ -0,0 +1,582 @@ +import math + +import numpy as np +from scipy.spatial.transform import Rotation + +import robosuite.utils.transform_utils as T +from robosuite.controllers.parts.controller import Controller +from robosuite.utils.control_utils import * + +# Supported impedance modes +IMPEDANCE_MODES = {"fixed", "variable", "variable_kp"} + +# TODO: Maybe better naming scheme to differentiate between input / output min / max and pos/ori limits, etc. + + +class OperationalSpaceController(Controller): + """ + Controller for controlling robot arm via operational space control. Allows position and / or orientation control + of the robot's end effector. For detailed information as to the mathematical foundation for this controller, please + reference http://khatib.stanford.edu/publications/pdfs/Khatib_1987_RA.pdf + + NOTE: Control input actions can either be taken to be relative to the current position / orientation of the + end effector or absolute values. In either case, a given action to this controller is assumed to be of the form: + (x, y, z, ax, ay, az) if controlling pos and ori or simply (x, y, z) if only controlling pos + + Args: + sim (MjSim): Simulator instance this controller will pull robot state updates from + + joint_indexes (dict): Each key contains sim reference indexes to relevant robot joint information, namely: + + :`'joints'`: list of indexes to relevant robot joints + :`'qpos'`: list of indexes to relevant robot joint positions + :`'qvel'`: list of indexes to relevant robot joint velocities + + actuator_range (2-tuple of array of float): 2-Tuple (low, high) representing the robot joint actuator range + + input_max (float or Iterable of float): Maximum above which an inputted action will be clipped. Can be either be + a scalar (same value for all action dimensions), or a list (specific values for each dimension). If the + latter, dimension should be the same as the control dimension for this controller + + input_min (float or Iterable of float): Minimum below which an inputted action will be clipped. Can be either be + a scalar (same value for all action dimensions), or a list (specific values for each dimension). If the + latter, dimension should be the same as the control dimension for this controller + + output_max (float or Iterable of float): Maximum which defines upper end of scaling range when scaling an input + action. Can be either be a scalar (same value for all action dimensions), or a list (specific values for + each dimension). If the latter, dimension should be the same as the control dimension for this controller + + output_min (float or Iterable of float): Minimum which defines upper end of scaling range when scaling an input + action. Can be either be a scalar (same value for all action dimensions), or a list (specific values for + each dimension). If the latter, dimension should be the same as the control dimension for this controller + + kp (float or Iterable of float): positional gain for determining desired torques based upon the pos / ori error. + Can be either be a scalar (same value for all action dims), or a list (specific values for each dim) + + damping_ratio (float or Iterable of float): used in conjunction with kp to determine the velocity gain for + determining desired torques based upon the joint pos errors. Can be either be a scalar (same value for all + action dims), or a list (specific values for each dim) + + impedance_mode (str): Impedance mode with which to run this controller. Options are {"fixed", "variable", + "variable_kp"}. If "fixed", the controller will have fixed kp and damping_ratio values as specified by the + @kp and @damping_ratio arguments. If "variable", both kp and damping_ratio will now be part of the + controller action space, resulting in a total action space of (6 or 3) + 6 * 2. If "variable_kp", only kp + will become variable, with damping_ratio fixed at 1 (critically damped). The resulting action space will + then be (6 or 3) + 6. + + kp_limits (2-list of float or 2-list of Iterable of floats): Only applicable if @impedance_mode is set to either + "variable" or "variable_kp". This sets the corresponding min / max ranges of the controller action space + for the varying kp values. Can be either be a 2-list (same min / max for all kp action dims), or a 2-list + of list (specific min / max for each kp dim) + + damping_ratio_limits (2-list of float or 2-list of Iterable of floats): Only applicable if @impedance_mode is + set to "variable". This sets the corresponding min / max ranges of the controller action space for the + varying damping_ratio values. Can be either be a 2-list (same min / max for all damping_ratio action dims), + or a 2-list of list (specific min / max for each damping_ratio dim) + + policy_freq (int): Frequency at which actions from the robot policy are fed into this controller + + position_limits (2-list of float or 2-list of Iterable of floats): Limits (m) below and above which the + magnitude of a calculated goal eef position will be clipped. Can be either be a 2-list (same min/max value + for all cartesian dims), or a 2-list of list (specific min/max values for each dim) + + orientation_limits (2-list of float or 2-list of Iterable of floats): Limits (rad) below and above which the + magnitude of a calculated goal eef orientation will be clipped. Can be either be a 2-list + (same min/max value for all joint dims), or a 2-list of list (specific min/mx values for each dim) + + interpolator_pos (Interpolator): Interpolator object to be used for interpolating from the current position to + the goal position during each timestep between inputted actions + + interpolator_ori (Interpolator): Interpolator object to be used for interpolating from the current orientation + to the goal orientation during each timestep between inputted actions + + control_ori (bool): Whether inputted actions will control both pos and ori or exclusively pos + + input_type (str): Whether to control the robot using delta ("delta") or absolute commands ("absolute"). + This is wrt the contorller reference frame (see input_ref_frame field) + + input_ref_frame (str): Reference frame for controller. Current supported options are: + "base": actions are wrt to the robot body (i.e., the base) + "world": actions are wrt the world coordinate frame + + uncouple_pos_ori (bool): Whether to decouple torques meant to control pos and torques meant to control ori + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + + **kwargs: Does nothing; placeholder to "sink" any additional arguments so that instantiating this controller + via an argument dict that has additional extraneous arguments won't raise an error + + Raises: + AssertionError: [Invalid impedance mode] + """ + + def __init__( + self, + sim, + ref_name, + joint_indexes, + actuator_range, + input_max=1, + input_min=-1, + output_max=(0.05, 0.05, 0.05, 0.5, 0.5, 0.5), + output_min=(-0.05, -0.05, -0.05, -0.5, -0.5, -0.5), + kp=150, + damping_ratio=1, + impedance_mode="fixed", + kp_limits=(0, 300), + damping_ratio_limits=(0, 100), + policy_freq=20, + position_limits=None, + orientation_limits=None, + interpolator_pos=None, + interpolator_ori=None, + control_ori=True, + input_type="delta", + input_ref_frame="base", + uncouple_pos_ori=True, + lite_physics=True, + **kwargs, # does nothing; used so no error raised when dict is passed with extra terms used previously + ): + + super().__init__( + sim, + ref_name=ref_name, + joint_indexes=joint_indexes, + actuator_range=actuator_range, + lite_physics=lite_physics, + part_name=kwargs.get("part_name", None), + naming_prefix=kwargs.get("naming_prefix", None), + ) + # Determine whether this is pos ori or just pos + self.use_ori = control_ori + # Determine whether we want to use delta or absolute values as inputs + self.input_type = input_type + assert self.input_type in ["delta", "absolute"], f"Input type must be delta or absolute, got: {self.input_type}" + + # determine reference frame wrt actions are set + self.input_ref_frame = input_ref_frame + assert self.input_ref_frame in [ + "world", + "base", + ], f"Input reference frame must be world or base, got: {self.input_ref_frame}" + + # Control dimension + self.control_dim = 6 if self.use_ori else 3 + self.name_suffix = "POSE" if self.use_ori else "POSITION" + + # input and output max and min (allow for either explicit lists or single numbers) + self.input_max = self.nums2array(input_max, self.control_dim) + self.input_min = self.nums2array(input_min, self.control_dim) + self.output_max = self.nums2array(output_max, self.control_dim) + self.output_min = self.nums2array(output_min, self.control_dim) + + # kp kd + self.kp = self.nums2array(kp, 6) + self.kd = 2 * np.sqrt(self.kp) * damping_ratio + + # kp and kd limits + self.kp_min = self.nums2array(kp_limits[0], 6) + self.kp_max = self.nums2array(kp_limits[1], 6) + self.damping_ratio_min = self.nums2array(damping_ratio_limits[0], 6) + self.damping_ratio_max = self.nums2array(damping_ratio_limits[1], 6) + + # Verify the proposed impedance mode is supported + assert impedance_mode in IMPEDANCE_MODES, ( + "Error: Tried to instantiate OSC controller for unsupported " + "impedance mode! Inputted impedance mode: {}, Supported modes: {}".format(impedance_mode, IMPEDANCE_MODES) + ) + + # Impedance mode + self.impedance_mode = impedance_mode + + # Add to control dim based on impedance_mode + if self.impedance_mode == "variable": + self.control_dim += 12 + elif self.impedance_mode == "variable_kp": + self.control_dim += 6 + + # limits + self.position_limits = np.array(position_limits) if position_limits is not None else position_limits + self.orientation_limits = np.array(orientation_limits) if orientation_limits is not None else orientation_limits + + # control frequency + self.control_freq = policy_freq + + # interpolator + self.interpolator_pos = interpolator_pos + self.interpolator_ori = interpolator_ori + + # whether or not pos and ori want to be uncoupled + self.uncoupling = uncouple_pos_ori + + # initialize goals + self.goal_pos = None + self.goal_ori = None + + # initialize orientation references + self.relative_ori = np.zeros(3) + self.ori_ref = None + + # initialize origin pos and ori + self.origin_pos = None + self.origin_ori = None + + def set_goal(self, action): + """ + Sets goal based on input @action. If self.impedance_mode is not "fixed", then the input will be parsed into the + delta values to update the goal position / pose and the kp and/or damping_ratio values to be immediately updated + internally before executing the proceeding control loop. + + Note that @action expected to be in the following format, based on impedance mode! + + :Mode `'fixed'`: [joint pos command] + :Mode `'variable'`: [damping_ratio values, kp values, joint pos command] + :Mode `'variable_kp'`: [kp values, joint pos command] + + Args: + action (Iterable): Desired relative joint position goal state + """ + # Update state + self.update() + + # Parse action based on the impedance mode, and update kp / kd as necessary + if self.impedance_mode == "variable": + damping_ratio, kp, delta = action[:6], action[6:12], action[12:] + self.kp = np.clip(kp, self.kp_min, self.kp_max) + self.kd = 2 * np.sqrt(self.kp) * np.clip(damping_ratio, self.damping_ratio_min, self.damping_ratio_max) + elif self.impedance_mode == "variable_kp": + kp, delta = action[:6], action[6:] + self.kp = np.clip(kp, self.kp_min, self.kp_max) + self.kd = 2 * np.sqrt(self.kp) # critically damped + else: # This is case "fixed" + delta = action + + # If we're using deltas, interpret actions as such + if self.input_type == "delta": + scaled_delta = self.scale_action(delta) + self.goal_pos = self.compute_goal_pos(scaled_delta[0:3]) + if self.use_ori is True: + self.goal_ori = self.compute_goal_ori(scaled_delta[3:6]) + else: + self.goal_ori = self.compute_goal_ori(np.zeros(3)) + # Else, interpret actions as absolute values + elif self.input_type == "absolute": + self.goal_pos = action[0:3] + if self.use_ori is True: + self.goal_ori = Rotation.from_rotvec(action[3:6]).as_matrix() + else: + self.goal_ori = self.compute_goal_ori(np.zeros(3)) + else: + raise ValueError(f"Unsupport input_type {self.input_type}") + + if self.interpolator_pos is not None: + self.interpolator_pos.set_goal(self.goal_pos) + + if self.interpolator_ori is not None: + self.ori_ref = np.array(self.ref_ori_mat) # reference is the current orientation at start + self.interpolator_ori.set_goal( + orientation_error(self.goal_ori, self.ori_ref) + ) # goal is the total orientation error + self.relative_ori = np.zeros(3) # relative orientation always starts at 0 + + def world_to_origin_frame(self, vec): + """ + transform vector from world to reference coordinate frame + """ + + # world rotation matrix is just identity + world_frame = np.eye(4) + world_frame[:3, 3] = vec + + origin_frame = T.make_pose(self.origin_pos, self.origin_ori) + origin_frame_inv = T.pose_inv(origin_frame) + vec_origin_pose = T.pose_in_A_to_pose_in_B(world_frame, origin_frame_inv) + vec_origin_pos, _ = T.mat2pose(vec_origin_pose) + return vec_origin_pos + + def goal_origin_to_eef_pose(self): + origin_pose = T.make_pose(self.origin_pos, self.origin_ori) + ee_pose = T.make_pose(self.ref_pos, self.ref_ori_mat) + origin_pose_inv = T.pose_inv(origin_pose) + return T.pose_in_A_to_pose_in_B(ee_pose, origin_pose_inv) + + def compute_goal_pos(self, delta, goal_update_mode=None): + """ + Compute new goal position, given a delta to update. Can either update the new goal based on + current achieved position or current deisred goal. Updating based on current deisred goal can be useful + if we want the robot to adhere with a sequence of target poses as closely as possible, + without lagging or overshooting. + + Args: + delta (np.array): Desired relative change in position [x, y, z] + goal_update_mode (str): either "achieved" (achieved position) or "desired" (desired goal) + + Returns: + np.array: updated goal position in the controller frame + """ + if goal_update_mode is None: + goal_update_mode = self._goal_update_mode + assert goal_update_mode in ["achieved", "desired"] + + if self.goal_pos is None: + # if goal is not already set, set it to current position (in controller ref frame) + if self.input_ref_frame == "base": + self.goal_pos = self.world_to_origin_frame(self.ref_pos) + elif self.input_ref_frame == "world": + self.goal_pos = self.ref_pos + else: + raise ValueError + + if goal_update_mode == "desired": + # update new goal wrt current desired goal + goal_pos = self.goal_pos + delta + elif goal_update_mode == "achieved": + # update new goal wrt current achieved position + if self.input_ref_frame == "base": + goal_pos = self.world_to_origin_frame(self.ref_pos) + delta + elif self.input_ref_frame == "world": + goal_pos = self.ref_pos + delta + else: + raise ValueError + + if self.position_limits is not None: + # to be implemented later + raise NotImplementedError + + return goal_pos + + def compute_goal_ori(self, delta, goal_update_mode=None): + """ + Compute new goal orientation, given a delta to update. Can either update the new goal based on + current achieved position or current deisred goal. Updating based on current deisred goal can be useful + if we want the robot to adhere with a sequence of target poses as closely as possible, + without lagging or overshooting. + + Args: + delta (np.array): Desired relative change in orientation, in axis-angle form [ax, ay, az] + goal_update_mode (str): either "achieved" (achieved position) or "desired" (desired goal) + + Returns: + np.array: updated goal orientation in the controller frame + """ + if goal_update_mode is None: + goal_update_mode = self._goal_update_mode + assert goal_update_mode in ["achieved", "desired"] + + if self.goal_ori is None: + # if goal is not already set, set it to current orientation (in controller ref frame) + if self.input_ref_frame == "base": + self.goal_ori = self.goal_origin_to_eef_pose()[:3, :3] + elif self.input_ref_frame == "world": + self.goal_ori = self.ref_ori_mat + else: + raise ValueError + + # convert axis-angle value to rotation matrix + quat_error = T.axisangle2quat(delta) + rotation_mat_error = T.quat2mat(quat_error) + + if self._goal_update_mode == "desired": + # update new goal wrt current desired goal + goal_ori = np.dot(rotation_mat_error, self.goal_ori) + elif self._goal_update_mode == "achieved": + # update new goal wrt current achieved orientation + if self.input_ref_frame == "base": + curr_goal_ori = self.goal_origin_to_eef_pose()[:3, :3] + elif self.input_ref_frame == "world": + curr_goal_ori = self.ref_ori_mat + else: + raise ValueError + goal_ori = np.dot(rotation_mat_error, curr_goal_ori) + else: + raise ValueError + + # check for orientation limits + if np.array(self.orientation_limits).any(): + # to be implemented later + raise NotImplementedError + return goal_ori + + def run_controller(self): + """ + Calculates the torques required to reach the desired setpoint. + + Executes Operational Space Control (OSC) -- either position only or position and orientation. + + A detailed overview of derivation of OSC equations can be seen at: + http://khatib.stanford.edu/publications/pdfs/Khatib_1987_RA.pdf + + Returns: + np.array: Command torques + """ + # Update state + self.update() + + desired_world_pos = None + # Only linear interpolator is currently supported + if self.interpolator_pos is not None: + # Linear case + if self.interpolator_pos.order == 1: + desired_world_pos = self.interpolator_pos.get_interpolated_goal() + else: + # Nonlinear case not currently supported + pass + else: + if self.input_ref_frame == "base": + # compute goal based on current base position and orientation + desired_world_pos = self.origin_pos + np.dot(self.origin_ori, self.goal_pos) + elif self.input_ref_frame == "world": + desired_world_pos = self.goal_pos + else: + raise ValueError + + if self.interpolator_ori is not None: + # relative orientation based on difference between current ori and ref + self.relative_ori = orientation_error(self.ref_ori_mat, self.ori_ref) + + ori_error = self.interpolator_ori.get_interpolated_goal() + else: + if self.input_ref_frame == "base": + # compute goal based on current base orientation + desired_world_ori = np.dot(self.origin_ori, self.goal_ori) + elif self.input_ref_frame == "world": + desired_world_ori = self.goal_ori + else: + raise ValueError + ori_error = orientation_error(desired_world_ori, self.ref_ori_mat) + + # Compute desired force and torque based on errors + position_error = desired_world_pos - self.ref_pos + base_pos_vel = np.array(self.sim.data.get_site_xvelp(f"{self.naming_prefix}{self.part_name}_center")) + vel_pos_error = -(self.ref_pos_vel - base_pos_vel) + + # F_r = kp * pos_err + kd * vel_err + desired_force = np.multiply(np.array(position_error), np.array(self.kp[0:3])) + np.multiply( + vel_pos_error, self.kd[0:3] + ) + + base_ori_vel = np.array(self.sim.data.get_site_xvelr(f"{self.naming_prefix}{self.part_name}_center")) + vel_ori_error = -(self.ref_ori_vel - base_ori_vel) + + # Tau_r = kp * ori_err + kd * vel_err + desired_torque = np.multiply(np.array(ori_error), np.array(self.kp[3:6])) + np.multiply( + vel_ori_error, self.kd[3:6] + ) + + # Compute nullspace matrix (I - Jbar * J) and lambda matrices ((J * M^-1 * J^T)^-1) + lambda_full, lambda_pos, lambda_ori, nullspace_matrix = opspace_matrices( + self.mass_matrix, self.J_full, self.J_pos, self.J_ori + ) + + # Decouples desired positional control from orientation control + if self.uncoupling: + decoupled_force = np.dot(lambda_pos, desired_force) + decoupled_torque = np.dot(lambda_ori, desired_torque) + decoupled_wrench = np.concatenate([decoupled_force, decoupled_torque]) + else: + desired_wrench = np.concatenate([desired_force, desired_torque]) + decoupled_wrench = np.dot(lambda_full, desired_wrench) + + # Gamma (without null torques) = J^T * F + gravity compensations + self.torques = np.dot(self.J_full.T, decoupled_wrench) + self.torque_compensation + # Calculate and add nullspace torques (nullspace_matrix^T * Gamma_null) to final torques + # Note: Gamma_null = desired nullspace pose torques, assumed to be positional joint control relative + # to the initial joint positions + self.torques += nullspace_torques( + self.mass_matrix, nullspace_matrix, self.initial_joint, self.joint_pos, self.joint_vel + ) + + # Always run superclass call for any cleanups at the end + super().run_controller() + + return self.torques + + def update_origin(self, origin_pos, origin_ori): + """ + Optional function to implement in subclass controllers that will take in @origin_pos and @origin_ori and update + internal configuration to account for changes in the respective states. Useful for controllers in which the origin + is a frame of reference that is dynamically changing, e.g., adapting the arm to move along with a moving base. + + Args: + origin_pos (3-tuple): x,y,z position of controller reference in mujoco world coordinates + origin_ori (np.array): 3x3 rotation matrix orientation of controller reference in mujoco world coordinates + """ + self.origin_pos = origin_pos + self.origin_ori = origin_ori + + def update_initial_joints(self, initial_joints): + # First, update from the superclass method + super().update_initial_joints(initial_joints) + + # We also need to reset the goal in case the old goals were set to the initial confguration + self.reset_goal() + + def set_goal_update_mode(self, goal_update_mode): + self._goal_update_mode = goal_update_mode + + def reset_goal(self, goal_update_mode="achieved"): + """ + Resets the goal to the current state of the robot. + + Args: + goal_update_mode (str): set mode for updating controller goals, + either "achieved" (achieved position) or "desired" (desired goal). + """ + self.goal_ori = np.array(self.ref_ori_mat) + self.goal_pos = np.array(self.ref_pos) + + assert goal_update_mode in ["achieved", "desired"] + self._goal_update_mode = goal_update_mode + + # Also reset interpolators if required + + if self.interpolator_pos is not None: + self.interpolator_pos.set_goal(self.goal_pos) + + if self.interpolator_ori is not None: + self.ori_ref = np.array(self.ref_ori_mat) # reference is the current orientation at start + self.interpolator_ori.set_goal( + orientation_error(self.goal_ori, self.ori_ref) + ) # goal is the total orientation error + self.relative_ori = np.zeros(3) # relative orientation always starts at 0 + + @property + def control_limits(self): + """ + Returns the limits over this controller's action space, overrides the superclass property + Returns the following (generalized for both high and low limits), based on the impedance mode: + + :Mode `'fixed'`: [joint pos command] + :Mode `'variable'`: [damping_ratio values, kp values, joint pos command] + :Mode `'variable_kp'`: [kp values, joint pos command] + + Returns: + 2-tuple: + + - (np.array) minimum action values + - (np.array) maximum action values + """ + if self.impedance_mode == "variable": + low = np.concatenate([self.damping_ratio_min, self.kp_min, self.input_min]) + high = np.concatenate([self.damping_ratio_max, self.kp_max, self.input_max]) + elif self.impedance_mode == "variable_kp": + low = np.concatenate([self.kp_min, self.input_min]) + high = np.concatenate([self.kp_max, self.input_max]) + else: # This is case "fixed" + low, high = self.input_min, self.input_max + return low, high + + def delta_to_abs_action(self, delta_ac, goal_update_mode): + """ + helper function that converts delta action into absolute action + """ + abs_pos = self.compute_goal_pos(delta_ac[0:3], goal_update_mode=goal_update_mode) + abs_ori = self.compute_goal_ori(delta_ac[3:6], goal_update_mode=goal_update_mode) + abs_rot = T.quat2axisangle(T.mat2quat(abs_ori)) + abs_action = np.concatenate([abs_pos, abs_rot]) + return abs_action + + @property + def name(self): + return "OSC_" + self.name_suffix diff --git a/third_party/robosuite/robosuite/controllers/parts/controller.py b/third_party/robosuite/robosuite/controllers/parts/controller.py new file mode 100644 index 0000000000000000000000000000000000000000..2b3b4f58b78cb7515c6b444340ac2d5d7f87411c --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/controller.py @@ -0,0 +1,347 @@ +import abc +from collections.abc import Iterable + +import mujoco +import numpy as np + +import robosuite.macros as macros + + +class Controller(object, metaclass=abc.ABCMeta): + """ + General controller interface. + + Requires reference to mujoco sim object, ref_name of specific robot, relevant joint_indexes to that robot, and + whether an initial_joint is used for nullspace torques or not + + Args: + sim (MjSim): Simulator instance this controller will pull robot state updates from + + ref_name (str): Name of controlled robot arm's end effector (from robot XML) + + joint_indexes (dict): Each key contains sim reference indexes to relevant robot joint information, namely: + + :`'joints'`: list of indexes to relevant robot joints + :`'qpos'`: list of indexes to relevant robot joint positions + :`'qvel'`: list of indexes to relevant robot joint velocities + + actuator_range (2-tuple of array of float): 2-Tuple (low, high) representing the robot joint actuator range + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Ignores all self.update() calls, unless set to force=True + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + """ + + def __init__( + self, + sim, + joint_indexes, + actuator_range, + ref_name=None, + part_name=None, + naming_prefix=None, + lite_physics=True, + ): + + # Actuator range + self.actuator_min = actuator_range[0] + self.actuator_max = actuator_range[1] + + # Attributes for scaling / clipping inputs to outputs + self.action_scale = None + self.action_input_transform = None + self.action_output_transform = None + + # Private property attributes + self.control_dim = None + self.output_min = None + self.output_max = None + self.input_min = None + self.input_max = None + + # mujoco simulator state + self.sim = sim + self.model_timestep = macros.SIMULATION_TIMESTEP + self.lite_physics = lite_physics + self.ref_name = ref_name + # A list of site the controller want to follow + # self.ref_site_names = ref_site_names + + self.part_name = part_name + self.naming_prefix = naming_prefix + self.joint_index = joint_indexes["joints"] + self.qpos_index = joint_indexes["qpos"] + self.qvel_index = joint_indexes["qvel"] + self.joint_names = [self.sim.model.joint_id2name(joint_id) for joint_id in self.joint_index] + + # robot states + self.ref_pos = None + self.ref_ori_mat = None + self.ref_pos_vel = None + self.ref_ori_vel = None + + self.joint_pos = None + self.joint_vel = None + + # Joint dimension + self.joint_dim = len(joint_indexes["joints"]) + + if ref_name is None: + self.ref_names = None + self.num_ref_sites = 0 + elif isinstance(ref_name, str): + self.ref_names = [ref_name] + self.num_ref_sites = 1 + else: + self.ref_names = ref_name + self.num_ref_sites = len(ref_name) + + # Initialize robot states + if self.num_ref_sites == 1: + # non-batched for backward compatibility + self.ref_pos = np.zeros(3) + self.ref_ori_mat = np.zeros((3, 3)) + self.ref_pos_vel = np.zeros(3) + self.ref_ori_vel = np.zeros(3) + # Initialize Jacobians + self.J_pos = np.zeros((3, len(self.joint_index))) + self.J_ori = np.zeros((3, len(self.joint_index))) + self.J_full = np.zeros((6, len(self.joint_index))) + else: + self.ref_pos = np.zeros((self.num_ref_sites, 3)) + self.ref_ori_mat = np.zeros((self.num_ref_sites, 3, 3)) + self.ref_pos_vel = np.zeros((self.num_ref_sites, 3)) + self.ref_ori_vel = np.zeros((self.num_ref_sites, 3)) + # Initialize Jacobians + self.J_pos = np.zeros((self.num_ref_sites, 3, len(self.joint_index))) + self.J_ori = np.zeros((self.num_ref_sites, 3, len(self.joint_index))) + self.J_full = np.zeros((self.num_ref_sites, 6, len(self.joint_index))) + + self.mass_matrix = None + + # Torques being outputted by the controller + self.torques = None + + # Update flag to prevent redundant update calls + self.new_update = True + + # Move forward one timestep to propagate updates before taking first update + self.sim.forward() + + # Initialize controller by updating internal state and setting the initial joint, pos, and ori + self.update() + self.initial_joint = self.joint_pos + self.initial_ref_pos = self.ref_pos + self.initial_ref_ori_mat = self.ref_ori_mat + + self.origin_pos = None + self.origin_ori = None + + @abc.abstractmethod + def run_controller(self): + """ + Abstract method that should be implemented in all subclass controllers, and should convert a given action + into torques (pre gravity compensation) to be executed on the robot. + Additionally, resets the self.new_update flag so that the next self.update call will occur + """ + self.new_update = True + + def scale_action(self, action): + """ + Clips @action to be within self.input_min and self.input_max, and then re-scale the values to be within + the range self.output_min and self.output_max + + Args: + action (Iterable): Actions to scale + + Returns: + np.array: Re-scaled action + """ + + if self.action_scale is None: + self.action_scale = abs(self.output_max - self.output_min) / abs(self.input_max - self.input_min) + self.action_output_transform = (self.output_max + self.output_min) / 2.0 + self.action_input_transform = (self.input_max + self.input_min) / 2.0 + action = np.clip(action, self.input_min, self.input_max) + transformed_action = (action - self.action_input_transform) * self.action_scale + self.action_output_transform + + return transformed_action + + def update_reference_data(self): + if self.num_ref_sites == 1: + self._update_single_reference(self.ref_name, 0) + else: + for i, name in enumerate(self.ref_name): + self._update_single_reference(name, i) + + def _update_single_reference(self, name: str, index: int): + # TODO: remove if statement once we unify the shapes of variables when num_ref_sites == 1 and num_ref_sites > 1 + ref_id = self.sim.model.site_name2id(name) + + if self.num_ref_sites == 1: + self.ref_pos[:] = np.array(self.sim.data.site_xpos[ref_id]) + self.ref_ori_mat[:, :] = np.array(self.sim.data.site_xmat[ref_id].reshape([3, 3])) + self.ref_pos_vel[:] = np.array(self.sim.data.get_site_xvelp(name)) + self.ref_ori_vel[:] = np.array(self.sim.data.get_site_xvelr(name)) + self.J_pos[:, :] = np.array(self.sim.data.get_site_jacp(name).reshape((3, -1))[:, self.qvel_index]) + self.J_ori[:, :] = np.array(self.sim.data.get_site_jacr(name).reshape((3, -1))[:, self.qvel_index]) + self.J_full[:, :] = np.vstack([self.J_pos, self.J_ori]) + else: + self.ref_pos[index, :] = np.array(self.sim.data.site_xpos[ref_id]) + self.ref_ori_mat[index, :, :] = np.array(self.sim.data.site_xmat[ref_id].reshape([3, 3])) + self.ref_pos_vel[index, :] = np.array(self.sim.data.get_site_xvelp(name)) + self.ref_ori_vel[index, :] = np.array(self.sim.data.get_site_xvelr(name)) + + self.J_pos[index, :, :] = np.array(self.sim.data.get_site_jacp(name).reshape((3, -1))[:, self.qvel_index]) + self.J_ori[index, :, :] = np.array(self.sim.data.get_site_jacr(name).reshape((3, -1))[:, self.qvel_index]) + self.J_full[index, :, :] = np.vstack([self.J_pos[index], self.J_ori[index]]) + + def update(self, force=False): + """ + Updates the state of the robot arm, including end effector pose / orientation / velocity, joint pos/vel, + jacobian, and mass matrix. By default, since this is a non-negligible computation, multiple redundant calls + will be ignored via the self.new_update attribute flag. However, if the @force flag is set, the update will + occur regardless of that state of self.new_update. This base class method of @run_controller resets the + self.new_update flag + + Args: + force (bool): Whether to force an update to occur or not + """ + + # Only run update if self.new_update or force flag is set + if self.new_update or force: + # no need to call sim.forward if using lite_physics + if self.lite_physics and not force: + pass + else: + # BUG: Potential bug here. If there are more than two controlllers, the simulation will be forwarded multiple times. + self.sim.forward() + + if self.ref_name is not None: + self.update_reference_data() + + self.joint_pos = np.array(self.sim.data.qpos[self.qpos_index]) + self.joint_vel = np.array(self.sim.data.qvel[self.qvel_index]) + + mass_matrix = np.ndarray(shape=(self.sim.model.nv, self.sim.model.nv), dtype=np.float64, order="C") + mujoco.mj_fullM(self.sim.model._model, mass_matrix, self.sim.data.qM) + mass_matrix = np.reshape(mass_matrix, (len(self.sim.data.qvel), len(self.sim.data.qvel))) + self.mass_matrix = mass_matrix[self.qvel_index, :][:, self.qvel_index] + + # Clear self.new_update + self.new_update = False + + def update_origin(self, origin_pos, origin_ori): + """ + Optional function to implement in subclass controllers that will take in @origin_pos and @origin_ori and update + internal configuration to account for changes in the respective states. Useful for controllers in which the origin + is a frame of reference that is dynamically changing, e.g., adapting the arm to move along with a moving base. + + Args: + origin_pos (3-tuple): x,y,z position of controller reference in mujoco world coordinates + origin_ori (np.array): 3x3 rotation matrix orientation of controller reference in mujoco world coordinates + """ + self.origin_pos = origin_pos + self.origin_ori = origin_ori + + def update_initial_joints(self, initial_joints): + """ + Updates the internal attribute self.initial_joints. This is useful for updating changes in controller-specific + behavior, such as with OSC where self.initial_joints is used for determine nullspace actions + + This function can also be extended by subclassed controllers for additional controller-specific updates + + Args: + initial_joints (Iterable): Array of joint position values to update the initial joints + """ + self.initial_joint = np.array(initial_joints) + self.update(force=True) + + if self.ref_name is not None: + self.initial_ref_pos = self.ref_pos + self.initial_ref_ori_mat = self.ref_ori_mat + + def clip_torques(self, torques): + """ + Clips the torques to be within the actuator limits + + Args: + torques (Iterable): Torques to clip + + Returns: + np.array: Clipped torques + """ + return np.clip(torques, self.actuator_min, self.actuator_max) + + def reset_goal(self): + """ + Resets the goal -- usually by setting to the goal to all zeros, but in some cases may be different (e.g.: OSC) + """ + raise NotImplementedError + + @staticmethod + def nums2array(nums, dim): + """ + Convert input @nums into numpy array of length @dim. If @nums is a single number, broadcasts it to the + corresponding dimension size @dim before converting into a numpy array + + Args: + nums (numeric or Iterable): Either single value or array of numbers + dim (int): Size of array to broadcast input to env.sim.data.actuator_force + + Returns: + np.array: Array filled with values specified in @nums + """ + # First run sanity check to make sure no strings are being inputted + if isinstance(nums, str): + raise TypeError("Error: Only numeric inputs are supported for this function, nums2array!") + + # Check if input is an Iterable, if so, we simply convert the input to np.array and return + # Else, input is a single value, so we map to a numpy array of correct size and return + return np.array(nums) if isinstance(nums, Iterable) else np.ones(dim) * nums + + @property + def torque_compensation(self): + """ + Gravity compensation for this robot arm + + Returns: + np.array: torques + """ + return self.sim.data.qfrc_bias[self.qvel_index] + + @property + def actuator_limits(self): + """ + Torque limits for this controller + + Returns: + 2-tuple: + + - (np.array) minimum actuator torques + - (np.array) maximum actuator torques + """ + return self.actuator_min, self.actuator_max + + @property + def control_limits(self): + """ + Limits over this controller's action space, which defaults to input min/max + + Returns: + 2-tuple: + + - (np.array) minimum action values + - (np.array) maximum action values + """ + return self.input_min, self.input_max + + @property + def name(self): + """ + Name of this controller + + Returns: + str: controller name + """ + raise NotImplementedError diff --git a/third_party/robosuite/robosuite/controllers/parts/controller_factory.py b/third_party/robosuite/robosuite/controllers/parts/controller_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..8c780f8d48d653e2c995ef975fd7484986fd219e --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/controller_factory.py @@ -0,0 +1,230 @@ +""" +Set of functions that streamline controller initialization process +""" +import json +import os +from copy import deepcopy + +import numpy as np + +from robosuite.controllers.parts import arm as arm_controllers +from robosuite.controllers.parts import generic +from robosuite.controllers.parts import gripper as gripper_controllers +from robosuite.controllers.parts import mobile_base as mobile_base_controllers +from robosuite.utils.traj_utils import LinearInterpolator + +# from . import legs as legs_controllers + + +def load_part_controller_config(custom_fpath=None, default_controller=None): + """ + Utility function that loads the desired controller and returns the loaded configuration as a dict + + If @default_controller is specified, any value inputted to @custom_fpath is overridden and the default controller + configuration is automatically loaded. See specific arg description below for available default controllers. + + Args: + custom_fpath (str): Absolute filepath to the custom controller configuration .json file to be loaded + default_controller (str): If specified, overrides @custom_fpath and loads a default configuration file for the + specified controller. + Choices are: {"JOINT_POSITION", "JOINT_TORQUE", "JOINT_VELOCITY", "OSC_POSITION", "OSC_POSE", "IK_POSE"} + + Returns: + dict: Controller configuration + + Raises: + AssertionError: [Unknown default controller name] + AssertionError: [No controller specified] + """ + # TODO (YL): this is nolonger usable, need to update + # First check if default controller is not None; if it + # is not, load the appropriate controller + if default_controller is not None: + + # Assert that requested default controller is in the available default controllers + from robosuite.controllers import ALL_PART_CONTROLLERS + + assert ( + default_controller in ALL_PART_CONTROLLERS + ), "Error: Unknown default controller specified. Requested {}, " "available controllers: {}".format( + default_controller, list(ALL_PART_CONTROLLERS) + ) + + # Store the default controller config fpath associated with the requested controller + custom_fpath = os.path.join( + os.path.dirname(__file__), "..", "config/default/parts/{}.json".format(default_controller.lower()) + ) + + # Assert that the fpath to load the controller is not empty + assert custom_fpath is not None, "Error: Either custom_fpath or default_controller must be specified!" + + # Attempt to load the controller + try: + with open(custom_fpath) as f: + controller_config = json.load(f) + except FileNotFoundError: + print("Error opening controller filepath at: {}. " "Please check filepath and try again.".format(custom_fpath)) + raise FileNotFoundError + + # Return the loaded controller + return controller_config + + +def arm_controller_factory(name, params): + """ + Generator for controllers + + Creates a Controller instance with the provided @name and relevant @params. + + Args: + name (str): the name of the controller. Must be one of: {JOINT_POSITION, JOINT_TORQUE, JOINT_VELOCITY, + OSC_POSITION, OSC_POSE, IK_POSE} + params (dict): dict containing the relevant params to pass to the controller + sim (MjSim): Mujoco sim reference to pass to the controller + + Returns: + Controller: Controller instance + + Raises: + ValueError: [unknown controller] + """ + + interpolator = None + if params["interpolation"] == "linear": + interpolator = LinearInterpolator( + ndim=params["ndim"], + controller_freq=(1 / params["sim"].model.opt.timestep), + policy_freq=params["policy_freq"], + ramp_ratio=params["ramp_ratio"], + ) + + if name == "OSC_POSE": + ori_interpolator = None + if interpolator is not None: + interpolator.set_states(dim=3) # EE control uses dim 3 for pos and ori each + ori_interpolator = deepcopy(interpolator) + ori_interpolator.set_states(ori="euler") + params["control_ori"] = True + return arm_controllers.OperationalSpaceController( + interpolator_pos=interpolator, interpolator_ori=ori_interpolator, **params + ) + + if name == "OSC_POSITION": + if interpolator is not None: + interpolator.set_states(dim=3) # EE control uses dim 3 for pos + params["control_ori"] = False + return arm_controllers.OperationalSpaceController(interpolator_pos=interpolator, **params) + + if name == "IK_POSE": + ori_interpolator = None + if interpolator is not None: + interpolator.set_states(dim=3) # EE IK control uses dim 3 for pos and dim 4 for ori + ori_interpolator = deepcopy(interpolator) + ori_interpolator.set_states(dim=4, ori="quat") + + from robosuite.controllers.parts.arm.ik import InverseKinematicsController + + return InverseKinematicsController( + interpolator_pos=interpolator, + interpolator_ori=ori_interpolator, + **params, + ) + + if name == "JOINT_VELOCITY": + return generic.JointVelocityController(interpolator=interpolator, **params) + + if name == "JOINT_POSITION": + return generic.JointPositionController(interpolator=interpolator, **params) + + if name == "JOINT_TORQUE": + return generic.JointTorqueController(interpolator=interpolator, **params) + + raise ValueError("Unknown controller name: {}".format(name)) + + +def controller_factory(part_name, controller_type, controller_params): + if part_name in ["right", "left"]: + return arm_controller_factory(controller_type, controller_params) + elif part_name in ["right_gripper", "left_gripper"]: + return gripper_controller_factory(controller_type, controller_params) + elif part_name == "base": + return mobile_base_controller_factory(controller_type, controller_params) + elif part_name == "torso": + return torso_controller_factory(controller_type, controller_params) + elif part_name == "head": + return head_controller_factory(controller_type, controller_params) + elif part_name == "legs": + return legs_controller_factory(controller_type, controller_params) + else: + raise ValueError("Unknown controller part name: {}".format(part_name)) + + +def gripper_controller_factory(name, params): + interpolator = None + if name == "GRIP": + return gripper_controllers.SimpleGripController(interpolator=interpolator, **params) + elif name == "JOINT_POSITION": + return generic.JointPositionController(interpolator=interpolator, **params) + raise ValueError("Unknown controller name: {}".format(name)) + + +def mobile_base_controller_factory(name, params): + interpolator = None + if name == "JOINT_VELOCITY": + return mobile_base_controllers.MobileBaseJointVelocityController(interpolator=interpolator, **params) + elif name == "JOINT_POSITION": + raise NotImplementedError + raise ValueError("Unknown controller name: {}".format(name)) + + +def torso_controller_factory(name, params): + interpolator = None + if params["interpolation"] == "linear": + interpolator = LinearInterpolator( + ndim=params["ndim"], + controller_freq=(1 / params["sim"].model.opt.timestep), + policy_freq=params["policy_freq"], + ramp_ratio=params["ramp_ratio"], + ) + + if name == "JOINT_VELOCITY": + return generic.JointVelocityController(interpolator=interpolator, **params) + elif name == "JOINT_POSITION": + return generic.JointPositionController(interpolator=interpolator, **params) + raise ValueError("Unknown controller name: {}".format(name)) + + +def head_controller_factory(name, params): + interpolator = None + if params["interpolation"] == "linear": + interpolator = LinearInterpolator( + ndim=params["ndim"], + controller_freq=(1 / params["sim"].model.opt.timestep), + policy_freq=params["policy_freq"], + ramp_ratio=params["ramp_ratio"], + ) + + if name == "JOINT_VELOCITY": + return generic.JointVelocityController(interpolator=interpolator, **params) + elif name == "JOINT_POSITION": + return generic.JointPositionController(interpolator=interpolator, **params) + raise ValueError("Unknown controller name: {}".format(name)) + + +def legs_controller_factory(name, params): + interpolator = None + if params["interpolation"] == "linear": + interpolator = LinearInterpolator( + ndim=params["ndim"], + controller_freq=(1 / params["sim"].model.opt.timestep), + policy_freq=params["policy_freq"], + ramp_ratio=params["ramp_ratio"], + ) + + if name == "JOINT_POSITION": + return generic.JointPositionController(interpolator=interpolator, **params) + + if name == "JOINT_TORQUE": + return generic.JointTorqueController(interpolator=interpolator, **params) + + raise ValueError("Unknown controller name: {}".format(name)) diff --git a/third_party/robosuite/robosuite/controllers/parts/generic/__init__.py b/third_party/robosuite/robosuite/controllers/parts/generic/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c334db11f377578b64eb11b6c896510c078de723 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/generic/__init__.py @@ -0,0 +1,3 @@ +from .joint_pos import JointPositionController +from .joint_vel import JointVelocityController +from .joint_tor import JointTorqueController diff --git a/third_party/robosuite/robosuite/controllers/parts/generic/joint_pos.py b/third_party/robosuite/robosuite/controllers/parts/generic/joint_pos.py new file mode 100644 index 0000000000000000000000000000000000000000..6d55ef0ae59c5f398abc8efef988bf0194606959 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/generic/joint_pos.py @@ -0,0 +1,307 @@ +from typing import Dict, List, Literal + +import numpy as np + +from robosuite.controllers.parts.controller import Controller +from robosuite.utils.control_utils import * + +# Supported impedance modes +IMPEDANCE_MODES = {"fixed", "variable", "variable_kp"} + + +class JointPositionController(Controller): + """ + Controller for controlling robot arm via impedance control. Allows position control of the robot's joints. + + NOTE: Control input actions assumed to be taken relative to the current joint positions. A given action to this + controller is assumed to be of the form: (dpos_j0, dpos_j1, ... , dpos_jn-1) for an n-joint robot + + Args: + sim (MjSim): Simulator instance this controller will pull robot state updates from + + eef_name (str): Name of controlled robot arm's end effector (from robot XML) + + joint_indexes (dict): Each key contains sim reference indexes to relevant robot joint information, namely: + + :`'joints'`: list of indexes to relevant robot joints + :`'qpos'`: list of indexes to relevant robot joint positions + :`'qvel'`: list of indexes to relevant robot joint velocities + + actuator_range (2-tuple of array of float): 2-Tuple (low, high) representing the robot joint actuator range + + input_max (float or Iterable of float): Maximum above which an inputted action will be clipped. Can be either be + a scalar (same value for all action dimensions), or a list (specific values for each dimension). If the + latter, dimension should be the same as the control dimension for this controller + + input_min (float or Iterable of float): Minimum below which an inputted action will be clipped. Can be either be + a scalar (same value for all action dimensions), or a list (specific values for each dimension). If the + latter, dimension should be the same as the control dimension for this controller + + output_max (float or Iterable of float): Maximum which defines upper end of scaling range when scaling an input + action. Can be either be a scalar (same value for all action dimensions), or a list (specific values for + each dimension). If the latter, dimension should be the same as the control dimension for this controller + + output_min (float or Iterable of float): Minimum which defines upper end of scaling range when scaling an input + action. Can be either be a scalar (same value for all action dimensions), or a list (specific values for + each dimension). If the latter, dimension should be the same as the control dimension for this controller + + kp (float or Iterable of float): positional gain for determining desired torques based upon the joint pos error. + Can be either be a scalar (same value for all action dims), or a list (specific values for each dim) + + damping_ratio (float or Iterable of float): used in conjunction with kp to determine the velocity gain for + determining desired torques based upon the joint pos errors. Can be either be a scalar (same value for all + action dims), or a list (specific values for each dim) + + impedance_mode (str): Impedance mode with which to run this controller. Options are {"fixed", "variable", + "variable_kp"}. If "fixed", the controller will have fixed kp and damping_ratio values as specified by the + @kp and @damping_ratio arguments. If "variable", both kp and damping_ratio will now be part of the + controller action space, resulting in a total action space of num_joints * 3. If "variable_kp", only kp + will become variable, with damping_ratio fixed at 1 (critically damped). The resulting action space will + then be num_joints * 2. + + kp_limits (2-list of float or 2-list of Iterable of floats): Only applicable if @impedance_mode is set to either + "variable" or "variable_kp". This sets the corresponding min / max ranges of the controller action space + for the varying kp values. Can be either be a 2-list (same min / max for all kp action dims), or a 2-list + of list (specific min / max for each kp dim) + + damping_ratio_limits (2-list of float or 2-list of Iterable of floats): Only applicable if @impedance_mode is + set to "variable". This sets the corresponding min / max ranges of the controller action space for the + varying damping_ratio values. Can be either be a 2-list (same min / max for all damping_ratio action dims), + or a 2-list of list (specific min / max for each damping_ratio dim) + + policy_freq (int): Frequency at which actions from the robot policy are fed into this controller + + qpos_limits (2-list of float or 2-list of Iterable of floats): Limits (rad) below and above which the magnitude + of a calculated goal joint position will be clipped. Can be either be a 2-list (same min/max value for all + joint dims), or a 2-list of list (specific min/max values for each dim) + + interpolator (Interpolator): Interpolator object to be used for interpolating from the current joint position to + the goal joint position during each timestep between inputted actions + + **kwargs: Does nothing; placeholder to "sink" any additional arguments so that instantiating this controller + via an argument dict that has additional extraneous arguments won't raise an error + + Raises: + AssertionError: [Invalid impedance mode] + """ + + def __init__( + self, + sim, + joint_indexes, + actuator_range, + ref_name=None, + input_max=1, + input_min=-1, + output_max=0.05, + output_min=-0.05, + kp=50, + damping_ratio=1, + impedance_mode="fixed", + kp_limits=(0, 300), + damping_ratio_limits=(0, 100), + policy_freq=20, + lite_physics=True, + qpos_limits=None, + interpolator=None, + input_type: Literal["delta", "absolute"] = "delta", + **kwargs, # does nothing; used so no error raised when dict is passed with extra terms used previously + ): + + super().__init__( + sim, + ref_name=ref_name, + joint_indexes=joint_indexes, + actuator_range=actuator_range, + part_name=kwargs.get("part_name", None), + naming_prefix=kwargs.get("naming_prefix", None), + lite_physics=lite_physics, + ) + + self.joint_indexes = joint_indexes + + # Control dimension + self.control_dim = len(joint_indexes["joints"]) + + # input and output max and min (allow for either explicit lists or single numbers) + self.input_max = self.nums2array(input_max, self.control_dim) + self.input_min = self.nums2array(input_min, self.control_dim) + self.output_max = self.nums2array(output_max, self.control_dim) + self.output_min = self.nums2array(output_min, self.control_dim) + + # limits + self.position_limits = np.array(qpos_limits) if qpos_limits is not None else qpos_limits + + # kp kd + self.kp = self.nums2array(kp, self.control_dim) + self.kd = ( + 2 * np.sqrt(self.kp) * damping_ratio + if kwargs.get("kd", None) is None + else self.nums2array(kwargs.get("kd", None), self.control_dim) + ) + + # kp and kd limits + self.kp_min = self.nums2array(kp_limits[0], self.control_dim) + self.kp_max = self.nums2array(kp_limits[1], self.control_dim) + self.damping_ratio_min = self.nums2array(damping_ratio_limits[0], self.control_dim) + self.damping_ratio_max = self.nums2array(damping_ratio_limits[1], self.control_dim) + + # Verify the proposed impedance mode is supported + assert impedance_mode in IMPEDANCE_MODES, ( + "Error: Tried to instantiate OSC controller for unsupported " + "impedance mode! Inputted impedance mode: {}, Supported modes: {}".format(impedance_mode, IMPEDANCE_MODES) + ) + + # Impedance mode + self.impedance_mode = impedance_mode + + # Add to control dim based on impedance_mode + if self.impedance_mode == "variable": + self.control_dim *= 3 + elif self.impedance_mode == "variable_kp": + self.control_dim *= 2 + + # control frequency + self.control_freq = policy_freq + + # interpolator + self.interpolator = interpolator + + self.input_type = input_type + assert self.input_type in ["delta", "absolute"], f"Input type must be delta or absolute, got: {self.input_type}" + if self.input_type == "absolute": + assert self.impedance_mode == "fixed", "Absolute input type is only supported for fixed impedance mode." + + # initialize + self.goal_qpos = None + + def set_goal(self, action, set_qpos=None): + """ + Sets goal based on input @action. If self.impedance_mode is not "fixed", then the input will be parsed into the + delta values to update the goal position / pose and the kp and/or damping_ratio values to be immediately updated + internally before executing the proceeding control loop. + + Note that @action expected to be in the following format, based on impedance mode! + + :Mode `'fixed'`: [joint pos command] + :Mode `'variable'`: [damping_ratio values, kp values, joint pos command] + :Mode `'variable_kp'`: [kp values, joint pos command] + + Args: + action (Iterable): Desired relative joint position goal state + set_qpos (Iterable): If set, overrides @action and sets the desired absolute joint position goal state + + Raises: + AssertionError: [Invalid action dimension size] + """ + # Update state + self.update() + + if self.input_type == "delta": + # Parse action based on the impedance mode, and update kp / kd as necessary + jnt_dim = len(self.qpos_index) + if self.impedance_mode == "variable": + damping_ratio, kp, delta = action[:jnt_dim], action[jnt_dim : 2 * jnt_dim], action[2 * jnt_dim :] + self.kp = np.clip(kp, self.kp_min, self.kp_max) + self.kd = 2 * np.sqrt(self.kp) * np.clip(damping_ratio, self.damping_ratio_min, self.damping_ratio_max) + elif self.impedance_mode == "variable_kp": + kp, delta = action[:jnt_dim], action[jnt_dim:] + self.kp = np.clip(kp, self.kp_min, self.kp_max) + self.kd = 2 * np.sqrt(self.kp) # critically damped + else: # This is case "fixed" + delta = action + + # Check to make sure delta is size self.joint_dim + assert len(delta) == jnt_dim, "Delta qpos must be equal to the robot's joint dimension space!" + + if delta is not None: + scaled_delta = self.scale_action(delta) + else: + scaled_delta = None + + self.goal_qpos = set_goal_position( + scaled_delta, self.joint_pos, position_limit=self.position_limits, set_pos=set_qpos + ) + elif self.input_type == "absolute": + self.goal_qpos = action + + if self.interpolator is not None: + self.interpolator.set_goal(self.goal_qpos) + + def run_controller(self): + """ + Calculates the torques required to reach the desired setpoint + + Returns: + np.array: Command torques + """ + # Make sure goal has been set + if self.goal_qpos is None: + self.set_goal(np.zeros(self.control_dim)) + + # Update state + self.update() + + desired_qpos = None + + # Only linear interpolator is currently supported + if self.interpolator is not None: + # Linear case + if self.interpolator.order == 1: + desired_qpos = self.interpolator.get_interpolated_goal() + else: + # Nonlinear case not currently supported + pass + else: + desired_qpos = np.array(self.goal_qpos) + + position_error = desired_qpos - self.joint_pos + vel_pos_error = -self.joint_vel + desired_torque = np.multiply(np.array(position_error), np.array(self.kp)) + np.multiply(vel_pos_error, self.kd) + + # Return desired torques plus gravity compensations + self.torques = np.dot(self.mass_matrix, desired_torque) + self.torque_compensation + + # Always run superclass call for any cleanups at the end + super().run_controller() + return self.torques + + def reset_goal(self): + """ + Resets joint position goal to be current position + """ + self.goal_qpos = self.joint_pos + + # Reset interpolator if required + if self.interpolator is not None: + self.interpolator.set_goal(self.goal_qpos) + + @property + def control_limits(self): + """ + Returns the limits over this controller's action space, overrides the superclass property + Returns the following (generalized for both high and low limits), based on the impedance mode: + + :Mode `'fixed'`: [joint pos command] + :Mode `'variable'`: [damping_ratio values, kp values, joint pos command] + :Mode `'variable_kp'`: [kp values, joint pos command] + + Returns: + 2-tuple: + + - (np.array) minimum action values + - (np.array) maximum action values + """ + if self.impedance_mode == "variable": + low = np.concatenate([self.damping_ratio_min, self.kp_min, self.input_min]) + high = np.concatenate([self.damping_ratio_max, self.kp_max, self.input_max]) + elif self.impedance_mode == "variable_kp": + low = np.concatenate([self.kp_min, self.input_min]) + high = np.concatenate([self.kp_max, self.input_max]) + else: # This is case "fixed" + low, high = self.input_min, self.input_max + return low, high + + @property + def name(self): + return "JOINT_POSITION" diff --git a/third_party/robosuite/robosuite/controllers/parts/generic/joint_tor.py b/third_party/robosuite/robosuite/controllers/parts/generic/joint_tor.py new file mode 100644 index 0000000000000000000000000000000000000000..c7bd2bd7f6e6a01a2512414d0130b87dd03e6924 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/generic/joint_tor.py @@ -0,0 +1,176 @@ +import numpy as np + +from robosuite.controllers.parts.controller import Controller + + +class JointTorqueController(Controller): + """ + Controller for controlling the robot arm's joint torques. As the actuators at the mujoco sim level are already + torque actuators, this "controller" usually simply "passes through" desired torques, though it also includes the + typical input / output scaling and clipping, as well as interpolator features seen in other controllers classes + as well + + NOTE: Control input actions assumed to be taken as absolute joint torques. A given action to this + controller is assumed to be of the form: (torq_j0, torq_j1, ... , torq_jn-1) for an n-joint robot + + Args: + sim (MjSim): Simulator instance this controller will pull robot state updates from + + eef_name (str): Name of controlled robot arm's end effector (from robot XML) + + joint_indexes (dict): Each key contains sim reference indexes to relevant robot joint information, namely: + + :`'joints'`: list of indexes to relevant robot joints + :`'qpos'`: list of indexes to relevant robot joint positions + :`'qvel'`: list of indexes to relevant robot joint velocities + + actuator_range (2-tuple of array of float): 2-Tuple (low, high) representing the robot joint actuator range + + input_max (float or list of float): Maximum above which an inputted action will be clipped. Can be either be + a scalar (same value for all action dimensions), or a list (specific values for each dimension). If the + latter, dimension should be the same as the control dimension for this controller + + input_min (float or list of float): Minimum below which an inputted action will be clipped. Can be either be + a scalar (same value for all action dimensions), or a list (specific values for each dimension). If the + latter, dimension should be the same as the control dimension for this controller + + output_max (float or list of float): Maximum which defines upper end of scaling range when scaling an input + action. Can be either be a scalar (same value for all action dimensions), or a list (specific values for + each dimension). If the latter, dimension should be the same as the control dimension for this controller + + output_min (float or list of float): Minimum which defines upper end of scaling range when scaling an input + action. Can be either be a scalar (same value for all action dimensions), or a list (specific values for + each dimension). If the latter, dimension should be the same as the control dimension for this controller + + policy_freq (int): Frequency at which actions from the robot policy are fed into this controller + + torque_limits (2-list of float or 2-list of list of floats): Limits (N-m) below and above which the magnitude + of a calculated goal joint torque will be clipped. Can be either be a 2-list (same min/max value for all + joint dims), or a 2-list of list (specific min/max values for each dim) + If not specified, will automatically set the limits to the actuator limits for this robot arm + + interpolator (Interpolator): Interpolator object to be used for interpolating from the current joint torques to + the goal joint torques during each timestep between inputted actions + + **kwargs: Does nothing; placeholder to "sink" any additional arguments so that instantiating this controller + via an argument dict that has additional extraneous arguments won't raise an error + """ + + def __init__( + self, + sim, + joint_indexes, + actuator_range, + ref_name=None, + input_max=1, + input_min=-1, + output_max=0.05, + output_min=-0.05, + policy_freq=20, + lite_physics=True, + torque_limits=None, + interpolator=None, + **kwargs, # does nothing; used so no error raised when dict is passed with extra terms used previously + ): + + super().__init__( + sim, + ref_name=ref_name, + joint_indexes=joint_indexes, + actuator_range=actuator_range, + part_name=kwargs.get("part_name", None), + naming_prefix=kwargs.get("naming_prefix", None), + lite_physics=lite_physics, + ) + + # Control dimension + self.control_dim = len(joint_indexes["joints"]) + + # input and output max and min (allow for either explicit lists or single numbers) + self.input_max = self.nums2array(input_max, self.control_dim) + self.input_min = self.nums2array(input_min, self.control_dim) + self.output_max = self.nums2array(output_max, self.control_dim) + self.output_min = self.nums2array(output_min, self.control_dim) + + # limits (if not specified, set them to actuator limits by default) + self.torque_limits = np.array(torque_limits) if torque_limits is not None else self.actuator_limits + + # control frequency + self.control_freq = policy_freq + + # interpolator + self.interpolator = interpolator + + # initialize torques + self.goal_torque = None # Goal torque desired, pre-compensation + self.current_torque = np.zeros(self.control_dim) # Current torques being outputted, pre-compensation + self.torques = None # Torques returned every time run_controller is called + + def set_goal(self, torques): + """ + Sets goal based on input @torques. + + Args: + torques (Iterable): Desired joint torques + + Raises: + AssertionError: [Invalid action dimension size] + """ + # Update state + self.update() + + # Check to make sure torques is size self.joint_dim + assert len(torques) == self.control_dim, "Delta torque must be equal to the robot's joint dimension space!" + + self.goal_torque = np.clip(self.scale_action(torques), self.torque_limits[0], self.torque_limits[1]) + + if self.interpolator is not None: + self.interpolator.set_goal(self.goal_torque) + + def run_controller(self): + """ + Calculates the torques required to reach the desired setpoint + + Returns: + np.array: Command torques + """ + # Make sure goal has been set + if self.goal_torque is None: + self.set_goal(np.zeros(self.control_dim)) + + # Update state + self.update() + + # Only linear interpolator is currently supported + if self.interpolator is not None: + # Linear case + if self.interpolator.order == 1: + self.current_torque = self.interpolator.get_interpolated_goal() + else: + # Nonlinear case not currently supported + pass + else: + self.current_torque = np.array(self.goal_torque) + + # Add gravity compensation + self.torques = self.current_torque + self.torque_compensation + + # Always run superclass call for any cleanups at the end + super().run_controller() + + # Return final torques + return self.torques + + def reset_goal(self): + """ + Resets joint torque goal to be all zeros (pre-compensation) + """ + self.goal_torque = np.zeros(self.control_dim) + + # Reset interpolator if required + if self.interpolator is not None: + self.interpolator.set_goal(self.goal_torque) + + @property + def name(self): + return "JOINT_TORQUE" diff --git a/third_party/robosuite/robosuite/controllers/parts/generic/joint_vel.py b/third_party/robosuite/robosuite/controllers/parts/generic/joint_vel.py new file mode 100644 index 0000000000000000000000000000000000000000..727d92f21da8db33373e1d75b68cc0704d605f05 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/generic/joint_vel.py @@ -0,0 +1,216 @@ +import numpy as np + +from robosuite.controllers.parts.controller import Controller +from robosuite.utils.buffers import RingBuffer + + +class JointVelocityController(Controller): + """ + Controller for controlling the robot arm's joint velocities. This is simply a P controller with desired torques + (pre gravity compensation) taken to be proportional to the velocity error of the robot joints. + + NOTE: Control input actions assumed to be taken as absolute joint velocities. A given action to this + controller is assumed to be of the form: (vel_j0, vel_j1, ... , vel_jn-1) for an n-joint robot + + Args: + sim (MjSim): Simulator instance this controller will pull robot state updates from + + eef_name (str): Name of controlled robot arm's end effector (from robot XML) + + joint_indexes (dict): Each key contains sim reference indexes to relevant robot joint information, namely: + + :`'joints'`: list of indexes to relevant robot joints + :`'qpos'`: list of indexes to relevant robot joint positions + :`'qvel'`: list of indexes to relevant robot joint velocities + + actuator_range (2-tuple of array of float): 2-Tuple (low, high) representing the robot joint actuator range + + input_max (float or list of float): Maximum above which an inputted action will be clipped. Can be either be + a scalar (same value for all action dimensions), or a list (specific values for each dimension). If the + latter, dimension should be the same as the control dimension for this controller + + input_min (float or list of float): Minimum below which an inputted action will be clipped. Can be either be + a scalar (same value for all action dimensions), or a list (specific values for each dimension). If the + latter, dimension should be the same as the control dimension for this controller + + output_max (float or list of float): Maximum which defines upper end of scaling range when scaling an input + action. Can be either be a scalar (same value for all action dimensions), or a list (specific values for + each dimension). If the latter, dimension should be the same as the control dimension for this controller + + output_min (float or list of float): Minimum which defines upper end of scaling range when scaling an input + action. Can be either be a scalar (same value for all action dimensions), or a list (specific values for + each dimension). If the latter, dimension should be the same as the control dimension for this controller + + kp (float or list of float): velocity gain for determining desired torques based upon the joint vel errors. + Can be either be a scalar (same value for all action dims), or a list (specific values for each dim) + + policy_freq (int): Frequency at which actions from the robot policy are fed into this controller + + velocity_limits (2-list of float or 2-list of list of floats): Limits (m/s) below and above which the magnitude + of a calculated goal joint velocity will be clipped. Can be either be a 2-list (same min/max value for all + joint dims), or a 2-list of list (specific min/max values for each dim) + + interpolator (Interpolator): Interpolator object to be used for interpolating from the current joint velocities + to the goal joint velocities during each timestep between inputted actions + + **kwargs: Does nothing; placeholder to "sink" any additional arguments so that instantiating this controller + via an argument dict that has additional extraneous arguments won't raise an error + """ + + def __init__( + self, + sim, + joint_indexes, + actuator_range, + ref_name=None, + input_max=1, + input_min=-1, + output_max=1, + output_min=-1, + kp=0.25, + policy_freq=20, + lite_physics=True, + velocity_limits=None, + interpolator=None, + **kwargs, # does nothing; used so no error raised when dict is passed with extra terms used previously + ): + + super().__init__( + sim, + ref_name=ref_name, + joint_indexes=joint_indexes, + actuator_range=actuator_range, + part_name=kwargs.get("part_name", None), + naming_prefix=kwargs.get("naming_prefix", None), + lite_physics=lite_physics, + ) + # Control dimension + self.control_dim = len(joint_indexes["joints"]) + + # input and output max and min (allow for either explicit lists or single numbers) + self.input_max = self.nums2array(input_max, self.joint_dim) + self.input_min = self.nums2array(input_min, self.joint_dim) + self.output_max = self.nums2array(output_max, self.joint_dim) + self.output_min = self.nums2array(output_min, self.joint_dim) + + # gains and corresopnding vars + self.kp = self.nums2array(kp, self.joint_dim) + # if kp is a single value, map wrist gains accordingly (scale down x10 for final two joints) + + if type(kp) is float or type(kp) is int: + # Scale kpp according to how wide the actuator range is for this robot + low, high = self.actuator_limits + self.kp = kp * (high - low) + + self.ki = self.kp * 0.005 + self.kd = self.kp * 0.001 + self.last_err = np.zeros(self.joint_dim) + self.derr_buf = RingBuffer(dim=self.joint_dim, length=5) + self.summed_err = np.zeros(self.joint_dim) + self.saturated = False + self.last_joint_vel = np.zeros(self.joint_dim) + + # limits + self.velocity_limits = np.array(velocity_limits) if velocity_limits is not None else None + + # control frequency + self.control_freq = policy_freq + + # interpolator + self.interpolator = interpolator + + # initialize torques and goal velocity + self.goal_vel = None # Goal velocity desired, pre-compensation + self.current_vel = np.zeros(self.joint_dim) # Current velocity setpoint, pre-compensation + self.torques = None # Torques returned every time run_controller is called + + def set_goal(self, velocities): + """ + Sets goal based on input @velocities. + + Args: + velocities (Iterable): Desired joint velocities + + Raises: + AssertionError: [Invalid action dimension size] + """ + # Update state + self.update() + + # Otherwise, check to make sure velocities is size self.joint_dim + assert ( + len(velocities) == self.joint_dim + ), "Goal action must be equal to the robot's joint dimension space! Expected {}, got {}".format( + self.joint_dim, len(velocities) + ) + + self.goal_vel = self.scale_action(velocities) + if self.velocity_limits is not None: + self.goal_vel = np.clip(self.goal_vel, self.velocity_limits[0], self.velocity_limits[1]) + + if self.interpolator is not None: + self.interpolator.set_goal(self.goal_vel) + + def run_controller(self): + """ + Calculates the torques required to reach the desired setpoint + + Returns: + np.array: Command torques + """ + # Make sure goal has been set + if self.goal_vel is None: + self.set_goal(np.zeros(self.joint_dim)) + + # Update state + self.update() + + # Only linear interpolator is currently supported + if self.interpolator is not None: + if self.interpolator.order == 1: + # Linear case + self.current_vel = self.interpolator.get_interpolated_goal() + else: + # Nonlinear case not currently supported + pass + else: + self.current_vel = np.array(self.goal_vel) + + # Compute necessary error terms for PID velocity controller + err = self.current_vel - self.joint_vel + derr = err - self.last_err + self.last_err = err + self.derr_buf.push(derr) + + # Only add to I component if we're not saturated (anti-windup) + if not self.saturated: + self.summed_err += err + + # Compute command torques via PID velocity controller plus gravity compensation torques + torques = self.kp * err + self.ki * self.summed_err + self.kd * self.derr_buf.average + self.torque_compensation + + # Clip torques + self.torques = self.clip_torques(torques) + + # Check if we're saturated + self.saturated = False if np.sum(np.abs(self.torques - torques)) == 0 else True + + # Always run superclass call for any cleanups at the end + super().run_controller() + + # Return final torques + return self.torques + + def reset_goal(self): + """ + Resets joint velocity goal to be all zeros + """ + self.goal_vel = np.zeros(self.joint_dim) + + # Reset interpolator if required + if self.interpolator is not None: + self.interpolator.set_goal(self.goal_vel) + + @property + def name(self): + return "JOINT_VELOCITY" diff --git a/third_party/robosuite/robosuite/controllers/parts/gripper/__init__.py b/third_party/robosuite/robosuite/controllers/parts/gripper/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..677dde370c0a76dd6c04c90612d881286be33271 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/gripper/__init__.py @@ -0,0 +1 @@ +from .simple_grip import SimpleGripController diff --git a/third_party/robosuite/robosuite/controllers/parts/gripper/gripper_controller.py b/third_party/robosuite/robosuite/controllers/parts/gripper/gripper_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..122df17be9ad1084b3c0df61178af9f16e386602 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/gripper/gripper_controller.py @@ -0,0 +1,234 @@ +import abc +from collections.abc import Iterable + +import mujoco +import numpy as np + +import robosuite.macros as macros + + +class GripperController(object, metaclass=abc.ABCMeta): + """ + General controller interface. + + Requires reference to mujoco sim object, relevant joint_indexes to that robot, and + whether an initial_joint is used for nullspace torques or not + + Args: + sim (MjSim): Simulator instance this controller will pull robot state updates from + + eef_name (str): Name of controlled robot arm's end effector (from robot XML) + + joint_indexes (dict): Each key contains sim reference indexes to relevant robot joint information, namely: + + :`'joints'`: list of indexes to relevant robot joints + :`'qpos'`: list of indexes to relevant robot joint positions + :`'qvel'`: list of indexes to relevant robot joint velocities + + actuator_range (2-tuple of array of float): 2-Tuple (low, high) representing the robot joint actuator range + """ + + def __init__( + self, + sim, + joint_indexes, + actuator_range, + part_name=None, + naming_prefix=None, + ): + + # Actuator range + self.actuator_min = actuator_range[0] + self.actuator_max = actuator_range[1] + + # Attributes for scaling / clipping inputs to outputs + self.action_scale = None + self.action_input_transform = None + self.action_output_transform = None + + # Private property attributes + self.control_dim = None + self.output_min = None + self.output_max = None + self.input_min = None + self.input_max = None + + # mujoco simulator state + self.sim = sim + self.model_timestep = macros.SIMULATION_TIMESTEP + self.part_name = part_name + self.naming_prefix = naming_prefix + + self.joint_index = joint_indexes["joints"] + self.actuator_index = joint_indexes["actuators"] + self.qpos_index = joint_indexes["qpos"] + self.qvel_index = joint_indexes["qvel"] + + # robot states + self.joint_pos = None + self.joint_vel = None + + # Joint dimension + self.joint_dim = len(joint_indexes["joints"]) + + # Torques being outputted by the controller + self.torques = None + + # Update flag to prevent redundant update calls + self.new_update = True + + # Move forward one timestep to propagate updates before taking first update + self.sim.forward() + + # Initialize controller by updating internal state and setting the initial joint, pos, and ori + self.update() + self.initial_joint = self.joint_pos + self.previous_qpos = None + + @abc.abstractmethod + def run_controller(self): + """ + Abstract method that should be implemented in all subclass controllers, and should convert a given action + into torques (pre gravity compensation) to be executed on the robot. + Additionally, resets the self.new_update flag so that the next self.update call will occur + """ + self.new_update = True + + def scale_action(self, action): + """ + Clips @action to be within self.input_min and self.input_max, and then re-scale the values to be within + the range self.output_min and self.output_max + + Args: + action (Iterable): Actions to scale + + Returns: + np.array: Re-scaled action + """ + + if self.action_scale is None: + self.action_scale = abs(self.output_max - self.output_min) / abs(self.input_max - self.input_min) + self.action_output_transform = (self.output_max + self.output_min) / 2.0 + self.action_input_transform = (self.input_max + self.input_min) / 2.0 + action = np.clip(action, self.input_min, self.input_max) + transformed_action = (action - self.action_input_transform) * self.action_scale + self.action_output_transform + + return transformed_action + + def update(self, force=False): + """ + Updates the state of the robot arm, including end effector pose / orientation / velocity, joint pos/vel, + jacobian, and mass matrix. By default, since this is a non-negligible computation, multiple redundant calls + will be ignored via the self.new_update attribute flag. However, if the @force flag is set, the update will + occur regardless of that state of self.new_update. This base class method of @run_controller resets the + self.new_update flag + + Args: + force (bool): Whether to force an update to occur or not + """ + + # Only run update if self.new_update or force flag is set + if self.new_update or force: + + self.joint_pos = np.array(self.sim.data.qpos[self.qpos_index]) + self.joint_vel = np.array(self.sim.data.qvel[self.qvel_index]) + # Clear self.new_update + self.new_update = False + + def update_initial_joints(self, initial_joints): + """ + Updates the internal attribute self.initial_joints. This is useful for updating changes in controller-specific + behavior, such as with OSC where self.initial_joints is used for determine nullspace actions + + This function can also be extended by subclassed controllers for additional controller-specific updates + + Args: + initial_joints (Iterable): Array of joint position values to update the initial joints + """ + self.initial_joint = np.array(initial_joints) + self.update(force=True) + + def clip_torques(self, torques): + """ + Clips the torques to be within the actuator limits + + Args: + torques (Iterable): Torques to clip + + Returns: + np.array: Clipped torques + """ + return np.clip(torques, self.actuator_min, self.actuator_max) + + def reset_goal(self): + """ + Resets the goal -- usually by setting to the goal to all zeros, but in some cases may be different (e.g.: OSC) + """ + raise NotImplementedError + + @staticmethod + def nums2array(nums, dim): + """ + Convert input @nums into numpy array of length @dim. If @nums is a single number, broadcasts it to the + corresponding dimension size @dim before converting into a numpy array + + Args: + nums (numeric or Iterable): Either single value or array of numbers + dim (int): Size of array to broadcast input to env.sim.data.actuator_force + + Returns: + np.array: Array filled with values specified in @nums + """ + # First run sanity check to make sure no strings are being inputted + if isinstance(nums, str): + raise TypeError("Error: Only numeric inputs are supported for this function, nums2array!") + + # Check if input is an Iterable, if so, we simply convert the input to np.array and return + # Else, input is a single value, so we map to a numpy array of correct size and return + return np.array(nums) if isinstance(nums, Iterable) else np.ones(dim) * nums + + @property + def torque_compensation(self): + """ + Gravity compensation for this robot arm + + Returns: + np.array: torques + """ + return self.sim.data.qfrc_bias[self.qvel_index] + + @property + def actuator_limits(self): + """ + Torque limits for this controller + + Returns: + 2-tuple: + + - (np.array) minimum actuator torques + - (np.array) maximum actuator torques + """ + return self.actuator_min, self.actuator_max + + @property + def control_limits(self): + """ + Limits over this controller's action space, which defaults to input min/max + + Returns: + 2-tuple: + + - (np.array) minimum action values + - (np.array) maximum action values + """ + return self.input_min, self.input_max + + @property + def name(self): + """ + Name of this controller + + Returns: + str: controller name + """ + raise NotImplementedError diff --git a/third_party/robosuite/robosuite/controllers/parts/gripper/simple_grip.py b/third_party/robosuite/robosuite/controllers/parts/gripper/simple_grip.py new file mode 100644 index 0000000000000000000000000000000000000000..359b5ebcc7401df63e9ab94d48d757fa3131a389 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/gripper/simple_grip.py @@ -0,0 +1,213 @@ +"""This is a controller that controls the fingers / grippers to do naive gripping. No matter how many fingers the gripper has, they all move in the same direction.""" + +import numpy as np + +from robosuite.controllers.parts.gripper.gripper_controller import GripperController +from robosuite.utils.control_utils import * + +# Supported impedance modes + + +class SimpleGripController(GripperController): + """ + Controller for controlling robot arm via impedance control. Allows position control of the robot's joints. + + NOTE: Control input actions assumed to be taken relative to the current joint positions. A given action to this + controller is assumed to be of the form: (dpos_j0, dpos_j1, ... , dpos_jn-1) for an n-joint robot + + Args: + sim (MjSim): Simulator instance this controller will pull robot state updates from + + eef_name (str): Name of controlled robot arm's end effector (from robot XML) + + joint_indexes (dict): Each key contains sim reference indexes to relevant robot joint information, namely: + + :`'joints'`: list of indexes to relevant robot joints + :`'qpos'`: list of indexes to relevant robot joint positions + :`'qvel'`: list of indexes to relevant robot joint velocities + + actuator_range (2-tuple of array of float): 2-Tuple (low, high) representing the robot joint actuator range + + input_max (float or Iterable of float): Maximum above which an inputted action will be clipped. Can be either be + a scalar (same value for all action dimensions), or a list (specific values for each dimension). If the + latter, dimension should be the same as the control dimension for this controller + + input_min (float or Iterable of float): Minimum below which an inputted action will be clipped. Can be either be + a scalar (same value for all action dimensions), or a list (specific values for each dimension). If the + latter, dimension should be the same as the control dimension for this controller + + output_max (float or Iterable of float): Maximum which defines upper end of scaling range when scaling an input + action. Can be either be a scalar (same value for all action dimensions), or a list (specific values for + each dimension). If the latter, dimension should be the same as the control dimension for this controller + + output_min (float or Iterable of float): Minimum which defines upper end of scaling range when scaling an input + action. Can be either be a scalar (same value for all action dimensions), or a list (specific values for + each dimension). If the latter, dimension should be the same as the control dimension for this controller + + policy_freq (int): Frequency at which actions from the robot policy are fed into this controller + + qpos_limits (2-list of float or 2-list of Iterable of floats): Limits (rad) below and above which the magnitude + of a calculated goal joint position will be clipped. Can be either be a 2-list (same min/max value for all + joint dims), or a 2-list of list (specific min/max values for each dim) + + interpolator (Interpolator): Interpolator object to be used for interpolating from the current joint position to + the goal joint position during each timestep between inputted actions + + **kwargs: Does nothing; placeholder to "sink" any additional arguments so that instantiating this controller + via an argument dict that has additional extraneous arguments won't raise an error + + Raises: + AssertionError: [Invalid impedance mode] + """ + + def __init__( + self, + sim, + joint_indexes, + actuator_range, + input_max=1, + input_min=-1, + output_max=1, + output_min=-1, + policy_freq=20, + qpos_limits=None, + interpolator=None, + use_action_scaling=True, + **kwargs, # does nothing; used so no error raised when dict is passed with extra terms used previously + ): + super().__init__( + sim, + joint_indexes, + actuator_range, + part_name=kwargs.get("part_name", None), + naming_prefix=kwargs.get("naming_prefix", None), + ) + + # Control dimension + self.control_dim = len(joint_indexes["actuators"]) + + # input and output max and min (allow for either explicit lists or single numbers) + self.input_max = self.nums2array(input_max, self.control_dim) + self.input_min = self.nums2array(input_min, self.control_dim) + self.output_max = self.nums2array(output_max, self.control_dim) + self.output_min = self.nums2array(output_min, self.control_dim) + + # limits + self.position_limits = np.array(qpos_limits) if qpos_limits is not None else qpos_limits + + # control frequency + self.control_freq = policy_freq + + # interpolator + self.interpolator = interpolator + + # action scaling + self.use_action_scaling = use_action_scaling + + # initialize + self.goal_qvel = None + + def set_goal(self, action, set_qpos=None): + """ + Sets goal based on input @action. If self.impedance_mode is not "fixed", then the input will be parsed into the + delta values to update the goal position / pose and the kp and/or damping_ratio values to be immediately updated + internally before executing the proceeding control loop. + + Note that @action expected to be in the following format, based on impedance mode! + + :Mode `'fixed'`: [joint pos command] + :Mode `'variable'`: [damping_ratio values, kp values, joint pos command] + :Mode `'variable_kp'`: [kp values, joint pos command] + + Args: + action (Iterable): Desired relative joint position goal state + set_qpos (Iterable): If set, overrides @action and sets the desired absolute joint position goal state + + Raises: + AssertionError: [Invalid action dimension size] + """ + # Update state + self.update() + + # Parse action based on the impedance mode, and update kp / kd as necessary + delta = action + + # Check to make sure delta is size self.joint_dim + assert len(delta) == self.control_dim, ( + f"Delta qpos must be equal to the control dimension of the robot!" + f"Expected {self.control_dim}, got {len(delta)}" + ) + + scaled_delta = delta + if self.use_action_scaling: + scaled_delta = self.scale_action(delta) + + self.goal_qvel = scaled_delta + + if self.interpolator is not None: + self.interpolator.set_goal(self.goal_qvel) + + def run_controller(self): + """ + Calculates the torques required to reach the desired setpoint + + Returns: + np.array: Command torques + """ + # Make sure goal has been set + if self.goal_qvel is None: + self.set_goal(np.zeros(self.control_dim)) + + # Update state + self.update() + + desired_qvel = None + + # Only linear interpolator is currently supported + if self.interpolator is not None: + # Linear case + if self.interpolator.order == 1: + desired_qvel = self.interpolator.get_interpolated_goal() + else: + # Nonlinear case not currently supported + pass + else: + desired_qvel = np.array(self.goal_qvel) + + self.vels = desired_qvel + if self.use_action_scaling: + ctrl_range = np.stack([self.actuator_min, self.actuator_max], axis=-1) + bias = 0.5 * (ctrl_range[:, 1] + ctrl_range[:, 0]) + weight = 0.5 * (ctrl_range[:, 1] - ctrl_range[:, 0]) + self.vels = bias + weight * desired_qvel + + # Always run superclass call for any cleanups at the end + super().run_controller() + return self.vels + + def reset_goal(self): + """ + Resets joint position goal to be current position + """ + self.goal_qvel = self.joint_vel + + # Reset interpolator if required + if self.interpolator is not None: + self.interpolator.set_goal(self.goal_qvel) + + @property + def control_limits(self): + """ + Returns the limits over this controller's action space, overrides the superclass property + Returns the following (generalized for both high and low limits), based on the impedance mode: + Returns: + 2-tuple: + + - (np.array) minimum action values + - (np.array) maximum action values + """ + return self.input_min, self.input_max + + @property + def name(self): + return "JOINT_VELOCITY" diff --git a/third_party/robosuite/robosuite/controllers/parts/mobile_base/__init__.py b/third_party/robosuite/robosuite/controllers/parts/mobile_base/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..530053c9fab24662015cfc1b8cd48901932191cc --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/mobile_base/__init__.py @@ -0,0 +1 @@ +from .joint_vel import MobileBaseJointVelocityController diff --git a/third_party/robosuite/robosuite/controllers/parts/mobile_base/joint_vel.py b/third_party/robosuite/robosuite/controllers/parts/mobile_base/joint_vel.py new file mode 100644 index 0000000000000000000000000000000000000000..4ed0eb80c6a402450fa584d20c3000f1eea54aa7 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/mobile_base/joint_vel.py @@ -0,0 +1,302 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.controllers.parts.mobile_base.mobile_base_controller import MobileBaseController +from robosuite.utils.control_utils import * + +# Supported impedance modes +IMPEDANCE_MODES = {"fixed", "variable", "variable_kp"} + + +class MobileBaseJointVelocityController(MobileBaseController): + """ + Controller for controlling robot arm via impedance control. Allows position control of the robot's joints. + + NOTE: Control input actions assumed to be taken relative to the current joint positions. A given action to this + controller is assumed to be of the form: (dpos_j0, dpos_j1, ... , dpos_jn-1) for an n-joint robot + + Args: + sim (MjSim): Simulator instance this controller will pull robot state updates from + + joint_indexes (dict): Each key contains sim reference indexes to relevant robot joint information, namely: + + :`'joints'`: list of indexes to relevant robot joints + :`'qpos'`: list of indexes to relevant robot joint positions + :`'qvel'`: list of indexes to relevant robot joint velocities + + actuator_range (2-tuple of array of float): 2-Tuple (low, high) representing the robot joint actuator range + + input_max (float or Iterable of float): Maximum above which an inputted action will be clipped. Can be either be + a scalar (same value for all action dimensions), or a list (specific values for each dimension). If the + latter, dimension should be the same as the control dimension for this controller + + input_min (float or Iterable of float): Minimum below which an inputted action will be clipped. Can be either be + a scalar (same value for all action dimensions), or a list (specific values for each dimension). If the + latter, dimension should be the same as the control dimension for this controller + + output_max (float or Iterable of float): Maximum which defines upper end of scaling range when scaling an input + action. Can be either be a scalar (same value for all action dimensions), or a list (specific values for + each dimension). If the latter, dimension should be the same as the control dimension for this controller + + output_min (float or Iterable of float): Minimum which defines upper end of scaling range when scaling an input + action. Can be either be a scalar (same value for all action dimensions), or a list (specific values for + each dimension). If the latter, dimension should be the same as the control dimension for this controller + + kp (float or Iterable of float): positional gain for determining desired torques based upon the joint pos error. + Can be either be a scalar (same value for all action dims), or a list (specific values for each dim) + + damping_ratio (float or Iterable of float): used in conjunction with kp to determine the velocity gain for + determining desired torques based upon the joint pos errors. Can be either be a scalar (same value for all + action dims), or a list (specific values for each dim) + + impedance_mode (str): Impedance mode with which to run this controller. Options are {"fixed", "variable", + "variable_kp"}. If "fixed", the controller will have fixed kp and damping_ratio values as specified by the + @kp and @damping_ratio arguments. If "variable", both kp and damping_ratio will now be part of the + controller action space, resulting in a total action space of num_joints * 3. If "variable_kp", only kp + will become variable, with damping_ratio fixed at 1 (critically damped). The resulting action space will + then be num_joints * 2. + + kp_limits (2-list of float or 2-list of Iterable of floats): Only applicable if @impedance_mode is set to either + "variable" or "variable_kp". This sets the corresponding min / max ranges of the controller action space + for the varying kp values. Can be either be a 2-list (same min / max for all kp action dims), or a 2-list + of list (specific min / max for each kp dim) + + damping_ratio_limits (2-list of float or 2-list of Iterable of floats): Only applicable if @impedance_mode is + set to "variable". This sets the corresponding min / max ranges of the controller action space for the + varying damping_ratio values. Can be either be a 2-list (same min / max for all damping_ratio action dims), + or a 2-list of list (specific min / max for each damping_ratio dim) + + policy_freq (int): Frequency at which actions from the robot policy are fed into this controller + + qpos_limits (2-list of float or 2-list of Iterable of floats): Limits (rad) below and above which the magnitude + of a calculated goal joint position will be clipped. Can be either be a 2-list (same min/max value for all + joint dims), or a 2-list of list (specific min/max values for each dim) + + interpolator (Interpolator): Interpolator object to be used for interpolating from the current joint position to + the goal joint position during each timestep between inputted actions + + **kwargs: Does nothing; placeholder to "sink" any additional arguments so that instantiating this controller + via an argument dict that has additional extraneous arguments won't raise an error + + Raises: + AssertionError: [Invalid impedance mode] + """ + + def __init__( + self, + sim, + joint_indexes, + actuator_range, + input_max=1, + input_min=-1, + output_max=1, + output_min=-1, + kp=50, + damping_ratio=1, + impedance_mode="fixed", + kp_limits=(0, 300), + damping_ratio_limits=(0, 100), + policy_freq=20, + qpos_limits=None, + interpolator=None, + **kwargs, # does nothing; used so no error raised when dict is passed with extra terms used previously + ): + super().__init__( + sim, + joint_indexes, + actuator_range, + naming_prefix=kwargs.get("naming_prefix", None), + ) + + # Control dimension + self.control_dim = len(joint_indexes["joints"]) + + # input and output max and min (allow for either explicit lists or single numbers) + self.input_max = self.nums2array(input_max, self.control_dim) + self.input_min = self.nums2array(input_min, self.control_dim) + self.output_max = self.nums2array(output_max, self.control_dim) + self.output_min = self.nums2array(output_min, self.control_dim) + + # limits + self.position_limits = np.array(qpos_limits) if qpos_limits is not None else qpos_limits + + # kp kd + self.kp = self.nums2array(kp, self.control_dim) + self.kd = 2 * np.sqrt(self.kp) * damping_ratio + + # kp and kd limits + self.kp_min = self.nums2array(kp_limits[0], self.control_dim) + self.kp_max = self.nums2array(kp_limits[1], self.control_dim) + self.damping_ratio_min = self.nums2array(damping_ratio_limits[0], self.control_dim) + self.damping_ratio_max = self.nums2array(damping_ratio_limits[1], self.control_dim) + + # Verify the proposed impedance mode is supported + assert impedance_mode in IMPEDANCE_MODES, ( + "Error: Tried to instantiate OSC controller for unsupported " + "impedance mode! Inputted impedance mode: {}, Supported modes: {}".format(impedance_mode, IMPEDANCE_MODES) + ) + + # Impedance mode + self.impedance_mode = impedance_mode + + # Add to control dim based on impedance_mode + if self.impedance_mode == "variable": + self.control_dim *= 3 + elif self.impedance_mode == "variable_kp": + self.control_dim *= 2 + + # control frequency + self.control_freq = policy_freq + + # interpolator + self.interpolator = interpolator + + # initialize + self.goal_qvel = None + self.init_pos = None + self.init_ori = None + + def set_goal(self, action, set_qpos=None): + """ + Sets goal based on input @action. If self.impedance_mode is not "fixed", then the input will be parsed into the + delta values to update the goal position / pose and the kp and/or damping_ratio values to be immediately updated + internally before executing the proceeding control loop. + + Note that @action expected to be in the following format, based on impedance mode! + + :Mode `'fixed'`: [joint pos command] + :Mode `'variable'`: [damping_ratio values, kp values, joint pos command] + :Mode `'variable_kp'`: [kp values, joint pos command] + + Args: + action (Iterable): Desired relative joint position goal state + set_qpos (Iterable): If set, overrides @action and sets the desired absolute joint position goal state + + Raises: + AssertionError: [Invalid action dimension size] + """ + # Update state + self.update() + + # Parse action based on the impedance mode, and update kp / kd as necessary + jnt_dim = len(self.qpos_index) + if self.impedance_mode == "variable": + damping_ratio, kp, delta = action[:jnt_dim], action[jnt_dim : 2 * jnt_dim], action[2 * jnt_dim :] + self.kp = np.clip(kp, self.kp_min, self.kp_max) + self.kd = 2 * np.sqrt(self.kp) * np.clip(damping_ratio, self.damping_ratio_min, self.damping_ratio_max) + elif self.impedance_mode == "variable_kp": + kp, delta = action[:jnt_dim], action[jnt_dim:] + self.kp = np.clip(kp, self.kp_min, self.kp_max) + self.kd = 2 * np.sqrt(self.kp) # critically damped + else: # This is case "fixed" + delta = action + + # Check to make sure delta is size self.joint_dim + assert len(delta) == jnt_dim, "Delta qpos must be equal to the robot's joint dimension space!" + + if delta is not None: + scaled_delta = self.scale_action(delta) + else: + scaled_delta = None + + curr_pos, curr_ori = self.get_base_pose() + + # transform the action relative to initial base orientation + init_theta = T.mat2euler(self.init_ori)[2] # np.arctan2(self.init_pos[1], self.init_pos[0]) + curr_theta = T.mat2euler(curr_ori)[2] # np.arctan2(curr_pos[1], curr_pos[0]) + theta = curr_theta - init_theta + + base_action = np.copy([action[i] for i in [1, 0, 2]]) + # input raw base action is delta relative to current pose of base + # controller expects deltas relative to initial pose of base at start of episode + # transform deltas from current base pose coordinates to initial base pose coordinates + x, y = base_action[0:2] + + # do the reverse of theta rotation + base_action[0] = x * np.cos(theta) + y * np.sin(theta) + base_action[1] = -x * np.sin(theta) + y * np.cos(theta) + + self.goal_qvel = base_action + if self.interpolator is not None: + self.interpolator.set_goal(self.goal_qvel) + + def run_controller(self): + """ + Calculates the torques required to reach the desired setpoint + + Returns: + np.array: Command torques + """ + # Make sure goal has been set + if self.goal_qvel is None: + self.set_goal(np.zeros(self.control_dim)) + + # Update state + self.update() + + desired_qvel = None + + # Only linear interpolator is currently supported + if self.interpolator is not None: + # Linear case + if self.interpolator.order == 1: + desired_qvel = self.interpolator.get_interpolated_goal() + else: + # Nonlinear case not currently supported + pass + else: + desired_qvel = np.array(self.goal_qvel) + + self.vels = desired_qvel + + ctrl_range = np.stack([self.actuator_min, self.actuator_max], axis=-1) + bias = 0.5 * (ctrl_range[:, 1] + ctrl_range[:, 0]) + weight = 0.5 * (ctrl_range[:, 1] - ctrl_range[:, 0]) + self.vels = bias + weight * self.vels + + # Always run superclass call for any cleanups at the end + super().run_controller() + + return self.vels + + def reset_goal(self): + """ + Resets joint position goal to be current position + """ + self.goal_qvel = self.joint_vel + + self.init_pos, self.init_ori = self.get_base_pose() + + # Reset interpolator if required + if self.interpolator is not None: + self.interpolator.set_goal(self.goal_qvel) + + @property + def control_limits(self): + """ + Returns the limits over this controller's action space, overrides the superclass property + Returns the following (generalized for both high and low limits), based on the impedance mode: + + :Mode `'fixed'`: [joint pos command] + :Mode `'variable'`: [damping_ratio values, kp values, joint pos command] + :Mode `'variable_kp'`: [kp values, joint pos command] + + Returns: + 2-tuple: + + - (np.array) minimum action values + - (np.array) maximum action values + """ + if self.impedance_mode == "variable": + low = np.concatenate([self.damping_ratio_min, self.kp_min, self.input_min]) + high = np.concatenate([self.damping_ratio_max, self.kp_max, self.input_max]) + elif self.impedance_mode == "variable_kp": + low = np.concatenate([self.kp_min, self.input_min]) + high = np.concatenate([self.kp_max, self.input_max]) + else: # This is case "fixed" + low, high = self.input_min, self.input_max + return low, high + + @property + def name(self): + return "JOINT_VELOCITY" diff --git a/third_party/robosuite/robosuite/controllers/parts/mobile_base/mobile_base_controller.py b/third_party/robosuite/robosuite/controllers/parts/mobile_base/mobile_base_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..d06c4b58ab48a9bc79d432ee92a045663c861f59 --- /dev/null +++ b/third_party/robosuite/robosuite/controllers/parts/mobile_base/mobile_base_controller.py @@ -0,0 +1,249 @@ +import abc +from collections.abc import Iterable + +import mujoco +import numpy as np + +import robosuite.macros as macros + + +class MobileBaseController(object, metaclass=abc.ABCMeta): + """ + General controller interface. + + Requires reference to mujoco sim object, relevant joint_indexes to that robot, and + whether an initial_joint is used for nullspace torques or not + + Args: + sim (MjSim): Simulator instance this controller will pull robot state updates from + + joint_indexes (dict): Each key contains sim reference indexes to relevant robot joint information, namely: + + :`'joints'`: list of indexes to relevant robot joints + :`'qpos'`: list of indexes to relevant robot joint positions + :`'qvel'`: list of indexes to relevant robot joint velocities + + actuator_range (2-tuple of array of float): 2-Tuple (low, high) representing the robot joint actuator range + """ + + def __init__( + self, + sim, + joint_indexes, + actuator_range, + naming_prefix=None, + ): + + # Actuator range + self.actuator_min = actuator_range[0] + self.actuator_max = actuator_range[1] + + # Attributes for scaling / clipping inputs to outputs + self.action_scale = None + self.action_input_transform = None + self.action_output_transform = None + + # Private property attributes + self.control_dim = None + self.output_min = None + self.output_max = None + self.input_min = None + self.input_max = None + + # mujoco simulator state + self.sim = sim + self.model_timestep = macros.SIMULATION_TIMESTEP + self.naming_prefix = naming_prefix + + self.joint_index = joint_indexes["joints"] + self.qpos_index = joint_indexes["qpos"] + self.qvel_index = joint_indexes["qvel"] + self.joint_names = [self.sim.model.joint_id2name(joint_id) for joint_id in self.joint_index] + + # robot states + self.joint_pos = None + self.joint_vel = None + + # Joint dimension + self.joint_dim = len(joint_indexes["joints"]) + + # Torques being outputted by the controller + self.torques = None + + # Update flag to prevent redundant update calls + self.new_update = True + + # Move forward one timestep to propagate updates before taking first update + self.sim.forward() + + # Initialize controller by updating internal state and setting the initial joint, pos, and ori + self.update() + self.initial_joint = self.joint_pos + + self.base_pos = None + self.base_ori_mat = None + + self.init_pos = None + self.init_ori = None + + def get_base_pose(self): + base_pos = np.array(self.sim.data.site_xpos[self.sim.model.site_name2id(f"{self.naming_prefix}center")]) + base_ori = np.array( + self.sim.data.site_xmat[self.sim.model.site_name2id(f"{self.naming_prefix}center")].reshape([3, 3]) + ) + return base_pos, base_ori + + def reset(self): + self.init_pos = self.base_pos + self.init_ori = self.base_ori_mat + + @abc.abstractmethod + def run_controller(self): + """ + Abstract method that should be implemented in all subclass controllers, and should convert a given action + into torques (pre gravity compensation) to be executed on the robot. + Additionally, resets the self.new_update flag so that the next self.update call will occur + """ + self.new_update = True + + def scale_action(self, action): + """ + Clips @action to be within self.input_min and self.input_max, and then re-scale the values to be within + the range self.output_min and self.output_max + + Args: + action (Iterable): Actions to scale + + Returns: + np.array: Re-scaled action + """ + + if self.action_scale is None: + self.action_scale = abs(self.output_max - self.output_min) / abs(self.input_max - self.input_min) + self.action_output_transform = (self.output_max + self.output_min) / 2.0 + self.action_input_transform = (self.input_max + self.input_min) / 2.0 + action = np.clip(action, self.input_min, self.input_max) + transformed_action = (action - self.action_input_transform) * self.action_scale + self.action_output_transform + + return transformed_action + + def update(self, force=False): + """ + Updates the state of the robot arm, including end effector pose / orientation / velocity, joint pos/vel, + jacobian, and mass matrix. By default, since this is a non-negligible computation, multiple redundant calls + will be ignored via the self.new_update attribute flag. However, if the @force flag is set, the update will + occur regardless of that state of self.new_update. This base class method of @run_controller resets the + self.new_update flag + + Args: + force (bool): Whether to force an update to occur or not + """ + + # Only run update if self.new_update or force flag is set + if self.new_update or force: + + self.joint_pos = np.array(self.sim.data.qpos[self.qpos_index]) + self.joint_vel = np.array(self.sim.data.qvel[self.qvel_index]) + + # Clear self.new_update + self.new_update = False + + def update_initial_joints(self, initial_joints): + """ + Updates the internal attribute self.initial_joints. This is useful for updating changes in controller-specific + behavior, such as with OSC where self.initial_joints is used for determine nullspace actions + + This function can also be extended by subclassed controllers for additional controller-specific updates + + Args: + initial_joints (Iterable): Array of joint position values to update the initial joints + """ + self.initial_joint = np.array(initial_joints) + self.update(force=True) + self.initial_ref_pos = self.ref_pos + self.initial_ref_ori_mat = self.ref_ori_mat + + def clip_torques(self, torques): + """ + Clips the torques to be within the actuator limits + + Args: + torques (Iterable): Torques to clip + + Returns: + np.array: Clipped torques + """ + return np.clip(torques, self.actuator_min, self.actuator_max) + + def reset_goal(self): + """ + Resets the goal -- usually by setting to the goal to all zeros, but in some cases may be different (e.g.: OSC) + """ + raise NotImplementedError + + @staticmethod + def nums2array(nums, dim): + """ + Convert input @nums into numpy array of length @dim. If @nums is a single number, broadcasts it to the + corresponding dimension size @dim before converting into a numpy array + + Args: + nums (numeric or Iterable): Either single value or array of numbers + dim (int): Size of array to broadcast input to env.sim.data.actuator_force + + Returns: + np.array: Array filled with values specified in @nums + """ + # First run sanity check to make sure no strings are being inputted + if isinstance(nums, str): + raise TypeError("Error: Only numeric inputs are supported for this function, nums2array!") + + # Check if input is an Iterable, if so, we simply convert the input to np.array and return + # Else, input is a single value, so we map to a numpy array of correct size and return + return np.array(nums) if isinstance(nums, Iterable) else np.ones(dim) * nums + + @property + def torque_compensation(self): + """ + Gravity compensation for this robot arm + + Returns: + np.array: torques + """ + return self.sim.data.qfrc_bias[self.qvel_index] + + @property + def actuator_limits(self): + """ + Torque limits for this controller + + Returns: + 2-tuple: + + - (np.array) minimum actuator torques + - (np.array) maximum actuator torques + """ + return self.actuator_min, self.actuator_max + + @property + def control_limits(self): + """ + Limits over this controller's action space, which defaults to input min/max + + Returns: + 2-tuple: + + - (np.array) minimum action values + - (np.array) maximum action values + """ + return self.input_min, self.input_max + + @property + def name(self): + """ + Name of this controller + + Returns: + str: controller name + """ + raise NotImplementedError diff --git a/third_party/robosuite/robosuite/demos/demo_collect_and_playback_data.py b/third_party/robosuite/robosuite/demos/demo_collect_and_playback_data.py new file mode 100644 index 0000000000000000000000000000000000000000..0dd3a4806178af9e4498dfd33827218b9a2568b2 --- /dev/null +++ b/third_party/robosuite/robosuite/demos/demo_collect_and_playback_data.py @@ -0,0 +1,132 @@ +""" +Record trajectory data with the DataCollectionWrapper wrapper and play them back. + +Example: + $ python demo_collect_and_playback_data.py --environment Lift +""" + +import argparse +import os +import time +from glob import glob + +import numpy as np + +import robosuite as suite +from robosuite.wrappers import DataCollectionWrapper + + +def collect_random_trajectory(env, timesteps=1000, max_fr=None): + """Run a random policy to collect trajectories. + + The rollout trajectory is saved to files in npz format. + Modify the DataCollectionWrapper wrapper to add new fields or change data formats. + + Args: + env (MujocoEnv): environment instance to collect trajectories from + timesteps(int): how many environment timesteps to run for a given trajectory + max_fr (int): if specified, pause the simulation whenever simulation runs faster than max_fr + """ + + env.reset() + dof = env.action_dim + + for t in range(timesteps): + start = time.time() + action = np.random.randn(dof) + env.step(action) + env.render() + if t % 100 == 0: + print(t) + + # limit frame rate if necessary + if max_fr is not None: + elapsed = time.time() - start + diff = 1 / max_fr - elapsed + if diff > 0: + time.sleep(diff) + + +def playback_trajectory(env, ep_dir, max_fr=None): + """Playback data from an episode. + + Args: + env (MujocoEnv): environment instance to playback trajectory in + ep_dir (str): The path to the directory containing data for an episode. + """ + + # first reload the model from the xml + xml_path = os.path.join(ep_dir, "model.xml") + with open(xml_path, "r") as f: + env.reset_from_xml_string(f.read()) + + state_paths = os.path.join(ep_dir, "state_*.npz") + + # read states back, load them one by one, and render + t = 0 + for state_file in sorted(glob(state_paths)): + print(state_file) + dic = np.load(state_file) + states = dic["states"] + for state in states: + start = time.time() + env.sim.set_state_from_flattened(state) + env.sim.forward() + env.viewer.update() + env.render() + t += 1 + if t % 100 == 0: + print(t) + + if max_fr is not None: + elapsed = time.time() - start + diff = 1 / max_fr - elapsed + if diff > 0: + time.sleep(diff) + env.close() + + +if __name__ == "__main__": + + parser = argparse.ArgumentParser() + parser.add_argument("--environment", type=str, default="Door") + parser.add_argument("--robots", nargs="+", type=str, default="Panda", help="Which robot(s) to use in the env") + parser.add_argument("--directory", type=str, default="/tmp/") + parser.add_argument("--timesteps", type=int, default=1000) + parser.add_argument( + "--max_fr", + default=20, + type=int, + help="Sleep when simluation runs faster than specified frame rate; 20 fps is real time.", + ) + args = parser.parse_args() + + # create original environment + env = suite.make( + args.environment, + robots=args.robots, + ignore_done=True, + use_camera_obs=False, + has_renderer=True, + has_offscreen_renderer=False, + control_freq=20, + ) + data_directory = args.directory + + # wrap the environment with data collection wrapper + env = DataCollectionWrapper(env, data_directory) + + # testing to make sure multiple env.reset calls don't create multiple directories + env.reset() + env.reset() + env.reset() + + # collect some data + print("Collecting some random data...") + collect_random_trajectory(env, timesteps=args.timesteps, max_fr=args.max_fr) + + # playback some data + _ = input("Press any key to begin the playback...") + print("Playing back the data...") + data_directory = env.ep_directory + playback_trajectory(env, data_directory, args.max_fr) diff --git a/third_party/robosuite/robosuite/demos/demo_composite_robot.py b/third_party/robosuite/robosuite/demos/demo_composite_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..9fb14c813920084ad3e89db8b41c52175077f92d --- /dev/null +++ b/third_party/robosuite/robosuite/demos/demo_composite_robot.py @@ -0,0 +1,85 @@ +import argparse +import time +from typing import Dict, List, Union + +import numpy as np + +import robosuite as suite +from robosuite.controllers import load_composite_controller_config +from robosuite.robots import ROBOT_CLASS_MAPPING +from robosuite.utils.robot_composition_utils import create_composite_robot + + +def create_and_test_env( + env: str, + robots: Union[str, List[str]], + controller_config: Dict, + headless: bool = False, + max_fr: int = None, +): + + config = { + "env_name": env, + "robots": robots, + "controller_configs": controller_config, + } + + env = suite.make( + **config, + has_renderer=not headless, + has_offscreen_renderer=headless, + ignore_done=True, + use_camera_obs=False, + reward_shaping=True, + control_freq=20, + ) + env.reset() + low, high = env.action_spec + low = np.clip(low, -1, 1) + high = np.clip(high, -1, 1) + + # Runs a few steps of the simulation as a sanity check + for i in range(100): + start = time.time() + + action = np.random.uniform(low, high) + obs, reward, done, _ = env.step(action) + + # limit frame rate if necessary + if max_fr is not None: + elapsed = time.time() - start + diff = 1 / max_fr - elapsed + if diff > 0: + time.sleep(diff) + + env.close() + + +if __name__ == "__main__": + + parser = argparse.ArgumentParser() + + parser.add_argument("--robot", type=str, required=True) + parser.add_argument("--base", type=str, default=None) + parser.add_argument("--grippers", nargs="+", type=str, default=["PandaGripper"]) + parser.add_argument("--env", type=str, default="Lift") + parser.add_argument("--headless", action="store_true") + parser.add_argument( + "--max_fr", + default=20, + type=int, + help="Sleep when simluation runs faster than specified frame rate; 20 fps is real time.", + ) + + args = parser.parse_args() + + if args.robot not in ROBOT_CLASS_MAPPING: + raise ValueError(f"Robot {args.robot} not found in ROBOT_CLASS_MAPPING \n" f"{ROBOT_CLASS_MAPPING.keys()}") + + name = f"Custom{args.robot}" + create_composite_robot(name, base=args.base, robot=args.robot, grippers=args.grippers) + controller_config = load_composite_controller_config(controller="BASIC", robot=name) + + create_and_test_env( + env="Lift", robots=name, controller_config=controller_config, headless=args.headless, max_fr=args.max_fr + ) diff --git a/third_party/robosuite/robosuite/demos/demo_control.py b/third_party/robosuite/robosuite/demos/demo_control.py new file mode 100644 index 0000000000000000000000000000000000000000..1622b255afec188b6863f89ca04c133161acaf50 --- /dev/null +++ b/third_party/robosuite/robosuite/demos/demo_control.py @@ -0,0 +1,185 @@ +""" +This demo script demonstrates the various functionalities of each controller available within robosuite. + +For a given controller, runs through each dimension and executes a perturbation "test_value" from its +neutral (stationary) value for a certain amount of time "steps_per_action", and then returns to all neutral values +for time "steps_per_rest" before proceeding with the next action dim. + + E.g.: Given that the expected action space of the Pos / Ori (OSC_POSE) controller (without a gripper) is + (dx, dy, dz, droll, dpitch, dyaw), the testing sequence of actions over time will be: + + ***START OF DEMO*** + ( dx, 0, 0, 0, 0, 0, grip) <-- Translation in x-direction for 'steps_per_action' steps + ( 0, 0, 0, 0, 0, 0, grip) <-- No movement (pause) for 'steps_per_rest' steps + ( 0, dy, 0, 0, 0, 0, grip) <-- Translation in y-direction for 'steps_per_action' steps + ( 0, 0, 0, 0, 0, 0, grip) <-- No movement (pause) for 'steps_per_rest' steps + ( 0, 0, dz, 0, 0, 0, grip) <-- Translation in z-direction for 'steps_per_action' steps + ( 0, 0, 0, 0, 0, 0, grip) <-- No movement (pause) for 'steps_per_rest' steps + ( 0, 0, 0, dr, 0, 0, grip) <-- Rotation in roll (x) axis for 'steps_per_action' steps + ( 0, 0, 0, 0, 0, 0, grip) <-- No movement (pause) for 'steps_per_rest' steps + ( 0, 0, 0, 0, dp, 0, grip) <-- Rotation in pitch (y) axis for 'steps_per_action' steps + ( 0, 0, 0, 0, 0, 0, grip) <-- No movement (pause) for 'steps_per_rest' steps + ( 0, 0, 0, 0, 0, dy, grip) <-- Rotation in yaw (z) axis for 'steps_per_action' steps + ( 0, 0, 0, 0, 0, 0, grip) <-- No movement (pause) for 'steps_per_rest' steps + ***END OF DEMO*** + + Thus the OSC_POSE controller should be expected to sequentially move linearly in the x direction first, + then the y direction, then the z direction, and then begin sequentially rotating about its x-axis, + then y-axis, then z-axis. + +Please reference the documentation of Controllers in the Modules section for an overview of each controller. +Controllers are expected to behave in a generally controlled manner, according to their control space. The expected +sequential qualitative behavior during the test is described below for each controller: + +* OSC_POSE: Gripper moves sequentially and linearly in x, y, z direction, then sequentially rotates in x-axis, y-axis, + z-axis, relative to the global coordinate frame +* OSC_POSITION: Gripper moves sequentially and linearly in x, y, z direction, relative to the global coordinate frame +* IK_POSE: Gripper moves sequentially and linearly in x, y, z direction, then sequentially rotates in x-axis, y-axis, + z-axis, relative to the local robot end effector frame +* JOINT_POSITION: Robot Joints move sequentially in a controlled fashion +* JOINT_VELOCITY: Robot Joints move sequentially in a controlled fashion +* JOINT_TORQUE: Unlike other controllers, joint torque controller is expected to act rather lethargic, as the + "controller" is really just a wrapper for direct torque control of the mujoco actuators. Therefore, a + "neutral" value of 0 torque will not guarantee a stable robot when it has non-zero velocity! + +""" + +import time +from typing import Dict + +import robosuite as suite +from robosuite.controllers.composite.composite_controller_factory import refactor_composite_controller_config +from robosuite.utils.input_utils import * + +MAX_FR = 25 # max frame rate for running simluation + +if __name__ == "__main__": + + # Create dict to hold options that will be passed to env creation call + options = {} + + # print welcome info + print("Welcome to robosuite v{}!".format(suite.__version__)) + print(suite.__logo__) + + # Choose environment and add it to options + options["env_name"] = choose_environment() + + # If a multi-arm environment has been chosen, choose configuration and appropriate robot(s) + if "TwoArm" in options["env_name"]: + # Choose env config and add it to options + options["env_configuration"] = choose_multi_arm_config() + + # If chosen configuration was bimanual, the corresponding robot must be Baxter. Else, have user choose robots + if options["env_configuration"] == "bimanual": + options["robots"] = "Baxter" + else: + options["robots"] = [] + + # Have user choose two robots + print("A multiple single-arm configuration was chosen.\n") + + for i in range(2): + print("Please choose Robot {}...\n".format(i)) + options["robots"].append(choose_robots(exclude_bimanual=True)) + # If a humanoid environment has been chosen, choose humanoid robots + elif "Humanoid" in options["env_name"]: + options["robots"] = choose_robots(use_humanoids=True) + # Else, we simply choose a single (single-armed) robot to instantiate in the environment + else: + options["robots"] = choose_robots(exclude_bimanual=True) + + # Hacky way to grab joint dimension for now + joint_dim = 6 if options["robots"] == "UR5e" else (16 if options["robots"] == "GR1" else 7) + + # Choose controller + controller_name = choose_controller(part_controllers=True) + + # Load the desired controller + arm_controller_config = suite.load_part_controller_config(default_controller=controller_name) + robot = options["robots"][0] if isinstance(options["robots"], list) else options["robots"] + options["controller_configs"] = refactor_composite_controller_config( + arm_controller_config, robot, ["right", "left"] + ) + + # Define the pre-defined controller actions to use (action_dim, num_test_steps, test_value) + controller_settings = { + "OSC_POSE": [6, 6, 0.1], + "OSC_POSITION": [3, 3, 0.1], + "IK_POSE": [6, 6, 0.01], + "JOINT_POSITION": [joint_dim, joint_dim, 0.2], + "JOINT_VELOCITY": [joint_dim, joint_dim, -0.1], + "JOINT_TORQUE": [joint_dim, joint_dim, 0.25], + } + + # Define variables for each controller test + action_dim = controller_settings[controller_name][0] + num_test_steps = controller_settings[controller_name][1] + test_value = controller_settings[controller_name][2] + + # Define the number of timesteps to use per controller action as well as timesteps in between actions + steps_per_action = 75 + steps_per_rest = 75 + + # initialize the task + env = suite.make( + **options, + has_renderer=True, + has_offscreen_renderer=False, + ignore_done=True, + use_camera_obs=False, + horizon=(steps_per_action + steps_per_rest) * num_test_steps, + control_freq=20, + ) + env.reset() + env.viewer.set_camera(camera_id=0) + + # To accommodate for multi-arm settings (e.g.: Baxter), we need to make sure to fill any extra action space + # Get total number of arms being controlled + n = 0 + gripper_dim = 0 + for robot in env.robots: + gripper_dim = robot.gripper["right"].dof + n += int(robot.action_dim / (action_dim + gripper_dim)) + + # Define neutral value + neutral = np.zeros(action_dim + gripper_dim) + + # Keep track of done variable to know when to break loop + count = 0 + # Loop through controller space + while count < num_test_steps: + action = neutral.copy() + for i in range(steps_per_action): + start = time.time() + if controller_name in {"IK_POSE", "OSC_POSE"} and count > 2: + # Set this value to be the scaled axis angle vector + vec = np.zeros(3) + vec[count - 3] = test_value + action[3:6] = vec + else: + action[count] = test_value + total_action = np.tile(action, n) + env.step(total_action) + env.render() + + # limit frame rate if necessary + elapsed = time.time() - start + diff = 1 / MAX_FR - elapsed + if diff > 0: + time.sleep(diff) + for i in range(steps_per_rest): + start = time.time() + total_action = np.tile(neutral, n) + env.step(total_action) + env.render() + + # limit frame rate if necessary + elapsed = time.time() - start + diff = 1 / MAX_FR - elapsed + if diff > 0: + time.sleep(diff) + count += 1 + + # Shut down this env before starting the next test + env.close() diff --git a/third_party/robosuite/robosuite/demos/demo_device_control.py b/third_party/robosuite/robosuite/demos/demo_device_control.py new file mode 100644 index 0000000000000000000000000000000000000000..673b6551bd056c105fed0cd685952eed2f9a14a2 --- /dev/null +++ b/third_party/robosuite/robosuite/demos/demo_device_control.py @@ -0,0 +1,253 @@ +"""Teleoperate robot with keyboard or SpaceMouse. + +***Choose user input option with the --device argument*** + +Keyboard: + We use the keyboard to control the end-effector of the robot. + The keyboard provides 6-DoF control commands through various keys. + The commands are mapped to joint velocities through an inverse kinematics + solver from Bullet physics. + + Note: + To run this script with macOS, you must run it with root access. + +SpaceMouse: + + We use the SpaceMouse 3D mouse to control the end-effector of the robot. + The mouse provides 6-DoF control commands. The commands are mapped to joint + velocities through an inverse kinematics solver from Bullet physics. + + The two side buttons of SpaceMouse are used for controlling the grippers. + + SpaceMouse Wireless from 3Dconnexion: https://www.3dconnexion.com/spacemouse_wireless/en/ + We used the SpaceMouse Wireless in our experiments. The paper below used the same device + to collect human demonstrations for imitation learning. + + Reinforcement and Imitation Learning for Diverse Visuomotor Skills + Yuke Zhu, Ziyu Wang, Josh Merel, Andrei Rusu, Tom Erez, Serkan Cabi, Saran Tunyasuvunakool, + János Kramár, Raia Hadsell, Nando de Freitas, Nicolas Heess + RSS 2018 + + Note: + This current implementation only supports macOS (Linux support can be added). + Download and install the driver before running the script: + https://www.3dconnexion.com/service/drivers.html + +Additionally, --pos_sensitivity and --rot_sensitivity provide relative gains for increasing / decreasing the user input +device sensitivity + + +***Choose controller with the --controller argument*** + +Choice of using either inverse kinematics controller (ik) or operational space controller (osc): +Main difference is that user inputs with ik's rotations are always taken relative to eef coordinate frame, whereas + user inputs with osc's rotations are taken relative to global frame (i.e.: static / camera frame of reference). + + +***Choose environment specifics with the following arguments*** + + --environment: Task to perform, e.g.: "Lift", "TwoArmPegInHole", "NutAssembly", etc. + + --robots: Robot(s) with which to perform the task. Can be any in + {"Panda", "Sawyer", "IIWA", "Jaco", "Kinova3", "UR5e", "Baxter"}. Note that the environments include sanity + checks, such that a "TwoArm..." environment will only accept either a 2-tuple of robot names or a single + bimanual robot name, according to the specified configuration (see below), and all other environments will + only accept a single single-armed robot name + + --config: Exclusively applicable and only should be specified for "TwoArm..." environments. Specifies the robot + configuration desired for the task. Options are {"parallel" and "opposed"} + + -"parallel": Sets up the environment such that two robots are stationed next to + each other facing the same direction. Expects a 2-tuple of robot names to be specified + in the --robots argument. + + -"opposed": Sets up the environment such that two robots are stationed opposed from + each other, facing each other from opposite directions. Expects a 2-tuple of robot names + to be specified in the --robots argument. + + --arm: Exclusively applicable and only should be specified for "TwoArm..." environments. Specifies which of the + multiple arm eef's to control. The other (passive) arm will remain stationary. Options are {"right", "left"} + (from the point of view of the robot(s) facing against the viewer direction) + + --switch-on-grasp: Exclusively applicable and only should be specified for "TwoArm..." environments. If enabled, + will switch the current arm being controlled every time the gripper input is pressed + + --toggle-camera-on-grasp: If enabled, gripper input presses will cycle through the available camera angles + +Examples: + + For normal single-arm environment: + $ python demo_device_control.py --environment PickPlaceCan --robots Sawyer --controller osc + + For two-arm bimanual environment: + $ python demo_device_control.py --environment TwoArmLift --robots Baxter --config bimanual --arm left --controller osc + + For two-arm multi single-arm robot environment: + $ python demo_device_control.py --environment TwoArmLift --robots Sawyer Sawyer --config parallel --controller osc + + +""" + +import argparse +import time + +import numpy as np + +import robosuite as suite +from robosuite import load_composite_controller_config +from robosuite.controllers.composite.composite_controller import WholeBody +from robosuite.wrappers import VisualizationWrapper + +if __name__ == "__main__": + + parser = argparse.ArgumentParser() + parser.add_argument("--environment", type=str, default="Lift") + parser.add_argument("--robots", nargs="+", type=str, default="Panda", help="Which robot(s) to use in the env") + parser.add_argument( + "--config", type=str, default="default", help="Specified environment configuration if necessary" + ) + parser.add_argument("--arm", type=str, default="right", help="Which arm to control (eg bimanual) 'right' or 'left'") + parser.add_argument("--switch-on-grasp", action="store_true", help="Switch gripper control on gripper action") + parser.add_argument("--toggle-camera-on-grasp", action="store_true", help="Switch camera angle on gripper action") + parser.add_argument( + "--controller", + type=str, + default=None, + help="Choice of controller. Can be generic (eg. 'BASIC' or 'WHOLE_BODY_MINK_IK') or json file (see robosuite/controllers/config for examples) or None to get the robot's default controller if it exists", + ) + parser.add_argument("--device", type=str, default="keyboard") + parser.add_argument("--pos-sensitivity", type=float, default=1.0, help="How much to scale position user inputs") + parser.add_argument("--rot-sensitivity", type=float, default=1.0, help="How much to scale rotation user inputs") + parser.add_argument( + "--max_fr", + default=20, + type=int, + help="Sleep when simluation runs faster than specified frame rate; 20 fps is real time.", + ) + args = parser.parse_args() + + # Get controller config + controller_config = load_composite_controller_config( + controller=args.controller, + robot=args.robots[0], + ) + + # Create argument configuration + config = { + "env_name": args.environment, + "robots": args.robots, + "controller_configs": controller_config, + } + + # Check if we're using a multi-armed environment and use env_configuration argument if so + if "TwoArm" in args.environment: + config["env_configuration"] = args.config + else: + args.config = None + + # Create environment + env = suite.make( + **config, + has_renderer=True, + has_offscreen_renderer=False, + render_camera="agentview", + ignore_done=True, + use_camera_obs=False, + reward_shaping=True, + control_freq=20, + hard_reset=False, + ) + + # Wrap this environment in a visualization wrapper + env = VisualizationWrapper(env, indicator_configs=None) + + # Setup printing options for numbers + np.set_printoptions(formatter={"float": lambda x: "{0:0.3f}".format(x)}) + + # initialize device + if args.device == "keyboard": + from robosuite.devices import Keyboard + + device = Keyboard(env=env, pos_sensitivity=args.pos_sensitivity, rot_sensitivity=args.rot_sensitivity) + env.viewer.add_keypress_callback(device.on_press) + elif args.device == "spacemouse": + from robosuite.devices import SpaceMouse + + device = SpaceMouse(env=env, pos_sensitivity=args.pos_sensitivity, rot_sensitivity=args.rot_sensitivity) + elif args.device == "mjgui": + from robosuite.devices.mjgui import MJGUI + + device = MJGUI(env=env) + else: + raise Exception("Invalid device choice: choose either 'keyboard' or 'spacemouse'.") + + while True: + # Reset the environment + obs = env.reset() + + # Setup rendering + cam_id = 0 + num_cam = len(env.sim.model.camera_names) + env.render() + + # Initialize variables that should the maintained between resets + last_grasp = 0 + + # Initialize device control + device.start_control() + all_prev_gripper_actions = [ + { + f"{robot_arm}_gripper": np.repeat([0], robot.gripper[robot_arm].dof) + for robot_arm in robot.arms + if robot.gripper[robot_arm].dof > 0 + } + for robot in env.robots + ] + + # Loop until we get a reset from the input or the task completes + while True: + start = time.time() + + # Set active robot + active_robot = env.robots[device.active_robot] + + # Get the newest action + input_ac_dict = device.input2action() + + # If action is none, then this a reset so we should break + if input_ac_dict is None: + break + + from copy import deepcopy + + action_dict = deepcopy(input_ac_dict) # {} + # set arm actions + for arm in active_robot.arms: + if isinstance(active_robot.composite_controller, WholeBody): # input type passed to joint_action_policy + controller_input_type = active_robot.composite_controller.joint_action_policy.input_type + else: + controller_input_type = active_robot.part_controllers[arm].input_type + + if controller_input_type == "delta": + action_dict[arm] = input_ac_dict[f"{arm}_delta"] + elif controller_input_type == "absolute": + action_dict[arm] = input_ac_dict[f"{arm}_abs"] + else: + raise ValueError + + # Maintain gripper state for each robot but only update the active robot with action + env_action = [robot.create_action_vector(all_prev_gripper_actions[i]) for i, robot in enumerate(env.robots)] + env_action[device.active_robot] = active_robot.create_action_vector(action_dict) + env_action = np.concatenate(env_action) + for gripper_ac in all_prev_gripper_actions[device.active_robot]: + all_prev_gripper_actions[device.active_robot][gripper_ac] = action_dict[gripper_ac] + + env.step(env_action) + env.render() + + # limit frame rate if necessary + if args.max_fr is not None: + elapsed = time.time() - start + diff = 1 / args.max_fr - elapsed + if diff > 0: + time.sleep(diff) diff --git a/third_party/robosuite/robosuite/demos/demo_domain_randomization.py b/third_party/robosuite/robosuite/demos/demo_domain_randomization.py new file mode 100644 index 0000000000000000000000000000000000000000..3f25dfd4a3e678a8c1a979da78e6282ab904967e --- /dev/null +++ b/third_party/robosuite/robosuite/demos/demo_domain_randomization.py @@ -0,0 +1,78 @@ +""" +Script to showcase domain randomization functionality. +""" + +import time + +import robosuite.macros as macros +from robosuite.utils.input_utils import * +from robosuite.wrappers import DomainRandomizationWrapper + +# We'll use instance randomization so that entire geom groups are randomized together +macros.USING_INSTANCE_RANDOMIZATION = True + +if __name__ == "__main__": + # Create dict to hold options that will be passed to env creation call + options = {} + + # print welcome info + print("Welcome to robosuite v{}!".format(suite.__version__)) + print(suite.__logo__) + + # Choose environment and add it to options + options["env_name"] = choose_environment() + + # If a multi-arm environment has been chosen, choose configuration and appropriate robot(s) + if "TwoArm" in options["env_name"]: + # Choose env config and add it to options + options["env_configuration"] = choose_multi_arm_config() + + # If chosen configuration was bimanual, the corresponding robot must be Baxter. Else, have user choose robots + if options["env_configuration"] == "bimanual": + options["robots"] = "Baxter" + else: + options["robots"] = [] + + # Have user choose two robots + print("A multiple single-arm configuration was chosen.\n") + + for i in range(2): + print("Please choose Robot {}...\n".format(i)) + options["robots"].append(choose_robots(exclude_bimanual=True)) + # If a humanoid environment has been chosen, choose humanoid robots + elif "Humanoid" in options["env_name"]: + options["robots"] = choose_robots(use_humanoids=True) + # Else, we simply choose a single (single-armed) robot to instantiate in the environment + else: + options["robots"] = choose_robots(exclude_bimanual=True) + + # initialize the task + env = suite.make( + **options, + has_renderer=True, + has_offscreen_renderer=False, + ignore_done=True, + use_camera_obs=False, + control_freq=20, + hard_reset=False, # TODO: Not setting this flag to False brings up a segfault on macos or glfw error on linux + ) + env = DomainRandomizationWrapper( + env, + randomize_color=False, # randomize_color currently only works for mujoco==3.1.1 + randomize_camera=False, # less jarring when visualizing + randomize_dynamics=False, + ) + env.reset() + env.viewer.set_camera(camera_id=0) + + max_frame_rate = 20 # Set the desired maximum frame rate + + # Get action limits + low, high = env.action_spec + + # do visualization + for i in range(100): + action = np.random.uniform(low, high) + obs, reward, done, _ = env.step(action) + env.render() + time.sleep(1 / max_frame_rate) diff --git a/third_party/robosuite/robosuite/demos/demo_gripper_interaction.py b/third_party/robosuite/robosuite/demos/demo_gripper_interaction.py new file mode 100644 index 0000000000000000000000000000000000000000..a677725f19e9c5b5c06911f6855c8d2515bee645 --- /dev/null +++ b/third_party/robosuite/robosuite/demos/demo_gripper_interaction.py @@ -0,0 +1,133 @@ +"""Gripper interaction demo. + +This script illustrates the process of importing grippers into a scene and making it interact +with the objects with actuators. It also shows how to procedurally generate a scene with the +APIs of the MJCF utility functions. + +Example: + $ python run_gripper_test.py +""" + +import xml.etree.ElementTree as ET + +from robosuite.models import MujocoWorldBase +from robosuite.models.arenas.table_arena import TableArena +from robosuite.models.grippers import PandaGripper, RethinkGripper +from robosuite.models.objects import BoxObject +from robosuite.utils import OpenCVRenderer +from robosuite.utils.binding_utils import MjRenderContextOffscreen, MjSim +from robosuite.utils.mjcf_utils import new_actuator, new_joint + +if __name__ == "__main__": + + # start with an empty world + world = MujocoWorldBase() + + # add a table + arena = TableArena(table_full_size=(0.4, 0.4, 0.05), table_offset=(0, 0, 1.1), has_legs=False) + world.merge(arena) + + # add a gripper + gripper = RethinkGripper() + # Create another body with a slider joint to which we'll add this gripper + gripper_body = ET.Element("body", name="gripper_base") + gripper_body.set("pos", "0 0 1.3") + gripper_body.set("quat", "0 0 1 0") # flip z + gripper_body.append(new_joint(name="gripper_z_joint", type="slide", axis="0 0 1", damping="50")) + # Add the dummy body with the joint to the global worldbody + world.worldbody.append(gripper_body) + # Merge the actual gripper as a child of the dummy body + world.merge(gripper, merge_body="gripper_base") + # Create a new actuator to control our slider joint + world.actuator.append(new_actuator(joint="gripper_z_joint", act_type="position", name="gripper_z", kp="500")) + + # add an object for grasping + mujoco_object = BoxObject( + name="box", size=[0.02, 0.02, 0.02], rgba=[1, 0, 0, 1], friction=[1, 0.005, 0.0001] + ).get_obj() + # Set the position of this object + mujoco_object.set("pos", "0 0 1.11") + # Add our object to the world body + world.worldbody.append(mujoco_object) + + # add reference objects for x and y axes + x_ref = BoxObject( + name="x_ref", size=[0.01, 0.01, 0.01], rgba=[0, 1, 0, 1], obj_type="visual", joints=None + ).get_obj() + x_ref.set("pos", "0.2 0 1.105") + world.worldbody.append(x_ref) + y_ref = BoxObject( + name="y_ref", size=[0.01, 0.01, 0.01], rgba=[0, 0, 1, 1], obj_type="visual", joints=None + ).get_obj() + y_ref.set("pos", "0 0.2 1.105") + world.worldbody.append(y_ref) + + # start simulation + model = world.get_model(mode="mujoco") + + sim = MjSim(model) + viewer = OpenCVRenderer(sim) + render_context = MjRenderContextOffscreen(sim, device_id=-1) + sim.add_render_context(render_context) + + sim_state = sim.get_state() + + # for gravity correction + gravity_corrected = ["gripper_z_joint"] + _ref_joint_vel_indexes = [sim.model.get_joint_qvel_addr(x) for x in gravity_corrected] + + # Set gripper parameters + gripper_z_id = sim.model.actuator_name2id("gripper_z") + gripper_z_low = 0.07 + gripper_z_high = -0.02 + gripper_z_is_low = False + + gripper_jaw_ids = [sim.model.actuator_name2id(x) for x in gripper.actuators] + gripper_open = [-0.0115, 0.0115] + gripper_closed = [0.020833, -0.020833] + gripper_is_closed = True + + # hardcode sequence for gripper looping trajectory + seq = [(False, False), (True, False), (True, True), (False, True)] + + sim.set_state(sim_state) + step = 0 + T = 500 + while True: + if step % 100 == 0: + print("step: {}".format(step)) + + # Get contact information + for contact in sim.data.contact[0 : sim.data.ncon]: + + geom_name1 = sim.model.geom_id2name(contact.geom1) + geom_name2 = sim.model.geom_id2name(contact.geom2) + if geom_name1 == "floor" and geom_name2 == "floor": + continue + + print("geom1: {}, geom2: {}".format(geom_name1, geom_name2)) + print("contact id {}".format(id(contact))) + print("friction: {}".format(contact.friction)) + print("normal: {}".format(contact.frame[0:3])) + + # Iterate through gripping trajectory + if step % T == 0: + plan = seq[int(step / T) % len(seq)] + gripper_z_is_low, gripper_is_closed = plan + print("changing plan: gripper low: {}, gripper closed {}".format(gripper_z_is_low, gripper_is_closed)) + + # Control gripper + if gripper_z_is_low: + sim.data.ctrl[gripper_z_id] = gripper_z_low + else: + sim.data.ctrl[gripper_z_id] = gripper_z_high + if gripper_is_closed: + sim.data.ctrl[gripper_jaw_ids] = gripper_closed + else: + sim.data.ctrl[gripper_jaw_ids] = gripper_open + + # Step through sim + sim.step() + sim.data.qfrc_applied[_ref_joint_vel_indexes] = sim.data.qfrc_bias[_ref_joint_vel_indexes] + viewer.render() + step += 1 diff --git a/third_party/robosuite/robosuite/demos/demo_gripper_selection.py b/third_party/robosuite/robosuite/demos/demo_gripper_selection.py new file mode 100644 index 0000000000000000000000000000000000000000..1da85c9dddfef86ec5e6dd64b143f736b676e9dc --- /dev/null +++ b/third_party/robosuite/robosuite/demos/demo_gripper_selection.py @@ -0,0 +1,56 @@ +""" +This script shows you how to select gripper for an environment. +This is controlled by gripper_type keyword argument. +""" +import time + +import numpy as np + +import robosuite as suite +from robosuite import ALL_GRIPPERS + +MAX_FR = 25 # max frame rate for running simluation + +if __name__ == "__main__": + + for gripper in ALL_GRIPPERS: + + # Notify user which gripper we're currently using + print("Using gripper {}...".format(gripper)) + + # create environment with selected grippers + env = suite.make( + "Lift", + robots="Panda", + gripper_types=gripper, + has_renderer=True, # make sure we can render to the screen + has_offscreen_renderer=False, # not needed since not using pixel obs + use_camera_obs=False, # do not use pixel observations + control_freq=50, # control should happen fast enough so that simulation looks smoother + camera_names="frontview", + ) + + # Reset the env + env.reset() + + # Get action limits + low, high = env.action_spec + + # Run random policy + for t in range(100): + start = time.time() + env.render() + action = np.random.uniform(low, high) + observation, reward, done, info = env.step(action) + if done: + print("Episode finished after {} timesteps".format(t + 1)) + break + + # limit frame rate if necessary + elapsed = time.time() - start + diff = 1 / MAX_FR - elapsed + if diff > 0: + time.sleep(diff) + + # close window + env.close() diff --git a/third_party/robosuite/robosuite/demos/demo_gym_functionality.py b/third_party/robosuite/robosuite/demos/demo_gym_functionality.py new file mode 100644 index 0000000000000000000000000000000000000000..21ca813ec09e6da0bba22827f386c9d206316c57 --- /dev/null +++ b/third_party/robosuite/robosuite/demos/demo_gym_functionality.py @@ -0,0 +1,61 @@ +""" +This script shows how to adapt an environment to be compatible +with the Gymnasium API. This is useful when using +learning pipelines that require supporting these APIs. + +For instance, this can be used with OpenAI Baselines +(https://github.com/openai/baselines) to train agents +with RL. + + +We base this script off of some code snippets found +in the "Basic Usage" section of the Gymnasium documentation + +The following snippet was used to demo basic functionality. + + import gymnasium as gym + env = gym.make("LunarLander-v2", render_mode="human") + observation, info = env.reset() + + for _ in range(1000): + action = env.action_space.sample() # agent policy that uses the observation and info + observation, reward, terminated, truncated, info = env.step(action) + if terminated or truncated: + observation, info = env.reset() + env.close() + +To adapt our APIs to be compatible with OpenAI Gym's style, this script +demonstrates how this can be easily achieved by using the GymWrapper. +""" + +import robosuite as suite +from robosuite.wrappers import GymWrapper + +if __name__ == "__main__": + + # Notice how the environment is wrapped by the wrapper + env = GymWrapper( + suite.make( + "Lift", + robots="Sawyer", # use Sawyer robot + use_camera_obs=False, # do not use pixel observations + has_offscreen_renderer=False, # not needed since not using pixel obs + has_renderer=True, # make sure we can render to the screen + reward_shaping=True, # use dense rewards + control_freq=20, # control should happen fast enough so that simulation looks smooth + ) + ) + + env.reset(seed=0) + + for i_episode in range(20): + observation = env.reset() + for t in range(500): + env.render() + action = env.action_space.sample() + observation, reward, terminated, truncated, info = env.step(action) + if terminated or truncated: + print("Episode finished after {} timesteps".format(t + 1)) + observation, info = env.reset() + break + env.close() diff --git a/third_party/robosuite/robosuite/demos/demo_random_action.py b/third_party/robosuite/robosuite/demos/demo_random_action.py new file mode 100644 index 0000000000000000000000000000000000000000..b8694fae3ab76ae05d2adea81391a859be0392e1 --- /dev/null +++ b/third_party/robosuite/robosuite/demos/demo_random_action.py @@ -0,0 +1,67 @@ +import time + +from robosuite.robots import MobileRobot +from robosuite.utils.input_utils import * + +MAX_FR = 25 # max frame rate for running simluation + +if __name__ == "__main__": + + # Create dict to hold options that will be passed to env creation call + options = {} + + # print welcome info + print("Welcome to robosuite v{}!".format(suite.__version__)) + print(suite.__logo__) + + # Choose environment and add it to options + options["env_name"] = choose_environment() + + # If a multi-arm environment has been chosen, choose configuration and appropriate robot(s) + if "TwoArm" in options["env_name"]: + # Choose env config and add it to options + options["env_configuration"] = choose_multi_arm_config() + + # If chosen configuration was bimanual, the corresponding robot must be Baxter. Else, have user choose robots + if options["env_configuration"] == "single-robot": + options["robots"] = choose_robots(exclude_bimanual=False, use_humanoids=True, exclude_single_arm=True) + else: + options["robots"] = [] + + # Have user choose two robots + for i in range(2): + print("Please choose Robot {}...\n".format(i)) + options["robots"].append(choose_robots(exclude_bimanual=False, use_humanoids=True)) + # If a humanoid environment has been chosen, choose humanoid robots + elif "Humanoid" in options["env_name"]: + options["robots"] = choose_robots(use_humanoids=True) + else: + options["robots"] = choose_robots(exclude_bimanual=False, use_humanoids=True) + + # initialize the task + env = suite.make( + **options, + has_renderer=True, + has_offscreen_renderer=False, + ignore_done=True, + use_camera_obs=False, + control_freq=20, + ) + env.reset() + env.viewer.set_camera(camera_id=0) + for robot in env.robots: + if isinstance(robot, MobileRobot): + robot.enable_parts(legs=False, base=False) + + # do visualization + for i in range(10000): + start = time.time() + action = np.random.randn(*env.action_spec[0].shape) + obs, reward, done, _ = env.step(action) + env.render() + + # limit frame rate if necessary + elapsed = time.time() - start + diff = 1 / MAX_FR - elapsed + if diff > 0: + time.sleep(diff) diff --git a/third_party/robosuite/robosuite/demos/demo_renderers.py b/third_party/robosuite/robosuite/demos/demo_renderers.py new file mode 100644 index 0000000000000000000000000000000000000000..f521239e4dd9f3e5594e9e1e4a3871a48c1414c3 --- /dev/null +++ b/third_party/robosuite/robosuite/demos/demo_renderers.py @@ -0,0 +1,123 @@ +import argparse +import time + +import numpy as np + +import robosuite as suite +from robosuite.controllers.composite.composite_controller_factory import load_composite_controller_config +from robosuite.utils.input_utils import choose_environment, choose_multi_arm_config, choose_robots + +MAX_FR = 25 # max frame rate for running simluation + + +def str2bool(v): + if v.lower() in ("yes", "true", "t", "y", "1"): + return True + elif v.lower() in ("no", "false", "f", "n", "0"): + return False + else: + raise argparse.ArgumentTypeError("Boolean value expected.") + + +def display_mjv_options(): + def print_command(char, info): + char += " " * (30 - len(char)) + print("{}\t{}".format(char, info)) + + print("") + print("Quick list of some of the interactive keyboard options:") + print("") + print_command("Keyboard Input", "Functionality") + print_command("Esc", "switch to free camera") + print_command("]", "toggle between camera views") + print_command("Shift + Tab", "visualize joints and control values") + print_command("W", "visualize wireframe") + print_command("C", "visualize contact points") + print_command("F1", "basic GUI help") + print_command("Tab", "view more toggleable options") + print_command("Tab + Right Hold", "view keyboard shortcuts for more toggleable options") + print("") + print("") + + +if __name__ == "__main__": + + """ + Registered environments: Lift, Stack, NutAssembly, NutAssemblySingle, NutAssemblySquare, NutAssemblyRound, + PickPlace, PickPlaceSingle, PickPlaceMilk, PickPlaceBread, PickPlaceCereal, + PickPlaceCan, Door, Wipe, TwoArmLift, TwoArmPegInHole, TwoArmHandover + + Possible robots: Baxter, IIWA, Jaco, Kinova3, Panda, Sawyer, UR5e + """ + + options = {} + + # print welcome info + print("Welcome to robosuite v{}!".format(suite.__version__)) + print(suite.__logo__) + + parser = argparse.ArgumentParser() + parser.add_argument("--renderer", type=str, default="mjviewer", help="Valid options include mujoco, and nvisii") + + args = parser.parse_args() + renderer = args.renderer + + options["env_name"] = choose_environment() + + # If a multi-arm environment has been chosen, choose configuration and appropriate robot(s) + if "TwoArm" in options["env_name"]: + # Choose env config and add it to options + options["env_configuration"] = choose_multi_arm_config() + + # If chosen configuration was bimanual, the corresponding robot must be Baxter. Else, have user choose robots + if options["env_configuration"] == "bimanual": + options["robots"] = "Baxter" + else: + options["robots"] = [] + + # Have user choose two robots + print("A multiple single-arm configuration was chosen.\n") + + for i in range(2): + print("Please choose Robot {}...\n".format(i)) + options["robots"].append(choose_robots(exclude_bimanual=True)) + # If a humanoid environment has been chosen, choose humanoid robots + elif "Humanoid" in options["env_name"]: + options["robots"] = choose_robots(use_humanoids=True) + # Else, we simply choose a single (single-armed) robot to instantiate in the environment + else: + options["robots"] = choose_robots(exclude_bimanual=True) + + controller_config = load_composite_controller_config(robot=options["robots"]) + options["controller_configs"] = controller_config + + env = suite.make( + **options, + has_renderer=True, # no on-screen renderer + has_offscreen_renderer=False, # no off-screen renderer + ignore_done=True, + use_camera_obs=False, # no camera observations + control_freq=20, + renderer=renderer, + ) + + env.reset() + + low, high = env.action_spec + + # do visualization + for i in range(10000): + start = time.time() + + action = np.random.uniform(low, high) + obs, reward, done, _ = env.step(action) + env.render() + + # limit frame rate if necessary + elapsed = time.time() - start + diff = 1 / MAX_FR - elapsed + if diff > 0: + time.sleep(diff) + + env.close_renderer() + print("Done.") diff --git a/third_party/robosuite/robosuite/demos/demo_segmentation.py b/third_party/robosuite/robosuite/demos/demo_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..bb53b72d345d13e6a2a4a1f1b90f423b6224e051 --- /dev/null +++ b/third_party/robosuite/robosuite/demos/demo_segmentation.py @@ -0,0 +1,112 @@ +""" +Play random actions in an environment and render a video that demonstrates segmentation. +""" +import argparse +import colorsys +import json +import random + +import imageio +import matplotlib.cm as cm +import numpy as np +from PIL import Image + +import robosuite as suite + + +def randomize_colors(N, bright=True): + """ + Modified from https://github.com/matterport/Mask_RCNN/blob/master/mrcnn/visualize.py#L59 + Generate random colors. + To get visually distinct colors, generate them in HSV space then + convert to RGB. + """ + brightness = 1.0 if bright else 0.5 + hsv = [(1.0 * i / N, 1, brightness) for i in range(N)] + colors = np.array(list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))) + rstate = np.random.RandomState(seed=20) + np.random.shuffle(colors) + return colors + + +def segmentation_to_rgb(seg_im, random_colors=False): + """ + Helper function to visualize segmentations as RGB frames. + NOTE: assumes that geom IDs go up to 255 at most - if not, + multiple geoms might be assigned to the same color. + """ + # ensure all values lie within [0, 255] + seg_im = np.mod(seg_im, 256) + + if random_colors: + colors = randomize_colors(N=256, bright=True) + return (255.0 * colors[seg_im]).astype(np.uint8) + else: + # deterministic shuffling of values to map each geom ID to a random int in [0, 255] + rstate = np.random.RandomState(seed=8) + inds = np.arange(256) + rstate.shuffle(inds) + + # use @inds to map each geom ID to a color + return (255.0 * cm.rainbow(inds[seg_im], 3)).astype(np.uint8)[..., :3] + + +if __name__ == "__main__": + + parser = argparse.ArgumentParser() + parser.add_argument("--video-path", type=str, default="/tmp/video.mp4", help="Path to video file") + parser.add_argument("--random-colors", action="store_true", help="Radnomize segmentation colors") + parser.add_argument("--segmentation-level", type=str, default="element", help="instance, class, or element") + args = parser.parse_args() + + # Create dict to hold options that will be passed to env creation call + options = {} + + # Choose environment and add it to options + options["env_name"] = "TwoArmHandover" + options["robots"] = ["Panda", "Panda"] + + # Choose camera + camera = "frontview" + + # Choose segmentation type + segmentation_level = args.segmentation_level # Options are {instance, class, element} + + # initialize the task + env = suite.make( + **options, + has_renderer=False, + has_offscreen_renderer=True, + ignore_done=True, + use_camera_obs=True, + control_freq=20, + camera_names=camera, + camera_segmentations=segmentation_level, + camera_heights=512, + camera_widths=512, + renderer="mujoco", # for segmentation + ) + env.reset() + + video_writer = imageio.get_writer(args.video_path, fps=20) + + # Get action limits + low, high = env.action_spec + + # do visualization + for i in range(100): + action = 0.5 * np.random.uniform(low, high) + obs, reward, done, _ = env.step(action) + + video_img = obs[f"{camera}_segmentation_{segmentation_level}"].squeeze(-1)[::-1] + np.savetxt("/tmp/seg_{}.txt".format(i), video_img, fmt="%.2f") + video_img = segmentation_to_rgb(video_img, args.random_colors) + video_writer.append_data(video_img) + + image = Image.fromarray(video_img) + image.save("/tmp/seg_{}.png".format(i)) + if i % 5 == 0: + print("Step #{} / 100".format(i)) + + video_writer.close() + print("Video saved to {}".format(args.video_path)) diff --git a/third_party/robosuite/robosuite/demos/demo_sensor_corruption.py b/third_party/robosuite/robosuite/demos/demo_sensor_corruption.py new file mode 100644 index 0000000000000000000000000000000000000000..5f62d84bafd21200194e45b512b9a78a0c75f2f2 --- /dev/null +++ b/third_party/robosuite/robosuite/demos/demo_sensor_corruption.py @@ -0,0 +1,245 @@ +"""Sensor Corruption Demo. + +This script provides an example of using the Observables functionality to implement a corrupted sensor +(corruption + delay). +Images will be rendered in a delayed fashion, such that the user will have seemingly delayed actions + +This is a modified version of the demo_device_control teleoperation script. + +Example: + $ python demo_sensor_corruption.py --environment Stack --robots Panda --delay 0.05 --corruption 5.0 --toggle-corruption-on-grasp +""" + +import argparse +import sys +from copy import deepcopy + +import cv2 +import numpy as np + +import robosuite as suite +from robosuite.controllers.composite.composite_controller import WholeBody +from robosuite.utils.observables import Observable, create_gaussian_noise_corrupter, create_uniform_sampled_delayer +from robosuite.wrappers import VisualizationWrapper + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--environment", type=str, default="Lift") + parser.add_argument("--robots", nargs="+", type=str, default="Panda", help="Which robot(s) to use in the env") + parser.add_argument( + "--config", type=str, default="default", help="Specified environment configuration if necessary" + ) + parser.add_argument("--arm", type=str, default="right", help="Which arm to control (eg bimanual) 'right' or 'left'") + parser.add_argument("--switch-on-grasp", action="store_true", help="Switch gripper control on gripper action") + parser.add_argument( + "--toggle-corruption-on-grasp", action="store_true", help="Toggle corruption ON / OFF on gripper action" + ) + parser.add_argument("--device", type=str, default="keyboard") + parser.add_argument("--pos-sensitivity", type=float, default=1.0, help="How much to scale position user inputs") + parser.add_argument("--rot-sensitivity", type=float, default=1.0, help="How much to scale rotation user inputs") + parser.add_argument("--delay", type=float, default=0.04, help="average delay to use (sec)") + parser.add_argument("--corruption", type=float, default=20.0, help="Scale of corruption to use (std dev)") + parser.add_argument("--camera", type=str, default="agentview", help="Name of camera to render") + parser.add_argument("--width", type=int, default=512) + parser.add_argument("--height", type=int, default=384) + args = parser.parse_args() + + # Create argument configuration + config = { + "env_name": args.environment, + "robots": args.robots, + } + + # Check if we're using a multi-armed environment and use env_configuration argument if so + if "TwoArm" in args.environment: + config["env_configuration"] = args.config + else: + args.config = None + + # Create environment + env = suite.make( + **config, + has_renderer=False, + has_offscreen_renderer=True, + ignore_done=True, + camera_names=args.camera, + camera_heights=args.height, + camera_widths=args.width, + use_camera_obs=True, + use_object_obs=True, + hard_reset=False, + ) + + # Wrap this environment in a visualization wrapper + env = VisualizationWrapper(env, indicator_configs=None) + + # Set shared settings + attributes = ["corrupter", "delayer", "sampling_rate"] + corruption_mode = 1 # 1 is corruption = ON, 0 is corruption = OFF + obs_settings = {} + + # Function to easily modify observable on the fly + def modify_obs(obs_name, attrs, mods): + for attr, mod in zip(attrs, mods): + env.modify_observable( + observable_name=obs_name, + attribute=attr, + modifier=mod, + ) + + # Add image corruption and delay + image_sampling_rate = 10.0 + image_obs_name = f"{args.camera}_image" + image_corrupter = create_gaussian_noise_corrupter(mean=0.0, std=args.corruption, low=0, high=255) + image_delayer = create_uniform_sampled_delayer(min_delay=max(0, args.delay - 0.025), max_delay=args.delay + 0.025) + image_modifiers = [image_corrupter, image_delayer, image_sampling_rate] + + # Initialize settings + modify_obs(obs_name=image_obs_name, attrs=attributes, mods=image_modifiers) + + # Add entry for the corruption / delay settings in dict + obs_settings[image_obs_name] = { + "attrs": attributes[:2], + "mods": lambda: image_modifiers[:2] if corruption_mode else [None, None], + } + + # Add proprioception corruption and delay + proprio_sampling_rate = 20.0 + proprio_obs_name = f"{env.robots[0].robot_model.naming_prefix}joint_pos" + joint_limits = env.sim.model.jnt_range[env.robots[0]._ref_joint_indexes] + joint_range = joint_limits[:, 1] - joint_limits[:, 0] + proprio_corrupter = create_gaussian_noise_corrupter(mean=0.0, std=joint_range / 50.0) + curr_proprio_delay = 0.0 + tmp_delayer = create_uniform_sampled_delayer( + min_delay=max(0, (args.delay - 0.025) / 2), max_delay=(args.delay + 0.025) / 2 + ) + + # Define delayer to synchronize delay between ground truth and corrupted sensors + def proprio_delayer(): + global curr_proprio_delay + curr_proprio_delay = tmp_delayer() + return curr_proprio_delay + + # Define function to convert raw delay time to actual sampling delay (in discrete timesteps) + def calculate_proprio_delay(): + base = env.model_timestep + return base * round(curr_proprio_delay / base) if corruption_mode else 0.0 + + proprio_modifiers = [proprio_corrupter, proprio_delayer, proprio_sampling_rate] + + # We will create a separate "ground truth" delayed proprio observable to track exactly + # how much corruption we're getting in real time + proprio_sensor = env._observables[proprio_obs_name]._sensor + proprio_ground_truth_obs_name = f"{proprio_obs_name}_ground_truth" + observable = Observable( + name=proprio_ground_truth_obs_name, + sensor=proprio_sensor, + delayer=lambda: curr_proprio_delay, + sampling_rate=proprio_sampling_rate, + ) + + # Add this observable + env.add_observable(observable) + + # We also need to set the normal joint pos observable to be active (not active by default) + env.modify_observable(observable_name=proprio_obs_name, attribute="active", modifier=True) + + # Initialize settings + modify_obs(obs_name=proprio_obs_name, attrs=attributes, mods=proprio_modifiers) + + # Add entry for the corruption / delay settings in dict + obs_settings[proprio_obs_name] = { + "attrs": attributes[:2], + "mods": lambda: proprio_modifiers[:2] if corruption_mode else [None, None], + } + obs_settings[proprio_ground_truth_obs_name] = { + "attrs": [attributes[1]], + "mods": lambda: [lambda: curr_proprio_delay] if corruption_mode else [None], + } + + # Setup printing options for numbers + np.set_printoptions(precision=3, suppress=True, floatmode="fixed") + + # initialize device + if args.device == "keyboard": + from robosuite.devices import Keyboard + + device = Keyboard(env=env, pos_sensitivity=args.pos_sensitivity, rot_sensitivity=args.rot_sensitivity) + elif args.device == "spacemouse": + from robosuite.devices import SpaceMouse + + device = SpaceMouse(env=env, pos_sensitivity=args.pos_sensitivity, rot_sensitivity=args.rot_sensitivity) + else: + raise Exception("Invalid device choice: choose either 'keyboard' or 'spacemouse'.") + + while True: + # Reset the environment + obs = env.reset() + + # Reset corruption mode + corruption_mode = 1 + + # Initialize variables that should the maintained between resets + last_grasp = 0 + + # Initialize device control + device.start_control() + + # Keep track of prev gripper actions when using since they are position-based and must be maintained when arms switched + all_prev_gripper_actions = [ + { + f"{robot_arm}_gripper": np.repeat([0], robot.gripper[robot_arm].dof) + for robot_arm in robot.arms + if robot.gripper[robot_arm].dof > 0 + } + for robot in env.robots + ] + + while True: + # Set active robot + active_robot = env.robots[device.active_robot] + + # Get the newest action + input_ac_dict = device.input2action() + + # If action is none, then this a reset so we should break + if input_ac_dict is None: + break + + action_dict = deepcopy(input_ac_dict) # {} + # set arm actions + for arm in active_robot.arms: + if isinstance(active_robot.composite_controller, WholeBody): # input type passed to joint_action_policy + controller_input_type = active_robot.composite_controller.joint_action_policy.input_type + else: + controller_input_type = active_robot.part_controllers[arm].input_type + + if controller_input_type == "delta": + action_dict[arm] = input_ac_dict[f"{arm}_delta"] + elif controller_input_type == "absolute": + action_dict[arm] = input_ac_dict[f"{arm}_abs"] + else: + raise ValueError + + # Maintain gripper state for each robot but only update the active robot with action + env_action = [robot.create_action_vector(all_prev_gripper_actions[i]) for i, robot in enumerate(env.robots)] + env_action[device.active_robot] = active_robot.create_action_vector(action_dict) + env_action = np.concatenate(env_action) + + # Step through the simulation and render + obs, reward, done, info = env.step(env_action) + + # Calculate and print out stats for proprio observation + observed_value = obs[proprio_obs_name] + ground_truth_delayed_value = obs[proprio_ground_truth_obs_name] + print( + f"Observed joint pos: {observed_value}, " + f"Corruption: {observed_value - ground_truth_delayed_value}, " + f"Delay: {calculate_proprio_delay():.3f} sec" + ) + + # read camera observation + im = np.flip(obs[args.camera + "_image"][..., ::-1], 0).astype(np.uint8) + + cv2.imshow("offscreen render", im) + cv2.waitKey(1) diff --git a/third_party/robosuite/robosuite/demos/demo_usd_export.py b/third_party/robosuite/robosuite/demos/demo_usd_export.py new file mode 100644 index 0000000000000000000000000000000000000000..0e0cbd756f643a98539a64dcd48ec3437da55bb5 --- /dev/null +++ b/third_party/robosuite/robosuite/demos/demo_usd_export.py @@ -0,0 +1,165 @@ +""" Exports a USD file corresponding to the collected trajectory. + +The USD (Universal Scene Description) file format allows users to save +trajectories such that they can be rendered in external renderers such +as Omniverse or Blender, offering higher quality rendering. To view the +USD file, open your renderer (must support USD) and import the USD file. +Start the animation in your renderer to view the full trajectory. + +***IMPORTANT***: If you are using mujoco version 3.1.1, please make sure +that you also have numpy < 2 installed in your environment. Failure to do +so may result in incorrect renderings. +""" +import argparse + +import mujoco +import numpy as np + +import robosuite as suite +from robosuite.controllers import load_composite_controller_config +from robosuite.controllers.composite.composite_controller import WholeBody +from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER +from robosuite.utils.usd import exporter +from robosuite.wrappers import VisualizationWrapper + +if mujoco.__version__ == "3.1.1" and np.__version__[0] == "2": + ROBOSUITE_DEFAULT_LOGGER.warning("If using mujoco==3.1.1, please use numpy < 2 for rendering with USD.") + +if __name__ == "__main__": + + parser = argparse.ArgumentParser() + parser.add_argument("--environment", type=str, default="Lift") + parser.add_argument("--robots", nargs="+", type=str, default="Panda", help="Which robot(s) to use in the env") + parser.add_argument( + "--config", type=str, default="default", help="Specified environment configuration if necessary" + ) + parser.add_argument("--arm", type=str, default="right", help="Which arm to control (eg bimanual) 'right' or 'left'") + parser.add_argument("--camera", type=str, default="agentview", help="Which camera to use for collecting demos") + parser.add_argument("--switch-on-grasp", action="store_true", help="Switch gripper control on gripper action") + parser.add_argument("--toggle-camera-on-grasp", action="store_true", help="Switch camera angle on gripper action") + parser.add_argument("--controller", type=str, default="BASIC", help="Choice of controller. Can be 'ik' or 'osc'") + parser.add_argument("--device", type=str, default="keyboard") + parser.add_argument("--pos-sensitivity", type=float, default=1.0, help="How much to scale position user inputs") + parser.add_argument("--rot-sensitivity", type=float, default=1.0, help="How much to scale rotation user inputs") + args = parser.parse_args() + + # Get controller config + controller_config = load_composite_controller_config( + controller=args.controller, + robot=args.robots[0], + ) + + # Create argument configuration + config = { + "env_name": args.environment, + "robots": args.robots, + "controller_configs": controller_config, + } + + # Check if we're using a multi-armed environment and use env_configuration argument if so + if "TwoArm" in args.environment: + config["env_configuration"] = args.config + else: + args.config = None + + # Create environment + env = suite.make( + **config, + has_renderer=True, + has_offscreen_renderer=False, + render_camera=args.camera, + ignore_done=True, + use_camera_obs=False, + reward_shaping=True, + control_freq=20, + hard_reset=False, + ) + + model = env.sim.model._model + data = env.sim.data._data + + scene_option = mujoco.MjvOption() + scene_option.geomgroup = [0, 1, 0, 0, 0, 0] + + exp = exporter.USDExporter(model=model, camera_names=["frontview"]) + + # initialize device + if args.device == "keyboard": + from robosuite.devices import Keyboard + + device = Keyboard(env=env, pos_sensitivity=args.pos_sensitivity, rot_sensitivity=args.rot_sensitivity) + env.viewer.add_keypress_callback(device.on_press) + elif args.device == "spacemouse": + from robosuite.devices import SpaceMouse + + device = SpaceMouse(env=env, pos_sensitivity=args.pos_sensitivity, rot_sensitivity=args.rot_sensitivity) + else: + raise Exception("Invalid device choice: choose either 'keyboard' or 'spacemouse'.") + + env.reset() + cam_id = 0 + num_cam = len(env.sim.model.camera_names) + env.render() + + # Initialize variables that should the maintained between resets + last_grasp = 0 + + device.start_control() + + for robot in env.robots: + robot.print_action_info_dict() + + # Keep track of prev gripper actions when using since they are position-based and must be maintained when arms switched + all_prev_gripper_actions = [ + { + f"{robot_arm}_gripper": np.repeat([0], robot.gripper[robot_arm].dof) + for robot_arm in robot.arms + if robot.gripper[robot_arm].dof > 0 + } + for robot in env.robots + ] + + # Loop until we get a reset from the input or the task completes + while True: + # Set active robot + active_robot = env.robots[device.active_robot] + + # Get the newest action + input_ac_dict = device.input2action() + + # If action is none, then this a reset so we should break + if input_ac_dict is None: + break + + from copy import deepcopy + + action_dict = deepcopy(input_ac_dict) # {} + # set arm actions + for arm in active_robot.arms: + if isinstance(active_robot.composite_controller, WholeBody): # input type passed to joint_action_policy + controller_input_type = active_robot.composite_controller.joint_action_policy.input_type + else: + controller_input_type = active_robot.part_controllers[arm].input_type + + if controller_input_type == "delta": + action_dict[arm] = input_ac_dict[f"{arm}_delta"] + elif controller_input_type == "absolute": + action_dict[arm] = input_ac_dict[f"{arm}_abs"] + else: + raise ValueError + + # Maintain gripper state for each robot but only update the active robot with action + env_action = [robot.create_action_vector(all_prev_gripper_actions[i]) for i, robot in enumerate(env.robots)] + env_action[device.active_robot] = active_robot.create_action_vector(action_dict) + env_action = np.concatenate(env_action) + + env.step(env_action) + env.render() + exp.update_scene(data, scene_option=scene_option) + + exp.add_light(pos=[0, 0, 0], intensity=2000, obj_name="dome_light", light_type="dome") + + exp.save_scene(filetype="usd") + + # cleanup for end of data collection episodes + env.close() diff --git a/third_party/robosuite/robosuite/demos/demo_video_recording.py b/third_party/robosuite/robosuite/demos/demo_video_recording.py new file mode 100644 index 0000000000000000000000000000000000000000..c336dbaaaff76ee004646ff55e6db48ae1e9a339 --- /dev/null +++ b/third_party/robosuite/robosuite/demos/demo_video_recording.py @@ -0,0 +1,70 @@ +""" +Record video of agent episodes with the imageio library. +This script uses offscreen rendering. + +Example: + $ python demo_video_recording.py --environment Lift --robots Panda +""" + +import argparse + +import imageio +import numpy as np + +import robosuite.macros as macros +from robosuite import make + +# Set the image convention to opencv so that the images are automatically rendered "right side up" when using imageio +# (which uses opencv convention) +macros.IMAGE_CONVENTION = "opencv" + +if __name__ == "__main__": + + parser = argparse.ArgumentParser() + parser.add_argument("--environment", type=str, default="Stack") + parser.add_argument("--robots", nargs="+", type=str, default="Panda", help="Which robot(s) to use in the env") + parser.add_argument("--camera", type=str, default="agentview", help="Name of camera to render") + parser.add_argument("--video_path", type=str, default="video.mp4") + parser.add_argument("--timesteps", type=int, default=500) + parser.add_argument("--height", type=int, default=512) + parser.add_argument("--width", type=int, default=512) + parser.add_argument("--skip_frame", type=int, default=1) + args = parser.parse_args() + + # initialize an environment with offscreen renderer + env = make( + args.environment, + args.robots, + has_renderer=False, + ignore_done=True, + use_camera_obs=True, + use_object_obs=False, + camera_names=args.camera, + camera_heights=args.height, + camera_widths=args.width, + ) + + obs = env.reset() + ndim = env.action_dim + + # create a video writer with imageio + writer = imageio.get_writer(args.video_path, fps=20) + + frames = [] + for i in range(args.timesteps): + + # run a uniformly random agent + action = 0.5 * np.random.randn(ndim) + obs, reward, done, info = env.step(action) + + # dump a frame from every K frames + if i % args.skip_frame == 0: + frame = obs[args.camera + "_image"] + writer.append_data(frame) + print("Saving frame #{}".format(i)) + + if done: + break + + writer.close() + print(f"Video saved to {args.video_path}") diff --git a/third_party/robosuite/robosuite/devices/__init__.py b/third_party/robosuite/robosuite/devices/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..39822e14659a86f406fdd53ede13fbbf1021e65c --- /dev/null +++ b/third_party/robosuite/robosuite/devices/__init__.py @@ -0,0 +1,12 @@ +from .device import Device +from .keyboard import Keyboard + +try: + from .spacemouse import SpaceMouse +except ImportError as e: + print("Exception!", e) + print( + """Unable to load module hid, required to interface with SpaceMouse.\n + Only macOS is officially supported. Install the additional\n + requirements with `pip install -r requirements-extra.txt`""" + ) diff --git a/third_party/robosuite/robosuite/devices/device.py b/third_party/robosuite/robosuite/devices/device.py new file mode 100644 index 0000000000000000000000000000000000000000..32da777a0d502d425111f0d7e60666bf0382f33d --- /dev/null +++ b/third_party/robosuite/robosuite/devices/device.py @@ -0,0 +1,265 @@ +import abc +from typing import Dict, List, Optional # for abstract base class definitions + +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.controllers.parts.arm.osc import OperationalSpaceController + + +class Device(metaclass=abc.ABCMeta): + """ + Base class for all robot controllers. + Defines basic interface for all controllers to adhere to. + Also contains shared logic for managing multiple and/or multiarmed robots. + """ + + def __init__(self, env): + """ + Args: + env (RobotEnv): The environment which contains the robot(s) to control + using this device. + """ + self.env = env + self.all_robot_arms = [robot.arms for robot in self.env.robots] + self.num_robots = len(self.all_robot_arms) + + def _reset_internal_state(self): + """ + Resets internal state related to robot control + """ + self.grasp_states = [[False] * len(self.all_robot_arms[i]) for i in range(self.num_robots)] + self.active_arm_indices = [0] * len(self.all_robot_arms) + self.active_robot = 0 + self.base_modes = [False] * len(self.all_robot_arms) + + self._prev_target = {arm: None for arm in self.all_robot_arms[self.active_robot]} + + @property + def active_arm(self): + return self.all_robot_arms[self.active_robot][self.active_arm_index] + + @property + def grasp(self): + return self.grasp_states[self.active_robot][self.active_arm_index] + + @property + def active_arm_index(self): + return self.active_arm_indices[self.active_robot] + + @property + def base_mode(self): + return self.base_modes[self.active_robot] + + @active_arm_index.setter + def active_arm_index(self, value): + self.active_arm_indices[self.active_robot] = value + + @abc.abstractmethod + def start_control(self): + """ + Method that should be called externally before controller can + start receiving commands. + """ + raise NotImplementedError + + @abc.abstractmethod + def get_controller_state(self) -> Dict: + """Returns the current state of the device, a dictionary of pos, orn, grasp, and reset.""" + raise NotImplementedError + + def _postprocess_device_outputs(self, dpos, drotation): + raise NotImplementedError + + def input2action(self, mirror_actions=False) -> Optional[Dict]: + """ + Converts an input from an active device into a valid action sequence that can be fed into an env.step() call + + If a reset is triggered from the device, immediately returns None. Else, returns the appropriate action + + Args: + mirror_actions (bool): actions corresponding to viewing robot from behind. + first axis: left/right. second axis: back/forward. third axis: down/up. + + Returns: + Optional[Dict]: Dictionary of actions to be fed into env.step() + if reset is triggered, returns None + """ + robot = self.env.robots[self.active_robot] + active_arm = self.active_arm + + state = self.get_controller_state() + # Note: Devices output rotation with x and z flipped to account for robots starting with gripper facing down + # Also note that the outputted rotation is an absolute rotation, while outputted dpos is delta pos + # Raw delta rotations from neutral user input is captured in raw_drotation (roll, pitch, yaw) + dpos, rotation, raw_drotation, grasp, reset = ( + state["dpos"], + state["rotation"], + state["raw_drotation"], + state["grasp"], + state["reset"], + ) + + if mirror_actions: + dpos[0] *= -1 + dpos[1] *= -1 + raw_drotation[0] *= -1 + raw_drotation[1] *= -1 + + # If we're resetting, immediately return None + if reset: + return None + + # Get controller reference + controller = robot.part_controllers[active_arm] + gripper_dof = robot.gripper[active_arm].dof + + assert controller.name in ["OSC_POSE", "JOINT_POSITION"], "only supporting OSC_POSE and JOINT_POSITION for now" + + # process raw device inputs + drotation = raw_drotation[[1, 0, 2]] + # Flip z + drotation[2] = -drotation[2] + # Scale rotation for teleoperation (tuned for OSC) -- gains tuned for each device + dpos, drotation = self._postprocess_device_outputs(dpos, drotation) + # map 0 to -1 (open) and map 1 to 1 (closed) + grasp = 1 if grasp else -1 + + ac_dict = {} + # populate delta actions for the arms + for arm in robot.arms: + # OSC keys + arm_action = self.get_arm_action( + robot, + arm, + norm_delta=np.zeros(6), + ) + ac_dict[f"{arm}_abs"] = arm_action["abs"] + ac_dict[f"{arm}_delta"] = arm_action["delta"] + ac_dict[f"{arm}_gripper"] = np.zeros(robot.gripper[arm].dof) + + if robot.is_mobile: + base_mode = bool(state["base_mode"]) + if base_mode is True: + arm_norm_delta = np.zeros(6) + base_ac = np.array([dpos[0], dpos[1], drotation[2]]) + torso_ac = np.array([dpos[2]]) + else: + arm_norm_delta = np.concatenate([dpos, drotation]) + base_ac = np.zeros(3) + torso_ac = np.zeros(1) + + ac_dict["base"] = base_ac + # ac_dict["torso"] = torso_ac + ac_dict["base_mode"] = np.array([1 if base_mode is True else -1]) + else: + arm_norm_delta = np.concatenate([dpos, drotation]) + + # populate action dict items for arm and grippers + arm_action = self.get_arm_action( + robot, + active_arm, + norm_delta=arm_norm_delta, + ) + ac_dict[f"{active_arm}_abs"] = arm_action["abs"] + ac_dict[f"{active_arm}_delta"] = arm_action["delta"] + ac_dict[f"{active_arm}_gripper"] = np.array([grasp] * gripper_dof) + + # clip actions between -1 and 1 + for (k, v) in ac_dict.items(): + if "abs" not in k: + ac_dict[k] = np.clip(v, -1, 1) + + return ac_dict + + def get_arm_action(self, robot, arm, norm_delta, goal_update_mode="target"): + assert np.all(norm_delta <= 1.0) and np.all(norm_delta >= -1.0) + + assert goal_update_mode in [ + "achieved", + "target", + ] # update next target either based on achieved pose or current target pose + + # TODO: the logic between OSC and while body based ik is fragmented right now. Unify + if isinstance(robot.part_controllers[arm], OperationalSpaceController): + arm_controller = robot.part_controllers[arm] + delta_action = arm_controller.scale_action(norm_delta.copy()) + abs_action = arm_controller.delta_to_abs_action(delta_action, goal_update_mode=None) + return { + "delta": norm_delta, + "abs": abs_action, + } + elif robot.composite_controller_config["type"] in ["WHOLE_BODY_MINK_IK"]: + ref_frame = self.env.robots[0].composite_controller.composite_controller_specific_config.get( + "ik_input_ref_frame", "world" + ) + + delta_action = norm_delta.copy() + delta_action[0:3] *= 0.05 + delta_action[3:6] *= 0.15 + + # general case + if goal_update_mode == "achieved" or self._prev_target[arm] is None: + site_name = f"gripper0_{arm}_grip_site" + # update next target based on current achieved pose + pos = self.env.sim.data.get_site_xpos(site_name).copy() + ori = self.env.sim.data.get_site_xmat(site_name).copy() + if ref_frame == "base": + # convert target in world coordinate to + pose_in_world = np.eye(4) + pose_in_world[:3, 3] = pos + pose_in_world[:3, :3] = ori + pose_in_base = self.env.robots[0].composite_controller.joint_action_policy.transform_pose( + src_frame_pose=pose_in_world, + src_frame="world", # mocap pose is world coordinates + dst_frame=ref_frame, + ) + pos, ori = pose_in_base[:3, 3], pose_in_base[:3, :3] + else: + # update next target based on previous target pose + pos = self._prev_target[arm][0:3].copy() + ori = T.quat2mat(T.axisangle2quat(self._prev_target[arm][3:6].copy())) + + # new positions computed in world frame coordinates + new_pos = pos + delta_action[0:3] + delta_ori = T.quat2mat(T.axisangle2quat(delta_action[3:6])) + new_ori = np.dot(delta_ori, ori) + new_axisangle = T.quat2axisangle(T.mat2quat(new_ori)) + + abs_action = np.concatenate([new_pos, new_axisangle]) + self._prev_target[arm] = abs_action.copy() + + return { + "delta": delta_action, + "abs": abs_action, + } + elif robot.composite_controller_config["type"] in ["WHOLE_BODY_IK"]: + if goal_update_mode == "achieved" or self._prev_target[arm] is None: + site_name = f"gripper0_{arm}_grip_site" + # update next target based on current achieved pose + pos = self.env.sim.data.get_site_xpos(site_name).copy() + ori = self.env.sim.data.get_site_xmat(site_name).copy() + else: + # update next target based on previous target pose + pos = self._prev_target[arm][0:3].copy() + ori = T.quat2mat(T.axisangle2quat(self._prev_target[arm][3:6].copy())) + + delta_action = norm_delta.copy() + delta_action[0:3] *= 0.05 + delta_action[3:6] *= 0.15 + + # new positions computed in world frame coordinates + new_pos = pos + delta_action[0:3] + delta_ori = T.quat2mat(T.axisangle2quat(delta_action[3:6])) + new_ori = np.dot(delta_ori, ori) + new_axisangle = T.quat2axisangle(T.mat2quat(new_ori)) + + abs_action = np.concatenate([new_pos, new_axisangle]) + self._prev_target[arm] = abs_action.copy() + + return { + "delta": delta_action, + "abs": abs_action, + } + else: + raise NotImplementedError diff --git a/third_party/robosuite/robosuite/devices/keyboard.py b/third_party/robosuite/robosuite/devices/keyboard.py new file mode 100644 index 0000000000000000000000000000000000000000..dcc58c757a47ad7b0ed178d36f1fa857c69a49a6 --- /dev/null +++ b/third_party/robosuite/robosuite/devices/keyboard.py @@ -0,0 +1,199 @@ +""" +Driver class for Keyboard controller. +""" + +import numpy as np +from pynput.keyboard import Controller, Key, Listener + +from robosuite.devices import Device +from robosuite.utils.transform_utils import rotation_matrix + + +class Keyboard(Device): + """ + A minimalistic driver class for a Keyboard. + Args: + env (RobotEnv): The environment which contains the robot(s) to control + using this device. + pos_sensitivity (float): Magnitude of input position command scaling + rot_sensitivity (float): Magnitude of scale input rotation commands scaling + """ + + def __init__(self, env, pos_sensitivity=1.0, rot_sensitivity=1.0): + super().__init__(env) + + self._display_controls() + self._reset_internal_state() + + self._reset_state = 0 + self._enabled = False + self._pos_step = 0.05 + + self.pos_sensitivity = pos_sensitivity + self.rot_sensitivity = rot_sensitivity + + # make a thread to listen to keyboard and register our callback functions + self.listener = Listener(on_press=self.on_press, on_release=self.on_release) + + # start listening + self.listener.start() + + @staticmethod + def _display_controls(): + """ + Method to pretty print controls. + """ + + def print_command(char, info): + char += " " * (30 - len(char)) + print("{}\t{}".format(char, info)) + + print("") + print_command("Keys", "Command") + print_command("Ctrl+q", "reset simulation") + print_command("spacebar", "toggle gripper (open/close)") + print_command("up-right-down-left", "move horizontally in x-y plane") + print_command(".-;", "move vertically") + print_command("o-p", "rotate (yaw)") + print_command("y-h", "rotate (pitch)") + print_command("e-r", "rotate (roll)") + print_command("b", "toggle arm/base mode (if applicable)") + print_command("s", "switch active arm (if multi-armed robot)") + print_command("=", "switch active robot (if multi-robot environment)") + print("") + + def _reset_internal_state(self): + """ + Resets internal state of controller, except for the reset signal. + """ + super()._reset_internal_state() + + self.rotation = np.array([[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]) + self.raw_drotation = np.zeros(3) # immediate roll, pitch, yaw delta values from keyboard hits + self.last_drotation = np.zeros(3) + self.pos = np.zeros(3) # (x, y, z) + self.last_pos = np.zeros(3) + + def start_control(self): + """ + Method that should be called externally before controller can + start receiving commands. + """ + self._reset_internal_state() + self._reset_state = 0 + self._enabled = True + + def get_controller_state(self): + """ + Grabs the current state of the keyboard. + Returns: + dict: A dictionary containing dpos, orn, unmodified orn, grasp, and reset + """ + + dpos = self.pos - self.last_pos + self.last_pos = np.array(self.pos) + raw_drotation = ( + self.raw_drotation - self.last_drotation + ) # create local variable to return, then reset internal drotation + self.last_drotation = np.array(self.raw_drotation) + return dict( + dpos=dpos, + rotation=self.rotation, + raw_drotation=raw_drotation, + grasp=int(self.grasp), + reset=self._reset_state, + base_mode=int(self.base_mode), + ) + + def on_press(self, key): + """ + Key handler for key presses. + Args: + key (str): key that was pressed + """ + + try: + # controls for moving position + if key == Key.up: + self.pos[0] -= self._pos_step * self.pos_sensitivity # dec x + elif key == Key.down: + self.pos[0] += self._pos_step * self.pos_sensitivity # inc x + elif key == Key.left: + self.pos[1] -= self._pos_step * self.pos_sensitivity # dec y + elif key == Key.right: + self.pos[1] += self._pos_step * self.pos_sensitivity # inc y + elif key.char == ".": + self.pos[2] -= self._pos_step * self.pos_sensitivity # dec z + elif key.char == ";": + self.pos[2] += self._pos_step * self.pos_sensitivity # inc z + + # controls for moving orientation + elif key.char == "e": + drot = rotation_matrix(angle=0.1 * self.rot_sensitivity, direction=[1.0, 0.0, 0.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates x + self.raw_drotation[1] -= 0.1 * self.rot_sensitivity + elif key.char == "r": + drot = rotation_matrix(angle=-0.1 * self.rot_sensitivity, direction=[1.0, 0.0, 0.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates x + self.raw_drotation[1] += 0.1 * self.rot_sensitivity + elif key.char == "y": + drot = rotation_matrix(angle=0.1 * self.rot_sensitivity, direction=[0.0, 1.0, 0.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates y + self.raw_drotation[0] += 0.1 * self.rot_sensitivity + elif key.char == "h": + drot = rotation_matrix(angle=-0.1 * self.rot_sensitivity, direction=[0.0, 1.0, 0.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates y + self.raw_drotation[0] -= 0.1 * self.rot_sensitivity + elif key.char == "p": + drot = rotation_matrix(angle=0.1 * self.rot_sensitivity, direction=[0.0, 0.0, 1.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates z + self.raw_drotation[2] += 0.1 * self.rot_sensitivity + elif key.char == "o": + drot = rotation_matrix(angle=-0.1 * self.rot_sensitivity, direction=[0.0, 0.0, 1.0])[:3, :3] + self.rotation = self.rotation.dot(drot) # rotates z + self.raw_drotation[2] -= 0.1 * self.rot_sensitivity + + except AttributeError as e: + pass + + def on_release(self, key): + """ + Key handler for key releases. + Args: + key (str): key that was pressed + """ + + try: + # controls for grasping + if key == Key.space: + self.grasp_states[self.active_robot][self.active_arm_index] = not self.grasp_states[self.active_robot][ + self.active_arm_index + ] # toggle gripper + + # controls for mobile base (only applicable if mobile base present) + elif key.char == "b": + self.base_modes[self.active_robot] = not self.base_modes[self.active_robot] # toggle mobile base + + # user-commanded reset + elif key.char == "q": + self._reset_state = 1 + self._enabled = False + self._reset_internal_state() + + elif key.char == "s": + self.active_arm_index = (self.active_arm_index + 1) % len(self.all_robot_arms[self.active_robot]) + + elif key.char == "=": + self.active_robot = (self.active_robot + 1) % self.num_robots + + except AttributeError as e: + pass + + def _postprocess_device_outputs(self, dpos, drotation): + drotation = drotation * 1.5 + dpos = dpos * 75 + + dpos = np.clip(dpos, -1, 1) + drotation = np.clip(drotation, -1, 1) + + return dpos, drotation diff --git a/third_party/robosuite/robosuite/devices/mjgui.py b/third_party/robosuite/robosuite/devices/mjgui.py new file mode 100644 index 0000000000000000000000000000000000000000..4c5d5f49160fc570c68176a86018bb234a365cfa --- /dev/null +++ b/third_party/robosuite/robosuite/devices/mjgui.py @@ -0,0 +1,188 @@ +from typing import Dict, List, Optional, Tuple + +import mujoco +import numpy as np + +from robosuite.controllers.composite.composite_controller import WholeBody, WholeBodyIK +from robosuite.devices import Device +from robosuite.utils import transform_utils +from robosuite.utils.transform_utils import rotation_matrix + + +def set_mocap_pose( + sim, target_pos: Optional[np.ndarray] = None, target_mat: Optional[np.ndarray] = None, mocap_name: str = "target" +): + mocap_id = sim.model.body(mocap_name).mocapid[0] + if target_pos is not None: + sim.data.mocap_pos[mocap_id] = target_pos + if target_mat is not None: + # convert mat to quat + target_quat = np.empty(4) + if target_mat.shape == (3, 3): + target_mat = target_mat.reshape(9, 1) # 9-dim for mju_mat2Quat input + mujoco.mju_mat2Quat(target_quat, target_mat) + sim.data.mocap_quat[mocap_id] = target_quat + + +def get_mocap_pose(sim, mocap_name: str = "target") -> Tuple[np.ndarray, np.ndarray]: + mocap_id = sim.model.body(mocap_name).mocapid[0] + target_pos = np.copy(sim.data.mocap_pos[mocap_id]) + target_quat = np.copy(sim.data.mocap_quat[mocap_id]) + target_mat = np.empty(9) + mujoco.mju_quat2Mat(target_mat, target_quat) + target_mat = target_mat.reshape(3, 3) + return target_pos, target_mat + + +class MJGUI(Device): + """ + Class for 'device' involving mujoco viewer and mocap bodies being dragged by user's mouse. + + Args: + env (RobotEnv): The environment which contains the robot(s) to control + using this device. + """ + + def __init__(self, env, active_end_effector: Optional[str] = "right"): + super().__init__(env) + + self._display_controls() + self._reset_internal_state() + + self._reset_state = 0 + self._enabled = False + + self.active_end_effector = active_end_effector + + @staticmethod + def _display_controls(): + """ + Method to pretty print controls. + """ + print("") + print( + "Mujoco viewer UI mouse 'device'. Use the mouse to drag mocap bodies. We use the mocap's coordinates " + "to output actions." + ) + print("") + + def start_control(self): + """ + Method that should be called externally before controller can + start receiving commands. + """ + self._reset_internal_state() + self._reset_state = 0 + self._enabled = True + + def get_controller_state(self): + """ + Grabs the current state of the keyboard. + Returns: + dict: A dictionary containing dpos, orn, unmodified orn, grasp, and reset + """ + return dict() + + def _get_site_names(self) -> List[str]: + """ + Helper function to get the names of the sites used for mocap bodies. + + TODO: unify this logic to be controller independent. + + Returns: + List[str]: A list of site names. + """ + if isinstance(self.env.robots[0].composite_controller, WholeBody): # input type passed to joint_action_policy + site_names = self.env.robots[0].composite_controller.joint_action_policy.site_names + else: + site_name = f"gripper0_{self.active_arm}_grip_site" + site_names = [site_name] + return site_names + + def _reset_internal_state(self): + """ + Resets internal state related to robot control + """ + super()._reset_internal_state() + self.grasp_states = [[False] * len(self.all_robot_arms[i]) for i in range(self.num_robots)] + self.active_arm_indices = [0] * len(self.all_robot_arms) + self.active_robot = 0 + self.base_modes = [False] * len(self.all_robot_arms) + + site_names = self._get_site_names() + for site_name in site_names: + target_name_prefix = "right" if "right" in site_name else "left" # hardcoded for now + target_pos = self.env.sim.data.site_xpos[self.env.sim.model.site_name2id(site_name)] + target_mat = self.env.sim.data.site_xmat[self.env.sim.model.site_name2id(site_name)] + set_mocap_pose(self.env.sim, target_pos, target_mat, f"{target_name_prefix}_eef_target") + + def input2action(self) -> Dict[str, np.ndarray]: + """ + Uses mocap body poses to determine action for robot. Obtain input_type + (i.e. absolute actions or delta actions) and input_ref_frame (i.e. world frame, base frame or eef frame) + from the controller itself. + + """ + # TODO: unify this logic to be independent from controller type. + action: Dict[str, np.ndarray] = {} + gripper_dof = self.env.robots[0].gripper[self.active_end_effector].dof + site_names = self._get_site_names() + for site_name in site_names: + target_name_prefix = "right" if "right" in site_name else "left" # hardcoded for now + target_pos_world, target_ori_mat_world = get_mocap_pose(self.env.sim, f"{target_name_prefix}_eef_target") + + if isinstance(self.env.robots[0].composite_controller, WholeBodyIK): + assert ( + self.env.robots[0].composite_controller.composite_controller_specific_config.get( + "ik_input_ref_frame", "world" + ) + == "world" + ), ("Only support world frame for MJGui teleop for now. " "Please modify the controller configs.") + assert ( + self.env.robots[0].composite_controller.composite_controller_specific_config.get( + "ik_input_type", "absolute" + ) + == "absolute" + ), ("Only support absolute actions for MJGui teleop for now. " "Please modify the controller configs.") + # check if need to update frames + if isinstance(self.env.robots[0].composite_controller, WholeBody): + # TODO: should be more general + if ( + self.env.robots[0].composite_controller.composite_controller_specific_config.get( + "ik_input_ref_frame", "world" + ) + != "world" + ): + target_pose = np.eye(4) + target_pose[:3, 3] = target_pos_world + target_pose[:3, :3] = target_ori_mat_world + target_pose = self.env.robots[0].composite_controller.joint_action_policy.transform_pose( + src_frame_pose=target_pose, + src_frame="world", # mocap pose is world coordinates + dst_frame=self.env.robots[0].composite_controller.composite_controller_specific_config.get( + "ik_input_ref_frame", "world" + ), + ) + target_pos, target_ori_mat = target_pose[:3, 3], target_pose[:3, :3] + else: + target_pos, target_ori_mat = target_pos_world, target_ori_mat_world + else: + assert ( + self.env.robots[0].part_controllers[self.active_end_effector].input_ref_frame == "world" + and self.env.robots[0].part_controllers[self.active_end_effector].input_type == "absolute" + ), ( + "Only support world frame and absolute actions for now. You can modify the controller configs " + "being used, e.g. in robosuite/controllers/config/robots/{robot_name}.json, " + "robosuite/controllers/config/default/composite/{}.json to enable other options." + ) + target_pos, target_ori_mat = target_pos_world, target_ori_mat_world + + # convert ori mat to axis angle + axis_angle_target = transform_utils.quat2axisangle(transform_utils.mat2quat(target_ori_mat)) + action[target_name_prefix + "_abs"] = np.concatenate([target_pos, axis_angle_target]) + grasp = 1 # hardcode grasp action for now + action[f"{target_name_prefix}_gripper"] = np.array([grasp] * gripper_dof) + + # TODO: enable delta actions. Currently only abs actions. + # now convert actions to desired frames (take from controller) + return action diff --git a/third_party/robosuite/robosuite/devices/spacemouse.py b/third_party/robosuite/robosuite/devices/spacemouse.py new file mode 100644 index 0000000000000000000000000000000000000000..82b49effd2ca4833c576d2c0c4835b0a58f68257 --- /dev/null +++ b/third_party/robosuite/robosuite/devices/spacemouse.py @@ -0,0 +1,379 @@ +"""Driver class for SpaceMouse controller. + +This class provides a driver support to SpaceMouse on macOS. +In particular, we assume you are using a SpaceMouse Wireless by default. + +To set up a new SpaceMouse controller: + 1. Download and install driver from https://www.3dconnexion.com/service/drivers.html + 2. Install hidapi library through pip + (make sure you run uninstall hid first if it is installed). + 3. Make sure SpaceMouse is connected before running the script + 4. (Optional) Based on the model of SpaceMouse, you might need to change the + vendor id and product id that correspond to the device. + +For Linux support, you can find open-source Linux drivers and SDKs online. + See http://spacenav.sourceforge.net/ + +""" + +import threading +import time +from collections import namedtuple + +import numpy as np +from pynput.keyboard import Controller, Key, Listener + +from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER + +try: + import hid +except ModuleNotFoundError as exc: + raise ImportError( + "Unable to load module hid, required to interface with SpaceMouse. " + "Only macOS is officially supported. Install the additional " + "requirements with `pip install -r requirements-extra.txt`" + ) from exc + +from pynput.keyboard import Controller, Key, Listener + +import robosuite.macros as macros +from robosuite.devices import Device +from robosuite.utils.transform_utils import rotation_matrix + +AxisSpec = namedtuple("AxisSpec", ["channel", "byte1", "byte2", "scale"]) + +SPACE_MOUSE_SPEC = { + "x": AxisSpec(channel=1, byte1=1, byte2=2, scale=1), + "y": AxisSpec(channel=1, byte1=3, byte2=4, scale=-1), + "z": AxisSpec(channel=1, byte1=5, byte2=6, scale=-1), + "roll": AxisSpec(channel=1, byte1=7, byte2=8, scale=-1), + "pitch": AxisSpec(channel=1, byte1=9, byte2=10, scale=-1), + "yaw": AxisSpec(channel=1, byte1=11, byte2=12, scale=1), +} + + +def to_int16(y1, y2): + """ + Convert two 8 bit bytes to a signed 16 bit integer. + + Args: + y1 (int): 8-bit byte + y2 (int): 8-bit byte + + Returns: + int: 16-bit integer + """ + x = (y1) | (y2 << 8) + if x >= 32768: + x = -(65536 - x) + return x + + +def scale_to_control(x, axis_scale=350.0, min_v=-1.0, max_v=1.0): + """ + Normalize raw HID readings to target range. + + Args: + x (int): Raw reading from HID + axis_scale (float): (Inverted) scaling factor for mapping raw input value + min_v (float): Minimum limit after scaling + max_v (float): Maximum limit after scaling + + Returns: + float: Clipped, scaled input from HID + """ + x = x / axis_scale + x = min(max(x, min_v), max_v) + return x + + +def convert(b1, b2): + """ + Converts SpaceMouse message to commands. + + Args: + b1 (int): 8-bit byte + b2 (int): 8-bit byte + + Returns: + float: Scaled value from Spacemouse message + """ + return scale_to_control(to_int16(b1, b2)) + + +class SpaceMouse(Device): + """ + A minimalistic driver class for SpaceMouse with HID library. + + Note: Use hid.enumerate() to view all USB human interface devices (HID). + Make sure SpaceMouse is detected before running the script. + You can look up its vendor/product id from this method. + + Args: + env (RobotEnv): The environment which contains the robot(s) to control + using this device. + pos_sensitivity (float): Magnitude of input position command scaling + rot_sensitivity (float): Magnitude of scale input rotation commands scaling + """ + + def __init__( + self, + env, + vendor_id=macros.SPACEMOUSE_VENDOR_ID, + product_id=macros.SPACEMOUSE_PRODUCT_ID, + pos_sensitivity=1.0, + rot_sensitivity=1.0, + ): + super().__init__(env) + + print("Opening SpaceMouse device") + self.vendor_id = vendor_id + self.product_id = product_id + self.device = hid.device() + try: + self.device.open(self.vendor_id, self.product_id) # SpaceMouse + except OSError as e: + ROBOSUITE_DEFAULT_LOGGER.warning( + "Failed to open SpaceMouse device" + "Consider killing other processes that may be using the device such as 3DconnexionHelper (killall 3DconnexionHelper)" + ) + raise + + self.pos_sensitivity = pos_sensitivity + self.rot_sensitivity = rot_sensitivity + + print("Manufacturer: %s" % self.device.get_manufacturer_string()) + print("Product: %s" % self.device.get_product_string()) + + # 6-DOF variables + self.x, self.y, self.z = 0, 0, 0 + self.roll, self.pitch, self.yaw = 0, 0, 0 + + self._display_controls() + + self.single_click_and_hold = False + + self._control = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + self._reset_state = 0 + self.rotation = np.array([[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]) + self._enabled = False + + # launch a new listener thread to listen to SpaceMouse + self.thread = threading.Thread(target=self.run) + self.thread.daemon = True + self.thread.start() + + # also add a keyboard for aux controls + self.listener = Listener(on_press=self.on_press, on_release=self.on_release) + + # start listening + self.listener.start() + + @staticmethod + def _display_controls(): + """ + Method to pretty print controls. + """ + + def print_command(char, info): + char += " " * (30 - len(char)) + print("{}\t{}".format(char, info)) + + print("") + print_command("Control", "Command") + print_command("Right button", "reset simulation") + print_command("Left button (hold)", "close gripper") + print_command("Move mouse laterally", "move arm horizontally in x-y plane") + print_command("Move mouse vertically", "move arm vertically") + print_command("Twist mouse about an axis", "rotate arm about a corresponding axis") + print_command("Control+C", "quit") + print_command("b", "toggle arm/base mode (if applicable)") + print_command("s", "switch active arm (if multi-armed robot)") + print_command("=", "switch active robot (if multi-robot environment)") + print("") + + def _reset_internal_state(self): + """ + Resets internal state of controller, except for the reset signal. + """ + super()._reset_internal_state() + + self.rotation = np.array([[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]) + # Reset 6-DOF variables + self.x, self.y, self.z = 0, 0, 0 + self.roll, self.pitch, self.yaw = 0, 0, 0 + # Reset control + self._control = np.zeros(6) + # Reset grasp + self.single_click_and_hold = False + + def start_control(self): + """ + Method that should be called externally before controller can + start receiving commands. + """ + self._reset_internal_state() + self._reset_state = 0 + self._enabled = True + + def get_controller_state(self): + """ + Grabs the current state of the 3D mouse. + + Returns: + dict: A dictionary containing dpos, orn, unmodified orn, grasp, and reset + """ + dpos = self.control[:3] * 0.005 * self.pos_sensitivity + roll, pitch, yaw = self.control[3:] * 0.005 * self.rot_sensitivity + + # convert RPY to an absolute orientation + drot1 = rotation_matrix(angle=-pitch, direction=[1.0, 0, 0], point=None)[:3, :3] + drot2 = rotation_matrix(angle=roll, direction=[0, 1.0, 0], point=None)[:3, :3] + drot3 = rotation_matrix(angle=yaw, direction=[0, 0, 1.0], point=None)[:3, :3] + + self.rotation = self.rotation.dot(drot1.dot(drot2.dot(drot3))) + + return dict( + dpos=dpos, + rotation=self.rotation, + raw_drotation=np.array([roll, pitch, yaw]), + grasp=self.control_gripper, + reset=self._reset_state, + base_mode=int(self.base_mode), + ) + + def run(self): + """Listener method that keeps pulling new messages.""" + + t_last_click = -1 + + while True: + d = self.device.read(13) + if d is not None and self._enabled: + + if self.product_id == 50741: + ## logic for older spacemouse model + + if d[0] == 1: ## readings from 6-DoF sensor + self.y = convert(d[1], d[2]) + self.x = convert(d[3], d[4]) + self.z = convert(d[5], d[6]) * -1.0 + + elif d[0] == 2: + + self.roll = convert(d[1], d[2]) + self.pitch = convert(d[3], d[4]) + self.yaw = convert(d[5], d[6]) + + self._control = [ + self.x, + self.y, + self.z, + self.roll, + self.pitch, + self.yaw, + ] + else: + ## default logic for all other spacemouse models + + if d[0] == 1: ## readings from 6-DoF sensor + self.y = convert(d[1], d[2]) + self.x = convert(d[3], d[4]) + self.z = convert(d[5], d[6]) * -1.0 + + self.roll = convert(d[7], d[8]) + self.pitch = convert(d[9], d[10]) + self.yaw = convert(d[11], d[12]) + + self._control = [ + self.x, + self.y, + self.z, + self.roll, + self.pitch, + self.yaw, + ] + + if d[0] == 3: ## readings from the side buttons + + # press left button + if d[1] == 1: + t_click = time.time() + elapsed_time = t_click - t_last_click + t_last_click = t_click + self.single_click_and_hold = True + + # release left button + if d[1] == 0: + self.single_click_and_hold = False + + # right button is for reset + if d[1] == 2: + self._reset_state = 1 + self._enabled = False + self._reset_internal_state() + + @property + def control(self): + """ + Grabs current pose of Spacemouse + + Returns: + np.array: 6-DoF control value + """ + return np.array(self._control) + + @property + def control_gripper(self): + """ + Maps internal states into gripper commands. + + Returns: + float: Whether we're using single click and hold or not + """ + if self.single_click_and_hold: + return 1.0 + return 0 + + def on_press(self, key): + """ + Key handler for key presses. + Args: + key (str): key that was pressed + """ + pass + + def on_release(self, key): + """ + Key handler for key releases. + Args: + key (str): key that was pressed + """ + try: + # controls for mobile base (only applicable if mobile base present) + if key.char == "b": + self.base_modes[self.active_robot] = not self.base_modes[self.active_robot] # toggle mobile base + elif key.char == "s": + self.active_arm_index = (self.active_arm_index + 1) % len(self.all_robot_arms[self.active_robot]) + elif key.char == "=": + self.active_robot = (self.active_robot + 1) % self.num_robots + + except AttributeError as e: + pass + + def _postprocess_device_outputs(self, dpos, drotation): + drotation = drotation * 50 + dpos = dpos * 125 + + dpos = np.clip(dpos, -1, 1) + drotation = np.clip(drotation, -1, 1) + + return dpos, drotation + + +if __name__ == "__main__": + + space_mouse = SpaceMouse() + for i in range(100): + print(space_mouse.control, space_mouse.control_gripper) + time.sleep(0.02) diff --git a/third_party/robosuite/robosuite/environments/__init__.py b/third_party/robosuite/robosuite/environments/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fff6081f09064994187ac1154f62c57066bd455c --- /dev/null +++ b/third_party/robosuite/robosuite/environments/__init__.py @@ -0,0 +1,3 @@ +from .base import REGISTERED_ENVS, MujocoEnv + +ALL_ENVIRONMENTS = REGISTERED_ENVS.keys() diff --git a/third_party/robosuite/robosuite/environments/base.py b/third_party/robosuite/robosuite/environments/base.py new file mode 100644 index 0000000000000000000000000000000000000000..043f8f6ff130e34731de0462c99ed1cdf6f07f36 --- /dev/null +++ b/third_party/robosuite/robosuite/environments/base.py @@ -0,0 +1,806 @@ +import os +import xml.etree.ElementTree as ET +from collections import OrderedDict +from copy import deepcopy + +import numpy as np + +import robosuite +import robosuite.macros as macros +import robosuite.utils.sim_utils as SU +from robosuite.renderers.base import load_renderer_config +from robosuite.utils import OpenCVRenderer, SimulationError, XMLError +from robosuite.utils.binding_utils import MjRenderContextOffscreen, MjSim + +REGISTERED_ENVS = {} + + +def register_env(target_class): + REGISTERED_ENVS[target_class.__name__] = target_class + + +def make(env_name, *args, **kwargs): + """ + Instantiates a robosuite environment. + This method attempts to mirror the equivalent functionality of gym.make in a somewhat sloppy way. + Args: + env_name (str): Name of the robosuite environment to initialize + *args: Additional arguments to pass to the specific environment class initializer + **kwargs: Additional arguments to pass to the specific environment class initializer + Returns: + MujocoEnv: Desired robosuite environment + Raises: + Exception: [Invalid environment name] + """ + if env_name not in REGISTERED_ENVS: + raise Exception( + "Environment {} not found. Make sure it is a registered environment among: {}".format( + env_name, ", ".join(REGISTERED_ENVS) + ) + ) + return REGISTERED_ENVS[env_name](*args, **kwargs) + + +class EnvMeta(type): + """Metaclass for registering environments""" + + def __new__(meta, name, bases, class_dict): + cls = super().__new__(meta, name, bases, class_dict) + + # List all environments that should not be registered here. + _unregistered_envs = ["MujocoEnv", "RobotEnv", "ManipulationEnv", "TwoArmEnv"] + + if cls.__name__ not in _unregistered_envs: + register_env(cls) + return cls + + +class MujocoEnv(metaclass=EnvMeta): + """ + Initializes a Mujoco Environment. + Args: + has_renderer (bool): If true, render the simulation state in + a viewer instead of headless mode. + has_offscreen_renderer (bool): True if using off-screen rendering. + render_camera (str): Name of camera to render if `has_renderer` is True. Setting this value to 'None' + will result in the default angle being applied, which is useful as it can be dragged / panned by + the user using the mouse + render_collision_mesh (bool): True if rendering collision meshes + in camera. False otherwise. + render_visual_mesh (bool): True if rendering visual meshes + in camera. False otherwise. + render_gpu_device_id (int): corresponds to the GPU device id to use for offscreen rendering. + Defaults to -1, in which case the device will be inferred from environment variables + (GPUS or CUDA_VISIBLE_DEVICES). + control_freq (float): how many control signals to receive + in every simulated second. This sets the amount of simulation time + that passes between every action input. + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + horizon (int): Every episode lasts for exactly @horizon timesteps. + ignore_done (bool): True if never terminating the environment (ignore @horizon). + hard_reset (bool): If True, re-loads model, sim, and render object upon a reset call, else, + only calls sim.reset and resets all robosuite-internal variables + renderer (str): string for the renderer to use + renderer_config (dict): dictionary for the renderer configurations + seed (int): environment seed. Default is None, where environment is unseeded, ie. random + Raises: + ValueError: [Invalid renderer selection] + """ + + def __init__( + self, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + lite_physics=True, + horizon=1000, + ignore_done=False, + hard_reset=True, + renderer="mjviewer", + renderer_config=None, + seed=None, + ): + # Rendering-specific attributes + self.has_renderer = has_renderer + # offscreen renderer needed for on-screen rendering + self.has_offscreen_renderer = (has_renderer and renderer != "mjviewer") or has_offscreen_renderer + self.render_camera = render_camera + self.render_collision_mesh = render_collision_mesh + self.render_visual_mesh = render_visual_mesh + self.render_gpu_device_id = render_gpu_device_id + self.viewer = None + + # Simulation-specific attributes + self._observables = {} # Maps observable names to observable objects + self._obs_cache = {} # Maps observable names to pre-/partially-computed observable values + self.control_freq = control_freq + self.lite_physics = lite_physics + self.horizon = horizon + self.ignore_done = ignore_done + self.hard_reset = hard_reset + # Function to process model xml in _initialize_sim() call + # include edit_model_xml function by default + self._xml_processors = [self.edit_model_xml] + self.model = None + self.cur_time = None + self.model_timestep = None + self.control_timestep = None + self.deterministic_reset = False # Whether to add randomized resetting of objects / robot joints + + self.renderer = renderer + self.renderer_config = renderer_config + + self.seed = seed + self.rng = np.random.default_rng(seed) + + self._ep_meta = {} + + # Load the model + self._load_model() + + # Initialize the simulation + self._initialize_sim() + + # initializes the rendering + self.initialize_renderer() + + # the variables will be set later. + # need to set to None, in case these variables are referenced before being set + self.viewer = None + self.viewer_get_obs = None + + # Run all further internal (re-)initialization required + self._reset_internal() + + # Load observables + if hasattr(self.viewer, "_setup_observables"): + self._observables = self.viewer._setup_observables() + else: + self._observables = self._setup_observables() + + # check if viewer has get observations method and set a flag for future use. + self.viewer_get_obs = hasattr(self.viewer, "_get_observations") + + def initialize_renderer(self): + self.renderer = self.renderer.lower() + + if self.renderer_config is None and self.renderer != "mujoco": + self.renderer_config = load_renderer_config(self.renderer) + + if self.renderer == "mujoco": + pass + elif self.renderer == "mjviewer": + from robosuite.renderers.mjviewer.mjviewer_renderer import MjviewerRenderer + + if self.render_camera is not None: + camera_id = self.sim.model.camera_name2id(self.render_camera) + else: + camera_id = None + self.viewer = MjviewerRenderer(env=self, camera_id=camera_id, **self.renderer_config) + else: + raise ValueError( + f"{self.renderer} is not a valid renderer name. Valid options include mjviewer (native mujoco renderer), mujoco" + ) + + def initialize_time(self, control_freq): + """ + Initializes the time constants used for simulation. + Args: + control_freq (float): Hz rate to run control loop at within the simulation + """ + self.cur_time = 0 + self.model_timestep = macros.SIMULATION_TIMESTEP + if self.model_timestep <= 0: + raise ValueError("Invalid simulation timestep defined!") + self.control_freq = control_freq + if control_freq <= 0: + raise SimulationError("Control frequency {} is invalid".format(control_freq)) + self.control_timestep = 1.0 / control_freq + + def set_xml_processor(self, processor): + """ + Sets the processor function that xml string will be passed to inside _initialize_sim() calls. + Args: + processor (None or function): If set, processing method should take in a xml string and + return no arguments. + """ + self._xml_processors.append(processor) + + def _load_model(self): + """Loads an xml model, puts it in self.model""" + pass + + def _setup_references(self): + """ + Sets up references to important components. A reference is typically an + index or a list of indices that point to the corresponding elements + in a flatten array, which is how MuJoCo stores physical simulation data. + """ + # Setup mappings from model to IDs + self.model.generate_id_mappings(sim=self.sim) + + def _setup_observables(self): + """ + Sets up observables to be used for this environment. + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + return OrderedDict() + + def _initialize_sim(self, xml_string=None): + """ + Creates a MjSim object and stores it in self.sim. If @xml_string is specified, the MjSim object will be created + from the specified xml_string. Else, it will pull from self.model to instantiate the simulation + Args: + xml_string (str): If specified, creates MjSim object from this filepath + """ + xml = xml_string if xml_string else self.model.get_xml() + + # process the xml before initializing sim + for processor in self._xml_processors: + xml = processor(xml) + + # Create the simulation instance + self.sim = MjSim.from_xml_string(xml) + + # run a single step to make sure changes have propagated through sim state + self.sim.forward() + + # Setup sim time based on control frequency + self.initialize_time(self.control_freq) + + def reset(self): + """ + Resets simulation. + Returns: + OrderedDict: Environment observation space after reset occurs + """ + # TODO(yukez): investigate black screen of death + # Use hard reset if requested + + # always terminate mjviewer + if self.renderer == "mjviewer": + self._destroy_viewer() + + if self.hard_reset and not self.deterministic_reset: + if self.renderer == "mujoco": + self._destroy_viewer() + self._destroy_sim() + self._load_model() + self._initialize_sim() + # Else, we only reset the sim internally + else: + self.sim.reset() + + # Reset necessary robosuite-centric variables + self._reset_internal() + self.sim.forward() + # Setup observables, reloading if + self._obs_cache = {} + self._reset_observables() + + # Make sure that all sites are toggled OFF by default + self.visualize(vis_settings={vis: False for vis in self._visualizations}) + + # update sites as needed + self.update_state() + + if self.viewer is not None and self.renderer != "mujoco": + self.viewer.reset() + + observations = ( + self.viewer._get_observations(force_update=True) + if self.viewer_get_obs + else self._get_observations(force_update=True) + ) + + # Return new observations + return observations + + def _reset_observables(self): + if self.hard_reset: + # If we're using hard reset, must re-update sensor object references + if hasattr(self.viewer, "_setup_observables"): + _observables = self.viewer._setup_observables() + else: + _observables = self._setup_observables() + for obs_name, obs in _observables.items(): + self.modify_observable(observable_name=obs_name, attribute="sensor", modifier=obs._sensor) + + def _reset_internal(self): + """Resets simulation internal configurations.""" + + # create visualization screen or renderer + if self.has_renderer and self.viewer is None: + if self.renderer == "mujoco": + self.viewer = OpenCVRenderer(self.sim) + + # Set the camera angle for viewing + if self.render_camera is not None: + camera_id = self.sim.model.camera_name2id(self.render_camera) + self.viewer.set_camera(camera_id) + + elif self.renderer == "mjviewer": + self.initialize_renderer() + + if self.has_offscreen_renderer: + if self.sim._render_context_offscreen is None: + render_context = MjRenderContextOffscreen(self.sim, device_id=self.render_gpu_device_id) + self.sim._render_context_offscreen.vopt.geomgroup[0] = 1 if self.render_collision_mesh else 0 + self.sim._render_context_offscreen.vopt.geomgroup[1] = 1 if self.render_visual_mesh else 0 + + # additional housekeeping + self.sim_state_initial = self.sim.get_state() + self._setup_references() + self.cur_time = 0 + self.timestep = 0 + self.done = False + + # Empty observation cache and reset all observables + self._obs_cache = {} + for observable in self._observables.values(): + observable.reset() + + def get_ep_meta(self): + """ + Returns a dictionary containing episode metadata + Returns: + dict: episode metadata + """ + return deepcopy(self._ep_meta) + + def set_ep_meta(self, meta): + """ + Set episode meta data + Args: + meta (dict): containing episode metadata + """ + self._ep_meta = meta + + def unset_ep_meta(self): + """ + Unset episode meta data + """ + self._ep_meta = {} + + def _update_observables(self, force=False): + """ + Updates all observables in this environment + Args: + force (bool): If True, will force all the observables to update their internal values to the newest + value. This is useful if, e.g., you want to grab observations when directly setting simulation states + without actually stepping the simulation. + """ + for observable in self._observables.values(): + observable.update(timestep=self.model_timestep, obs_cache=self._obs_cache, force=force) + + def _get_observations(self, force_update=False): + """ + Grabs observations from the environment. + Args: + force_update (bool): If True, will force all the observables to update their internal values to the newest + value. This is useful if, e.g., you want to grab observations when directly setting simulation states + without actually stepping the simulation. + Returns: + OrderedDict: OrderedDict containing observations [(name_string, np.array), ...] + """ + observations = OrderedDict() + obs_by_modality = OrderedDict() + + # Force an update if requested + if force_update: + self._update_observables(force=True) + + # Loop through all observables and grab their current observation + for obs_name, observable in self._observables.items(): + if observable.is_enabled() and observable.is_active(): + obs = observable.obs + observations[obs_name] = obs + modality = observable.modality + "-state" + if modality not in obs_by_modality: + obs_by_modality[modality] = [] + # Make sure all observations are numpy arrays so we can concatenate them + array_obs = [obs] if type(obs) in {int, float} or not obs.shape else obs + obs_by_modality[modality].append(np.array(array_obs)) + + # Add in modality observations + for modality, obs in obs_by_modality.items(): + # To save memory, we only concatenate the image observations if explicitly requested + if modality == "image-state" and not macros.CONCATENATE_IMAGES: + continue + observations[modality] = np.concatenate(obs, axis=-1) + + return observations + + def step(self, action): + """ + Takes a step in simulation with control command @action. + Args: + action (np.array): Action to execute within the environment + Returns: + 4-tuple: + - (OrderedDict) observations from the environment + - (float) reward from the environment + - (bool) whether the current episode is completed or not + - (dict) misc information + Raises: + ValueError: [Steps past episode termination] + """ + if self.done: + raise ValueError("executing action in terminated episode") + + self.timestep += 1 + + # Since the env.step frequency is slower than the mjsim timestep frequency, the internal controller will output + # multiple torque commands in between new high level action commands. Therefore, we need to denote via + # 'policy_step' whether the current step we're taking is simply an internal update of the controller, + # or an actual policy update + policy_step = True + + # Loop through the simulation at the model timestep rate until we're ready to take the next policy step + # (as defined by the control frequency specified at the environment level) + for i in range(int(self.control_timestep / self.model_timestep)): + if self.lite_physics: + self.sim.step1() + else: + self.sim.forward() + self._pre_action(action, policy_step) + if self.lite_physics: + self.sim.step2() + else: + self.sim.step() + self._update_observables() + policy_step = False + + # Note: this is done all at once to avoid floating point inaccuracies + self.cur_time += self.control_timestep + + reward, done, info = self._post_action(action) + + if self.viewer is not None and self.renderer != "mujoco": + self.viewer.update() + elif self.has_renderer and self.renderer == "mjviewer" and self.viewer is None: + # need to launch again after it was destroyed + self.initialize_renderer() + # so that mujoco viewer renders + self.viewer.update() + + observations = self.viewer._get_observations() if self.viewer_get_obs else self._get_observations() + return observations, reward, done, info + + def _pre_action(self, action, policy_step=False): + """ + Do any preprocessing before taking an action. + Args: + action (np.array): Action to execute within the environment + policy_step (bool): Whether this current loop is an actual policy step or internal sim update step + """ + self.sim.data.ctrl[:] = action + + def _post_action(self, action): + """ + Do any housekeeping after taking an action. + Args: + action (np.array): Action to execute within the environment + Returns: + 3-tuple: + - (float) reward from the environment + - (bool) whether the current episode is completed or not + - (dict) empty dict to be filled with information by subclassed method + """ + reward = self.reward(action) + + # done if number of elapsed timesteps is greater than horizon + self.done = (self.timestep >= self.horizon) and not self.ignore_done + + return reward, self.done, {} + + def reward(self, action): + """ + Reward should be a function of state and action + Args: + action (np.array): Action to execute within the environment + Returns: + float: Reward from environment + """ + raise NotImplementedError + + def render(self): + """ + Renders to an on-screen window. + """ + self.viewer.render() + + def get_pixel_obs(self): + """ + Gets the pixel observations for the environment from the specified renderer + """ + self.viewer.get_pixel_obs() + + def close_renderer(self): + """ + Closes the renderer + """ + self.viewer.close() + + def observation_spec(self): + """ + Returns an observation as observation specification. + An alternative design is to return an OrderedDict where the keys + are the observation names and the values are the shapes of observations. + We leave this alternative implementation commented out, as we find the + current design is easier to use in practice. + Returns: + OrderedDict: Observations from the environment + """ + observation = self.viewer._get_observations() if self.viewer_get_obs else self._get_observations() + return observation + + def clear_objects(self, object_names): + """ + Clears objects with the name @object_names out of the task space. This is useful + for supporting task modes with single types of objects, as in + @self.single_object_mode without changing the model definition. + Args: + object_names (str or list of str): Name of object(s) to remove from the task workspace + """ + object_names = {object_names} if type(object_names) is str else set(object_names) + for obj in self.model.mujoco_objects: + if obj.name in object_names: + self.sim.data.set_joint_qpos(obj.joints[0], np.array((10, 10, 10, 1, 0, 0, 0))) + + def visualize(self, vis_settings): + """ + Do any needed visualization here + Args: + vis_settings (dict): Visualization keywords mapped to T/F, determining whether that specific + component should be visualized. Should have "env" keyword as well as any other relevant + options specified. + """ + # Set visuals for environment objects + for obj in self.model.mujoco_objects: + obj.set_sites_visibility(sim=self.sim, visible=vis_settings["env"]) + + def edit_model_xml(self, xml_str): + """ + This function edits the model xml with custom changes, including resolving relative paths, + applying changes retroactively to existing demonstration files, and other custom scripts. + Environment subclasses should modify this function to add environment-specific xml editing features. + Args: + xml_str (str): Mujoco sim demonstration XML file as string + Returns: + str: Edited xml file as string + """ + + path = os.path.split(robosuite.__file__)[0] + path_split = path.split("/") + + # replace mesh and texture file paths + tree = ET.fromstring(xml_str) + root = tree + asset = root.find("asset") + meshes = asset.findall("mesh") + textures = asset.findall("texture") + all_elements = meshes + textures + + for elem in all_elements: + old_path = elem.get("file") + if old_path is None: + continue + + old_path_split = old_path.split("/") + # maybe replace all paths to robosuite assets + check_lst = [loc for loc, val in enumerate(old_path_split) if val == "robosuite"] + if len(check_lst) > 0: + ind = max(check_lst) # last occurrence index + new_path_split = path_split + old_path_split[ind + 1 :] + new_path = "/".join(new_path_split) + elem.set("file", new_path) + + return ET.tostring(root, encoding="utf8").decode("utf8") + + def reset_from_xml_string(self, xml_string): + """ + Reloads the environment from an XML description of the environment. + Args: + xml_string (str): Filepath to the xml file that will be loaded directly into the sim + """ + + self.close() + + # Since we are reloading from an xml_string, we are deterministically resetting + self.deterministic_reset = True + + # initialize sim from xml + self._initialize_sim(xml_string=xml_string) + + # Now reset as normal + self.reset() + + # Turn off deterministic reset + self.deterministic_reset = False + + def update_state(self): + """ + update internal state of environment (can be called after resetting simulation or after step) + """ + pass + + def check_contact(self, geoms_1, geoms_2=None): + """ + Finds contact between two geom groups. + Args: + geoms_1 (str or list of str or MujocoModel): an individual geom name or list of geom names or a model. If + a MujocoModel is specified, the geoms checked will be its contact_geoms + geoms_2 (str or list of str or MujocoModel or None): another individual geom name or list of geom names. + If a MujocoModel is specified, the geoms checked will be its contact_geoms. If None, will check + any collision with @geoms_1 to any other geom in the environment + Returns: + bool: True if any geom in @geoms_1 is in contact with any geom in @geoms_2. + """ + return SU.check_contact(sim=self.sim, geoms_1=geoms_1, geoms_2=geoms_2) + + def get_contacts(self, model): + """ + Checks for any contacts with @model (as defined by @model's contact_geoms) and returns the set of + geom names currently in contact with that model (excluding the geoms that are part of the model itself). + Args: + model (MujocoModel): Model to check contacts for. + Returns: + set: Unique geoms that are actively in contact with this model. + Raises: + AssertionError: [Invalid input type] + """ + return SU.get_contacts(sim=self.sim, model=model) + + def add_observable(self, observable): + """ + Adds an observable to this environment. + Args: + observable (Observable): Observable instance. + """ + assert observable.name not in self._observables, ( + "Observable name {} is already associated with an existing observable! Use modify_observable(...) " + "to modify a pre-existing observable.".format(observable.name) + ) + self._observables[observable.name] = observable + + def modify_observable(self, observable_name, attribute, modifier): + """ + Modifies observable with associated name @observable_name, replacing the given @attribute with @modifier. + Args: + observable_name (str): Observable to modify + attribute (str): Observable attribute to modify. + Options are {`'sensor'`, `'corrupter'`,`'filter'`, `'delayer'`, `'sampling_rate'`, + `'enabled'`, `'active'`} + modifier (any): New function / value to replace with for observable. If a function, new signature should + match the function being replaced. + """ + # Find the observable + assert observable_name in self._observables, "No valid observable with name {} found. Options are: {}".format( + observable_name, self.observation_names + ) + obs = self._observables[observable_name] + # replace attribute accordingly + if attribute == "sensor": + obs.set_sensor(modifier) + elif attribute == "corrupter": + obs.set_corrupter(modifier) + elif attribute == "filter": + obs.set_filter(modifier) + elif attribute == "delayer": + obs.set_delayer(modifier) + elif attribute == "sampling_rate": + obs.set_sampling_rate(modifier) + elif attribute == "enabled": + obs.set_enabled(modifier) + elif attribute == "active": + obs.set_active(modifier) + else: + # Invalid attribute specified + raise ValueError( + "Invalid observable attribute specified. Requested: {}, valid options are {}".format( + attribute, {"sensor", "corrupter", "filter", "delayer", "sampling_rate", "enabled", "active"} + ) + ) + + def _check_success(self): + """ + Checks if the task has been completed. Should be implemented by subclasses + Returns: + bool: True if the task has been completed + """ + raise NotImplementedError + + def _destroy_viewer(self): + """ + Destroys the current mujoco renderer instance if it exists + """ + # if there is an active viewer window, destroy it + if self.viewer is not None: + self.viewer.close() # change this to viewer.finish()? + self.viewer = None + + def _destroy_sim(self): + """ + Destroys the current MjSim instance if it exists + """ + if self.sim is not None: + self.sim.free() + self.sim = None + + def close(self): + """Do any cleanup necessary here.""" + self._destroy_viewer() + self._destroy_sim() + + @property + def observation_modalities(self): + """ + Modalities for this environment's observations + Returns: + set: All observation modalities + """ + return set([observable.modality for observable in self._observables.values()]) + + @property + def observation_names(self): + """ + Grabs all names for this environment's observables + Returns: + set: All observation names + """ + return set(self._observables.keys()) + + @property + def enabled_observables(self): + """ + Grabs all names of enabled observables for this environment. An observable is considered enabled if its values + are being continually computed / updated at each simulation timestep. + Returns: + set: All enabled observation names + """ + return set([name for name, observable in self._observables.items() if observable.is_enabled()]) + + @property + def active_observables(self): + """ + Grabs all names of active observables for this environment. An observable is considered active if its value is + being returned in the observation dict from _get_observations() call or from the step() call (assuming this + observable is enabled). + Returns: + set: All active observation names + """ + return set([name for name, observable in self._observables.items() if observable.is_active()]) + + @property + def _visualizations(self): + """ + Visualization keywords for this environment + Returns: + set: All components that can be individually visualized for this environment + """ + return {"env"} + + @property + def action_spec(self): + """ + Action specification should be implemented in subclasses. + Action space is represented by a tuple of (low, high), which are two numpy + vectors that specify the min/max action limits per dimension. + """ + raise NotImplementedError + + @property + def action_dim(self): + """ + Size of the action space + Returns: + int: Action space dimension + """ + raise NotImplementedError diff --git a/third_party/robosuite/robosuite/environments/manipulation/__init__.py b/third_party/robosuite/robosuite/environments/manipulation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/third_party/robosuite/robosuite/environments/manipulation/__init__.py @@ -0,0 +1 @@ + diff --git a/third_party/robosuite/robosuite/environments/manipulation/door.py b/third_party/robosuite/robosuite/environments/manipulation/door.py new file mode 100644 index 0000000000000000000000000000000000000000..6d8dc189e2c1c9d0b334518eded79371dd7af519 --- /dev/null +++ b/third_party/robosuite/robosuite/environments/manipulation/door.py @@ -0,0 +1,466 @@ +from collections import OrderedDict + +import numpy as np + +from robosuite.environments.manipulation.manipulation_env import ManipulationEnv +from robosuite.models.arenas import TableArena +from robosuite.models.objects import DoorObject +from robosuite.models.tasks import ManipulationTask +from robosuite.utils.observables import Observable, sensor +from robosuite.utils.placement_samplers import UniformRandomSampler + + +class Door(ManipulationEnv): + """ + This class corresponds to the door opening task for a single robot arm. + + Args: + robots (str or list of str): Specification for specific robot arm(s) to be instantiated within this env + (e.g: "Sawyer" would generate one arm; ["Panda", "Panda", "Sawyer"] would generate three robot arms) + Note: Must be a single single-arm robot! + + env_configuration (str): Specifies how to position the robots within the environment (default is "default"). + For most single arm environments, this argument has no impact on the robot setup. + + controller_configs (str or list of dict): If set, contains relevant controller parameters for creating a + custom controller. Else, uses the default controller for this specific task. Should either be single + dict if same controller is to be used for all robots or else it should be a list of the same length as + "robots" param + + gripper_types (str or list of str): type of gripper, used to instantiate + gripper models from gripper factory. Default is "default", which is the default grippers(s) associated + with the robot(s) the 'robots' specification. None removes the gripper, and any other (valid) model + overrides the default gripper. Should either be single str if same gripper type is to be used for all + robots or else it should be a list of the same length as "robots" param + + initialization_noise (dict or list of dict): Dict containing the initialization noise parameters. + The expected keys and corresponding value types are specified below: + + :`'magnitude'`: The scale factor of uni-variate random noise applied to each of a robot's given initial + joint positions. Setting this value to `None` or 0.0 results in no noise being applied. + If "gaussian" type of noise is applied then this magnitude scales the standard deviation applied, + If "uniform" type of noise is applied then this magnitude sets the bounds of the sampling range + :`'type'`: Type of noise to apply. Can either specify "gaussian" or "uniform" + + Should either be single dict if same noise value is to be used for all robots or else it should be a + list of the same length as "robots" param + + :Note: Specifying "default" will automatically use the default noise settings. + Specifying None will automatically create the required dict with "magnitude" set to 0.0. + + use_latch (bool): if True, uses a spring-loaded handle and latch to "lock" the door closed initially + Otherwise, door is instantiated with a fixed handle + + use_camera_obs (bool): if True, every observation includes rendered image(s) + + use_object_obs (bool): if True, include object (cube) information in + the observation. + + reward_scale (None or float): Scales the normalized reward function by the amount specified. + If None, environment reward remains unnormalized + + reward_shaping (bool): if True, use dense rewards. + + placement_initializer (ObjectPositionSampler): if provided, will + be used to place objects on every reset, else a UniformRandomSampler + is used by default. + + has_renderer (bool): If true, render the simulation state in + a viewer instead of headless mode. + + has_offscreen_renderer (bool): True if using off-screen rendering + + render_camera (str): Name of camera to render if `has_renderer` is True. Setting this value to 'None' + will result in the default angle being applied, which is useful as it can be dragged / panned by + the user using the mouse + + render_collision_mesh (bool): True if rendering collision meshes in camera. False otherwise. + + render_visual_mesh (bool): True if rendering visual meshes in camera. False otherwise. + + render_gpu_device_id (int): corresponds to the GPU device id to use for offscreen rendering. + Defaults to -1, in which case the device will be inferred from environment variables + (GPUS or CUDA_VISIBLE_DEVICES). + + control_freq (float): how many control signals to receive in every second. This sets the amount of + simulation time that passes between every action input. + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + + horizon (int): Every episode lasts for exactly @horizon timesteps. + + ignore_done (bool): True if never terminating the environment (ignore @horizon). + + hard_reset (bool): If True, re-loads model, sim, and render object upon a reset call, else, + only calls sim.reset and resets all robosuite-internal variables + + camera_names (str or list of str): name of camera to be rendered. Should either be single str if + same name is to be used for all cameras' rendering or else it should be a list of cameras to render. + + :Note: At least one camera must be specified if @use_camera_obs is True. + + :Note: To render all robots' cameras of a certain type (e.g.: "robotview" or "eye_in_hand"), use the + convention "all-{name}" (e.g.: "all-robotview") to automatically render all camera images from each + robot's camera list). + + camera_heights (int or list of int): height of camera frame. Should either be single int if + same height is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_widths (int or list of int): width of camera frame. Should either be single int if + same width is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_depths (bool or list of bool): True if rendering RGB-D, and RGB otherwise. Should either be single + bool if same depth setting is to be used for all cameras or else it should be a list of the same length as + "camera names" param. + + camera_segmentations (None or str or list of str or list of list of str): Camera segmentation(s) to use + for each camera. Valid options are: + + `None`: no segmentation sensor used + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + + If not None, multiple types of segmentations can be specified. A [list of str / str or None] specifies + [multiple / a single] segmentation(s) to use for all cameras. A list of list of str specifies per-camera + segmentation setting(s) to use. + + Raises: + AssertionError: [Invalid number of robots specified] + """ + + def __init__( + self, + robots, + env_configuration="default", + controller_configs=None, + gripper_types="default", + initialization_noise="default", + use_latch=True, + use_camera_obs=True, + use_object_obs=True, + reward_scale=1.0, + reward_shaping=False, + placement_initializer=None, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + lite_physics=True, + horizon=1000, + ignore_done=False, + hard_reset=True, + camera_names="agentview", + camera_heights=256, + camera_widths=256, + camera_depths=False, + camera_segmentations=None, # {None, instance, class, element} + renderer="mjviewer", + renderer_config=None, + ): + # settings for table top (hardcoded since it's not an essential part of the environment) + self.table_full_size = (0.8, 0.3, 0.05) + self.table_offset = (-0.2, -0.35, 0.8) + + # reward configuration + self.use_latch = use_latch + self.reward_scale = reward_scale + self.reward_shaping = reward_shaping + + # whether to use ground-truth object states + self.use_object_obs = use_object_obs + + # object placement initializer + self.placement_initializer = placement_initializer + + super().__init__( + robots=robots, + env_configuration=env_configuration, + controller_configs=controller_configs, + base_types="default", + gripper_types=gripper_types, + initialization_noise=initialization_noise, + use_camera_obs=use_camera_obs, + has_renderer=has_renderer, + has_offscreen_renderer=has_offscreen_renderer, + render_camera=render_camera, + render_collision_mesh=render_collision_mesh, + render_visual_mesh=render_visual_mesh, + render_gpu_device_id=render_gpu_device_id, + control_freq=control_freq, + lite_physics=lite_physics, + horizon=horizon, + ignore_done=ignore_done, + hard_reset=hard_reset, + camera_names=camera_names, + camera_heights=camera_heights, + camera_widths=camera_widths, + camera_depths=camera_depths, + camera_segmentations=camera_segmentations, + renderer=renderer, + renderer_config=renderer_config, + ) + + def reward(self, action=None): + """ + Reward function for the task. + + Sparse un-normalized reward: + + - a discrete reward of 1.0 is provided if the door is opened + + Un-normalized summed components if using reward shaping: + + - Reaching: in [0, 0.25], proportional to the distance between door handle and robot arm + - Rotating: in [0, 0.25], proportional to angle rotated by door handled + - Note that this component is only relevant if the environment is using the locked door version + + Note that a successfully completed task (door opened) will return 1.0 irregardless of whether the environment + is using sparse or shaped rewards + + Note that the final reward is normalized and scaled by reward_scale / 1.0 as + well so that the max score is equal to reward_scale + + Args: + action (np.array): [NOT USED] + + Returns: + float: reward value + """ + reward = 0.0 + + # sparse completion reward + if self._check_success(): + reward = 1.0 + + # else, we consider only the case if we're using shaped rewards + elif self.reward_shaping: + # Add reaching component + dist = np.linalg.norm(self._gripper_to_handle) + reaching_reward = 0.25 * (1 - np.tanh(10.0 * dist)) + reward += reaching_reward + # Add rotating component if we're using a locked door + if self.use_latch: + handle_qpos = self.sim.data.qpos[self.handle_qpos_addr] + reward += np.clip(0.25 * np.abs(handle_qpos / (0.5 * np.pi)), -0.25, 0.25) + + # Scale reward if requested + if self.reward_scale is not None: + reward *= self.reward_scale / 1.0 + + return reward + + def _load_model(self): + """ + Loads an xml model, puts it in self.model + """ + super()._load_model() + + # Adjust base pose accordingly + xpos = self.robots[0].robot_model.base_xpos_offset["table"](self.table_full_size[0]) + self.robots[0].robot_model.set_base_xpos(xpos) + + # load model for table top workspace + mujoco_arena = TableArena( + table_full_size=self.table_full_size, + table_offset=self.table_offset, + ) + + # Arena always gets set to zero origin + mujoco_arena.set_origin([0, 0, 0]) + + # Modify default agentview camera + mujoco_arena.set_camera( + camera_name="agentview", + pos=[0.5986131746834771, -4.392035683362857e-09, 1.5903500240372423], + quat=[0.6380177736282349, 0.3048497438430786, 0.30484986305236816, 0.6380177736282349], + ) + + # initialize objects of interest + self.door = DoorObject( + name="Door", + friction=0.0, + damping=0.1, + lock=self.use_latch, + ) + + # Create placement initializer + if self.placement_initializer is not None: + self.placement_initializer.reset() + self.placement_initializer.add_objects(self.door) + else: + self.placement_initializer = UniformRandomSampler( + name="ObjectSampler", + mujoco_objects=self.door, + x_range=[0.07, 0.09], + y_range=[-0.01, 0.01], + rotation=(-np.pi / 2.0 - 0.25, -np.pi / 2.0), + rotation_axis="z", + ensure_object_boundary_in_range=False, + ensure_valid_placement=True, + reference_pos=self.table_offset, + ) + + # task includes arena, robot, and objects of interest + self.model = ManipulationTask( + mujoco_arena=mujoco_arena, + mujoco_robots=[robot.robot_model for robot in self.robots], + mujoco_objects=self.door, + ) + + def _setup_references(self): + """ + Sets up references to important components. A reference is typically an + index or a list of indices that point to the corresponding elements + in a flatten array, which is how MuJoCo stores physical simulation data. + """ + super()._setup_references() + + # Additional object references from this env + self.object_body_ids = dict() + self.object_body_ids["door"] = self.sim.model.body_name2id(self.door.door_body) + self.object_body_ids["frame"] = self.sim.model.body_name2id(self.door.frame_body) + self.object_body_ids["latch"] = self.sim.model.body_name2id(self.door.latch_body) + self.door_handle_site_id = self.sim.model.site_name2id(self.door.important_sites["handle"]) + self.hinge_qpos_addr = self.sim.model.get_joint_qpos_addr(self.door.joints[0]) + if self.use_latch: + self.handle_qpos_addr = self.sim.model.get_joint_qpos_addr(self.door.joints[1]) + + def _setup_observables(self): + """ + Sets up observables to be used for this environment. Creates object-based observables if enabled + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + observables = super()._setup_observables() + + # low-level object information + if self.use_object_obs: + modality = "object" + + # Define sensor callbacks + @sensor(modality=modality) + def door_pos(obs_cache): + return np.array(self.sim.data.body_xpos[self.object_body_ids["door"]]) + + @sensor(modality=modality) + def handle_pos(obs_cache): + return self._handle_xpos + + @sensor(modality=modality) + def hinge_qpos(obs_cache): + return np.array([self.sim.data.qpos[self.hinge_qpos_addr]]) + + arm_prefixes = self._get_arm_prefixes(self.robots[0], include_robot_name=False) + full_prefixes = self._get_arm_prefixes(self.robots[0]) + sensors = [door_pos, handle_pos, hinge_qpos] + + # create variable number of sensors for each arm representing distance from specified arm to handle/door + sensors += [ + self._get_obj_eef_sensor(full_pf, "door_pos", f"door_to_{arm_pf}eef_pos", modality) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + sensors += [ + self._get_obj_eef_sensor(full_pf, "handle_pos", f"handle_to_{arm_pf}eef_pos", modality) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + + names = [s.__name__ for s in sensors] + + # Also append handle qpos if we're using a locked door version with rotatable handle + if self.use_latch: + + @sensor(modality=modality) + def handle_qpos(obs_cache): + return np.array([self.sim.data.qpos[self.handle_qpos_addr]]) + + sensors.append(handle_qpos) + names.append("handle_qpos") + + # Create observables + for name, s in zip(names, sensors): + observables[name] = Observable( + name=name, + sensor=s, + sampling_rate=self.control_freq, + ) + + return observables + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + super()._reset_internal() + + # Reset all object positions using initializer sampler if we're not directly loading from an xml + if not self.deterministic_reset: + + # Sample from the placement initializer for all objects + object_placements = self.placement_initializer.sample() + + # We know we're only setting a single object (the door), so specifically set its pose + door_pos, door_quat, _ = object_placements[self.door.name] + door_body_id = self.sim.model.body_name2id(self.door.root_body) + self.sim.model.body_pos[door_body_id] = door_pos + self.sim.model.body_quat[door_body_id] = door_quat + + def _check_success(self): + """ + Check if door has been opened. + + Returns: + bool: True if door has been opened + """ + hinge_qpos = self.sim.data.qpos[self.hinge_qpos_addr] + return hinge_qpos > 0.3 + + def visualize(self, vis_settings): + """ + In addition to super call, visualize gripper site proportional to the distance to the door handle. + + Args: + vis_settings (dict): Visualization keywords mapped to T/F, determining whether that specific + component should be visualized. Should have "grippers" keyword as well as any other relevant + options specified. + """ + # Run superclass method first + super().visualize(vis_settings=vis_settings) + + # Color the gripper visualization site according to its distance to the door handle + if vis_settings["grippers"]: + self._visualize_gripper_to_target( + gripper=self.robots[0].gripper, target=self.door.important_sites["handle"], target_type="site" + ) + + @property + def _handle_xpos(self): + """ + Grabs the position of the door handle handle. + + Returns: + np.array: Door handle (x,y,z) + """ + return self.sim.data.site_xpos[self.door_handle_site_id] + + @property + def _gripper_to_handle(self): + """ + Calculates distance from the gripper to the door handle. + If multiple arms, returns the minimum distance. + + Returns: + np.array: (x,y,z) distance between handle and eef + """ + dists = [] + for arm in self.robots[0].arms: + diff = self._handle_xpos - np.array(self.sim.data.site_xpos[self.robots[0].eef_site_id[arm]]) + dists.append(np.linalg.norm(diff)) + return min(dists) diff --git a/third_party/robosuite/robosuite/environments/manipulation/lift.py b/third_party/robosuite/robosuite/environments/manipulation/lift.py new file mode 100644 index 0000000000000000000000000000000000000000..768161ae6083d20cf7794f2dd7dbda32dc646b78 --- /dev/null +++ b/third_party/robosuite/robosuite/environments/manipulation/lift.py @@ -0,0 +1,433 @@ +from collections import OrderedDict + +import numpy as np + +from robosuite.environments.manipulation.manipulation_env import ManipulationEnv +from robosuite.models.arenas import TableArena +from robosuite.models.objects import BoxObject +from robosuite.models.tasks import ManipulationTask +from robosuite.utils.mjcf_utils import CustomMaterial +from robosuite.utils.observables import Observable, sensor +from robosuite.utils.placement_samplers import UniformRandomSampler +from robosuite.utils.transform_utils import convert_quat + + +class Lift(ManipulationEnv): + """ + This class corresponds to the lifting task for a single robot arm. + + Args: + robots (str or list of str): Specification for specific robot arm(s) to be instantiated within this env + (e.g: "Sawyer" would generate one arm; ["Panda", "Panda", "Sawyer"] would generate three robot arms) + Note: Must be a single single-arm robot! + + env_configuration (str): Specifies how to position the robots within the environment (default is "default"). + For most single arm environments, this argument has no impact on the robot setup. + + controller_configs (str or list of dict): If set, contains relevant controller parameters for creating a + custom controller. Else, uses the default controller for this specific task. Should either be single + dict if same controller is to be used for all robots or else it should be a list of the same length as + "robots" param + + gripper_types (str or list of str): type of gripper, used to instantiate + gripper models from gripper factory. Default is "default", which is the default grippers(s) associated + with the robot(s) the 'robots' specification. None removes the gripper, and any other (valid) model + overrides the default gripper. Should either be single str if same gripper type is to be used for all + robots or else it should be a list of the same length as "robots" param + + initialization_noise (dict or list of dict): Dict containing the initialization noise parameters. + The expected keys and corresponding value types are specified below: + + :`'magnitude'`: The scale factor of uni-variate random noise applied to each of a robot's given initial + joint positions. Setting this value to `None` or 0.0 results in no noise being applied. + If "gaussian" type of noise is applied then this magnitude scales the standard deviation applied, + If "uniform" type of noise is applied then this magnitude sets the bounds of the sampling range + :`'type'`: Type of noise to apply. Can either specify "gaussian" or "uniform" + + Should either be single dict if same noise value is to be used for all robots or else it should be a + list of the same length as "robots" param + + :Note: Specifying "default" will automatically use the default noise settings. + Specifying None will automatically create the required dict with "magnitude" set to 0.0. + + table_full_size (3-tuple): x, y, and z dimensions of the table. + + table_friction (3-tuple): the three mujoco friction parameters for + the table. + + use_camera_obs (bool): if True, every observation includes rendered image(s) + + use_object_obs (bool): if True, include object (cube) information in + the observation. + + reward_scale (None or float): Scales the normalized reward function by the amount specified. + If None, environment reward remains unnormalized + + reward_shaping (bool): if True, use dense rewards. + + placement_initializer (ObjectPositionSampler): if provided, will + be used to place objects on every reset, else a UniformRandomSampler + is used by default. + + has_renderer (bool): If true, render the simulation state in + a viewer instead of headless mode. + + has_offscreen_renderer (bool): True if using off-screen rendering + + render_camera (str): Name of camera to render if `has_renderer` is True. Setting this value to 'None' + will result in the default angle being applied, which is useful as it can be dragged / panned by + the user using the mouse + + render_collision_mesh (bool): True if rendering collision meshes in camera. False otherwise. + + render_visual_mesh (bool): True if rendering visual meshes in camera. False otherwise. + + render_gpu_device_id (int): corresponds to the GPU device id to use for offscreen rendering. + Defaults to -1, in which case the device will be inferred from environment variables + (GPUS or CUDA_VISIBLE_DEVICES). + + control_freq (float): how many control signals to receive in every second. This sets the amount of + simulation time that passes between every action input. + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + + horizon (int): Every episode lasts for exactly @horizon timesteps. + + ignore_done (bool): True if never terminating the environment (ignore @horizon). + + hard_reset (bool): If True, re-loads model, sim, and render object upon a reset call, else, + only calls sim.reset and resets all robosuite-internal variables + + camera_names (str or list of str): name of camera to be rendered. Should either be single str if + same name is to be used for all cameras' rendering or else it should be a list of cameras to render. + + :Note: At least one camera must be specified if @use_camera_obs is True. + + :Note: To render all robots' cameras of a certain type (e.g.: "robotview" or "eye_in_hand"), use the + convention "all-{name}" (e.g.: "all-robotview") to automatically render all camera images from each + robot's camera list). + + camera_heights (int or list of int): height of camera frame. Should either be single int if + same height is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_widths (int or list of int): width of camera frame. Should either be single int if + same width is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_depths (bool or list of bool): True if rendering RGB-D, and RGB otherwise. Should either be single + bool if same depth setting is to be used for all cameras or else it should be a list of the same length as + "camera names" param. + + camera_segmentations (None or str or list of str or list of list of str): Camera segmentation(s) to use + for each camera. Valid options are: + + `None`: no segmentation sensor used + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + + If not None, multiple types of segmentations can be specified. A [list of str / str or None] specifies + [multiple / a single] segmentation(s) to use for all cameras. A list of list of str specifies per-camera + segmentation setting(s) to use. + + Raises: + AssertionError: [Invalid number of robots specified] + """ + + def __init__( + self, + robots, + env_configuration="default", + controller_configs=None, + gripper_types="default", + initialization_noise="default", + table_full_size=(0.8, 0.8, 0.05), + table_friction=(1.0, 5e-3, 1e-4), + use_camera_obs=True, + use_object_obs=True, + reward_scale=1.0, + reward_shaping=False, + placement_initializer=None, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + lite_physics=True, + horizon=1000, + ignore_done=False, + hard_reset=True, + camera_names="agentview", + camera_heights=256, + camera_widths=256, + camera_depths=False, + camera_segmentations=None, # {None, instance, class, element} + renderer="mjviewer", + renderer_config=None, + ): + # settings for table top + self.table_full_size = table_full_size + self.table_friction = table_friction + self.table_offset = np.array((0, 0, 0.8)) + + # reward configuration + self.reward_scale = reward_scale + self.reward_shaping = reward_shaping + + # whether to use ground-truth object states + self.use_object_obs = use_object_obs + + # object placement initializer + self.placement_initializer = placement_initializer + + super().__init__( + robots=robots, + env_configuration=env_configuration, + controller_configs=controller_configs, + base_types="default", + gripper_types=gripper_types, + initialization_noise=initialization_noise, + use_camera_obs=use_camera_obs, + has_renderer=has_renderer, + has_offscreen_renderer=has_offscreen_renderer, + render_camera=render_camera, + render_collision_mesh=render_collision_mesh, + render_visual_mesh=render_visual_mesh, + render_gpu_device_id=render_gpu_device_id, + control_freq=control_freq, + lite_physics=lite_physics, + horizon=horizon, + ignore_done=ignore_done, + hard_reset=hard_reset, + camera_names=camera_names, + camera_heights=camera_heights, + camera_widths=camera_widths, + camera_depths=camera_depths, + camera_segmentations=camera_segmentations, + renderer=renderer, + renderer_config=renderer_config, + ) + + def reward(self, action=None): + """ + Reward function for the task. + + Sparse un-normalized reward: + + - a discrete reward of 2.25 is provided if the cube is lifted + + Un-normalized summed components if using reward shaping: + + - Reaching: in [0, 1], to encourage the arm to reach the cube + - Grasping: in {0, 0.25}, non-zero if arm is grasping the cube + - Lifting: in {0, 1}, non-zero if arm has lifted the cube + + The sparse reward only consists of the lifting component. + + Note that the final reward is normalized and scaled by + reward_scale / 2.25 as well so that the max score is equal to reward_scale + + Args: + action (np array): [NOT USED] + + Returns: + float: reward value + """ + reward = 0.0 + + # sparse completion reward + if self._check_success(): + reward = 2.25 + + # use a shaping reward + elif self.reward_shaping: + + # reaching reward + dist = self._gripper_to_target( + gripper=self.robots[0].gripper, target=self.cube.root_body, target_type="body", return_distance=True + ) + reaching_reward = 1 - np.tanh(10.0 * dist) + reward += reaching_reward + + # grasping reward + if self._check_grasp(gripper=self.robots[0].gripper, object_geoms=self.cube): + reward += 0.25 + + # Scale reward if requested + if self.reward_scale is not None: + reward *= self.reward_scale / 2.25 + + return reward + + def _load_model(self): + """ + Loads an xml model, puts it in self.model + """ + super()._load_model() + + # Adjust base pose accordingly + xpos = self.robots[0].robot_model.base_xpos_offset["table"](self.table_full_size[0]) + self.robots[0].robot_model.set_base_xpos(xpos) + + # load model for table top workspace + mujoco_arena = TableArena( + table_full_size=self.table_full_size, + table_friction=self.table_friction, + table_offset=self.table_offset, + ) + + # Arena always gets set to zero origin + mujoco_arena.set_origin([0, 0, 0]) + + # initialize objects of interest + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "1 1", + "specular": "0.4", + "shininess": "0.1", + } + redwood = CustomMaterial( + texture="WoodRed", + tex_name="redwood", + mat_name="redwood_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.cube = BoxObject( + name="cube", + size_min=[0.020, 0.020, 0.020], # [0.015, 0.015, 0.015], + size_max=[0.022, 0.022, 0.022], # [0.018, 0.018, 0.018]) + rgba=[1, 0, 0, 1], + material=redwood, + ) + + # Create placement initializer + if self.placement_initializer is not None: + self.placement_initializer.reset() + self.placement_initializer.add_objects(self.cube) + else: + self.placement_initializer = UniformRandomSampler( + name="ObjectSampler", + mujoco_objects=self.cube, + x_range=[-0.03, 0.03], + y_range=[-0.03, 0.03], + rotation=None, + ensure_object_boundary_in_range=False, + ensure_valid_placement=True, + reference_pos=self.table_offset, + z_offset=0.01, + ) + + # task includes arena, robot, and objects of interest + self.model = ManipulationTask( + mujoco_arena=mujoco_arena, + mujoco_robots=[robot.robot_model for robot in self.robots], + mujoco_objects=self.cube, + ) + + def _setup_references(self): + """ + Sets up references to important components. A reference is typically an + index or a list of indices that point to the corresponding elements + in a flatten array, which is how MuJoCo stores physical simulation data. + """ + super()._setup_references() + + # Additional object references from this env + self.cube_body_id = self.sim.model.body_name2id(self.cube.root_body) + + def _setup_observables(self): + """ + Sets up observables to be used for this environment. Creates object-based observables if enabled + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + observables = super()._setup_observables() + + # low-level object information + if self.use_object_obs: + # define observables modality + modality = "object" + + # cube-related observables + @sensor(modality=modality) + def cube_pos(obs_cache): + return np.array(self.sim.data.body_xpos[self.cube_body_id]) + + @sensor(modality=modality) + def cube_quat(obs_cache): + return convert_quat(np.array(self.sim.data.body_xquat[self.cube_body_id]), to="xyzw") + + sensors = [cube_pos, cube_quat] + + arm_prefixes = self._get_arm_prefixes(self.robots[0], include_robot_name=False) + full_prefixes = self._get_arm_prefixes(self.robots[0]) + + # gripper to cube position sensor; one for each arm + sensors += [ + self._get_obj_eef_sensor(full_pf, "cube_pos", f"{arm_pf}gripper_to_cube_pos", modality) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + names = [s.__name__ for s in sensors] + + # Create observables + for name, s in zip(names, sensors): + observables[name] = Observable( + name=name, + sensor=s, + sampling_rate=self.control_freq, + ) + + return observables + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + super()._reset_internal() + + # Reset all object positions using initializer sampler if we're not directly loading from an xml + if not self.deterministic_reset: + + # Sample from the placement initializer for all objects + object_placements = self.placement_initializer.sample() + + # Loop through all objects and reset their positions + for obj_pos, obj_quat, obj in object_placements.values(): + self.sim.data.set_joint_qpos(obj.joints[0], np.concatenate([np.array(obj_pos), np.array(obj_quat)])) + + def visualize(self, vis_settings): + """ + In addition to super call, visualize gripper site proportional to the distance to the cube. + + Args: + vis_settings (dict): Visualization keywords mapped to T/F, determining whether that specific + component should be visualized. Should have "grippers" keyword as well as any other relevant + options specified. + """ + # Run superclass method first + super().visualize(vis_settings=vis_settings) + + # Color the gripper visualization site according to its distance to the cube + if vis_settings["grippers"]: + self._visualize_gripper_to_target(gripper=self.robots[0].gripper, target=self.cube) + + def _check_success(self): + """ + Check if cube has been lifted. + + Returns: + bool: True if cube has been lifted + """ + cube_height = self.sim.data.body_xpos[self.cube_body_id][2] + table_height = self.model.mujoco_arena.table_offset[2] + + # cube is higher than the table top above a margin + return cube_height > table_height + 0.04 diff --git a/third_party/robosuite/robosuite/environments/manipulation/manipulation_env.py b/third_party/robosuite/robosuite/environments/manipulation/manipulation_env.py new file mode 100644 index 0000000000000000000000000000000000000000..1559cd6a83a92f81f0e71c45414b5449f05d3829 --- /dev/null +++ b/third_party/robosuite/robosuite/environments/manipulation/manipulation_env.py @@ -0,0 +1,491 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.environments.robot_env import RobotEnv +from robosuite.models.base import MujocoModel +from robosuite.models.grippers import GripperModel +from robosuite.robots import ROBOT_CLASS_MAPPING, FixedBaseRobot, MobileRobot +from robosuite.robots.legged_robot import LeggedRobot +from robosuite.utils.observables import Observable, sensor + + +class ManipulationEnv(RobotEnv): + """ + Initializes a manipulation-specific robot environment in Mujoco. + + Args: + robots: Specification for specific robot arm(s) to be instantiated within this env + (e.g: "Sawyer" would generate one arm; ["Panda", "Panda", "Sawyer"] would generate three robot arms) + + env_configuration (str): Specifies how to position the robot(s) within the environment. Default is "default", + which should be interpreted accordingly by any subclasses. + + controller_configs (str or list of dict): If set, contains relevant controller parameters for creating a + custom controller. Else, uses the default controller for this specific task. Should either be single + dict if same controller is to be used for all robots or else it should be a list of the same length as + "robots" param + + base_types (None or str or list of str): type of base, used to instantiate base models from base factory. + Default is "default", which is the default base associated with the robot(s) the 'robots' specification. + None results in no base, and any other (valid) model overrides the default base. Should either be + single str if same base type is to be used for all robots or else it should be a list of the same + length as "robots" param + + gripper_types (None or str or list of str): type of gripper, used to instantiate + gripper models from gripper factory. Default is "default", which is the default grippers(s) associated + with the robot(s) the 'robots' specification. None removes the gripper, and any other (valid) model + overrides the default gripper. Should either be single str if same gripper type is to be used for all + robots or else it should be a list of the same length as "robots" param + + initialization_noise (dict or list of dict): Dict containing the initialization noise parameters. + The expected keys and corresponding value types are specified below: + + :`'magnitude'`: The scale factor of uni-variate random noise applied to each of a robot's given initial + joint positions. Setting this value to `None` or 0.0 results in no noise being applied. + If "gaussian" type of noise is applied then this magnitude scales the standard deviation applied, + If "uniform" type of noise is applied then this magnitude sets the bounds of the sampling range + :`'type'`: Type of noise to apply. Can either specify "gaussian" or "uniform" + + Should either be single dict if same noise value is to be used for all robots or else it should be a + list of the same length as "robots" param + + :Note: Specifying "default" will automatically use the default noise settings. + Specifying None will automatically create the required dict with "magnitude" set to 0.0. + + use_camera_obs (bool): if True, every observation includes rendered image(s) + + has_renderer (bool): If true, render the simulation state in + a viewer instead of headless mode. + + has_offscreen_renderer (bool): True if using off-screen rendering + + render_camera (str): Name of camera to render if `has_renderer` is True. Setting this value to 'None' + will result in the default angle being applied, which is useful as it can be dragged / panned by + the user using the mouse + + render_collision_mesh (bool): True if rendering collision meshes in camera. False otherwise. + + render_visual_mesh (bool): True if rendering visual meshes in camera. False otherwise. + + render_gpu_device_id (int): corresponds to the GPU device id to use for offscreen rendering. + Defaults to -1, in which case the device will be inferred from environment variables + (GPUS or CUDA_VISIBLE_DEVICES). + + control_freq (float): how many control signals to receive in every second. This sets the abase of + simulation time that passes between every action input. + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + + horizon (int): Every episode lasts for exactly @horizon timesteps. + + ignore_done (bool): True if never terminating the environment (ignore @horizon). + + hard_reset (bool): If True, re-loads model, sim, and render object upon a reset call, else, + only calls sim.reset and resets all robosuite-internal variables + + camera_names (str or list of str): name of camera to be rendered. Should either be single str if + same name is to be used for all cameras' rendering or else it should be a list of cameras to render. + + :Note: At least one camera must be specified if @use_camera_obs is True. + + :Note: To render all robots' cameras of a certain type (e.g.: "robotview" or "eye_in_hand"), use the + convention "all-{name}" (e.g.: "all-robotview") to automatically render all camera images from each + robot's camera list). + + camera_heights (int or list of int): height of camera frame. Should either be single int if + same height is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_widths (int or list of int): width of camera frame. Should either be single int if + same width is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_depths (bool or list of bool): True if rendering RGB-D, and RGB otherwise. Should either be single + bool if same depth setting is to be used for all cameras or else it should be a list of the same length as + "camera names" param. + + camera_segmentations (None or str or list of str or list of list of str): Camera segmentation(s) to use + for each camera. Valid options are: + + `None`: no segmentation sensor used + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + + If not None, multiple types of segmentations can be specified. A [list of str / str or None] specifies + [multiple / a single] segmentation(s) to use for all cameras. A list of list of str specifies per-camera + segmentation setting(s) to use. + + seed (int): environment seed. Default is None, where environment is unseeded, ie. random + + Raises: + ValueError: [Camera obs require offscreen renderer] + ValueError: [Camera name must be specified to use camera obs] + """ + + def __init__( + self, + robots, + env_configuration="default", + controller_configs=None, + base_types="default", + gripper_types="default", + initialization_noise=None, + use_camera_obs=True, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + lite_physics=True, + horizon=1000, + ignore_done=False, + hard_reset=True, + camera_names="agentview", + camera_heights=256, + camera_widths=256, + camera_depths=False, + camera_segmentations=None, + renderer="mjviewer", + renderer_config=None, + seed=None, + ): + # Robot info + robots = list(robots) if type(robots) is list or type(robots) is tuple else [robots] + num_robots = len(robots) + + # Gripper + gripper_types = self._input2list(gripper_types, num_robots) + + # Robot configurations to pass to super call + robot_configs = [ + { + "gripper_type": gripper_types[idx], + } + for idx in range(num_robots) + ] + + # Run superclass init + super().__init__( + robots=robots, + env_configuration=env_configuration, + controller_configs=controller_configs, + base_types=base_types, + initialization_noise=initialization_noise, + use_camera_obs=use_camera_obs, + has_renderer=has_renderer, + has_offscreen_renderer=has_offscreen_renderer, + render_camera=render_camera, + render_collision_mesh=render_collision_mesh, + render_visual_mesh=render_visual_mesh, + render_gpu_device_id=render_gpu_device_id, + control_freq=control_freq, + lite_physics=lite_physics, + horizon=horizon, + ignore_done=ignore_done, + hard_reset=hard_reset, + camera_names=camera_names, + camera_heights=camera_heights, + camera_widths=camera_widths, + camera_depths=camera_depths, + camera_segmentations=camera_segmentations, + robot_configs=robot_configs, + renderer=renderer, + renderer_config=renderer_config, + seed=seed, + ) + + @property + def _visualizations(self): + """ + Visualization keywords for this environment + + Returns: + set: All components that can be individually visualized for this environment + """ + vis_set = super()._visualizations + vis_set.add("grippers") + return vis_set + + def _get_obj_eef_sensor(self, prefix, obj_key, fn_name, modality): + """ + Creates a sensor function that returns the relative position between the object specified by @obj_key + and the end effector specified by @prefix. + + Args: + prefix (str): Prefix for the arm to which the end effector belongs + obj_key (str): Key to access the object's position in the observation cache + fn_name (str): Name to assign to the sensor function + modality (str): Modality for the sensor + + Returns: + function: Sensor function that returns the relative position between the object and the end effector + """ + + @sensor(modality) + def sensor_fn(obs_cache): + return ( + obs_cache[obj_key] - obs_cache[f"{prefix}eef_pos"] + if obj_key in obs_cache and f"{prefix}eef_pos" in obs_cache + else np.zeros(3) + ) + + sensor_fn.__name__ = fn_name + return sensor_fn + + def _get_world_pose_in_gripper_sensor(self, prefix, fn_name, modality): + """ + Creates a sensor function that returns the inverse pose of the gripper. + + Args: + prefix (str): Prefix for the arm to which the gripper belongs + fn_name (str): Name to assign to the sensor function + modality (str): Modality for the sensor + + Returns: + function: Sensor function that returns the relative pose between the world and the gripper + """ + + @sensor(modality=modality) + def fn(obs_cache): + return ( + T.pose_inv(T.pose2mat((obs_cache[f"{prefix}eef_pos"], obs_cache[f"{prefix}eef_quat"]))) + if f"{prefix}eef_pos" in obs_cache and f"{prefix}eef_quat" in obs_cache + else np.eye(4) + ) + + fn.__name__ = fn_name + return fn + + def _get_rel_obj_eef_sensor(self, prefix, obj_key, fn_name, new_key_prefix, modality): + """ + Creates a sensor function that returns the relative position between the object specified by @obj_key + and populates the observation cache with relative quaternion. This sensor function uses the robots + gripper's inverse pose which should be in the observation cache. + + + Args: + prefix (str): Prefix used to access the robot arm's inverse pose in the observation cache + obj_key (str): Key to access the object's position/quaternion in the observation cache + fn_name (str): Name to assign to the sensor function + new_key_prefix (str): Prefix to use for the new key in the observation cache + modality (str): Modality for the sensor + + Returns: + function: Sensor function that returns the relative position between the object and the end effector + """ + + @sensor(modality=modality) + def fn(obs_cache): + # Immediately return default value if cache is empty + if any( + [ + name not in obs_cache + for name in [f"{obj_key}_pos", f"{obj_key}_quat", f"world_pose_in_{prefix}gripper"] + ] + ): + return np.zeros(3) + obj_pose = T.pose2mat((obs_cache[f"{obj_key}_pos"], obs_cache[f"{obj_key}_quat"])) + rel_pose = T.pose_in_A_to_pose_in_B(obj_pose, obs_cache[f"world_pose_in_{prefix}gripper"]) + rel_pos, rel_quat = T.mat2pose(rel_pose) + obs_cache[f"{obj_key}_to_{new_key_prefix}eef_quat"] = rel_quat + return rel_pos + + fn.__name__ = fn_name + return fn + + def _get_obj_eef_rel_quat_sensor(self, prefix, obj_key, fn_name, modality): + """ + Creates a sensor function that returns the relative quaternion between the object specified by @obj_key + and the end effector specified by @prefix. + + Args: + prefix (str): Prefix for the arm to which the end effector belongs + obj_key (str): Key to access the object's quaternion in the observation cache + fn_name (str): Name to assign to the sensor function + modality (str): Modality for the sensor + + Returns: + function: Sensor function that returns the relative quaternion between the object and the end effector + """ + + @sensor(modality) + def sensor_fn(obs_cache): + return ( + obs_cache[f"{obj_key}_to_{prefix}eef_quat"] + if f"{obj_key}_to_{prefix}eef_quat" in obs_cache + else np.zeros(4) + ) + + sensor_fn.__name__ = fn_name + return sensor_fn + + def _check_grasp(self, gripper, object_geoms): + """ + Checks whether the specified gripper as defined by @gripper is grasping the specified object in the environment. + If multiple grippers are specified, will return True if at least one gripper is grasping the object. + + By default, this will return True if at least one geom in both the "left_fingerpad" and "right_fingerpad" geom + groups are in contact with any geom specified by @object_geoms. Custom gripper geom groups can be + specified with @gripper as well. + + Args: + gripper (GripperModel or str or list of str or list of list of str or dict): If a MujocoModel, this is specific + gripper to check for grasping (as defined by "left_fingerpad" and "right_fingerpad" geom groups). Otherwise, + this sets custom gripper geom groups which together define a grasp. This can be a string + (one group of single gripper geom), a list of string (multiple groups of single gripper geoms) or a + list of list of string (multiple groups of multiple gripper geoms), or a dictionary in the case + where the robot has multiple arms/grippers. At least one geom from each group must be in contact + with any geom in @object_geoms for this method to return True. + object_geoms (str or list of str or MujocoModel): If a MujocoModel is inputted, will check for any + collisions with the model's contact_geoms. Otherwise, this should be specific geom name(s) composing + the object to check for contact. + + Returns: + bool: True if the gripper is grasping the given object + """ + # Convert object, gripper geoms into standardized form + if isinstance(object_geoms, MujocoModel): + o_geoms = object_geoms.contact_geoms + else: + o_geoms = [object_geoms] if type(object_geoms) is str else object_geoms + + if isinstance(gripper, GripperModel): + g_geoms = [gripper.important_geoms["left_fingerpad"], gripper.important_geoms["right_fingerpad"]] + elif type(gripper) is str: + g_geoms = [[gripper]] + elif isinstance(gripper, dict): + assert all([isinstance(gripper[arm], GripperModel) for arm in gripper]), "Invalid gripper dict format!" + return any([self._check_grasp(gripper[arm], object_geoms) for arm in gripper]) + else: + # Parse each element in the gripper_geoms list accordingly + g_geoms = [[g_group] if type(g_group) is str else g_group for g_group in gripper] + + # Search for collisions between each gripper geom group and the object geoms group + for g_group in g_geoms: + if not self.check_contact(g_group, o_geoms): + return False + return True + + def _gripper_to_target(self, gripper, target, target_type="body", return_distance=False): + """ + Calculates the (x,y,z) Cartesian distance (target_pos - gripper_pos) from the specified @gripper to the + specified @target. If @return_distance is set, will return the Euclidean (scalar) distance instead. + If the @gripper is a dict, will return the minimum distance across all grippers. + + Args: + gripper (MujocoModel or dict): Gripper model to update grip site rgb + target (MujocoModel or str): Either a site / geom / body name, or a model that serves as the target. + If a model is given, then the root body will be used as the target. + target_type (str): One of {"body", "geom", or "site"}, corresponding to the type of element @target + refers to. + return_distance (bool): If set, will return Euclidean distance instead of Cartesian distance + + Returns: + np.array or float: (Cartesian or Euclidean) distance from gripper to target + """ + if isinstance(gripper, dict): + assert all([isinstance(gripper[arm], GripperModel) for arm in gripper]), "Invalid gripper dict format!" + # get the min distance to the target if there are multiple arms + if return_distance: + return min( + [self._gripper_to_target(gripper[arm], target, target_type, return_distance) for arm in gripper] + ) + else: + return min( + [self._gripper_to_target(gripper[arm], target, target_type, return_distance) for arm in gripper], + key=lambda x: np.linalg.norm(x), + ) + + # Get gripper and target positions + gripper_pos = self.sim.data.get_site_xpos(gripper.important_sites["grip_site"]) + # If target is MujocoModel, grab the correct body as the target and find the target position + if isinstance(target, MujocoModel): + target_pos = self.sim.data.get_body_xpos(target.root_body) + elif target_type == "body": + target_pos = self.sim.data.get_body_xpos(target) + elif target_type == "site": + target_pos = self.sim.data.get_site_xpos(target) + else: + target_pos = self.sim.data.get_geom_xpos(target) + # Calculate distance + diff = target_pos - gripper_pos + # Return appropriate value + return np.linalg.norm(diff) if return_distance else diff + + def _visualize_gripper_to_target(self, gripper, target, target_type="body"): + """ + Colors the grip visualization site proportional to the Euclidean distance to the specified @target. + Colors go from red --> green as the gripper gets closer. If a dict of grippers is given, will visualize + all grippers to the target. + + Args: + gripper (MujocoModel or dict): Gripper model to update grip site rgb + target (MujocoModel or str): Either a site / geom / body name, or a model that serves as the target. + If a model is given, then the root body will be used as the target. + target_type (str): One of {"body", "geom", or "site"}, corresponding to the type of element @target + refers to. + """ + if isinstance(gripper, dict): + assert all([isinstance(gripper[arm], GripperModel) for arm in gripper]), "Invalid gripper dict format!" + for arm in gripper: + self._visualize_gripper_to_target(gripper[arm], target, target_type) + return + # Get gripper and target positions + gripper_pos = self.sim.data.get_site_xpos(gripper.important_sites["grip_site"]) + # If target is MujocoModel, grab the correct body as the target and find the target position + if isinstance(target, MujocoModel): + target_pos = self.sim.data.get_body_xpos(target.root_body) + elif target_type == "body": + target_pos = self.sim.data.get_body_xpos(target) + elif target_type == "site": + target_pos = self.sim.data.get_site_xpos(target) + else: + target_pos = self.sim.data.get_geom_xpos(target) + # color the gripper site appropriately based on (squared) distance to target + dist = np.sum(np.square((target_pos - gripper_pos))) + max_dist = 0.1 + scaled = (1.0 - min(dist / max_dist, 1.0)) ** 15 + rgba = np.zeros(3) + rgba[0] = 1 - scaled + rgba[1] = scaled + self.sim.model.site_rgba[self.sim.model.site_name2id(gripper.important_sites["grip_site"])][:3] = rgba + + def _get_arm_prefixes(self, robot, include_robot_name=True): + """ + Returns the naming prefixes for the robot arms in the environment used to access proprioceptive information. + By convention, if there is only one arm, it does not include the arm name. Otherwise, returns + a list of prefixes for each arm containing the robot's naming prefix (if include_robot_name is set) and the arm name. + + Args: + robot (RobotModel): Robot model to extract prefixes from + + Returns: + list: List of prefixes for the robot arms + """ + + name_pf = robot.robot_model.naming_prefix if include_robot_name else "" + if len(robot.arms) == 1: + return [name_pf] + + prefixes = [f"{name_pf}{arm}_" for arm in robot.arms] + return prefixes + + def _check_robot_configuration(self, robots): + """ + Sanity check to make sure inputted robots and the corresponding requested task/configuration combo is legal. + Should be implemented in every specific task module + + Args: + robots (str or list of str): Inputted requested robots at the task-level environment + """ + # Make sure all inputted robots are a manipulation robot + if type(robots) is str: + robots = [robots] + for robot in robots: + assert issubclass(ROBOT_CLASS_MAPPING[robot], FixedBaseRobot) or issubclass( + ROBOT_CLASS_MAPPING[robot], MobileRobot or issubclass(ROBOT_CLASS_MAPPING[robot], LeggedRobot) + ), f"Only manipulator robots supported for manipulation environment! Got {ROBOT_CLASS_MAPPING[robot]}" diff --git a/third_party/robosuite/robosuite/environments/manipulation/nut_assembly.py b/third_party/robosuite/robosuite/environments/manipulation/nut_assembly.py new file mode 100644 index 0000000000000000000000000000000000000000..b2dc996ff73906a167cfe8f44c7b78f52f773e75 --- /dev/null +++ b/third_party/robosuite/robosuite/environments/manipulation/nut_assembly.py @@ -0,0 +1,705 @@ +import random +from collections import OrderedDict + +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.environments.manipulation.manipulation_env import ManipulationEnv +from robosuite.models.arenas import PegsArena +from robosuite.models.objects import RoundNutObject, SquareNutObject +from robosuite.models.tasks import ManipulationTask +from robosuite.utils.observables import Observable, sensor +from robosuite.utils.placement_samplers import SequentialCompositeSampler, UniformRandomSampler + + +class NutAssembly(ManipulationEnv): + """ + This class corresponds to the nut assembly task for a single robot arm. + + Args: + robots (str or list of str): Specification for specific robot arm(s) to be instantiated within this env + (e.g: "Sawyer" would generate one arm; ["Panda", "Panda", "Sawyer"] would generate three robot arms) + Note: Must be a single single-arm robot! + + env_configuration (str): Specifies how to position the robots within the environment (default is "default"). + For most single arm environments, this argument has no impact on the robot setup. + + controller_configs (str or list of dict): If set, contains relevant controller parameters for creating a + custom controller. Else, uses the default controller for this specific task. Should either be single + dict if same controller is to be used for all robots or else it should be a list of the same length as + "robots" param + + gripper_types (str or list of str): type of gripper, used to instantiate + gripper models from gripper factory. Default is "default", which is the default grippers(s) associated + with the robot(s) the 'robots' specification. None removes the gripper, and any other (valid) model + overrides the default gripper. Should either be single str if same gripper type is to be used for all + robots or else it should be a list of the same length as "robots" param + + initialization_noise (dict or list of dict): Dict containing the initialization noise parameters. + The expected keys and corresponding value types are specified below: + + :`'magnitude'`: The scale factor of uni-variate random noise applied to each of a robot's given initial + joint positions. Setting this value to `None` or 0.0 results in no noise being applied. + If "gaussian" type of noise is applied then this magnitude scales the standard deviation applied, + If "uniform" type of noise is applied then this magnitude sets the bounds of the sampling range + :`'type'`: Type of noise to apply. Can either specify "gaussian" or "uniform" + + Should either be single dict if same noise value is to be used for all robots or else it should be a + list of the same length as "robots" param + + :Note: Specifying "default" will automatically use the default noise settings. + Specifying None will automatically create the required dict with "magnitude" set to 0.0. + + table_full_size (3-tuple): x, y, and z dimensions of the table. + + table_friction (3-tuple): the three mujoco friction parameters for + the table. + + use_camera_obs (bool): if True, every observation includes rendered image(s) + + use_object_obs (bool): if True, include object (cube) information in + the observation. + + reward_scale (None or float): Scales the normalized reward function by the amount specified. + If None, environment reward remains unnormalized + + reward_shaping (bool): if True, use dense rewards. + + placement_initializer (ObjectPositionSampler): if provided, will + be used to place objects on every reset, else a UniformRandomSampler + is used by default. + + single_object_mode (int): specifies which version of the task to do. Note that + the observations change accordingly. + + :`0`: corresponds to the full task with both types of nuts. + + :`1`: corresponds to an easier task with only one type of nut initialized + on the table with every reset. The type is randomized on every reset. + + :`2`: corresponds to an easier task with only one type of nut initialized + on the table with every reset. The type is kept constant and will not + change between resets. + + nut_type (string): if provided, should be either "round" or "square". Determines + which type of nut (round or square) will be spawned on every environment + reset. Only used if @single_object_mode is 2. + + has_renderer (bool): If true, render the simulation state in + a viewer instead of headless mode. + + has_offscreen_renderer (bool): True if using off-screen rendering + + render_camera (str): Name of camera to render if `has_renderer` is True. Setting this value to 'None' + will result in the default angle being applied, which is useful as it can be dragged / panned by + the user using the mouse + + render_collision_mesh (bool): True if rendering collision meshes in camera. False otherwise. + + render_visual_mesh (bool): True if rendering visual meshes in camera. False otherwise. + + render_gpu_device_id (int): corresponds to the GPU device id to use for offscreen rendering. + Defaults to -1, in which case the device will be inferred from environment variables + (GPUS or CUDA_VISIBLE_DEVICES). + + control_freq (float): how many control signals to receive in every second. This sets the amount of + simulation time that passes between every action input. + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + + horizon (int): Every episode lasts for exactly @horizon timesteps. + + ignore_done (bool): True if never terminating the environment (ignore @horizon). + + hard_reset (bool): If True, re-loads model, sim, and render object upon a reset call, else, + only calls sim.reset and resets all robosuite-internal variables + + camera_names (str or list of str): name of camera to be rendered. Should either be single str if + same name is to be used for all cameras' rendering or else it should be a list of cameras to render. + + :Note: At least one camera must be specified if @use_camera_obs is True. + + :Note: To render all robots' cameras of a certain type (e.g.: "robotview" or "eye_in_hand"), use the + convention "all-{name}" (e.g.: "all-robotview") to automatically render all camera images from each + robot's camera list). + + camera_heights (int or list of int): height of camera frame. Should either be single int if + same height is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_widths (int or list of int): width of camera frame. Should either be single int if + same width is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_depths (bool or list of bool): True if rendering RGB-D, and RGB otherwise. Should either be single + bool if same depth setting is to be used for all cameras or else it should be a list of the same length as + "camera names" param. + + camera_segmentations (None or str or list of str or list of list of str): Camera segmentation(s) to use + for each camera. Valid options are: + + `None`: no segmentation sensor used + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + + If not None, multiple types of segmentations can be specified. A [list of str / str or None] specifies + [multiple / a single] segmentation(s) to use for all cameras. A list of list of str specifies per-camera + segmentation setting(s) to use. + + Raises: + AssertionError: [Invalid nut type specified] + AssertionError: [Invalid number of robots specified] + """ + + def __init__( + self, + robots, + env_configuration="default", + controller_configs=None, + gripper_types="default", + initialization_noise="default", + table_full_size=(0.8, 0.8, 0.05), + table_friction=(1, 0.005, 0.0001), + use_camera_obs=True, + use_object_obs=True, + reward_scale=1.0, + reward_shaping=False, + placement_initializer=None, + single_object_mode=0, + nut_type=None, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + lite_physics=True, + horizon=1000, + ignore_done=False, + hard_reset=True, + camera_names="agentview", + camera_heights=256, + camera_widths=256, + camera_depths=False, + camera_segmentations=None, # {None, instance, class, element} + renderer="mjviewer", + renderer_config=None, + ): + # task settings + self.single_object_mode = single_object_mode + self.nut_to_id = {"square": 0, "round": 1} + self.nut_id_to_sensors = {} # Maps nut id to sensor names for that nut + if nut_type is not None: + assert nut_type in self.nut_to_id.keys(), "invalid @nut_type argument - choose one of {}".format( + list(self.nut_to_id.keys()) + ) + self.nut_id = self.nut_to_id[nut_type] # use for convenient indexing + self.obj_to_use = None + + # settings for table top + self.table_full_size = table_full_size + self.table_friction = table_friction + self.table_offset = np.array((0, 0, 0.82)) + + # reward configuration + self.reward_scale = reward_scale + self.reward_shaping = reward_shaping + + # whether to use ground-truth object states + self.use_object_obs = use_object_obs + + # object placement initializer + self.placement_initializer = placement_initializer + + super().__init__( + robots=robots, + env_configuration=env_configuration, + controller_configs=controller_configs, + base_types="default", + gripper_types=gripper_types, + initialization_noise=initialization_noise, + use_camera_obs=use_camera_obs, + has_renderer=has_renderer, + has_offscreen_renderer=has_offscreen_renderer, + render_camera=render_camera, + render_collision_mesh=render_collision_mesh, + render_visual_mesh=render_visual_mesh, + render_gpu_device_id=render_gpu_device_id, + control_freq=control_freq, + lite_physics=lite_physics, + horizon=horizon, + ignore_done=ignore_done, + hard_reset=hard_reset, + camera_names=camera_names, + camera_heights=camera_heights, + camera_widths=camera_widths, + camera_depths=camera_depths, + camera_segmentations=camera_segmentations, + renderer=renderer, + renderer_config=renderer_config, + ) + + def reward(self, action=None): + """ + Reward function for the task. + + Sparse un-normalized reward: + + - a discrete reward of 1.0 per nut if it is placed around its correct peg + + Un-normalized components if using reward shaping, where the maximum is returned if not solved: + + - Reaching: in [0, 0.1], proportional to the distance between the gripper and the closest nut + - Grasping: in {0, 0.35}, nonzero if the gripper is grasping a nut + - Lifting: in {0, [0.35, 0.5]}, nonzero only if nut is grasped; proportional to lifting height + - Hovering: in {0, [0.5, 0.7]}, nonzero only if nut is lifted; proportional to distance from nut to peg + + Note that a successfully completed task (nut around peg) will return 1.0 per nut irregardless of whether the + environment is using sparse or shaped rewards + + Note that the final reward is normalized and scaled by reward_scale / 2.0 (or 1.0 if only a single nut is + being used) as well so that the max score is equal to reward_scale + + Args: + action (np.array): [NOT USED] + + Returns: + float: reward value + """ + # compute sparse rewards + self._check_success() + reward = np.sum(self.objects_on_pegs) + + # add in shaped rewards + if self.reward_shaping: + staged_rewards = self.staged_rewards() + reward += max(staged_rewards) + if self.reward_scale is not None: + reward *= self.reward_scale + if self.single_object_mode == 0: + reward /= 2.0 + return reward + + def staged_rewards(self): + """ + Calculates staged rewards based on current physical states. + Stages consist of reaching, grasping, lifting, and hovering. + + Returns: + 4-tuple: + + - (float) reaching reward + - (float) grasping reward + - (float) lifting reward + - (float) hovering reward + """ + + reach_mult = 0.1 + grasp_mult = 0.35 + lift_mult = 0.5 + hover_mult = 0.7 + + # filter out objects that are already on the correct pegs + active_nuts = [] + for i, nut in enumerate(self.nuts): + if self.objects_on_pegs[i]: + continue + active_nuts.append(nut) + + # reaching reward governed by distance to closest object + r_reach = 0.0 + if active_nuts: + # reaching reward via minimum distance to the handles of the objects + dists = [ + self._gripper_to_target( + gripper=self.robots[0].gripper, + target=active_nut.important_sites["handle"], + target_type="site", + return_distance=True, + ) + for active_nut in active_nuts + ] + r_reach = (1 - np.tanh(10.0 * min(dists))) * reach_mult + + # grasping reward for touching any objects of interest + r_grasp = ( + int( + self._check_grasp( + gripper=self.robots[0].gripper, + object_geoms=[g for active_nut in active_nuts for g in active_nut.contact_geoms], + ) + ) + * grasp_mult + ) + + # lifting reward for picking up an object + r_lift = 0.0 + table_pos = np.array(self.sim.data.body_xpos[self.table_body_id]) + if active_nuts and r_grasp > 0.0: + z_target = table_pos[2] + 0.2 + object_z_locs = self.sim.data.body_xpos[[self.obj_body_id[active_nut.name] for active_nut in active_nuts]][ + :, 2 + ] + z_dists = np.maximum(z_target - object_z_locs, 0.0) + r_lift = grasp_mult + (1 - np.tanh(15.0 * min(z_dists))) * (lift_mult - grasp_mult) + + # hover reward for getting object above peg + r_hover = 0.0 + if active_nuts: + r_hovers = np.zeros(len(active_nuts)) + peg_body_ids = [self.peg1_body_id, self.peg2_body_id] + for i, nut in enumerate(active_nuts): + valid_obj = False + peg_pos = None + for nut_name, idn in self.nut_to_id.items(): + if nut_name in nut.name.lower(): + peg_pos = np.array(self.sim.data.body_xpos[peg_body_ids[idn]])[:2] + valid_obj = True + break + if not valid_obj: + raise Exception("Got invalid object to reach: {}".format(nut.name)) + ob_xy = self.sim.data.body_xpos[self.obj_body_id[nut.name]][:2] + dist = np.linalg.norm(peg_pos - ob_xy) + r_hovers[i] = r_lift + (1 - np.tanh(10.0 * dist)) * (hover_mult - lift_mult) + r_hover = np.max(r_hovers) + + return r_reach, r_grasp, r_lift, r_hover + + def on_peg(self, obj_pos, peg_id): + + if peg_id == 0: + peg_pos = np.array(self.sim.data.body_xpos[self.peg1_body_id]) + else: + peg_pos = np.array(self.sim.data.body_xpos[self.peg2_body_id]) + res = False + if ( + abs(obj_pos[0] - peg_pos[0]) < 0.03 + and abs(obj_pos[1] - peg_pos[1]) < 0.03 + and obj_pos[2] < self.table_offset[2] + 0.05 + ): + res = True + return res + + def _load_model(self): + """ + Loads an xml model, puts it in self.model + """ + super()._load_model() + + # Adjust base pose accordingly + xpos = self.robots[0].robot_model.base_xpos_offset["table"](self.table_full_size[0]) + self.robots[0].robot_model.set_base_xpos(xpos) + + # load model for table top workspace + mujoco_arena = PegsArena( + table_full_size=self.table_full_size, + table_friction=self.table_friction, + table_offset=self.table_offset, + ) + + # Arena always gets set to zero origin + mujoco_arena.set_origin([0, 0, 0]) + + # define nuts + self.nuts = [] + nut_names = ("SquareNut", "RoundNut") + + # Create default (SequentialCompositeSampler) sampler if it has not already been specified + if self.placement_initializer is None: + self.placement_initializer = SequentialCompositeSampler(name="ObjectSampler") + for nut_name, default_y_range in zip(nut_names, ([0.11, 0.225], [-0.225, -0.11])): + self.placement_initializer.append_sampler( + sampler=UniformRandomSampler( + name=f"{nut_name}Sampler", + x_range=[-0.115, -0.11], + y_range=default_y_range, + rotation=None, + rotation_axis="z", + ensure_object_boundary_in_range=False, + ensure_valid_placement=True, + reference_pos=self.table_offset, + z_offset=0.02, + ) + ) + # Reset sampler before adding any new samplers / objects + self.placement_initializer.reset() + + for i, (nut_cls, nut_name) in enumerate( + zip( + (SquareNutObject, RoundNutObject), + nut_names, + ) + ): + nut = nut_cls(name=nut_name) + self.nuts.append(nut) + # Add this nut to the placement initializer + if isinstance(self.placement_initializer, SequentialCompositeSampler): + # assumes we have two samplers so we add nuts to them + self.placement_initializer.add_objects_to_sampler(sampler_name=f"{nut_name}Sampler", mujoco_objects=nut) + else: + # This is assumed to be a flat sampler, so we just add all nuts to this sampler + self.placement_initializer.add_objects(nut) + + # task includes arena, robot, and objects of interest + self.model = ManipulationTask( + mujoco_arena=mujoco_arena, + mujoco_robots=[robot.robot_model for robot in self.robots], + mujoco_objects=self.nuts, + ) + + def _setup_references(self): + """ + Sets up references to important components. A reference is typically an + index or a list of indices that point to the corresponding elements + in a flatten array, which is how MuJoCo stores physical simulation data. + """ + super()._setup_references() + + # Additional object references from this env + self.obj_body_id = {} + self.obj_geom_id = {} + + self.table_body_id = self.sim.model.body_name2id("table") + self.peg1_body_id = self.sim.model.body_name2id("peg1") + self.peg2_body_id = self.sim.model.body_name2id("peg2") + + for nut in self.nuts: + self.obj_body_id[nut.name] = self.sim.model.body_name2id(nut.root_body) + self.obj_geom_id[nut.name] = [self.sim.model.geom_name2id(g) for g in nut.contact_geoms] + + # information of objects + self.object_site_ids = [self.sim.model.site_name2id(nut.important_sites["handle"]) for nut in self.nuts] + + # keep track of which objects are on their corresponding pegs + self.objects_on_pegs = np.zeros(len(self.nuts)) + + def _setup_observables(self): + """ + Sets up observables to be used for this environment. Creates object-based observables if enabled + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + observables = super()._setup_observables() + + # low-level object information + if self.use_object_obs: + modality = "object" + + # Reset nut sensor mappings + self.nut_id_to_sensors = {} + arm_prefixes = self._get_arm_prefixes(self.robots[0], include_robot_name=False) + full_prefixes = self._get_arm_prefixes(self.robots[0]) + sensors = [ + self._get_world_pose_in_gripper_sensor(full_pf, f"world_pose_in_{arm_pf}gripper", modality) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + names = [fn.__name__ for fn in sensors] + actives = [False] * len(sensors) + enableds = [True] * len(sensors) + + # Define nut related sensors + for i, nut in enumerate(self.nuts): + # Create sensors for this nut + using_nut = self.single_object_mode == 0 or self.nut_id == i + nut_sensors, nut_sensor_names = self._create_nut_sensors(nut_name=nut.name, modality=modality) + sensors += nut_sensors + names += nut_sensor_names + enableds += [using_nut] * len(nut_sensors) + actives += [using_nut] * len(nut_sensors) + self.nut_id_to_sensors[i] = nut_sensor_names + + if self.single_object_mode == 1: + # This is randomly sampled object, so we need to include object id as observation + @sensor(modality=modality) + def nut_id(obs_cache): + return self.nut_id + + sensors.append(nut_id) + names.append("nut_id") + enableds.append(True) + actives.append(True) + + # Create observables + for name, s, enabled, active in zip(names, sensors, enableds, actives): + observables[name] = Observable( + name=name, + sensor=s, + sampling_rate=self.control_freq, + enabled=enabled, + active=active, + ) + + return observables + + def _create_nut_sensors(self, nut_name, modality="object"): + """ + Helper function to create sensors for a given nut. This is abstracted in a separate function call so that we + don't have local function naming collisions during the _setup_observables() call. + + Args: + nut_name (str): Name of nut to create sensors for + modality (str): Modality to assign to all sensors + + Returns: + 2-tuple: + sensors (list): Array of sensors for the given nut + names (list): array of corresponding observable names + """ + + @sensor(modality=modality) + def nut_pos(obs_cache): + return np.array(self.sim.data.body_xpos[self.obj_body_id[nut_name]]) + + @sensor(modality=modality) + def nut_quat(obs_cache): + return T.convert_quat(self.sim.data.body_xquat[self.obj_body_id[nut_name]], to="xyzw") + + arm_prefixes = self._get_arm_prefixes(self.robots[0], include_robot_name=False) + full_prefixes = self._get_arm_prefixes(self.robots[0]) + + sensors = [ + self._get_rel_obj_eef_sensor(arm_pf, nut_name, f"{nut_name}_to_{full_pf}eef_pos", full_pf, modality) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + sensors += [ + self._get_obj_eef_rel_quat_sensor(full_pf, nut_name, f"{nut_name}_to_{full_pf}eef_quat", modality) + for full_pf in full_prefixes + ] + names = [fn.__name__ for fn in sensors] + + sensors += [nut_pos, nut_quat] + names += [f"{nut_name}_pos", f"{nut_name}_quat"] + + return sensors, names + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + super()._reset_internal() + + # Reset all object positions using initializer sampler if we're not directly loading from an xml + if not self.deterministic_reset: + + # Sample from the placement initializer for all objects + object_placements = self.placement_initializer.sample() + + # Loop through all objects and reset their positions + for obj_pos, obj_quat, obj in object_placements.values(): + self.sim.data.set_joint_qpos(obj.joints[0], np.concatenate([np.array(obj_pos), np.array(obj_quat)])) + + # Move objects out of the scene depending on the mode + nut_names = {nut.name for nut in self.nuts} + if self.single_object_mode == 1: + self.obj_to_use = random.choice(list(nut_names)) + for nut_type, i in self.nut_to_id.items(): + if nut_type.lower() in self.obj_to_use.lower(): + self.nut_id = i + break + elif self.single_object_mode == 2: + self.obj_to_use = self.nuts[self.nut_id].name + if self.single_object_mode in {1, 2}: + nut_names.remove(self.obj_to_use) + self.clear_objects(list(nut_names)) + + # Make sure to update sensors' active and enabled states + if self.single_object_mode != 0: + for i, sensor_names in self.nut_id_to_sensors.items(): + for name in sensor_names: + # Set all of these sensors to be enabled and active if this is the active nut, else False + self._observables[name].set_enabled(i == self.nut_id) + self._observables[name].set_active(i == self.nut_id) + + def _check_success(self): + """ + Check if all nuts have been successfully placed around their corresponding pegs. + + Returns: + bool: True if all nuts are placed correctly + """ + # remember objects that are on the correct pegs + for i, nut in enumerate(self.nuts): + obj_str = nut.name + obj_pos = self.sim.data.body_xpos[self.obj_body_id[obj_str]] + dist = min( + [ + np.linalg.norm(self.sim.data.site_xpos[self.robots[0].eef_site_id[arm]] - obj_pos) + for arm in self.robots[0].arms + ] + ) + r_reach = 1 - np.tanh(10.0 * dist) + self.objects_on_pegs[i] = int(self.on_peg(obj_pos, i) and r_reach < 0.6) + + if self.single_object_mode > 0: + return np.sum(self.objects_on_pegs) > 0 # need one object on peg + + # returns True if all objects are on correct pegs + return np.sum(self.objects_on_pegs) == len(self.nuts) + + def visualize(self, vis_settings): + """ + In addition to super call, visualize gripper site proportional to the distance to the closest nut. + + Args: + vis_settings (dict): Visualization keywords mapped to T/F, determining whether that specific + component should be visualized. Should have "grippers" keyword as well as any other relevant + options specified. + """ + # Run superclass method first + super().visualize(vis_settings=vis_settings) + + # Color the gripper visualization site according to its distance to the closest nut + if vis_settings["grippers"]: + # if the robot has multiple arms color each arm independently based on its closest object + for arm in self.robots[0].arms: + # find closest object + dists = [ + self._gripper_to_target( + gripper=self.robots[0].gripper[arm], + target=nut.important_sites["handle"], + target_type="site", + return_distance=True, + ) + for nut in self.nuts + ] + closest_nut_id = np.argmin(dists) + # Visualize the distance to this target + self._visualize_gripper_to_target( + gripper=self.robots[0].gripper[arm], + target=self.nuts[closest_nut_id].important_sites["handle"], + target_type="site", + ) + + +class NutAssemblySingle(NutAssembly): + """ + Easier version of task - place either one round nut or one square nut into its peg. + """ + + def __init__(self, **kwargs): + assert "single_object_mode" not in kwargs, "invalid set of arguments" + super().__init__(single_object_mode=1, **kwargs) + + +class NutAssemblySquare(NutAssembly): + """ + Easier version of task - place one square nut into its peg. + """ + + def __init__(self, **kwargs): + assert "single_object_mode" not in kwargs and "nut_type" not in kwargs, "invalid set of arguments" + super().__init__(single_object_mode=2, nut_type="square", **kwargs) + + +class NutAssemblyRound(NutAssembly): + """ + Easier version of task - place one round nut into its peg. + """ + + def __init__(self, **kwargs): + assert "single_object_mode" not in kwargs and "nut_type" not in kwargs, "invalid set of arguments" + super().__init__(single_object_mode=2, nut_type="round", **kwargs) diff --git a/third_party/robosuite/robosuite/environments/manipulation/pick_place.py b/third_party/robosuite/robosuite/environments/manipulation/pick_place.py new file mode 100644 index 0000000000000000000000000000000000000000..beafad45faaf0c9df70fdc014c4fecac86ae4c74 --- /dev/null +++ b/third_party/robosuite/robosuite/environments/manipulation/pick_place.py @@ -0,0 +1,836 @@ +import random +from collections import OrderedDict + +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.environments.manipulation.manipulation_env import ManipulationEnv +from robosuite.models.arenas import BinsArena +from robosuite.models.objects import ( + BreadObject, + BreadVisualObject, + CanObject, + CanVisualObject, + CerealObject, + CerealVisualObject, + MilkObject, + MilkVisualObject, +) +from robosuite.models.tasks import ManipulationTask +from robosuite.utils.observables import Observable, sensor +from robosuite.utils.placement_samplers import SequentialCompositeSampler, UniformRandomSampler + + +class PickPlace(ManipulationEnv): + """ + This class corresponds to the pick place task for a single robot arm. + + Args: + robots (str or list of str): Specification for specific robot arm(s) to be instantiated within this env + (e.g: "Sawyer" would generate one arm; ["Panda", "Panda", "Sawyer"] would generate three robot arms) + Note: Must be a single single-arm robot! + + env_configuration (str): Specifies how to position the robots within the environment (default is "default"). + For most single arm environments, this argument has no impact on the robot setup. + + controller_configs (str or list of dict): If set, contains relevant controller parameters for creating a + custom controller. Else, uses the default controller for this specific task. Should either be single + dict if same controller is to be used for all robots or else it should be a list of the same length as + "robots" param + + gripper_types (str or list of str): type of gripper, used to instantiate + gripper models from gripper factory. Default is "default", which is the default grippers(s) associated + with the robot(s) the 'robots' specification. None removes the gripper, and any other (valid) model + overrides the default gripper. Should either be single str if same gripper type is to be used for all + robots or else it should be a list of the same length as "robots" param + + initialization_noise (dict or list of dict): Dict containing the initialization noise parameters. + The expected keys and corresponding value types are specified below: + + :`'magnitude'`: The scale factor of uni-variate random noise applied to each of a robot's given initial + joint positions. Setting this value to `None` or 0.0 results in no noise being applied. + If "gaussian" type of noise is applied then this magnitude scales the standard deviation applied, + If "uniform" type of noise is applied then this magnitude sets the bounds of the sampling range + :`'type'`: Type of noise to apply. Can either specify "gaussian" or "uniform" + + Should either be single dict if same noise value is to be used for all robots or else it should be a + list of the same length as "robots" param + + :Note: Specifying "default" will automatically use the default noise settings. + Specifying None will automatically create the required dict with "magnitude" set to 0.0. + + table_full_size (3-tuple): x, y, and z dimensions of the table. + + table_friction (3-tuple): the three mujoco friction parameters for + the table. + + bin1_pos (3-tuple): Absolute cartesian coordinates of the bin initially holding the objects + + bin2_pos (3-tuple): Absolute cartesian coordinates of the goal bin + + z_offset (float): amount of z offset for initializing objects in bin + + z_rotation (float, tuple, or None): if provided, controls the range of z-rotation initialization + for the objects + + use_camera_obs (bool): if True, every observation includes rendered image(s) + + use_object_obs (bool): if True, include object (cube) information in + the observation. + + reward_scale (None or float): Scales the normalized reward function by the amount specified. + If None, environment reward remains unnormalized + + reward_shaping (bool): if True, use dense rewards. + + single_object_mode (int): specifies which version of the task to do. Note that + the observations change accordingly. + + :`0`: corresponds to the full task with all types of objects. + + :`1`: corresponds to an easier task with only one type of object initialized + on the table with every reset. The type is randomized on every reset. + + :`2`: corresponds to an easier task with only one type of object initialized + on the table with every reset. The type is kept constant and will not + change between resets. + + object_type (string): if provided, should be one of "milk", "bread", "cereal", + or "can". Determines which type of object will be spawned on every + environment reset. Only used if @single_object_mode is 2. + + has_renderer (bool): If true, render the simulation state in + a viewer instead of headless mode. + + has_offscreen_renderer (bool): True if using off-screen rendering + + render_camera (str): Name of camera to render if `has_renderer` is True. Setting this value to 'None' + will result in the default angle being applied, which is useful as it can be dragged / panned by + the user using the mouse + + render_collision_mesh (bool): True if rendering collision meshes in camera. False otherwise. + + render_visual_mesh (bool): True if rendering visual meshes in camera. False otherwise. + + render_gpu_device_id (int): corresponds to the GPU device id to use for offscreen rendering. + Defaults to -1, in which case the device will be inferred from environment variables + (GPUS or CUDA_VISIBLE_DEVICES). + + control_freq (float): how many control signals to receive in every second. This sets the amount of + simulation time that passes between every action input. + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + + horizon (int): Every episode lasts for exactly @horizon timesteps. + + ignore_done (bool): True if never terminating the environment (ignore @horizon). + + hard_reset (bool): If True, re-loads model, sim, and render object upon a reset call, else, + only calls sim.reset and resets all robosuite-internal variables + + camera_names (str or list of str): name of camera to be rendered. Should either be single str if + same name is to be used for all cameras' rendering or else it should be a list of cameras to render. + + :Note: At least one camera must be specified if @use_camera_obs is True. + + :Note: To render all robots' cameras of a certain type (e.g.: "robotview" or "eye_in_hand"), use the + convention "all-{name}" (e.g.: "all-robotview") to automatically render all camera images from each + robot's camera list). + + camera_heights (int or list of int): height of camera frame. Should either be single int if + same height is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_widths (int or list of int): width of camera frame. Should either be single int if + same width is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_depths (bool or list of bool): True if rendering RGB-D, and RGB otherwise. Should either be single + bool if same depth setting is to be used for all cameras or else it should be a list of the same length as + "camera names" param. + + camera_segmentations (None or str or list of str or list of list of str): Camera segmentation(s) to use + for each camera. Valid options are: + + `None`: no segmentation sensor used + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + + If not None, multiple types of segmentations can be specified. A [list of str / str or None] specifies + [multiple / a single] segmentation(s) to use for all cameras. A list of list of str specifies per-camera + segmentation setting(s) to use. + + Raises: + AssertionError: [Invalid object type specified] + AssertionError: [Invalid number of robots specified] + """ + + def __init__( + self, + robots, + env_configuration="default", + controller_configs=None, + gripper_types="default", + initialization_noise="default", + table_full_size=(0.39, 0.49, 0.82), + table_friction=(1, 0.005, 0.0001), + bin1_pos=(0.1, -0.25, 0.8), + bin2_pos=(0.1, 0.28, 0.8), + z_offset=0.0, + z_rotation=None, + use_camera_obs=True, + use_object_obs=True, + reward_scale=1.0, + reward_shaping=False, + single_object_mode=0, + object_type=None, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + lite_physics=True, + horizon=1000, + ignore_done=False, + hard_reset=True, + camera_names="agentview", + camera_heights=256, + camera_widths=256, + camera_depths=False, + camera_segmentations=None, # {None, instance, class, element} + renderer="mjviewer", + renderer_config=None, + ): + # task settings + self.single_object_mode = single_object_mode + self.object_to_id = {"milk": 0, "bread": 1, "cereal": 2, "can": 3} + self.object_id_to_sensors = {} # Maps object id to sensor names for that object + self.obj_names = ["Milk", "Bread", "Cereal", "Can"] + if object_type is not None: + assert object_type in self.object_to_id.keys(), "invalid @object_type argument - choose one of {}".format( + list(self.object_to_id.keys()) + ) + self.object_id = self.object_to_id[object_type] # use for convenient indexing + self.obj_to_use = None + + # settings for table top + self.table_full_size = table_full_size + self.table_friction = table_friction + + # settings for bin position + self.bin1_pos = np.array(bin1_pos) + self.bin2_pos = np.array(bin2_pos) + self.z_offset = z_offset # z offset for initializing items in bin + self.z_rotation = z_rotation # z rotation for initializing items in bin + + # reward configuration + self.reward_scale = reward_scale + self.reward_shaping = reward_shaping + + # whether to use ground-truth object states + self.use_object_obs = use_object_obs + + super().__init__( + robots=robots, + env_configuration=env_configuration, + controller_configs=controller_configs, + base_types="default", + gripper_types=gripper_types, + initialization_noise=initialization_noise, + use_camera_obs=use_camera_obs, + has_renderer=has_renderer, + has_offscreen_renderer=has_offscreen_renderer, + render_camera=render_camera, + render_collision_mesh=render_collision_mesh, + render_visual_mesh=render_visual_mesh, + render_gpu_device_id=render_gpu_device_id, + control_freq=control_freq, + lite_physics=lite_physics, + horizon=horizon, + ignore_done=ignore_done, + hard_reset=hard_reset, + camera_names=camera_names, + camera_heights=camera_heights, + camera_widths=camera_widths, + camera_depths=camera_depths, + camera_segmentations=camera_segmentations, + renderer=renderer, + renderer_config=renderer_config, + ) + + def reward(self, action=None): + """ + Reward function for the task. + + Sparse un-normalized reward: + + - a discrete reward of 1.0 per object if it is placed in its correct bin + + Un-normalized components if using reward shaping, where the maximum is returned if not solved: + + - Reaching: in [0, 0.1], proportional to the distance between the gripper and the closest object + - Grasping: in {0, 0.35}, nonzero if the gripper is grasping an object + - Lifting: in {0, [0.35, 0.5]}, nonzero only if object is grasped; proportional to lifting height + - Hovering: in {0, [0.5, 0.7]}, nonzero only if object is lifted; proportional to distance from object to bin + + Note that a successfully completed task (object in bin) will return 1.0 per object irregardless of whether the + environment is using sparse or shaped rewards + + Note that the final reward is normalized and scaled by reward_scale / 4.0 (or 1.0 if only a single object is + being used) as well so that the max score is equal to reward_scale + + Args: + action (np.array): [NOT USED] + + Returns: + float: reward value + """ + # compute sparse rewards + self._check_success() + reward = np.sum(self.objects_in_bins) + + # add in shaped rewards + if self.reward_shaping: + staged_rewards = self.staged_rewards() + reward += max(staged_rewards) + if self.reward_scale is not None: + reward *= self.reward_scale + if self.single_object_mode == 0: + reward /= 4.0 + return reward + + def staged_rewards(self): + """ + Returns staged rewards based on current physical states. + Stages consist of reaching, grasping, lifting, and hovering. + + Returns: + 4-tuple: + + - (float) reaching reward + - (float) grasping reward + - (float) lifting reward + - (float) hovering reward + """ + + reach_mult = 0.1 + grasp_mult = 0.35 + lift_mult = 0.5 + hover_mult = 0.7 + + # filter out objects that are already in the correct bins + active_objs = [] + for i, obj in enumerate(self.objects): + if self.objects_in_bins[i]: + continue + active_objs.append(obj) + + # reaching reward governed by distance to closest object + r_reach = 0.0 + if active_objs: + # get reaching reward via minimum distance to a target object + dists = [ + self._gripper_to_target( + gripper=self.robots[0].gripper, + target=active_obj.root_body, + target_type="body", + return_distance=True, + ) + for active_obj in active_objs + ] + r_reach = (1 - np.tanh(10.0 * min(dists))) * reach_mult + + # grasping reward for touching any objects of interest + r_grasp = ( + int( + self._check_grasp( + gripper=self.robots[0].gripper, + object_geoms=[g for active_obj in active_objs for g in active_obj.contact_geoms], + ) + ) + * grasp_mult + ) + + # lifting reward for picking up an object + r_lift = 0.0 + if active_objs and r_grasp > 0.0: + z_target = self.bin2_pos[2] + 0.25 + object_z_locs = self.sim.data.body_xpos[[self.obj_body_id[active_obj.name] for active_obj in active_objs]][ + :, 2 + ] + z_dists = np.maximum(z_target - object_z_locs, 0.0) + r_lift = grasp_mult + (1 - np.tanh(15.0 * min(z_dists))) * (lift_mult - grasp_mult) + + # hover reward for getting object above bin + r_hover = 0.0 + if active_objs: + target_bin_ids = [self.object_to_id[active_obj.name.lower()] for active_obj in active_objs] + # segment objects into left of the bins and above the bins + object_xy_locs = self.sim.data.body_xpos[[self.obj_body_id[active_obj.name] for active_obj in active_objs]][ + :, :2 + ] + y_check = ( + np.abs(object_xy_locs[:, 1] - self.target_bin_placements[target_bin_ids, 1]) < self.bin_size[1] / 4.0 + ) + x_check = ( + np.abs(object_xy_locs[:, 0] - self.target_bin_placements[target_bin_ids, 0]) < self.bin_size[0] / 4.0 + ) + objects_above_bins = np.logical_and(x_check, y_check) + objects_not_above_bins = np.logical_not(objects_above_bins) + dists = np.linalg.norm(self.target_bin_placements[target_bin_ids, :2] - object_xy_locs, axis=1) + # objects to the left get r_lift added to hover reward, + # those on the right get max(r_lift) added (to encourage dropping) + r_hover_all = np.zeros(len(active_objs)) + r_hover_all[objects_above_bins] = lift_mult + (1 - np.tanh(10.0 * dists[objects_above_bins])) * ( + hover_mult - lift_mult + ) + r_hover_all[objects_not_above_bins] = r_lift + (1 - np.tanh(10.0 * dists[objects_not_above_bins])) * ( + hover_mult - lift_mult + ) + r_hover = np.max(r_hover_all) + + return r_reach, r_grasp, r_lift, r_hover + + def not_in_bin(self, obj_pos, bin_id): + + bin_x_low = self.bin2_pos[0] + bin_y_low = self.bin2_pos[1] + if bin_id == 0 or bin_id == 2: + bin_x_low -= self.bin_size[0] / 2 + if bin_id < 2: + bin_y_low -= self.bin_size[1] / 2 + + bin_x_high = bin_x_low + self.bin_size[0] / 2 + bin_y_high = bin_y_low + self.bin_size[1] / 2 + + res = True + if ( + bin_x_low < obj_pos[0] < bin_x_high + and bin_y_low < obj_pos[1] < bin_y_high + and self.bin2_pos[2] < obj_pos[2] < self.bin2_pos[2] + 0.1 + ): + res = False + return res + + def _get_placement_initializer(self): + """ + Helper function for defining placement initializer and object sampling bounds. + """ + self.placement_initializer = SequentialCompositeSampler(name="ObjectSampler") + + # can sample anywhere in bin + bin_x_half = self.model.mujoco_arena.table_full_size[0] / 2 - 0.05 + bin_y_half = self.model.mujoco_arena.table_full_size[1] / 2 - 0.05 + + # each object should just be sampled in the bounds of the bin (with some tolerance) + self.placement_initializer.append_sampler( + sampler=UniformRandomSampler( + name="CollisionObjectSampler", + mujoco_objects=self.objects, + x_range=[-bin_x_half, bin_x_half], + y_range=[-bin_y_half, bin_y_half], + rotation=self.z_rotation, + rotation_axis="z", + ensure_object_boundary_in_range=True, + ensure_valid_placement=True, + reference_pos=self.bin1_pos, + z_offset=self.z_offset, + ) + ) + + # each visual object should just be at the center of each target bin + index = 0 + for vis_obj in self.visual_objects: + + # get center of target bin + bin_x_low = self.bin2_pos[0] + bin_y_low = self.bin2_pos[1] + if index == 0 or index == 2: + bin_x_low -= self.bin_size[0] / 2 + if index < 2: + bin_y_low -= self.bin_size[1] / 2 + bin_x_high = bin_x_low + self.bin_size[0] / 2 + bin_y_high = bin_y_low + self.bin_size[1] / 2 + bin_center = np.array( + [ + (bin_x_low + bin_x_high) / 2.0, + (bin_y_low + bin_y_high) / 2.0, + ] + ) + + # placement is relative to object bin, so compute difference and send to placement initializer + rel_center = bin_center - self.bin1_pos[:2] + + self.placement_initializer.append_sampler( + sampler=UniformRandomSampler( + name=f"{vis_obj.name}ObjectSampler", + mujoco_objects=vis_obj, + x_range=[rel_center[0], rel_center[0]], + y_range=[rel_center[1], rel_center[1]], + rotation=0.0, + rotation_axis="z", + ensure_object_boundary_in_range=False, + ensure_valid_placement=False, + reference_pos=self.bin1_pos, + z_offset=self.bin2_pos[2] - self.bin1_pos[2], + ) + ) + index += 1 + + def _construct_visual_objects(self): + """ + Function that can be overriden by subclasses to load different objects. + """ + self.visual_objects = [] + for vis_obj_cls, obj_name in zip( + (MilkVisualObject, BreadVisualObject, CerealVisualObject, CanVisualObject), + self.obj_names, + ): + vis_name = "Visual" + obj_name + vis_obj = vis_obj_cls(name=vis_name) + self.visual_objects.append(vis_obj) + + def _construct_objects(self): + """ + Function that can be overriden by subclasses to load different objects. + """ + self.objects = [] + for obj_cls, obj_name in zip( + (MilkObject, BreadObject, CerealObject, CanObject), + self.obj_names, + ): + obj = obj_cls(name=obj_name) + self.objects.append(obj) + + def _load_model(self): + """ + Loads an xml model, puts it in self.model + """ + super()._load_model() + + # Adjust base pose accordingly + xpos = self.robots[0].robot_model.base_xpos_offset["bins"] + self.robots[0].robot_model.set_base_xpos(xpos) + + # load model for table top workspace + mujoco_arena = BinsArena( + bin1_pos=self.bin1_pos, table_full_size=self.table_full_size, table_friction=self.table_friction + ) + + # Arena always gets set to zero origin + mujoco_arena.set_origin([0, 0, 0]) + + # store some arena attributes + self.bin_size = mujoco_arena.table_full_size + + # make objects + self._construct_visual_objects() + self._construct_objects() + + # task includes arena, robot, and objects of interest + self.model = ManipulationTask( + mujoco_arena=mujoco_arena, + mujoco_robots=[robot.robot_model for robot in self.robots], + mujoco_objects=self.visual_objects + self.objects, + ) + + # Generate placement initializer + self._get_placement_initializer() + + def _setup_references(self): + """ + Sets up references to important components. A reference is typically an + index or a list of indices that point to the corresponding elements + in a flatten array, which is how MuJoCo stores physical simulation data. + """ + super()._setup_references() + + # Additional object references from this env + self.obj_body_id = {} + self.obj_geom_id = {} + + # object-specific ids + for obj in self.visual_objects + self.objects: + self.obj_body_id[obj.name] = self.sim.model.body_name2id(obj.root_body) + self.obj_geom_id[obj.name] = [self.sim.model.geom_name2id(g) for g in obj.contact_geoms] + + # keep track of which objects are in their corresponding bins + self.objects_in_bins = np.zeros(len(self.objects)) + + # target locations in bin for each object type + self.target_bin_placements = np.zeros((len(self.objects), 3)) + for i, obj in enumerate(self.objects): + bin_id = i + bin_x_low = self.bin2_pos[0] + bin_y_low = self.bin2_pos[1] + if bin_id == 0 or bin_id == 2: + bin_x_low -= self.bin_size[0] / 2.0 + if bin_id < 2: + bin_y_low -= self.bin_size[1] / 2.0 + bin_x_low += self.bin_size[0] / 4.0 + bin_y_low += self.bin_size[1] / 4.0 + self.target_bin_placements[i, :] = [bin_x_low, bin_y_low, self.bin2_pos[2]] + + def _setup_observables(self): + """ + Sets up observables to be used for this environment. Creates object-based observables if enabled + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + observables = super()._setup_observables() + + # low-level object information + if self.use_object_obs: + # define observables modality + modality = "object" + + # Reset obj sensor mappings + self.object_id_to_sensors = {} + + arm_prefixes = self._get_arm_prefixes(self.robots[0], include_robot_name=False) + full_prefixes = self._get_arm_prefixes(self.robots[0]) + sensors = [ + self._get_world_pose_in_gripper_sensor(full_pf, f"world_pose_in_{arm_pf}gripper", modality) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + names = [fn.__name__ for fn in sensors] + actives = [False] * len(sensors) + enableds = [True] * len(sensors) + + for i, obj in enumerate(self.objects): + # Create object sensors + using_obj = self.single_object_mode == 0 or self.object_id == i + obj_sensors, obj_sensor_names = self._create_obj_sensors(obj_name=obj.name, modality=modality) + sensors += obj_sensors + names += obj_sensor_names + enableds += [using_obj] * len(obj_sensor_names) + actives += [using_obj] * len(obj_sensor_names) + self.object_id_to_sensors[i] = obj_sensor_names + + if self.single_object_mode == 1: + # This is randomly sampled object, so we need to include object id as observation + @sensor(modality=modality) + def obj_id(obs_cache): + return self.object_id + + sensors.append(obj_id) + names.append("obj_id") + enableds.append(True) + actives.append(True) + + # Create observables + for name, s, enabled, active in zip(names, sensors, enableds, actives): + observables[name] = Observable( + name=name, + sensor=s, + sampling_rate=self.control_freq, + enabled=enabled, + active=active, + ) + + return observables + + def _create_obj_sensors(self, obj_name, modality="object"): + """ + Helper function to create sensors for a given object. This is abstracted in a separate function call so that we + don't have local function naming collisions during the _setup_observables() call. + + Args: + obj_name (str): Name of object to create sensors for + modality (str): Modality to assign to all sensors + + Returns: + 2-tuple: + sensors (list): Array of sensors for the given obj + names (list): array of corresponding observable names + """ + + @sensor(modality=modality) + def obj_pos(obs_cache): + return np.array(self.sim.data.body_xpos[self.obj_body_id[obj_name]]) + + @sensor(modality=modality) + def obj_quat(obs_cache): + return T.convert_quat(self.sim.data.body_xquat[self.obj_body_id[obj_name]], to="xyzw") + + arm_prefixes = self._get_arm_prefixes(self.robots[0], include_robot_name=False) + full_prefixes = self._get_arm_prefixes(self.robots[0]) + + sensors = [ + self._get_rel_obj_eef_sensor(arm_pf, obj_name, f"{obj_name}_to_{full_pf}eef_pos", full_pf, modality) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + sensors += [ + self._get_obj_eef_rel_quat_sensor(full_pf, obj_name, f"{obj_name}_to_{full_pf}eef_quat", modality) + for full_pf in full_prefixes + ] + names = [fn.__name__ for fn in sensors] + sensors += [obj_pos, obj_quat] + names += [f"{obj_name}_pos", f"{obj_name}_quat"] + + return sensors, names + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + super()._reset_internal() + + # Reset all object positions using initializer sampler if we're not directly loading from an xml + if not self.deterministic_reset: + + # Sample from the placement initializer for all objects + object_placements = self.placement_initializer.sample() + + # Loop through all objects and reset their positions + for obj_pos, obj_quat, obj in object_placements.values(): + # Set the visual object body locations + if "visual" in obj.name.lower(): + self.sim.model.body_pos[self.obj_body_id[obj.name]] = obj_pos + self.sim.model.body_quat[self.obj_body_id[obj.name]] = obj_quat + else: + # Set the collision object joints + self.sim.data.set_joint_qpos(obj.joints[0], np.concatenate([np.array(obj_pos), np.array(obj_quat)])) + + # Set the bins to the desired position + self.sim.model.body_pos[self.sim.model.body_name2id("bin1")] = self.bin1_pos + self.sim.model.body_pos[self.sim.model.body_name2id("bin2")] = self.bin2_pos + + # Move objects out of the scene depending on the mode + obj_names = {obj.name for obj in self.objects} + if self.single_object_mode == 1: + self.obj_to_use = random.choice(list(obj_names)) + for obj_type, i in self.object_to_id.items(): + if obj_type.lower() in self.obj_to_use.lower(): + self.object_id = i + break + elif self.single_object_mode == 2: + self.obj_to_use = self.objects[self.object_id].name + if self.single_object_mode in {1, 2}: + obj_names.remove(self.obj_to_use) + self.clear_objects(list(obj_names)) + + # Make sure to update sensors' active and enabled states + if self.single_object_mode != 0: + for i, sensor_names in self.object_id_to_sensors.items(): + for name in sensor_names: + # Set all of these sensors to be enabled and active if this is the active object, else False + self._observables[name].set_enabled(i == self.object_id) + self._observables[name].set_active(i == self.object_id) + + def _check_success(self): + """ + Check if all objects have been successfully placed in their corresponding bins. + + Returns: + bool: True if all objects are placed correctly + """ + # remember objects that are in the correct bins + for i, obj in enumerate(self.objects): + obj_str = obj.name + obj_pos = self.sim.data.body_xpos[self.obj_body_id[obj_str]] + dist = min( + [ + np.linalg.norm(self.sim.data.site_xpos[self.robots[0].eef_site_id[arm]] - obj_pos) + for arm in self.robots[0].arms + ] + ) + r_reach = 1 - np.tanh(10.0 * dist) + self.objects_in_bins[i] = int((not self.not_in_bin(obj_pos, i)) and r_reach < 0.6) + + # returns True if a single object is in the correct bin + if self.single_object_mode in {1, 2}: + return np.sum(self.objects_in_bins) > 0 + + # returns True if all objects are in correct bins + return np.sum(self.objects_in_bins) == len(self.objects) + + def visualize(self, vis_settings): + """ + In addition to super call, visualize gripper site proportional to the distance to the closest object. + + Args: + vis_settings (dict): Visualization keywords mapped to T/F, determining whether that specific + component should be visualized. Should have "grippers" keyword as well as any other relevant + options specified. + """ + # Run superclass method first + super().visualize(vis_settings=vis_settings) + + # Color the gripper visualization site according to its distance to the closest object + if vis_settings["grippers"]: + # if the robot has multiple arms color each arm independently based on its closest object + for arm in self.robots[0].arms: + # find closest object + dists = [ + self._gripper_to_target( + gripper=self.robots[0].gripper[arm], + target=obj.root_body, + target_type="body", + return_distance=True, + ) + for obj in self.objects + ] + closest_obj_id = np.argmin(dists) + # Visualize the distance to this target + self._visualize_gripper_to_target( + gripper=self.robots[0].gripper[arm], + target=self.objects[closest_obj_id].root_body, + target_type="body", + ) + + +class PickPlaceSingle(PickPlace): + """ + Easier version of task - place one object into its bin. + A new object is sampled on every reset. + """ + + def __init__(self, **kwargs): + assert "single_object_mode" not in kwargs, "invalid set of arguments" + super().__init__(single_object_mode=1, **kwargs) + + +class PickPlaceMilk(PickPlace): + """ + Easier version of task - place one milk into its bin. + """ + + def __init__(self, **kwargs): + assert "single_object_mode" not in kwargs and "object_type" not in kwargs, "invalid set of arguments" + super().__init__(single_object_mode=2, object_type="milk", **kwargs) + + +class PickPlaceBread(PickPlace): + """ + Easier version of task - place one bread into its bin. + """ + + def __init__(self, **kwargs): + assert "single_object_mode" not in kwargs and "object_type" not in kwargs, "invalid set of arguments" + super().__init__(single_object_mode=2, object_type="bread", **kwargs) + + +class PickPlaceCereal(PickPlace): + """ + Easier version of task - place one cereal into its bin. + """ + + def __init__(self, **kwargs): + assert "single_object_mode" not in kwargs and "object_type" not in kwargs, "invalid set of arguments" + super().__init__(single_object_mode=2, object_type="cereal", **kwargs) + + +class PickPlaceCan(PickPlace): + """ + Easier version of task - place one can into its bin. + """ + + def __init__(self, **kwargs): + assert "single_object_mode" not in kwargs and "object_type" not in kwargs, "invalid set of arguments" + super().__init__(single_object_mode=2, object_type="can", **kwargs) diff --git a/third_party/robosuite/robosuite/environments/manipulation/stack.py b/third_party/robosuite/robosuite/environments/manipulation/stack.py new file mode 100644 index 0000000000000000000000000000000000000000..1fc0f389ac68d3d56e36aee2985a49449c75897e --- /dev/null +++ b/third_party/robosuite/robosuite/environments/manipulation/stack.py @@ -0,0 +1,499 @@ +from collections import OrderedDict + +import numpy as np + +from robosuite.environments.manipulation.manipulation_env import ManipulationEnv +from robosuite.models.arenas import TableArena +from robosuite.models.objects import BoxObject +from robosuite.models.tasks import ManipulationTask +from robosuite.utils.mjcf_utils import CustomMaterial +from robosuite.utils.observables import Observable, sensor +from robosuite.utils.placement_samplers import UniformRandomSampler +from robosuite.utils.transform_utils import convert_quat + + +class Stack(ManipulationEnv): + """ + This class corresponds to the stacking task for a single robot arm. + + Args: + robots (str or list of str): Specification for specific robot arm(s) to be instantiated within this env + (e.g: "Sawyer" would generate one arm; ["Panda", "Panda", "Sawyer"] would generate three robot arms) + Note: Must be a single single-arm robot! + + env_configuration (str): Specifies how to position the robots within the environment (default is "default"). + For most single arm environments, this argument has no impact on the robot setup. + + controller_configs (str or list of dict): If set, contains relevant controller parameters for creating a + custom controller. Else, uses the default controller for this specific task. Should either be single + dict if same controller is to be used for all robots or else it should be a list of the same length as + "robots" param + + gripper_types (str or list of str): type of gripper, used to instantiate + gripper models from gripper factory. Default is "default", which is the default grippers(s) associated + with the robot(s) the 'robots' specification. None removes the gripper, and any other (valid) model + overrides the default gripper. Should either be single str if same gripper type is to be used for all + robots or else it should be a list of the same length as "robots" param + + initialization_noise (dict or list of dict): Dict containing the initialization noise parameters. + The expected keys and corresponding value types are specified below: + + :`'magnitude'`: The scale factor of uni-variate random noise applied to each of a robot's given initial + joint positions. Setting this value to `None` or 0.0 results in no noise being applied. + If "gaussian" type of noise is applied then this magnitude scales the standard deviation applied, + If "uniform" type of noise is applied then this magnitude sets the bounds of the sampling range + :`'type'`: Type of noise to apply. Can either specify "gaussian" or "uniform" + + Should either be single dict if same noise value is to be used for all robots or else it should be a + list of the same length as "robots" param + + :Note: Specifying "default" will automatically use the default noise settings. + Specifying None will automatically create the required dict with "magnitude" set to 0.0. + + table_full_size (3-tuple): x, y, and z dimensions of the table. + + table_friction (3-tuple): the three mujoco friction parameters for + the table. + + use_camera_obs (bool): if True, every observation includes rendered image(s) + + use_object_obs (bool): if True, include object (cube) information in + the observation. + + reward_scale (None or float): Scales the normalized reward function by the amount specified. + If None, environment reward remains unnormalized + + reward_shaping (bool): if True, use dense rewards. + + placement_initializer (ObjectPositionSampler): if provided, will + be used to place objects on every reset, else a UniformRandomSampler + is used by default. + + has_renderer (bool): If true, render the simulation state in + a viewer instead of headless mode. + + has_offscreen_renderer (bool): True if using off-screen rendering + + render_camera (str): Name of camera to render if `has_renderer` is True. Setting this value to 'None' + will result in the default angle being applied, which is useful as it can be dragged / panned by + the user using the mouse + + render_collision_mesh (bool): True if rendering collision meshes in camera. False otherwise. + + render_visual_mesh (bool): True if rendering visual meshes in camera. False otherwise. + + render_gpu_device_id (int): corresponds to the GPU device id to use for offscreen rendering. + Defaults to -1, in which case the device will be inferred from environment variables + (GPUS or CUDA_VISIBLE_DEVICES). + + control_freq (float): how many control signals to receive in every second. This sets the amount of + simulation time that passes between every action input. + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + + horizon (int): Every episode lasts for exactly @horizon timesteps. + + ignore_done (bool): True if never terminating the environment (ignore @horizon). + + hard_reset (bool): If True, re-loads model, sim, and render object upon a reset call, else, + only calls sim.reset and resets all robosuite-internal variables + + camera_names (str or list of str): name of camera to be rendered. Should either be single str if + same name is to be used for all cameras' rendering or else it should be a list of cameras to render. + + :Note: At least one camera must be specified if @use_camera_obs is True. + + :Note: To render all robots' cameras of a certain type (e.g.: "robotview" or "eye_in_hand"), use the + convention "all-{name}" (e.g.: "all-robotview") to automatically render all camera images from each + robot's camera list). + + camera_heights (int or list of int): height of camera frame. Should either be single int if + same height is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_widths (int or list of int): width of camera frame. Should either be single int if + same width is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_depths (bool or list of bool): True if rendering RGB-D, and RGB otherwise. Should either be single + bool if same depth setting is to be used for all cameras or else it should be a list of the same length as + "camera names" param. + + camera_segmentations (None or str or list of str or list of list of str): Camera segmentation(s) to use + for each camera. Valid options are: + + `None`: no segmentation sensor used + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + + If not None, multiple types of segmentations can be specified. A [list of str / str or None] specifies + [multiple / a single] segmentation(s) to use for all cameras. A list of list of str specifies per-camera + segmentation setting(s) to use. + + Raises: + AssertionError: [Invalid number of robots specified] + """ + + def __init__( + self, + robots, + env_configuration="default", + controller_configs=None, + gripper_types="default", + initialization_noise="default", + table_full_size=(0.8, 0.8, 0.05), + table_friction=(1.0, 5e-3, 1e-4), + use_camera_obs=True, + use_object_obs=True, + reward_scale=1.0, + reward_shaping=False, + placement_initializer=None, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + lite_physics=True, + horizon=1000, + ignore_done=False, + hard_reset=True, + camera_names="agentview", + camera_heights=256, + camera_widths=256, + camera_depths=False, + camera_segmentations=None, # {None, instance, class, element} + renderer="mjviewer", + renderer_config=None, + ): + # settings for table top + self.table_full_size = table_full_size + self.table_friction = table_friction + self.table_offset = np.array((0, 0, 0.8)) + + # reward configuration + self.reward_scale = reward_scale + self.reward_shaping = reward_shaping + + # whether to use ground-truth object states + self.use_object_obs = use_object_obs + + # object placement initializer + self.placement_initializer = placement_initializer + + super().__init__( + robots=robots, + env_configuration=env_configuration, + controller_configs=controller_configs, + base_types="default", + gripper_types=gripper_types, + initialization_noise=initialization_noise, + use_camera_obs=use_camera_obs, + has_renderer=has_renderer, + has_offscreen_renderer=has_offscreen_renderer, + render_camera=render_camera, + render_collision_mesh=render_collision_mesh, + render_visual_mesh=render_visual_mesh, + render_gpu_device_id=render_gpu_device_id, + control_freq=control_freq, + lite_physics=lite_physics, + horizon=horizon, + ignore_done=ignore_done, + hard_reset=hard_reset, + camera_names=camera_names, + camera_heights=camera_heights, + camera_widths=camera_widths, + camera_depths=camera_depths, + camera_segmentations=camera_segmentations, + renderer=renderer, + renderer_config=renderer_config, + ) + + def reward(self, action): + """ + Reward function for the task. + + Sparse un-normalized reward: + + - a discrete reward of 2.0 is provided if the red block is stacked on the green block + + Un-normalized components if using reward shaping: + + - Reaching: in [0, 0.25], to encourage the arm to reach the cube + - Grasping: in {0, 0.25}, non-zero if arm is grasping the cube + - Lifting: in {0, 1}, non-zero if arm has lifted the cube + - Aligning: in [0, 0.5], encourages aligning one cube over the other + - Stacking: in {0, 2}, non-zero if cube is stacked on other cube + + The reward is max over the following: + + - Reaching + Grasping + - Lifting + Aligning + - Stacking + + The sparse reward only consists of the stacking component. + + Note that the final reward is normalized and scaled by + reward_scale / 2.0 as well so that the max score is equal to reward_scale + + Args: + action (np array): [NOT USED] + + Returns: + float: reward value + """ + r_reach, r_lift, r_stack = self.staged_rewards() + if self.reward_shaping: + reward = max(r_reach, r_lift, r_stack) + else: + reward = 2.0 if r_stack > 0 else 0.0 + + if self.reward_scale is not None: + reward *= self.reward_scale / 2.0 + + return reward + + def staged_rewards(self): + """ + Helper function to calculate staged rewards based on current physical states. + + Returns: + 3-tuple: + + - (float): reward for reaching and grasping + - (float): reward for lifting and aligning + - (float): reward for stacking + """ + # reaching is successful when the gripper site is close to the center of the cube + cubeA_pos = self.sim.data.body_xpos[self.cubeA_body_id] + cubeB_pos = self.sim.data.body_xpos[self.cubeB_body_id] + dist = min( + [ + np.linalg.norm(self.sim.data.site_xpos[self.robots[0].eef_site_id[arm]] - cubeA_pos) + for arm in self.robots[0].arms + ] + ) + r_reach = (1 - np.tanh(10.0 * dist)) * 0.25 + + # grasping reward + grasping_cubeA = self._check_grasp(gripper=self.robots[0].gripper, object_geoms=self.cubeA) + if grasping_cubeA: + r_reach += 0.25 + + # lifting is successful when the cube is above the table top by a margin + cubeA_height = cubeA_pos[2] + table_height = self.table_offset[2] + cubeA_lifted = cubeA_height > table_height + 0.04 + r_lift = 1.0 if cubeA_lifted else 0.0 + + # Aligning is successful when cubeA is right above cubeB + if cubeA_lifted: + horiz_dist = np.linalg.norm(np.array(cubeA_pos[:2]) - np.array(cubeB_pos[:2])) + r_lift += 0.5 * (1 - np.tanh(horiz_dist)) + + # stacking is successful when the block is lifted and the gripper is not holding the object + r_stack = 0 + cubeA_touching_cubeB = self.check_contact(self.cubeA, self.cubeB) + if not grasping_cubeA and r_lift > 0 and cubeA_touching_cubeB: + r_stack = 2.0 + + return r_reach, r_lift, r_stack + + def _load_model(self): + """ + Loads an xml model, puts it in self.model + """ + super()._load_model() + + # Adjust base pose accordingly + xpos = self.robots[0].robot_model.base_xpos_offset["table"](self.table_full_size[0]) + self.robots[0].robot_model.set_base_xpos(xpos) + + # load model for table top workspace + mujoco_arena = TableArena( + table_full_size=self.table_full_size, + table_friction=self.table_friction, + table_offset=self.table_offset, + ) + + # Arena always gets set to zero origin + mujoco_arena.set_origin([0, 0, 0]) + + # initialize objects of interest + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "1 1", + "specular": "0.4", + "shininess": "0.1", + } + redwood = CustomMaterial( + texture="WoodRed", + tex_name="redwood", + mat_name="redwood_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + greenwood = CustomMaterial( + texture="WoodGreen", + tex_name="greenwood", + mat_name="greenwood_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.cubeA = BoxObject( + name="cubeA", + size_min=[0.02, 0.02, 0.02], + size_max=[0.02, 0.02, 0.02], + rgba=[1, 0, 0, 1], + material=redwood, + ) + self.cubeB = BoxObject( + name="cubeB", + size_min=[0.025, 0.025, 0.025], + size_max=[0.025, 0.025, 0.025], + rgba=[0, 1, 0, 1], + material=greenwood, + ) + cubes = [self.cubeA, self.cubeB] + # Create placement initializer + if self.placement_initializer is not None: + self.placement_initializer.reset() + self.placement_initializer.add_objects(cubes) + else: + self.placement_initializer = UniformRandomSampler( + name="ObjectSampler", + mujoco_objects=cubes, + x_range=[-0.08, 0.08], + y_range=[-0.08, 0.08], + rotation=None, + ensure_object_boundary_in_range=False, + ensure_valid_placement=True, + reference_pos=self.table_offset, + z_offset=0.01, + ) + + # task includes arena, robot, and objects of interest + self.model = ManipulationTask( + mujoco_arena=mujoco_arena, + mujoco_robots=[robot.robot_model for robot in self.robots], + mujoco_objects=cubes, + ) + + def _setup_references(self): + """ + Sets up references to important components. A reference is typically an + index or a list of indices that point to the corresponding elements + in a flatten array, which is how MuJoCo stores physical simulation data. + """ + super()._setup_references() + + # Additional object references from this env + self.cubeA_body_id = self.sim.model.body_name2id(self.cubeA.root_body) + self.cubeB_body_id = self.sim.model.body_name2id(self.cubeB.root_body) + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + super()._reset_internal() + + # Reset all object positions using initializer sampler if we're not directly loading from an xml + if not self.deterministic_reset: + + # Sample from the placement initializer for all objects + object_placements = self.placement_initializer.sample() + + # Loop through all objects and reset their positions + for obj_pos, obj_quat, obj in object_placements.values(): + self.sim.data.set_joint_qpos(obj.joints[0], np.concatenate([np.array(obj_pos), np.array(obj_quat)])) + + def _setup_observables(self): + """ + Sets up observables to be used for this environment. Creates object-based observables if enabled + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + observables = super()._setup_observables() + + # low-level object information + if self.use_object_obs: + # define observables modality + modality = "object" + + # position and rotation of the first cube + @sensor(modality=modality) + def cubeA_pos(obs_cache): + return np.array(self.sim.data.body_xpos[self.cubeA_body_id]) + + @sensor(modality=modality) + def cubeA_quat(obs_cache): + return convert_quat(np.array(self.sim.data.body_xquat[self.cubeA_body_id]), to="xyzw") + + @sensor(modality=modality) + def cubeB_pos(obs_cache): + return np.array(self.sim.data.body_xpos[self.cubeB_body_id]) + + @sensor(modality=modality) + def cubeB_quat(obs_cache): + return convert_quat(np.array(self.sim.data.body_xquat[self.cubeB_body_id]), to="xyzw") + + @sensor(modality=modality) + def cubeA_to_cubeB(obs_cache): + return ( + obs_cache["cubeB_pos"] - obs_cache["cubeA_pos"] + if "cubeA_pos" in obs_cache and "cubeB_pos" in obs_cache + else np.zeros(3) + ) + + arm_prefixes = self._get_arm_prefixes(self.robots[0], include_robot_name=False) + full_prefixes = self._get_arm_prefixes(self.robots[0]) + + sensors = [cubeA_pos, cubeA_quat, cubeB_pos, cubeB_quat, cubeA_to_cubeB] + sensors += [ + self._get_obj_eef_sensor(full_pf, f"{cube}_pos", f"{arm_pf}gripper_to_{cube}", modality) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + for cube in ["cubeA", "cubeB"] + ] + names = [s.__name__ for s in sensors] + + # Create observables + for name, s in zip(names, sensors): + observables[name] = Observable( + name=name, + sensor=s, + sampling_rate=self.control_freq, + ) + + return observables + + def _check_success(self): + """ + Check if blocks are stacked correctly. + + Returns: + bool: True if blocks are correctly stacked + """ + _, _, r_stack = self.staged_rewards() + return r_stack > 0 + + def visualize(self, vis_settings): + """ + In addition to super call, visualize gripper site proportional to the distance to the cube. + + Args: + vis_settings (dict): Visualization keywords mapped to T/F, determining whether that specific + component should be visualized. Should have "grippers" keyword as well as any other relevant + options specified. + """ + # Run superclass method first + super().visualize(vis_settings=vis_settings) + + # Color the gripper visualization site according to its distance to the cube + if vis_settings["grippers"]: + self._visualize_gripper_to_target(gripper=self.robots[0].gripper, target=self.cubeA) diff --git a/third_party/robosuite/robosuite/environments/manipulation/tool_hang.py b/third_party/robosuite/robosuite/environments/manipulation/tool_hang.py new file mode 100644 index 0000000000000000000000000000000000000000..7705450b5b979e19fa7c9c8e4f825a19d7075ac8 --- /dev/null +++ b/third_party/robosuite/robosuite/environments/manipulation/tool_hang.py @@ -0,0 +1,728 @@ +from collections import OrderedDict + +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.environments.manipulation.manipulation_env import ManipulationEnv +from robosuite.models.arenas import TableArena +from robosuite.models.objects import HookFrame, RatchetingWrenchObject, StandWithMount +from robosuite.models.tasks import ManipulationTask +from robosuite.utils.mjcf_utils import CustomMaterial +from robosuite.utils.observables import Observable, sensor +from robosuite.utils.placement_samplers import SequentialCompositeSampler, UniformRandomSampler +from robosuite.utils.sim_utils import check_contact + + +class ToolHang(ManipulationEnv): + """ + This class corresponds to the tool hang task for a single robot arm. + + Args: + robots (str or list of str): Specification for specific robot arm(s) to be instantiated within this env + (e.g: "Sawyer" would generate one arm; ["Panda", "Panda", "Sawyer"] would generate three robot arms) + Note: Must be a single single-arm robot! + + env_configuration (str): Specifies how to position the robots within the environment (default is "default"). + For most single arm environments, this argument has no impact on the robot setup. + + controller_configs (str or list of dict): If set, contains relevant controller parameters for creating a + custom controller. Else, uses the default controller for this specific task. Should either be single + dict if same controller is to be used for all robots or else it should be a list of the same length as + "robots" param + + gripper_types (str or list of str): type of gripper, used to instantiate + gripper models from gripper factory. Default is "default", which is the default grippers(s) associated + with the robot(s) the 'robots' specification. None removes the gripper, and any other (valid) model + overrides the default gripper. Should either be single str if same gripper type is to be used for all + robots or else it should be a list of the same length as "robots" param + + initialization_noise (dict or list of dict): Dict containing the initialization noise parameters. + The expected keys and corresponding value types are specified below: + + :`'magnitude'`: The scale factor of uni-variate random noise applied to each of a robot's given initial + joint positions. Setting this value to `None` or 0.0 results in no noise being applied. + If "gaussian" type of noise is applied then this magnitude scales the standard deviation applied, + If "uniform" type of noise is applied then this magnitude sets the bounds of the sampling range + :`'type'`: Type of noise to apply. Can either specify "gaussian" or "uniform" + + Should either be single dict if same noise value is to be used for all robots or else it should be a + list of the same length as "robots" param + + :Note: Specifying "default" will automatically use the default noise settings. + Specifying None will automatically create the required dict with "magnitude" set to 0.0. + + table_full_size (3-tuple): x, y, and z dimensions of the table. + + table_friction (3-tuple): the three mujoco friction parameters for + the table. + + use_camera_obs (bool): if True, every observation includes rendered image(s) + + use_object_obs (bool): if True, include object (cube) information in + the observation. + + reward_scale (None or float): Scales the normalized reward function by the amount specified. + If None, environment reward remains unnormalized + + reward_shaping (bool): if True, use dense rewards. + + has_renderer (bool): If true, render the simulation state in + a viewer instead of headless mode. + + has_offscreen_renderer (bool): True if using off-screen rendering + + render_camera (str): Name of camera to render if `has_renderer` is True. Setting this value to 'None' + will result in the default angle being applied, which is useful as it can be dragged / panned by + the user using the mouse + + render_collision_mesh (bool): True if rendering collision meshes in camera. False otherwise. + + render_visual_mesh (bool): True if rendering visual meshes in camera. False otherwise. + + render_gpu_device_id (int): corresponds to the GPU device id to use for offscreen rendering. + Defaults to -1, in which case the device will be inferred from environment variables + (GPUS or CUDA_VISIBLE_DEVICES). + + control_freq (float): how many control signals to receive in every second. This sets the amount of + simulation time that passes between every action input. + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + + horizon (int): Every episode lasts for exactly @horizon timesteps. + + ignore_done (bool): True if never terminating the environment (ignore @horizon). + + hard_reset (bool): If True, re-loads model, sim, and render object upon a reset call, else, + only calls sim.reset and resets all robosuite-internal variables + + camera_names (str or list of str): name of camera to be rendered. Should either be single str if + same name is to be used for all cameras' rendering or else it should be a list of cameras to render. + + :Note: At least one camera must be specified if @use_camera_obs is True. + + :Note: To render all robots' cameras of a certain type (e.g.: "robotview" or "eye_in_hand"), use the + convention "all-{name}" (e.g.: "all-robotview") to automatically render all camera images from each + robot's camera list). + + camera_heights (int or list of int): height of camera frame. Should either be single int if + same height is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_widths (int or list of int): width of camera frame. Should either be single int if + same width is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_depths (bool or list of bool): True if rendering RGB-D, and RGB otherwise. Should either be single + bool if same depth setting is to be used for all cameras or else it should be a list of the same length as + "camera names" param. + + camera_segmentations (None or str or list of str or list of list of str): Camera segmentation(s) to use + for each camera. Valid options are: + + `None`: no segmentation sensor used + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + + If not None, multiple types of segmentations can be specified. A [list of str / str or None] specifies + [multiple / a single] segmentation(s) to use for all cameras. A list of list of str specifies per-camera + segmentation setting(s) to use. + + Raises: + AssertionError: [Invalid number of robots specified] + """ + + def __init__( + self, + robots, + env_configuration="default", + controller_configs=None, + gripper_types="default", + initialization_noise="default", + table_full_size=(0.8, 0.8, 0.05), + table_friction=(1.0, 5e-3, 1e-4), + use_camera_obs=True, + use_object_obs=True, + reward_scale=1.0, + reward_shaping=False, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + lite_physics=True, + horizon=1000, + ignore_done=False, + hard_reset=True, + camera_names="agentview", + camera_heights=256, + camera_widths=256, + camera_depths=False, + camera_segmentations=None, # {None, instance, class, element} + renderer="mjviewer", + renderer_config=None, + ): + # settings for table top + self.table_full_size = table_full_size + self.table_friction = table_friction + self.table_offset = np.array((0, 0, 0.8)) + + # reward configuration + self.reward_scale = reward_scale + self.reward_shaping = reward_shaping + + # whether to use ground-truth object states + self.use_object_obs = use_object_obs + + super().__init__( + robots=robots, + env_configuration=env_configuration, + controller_configs=controller_configs, + base_types="default", + gripper_types=gripper_types, + initialization_noise=initialization_noise, + use_camera_obs=use_camera_obs, + has_renderer=has_renderer, + has_offscreen_renderer=has_offscreen_renderer, + render_camera=render_camera, + render_collision_mesh=render_collision_mesh, + render_visual_mesh=render_visual_mesh, + render_gpu_device_id=render_gpu_device_id, + control_freq=control_freq, + lite_physics=lite_physics, + horizon=horizon, + ignore_done=ignore_done, + hard_reset=hard_reset, + camera_names=camera_names, + camera_heights=camera_heights, + camera_widths=camera_widths, + camera_depths=camera_depths, + camera_segmentations=camera_segmentations, + renderer=renderer, + renderer_config=renderer_config, + ) + + def reward(self, action=None): + """ + Reward function for the task. + + Args: + action (np array): [NOT USED] + + Returns: + float: reward value + """ + reward = 0.0 + + # sparse completion reward + if self._check_success(): + reward = 1.0 + + # Scale reward if requested + if self.reward_scale is not None: + reward *= self.reward_scale + + return reward + + def _load_model(self): + """ + Loads an xml model, puts it in self.model + + Made some aspects easier than the real world task: + - increase base thickness for stand + - increase mount width to 1.2 cm + - add hole visualization + - reduce hook height on stand a little + - reduce tool ends height a little + """ + super()._load_model() + + # Adjust base pose accordingly + xpos = self.robots[0].robot_model.base_xpos_offset["table"](self.table_full_size[0]) + self.robots[0].robot_model.set_base_xpos(xpos) + + # load model for table top workspace + mujoco_arena = TableArena( + table_full_size=self.table_full_size, + table_friction=self.table_friction, + table_offset=self.table_offset, + ) + + # Arena always gets set to zero origin + mujoco_arena.set_origin([0, 0, 0]) + + # Modify default agentview camera + mujoco_arena.set_camera( + camera_name="agentview", + pos=[0.4837275266036987, 0.2505579098815722, 1.2639379055124524], + quat=[0.39713290333747864, 0.27807527780532837, 0.5016612410545349, 0.7164464592933655], + ) + + # Add sideview + mujoco_arena.set_camera( + camera_name="sideview", + pos=[0.4837275266036987, 0.2505579098815722, 1.2139379055124524], + quat=[0.39713290333747864, 0.27807527780532837, 0.5016612410545349, 0.7164464592933655], + ) + + # Create stand, frame, and tool + self.stand_args = dict( + name="stand", + size=( + (12.0 / 100.0), + (14.0 / 100.0), + (16.0 / 100.0), + ), # 14 cm x 12 cm base, with 16 cm height (in real world we cut the 32 cm height stand in half as well) + mount_location=(0.0, (4.5 / 100.0)), # 2.5 cm from right edge, so 4.5 cm to the right + mount_width=(1.2 / 100.0), # 1.2 cm thickness for rod cavity + wall_thickness=(0.1 / 100.0), # about 0.1-0.2 cm thickness for walls + base_thickness=(1 / 100.0), # increased thickness to 1 cm (different from real) + initialize_on_side=False, + add_hole_vis=True, + density=50000.0, + solref=(0.02, 1.0), + solimp=(0.998, 0.998, 0.001), + ) + self.stand = StandWithMount(**self.stand_args) + + self.frame_args = dict( + name="frame", + frame_length=(9.5 / 100.0), # 9.5 cm wide + frame_height=(18.0 / 100.0), # 18 cm tall (in real world we cut the physical 36 cm rod in half as well) + frame_thickness=(0.75 / 100.0), # 0.75 cm thick + hook_height=(1.2 / 100.0), # lowered to 1.2 cm tall (instead of 1.7 cm in real world) + grip_location=((9.0 - 3.0) / 100.0) + - (0.75 / 200.0), # move up by half height of frame minus half height of grip minus half thickness + grip_size=((2.54 / 200.0), (6.35 / 200.0)), # 6.35 cm length, 2.54 cm thick + tip_size=( + (2.54 / 200.0), + (0.2 / 200.0), + (0.65 / 200.0), + (1.905 / 100.0), + ), # 1-inch cylinder, 0.65 inch solder tip + density=500.0, + solref=(0.02, 1.0), + solimp=(0.998, 0.998, 0.001), + ) + self.frame = HookFrame(**self.frame_args) + + self.real_tool_args = dict( + name="tool", + handle_size=( + (16.5 / 200.0), + (1.75 / 200.0), + (0.32 / 200.0), + ), # 16.5 cm length, 1.75 cm width, 0.32 cm thick (1.5 cm with foam) + outer_radius_1=(3.5 / 200.0), # larger hole 3.5 cm outer diameter + inner_radius_1=(2.1 / 200.0), # reduced larger hole 2.1 cm inner diameter (from real world 2.3 cm) + height_1=(0.7 / 200.0), # 0.7 cm height + outer_radius_2=(3.0 / 200.0), # smaller hole 3 cm outer diameter + inner_radius_2=(2.0 / 200.0), # smaller hole 2 cm outer diameter + height_2=(0.7 / 200.0), # 0.7 cm height + ngeoms=8, + grip_size=((3 / 200.0), (8.0 / 200.0)), # 8 cm length, 3 cm thick + density=2000.0, + solref=(0.02, 1.0), + solimp=(0.998, 0.998, 0.001), + friction=(0.95, 0.3, 0.1), + ) + + self.tool_args = self.real_tool_args + self.tool = RatchetingWrenchObject(**self.tool_args) + + # Create placement initializer + self._get_placement_initializer() + + # task includes arena, robot, and objects of interest + self.model = ManipulationTask( + mujoco_arena=mujoco_arena, + mujoco_robots=[robot.robot_model for robot in self.robots], + mujoco_objects=[self.stand, self.frame, self.tool], + ) + + def _get_placement_initializer(self): + """ + Helper function for defining placement initializer and object sampling bounds + """ + # Create placement initializer + self.placement_initializer = SequentialCompositeSampler(name="ObjectSampler") + + # Pre-define settings for each object's placement + objects = [self.stand, self.frame, self.tool] + x_centers = [-self.table_full_size[0] * 0.1, -self.table_full_size[0] * 0.05, self.table_full_size[0] * 0.05] + y_centers = [0.0, -self.table_full_size[1] * 0.3, -self.table_full_size[1] * 0.25] + x_tols = [0.0, 0.02, 0.02] + y_tols = [0.0, 0.02, 0.02] + rot_centers = [0, (-np.pi / 2) + (np.pi / 6), (-np.pi / 2) - (np.pi / 9.0)] + rot_tols = [0.0, np.pi / 18, np.pi / 18.0] + rot_axes = ["z", "y", "z"] + z_offsets = [ + 0.001, + (self.frame_args["frame_thickness"] - self.frame_args["frame_height"]) / 2.0 + + 0.001 + + (self.stand_args["base_thickness"] / 2.0) + + (self.frame_args["grip_size"][1]), + 0.001, + ] + if ("tip_size" in self.frame_args) and (self.frame_args["tip_size"] is not None): + z_offsets[1] -= self.frame_args["tip_size"][0] + 2.0 * self.frame_args["tip_size"][3] + for obj, x, y, x_tol, y_tol, r, r_tol, r_axis, z_offset in zip( + objects, x_centers, y_centers, x_tols, y_tols, rot_centers, rot_tols, rot_axes, z_offsets + ): + # Create sampler for this object and add it to the sequential sampler + self.placement_initializer.append_sampler( + sampler=UniformRandomSampler( + name=f"{obj.name}ObjectSampler", + mujoco_objects=obj, + x_range=[x - x_tol, x + x_tol], + y_range=[y - y_tol, y + y_tol], + rotation=[r - r_tol, r + r_tol], + rotation_axis=r_axis, + ensure_object_boundary_in_range=False, + ensure_valid_placement=False, + reference_pos=self.table_offset, + z_offset=z_offset, + ) + ) + + def _setup_references(self): + """ + Sets up references to important components. A reference is typically an + index or a list of indices that point to the corresponding elements + in a flatten array, which is how MuJoCo stores physical simulation data. + """ + super()._setup_references() + + # Additional object references from this env + self.obj_body_id = dict( + stand=self.sim.model.body_name2id(self.stand.root_body), + frame=self.sim.model.body_name2id(self.frame.root_body), + tool=self.sim.model.body_name2id(self.tool.root_body), + ) + + # Important sites: + # tool_hole1_center - for checking hanging + # frame_hang_site, frame_mount_site, frame_intersection_site - for orienting the hook, and checking hanging + # stand_mount_site - for checking that stand base is upright + self.obj_site_id = dict( + tool_hole1_center=self.sim.model.site_name2id("tool_hole1_center"), # center of one end of wrench + # tool_hole2_center=self.sim.model.site_name2id("tool_hole2_center"), # center of other end of wrench + frame_hang_site=self.sim.model.site_name2id("frame_hang_site"), # end of frame where hanging takes place + frame_mount_site=self.sim.model.site_name2id( + "frame_mount_site" + ), # bottom of frame that needs to be inserted into base + frame_intersection_site=self.sim.model.site_name2id("frame_intersection_site"), # corner of frame + stand_mount_site=self.sim.model.site_name2id( + "stand_mount_site" + ), # where frame needs to be inserted into stand + ) + if ("tip_size" in self.frame_args) and (self.frame_args["tip_size"] is not None): + self.obj_site_id["frame_tip_site"] = self.sim.model.site_name2id("frame_tip_site") # tip site for insertion + + # Important geoms: + # stand_base - for checking that stand base is upright + # stand wall geoms - for checking rod insertion into stand + # tool hole geoms - for checking insertion + self.obj_geom_id = dict( + stand_base=self.sim.model.geom_name2id("stand_base"), # bottom of stand + ) + for i in range(4): + self.obj_geom_id["stand_wall_{}".format(i)] = self.sim.model.geom_name2id("stand_wall{}".format(i)) + for i in range(self.tool_args["ngeoms"]): + self.obj_geom_id["tool_hole1_hc_{}".format(i)] = self.sim.model.geom_name2id("tool_hole1_hc_{}".format(i)) + + def _setup_observables(self): + """ + Sets up observables to be used for this environment. Creates object-based observables if enabled + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + observables = super()._setup_observables() + + # low-level object information + if self.use_object_obs: + # define observables modality + modality = "object" + + arm_prefixes = self._get_arm_prefixes(self.robots[0], include_robot_name=False) + full_prefixes = self._get_arm_prefixes(self.robots[0]) + sensors = [ + self._get_world_pose_in_gripper_sensor(full_pf, f"world_pose_in_{arm_pf}gripper", modality) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + names = [fn.__name__ for fn in sensors] + names = [fn.__name__ for fn in sensors] + actives = [False] * len(sensors) + + # Add absolute and relative pose for each object + obj_names = ["base", "frame", "tool"] + query_names = ["stand_base", "frame_intersection_site", "tool"] + query_types = ["geom", "site", "body"] + for i in range(len(obj_names)): + obj_sensors, obj_sensor_names = self._create_obj_sensors( + obj_name=obj_names[i], modality=modality, query_name=query_names[i], query_type=query_types[i] + ) + sensors += obj_sensors + names += obj_sensor_names + actives += [True] * len(obj_sensors) + + # Key boolean checks + @sensor(modality=modality) + def frame_is_assembled(obs_cache): + return [float(self._check_frame_assembled())] + + @sensor(modality=modality) + def tool_on_frame(obs_cache): + return [float(self._check_tool_on_frame())] + + sensors += [frame_is_assembled, tool_on_frame] + names += [frame_is_assembled.__name__, tool_on_frame.__name__] + actives += [True, True] + + # Create observables + for name, s, active in zip(names, sensors, actives): + observables[name] = Observable( + name=name, + sensor=s, + sampling_rate=self.control_freq, + active=active, + ) + + return observables + + def _create_obj_sensors(self, obj_name, modality="object", query_name=None, query_type="body"): + """ + Helper function to create sensors for a given object. This is abstracted in a separate function call so that we + don't have local function naming collisions during the _setup_observables() call. + + Args: + obj_name (str): Name of object to create sensors for (used for naming observations) + modality (str): Modality to assign to all sensors + query_name (str): Name to query mujoco for the pose attributes of this object - if None, use @obj_name + query_type (str): Either "body", "geom", or "site" - type of mujoco sensor that will be queried for pose + + Returns: + 2-tuple: + sensors (list): Array of sensors for the given obj + names (list): array of corresponding observable names + """ + if query_name is None: + query_name = obj_name + + assert query_type in ["body", "geom", "site"] + if query_type == "body": + id_lookup = self.obj_body_id + pos_lookup = self.sim.data.body_xpos + mat_lookup = self.sim.data.body_xmat + elif query_type == "geom": + id_lookup = self.obj_geom_id + pos_lookup = self.sim.data.geom_xpos + mat_lookup = self.sim.data.geom_xmat + else: + id_lookup = self.obj_site_id + pos_lookup = self.sim.data.site_xpos + mat_lookup = self.sim.data.site_xmat + + @sensor(modality=modality) + def obj_pos(obs_cache): + return np.array(pos_lookup[id_lookup[query_name]]) + + @sensor(modality=modality) + def obj_quat(obs_cache): + return T.mat2quat(np.array(mat_lookup[id_lookup[query_name]]).reshape(3, 3)) + + arm_prefixes = self._get_arm_prefixes(self.robots[0], include_robot_name=False) + full_prefixes = self._get_arm_prefixes(self.robots[0]) + + sensors = [ + self._get_rel_obj_eef_sensor(arm_pf, obj_name, f"{obj_name}_to_{full_pf}eef_pos", full_pf, modality) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + sensors += [ + self._get_obj_eef_rel_quat_sensor(full_pf, obj_name, f"{obj_name}_to_{full_pf}eef_quat", modality) + for full_pf in full_prefixes + ] + names = [fn.__name__ for fn in sensors] + sensors += [obj_pos, obj_quat] + names += [f"{obj_name}_pos", f"{obj_name}_quat"] + + return sensors, names + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + super()._reset_internal() + + # Reset all object positions using initializer sampler if we're not directly loading from an xml + if not self.deterministic_reset: + + # Sample from the placement initializer for all objects + object_placements = self.placement_initializer.sample() + + # Loop through all objects and reset their positions + for obj_pos, obj_quat, obj in object_placements.values(): + self.sim.data.set_joint_qpos(obj.joints[0], np.concatenate([np.array(obj_pos), np.array(obj_quat)])) + + def visualize(self, vis_settings): + """ + In addition to super call, visualize gripper site proportional to the distance to the cube. + + Args: + vis_settings (dict): Visualization keywords mapped to T/F, determining whether that specific + component should be visualized. Should have "grippers" keyword as well as any other relevant + options specified. + """ + # Run superclass method first + super().visualize(vis_settings=vis_settings) + + # Color the gripper visualization site according to its distance to the cube + if vis_settings["grippers"]: + self._visualize_gripper_to_target(gripper=self.robots[0].gripper, target=self.tool) + + def _check_success(self): + """ + Check if tool is hung on frame correctly and frame is assembled coorectly as well. + + Returns: + bool: True if tool is hung on frame correctly + """ + return self._check_frame_assembled() and self._check_tool_on_frame() + + def _check_frame_assembled(self): + """ + Check if the frame has been assembled correctly. This checks the following things: + (1) the base is upright + (2) the end of the hook frame is close enough to the base + (3) the hook frame is between the walls of the base + """ + + # position of base + base_pos = self.sim.data.geom_xpos[self.obj_geom_id["stand_base"]] + + # check (1): the base is upright. Just take the vector between two locations on the base shaft, and check + # that the angle to the z-axis is small, by computing the angle between that unit vector and + # the z-axis. Recall that for two unit vectors, the arccosine of the dot product gives the angle. + vec_along_base_shaft = self.sim.data.site_xpos[self.obj_site_id["stand_mount_site"]] - base_pos + vec_along_base_shaft = vec_along_base_shaft / np.linalg.norm(vec_along_base_shaft) + angle_to_z_axis = np.abs(np.arccos(vec_along_base_shaft[2])) + base_shaft_is_vertical = angle_to_z_axis < np.pi / 18.0 # less than 10 degrees + + # check (2): the end of the hook frame is close enough to the base. Just check the distance + if "frame_tip_site" in self.obj_site_id: + bottom_hook_pos = self.sim.data.site_xpos[self.obj_site_id["frame_tip_site"]] + else: + bottom_hook_pos = self.sim.data.site_xpos[self.obj_site_id["frame_mount_site"]] + insertion_dist = np.linalg.norm(bottom_hook_pos - base_pos) + # insertion_tolerance = (self.frame_args["frame_thickness"] / 2.) + insertion_tolerance = 0.05 # NOTE: this was manually tuned + bottom_is_close_enough = insertion_dist < insertion_tolerance + + # check (3): the hook frame is in between the walls of the base. Take the geom positions of opposing base walls + # and check that they are on opposite sides of the line defined by the hook frame. + + # normalized vector that points along the frame hook + hook_endpoint = self.sim.data.site_xpos[self.obj_site_id["frame_mount_site"]] + frame_hook_vec = self.sim.data.site_xpos[self.obj_site_id["frame_intersection_site"]] - hook_endpoint + frame_hook_length = np.linalg.norm(frame_hook_vec) + frame_hook_vec = frame_hook_vec / frame_hook_length + + # geom wall position vectors relative to base position + geom_positions = [ + self.sim.data.geom_xpos[self.obj_geom_id["stand_wall_{}".format(i)]] - hook_endpoint for i in range(4) + ] + + # take cross product of each point against the line, and then dot the result to see if + # the sign is positive or negative. If it is positive, then they are on the same side + # (visualize with right-hand-rule to see this) + rod_is_between_stand_walls = all( + [ + np.dot(np.cross(geom_positions[0], frame_hook_vec), np.cross(geom_positions[2], frame_hook_vec)) < 0, + np.dot(np.cross(geom_positions[1], frame_hook_vec), np.cross(geom_positions[3], frame_hook_vec)) < 0, + ] + ) + + return base_shaft_is_vertical and (bottom_is_close_enough and rod_is_between_stand_walls) + + def _check_tool_on_frame(self): + """ + Check if the tool has been hung on the frame correctly. This checks the following things: + (1) the robot is not touching the tool (it is hanging on its own) + (2) the tool hole is making contact with the frame hook + (3) the tool hole is close to the line defined by the frame hook + (4) either end of the tool hole are on opposite sides of the frame hook + (5) the tool hole is inserted far enough into the frame hook + """ + + # check (1): robot is not touching the tool + robot_grasp_geoms = [ + self.robots[0].gripper[arm].important_geoms[key] + for arm in self.robots[0].gripper + for key in self.robots[0].gripper[arm].important_geoms + ] + robot_and_tool_contact = False + for g_group in robot_grasp_geoms: + if check_contact(self.sim, g_group, self.tool.contact_geoms): + robot_and_tool_contact = True + break + + # check (2): the tool hole is making contact with the frame hook + all_tool_hole_geoms = ["tool_hole1_hc_{}".format(i) for i in range(self.tool_args["ngeoms"])] + frame_hook_geom = "frame_horizontal_frame" + frame_and_tool_hole_contact = check_contact(self.sim, all_tool_hole_geoms, frame_hook_geom) + + # check (3): compute distance from tool hole center to the line defined by the frame hook + + # normalized vector that points along the frame hook + hook_endpoint = self.sim.data.site_xpos[self.obj_site_id["frame_hang_site"]] + frame_hook_vec = self.sim.data.site_xpos[self.obj_site_id["frame_intersection_site"]] - hook_endpoint + frame_hook_length = np.linalg.norm(frame_hook_vec) + frame_hook_vec = frame_hook_vec / frame_hook_length + + # compute orthogonal projection of tool hole point to get distance to frame hook line + # (see https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Vector_formulation) + tool_hole_center = self.sim.data.site_xpos[self.obj_site_id["tool_hole1_center"]] + tool_hole_vec = tool_hole_center - hook_endpoint + tool_hole_dot = np.dot(tool_hole_vec, frame_hook_vec) + tool_hole_proj = tool_hole_dot * frame_hook_vec + tool_hole_ortho_proj = tool_hole_vec - tool_hole_proj + dist_to_frame_hook_line = np.linalg.norm(tool_hole_ortho_proj) + + # distance needs to be less than the difference between the inner tool hole radius and the half-length of the frame hook box geom + tool_hole_is_close_enough = dist_to_frame_hook_line < ( + self.tool_args["inner_radius_1"] - (self.frame_args["frame_thickness"] / 2.0) + ) + + # check (4): take two opposite geoms around the tool hole, and check that they are on opposite sides of the frame hook line + # to guarantee that insertion has taken place + g2_id = self.tool_args["ngeoms"] // 2 # get geom opposite geom 0 + g1_pos = self.sim.data.geom_xpos[self.obj_geom_id["tool_hole1_hc_0"]] + g2_pos = self.sim.data.geom_xpos[self.obj_geom_id["tool_hole1_hc_{}".format(g2_id)]] + + # take cross product of each point against the line, and then dot the result to see if + # the sign is positive or negative. If it is positive, then they are on the same side + # (visualize with right-hand-rule to see this) + g1_vec = g1_pos - hook_endpoint + g2_vec = g2_pos - hook_endpoint + tool_is_between_hook = np.dot(np.cross(g1_vec, frame_hook_vec), np.cross(g2_vec, frame_hook_vec)) < 0 + + # check (5): check if tool insertion is far enough - check this by computing normalized distance of projection along frame hook line. + # We ensure that it's at least 5% inserted along the length of the frame hook. + normalized_dist_along_frame_hook_line = tool_hole_dot / frame_hook_length + tool_is_inserted_far_enough = (normalized_dist_along_frame_hook_line > 0.05) and ( + normalized_dist_along_frame_hook_line < 1.0 + ) + + return all( + [ + (not robot_and_tool_contact), + frame_and_tool_hole_contact, + tool_hole_is_close_enough, + tool_is_between_hook, + tool_is_inserted_far_enough, + ] + ) diff --git a/third_party/robosuite/robosuite/environments/manipulation/two_arm_env.py b/third_party/robosuite/robosuite/environments/manipulation/two_arm_env.py new file mode 100644 index 0000000000000000000000000000000000000000..ff3f7612df5751c0e8007a4918c9b270be6340b4 --- /dev/null +++ b/third_party/robosuite/robosuite/environments/manipulation/two_arm_env.py @@ -0,0 +1,146 @@ +import numpy as np + +from robosuite.environments.manipulation.manipulation_env import ManipulationEnv +from robosuite.utils.robot_utils import check_bimanual +from robosuite.utils.transform_utils import mat2quat + + +class TwoArmEnv(ManipulationEnv): + """ + A manipulation environment intended for two robot arms. + """ + + # Dictionary which maps the old configuration names to the new configuration names. + # This is used to maintain backwards compatibility with past environment configurations. + _PREV_CONFIG_TO_NEW_CONFIG = { + "single-arm-opposed": "opposed", + "single-arm-parallel": "parallel", + } + + def _check_robot_configuration(self, robots): + """ + Sanity check to make sure the inputted robots and configuration is acceptable + + Args: + robots (str or list of str): Robots to instantiate within this env + """ + super()._check_robot_configuration(robots) + if self.env_configuration in self._PREV_CONFIG_TO_NEW_CONFIG: + self.env_configuration = self._PREV_CONFIG_TO_NEW_CONFIG[self.env_configuration] + robots = robots if type(robots) == list or type(robots) == tuple else [robots] + + # Process single robot and 2 robot cases separately + if len(robots) == 1: + if not check_bimanual(robots[0]): + raise ValueError("Error: If inputting a single robot, it must be bimanual.") + # Automatically set the configuration to single-robot if one robot is given + self.env_configuration = "single-robot" + elif len(robots) == 2: + if self.env_configuration == "default": + self.env_configuration = "opposed" + + # Check that the configuration is valid + if not (self.env_configuration == "opposed" or self.env_configuration == "parallel"): + # This is an unknown env configuration, print error + raise ValueError( + "Error: Unknown environment configuration received. Only 'opposed', 'parallel', " + "are supported. Got: {}".format(self.env_configuration) + ) + else: + raise ValueError( + "Error: Invalid number of robots received. Expected either 1 bimanual robot or 2 of any type of robots." + ) + + def _gripper0_to_target(self, target, target_type="body", return_distance=False): + """ + Returns the distance/distance vector between gripper0 and target. If there is only one robot, + gripper0 is the right gripper of the first robot. Otherwise, it is the gripper(s) of the + first robot and the returned distance is the minimum distance between the gripper(s) and the target. + + Args: + target (MujocoModel or str): Either a site / geom / body name, or a model that serves as the target. + If a model is given, then the root body will be used as the target. + target_type (str): One of {"body", "geom", or "site"}, corresponding to the type of element @target + refers to. + return_distance (bool): If set, will return Euclidean distance instead of Cartesian distance + + Returns: + np.array or float: (Cartesian or Euclidean) distance from gripper to target + """ + + if self.env_configuration == "single-robot": + return self._gripper_to_target(self.robots[0].gripper["right"], target, target_type, return_distance) + else: + return self._gripper_to_target(self.robots[0].gripper, target, target_type, return_distance) + + def _gripper1_to_target(self, target, target_type="body", return_distance=False): + """ + Returns the distance/distance vector between gripper1 and target. If there is only one robot, + gripper1 is the left gripper of the first robot. Otherwise, it is the gripper(s) of the + second robot and the returned distance is the minimum distance between the gripper(s) and the target. + + Args: + target (MujocoModel or str): Either a site / geom / body name, or a model that serves as the target. + If a model is given, then the root body will be used as the target. + target_type (str): One of {"body", "geom", or "site"}, corresponding to the type of element @target + refers to. + return_distance (bool): If set, will return Euclidean distance instead of Cartesian distance + + Returns: + np.array or float: (Cartesian or Euclidean) distance from gripper to target + """ + + if self.env_configuration == "single-robot": + return self._gripper_to_target(self.robots[0].gripper["left"], target, target_type, return_distance) + else: + return self._gripper_to_target(self.robots[1].gripper, target, target_type, return_distance) + + @property + def _eef0_xpos(self): + """ + Grab the position of Robot 0's right end effector. + + Returns: + np.array: (x,y,z) position of EEF0 + """ + + return np.array(self.sim.data.site_xpos[self.robots[0].eef_site_id["right"]]) + + @property + def _eef1_xpos(self): + """ + Grab the position of Robot 1's end effector. + + Returns: + np.array: (x,y,z) position of EEF1 + """ + if self.env_configuration == "single-robot": + return np.array(self.sim.data.site_xpos[self.robots[0].eef_site_id["left"]]) + else: + # right is the default first arm + return np.array(self.sim.data.site_xpos[self.robots[1].eef_site_id["right"]]) + + @property + def _eef0_xmat(self): + """ + Right End Effector 0 orientation as a rotation matrix + Note that this draws the orientation from the "ee" site, NOT the gripper site, since the gripper + orientations are inconsistent! + + Returns: + np.array: (3,3) orientation matrix for EEF0 + """ + pf = self.robots[0].gripper["right"].naming_prefix + return np.array(self.sim.data.site_xmat[self.sim.model.site_name2id(pf + "grip_site")]).reshape(3, 3) + + @property + def _eef0_xquat(self): + """ + Right End Effector 0 orientation as a (x,y,z,w) quaternion + Note that this draws the orientation from the "ee" site, NOT the gripper site, since the gripper + orientations are inconsistent! + + Returns: + np.array: (x,y,z,w) quaternion for EEF0 + """ + return mat2quat(self._eef0_xmat) diff --git a/third_party/robosuite/robosuite/environments/manipulation/two_arm_handover.py b/third_party/robosuite/robosuite/environments/manipulation/two_arm_handover.py new file mode 100644 index 0000000000000000000000000000000000000000..7f60e309fba572a798ded2c72a0f25e43d092d11 --- /dev/null +++ b/third_party/robosuite/robosuite/environments/manipulation/two_arm_handover.py @@ -0,0 +1,618 @@ +from collections import OrderedDict + +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.environments.manipulation.two_arm_env import TwoArmEnv +from robosuite.models.arenas import TableArena +from robosuite.models.objects import HammerObject +from robosuite.models.tasks import ManipulationTask +from robosuite.utils.observables import Observable, sensor +from robosuite.utils.placement_samplers import UniformRandomSampler + + +class TwoArmHandover(TwoArmEnv): + """ + This class corresponds to the handover task for two robot arms. + + Args: + robots (str or list of str): Specification for specific robot(s) + Note: Must be either 2 robots or 1 bimanual robot! + + env_configuration (str): Specifies how to position the robots within the environment if two robots inputted. Can be either: + + :`'parallel'`: Sets up the two robots next to each other on the -x side of the table + :`'opposed'`: Sets up the two robots opposed from each others on the opposite +/-y sides of the table. + + Note that "default" "opposed" if two robots are used. + + controller_configs (str or list of dict): If set, contains relevant controller parameters for creating a + custom controller. Else, uses the default controller for this specific task. Should either be single + dict if same controller is to be used for all robots or else it should be a list of the same length as + "robots" param + + gripper_types (str or list of str): type of gripper, used to instantiate + gripper models from gripper factory. Default is "default", which is the default grippers(s) associated + with the robot(s) the 'robots' specification. None removes the gripper, and any other (valid) model + overrides the default gripper. Should either be single str if same gripper type is to be used for all + robots or else it should be a list of the same length as "robots" param + + initialization_noise (dict or list of dict): Dict containing the initialization noise parameters. + The expected keys and corresponding value types are specified below: + + :`'magnitude'`: The scale factor of uni-variate random noise applied to each of a robot's given initial + joint positions. Setting this value to `None` or 0.0 results in no noise being applied. + If "gaussian" type of noise is applied then this magnitude scales the standard deviation applied, + If "uniform" type of noise is applied then this magnitude sets the bounds of the sampling range + :`'type'`: Type of noise to apply. Can either specify "gaussian" or "uniform" + + Should either be single dict if same noise value is to be used for all robots or else it should be a + list of the same length as "robots" param + + :Note: Specifying "default" will automatically use the default noise settings. + Specifying None will automatically create the required dict with "magnitude" set to 0.0. + + prehensile (bool): If true, handover object starts on the table. Else, the object starts in Arm0's gripper + + table_full_size (3-tuple): x, y, and z dimensions of the table. + + table_friction (3-tuple): the three mujoco friction parameters for + the table. + + use_camera_obs (bool): if True, every observation includes rendered image(s) + + use_object_obs (bool): if True, include object (cube) information in + the observation. + + reward_scale (None or float): Scales the normalized reward function by the amount specified. + If None, environment reward remains unnormalized + + reward_shaping (bool): if True, use dense rewards. + + placement_initializer (ObjectPositionSampler): if provided, will + be used to place objects on every reset, else a UniformRandomSampler + is used by default. + + has_renderer (bool): If true, render the simulation state in + a viewer instead of headless mode. + + has_offscreen_renderer (bool): True if using off-screen rendering + + render_camera (str): Name of camera to render if `has_renderer` is True. Setting this value to 'None' + will result in the default angle being applied, which is useful as it can be dragged / panned by + the user using the mouse + + render_collision_mesh (bool): True if rendering collision meshes in camera. False otherwise. + + render_visual_mesh (bool): True if rendering visual meshes in camera. False otherwise. + + render_gpu_device_id (int): corresponds to the GPU device id to use for offscreen rendering. + Defaults to -1, in which case the device will be inferred from environment variables + (GPUS or CUDA_VISIBLE_DEVICES). + + control_freq (float): how many control signals to receive in every second. This sets the amount of + simulation time that passes between every action input. + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + + horizon (int): Every episode lasts for exactly @horizon timesteps. + + ignore_done (bool): True if never terminating the environment (ignore @horizon). + + hard_reset (bool): If True, re-loads model, sim, and render object upon a reset call, else, + only calls sim.reset and resets all robosuite-internal variables + + camera_names (str or list of str): name of camera to be rendered. Should either be single str if + same name is to be used for all cameras' rendering or else it should be a list of cameras to render. + + :Note: At least one camera must be specified if @use_camera_obs is True. + + :Note: To render all robots' cameras of a certain type (e.g.: "robotview" or "eye_in_hand"), use the + convention "all-{name}" (e.g.: "all-robotview") to automatically render all camera images from each + robot's camera list). + + camera_heights (int or list of int): height of camera frame. Should either be single int if + same height is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_widths (int or list of int): width of camera frame. Should either be single int if + same width is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_depths (bool or list of bool): True if rendering RGB-D, and RGB otherwise. Should either be single + bool if same depth setting is to be used for all cameras or else it should be a list of the same length as + "camera names" param. + + camera_segmentations (None or str or list of str or list of list of str): Camera segmentation(s) to use + for each camera. Valid options are: + + `None`: no segmentation sensor used + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + + If not None, multiple types of segmentations can be specified. A [list of str / str or None] specifies + [multiple / a single] segmentation(s) to use for all cameras. A list of list of str specifies per-camera + segmentation setting(s) to use. + + Raises: + ValueError: [Invalid number of robots specified] + ValueError: [Invalid env configuration] + ValueError: [Invalid robots for specified env configuration] + """ + + def __init__( + self, + robots, + env_configuration="default", + controller_configs=None, + gripper_types="default", + initialization_noise="default", + prehensile=True, + table_full_size=(0.8, 1.2, 0.05), + table_friction=(1.0, 5e-3, 1e-4), + use_camera_obs=True, + use_object_obs=True, + reward_scale=1.0, + reward_shaping=False, + placement_initializer=None, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + lite_physics=True, + horizon=1000, + ignore_done=False, + hard_reset=True, + camera_names="agentview", + camera_heights=256, + camera_widths=256, + camera_depths=False, + camera_segmentations=None, # {None, instance, class, element} + renderer="mjviewer", + renderer_config=None, + ): + # Task settings + self.prehensile = prehensile + + # settings for table top + self.table_full_size = table_full_size + self.table_true_size = list(table_full_size) + self.table_true_size[1] *= 0.25 # true size will only be partially wide + self.table_friction = table_friction + self.table_offset = [0, self.table_full_size[1] * (-3 / 8), 0.8] + + # reward configuration + self.reward_scale = reward_scale + self.reward_shaping = reward_shaping + self.height_threshold = 0.1 # threshold above the table surface which the hammer is considered lifted + + # whether to use ground-truth object states + self.use_object_obs = use_object_obs + + # object placement initializer + self.placement_initializer = placement_initializer + + super().__init__( + robots=robots, + env_configuration=env_configuration, + controller_configs=controller_configs, + base_types="default", + gripper_types=gripper_types, + initialization_noise=initialization_noise, + use_camera_obs=use_camera_obs, + has_renderer=has_renderer, + has_offscreen_renderer=has_offscreen_renderer, + render_camera=render_camera, + render_collision_mesh=render_collision_mesh, + render_visual_mesh=render_visual_mesh, + render_gpu_device_id=render_gpu_device_id, + control_freq=control_freq, + lite_physics=lite_physics, + horizon=horizon, + ignore_done=ignore_done, + hard_reset=hard_reset, + camera_names=camera_names, + camera_heights=camera_heights, + camera_widths=camera_widths, + camera_depths=camera_depths, + camera_segmentations=camera_segmentations, + renderer=renderer, + renderer_config=renderer_config, + ) + + def reward(self, action=None): + """ + Reward function for the task. + + Sparse un-normalized reward: + + - a discrete reward of 2.0 is provided when only Arm 1 is gripping the handle and has the handle + lifted above a certain threshold + + Un-normalized max-wise components if using reward shaping: + + - Arm0 Reaching: (1) in [0, 0.25] proportional to the distance between Arm 0 and the handle + - Arm0 Grasping: (2) in {0, 0.5}, nonzero if Arm 0 is gripping the hammer (any part). + - Arm0 Lifting: (3) in {0, 1.0}, nonzero if Arm 0 lifts the handle from the table past a certain threshold + - Arm0 Hovering: (4) in {0, [1.0, 1.25]}, nonzero only if Arm0 is actively lifting the hammer, and is + proportional to the distance between the handle and Arm 1 + conditioned on the handle being lifted from the table and being grasped by Arm 0 + - Mutual Grasping: (5) in {0, 1.5}, nonzero if both Arm 0 and Arm 1 are gripping the hammer (Arm 1 must be + gripping the handle) while lifted above the table + - Handover: (6) in {0, 2.0}, nonzero when only Arm 1 is gripping the handle and has the handle + lifted above the table + + Note that the final reward is normalized and scaled by reward_scale / 2.0 as + well so that the max score is equal to reward_scale + + Args: + action (np array): [NOT USED] + + Returns: + float: reward value + """ + # Initialize reward + reward = 0 + + # use a shaping reward if specified + if self.reward_shaping: + # Grab relevant parameters + arm0_grasp_any, arm1_grasp_handle, hammer_height, table_height = self._get_task_info() + # First, we'll consider the cases if the hammer is lifted above the threshold (step 3 - 6) + if hammer_height - table_height > self.height_threshold: + # Split cases depending on whether arm1 is currently grasping the handle or not + if arm1_grasp_handle: + # Check if arm0 is grasping + if arm0_grasp_any: + # This is step 5 + reward = 1.5 + else: + # This is step 6 (completed task!) + reward = 2.0 + # This is the case where only arm0 is grasping (step 2-3) + else: + reward = 1.0 + # Add in up to 0.25 based on distance between handle and arm1 + dist = np.linalg.norm(self._gripper_1_to_handle) + reaching_reward = 0.25 * (1 - np.tanh(1.0 * dist)) + reward += reaching_reward + # Else, the hammer is still on the ground ): + else: + # Split cases depending on whether arm0 is currently grasping the handle or not + if arm0_grasp_any: + # This is step 2 + reward = 0.5 + else: + # This is step 1, we want to encourage arm0 to reach for the handle + dist = np.linalg.norm(self._gripper_0_to_handle) + reaching_reward = 0.25 * (1 - np.tanh(1.0 * dist)) + reward = reaching_reward + + # Else this is the sparse reward setting + else: + # Provide reward if only Arm 1 is grasping the hammer and the handle lifted above the pre-defined threshold + if self._check_success(): + reward = 2.0 + + if self.reward_scale is not None: + reward *= self.reward_scale / 2.0 + + return reward + + def _load_model(self): + """ + Loads an xml model, puts it in self.model + """ + super()._load_model() + + # Adjust base pose(s) accordingly + if self.env_configuration == "single-robot": + xpos = self.robots[0].robot_model.base_xpos_offset["table"](self.table_full_size[0]) + self.robots[0].robot_model.set_base_xpos(xpos) + else: + if self.env_configuration == "opposed": + # Set up robots facing towards each other by rotating them from their default position + for robot, rotation, offset in zip(self.robots, (np.pi / 2, -np.pi / 2), (-0.25, 0.25)): + xpos = robot.robot_model.base_xpos_offset["table"](self.table_full_size[0]) + rot = np.array((0, 0, rotation)) + xpos = T.euler2mat(rot) @ np.array(xpos) + xpos += np.array((0, offset, 0)) + robot.robot_model.set_base_xpos(xpos) + robot.robot_model.set_base_ori(rot) + else: # "parallel" configuration setting + # Set up robots parallel to each other but offset from the center + for robot, offset in zip(self.robots, (-0.6, 0.6)): + xpos = robot.robot_model.base_xpos_offset["table"](self.table_full_size[0]) + xpos = np.array(xpos) + np.array((0, offset, 0)) + robot.robot_model.set_base_xpos(xpos) + + # load model for table top workspace + mujoco_arena = TableArena( + table_full_size=self.table_true_size, table_friction=self.table_friction, table_offset=self.table_offset + ) + + # Arena always gets set to zero origin + mujoco_arena.set_origin([0, 0, 0]) + + # Modify default agentview camera + mujoco_arena.set_camera( + camera_name="agentview", + pos=[0.8894354364730311, -3.481824231498976e-08, 1.7383813133506494], + quat=[0.6530981063842773, 0.2710406184196472, 0.27104079723358154, 0.6530979871749878], + ) + + # initialize objects of interest + self.hammer = HammerObject(name="hammer") + + # Create placement initializer + if self.placement_initializer is not None: + self.placement_initializer.reset() + self.placement_initializer.add_objects(self.hammer) + else: + # Set rotation about y-axis if hammer starts on table else rotate about z if it starts in gripper + rotation_axis = "y" if self.prehensile else "z" + self.placement_initializer = UniformRandomSampler( + name="ObjectSampler", + mujoco_objects=self.hammer, + x_range=[-0.1, 0.1], + y_range=[-0.05, 0.05], + rotation=None, + rotation_axis=rotation_axis, + ensure_object_boundary_in_range=False, + ensure_valid_placement=True, + reference_pos=self.table_offset, + ) + + # task includes arena, robot, and objects of interest + self.model = ManipulationTask( + mujoco_arena=mujoco_arena, + mujoco_robots=[robot.robot_model for robot in self.robots], + mujoco_objects=self.hammer, + ) + + def _setup_references(self): + """ + Sets up references to important components. A reference is typically an + index or a list of indices that point to the corresponding elements + in a flatten array, which is how MuJoCo stores physical simulation data. + """ + super()._setup_references() + + # Hammer object references from this env + self.hammer_body_id = self.sim.model.body_name2id(self.hammer.root_body) + self.hammer_handle_geom_id = self.sim.model.geom_name2id(self.hammer.handle_geoms[0]) + + # General env references + self.table_top_id = self.sim.model.site_name2id("table_top") + + def _setup_observables(self): + """ + Sets up observables to be used for this environment. Creates object-based observables if enabled + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + observables = super()._setup_observables() + + # low-level object information + if self.use_object_obs: + modality = "object" + + # position and rotation of hammer + @sensor(modality=modality) + def hammer_pos(obs_cache): + return np.array(self._hammer_pos) + + @sensor(modality=modality) + def hammer_quat(obs_cache): + return np.array(self._hammer_quat) + + @sensor(modality=modality) + def handle_xpos(obs_cache): + return np.array(self._handle_xpos) + + sensors = [hammer_pos, hammer_quat, handle_xpos] + names = [s.__name__ for s in sensors] + arm_sensor_fns = [] + if self.env_configuration == "single-robot": + # If single-robot, we only have one robot. gripper 0 is always right and gripper 1 is always left + pf0 = self.robots[0].robot_model.naming_prefix + "right_" + pf1 = self.robots[0].robot_model.naming_prefix + "left_" + prefixes = [pf0, pf1] + arm_sensor_fns = [ + self._get_obj_eef_sensor(full_pf, f"handle_xpos", f"gripper{i}_to_handle", modality) + for i, full_pf in enumerate(prefixes) + ] + else: + # If not single-robot, we have two robots. gripper 0 is always the first robot's gripper and + # gripper 1 is always the second robot's gripper. However, must account for the fact that + # each robot may have multiple arms/grippers + robot_arm_prefixes = [self._get_arm_prefixes(robot, include_robot_name=False) for robot in self.robots] + robot_full_prefixes = [self._get_arm_prefixes(robot, include_robot_name=True) for robot in self.robots] + for i, (arm_prefixes, full_prefixes) in enumerate(zip(robot_arm_prefixes, robot_full_prefixes)): + arm_sensor_fns += [ + self._get_obj_eef_sensor(full_pf, f"handle_xpos", f"{arm_pf}gripper{i}_to_handle", modality) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + + sensors += arm_sensor_fns + names += [s.__name__ for s in arm_sensor_fns] + + # Create observables + for name, s in zip(names, sensors): + observables[name] = Observable( + name=name, + sensor=s, + sampling_rate=self.control_freq, + ) + + return observables + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + super()._reset_internal() + + # Reset all object positions using initializer sampler if we're not directly loading from an xml + if not self.deterministic_reset: + + # Sample from the placement initializer for all objects + object_placements = self.placement_initializer.sample() + + # Loop through all objects and reset their positions + for obj_pos, obj_quat, obj in object_placements.values(): + # If prehensile, set the object normally + if self.prehensile: + self.sim.data.set_joint_qpos(obj.joints[0], np.concatenate([np.array(obj_pos), np.array(obj_quat)])) + # Else, set the object in the hand of the robot and loop a few steps to guarantee the robot is grasping + # the object initially + else: + eef_rot_quat = T.mat2quat(T.euler2mat([np.pi - T.mat2euler(self._eef0_xmat)[2], 0, 0])) + obj_quat = T.quat_multiply(obj_quat, eef_rot_quat) + for j in range(100): + # Set object in hand always placing it in the right gripper + self.sim.data.set_joint_qpos( + obj.joints[0], np.concatenate([self._eef0_xpos, np.array(obj_quat)]) + ) + # Close gripper (action = 1) and prevent arm from moving + if self.env_configuration == "single-robot": + # Execute no-op action with gravity compensation + torques = np.concatenate( + [ + self.robots[0].part_controllers["right"].torque_compensation, + self.robots[0].part_controllers["left"].torque_compensation, + ] + ) + self.sim.data.ctrl[self.robots[0]._ref_arm_joint_actuator_indexes] = torques + else: + robot_noops = [ + np.concatenate([robot.controller[arm].torque_compensation for arm in robot.arms]) + for robot in self.robots + ] + + # Execute no-op action with gravity compensation + self.sim.data.ctrl[self.robots[0]._ref_arm_joint_actuator_indexes] = robot_noops[0] + self.sim.data.ctrl[self.robots[1]._ref_arm_joint_actuator_indexes] = robot_noops[1] + # Execute gripper action + gripper_ac = [1] * self.robots[0].gripper["right"].dof + gripper_ac = self.robots[0].gripper["right"].format_action(gripper_ac) + self.robots[0].part_controllers["right_gripper"].set_goal(gripper_ac) + # Take forward step + self.sim.step() + + def _get_task_info(self): + """ + Helper function that grabs the current relevant locations of objects of interest within the environment + + Returns: + 4-tuple: + + - (bool) True if Arm0 is grasping any part of the hammer + - (bool) True if Arm1 is grasping the hammer handle + - (float) Height of the hammer body + - (float) Height of the table surface + """ + # Get height of hammer and table and define height threshold + hammer_angle_offset = (self.hammer.handle_length / 2 + 2 * self.hammer.head_halfsize) * np.sin( + self._hammer_angle + ) + hammer_height = ( + self.sim.data.geom_xpos[self.hammer_handle_geom_id][2] - self.hammer.top_offset[2] - hammer_angle_offset + ) + table_height = self.sim.data.site_xpos[self.table_top_id][2] + + # Check if any Arm's gripper is grasping the hammer handle + (g0, g1) = ( + (self.robots[0].gripper["right"], self.robots[0].gripper["left"]) + if self.env_configuration == "single-robot" + else (self.robots[0].gripper, self.robots[1].gripper) + ) + arm0_grasp_any = self._check_grasp(gripper=g0, object_geoms=self.hammer) + arm1_grasp_handle = self._check_grasp(gripper=g1, object_geoms=self.hammer.handle_geoms) + + # Return all relevant values + return arm0_grasp_any, arm1_grasp_handle, hammer_height, table_height + + def _check_success(self): + """ + Check if hammer is successfully handed off + + Returns: + bool: True if handover has been completed + """ + # Grab relevant params + arm0_grasp_any, arm1_grasp_handle, hammer_height, table_height = self._get_task_info() + return ( + True + if arm1_grasp_handle and not arm0_grasp_any and hammer_height - table_height > self.height_threshold + else False + ) + + @property + def _handle_xpos(self): + """ + Grab the position of the hammer handle. + + Returns: + np.array: (x,y,z) position of handle + """ + return self.sim.data.geom_xpos[self.hammer_handle_geom_id] + + @property + def _hammer_pos(self): + """ + Grab the position of the hammer body. + + Returns: + np.array: (x,y,z) position of body + """ + return np.array(self.sim.data.body_xpos[self.hammer_body_id]) + + @property + def _hammer_quat(self): + """ + Grab the orientation of the hammer body. + + Returns: + np.array: (x,y,z,w) quaternion of the hammer body + """ + return T.convert_quat(self.sim.data.body_xquat[self.hammer_body_id], to="xyzw") + + @property + def _hammer_angle(self): + """ + Calculate the angle of hammer with the ground, relative to it resting horizontally + + Returns: + float: angle in radians + """ + mat = T.quat2mat(self._hammer_quat) + z_unit = [0, 0, 1] + z_rotated = np.matmul(mat, z_unit) + return np.pi / 2 - np.arccos(np.dot(z_unit, z_rotated)) + + @property + def _gripper_0_to_handle(self): + """ + Calculate vector from gripper0 to the hammer handle. + + Returns: + np.array: (dx,dy,dz) distance vector between handle and EEF0 + """ + return self._gripper0_to_target(self.hammer.handle_geoms[0], target_type="geom") + + @property + def _gripper_1_to_handle(self): + """ + Calculate vector from gripper1 to the hammer handle. + + Returns: + np.array: (dx,dy,dz) distance vector between handle and EEF1 + """ + return self._gripper1_to_target(self.hammer.handle_geoms[0], target_type="geom") diff --git a/third_party/robosuite/robosuite/environments/manipulation/two_arm_lift.py b/third_party/robosuite/robosuite/environments/manipulation/two_arm_lift.py new file mode 100644 index 0000000000000000000000000000000000000000..94ffa5f2046e56d6902792beff0d34251c07b26c --- /dev/null +++ b/third_party/robosuite/robosuite/environments/manipulation/two_arm_lift.py @@ -0,0 +1,548 @@ +from collections import OrderedDict + +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.environments.manipulation.two_arm_env import TwoArmEnv +from robosuite.models.arenas import TableArena +from robosuite.models.objects import PotWithHandlesObject +from robosuite.models.tasks import ManipulationTask +from robosuite.utils.observables import Observable, sensor +from robosuite.utils.placement_samplers import UniformRandomSampler + + +class TwoArmLift(TwoArmEnv): + """ + This class corresponds to the lifting task for two robot arms. + + Args: + robots (str or list of str): Specification for specific robot(s) + Note: Must be either 2 robots or 1 bimanual robot! + + env_configuration (str): Specifies how to position the robots within the environment if two robots inputted. Can be either: + + :`'parallel'`: Sets up the two robots next to each other on the -x side of the table + :`'opposed'`: Sets up the two robots opposed from each others on the opposite +/-y sides of the table. + + Note that "default" "opposed" if two robots are used. + + controller_configs (str or list of dict): If set, contains relevant controller parameters for creating a + custom controller. Else, uses the default controller for this specific task. Should either be single + dict if same controller is to be used for all robots or else it should be a list of the same length as + "robots" param + + gripper_types (str or list of str): type of gripper, used to instantiate + gripper models from gripper factory. Default is "default", which is the default grippers(s) associated + with the robot(s) the 'robots' specification. None removes the gripper, and any other (valid) model + overrides the default gripper. Should either be single str if same gripper type is to be used for all + robots or else it should be a list of the same length as "robots" param + + initialization_noise (dict or list of dict): Dict containing the initialization noise parameters. + The expected keys and corresponding value types are specified below: + + :`'magnitude'`: The scale factor of uni-variate random noise applied to each of a robot's given initial + joint positions. Setting this value to `None` or 0.0 results in no noise being applied. + If "gaussian" type of noise is applied then this magnitude scales the standard deviation applied, + If "uniform" type of noise is applied then this magnitude sets the bounds of the sampling range + :`'type'`: Type of noise to apply. Can either specify "gaussian" or "uniform" + + Should either be single dict if same noise value is to be used for all robots or else it should be a + list of the same length as "robots" param + + :Note: Specifying "default" will automatically use the default noise settings. + Specifying None will automatically create the required dict with "magnitude" set to 0.0. + + table_full_size (3-tuple): x, y, and z dimensions of the table. + + table_friction (3-tuple): the three mujoco friction parameters for + the table. + + use_camera_obs (bool): if True, every observation includes rendered image(s) + + use_object_obs (bool): if True, include object (cube) information in + the observation. + + reward_scale (None or float): Scales the normalized reward function by the amount specified. + If None, environment reward remains unnormalized + + reward_shaping (bool): if True, use dense rewards. + + placement_initializer (ObjectPositionSampler): if provided, will + be used to place objects on every reset, else a UniformRandomSampler + is used by default. + + has_renderer (bool): If true, render the simulation state in + a viewer instead of headless mode. + + has_offscreen_renderer (bool): True if using off-screen rendering + + render_camera (str): Name of camera to render if `has_renderer` is True. Setting this value to 'None' + will result in the default angle being applied, which is useful as it can be dragged / panned by + the user using the mouse + + render_collision_mesh (bool): True if rendering collision meshes in camera. False otherwise. + + render_visual_mesh (bool): True if rendering visual meshes in camera. False otherwise. + + render_gpu_device_id (int): corresponds to the GPU device id to use for offscreen rendering. + Defaults to -1, in which case the device will be inferred from environment variables + (GPUS or CUDA_VISIBLE_DEVICES). + + control_freq (float): how many control signals to receive in every second. This sets the amount of + simulation time that passes between every action input. + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + + horizon (int): Every episode lasts for exactly @horizon timesteps. + + ignore_done (bool): True if never terminating the environment (ignore @horizon). + + hard_reset (bool): If True, re-loads model, sim, and render object upon a reset call, else, + only calls sim.reset and resets all robosuite-internal variables + + camera_names (str or list of str): name of camera to be rendered. Should either be single str if + same name is to be used for all cameras' rendering or else it should be a list of cameras to render. + + :Note: At least one camera must be specified if @use_camera_obs is True. + + :Note: To render all robots' cameras of a certain type (e.g.: "robotview" or "eye_in_hand"), use the + convention "all-{name}" (e.g.: "all-robotview") to automatically render all camera images from each + robot's camera list). + + camera_heights (int or list of int): height of camera frame. Should either be single int if + same height is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_widths (int or list of int): width of camera frame. Should either be single int if + same width is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_depths (bool or list of bool): True if rendering RGB-D, and RGB otherwise. Should either be single + bool if same depth setting is to be used for all cameras or else it should be a list of the same length as + "camera names" param. + + camera_segmentations (None or str or list of str or list of list of str): Camera segmentation(s) to use + for each camera. Valid options are: + + `None`: no segmentation sensor used + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + + If not None, multiple types of segmentations can be specified. A [list of str / str or None] specifies + [multiple / a single] segmentation(s) to use for all cameras. A list of list of str specifies per-camera + segmentation setting(s) to use. + + Raises: + ValueError: [Invalid number of robots specified] + ValueError: [Invalid env configuration] + ValueError: [Invalid robots for specified env configuration] + """ + + def __init__( + self, + robots, + env_configuration="default", + controller_configs=None, + gripper_types="default", + initialization_noise="default", + table_full_size=(0.8, 0.8, 0.05), + table_friction=(1.0, 5e-3, 1e-4), + use_camera_obs=True, + use_object_obs=True, + reward_scale=1.0, + reward_shaping=False, + placement_initializer=None, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + lite_physics=True, + horizon=1000, + ignore_done=False, + hard_reset=True, + camera_names="agentview", + camera_heights=256, + camera_widths=256, + camera_depths=False, + camera_segmentations=None, # {None, instance, class, element} + renderer="mjviewer", + renderer_config=None, + ): + # settings for table top + self.table_full_size = table_full_size + self.table_friction = table_friction + self.table_offset = np.array((0, 0, 0.8)) + + # reward configuration + self.reward_scale = reward_scale + self.reward_shaping = reward_shaping + + # whether to use ground-truth object states + self.use_object_obs = use_object_obs + + # object placement initializer + self.placement_initializer = placement_initializer + + super().__init__( + robots=robots, + env_configuration=env_configuration, + controller_configs=controller_configs, + base_types="default", + gripper_types=gripper_types, + initialization_noise=initialization_noise, + use_camera_obs=use_camera_obs, + has_renderer=has_renderer, + has_offscreen_renderer=has_offscreen_renderer, + render_camera=render_camera, + render_collision_mesh=render_collision_mesh, + render_visual_mesh=render_visual_mesh, + render_gpu_device_id=render_gpu_device_id, + control_freq=control_freq, + lite_physics=lite_physics, + horizon=horizon, + ignore_done=ignore_done, + hard_reset=hard_reset, + camera_names=camera_names, + camera_heights=camera_heights, + camera_widths=camera_widths, + camera_depths=camera_depths, + camera_segmentations=camera_segmentations, + renderer=renderer, + renderer_config=renderer_config, + ) + + def reward(self, action=None): + """ + Reward function for the task. + + Sparse un-normalized reward: + + - a discrete reward of 3.0 is provided if the pot is lifted and is parallel within 30 deg to the table + + Un-normalized summed components if using reward shaping: + + - Reaching: in [0, 0.5], per-arm component that is proportional to the distance between each arm and its + respective pot handle, and exactly 0.5 when grasping the handle + - Note that the agent only gets the lifting reward when flipping no more than 30 degrees. + - Grasping: in {0, 0.25}, binary per-arm component awarded if the gripper is grasping its correct handle + - Lifting: in [0, 1.5], proportional to the pot's height above the table, and capped at a certain threshold + + Note that the final reward is normalized and scaled by reward_scale / 3.0 as + well so that the max score is equal to reward_scale + + Args: + action (np array): [NOT USED] + + Returns: + float: reward value + """ + reward = 0 + + # check if the pot is tilted more than 30 degrees + mat = T.quat2mat(self._pot_quat) + z_unit = [0, 0, 1] + z_rotated = np.matmul(mat, z_unit) + cos_z = np.dot(z_unit, z_rotated) + cos_30 = np.cos(np.pi / 6) + direction_coef = 1 if cos_z >= cos_30 else 0 + + # check for goal completion: cube is higher than the table top above a margin + if self._check_success(): + reward = 3.0 * direction_coef + + # use a shaping reward + elif self.reward_shaping: + # lifting reward + pot_bottom_height = self.sim.data.site_xpos[self.pot_center_id][2] - self.pot.top_offset[2] + table_height = self.sim.data.site_xpos[self.table_top_id][2] + elevation = pot_bottom_height - table_height + r_lift = min(max(elevation - 0.05, 0), 0.15) + reward += 10.0 * direction_coef * r_lift + + _gripper0_to_handle0 = self._gripper0_to_handle0 + _gripper1_to_handle1 = self._gripper1_to_handle1 + + # gh stands for gripper-handle + # When grippers are far away, tell them to be closer + + # Get contacts + (g0, g1) = ( + (self.robots[0].gripper["right"], self.robots[0].gripper["left"]) + if self.env_configuration == "single-robot" + else (self.robots[0].gripper, self.robots[1].gripper) + ) + + _g0h_dist = np.linalg.norm(_gripper0_to_handle0) + _g1h_dist = np.linalg.norm(_gripper1_to_handle1) + + # Grasping reward + if self._check_grasp(gripper=g0, object_geoms=self.pot.handle0_geoms): + reward += 0.25 + # Reaching reward + reward += 0.5 * (1 - np.tanh(10.0 * _g0h_dist)) + + # Grasping reward + if self._check_grasp(gripper=g1, object_geoms=self.pot.handle1_geoms): + reward += 0.25 + # Reaching reward + reward += 0.5 * (1 - np.tanh(10.0 * _g1h_dist)) + + if self.reward_scale is not None: + reward *= self.reward_scale / 3.0 + + return reward + + def _load_model(self): + """ + Loads an xml model, puts it in self.model + """ + super()._load_model() + + # Adjust base pose(s) accordingly + if self.env_configuration == "single-robot": + xpos = self.robots[0].robot_model.base_xpos_offset["table"](self.table_full_size[0]) + self.robots[0].robot_model.set_base_xpos(xpos) + else: + if self.env_configuration == "opposed": + # Set up robots facing towards each other by rotating them from their default position + for robot, rotation in zip(self.robots, (np.pi / 2, -np.pi / 2)): + xpos = robot.robot_model.base_xpos_offset["table"](self.table_full_size[0]) + rot = np.array((0, 0, rotation)) + xpos = T.euler2mat(rot) @ np.array(xpos) + robot.robot_model.set_base_xpos(xpos) + robot.robot_model.set_base_ori(rot) + else: # "parallel" configuration setting + # Set up robots parallel to each other but offset from the center + for robot, offset in zip(self.robots, (-0.25, 0.25)): + xpos = robot.robot_model.base_xpos_offset["table"](self.table_full_size[0]) + xpos = np.array(xpos) + np.array((0, offset, 0)) + robot.robot_model.set_base_xpos(xpos) + + # load model for table top workspace + mujoco_arena = TableArena( + table_full_size=self.table_full_size, + table_friction=self.table_friction, + table_offset=self.table_offset, + ) + + # Arena always gets set to zero origin + mujoco_arena.set_origin([0, 0, 0]) + + # initialize objects of interest + self.pot = PotWithHandlesObject(name="pot") + + # Create placement initializer + if self.placement_initializer is not None: + self.placement_initializer.reset() + self.placement_initializer.add_objects(self.pot) + else: + self.placement_initializer = UniformRandomSampler( + name="ObjectSampler", + mujoco_objects=self.pot, + x_range=[-0.03, 0.03], + y_range=[-0.03, 0.03], + ensure_object_boundary_in_range=False, + ensure_valid_placement=True, + reference_pos=self.table_offset, + rotation=(np.pi + -np.pi / 3, np.pi + np.pi / 3), + ) + + # task includes arena, robot, and objects of interest + self.model = ManipulationTask( + mujoco_arena=mujoco_arena, + mujoco_robots=[robot.robot_model for robot in self.robots], + mujoco_objects=self.pot, + ) + + def _setup_references(self): + """ + Sets up references to important components. A reference is typically an + index or a list of indices that point to the corresponding elements + in a flatten array, which is how MuJoCo stores physical simulation data. + """ + super()._setup_references() + + # Additional object references from this env + self.pot_body_id = self.sim.model.body_name2id(self.pot.root_body) + self.handle0_site_id = self.sim.model.site_name2id(self.pot.important_sites["handle0"]) + self.handle1_site_id = self.sim.model.site_name2id(self.pot.important_sites["handle1"]) + self.table_top_id = self.sim.model.site_name2id("table_top") + self.pot_center_id = self.sim.model.site_name2id(self.pot.important_sites["center"]) + + def _setup_observables(self): + """ + Sets up observables to be used for this environment. Creates object-based observables if enabled + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + observables = super()._setup_observables() + + # low-level object information + if self.use_object_obs: + modality = "object" + + # position and rotation of object + + @sensor(modality=modality) + def pot_pos(obs_cache): + return np.array(self.sim.data.body_xpos[self.pot_body_id]) + + @sensor(modality=modality) + def pot_quat(obs_cache): + return T.convert_quat(self.sim.data.body_xquat[self.pot_body_id], to="xyzw") + + @sensor(modality=modality) + def handle0_xpos(obs_cache): + return np.array(self._handle0_xpos) + + @sensor(modality=modality) + def handle1_xpos(obs_cache): + return np.array(self._handle1_xpos) + + sensors = [pot_pos, pot_quat, handle0_xpos, handle1_xpos] + names = [s.__name__ for s in sensors] + + arm_sensor_fns = [] + if self.env_configuration == "single-robot": + # If single-robot, we only have one robot. gripper 0 is always right and gripper 1 is always left + pf0 = self.robots[0].robot_model.naming_prefix + "right_" + pf1 = self.robots[0].robot_model.naming_prefix + "left_" + prefixes = [pf0, pf1] + arm_sensor_fns = [ + self._get_obj_eef_sensor(full_pf, f"handle{i}_xpos", f"gripper{i}_to_handle{i}", modality) + for i, full_pf in enumerate(prefixes) + ] + else: + # If not single-robot, we have two robots. gripper 0 is always the first robot's gripper and + # gripper 1 is always the second robot's gripper. However, must account for the fact that + # each robot may have multiple arms/grippers + robot_arm_prefixes = [self._get_arm_prefixes(robot, include_robot_name=False) for robot in self.robots] + robot_full_prefixes = [self._get_arm_prefixes(robot, include_robot_name=True) for robot in self.robots] + for i, (arm_prefixes, full_prefixes) in enumerate(zip(robot_arm_prefixes, robot_full_prefixes)): + arm_sensor_fns += [ + self._get_obj_eef_sensor( + full_pf, f"handle{i}_xpos", f"{arm_pf}gripper{i}_to_handle{i}", modality + ) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + + sensors += arm_sensor_fns + names += [s.__name__ for s in arm_sensor_fns] + + # Create observables + for name, s in zip(names, sensors): + observables[name] = Observable( + name=name, + sensor=s, + sampling_rate=self.control_freq, + ) + + return observables + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + super()._reset_internal() + + # Reset all object positions using initializer sampler if we're not directly loading from an xml + if not self.deterministic_reset: + + # Sample from the placement initializer for all objects + object_placements = self.placement_initializer.sample() + + # Loop through all objects and reset their positions + for obj_pos, obj_quat, obj in object_placements.values(): + self.sim.data.set_joint_qpos(obj.joints[0], np.concatenate([np.array(obj_pos), np.array(obj_quat)])) + + def visualize(self, vis_settings): + """ + In addition to super call, visualize gripper site proportional to the distance to each handle. + + Args: + vis_settings (dict): Visualization keywords mapped to T/F, determining whether that specific + component should be visualized. Should have "grippers" keyword as well as any other relevant + options specified. + """ + # Run superclass method first + super().visualize(vis_settings=vis_settings) + + # Color the gripper visualization site according to its distance to each handle + if vis_settings["grippers"]: + handles = [self.pot.important_sites[f"handle{i}"] for i in range(2)] + grippers = ( + [self.robots[0].gripper[arm] for arm in self.robots[0].arms] + if self.env_configuration == "single-robot" + else [robot.gripper for robot in self.robots] + ) + for gripper, handle in zip(grippers, handles): + self._visualize_gripper_to_target(gripper=gripper, target=handle, target_type="site") + + def _check_success(self): + """ + Check if pot is successfully lifted + + Returns: + bool: True if pot is lifted + """ + pot_bottom_height = self.sim.data.site_xpos[self.pot_center_id][2] - self.pot.top_offset[2] + table_height = self.sim.data.site_xpos[self.table_top_id][2] + + # cube is higher than the table top above a margin + return pot_bottom_height > table_height + 0.10 + + @property + def _handle0_xpos(self): + """ + Grab the position of the left (blue) hammer handle. + + Returns: + np.array: (x,y,z) position of handle + """ + return self.sim.data.site_xpos[self.handle0_site_id] + + @property + def _handle1_xpos(self): + """ + Grab the position of the right (green) hammer handle. + + Returns: + np.array: (x,y,z) position of handle + """ + return self.sim.data.site_xpos[self.handle1_site_id] + + @property + def _pot_quat(self): + """ + Grab the orientation of the pot body. + + Returns: + np.array: (x,y,z,w) quaternion of the pot body + """ + return T.convert_quat(self.sim.data.body_xquat[self.pot_body_id], to="xyzw") + + @property + def _gripper0_to_handle0(self): + """ + Calculate vector from gripper0 to the left pot handle. + + Returns: + np.array: (dx,dy,dz) distance vector between handle and gripper0 + """ + return self._gripper0_to_target(self.pot.important_sites["handle0"], target_type="site") + + @property + def _gripper1_to_handle1(self): + """ + Calculate vector from gripper1 to the right pot handle. + + Returns: + np.array: (dx,dy,dz) distance vector between handle and EEF0 + """ + return self._gripper1_to_target(self.pot.important_sites["handle1"], target_type="site") diff --git a/third_party/robosuite/robosuite/environments/manipulation/two_arm_peg_in_hole.py b/third_party/robosuite/robosuite/environments/manipulation/two_arm_peg_in_hole.py new file mode 100644 index 0000000000000000000000000000000000000000..0aba4db74adbab7a3ef9c72005baaa60e3c642a3 --- /dev/null +++ b/third_party/robosuite/robosuite/environments/manipulation/two_arm_peg_in_hole.py @@ -0,0 +1,553 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.environments.manipulation.two_arm_env import TwoArmEnv +from robosuite.models.arenas import EmptyArena +from robosuite.models.objects import CylinderObject, PlateWithHoleObject +from robosuite.models.tasks import ManipulationTask +from robosuite.utils.mjcf_utils import CustomMaterial, array_to_string, find_elements +from robosuite.utils.observables import Observable, sensor + +""" +Offset functions for peg and hole objects. These are needed because the peg and +hole objects are placed on the robot relative to the robot's end effector. This +means that based on the position/orientation of the end-effector, the peg and +hole may require different offsets to be placed correctly. For example, some of +the humanoid robots are positioned such that changes in the z-direction result +in translations going in the opposite direction. Hence, we flip the sign of the +z-component of the offset for these robots. +""" +_flip_last_dim_fn = lambda offset: offset[:-1] + [-1 * offset[-1]] +_OBJECT_POS_OFFSET_FN = { + "GR1FloatingBody": { + "peg": _flip_last_dim_fn, + "hole": _flip_last_dim_fn, + }, + "GR1": { + "peg": _flip_last_dim_fn, + "hole": _flip_last_dim_fn, + }, + "G1": { + "peg": _flip_last_dim_fn, + "hole": _flip_last_dim_fn, + }, + "G1FloatingBody": {"peg": _flip_last_dim_fn, "hole": _flip_last_dim_fn}, +} + + +class TwoArmPegInHole(TwoArmEnv): + """ + This class corresponds to the peg-in-hole task for two robot arms. + + Args: + robots (str or list of str): Specification for specific robot(s) + Note: Must be either 2 robots or 1 bimanual robot! + + env_configuration (str): Specifies how to position the robots within the environment if two robots inputted. Can be either: + + :`'parallel'`: Sets up the two robots next to each other on the -x side of the table + :`'opposed'`: Sets up the two robots opposed from each others on the opposite +/-y sides of the table. + + Note that "default" "opposed" if two robots are used. + + controller_configs (str or list of dict): If set, contains relevant controller parameters for creating a + custom controller. Else, uses the default controller for this specific task. Should either be single + dict if same controller is to be used for all robots or else it should be a list of the same length as + "robots" param + + gripper_types (str or list of str): type of gripper, used to instantiate gripper models from gripper factory. + For this environment, setting a value other than the default (None) will raise an AssertionError, as + this environment is not meant to be used with any gripper at all. + + initialization_noise (dict or list of dict): Dict containing the initialization noise parameters. + The expected keys and corresponding value types are specified below: + + :`'magnitude'`: The scale factor of uni-variate random noise applied to each of a robot's given initial + joint positions. Setting this value to `None` or 0.0 results in no noise being applied. + If "gaussian" type of noise is applied then this magnitude scales the standard deviation applied, + If "uniform" type of noise is applied then this magnitude sets the bounds of the sampling range + :`'type'`: Type of noise to apply. Can either specify "gaussian" or "uniform" + + Should either be single dict if same noise value is to be used for all robots or else it should be a + list of the same length as "robots" param + + :Note: Specifying "default" will automatically use the default noise settings. + Specifying None will automatically create the required dict with "magnitude" set to 0.0. + + use_camera_obs (bool or list of bool): if True, every observation for a specific robot includes a rendered + image. Should either be single bool if camera obs value is to be used for all + robots or else it should be a list of the same length as "robots" param + + use_object_obs (bool): if True, include object (cube) information in + the observation. + + reward_scale (None or float): Scales the normalized reward function by the amount specified. + If None, environment reward remains unnormalized + + reward_shaping (bool): if True, use dense rewards. + + peg_radius (2-tuple): low and high limits of the (uniformly sampled) + radius of the peg + + peg_length (float): length of the peg + + has_renderer (bool): If true, render the simulation state in + a viewer instead of headless mode. + + has_offscreen_renderer (bool): True if using off-screen rendering + + render_camera (str): Name of camera to render if `has_renderer` is True. Setting this value to 'None' + will result in the default angle being applied, which is useful as it can be dragged / panned by + the user using the mouse + + render_collision_mesh (bool): True if rendering collision meshes in camera. False otherwise. + + render_visual_mesh (bool): True if rendering visual meshes in camera. False otherwise. + + render_gpu_device_id (int): corresponds to the GPU device id to use for offscreen rendering. + Defaults to -1, in which case the device will be inferred from environment variables + (GPUS or CUDA_VISIBLE_DEVICES). + + control_freq (float): how many control signals to receive in every second. This sets the amount of + simulation time that passes between every action input. + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + + horizon (int): Every episode lasts for exactly @horizon timesteps. + + ignore_done (bool): True if never terminating the environment (ignore @horizon). + + hard_reset (bool): If True, re-loads model, sim, and render object upon a reset call, else, + only calls sim.reset and resets all robosuite-internal variables + + camera_names (str or list of str): name of camera to be rendered. Should either be single str if + same name is to be used for all cameras' rendering or else it should be a list of cameras to render. + + :Note: At least one camera must be specified if @use_camera_obs is True. + + :Note: To render all robots' cameras of a certain type (e.g.: "robotview" or "eye_in_hand"), use the + convention "all-{name}" (e.g.: "all-robotview") to automatically render all camera images from each + robot's camera list). + + camera_heights (int or list of int): height of camera frame. Should either be single int if + same height is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_widths (int or list of int): width of camera frame. Should either be single int if + same width is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_depths (bool or list of bool): True if rendering RGB-D, and RGB otherwise. Should either be single + bool if same depth setting is to be used for all cameras or else it should be a list of the same length as + "camera names" param. + + camera_segmentations (None or str or list of str or list of list of str): Camera segmentation(s) to use + for each camera. Valid options are: + + `None`: no segmentation sensor used + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + + If not None, multiple types of segmentations can be specified. A [list of str / str or None] specifies + [multiple / a single] segmentation(s) to use for all cameras. A list of list of str specifies per-camera + segmentation setting(s) to use. + + Raises: + AssertionError: [Gripper specified] + ValueError: [Invalid number of robots specified] + ValueError: [Invalid env configuration] + ValueError: [Invalid robots for specified env configuration] + """ + + def __init__( + self, + robots, + env_configuration="default", + controller_configs=None, + gripper_types=None, + initialization_noise="default", + use_camera_obs=True, + use_object_obs=True, + reward_scale=1.0, + reward_shaping=False, + peg_radius=(0.015, 0.03), + peg_length=0.13, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + lite_physics=True, + horizon=1000, + ignore_done=False, + hard_reset=True, + camera_names="agentview", + camera_heights=256, + camera_widths=256, + camera_depths=False, + camera_segmentations=None, # {None, instance, class, element} + renderer="mjviewer", + renderer_config=None, + ): + # Assert that the gripper type is None + assert gripper_types is None, "Tried to specify gripper other than None in TwoArmPegInHole environment!" + + # reward configuration + self.reward_scale = reward_scale + self.reward_shaping = reward_shaping + + # whether to use ground-truth object states + self.use_object_obs = use_object_obs + + # Save peg specs + self.peg_radius = peg_radius + self.peg_length = peg_length + + super().__init__( + robots=robots, + env_configuration=env_configuration, + controller_configs=controller_configs, + base_types="default", + gripper_types=gripper_types, + initialization_noise=initialization_noise, + use_camera_obs=use_camera_obs, + has_renderer=has_renderer, + has_offscreen_renderer=has_offscreen_renderer, + render_camera=render_camera, + render_collision_mesh=render_collision_mesh, + render_visual_mesh=render_visual_mesh, + render_gpu_device_id=render_gpu_device_id, + control_freq=control_freq, + lite_physics=lite_physics, + horizon=horizon, + ignore_done=ignore_done, + hard_reset=hard_reset, + camera_names=camera_names, + camera_heights=camera_heights, + camera_widths=camera_widths, + camera_depths=camera_depths, + camera_segmentations=camera_segmentations, + renderer=renderer, + renderer_config=renderer_config, + ) + + def reward(self, action=None): + """ + Reward function for the task. + + Sparse un-normalized reward: + + - a discrete reward of 5.0 is provided if the peg is inside the plate's hole + - Note that we enforce that it's inside at an appropriate angle (cos(theta) > 0.95). + + Un-normalized summed components if using reward shaping: + + - Reaching: in [0, 1], to encourage the arms to approach each other + - Perpendicular Distance: in [0,1], to encourage the arms to approach each other + - Parallel Distance: in [0,1], to encourage the arms to approach each other + - Alignment: in [0, 1], to encourage having the right orientation between the peg and hole. + - Placement: in {0, 1}, nonzero if the peg is in the hole with a relatively correct alignment + + Note that the final reward is normalized and scaled by reward_scale / 5.0 as + well so that the max score is equal to reward_scale + + """ + reward = 0 + + # Right location and angle + if self._check_success(): + reward = 1.0 + + # use a shaping reward + if self.reward_shaping: + # Grab relevant values + t, d, cos = self._compute_orientation() + # reaching reward + hole_pos = self.sim.data.body_xpos[self.hole_body_id] + gripper_site_pos = self.sim.data.body_xpos[self.peg_body_id] + dist = np.linalg.norm(gripper_site_pos - hole_pos) + reaching_reward = 1 - np.tanh(1.0 * dist) + reward += reaching_reward + + # Orientation reward + reward += 1 - np.tanh(d) + reward += 1 - np.tanh(np.abs(t)) + reward += cos + + # if we're not reward shaping, scale sparse reward so that the max reward is identical to its dense version + else: + reward *= 5.0 + + if self.reward_scale is not None: + reward *= self.reward_scale / 5.0 + + return reward + + def _load_model(self): + """ + Loads an xml model, puts it in self.model + """ + super()._load_model() + + # Adjust base pose(s) accordingly + if self.env_configuration == "single-robot": + xpos = self.robots[0].robot_model.base_xpos_offset["empty"] + self.robots[0].robot_model.set_base_xpos(xpos) + else: + if self.env_configuration == "opposed": + # Set up robots facing towards each other by rotating them from their default position + for robot, rotation in zip(self.robots, (np.pi / 2, -np.pi / 2)): + xpos = robot.robot_model.base_xpos_offset["empty"] + rot = np.array((0, 0, rotation)) + xpos = T.euler2mat(rot) @ np.array(xpos) + robot.robot_model.set_base_xpos(xpos) + robot.robot_model.set_base_ori(rot) + else: # "parallel" configuration setting + # Set up robots parallel to each other but offset from the center + for robot, offset in zip(self.robots, (-0.25, 0.25)): + xpos = robot.robot_model.base_xpos_offset["empty"] + xpos = np.array(xpos) + np.array((0, offset, 0)) + robot.robot_model.set_base_xpos(xpos) + + # Add arena and robot + mujoco_arena = EmptyArena() + + # Arena always gets set to zero origin + mujoco_arena.set_origin([0, 0, 0]) + + # Modify default agentview camera + mujoco_arena.set_camera( + camera_name="agentview", + pos=[1.0666432116509934, 1.4903257668114777e-08, 2.0563394967349096], + quat=[0.6530979871749878, 0.27104058861732483, 0.27104055881500244, 0.6530978679656982], + ) + + # initialize objects of interest + self.hole = PlateWithHoleObject(name="hole") + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "1 1", + "specular": "0.4", + "shininess": "0.1", + } + greenwood = CustomMaterial( + texture="WoodGreen", + tex_name="greenwood", + mat_name="greenwood_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.peg = CylinderObject( + name="peg", + size_min=(self.peg_radius[0], self.peg_length), + size_max=(self.peg_radius[1], self.peg_length), + material=greenwood, + rgba=[0, 1, 0, 1], + joints=None, + ) + + # Load hole object + hole_obj = self.hole.get_obj() + hole_obj.set("quat", "0 0 0.707 0.707") + hole_robot = self.robots[0] if self.env_configuration == "single-robot" else self.robots[1] + # Get offset function for hole object based on the robot type + hole_offset_fn = _OBJECT_POS_OFFSET_FN.get(hole_robot.robot_model.__class__.__name__, {}).get( + "hole", lambda x: x + ) + hole_obj.set("pos", array_to_string(hole_offset_fn([0.11, 0, 0.17]))) + + # Load peg object + peg_obj = self.peg.get_obj() + # Get offset function for peg object based on the robot type + peg_pos_offset_fn = _OBJECT_POS_OFFSET_FN.get(self.robots[0].robot_model.__class__.__name__, {}).get( + "peg", lambda x: x + ) + peg_obj.set("pos", array_to_string(peg_pos_offset_fn([0, 0, self.peg_length]))) + + # Append appropriate objects to arms + if self.env_configuration == "single-robot": + eef0, eef1 = [self.robots[0].robot_model.eef_name[arm] for arm in self.robots[0].arms] + model0, model1 = [self.robots[0].robot_model, self.robots[0].robot_model] + else: + # Always place object on the right arm when 2 robots are used + eef0, eef1 = [robot.robot_model.eef_name["right"] for robot in self.robots] + model0, model1 = [self.robots[0].robot_model, self.robots[1].robot_model] + body1 = find_elements(root=model0.worldbody, tags="body", attribs={"name": eef0}, return_first=True) + body2 = find_elements(root=model1.worldbody, tags="body", attribs={"name": eef1}, return_first=True) + body1.append(peg_obj) + body2.append(hole_obj) + + # task includes arena, robot, and objects of interest + # We don't add peg and hole directly since they were already appended to the robots + self.model = ManipulationTask( + mujoco_arena=mujoco_arena, + mujoco_robots=[robot.robot_model for robot in self.robots], + ) + + # Make sure to add relevant assets from peg and hole objects + self.model.merge_assets(self.hole) + self.model.merge_assets(self.peg) + + def _setup_references(self): + """ + Sets up references to important components. A reference is typically an + index or a list of indices that point to the corresponding elements + in a flatten array, which is how MuJoCo stores physical simulation data. + """ + super()._setup_references() + + # Additional object references from this env + self.hole_body_id = self.sim.model.body_name2id(self.hole.root_body) + self.peg_body_id = self.sim.model.body_name2id(self.peg.root_body) + + def _setup_observables(self): + """ + Sets up observables to be used for this environment. Creates object-based observables if enabled + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + observables = super()._setup_observables() + + # low-level object information + if self.use_object_obs: + # Get robot prefix and define observables modality + if self.env_configuration == "single-robot": + pf0 = self.robots[0].robot_model.naming_prefix + "right_" + pf1 = self.robots[0].robot_model.naming_prefix + "left_" + else: + pf0 = self.robots[0].robot_model.naming_prefix + pf1 = self.robots[1].robot_model.naming_prefix + modality = "object" + + # position and rotation of peg and hole + @sensor(modality=modality) + def hole_pos(obs_cache): + return np.array(self.sim.data.body_xpos[self.hole_body_id]) + + @sensor(modality=modality) + def hole_quat(obs_cache): + return T.convert_quat(self.sim.data.body_xquat[self.hole_body_id], to="xyzw") + + @sensor(modality=modality) + def peg_to_hole(obs_cache): + return ( + obs_cache["hole_pos"] - np.array(self.sim.data.body_xpos[self.peg_body_id]) + if "hole_pos" in obs_cache + else np.zeros(3) + ) + + @sensor(modality=modality) + def peg_quat(obs_cache): + return T.convert_quat(self.sim.data.body_xquat[self.peg_body_id], to="xyzw") + + # Relative orientation parameters + @sensor(modality=modality) + def angle(obs_cache): + t, d, cos = self._compute_orientation() + obs_cache["t"] = t + obs_cache["d"] = d + return cos + + @sensor(modality=modality) + def t(obs_cache): + return obs_cache["t"] if "t" in obs_cache else 0.0 + + @sensor(modality=modality) + def d(obs_cache): + return obs_cache["d"] if "d" in obs_cache else 0.0 + + sensors = [hole_pos, hole_quat, peg_to_hole, peg_quat, angle, t, d] + names = [s.__name__ for s in sensors] + + # Create observables + for name, s in zip(names, sensors): + observables[name] = Observable( + name=name, + sensor=s, + sampling_rate=self.control_freq, + ) + + return observables + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + super()._reset_internal() + + def _check_success(self): + """ + Check if peg is successfully aligned and placed within the hole + + Returns: + bool: True if peg is placed in hole correctly + """ + t, d, cos = self._compute_orientation() + + return d < 0.06 and -0.12 <= t <= 0.14 and cos > 0.95 + + def _compute_orientation(self): + """ + Helper function to return the relative positions between the hole and the peg. + In particular, the intersection of the line defined by the peg and the plane + defined by the hole is computed; the parallel distance, perpendicular distance, + and angle are returned. + + Returns: + 3-tuple: + + - (float): parallel distance + - (float): perpendicular distance + - (float): angle + """ + peg_mat = self.sim.data.body_xmat[self.peg_body_id] + peg_mat.shape = (3, 3) + peg_pos = self.sim.data.body_xpos[self.peg_body_id] + + hole_pos = self.sim.data.body_xpos[self.hole_body_id] + hole_mat = self.sim.data.body_xmat[self.hole_body_id] + hole_mat.shape = (3, 3) + + v = peg_mat @ np.array([0, 0, 1]) + v = v / np.linalg.norm(v) + center = hole_pos + hole_mat @ np.array([0.1, 0, 0]) + + t = (center - peg_pos) @ v / (np.linalg.norm(v) ** 2) + d = np.linalg.norm(np.cross(v, peg_pos - center)) / np.linalg.norm(v) + + hole_normal = hole_mat @ np.array([0, 0, 1]) + return ( + t, + d, + abs(np.dot(hole_normal, v) / np.linalg.norm(hole_normal) / np.linalg.norm(v)), + ) + + def _peg_pose_in_hole_frame(self): + """ + A helper function that takes in a named data field and returns the pose of that + object in the base frame. + + Returns: + np.array: (4,4) matrix corresponding to the pose of the peg in the hole frame + """ + # World frame + peg_pos_in_world = self.sim.data.get_body_xpos(self.peg.root_body) + peg_rot_in_world = self.sim.data.get_body_xmat(self.peg.root_body).reshape((3, 3)) + peg_pose_in_world = T.make_pose(peg_pos_in_world, peg_rot_in_world) + + # World frame + hole_pos_in_world = self.sim.data.get_body_xpos(self.hole.root_body) + hole_rot_in_world = self.sim.data.get_body_xmat(self.hole.root_body).reshape((3, 3)) + hole_pose_in_world = T.make_pose(hole_pos_in_world, hole_rot_in_world) + + world_pose_in_hole = T.pose_inv(hole_pose_in_world) + + peg_pose_in_hole = T.pose_in_A_to_pose_in_B(peg_pose_in_world, world_pose_in_hole) + return peg_pose_in_hole diff --git a/third_party/robosuite/robosuite/environments/manipulation/two_arm_transport.py b/third_party/robosuite/robosuite/environments/manipulation/two_arm_transport.py new file mode 100644 index 0000000000000000000000000000000000000000..a552b2f207d15001df1de91654ce286c2da1f525 --- /dev/null +++ b/third_party/robosuite/robosuite/environments/manipulation/two_arm_transport.py @@ -0,0 +1,599 @@ +from collections import OrderedDict + +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.environments.manipulation.two_arm_env import TwoArmEnv +from robosuite.models.arenas import MultiTableArena +from robosuite.models.objects import BoxObject, HammerObject, TransportGroup +from robosuite.models.tasks import ManipulationTask +from robosuite.utils.mjcf_utils import CustomMaterial +from robosuite.utils.observables import Observable, sensor +from robosuite.utils.placement_samplers import SequentialCompositeSampler, UniformRandomSampler + + +class TwoArmTransport(TwoArmEnv): + """ + This class corresponds to the transport task for two robot arms, requiring a payload to be transported from an + initial bin into a target bin, while removing trash from the target bin to a trash bin. + + Args: + robots (str or list of str): Specification for specific robot(s) + Note: Must be either 2 robots or 1 bimanual robot! + + env_configuration (str): Specifies how to position the robots within the environment if two robots inputted. Can be either: + + :`'parallel'`: Sets up the two robots next to each other on the -x side of the table + :`'opposed'`: Sets up the two robots opposed from each others on the opposite +/-y sides of the table. + + Note that "default" "opposed" if two robots are used. + + controller_configs (str or list of dict): If set, contains relevant controller parameters for creating a + custom controller. Else, uses the default controller for this specific task. Should either be single + dict if same controller is to be used for all robots or else it should be a list of the same length as + "robots" param + + gripper_types (str or list of str): type of gripper, used to instantiate + gripper models from gripper factory. Default is "default", which is the default grippers(s) associated + with the robot(s) the 'robots' specification. None removes the gripper, and any other (valid) model + overrides the default gripper. Should either be single str if same gripper type is to be used for all + robots or else it should be a list of the same length as "robots" param + + initialization_noise (dict or list of dict): Dict containing the initialization noise parameters. + The expected keys and corresponding value types are specified below: + + :`'magnitude'`: The scale factor of uni-variate random noise applied to each of a robot's given initial + joint positions. Setting this value to `None` or 0.0 results in no noise being applied. + If "gaussian" type of noise is applied then this magnitude scales the standard deviation applied, + If "uniform" type of noise is applied then this magnitude sets the bounds of the sampling range + :`'type'`: Type of noise to apply. Can either specify "gaussian" or "uniform" + + Should either be single dict if same noise value is to be used for all robots or else it should be a + list of the same length as "robots" param + + :Note: Specifying "default" will automatically use the default noise settings. + Specifying None will automatically create the required dict with "magnitude" set to 0.0. + + tables_boundary (3-tuple): x, y, and z dimensions of the table bounds. Two tables will be created at the edges of + this boundary + + table_friction (3-tuple): the three mujoco friction parameters for + each table. + + bin_size (3-tuple): (x,y,z) dimensions of bins to use + + use_camera_obs (bool): if True, every observation includes rendered image(s) + + use_object_obs (bool): if True, include object (cube) information in + the observation. + + reward_scale (None or float): Scales the normalized reward function by the amount specified. + If None, environment reward remains unnormalized + + reward_shaping (bool): if True, use dense rewards. + + has_renderer (bool): If true, render the simulation state in + a viewer instead of headless mode. + + has_offscreen_renderer (bool): True if using off-screen rendering + + render_camera (str): Name of camera to render if `has_renderer` is True. Setting this value to 'None' + will result in the default angle being applied, which is useful as it can be dragged / panned by + the user using the mouse + + render_collision_mesh (bool): True if rendering collision meshes in camera. False otherwise. + + render_visual_mesh (bool): True if rendering visual meshes in camera. False otherwise. + + render_gpu_device_id (int): corresponds to the GPU device id to use for offscreen rendering. + Defaults to -1, in which case the device will be inferred from environment variables + (GPUS or CUDA_VISIBLE_DEVICES). + + control_freq (float): how many control signals to receive in every second. This sets the amount of + simulation time that passes between every action input. + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + + horizon (int): Every episode lasts for exactly @horizon timesteps. + + ignore_done (bool): True if never terminating the environment (ignore @horizon). + + hard_reset (bool): If True, re-loads model, sim, and render object upon a reset call, else, + only calls sim.reset and resets all robosuite-internal variables + + camera_names (str or list of str): name of camera to be rendered. Should either be single str if + same name is to be used for all cameras' rendering or else it should be a list of cameras to render. + + :Note: At least one camera must be specified if @use_camera_obs is True. + + :Note: To render all robots' cameras of a certain type (e.g.: "robotview" or "eye_in_hand"), use the + convention "all-{name}" (e.g.: "all-robotview") to automatically render all camera images from each + robot's camera list). + + camera_heights (int or list of int): height of camera frame. Should either be single int if + same height is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_widths (int or list of int): width of camera frame. Should either be single int if + same width is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_depths (bool or list of bool): True if rendering RGB-D, and RGB otherwise. Should either be single + bool if same depth setting is to be used for all cameras or else it should be a list of the same length as + "camera names" param. + + camera_segmentations (None or str or list of str or list of list of str): Camera segmentation(s) to use + for each camera. Valid options are: + + `None`: no segmentation sensor used + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + + If not None, multiple types of segmentations can be specified. A [list of str / str or None] specifies + [multiple / a single] segmentation(s) to use for all cameras. A list of list of str specifies per-camera + segmentation setting(s) to use. + + Raises: + ValueError: [Invalid number of robots specified] + ValueError: [Invalid env configuration] + ValueError: [Invalid robots for specified env configuration] + """ + + def __init__( + self, + robots, + env_configuration="default", + controller_configs=None, + gripper_types="default", + initialization_noise="default", + tables_boundary=(0.8, 1.2, 0.05), + table_friction=(1.0, 5e-3, 1e-4), + bin_size=(0.3, 0.3, 0.15), + use_camera_obs=True, + use_object_obs=True, + reward_scale=1.0, + reward_shaping=False, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + lite_physics=True, + horizon=1000, + ignore_done=False, + hard_reset=True, + camera_names="agentview", + camera_heights=256, + camera_widths=256, + camera_depths=False, + camera_segmentations=None, # {None, instance, class, element} + renderer="mjviewer", + renderer_config=None, + ): + # settings for table top + self.tables_boundary = tables_boundary + self.table_full_size = np.array(tables_boundary) + self.table_full_size[1] *= 0.25 # each table size will only be a fraction of the full boundary + self.table_friction = table_friction + self.table_offsets = np.zeros((2, 3)) + self.table_offsets[0, 1] = self.tables_boundary[1] * -3 / 8 # scale y offset + self.table_offsets[1, 1] = self.tables_boundary[1] * 3 / 8 # scale y offset + self.table_offsets[:, 2] = 0.8 # scale z offset + self.bin_size = np.array(bin_size) + + # reward configuration + self.reward_scale = reward_scale + self.reward_shaping = reward_shaping + self.height_threshold = 0.1 # threshold above the table surface which the payload is considered lifted + + # whether to use ground-truth object states + self.use_object_obs = use_object_obs + + super().__init__( + robots=robots, + env_configuration=env_configuration, + controller_configs=controller_configs, + base_types="default", + gripper_types=gripper_types, + initialization_noise=initialization_noise, + use_camera_obs=use_camera_obs, + has_renderer=has_renderer, + has_offscreen_renderer=has_offscreen_renderer, + render_camera=render_camera, + render_collision_mesh=render_collision_mesh, + render_visual_mesh=render_visual_mesh, + render_gpu_device_id=render_gpu_device_id, + control_freq=control_freq, + lite_physics=lite_physics, + horizon=horizon, + ignore_done=ignore_done, + hard_reset=hard_reset, + camera_names=camera_names, + camera_heights=camera_heights, + camera_widths=camera_widths, + camera_depths=camera_depths, + camera_segmentations=camera_segmentations, + renderer=renderer, + renderer_config=renderer_config, + ) + + def reward(self, action=None): + """ + Reward function for the task. + + Sparse un-normalized reward: + + - a discrete reward of 1.0 is provided when the payload is in the target bin and the trash is in the trash + bin + + Un-normalized max-wise components if using reward shaping: + + # TODO! + + Note that the final reward is normalized and scaled by reward_scale / 1.0 as + well so that the max score is equal to reward_scale + + Args: + action (np array): [NOT USED] + + Returns: + float: reward value + """ + # Initialize reward + reward = 0 + + # use a shaping reward if specified + if self.reward_shaping: + # TODO! So we print a warning and force sparse rewards + print(f"\n\nWarning! No dense reward current implemented for this task. Forcing sparse rewards\n\n") + self.reward_shaping = False + + # Else this is the sparse reward setting + else: + # Provide reward if payload is in target bin and trash is in trash bin + if self._check_success(): + reward = 1.0 + + if self.reward_scale is not None: + reward *= self.reward_scale / 1.0 + + return reward + + def _load_model(self): + """ + Loads an xml model, puts it in self.model + """ + super()._load_model() + + # Adjust base pose(s) accordingly + if self.env_configuration == "single-robot": + xpos = self.robots[0].robot_model.base_xpos_offset["table"](self.table_full_size[0]) + self.robots[0].robot_model.set_base_xpos(xpos) + else: + if self.env_configuration == "opposed": + # Set up robots facing towards each other by rotating them from their default position + for robot, rotation, offset in zip(self.robots, (np.pi / 2, -np.pi / 2), (-0.25, 0.25)): + xpos = robot.robot_model.base_xpos_offset["table"](self.table_full_size[0]) + rot = np.array((0, 0, rotation)) + xpos = T.euler2mat(rot) @ np.array(xpos) + xpos += np.array((0, offset, 0)) + robot.robot_model.set_base_xpos(xpos) + robot.robot_model.set_base_ori(rot) + else: # "parallel" configuration setting + # Set up robots parallel to each other but offset from the center + for robot, offset in zip(self.robots, (-0.6, 0.6)): + xpos = robot.robot_model.base_xpos_offset["table"](self.table_full_size[0]) + xpos = np.array(xpos) + np.array((0, offset, 0)) + robot.robot_model.set_base_xpos(xpos) + + # load model for table top workspace + mujoco_arena = MultiTableArena( + table_offsets=self.table_offsets, + table_rots=0, + table_full_sizes=self.table_full_size, + table_frictions=self.table_friction, + has_legs=True, + ) + + # Arena always gets set to zero origin + mujoco_arena.set_origin([0, 0, 0]) + + # Modify default agentview camera + mujoco_arena.set_camera( + camera_name="agentview", + pos=[0.8894354364730311, -3.481824231498976e-08, 1.7383813133506494], + quat=[0.6530981063842773, 0.2710406184196472, 0.27104079723358154, 0.6530979871749878], + ) + + # TODO: Add built-in method into TwoArmEnv so we have an elegant way of automatically adding extra cameras to all these envs + # Add shoulder cameras + mujoco_arena.set_camera( + camera_name="shouldercamera0", + pos=[0.4430096057365183, -1.0697399743660143, 1.3639950119362048], + quat=[0.804057240486145, 0.5531665086746216, 0.11286306381225586, 0.18644218146800995], + ) + mujoco_arena.set_camera( + camera_name="shouldercamera1", + pos=[-0.40900713993039983, 0.9613722572245062, 1.3084072951772754], + quat=[0.15484197437763214, 0.12077208608388901, -0.5476858019828796, -0.8133130073547363], + ) + + # Add relevant materials + # Textures to use + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "3 3", + "specular": "0.4", + "shininess": "0.1", + } + redwood = CustomMaterial( + texture="WoodRed", + tex_name="redwood", + mat_name="redwood_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + + # initialize objects of interest + payload = HammerObject( + name="payload", + handle_radius=0.015, + handle_length=0.20, + handle_density=150.0, + handle_friction=4.0, + head_density_ratio=1.5, + ) + trash = BoxObject(name="trash", size=[0.02, 0.02, 0.02], material=redwood) + self.transport = TransportGroup( + name="transport", + payload=payload, + trash=trash, + bin_size=self.bin_size, + ) + + # task includes arena, robot, and objects of interest + self.model = ManipulationTask( + mujoco_arena=mujoco_arena, + mujoco_robots=[robot.robot_model for robot in self.robots], + mujoco_objects=list(self.transport.objects.values()), + ) + + # Create placement initializer + self._get_placement_initializer() + + def _get_placement_initializer(self): + """ + Helper function for defining placement initializer and object sampling bounds + """ + # Create placement initializer + self.placement_initializer = SequentialCompositeSampler(name="ObjectSampler") + + # Pre-define settings for each object's placement + object_names = ["start_bin", "lid", "payload", "target_bin", "trash", "trash_bin"] + table_nums = [0, 0, 0, 1, 1, 1] + x_centers = [ + self.table_full_size[0] * 0.25, + 0, # gets overridden anyways + 0, # gets overridden anyways + -self.table_full_size[0] * 0.25, + 0, # gets overridden anyways + self.table_full_size[0] * 0.25, + ] + pos_tol = 0.005 + rot_centers = [0, 0, np.pi / 2, 0, 0, 0] + rot_tols = [0, 0, np.pi / 6, 0, 0.3 * np.pi, 0] + rot_axes = ["z", "z", "y", "z", "z", "z"] + for obj_name, x, r, r_tol, r_axis, table_num in zip( + object_names, x_centers, rot_centers, rot_tols, rot_axes, table_nums + ): + # Get name and table + obj = self.transport.objects[obj_name] + table_pos = self.table_offsets[table_num] + # Create sampler for this object and add it to the sequential sampler + self.placement_initializer.append_sampler( + sampler=UniformRandomSampler( + name=f"{obj_name}ObjectSampler", + mujoco_objects=obj, + x_range=[x - pos_tol, x + pos_tol], + y_range=[-pos_tol, pos_tol], + rotation=[r - r_tol, r + r_tol], + rotation_axis=r_axis, + ensure_object_boundary_in_range=False, + ensure_valid_placement=False, + reference_pos=table_pos, + z_offset=0.001, + ) + ) + + def _setup_references(self): + """ + Sets up references to important components. A reference is typically an + index or a list of indices that point to the corresponding elements + in a flatten array, which is how MuJoCo stores physical simulation data. + """ + super()._setup_references() + + def _setup_observables(self): + """ + Sets up observables to be used for this environment. Creates object-based observables if enabled + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + observables = super()._setup_observables() + + # low-level object information + if self.use_object_obs: + modality = "object" + + # position and rotation of payload + @sensor(modality=modality) + def payload_pos(obs_cache): + return np.array(self.transport.payload_pos) + + @sensor(modality=modality) + def payload_quat(obs_cache): + return np.array(self.transport.payload_quat) + + # position and rotation of trash + @sensor(modality=modality) + def trash_pos(obs_cache): + return np.array(self.transport.trash_pos) + + @sensor(modality=modality) + def trash_quat(obs_cache): + return np.array(self.transport.trash_quat) + + # position and rotation of lid handle + @sensor(modality=modality) + def lid_handle_pos(obs_cache): + return np.array(self.transport.lid_handle_pos) + + @sensor(modality=modality) + def lid_handle_quat(obs_cache): + return np.array(self.transport.lid_handle_quat) + + # bin positions + @sensor(modality=modality) + def target_bin_pos(obs_cache): + return np.array(self.transport.target_bin_pos) + + @sensor(modality=modality) + def trash_bin_pos(obs_cache): + return np.array(self.transport.trash_bin_pos) + + # Key boolean checks + @sensor(modality=modality) + def payload_in_target_bin(obs_cache): + return self.transport.payload_in_target_bin + + @sensor(modality=modality) + def trash_in_trash_bin(obs_cache): + return self.transport.trash_in_trash_bin + + sensors = [ + payload_pos, + payload_quat, + trash_pos, + trash_quat, + lid_handle_pos, + lid_handle_quat, + target_bin_pos, + trash_bin_pos, + payload_in_target_bin, + trash_in_trash_bin, + ] + names = [s.__name__ for s in sensors] + + arm_sensor_fns = [] + if self.env_configuration == "single-robot": + # If single-robot, we only have one robot. gripper 0 is always right and gripper 1 is always left + pf0 = self.robots[0].robot_model.naming_prefix + "right_" + pf1 = self.robots[0].robot_model.naming_prefix + "left_" + prefixes = [pf0, pf1] + arm_sensor_fns = [ + self._get_obj_eef_sensor(full_pf, "payload_pos", f"gripper{i}_to_payload", modality) + for i, full_pf in enumerate(prefixes) + ] + arm_sensor_fns += [ + self._get_obj_eef_sensor(pf0, "lid_handle_pos", "gripper0_to_lid_handle", modality), + self._get_obj_eef_sensor(pf1, "trash_pos", "gripper1_to_trash", modality), + ] + else: + # If not single-robot, we have two robots. gripper 0 is always the first robot's gripper and + # gripper 1 is always the second robot's gripper. However, must account for the fact that + # each robot may have multiple arms/grippers + robot_arm_prefixes = [self._get_arm_prefixes(robot, include_robot_name=False) for robot in self.robots] + robot_full_prefixes = [self._get_arm_prefixes(robot, include_robot_name=True) for robot in self.robots] + for i, (arm_prefixes, full_prefixes) in enumerate(zip(robot_arm_prefixes, robot_full_prefixes)): + arm_sensor_fns += [ + self._get_obj_eef_sensor(full_pf, "payload_pos", f"{arm_pf}gripper{i}_to_payload", modality) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + + # If this is the first robot, add lid handle sensor, else add trash sensor + if i == 0: + arm_sensor_fns += [ + self._get_obj_eef_sensor( + full_pf, "lid_handle_pos", f"{arm_pf}gripper0_to_lid_handle", modality + ) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + else: + arm_sensor_fns += [ + self._get_obj_eef_sensor(full_pf, "trash_pos", f"{arm_pf}gripper1_to_trash", modality) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + + sensors += arm_sensor_fns + names += [s.__name__ for s in arm_sensor_fns] + + # Create observables + for name, s in zip(names, sensors): + observables[name] = Observable( + name=name, + sensor=s, + sampling_rate=self.control_freq, + ) + + return observables + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + super()._reset_internal() + + # Update sim + self.transport.update_sim(sim=self.sim) + + # Reset all object positions using initializer sampler if we're not directly loading from an xml + if not self.deterministic_reset: + + # Sample from the placement initializer for all objects + object_placements = self.placement_initializer.sample() + + # Initialize placeholders that we'll need to override the payload, lid, and trash object locations + start_bin_pos = None + target_bin_pos = None + + # Loop through all objects and reset their positions + for obj_pos, obj_quat, obj in object_placements.values(): + # If this is toolbox or good bin, store their sampled positions + if "start_bin" in obj.name and "lid" not in obj.name: + start_bin_pos = obj_pos + elif "target_bin" in obj.name: + target_bin_pos = obj_pos + # Else if this is either the lid, payload, or trash object, + # we override their positions to match their respective containers' positions + elif "lid" in obj.name: + obj_pos = (start_bin_pos[0], start_bin_pos[1], obj_pos[2] + self.transport.bin_size[2]) + elif "payload" in obj.name: + obj_pos = ( + start_bin_pos[0], + start_bin_pos[1], + obj_pos[2] + self.transport.objects["start_bin"].wall_thickness, + ) + elif "trash" in obj.name and "bin" not in obj.name: + obj_pos = ( + target_bin_pos[0], + target_bin_pos[1], + obj_pos[2] + self.transport.objects["target_bin"].wall_thickness, + ) + # Set the collision object joints + self.sim.data.set_joint_qpos(obj.joints[0], np.concatenate([np.array(obj_pos), np.array(obj_quat)])) + + def _check_success(self): + """ + Check if payload is in target in and trash is in trash bin + + Returns: + bool: True if transport has been completed + """ + return True if self.transport.payload_in_target_bin and self.transport.trash_in_trash_bin else False diff --git a/third_party/robosuite/robosuite/environments/manipulation/wipe.py b/third_party/robosuite/robosuite/environments/manipulation/wipe.py new file mode 100644 index 0000000000000000000000000000000000000000..07028f20b922e5a2a7327bcefa911bece2eab882 --- /dev/null +++ b/third_party/robosuite/robosuite/environments/manipulation/wipe.py @@ -0,0 +1,816 @@ +import multiprocessing +from collections import OrderedDict + +import numpy as np + +from robosuite.environments.manipulation.manipulation_env import ManipulationEnv +from robosuite.models.arenas import WipeArena +from robosuite.models.tasks import ManipulationTask +from robosuite.utils.observables import Observable, sensor + +# Default Wipe environment configuration +DEFAULT_WIPE_CONFIG = { + # settings for reward + "arm_limit_collision_penalty": -10.0, # penalty for reaching joint limit or arm collision (except the wiping tool) with the table + "wipe_contact_reward": 0.01, # reward for contacting something with the wiping tool + "unit_wiped_reward": 50.0, # reward per peg wiped + "ee_accel_penalty": 0, # penalty for large end-effector accelerations + "excess_force_penalty_mul": 0.05, # penalty for each step that the force is over the safety threshold + "distance_multiplier": 5.0, # multiplier for the dense reward inversely proportional to the mean location of the pegs to wipe + "distance_th_multiplier": 5.0, # multiplier in the tanh function for the aforementioned reward + # settings for table top + "table_full_size": [0.5, 0.8, 0.05], # Size of tabletop + "table_offset": [0.15, 0, 0.9], # Offset of table (z dimension defines max height of table) + "table_friction": [0.03, 0.005, 0.0001], # Friction parameters for the table + "table_friction_std": 0, # Standard deviation to sample different friction parameters for the table each episode + "table_height": 0.0, # Additional height of the table over the default location + "table_height_std": 0.0, # Standard deviation to sample different heigths of the table each episode + "line_width": 0.04, # Width of the line to wipe (diameter of the pegs) + "two_clusters": False, # if the dirt to wipe is one continuous line or two + "coverage_factor": 0.6, # how much of the table surface we cover + "num_markers": 100, # How many particles of dirt to generate in the environment + # settings for thresholds + "contact_threshold": 1.0, # Minimum eef force to qualify as contact [N] + "pressure_threshold": 0.5, # force threshold (N) to overcome to get increased contact wiping reward + "pressure_threshold_max": 60.0, # maximum force allowed (N) + # misc settings + "print_results": False, # Whether to print results or not + "get_info": False, # Whether to grab info after each env step if not + "use_robot_obs": True, # if we use robot observations (proprioception) as input to the policy + "use_contact_obs": True, # if we use a binary observation for whether robot is in contact or not + "early_terminations": True, # Whether we allow for early terminations or not + "use_condensed_obj_obs": True, # Whether to use condensed object observation representation (only applicable if obj obs is active) +} + + +class Wipe(ManipulationEnv): + """ + This class corresponds to the Wiping task for a single robot arm + + Args: + robots (str or list of str): Specification for specific robot arm(s) to be instantiated within this env + (e.g: "Sawyer" would generate one arm; ["Panda", "Panda", "Sawyer"] would generate three robot arms) + Note: Must be a single single-arm robot! + + env_configuration (str): Specifies how to position the robots within the environment (default is "default"). + For most single arm environments, this argument has no impact on the robot setup. + + controller_configs (str or list of dict): If set, contains relevant controller parameters for creating a + custom controller. Else, uses the default controller for this specific task. Should either be single + dict if same controller is to be used for all robots or else it should be a list of the same length as + "robots" param + + gripper_types (str or list of str): type of gripper, used to instantiate + gripper models from gripper factory. + For this environment, setting a value other than the default ("WipingGripper") will raise an + AssertionError, as this environment is not meant to be used with any other alternative gripper. + + initialization_noise (dict or list of dict): Dict containing the initialization noise parameters. + The expected keys and corresponding value types are specified below: + + :`'magnitude'`: The scale factor of uni-variate random noise applied to each of a robot's given initial + joint positions. Setting this value to `None` or 0.0 results in no noise being applied. + If "gaussian" type of noise is applied then this magnitude scales the standard deviation applied, + If "uniform" type of noise is applied then this magnitude sets the bounds of the sampling range + :`'type'`: Type of noise to apply. Can either specify "gaussian" or "uniform" + + Should either be single dict if same noise value is to be used for all robots or else it should be a + list of the same length as "robots" param + + :Note: Specifying "default" will automatically use the default noise settings. + Specifying None will automatically create the required dict with "magnitude" set to 0.0. + + use_camera_obs (bool): if True, every observation includes rendered image(s) + + use_object_obs (bool): if True, include object (cube) information in + the observation. + + reward_scale (None or float): Scales the normalized reward function by the amount specified. + If None, environment reward remains unnormalized + + reward_shaping (bool): if True, use dense rewards. + + has_renderer (bool): If true, render the simulation state in + a viewer instead of headless mode. + + has_offscreen_renderer (bool): True if using off-screen rendering + + render_camera (str): Name of camera to render if `has_renderer` is True. Setting this value to 'None' + will result in the default angle being applied, which is useful as it can be dragged / panned by + the user using the mouse + + render_collision_mesh (bool): True if rendering collision meshes in camera. False otherwise. + + render_visual_mesh (bool): True if rendering visual meshes in camera. False otherwise. + + render_gpu_device_id (int): corresponds to the GPU device id to use for offscreen rendering. + Defaults to -1, in which case the device will be inferred from environment variables + (GPUS or CUDA_VISIBLE_DEVICES). + + control_freq (float): how many control signals to receive in every second. This sets the amount of + simulation time that passes between every action input. + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + + horizon (int): Every episode lasts for exactly @horizon timesteps. + + ignore_done (bool): True if never terminating the environment (ignore @horizon). + + hard_reset (bool): If True, re-loads model, sim, and render object upon a reset call, else, + only calls sim.reset and resets all robosuite-internal variables + + camera_names (str or list of str): name of camera to be rendered. Should either be single str if + same name is to be used for all cameras' rendering or else it should be a list of cameras to render. + + :Note: At least one camera must be specified if @use_camera_obs is True. + + :Note: To render all robots' cameras of a certain type (e.g.: "robotview" or "eye_in_hand"), use the + convention "all-{name}" (e.g.: "all-robotview") to automatically render all camera images from each + robot's camera list). + + camera_heights (int or list of int): height of camera frame. Should either be single int if + same height is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_widths (int or list of int): width of camera frame. Should either be single int if + same width is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_depths (bool or list of bool): True if rendering RGB-D, and RGB otherwise. Should either be single + bool if same depth setting is to be used for all cameras or else it should be a list of the same length as + "camera names" param. + + camera_segmentations (None or str or list of str or list of list of str): Camera segmentation(s) to use + for each camera. Valid options are: + + `None`: no segmentation sensor used + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + + If not None, multiple types of segmentations can be specified. A [list of str / str or None] specifies + [multiple / a single] segmentation(s) to use for all cameras. A list of list of str specifies per-camera + segmentation setting(s) to use. + + task_config (None or dict): Specifies the parameters relevant to this task. For a full list of expected + parameters, see the default configuration dict at the top of this file. + If None is specified, the default configuration will be used. + + Raises: + AssertionError: [Gripper specified] + AssertionError: [Bad reward specification] + AssertionError: [Invalid number of robots specified] + """ + + def __init__( + self, + robots, + env_configuration="default", + controller_configs=None, + gripper_types="WipingGripper", + initialization_noise="default", + use_camera_obs=True, + use_object_obs=True, + reward_scale=1.0, + reward_shaping=True, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + lite_physics=True, + horizon=1000, + ignore_done=False, + hard_reset=True, + camera_names="agentview", + camera_heights=256, + camera_widths=256, + camera_depths=False, + camera_segmentations=None, # {None, instance, class, element} + task_config=None, + renderer="mjviewer", + renderer_config=None, + ): + # Assert that the gripper type is None + assert ( + gripper_types == "WipingGripper" + ), "Tried to specify gripper other than WipingGripper in Wipe environment!" + + # Get config + self.task_config = task_config if task_config is not None else DEFAULT_WIPE_CONFIG + + # Set task-specific parameters + + # settings for the reward + self.reward_scale = reward_scale + self.reward_shaping = reward_shaping + self.arm_limit_collision_penalty = self.task_config["arm_limit_collision_penalty"] + self.wipe_contact_reward = self.task_config["wipe_contact_reward"] + self.unit_wiped_reward = self.task_config["unit_wiped_reward"] + self.ee_accel_penalty = self.task_config["ee_accel_penalty"] + self.excess_force_penalty_mul = self.task_config["excess_force_penalty_mul"] + self.distance_multiplier = self.task_config["distance_multiplier"] + self.distance_th_multiplier = self.task_config["distance_th_multiplier"] + # Final reward computation + # So that is better to finish that to stay touching the table for 100 steps + # The 0.5 comes from continuous_distance_reward at 0. If something changes, this may change as well + self.task_complete_reward = self.unit_wiped_reward * (self.wipe_contact_reward + 0.5) + # Verify that the distance multiplier is not greater than the task complete reward + assert ( + self.task_complete_reward > self.distance_multiplier + ), "Distance multiplier cannot be greater than task complete reward!" + + # settings for table top + self.table_full_size = self.task_config["table_full_size"] + self.table_height = self.task_config["table_height"] + self.table_height_std = self.task_config["table_height_std"] + delta_height = min(0, np.random.normal(self.table_height, self.table_height_std)) # sample variation in height + self.table_offset = np.array(self.task_config["table_offset"]) + np.array((0, 0, delta_height)) + self.table_friction = self.task_config["table_friction"] + self.table_friction_std = self.task_config["table_friction_std"] + self.line_width = self.task_config["line_width"] + self.two_clusters = self.task_config["two_clusters"] + self.coverage_factor = self.task_config["coverage_factor"] + self.num_markers = self.task_config["num_markers"] + + # settings for thresholds + self.contact_threshold = self.task_config["contact_threshold"] + self.pressure_threshold = self.task_config["pressure_threshold"] + self.pressure_threshold_max = self.task_config["pressure_threshold_max"] + + # misc settings + self.print_results = self.task_config["print_results"] + self.get_info = self.task_config["get_info"] + self.use_robot_obs = self.task_config["use_robot_obs"] + self.use_contact_obs = self.task_config["use_contact_obs"] + self.early_terminations = self.task_config["early_terminations"] + self.use_condensed_obj_obs = self.task_config["use_condensed_obj_obs"] + + # Scale reward if desired (see reward method for details) + self.reward_normalization_factor = horizon / ( + self.num_markers * self.unit_wiped_reward + horizon * (self.wipe_contact_reward + self.task_complete_reward) + ) + + # set other wipe-specific attributes + self.wiped_markers = [] + self.collisions = 0 + self.f_excess = 0 + self.metadata = [] + self.spec = "spec" + + # whether to include and use ground-truth object states + self.use_object_obs = use_object_obs + + super().__init__( + robots=robots, + env_configuration=env_configuration, + controller_configs=controller_configs, + base_types="default", + gripper_types=gripper_types, + initialization_noise=initialization_noise, + use_camera_obs=use_camera_obs, + has_renderer=has_renderer, + has_offscreen_renderer=has_offscreen_renderer, + render_camera=render_camera, + render_collision_mesh=render_collision_mesh, + render_visual_mesh=render_visual_mesh, + render_gpu_device_id=render_gpu_device_id, + control_freq=control_freq, + lite_physics=lite_physics, + horizon=horizon, + ignore_done=ignore_done, + hard_reset=hard_reset, + camera_names=camera_names, + camera_heights=camera_heights, + camera_widths=camera_widths, + camera_depths=camera_depths, + camera_segmentations=camera_segmentations, + renderer=renderer, + renderer_config=renderer_config, + ) + + # set after init to ensure self.robots is set + self.ee_force_bias = {arm: np.zeros(3) for arm in self.robots[0].arms} + self.ee_torque_bias = {arm: np.zeros(3) for arm in self.robots[0].arms} + + def _get_active_markers(self, c_geoms): + """ + Get the markers that are currently being wiped by the tool + + Args: + c_geoms (list): List of corner geoms for the tool + + Returns: + list: List of active markers + """ + active_markers = [] + corner1_id = self.sim.model.geom_name2id(c_geoms[0]) + corner1_pos = np.array(self.sim.data.geom_xpos[corner1_id]) + corner2_id = self.sim.model.geom_name2id(c_geoms[1]) + corner2_pos = np.array(self.sim.data.geom_xpos[corner2_id]) + corner3_id = self.sim.model.geom_name2id(c_geoms[2]) + corner3_pos = np.array(self.sim.data.geom_xpos[corner3_id]) + corner4_id = self.sim.model.geom_name2id(c_geoms[3]) + corner4_pos = np.array(self.sim.data.geom_xpos[corner4_id]) + + # Unit vectors on my plane + v1 = corner1_pos - corner2_pos + v1 /= np.linalg.norm(v1) + v2 = corner4_pos - corner2_pos + v2 /= np.linalg.norm(v2) + + # Corners of the tool in the coordinate frame of the plane + t1 = np.array([np.dot(corner1_pos - corner2_pos, v1), np.dot(corner1_pos - corner2_pos, v2)]) + t2 = np.array([np.dot(corner2_pos - corner2_pos, v1), np.dot(corner2_pos - corner2_pos, v2)]) + t3 = np.array([np.dot(corner3_pos - corner2_pos, v1), np.dot(corner3_pos - corner2_pos, v2)]) + t4 = np.array([np.dot(corner4_pos - corner2_pos, v1), np.dot(corner4_pos - corner2_pos, v2)]) + + pp = [t1, t2, t4, t3] + + # Normal of the plane defined by v1 and v2 + n = np.cross(v1, v2) + n /= np.linalg.norm(n) + + def isLeft(P0, P1, P2): + return (P1[0] - P0[0]) * (P2[1] - P0[1]) - (P2[0] - P0[0]) * (P1[1] - P0[1]) + + def PointInRectangle(X, Y, Z, W, P): + return isLeft(X, Y, P) < 0 and isLeft(Y, Z, P) < 0 and isLeft(Z, W, P) < 0 and isLeft(W, X, P) < 0 + + # Only go into this computation if there are contact points + if self.sim.data.ncon != 0: + + # Check each marker that is still active + for marker in self.model.mujoco_arena.markers: + + # Current marker 3D location in world frame + marker_pos = np.array(self.sim.data.body_xpos[self.sim.model.body_name2id(marker.root_body)]) + + # We use the second tool corner as point on the plane and define the vector connecting + # the marker position to that point + v = marker_pos - corner2_pos + + # Shortest distance between the center of the marker and the plane + dist = np.dot(v, n) + + # Projection of the center of the marker onto the plane + projected_point = np.array(marker_pos) - dist * n + + # Positive distances means the center of the marker is over the plane + # The plane is aligned with the bottom of the wiper and pointing up, so the marker would be over it + if dist > 0.0: + # Distance smaller than this threshold means we are close to the plane on the upper part + if dist < 0.02: + # Write touching points and projected point in coordinates of the plane + pp_2 = np.array( + [np.dot(projected_point - corner2_pos, v1), np.dot(projected_point - corner2_pos, v2)] + ) + # Check if marker is within the tool center: + if PointInRectangle(pp[0], pp[1], pp[2], pp[3], pp_2): + active_markers.append(marker) + return active_markers + + def reward(self, action=None): + """ + Reward function for the task. + + Sparse un-normalized reward: + + - a discrete reward of self.unit_wiped_reward is provided per single dirt (peg) wiped during this step + - a discrete reward of self.task_complete_reward is provided if all dirt is wiped + + Note that if the arm is either colliding or near its joint limit, a reward of 0 will be automatically given + + Un-normalized summed components if using reward shaping (individual components can be set to 0: + + - Reaching: in [0, self.distance_multiplier], proportional to distance between wiper and centroid of dirt + and zero if the table has been fully wiped clean of all the dirt + - Table Contact: in {0, self.wipe_contact_reward}, non-zero if wiper is in contact with table + - Wiping: in {0, self.unit_wiped_reward}, non-zero for each dirt (peg) wiped during this step + - Cleaned: in {0, self.task_complete_reward}, non-zero if no dirt remains on the table + - Collision / Joint Limit Penalty: in {self.arm_limit_collision_penalty, 0}, nonzero if robot arm + is colliding with an object + - Note that if this value is nonzero, no other reward components can be added + - Large Force Penalty: in [-inf, 0], scaled by wiper force and directly proportional to + self.excess_force_penalty_mul if the current force exceeds self.pressure_threshold_max + - Large Acceleration Penalty: in [-inf, 0], scaled by estimated wiper acceleration and directly + proportional to self.ee_accel_penalty + + Note that the final per-step reward is normalized given the theoretical best episode return and then scaled: + reward_scale * (horizon / + (num_markers * unit_wiped_reward + horizon * (wipe_contact_reward + task_complete_reward))) + + Args: + action (np array): [NOT USED] + + Returns: + float: reward value + """ + reward = 0 + + total_force_ee = max( + [ + np.linalg.norm(np.array(self.robots[0].recent_ee_forcetorques[arm].current[:3])) + for arm in self.robots[0].arms + ] + ) + + # Neg Reward from collisions of the arm with the table + if self.check_contact(self.robots[0].robot_model): + if self.reward_shaping: + reward = self.arm_limit_collision_penalty + self.collisions += 1 + elif self.robots[0].check_q_limits(): + if self.reward_shaping: + reward = self.arm_limit_collision_penalty + self.collisions += 1 + else: + # If the arm is not colliding or in joint limits, we check if we are wiping + # (we don't want to reward wiping if there are unsafe situations) + active_markers = [] + + # Current 3D location of the corners of the wiping tool in world frame + for arm in self.robots[0].arms: + c_geoms = self.robots[0].gripper[arm].important_geoms["corners"] + active_markers += self._get_active_markers(c_geoms) + + # Obtain the list of currently active (wiped) markers that where not wiped before + # These are the markers we are wiping at this step + lall = np.where(np.isin(active_markers, self.wiped_markers, invert=True)) + new_active_markers = np.array(active_markers)[lall] + + # Loop through all new markers we are wiping at this step + for new_active_marker in new_active_markers: + # Grab relevant marker id info + new_active_marker_geom_id = self.sim.model.geom_name2id(new_active_marker.visual_geoms[0]) + # Make this marker transparent since we wiped it (alpha = 0) + self.sim.model.geom_rgba[new_active_marker_geom_id][3] = 0 + # Add this marker the wiped list + self.wiped_markers.append(new_active_marker) + # Add reward if we're using the dense reward + if self.reward_shaping: + reward += self.unit_wiped_reward + + # Additional reward components if using dense rewards + if self.reward_shaping: + # If we haven't wiped all the markers yet, add a smooth reward for getting closer + # to the centroid of the dirt to wipe + if len(self.wiped_markers) < self.num_markers: + _, _, mean_pos_to_things_to_wipe = self._get_wipe_information() + mean_distance_to_things_to_wipe = np.linalg.norm(mean_pos_to_things_to_wipe) + reward += self.distance_multiplier * ( + 1 - np.tanh(self.distance_th_multiplier * mean_distance_to_things_to_wipe) + ) + + # Reward for keeping contact + if self.sim.data.ncon != 0 and self._has_gripper_contact: + reward += self.wipe_contact_reward + + # Penalty for excessive force with the end-effector + if total_force_ee > self.pressure_threshold_max: + reward -= self.excess_force_penalty_mul * total_force_ee + self.f_excess += 1 + + # Reward for pressing into table + # TODO: Need to include this computation somehow in the scaled reward computation + elif total_force_ee > self.pressure_threshold and self.sim.data.ncon > 1: + reward += self.wipe_contact_reward + 0.01 * total_force_ee + if self.sim.data.ncon > 50: + reward += 10.0 * self.wipe_contact_reward + + # Penalize large accelerations + reward -= self.ee_accel_penalty * max( + [np.mean(abs(self.robots[0].recent_ee_acc[arm].current)) for arm in self.robots[0].arms] + ) + + # Final reward if all wiped + if len(self.wiped_markers) == self.num_markers: + reward += self.task_complete_reward + + # Printing results + if self.print_results: + string_to_print = ( + "Process {pid}, timestep {ts:>4}: reward: {rw:8.4f}" + "wiped markers: {ws:>3} collisions: {sc:>3} f-excess: {fe:>3}".format( + pid=id(multiprocessing.current_process()), + ts=self.timestep, + rw=reward, + ws=len(self.wiped_markers), + sc=self.collisions, + fe=self.f_excess, + ) + ) + print(string_to_print) + + # If we're scaling our reward, we normalize the per-step rewards given the theoretical best episode return + # This is equivalent to scaling the reward by: + # reward_scale * (horizon / + # (num_markers * unit_wiped_reward + horizon * (wipe_contact_reward + task_complete_reward))) + if self.reward_scale: + reward *= self.reward_scale * self.reward_normalization_factor + return reward + + def _load_model(self): + """ + Loads an xml model, puts it in self.model + """ + super()._load_model() + + # Adjust base pose accordingly + xpos = self.robots[0].robot_model.base_xpos_offset["table"](self.table_full_size[0]) + self.robots[0].robot_model.set_base_xpos(xpos) + + # Get robot's contact geoms + self.robot_contact_geoms = self.robots[0].robot_model.contact_geoms + + mujoco_arena = WipeArena( + table_full_size=self.table_full_size, + table_friction=self.table_friction, + table_offset=self.table_offset, + table_friction_std=self.table_friction_std, + coverage_factor=self.coverage_factor, + num_markers=self.num_markers, + line_width=self.line_width, + two_clusters=self.two_clusters, + ) + + # Arena always gets set to zero origin + mujoco_arena.set_origin([0, 0, 0]) + + # task includes arena, robot, and objects of interest + self.model = ManipulationTask( + mujoco_arena=mujoco_arena, + mujoco_robots=[robot.robot_model for robot in self.robots], + ) + + def _setup_observables(self): + """ + Sets up observables to be used for this environment. Creates object-based observables if enabled + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + observables = super()._setup_observables() + + # Get prefix from robot model to avoid naming clashes for multiple robots + pf = self.robots[0].robot_model.naming_prefix + modality = "object" + + sensors = [] + names = [] + + # Add binary contact observation + if self.use_contact_obs: + + @sensor(modality=f"{pf}proprio") + def gripper_contact(obs_cache): + return self._has_gripper_contact + + sensors.append(gripper_contact) + names.append(f"{pf}contact") + + # object information in the observation + if self.use_object_obs: + + if self.use_condensed_obj_obs: + # use implicit representation of wiping objects + @sensor(modality=modality) + def wipe_radius(obs_cache): + wipe_rad, wipe_cent, _ = self._get_wipe_information() + obs_cache["wipe_centroid"] = wipe_cent + return wipe_rad + + @sensor(modality=modality) + def wipe_centroid(obs_cache): + return obs_cache["wipe_centroid"] if "wipe_centroid" in obs_cache else np.zeros(3) + + @sensor(modality=modality) + def proportion_wiped(obs_cache): + return len(self.wiped_markers) / self.num_markers + + sensors += [proportion_wiped, wipe_radius, wipe_centroid] + names += ["proportion_wiped", "wipe_radius", "wipe_centroid"] + + if self.use_robot_obs: + arm_prefixes = self._get_arm_prefixes(self.robots[0], include_robot_name=False) + full_prefixes = self._get_arm_prefixes(self.robots[0]) + + # also use ego-centric obs + robot_obs_sensors = [ + self._get_obj_eef_sensor( + full_pf, "wipe_centroid", f"{arm_pf}gripper_to_wipe_centroid", modality + ) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + + sensors.extend(robot_obs_sensors) + names.extend([fn.__name__ for fn in robot_obs_sensors]) + + else: + # use explicit representation of wiping objects + for i, marker in enumerate(self.model.mujoco_arena.markers): + marker_sensors, marker_sensor_names = self._create_marker_sensors(i, marker, modality) + sensors += marker_sensors + names += marker_sensor_names + + # Create observables + for name, s in zip(names, sensors): + observables[name] = Observable( + name=name, + sensor=s, + sampling_rate=self.control_freq, + ) + + return observables + + def _create_marker_sensors(self, i, marker, modality="object"): + """ + Helper function to create sensors for a given marker. This is abstracted in a separate function call so that we + don't have local function naming collisions during the _setup_observables() call. + + Args: + i (int): ID number corresponding to the marker + marker (MujocoObject): Marker to create sensors for + modality (str): Modality to assign to all sensors + + Returns: + 2-tuple: + sensors (list): Array of sensors for the given marker + names (list): array of corresponding observable names + """ + + @sensor(modality=modality) + def marker_pos(obs_cache): + return np.array(self.sim.data.body_xpos[self.sim.model.body_name2id(marker.root_body)]) + + @sensor(modality=modality) + def marker_wiped(obs_cache): + return [0, 1][marker in self.wiped_markers] + + sensors = [marker_pos, marker_wiped] + names = [f"marker{i}_pos", f"marker{i}_wiped"] + + if self.use_robot_obs: + arm_prefixes = self._get_arm_prefixes(self.robots[0], include_robot_name=False) + full_prefixes = self._get_arm_prefixes(self.robots[0]) + grippers_to_marker_fns = [ + self._get_obj_eef_sensor(full_pf, f"marker{i}_pos", f"{arm_pf}gripper_to_marker{i}", modality) + for arm_pf, full_pf in zip(arm_prefixes, full_prefixes) + ] + + sensors.extend(grippers_to_marker_fns) + names.extend([fn.__name__ for fn in grippers_to_marker_fns]) + + return sensors, names + + def _reset_internal(self): + super()._reset_internal() + + # inherited class should reset positions of objects (only if we're not using a deterministic reset) + if not self.deterministic_reset: + self.model.mujoco_arena.reset_arena(self.sim) + + # Reset all internal vars for this wipe task + self.timestep = 0 + self.wiped_markers = [] + self.collisions = 0 + self.f_excess = 0 + + # ee resets - bias at initial state + self.ee_force_bias = {arm: np.zeros(3) for arm in self.robots[0].arms} + self.ee_torque_bias = {arm: np.zeros(3) for arm in self.robots[0].arms} + + def _check_success(self): + """ + Checks if Task succeeds (all dirt wiped). + + Returns: + bool: True if completed task + """ + return True if len(self.wiped_markers) == self.num_markers else False + + def _check_terminated(self): + """ + Check if the task has completed one way or another. The following conditions lead to termination: + + - Collision + - Task completion (wiping succeeded) + - Joint Limit reached + + Returns: + bool: True if episode is terminated + """ + + terminated = False + + # Prematurely terminate if contacting the table with the arm + if self.check_contact(self.robots[0].robot_model): + if self.print_results: + print(40 * "-" + " COLLIDED " + 40 * "-") + terminated = True + + # Prematurely terminate if task is success + if self._check_success(): + if self.print_results: + print(40 * "+" + " FINISHED WIPING " + 40 * "+") + terminated = True + + # Prematurely terminate if contacting the table with the arm + if self.robots[0].check_q_limits(): + if self.print_results: + print(40 * "-" + " JOINT LIMIT " + 40 * "-") + terminated = True + + return terminated + + def _post_action(self, action): + """ + In addition to super method, add additional info if requested + + Args: + action (np.array): Action to execute within the environment + + Returns: + 3-tuple: + + - (float) reward from the environment + - (bool) whether the current episode is completed or not + - (dict) info about current env step + """ + reward, done, info = super()._post_action(action) + + # Update force bias + if all([np.linalg.norm(self.ee_force_bias[arm]) == 0 for arm in self.ee_force_bias]): + self.ee_force_bias = self.robots[0].ee_force + self.ee_torque_bias = self.robots[0].ee_torque + + if self.get_info: + info["add_vals"] = ["nwipedmarkers", "colls", "percent_viapoints_", "f_excess"] + info["nwipedmarkers"] = len(self.wiped_markers) + info["colls"] = self.collisions + info["percent_viapoints_"] = len(self.wiped_markers) / self.num_markers + info["f_excess"] = self.f_excess + + # allow episode to finish early if allowed + if self.early_terminations: + done = done or self._check_terminated() + + return reward, done, info + + def _get_wipe_information(self): + """Returns set of wiping information""" + mean_pos_to_things_to_wipe = np.zeros(3) + wipe_centroid = np.zeros(3) + marker_positions = [] + num_non_wiped_markers = 0 + if len(self.wiped_markers) < self.num_markers: + for marker in self.model.mujoco_arena.markers: + if marker not in self.wiped_markers: + marker_pos = np.array(self.sim.data.body_xpos[self.sim.model.body_name2id(marker.root_body)]) + wipe_centroid += marker_pos + marker_positions.append(marker_pos) + num_non_wiped_markers += 1 + wipe_centroid /= max(1, num_non_wiped_markers) + + # Mean position to things to wipe to the closest arm + mean_pos_to_things_to_wipe_list = [wipe_centroid - self._get_eef_xpos(arm) for arm in self.robots[0].arms] + mean_pos_to_things_to_wipe = mean_pos_to_things_to_wipe_list[ + np.argmin([np.linalg.norm(x) for x in mean_pos_to_things_to_wipe_list]) + ] + # Radius of circle from centroid capturing all remaining wiping markers + max_radius = 0 + if num_non_wiped_markers > 0: + max_radius = np.max(np.linalg.norm(np.array(marker_positions) - wipe_centroid, axis=1)) + # Return all values + return max_radius, wipe_centroid, mean_pos_to_things_to_wipe + + def _get_eef_xpos(self, arm): + """ + Grabs End Effector position as specifed by the arm argument + + Args: + arm (str): Arm name + + Returns: + np.array: End effector(x,y,z) + """ + return np.array(self.sim.data.site_xpos[self.robots[0].eef_site_id[arm]]) + + @property + def _has_gripper_contact(self): + """ + Determines whether the any of the grippers are making contact with an object, as defined by the eef force surprassing + a certain threshold defined by self.contact_threshold + + Returns: + bool: True if contact is surpasses given threshold magnitude + """ + return any( + [ + np.linalg.norm(self.robots[0].ee_force[arm] - self.ee_force_bias[arm]) > self.contact_threshold + for arm in self.robots[0].arms + ] + ) diff --git a/third_party/robosuite/robosuite/environments/robot_env.py b/third_party/robosuite/robosuite/environments/robot_env.py new file mode 100644 index 0000000000000000000000000000000000000000..9c58f2964a54ad07264f3d641323cd29012263e2 --- /dev/null +++ b/third_party/robosuite/robosuite/environments/robot_env.py @@ -0,0 +1,623 @@ +from collections import OrderedDict +from copy import deepcopy + +import numpy as np + +import robosuite.macros as macros +from robosuite.environments.base import MujocoEnv +from robosuite.robots import ROBOT_CLASS_MAPPING +from robosuite.utils.mjcf_utils import IMAGE_CONVENTION_MAPPING +from robosuite.utils.observables import Observable, sensor + + +class RobotEnv(MujocoEnv): + """ + Initializes a robot environment in Mujoco. + + Args: + robots: Specification for specific robot(s) to be instantiated within this env + + env_configuration (str): Specifies how to position the robot(s) within the environment. Default is "default", + which should be interpreted accordingly by any subclasses. + + controller_configs (str or list of dict): If set, contains relevant controller parameters for creating a + custom controller. Else, uses the default controller for this specific task. Should either be single + dict if same controller is to be used for all robots or else it should be a list of the same length as + "robots" param + + mount_types (None or str or list of str): type of mount, used to instantiate mount models from mount factory. + Default is "default", which is the default mount associated with the robot(s) the 'robots' specification. + None results in no mount, and any other (valid) model overrides the default mount. Should either be + single str if same mount type is to be used for all robots or else it should be a list of the same + length as "robots" param + + initialization_noise (dict or list of dict): Dict containing the initialization noise parameters. + The expected keys and corresponding value types are specified below: + + :`'magnitude'`: The scale factor of uni-variate random noise applied to each of a robot's given initial + joint positions. Setting this value to `None` or 0.0 results in no noise being applied. + If "gaussian" type of noise is applied then this magnitude scales the standard deviation applied, + If "uniform" type of noise is applied then this magnitude sets the bounds of the sampling range + :`'type'`: Type of noise to apply. Can either specify "gaussian" or "uniform" + + Should either be single dict if same noise value is to be used for all robots or else it should be a + list of the same length as "robots" param + + :Note: Specifying "default" will automatically use the default noise settings. + Specifying None will automatically create the required dict with "magnitude" set to 0.0. + + use_camera_obs (bool): if True, every observation includes rendered image(s) + + has_renderer (bool): If true, render the simulation state in + a viewer instead of headless mode. + + has_offscreen_renderer (bool): True if using off-screen rendering + + render_camera (str): Name of camera to render if `has_renderer` is True. Setting this value to 'None' + will result in the default angle being applied, which is useful as it can be dragged / panned by + the user using the mouse + + render_collision_mesh (bool): True if rendering collision meshes in camera. False otherwise. + + render_visual_mesh (bool): True if rendering visual meshes in camera. False otherwise. + + render_gpu_device_id (int): corresponds to the GPU device id to use for offscreen rendering. + Defaults to -1, in which case the device will be inferred from environment variables + (GPUS or CUDA_VISIBLE_DEVICES). + + control_freq (float): how many control signals to receive in every second. This sets the amount of + simulation time that passes between every action input. + + lite_physics (bool): Whether to optimize for mujoco forward and step calls to reduce total simulation overhead. + Set to False to preserve backward compatibility with datasets collected in robosuite <= 1.4.1. + + horizon (int): Every episode lasts for exactly @horizon timesteps. + + ignore_done (bool): True if never terminating the environment (ignore @horizon). + + hard_reset (bool): If True, re-loads model, sim, and render object upon a reset call, else, + only calls sim.reset and resets all robosuite-internal variables + + camera_names (str or list of str): name of camera to be rendered. Should either be single str if + same name is to be used for all cameras' rendering or else it should be a list of cameras to render. + + :Note: At least one camera must be specified if @use_camera_obs is True. + + :Note: To render all robots' cameras of a certain type (e.g.: "robotview" or "eye_in_hand"), use the + convention "all-{name}" (e.g.: "all-robotview") to automatically render all camera images from each + robot's camera list). + + camera_heights (int or list of int): height of camera frame. Should either be single int if + same height is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_widths (int or list of int): width of camera frame. Should either be single int if + same width is to be used for all cameras' frames or else it should be a list of the same length as + "camera names" param. + + camera_depths (bool or list of bool): True if rendering RGB-D, and RGB otherwise. Should either be single + bool if same depth setting is to be used for all cameras or else it should be a list of the same length as + "camera names" param. + + camera_segmentations (None or str or list of str or list of list of str): Camera segmentation(s) to use + for each camera. Valid options are: + + `None`: no segmentation sensor used + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + + If not None, multiple types of segmentations can be specified. A [list of str / str or None] specifies + [multiple / a single] segmentation(s) to use for all cameras. A list of list of str specifies per-camera + segmentation setting(s) to use. + + robot_configs (list of dict): Per-robot configurations set from any subclass initializers. + + seed (int): environment seed. Default is None, where environment is unseeded, ie. random + + Raises: + ValueError: [Camera obs require offscreen renderer] + ValueError: [Camera name must be specified to use camera obs] + """ + + def __init__( + self, + robots, + env_configuration="default", + base_types="default", + controller_configs=None, + initialization_noise=None, + use_camera_obs=True, + has_renderer=False, + has_offscreen_renderer=True, + render_camera="frontview", + render_collision_mesh=False, + render_visual_mesh=True, + render_gpu_device_id=-1, + control_freq=20, + lite_physics=True, + horizon=1000, + ignore_done=False, + hard_reset=True, + camera_names="agentview", + camera_heights=256, + camera_widths=256, + camera_depths=False, + camera_segmentations=None, + robot_configs=None, + renderer="mjviewer", + renderer_config=None, + seed=None, + ): + # First, verify that correct number of robots are being inputted + self.env_configuration = env_configuration + self._check_robot_configuration(robots) + + # Robot + robots = list(robots) if type(robots) is list or type(robots) is tuple else [robots] + self.num_robots = len(robots) + self.robot_names = robots + self.robots = self._input2list(None, self.num_robots) + self._action_dim = None + + # Robot base + base_types = self._input2list(base_types, self.num_robots) + + # Composite Controller + controller_configs = self._input2list(controller_configs, self.num_robots) + + # Initialization Noise + initialization_noise = self._input2list(initialization_noise, self.num_robots) + + # Observations -- Ground truth = object_obs, Image data = camera_obs + self.use_camera_obs = use_camera_obs + + # Camera / Rendering Settings + self.has_offscreen_renderer = has_offscreen_renderer + self.camera_names = ( + list(camera_names) if type(camera_names) is list or type(camera_names) is tuple else [camera_names] + ) + self.num_cameras = len(self.camera_names) + + self.camera_heights = self._input2list(camera_heights, self.num_cameras) + self.camera_widths = self._input2list(camera_widths, self.num_cameras) + self.camera_depths = self._input2list(camera_depths, self.num_cameras) + self.camera_segmentations = self._input2list(camera_segmentations, self.num_cameras) + # We need to parse camera segmentations more carefully since it may be a nested list + seg_is_nested = False + for i, camera_s in enumerate(self.camera_segmentations): + if isinstance(camera_s, list) or isinstance(camera_s, tuple): + seg_is_nested = True + break + camera_segs = deepcopy(self.camera_segmentations) + for i, camera_s in enumerate(self.camera_segmentations): + if camera_s is not None: + self.camera_segmentations[i] = self._input2list(camera_s, 1) if seg_is_nested else deepcopy(camera_segs) + + # sanity checks for camera rendering + if self.use_camera_obs and not self.has_offscreen_renderer: + raise ValueError("Error: Camera observations require an offscreen renderer!") + if self.use_camera_obs and self.camera_names is None: + raise ValueError("Must specify at least one camera name when using camera obs") + + # Robot configurations -- update from subclass configs + if robot_configs is None: + robot_configs = [{} for _ in range(self.num_robots)] + self.robot_configs = [ + dict( + **{ + "composite_controller_config": controller_configs[idx], + "base_type": base_types[idx], + "initialization_noise": initialization_noise[idx], + "control_freq": control_freq, + "lite_physics": lite_physics, + }, + **robot_config, + ) + for idx, robot_config in enumerate(robot_configs) + ] + + # Run superclass init + super().__init__( + has_renderer=has_renderer, + has_offscreen_renderer=self.has_offscreen_renderer, + render_camera=render_camera, + render_collision_mesh=render_collision_mesh, + render_visual_mesh=render_visual_mesh, + render_gpu_device_id=render_gpu_device_id, + control_freq=control_freq, + lite_physics=lite_physics, + horizon=horizon, + ignore_done=ignore_done, + hard_reset=hard_reset, + renderer=renderer, + renderer_config=renderer_config, + seed=seed, + ) + + def visualize(self, vis_settings): + """ + In addition to super call, visualizes robots. + + Args: + vis_settings (dict): Visualization keywords mapped to T/F, determining whether that specific + component should be visualized. Should have "robots" keyword as well as any other relevant + options specified. + """ + # Run superclass method first + super().visualize(vis_settings=vis_settings) + # Loop over robots to visualize them independently + for robot in self.robots: + robot.visualize(vis_settings=vis_settings) + + @property + def _visualizations(self): + """ + Visualization keywords for this environment + + Returns: + set: All components that can be individually visualized for this environment + """ + vis_set = super()._visualizations + vis_set.add("robots") + return vis_set + + @property + def action_spec(self): + """ + Action space (low, high) for this environment + + Returns: + 2-tuple: + + - (np.array) minimum (low) action values + - (np.array) maximum (high) action values + """ + low, high = [], [] + for robot in self.robots: + lo, hi = robot.action_limits + low, high = np.concatenate([low, lo]), np.concatenate([high, hi]) + return low, high + + @property + def action_dim(self): + """ + Size of the action space + + Returns: + int: Action space dimension + """ + return self._action_dim + + @staticmethod + def _input2list(inp, length): + """ + Helper function that converts an input that is either a single value or a list into a list + + Args: + inp (None or str or list): Input value to be converted to list + length (int): Length of list to broadcast input to + + Returns: + list: input @inp converted into a list of length @length + """ + # convert to list if necessary + return list(inp) if type(inp) is list or type(inp) is tuple else [inp for _ in range(length)] + + def _load_model(self): + """ + Loads an xml model, puts it in self.model + """ + super()._load_model() + + # Load robots + self._load_robots() + + def _setup_references(self): + """ + Sets up references to important components. A reference is typically an + index or a list of indices that point to the corresponding elements + in a flatten array, which is how MuJoCo stores physical simulation data. + """ + super()._setup_references() + + # Setup robot-specific references as well (note: requires resetting of sim for robot first) + for robot in self.robots: + robot.reset_sim(self.sim) + robot.setup_references() + + def _setup_observables(self): + """ + Sets up observables to be used for this environment. Loops through all robots and grabs their corresponding + observables to add to the procedurally generated dict of observables + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + observables = super()._setup_observables() + # Loop through all robots and grab their observables, adding it to the proprioception modality + for robot in self.robots: + robot_obs = robot.setup_observables() + observables.update(robot_obs) + + # Loop through cameras and update the observations if using camera obs + if self.use_camera_obs: + # Create sensor information + sensors = [] + names = [] + for (cam_name, cam_w, cam_h, cam_d, cam_segs) in zip( + self.camera_names, + self.camera_widths, + self.camera_heights, + self.camera_depths, + self.camera_segmentations, + ): + + # Add cameras associated to our arrays + cam_sensors, cam_sensor_names = self._create_camera_sensors( + cam_name, cam_w=cam_w, cam_h=cam_h, cam_d=cam_d, cam_segs=cam_segs, modality="image" + ) + sensors += cam_sensors + names += cam_sensor_names + + # If any the camera segmentations are not None, then we shrink all the sites as a hacky way to + # prevent them from being rendered in the segmentation mask + if not all(seg is None for seg in self.camera_segmentations): + self.sim.model.site_size[:, :] = 1.0e-8 + + # Create observables for these cameras + for name, s in zip(names, sensors): + observables[name] = Observable( + name=name, + sensor=s, + sampling_rate=self.control_freq, + ) + + return observables + + def _create_camera_sensors(self, cam_name, cam_w, cam_h, cam_d, cam_segs, modality="image"): + """ + Helper function to create sensors for a given camera. This is abstracted in a separate function call so that we + don't have local function naming collisions during the _setup_observables() call. + Args: + cam_name (str): Name of camera to create sensors for + cam_w (int): Width of camera + cam_h (int): Height of camera + cam_d (bool): Whether to create a depth sensor as well + cam_segs (None or list): Type of segmentation(s) to use, where each entry can be the following: + `None`: no segmentation sensor used + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + + modality (str): Modality to assign to all sensors + Returns: + 2-tuple: + sensors (list): Array of sensors for the given camera + names (list): array of corresponding observable names + """ + # Make sure we get correct convention + convention = IMAGE_CONVENTION_MAPPING[macros.IMAGE_CONVENTION] + + # Create sensor information + sensors = [] + names = [] + + # Add camera observables to the dict + rgb_sensor_name = f"{cam_name}_image" + depth_sensor_name = f"{cam_name}_depth" + segmentation_sensor_name = f"{cam_name}_segmentation" + + @sensor(modality=modality) + def camera_rgb(obs_cache): + img = self.sim.render( + camera_name=cam_name, + width=cam_w, + height=cam_h, + depth=cam_d, + ) + if cam_d: + rgb, depth = img + obs_cache[depth_sensor_name] = np.expand_dims(depth[::convention], axis=-1) + return rgb[::convention] + else: + return img[::convention] + + sensors.append(camera_rgb) + names.append(rgb_sensor_name) + + if cam_d: + + @sensor(modality=modality) + def camera_depth(obs_cache): + return obs_cache[depth_sensor_name] if depth_sensor_name in obs_cache else np.zeros((cam_h, cam_w, 1)) + + sensors.append(camera_depth) + names.append(depth_sensor_name) + + if cam_segs is not None: + # Define mapping we'll use for segmentation + for cam_s in cam_segs: + seg_sensor, seg_sensor_name = self._create_segementation_sensor( + cam_name=cam_name, + cam_w=cam_w, + cam_h=cam_h, + cam_s=cam_s, + seg_name_root=segmentation_sensor_name, + modality=modality, + ) + + sensors.append(seg_sensor) + names.append(seg_sensor_name) + + return sensors, names + + def _create_segementation_sensor(self, cam_name, cam_w, cam_h, cam_s, seg_name_root, modality="image"): + """ + Helper function to create sensors for a given camera. This is abstracted in a separate function call so that we + don't have local function naming collisions during the _setup_observables() call. + + Args: + cam_name (str): Name of camera to create sensors for + cam_w (int): Width of camera + cam_h (int): Height of camera + cam_s (None or list): Type of segmentation to use, should be the following: + `'instance'`: segmentation at the class-instance level + `'class'`: segmentation at the class level + `'element'`: segmentation at the per-geom level + seg_name_root (str): Sensor name root to assign to this sensor + + modality (str): Modality to assign to all sensors + + Returns: + 2-tuple: + camera_segmentation (function): Generated sensor function for this segmentation sensor + name (str): Corresponding sensor name + """ + # Make sure we get correct convention + convention = IMAGE_CONVENTION_MAPPING[macros.IMAGE_CONVENTION] + + if cam_s == "instance": + name2id = {inst: i for i, inst in enumerate(list(self.model.instances_to_ids.keys()))} + mapping = {idn: name2id[inst] for idn, inst in self.model.geom_ids_to_instances.items()} + elif cam_s == "class": + name2id = {cls: i for i, cls in enumerate(list(self.model.classes_to_ids.keys()))} + mapping = {idn: name2id[cls] for idn, cls in self.model.geom_ids_to_classes.items()} + else: # element + # No additional mapping needed + mapping = None + + @sensor(modality=modality) + def camera_segmentation(obs_cache): + seg = self.sim.render( + camera_name=cam_name, + width=cam_w, + height=cam_h, + depth=False, + segmentation=True, + ) + seg = np.expand_dims(seg[::convention, :, 1], axis=-1) + # Map raw IDs to grouped IDs if we're using instance or class-level segmentation + if mapping is not None: + seg = ( + np.fromiter(map(lambda x: mapping.get(x, -1), seg.flatten()), dtype=np.int32).reshape( + cam_h, cam_w, 1 + ) + + 1 + ) + return seg + + name = f"{seg_name_root}_{cam_s}" + + return camera_segmentation, name + + def _reset_internal(self): + """ + Resets simulation internal configurations. + """ + # Run superclass reset functionality + super()._reset_internal() + + # Reset action dim + self._action_dim = 0 + + # Reset robot and update action space dimension along the way + for robot in self.robots: + robot.reset(deterministic=self.deterministic_reset) + self._action_dim += robot.action_dim + + # Update cameras if appropriate + if self.use_camera_obs: + temp_names = [] + for cam_name in self.camera_names: + if "all-" in cam_name: + # We need to add all robot-specific camera names that include the key after the tag "all-" + start_idx = len(temp_names) - 1 + key = cam_name.replace("all-", "") + for robot in self.robots: + for robot_cam_name in robot.robot_model.cameras: + if key in robot_cam_name: + temp_names.append(robot_cam_name) + # We also need to broadcast the corresponding values from each camera dimensions as well + end_idx = len(temp_names) - 1 + self.camera_widths = ( + self.camera_widths[:start_idx] + + [self.camera_widths[start_idx]] * (end_idx - start_idx) + + self.camera_widths[(start_idx + 1) :] + ) + self.camera_heights = ( + self.camera_heights[:start_idx] + + [self.camera_heights[start_idx]] * (end_idx - start_idx) + + self.camera_heights[(start_idx + 1) :] + ) + self.camera_depths = ( + self.camera_depths[:start_idx] + + [self.camera_depths[start_idx]] * (end_idx - start_idx) + + self.camera_depths[(start_idx + 1) :] + ) + else: + # We simply add this camera to the temp_names + temp_names.append(cam_name) + # Lastly, replace camera names with the updated ones + self.camera_names = temp_names + + def _pre_action(self, action, policy_step=False): + """ + Overrides the superclass method to control the robot(s) within this enviornment using their respective + controllers using the passed actions and gripper control. + + Args: + action (np.array): The control to apply to the robot(s). Note that this should be a flat 1D array that + encompasses all actions to be distributed to each robot if there are multiple. For each section of the + action space assigned to a single robot, the first @self.robots[i].controller.control_dim dimensions + should be the desired controller actions and if the robot has a gripper, the next + @self.robots[i].gripper.dof dimensions should be actuation controls for the gripper. + policy_step (bool): Whether a new policy step (action) is being taken + + Raises: + AssertionError: [Invalid action dimension] + """ + # Verify that the action is the correct dimension + assert len(action) == self.action_dim, "environment got invalid action dimension -- expected {}, got {}".format( + self.action_dim, len(action) + ) + + # Update robot joints based on controller actions + cutoff = 0 + for idx, robot in enumerate(self.robots): + robot_action = action[cutoff : cutoff + robot.action_dim] + robot.control(robot_action, policy_step=policy_step) + cutoff += robot.action_dim + + def _load_robots(self): + """ + Instantiates robots and stores them within the self.robots attribute + """ + # Loop through robots and instantiate Robot object for each + for idx, (name, config) in enumerate(zip(self.robot_names, self.robot_configs)): + # Create the robot instance + self.robots[idx] = ROBOT_CLASS_MAPPING[name](robot_type=name, idn=idx, **config) + # Now, load the robot models + self.robots[idx].load_model() + + def reward(self, action): + """ + Runs superclass method by default + """ + return super().reward(action) + + def _check_success(self): + """ + Runs superclass method by default + """ + return super()._check_success() + + def _check_robot_configuration(self, robots): + """ + Sanity check to make sure inputted robots and the corresponding requested task/configuration combo is legal. + Should be implemented in every specific task module + + Args: + robots (str or list of str): Inputted requested robots at the task-level environment + """ + raise NotImplementedError diff --git a/third_party/robosuite/robosuite/macros.py b/third_party/robosuite/robosuite/macros.py new file mode 100644 index 0000000000000000000000000000000000000000..06dac6a9b86840cc95c9f7cc6381ddcda4b37f69 --- /dev/null +++ b/third_party/robosuite/robosuite/macros.py @@ -0,0 +1,55 @@ +""" +Macro settings that can be imported and toggled. Internally, specific parts of the codebase rely on these settings +for determining core functionality. + +To make sure global reference is maintained, should import these settings as: + +`import robosuite.macros as macros` +""" + +# Global Mujoco Simulation Parameters +SIMULATION_TIMESTEP = 0.002 # Internal simulation timestep (in seconds) + +# Instance Randomization +# Used if we want to randomize geom groups uniformly per instance -- e.g.: entire robot arm, vs. per-joint geom +# This should get set to True in your script BEFORE an environment is created or the DR wrapper is used +USING_INSTANCE_RANDOMIZATION = False + +# Numba settings +# TODO: Numba causes BSOD for NutAssembly task when rendering offscreen (deterministically!) +ENABLE_NUMBA = True +CACHE_NUMBA = True + +# Image Convention +# Robosuite (Mujoco)-rendered images are based on the OpenGL coordinate frame convention, whereas many downstream +# applications assume an OpenCV coordinate frame convention. For consistency, you can set the image convention +# here; this will assure that any rendered frames will match the associated convention. +# See the figure at the bottom of https://amytabb.com/ts/2019_06_28/ for an informative overview. +IMAGE_CONVENTION = "opengl" # Options are {"opengl", "opencv"} + +# Image concatenation +# In general, observations are concatenated together by modality. However, image observations are expensive memory-wise, +# so we skip concatenating all images together by default, unless this flag is set to True +CONCATENATE_IMAGES = False + +MUJOCO_GPU_RENDERING = True + +# Spacemouse settings. Used by SpaceMouse class in robosuite/devices/spacemouse.py +SPACEMOUSE_VENDOR_ID = 9583 +SPACEMOUSE_PRODUCT_ID = 50734 + +# If LOGGING LEVEL is set to None, the logger will be turned off +CONSOLE_LOGGING_LEVEL = "INFO" +# File logging is written to /tmp/robosuite_{time}_{pid}.log by default +FILE_LOGGING_LEVEL = None + +# Override with macros from macros_private.py file, if it exists +try: + from robosuite.macros_private import * +except ImportError: + import robosuite + from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER + + ROBOSUITE_DEFAULT_LOGGER.warning("No private macro file found!") + ROBOSUITE_DEFAULT_LOGGER.warning("It is recommended to use a private macro file") + ROBOSUITE_DEFAULT_LOGGER.warning("To setup, run: python {}/scripts/setup_macros.py".format(robosuite.__path__[0])) diff --git a/third_party/robosuite/robosuite/models/__init__.py b/third_party/robosuite/robosuite/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..73dc77f94297a4ff36e4db5e3e360f691189f6f8 --- /dev/null +++ b/third_party/robosuite/robosuite/models/__init__.py @@ -0,0 +1,4 @@ +import os +from .world import MujocoWorldBase + +assets_root = os.path.join(os.path.dirname(__file__), "assets") diff --git a/third_party/robosuite/robosuite/models/arenas/__init__.py b/third_party/robosuite/robosuite/models/arenas/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0ec058e8377099efdebcaeac091b19cb56942759 --- /dev/null +++ b/third_party/robosuite/robosuite/models/arenas/__init__.py @@ -0,0 +1,7 @@ +from .arena import Arena +from .table_arena import TableArena +from .multi_table_arena import MultiTableArena +from .pegs_arena import PegsArena +from .bins_arena import BinsArena +from .empty_arena import EmptyArena +from .wipe_arena import WipeArena diff --git a/third_party/robosuite/robosuite/models/arenas/arena.py b/third_party/robosuite/robosuite/models/arenas/arena.py new file mode 100644 index 0000000000000000000000000000000000000000..ff775eca2ac4456ed89f8e2c8af624d86b1d264c --- /dev/null +++ b/third_party/robosuite/robosuite/models/arenas/arena.py @@ -0,0 +1,131 @@ +import numpy as np + +from robosuite.models.base import MujocoXML +from robosuite.utils.mjcf_utils import ( + ENVIRONMENT_COLLISION_COLOR, + array_to_string, + find_elements, + new_body, + new_element, + new_geom, + new_joint, + recolor_collision_geoms, + string_to_array, +) + + +class Arena(MujocoXML): + """Base arena class.""" + + def __init__(self, fname): + super().__init__(fname) + # Get references to floor and bottom + self.bottom_pos = np.zeros(3) + self.floor = self.worldbody.find("./geom[@name='floor']") + + # Add mocap bodies to self.root for mocap control in mjviewer UI for robot control + mocap_body_1 = new_body(name="left_eef_target", pos="0 0 -1", mocap=True) + mocap_body_1_geom = new_geom( + name="left_eef_target_box", + type="box", + size="0.05 0.05 0.05", + rgba="0.898 0.420 0.435 0.5", + conaffinity="0", + contype="0", + group="2", + ) + mocap_body_1_sphere = new_geom( + name="left_eef_target_sphere", + type="sphere", + size="0.01", + pos="0 0 0", + rgba="0.898 0.420 0.435 0.8", + conaffinity="0", + contype="0", + group="2", + ) + mocap_body_2 = new_body(name="right_eef_target", pos="0 0 -1", mocap=True) + mocap_body_2_geom = new_geom( + name="right_eef_target_box", + type="box", + size="0.05 0.05 0.05", + rgba="0.208 0.314 0.439 0.5", + conaffinity="0", + contype="0", + group="2", + ) + mocap_body_2_sphere = new_geom( + name="right_eef_target_sphere", + type="sphere", + size="0.01", + pos="0 0 0", + rgba="0.208 0.314 0.439 0.8", + conaffinity="0", + contype="0", + group="2", + ) + # Append the box and sphere geometries to their respective mocap bodies + mocap_body_1.append(mocap_body_1_geom) + mocap_body_1.append(mocap_body_1_sphere) + mocap_body_2.append(mocap_body_2_geom) + mocap_body_2.append(mocap_body_2_sphere) + # Add the mocap bodies to the world + self.worldbody.append(mocap_body_1) + self.worldbody.append(mocap_body_2) + + # Run any necessary post-processing on the model + self._postprocess_arena() + + # Recolor all geoms + recolor_collision_geoms( + root=self.worldbody, + rgba=ENVIRONMENT_COLLISION_COLOR, + exclude=lambda e: True if e.get("name", None) == "floor" else False, + ) + + def set_origin(self, offset): + """ + Applies a constant offset to all objects. + + Args: + offset (3-tuple): (x,y,z) offset to apply to all nodes in this XML + """ + offset = np.array(offset) + for node in self.worldbody.findall("./*[@pos]"): + cur_pos = string_to_array(node.get("pos")) + new_pos = cur_pos + offset + node.set("pos", array_to_string(new_pos)) + + def set_camera(self, camera_name, pos, quat, camera_attribs=None): + """ + Sets a camera with @camera_name. If the camera already exists, then this overwrites its pos and quat values. + + Args: + camera_name (str): Camera name to search for / create + pos (3-array): (x,y,z) coordinates of camera in world frame + quat (4-array): (w,x,y,z) quaternion of camera in world frame + camera_attribs (dict): If specified, should be additional keyword-mapped attributes for this camera. + See http://www.mujoco.org/book/XMLreference.html#camera for exact attribute specifications. + """ + # Determine if camera already exists + camera = find_elements(root=self.worldbody, tags="camera", attribs={"name": camera_name}, return_first=True) + + # Compose attributes + if camera_attribs is None: + camera_attribs = {} + camera_attribs["pos"] = array_to_string(pos) + camera_attribs["quat"] = array_to_string(quat) + + if camera is None: + # If camera doesn't exist, then add a new camera with the specified attributes + self.worldbody.append(new_element(tag="camera", name=camera_name, **camera_attribs)) + else: + # Otherwise, we edit all specified attributes in that camera + for attrib, value in camera_attribs.items(): + camera.set(attrib, value) + + def _postprocess_arena(self): + """ + Runs any necessary post-processing on the imported Arena model + """ + pass diff --git a/third_party/robosuite/robosuite/models/arenas/bins_arena.py b/third_party/robosuite/robosuite/models/arenas/bins_arena.py new file mode 100644 index 0000000000000000000000000000000000000000..b50b40bcdd298a3398607fb284bf0a48962343f7 --- /dev/null +++ b/third_party/robosuite/robosuite/models/arenas/bins_arena.py @@ -0,0 +1,34 @@ +import numpy as np + +from robosuite.models.arenas import Arena +from robosuite.utils.mjcf_utils import array_to_string, xml_path_completion + + +class BinsArena(Arena): + """ + Workspace that contains two bins placed side by side. + + Args: + bin1_pos (3-tuple): (x,y,z) position to place bin1 + table_full_size (3-tuple): (L,W,H) full dimensions of the table + table_friction (3-tuple): (sliding, torsional, rolling) friction parameters of the table + """ + + def __init__( + self, bin1_pos=(0.1, -0.5, 0.8), table_full_size=(0.39, 0.49, 0.82), table_friction=(1, 0.005, 0.0001) + ): + super().__init__(xml_path_completion("arenas/bins_arena.xml")) + + self.table_full_size = np.array(table_full_size) + self.table_half_size = self.table_full_size / 2 + self.table_friction = table_friction + + self.bin1_body = self.worldbody.find("./body[@name='bin1']") + self.bin2_body = self.worldbody.find("./body[@name='bin2']") + self.table_top_abs = np.array(bin1_pos) + + self.configure_location() + + def configure_location(self): + """Configures correct locations for this arena""" + self.floor.set("pos", array_to_string(self.bottom_pos)) diff --git a/third_party/robosuite/robosuite/models/arenas/empty_arena.py b/third_party/robosuite/robosuite/models/arenas/empty_arena.py new file mode 100644 index 0000000000000000000000000000000000000000..e10da831b24b0c1870ffb640327cdf543efd02ab --- /dev/null +++ b/third_party/robosuite/robosuite/models/arenas/empty_arena.py @@ -0,0 +1,9 @@ +from robosuite.models.arenas import Arena +from robosuite.utils.mjcf_utils import xml_path_completion + + +class EmptyArena(Arena): + """Empty workspace.""" + + def __init__(self): + super().__init__(xml_path_completion("arenas/empty_arena.xml")) diff --git a/third_party/robosuite/robosuite/models/arenas/multi_table_arena.py b/third_party/robosuite/robosuite/models/arenas/multi_table_arena.py new file mode 100644 index 0000000000000000000000000000000000000000..f62ef357e2c45a483ac2643cdea084a7b9380722 --- /dev/null +++ b/third_party/robosuite/robosuite/models/arenas/multi_table_arena.py @@ -0,0 +1,149 @@ +from collections.abc import Iterable + +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.arenas import Arena +from robosuite.utils.mjcf_utils import ( + array_to_string, + new_body, + new_geom, + new_site, + string_to_array, + xml_path_completion, +) + + +class MultiTableArena(Arena): + """ + Workspace that contains multiple tables. + Args: + table_offsets (list of 3-array): (x,y,z) offset from center of arena when placing each table. + Note that the number of tables is inferred from the length of this list + Note that the z value sets the upper limit of the table + table_rots (float or list of float): z-rotation to apply to each table. If only a + single value is given, it will be broadcasted according to the total number of tables + table_full_sizes (3-array or list of 3-array): (L,W,H) full dimensions of each table. If only a + single value is given, it will be broadcasted according to the total number of tables + table_frictions (3-array or list of 3-array): (sliding, torsional, rolling) friction parameters of each table. + has_legs (bool or list of bool): whether each table has legs or not. If only a + single value is given, it will be broadcasted according to the total number of tables + xml (str): xml file to load arena + """ + + def __init__( + self, + table_offsets, + table_rots=0, + table_full_sizes=(0.8, 0.8, 0.05), + table_frictions=(1, 0.005, 0.0001), + has_legs=True, + xml="arenas/multi_table_arena.xml", + ): + # Set internal vars + self.table_offsets = np.array(table_offsets) + self.n_tables = self.table_offsets.shape[0] + self.table_rots = ( + np.array(table_rots) if isinstance(table_rots, Iterable) else np.ones(self.n_tables) * table_rots + ) + self.table_full_sizes = np.array(table_full_sizes) + if len(self.table_full_sizes.shape) == 1: + self.table_full_sizes = np.stack([self.table_full_sizes] * self.n_tables, axis=0) + self.table_half_sizes = self.table_full_sizes / 2 + self.table_frictions = np.array(table_frictions) + if len(self.table_frictions.shape) == 1: + self.table_frictions = np.stack([self.table_frictions] * self.n_tables, axis=0) + self.center_pos = np.array(self.table_offsets) + self.center_pos[:, 2] -= self.table_half_sizes[:, 2] + self.has_legs = has_legs if isinstance(has_legs, Iterable) else [has_legs] * self.n_tables + + # Run super init + super().__init__(xml_path_completion(xml)) + + # Configure any relevant locations + self.configure_location() + + def _add_table(self, name, offset, rot, half_size, friction, has_legs): + """ + Procedurally generates a table and adds it to the XML + """ + # Create body for this table, and add it to worldbody + table_body = new_body(name=name, pos=offset - np.array([0, 0, half_size[2]])) + self.worldbody.append(table_body) + + # Create core attributes for table geoms + table_attribs = { + "pos": (0, 0, 0), + "quat": T.convert_quat(T.axisangle2quat([0, 0, rot]), to="wxyz"), + "size": half_size, + "type": "box", + } + + # Create collision and visual bodies, and add them to the table body + col_geom = new_geom(name=f"{name}_collision", group=0, friction=friction, **table_attribs) + vis_geom = new_geom( + name=f"{name}_visual", group=1, conaffinity=0, contype=0, material="table_ceramic", **table_attribs + ) + table_body.append(col_geom) + table_body.append(vis_geom) + + # Add tabletop site to table + top_site = new_site(name=f"{name}_top", pos=(0, 0, half_size[2]), size=(0.001, 0.001, 0.001), rgba=(0, 0, 0, 0)) + table_body.append(top_site) + + # Add legs if requested + if has_legs: + delta_x = [0.1, -0.1, -0.1, 0.1] + delta_y = [0.1, 0.1, -0.1, -0.1] + for i, (dx, dy) in enumerate(zip(delta_x, delta_y)): + # If x-length of table is less than a certain length, place leg in the middle between ends + # Otherwise we place it near the edge + x = 0 + if half_size[0] > abs(dx * 2.0): + x += np.sign(dx) * half_size[0] - dx + # Repeat the same process for y + y = 0 + if half_size[1] > abs(dy * 2.0): + y += np.sign(dy) * half_size[1] - dy + # Rotate x and y values according to requested rotation + c, s = np.cos(rot), np.sin(rot) + rot_xy = np.array([[c, -s], [s, c]]) @ np.array([x, y]) + # Add in offsets + x = rot_xy[0] + y = rot_xy[1] + # Get z value + z = (offset[2] - half_size[2]) / 2.0 + # Create visual geom and add it to table body + leg_geom = new_geom( + name=f"{name}_leg{i}_visual", + pos=(x, y, -z), + type="cylinder", + size=(0.025, z), + group=1, + conaffinity=0, + contype=0, + material="table_legs_metal", + ) + table_body.append(leg_geom) + + def configure_location(self): + """Configures correct locations for this arena""" + # Set floor correctly + self.floor.set("pos", array_to_string(self.bottom_pos)) + + def _postprocess_arena(self): + """ + Runs any necessary post-processing on the imported Arena model + """ + # Create tables + for i, (offset, rot, half_size, friction, legs) in enumerate( + zip(self.table_offsets, self.table_rots, self.table_half_sizes, self.table_frictions, self.has_legs) + ): + self._add_table( + name=f"table{i}", + offset=offset, + rot=rot, + half_size=half_size, + friction=friction, + has_legs=legs, + ) diff --git a/third_party/robosuite/robosuite/models/arenas/pegs_arena.py b/third_party/robosuite/robosuite/models/arenas/pegs_arena.py new file mode 100644 index 0000000000000000000000000000000000000000..492b99d331038c2a791d111e43d797030ec1cac9 --- /dev/null +++ b/third_party/robosuite/robosuite/models/arenas/pegs_arena.py @@ -0,0 +1,30 @@ +from robosuite.models.arenas import TableArena + + +class PegsArena(TableArena): + """ + Workspace that contains a tabletop with two fixed pegs. + + Args: + table_full_size (3-tuple): (L,W,H) full dimensions of the table + table_friction (3-tuple): (sliding, torsional, rolling) friction parameters of the table + table_offset (3-tuple): (x,y,z) offset from center of arena when placing table. + Note that the z value sets the upper limit of the table + """ + + def __init__( + self, + table_full_size=(0.45, 0.69, 0.05), + table_friction=(1, 0.005, 0.0001), + table_offset=(0, 0, 0), + ): + super().__init__( + table_full_size=table_full_size, + table_friction=table_friction, + table_offset=table_offset, + xml="arenas/pegs_arena.xml", + ) + + # Get references to peg bodies + self.peg1_body = self.worldbody.find("./body[@name='peg1']") + self.peg2_body = self.worldbody.find("./body[@name='peg2']") diff --git a/third_party/robosuite/robosuite/models/arenas/table_arena.py b/third_party/robosuite/robosuite/models/arenas/table_arena.py new file mode 100644 index 0000000000000000000000000000000000000000..4a14c11c95d612ec6fd34eea62623d28a2460220 --- /dev/null +++ b/third_party/robosuite/robosuite/models/arenas/table_arena.py @@ -0,0 +1,97 @@ +import numpy as np + +from robosuite.models.arenas import Arena +from robosuite.utils.mjcf_utils import array_to_string, string_to_array, xml_path_completion + + +class TableArena(Arena): + """ + Workspace that contains an empty table. + + + Args: + table_full_size (3-tuple): (L,W,H) full dimensions of the table + table_friction (3-tuple): (sliding, torsional, rolling) friction parameters of the table + table_offset (3-tuple): (x,y,z) offset from center of arena when placing table. + Note that the z value sets the upper limit of the table + has_legs (bool): whether the table has legs or not + xml (str): xml file to load arena + """ + + def __init__( + self, + table_full_size=(0.8, 0.8, 0.05), + table_friction=(1, 0.005, 0.0001), + table_offset=(0, 0, 0.8), + has_legs=True, + xml="arenas/table_arena.xml", + ): + super().__init__(xml_path_completion(xml)) + + self.table_full_size = np.array(table_full_size) + self.table_half_size = self.table_full_size / 2 + self.table_friction = table_friction + self.table_offset = table_offset + self.center_pos = self.bottom_pos + np.array([0, 0, -self.table_half_size[2]]) + self.table_offset + + self.table_body = self.worldbody.find("./body[@name='table']") + self.table_collision = self.table_body.find("./geom[@name='table_collision']") + self.table_visual = self.table_body.find("./geom[@name='table_visual']") + self.table_top = self.table_body.find("./site[@name='table_top']") + + self.has_legs = has_legs + self.table_legs_visual = [ + self.table_body.find("./geom[@name='table_leg1_visual']"), + self.table_body.find("./geom[@name='table_leg2_visual']"), + self.table_body.find("./geom[@name='table_leg3_visual']"), + self.table_body.find("./geom[@name='table_leg4_visual']"), + ] + + self.configure_location() + + def configure_location(self): + """Configures correct locations for this arena""" + self.floor.set("pos", array_to_string(self.bottom_pos)) + + self.table_body.set("pos", array_to_string(self.center_pos)) + self.table_collision.set("size", array_to_string(self.table_half_size)) + self.table_collision.set("friction", array_to_string(self.table_friction)) + self.table_visual.set("size", array_to_string(self.table_half_size)) + + self.table_top.set("pos", array_to_string(np.array([0, 0, self.table_half_size[2]]))) + + # If we're not using legs, set their size to 0 + if not self.has_legs: + for leg in self.table_legs_visual: + leg.set("rgba", array_to_string([1, 0, 0, 0])) + leg.set("size", array_to_string([0.0001, 0.0001])) + else: + # Otherwise, set leg locations appropriately + delta_x = [0.1, -0.1, -0.1, 0.1] + delta_y = [0.1, 0.1, -0.1, -0.1] + for leg, dx, dy in zip(self.table_legs_visual, delta_x, delta_y): + # If x-length of table is less than a certain length, place leg in the middle between ends + # Otherwise we place it near the edge + x = 0 + if self.table_half_size[0] > abs(dx * 2.0): + x += np.sign(dx) * self.table_half_size[0] - dx + # Repeat the same process for y + y = 0 + if self.table_half_size[1] > abs(dy * 2.0): + y += np.sign(dy) * self.table_half_size[1] - dy + # Get z value + z = (self.table_offset[2] - self.table_half_size[2]) / 2.0 + # Set leg position + leg.set("pos", array_to_string([x, y, -z])) + # Set leg size + leg.set("size", array_to_string([0.025, z])) + + @property + def table_top_abs(self): + """ + Grabs the absolute position of table top + + Returns: + np.array: (x,y,z) table position + """ + return string_to_array(self.floor.get("pos")) + self.table_offset diff --git a/third_party/robosuite/robosuite/models/arenas/wipe_arena.py b/third_party/robosuite/robosuite/models/arenas/wipe_arena.py new file mode 100644 index 0000000000000000000000000000000000000000..c1db1cad4eb0501dda1db869eb86871dc74981a3 --- /dev/null +++ b/third_party/robosuite/robosuite/models/arenas/wipe_arena.py @@ -0,0 +1,186 @@ +import numpy as np + +from robosuite.models.arenas import TableArena +from robosuite.models.objects import CylinderObject +from robosuite.utils.mjcf_utils import CustomMaterial, find_elements + + +class WipeArena(TableArena): + """ + Workspace that contains an empty table with visual markers on its surface. + + Args: + table_full_size (3-tuple): (L,W,H) full dimensions of the table + table_friction (3-tuple): (sliding, torsional, rolling) friction parameters of the table + table_offset (3-tuple): (x,y,z) offset from center of arena when placing table. + Note that the z value sets the upper limit of the table + coverage_factor (float): Fraction of table that will be sampled for dirt placement + num_markers (int): Number of dirt (peg) particles to generate in a path on the table + table_friction_std (float): Standard deviation to sample for the peg friction + line_width (float): Diameter of dirt path trace + two_clusters (bool): If set, will generate two separate dirt paths with half the number of sensors in each + """ + + def __init__( + self, + table_full_size=(0.8, 0.8, 0.05), + table_friction=(0.01, 0.005, 0.0001), + table_offset=(0, 0, 0.8), + coverage_factor=0.9, + num_markers=10, + table_friction_std=0, + line_width=0.02, + two_clusters=False, + ): + # Tactile table-specific features + self.table_friction_std = table_friction_std + self.line_width = line_width + self.markers = [] + self.coverage_factor = coverage_factor + self.num_markers = num_markers + self.two_clusters = two_clusters + + # Attribute to hold current direction of sampled dirt path + self.direction = None + + # run superclass init + super().__init__( + table_full_size=table_full_size, + table_friction=table_friction, + table_offset=table_offset, + ) + + def configure_location(self): + """Configures correct locations for this arena""" + # Run superclass first + super().configure_location() + + # Define start position for drawing the line + pos = self.sample_start_pos() + + # Define dirt material for markers + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "1 1", + "specular": "0.0", + "shininess": "0.0", + } + dirt = CustomMaterial( + texture="Dirt", + tex_name="dirt", + mat_name="dirt_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + shared=True, + ) + + # Define line(s) drawn on table + for i in range(self.num_markers): + # If we're using two clusters, we resample the starting position and direction at the halfway point + if self.two_clusters and i == int(np.floor(self.num_markers / 2)): + pos = self.sample_start_pos() + marker_name = f"contact{i}" + marker = CylinderObject( + name=marker_name, + size=[self.line_width / 2, 0.001], + rgba=[1, 1, 1, 1], + material=dirt, + obj_type="visual", + joints=None, + ) + # Manually add this object to the arena xml + self.merge_assets(marker) + table = find_elements(root=self.worldbody, tags="body", attribs={"name": "table"}, return_first=True) + table.append(marker.get_obj()) + + # Add this marker to our saved list of all markers + self.markers.append(marker) + + # Add to the current dirt path + pos = self.sample_path_pos(pos) + + def reset_arena(self, sim): + """ + Reset the visual marker locations in the environment. Requires @sim (MjSim) reference to be passed in so that + the Mujoco sim can be directly modified + + Args: + sim (MjSim): Simulation instance containing this arena and visual markers + """ + # Sample new initial position and direction for generated marker paths + pos = self.sample_start_pos() + + # Loop through all visual markers + for i, marker in enumerate(self.markers): + # If we're using two clusters, we resample the starting position and direction at the halfway point + if self.two_clusters and i == int(np.floor(self.num_markers / 2)): + pos = self.sample_start_pos() + # Get IDs to the body, geom, and site of each marker + body_id = sim.model.body_name2id(marker.root_body) + geom_id = sim.model.geom_name2id(marker.visual_geoms[0]) + site_id = sim.model.site_name2id(marker.sites[0]) + # Determine new position for this marker + position = np.array([pos[0], pos[1], self.table_half_size[2]]) + # Set the current marker (body) to this new position + sim.model.body_pos[body_id] = position + # Reset the marker visualization -- setting geom rgba alpha value to 1 + sim.model.geom_rgba[geom_id][3] = 1 + # Hide the default visualization site + sim.model.site_rgba[site_id][3] = 0 + # Sample next values in local marker trajectory + pos = self.sample_path_pos(pos) + + def sample_start_pos(self): + """ + Helper function to return sampled start position of a new dirt (peg) location + + Returns: + np.array: the (x,y) value of the newly sampled dirt starting location + """ + # First define the random direction that we will start at + self.direction = np.random.uniform(-np.pi, np.pi) + + return np.array( + ( + np.random.uniform( + -self.table_half_size[0] * self.coverage_factor + self.line_width / 2, + self.table_half_size[0] * self.coverage_factor - self.line_width / 2, + ), + np.random.uniform( + -self.table_half_size[1] * self.coverage_factor + self.line_width / 2, + self.table_half_size[1] * self.coverage_factor - self.line_width / 2, + ), + ) + ) + + def sample_path_pos(self, pos): + """ + Helper function to add a sampled dirt (peg) position to a pre-existing dirt path, whose most + recent dirt position is defined by @pos + + Args: + pos (np.array): (x,y) value of most recent dirt position + + Returns: + np.array: the (x,y) value of the newly sampled dirt position to add to the current dirt path + """ + # Random chance to alter the current dirt direction + if np.random.uniform(0, 1) > 0.7: + self.direction += np.random.normal(0, 0.5) + + posnew0 = pos[0] + 0.005 * np.sin(self.direction) + posnew1 = pos[1] + 0.005 * np.cos(self.direction) + + # We keep resampling until we get a valid new position that's on the table + while ( + abs(posnew0) >= self.table_half_size[0] * self.coverage_factor - self.line_width / 2 + or abs(posnew1) >= self.table_half_size[1] * self.coverage_factor - self.line_width / 2 + ): + self.direction += np.random.normal(0, 0.5) + posnew0 = pos[0] + 0.005 * np.sin(self.direction) + posnew1 = pos[1] + 0.005 * np.cos(self.direction) + + # Return this newly sampled position + return np.array((posnew0, posnew1)) diff --git a/third_party/robosuite/robosuite/models/base.py b/third_party/robosuite/robosuite/models/base.py new file mode 100644 index 0000000000000000000000000000000000000000..52e6f98d47904d4c05c8e8c34fb297d8cf570398 --- /dev/null +++ b/third_party/robosuite/robosuite/models/base.py @@ -0,0 +1,696 @@ +import io +import os +import xml.dom.minidom +import xml.etree.ElementTree as ET + +import robosuite.macros as macros +from robosuite.utils import XMLError +from robosuite.utils.mjcf_utils import ( + _element_filter, + add_material, + add_prefix, + find_elements, + recolor_collision_geoms, + sort_elements, + string_to_array, +) + + +class MujocoXML(object): + """ + Base class of Mujoco xml file + Wraps around ElementTree and provides additional functionality for merging different models. + Specially, we keep track of , and + + When initialized, loads a mujoco xml from file. + + Args: + fname (str): path to the MJCF xml file. + """ + + def __init__(self, fname): + self.file = fname + self.folder = os.path.dirname(fname) + self.tree = ET.parse(fname) + self.root = self.tree.getroot() + self.worldbody = self.create_default_element("worldbody") + self.actuator = self.create_default_element("actuator") + self.sensor = self.create_default_element("sensor") + self.asset = self.create_default_element("asset") + self.tendon = self.create_default_element("tendon") + self.equality = self.create_default_element("equality") + self.contact = self.create_default_element("contact") + + # Parse any default classes and replace them inline + default = self.create_default_element("default") + default_classes = self._get_default_classes(default) + self._replace_defaults_inline(default_dic=default_classes) + + # Remove original default classes + self.root.remove(default) + + self.resolve_asset_dependency() + + def resolve_asset_dependency(self): + """ + Converts every file dependency into absolute path so when we merge we don't break things. + """ + + for node in self.asset.findall("./*[@file]"): + file = node.get("file") + abs_path = os.path.abspath(self.folder) + abs_path = os.path.join(abs_path, file) + node.set("file", abs_path) + + def create_default_element(self, name): + """ + Creates a <@name/> tag under root if there is none. + + Args: + name (str): Name to generate default element + + Returns: + ET.Element: Node that was created + """ + + found = self.root.find(name) + if found is not None: + return found + ele = ET.Element(name) + self.root.append(ele) + return ele + + def merge(self, others, merge_body="default"): + """ + Default merge method. + + Args: + others (MujocoXML or list of MujocoXML): other xmls to merge into this one + raises XML error if @others is not a MujocoXML instance. + merges , and of @others into @self + merge_body (None or str): If set, will merge child bodies of @others. Default is "default", which + corresponds to the root worldbody for this XML. Otherwise, should be an existing body name + that exists in this XML. None results in no merging of @other's bodies in its worldbody. + + Raises: + XMLError: [Invalid XML instance] + """ + if type(others) is not list: + others = [others] + for idx, other in enumerate(others): + if not isinstance(other, MujocoXML): + raise XMLError("{} is not a MujocoXML instance.".format(type(other))) + if merge_body is not None: + root = ( + self.worldbody + if merge_body == "default" + else find_elements( + root=self.worldbody, tags="body", attribs={"name": merge_body}, return_first=True + ) + ) + for body in other.worldbody: + root.append(body) + self.merge_assets(other) + for one_actuator in other.actuator: + self.actuator.append(one_actuator) + for one_sensor in other.sensor: + self.sensor.append(one_sensor) + for one_tendon in other.tendon: + self.tendon.append(one_tendon) + for one_equality in other.equality: + self.equality.append(one_equality) + for one_contact in other.contact: + self.contact.append(one_contact) + + def get_model(self, mode="mujoco"): + """ + Generates a MjModel instance from the current xml tree. + + Args: + mode (str): Mode with which to interpret xml tree + + Returns: + MjModel: generated model from xml + + Raises: + ValueError: [Invalid mode] + """ + + available_modes = ["mujoco"] + with io.StringIO() as string: + string.write(ET.tostring(self.root, encoding="unicode")) + if mode == "mujoco": + import mujoco + + model = mujoco.MjModel.from_xml_string(string.getvalue()) + return model + raise ValueError("Unkown model mode: {}. Available options are: {}".format(mode, ",".join(available_modes))) + + def get_xml(self): + """ + Reads a string of the MJCF XML file. + + Returns: + str: XML tree read in from file + """ + with io.StringIO() as string: + string.write(ET.tostring(self.root, encoding="unicode")) + return string.getvalue() + + def save_model(self, fname, pretty=False): + """ + Saves the xml to file. + + Args: + fname (str): output file location + pretty (bool): If True, (attempts!! to) pretty print the output + """ + with open(fname, "w") as f: + xml_str = ET.tostring(self.root, encoding="unicode") + if pretty: + parsed_xml = xml.dom.minidom.parseString(xml_str) + xml_str = parsed_xml.toprettyxml(newl="") + f.write(xml_str) + + def merge_assets(self, other): + """ + Merges @other's assets in a custom logic. + + Args: + other (MujocoXML or MujocoObject): other xml file whose assets will be merged into this one + """ + for asset in other.asset: + if ( + find_elements(root=self.asset, tags=asset.tag, attribs={"name": asset.get("name")}, return_first=True) + is None + ): + self.asset.append(asset) + + def get_element_names(self, root, element_type): + """ + Searches recursively through the @root and returns a list of names of the specified @element_type + + Args: + root (ET.Element): Root of the xml element tree to start recursively searching through + (e.g.: `self.worldbody`) + element_type (str): Name of element to return names of. (e.g.: "site", "geom", etc.) + + Returns: + list: names that correspond to the specified @element_type + """ + names = [] + for child in root: + if child.tag == element_type: + names.append(child.get("name")) + names += self.get_element_names(child, element_type) + return names + + @staticmethod + def _get_default_classes(default): + """ + Utility method to convert all default tags into a nested dictionary of values -- this will be used to replace + all elements' class tags inline with the appropriate defaults if not specified. + + Args: + default (ET.Element): Nested default tag XML root. + + Returns: + dict: Nested dictionary, where each default class name is mapped to its own dict mapping element tag names + (e.g.: geom, site, etc.) to the set of default attributes for that tag type + """ + # Create nested dict to return + default_dic = {} + # Parse the default tag accordingly + for cls in default: + default_dic[cls.get("class")] = {child.tag: child for child in cls} + return default_dic + + def _replace_defaults_inline(self, default_dic, root=None): + """ + Utility method to replace all default class attributes recursively in the XML tree starting from @root + with the corresponding defaults in @default_dic if they are not explicitly specified for ta given element. + + Args: + root (ET.Element): Root of the xml element tree to start recursively replacing defaults. Only is used by + recursive calls + default_dic (dict): Nested dictionary, where each default class name is mapped to its own dict mapping + element tag names (e.g.: geom, site, etc.) to the set of default attributes for that tag type + """ + # If root is None, this is the top level call -- replace root with self.root + if root is None: + root = self.root + # Check this current element if it contains any class elements + cls_name = root.attrib.pop("class", None) + if cls_name is not None: + # If the tag for this element is contained in our default dic, we add any defaults that are not + # explicitly specified in this + tag_attrs = default_dic[cls_name].get(root.tag, None) + if tag_attrs is not None: + for k, v in tag_attrs.items(): + if root.get(k, None) is None: + root.set(k, v) + # Loop through all child elements + for child in root: + self._replace_defaults_inline(default_dic=default_dic, root=child) + + @property + def name(self): + """ + Returns name of this MujocoXML + + Returns: + str: Name of this MujocoXML + """ + return self.root.get("model") + + +class MujocoModel(object): + """ + Base class for all simulation models used in mujoco. + + Standardizes core API for accessing models' relevant geoms, names, etc. + """ + + def correct_naming(self, names): + """ + Corrects all strings in @names by adding the naming prefix to it and returns the name-corrected values + + Args: + names (str, list, or dict): Name(s) to be corrected + + Raises: + TypeError: [Invalid input type] + """ + if type(names) is str: + return self.naming_prefix + names if not self.exclude_from_prefixing(names) else names + elif type(names) is list: + return [self.naming_prefix + name if not self.exclude_from_prefixing(name) else name for name in names] + elif type(names) is dict: + names = names.copy() + for key, val in names.items(): + names[key] = self.correct_naming(val) + return names + else: + # Assumed to be type error + raise TypeError("Error: type of 'names' must be str, list, or dict!") + + def set_sites_visibility(self, sim, visible): + """ + Set all site visual states for this model. + + Args: + sim (MjSim): Current active mujoco simulation instance + visible (bool): If True, will visualize model sites. Else, will hide the sites. + """ + # Loop through all visualization geoms and set their alpha values appropriately + for vis_g in self.sites: + vis_g_id = sim.model.site_name2id(vis_g) + if (visible and sim.model.site_rgba[vis_g_id][3] < 0) or ( + not visible and sim.model.site_rgba[vis_g_id][3] > 0 + ): + # We toggle the alpha value + sim.model.site_rgba[vis_g_id][3] = -sim.model.site_rgba[vis_g_id][3] + + def exclude_from_prefixing(self, inp): + """ + A function that should take in an arbitrary input and return either True or False, determining whether the + corresponding name to @inp should have naming_prefix added to it. Must be defined by subclass. + + Args: + inp (any): Arbitrary input, depending on subclass. Can be str, ET.Element, etc. + + Returns: + bool: True if we should exclude the associated name(s) with @inp from being prefixed with naming_prefix + """ + raise NotImplementedError + + @property + def name(self): + """ + Name for this model. Should be unique. + + Returns: + str: Unique name for this model. + """ + raise NotImplementedError + + @property + def naming_prefix(self): + """ + Generates a standardized prefix to prevent naming collisions + + Returns: + str: Prefix unique to this model. + """ + raise NotImplementedError + + @property + def root_body(self): + """ + Root body name for this model. This should correspond to the top-level body element in the equivalent mujoco xml + tree for this object. + """ + raise NotImplementedError + + @property + def bodies(self): + """ + Returns: + list: Body names for this model + """ + raise NotImplementedError + + @property + def joints(self): + """ + Returns: + list: Joint names for this model + """ + raise NotImplementedError + + @property + def actuators(self): + """ + Returns: + list: Actuator names for this model + """ + raise NotImplementedError + + @property + def sites(self): + """ + Returns: + list: Site names for this model + """ + raise NotImplementedError + + @property + def sensors(self): + """ + Returns: + list: Sensor names for this model + """ + raise NotImplementedError + + @property + def contact_geoms(self): + """ + List of names corresponding to the geoms used to determine contact with this model. + + Returns: + list: relevant contact geoms for this model + """ + raise NotImplementedError + + @property + def visual_geoms(self): + """ + List of names corresponding to the geoms used for visual rendering of this model. + + Returns: + list: relevant visual geoms for this model + """ + raise NotImplementedError + + @property + def important_geoms(self): + """ + Geoms corresponding to important components of this model. String keywords should be mapped to lists of geoms. + + Returns: + dict of list: Important set of geoms, where each set of geoms are grouped as a list and are + organized by keyword string entries into a dict + """ + raise NotImplementedError + + @property + def important_sites(self): + """ + Dict of sites corresponding to the important site geoms (e.g.: used to aid visualization during sim). + + Returns: + dict: Important site geoms, where each specific geom name is mapped from keyword string entries + in the dict + """ + raise NotImplementedError + + @property + def important_sensors(self): + """ + Dict of important sensors enabled for this model. + + Returns: + dict: Important sensors for this model, where each specific sensor name is mapped from keyword string + entries in the dict + """ + raise NotImplementedError + + @property + def bottom_offset(self): + """ + Returns vector from model root body to model bottom. + Useful for, e.g. placing models on a surface. + Must be defined by subclass. + + Returns: + np.array: (dx, dy, dz) offset vector + """ + raise NotImplementedError + + @property + def top_offset(self): + """ + Returns vector from model root body to model top. + Useful for, e.g. placing models on a surface. + Must be defined by subclass. + + Returns: + np.array: (dx, dy, dz) offset vector + """ + raise NotImplementedError + + @property + def horizontal_radius(self): + """ + Returns maximum distance from model root body to any radial point of the model. + + Helps us put models programmatically without them flying away due to a huge initial contact force. + Must be defined by subclass. + + Returns: + float: radius + """ + raise NotImplementedError + + +class MujocoXMLModel(MujocoXML, MujocoModel): + """ + Base class for all MujocoModels that are based on a raw XML file. + + Args: + fname (str): Path to relevant xml file from which to create this robot instance + idn (int or str): Number or some other unique identification string for this model instance + """ + + def __init__(self, fname, idn=0): + super().__init__(fname) + + # Set id and add prefixes to all body names to prevent naming clashes + self.idn = idn + + # Define other variables that get filled later + self.mount = None + + # Define filter method to automatically add a default name to visual / collision geoms if encountered + group_mapping = { + None: "col", + "0": "col", + "1": "vis", + } + ctr_mapping = { + "col": 0, + "vis": 0, + } + + def _add_default_name_filter(element, parent): + # Run default filter + filter_key = _element_filter(element=element, parent=parent) + # Also additionally modify element if it is (a) a geom and (b) has no name + if element.tag == "geom" and element.get("name") is None: + group = group_mapping[element.get("group")] + element.set("name", f"g{ctr_mapping[group]}_{group}") + ctr_mapping[group] += 1 + # Return default filter key + return filter_key + + # Parse element tree to get all relevant bodies, joints, actuators, and geom groups + self._elements = sort_elements(root=self.root, element_filter=_add_default_name_filter) + assert ( + len(self._elements["root_body"]) == 1 + ), "Invalid number of root bodies found for robot model. Expected 1," "got {}".format( + len(self._elements["root_body"]) + ) + self._elements["root_body"] = self._elements["root_body"][0] + self._elements["bodies"] = ( + [self._elements["root_body"]] + self._elements["bodies"] + if "bodies" in self._elements + else [self._elements["root_body"]] + ) + self._root_body = self._elements["root_body"].get("name") + self._bodies = [e.get("name") for e in self._elements.get("bodies", [])] + self._joints = [e.get("name") for e in self._elements.get("joints", [])] + self._actuators = [e.get("name") for e in self._elements.get("actuators", [])] + self._sites = [e.get("name") for e in self._elements.get("sites", [])] + self._sensors = [e.get("name") for e in self._elements.get("sensors", [])] + self._contact_geoms = [e.get("name") for e in self._elements.get("contact_geoms", [])] + self._visual_geoms = [e.get("name") for e in self._elements.get("visual_geoms", [])] + self._base_offset = string_to_array(self._elements["root_body"].get("pos", "0 0 0")) + + # Update all xml element prefixes + add_prefix(root=self.root, prefix=self.naming_prefix, exclude=self.exclude_from_prefixing) + + # Recolor all collision geoms appropriately + recolor_collision_geoms(root=self.worldbody, rgba=self.contact_geom_rgba) + + # Add default materials + if macros.USING_INSTANCE_RANDOMIZATION: + tex_element, mat_element, _, used = add_material(root=self.worldbody, naming_prefix=self.naming_prefix) + # Only add if material / texture was actually used + if used: + self.asset.append(tex_element) + self.asset.append(mat_element) + + def exclude_from_prefixing(self, inp): + """ + By default, don't exclude any from being prefixed + """ + return False + + @property + def base_offset(self): + """ + Provides position offset of root body. + + Returns: + 3-array: (x,y,z) pos value of root_body body element. If no pos in element, returns all zeros. + """ + return self._base_offset + + @property + def name(self): + return "{}{}".format(type(self).__name__, self.idn) + + @property + def naming_prefix(self): + return "{}_".format(self.idn) + + @property + def root_body(self): + return self.correct_naming(self._root_body) + + @property + def bodies(self): + return self.correct_naming(self._bodies) + + @property + def joints(self): + return self.correct_naming(self._joints) + + @property + def actuators(self): + return self.correct_naming(self._actuators) + + @property + def sites(self): + return self.correct_naming(self._sites) + + @property + def sensors(self): + return self.correct_naming(self._sensors) + + @property + def contact_geoms(self): + return self.correct_naming(self._contact_geoms) + + @property + def visual_geoms(self): + return self.correct_naming(self._visual_geoms) + + @property + def important_sites(self): + return self.correct_naming(self._important_sites) + + @property + def important_geoms(self): + return self.correct_naming(self._important_geoms) + + @property + def important_sensors(self): + return self.correct_naming(self._important_sensors) + + @property + def _important_sites(self): + """ + Dict of sites corresponding to the important site geoms (e.g.: used to aid visualization during sim). + + Returns: + dict: Important site geoms, where each specific geom name is mapped from keyword string entries + in the dict. Note that the mapped sites should be the RAW site names found directly in the XML file -- + the naming prefix will be automatically added in the public method call + """ + raise NotImplementedError + + @property + def _important_geoms(self): + """ + Geoms corresponding to important components of this model. String keywords should be mapped to lists of geoms. + + Returns: + dict of list: Important set of geoms, where each set of geoms are grouped as a list and are + organized by keyword string entries into a dict. Note that the mapped geoms should be the RAW geom + names found directly in the XML file -- the naming prefix will be automatically added in the + public method call + """ + raise NotImplementedError + + @property + def _important_sensors(self): + """ + Dict of important sensors enabled for this model. + + Returns: + dict: Important sensors for this model, where each specific sensor name is mapped from keyword string + entries in the dict. Note that the mapped geoms should be the RAW sensor names found directly in the + XML file -- the naming prefix will be automatically added in the public method call + """ + raise NotImplementedError + + @property + def contact_geom_rgba(self): + """ + RGBA color to assign to all contact geoms for this model + + Returns: + 4-array: (r,g,b,a) values from 0 to 1 for this model's set of contact geoms + """ + raise NotImplementedError + + @property + def bottom_offset(self): + """ + Returns vector from model root body to model bottom. + Useful for, e.g. placing models on a surface. + By default, this corresponds to the root_body's base offset. + + Returns: + np.array: (dx, dy, dz) offset vector + """ + return self.base_offset + + @property + def top_offset(self): + raise NotImplementedError + + @property + def horizontal_radius(self): + raise NotImplementedError diff --git a/third_party/robosuite/robosuite/models/bases/__init__.py b/third_party/robosuite/robosuite/models/bases/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4fe39ea50f0a11ad38ddc8f5f2b2ec800125c885 --- /dev/null +++ b/third_party/robosuite/robosuite/models/bases/__init__.py @@ -0,0 +1,35 @@ +from .mount_model import MountModel +from .robot_base_model import RobotBaseModel +from .robot_base_factory import robot_base_factory +from .mobile_base_model import MobileBaseModel +from .leg_base_model import LegBaseModel + +from .rethink_mount import RethinkMount +from .rethink_minimal_mount import RethinkMinimalMount +from .null_mount import NullMount + +from .omron_mobile_base import OmronMobileBase +from .null_mobile_base import NullMobileBase +from .no_actuation_base import NoActuationBase +from .floating_legged_base import FloatingLeggedBase + +from .spot_base import Spot, SpotFloating + +BASE_MAPPING = { + "RethinkMount": RethinkMount, + "RethinkMinimalMount": RethinkMinimalMount, + "NullMount": NullMount, + "OmronMobileBase": OmronMobileBase, + "NullMobileBase": NullMobileBase, + "NoActuationBase": NoActuationBase, + "FloatingLeggedBase": FloatingLeggedBase, + "Spot": Spot, + "SpotFloating": SpotFloating, +} + +ALL_BASES = BASE_MAPPING.keys() + + +def register_base(target_class): + BASE_MAPPING[target_class.__name__] = target_class + return target_class diff --git a/third_party/robosuite/robosuite/models/bases/floating_legged_base.py b/third_party/robosuite/robosuite/models/bases/floating_legged_base.py new file mode 100644 index 0000000000000000000000000000000000000000..2a41ed9beaa12455d01a5d969af6198cfe40b9bf --- /dev/null +++ b/third_party/robosuite/robosuite/models/bases/floating_legged_base.py @@ -0,0 +1,27 @@ +""" +Rethink's Generic Mount (Officially used on Sawyer). +""" +import numpy as np + +from robosuite.models.bases.mobile_base_model import MobileBaseModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class FloatingLeggedBase(MobileBaseModel): + """ + Dummy mobile base to signify no mount. + + Args: + idn (int or str): Number or some other unique identification string for this mount instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("bases/floating_legged_base.xml"), idn=idn) + + @property + def top_offset(self): + return np.array((0, 0, 0)) + + @property + def horizontal_radius(self): + return 0 diff --git a/third_party/robosuite/robosuite/models/bases/leg_base_model.py b/third_party/robosuite/robosuite/models/bases/leg_base_model.py new file mode 100644 index 0000000000000000000000000000000000000000..d272e4c0ef49a0afd6b696a5a3ec2f643d96b3e5 --- /dev/null +++ b/third_party/robosuite/robosuite/models/bases/leg_base_model.py @@ -0,0 +1,145 @@ +""" +Defines the base class of all mobile bases +""" +from xml.etree import ElementTree as ET + +import numpy as np + +from robosuite.models.bases.robot_base_model import RobotBaseModel +from robosuite.utils.mjcf_utils import find_elements, find_parent + + +class LegBaseModel(RobotBaseModel): + @property + def init_qpos(self): + raise NotImplementedError + + # -------------------------------------------------------------------------------------- # + # Properties: In general, these are the name-adjusted versions from the private # + # subclass implementations pulled from their respective raw xml files # + # -------------------------------------------------------------------------------------- # + + @property + def naming_prefix(self): + return "leg{}_".format(self.idn) + + def _remove_joint_actuation(self, part_name): + for joint in self.worldbody.findall(".//joint"): + if part_name in joint.get("name"): + parent_body = find_parent(self.worldbody, joint) + parent_body.remove(joint) + self._joints.remove(joint.get("name").replace(self.naming_prefix, "")) + for motor in self.actuator.findall(".//motor"): + if part_name in motor.get("name"): + parent_body = find_parent(self.actuator, motor) + parent_body.remove(motor) + self._actuators.remove(motor.get("name").replace(self.naming_prefix, "")) + + def _remove_free_joint(self): + """Remove all freejoints from the model.""" + for freejoint in self.worldbody.findall(".//freejoint"): + find_parent(self.worldbody, freejoint).remove(freejoint) + + def _add_mobile_joint(self): + """This is a special processing of leg base, which converts leg bases into floating ones without users to manually modify the xml file.""" + + # Define the dictionary representing the attributes of the tag + forward_joint_attributes = { + "name": self.naming_prefix + "joint_mobile_forward", + "pos": "0 0 0", + "axis": "0 1 0", + "type": "slide", + "limited": "false", + "damping": "0", + "armature": "0.0", + "frictionloss": "250", + } + + side_joint_attributes = { + "name": self.naming_prefix + "joint_mobile_side", + "pos": "0 0 0", + "axis": "1 0 0", + "type": "slide", + "limited": "false", + "damping": "0", + "armature": "0.0", + "frictionloss": "250", + } + + yaw_joint_attributes = { + "name": self.naming_prefix + "joint_mobile_yaw", + "pos": "0 0 0", + "axis": "0 0 1", + "type": "hinge", + "limited": "false", + "damping": "0", + "armature": "0.0", + "frictionloss": "250", + } + + # Create the root element + forward_joint = ET.Element("joint") + side_joint = ET.Element("joint") + yaw_joint = ET.Element("joint") + + # Set the attributes of the root element from the dictionary + for key, value in forward_joint_attributes.items(): + forward_joint.set(key, value) + for key, value in side_joint_attributes.items(): + side_joint.set(key, value) + for key, value in yaw_joint_attributes.items(): + yaw_joint.set(key, value) + + forward_actuation_attributes = { + "ctrllimited": "true", + "ctrlrange": "-1.00 1.00", + "joint": self.naming_prefix + "joint_mobile_forward", + "kv": "1000", + "name": self.naming_prefix + "actuator_mobile_forward", + "forcelimited": "true", + "forcerange": "-600 600", + } + side_actuation_attributes = { + "ctrllimited": "true", + "ctrlrange": "-1.00 1.00", + "joint": self.naming_prefix + "joint_mobile_side", + "kv": "1000", + "name": self.naming_prefix + "actuator_mobile_side", + "forcelimited": "true", + "forcerange": "-600 600", + } + yaw_actuation_attributes = { + "ctrllimited": "true", + "ctrlrange": "-1.50 1.50", + "joint": self.naming_prefix + "joint_mobile_yaw", + "kv": "1500", + "name": self.naming_prefix + "actuator_mobile_yaw", + "forcelimited": "true", + "forcerange": "-600 600", + } + + forward_actuation = ET.Element("velocity") + side_actuation = ET.Element("velocity") + yaw_actuation = ET.Element("velocity") + + for key, value in forward_actuation_attributes.items(): + forward_actuation.set(key, str(value)) + for key, value in side_actuation_attributes.items(): + side_actuation.set(key, str(value)) + for key, value in yaw_actuation_attributes.items(): + yaw_actuation.set(key, str(value)) + + root = find_elements(self.worldbody, tags="body", return_first=True) + + for joint in [forward_joint, side_joint, yaw_joint]: + root.append(joint) + self._joints.append(joint.get("name").replace(self.naming_prefix, "")) + + actuators = find_elements(self.actuator, tags="actuator", return_first=True) + for actuator in [forward_actuation, side_actuation, yaw_actuation]: + actuators.append(actuator) + self._actuators.append(actuator.get("name").replace(self.naming_prefix, "")) + + @property + def default_base(self): + return "NullMobileBase" diff --git a/third_party/robosuite/robosuite/models/bases/mobile_base_model.py b/third_party/robosuite/robosuite/models/bases/mobile_base_model.py new file mode 100644 index 0000000000000000000000000000000000000000..00af4a0398d026fccadf48c7f27026458c0d8ad7 --- /dev/null +++ b/third_party/robosuite/robosuite/models/bases/mobile_base_model.py @@ -0,0 +1,11 @@ +""" +Defines the mobile base model +""" + +from robosuite.models.bases.robot_base_model import RobotBaseModel + + +class MobileBaseModel(RobotBaseModel): + @property + def naming_prefix(self): + return "mobilebase{}_".format(self.idn) diff --git a/third_party/robosuite/robosuite/models/bases/mount_model.py b/third_party/robosuite/robosuite/models/bases/mount_model.py new file mode 100644 index 0000000000000000000000000000000000000000..4abe60bc3f3f0305d448dad5bfccdb4c1814ab7f --- /dev/null +++ b/third_party/robosuite/robosuite/models/bases/mount_model.py @@ -0,0 +1,11 @@ +""" +Defines the MountModel class (Fixed Base that is mounted to the robot) +""" + +from robosuite.models.bases.robot_base_model import RobotBaseModel + + +class MountModel(RobotBaseModel): + @property + def naming_prefix(self) -> str: + return "fixed_mount{}_".format(self.idn) diff --git a/third_party/robosuite/robosuite/models/bases/no_actuation_base.py b/third_party/robosuite/robosuite/models/bases/no_actuation_base.py new file mode 100644 index 0000000000000000000000000000000000000000..5c77f3ab1944be35a364505ce85200e110d21510 --- /dev/null +++ b/third_party/robosuite/robosuite/models/bases/no_actuation_base.py @@ -0,0 +1,27 @@ +""" +Rethink's Generic Mount (Officially used on Sawyer). +""" +import numpy as np + +from robosuite.models.bases.mobile_base_model import MobileBaseModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class NoActuationBase(MobileBaseModel): + """ + Dummy mobile base to signify no mount. + + Args: + idn (int or str): Number or some other unique identification string for this mount instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("bases/no_actuation_base.xml"), idn=idn) + + @property + def top_offset(self): + return np.array((0, 0, 0)) + + @property + def horizontal_radius(self): + return 0 diff --git a/third_party/robosuite/robosuite/models/bases/null_mobile_base.py b/third_party/robosuite/robosuite/models/bases/null_mobile_base.py new file mode 100644 index 0000000000000000000000000000000000000000..a3e8e6d5a7ae96c35869b2fcb7e479dac18d7255 --- /dev/null +++ b/third_party/robosuite/robosuite/models/bases/null_mobile_base.py @@ -0,0 +1,27 @@ +""" +Rethink's Generic Mount (Officially used on Sawyer). +""" +import numpy as np + +from robosuite.models.bases.mobile_base_model import MobileBaseModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class NullMobileBase(MobileBaseModel): + """ + Dummy mobile base to signify no mount. + + Args: + idn (int or str): Number or some other unique identification string for this mount instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("bases/null_mobile_base.xml"), idn=idn) + + @property + def top_offset(self): + return np.array((0, 0, 0)) + + @property + def horizontal_radius(self): + return 0 diff --git a/third_party/robosuite/robosuite/models/bases/null_mount.py b/third_party/robosuite/robosuite/models/bases/null_mount.py new file mode 100644 index 0000000000000000000000000000000000000000..a7896be35e532380f7f95af3fe476a1edfd6f7b5 --- /dev/null +++ b/third_party/robosuite/robosuite/models/bases/null_mount.py @@ -0,0 +1,27 @@ +""" +Rethink's Generic Mount (Officially used on Sawyer). +""" +import numpy as np + +from robosuite.models.bases.mount_model import MountModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class NullMount(MountModel): + """ + Dummy Mount to signify no mount. + + Args: + idn (int or str): Number or some other unique identification string for this mount instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("bases/null_mount.xml"), idn=idn) + + @property + def top_offset(self): + return np.array((0, 0, 0)) + + @property + def horizontal_radius(self): + return 0 diff --git a/third_party/robosuite/robosuite/models/bases/omron_mobile_base.py b/third_party/robosuite/robosuite/models/bases/omron_mobile_base.py new file mode 100644 index 0000000000000000000000000000000000000000..12f40bb96a0cd74777bf36ddeb7be49703bab523 --- /dev/null +++ b/third_party/robosuite/robosuite/models/bases/omron_mobile_base.py @@ -0,0 +1,28 @@ +""" +Omron LD-60 Mobile Base. +""" +import numpy as np + +from robosuite.models.bases.mobile_base_model import MobileBaseModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class OmronMobileBase(MobileBaseModel): + """ + Omron LD-60 Mobile Base. + + Args: + idn (int or str): Number or some other unique identification string for this mount instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("bases/omron_mobile_base.xml"), idn=idn) + + @property + def top_offset(self): + return np.array((0, 0, 0)) + + @property + def horizontal_radius(self): + # TODO: This may be inaccurate; just a placeholder for now + return 0.25 diff --git a/third_party/robosuite/robosuite/models/bases/rethink_minimal_mount.py b/third_party/robosuite/robosuite/models/bases/rethink_minimal_mount.py new file mode 100644 index 0000000000000000000000000000000000000000..a0263bd200ac9962b2e042f2c4eb04ce14dd9e52 --- /dev/null +++ b/third_party/robosuite/robosuite/models/bases/rethink_minimal_mount.py @@ -0,0 +1,28 @@ +""" +Rethink's Alternative Mount (Officially used on Baxter). +""" +import numpy as np + +from robosuite.models.bases.mount_model import MountModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class RethinkMinimalMount(MountModel): + """ + Mount officially used for Rethink's Baxter Robot. Includes only a wheeled pedestal. + + Args: + idn (int or str): Number or some other unique identification string for this mount instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("bases/rethink_minimal_mount.xml"), idn=idn) + + @property + def top_offset(self): + return np.array((0, 0, -0.062)) + + @property + def horizontal_radius(self): + # TODO: This may be inaccurate; just a placeholder for now + return 0.25 diff --git a/third_party/robosuite/robosuite/models/bases/rethink_mount.py b/third_party/robosuite/robosuite/models/bases/rethink_mount.py new file mode 100644 index 0000000000000000000000000000000000000000..3277ba2128f6f43bb73bc7f06214f7665f486b86 --- /dev/null +++ b/third_party/robosuite/robosuite/models/bases/rethink_mount.py @@ -0,0 +1,28 @@ +""" +Rethink's Generic Mount (Officially used on Sawyer). +""" +import numpy as np + +from robosuite.models.bases.mount_model import MountModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class RethinkMount(MountModel): + """ + Mount officially used for Rethink's Sawyer Robot. Includes a controller box and wheeled pedestal. + + Args: + idn (int or str): Number or some other unique identification string for this mount instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("bases/rethink_mount.xml"), idn=idn) + + @property + def top_offset(self): + return np.array((0, 0, -0.01)) + + @property + def horizontal_radius(self): + # TODO: This may be inaccurate; just a placeholder for now + return 0.25 diff --git a/third_party/robosuite/robosuite/models/bases/robot_base_factory.py b/third_party/robosuite/robosuite/models/bases/robot_base_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..542b3282fe2ae009d31af701bdb48159f4326175 --- /dev/null +++ b/third_party/robosuite/robosuite/models/bases/robot_base_factory.py @@ -0,0 +1,29 @@ +""" +Defines a string based method of initializing mounts +""" + +from typing import Optional + +from robosuite.models.bases.robot_base_model import RobotBaseModel + + +def robot_base_factory(name: Optional[str], idn=0) -> RobotBaseModel: + """ + Generator for grippers + + Creates a RobotBaseModel instance with the provided name. + + Args: + name (None or str): the name of the mount class + idn (int or str): Number or some other unique identification string for this mount instance + + Returns: + RobotBaseModel class: e.g. MobileBaseModel, LegBaseModel, or MountModel instance + + Raises: + XMLError: [invalid XML] + """ + # Import MOUNT_MAPPING at runtime so we avoid circular imports + from robosuite.models.bases import BASE_MAPPING + + return BASE_MAPPING.get(name, "Unknown base name: {}".format(name))(idn=idn) diff --git a/third_party/robosuite/robosuite/models/bases/robot_base_model.py b/third_party/robosuite/robosuite/models/bases/robot_base_model.py new file mode 100644 index 0000000000000000000000000000000000000000..f1353f103c772b18e4b0ba9d6c243baa22aa6491 --- /dev/null +++ b/third_party/robosuite/robosuite/models/bases/robot_base_model.py @@ -0,0 +1,94 @@ +""" +Defines the base class of all mounts +""" +from typing import Dict, List + +import numpy as np + +from robosuite.models.base import MujocoXMLModel +from robosuite.utils.mjcf_utils import MOUNT_COLLISION_COLOR + + +class RobotBaseModel(MujocoXMLModel): + """ + Base class for mounts that will be attached to robots. Note that this model's root body will be directly + appended to the robot's root body, so all offsets should be taken relative to that. + + Args: + fname (str): Path to relevant xml file to create this mount instance + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, fname: str, idn=0): + super().__init__(fname, idn=idn) + + # Grab mount offset (string -> np.array -> elements [1, 2, 3, 0] (x, y, z, w)) + self.rotation_offset = np.fromstring( + self.worldbody[0].attrib.get("quat", "1 0 0 0"), dtype=np.float64, sep=" " + )[[1, 2, 3, 0]] + + # -------------------------------------------------------------------------------------- # + # Properties: In general, these are the name-adjusted versions from the private # + # subclass implementations pulled from their respective raw xml files # + # -------------------------------------------------------------------------------------- # + + @property + def naming_prefix(self) -> str: + raise NotImplementedError + + @property + def _important_sites(self) -> Dict[str, str]: + """ + Returns: + dict: (Default is no important sites; i.e.: empty dict) + """ + return {} + + @property + def _important_geoms(self) -> Dict[str, List[str]]: + """ + Returns: + dict: (Default is no important geoms; i.e.: empty dict) + """ + return {} + + @property + def _important_sensors(self) -> Dict[str, str]: + """ + Returns: + dict: (Default is no sensors; i.e.: empty dict) + """ + return {} + + @property + def contact_geom_rgba(self) -> np.array: + return MOUNT_COLLISION_COLOR + + # -------------------------------------------------------------------------------------- # + # All subclasses must implement the following properties # + # -------------------------------------------------------------------------------------- # + + @property + def top_offset(self) -> np.array: + """ + Returns vector from model root body to model top. + This should correspond to the distance from the root body to the actual mounting surface + location of this mount. + + Returns: + np.array: (dx, dy, dz) offset vector + """ + raise NotImplementedError + + @property + def horizontal_radius(self) -> float: + """ + Returns maximum distance from model root body to any radial point of the model. + + Helps us put models programmatically without them flying away due to a huge initial contact force. + Must be defined by subclass. + + Returns: + float: radius + """ + raise NotImplementedError diff --git a/third_party/robosuite/robosuite/models/bases/spot_base.py b/third_party/robosuite/robosuite/models/bases/spot_base.py new file mode 100644 index 0000000000000000000000000000000000000000..bcdd54945733846670700a325606599efa2bc162 --- /dev/null +++ b/third_party/robosuite/robosuite/models/bases/spot_base.py @@ -0,0 +1,57 @@ +import numpy as np + +from robosuite.models.bases.leg_base_model import LegBaseModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class Spot(LegBaseModel): + """ + Rethink's Generic Mount (Officially used on Baxter). + + Args: + idn (int or str): Number or some other unique identification string for this mount instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("robots/spot/robot.xml"), idn=idn) + + @property + def top_offset(self): + return np.array((0, 0, 0)) + + @property + def horizontal_radius(self): + return 0.1 + + @property + def init_qpos(self): + return np.array([0.0, 0.9, -1.8] * 4) + + +class SpotFloating(LegBaseModel): + """ + Rethink's Generic Mount (Officially used on Baxter). + + Args: + idn (int or str): Number or some other unique identification string for this mount instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("robots/spot/robot.xml"), idn=idn) + + self._remove_joint_actuation("leg") + self._remove_free_joint() + + self._add_mobile_joint() + + @property + def top_offset(self): + return np.array((0, 0, 0)) + + @property + def horizontal_radius(self): + return 0.1 + + @property + def init_qpos(self): + return np.array([]) diff --git a/third_party/robosuite/robosuite/models/grippers/__init__.py b/third_party/robosuite/robosuite/models/grippers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..56089af8f76be68323cc3886e473898fce9856da --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/__init__.py @@ -0,0 +1,41 @@ +from .gripper_model import GripperModel +from .gripper_factory import gripper_factory +from .gripper_tester import GripperTester + +from .panda_gripper import PandaGripper +from .rethink_gripper import RethinkGripper +from .robotiq_85_gripper import Robotiq85Gripper +from .robotiq_three_finger_gripper import RobotiqThreeFingerGripper, RobotiqThreeFingerDexterousGripper +from .panda_gripper import PandaGripper +from .jaco_three_finger_gripper import JacoThreeFingerGripper, JacoThreeFingerDexterousGripper +from .robotiq_140_gripper import Robotiq140Gripper +from .wiping_gripper import WipingGripper +from .bd_gripper import BDGripper +from .null_gripper import NullGripper +from .inspire_hands import InspireLeftHand, InspireRightHand +from .fourier_hands import FourierLeftHand, FourierRightHand + +GRIPPER_MAPPING = { + "RethinkGripper": RethinkGripper, + "PandaGripper": PandaGripper, + "JacoThreeFingerGripper": JacoThreeFingerGripper, + "JacoThreeFingerDexterousGripper": JacoThreeFingerDexterousGripper, + "WipingGripper": WipingGripper, + "Robotiq85Gripper": Robotiq85Gripper, + "Robotiq140Gripper": Robotiq140Gripper, + "RobotiqThreeFingerGripper": RobotiqThreeFingerGripper, + "RobotiqThreeFingerDexterousGripper": RobotiqThreeFingerDexterousGripper, + "BDGripper": BDGripper, + "InspireLeftHand": InspireLeftHand, + "InspireRightHand": InspireRightHand, + "FourierLeftHand": FourierLeftHand, + "FourierRightHand": FourierRightHand, + None: NullGripper, +} + +ALL_GRIPPERS = GRIPPER_MAPPING.keys() + + +def register_gripper(target_class): + GRIPPER_MAPPING[target_class.__name__] = target_class + return target_class diff --git a/third_party/robosuite/robosuite/models/grippers/bd_gripper.py b/third_party/robosuite/robosuite/models/grippers/bd_gripper.py new file mode 100644 index 0000000000000000000000000000000000000000..ce137f9a849e295c6855727b845f173822dc825f --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/bd_gripper.py @@ -0,0 +1,36 @@ +import numpy as np + +from robosuite.models.grippers.gripper_model import GripperModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class BDGripper(GripperModel): + """ + Gripper for the Spot Arm. + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("grippers/bd_gripper.xml"), idn=idn) + + def format_action(self, action): + assert len(action) == self.dof + self.current_action = np.clip(self.current_action + np.array([1.0]) * self.speed * np.sign(action), -1.0, 1.0) + return self.current_action + + @property + def init_qpos(self): + return np.array([-1.57]) + + @property + def speed(self): + return 0.2 + + @property + def _important_geoms(self): + return { + "arm_link_fngr": ["arm_link_fngr_0", "arm_link_fngr_1", "left_finger_coll", "right_finger_coll"], + "left_fingerpad": ["left_finger_coll"], + "right_fingerpad": ["right_finger_coll"], + } diff --git a/third_party/robosuite/robosuite/models/grippers/fourier_hands.py b/third_party/robosuite/robosuite/models/grippers/fourier_hands.py new file mode 100644 index 0000000000000000000000000000000000000000..6a2a368d0fe9781b403fc193b4147d9e92aaa570 --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/fourier_hands.py @@ -0,0 +1,143 @@ +""" +Dexterous hands for GR1 robot. +""" +import numpy as np + +from robosuite.models.grippers.gripper_model import GripperModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class FourierLeftHand(GripperModel): + """ + Dexterous left hand of GR1 robot + + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("grippers/fourier_left_hand.xml"), idn=idn) + + def format_action(self, action): + # the more correct way is to add tag in the xml + # however the tag makes finger movement laggy, so manually copy the value for finger joints + # 0 is thumb rot, no copying. Thumb bend has 3 joints, so copy 3 times. Other fingers has 2 joints, so copy 2 times. + assert len(action) == self.dof + action = np.array(action) + indices = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5]) + return action[indices] + + @property + def init_qpos(self): + return np.array([0.0] * 11) + + @property + def speed(self): + return 0.15 + + @property + def dof(self): + return 6 + + @property + def _important_geoms(self): + return { + "left_finger": [ + "L_thumb_proximal_base_link_col", + "L_thumb_proximal_link_col", + "L_thumb_distal_link_col", + ], + "right_finger": [ + "L_index_proximal_link_col", + "L_index_intermediate_link_col", + "L_middle_proximal_link_col", + "L_middle_proximal_link_col", + "L_ring_proximal_link_col", + "L_ring_intermediate_link_col", + "L_pinky_proximal_link_col", + "L_pinky_intermediate_link_col", + ], + "left_fingerpad": [ + "L_thumb_proximal_base_link_col", + "L_thumb_proximal_link_col", + "L_thumb_distal_link_col", + ], + "right_fingerpad": [ + "L_index_proximal_link_col", + "L_index_intermediate_link_col", + "L_middle_proximal_link_col", + "L_middle_proximal_link_col", + "L_ring_proximal_link_col", + "L_ring_intermediate_link_col", + "L_pinky_proximal_link_col", + "L_pinky_intermediate_link_col", + ], + } + + +class FourierRightHand(GripperModel): + """ + Dexterous right hand of GR1 robot + + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("grippers/fourier_right_hand.xml"), idn=idn) + + def format_action(self, action): + # the more correct way is to add tag in the xml + # however the tag makes finger movement laggy, so manually copy the value for finger joints + # 0 is thumb rot, no copying. Thumb bend has 3 joints, so copy 3 times. Other fingers has 2 joints, so copy 2 times. + assert len(action) == self.dof + action = np.array(action) + indices = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5]) + return action[indices] + + @property + def init_qpos(self): + return np.array([0.0] * 11) + + @property + def speed(self): + return 0.15 + + @property + def dof(self): + return 6 + + @property + def _important_geoms(self): + return { + "left_finger": [ + "R_thumb_proximal_base_link_col", + "R_thumb_proximal_link_col", + "R_thumb_distal_link_col", + ], + "right_finger": [ + "R_index_proximal_link_col", + "R_index_intermediate_link_col", + "R_middle_proximal_link_col", + "R_middle_proximal_link_col", + "R_ring_proximal_link_col", + "R_ring_intermediate_link_col", + "R_pinky_proximal_link_col", + "R_pinky_intermediate_link_col", + ], + "left_fingerpad": [ + "R_thumb_proximal_base_link_col", + "R_thumb_proximal_link_col", + "R_thumb_distal_link_col", + ], + "right_fingerpad": [ + "R_index_proximal_link_col", + "R_index_intermediate_link_col", + "R_middle_proximal_link_col", + "R_middle_proximal_link_col", + "R_ring_proximal_link_col", + "R_ring_intermediate_link_col", + "R_pinky_proximal_link_col", + "R_pinky_intermediate_link_col", + ], + } diff --git a/third_party/robosuite/robosuite/models/grippers/gripper_factory.py b/third_party/robosuite/robosuite/models/grippers/gripper_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..79f5348e672d6ead4618b1525612864b69b42c1d --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/gripper_factory.py @@ -0,0 +1,32 @@ +""" +Defines a string based method of initializing grippers +""" +from typing import Optional + +from robosuite.models.grippers.gripper_model import GripperModel + + +def gripper_factory(name: Optional[str], idn=0) -> GripperModel: + """ + Generator for grippers + + Creates a GripperModel instance with the provided name. + + Args: + name (None or str): the name of the gripper class + idn (int or str): Number or some other unique identification string for this gripper instance + + Returns: + GripperModel: requested gripper instance + + Raises: + XMLError: [invalid XML] + """ + # Import GRIPPER_MAPPING at runtime so we avoid circular imports + from robosuite.models.grippers import ALL_GRIPPERS, GRIPPER_MAPPING + + # Make sure gripper is valid + assert name in GRIPPER_MAPPING, f"Unknown end effector name: {name}. Valid options are: {ALL_GRIPPERS}" + + # Generate gripper + return GRIPPER_MAPPING[name](idn=idn) diff --git a/third_party/robosuite/robosuite/models/grippers/gripper_model.py b/third_party/robosuite/robosuite/models/grippers/gripper_model.py new file mode 100644 index 0000000000000000000000000000000000000000..5ebe18b3ae96aa2a0d04134071388dde1c75de10 --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/gripper_model.py @@ -0,0 +1,161 @@ +""" +Defines the base class of all grippers +""" +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.base import MujocoXMLModel +from robosuite.utils.mjcf_utils import GRIPPER_COLLISION_COLOR, find_elements, string_to_array + + +class GripperModel(MujocoXMLModel): + """ + Base class for grippers + + Args: + fname (str): Path to relevant xml file to create this gripper instance + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, fname, idn=0): + super().__init__(fname, idn=idn) + + # Set variable to hold current action being outputted + self.current_action = np.zeros(self.dof) + + # Grab gripper offset (string -> np.array -> elements [1, 2, 3, 0] (x, y, z, w)) + # This is the comopunded rotation with the base body and the eef body as well! + base_quat = np.fromstring(self.worldbody[0].attrib.get("quat", "1 0 0 0"), dtype=np.float64, sep=" ")[ + [1, 2, 3, 0] + ] + eef_element = find_elements( + root=self.root, tags="body", attribs={"name": self.correct_naming("eef")}, return_first=True + ) + eef_relative_quat = string_to_array(eef_element.get("quat", "1 0 0 0"))[[1, 2, 3, 0]] + self.rotation_offset = T.quat_multiply(eef_relative_quat, base_quat) + + def format_action(self, action): + """ + Given (-1,1) abstract control as np-array + returns the (-1,1) control signals + for underlying actuators as 1-d np array + """ + raise NotImplementedError + + # -------------------------------------------------------------------------------------- # + # Properties: In general, these are the name-adjusted versions from the private # + # subclass implementations pulled from their respective raw xml files # + # -------------------------------------------------------------------------------------- # + + @property + def naming_prefix(self): + return "gripper{}_".format(self.idn) + + @property + def speed(self): + """ + How quickly the gripper opens / closes + + Returns: + float: Speed of the gripper + """ + return 0.0 + + @property + def dof(self): + """ + Defines the number of DOF of the gripper + + Returns: + int: gripper DOF + """ + return len(self._actuators) + + @property + def bottom_offset(self): + return np.zeros(3) + + @property + def top_offset(self): + return np.zeros(3) + + @property + def horizontal_radius(self): + return 0 + + @property + def contact_geom_rgba(self): + return GRIPPER_COLLISION_COLOR + + # -------------------------------------------------------------------------------------- # + # All subclasses must implement the following properties # + # -------------------------------------------------------------------------------------- # + + @property + def init_qpos(self): + """ + Defines the default rest (open) qpos of the gripper + + Returns: + np.array: Default init qpos of this gripper + """ + raise NotImplementedError + + @property + def _important_sites(self): + """ + Sites used to aid visualization by human. (usually "grip_site" and "grip_cylinder") + (and should be hidden from robots) + + Returns: + dict: + + :`'grip_site'`: Name of grip actuation intersection location site + :`'grip_cylinder'`: Name of grip actuation z-axis location site + :`'ee'`: Name of end effector site + :`'ee_x'`: Name of end effector site (x-axis) + :`'ee_y'`: Name of end effector site (y-axis) + :`'ee_z'`: Name of end effector site (z-axis) + """ + return { + "grip_site": "grip_site", + "grip_cylinder": "grip_site_cylinder", + "ee": "ee", + "ee_x": "ee_x", + "ee_y": "ee_y", + "ee_z": "ee_z", + } + + @property + def _important_geoms(self): + """ + Geoms corresponding to important components of the gripper (by default, left_finger, right_finger, + left_fingerpad, right_fingerpad). + Note that these are the raw string names directly pulled from a gripper's corresponding XML file, + NOT the adjusted name with an auto-generated naming prefix + + Note that this should be a dict of lists. + + Returns: + dict of list: Raw XML important geoms, where each set of geoms are grouped as a list and are + organized by keyword string entries into a dict + """ + return { + "left_finger": [], + "right_finger": [], + "left_fingerpad": [], + "right_fingerpad": [], + } + + @property + def _important_sensors(self): + """ + Sensor names for each gripper (usually "force_ee" and "torque_ee") + + Returns: + dict: + + :`'force_ee'`: Name of force eef sensor for this gripper + :`'torque_ee'`: Name of torque eef sensor for this gripper + """ + return {sensor: sensor for sensor in ["force_ee", "torque_ee"]} diff --git a/third_party/robosuite/robosuite/models/grippers/gripper_tester.py b/third_party/robosuite/robosuite/models/grippers/gripper_tester.py new file mode 100644 index 0000000000000000000000000000000000000000..8221d855fad0580a5b31b2f500617d825d026707 --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/gripper_tester.py @@ -0,0 +1,235 @@ +""" +Defines GripperTester that is used to test the physical properties of various grippers +""" +import xml.etree.ElementTree as ET + +import numpy as np + +import robosuite.macros as macros +from robosuite.models.arenas.table_arena import TableArena +from robosuite.models.objects import BoxObject +from robosuite.models.world import MujocoWorldBase +from robosuite.utils import OpenCVRenderer +from robosuite.utils.binding_utils import MjRenderContextOffscreen, MjSim +from robosuite.utils.mjcf_utils import array_to_string, new_actuator, new_joint + + +class GripperTester: + """ + A class that is used to test gripper + + Args: + gripper (GripperModel): A gripper instance to be tested + pos (str): (x y z) position to place the gripper in string form, e.g. '0 0 0.3' + quat (str): rotation to apply to gripper in string form, e.g. '0 0 1 0' to flip z axis + gripper_low_pos (float): controls the gipper y position, larger -> higher + gripper_high_pos (float): controls the gipper y high position larger -> higher, + must be larger than gripper_low_pos + box_size (None or 3-tuple of int): the size of the box to grasp, None defaults to [0.02, 0.02, 0.02] + box_density (int): the density of the box to grasp + step_time (int): the interval between two gripper actions + render (bool): if True, show rendering + """ + + def __init__( + self, + gripper, + pos, + quat, + gripper_low_pos, + gripper_high_pos, + box_size=None, + box_density=10000, + step_time=400, + render=True, + ): + # define viewer + self.viewer = None + + world = MujocoWorldBase() + # Add a table + arena = TableArena(table_full_size=(0.4, 0.4, 0.1), table_offset=(0, 0, 0.1), has_legs=False) + world.merge(arena) + + # Add a gripper + self.gripper = gripper + # Create another body with a slider joint to which we'll add this gripper + gripper_body = ET.Element("body") + gripper_body.set("pos", pos) + gripper_body.set("quat", quat) # flip z + gripper_body.append(new_joint(name="gripper_z_joint", type="slide", axis="0 0 -1", damping="50")) + # Add all gripper bodies to this higher level body + for body in gripper.worldbody: + gripper_body.append(body) + # Merge the all of the gripper tags except its bodies + world.merge(gripper, merge_body=None) + # Manually add the higher level body we created + world.worldbody.append(gripper_body) + # Create a new actuator to control our slider joint + world.actuator.append(new_actuator(joint="gripper_z_joint", act_type="position", name="gripper_z", kp="500")) + + # Add an object for grasping + # density is in units kg / m3 + TABLE_TOP = [0, 0, 0.09] + if box_size is None: + box_size = [0.02, 0.02, 0.02] + box_size = np.array(box_size) + self.cube = BoxObject( + name="object", size=box_size, rgba=[1, 0, 0, 1], friction=[1, 0.005, 0.0001], density=box_density + ) + object_pos = np.array(TABLE_TOP + box_size * [0, 0, 1]) + mujoco_object = self.cube.get_obj() + # Set the position of this object + mujoco_object.set("pos", array_to_string(object_pos)) + # Add our object to the world body + world.worldbody.append(mujoco_object) + + # add reference objects for x and y axes + x_ref = BoxObject( + name="x_ref", size=[0.01, 0.01, 0.01], rgba=[0, 1, 0, 1], obj_type="visual", joints=None + ).get_obj() + x_ref.set("pos", "0.2 0 0.105") + world.worldbody.append(x_ref) + y_ref = BoxObject( + name="y_ref", size=[0.01, 0.01, 0.01], rgba=[0, 0, 1, 1], obj_type="visual", joints=None + ).get_obj() + y_ref.set("pos", "0 0.2 0.105") + world.worldbody.append(y_ref) + + self.world = world + self.render = render + self.simulation_ready = False + self.step_time = step_time + self.cur_step = 0 + if gripper_low_pos > gripper_high_pos: + raise ValueError( + "gripper_low_pos {} is larger " "than gripper_high_pos {}".format(gripper_low_pos, gripper_high_pos) + ) + self.gripper_low_pos = gripper_low_pos + self.gripper_high_pos = gripper_high_pos + + def start_simulation(self): + """ + Starts simulation of the test world + """ + model_xml = self.world.get_xml() + self.sim = MjSim.from_xml_string(model_xml) + + if self.render: + self.viewer = OpenCVRenderer(self.sim) + # We also need to add the offscreen context + if self.sim._render_context_offscreen is None: + render_context = MjRenderContextOffscreen(self.sim, device_id=-1) + self.sim.add_render_context(render_context) + self.sim_state = self.sim.get_state() + + # For gravity correction + gravity_corrected = ["gripper_z_joint"] + self._gravity_corrected_qvels = [self.sim.model.get_joint_qvel_addr(x) for x in gravity_corrected] + + self.gripper_z_id = self.sim.model.actuator_name2id("gripper_z") + self.gripper_z_is_low = False + + self.gripper_actuator_ids = [self.sim.model.actuator_name2id(x) for x in self.gripper.actuators] + + self.gripper_is_closed = True + + self.object_id = self.sim.model.body_name2id(self.cube.root_body) + object_default_pos = self.sim.data.body_xpos[self.object_id] + self.object_default_pos = np.array(object_default_pos, copy=True) + + self.reset() + self.simulation_ready = True + + def reset(self): + """ + Resets the simulation to the initial state + """ + self.sim.set_state(self.sim_state) + self.cur_step = 0 + + def close(self): + """ + Close the viewer if it exists + """ + if self.viewer is not None: + self.viewer.close() + + def step(self): + """ + Forward the simulation by one timestep + + Raises: + RuntimeError: if start_simulation is not yet called. + """ + if not self.simulation_ready: + raise RuntimeError("Call start_simulation before calling step") + if self.gripper_z_is_low: + self.sim.data.ctrl[self.gripper_z_id] = self.gripper_low_pos + else: + self.sim.data.ctrl[self.gripper_z_id] = self.gripper_high_pos + if self.gripper_is_closed: + self._apply_gripper_action(1) + else: + self._apply_gripper_action(-1) + self._apply_gravity_compensation() + self.sim.step() + if self.render: + self.viewer.render() + self.cur_step += 1 + + def _apply_gripper_action(self, action): + """ + Applies binary gripper action + + Args: + action (int): Action to apply. Should be -1 (open) or 1 (closed) + """ + gripper_action_actual = self.gripper.format_action(np.array([action])) + # rescale normalized gripper action to control ranges + ctrl_range = self.sim.model.actuator_ctrlrange[self.gripper_actuator_ids] + bias = 0.5 * (ctrl_range[:, 1] + ctrl_range[:, 0]) + weight = 0.5 * (ctrl_range[:, 1] - ctrl_range[:, 0]) + applied_gripper_action = bias + weight * gripper_action_actual + self.sim.data.ctrl[self.gripper_actuator_ids] = applied_gripper_action + + def _apply_gravity_compensation(self): + """ + Applies gravity compensation to the simulation + """ + self.sim.data.qfrc_applied[self._gravity_corrected_qvels] = self.sim.data.qfrc_bias[ + self._gravity_corrected_qvels + ] + + def loop(self, total_iters=1, test_y=False, y_baseline=0.01): + """ + Performs lower, grip, raise and release actions of a gripper, + each separated with T timesteps + + Args: + total_iters (int): Iterations to perform before exiting + test_y (bool): test if object is lifted + y_baseline (float): threshold for determining that object is lifted + """ + seq = [(False, False), (True, False), (True, True), (False, True)] + for cur_iter in range(total_iters): + for cur_plan in seq: + self.gripper_z_is_low, self.gripper_is_closed = cur_plan + for step in range(self.step_time): + self.step() + if test_y: + if not self.object_height > y_baseline: + raise ValueError( + "object is lifed by {}, ".format(self.object_height) + + "not reaching the requirement {}".format(y_baseline) + ) + + @property + def object_height(self): + """ + Queries the height (z) of the object compared to on the ground + + Returns: + float: Object height relative to default (ground) object position + """ + return self.sim.data.body_xpos[self.object_id][2] - self.object_default_pos[2] diff --git a/third_party/robosuite/robosuite/models/grippers/inspire_hands.py b/third_party/robosuite/robosuite/models/grippers/inspire_hands.py new file mode 100644 index 0000000000000000000000000000000000000000..1484fe55ea50da83bed99c4b6158a543dddedfdb --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/inspire_hands.py @@ -0,0 +1,147 @@ +""" +Dexterous hands for GR1 robot. +""" +import numpy as np + +from robosuite.models.grippers.gripper_model import GripperModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class InspireLeftHand(GripperModel): + """ + Dexterous left hand of GR1 robot + + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("grippers/inspire_left_hand.xml"), idn=idn) + + def format_action(self, action): + # the more correct way is to add tag in the xml + # however the tag makes finger movement laggy, so manually copy the value for finger joints + # 0 is thumb rot, no copying. Thumb bend has 3 joints, so copy 3 times. Other fingers has 2 joints, so copy 2 times. + assert len(action) == self.dof + action = np.array(action) + indices = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5]) + return action[indices] + + @property + def init_qpos(self): + return np.array([0.0] * 12) + + @property + def speed(self): + return 0.15 + + @property + def dof(self): + return 6 + + @property + def _important_geoms(self): + return { + "left_finger": [ + "l_thumb_proximal_col", + "l_thumb_proximal_2_col", + "l_thumb_middle_col", + "l_thumb_distal_col", + ], + "right_finger": [ + "l_index_proximal_col", + "l_index_distal_col", + "l_middle_proximal_col", + "l_middle_distal_col", + "l_ring_proximal_col", + "l_ring_distal_col", + "l_pinky_proximal_col", + "l_pinky_distal_col", + ], + "left_fingerpad": [ + "l_thumb_proximal_col", + "l_thumb_proximal_2_col", + "l_thumb_middle_col", + "l_thumb_distal_col", + ], + "right_fingerpad": [ + "l_index_proximal_col", + "l_index_distal_col", + "l_middle_proximal_col", + "l_middle_distal_col", + "l_ring_proximal_col", + "l_ring_distal_col", + "l_pinky_proximal_col", + "l_pinky_distal_col", + ], + } + + +class InspireRightHand(GripperModel): + """ + Dexterous right hand of GR1 robot + + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("grippers/inspire_right_hand.xml"), idn=idn) + + def format_action(self, action): + # the more correct way is to add tag in the xml + # however the tag makes finger movement laggy, so manually copy the value for finger joints + # 0 is thumb rot, no copying. Thumb bend has 3 joints, so copy 3 times. Other fingers has 2 joints, so copy 2 times. + assert len(action) == self.dof + action = np.array(action) + indices = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5]) + return action[indices] + + @property + def init_qpos(self): + return np.array([0.0] * 12) + + @property + def speed(self): + return 0.15 + + @property + def dof(self): + return 6 + + @property + def _important_geoms(self): + return { + "left_finger": [ + "r_thumb_proximal_col", + "r_thumb_proximal_2_col", + "r_thumb_middle_col", + "r_thumb_distal_col", + ], + "right_finger": [ + "r_index_proximal_col", + "r_index_distal_col", + "r_middle_proximal_col", + "r_middle_distal_col", + "r_ring_proximal_col", + "r_ring_distal_col", + "r_pinky_proximal_col", + "r_pinky_distal_col", + ], + "left_fingerpad": [ + "r_thumb_proximal_col", + "r_thumb_proximal_2_col", + "r_thumb_middle_col", + "r_thumb_distal_col", + ], + "right_fingerpad": [ + "r_index_proximal_col", + "r_index_distal_col", + "r_middle_proximal_col", + "r_middle_distal_col", + "r_ring_proximal_col", + "r_ring_distal_col", + "r_pinky_proximal_col", + "r_pinky_distal_col", + ], + } diff --git a/third_party/robosuite/robosuite/models/grippers/jaco_three_finger_gripper.py b/third_party/robosuite/robosuite/models/grippers/jaco_three_finger_gripper.py new file mode 100644 index 0000000000000000000000000000000000000000..3a379a37dc4e24612c6eb9202aaaa185fffe2a96 --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/jaco_three_finger_gripper.py @@ -0,0 +1,108 @@ +""" +Gripper for Kinova's Jaco robot arm (has three fingers). +""" +import numpy as np + +from robosuite.models.grippers.gripper_model import GripperModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class JacoThreeFingerGripperBase(GripperModel): + """ + Gripper for Kinova's Jaco robot arm (has three fingers). + + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("grippers/jaco_three_finger_gripper.xml"), idn=idn) + + def format_action(self, action): + return action + + @property + def init_qpos(self): + return np.array([0.5, 0, 0.5, 0, 0.5, 0]) + + @property + def _important_geoms(self): + return { + "left_finger": [ + "index_proximal_collision", + "index_distal_collision", + "index_tip_collision", + "pinky_proximal_collision", + "pinky_distal_collision", + "pinky_tip_collision", + "index_tip_collision", + "pinky_pad_collision", + ], + "right_finger": [ + "thumb_proximal_collision", + "thumb_distal_collision", + "thumb_tip_collision", + "thumb_pad_collision", + ], + "left_fingerpad": ["index_pad_collision", "pinky_pad_collision"], + "right_fingerpad": ["thumb_pad_collision"], + } + + +class JacoThreeFingerGripper(JacoThreeFingerGripperBase): + """ + Modifies JacoThreeFingerGripperBase to only take one action. + """ + + def format_action(self, action): + """ + Maps continuous action into binary output + -1 => open, 1 => closed + + Args: + action (np.array): gripper-specific action + + Raises: + AssertionError: [Invalid action dimension size] + """ + assert len(action) == self.dof + self.current_action = np.clip(self.current_action - self.speed * np.sign(action), -1.0, 1.0) + # NOTE(YL): format 1dof to default 3dof + return self.current_action * np.array([1, 1, 1]) + + @property + def speed(self): + return 0.01 + + @property + def dof(self): + return 1 + + +class JacoThreeFingerDexterousGripper(JacoThreeFingerGripperBase): + """ + Dexterous variation of the Jaco gripper in which all finger are actuated independently + """ + + def format_action(self, action): + """ + Maps continuous action into binary output + all -1 => open, all 1 => closed + + Args: + action (np.array): gripper-specific action + + Raises: + AssertionError: [Invalid action dimension size] + """ + assert len(action) == self.dof + self.current_action = np.clip(self.current_action - self.speed * np.sign(action), -1.0, 1.0) + return self.current_action + + @property + def speed(self): + return 0.01 + + @property + def dof(self): + return 3 diff --git a/third_party/robosuite/robosuite/models/grippers/null_gripper.py b/third_party/robosuite/robosuite/models/grippers/null_gripper.py new file mode 100644 index 0000000000000000000000000000000000000000..48f6a804744099f5cfca1dd23397d2bd7f5cd5ca --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/null_gripper.py @@ -0,0 +1,24 @@ +""" +Null Gripper (if we don't want to attach gripper to robot eef). +""" +from robosuite.models.grippers.gripper_model import GripperModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class NullGripper(GripperModel): + """ + Dummy Gripper class to represent no gripper + + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("grippers/null_gripper.xml"), idn=idn) + + def format_action(self, action): + return action + + @property + def init_qpos(self): + return None diff --git a/third_party/robosuite/robosuite/models/grippers/panda_gripper.py b/third_party/robosuite/robosuite/models/grippers/panda_gripper.py new file mode 100644 index 0000000000000000000000000000000000000000..738d49f9502b253d674511b54d032ae0dae9e473 --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/panda_gripper.py @@ -0,0 +1,66 @@ +""" +Gripper for Franka's Panda (has two fingers). +""" +import numpy as np + +from robosuite.models.grippers.gripper_model import GripperModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class PandaGripperBase(GripperModel): + """ + Gripper for Franka's Panda (has two fingers). + + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("grippers/panda_gripper.xml"), idn=idn) + + def format_action(self, action): + return action + + @property + def init_qpos(self): + return np.array([0.020833, -0.020833]) + + @property + def _important_geoms(self): + return { + "left_finger": ["finger1_collision", "finger1_pad_collision"], + "right_finger": ["finger2_collision", "finger2_pad_collision"], + "left_fingerpad": ["finger1_pad_collision"], + "right_fingerpad": ["finger2_pad_collision"], + } + + +class PandaGripper(PandaGripperBase): + """ + Modifies PandaGripperBase to only take one action. + """ + + def format_action(self, action): + """ + Maps continuous action into binary output + -1 => open, 1 => closed + + Args: + action (np.array): gripper-specific action + + Raises: + AssertionError: [Invalid action dimension size] + """ + assert len(action) == self.dof + self.current_action = np.clip( + self.current_action + np.array([-1.0, 1.0]) * self.speed * np.sign(action), -1.0, 1.0 + ) + return self.current_action + + @property + def speed(self): + return 0.2 + + @property + def dof(self): + return 1 diff --git a/third_party/robosuite/robosuite/models/grippers/rethink_gripper.py b/third_party/robosuite/robosuite/models/grippers/rethink_gripper.py new file mode 100644 index 0000000000000000000000000000000000000000..0c13154b4d35cb0796318fb413761f503804735c --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/rethink_gripper.py @@ -0,0 +1,66 @@ +""" +Gripper with two fingers for Rethink Robots. +""" +import numpy as np + +from robosuite.models.grippers.gripper_model import GripperModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class RethinkGripperBase(GripperModel): + """ + Gripper with long two-fingered parallel jaw. + + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("grippers/rethink_gripper.xml"), idn=idn) + + def format_action(self, action): + return action + + @property + def init_qpos(self): + return np.array([0.020833, -0.020833]) + + @property + def _important_geoms(self): + return { + "left_finger": ["l_finger_g0", "l_finger_g1", "l_fingertip_g0", "l_fingerpad_g0"], + "right_finger": ["r_finger_g0", "r_finger_g1", "r_fingertip_g0", "r_fingerpad_g0"], + "left_fingerpad": ["l_fingerpad_g0"], + "right_fingerpad": ["r_fingerpad_g0"], + } + + +class RethinkGripper(RethinkGripperBase): + """ + Modifies two finger base to only take one action. + """ + + def format_action(self, action): + """ + Maps continuous action into binary output + -1 => open, 1 => closed + + Args: + action (np.array): gripper-specific action + + Raises: + AssertionError: [Invalid action dimension size] + """ + assert len(action) == 1 + self.current_action = np.clip( + self.current_action + np.array([1.0, -1.0]) * self.speed * np.sign(action), -1.0, 1.0 + ) + return self.current_action + + @property + def speed(self): + return 0.2 + + @property + def dof(self): + return 1 diff --git a/third_party/robosuite/robosuite/models/grippers/robotiq_140_gripper.py b/third_party/robosuite/robosuite/models/grippers/robotiq_140_gripper.py new file mode 100644 index 0000000000000000000000000000000000000000..f5a31e250d330fdce18777cd91f7ceda8d75fbe8 --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/robotiq_140_gripper.py @@ -0,0 +1,77 @@ +""" +Gripper with 140mm Jaw width from Robotiq (has two fingers). +""" +import numpy as np + +from robosuite.models.grippers.gripper_model import GripperModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class Robotiq140GripperBase(GripperModel): + """ + Gripper with 140mm Jaw width from Robotiq (has two fingers). + + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("grippers/robotiq_gripper_140.xml"), idn=idn) + + def format_action(self, action): + return action + + @property + def init_qpos(self): + return np.array([0.012, 0.065, 0.065, -0.012, 0.065, 0.065]) + + @property + def _important_geoms(self): + return { + "left_finger": [ + "left_outer_finger_collision", + "left_inner_finger_collision", + "left_fingertip_collision", + "left_fingerpad_collision", + ], + "right_finger": [ + "right_outer_finger_collision", + "right_inner_finger_collision", + "right_fingertip_collision", + "right_fingerpad_collision", + ], + "left_fingerpad": ["left_fingerpad_collision"], + "right_fingerpad": ["right_fingerpad_collision"], + } + + +class Robotiq140Gripper(Robotiq140GripperBase): + """ + Modifies Robotiq140GripperBase to only take one action. + """ + + def format_action(self, action): + """ + Maps continuous action into binary output + -1 => open, 1 => closed + + Args: + action (np.array): gripper-specific action + + Raises: + AssertionError: [Invalid action dimension size] + """ + assert len(action) == 1 + self.current_action = np.clip( + self.current_action + np.array([1.0, -1.0]) * self.speed * np.sign(action), -1.0, 1.0 + ) + return self.current_action + + @property + def speed(self): + return 0.2 + + @property + def dof(self): + return 1 diff --git a/third_party/robosuite/robosuite/models/grippers/robotiq_85_gripper.py b/third_party/robosuite/robosuite/models/grippers/robotiq_85_gripper.py new file mode 100644 index 0000000000000000000000000000000000000000..6eaeb39afe9d0b7fa8d7925bff4e731649ee79fa --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/robotiq_85_gripper.py @@ -0,0 +1,76 @@ +""" +6-DoF gripper with its open/close variant +""" +import numpy as np + +from robosuite.models.grippers.gripper_model import GripperModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class Robotiq85GripperBase(GripperModel): + """ + 6-DoF Robotiq gripper. + + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("grippers/robotiq_gripper_85.xml"), idn=idn) + + def format_action(self, action): + return action + + @property + def init_qpos(self): + return np.array([-0.026, -0.267, -0.200, -0.026, -0.267, -0.200]) + + @property + def _important_geoms(self): + return { + "left_finger": [ + "left_outer_finger_collision", + "left_inner_finger_collision", + "left_fingertip_collision", + "left_fingerpad_collision", + ], + "right_finger": [ + "right_outer_finger_collision", + "right_inner_finger_collision", + "right_fingertip_collision", + "right_fingerpad_collision", + ], + "left_fingerpad": ["left_fingerpad_collision"], + "right_fingerpad": ["right_fingerpad_collision"], + } + + +class Robotiq85Gripper(Robotiq85GripperBase): + """ + 1-DoF variant of RobotiqGripperBase. + """ + + def format_action(self, action): + """ + Maps continuous action into binary output + -1 => open, 1 => closed + + Args: + action (np.array): gripper-specific action + + Raises: + AssertionError: [Invalid action dimension size] + """ + assert len(action) == 1 + self.current_action = np.clip( + self.current_action * np.array([1.0, 1.0]) + self.speed * np.sign(action), -1.0, 1.0 + ) + return self.current_action + + @property + def speed(self): + return 0.20 + + @property + def dof(self): + return 1 diff --git a/third_party/robosuite/robosuite/models/grippers/robotiq_three_finger_gripper.py b/third_party/robosuite/robosuite/models/grippers/robotiq_three_finger_gripper.py new file mode 100644 index 0000000000000000000000000000000000000000..c7cc7c830f8d231d99bd67662691c9408b269f76 --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/robotiq_three_finger_gripper.py @@ -0,0 +1,115 @@ +""" +Gripper with 11-DoF controlling three fingers and its open/close variant. +""" +import numpy as np + +from robosuite.models.grippers.gripper_model import GripperModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class RobotiqThreeFingerGripperBase(GripperModel): + """ + Gripper with 11 dof controlling three fingers. + + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("grippers/robotiq_gripper_s.xml"), idn=idn) + + def format_action(self, action): + return action + + @property + def init_qpos(self): + return np.zeros(11) + + @property + def _important_geoms(self): + return { + "left_finger": [ + "f1_l0", + "f1_l1", + "f1_l2", + "f1_l3", + "f2_l0", + "f2_l1", + "f2_l2", + "f2_l3", + "f1_tip_collision", + "f2_tip_collision", + "f1_pad_collision", + "f2_pad_collision", + ], + "right_finger": [ + "f3_l0", + "f3_l1", + "f3_l2", + "f3_l3", + "finger_middle_tip_collision", + "finger_middle_pad_collision", + ], + "left_fingerpad": ["f1_pad_collision", "f2_pad_collision"], + "right_fingerpad": ["finger_middle_pad_collision"], + } + + +class RobotiqThreeFingerGripper(RobotiqThreeFingerGripperBase): + """ + 1-DoF variant of RobotiqThreeFingerGripperBase. + """ + + def format_action(self, action): + """ + Maps continuous action into binary output + -1 => open, 1 => closed + + Args: + action (np.array): gripper-specific action + + Raises: + AssertionError: [Invalid action dimension size] + """ + assert len(action) == self.dof + self.current_action = np.clip(self.current_action + self.speed * np.array(action), -1.0, 1.0) + # Automatically set the scissor joint to "closed" position by default + return np.concatenate([self.current_action * np.ones(3), [-1]]) + + @property + def speed(self): + return 0.2 + + @property + def dof(self): + return 1 + + +class RobotiqThreeFingerDexterousGripper(RobotiqThreeFingerGripperBase): + """ + Dexterous variation of the 3-finger Robotiq gripper in which all finger are actuated independently as well + as the scissor joint between fingers 1 and 2 + """ + + def format_action(self, action): + """ + Maps continuous action into binary output + all -1 => open, all 1 => closed + + Args: + action (np.array): gripper-specific action + + Raises: + AssertionError: [Invalid action dimension size] + """ + assert len(action) == self.dof + self.current_action = np.clip(self.current_action + self.speed * np.sign(action), -1.0, 1.0) + return self.current_action + + @property + def speed(self): + return 0.2 + + @property + def dof(self): + return 4 diff --git a/third_party/robosuite/robosuite/models/grippers/wiping_gripper.py b/third_party/robosuite/robosuite/models/grippers/wiping_gripper.py new file mode 100644 index 0000000000000000000000000000000000000000..692475efaba30837edd8ef987801124f6dfb672b --- /dev/null +++ b/third_party/robosuite/robosuite/models/grippers/wiping_gripper.py @@ -0,0 +1,34 @@ +""" +Gripper without fingers to wipe a surface +""" +from robosuite.models.grippers.gripper_model import GripperModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class WipingGripper(GripperModel): + """ + A Wiping Gripper with no actuation and enabled with sensors to detect contact forces + + Args: + idn (int or str): Number or some other unique identification string for this gripper instance + """ + + def __init__(self, idn=0): + super().__init__(xml_path_completion("grippers/wiping_gripper.xml"), idn=idn) + + def format_action(self, action): + return action + + @property + def init_qpos(self): + return None + + @property + def _important_geoms(self): + return { + "left_finger": [], + "right_finger": [], + "left_fingerpad": [], + "right_fingerpad": [], + "corners": ["wiping_corner1", "wiping_corner2", "wiping_corner3", "wiping_corner4"], + } diff --git a/third_party/robosuite/robosuite/models/objects/__init__.py b/third_party/robosuite/robosuite/models/objects/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e11ddca0521eb6d0a4bdba1e9d1582cef2fafa7c --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/__init__.py @@ -0,0 +1,24 @@ +from .objects import MujocoObject, MujocoXMLObject, MujocoGeneratedObject +from .generated_objects import CompositeBodyObject, CompositeObject, PrimitiveObject +from .object_groups import ObjectGroup + +from .xml_objects import ( + BottleObject, + CanObject, + LemonObject, + MilkObject, + BreadObject, + CerealObject, + SquareNutObject, + RoundNutObject, + MilkVisualObject, + BreadVisualObject, + CerealVisualObject, + CanVisualObject, + PlateWithHoleObject, + DoorObject, +) +from .primitive import * +from .composite import * +from .composite_body import * +from .group import * diff --git a/third_party/robosuite/robosuite/models/objects/composite/__init__.py b/third_party/robosuite/robosuite/models/objects/composite/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67b6a445552775cb953873d0f3dddcea00dcaf2d --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/composite/__init__.py @@ -0,0 +1,8 @@ +from .bin import Bin +from .hammer import HammerObject +from .lid import Lid +from .pot_with_handles import PotWithHandlesObject +from .hollow_cylinder import HollowCylinderObject +from .cone import ConeObject +from .hook_frame import HookFrame +from .stand_with_mount import StandWithMount diff --git a/third_party/robosuite/robosuite/models/objects/composite/bin.py b/third_party/robosuite/robosuite/models/objects/composite/bin.py new file mode 100644 index 0000000000000000000000000000000000000000..a69afc06c4892894a3fec2b01625f8cf5137a870 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/composite/bin.py @@ -0,0 +1,146 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import CustomMaterial, add_to_dict + + +class Bin(CompositeObject): + """ + Generates a four-walled bin container with an open top. + Args: + name (str): Name of this Bin object + bin_size (3-array): (x,y,z) full size of bin + wall_thickness (float): How thick to make walls of bin + transparent_walls (bool): If True, walls will be semi-translucent + friction (3-array or None): If specified, sets friction values for this bin. None results in default values + density (float): Density value to use for all geoms. Defaults to 1000 + use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored + rgba (4-array or None): If specified, sets rgba values for all geoms. None results in default values + """ + + def __init__( + self, + name, + bin_size=(0.3, 0.3, 0.15), + wall_thickness=0.01, + transparent_walls=True, + friction=None, + density=1000.0, + use_texture=True, + rgba=(0.2, 0.1, 0.0, 1.0), + ): + # Set name + self._name = name + + # Set object attributes + self.bin_size = np.array(bin_size) + self.wall_thickness = wall_thickness + self.transparent_walls = transparent_walls + self.friction = friction if friction is None else np.array(friction) + self.density = density + self.use_texture = use_texture + self.rgba = rgba + self.bin_mat_name = "dark_wood_mat" + + # Element references + self._base_geom = "base" + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "3 3", + "specular": "0.4", + "shininess": "0.1", + } + bin_mat = CustomMaterial( + texture="WoodDark", + tex_name="dark_wood", + mat_name=self.bin_mat_name, + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(bin_mat) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": self.bin_size / 2.0, + "name": self.name, + "locations_relative_to_center": True, + "obj_types": "all", + "density": self.density, + } + obj_args = {} + + # Base + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(0, 0, -(self.bin_size[2] - self.wall_thickness) / 2), + geom_quats=(1, 0, 0, 0), + geom_sizes=( + np.array((self.bin_size[0], self.bin_size[1], self.wall_thickness)) + - np.array((self.wall_thickness, self.wall_thickness, 0)) + ) + / 2, + geom_names=self._base_geom, + geom_rgbas=None if self.use_texture else self.rgba, + geom_materials=self.bin_mat_name if self.use_texture else None, + geom_frictions=self.friction, + ) + + # Walls + x_vals = np.array( + [0, -(self.bin_size[0] - self.wall_thickness) / 2, 0, (self.bin_size[0] - self.wall_thickness) / 2] + ) + y_vals = np.array( + [-(self.bin_size[1] - self.wall_thickness) / 2, 0, (self.bin_size[1] - self.wall_thickness) / 2, 0] + ) + w_vals = np.array([self.bin_size[0], self.bin_size[1], self.bin_size[0], self.bin_size[1]]) + r_vals = np.array([np.pi / 2, 0, -np.pi / 2, np.pi]) + if self.transparent_walls: + wall_rgba = (1.0, 1.0, 1.0, 0.3) + wall_mat = None + else: + wall_rgba = None if self.use_texture else self.rgba + wall_mat = self.bin_mat_name if self.use_texture else None + for i, (x, y, w, r) in enumerate(zip(x_vals, y_vals, w_vals, r_vals)): + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(x, y, 0), + geom_quats=T.convert_quat(T.axisangle2quat(np.array([0, 0, r])), to="wxyz"), + geom_sizes=(self.wall_thickness / 2, w / 2, self.bin_size[2] / 2), + geom_names=f"wall{i}", + geom_rgbas=wall_rgba, + geom_materials=wall_mat, + geom_frictions=self.friction, + ) + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args + + @property + def base_geoms(self): + """ + Returns: + list of str: geom names corresponding to bin base + """ + return [self.correct_naming(self._base_geom)] diff --git a/third_party/robosuite/robosuite/models/objects/composite/cone.py b/third_party/robosuite/robosuite/models/objects/composite/cone.py new file mode 100644 index 0000000000000000000000000000000000000000..7b35e3fe36205e4162b27addf5d9da2d50629354 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/composite/cone.py @@ -0,0 +1,156 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import RED, CustomMaterial, add_to_dict + + +class ConeObject(CompositeObject): + """ + Generates an approximate cone object by using cylinder or box geoms. + Args: + name (str): Name of this Cone object + outer_radius (float): Radius of cone base + inner_radius (float): Radius of cone tip (since everything is a cylinder or box) + height (float): Height of cone + ngeoms (int): Number of cylinder or box geoms used to approximate the cone. Use + more geoms to make the approximation better. + use_box (bool): If true, use box geoms instead of cylinders, corresponding to a + square pyramid shape instead of a conical shape. + """ + + def __init__( + self, + name, + outer_radius=0.0425, + inner_radius=0.03, + height=0.05, + ngeoms=8, + use_box=False, + rgba=None, + material=None, + density=1000.0, + solref=(0.02, 1.0), + solimp=(0.9, 0.95, 0.001), + friction=None, + ): + + # Set object attributes + self._name = name + self.rgba = rgba + self.density = density + self.friction = friction if friction is None else np.array(friction) + self.solref = solref + self.solimp = solimp + + self.has_material = material is not None + if self.has_material: + assert isinstance(material, CustomMaterial) + self.material = material + + # Other private attributes + self._important_sites = {} + + # radius of the tip and the base + self.r1 = inner_radius + self.r2 = outer_radius + + # number of geoms used to approximate the cone + if ngeoms % 2 == 0: + # use an odd number of geoms for easier computation + ngeoms += 1 + self.n = ngeoms + + # cone height + self.height = height + + # unit half-height for geoms + self.unit_height = (height / ngeoms) / 2.0 + + # unit radius for geom radius grid + self.unit_r = (self.r2 - self.r1) / (self.n - 1) + + self.use_box = use_box + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Optionally add material + if self.has_material: + self.append_material(self.material) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": [self.r2, self.r2, self.height / 2.0], + "name": self.name, + "locations_relative_to_center": True, + "obj_types": "all", + "density": self.density, + "solref": self.solref, + "solimp": self.solimp, + } + obj_args = {} + + # stack the boxes / cylinders in the z-direction + ngeoms_each_side = (self.n - 1) // 2 + geom_locations = [ + (0.0, 0.0, i * self.unit_height * 2.0) for i in range(-ngeoms_each_side, ngeoms_each_side + 1) + ] + + if self.use_box: + geom_sizes = [ + ( + self.r1 + i * self.unit_r, + self.r1 + i * self.unit_r, + self.unit_height, + ) + for i in range(self.n) + ][::-1] + else: + geom_sizes = [ + ( + self.r1 + i * self.unit_r, + self.unit_height, + ) + for i in range(self.n) + ][::-1] + + for i in range(self.n): + # note: set geom condim to 4 for consistency with round-nut.xml + # geom_quat = np.array([np.cos(geom_angle / 2.), 0., 0., np.sin(geom_angle / 2.)]) + add_to_dict( + dic=obj_args, + geom_types="box" if self.use_box else "cylinder", + geom_locations=geom_locations[i], + geom_quats=None, + geom_sizes=geom_sizes[i], + geom_names="c_{}".format(i), + # geom_rgbas=None if self.has_material else self.rgba, + geom_rgbas=self.rgba, + geom_materials=self.material.mat_attrib["name"] if self.has_material else None, + geom_frictions=self.friction, + geom_condims=4, + ) + + # Sites + obj_args["sites"] = [ + { + "name": "center", + "pos": (0, 0, 0), + "size": "0.002", + "rgba": RED, + "type": "sphere", + } + ] + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args diff --git a/third_party/robosuite/robosuite/models/objects/composite/hammer.py b/third_party/robosuite/robosuite/models/objects/composite/hammer.py new file mode 100644 index 0000000000000000000000000000000000000000..dcfa96c9d038f2197201dba5b3094526e4e69ff1 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/composite/hammer.py @@ -0,0 +1,282 @@ +from collections.abc import Iterable + +import numpy as np + +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import BLUE, CYAN, GREEN, RED, CustomMaterial, add_to_dict + + +class HammerObject(CompositeObject): + """ + Generates a Hammer object with a cylindrical or box-shaped handle, cubic head, cylindrical face and triangular claw + (used in Handover task) + + Args: + name (str): Name of this Hammer object + + handle_shape (str): Either "box", for a box-shaped handle, or "cylinder", for a cylindrically-shaped handle + + handle_radius (float or 2-array of float): Either specific or range of values to draw randomly from + uniformly for the handle radius + + handle_length (float or 2-array of float): Either specific or range of values to draw randomly from + uniformly for the handle length + + handle_density (float or 2-array of float): Either specific or range of values to draw randomly from + uniformly for the handle density (in SI units). Note that this value is scaled x4 for the hammer head + + handle_friction (float or 2-array of float): Either specific or range of values to draw randomly from + uniformly for the handle friction. Note that Mujoco default values are used for the head + + head_density_ratio (float): Ratio of density of handle to head (including face and claw) + + use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored + + rgba_handle (4-array or None): If specified, sets handle rgba values + + rgba_head (4-array or None): If specified, sets handle rgba values + + rgba_face (4-array or None): If specified, sets handle rgba values + + rgba_claw (4-array or None): If specified, sets handle rgba values + + Raises: + ValueError: [Invalid handle shape] + """ + + def __init__( + self, + name, + handle_shape="box", + handle_radius=(0.015, 0.02), + handle_length=(0.1, 0.25), + handle_density=(100, 250), + handle_friction=(3.0, 5.0), + head_density_ratio=2.0, + use_texture=True, + rgba_handle=None, + rgba_head=None, + rgba_face=None, + rgba_claw=None, + ): + # Set name + self._name = name + + # Set handle type and density ratio + self.handle_shape = handle_shape + self.head_density_ratio = head_density_ratio + + # Set radius and length ranges + self.handle_radius_range = handle_radius if isinstance(handle_radius, Iterable) else [handle_radius] * 2 + self.handle_length_range = handle_length if isinstance(handle_length, Iterable) else [handle_length] * 2 + self.handle_density_range = handle_density if isinstance(handle_density, Iterable) else [handle_density] * 2 + self.handle_friction_range = handle_friction if isinstance(handle_friction, Iterable) else [handle_friction] * 2 + + # Sample actual radius and length, as well as head half-size + self.handle_radius = np.random.uniform(self.handle_radius_range[0], self.handle_radius_range[1]) + self.handle_length = np.random.uniform(self.handle_length_range[0], self.handle_length_range[1]) + self.handle_density = np.random.uniform(self.handle_density_range[0], self.handle_density_range[1]) + self.handle_friction = np.random.uniform(self.handle_friction_range[0], self.handle_friction_range[1]) + self.head_halfsize = np.random.uniform(self.handle_radius, self.handle_radius * 1.2) + + # Initialize RGBA values and texture flag + self.use_texture = use_texture + self.rgba_handle = rgba_handle if rgba_handle is not None else RED + self.rgba_head = rgba_head if rgba_head is not None else CYAN + self.rgba_face = rgba_face if rgba_face is not None else BLUE + self.rgba_claw = rgba_claw if rgba_claw is not None else GREEN + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "3 3", + "specular": "0.4", + "shininess": "0.1", + } + metal = CustomMaterial( + texture="SteelScratched", + tex_name="metal", + mat_name="metal_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + wood = CustomMaterial( + texture="WoodLight", + tex_name="wood", + mat_name="wood_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + + # Append materials to object + self.append_material(metal) + self.append_material(wood) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + full_size = np.array( + (3.2 * self.head_halfsize, self.head_halfsize, self.handle_length + 2 * self.head_halfsize) + ) + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": full_size / 2.0, + "name": self.name, + "locations_relative_to_center": True, + "obj_types": "all", + } + obj_args = {} + + # Add handle component + assert self.handle_shape in { + "cylinder", + "box", + }, "Error loading hammer: Handle type must either be 'box' or 'cylinder', got {}.".format(self.handle_shape) + add_to_dict( + dic=obj_args, + geom_types="cylinder" if self.handle_shape == "cylinder" else "box", + geom_locations=(0, 0, 0), + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array([self.handle_radius, self.handle_length / 2.0]) + if self.handle_shape == "cylinder" + else np.array([self.handle_radius, self.handle_radius, self.handle_length / 2.0]), + geom_names="handle", + geom_rgbas=None if self.use_texture else self.rgba_handle, + geom_materials="wood_mat" if self.use_texture else None, + geom_frictions=(self.handle_friction, 0.005, 0.0001), + density=self.handle_density, + ) + + # Add head component + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(0, 0, self.handle_length / 2.0 + self.head_halfsize), + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array([self.head_halfsize * 2, self.head_halfsize, self.head_halfsize]), + geom_names="head", + geom_rgbas=None if self.use_texture else self.rgba_head, + geom_materials="metal_mat" if self.use_texture else None, + geom_frictions=None, + density=self.handle_density * self.head_density_ratio, + ) + + # Add neck component + add_to_dict( + dic=obj_args, + geom_types="cylinder", + geom_locations=(self.head_halfsize * 2.2, 0, self.handle_length / 2.0 + self.head_halfsize), + geom_quats=(0.707106, 0, 0.707106, 0), + geom_sizes=np.array([self.head_halfsize * 0.8, self.head_halfsize * 0.2]), + geom_names="neck", + geom_rgbas=None if self.use_texture else self.rgba_face, + geom_materials="metal_mat" if self.use_texture else None, + geom_frictions=None, + density=self.handle_density * self.head_density_ratio, + ) + + # Add face component + add_to_dict( + dic=obj_args, + geom_types="cylinder", + geom_locations=(self.head_halfsize * 2.8, 0, self.handle_length / 2.0 + self.head_halfsize), + geom_quats=(0.707106, 0, 0.707106, 0), + geom_sizes=np.array([self.head_halfsize, self.head_halfsize * 0.4]), + geom_names="face", + geom_rgbas=None if self.use_texture else self.rgba_face, + geom_materials="metal_mat" if self.use_texture else None, + geom_frictions=None, + density=self.handle_density * self.head_density_ratio, + ) + + # Add claw component + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(-self.head_halfsize * 2, 0, self.handle_length / 2.0 + self.head_halfsize), + geom_quats=(0.9238795, 0, 0.3826834, 0), + geom_sizes=np.array([self.head_halfsize * 0.7072, self.head_halfsize * 0.95, self.head_halfsize * 0.7072]), + geom_names="claw", + geom_rgbas=None if self.use_texture else self.rgba_claw, + geom_materials="metal_mat" if self.use_texture else None, + geom_frictions=None, + density=self.handle_density * self.head_density_ratio, + ) + + # Add back in base args + obj_args.update(base_args) + + # Return this dict + return obj_args + + @property + def init_quat(self): + """ + Generates a new random orientation for the hammer + + Returns: + np.array: (x, y, z, w) quaternion orientation for the hammer + """ + # Randomly sample between +/- flip (such that the hammer head faces one way or the other) + return np.array([0.5, -0.5, 0.5, -0.5]) if np.random.rand() >= 0.5 else np.array([-0.5, -0.5, -0.5, -0.5]) + + @property + def handle_geoms(self): + """ + Returns: + list of str: geom names corresponding to hammer handle + """ + return self.correct_naming(["handle"]) + + @property + def head_geoms(self): + """ + Returns: + list of str: geom names corresponding to hammer head + """ + return self.correct_naming(["head"]) + + @property + def face_geoms(self): + """ + Returns: + list of str: geom names corresponding to hammer face + """ + return self.correct_naming(["neck", "face"]) + + @property + def claw_geoms(self): + """ + Returns: + list of str: geom names corresponding to hammer claw + """ + return self.correct_naming(["claw"]) + + @property + def all_geoms(self): + """ + Returns: + list of str: geom names corresponding to all hammer components + """ + return self.handle_geoms + self.head_geoms + self.face_geoms + self.claw_geoms + + @property + def bottom_offset(self): + return np.array([0, 0, -self.handle_radius]) + + @property + def top_offset(self): + return np.array([0, 0, self.handle_radius]) + + @property + def horizontal_radius(self): + return self.head_halfsize + 0.5 * self.handle_length diff --git a/third_party/robosuite/robosuite/models/objects/composite/hollow_cylinder.py b/third_party/robosuite/robosuite/models/objects/composite/hollow_cylinder.py new file mode 100644 index 0000000000000000000000000000000000000000..329dba0b045bfd99390fa269d34625785f845934 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/composite/hollow_cylinder.py @@ -0,0 +1,146 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import RED, CustomMaterial, add_to_dict + + +class HollowCylinderObject(CompositeObject): + """ + Generates an approximate hollow cylinder object by using box geoms. + Args: + name (str): Name of this HollowCylinder object + outer_radius (float): Outer radius of hollow cylinder + inner_radius (float): Inner radius of hollow cylinder + height (float): Height of hollow cylinder + ngeoms (int): Number of box geoms used to approximate the cylindrical shell. Use + more geoms to make the approximation better. + make_half (bool): If true, only make half of the shell. + """ + + def __init__( + self, + name, + outer_radius=0.0425, + inner_radius=0.03, + height=0.05, + ngeoms=8, + rgba=None, + material=None, + density=1000.0, + solref=(0.02, 1.0), + solimp=(0.9, 0.95, 0.001), + friction=None, + make_half=False, + ): + + # Set object attributes + self._name = name + self.rgba = rgba + self.density = density + self.friction = friction if friction is None else np.array(friction) + self.solref = solref + self.solimp = solimp + self.make_half = make_half # if True, will only make half the hollow cylinder + + self.has_material = material is not None + if self.has_material: + assert isinstance(material, CustomMaterial) + self.material = material + + # Other private attributes + self._important_sites = {} + + # radius of the inner cup hole and entire cup + self.r1 = inner_radius + self.r2 = outer_radius + + # number of geoms used to approximate the cylindrical shell + self.n = ngeoms + + # cylinder half-height + self.height = height + + # half-width of each box inferred from triangle of radius + box half-length + # since the angle will be (360 / n) / 2 + self.unit_box_width = self.r2 * np.sin(np.pi / self.n) + + # half-height of each box inferred from the same triangle with inner radius + self.unit_box_height = (self.r2 - self.r1) * np.cos(np.pi / self.n) / 2.0 + + # each box geom depth will end up defining the height of the cup + self.unit_box_depth = self.height + + # radius of intermediate circle that connects all box centers + self.int_r = (self.r1 * np.cos(np.pi / self.n)) + self.unit_box_height + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Optionally add material + if self.has_material: + self.append_material(self.material) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": [self.r2, self.r2, self.height], + "name": self.name, + "locations_relative_to_center": True, + "obj_types": "all", + "density": self.density, + "solref": self.solref, + "solimp": self.solimp, + } + obj_args = {} + + n_make = self.n + if self.make_half: + # only make half the shell + n_make = (self.n // 2) + 1 + + # infer locations of all geoms with trigonometry + angle_step = 2.0 * np.pi / self.n + for i in range(n_make): + # we start with the top-most box object and proceed clockwise (thus an offset of np.pi) + geom_angle = np.pi - i * angle_step + geom_center = np.array([self.int_r * np.cos(geom_angle), self.int_r * np.sin(geom_angle), 0.0]) + geom_quat = np.array([np.cos(geom_angle / 2.0), 0.0, 0.0, np.sin(geom_angle / 2.0)]) + geom_size = np.array([self.unit_box_height, self.unit_box_width, self.unit_box_depth]) + + # note: set geom condim to 4 for consistency with round-nut.xml + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=tuple(geom_center), + geom_quats=tuple(geom_quat), + geom_sizes=tuple(geom_size), + geom_names="hc_{}".format(i), + # geom_rgbas=None if self.has_material else self.rgba, + geom_rgbas=self.rgba, + geom_materials=self.material.mat_attrib["name"] if self.has_material else None, + geom_frictions=self.friction, + geom_condims=4, + ) + + # Sites + obj_args["sites"] = [ + { + "name": "center", + "pos": (0, 0, 0), + "size": "0.002", + "rgba": RED, + "type": "sphere", + } + ] + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args diff --git a/third_party/robosuite/robosuite/models/objects/composite/hook_frame.py b/third_party/robosuite/robosuite/models/objects/composite/hook_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..3741c7b74dac78a1963da1c2c01d7023fc9c85d5 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/composite/hook_frame.py @@ -0,0 +1,332 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import BLUE, GREEN, RED, CustomMaterial, add_to_dict + + +class HookFrame(CompositeObject): + """ + Generates an upside down L-shaped frame (a "hook" shape), intended to be used with StandWithMount object. + Args: + name (str): Name of this object + frame_length (float): How long the frame is + frame_height (float): How tall the frame is + frame_thickness (float): How thick the frame is + hook_height (float): if not None, add a box geom at the edge of the hook with this height (not half-height) + grip_location (float): if not None, adds a grip to passed location, relative to center of the rod corresponding to @frame_height. + grip_size ([float]): (R, H) radius and half-height for the cylindrical grip. Set to None + to not add a grip. + tip_size ([float]): if not None, adds a cone tip to the end of the hook for easier insertion, with the + provided (CH, LR, UR, H) where CH is the base cylinder height, LR and UR are the lower and upper radius + of the cone tip, and H is the half-height of the cone tip + friction (3-array or None): If specified, sets friction values for this object. None results in default values + density (float): Density value to use for all geoms. Defaults to 1000 + use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored + rgba (4-array or None): If specified, sets rgba values for all geoms. None results in default values + """ + + def __init__( + self, + name, + frame_length=0.3, + frame_height=0.2, + frame_thickness=0.025, + hook_height=None, + grip_location=None, + grip_size=None, + tip_size=None, + friction=None, + density=1000.0, + solref=(0.02, 1.0), + solimp=(0.9, 0.95, 0.001), + use_texture=True, + rgba=(0.2, 0.1, 0.0, 1.0), + ): + # Set name + self._name = name + + # Set object attributes + self.size = None # Filled in automatically + self.frame_length = frame_length + self.frame_height = frame_height + self.frame_thickness = frame_thickness + self.hook_height = hook_height + self.grip_location = grip_location + self.grip_size = tuple(grip_size) if grip_size is not None else None + self.tip_size = tuple(tip_size) if tip_size is not None else None + self.friction = friction if friction is None else np.array(friction) + self.solref = solref + self.solimp = solimp + self.density = density + self.use_texture = use_texture + self.rgba = rgba + self.mat_name = "brass_mat" + self.grip_mat_name = "ceramic_mat" + self.tip_mat_name = "steel_mat" + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "3 3", + "specular": "0.4", + "shininess": "0.1", + } + bin_mat = CustomMaterial( + texture="Brass", + tex_name="brass", + mat_name=self.mat_name, + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(bin_mat) + # optionally add material for grip + if (self.grip_location is not None) and (self.grip_size is not None): + grip_mat = CustomMaterial( + texture="Ceramic", + tex_name="ceramic", + mat_name=self.grip_mat_name, + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(grip_mat) + # optionally add material for tip + if self.tip_size is not None: + tip_mat = CustomMaterial( + texture="SteelScratched", + tex_name="steel", + mat_name=self.tip_mat_name, + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(tip_mat) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + self.size = np.array((self.frame_length, self.frame_thickness, self.frame_height)) + if self.tip_size is not None: + self.size[2] += 2.0 * (self.tip_size[0] + (2.0 * self.tip_size[3])) + base_args = { + "total_size": self.size / 2, + "name": self.name, + "locations_relative_to_center": True, + "obj_types": "all", + "density": self.density, + "solref": self.solref, + "solimp": self.solimp, + } + obj_args = {} + + # Vertical Frame + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=((self.frame_length - self.frame_thickness) / 2, 0, -self.frame_thickness / 2), + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array((self.frame_thickness, self.frame_thickness, self.frame_height - self.frame_thickness)) + / 2, + geom_names="vertical_frame", + geom_rgbas=None if self.use_texture else self.rgba, + geom_materials=self.mat_name if self.use_texture else None, + geom_frictions=self.friction, + ) + + # Horizontal Frame + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(0, 0, (self.frame_height - self.frame_thickness) / 2), + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array((self.frame_length, self.frame_thickness, self.frame_thickness)) / 2, + geom_names="horizontal_frame", + geom_rgbas=None if self.use_texture else self.rgba, + geom_materials=self.mat_name if self.use_texture else None, + geom_frictions=self.friction, + ) + + # optionally add hook at the end of the horizontal frame + if self.hook_height is not None: + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=( + (-self.frame_length + self.frame_thickness) / 2, + 0, + (self.frame_height + self.hook_height) / 2, + ), + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array((self.frame_thickness, self.frame_thickness, self.hook_height)) / 2, + geom_names="hook_frame", + geom_rgbas=None if self.use_texture else self.rgba, + geom_materials=self.mat_name if self.use_texture else None, + geom_frictions=self.friction, + ) + + # optionally add a grip + if (self.grip_location is not None) and (self.grip_size is not None): + # note: use box grip instead of cylindrical grip for stability + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=( + (self.frame_length - self.frame_thickness) / 2, + 0, + (-self.frame_thickness / 2) + self.grip_location, + ), + geom_quats=(1, 0, 0, 0), + geom_sizes=(self.grip_size[0], self.grip_size[0], self.grip_size[1]), + geom_names="grip_frame", + # geom_rgbas=None if self.use_texture else self.rgba, + geom_rgbas=(0.13, 0.13, 0.13, 1.0), + geom_materials=self.grip_mat_name if self.use_texture else None, + # geom_frictions=self.friction, + geom_frictions=(1.0, 0.005, 0.0001), # use default friction + ) + + # optionally add cone tip + if self.tip_size is not None: + from robosuite.models.objects import ConeObject + + cone = ConeObject( + name="cone", + outer_radius=self.tip_size[2], + inner_radius=self.tip_size[1], + height=self.tip_size[3], + # ngeoms=8, + ngeoms=50, + use_box=True, + # use_box=False, + rgba=None, + material=None, + density=self.density, + solref=self.solref, + solimp=self.solimp, + friction=self.friction, + ) + cone_args = cone._get_geom_attrs() + + # DIRTY HACK: add them in reverse (in hindsight, should just turn this into a composite body...) + cone_geom_types = cone_args["geom_types"] + cone_geom_locations = cone_args["geom_locations"] + cone_geom_sizes = cone_args["geom_sizes"][::-1] + + # location of mount site is the translation we need + cylinder_offset = ( + (self.frame_length - self.frame_thickness) / 2, + 0, + -self.frame_height / 2 - self.tip_size[0], # account for half-height of cylinder + ) + cone_offset = ( + cylinder_offset[0], + cylinder_offset[1], + cylinder_offset[2] + - self.tip_size[0] + - self.tip_size[3] / 2.0, # need to move below cylinder, and account for half-height + ) + + # first add cylinder + add_to_dict( + dic=obj_args, + geom_types="cylinder", + geom_locations=cylinder_offset, + geom_quats=(1, 0, 0, 0), + geom_sizes=(self.tip_size[2], self.tip_size[0]), + geom_names="tip_cylinder", + geom_rgbas=None if self.use_texture else self.rgba, + geom_materials=self.tip_mat_name if self.use_texture else None, + geom_frictions=self.friction, + ) + + # then add cone tip geoms + for i in range(len(cone_geom_types)): + add_to_dict( + dic=obj_args, + geom_types=cone_geom_types[i], + geom_locations=( + cone_geom_locations[i][0] + cone_offset[0], + cone_geom_locations[i][1] + cone_offset[1], + cone_geom_locations[i][2] + cone_offset[2], + ), + geom_quats=(1, 0, 0, 0), + geom_sizes=cone_geom_sizes[i], + geom_names="tip_cone_{}".format(i), + geom_rgbas=None if self.use_texture else self.rgba, + geom_materials=self.tip_mat_name if self.use_texture else None, + geom_frictions=self.friction, + ) + + # Sites + obj_args["sites"] = [ + { + "name": f"hang_site", + "pos": (-self.frame_length / 2, 0, (self.frame_height - self.frame_thickness) / 2), + "size": "0.002", + "rgba": RED, + "type": "sphere", + }, + { + "name": f"mount_site", + "pos": ((self.frame_length - self.frame_thickness) / 2, 0, -self.frame_height / 2), + "size": "0.002", + "rgba": GREEN, + "type": "sphere", + }, + { + "name": f"intersection_site", + "pos": ( + (self.frame_length - self.frame_thickness) / 2, + 0, + (self.frame_height - self.frame_thickness) / 2, + ), + "size": "0.002", + "rgba": BLUE, + "type": "sphere", + }, + ] + + if self.tip_size is not None: + obj_args["sites"].append( + { + "name": f"tip_site", + "pos": ( + ((self.frame_length - self.frame_thickness) / 2), + 0, + (-self.frame_height / 2) - 2.0 * self.tip_size[0] - self.tip_size[3], + ), + "size": "0.002", + "rgba": RED, + "type": "sphere", + }, + ) + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args + + @property + def init_quat(self): + """ + Rotate the frame on its side so it is flat + Returns: + np.array: (x, y, z, w) quaternion orientation for this object + """ + # Rotate 90 degrees about two consecutive axes to make the hook lie on the table instead of being upright. + return T.quat_multiply( + np.array([0, 0.0, np.sqrt(2) / 2.0, np.sqrt(2) / 2.0]), + np.array([-np.sqrt(2) / 2.0, 0.0, 0.0, np.sqrt(2) / 2.0]), + ) diff --git a/third_party/robosuite/robosuite/models/objects/composite/lid.py b/third_party/robosuite/robosuite/models/objects/composite/lid.py new file mode 100644 index 0000000000000000000000000000000000000000..3eb602bd9308bbe387e4648939d61c00c32f5520 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/composite/lid.py @@ -0,0 +1,136 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import CustomMaterial, add_to_dict + + +class Lid(CompositeObject): + """ + Generates a square lid with a simple handle. + Args: + name (str): Name of this Lid object + lid_size (3-array): (length, width, thickness) of lid + handle_size (3-array): (thickness, length, height) of handle + transparent (bool): If True, lid will be semi-translucent + friction (3-array or None): If specified, sets friction values for this lid. None results in default values + density (float): Density value to use for all geoms. Defaults to 1000 + use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored + rgba (4-array or None): If specified, sets rgba values for all geoms. None results in default values + """ + + def __init__( + self, + name, + lid_size=(0.3, 0.3, 0.01), + handle_size=(0.02, 0.08, 0.03), + transparent=True, + friction=None, + density=250.0, + use_texture=True, + rgba=(0.2, 0.1, 0.0, 1.0), + ): + # Set name + self._name = name + + # Set object attributes + self.lid_size = np.array(lid_size) + self.handle_size = np.array(handle_size) + self.transparent = transparent + self.friction = friction if friction is None else np.array(friction) + self.density = density + self.use_texture = use_texture + self.rgba = rgba + self.lid_mat_name = "dark_wood_mat" + + # Element references + self._handle_geom = "handle" + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "3 3", + "specular": "0.4", + "shininess": "0.1", + } + lid_mat = CustomMaterial( + texture="WoodDark", + tex_name="dark_wood", + mat_name=self.lid_mat_name, + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(lid_mat) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + full_height = self.lid_size[2] + self.handle_size[2] + full_size = np.array([self.lid_size[0], self.lid_size[1], full_height]) + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": full_size / 2.0, + "name": self.name, + "locations_relative_to_center": True, + "obj_types": "all", + } + obj_args = {} + + # Top + if self.transparent: + top_rgba = (1.0, 1.0, 1.0, 0.3) + top_mat = None + else: + top_rgba = None if self.use_texture else self.rgba + top_mat = self.lid_mat_name if self.use_texture else None + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(0, 0, (-full_size[2] + self.lid_size[2]) / 2), + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array((full_size[0], full_size[1], self.lid_size[2])) / 2, + geom_names="top", + geom_rgbas=top_rgba, + geom_materials=top_mat, + geom_frictions=self.friction, + density=self.density, + ) + + # Handle + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(0, 0, (full_size[2] - self.handle_size[2]) / 2), + geom_quats=(1, 0, 0, 0), + geom_sizes=self.handle_size / 2, + geom_names=self._handle_geom, + geom_rgbas=None if self.use_texture else self.rgba, + geom_materials=self.lid_mat_name if self.use_texture else None, + geom_frictions=self.friction, + density=self.density * 2, + ) + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args + + @property + def handle_geoms(self): + """ + Returns: + list of str: geom names corresponding to lid handle + """ + return [self.correct_naming(self._handle_geom)] diff --git a/third_party/robosuite/robosuite/models/objects/composite/pot_with_handles.py b/third_party/robosuite/robosuite/models/objects/composite/pot_with_handles.py new file mode 100644 index 0000000000000000000000000000000000000000..157c1624771fcd15437d6f8c06eab9cefbce7422 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/composite/pot_with_handles.py @@ -0,0 +1,350 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import BLUE, GREEN, RED, CustomMaterial, add_to_dict, array_to_string + + +class PotWithHandlesObject(CompositeObject): + """ + Generates the Pot object with side handles (used in TwoArmLift) + + Args: + name (str): Name of this Pot object + + body_half_size (3-array of float): If specified, defines the (x,y,z) half-dimensions of the main pot + body. Otherwise, defaults to [0.07, 0.07, 0.07] + + handle_radius (float): Determines the pot handle radius + + handle_length (float): Determines the pot handle length + + handle_width (float): Determines the pot handle width + + handle_friction (float): Friction value to use for pot handles. Defauls to 1.0 + + density (float): Density value to use for all geoms. Defaults to 1000 + + use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored + + rgba_body (4-array or None): If specified, sets pot body rgba values + + rgba_handle_0 (4-array or None): If specified, sets handle 0 rgba values + + rgba_handle_1 (4-array or None): If specified, sets handle 1 rgba values + + solid_handle (bool): If true, uses a single geom to represent the handle + + thickness (float): How thick to make the pot body walls + """ + + def __init__( + self, + name, + body_half_size=(0.07, 0.07, 0.07), + handle_radius=0.01, + handle_length=0.09, + handle_width=0.09, + handle_friction=1.0, + density=1000, + use_texture=True, + rgba_body=None, + rgba_handle_0=None, + rgba_handle_1=None, + solid_handle=False, + thickness=0.01, # For body + ): + # Set name + self._name = name + + # Set object attributes + self.body_half_size = np.array(body_half_size) + self.thickness = thickness + self.handle_radius = handle_radius + self.handle_length = handle_length + self.handle_width = handle_width + self.handle_friction = handle_friction + self.density = density + self.use_texture = use_texture + self.rgba_body = np.array(rgba_body) if rgba_body else RED + self.rgba_handle_0 = np.array(rgba_handle_0) if rgba_handle_0 else GREEN + self.rgba_handle_1 = np.array(rgba_handle_1) if rgba_handle_1 else BLUE + self.solid_handle = solid_handle + + # Element references to be filled when generated + self._handle0_geoms = None + self._handle1_geoms = None + self.pot_base = None + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "1 1", + "specular": "0.4", + "shininess": "0.1", + } + redwood = CustomMaterial( + texture="WoodRed", + tex_name="redwood", + mat_name="pot_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + greenwood = CustomMaterial( + texture="WoodGreen", + tex_name="greenwood", + mat_name="handle0_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + bluewood = CustomMaterial( + texture="WoodBlue", + tex_name="bluewood", + mat_name="handle1_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(redwood) + self.append_material(greenwood) + self.append_material(bluewood) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + full_size = np.array( + ( + self.body_half_size, + self.body_half_size + self.handle_length * 2, + self.body_half_size, + ) + ) + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": full_size / 2.0, + "name": self.name, + "locations_relative_to_center": True, + "obj_types": "all", + } + site_attrs = [] + obj_args = {} + + # Initialize geom lists + self._handle0_geoms = [] + self._handle1_geoms = [] + + # Add main pot body + # Base geom + name = f"base" + self.pot_base = [name] + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(0, 0, -self.body_half_size[2] + self.thickness / 2), + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array([self.body_half_size[0], self.body_half_size[1], self.thickness / 2]), + geom_names=name, + geom_rgbas=None if self.use_texture else self.rgba_body, + geom_materials="pot_mat" if self.use_texture else None, + geom_frictions=None, + density=self.density, + ) + + # Walls + x_off = np.array( + [0, -(self.body_half_size[0] - self.thickness / 2), 0, self.body_half_size[0] - self.thickness / 2] + ) + y_off = np.array( + [-(self.body_half_size[1] - self.thickness / 2), 0, self.body_half_size[1] - self.thickness / 2, 0] + ) + w_vals = np.array( + [self.body_half_size[0], self.body_half_size[1], self.body_half_size[0], self.body_half_size[1]] + ) + r_vals = np.array([np.pi / 2, 0, -np.pi / 2, np.pi]) + for i, (x, y, w, r) in enumerate(zip(x_off, y_off, w_vals, r_vals)): + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(x, y, 0), + geom_quats=T.convert_quat(T.axisangle2quat(np.array([0, 0, r])), to="wxyz"), + geom_sizes=np.array([self.thickness / 2, w, self.body_half_size[2]]), + geom_names=f"body{i}", + geom_rgbas=None if self.use_texture else self.rgba_body, + geom_materials="pot_mat" if self.use_texture else None, + geom_frictions=None, + density=self.density, + ) + + # Add handles + main_bar_size = np.array( + [ + self.handle_width / 2 + self.handle_radius, + self.handle_radius, + self.handle_radius, + ] + ) + side_bar_size = np.array([self.handle_radius, self.handle_length / 2, self.handle_radius]) + handle_z = self.body_half_size[2] - self.handle_radius + for i, (g_list, handle_side, rgba) in enumerate( + zip([self._handle0_geoms, self._handle1_geoms], [1.0, -1.0], [self.rgba_handle_0, self.rgba_handle_1]) + ): + handle_center = np.array((0, handle_side * (self.body_half_size[1] + self.handle_length), handle_z)) + # Solid handle case + if self.solid_handle: + name = f"handle{i}" + g_list.append(name) + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=handle_center, + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array([self.handle_width / 2, self.handle_length / 2, self.handle_radius]), + geom_names=name, + geom_rgbas=None if self.use_texture else rgba, + geom_materials=f"handle{i}_mat" if self.use_texture else None, + geom_frictions=(self.handle_friction, 0.005, 0.0001), + density=self.density, + ) + # Hollow handle case + else: + # Center bar + name = f"handle{i}_c" + g_list.append(name) + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=handle_center, + geom_quats=(1, 0, 0, 0), + geom_sizes=main_bar_size, + geom_names=name, + geom_rgbas=None if self.use_texture else rgba, + geom_materials=f"handle{i}_mat" if self.use_texture else None, + geom_frictions=(self.handle_friction, 0.005, 0.0001), + density=self.density, + ) + # Side bars + for bar_side, suffix in zip([-1.0, 1.0], ["-", "+"]): + name = f"handle{i}_{suffix}" + g_list.append(name) + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=( + bar_side * self.handle_width / 2, + handle_side * (self.body_half_size[1] + self.handle_length / 2), + handle_z, + ), + geom_quats=(1, 0, 0, 0), + geom_sizes=side_bar_size, + geom_names=name, + geom_rgbas=None if self.use_texture else rgba, + geom_materials=f"handle{i}_mat" if self.use_texture else None, + geom_frictions=(self.handle_friction, 0.005, 0.0001), + density=self.density, + ) + # Add relevant site + handle_site = self.get_site_attrib_template() + handle_name = f"handle{i}" + handle_site.update( + { + "name": handle_name, + "pos": array_to_string(handle_center - handle_side * np.array([0, 0.005, 0])), + "size": "0.005", + "rgba": rgba, + } + ) + site_attrs.append(handle_site) + # Add to important sites + self._important_sites[f"handle{i}"] = self.naming_prefix + handle_name + + # Add pot body site + pot_site = self.get_site_attrib_template() + center_name = "center" + pot_site.update( + { + "name": center_name, + "size": "0.005", + } + ) + site_attrs.append(pot_site) + # Add to important sites + self._important_sites["center"] = self.naming_prefix + center_name + + # Add back in base args and site args + obj_args.update(base_args) + obj_args["sites"] = site_attrs # All sites are part of main (top) body + + # Return this dict + return obj_args + + @property + def handle_distance(self): + + """ + Calculates how far apart the handles are + + Returns: + float: handle distance + """ + return self.body_half_size[1] * 2 + self.handle_length * 2 + + @property + def handle0_geoms(self): + """ + Returns: + list of str: geom names corresponding to handle0 (green handle) + """ + return self.correct_naming(self._handle0_geoms) + + @property + def handle1_geoms(self): + """ + Returns: + list of str: geom names corresponding to handle1 (blue handle) + """ + return self.correct_naming(self._handle1_geoms) + + @property + def handle_geoms(self): + """ + Returns: + list of str: geom names corresponding to both handles + """ + return self.handle0_geoms + self.handle1_geoms + + @property + def important_sites(self): + """ + Returns: + dict: In addition to any default sites for this object, also provides the following entries + + :`'handle0'`: Name of handle0 location site + :`'handle1'`: Name of handle1 location site + """ + # Get dict from super call and add to it + dic = super().important_sites + dic.update(self._important_sites) + return dic + + @property + def bottom_offset(self): + return np.array([0, 0, -1 * self.body_half_size[2]]) + + @property + def top_offset(self): + return np.array([0, 0, self.body_half_size[2]]) + + @property + def horizontal_radius(self): + return np.sqrt(2) * (max(self.body_half_size) + self.handle_length) diff --git a/third_party/robosuite/robosuite/models/objects/composite/stand_with_mount.py b/third_party/robosuite/robosuite/models/objects/composite/stand_with_mount.py new file mode 100644 index 0000000000000000000000000000000000000000..903c35a19a2443a58a51b9ce05f8af0b6ea8f8c8 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/composite/stand_with_mount.py @@ -0,0 +1,199 @@ +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.models.objects import CompositeObject +from robosuite.utils.mjcf_utils import RED, CustomMaterial, add_to_dict + + +class StandWithMount(CompositeObject): + """ + Generates a flat stand with a four-walled mount sticking out of the top. + Args: + name (str): Name of this object + size (3-array): (x,y,z) full size of object + mount_location (2-array): (x,y) location to place mount, relative to center of stand + mount_width (float): How wide mount is (measured from outside of walls!) + wall_thickness (float): How thick to make walls of mount + initialize_on_side (bool): If True, will initialize this stand on its side (tipped over) + add_hole_vis (bool): If True, adds a rim around the top of the walls, to help make the hole more visually distinctive + friction (3-array or None): If specified, sets friction values for this object. None results in default values + density (float): Density value to use for all geoms. Defaults to 1000 + use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored + rgba (4-array or None): If specified, sets rgba values for all geoms. None results in default values + """ + + def __init__( + self, + name, + size=(0.3, 0.3, 0.15), + mount_location=(0.0, 0.0), + mount_width=0.05, + wall_thickness=0.01, + base_thickness=0.01, + initialize_on_side=True, + add_hole_vis=False, + friction=None, + density=1000.0, + solref=(0.02, 1.0), + solimp=(0.9, 0.95, 0.001), + use_texture=True, + rgba=(0.2, 0.1, 0.0, 1.0), + ): + # Set name + self._name = name + + # Set object attributes + self.size = np.array(size) + self.mount_location = np.array(mount_location) + self.mount_width = mount_width + self.wall_thickness = wall_thickness + self.base_thickness = base_thickness + self.initialize_on_side = initialize_on_side + self.add_hole_vis = add_hole_vis + self.friction = friction if friction is None else np.array(friction) + self.solref = solref + self.solimp = solimp + self.density = density + self.use_texture = use_texture + self.rgba = rgba + self.mat_name = "brass_mat" + + # Element references + self._base_geom = "base" + + # Other private attributes + self._important_sites = {} + + # Create dictionary of values to create geoms for composite object and run super init + super().__init__(**self._get_geom_attrs()) + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "3 3", + "specular": "0.4", + "shininess": "0.1", + } + bin_mat = CustomMaterial( + texture="Brass", + tex_name="brass", + mat_name=self.mat_name, + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.append_material(bin_mat) + + def _get_geom_attrs(self): + """ + Creates geom elements that will be passed to superclass CompositeObject constructor + Returns: + dict: args to be used by CompositeObject to generate geoms + """ + # Initialize dict of obj args that we'll pass to the CompositeObject constructor + base_args = { + "total_size": self.size / 2.0, + "name": self.name, + "locations_relative_to_center": True, + "obj_types": "all", + "density": self.density, + "solref": self.solref, + "solimp": self.solimp, + } + obj_args = {} + + # Base + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(0, 0, -(self.size[2] - self.base_thickness) / 2), + geom_quats=(1, 0, 0, 0), + geom_sizes=np.array((self.size[0], self.size[1], self.base_thickness)) / 2, + geom_names=self._base_geom, + geom_rgbas=None if self.use_texture else self.rgba, + geom_materials=self.mat_name if self.use_texture else None, + geom_frictions=self.friction, + ) + + # Walls + x_vals = ( + np.array( + [0, -(self.mount_width - self.wall_thickness) / 2, 0, (self.mount_width - self.wall_thickness) / 2] + ) + + self.mount_location[0] + ) + y_vals = ( + np.array( + [-(self.mount_width - self.wall_thickness) / 2, 0, (self.mount_width - self.wall_thickness) / 2, 0] + ) + + self.mount_location[1] + ) + r_vals = np.array([np.pi / 2, 0, -np.pi / 2, np.pi]) + for i, (x, y, r) in enumerate(zip(x_vals, y_vals, r_vals)): + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(x, y, self.base_thickness / 2), + geom_quats=T.convert_quat(T.axisangle2quat(np.array([0, 0, r])), to="wxyz"), + geom_sizes=(self.wall_thickness / 2, self.mount_width / 2, (self.size[2] - self.base_thickness) / 2), + geom_names=f"wall{i}", + geom_rgbas=None if self.use_texture else self.rgba, + geom_materials=self.mat_name if self.use_texture else None, + geom_frictions=self.friction, + ) + + if self.add_hole_vis: + # add a purely visual rim + del base_args["obj_types"] + obj_args["obj_types"] = len(obj_args["geom_types"]) * ["all"] + + vis_geom_side = 0.7 * ((self.mount_width - self.wall_thickness) / 2) + vis_geom_size = (vis_geom_side, vis_geom_side, self.wall_thickness / 2) + add_to_dict( + dic=obj_args, + geom_types="box", + geom_locations=(self.mount_location[0], self.mount_location[1], (self.size[2] / 2) - vis_geom_size[2]), + geom_quats=(1, 0, 0, 0), + geom_sizes=vis_geom_size, + geom_names="hole_vis", + geom_rgbas=(0.0, 1.0, 0.0, 0.5), + geom_materials=None, + geom_frictions=self.friction, + obj_types="visual", + ) + + # Sites + obj_args["sites"] = [ + { + "name": f"mount_site", + "pos": (0, 0, self.size[2] / 2), + "size": "0.002", + "rgba": RED, + "type": "sphere", + } + ] + + # Add back in base args and site args + obj_args.update(base_args) + + # Return this dict + return obj_args + + @property + def init_quat(self): + """ + Optionally rotate the mount on its side so it is flat + Returns: + np.array: (x, y, z, w) quaternion orientation for this object + """ + # Rotate 90 deg about Y axis if at all + return np.array([0, 0.707107, 0, 0.707107]) if self.initialize_on_side else np.array([0, 0, 0, 1]) + + @property + def base_geoms(self): + """ + Returns: + list of str: geom names corresponding to base + """ + return [self.correct_naming(self._base_geom)] diff --git a/third_party/robosuite/robosuite/models/objects/composite_body/__init__.py b/third_party/robosuite/robosuite/models/objects/composite_body/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..79ccc9a8e74b24e77ac07a4045d2be68e8872167 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/composite_body/__init__.py @@ -0,0 +1,2 @@ +from .hinged_box import HingedBoxObject +from .ratcheting_wrench import RatchetingWrenchObject diff --git a/third_party/robosuite/robosuite/models/objects/composite_body/hinged_box.py b/third_party/robosuite/robosuite/models/objects/composite_body/hinged_box.py new file mode 100644 index 0000000000000000000000000000000000000000..12aa3cd0c62ab94df33033ea0bbcd88693876866 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/composite_body/hinged_box.py @@ -0,0 +1,141 @@ +import numpy as np + +from robosuite.models.objects import BoxObject, CompositeBodyObject, CylinderObject +from robosuite.utils.mjcf_utils import BLUE, RED, CustomMaterial, array_to_string + + +class HingedBoxObject(CompositeBodyObject): + """ + An example object that demonstrates the CompositeBodyObject functionality. This object consists of two cube bodies + joined together by a hinge joint. + + Args: + name (str): Name of this object + + box1_size (3-array): (L, W, H) half-sizes for the first box + + box2_size (3-array): (L, W, H) half-sizes for the second box + + use_texture (bool): set True if using wood textures for the blocks + """ + + def __init__( + self, + name, + box1_size=(0.025, 0.025, 0.025), + box2_size=(0.025, 0.025, 0.0125), + use_texture=True, + ): + # Set box sizes + self.box1_size = np.array(box1_size) + self.box2_size = np.array(box2_size) + + # Set texture attributes + self.use_texture = use_texture + self.box1_material = None + self.box2_material = None + self.box1_rgba = RED + self.box2_rgba = BLUE + + # Define materials we want to use for this object + if self.use_texture: + # Remove RGBAs + self.box1_rgba = None + self.box2_rgba = None + + # Set materials for each box + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "3 3", + "specular": "0.4", + "shininess": "0.1", + } + self.box1_material = CustomMaterial( + texture="WoodRed", + tex_name="box1_tex", + mat_name="box1_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + self.box2_material = CustomMaterial( + texture="WoodBlue", + tex_name="box2_tex", + mat_name="box2_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + + # Create objects + objects = [] + for i, (size, mat, rgba) in enumerate( + zip( + (self.box1_size, self.box2_size), + (self.box1_material, self.box2_material), + (self.box1_rgba, self.box2_rgba), + ) + ): + objects.append( + BoxObject( + name=f"box{i + 1}", + size=size, + rgba=rgba, + material=mat, + ) + ) + + # Also add hinge for visualization + objects.append( + CylinderObject( + name="hinge", + size=np.array( + [min(self.box1_size[2], self.box2_size[2]) / 5.0, min(self.box1_size[0], self.box2_size[0])] + ), + rgba=[0.5, 0.5, 0, 1], + obj_type="visual", + ) + ) + + # Define hinge joint + rel_hinge_pos = [self.box2_size[0], 0, -self.box2_size[2]] # want offset in all except y-axis + hinge_joint = { + "name": "box_hinge", + "type": "hinge", + "axis": "0 1 0", # y-axis hinge + "pos": array_to_string(rel_hinge_pos), + "stiffness": "0.0001", + "limited": "true", + "range": "0 1.57", + } + + # Define positions -- second box should lie on top of first box with edge aligned at hinge joint + # Hinge visualizer should be aligned at hinge joint location + positions = [ + np.zeros(3), # First box is centered at top-level body anyways + np.array([-(self.box2_size[0] - self.box1_size[0]), 0, self.box1_size[2] + self.box2_size[2]]), + np.array(rel_hinge_pos), + ] + + quats = [ + None, # Default quaternion for box 1 + None, # Default quaternion for box 2 + [0.707, 0.707, 0, 0], # Rotated 90 deg about x-axis + ] + + # Define parents -- which body each is aligned to + parents = [ + None, # box 1 attached to top-level body + objects[0].root_body, # box 2 attached to box 1 + objects[1].root_body, # hinge attached to box 2 + ] + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=positions, + object_quats=quats, + object_parents=parents, + body_joints={objects[1].root_body: [hinge_joint]}, + ) diff --git a/third_party/robosuite/robosuite/models/objects/composite_body/ratcheting_wrench.py b/third_party/robosuite/robosuite/models/objects/composite_body/ratcheting_wrench.py new file mode 100644 index 0000000000000000000000000000000000000000..6686541956d90f7fd06125332bbc342e6c7b5ac1 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/composite_body/ratcheting_wrench.py @@ -0,0 +1,150 @@ +import numpy as np + +from robosuite.models.objects import BoxObject, CompositeBodyObject, CylinderObject, HollowCylinderObject +from robosuite.utils.mjcf_utils import CustomMaterial + + +class RatchetingWrenchObject(CompositeBodyObject): + """ + A ratcheting wrench made out of mujoco primitives. + Args: + name (str): Name of this object + handle_size ([float]): (L, W, H) half-sizes for the handle (center part of wrench) + outer_radius_1 (float): Outer radius of first end of wrench + inner_radius_1 (float): Inner radius of first end of wrench + height_1 (float): Height of first end of wrench + outer_radius_2 (float): Outer radius of second end of wrench + inner_radius_2 (float): Inner radius of second end of wrench + height_2 (float): Height of second end of wrench + ngeoms (int): Number of box geoms used to approximate the ends of the wrench. Use + more geoms to make the approximation better. + grip_size ([float]): (R, H) radius and half-height for the box grip. Set to None + to not add a grip. + """ + + def __init__( + self, + name, + handle_size=(0.08, 0.01, 0.005), + outer_radius_1=0.0425, + inner_radius_1=0.03, + height_1=0.05, + outer_radius_2=0.0425, + inner_radius_2=0.03, + height_2=0.05, + ngeoms=8, + grip_size=None, + # rgba=None, + density=1000.0, + solref=(0.02, 1.0), + solimp=(0.9, 0.95, 0.001), + friction=None, + ): + # Object properties + self.handle_size = tuple(handle_size) + self.outer_radii = (outer_radius_1, outer_radius_2) + self.inner_radii = (inner_radius_1, inner_radius_2) + self.heights = (height_1, height_2) + self.ngeoms = ngeoms + self.grip_size = tuple(grip_size) if grip_size is not None else None + + # Define materials we want to use for this object + tex_attrib = { + "type": "cube", + } + mat_attrib = { + "texrepeat": "3 3", + "specular": "0.4", + "shininess": "0.1", + } + wrench_mat = CustomMaterial( + texture="SteelScratched", + tex_name="steel", + mat_name="steel_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + + if self.grip_size is not None: + grip_mat = CustomMaterial( + texture="Ceramic", + tex_name="ceramic", + mat_name="ceramic_mat", + tex_attrib=tex_attrib, + mat_attrib=mat_attrib, + ) + + # Create objects + objects = [] + + # each end of the wrench is modeled by a hollow cylinder + for i in range(2): + objects.append( + HollowCylinderObject( + name=f"hole{i + 1}", + outer_radius=self.outer_radii[i], + inner_radius=self.inner_radii[i], + height=self.heights[i], + ngeoms=self.ngeoms, + rgba=None, + material=wrench_mat, + density=density, + solref=solref, + solimp=solimp, + friction=friction, + make_half=False, + ) + ) + + # also add center box geom for handle + objects.append( + BoxObject( + name="handle", + size=handle_size, + rgba=None, + material=wrench_mat, + density=density, + solref=solref, + solimp=solimp, + friction=friction, + ) + ) + + # Define positions (top-level body is centered at handle) + hole_1_box_geom_height = 2.0 * objects[0].unit_box_height + hole_2_box_geom_height = 2.0 * objects[1].unit_box_height + positions = [ + # this computation ensures no gaps between the center bar geom and the two wrench holes at the end + np.array([-handle_size[0] - self.outer_radii[0] + hole_1_box_geom_height, 0, 0]), + np.array([handle_size[0] + self.outer_radii[1] - hole_2_box_geom_height, 0, 0]), + np.zeros(3), + ] + quats = [None, None, None] + parents = [None, None, None] + + # maybe add grip + if self.grip_size is not None: + objects.append( + BoxObject( + name="grip", + size=[self.grip_size[0], self.grip_size[0], self.grip_size[1]], + rgba=(0.13, 0.13, 0.13, 1.0), + density=density, + solref=solref, + solimp=solimp, + friction=(1.0, 0.005, 0.0001), # use default friction + ) + ) + positions.append(np.zeros(3)) + quats.append((np.sqrt(2) / 2.0, 0.0, np.sqrt(2) / 2.0, 0.0)) # rotate 90 degrees about y-axis + parents.append(None) + + # Run super init + super().__init__( + name=name, + objects=objects, + object_locations=positions, + object_quats=quats, + object_parents=parents, + joints=[dict(type="free", damping="0.0005")], # be consistent with round-nut.xml + ) diff --git a/third_party/robosuite/robosuite/models/objects/generated_objects.py b/third_party/robosuite/robosuite/models/objects/generated_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..770624b848099721f9d86ec8193e2cbd0c6e6ca2 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/generated_objects.py @@ -0,0 +1,785 @@ +from copy import deepcopy + +import numpy as np + +from robosuite.models.objects import MujocoGeneratedObject, MujocoObject +from robosuite.utils.mjcf_utils import ( + OBJECT_COLLISION_COLOR, + CustomMaterial, + add_prefix, + array_to_string, + find_elements, + new_body, + new_geom, + new_joint, + new_site, +) + + +class CompositeBodyObject(MujocoGeneratedObject): + """ + An object constructed out of multiple bodies to make more complex shapes. + + Args: + name (str): Name of overall object + + objects (MujocoObject or list of MujocoObjects): object(s) to combine to form the composite body object. + Note that these objects will be added sequentially, so if an object is required to be nested relative to + another object, that nested object should be listed after the parent object. Note that all top-level joints + for any inputted objects are automatically stripped + + object_locations (list): list of body locations in the composite. Each + location should be a list or tuple of 3 elements and all + locations are taken relative to that object's parent body. Giving None for a location results in (0,0,0) + for that object. + + object_quats (None or list): list of (w, x, y, z) quaternions for each body. None results in (1,0,0,0) for + that object. + + object_parents (None or list): Parent bodies to append each object to. Note that specifying "None" will + automatically append all objects to the root body ("root") + + joints (None or list): Joints to use for the top-level composite body object. If None, no joints will be used + for this top-level object. If "default", a single free joint will be added to the top-level body of this + object. Otherwise, should be a list of dictionaries, where each dictionary should specify the specific + joint attributes necessary. See http://www.mujoco.org/book/XMLreference.html#joint for reference. + + body_joints (None or dict): If specified, maps body names to joint specifications to append to that + body. If None, no extra joints will be used. If mapped value is "default", a single free joint will be + added to the specified body. Otherwise, should be a list of dictionaries, where each dictionary should + specify the specific joint attributes necessary. See http://www.mujoco.org/book/XMLreference.html#joint + for reference. + + sites (None or list): list of sites to add to top-level composite body object. If None, only the default + top-level object site will be used. Otherwise, should be a list of dictionaries, where each dictionary + should specify the appropriate attributes for the given site. + See http://www.mujoco.org/book/XMLreference.html#site for reference. + + total_size (None or np.array): if provided, use this to describe the bounding box for this composite body + object. Can also be used to specify @object_locations relative to the lower left corner of the bounding + box defined by @total_size, instead of the center of this body, with @locations_relative_to_corner. + + locations_relative_to_corner (bool): if True, must supply @total_size. All object locations will be + relative to the lower left corner of the bounding box. + """ + + def __init__( + self, + name, + objects, + object_locations, + object_quats=None, + object_parents=None, + joints="default", + body_joints=None, + sites=None, + total_size=None, + locations_relative_to_corner=False, + ): + # Always call superclass first + super().__init__() + + self._name = name + + # Set internal variable geometric properties which will be modified later + self._object_absolute_positions = {"root": np.zeros(3)} # maps body names to abs positions (rel to root) + self._top = 0 + self._bottom = 0 + self._horizontal = 0 + + # Standardize inputs + if isinstance(objects, MujocoObject): + self.objects = [objects] + elif type(objects) in {list, tuple}: + self.objects = list(objects) + else: + # Invalid objects received + raise ValueError("Invalid objects received, got type: {}".format(type(objects))) + + n_objects = len(self.objects) + self.object_locations = np.array(object_locations) + self.object_quats = deepcopy(object_quats) if object_quats is not None else [None] * n_objects + self.object_parents = deepcopy(object_parents) if object_parents is not None else ["root"] * n_objects + + # Set joints + if joints == "default": + self.joint_specs = [self.get_joint_attrib_template()] # default free joint + elif joints is None: + self.joint_specs = [] + else: + self.joint_specs = joints + + # Set body joints + if body_joints is None: + body_joints = {} + self.body_joint_specs = body_joints + + # Make sure all joints are named appropriately + j_num = 0 + for joint_spec in self.joint_specs: + if "name" not in joint_spec: + joint_spec["name"] = "joint{}".format(j_num) + j_num += 1 + + # Set sites + self.site_specs = deepcopy(sites) if sites is not None else [] + # Add default site + site_element_attr = self.get_site_attrib_template() + site_element_attr["rgba"] = "1 0 0 0" + site_element_attr["name"] = "default_site" + self.site_specs.append(site_element_attr) + + # Make sure all sites are named appropriately + s_num = 0 + for site_spec in self.site_specs: + if "name" not in site_spec: + site_spec["name"] = "site{}".format(s_num) + s_num += 1 + + self.total_size = np.array(total_size) if total_size is not None else None + self.locations_relative_to_corner = locations_relative_to_corner + if self.locations_relative_to_corner: + assert self.total_size is not None + + # Always run sanity check + self.sanity_check() + + # Lastly, parse XML tree appropriately + self._obj = self._get_object_subtree() + + # Extract the appropriate private attributes for this + self._get_object_properties() + + def _get_object_subtree(self): + # Initialize top-level body + obj = new_body(name="root") + + # Add all joints and sites + for joint_spec in self.joint_specs: + obj.append(new_joint(**joint_spec)) + for site_spec in self.site_specs: + obj.append(new_site(**site_spec)) + + # Loop through all objects and associated args and append them appropriately + for o, o_parent, o_pos, o_quat in zip( + self.objects, self.object_parents, self.object_locations, self.object_quats + ): + self._append_object(root=obj, obj=o, parent_name=o_parent, pos=o_pos, quat=o_quat) + + # Loop through all joints and append them appropriately + for body_name, joint_specs in self.body_joint_specs.items(): + self._append_joints(root=obj, body_name=body_name, joint_specs=joint_specs) + + # Return final object + return obj + + def _get_object_properties(self): + """ + Extends the superclass method to add prefixes to all assets + """ + super()._get_object_properties() + # Add prefix to all assets + add_prefix(root=self.asset, prefix=self.naming_prefix, exclude=self.exclude_from_prefixing) + + def _append_object(self, root, obj, parent_name=None, pos=None, quat=None): + """ + Helper function to add pre-generated object @obj to the body with name @parent_name + + Args: + root (ET.Element): Top-level element to iteratively search through for @parent_name to add @obj to + obj (MujocoObject): Object to append to the body specified by @parent_name + parent_name (None or str): Body name to search for in @root to append @obj to. + None defaults to "root" (top-level body) + pos (None or 3-array): (x,y,z) relative offset from parent body when appending @obj. + None defaults to (0,0,0) + quat (None or 4-array) (w,x,y,z) relative quaternion rotation from parent body when appending @obj. + None defaults to (1,0,0,0) + """ + # Set defaults if any are None + if parent_name is None: + parent_name = "root" + if pos is None: + pos = np.zeros(3) + if quat is None: + quat = np.array([1, 0, 0, 0]) + # First, find parent body + parent = find_elements(root=root, tags="body", attribs={"name": parent_name}, return_first=True) + assert parent is not None, "Could not find parent body with name: {}".format(parent_name) + # Get the object xml element tree, remove its top-level joints, and modify its top-level pos / quat + child = obj.get_obj() + self._remove_joints(child) + + if self.locations_relative_to_corner: + # use object location to convert to position coordinate (the origin is the + # center of the composite object) + cartesian_size = obj.get_bounding_box_half_size() + pos = [ + (-self.total_size[0] + cartesian_size[0]) + pos[0], + (-self.total_size[1] + cartesian_size[1]) + pos[1], + (-self.total_size[2] + cartesian_size[2]) + pos[2], + ] + + child.set("pos", array_to_string(pos)) + child.set("quat", array_to_string(quat)) + # Add this object and its assets to this composite object + self.merge_assets(other=obj) + parent.append(child) + # Update geometric properties for this composite object + obj_abs_pos = self._object_absolute_positions[parent_name] + np.array(pos) + self._object_absolute_positions[obj.root_body] = obj_abs_pos + self._top = max(self._top, obj_abs_pos[2] + obj.top_offset[2]) + self._bottom = min(self._bottom, obj_abs_pos[2] + obj.bottom_offset[2]) + self._horizontal = max(self._horizontal, max(obj_abs_pos[:2]) + obj.horizontal_radius) + + def _append_joints(self, root, body_name=None, joint_specs="default"): + """ + Appends all joints as specified by @joint_specs to @body. + + Args: + root (ET.Element): Top-level element to iteratively search through for @body_name + body_name (None or str): Name of the body to append the joints to. + None defaults to "root" (top-level body) + joint_specs (str or list): List of joint specifications to add to the specified body, or + "default", which results in a single free joint + """ + # Standardize inputs + if body_name is None: + body_name = "root" + if joint_specs == "default": + joint_specs = [self.get_joint_attrib_template()] + for i, joint_spec in enumerate(joint_specs): + if "name" not in joint_spec: + joint_spec["name"] = f"{body_name}_joint{i}" + # Search for body and make sure it exists + body = find_elements(root=root, tags="body", attribs={"name": body_name}, return_first=True) + assert body is not None, "Could not find body with name: {}".format(body_name) + # Add joint(s) to this body + for joint_spec in joint_specs: + body.append(new_joint(**joint_spec)) + + @staticmethod + def _remove_joints(body): + """ + Helper function to strip all joints directly appended to the specified @body. + + Args: + body (ET.Element): Body to strip joints from + """ + children_to_remove = [] + for child in body: + if child.tag == "joint": + children_to_remove.append(child) + for child in children_to_remove: + body.remove(child) + + @property + def bottom_offset(self): + return np.array([0.0, 0.0, self._bottom]) + + @property + def top_offset(self): + return np.array([0.0, 0.0, self._top]) + + @property + def horizontal_radius(self): + return self._horizontal + + def get_bounding_box_half_size(self): + if self.total_size is not None: + return np.array(self.total_size) + return super().get_bounding_box_half_size() + + +class CompositeObject(MujocoGeneratedObject): + """ + An object constructed out of basic geoms to make more intricate shapes. + + Note that by default, specifying None for a specific geom element will usually set a value to the mujoco defaults. + + Args: + name (str): Name of overall object + + total_size (list): (x, y, z) half-size in each dimension for the bounding box for + this Composite object + + geom_types (list): list of geom types in the composite. Must correspond + to MuJoCo geom primitives, such as "box" or "capsule". + + geom_locations (list): list of geom locations in the composite. Each + location should be a list or tuple of 3 elements and all + locations are relative to the lower left corner of the total box + (e.g. (0, 0, 0) corresponds to this corner). + + geom_sizes (list): list of geom sizes ordered the same as @geom_locations + + geom_quats (None or list): list of (w, x, y, z) quaternions for each geom. + + geom_names (None or list): list of geom names ordered the same as @geom_locations. The + names will get appended with an underscore to the passed name in @get_collision + and @get_visual + + geom_rgbas (None or list): list of geom colors ordered the same as @geom_locations. If + passed as an argument, @rgba is ignored. + + geom_materials (None or list of CustomTexture): list of custom textures to use for this object material + + geom_frictions (None or list): list of geom frictions to use for each geom. + + rgba (None or list): (r, g, b, a) default values to use if geom-specific @geom_rgbas isn't specified for a given element + + density (float or list of float): either single value to use for all geom densities or geom-specific values + + solref (list or list of list): parameters used for the mujoco contact solver. Can be single set of values or + element-specific values. See http://www.mujoco.org/book/modeling.html#CSolver for details. + + solimp (list or list of list): parameters used for the mujoco contact solver. Can be single set of values or + element-specific values. See http://www.mujoco.org/book/modeling.html#CSolver for details. + + locations_relative_to_center (bool): If true, @geom_locations will be considered relative to the center of the + overall object bounding box defined by @total_size. Else, the corner of this bounding box is considered the + origin. + + joints (None or list): Joints to use for this composite object. If None, no joints will be used + for this top-level object. If "default", a single free joint will be added to this object. + Otherwise, should be a list of dictionaries, where each dictionary should specify the specific + joint attributes necessary. See http://www.mujoco.org/book/XMLreference.html#joint for reference. + + sites (None or list): list of sites to add to this composite object. If None, only the default + object site will be used. Otherwise, should be a list of dictionaries, where each dictionary + should specify the appropriate attributes for the given site. + See http://www.mujoco.org/book/XMLreference.html#site for reference. + + obj_types (str or list of str): either single obj_type for all geoms or geom-specific type. Choices are + {"collision", "visual", "all"} + """ + + def __init__( + self, + name, + total_size, + geom_types, + geom_sizes, + geom_locations, + geom_quats=None, + geom_names=None, + geom_rgbas=None, + geom_materials=None, + geom_frictions=None, + geom_condims=None, + rgba=None, + density=100.0, + solref=(0.02, 1.0), + solimp=(0.9, 0.95, 0.001), + locations_relative_to_center=False, + joints="default", + sites=None, + obj_types="all", + duplicate_collision_geoms=True, + ): + # Always call superclass first + super().__init__(duplicate_collision_geoms=duplicate_collision_geoms) + + self._name = name + + # Set joints + if joints == "default": + self.joint_specs = [self.get_joint_attrib_template()] # default free joint + elif joints is None: + self.joint_specs = [] + else: + self.joint_specs = joints + + # Make sure all joints are named appropriately + j_num = 0 + for joint_spec in self.joint_specs: + if "name" not in joint_spec: + joint_spec["name"] = "joint{}".format(j_num) + j_num += 1 + + # Set sites + self.site_specs = deepcopy(sites) if sites is not None else [] + # Add default site + site_element_attr = self.get_site_attrib_template() + site_element_attr["rgba"] = "1 0 0 0" + site_element_attr["name"] = "default_site" + self.site_specs.append(site_element_attr) + + # Make sure all sites are named appropriately + s_num = 0 + for site_spec in self.site_specs: + if "name" not in site_spec: + site_spec["name"] = "site{}".format(s_num) + s_num += 1 + + n_geoms = len(geom_types) + self.total_size = np.array(total_size) + self.geom_types = np.array(geom_types) + self.geom_sizes = deepcopy(geom_sizes) + self.geom_locations = np.array(geom_locations) + self.geom_quats = deepcopy(geom_quats) if geom_quats is not None else [None] * n_geoms + self.geom_names = list(geom_names) if geom_names is not None else [None] * n_geoms + self.geom_rgbas = list(geom_rgbas) if geom_rgbas is not None else [None] * n_geoms + self.geom_materials = list(geom_materials) if geom_materials is not None else [None] * n_geoms + self.geom_frictions = list(geom_frictions) if geom_frictions is not None else [None] * n_geoms + self.geom_condims = list(geom_condims) if geom_condims is not None else [None] * n_geoms + self.density = [density] * n_geoms if density is None or type(density) in {float, int} else list(density) + self.solref = [solref] * n_geoms if solref is None or type(solref[0]) in {float, int} else list(solref) + self.solimp = [solimp] * n_geoms if obj_types is None or type(solimp[0]) in {float, int} else list(solimp) + self.rgba = rgba # override superclass setting of this variable + self.locations_relative_to_center = locations_relative_to_center + self.obj_types = [obj_types] * n_geoms if obj_types is None or type(obj_types) is str else list(obj_types) + + # Always run sanity check + self.sanity_check() + + # Lastly, parse XML tree appropriately + self._obj = self._get_object_subtree() + + # Extract the appropriate private attributes for this + self._get_object_properties() + + def get_bounding_box_half_size(self): + return np.array(self.total_size) + + def in_box(self, position, object_position): + """ + Checks whether the object is contained within this CompositeObject. + Useful for when the CompositeObject has holes and the object should + be within one of the holes. Makes an approximation by treating the + object as a point, and the CompositeBoxObject as an axis-aligned grid. + Args: + position: 3D body position of CompositeObject + object_position: 3D position of object to test for insertion + """ + ub = position + self.total_size + lb = position - self.total_size + + # fudge factor for the z-check, since after insertion the object falls to table + lb[2] -= 0.01 + + return np.all(object_position > lb) and np.all(object_position < ub) + + def _get_object_subtree(self): + # Initialize top-level body + obj = new_body(name="root") + + # Add all joints and sites + for joint_spec in self.joint_specs: + obj.append(new_joint(**joint_spec)) + for site_spec in self.site_specs: + obj.append(new_site(**site_spec)) + + # Loop through all geoms and generate the composite object + for i, ( + obj_type, + g_type, + g_size, + g_loc, + g_name, + g_rgba, + g_friction, + g_condim, + g_quat, + g_material, + g_density, + g_solref, + g_solimp, + ) in enumerate( + zip( + self.obj_types, + self.geom_types, + self.geom_sizes, + self.geom_locations, + self.geom_names, + self.geom_rgbas, + self.geom_frictions, + self.geom_condims, + self.geom_quats, + self.geom_materials, + self.density, + self.solref, + self.solimp, + ) + ): + # geom type + geom_type = g_type + # get cartesian size from size spec + size = g_size + cartesian_size = self._size_to_cartesian_half_lengths(geom_type, size) + if self.locations_relative_to_center: + # no need to convert + pos = g_loc + else: + # use geom location to convert to position coordinate (the origin is the + # center of the composite object) + pos = [ + (-self.total_size[0] + cartesian_size[0]) + g_loc[0], + (-self.total_size[1] + cartesian_size[1]) + g_loc[1], + (-self.total_size[2] + cartesian_size[2]) + g_loc[2], + ] + + # geom name + geom_name = g_name if g_name is not None else f"g{i}" + + # geom rgba + geom_rgba = g_rgba if g_rgba is not None else self.rgba + + # geom friction + geom_friction = ( + array_to_string(g_friction) + if g_friction is not None + else array_to_string(np.array([1.0, 0.005, 0.0001])) + ) # mujoco default + + # Define base geom attributes + geom_attr = { + "size": size, + "pos": pos, + "name": geom_name, + "type": geom_type, + } + + # Optionally define quat if specified + if g_quat is not None: + geom_attr["quat"] = array_to_string(g_quat) + + # Add collision geom if necessary + if obj_type in {"collision", "all"}: + col_geom_attr = deepcopy(geom_attr) + col_geom_attr.update(self.get_collision_attrib_template()) + if g_density is not None: + col_geom_attr["density"] = str(g_density) + col_geom_attr["friction"] = geom_friction + col_geom_attr["solref"] = array_to_string(g_solref) + col_geom_attr["solimp"] = array_to_string(g_solimp) + col_geom_attr["rgba"] = OBJECT_COLLISION_COLOR + if g_condim is not None: + col_geom_attr["condim"] = str(g_condim) + obj.append(new_geom(**col_geom_attr)) + + # Add visual geom if necessary + if obj_type in {"visual", "all"}: + vis_geom_attr = deepcopy(geom_attr) + vis_geom_attr.update(self.get_visual_attrib_template()) + vis_geom_attr["name"] += "_vis" + if g_material is not None: + vis_geom_attr["material"] = g_material + vis_geom_attr["rgba"] = geom_rgba + obj.append(new_geom(**vis_geom_attr)) + + return obj + + @staticmethod + def _size_to_cartesian_half_lengths(geom_type, geom_size): + """ + converts from geom size specification to x, y, and z half-length bounding box + """ + if geom_type in ["box", "ellipsoid"]: + return geom_size + if geom_type == "sphere": + # size is radius + return [geom_size[0], geom_size[0], geom_size[0]] + if geom_type == "capsule": + # size is radius, half-length of cylinder part + return [geom_size[0], geom_size[0], geom_size[0] + geom_size[1]] + if geom_type == "cylinder": + # size is radius, half-length + return [geom_size[0], geom_size[0], geom_size[1]] + raise Exception("unsupported geom type!") + + @property + def bottom_offset(self): + return np.array([0.0, 0.0, -self.total_size[2]]) + + @property + def top_offset(self): + return np.array([0.0, 0.0, self.total_size[2]]) + + @property + def horizontal_radius(self): + return np.linalg.norm(self.total_size[:2], 2) + + +class PrimitiveObject(MujocoGeneratedObject): + """ + Base class for all programmatically generated mujoco object + i.e., every MujocoObject that does not have an corresponding xml file + + Args: + name (str): (unique) name to identify this generated object + + size (n-tuple of float): relevant size parameters for the object, should be of size 1 - 3 + + rgba (4-tuple of float): Color + + density (float): Density + + friction (3-tuple of float): (sliding friction, torsional friction, and rolling friction). + A single float can also be specified, in order to set the sliding friction (the other values) will + be set to the MuJoCo default. See http://www.mujoco.org/book/modeling.html#geom for details. + + solref (2-tuple of float): MuJoCo solver parameters that handle contact. + See http://www.mujoco.org/book/XMLreference.html for more details. + + solimp (3-tuple of float): MuJoCo solver parameters that handle contact. + See http://www.mujoco.org/book/XMLreference.html for more details. + + material (CustomMaterial or `'default'` or None): if "default", add a template material and texture for this + object that is used to color the geom(s). + Otherwise, input is expected to be a CustomMaterial object + + See http://www.mujoco.org/book/XMLreference.html#asset for specific details on attributes expected for + Mujoco texture / material tags, respectively + + Note that specifying a custom texture in this way automatically overrides any rgba values set + + joints (None or str or list of dict): Joints for this object. If None, no joint will be created. If "default", + a single (free) joint will be crated. Else, should be a list of dict, where each dictionary corresponds to + a joint that will be created for this object. The dictionary should specify the joint attributes + (type, pos, etc.) according to the MuJoCo xml specification. + + obj_type (str): Geom elements to generate / extract for this object. Must be one of: + + :`'collision'`: Only collision geoms are returned (this corresponds to group 0 geoms) + :`'visual'`: Only visual geoms are returned (this corresponds to group 1 geoms) + :`'all'`: All geoms are returned + + duplicate_collision_geoms (bool): If set, will guarantee that each collision geom has a + visual geom copy + """ + + def __init__( + self, + name, + size=None, + rgba=None, + density=None, + friction=None, + solref=None, + solimp=None, + material=None, + joints="default", + obj_type="all", + duplicate_collision_geoms=True, + ): + # Always call superclass first + super().__init__(obj_type=obj_type, duplicate_collision_geoms=duplicate_collision_geoms) + + # Set name + self._name = name + + if size is None: + size = [0.05, 0.05, 0.05] + self.size = list(size) + + if rgba is None: + rgba = [1, 0, 0, 1] + assert len(rgba) == 4, "rgba must be a length 4 array" + self.rgba = list(rgba) + + if density is None: + density = 1000 # water + self.density = density + + if friction is None: + friction = [1, 0.005, 0.0001] # MuJoCo default + elif isinstance(friction, float) or isinstance(friction, int): + friction = [friction, 0.005, 0.0001] + assert len(friction) == 3, "friction must be a length 3 array or a single number" + self.friction = list(friction) + + if solref is None: + self.solref = [0.02, 1.0] # MuJoCo default + else: + self.solref = solref + + if solimp is None: + self.solimp = [0.9, 0.95, 0.001] # MuJoCo default + else: + self.solimp = solimp + + self.material = material + if material == "default": + # add in default texture and material for this object (for domain randomization) + default_tex = CustomMaterial( + texture=self.rgba, + tex_name="tex", + mat_name="mat", + ) + self.append_material(default_tex) + elif material is not None: + # add in custom texture and material + self.append_material(material) + + # joints for this object + if joints == "default": + self.joint_specs = [self.get_joint_attrib_template()] # default free joint + elif joints is None: + self.joint_specs = [] + else: + self.joint_specs = joints + + # Make sure all joints have names! + for i, joint_spec in enumerate(self.joint_specs): + if "name" not in joint_spec: + joint_spec["name"] = "joint{}".format(i) + + # Always run sanity check + self.sanity_check() + + # Lastly, parse XML tree appropriately + self._obj = self._get_object_subtree() + + # Extract the appropriate private attributes for this + self._get_object_properties() + + def _get_object_subtree_(self, ob_type="box"): + # Create element tree + obj = new_body(name="main") + + # Get base element attributes + element_attr = {"name": "g0", "type": ob_type, "size": array_to_string(self.size)} + + # Add collision geom if necessary + if self.obj_type in {"collision", "all"}: + col_element_attr = deepcopy(element_attr) + col_element_attr.update(self.get_collision_attrib_template()) + col_element_attr["density"] = str(self.density) + col_element_attr["friction"] = array_to_string(self.friction) + col_element_attr["solref"] = array_to_string(self.solref) + col_element_attr["solimp"] = array_to_string(self.solimp) + obj.append(new_geom(**col_element_attr)) + # Add visual geom if necessary + if self.obj_type in {"visual", "all"}: + vis_element_attr = deepcopy(element_attr) + vis_element_attr.update(self.get_visual_attrib_template()) + vis_element_attr["name"] += "_vis" + if self.material == "default": + vis_element_attr["rgba"] = "0.5 0.5 0.5 1" # mujoco default + vis_element_attr["material"] = "mat" + elif self.material is not None: + vis_element_attr["material"] = self.material.mat_attrib["name"] + else: + vis_element_attr["rgba"] = array_to_string(self.rgba) + obj.append(new_geom(**vis_element_attr)) + # add joint(s) + for joint_spec in self.joint_specs: + obj.append(new_joint(**joint_spec)) + # add a site as well + site_element_attr = self.get_site_attrib_template() + site_element_attr["name"] = "default_site" + obj.append(new_site(**site_element_attr)) + return obj + + # Methods that still need to be defined by subclass + def _get_object_subtree(self): + raise NotImplementedError + + def bottom_offset(self): + raise NotImplementedError + + def top_offset(self): + raise NotImplementedError + + def horizontal_radius(self): + raise NotImplementedError diff --git a/third_party/robosuite/robosuite/models/objects/group/__init__.py b/third_party/robosuite/robosuite/models/objects/group/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c6f000410cd83b63dd4c255d31c6722cfcd319de --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/group/__init__.py @@ -0,0 +1 @@ +from .transport import TransportGroup diff --git a/third_party/robosuite/robosuite/models/objects/group/transport.py b/third_party/robosuite/robosuite/models/objects/group/transport.py new file mode 100644 index 0000000000000000000000000000000000000000..58c3bd894dc6d67f41f5e0246f122d97614fa1d8 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/group/transport.py @@ -0,0 +1,174 @@ +import numpy as np + +import robosuite.utils.sim_utils as SU +import robosuite.utils.transform_utils as T +from robosuite.models.objects import Bin, Lid, ObjectGroup + + +class TransportGroup(ObjectGroup): + """ + Group of objects that capture transporting a payload placed in a start bin to a target bin, while + also requiring a piece of trash to be removed from the target bin + Args: + name (str): Name of that will the prepended to all geom bodies generated for this group + payload (MujocoObject): Object that represents payload + trash (MujocoObject): Object that represents trash + bin_size (3-tuple): (x,y,z) full size of bins to place on tables + """ + + def __init__(self, name, payload, trash, bin_size=(0.3, 0.3, 0.15)): + # Store and initialize internal variables + self.payload = payload + self.trash = trash + self.bin_size = bin_size + + # Create bins and lid + self.start_bin = Bin(name=f"{name}_start_bin", bin_size=bin_size, density=10000.0) + self.target_bin = Bin(name=f"{name}_target_bin", bin_size=bin_size, density=10000.0) + self.trash_bin = Bin(name=f"{name}_trash_bin", bin_size=bin_size, density=10000.0) + self.lid = Lid(name=f"{name}_start_bin_lid", lid_size=(*bin_size[:2], 0.01)) + + # Relevant geom ids + self.payload_geom_ids = None + self.trash_geom_ids = None + self.target_bin_base_geom_ids = None + self.trash_bin_base_geom_ids = None + self.lid_handle_geom_ids = None + self.payload_body_id = None + self.trash_body_id = None + + # Run super init + super().__init__(name=name) + + def get_states(self): + """ + Grabs all relevant information for this transport group. Returned dictionary maps keywords to corresponding + values pulled from the current sim state. + Returns: + dict: + "lid_handle_pose": list of (pos, quat) of lid handle + "payload_pose": list of (pos, quat) of hammer handle + "trash_pose": list of (pos, quat) of trash object + "target_bin_pos": position of target bin (base geom) + "trash_bin_pos": position of trash bin (base geom) + "trash_in_trash_bin": True if trash object is touching the base of the trash bin + "payload_in_target_bin": True if payload object is touching the base of the target bin + """ + return { + "lid_handle_pose": (self.lid_handle_pos, self.lid_handle_quat), + "payload_pose": (self.payload_pos, self.payload_quat), + "trash_pose": (self.trash_pos, self.trash_quat), + "target_bin_pos": self.target_bin_pos, + "trash_bin_pos": self.trash_bin_pos, + "trash_in_trash_bin": self.trash_in_trash_bin, + "payload_in_target_bin": self.payload_in_target_bin, + } + + def _generate_objects(self): + # Store all relevant objects in self._objects + self._objects = { + "payload": self.payload, + "trash": self.trash, + "start_bin": self.start_bin, + "target_bin": self.target_bin, + "trash_bin": self.trash_bin, + "lid": self.lid, + } + + def update_sim(self, sim): + """ + Updates internal reference to sim and all other references + Args: + sim (MjSim): Active mujoco sim reference + """ + # Always run super first + super().update_sim(sim=sim) + + # Update internal references to IDs + self.payload_geom_ids = [self.sim.model.geom_name2id(geom) for geom in self.payload.contact_geoms] + self.trash_geom_ids = [self.sim.model.geom_name2id(geom) for geom in self.trash.contact_geoms] + self.target_bin_base_geom_ids = [self.sim.model.geom_name2id(geom) for geom in self.target_bin.base_geoms] + self.trash_bin_base_geom_ids = [self.sim.model.geom_name2id(geom) for geom in self.trash_bin.base_geoms] + self.lid_handle_geom_ids = [self.sim.model.geom_name2id(geom) for geom in self.lid.handle_geoms] + self.payload_body_id = self.sim.model.body_name2id(self.payload.root_body) + self.trash_body_id = self.sim.model.body_name2id(self.trash.root_body) + + @property + def lid_handle_pos(self): + """ + Returns: + np.array: (x,y,z) absolute position of the lid handle + """ + return np.array(self.sim.data.geom_xpos[self.lid_handle_geom_ids[0]]) + + @property + def lid_handle_quat(self): + """ + Returns: + np.array: (x,y,z,w) quaternion of the lid handle + """ + return np.array(T.mat2quat(self.sim.data.geom_xmat[self.lid_handle_geom_ids[0]].reshape(3, 3))) + + @property + def payload_pos(self): + """ + Returns: + np.array: (x,y,z) absolute position of the payload + """ + return np.array(self.sim.data.body_xpos[self.payload_body_id]) + + @property + def payload_quat(self): + """ + Returns: + np.array: (x,y,z,w) quaternion of the payload + """ + return np.array(T.mat2quat(self.sim.data.body_xmat[self.payload_body_id].reshape(3, 3))) + + @property + def trash_pos(self): + """ + Returns: + np.array: (x,y,z) absolute position of the trash + """ + return np.array(self.sim.data.body_xpos[self.trash_body_id]) + + @property + def trash_quat(self): + """ + Returns: + np.array: (x,y,z,w) quaternion of the trash + """ + return np.array(T.mat2quat(self.sim.data.body_xmat[self.trash_body_id].reshape(3, 3))) + + @property + def target_bin_pos(self): + """ + Returns: + np.array: (x,y,z) absolute position of the target bin + """ + return np.array(self.sim.data.geom_xpos[self.target_bin_base_geom_ids[0]]) + + @property + def trash_bin_pos(self): + """ + Returns: + np.array: (x,y,z) absolute position of the trash bin + """ + return np.array(self.sim.data.geom_xpos[self.trash_bin_base_geom_ids[0]]) + + @property + def trash_in_trash_bin(self): + """ + Returns: + bool: True if trash is in trash bin + """ + return SU.check_contact(self.sim, self.trash_bin.base_geoms, self.trash.contact_geoms) + + @property + def payload_in_target_bin(self): + """ + Returns: + bool: True if payload is in target bin + """ + return SU.check_contact(self.sim, self.target_bin.base_geoms, self.payload.contact_geoms) diff --git a/third_party/robosuite/robosuite/models/objects/object_groups.py b/third_party/robosuite/robosuite/models/objects/object_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..eb1100920fbb4a49db4c30bef139870f215dac30 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/object_groups.py @@ -0,0 +1,46 @@ +class ObjectGroup: + """ + An abstraction that encompasses a group of objects that interact together in a meaningful way + name (str): Name of this object group. This will be prepended to all objects generated by this group. + """ + + def __init__(self, name): + # Store internal variables + self.name = name + self.sim = None # Reference to shared mjsim object + self._objects = {} # maps object names to object class instances + + # Generate objects + self._generate_objects() + + def get_states(self): + """ + Function to grab group-relevant states. This should be implemented by the subclass. + Returns: + dict: Keyword-mapped states for this group + """ + raise NotImplementedError + + def update_sim(self, sim): + """ + Updates internal reference to sim and all other relevant references + Args: + sim (MjSim): Active mujoco sim reference + """ + self.sim = sim + + def _generate_objects(self): + """ + Internal helper function that generates the objects for this group. Should populate self._objects mapping + names of objects to their actual object class instances. + """ + raise NotImplementedError + + @property + def objects(self): + """ + Contains references to all objects owned by this group. Mapped from names to object instances + Returns: + dict: keyword-mapped object class instances + """ + return self._objects diff --git a/third_party/robosuite/robosuite/models/objects/objects.py b/third_party/robosuite/robosuite/models/objects/objects.py new file mode 100644 index 0000000000000000000000000000000000000000..e7681f8f39a3cdf0c2403ed378f605fe560f6f9c --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/objects.py @@ -0,0 +1,776 @@ +import copy +import xml.etree.ElementTree as ET +from copy import deepcopy + +import numpy as np + +import robosuite.macros as macros +from robosuite.models.base import MujocoModel, MujocoXML +from robosuite.utils.mjcf_utils import ( + OBJECT_COLLISION_COLOR, + CustomMaterial, + add_material, + add_prefix, + array_to_string, + find_elements, + new_joint, + sort_elements, + string_to_array, +) + +# Dict mapping geom type string keywords to group number +GEOMTYPE2GROUP = { + "collision": {0}, # If we want to use a geom for physics, but NOT visualize + "visual": {1}, # If we want to use a geom for visualization, but NOT physics + "all": {0, 1}, # If we want to use a geom for BOTH physics + visualization +} + +GEOM_GROUPS = GEOMTYPE2GROUP.keys() + + +class MujocoObject(MujocoModel): + """ + Base class for all objects. + + We use Mujoco Objects to implement all objects that: + + 1) may appear for multiple times in a task + 2) can be swapped between different tasks + + Typical methods return copy so the caller can all joints/attributes as wanted + + Args: + obj_type (str): Geom elements to generate / extract for this object. Must be one of: + + :`'collision'`: Only collision geoms are returned (this corresponds to group 0 geoms) + :`'visual'`: Only visual geoms are returned (this corresponds to group 1 geoms) + :`'all'`: All geoms are returned + + duplicate_collision_geoms (bool): If set, will guarantee that each collision geom has a + visual geom copy + + """ + + def __init__(self, obj_type="all", duplicate_collision_geoms=True): + super().__init__() + self.asset = ET.Element("asset") + assert obj_type in GEOM_GROUPS, "object type must be one in {}, got: {} instead.".format(GEOM_GROUPS, obj_type) + self.obj_type = obj_type + self.duplicate_collision_geoms = duplicate_collision_geoms + + # Attributes that should be filled in within the subclass + self._name = None + self._obj = None + + # Attributes that are auto-filled by _get_object_properties call + self._root_body = None + self._bodies = None + self._joints = None + self._actuators = None + self._sites = None + self._contact_geoms = None + self._visual_geoms = None + + def merge_assets(self, other): + """ + Merges @other's assets in a custom logic. + + Args: + other (MujocoXML or MujocoObject): other xml file whose assets will be merged into this one + """ + for asset in other.asset: + if ( + find_elements(root=self.asset, tags=asset.tag, attribs={"name": asset.get("name")}, return_first=True) + is None + ): + self.asset.append(asset) + + def get_obj(self): + """ + Returns the generated / extracted object, in XML ElementTree form. + + Returns: + ET.Element: Object in XML form. + """ + assert self._obj is not None, "Object XML tree has not been generated yet!" + return self._obj + + def exclude_from_prefixing(self, inp): + """ + A function that should take in either an ET.Element or its attribute (str) and return either True or False, + determining whether the corresponding name / str to @inp should have naming_prefix added to it. + Must be defined by subclass. + + Args: + inp (ET.Element or str): Element or its attribute to check for prefixing. + + Returns: + bool: True if we should exclude the associated name(s) with @inp from being prefixed with naming_prefix + """ + raise NotImplementedError + + def _get_object_subtree(self): + + """ + Returns a ET.Element + It is a subtree that defines all collision and / or visualization related fields + of this object. + Return should be a copy. + Must be defined by subclass. + + Returns: + ET.Element: body + """ + raise NotImplementedError + + def _get_object_properties(self): + """ + Helper function to extract relevant object properties (bodies, joints, contact/visual geoms, etc...) from this + object's XML tree. Assumes the self._obj attribute has already been filled. + """ + # Parse element tree to get all relevant bodies, joints, actuators, and geom groups + _elements = sort_elements(root=self.get_obj()) + assert ( + len(_elements["root_body"]) == 1 + ), "Invalid number of root bodies found for robot model. Expected 1," "got {}".format( + len(_elements["root_body"]) + ) + _elements["root_body"] = _elements["root_body"][0] + _elements["bodies"] = ( + [_elements["root_body"]] + _elements["bodies"] if "bodies" in _elements else [_elements["root_body"]] + ) + self._root_body = _elements["root_body"].get("name") + self._bodies = [e.get("name") for e in _elements.get("bodies", [])] + self._joints = [e.get("name") for e in _elements.get("joints", [])] + self._actuators = [e.get("name") for e in _elements.get("actuators", [])] + self._sites = [e.get("name") for e in _elements.get("sites", [])] + self._sensors = [e.get("name") for e in _elements.get("sensors", [])] + self._contact_geoms = [e.get("name") for e in _elements.get("contact_geoms", [])] + self._visual_geoms = [e.get("name") for e in _elements.get("visual_geoms", [])] + + # Add default materials if we're using domain randomization + if macros.USING_INSTANCE_RANDOMIZATION: + tex_element, mat_element, _, used = add_material(root=self.get_obj(), naming_prefix=self.naming_prefix) + # Only add the material / texture if they were actually used + if used: + self.asset.append(tex_element) + self.asset.append(mat_element) + + # Add prefix to all elements + add_prefix(root=self.get_obj(), prefix=self.naming_prefix, exclude=self.exclude_from_prefixing) + + @property + def name(self): + return self._name + + @property + def naming_prefix(self): + return "{}_".format(self.name) + + @property + def root_body(self): + return self.correct_naming(self._root_body) + + @property + def bodies(self): + return self.correct_naming(self._bodies) + + @property + def joints(self): + return self.correct_naming(self._joints) + + @property + def actuators(self): + return self.correct_naming(self._actuators) + + @property + def sites(self): + return self.correct_naming(self._sites) + + @property + def sensors(self): + return self.correct_naming(self._sensors) + + @property + def contact_geoms(self): + return self.correct_naming(self._contact_geoms) + + @property + def visual_geoms(self): + return self.correct_naming(self._visual_geoms) + + @property + def important_geoms(self): + """ + Returns: + dict: (Default is no important geoms; i.e.: empty dict) + """ + return {} + + @property + def important_sites(self): + """ + Returns: + dict: + + :`obj`: Object default site + """ + return {"obj": self.naming_prefix + "default_site"} + + @property + def important_sensors(self): + """ + Returns: + dict: (Default is no sensors; i.e.: empty dict) + """ + return {} + + @property + def bottom_offset(self): + """ + Returns vector from model root body to model bottom. + Useful for, e.g. placing models on a surface. + Must be defined by subclass. + + Returns: + np.array: (dx, dy, dz) offset vector + """ + raise NotImplementedError + + @property + def top_offset(self): + """ + Returns vector from model root body to model top. + Useful for, e.g. placing models on a surface. + Must be defined by subclass. + + Returns: + np.array: (dx, dy, dz) offset vector + """ + raise NotImplementedError + + @property + def horizontal_radius(self): + """ + Returns maximum distance from model root body to any radial point of the model. + + Helps us put models programmatically without them flying away due to a huge initial contact force. + Must be defined by subclass. + + Returns: + float: radius + """ + raise NotImplementedError + + @staticmethod + def get_site_attrib_template(): + """ + Returns attribs of spherical site used to mark body origin + + Returns: + dict: Dictionary of default site attributes + """ + return { + "pos": "0 0 0", + "size": "0.002 0.002 0.002", + "rgba": "1 0 0 1", + "type": "sphere", + "group": "0", + } + + @staticmethod + def get_joint_attrib_template(): + """ + Returns attribs of free joint + + Returns: + dict: Dictionary of default joint attributes + """ + return { + "type": "free", + } + + def get_bounding_box_half_size(self): + raise NotImplementedError + + def get_bounding_box_size(self): + """ + Returns numpy array with dimensions of a bounding box around this object. + """ + return 2.0 * self.get_bounding_box_half_size() + + +class MujocoXMLObject(MujocoObject, MujocoXML): + """ + MujocoObjects that are loaded from xml files (by default, inherit all properties (e.g.: name) + from MujocoObject class first!) + + Args: + fname (str): XML File path + + name (str): Name of this MujocoXMLObject + + joints (None or str or list of dict): each dictionary corresponds to a joint that will be created for this + object. The dictionary should specify the joint attributes (type, pos, etc.) according to the MuJoCo xml + specification. If "default", a single free-joint will be automatically generated. If None, no joints will + be created. + + obj_type (str): Geom elements to generate / extract for this object. Must be one of: + + :`'collision'`: Only collision geoms are returned (this corresponds to group 0 geoms) + :`'visual'`: Only visual geoms are returned (this corresponds to group 1 geoms) + :`'all'`: All geoms are returned + + duplicate_collision_geoms (bool): If set, will guarantee that each collision geom has a + visual geom copy + + scale (float or list of floats): 3D scale factor + """ + + def __init__(self, fname, name, joints="default", obj_type="all", duplicate_collision_geoms=True, scale=None): + MujocoXML.__init__(self, fname) + # Set obj type and duplicate args + assert obj_type in GEOM_GROUPS, "object type must be one in {}, got: {} instead.".format(GEOM_GROUPS, obj_type) + self.obj_type = obj_type + self.duplicate_collision_geoms = duplicate_collision_geoms + + # Set name + self._name = name + + # set scale + self._scale = scale + + # joints for this object + if joints == "default": + self.joint_specs = [self.get_joint_attrib_template()] # default free joint + elif joints is None: + self.joint_specs = [] + else: + self.joint_specs = joints + + # Make sure all joints have names! + for i, joint_spec in enumerate(self.joint_specs): + if "name" not in joint_spec: + joint_spec["name"] = "joint{}".format(i) + + # Lastly, parse XML tree appropriately + self._obj = self._get_object_subtree() + + # scale + if self._scale is not None: + self.set_scale(self._scale) + + # Extract the appropriate private attributes for this + self._get_object_properties() + + def _get_object_subtree(self): + # Parse object + # this line used to be wrapped in deepcopy. + # removed this deepcopy line, as it creates discrepancies between obj and self.worldbody! + obj = self.worldbody.find("./body/body[@name='object']") + # Rename this top level object body (will have self.naming_prefix added later) + obj.attrib["name"] = "main" + # Get all geom_pairs in this tree + geom_pairs = self._get_geoms(obj) + + # Define a temp function so we don't duplicate so much code + obj_type = self.obj_type + + def _should_keep(el): + return int(el.get("group")) in GEOMTYPE2GROUP[obj_type] + + # Loop through each of these pairs and modify them according to @elements arg + for i, (parent, element) in enumerate(geom_pairs): + # Delete non-relevant geoms and rename remaining ones + if not _should_keep(element): + parent.remove(element) + else: + g_name = element.get("name") + g_name = g_name if g_name is not None else f"g{i}" + element.set("name", g_name) + # Also optionally duplicate collision geoms if requested (and this is a collision geom) + if self.duplicate_collision_geoms and element.get("group") in {None, "0"}: + parent.append(self._duplicate_visual_from_collision(element)) + # Also manually set the visual appearances to the original collision model + element.set("rgba", array_to_string(OBJECT_COLLISION_COLOR)) + if element.get("material") is not None: + del element.attrib["material"] + # add joint(s) + for joint_spec in self.joint_specs: + obj.append(new_joint(**joint_spec)) + # Lastly, add a site for this object + template = self.get_site_attrib_template() + template["rgba"] = "1 0 0 0" + template["name"] = "default_site" + obj.append(ET.Element("site", attrib=template)) + + return obj + + def exclude_from_prefixing(self, inp): + """ + By default, don't exclude any from being prefixed + """ + return False + + def _get_object_properties(self): + """ + Extends the base class method to also add prefixes to all bodies in this object + """ + super()._get_object_properties() + add_prefix(root=self.root, prefix=self.naming_prefix, exclude=self.exclude_from_prefixing) + + @staticmethod + def _duplicate_visual_from_collision(element): + """ + Helper function to duplicate a geom element to be a visual element. Namely, this corresponds to the + following attribute requirements: group=1, conaffinity/contype=0, no mass, name appended with "_visual" + + Args: + element (ET.Element): element to duplicate as a visual geom + + Returns: + element (ET.Element): duplicated element + """ + # Copy element + vis_element = deepcopy(element) + # Modify for visual-specific attributes (group=1, conaffinity/contype=0, no mass, update name) + vis_element.set("group", "1") + vis_element.set("conaffinity", "0") + vis_element.set("contype", "0") + vis_element.set("mass", "1e-8") + vis_element.set("name", vis_element.get("name") + "_visual") + return vis_element + + def _get_geoms(self, root, _parent=None): + """ + Helper function to recursively search through element tree starting at @root and returns + a list of (parent, child) tuples where the child is a geom element + + Args: + root (ET.Element): Root of xml element tree to start recursively searching through + _parent (ET.Element): Parent of the root element tree. Should not be used externally; only set + during the recursive call + + Returns: + list: array of (parent, child) tuples where the child element is a geom type + """ + return self._get_elements(root, "geom", _parent) + + def _get_elements(self, root, type, _parent=None): + """ + Helper function to recursively search through element tree starting at @root and returns + a list of (parent, child) tuples where the child is a specific type of element + + Args: + root (ET.Element): Root of xml element tree to start recursively searching through + _parent (ET.Element): Parent of the root element tree. Should not be used externally; only set + during the recursive call + + Returns: + list: array of (parent, child) tuples where the child element is of type + """ + # Initialize return array + elem_pairs = [] + # If the parent exists and this is a desired element, we add this current (parent, element) combo to the output + if _parent is not None and root.tag == type: + elem_pairs.append((_parent, root)) + # Loop through all children elements recursively and add to pairs + for child in root: + elem_pairs += self._get_elements(child, type, _parent=root) + + # Return all found pairs + return elem_pairs + + def set_pos(self, pos): + """ + Set position of object position is defined as center of bounding box + + Args: + pos (list of floats): 3D position to set object (should be 3 dims) + """ + self._obj.set("pos", array_to_string(pos)) + + def set_euler(self, euler): + """ + Set Euler value object position + + Args: + euler (list of floats): 3D Euler values (should be 3 dims) + """ + self._obj.set("euler", array_to_string(euler)) + + @property + def rot(self): + rot = string_to_array(self._obj.get("euler", "0.0 0.0 0.0")) + return rot[2] + + def set_scale(self, scale, obj=None): + """ + Scales each geom, mesh, site, and body. + Called during initialization but can also be used externally + + Args: + scale (float or list of floats): Scale factor (1 or 3 dims) + obj (ET.Element) Root object to apply. Defaults to root object of model + """ + if obj is None: + obj = self._obj + + self._scale = scale + + # scale geoms + geom_pairs = self._get_geoms(obj) + for _, (_, element) in enumerate(geom_pairs): + g_pos = element.get("pos") + g_size = element.get("size") + if g_pos is not None: + g_pos = array_to_string(string_to_array(g_pos) * self._scale) + element.set("pos", g_pos) + if g_size is not None: + g_size_np = string_to_array(g_size) + # handle cases where size is not 3 dimensional + if len(g_size_np) == 3: + g_size_np = g_size_np * self._scale + elif len(g_size_np) == 2: + scale = np.array(self._scale).reshape(-1) + if len(scale) == 1: + g_size_np[1] *= scale + elif len(scale) == 3: + # g_size_np[0] *= np.mean(scale[:2]) + g_size_np[0] *= np.mean(scale[:2]) # width + g_size_np[1] *= scale[2] # height + else: + raise ValueError + else: + raise ValueError + g_size = array_to_string(g_size_np) + element.set("size", g_size) + + # scale meshes + meshes = self.asset.findall("mesh") + for elem in meshes: + m_scale = elem.get("scale") + if m_scale is not None: + m_scale = string_to_array(m_scale) + else: + m_scale = np.ones(3) + + m_scale *= self._scale + elem.set("scale", array_to_string(m_scale)) + + # scale bodies + body_pairs = self._get_elements(obj, "body") + for (_, elem) in body_pairs: + b_pos = elem.get("pos") + if b_pos is not None: + b_pos = string_to_array(b_pos) * self._scale + elem.set("pos", array_to_string(b_pos)) + + # scale joints + joint_pairs = self._get_elements(obj, "joint") + for (_, elem) in joint_pairs: + j_pos = elem.get("pos") + if j_pos is not None: + j_pos = string_to_array(j_pos) * self._scale + elem.set("pos", array_to_string(j_pos)) + + # scale sites + site_pairs = self._get_elements(self.worldbody, "site") + for (_, elem) in site_pairs: + s_pos = elem.get("pos") + if s_pos is not None: + s_pos = string_to_array(s_pos) * self._scale + elem.set("pos", array_to_string(s_pos)) + + s_size = elem.get("size") + if s_size is not None: + s_size_np = string_to_array(s_size) + # handle cases where size is not 3 dimensional + if len(s_size_np) == 3: + s_size_np = s_size_np * self._scale + elif len(s_size_np) == 2: + scale = np.array(self._scale).reshape(-1) + if len(scale) == 1: + s_size_np *= scale + elif len(scale) == 3: + s_size_np[0] *= np.mean(scale[:2]) # width + s_size_np[1] *= scale[2] # height + else: + raise ValueError + elif len(s_size_np) == 1: + s_size_np *= np.mean(self._scale) + else: + raise ValueError + s_size = array_to_string(s_size_np) + elem.set("size", s_size) + + @property + def bottom_offset(self): + bottom_site = self.worldbody.find("./body/site[@name='{}bottom_site']".format(self.naming_prefix)) + return string_to_array(bottom_site.get("pos")) + + @property + def top_offset(self): + top_site = self.worldbody.find("./body/site[@name='{}top_site']".format(self.naming_prefix)) + return string_to_array(top_site.get("pos")) + + @property + def horizontal_radius(self): + horizontal_radius_site = self.worldbody.find( + "./body/site[@name='{}horizontal_radius_site']".format(self.naming_prefix) + ) + return string_to_array(horizontal_radius_site.get("pos"))[0] + + def get_bounding_box_half_size(self): + horizontal_radius_site = self.worldbody.find( + "./body/site[@name='{}horizontal_radius_site']".format(self.naming_prefix) + ) + return string_to_array(horizontal_radius_site.get("pos")) - self.bottom_offset + + def _get_elements_by_name(self, geom_names, body_names=None, joint_names=None): + """ + seaches for returns all geoms, bodies, and joints used for cabinet + called by _get_cab_components, as implemented in subclasses + + for geoms, include both collision and visual geoms + """ + + # names of every geom + geoms = {geom_name: list() for geom_name in geom_names} + for geom_name in geoms.keys(): + for postfix in ["", "_visual"]: + g = find_elements( + root=self._obj, + tags="geom", + attribs={"name": self.name + "_" + geom_name + postfix}, + return_first=True, + ) + geoms[geom_name].append(g) + + # get bodies + bodies = dict() + if body_names is not None: + for body_name in body_names: + bodies[body_name] = find_elements( + root=self._obj, tags="body", attribs={"name": self.name + "_" + body_name}, return_first=True + ) + + # get joints + joints = dict() + if joint_names is not None: + for joint_name in joint_names: + joints[joint_name] = find_elements( + root=self._obj, tags="joint", attribs={"name": self.name + "_" + joint_name}, return_first=True + ) + return geoms, bodies, joints + + +class MujocoGeneratedObject(MujocoObject): + """ + Base class for all procedurally generated objects. + + Args: + obj_type (str): Geom elements to generate / extract for this object. Must be one of: + + :`'collision'`: Only collision geoms are returned (this corresponds to group 0 geoms) + :`'visual'`: Only visual geoms are returned (this corresponds to group 1 geoms) + :`'all'`: All geoms are returned + + duplicate_collision_geoms (bool): If set, will guarantee that each collision geom has a + visual geom copy + """ + + def __init__(self, obj_type="all", duplicate_collision_geoms=True): + super().__init__(obj_type=obj_type, duplicate_collision_geoms=duplicate_collision_geoms) + + # Store common material names so we don't add prefixes to them + self.shared_materials = set() + self.shared_textures = set() + + def sanity_check(self): + """ + Checks if data provided makes sense. + Called in __init__() + For subclasses to inherit from + """ + pass + + @staticmethod + def get_collision_attrib_template(): + """ + Generates template with collision attributes for a given geom + + Returns: + dict: Initial template with `'pos'` and `'group'` already specified + """ + return {"group": "0", "rgba": array_to_string(OBJECT_COLLISION_COLOR)} + + @staticmethod + def get_visual_attrib_template(): + """ + Generates template with visual attributes for a given geom + + Returns: + dict: Initial template with `'conaffinity'`, `'contype'`, and `'group'` already specified + """ + return {"conaffinity": "0", "contype": "0", "mass": "1e-8", "group": "1"} + + def append_material(self, material): + """ + Adds a new texture / material combination to the assets subtree of this XML + Input is expected to be a CustomMaterial object + + See http://www.mujoco.org/book/XMLreference.html#asset for specific details on attributes expected for + Mujoco texture / material tags, respectively + + Note that the "file" attribute for the "texture" tag should be specified relative to the textures directory + located in robosuite/models/assets/textures/ + + Args: + material (CustomMaterial): Material to add to this object + """ + # First check if asset attribute exists; if not, define the asset attribute + if not hasattr(self, "asset"): + self.asset = ET.Element("asset") + # If the material name is not in shared materials, add this to our assets + if material.name not in self.shared_materials: + self.asset.append(ET.Element("texture", attrib=material.tex_attrib)) + self.asset.append(ET.Element("material", attrib=material.mat_attrib)) + # Add this material name to shared materials if it should be shared + if material.shared: + self.shared_materials.add(material.name) + self.shared_textures.add(material.tex_attrib["name"]) + # Update prefix for assets + add_prefix(root=self.asset, prefix=self.naming_prefix, exclude=self.exclude_from_prefixing) + + def exclude_from_prefixing(self, inp): + """ + Exclude all shared materials and their associated names from being prefixed. + + Args: + inp (ET.Element or str): Element or its attribute to check for prefixing. + + Returns: + bool: True if we should exclude the associated name(s) with @inp from being prefixed with naming_prefix + """ + # Automatically return False if this is not of type "str" + if type(inp) is not str: + return False + # Only return True if the string matches the name of a common material + return True if inp in self.shared_materials or inp in self.shared_textures else False + + # Methods that still need to be defined by subclass + def _get_object_subtree(self): + raise NotImplementedError + + def bottom_offset(self): + raise NotImplementedError + + def top_offset(self): + raise NotImplementedError + + def horizontal_radius(self): + raise NotImplementedError + + def get_bounding_box_half_size(self): + return np.array([self.horizontal_radius, self.horizontal_radius, 0.0]) - self.bottom_offset diff --git a/third_party/robosuite/robosuite/models/objects/primitive/__init__.py b/third_party/robosuite/robosuite/models/objects/primitive/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b224ac36f77f0c71cc7b6e38fd9b697f75f2823 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/primitive/__init__.py @@ -0,0 +1,4 @@ +from .ball import BallObject +from .box import BoxObject +from .capsule import CapsuleObject +from .cylinder import CylinderObject diff --git a/third_party/robosuite/robosuite/models/objects/primitive/ball.py b/third_party/robosuite/robosuite/models/objects/primitive/ball.py new file mode 100644 index 0000000000000000000000000000000000000000..95c6621dedadaf436ecb33dc3720fc8db7ddbacf --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/primitive/ball.py @@ -0,0 +1,71 @@ +import numpy as np + +from robosuite.models.objects import PrimitiveObject +from robosuite.utils.mjcf_utils import get_size + + +class BallObject(PrimitiveObject): + """ + A ball (sphere) object. + + Args: + size (1-tuple of float): (radius) size parameters for this ball object + """ + + def __init__( + self, + name, + size=None, + size_max=None, + size_min=None, + density=None, + friction=None, + rgba=None, + solref=None, + solimp=None, + material=None, + joints="default", + obj_type="all", + duplicate_collision_geoms=True, + ): + size = get_size(size, size_max, size_min, [0.07], [0.03]) + super().__init__( + name=name, + size=size, + rgba=rgba, + density=density, + friction=friction, + solref=solref, + solimp=solimp, + material=material, + joints=joints, + obj_type=obj_type, + duplicate_collision_geoms=duplicate_collision_geoms, + ) + + def sanity_check(self): + """ + Checks to make sure inputted size is of correct length + + Raises: + AssertionError: [Invalid size length] + """ + assert len(self.size) == 1, "ball size should have length 1" + + def _get_object_subtree(self): + return self._get_object_subtree_(ob_type="sphere") + + @property + def bottom_offset(self): + return np.array([0, 0, -1 * self.size[0]]) + + @property + def top_offset(self): + return np.array([0, 0, self.size[0]]) + + @property + def horizontal_radius(self): + return self.size[0] + + def get_bounding_box_half_size(self): + return np.array([self.size[0], self.size[0], self.size[0]]) diff --git a/third_party/robosuite/robosuite/models/objects/primitive/box.py b/third_party/robosuite/robosuite/models/objects/primitive/box.py new file mode 100644 index 0000000000000000000000000000000000000000..6fcb660be972e8862887be7508d16d7bbe6307c8 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/primitive/box.py @@ -0,0 +1,71 @@ +import numpy as np + +from robosuite.models.objects import PrimitiveObject +from robosuite.utils.mjcf_utils import get_size + + +class BoxObject(PrimitiveObject): + """ + A box object. + + Args: + size (3-tuple of float): (half-x, half-y, half-z) size parameters for this box object + """ + + def __init__( + self, + name, + size=None, + size_max=None, + size_min=None, + density=None, + friction=None, + rgba=None, + solref=None, + solimp=None, + material=None, + joints="default", + obj_type="all", + duplicate_collision_geoms=True, + ): + size = get_size(size, size_max, size_min, [0.07, 0.07, 0.07], [0.03, 0.03, 0.03]) + super().__init__( + name=name, + size=size, + rgba=rgba, + density=density, + friction=friction, + solref=solref, + solimp=solimp, + material=material, + joints=joints, + obj_type=obj_type, + duplicate_collision_geoms=duplicate_collision_geoms, + ) + + def sanity_check(self): + """ + Checks to make sure inputted size is of correct length + + Raises: + AssertionError: [Invalid size length] + """ + assert len(self.size) == 3, "box size should have length 3" + + def _get_object_subtree(self): + return self._get_object_subtree_(ob_type="box") + + @property + def bottom_offset(self): + return np.array([0, 0, -1 * self.size[2]]) + + @property + def top_offset(self): + return np.array([0, 0, self.size[2]]) + + @property + def horizontal_radius(self): + return np.linalg.norm(self.size[0:2], 2) + + def get_bounding_box_half_size(self): + return np.array([self.size[0], self.size[1], self.size[2]]) diff --git a/third_party/robosuite/robosuite/models/objects/primitive/capsule.py b/third_party/robosuite/robosuite/models/objects/primitive/capsule.py new file mode 100644 index 0000000000000000000000000000000000000000..6139cb3473d1d658a169f5620775722e75581929 --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/primitive/capsule.py @@ -0,0 +1,71 @@ +import numpy as np + +from robosuite.models.objects import PrimitiveObject +from robosuite.utils.mjcf_utils import get_size + + +class CapsuleObject(PrimitiveObject): + """ + A capsule object. + + Args: + size (2-tuple of float): (radius, half-length) size parameters for this capsule object + """ + + def __init__( + self, + name, + size=None, + size_max=None, + size_min=None, + density=None, + friction=None, + rgba=None, + solref=None, + solimp=None, + material=None, + joints="default", + obj_type="all", + duplicate_collision_geoms=True, + ): + size = get_size(size, size_max, size_min, [0.07, 0.07], [0.03, 0.03]) + super().__init__( + name=name, + size=size, + rgba=rgba, + density=density, + friction=friction, + solref=solref, + solimp=solimp, + material=material, + joints=joints, + obj_type=obj_type, + duplicate_collision_geoms=duplicate_collision_geoms, + ) + + def sanity_check(self): + """ + Checks to make sure inputted size is of correct length + + Raises: + AssertionError: [Invalid size length] + """ + assert len(self.size) == 2, "capsule size should have length 2" + + def _get_object_subtree(self): + return self._get_object_subtree_(ob_type="capsule") + + @property + def bottom_offset(self): + return np.array([0, 0, -1 * (self.size[0] + self.size[1])]) + + @property + def top_offset(self): + return np.array([0, 0, (self.size[0] + self.size[1])]) + + @property + def horizontal_radius(self): + return self.size[0] + + def get_bounding_box_half_size(self): + return np.array([self.size[0], self.size[0], self.size[0] + self.size[1]])