diff --git a/third_party/robosuite/robosuite/models/objects/primitive/cylinder.py b/third_party/robosuite/robosuite/models/objects/primitive/cylinder.py new file mode 100644 index 0000000000000000000000000000000000000000..9e2dc9af1d6ab3a4c10226b141f6a181437cd44a --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/primitive/cylinder.py @@ -0,0 +1,95 @@ +import numpy as np + +from robosuite.models.objects import MujocoGeneratedObject, PrimitiveObject +from robosuite.utils.mjcf_utils import get_size + + +class CylinderObject(PrimitiveObject): + """ + A cylinder object. + + Args: + size (2-tuple of float): (radius, half-length) size parameters for this cylinder 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]) + + # We override solref, solimp, and joint default values for better stability + if friction is None: + friction = [1, 0.01, 0.001] + if solref is None: + solref = [0.01, 0.5] + if joints == "default": + joints = [{"type": "free", "damping": "0.0001"}] + + 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, "cylinder size should have length 2" + + def _get_object_subtree(self): + return self._get_object_subtree_(ob_type="cylinder") + + @staticmethod + def get_collision_attrib_template(): + """ + Generates template with collision attributes for a given geom + + Extends super method for better stability for contacts + + Returns: + dict: Initial template with `'pos'` and `'group'` already specified + """ + template = MujocoGeneratedObject.get_collision_attrib_template() + # Add condim value + template["margin"] = "0.001" + return template + + @property + def bottom_offset(self): + return np.array([0, 0, -1 * self.size[1]]) + + @property + def top_offset(self): + return np.array([0, 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[1]]) diff --git a/third_party/robosuite/robosuite/models/objects/xml_objects.py b/third_party/robosuite/robosuite/models/objects/xml_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..68e0369d469d33e8052e6e0157182bb65e0b194d --- /dev/null +++ b/third_party/robosuite/robosuite/models/objects/xml_objects.py @@ -0,0 +1,299 @@ +import numpy as np + +from robosuite.models.objects import MujocoXMLObject +from robosuite.utils.mjcf_utils import array_to_string, find_elements, xml_path_completion + + +class BottleObject(MujocoXMLObject): + """ + Bottle object + """ + + def __init__(self, name): + super().__init__( + xml_path_completion("objects/bottle.xml"), + name=name, + joints=[dict(type="free", damping="0.0005")], + obj_type="all", + duplicate_collision_geoms=True, + ) + + +class CanObject(MujocoXMLObject): + """ + Coke can object (used in PickPlace) + """ + + def __init__(self, name): + super().__init__( + xml_path_completion("objects/can.xml"), + name=name, + joints=[dict(type="free", damping="0.0005")], + obj_type="all", + duplicate_collision_geoms=True, + ) + + +class LemonObject(MujocoXMLObject): + """ + Lemon object + """ + + def __init__(self, name): + super().__init__( + xml_path_completion("objects/lemon.xml"), name=name, obj_type="all", duplicate_collision_geoms=True + ) + + +class MilkObject(MujocoXMLObject): + """ + Milk carton object (used in PickPlace) + """ + + def __init__(self, name): + super().__init__( + xml_path_completion("objects/milk.xml"), + name=name, + joints=[dict(type="free", damping="0.0005")], + obj_type="all", + duplicate_collision_geoms=True, + ) + + +class BreadObject(MujocoXMLObject): + """ + Bread loaf object (used in PickPlace) + """ + + def __init__(self, name): + super().__init__( + xml_path_completion("objects/bread.xml"), + name=name, + joints=[dict(type="free", damping="0.0005")], + obj_type="all", + duplicate_collision_geoms=True, + ) + + +class CerealObject(MujocoXMLObject): + """ + Cereal box object (used in PickPlace) + """ + + def __init__(self, name): + super().__init__( + xml_path_completion("objects/cereal.xml"), + name=name, + joints=[dict(type="free", damping="0.0005")], + obj_type="all", + duplicate_collision_geoms=True, + ) + + +class SquareNutObject(MujocoXMLObject): + """ + Square nut object (used in NutAssembly) + """ + + def __init__(self, name): + super().__init__( + xml_path_completion("objects/square-nut.xml"), + name=name, + joints=[dict(type="free", damping="0.0005")], + obj_type="all", + duplicate_collision_geoms=True, + ) + + @property + def important_sites(self): + """ + Returns: + dict: In addition to any default sites for this object, also provides the following entries + + :`'handle'`: Name of nut handle location site + """ + # Get dict from super call and add to it + dic = super().important_sites + dic.update({"handle": self.naming_prefix + "handle_site"}) + return dic + + +class RoundNutObject(MujocoXMLObject): + """ + Round nut (used in NutAssembly) + """ + + def __init__(self, name): + super().__init__( + xml_path_completion("objects/round-nut.xml"), + name=name, + joints=[dict(type="free", damping="0.0005")], + obj_type="all", + duplicate_collision_geoms=True, + ) + + @property + def important_sites(self): + """ + Returns: + dict: In addition to any default sites for this object, also provides the following entries + + :`'handle'`: Name of nut handle location site + """ + # Get dict from super call and add to it + dic = super().important_sites + dic.update({"handle": self.naming_prefix + "handle_site"}) + return dic + + +class MilkVisualObject(MujocoXMLObject): + """ + Visual fiducial of milk carton (used in PickPlace). + + Fiducial objects are not involved in collision physics. + They provide a point of reference to indicate a position. + """ + + def __init__(self, name): + super().__init__( + xml_path_completion("objects/milk-visual.xml"), + name=name, + joints=None, + obj_type="visual", + duplicate_collision_geoms=True, + ) + + +class BreadVisualObject(MujocoXMLObject): + """ + Visual fiducial of bread loaf (used in PickPlace) + + Fiducial objects are not involved in collision physics. + They provide a point of reference to indicate a position. + """ + + def __init__(self, name): + super().__init__( + xml_path_completion("objects/bread-visual.xml"), + name=name, + joints=None, + obj_type="visual", + duplicate_collision_geoms=True, + ) + + +class CerealVisualObject(MujocoXMLObject): + """ + Visual fiducial of cereal box (used in PickPlace) + + Fiducial objects are not involved in collision physics. + They provide a point of reference to indicate a position. + """ + + def __init__(self, name): + super().__init__( + xml_path_completion("objects/cereal-visual.xml"), + name=name, + joints=None, + obj_type="visual", + duplicate_collision_geoms=True, + ) + + +class CanVisualObject(MujocoXMLObject): + """ + Visual fiducial of coke can (used in PickPlace) + + Fiducial objects are not involved in collision physics. + They provide a point of reference to indicate a position. + """ + + def __init__(self, name): + super().__init__( + xml_path_completion("objects/can-visual.xml"), + name=name, + joints=None, + obj_type="visual", + duplicate_collision_geoms=True, + ) + + +class PlateWithHoleObject(MujocoXMLObject): + """ + Square plate with a hole in the center (used in PegInHole) + """ + + def __init__(self, name): + super().__init__( + xml_path_completion("objects/plate-with-hole.xml"), + name=name, + joints=None, + obj_type="all", + duplicate_collision_geoms=True, + ) + + +class DoorObject(MujocoXMLObject): + """ + Door with handle (used in Door) + + Args: + friction (3-tuple of float): friction parameters to override the ones specified in the XML + damping (float): damping parameter to override the ones specified in the XML + lock (bool): Whether to use the locked door variation object or not + """ + + def __init__(self, name, friction=None, damping=None, lock=False): + xml_path = "objects/door.xml" + if lock: + xml_path = "objects/door_lock.xml" + super().__init__( + xml_path_completion(xml_path), name=name, joints=None, obj_type="all", duplicate_collision_geoms=True + ) + + # Set relevant body names + self.door_body = self.naming_prefix + "door" + self.frame_body = self.naming_prefix + "frame" + self.latch_body = self.naming_prefix + "latch" + self.hinge_joint = self.naming_prefix + "hinge" + + self.lock = lock + self.friction = friction + self.damping = damping + if self.friction is not None: + self._set_door_friction(self.friction) + if self.damping is not None: + self._set_door_damping(self.damping) + + def _set_door_friction(self, friction): + """ + Helper function to override the door friction directly in the XML + + Args: + friction (3-tuple of float): friction parameters to override the ones specified in the XML + """ + hinge = find_elements(root=self.worldbody, tags="joint", attribs={"name": self.hinge_joint}, return_first=True) + hinge.set("frictionloss", array_to_string(np.array([friction]))) + + def _set_door_damping(self, damping): + """ + Helper function to override the door friction directly in the XML + + Args: + damping (float): damping parameter to override the ones specified in the XML + """ + hinge = find_elements(root=self.worldbody, tags="joint", attribs={"name": self.hinge_joint}, return_first=True) + hinge.set("damping", array_to_string(np.array([damping]))) + + @property + def important_sites(self): + """ + Returns: + dict: In addition to any default sites for this object, also provides the following entries + + :`'handle'`: Name of door handle location site + """ + # Get dict from super call and add to it + dic = super().important_sites + dic.update({"handle": self.naming_prefix + "handle"}) + return dic diff --git a/third_party/robosuite/robosuite/models/robots/__init__.py b/third_party/robosuite/robosuite/models/robots/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e9188e4a3ce6945faeabb5e5f8ce7c78fabffe28 --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/__init__.py @@ -0,0 +1,15 @@ +from .robot_model import RobotModel, create_robot +from .manipulators import * +from .compositional import * + + +def is_robosuite_robot(robot: str) -> bool: + """ + robot is robosuite repo robot if can import robot class from robosuite.models.robots + """ + try: + module = __import__("robosuite.models.robots", fromlist=[robot]) + getattr(module, robot) + return True + except (ImportError, AttributeError): + return False diff --git a/third_party/robosuite/robosuite/models/robots/compositional.py b/third_party/robosuite/robosuite/models/robots/compositional.py new file mode 100644 index 0000000000000000000000000000000000000000..e8bc153e690f43685278be6a3dd2ed437b33875d --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/compositional.py @@ -0,0 +1,104 @@ +import numpy as np + +from robosuite.models.robots import * + + +class PandaOmron(Panda): + @property + def default_base(self): + return "OmronMobileBase" + + @property + def default_arms(self): + return {"right": "Panda"} + + @property + def init_qpos(self): + return np.array([0, np.pi / 16.0 - 0.2, 0.00, -np.pi / 2.0 - np.pi / 3.0, 0.00, np.pi - 0.4, np.pi / 4]) + + @property + def init_torso_qpos(self): + return np.array([0.2]) + + @property + def base_xpos_offset(self): + return { + "bins": (-0.6, -0.1, 0), + "empty": (-0.6, 0, 0), + "table": lambda table_length: (-0.16 - table_length / 2, 0, 0), + } + + +class SpotWithArm(SpotArm): + @property + def default_base(self): + return "Spot" + + @property + def default_arms(self): + return {"right": "SpotArm"} + + @property + def init_qpos(self): + return np.array([0.0, -2, 1.26, -0.335, 0.862, 0.0]) + + @property + def base_xpos_offset(self): + return { + "bins": (-1.05, -0.1, -0.22), + "empty": (-1.1, 0, -0.22), + "table": lambda table_length: (-0.5 - table_length / 2, 0.0, -0.22), + } + + +class SpotWithArmFloating(SpotArm): + def __init__(self, idn=0): + super().__init__(idn=idn) + + @property + def init_qpos(self): + return np.array([0.0, -2, 1.26, -0.335, 0.862, 0.0]) + + @property + def default_base(self): + return "SpotFloating" + + @property + def default_arms(self): + return {"right": "SpotArm"} + + @property + def base_xpos_offset(self): + return { + "bins": (-0.7, -0.1, 0.0), + "empty": (-0.6, 0, 0.0), + "table": lambda table_length: (-0.5 - table_length / 2, 0.0, 0.0), + } + + +class PandaDexRH(Panda): + @property + def default_gripper(self): + return {"right": "InspireRightHand"} + + @property + def gripper_mount_pos_offset(self): + return {"right": [0.0, 0.0, 0.0]} + + @property + def gripper_mount_quat_offset(self): + return {"right": [-0.5, 0.5, 0.5, -0.5]} + + +class PandaDexLH(Panda): + @property + def default_gripper(self): + return {"right": "InspireLeftHand"} + + @property + def gripper_mount_pos_offset(self): + return {"right": [0.0, 0.0, 0.0]} + + @property + def gripper_mount_quat_offset(self): + return {"right": [0.5, -0.5, 0.5, -0.5]} diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/__init__.py b/third_party/robosuite/robosuite/models/robots/manipulators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8536f9cefe74d661b4ea50b5f820b60b48b00240 --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/__init__.py @@ -0,0 +1,11 @@ +from .manipulator_model import ManipulatorModel +from .sawyer_robot import Sawyer +from .baxter_robot import Baxter +from .panda_robot import Panda +from .jaco_robot import Jaco +from .kinova3_robot import Kinova3 +from .iiwa_robot import IIWA +from .ur5e_robot import UR5e +from .spot_arm import SpotArm +from .tiago_robot import Tiago +from .gr1_robot import GR1, GR1FixedLowerBody, GR1ArmsOnly, GR1FloatingBody diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/baxter_robot.py b/third_party/robosuite/robosuite/models/robots/manipulators/baxter_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..58d8eb44f2aa26fe3b929202e1e6cfc2254051bf --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/baxter_robot.py @@ -0,0 +1,91 @@ +import numpy as np + +from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class Baxter(ManipulatorModel): + """ + Baxter is a hunky bimanual robot designed by Rethink Robotics. + + Args: + idn (int or str): Number or some other unique identification string for this robot instance + """ + + arms = ["right", "left"] + + def __init__(self, idn=0): + super().__init__(xml_path_completion("robots/baxter/robot.xml"), idn=idn) + + @property + def default_base(self): + return "RethinkMinimalMount" + + @property + def default_gripper(self): + """ + Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective + values + + Returns: + dict: Dictionary containing arm-specific gripper names + """ + return {"right": "RethinkGripper", "left": "RethinkGripper"} + + @property + def default_controller_config(self): + """ + Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective + values + + Returns: + dict: Dictionary containing arm-specific default controller config names + """ + return {"right": "osc_pose", "left": "osc_pose"} + + @property + def init_qpos(self): + """ + Since this is bimanual robot, returns [right, left] array corresponding to respective values + + Note that this is a pose such that the arms are half extended + + Returns: + np.array: default initial qpos for the right, left arms + """ + # [right, left] + # Arms half extended + return np.array( + [0.403, -0.636, 0.114, 1.432, 0.735, 1.205, -0.269, -0.403, -0.636, -0.114, 1.432, -0.735, 1.205, 0.269] + ) + + @property + def base_xpos_offset(self): + return { + "bins": (-0.5, -0.1, 0), + "empty": (-0.29, 0, 0), + "table": lambda table_length: (-0.26 - table_length / 2, 0, 0), + } + + @property + def top_offset(self): + return np.array((0, 0, 1.0)) + + @property + def _horizontal_radius(self): + return 0.5 + + @property + def arm_type(self): + return "bimanual" + + @property + def _eef_name(self): + """ + Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective + values + + Returns: + dict: Dictionary containing arm-specific eef names + """ + return {"right": "right_hand", "left": "left_hand"} diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/gr1_robot.py b/third_party/robosuite/robosuite/models/robots/manipulators/gr1_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..ed6119cf90213255cef83256601d15b4cbbfb965 --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/gr1_robot.py @@ -0,0 +1,195 @@ +import numpy as np + +from robosuite.models.robots.manipulators.legged_manipulator_model import LeggedManipulatorModel +from robosuite.utils.mjcf_utils import find_parent, xml_path_completion + + +class GR1(LeggedManipulatorModel): + """ + Tiago is a mobile manipulator robot created by PAL Robotics. + + Args: + idn (int or str): Number or some other unique identification string for this robot instance + """ + + arms = ["right", "left"] + + def __init__(self, idn=0): + super().__init__(xml_path_completion("robots/gr1/robot.xml"), idn=idn) + + @property + def default_base(self): + return "NoActuationBase" + + @property + def default_gripper(self): + """ + Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective + values + + Returns: + dict: Dictionary containing arm-specific gripper names + """ + return {"right": "FourierRightHand", "left": "FourierLeftHand"} + + @property + def default_controller_config(self): + """ + Since this is bimanual robot, returns dict with `'right'`, `'left'`, `'head'`, `'torso'` keywords corresponding to their respective + values + + Returns: + dict: Dictionary containing arm,head,torso-specific default controller config names + """ + return { + "right": "default_gr1", + "left": "default_gr1", + "head": "default_gr1_head", + "torso": "default_gr1_torso", + "right_leg": "default_gr1", + "left_leg": "default_gr1", + } + + @property + def init_qpos(self): + """ + Since this is bimanual robot, returns [right, left] array corresponding to respective values + + Note that this is a pose such that the arms are half extended + + Returns: + np.array: default initial qpos for the right, left arms + """ + init_qpos = np.array([0.0] * 32) + right_arm_init = np.array([0.0, -0.1, 0.0, -1.57, 0.0, 0.0, 0.0]) + init_qpos[6:13] = right_arm_init + left_arm_init = np.array([0.0, 0.1, 0.0, -1.57, 0.0, 0.0, 0.0]) + init_qpos[13:20] = left_arm_init + return init_qpos + + @property + def base_xpos_offset(self): + return { + "bins": (-0.30, -0.1, 0.95), + "empty": (-0.29, 0, 0.95), + "table": lambda table_length: (-0.15 - table_length / 2, 0, 0.95), + } + + @property + def top_offset(self): + return np.array((0, 0, 1.0)) + + @property + def _horizontal_radius(self): + return 0.5 + + @property + def arm_type(self): + return "bimanual" + + @property + def _eef_name(self): + """ + Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective + values + + Returns: + dict: Dictionary containing arm-specific eef names + """ + return {"right": "right_eef", "left": "left_eef"} + + +class GR1FixedLowerBody(GR1): + def __init__(self, idn=0): + super().__init__(idn=idn) + + # fix lower body + self._remove_joint_actuation("leg") + self._remove_free_joint() + + @property + def init_qpos(self): + """ + Since this is bimanual robot, returns [right, left] array corresponding to respective values + + Note that this is a pose such that the arms are half extended + + Returns: + np.array: default initial qpos for the right, left arms + """ + init_qpos = np.array([0.0] * 20) + right_arm_init = np.array([0.0, -0.1, 0.0, -1.57, 0.0, 0.0, 0.0]) + init_qpos[6:13] = right_arm_init + left_arm_init = np.array([0.0, 0.1, 0.0, -1.57, 0.0, 0.0, 0.0]) + init_qpos[13:20] = left_arm_init + return init_qpos + + @property + def default_base(self): + return "NoActuationBase" + + +class GR1FloatingBody(GR1): + def __init__(self, idn=0): + super().__init__(idn=idn) + + # fix lower body + self._remove_joint_actuation("leg") + self._remove_free_joint() + + @property + def init_qpos(self): + """ + Since this is bimanual robot, returns [right, left] array corresponding to respective values + + Note that this is a pose such that the arms are half extended + + Returns: + np.array: default initial qpos for the right, left arms + """ + init_qpos = np.array([0.0] * 20) + right_arm_init = np.array([0.0, -0.1, 0.0, -1.57, 0.0, 0.0, 0.0]) + init_qpos[6:13] = right_arm_init + left_arm_init = np.array([0.0, 0.1, 0.0, -1.57, 0.0, 0.0, 0.0]) + init_qpos[13:20] = left_arm_init + return init_qpos + + @property + def default_base(self): + return "FloatingLeggedBase" + + @property + def base_xpos_offset(self): + return { + "bins": (-0.30, -0.1, 0.97), + "empty": (-0.29, 0, 0.97), + "table": lambda table_length: (-0.15 - table_length / 2, 0, 0.97), + } + + +class GR1ArmsOnly(GR1): + def __init__(self, idn=0): + super().__init__(idn=idn) + + # fix lower body + self._remove_joint_actuation("leg") + self._remove_joint_actuation("head") + self._remove_joint_actuation("torso") + self._remove_free_joint() + + @property + def init_qpos(self): + """ + Since this is bimanual robot, returns [right, left] array corresponding to respective values + + Note that this is a pose such that the arms are half extended + + Returns: + np.array: default initial qpos for the right, left arms + """ + init_qpos = np.array([0.0] * 14) + 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[0:7] = right_arm_init + init_qpos[7:14] = left_arm_init + return init_qpos diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/humanoid_model.py b/third_party/robosuite/robosuite/models/robots/manipulators/humanoid_model.py new file mode 100644 index 0000000000000000000000000000000000000000..56313c59ac05101dfbb5aafd73604254cc7654a0 --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/humanoid_model.py @@ -0,0 +1,171 @@ +from collections import OrderedDict + +import numpy as np + +from robosuite.models.robots import RobotModel +from robosuite.utils.mjcf_utils import find_elements, string_to_array + + +class HumanoidModel(RobotModel): + """ + Base class for all humanoid models. + + 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 robot instance + """ + + def __init__(self, fname, idn=0): + # Always run super init first + super().__init__(fname, idn=idn) + + # key: gripper name and value: gripper model + self.grippers = OrderedDict() + + # Grab hand's offset from final robot link (string -> np.array -> elements [1, 2, 3, 0] (x, y, z, w)) + # We're dealing with bimanual armed robot + self.hand_rotation_offset = {} + for arm in ("right", "left"): + hand_element = find_elements( + root=self.root, tags="body", attribs={"name": self.eef_name[arm]}, return_first=True + ) + self.hand_rotation_offset[arm] = string_to_array(hand_element.get("quat", "1 0 0 0"))[[1, 2, 3, 0]] + + # Get camera names for this robot + self.cameras = self.get_element_names(self.worldbody, "camera") + + def add_gripper(self, gripper, arm_name=None): + """ + Mounts @gripper to arm. + + Throws error if robot already has a gripper or gripper type is incorrect. + + Args: + gripper (GripperModel): gripper MJCF model + arm_name (str): name of arm mount -- defaults to self.eef_name if not specified + + Raises: + ValueError: [Multiple grippers] + """ + if arm_name is None: + arm_name = self.eef_name + if arm_name in self.grippers: + raise ValueError("Attempts to add multiple grippers to one body") + + self.merge(gripper, merge_body=arm_name) + + self.grippers[arm_name] = gripper + + # Update cameras in this model + self.cameras = self.get_element_names(self.worldbody, "camera") + + # -------------------------------------------------------------------------------------- # + # Public Properties: In general, these are the name-adjusted versions from the private # + # attributes pulled from their respective raw xml files # + # -------------------------------------------------------------------------------------- # + + @property + def eef_name(self): + """ + Returns: + str or dict of str: Prefix-adjusted eef name for this robot. If bimanual robot, returns {"left", "right"} + keyword-mapped eef names + """ + return self.correct_naming(self._eef_name) + + @property + def models(self): + """ + Returns a list of all m(sub-)models owned by this robot model. By default, this includes the gripper model, + if specified + + Returns: + list: models owned by this object + """ + models = super().models + return models + list(self.grippers.values()) + + # -------------------------------------------------------------------------------------- # + # -------------------------- Private Properties ---------------------------------------- # + # -------------------------------------------------------------------------------------- # + + @property + def _important_sites(self): + """ + Returns: + dict: (Default is no important sites; i.e.: empty dict) + """ + return {} + + @property + def _eef_name(self): + """ + XML eef name for this robot to which grippers can be attached. Note that these should be the raw + string names directly pulled from a robot's corresponding XML file, NOT the adjusted name with an + auto-generated naming prefix + + Returns: + str: Raw XML eef name for this robot (default is "right_hand") + """ + return "right_hand" + + # -------------------------------------------------------------------------------------- # + # All subclasses must implement the following properties # + # -------------------------------------------------------------------------------------- # + + @property + def default_gripper(self): + """ + Defines the default gripper type for this robot that gets added to end effector + + Returns: + str: Default gripper name to add to this robot + """ + raise NotImplementedError + + @property + def arm_type(self): + """ + Type of robot arm. Should be either "bimanual" or "single" (or something else if it gets added in the future) + + Returns: + str: Type of robot + """ + raise NotImplementedError + + @property + def base_xpos_offset(self): + """ + Defines the dict of various (x,y,z) tuple offsets relative to specific arenas placed at (0,0,0) + Assumes robot is facing forwards (in the +x direction) when determining offset. Should have entries for each + manipulator arena case; i.e.: "bins", "empty", and "table") + + Returns: + dict: + + :`'bins'`: (x,y,z) robot offset if placed in bins arena + :`'empty'`: (x,y,z) robot offset if placed in the empty arena + :`'table'`: lambda function that takes in table_length and returns corresponding (x,y,z) offset + if placed in the table arena + """ + raise NotImplementedError + + @property + def top_offset(self): + raise NotImplementedError + + @property + def _horizontal_radius(self): + raise NotImplementedError + + @property + def default_mount(self): + return "HumanoidFreeMount" + + @property + def default_controller_config(self): + raise NotImplementedError + + @property + def init_qpos(self): + raise NotImplementedError diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/humanoid_upperbody_model.py b/third_party/robosuite/robosuite/models/robots/manipulators/humanoid_upperbody_model.py new file mode 100644 index 0000000000000000000000000000000000000000..a66516049b303905715d251c29ce4c550ebc50ca --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/humanoid_upperbody_model.py @@ -0,0 +1,171 @@ +from collections import OrderedDict + +import numpy as np + +from robosuite.models.robots import RobotModel +from robosuite.utils.mjcf_utils import find_elements, string_to_array + + +class HumanoidUpperBodyModel(RobotModel): + """ + Base class for all humanoid upper models (base can be any, bimanual upper body of humanoids). + + 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 robot instance + """ + + def __init__(self, fname, idn=0): + # Always run super init first + super().__init__(fname, idn=idn) + + # key: gripper name and value: gripper model + self.grippers = OrderedDict() + + # Grab hand's offset from final robot link (string -> np.array -> elements [1, 2, 3, 0] (x, y, z, w)) + # We're dealing with bimanual armed robot + self.hand_rotation_offset = {} + for arm in ("right", "left"): + hand_element = find_elements( + root=self.root, tags="body", attribs={"name": self.eef_name[arm]}, return_first=True + ) + self.hand_rotation_offset[arm] = string_to_array(hand_element.get("quat", "1 0 0 0"))[[1, 2, 3, 0]] + + # Get camera names for this robot + self.cameras = self.get_element_names(self.worldbody, "camera") + + def add_gripper(self, gripper, arm_name=None): + """ + Mounts @gripper to arm. + + Throws error if robot already has a gripper or gripper type is incorrect. + + Args: + gripper (GripperModel): gripper MJCF model + arm_name (str): name of arm mount -- defaults to self.eef_name if not specified + + Raises: + ValueError: [Multiple grippers] + """ + if arm_name is None: + arm_name = self.eef_name + if arm_name in self.grippers: + raise ValueError("Attempts to add multiple grippers to one body") + + self.merge(gripper, merge_body=arm_name) + + self.grippers[arm_name] = gripper + + # Update cameras in this model + self.cameras = self.get_element_names(self.worldbody, "camera") + + # -------------------------------------------------------------------------------------- # + # Public Properties: In general, these are the name-adjusted versions from the private # + # attributes pulled from their respective raw xml files # + # -------------------------------------------------------------------------------------- # + + @property + def eef_name(self): + """ + Returns: + str or dict of str: Prefix-adjusted eef name for this robot. If bimanual robot, returns {"left", "right"} + keyword-mapped eef names + """ + return self.correct_naming(self._eef_name) + + @property + def models(self): + """ + Returns a list of all m(sub-)models owned by this robot model. By default, this includes the gripper model, + if specified + + Returns: + list: models owned by this object + """ + models = super().models + return models + list(self.grippers.values()) + + # -------------------------------------------------------------------------------------- # + # -------------------------- Private Properties ---------------------------------------- # + # -------------------------------------------------------------------------------------- # + + @property + def _important_sites(self): + """ + Returns: + dict: (Default is no important sites; i.e.: empty dict) + """ + return {} + + @property + def _eef_name(self): + """ + XML eef name for this robot to which grippers can be attached. Note that these should be the raw + string names directly pulled from a robot's corresponding XML file, NOT the adjusted name with an + auto-generated naming prefix + + Returns: + str: Raw XML eef name for this robot (default is "right_hand") + """ + return "right_hand" + + # -------------------------------------------------------------------------------------- # + # All subclasses must implement the following properties # + # -------------------------------------------------------------------------------------- # + + @property + def default_gripper(self): + """ + Defines the default gripper type for this robot that gets added to end effector + + Returns: + str: Default gripper name to add to this robot + """ + raise NotImplementedError + + @property + def arm_type(self): + """ + Type of robot arm. Should be either "bimanual" or "single" (or something else if it gets added in the future) + + Returns: + str: Type of robot + """ + raise NotImplementedError + + @property + def base_xpos_offset(self): + """ + Defines the dict of various (x,y,z) tuple offsets relative to specific arenas placed at (0,0,0) + Assumes robot is facing forwards (in the +x direction) when determining offset. Should have entries for each + manipulator arena case; i.e.: "bins", "empty", and "table") + + Returns: + dict: + + :`'bins'`: (x,y,z) robot offset if placed in bins arena + :`'empty'`: (x,y,z) robot offset if placed in the empty arena + :`'table'`: lambda function that takes in table_length and returns corresponding (x,y,z) offset + if placed in the table arena + """ + raise NotImplementedError + + @property + def top_offset(self): + raise NotImplementedError + + @property + def _horizontal_radius(self): + raise NotImplementedError + + @property + def default_mount(self): + raise NotImplementedError + + @property + def default_controller_config(self): + raise NotImplementedError + + @property + def init_qpos(self): + raise NotImplementedError diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/iiwa_robot.py b/third_party/robosuite/robosuite/models/robots/manipulators/iiwa_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..68b7326c3f880573f5a7c3876e6effb6237c2c7d --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/iiwa_robot.py @@ -0,0 +1,54 @@ +import numpy as np + +from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class IIWA(ManipulatorModel): + """ + IIWA is a bright and spunky robot created by KUKA + + Args: + idn (int or str): Number or some other unique identification string for this robot instance + """ + + arms = ["right"] + + def __init__(self, idn=0): + super().__init__(xml_path_completion("robots/iiwa/robot.xml"), idn=idn) + + @property + def default_base(self): + return "RethinkMount" + + @property + def default_gripper(self): + return {"right": "Robotiq140Gripper"} + + @property + def default_controller_config(self): + return {"right": "default_iiwa"} + + @property + def init_qpos(self): + return np.array([0.000, 0.650, 0.000, -1.890, 0.000, 0.600, 0.000]) + + @property + def base_xpos_offset(self): + return { + "bins": (-0.5, -0.1, 0), + "empty": (-0.6, 0, 0), + "table": lambda table_length: (-0.16 - table_length / 2, 0, 0), + } + + @property + def top_offset(self): + return np.array((0, 0, 1.0)) + + @property + def _horizontal_radius(self): + return 0.5 + + @property + def arm_type(self): + return "single" diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/jaco_robot.py b/third_party/robosuite/robosuite/models/robots/manipulators/jaco_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..c29ac7bd72de7d77ff8d90c6fc7a0a595b735854 --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/jaco_robot.py @@ -0,0 +1,54 @@ +import numpy as np + +from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class Jaco(ManipulatorModel): + """ + Jaco is a kind and assistive robot created by Kinova + + Args: + idn (int or str): Number or some other unique identification string for this robot instance + """ + + arms = ["right"] + + def __init__(self, idn=0): + super().__init__(xml_path_completion("robots/jaco/robot.xml"), idn=idn) + + @property + def default_base(self): + return "RethinkMount" + + @property + def default_gripper(self): + return {"right": "JacoThreeFingerGripper"} + + @property + def default_controller_config(self): + return {"right": "default_jaco"} + + @property + def init_qpos(self): + return np.array([3.192, 3.680, -0.000, 1.170, 0.050, 3.760, 3.142]) + + @property + def base_xpos_offset(self): + return { + "bins": (-0.5, -0.1, 0), + "empty": (-0.6, 0, 0), + "table": lambda table_length: (-0.16 - table_length / 2, 0, 0), + } + + @property + def top_offset(self): + return np.array((0, 0, 1.0)) + + @property + def _horizontal_radius(self): + return 0.5 + + @property + def arm_type(self): + return "single" diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/kinova3_robot.py b/third_party/robosuite/robosuite/models/robots/manipulators/kinova3_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..b3bce25a164979c69506b8d56faab463ee23f9a6 --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/kinova3_robot.py @@ -0,0 +1,54 @@ +import numpy as np + +from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class Kinova3(ManipulatorModel): + """ + The Gen3 robot is the sparkly newest addition to the Kinova line + + Args: + idn (int or str): Number or some other unique identification string for this robot instance + """ + + arms = ["right"] + + def __init__(self, idn=0): + super().__init__(xml_path_completion("robots/kinova3/robot.xml"), idn=idn) + + @property + def default_base(self): + return "RethinkMount" + + @property + def default_gripper(self): + return {"right": "Robotiq85Gripper"} + + @property + def default_controller_config(self): + return {"right": "osc_pose"} + + @property + def init_qpos(self): + return np.array([0.000, 0.650, 0.000, 1.890, 0.000, 0.600, -np.pi / 2]) + + @property + def base_xpos_offset(self): + return { + "bins": (-0.5, -0.1, 0), + "empty": (-0.6, 0, 0), + "table": lambda table_length: (-0.16 - table_length / 2, 0, 0), + } + + @property + def top_offset(self): + return np.array((0, 0, 1.0)) + + @property + def _horizontal_radius(self): + return 0.5 + + @property + def arm_type(self): + return "single" diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/legged_manipulator_model.py b/third_party/robosuite/robosuite/models/robots/manipulators/legged_manipulator_model.py new file mode 100644 index 0000000000000000000000000000000000000000..f405b1d28e62d9107556b083169eb2b7761dd7ae --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/legged_manipulator_model.py @@ -0,0 +1,64 @@ +from collections import OrderedDict + +import numpy as np + +from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel +from robosuite.utils.mjcf_utils import find_parent + + +class LeggedManipulatorModel(ManipulatorModel): + """ + Base class for all manipulator models (robot arm(s) with gripper(s)). + + 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 robot instance + """ + + def __init__(self, fname, idn=0): + # Always run super init first + super().__init__(fname, idn=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, "")) + for motor in self.actuator.findall(".//position"): + 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, "")) + for fixed in self.tendon.findall(".//fixed"): + for joint in fixed.findall(".//joint"): + if part_name in joint.get("joint"): + parent_body = find_parent(self.tendon, fixed) + parent_body.remove(fixed) + break + # remove joint in equality + for equality in self.equality.findall(".//joint"): + # If either joint1 or joint2 is the joint we want to remove + if part_name in equality.get("joint1") or part_name in equality.get("joint2"): + parent_body = find_parent(self.equality, equality) + parent_body.remove(equality) + + def _remove_free_joint(self): + # remove freejoint + for freejoint in self.worldbody.findall(".//freejoint"): + find_parent(self.worldbody, freejoint).remove(freejoint) + + @property + def legs_joints(self): + """ + No need for name correcting because the prefix has been added during creation. + + Returns: + list: (Default is no joints; i.e.: empty dict) + """ + return self._legs_joints diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/manipulator_model.py b/third_party/robosuite/robosuite/models/robots/manipulators/manipulator_model.py new file mode 100644 index 0000000000000000000000000000000000000000..07946abc267829e982d532ccc0fae144d0ee6366 --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/manipulator_model.py @@ -0,0 +1,376 @@ +from collections import OrderedDict +from typing import Dict, List, Optional, Union + +import numpy as np + +from robosuite.models.grippers.gripper_model import GripperModel +from robosuite.models.robots import RobotModel +from robosuite.utils.mjcf_utils import find_elements, find_elements_by_substring, string_to_array + + +class ManipulatorModel(RobotModel): + """ + Base class for all manipulator models (robot arm(s) with gripper(s)). + + 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 robot instance + """ + + def __init__(self, fname: str, idn=0): + # Always run super init first + super().__init__(fname, idn=idn) + + # key: gripper name and value: gripper model + self.grippers = OrderedDict() + + # # Grab hand's offset from final robot link (string -> np.array -> elements [1, 2, 3, 0] (x, y, z, w)) + # # Different case based on whether we're dealing with single or bimanual armed robot + # if self.arm_type == "single": + # hand_element = find_elements( + # root=self.root, tags="body", attribs={"name": self.eef_name}, return_first=True + # ) + # self.hand_rotation_offset = string_to_array(hand_element.get("quat", "1 0 0 0"))[[1, 2, 3, 0]] + # else: # "bimanual" case + if self.arm_type == "single": + arms = ["right"] + elif self.arm_type == "bimanual": + arms = ["right", "left"] + self.hand_rotation_offset = {} + for arm in arms: + hand_element = find_elements( + root=self.root, tags="body", attribs={"name": self.eef_name[arm]}, return_first=True + ) + self.hand_rotation_offset[arm] = string_to_array(hand_element.get("quat", "1 0 0 0"))[[1, 2, 3, 0]] + + # Get camera names for this robot + self.cameras = self.get_element_names(self.worldbody, "camera") + + self._base_actuators = [] + self._torso_actuators = [] + self._head_actuators = [] + self._legs_actuators = [] + + self._arms_actuators = [] + # specify arm actuators by excluding overallpy actuators from previous ones + + self._base_joints = [] + self._torso_joints = [] + self._head_joints = [] + self._legs_joints = [] + + self._arms_joints = [] + + def add_gripper(self, gripper: GripperModel, arm_name: Optional[str] = None): + """ + Mounts @gripper to arm. + + Throws error if robot already has a gripper or gripper type is incorrect. + + Args: + gripper (GripperModel): gripper MJCF model + arm_name (str): name of arm mount -- + defaults add to all self.eef_name if not specified + + Raises: + ValueError: [Multiple grippers] + """ + if arm_name is None: + assert isinstance(self.eef_name, dict), "only support single insertion of gripper now" + arm_names = list(self.eef_name.values()) + else: + arm_names = [arm_name] + + for arm_name in arm_names: + if arm_name in self.grippers: + raise ValueError("Attempts to add multiple grippers to one body") + + self.merge(gripper, merge_body=arm_name) + + self.grippers[arm_name] = gripper + + # Update cameras in this model + self.cameras = self.get_element_names(self.worldbody, "camera") + + def update_joints(self): + """internal function to update joint lists""" + for joint in self.all_joints: + if "torso" in joint: + self.torso_joints.append(joint) + elif "mobile" in joint: + self.base_joints.append(joint) + elif "head" in joint: + self.head_joints.append(joint) + elif "leg" in joint: + self.legs_joints.append(joint) + + for joint in self.all_joints: + if ( + joint not in self._base_joints + and joint not in self._torso_joints + and joint not in self._head_joints + and joint not in self._legs_joints + ): + self._arms_joints.append(joint) + + def update_actuators(self): + """internal function to update actuator lists""" + for actuator in self.all_actuators: + if "torso" in actuator: + self.torso_actuators.append(actuator) + elif "mobile" in actuator: + self.base_actuators.append(actuator) + elif "head" in actuator: + self.head_actuators.append(actuator) + elif "leg" in actuator: + self.legs_actuators.append(actuator) + + for actuator in self.all_actuators: + if ( + actuator not in self._base_actuators + and actuator not in self._torso_actuators + and actuator not in self._head_actuators + and actuator not in self._legs_actuators + ): + self._arms_actuators.append(actuator) + + # -------------------------------------------------------------------------------------- # + # Public Properties: In general, these are the name-adjusted versions from the private # + # attributes pulled from their respective raw xml files # + # -------------------------------------------------------------------------------------- # + + @property + def eef_name(self) -> Dict[str, str]: + """ + Returns: + dict of str: Prefix-adjusted eef name for this robot. If bimanual robot, returns {"left", "right"} + keyword-mapped eef names + """ + return self.correct_naming(self._eef_name) + + @property + def models(self) -> List[Union[GripperModel, RobotModel]]: + """ + Returns a list of all m(sub-)models owned by this robot model. By default, this includes the gripper model, + if specified + + Returns: + list: models owned by this object + """ + models = super().models + return models + list(self.grippers.values()) + + # -------------------------------------------------------------------------------------- # + # -------------------------- Private Properties ---------------------------------------- # + # -------------------------------------------------------------------------------------- # + + @property + def _important_sites(self) -> Dict[str, str]: + """ + Returns: + dict: (Default is no important sites; i.e.: empty dict) + """ + return {} + + @property + def _eef_name(self) -> Dict[str, str]: + """ + XML eef name for this robot to which grippers can be attached. Note that these should be the raw + string names directly pulled from a robot's corresponding XML file, NOT the adjusted name with an + auto-generated naming prefix + + Returns: + dict of str: eef name of this robot. + If bimanual robot, returns {"left", "right"} keyword-mapped eef names + """ + return {"right": "right_hand"} + + # -------------------------------------------------------------------------------------- # + # All subclasses must implement the following properties # + # -------------------------------------------------------------------------------------- # + + @property + def default_gripper(self) -> Dict[str, str]: + """ + Defines the default gripper type for this robot that gets added to end effector + + Returns: + dict: (Default is no gripper; i.e.: empty dict) + """ + raise NotImplementedError + + @property + def gripper_mount_pos_offset(self): + """ + Define the custom offset of the gripper that is different from the one defined in xml. + The offset will applied to the first body in the gripper definition file. + + Returns: + Empty dictionary unless specified. + """ + return {} + + @property + def gripper_mount_quat_offset(self): + """ + Define the custom orientation offset of the gripper with respect to the arm. + The offset will applied to the first body in the gripper definition file. + Return empty dict by default unless specified. + The quaternion is in the (w, x, y, z) format to match the mjcf format. + """ + return {} + + @property + def arm_type(self) -> str: + """ + Type of robot arm. Should be either "bimanual" or "single" (or something else if it gets added in the future) + + Returns: + str: Type of robot + """ + raise NotImplementedError + + @property + def base_xpos_offset(self) -> Dict[str, Union[tuple, dict]]: + """ + Defines the dict of various (x,y,z) tuple offsets relative to specific arenas placed at (0,0,0) + Assumes robot is facing forwards (in the +x direction) when determining offset. Should have entries for each + manipulator arena case; i.e.: "bins", "empty", and "table") + + Returns: + dict: + + :`'bins'`: (x,y,z) robot offset if placed in bins arena + :`'empty'`: (x,y,z) robot offset if placed in the empty arena + :`'table'`: lambda function that takes in table_length and returns corresponding (x,y,z) offset + if placed in the table arena + """ + raise NotImplementedError + + @property + def top_offset(self) -> np.array: + raise NotImplementedError + + @property + def _horizontal_radius(self): + raise NotImplementedError + + @property + def default_base(self): + raise NotImplementedError + + @property + def default_controller_config(self): + raise NotImplementedError + + @property + def init_qpos(self): + raise NotImplementedError + + @property + def init_base_qpos(self): + return None + + @property + def init_torso_qpos(self): + return None + + @property + def arm_actuators(self): + """ + No need for name correcting because the prefix has been added during creation. + + Returns: + list: (Default is no actuators; i.e.: empty dict) + """ + return self._arms_actuators + + @property + def base_actuators(self): + """ + No need for name correcting because the prefix has been added during creation. + + Returns: + list: (Default is no actuators; i.e.: empty dict) + """ + return self._base_actuators + + @property + def torso_actuators(self): + """ + No need for name correcting because the prefix has been added during creation. + + Returns: + list: (Default is no actuators; i.e.: empty dict) + """ + return self._torso_actuators + + @property + def head_actuators(self): + """ + No need for name correcting because the prefix has been added during creation. + + Returns: + list: (Default is no actuators; i.e.: empty dict) + """ + return self._head_actuators + + @property + def legs_actuators(self): + """ + No need for name correcting because the prefix has been added during creation. + + Returns: + list: (Default is no actuators; i.e.: empty dict) + """ + return self._legs_actuators + + @property + def arm_joints(self): + """ + No need for name correcting because the prefix has been added during creation. + + Returns: + list: (Default is no joints; i.e.: empty dict) + """ + return self._arms_joints + + @property + def base_joints(self): + """ + No need for name correcting because the prefix has been added during creation. + + Returns: + list: (Default is no joints; i.e.: empty dict) + """ + return self._base_joints + + @property + def torso_joints(self): + """ + No need for name correcting because the prefix has been added during creation. + + Returns: + list: (Default is no joints; i.e.: empty dict) + """ + return self._torso_joints + + @property + def head_joints(self): + """ + No need for name correcting because the prefix has been added during creation. + + Returns: + list: (Default is no joints; i.e.: empty dict) + """ + return self._head_joints + + @property + def legs_joints(self): + """ + No need for name correcting because the prefix has been added during creation. + + Returns: + list: (Default is no joints; i.e.: empty dict) + """ + return self._legs_joints diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/panda_robot.py b/third_party/robosuite/robosuite/models/robots/manipulators/panda_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..413697e26014950f8084712d8cbfbecb3350664a --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/panda_robot.py @@ -0,0 +1,57 @@ +import numpy as np + +from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class Panda(ManipulatorModel): + """ + Panda is a sensitive single-arm robot designed by Franka. + + Args: + idn (int or str): Number or some other unique identification string for this robot instance + """ + + arms = ["right"] + + def __init__(self, idn=0): + super().__init__(xml_path_completion("robots/panda/robot.xml"), idn=idn) + + # Set joint damping + self.set_joint_attribute(attrib="damping", values=np.array((0.1, 0.1, 0.1, 0.1, 0.1, 0.01, 0.01))) + + @property + def default_base(self): + return "RethinkMount" + + @property + def default_gripper(self): + return {"right": "PandaGripper"} + + @property + def default_controller_config(self): + return {"right": "default_panda"} + + @property + def init_qpos(self): + return np.array([0, np.pi / 16.0, 0.00, -np.pi / 2.0 - np.pi / 3.0, 0.00, np.pi - 0.2, np.pi / 4]) + + @property + def base_xpos_offset(self): + return { + "bins": (-0.5, -0.1, 0), + "empty": (-0.6, 0, 0), + "table": lambda table_length: (-0.16 - table_length / 2, 0, 0), + } + + @property + def top_offset(self): + return np.array((0, 0, 1.0)) + + @property + def _horizontal_radius(self): + return 0.5 + + @property + def arm_type(self): + return "single" diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/sawyer_robot.py b/third_party/robosuite/robosuite/models/robots/manipulators/sawyer_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..dec1251c0154b1ec217bc14f5093921f1a72219a --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/sawyer_robot.py @@ -0,0 +1,54 @@ +import numpy as np + +from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class Sawyer(ManipulatorModel): + """ + Sawyer is a witty single-arm robot designed by Rethink Robotics. + + Args: + idn (int or str): Number or some other unique identification string for this robot instance + """ + + arms = ["right"] + + def __init__(self, idn=0): + super().__init__(xml_path_completion("robots/sawyer/robot.xml"), idn=idn) + + @property + def default_base(self): + return "RethinkMount" + + @property + def default_gripper(self): + return {"right": "RethinkGripper"} + + @property + def default_controller_config(self): + return {"right": "default_sawyer"} + + @property + def init_qpos(self): + return np.array([0, -1.18, 0.00, 2.18, 0.00, 0.57, -1.57]) + + @property + def base_xpos_offset(self): + return { + "bins": (-0.5, -0.1, 0), + "empty": (-0.6, 0, 0), + "table": lambda table_length: (-0.16 - table_length / 2, 0, 0), + } + + @property + def top_offset(self): + return np.array((0, 0, 1.0)) + + @property + def _horizontal_radius(self): + return 0.5 + + @property + def arm_type(self): + return "single" diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/spot_arm.py b/third_party/robosuite/robosuite/models/robots/manipulators/spot_arm.py new file mode 100644 index 0000000000000000000000000000000000000000..8424e284215128925e92fade3c24bf9881495322 --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/spot_arm.py @@ -0,0 +1,57 @@ +import numpy as np + +from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class SpotArm(ManipulatorModel): + """ + Spot Arm is a single-arm robot for mouting on the spot robot. + + Args: + idn (int or str): Number or some other unique identification string for this robot instance + """ + + arms = ["right"] + + def __init__(self, idn=0): + super().__init__(xml_path_completion("robots/spot_arm/robot.xml"), idn=idn) + + # Set joint damping + self.set_joint_attribute(attrib="damping", values=np.array((0.1, 0.1, 0.1, 0.1, 0.1, 0.01))) + + @property + def default_base(self): + return "RethinkMount" + + @property + def default_gripper(self): + return {"right": "BDGripper"} + + @property + def default_controller_config(self): + return {"right": "default_spot"} + + @property + def init_qpos(self): + return np.array([0.0, -1.2, 1.85, 0.0, 0.862, 0.0]) + + @property + def base_xpos_offset(self): + return { + "bins": (-0.5, -0.1, 0), + "empty": (-0.6, 0, 0), + "table": lambda table_length: (-0.16 - 0.9 - table_length / 2, 0.0, 0.0), + } + + @property + def top_offset(self): + return np.array((0, 0, 1.0)) + + @property + def _horizontal_radius(self): + return 0.5 + + @property + def arm_type(self): + return "single" diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/tiago_robot.py b/third_party/robosuite/robosuite/models/robots/manipulators/tiago_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..802f6a1166eb713c9676d2554d9eaf1f289772e4 --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/tiago_robot.py @@ -0,0 +1,112 @@ +import numpy as np + +from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class Tiago(ManipulatorModel): + """ + Tiago is a mobile manipulator robot created by PAL Robotics. + + Args: + idn (int or str): Number or some other unique identification string for this robot instance + """ + + arms = ["right", "left"] + + def __init__(self, idn=0): + super().__init__(xml_path_completion("robots/tiago/robot.xml"), idn=idn) + + @property + def default_base(self): + return "NullMobileBase" + + @property + def default_gripper(self): + """ + Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective + values + + Returns: + dict: Dictionary containing arm-specific gripper names + """ + return {"right": "Robotiq85Gripper", "left": "Robotiq85Gripper"} + + @property + def default_controller_config(self): + """ + Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective + values + + Returns: + dict: Dictionary containing arm-specific default controller config names + """ + return { + "right": "joint_position", + "left": "joint_position", + "head": "joint_position", + "torso": "joint_position", + } + + @property + def init_qpos(self): + """ + Since this is bimanual robot, returns [right, left] array corresponding to respective values + + Note that this is a pose such that the arms are half extended + + Returns: + np.array: default initial qpos for the right, left arms + """ + # [right, left] + # Arms half extended + return np.array( + [ + 0.1, + 0, + 0, + 0, + -0.9, + 1.45, + 1.7, + -1.5, + 0.5, + 0, + -0.9, + 1.45, + 1.7, + -1.5, + 0.5, + ] + ) + + @property + def base_xpos_offset(self): + return { + "bins": (-0.5, -0.1, 0), + "empty": (-0.29, 0, 0), + "table": lambda table_length: (-0.20 - table_length / 2, 0, 0), + } + + @property + def top_offset(self): + return np.array((0, 0, 1.0)) + + @property + def _horizontal_radius(self): + return 0.5 + + @property + def arm_type(self): + return "bimanual" + + @property + def _eef_name(self): + """ + Since this is bimanual robot, returns dict with `'right'`, `'left'` keywords corresponding to their respective + values + + Returns: + dict: Dictionary containing arm-specific eef names + """ + return {"right": "right_hand", "left": "left_hand"} diff --git a/third_party/robosuite/robosuite/models/robots/manipulators/ur5e_robot.py b/third_party/robosuite/robosuite/models/robots/manipulators/ur5e_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..e6e3fe7aa3028441a80f1cb95eab03dd775c43b9 --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/manipulators/ur5e_robot.py @@ -0,0 +1,54 @@ +import numpy as np + +from robosuite.models.robots.manipulators.manipulator_model import ManipulatorModel +from robosuite.utils.mjcf_utils import xml_path_completion + + +class UR5e(ManipulatorModel): + """ + UR5e is a sleek and elegant new robot created by Universal Robots + + Args: + idn (int or str): Number or some other unique identification string for this robot instance + """ + + arms = ["right"] + + def __init__(self, idn=0): + super().__init__(xml_path_completion("robots/ur5e/robot.xml"), idn=idn) + + @property + def default_base(self): + return "RethinkMount" + + @property + def default_gripper(self): + return {"right": "Robotiq85Gripper"} + + @property + def default_controller_config(self): + return {"right": "default_ur5e"} + + @property + def init_qpos(self): + return np.array([-0.470, -1.735, 2.480, -2.275, -1.590, -1.991]) + + @property + def base_xpos_offset(self): + return { + "bins": (-0.5, -0.1, 0), + "empty": (-0.6, 0, 0), + "table": lambda table_length: (-0.16 - table_length / 2, 0, 0), + } + + @property + def top_offset(self): + return np.array((0, 0, 1.0)) + + @property + def _horizontal_radius(self): + return 0.5 + + @property + def arm_type(self): + return "single" diff --git a/third_party/robosuite/robosuite/models/robots/robot_model.py b/third_party/robosuite/robosuite/models/robots/robot_model.py new file mode 100644 index 0000000000000000000000000000000000000000..a988306bfde62cee66abbe93a65c5ba0f438a047 --- /dev/null +++ b/third_party/robosuite/robosuite/models/robots/robot_model.py @@ -0,0 +1,457 @@ +from copy import deepcopy +from typing import Dict, List, Optional + +import mujoco +import numpy as np + +from robosuite.models.base import MujocoXMLModel +from robosuite.models.bases import LegBaseModel, MobileBaseModel, MountModel, RobotBaseModel +from robosuite.utils.mjcf_utils import ROBOT_COLLISION_COLOR, array_to_string, find_elements, find_parent +from robosuite.utils.transform_utils import euler2mat, mat2quat + +REGISTERED_ROBOTS = {} + + +def register_robot(target_class): + REGISTERED_ROBOTS[target_class.__name__] = target_class + + +def create_robot(robot_name, *args, **kwargs): + """ + Instantiates a Robot object. + + Args: + robot_name (str): Name of the robot to initialize + *args: Additional arguments to pass to the specific Robot class initializer + **kwargs: Additional arguments to pass to the specific Robot class initializer + + Returns: + Robot: Desired robot + + Raises: + Exception: [Invalid robot name] + """ + if robot_name not in REGISTERED_ROBOTS: + raise Exception( + "Robot {} not found. Make sure it is a registered robot among: {}".format( + robot_name, ", ".join(REGISTERED_ROBOTS) + ) + ) + return REGISTERED_ROBOTS[robot_name](*args, **kwargs) + + +class RobotModelMeta(type): + """Metaclass for registering robot arms""" + + 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 = ["RobotModel", "ManipulatorModel"] + + if cls.__name__ not in _unregistered_envs: + register_robot(cls) + return cls + + +class RobotModel(MujocoXMLModel, metaclass=RobotModelMeta): + """ + Base class for all robot models. + + 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 robot instance + """ + + def __init__(self, fname: str, idn=0): + super().__init__(fname, idn=idn) + + # Define other variables that get filled later + self.base = None + + # Get camera names for this robot + self.cameras = self.get_element_names(self.worldbody, "camera") + + # By default, set small frictionloss and armature values + self.set_joint_attribute(attrib="frictionloss", values=0.1 * np.ones(self.dof), force=False) + self.set_joint_attribute(attrib="damping", values=0.1 * np.ones(self.dof), force=False) + self.set_joint_attribute( + attrib="armature", values=np.array([5.0 / (i + 1) for i in range(self.dof)]), force=False + ) + self.mujoco_model: Optional[mujoco.MjModel] = None + + def set_mujoco_model(self, mujoco_model: Optional[mujoco.MjModel] = None): + if mujoco_model is not None: + self.mujoco_model = mujoco_model + else: + self.mujoco_model = self.get_model() + + def set_base_xpos(self, pos: np.ndarray): + """ + Places the robot on position @pos. + + Args: + pos (3-array): (x,y,z) position to place robot base + """ + self._elements["root_body"].set("pos", array_to_string(pos - self.bottom_offset)) + + def set_base_ori(self, rot: np.ndarray): + """ + Rotates robot by rotation @rot from its original orientation. + + Args: + rot (3-array): (r,p,y) euler angles specifying the orientation for the robot base + """ + # xml quat assumes w,x,y,z so we need to convert to this format from outputted x,y,z,w format from fcn + rot = mat2quat(euler2mat(rot))[[3, 0, 1, 2]] + self._elements["root_body"].set("quat", array_to_string(rot)) + + def set_joint_attribute(self, attrib: str, values: np.ndarray, force=True): + """ + Sets joint attributes, e.g.: friction loss, damping, etc. + + Args: + attrib (str): Attribute to set for all joints + values (n-array): Values to set for each joint + force (bool): If True, will automatically override any pre-existing value. Otherwise, if a value already + exists for this value, it will be skipped + + Raises: + AssertionError: [Inconsistent dimension sizes] + """ + assert values.size == len(self._elements["joints"]), ( + "Error setting joint attributes: " + + "Values must be same size as joint dimension. Got {}, expected {}!".format(values.size, self.dof) + ) + for i, joint in enumerate(self._elements["joints"]): + if force or joint.get(attrib, None) is None: + joint.set(attrib, array_to_string(np.array([values[i]]))) + + def add_base(self, base: RobotBaseModel): + """ + Mounts a base to the robot. Bases are defined in robosuite.models.bases + """ + if isinstance(base, MountModel): + self.add_mount(base) + elif isinstance(base, MobileBaseModel): + self.add_mobile_base(base) + elif isinstance(base, LegBaseModel): + self.add_leg_base(base) + else: + raise ValueError("Invalid base type to add to robot!") + + def add_mount(self, mount: MountModel): + """ + Mounts @mount to arm. + + Throws error if robot already has a mount or if mount type i\s incorrect. + + Args: + mount (MountModel): mount MJCF model + + Raises: + ValueError: [mount already added] + """ + if self.base is not None: + raise ValueError("Mount already added for this robot!") + + # First adjust mount's base position + offset = self.base_offset - mount.top_offset + mount._elements["root_body"].set("pos", array_to_string(offset)) + + self.merge(mount, merge_body=self.root_body) + + self.base = mount + + # Update cameras in this model + self.cameras = self.get_element_names(self.worldbody, "camera") + + def add_mobile_base(self, mobile_base: MobileBaseModel): + """ + Mounts @mobile_base to arm. + + Throws error if robot already has a mobile base or if mobile base type is incorrect. + + Args: + mobile base (MobileBaseModel): mount MJCF model + + Raises: + ValueError: [mobile base already added] + """ + if self.base is not None: + raise ValueError("Mobile base already added for this robot!") + + # First adjust mount's base position + offset = self.base_offset - mobile_base.top_offset + mobile_base._elements["root_body"].set("pos", array_to_string(offset)) + + # if the mount is mobile, the robot should be "merged" into the mount, + # so that when the mount moves the robot moves along with it + merge_body = self.root_body + root = find_elements(root=self.worldbody, tags="body", attribs={"name": merge_body}, return_first=True) + for body in mobile_base.worldbody: + root.append(body) + arm_root = find_elements(root=self.worldbody, tags="body", return_first=False)[1] + + mount_support = find_elements( + root=self.worldbody, tags="body", attribs={"name": mobile_base.correct_naming("support")}, return_first=True + ) + mount_support.append(deepcopy(arm_root)) + root.remove(arm_root) + self.merge_assets(mobile_base) + for one_actuator in mobile_base.actuator: + self.actuator.append(one_actuator) + for one_sensor in mobile_base.sensor: + self.sensor.append(one_sensor) + for one_tendon in mobile_base.tendon: + self.tendon.append(one_tendon) + for one_equality in mobile_base.equality: + self.equality.append(one_equality) + for one_contact in mobile_base.contact: + self.contact.append(one_contact) + + self.base = mobile_base + + # Update cameras in this model + self.cameras = self.get_element_names(self.worldbody, "camera") + + def add_leg_base(self, leg_base: LegBaseModel): + """ + Mounts @mobile_base to arm. + + Throws error if robot already has a mobile base or if mobile base type is incorrect. + + Args: + mobile base (MobileBaseModel): mount MJCF model + + Raises: + ValueError: [mobile base already added] + """ + if self.base is not None: + raise ValueError("Mobile base already added for this robot!") + + # First adjust mount's base position + offset = self.base_offset - leg_base.top_offset + leg_base._elements["root_body"].set("pos", array_to_string(offset)) + + # if the mount is mobile, the robot should be "merged" into the mount, + # so that when the mount moves the robot moves along with it + merge_body = self.root_body + root = find_elements(root=self.worldbody, tags="body", return_first=True) + for body in leg_base.worldbody: + root.append(body) + # import pdb; pdb.set_trace() + + arm_root = find_elements(root=self.worldbody, tags="body", return_first=False)[1] + + mount_support = find_elements( + root=leg_base.worldbody, + tags="body", + attribs={"name": leg_base.correct_naming("support")}, + return_first=True, + ) + + free_joint = find_elements(root=leg_base.worldbody, tags="freejoint", return_first=True) + if free_joint is not None: + root.append(deepcopy(free_joint)) + free_joint_parent = find_parent(leg_base.worldbody, free_joint) + free_joint_parent.remove(free_joint) + mount_support.append(deepcopy(arm_root)) + root.remove(arm_root) + self.merge_assets(leg_base) + for one_actuator in leg_base.actuator: + self.actuator.append(one_actuator) + for one_sensor in leg_base.sensor: + self.sensor.append(one_sensor) + for one_tendon in leg_base.tendon: + self.tendon.append(one_tendon) + for one_equality in leg_base.equality: + self.equality.append(one_equality) + for one_contact in leg_base.contact: + self.contact.append(one_contact) + + self.base = leg_base + + # Update cameras in this model + self.cameras = self.get_element_names(self.worldbody, "camera") + + # -------------------------------------------------------------------------------------- # + # Public Properties: In general, these are the name-adjusted versions from the private # + # attributes pulled from their respective raw xml files # + # -------------------------------------------------------------------------------------- # + + @property + def naming_prefix(self) -> str: + return "robot{}_".format(self.idn) + + @property + def dof(self) -> int: + """ + Defines the number of DOF of the robot + + Returns: + int: robot DOF + """ + return len(self._joints) + + @property + def bottom_offset(self) -> np.ndarray: + """ + Returns vector from model root body to model bottom. + By default, this is equivalent to this robot's mount's (bottom_offset - top_offset) + this robot's base offset + + Returns: + np.array: (dx, dy, dz) offset vector + """ + return ( + (self.base.bottom_offset - self.base.top_offset) + self._base_offset + if self.base is not None + else self._base_offset + ) + + @property + def horizontal_radius(self) -> float: + """ + Returns maximum distance from model root body to any radial point of the model. This method takes into + account the mount horizontal radius as well + + Returns: + float: radius + """ + return max(self._horizontal_radius, self.base.horizontal_radius) + + @property + def models(self) -> List[MujocoXMLModel]: + """ + Returns a list of all m(sub-)models owned by this robot model. By default, this includes the mount model, + if specified + + Returns: + list: models owned by this object + """ + return [self.base] if self.base is not None else [] + + @property + def contact_geom_rgba(self): + return ROBOT_COLLISION_COLOR + + # -------------------------------------------------------------------------------------- # + # All subclasses must implement the following properties # + # -------------------------------------------------------------------------------------- # + + @property + def default_base(self) -> str: + """ + Defines the default mount type for this robot that gets added to root body (base) + + Returns: + str: Default base name to add to this robot + """ + raise NotImplementedError + + @property + def default_controller_config(self) -> Dict[str, str]: + """ + Defines the name of default controller config file in the controllers/config directory for this robot. + + Returns: + dict: Dictionary containing arm-specific default controller config names + e.g.: {"right": "default_panda", "left": "default_panda"} + """ + raise NotImplementedError + + @property + def init_qpos(self) -> np.ndarray: + """ + Defines the default rest qpos of this robot + + Returns: + np.array: Default init qpos of this robot + """ + raise NotImplementedError + + @property + def base_xpos_offset(self) -> Dict[str, np.ndarray]: + """ + Defines the dict of various (x,y,z) tuple offsets relative to specific arenas placed at (0,0,0) + Assumes robot is facing forwards (in the +x direction) when determining offset. Should have entries for each + arena case; i.e.: "bins", "empty", and "table") + + Returns: + dict: Dict mapping arena names to robot offsets from the global origin (dict entries may also be lambdas + for variable offsets) + """ + raise NotImplementedError + + @property + def top_offset(self) -> np.ndarray: + """ + 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) -> 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 + + @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 all_joints(self) -> List: + """ + Returns: + list: (Default is no joints; i.e.: empty list) + """ + all_joints = [] + all_joints += self.joints + if self.base is not None: + all_joints += self.base.joints + return all_joints + + @property + def all_actuators(self) -> List: + """ + Returns: + list: (Default is no actuators; i.e.: empty list) + """ + all_actuators = [] + all_actuators += self.actuators + if self.base is not None: + all_actuators += self.base.actuators + return all_actuators diff --git a/third_party/robosuite/robosuite/models/tasks/__init__.py b/third_party/robosuite/robosuite/models/tasks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f92c679f3dc810b4870bcc4c30b185299c2da5fd --- /dev/null +++ b/third_party/robosuite/robosuite/models/tasks/__init__.py @@ -0,0 +1,2 @@ +from .task import Task +from .manipulation_task import ManipulationTask diff --git a/third_party/robosuite/robosuite/models/tasks/manipulation_task.py b/third_party/robosuite/robosuite/models/tasks/manipulation_task.py new file mode 100644 index 0000000000000000000000000000000000000000..8309e2420d1145be40b9c3872743f2939d6b061a --- /dev/null +++ b/third_party/robosuite/robosuite/models/tasks/manipulation_task.py @@ -0,0 +1,7 @@ +from robosuite.models.tasks.task import Task + + +class ManipulationTask(Task): + """ + A manipulation-specific task. This is currently a future-proofing placeholder. + """ diff --git a/third_party/robosuite/robosuite/models/tasks/task.py b/third_party/robosuite/robosuite/models/tasks/task.py new file mode 100644 index 0000000000000000000000000000000000000000..658fc2f3fd463d8a3bde4ffd1f7496c3070ab7bc --- /dev/null +++ b/third_party/robosuite/robosuite/models/tasks/task.py @@ -0,0 +1,191 @@ +from copy import deepcopy + +from robosuite.models.objects import MujocoObject +from robosuite.models.robots import RobotModel +from robosuite.models.world import MujocoWorldBase +from robosuite.utils.mjcf_utils import get_ids + + +class Task(MujocoWorldBase): + """ + Creates MJCF model for a task performed. + + A task consists of one or more robots interacting with a variable number of + objects. This class combines the robot(s), the arena, and the objects + into a single MJCF model. + + Args: + mujoco_arena (Arena): MJCF model of robot workspace + + mujoco_robots (RobotModel or list of RobotModel): MJCF model of robot model(s) (list) + + mujoco_objects (None or MujocoObject or list of MujocoObject): a list of MJCF models of physical objects + + Raises: + AssertionError: [Invalid input object type] + """ + + def __init__( + self, + mujoco_arena, + mujoco_robots, + mujoco_objects=None, + ): + super().__init__() + + # Store references to all models + self.mujoco_arena = mujoco_arena + self.mujoco_robots = [mujoco_robots] if isinstance(mujoco_robots, RobotModel) else mujoco_robots + if mujoco_objects is None: + self.mujoco_objects = [] + else: + self.mujoco_objects = [mujoco_objects] if isinstance(mujoco_objects, MujocoObject) else mujoco_objects + + # Merge all models + self.merge_arena(self.mujoco_arena) + for mujoco_robot in self.mujoco_robots: + self.merge_robot(mujoco_robot) + self.merge_objects(self.mujoco_objects) + + self._instances_to_ids = None + self._geom_ids_to_instances = None + self._site_ids_to_instances = None + self._classes_to_ids = None + self._geom_ids_to_classes = None + self._site_ids_to_classes = None + + def merge_robot(self, mujoco_robot): + """ + Adds robot model to the MJCF model. + + Args: + mujoco_robot (RobotModel): robot to merge into this MJCF model + """ + self.merge(mujoco_robot) + + def merge_arena(self, mujoco_arena): + """ + Adds arena model to the MJCF model. + + Args: + mujoco_arena (Arena): arena to merge into this MJCF model + """ + self.merge(mujoco_arena) + + def merge_objects(self, mujoco_objects): + """ + Adds object models to the MJCF model. + + Args: + mujoco_objects (list of MujocoObject): objects to merge into this MJCF model + """ + for mujoco_obj in mujoco_objects: + # Make sure we actually got a MujocoObject + assert isinstance(mujoco_obj, MujocoObject), "Tried to merge non-MujocoObject! Got type: {}".format( + type(mujoco_obj) + ) + # Merge this object + self.merge_assets(mujoco_obj) + self.worldbody.append(mujoco_obj.get_obj()) + + def generate_id_mappings(self, sim): + """ + Generates IDs mapping class instances to set of (visual) geom IDs corresponding to that class instance + + Args: + sim (MjSim): Current active mujoco simulation object + """ + self._instances_to_ids = {} + self._geom_ids_to_instances = {} + self._site_ids_to_instances = {} + self._classes_to_ids = {} + self._geom_ids_to_classes = {} + self._site_ids_to_classes = {} + + models = [model for model in self.mujoco_objects] + for robot in self.mujoco_robots: + models += [robot] + robot.models + + # Parse all mujoco models from robots and objects + for model in models: + # Grab model class name and visual IDs + cls = str(type(model)).split("'")[1].split(".")[-1] + inst = model.name + id_groups = [ + get_ids(sim=sim, elements=model.visual_geoms + model.contact_geoms, element_type="geom"), + get_ids(sim=sim, elements=model.sites, element_type="site"), + ] + group_types = ("geom", "site") + ids_to_instances = (self._geom_ids_to_instances, self._site_ids_to_instances) + ids_to_classes = (self._geom_ids_to_classes, self._site_ids_to_classes) + + # Add entry to mapping dicts + + # Instances should be unique + assert inst not in self._instances_to_ids, f"Instance {inst} already registered; should be unique" + self._instances_to_ids[inst] = {} + + # Classes may not be unique + if cls not in self._classes_to_ids: + self._classes_to_ids[cls] = {group_type: [] for group_type in group_types} + + for ids, group_type, ids_to_inst, ids_to_cls in zip( + id_groups, group_types, ids_to_instances, ids_to_classes + ): + # Add geom, site ids + self._instances_to_ids[inst][group_type] = ids + self._classes_to_ids[cls][group_type] += ids + + # Add reverse mappings as well + for idn in ids: + assert idn not in ids_to_inst, f"ID {idn} already registered; should be unique" + ids_to_inst[idn] = inst + ids_to_cls[idn] = cls + + @property + def geom_ids_to_instances(self): + """ + Returns: + dict: Mapping from geom IDs in sim to specific class instance names + """ + return deepcopy(self._geom_ids_to_instances) + + @property + def site_ids_to_instances(self): + """ + Returns: + dict: Mapping from site IDs in sim to specific class instance names + """ + return deepcopy(self._site_ids_to_instances) + + @property + def instances_to_ids(self): + """ + Returns: + dict: Mapping from specific class instance names to {geom, site} IDs in sim + """ + return deepcopy(self._instances_to_ids) + + @property + def geom_ids_to_classes(self): + """ + Returns: + dict: Mapping from geom IDs in sim to specific classes + """ + return deepcopy(self._geom_ids_to_classes) + + @property + def site_ids_to_classes(self): + """ + Returns: + dict: Mapping from site IDs in sim to specific classes + """ + return deepcopy(self._site_ids_to_classes) + + @property + def classes_to_ids(self): + """ + Returns: + dict: Mapping from specific classes to {geom, site} IDs in sim + """ + return deepcopy(self._classes_to_ids) diff --git a/third_party/robosuite/robosuite/models/world.py b/third_party/robosuite/robosuite/models/world.py new file mode 100644 index 0000000000000000000000000000000000000000..ee2f265d374dd0e9a7e2586176c0758a91f015dc --- /dev/null +++ b/third_party/robosuite/robosuite/models/world.py @@ -0,0 +1,13 @@ +import robosuite.macros as macros +from robosuite.models.base import MujocoXML +from robosuite.utils.mjcf_utils import convert_to_string, find_elements, xml_path_completion + + +class MujocoWorldBase(MujocoXML): + """Base class to inherit all mujoco worlds from.""" + + def __init__(self): + super().__init__(xml_path_completion("base.xml")) + # Modify the simulation timestep to be the requested value + options = find_elements(root=self.root, tags="option", attribs=None, return_first=True) + options.set("timestep", convert_to_string(macros.SIMULATION_TIMESTEP)) diff --git a/third_party/robosuite/robosuite/renderers/__init__.py b/third_party/robosuite/robosuite/renderers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6ac7004e9d49e6122425170c97027b242029305c --- /dev/null +++ b/third_party/robosuite/robosuite/renderers/__init__.py @@ -0,0 +1 @@ +from .base import load_renderer_config diff --git a/third_party/robosuite/robosuite/renderers/base.py b/third_party/robosuite/robosuite/renderers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..030592cd1f54e0fc339c20780ce510dc4c946f87 --- /dev/null +++ b/third_party/robosuite/robosuite/renderers/base.py @@ -0,0 +1,64 @@ +""" +This file contains the base renderer class for Mujoco environments. +""" + +import abc +import json +import os + + +def load_renderer_config(renderer): + """Loads the config of the specified renderer. + Modify the dictionary returned by this function + according to reuirements. + + Args: + renderer (str): Name of the renderer to use. + + Returns: + dict: renderer default config. + """ + return {} + + +class Renderer: + """ + Base class for all robosuite renderers + Defines basic interface for all renderers to adhere to + """ + + def __init__(self, env, renderer_type="mujoco"): + self.env = env + self.renderer_type = renderer_type + + def __str__(self): + """Prints the renderer type in a formatted way + + Returns: + str: string representing the renderer + """ + return f'' + + @abc.abstractmethod + def render(self, **kwargs): + """Renders the current state with the specified renderer""" + raise NotImplementedError + + @abc.abstractmethod + def close(self): + """Closes the renderer objects""" + raise NotImplementedError + + @abc.abstractmethod + def reset(self): + """Reset the renderer with initial states for environment""" + raise NotImplementedError + + @abc.abstractmethod + def get_pixel_obs(self): + """Get the pixel observations from the given renderer + + Returns: + numpyarr: numpy array representing pixels of renderer + """ + raise NotImplementedError diff --git a/third_party/robosuite/robosuite/renderers/base_parser.py b/third_party/robosuite/robosuite/renderers/base_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..7e0ff7aed6f533b60a3aa2f8914cb3fa5db1bf04 --- /dev/null +++ b/third_party/robosuite/robosuite/renderers/base_parser.py @@ -0,0 +1,55 @@ +import abc +import xml.etree.ElementTree as ET + + +class BaseParser(object): + """ + Base class for Parser objects used by renderers. + """ + + def __init__(self, renderer, env): + """ + Parse the mujoco xml and initialize iG renderer objects. + + Args: + renderer: the renderer + env : Mujoco env + """ + + self.renderer = renderer + self.env = env + self.xml_root = ET.fromstring(self.env.sim.model.get_xml()) + self.parent_map = {c: p for p in self.xml_root.iter() for c in p} + self.visual_objects = {} + + @abc.abstractmethod + def parse_textures(self): + """ + Parse and load all textures and store them + """ + raise NotImplementedError + + @abc.abstractmethod + def parse_materials(self): + """ + Parse all materials and use texture mapping to initialize materials + """ + raise NotImplementedError + + def parse_cameras(self): + """ + Parse cameras and initialize the cameras. + """ + raise NotImplementedError + + def parse_meshes(self): + """ + Create mapping of meshes. + """ + raise NotImplementedError + + def parse_geometries(self): + """ + Iterate through each geometry and load it in the renderer. + """ + raise NotImplementedError diff --git a/third_party/robosuite/robosuite/renderers/context/__init__.py b/third_party/robosuite/robosuite/renderers/context/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third_party/robosuite/robosuite/renderers/context/egl_context.py b/third_party/robosuite/robosuite/renderers/context/egl_context.py new file mode 100644 index 0000000000000000000000000000000000000000..093953947d1962c0f2cd67fcb5e8ed588c77e741 --- /dev/null +++ b/third_party/robosuite/robosuite/renderers/context/egl_context.py @@ -0,0 +1,159 @@ +# Modifications Copyright 2025 The robosuite Authors +# Original Copyright 2018 The dm_control Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +import atexit +import ctypes +import os + +PYOPENGL_PLATFORM = os.environ.get("PYOPENGL_PLATFORM") + +if not PYOPENGL_PLATFORM: + os.environ["PYOPENGL_PLATFORM"] = "egl" +elif PYOPENGL_PLATFORM.lower() != "egl": + raise ImportError( + "Cannot use EGL rendering platform. " + "The PYOPENGL_PLATFORM environment variable is set to {!r} " + "(should be either unset or 'egl')." + ) + +from mujoco.egl import egl_ext as EGL +from OpenGL import error + + +def create_initialized_egl_device_display(device_id=0): + """Creates an initialized EGL display directly on a device.""" + all_devices = EGL.eglQueryDevicesEXT() + selected_device = ( + os.environ.get("CUDA_VISIBLE_DEVICES", None) + if os.environ.get("MUJOCO_EGL_DEVICE_ID", None) is None + else os.environ.get("MUJOCO_EGL_DEVICE_ID", None) + ) + if selected_device is None: + candidates = all_devices + if device_id == -1: + device_idx = 0 + else: + device_idx = device_id + else: + if not selected_device.isdigit(): + device_inds = [int(x) for x in selected_device.split(",")] + if device_id == -1: + device_idx = device_inds[0] + else: + assert device_id in device_inds, "specified device id is not made visible in environment variables." + device_idx = device_id + else: + device_idx = int(selected_device) + if not 0 <= device_idx < len(all_devices): + raise RuntimeError( + f"The MUJOCO_EGL_DEVICE_ID environment variable must be an integer " + f"between 0 and {len(all_devices)-1} (inclusive), got {device_idx}." + ) + candidates = all_devices[device_idx : device_idx + 1] + for device in candidates: + display = EGL.eglGetPlatformDisplayEXT(EGL.EGL_PLATFORM_DEVICE_EXT, device, None) + if display != EGL.EGL_NO_DISPLAY and EGL.eglGetError() == EGL.EGL_SUCCESS: + # `eglInitialize` may or may not raise an exception on failure depending + # on how PyOpenGL is configured. We therefore catch a `GLError` and also + # manually check the output of `eglGetError()` here. + try: + initialized = EGL.eglInitialize(display, None, None) + except error.GLError: + pass + else: + if initialized == EGL.EGL_TRUE and EGL.eglGetError() == EGL.EGL_SUCCESS: + return display + return EGL.EGL_NO_DISPLAY + + +global EGL_DISPLAY +EGL_DISPLAY = None + +EGL_ATTRIBUTES = ( + EGL.EGL_RED_SIZE, + 8, + EGL.EGL_GREEN_SIZE, + 8, + EGL.EGL_BLUE_SIZE, + 8, + EGL.EGL_ALPHA_SIZE, + 8, + EGL.EGL_DEPTH_SIZE, + 24, + EGL.EGL_STENCIL_SIZE, + 8, + EGL.EGL_COLOR_BUFFER_TYPE, + EGL.EGL_RGB_BUFFER, + EGL.EGL_SURFACE_TYPE, + EGL.EGL_PBUFFER_BIT, + EGL.EGL_RENDERABLE_TYPE, + EGL.EGL_OPENGL_BIT, + EGL.EGL_NONE, +) + + +class EGLGLContext: + """An EGL context for headless accelerated OpenGL rendering on GPU devices.""" + + def __init__(self, max_width, max_height, device_id=0): + + del max_width, max_height # unused + num_configs = ctypes.c_long() + config_size = 1 + config_ptr = EGL.EGLConfig() # Makes an opaque pointer + EGL.eglReleaseThread() + global EGL_DISPLAY + if EGL_DISPLAY is None: + # only initialize for the first time + EGL_DISPLAY = create_initialized_egl_device_display(device_id=device_id) + if EGL_DISPLAY == EGL.EGL_NO_DISPLAY: + raise ImportError( + "Cannot initialize a EGL device display. This likely means that your EGL " + "driver does not support the PLATFORM_DEVICE extension, which is " + "required for creating a headless rendering context." + ) + atexit.register(EGL.eglTerminate, EGL_DISPLAY) + EGL.eglChooseConfig(EGL_DISPLAY, EGL_ATTRIBUTES, config_ptr, config_size, num_configs) + if num_configs.value < 1: + raise RuntimeError( + "EGL failed to find a framebuffer configuration that matches the " + "desired attributes: {}".format(EGL_ATTRIBUTES) + ) + EGL.eglBindAPI(EGL.EGL_OPENGL_API) + self._context = EGL.eglCreateContext(EGL_DISPLAY, config_ptr, EGL.EGL_NO_CONTEXT, None) + if not self._context: + raise RuntimeError("Cannot create an EGL context.") + + def make_current(self): + if not EGL.eglMakeCurrent(EGL_DISPLAY, EGL.EGL_NO_SURFACE, EGL.EGL_NO_SURFACE, self._context): + raise RuntimeError("Failed to make the EGL context current.") + + def free(self): + """Frees resources associated with this context.""" + if self._context: + current_context = EGL.eglGetCurrentContext() + if current_context and self._context.address == current_context.address: + EGL.eglMakeCurrent(EGL_DISPLAY, EGL.EGL_NO_SURFACE, EGL.EGL_NO_SURFACE, EGL.EGL_NO_CONTEXT) + EGL.eglDestroyContext(EGL_DISPLAY, self._context) + EGL.eglReleaseThread() + self._context = None + + def __del__(self): + try: + self.free() + except Exception: + # avoid getting OpenGL.error.GLError + pass diff --git a/third_party/robosuite/robosuite/renderers/context/glfw_context.py b/third_party/robosuite/robosuite/renderers/context/glfw_context.py new file mode 100644 index 0000000000000000000000000000000000000000..087fe0d496833c489bc4debb652a08228cc7b0bf --- /dev/null +++ b/third_party/robosuite/robosuite/renderers/context/glfw_context.py @@ -0,0 +1,24 @@ +# Copyright 2017 The dm_control Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""An OpenGL context created via GLFW.""" + +from mujoco.glfw import GLContext + + +class GLFWGLContext(GLContext): + """An OpenGL context created via GLFW.""" + + def __init__(self, max_width, max_height, device_id=0): + super().__init__(max_width, max_height) diff --git a/third_party/robosuite/robosuite/renderers/context/osmesa_context.py b/third_party/robosuite/robosuite/renderers/context/osmesa_context.py new file mode 100644 index 0000000000000000000000000000000000000000..b2c8918cc270a7853cb5af7df15ac8ea00019031 --- /dev/null +++ b/third_party/robosuite/robosuite/renderers/context/osmesa_context.py @@ -0,0 +1,26 @@ +# Copyright 2018 The dm_control Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""An OSMesa context for software-based OpenGL rendering.""" + +import os + +from mujoco.osmesa import GLContext + + +class OSMesaGLContext(GLContext): + """An OSMesa context for software-based OpenGL rendering.""" + + def __init__(self, max_width, max_height, device_id=-1): + super().__init__(max_width, max_height) diff --git a/third_party/robosuite/robosuite/renderers/mjviewer/__init__.py b/third_party/robosuite/robosuite/renderers/mjviewer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/third_party/robosuite/robosuite/renderers/mjviewer/mjviewer_renderer.py b/third_party/robosuite/robosuite/renderers/mjviewer/mjviewer_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..3f8c8b50c92211c9c6ce7a4fa3975c31430864e7 --- /dev/null +++ b/third_party/robosuite/robosuite/renderers/mjviewer/mjviewer_renderer.py @@ -0,0 +1,63 @@ +from mujoco import viewer + +DEFAULT_FREE_CAM = { + "lookat": [0, 0, 1], + "distance": 2, + "azimuth": 180, + "elevation": -20, +} + + +class MjviewerRenderer: + def __init__(self, env, camera_id=None, cam_config=None): + if cam_config is None: + cam_config = DEFAULT_FREE_CAM + self.env = env + self.camera_id = camera_id + self.viewer = None + self.camera_config = cam_config + + def render(self): + pass + + def set_camera(self, camera_id): + self.camera_id = camera_id + + def update(self): + if self.viewer is None: + self.viewer = viewer.launch_passive( + self.env.sim.model._model, + self.env.sim.data._data, + show_left_ui=False, + show_right_ui=False, + ) + + self.viewer.opt.geomgroup[0] = 0 + + if self.camera_config is not None: + self.viewer.cam.lookat = self.camera_config["lookat"] + self.viewer.cam.distance = self.camera_config["distance"] + self.viewer.cam.azimuth = self.camera_config["azimuth"] + self.viewer.cam.elevation = self.camera_config["elevation"] + + if self.camera_id is not None: + if self.camera_id >= 0: + self.viewer.cam.type = 2 + self.viewer.cam.fixedcamid = self.camera_id + else: + self.viewer.cam.type = 0 + + self.viewer.sync() + + def reset(self): + pass + + def close(self): + + self.sim = None + if self.viewer is not None: + self.viewer.close() + self.viewer = None + + def add_keypress_callback(self, keypress_callback): + self.keypress_callback = keypress_callback diff --git a/third_party/robosuite/robosuite/robots/__init__.py b/third_party/robosuite/robosuite/robots/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d58a193186fc41bde72c96ea8a82b9291d7dbc30 --- /dev/null +++ b/third_party/robosuite/robosuite/robots/__init__.py @@ -0,0 +1,50 @@ +from .fixed_base_robot import FixedBaseRobot +from .mobile_robot import MobileRobot +from .wheeled_robot import WheeledRobot +from .legged_robot import LeggedRobot + +from robosuite.models.robots.robot_model import REGISTERED_ROBOTS + +from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER + +ALL_ROBOTS = REGISTERED_ROBOTS.keys() + +# Robot class mappings -- must be maintained manually +# These are the main robot used. Remaining robots are located in +# https://github.com/ARISE-Initiative/robosuite_models +ROBOT_CLASS_MAPPING = { + "Baxter": FixedBaseRobot, + "IIWA": FixedBaseRobot, + "Jaco": FixedBaseRobot, + "Kinova3": FixedBaseRobot, + "Panda": FixedBaseRobot, + "Sawyer": FixedBaseRobot, + "UR5e": FixedBaseRobot, + "SpotWithArm": LeggedRobot, + "SpotWithArmFloating": LeggedRobot, + "PandaOmron": WheeledRobot, + "Tiago": WheeledRobot, + "GR1": LeggedRobot, + "GR1FixedLowerBody": LeggedRobot, + "GR1ArmsOnly": LeggedRobot, + "GR1FloatingBody": LeggedRobot, + "PandaDexRH": FixedBaseRobot, + "PandaDexLH": FixedBaseRobot, +} + +target_type_mapping = { + "FixedBaseRobot": FixedBaseRobot, + "MobileRobot": MobileRobot, + "WheeledRobot": WheeledRobot, + "LeggedRobot": LeggedRobot, +} + + +def register_robot_class(target_type, **kwargs): + def decorator(target_class): + # Store the class in the registry with additional arguments + ROBOT_CLASS_MAPPING.update({target_class.__name__: target_type_mapping[target_type]}) + + return target_class # Return the class itself + + return decorator diff --git a/third_party/robosuite/robosuite/robots/fixed_base_robot.py b/third_party/robosuite/robosuite/robots/fixed_base_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..430bc5fd5972d3a294fb26c0d3c4c7d02a6130a0 --- /dev/null +++ b/third_party/robosuite/robosuite/robots/fixed_base_robot.py @@ -0,0 +1,216 @@ +import copy +import os +from collections import OrderedDict + +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.controllers import composite_controller_factory +from robosuite.robots.robot import Robot + + +class FixedBaseRobot(Robot): + """ + Initializes a robot with a fixed base. + """ + + def __init__( + self, + robot_type: str, + idn=0, + composite_controller_config=None, + initial_qpos=None, + initialization_noise=None, + base_type="default", + gripper_type="default", + control_freq=20, + lite_physics=True, + ): + super().__init__( + robot_type=robot_type, + idn=idn, + composite_controller_config=composite_controller_config, + initial_qpos=initial_qpos, + initialization_noise=initialization_noise, + base_type=base_type, + gripper_type=gripper_type, + control_freq=control_freq, + lite_physics=lite_physics, + ) + + def _load_controller(self): + """ + Loads controller to be used for dynamic trajectories + """ + # Flag for loading urdf once (only applicable for IK controllers) + self.composite_controller = composite_controller_factory( + type=self.composite_controller_config.get("type", "BASIC"), + sim=self.sim, + robot_model=self.robot_model, + grippers={self.get_gripper_name(arm): self.gripper[arm] for arm in self.arms}, + ) + self._load_arm_controllers() + + self._postprocess_part_controller_config() + self.composite_controller.load_controller_config( + self.part_controller_config, + self.composite_controller_config.get("composite_controller_specific_configs", {}), + ) + + self.enable_parts() + + def load_model(self): + """ + Loads robot and optionally add grippers. + """ + # First, run the superclass method to load the relevant model + super().load_model() + + def reset(self, deterministic=False): + """ + Sets initial pose of arm and grippers. Overrides gripper joint configuration if we're using a + deterministic reset (e.g.: hard reset from xml file) + + Args: + deterministic (bool): If true, will not randomize initializations within the sim + """ + # First, run the superclass method to reset the position and controller + super().reset(deterministic) + + def setup_references(self): + """ + Sets up necessary reference for robots, grippers, and objects. + + Note that this should get called during every reset from the environment + """ + # First, run the superclass method to setup references for joint-related values / indexes + super().setup_references() + + # Now, add references to gripper if necessary + # indices for grippers in qpos, qvel + for arm in self.arms: + (start, end) = (None, self._joint_split_idx) if arm == "right" else (self._joint_split_idx, None) + self._ref_joints_indexes_dict[arm] = [ + self.sim.model.joint_name2id(joint) for joint in self.robot_model.arm_joints[start:end] + ] + self._ref_actuators_indexes_dict[arm] = [ + self.sim.model.actuator_name2id(joint) for joint in self.robot_model.arm_actuators[start:end] + ] + if self.has_gripper[arm]: + self.gripper_joints[arm] = list(self.gripper[arm].joints) + self._ref_gripper_joint_pos_indexes[arm] = [ + self.sim.model.get_joint_qpos_addr(x) for x in self.gripper_joints[arm] + ] + self._ref_gripper_joint_vel_indexes[arm] = [ + self.sim.model.get_joint_qvel_addr(x) for x in self.gripper_joints[arm] + ] + self._ref_joint_gripper_actuator_indexes[arm] = [ + self.sim.model.actuator_name2id(actuator) for actuator in self.gripper[arm].actuators + ] + self._ref_joints_indexes_dict[self.get_gripper_name(arm)] = [ + self.sim.model.joint_name2id(joint) for joint in self.gripper_joints[arm] + ] + self._ref_actuators_indexes_dict[self.get_gripper_name(arm)] = self._ref_joint_gripper_actuator_indexes[ + arm + ] + + # IDs of sites for eef visualization + self.eef_site_id[arm] = self.sim.model.site_name2id(self.gripper[arm].important_sites["grip_site"]) + self.eef_cylinder_id[arm] = self.sim.model.site_name2id(self.gripper[arm].important_sites["grip_cylinder"]) + + def control(self, action, policy_step=False): + """ + Actuate the robot with the + passed joint velocities and gripper control. + + Args: + action (np.array): The control to apply to the robot. The first @self.robot_model.dof dimensions should + be the desired normalized joint velocities and if the robot has a gripper, the next @self.gripper.dof + dimensions should be actuation controls for the gripper. + + :NOTE: Assumes inputted actions are of form: + [right_arm_control, right_gripper_control, left_arm_control, left_gripper_control] + + policy_step (bool): Whether a new policy step (action) is being taken + + Raises: + AssertionError: [Invalid action dimension] + """ + # clip actions into valid range + assert len(action) == self.action_dim, "environment got invalid action dimension -- expected {}, got {}".format( + self.action_dim, len(action) + ) + + self.composite_controller.update_state() + if policy_step: + self.composite_controller.set_goal(action) + + applied_action_dict = self.composite_controller.run_controller(self._enabled_parts) + for part_name, applied_action in applied_action_dict.items(): + applied_action_low = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[part_name], 0] + applied_action_high = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[part_name], 1] + applied_action = np.clip(applied_action, applied_action_low, applied_action_high) + self.sim.data.ctrl[self._ref_actuators_indexes_dict[part_name]] = applied_action + + if policy_step: + # Update proprioceptive values + self.recent_qpos.push(self._joint_positions) + self.recent_actions.push(action) + self.recent_torques.push(self.torques) + + for arm in self.arms: + controller = self.part_controllers[arm] + # Update arm-specific proprioceptive values + self.recent_ee_forcetorques[arm].push(np.concatenate((self.ee_force[arm], self.ee_torque[arm]))) + self.recent_ee_pose[arm].push(np.concatenate((controller.ref_pos, T.mat2quat(controller.ref_ori_mat)))) + self.recent_ee_vel[arm].push(np.concatenate((controller.ref_pos_vel, controller.ref_ori_vel))) + + # Estimation of eef acceleration (averaged derivative of recent velocities) + self.recent_ee_vel_buffer[arm].push(np.concatenate((controller.ref_pos_vel, controller.ref_ori_vel))) + diffs = np.vstack( + [ + self.recent_ee_acc[arm].current, + self.control_freq * np.diff(self.recent_ee_vel_buffer[arm].buf, axis=0), + ] + ) + ee_acc = np.array([np.convolve(col, np.ones(10) / 10.0, mode="valid")[0] for col in diffs.transpose()]) + self.recent_ee_acc[arm].push(ee_acc) + + def setup_observables(self): + """ + Sets up observables to be used for this robot + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + # Get general robot observables first + observables = super().setup_observables() + + return observables + + @property + def action_limits(self): + """ + Action lower/upper limits per dimension. + + Returns: + 2-tuple: + + - (np.array) minimum (low) action values + - (np.array) maximum (high) action values + """ + return self.composite_controller.action_limits + + @property + def is_mobile(self): + return False + + @property + def _action_split_indexes(self): + """ + Dictionary of split indexes for each part of the robot + + Returns: + dict: Dictionary of split indexes for each part of the robot + """ + return self.composite_controller._action_split_indexes diff --git a/third_party/robosuite/robosuite/robots/legged_robot.py b/third_party/robosuite/robosuite/robots/legged_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..8d89431b5d6151c618ce8d8fe61ceb6911a68e48 --- /dev/null +++ b/third_party/robosuite/robosuite/robots/legged_robot.py @@ -0,0 +1,253 @@ +import copy +import os +import time +from collections import OrderedDict +from typing import Dict, List + +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.controllers import composite_controller_factory, load_part_controller_config +from robosuite.models.bases.leg_base_model import LegBaseModel +from robosuite.robots.mobile_robot import MobileRobot +from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER +from robosuite.utils.observables import sensor + + +class LeggedRobot(MobileRobot): + """ + Initializes a robot with a wheeled base. + """ + + def __init__( + self, + robot_type: str, + idn=0, + composite_controller_config=None, + initial_qpos=None, + initialization_noise=None, + base_type="default", + gripper_type="default", + control_freq=20, + lite_physics=True, + ): + super().__init__( + robot_type=robot_type, + idn=idn, + composite_controller_config=composite_controller_config, + initial_qpos=initial_qpos, + initialization_noise=initialization_noise, + base_type=base_type, + gripper_type=gripper_type, + control_freq=control_freq, + lite_physics=lite_physics, + ) + + def _load_leg_controllers(self): + if len(self._ref_actuators_indexes_dict[self.legs]) == 0: + return None + + assert self.legs is not None, ( + "Legs must be defined for legged robots in part_controller_config. " + "Please specify legs in controller configs." + ) + assert ( + type(self.part_controller_config[self.legs]) == dict + ), "Inputted controller config must be a dict! Instead, got type: {}".format( + type(self.part_controller_config[self.legs]) + ) + self.part_controller_config[self.legs] = {} + self.part_controller_config[self.legs]["ramp_ratio"] = 1.0 + self.part_controller_config[self.legs]["robot_name"] = self.name + + self.part_controller_config[self.legs]["sim"] = self.sim + self.part_controller_config[self.legs]["part_name"] = self.legs + self.part_controller_config[self.legs]["naming_prefix"] = self.robot_model.base.naming_prefix + self.part_controller_config[self.legs]["ndim"] = self.num_leg_joints + self.part_controller_config[self.legs]["policy_freq"] = self.control_freq + + ref_legs_joint_indexes = [self.sim.model.joint_name2id(x) for x in self.robot_model.legs_joints] + ref_legs_joint_pos_indexes = [self.sim.model.get_joint_qpos_addr(x) for x in self.robot_model.legs_joints] + ref_legs_joint_vel_indexes = [self.sim.model.get_joint_qvel_addr(x) for x in self.robot_model.legs_joints] + self.part_controller_config[self.legs]["joint_indexes"] = { + "joints": ref_legs_joint_indexes, + "qpos": ref_legs_joint_pos_indexes, + "qvel": ref_legs_joint_vel_indexes, + } + + low = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.legs], 0] + high = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.legs], 1] + + self.part_controller_config[self.legs]["actuator_range"] = (low, high) + + def _load_controller(self): + """ + Loads controller to be used for dynamic trajectories + """ + # Flag for loading urdf once (only applicable for IK controllers) + self.composite_controller = composite_controller_factory( + type=self.composite_controller_config.get("type", "BASIC"), + sim=self.sim, + robot_model=self.robot_model, + grippers={self.get_gripper_name(arm): self.gripper[arm] for arm in self.arms}, + ) + + self._load_arm_controllers() + + # default base, torso, and head controllers are inherited from MobileRobot + self._load_base_controller() + + if self.is_legs_actuated: + self._load_leg_controllers() + + self._load_head_controller() + self._load_torso_controller() + self._postprocess_part_controller_config() + + self.composite_controller.load_controller_config( + self.part_controller_config, + self.composite_controller_config.get("composite_controller_specific_configs", {}), + ) + self.enable_parts() + + def load_model(self): + """ + Loads robot and optionally add grippers. + """ + # First, run the superclass method to load the relevant model + super().load_model() + + def reset(self, deterministic=False): + """ + Sets initial pose of arm and grippers. Overrides gripper joint configuration if we're using a + deterministic reset (e.g.: hard reset from xml file) + + Args: + deterministic (bool): If true, will not randomize initializations within the sim + """ + # First, run the superclass method to reset the position and controller + super().reset(deterministic) + + # Set initial q pos of the legged base + if isinstance(self.robot_model.base, LegBaseModel): + # Set the initial joint positions of the legged base + self.sim.data.qpos[self._ref_legs_joint_pos_indexes] = self.robot_model.base.init_qpos + + def setup_references(self): + """ + Sets up necessary reference for robots, grippers, and objects. + + Note that this should get called during every reset from the environment + """ + # First, run the superclass method to setup references for joint-related values / indexes + super().setup_references() + + # Now, add references to gripper if necessary + # indices for grippers in qpos, qvel + self._ref_actuators_indexes_dict[self.legs] = [ + self.sim.model.actuator_name2id(actuator) for actuator in self.robot_model.legs_actuators + ] + + self._ref_joints_indexes_dict[self.legs] = [ + self.sim.model.joint_name2id(joint) for joint in self.robot_model.legs_joints + ] + + self._ref_legs_joint_pos_indexes = [self.sim.model.get_joint_qpos_addr(x) for x in self.robot_model.legs_joints] + self._ref_legs_joint_vel_indexes = [self.sim.model.get_joint_qvel_addr(x) for x in self.robot_model.legs_joints] + + def control(self, action, policy_step=False): + """ + Actuate the robot with the + passed joint velocities and gripper control. + + Args: + action (np.array): The control to apply to the robot. The first @self.robot_model.dof dimensions should + be the desired normalized joint velocities and if the robot has a gripper, the next @self.gripper.dof + dimensions should be actuation controls for the gripper. + + :NOTE: Assumes inputted actions are of form: + [right_arm_control, right_gripper_control, left_arm_control, left_gripper_control] + + policy_step (bool): Whether a new policy step (action) is being taken + + Raises: + AssertionError: [Invalid action dimension] + """ + # clip actions into valid range + assert len(action) == self.action_dim, "environment got invalid action dimension -- expected {}, got {}".format( + self.action_dim, len(action) + ) + + self.composite_controller.update_state() + if policy_step: + self.composite_controller.set_goal(action) + + applied_action_dict = self.composite_controller.run_controller(self._enabled_parts) + for part_name, applied_action in applied_action_dict.items(): + applied_action_low = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[part_name], 0] + applied_action_high = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[part_name], 1] + actuator_indexes = self._ref_actuators_indexes_dict[part_name] + actuator_gears = self.sim.model.actuator_gear[actuator_indexes, 0] + applied_action = np.clip(applied_action / actuator_gears, applied_action_low, applied_action_high) + self.sim.data.ctrl[actuator_indexes] = applied_action + + # If this is a policy step, also update buffers holding recent values of interest + if policy_step: + # Update proprioceptive values + self.recent_qpos.push(self._joint_positions) + self.recent_actions.push(action) + self.recent_torques.push(self.torques) + + for arm in self.arms: + controller = self.part_controllers.get(arm, None) + if controller is None: + # TODO: enable buffer update for whole body controllers not using individual arm controllers + continue + # Update arm-specific proprioceptive values + self.recent_ee_forcetorques[arm].push(np.concatenate((self.ee_force[arm], self.ee_torque[arm]))) + self.recent_ee_pose[arm].push(np.concatenate((controller.ref_pos, T.mat2quat(controller.ref_ori_mat)))) + self.recent_ee_vel[arm].push(np.concatenate((controller.ref_pos_vel, controller.ref_ori_vel))) + + # Estimation of eef acceleration (averaged derivative of recent velocities) + self.recent_ee_vel_buffer[arm].push(np.concatenate((controller.ref_pos_vel, controller.ref_ori_vel))) + diffs = np.vstack( + [ + self.recent_ee_acc[arm].current, + self.control_freq * np.diff(self.recent_ee_vel_buffer[arm].buf, axis=0), + ] + ) + ee_acc = np.array([np.convolve(col, np.ones(10) / 10.0, mode="valid")[0] for col in diffs.transpose()]) + self.recent_ee_acc[arm].push(ee_acc) + + def setup_observables(self): + """ + Sets up observables to be used for this robot + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + # Get general robot observables first + observables = super().setup_observables() + + return observables + + @property + def action_limits(self): + """ + Action lower/upper limits per dimension. + + Returns: + 2-tuple: + + - (np.array) minimum (low) action values + - (np.array) maximum (high) action values + """ + return self.composite_controller.action_limits + + @property + def is_legs_actuated(self): + return len(self.robot_model.legs_actuators) > 0 + + @property + def num_leg_joints(self): + return len(self.robot_model.legs_joints) diff --git a/third_party/robosuite/robosuite/robots/mobile_robot.py b/third_party/robosuite/robosuite/robots/mobile_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..60c28bf35d903bed9c07700555694609326793d5 --- /dev/null +++ b/third_party/robosuite/robosuite/robots/mobile_robot.py @@ -0,0 +1,464 @@ +import copy +import os +from collections import OrderedDict + +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.controllers import load_part_controller_config +from robosuite.robots.robot import Robot +from robosuite.utils.observables import Observable, sensor + + +class MobileRobot(Robot): + """ + Initializes a robot with a fixed base. + """ + + def __init__( + self, + robot_type: str, + idn=0, + composite_controller_config=None, + initial_qpos=None, + initialization_noise=None, + base_type="default", + gripper_type="default", + control_freq=20, + lite_physics=True, + ): + super().__init__( + robot_type=robot_type, + idn=idn, + composite_controller_config=composite_controller_config, + initial_qpos=initial_qpos, + initialization_noise=initialization_noise, + base_type=base_type, + gripper_type=gripper_type, + control_freq=control_freq, + lite_physics=lite_physics, + ) + + def _load_controller(self): + """ + Loads controller to be used for dynamic trajectories + """ + pass + + def _load_base_controller(self): + """ + Load base controller + """ + if len(self._ref_actuators_indexes_dict[self.base]) == 0: + return None + if self.part_controller_config.get(self.base) is None: + controller_path = os.path.join( + os.path.dirname(__file__), + "..", + "controllers/config/{}.json".format(self.robot_model.default_controller_config[self.base]), + ) + self.part_controller_config[self.base] = load_part_controller_config(custom_fpath=controller_path) + + # Assert that the controller config is a dict file: + # NOTE: "type" must be one of: {JOINT_POSITION, JOINT_TORQUE, JOINT_VELOCITY, + # OSC_POSITION, OSC_POSE, IK_POSE} + assert ( + type(self.part_controller_config[self.base]) == dict + ), "Inputted controller config must be a dict! Instead, got type: {}".format( + type(self.part_controller_config[self.base]) + ) + + self.part_controller_config[self.base]["ramp_ratio"] = 1.0 + self.part_controller_config[self.base]["robot_name"] = self.name + + self.part_controller_config[self.base]["sim"] = self.sim + self.part_controller_config[self.base]["part_name"] = self.base + self.part_controller_config[self.base]["naming_prefix"] = self.robot_model.base.naming_prefix + self.part_controller_config[self.base]["ndim"] = self._joint_split_idx + self.part_controller_config[self.base]["policy_freq"] = self.control_freq + self.part_controller_config[self.base]["lite_physics"] = self.lite_physics + + ref_base_joint_indexes = [self.sim.model.joint_name2id(x) for x in self.robot_model.base_joints] + ref_base_joint_pos_indexes = [self.sim.model.get_joint_qpos_addr(x) for x in self.robot_model.base_joints] + ref_base_joint_vel_indexes = [self.sim.model.get_joint_qvel_addr(x) for x in self.robot_model.base_joints] + self.part_controller_config[self.base]["joint_indexes"] = { + "joints": ref_base_joint_indexes, + "qpos": ref_base_joint_pos_indexes, + "qvel": ref_base_joint_vel_indexes, + } + + low = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.base], 0] + high = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.base], 1] + + self.part_controller_config[self.base]["actuator_range"] = (low, high) + + def _load_torso_controller(self): + """ + Load torso controller + """ + if len(self._ref_actuators_indexes_dict[self.torso]) == 0: + return None + + if self.part_controller_config.get(self.torso) is None: + controller_path = os.path.join( + os.path.dirname(__file__), + "..", + "controllers/config/{}.json".format(self.robot_model.default_controller_config[self.torso]), + ) + self.part_controller_config[self.torso] = load_part_controller_config(custom_fpath=controller_path) + + # Assert that the controller config is a dict file: + # NOTE: "type" must be one of: {JOINT_POSITION, JOINT_TORQUE, JOINT_VELOCITY, + # OSC_POSITION, OSC_POSE, IK_POSE} + assert ( + type(self.part_controller_config[self.torso]) == dict + ), "Inputted controller config must be a dict! Instead, got type: {}".format( + type(self.part_controller_config[self.torso]) + ) + + # TODO: Add a default controller config for torso + self.part_controller_config[self.torso]["robot_name"] = self.name + self.part_controller_config[self.torso]["sim"] = self.sim + self.part_controller_config[self.torso]["part_name"] = self.torso + self.part_controller_config[self.torso]["naming_prefix"] = self.robot_model.naming_prefix + self.part_controller_config[self.torso]["ndim"] = self._joint_split_idx + self.part_controller_config[self.torso]["policy_freq"] = self.control_freq + self.part_controller_config[self.torso]["lite_physics"] = self.lite_physics + + ref_torso_joint_indexes = [self.sim.model.joint_name2id(x) for x in self.robot_model.torso_joints] + ref_torso_joint_pos_indexes = [self.sim.model.get_joint_qpos_addr(x) for x in self.robot_model.torso_joints] + ref_torso_joint_vel_indexes = [self.sim.model.get_joint_qvel_addr(x) for x in self.robot_model.torso_joints] + self.part_controller_config[self.torso]["joint_indexes"] = { + "joints": ref_torso_joint_indexes, + "qpos": ref_torso_joint_pos_indexes, + "qvel": ref_torso_joint_vel_indexes, + } + + low = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.torso], 0] + high = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.torso], 1] + + self.part_controller_config[self.torso]["actuator_range"] = (low, high) + + def _load_head_controller(self): + """ + Load head controller + """ + if len(self._ref_actuators_indexes_dict[self.head]) == 0: + return None + if self.part_controller_config.get(self.head) is None: + controller_path = os.path.join( + os.path.dirname(__file__), + "..", + "controllers/config/{}.json".format(self.robot_model.default_controller_config[self.head]), + ) + self.part_controller_config[self.head] = load_part_controller_config(custom_fpath=controller_path) + + # Assert that the controller config is a dict file: + # NOTE: "type" must be one of: {JOINT_POSITION, JOINT_TORQUE, JOINT_VELOCITY, + # OSC_POSITION, OSC_POSE, IK_POSE} + assert ( + type(self.part_controller_config[self.head]) == dict + ), "Inputted controller config must be a dict! Instead, got type: {}".format( + type(self.part_controller_config[self.head]) + ) + + self.part_controller_config[self.head]["robot_name"] = self.name + self.part_controller_config[self.head]["sim"] = self.sim + + self.part_controller_config[self.head]["part_name"] = self.head + self.part_controller_config[self.head]["naming_prefix"] = self.robot_model.naming_prefix + self.part_controller_config[self.head]["ndim"] = self._joint_split_idx + self.part_controller_config[self.head]["policy_freq"] = self.control_freq + self.part_controller_config[self.head]["lite_physics"] = self.lite_physics + + ref_head_joint_indexes = [self.sim.model.joint_name2id(x) for x in self.robot_model.head_joints] + ref_head_joint_pos_indexes = [self.sim.model.get_joint_qpos_addr(x) for x in self.robot_model.head_joints] + ref_head_joint_vel_indexes = [self.sim.model.get_joint_qvel_addr(x) for x in self.robot_model.head_joints] + self.part_controller_config[self.head]["joint_indexes"] = { + "joints": ref_head_joint_indexes, + "qpos": ref_head_joint_pos_indexes, + "qvel": ref_head_joint_vel_indexes, + } + + low = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.head], 0] + high = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[self.head], 1] + + self.part_controller_config[self.head]["actuator_range"] = (low, high) + + def load_model(self): + """ + Loads robot and optionally add grippers. + """ + # First, run the superclass method to load the relevant model + super().load_model() + + def reset(self, deterministic=False): + """ + Sets initial pose of arm and grippers. Overrides gripper joint configuration if we're using a + deterministic reset (e.g.: hard reset from xml file) + + Args: + deterministic (bool): If true, will not randomize initializations within the sim + """ + # First, run the superclass method to reset the position and controller + super().reset(deterministic) + + def setup_references(self): + """ + Sets up necessary reference for robots, grippers, and objects. + + Note that this should get called during every reset from the environment + """ + # First, run the superclass method to setup references for joint-related values / indexes + super().setup_references() + for arm in self.arms: + (start, end) = (None, self._joint_split_idx) if arm == "right" else (self._joint_split_idx, None) + self._ref_joints_indexes_dict[arm] = [ + self.sim.model.joint_name2id(joint) for joint in self.robot_model.arm_joints[start:end] + ] + self._ref_actuators_indexes_dict[arm] = [ + self.sim.model.actuator_name2id(joint) for joint in self.robot_model.arm_actuators[start:end] + ] + + if self.has_gripper[arm]: + self.gripper_joints[arm] = list(self.gripper[arm].joints) + self._ref_gripper_joint_pos_indexes[arm] = [ + self.sim.model.get_joint_qpos_addr(x) for x in self.gripper_joints[arm] + ] + self._ref_gripper_joint_vel_indexes[arm] = [ + self.sim.model.get_joint_qvel_addr(x) for x in self.gripper_joints[arm] + ] + self._ref_joint_gripper_actuator_indexes[arm] = [ + self.sim.model.actuator_name2id(actuator) for actuator in self.gripper[arm].actuators + ] + self._ref_joints_indexes_dict[self.get_gripper_name(arm)] = [ + self.sim.model.joint_name2id(joint) for joint in self.gripper_joints[arm] + ] + self._ref_actuators_indexes_dict[self.get_gripper_name(arm)] = self._ref_joint_gripper_actuator_indexes[ + arm + ] + + # IDs of sites for eef visualization + self.eef_site_id[arm] = self.sim.model.site_name2id(self.gripper[arm].important_sites["grip_site"]) + self.eef_cylinder_id[arm] = self.sim.model.site_name2id(self.gripper[arm].important_sites["grip_cylinder"]) + + self._ref_actuators_indexes_dict[self.base] = [ + self.sim.model.actuator_name2id(actuator) for actuator in self.robot_model.base_actuators + ] + + self._ref_actuators_indexes_dict[self.torso] = [ + self.sim.model.actuator_name2id(actuator) for actuator in self.robot_model.torso_actuators + ] + + self._ref_actuators_indexes_dict[self.head] = [ + self.sim.model.actuator_name2id(actuator) for actuator in self.robot_model.head_actuators + ] + + self._ref_joints_indexes_dict[self.base] = [ + self.sim.model.joint_name2id(joint) for joint in self.robot_model.base_joints + ] + + self._ref_joints_indexes_dict[self.torso] = [ + self.sim.model.joint_name2id(joint) for joint in self.robot_model.torso_joints + ] + + self._ref_joints_indexes_dict[self.head] = [ + self.sim.model.joint_name2id(joint) for joint in self.robot_model.head_joints + ] + + def control(self, action, policy_step=False): + """ + Actuate the robot with the + passed joint velocities and gripper control. + + Args: + action (np.array): The control to apply to the robot. The first @self.robot_model.dof dimensions should + be the desired normalized joint velocities and if the robot has a gripper, the next @self.gripper.dof + dimensions should be actuation controls for the gripper. + + :NOTE: Assumes inputted actions are of form: + [right_arm_control, right_gripper_control, left_arm_control, left_gripper_control] + + policy_step (bool): Whether a new policy step (action) is being taken + + Raises: + AssertionError: [Invalid action dimension] + """ + raise NotImplementedError + + def setup_observables(self): + """ + Sets up observables to be used for this robot + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + # Get general robot observables first + observables = super().setup_observables() + + return observables + + def _create_base_sensors(self, modality): + """ + Creates base sensors for the robot. + + Args: + modality (str): Type/modality of the created sensor + """ + + @sensor(modality=modality) + def base_pos(obs_cache): + return np.array( + self.sim.data.site_xpos[self.sim.model.site_name2id(self.robot_model.base.correct_naming("center"))] + ) + + @sensor(modality=modality) + def base_quat(obs_cache): + return T.mat2quat(self.sim.data.get_site_xmat(self.robot_model.base.correct_naming("center"))) + + sensors = [base_pos, base_quat] + names = ["base_pos", "base_quat"] + + for arm in self.arms: + + @sensor(modality=modality) + def base_to_eef_pos(obs_cache): + eef_pos = np.array(self.sim.data.site_xpos[self.eef_site_id[arm]]) + base_pos = np.array( + self.sim.data.site_xpos[self.sim.model.site_name2id(self.robot_model.base.correct_naming("center"))] + ) + + eef_quat = T.convert_quat(self.sim.data.get_body_xquat(self.robot_model.eef_name[arm]), to="xyzw") + eef_mat = T.quat2mat(eef_quat) + base_mat = self.sim.data.get_site_xmat(self.robot_model.base.correct_naming("center")) + + T_WA = np.vstack((np.hstack((base_mat, base_pos[:, None])), [0, 0, 0, 1])) + T_WB = np.vstack((np.hstack((eef_mat, eef_pos[:, None])), [0, 0, 0, 1])) + T_AB = np.matmul(np.linalg.inv(T_WA), T_WB) + base_to_eef_pos = T_AB[:3, 3] + return base_to_eef_pos + + @sensor(modality=modality) + def base_to_eef_quat(obs_cache): + """ + Args: + obs_cache (dict): A dictionary containing cached observations. + + Returns: + numpy.ndarray: The quaternion representing the orientation of the end effector *body* + in the robot base coordinate frame. + + Note: + In robosuite<=1.5, eef_quat has been queried from the body instead + of the site and has thus been inconsistent with base_to_eef_pos, which queries the position + from the site. This inconsistency has been raised in issue + https://github.com/ARISE-Initiative/robosuite/issues/298 + + Datasets collected with robosuite<=1.4 have use the eef_quat queried from the body, so we keep this key. + New datasets should ideally use the logic in base_to_eef_quat_site. + + In a later robosuite release, we will directly update base_to_eef_quat to query + the orientation from the site. + """ + eef_pos = np.array(self.sim.data.site_xpos[self.eef_site_id[arm]]) + base_pos = np.array( + self.sim.data.site_xpos[self.sim.model.site_name2id(self.robot_model.base.correct_naming("center"))] + ) + + eef_quat = T.convert_quat(self.sim.data.get_body_xquat(self.robot_model.eef_name[arm]), to="xyzw") + eef_mat = T.quat2mat(eef_quat) + base_mat = self.sim.data.get_site_xmat(self.robot_model.base.correct_naming("center")) + + T_WA = np.vstack((np.hstack((base_mat, base_pos[:, None])), [0, 0, 0, 1])) + T_WB = np.vstack((np.hstack((eef_mat, eef_pos[:, None])), [0, 0, 0, 1])) + T_AB = np.matmul(np.linalg.inv(T_WA), T_WB) + base_to_eef_mat = T_AB[:3, :3] + return T.mat2quat(base_to_eef_mat) + + @sensor(modality=modality) + def base_to_eef_quat_site(obs_cache): + """ + Args: + obs_cache (dict): A dictionary containing cached observations. + + Returns: + numpy.ndarray: The quaternion representing the orientation of the end effector *site* + in the robot base coordinate frame. + + Note: + In robosuite<=1.5, eef_quat has been queried from the body instead + of the site and has thus been inconsistent with base_to_eef_pos, which queries the position + from the site. This inconsistency has been raised in issue + https://github.com/ARISE-Initiative/robosuite/issues/298 + + Datasets collected with robosuite<=1.4 have use the eef_quat queried from the body, + so we keep this key. New datasets should ideally use the logic in base_to_eef_quat_site. + + In a later robosuite release, we will directly update base_to_eef_quat to query + the orientation from the site, and then remove this base_to_eef_quat_site key. + """ + eef_pos = np.array(self.sim.data.site_xpos[self.eef_site_id[arm]]) + base_pos = np.array( + self.sim.data.site_xpos[self.sim.model.site_name2id(self.robot_model.base.correct_naming("center"))] + ) + + eef_mat_site = self.sim.data.site_xmat[self.eef_site_id[arm]].reshape((3, 3)) + base_mat = self.sim.data.get_site_xmat(self.robot_model.base.correct_naming("center")) + + T_WA = np.vstack((np.hstack((base_mat, base_pos[:, None])), [0, 0, 0, 1])) + T_WB = np.vstack((np.hstack((eef_mat_site, eef_pos[:, None])), [0, 0, 0, 1])) + T_AB = np.matmul(np.linalg.inv(T_WA), T_WB) + base_to_eef_mat_site = T_AB[:3, :3] + + return T.mat2quat(base_to_eef_mat_site) + + # only consider prefix if there is more than one arm + pf = f"{arm}_" if len(self.arms) > 1 else "" + + sensors += [base_to_eef_pos, base_to_eef_quat, base_to_eef_quat_site] + names += [f"base_to_{pf}eef_pos", f"base_to_{pf}eef_quat", f"base_to_{pf}eef_quat_site"] + + return sensors, names + + def enable_parts(self, right=True, left=True, torso=True, head=True, base=True, legs=True): + + self._enabled_parts = { + "right": right, + "right_gripper": right, + "left": left, + "left_gripper": left, + self.torso: torso, + self.head: head, + self.base: base, + self.legs: legs, + } + + @property + def is_mobile(self): + return True + + @property + def base(self): + return "base" + + @property + def torso(self): + return "torso" + + @property + def head(self): + return "head" + + @property + def legs(self): + return "legs" + + @property + def _action_split_indexes(self): + """ + Dictionary of split indexes for each part of the robot + + Returns: + dict: Dictionary of split indexes for each part of the robot + """ + return self.composite_controller._action_split_indexes diff --git a/third_party/robosuite/robosuite/robots/robot.py b/third_party/robosuite/robosuite/robots/robot.py new file mode 100644 index 0000000000000000000000000000000000000000..0958b0859936ef62cd39209e09b1f2a7c65fc64f --- /dev/null +++ b/third_party/robosuite/robosuite/robots/robot.py @@ -0,0 +1,1007 @@ +import copy +import json +import os +from collections import OrderedDict +from typing import Optional + +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.controllers import load_composite_controller_config, load_part_controller_config +from robosuite.models.bases import robot_base_factory +from robosuite.models.grippers import gripper_factory +from robosuite.models.robots import create_robot +from robosuite.models.robots.robot_model import REGISTERED_ROBOTS +from robosuite.utils.binding_utils import MjSim +from robosuite.utils.buffers import DeltaBuffer, RingBuffer +from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER +from robosuite.utils.mjcf_utils import array_to_string +from robosuite.utils.observables import Observable, sensor + + +class Robot(object): + """ + Initializes a robot simulation object, as defined by a single corresponding robot XML + + Args: + robot_type (str): Specification for specific robot arm to be instantiated within this env (e.g: "Panda") + + idn (int or str): Unique ID of this robot. Should be different from others + + initial_qpos (sequence of float): If set, determines the initial joint positions of the robot to be + instantiated for the task + + initialization_noise (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" + + :Note: Specifying None will automatically create the required dict with "magnitude" set to 0.0 + + base_type (str): type of base, used to instantiate base models from base factory. + Default is "default", which is the default base associated with this robot's corresponding model. + None results in no base, and any other (valid) model overrides the default base. + + 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. + """ + + def __init__( + self, + robot_type: str, + idn=0, + composite_controller_config=None, + initial_qpos=None, + initialization_noise=None, + base_type="default", + gripper_type="default", + control_freq=20, + lite_physics=True, + ): + self.arms = REGISTERED_ROBOTS[robot_type].arms + + # TODO: Merge self.part_controller_config and self.composite_controller_config into one + if composite_controller_config is not None: + self.composite_controller_config = composite_controller_config + else: + self.composite_controller_config = load_composite_controller_config(robot=robot_type) + + self.part_controller_config = copy.deepcopy(self.composite_controller_config.get("body_parts", {})) + + self.gripper = self._input2dict(None) + self.gripper_type = self._input2dict(gripper_type) + self.has_gripper = self._input2dict([gripper_type is not None for _, gripper_type in self.gripper_type.items()]) + + self.gripper_joints = self._input2dict(None) # xml joint names for gripper + self._ref_gripper_joint_pos_indexes = self._input2dict(None) # xml gripper joint position indexes in mjsim + self._ref_gripper_joint_vel_indexes = self._input2dict(None) # xml gripper joint velocity indexes in mjsim + self._ref_joint_gripper_actuator_indexes = self._input2dict( + None + ) # xml gripper (pos) actuator indexes for robot in mjsim + self.eef_rot_offset = self._input2dict(None) # rotation offsets from final arm link to gripper (quat) + self.eef_site_id = self._input2dict(None) # xml element id for eef in mjsim + self.eef_cylinder_id = self._input2dict(None) # xml element id for eef cylinder in mjsim + self.torques = None # Current torques being applied + + self.recent_ee_forcetorques = self._input2dict(None) # Current and last forces / torques sensed at eef + self.recent_ee_pose = self._input2dict(None) # Current and last eef pose (pos + ori (quat)) + self.recent_ee_vel = self._input2dict(None) # Current and last eef velocity + self.recent_ee_vel_buffer = self._input2dict(None) # RingBuffer holding prior 10 values of velocity values + self.recent_ee_acc = self._input2dict(None) # Current and last eef acceleration + + # Set relevant attributes + self.sim = None # MjSim this robot is tied to + self.name = robot_type # Specific robot to instantiate + self.idn = idn # Unique ID of this robot + self.robot_model = None # object holding robot model-specific info + self.control_freq = control_freq # controller Hz + self.lite_physics = lite_physics + self.base_type = base_type # Type of robot base to use + + # Scaling of Gaussian initial noise applied to robot joints + self.initialization_noise = initialization_noise + if self.initialization_noise is None: + self.initialization_noise = {"magnitude": 0.0, "type": "gaussian"} # no noise conditions + elif self.initialization_noise == "default": + self.initialization_noise = {"magnitude": 0.02, "type": "gaussian"} + self.initialization_noise["magnitude"] = ( + self.initialization_noise["magnitude"] if self.initialization_noise["magnitude"] else 0.0 + ) + + self.init_qpos = initial_qpos # n-dim list / array of robot joints + self.init_torso_qpos = None + + self.robot_joints = None # xml joint names for robot + self.base_pos = None # Base position in world coordinates (x,y,z) + self.base_ori = None # Base rotation in world coordinates (x,y,z,w quat) + self._ref_joint_indexes = None # xml joint indexes for robot in mjsim + self._ref_joint_pos_indexes = None # xml joint position indexes in mjsim + self._ref_joint_vel_indexes = None # xml joint velocity indexes in mjsim + self._ref_arm_joint_actuator_indexes = None # xml joint (torq) actuator indexes for robot in mjsim + + self.recent_qpos = None # Current and last robot arm qpos + self.recent_actions = None # Current and last action applied + self.recent_torques = None # Current and last torques applied + + self._ref_actuators_indexes_dict = {} + self._ref_joints_indexes_dict = {} + + self._enabled_parts = {} + self.composite_controller = None + + def _load_controller(self): + """ + Loads controller to be used for dynamic trajectories. + """ + raise NotImplementedError + + def _postprocess_part_controller_config(self): + """ + Update part_controller_config with values from composite_controller_config for each body part. + Remove unused parts that are not in the controller. + Called by _load_controller() function + """ + for part_name, controller_config in self.composite_controller_config.get("body_parts", {}).items(): + if not self.has_part(part_name): + ROBOSUITE_DEFAULT_LOGGER.warning( + f'The config has defined for the controller "{part_name}", ' + "but the robot does not have this component. Skipping, but make sure this is intended." + f"Removing the controller config for {part_name} from self.part_controller_config." + ) + self.part_controller_config.pop(part_name, None) + continue + if part_name in self.part_controller_config: + self.part_controller_config[part_name].update(controller_config) + + def load_model(self): + """ + Loads robot and optionally add grippers. + """ + self.robot_model = create_robot(self.name, idn=self.idn) + + # Add base if specified + if self.base_type == "default": + self.robot_model.add_base(base=robot_base_factory(self.robot_model.default_base, idn=self.idn)) + else: + self.robot_model.add_base(base=robot_base_factory(self.base_type, idn=self.idn)) + + self.robot_model.update_joints() + self.robot_model.update_actuators() + # Use default from robot model for initial joint positions if not specified + if self.init_qpos is None: + self.init_qpos = self.robot_model.init_qpos + + # Now, load the gripper if necessary + for arm in self.arms: + if self.has_gripper[arm]: + if self.gripper_type[arm] == "default": + # Load the default gripper from the robot file + idn = "_".join((str(self.idn), arm)) + self.gripper[arm] = gripper_factory(self.robot_model.default_gripper[arm], idn=idn) + else: + # Load user-specified gripper + self.gripper[arm] = gripper_factory(self.gripper_type[arm], idn="_".join((str(self.idn), arm))) + else: + # Load null gripper + self.gripper[arm] = gripper_factory(None, idn="_".join((str(self.idn), arm))) + # Grab eef rotation offset + self.eef_rot_offset[arm] = T.quat_multiply( + self.robot_model.hand_rotation_offset[arm], self.gripper[arm].rotation_offset + ) + + # Adjust gripper mount offset and quaternion if users specify custom values. This part is essential to support more flexible composition of new robots. + custom_gripper_mount_pos_offset = self.robot_model.gripper_mount_pos_offset.get(arm, None) + custom_gripper_mount_quat_offset = self.robot_model.gripper_mount_quat_offset.get(arm, None) + + # The offset of position and oriientation (quaternion) is assumed to be the very first body in the gripper xml. + if custom_gripper_mount_pos_offset is not None: + assert len(custom_gripper_mount_pos_offset) == 3 + # update an attribute inside an xml object + self.gripper[arm].worldbody.find("body").attrib["pos"] = array_to_string( + custom_gripper_mount_pos_offset + ) + if custom_gripper_mount_quat_offset is not None: + assert len(custom_gripper_mount_quat_offset) == 4 + self.gripper[arm].worldbody.find("body").attrib["quat"] = array_to_string( + custom_gripper_mount_quat_offset + ) + + # Add this gripper to the robot model + self.robot_model.add_gripper(self.gripper[arm], self.robot_model.eef_name[arm]) + + # calling `mujoco.MjModel.from_xml_path()` resets mujoco's internal XML model and thus + # affects get_xml() used in calls in binding_utils.py + # https://mujoco.readthedocs.io/en/stable/APIreference/APIfunctions.html#mj-savelastxml + # https://mujoco.readthedocs.io/en/stable/APIreference/APIfunctions.html#mj-freelastxml + # our solution to requiring robot-only mujoco MjModels is to load the robot MjModels once first + # then using this mujoco MjModel herein + self.robot_model.set_mujoco_model() + + def reset_sim(self, sim: MjSim): + """ + Replaces current sim with a new sim + + Args: + sim (MjSim): New simulation being instantiated to replace the old one + """ + self.sim = sim + + def reset(self, deterministic=False): + """ + Sets initial pose of arm and grippers. Overrides robot joint configuration if we're using a + deterministic reset (e.g.: hard reset from xml file) + + Args: + deterministic (bool): If true, will not randomize initializations within the sim + + Raises: + ValueError: [Invalid noise type] + """ + init_qpos = np.array(self.init_qpos) + if not deterministic: + # Determine noise + if self.initialization_noise["type"] == "gaussian": + noise = np.random.randn(len(self.init_qpos)) * self.initialization_noise["magnitude"] + elif self.initialization_noise["type"] == "uniform": + noise = np.random.uniform(-1.0, 1.0, len(self.init_qpos)) * self.initialization_noise["magnitude"] + else: + raise ValueError("Error: Invalid noise type specified. Options are 'gaussian' or 'uniform'.") + init_qpos += noise + + # Set initial position in sim + self.sim.data.qpos[self._ref_joint_pos_indexes] = init_qpos + + if self.robot_model.init_base_qpos is not None: + self.sim.data.qpos[self._ref_base_joint_pos_indexes] = self.robot_model.init_base_qpos + + init_torso_qpos = self.init_torso_qpos + if self.init_torso_qpos is None: + init_torso_qpos = self.robot_model.init_torso_qpos + if init_torso_qpos is not None: + self.sim.data.qpos[self._ref_torso_joint_pos_indexes] = init_torso_qpos + + # Load controllers + self._load_controller() + + # Update base pos / ori references + self.base_pos = self.sim.data.get_body_xpos(self.robot_model.root_body) + self.base_ori = self.sim.data.get_body_xmat(self.robot_model.root_body).reshape((3, 3)) + + # Setup buffers to hold recent values + self.recent_qpos = DeltaBuffer(dim=len(self.joint_indexes)) + self.recent_actions = DeltaBuffer(dim=self.action_dim) + self.recent_torques = DeltaBuffer(dim=len(self.joint_indexes)) + + # Setup arm-specific values + for arm in self.arms: + # Now, reset the grippers if necessary + if self.has_gripper[arm]: + if not deterministic: + self.sim.data.qpos[self._ref_gripper_joint_pos_indexes[arm]] = self.gripper[arm].init_qpos + + self.gripper[arm].current_action = np.zeros(self.gripper[arm].dof) + + # Setup buffers for eef values + self.recent_ee_forcetorques[arm] = DeltaBuffer(dim=6) + self.recent_ee_pose[arm] = DeltaBuffer(dim=7) + self.recent_ee_vel[arm] = DeltaBuffer(dim=6) + self.recent_ee_vel_buffer[arm] = RingBuffer(dim=6, length=10) + self.recent_ee_acc[arm] = DeltaBuffer(dim=6) + + # reset internal variables for composite controller + self.composite_controller.update_state() + self.composite_controller.reset() + + def setup_references(self): + """ + Sets up necessary reference for robots, bases, grippers, and objects. + """ + # indices for joints in qpos, qvel + self.robot_joints = self.robot_model.joints + self._ref_joint_pos_indexes = [self.sim.model.get_joint_qpos_addr(x) for x in self.robot_joints] + self._ref_joint_vel_indexes = [self.sim.model.get_joint_qvel_addr(x) for x in self.robot_joints] + + # indices for joint indexes + self._ref_joint_indexes = [self.sim.model.joint_name2id(joint) for joint in self.robot_joints] + + # indices for joint pos actuation, joint vel actuation, gripper actuation + self._ref_arm_joint_actuator_indexes = [ + self.sim.model.actuator_name2id(actuator) for actuator in self.robot_model.arm_actuators + ] + + self.robot_arm_joints = self.robot_model.arm_joints + self._ref_arm_joint_indexes = [self.sim.model.joint_name2id(joint) for joint in self.robot_arm_joints] + self._ref_arm_joint_pos_indexes = [self.sim.model.get_joint_qpos_addr(x) for x in self.robot_arm_joints] + self._ref_arm_joint_vel_indexes = [self.sim.model.get_joint_qvel_addr(x) for x in self.robot_arm_joints] + + # indices for base joints + self._ref_base_joint_pos_indexes = [ + self.sim.model.get_joint_qpos_addr(x) for x in self.robot_model._base_joints + ] + self._ref_torso_joint_pos_indexes = [ + self.sim.model.get_joint_qpos_addr(x) for x in self.robot_model._torso_joints + ] + + def setup_observables(self): + """ + Sets up observables to be used for this robot + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + # Get prefix from robot model to avoid naming clashes for multiple robots and define observables modality + pf = self.robot_model.naming_prefix + pre_compute = f"{pf}joint_pos" + modality = f"{pf}proprio" + + # proprioceptive features + @sensor(modality=modality) + def joint_pos(obs_cache): + return np.array([self.sim.data.qpos[x] for x in self._ref_joint_pos_indexes]) + + @sensor(modality=modality) + def joint_pos_cos(obs_cache): + return np.cos(obs_cache[pre_compute]) if pre_compute in obs_cache else np.zeros(self.robot_model.dof) + + @sensor(modality=modality) + def joint_pos_sin(obs_cache): + return np.sin(obs_cache[pre_compute]) if pre_compute in obs_cache else np.zeros(self.robot_model.dof) + + @sensor(modality=modality) + def joint_vel(obs_cache): + return np.array([self.sim.data.qvel[x] for x in self._ref_joint_vel_indexes]) + + sensors = [joint_pos, joint_pos_cos, joint_pos_sin, joint_vel] + names = ["joint_pos", "joint_pos_cos", "joint_pos_sin", "joint_vel"] + # We don't want to include the direct joint pos sensor outputs + actives = [True, True, True, True] + + for arm in self.arms: + arm_sensors, arm_sensor_names = self._create_arm_sensors(arm, modality=modality) + sensors += arm_sensors + names += arm_sensor_names + actives += [True] * len(arm_sensors) + + base_sensors, base_sensor_names = self._create_base_sensors(modality=modality) + sensors += base_sensors + names += base_sensor_names + actives += [True] * len(base_sensors) + + # Create observables for this robot + observables = OrderedDict() + for name, s, active in zip(names, sensors, actives): + obs_name = pf + name + observables[obs_name] = Observable( + name=obs_name, + sensor=s, + sampling_rate=self.control_freq, + active=active, + ) + + return observables + + def _create_arm_sensors(self, arm, modality): + """ + Helper function to create sensors for a given arm. This is abstracted in a separate function call so that we + don't have local function naming collisions during the _setup_observables() call. + + Args: + arm (str): Arm to create sensors for + modality (str): Modality to assign to all sensors + + Returns: + 2-tuple: + sensors (list): Array of sensors for the given arm + names (list): array of corresponding observable names + """ + + # eef features + @sensor(modality=modality) + def eef_pos(obs_cache): + return np.array(self.sim.data.site_xpos[self.eef_site_id[arm]]) + + @sensor(modality=modality) + def eef_quat(obs_cache): + """ + Args: + obs_cache (dict): A dictionary containing cached observations. + + Returns: + numpy.ndarray: The quaternion representing the orientation of the end effector *body* + in the mujoco world coordinate frame. + + Note: + In robosuite<=1.5, eef_quat has been queried from the body instead + of the site and has thus been inconsistent with the eef_pos, which queries from the site. + + This inconsistency has been raised in issue https://github.com/ARISE-Initiative/robosuite/issues/298. + + Datasets collected with robosuite<=1.4 have use the eef_quat queried from the body, so we keep this key. + New datasets should ideally use the logic in eef_quat_site. + + In a later robosuite release, we will directly update eef_quat to query + the orientation from the site. + """ + return T.convert_quat(self.sim.data.get_body_xquat(self.robot_model.eef_name[arm]), to="xyzw") + + @sensor(modality=modality) + def eef_quat_site(obs_cache): + """ + Args: + obs_cache (dict): A dictionary containing cached observations. + + Returns: + numpy.ndarray: The quaternion representing the orientation of the end effector *site* + in the mujoco world coordinate frame. + + Note: + In robosuite<=1.5, eef_quat_site has been queried from the body instead + of the site and has thus been inconsistent with the eef_pos, which queries from the site. + + This inconsistency has been raised in issue https://github.com/ARISE-Initiative/robosuite/issues/298 + + Datasets collected with robosuite<=1.4 have use the eef_quat queried from the body, so we keep this key. + New datasets should ideally use the logic in eef_quat_site. + + In a later robosuite release, we will directly update eef_quat to query + the orientation from the site, and then remove this eef_quat_site key. + """ + return T.mat2quat(self.sim.data.site_xmat[self.eef_site_id[arm]].reshape((3, 3))) + + # only consider prefix if there is more than one arm + pf = f"{arm}_" if len(self.arms) > 1 else "" + + sensors = [eef_pos, eef_quat, eef_quat_site] + names = [f"{pf}eef_pos", f"{pf}eef_quat", f"{pf}eef_quat_site"] + + # add in gripper sensors if this robot has a gripper + if self.has_gripper[arm]: + + @sensor(modality=modality) + def gripper_qpos(obs_cache): + return np.array([self.sim.data.qpos[x] for x in self._ref_gripper_joint_pos_indexes[arm]]) + + @sensor(modality=modality) + def gripper_qvel(obs_cache): + return np.array([self.sim.data.qvel[x] for x in self._ref_gripper_joint_vel_indexes[arm]]) + + sensors += [gripper_qpos, gripper_qvel] + names += [f"{pf}gripper_qpos", f"{pf}gripper_qvel"] + + return sensors, names + + def _create_base_sensors(self, modality): + """ + Helper function to create sensors for the robot base. This will be + overriden by subclasses. + + Args: + modality (str): Type/modality of the created sensor + """ + return [], [] + + def control(self, action, policy_step=False): + """ + Actuate the robot with the + passed joint velocities and gripper control. + + Args: + action (np.array): The control to apply to the robot. The first @self.robot_model.dof dimensions should + be the desired normalized joint velocities and if the robot has a gripper, the next @self.gripper.dof + dimensions should be actuation controls for the gripper. + policy_step (bool): Whether a new policy step (action) is being taken + """ + raise NotImplementedError + + def check_q_limits(self): + """ + Check if this robot is either very close or at the joint limits + + Returns: + bool: True if this arm is near its joint limits + """ + tolerance = 0.1 + for qidx, (q, q_limits) in enumerate( + zip(self.sim.data.qpos[self._ref_joint_pos_indexes], self.sim.model.jnt_range[self._ref_joint_indexes]) + ): + if q_limits[0] != q_limits[1] and not (q_limits[0] + tolerance < q < q_limits[1] - tolerance): + ROBOSUITE_DEFAULT_LOGGER.warning("Joint limit reached in joint " + str(qidx)) + return True + return False + + @property + def is_mobile(self): + return False + + @property + def action_limits(self): + """ + Action lower/upper limits per dimension. + + Returns: + 2-tuple: + + - (np.array) minimum (low) action values + - (np.array) maximum (high) action values + """ + raise NotImplementedError + + def _input2dict(self, inp): + """ + Helper function that converts an input that is either a single value or a list into a dict with keys for + each arm: "right", "left" + + Args: + inp (str or list or None): Input value to be converted to dict + + :Note: If inp is a list, then assumes format is [right, left] + + Returns: + dict: Inputs mapped for each robot arm + """ + # First, convert to list if necessary + if type(inp) is not list: + inp = [inp for _ in range(2)] + # Now, convert list to dict and return + return {key: copy.deepcopy(value) for key, value in zip(self.arms, inp)} + + @property + def torque_limits(self): + """ + Torque lower/upper limits per dimension. + + Returns: + 2-tuple: + + - (np.array) minimum (low) torque values + - (np.array) maximum (high) torque values + """ + # Torque limit values pulled from relevant robot.xml file + low = self.sim.model.actuator_ctrlrange[self._ref_arm_joint_actuator_indexes, 0] + high = self.sim.model.actuator_ctrlrange[self._ref_arm_joint_actuator_indexes, 1] + return low, high + + @property + def action_dim(self): + """ + Action space dimension for this robot + """ + return self.action_limits[0].shape[0] + + @property + def dof(self): + """ + Returns: + int: the active DoF of the robot (Number of robot joints + active gripper DoF). + """ + return self.robot_model.dof + + def pose_in_base_from_name(self, name): + """ + A helper function that takes in a named data field and returns the pose + of that object in the base frame. + + Args: + name (str): Name of body in sim to grab pose + + Returns: + np.array: (4,4) array corresponding to the pose of @name in the base frame + """ + + pos_in_world = self.sim.data.get_body_xpos(name) + rot_in_world = self.sim.data.get_body_xmat(name).reshape((3, 3)) + pose_in_world = T.make_pose(pos_in_world, rot_in_world) + + base_pos_in_world = self.sim.data.get_body_xpos(self.robot_model.root_body) + base_rot_in_world = self.sim.data.get_body_xmat(self.robot_model.root_body).reshape((3, 3)) + base_pose_in_world = T.make_pose(base_pos_in_world, base_rot_in_world) + world_pose_in_base = T.pose_inv(base_pose_in_world) + + pose_in_base = T.pose_in_A_to_pose_in_B(pose_in_world, world_pose_in_base) + return pose_in_base + + def set_robot_joint_positions(self, jpos): + """ + Helper method to force robot joint positions to the passed values. + + Args: + jpos (np.array): Joint positions to manually set the robot to + """ + self.sim.data.qpos[self._ref_joint_pos_indexes] = jpos + self.sim.forward() + + def set_gripper_joint_positions(self, jpos: np.ndarray, gripper_arm: Optional[str] = None): + """ + Helper method to force gripper joint positions to the passed values. + + Args: + jpos (np.array): Joint jpos to manually set the gripper to + gripper_arm: arm corresponding to the gripper for which to set the gripper joint jpos. + If None, use default arm. + """ + if gripper_arm is None: + gripper_arm = self.arms[0] + if self.has_gripper[gripper_arm]: + self.sim.data.qpos[self._ref_gripper_joint_pos_indexes[gripper_arm]] = jpos + self.sim.forward() + else: + raise ValueError(f"No gripper found for arm {gripper_arm}") + + @property + def js_energy(self): + """ + Returns: + np.array: the energy consumed by each joint between previous and current steps + """ + # We assume in the motors torque is proportional to current (and voltage is constant) + # In that case the amount of power scales proportional to the torque and the energy is the + # time integral of that + # Note that we use mean torque + return np.abs((1.0 / self.control_freq) * self.recent_torques.average) + + @property + def _joint_positions(self): + """ + Returns: + np.array: joint positions (in angles / radians) + """ + return self.sim.data.qpos[self._ref_joint_pos_indexes] + + @property + def _joint_velocities(self): + """ + Returns: + np.array: joint velocities (angular velocity) + """ + return self.sim.data.qvel[self._ref_joint_vel_indexes] + + @property + def joint_indexes(self): + """ + Returns: + list: mujoco internal indexes for the robot joints + """ + return self._ref_joint_indexes + + @property + def arm_joint_indexes(self): + """ + Returns: + list: mujoco internal indexes for the robot arm joints + """ + return self._ref_arm_joint_indexes + + def get_sensor_measurement(self, sensor_name): + """ + Grabs relevant sensor data from the sim object + + Args: + sensor_name (str): name of the sensor + + Returns: + np.array: sensor values + """ + sensor_idx = np.sum(self.sim.model.sensor_dim[: self.sim.model.sensor_name2id(sensor_name)]) + sensor_dim = self.sim.model.sensor_dim[self.sim.model.sensor_name2id(sensor_name)] + return np.array(self.sim.data.sensordata[sensor_idx : sensor_idx + sensor_dim]) + + def visualize(self, vis_settings): + """ + Do any necessary visualization for this manipulator + + Args: + vis_settings (dict): Visualization keywords mapped to T/F, determining whether that specific + component should be visualized. Should have "robots" and "grippers" keyword as well as any other + robot-specific options specified. + """ + self.robot_model.set_sites_visibility(sim=self.sim, visible=vis_settings["robots"]) + self._visualize_grippers(visible=vis_settings["grippers"]) + + def _visualize_grippers(self, visible): + """ + Visualizes the gripper site(s) if applicable. + + Args: + visible (bool): True if visualizing the gripper for this arm. + """ + for arm in self.arms: + self.gripper[arm].set_sites_visibility(sim=self.sim, visible=visible) + + @property + def action_limits(self): + raise NotImplementedError + + @property + def is_mobile(self): + return NotImplementedError + + @property + def ee_ft_integral(self): + """ + Returns: + dict: each arm-specific entry specifies the integral over time of the applied ee force-torque for that arm + """ + vals = {} + for arm in self.arms: + vals[arm] = np.abs((1.0 / self.control_freq) * self.recent_ee_forcetorques[arm].average) + return vals + + @property + def ee_force(self): + """ + Returns: + dict: each arm-specific entry specifies the force applied at the force sensor at the robot arm's eef + """ + vals = {} + for arm in self.arms: + vals[arm] = self.get_sensor_measurement(self.gripper[arm].important_sensors["force_ee"]) + return vals + + @property + def ee_torque(self): + """ + Returns: + dict: each arm-specific entry specifies the torque applied at the torque sensor at the robot arm's eef + """ + vals = {} + for arm in self.arms: + vals[arm] = self.get_sensor_measurement(self.gripper[arm].important_sensors["torque_ee"]) + return vals + + @property + def _hand_pose(self): + """ + Returns: + dict: each arm-specific entry specifies the eef pose in base frame of robot. + """ + vals = {} + for arm in self.arms: + vals[arm] = self.pose_in_base_from_name(self.robot_model.eef_name[arm]) + return vals + + @property + def _hand_quat(self): + """ + Returns: + dict: each arm-specific entry specifies the eef quaternion in base frame of robot. + """ + vals = {} + orns = self._hand_orn + for arm in self.arms: + vals[arm] = T.mat2quat(orns[arm]) + return vals + + @property + def _hand_total_velocity(self): + """ + Returns: + dict: each arm-specific entry specifies the total eef velocity (linear + angular) in the base frame + as a numpy array of shape (6,) + """ + vals = {} + for arm in self.arms: + # Determine correct start, end points based on arm + (start, end) = (None, self._joint_split_idx) if arm == "right" else (self._joint_split_idx, None) + + # Use jacobian to translate joint velocities to end effector velocities. + Jp = self.sim.data.get_body_jacp(self.robot_model.eef_name[arm]).reshape((3, -1)) + Jp_joint = Jp[:, self._ref_joint_vel_indexes[start:end]] + + Jr = self.sim.data.get_body_jacr(self.robot_model.eef_name[arm]).reshape((3, -1)) + Jr_joint = Jr[:, self._ref_joint_vel_indexes[start:end]] + + eef_lin_vel = Jp_joint.dot(self._joint_velocities) + eef_rot_vel = Jr_joint.dot(self._joint_velocities) + vals[arm] = np.concatenate([eef_lin_vel, eef_rot_vel]) + return vals + + @property + def _hand_pos(self): + """ + Returns: + dict: each arm-specific entry specifies the position of eef in base frame of robot. + """ + vals = {} + poses = self._hand_pose + for arm in self.arms: + eef_pose_in_base = poses[arm] + vals[arm] = eef_pose_in_base[:3, 3] + return vals + + @property + def _hand_orn(self): + """ + Returns: + dict: each arm-specific entry specifies the orientation of eef in base frame of robot as a rotation matrix. + """ + vals = {} + poses = self._hand_pose + for arm in self.arms: + eef_pose_in_base = poses[arm] + vals[arm] = eef_pose_in_base[:3, :3] + return vals + + @property + def _hand_vel(self): + """ + Returns: + dict: each arm-specific entry specifies the velocity of eef in base frame of robot. + """ + vels = self._hand_total_velocity + for arm in self.arms: + vels[arm] = vels[arm][:3] + return vels + + @property + def _hand_ang_vel(self): + """ + Returns: + dict: each arm-specific entry specifies the angular velocity of eef in base frame of robot. + """ + vels = self._hand_total_velocity + for arm in self.arms: + vels[arm] = vels[arm][3:] + return vels + + def _load_arm_controllers(self): + urdf_loaded = False + # Load composite controller configs for both left and right arm + for arm in self.arms: + # Assert that the controller config is a dict file: + # NOTE: "type" must be one of: {JOINT_POSITION, JOINT_TORQUE, JOINT_VELOCITY, + # OSC_POSITION, OSC_POSE, IK_POSE} + assert ( + type(self.part_controller_config[arm]) == dict + ), "Inputted controller config must be a dict! Instead, got type: {}".format( + type(self.part_controller_config[arm]) + ) + + # Add to the controller dict additional relevant params: + # the robot name, mujoco sim, eef_name, actuator_range, joint_indexes, timestep (model) freq, + # policy (control) freq, and ndim (# joints) + self.part_controller_config[arm]["robot_name"] = self.name + self.part_controller_config[arm]["sim"] = self.sim + self.part_controller_config[arm]["ref_name"] = self.gripper[arm].important_sites["grip_site"] + self.part_controller_config[arm]["part_name"] = arm + self.part_controller_config[arm]["naming_prefix"] = self.robot_model.naming_prefix + + self.part_controller_config[arm]["eef_rot_offset"] = self.eef_rot_offset[arm] + self.part_controller_config[arm]["ndim"] = self._joint_split_idx + self.part_controller_config[arm]["policy_freq"] = self.control_freq + self.part_controller_config[arm]["lite_physics"] = self.lite_physics + (start, end) = (None, self._joint_split_idx) if arm == "right" else (self._joint_split_idx, None) + self.part_controller_config[arm]["joint_indexes"] = { + "joints": self.arm_joint_indexes[start:end], + "qpos": self._ref_arm_joint_pos_indexes[start:end], + "qvel": self._ref_arm_joint_vel_indexes[start:end], + } + self.part_controller_config[arm]["actuator_range"] = ( + self.torque_limits[0][start:end], + self.torque_limits[1][start:end], + ) + + # Only load urdf the first time this controller gets called + self.part_controller_config[arm]["load_urdf"] = True if not urdf_loaded else False + urdf_loaded = True + + # # Instantiate the relevant controller + + if self.has_gripper[arm]: + # Load gripper controllers + assert "gripper" in self.part_controller_config[arm], "Gripper controller config not found!" + gripper_name = self.get_gripper_name(arm) + self.part_controller_config[gripper_name] = {} + self.part_controller_config[gripper_name]["type"] = self.part_controller_config[arm]["gripper"]["type"] + self.part_controller_config[gripper_name]["use_action_scaling"] = self.part_controller_config[arm][ + "gripper" + ].get("use_action_scaling", True) + self.part_controller_config[gripper_name]["robot_name"] = self.name + self.part_controller_config[gripper_name]["sim"] = self.sim + self.part_controller_config[gripper_name]["eef_name"] = self.gripper[arm].important_sites["grip_site"] + self.part_controller_config[gripper_name]["part_name"] = gripper_name + self.part_controller_config[gripper_name]["naming_prefix"] = self.robot_model.naming_prefix + self.part_controller_config[gripper_name]["ndim"] = self.gripper[arm].dof + self.part_controller_config[gripper_name]["policy_freq"] = self.control_freq + self.part_controller_config[gripper_name]["joint_indexes"] = { + "joints": self.gripper_joints[arm], + "actuators": self._ref_joint_gripper_actuator_indexes[arm], + "qpos": self._ref_gripper_joint_pos_indexes[arm], + "qvel": self._ref_gripper_joint_vel_indexes[arm], + } + low = self.sim.model.actuator_ctrlrange[self._ref_joint_gripper_actuator_indexes[arm], 0] + high = self.sim.model.actuator_ctrlrange[self._ref_joint_gripper_actuator_indexes[arm], 1] + + self.part_controller_config[gripper_name]["actuator_range"] = (low, high) + + def enable_parts(self, right=True, left=True): + self._enabled_parts = { + "right": right, + "right_gripper": right, + "left": left, + "left_gripper": left, + } + + def enabled(self, part_name): + return self._enabled_parts[part_name] + + def create_action_vector(self, action_dict): + """ + A helper function that creates the action vector given a dictionary + """ + # check if there's a composite controller and if the controller has a create_action_vector method + if self.composite_controller is not None and hasattr(self.composite_controller, "create_action_vector"): + return self.composite_controller.create_action_vector(action_dict) + else: + full_action_vector = np.zeros(self.action_dim) + 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 + return full_action_vector + + def print_action_info(self): + if self.composite_controller is not None and hasattr(self.composite_controller, "print_action_info"): + self.composite_controller.print_action_info() + return + action_index_info = [] + action_dim_info = [] + for part_name, (start_idx, end_idx) in self._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): + if self.composite_controller is not None and hasattr(self.composite_controller, "print_action_info_dict"): + self.composite_controller.print_action_info_dict(name=self.name) + return + info_dict = {} + info_dict["Action Dimension"] = self.action_dim + info_dict.update(dict(self._action_split_indexes)) + + info_dict_str = f"\nAction Info for {self.name}:\n\n{json.dumps(dict(info_dict), indent=4)}" + ROBOSUITE_DEFAULT_LOGGER.info(info_dict_str) + + def get_gripper_name(self, arm): + return f"{arm}_gripper" + + def has_part(self, part_name): + if part_name in self._ref_joints_indexes_dict.keys() and len(self._ref_joints_indexes_dict[part_name]) > 0: + return True + else: + return False + + @property + def _joint_split_idx(self): + """ + Returns: + int: the index that correctly splits the right arm from the left arm joints + """ + return int(len(self.robot_arm_joints) / len(self.arms)) + + @property + def part_controllers(self): + """ + Controller dictionary for the robot + + Returns: + dict: Controller dictionary for the robot + """ + return self.composite_controller.part_controllers diff --git a/third_party/robosuite/robosuite/robots/wheeled_robot.py b/third_party/robosuite/robosuite/robots/wheeled_robot.py new file mode 100644 index 0000000000000000000000000000000000000000..88cbd4265a98363324370bbd1d16ef09c237c509 --- /dev/null +++ b/third_party/robosuite/robosuite/robots/wheeled_robot.py @@ -0,0 +1,182 @@ +import copy +import os +from collections import OrderedDict + +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.controllers import composite_controller_factory +from robosuite.robots.mobile_robot import MobileRobot +from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER + + +class WheeledRobot(MobileRobot): + """ + Initializes a robot with a wheeled base. + """ + + def __init__( + self, + robot_type: str, + idn=0, + composite_controller_config=None, + initial_qpos=None, + initialization_noise=None, + base_type="default", + gripper_type="default", + control_freq=20, + lite_physics=True, + ): + super().__init__( + robot_type=robot_type, + idn=idn, + composite_controller_config=composite_controller_config, + initial_qpos=initial_qpos, + initialization_noise=initialization_noise, + base_type=base_type, + gripper_type=gripper_type, + control_freq=control_freq, + lite_physics=lite_physics, + ) + + def _load_controller(self): + """ + Loads controller to be used for dynamic trajectories + """ + # Flag for loading urdf once (only applicable for IK controllers) + self.composite_controller = composite_controller_factory( + type=self.composite_controller_config.get("type", "BASIC"), + sim=self.sim, + robot_model=self.robot_model, + grippers={self.get_gripper_name(arm): self.gripper[arm] for arm in self.arms}, + ) + + self._load_arm_controllers() + + # default base, torso, and head controllers are inherited from MobileRobot + self._load_base_controller() + + self._load_head_controller() + self._load_torso_controller() + + self._postprocess_part_controller_config() + self.composite_controller.load_controller_config( + self.part_controller_config, + self.composite_controller_config.get("composite_controller_specific_configs", {}), + ) + self.enable_parts() + + def load_model(self): + """ + Loads robot and optionally add grippers. + """ + # First, run the superclass method to load the relevant model + super().load_model() + + def reset(self, deterministic=False): + """ + Sets initial pose of arm and grippers. Overrides gripper joint configuration if we're using a + deterministic reset (e.g.: hard reset from xml file) + + Args: + deterministic (bool): If true, will not randomize initializations within the sim + """ + # First, run the superclass method to reset the position and controller + super().reset(deterministic) + + def setup_references(self): + """ + Sets up necessary reference for robots, grippers, and objects. + + Note that this should get called during every reset from the environment + """ + # All the references are by default set up in the superclass method + super().setup_references() + + def control(self, action, policy_step=False): + """ + Actuate the robot with the + passed joint velocities and gripper control. + + Args: + action (np.array): The control to apply to the robot. The first @self.robot_model.dof dimensions should + be the desired normalized joint velocities and if the robot has a gripper, the next @self.gripper.dof + dimensions should be actuation controls for the gripper. + + :NOTE: Assumes inputted actions are of form: + [right_arm_control, right_gripper_control, left_arm_control, left_gripper_control] + + policy_step (bool): Whether a new policy step (action) is being taken + + Raises: + AssertionError: [Invalid action dimension] + """ + # clip actions into valid range + assert len(action) == self.action_dim, "environment got invalid action dimension -- expected {}, got {}".format( + self.action_dim, len(action) + ) + + # self.composite_controller.update_state() # remove this for now, messes up base velocity calculation + if policy_step: + self.composite_controller.set_goal(action) + + applied_action_dict = self.composite_controller.run_controller(self._enabled_parts) + for part_name, applied_action in applied_action_dict.items(): + applied_action_low = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[part_name], 0] + applied_action_high = self.sim.model.actuator_ctrlrange[self._ref_actuators_indexes_dict[part_name], 1] + applied_action = np.clip(applied_action, applied_action_low, applied_action_high) + self.sim.data.ctrl[self._ref_actuators_indexes_dict[part_name]] = applied_action + + # If this is a policy step, also update buffers holding recent values of interest + if policy_step: + # Update proprioceptive values + self.recent_qpos.push(self._joint_positions) + self.recent_actions.push(action) + self.recent_torques.push(self.torques) + + for arm in self.arms: + controller = self.part_controllers.get(arm, None) + if controller is None: + # TODO: enable buffer update for whole body controllers not using individual arm controllers + continue + + # Update arm-specific proprioceptive values + self.recent_ee_forcetorques[arm].push(np.concatenate((self.ee_force[arm], self.ee_torque[arm]))) + self.recent_ee_pose[arm].push(np.concatenate((controller.ref_pos, T.mat2quat(controller.ref_ori_mat)))) + self.recent_ee_vel[arm].push(np.concatenate((controller.ref_pos_vel, controller.ref_ori_vel))) + + # Estimation of eef acceleration (averaged derivative of recent velocities) + self.recent_ee_vel_buffer[arm].push(np.concatenate((controller.ref_pos_vel, controller.ref_ori_vel))) + diffs = np.vstack( + [ + self.recent_ee_acc[arm].current, + self.control_freq * np.diff(self.recent_ee_vel_buffer[arm].buf, axis=0), + ] + ) + ee_acc = np.array([np.convolve(col, np.ones(10) / 10.0, mode="valid")[0] for col in diffs.transpose()]) + self.recent_ee_acc[arm].push(ee_acc) + + def setup_observables(self): + """ + Sets up observables to be used for this robot + + Returns: + OrderedDict: Dictionary mapping observable names to its corresponding Observable object + """ + # Get general robot observables first + observables = super().setup_observables() + + return observables + + @property + def action_limits(self): + """ + Action lower/upper limits per dimension. + + Returns: + 2-tuple: + + - (np.array) minimum (low) action values + - (np.array) maximum (high) action values + """ + return self.composite_controller.action_limits diff --git a/third_party/robosuite/robosuite/scripts/browse_mjcf_model.py b/third_party/robosuite/robosuite/scripts/browse_mjcf_model.py new file mode 100644 index 0000000000000000000000000000000000000000..187d9f013a424765744467cba9cf3608d8f4949d --- /dev/null +++ b/third_party/robosuite/robosuite/scripts/browse_mjcf_model.py @@ -0,0 +1,67 @@ +"""Visualize MJCF models. + +Loads MJCF XML models from file and renders it on screen. + +Example: + $ python browse_mjcf_model.py --filepath ../models/assets/arenas/table_arena.xml +""" + +import argparse +import os + +import mujoco +from mujoco import viewer +from pynput import keyboard + +import robosuite as suite +from robosuite.utils.binding_utils import MjSim + +DEFAULT_FREE_CAM = { + "lookat": [0, 0, 0.7], + "distance": 1.5, + "azimuth": 180, + "elevation": -20, +} + +continue_running = True + + +def on_press(key): + global continue_running + try: + if key == keyboard.Key.esc: + continue_running = False + except AttributeError: + pass + + +if __name__ == "__main__": + + arena_file = os.path.join(suite.models.assets_root, "arenas/pegs_arena.xml") + + parser = argparse.ArgumentParser() + parser.add_argument("--filepath", type=str, default=arena_file) + args = parser.parse_args() + + print("Loading model from: {}".format(args.filepath)) + model = mujoco.MjModel.from_xml_path(args.filepath) + sim = MjSim(model) + + vwr = viewer.launch_passive(sim.model._model, sim.data._data, show_left_ui=False, show_right_ui=False) + vwr.cam.lookat = DEFAULT_FREE_CAM["lookat"] + vwr.cam.distance = DEFAULT_FREE_CAM["distance"] + vwr.cam.azimuth = DEFAULT_FREE_CAM["azimuth"] + vwr.cam.elevation = DEFAULT_FREE_CAM["elevation"] + + vwr.sync() + + listener = keyboard.Listener(on_press=on_press) + listener.start() + print("Press 'ESC' to exit.") + + while continue_running: + pass + + vwr.close() + listener.stop() + listener.join() diff --git a/third_party/robosuite/robosuite/scripts/check_custom_robot_model.py b/third_party/robosuite/robosuite/scripts/check_custom_robot_model.py new file mode 100644 index 0000000000000000000000000000000000000000..c03b42aefb644ffe8439e32eb6a4f6445e887ed9 --- /dev/null +++ b/third_party/robosuite/robosuite/scripts/check_custom_robot_model.py @@ -0,0 +1,108 @@ +import argparse +from xml.etree import ElementTree as ET + +from robosuite.controllers.composite.composite_controller_factory import load_composite_controller_config +from robosuite.robots.robot import Robot +from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER as logger + + +def check_xml_definition(root): + logger.info(f"Successfully loaded the xml file of robot model.") + + # get all joints + world_body = root.find(".//worldbody") + parts_dict = {} + added_joints = [] + for part_name in ["torso", "head", "leg", "gripper", "base"]: + parts_dict[part_name] = [] + for joint in world_body.findall(".//joint"): + if part_name in joint.attrib["name"] and joint.attrib["name"] not in added_joints: + parts_dict[part_name].append(joint.attrib["name"]) + added_joints.append(joint.attrib["name"]) + parts_dict["arm"] = [] + + print(len(world_body.findall(".//joint"))) + for joint in world_body.findall(".//joint"): + is_non_arm_part = False + for non_arm_part_name in ["torso", "head", "leg", "gripper", "base"]: + if non_arm_part_name in joint.attrib["name"]: + is_non_arm_part = True + break + if not is_non_arm_part: + parts_dict["arm"].append(joint.attrib["name"]) + total_counted_joints = sum([len(parts_dict[part_name]) for part_name in parts_dict.keys()]) + if total_counted_joints != len(world_body.findall(".//joint")): + logger.error(f"Counted {total_counted_joints} joints, but found {len(world_body.findall('.//joint'))} joints") + else: + logger.info(f"Your joint definition aligns with robosuite convention.") + # remove empty list entries + parts_dict = {part_name: joints for part_name, joints in parts_dict.items() if joints} + print(f" • Robosuite will be able to detect the following body parts: {list(parts_dict.keys())}") + print(" • For each body part, you have defined the following joints:") + for part_name in parts_dict.keys(): + print(f" • {part_name} - {len(parts_dict[part_name])} joints: {parts_dict[part_name]}") + return parts_dict + + +def check_registered_robot(robot_name): + + print(f"Loading {robot_name} ...") + controller_config = load_composite_controller_config("BASIC") + robot = Robot(robot_type=robot_name, composite_controller_config=controller_config, gripper_type=None) + logger.info(f"Succcessfully found the defined robot") + + robot.load_model() + robot_model = robot.robot_model + + root = robot_model.tree.getroot() + parts_dict = check_xml_definition(root) + + if parts_dict.get("arm") is not None and parts_dict["arm"] != []: + # checking the order of arm joints defined. + arm_joint_names = parts_dict["arm"] + first_arm_joint_name = arm_joint_names[0] + if "l_" in first_arm_joint_name or "left" in first_arm_joint_name: + logger.warning( + "Incorrect order of the arm joints. THe arm joints needs to be defined first for the right arm and then for the left arm." + ) + + # check if the body for mounting exists + num_arms = len(robot.arms) + + mount_names = [robot.robot_model._eef_name[name] for name in robot.robot_model._eef_name] + world_body = root.find(".//worldbody") + for mount_name in mount_names[:num_arms]: + # find the body name of mount_name in the worldbody + mount_body = world_body.find(f".//body[@name='robot0_{mount_name}']") + if mount_body is None: + logger.error( + f"Error: No body named '{mount_name}' found in the worldbody. Please make sure you have defined the body for mounting the arm." + ) + exit(1) + print(" • Grippers will be mounted on the following bodies ", mount_names[:num_arms]) + + logger.warning( + "Attention!!! Make sure your definition of the motors for arms are in the same order as the joints defined. This program does not check on this item." + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--robot", type=str, default=None) + parser.add_argument("--robot-xml-file", type=str, default=None) + args = parser.parse_args() + if args.robot is None and args.robot_xml_file is None: + logger.error("Please provide either the robot name or the robot xml file.") + exit(1) + if args.robot is not None: + check_registered_robot(args.robot) + + if args.robot_xml_file is not None: + etree_root = ET.parse(args.robot_xml_file) + parts_dict = check_xml_definition(etree_root) + arm_joint_names = parts_dict["arm"] + first_arm_joint_name = arm_joint_names[0] + if "l_" in first_arm_joint_name or "left" in first_arm_joint_name: + logger.warning( + "Incorrect order of the arm joints. THe arm joints needs to be defined first for the right arm and then for the left arm." + ) diff --git a/third_party/robosuite/robosuite/scripts/collect_human_demonstrations.py b/third_party/robosuite/robosuite/scripts/collect_human_demonstrations.py new file mode 100644 index 0000000000000000000000000000000000000000..2cd28732c3a20d02099c48a1ab66c77b96de8b07 --- /dev/null +++ b/third_party/robosuite/robosuite/scripts/collect_human_demonstrations.py @@ -0,0 +1,318 @@ +""" +A script to collect a batch of human demonstrations. + +The demonstrations can be played back using the `playback_demonstrations_from_hdf5.py` script. +""" + +import argparse +import datetime +import json +import os +import time +from glob import glob + +import h5py +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.wrappers import DataCollectionWrapper, VisualizationWrapper + + +def collect_human_trajectory(env, device, arm, max_fr): + """ + Use the device (keyboard or SpaceNav 3D mouse) to collect a demonstration. + 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 to control + device (Device): to receive controls from the device + arms (str): which arm to control (eg bimanual) 'right' or 'left' + max_fr (int): if specified, pause the simulation whenever simulation runs faster than max_fr + """ + + env.reset() + env.render() + + task_completion_hold_count = -1 # counter to collect 10 timesteps after reaching goal + 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: + 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() + + # Also break if we complete the task + if task_completion_hold_count == 0: + break + + # state machine to check for having a success for 10 consecutive timesteps + if env._check_success(): + if task_completion_hold_count > 0: + task_completion_hold_count -= 1 # latched state, decrement count + else: + task_completion_hold_count = 10 # reset count on first success timestep + else: + task_completion_hold_count = -1 # null the counter if there's no success + + # 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) + + # cleanup for end of data collection episodes + env.close() + + +def gather_demonstrations_as_hdf5(directory, out_dir, env_info): + """ + Gathers the demonstrations saved in @directory into a + single hdf5 file. + + The strucure of the hdf5 file is as follows. + + data (group) + date (attribute) - date of collection + time (attribute) - time of collection + repository_version (attribute) - repository version used during collection + env (attribute) - environment name on which demos were collected + + demo1 (group) - every demonstration has a group + model_file (attribute) - model xml string for demonstration + states (dataset) - flattened mujoco states + actions (dataset) - actions applied during demonstration + + demo2 (group) + ... + + Args: + directory (str): Path to the directory containing raw demonstrations. + out_dir (str): Path to where to store the hdf5 file. + env_info (str): JSON-encoded string containing environment information, + including controller and robot info + """ + + hdf5_path = os.path.join(out_dir, "demo.hdf5") + f = h5py.File(hdf5_path, "w") + + # store some metadata in the attributes of one group + grp = f.create_group("data") + + num_eps = 0 + env_name = None # will get populated at some point + + for ep_directory in os.listdir(directory): + + state_paths = os.path.join(directory, ep_directory, "state_*.npz") + states = [] + actions = [] + success = False + + for state_file in sorted(glob(state_paths)): + dic = np.load(state_file, allow_pickle=True) + env_name = str(dic["env"]) + + states.extend(dic["states"]) + for ai in dic["action_infos"]: + actions.append(ai["actions"]) + success = success or dic["successful"] + + if len(states) == 0: + continue + + # Add only the successful demonstration to dataset + if success: + print("Demonstration is successful and has been saved") + # Delete the last state. This is because when the DataCollector wrapper + # recorded the states and actions, the states were recorded AFTER playing that action, + # so we end up with an extra state at the end. + del states[-1] + assert len(states) == len(actions) + + num_eps += 1 + ep_data_grp = grp.create_group("demo_{}".format(num_eps)) + + # store model xml as an attribute + xml_path = os.path.join(directory, ep_directory, "model.xml") + with open(xml_path, "r") as f: + xml_str = f.read() + ep_data_grp.attrs["model_file"] = xml_str + + # write datasets for states and actions + ep_data_grp.create_dataset("states", data=np.array(states)) + ep_data_grp.create_dataset("actions", data=np.array(actions)) + else: + print("Demonstration is unsuccessful and has NOT been saved") + + # write dataset attributes (metadata) + now = datetime.datetime.now() + grp.attrs["date"] = "{}-{}-{}".format(now.month, now.day, now.year) + grp.attrs["time"] = "{}:{}:{}".format(now.hour, now.minute, now.second) + grp.attrs["repository_version"] = suite.__version__ + grp.attrs["env"] = env_name + grp.attrs["env_info"] = env_info + + f.close() + + +if __name__ == "__main__": + # Arguments + parser = argparse.ArgumentParser() + parser.add_argument( + "--directory", + type=str, + default=os.path.join(suite.models.assets_root, "demonstrations_private"), + ) + 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( + "--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)", + ) + 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( + "--renderer", + type=str, + default="mjviewer", + help="Use Mujoco's builtin interactive viewer (mjviewer) or OpenCV viewer (mujoco)", + ) + 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], + ) + + if controller_config["type"] == "WHOLE_BODY_MINK_IK": + # mink-speicific import. requires installing mink + from robosuite.examples.third_party_controller.mink_controller import WholeBodyMinkIK + + # 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 + + # Create environment + env = suite.make( + **config, + has_renderer=True, + renderer=args.renderer, + has_offscreen_renderer=False, + render_camera=args.camera, + ignore_done=True, + use_camera_obs=False, + reward_shaping=True, + control_freq=20, + ) + + # Wrap this with visualization wrapper + env = VisualizationWrapper(env) + + # Grab reference to controller config and convert it to json-encoded string + env_info = json.dumps(config) + + # wrap the environment with data collection wrapper + tmp_directory = "/tmp/{}".format(str(time.time()).replace(".", "_")) + env = DataCollectionWrapper(env, tmp_directory) + + # 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) + elif args.device == "mjgui": + assert args.renderer == "mjviewer", "Mocap is only supported with the mjviewer renderer" + from robosuite.devices.mjgui import MJGUI + + device = MJGUI(env=env) + else: + raise Exception("Invalid device choice: choose either 'keyboard' or 'spacemouse'.") + + # make a new timestamped directory + t1, t2 = str(time.time()).split(".") + new_dir = os.path.join(args.directory, "{}_{}".format(t1, t2)) + os.makedirs(new_dir) + + # collect demonstrations + while True: + collect_human_trajectory(env, device, args.arm, args.max_fr) + gather_demonstrations_as_hdf5(tmp_directory, new_dir, env_info) diff --git a/third_party/robosuite/robosuite/scripts/compile_mjcf_model.py b/third_party/robosuite/robosuite/scripts/compile_mjcf_model.py new file mode 100644 index 0000000000000000000000000000000000000000..b5b9334a00d4b3fdfa5a2ab8fa06eb4013faf5cc --- /dev/null +++ b/third_party/robosuite/robosuite/scripts/compile_mjcf_model.py @@ -0,0 +1,39 @@ +"""Loads a raw mjcf file and saves a compiled mjcf file. + +This avoids mujoco-py from complaining about .urdf extension. +Also allows assets to be compiled properly. + +Example: + $ python compile_mjcf_model.py source_mjcf.xml target_mjcf.xml +""" + +import os +import sys +from shutil import copyfile + +import mujoco + + +def print_usage(): + print("""python compile_mjcf_model.py input_file output_file""") + + +if __name__ == "__main__": + + if len(sys.argv) != 3: + print_usage() + exit(0) + + input_file = sys.argv[1] + output_file = sys.argv[2] + input_folder = os.path.dirname(input_file) + + tempfile = os.path.join(input_folder, ".robosuite_temp_model.xml") + copyfile(input_file, tempfile) + + model = mujoco.MjModel.from_xml_path(tempfile) + xml_string = model.get_xml() + with open(output_file, "w") as f: + f.write(xml_string) + + os.remove(tempfile) diff --git a/third_party/robosuite/robosuite/scripts/internal/view_robot_initialization.py b/third_party/robosuite/robosuite/scripts/internal/view_robot_initialization.py new file mode 100644 index 0000000000000000000000000000000000000000..07c021f4a95a1061023f55f1e7dcdd59d86328f5 --- /dev/null +++ b/third_party/robosuite/robosuite/scripts/internal/view_robot_initialization.py @@ -0,0 +1,74 @@ +import argparse + +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.wrappers import VisualizationWrapper + + +def bimanual_check(robot): + bimanual_robots = ["Baxter", "Tiago", "GR1", "G1", "H1", "PR2", "Yumi", "Aloha"] + for br in bimanual_robots: + if br in robot: + return True + return False + + +if __name__ == "__main__": + + parser = argparse.ArgumentParser() + parser.add_argument("--environment", type=str, default="Lift") + parser.add_argument("--robots", type=str, nargs="+", default=ROBOT_CLASS_MAPPING.keys()) + parser.add_argument("--controller", type=str, default="BASIC", help="Choice of controller. Can be 'ik' or 'osc'") + args = parser.parse_args() + + for robot in args.robots: + print(f"{robot} demo...") + + # Check if we're using a multi-armed environment + if "TwoArm" in args.environment and not bimanual_check(robot): + robots = [robot, robot] + else: + robots = [robot] + + # Get controller config + controller_config = load_composite_controller_config( + controller=args.controller, + robot=robot, + ) + + # Create argument configuration + config = { + "env_name": args.environment, + "robots": robots, + "controller_configs": controller_config, + } + + # Create environment + env = suite.make( + **config, + has_renderer=True, + has_offscreen_renderer=False, + renderer="mjviewer", + render_camera="free", + 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) + + env.reset() + low, high = env.action_spec + + for i in range(200): + action = np.zeros(len(low)) + env.step(action) + env.render() + + env.close() diff --git a/third_party/robosuite/robosuite/scripts/make_reset_video.py b/third_party/robosuite/robosuite/scripts/make_reset_video.py new file mode 100644 index 0000000000000000000000000000000000000000..249dd630b06299153d7587e3ce961afb7e760d7d --- /dev/null +++ b/third_party/robosuite/robosuite/scripts/make_reset_video.py @@ -0,0 +1,93 @@ +""" +Convenience script to make a video out of initial environment +configurations. This can be a useful debugging tool to understand +what different sampled environment configurations look like. +""" + +import argparse + +import imageio +import numpy as np + +import robosuite as suite +from robosuite.utils.input_utils import * + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + # camera to use for generating frames + parser.add_argument( + "--camera", + type=str, + default="agentview", + ) + + # number of frames in output video + parser.add_argument( + "--frames", + type=int, + default=10, + ) + + # path to output video + parser.add_argument( + "--output", + type=str, + default="reset.mp4", + ) + + args = parser.parse_args() + camera_name = args.camera + num_frames = args.frames + output_path = args.output + + # 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)) + + # 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=False, + has_offscreen_renderer=True, + ignore_done=True, + use_camera_obs=False, + control_freq=20, + ) + + # write a video + video_writer = imageio.get_writer(output_path, fps=5) + for i in range(num_frames): + env.reset() + video_img = env.sim.render(height=512, width=512, camera_name=camera_name)[::-1] + env.step(np.zeros_like(env.action_spec[0])) + video_writer.append_data(video_img) + video_writer.close() diff --git a/third_party/robosuite/robosuite/scripts/playback_demonstrations_from_hdf5.py b/third_party/robosuite/robosuite/scripts/playback_demonstrations_from_hdf5.py new file mode 100644 index 0000000000000000000000000000000000000000..d20ce0dc4472cc3b137015a9fe9d8aa17ab88777 --- /dev/null +++ b/third_party/robosuite/robosuite/scripts/playback_demonstrations_from_hdf5.py @@ -0,0 +1,110 @@ +""" +A convenience script to playback random demonstrations from +a set of demonstrations stored in a hdf5 file. + +Arguments: + --folder (str): Path to demonstrations + --use-actions (optional): If this flag is provided, the actions are played back + through the MuJoCo simulator, instead of loading the simulator states + one by one. + --visualize-gripper (optional): If set, will visualize the gripper site + +Example: + $ python playback_demonstrations_from_hdf5.py --folder ../models/assets/demonstrations/lift/ +""" + +import argparse +import json +import os +import random + +import h5py +import numpy as np + +import robosuite + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--folder", + type=str, + required=True, + help="Path to your demonstration folder that contains the demo.hdf5 file, e.g.: " + "'path_to_assets_dir/demonstrations/YOUR_DEMONSTRATION'", + ), + parser.add_argument( + "--use-actions", + action="store_true", + ) + args = parser.parse_args() + + demo_path = args.folder + hdf5_path = os.path.join(demo_path, "demo.hdf5") + + f = h5py.File(hdf5_path, "r") + env_name = f["data"].attrs["env"] + env_info = json.loads(f["data"].attrs["env_info"]) + + env = robosuite.make( + **env_info, + has_renderer=True, + has_offscreen_renderer=False, + ignore_done=True, + use_camera_obs=False, + reward_shaping=True, + control_freq=20, + ) + + # list of all demonstrations episodes + demos = list(f["data"].keys()) + + while True: + print("Playing back random episode... (press ESC to quit)") + + # select an episode randomly + ep = random.choice(demos) + + # read the model xml, using the metadata stored in the attribute for this episode + model_xml = f["data/{}".format(ep)].attrs["model_file"] + + env.reset() + xml = env.edit_model_xml(model_xml) + env.reset_from_xml_string(xml) + env.sim.reset() + env.viewer.set_camera(0) + + # load the flattened mujoco states + states = f["data/{}/states".format(ep)][()] + + if args.use_actions: + + # load the initial state + env.sim.set_state_from_flattened(states[0]) + env.sim.forward() + + # load the actions and play them back open-loop + actions = np.array(f["data/{}/actions".format(ep)][()]) + num_actions = actions.shape[0] + + for j, action in enumerate(actions): + env.step(action) + env.render() + + if j < num_actions - 1: + # ensure that the actions deterministically lead to the same recorded states + state_playback = env.sim.get_state().flatten() + if not np.all(np.equal(states[j + 1], state_playback)): + err = np.linalg.norm(states[j + 1] - state_playback) + print(f"[warning] playback diverged by {err:.2f} for ep {ep} at step {j}") + + else: + + # force the sequence of internal mujoco states one by one + for state in states: + env.sim.set_state_from_flattened(state) + env.sim.forward() + if env.renderer == "mjviewer": + env.viewer.update() + env.render() + + f.close() diff --git a/third_party/robosuite/robosuite/scripts/print_robosuite_info.py b/third_party/robosuite/robosuite/scripts/print_robosuite_info.py new file mode 100644 index 0000000000000000000000000000000000000000..edfcab0ff3f59f5a1bc5591881bbec1c8fd066f0 --- /dev/null +++ b/third_party/robosuite/robosuite/scripts/print_robosuite_info.py @@ -0,0 +1,52 @@ +from collections import OrderedDict + +from robosuite.environments.base import REGISTERED_ENVS +from robosuite.models.bases import BASE_MAPPING +from robosuite.models.robots.robot_model import REGISTERED_ROBOTS +from robosuite.robots import ROBOT_CLASS_MAPPING + + +def bold_green_text(text): + return f"\033[1m\033[32m{text}\033[0m" + + +def get_base_type(robot): + return ROBOT_CLASS_MAPPING[robot].__name__ if robot in ROBOT_CLASS_MAPPING else "N/A" + + +def get_robot_info_dict(): + info = {} + for i, key in enumerate(REGISTERED_ROBOTS): + try: + info[key] = {} + robot = REGISTERED_ROBOTS[key](idn=i) + base_type = get_base_type(key) + robot_base_model = robot.default_base + arm_type = robot.arm_type + gripper = robot.default_gripper + info[key]["Base_Type"] = base_type + info[key]["Robot_Base_Model"] = robot_base_model + info[key]["Arm_Type"] = arm_type + info[key]["Gripper_Model"] = gripper + except Exception as e: + # could not instantiate the class on its own + pass + return info + + +print("Available environments/tasks:\n") +for i, env in enumerate(REGISTERED_ENVS): + print(f"{i}. {bold_green_text(env)}") + + +info = get_robot_info_dict() +info_sorted = dict(sorted(info.items(), key=lambda item: item[1].get("Base_Type", "zzz"))) + +print("\n\n\nAvailable Robots:\n") + +for i, key in enumerate(info_sorted): + print(f"{i}. {bold_green_text(key)}") + for k, item in info[key].items(): + k = k.replace("_", " ") + print(f"\t{k}: {item}") + print("\n") diff --git a/third_party/robosuite/robosuite/scripts/print_robot_action_info.py b/third_party/robosuite/robosuite/scripts/print_robot_action_info.py new file mode 100644 index 0000000000000000000000000000000000000000..190de88878c63cb3419e82b1a95804d3f1dd7dbc --- /dev/null +++ b/third_party/robosuite/robosuite/scripts/print_robot_action_info.py @@ -0,0 +1,58 @@ +import argparse +import json + +import robosuite as suite +from robosuite.controllers import load_composite_controller_config + +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="opposed", help="Specified environment configuration if necessary") +parser.add_argument( + "--controller", + type=str, + default=None, + help="Choice of controller. Can be generic (eg. 'BASIC' or 'WHOLE_BODY_IK') or json file (see robosuite/controllers/config for examples)", +) + +args = parser.parse_args() + +controller_config = load_composite_controller_config( + controller=args.controller, + robot=args.robots[0], +) + +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 + +# Create environment +env = suite.make( + **config, + has_renderer=True, + ignore_done=True, + use_camera_obs=False, + reward_shaping=True, + control_freq=20, +) +env.reset() + +print(f"Action info for {args.environment}") +for robot in env.robots: + print(f"Action info for {robot.name}") + print(json.dumps(robot._action_split_indexes, indent=4)) + print() + + +env.close() + +print( + "Actions can created by calling robot.create_action_vector, and passing in a dictionary with the above keys and desired values." +) diff --git a/third_party/robosuite/robosuite/scripts/render_dataset_with_omniverse.py b/third_party/robosuite/robosuite/scripts/render_dataset_with_omniverse.py new file mode 100644 index 0000000000000000000000000000000000000000..43b7673e51f8ed25da6944a2d792888ae5f756cb --- /dev/null +++ b/third_party/robosuite/robosuite/scripts/render_dataset_with_omniverse.py @@ -0,0 +1,735 @@ +import argparse + +from omni.isaac.lab.app import AppLauncher + +parser = argparse.ArgumentParser(description="Settings for SimulationApp") + +# General arguments for robocasa script +parser.add_argument("--dataset", type=str, required=True, help="the hdf5 dataset") + +parser.add_argument( + "--ds_format", type=str, default="robomimic", help="the format of the dataset. Can be robosuite or robomimic" +) + +# episode is a list +parser.add_argument( + "--episode", + type=int, + nargs="+", + default=[], + help="(optional) episode number(s) to render. Default is all episodes in the dataset", +) + +parser.add_argument( + "--output_directory", type=str, default=None, help="(optional) directory to store outputs of USD rendering pipeline" +) + +parser.add_argument( + "--cameras", + type=str, + nargs="+", + default=["agentview"], + 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", +) + +# Arguments to set up simulation app +parser.add_argument( + "--width", type=int, default=1280, help="(optional) width of the viewport and generated images. Defaults to 1280" +) + +parser.add_argument( + "--height", type=int, default=720, help="(optional) height of the viewport and generated images. Defaults to 720" +) + +parser.add_argument( + "--renderer", + type=str, + default="RayTracedLighting", + help="(optional) rendering mode, can be RayTracedLighting or PathTracing. Defaults to RayTracedLighting", +) + +parser.add_argument( + "--save_video", action="store_true", default=False, help="(optional) save the rendered frames to a video file" +) + +parser.add_argument( + "--online", + action="store_true", + default=False, + help="(optional) enable online rendering, will not save the usd file in this mode", +) + +parser.add_argument("--skip_frames", type=int, default=1, help="(optional) render every nth frame. Defaults to 1") + +parser.add_argument("--hide_sites", action="store_true", default=False, help="(optional) hide all sites in the scene") + +parser.add_argument( + "--reload_model", + action="store_true", + default=False, +) + +parser.add_argument( + "--keep_models", type=str, nargs="+", default=[], help="(optional) keep the model from the Mujoco XML file" +) + +# adding rendering types +parser.add_argument( + "--rgb", + action="store_true", + default=False, +) +parser.add_argument( + "--normals", + action="store_true", + default=False, +) +parser.add_argument( + "--semantic_segmentation", + action="store_true", + default=False, +) + +# Add arguments for launch +AppLauncher.add_app_launcher_args(parser) +# Parse the arguments +args = parser.parse_args() +# args.headless = True +args.enable_cameras = True +# Launch the Omniverse app +app_launcher = AppLauncher(args) +simulation_app = app_launcher.app + + +import json +import os +import re +import shutil +from enum import Enum + +import carb.settings +import cv2 +import h5py +import lxml.etree as ET +import numpy as np +import omni +import omni.isaac.core.utils.stage as stage_utils +import omni.kit.app +import omni.replicator.core as rep +import omni.timeline +from pxr import Semantics +from termcolor import colored +from tqdm import tqdm + +# Robocasa imports +try: + import robocasa +except ImportError: + print("Warning: Robocasa not found.") + +try: + import dexmimicgen_environments + import mimicgen +except ImportError: + print("Warning: MimicGen not found.") + +# USD imports +import mujoco + +import robosuite +import robosuite.utils.usd.exporter as exporter + +scene_option = mujoco.MjvOption() +scene_option.geomgroup = [0, 1, 0, 0, 0, 0] + +render_modalities = {"rgb": args.rgb, "normals": args.normals, "semantic_segmentation": args.semantic_segmentation} + + +def make_sites_invisible(mujoco_xml): + """ + Makes all site elements in a Mujoco XML string invisible by setting their rgba attribute to fully transparent. + """ + # Parse the Mujoco XML string + root = ET.fromstring(mujoco_xml) + + # Find all site elements + site_elements = root.findall(".//site") + + # Make all site elements invisible by setting rgba attribute + for site in site_elements: + site.set("rgba", "0 0 0 0") # Set rgba to fully transparent + + # Return the modified XML string + return ET.tostring(root, encoding="unicode") + + +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 hasattr(env, "unset_ep_meta"): # unset the ep meta after reset complete + env.unset_ep_meta() + 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 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) + f = h5py.File(dataset_path, "r") + if ds_format == "robomimic": + env_meta = json.loads(f["data"].attrs["env_args"]) + elif ds_format == "robosuite": + env_name = f["data"].attrs["env"] + env_info = json.loads(f["data"].attrs["env_info"]) + env_meta = dict( + env_name=env_name, + env_version=f["data"].attrs["repository_version"], + env_kwargs=env_info, + ) + else: + raise ValueError + f.close() + return env_meta + + +class RobosuiteEnvInterface: + """ + Env wrapper to load a robosuite demonstration + """ + + def __init__( + self, dataset, episode, output_directory, cameras="agentview", reload_model=False, keep_models=[] + ) -> None: + self.dataset = dataset + self.episode = episode + self.output_directory = output_directory + self.cameras = cameras + self.reload_model = reload_model + self.keep_models = keep_models + self.env = self.load_robosuite_environment() + initial_state, self.states = self.get_states() + reset_to(self.env, initial_state) + self.exp = self.link_env_with_ov() + self.traj_len = self.states.shape[0] + + def load_robosuite_environment(self): + """ + Loads the specified robosuite demonstration and + """ + env_meta = get_env_metadata_from_dataset(dataset_path=self.dataset, ds_format=args.ds_format) + env_kwargs = env_meta["env_kwargs"] + env_kwargs["env_name"] = env_meta["env_name"] + env_kwargs["has_renderer"] = False + env_kwargs["has_offscreen_renderer"] = False + env_kwargs["use_camera_obs"] = False + # for robosuite compatibility, remove robocasa specific arguments + if "env_lang" in env_kwargs: + del env_kwargs["env_lang"] + # temporary fix for backward compatibility here to load the correct config if version is less than v1.5.0 + # assume all version number is single digit + if env_meta["env_version"] < "v1.5.0": + from robosuite.controllers import load_composite_controller_config + + if "composite_controller_configs" in env_kwargs: + del env_kwargs["composite_controller_configs"] + robot = env_kwargs["robots"][0] if isinstance(env_kwargs["robots"], list) else env_kwargs["robots"] + if robot == "PandaMobile": + robot = "PandaOmron" + composite_controller_config = load_composite_controller_config(controller=None, robot=robot) + # breakpoint() + env_kwargs["controller_configs"] = composite_controller_config + print(colored("Initializing environment for {}...".format(env_kwargs["env_name"]), "yellow")) + env = robosuite.make(**env_kwargs) + + return env + + def get_states(self): + """ + Gets the initial state of the robosuite demonstration + """ + f = h5py.File(self.dataset, "r+") + ep = "demo_" + str(self.episode) + states = f["data/{}/states".format(ep)][()][:: args.skip_frames] + initial_state = dict(states=states[0]) + model_xml = f["data/{}".format(ep)].attrs["model_file"] + if self.reload_model: + env_xml = self.env.sim.model.get_xml() + for name in self.keep_models: + root_model = ET.fromstring(model_xml) + root_env = ET.fromstring(env_xml) + body_model = root_model.find(".//body[@name='{}']".format(name)) + body_env = root_env.find(".//body[@name='{}']".format(name)) + # change the properties of the body in env to match the model + if body_model is not None and body_env is not None: + for attr_name, attr_value in body_model.attrib.items(): + body_env.set(attr_name, attr_value) + env_xml = ET.tostring(root_env, encoding="unicode") + model_xml = env_xml + + if args.hide_sites: + model_xml = make_sites_invisible(model_xml) + + initial_state["model"] = model_xml + initial_state["ep_meta"] = f["data/{}".format(ep)].attrs.get("ep_meta", None) + + return initial_state, states + + def link_env_with_ov(self): + """ + Loads the initial state of a robosuite scene into simulation + """ + model = self.env.sim.model._model + data = self.env.sim.data._data + + # Create a USD exporter instance with the current stage + stage = None + if args.online: + stage = stage_utils.get_current_stage() + + exp = exporter.USDExporter( + model=model, + output_directory_name=self.output_directory, + camera_names=args.cameras, + online=args.online, + shareable=not args.online, + framerate=20, + stage=stage, + ) + exp.update_scene(data=data, scene_option=scene_option) + exp.add_light(pos=[0, 0, 0], intensity=1500, light_type="dome", light_name="dome_1") + + # adds semantic information to objects in the scene + if args.semantic_segmentation: + for geom in exp.scene.geoms: + geom_id = geom.objid + geom_name = exp._get_geom_name(geom) + if geom_id in self.env.model._geom_ids_to_classes: + semantic_value = self.env.model._geom_ids_to_classes[geom_id] + if "site" in geom_name or "None" in geom_name: + continue + prim = exp.geom_refs[geom_name].usd_prim + instance_name = f"class_{semantic_value}" + sem = Semantics.SemanticsAPI.Apply(prim, instance_name) + sem.CreateSemanticTypeAttr() + sem.CreateSemanticDataAttr() + sem.GetSemanticTypeAttr().Set("class") + sem.GetSemanticDataAttr().Set(semantic_value) + + return exp + + def update_simulation(self, index): + """ + Renders a robosuite trajectory given the state at a given frame + """ + state = self.states[index] + reset_to(self.env, {"states": state}) + data = self.env.sim.data._data + self.exp.update_scene(data=data, scene_option=scene_option) + + def close(self): + if not args.online: + self.exp.save_scene(filetype="usd") + self.env.close() + + +__version__ = "0.0.2" + + +class RobosuiteWriter(rep.Writer): + def __init__( + self, + output_dir: str = None, + image_output_format: str = "png", + rgb: bool = False, + normals: bool = False, + semantic_segmentation: bool = False, + frame_padding: int = 4, + ): + self._output_dir = output_dir + if output_dir: + self._backend = rep.BackendDispatch(output_dir=output_dir) + + self._frame_id = 0 + self._frame_padding = frame_padding + self._sequence_id = 0 + self._image_output_format = image_output_format + self._output_data_format = {} + self.annotators = [] + self.version = __version__ + self.data_structure = "annotator" + self.write_ready = False + + self.rgb = rgb + self.normals = normals + self.semantic_segmentation = semantic_segmentation + + if rgb: + self.annotators.append(rep.AnnotatorRegistry.get_annotator("rgb")) + if normals: + self.annotators.append(rep.AnnotatorRegistry.get_annotator("normals")) + if semantic_segmentation: + self.annotators.append(rep.AnnotatorRegistry.get_annotator("semantic_segmentation", {"colorize": True})) + + def write(self, data: dict): + """Write function called from the OgnWriter node on every frame to process annotator output. + + Args: + data: A dictionary containing the annotator data for the current frame. + """ + if self.write_ready: + for annotator_name, annotator_data in data["annotators"].items(): + for idx, (render_product_name, anno_rp_data) in enumerate(annotator_data.items()): + if annotator_name == "rgb": + filepath = os.path.join( + args.cameras[idx], "rgb", f"rgb_{self._frame_id}.{self._image_output_format}" + ) + self._backend.write_image(filepath, anno_rp_data["data"]) + elif annotator_name == "normals": + normals = anno_rp_data["data"][..., :3] + norm_lengths = np.linalg.norm(normals, axis=-1, keepdims=True) + normals_normalized = normals / np.clip(norm_lengths, 1e-8, None) + img = ((normals_normalized + 1) / 2 * 255).astype(np.uint8) + filepath = os.path.join( + args.cameras[idx], "normals", f"normals_{self._frame_id}.{self._image_output_format}" + ) + self._backend.write_image(filepath, img) + elif annotator_name == "semantic_segmentation": + filepath = os.path.join( + args.cameras[idx], + "semantic_segmentation", + f"semantic_segmentation_{self._frame_id}.{self._image_output_format}", + ) + self._backend.write_image(filepath, anno_rp_data["data"]) + + self._frame_id += 1 + + +rep.WriterRegistry.register(RobosuiteWriter) + + +class RecorderState(Enum): + READY = 0 + RUNNING = 1 + COMPLETED = 2 + + +class DataGenerator: + def __init__(self, robosuite_env) -> None: + # State variables + self.recorder_state = RecorderState.READY + self.writer = None + self.render_products = [] + self.current_frame = 0 + self.robosuite_env = robosuite_env + + # Define writer format + self.writer_name = "RobosuiteWriter" + + self.num_frames = self.robosuite_env.traj_len + self.rt_subframes = 1 + # skip 5 frames at the beginning to allow the scene to settle + self.initial_skip = 5 + + self.output_dir = os.path.abspath(self.robosuite_env.output_directory) + + def _check_if_valid_camera(self, path): + context = omni.usd.get_context() + stage = context.get_stage() + prim = stage.GetPrimAtPath(path) + + if not prim.IsValid(): + print(f"{path} is not a valid prim path.") + return False + + if prim.GetTypeName() == "Camera": + return True + else: + print(f"{prim} is not a 'Camera' type.") + return False + + def _check_if_valid_resolution(self, resolution): + width, height = resolution[0], resolution[1] + MAX_RESOLUTION = (16000, 8000) # 16K + if 0 <= width <= MAX_RESOLUTION[0] and 0 <= height <= MAX_RESOLUTION[1]: + return True + else: + print( + f"Invalid resolution: {width}x{height}. Must be between 1x1 and {MAX_RESOLUTION[0]}x{MAX_RESOLUTION[1]}." + ) + return False + + def load_stage(self): + usd_path = os.path.join(self.output_dir, f"frames/frame_{self.num_frames + 1}.usd") + print(f"Opening stage {usd_path}") + stage_utils.open_stage(usd_path) + print("Stage loaded") + + def init_recorder(self): + # Open USD stage + if not args.online: + self.load_stage() + + if carb.settings.get_settings().get("/omni/replicator/captureOnPlay"): + carb.settings.get_settings().set_bool("/omni/replicator/captureOnPlay", False) + + carb.settings.get_settings().set_bool("/app/renderer/waitIdle", False) + carb.settings.get_settings().set_bool("/app/hydraEngine/waitIdle", False) + carb.settings.get_settings().set_bool("/app/asyncRendering", True) + carb.settings.get_settings().set("/rtx/pathtracing/spp", 30) + carb.settings.get_settings().set_bool("/exts/omni.replicator.core/Orchestrator/enabled", True) + + # Create writer for capturing generated data + self.writer = rep.WriterRegistry.get(self.writer_name) + self.writer.initialize( + output_dir=self.output_dir, + rgb=args.rgb, + normals=args.normals, + semantic_segmentation=args.semantic_segmentation, + ) + + print("Writer Initiazed") + + # Create render products + for camera_name in args.cameras: + resolution = (args.width, args.height) + camera_path = f"/World/Camera_Xform_{camera_name}/Camera_{camera_name}" + if self._check_if_valid_camera(camera_path) and self._check_if_valid_resolution(resolution): + rp = rep.create.render_product(camera_path, (resolution[0], resolution[1]), force_new=True) + self.render_products.append(rp) + else: + print(f"Invalid render product entry: {camera_path}") + + print("Render products created") + + # Attach render products to writers + if self.render_products: + self.writer.attach(self.render_products) + else: + print("No valid render products found to initialize the writer.") + return False + + print("Render products attached") + return True + + def start_recorder(self): + if self.recorder_state == RecorderState.READY and self.init_recorder(): + self.recorder_state = RecorderState.RUNNING + self.run_recording_loop() + else: + self.finish_recording() + + def run_recording_loop(self): + max_frames = self.num_frames if self.num_frames > 0 else 200 # Testing + print(f"Recording {max_frames} frames to: {self.output_dir}") + + for _ in range(self.initial_skip): + rep.orchestrator.step(rt_subframes=1, delta_time=None, pause_timeline=False) + + self.writer.write_ready = True + if not args.online: + timeline = omni.timeline.get_timeline_interface() + timeline.set_end_time(max_frames) + with tqdm(total=max_frames) as pbar: + while self.current_frame < max_frames: + if self.recorder_state != RecorderState.RUNNING: + break + if args.online: + self.robosuite_env.update_simulation(self.current_frame) + else: + timeline.forward_one_frame() + rep.orchestrator.step(rt_subframes=self.rt_subframes, delta_time=None, pause_timeline=True) + self.current_frame += 1 + pbar.update(1) + + if self.recorder_state == RecorderState.RUNNING: + self.finish_recording() + + def finish_recording(self): + if not args.online: + timeline = omni.timeline.get_timeline_interface() + timeline.stop() + rep.orchestrator.wait_until_complete() + print(f"[SDR] Finished;\tWrote {self.current_frame} frames to: {self.output_dir};") + self.clear_recorder() + self.recorder_state = RecorderState.COMPLETED + + def clear_recorder(self): + if self.recorder_state != RecorderState.COMPLETED: + self.recorder_state = RecorderState.COMPLETED + if self.writer: + self.writer.detach() + self.writer = None + for rp in self.render_products: + rp.destroy() + self.render_products.clear() + stage_utils.clear_stage() + if args.online: + stage_utils.close_stage() + stage_utils.create_new_stage() + stage_utils.update_stage() + + def natural_sort_key(self, s): + return [int(c) if c.isdigit() else c.lower() for c in re.split(r"(\d+)", s)] + + def create_video_from_frames(self, frame_folder, output_path, fps=30): + frames = [f for f in os.listdir(frame_folder) if f.endswith(".png")] + frames.sort(key=self.natural_sort_key) + assert ( + len(frames) == self.current_frame + ), f"Number of frames in folder ({len(frames)}) does not match number of frames rendered ({self.current_frame})" + if not frames: + print(f"No frames found in {frame_folder}") + return + + first_frame = cv2.imread(os.path.join(frame_folder, frames[0])) + height, width, layers = first_frame.shape + + fourcc = cv2.VideoWriter_fourcc(*"mp4v") + video = cv2.VideoWriter(output_path, fourcc, fps, (width, height)) + + for frame in frames: + video.write(cv2.imread(os.path.join(frame_folder, frame))) + + video.release() + print(f"Video saved: {output_path}") + + def create_video(self, videos_folder, camera, data_type): + camera_folder_path = os.path.join(self.output_dir, camera, data_type) # temp, change to render type + if not os.path.isdir(camera_folder_path): + return + + # Construct output filename and path + output_filename = f"{camera}_{data_type}.mp4" + output_path = os.path.join(videos_folder, output_filename) + + # Create the video from the frames in the camera folder + self.create_video_from_frames(camera_folder_path, output_path) + + def process_folders(self): + videos_folder = os.path.join(self.output_dir, "videos") + os.makedirs(videos_folder, exist_ok=True) + + # Iterate over each camera folder in the output directory + for camera in args.cameras: + for render_modality, selected in render_modalities.items(): + if selected: + self.create_video(videos_folder=videos_folder, camera=camera, data_type=render_modality) + + +def main(): + f = h5py.File(args.dataset, "r") + total_episodes = args.episode + if not total_episodes: + # get all the int keys + total_episodes = [int(k.split("_")[1]) for k in f["data"].keys()] + f.close() + print(f"Total episodes: {total_episodes}") + dataset_name = "_".join(args.dataset.split("/")[-1].split(".")[:-1]) + if args.output_directory is None: + # use the dataset directory + args.output_directory = os.path.dirname(args.dataset) + + for episode in total_episodes: + output_directory = os.path.join(args.output_directory, dataset_name, "demo_" + str(episode)) + robosuite_env = RobosuiteEnvInterface( + dataset=args.dataset, + episode=episode, + output_directory=output_directory, + cameras=args.cameras, + reload_model=args.reload_model, + keep_models=args.keep_models, + ) + if not args.online: + # generate the usd first, and close the env to save the usd + for i in tqdm(range(robosuite_env.traj_len)): + robosuite_env.update_simulation(i) + robosuite_env.close() + + data_generator = DataGenerator(robosuite_env) + data_generator.start_recorder() + + while data_generator.recorder_state != RecorderState.COMPLETED: + stage_utils.update_stage() + + if args.save_video: + data_generator.process_folders() + + # remove all image frames + for camera in args.cameras: + camera_folder_path = os.path.join(output_directory, camera) + if os.path.isdir(camera_folder_path): + shutil.rmtree(camera_folder_path) + + print("Recording complete") + + +if __name__ == "__main__": + main() + print("Script execution completed.") diff --git a/third_party/robosuite/robosuite/scripts/setup_macros.py b/third_party/robosuite/robosuite/scripts/setup_macros.py new file mode 100644 index 0000000000000000000000000000000000000000..16abdde5ad8246d018e387890e2c32539602e1b3 --- /dev/null +++ b/third_party/robosuite/robosuite/scripts/setup_macros.py @@ -0,0 +1,31 @@ +""" +This script sets up a private macros file. +The private macros file (macros_private.py) is not tracked by git, +allowing user-specific settings that are not tracked by git. +This script checks if macros_private.py exists. +If applicable, it creates the private macros at robosuite/macros_private.py +""" + +import os +import shutil + +import robosuite + +if __name__ == "__main__": + base_path = robosuite.__path__[0] + macros_path = os.path.join(base_path, "macros.py") + macros_private_path = os.path.join(base_path, "macros_private.py") + + if not os.path.exists(macros_path): + print("{} does not exist! Aborting...".format(macros_path)) + + if os.path.exists(macros_private_path): + ans = input("{} already exists! \noverwrite? (y/n)\n".format(macros_private_path)) + + if ans == "y": + print("REMOVING") + else: + exit() + + shutil.copyfile(macros_path, macros_private_path) + print("copied {}\nto {}".format(macros_path, macros_private_path)) diff --git a/third_party/robosuite/robosuite/scripts/tune_camera.py b/third_party/robosuite/robosuite/scripts/tune_camera.py new file mode 100644 index 0000000000000000000000000000000000000000..e27e380b743fd158298157d7f9046a419c36f93f --- /dev/null +++ b/third_party/robosuite/robosuite/scripts/tune_camera.py @@ -0,0 +1,226 @@ +""" +Convenience script to tune a camera view in a mujoco environment. +Allows keyboard presses to move a camera around in the viewer, and +then prints the final position and quaternion you should set +for your camera in the mujoco XML file. +""" + +import argparse +import time +import xml.etree.ElementTree as ET + +import numpy as np +from pynput.keyboard import Controller, Key, Listener + +import robosuite +import robosuite.utils.transform_utils as T +from robosuite.utils.camera_utils import CameraMover +from robosuite.utils.mjcf_utils import find_elements, find_parent + +# some settings +DELTA_POS_KEY_PRESS = 0.05 # delta camera position per key press +DELTA_ROT_KEY_PRESS = 1 # delta camera angle per key press + + +class KeyboardHandler: + def __init__(self, camera_mover): + """ + Store internal state here. + + Args: + camera_mover (CameraMover): Playback camera class + cam_body_id (int): id corresponding to parent body of camera element + """ + self.camera_mover = camera_mover + + # 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() + + def on_press(self, key): + """ + Key handler for key presses. + + Args: + key (int): keycode corresponding to the key that was pressed + """ + + try: + # controls for moving rotation + if key == Key.up: + # rotate up + self.camera_mover.rotate_camera(point=None, axis=[1.0, 0.0, 0.0], angle=DELTA_ROT_KEY_PRESS) + elif key == Key.down: + # rotate down + self.camera_mover.rotate_camera(point=None, axis=[-1.0, 0.0, 0.0], angle=DELTA_ROT_KEY_PRESS) + elif key == Key.left: + # rotate left + self.camera_mover.rotate_camera(point=None, axis=[0.0, 1.0, 0.0], angle=DELTA_ROT_KEY_PRESS) + elif key == Key.right: + # rotate right + self.camera_mover.rotate_camera(point=None, axis=[0.0, -1.0, 0.0], angle=DELTA_ROT_KEY_PRESS) + + # controls for moving position + elif key.char == "w": + # move forward + self.camera_mover.move_camera(direction=[0.0, 0.0, -1.0], scale=DELTA_POS_KEY_PRESS) + elif key.char == "s": + # move backward + self.camera_mover.move_camera(direction=[0.0, 0.0, 1.0], scale=DELTA_POS_KEY_PRESS) + elif key.char == "a": + # move left + self.camera_mover.move_camera(direction=[-1.0, 0.0, 0.0], scale=DELTA_POS_KEY_PRESS) + elif key.char == "d": + # move right + self.camera_mover.move_camera(direction=[1.0, 0.0, 0.0], scale=DELTA_POS_KEY_PRESS) + elif key.char == "r": + # move up + self.camera_mover.move_camera(direction=[0.0, 1.0, 0.0], scale=DELTA_POS_KEY_PRESS) + elif key.char == "f": + # move down + self.camera_mover.move_camera(direction=[0.0, -1.0, 0.0], scale=DELTA_POS_KEY_PRESS) + elif key.char == ".": + # rotate counterclockwise + self.camera_mover.rotate_camera(point=None, axis=[0.0, 0.0, 1.0], angle=DELTA_ROT_KEY_PRESS) + elif key.char == "/": + # rotate clockwise + self.camera_mover.rotate_camera(point=None, axis=[0.0, 0.0, -1.0], angle=DELTA_ROT_KEY_PRESS) + + except AttributeError as e: + pass + + def on_release(self, key): + """ + Key handler for key releases. + + Args: + key: [NOT USED] + """ + pass + + +def print_command(char, info): + """ + Prints out the command + relevant info entered by user + + Args: + char (str): Command entered + info (str): Any additional info to print + """ + char += " " * (10 - len(char)) + print("{}\t{}".format(char, info)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--env", type=str, default="Lift") + parser.add_argument("--robots", nargs="+", type=str, default="Sawyer", help="Which robot(s) to use in the env") + args = parser.parse_args() + + print("\nWelcome to the camera tuning script! You will be able to tune a camera view") + print("by moving it around using your keyboard. The controls are printed below.") + + print("") + print_command("Keys", "Command") + print_command("w-s", "zoom the camera in/out") + print_command("a-d", "pan the camera left/right") + print_command("r-f", "pan the camera up/down") + print_command("arrow keys", "rotate the camera to change view direction") + print_command(".-/", "rotate the camera view without changing view direction") + print("") + + # read camera XML tag from user input + inp = input( + "\nPlease paste a camera name below \n" + "OR xml tag below (e.g. ) \n" + "OR leave blank for an example:\n" + ) + + if len(inp) == 0: + if args.env != "Lift": + raise Exception("ERROR: env must be Lift to run default example.") + print("\nUsing an example tag corresponding to the frontview camera.") + print("This xml tag was copied from robosuite/models/assets/arenas/table_arena.xml") + inp = '' + + # remember the tag and infer some properties + from_tag = "<" in inp + notify_str = ( + "NOTE: using the following xml tag:\n" + if from_tag + else "NOTE: using the following camera (initialized at default sim location)\n" + ) + + print(notify_str) + print("{}\n".format(inp)) + + cam_tree = ET.fromstring(inp) if from_tag else ET.Element("camera", attrib={"name": inp}) + CAMERA_NAME = cam_tree.get("name") + + # make the environment + env = robosuite.make( + args.env, + robots=args.robots, + has_renderer=True, + has_offscreen_renderer=False, + ignore_done=True, + use_camera_obs=False, + control_freq=100, + ) + env.reset() + + # Create the camera mover + camera_mover = CameraMover( + env=env, + camera=CAMERA_NAME, + ) + + # Make sure we're using the camera that we're modifying + camera_id = env.sim.model.camera_name2id(CAMERA_NAME) + env.viewer.set_camera(camera_id=camera_id) + + # Infer initial camera pose + if from_tag: + initial_file_camera_pos = np.array(cam_tree.get("pos").split(" ")).astype(float) + initial_file_camera_quat = T.convert_quat(np.array(cam_tree.get("quat").split(" ")).astype(float), to="xyzw") + # Set these values as well + camera_mover.set_camera_pose(pos=initial_file_camera_pos, quat=initial_file_camera_quat) + # Optionally set fov if specified + cam_fov = cam_tree.get("fovy", None) + if cam_fov is not None: + env.sim.model.cam_fovy[camera_id] = float(cam_fov) + else: + initial_file_camera_pos, initial_file_camera_quat = camera_mover.get_camera_pose() + # Define initial file camera pose + initial_file_camera_pose = T.make_pose(initial_file_camera_pos, T.quat2mat(initial_file_camera_quat)) + + # remember difference between camera pose in initial tag and absolute camera pose in world + initial_world_camera_pos, initial_world_camera_quat = camera_mover.get_camera_pose() + initial_world_camera_pose = T.make_pose(initial_world_camera_pos, T.quat2mat(initial_world_camera_quat)) + world_in_file = initial_file_camera_pose.dot(T.pose_inv(initial_world_camera_pose)) + + # register callbacks to handle key presses in the viewer + key_handler = KeyboardHandler(camera_mover=camera_mover) + + # just spin to let user interact with window + spin_count = 0 + while True: + action = np.zeros(env.action_dim) + obs, reward, done, _ = env.step(action) + env.render() + spin_count += 1 + if spin_count % 500 == 0: + # convert from world coordinates to file coordinates (xml subtree) + camera_pos, camera_quat = camera_mover.get_camera_pose() + world_camera_pose = T.make_pose(camera_pos, T.quat2mat(camera_quat)) + file_camera_pose = world_in_file.dot(world_camera_pose) + # TODO: Figure out why numba causes black screen of death (specifically, during mat2pose --> mat2quat call below) + camera_pos, camera_quat = T.mat2pose(file_camera_pose) + camera_quat = T.convert_quat(camera_quat, to="wxyz") + + print("\n\ncurrent camera tag you should copy") + cam_tree.set("pos", "{} {} {}".format(camera_pos[0], camera_pos[1], camera_pos[2])) + cam_tree.set("quat", "{} {} {} {}".format(camera_quat[0], camera_quat[1], camera_quat[2], camera_quat[3])) + print(ET.tostring(cam_tree, encoding="utf8").decode("utf8")) diff --git a/third_party/robosuite/robosuite/scripts/tune_joints.py b/third_party/robosuite/robosuite/scripts/tune_joints.py new file mode 100644 index 0000000000000000000000000000000000000000..b6e94ef9347cf25a96e27a3ca8b036b2026b85b3 --- /dev/null +++ b/third_party/robosuite/robosuite/scripts/tune_joints.py @@ -0,0 +1,315 @@ +""" +Convenience script to tune a robot's joint positions in a mujoco environment. +Allows keyboard presses to move specific robot joints around in the viewer, and +then prints the current joint parameters upon an inputted command + +RELEVANT KEY PRESSES: + '1 - n' : Sets the active robot joint being tuned to this number. Maximum + is n which is the number of robot joints + 't' : Toggle between robot arms being tuned (only applicable for multi-arm environments) + 'r' : Resets the active joint values to 0 + 'UP_ARROW' : Increment the active robot joint position + 'DOWN_ARROW' : Decrement the active robot joint position + 'RIGHT_ARROW' : Increment the delta joint position change per keypress + 'LEFT_ARROW' : Decrement the delta joint position change per keypress + +""" + +import argparse + +import numpy as np +from pynput.keyboard import Key, Listener + +import robosuite + + +class KeyboardHandler: + def __init__(self, env, delta=0.05): + """ + Store internal state here. + + Args: + env (MujocoEnv): Environment to use + delta (float): initial joint tuning increment + """ + self.env = env + self.delta = delta + self.num_robots = len(env.robots) + self.active_robot_num = 0 + self.active_arm_joint = 1 + self.active_arm = "right" # only relevant for bimanual robots + self.current_joints_pos = env.sim.data.qpos[self.active_robot._ref_joint_pos_indexes[: self.num_joints]] + + # 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() + + def on_press(self, key): + """ + Key handler for key presses. + + Args: + key (int): keycode corresponding to the key that was pressed + """ + + try: + if key == Key.up: + # Increment the active joint + self._update_joint_position(self.active_arm_joint, self.delta) + elif key == Key.down: + # Decrement the active joint + self._update_joint_position(self.active_arm_joint, -self.delta) + elif key == Key.right: + # Increment the delta value + self.delta = min(1.0, self.delta + 0.005) + # Print out new value to user + print("Delta now = {:.3f}".format(self.delta)) + elif key == Key.left: + # Decrement the delta value + self.delta = max(0, self.delta - 0.005) + print("Delta now = {:.3f}".format(self.delta)) + # controls for setting active arm + elif key.char == "0": + # Notify use that joint indexes are 1-indexed + print("Joint Indexes are 1-Indexed. Available joints are 1 - {}".format(self.num_joints)) + elif key.char == "1": + # Make sure range is valid; if so, update this specific joint + if self._check_valid_joint(1): + self.active_arm_joint = 1 + # Print out to user + print("New joint being tuned: {}".format(self.active_arm_joint)) + elif key.char == "2": + # Make sure range is valid; if so, update this specific joint + if self._check_valid_joint(2): + self.active_arm_joint = 2 + # Print out to user + print("New joint being tuned: {}".format(self.active_arm_joint)) + elif key.char == "3": + # Make sure range is valid; if so, update this specific joint + if self._check_valid_joint(3): + self.active_arm_joint = 3 + # Print out to user + print("New joint being tuned: {}".format(self.active_arm_joint)) + elif key.char == "4": + # Make sure range is valid; if so, update this specific joint + if self._check_valid_joint(4): + self.active_arm_joint = 4 + # Print out to user + print("New joint being tuned: {}".format(self.active_arm_joint)) + elif key.char == "5": + # Make sure range is valid; if so, update this specific joint + if self._check_valid_joint(5): + self.active_arm_joint = 5 + # Print out to user + print("New joint being tuned: {}".format(self.active_arm_joint)) + elif key.char == "6": + # Make sure range is valid; if so, update this specific joint + if self._check_valid_joint(6): + self.active_arm_joint = 6 + # Print out to user + print("New joint being tuned: {}".format(self.active_arm_joint)) + elif key.char == "7": + # Make sure range is valid; if so, update this specific joint + if self._check_valid_joint(7): + self.active_arm_joint = 7 + # Print out to user + print("New joint being tuned: {}".format(self.active_arm_joint)) + elif key.char == "8": + # Make sure range is valid; if so, update this specific joint + if self._check_valid_joint(8): + self.active_arm_joint = 8 + # Print out to user + print("New joint being tuned: {}".format(self.active_arm_joint)) + elif key.char == "9": + # Make sure range is valid; if so, update this specific joint + if self._check_valid_joint(9): + self.active_arm_joint = 9 + # Print out to user + print("New joint being tuned: {}".format(self.active_arm_joint)) + elif key.char == "t": + # Toggle active arm + self._toggle_arm() + elif key.char == "r": + # Reset active arm joint qpos to 0 + self.set_joint_positions(np.zeros(self.num_joints)) + + except AttributeError as e: + pass + + def on_release(self, key): + """ + Key handler for key releases. + + Args: + key: [NOT USED] + """ + pass + + def set_joint_positions(self, qpos): + """ + Automatically sets the joint positions to be the given value + + Args: + qpos (np.array): Joint positions to set + """ + self.current_joints_pos = qpos + self._update_joint_position(1, 0) + + def _check_valid_joint(self, i): + """ + Checks to make sure joint number request @i is within valid range + + Args: + i (int): Index to validate + + Returns: + bool: True if index @i is valid, else prints out an error and returns False + """ + if i > self.num_joints: + # Print error + print("Error: Requested joint {} is out of range; available joints are 1 - {}".format(i, self.num_joints)) + return False + else: + return True + + def _toggle_arm(self): + """ + Toggle between arms in the environment to set as current active arm + """ + if len(self.active_robot.arms) == 1: + self.active_robot_num = (self.active_robot_num + 1) % self.num_robots + robot = self.active_robot_num + elif len(self.active_robot.arms) == 2: + self.active_arm = "left" if self.active_arm == "right" else "right" + robot = self.active_arm + else: + raise ValueError("number of arms must be 1 or 2") + # Reset joint being controlled to 1 + self.active_arm_joint = 1 + # Print out new robot to user + print("New robot arm being tuned: {}".format(robot)) + + def _update_joint_position(self, i, delta): + """ + Updates specified joint position @i by value @delta from its current position + Note: assumes @i is already within the valid joint range + + Args: + i (int): Joint index to update + delta (float): Increment to alter specific joint by + """ + self.current_joints_pos[i - 1] += delta + if len(self.active_robot.arms) == 1: + robot = self.active_robot_num + self.env.sim.data.qpos[self.active_robot._ref_joint_pos_indexes] = self.current_joints_pos + elif len(self.active_robot.arms) == 2: + robot = self.active_arm + if self.active_arm == "right": + self.env.sim.data.qpos[ + self.active_robot._ref_joint_pos_indexes[: self.num_joints] + ] = self.current_joints_pos + else: # left arm case + self.env.sim.data.qpos[ + self.active_robot._ref_joint_pos_indexes[self.num_joints :] + ] = self.current_joints_pos + else: + raise ValueError("number of arms must be 1 or 2") + # Print out current joint positions to user + print("Robot {} joint qpos: {}".format(robot, self.current_joints_pos)) + + @property + def active_robot(self): + """ + Returns: + Robot: active robot arm currently being tuned + """ + return self.env.robots[self.active_robot_num] + + @property + def num_joints(self): + """ + Returns: + int: number of joints for the current arm + """ + if len(self.active_robot.arms) == 1: + return len(self.active_robot.torque_limits[0]) + elif len(self.active_robot.arms) == 2: + return int(len(self.active_robot.torque_limits[0]) / 2) + else: + raise ValueError("number of arms must be 1 or 2") + + +def print_command(char, info): + """ + Prints out the command + relevant info entered by user + + Args: + char (str): Command entered + info (str): Any additional info to print + """ + char += " " * (10 - len(char)) + print("{}\t{}".format(char, info)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--env", 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( + "--init_qpos", nargs="+", type=float, default=0, help="Initial qpos to use. 0 defaults to all zeros" + ) + + args = parser.parse_args() + + print( + "\nWelcome to the joint tuning script! You will be able to tune the robot\n" + "arm joints in the specified environment by using your keyboard. The \n" + "controls are printed below:" + ) + + print("") + print_command("Keys", "Command") + print_command("1-N", "Active Joint being tuned (N=number of joints for the active arm)") + print_command("t", "Toggle between robot arms in the environment") + print_command("r", "Reset active arm joints to all 0s") + print_command("up/down", "incr/decrement the active joint angle") + print("") + + # Setup printing options for numbers + np.set_printoptions(formatter={"float": lambda x: "{0:0.3f}".format(x)}) + + # Define the controller + controller_config = robosuite.load_composite_controller_config(controller="BASIC") + + # make the environment + env = robosuite.make( + args.env, + robots=args.robots, + has_renderer=True, + has_offscreen_renderer=False, + ignore_done=True, + use_camera_obs=False, + control_freq=20, + render_camera=None, + controller_configs=controller_config, + initialization_noise=None, + ) + env.reset() + + # register callbacks to handle key presses in the viewer + key_handler = KeyboardHandler(env=env) + + # Set initial state + if type(args.init_qpos) == int and args.init_qpos == 0: + # Default to all zeros + pass + else: + key_handler.set_joint_positions(args.init_qpos) + + # just spin to let user interact with window + while True: + action = np.zeros(env.action_dim) + obs, reward, done, _ = env.step(action) + env.render() diff --git a/third_party/robosuite/robosuite/utils/__init__.py b/third_party/robosuite/robosuite/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..70f80caa075d3150eb8346a4aae00fdf6438f499 --- /dev/null +++ b/third_party/robosuite/robosuite/utils/__init__.py @@ -0,0 +1,3 @@ +from .errors import robosuiteError, XMLError, SimulationError, RandomizationError + +from .opencv_renderer import OpenCVRenderer diff --git a/third_party/robosuite/robosuite/utils/binding_utils.py b/third_party/robosuite/robosuite/utils/binding_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ad09297f4a535a67a3daf59ed36cc6ce0286f377 --- /dev/null +++ b/third_party/robosuite/robosuite/utils/binding_utils.py @@ -0,0 +1,1187 @@ +""" +Useful classes for supporting DeepMind MuJoCo binding. +""" + +import gc +import os +from tempfile import TemporaryDirectory + +# DIRTY HACK copied from mujoco-py - a global lock on rendering +from threading import Lock + +import mujoco +import numpy as np + +_MjSim_render_lock = Lock() + +import ctypes +import ctypes.util +import os +import platform +import subprocess + +import robosuite.macros as macros + +_SYSTEM = platform.system() +if _SYSTEM == "Windows": + ctypes.WinDLL(os.path.join(os.path.dirname(__file__), "mujoco.dll")) + +CUDA_VISIBLE_DEVICES = os.environ.get("CUDA_VISIBLE_DEVICES", "") +if CUDA_VISIBLE_DEVICES != "": + MUJOCO_EGL_DEVICE_ID = os.environ.get("MUJOCO_EGL_DEVICE_ID", None) + if MUJOCO_EGL_DEVICE_ID is not None: + assert MUJOCO_EGL_DEVICE_ID.isdigit() and ( + MUJOCO_EGL_DEVICE_ID in CUDA_VISIBLE_DEVICES + ), "MUJOCO_EGL_DEVICE_ID needs to be set to one of the device id specified in CUDA_VISIBLE_DEVICES" + +if macros.MUJOCO_GPU_RENDERING and os.environ.get("MUJOCO_GL", None) not in ["osmesa", "glx"]: + # If gpu rendering is specified in macros, then we enforce gpu + # option for rendering + if _SYSTEM == "Darwin": + os.environ["MUJOCO_GL"] = "cgl" + else: + os.environ["MUJOCO_GL"] = "egl" +_MUJOCO_GL = os.environ.get("MUJOCO_GL", "").lower().strip() + + +class MjRenderContext: + """ + Class that encapsulates rendering functionality for a + MuJoCo simulation. + + See https://github.com/openai/mujoco-py/blob/4830435a169c1f3e3b5f9b58a7c3d9c39bdf4acb/mujoco_py/mjrendercontext.pyx + """ + + def __init__(self, sim, offscreen=True, device_id=-1, max_width=640, max_height=480): + + # move this logic from outside to inside class to avoid multiprocessing issues + if _MUJOCO_GL not in ("disable", "disabled", "off", "false", "0"): + _VALID_MUJOCO_GL = ("enable", "enabled", "on", "true", "1", "glfw", "") + if _SYSTEM == "Linux": + _VALID_MUJOCO_GL += ("glx", "egl", "osmesa") + elif _SYSTEM == "Windows": + _VALID_MUJOCO_GL += ("wgl",) + elif _SYSTEM == "Darwin": + _VALID_MUJOCO_GL += ("cgl",) + if _MUJOCO_GL not in _VALID_MUJOCO_GL: + raise RuntimeError(f"invalid value for environment variable MUJOCO_GL: {_MUJOCO_GL}") + if _SYSTEM == "Linux" and _MUJOCO_GL == "osmesa": + from robosuite.renderers.context.osmesa_context import OSMesaGLContext as GLContext + elif _SYSTEM == "Linux" and _MUJOCO_GL == "egl": + from robosuite.renderers.context.egl_context import EGLGLContext as GLContext + else: + from robosuite.renderers.context.glfw_context import GLFWGLContext as GLContext + + assert offscreen, "only offscreen supported for now" + self.sim = sim + self.offscreen = offscreen + self.device_id = device_id + + # setup GL context with defaults for now + self.gl_ctx = GLContext(max_width=max_width, max_height=max_height, device_id=self.device_id) + self.gl_ctx.make_current() + + # Ensure the model data has been updated so that there + # is something to render + sim.forward() + # make sure sim has this context + sim.add_render_context(self) + + self.model = sim.model + self.data = sim.data + + # create default scene + # set maxgeom to 10k to support large-scale scenes + self.scn = mujoco.MjvScene(sim.model._model, maxgeom=10000) + + # camera + self.cam = mujoco.MjvCamera() + self.cam.fixedcamid = 0 + self.cam.type = mujoco.mjtCamera.mjCAMERA_FIXED + + # options for visual / collision mesh can be set externally, e.g. vopt.geomgroup[0], vopt.geomgroup[1] + self.vopt = mujoco.MjvOption() + + self.pert = mujoco.MjvPerturb() + self.pert.active = 0 + self.pert.select = 0 + self.pert.skinselect = -1 + + # self._markers = [] + # self._overlay = {} + + self._set_mujoco_context_and_buffers() + + def _set_mujoco_context_and_buffers(self): + self.con = mujoco.MjrContext(self.model._model, mujoco.mjtFontScale.mjFONTSCALE_150) + mujoco.mjr_setBuffer(mujoco.mjtFramebuffer.mjFB_OFFSCREEN, self.con) + + def update_offscreen_size(self, width, height): + if (width != self.con.offWidth) or (height != self.con.offHeight): + self.model.vis.global_.offwidth = width + self.model.vis.global_.offheight = height + self.con.free() + del self.con + self._set_mujoco_context_and_buffers() + + def render(self, width, height, camera_id=None, segmentation=False): + viewport = mujoco.MjrRect(0, 0, width, height) + + # if self.sim.render_callback is not None: + # self.sim.render_callback(self.sim, self) + + # update width and height of rendering context if necessary + if width > self.con.offWidth or height > self.con.offHeight: + new_width = max(width, self.model.vis.global_.offwidth) + new_height = max(height, self.model.vis.global_.offheight) + self.update_offscreen_size(new_width, new_height) + + if camera_id is not None: + if camera_id == -1: + self.cam.type = mujoco.mjtCamera.mjCAMERA_FREE + else: + self.cam.type = mujoco.mjtCamera.mjCAMERA_FIXED + self.cam.fixedcamid = camera_id + + mujoco.mjv_updateScene( + self.model._model, self.data._data, self.vopt, self.pert, self.cam, mujoco.mjtCatBit.mjCAT_ALL, self.scn + ) + + if segmentation: + self.scn.flags[mujoco.mjtRndFlag.mjRND_SEGMENT] = 1 + self.scn.flags[mujoco.mjtRndFlag.mjRND_IDCOLOR] = 1 + + # for marker_params in self._markers: + # self._add_marker_to_scene(marker_params) + + mujoco.mjr_render(viewport=viewport, scn=self.scn, con=self.con) + # for gridpos, (text1, text2) in self._overlay.items(): + # mjr_overlay(const.FONTSCALE_150, gridpos, rect, text1.encode(), text2.encode(), &self._con) + + if segmentation: + self.scn.flags[mujoco.mjtRndFlag.mjRND_SEGMENT] = 0 + self.scn.flags[mujoco.mjtRndFlag.mjRND_IDCOLOR] = 0 + + def read_pixels(self, width, height, depth=False, segmentation=False): + viewport = mujoco.MjrRect(0, 0, width, height) + rgb_img = np.empty((height, width, 3), dtype=np.uint8) + depth_img = np.empty((height, width), dtype=np.float32) if depth else None + + mujoco.mjr_readPixels(rgb=rgb_img, depth=depth_img, viewport=viewport, con=self.con) + + ret_img = rgb_img + if segmentation: + uint32_rgb_img = rgb_img.astype(np.int32) + seg_img = uint32_rgb_img[:, :, 0] + uint32_rgb_img[:, :, 1] * (2**8) + uint32_rgb_img[:, :, 2] * (2**16) + seg_img[seg_img >= (self.scn.ngeom + 1)] = 0 + seg_ids = np.full((self.scn.ngeom + 1, 2), fill_value=-1, dtype=np.int32) + + for i in range(self.scn.ngeom): + geom = self.scn.geoms[i] + if geom.segid != -1: + seg_ids[geom.segid + 1, 0] = geom.objtype + seg_ids[geom.segid + 1, 1] = geom.objid + ret_img = seg_ids[seg_img] + + if depth: + return (ret_img, depth_img) + else: + return ret_img + + def upload_texture(self, tex_id): + """Uploads given texture to the GPU.""" + self.gl_ctx.make_current() + mujoco.mjr_uploadTexture(self.model._model, self.con, tex_id) + + def __del__(self): + # free mujoco rendering context and GL rendering context + self.con.free() + try: + self.gl_ctx.free() + except Exception: + # avoid getting OpenGL.error.GLError + pass + del self.con + del self.gl_ctx + del self.scn + del self.cam + del self.vopt + del self.pert + + +class MjRenderContextOffscreen(MjRenderContext): + def __init__(self, sim, device_id, max_width=640, max_height=480): + super().__init__(sim, offscreen=True, device_id=device_id, max_width=max_width, max_height=max_height) + + +class MjSimState: + """ + A mujoco simulation state. + """ + + def __init__(self, time, qpos, qvel): + self.time = time + self.qpos = qpos + self.qvel = qvel + + @classmethod + def from_flattened(cls, array, sim): + """ + Takes flat mjstate array and MjSim instance and + returns MjSimState. + """ + idx_time = 0 + idx_qpos = idx_time + 1 + idx_qvel = idx_qpos + sim.model.nq + + time = array[idx_time] + qpos = array[idx_qpos : idx_qpos + sim.model.nq] + qvel = array[idx_qvel : idx_qvel + sim.model.nv] + assert sim.model.na == 0 + + return cls(time=time, qpos=qpos, qvel=qvel) + + def flatten(self): + return np.concatenate([[self.time], self.qpos, self.qvel], axis=0) + + +class _MjModelMeta(type): + """ + Metaclass which allows MjModel below to delegate to mujoco.MjModel. + + Taken from dm_control: https://github.com/deepmind/dm_control/blob/main/dm_control/mujoco/wrapper/core.py#L244 + """ + + def __new__(cls, name, bases, dct): + for attr in dir(mujoco.MjModel): + if not attr.startswith("_"): + if attr not in dct: + # pylint: disable=protected-access + fget = lambda self, attr=attr: getattr(self._model, attr) + fset = lambda self, value, attr=attr: setattr(self._model, attr, value) + # pylint: enable=protected-access + dct[attr] = property(fget, fset) + return super().__new__(cls, name, bases, dct) + + +class MjModel(metaclass=_MjModelMeta): + """Wrapper class for a MuJoCo 'mjModel' instance. + MjModel encapsulates features of the model that are expected to remain + constant. It also contains simulation and visualization options which may be + changed occasionally, although this is done explicitly by the user. + """ + + _HAS_DYNAMIC_ATTRIBUTES = True + + def __init__(self, model_ptr): + """Creates a new MjModel instance from a mujoco.MjModel.""" + self._model = model_ptr + + # make useful mappings such as _body_name2id and _body_id2name + self.make_mappings() + + def __del__(self): + # free mujoco model + del self._model + + """ + Some methods supported by sim.model in mujoco-py. + Copied from https://github.com/openai/mujoco-py/blob/ab86d331c9a77ae412079c6e58b8771fe63747fc/mujoco_py/generated/wrappers.pxi#L2611 + """ + + def _extract_mj_names(self, name_adr, num_obj, obj_type): + """ + See https://github.com/openai/mujoco-py/blob/ab86d331c9a77ae412079c6e58b8771fe63747fc/mujoco_py/generated/wrappers.pxi#L1127 + """ + + ### TODO: fix this to use @name_adr like mujoco-py - more robust than assuming IDs are continuous ### + + # objects don't need to be named in the XML, so name might be None + id2name = {i: None for i in range(num_obj)} + name2id = {} + for i in range(num_obj): + name = mujoco.mj_id2name(self._model, obj_type, i) + name2id[name] = i + id2name[i] = name + + # # objects don't need to be named in the XML, so name might be None + # id2name = { i: None for i in range(num_obj) } + # name2id = {} + # for i in range(num_obj): + # name = self.model.names[name_adr[i]] + # decoded_name = name.decode() + # if decoded_name: + # obj_id = mujoco.mj_name2id(self.model, obj_type, name) + # assert (0 <= obj_id < num_obj) and (id2name[obj_id] is None) + # name2id[decoded_name] = obj_id + # id2name[obj_id] = decoded_name + + # sort names by increasing id to keep order deterministic + return tuple(id2name[nid] for nid in sorted(name2id.values())), name2id, id2name + + def make_mappings(self): + """ + Make some useful internal mappings that mujoco-py supported. + """ + p = self + self.body_names, self._body_name2id, self._body_id2name = self._extract_mj_names( + p.name_bodyadr, p.nbody, mujoco.mjtObj.mjOBJ_BODY + ) + self.joint_names, self._joint_name2id, self._joint_id2name = self._extract_mj_names( + p.name_jntadr, p.njnt, mujoco.mjtObj.mjOBJ_JOINT + ) + self.geom_names, self._geom_name2id, self._geom_id2name = self._extract_mj_names( + p.name_geomadr, p.ngeom, mujoco.mjtObj.mjOBJ_GEOM + ) + self.site_names, self._site_name2id, self._site_id2name = self._extract_mj_names( + p.name_siteadr, p.nsite, mujoco.mjtObj.mjOBJ_SITE + ) + self.light_names, self._light_name2id, self._light_id2name = self._extract_mj_names( + p.name_lightadr, p.nlight, mujoco.mjtObj.mjOBJ_LIGHT + ) + self.camera_names, self._camera_name2id, self._camera_id2name = self._extract_mj_names( + p.name_camadr, p.ncam, mujoco.mjtObj.mjOBJ_CAMERA + ) + self.actuator_names, self._actuator_name2id, self._actuator_id2name = self._extract_mj_names( + p.name_actuatoradr, p.nu, mujoco.mjtObj.mjOBJ_ACTUATOR + ) + self.sensor_names, self._sensor_name2id, self._sensor_id2name = self._extract_mj_names( + p.name_sensoradr, p.nsensor, mujoco.mjtObj.mjOBJ_SENSOR + ) + self.tendon_names, self._tendon_name2id, self._tendon_id2name = self._extract_mj_names( + p.name_tendonadr, p.ntendon, mujoco.mjtObj.mjOBJ_TENDON + ) + self.mesh_names, self._mesh_name2id, self._mesh_id2name = self._extract_mj_names( + p.name_meshadr, p.nmesh, mujoco.mjtObj.mjOBJ_MESH + ) + + def body_id2name(self, id): + """Get body name from mujoco body id.""" + if id not in self._body_id2name: + raise ValueError("No body with id %d exists." % id) + return self._body_id2name[id] + + def body_name2id(self, name): + """Get body id from mujoco body name.""" + if name not in self._body_name2id: + raise ValueError('No "body" with name %s exists. Available "body" names = %s.' % (name, self.body_names)) + return self._body_name2id[name] + + def joint_id2name(self, id): + """Get joint name from mujoco joint id.""" + if id not in self._joint_id2name: + raise ValueError("No joint with id %d exists." % id) + return self._joint_id2name[id] + + def joint_name2id(self, name): + """Get joint id from joint name.""" + if name not in self._joint_name2id: + raise ValueError('No "joint" with name %s exists. Available "joint" names = %s.' % (name, self.joint_names)) + return self._joint_name2id[name] + + def geom_id2name(self, id): + """Get geom name from geom id.""" + if id not in self._geom_id2name: + raise ValueError("No geom with id %d exists." % id) + return self._geom_id2name[id] + + def geom_name2id(self, name): + """Get geom id from geom name.""" + if name not in self._geom_name2id: + raise ValueError('No "geom" with name %s exists. Available "geom" names = %s.' % (name, self.geom_names)) + return self._geom_name2id[name] + + def site_id2name(self, id): + """Get site name from site id.""" + if id not in self._site_id2name: + raise ValueError("No site with id %d exists." % id) + return self._site_id2name[id] + + def site_name2id(self, name): + """Get site id from site name.""" + if name not in self._site_name2id: + raise ValueError('No "site" with name %s exists. Available "site" names = %s.' % (name, self.site_names)) + return self._site_name2id[name] + + def light_id2name(self, id): + """Get light name from light id.""" + if id not in self._light_id2name: + raise ValueError("No light with id %d exists." % id) + return self._light_id2name[id] + + def light_name2id(self, name): + """Get light id from light name.""" + if name not in self._light_name2id: + raise ValueError('No "light" with name %s exists. Available "light" names = %s.' % (name, self.light_names)) + return self._light_name2id[name] + + def camera_id2name(self, id): + """Get camera name from camera id.""" + if id == -1: + return "free" + if id not in self._camera_id2name: + raise ValueError("No camera with id %d exists." % id) + return self._camera_id2name[id] + + def camera_name2id(self, name): + """Get camera id from camera name.""" + if name == "free": + return -1 + if name not in self._camera_name2id: + raise ValueError( + 'No "camera" with name %s exists. Available "camera" names = %s.' % (name, self.camera_names) + ) + return self._camera_name2id[name] + + def actuator_id2name(self, id): + """Get actuator name from actuator id.""" + if id not in self._actuator_id2name: + raise ValueError("No actuator with id %d exists." % id) + return self._actuator_id2name[id] + + def actuator_name2id(self, name): + """Get actuator id from actuator name.""" + if name not in self._actuator_name2id: + raise ValueError( + 'No "actuator" with name %s exists. Available "actuator" names = %s.' % (name, self.actuator_names) + ) + return self._actuator_name2id[name] + + def sensor_id2name(self, id): + """Get sensor name from sensor id.""" + if id not in self._sensor_id2name: + raise ValueError("No sensor with id %d exists." % id) + return self._sensor_id2name[id] + + def sensor_name2id(self, name): + """Get sensor id from sensor name.""" + if name not in self._sensor_name2id: + raise ValueError( + 'No "sensor" with name %s exists. Available "sensor" names = %s.' % (name, self.sensor_names) + ) + return self._sensor_name2id[name] + + def tendon_id2name(self, id): + """Get tendon name from tendon id.""" + if id not in self._tendon_id2name: + raise ValueError("No tendon with id %d exists." % id) + return self._tendon_id2name[id] + + def tendon_name2id(self, name): + """Get tendon id from tendon name.""" + if name not in self._tendon_name2id: + raise ValueError( + 'No "tendon" with name %s exists. Available "tendon" names = %s.' % (name, self.tendon_names) + ) + return self._tendon_name2id[name] + + def mesh_id2name(self, id): + """Get mesh name from mesh id.""" + if id not in self._mesh_id2name: + raise ValueError("No mesh with id %d exists." % id) + return self._mesh_id2name[id] + + def mesh_name2id(self, name): + """Get mesh id from mesh name.""" + if name not in self._mesh_name2id: + raise ValueError('No "mesh" with name %s exists. Available "mesh" names = %s.' % (name, self.mesh_names)) + return self._mesh_name2id[name] + + # def userdata_id2name(self, id): + # if id not in self._userdata_id2name: + # raise ValueError("No userdata with id %d exists." % id) + # return self._userdata_id2name[id] + + # def userdata_name2id(self, name): + # if name not in self._userdata_name2id: + # raise ValueError("No \"userdata\" with name %s exists. Available \"userdata\" names = %s." % (name, self.userdata_names)) + # return self._userdata_name2id[name] + + def get_xml(self): + with TemporaryDirectory() as td: + filename = os.path.join(td, "model.xml") + ret = mujoco.mj_saveLastXML(filename.encode(), self._model) + return open(filename).read() + + def get_joint_qpos_addr(self, name): + """ + See https://github.com/openai/mujoco-py/blob/ab86d331c9a77ae412079c6e58b8771fe63747fc/mujoco_py/generated/wrappers.pxi#L1178 + + Returns the qpos address for given joint. + Returns: + - address (int, tuple): returns int address if 1-dim joint, otherwise + returns the a (start, end) tuple for pos[start:end] access. + """ + joint_id = self.joint_name2id(name) + joint_type = self.jnt_type[joint_id] + joint_addr = self.jnt_qposadr[joint_id] + if joint_type == mujoco.mjtJoint.mjJNT_FREE: + ndim = 7 + elif joint_type == mujoco.mjtJoint.mjJNT_BALL: + ndim = 4 + else: + assert joint_type in (mujoco.mjtJoint.mjJNT_HINGE, mujoco.mjtJoint.mjJNT_SLIDE) + ndim = 1 + + if ndim == 1: + return joint_addr + else: + return (joint_addr, joint_addr + ndim) + + def get_joint_qvel_addr(self, name): + """ + See https://github.com/openai/mujoco-py/blob/ab86d331c9a77ae412079c6e58b8771fe63747fc/mujoco_py/generated/wrappers.pxi#L1202 + + Returns the qvel address for given joint. + Returns: + - address (int, tuple): returns int address if 1-dim joint, otherwise + returns the a (start, end) tuple for vel[start:end] access. + """ + joint_id = self.joint_name2id(name) + joint_type = self.jnt_type[joint_id] + joint_addr = self.jnt_dofadr[joint_id] + if joint_type == mujoco.mjtJoint.mjJNT_FREE: + ndim = 6 + elif joint_type == mujoco.mjtJoint.mjJNT_BALL: + ndim = 3 + else: + assert joint_type in (mujoco.mjtJoint.mjJNT_HINGE, mujoco.mjtJoint.mjJNT_SLIDE) + ndim = 1 + + if ndim == 1: + return joint_addr + else: + return (joint_addr, joint_addr + ndim) + + +class _MjDataMeta(type): + """ + Metaclass which allows MjData below to delegate to mujoco.MjData. + + Taken from dm_control. + """ + + def __new__(cls, name, bases, dct): + for attr in dir(mujoco.MjData): + if not attr.startswith("_"): + if attr not in dct: + # pylint: disable=protected-access + fget = lambda self, attr=attr: getattr(self._data, attr) + fset = lambda self, value, attr=attr: setattr(self._data, attr, value) + # pylint: enable=protected-access + dct[attr] = property(fget, fset) + return super().__new__(cls, name, bases, dct) + + +class MjData(metaclass=_MjDataMeta): + """Wrapper class for a MuJoCo 'mjData' instance. + MjData contains all of the dynamic variables and intermediate results produced + by the simulation. These are expected to change on each simulation timestep. + The properties without docstrings are defined in mujoco source code from https://github.com/deepmind/mujoco/blob/062cb53a4a14b2a7a900453613a7ce498728f9d8/include/mujoco/mjdata.h#L126. + """ + + def __init__(self, model): + """Construct a new MjData instance. + Args: + model: An MjModel instance. + """ + self._model = model + self._data = mujoco.MjData(model._model) + + @property + def model(self): + """The parent MjModel for this MjData instance.""" + return self._model + + def __del__(self): + # free mujoco data + del self._data + + """ + Some methods supported by sim.data in mujoco-py. + Copied from https://github.com/openai/mujoco-py/blob/ab86d331c9a77ae412079c6e58b8771fe63747fc/mujoco_py/generated/wrappers.pxi#L2611 + """ + + @property + def body_xpos(self): + """ + Note: mujoco-py used to support sim.data.body_xpos but DM mujoco bindings requires sim.data.xpos, + so we explicitly expose this as a property + """ + return self._data.xpos + + @property + def body_xquat(self): + """ + Note: mujoco-py used to support sim.data.body_xquat but DM mujoco bindings requires sim.data.xquat, + so we explicitly expose this as a property + """ + return self._data.xquat + + @property + def body_xmat(self): + """ + Note: mujoco-py used to support sim.data.body_xmat but DM mujoco bindings requires sim.data.xmax, + so we explicitly expose this as a property + """ + return self._data.xmat + + def get_body_xpos(self, name): + """ + Query cartesian position of a mujoco body using a name string. + + Args: + name (str): The name of a mujoco body + Returns: + xpos (np.ndarray): The xpos value of the mujoco body + """ + bid = self.model.body_name2id(name) + return self.xpos[bid] + + def get_body_xquat(self, name): + """ + Query the rotation of a mujoco body in quaternion (in wxyz convention) using a name string. + + Args: + name (str): The name of a mujoco body + Returns: + xquat (np.ndarray): The xquat value of the mujoco body + """ + bid = self.model.body_name2id(name) + return self.xquat[bid] + + def get_body_xmat(self, name): + """ + Query the rotation of a mujoco body in a rotation matrix using a name string. + + Args: + name (str): The name of a mujoco body + Returns: + xmat (np.ndarray): The xmat value of the mujoco body + """ + bid = self.model.body_name2id(name) + return self.xmat[bid].reshape((3, 3)) + + def get_body_jacp(self, name): + """ + Query the position jacobian of a mujoco body using a name string. + + Args: + name (str): The name of a mujoco body + Returns: + jacp (np.ndarray): The jacp value of the mujoco body + """ + bid = self.model.body_name2id(name) + jacp = np.zeros((3, self.model.nv)) + mujoco.mj_jacBody(self.model._model, self._data, jacp, None, bid) + return jacp + + def get_body_jacr(self, name): + """ + Query the rotation jacobian of a mujoco body using a name string. + + Args: + name (str): The name of a mujoco body + Returns: + jacr (np.ndarray): The jacr value of the mujoco body + """ + bid = self.model.body_name2id(name) + jacr = np.zeros((3, self.model.nv)) + mujoco.mj_jacBody(self.model._model, self._data, None, jacr, bid) + return jacr + + def get_body_xvelp(self, name): + """ + Query the translational velocity of a mujoco body using a name string. + + Args: + name (str): The name of a mujoco body + Returns: + xvelp (np.ndarray): The translational velocity of the mujoco body. + """ + jacp = self.get_body_jacp(name) + xvelp = np.dot(jacp, self.qvel) + return xvelp + + def get_body_xvelr(self, name): + """ + Query the rotational velocity of a mujoco body using a name string. + + Args: + name (str): The name of a mujoco body + Returns: + xvelr (np.ndarray): The rotational velocity of the mujoco body. + """ + jacr = self.get_body_jacr(name) + xvelr = np.dot(jacr, self.qvel) + return xvelr + + def get_geom_xpos(self, name): + """ + Query the cartesian position of a mujoco geom using a name string. + + Args: + name (str): The name of a mujoco geom + Returns: + geom_xpos (np.ndarray): The cartesian position of the mujoco body. + """ + gid = self.model.geom_name2id(name) + return self.geom_xpos[gid] + + def get_geom_xmat(self, name): + """ + Query the rotation of a mujoco geom in a rotation matrix using a name string. + + Args: + name (str): The name of a mujoco geom + Returns: + geom_xmat (np.ndarray): The 3x3 rotation matrix of the mujoco geom. + """ + gid = self.model.geom_name2id(name) + return self.geom_xmat[gid].reshape((3, 3)) + + def get_geom_jacp(self, name): + """ + Query the position jacobian of a mujoco geom using a name string. + + Args: + name (str): The name of a mujoco geom + Returns: + jacp (np.ndarray): The jacp value of the mujoco geom + """ + gid = self.model.geom_name2id(name) + jacp = np.zeros((3, self.model.nv)) + mujoco.mj_jacGeom(self.model._model, self._data, jacp, None, gid) + return jacp + + def get_geom_jacr(self, name): + """ + Query the rotation jacobian of a mujoco geom using a name string. + + Args: + name (str): The name of a mujoco geom + Returns: + jacr (np.ndarray): The jacr value of the mujoco geom + """ + gid = self.model.geom_name2id(name) + jacr = np.zeros((3, self.model.nv)) + mujoco.mj_jacGeom(self.model._model, self._data, None, jacr, gid) + return jacr + + def get_geom_xvelp(self, name): + """ + Query the translational velocity of a mujoco geom using a name string. + + Args: + name (str): The name of a mujoco geom + Returns: + xvelp (np.ndarray): The translational velocity of the mujoco geom + """ + jacp = self.get_geom_jacp(name) + xvelp = np.dot(jacp, self.qvel) + return xvelp + + def get_geom_xvelr(self, name): + """ + Query the rotational velocity of a mujoco geom using a name string. + + Args: + name (str): The name of a mujoco geom + Returns: + xvelr (np.ndarray): The rotational velocity of the mujoco geom + """ + jacr = self.get_geom_jacr(name) + xvelr = np.dot(jacr, self.qvel) + return xvelr + + def get_site_xpos(self, name): + """ + Query the cartesian position of a mujoco site using a name string. + + Args: + name (str): The name of a mujoco site + Returns: + site_xpos (np.ndarray): The carteisan position of the mujoco site + """ + sid = self.model.site_name2id(name) + return self.site_xpos[sid] + + def get_site_xmat(self, name): + """ + Query the rotation of a mujoco site in a rotation matrix using a name string. + + Args: + name (str): The name of a mujoco site + Returns: + site_xmat (np.ndarray): The 3x3 rotation matrix of the mujoco site. + """ + sid = self.model.site_name2id(name) + return self.site_xmat[sid].reshape((3, 3)) + + def get_site_jacp(self, name): + """ + Query the position jacobian of a mujoco site using a name string. + + Args: + name (str): The name of a mujoco site + Returns: + jacp (np.ndarray): The jacp value of the mujoco site + """ + sid = self.model.site_name2id(name) + jacp = np.zeros((3, self.model.nv)) + mujoco.mj_jacSite(self.model._model, self._data, jacp, None, sid) + return jacp + + def get_site_jacr(self, name): + """ + Query the rotation jacobian of a mujoco site using a name string. + + Args: + name (str): The name of a mujoco site + Returns: + jacr (np.ndarray): The jacr value of the mujoco site + """ + sid = self.model.site_name2id(name) + jacr = np.zeros((3, self.model.nv)) + mujoco.mj_jacSite(self.model._model, self._data, None, jacr, sid) + return jacr + + def get_site_xvelp(self, name): + """ + Query the translational velocity of a mujoco site using a name string. + + Args: + name (str): The name of a mujoco site + Returns: + xvelp (np.ndarray): The translational velocity of the mujoco site + """ + jacp = self.get_site_jacp(name) + xvelp = np.dot(jacp, self.qvel) + return xvelp + + def get_site_xvelr(self, name): + """ + Query the rotational velocity of a mujoco site using a name string. + + Args: + name (str): The name of a mujoco site + Returns: + xvelr (np.ndarray): The rotational velocity of the mujoco site + """ + jacr = self.get_site_jacr(name) + xvelr = np.dot(jacr, self.qvel) + return xvelr + + def get_camera_xpos(self, name): + """ + Get the cartesian position of a camera using name + + Args: + name (str): The name of a camera + Returns: + cam_xpos (np.ndarray): The cartesian position of a camera + """ + cid = self.model.camera_name2id(name) + return self.cam_xpos[cid] + + def get_camera_xmat(self, name): + """ + Get the rotation of a camera in a rotation matrix using name + + Args: + name (str): The name of a camera + Returns: + cam_xmat (np.ndarray): The 3x3 rotation matrix of a camera + """ + cid = self.model.camera_name2id(name) + return self.cam_xmat[cid].reshape((3, 3)) + + def get_light_xpos(self, name): + """ + Get cartesian position of a light source + + Args: + name (str): The name of a lighting source + Returns: + light_xpos (np.ndarray): The cartesian position of the light source + """ + lid = self.model.light_name2id(name) + return self.light_xpos[lid] + + def get_light_xdir(self, name): + """ + Get the direction of a light source using name + + Args: + name (str): The name of a light + Returns: + light_xdir (np.ndarray): The direction vector of the lightsource + """ + lid = self.model.light_name2id(name) + return self.light_xdir[lid] + + def get_sensor(self, name): + """ + Get the data of a sensor using name + + Args: + name (str): The name of a sensor + Returns: + sensordata (np.ndarray): The sensor data vector + """ + sid = self.model.sensor_name2id(name) + return self.sensordata[sid] + + def get_mocap_pos(self, name): + """ + Get the position of a mocap body using name. + + Args: + name (str): The name of a joint + Returns: + mocap_pos (np.ndarray): The current position of a mocap body. + """ + body_id = self.model.body_name2id(name) + mocap_id = self.model.body_mocapid[body_id] + return self.mocap_pos[mocap_id] + + def set_mocap_pos(self, name, value): + """ + Set the quaternion of a mocap body using name. + + Args: + name (str): The name of a joint + value (float): The desired joint position of a mocap body. + """ + body_id = self.model.body_name2id(name) + mocap_id = self.model.body_mocapid[body_id] + self.mocap_pos[mocap_id] = value + + def get_mocap_quat(self, name): + """ + Get the quaternion of a mocap body using name. + + Args: + name (str): The name of a joint + Returns: + mocap_quat (np.ndarray): The current quaternion of a mocap body. + """ + body_id = self.model.body_name2id(name) + mocap_id = self.model.body_mocapid[body_id] + return self.mocap_quat[mocap_id] + + def set_mocap_quat(self, name, value): + """ + Set the quaternion of a mocap body using name. + + Args: + name (str): The name of a joint + value (float): The desired joint quaternion of a mocap body. + """ + body_id = self.model.body_name2id(name) + mocap_id = self.model.body_mocapid[body_id] + self.mocap_quat[mocap_id] = value + + def get_joint_qpos(self, name): + """ + Get the position of a joint using name. + + Args: + name (str): The name of a joint + + Returns: + qpos (np.ndarray): The current position of a joint. + """ + addr = self.model.get_joint_qpos_addr(name) + if isinstance(addr, (int, np.int32, np.int64)): + return self.qpos[addr] + else: + start_i, end_i = addr + return self.qpos[start_i:end_i] + + def set_joint_qpos(self, name, value): + """ + Set the position of a joint using name. + + Args: + name (str): The name of a joint + value (float): The desired joint velocity of a joint. + """ + addr = self.model.get_joint_qpos_addr(name) + if isinstance(addr, (int, np.int32, np.int64)): + self.qpos[addr] = value + else: + start_i, end_i = addr + value = np.array(value) + assert value.shape == (end_i - start_i,), "Value has incorrect shape %s: %s" % (name, value) + self.qpos[start_i:end_i] = value + + def get_joint_qvel(self, name): + """ + Get the velocity of a joint using name. + + Args: + name (str): The name of a joint + + Returns: + qvel (np.ndarray): The current velocity of a joint. + """ + addr = self.model.get_joint_qvel_addr(name) + if isinstance(addr, (int, np.int32, np.int64)): + return self.qvel[addr] + else: + start_i, end_i = addr + return self.qvel[start_i:end_i] + + def set_joint_qvel(self, name, value): + """ + Set the velocities of a joint using name. + + Args: + name (str): The name of a joint + value (float): The desired joint velocity of a joint. + """ + addr = self.model.get_joint_qvel_addr(name) + if isinstance(addr, (int, np.int32, np.int64)): + self.qvel[addr] = value + else: + start_i, end_i = addr + value = np.array(value) + assert value.shape == (end_i - start_i,), "Value has incorrect shape %s: %s" % (name, value) + self.qvel[start_i:end_i] = value + + +class MjSim: + """ + Meant to somewhat replicate functionality in mujoco-py's MjSim object + (see https://github.com/openai/mujoco-py/blob/master/mujoco_py/mjsim.pyx). + """ + + def __init__(self, model): + """ + Args: + model: should be an MjModel instance created via a factory function + such as mujoco.MjModel.from_xml_string(xml) + """ + self.model = MjModel(model) + self.data = MjData(self.model) + + # offscreen render context object + self._render_context_offscreen = None + + @classmethod + def from_xml_string(cls, xml): + model = mujoco.MjModel.from_xml_string(xml) + return cls(model) + + @classmethod + def from_xml_file(cls, xml_file): + f = open(xml_file, "r") + xml = f.read() + f.close() + return cls.from_xml_string(xml) + + def reset(self): + """Reset simulation.""" + mujoco.mj_resetData(self.model._model, self.data._data) + + def forward(self): + """Forward call to synchronize derived quantities.""" + mujoco.mj_forward(self.model._model, self.data._data) + + def step(self, with_udd=True): + """Step simulation.""" + mujoco.mj_step(self.model._model, self.data._data) + + def step1(self): + """Step1 (before actions are set).""" + mujoco.mj_step1(self.model._model, self.data._data) + + def step2(self): + """Step2 (after actions are set).""" + mujoco.mj_step2(self.model._model, self.data._data) + + def render( + self, + width=None, + height=None, + *, + camera_name=None, + depth=False, + mode="offscreen", + device_id=-1, + segmentation=False, + ): + """ + Renders view from a camera and returns image as an `numpy.ndarray`. + Args: + - width (int): desired image width. + - height (int): desired image height. + - camera_name (str): name of camera in model. If None, the free + camera will be used. + - depth (bool): if True, also return depth buffer + - device (int): device to use for rendering (only for GPU-backed + rendering). + Returns: + - rgb (uint8 array): image buffer from camera + - depth (float array): depth buffer from camera (only returned + if depth=True) + """ + if camera_name is None: + camera_id = None + else: + camera_id = self.model.camera_name2id(camera_name) + + assert mode == "offscreen", "only offscreen supported for now" + assert self._render_context_offscreen is not None + with _MjSim_render_lock: + self._render_context_offscreen.render( + width=width, height=height, camera_id=camera_id, segmentation=segmentation + ) + return self._render_context_offscreen.read_pixels(width, height, depth=depth, segmentation=segmentation) + + def add_render_context(self, render_context): + assert render_context.offscreen + if self._render_context_offscreen is not None: + # free context + del self._render_context_offscreen + self._render_context_offscreen = render_context + + def get_state(self): + """Return MjSimState instance for current state.""" + return MjSimState( + time=self.data.time, + qpos=np.copy(self.data.qpos), + qvel=np.copy(self.data.qvel), + ) + + def set_state(self, value): + """ + Set internal state from MjSimState instance. Should + call @forward afterwards to synchronize derived quantities. + """ + self.data.time = value.time + self.data.qpos[:] = np.copy(value.qpos) + self.data.qvel[:] = np.copy(value.qvel) + + def set_state_from_flattened(self, value): + """ + Set internal mujoco state using flat mjstate array. Should + call @forward afterwards to synchronize derived quantities. + + See https://github.com/openai/mujoco-py/blob/4830435a169c1f3e3b5f9b58a7c3d9c39bdf4acb/mujoco_py/mjsimstate.pyx#L54 + """ + state = MjSimState.from_flattened(value, self) + + # do this instead of @set_state to avoid extra copy of qpos and qvel + self.data.time = state.time + self.data.qpos[:] = state.qpos + self.data.qvel[:] = state.qvel + + def free(self): + # clean up here to prevent memory leaks + del self._render_context_offscreen + del self.data + del self.model + del self + gc.collect() diff --git a/third_party/robosuite/robosuite/utils/buffers.py b/third_party/robosuite/robosuite/utils/buffers.py new file mode 100644 index 0000000000000000000000000000000000000000..b2a1bc20f86a79870d885d76a12739f0263c03fb --- /dev/null +++ b/third_party/robosuite/robosuite/utils/buffers.py @@ -0,0 +1,173 @@ +""" +Collection of Buffer objects with general functionality +""" + + +import numpy as np + + +class Buffer(object): + """ + Abstract class for different kinds of data buffers. Minimum API should have a "push" and "clear" method + """ + + def push(self, value): + """ + Pushes a new @value to the buffer + + Args: + value: Value to push to the buffer + """ + raise NotImplementedError + + def clear(self): + raise NotImplementedError + + +class RingBuffer(Buffer): + """ + Simple RingBuffer object to hold values to average (useful for, e.g.: filtering D component in PID control) + + Note that the buffer object is a 2D numpy array, where each row corresponds to + individual entries into the buffer + + Args: + dim (int): Size of entries being added. This is, e.g.: the size of a state vector that is to be stored + length (int): Size of the ring buffer + """ + + def __init__(self, dim, length): + # Store input args + self.dim = dim + self.length = length + + # Variable so that initial average values are accurate + self._size = 0 + + # Save pointer to end of buffer + self.ptr = self.length - 1 + + # Construct ring buffer + self.buf = np.zeros((length, dim)) + + def push(self, value): + """ + Pushes a new value into the buffer + + Args: + value (int or float or array): Value(s) to push into the array (taken as a single new element) + """ + # Increment pointer, then add value (also increment size if necessary) + self.ptr = (self.ptr + 1) % self.length + self.buf[self.ptr] = np.array(value) + if self._size < self.length: + self._size += 1 + + def clear(self): + """ + Clears buffer and reset pointer + """ + self.buf = np.zeros((self.length, self.dim)) + self.ptr = self.length - 1 + self._size = 0 + + @property + def current(self): + """ + Gets the most recent value pushed to the buffer + + Returns: + float or np.array: Most recent value in buffer + """ + return self.buf[self.ptr] + + @property + def average(self): + """ + Gets the average of components in buffer + + Returns: + float or np.array: Averaged value of all elements in buffer + """ + return np.mean(self.buf[: self._size], axis=0) + + +class DeltaBuffer(Buffer): + """ + Simple 2-length buffer object to streamline grabbing delta values between "current" and "last" values + + Constructs delta object. + + Args: + dim (int): Size of numerical arrays being inputted + init_value (None or Iterable): Initial value to fill "last" value with initially. + If None (default), last array will be filled with zeros + """ + + def __init__(self, dim, init_value=None): + # Setup delta object + self.dim = dim + self.last = np.zeros(self.dim) if init_value is None else np.array(init_value) + self.current = np.zeros(self.dim) + + def push(self, value): + """ + Pushes a new value into the buffer; current becomes last and @value becomes current + + Args: + value (int or float or array): Value(s) to push into the array (taken as a single new element) + """ + self.last = self.current + self.current = np.array(value) + + def clear(self): + """ + Clears last and current value + """ + self.last, self.current = np.zeros(self.dim), np.zeros(self.dim) + + @property + def delta(self, abs_value=False): + """ + Returns the delta between last value and current value. If abs_value is set to True, then returns + the absolute value between the values + + Args: + abs_value (bool): Whether to return absolute value or not + + Returns: + float or np.array: difference between current and last value + """ + return self.current - self.last if not abs_value else np.abs(self.current - self.last) + + @property + def average(self): + """ + Returns the average between the current and last value + + Returns: + float or np.array: Averaged value of all elements in buffer + """ + return (self.current + self.last) / 2.0 + + +class DelayBuffer(RingBuffer): + """ + Modified RingBuffer that returns delayed values when polled + """ + + def get_delayed_value(self, delay): + """ + Returns value @delay increments behind most recent value. + + Args: + delay (int): How many steps backwards from most recent value to grab value. Note that this should not be + greater than the buffer's length + + Returns: + np.array: delayed value + """ + # First make sure that the delay is valid + assert delay < self.length, "Requested delay must be less than buffer's length!" + # Grab delayed value + return self.buf[(self.ptr - delay) % self.length] diff --git a/third_party/robosuite/robosuite/utils/camera_utils.py b/third_party/robosuite/robosuite/utils/camera_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..733e65c57c6597ae7b065674ffe23ffad7d93d74 --- /dev/null +++ b/third_party/robosuite/robosuite/utils/camera_utils.py @@ -0,0 +1,628 @@ +""" +This module includes: + +- Utility classes for modifying sim cameras + +- Utility functions for performing common camera operations such as retrieving +camera matrices and transforming from world to camera frame or vice-versa. +""" +import json +import xml.etree.ElementTree as ET + +import h5py +import numpy as np + +import robosuite +import robosuite.utils.transform_utils as T +from robosuite.wrappers import DomainRandomizationWrapper, VisualizationWrapper + + +def get_camera_intrinsic_matrix(sim, camera_name, camera_height, camera_width): + """ + Obtains camera intrinsic matrix. + + Args: + sim (MjSim): simulator instance + camera_name (str): name of camera + camera_height (int): height of camera images in pixels + camera_width (int): width of camera images in pixels + Return: + K (np.array): 3x3 camera matrix + """ + cam_id = sim.model.camera_name2id(camera_name) + fovy = sim.model.cam_fovy[cam_id] + f = 0.5 * camera_height / np.tan(fovy * np.pi / 360) + K = np.array([[f, 0, camera_width / 2], [0, f, camera_height / 2], [0, 0, 1]]) + return K + + +def get_camera_extrinsic_matrix(sim, camera_name): + """ + Returns a 4x4 homogenous matrix corresponding to the camera pose in the + world frame. MuJoCo has a weird convention for how it sets up the + camera body axis, so we also apply a correction so that the x and y + axis are along the camera view and the z axis points along the + viewpoint. + Normal camera convention: https://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html + + Args: + sim (MjSim): simulator instance + camera_name (str): name of camera + Return: + R (np.array): 4x4 camera extrinsic matrix + """ + cam_id = sim.model.camera_name2id(camera_name) + camera_pos = sim.data.cam_xpos[cam_id] + camera_rot = sim.data.cam_xmat[cam_id].reshape(3, 3) + R = T.make_pose(camera_pos, camera_rot) + + # IMPORTANT! This is a correction so that the camera axis is set up along the viewpoint correctly. + camera_axis_correction = np.array( + [[1.0, 0.0, 0.0, 0.0], [0.0, -1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] + ) + R = R @ camera_axis_correction + return R + + +def get_camera_transform_matrix(sim, camera_name, camera_height, camera_width): + """ + Camera transform matrix to project from world coordinates to pixel coordinates. + + Args: + sim (MjSim): simulator instance + camera_name (str): name of camera + camera_height (int): height of camera images in pixels + camera_width (int): width of camera images in pixels + Return: + K (np.array): 4x4 camera matrix to project from world coordinates to pixel coordinates + """ + R = get_camera_extrinsic_matrix(sim=sim, camera_name=camera_name) + K = get_camera_intrinsic_matrix( + sim=sim, camera_name=camera_name, camera_height=camera_height, camera_width=camera_width + ) + K_exp = np.eye(4) + K_exp[:3, :3] = K + + # Takes a point in world, transforms to camera frame, and then projects onto image plane. + return K_exp @ T.pose_inv(R) + + +def get_camera_segmentation(sim, camera_name, camera_height, camera_width): + """ + Obtains camera segmentation matrix. + + Args: + sim (MjSim): simulator instance + camera_name (str): name of camera + camera_height (int): height of camera images in pixels + camera_width (int): width of camera images in pixels + Return: + im (np.array): 2-channel segmented image where the first contains the + geom types and the second contains the geom IDs + """ + return sim.render(camera_name=camera_name, height=camera_height, width=camera_width, segmentation=True)[::-1] + + +def get_real_depth_map(sim, depth_map): + """ + By default, MuJoCo will return a depth map that is normalized in [0, 1]. This + helper function converts the map so that the entries correspond to actual distances. + + (see https://github.com/deepmind/dm_control/blob/master/dm_control/mujoco/engine.py#L742) + + Args: + sim (MjSim): simulator instance + depth_map (np.array): depth map with values normalized in [0, 1] (default depth map + returned by MuJoCo) + Return: + depth_map (np.array): depth map that corresponds to actual distances + """ + # Make sure that depth values are normalized + assert np.all(depth_map >= 0.0) and np.all(depth_map <= 1.0) + extent = sim.model.stat.extent + far = sim.model.vis.map.zfar * extent + near = sim.model.vis.map.znear * extent + return near / (1.0 - depth_map * (1.0 - near / far)) + + +def project_points_from_world_to_camera(points, world_to_camera_transform, camera_height, camera_width): + """ + Helper function to project a batch of points in the world frame + into camera pixels using the world to camera transformation. + + Args: + points (np.array): 3D points in world frame to project onto camera pixel locations. Should + be shape [..., 3]. + world_to_camera_transform (np.array): 4x4 Tensor to go from robot coordinates to pixel + coordinates. + camera_height (int): height of the camera image + camera_width (int): width of the camera image + + Return: + pixels (np.array): projected pixel indices of shape [..., 2] + """ + assert points.shape[-1] == 3 # last dimension must be 3D + assert len(world_to_camera_transform.shape) == 2 + assert world_to_camera_transform.shape[0] == 4 and world_to_camera_transform.shape[1] == 4 + + # convert points to homogenous coordinates -> (px, py, pz, 1) + ones_pad = np.ones(points.shape[:-1] + (1,)) + points = np.concatenate((points, ones_pad), axis=-1) # shape [..., 4] + + # batch matrix multiplication of 4 x 4 matrix and 4 x 1 vectors to do robot frame to pixels transform + mat_reshape = [1] * len(points.shape[:-1]) + [4, 4] + cam_trans = world_to_camera_transform.reshape(mat_reshape) # shape [..., 4, 4] + pixels = np.matmul(cam_trans, points[..., None])[..., 0] # shape [..., 4] + + # re-scaling from homogenous coordinates to recover pixel values + # (x, y, z) -> (x / z, y / z) + pixels = pixels / pixels[..., 2:3] + pixels = pixels[..., :2].round().astype(int) # shape [..., 2] + + # swap first and second coordinates to get pixel indices that correspond to (height, width) + # and also clip pixels that are out of range of the camera image + pixels = np.concatenate( + ( + pixels[..., 1:2].clip(0, camera_height - 1), + pixels[..., 0:1].clip(0, camera_width - 1), + ), + axis=-1, + ) + + return pixels + + +def transform_from_pixels_to_world(pixels, depth_map, camera_to_world_transform): + """ + Helper function to take a batch of pixel locations and the corresponding depth image + and transform these points from the camera frame to the world frame. + + Args: + pixels (np.array): pixel coordinates of shape [..., 2] + depth_map (np.array): depth images of shape [..., H, W, 1] + camera_to_world_transform (np.array): 4x4 Tensor to go from pixel coordinates to world + coordinates. + + Return: + points (np.array): 3D points in robot frame of shape [..., 3] + """ + + # make sure leading dimensions are consistent + pixels_leading_shape = pixels.shape[:-1] + depth_map_leading_shape = depth_map.shape[:-3] + assert depth_map_leading_shape == pixels_leading_shape + + # sample from the depth map using the pixel locations with bilinear sampling + pixels = pixels.astype(float) + im_h, im_w = depth_map.shape[-2:] + depth_map_reshaped = depth_map.reshape(-1, im_h, im_w, 1) + z = bilinear_interpolate(im=depth_map_reshaped, x=pixels[..., 1:2], y=pixels[..., 0:1]) + z = z.reshape(*depth_map_leading_shape, 1) # shape [..., 1] + + # form 4D homogenous camera vector to transform - [x * z, y * z, z, 1] + # (note that we need to swap the first 2 dimensions of pixels to go from pixel indices + # to camera coordinates) + cam_pts = [pixels[..., 1:2] * z, pixels[..., 0:1] * z, z, np.ones_like(z)] + cam_pts = np.concatenate(cam_pts, axis=-1) # shape [..., 4] + + # batch matrix multiplication of 4 x 4 matrix and 4 x 1 vectors to do camera to robot frame transform + mat_reshape = [1] * len(cam_pts.shape[:-1]) + [4, 4] + cam_trans = camera_to_world_transform.reshape(mat_reshape) # shape [..., 4, 4] + points = np.matmul(cam_trans, cam_pts[..., None])[..., 0] # shape [..., 4] + return points[..., :3] + + +def bilinear_interpolate(im, x, y): + """ + Bilinear sampling for pixel coordinates x and y from source image im. + Taken from https://stackoverflow.com/questions/12729228/simple-efficient-bilinear-interpolation-of-images-in-numpy-and-python + """ + x = np.asarray(x) + y = np.asarray(y) + + x0 = np.floor(x).astype(int) + x1 = x0 + 1 + y0 = np.floor(y).astype(int) + y1 = y0 + 1 + + x0 = np.clip(x0, 0, im.shape[1] - 1) + x1 = np.clip(x1, 0, im.shape[1] - 1) + y0 = np.clip(y0, 0, im.shape[0] - 1) + y1 = np.clip(y1, 0, im.shape[0] - 1) + + Ia = im[y0, x0] + Ib = im[y1, x0] + Ic = im[y0, x1] + Id = im[y1, x1] + + wa = (x1 - x) * (y1 - y) + wb = (x1 - x) * (y - y0) + wc = (x - x0) * (y1 - y) + wd = (x - x0) * (y - y0) + + return wa * Ia + wb * Ib + wc * Ic + wd * Id + + +class CameraMover: + """ + A class for manipulating a camera. + + WARNING: This class will initially RE-INITIALIZE the environment. + + Args: + env (MujocoEnv): Mujoco environment to modify camera + camera (str): Which camera to mobilize during playback, e.g.: frontview, agentview, etc. + init_camera_pos (None or 3-array): If specified, should be the (x,y,z) global cartesian pos to + initialize camera to + init_camera_quat (None or 4-array): If specified, should be the (x,y,z,w) global quaternion orientation to + initialize camera to + """ + + def __init__( + self, + env, + camera="frontview", + init_camera_pos=None, + init_camera_quat=None, + ): + # Store relevant values and initialize other values + self.env = env + self.camera = camera + self.mover_body_name = f"{self.camera}_cameramover" + + # Get state + state = self.env.sim.get_state().flatten() + + # Grab environment xml + xml = env.sim.model.get_xml() + + # Modify xml to add mocap to move camera around + xml = self.modify_xml_for_camera_movement(xml=xml, camera_name=self.camera) + + # Reset the environment and restore the state + self.env.reset_from_xml_string(xml) + self.env.sim.reset() + self.env.sim.set_state_from_flattened(state) + self.env.sim.forward() + + # Set initial camera pose + self.set_camera_pose(pos=init_camera_pos, quat=init_camera_quat) + + def set_camera_pose(self, pos=None, quat=None): + """ + Sets the camera pose, which optionally includes position and / or quaternion + + Args: + pos (None or 3-array): If specified, should be the (x,y,z) global cartesian pos to set camera to + quat (None or 4-array): If specified, should be the (x,y,z,w) global quaternion orientation to set camera to + """ + if pos is not None: + self.env.sim.data.set_mocap_pos(self.mover_body_name, pos) + if quat is not None: + self.env.sim.data.set_mocap_quat(self.mover_body_name, T.convert_quat(quat, to="wxyz")) + + # Make sure changes propagate in sim + self.env.sim.forward() + + def get_camera_pose(self): + """ + Grab the current camera pose, which optionally includes position and / or quaternion + + Returns: + 2-tuple: + - 3-array: (x,y,z) camera global cartesian pos + - 4-array: (x,y,z,w) camera global quaternion orientation + """ + # Grab values from sim + pos = self.env.sim.data.get_mocap_pos(self.mover_body_name) + quat = T.convert_quat(self.env.sim.data.get_mocap_quat(self.mover_body_name), to="xyzw") + + return pos, quat + + def modify_xml_for_camera_movement(self, xml, camera_name): + """ + Cameras in mujoco are 'fixed', so they can't be moved by default. + Although it's possible to hack position movement, rotation movement + does not work. An alternative is to attach a camera to a mocap body, + and move the mocap body. + + This function modifies the camera with name @camera_name in the xml + by attaching it to a mocap body that can move around freely. In this + way, we can move the camera by moving the mocap body. + + See http://www.mujoco.org/forum/index.php?threads/move-camera.2201/ for + further details. + + Args: + xml (str): Mujoco sim XML file as a string + camera_name (str): Name of camera to tune + """ + tree = ET.fromstring(xml) + wb = tree.find("worldbody") + + # find the correct camera + camera_elem = None + cameras = wb.findall("camera") + for camera in cameras: + if camera.get("name") == camera_name: + camera_elem = camera + break + assert camera_elem is not None + + # add mocap body + mocap = ET.SubElement(wb, "body") + mocap.set("name", self.mover_body_name) + mocap.set("mocap", "true") + mocap.set("pos", camera.get("pos")) + mocap.set("quat", camera.get("quat")) + new_camera = ET.SubElement(mocap, "camera") + new_camera.set("mode", "fixed") + new_camera.set("name", camera.get("name")) + new_camera.set("pos", "0 0 0") + + # remove old camera element + wb.remove(camera_elem) + + return ET.tostring(tree, encoding="utf8").decode("utf8") + + def rotate_camera(self, point, axis, angle): + """ + Rotate the camera view about a direction (in the camera frame). + + Args: + point (None or 3-array): (x,y,z) cartesian coordinates about which to rotate camera in camera frame. If None, + assumes the point is the current location of the camera + axis (3-array): (ax,ay,az) axis about which to rotate camera in camera frame + angle (float): how much to rotate about that direction + + Returns: + 2-tuple: + pos: (x,y,z) updated camera position + quat: (x,y,z,w) updated camera quaternion orientation + """ + # current camera rotation + pos + camera_pos = np.array(self.env.sim.data.get_mocap_pos(self.mover_body_name)) + camera_rot = T.quat2mat(T.convert_quat(self.env.sim.data.get_mocap_quat(self.mover_body_name), to="xyzw")) + + # rotate by angle and direction to get new camera rotation + rad = np.pi * angle / 180.0 + R = T.rotation_matrix(rad, axis, point=point) + camera_pose = np.zeros((4, 4)) + camera_pose[:3, :3] = camera_rot + camera_pose[:3, 3] = camera_pos + camera_pose = camera_pose @ R + + # Update camera pose + pos, quat = camera_pose[:3, 3], T.mat2quat(camera_pose[:3, :3]) + self.set_camera_pose(pos=pos, quat=quat) + + return pos, quat + + def move_camera(self, direction, scale): + """ + Move the camera view along a direction (in the camera frame). + + Args: + direction (3-array): direction vector for where to move camera in camera frame + scale (float): how much to move along that direction + """ + # current camera rotation + pos + camera_pos = np.array(self.env.sim.data.get_mocap_pos(self.mover_body_name)) + camera_quat = self.env.sim.data.get_mocap_quat(self.mover_body_name) + camera_rot = T.quat2mat(T.convert_quat(camera_quat, to="xyzw")) + + # move along camera frame axis and set new position + camera_pos += scale * camera_rot.dot(direction) + self.set_camera_pose(pos=camera_pos) + + return camera_pos, camera_quat + + +class DemoPlaybackCameraMover(CameraMover): + """ + A class for playing back demonstrations and recording the resulting frames with the flexibility of a mobile camera + that can be set manually or panned automatically frame-by-frame + + Note: domain randomization is also supported for playback! + + Args: + demo (str): absolute fpath to .hdf5 demo + env_config (None or dict): (optional) values to override inferred environment information from demonstration. + (e.g.: camera h / w, depths, segmentations, etc...) + Any value not specified will be inferred from the extracted demonstration metadata + Note that there are some specific arguments that MUST be set a certain way, if any of these values + are specified with @env_config, an error will be raised + replay_from_actions (bool): If True, will replay demonstration's actions. Otherwise, replays will be hardcoded + from the demonstration states + visualize_sites (bool): If True, will visualize sites during playback. Note that this CANNOT be paired + simultaneously with camera segmentations + camera (str): Which camera to mobilize during playback, e.g.: frontview, agentview, etc. + init_camera_pos (None or 3-array): If specified, should be the (x,y,z) global cartesian pos to + initialize camera to + init_camera_quat (None or 4-array): If specified, should be the (x,y,z,w) global quaternion orientation to + initialize camera to + use_dr (bool): If True, will use domain randomization during playback + dr_args (None or dict): If specified, will set the domain randomization wrapper arguments if using dr + """ + + def __init__( + self, + demo, + env_config=None, + replay_from_actions=False, + visualize_sites=False, + camera="frontview", + init_camera_pos=None, + init_camera_quat=None, + use_dr=False, + dr_args=None, + ): + # Store relevant values and initialize other values + self.camera_id = None + self.replay_from_actions = replay_from_actions + self.states = None + self.actions = None + self.step = None + self.n_steps = None + self.current_ep = None + self.started = False + + # Load the demo + self.f = h5py.File(demo, "r") + + # Extract relevant info + env_info = json.loads(self.f["data"].attrs["env_info"]) + + # Construct default env arguments + default_args = { + "has_renderer": False, + "has_offscreen_renderer": True, + "ignore_done": True, + "use_camera_obs": True, + "reward_shaping": True, + "hard_reset": False, + "camera_names": camera, + } + + # If custom env_config is specified, make sure that there's no overlap with default args and merge with config + if env_config is not None: + for k in env_config.keys(): + assert k not in default_args, f"Key {k} cannot be specified in env_config!" + env_info.update(env_config) + + # Merge in default args + env_info.update(default_args) + + # Create env + env = robosuite.make(**env_info) + + # Optionally wrap with visualization wrapper + if visualize_sites: + env = VisualizationWrapper(env=self.env) + + # Optionally use domain randomization if specified + self.use_dr = use_dr + if self.use_dr: + default_dr_args = { + "seed": 1, + "randomize_camera": False, + "randomize_every_n_steps": 10, + } + default_dr_args.update(dr_args) + env = DomainRandomizationWrapper( + env=self.env, + **default_dr_args, + ) + + # list of all demonstrations episodes + self.demos = list(self.f["data"].keys()) + + # Run super init + super().__init__( + env=env, + camera=camera, + init_camera_pos=init_camera_pos, + init_camera_quat=init_camera_quat, + ) + + # Load episode 0 by default + self.load_episode_xml(demo_num=0) + + def load_episode_xml(self, demo_num): + """ + Loads demo episode with specified @demo_num into the simulator. + + Args: + demo_num (int): Demonstration number to load + """ + # Grab raw xml file + ep = self.demos[demo_num] + model_xml = self.f[f"data/{ep}"].attrs["model_file"] + + # Reset environment + self.env.reset() + xml = self.env.edit_model_xml(model_xml) + xml = self.modify_xml_for_camera_movement(xml, camera_name=self.camera) + self.env.reset_from_xml_string(xml) + self.env.sim.reset() + + # Update camera info + self.camera_id = self.env.sim.model.camera_name2id(self.camera) + + # Load states and actions + self.states = self.f[f"data/{ep}/states"].value + self.actions = np.array(self.f[f"data/{ep}/actions"].value) + + # Set initial state + self.env.sim.set_state_from_flattened(self.states[0]) + + # Reset step count and set current episode number + self.step = 0 + self.n_steps = len(self.actions) + self.current_ep = demo_num + + # Notify user of loaded episode + print(f"Loaded episode {demo_num}.") + + def grab_next_frame(self): + """ + Grabs the next frame in the demo sequence by stepping the simulation and returning the resulting value(s) + + Returns: + dict: Keyword-mapped np.arrays from the demonstration sequence, corresponding to all image modalities used + in the playback environment (e.g.: "image", "depth", "segmentation_instance") + """ + # Make sure the episode isn't completed yet, if so, we load the next episode + if self.step == self.n_steps: + self.load_episode_xml(demo_num=self.current_ep + 1) + + # Step the environment and grab obs + if self.replay_from_actions: + obs, _, _, _ = self.env.step(self.actions[self.step]) + else: # replay from states + self.env.sim.set_state_from_flattened(self.states[self.step + 1]) + if self.use_dr: + self.env.step_randomization() + self.env.sim.forward() + obs = self.env._get_observation() + + # Increment the step counter + self.step += 1 + + # Return all relevant frames + return {k.split(f"{self.camera}_")[-1]: obs[k] for k in obs if self.camera in k} + + def grab_episode_frames(self, demo_num, pan_point=(0, 0, 0.8), pan_axis=(0, 0, 1), pan_rate=0.01): + """ + Playback entire episode @demo_num, while optionally rotating the camera about point @pan_point and + axis @pan_axis if @pan_rate > 0 + + Args: + demo_num (int): Demonstration episode number to load for playback + pan_point (3-array): (x,y,z) cartesian coordinates about which to rotate camera in camera frame + pan_direction (3-array): (ax,ay,az) axis about which to rotate camera in camera frame + pan_rate (float): how quickly to pan camera if not 0 + + Returns: + dict: Keyword-mapped stacked np.arrays from the demonstration sequence, corresponding to all image + modalities used in the playback environment (e.g.: "image", "depth", "segmentation_instance") + + """ + # First, load env + self.load_episode_xml(demo_num=demo_num) + + # Initialize dict to return + obs = self.env._get_observation() + frames_dict = {k.split(f"{self.camera}_")[-1]: [] for k in obs if self.camera in k} + + # Continue to loop playback steps while there are still frames left in the episode + while self.step < self.n_steps: + # Take playback step and add frames + for k, frame in self.grab_next_frame().items(): + frames_dict[k].append(frame) + + # Update camera pose + self.rotate_camera(point=pan_point, axis=pan_axis, angle=pan_rate) + + # Stack all frames and return + return {k: np.stack(frames) for k, frames in frames_dict.items()} diff --git a/third_party/robosuite/robosuite/utils/control_utils.py b/third_party/robosuite/robosuite/utils/control_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..18cc0a6b30cd8011f5267cc39542c86a01867e44 --- /dev/null +++ b/third_party/robosuite/robosuite/utils/control_utils.py @@ -0,0 +1,236 @@ +import numpy as np + +import robosuite.utils.transform_utils as trans +from robosuite.utils.numba import jit_decorator + + +@jit_decorator +def nullspace_torques(mass_matrix, nullspace_matrix, initial_joint, joint_pos, joint_vel, joint_kp=10): + """ + For a robot with redundant DOF(s), a nullspace exists which is orthogonal to the remainder of the controllable + subspace of the robot's joints. Therefore, an additional secondary objective that does not impact the original + controller objective may attempt to be maintained using these nullspace torques. + + This utility function specifically calculates nullspace torques that attempt to maintain a given robot joint + positions @initial_joint with zero velocity using proportinal gain @joint_kp + + :Note: @mass_matrix, @nullspace_matrix, @joint_pos, and @joint_vel should reflect the robot's state at the current + timestep + + Args: + mass_matrix (np.array): 2d array representing the mass matrix of the robot + nullspace_matrix (np.array): 2d array representing the nullspace matrix of the robot + initial_joint (np.array): Joint configuration to be used for calculating nullspace torques + joint_pos (np.array): Current joint positions + joint_vel (np.array): Current joint velocities + joint_kp (float): Proportional control gain when calculating nullspace torques + + Returns: + np.array: nullspace torques + """ + + # kv calculated below corresponds to critical damping + joint_kv = np.sqrt(joint_kp) * 2 + + # calculate desired torques based on gains and error + pose_torques = np.dot(mass_matrix, (joint_kp * (initial_joint - joint_pos) - joint_kv * joint_vel)) + + # map desired torques to null subspace within joint torque actuator space + nullspace_torques = np.dot(nullspace_matrix.transpose(), pose_torques) + return nullspace_torques + + +@jit_decorator +def opspace_matrices(mass_matrix, J_full, J_pos, J_ori): + """ + Calculates the relevant matrices used in the operational space control algorithm + + Args: + mass_matrix (np.array): 2d array representing the mass matrix of the robot + J_full (np.array): 2d array representing the full Jacobian matrix of the robot + J_pos (np.array): 2d array representing the position components of the Jacobian matrix of the robot + J_ori (np.array): 2d array representing the orientation components of the Jacobian matrix of the robot + + Returns: + 4-tuple: + + - (np.array): full lambda matrix (as 2d array) + - (np.array): position components of lambda matrix (as 2d array) + - (np.array): orientation components of lambda matrix (as 2d array) + - (np.array): nullspace matrix (as 2d array) + """ + mass_matrix_inv = np.linalg.inv(mass_matrix) + + # J M^-1 J^T + lambda_full_inv = np.dot(np.dot(J_full, mass_matrix_inv), J_full.transpose()) + + # Jx M^-1 Jx^T + lambda_pos_inv = np.dot(np.dot(J_pos, mass_matrix_inv), J_pos.transpose()) + + # Jr M^-1 Jr^T + lambda_ori_inv = np.dot(np.dot(J_ori, mass_matrix_inv), J_ori.transpose()) + + # take the inverses, but zero out small singular values for stability + lambda_full = np.linalg.pinv(lambda_full_inv) + lambda_pos = np.linalg.pinv(lambda_pos_inv) + lambda_ori = np.linalg.pinv(lambda_ori_inv) + + # nullspace + Jbar = np.dot(mass_matrix_inv, J_full.transpose()).dot(lambda_full) + nullspace_matrix = np.eye(J_full.shape[-1], J_full.shape[-1]) - np.dot(Jbar, J_full) + + return lambda_full, lambda_pos, lambda_ori, nullspace_matrix + + +@jit_decorator +def orientation_error(desired, current): + """ + This function calculates a 3-dimensional orientation error vector for use in the + impedance controller. It does this by computing the delta rotation between the + inputs and converting that rotation to exponential coordinates (axis-angle + representation, where the 3d vector is axis * angle). + See https://en.wikipedia.org/wiki/Axis%E2%80%93angle_representation for more information. + Optimized function to determine orientation error from matrices + + Args: + desired (np.array): 2d array representing target orientation matrix + current (np.array): 2d array representing current orientation matrix + + Returns: + np.array: 2d array representing orientation error as a matrix + """ + rc1 = current[0:3, 0] + rc2 = current[0:3, 1] + rc3 = current[0:3, 2] + rd1 = desired[0:3, 0] + rd2 = desired[0:3, 1] + rd3 = desired[0:3, 2] + + error = 0.5 * (np.cross(rc1, rd1) + np.cross(rc2, rd2) + np.cross(rc3, rd3)) + + return error + + +def set_goal_position(delta, current_position, position_limit=None, set_pos=None): + """ + Calculates and returns the desired goal position, clipping the result accordingly to @position_limits. + @delta and @current_position must be specified if a relative goal is requested, else @set_pos must be + specified to define a global goal position + + Args: + delta (np.array): Desired relative change in position + current_position (np.array): Current position + position_limit (None or np.array): 2d array defining the (min, max) limits of permissible position goal commands + set_pos (None or np.array): If set, will ignore @delta and set the goal position to this value + + Returns: + np.array: calculated goal position in absolute coordinates + + Raises: + ValueError: [Invalid position_limit shape] + """ + n = len(current_position) + if set_pos is not None: + goal_position = set_pos + else: + goal_position = current_position + delta + + if position_limit is not None: + if position_limit.shape != (2, n): + raise ValueError( + "Position limit should be shaped (2,{}) " "but is instead: {}".format(n, position_limit.shape) + ) + + # Clip goal position + goal_position = np.clip(goal_position, position_limit[0], position_limit[1]) + + return goal_position + + +def set_goal_orientation(delta, current_orientation, orientation_limit=None, set_ori=None): + """ + Calculates and returns the desired goal orientation, clipping the result accordingly to @orientation_limits. + @delta and @current_orientation must be specified if a relative goal is requested, else @set_ori must be + an orientation matrix specified to define a global orientation + + Args: + delta (np.array): Desired relative change in orientation, in axis-angle form [ax, ay, az] + current_orientation (np.array): Current orientation, in rotation matrix form + orientation_limit (None or np.array): 2d array defining the (min, max) limits of permissible orientation goal commands + set_ori (None or np.array): If set, will ignore @delta and set the goal orientation to this value + + Returns: + np.array: calculated goal orientation in absolute coordinates + + Raises: + ValueError: [Invalid orientation_limit shape] + """ + # directly set orientation + if set_ori is not None: + goal_orientation = set_ori + + # otherwise use delta to set goal orientation + else: + # convert axis-angle value to rotation matrix + quat_error = trans.axisangle2quat(delta) + rotation_mat_error = trans.quat2mat(quat_error) + goal_orientation = np.dot(rotation_mat_error, current_orientation) + + # check for orientation limits + if np.array(orientation_limit).any(): + if orientation_limit.shape != (2, 3): + raise ValueError( + "Orientation limit should be shaped (2,3) " "but is instead: {}".format(orientation_limit.shape) + ) + + # Convert to euler angles for clipping + euler = trans.mat2euler(goal_orientation) + + # Clip euler angles according to specified limits + limited = False + for idx in range(3): + if orientation_limit[0][idx] < orientation_limit[1][idx]: # Normal angle sector meaning + if orientation_limit[0][idx] < euler[idx] < orientation_limit[1][idx]: + continue + else: + limited = True + dist_to_lower = euler[idx] - orientation_limit[0][idx] + if dist_to_lower > np.pi: + dist_to_lower -= 2 * np.pi + elif dist_to_lower < -np.pi: + dist_to_lower += 2 * np.pi + + dist_to_higher = euler[idx] - orientation_limit[1][idx] + if dist_to_lower > np.pi: + dist_to_higher -= 2 * np.pi + elif dist_to_lower < -np.pi: + dist_to_higher += 2 * np.pi + + if dist_to_lower < dist_to_higher: + euler[idx] = orientation_limit[0][idx] + else: + euler[idx] = orientation_limit[1][idx] + else: # Inverted angle sector meaning + if orientation_limit[0][idx] < euler[idx] or euler[idx] < orientation_limit[1][idx]: + continue + else: + limited = True + dist_to_lower = euler[idx] - orientation_limit[0][idx] + if dist_to_lower > np.pi: + dist_to_lower -= 2 * np.pi + elif dist_to_lower < -np.pi: + dist_to_lower += 2 * np.pi + + dist_to_higher = euler[idx] - orientation_limit[1][idx] + if dist_to_lower > np.pi: + dist_to_higher -= 2 * np.pi + elif dist_to_lower < -np.pi: + dist_to_higher += 2 * np.pi + + if dist_to_lower < dist_to_higher: + euler[idx] = orientation_limit[0][idx] + else: + euler[idx] = orientation_limit[1][idx] + if limited: + goal_orientation = trans.euler2mat(np.array([euler[0], euler[1], euler[2]])) + return goal_orientation diff --git a/third_party/robosuite/robosuite/utils/errors.py b/third_party/robosuite/robosuite/utils/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..efe0b5cd7119b9a987975ae6028a9e76326d1f8c --- /dev/null +++ b/third_party/robosuite/robosuite/utils/errors.py @@ -0,0 +1,22 @@ +class robosuiteError(Exception): + """Base class for exceptions in robosuite.""" + + pass + + +class XMLError(robosuiteError): + """Exception raised for errors related to xml.""" + + pass + + +class SimulationError(robosuiteError): + """Exception raised for errors during runtime.""" + + pass + + +class RandomizationError(robosuiteError): + """Exception raised for really really bad RNG.""" + + pass diff --git a/third_party/robosuite/robosuite/utils/ik_utils.py b/third_party/robosuite/robosuite/utils/ik_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a4fc7bb9d5ca5eaec7beb3c6398e058336eebe3b --- /dev/null +++ b/third_party/robosuite/robosuite/utils/ik_utils.py @@ -0,0 +1,327 @@ +from typing import Dict, List, Literal, Optional, Tuple + +import mujoco +import mujoco.viewer +import numpy as np + +import robosuite.utils.transform_utils as T +from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER + + +def get_nullspace_gains(joint_names: List[str], weight_dict: Dict[str, float]) -> np.ndarray: + return np.array([weight_dict.get(joint, 1.0) for joint in joint_names]) + + +class IKSolver: + def __init__( + self, + model: mujoco.MjModel, + data: mujoco.MjData, + robot_config: Dict, + damping: float, + integration_dt: float, + max_dq: float, + max_dq_torso: float = 0.3, + input_type: Literal["keyboard", "mocap", "pkl"] = "keyboard", + debug: bool = False, + input_action_repr: Literal["absolute", "relative", "relative_pose"] = "absolute", + input_file: Optional[str] = None, + input_rotation_repr: Literal["quat_wxyz", "axis_angle"] = "axis_angle", + ): + """ + Args: + input_action_repr: + absolute: input actions are absolute positions and rotations. + relative: input actions are relative to the current position and rotation, separately. + relative_pose: input actions are relative_pose to the pose of the respective reference site. + """ + self.full_model = model + self.full_model_data = data + + self.damping = damping + self.integration_dt = integration_dt + self.max_dq = max_dq + self.max_dq_torso = max_dq_torso + + self.joint_names = robot_config["joint_names"] + self.site_names = robot_config["end_effector_sites"] + self.site_ids = [ + self.full_model.site(robot_config["end_effector_sites"][i]).id + for i in range(len(robot_config["end_effector_sites"])) + ] + self.dof_ids = np.array([self.full_model.joint(name).id for name in robot_config["joint_names"]]) + # self.actuator_ids = np.array([self.full_model.actuator(name).id for name in robot_config['joint_names']]) # this works if actuators match joints + self.actuator_ids = np.array([i for i in range(20)]) # TODO no hardcode; cur for GR1; model.nu is 32 + self.key_id = ( + self.full_model.key(robot_config["initial_keyframe"]).id if "initial_keyframe" in robot_config else None + ) + + self.jac_temps: List[np.ndarray] = [np.zeros((6, self.full_model.nv)) for _ in range(len(self.site_ids))] + self.twists: List[np.ndarray] = [np.zeros(6) for _ in range(len(self.site_ids))] + self.site_quats: List[np.ndarray] = [np.zeros(4) for _ in range(len(self.site_ids))] + self.site_quat_conjs: List[np.ndarray] = [np.zeros(4) for _ in range(len(self.site_ids))] + self.error_quats: List[np.ndarray] = [np.zeros(4) for _ in range(len(self.site_ids))] + + self.input_action_repr = input_action_repr + self.input_rotation_repr = input_rotation_repr + ROTATION_REPRESENTATION_DIMS: Dict[str, int] = {"quat_wxyz": 4, "axis_angle": 3} + self.rot_dim = ROTATION_REPRESENTATION_DIMS[input_rotation_repr] + self.pos_dim = 3 + self.control_dim = len(self.site_names) * (self.pos_dim + self.rot_dim) + # hardcoded control limits for now + self.control_limits = np.array([-np.inf] * self.control_dim), np.array([np.inf] * self.control_dim) + self.debug_iter = 0 + self.debug = debug + if debug: + self.pre_clip_errors: List[np.ndarray] = [] + + self.input_type = input_type + if input_type == "mocap": + self.mocap_ids = [self.full_model.body(name).mocapid[0] for name in robot_config["mocap_bodies"]] + elif input_type == "pkl": + self.mocap_ids = [self.full_model.body(name).mocapid[0] for name in robot_config["mocap_bodies"]] + self.pkl_t = 0 + import pickle + + with open(input_file, "rb") as f: + input_file = pickle.load(f) + self.history = input_file + + # Nullspace control + self.q0 = np.zeros(len(self.dof_ids)) + self.Kn = np.array(robot_config["nullspace_gains"]) + + # Initialize error and error_dot + self.error_prev = np.zeros_like(self.q0) + self.error_dot = np.zeros_like(self.q0) + + def action_split_indexes(self) -> Dict[str, Tuple[int, int]]: + action_split_indexes: Dict[str, Tuple[int, int]] = {} + previous_idx = 0 + + for site_name in self.site_names: + total_dim = self.pos_dim + self.rot_dim + last_idx = previous_idx + total_dim + simplified_site_name = "left" if "left" in site_name else "right" # hack to simplify site names + # goal is to specify the end effector actions as "left" or "right" instead of the actual site name + # we assume that the site names for the ik solver are unique and contain "left" or "right" in them + action_split_indexes[simplified_site_name] = (previous_idx, last_idx) + previous_idx = last_idx + + return action_split_indexes + + def reset_to_initial_state(self): + if self.key_id is not None: + mujoco.mj_resetDataKeyframe(self.full_model, self.full_model_data, self.key_id) + else: + print("No initial keyframe set. Skipping reset.") + + def set_target_positions(self, target_positions: List): + for i, pos in enumerate(target_positions): + self.full_model_data.mocap_pos[self.mocap_ids[i]] = pos + + def set_target_rotations(self, target_rotations: List): + for i, quat_wxyz in enumerate(target_rotations): + self.full_model_data.mocap_quat[self.mocap_ids[i]] = quat_wxyz + + def get_targets(self): + # by default set target to current site position + target_pos = np.array([self.full_model_data.site(site_id).xpos for site_id in self.site_ids]) + target_ori_mat = np.array([self.full_model_data.site(site_id).xmat for site_id in self.site_ids]) + target_ori = np.array([np.ones(4) for _ in range(len(self.site_ids))]) + [mujoco.mju_mat2Quat(target_ori[i], target_ori_mat[i]) for i in range(len(self.site_ids))] + + if self.input_type == "mocap": + for i in range(len(self.site_ids)): + target_pos[i] = self.full_model_data.mocap_pos[self.mocap_ids[i]] + target_ori[i] = self.full_model_data.mocap_quat[self.mocap_ids[i]] + elif self.input_type == "pkl": + left_index, right_index = 0, 1 + self.pkl_t += 1 / 10 # hardcoded pkl playback freq for now + if int(self.pkl_t) >= len(self.history["left_eef_pos"]): + print("Reached end of pkl file. Exiting.") + exit() + target_pos[left_index] = self.history["left_eef_pos"][int(self.pkl_t)] + target_pos[right_index] = self.history["right_eef_pos"][int(self.pkl_t)] + target_ori[left_index] = self.history["left_eef_quat_wxyz"][int(self.pkl_t)] + target_ori[right_index] = self.history["right_eef_quat_wxyz"][int(self.pkl_t)] + self.full_model_data.mocap_pos[self.mocap_ids[left_index]] = self.history["left_eef_pos"][int(self.pkl_t)] + self.full_model_data.mocap_pos[self.mocap_ids[right_index]] = self.history["right_eef_pos"][int(self.pkl_t)] + self.full_model_data.mocap_quat[self.mocap_ids[left_index]] = self.history["left_eef_quat_wxyz"][ + int(self.pkl_t) + ] + self.full_model_data.mocap_quat[self.mocap_ids[right_index]] = self.history["right_eef_quat_wxyz"][ + int(self.pkl_t) + ] + else: + raise ValueError(f"Invalid input type {self.input_type}") + + return target_pos, target_ori + + def _compute_jacobian(self, model: mujoco.MjModel, data: mujoco.MjData): + for i, site_id in enumerate(self.site_ids): + mujoco.mj_jacSite(model, data, self.jac_temps[i][:3], self.jac_temps[i][3:], site_id) + + jac = np.vstack(self.jac_temps) + # compute jacobian for our dof_ids + jac = jac[:, self.dof_ids] + return jac + + def forward_kinematics(self, qpos: np.ndarray) -> Dict[str, np.ndarray]: + data = mujoco.MjData(self.full_model) + data.qpos[self.dof_ids] = qpos + mujoco.mj_kinematics(self.full_model, data) + return {name: data.site(site_id).xpos for name, site_id in zip(self.site_names, self.site_ids)} + + def transform_pose( + self, src_frame_pose: np.ndarray, src_frame: Literal["world", "base"], dst_frame: Literal["world", "base"] + ) -> np.ndarray: + """ + Transforms src_frame_pose from src_frame to dst_frame. + """ + if src_frame == dst_frame: + return src_frame_pose + + X_src_frame_pose = src_frame_pose + # convert src frame pose to world frame pose + if src_frame != "world": + X_W_src_frame = T.make_pose( + translation=self.full_model.body(src_frame).pos, + rotation=T.quat2mat(np.roll(self.full_model.body(src_frame).quat, shift=-1)), + ) + X_W_pose = X_W_src_frame @ X_src_frame_pose + else: + X_W_pose = src_frame_pose + + # now convert to destination frame + if dst_frame == "world": + X_dst_frame_pose = X_W_pose + elif dst_frame == "base": + X_dst_frame_W = np.linalg.inv( + T.make_pose( + translation=self.full_model.body("robot0_base").pos, + rotation=T.quat2mat(np.roll(self.full_model.body("robot0_base").quat, shift=-1)), + ) + ) # hardcode name of base + X_dst_frame_pose = X_dst_frame_W.dot(X_W_pose) + + return X_dst_frame_pose + + def solve( + self, + target_action: np.ndarray, + Kpos: float = 0.95, + Kori: float = 0.95, + ): + target_action = target_action.reshape(len(self.site_names), -1) + target_pos = target_action[:, : self.pos_dim] + target_ori = target_action[:, self.pos_dim :] + target_quat_wxyz = None + + if self.input_rotation_repr == "axis_angle": + target_quat_wxyz = np.array([np.roll(T.axisangle2quat(target_ori[i]), 1) for i in range(len(target_ori))]) + elif self.input_rotation_repr == "mat": + target_quat_wxyz = np.array([np.roll(T.mat2quat(target_ori[i])) for i in range(len(target_ori))]) + elif self.input_rotation_repr == "quat_wxyz": + target_quat_wxyz = target_ori + + if "relative" in self.input_action_repr: + cur_pos = np.array([self.full_model_data.site(site_id).xpos for site_id in self.site_ids]) + cur_ori = np.array([self.full_model_data.site(site_id).xmat for site_id in self.site_ids]) + if self.input_action_repr == "relative": + # decoupled pos and rotation deltas + target_pos += cur_pos + target_quat_xyzw = np.array( + [ + T.quat_multiply(T.mat2quat(cur_ori[i].reshape(3, 3)), np.roll(target_quat_wxyz[i], -1)) + for i in range(len(self.site_ids)) + ] + ) + target_quat_wxyz = np.array([np.roll(target_quat_xyzw[i], shift=1) for i in range(len(self.site_ids))]) + elif self.input_action_repr == "relative_pose": + cur_poses = np.zeros((len(self.site_ids), 4, 4)) + for i in range(len(self.site_ids)): + cur_poses[i, :3, :3] = cur_ori[i].reshape(3, 3) + cur_poses[i, :3, 3] = cur_pos[i] + cur_poses[i, 3, :] = [0, 0, 0, 1] + + # Convert target action to target pose + target_poses = np.zeros_like(cur_poses) + for i in range(len(self.site_ids)): + target_poses[i, :3, :3] = T.quat2mat(target_quat_wxyz[i]) + target_poses[i, :3, 3] = target_pos[i] + target_poses[i, 3, :] = [0, 0, 0, 1] + + # Apply target pose to current pose + new_target_poses = np.array([np.dot(cur_poses[i], target_poses[i]) for i in range(len(self.site_ids))]) + + # Split new target pose back into position and quaternion + target_pos = new_target_poses[:, :3, 3] + target_quat_wxyz = np.array( + [np.roll(T.mat2quat(new_target_poses[i, :3, :3]), shift=1) for i in range(len(self.site_ids))] + ) + + jac = self._compute_jacobian(self.full_model, self.full_model_data) + + for i in range(len(self.site_ids)): + dx = target_pos[i] - self.full_model_data.site(self.site_ids[i]).xpos + self.twists[i][:3] = Kpos * dx / self.integration_dt + mujoco.mju_mat2Quat(self.site_quats[i], self.full_model_data.site(self.site_ids[i]).xmat) + mujoco.mju_negQuat(self.site_quat_conjs[i], self.site_quats[i]) + mujoco.mju_mulQuat(self.error_quats[i], target_quat_wxyz[i], self.site_quat_conjs[i]) + mujoco.mju_quat2Vel(self.twists[i][3:], self.error_quats[i], 1.0) + self.twists[i][3:] *= Kori / self.integration_dt + + self.twist = np.hstack(self.twists) + diag = self.damping**2 * np.eye(len(self.twist)) + eye = np.eye(len(self.dof_ids)) + # basically dq = J^{-1} dx. This formulation is nicer since m is small in dimensionality. + self.dq = jac.T @ np.linalg.solve(jac @ jac.T + diag, self.twist) + # Nullspace control: intuitively, (eye - np.linalg.pinv(jac) @ jac) + # projects dqs into the nullspace of the Jacobian, which intuitively + # only allows movements that don't affect the task space. + dq_null = (eye - np.linalg.pinv(jac) @ jac) @ (self.Kn * (self.q0 - self.full_model_data.qpos[self.dof_ids])) + self.dq += dq_null + + if self.max_dq > 0: + dq_abs_max = np.abs(self.dq).max() + if dq_abs_max > self.max_dq: + self.dq *= self.max_dq / dq_abs_max + + torso_joint_ids = [self.full_model.joint(name).id for name in self.joint_names if "torso" in name] + if len(torso_joint_ids) > 0 and self.max_dq_torso > 0: + dq_torso = self.dq[torso_joint_ids] + dq_torso_abs_max = np.abs(dq_torso).max() + if dq_torso_abs_max > self.max_dq_torso: + dq_torso *= self.max_dq_torso / dq_torso_abs_max + self.dq[torso_joint_ids] = dq_torso + + # get the desired joint angles by integrating the desired joint velocities + self.q_des = self.full_model_data.qpos[self.dof_ids].copy() + # mujoco.mj_integratePos(self.full_model, self.q_des, self.dq, self.integration_dt) + self.q_des += self.dq * self.integration_dt # manually integrate q_des + + pre_clip_error = np.inf + post_clip_error = np.inf + + if self.debug and self.debug_iter % 10 == 0: + # compare q_des's forward kinematics with target_pos + integrated_pos: Dict[str, np.ndarray] = self.forward_kinematics(self.q_des) + integrated_pos_np = np.array([integrated_pos[site] for site in integrated_pos]) + pre_clip_error = np.linalg.norm(target_pos - integrated_pos_np) + ROBOSUITE_DEFAULT_LOGGER.info(f"IK error before clipping based on joint ranges: {pre_clip_error}") + # self.pre_clip_errors.append(pre_clip_error) + + # Set the control signal. + np.clip(self.q_des, *self.full_model.jnt_range[self.dof_ids].T, out=self.q_des) + + if self.debug and self.debug_iter % 10 == 0: + # compare self.q_des's forward kinematics with target_pos + integrated_pos: Dict[str, np.ndarray] = self.forward_kinematics(self.q_des) + integrated_pos_np = np.array([integrated_pos[site] for site in integrated_pos]) + post_clip_error = np.linalg.norm(target_pos - integrated_pos_np) + ROBOSUITE_DEFAULT_LOGGER.info(f"IK error after clipping based on joint ranges: {post_clip_error}") + + self.debug_iter += 1 + + return self.q_des diff --git a/third_party/robosuite/robosuite/utils/input_utils.py b/third_party/robosuite/robosuite/utils/input_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2a558df1ee5553387bd7df758d3419ab14ee1c5a --- /dev/null +++ b/third_party/robosuite/robosuite/utils/input_utils.py @@ -0,0 +1,150 @@ +""" +Utility functions for grabbing user inputs +""" + +import numpy as np + +import robosuite as suite +import robosuite.utils.transform_utils as T + +# from robosuite.devices import * +from robosuite.models.robots import * +from robosuite.robots import * + + +def choose_environment(): + """ + Prints out environment options, and returns the selected env_name choice + + Returns: + str: Chosen environment name + """ + # get the list of all environments + envs = sorted(suite.ALL_ENVIRONMENTS) + + # Select environment to run + print("Here is a list of environments in the suite:\n") + + for k, env in enumerate(envs): + print("[{}] {}".format(k, env)) + print() + try: + s = input("Choose an environment to run " + "(enter a number from 0 to {}): ".format(len(envs) - 1)) + # parse input into a number within range + k = min(max(int(s), 0), len(envs)) + except: + k = 0 + print("Input is not valid. Use {} by default.\n".format(envs[k])) + + # Return the chosen environment name + return envs[k] + + +def choose_controller(part_controllers=False): + """ + Prints out controller options, and returns the requested controller name + + Returns: + str: Chosen controller name + """ + # get the list of all controllers + controllers = list(suite.ALL_PART_CONTROLLERS) if part_controllers else list(suite.ALL_COMPOSITE_CONTROLLERS) + + # Select controller to use + print("Here is a list of controllers in the suite:\n") + + for k, controller in enumerate(controllers): + print("[{}] {}".format(k, controller)) + print() + try: + s = input("Choose a controller for the robot " + "(enter a number from 0 to {}): ".format(len(controllers) - 1)) + # parse input into a number within range + k = min(max(int(s), 0), len(controllers) - 1) + except: + k = 0 + print("Input is not valid. Use {} by default.".format(controllers)[k]) + + # Return chosen controller + return controllers[k] + + +def choose_multi_arm_config(): + """ + Prints out multi-arm environment configuration options, and returns the requested config name + + Returns: + str: Requested multi-arm configuration name + """ + # Get the list of all multi arm configs + env_configs = { + "Opposed": "opposed", + "Parallel": "parallel", + "Single-Robot": "single-robot", + } + + # Select environment configuration + print("A multi-arm environment was chosen. Here is a list of multi-arm environment configurations:\n") + + for k, env_config in enumerate(list(env_configs)): + print("[{}] {}".format(k, env_config)) + print() + try: + s = input( + "Choose a configuration for this environment " + + "(enter a number from 0 to {}): ".format(len(env_configs) - 1) + ) + # parse input into a number within range + k = min(max(int(s), 0), len(env_configs)) + except: + k = 0 + print("Input is not valid. Use {} by default.".format(list(env_configs)[k])) + + # Return requested configuration + return list(env_configs.values())[k] + + +def choose_robots(exclude_bimanual=False, use_humanoids=False, exclude_single_arm=False): + """ + Prints out robot options, and returns the requested robot. Restricts options to single-armed robots if + @exclude_bimanual is set to True (False by default). Restrict options to humanoids if @use_humanoids is set to True (Flase by default). + + Args: + exclude_bimanual (bool): If set, excludes bimanual robots from the robot options + use_humanoids (bool): If set, use humanoid robots + + Returns: + str: Requested robot name + """ + # Get the list of robots + if exclude_single_arm: + robots = set() + else: + robots = {"Sawyer", "Panda", "Jaco", "Kinova3", "IIWA", "UR5e", "SpotWithArmFloating"} + + # Add Baxter if bimanual robots are not excluded + if not exclude_bimanual: + robots.add("Baxter") + robots.add("GR1ArmsOnly") + robots.add("Tiago") + if use_humanoids: + robots.add("GR1ArmsOnly") + + # Make sure set is deterministically sorted + robots = sorted(robots) + + # Select robot + print("Here is a list of available robots:\n") + + for k, robot in enumerate(robots): + print("[{}] {}".format(k, robot)) + print() + try: + s = input("Choose a robot " + "(enter a number from 0 to {}): ".format(len(robots) - 1)) + # parse input into a number within range + k = min(max(int(s), 0), len(robots)) + except: + k = 0 + print("Input is not valid. Use {} by default.".format(list(robots)[k])) + + # Return requested robot + return list(robots)[k] diff --git a/third_party/robosuite/robosuite/utils/log_utils.py b/third_party/robosuite/robosuite/utils/log_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e2dc96c9836cc06fee8bdb066690418b4c82085d --- /dev/null +++ b/third_party/robosuite/robosuite/utils/log_utils.py @@ -0,0 +1,150 @@ +""" +This file contains utility classes and functions for logging to stdout and stderr +Adapted from robomimic: https://github.com/ARISE-Initiative/robomimic/blob/master/robomimic/utils/log_utils.py +""" +import inspect +import logging +import os +import time + +from termcolor import colored + +import robosuite.macros as macros + +LEVEL_COLORS = { + logging.DEBUG: "green", + logging.INFO: "green", + logging.WARNING: "yellow", + logging.ERROR: "red", + logging.CRITICAL: "red", +} + +FORMAT_STR = {"file": "[robosuite %(levelname)s - %(asctime)s] ", "console": "[robosuite %(levelname)s] "} + +MESSAGE_STR = "%(message)s (%(filename)s:%(lineno)d)" + + +class FileFormatter(logging.Formatter): + """Formatter class of logging for file logging.""" + + FORMATS = { + levelno: colored(FORMAT_STR["file"], color, attrs=["bold"]) + MESSAGE_STR + for (levelno, color) in LEVEL_COLORS.items() + } + + def format(self, record): + """Apply custom fomatting on LogRecord object record.""" + log_fmt = self.FORMATS.get(record.levelno) + formatter = logging.Formatter(log_fmt, "%Y-%m-%d %H:%M:%S") + return formatter.format(record) + + +class ConsoleFormatter(logging.Formatter): + """Formatter class of logging for console logging.""" + + FORMATS = { + logging.DEBUG: FORMAT_STR["console"] + MESSAGE_STR, + logging.INFO: colored(FORMAT_STR["console"], "green", attrs=["bold"]) + MESSAGE_STR, + logging.WARNING: colored(FORMAT_STR["console"], "yellow", attrs=["bold"]) + MESSAGE_STR, + logging.ERROR: colored(FORMAT_STR["console"], "red", attrs=["bold"]) + MESSAGE_STR, + logging.CRITICAL: colored(FORMAT_STR["console"], "red", attrs=["bold", "reverse"]) + MESSAGE_STR, + } + + def format(self, record): + """Apply custom fomatting on LogRecord object record.""" + log_fmt = self.FORMATS.get(record.levelno) + formatter = logging.Formatter(log_fmt) + return formatter.format(record) + + +class DefaultLogger: + """Default logger class in robosuite codebase.""" + + def __init__(self, logger_name="robosuite_logs", console_logging_level="INFO", file_logging_level=None): + """ + Args: + logger_name (str, optional): logger name. Defaults to "robosuite_logs". + console_logging_level (str, optional): logging level for console logging. Defaults to "INFO". + file_logging_level (_type_, optional): logging level for file logging. Defaults to None. + """ + self.logger_name = logger_name + logger = logging.getLogger(self.logger_name) + + if file_logging_level is not None: + time_str = str(time.time()).replace(".", "_") + log_file_path = "/tmp/robosuite_{}_{}.log".format(time_str, os.getpid()) + fh = logging.FileHandler(log_file_path) + print(colored("[robosuite]: Saving logs to {}".format(log_file_path), "yellow")) + fh.setLevel(logging.getLevelName(file_logging_level)) + file_formatter = FileFormatter() + fh.setFormatter(file_formatter) + logger.addHandler(fh) + + if console_logging_level is not None: + ch = logging.StreamHandler() + ch.setLevel(logging.getLevelName(console_logging_level)) + console_formatter = ConsoleFormatter() + ch.setFormatter(console_formatter) + logger.addHandler(ch) + logger.setLevel(logging.getLevelName(console_logging_level)) + + def get_logger(self): + """_summary_ + + Returns: + DefaultLogger: The retrieved logger whose name equals self.logger_name + """ + logger = logging.getLogger(self.logger_name) + return logger + + +def format_message(level: str, message: str) -> str: + """ + Format a message with colors based on the level and include file and line number. + + Args: + level (str): The logging level (e.g., "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"). + message (str): The message to format. + + Returns: + str: The formatted message with file and line number. + """ + # Get the caller's file name and line number + frame = inspect.currentframe().f_back + filename = frame.f_code.co_filename + lineno = frame.f_lineno + + # Level-based coloring + level_colors = { + "DEBUG": "blue", + "INFO": "green", + "WARNING": "yellow", + "ERROR": "red", + "CRITICAL": "red", + } + attrs = ["bold"] + if level == "CRITICAL": + attrs.append("reverse") + + color = level_colors.get(level, "white") + formatted_message = colored(f"[{level}] {filename}:{lineno} - {message}", color, attrs=attrs) + return formatted_message + + +def rs_assert(condition: bool, message: str): + """ + Assert a condition and raise an error with a formatted message if the condition fails. + + Args: + condition (bool): The condition to check. + message (str): The error message to display if the assertion fails. + """ + if not condition: + formatted_message = format_message("ERROR", message) + raise AssertionError(formatted_message) + + +ROBOSUITE_DEFAULT_LOGGER = DefaultLogger( + console_logging_level=macros.CONSOLE_LOGGING_LEVEL, + file_logging_level=macros.FILE_LOGGING_LEVEL, +).get_logger() diff --git a/third_party/robosuite/robosuite/utils/mjcf_utils.py b/third_party/robosuite/robosuite/utils/mjcf_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6f7207a81f57a84f1d93ffd69a7c3d7a3844075f --- /dev/null +++ b/third_party/robosuite/robosuite/utils/mjcf_utils.py @@ -0,0 +1,912 @@ +# utility functions for manipulating MJCF XML models + +import os +import xml.etree.ElementTree as ET +from collections.abc import Iterable +from copy import deepcopy +from pathlib import Path + +import numpy as np +from PIL import Image + +import robosuite + +RED = [1, 0, 0, 1] +GREEN = [0, 1, 0, 1] +BLUE = [0, 0, 1, 1] +CYAN = [0, 1, 1, 1] +ROBOT_COLLISION_COLOR = [0, 0.5, 0, 1] +MOUNT_COLLISION_COLOR = [0.5, 0.5, 0, 1] +GRIPPER_COLLISION_COLOR = [0, 0, 0.5, 1] +OBJECT_COLLISION_COLOR = [0.5, 0, 0, 1] +ENVIRONMENT_COLLISION_COLOR = [0.5, 0.5, 0, 1] +SENSOR_TYPES = { + "touch", + "accelerometer", + "velocimeter", + "gyro", + "force", + "torque", + "magnetometer", + "rangefinder", + "jointpos", + "jointvel", + "tendonpos", + "tendonvel", + "actuatorpos", + "actuatorvel", + "actuatorfrc", + "ballangvel", + "jointlimitpos", + "jointlimitvel", + "jointlimitfrc", + "tendonlimitpos", + "tendonlimitvel", + "tendonlimitfrc", + "framepos", + "framequat", + "framexaxis", + "frameyaxis", + "framezaxis", + "framelinvel", + "frameangvel", + "framelinacc", + "frameangacc", + "subtreecom", + "subtreelinvel", + "subtreeangmom", + "user", +} + +MUJOCO_NAMED_ATTRIBUTES = { + "class", + "childclass", + "name", + "objname", + "material", + "texture", + "joint", + "joint1", + "joint2", + "jointinparent", + "geom", + "geom1", + "geom2", + "mesh", + "fixed", + "actuator", + "objname", + "tendon", + "tendon1", + "tendon2", + "slidesite", + "cranksite", + "body", + "body1", + "body2", + "hfield", + "target", + "prefix", + "site", +} + +IMAGE_CONVENTION_MAPPING = { + "opengl": 1, + "opencv": -1, +} + +TEXTURE_FILES = { + "WoodRed": "red-wood.png", + "WoodGreen": "green-wood.png", + "WoodBlue": "blue-wood.png", + "WoodLight": "light-wood.png", + "WoodDark": "dark-wood.png", + "WoodTiles": "wood-tiles.png", + "WoodPanels": "wood-varnished-panels.png", + "WoodgrainGray": "gray-woodgrain.png", + "PlasterCream": "cream-plaster.png", + "PlasterPink": "pink-plaster.png", + "PlasterYellow": "yellow-plaster.png", + "PlasterGray": "gray-plaster.png", + "PlasterWhite": "white-plaster.png", + "BricksWhite": "white-bricks.png", + "Metal": "metal.png", + "SteelBrushed": "steel-brushed.png", + "SteelScratched": "steel-scratched.png", + "Brass": "brass-ambra.png", + "Bread": "bread.png", + "Can": "can.png", + "Ceramic": "ceramic.png", + "Cereal": "cereal.png", + "Clay": "clay.png", + "Dirt": "dirt.png", + "Glass": "glass.png", + "FeltGray": "gray-felt.png", + "Lemon": "lemon.png", +} + +TEXTURES = { + texture_name: os.path.join("textures", texture_file) for (texture_name, texture_file) in TEXTURE_FILES.items() +} + +ALL_TEXTURES = TEXTURES.keys() + + +class CustomMaterial(object): + """ + Simple class to instantiate the necessary parameters to define an appropriate texture / material combo + + Instantiates a nested dict holding necessary components for procedurally generating a texture / material combo + + Please see http://www.mujoco.org/book/XMLreference.html#asset for specific details on + attributes expected for Mujoco texture / material tags, respectively + + Note that the values in @tex_attrib and @mat_attrib can be in string or array / numerical form. + + Args: + texture (None or str or 4-array): Name of texture file to be imported. If a string, should be part of + ALL_TEXTURES. If texture is a 4-array, then this argument will be interpreted as an rgba tuple value and + a template png will be procedurally generated during object instantiation, with any additional + texture / material attributes specified. If None, no file will be linked and no rgba value will be set + Note, if specified, the RGBA values are expected to be floats between 0 and 1 + + tex_name (str): Name to reference the imported texture + + mat_name (str): Name to reference the imported material + + tex_attrib (dict): Any other optional mujoco texture specifications. + + mat_attrib (dict): Any other optional mujoco material specifications. + + shared (bool): If True, this material should not have any naming prefixes added to all names + + Raises: + AssertionError: [Invalid texture] + """ + + def __init__( + self, + texture, + tex_name, + mat_name, + tex_attrib=None, + mat_attrib=None, + shared=False, + ): + # Check if the desired texture is an rgba value + if type(texture) is str: + default = False + # Verify that requested texture is valid + texture_is_path = "/" in texture + if not texture_is_path: + assert ( + texture in ALL_TEXTURES + ), "Error: Requested invalid texture. Got {}. Valid options are:\n{}".format(texture, ALL_TEXTURES) + else: + default = True + # If specified, this is an rgba value and a default texture is desired; make sure length of rgba array is 4 + if texture is not None: + assert len(texture) == 4, ( + "Error: Requested default texture. Got array of length {}." + "Expected rgba array of length 4.".format(len(texture)) + ) + + # Setup the texture and material attributes + self.tex_attrib = {} if tex_attrib is None else tex_attrib.copy() + self.mat_attrib = {} if mat_attrib is None else mat_attrib.copy() + + # Add in name values + self.name = mat_name + self.shared = shared + self.tex_attrib["name"] = tex_name + self.mat_attrib["name"] = mat_name + self.mat_attrib["texture"] = tex_name + + # Loop through all attributes and convert all non-string values into strings + for attrib in (self.tex_attrib, self.mat_attrib): + for k, v in attrib.items(): + if type(v) is not str: + if isinstance(v, Iterable): + attrib[k] = array_to_string(v) + else: + attrib[k] = str(v) + + # Handle default and non-default cases separately for linking texture patch file locations + if not default: + # Add in the filepath to texture patch + texture_is_path = "/" in texture + if texture_is_path: + self.tex_attrib["file"] = xml_path_completion(texture) + else: + self.tex_attrib["file"] = xml_path_completion(TEXTURES[texture]) + else: + if texture is not None: + # Create a texture patch + tex = Image.new("RGBA", (100, 100), tuple((np.array(texture) * 255).astype("int"))) + # Create temp directory if it does not exist + save_dir = "/tmp/robosuite_temp_tex" + Path(save_dir).mkdir(parents=True, exist_ok=True) + # Save this texture patch to the temp directory on disk (MacOS / Linux) + fpath = save_dir + "/{}.png".format(tex_name) + tex.save(fpath, "PNG") + # Link this texture file to the default texture dict + self.tex_attrib["file"] = fpath + + +def xml_path_completion(xml_path, root=None): + """ + Takes in a local xml path and returns a full path. + if @xml_path is absolute, do nothing + if @xml_path is not absolute, load xml that is shipped by the package + + Args: + xml_path (str): local xml path + root (str): root folder for xml path. If not specified defaults to robosuite.models.assets_root + + Returns: + str: Full (absolute) xml path + """ + if xml_path.startswith("/"): + full_path = xml_path + else: + if root is None: + root = robosuite.models.assets_root + full_path = os.path.join(root, xml_path) + return full_path + + +def array_to_string(array): + """ + Converts a numeric array into the string format in mujoco. + + Examples: + [0, 1, 2] => "0 1 2" + + Args: + array (n-array): Array to convert to a string + + Returns: + str: String equivalent of @array + """ + return " ".join(["{}".format(x) for x in array]) + + +def string_to_array(string): + """ + Converts a array string in mujoco xml to np.array. + + Examples: + "0 1 2" => [0, 1, 2] + + Args: + string (str): String to convert to an array + + Returns: + np.array: Numerical array equivalent of @string + """ + return np.array([float(x) if x != "None" else None for x in string.strip().split(" ")]) + + +def convert_to_string(inp): + """ + Converts any type of {bool, int, float, list, tuple, array, string, np.str_} into an mujoco-xml compatible string. + Note that an input string / np.str_ results in a no-op action. + + Args: + inp: Input to convert to string + + Returns: + str: String equivalent of @inp + """ + if type(inp) in {list, tuple, np.ndarray}: + return array_to_string(inp) + elif type(inp) in {int, float, bool}: + return str(inp).lower() + elif type(inp) in {str, np.str_}: + return inp + else: + raise ValueError("Unsupported type received: got {}".format(type(inp))) + + +def set_alpha(node, alpha=0.1): + """ + Sets all a(lpha) field of the rgba attribute to be @alpha + for @node and all subnodes + used for managing display + + Args: + node (ET.Element): Specific node element within XML tree + alpha (float): Value to set alpha value of rgba tuple + """ + for child_node in node.findall(".//*[@rgba]"): + rgba_orig = string_to_array(child_node.get("rgba")) + child_node.set("rgba", array_to_string(list(rgba_orig[0:3]) + [alpha])) + + +def new_element(tag, name, **kwargs): + """ + Creates a new @tag element with attributes specified by @**kwargs. + + Args: + tag (str): Type of element to create + name (None or str): Name for this element. Should only be None for elements that do not have an explicit + name attribute (e.g.: inertial elements) + **kwargs: Specified attributes for the new joint + + Returns: + ET.Element: new specified xml element + """ + # Name will be set if it's not None + if name is not None: + kwargs["name"] = name + # Loop through all attributes and pop any that are None, otherwise convert them to strings + for k, v in kwargs.copy().items(): + if v is None: + kwargs.pop(k) + else: + kwargs[k] = convert_to_string(v) + element = ET.Element(tag, attrib=kwargs) + return element + + +def new_joint(name, **kwargs): + """ + Creates a joint tag with attributes specified by @**kwargs. + + Args: + name (str): Name for this joint + **kwargs: Specified attributes for the new joint + + Returns: + ET.Element: new joint xml element + """ + return new_element(tag="joint", name=name, **kwargs) + + +def new_actuator(name, joint, act_type="actuator", **kwargs): + """ + Creates an actuator tag with attributes specified by @**kwargs. + + Args: + name (str): Name for this actuator + joint (str): type of actuator transmission. + see all types here: http://mujoco.org/book/modeling.html#actuator + act_type (str): actuator type. Defaults to "actuator" + **kwargs: Any additional specified attributes for the new joint + + Returns: + ET.Element: new actuator xml element + """ + element = new_element(tag=act_type, name=name, **kwargs) + element.set("joint", joint) + return element + + +def new_site(name, rgba=RED, pos=(0, 0, 0), size=(0.005,), **kwargs): + """ + Creates a site element with attributes specified by @**kwargs. + + NOTE: With the exception of @name, @pos, and @size, if any arg is set to + None, the value will automatically be popped before passing the values + to create the appropriate XML + + Args: + name (str): Name for this site + rgba (4-array): (r,g,b,a) color and transparency. Defaults to solid red. + pos (3-array): (x,y,z) 3d position of the site. + size (n-array of float): site size (sites are spherical by default). + **kwargs: Any additional specified attributes for the new site + + Returns: + ET.Element: new site xml element + """ + kwargs["pos"] = pos + kwargs["size"] = size + kwargs["rgba"] = rgba if rgba is not None else None + return new_element(tag="site", name=name, **kwargs) + + +def new_geom(name, type, size, pos=(0, 0, 0), group=0, **kwargs): + """ + Creates a geom element with attributes specified by @**kwargs. + + NOTE: With the exception of @geom_type, @size, and @pos, if any arg is set to + None, the value will automatically be popped before passing the values + to create the appropriate XML + + Args: + name (str): Name for this geom + type (str): type of the geom. + see all types here: http://mujoco.org/book/modeling.html#geom + size (n-array of float): geom size parameters. + pos (3-array): (x,y,z) 3d position of the site. + group (int): the integrer group that the geom belongs to. useful for + separating visual and physical elements. + **kwargs: Any additional specified attributes for the new geom + + Returns: + ET.Element: new geom xml element + """ + kwargs["type"] = type + kwargs["size"] = size + kwargs["pos"] = pos + kwargs["group"] = group if group is not None else None + return new_element(tag="geom", name=name, **kwargs) + + +def new_body(name, pos=(0, 0, 0), **kwargs): + """ + Creates a body element with attributes specified by @**kwargs. + + Args: + name (str): Name for this body + pos (3-array): (x,y,z) 3d position of the body frame. + **kwargs: Any additional specified attributes for the new body + + Returns: + ET.Element: new body xml element + """ + kwargs["pos"] = pos + return new_element(tag="body", name=name, **kwargs) + + +def new_inertial(pos=(0, 0, 0), mass=None, **kwargs): + """ + Creates a inertial element with attributes specified by @**kwargs. + + Args: + pos (3-array): (x,y,z) 3d position of the inertial frame. + mass (float): The mass of inertial + **kwargs: Any additional specified attributes for the new inertial element + + Returns: + ET.Element: new inertial xml element + """ + kwargs["mass"] = mass if mass is not None else None + kwargs["pos"] = pos + return new_element(tag="inertial", name=None, **kwargs) + + +def get_size(size, size_max, size_min, default_max, default_min): + """ + Helper method for providing a size, or a range to randomize from + + Args: + size (n-array): Array of numbers that explicitly define the size + size_max (n-array): Array of numbers that define the custom max size from which to randomly sample + size_min (n-array): Array of numbers that define the custom min size from which to randomly sample + default_max (n-array): Array of numbers that define the default max size from which to randomly sample + default_min (n-array): Array of numbers that define the default min size from which to randomly sample + + Returns: + np.array: size generated + + Raises: + ValueError: [Inconsistent array sizes] + """ + if len(default_max) != len(default_min): + raise ValueError( + "default_max = {} and default_min = {}".format(str(default_max), str(default_min)) + + " have different lengths" + ) + if size is not None: + if (size_max is not None) or (size_min is not None): + raise ValueError("size = {} overrides size_max = {}, size_min = {}".format(size, size_max, size_min)) + else: + if size_max is None: + size_max = default_max + if size_min is None: + size_min = default_min + size = np.array([np.random.uniform(size_min[i], size_max[i]) for i in range(len(default_max))]) + return np.array(size) + + +def add_to_dict(dic, fill_in_defaults=True, default_value=None, **kwargs): + """ + Helper function to add key-values to dictionary @dic where each entry is its own array (list). + Args: + dic (dict): Dictionary to which new key / value pairs will be added. If the key already exists, + will append the value to that key entry + fill_in_defaults (bool): If True, will automatically add @default_value to all dictionary entries that are + not explicitly specified in @kwargs + default_value (any): Default value to fill (None by default) + + Returns: + dict: Modified dictionary + """ + # Get keys and length of array for a given entry in dic + keys = set(dic.keys()) + n = len(list(keys)[0]) if keys else 0 + for k, v in kwargs.items(): + if k in dic: + dic[k].append(v) + keys.remove(k) + else: + dic[k] = [default_value] * n + [v] if fill_in_defaults else [v] + # If filling in defaults, fill in remaining default values + if fill_in_defaults: + for k in keys: + dic[k].append(default_value) + return dic + + +def add_prefix( + root, + prefix, + tags="default", + attribs="default", + exclude=None, +): + """ + Find all element(s) matching the requested @tag, and appends @prefix to all @attributes if they exist. + + Args: + root (ET.Element): Root of the xml element tree to start recursively searching through. + prefix (str): Prefix to add to all specified attributes + tags (str or list of str or set): Tag(s) to search for in this ElementTree. "Default" corresponds to all tags + attribs (str or list of str or set): Element attribute(s) to append prefix to. "Default" corresponds + to all attributes that reference names + exclude (None or function): Filtering function that should take in an ET.Element or a string (attribute) and + return True if we should exclude the given element / attribute from having any prefixes added + """ + # Standardize tags and attributes to be a set + if tags != "default": + tags = {tags} if type(tags) is str else set(tags) + if attribs == "default": + attribs = MUJOCO_NAMED_ATTRIBUTES + attribs = {attribs} if type(attribs) is str else set(attribs) + + # Check the current element for matching conditions + if (tags == "default" or root.tag in tags) and (exclude is None or not exclude(root)): + for attrib in attribs: + v = root.get(attrib, None) + # Only add prefix if the attribute exist, the current attribute doesn't already begin with prefix, + # and the @exclude filter is either None or returns False + if v is not None and not v.startswith(prefix) and (exclude is None or not exclude(v)): + root.set(attrib, prefix + v) + # Continue recursively searching through the element tree + for r in root: + add_prefix(root=r, prefix=prefix, tags=tags, attribs=attribs, exclude=exclude) + + +def add_material(root, naming_prefix="", custom_material=None): + """ + Iterates through all element(s) in @root recursively and adds a material / texture to all visual geoms that don't + already have a material specified. + + Args: + root (ET.Element): Root of the xml element tree to start recursively searching through. + naming_prefix (str): Adds this prefix to all material and texture names + custom_material (None or CustomMaterial): If specified, will add this material to all visual geoms. + Else, will add a default "no-change" material. + + Returns: + 4-tuple: (ET.Element, ET.Element, CustomMaterial, bool) (tex_element, mat_element, material, used) + corresponding to the added material and whether the material was actually used or not. + """ + # Initialize used as False + used = False + # First, make sure material is specified + if custom_material is None: + custom_material = CustomMaterial( + texture=None, + tex_name="default_tex", + mat_name="default_mat", + tex_attrib={ + "type": "cube", + "builtin": "flat", + "width": 100, + "height": 100, + "rgb1": np.ones(3), + "rgb2": np.ones(3), + }, + ) + # Else, check to make sure the custom material begins with the specified prefix and that it's unique + if not custom_material.name.startswith(naming_prefix) and not custom_material.shared: + custom_material.name = naming_prefix + custom_material.name + custom_material.tex_attrib["name"] = naming_prefix + custom_material.tex_attrib["name"] + custom_material.mat_attrib["name"] = naming_prefix + custom_material.mat_attrib["name"] + custom_material.mat_attrib["texture"] = naming_prefix + custom_material.mat_attrib["texture"] + + # Check the current element for matching conditions + if root.tag == "geom" and root.get("group", None) == "1" and root.get("material", None) is None: + # Add a new material attribute to this geom + root.set("material", custom_material.name) + # Set used to True + used = True + # Continue recursively searching through the element tree + for r in root: + _, _, _, _used = add_material(root=r, naming_prefix=naming_prefix, custom_material=custom_material) + # Update used + used = used or _used + # Lastly, return the new texture and material elements + tex_element = new_element(tag="texture", **custom_material.tex_attrib) + mat_element = new_element(tag="material", **custom_material.mat_attrib) + return tex_element, mat_element, custom_material, used + + +def recolor_collision_geoms(root, rgba, exclude=None): + """ + Iteratively searches through all elements starting with @root to find all geoms belonging to group 0 and set + the corresponding rgba value to the specified @rgba argument. Note: also removes any material values for these + elements. + + Args: + root (ET.Element): Root of the xml element tree to start recursively searching through + rgba (4-array): (R, G, B, A) values to assign to all geoms with this group. + exclude (None or function): Filtering function that should take in an ET.Element and + return True if we should exclude the given element / attribute from having its collision geom impacted. + """ + # Check this body + if root.tag == "geom" and root.get("group") in {None, "0"} and (exclude is None or not exclude(root)): + root.set("rgba", array_to_string(rgba)) + root.attrib.pop("material", None) + + # Iterate through all children elements + for r in root: + recolor_collision_geoms(root=r, rgba=rgba, exclude=exclude) + + +def _element_filter(element, parent): + """ + Default element filter to be used in sort_elements. This will filter for the following groups: + + :`'root_body'`: Top-level body element + :`'bodies'`: Any body elements + :`'joints'`: Any joint elements + :`'actuators'`: Any actuator elements + :`'sites'`: Any site elements + :`'sensors'`: Any sensor elements + :`'contact_geoms'`: Any geoms used for collision (as specified by group 0 (default group) geoms) + :`'visual_geoms'`: Any geoms used for visual rendering (as specified by group 1 geoms) + + Args: + element (ET.Element): Current XML element that we are filtering + parent (ET.Element): Parent XML element for the current element + + Returns: + str or None: Assigned filter key for this element. None if no matching filter is found. + """ + # Check for actuator first since this is dependent on the parent element + if parent is not None and parent.tag == "actuator": + return "actuators" + elif element.tag == "joint": + # Make sure this is not a tendon (this should not have a "joint", "joint1", or "joint2" attribute specified) + if element.get("joint") is None and element.get("joint1") is None: + return "joints" + elif element.tag == "body": + # If the parent of this does not have a tag "body", then this is the top-level body element + if parent is None or parent.tag != "body": + return "root_body" + return "bodies" + elif element.tag == "site": + return "sites" + elif element.tag in SENSOR_TYPES: + return "sensors" + elif element.tag == "geom": + # Only get collision and visual geoms (group 0 / None, or 1, respectively) + group = element.get("group") + if group in {None, "0", "1"}: + return "visual_geoms" if group == "1" else "contact_geoms" + else: + # If no condition met, return None + return None + + +def sort_elements(root, parent=None, element_filter=None, _elements_dict=None): + """ + Utility method to iteratively sort all elements based on @tags. This XML ElementTree will be parsed such that + all elements with the same key as returned by @element_filter will be grouped as a list entry in the returned + dictionary. + + Args: + root (ET.Element): Root of the xml element tree to start recursively searching through + parent (ET.Element): Parent of the root node. Default is None (no parent node initially) + element_filter (None or function): Function used to filter the incoming elements. Should take in two + ET.Elements (current_element, parent_element) and return a string filter_key if the element + should be added to the list of values sorted by filter_key, and return None if no value should be added. + If no element_filter is specified, defaults to self._element_filter. + _elements_dict (dict): Dictionary that gets passed to recursive calls. Should not be modified externally by + top-level call. + + Returns: + dict: Filtered key-specific lists of the corresponding elements + """ + # Initialize dictionary and element filter if None is set + if _elements_dict is None: + _elements_dict = {} + if element_filter is None: + element_filter = _element_filter + + # Parse this element + key = element_filter(root, parent) + if key is not None: + # Initialize new entry in the dict if this is the first time encountering this value, otherwise append + if key not in _elements_dict: + _elements_dict[key] = [root] + else: + _elements_dict[key].append(root) + + # Loop through all possible subtrees for this XML recurisvely + for r in root: + _elements_dict = sort_elements( + root=r, parent=root, element_filter=element_filter, _elements_dict=_elements_dict + ) + + return _elements_dict + + +def find_parent(root, child): + """ + Find the parent element of the specified @child node, recurisvely searching through @root. + + Args: + root (ET.Element): Root of the xml element tree to start recursively searching through. + child (ET.Element): Child element whose parent is to be found + + Returns: + None or ET.Element: Matching parent if found, else None + """ + # Iterate through children (DFS), if the correct child element is found, then return the current root as the parent + for r in root: + if r == child: + return root + parent = find_parent(root=r, child=child) + if parent is not None: + return parent + # If we get here, we didn't find anything ): + return None + + +def find_elements(root, tags, attribs=None, return_first=True): + """ + Find all element(s) matching the requested @tag and @attributes. If @return_first is True, then will return the + first element found matching the criteria specified. Otherwise, will return a list of elements that match the + criteria. + + Args: + root (ET.Element): Root of the xml element tree to start recursively searching through. + tags (str or list of str or set): Tag(s) to search for in this ElementTree. + attribs (None or dict of str): Element attribute(s) to check against for a filtered element. A match is + considered found only if all attributes match. Each attribute key should have a corresponding value with + which to compare against. + return_first (bool): Whether to immediately return once the first matching element is found. + + Returns: + None or ET.Element or list of ET.Element: Matching element(s) found. Returns None if there was no match. + """ + # Initialize return value + elements = None if return_first else [] + + # Make sure tags is list + tags = [tags] if type(tags) is str else tags + + # Check the current element for matching conditions + if root.tag in tags: + matching = True + if attribs is not None: + for k, v in attribs.items(): + if root.get(k) != v: + matching = False + break + # If all criteria were matched, add this to the solution (or return immediately if specified) + if matching: + if return_first: + return root + else: + elements.append(root) + # Continue recursively searching through the element tree + for r in root: + if return_first: + elements = find_elements(tags=tags, attribs=attribs, root=r, return_first=return_first) + if elements is not None: + return elements + else: + found_elements = find_elements(tags=tags, attribs=attribs, root=r, return_first=return_first) + pre_elements = deepcopy(elements) + if found_elements: + elements += found_elements if type(found_elements) is list else [found_elements] + + return elements if elements else None + + +def find_elements_by_substring(root, tags, substrings, attribs=None, return_first=False): + """ + Find all element(s) matching the requested @substrings and @attributes. If @return_first is True, then will return the + first element found matching the criteria specified. Otherwise, will return a list of elements that match the + criteria. + + Args: + root (ET.Element): Root of the xml element tree to start recursively searching through. + tags (str or list of str or set): Tag(s) to search for in this ElementTree. + substrings (str or list of str or set): Substring(s) to search for in this ElementTree. + attribs (None or dict of str): Element attribute(s) to check against for a filtered element. A match is + considered found only if all attributes match. Each attribute key should have a corresponding value with + which to compare against. + return_first (bool): Whether to immediately return once the first matching element is found. + + Returns: + None or ET.Element or list of ET.Element: Matching element(s) found. Returns None if there was no match. + """ + # Initialize return value + elements = None if return_first else [] + + # Make sure substrings is list + substrings = [substrings] if type(substrings) is str else substrings + elements = find_elements(root, tags, attribs=attribs, return_first=return_first) + + new_elements = [] + if elements is not None: + for element in elements: + for substring in substrings: + if substring in element.get("name"): + new_elements.append(element) + break + return new_elements if len(new_elements) > 0 else None + + +def find_parent(element, target): + """ + Find the parent element of the target. + """ + for child in element: + if child == target: + return element # Found the parent + parent = find_parent(child, target) + if parent is not None: + return parent + return None + + +def save_sim_model(sim, fname): + """ + Saves the current model xml from @sim at file location @fname. + + Args: + sim (MjSim): XML file to save, in string form + fname (str): Absolute filepath to the location to save the file + """ + with open(fname, "w") as f: + sim.save(file=f, format="xml") + + +def get_ids(sim, elements, element_type="geom", inplace=False): + """ + Grabs the mujoco IDs for each element in @elements, corresponding to the specified @element_type. + + Args: + sim (MjSim): Active mujoco simulation object + elements (str or list or dict): Element(s) to convert into IDs. Note that the return type corresponds to + @elements type, where each element name is replaced with the ID + element_type (str): The type of element to grab ID for. Options are {geom, body, site} + inplace (bool): If False, will create a copy of @elements to prevent overwriting the original data structure + + Returns: + str or list or dict: IDs corresponding to @elements. + """ + if not inplace: + # Copy elements first so we don't write to the underlying object + elements = deepcopy(elements) + # Choose what to do based on elements type + if isinstance(elements, str): + # We simply return the value of this single element + assert element_type in { + "geom", + "body", + "site", + }, f"element_type must be either geom, body, or site. Got: {element_type}" + if element_type == "geom": + elements = sim.model.geom_name2id(elements) + elif element_type == "body": + elements = sim.model.body_name2id(elements) + else: # site + elements = sim.model.site_name2id(elements) + elif isinstance(elements, dict): + # Iterate over each element in dict and recursively repeat + for name, ele in elements: + elements[name] = get_ids(sim=sim, elements=ele, element_type=element_type, inplace=True) + else: # We assume this is an iterable array + assert isinstance(elements, Iterable), "Elements must be iterable for get_id!" + elements = [get_ids(sim=sim, elements=ele, element_type=element_type, inplace=True) for ele in elements] + + return elements diff --git a/third_party/robosuite/robosuite/utils/mjmod.py b/third_party/robosuite/robosuite/utils/mjmod.py new file mode 100644 index 0000000000000000000000000000000000000000..3712e619906214e4221b4937b655b7092aba7611 --- /dev/null +++ b/third_party/robosuite/robosuite/utils/mjmod.py @@ -0,0 +1,1997 @@ +""" +Modder classes used for domain randomization. Largely based off of the mujoco-py +implementation below. + +https://github.com/openai/mujoco-py/blob/1fe312b09ae7365f0dd9d4d0e453f8da59fae0bf/mujoco_py/modder.py +""" + +import copy +import os +from collections import defaultdict + +import numpy as np +from PIL import Image + +import robosuite +import robosuite.utils.transform_utils as trans +from robosuite.utils.binding_utils import MjRenderContextOffscreen + + +class BaseModder: + """ + Base class meant to modify simulation attributes mid-sim. + + Using @random_state ensures that sampling here won't be affected + by sampling that happens outside of the modders. + + Args: + sim (MjSim): simulation object + + random_state (RandomState): instance of np.random.RandomState, specific + seed used to randomize these modifications without impacting other + numpy seeds / randomizations + """ + + def __init__(self, sim, random_state=None): + self.sim = sim + if random_state is None: + # default to global RandomState instance + self.random_state = np.random.mtrand._rand + else: + self.random_state = random_state + + def update_sim(self, sim): + """ + Setter function to update internal sim variable + + Args: + sim (MjSim): MjSim object + """ + self.sim = sim + + @property + def model(self): + """ + Returns: + MjModel: Mujoco sim model + """ + # Available for quick convenience access + return self.sim.model + + +class LightingModder(BaseModder): + """ + Modder to modify lighting within a Mujoco simulation. + + Args: + sim (MjSim): MjSim object + + random_state (RandomState): instance of np.random.RandomState + + light_names (None or list of str): list of lights to use for randomization. If not provided, all + lights in the model are randomized. + + randomize_position (bool): If True, randomizes position of lighting + + randomize_direction (bool): If True, randomizes direction of lighting + + randomize_specular (bool): If True, randomizes specular attribute of lighting + + randomize_ambient (bool): If True, randomizes ambient attribute of lighting + + randomize_diffuse (bool): If True, randomizes diffuse attribute of lighting + + randomize_active (bool): If True, randomizes active nature of lighting + + position_perturbation_size (float): Magnitude of position randomization + + direction_perturbation_size (float): Magnitude of direction randomization + + specular_perturbation_size (float): Magnitude of specular attribute randomization + + ambient_perturbation_size (float): Magnitude of ambient attribute randomization + + diffuse_perturbation_size (float): Magnitude of diffuse attribute randomization + """ + + def __init__( + self, + sim, + random_state=None, + light_names=None, + randomize_position=True, + randomize_direction=True, + randomize_specular=True, + randomize_ambient=True, + randomize_diffuse=True, + randomize_active=True, + position_perturbation_size=0.1, + direction_perturbation_size=0.35, # 20 degrees + specular_perturbation_size=0.1, + ambient_perturbation_size=0.1, + diffuse_perturbation_size=0.1, + ): + super().__init__(sim, random_state=random_state) + + if light_names is None: + light_names = self.sim.model.light_names + self.light_names = light_names + + self.randomize_position = randomize_position + self.randomize_direction = randomize_direction + self.randomize_specular = randomize_specular + self.randomize_ambient = randomize_ambient + self.randomize_diffuse = randomize_diffuse + self.randomize_active = randomize_active + + self.position_perturbation_size = position_perturbation_size + self.direction_perturbation_size = direction_perturbation_size + self.specular_perturbation_size = specular_perturbation_size + self.ambient_perturbation_size = ambient_perturbation_size + self.diffuse_perturbation_size = diffuse_perturbation_size + + self.save_defaults() + + def save_defaults(self): + """ + Uses the current MjSim state and model to save default parameter values. + """ + self._defaults = {k: {} for k in self.light_names} + for name in self.light_names: + self._defaults[name]["pos"] = np.array(self.get_pos(name)) + self._defaults[name]["dir"] = np.array(self.get_dir(name)) + self._defaults[name]["specular"] = np.array(self.get_specular(name)) + self._defaults[name]["ambient"] = np.array(self.get_ambient(name)) + self._defaults[name]["diffuse"] = np.array(self.get_diffuse(name)) + self._defaults[name]["active"] = self.get_active(name) + + def restore_defaults(self): + """ + Reloads the saved parameter values. + """ + for name in self.light_names: + self.set_pos(name, self._defaults[name]["pos"]) + self.set_dir(name, self._defaults[name]["dir"]) + self.set_specular(name, self._defaults[name]["specular"]) + self.set_ambient(name, self._defaults[name]["ambient"]) + self.set_diffuse(name, self._defaults[name]["diffuse"]) + self.set_active(name, self._defaults[name]["active"]) + + def randomize(self): + """ + Randomizes all requested lighting values within the sim + """ + for name in self.light_names: + if self.randomize_position: + self._randomize_position(name) + + if self.randomize_direction: + self._randomize_direction(name) + + if self.randomize_specular: + self._randomize_specular(name) + + if self.randomize_ambient: + self._randomize_ambient(name) + + if self.randomize_diffuse: + self._randomize_diffuse(name) + + if self.randomize_active: + self._randomize_active(name) + + def _randomize_position(self, name): + """ + Helper function to randomize position of a specific light source + + Args: + name (str): Name of the lighting source to randomize for + """ + delta_pos = self.random_state.uniform( + low=-self.position_perturbation_size, + high=self.position_perturbation_size, + size=3, + ) + self.set_pos( + name, + self._defaults[name]["pos"] + delta_pos, + ) + + def _randomize_direction(self, name): + """ + Helper function to randomize direction of a specific light source + + Args: + name (str): Name of the lighting source to randomize for + """ + # sample a small, random axis-angle delta rotation + random_axis, random_angle = trans.random_axis_angle( + angle_limit=self.direction_perturbation_size, random_state=self.random_state + ) + random_delta_rot = trans.quat2mat(trans.axisangle2quat(random_axis * random_angle)) + + # rotate direction by this delta rotation and set the new direction + new_dir = random_delta_rot.dot(self._defaults[name]["dir"]) + self.set_dir( + name, + new_dir, + ) + + def _randomize_specular(self, name): + """ + Helper function to randomize specular attribute of a specific light source + + Args: + name (str): Name of the lighting source to randomize for + """ + delta = self.random_state.uniform( + low=-self.specular_perturbation_size, + high=self.specular_perturbation_size, + size=3, + ) + self.set_specular( + name, + self._defaults[name]["specular"] + delta, + ) + + def _randomize_ambient(self, name): + """ + Helper function to randomize ambient attribute of a specific light source + + Args: + name (str): Name of the lighting source to randomize for + """ + delta = self.random_state.uniform( + low=-self.ambient_perturbation_size, + high=self.ambient_perturbation_size, + size=3, + ) + self.set_ambient( + name, + self._defaults[name]["ambient"] + delta, + ) + + def _randomize_diffuse(self, name): + """ + Helper function to randomize diffuse attribute of a specific light source + + Args: + name (str): Name of the lighting source to randomize for + """ + delta = self.random_state.uniform( + low=-self.diffuse_perturbation_size, + high=self.diffuse_perturbation_size, + size=3, + ) + self.set_diffuse( + name, + self._defaults[name]["diffuse"] + delta, + ) + + def _randomize_active(self, name): + """ + Helper function to randomize active nature of a specific light source + + Args: + name (str): Name of the lighting source to randomize for + """ + active = int(self.random_state.uniform() > 0.5) + self.set_active(name, active) + + def get_pos(self, name): + """ + Grabs position of a specific light source + + Args: + name (str): Name of the lighting source + + Returns: + np.array: (x,y,z) position of lighting source + + Raises: + AssertionError: Invalid light name + """ + lightid = self.get_lightid(name) + assert lightid > -1, "Unkwnown light %s" % name + + return self.model.light_pos[lightid] + + def set_pos(self, name, value): + """ + Sets position of a specific light source + + Args: + name (str): Name of the lighting source + value (np.array): (x,y,z) position to set lighting source to + + Raises: + AssertionError: Invalid light name + AssertionError: Invalid @value + """ + lightid = self.get_lightid(name) + assert lightid > -1, "Unkwnown light %s" % name + + value = list(value) + assert len(value) == 3, "Expected 3-dim value, got %s" % value + + self.model.light_pos[lightid] = value + + def get_dir(self, name): + """ + Grabs direction of a specific light source + + Args: + name (str): Name of the lighting source + + Returns: + np.array: (x,y,z) direction of lighting source + + Raises: + AssertionError: Invalid light name + """ + lightid = self.get_lightid(name) + assert lightid > -1, "Unkwnown light %s" % name + + return self.model.light_dir[lightid] + + def set_dir(self, name, value): + """ + Sets direction of a specific light source + + Args: + name (str): Name of the lighting source + value (np.array): (ax,ay,az) direction to set lighting source to + + Raises: + AssertionError: Invalid light name + AssertionError: Invalid @value + """ + lightid = self.get_lightid(name) + assert lightid > -1, "Unkwnown light %s" % name + + value = list(value) + assert len(value) == 3, "Expected 3-dim value, got %s" % value + + self.model.light_dir[lightid] = value + + def get_active(self, name): + """ + Grabs active nature of a specific light source + + Args: + name (str): Name of the lighting source + + Returns: + int: Whether light source is active (1) or not (0) + + Raises: + AssertionError: Invalid light name + """ + lightid = self.get_lightid(name) + assert lightid > -1, "Unkwnown light %s" % name + + return self.model.light_active[lightid] + + def set_active(self, name, value): + """ + Sets active nature of a specific light source + + Args: + name (str): Name of the lighting source + value (int): Whether light source is active (1) or not (0) + + Raises: + AssertionError: Invalid light name + """ + lightid = self.get_lightid(name) + assert lightid > -1, "Unkwnown light %s" % name + + self.model.light_active[lightid] = value + + def get_specular(self, name): + """ + Grabs specular attribute of a specific light source + + Args: + name (str): Name of the lighting source + + Returns: + np.array: (r,g,b) specular color of lighting source + + Raises: + AssertionError: Invalid light name + """ + lightid = self.get_lightid(name) + assert lightid > -1, "Unkwnown light %s" % name + + return self.model.light_specular[lightid] + + def set_specular(self, name, value): + """ + Sets specular attribute of a specific light source + + Args: + name (str): Name of the lighting source + value (np.array): (r,g,b) specular color to set lighting source to + + Raises: + AssertionError: Invalid light name + AssertionError: Invalid @value + """ + lightid = self.get_lightid(name) + assert lightid > -1, "Unkwnown light %s" % name + + value = list(value) + assert len(value) == 3, "Expected 3-dim value, got %s" % value + + self.model.light_specular[lightid] = value + + def get_ambient(self, name): + """ + Grabs ambient attribute of a specific light source + + Args: + name (str): Name of the lighting source + + Returns: + np.array: (r,g,b) ambient color of lighting source + + Raises: + AssertionError: Invalid light name + """ + lightid = self.get_lightid(name) + assert lightid > -1, "Unkwnown light %s" % name + + return self.model.light_ambient[lightid] + + def set_ambient(self, name, value): + """ + Sets ambient attribute of a specific light source + + Args: + name (str): Name of the lighting source + value (np.array): (r,g,b) ambient color to set lighting source to + + Raises: + AssertionError: Invalid light name + AssertionError: Invalid @value + """ + lightid = self.get_lightid(name) + assert lightid > -1, "Unkwnown light %s" % name + + value = list(value) + assert len(value) == 3, "Expected 3-dim value, got %s" % value + + self.model.light_ambient[lightid] = value + + def get_diffuse(self, name): + """ + Grabs diffuse attribute of a specific light source + + Args: + name (str): Name of the lighting source + + Returns: + np.array: (r,g,b) diffuse color of lighting source + + Raises: + AssertionError: Invalid light name + """ + lightid = self.get_lightid(name) + assert lightid > -1, "Unkwnown light %s" % name + + return self.model.light_diffuse[lightid] + + def set_diffuse(self, name, value): + """ + Sets diffuse attribute of a specific light source + + Args: + name (str): Name of the lighting source + value (np.array): (r,g,b) diffuse color to set lighting source to + + Raises: + AssertionError: Invalid light name + AssertionError: Invalid @value + """ + lightid = self.get_lightid(name) + assert lightid > -1, "Unkwnown light %s" % name + + value = list(value) + assert len(value) == 3, "Expected 3-dim value, got %s" % value + + self.model.light_diffuse[lightid] = value + + def get_lightid(self, name): + """ + Grabs unique id number of a specific light source + + Args: + name (str): Name of the lighting source + + Returns: + int: id of lighting source. -1 if not found + """ + return self.model.light_name2id(name) + + +class CameraModder(BaseModder): + """ + Modder for modifying camera attributes in mujoco sim + + Args: + sim (MjSim): MjSim object + + random_state (None or RandomState): instance of np.random.RandomState + + camera_names (None or list of str): list of camera names to use for randomization. If not provided, + all cameras are used for randomization. + + randomize_position (bool): if True, randomize camera position + + randomize_rotation (bool): if True, randomize camera rotation + + randomize_fovy (bool): if True, randomize camera fovy + + position_perturbation_size (float): size of camera position perturbations to each dimension + + rotation_perturbation_size (float): magnitude of camera rotation perturbations in axis-angle. + Default corresponds to around 5 degrees. + + fovy_perturbation_size (float): magnitude of camera fovy perturbations (corresponds to focusing) + + Raises: + AssertionError: [No randomization selected] + """ + + def __init__( + self, + sim, + random_state=None, + camera_names=None, + randomize_position=True, + randomize_rotation=True, + randomize_fovy=True, + position_perturbation_size=0.01, + rotation_perturbation_size=0.087, + fovy_perturbation_size=5.0, + ): + super().__init__(sim, random_state=random_state) + + assert randomize_position or randomize_rotation or randomize_fovy + + if camera_names is None: + camera_names = self.sim.model.camera_names + self.camera_names = camera_names + + self.randomize_position = randomize_position + self.randomize_rotation = randomize_rotation + self.randomize_fovy = randomize_fovy + + self.position_perturbation_size = position_perturbation_size + self.rotation_perturbation_size = rotation_perturbation_size + self.fovy_perturbation_size = fovy_perturbation_size + + self.save_defaults() + + def save_defaults(self): + """ + Uses the current MjSim state and model to save default parameter values. + """ + self._defaults = {k: {} for k in self.camera_names} + for camera_name in self.camera_names: + self._defaults[camera_name]["pos"] = np.array(self.get_pos(camera_name)) + self._defaults[camera_name]["quat"] = np.array(self.get_quat(camera_name)) + self._defaults[camera_name]["fovy"] = self.get_fovy(camera_name) + + def restore_defaults(self): + """ + Reloads the saved parameter values. + """ + for camera_name in self.camera_names: + self.set_pos(camera_name, self._defaults[camera_name]["pos"]) + self.set_quat(camera_name, self._defaults[camera_name]["quat"]) + self.set_fovy(camera_name, self._defaults[camera_name]["fovy"]) + + def randomize(self): + """ + Randomizes all requested camera values within the sim + """ + for camera_name in self.camera_names: + if self.randomize_position: + self._randomize_position(camera_name) + + if self.randomize_rotation: + self._randomize_rotation(camera_name) + + if self.randomize_fovy: + self._randomize_fovy(camera_name) + + def _randomize_position(self, name): + """ + Helper function to randomize position of a specific camera + + Args: + name (str): Name of the camera to randomize for + """ + delta_pos = self.random_state.uniform( + low=-self.position_perturbation_size, + high=self.position_perturbation_size, + size=3, + ) + self.set_pos( + name, + self._defaults[name]["pos"] + delta_pos, + ) + + def _randomize_rotation(self, name): + """ + Helper function to randomize orientation of a specific camera + + Args: + name (str): Name of the camera to randomize for + """ + # sample a small, random axis-angle delta rotation + random_axis, random_angle = trans.random_axis_angle( + angle_limit=self.rotation_perturbation_size, random_state=self.random_state + ) + random_delta_rot = trans.quat2mat(trans.axisangle2quat(random_axis * random_angle)) + + # compute new rotation and set it + base_rot = trans.quat2mat(trans.convert_quat(self._defaults[name]["quat"], to="xyzw")) + new_rot = random_delta_rot.T.dot(base_rot) + new_quat = trans.convert_quat(trans.mat2quat(new_rot), to="wxyz") + self.set_quat( + name, + new_quat, + ) + + def _randomize_fovy(self, name): + """ + Helper function to randomize fovy of a specific camera + + Args: + name (str): Name of the camera to randomize for + """ + delta_fovy = self.random_state.uniform( + low=-self.fovy_perturbation_size, + high=self.fovy_perturbation_size, + ) + self.set_fovy( + name, + self._defaults[name]["fovy"] + delta_fovy, + ) + + def get_fovy(self, name): + """ + Grabs fovy of a specific camera + + Args: + name (str): Name of the camera + + Returns: + float: vertical field of view of the camera, expressed in degrees + + Raises: + AssertionError: Invalid camera name + """ + camid = self.get_camid(name) + assert camid > -1, "Unknown camera %s" % name + return self.model.cam_fovy[camid] + + def set_fovy(self, name, value): + """ + Sets fovy of a specific camera + + Args: + name (str): Name of the camera + value (float): vertical field of view of the camera, expressed in degrees + + Raises: + AssertionError: Invalid camera name + AssertionError: Invalid value + """ + camid = self.get_camid(name) + assert 0 < value < 180 + assert camid > -1, "Unknown camera %s" % name + self.model.cam_fovy[camid] = value + + def get_quat(self, name): + """ + Grabs orientation of a specific camera + + Args: + name (str): Name of the camera + + Returns: + np.array: (w,x,y,z) orientation of the camera, expressed in quaternions + + Raises: + AssertionError: Invalid camera name + """ + camid = self.get_camid(name) + assert camid > -1, "Unknown camera %s" % name + return self.model.cam_quat[camid] + + def set_quat(self, name, value): + """ + Sets orientation of a specific camera + + Args: + name (str): Name of the camera + value (np.array): (w,x,y,z) orientation of the camera, expressed in quaternions + + Raises: + AssertionError: Invalid camera name + AssertionError: Invalid value + """ + value = list(value) + assert len(value) == 4, "Expectd value of length 4, instead got %s" % value + camid = self.get_camid(name) + assert camid > -1, "Unknown camera %s" % name + self.model.cam_quat[camid] = value + + def get_pos(self, name): + """ + Grabs position of a specific camera + + Args: + name (str): Name of the camera + + Returns: + np.array: (x,y,z) position of the camera + + Raises: + AssertionError: Invalid camera name + """ + camid = self.get_camid(name) + assert camid > -1, "Unknown camera %s" % name + return self.model.cam_pos[camid] + + def set_pos(self, name, value): + """ + Sets position of a specific camera + + Args: + name (str): Name of the camera + value (np.array): (x,y,z) position of the camera + + Raises: + AssertionError: Invalid camera name + AssertionError: Invalid value + """ + value = list(value) + assert len(value) == 3, "Expected value of length 3, instead got %s" % value + camid = self.get_camid(name) + assert camid > -1 + self.model.cam_pos[camid] = value + + def get_camid(self, name): + """ + Grabs unique id number of a specific camera + + Args: + name (str): Name of the camera + + Returns: + int: id of camera. -1 if not found + """ + return self.model.camera_name2id(name) + + +class TextureModder(BaseModder): + """ + Modify textures in model. Example use: + sim = MjSim(...) + modder = TextureModder(sim) + modder.whiten_materials() # ensures materials won't impact colors + modder.set_checker('some_geom', (255, 0, 0), (0, 0, 0)) + modder.rand_all('another_geom') + + Note: in order for the textures to take full effect, you'll need to set + the rgba values for all materials to [1, 1, 1, 1], otherwise the texture + colors will be modulated by the material colors. Call the + `whiten_materials` helper method to set all material colors to white. + + Args: + sim (MjSim): MjSim object + + random_state (RandomState): instance of np.random.RandomState + + geom_names ([string]): list of geom names to use for randomization. If not provided, + all geoms are used for randomization. + + randomize_local (bool): if True, constrain RGB color variations to be close to the + original RGB colors per geom and texture. Otherwise, RGB color values will + be sampled uniformly at random. + + randomize_material (bool): if True, randomizes material properties associated with a + given texture (reflectance, shininess, specular) + + local_rgb_interpolation (float): determines the size of color variations from + the base geom colors when @randomize_local is True. + + local_material_interpolation (float): determines the size of material variations from + the base material when @randomize_local and @randomize_material are both True. + + texture_variations (list of str): a list of texture variation strings. Each string + must be either 'rgb', 'checker', 'noise', or 'gradient' and corresponds to + a specific kind of texture randomization. For each geom that has a material + and texture, a random variation from this list is sampled and applied. + + randomize_skybox (bool): if True, apply texture variations to the skybox as well. + """ + + def __init__( + self, + sim, + random_state=None, + geom_names=None, + randomize_local=False, + randomize_material=False, + local_rgb_interpolation=0.1, + local_material_interpolation=0.2, + texture_variations=("rgb", "checker", "noise", "gradient"), + randomize_skybox=True, + ): + super().__init__(sim, random_state=random_state) + + if geom_names is None: + geom_names = self.sim.model.geom_names + self.geom_names = geom_names + + self.randomize_local = randomize_local + self.randomize_material = randomize_material + self.local_rgb_interpolation = local_rgb_interpolation + self.local_material_interpolation = local_material_interpolation + self.texture_variations = list(texture_variations) + self.randomize_skybox = randomize_skybox + + self._all_texture_variation_callbacks = { + "rgb": self.rand_rgb, + "checker": self.rand_checker, + "noise": self.rand_noise, + "gradient": self.rand_gradient, + } + self._texture_variation_callbacks = { + k: self._all_texture_variation_callbacks[k] for k in self.texture_variations + } + + self.save_defaults() + + def save_defaults(self): + """ + Uses the current MjSim state and model to save default parameter values. + """ + self.textures = [Texture(self.model, i) for i in range(self.model.ntex)] + # self._build_tex_geom_map() + + # save copy of original texture bitmaps + self._default_texture_bitmaps = [np.array(text.bitmap) for text in self.textures] + + # These matrices will be used to rapidly synthesize + # checker pattern bitmaps + self._cache_checker_matrices() + + self._defaults = {k: {} for k in self.geom_names} + if self.randomize_skybox: + self._defaults["skybox"] = {} + for name in self.geom_names: + if self._check_geom_for_texture(name): + # store the texture bitmap for this geom + tex_id = self._name_to_tex_id(name) + self._defaults[name]["texture"] = self._default_texture_bitmaps[tex_id] + # store material properties as well (in tuple (reflectance, shininess, specular) form) + self._defaults[name]["material"] = self.get_material(name) + else: + # store geom color + self._defaults[name]["rgb"] = np.array(self.get_geom_rgb(name)) + + if self.randomize_skybox: + tex_id = self._name_to_tex_id("skybox") + self._defaults["skybox"]["texture"] = self._default_texture_bitmaps[tex_id] + + def restore_defaults(self): + """ + Reloads the saved parameter values. + """ + for name in self.geom_names: + if self._check_geom_for_texture(name): + self.set_texture(name, self._defaults[name]["texture"], perturb=False) + self.set_material(name, self._defaults[name]["material"], perturb=False) + else: + self.set_geom_rgb(name, self._defaults[name]["rgb"]) + + if self.randomize_skybox: + self.set_texture("skybox", self._defaults["skybox"]["texture"], perturb=False) + + def randomize(self): + """ + Overrides mujoco-py implementation to also randomize color + for geoms that have no material. + """ + self.whiten_materials() + for name in self.geom_names: + if self._check_geom_for_texture(name): + # geom has valid texture that can be randomized + self._randomize_texture(name) + # randomize material if requested + if self.randomize_material: + self._randomize_material(name) + else: + # randomize geom color + self._randomize_geom_color(name) + + if self.randomize_skybox: + self._randomize_texture("skybox") + + def _randomize_geom_color(self, name): + """ + Helper function to randomize color of a specific geom + + Args: + name (str): Name of the geom to randomize for + """ + if self.randomize_local: + random_color = self.random_state.uniform(0, 1, size=3) + rgb = (1.0 - self.local_rgb_interpolation) * self._defaults[name][ + "rgb" + ] + self.local_rgb_interpolation * random_color + else: + rgb = self.random_state.uniform(0, 1, size=3) + self.set_geom_rgb(name, rgb) + + def _randomize_texture(self, name): + """ + Helper function to randomize texture of a specific geom + + Args: + name (str): Name of the geom to randomize for + """ + keys = list(self._texture_variation_callbacks.keys()) + choice = keys[self.random_state.randint(len(keys))] + self._texture_variation_callbacks[choice](name) + + def _randomize_material(self, name): + """ + Helper function to randomize material of a specific geom + + Args: + name (str): Name of the geom to randomize for + """ + # Return immediately if this is the skybox + if name == "skybox": + return + # Grab material id + mat_id = self._name_to_mat_id(name) + # Randomize reflectance, shininess, and specular + material = self.random_state.uniform(0, 1, size=3) # (reflectance, shininess, specular) + self.set_material(name, material, perturb=self.randomize_local) + + def rand_checker(self, name): + """ + Generates a random checker pattern for a specific geom + + Args: + name (str): Name of the geom to randomize for + """ + rgb1, rgb2 = self.get_rand_rgb(2) + self.set_checker(name, rgb1, rgb2, perturb=self.randomize_local) + + def rand_gradient(self, name): + """ + Generates a random gradient pattern for a specific geom + + Args: + name (str): Name of the geom to randomize for + """ + rgb1, rgb2 = self.get_rand_rgb(2) + vertical = bool(self.random_state.uniform() > 0.5) + self.set_gradient(name, rgb1, rgb2, vertical=vertical, perturb=self.randomize_local) + + def rand_rgb(self, name): + """ + Generates a random RGB color for a specific geom + + Args: + name (str): Name of the geom to randomize for + """ + rgb = self.get_rand_rgb() + self.set_rgb(name, rgb, perturb=self.randomize_local) + + def rand_noise(self, name): + """ + Generates a random RGB noise pattern for a specific geom + + Args: + name (str): Name of the geom to randomize for + """ + fraction = 0.1 + self.random_state.uniform() * 0.8 + rgb1, rgb2 = self.get_rand_rgb(2) + self.set_noise(name, rgb1, rgb2, fraction, perturb=self.randomize_local) + + def whiten_materials(self): + """ + Extends modder.TextureModder to also whiten geom_rgba + + Helper method for setting all material colors to white, otherwise + the texture modifications won't take full effect. + """ + for name in self.geom_names: + # whiten geom + geom_id = self.model.geom_name2id(name) + self.model.geom_rgba[geom_id, :] = 1.0 + + if self._check_geom_for_texture(name): + # whiten material + mat_id = self.model.geom_matid[geom_id] + self.model.mat_rgba[mat_id, :] = 1.0 + + def get_geom_rgb(self, name): + """ + Grabs rgb color of a specific geom + + Args: + name (str): Name of the geom + + Returns: + np.array: (r,g,b) geom colors + """ + geom_id = self.model.geom_name2id(name) + return self.model.geom_rgba[geom_id, :3] + + def set_geom_rgb(self, name, rgb): + """ + Sets rgb color of a specific geom + + Args: + name (str): Name of the geom + rgb (np.array): (r,g,b) geom colors + """ + geom_id = self.model.geom_name2id(name) + self.model.geom_rgba[geom_id, :3] = rgb + + def get_rand_rgb(self, n=1): + """ + Grabs a batch of random rgb tuple combos + + Args: + n (int): How many sets of rgb tuples to randomly generate + + Returns: + np.array or n-tuple: if n > 1, each tuple entry is a rgb tuple. else, single (r,g,b) array + """ + + def _rand_rgb(): + return np.array(self.random_state.uniform(size=3) * 255, dtype=np.uint8) + + if n == 1: + return _rand_rgb() + else: + return tuple(_rand_rgb() for _ in range(n)) + + def get_texture(self, name): + """ + Grabs texture of a specific geom + + Args: + name (str): Name of the geom + + Returns: + Texture: texture associated with the geom + """ + tex_id = self._name_to_tex_id(name) + texture = self.textures[tex_id] + return texture + + def set_texture(self, name, bitmap, perturb=False): + """ + Sets the bitmap for the texture that corresponds + to geom @name. + + If @perturb is True, then use the computed bitmap + to perturb the default bitmap slightly, instead + of replacing it. + + Args: + name (str): Name of the geom + bitmap (np.array): 3d-array representing rgb pixel-wise values + perturb (bool): Whether to perturb the inputted bitmap or not + """ + bitmap_to_set = self.get_texture(name).bitmap + if perturb: + bitmap = (1.0 - self.local_rgb_interpolation) * self._defaults[name][ + "texture" + ] + self.local_rgb_interpolation * bitmap + bitmap_to_set[:] = bitmap + self.upload_texture(name) + + def get_material(self, name): + """ + Grabs material of a specific geom + + Args: + name (str): Name of the geom + + Returns: + np.array: (reflectance, shininess, specular) material properties associated with the geom + """ + mat_id = self._name_to_mat_id(name) + # Material is in tuple form (reflectance, shininess, specular) + material = np.array( + (self.model.mat_reflectance[mat_id], self.model.mat_shininess[mat_id], self.model.mat_specular[mat_id]) + ) + return material + + def set_material(self, name, material, perturb=False): + """ + Sets the material that corresponds to geom @name. + + If @perturb is True, then use the computed material + to perturb the default material slightly, instead + of replacing it. + + Args: + name (str): Name of the geom + material (np.array): (reflectance, shininess, specular) material properties associated with the geom + perturb (bool): Whether to perturb the inputted material properties or not + """ + mat_id = self._name_to_mat_id(name) + if perturb: + material = (1.0 - self.local_material_interpolation) * self._defaults[name][ + "material" + ] + self.local_material_interpolation * material + self.model.mat_reflectance[mat_id] = material[0] + self.model.mat_shininess[mat_id] = material[1] + self.model.mat_specular[mat_id] = material[2] + + def get_checker_matrices(self, name): + """ + Grabs checker pattern matrix associated with @name. + + Args: + name (str): Name of geom + + Returns: + np.array: 3d-array representing rgb checker pattern + """ + tex_id = self._name_to_tex_id(name) + return self._texture_checker_mats[tex_id] + + def set_checker(self, name, rgb1, rgb2, perturb=False): + """ + Use the two checker matrices to create a checker + pattern from the two colors, and set it as + the texture for geom @name. + + Args: + name (str): Name of geom + rgb1 (3-array): (r,g,b) value for one half of checker pattern + rgb2 (3-array): (r,g,b) value for other half of checker pattern + perturb (bool): Whether to perturb the resulting checker pattern or not + """ + cbd1, cbd2 = self.get_checker_matrices(name) + rgb1 = np.asarray(rgb1).reshape([1, 1, -1]) + rgb2 = np.asarray(rgb2).reshape([1, 1, -1]) + bitmap = rgb1 * cbd1 + rgb2 * cbd2 + + self.set_texture(name, bitmap, perturb=perturb) + + def set_gradient(self, name, rgb1, rgb2, vertical=True, perturb=False): + """ + Creates a linear gradient from rgb1 to rgb2. + + Args: + name (str): Name of geom + rgb1 (3-array): start color + rgb2 (3- array): end color + vertical (bool): if True, the gradient in the positive + y-direction, if False it's in the positive x-direction. + perturb (bool): Whether to perturb the resulting gradient pattern or not + """ + # NOTE: MuJoCo's gradient uses a sigmoid. Here we simplify + # and just use a linear gradient... We could change this + # to just use a tanh-sigmoid if needed. + bitmap = self.get_texture(name).bitmap + h, w = bitmap.shape[:2] + if vertical: + p = np.tile(np.linspace(0, 1, h)[:, None], (1, w)) + else: + p = np.tile(np.linspace(0, 1, w), (h, 1)) + + new_bitmap = np.zeros_like(bitmap) + for i in range(3): + new_bitmap[..., i] = rgb2[i] * p + rgb1[i] * (1.0 - p) + + self.set_texture(name, new_bitmap, perturb=perturb) + + def set_rgb(self, name, rgb, perturb=False): + """ + Just set the texture bitmap for geom @name + to a constant rgb value. + + Args: + name (str): Name of geom + rgb (3-array): desired (r,g,b) color + perturb (bool): Whether to perturb the resulting color pattern or not + """ + bitmap = self.get_texture(name).bitmap + new_bitmap = np.zeros_like(bitmap) + new_bitmap[..., :] = np.asarray(rgb) + + self.set_texture(name, new_bitmap, perturb=perturb) + + def set_noise(self, name, rgb1, rgb2, fraction=0.9, perturb=False): + """ + Sets the texture bitmap for geom @name to a noise pattern + + Args: + name (str): name of geom + rgb1 (3-array): background color + rgb2 (3-array): color of random noise foreground color + fraction (float): fraction of pixels with foreground color + perturb (bool): Whether to perturb the resulting color pattern or not + """ + bitmap = self.get_texture(name).bitmap + h, w = bitmap.shape[:2] + mask = self.random_state.uniform(size=(h, w)) < fraction + + new_bitmap = np.zeros_like(bitmap) + new_bitmap[..., :] = np.asarray(rgb1) + new_bitmap[mask, :] = np.asarray(rgb2) + + self.set_texture(name, new_bitmap, perturb=perturb) + + def upload_texture(self, name, device_id=0): + """ + Uploads the texture to the GPU so it's available in the rendering. + + Args: + name (str): name of geom + """ + texture = self.get_texture(name) + if self.sim._render_context_offscreen is None: + render_context = MjRenderContextOffscreen(self.sim, device_id) + render_context.upload_texture(texture.id) + + def _check_geom_for_texture(self, name): + """ + Helper function to determined if the geom @name has + an assigned material and that the material has + an assigned texture. + + Args: + name (str): name of geom + + Returns: + bool: True if specific geom has both material and texture associated, else False + """ + geom_id = self.model.geom_name2id(name) + mat_id = self.model.geom_matid[geom_id] + if mat_id < 0: + return False + tex_id = self.model.mat_texid[mat_id] + if tex_id < 0: + return False + return True + + def _name_to_tex_id(self, name): + """ + Helper function to get texture id from geom name. + + Args: + name (str): name of geom + + Returns: + int: id of texture associated with geom + + Raises: + AssertionError: [No texture associated with geom] + """ + + # handle skybox separately + if name == "skybox": + skybox_tex_id = -1 + for tex_id in range(self.model.ntex): + skybox_textype = 2 + if self.model.tex_type[tex_id] == skybox_textype: + skybox_tex_id = tex_id + assert skybox_tex_id >= 0 + return skybox_tex_id + + assert self._check_geom_for_texture(name) + geom_id = self.model.geom_name2id(name) + mat_id = self.model.geom_matid[geom_id] + tex_id = self.model.mat_texid[mat_id] + return tex_id + + def _name_to_mat_id(self, name): + """ + Helper function to get material id from geom name. + + Args: + name (str): name of geom + + Returns: + int: id of material associated with geom + + Raises: + ValueError: [No material associated with skybox] + AssertionError: [No material associated with geom] + """ + + # handle skybox separately + if name == "skybox": + raise ValueError("Error: skybox has no material!") + + assert self._check_geom_for_texture(name) + geom_id = self.model.geom_name2id(name) + mat_id = self.model.geom_matid[geom_id] + return mat_id + + def _cache_checker_matrices(self): + """ + Cache two matrices of the form [[1, 0, 1, ...], + [0, 1, 0, ...], + ...] + and [[0, 1, 0, ...], + [1, 0, 1, ...], + ...] + for each texture. To use for fast creation of checkerboard patterns + """ + self._texture_checker_mats = [] + for tex_id in range(self.model.ntex): + texture = self.textures[tex_id] + h, w = texture.bitmap.shape[:2] + self._texture_checker_mats.append(self._make_checker_matrices(h, w)) + + def _make_checker_matrices(self, h, w): + """ + Helper function to quickly generate binary matrices used to create checker patterns + + Args: + h (int): Desired height of matrices + w (int): Desired width of matrices + + Returns: + 2-tuple: + + - (np.array): 2d-array representing first half of checker matrix + - (np.array): 2d-array representing second half of checker matrix + """ + re = np.r_[((w + 1) // 2) * [0, 1]] + ro = np.r_[((w + 1) // 2) * [1, 0]] + cbd1 = np.expand_dims(np.row_stack(((h + 1) // 2) * [re, ro]), -1)[:h, :w] + cbd2 = np.expand_dims(np.row_stack(((h + 1) // 2) * [ro, re]), -1)[:h, :w] + return cbd1, cbd2 + + +# From mjtTexture +MJT_TEXTURE_ENUM = ["2d", "cube", "skybox"] + + +class Texture: + """ + Helper class for operating on the MuJoCo textures. + + Args: + model (MjModel): Mujoco sim model + tex_id (int): id of specific texture in mujoco sim + """ + + __slots__ = ["id", "type", "height", "width", "tex_adr", "tex_rgb"] + + def __init__(self, model, tex_id): + self.id = tex_id + self.type = MJT_TEXTURE_ENUM[model.tex_type[tex_id]] + self.height = model.tex_height[tex_id] + self.width = model.tex_width[tex_id] + self.tex_adr = model.tex_adr[tex_id] + self.tex_rgb = model.tex_rgb + + @property + def bitmap(self): + """ + Grabs color bitmap associated with this texture from the mujoco sim. + + Returns: + np.array: 3d-array representing the rgb texture bitmap + """ + size = self.height * self.width * 3 + data = self.tex_rgb[self.tex_adr : self.tex_adr + size] + return data.reshape((self.height, self.width, 3)) + + +class DynamicsModder(BaseModder): + """ + Modder for various dynamics properties of the mujoco model, such as friction, damping, etc. + This can be used to modify parameters stored in MjModel (ie friction, damping, etc.) as + well as optimizer parameters stored in PyMjOption (i.e.: medium density, viscosity, etc.) + To modify a parameter, use the parameter to be changed as a keyword argument to + self.mod and the new value as the value for that argument. Supports arbitrary many + modifications in a single step. Example use: + sim = MjSim(...) + modder = DynamicsModder(sim) + modder.mod("element1_name", "attr1", new_value1) + modder.mod("element2_name", "attr2", new_value2) + ... + modder.update() + + NOTE: It is necessary to perform modder.update() after performing all modifications to make sure + the changes are propagated + + NOTE: A full list of supported randomizable parameters can be seen by calling modder.dynamics_parameters + + NOTE: When modifying parameters belonging to MjModel.opt (e.g.: density, viscosity), no name should + be specified (set it as None in mod(...)). This is because opt does not have a name attribute + associated with it + + Args: + sim (MjSim): Mujoco sim instance + + random_state (RandomState): instance of np.random.RandomState + + randomize_density (bool): If True, randomizes global medium density + + randomize_viscosity (bool): If True, randomizes global medium viscosity + + density_perturbation_ratio (float): Relative (fraction) magnitude of default density randomization + + viscosity_perturbation_ratio: Relative (fraction) magnitude of default viscosity randomization + + body_names (None or list of str): list of bodies to use for randomization. If not provided, all + bodies in the model are randomized. + + randomize_position (bool): If True, randomizes body positions + + randomize_quaternion (bool): If True, randomizes body quaternions + + randomize_inertia (bool): If True, randomizes body inertias (only applicable for non-zero mass bodies) + + randomize_mass (bool): If True, randomizes body masses (only applicable for non-zero mass bodies) + + position_perturbation_size (float): Magnitude of body position randomization + + quaternion_perturbation_size (float): Magnitude of body quaternion randomization (angle in radians) + + inertia_perturbation_ratio (float): Relative (fraction) magnitude of body inertia randomization + + mass_perturbation_ratio (float): Relative (fraction) magnitude of body mass randomization + + geom_names (None or list of str): list of geoms to use for randomization. If not provided, all + geoms in the model are randomized. + + randomize_friction (bool): If True, randomizes geom frictions + + randomize_solref (bool): If True, randomizes geom solrefs + + randomize_solimp (bool): If True, randomizes geom solimps + + friction_perturbation_ratio (float): Relative (fraction) magnitude of geom friction randomization + + solref_perturbation_ratio (float): Relative (fraction) magnitude of geom solref randomization + + solimp_perturbation_ratio (float): Relative (fraction) magnitude of geom solimp randomization + + joint_names (None or list of str): list of joints to use for randomization. If not provided, all + joints in the model are randomized. + + randomize_stiffness (bool): If True, randomizes joint stiffnesses + + randomize_frictionloss (bool): If True, randomizes joint frictionlosses + + randomize_damping (bool): If True, randomizes joint dampings + + randomize_armature (bool): If True, randomizes joint armatures + + stiffness_perturbation_ratio (float): Relative (fraction) magnitude of joint stiffness randomization + + frictionloss_perturbation_size (float): Magnitude of joint frictionloss randomization + + damping_perturbation_size (float): Magnitude of joint damping randomization + + armature_perturbation_size (float): Magnitude of joint armature randomization + """ + + def __init__( + self, + sim, + random_state=None, + # Opt parameters + randomize_density=True, + randomize_viscosity=True, + density_perturbation_ratio=0.1, + viscosity_perturbation_ratio=0.1, + # Body parameters + body_names=None, + randomize_position=True, + randomize_quaternion=True, + randomize_inertia=True, + randomize_mass=True, + position_perturbation_size=0.02, + quaternion_perturbation_size=0.02, + inertia_perturbation_ratio=0.02, + mass_perturbation_ratio=0.02, + # Geom parameters + geom_names=None, + randomize_friction=True, + randomize_solref=True, + randomize_solimp=True, + friction_perturbation_ratio=0.1, + solref_perturbation_ratio=0.1, + solimp_perturbation_ratio=0.1, + # Joint parameters + joint_names=None, + randomize_stiffness=True, + randomize_frictionloss=True, + randomize_damping=True, + randomize_armature=True, + stiffness_perturbation_ratio=0.1, + frictionloss_perturbation_size=0.05, + damping_perturbation_size=0.01, + armature_perturbation_size=0.01, + ): + super().__init__(sim=sim, random_state=random_state) + + # Setup relevant values + self.dummy_bodies = set() + # Find all bodies that don't have any mass associated with them + for body_name in self.sim.model.body_names: + body_id = self.sim.model.body_name2id(body_name) + if self.sim.model.body_mass[body_id] == 0: + self.dummy_bodies.add(body_name) + + # Get all values to randomize + self.body_names = list(self.sim.model.body_names) if body_names is None else body_names + self.geom_names = list(self.sim.model.geom_names) if geom_names is None else geom_names + self.joint_names = list(self.sim.model.joint_names) if joint_names is None else joint_names + + # Setup randomization settings + # Each dynamics randomization group has its set of randomizable parameters, each of which has + # its own settings ["randomize": whether its actively being randomized, "perturbation": the (potentially) + # relative magnitude of the randomization to use, "type": either "ratio" or "size" (relative or absolute + # perturbations), and "clip": (low, high) values to clip the final perturbed value by] + self.opt_randomizations = { + "density": { + "randomize": randomize_density, + "perturbation": density_perturbation_ratio, + "type": "ratio", + "clip": (0.0, np.inf), + }, + "viscosity": { + "randomize": randomize_viscosity, + "perturbation": viscosity_perturbation_ratio, + "type": "ratio", + "clip": (0.0, np.inf), + }, + } + + self.body_randomizations = { + "position": { + "randomize": randomize_position, + "perturbation": position_perturbation_size, + "type": "size", + "clip": (-np.inf, np.inf), + }, + "quaternion": { + "randomize": randomize_quaternion, + "perturbation": quaternion_perturbation_size, + "type": "size", + "clip": (-np.inf, np.inf), + }, + "inertia": { + "randomize": randomize_inertia, + "perturbation": inertia_perturbation_ratio, + "type": "ratio", + "clip": (0.0, np.inf), + }, + "mass": { + "randomize": randomize_mass, + "perturbation": mass_perturbation_ratio, + "type": "ratio", + "clip": (0.0, np.inf), + }, + } + + self.geom_randomizations = { + "friction": { + "randomize": randomize_friction, + "perturbation": friction_perturbation_ratio, + "type": "ratio", + "clip": (0.0, np.inf), + }, + "solref": { + "randomize": randomize_solref, + "perturbation": solref_perturbation_ratio, + "type": "ratio", + "clip": (0.0, 1.0), + }, + "solimp": { + "randomize": randomize_solimp, + "perturbation": solimp_perturbation_ratio, + "type": "ratio", + "clip": (0.0, np.inf), + }, + } + + self.joint_randomizations = { + "stiffness": { + "randomize": randomize_stiffness, + "perturbation": stiffness_perturbation_ratio, + "type": "ratio", + "clip": (0.0, np.inf), + }, + "frictionloss": { + "randomize": randomize_frictionloss, + "perturbation": frictionloss_perturbation_size, + "type": "size", + "clip": (0.0, np.inf), + }, + "damping": { + "randomize": randomize_damping, + "perturbation": damping_perturbation_size, + "type": "size", + "clip": (0.0, np.inf), + }, + "armature": { + "randomize": randomize_armature, + "perturbation": armature_perturbation_size, + "type": "size", + "clip": (0.0, np.inf), + }, + } + + # Store defaults so we don't loss track of the original (non-perturbed) values + self.opt_defaults = None + self.body_defaults = None + self.geom_defaults = None + self.joint_defaults = None + self.save_defaults() + + def save_defaults(self): + """ + Grabs the current values for all parameters in sim and stores them as default values + """ + self.opt_defaults = { + None: { # no name associated with the opt parameters + "density": self.sim.model.opt.density, + "viscosity": self.sim.model.opt.viscosity, + } + } + + self.body_defaults = {} + for body_name in self.sim.model.body_names: + body_id = self.sim.model.body_name2id(body_name) + self.body_defaults[body_name] = { + "position": np.array(self.sim.model.body_pos[body_id]), + "quaternion": np.array(self.sim.model.body_quat[body_id]), + "inertia": np.array(self.sim.model.body_inertia[body_id]), + "mass": self.sim.model.body_mass[body_id], + } + + self.geom_defaults = {} + for geom_name in self.sim.model.geom_names: + geom_id = self.sim.model.geom_name2id(geom_name) + self.geom_defaults[geom_name] = { + "friction": np.array(self.sim.model.geom_friction[geom_id]), + "solref": np.array(self.sim.model.geom_solref[geom_id]), + "solimp": np.array(self.sim.model.geom_solimp[geom_id]), + } + + self.joint_defaults = {} + for joint_name in self.sim.model.joint_names: + joint_id = self.sim.model.joint_name2id(joint_name) + dof_idx = [i for i, v in enumerate(self.sim.model.dof_jntid) if v == joint_id] + self.joint_defaults[joint_name] = { + "stiffness": self.sim.model.jnt_stiffness[joint_id], + "frictionloss": np.array(self.sim.model.dof_frictionloss[dof_idx]), + "damping": np.array(self.sim.model.dof_damping[dof_idx]), + "armature": np.array(self.sim.model.dof_armature[dof_idx]), + } + + def restore_defaults(self): + """ + Restores the default values curently saved in this modder + """ + # Loop through all defaults and set the default value in sim + for group_defaults in (self.opt_defaults, self.body_defaults, self.geom_defaults, self.joint_defaults): + for name, defaults in group_defaults.items(): + for attr, default_val in defaults.items(): + self.mod(name=name, attr=attr, val=default_val) + + # Make sure changes propagate in sim + self.update() + + def randomize(self): + """ + Randomizes all enabled dynamics parameters in the simulation + """ + for group_defaults, group_randomizations, group_randomize_names in zip( + (self.opt_defaults, self.body_defaults, self.geom_defaults, self.joint_defaults), + (self.opt_randomizations, self.body_randomizations, self.geom_randomizations, self.joint_randomizations), + ([None], self.body_names, self.geom_names, self.joint_names), + ): + for name in group_randomize_names: + # Randomize all parameters associated with this element + for attr, default_val in group_defaults[name].items(): + val = copy.copy(default_val) + settings = group_randomizations[attr] + if settings["randomize"]: + # Randomize accordingly, and clip the final perturbed value + perturbation = np.random.rand() if type(val) in {int, float} else np.random.rand(*val.shape) + perturbation = settings["perturbation"] * (-1 + 2 * perturbation) + val = val + perturbation if settings["type"] == "size" else val * (1.0 + perturbation) + val = np.clip(val, *settings["clip"]) + # Modify this value + self.mod(name=name, attr=attr, val=val) + + # Make sure changes propagate in sim + self.update() + + def update_sim(self, sim): + """ + In addition to super method, update internal default values to match the current values from + (the presumably new) @sim. + + Args: + sim (MjSim): MjSim object + """ + super().update_sim(sim=sim) + self.save_defaults() + + def update(self): + """ + Propagates the changes made up to this point through the simulation + """ + self.sim.forward() + + def mod(self, name, attr, val): + """ + General method to modify dynamics parameter @attr to be new value @val, associated with element @name. + + Args: + name (str): Name of element to modify parameter. This can be a body, geom, or joint name. If modifying + an opt parameter, this should be set to None + attr (str): Name of the dynamics parameter to modify. Valid options are self.dynamics_parameters + val (int or float or n-array): New value(s) to set for the given dynamics parameter. The type of this + argument should match the expected type for the given parameter. + """ + # Make sure specified parameter is valid, and then modify it + assert ( + attr in self.dynamics_parameters + ), "Invalid dynamics parameter specified! Supported parameters are: {};" " requested: {}".format( + self.dynamics_parameters, attr + ) + # Modify the requested parameter (uses a clean way to programmatically call the appropriate method) + getattr(self, f"mod_{attr}")(name, val) + + def mod_density(self, name=None, val=0.0): + """ + Modifies the global medium density of the simulation. + See http://www.mujoco.org/book/XMLreference.html#option for more details. + + Args: + name (str): Name for this element. Should be left as None (opt has no name attribute) + val (float): New density value. + """ + # Make sure inputs are of correct form + assert name is None, "No name should be specified if modding density!" + + # Modify this value + self.sim.model.opt.density = val + + def mod_viscosity(self, name=None, val=0.0): + """ + Modifies the global medium viscosity of the simulation. + See http://www.mujoco.org/book/XMLreference.html#option for more details. + + Args: + name (str): Name for this element. Should be left as None (opt has no name attribute) + val (float): New viscosity value. + """ + # Make sure inputs are of correct form + assert name is None, "No name should be specified if modding density!" + + # Modify this value + self.sim.model.opt.viscosity = val + + def mod_position(self, name, val=(0, 0, 0)): + """ + Modifies the @name's relative body position within the simulation. + See http://www.mujoco.org/book/XMLreference.html#body for more details. + + Args: + name (str): Name for this element. + val (3-array): New (x, y, z) relative position. + """ + # Modify this value + body_id = self.sim.model.body_name2id(name) + self.sim.model.body_pos[body_id] = np.array(val) + + def mod_quaternion(self, name, val=(1, 0, 0, 0)): + """ + Modifies the @name's relative body orientation (quaternion) within the simulation. + See http://www.mujoco.org/book/XMLreference.html#body for more details. + + Note: This method automatically normalizes the inputted value. + + Args: + name (str): Name for this element. + val (4-array): New (w, x, y, z) relative quaternion. + """ + # Normalize the inputted value + val = np.array(val) / np.linalg.norm(val) + # Modify this value + body_id = self.sim.model.body_name2id(name) + self.sim.model.body_quat[body_id] = val + + def mod_inertia(self, name, val): + """ + Modifies the @name's relative body inertia within the simulation. + See http://www.mujoco.org/book/XMLreference.html#body for more details. + + Args: + name (str): Name for this element. + val (3-array): New (ixx, iyy, izz) diagonal values in the inertia matrix. + """ + # Modify this value if it's not a dummy body + if name not in self.dummy_bodies: + body_id = self.sim.model.body_name2id(name) + self.sim.model.body_inertia[body_id] = np.array(val) + + def mod_mass(self, name, val): + """ + Modifies the @name's mass within the simulation. + See http://www.mujoco.org/book/XMLreference.html#body for more details. + + Args: + name (str): Name for this element. + val (float): New mass. + """ + # Modify this value if it's not a dummy body + if name not in self.dummy_bodies: + body_id = self.sim.model.body_name2id(name) + self.sim.model.body_mass[body_id] = val + + def mod_friction(self, name, val): + """ + Modifies the @name's geom friction within the simulation. + See http://www.mujoco.org/book/XMLreference.html#geom for more details. + + Args: + name (str): Name for this element. + val (3-array): New (sliding, torsional, rolling) friction values. + """ + # Modify this value + geom_id = self.sim.model.geom_name2id(name) + self.sim.model.geom_friction[geom_id] = np.array(val) + + def mod_solref(self, name, val): + """ + Modifies the @name's geom contact solver parameters within the simulation. + See http://www.mujoco.org/book/modeling.html#CSolver for more details. + + Args: + name (str): Name for this element. + val (2-array): New (timeconst, dampratio) solref values. + """ + # Modify this value + geom_id = self.sim.model.geom_name2id(name) + self.sim.model.geom_solref[geom_id] = np.array(val) + + def mod_solimp(self, name, val): + """ + Modifies the @name's geom contact solver impedance parameters within the simulation. + See http://www.mujoco.org/book/modeling.html#CSolver for more details. + + Args: + name (str): Name for this element. + val (5-array): New (dmin, dmax, width, midpoint, power) solimp values. + """ + # Modify this value + geom_id = self.sim.model.geom_name2id(name) + self.sim.model.geom_solimp[geom_id] = np.array(val) + + def mod_stiffness(self, name, val): + """ + Modifies the @name's joint stiffness within the simulation. + See http://www.mujoco.org/book/XMLreference.html#joint for more details. + + NOTE: If the stiffness is already at 0, we IGNORE this value since a non-stiff joint (i.e.: free-turning) + joint is fundamentally different than a stiffened joint) + + Args: + name (str): Name for this element. + val (float): New stiffness. + """ + # Modify this value (only if there is stiffness to begin with) + jnt_id = self.sim.model.joint_name2id(name) + if self.sim.model.jnt_stiffness[jnt_id] != 0: + self.sim.model.jnt_stiffness[jnt_id] = val + + def mod_frictionloss(self, name, val): + """ + Modifies the @name's joint frictionloss within the simulation. + See http://www.mujoco.org/book/XMLreference.html#joint for more details. + + NOTE: If the requested joint is a free joint, it will be ignored since it does not + make physical sense to have friction loss associated with this joint (air drag / damping + is already captured implicitly by the medium density / viscosity values) + + Args: + name (str): Name for this element. + val (float): New friction loss. + """ + # Modify this value (only if it's not a free joint) + jnt_id = self.sim.model.joint_name2id(name) + if self.sim.model.jnt_type[jnt_id] != 0: + dof_idx = [i for i, v in enumerate(self.sim.model.dof_jntid) if v == jnt_id] + self.sim.model.dof_frictionloss[dof_idx] = val + + def mod_damping(self, name, val): + """ + Modifies the @name's joint damping within the simulation. + See http://www.mujoco.org/book/XMLreference.html#joint for more details. + + NOTE: If the requested joint is a free joint, it will be ignored since it does not + make physical sense to have damping associated with this joint (air drag / damping + is already captured implicitly by the medium density / viscosity values) + + Args: + name (str): Name for this element. + val (float): New damping. + """ + # Modify this value (only if it's not a free joint) + jnt_id = self.sim.model.joint_name2id(name) + if self.sim.model.jnt_type[jnt_id] != 0: + dof_idx = [i for i, v in enumerate(self.sim.model.dof_jntid) if v == jnt_id] + self.sim.model.dof_damping[dof_idx] = val + + def mod_armature(self, name, val): + """ + Modifies the @name's joint armature within the simulation. + See http://www.mujoco.org/book/XMLreference.html#joint for more details. + + Args: + name (str): Name for this element. + val (float): New armature. + """ + # Modify this value (only if it's not a free joint) + jnt_id = self.sim.model.joint_name2id(name) + if self.sim.model.jnt_type[jnt_id] != 0: + dof_idx = [i for i, v in enumerate(self.sim.model.dof_jntid) if v == jnt_id] + self.sim.model.dof_armature[dof_idx] = val + + @property + def dynamics_parameters(self): + """ + Returns: + set: All dynamics parameters that can be randomized using this modder. + """ + return { + # Opt parameters + "density", + "viscosity", + # Body parameters + "position", + "quaternion", + "inertia", + "mass", + # Geom parameters + "friction", + "solref", + "solimp", + # Joint parameters + "stiffness", + "frictionloss", + "damping", + "armature", + } + + @property + def opt(self): + """ + Returns: + PyMjOption: MjModel sim options + """ + return self.sim.model.opt diff --git a/third_party/robosuite/robosuite/utils/numba.py b/third_party/robosuite/robosuite/utils/numba.py new file mode 100644 index 0000000000000000000000000000000000000000..bd5d8549758e24993abbd72bbf970d90c0e0091b --- /dev/null +++ b/third_party/robosuite/robosuite/utils/numba.py @@ -0,0 +1,12 @@ +""" +Numba utils. +""" +import numba + +import robosuite.macros as macros + + +def jit_decorator(func): + if macros.ENABLE_NUMBA: + return numba.jit(nopython=True, cache=macros.CACHE_NUMBA)(func) + return func diff --git a/third_party/robosuite/robosuite/utils/observables.py b/third_party/robosuite/robosuite/utils/observables.py new file mode 100644 index 0000000000000000000000000000000000000000..2c23e8189bcdc1d84a47efe14299a661e11de468 --- /dev/null +++ b/third_party/robosuite/robosuite/utils/observables.py @@ -0,0 +1,403 @@ +import numpy as np + + +def sensor(modality): + """ + Decorator that should be added to any sensors that will be an observable. + + Decorated functions should have signature: + + any = func(obs_cache) + + Where @obs_cache is a dictionary mapping observable keys to pre-computed values, and @any is either a scalar + or array. This function should also handle the case if obs_cache is either None or an empty dict. + + An example use case is shown below: + + >>> @sensor(modality="proprio") + >>> def joint_pos(obs_cache): + # Always handle case if obs_cache is empty + if not obs_cache: + return np.zeros(7) + # Otherwise, run necessary calculations and return output + ... + out = ... + return out + + Args: + modality (str): Modality for this sensor + + Returns: + function: decorator function + """ + # Define standard decorator (with no args) + def decorator(func): + # Add modality attribute + func.__modality__ = modality + # Return function + return func + + return decorator + + +def create_deterministic_corrupter(corruption, low=-np.inf, high=np.inf): + """ + Creates a deterministic corrupter that applies the same corrupted value to all sensor values + + Args: + corruption (float): Corruption to apply + low (float): Minimum value for output for clipping + high (float): Maximum value for output for clipping + + Returns: + function: corrupter + """ + + def corrupter(inp): + inp = np.array(inp) + return np.clip(inp + corruption, low, high) + + return corrupter + + +def create_uniform_noise_corrupter(min_noise, max_noise, low=-np.inf, high=np.inf): + """ + Creates a corrupter that applies uniform noise to a given input within range @low to @high + + Args: + min_noise (float): Minimum noise to apply + max_noise (float): Maximum noise to apply + low (float): Minimum value for output for clipping + high (float): Maxmimum value for output for clipping + + Returns: + function: corrupter + """ + + def corrupter(inp): + inp = np.array(inp) + noise = (max_noise - min_noise) * np.random.random_sample(inp.shape) + min_noise + return np.clip(inp + noise, low, high) + + return corrupter + + +def create_gaussian_noise_corrupter(mean, std, low=-np.inf, high=np.inf): + """ + Creates a corrupter that applies gaussian noise to a given input with mean @mean and std dev @std + + Args: + mean (float): Mean of the noise to apply + std (float): Standard deviation of the noise to apply + low (float): Minimum value for output for clipping + high (float): Maxmimum value for output for clipping + + Returns: + function: corrupter + """ + + def corrupter(inp): + inp = np.array(inp) + noise = mean + std * np.random.randn(*inp.shape) + return np.clip(inp + noise, low, high) + + return corrupter + + +def create_deterministic_delayer(delay): + """ + Create a deterministic delayer that always returns the same delay value + + Args: + delay (float): Delay value to return + + Returns: + function: delayer + """ + assert delay >= 0, "Inputted delay must be non-negative!" + return lambda: delay + + +def create_uniform_sampled_delayer(min_delay, max_delay): + """ + Creates uniformly sampled delayer, with minimum delay @low and maximum delay @high, both inclusive + + Args: + min_delay (float): Minimum possible delay + max_delay (float): Maxmimum possible delay + + Returns: + function: delayer + """ + assert min(min_delay, max_delay) >= 0, "Inputted delay must be non-negative!" + return lambda: min_delay + (max_delay - min_delay) * np.random.random() + + +def create_gaussian_sampled_delayer(mean, std): + """ + Creates a gaussian sampled delayer, with average delay @mean which varies by standard deviation @std + + Args: + mean (float): Average delay + std (float): Standard deviation of the delay variation + + Returns: + function: delayer + """ + assert mean >= 0, "Inputted mean delay must be non-negative!" + return lambda: max(0.0, int(np.round(mean + std * np.random.randn()))) + + +# Common defaults to use +NO_CORRUPTION = lambda inp: inp +NO_FILTER = lambda inp: inp +NO_DELAY = lambda: 0.0 + + +class Observable: + """ + Base class for all observables -- defines interface for interacting with sensors + + Args: + name (str): Name for this observable + sensor (function with `sensor` decorator): Method to grab raw sensor data for this observable. Should take in a + single dict argument (observation cache if a pre-computed value is required) and return the raw sensor data + for the current timestep. Must handle case if inputted argument is empty ({}), and should have `sensor` + decorator when defined + corrupter (None or function): Method to corrupt the raw sensor data for this observable. Should take in + the output of @sensor and return the same type (corrupted data). If None, results in default no corruption + filter (None or function): Method to filter the outputted reading for this observable. Should take in the output + of @corrupter and return the same type (filtered data). If None, results in default no filter. Note that + this function can also double as an observer, where sampled data is recorded by this function. + delayer (None or function): Method to delay the raw sensor data when polling this observable. Should take in + no arguments and return a float, for the number of seconds to delay the measurement by. If None, results in + default no delayer + sampling_rate (float): Sampling rate for this observable (Hz) + enabled (bool): Whether this sensor is enabled or not. If enabled, this observable's values + are continually computed / updated every time update() is called. + active (bool): Whether this sensor is active or not. If active, this observable's current + observed value is returned from self.obs, otherwise self.obs returns None. + """ + + def __init__( + self, + name, + sensor, + corrupter=None, + filter=None, + delayer=None, + sampling_rate=20, + enabled=True, + active=True, + ): + # Set all internal variables and methods + self.name = name + self._sensor = sensor + self._corrupter = corrupter if corrupter is not None else NO_CORRUPTION + self._filter = filter if filter is not None else NO_FILTER + self._delayer = delayer if delayer is not None else NO_DELAY + self._sampling_timestep = 1.0 / sampling_rate + self._enabled = enabled + self._active = active + self._is_number = False # filled in during sensor check call + self._data_shape = (1,) # filled in during sensor check call + + # Make sure sensor is working + self._check_sensor_validity() + + # These values will be modified during update() call + self._time_since_last_sample = 0.0 # seconds + self._current_delay = self._delayer() # seconds + self._current_observed_value = 0 if self._is_number else np.zeros(self._data_shape) + self._sampled = False + + def update(self, timestep, obs_cache, force=False): + """ + Updates internal values for this observable, if enabled. + + Args: + timestep (float): Amount of simulation time (in sec) that has passed since last call. + obs_cache (dict): Observation cache mapping observable names to pre-computed values to pass to sensor. This + will be updated in-place during this call. + force (bool): If True, will force the observable to update its internal value to the newest value. + """ + if self._enabled: + # Increment internal time counter + self._time_since_last_sample += timestep + + # If the delayed sampling time has been passed and we haven't sampled yet for this sampling period, + # we should grab a new measurement + if ( + not self._sampled and self._sampling_timestep - self._current_delay >= self._time_since_last_sample + ) or force: + # Get newest raw value, corrupt it, filter it, and set it as our current observed value + obs = np.array(self._filter(self._corrupter(self._sensor(obs_cache)))) + self._current_observed_value = obs[0] if len(obs.shape) == 1 and obs.shape[0] == 1 else obs + # Update cache entry as well + obs_cache[self.name] = np.array(self._current_observed_value) + # Toggle sampled and re-sample next time delay + self._sampled = True + self._current_delay = self._delayer() + + # If our total time since last sample has surpassed our sampling timestep, + # then we reset our timer and sampled flag + if self._time_since_last_sample >= self._sampling_timestep: + if not self._sampled: + # If we still haven't sampled yet, sample immediately and warn user that sampling rate is too low + print( + f"Warning: sampling rate for observable {self.name} is either too low or delay is too high. " + f"Please adjust one (or both)" + ) + # Get newest raw value, corrupt it, filter it, and set it as our current observed value + obs = np.array(self._filter(self._corrupter(self._sensor(obs_cache)))) + self._current_observed_value = obs[0] if len(obs.shape) == 1 and obs.shape[0] == 1 else obs + # Update cache entry as well + obs_cache[self.name] = np.array(self._current_observed_value) + # Re-sample next time delay + self._current_delay = self._delayer() + self._time_since_last_sample %= self._sampling_timestep + self._sampled = False + + def reset(self): + """ + Resets this observable's internal values (but does not reset its sensor, corrupter, delayer, or filter) + """ + self._time_since_last_sample = 0.0 + self._current_delay = self._delayer() + self._current_observed_value = 0 if self._is_number else np.zeros(self._data_shape) + + def is_enabled(self): + """ + Determines whether observable is enabled or not. This observable is considered enabled if its values + are being continually computed / updated during each update() call. + + Returns: + bool: True if this observable is enabled + """ + return self._enabled + + def is_active(self): + """ + Determines whether observable is active or not. This observable is considered active if its current observation + value is being returned in self.obs. + + Returns: + bool: True if this observable is active + """ + return self._active + + def set_enabled(self, enabled): + """ + Sets whether this observable is enabled or not. If enabled, this observable's values + are continually computed / updated every time update() is called. + + Args: + enabled (bool): True if this observable should be enabled + """ + self._enabled = enabled + # Reset values + self.reset() + + def set_active(self, active): + """ + Sets whether this observable is active or not. If active, this observable's current + observed value is returned from self.obs, otherwise self.obs returns None. + + Args: + active (bool): True if this observable should be active + """ + self._active = active + + def set_sensor(self, sensor): + """ + Sets the sensor for this observable. + + Args: + sensor (function with sensor decorator): Method to grab raw sensor data for this observable. Should take in + a single dict argument (observation cache if a pre-computed value is required) and return the raw + sensor data for the current timestep. Must handle case if inputted argument is empty ({}), and should + have `sensor` decorator when defined + """ + self._sensor = sensor + self._check_sensor_validity() + + def set_corrupter(self, corrupter): + """ + Sets the corrupter for this observable. + + Args: + corrupter (None or function): Method to corrupt the raw sensor data for this observable. Should take in + the output of self.sensor and return the same type (corrupted data). + If None, results in default no corruption + """ + self._corrupter = corrupter if corrupter is not None else NO_CORRUPTION + + def set_filter(self, filter): + """ + Sets the filter for this observable. Note that this function can also double as an observer, where sampled + data is recorded by this function. + + Args: + filter (None or function): Method to filter the outputted reading for this observable. Should take in + the output of @corrupter and return the same type (filtered data). + If None, results in default no filter + """ + self._filter = filter if filter is not None else NO_FILTER + + def set_delayer(self, delayer): + """ + Sets the delayer for this observable. + + Args: + delayer (None or function): Method to delay the raw sensor data when polling this observable. Should take + in no arguments and return a float, for the number of seconds to delay the measurement by. + If None, results in default no filter + """ + self._delayer = delayer if delayer is not None else NO_DELAY + + def set_sampling_rate(self, rate): + """ + Sets the sampling rate for this observable. + + Args: + rate (int): New sampling rate for this observable (Hz) + """ + self._sampling_timestep = 1.0 / rate + + def _check_sensor_validity(self): + """ + Internal function that checks the validity of this observable's sensor. It does the following: + + - Asserts that the inputted sensor has its __modality__ attribute defined from the sensor decorator + - Asserts that the inputted sensor can handle the empty dict {} arg case + - Updates the corresponding name, and data-types for this sensor + """ + try: + _ = self.modality + self._data_shape = np.array(self._sensor({})).shape + self._is_number = len(self._data_shape) == 1 and self._data_shape[0] == 1 + except Exception as e: + from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER + + ROBOSUITE_DEFAULT_LOGGER.error(e) + raise ValueError("Current sensor for observable {} is invalid.".format(self.name)) + + @property + def obs(self): + """ + Current observation from this observable + + Returns: + None or float or np.array: If active, current observed value from this observable. Otherwise, None + """ + return self._current_observed_value if self._active else None + + @property + def modality(self): + """ + Modality of this sensor + + Returns: + str: Modality name for this observable + """ + return self._sensor.__modality__ diff --git a/third_party/robosuite/robosuite/utils/opencv_renderer.py b/third_party/robosuite/robosuite/utils/opencv_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..c6d6386b75870248519a12a18e62c233e256c246 --- /dev/null +++ b/third_party/robosuite/robosuite/utils/opencv_renderer.py @@ -0,0 +1,50 @@ +""" +opencv renderer class. +""" +import cv2 +import numpy as np + + +class OpenCVRenderer: + def __init__(self, sim): + # TODO: update this appropriately - need to get screen dimensions + self.width = 1280 + self.height = 800 + + self.sim = sim + self.camera_name = self.sim.model.camera_id2name(0) + + self.keypress_callback = None + + def set_camera(self, camera_id): + """ + Set the camera view to the specified camera ID. + Args: + camera_id (int): id of the camera to set the current viewer to + """ + self.camera_name = self.sim.model.camera_id2name(camera_id) + + def render(self): + # get frame with offscreen renderer (assumes that the renderer already exists) + im = self.sim.render(camera_name=self.camera_name, height=self.height, width=self.width)[..., ::-1] + + # write frame to window + im = np.flip(im, axis=0) + cv2.imshow("offscreen render", im) + key = cv2.waitKey(1) + if self.keypress_callback: + self.keypress_callback(key) + + def add_keypress_callback(self, keypress_callback): + self.keypress_callback = keypress_callback + + def close(self): + """ + Any cleanup to close renderer. + """ + + # NOTE: assume that @sim will get cleaned up outside the renderer - just delete the reference + self.sim = None + + # close window + cv2.destroyAllWindows() diff --git a/third_party/robosuite/robosuite/utils/placement_samplers.py b/third_party/robosuite/robosuite/utils/placement_samplers.py new file mode 100644 index 0000000000000000000000000000000000000000..0bd8bb99712d8dac51ca5acf90261ca21cba60c4 --- /dev/null +++ b/third_party/robosuite/robosuite/utils/placement_samplers.py @@ -0,0 +1,441 @@ +import collections +from copy import copy + +import numpy as np + +from robosuite.models.objects import MujocoObject +from robosuite.utils import RandomizationError +from robosuite.utils.transform_utils import quat_multiply + + +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), + z_offset=0.0, + ): + # 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.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 + + +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. + """ + + 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, + reference_pos=(0, 0, 0), + z_offset=0.0, + ): + self.x_range = x_range + self.y_range = y_range + self.rotation = rotation + self.rotation_axis = rotation_axis + + 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, + z_offset=z_offset, + ) + + def _sample_x(self, object_horizontal_radius): + """ + Samples the x location for a given object + + Args: + object_horizontal_radius (float): Radius of the object currently being sampled for + + Returns: + float: sampled x position + """ + minimum, maximum = self.x_range + if self.ensure_object_boundary_in_range: + minimum += object_horizontal_radius + maximum -= object_horizontal_radius + return np.random.uniform(high=maximum, low=minimum) + + def _sample_y(self, object_horizontal_radius): + """ + Samples the y location for a given object + + Args: + object_horizontal_radius (float): Radius of the object currently being sampled for + + Returns: + float: sampled y position + """ + minimum, maximum = self.y_range + if self.ensure_object_boundary_in_range: + minimum += object_horizontal_radius + maximum -= object_horizontal_radius + return np.random.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 = np.random.uniform(high=2 * np.pi, low=0) + elif isinstance(self.rotation, collections.abc.Iterable): + rot_angle = np.random.uniform(high=max(self.rotation), low=min(self.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, fixtures=None, reference=None, on_top=True): + """ + Uniformly sample relative to this sampler's reference_pos or @reference (if specified). + + 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. 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 fixtures is None else copy(fixtures) + 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])) + 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) + + horizontal_radius = obj.horizontal_radius + bottom_offset = obj.bottom_offset + success = False + for i in range(5000): # 5000 retries + object_x = self._sample_x(horizontal_radius) + base_offset[0] + object_y = self._sample_y(horizontal_radius) + base_offset[1] + object_z = self.z_offset + base_offset[2] + if on_top: + object_z -= bottom_offset[-1] + + # objects cannot overlap + location_valid = True + if self.ensure_valid_placement: + for (x, y, z), _, other_obj in placed_objects.values(): + if ( + np.linalg.norm((object_x - x, object_y - y)) + <= other_obj.horizontal_radius + horizontal_radius + ) and (object_z - z <= other_obj.top_offset[-1] - bottom_offset[-1]): + location_valid = False + break + + if location_valid: + # 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) + + # 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("Cannot place all objects ):") + + 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): + # Samplers / args will be filled in later + self.samplers = collections.OrderedDict() + self.sample_args = collections.OrderedDict() + + super().__init__(name=name) + + def append_sampler(self, sampler, sample_args=None): + """ + 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) + + 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 + + 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, + ) + 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, fixtures=None, reference=None, on_top=True): + """ + Sample from each placement initializer sequentially, in the order + that they were appended. + + 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. 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 fixtures is None else copy(fixtures) + + # 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 + new_placements = sampler.sample(fixtures=placed_objects, **s_args) + # Update placements + placed_objects.update(new_placements) + + return placed_objects diff --git a/third_party/robosuite/robosuite/utils/robot_composition_utils.py b/third_party/robosuite/robosuite/utils/robot_composition_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cb757f2eff252f058afb9436f2b514abccf14a90 --- /dev/null +++ b/third_party/robosuite/robosuite/utils/robot_composition_utils.py @@ -0,0 +1,67 @@ +from typing import List, Optional, Tuple, Union + +from robosuite.models.robots.robot_model import REGISTERED_ROBOTS, RobotModel +from robosuite.robots import register_robot_class +from robosuite.utils.log_utils import ROBOSUITE_DEFAULT_LOGGER +from robosuite.utils.robot_utils import check_bimanual + +BASE_TARGET_MAPPING = { + "RethinkMount": "FixedBaseRobot", + "RethinkMinimalMount": "FixedBaseRobot", + "NullMount": "FixedBaseRobot", + "OmronMobileBase": "WheeledRobot", + "NullMobileBase": "WheeledRobot", + "NoActuationBase": "LeggedRobot", + "Spot": "LeggedRobot", + "SpotFloating": "LeggedRobot", +} + + +def get_target_type(base) -> str: + """ + Returns the target type of the robot + """ + return BASE_TARGET_MAPPING[base] + + +def create_composite_robot( + name: str, robot: str, base: Optional[str] = None, grippers: Optional[Union[str, List[str], Tuple[str]]] = None +) -> RobotModel: + """ + Factory function to create a composite robot + """ + + bimanual_robot = check_bimanual(robot) + grippers = grippers if type(grippers) == list or type(grippers) == tuple else [grippers] + + # perform checks and issues warning if necessary + if bimanual_robot and len(grippers) == 1: + grippers = grippers + grippers + if not bimanual_robot and len(grippers) == 2: + ROBOSUITE_DEFAULT_LOGGER.warning( + f"Grippers {grippers} supplied for single gripper robot.\ + Using gripper {grippers[0]}." + ) + if not base: + base = REGISTERED_ROBOTS[robot]().default_base + if robot in ["Tiago", "GR1"] and base: + ROBOSUITE_DEFAULT_LOGGER.warning(f"Defined custom base when using {robot} robot. Ignoring base.") + if robot in ["Tiago"]: + base = "NullMobileBase" + elif robot == "GR1": + base = "NoActuationBase" + + target_type = get_target_type(base) + + class_dict = { + "default_base": property(lambda self: base), + "default_arms": property(lambda self: {"right": robot}), + "default_gripper": property( + lambda self: {"right": grippers[0], "left": grippers[1]} if bimanual_robot else {"right": grippers[0]} + ), + } + + CustomCompositeRobotClass = type(name, (REGISTERED_ROBOTS[robot],), class_dict) + register_robot_class(target_type)(CustomCompositeRobotClass) + + return CustomCompositeRobotClass diff --git a/third_party/robosuite/robosuite/utils/robot_utils.py b/third_party/robosuite/robosuite/utils/robot_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a86d0fbc1d47d5138cdc27242590951a1e5b81ab --- /dev/null +++ b/third_party/robosuite/robosuite/utils/robot_utils.py @@ -0,0 +1,17 @@ +# Utilities functions for working with robots + +from robosuite.models.robots.robot_model import REGISTERED_ROBOTS + + +def check_bimanual(robot_name): + """ + Utility function that returns whether the inputted robot_name is a bimanual robot or not + + Args: + robot_name (str): Name of the robot to check + + Returns: + bool: True if the inputted robot is a bimanual robot + """ + robot = REGISTERED_ROBOTS[robot_name]() + return robot.arm_type == "bimanual" diff --git a/third_party/robosuite/robosuite/utils/sim_utils.py b/third_party/robosuite/robosuite/utils/sim_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5452add1a7ee82b947e81c76bd43698ff128047d --- /dev/null +++ b/third_party/robosuite/robosuite/utils/sim_utils.py @@ -0,0 +1,67 @@ +""" +Collection of useful simulation utilities +""" + +from robosuite.models.base import MujocoModel + + +def check_contact(sim, geoms_1, geoms_2=None): + """ + Finds contact between two geom groups. + Args: + sim (MjSim): Current simulation object + 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. + """ + # Check if either geoms_1 or geoms_2 is a string, convert to list if so + if type(geoms_1) is str: + geoms_1 = [geoms_1] + elif isinstance(geoms_1, MujocoModel): + geoms_1 = geoms_1.contact_geoms + if type(geoms_2) is str: + geoms_2 = [geoms_2] + elif isinstance(geoms_2, MujocoModel): + geoms_2 = geoms_2.contact_geoms + for i in range(sim.data.ncon): + contact = sim.data.contact[i] + # check contact geom in geoms + c1_in_g1 = sim.model.geom_id2name(contact.geom1) in geoms_1 + c2_in_g2 = sim.model.geom_id2name(contact.geom2) in geoms_2 if geoms_2 is not None else True + # check contact geom in geoms (flipped) + c2_in_g1 = sim.model.geom_id2name(contact.geom2) in geoms_1 + c1_in_g2 = sim.model.geom_id2name(contact.geom1) in geoms_2 if geoms_2 is not None else True + if (c1_in_g1 and c2_in_g2) or (c1_in_g2 and c2_in_g1): + return True + return False + + +def get_contacts(sim, 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: + sim (MjSim): Current simulation model + model (MujocoModel): Model to check contacts for. + Returns: + set: Unique geoms that are actively in contact with this model. + Raises: + AssertionError: [Invalid input type] + """ + # Make sure model is MujocoModel type + assert isinstance(model, MujocoModel), "Inputted model must be of type MujocoModel; got type {} instead!".format( + type(model) + ) + contact_set = set() + for contact in sim.data.contact[: sim.data.ncon]: + # check contact geom in geoms; add to contact set if match is found + g1, g2 = sim.model.geom_id2name(contact.geom1), sim.model.geom_id2name(contact.geom2) + if g1 in model.contact_geoms and g2 not in model.contact_geoms: + contact_set.add(g2) + elif g2 in model.contact_geoms and g1 not in model.contact_geoms: + contact_set.add(g1) + return contact_set diff --git a/third_party/robosuite/robosuite/utils/traj_utils.py b/third_party/robosuite/robosuite/utils/traj_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bee9ab38785fec241acd8f9f4337ad714b44b291 --- /dev/null +++ b/third_party/robosuite/robosuite/utils/traj_utils.py @@ -0,0 +1,155 @@ +import abc + +import numpy as np + +import robosuite.utils.transform_utils as T + + +# Classes for trajectory interpolation +class Interpolator(object, metaclass=abc.ABCMeta): + """ + General interpolator interface. + """ + + @abc.abstractmethod + def get_interpolated_goal(self): + """ + Provides the next step in interpolation given the remaining steps. + + Returns: + np.array: Next interpolated step + """ + raise NotImplementedError + + +class LinearInterpolator(Interpolator): + """ + Simple class for implementing a linear interpolator. + + Abstracted to interpolate n-dimensions + + Args: + ndim (int): Number of dimensions to interpolate + + controller_freq (float): Frequency (Hz) of the controller + + policy_freq (float): Frequency (Hz) of the policy model + + ramp_ratio (float): Percentage of interpolation timesteps across which we will interpolate to a goal position. + + :Note: Num total interpolation steps will be equal to np.floor(ramp_ratio * controller_freq / policy_freq) + i.e.: how many controller steps we get per action space update + + ori_interpolate (None or str): If set, assumes that we are interpolating angles (orientation) + Specified string determines assumed type of input: + + `'euler'`: Euler orientation inputs + `'quat'`: Quaternion inputs + """ + + def __init__( + self, + ndim, + controller_freq, + policy_freq, + ramp_ratio=0.2, + use_delta_goal=False, + ori_interpolate=None, + ): + self.dim = ndim # Number of dimensions to interpolate + self.ori_interpolate = ori_interpolate # Whether this is interpolating orientation or not + self.order = 1 # Order of the interpolator (1 = linear) + self.step = 0 # Current step of the interpolator + self.total_steps = np.ceil( + ramp_ratio * controller_freq / policy_freq + ) # Total num steps per interpolator action + self.use_delta_goal = use_delta_goal # Whether to use delta or absolute goals (currently + # not implemented yet- TODO) + self.set_states(dim=ndim, ori=ori_interpolate) + + def set_states(self, dim=None, ori=None): + """ + Updates self.dim and self.ori_interpolate. + + Initializes self.start and self.goal with correct dimensions. + + Args: + ndim (None or int): Number of dimensions to interpolate + + ori_interpolate (None or str): If set, assumes that we are interpolating angles (orientation) + Specified string determines assumed type of input: + + `'euler'`: Euler orientation inputs + `'quat'`: Quaternion inputs + """ + # Update self.dim and self.ori_interpolate + self.dim = dim if dim is not None else self.dim + self.ori_interpolate = ori if ori is not None else self.ori_interpolate + + # Set start and goal states + if self.ori_interpolate is not None: + if self.ori_interpolate == "euler": + self.start = np.zeros(3) + else: # quaternions + self.start = np.array((0, 0, 0, 1)) + else: + self.start = np.zeros(self.dim) + self.goal = np.array(self.start) + + def set_goal(self, goal): + """ + Takes a requested (absolute) goal and updates internal parameters for next interpolation step + + Args: + np.array: Requested goal (absolute value). Should be same dimension as self.dim + """ + # First, check to make sure requested goal shape is the same as self.dim + if goal.shape[0] != self.dim: + print("Requested goal: {}".format(goal)) + raise ValueError( + "LinearInterpolator: Input size wrong for goal; got {}, needs to be {}!".format(goal.shape[0], self.dim) + ) + + # Update start and goal + self.start = np.array(self.goal) + self.goal = np.array(goal) + + # Reset interpolation steps + self.step = 0 + + def get_interpolated_goal(self): + """ + Provides the next step in interpolation given the remaining steps. + + NOTE: If this interpolator is for orientation, it is assumed to be receiving either euler angles or quaternions + + Returns: + np.array: Next position in the interpolated trajectory + """ + # Grab start position + x = np.array(self.start) + # Calculate the desired next step based on remaining interpolation steps + if self.ori_interpolate is not None: + # This is an orientation interpolation, so we interpolate linearly around a sphere instead + goal = np.array(self.goal) + if self.ori_interpolate == "euler": + # this is assumed to be euler angles (x,y,z), so we need to first map to quat + x = T.mat2quat(T.euler2mat(x)) + goal = T.mat2quat(T.euler2mat(self.goal)) + + # Interpolate to the next sequence + x_current = T.quat_slerp(x, goal, fraction=(self.step + 1) / self.total_steps) + if self.ori_interpolate == "euler": + # Map back to euler + x_current = T.mat2euler(T.quat2mat(x_current)) + else: + # This is a normal interpolation + dx = (self.goal - x) / (self.total_steps - self.step) + x_current = x + dx + + # Increment step if there's still steps remaining based on ramp ratio + if self.step < self.total_steps - 1: + self.step += 1 + + # Return the new interpolated step + return x_current diff --git a/third_party/robosuite/robosuite/utils/transform_utils.py b/third_party/robosuite/robosuite/utils/transform_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a5018bc9a2f8c36e71b3c335d9c8ce23601e973b --- /dev/null +++ b/third_party/robosuite/robosuite/utils/transform_utils.py @@ -0,0 +1,947 @@ +""" +Utility functions of matrix and vector transformations. + +NOTE: convention for quaternions is (x, y, z, w) +""" + +import math + +import numpy as np + +from robosuite.utils.numba import jit_decorator + +PI = np.pi +EPS = np.finfo(float).eps * 4.0 + +# axis sequences for Euler angles +_NEXT_AXIS = [1, 2, 0, 1] + +# map axes strings to/from tuples of inner axis, parity, repetition, frame +_AXES2TUPLE = { + "sxyz": (0, 0, 0, 0), + "sxyx": (0, 0, 1, 0), + "sxzy": (0, 1, 0, 0), + "sxzx": (0, 1, 1, 0), + "syzx": (1, 0, 0, 0), + "syzy": (1, 0, 1, 0), + "syxz": (1, 1, 0, 0), + "syxy": (1, 1, 1, 0), + "szxy": (2, 0, 0, 0), + "szxz": (2, 0, 1, 0), + "szyx": (2, 1, 0, 0), + "szyz": (2, 1, 1, 0), + "rzyx": (0, 0, 0, 1), + "rxyx": (0, 0, 1, 1), + "ryzx": (0, 1, 0, 1), + "rxzx": (0, 1, 1, 1), + "rxzy": (1, 0, 0, 1), + "ryzy": (1, 0, 1, 1), + "rzxy": (1, 1, 0, 1), + "ryxy": (1, 1, 1, 1), + "ryxz": (2, 0, 0, 1), + "rzxz": (2, 0, 1, 1), + "rxyz": (2, 1, 0, 1), + "rzyz": (2, 1, 1, 1), +} + +_TUPLE2AXES = dict((v, k) for k, v in _AXES2TUPLE.items()) + + +def convert_quat(q, to="xyzw"): + """ + Converts quaternion from one convention to another. + The convention to convert TO is specified as an optional argument. + If to == 'xyzw', then the input is in 'wxyz' format, and vice-versa. + + Args: + q (np.array): a 4-dim array corresponding to a quaternion + to (str): either 'xyzw' or 'wxyz', determining which convention to convert to. + """ + if to == "xyzw": + return q[[1, 2, 3, 0]] + if to == "wxyz": + return q[[3, 0, 1, 2]] + raise Exception("convert_quat: choose a valid `to` argument (xyzw or wxyz)") + + +def quat_multiply(quaternion1, quaternion0): + """ + Return multiplication of two quaternions (q1 * q0). + + E.g.: + >>> q = quat_multiply([1, -2, 3, 4], [-5, 6, 7, 8]) + >>> np.allclose(q, [-44, -14, 48, 28]) + True + + Args: + quaternion1 (np.array): (x,y,z,w) quaternion + quaternion0 (np.array): (x,y,z,w) quaternion + + Returns: + np.array: (x,y,z,w) multiplied quaternion + """ + x0, y0, z0, w0 = quaternion0 + x1, y1, z1, w1 = quaternion1 + return np.array( + ( + x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0, + -x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0, + x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0, + -x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0, + ), + dtype=np.float32, + ) + + +def quat_conjugate(quaternion): + """ + Return conjugate of quaternion. + + E.g.: + >>> q0 = random_quaternion() + >>> q1 = quat_conjugate(q0) + >>> q1[3] == q0[3] and all(q1[:3] == -q0[:3]) + True + + Args: + quaternion (np.array): (x,y,z,w) quaternion + + Returns: + np.array: (x,y,z,w) quaternion conjugate + """ + return np.array( + (-quaternion[0], -quaternion[1], -quaternion[2], quaternion[3]), + dtype=np.float32, + ) + + +def quat_inverse(quaternion): + """ + Return inverse of quaternion. + + E.g.: + >>> q0 = random_quaternion() + >>> q1 = quat_inverse(q0) + >>> np.allclose(quat_multiply(q0, q1), [0, 0, 0, 1]) + True + + Args: + quaternion (np.array): (x,y,z,w) quaternion + + Returns: + np.array: (x,y,z,w) quaternion inverse + """ + return quat_conjugate(quaternion) / np.dot(quaternion, quaternion) + + +def quat_distance(quaternion1, quaternion0): + """ + Returns distance between two quaternions, such that distance * quaternion0 = quaternion1 + + Args: + quaternion1 (np.array): (x,y,z,w) quaternion + quaternion0 (np.array): (x,y,z,w) quaternion + + Returns: + np.array: (x,y,z,w) quaternion distance + """ + return quat_multiply(quaternion1, quat_inverse(quaternion0)) + + +def quat_slerp(quat0, quat1, fraction, shortestpath=True): + """ + Return spherical linear interpolation between two quaternions. + + E.g.: + >>> q0 = random_quat() + >>> q1 = random_quat() + >>> q = quat_slerp(q0, q1, 0.0) + >>> np.allclose(q, q0) + True + + >>> q = quat_slerp(q0, q1, 1.0) + >>> np.allclose(q, q1) + True + + >>> q = quat_slerp(q0, q1, 0.5) + >>> angle = math.acos(np.dot(q0, q)) + >>> np.allclose(2.0, math.acos(np.dot(q0, q1)) / angle) or \ + np.allclose(2.0, math.acos(-np.dot(q0, q1)) / angle) + True + + Args: + quat0 (np.array): (x,y,z,w) quaternion startpoint + quat1 (np.array): (x,y,z,w) quaternion endpoint + fraction (float): fraction of interpolation to calculate + shortestpath (bool): If True, will calculate the shortest path + + Returns: + np.array: (x,y,z,w) quaternion distance + """ + q0 = unit_vector(quat0[:4]) + q1 = unit_vector(quat1[:4]) + if fraction == 0.0: + return q0 + elif fraction == 1.0: + return q1 + d = np.dot(q0, q1) + if abs(abs(d) - 1.0) < EPS: + return q0 + if shortestpath and d < 0.0: + # invert rotation + d = -d + q1 *= -1.0 + angle = math.acos(np.clip(d, -1, 1)) + if abs(angle) < EPS: + return q0 + isin = 1.0 / math.sin(angle) + q0 *= math.sin((1.0 - fraction) * angle) * isin + q1 *= math.sin(fraction * angle) * isin + q0 += q1 + return q0 + + +def random_quat(rand=None): + """ + Return uniform random unit quaternion. + + E.g.: + >>> q = random_quat() + >>> np.allclose(1.0, vector_norm(q)) + True + >>> q = random_quat(np.random.random(3)) + >>> q.shape + (4,) + + Args: + rand (3-array or None): If specified, must be three independent random variables that are uniformly distributed + between 0 and 1. + + Returns: + np.array: (x,y,z,w) random quaternion + """ + if rand is None: + rand = np.random.rand(3) + else: + assert len(rand) == 3 + r1 = np.sqrt(1.0 - rand[0]) + r2 = np.sqrt(rand[0]) + pi2 = math.pi * 2.0 + t1 = pi2 * rand[1] + t2 = pi2 * rand[2] + return np.array( + (np.sin(t1) * r1, np.cos(t1) * r1, np.sin(t2) * r2, np.cos(t2) * r2), + dtype=np.float32, + ) + + +def random_axis_angle(angle_limit=None, random_state=None): + """ + Samples an axis-angle rotation by first sampling a random axis + and then sampling an angle. If @angle_limit is provided, the size + of the rotation angle is constrained. + + If @random_state is provided (instance of np.random.RandomState), it + will be used to generate random numbers. + + Args: + angle_limit (None or float): If set, determines magnitude limit of angles to generate + random_state (None or RandomState): RNG to use if specified + + Raises: + AssertionError: [Invalid RNG] + """ + if angle_limit is None: + angle_limit = 2.0 * np.pi + + if random_state is not None: + assert isinstance(random_state, np.random.RandomState) + npr = random_state + else: + npr = np.random + + # sample random axis using a normalized sample from spherical Gaussian. + # see (http://extremelearning.com.au/how-to-generate-uniformly-random-points-on-n-spheres-and-n-balls/) + # for why it works. + random_axis = npr.randn(3) + random_axis /= np.linalg.norm(random_axis) + random_angle = npr.uniform(low=0.0, high=angle_limit) + return random_axis, random_angle + + +def vec(values): + """ + Converts value tuple into a numpy vector. + + Args: + values (n-array): a tuple of numbers + + Returns: + np.array: vector of given values + """ + return np.array(values, dtype=np.float32) + + +def mat4(array): + """ + Converts an array to 4x4 matrix. + + Args: + array (n-array): the array in form of vec, list, or tuple + + Returns: + np.array: a 4x4 numpy matrix + """ + return np.array(array, dtype=np.float32).reshape((4, 4)) + + +def mat2pose(hmat): + """ + Converts a homogeneous 4x4 matrix into pose. + + Args: + hmat (np.array): a 4x4 homogeneous matrix + + Returns: + 2-tuple: + + - (np.array) (x,y,z) position array in cartesian coordinates + - (np.array) (x,y,z,w) orientation array in quaternion form + """ + pos = hmat[:3, 3] + orn = mat2quat(hmat[:3, :3]) + return pos, orn + + +@jit_decorator +def mat2quat(rmat): + """ + Converts given rotation matrix to quaternion. + + Args: + rmat (np.array): 3x3 rotation matrix + + Returns: + np.array: (x,y,z,w) float quaternion angles + """ + M = np.asarray(rmat).astype(np.float32)[:3, :3] + + m00 = M[0, 0] + m01 = M[0, 1] + m02 = M[0, 2] + m10 = M[1, 0] + m11 = M[1, 1] + m12 = M[1, 2] + m20 = M[2, 0] + m21 = M[2, 1] + m22 = M[2, 2] + # symmetric matrix K + K = np.array( + [ + [m00 - m11 - m22, np.float32(0.0), np.float32(0.0), np.float32(0.0)], + [m01 + m10, m11 - m00 - m22, np.float32(0.0), np.float32(0.0)], + [m02 + m20, m12 + m21, m22 - m00 - m11, np.float32(0.0)], + [m21 - m12, m02 - m20, m10 - m01, m00 + m11 + m22], + ] + ) + K /= 3.0 + # quaternion is Eigen vector of K that corresponds to largest eigenvalue + w, V = np.linalg.eigh(K) + inds = np.array([3, 0, 1, 2]) + q1 = V[inds, np.argmax(w)] + if q1[0] < 0.0: + np.negative(q1, q1) + inds = np.array([1, 2, 3, 0]) + return q1[inds] + + +def euler2mat(euler): + """ + Converts euler angles into rotation matrix form + + Args: + euler (np.array): (r,p,y) angles + + Returns: + np.array: 3x3 rotation matrix + + Raises: + AssertionError: [Invalid input shape] + """ + + euler = np.asarray(euler, dtype=np.float64) + assert euler.shape[-1] == 3, "Invalid shaped euler {}".format(euler) + + ai, aj, ak = -euler[..., 2], -euler[..., 1], -euler[..., 0] + si, sj, sk = np.sin(ai), np.sin(aj), np.sin(ak) + ci, cj, ck = np.cos(ai), np.cos(aj), np.cos(ak) + cc, cs = ci * ck, ci * sk + sc, ss = si * ck, si * sk + + mat = np.empty(euler.shape[:-1] + (3, 3), dtype=np.float64) + mat[..., 2, 2] = cj * ck + mat[..., 2, 1] = sj * sc - cs + mat[..., 2, 0] = sj * cc + ss + mat[..., 1, 2] = cj * sk + mat[..., 1, 1] = sj * ss + cc + mat[..., 1, 0] = sj * cs - sc + mat[..., 0, 2] = -sj + mat[..., 0, 1] = cj * si + mat[..., 0, 0] = cj * ci + return mat + + +def mat2euler(rmat, axes="sxyz"): + """ + Converts given rotation matrix to euler angles in radian. + + Args: + rmat (np.array): 3x3 rotation matrix + axes (str): One of 24 axis sequences as string or encoded tuple (see top of this module) + + Returns: + np.array: (r,p,y) converted euler angles in radian vec3 float + """ + try: + firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()] + except (AttributeError, KeyError): + firstaxis, parity, repetition, frame = axes + + i = firstaxis + j = _NEXT_AXIS[i + parity] + k = _NEXT_AXIS[i - parity + 1] + + M = np.asarray(rmat, dtype=np.float32)[:3, :3] + if repetition: + sy = math.sqrt(M[i, j] * M[i, j] + M[i, k] * M[i, k]) + if sy > EPS: + ax = math.atan2(M[i, j], M[i, k]) + ay = math.atan2(sy, M[i, i]) + az = math.atan2(M[j, i], -M[k, i]) + else: + ax = math.atan2(-M[j, k], M[j, j]) + ay = math.atan2(sy, M[i, i]) + az = 0.0 + else: + cy = math.sqrt(M[i, i] * M[i, i] + M[j, i] * M[j, i]) + if cy > EPS: + ax = math.atan2(M[k, j], M[k, k]) + ay = math.atan2(-M[k, i], cy) + az = math.atan2(M[j, i], M[i, i]) + else: + ax = math.atan2(-M[j, k], M[j, j]) + ay = math.atan2(-M[k, i], cy) + az = 0.0 + + if parity: + ax, ay, az = -ax, -ay, -az + if frame: + ax, az = az, ax + return vec((ax, ay, az)) + + +def pose2mat(pose): + """ + Converts pose to homogeneous matrix. + + Args: + pose (2-tuple): a (pos, orn) tuple where pos is vec3 float cartesian, and + orn is vec4 float quaternion. + + Returns: + np.array: 4x4 homogeneous matrix + """ + homo_pose_mat = np.zeros((4, 4), dtype=np.float32) + homo_pose_mat[:3, :3] = quat2mat(pose[1]) + homo_pose_mat[:3, 3] = np.array(pose[0], dtype=np.float32) + homo_pose_mat[3, 3] = 1.0 + return homo_pose_mat + + +@jit_decorator +def quat2mat(quaternion): + """ + Converts given quaternion to matrix. + + Args: + quaternion (np.array): (x,y,z,w) vec4 float angles + + Returns: + np.array: 3x3 rotation matrix + """ + # awkward semantics for use with numba + inds = np.array([3, 0, 1, 2]) + q = np.asarray(quaternion).copy().astype(np.float32)[inds] + + n = np.dot(q, q) + if n < EPS: + return np.identity(3) + q *= math.sqrt(2.0 / n) + q2 = np.outer(q, q) + return np.array( + [ + [1.0 - q2[2, 2] - q2[3, 3], q2[1, 2] - q2[3, 0], q2[1, 3] + q2[2, 0]], + [q2[1, 2] + q2[3, 0], 1.0 - q2[1, 1] - q2[3, 3], q2[2, 3] - q2[1, 0]], + [q2[1, 3] - q2[2, 0], q2[2, 3] + q2[1, 0], 1.0 - q2[1, 1] - q2[2, 2]], + ] + ) + + +def quat2axisangle(quat): + """ + Converts quaternion to axis-angle format. + Returns a unit vector direction scaled by its angle in radians. + + Args: + quat (np.array): (x,y,z,w) vec4 float angles + + Returns: + np.array: (ax,ay,az) axis-angle exponential coordinates + """ + # clip quaternion + if quat[3] > 1.0: + quat[3] = 1.0 + elif quat[3] < -1.0: + quat[3] = -1.0 + + den = np.sqrt(1.0 - quat[3] * quat[3]) + if math.isclose(den, 0.0): + # This is (close to) a zero degree rotation, immediately return + return np.zeros(3) + + return (quat[:3] * 2.0 * math.acos(quat[3])) / den + + +def axisangle2quat(vec): + """ + Converts scaled axis-angle to quat. + + Args: + vec (np.array): (ax,ay,az) axis-angle exponential coordinates + + Returns: + np.array: (x,y,z,w) vec4 float angles + """ + # Grab angle + angle = np.linalg.norm(vec) + + # handle zero-rotation case + if math.isclose(angle, 0.0): + return np.array([0.0, 0.0, 0.0, 1.0]) + + # make sure that axis is a unit vector + axis = vec / angle + + q = np.zeros(4) + q[3] = np.cos(angle / 2.0) + q[:3] = axis * np.sin(angle / 2.0) + return q + + +def pose_in_A_to_pose_in_B(pose_A, pose_A_in_B): + """ + Converts a homogenous matrix corresponding to a point C in frame A + to a homogenous matrix corresponding to the same point C in frame B. + + Args: + pose_A (np.array): 4x4 matrix corresponding to the pose of C in frame A + pose_A_in_B (np.array): 4x4 matrix corresponding to the pose of A in frame B + + Returns: + np.array: 4x4 matrix corresponding to the pose of C in frame B + """ + + # pose of A in B takes a point in A and transforms it to a point in C. + + # pose of C in B = pose of A in B * pose of C in A + # take a point in C, transform it to A, then to B + # T_B^C = T_A^C * T_B^A + return pose_A_in_B.dot(pose_A) + + +def pose_inv(pose): + """ + Computes the inverse of a homogeneous matrix corresponding to the pose of some + frame B in frame A. The inverse is the pose of frame A in frame B. + + Args: + pose (np.array): 4x4 matrix for the pose to inverse + + Returns: + np.array: 4x4 matrix for the inverse pose + """ + + # Note, the inverse of a pose matrix is the following + # [R t; 0 1]^-1 = [R.T -R.T*t; 0 1] + + # Intuitively, this makes sense. + # The original pose matrix translates by t, then rotates by R. + # We just invert the rotation by applying R-1 = R.T, and also translate back. + # Since we apply translation first before rotation, we need to translate by + # -t in the original frame, which is -R-1*t in the new frame, and then rotate back by + # R-1 to align the axis again. + + pose_inv = np.zeros((4, 4)) + pose_inv[:3, :3] = pose[:3, :3].T + pose_inv[:3, 3] = -pose_inv[:3, :3].dot(pose[:3, 3]) + pose_inv[3, 3] = 1.0 + return pose_inv + + +def _skew_symmetric_translation(pos_A_in_B): + """ + Helper function to get a skew symmetric translation matrix for converting quantities + between frames. + + Args: + pos_A_in_B (np.array): (x,y,z) position of A in frame B + + Returns: + np.array: 3x3 skew symmetric translation matrix + """ + return np.array( + [ + 0.0, + -pos_A_in_B[2], + pos_A_in_B[1], + pos_A_in_B[2], + 0.0, + -pos_A_in_B[0], + -pos_A_in_B[1], + pos_A_in_B[0], + 0.0, + ] + ).reshape((3, 3)) + + +def vel_in_A_to_vel_in_B(vel_A, ang_vel_A, pose_A_in_B): + """ + Converts linear and angular velocity of a point in frame A to the equivalent in frame B. + + Args: + vel_A (np.array): (vx,vy,vz) linear velocity in A + ang_vel_A (np.array): (wx,wy,wz) angular velocity in A + pose_A_in_B (np.array): 4x4 matrix corresponding to the pose of A in frame B + + Returns: + 2-tuple: + + - (np.array) (vx,vy,vz) linear velocities in frame B + - (np.array) (wx,wy,wz) angular velocities in frame B + """ + pos_A_in_B = pose_A_in_B[:3, 3] + rot_A_in_B = pose_A_in_B[:3, :3] + skew_symm = _skew_symmetric_translation(pos_A_in_B) + vel_B = rot_A_in_B.dot(vel_A) + skew_symm.dot(rot_A_in_B.dot(ang_vel_A)) + ang_vel_B = rot_A_in_B.dot(ang_vel_A) + return vel_B, ang_vel_B + + +def force_in_A_to_force_in_B(force_A, torque_A, pose_A_in_B): + """ + Converts linear and rotational force at a point in frame A to the equivalent in frame B. + + Args: + force_A (np.array): (fx,fy,fz) linear force in A + torque_A (np.array): (tx,ty,tz) rotational force (moment) in A + pose_A_in_B (np.array): 4x4 matrix corresponding to the pose of A in frame B + + Returns: + 2-tuple: + + - (np.array) (fx,fy,fz) linear forces in frame B + - (np.array) (tx,ty,tz) moments in frame B + """ + pos_A_in_B = pose_A_in_B[:3, 3] + rot_A_in_B = pose_A_in_B[:3, :3] + skew_symm = _skew_symmetric_translation(pos_A_in_B) + force_B = rot_A_in_B.T.dot(force_A) + torque_B = -rot_A_in_B.T.dot(skew_symm.dot(force_A)) + rot_A_in_B.T.dot(torque_A) + return force_B, torque_B + + +def rotation_matrix(angle, direction, point=None): + """ + Returns matrix to rotate about axis defined by point and direction. + + E.g.: + >>> angle = (random.random() - 0.5) * (2*math.pi) + >>> direc = numpy.random.random(3) - 0.5 + >>> point = numpy.random.random(3) - 0.5 + >>> R0 = rotation_matrix(angle, direc, point) + >>> R1 = rotation_matrix(angle-2*math.pi, direc, point) + >>> is_same_transform(R0, R1) + True + + >>> R0 = rotation_matrix(angle, direc, point) + >>> R1 = rotation_matrix(-angle, -direc, point) + >>> is_same_transform(R0, R1) + True + + >>> I = numpy.identity(4, numpy.float32) + >>> numpy.allclose(I, rotation_matrix(math.pi*2, direc)) + True + + >>> numpy.allclose(2., numpy.trace(rotation_matrix(math.pi/2, + ... direc, point))) + True + + Args: + angle (float): Magnitude of rotation + direction (np.array): (ax,ay,az) axis about which to rotate + point (None or np.array): If specified, is the (x,y,z) point about which the rotation will occur + + Returns: + np.array: 4x4 homogeneous matrix that includes the desired rotation + """ + sina = math.sin(angle) + cosa = math.cos(angle) + direction = unit_vector(direction[:3]) + # rotation matrix around unit vector + R = np.array(((cosa, 0.0, 0.0), (0.0, cosa, 0.0), (0.0, 0.0, cosa)), dtype=np.float32) + R += np.outer(direction, direction) * (1.0 - cosa) + direction *= sina + R += np.array( + ( + (0.0, -direction[2], direction[1]), + (direction[2], 0.0, -direction[0]), + (-direction[1], direction[0], 0.0), + ), + dtype=np.float32, + ) + M = np.identity(4) + M[:3, :3] = R + if point is not None: + # rotation not around origin + point = np.asarray(point[:3], dtype=np.float32) + M[:3, 3] = point - np.dot(R, point) + return M + + +def clip_translation(dpos, limit): + """ + Limits a translation (delta position) to a specified limit + + Scales down the norm of the dpos to 'limit' if norm(dpos) > limit, else returns immediately + + Args: + dpos (n-array): n-dim Translation being clipped (e,g.: (x, y, z)) -- numpy array + limit (float): Value to limit translation by -- magnitude (scalar, in same units as input) + + Returns: + 2-tuple: + + - (np.array) Clipped translation (same dimension as inputs) + - (bool) whether the value was clipped or not + """ + input_norm = np.linalg.norm(dpos) + return (dpos * limit / input_norm, True) if input_norm > limit else (dpos, False) + + +def clip_rotation(quat, limit): + """ + Limits a (delta) rotation to a specified limit + + Converts rotation to axis-angle, clips, then re-converts back into quaternion + + Args: + quat (np.array): (x,y,z,w) rotation being clipped + limit (float): Value to limit rotation by -- magnitude (scalar, in radians) + + Returns: + 2-tuple: + + - (np.array) Clipped rotation quaternion (x, y, z, w) + - (bool) whether the value was clipped or not + """ + clipped = False + + # First, normalize the quaternion + quat = quat / np.linalg.norm(quat) + + den = np.sqrt(max(1 - quat[3] * quat[3], 0)) + if den == 0: + # This is a zero degree rotation, immediately return + return quat, clipped + else: + # This is all other cases + x = quat[0] / den + y = quat[1] / den + z = quat[2] / den + a = 2 * math.acos(quat[3]) + + # Clip rotation if necessary and return clipped quat + if abs(a) > limit: + a = limit * np.sign(a) / 2 + sa = math.sin(a) + ca = math.cos(a) + quat = np.array([x * sa, y * sa, z * sa, ca]) + clipped = True + + return quat, clipped + + +def make_pose(translation, rotation): + """ + Makes a homogeneous pose matrix from a translation vector and a rotation matrix. + + Args: + translation (np.array): (x,y,z) translation value + rotation (np.array): a 3x3 matrix representing rotation + + Returns: + pose (np.array): a 4x4 homogeneous matrix + """ + pose = np.zeros((4, 4)) + pose[:3, :3] = rotation + pose[:3, 3] = translation + pose[3, 3] = 1.0 + return pose + + +def unit_vector(data, axis=None, out=None): + """ + Returns ndarray normalized by length, i.e. eucledian norm, along axis. + + E.g.: + >>> v0 = numpy.random.random(3) + >>> v1 = unit_vector(v0) + >>> numpy.allclose(v1, v0 / numpy.linalg.norm(v0)) + True + + >>> v0 = numpy.random.rand(5, 4, 3) + >>> v1 = unit_vector(v0, axis=-1) + >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=2)), 2) + >>> numpy.allclose(v1, v2) + True + + >>> v1 = unit_vector(v0, axis=1) + >>> v2 = v0 / numpy.expand_dims(numpy.sqrt(numpy.sum(v0*v0, axis=1)), 1) + >>> numpy.allclose(v1, v2) + True + + >>> v1 = numpy.empty((5, 4, 3), dtype=numpy.float32) + >>> unit_vector(v0, axis=1, out=v1) + >>> numpy.allclose(v1, v2) + True + + >>> list(unit_vector([])) + [] + + >>> list(unit_vector([1.0])) + [1.0] + + Args: + data (np.array): data to normalize + axis (None or int): If specified, determines specific axis along data to normalize + out (None or np.array): If specified, will store computation in this variable + + Returns: + None or np.array: If @out is not specified, will return normalized vector. Otherwise, stores the output in @out + """ + if out is None: + data = np.array(data, dtype=np.float32, copy=True) + if data.ndim == 1: + data /= math.sqrt(np.dot(data, data)) + return data + else: + if out is not data: + out[:] = np.asarray(data) + data = out + length = np.atleast_1d(np.sum(data * data, axis)) + np.sqrt(length, length) + if axis is not None: + length = np.expand_dims(length, axis) + data /= length + if out is None: + return data + + +def get_orientation_error(target_orn, current_orn): + """ + Returns the difference between two quaternion orientations as a 3 DOF numpy array. + For use in an impedance controller / task-space PD controller. + + Args: + target_orn (np.array): (x, y, z, w) desired quaternion orientation + current_orn (np.array): (x, y, z, w) current quaternion orientation + + Returns: + orn_error (np.array): (ax,ay,az) current orientation error, corresponds to + (target_orn - current_orn) + """ + current_orn = np.array([current_orn[3], current_orn[0], current_orn[1], current_orn[2]]) + target_orn = np.array([target_orn[3], target_orn[0], target_orn[1], target_orn[2]]) + + pinv = np.zeros((3, 4)) + pinv[0, :] = [-current_orn[1], current_orn[0], -current_orn[3], current_orn[2]] + pinv[1, :] = [-current_orn[2], current_orn[3], current_orn[0], -current_orn[1]] + pinv[2, :] = [-current_orn[3], -current_orn[2], current_orn[1], current_orn[0]] + orn_error = 2.0 * pinv.dot(np.array(target_orn)) + return orn_error + + +def get_pose_error(target_pose, current_pose): + """ + Computes the error corresponding to target pose - current pose as a 6-dim vector. + The first 3 components correspond to translational error while the last 3 components + correspond to the rotational error. + + Args: + target_pose (np.array): a 4x4 homogenous matrix for the target pose + current_pose (np.array): a 4x4 homogenous matrix for the current pose + + Returns: + np.array: 6-dim pose error. + """ + error = np.zeros(6) + + # compute translational error + target_pos = target_pose[:3, 3] + current_pos = current_pose[:3, 3] + pos_err = target_pos - current_pos + + # compute rotational error + r1 = current_pose[:3, 0] + r2 = current_pose[:3, 1] + r3 = current_pose[:3, 2] + r1d = target_pose[:3, 0] + r2d = target_pose[:3, 1] + r3d = target_pose[:3, 2] + rot_err = 0.5 * (np.cross(r1, r1d) + np.cross(r2, r2d) + np.cross(r3, r3d)) + + error[:3] = pos_err + error[3:] = rot_err + return error + + +@jit_decorator +def matrix_inverse(matrix): + """ + Helper function to have an efficient matrix inversion function. + + Args: + matrix (np.array): 2d-array representing a matrix + + Returns: + np.array: 2d-array representing the matrix inverse + """ + return np.linalg.inv(matrix) + + +def rotate_2d_point(input, rot): + """ + rotate a 2d vector counterclockwise + + Args: + input (np.array): 1d-array representing 2d vector + rot (float): rotation value + + Returns: + np.array: rotated 1d-array + """ + input_x, input_y = input + x = input_x * np.cos(rot) - input_y * np.sin(rot) + y = input_x * np.sin(rot) + input_y * np.cos(rot) + + return np.array([x, y]) diff --git a/third_party/robosuite/robosuite/wrappers/__init__.py b/third_party/robosuite/robosuite/wrappers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..282a66a0702dda49c0a4d2822bb5c994d85d8cd4 --- /dev/null +++ b/third_party/robosuite/robosuite/wrappers/__init__.py @@ -0,0 +1,10 @@ +from robosuite.wrappers.wrapper import Wrapper +from robosuite.wrappers.data_collection_wrapper import DataCollectionWrapper +from robosuite.wrappers.demo_sampler_wrapper import DemoSamplerWrapper +from robosuite.wrappers.domain_randomization_wrapper import DomainRandomizationWrapper +from robosuite.wrappers.visualization_wrapper import VisualizationWrapper + +try: + from robosuite.wrappers.gym_wrapper import GymWrapper +except: + print("Warning: make sure gym is installed if you want to use the GymWrapper.") diff --git a/third_party/robosuite/robosuite/wrappers/data_collection_wrapper.py b/third_party/robosuite/robosuite/wrappers/data_collection_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..7618585e190234d73950e4ae7c609940229ff783 --- /dev/null +++ b/third_party/robosuite/robosuite/wrappers/data_collection_wrapper.py @@ -0,0 +1,204 @@ +""" +This file implements a wrapper for saving simulation states to disk. +This data collection wrapper is useful for collecting demonstrations. +""" + +import json +import os +import time + +import numpy as np + +from robosuite.utils.mjcf_utils import save_sim_model +from robosuite.wrappers import Wrapper + + +class DataCollectionWrapper(Wrapper): + def __init__(self, env, directory, collect_freq=1, flush_freq=100): + """ + Initializes the data collection wrapper. + + Args: + env (MujocoEnv): The environment to monitor. + directory (str): Where to store collected data. + collect_freq (int): How often to save simulation state, in terms of environment steps. + flush_freq (int): How frequently to dump data to disk, in terms of environment steps. + """ + super().__init__(env) + + # the base directory for all logging + self.directory = directory + + # in-memory cache for simulation states and action info + self.states = [] + self.action_infos = [] # stores information about actions taken + self.successful = False # stores success state of demonstration + + # how often to save simulation state, in terms of environment steps + self.collect_freq = collect_freq + + # how frequently to dump data to disk, in terms of environment steps + self.flush_freq = flush_freq + + if not os.path.exists(directory): + print("DataCollectionWrapper: making new directory at {}".format(directory)) + os.makedirs(directory) + + # store logging directory for current episode + self.ep_directory = None + + # remember whether any environment interaction has occurred + self.has_interaction = False + + # some variables for remembering the current episode's initial state and model xml + self._current_task_instance_state = None + self._current_task_instance_xml = None + + def _start_new_episode(self): + """ + Bookkeeping to do at the start of each new episode. + """ + + # flush any data left over from the previous episode if any interactions have happened + if self.has_interaction: + self._flush() + + # timesteps in current episode + self.t = 0 + self.has_interaction = False + + # save the task instance (will be saved on the first env interaction) + + # NOTE: was previously self.env.model.get_xml(). Was causing the following issue in rare cases: + # ValueError: Error: eigenvalues of mesh inertia violate A + B >= C + # switching to self.env.sim.model.get_xml() does not create this issue + self._current_task_instance_xml = self.env.sim.model.get_xml() + self._current_task_instance_state = np.array(self.env.sim.get_state().flatten()) + + # trick for ensuring that we can play MuJoCo demonstrations back + # deterministically by using the recorded actions open loop + self.env.reset_from_xml_string(self._current_task_instance_xml) + self.env.sim.reset() + self.env.sim.set_state_from_flattened(self._current_task_instance_state) + self.env.sim.forward() + + def _on_first_interaction(self): + """ + Bookkeeping for first timestep of episode. + This function is necessary to make sure that logging only happens after the first + step call to the simulation, instead of on the reset (people tend to call + reset more than is necessary in code). + + Raises: + AssertionError: [Episode path already exists] + """ + + self.has_interaction = True + + # create a directory with a timestamp + t1, t2 = str(time.time()).split(".") + self.ep_directory = os.path.join(self.directory, "ep_{}_{}".format(t1, t2)) + assert not os.path.exists(self.ep_directory) + print("DataCollectionWrapper: making folder at {}".format(self.ep_directory)) + os.makedirs(self.ep_directory) + + # save the model xml + xml_path = os.path.join(self.ep_directory, "model.xml") + with open(xml_path, "w") as f: + f.write(self._current_task_instance_xml) + + # save the episode info to json file + ep_meta_path = os.path.join(self.ep_directory, "ep_meta.json") + with open(ep_meta_path, "w") as f: + json.dump(self.env.get_ep_meta(), f) + + # save initial state and action + assert len(self.states) == 0 + self.states.append(self._current_task_instance_state) + + def _flush(self): + """ + Method to flush internal state to disk. + """ + t1, t2 = str(time.time()).split(".") + state_path = os.path.join(self.ep_directory, "state_{}_{}.npz".format(t1, t2)) + if hasattr(self.env, "unwrapped"): + env_name = self.env.unwrapped.__class__.__name__ + else: + env_name = self.env.__class__.__name__ + np.savez( + state_path, + states=np.array(self.states), + action_infos=self.action_infos, + successful=self.successful, + env=env_name, + ) + self.states = [] + self.action_infos = [] + self.successful = False + + def reset(self): + """ + Extends vanilla reset() function call to accommodate data collection + + Returns: + OrderedDict: Environment observation space after reset occurs + """ + ret = super().reset() + self._start_new_episode() + return ret + + def step(self, action): + """ + Extends vanilla step() function call to accommodate data collection + + Args: + action (np.array): Action to take in 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 + """ + ret = super().step(action) + self.t += 1 + + # on the first time step, make directories for logging + if not self.has_interaction: + self._on_first_interaction() + + # collect the current simulation state if necessary + if self.t % self.collect_freq == 0: + state = self.env.sim.get_state().flatten() + self.states.append(state) + + info = {} + info["actions"] = np.array(action) + + # (if applicable) store absolute actions + step_info = ret[3] + if "action_abs" in step_info.keys(): + info["actions_abs"] = np.array(step_info["action_abs"]) + + self.action_infos.append(info) + + # check if the demonstration is successful + if self.env._check_success(): + self.successful = True + + # flush collected data to disk if necessary + if self.t % self.flush_freq == 0: + self._flush() + + return ret + + def close(self): + """ + Override close method in order to flush left over data + """ + if self.has_interaction: + self._flush() + self.env.close() diff --git a/third_party/robosuite/robosuite/wrappers/demo_sampler_wrapper.py b/third_party/robosuite/robosuite/wrappers/demo_sampler_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..227045fa52c0d3b01ca563886ca56f6eae1593f5 --- /dev/null +++ b/third_party/robosuite/robosuite/wrappers/demo_sampler_wrapper.py @@ -0,0 +1,316 @@ +""" +This file contains a wrapper for sampling environment states +from a set of demonstrations on every reset. The main use case is for +altering the start state distribution of training episodes for +learning RL policies. +""" + +import os +import random +import time + +import h5py +import numpy as np + +from robosuite.wrappers import Wrapper + + +class DemoSamplerWrapper(Wrapper): + """ + Initializes a wrapper that provides support for resetting the environment + state to one from a demonstration. It also supports curriculums for + altering how often to sample from demonstration vs. sampling a reset + state from the environment. + + Args: + env (MujocoEnv): The environment to wrap. + + demo_path (str): The path to the folder containing the demonstrations. + There should be a `demo.hdf5` file and a folder named `models` with + all of the stored model xml files from the demonstrations. + + need_xml (bool): If True, the mujoco model needs to be reloaded when + sampling a state from a demonstration. This could be because every + demonstration was taken under varied object properties, for example. + In this case, every sampled state comes with a corresponding xml to + be used for the environment reset. + + num_traj (int): If provided, subsample @number demonstrations from the + provided set of demonstrations instead of using all of them. + + sampling_schemes (list of str): A list of sampling schemes + to be used. The following strings are valid schemes: + + `'random'`: sample a reset state directly from the wrapped environment + + `'uniform'`: sample a state from a demonstration uniformly at random + + `'forward'`: sample a state from a window that grows progressively from + the start of demonstrations + + `'reverse'`: sample a state from a window that grows progressively from + the end of demonstrations + + scheme_ratios (list of float --> np.array): A list of probability values to + assign to each member of @sampling_schemes. Must be non-negative and + sum to 1. + + open_loop_increment_freq (int): How frequently to increase + the window size in open loop schemes ("forward" and "reverse"). The + window size will increase by @open_loop_window_increment every + @open_loop_increment_freq samples. Only samples that are generated + by open loop schemes contribute to this count. + + open_loop_initial_window_width (int): The width of the initial sampling + window, in terms of number of demonstration time steps, for + open loop schemes. + + open_loop_window_increment (int): The window size will increase by + @open_loop_window_increment every @open_loop_increment_freq samples. + This number is in terms of number of demonstration time steps. + + Raises: + AssertionError: [Incompatible envs] + AssertionError: [Invalid sampling scheme] + AssertionError: [Invalid scheme ratio] + """ + + def __init__( + self, + env, + demo_path, + need_xml=False, + num_traj=-1, + sampling_schemes=("uniform", "random"), + scheme_ratios=(0.9, 0.1), + open_loop_increment_freq=100, + open_loop_initial_window_width=25, + open_loop_window_increment=25, + ): + super().__init__(env) + + self.demo_path = demo_path + hdf5_path = os.path.join(self.demo_path, "demo.hdf5") + self.demo_file = h5py.File(hdf5_path, "r") + + # ensure that wrapped env matches the env on which demonstrations were collected + env_name = self.demo_file["data"].attrs["env"] + assert ( + env_name == self.unwrapped.__class__.__name__ + ), "Wrapped env {} does not match env on which demos were collected ({})".format( + env.__class__.__name__, env_name + ) + + # list of all demonstrations episodes + self.demo_list = list(self.demo_file["data"].keys()) + + # subsample a selection of demonstrations if requested + if num_traj > 0: + random.seed(3141) # ensure that the same set is sampled every time + self.demo_list = random.sample(self.demo_list, num_traj) + + self.need_xml = need_xml + self.demo_sampled = 0 + + self.sample_method_dict = { + "random": "_random_sample", + "uniform": "_uniform_sample", + "forward": "_forward_sample_open_loop", + "reverse": "_reverse_sample_open_loop", + } + + self.sampling_schemes = sampling_schemes + self.scheme_ratios = np.asarray(scheme_ratios) + + # make sure the list of schemes is valid + schemes = self.sample_method_dict.keys() + assert np.all([(s in schemes) for s in self.sampling_schemes]) + + # make sure the distribution is the correct size + assert len(self.sampling_schemes) == len(self.scheme_ratios) + + # make sure the distribution lies in the probability simplex + assert np.all(self.scheme_ratios > 0.0) + assert sum(self.scheme_ratios) == 1.0 + + # open loop configuration + self.open_loop_increment_freq = open_loop_increment_freq + self.open_loop_window_increment = open_loop_window_increment + + # keep track of window size + self.open_loop_window_size = open_loop_initial_window_width + + def reset(self): + """ + Logic for sampling a state from the demonstration and resetting + the simulation to that state. + + Returns: + OrderedDict: Environment observation space after reset occurs + """ + state = self.sample() + if state is None: + # None indicates that a normal env reset should occur + return self.env.reset() + else: + if self.need_xml: + # reset the simulation from the model if necessary + state, xml = state + self.env.reset_from_xml_string(xml) + + if isinstance(state, tuple): + state = state[0] + + # force simulator state to one from the demo + self.sim.set_state_from_flattened(state) + self.sim.forward() + + return self.env._get_observation() + + def sample(self): + """ + This is the core sampling method. Samples a state from a + demonstration, in accordance with the configuration. + + Returns: + None or np.array or 2-tuple: If np.array, is the state sampled from a demo file. If 2-tuple, additionally + includes the model xml file + """ + + # chooses a sampling scheme randomly based on the mixing ratios + seed = random.uniform(0, 1) + ratio = np.cumsum(self.scheme_ratios) + ratio = ratio > seed + for i, v in enumerate(ratio): + if v: + break + + sample_method = getattr(self, self.sample_method_dict[self.sampling_schemes[i]]) + return sample_method() + + def _random_sample(self): + """ + Sampling method. + + Return None to indicate that the state should be sampled directly + from the environment. + """ + return None + + def _uniform_sample(self): + """ + Sampling method. + + First uniformly sample a demonstration from the set of demonstrations. + Then uniformly sample a state from the selected demonstration. + + Returns: + np.array or 2-tuple: If np.array, is the state sampled from a demo file. If 2-tuple, additionally + includes the model xml file + """ + + # get a random episode index + ep_ind = random.choice(self.demo_list) + + # select a flattened mujoco state uniformly from this episode + states = self.demo_file["data/{}/states".format(ep_ind)][()] + state = random.choice(states) + + if self.need_xml: + model_xml = self._xml_for_episode_index(ep_ind) + xml = self.env.edit_model_xml(model_xml) + return state, xml + return state + + def _reverse_sample_open_loop(self): + """ + Sampling method. + + Open loop reverse sampling from demonstrations. Starts by + sampling from states near the end of the demonstrations. + Increases the window backwards as the number of calls to + this sampling method increases at a fixed rate. + + Returns: + np.array or 2-tuple: If np.array, is the state sampled from a demo file. If 2-tuple, additionally + includes the model xml file + """ + + # get a random episode index + ep_ind = random.choice(self.demo_list) + + # sample uniformly in a window that grows backwards from the end of the demos + states = self.demo_file["data/{}/states".format(ep_ind)][()] + eps_len = states.shape[0] + index = np.random.randint(max(eps_len - self.open_loop_window_size, 0), eps_len) + state = states[index] + + # increase window size at a fixed frequency (open loop) + self.demo_sampled += 1 + if self.demo_sampled >= self.open_loop_increment_freq: + if self.open_loop_window_size < eps_len: + self.open_loop_window_size += self.open_loop_window_increment + self.demo_sampled = 0 + + if self.need_xml: + model_xml = self._xml_for_episode_index(ep_ind) + xml = self.env.edit_model_xml(model_xml) + return state, xml + + return state + + def _forward_sample_open_loop(self): + """ + Sampling method. + + Open loop forward sampling from demonstrations. Starts by + sampling from states near the beginning of the demonstrations. + Increases the window forwards as the number of calls to + this sampling method increases at a fixed rate. + + Returns: + np.array or 2-tuple: If np.array, is the state sampled from a demo file. If 2-tuple, additionally + includes the model xml file + """ + + # get a random episode index + ep_ind = random.choice(self.demo_list) + + # sample uniformly in a window that grows forwards from the beginning of the demos + states = self.demo_file["data/{}/states".format(ep_ind)][()] + eps_len = states.shape[0] + index = np.random.randint(0, min(self.open_loop_window_size, eps_len)) + state = states[index] + + # increase window size at a fixed frequency (open loop) + self.demo_sampled += 1 + if self.demo_sampled >= self.open_loop_increment_freq: + if self.open_loop_window_size < eps_len: + self.open_loop_window_size += self.open_loop_window_increment + self.demo_sampled = 0 + + if self.need_xml: + model_xml = self._xml_for_episode_index(ep_ind) + xml = self.env.edit_model_xml(model_xml) + return state, xml + + return state + + def _xml_for_episode_index(self, ep_ind): + """ + Helper method to retrieve the corresponding model xml string + for the passed episode index. + + Args: + ep_ind (int): Episode index to pull from demo file + + Returns: + str: model xml as a string + """ + + # read the model xml, using the metadata stored in the attribute for this episode + model_file = self.demo_file["data/{}".format(ep_ind)].attrs["model_file"] + model_path = os.path.join(self.demo_path, "models", model_file) + with open(model_path, "r") as model_f: + model_xml = model_f.read() + return model_xml diff --git a/third_party/robosuite/robosuite/wrappers/domain_randomization_wrapper.py b/third_party/robosuite/robosuite/wrappers/domain_randomization_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..ce27582663cdd84326acc4d0771a723d40bedd67 --- /dev/null +++ b/third_party/robosuite/robosuite/wrappers/domain_randomization_wrapper.py @@ -0,0 +1,275 @@ +""" +This file implements a wrapper for facilitating domain randomization over +robosuite environments. +""" +import mujoco +import numpy as np + +from robosuite.utils.log_utils import rs_assert +from robosuite.utils.mjmod import CameraModder, DynamicsModder, LightingModder, TextureModder +from robosuite.wrappers import Wrapper + +DEFAULT_COLOR_ARGS = { + "geom_names": None, # all geoms are randomized + "randomize_local": True, # sample nearby colors + "randomize_material": True, # randomize material reflectance / shininess / specular + "local_rgb_interpolation": 0.2, + "local_material_interpolation": 0.3, + "texture_variations": ["rgb", "checker", "noise", "gradient"], # all texture variation types + "randomize_skybox": True, # by default, randomize skybox too +} + +DEFAULT_CAMERA_ARGS = { + "camera_names": None, # all cameras are randomized + "randomize_position": True, + "randomize_rotation": True, + "randomize_fovy": True, + "position_perturbation_size": 0.01, + "rotation_perturbation_size": 0.087, + "fovy_perturbation_size": 5.0, +} + +DEFAULT_LIGHTING_ARGS = { + "light_names": None, # all lights are randomized + "randomize_position": True, + "randomize_direction": True, + "randomize_specular": True, + "randomize_ambient": True, + "randomize_diffuse": True, + "randomize_active": True, + "position_perturbation_size": 0.1, + "direction_perturbation_size": 0.35, + "specular_perturbation_size": 0.1, + "ambient_perturbation_size": 0.1, + "diffuse_perturbation_size": 0.1, +} + +DEFAULT_DYNAMICS_ARGS = { + # Opt parameters + "randomize_density": True, + "randomize_viscosity": True, + "density_perturbation_ratio": 0.1, + "viscosity_perturbation_ratio": 0.1, + # Body parameters + "body_names": None, # all bodies randomized + "randomize_position": True, + "randomize_quaternion": True, + "randomize_inertia": True, + "randomize_mass": True, + "position_perturbation_size": 0.0015, + "quaternion_perturbation_size": 0.003, + "inertia_perturbation_ratio": 0.02, + "mass_perturbation_ratio": 0.02, + # Geom parameters + "geom_names": None, # all geoms randomized + "randomize_friction": True, + "randomize_solref": True, + "randomize_solimp": True, + "friction_perturbation_ratio": 0.1, + "solref_perturbation_ratio": 0.1, + "solimp_perturbation_ratio": 0.1, + # Joint parameters + "joint_names": None, # all joints randomized + "randomize_stiffness": True, + "randomize_frictionloss": True, + "randomize_damping": True, + "randomize_armature": True, + "stiffness_perturbation_ratio": 0.1, + "frictionloss_perturbation_size": 0.05, + "damping_perturbation_size": 0.01, + "armature_perturbation_size": 0.01, +} + + +class DomainRandomizationWrapper(Wrapper): + """ + Wrapper that allows for domain randomization mid-simulation. + + Args: + env (MujocoEnv): The environment to wrap. + + seed (int): Integer used to seed all randomizations from this wrapper. It is + used to create a np.random.RandomState instance to make sure samples here + are isolated from sampling occurring elsewhere in the code. If not provided, + will default to using global random state. + + randomize_color (bool): if True, randomize geom colors and texture colors + + randomize_camera (bool): if True, randomize camera locations and parameters + + randomize_lighting (bool): if True, randomize light locations and properties + + randomize_dyanmics (bool): if True, randomize dynamics parameters + + color_randomization_args (dict): Color-specific randomization arguments + + camera_randomization_args (dict): Camera-specific randomization arguments + + lighting_randomization_args (dict): Lighting-specific randomization arguments + + dynamics_randomization_args (dict): Dyanmics-specific randomization arguments + + randomize_on_reset (bool): if True, randomize on every call to @reset. This, in + conjunction with setting @randomize_every_n_steps to 0, is useful to + generate a new domain per episode. + + randomize_every_n_steps (int): determines how often randomization should occur. Set + to 0 if randomization should happen manually (by calling @randomize_domain) + + """ + + def __init__( + self, + env, + seed=None, + randomize_color=True, + randomize_camera=True, + randomize_lighting=True, + randomize_dynamics=True, + color_randomization_args=DEFAULT_COLOR_ARGS, + camera_randomization_args=DEFAULT_CAMERA_ARGS, + lighting_randomization_args=DEFAULT_LIGHTING_ARGS, + dynamics_randomization_args=DEFAULT_DYNAMICS_ARGS, + randomize_on_reset=True, + randomize_every_n_steps=1, + ): + super().__init__(env) + + self.seed = seed + if seed is not None: + self.random_state = np.random.RandomState(seed) + else: + self.random_state = None + self.randomize_color = randomize_color + self.randomize_camera = randomize_camera + self.randomize_lighting = randomize_lighting + self.randomize_dynamics = randomize_dynamics + self.color_randomization_args = color_randomization_args + self.camera_randomization_args = camera_randomization_args + self.lighting_randomization_args = lighting_randomization_args + self.dynamics_randomization_args = dynamics_randomization_args + self.randomize_on_reset = randomize_on_reset + self.randomize_every_n_steps = randomize_every_n_steps + + self.step_counter = 0 + + self.modders = [] + + if self.randomize_color: + rs_assert( + mujoco.__version__ == "3.1.1", + ( + "TextureModder requires mujoco version 3.1.1 to run. " + "Pending support for later versions. Alternatively, you can set randomize_color=False." + ), + ) + self.tex_modder = TextureModder( + sim=self.env.sim, random_state=self.random_state, **self.color_randomization_args + ) + self.modders.append(self.tex_modder) + + if self.randomize_camera: + self.camera_modder = CameraModder( + sim=self.env.sim, + random_state=self.random_state, + **self.camera_randomization_args, + ) + self.modders.append(self.camera_modder) + + if self.randomize_lighting: + self.light_modder = LightingModder( + sim=self.env.sim, + random_state=self.random_state, + **self.lighting_randomization_args, + ) + self.modders.append(self.light_modder) + + if self.randomize_dynamics: + self.dynamics_modder = DynamicsModder( + sim=self.env.sim, + random_state=self.random_state, + **self.dynamics_randomization_args, + ) + self.modders.append(self.dynamics_modder) + + self.save_default_domain() + + def reset(self): + """ + Extends superclass method to reset the domain randomizer. + + Returns: + OrderedDict: Environment observation space after reset occurs + """ + # undo all randomizations + self.restore_default_domain() + + # normal env reset + ret = super().reset() + + # save the original env parameters + self.save_default_domain() + + # reset counter for doing domain randomization at a particular frequency + self.step_counter = 0 + + # update sims + for modder in self.modders: + modder.update_sim(self.env.sim) + + if self.randomize_on_reset: + # domain randomize + regenerate observation + self.randomize_domain() + ret = self.env._get_observations() + + return ret + + def step(self, action): + """ + Extends vanilla step() function call to accommodate domain randomization + + 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 + """ + # Step the internal randomization state + self.step_randomization() + + return super().step(action) + + def step_randomization(self): + """ + Steps the internal randomization state + """ + # functionality for randomizing at a particular frequency + if self.randomize_every_n_steps > 0: + if self.step_counter % self.randomize_every_n_steps == 0: + self.randomize_domain() + self.step_counter += 1 + + def randomize_domain(self): + """ + Runs domain randomization over the environment. + """ + for modder in self.modders: + modder.randomize() + + def save_default_domain(self): + """ + Saves the current simulation model parameters so + that they can be restored later. + """ + for modder in self.modders: + modder.save_defaults() + + def restore_default_domain(self): + """ + Restores the simulation model parameters saved + in the last call to @save_default_domain. + """ + for modder in self.modders: + modder.restore_defaults() diff --git a/third_party/robosuite/robosuite/wrappers/gym_wrapper.py b/third_party/robosuite/robosuite/wrappers/gym_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..51bb6f5efbc3cbb396d545643e795edf8aa975d1 --- /dev/null +++ b/third_party/robosuite/robosuite/wrappers/gym_wrapper.py @@ -0,0 +1,184 @@ +""" +This file implements a wrapper for facilitating compatibility with OpenAI gym. +This is useful when using these environments with code that assumes a gym-like +interface. +""" + +import numpy as np + +try: + import gymnasium as gym + from gymnasium import spaces +except ImportError: + # Most APIs between gym and gymnasium are compatible + print("WARNING! gymnasium is not installed. We will try to use openai gym instead.") + import gym + from gym import spaces + + if not gym.__version__ >= "0.26.0": + # Due to API Changes in gym>=0.26.0, we need to ensure that the version is correct + # Please check: https://github.com/openai/gym/releases/tag/0.26.0 + raise ImportError("Please ensure version of gym>=0.26.0 to use the GymWrapper.") + +from robosuite.wrappers import Wrapper + + +class GymWrapper(Wrapper, gym.Env): + metadata = None + render_mode = None + """ + Initializes the Gym wrapper. Mimics many of the required functionalities of the Wrapper class + found in the gym.core module + + Args: + env (MujocoEnv): The environment to wrap. + keys (None or list of str): If provided, each observation will + consist of concatenated keys from the wrapped environment's + observation dictionary. Defaults to proprio-state and object-state. + flatten_obs (bool): + Whether to flatten the observation dictionary into a 1d array. Defaults to True. + + Raises: + AssertionError: [Object observations must be enabled if no keys] + """ + + def __init__(self, env, keys=None, flatten_obs=True): + # Run super method + super().__init__(env=env) + # Create name for gym + robots = "".join([type(robot.robot_model).__name__ for robot in self.env.robots]) + self.name = robots + "_" + type(self.env).__name__ + + # Get reward range + self.reward_range = (0, self.env.reward_scale) + + if keys is None: + keys = [] + # Add object obs if requested + if self.env.use_object_obs: + keys += ["object-state"] + # Add image obs if requested + if self.env.use_camera_obs: + keys += [f"{cam_name}_image" for cam_name in self.env.camera_names] + # Iterate over all robots to add to state + for idx in range(len(self.env.robots)): + keys += ["robot{}_proprio-state".format(idx)] + self.keys = keys + + # Gym specific attributes + self.env.spec = None + + # set up observation and action spaces + obs = self.env.reset() + + # Whether to flatten the observation space + self.flatten_obs: bool = flatten_obs + + if self.flatten_obs: + flat_ob = self._flatten_obs(obs) + self.obs_dim = flat_ob.size + high = np.inf * np.ones(self.obs_dim) + low = -high + self.observation_space = spaces.Box(low, high) + else: + + def get_box_space(sample): + """Util fn to obtain the space of a single numpy sample data""" + if np.issubdtype(sample.dtype, np.integer): + low = np.iinfo(sample.dtype).min + high = np.iinfo(sample.dtype).max + elif np.issubdtype(sample.dtype, np.inexact): + low = float("-inf") + high = float("inf") + else: + raise ValueError() + return spaces.Box(low=low, high=high, shape=sample.shape, dtype=sample.dtype) + + self.observation_space = spaces.Dict({key: get_box_space(obs[key]) for key in self.keys}) + + low, high = self.env.action_spec + self.action_space = spaces.Box(low, high) + + def _flatten_obs(self, obs_dict, verbose=False): + """ + Filters keys of interest out and concatenate the information. + + Args: + obs_dict (OrderedDict): ordered dictionary of observations + verbose (bool): Whether to print out to console as observation keys are processed + + Returns: + np.array: observations flattened into a 1d array + """ + ob_lst = [] + for key in self.keys: + if key in obs_dict: + if verbose: + print("adding key: {}".format(key)) + ob_lst.append(np.array(obs_dict[key]).flatten()) + return np.concatenate(ob_lst) + + def _filter_obs(self, obs_dict) -> dict: + """ + Filters keys of interest out of the observation dictionary, returning a filterd dictionary. + """ + return {key: obs_dict[key] for key in self.keys if key in obs_dict} + + def reset(self, seed=None, options=None): + """ + Extends env reset method to return observation instead of normal OrderedDict and optionally resets seed + + Returns: + 2-tuple: + - (np.array) observations from the environment + - (dict) an empty dictionary, as part of the standard return format + """ + if seed is not None: + if isinstance(seed, int): + np.random.seed(seed) + else: + raise TypeError("Seed must be an integer type!") + ob_dict = self.env.reset() + obs = self._flatten_obs(ob_dict) if self.flatten_obs else self._filter_obs(ob_dict) + return obs, {} + + def step(self, action): + """ + Extends vanilla step() function call to return observation instead of normal OrderedDict. + + Args: + action (np.array): Action to take in environment + + Returns: + 4-tuple: + + - (np.array) observations from the environment + - (float) reward from the environment + - (bool) episode ending after reaching an env terminal state + - (bool) episode ending after an externally defined condition + - (dict) misc information + """ + ob_dict, reward, terminated, info = self.env.step(action) + obs = self._flatten_obs(ob_dict) if self.flatten_obs else self._filter_obs(ob_dict) + return obs, reward, terminated, False, info + + def compute_reward(self, achieved_goal, desired_goal, info): + """ + Dummy function to be compatible with gym interface that simply returns environment reward + + Args: + achieved_goal: [NOT USED] + desired_goal: [NOT USED] + info: [NOT USED] + + Returns: + float: environment reward + """ + # Dummy args used to mimic Wrapper interface + return self.env.reward() + + def close(self): + """ + wrapper for calling underlying env close function + """ + self.env.close() diff --git a/third_party/robosuite/robosuite/wrappers/visualization_wrapper.py b/third_party/robosuite/robosuite/wrappers/visualization_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..64b847af6ee67acbe61353340bfbf06f2cb09c1e --- /dev/null +++ b/third_party/robosuite/robosuite/wrappers/visualization_wrapper.py @@ -0,0 +1,186 @@ +""" +This file implements a wrapper for visualizing important sites in a given environment. + +By default, this visualizes all sites possible for the environment. Visualization options +for a given environment can be found by calling `get_visualization_settings()`, and can +be set individually by calling `set_visualization_setting(setting, visible)`. +""" +import xml.etree.ElementTree as ET +from copy import deepcopy + +import numpy as np + +from robosuite.utils.mjcf_utils import new_body, new_geom, new_site +from robosuite.wrappers import Wrapper + +DEFAULT_INDICATOR_SITE_CONFIG = { + "type": "sphere", + "size": [0.03], + "rgba": [1, 0, 0, 0.5], +} + + +class VisualizationWrapper(Wrapper): + def __init__(self, env, indicator_configs=None): + """ + Initializes the data collection wrapper. Note that this automatically conducts a (hard) reset initially to make + sure indicators are properly added to the sim model. + + Args: + env (MujocoEnv): The environment to visualize + + indicator_configs (None or str or dict or list): Configurations to use for indicator objects. + + If None, no indicator objects will be used + + If a string, this should be `'default'`, which corresponds to single default spherical indicator + + If a dict, should specify a single indicator object config + + If a list, should specify specific indicator object configs to use for multiple indicators (which in + turn can either be `'default'` or a dict) + + As each indicator object is essentially a site element, each dict should map site attribute keywords to + values. Note that, at the very minimum, the `'name'` attribute MUST be specified for each indicator. See + http://www.mujoco.org/book/XMLreference.html#site for specific site attributes that can be specified. + """ + super().__init__(env) + + # Make sure that the environment is NOT using segmentation sensors, since we cannot use segmentation masks + # with visualization sites simultaneously + assert all( + seg is None for seg in env.camera_segmentations + ), "Cannot use camera segmentations with visualization wrapper!" + + # Standardize indicator configs + self.indicator_configs = None + if indicator_configs is not None: + self.indicator_configs = [] + if type(indicator_configs) in {str, dict}: + indicator_configs = [indicator_configs] + for i, indicator_config in enumerate(indicator_configs): + if indicator_config == "default": + indicator_config = deepcopy(DEFAULT_INDICATOR_SITE_CONFIG) + indicator_config["name"] = f"indicator{i}" + # Make sure name attribute is specified + assert "name" in indicator_config, "Name must be specified for all indicator object configurations!" + # Add this configuration to the internal array + self.indicator_configs.append(indicator_config) + + # Create internal dict to store visualization settings (set to True by default) + self._vis_settings = {vis: True for vis in self.env._visualizations} + + # Add the post-processor to make sure indicator objects get added to model before it's actually loaded in sim + self.env.set_xml_processor(processor=self._add_indicators_to_model) + + # Conduct a (hard) reset to make sure visualization changes propagate + reset_mode = self.env.hard_reset + self.env.hard_reset = True + self.reset() + self.env.hard_reset = reset_mode + + def get_indicator_names(self): + """ + Gets all indicator object names for this environment. + + Returns: + list: Indicator names for this environment. + """ + return ( + [ind_config["name"] for ind_config in self.indicator_configs] if self.indicator_configs is not None else [] + ) + + def set_indicator_pos(self, indicator, pos): + """ + Sets the specified @indicator to the desired position @pos + + Args: + indicator (str): Name of the indicator to set + pos (3-array): (x, y, z) Cartesian world coordinates to set the specified indicator to + """ + # Make sure indicator is valid + indicator_names = set(self.get_indicator_names()) + assert indicator in indicator_names, "Invalid indicator name specified. Valid options are {}, got {}".format( + indicator_names, indicator + ) + # Set the specified indicator + self.env.sim.model.body_pos[self.env.sim.model.body_name2id(indicator + "_body")] = np.array(pos) + + def get_visualization_settings(self): + """ + Gets all settings for visualizing this environment + + Returns: + list: Visualization keywords for this environment. + """ + return self._vis_settings.keys() + + def set_visualization_setting(self, setting, visible): + """ + Sets the specified @setting to have visibility = @visible. + + Args: + setting (str): Visualization keyword to set + visible (bool): True if setting should be visualized. + """ + assert ( + setting in self._vis_settings + ), "Invalid visualization setting specified. Valid options are {}, got {}".format( + self._vis_settings.keys(), setting + ) + self._vis_settings[setting] = visible + + def reset(self): + """ + Extends vanilla reset() function call to accommodate visualization + + Returns: + OrderedDict: Environment observation space after reset occurs + """ + ret = super().reset() + # Update any visualization + self.env.visualize(vis_settings=self._vis_settings) + return ret + + def step(self, action): + """ + Extends vanilla step() function call to accommodate visualization + + Args: + action (np.array): Action to take in 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 + """ + ret = super().step(action) + + # Update any visualization + self.env.visualize(vis_settings=self._vis_settings) + + return ret + + def _add_indicators_to_model(self, xml): + """ + Adds indicators to the mujoco simulation model + + Args: + xml (string): MJCF model in xml format, for the current simulation to be loaded + """ + if self.indicator_configs is not None: + root = ET.fromstring(xml) + worldbody = root.find("worldbody") + + for indicator_config in self.indicator_configs: + config = deepcopy(indicator_config) + indicator_body = new_body(name=config["name"] + "_body", pos=config.pop("pos", (0, 0, 0))) + indicator_body.append(new_site(**config)) + worldbody.append(indicator_body) + + xml = ET.tostring(root, encoding="utf8").decode("utf8") + + return xml diff --git a/third_party/robosuite/robosuite/wrappers/wrapper.py b/third_party/robosuite/robosuite/wrappers/wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..77c922dfdfc0fcd58109e4a36c7815dea4524cb8 --- /dev/null +++ b/third_party/robosuite/robosuite/wrappers/wrapper.py @@ -0,0 +1,135 @@ +""" +This file contains the base wrapper class for Mujoco environments. +Wrappers are useful for data collection and logging. Highly recommended. +""" + + +class Wrapper: + """ + Base class for all wrappers in robosuite. + + Args: + env (MujocoEnv): The environment to wrap. + """ + + def __init__(self, env): + self.env = env + + @classmethod + def class_name(cls): + return cls.__name__ + + def _warn_double_wrap(self): + """ + Utility function that checks if we're accidentally trying to double wrap an env + + Raises: + Exception: [Double wrapping env] + """ + env = self.env + while True: + if isinstance(env, Wrapper): + if env.class_name() == self.class_name(): + raise Exception("Attempted to double wrap with Wrapper: {}".format(self.__class__.__name__)) + env = env.env + else: + break + + def step(self, action): + """ + By default, run the normal environment step() function + + Args: + action (np.array): action to take in 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 + """ + return self.env.step(action) + + def reset(self): + """ + By default, run the normal environment reset() function + + Returns: + OrderedDict: Environment observation space after reset occurs + """ + return self.env.reset() + + def render(self, **kwargs): + """ + By default, run the normal environment render() function + + Args: + **kwargs (dict): Any args to pass to environment render function + """ + return self.env.render(**kwargs) + + def observation_spec(self): + """ + By default, grabs the normal environment observation_spec + + Returns: + OrderedDict: Observations from the environment + """ + return self.env.observation_spec() + + @property + def action_spec(self): + """ + By default, grabs the normal environment action_spec + + Returns: + 2-tuple: + + - (np.array) minimum (low) action values + - (np.array) maximum (high) action values + """ + return self.env.action_spec + + @property + def action_dim(self): + """ + By default, grabs the normal environment action_dim + + Returns: + int: Action space dimension + """ + return self.env.dof + + @property + def unwrapped(self): + """ + Grabs unwrapped environment + + Returns: + env (MujocoEnv): Unwrapped environment + """ + if hasattr(self.env, "unwrapped"): + return self.env.unwrapped + else: + return self.env + + # this method is a fallback option on any methods the original env might support + def __getattr__(self, attr): + # using getattr ensures that both __getattribute__ and __getattr__ (fallback) get called + # (see https://stackoverflow.com/questions/3278077/difference-between-getattr-vs-getattribute) + orig_attr = getattr(self.env, attr) + if callable(orig_attr): + + def hooked(*args, **kwargs): + result = orig_attr(*args, **kwargs) + # prevent wrapped_class from becoming unwrapped + # NOTE: had to use "is" to prevent errors when returning numpy arrays from a wrapped method + if result is self.env: + return self + return result + + return hooked + else: + return orig_attr