repo
stringlengths
3
91
file
stringlengths
16
152
code
stringlengths
0
3.77M
file_length
int64
0
3.77M
avg_line_length
float64
0
16k
max_line_length
int64
0
273k
extension_type
stringclasses
1 value
robogym
robogym-master/robogym/envs/rearrange/blocks_pickandplace.py
from robogym.envs.rearrange.blocks import BlockRearrangeEnv from robogym.envs.rearrange.common.base import RearrangeEnvConstants from robogym.envs.rearrange.goals.pickandplace import PickAndPlaceGoal from robogym.envs.rearrange.simulation.blocks import BlockRearrangeSim class BlocksPickAndPlaceEnv(BlockRearrangeEnv): @classmethod def build_goal_generation( cls, constants: RearrangeEnvConstants, mujoco_simulation: BlockRearrangeSim ): return PickAndPlaceGoal(mujoco_simulation, constants.goal_args) make_env = BlocksPickAndPlaceEnv.build
573
34.875
83
py
robogym
robogym-master/robogym/envs/rearrange/blocks_attached.py
from typing import TypeVar import attr from robogym.envs.rearrange.common.base import ( RearrangeEnv, RearrangeEnvConstants, RearrangeEnvParameters, ) from robogym.envs.rearrange.goals.attached_block_state import AttachedBlockStateGoal from robogym.envs.rearrange.simulation.blocks import ( BlockRearrangeSim, BlockRearrangeSimParameters, ) from robogym.robot_env import build_nested_attr @attr.s(auto_attribs=True) class AttachedBlockRearrangeEnvParameters(RearrangeEnvParameters): simulation_params: BlockRearrangeSimParameters = build_nested_attr( BlockRearrangeSimParameters, default=dict(num_objects=8) ) PType = TypeVar("PType", bound=AttachedBlockRearrangeEnvParameters) CType = TypeVar("CType", bound=RearrangeEnvConstants) SType = TypeVar("SType", bound=BlockRearrangeSim) class AttachedBlockRearrangeEnv(RearrangeEnv[PType, CType, SType]): @classmethod def build_goal_generation(cls, constants: CType, mujoco_simulation: SType): return AttachedBlockStateGoal(mujoco_simulation, args=constants.goal_args) make_env = AttachedBlockRearrangeEnv.build
1,119
29.27027
84
py
robogym
robogym-master/robogym/envs/rearrange/ycb.py
import logging import os from typing import Dict, List import attr from robogym.envs.rearrange.common.mesh import ( MeshRearrangeEnv, MeshRearrangeEnvConstants, MeshRearrangeEnvParameters, ) from robogym.envs.rearrange.common.utils import find_meshes_by_dirname from robogym.envs.rearrange.simulation.mesh import MeshRearrangeSim logger = logging.getLogger(__name__) def find_ycb_meshes() -> Dict[str, list]: return find_meshes_by_dirname("ycb") def extract_object_name(mesh_files: List[str]) -> str: """ Given a list of mesh file paths, this method returns an consistent name for the object :param mesh_files: List of paths to mesh files on disk for the object :return: Consistent name for the object based on the mesh file paths """ dir_names = sorted(set([os.path.basename(os.path.dirname(p)) for p in mesh_files])) if len(dir_names) != 1: logger.warning( f"Multiple directory names found: {dir_names} for object: {mesh_files}." ) return dir_names[0] @attr.s(auto_attribs=True) class YcbRearrangeEnvConstants(MeshRearrangeEnvConstants): # Whether to sample meshes with replacement sample_with_replacement: bool = True class YcbRearrangeEnv( MeshRearrangeEnv[ MeshRearrangeEnvParameters, YcbRearrangeEnvConstants, MeshRearrangeSim, ] ): MESH_FILES = find_ycb_meshes() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._cached_object_names: Dict[str, str] = {} def _recreate_sim(self) -> None: # Call super to recompute `self.parameters.simulation_params.mesh_files`. super()._recreate_sim() # Recompute object names from new mesh files self._cached_object_names = {} for obj_group in self.mujoco_simulation.object_groups: mesh_obj_name = extract_object_name(obj_group.mesh_files) for i in obj_group.object_ids: self._cached_object_names[f"object{i}"] = mesh_obj_name def _sample_object_meshes(self, num_groups: int) -> List[List[str]]: if self.parameters.mesh_names is not None: candidates = [ files for dir_name, files in self.MESH_FILES.items() if dir_name in self.parameters.mesh_names ] else: candidates = list(self.MESH_FILES.values()) assert len(candidates) > 0, f"No mesh file for {self.parameters.mesh_names}." candidates = sorted(candidates) replace = self.constants.sample_with_replacement indices = self._random_state.choice( len(candidates), size=num_groups, replace=replace ) return [candidates[i] for i in indices] def _get_simulation_info(self) -> dict: simulation_info = super()._get_simulation_info() simulation_info.update(self._cached_object_names) return simulation_info make_env = YcbRearrangeEnv.build
2,976
30.670213
90
py
robogym
robogym-master/robogym/envs/rearrange/blocks_train.py
import attr import numpy as np from robogym.envs.rearrange.common.base import ( RearrangeEnv, RearrangeEnvConstants, RearrangeEnvParameters, ) from robogym.envs.rearrange.simulation.blocks import ( BlockRearrangeSim, BlockRearrangeSimParameters, ) from robogym.robot_env import build_nested_attr @attr.s(auto_attribs=True) class BlockTrainRearrangeEnvConstants(RearrangeEnvConstants): # If true, we randomize width, height, depth of each block object independently. # If false, we use regular-shaped cube blocks with weight == height == depth. use_cuboid: bool = False goal_generation: str = "train" @attr.s(auto_attribs=True) class BlockTrainRearrangeEnvParameters(RearrangeEnvParameters): simulation_params: BlockRearrangeSimParameters = build_nested_attr( BlockRearrangeSimParameters ) class BlockTrainRearrangeEnv( RearrangeEnv[ BlockTrainRearrangeEnvParameters, BlockTrainRearrangeEnvConstants, BlockRearrangeSim, ] ): def _apply_object_size_scales(self): if not self.constants.use_cuboid: super()._apply_object_size_scales() return # Randomize width, length and height of each block. object_scales_by_group = np.exp( self._random_state.uniform( low=-self.parameters.object_scale_low, high=self.parameters.object_scale_high, size=(self.mujoco_simulation.num_groups, 3), ) ) object_scales = np.array( [ object_scales_by_group[i].copy() for i, obj_group in enumerate(self.mujoco_simulation.object_groups) for _ in range(obj_group.count) ] ) assert object_scales.shape == (self.mujoco_simulation.num_objects, 3) self.mujoco_simulation.rescale_object_sizes(object_scales) make_env = BlockTrainRearrangeEnv.build
1,944
29.390625
84
py
robogym
robogym-master/robogym/envs/rearrange/wordblocks.py
import logging from typing import List import attr import numpy as np from robogym.envs.rearrange.common.base import ( RearrangeEnv, RearrangeEnvConstants, RearrangeEnvParameters, ) from robogym.envs.rearrange.common.utils import update_object_body_quat from robogym.envs.rearrange.goals.object_state_fixed import ObjectFixedStateGoal from robogym.envs.rearrange.simulation.base import ( ObjectGroupConfig, RearrangeSimParameters, ) from robogym.envs.rearrange.simulation.wordblocks import WordBlocksSim from robogym.robot_env import build_nested_attr from robogym.utils.rotation import quat_from_angle_and_axis logger = logging.getLogger(__name__) @attr.s(auto_attribs=True) class WordBlocksEnvConstants(RearrangeEnvConstants): rainbow_mode: bool = False @attr.s(auto_attribs=True) class WordBlocksEnvParameters(RearrangeEnvParameters): simulation_params: RearrangeSimParameters = build_nested_attr( RearrangeSimParameters, default=dict(num_objects=6) ) class WordBlocksEnv( RearrangeEnv[WordBlocksEnvParameters, WordBlocksEnvConstants, WordBlocksSim] ): def _sample_random_object_groups( self, dedupe_objects: bool = False ) -> List[ObjectGroupConfig]: return super()._sample_random_object_groups(dedupe_objects=True) def _sample_object_colors(self, num_groups: int): if self.constants.rainbow_mode: colors = [ [1.0, 0.0, 0.0, 1.0], [1.0, 0.647, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0], [0.0, 0.502, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.294, 0.0, 0.51, 1.0], ] else: colors = [[0.702, 0.522, 0.212, 1.0]] * 6 return colors def _reset(self): super()._reset() # rotate A & I block a bit. new_quat = quat_from_angle_and_axis(0.38, np.array([0, 0, 1.0])) update_object_body_quat( self.mujoco_simulation.mj_sim, "target:object4", new_quat ) update_object_body_quat( self.mujoco_simulation.mj_sim, "target:object5", new_quat ) @classmethod def build_goal_generation(cls, constants, mujoco_simulation): return ObjectFixedStateGoal( mujoco_simulation, args=constants.goal_args, relative_placements=np.array( [ [0.5, 0.05], [0.5, 0.2], [0.5, 0.35], [0.5, 0.65], [0.5, 0.8], [0.5, 0.95], ] ), ) make_env = WordBlocksEnv.build
2,661
28.252747
80
py
robogym
robogym-master/robogym/envs/rearrange/dominos.py
import attr from robogym.envs.rearrange.common.base import ( RearrangeEnv, RearrangeEnvConstants, RearrangeEnvParameters, ) from robogym.envs.rearrange.goals.dominos import DominoStateGoal from robogym.envs.rearrange.goals.object_state import GoalArgs from robogym.envs.rearrange.goals.train_state import TrainStateGoal from robogym.envs.rearrange.simulation.dominos import ( DominosRearrangeSim, DominosRearrangeSimParameters, ) from robogym.robot_env import build_nested_attr @attr.s(auto_attribs=True) class DominosRearrangeEnvParameters(RearrangeEnvParameters): simulation_params: DominosRearrangeSimParameters = build_nested_attr( DominosRearrangeSimParameters, ) @attr.s(auto_attribs=True) class DominosRearrangeEnvConstants(RearrangeEnvConstants): # If set then we will setup the goal as a `DominoStateGoal` where we try to place # dominos in an arc. Otherise, use the same goal logic as `TrainStateGoal`. is_holdout: bool = False goal_args: GoalArgs = build_nested_attr( GoalArgs, default=dict(rot_dist_type="mod180") ) class DominosRearrangeEnv( RearrangeEnv[ DominosRearrangeEnvParameters, DominosRearrangeEnvConstants, DominosRearrangeSim, ] ): @classmethod def build_goal_generation(cls, constants, mujoco_simulation): if constants.is_holdout: return DominoStateGoal(mujoco_simulation, args=constants.goal_args) else: return TrainStateGoal(mujoco_simulation, args=constants.goal_args) make_env = DominosRearrangeEnv.build
1,588
29.557692
85
py
robogym
robogym-master/robogym/envs/rearrange/blocks_duplicate.py
from typing import List from robogym.envs.rearrange.blocks import BlockRearrangeEnv from robogym.envs.rearrange.simulation.base import ObjectGroupConfig class DuplicateBlockRearrangeEnv(BlockRearrangeEnv): def _sample_random_object_groups( self, dedupe_objects: bool = False ) -> List[ObjectGroupConfig]: """ Create one group of block objects with a random color. Overwrite the object groups info to contain only one group for all the blocks. """ object_groups = super()._sample_random_object_groups() num_objects = self.parameters.simulation_params.num_objects first_object_group = object_groups[0] first_object_group.count = num_objects first_object_group.object_ids = list(range(num_objects)) object_groups = [first_object_group] return object_groups make_env = DuplicateBlockRearrangeEnv.build
908
33.961538
86
py
robogym
robogym-master/robogym/envs/rearrange/blocks.py
import attr from robogym.envs.rearrange.common.base import ( RearrangeEnv, RearrangeEnvConstants, RearrangeEnvParameters, ) from robogym.envs.rearrange.simulation.blocks import ( BlockRearrangeSim, BlockRearrangeSimParameters, ) from robogym.robot_env import build_nested_attr @attr.s(auto_attribs=True) class BlockRearrangeEnvParameters(RearrangeEnvParameters): simulation_params: BlockRearrangeSimParameters = build_nested_attr( BlockRearrangeSimParameters ) class BlockRearrangeEnv( RearrangeEnv[BlockRearrangeEnvParameters, RearrangeEnvConstants, BlockRearrangeSim] ): OBJECT_COLORS = ( (1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1), (1, 1, 0, 1), (0, 1, 1, 1), (1, 0, 1, 1), (0, 0, 0, 1), (1, 1, 1, 1), ) def _sample_object_colors(self, num_groups: int): return self._random_state.permutation(self.OBJECT_COLORS)[:num_groups] make_env = BlockRearrangeEnv.build
993
23.243902
87
py
robogym
robogym-master/robogym/envs/rearrange/common/base.py
import abc import logging from typing import Any, Dict, List, Optional, Tuple, TypeVar, Union import attr import numpy as np import scipy from gym.envs.robotics import utils import robogym.utils.rotation as rotation from robogym.envs.rearrange.common.utils import ( load_all_materials, load_material_args, place_objects_in_grid, place_objects_with_no_constraint, sample_group_counts, stabilize_objects, ) from robogym.envs.rearrange.goals.object_state import GoalArgs, ObjectStateGoal from robogym.envs.rearrange.goals.train_state import TrainStateGoal from robogym.envs.rearrange.observation.common import ( MujocoGoalImageObservationProvider, MujocoImageObservationProvider, ) from robogym.envs.rearrange.simulation.base import ( ObjectGroupConfig, RearrangeSimParameters, RearrangeSimulationInterface, ) from robogym.mujoco.constants import MujocoEquality from robogym.observation.common import SyncType from robogym.observation.image import ImageObservation from robogym.randomization.env import build_randomizable_param from robogym.randomization.sim import ( GenericSimRandomizer, GeomSolimpRandomizer, GeomSolrefRandomizer, GravityRandomizer, JointMarginRandomizer, PidRandomizer, ) from robogym.robot.robot_interface import RobotControlParameters from robogym.robot_env import ObservationMapValue as omv from robogym.robot_env import ( RobotEnv, RobotEnvConstants, RobotEnvParameters, build_nested_attr, get_generic_param_type, ) from robogym.utils.env_utils import InvalidSimulationError from robogym.wrappers.util import ( BinSpacing, ClipRewardWrapper, DiscretizeActionWrapper, SmoothActionWrapper, ) logger = logging.getLogger(__name__) VISION_OBS = "vision_obs" VISION_OBS_MOBILE = "vision_obs_mobile" VISION_GOAL = "vision_goal" @attr.s(auto_attribs=True) class EncryptEnvConstants: enabled: bool = False use_dummy: bool = False input_shape: List[int] = [200, 200, 3] distortable_keys: List[str] = [] encryption_prefix: str = "enc_" last_activation: str = "TANH" # Set hardcoded values for randomization parameters here. # This is useful for creating an evaluator with fixed parameters (i.e. not subject to ADR). param_values: Optional[Dict[str, Union[float, int]]] = None # Whether we should use different Encryption networks for each input key. use_separate_networks_per_key: bool = True @attr.s(auto_attribs=True) class VisionArgs: # The size of the rendered obs and goal images in pixel. image_size: int = 200 # Whether rendering high-res images, only used in examine_vision. high_res_mujoco: bool = False # Names for static cameras. camera_names: List[str] = ["vision_cam_front"] # Camera used for mobile cameras. They are only used # for obs images. mobile_camera_names: List[str] = ["vision_cam_wrist"] def all_camera_names(self): """Returns all camera names specified by static and mobile camera lists.""" return self.mobile_camera_names + self.camera_names @attr.s(auto_attribs=True) class RearrangeEnvConstants(RobotEnvConstants): mujoco_substeps: int = 40 mujoco_timestep: float = 0.001 # If this is set to true, new "masked_*" observation keys will be created with goal and # object states where objects outside the placement area will be zeroed out. mask_obs_outside_placement_area: bool = False # If use vision observation. vision: bool = False vision_args: VisionArgs = build_nested_attr(VisionArgs) # lambda range in exponential decay distribution for sampling duplicated object counts. sample_lam_low: float = 0.1 sample_lam_high: float = 5.0 ##################### # Success/Rewards # Only the metrics present here will be used to compute goal distance success_threshold: dict = {"obj_pos": 0.04, "obj_rot": 0.2} # Max timesteps per object for each goal until timeout. # `constants.max_timesteps_per_goal` will be overwritten by this x num. object. max_timesteps_per_goal_per_obj: int = 200 # Reward per object that is achieved if all distances are under `success_threshold` goal_reward_per_object: float = 1.0 ##################### # Goal settings goal_args: GoalArgs = build_nested_attr(GoalArgs) encrypt_env_constants: EncryptEnvConstants = build_nested_attr(EncryptEnvConstants) # Action spacing function to be used by the DiscretizeActionWrapper action_spacing: BinSpacing = attr.ib( default=BinSpacing.LINEAR, validator=attr.validators.in_(BinSpacing), converter=BinSpacing, ) def has_mobile_cameras_enabled(self): return self.vision and len(self.vision_args.mobile_camera_names) > 0 # This setting causes the env to ignore all actions and teleport directly to the goal. # This is useful for training a standalone goal classifier with a balanced distribution of # goal/non-goal images. teleport_to_goal: bool = False # Goal generation for env. # state: Use fully random object state (pos + rot) as goal. # image: Use real image as goal. # train: Use random object state controlled by ADR params as goal. goal_generation: str = attr.ib( default="state", validator=attr.validators.in_(["state", "image", "train"]) ) # Fix initial state # for debugging purpose, this option starts episode from fixed initial state again and # again. Initial state is determined by the `starting_seed`. use_fixed_seed: bool = False ##################### # Self play settings. stabilize_objects: bool = True @attr.s(auto_attribs=True) class RearrangeRobotControlParameters(RobotControlParameters): """ Robot control parameters – defined as parameters since max_position_change can be subject to ADR randomization """ # refer to RobotControlParameters.default_max_pos_change_for_solver to set a # reasonable default here. max_position_change: float = build_randomizable_param(0.1, low=0.01, high=2.5) @attr.s(auto_attribs=True) class RearrangeEnvParameters(RobotEnvParameters): robot_control_params: RearrangeRobotControlParameters = build_nested_attr( RearrangeRobotControlParameters ) simulation_params: RearrangeSimParameters = build_nested_attr( RearrangeSimParameters ) # If true, turn on debugging features like visualizing bounding boxes. debug: bool = False # the range of object rescaling ratios (in log scale) object_scale_low: float = build_randomizable_param(0.0, low=0.0, high=0.5) object_scale_high: float = build_randomizable_param(0.0, low=0.0, high=1.8) # List of materials available for this environment. If multiple materials are specified # we will randomly select material from the list for each object. # If the list is None, all materials under materials folder will be considered. # If the list is empty, no material specific mujoco args will be applied. material_names: Optional[List[str]] = ["default"] PType = TypeVar("PType", bound=RearrangeEnvParameters) CType = TypeVar("CType", bound=RearrangeEnvConstants) SType = TypeVar("SType", bound=RearrangeSimulationInterface) class RearrangeEnv(RobotEnv[PType, CType, SType], abc.ABC): """ Base env setup for Rearrange. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Cache the boundary of placement area per reset to speed up calculation of masked observation. self._placement_area_boundary = ( self.mujoco_simulation.extract_placement_area_boundary() ) def _build_observation_providers(self): providers = {} if self.constants.vision: image_size = self.constants.vision_args.image_size # Default to mujoco based rendering. providers.update( { "image": MujocoImageObservationProvider( self.mujoco_simulation, self.constants.vision_args.camera_names, image_size, ), "image_mobile": MujocoImageObservationProvider( self.mujoco_simulation, self.constants.vision_args.mobile_camera_names, image_size, ), "goal_image": MujocoGoalImageObservationProvider( self.mujoco_simulation, self.constants.vision_args.camera_names, image_size, self.goal_info, "qpos_goal", hide_robot=self.constants.goal_args.goal_hide_robot, ), } ) if self.constants.vision_args.high_res_mujoco: providers.update( { "image_high_res": MujocoImageObservationProvider( self.mujoco_simulation, self.constants.vision_args.camera_names, 600, ), "image_mobile_high_res": MujocoImageObservationProvider( self.mujoco_simulation, self.constants.vision_args.mobile_camera_names, 600, ), "goal_image_high_res": MujocoGoalImageObservationProvider( self.mujoco_simulation, self.constants.vision_args.camera_names, 600, self.goal_info, "qpos_goal", hide_robot=self.constants.goal_args.goal_hide_robot, ), } ) return providers def _default_observation_map(self): obs_map = {} if self.constants.vision: obs_map.update( { VISION_OBS: omv({"image": ImageObservation}), VISION_OBS_MOBILE: omv({"image_mobile": ImageObservation}), VISION_GOAL: omv({"goal_image": ImageObservation}), } ) if self.constants.vision_args.high_res_mujoco: obs_map.update( { VISION_OBS + "_high_res": omv({"image_high_res": ImageObservation}), VISION_OBS_MOBILE + "_high_res": omv({"image_mobile_high_res": ImageObservation}), VISION_GOAL + "_high_res": omv({"goal_image_high_res": ImageObservation}), } ) return obs_map def _mask_goal_observation( self, obs: dict, goal_objects_in_placement_area: np.ndarray ) -> dict: """Create masked goal observation. """ if not self.constants.mask_obs_outside_placement_area: return obs # Add goal observations (with optional masking). # 1.0 if an object is within the placement area. mask = goal_objects_in_placement_area.astype(np.float).reshape(-1, 1) assert mask.ndim == obs["goal_obj_pos"].ndim assert mask.shape[0] == obs["goal_obj_pos"].shape[0] obs["goal_placement_mask"] = mask.copy() # Mask all other goal-related observations. Note that We do not mask qpos_goal since # it contains the robot joints. qpos is only used for image rendering and policy should # not observe it. goal_obs_keys = [ "goal_obj_pos", "goal_obj_rot", "rel_goal_obj_pos", "rel_goal_obj_rot", ] for k in goal_obs_keys: obs[f"masked_{k}"] = obs[k] * mask return obs def _mask_object_observation(self, obs: dict) -> dict: """Create masked object state observation. """ if not self.constants.mask_obs_outside_placement_area: return obs assert self._placement_area_boundary is not None mask = self.mujoco_simulation.check_objects_in_placement_area( obs["obj_pos"].copy(), placement_area_boundary=self._placement_area_boundary, margin=self.constants.goal_args.mask_margin, soft=self.constants.goal_args.soft_mask, ) # 1.0 if an object is in the placement area. mask = mask.astype(np.float).reshape(-1, 1) assert mask.ndim == obs["obj_pos"].ndim assert mask.shape[0] == obs["obj_pos"].shape[0] obs["placement_mask"] = mask.copy() obs_keys_to_mask = [ "obj_pos", "obj_rot", "obj_rel_pos", "obj_vel_pos", "obj_vel_rot", "obj_gripper_contact", "obj_bbox_size", "obj_colors", ] for k in obs_keys_to_mask: obs[f"masked_{k}"] = obs[k] * mask return obs def _observe_simple(self): """ Default observation for the environment. An observation can be added here if it meets one of the condition below: 1. It's cheap to fetch on a per step basic and doesn't cause side effect even if not used by policy. 2. It's shared across all variances of the env. """ robot_obs = self.mujoco_simulation.robot.observe() obs = { "obj_pos": self.mujoco_simulation.get_object_pos(), "obj_rel_pos": self.mujoco_simulation.get_object_rel_pos(), "obj_vel_pos": self.mujoco_simulation.get_object_vel_pos(), "obj_rot": self.mujoco_simulation.get_object_rot(), "obj_vel_rot": self.mujoco_simulation.get_object_vel_rot(), "robot_joint_pos": robot_obs.joint_positions(), "gripper_pos": robot_obs.tcp_xyz(), "gripper_velp": robot_obs.tcp_vel(), "gripper_controls": robot_obs.gripper_controls(), "gripper_qpos": robot_obs.gripper_qpos(), "gripper_vel": robot_obs.gripper_vel(), "qpos": self.mujoco_simulation.qpos, "qpos_goal": self._goal["qpos_goal"].copy(), "goal_obj_pos": self._goal["obj_pos"].copy(), "goal_obj_rot": self._goal["obj_rot"].copy(), "is_goal_achieved": np.array([self._is_goal_achieved], np.int32), "rel_goal_obj_pos": self._goal_info_dict["rel_goal_obj_pos"].copy(), "rel_goal_obj_rot": self._goal_info_dict["rel_goal_obj_rot"].copy(), "obj_gripper_contact": self.mujoco_simulation.get_object_gripper_contact(), "obj_bbox_size": self.mujoco_simulation.get_object_bounding_box_sizes(), "obj_colors": self.mujoco_simulation.get_object_colors(), "safety_stop": np.array([robot_obs.is_in_safety_stop()]), "tcp_force": robot_obs.tcp_force(), "tcp_torque": robot_obs.tcp_torque(), } if self.constants.mask_obs_outside_placement_area: obs = self._mask_goal_observation( obs, self._goal["goal_objects_in_placement_area"].copy() ) obs = self._mask_object_observation(obs) return obs @classmethod def build_simulation(cls, constants: CType, parameters: PType) -> SType: constants.max_timesteps_per_goal = ( constants.max_timesteps_per_goal_per_obj * parameters.simulation_params.num_objects ) simulation_type = get_generic_param_type(cls, 2, RearrangeSimulationInterface) return simulation_type.build( robot_control_params=parameters.robot_control_params, simulation_params=parameters.simulation_params, n_substeps=constants.mujoco_substeps, mujoco_timestep=constants.mujoco_timestep, ) @classmethod def build_robot(cls, mujoco_simulation: SType, physical): return mujoco_simulation.robot @property def robot(self): return self.mujoco_simulation.robot ############################################################################################### # Methods to ensure we handle sim recreation properly. def _initialize_sim_state(self): if self.parameters.robot_control_params.is_joint_actuated(): for idx, eq_type in enumerate(self.mujoco_simulation.mj_sim.model.eq_type): if eq_type == MujocoEquality.mjEQ_WELD.value: self.mujoco_simulation.mj_sim.model.eq_active[idx] = 0 else: utils.reset_mocap_welds(self.sim) self.sim.forward() tcp_pos = self.mujoco_simulation.mj_sim.data.get_body_xpos( "robot0:gripper_base" ) tcp_quat = self.sim.data.get_body_xquat("robot0:gripper_base") self.mujoco_simulation.mj_sim.data.set_mocap_pos("robot0:mocap", tcp_pos) self.mujoco_simulation.mj_sim.data.set_mocap_quat("robot0:mocap", tcp_quat) for _ in range(10): self.mujoco_simulation.step() self.robot.reset() def _randomize_object_initial_positions(self): """ Randomize initial position for each object. """ object_pos, is_valid = self._generate_object_placements() if not is_valid: raise InvalidSimulationError("Object placement is invalid.") self.mujoco_simulation.set_object_pos(object_pos) def _randomize_object_initial_states(self): # It's important to re-scale and rotate objects before placement since this # will influence their placement. self._randomize_object_initial_rotations() self._randomize_object_initial_positions() def _randomize_robot_initial_position(self): action = self.action_space.sample() if self.parameters.n_random_initial_steps < 1: return for _ in range(self.parameters.n_random_initial_steps): self._set_action(action) self.mujoco_simulation.step() self._set_action(action * 0.0) for _ in range(100): # calling set_action each tick is necessary for the robot to reach stability with relative actions self._set_action(action * 0.0) self.mujoco_simulation.step() def _randomize_object_groups(self, dedupe_objects: bool = False): """ :param dedupe_objects: if set to True, every object is different, no duplicated ones. """ object_groups = self._sample_attributed_object_groups(dedupe_objects) self._set_object_groups(object_groups) def _set_object_groups(self, object_groups: List[ObjectGroupConfig]): self.parameters.simulation_params.object_groups = object_groups def _sample_attributed_object_groups(self, dedupe_objects: bool = False): object_groups = self._sample_random_object_groups(dedupe_objects) attrs_per_group = self._sample_group_attributes(len(object_groups)) return self._set_group_attributes(object_groups, attrs_per_group) def _sample_random_object_groups( self, dedupe_objects: bool = False ) -> List[ObjectGroupConfig]: """ :param dedupe_objects: if set to True, every object is different, no duplicated ones. """ num_objects = self.mujoco_simulation.num_objects if dedupe_objects: group_counts = [1] * num_objects else: group_counts = sample_group_counts( self._random_state, num_objects, lam_low=self.constants.sample_lam_low, lam_high=self.constants.sample_lam_high, ) assert len(self.parameters.simulation_params.object_groups) > 0 obj_group_config_type = type(self.parameters.simulation_params.object_groups[0]) num_groups = len(group_counts) object_groups = [] obj_id = 0 for i in range(num_groups): # Initialize with object counts obj_group = obj_group_config_type(count=group_counts[i]) # Set up object ids obj_group.object_ids = list(range(obj_id, obj_id + group_counts[i])) obj_id += group_counts[i] object_groups.append(obj_group) return object_groups def _set_group_attributes( self, object_groups: List[ObjectGroupConfig], attrs_per_group: Dict[str, list] ) -> List[ObjectGroupConfig]: assert len(object_groups) > 0 obj_group_config_type = type(object_groups[0]) num_groups = len(object_groups) for i in range(num_groups): # Set up scale, color & material args. for attr_name, attr_values in attrs_per_group.items(): assert hasattr( object_groups[i], attr_name ), f"{obj_group_config_type} has no attribute {attr_name}." setattr(object_groups[i], attr_name, attr_values[i]) return object_groups def _sample_group_attributes(self, num_groups: int) -> Dict[str, list]: attrs_per_group = { "material_args": self._sample_object_materials(num_groups), "color": self._sample_object_colors(num_groups), "scale": self._sample_object_size_scales(num_groups), } assert all(len(v) == num_groups for k, v in attrs_per_group.items()) return attrs_per_group def _sample_object_materials(self, num_groups: int) -> List[Dict[str, Any]]: if not self.parameters.material_names: self.parameters.material_names = load_all_materials() material_args = { m: load_material_args(m) for m in set(self.parameters.material_names) } names = self._random_state.choice( self.parameters.material_names, size=num_groups ) return [material_args[name] for name in names] def _sample_object_colors( self, num_groups: int ) -> List[Union[np.ndarray, list, tuple]]: random_colors = self._random_state.random((num_groups, 4)) random_colors[:, -1] = 1.0 return random_colors def _sample_object_size_scales(self, num_groups: int): return np.exp( self._random_state.uniform( low=-self.parameters.object_scale_low, high=self.parameters.object_scale_high, size=num_groups, ) ) def _apply_object_colors(self): obj_groups = self.mujoco_simulation.object_groups obj_colors = [g.color.copy() for g in obj_groups for _ in range(g.count)] self.mujoco_simulation.set_object_colors(obj_colors) def _apply_object_size_scales(self): obj_groups = self.mujoco_simulation.object_groups obj_scales = [g.scale for g in obj_groups for _ in range(g.count)] self.mujoco_simulation.rescale_object_sizes(obj_scales) def _sample_default_quaternions(self): num_objects = self.mujoco_simulation.num_objects quats = rotation.quat_from_angle_and_axis( angle=self._random_state.uniform(0.0, 2 * np.pi, size=num_objects), axis=np.array([[0, 0, 1.0]] * num_objects), ) assert quats.shape == (num_objects, 4) return quats def _randomize_object_initial_rotations(self): """ Randomize initial rotation for each object. """ quats = self._sample_object_initial_rotations() self._set_object_initial_rotations(quats) def _sample_object_initial_rotations(self): return self._sample_default_quaternions() def _set_object_initial_rotations(self, quats: np.ndarray): self.mujoco_simulation.set_object_quat(quats) self.mujoco_simulation.set_target_quat(quats) self.mujoco_simulation.forward() def _randomize_camera(self): """ An reimplementation of jitter mode of ORRB::CameraRandomizer::RunComponent https://github.com/openai/orrb/blob/master/unity/Assets/Scripts/Randomizers/CameraRandomizer.cs#L73 It is slightly different as it follows the curriculum defined by fovy/pos/quat radius. """ nc = len(self.mujoco_simulation.initial_values["camera_fovy"]) fovy_delta = ( self._random_state.uniform(-1.0, 1.0, nc) * self.mujoco_simulation.simulation_params.camera_fovy_radius ) # pos delta is sampled from a sphere with pos_radius distance away from original pos. pos_delta = [np.zeros(3)] * nc for i in range(nc): vec = self._random_state.randn(3) vec /= np.linalg.norm(vec) pos_delta[i] = vec pos_delta = ( np.array(pos_delta) * self.mujoco_simulation.simulation_params.camera_pos_radius ) """ quat delta is sampled from fixed quat_radius (in radian) rotation around a uniform sampled axis, adapted from original c# code here, except the uniform sampling: Vector3 axis = Random.rotationUniform * Vector3.up; camera_state.camera.transform.localRotation = camera_state.rot * Quaternion.AngleAxis(Random.Range(rot_min, rot_max) * Mathf.Rad2Deg, axis); """ quat_delta = [np.zeros(4)] * nc up = np.array([0, 1, 0]) angle = self.mujoco_simulation.simulation_params.camera_quat_radius for i in range(nc): uniform_quat = rotation.uniform_quat(self._random_state) axis = rotation.quat_rot_vec(uniform_quat, up) quat_delta[i] = rotation.quat_from_angle_and_axis(angle, axis) self.mujoco_simulation.reset_camera(fovy_delta, pos_delta, quat_delta) def _randomize_lighting(self): """ Randomizes the position and direction of all lights, and randomizes the ambient and diffuse headlight intensities. """ # Controls the fraction of valid positions for the light which are able to be sampled. range_fraction = self.mujoco_simulation.simulation_params.light_pos_range positions = [] directions = [] n_lights = len(self.mujoco_simulation.get_light_positions()) for i in range(n_lights): # Randomly sample (x, y, z) coordinates for position independently, uniformly randomly # from their valid range (which is modulated by `range_fraction`). Given these # coordinates, we then normalize the resulting position vector and scale it such that # the light is always 4m away from the origin. You can view these coordinates as points # on a surface of the sphere centered at the origin with radius 4m; this surface # initially is just the point (0, 0, 4) and then expands outwards according to # `range_fraction`. x = self._random_state.uniform( -0.25 * range_fraction, 0.75 * range_fraction ) y = range_fraction * self._random_state.uniform(-4.0, 4.0) z = self._random_state.uniform(4.0 - (range_fraction * 4.0), 4.0) raw_pos = np.array([x, y, z]) pos_norm = np.linalg.norm(raw_pos) # Keep the light 4 m away from the origin. pos = (raw_pos / pos_norm) * 4.0 # Direction is unit-norm of the negative position vector direction = -raw_pos / pos_norm positions.append(pos) directions.append(direction) # Randomize the intensity of diffuse and ambient headlights. diffuse_intensity = ( self.mujoco_simulation.simulation_params.light_diffuse_intensity ) ambient_intensity = ( self.mujoco_simulation.simulation_params.light_ambient_intensity ) self.mujoco_simulation.set_lighting( np.array(positions), np.array(directions), diffuse_intensity, ambient_intensity, ) def reset_goal( self, update_seed=False, sync_type=SyncType.RESET_GOAL, raise_when_invalid=True ): obs = super().reset_goal(update_seed=update_seed, sync_type=sync_type) # Check if goal placement is valid here. if not self._goal["goal_valid"]: if raise_when_invalid: raise InvalidSimulationError( self._goal.get("goal_invalid_reason", "Goal is invalid.") ) else: logger.info( "InvalidSimulationError: " + self._goal.get("goal_invalid_reason", "Goal is invalid.") ) return obs def _get_simulation_info(self) -> dict: object_positions = self.mujoco_simulation.get_object_pos()[ : self.mujoco_simulation.num_objects ] objects_off_table = self.mujoco_simulation.check_objects_off_table( object_positions ) simulation_info = super()._get_simulation_info() simulation_info["objects_off_table"] = objects_off_table if "vision_cam_wrist" in self.constants.vision_args.mobile_camera_names: wrist_cam_contacts = self.mujoco_simulation.get_wrist_cam_collisions() simulation_info["wrist_cam_contacts"] = wrist_cam_contacts return simulation_info def _get_simulation_reward_with_done(self, info: dict) -> Tuple[float, bool]: reward, done = super()._get_simulation_reward_with_done(info) # If there is a gripper to table contact, apply table_collision penalty table_penalty = self.parameters.simulation_params.penalty.get( "table_collision", 0.0 ) if self.mujoco_simulation.get_gripper_table_contact(): reward -= table_penalty # Add a large negative penalty for "breaking" the wrist camera by hitting it # with the table or another object. if info.get("wrist_cam_contacts", {}).get("any", False): reward -= self.parameters.simulation_params.penalty.get( "wrist_collision", 0.0 ) if "objects_off_table" in info and info["objects_off_table"].any(): # If any object is off the table, we will end the episode done = True # Add a penalty to letting an object go off the table reward -= self.parameters.simulation_params.penalty.get( "objects_off_table", 0.0 ) if any(self.observe()["safety_stop"]): reward -= self.parameters.simulation_params.penalty.get("safety_stop", 0.0) return reward, done def _generate_object_placements(self) -> Tuple[np.ndarray, bool]: """ Generate placement for each object. Return object placement and a boolean indicating whether the placement is valid. """ placement, is_valid = place_objects_in_grid( self.mujoco_simulation.get_object_bounding_boxes(), self.mujoco_simulation.get_table_dimensions(), self.mujoco_simulation.get_placement_area(), random_state=self._random_state, max_num_trials=self.mujoco_simulation.max_placement_retry, ) if not is_valid: # Fall back to random placement, which works better for envs with more irregular # objects (e.g. ycb-8 with no mesh normalization). return place_objects_with_no_constraint( self.mujoco_simulation.get_object_bounding_boxes(), self.mujoco_simulation.get_table_dimensions(), self.mujoco_simulation.get_placement_area(), max_placement_trial_count=self.mujoco_simulation.max_placement_retry, max_placement_trial_count_per_object=self.mujoco_simulation.max_placement_retry_per_object, random_state=self._random_state, ) else: return placement, is_valid def _calculate_num_success(self, goal_distance) -> float: """ This method calculates the reward summed over all objects, where we only consider a success if all goal distances are under the threshold. NOTE: This method takes into account objects that are not being used and appear as a 0. in goal_distance so it should only be used in situations where you're subtracting the output of this with 2 different goal_distance values. """ per_goal_successful = np.stack( [ goal_distance[k] < self.constants.success_threshold[k] for k in self.constants.success_threshold ], axis=0, ) # Dimensions [metric, object] per_goal_successful = np.all(per_goal_successful, axis=0) # Dimensions [object] return np.sum(per_goal_successful) * self.constants.goal_reward_per_object def _calculate_goal_distance_reward( self, previous_goal_distance, goal_distance ) -> float: previous_num_success = self._calculate_num_success(previous_goal_distance) num_success = self._calculate_num_success(goal_distance) return num_success - previous_num_success def _recreate_sim(self) -> None: self.mujoco_simulation.update( self.build_simulation(self.constants, self.parameters) ) self.mujoco_simulation.mj_sim.render_callback = self._render_callback self._setup_simulation_from_parameters() self._initialize_sim_state() def _render_callback(self, _sim, _viewer): super()._render_callback(_sim, _viewer) if not self.parameters.debug: return # Debug visualization of object bounding boxes. bounding_boxes = ( self.mujoco_simulation.get_object_bounding_boxes_in_table_coordinates() ) for idx, (pos, size) in enumerate(bounding_boxes): name = f"object{idx}" _viewer.add_marker( size=size, pos=pos, rgba=np.array([0, 0.5, 1, 0.1]), label=name ) # Debug visualization of target bounding boxes. bounding_boxes = ( self.mujoco_simulation.get_target_bounding_boxes_in_table_coordinates() ) for idx, (pos, size) in enumerate(bounding_boxes): name = f"target:object{idx}" _viewer.add_marker( size=size, pos=pos, rgba=np.array([0.5, 0, 1, 0.1]), label=name ) # Debug visualization of the placement area. ( table_pos, table_size, table_height, ) = self.mujoco_simulation.get_table_dimensions() placement_area = self.mujoco_simulation.get_placement_area() size = np.array(placement_area.size) / 2.0 pos = np.array([placement_area.offset]) + table_pos - table_size + size _viewer.add_marker( size=size, pos=pos, rgba=np.array([1, 0.5, 0, 0.1]), label="placement_area" ) def _reset(self): if self.constants.use_fixed_seed: self.seed(self.seed()) # This needs to happen before sim creation because sim creation depends # on the mujoco args generated from material randomization. self._randomize_object_groups() self._recreate_sim() self._apply_object_size_scales() self._apply_object_colors() self._randomize_object_initial_states() self._randomize_camera() self._randomize_lighting() if self.constants.stabilize_objects: stabilize_objects(self.mujoco_simulation) self.mujoco_simulation.forward() self._randomize_robot_initial_position() # Update `max_timesteps_per_goal` directly in the tracker. Do NOT update # `self.constants.max_timesteps_per_goal` here since it won't propagate correctly # to `MultiGoalTracker`. assert hasattr(self.multi_goal_tracker, "max_timesteps_per_goal") self.multi_goal_tracker.max_timesteps_per_goal = ( self.constants.max_timesteps_per_goal_per_obj * self.mujoco_simulation.num_objects ) # Reset the placement area boundary, a tuple of (min_x, min_y, min_z, max_x, max_y, max_z). self._placement_area_boundary = ( self.mujoco_simulation.extract_placement_area_boundary() ) def _act(self, action): if self.constants.teleport_to_goal and self.t > 10: # Override the policy by teleporting directly to the goal state (used to generate # a balanced distribution for training a goal classifier). Add some noise to the # objects' states; we tune the scale of the noise so that with probability p=0.5, # all objects are within the success_threshold. This will result in our episodes # containing a ~p/(1+p) fraction of goal-achieved states. target_pos = self.mujoco_simulation.get_target_pos(pad=False) target_quat = self.mujoco_simulation.get_target_quat(pad=False) num_objects = target_pos.shape[0] num_randomizations = num_objects * ( ("obj_pos" in self.constants.success_threshold) + ("obj_rot" in self.constants.success_threshold) ) assert num_randomizations > 0 success_prob = 0.5 ** (1 / num_randomizations) # Add Gaussian noise to x and y position. if "obj_pos" in self.constants.success_threshold: # Tune the noise so that the position is within success_threshold with # probability success_prob. Note for example that noise_scale -> 0 when # success_prob -> 1, and noise_scale -> infinity when success_prob -> 0. noise_scale = np.ones_like(target_pos) noise_scale *= self.constants.success_threshold["obj_pos"] noise_scale /= np.sqrt(-2 * np.log(1 - success_prob)) noise_scale[:, 2] = 0.0 # Don't add noise to the z-axis target_pos = np.random.normal(loc=target_pos, scale=noise_scale) # Add Gaussian noise to rotation about z-axis. if "obj_rot" in self.constants.success_threshold: # Tune the noise so that the rotation is within success_threshold with # probability success_prob. Note for example that noise_scale -> 0 when # success_prob -> 1, and noise_scale -> infinity when success_prob -> 0. noise_scale = self.constants.success_threshold["obj_rot"] noise_scale /= scipy.special.ndtri( success_prob + (1 - success_prob) / 2 ) noise_quat = rotation.quat_from_angle_and_axis( angle=np.random.normal( loc=np.zeros((num_objects,)), scale=noise_scale ), axis=np.array([[0, 0, 1.0]] * num_objects), ) target_quat = rotation.quat_mul(target_quat, noise_quat) self.mujoco_simulation.set_object_pos(target_pos) self.mujoco_simulation.set_object_quat(target_quat) self.mujoco_simulation.forward() else: self._set_action(action) def apply_wrappers(self, **wrapper_params): env = SmoothActionWrapper(self, alpha=0.3) env = ClipRewardWrapper(env) env = DiscretizeActionWrapper( env, n_action_bins=self.constants.n_action_bins, bin_spacing=self.constants.action_spacing, ) return env @classmethod def build_goal_generation(cls, constants: CType, mujoco_simulation: SType): if constants.goal_generation == "train": return TrainStateGoal(mujoco_simulation, args=constants.goal_args) else: return ObjectStateGoal(mujoco_simulation, args=constants.goal_args) @classmethod def build_observation_randomizers(cls, constants: CType): return [] @classmethod def build_simulation_randomizers(cls, constants): return [ GravityRandomizer(), JointMarginRandomizer(), GenericSimRandomizer( name="dof_frictionloss_robot", field_name="dof_frictionloss", dof_jnt_prefix="robot0:", apply_mode="uncoupled_mean_variance", ), GenericSimRandomizer( name="dof_damping_robot", field_name="dof_damping", dof_jnt_prefix="robot0:", apply_mode="uncoupled_mean_variance", ), GenericSimRandomizer( name="dof_armature_robot", field_name="dof_armature", dof_jnt_prefix="robot0:", apply_mode="uncoupled_mean_variance", ), GenericSimRandomizer( name="jnt_stiffness_robot", field_name="jnt_stiffness", jnt_prefix="robot0:", apply_mode="variance_mean_additive", coef=0.005, positive_only=True, ), GenericSimRandomizer( name="body_pos_robot", field_name="body_pos", body_prefix="robot0:", apply_mode="variance_additive", coef=0.02, ), PidRandomizer("pid_kp"), PidRandomizer("pid_ti"), PidRandomizer("pid_td"), PidRandomizer("pid_imax_clamp"), PidRandomizer("pid_error_deadband"), GenericSimRandomizer( name="actuator_forcerange", field_name="actuator_forcerange", apply_mode="uncoupled_mean_variance", ), GeomSolimpRandomizer(), GeomSolrefRandomizer(), GenericSimRandomizer( name="geom_margin", field_name="geom_margin", apply_mode="variance_additive", coef=0.0005, ), GenericSimRandomizer( name="geom_pos", field_name="geom_pos", apply_mode="variance_additive", coef=0.002, ), GenericSimRandomizer( name="geom_gap", field_name="geom_gap", apply_mode="max_additive", coef=0.01, ), GenericSimRandomizer( name="geom_friction", field_name="geom_friction", apply_mode="uncoupled_mean_variance", ), GenericSimRandomizer( name="body_mass", field_name="body_mass", apply_mode="uncoupled_mean_variance", zero_threshold=0.208, ), GenericSimRandomizer( name="body_inertia", field_name="body_inertia", apply_mode="variance_additive", ), ]
43,261
38.58097
110
py
robogym
robogym-master/robogym/envs/rearrange/common/utils.py
import collections import glob import itertools import json import logging import os from copy import deepcopy from functools import lru_cache from typing import Callable, Dict, List, NamedTuple, Optional, Tuple, Union import _jsonnet import numpy as np import trimesh from collision import Poly, Vector, collide from mujoco_py import MjSim, const from numpy.random import RandomState from robogym.mujoco.mujoco_xml import ASSETS_DIR, MujocoXML from robogym.utils.env_utils import InvalidSimulationError from robogym.utils.mesh import get_vertices_bounding_box, subdivide_mesh from robogym.utils.misc import robogym_path from robogym.utils.rotation import mat2quat, quat2mat, quat_conjugate, uniform_quat MATERIAL_DIR = robogym_path("envs", "rearrange", "materials") NumType = Union[int, float] class PlacementArea(NamedTuple): """The offset of the placement area, which is in the lower left corner""" offset: Tuple[float, float, float] """The full-size of the placement area (note that we do NOT use half-size convention here)""" size: Tuple[float, float, float] def recursive_dict_update(dictionary, update): for k, v in update.items(): if isinstance(v, collections.abc.Mapping): dictionary[k] = recursive_dict_update(dictionary.get(k, {}), v) else: dictionary[k] = v return dictionary def sample_group_counts( random_state: RandomState, total: int, lam_low: float = 1.0, lam_high: float = 8.0 ) -> List[int]: """ Sample a list of integers which sum up to `total`. The probability of sampling an integer follows exponential decay, k ~ np.exp(-k * lam), where lam is a hyperparam sampled from a range [lam_low, lam_high). :param random_state: numpy random state :param total: the expected sum of sampled numbers. :param lam_low: lower bound for lambda in exponential decay. :param lam_high: higher bound for lambda in exponential decay. :return: """ current_max = total counts = [] while current_max > 0: candidates = range(1, current_max + 1) lam = random_state.uniform(lam_low, lam_high) probs = np.array([np.exp(-i * lam) for i in candidates]) probs /= sum(probs) selected = random_state.choice(candidates, p=probs) counts.append(selected) current_max -= selected assert sum(counts) == total return counts def stabilize_objects(mujoco_simulation, n_steps: int = 100): """ Stabilize objects. """ # Store original damping value for objects. damping = mujoco_simulation.get_object_damping() # Decrease damping value to make object stabilize faster. mujoco_simulation.set_object_damping(1e-3) # Step simulation to let object stabilize. for _ in range(n_steps): mujoco_simulation.step() # Restore damping value. mujoco_simulation.set_object_damping(damping) mujoco_simulation.forward() def make_openai_block(name: str, object_size: np.ndarray) -> MujocoXML: """ Creates a block with OPENAI letters on it faces. :param name: The name of the block :param object_size: The size of the block (3-dimensional). This is half-size as per Mujoco convention """ default_object_size = 0.0285 default_letter_offset = 0.0009 # scale face meshes properly scale = object_size / default_object_size letter_offset = default_letter_offset * scale def to_str(x: np.ndarray): return " ".join(map(str, x.tolist())) face_pos = { "top": { "body": to_str(np.array([0, 0, object_size[2]])), "geom": to_str(np.array([0, 0, -letter_offset[2]])), }, "bottom": { "body": to_str(np.array([0, 0, -object_size[2]])), "geom": to_str(np.array([0, 0, letter_offset[2]])), }, "back": { "body": to_str(np.array([0, object_size[1], 0])), "geom": to_str(np.array([0, -letter_offset[1], 0])), }, "right": { "body": to_str(np.array([object_size[0], 0, 0])), "geom": to_str(np.array([-letter_offset[0], 0, 0])), }, "front": { "body": to_str(np.array([0, -object_size[1], 0])), "geom": to_str(np.array([0, letter_offset[1], 0])), }, "left": { "body": to_str(np.array([-object_size[0], 0, 0])), "geom": to_str(np.array([letter_offset[0], 0, 0])), }, } face_euler = { "top": to_str(np.array([np.pi / 2, 0, np.pi / 2])), "bottom": to_str(np.array([np.pi / 2, 0, np.pi / 2])), "back": to_str(np.array([0, 0, np.pi / 2])), "right": to_str(np.array([0, 0, 0])), "front": to_str(np.array([0, 0, -np.pi / 2])), "left": to_str(np.array([0, 0, np.pi])), } def face_xml(_name: str, _face: str, _c: str): xml = f""" <body name="{_face}:{_name}" pos="{face_pos[_face]['body']}"> <geom name="letter_{_c}:{_name}" mesh="{_name}{_c}" euler="{face_euler[_face]}" pos="{face_pos[_face]['geom']}" type="mesh" material="{_name}letter" conaffinity="0" contype="0" /> </body> """ return xml size_string = " ".join(map(str, list(object_size))) scale_string = " ".join(map(str, list(scale))) xml_source = f""" <mujoco> <asset> <material name="{name}letter" specular="1" shininess="0.3" rgba="1 1 1 1"/> <mesh name="{name}O" file="{ASSETS_DIR}/stls/openai_cube/O.stl" scale="{scale_string}" /> <mesh name="{name}P" file="{ASSETS_DIR}/stls/openai_cube/P.stl" scale="{scale_string}" /> <mesh name="{name}E" file="{ASSETS_DIR}/stls/openai_cube/E.stl" scale="{scale_string}" /> <mesh name="{name}N" file="{ASSETS_DIR}/stls/openai_cube/N.stl" scale="{scale_string}" /> <mesh name="{name}A" file="{ASSETS_DIR}/stls/openai_cube/A.stl" scale="{scale_string}" /> <mesh name="{name}I" file="{ASSETS_DIR}/stls/openai_cube/I.stl" scale="{scale_string}" /> </asset> <worldbody> <body name="{name}"> <geom name="{name}" size="{size_string}" type="box" rgba="0.0 0.0 0.0 0.0" material="block_mat"/> <joint name="{name}:joint" type="free"/> {face_xml(name, "top", "O")} {face_xml(name, "bottom", "P")} {face_xml(name, "back", "E")} {face_xml(name, "right", "N")} {face_xml(name, "front", "A")} {face_xml(name, "left", "I")} </body> </worldbody> </mujoco> """ return MujocoXML.from_string(xml_source) def make_block(name: str, object_size: np.ndarray) -> MujocoXML: """Creates a block. :param name: The name of the block :param object_size: The size of the block (3-dimensional). This is half-size as per Mujoco convention """ xml_source = f""" <mujoco> <worldbody> <body name="{name}" pos="0.0 0.0 0.0"> <geom type="box" rgba="0.0 0.0 0.0 0.0" material="block_mat"/> <joint name="{name}:joint" type="free"/> </body> </worldbody> </mujoco> """ xml = MujocoXML.from_string(xml_source).set_objects_attr( tag="geom", size=object_size ) return xml def make_blocks_and_targets( num_objects: int, block_size: Union[float, np.ndarray], appearance: str = "standard" ) -> List[Tuple[MujocoXML, MujocoXML]]: if isinstance( block_size, (int, float, np.integer, np.floating) ) or block_size.shape == (1,): block_size = np.tile(block_size, 3) assert block_size.shape == ( 3, ), f"Bad block_size: {block_size}, expected float, np.ndarray(1,) or np.ndarray(3,)" if appearance == "standard": make_block_fn = make_block elif appearance == "openai": make_block_fn = make_openai_block xmls: List[Tuple[MujocoXML, MujocoXML]] = [] for i in range(num_objects): # add the block block_xml = make_block_fn(f"object{i}", block_size.copy()) xmls.append((block_xml, make_target(block_xml))) return xmls def get_combined_mesh(files: List[str]) -> trimesh.Trimesh: return trimesh.util.concatenate( [trimesh.load(os.path.join(ASSETS_DIR, "stls", file)) for file in files] ) def make_mesh_object(name: str, files: List[str], scale: float) -> MujocoXML: # Center mesh properly by offsetting with center position of combined mesh. mesh = get_combined_mesh(files) pos = -mesh.center_mass * scale pos_string = " ".join(map(str, pos)) scale_string = " ".join(map(str, [scale] * 3)) assets = [ f'<mesh file="{file}" name="{name}-{idx}" scale="{scale_string}" />' for idx, file in enumerate(files) ] geoms = [ f'<geom type="mesh" mesh="{name}-{idx}" pos="{pos_string}"/>' for idx in range(len(files)) ] assets_xml = "\n".join(assets) geoms_xml = "\n".join(geoms) xml_source = f""" <mujoco> <asset> {assets_xml} </asset> <worldbody> <body name="{name}" pos="0.0 0.0 0.0"> {geoms_xml} <joint name="{name}:joint" type="free"/> </body> </worldbody> </mujoco> """ return MujocoXML.from_string(xml_source) def make_target(xml): xml = deepcopy(xml) xml = ( xml.remove_objects_by_tag("joint") .add_name_prefix("target:", exclude_attribs=["material", "mesh", "class"]) .set_objects_attr(tag="geom", contype=0, conaffinity=0) ) return xml def get_all_vertices(sim, object_name, subdivide_threshold=None) -> np.ndarray: """ Return all vertices for given object. :param sim: The MjSim instance. :param object_name: The object name. :param subdivide_threshold: If provided, subdivide mesh into smaller faces. See subdivide_mesh for detail of this parameter. :return: Array of all vertices for this object. """ all_verts: List[np.ndarray] = [] all_faces: List[Optional[np.ndarray]] = [] object_rot_mat = quat2mat( quat_conjugate(mat2quat(sim.data.get_body_xmat(object_name))) ) geom_ids = geom_ids_of_body(sim, object_name) for geom_id in geom_ids: pos = sim.model.geom_pos[geom_id] quat = quat_conjugate(sim.model.geom_quat[geom_id]) mat = quat2mat(quat) # Get all vertices associated with the current geom. verts = get_geom_vertices(sim, geom_id) faces = get_geom_faces(sim, geom_id) # Translate from geom's to body's coordinate frame. geom_ref_verts = verts @ mat geom_ref_verts = pos + geom_ref_verts all_verts.append(geom_ref_verts) all_faces.append(faces) if subdivide_threshold is not None and all(f is not None for f in all_faces): # We can only subdivide mesh with faces. mesh = trimesh.util.concatenate( [ trimesh.Trimesh(vertices=verts, faces=faces) for verts, faces in zip(all_verts, all_faces) ] ) verts = subdivide_mesh(mesh.vertices, mesh.faces, subdivide_threshold) else: verts = np.concatenate(all_verts, axis=0) return verts @ object_rot_mat def get_geom_vertices(sim, geom_id): geom_type = sim.model.geom_type[geom_id] geom_size = sim.model.geom_size[geom_id] if geom_type == const.GEOM_BOX: dx, dy, dz = geom_size return np.array(list(itertools.product([dx, -dx], [dy, -dy], [dz, -dz]))) elif geom_type in (const.GEOM_SPHERE, const.GEOM_ELLIPSOID): if geom_type == const.GEOM_SPHERE: r = [geom_size[0]] * 3 else: r = geom_size[:3] # https://stats.stackexchange.com/a/30622 vertices = [] phi = np.linspace(0, np.pi * 2, 20) cos_theta = np.linspace(-1, 1, 20) for p, c in itertools.product(phi, cos_theta): x = np.sqrt(1 - c ** 2) * np.cos(p) y = np.sqrt(1 - c ** 2) * np.sin(p) z = c vertices.append(np.array([x, y, z])) return np.array(vertices) * r elif geom_type in (const.GEOM_CYLINDER, const.GEOM_CAPSULE): # We treat cylinder and capsule the same. r, h = geom_size[0], geom_size[2] points = np.array( [[r * np.cos(x), r * np.sin(x), 0.0] for x in np.linspace(0, np.pi * 2, 50)] ) return np.concatenate([points + h, points - h]) elif geom_type == const.GEOM_MESH: return sim.model.mesh_vert[mesh_vert_range_of_geom(sim, geom_id)] else: raise AssertionError(f"Unexpected geom type {geom_type}") def get_geom_faces(sim, geom_id): if sim.model.geom_type[geom_id] != const.GEOM_MESH: return None data_id = sim.model.geom_dataid[geom_id] face_adr = sim.model.mesh_faceadr[data_id] face_num = sim.model.mesh_facenum[data_id] return sim.model.mesh_face[range(face_adr, face_adr + face_num)] def get_mesh_bounding_box(sim, object_name) -> Tuple[float, float]: """ Returns the bounding box of a mesh body. If the block is rotated in the world frame, the rotation is applied and the tightest axis-aligned bounding box is returned. """ all_verts = get_all_vertices(sim, object_name) pos, size, _ = get_vertices_bounding_box(all_verts) return pos, size def get_block_bounding_box(sim, object_name) -> Tuple[float, float]: """ Returns the bounding box of a block body. If the block is rotated in the world frame, the rotation is applied and the tightest axis-aligned bounding box is returned. """ geom_ids = geom_ids_of_body(sim, object_name) assert len(geom_ids) == 1, f"More than 1 geoms in {object_name}." geom_id = geom_ids[0] size = sim.model.geom_size[geom_id] pos = sim.model.geom_pos[geom_id] quat = quat_conjugate(mat2quat(sim.data.get_body_xmat(object_name))) pos, size = rotate_bounding_box((pos, size), quat) return pos, size class MeshGeom: """A little helper class for generating random mesh geoms.""" def __init__( self, mesh_path: str, mesh: trimesh.Trimesh, pos: np.array, quat: np.array, scale: np.array, parent: Optional["MeshGeom"] = None, ): self.mesh_path = mesh_path self.mesh = mesh self.pos = pos self.quat = quat self.scale = scale self.parent = parent self.children: List[MeshGeom] = [] def to_geom_xml(self, name: str, idx: int): pos_str = " ".join([str(x) for x in self.pos]) quat_str = " ".join([str(x) for x in self.quat]) return f'<geom type="mesh" mesh="{name}:mesh-{idx}" name="{name}:geom-{idx}" pos="{pos_str}" quat="{quat_str}" />' def to_mesh_xml(self, name: str, idx: int): scale_str = " ".join([str(x) for x in self.scale]) return f'<mesh file="{self.mesh_path}" name="{name}:mesh-{idx}" scale="{scale_str}" />' def min_max_xyz(self): # We already applied the scaling and rotation to the mesh vertices, so we only need # to apply the offset here. transformed_vertices = self.pos + self.mesh.vertices min_xyz = np.min(transformed_vertices, axis=0) max_xyz = np.max(transformed_vertices, axis=0) return min_xyz, max_xyz def make_composed_mesh_object( name: str, primitives: List[str], random_state: np.random.RandomState, mesh_size_range: tuple = (0.01, 0.1), attachment: str = "random", object_size: Optional[float] = None, ) -> MujocoXML: """ Composes an object out of mesh primitives by combining them in a random but systematic way. In the resulting object, all meshes are guaranteed to be connected. :param name: The name of the resulting object. :param primitives: A list of STL files that will be used as primitives in the provided order. :param random_state: The random state used for sampling. :param mesh_size_range: Each mesh is randomly resized (iid per dimension) but each side is guaranteed to be within this size. This is full-size, not half-size. :param attachment: How primitives are connected. If "random", the parent geom is randomly selected from the already placed geoms. If "last", the geom that was place last is used. :param object_size: If this is not None, the final object) will be re-scaled so that the longest side has exactly object_size half-size. This parameter is in half-size, as per Mujoco convention. :return: a MujocoXML object. """ assert 0 <= mesh_size_range[0] <= mesh_size_range[1] assert attachment in ["random", "last"] def compute_pos_and_size(geoms): min_max_xyzs = np.array([geom.min_max_xyz() for geom in geoms]) min_xyz = np.min(min_max_xyzs[:, 0, :], axis=0) max_xyz = np.max(min_max_xyzs[:, 1, :], axis=0) size = (max_xyz - min_xyz) / 2.0 pos = min_xyz + size return pos, size geoms: List[MeshGeom] = [] for i, mesh_path in enumerate(primitives): # Load mesh. mesh = trimesh.load(mesh_path) # Scale randomly but such that the mesh is within mesh_size_range. min_scale = mesh_size_range[0] / mesh.bounding_box.extents max_scale = mesh_size_range[1] / mesh.bounding_box.extents assert min_scale.shape == max_scale.shape == (3,) scale = random_state.uniform(min_scale, max_scale) * random_state.choice( [-1, 1], size=3 ) assert scale.shape == (3,) scale_matrix = np.eye(4) np.fill_diagonal(scale_matrix[:3, :3], scale) # Rotate randomly. quat = uniform_quat(random_state) rotation_matrix = np.eye(4) rotation_matrix[:3, :3] = quat2mat(quat) # Apply transformations. Apply scaling first since we computed the scale # in the original reference frame! In principle, we could also sheer the # object, but we currently do not do this. mesh.apply_transform(scale_matrix) mesh.apply_transform(rotation_matrix) if len(geoms) == 0: pos = -mesh.center_mass else: if attachment == "random": parent_geom = random_state.choice(geoms) elif attachment == "last": parent_geom = geoms[-1] else: raise ValueError() # We sample 10 points here because sample_surface sometimes returns less points # than we requested (unclear why). surface_pos = trimesh.sample.sample_surface(parent_geom.mesh, 10)[0][0] pos = parent_geom.pos + (surface_pos - mesh.center_mass) geom = MeshGeom(mesh_path=mesh_path, mesh=mesh, pos=pos, quat=quat, scale=scale) geoms.append(geom) # Shift everything so that the reference of the body is at the very center of the composed # object. This is very important. off_center_pos, _ = compute_pos_and_size(geoms) for geom in geoms: geom.pos -= off_center_pos # Ensure that the object origin is exactly at the center. assert np.allclose(compute_pos_and_size(geoms)[0], 0.0) # Resize object. if object_size is not None: _, size = compute_pos_and_size(geoms) # Apply global scale (so that ratio is not changed and longest side is exactly # object_size). ratio = object_size / np.max(size) for geom in geoms: geom.scale *= ratio geom.pos *= ratio geoms_str = "\n".join([g.to_geom_xml(name, idx) for idx, g in enumerate(geoms)]) meshes_str = "\n".join([g.to_mesh_xml(name, idx) for idx, g in enumerate(geoms)]) xml_source = f""" <mujoco> <asset> {meshes_str} </asset> <worldbody> <body name="{name}" pos="0 0 0"> {geoms_str} <joint name="{name}:joint" type="free"/> </body> </worldbody> </mujoco> """ return MujocoXML.from_string(xml_source) def geom_ids_of_body(sim: MjSim, body_name: str) -> List[int]: object_id = sim.model.body_name2id(body_name) object_geomadr = sim.model.body_geomadr[object_id] object_geomnum = sim.model.body_geomnum[object_id] return list(range(object_geomadr, object_geomadr + object_geomnum)) def mesh_vert_range_of_geom(sim: MjSim, geom_id: int): assert sim.model.geom_type[geom_id] == const.GEOM_MESH data_id = sim.model.geom_dataid[geom_id] vert_adr = sim.model.mesh_vertadr[data_id] vert_num = sim.model.mesh_vertnum[data_id] return range(vert_adr, vert_adr + vert_num) def mesh_face_range_of_geom(sim: MjSim, geom_id: int): assert sim.model.geom_type[geom_id] == const.GEOM_MESH data_id = sim.model.geom_dataid[geom_id] face_adr = sim.model.mesh_faceadr[data_id] face_num = sim.model.mesh_facenum[data_id] return range(face_adr, face_adr + face_num) def update_object_body_quat(sim: MjSim, body_name: str, new_quat: np.ndarray): body_id = sim.model.body_name2id(body_name) sim.model.body_quat[body_id][:] = new_quat.copy() def _is_valid_proposal(o1_x, o1_y, object1_index, bounding_boxes, placements): o1_x += bounding_boxes[object1_index, 0, 0] o1_y += bounding_boxes[object1_index, 0, 1] # Check if object collides with any of already placed objects. We use half-sizes, # but collision uses full-sizes. That's why we multiply by 2x here. o1_w, o1_h, _ = bounding_boxes[object1_index, 1] object1 = Poly.from_box(Vector(o1_x, o1_y), o1_w * 2.0, o1_h * 2.0) for object2_index in range(len(placements)): # Don't care about z placement o2_x, o2_y, _ = placements[object2_index] o2_x += bounding_boxes[object2_index, 0, 0] o2_y += bounding_boxes[object2_index, 0, 1] # Don't care about object depth. o2_w, o2_h, _ = bounding_boxes[object2_index, 1] object2 = Poly.from_box(Vector(o2_x, o2_y), o2_w * 2.0, o2_h * 2.0) if collide(object1, object2): return False return True def _place_objects( object_bounding_boxes: np.ndarray, table_dimensions: Tuple[np.ndarray, np.ndarray, float], placement_area: PlacementArea, get_proposal: Callable[[int], Tuple[NumType, NumType]], max_placement_trial_count: int, max_placement_trial_count_per_object: int, run_collision_check: bool = True, ) -> Tuple[np.ndarray, bool]: """ Wrapper for _place_objects_trial() function. Call _place_object_trial() multiple times until it returns a valid placements. The _place_objects_trial() function can be called for `max_placement_trial_count` times. """ assert max_placement_trial_count >= 1 assert max_placement_trial_count_per_object >= 1 for _ in range(max_placement_trial_count): placements, is_valid = _place_objects_trial( object_bounding_boxes, table_dimensions, placement_area, get_proposal, max_placement_trial_count_per_object, run_collision_check, ) if is_valid: return placements, is_valid return placements, False def _place_objects_trial( object_bounding_boxes: np.ndarray, table_dimensions: Tuple[np.ndarray, np.ndarray, float], placement_area: PlacementArea, get_proposal: Callable[[int], Tuple[NumType, NumType]], max_placement_trial_count_per_object: int, run_collision_check: bool = True, ) -> Tuple[np.ndarray, bool]: """ Place objects within rectangular boundaries with given get proposal function. :param object_bounding_boxes: matrix of bounding boxes (num_objects, 2, 3) where [:, 0, :] contains the center position of the bounding box in Cartesian space relative to the body's frame of reference and where [:, 1, :] contains the half-width, half-height, and half-depth of the object. :param table_dimensions: Tuple (table_pos, table_size, table_height) defining dimension of the table where table_pos: position of the table. table_size: half-size of the table along (x, y, z). table_height: height of the table. :param placement_area: the placement area in which to place objects. :param get_proposal: Function to get a proposal of target position for given object. This function takes in object index and return proposed (x, y) position. :param max_placement_trial_count_per_object: If set, will give up re-generating new proposal after this number is hit. :param run_collision_check: If true, run collision to check if proposal is valid. :return: np.ndarray of size (num_objects, 3) where columns are x, y, z coordinates of objects relative to the world frame and boolean indicating whether the placement is valid. """ offset_x, offset_y, _ = placement_area.offset width, height, _ = placement_area.size table_pos, table_size, table_height = table_dimensions def _get_global_placement(placement: np.ndarray): return placement + [offset_x, offset_y, 0.0] - table_size + table_pos # place the objects one by one, resampling if a collision with previous objects happens n_objects = object_bounding_boxes.shape[0] placements: List[Tuple[NumType, NumType, NumType]] = [] for i in range(n_objects): placement_trial_count = 0 # Reference is to (xmin, ymin, zmin) of table. prop_z = object_bounding_boxes[i, 1, -1] + 2 * table_size[-1] prop_z -= object_bounding_boxes[i, 0, -1] while True: prop_x, prop_y = get_proposal(i) placement = _get_global_placement(np.array([prop_x, prop_y, prop_z])) b1_x, b1_y = placement[:2] if not run_collision_check or _is_valid_proposal( b1_x, b1_y, i, object_bounding_boxes, placements ): break placement_trial_count += 1 if placement_trial_count > max_placement_trial_count_per_object: return np.zeros((n_objects, len(placement))), False placements.append(placement) return np.array(placements), True def place_objects_in_grid( object_bounding_boxes: np.ndarray, table_dimensions: Tuple[np.ndarray, np.ndarray, float], placement_area: PlacementArea, random_state: np.random.RandomState, max_num_trials: int = 5, ) -> Tuple[np.ndarray, bool]: """ Place objects within rectangular boundaries by dividing the placement area into a grid of cells of equal size, and then randomly sampling cells for each object to be placed in. :param object_bounding_boxes: matrix of bounding boxes (num_objects, 2, 3) where [:, 0, :] contains the center position of the bounding box in Cartesian space relative to the body's frame of reference and where [:, 1, :] contains the half-width, half-height, and half-depth of the object. :param table_dimensions: Tuple (table_pos, table_size, table_height) defining dimension of the table where table_pos: position of the table. table_size: half-size of the table along (x, y, z). table_height: height of the table. :param placement_area: the placement area in which to place objects. :param random_state: numpy random state to use to shuffle placement positions :param max_num_trials: maximum number of trials to run (a trial will fail if there is overlap detected between any two placements; generally this shouldn't happen with this algorithm) :return: Tuple[np.ndarray, bool], where the array is of size (num_objects, 3) with columns set to the x, y, z coordinates of objects relative to the world frame, and the boolean indicates whether the placement is valid. """ offset_x, offset_y, _ = placement_area.offset width, height, _ = placement_area.size table_pos, table_size, table_height = table_dimensions def _get_global_placement(placement: np.ndarray): return placement + [offset_x, offset_y, 0.0] - table_size + table_pos # 1. Determine the number of rows and columns of the grid, based on the largest object width # and height. total_object_area = 0.0 n_objects = object_bounding_boxes.shape[0] max_obj_height = 0.0 max_obj_width = 0.0 for i in range(n_objects): # Bounding boxes are in half-sizes. obj_width = object_bounding_boxes[i, 1, 0] * 2 obj_height = object_bounding_boxes[i, 1, 1] * 2 max_obj_height = max(max_obj_height, obj_height) max_obj_width = max(max_obj_width, obj_width) object_area = obj_width * obj_height total_object_area += object_area n_columns = int(width // max_obj_width) n_rows = int(height // max_obj_height) n_cells = n_columns * n_rows cell_width = width / n_columns cell_height = height / n_rows if n_cells < n_objects: # Cannot find a valid placement via this method; give up. logging.warning( f"Unable to fit {n_objects} objects into placement area with {n_cells} cells" ) return np.zeros(shape=(n_objects, 3)), False for trial_i in range(max_num_trials): placement_valid = True placements: List[Tuple[NumType, NumType, NumType]] = [] # 2. Initialize an array with all valid cell coordinates. # Create an array of shape (n_rows, n_columns, 2) where each element contains the row,col # coord coords = np.dstack(np.mgrid[0:n_rows, 0:n_columns]) # Create a shuffled list where ever entry is a valid (row, column) coordinate. coords = np.reshape(coords, (n_rows * n_columns, 2)) random_state.shuffle(coords) coords = list(coords) # 3. Place each object into a randomly selected cell. for object_idx in range(n_objects): row, col = coords.pop() pos, size = object_bounding_boxes[object_idx] prop_x = cell_width * col + size[0] - pos[0] prop_y = cell_height * row + size[1] - pos[1] # Reference is to (xmin, ymin, zmin) of table. prop_z = object_bounding_boxes[object_idx, 1, -1] + 2 * table_size[-1] prop_z -= object_bounding_boxes[object_idx, 0, -1] placement = _get_global_placement(np.array([prop_x, prop_y, prop_z])) b1_x, b1_y = placement[:2] if not _is_valid_proposal( b1_x, b1_y, object_idx, object_bounding_boxes, placements ): placement_valid = False logging.warning(f"Trial {trial_i} failed on object {object_idx}") break placements.append(placement) if placement_valid: assert ( len(placements) == n_objects ), "There should be a placement for every object" break return np.array(placements), placement_valid def place_objects_with_no_constraint( object_bounding_boxes: np.ndarray, table_dimensions: Tuple[np.ndarray, np.ndarray, float], placement_area: PlacementArea, max_placement_trial_count: int, max_placement_trial_count_per_object: int, random_state: np.random.RandomState, ) -> Tuple[np.ndarray, bool]: """ Place objects within rectangular boundaries without any extra constraint. :param object_bounding_boxes: matrix of bounding boxes (num_objects, 2, 3) where [:, 0, :] contains the center position of the bounding box in Cartesian space relative to the body's frame of reference and where [:, 1, :] contains the half-width, half-height, and half-depth of the object. :param table_dimensions: Tuple (table_pos, table_size, table_height) defining dimension of the table where table_pos: position of the table. table_size: half-size of the table along (x, y, z). table_height: height of the table. :param placement_area: the placement area in which to place objects :param max_placement_trial_count: To prevent infinite loop caused by target placements, max_placement_trial_count should set to a finite positive number. :param max_placement_trial_count_per_object: To prevent infinite loop caused by target placements, max_placement_trial_count_per_object should set to a finite positive number. :param random_state: numpy RandomState to use for sampling :return: np.ndarray of size (num_objects, 3) where columns are x, y, z coordinates of objects relative to the world frame and boolean indicating whether if the proposal is valid. """ def _get_placement_proposal(object_idx): # randomly place the object within the bounds pos, size = object_bounding_boxes[object_idx] offset_x, offset_y, _ = placement_area.offset width, height, _ = placement_area.size x, y = random_state.uniform( low=(size[0], size[1]), high=(width - size[0], height - size[1]) ) x -= pos[0] y -= pos[1] return x, y return _place_objects( object_bounding_boxes, table_dimensions, placement_area, _get_placement_proposal, max_placement_trial_count, max_placement_trial_count_per_object, ) def place_targets_with_fixed_position( object_bounding_boxes: np.ndarray, table_dimensions: Tuple[np.ndarray, np.ndarray, float], placement_area: PlacementArea, target_placements: np.ndarray, ): """ Place target object according to specified placement positions. :param object_bounding_boxes: matrix of bounding boxes (num_objects, 2, 3) where [:, 0, :] contains the center position of the bounding box in Cartesian space relative to the body's frame of reference and where [:, 1, :] contains the half-width, half-height, and half-depth of the object. :param table_dimensions: Tuple (table_pos, table_size, table_height) defining dimension of the table where table_pos: position of the table. table_size: half-size of the table along (x, y, z). table_height: height of the table. :param placement_area: the placement area in which to place objects :param target_placements: Placement positions (x, y) relative to the placement area. Normalized to [0, 1] :return: Global placement positions (x, y, z) for all objects. """ def _get_placement_proposal(object_idx): width, height, _ = placement_area.size return target_placements[object_idx] * [width, height] return _place_objects( object_bounding_boxes, table_dimensions, placement_area, _get_placement_proposal, max_placement_trial_count=1, max_placement_trial_count_per_object=1, run_collision_check=False, ) def place_targets_with_goal_distance_ratio( object_bounding_boxes: np.ndarray, table_dimensions: Tuple[np.ndarray, np.ndarray, float], placement_area: PlacementArea, object_placements: np.ndarray, goal_distance_ratio: float, goal_distance_min: float, max_placement_trial_count: int, max_placement_trial_count_per_object: int, random_state: np.random.RandomState, ) -> Tuple[np.ndarray, bool]: """ Place targets around objects with goal distance. :param object_bounding_boxes: matrix of bounding boxes (num_objects, 2, 3) where [:, 0, :] contains the center position of the bounding box in Cartesian space relative to the body's frame of reference and where [:, 1, :] contains the half-width, half-height, and half-depth of the object. :param table_dimensions: Tuple (table_pos, table_size, table_height) defining dimension of the table where table_pos: position of the table. table_size: half-size of the table along (x, y, z). table_height: height of the table. :param placement_area: the placement area in which to place objects :param object_placements: placements of boxes - this is the result of place_objects :param goal_distance_ratio: goal is uniformly sampled first and then distance beween the object and the goal is shrinked. The shrinked distance is original distance times goal_distance_ratio. :param goal_distance_min: minimum goal distance to ensure that goal is not too close to the object position. :param max_placement_trial_count: To prevent infinite loop caused by target placements, max_placement_trial_count should set to a finite positive number. :param max_placement_trial_count_per_object: To prevent infinite loop caused by target placements, max_placement_trial_count_per_object should set to a finite positive number. :param random_state: numpy RandomState to use for sampling :return: np.ndarray of size (num_objects, 3) where columns are x, y coordinates of objects and boolean indicating whether if the proposal is valid. """ def _get_placement_proposal(object_idx): # Sample goal position relative to table area pos, size = object_bounding_boxes[object_idx] offset_x, offset_y, _ = placement_area.offset width, height, _ = placement_area.size gx, gy = random_state.uniform( low=(size[0], size[1]), high=(width - size[0], height - size[1]) ) # Retrieve object position relative to table area table_pos, table_size, table_height = table_dimensions object_place = ( object_placements[object_idx] - [offset_x, offset_y, 0.0] + table_size - table_pos ) x = object_place[0] + pos[0] y = object_place[1] + pos[1] # Pull goal position close to the object position dist = np.linalg.norm([gx - x, gy - y]) min_ratio = goal_distance_min / dist if dist >= goal_distance_min else 0.0 ratio = np.clip(goal_distance_ratio, min_ratio, 1.0) gx = x + (gx - x) * ratio gy = y + (gy - y) * ratio return gx - pos[0], gy - pos[1] return _place_objects( object_bounding_boxes, table_dimensions, placement_area, _get_placement_proposal, max_placement_trial_count, max_placement_trial_count_per_object, ) def find_meshes_by_dirname(root_mesh_dir) -> Dict[str, list]: """ Find all meshes under given mesh directory, grouped by top level folder name. :param root_mesh_dir: The root directory name for mesh files. :return: {dir_name -> list of mesh files} """ root_path = os.path.join(ASSETS_DIR, "stls", root_mesh_dir) all_stls = {} for subdir in os.listdir(root_path): curr_path = os.path.join(root_path, subdir) if not os.path.isdir(curr_path) and not curr_path.endswith(".stl"): continue if curr_path.endswith(".stl"): stls = [curr_path] else: stls = glob.glob(os.path.join(curr_path, "*.stl")) assert len(stls) > 0 all_stls[subdir] = stls assert len(all_stls) > 0 return all_stls def find_stls(mesh_dir) -> List[str]: return glob.glob(os.path.join(mesh_dir, "**", "*.stl"), recursive=True) def load_all_materials() -> List[str]: """ Return name for all material files under envs/rearrange/materials """ return [ os.path.splitext(os.path.basename(material_path))[0] for material_path in glob.glob(os.path.join(MATERIAL_DIR, "*.jsonnet")) ] # NOTE: Use lru_cache so that we don't have to re-compile materials files over and over @lru_cache() def load_material_args(material_name: str) -> dict: """ Load mujoco args related to given material. """ material_path = os.path.join(MATERIAL_DIR, f"{material_name}.jsonnet") return json.loads(_jsonnet.evaluate_file(material_path)) def safe_reset_env( env, max_reset_retry_on_invalid_sim_error=100, only_reset_goal=False ) -> dict: for i in range(max_reset_retry_on_invalid_sim_error): try: if only_reset_goal: obs = env.reset_goal() else: obs = env.reset() except InvalidSimulationError: if i == max_reset_retry_on_invalid_sim_error - 1: raise RuntimeError( f"Too many consecutive env reset error:" f" {max_reset_retry_on_invalid_sim_error} times" ) else: break return obs def rotate_bounding_box( bounding_box: np.ndarray, quat: np.ndarray ) -> Tuple[float, float]: """ Rotates a bounding box by applying the quaternion and then re-computing the tightest possible fit of an *axis-aligned* bounding box. """ pos, size = bounding_box # Compute 8 corners of bounding box. signs = np.array([[x, y, z] for x in [-1, 1] for y in [-1, 1] for z in [-1, 1]]) corners = pos + signs * size assert corners.shape == (8, 3) # Rotate corners. mat = quat2mat(quat) rotated_corners = corners @ mat # Re-compute bounding-box. min_xyz = np.min(rotated_corners, axis=0) max_xyz = np.max(rotated_corners, axis=0) size = (max_xyz - min_xyz) / 2.0 assert np.all(size >= 0.0) pos = min_xyz + size return pos, size def update_object_z_coordinate( position: np.ndarray, object_bounding_boxes: np.ndarray, table_dimensions: Tuple[np.ndarray, np.ndarray, float], ) -> np.ndarray: """ Update object z position based on bounding box. In case an object is rotated, the z position of object, which is computed to be on top of the table, can be invalidated. This method is useful to update z position based on up-to-date bounding box information. :param position: position of objects (num_objects, 3) where the second dimension of the tensor corresponds to (x, y, z) world coordinates of each object. :param object_bounding_boxes: matrix of bounding boxes (num_objects, 2, 3) where [:, 0, :] contains the center position of the bounding box in Cartesian space relative to the body's frame of reference and where [:, 1, :] contains the half-width, half-height, and half-depth of the object. :param table_dimensions: Tuple (table_pos, table_size, table_height) defining dimension of the table where table_pos: position of the table. table_size: half-size of the table along (x, y, z). table_height: height of the table. :return: position of objects (num_objects, 3) with updated z coordinate """ table_pos, table_size, table_height = table_dimensions n_objects = object_bounding_boxes.shape[0] updated = position.copy() for i in range(n_objects): center, size = object_bounding_boxes[i] updated[i, -1] = size[-1] - center[-1] + table_size[-1] + table_pos[-1] return updated
43,262
37.421847
122
py
robogym
robogym-master/robogym/envs/rearrange/common/wrappers.py
import gym import numpy as np class RewardDiffWrapper(gym.RewardWrapper): """ This wrapper is meant to work only with goal envs. It returns the difference in reward between steps instead of the reward. For distance based rewards, this turns the reward into a potential function. """ def __init__(self, env=None): super().__init__(env) self.previous_rew = None def reset(self, *args, **kwargs): obs = self.env.reset(*args, **kwargs) self.previous_rew = self.unwrapped.compute_reward( obs["achieved_goal"], self.unwrapped.goal, {} ) return obs def reward(self, reward): reward_diff = reward - self.previous_rew self.previous_rew = reward return reward_diff class RobotStateObservationWrapper(gym.ObservationWrapper): """ Adds robot state observations (i.e. the qpos values for all robot joints) without leaking information about the goal. This is necessary because the original Gym environment does not include this information and also concatenates everything into a single observation vector--which leaks the goal if using vision training. """ def __init__(self, env: gym.Env): super().__init__(env) self._robot_joint_names = [ n for n in self.env.unwrapped.sim.model.joint_names if n.startswith("robot0:") ] self.observation_space.spaces["robot_state"] = gym.spaces.Box( low=-np.inf, high=np.inf, shape=(len(self._robot_joint_names),) ) def observation(self, obs): obs["robot_state"] = np.array( [ self.env.unwrapped.sim.data.get_joint_qpos(n) for n in self._robot_joint_names ] ) return obs class CompatibilityWrapper(gym.Wrapper): """ successes_so_far is use to track success in evaluator. This field has the same meaning as is_success coming from gym fetch environment. """ def step(self, action): obs, reward, done, info = self.env.step(action) info["successes_so_far"] = info["is_success"] return obs, reward, done, info
2,205
30.070423
86
py
robogym
robogym-master/robogym/envs/rearrange/common/mesh.py
import abc from typing import List, Optional, TypeVar import attr import numpy as np from robogym.envs.rearrange.common.base import ( RearrangeEnv, RearrangeEnvConstants, RearrangeEnvParameters, ) from robogym.envs.rearrange.common.utils import get_combined_mesh from robogym.envs.rearrange.simulation.mesh import ( MeshRearrangeSim, MeshRearrangeSimParameters, ) from robogym.robot_env import build_nested_attr @attr.s(auto_attribs=True) class MeshRearrangeEnvParameters(RearrangeEnvParameters): simulation_params: MeshRearrangeSimParameters = build_nested_attr( MeshRearrangeSimParameters ) # A list of mesh folders to sample from in _sample_object_meshes(). If None, we # just sample from all the available meshes. mesh_names: Optional[List[str]] = None @attr.s(auto_attribs=True) class MeshRearrangeEnvConstants(RearrangeEnvConstants): use_grey_colors: bool = False # If true, the dimension with max size will be normalized to mesh_size parameter # defined below. This overwrite the global scaling factor `mesh_scale`. normalize_mesh: bool = False # Half size for the dimension with max size after normalization. normalized_mesh_size: float = 0.05 CType = TypeVar("CType", bound=MeshRearrangeEnvConstants) PType = TypeVar("PType", bound=MeshRearrangeEnvParameters) SType = TypeVar("SType", bound=MeshRearrangeSim) class MeshRearrangeEnv(RearrangeEnv[PType, CType, SType], abc.ABC): def _sample_group_attributes(self, num_groups: int): attrs_dict = super()._sample_group_attributes(num_groups) attrs_dict["mesh_files"] = self._sample_object_meshes(num_groups) return attrs_dict def _sample_object_colors(self, num_groups: int): # Overwrite colors if needed. if self.constants.use_grey_colors: return [[0.5, 0.5, 0.5, 1]] * num_groups return super()._sample_object_colors(num_groups) @abc.abstractmethod def _sample_object_meshes(self, num_groups: int) -> List[List[str]]: """Sample `num_groups` sets of mesh_files and return. """ pass def _recreate_sim(self): num_objects = self.mujoco_simulation.num_objects # If we have 10 or more objects, downscale all objects so that the total object area is # roughly equal to the area occupied by 10 "normal" objects. global_scale = 1.0 if num_objects < 10 else (10.0 / num_objects) ** 0.5 if self.constants.normalize_mesh: # Use trimesh to measure the size of each object group's mesh so that we can compute # the appropriate normalizing rescaling factor. new_obj_group_scales = [] for obj_group in self.parameters.simulation_params.object_groups: mesh = get_combined_mesh(obj_group.mesh_files) size = mesh.extents # The size is the "full size", so divide by 2 to get the half-size since this is # what MuJoCo uses and the normalized_mesh_size param expects. max_size = np.max(size) / 2.0 new_obj_group_scales.append( self.constants.normalized_mesh_size / max_size ) else: new_obj_group_scales = np.ones( len(self.parameters.simulation_params.object_groups) ) # For meshes, we cannot resize 'mesh' geoms directly. We need to change the scale # when loading the mesh assets into XML. for i, obj_group in enumerate(self.parameters.simulation_params.object_groups): orig_group_scale = obj_group.scale if num_objects >= 10: # If we have more than 10 objects, then we don't allow upscaling the object since # this could result in too little space to place objects. orig_group_scale = min(orig_group_scale, 1.0) obj_group.scale = orig_group_scale * new_obj_group_scales[i] * global_scale return super()._recreate_sim() def _apply_object_size_scales(self): # We need to apply rescaling for mesh objects when creating the XML, so we do # nothing here after sim has been created. pass
4,230
38.175926
97
py
robogym
robogym-master/robogym/envs/rearrange/holdouts/__init__.py
from os.path import abspath, dirname, join STATE_DIR = abspath(join(dirname(__file__), "states"))
99
24
54
py
robogym
robogym-master/robogym/envs/rearrange/holdouts/tests/test_stability.py
import os from typing import List import numpy as np from mujoco_py import const from robogym.robot_env import RobotEnv from robogym.utils.env_utils import load_env ROOT_PATH = os.path.join("robogym", "envs", "rearrange", "holdouts", "configs") # Number of steps to let the env run for while we test for stability. NUM_STEPS = 50 MATERIALS_JSONNET_TEMPLATE = """ (import "{config_file}") + {{ mat:: {material}, rgba:: "{color}" }} """ # Template which sets the initial state to the first goal state, used to test goal state stability. GOAL_STATE_JSONNET_TEMPLATE = """ (import "{config_file}") + {{ initial_state_path:: $.goal_state_paths[0], make_env+: {{ args+: {{ parameters+: {{ # Prevent the robot from knocking over objects. n_random_initial_steps: 0, }}, }}, }}, }} """ ALL_MATERIALS = [ # FIXME: the default material is not as stable as others, since it doesn't set solref # Uncomment the below once we resolve the investigation into the default material. # ('default.jsonnet', '0 1 0 1'), ("painted_wood.jsonnet", "0 0 1 1"), ("tangram.jsonnet", "1 0 0 1"), ("rubber-ball.jsonnet", "1 1 0 1"), ("chess.jsonnet", "1 0 1 1"), ] # Each entry contains (config path, max speed w/ initial state, max speed w/ goal state) # These thresholds are chosen so that we don't accidentally make things less stable; as we # improve physics stability, we should ideally lower these thresholds. HOLDOUT_ENVS = [ ( "ball_capture.jsonnet", 0.1, 1.0, ), # Ball capture's goal state is currently unstable. ("chess.jsonnet", 0.2, 0.2), # Chess is a bit more unstable. ("dominoes.jsonnet", 0.1, 0.1), ("rainbow.jsonnet", 0.1, 0.1), ("tangram.jsonnet", 0.1, 0.1), ("rainbow_build/rainbow_stack6.jsonnet", 0.1, 0.1), ("rainbow_build/rainbow_stack_inv6.jsonnet", 0.1, 0.1), ("rainbow_build/rainbow_balance.jsonnet", 0.1, 0.1), ("bin_packing.jsonnet", 0.1, 0.1), ("ball_in_mug.jsonnet", 0.1, 0.1), ("jenga/leaning_tower.jsonnet", 0.1, 0.1), ("jenga/stack6.jsonnet", 0.1, 0.1), ("jenga/cross.jsonnet", 0.1, 0.1), ("lego/easy_stack2.jsonnet", 0.1, 0.1), ("lego/easy_stack3.jsonnet", 0.1, 0.1), ("lego/stack2.jsonnet", 0.1, 0.1), ("lego/stack3.jsonnet", 0.1, 0.1), ("lego/stack5.jsonnet", 0.1, 0.1), ("lego/stack2L.jsonnet", 0.1, 0.1), ] # Basic physics tests used to test all materials. ALL_PHYSICS_TESTS = [ "block_stacking4.jsonnet", "static.jsonnet", ] def _test_static_stability( env: RobotEnv, description: str, max_object_speed_allowed: float = 0.5, max_angular_speed_allowed: float = 0.05, render: bool = False, verbose: bool = False, ): """ Steps the given env for NUM_STEPS and asserts that the max object speed observed is less than the given threshold. """ env.reset() sim = env.unwrapped.mujoco_simulation if render: sim.mujoco_viewer.cam.fixedcamid = 2 sim.mujoco_viewer.cam.type = const.CAMERA_FIXED episode_max_speed = 0.0 sum_max_speed = 0.0 episode_max_ang_speed = 0.0 sum_max_ang_speed = 0.0 with sim.hide_target(): for _ in range(NUM_STEPS): zeros = (env.action_space.nvec - 1) // 2 env.step(zeros) # Compute the speed of all objects by taking the norm of the Cartesian velocity. speeds = [ np.linalg.norm(sim.get_qvel(f"object{obj_idx}")[:3]) for obj_idx in range(sim.num_objects) ] max_speed = np.max(speeds) sum_max_speed += max_speed episode_max_speed = max(max_speed, episode_max_speed) # Compute the angular speed of all objects (we have seen some issues with sim lead to # angular jittering but not translational jittering). ang_speeds = [ np.linalg.norm(sim.get_qvel(f"object{obj_idx}")[3:]) for obj_idx in range(sim.num_objects) ] max_ang_speed = np.max(ang_speeds) sum_max_ang_speed += max_ang_speed episode_max_ang_speed = max(max_ang_speed, episode_max_ang_speed) if render: env.render() if verbose: print( f"Max speed for {description} = {episode_max_speed:.3f}, " f"mean = {sum_max_speed / NUM_STEPS:.3f}" ) print( f"Max angular speed for {description} = {episode_max_ang_speed:.3f}, " f"mean = {sum_max_ang_speed / NUM_STEPS:.3f}" ) assert episode_max_speed <= max_object_speed_allowed, ( f"Max speed = {episode_max_speed} > " f"{max_object_speed_allowed}, which is the maximum we allow. This means the following " f"combo is unstable: {description}" ) assert episode_max_ang_speed <= max_angular_speed_allowed, ( f"Max angular speed = " f"{episode_max_ang_speed} > {max_angular_speed_allowed}, which is the maximum we allow. " f"This means the following combo is unstable: {description}" ) return episode_max_speed, episode_max_ang_speed def _test_materials( test_cases: List, max_object_speed_allowed: float = 0.1, max_angular_speed: float = 0.05, materials: List = None, render: bool = False, verbose: bool = False, ): """ Evaluates the stability of all test cases on all given materials (defaults to all available materials). """ if not materials: materials = ALL_MATERIALS overall_max_speed = 0.0 overall_max_ang_speed = 0.0 for material, color in materials: for test in test_cases: path = os.path.join(ROOT_PATH, "physics_tests", "tmp_" + test) if material: parsed_material = f'(import "../../../materials/{material}")' else: parsed_material = "{}" jsonnet = MATERIALS_JSONNET_TEMPLATE.format( config_file=test, material=parsed_material, color=color ) with open(path, "w") as f: f.write(jsonnet) env = load_env(path, starting_seed=0) os.remove(path) desc = f"material = {material} on test = {test}" env_max_speed, env_max_ang_speed = _test_static_stability( env, desc, max_object_speed_allowed, max_angular_speed, render=render, verbose=verbose, ) overall_max_speed = max(overall_max_speed, env_max_speed) overall_max_ang_speed = max(overall_max_ang_speed, env_max_ang_speed) if verbose: print(f"\nMax object speed across all test cases = {overall_max_speed:.3f}") print( f"\nMax angular speed across all test cases = {overall_max_ang_speed:.3f}" ) def test_stacking(): _test_materials( ["block_stacking4.jsonnet"], max_object_speed_allowed=0.3, max_angular_speed=3.0, materials=ALL_MATERIALS, ) def test_resting(): _test_materials( ["static.jsonnet"], max_object_speed_allowed=0.1, max_angular_speed=1.0, materials=ALL_MATERIALS, ) def test_initial_states(): for holdout_env, max_speed, _ in HOLDOUT_ENVS: path = os.path.join(ROOT_PATH, holdout_env) env = load_env(path, starting_seed=0) _test_static_stability( env, f"initial state for {holdout_env}", max_object_speed_allowed=max_speed, max_angular_speed_allowed=6.0, ) def test_goal_states(): for holdout_env, _, max_speed in HOLDOUT_ENVS: fname = "tmp_" + holdout_env.split("/")[-1] path = os.path.join(ROOT_PATH, fname) jsonnet = GOAL_STATE_JSONNET_TEMPLATE.format(config_file=holdout_env) with open(path, "w") as f: f.write(jsonnet) env = load_env(path, starting_seed=0) os.remove(path) _test_static_stability( env, f"goal state for {holdout_env}", max_object_speed_allowed=max_speed, max_angular_speed_allowed=6.0, )
8,309
30.717557
99
py
robogym
robogym-master/robogym/envs/rearrange/observation/physical.py
0
0
0
py
robogym
robogym-master/robogym/envs/rearrange/observation/common.py
from typing import Callable, List, Optional, TypeVar import numpy as np from robogym.envs.rearrange.simulation.base import RearrangeSimulationInterface from robogym.observation.goal import GoalRenderedImageObservationProvider from robogym.observation.image import ImageObservationProvider SType = TypeVar("SType", bound=RearrangeSimulationInterface) class MujocoImageObservationProvider(ImageObservationProvider): """ Observation provider which provider mujoco rendered image. """ def __init__( self, mujoco_simulation: SType, camera_names: List[str], image_size: int ): """ :param mujoco_simulation: this mujoco simulation instance. :param camera_names: name of the cameras to render images. :param image_size: size of rendered image. """ self.mujoco_simulation = mujoco_simulation self.camera_names = camera_names self.image_size = image_size self._images: Optional[np.ndarray] = None def sync(self): with self.mujoco_simulation.hide_target(): images = np.array( [ self.mujoco_simulation.render( width=self.image_size, height=self.image_size, camera_name=cam ) for cam in self.camera_names ], dtype=np.uint8, ) assert images.dtype == np.uint8 self._images = images @property def images(self): assert self._images is not None return self._images class MujocoGoalImageObservationProvider(GoalRenderedImageObservationProvider): """ Goal observation which renders mujoco image for goal qpos. """ def __init__( self, mujoco_simulation: RearrangeSimulationInterface, camera_names: List[str], image_size: int, get_goal: Callable[[], dict], goal_qpos_key: str, hide_robot: bool = True, ): """ :param mujoco_simulation: this mujoco simulation instance. :param camera_names: name of the cameras to render images. :param image_size: size of rendered image. :param get_goal: The function to get goal info dict. :param goal_qpos_key: The key to get goal qpos from goal info dict. :param hide_robot: If true, hide robot from rendered image. """ super().__init__(get_goal, goal_qpos_key) self.mujoco_simulation = mujoco_simulation self.camera_names = camera_names self.image_size = image_size self.hide_robot = hide_robot def _render_goal_images(self, goal_qpos): with self.mujoco_simulation.hide_target(hide_robot=self.hide_robot): old_qpos = self.mujoco_simulation.qpos.copy() self.mujoco_simulation.mj_sim.data.qpos[:] = goal_qpos.copy() self.mujoco_simulation.forward() goal_images = np.array( [ self.mujoco_simulation.render( width=self.image_size, height=self.image_size, camera_name=cam ) for cam in self.camera_names ] ) self.mujoco_simulation.mj_sim.data.qpos[:] = old_qpos self.mujoco_simulation.forward() return goal_images
3,359
32.939394
86
py
robogym
robogym-master/robogym/envs/rearrange/datasets/objects/base.py
from typing import Any, Dict, List import numpy as np from numpy.random.mtrand import RandomState class ObjectDataset: """ Base class for object dataset """ def __init__(self, random_state: RandomState, mesh_scale: float = 1.0): self._random_state = random_state self.mesh_scale = mesh_scale # Set of all objects that can be sampled from this datasetset. {object_id: path to object} self.objects: Dict[str, Any] = self.get_objects() # List of all object ids self.object_ids: List[str] = list(self.objects.keys()) def get_objects(self) -> Dict[str, Any]: """ Return a dictionary of {object_id: pointer to the object meshes}""" raise NotImplementedError def get_mesh_list(self, object_ids: List[str]) -> List[List[str]]: """ Return a list of (a list of mesh file paths) for a list of objects """ meshes = [] for object_id in object_ids: meshes.append(self.get_mesh(object_id)) return meshes def get_mesh(self, object_id: str) -> List[str]: """ Return a list of mesh file paths for an object """ raise NotImplementedError def sample(self, num_groups: int) -> List[str]: """ Sample object ids for this dataset """ raise NotImplementedError @classmethod def post_process_quat(cls, quat: np.ndarray) -> np.ndarray: """ Apply object dataset specific logic to post process object's initial rotation This function can be useful if all meshes in some object dataset has weird default orientations. """ return quat
1,635
33.808511
98
py
robogym
robogym-master/robogym/envs/rearrange/datasets/objects/utils.py
from typing import Dict from numpy.random.mtrand import RandomState from robogym.utils.env_utils import get_function def get_object_datasets(object_config: Dict[str, dict], random_state: RandomState): datasets = {} for key in object_config: datasets[key] = get_function(object_config[key])(random_state=random_state) return datasets
357
26.538462
83
py
robogym
robogym-master/robogym/envs/rearrange/datasets/objects/local_mesh.py
from numpy.random.mtrand import RandomState from robogym.envs.rearrange.common.utils import find_meshes_by_dirname from robogym.envs.rearrange.datasets.objects.base import ObjectDataset class LocalMeshObjectDataset(ObjectDataset): """ Class of object dataset loading mesh files for objects from local directory. mesh files are loaded from robogym/assets/stls/{mesh_dirname} e.g. * mesh_dirname == 'ycb': load ycb object dataset * mesh_dirname == 'geom': load geom object dataset """ def __init__( self, random_state: RandomState, mesh_dirname: str, mesh_scale: float = 1.0 ): """ :param mesh_dirname: local directory name (path: robogym/assets/stls/{mesh_dirname}) to load object mesh files from """ self.mesh_dirname = mesh_dirname super().__init__(random_state=random_state, mesh_scale=mesh_scale) def get_mesh(self, object_id: str): return self.objects[object_id] def get_objects(self): return find_meshes_by_dirname(self.mesh_dirname) def sample(self, num_groups: int): indices = self._random_state.choice(len(self.object_ids), size=num_groups) return [self.object_ids[i] for i in indices] create = LocalMeshObjectDataset
1,276
31.74359
95
py
robogym
robogym-master/robogym/envs/rearrange/datasets/envstates/base.py
from typing import Dict, List import attr import numpy as np from numpy.random.mtrand import RandomState from robogym.envs.rearrange.common.mesh import MeshRearrangeEnv from robogym.envs.rearrange.datasets.objects.base import ObjectDataset from robogym.envs.rearrange.simulation.base import ObjectGroupConfig @attr.s(auto_attribs=True) class Envstate: """ Set of attributes that fully defines an environment state""" object_groups: List[ObjectGroupConfig] # list of object groups for each objects object_dataset_names: List[str] # object dataset names for each mesh object_ids: List[str] # object id for each mesh in its object dataset init_pos: np.ndarray # initial position of objects is_valid: bool # whether placement of objects are valid init_quats: np.ndarray # initial rotation of objects class EnvstateDataset: """ Base class for environment state dataset """ def __init__( self, object_datasets: Dict[str, ObjectDataset], random_state: RandomState ): """ :param object_datasets: set of object datasets that are used to define environment states {dataset_name: dataset_object}. :param random_state: random state for envstate randomization. """ self._random_state = random_state self.object_datasets = object_datasets self.envstate: Envstate = Envstate( object_groups=[], object_dataset_names=[], object_ids=[], init_pos=np.array([[]]), is_valid=False, init_quats=np.array([[]]), ) self.initialized = False def reset(self, env: MeshRearrangeEnv): self._reset(env) self.initialized = True def _reset(self, env: MeshRearrangeEnv): """ Initialize self.envstate to fully define an environment's initial state """ raise NotImplementedError def check_initialized(self): assert self.initialized, "dataset.reset(env) should be called before env reset" def _post_process_quat( self, quat: np.ndarray, object_groups: List[ObjectGroupConfig], mesh_object_dataset_names: List[str], ) -> np.ndarray: """ Utility function for post processing object orientation based on object dataset specific logics """ assert len(object_groups) == len(mesh_object_dataset_names) assert quat.shape[0] == np.sum( [grp.count for grp in object_groups] ) # num_objects result_quat = quat.copy() idx = 0 for grp, dataset_name in zip(object_groups, mesh_object_dataset_names): dataset = self.object_datasets[dataset_name] result_quat[idx: idx + grp.count] = dataset.post_process_quat( result_quat[idx: idx + grp.count] ) idx += grp.count return result_quat
2,909
34.487805
97
py
robogym
robogym-master/robogym/envs/rearrange/datasets/envstates/utils.py
from typing import Dict from numpy.random.mtrand import RandomState from robogym.envs.rearrange.datasets.objects.base import ObjectDataset from robogym.utils.env_utils import get_function def get_envstate_datasets( dataset_config: Dict[str, dict], object_datasets: Dict[str, ObjectDataset], random_state: RandomState, ): datasets = {} for key in dataset_config: datasets[key] = get_function(dataset_config[key])( object_datasets=object_datasets, random_state=random_state ) return datasets
546
26.35
70
py
robogym
robogym-master/robogym/envs/rearrange/datasets/envstates/random.py
from collections import Counter from copy import deepcopy from typing import Dict, List import numpy as np from numpy.random.mtrand import RandomState from robogym.envs.rearrange.common.mesh import MeshRearrangeEnv from robogym.envs.rearrange.datasets.envstates.base import Envstate, EnvstateDataset from robogym.envs.rearrange.datasets.objects.base import ObjectDataset class RandomObjectDataset(EnvstateDataset): """ Class for randomly generating environment states. An environment state is generated by randomly picking a set of objects from object datasets and then applying default environment randomizations (initial position, orientation, scales ..) """ def __init__( self, object_datasets: Dict[str, ObjectDataset], random_state: RandomState, object_sample_prob: Dict[str, float], ): """ :param object_sample_prob: {object dataset name: probability for sampling from it}. """ super().__init__(object_datasets, random_state) self.object_sample_prob = object_sample_prob self.object_dataset_names = sorted(list(object_sample_prob)) self.object_dataset_prob = [ object_sample_prob[i] for i in self.object_dataset_names ] assert np.sum(self.object_dataset_prob) == 1.0 def _reset(self, env: MeshRearrangeEnv): object_groups = MeshRearrangeEnv._sample_random_object_groups(env) num_groups = len(object_groups) ( meshes, mesh_object_dataset_names, mesh_object_ids, mesh_scales, ) = self._sample_meshes(num_groups) attrs_per_group = { "material_args": MeshRearrangeEnv._sample_object_materials(env, num_groups), "color": MeshRearrangeEnv._sample_object_colors(env, num_groups), "scale": MeshRearrangeEnv._sample_object_size_scales(env, num_groups), "mesh_files": meshes, } attrs_per_group["scale"] *= np.array(mesh_scales) object_groups = MeshRearrangeEnv._set_group_attributes( env, object_groups, attrs_per_group ) # Be sure to recreate sim before randomizing position and rotation, because # randomization algorithm required bounding box for the current mesh objects. # In addition, object_groups should be deepcopied so that scale normalization inside # _recreate_sim is not applied to the current variable. MeshRearrangeEnv._set_object_groups(env, deepcopy(object_groups)) MeshRearrangeEnv._recreate_sim(env) init_quats = self._sample_object_initial_rotations(env) init_quats = self._post_process_quat( init_quats, object_groups, mesh_object_dataset_names ) # Note that environment object placement function should be called after object # orientation is set. Therefore we first set object orientation quats to environment, # and then call object placement function. MeshRearrangeEnv._set_object_initial_rotations(env, init_quats) init_pos, is_valid = MeshRearrangeEnv._generate_object_placements(env) self.envstate = Envstate( object_groups=object_groups, object_dataset_names=mesh_object_dataset_names, object_ids=mesh_object_ids, init_pos=init_pos, is_valid=is_valid, init_quats=init_quats, ) def _sample_meshes(self, num_groups: int): """ Sample object meshes from object datasets """ object_dataset_type_indices = self._random_state.choice( len(self.object_dataset_names), p=self.object_dataset_prob, size=num_groups ) idx_to_num: Counter = Counter(object_dataset_type_indices) meshes: List[List[str]] = [] mesh_object_dataset_names = [] mesh_object_ids = [] mesh_scales = [] for object_dataset_idx, n_groups in idx_to_num.items(): object_dataset_name = self.object_dataset_names[object_dataset_idx] object_dataset = self.object_datasets[object_dataset_name] object_ids = object_dataset.sample(n_groups) for object_id in object_ids: mesh_object_dataset_names.append(object_dataset_name) mesh_object_ids.append(object_id) mesh_scales.append(object_dataset.mesh_scale) meshes.extend(object_dataset.get_mesh_list(object_ids)) assert len(meshes) == len(mesh_object_dataset_names) return meshes, mesh_object_dataset_names, mesh_object_ids, mesh_scales def _sample_object_initial_rotations(self, env: MeshRearrangeEnv): return MeshRearrangeEnv._sample_object_initial_rotations(env) create = RandomObjectDataset
4,804
38.710744
99
py
robogym
robogym-master/robogym/envs/rearrange/tests/test_object_off_table.py
import pytest from robogym.envs.rearrange.composer import make_env class ObjectOffTableTest: def __init__(self): env = make_env() env.reset() self.sim = env.unwrapped.mujoco_simulation @pytest.mark.parametrize( "object_positions,expected_off_table", [ ([[1.3, 0.75, 0.4]], [False]), ([[1.05, 0.4, 0.4]], [False]), ([[1.05, 1.1, 0.4]], [False]), ([[1.55, 0.4, 0.4]], [False]), ([[1.55, 1.1, 0.4]], [False]), ], ) def test_single_obj_on_table(self, object_positions, expected_off_table): assert expected_off_table == self.sim.check_objects_off_table(object_positions) @pytest.mark.parametrize( "object_positions,expected_off_table", [ ([[1.3, 0.75, 0.299]], [True]), ([[1.05, 0.4, 0.299]], [True]), ([[1.05, 1.1, 0.299]], [True]), ([[1.55, 0.4, 0.299]], [True]), ([[1.55, 1.1, 0.299]], [True]), ], ) def test_single_obj_under_table(self, object_positions, expected_off_table): assert expected_off_table == self.sim.check_objects_off_table(object_positions) @pytest.mark.parametrize( "object_positions,expected_off_table", [ ([[-0.1 + 1.05, 0.4, 0.4]], [True]), ([[1.05, -0.1 + 0.4, 0.4]], [True]), ([[-0.1 + 1.05, 1.1, 0.4]], [True]), ([[1.05, +0.1 + 1.1, 0.4]], [True]), ([[+0.1 + 1.55, 0.4, 0.4]], [True]), ([[1.55, -0.1 + 0.4, 0.4]], [True]), ([[+0.1 + 1.55, 1.1, 0.4]], [True]), ([[1.55, +0.1 + 1.1, 0.4]], [True]), ], ) def test_single_obj_outside_table_hor(self, object_positions, expected_off_table): assert expected_off_table == self.sim.check_objects_off_table(object_positions) @pytest.mark.parametrize( "object_positions,expected_off_table", [ ([[-0.1 + 1.05, 0.4, 0.299]], [True]), ([[1.05, -0.1 + 0.4, 0.299]], [True]), ([[-0.1 + 1.05, 1.1, 0.299]], [True]), ([[1.05, +0.1 + 1.1, 0.299]], [True]), ([[+0.1 + 1.55, 0.4, 0.299]], [True]), ([[1.55, -0.1 + 0.4, 0.299]], [True]), ([[+0.1 + 1.55, 1.1, 0.299]], [True]), ([[1.55, +0.1 + 1.1, 0.299]], [True]), ], ) def test_single_obj_outside_and_under(self, object_positions, expected_off_table): assert expected_off_table == self.sim.check_objects_off_table(object_positions) # Multiple objects @pytest.mark.parametrize( "object_positions,expected_off_table", [ ([[1.3, 0.75, 0.4]], [False]), ([[1.05, 0.4, 0.4]], [False]), ([[1.05, 1.1, 0.4]], [False]), ([[1.55, 0.4, 0.4]], [False]), ([[1.55, 1.1, 0.4]], [False]), ], ) def test_mul_obj_on_table(self, object_positions, expected_off_table): object_positions.append([1.3, 0.75, 0.4]) expected_off_table.append(False) assert ( expected_off_table == self.sim.check_objects_off_table(object_positions) ).all() @pytest.mark.parametrize( "object_positions,expected_off_table", [ ([[1.3, 0.75, 0.299]], [True]), ([[1.05, 0.4, 0.299]], [True]), ([[1.05, 1.1, 0.299]], [True]), ([[1.55, 0.4, 0.299]], [True]), ([[1.55, 1.1, 0.299]], [True]), ], ) def test_mul_obj_under_table(self, object_positions, expected_off_table): object_positions.append([1.3, 0.75, 0.4]) expected_off_table.append(False) assert ( expected_off_table == self.sim.check_objects_off_table(object_positions) ).all() @pytest.mark.parametrize( "object_positions,expected_off_table", [ ([[-0.1 + 1.05, 0.4, 0.4]], [True]), ([[1.05, -0.1 + 0.4, 0.4]], [True]), ([[-0.1 + 1.05, 1.1, 0.4]], [True]), ([[1.05, +0.1 + 1.1, 0.4]], [True]), ([[+0.1 + 1.55, 0.4, 0.4]], [True]), ([[1.55, -0.1 + 0.4, 0.4]], [True]), ([[+0.1 + 1.55, 1.1, 0.4]], [True]), ([[1.55, +0.1 + 1.1, 0.4]], [True]), ], ) def test_mul_obj_outside_table_hor(self, object_positions, expected_off_table): object_positions.append([1.3, 0.75, 0.4]) expected_off_table.append(False) assert ( expected_off_table == self.sim.check_objects_off_table(object_positions) ).all() @pytest.mark.parametrize( "object_positions,expected_off_table", [ ([[-0.1 + 1.05, 0.4, 0.299]], [True]), ([[1.05, -0.1 + 0.4, 0.299]], [True]), ([[-0.1 + 1.05, 1.1, 0.299]], [True]), ([[1.05, +0.1 + 1.1, 0.299]], [True]), ([[+0.1 + 1.55, 0.4, 0.299]], [True]), ([[1.55, -0.1 + 0.4, 0.299]], [True]), ([[+0.1 + 1.55, 1.1, 0.299]], [True]), ([[1.55, +0.1 + 1.1, 0.299]], [True]), ], ) def test_mul_obj_outside_and_under(self, object_positions, expected_off_table): object_positions.append([1.3, 0.75, 0.4]) expected_off_table.append(False) assert ( expected_off_table == self.sim.check_objects_off_table(object_positions) ).all()
5,396
35.221477
87
py
robogym
robogym-master/robogym/envs/rearrange/tests/test_goal_generation.py
import mock import numpy as np import pytest from robogym.envs.rearrange.blocks import make_env as make_blocks_env from robogym.envs.rearrange.common.utils import safe_reset_env from robogym.envs.rearrange.composer import make_env as make_composer_env from robogym.envs.rearrange.goals.holdout_object_state import HoldoutObjectStateGoal from robogym.envs.rearrange.goals.object_state import ObjectStateGoal from robogym.envs.rearrange.holdout import make_env as make_holdout_env from robogym.utils import rotation def test_stablize_goal_objects(): random_state = np.random.RandomState(seed=0) env = make_composer_env( parameters={"simulation_params": {"num_objects": 3, "max_num_objects": 8}} ).unwrapped safe_reset_env(env) goal_gen = env.goal_generation # randomly sample goals goal_gen._randomize_goal_orientation(random_state) goal_positions, _ = goal_gen._sample_next_goal_positions(random_state) # intentionally put the target up in the air goal_positions[:, -1] += 0.1 goal_gen.mujoco_simulation.set_target_pos(goal_positions) goal_gen.mujoco_simulation.forward() old_obj_pos = goal_gen.mujoco_simulation.get_object_pos() old_obj_rot = goal_gen.mujoco_simulation.get_object_rot() old_target_pos = goal_gen.mujoco_simulation.get_target_pos() old_target_rot = goal_gen.mujoco_simulation.get_target_rot() goal_gen._stablize_goal_objects() new_obj_pos = goal_gen.mujoco_simulation.get_object_pos() new_obj_rot = goal_gen.mujoco_simulation.get_object_rot() assert np.allclose(new_obj_pos, old_obj_pos) assert np.allclose(new_obj_rot, old_obj_rot) new_target_pos = goal_gen.mujoco_simulation.get_target_pos() new_target_rot = goal_gen.mujoco_simulation.get_target_rot() assert all(old_target_pos[:3, -1] > new_target_pos[:3, -1]) assert not np.allclose(old_target_rot, new_target_rot) @pytest.mark.parametrize("rot_type", ["z_axis", "block", "full"]) def test_randomize_goal_orientation(rot_type): random_state = np.random.RandomState(seed=0) env = make_blocks_env( parameters={"simulation_params": {"num_objects": 3, "max_num_objects": 8}}, constants={ "goal_args": { "randomize_goal_rot": True, "rot_randomize_type": rot_type, "stabilize_goal": False, # stabilize_goal should be False to test 'full' rotation } }, ) safe_reset_env(env) goal_gen = env.goal_generation quats = [] for _ in range(100): goal_gen._randomize_goal_orientation(random_state) quats.append(goal_gen.mujoco_simulation.get_target_quat(pad=False)) quats = np.concatenate(quats, axis=0) # [num randomization, 4] # there should be some variance in the randomized results assert quats.std() > 0.0 if rot_type == "z_axis": # ensure objects are rotated along z axis only for i in range(quats.shape[0]): assert rotation.rot_z_aligned(quats[i], 0.02, include_flip=False) elif rot_type == "block": # ensure at least one face of the block is facing on top for i in range(quats.shape[0]): assert rotation.rot_xyz_aligned(quats[i], 0.02) elif rot_type == "full": # ensure that at least one randomize object has weird pose that any of the face does not # face the top direction rot_xyz_aligned = [] for i in range(quats.shape[0]): rot_xyz_aligned.append(rotation.rot_xyz_aligned(quats[i], 0.02)) assert all(rot_xyz_aligned) is False @mock.patch( "robogym.envs.rearrange.common.base.sample_group_counts", mock.MagicMock(return_value=[3, 2, 1]), ) def test_relative_pos_for_duplicated_objects(): current_goal_state = { "obj_rot": np.array( [ [0, 0, np.pi / 2], [np.pi / 2, 0, 0], [0, np.pi / 2, 0], [np.pi / 2, 0, 0], [0, np.pi / 2, 0], [np.pi / 2, 0, 0], ] ), "obj_pos": np.array( [[2, 2, 2], [3, 3, 4], [0, 1, 1], [1, 2, 3], [1, 1, 1], [5, 5, 6]] ), } target_goal_state = { "obj_rot": np.array( [ [0, np.pi / 2, 0], [0, 0, np.pi / 2], [np.pi / 2, 0, 0], [0, np.pi / 2, 0], [np.pi / 2, 0, 0], [np.pi / 2, 0, 0], ] ), "obj_pos": np.array( [[1, 1, 1], [2, 2, 2], [3, 3, 3], [1, 1, 1], [1, 2, 3], [6, 5, 6]] ), } env = make_composer_env( parameters={ "simulation_params": { "num_objects": 6, "max_num_objects": 6, "num_max_geoms": 1, } } ) safe_reset_env(env) goal_generator = ObjectStateGoal(env.unwrapped.mujoco_simulation) relative_goal = goal_generator.relative_goal(target_goal_state, current_goal_state) assert np.allclose( relative_goal["obj_pos"], np.array([[0, 0, 0], [0, 0, -1], [1, 0, 0], [0, 0, 0], [0, 0, 0], [1, 0, 0]]), ) assert np.allclose(relative_goal["obj_rot"], np.zeros((6, 3))) def test_relative_distance(): pos = np.array( [ [1.35620895, 0.5341387, 0.48623528], [1.37134474, 0.53952575, 0.526087], [1.3713598, 0.53945007, 0.5056565], ] ) goal_state = { "obj_pos": pos, "obj_rot": np.zeros_like(pos), } current_pos = pos.copy() rnd_pos = np.array([np.random.random(), np.random.random(), 0]) current_pos += rnd_pos current_state = { "obj_pos": current_pos, "obj_rot": np.zeros_like(current_pos), } env = make_holdout_env() safe_reset_env(env) goal = HoldoutObjectStateGoal(env.unwrapped.mujoco_simulation) dist = goal.goal_distance(goal_state, current_state) assert np.allclose(dist["rel_dist"], np.zeros(3))
6,025
32.853933
98
py
robogym
robogym-master/robogym/envs/rearrange/tests/test_mesh.py
import numpy as np import pytest from robogym.envs.rearrange.ycb import make_env @pytest.mark.parametrize("mesh_scale", [0.5, 1.0, 1.5]) def test_mesh_centering(mesh_scale): # We know these meshe stls. are not center properly. for mesh_name in ["005_tomato_soup_can", "073-b_lego_duplo", "062_dice"]: env = make_env( parameters={ "mesh_names": mesh_name, "simulation_params": {"mesh_scale": mesh_scale}, } ).unwrapped obj_pos = env.mujoco_simulation.get_object_pos() bounding_pos = env.mujoco_simulation.get_object_bounding_boxes()[:, 0, :] assert np.allclose(obj_pos, bounding_pos, atol=5e-3)
702
32.47619
81
py
robogym
robogym-master/robogym/envs/rearrange/tests/test_observation.py
import numpy as np import pytest from robogym.envs.rearrange.blocks import make_env as make_blocks_env from robogym.envs.rearrange.blocks_train import make_env as make_train_env from robogym.envs.rearrange.common.utils import safe_reset_env from robogym.envs.rearrange.composer import make_env as make_composer_env from robogym.envs.rearrange.tests.test_rearrange_envs import ( _list_rearrange_envs, is_fixed_goal_env, is_fixed_initial_state_env, ) from robogym.envs.rearrange.ycb import make_env as make_ycb_env from robogym.robot.robot_interface import ControlMode def _read_goal_state_from_sim(sim): return np.stack( [ sim.data.get_body_xpos(name).copy() for name in sim.model.body_names if name.startswith("target:object") and not name.startswith("target:object:letter") ], axis=0, ) def is_env_without_goal_rot_randomize(env) -> bool: return any( keyword in str(env.unwrapped.__class__).lower() for keyword in ("reach", "attachedblock") ) def test_vision_observations(): for env in _list_rearrange_envs(constants={"vision": True}): env.seed(123) obs1 = safe_reset_env(env) assert "vision_obs" in obs1 assert "vision_goal" in obs1 for _ in range(10): obs2, _, _, info = env.step(np.ones_like(env.action_space.sample())) assert "vision_obs" in obs2 assert "vision_goal" in obs2 assert "successes_so_far" in info assert not np.allclose(obs1["vision_obs"], obs2["vision_obs"]) if info["successes_so_far"] == 0: # Goal should not have changed. assert np.allclose(obs1["vision_goal"], obs2["vision_goal"]) # check the goal is up-to-date in simulator. old_goal = obs1["goal_obj_pos"].copy() old_sim_goal = _read_goal_state_from_sim(env.unwrapped.sim) assert np.array_equal(old_goal, old_sim_goal) else: # Unlikely but might happen: We achieved the goal on accident and we might # thus have a new goal. old_goal = obs2["goal_obj_pos"].copy() assert not np.allclose(obs1["vision_goal"], obs2["vision_goal"]) # Reset the goal and ensure that the goal vision observation has indeed changed. env.reset_goal() obs3, _, _, _ = env.step(np.zeros_like(env.action_space.sample())) assert "vision_obs" in obs3 assert "vision_goal" in obs3 assert is_fixed_goal_env(env) or not np.allclose( obs2["vision_goal"], obs3["vision_goal"] ) # check the new goal should take effect in simulator. new_goal = obs3["goal_obj_pos"].copy() new_sim_goal = _read_goal_state_from_sim(env.unwrapped.sim) assert is_fixed_goal_env(env) or not np.array_equal(new_goal, old_goal) assert np.array_equal(new_goal, new_sim_goal) @pytest.mark.parametrize("randomize_goal_rot", [True, False]) def test_randomize_goal_rotation(randomize_goal_rot): make_env_args = { "starting_seed": 0, "constants": {"goal_args": {"randomize_goal_rot": randomize_goal_rot}}, "parameters": { "n_random_initial_steps": 0, "simulation_params": {"num_objects": 1}, }, } for make_env in [make_blocks_env, make_train_env]: env = make_env(**make_env_args) obs = safe_reset_env(env) if randomize_goal_rot: assert not np.allclose(obs["obj_rot"], obs["goal_obj_rot"], atol=1e-3) else: # If we do not randomize goal rotation, it is same as object rotation by default. assert np.allclose(obs["obj_rot"], obs["goal_obj_rot"], atol=1e-3) assert np.allclose( obs["rel_goal_obj_rot"], np.zeros(obs["rel_goal_obj_rot"].shape), atol=1e-3, ) @pytest.mark.parametrize("n_random_initial_steps", [0, 5]) @pytest.mark.parametrize("randomize_goal_rot", [True, False]) def test_observations_change_between_resets(n_random_initial_steps, randomize_goal_rot): # Ignore keys which are mostly static, and may or may not differ between resets. skip_keys = { "is_goal_achieved", "rel_goal_obj_rot", "obj_bbox_size", # gripper initial control (should be zero) "gripper_controls", # robogym.envs.rearrange.common.utils.stabilize_objects is not perfect to ensure zero # initial velocity of every object "obj_vel_pos", "obj_vel_rot", # gripper data "gripper_qpos", "gripper_vel", "gripper_pos", "gripper_velp", "obj_gripper_contact", # robot_joint_pos has small perturbation even when n_random_initial_steps=0 "robot_joint_pos", # safety stop obs will be False most of the time, and tcp_force/torque may not change # when the robot is not interacting with objects "safety_stop", "tcp_force", "tcp_torque", } static_keys = {"action_ema"} static_keys = frozenset(static_keys) skip_keys = frozenset(skip_keys) make_env_args = dict( constants={"goal_args": {"randomize_goal_rot": randomize_goal_rot}}, parameters={"n_random_initial_steps": n_random_initial_steps}, starting_seed=1, # seed 0 failed for ReachEnv ) for env in _list_rearrange_envs(**make_env_args): # Fixed goal envs are taken care of in the test below. if is_fixed_goal_env(env): continue extra_skip_keys = set() if is_env_without_goal_rot_randomize(env): extra_skip_keys.add("goal_obj_rot") extra_static_keys = set() if is_fixed_initial_state_env(env): # Unreliable gripper make obj_rel_pos also unreliable. extra_skip_keys.add("obj_rel_pos") extra_static_keys.update(["obj_pos", "obj_rot"]) if not randomize_goal_rot: extra_static_keys.add("goal_obj_rot") if n_random_initial_steps == 0: extra_static_keys.add("qpos") if "block" in env.unwrapped.__class__.__name__.lower(): extra_skip_keys.add("obj_colors") obs1 = safe_reset_env(env) obs2 = safe_reset_env(env) assert set(obs1.keys()) == set(obs2.keys()) for key in obs1: if key in skip_keys or key in extra_skip_keys: continue elif key in static_keys or key in extra_static_keys: assert np.allclose(obs1[key], obs2[key], atol=5e-3), ( f"Observations in {env.unwrapped.__class__.__name__} changed " f"between resets for {key}: {obs1[key]}" ) else: assert not np.allclose(obs1[key], obs2[key], atol=1e-3), ( f"Observations in {env.unwrapped.__class__.__name__} unchanged " f"between resets for {key}: {obs1[key]}" ) def test_static_observations_for_fixed_goal_envs(): static_keys = set(["goal_obj_pos", "goal_obj_rot", "robot_joint_pos", "qpos_goal"]) for env in _list_rearrange_envs( constants={"goal_args": {"randomize_goal_rot": False}}, parameters={"n_random_initial_steps": 0}, starting_seed=0, ): # We are only interested in fixed-goal envs here. # Goals for Chessboard are currently non-deterministic, likely due to physics # stability issues. Remove the check below once physics issues are resolved. if ( not is_fixed_goal_env(env) or env.unwrapped.__class__.__name__ == "ChessboardRearrangeEnv" ): continue obs1 = env.reset() obs2 = env.reset() for key in static_keys: assert np.allclose(obs1[key], obs2[key], atol=1e-2), ( f"Observations in {env.unwrapped.__class__.__name__} changed " f"between resets for {key}: {obs1[key]}" ) def test_observation_static_within_step(): for env in _list_rearrange_envs(): obs = env.reset() for _ in range(5): new_obs = env.observe() for key in new_obs: assert np.allclose(obs[key], new_obs[key]) def test_observations_change_over_time(n_resets=3, n_trials=3): static_keys = frozenset( ( "obj_pos", "obj_rel_pos", "obj_vel_pos", "obj_rot", "obj_vel_rot", "obj_bbox_size", "goal_obj_pos", "goal_obj_rot", "qpos_goal", "is_goal_achieved", "gripper_controls", "gripper_qpos", "gripper_vel", "rel_goal_obj_pos", "rel_goal_obj_rot", "obj_gripper_contact", "obj_colors", "safety_stop", ) ) for env in _list_rearrange_envs(): for reset_i in range(n_resets): obs = safe_reset_env(env) for i in range(n_trials): last_obs = obs # Apply 10 random steps. for _ in range(10): obs, _, _, _ = env.step(env.action_space.sample()) for key in obs: if key not in static_keys: assert not np.allclose(obs[key], last_obs[key]), ( f"Observations unchanged between steps for {key} at reset {reset_i} " f"and trial {i}: {obs[key]}" ) def test_observation_deterministic_with_fixed_seed(): batch1 = _list_rearrange_envs(starting_seed=0) batch2 = _list_rearrange_envs(starting_seed=0) for env1, env2 in zip(batch1, batch2): if "Composer" in env1.unwrapped.__class__.__name__: # FIXME: ComposerRearrangeSim.make_object_xml cannot be controlled by starting seed. continue obs1 = env1.reset() obs2 = env2.reset() assert set(obs1.keys()) == set(obs2.keys()) for key in obs1: assert np.allclose( obs1[key], obs2[key], atol=1e-5 ), f"{env1.unwrapped.__class__.__name__} failed on key {key}" def test_info_obs_consistency(): for env in _list_rearrange_envs(): if "ReachEnv" in str(env.unwrapped): # obs and info['current_state'] consistency does not hold for ReachEnv because # ReachEnv uses `gripper_pos` as `obj_pos` for checking goals. Therefore be sure not # to use `current_state` instead of `obs` for ReachEnv. continue obs1 = env.reset() info1 = env.unwrapped.get_info() for _ in range(5): obs2 = env.observe() info2 = env.unwrapped.get_info() for key in ["obj_pos", "obj_rot"]: assert np.allclose( obs1[key], info1["current_state"][key] ), f"key: {key}" assert np.allclose( obs1[key], info2["current_state"][key] ), f"key: {key}" assert np.allclose(obs1[key], obs2[key]), f"key: {key}" obs1, _, _, info1 = env.step(np.ones_like(env.action_space.sample())) def test_observation_with_default_sim_randomization(): test_seed = 2 env1 = make_blocks_env( starting_seed=test_seed, parameters=dict(n_random_initial_steps=0) ) env1.unwrapped.randomization.simulation_randomizer.disable() env1.seed(test_seed) env1.reset() env1.seed(test_seed) env1.reset_goal() env1.action_space.seed(test_seed) # This feels like an excessive amount of fixing the seed, but it appears that enabling the # default simulation randomizer affects random number generation to some extent, so all of the # seed-fixing below is necessary. env2 = make_blocks_env( starting_seed=test_seed, parameters=dict(n_random_initial_steps=0) ) env2.seed(test_seed) env2.reset() env2.seed(test_seed) env2.reset_goal() env2.action_space.seed(test_seed) # Step such that two envs have same initial and goal states. The # test is to make sure sim randomization by default shoudn't change env # behavior. for _ in range(50): obs1 = env1.step(env1.action_space.sample())[0] obs2 = env2.step(env2.action_space.sample())[0] assert set(obs1.keys()) == set(obs2.keys()) for key in obs1: assert np.allclose( obs1[key], obs2[key], atol=1e-4 ), f"{env1.unwrapped.__class__.__name__} failed on key {key}" @pytest.mark.parametrize( "control_mode, action_dim, gripper_dim, robot_dim, robot_joint_pos", [ (ControlMode.TCP_ROLL_YAW.value, 6, 1, 8, 6), (ControlMode.TCP_WRIST.value, 5, 1, 8, 6), ], ) def test_observation_space( control_mode, action_dim, gripper_dim, robot_dim, robot_joint_pos ): def _get_expected_obs_space_shape(num_objects): return { "goal_obj_pos": (num_objects, 3,), "gripper_pos": (3,), "gripper_qpos": (gripper_dim,), "gripper_vel": (gripper_dim,), "gripper_velp": (3,), "obj_pos": (num_objects, 3,), "obj_rel_pos": (num_objects, 3,), "obj_rot": (num_objects, 3,), "obj_vel_pos": (num_objects, 3,), "obj_vel_rot": (num_objects, 3,), "qpos": (robot_dim + 7 * num_objects,), "qpos_goal": (robot_dim + 7 * num_objects,), "robot_joint_pos": (robot_joint_pos,), "safety_stop": (1,), "tcp_force": (3,), "tcp_torque": (3,), } env_args = dict( parameters=dict(robot_control_params=dict(control_mode=control_mode)), ) for env in _list_rearrange_envs(**env_args): num_objects = env.unwrapped.mujoco_simulation.num_objects ob_shapes = _get_expected_obs_space_shape(num_objects) for key, ref_shape in ob_shapes.items(): assert ( key in env.observation_space.spaces ), f"{key} not in observation_space" curr_shape = env.observation_space.spaces[key].shape assert ( curr_shape == ref_shape ), f"{key} has wrong shape: is {curr_shape}, expected {ref_shape}" obs = safe_reset_env(env) for key, ref_shape in ob_shapes.items(): assert key in obs, f"{key} not in observation_space" curr_shape = obs[key].shape assert ( curr_shape == ref_shape ), f"{key} has wrong shape: is {curr_shape}, expected {ref_shape}" @pytest.mark.parametrize("vision", [True, False]) def test_goals_differ_from_obs(vision): make_env_args = { "constants": {"vision": vision, "goal_args": {"randomize_goal_rot": True}}, "parameters": { "simulation_params": { "num_objects": 3, "goal_rot_weight": 1.0, "goal_distance_ratio": 1.0, } }, } for make_env in [make_blocks_env, make_train_env, make_ycb_env, make_composer_env]: env = make_env(**make_env_args) obs = safe_reset_env(env) assert not np.allclose(obs["obj_pos"], obs["goal_obj_pos"]) assert not np.allclose(obs["obj_rot"], obs["goal_obj_rot"]) obs, _, _, _ = env.step(env.action_space.sample()) assert not np.allclose(obs["obj_pos"], obs["goal_obj_pos"]) assert not np.allclose(obs["obj_rot"], obs["goal_obj_rot"]) obs = safe_reset_env(env, only_reset_goal=True) assert not np.allclose(obs["obj_pos"], obs["goal_obj_pos"]) assert not np.allclose(obs["obj_rot"], obs["goal_obj_rot"]) def test_object_gripper_contact(): env = make_blocks_env( parameters={ "simulation_params": {"num_objects": 3}, "n_random_initial_steps": 0, } ) env.reset() contact = env.unwrapped.mujoco_simulation.get_object_gripper_contact() assert np.array_equal(contact, np.zeros((3, 2)))
16,233
35.399103
98
py
robogym
robogym-master/robogym/envs/rearrange/tests/test_placement.py
import numpy as np import pytest from robogym.envs.rearrange.common.utils import PlacementArea @pytest.mark.parametrize( "used_table_portion,expected_placement_area", [ ( 1.0, PlacementArea( offset=(0.3038, 0.38275, 0.06648), size=(0.6075, 0.58178, 0.26) ), ), ( 0.8, PlacementArea( offset=(0.3645, 0.44093, 0.06648), size=(0.486, 0.46542, 0.26) ), ), ( 0.6, PlacementArea( offset=(0.4253, 0.49911, 0.06648), size=(0.3645, 0.3491, 0.26) ), ), ( 0.4, PlacementArea( offset=(0.486, 0.55728, 0.06648), size=(0.243, 0.23271, 0.26) ), ), ], ) def test_block_placement(used_table_portion, expected_placement_area): from robogym.envs.rearrange.blocks import make_env parameters = dict(simulation_params=dict(used_table_portion=used_table_portion)) env = make_env(parameters=parameters) env.reset() placement_area = env.mujoco_simulation.get_placement_area() assert np.allclose(placement_area.size, expected_placement_area.size, atol=1e-4) assert np.allclose(placement_area.offset, expected_placement_area.offset, atol=1e-4) @pytest.mark.parametrize( "num_objects,object_scale_high,object_scale_low,normalize_mesh", [ (1, 0.0, 0.0, True), (1, 0.0, 0.0, False), (8, 0.0, 0.0, True), (8, 0.0, 0.0, False), (16, 0.0, 0.0, True), (32, 0.0, 0.0, True), (32, 0.7, 0.0, True), (32, 0.0, 0.5, True), ], ) def test_ycb_placement( num_objects, object_scale_high, object_scale_low, normalize_mesh ): # Tests initial/goal object placement in a variety of scenarios. from robogym.envs.rearrange.ycb import make_env parameters = dict( simulation_params=dict( num_objects=num_objects, max_num_objects=num_objects, mesh_scale=1.0 if normalize_mesh else 0.6, ), object_scale_high=object_scale_high, object_scale_low=object_scale_low, ) constants = dict(normalize_mesh=normalize_mesh,) env = make_env(parameters=parameters, constants=constants) for i in range(5): # This will throw an exception if placement is invalid. env.reset()
2,420
28.168675
88
py
robogym
robogym-master/robogym/envs/rearrange/tests/test_object_creation.py
import numpy as np from numpy.testing import assert_allclose from robogym.envs.rearrange.common.utils import ( get_mesh_bounding_box, make_block, make_blocks_and_targets, ) from robogym.envs.rearrange.simulation.composer import RandomMeshComposer from robogym.mujoco.mujoco_xml import MujocoXML def _get_default_xml(): xml_source = """ <mujoco> <asset> <material name="block_mat" specular="0" shininess="0.5" reflectance="0" rgba="1 0 0 1"></material> </asset> </mujoco> """ xml = MujocoXML.from_string(xml_source) return xml def test_mesh_composer(): for path in [ None, RandomMeshComposer.GEOM_ASSET_PATH, RandomMeshComposer.GEOM_ASSET_PATH, ]: composer = RandomMeshComposer(mesh_path=path) for num_geoms in range(1, 6): xml = _get_default_xml() composer.reset() xml.append(composer.sample("object0", num_geoms, object_size=0.05)) sim = xml.build() assert len(sim.model.geom_names) == num_geoms pos, size = get_mesh_bounding_box(sim, "object0") assert np.isclose(np.max(size), 0.05) pos2, size2 = composer.get_bounding_box(sim, "object0") assert np.allclose(pos, pos2) assert np.allclose(size, size2) def test_block_object(): xml = _get_default_xml() xml.append(make_block("object0", object_size=np.ones(3) * 0.05)) sim = xml.build() assert len(sim.model.geom_size) == 1 assert_allclose(sim.model.geom_size, 0.05) def test_blocks_and_targets(): xml = _get_default_xml() for obj_xml, target_xml in make_blocks_and_targets(num_objects=5, block_size=0.05): xml.append(obj_xml) xml.append(target_xml) sim = xml.build() assert len(sim.model.geom_size) == 10 assert_allclose(sim.model.geom_size, 0.05)
1,888
29.467742
106
py
robogym
robogym-master/robogym/envs/rearrange/tests/test_multi_goals_env.py
from unittest import TestCase import numpy as np from robogym.envs.rearrange.blocks import make_env from robogym.utils.testing import assert_dict_match from robogym.wrappers.util import DiscretizeActionWrapper class TestMultiGoalsEnv(TestCase): def setUp(self): np.random.seed(0) self.env = self._create_env( starting_seed=0, constants={ "max_timesteps_per_goal_per_obj": 5, "successes_needed": 5, "success_reward": 100.0, "success_pause_range_s": (0, 0), }, parameters={"simulation_params": {"num_objects": 2}}, ) assert self.env.unwrapped.multi_goal_tracker.max_timesteps_per_goal == 10 assert self.env.unwrapped.constants.max_timesteps_per_goal == 10 self.zero_action = np.zeros(self.env.action_space.shape) def _create_env(self, **env_params): # Create a test env with 2 blocks and position-only goals. env = make_env(**env_params) assert isinstance(env, DiscretizeActionWrapper) env = env.env # remove discretized action so that we can use zero action. env.reset() return env def test_basic_info(self): assert_dict_match(self.env.unwrapped.get_info(), self.env.unwrapped.get_info()) for step in range(9): _, reward, done, info = self.env.step(self.env.action_space.sample()) assert_dict_match(info, self.env.unwrapped.get_info()) assert_dict_match( self.env.unwrapped.get_info(), self.env.unwrapped.get_info() ) assert not done assert list(reward) == [0.0] * 3 assert info["goals_so_far"] == 1 assert info["goal_reachable"] assert not info["goal_terminally_unreachable"] assert not info["solved"] assert not info["sub_goal_is_successful"] assert not info["trial_success"] assert info["steps_since_last_goal"] == step + 1 assert info["sub_goal_type"] == "generic" assert info["steps_by_goal_type"] == {"generic": step + 1} assert info["successes_so_far"] == 0 assert info["successes_so_far_by_goal_type"] == {"generic": 0} assert not info["env_crash"] assert info["steps_per_success"] == 10 assert info["steps_per_success_by_goal_type"] == {"generic": 10} _, _, done, _ = self.env.step(self.env.action_space.sample()) assert done def _fake_one_success(self): obj_pos = self.env.unwrapped._goal["obj_pos"] self.env.unwrapped.mujoco_simulation.set_object_pos(obj_pos) self.env.unwrapped.mujoco_simulation.forward() def test_reset(self): for _ in range(5): for _ in range(5): self.env.step(self.zero_action) self._fake_one_success() assert self.env.step(self.zero_action)[-1]["sub_goal_is_successful"] self.env.reset() info = self.env.step(self.zero_action)[-1] assert info["goals_so_far"] == 1 assert info["steps_since_last_goal"] == 1 assert info["successes_so_far"] == 0 assert info["successes_so_far_by_goal_type"] == {"generic": 0} assert info["steps_per_success"] == 10 assert info["steps_per_success_by_goal_type"] == {"generic": 10} def test_multi_successes_full(self): for goal_idx in range(5): for step in range(5): _, reward, done, info = self.env.step(self.zero_action) assert not done assert not info["sub_goal_is_successful"] assert not info["trial_success"] assert info["steps_since_last_goal"] == step + 1 assert info["successes_so_far"] == goal_idx assert info["goals_so_far"] == goal_idx + 1 assert info["steps_per_success"] == (10 if goal_idx == 0 else 6) self._fake_one_success() _, reward, done, info = self.env.step(self.zero_action) assert reward[0] == 0 assert reward[-1] == 100.0 assert info["sub_goal_is_successful"] assert info["successes_so_far"] == goal_idx + 1 assert info["steps_per_success"] == 6 assert info["steps_per_success_by_goal_type"] == {"generic": 6} if goal_idx == 4: # When the last goal is successful. assert done assert info["trial_success"] assert info["goals_so_far"] == 5 else: # When the episode should continue with more goals. assert not done assert not info["trial_success"] assert info["goals_so_far"] == goal_idx + 2 def test_multi_successes_fail(self): for goal_idx in range(3): # We need 2, 4, 6 steps to achieve one success. steps_to_success = (goal_idx + 1) * 2 for step in range(steps_to_success - 1): _, reward, done, info = self.env.step(self.zero_action) assert not done if goal_idx == 0: expected_steps_per_success = 10 elif goal_idx == 1: expected_steps_per_success = 2 else: expected_steps_per_success = (2 + 4) / 2 assert info["steps_per_success"] == expected_steps_per_success self._fake_one_success() _, reward, done, info = self.env.step(self.zero_action) assert info["sub_goal_is_successful"] # failed on the 4th goal. for step in range(9): _, reward, done, info = self.env.step(self.zero_action) assert not done _, reward, done, info = self.env.step(self.zero_action) assert done assert not info["sub_goal_is_successful"] assert info["steps_per_success"] == (2 + 4 + 6) / 3 assert not info["trial_success"] def test_max_timesteps(self): self.env = self._create_env( starting_seed=0, constants={ "max_timesteps_per_goal_per_obj": 50, "success_reward": 100.0, "successes_needed": 1, "success_pause_range_s": (1.0, 1.0), }, parameters={"simulation_params": {"num_objects": 1, "max_num_objects": 8}}, ) for num_objects in range(1, 9): self.env.unwrapped.randomization.update_parameter( "parameters:num_objects", num_objects ) self.env.reset() assert self.env.unwrapped.mujoco_simulation.num_objects == num_objects assert ( self.env.unwrapped.multi_goal_tracker.max_timesteps_per_goal == 50 * num_objects ) assert ( self.env.unwrapped.constants.max_timesteps_per_goal == 50 * num_objects ) def test_consecutive_success_steps_required(self): self.env = self._create_env( starting_seed=0, constants={ "max_timesteps_per_goal_per_obj": 50, "success_reward": 100.0, "successes_needed": 1, "success_pause_range_s": (1.0, 1.0), }, parameters={"simulation_params": {"num_objects": 2}}, ) mj_sim = self.env.unwrapped.mujoco_simulation.mj_sim step_duration_s = mj_sim.nsubsteps * mj_sim.model.opt.timestep success_steps_required = int(1.0 / step_duration_s) assert ( self.env.unwrapped.multi_goal_tracker._success_steps_required == success_steps_required ) # take 4 steps without achieving the goal. for i in range(4): _, _, done, info = self.env.step(self.zero_action) assert not done assert not info["sub_goal_is_successful"] assert info["steps_since_last_goal"] == i + 1 assert ( self.env.unwrapped.multi_goal_tracker._consecutive_steps_with_success == 0 ) # achieve the goal! self._fake_one_success() # remain the state for successful goal achievement for some steps. for j in range(success_steps_required - 1): _, _, done, info = self.env.step(self.zero_action) assert ( self.env.unwrapped.multi_goal_tracker._consecutive_steps_with_success == j + 1 ) assert not done assert not info["sub_goal_is_successful"] assert not info["trial_success"] assert info["steps_since_last_goal"] == j + 5 _, _, done, info = self.env.step(self.zero_action) assert ( self.env.unwrapped.multi_goal_tracker._consecutive_steps_with_success == success_steps_required ) assert done assert info["sub_goal_is_successful"] assert info["trial_success"]
9,153
36.670782
87
py
robogym
robogym-master/robogym/envs/rearrange/tests/test_object_rotation.py
import os from typing import Tuple import numpy as np import pytest from mock import patch from numpy.random import RandomState from numpy.testing import assert_allclose from robogym.envs.rearrange.blocks import make_env as make_blocks_env from robogym.envs.rearrange.common.mesh import MeshRearrangeEnv from robogym.envs.rearrange.common.utils import rotate_bounding_box, safe_reset_env from robogym.envs.rearrange.goals.object_state import ObjectStateGoal from robogym.envs.rearrange.ycb import make_env as make_ycb_env from robogym.mujoco.mujoco_xml import ASSETS_DIR from robogym.utils import rotation class SimpleGeomMeshRearrangeEnv(MeshRearrangeEnv): def _sample_object_meshes(self, num_groups: int): geom = self.parameters.mesh_names[0] return [[os.path.join(ASSETS_DIR, "stls/geom", f"{geom}.stl")]] * num_groups class FixedRotationGoal(ObjectStateGoal): def __init__(self, *args, fixed_z=0.0, **kwargs): self.fixed_z = fixed_z super().__init__(*args, **kwargs) def _sample_next_goal_positions( self, random_state: RandomState ) -> Tuple[np.ndarray, bool]: object_pos = self.mujoco_simulation.get_object_pos()[ : self.mujoco_simulation.num_objects ] return object_pos.copy(), True def _sample_next_goal_orientations(self, random_state: RandomState) -> np.ndarray: num_objects = self.mujoco_simulation.num_objects z_quat = rotation.quat_from_angle_and_axis( angle=np.array([self.fixed_z] * num_objects), axis=np.array([[0, 0, 1.0]] * num_objects), ) return rotation.quat_mul( z_quat, self.mujoco_simulation.get_target_quat(pad=False) ) def _run_rotation_test(make_env, parameters, constants, angles_to_dists, atol=0.005): env = make_env(parameters=parameters, constants=constants) env.unwrapped.goal_generation = FixedRotationGoal( env.mujoco_simulation, args=constants["goal_args"] ) for angle, dist in angles_to_dists.items(): # Attempt 10 times, since sometimes the object is placed so that the gripper bumps # into it. for attempt in range(10): env.unwrapped.goal_generation.fixed_z = angle safe_reset_env(env) info = env.goal_info()[-1] assert "goal_dist" in info if np.allclose(info["goal_dist"]["obj_rot"], dist, atol=atol): break assert_allclose(info["goal_dist"]["obj_rot"], dist, atol=atol) def test_mod90_rotation_blocks(): parameters = {} constants = { "goal_args": {"rot_dist_type": "mod90", "randomize_goal_rot": True}, "success_threshold": {"obj_pos": 0.05, "obj_rot": 0.2}, } angles_to_dists = { # Basic cases. 0.0: 0.0, 0.05: 0.05, 0.1: 0.1, # Rotating in different direction has same distance. -0.05: 0.05, -0.1: 0.1, # mod90-specific cases np.pi: 0.0, -np.pi: 0.0, 2 * np.pi: 0.0, np.pi / 2: 0.0, -np.pi / 2: 0.0, np.pi / 2 + 0.05: 0.05, np.pi / 2 - 0.05: 0.05, np.pi / 4: np.pi / 4, np.pi / 4 + 0.05: np.pi / 4 - 0.05, np.pi / 4 - 0.05: np.pi / 4 - 0.05, } _run_rotation_test(make_blocks_env, parameters, constants, angles_to_dists) def test_mod180_rotation_blocks(): parameters = {} constants = { "goal_args": {"rot_dist_type": "mod180", "randomize_goal_rot": True}, "success_threshold": {"obj_pos": 0.05, "obj_rot": 0.2}, } angles_to_dists = { # Basic cases. 0.0: 0.0, 0.05: 0.05, 0.1: 0.1, # Rotating in different direction has same distance. -0.05: 0.05, -0.1: 0.1, # mod180-specific cases np.pi: 0.0, -np.pi: 0.0, 2 * np.pi: 0.0, np.pi / 2: np.pi / 2, -np.pi / 2: np.pi / 2, np.pi / 4: np.pi / 4, -np.pi / 4: np.pi / 4, np.pi * 3 / 4: np.pi / 4, -np.pi * 3 / 4: np.pi / 4, np.pi * 5 / 4: np.pi / 4, -np.pi * 5 / 4: np.pi / 4, np.pi + 0.05: 0.05, np.pi - 0.05: 0.05, np.pi / 2 + 0.05: np.pi / 2 - 0.05, np.pi / 2 - 0.05: np.pi / 2 - 0.05, } _run_rotation_test(make_blocks_env, parameters, constants, angles_to_dists) def test_full_rotation_blocks(): parameters = {} constants = { "goal_args": {"rot_dist_type": "full", "randomize_goal_rot": True}, "success_threshold": {"obj_pos": 0.05, "obj_rot": 0.2}, } angles_to_dists = { # Basic cases. 0.0: 0.0, 0.05: 0.05, 0.1: 0.1, # Rotating in different direction has same distance. -0.05: 0.05, -0.1: 0.1, # full-specific cases np.pi: np.pi, np.pi / 2: np.pi / 2, -np.pi / 2: np.pi / 2, np.pi + 0.05: np.pi - 0.05, np.pi - 0.05: np.pi - 0.05, 2 * np.pi: 0.0, } _run_rotation_test(make_blocks_env, parameters, constants, angles_to_dists) def test_bounding_box_rotation(): # Identity quaternion should have no effect. bounding_box = (np.zeros(3), np.ones(3)) quat = np.array([1, 0, 0, 0]) rotated_bounding_box = rotate_bounding_box(bounding_box, quat) assert_allclose(bounding_box, rotated_bounding_box) # 90 degree rotations should have no effect. bounding_box = (np.zeros(3), np.ones(3)) for parallel in rotation.get_parallel_rotations(): quat = rotation.euler2quat(parallel) rotated_bounding_box = rotate_bounding_box(bounding_box, quat) assert_allclose(bounding_box, rotated_bounding_box) # 45 degree rotation around parallel axis. for axis in [[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]: bounding_box = (np.zeros(3), np.ones(3)) quat = rotation.quat_from_angle_and_axis( np.array(np.deg2rad(45)), axis=np.array(axis) ) assert quat.shape == (4,) rotated_bounding_box = rotate_bounding_box(bounding_box, quat) assert_allclose(rotated_bounding_box[0], np.zeros(3)) axis_idx = np.argmax(axis) ref_size = np.ones(3) * np.sqrt(2) ref_size[axis_idx] = 1.0 assert_allclose(rotated_bounding_box[1], ref_size) def test_full_rotation_ycb(): parameters = {"mesh_names": ["029_plate"]} constants = { "goal_args": {"rot_dist_type": "full", "randomize_goal_rot": True}, "success_threshold": {"obj_pos": 0.05, "obj_rot": 0.2}, } angles_to_dists = { # Basic cases. 0.0: 0.0, 0.05: 0.05, 0.1: 0.1, 2 * np.pi: 0.0, # Rotating in different direction has same distance. -0.05: 0.05, -0.1: 0.1, # full-specific cases np.pi: np.pi, np.pi / 2: np.pi / 2, -np.pi / 2: np.pi / 2, np.pi + 0.05: np.pi - 0.05, np.pi - 0.05: np.pi - 0.05, 2 * np.pi: 0.0, } _run_rotation_test(make_ycb_env, parameters, constants, angles_to_dists) # FIXME: The test is flaky when use_bbox_precheck = True. @pytest.mark.parametrize("use_bbox_precheck", [False]) @pytest.mark.parametrize( "mesh_names,z_rots,matches", [ # rotation symmetry around z axis. ( [ "005_tomato_soup_can", "029_plate", "024_bowl", "013_apple", "017_orange", "007_tuna_fish_can", ], [0.0, np.pi / 4, np.pi / 2, np.pi * 3 / 4], [True, True, True, True], ), # mod90 symmetry around z axis. ( ["062_dice", "070-b_colored_wood_blocks"], [0.0, np.pi / 4, np.pi / 2, np.pi * 3 / 4], [True, False, True, False], ), # mod180 symmetry around z axis. ( [ "061_foam_brick", "009_gelatin_box", "008_pudding_box", "003_cracker_box", "004_sugar_box", ], [0.0, np.pi / 4, np.pi / 2, np.pi], [True, False, False, True], ), # asymmetric objects. ( [ "037_scissors", "011_banana", "030_fork", "050_medium_clamp", "048_hammer", "072-b_toy_airplane", "035_power_drill", "033_spatula", "042_adjustable_wrench", ], [0.0, np.pi / 4, np.pi / 2, np.pi * 3 / 4, np.pi], [True, False, False, False, False, False], ), ], ) def test_icp_rotation_goal_mesh(use_bbox_precheck, mesh_names, z_rots, matches): for mesh_name in mesh_names: env = make_ycb_env( constants={ "goal_args": { "randomize_goal_rot": True, "rot_dist_type": "icp", "icp_use_bbox_precheck": use_bbox_precheck, } }, parameters={"n_random_initial_steps": 0, "mesh_names": [mesh_name]}, ).unwrapped _run_icp_rotation_goal_test(env, z_rots, matches) @pytest.mark.parametrize( "mesh_names,init_rot,z_rots,matches", [ # mod180 symmetry around z axis. ( ["capsule"], np.array([0.0, np.pi / 2, 0.0]), [0.0, np.pi / 4, np.pi / 2, np.pi], [True, False, False, True], ), # rotation symmetry around z axis. ( ["cylinder", "capsule", "halfsphere", "sphere320", "sphere1280"], np.zeros(3), [0.0, np.pi / 4, np.pi / 2, np.pi * 3 / 4], [True, True, True, True], ), # mod90 symmetry around z axis. ( ["cube"], np.zeros(3), [0.0, np.pi / 4, np.pi / 2, np.pi * 3 / 4], [True, False, True, False], ), ], ) def test_icp_rotation_goal_geom(mesh_names, init_rot, z_rots, matches): for mesh_name in mesh_names: env = SimpleGeomMeshRearrangeEnv.build( constants={ "goal_args": {"randomize_goal_rot": True, "rot_dist_type": "icp"} }, parameters={"n_random_initial_steps": 0, "mesh_names": [mesh_name]}, ).unwrapped _run_icp_rotation_goal_test(env, z_rots, matches, init_rot=init_rot) def _run_icp_rotation_goal_test(env, z_rots, matches, init_rot=np.zeros(3)): init_quat = rotation.euler2quat(init_rot) for z_rot, match in zip(z_rots, matches): def mock_randomize_goal_rot(*args, **kwargs): z_quat = rotation.quat_from_angle_and_axis(z_rot, np.array([0.0, 0.0, 1])) target_quat = rotation.quat_mul(z_quat, init_quat) env.mujoco_simulation.set_object_quat(np.array([init_quat])) env.mujoco_simulation.set_target_quat(np.array([target_quat])) env.mujoco_simulation.forward() with patch( "robogym.envs.rearrange.goals.object_state.ObjectStateGoal." "_randomize_goal_orientation" ) as mock_obj: mock_obj.side_effect = mock_randomize_goal_rot safe_reset_env(env) # set the object position same as the target position. sim = env.unwrapped.mujoco_simulation sim.set_object_pos(sim.get_target_pos()) sim.forward() goal_dist = env.unwrapped.goal_generation.goal_distance( env.unwrapped._goal, env.unwrapped.goal_generation.current_state() ) rot_dist = goal_dist["obj_rot"] if match: assert np.all(rot_dist < 0.2) else: assert np.all(rot_dist > 0.2)
11,848
31.732044
90
py
robogym
robogym-master/robogym/envs/rearrange/tests/test_rearrange_sim.py
import numpy as np import pytest from robogym.envs.rearrange.blocks import make_env as make_blocks_env from robogym.envs.rearrange.simulation.base import RearrangeSimulationInterface from robogym.robot.robot_interface import ControlMode, TcpSolverMode from robogym.wrappers.util import DiscretizeActionWrapper def test_sim_sizes(): env = make_blocks_env( parameters=dict(robot_control_params=dict(tcp_solver_mode="mocap")) ) env.reset() assert env.sim.model.njmax == 2000 assert env.sim.model.nconmax == 500 assert env.sim.model.nuserdata == 2000 assert env.sim.model.nuser_actuator == 16 assert env.sim.model.opt.timestep == 0.001 arm_simulation = env.robot.robots[0].controller_arm.mj_sim assert arm_simulation.model.opt.timestep == 0.001 assert arm_simulation == env.sim @pytest.mark.parametrize( "control_mode,tcp_solver_mode", [ [ControlMode.TCP_WRIST, TcpSolverMode.MOCAP_IK], [ControlMode.TCP_ROLL_YAW, TcpSolverMode.MOCAP_IK], ], ) def test_dual_sim_sizes(control_mode, tcp_solver_mode): env = make_blocks_env( parameters=dict( robot_control_params=dict( control_mode=control_mode, tcp_solver_mode=tcp_solver_mode ) ) ) env.reset() assert env.sim.model.njmax == 2000 assert env.sim.model.nconmax == 500 assert env.sim.model.nuserdata == 2000 assert env.sim.model.nuser_actuator == 16 arm_simulation = env.robot.robots[0].controller_arm.mj_sim assert arm_simulation != env.sim assert arm_simulation.model.njmax == 200 assert arm_simulation.model.nconmax == 200 assert arm_simulation.model.nuserdata == 200 assert arm_simulation.model.nuser_actuator == 16 def test_dual_sim_stepping_times(): """Ensures time advances the same way for main and solver sim to avoid bugs like double-stepping sims """ env = make_blocks_env( parameters=dict( robot_control_params=dict( control_mode=ControlMode.TCP_ROLL_YAW, tcp_solver_mode=TcpSolverMode.MOCAP_IK, ) ) ) env.reset() def get_main_sim_time(): return env.mujoco_simulation.mj_sim.data.time def get_solver_sim_time(): return env.robot.robots[0].controller_arm.mj_sim.data.time initial_offset = get_main_sim_time() - get_solver_sim_time() for _ in range(10): env.step(env.action_space.sample()) time_diff = get_main_sim_time() - get_solver_sim_time() assert np.isclose(time_diff, initial_offset, atol=1e-5), ( f"Time does not advance at the same" f"rate for both sims. " f"diff: {time_diff - initial_offset:.3f}s" ) def test_dual_sim_timesteps(): env = make_blocks_env(constants=dict(mujoco_timestep=0.008,)) env.reset() arm_simulation = env.robot.robots[0].controller_arm.mj_sim assert env.sim.model.opt.timestep == 0.008 assert arm_simulation.model.opt.timestep == 0.008 def test_dual_sim_gripper_sync(): env = make_blocks_env( parameters=dict( n_random_initial_steps=0, robot_control_params=dict(tcp_solver_mode=TcpSolverMode.MOCAP_IK,), ), starting_seed=2, ) env.reset() # Remove discretize action wrapper so the env accepts zero action. assert isinstance(env, DiscretizeActionWrapper) env = env.env def _get_helper_gripper_qpos(): helper_sim = env.robot.robots[0].controller_arm.simulation return helper_sim.gripper.observe().joint_positions()[0] # verify initial gripper state is synced between two sims main_sim_gripper_pos = env.observe()["gripper_qpos"] assert np.isclose(main_sim_gripper_pos, 0.0, atol=1e-4) assert np.isclose(_get_helper_gripper_qpos(), 0.0, atol=1e-4) # open gripper zeros_open_gripper = np.zeros_like(env.action_space.sample()) zeros_open_gripper[-1] = -1 for i in range(25): # first 5 steps deviate more, then the helper arm should catch up. obs_tol = 0.012 if i < 5 else 0.001 env.step(zeros_open_gripper) assert np.isclose( env.observe()["gripper_qpos"], _get_helper_gripper_qpos(), atol=obs_tol ) # verify final gripper state is synced between two sims main_sim_gripper_pos = env.observe()["gripper_qpos"] assert np.isclose(main_sim_gripper_pos, -0.04473, atol=1e-4) assert np.isclose(_get_helper_gripper_qpos(), -0.04473, atol=1e-4) @pytest.mark.parametrize( "reset_controller_error, max_position_change, expected_displacement, response_time_steps", [ (True, 0.165, 0.036, 5), (False, 0.05, 0.0363, 12), (True, 0.1, 0.022, 5), (False, 0.03, 0.022, 12), ], ) def test_mocap_ik_impulse_response( reset_controller_error, max_position_change, expected_displacement, response_time_steps, ): """ Ensures that the expected displacement is achieved after an 'impulse' action at a given TCP dimension to the policy within a given responsiveness. :param reset_controller_error: Whether the test resets controller error on mocap_ik motion :param max_position_change: Max position change in TCP space :param expected_displacement: Expected steady-state displacement caused by the impulse action :param response_time_steps: Number of steps it should take to reach 90% of the expected steady-state displacement """ def make_env(arm_reset_controller_error, max_position_change): env = make_blocks_env( parameters=dict( n_random_initial_steps=0, robot_control_params=dict( control_mode=ControlMode.TCP_ROLL_YAW, tcp_solver_mode=TcpSolverMode.MOCAP_IK, arm_reset_controller_error=arm_reset_controller_error, max_position_change=max_position_change, ), ), starting_seed=0, ) env.reset() # Remove discretize action wrapper so the env accepts zero action. assert isinstance(env, DiscretizeActionWrapper) return env.env def get_trajectory(impulse_dim, impulse_lag=2, **kwargs): """ Generates a trajectory with applying an "impulse" maximum action in the specified dimension. :param impulse_dim: Specified action dimension to apply the impulse to :param impulse_lag: Lag in steps before we apply the impulse :return: Gripper pos trajectories for main and helper arms """ mocap_env = make_env(**kwargs) zero_action = np.zeros(mocap_env.action_space.shape[0]) impulse_action = zero_action.copy() impulse_action[impulse_dim] = 1 gripper_pos = [] helper_pos = [] main_arm = mocap_env.robot.robots[0] helper_arm = mocap_env.robot.robots[0].controller_arm for _ in range(impulse_lag): mocap_env.step(zero_action) gripper_pos.append(main_arm.observe().tcp_xyz()) helper_pos.append(helper_arm.observe().tcp_xyz()) for _ in range(1): mocap_env.step(impulse_action) gripper_pos.append(main_arm.observe().tcp_xyz()) helper_pos.append(helper_arm.observe().tcp_xyz()) for _ in range(40): mocap_env.step(zero_action) gripper_pos.append(main_arm.observe().tcp_xyz()) helper_pos.append(helper_arm.observe().tcp_xyz()) return np.asarray(gripper_pos), np.asarray(helper_pos) impulse_lag = 2 # apply an impulse action in x, y, z dimensions for control_dimension in range(3): main_pos, helper_pos = get_trajectory( impulse_dim=control_dimension, impulse_lag=impulse_lag, max_position_change=max_position_change, arm_reset_controller_error=reset_controller_error, ) # normalize main pos main_pos = main_pos - main_pos[0, :] total_displacement = main_pos[-1, control_dimension] assert np.isclose(total_displacement, expected_displacement, atol=1e-3) # assert that we can get within 10% of the max value in <rise_time_steps> steps assert ( np.abs(main_pos[impulse_lag + response_time_steps, control_dimension]) > total_displacement * 0.9 ) def test_hide_geoms(): """ Tests all modes of RearrangeSimulationInterface._hide_geoms """ env = make_blocks_env(constants=dict(vision=True), starting_seed=0) env.reset() sim: RearrangeSimulationInterface = env.mujoco_simulation img_no_hiding = sim.render() img_no_hiding2 = sim.render() # Sanity check that two renderings of the same state are identical. assert np.allclose(img_no_hiding, img_no_hiding2) with sim.hide_target(): img_hide_targets = sim.render() assert not np.allclose( img_no_hiding, img_hide_targets ), "Image with hidden targets should be different than without hiding targets" with sim.hide_target(hide_robot=True): img_hide_targets_and_robot = sim.render() assert not np.allclose( img_hide_targets, img_hide_targets_and_robot ), "Hiding the robot should result in a different image" with sim.hide_objects(): img_hide_objects = sim.render() assert not np.allclose( img_hide_objects, img_hide_targets ), "Image with hidden objects & targets should be different than with just hiding targets" with sim.hide_objects(hide_robot=True): img_hide_objects_and_robot = sim.render() assert not np.allclose( img_hide_objects, img_hide_objects_and_robot ), "Hiding the robot should result in a different image"
9,853
35.906367
119
py
robogym
robogym-master/robogym/envs/rearrange/tests/test_rearrange_envs.py
from copy import deepcopy from glob import glob from os.path import abspath, basename, dirname, join import numpy as np import pytest from mock import patch import robogym.utils.rotation as rotation from robogym.envs.rearrange.blocks import make_env as make_blocks_env from robogym.envs.rearrange.blocks_reach import make_env as make_reach_env from robogym.envs.rearrange.common.utils import ( geom_ids_of_body, load_material_args, recursive_dict_update, safe_reset_env, ) from robogym.envs.rearrange.composer import make_env as make_composer_env from robogym.envs.rearrange.goals.object_state import ObjectStateGoal from robogym.envs.rearrange.holdout import HoldoutRearrangeEnv from robogym.mujoco.mujoco_xml import StaleMjSimError from robogym.robot.robot_interface import ( ControlMode, RobotControlParameters, TcpSolverMode, ) from robogym.utils.env_utils import InvalidSimulationError, load_env from robogym.utils.rotation import normalize_angles def is_holdout_env(env) -> bool: return isinstance(env.unwrapped, HoldoutRearrangeEnv) def is_fixed_goal_env(env) -> bool: # The manually designed hold-out envs which can provide the same goal across resets. FIXED_GOAL_ENVS = [ "TableSetting", "Chessboard", "WordBlocks", "DiversityBlockRearrange", ] if any(keyword in str(env.unwrapped.__class__) for keyword in FIXED_GOAL_ENVS): return True if is_holdout_env(env): return len(env.unwrapped.constants.goal_args.goal_state_paths) == 1 return False def is_fixed_initial_state_env(env) -> bool: if is_holdout_env(env): return env.unwrapped.constants.initial_state_path is not None else: return False def is_complex_object_env(env) -> bool: # For envs with complex objects, different keys should be static. Here, # we exclude all object-related things since the objects for YCB are not simple # blocks, i.e. they will move slightly when positioned due to their more complex # geometry. COMPLEX_OBJECT_ENVS = ["Ycb", "ShapeNet", "Composer"] return any( keyword in str(env.unwrapped.__class__) for keyword in COMPLEX_OBJECT_ENVS ) def _list_rearrange_envs(include_holdout=True, **kwargs): rearrange_path = abspath(join(dirname(__file__), "..")) # Load envs defined as python file. for env_path in glob(join(rearrange_path, "*.py")): if basename(env_path).startswith("__"): continue if basename(env_path) == "holdout.py": # Don't load holdout env directly. continue if "shapenet" in env_path: # We need to use small default mesh_scale for shapenet because objects are too big # and this causes collision among objects and a robot. shapenet_args = recursive_dict_update( deepcopy(kwargs), {"parameters": {"simulation_params": {"mesh_scale": 0.1}}}, ) yield load_env(env_path, **shapenet_args) else: yield load_env(env_path, **kwargs) # Load holdout envs defined as jsonnet. if include_holdout: for env_path in glob(join(rearrange_path, "holdouts/configs", "*.jsonnet")): yield load_env(f"{env_path}::make_env", **kwargs) def test_env_basic_action(): for env in _list_rearrange_envs(): safe_reset_env(env) for _ in range(10): env.step(env.action_space.sample()) def test_composer_env(): for num_max_geoms in [1, 3, 5, 8]: parameters = { "simulation_params": {"num_max_geoms": num_max_geoms, "num_objects": 3} } env = make_composer_env(parameters=parameters) for _ in range(10): safe_reset_env(env) env.step(env.action_space.sample()) @pytest.mark.parametrize( "control_mode, expected_action_dim", [(ControlMode.TCP_WRIST.value, 5), (ControlMode.TCP_ROLL_YAW.value, 6)], ) def test_action_space(control_mode, expected_action_dim): env_args = dict( parameters=dict(robot_control_params=dict(control_mode=control_mode)), ) for env in _list_rearrange_envs(**env_args): assert len(env.action_space.sample()) == expected_action_dim def test_max_num_objects(): """ Test which makes sure all rearrange environments runs fine with max number of objects. """ env = make_blocks_env( parameters={"simulation_params": {"num_objects": 8, "max_num_objects": 8}} ) env.reset() env.step(env.action_space.sample()) REACH_THRESHOLD = 0.02 STEPS_THRESHOLD = 10 @pytest.mark.parametrize( "control_mode, action_dim", [(ControlMode.TCP_WRIST.value, 5), (ControlMode.TCP_ROLL_YAW.value, 6)], ) def test_gripper_table_proximity(control_mode, action_dim): env = make_blocks_env( parameters={ "n_random_initial_steps": 0, "robot_control_params": {"control_mode": control_mode}, }, starting_seed=0, ) env.reset() # prompt arm to move in the -z direction action = np.zeros(action_dim) action[2] = -1.0 gripper_z_obs = env.observe()["gripper_pos"][2] # robot0:grip site offset z_min = np.Inf _, _, table_height = env.mujoco_simulation.get_table_dimensions() t = 0 while gripper_z_obs > table_height + REACH_THRESHOLD and t < STEPS_THRESHOLD: env.unwrapped.step(action) gripper_z_obs = env.observe()["gripper_pos"][2] z_min = min(z_min, gripper_z_obs) t += 1 gripper_z_obs = env.observe()["gripper_pos"][2] # gripper can get within REACH_THRESHOLD units to the tabletop assert gripper_z_obs <= table_height + REACH_THRESHOLD # gripper does not get closer to the table than TCP_PROTECTION_THRESHOLD assert z_min >= table_height def test_randomize_camera(): env = make_blocks_env( parameters={ "simulation_params": { "camera_fovy_radius": 0.1, "camera_pos_radius": 0.007, "camera_quat_radius": 0.09, } } ) nc = len(env.mujoco_simulation.initial_values["camera_fovy"]) for _ in range(5): env.reset() assert np.all( np.abs( env.mujoco_simulation.mj_sim.model.cam_fovy - env.mujoco_simulation.initial_values["camera_fovy"] ) < 0.1 ) assert np.allclose( np.linalg.norm( env.mujoco_simulation.mj_sim.model.cam_pos - env.mujoco_simulation.initial_values["camera_pos"], axis=1, ), 0.007, ) for ic in range(nc): # quarernion between two quat should be cos(a/2) angle = rotation.quat_mul( rotation.quat_conjugate( env.mujoco_simulation.mj_sim.model.cam_quat[ic] ), env.mujoco_simulation.initial_values["camera_quat"][ic], ) assert abs(angle[0] - np.cos(0.045)) < 1e-6 def test_randomize_lighting(): env = make_blocks_env( parameters={ "simulation_params": { "light_pos_range": 0.8, "light_ambient_intensity": 0.6, "light_diffuse_intensity": 0.4, } } ) for trial in range(5): env.reset() light_pos = env.mujoco_simulation.mj_sim.model.light_pos light_dir = env.mujoco_simulation.mj_sim.model.light_dir for i in range(len(light_pos)): position = light_pos[i] direction = light_dir[i] pos_norm = np.linalg.norm(position) dir_norm = np.linalg.norm(direction) assert np.isclose(pos_norm, 4.0), "Lights should always be 4m from origin" assert np.isclose(dir_norm, 1.0), "Light direction should be unit norm" assert np.allclose( -position / pos_norm, direction ), "Light direction should always point to the origin" ambient_intensity = env.mujoco_simulation.mj_sim.model.vis.headlight.ambient assert np.allclose(ambient_intensity, 0.6) diffuse_intensity = env.mujoco_simulation.mj_sim.model.vis.headlight.diffuse assert np.allclose(diffuse_intensity, 0.4) @pytest.mark.parametrize("material_name", ["painted_wood", "rubber-ball"]) def test_randomize_material(material_name): def str_to_np_array(s): return np.array([float(v) for v in s.split(" ")]) material_args = load_material_args(material_name) for env in _list_rearrange_envs( include_holdout=False, parameters={"material_names": [material_name]} ): env.reset() sim = env.unwrapped.mujoco_simulation.sim for i in range(env.unwrapped.mujoco_simulation.num_objects): geom_ids = geom_ids_of_body(sim, f"object{i}") for geom_id in geom_ids: for key in ["solref", "solimp", "friction"]: if key in material_args["geom"]: expected = str_to_np_array(material_args["geom"][key]) actual = (getattr(sim.model, f"geom_{key}")[geom_id],) assert np.allclose(actual, expected) def test_invalid_goal_crash(): class InvalidStateGoal(ObjectStateGoal): def next_goal(self, random_state, current_state): goal = super().next_goal(random_state, current_state) goal["goal_valid"] = False return goal env = make_blocks_env() env.unwrapped.goal_generation = InvalidStateGoal(env.unwrapped.mujoco_simulation) for fn in [env.reset, env.reset_goal, env.reset_goal_generation]: with pytest.raises(InvalidSimulationError): fn() @pytest.mark.parametrize( "control_mode,tcp_solver_mode", [ [ControlMode.TCP_WRIST, TcpSolverMode.MOCAP], [ControlMode.TCP_ROLL_YAW, TcpSolverMode.MOCAP], [ControlMode.TCP_ROLL_YAW, TcpSolverMode.MOCAP_IK], [ControlMode.TCP_WRIST, TcpSolverMode.MOCAP_IK], ], ) def test_randomize_initial_robot_position(control_mode, tcp_solver_mode): parameters = dict( n_random_initial_steps=10, robot_control_params=dict( control_mode=control_mode, tcp_solver_mode=tcp_solver_mode, max_position_change=RobotControlParameters.default_max_pos_change_for_solver( control_mode=control_mode, tcp_solver_mode=tcp_solver_mode, ), ), ) for env in _list_rearrange_envs(parameters=parameters, starting_seed=1): obs1 = safe_reset_env(env) obs2 = safe_reset_env(env) # robot TCP pos is randomized, gripper not in motion assert not np.allclose(obs2["gripper_pos"], obs1["gripper_pos"]) assert np.allclose(obs2["gripper_velp"], 0.0, atol=3e-3) @pytest.mark.parametrize( "make_env,z_action,tcp_solver_mode", [ (make_blocks_env, 1, TcpSolverMode.MOCAP), (make_blocks_env, 1, TcpSolverMode.MOCAP_IK), (make_blocks_env, -1, TcpSolverMode.MOCAP), (make_blocks_env, -1, TcpSolverMode.MOCAP_IK), (make_reach_env, 1, TcpSolverMode.MOCAP), (make_reach_env, 1, TcpSolverMode.MOCAP_IK), (make_reach_env, -1, TcpSolverMode.MOCAP), (make_reach_env, -1, TcpSolverMode.MOCAP_IK), ], ) def test_table_collision_penalty(make_env, z_action, tcp_solver_mode): """ This test ensures table penalty is applied correctly when the gripper is in close proximity of the table, and also tests it is not spuriously applied when it is not. To achieve this, it applies a prescribed action in the Z direction to the arm and checks the gripper penalties are calculated correctly. :param make_env: make_env function to test :param z_action: action to apply in the world Z direction. All other actions will be zero. :param tcp_solver_mode: TCP solver mode to test. """ TABLE_COLLISION_PENALTY = 0.2 # Reward calculated by RobotEnv is of form [reward, goal_reward, success_reward]. ENV_REWARD_IDX = 0 SIM_REWARD_IDX = 1 max_position_change = RobotControlParameters.default_max_pos_change_for_solver( control_mode=ControlMode.TCP_ROLL_YAW, tcp_solver_mode=tcp_solver_mode ) env = make_env( parameters=dict( n_random_initial_steps=0, simulation_params=dict( penalty=dict(table_collision=TABLE_COLLISION_PENALTY), ), robot_control_params=dict( tcp_solver_mode=tcp_solver_mode, max_position_change=max_position_change, ), ), constants=dict(use_goal_distance_reward=False), starting_seed=0, ).env env.reset() # check condition at start expect_initial_penalty = env.unwrapped.mujoco_simulation.get_gripper_table_contact() if expect_initial_penalty: assert ( env.get_simulation_info_reward_with_done()[SIM_REWARD_IDX] == TABLE_COLLISION_PENALTY ) else: assert env.get_simulation_info_reward_with_done()[SIM_REWARD_IDX] == 0.0 action = np.zeros_like(env.action_space.sample()) action[2] = z_action for _ in range(20): _, reward, _, _ = env.step(action) expect_penalty = ( z_action < 0 ) # expect penalty if the action is pushing the gripper towards the table if expect_penalty: # assert env.reward() == TABLE_COLLISION_PENALTY assert ( reward[ENV_REWARD_IDX] == -TABLE_COLLISION_PENALTY ) # goal reward should be negative else: # assert env.reward() == 0.0 assert reward[ENV_REWARD_IDX] >= 0.0 # goal reward should be non-negative def test_off_table_penalty(): from robogym.envs.rearrange.blocks import make_env env = make_env() env.reset() _, rew, _, info = env.step(env.action_space.sample()) assert np.equal(info.get("objects_off_table")[0], False) assert rew[0] >= 0.0 with patch( "robogym.envs.rearrange.simulation.base.RearrangeSimulationInterface.check_objects_off_table" ) as mock_sim: mock_sim.return_value = np.array([True]) env = make_env() _, rew, done, info = env.unwrapped.step(env.action_space.sample()) assert np.equal(info.get("objects_off_table")[0], True) assert rew[0] == -1.0 assert done def test_safety_stop_penalty(): from robogym.envs.rearrange.blocks import make_env SAFETY_STOP_PENALTY = 5.0 env = make_env( parameters=dict( simulation_params=dict(penalty=dict(safety_stop=SAFETY_STOP_PENALTY),), ), constants=dict(use_goal_distance_reward=False), starting_seed=0, ).env env.reset() action = np.zeros_like(env.action_space.sample()) action[2] = -1 # drive the arm into the table for _ in range(20): obs, reward, _, _ = env.step(action) assert obs["safety_stop"] assert reward[0] == -SAFETY_STOP_PENALTY def test_override_state(): from robogym.envs.rearrange.blocks import make_env env = make_env() env.reset() object_pos = env.mujoco_simulation.get_object_pos() object_rot = env.mujoco_simulation.get_object_rot() new_object_pos = object_pos + np.ones(3) new_object_rot = normalize_angles(object_rot + np.ones(3) * 0.1) with env.mujoco_simulation.override_object_state(new_object_pos, new_object_rot): assert np.array_equal(env.mujoco_simulation.get_object_pos(), new_object_pos) assert np.allclose( env.mujoco_simulation.get_object_rot(), new_object_rot, atol=1e-3 ) assert np.array_equal(env.mujoco_simulation.get_object_pos(), object_pos) assert np.allclose(env.mujoco_simulation.get_object_rot(), object_rot, atol=1e-3) def test_teleport_to_goal(): from robogym.envs.rearrange.blocks import make_env env = make_env() env.reset() for _ in range(15): env.step(env.action_space.sample()) def test_stale_sim_error(): env = make_blocks_env() env.reset() sim = env.sim _ = sim.model raised = False env.reset() try: _ = sim.model except StaleMjSimError: raised = True assert raised def test_robot_recreation_on_reset(): env = make_blocks_env() initial_robot = env.robot env.reset() assert env.robot == env.mujoco_simulation.robot env.reset() assert ( env.robot == env.mujoco_simulation.robot ), "Robot instance not refreshed on sim.reset" assert ( initial_robot != env.robot ), "Expected a new robot to be created on sim reset."
16,773
32.084813
101
py
robogym
robogym-master/robogym/envs/rearrange/tests/test_object_in_placement_area.py
import numpy as np import pytest from robogym.envs.rearrange.blocks import make_env KEYS_TO_MASK = [ "goal_obj_pos", "goal_obj_rot", "rel_goal_obj_pos", "rel_goal_obj_rot", "obj_pos", "obj_rot", "obj_rel_pos", "obj_vel_pos", "obj_vel_rot", "obj_gripper_contact", "obj_bbox_size", "obj_colors", ] @pytest.mark.parametrize( "obj_pos,in_placement_area,margin", [ ([[1.45, 0.68, 0.5]], [True], 0.02), # Center of placement area. ([[1.15, 0.39, 0.5]], [True], 0.02), # top left in boundary ([[1.10, 0.39, 0.5]], [False], 0.02), # top left out of boundary ( [[1.10, 0.39, 0.5]], [True], 0.1, ), # top left close to boundary with a big margin ([[1.75, 0.97, 0.5]], [True], 0.02), # bottom right in boundary ([[1.80, 1.0, 0.5]], [False], 0.02), # bottom right out of boundary ([[1.15, 0.97, 0.5]], [True], 0.02), # top right in boundary ([[1.10, 1.0, 0.5]], [False], 0.02), # top right out of boundary ([[1.75, 0.39, 0.5]], [True], 0.02), # bottom left in boundary ([[1.75, 0.36, 0.5]], [False], 0.02), # bottom left out of boundary ( [[1.75, 0.36, 0.5]], [True], 0.1, ), # bottom close to boundary with a big margin # Some combinations ([[1.15, 0.39, 0.5], [1.10, 0.39, 0.5]], [True, False], 0.02), ([[1.80, 1.0, 0.5], [1.15, 0.97, 0.5]], [False, True], 0.02), ( [[1.80, 1.0, 0.5], [1.10, 1.0, 0.5], [1.75, 0.39, 0.5]], [False, False, True], 0.02, ), ], ) def test_single_obj_in_placement_area(obj_pos, in_placement_area, margin): in_placement_area = np.array(in_placement_area) n_obj = len(obj_pos) max_obj = 12 env = make_env( parameters={ "simulation_params": {"num_objects": n_obj, "max_num_objects": max_obj} }, ) env.reset() sim = env.unwrapped.mujoco_simulation assert np.array_equal( in_placement_area, sim.check_objects_in_placement_area(np.array(obj_pos), margin=margin), ) obj_pos_with_padding = np.array(obj_pos + list(np.zeros((max_obj - n_obj, 3)))) assert obj_pos_with_padding.shape == (max_obj, 3) with_padding = sim.check_objects_in_placement_area( obj_pos_with_padding, margin=margin ) assert len(with_padding) == max_obj assert np.array_equal(in_placement_area, with_padding[:n_obj]) assert np.all(in_placement_area[n_obj:]) no_padding = sim.check_objects_in_placement_area(np.array(obj_pos), margin=margin) assert len(no_padding) == len(obj_pos) assert np.array_equal(in_placement_area, no_padding) @pytest.mark.parametrize("should_mask", [True, False]) @pytest.mark.parametrize( "obj_pos,in_placement_area", [ ([[1.45, 0.68, 0.5]], [True]), ([[1.15, 0.39, 0.5], [1.10, 0.39, 0.5]], [True, False]), ([[1.80, 1.0, 0.5], [1.15, 0.97, 0.5]], [False, True]), ([[1.80, 1.0, 0.5], [1.10, 1.0, 0.5], [1.75, 0.39, 0.5]], [False, False, True]), ], ) def test_mask_observation(obj_pos, in_placement_area, should_mask): n_obj = len(obj_pos) obj_pos = np.array(obj_pos) in_placement_area_padded = np.array(in_placement_area + [True] * (3 - n_obj)) expected_mask = in_placement_area_padded.astype(np.float).reshape(-1, 1) env = make_env( parameters={"simulation_params": {"num_objects": n_obj, "max_num_objects": 3}}, constants={"mask_obs_outside_placement_area": should_mask}, ) env.reset() env.unwrapped.mujoco_simulation.set_object_pos(np.array(obj_pos)) env.unwrapped.mujoco_simulation.forward() env.unwrapped._goal["goal_objects_in_placement_area"] = in_placement_area_padded obs = env.observe() sim = env.unwrapped.mujoco_simulation assert in_placement_area == list(sim.check_objects_in_placement_area(obj_pos)) for k in KEYS_TO_MASK: masked_k = f"masked_{k}" if not should_mask: assert masked_k not in obs else: assert np.array_equal(obs["placement_mask"], expected_mask) assert np.array_equal(obs["goal_placement_mask"], expected_mask) for i in range(n_obj): if in_placement_area[i]: assert np.all(obs[masked_k][i] == obs[k][i]) else: # if outside the placement area, mask it. assert np.all(obs[masked_k][i] == np.zeros_like(obs[k][i])) @pytest.mark.parametrize( "obj_pos,in_placement_area", [ ( [ [1.45, 0.68, 0.5], # in the middle of the placement area [1.45, 0.395, 0.5], # on the left edge [1.45, 0.34, 0.5], # within the margin [1.45, 0.25, 0.5], ], # outside the margin [True, True, None, False], ) ], ) def test_soft_mask_observation(obj_pos, in_placement_area): env = make_env(parameters={"simulation_params": {"num_objects": len(obj_pos)}}) env.reset() sim = env.unwrapped.mujoco_simulation stochastic_mask = set() for _ in range(20): mask = sim.check_objects_in_placement_area( np.array(obj_pos), soft=True, margin=0.1 ) for i in range(len(in_placement_area)): if in_placement_area[i] is None: stochastic_mask.add(mask[i]) else: assert in_placement_area[i] == mask[i] assert len(stochastic_mask) == 2
5,613
34.308176
88
py
robogym
robogym-master/robogym/envs/rearrange/tests/test_rearrange_robots.py
from typing import Optional import numpy as np import pytest from gym.envs.robotics import utils from robogym.envs.rearrange.simulation.blocks import ( BlockRearrangeSim, BlockRearrangeSimParameters, ) from robogym.robot.control.tcp.solver import PrincipalAxis from robogym.robot.robot_interface import ( ControlMode, RobotControlParameters, TcpSolverMode, ) from robogym.robot.ur16e.arm_interface import TABLETOP_EXPERIMENT_INITIAL_POS, Arm from robogym.robot.ur16e.mujoco.free_dof_tcp_arm import DOF_DIM_SPEED_SCALE from robogym.robot.utils import reach_helper from robogym.robot.utils.reach_helper import ReachHelperDebugRecorder, reach_wrist_angle from robogym.robot.utils.tests.test_reach_helper import assert_speed_is_ok def _build_robot(control_mode, max_position_change): sim = BlockRearrangeSim.build( n_substeps=1, robot_control_params=RobotControlParameters( control_mode=control_mode, max_position_change=max_position_change, ), simulation_params=BlockRearrangeSimParameters(), ) # reset mocap welds if any. This is actually needed for TCP arms to move, so other tests that did not use # env may benefit from it. utils.reset_mocap_welds(sim.mj_sim) return sim.robot ANGLE_SCALER = np.array( [DOF_DIM_SPEED_SCALE[PrincipalAxis.ROLL], DOF_DIM_SPEED_SCALE[PrincipalAxis.PITCH]] ) @pytest.mark.parametrize( "max_position_change,normalized_control,denormalized_pos,denormalized_angle,denormalized_gripper_ctrl", [ (1.0, np.ones(7), [1.0, 1.0, 1.0], ANGLE_SCALER, [0]), (0.05, np.ones(7), [0.05, 0.05, 0.05], ANGLE_SCALER * 0.05, [0]), (1.0, -np.ones(7), [-1.0, -1.0, -1.0], ANGLE_SCALER * -1, [-0.022365]), (0.05, -np.ones(7), [-0.05, -0.05, -0.05], ANGLE_SCALER * -0.05, [-0.022365]), ], ) def test_tcp_arm_denormalization_ur16( max_position_change, normalized_control, denormalized_pos, denormalized_angle, denormalized_gripper_ctrl, ): """ Test for the composite robot where the first 5 dimensions of the action space come from a TCP controlled arm, (3 entries for position, 2 for angle) and the last dimension comes from a position-controlled gripper. :return: """ robot = _build_robot(ControlMode.TCP_ROLL_YAW.value, max_position_change) # important to make sure gripper starts at a neutral state so actions don't get clipped assert np.array_equal(robot.observe().gripper_qpos(), np.zeros(1)) expected_full_ctrl = np.concatenate( (denormalized_pos, denormalized_angle, denormalized_gripper_ctrl) ) assert np.allclose( robot.denormalize_position_control( position_control=normalized_control, relative_action=True ), expected_full_ctrl, ) @pytest.mark.parametrize( "control_mode,expected_dim", [(ControlMode.TCP_ROLL_YAW, 6), (ControlMode.JOINT, 6)] ) def test_joint_position_observations(control_mode, expected_dim): robot = _build_robot(control_mode, 0.05) assert len(robot.observe().joint_positions()) == expected_dim def test_gripper_observations(): robot = _build_robot(ControlMode.TCP_ROLL_YAW.value, 0.05) obs = robot.observe() assert len(obs.gripper_qpos()) == 1 assert len(obs.gripper_vel()) == 1 assert len(obs.tcp_xyz()) == 3 assert len(obs.tcp_vel()) == 3 def test_action_space_dims(): robot = _build_robot(ControlMode.TCP_ROLL_YAW.value, 0.05) assert len(robot.zero_control()) == 6 def test_joint_positions_to_control(): robot = _build_robot(ControlMode.JOINT.value, 0.05) assert np.array_equal(robot.joint_positions_to_control(np.zeros(12)), np.zeros(7)) @pytest.mark.parametrize( "control_mode,tcp_solver_mode,expected_joint_count", [ (ControlMode.JOINT, TcpSolverMode.MOCAP, 7), (ControlMode.TCP_WRIST, TcpSolverMode.MOCAP, 1), (ControlMode.TCP_ROLL_YAW, TcpSolverMode.MOCAP, 1), (ControlMode.TCP_WRIST, TcpSolverMode.MOCAP_IK, 7), (ControlMode.TCP_ROLL_YAW, TcpSolverMode.MOCAP_IK, 7), ], ) def test_arm_actuators(control_mode, tcp_solver_mode, expected_joint_count): from robogym.envs.rearrange.blocks_reach import make_env env = make_env( parameters=dict( robot_control_params=dict( control_mode=control_mode, tcp_solver_mode=tcp_solver_mode, ) ) ) assert len(env.sim.model.actuator_names) == expected_joint_count @pytest.mark.parametrize( "control_mode,tcp_solver_mode", [ (ControlMode.TCP_ROLL_YAW, TcpSolverMode.MOCAP), (ControlMode.TCP_WRIST, TcpSolverMode.MOCAP), (ControlMode.TCP_ROLL_YAW, TcpSolverMode.MOCAP_IK), (ControlMode.TCP_WRIST, TcpSolverMode.MOCAP_IK), ], ) def test_free_wrist_reach(control_mode, tcp_solver_mode): from robogym.envs.rearrange.blocks import make_env max_position_change = RobotControlParameters.default_max_pos_change_for_solver( control_mode=control_mode, tcp_solver_mode=tcp_solver_mode, arm_reset_controller_error=True, ) env = make_env( starting_seed=1, parameters=dict( robot_control_params=dict( control_mode=control_mode, tcp_solver_mode=tcp_solver_mode, max_position_change=max_position_change, arm_reset_controller_error=True, ), n_random_initial_steps=10, ), ) arm = env.robot.robots[0] j6_lower_bound = arm.actuator_ctrl_range_lower_bound()[5] j6_upper_bound = arm.actuator_ctrl_range_upper_bound()[5] reach_buffer = np.deg2rad(5) def _reset_and_get_arm(env): env.reset() arm = env.robot.robots[0] arm.autostep = True return arm for target_angle in np.linspace( j6_lower_bound + reach_buffer, j6_upper_bound - reach_buffer, 12 ): arm = _reset_and_get_arm(env) assert reach_wrist_angle( robot=arm, wrist_angle=target_angle, max_steps=200, Kp=2, ), ( f"Failed reach. desired pos: {np.rad2deg(target_angle)} " f"achieved pos: {np.rad2deg(arm.observe().joint_positions()[-1]):.2f}" ) for unreachable_angle in [ j6_lower_bound - reach_buffer, j6_upper_bound + reach_buffer, ]: arm = _reset_and_get_arm(env) assert not reach_wrist_angle( robot=arm, wrist_angle=unreachable_angle ), f"Reached unreachable angle: {np.rad2deg(unreachable_angle)}" @pytest.mark.parametrize( "control_mode,tcp_solver_mode,max_position_change, expected_controls", [ ( ControlMode.TCP_WRIST, TcpSolverMode.MOCAP, 0.05, [0.05, 0.05, 0.05, np.deg2rad(30)], ), ( ControlMode.TCP_WRIST, TcpSolverMode.MOCAP_IK, 0.27, [0.27, 0.27, 0.27, np.deg2rad(162)], ), ( ControlMode.TCP_ROLL_YAW, TcpSolverMode.MOCAP, 0.05, [0.05, 0.05, 0.05, np.deg2rad(10), np.deg2rad(30)], ), ( ControlMode.TCP_ROLL_YAW, TcpSolverMode.MOCAP_IK, 0.27, [0.27, 0.27, 0.27, np.deg2rad(54), np.deg2rad(162)], ), ], ) def test_tcp_action_scaling( control_mode, tcp_solver_mode, max_position_change, expected_controls ): from robogym.envs.rearrange.blocks import make_env env = make_env( starting_seed=0, parameters=dict( robot_control_params=dict( control_mode=control_mode, tcp_solver_mode=tcp_solver_mode, max_position_change=max_position_change, ), ), ) env.reset() arm = env.robot.robots[0] control = np.ones_like(arm.zero_control()) denormalized_ctrl = arm.denormalize_position_control(control, relative_action=True) assert np.allclose(denormalized_ctrl, expected_controls) @pytest.mark.parametrize( "tcp_solver_mode,arm_joint_calibration_path,off_axis_threshold", [ (TcpSolverMode.MOCAP_IK, "cascaded_pi", 3), (TcpSolverMode.MOCAP, "cascaded_pi", 3), ], ) def test_free_wrist_quat_constraint( tcp_solver_mode: TcpSolverMode, arm_joint_calibration_path: str, off_axis_threshold: float, ): """ FreeWristTCP controlled env is only allowed to vary TCP quat about the y axis this test checks for max deviation in the other axes when the arm is driven to an extreme of the arm's reach so that mocap will deviate from the actual gripper pos and may cause angle deviations if we have an alignment bug. :return: """ from robogym.envs.rearrange.blocks import make_env from robogym.utils import rotation max_position_change = RobotControlParameters.default_max_pos_change_for_solver( control_mode=ControlMode.TCP_WRIST, tcp_solver_mode=tcp_solver_mode, ) env = make_env( starting_seed=3, parameters=dict( robot_control_params=dict( control_mode=ControlMode.TCP_WRIST, tcp_solver_mode=tcp_solver_mode, max_position_change=max_position_change, arm_joint_calibration_path=arm_joint_calibration_path, ), ), ) env.reset() max_off_axis_deviation_deg = 0 for _ in range(50): env.step([6, 10, 5, 5, 5]) angle = np.rad2deg( rotation.quat2euler( env.mujoco_simulation.mj_sim.data.get_body_xquat("robot0:gripper_base") ) ) x_rot = min(angle[0], 90 - angle[0]) z_rot = min(angle[2], 90 - angle[2]) max_off_axis_deviation_deg = np.max([max_off_axis_deviation_deg, x_rot, z_rot]) assert max_off_axis_deviation_deg < off_axis_threshold @pytest.mark.parametrize( "tcp_solver_mode,control_mode,off_joint_threshold_deg", [ (TcpSolverMode.MOCAP_IK, ControlMode.TCP_WRIST, 0.7), (TcpSolverMode.MOCAP, ControlMode.TCP_WRIST, 0.7), (TcpSolverMode.MOCAP_IK, ControlMode.TCP_ROLL_YAW, 0.7), (TcpSolverMode.MOCAP, ControlMode.TCP_ROLL_YAW, 0.7), ], ) def test_wrist_isolation( tcp_solver_mode: TcpSolverMode, control_mode: ControlMode, off_joint_threshold_deg: float, ): """ FreeWristTCP controlled env is only allowed to vary TCP quat about the y axis this test checks for max deviation in the other joints than J6 when only wrist rotation action is applied. :return: """ from robogym.envs.rearrange.blocks import make_env max_position_change = RobotControlParameters.default_max_pos_change_for_solver( control_mode=control_mode, tcp_solver_mode=tcp_solver_mode, ) env = make_env( starting_seed=3, parameters=dict( n_random_initial_steps=0, robot_control_params=dict( control_mode=control_mode, tcp_solver_mode=tcp_solver_mode, max_position_change=max_position_change, ), ), ) env.reset() initial_joint_angles = env.observe()["robot_joint_pos"] wrist_rot_action = np.ones(env.action_space.shape[0], dtype=np.int) * 5 wrist_joint_index = -2 # move wrist CW wrist_rot_action[wrist_joint_index] = 7 for _ in range(100): env.step(wrist_rot_action) final_joint_angles = env.observe()["robot_joint_pos"] assert np.allclose( initial_joint_angles[:5], final_joint_angles[:5], atol=np.deg2rad(off_joint_threshold_deg), ) # move wrist CCW env.reset() wrist_rot_action[wrist_joint_index] = 3 for _ in range(100): env.step(wrist_rot_action) final_joint_angles = env.observe()["robot_joint_pos"] assert np.allclose( initial_joint_angles[:5], final_joint_angles[:5], atol=np.deg2rad(off_joint_threshold_deg), ) @pytest.mark.parametrize( "control_mode, max_position_change, speed_limit_threshold_mult", [ ( ControlMode.JOINT.value, None, 10 / 30, ), # mult=10/30 means '10 degrees when speed is 30 deg/sc' (ControlMode.TCP_ROLL_YAW.value, 0.025, None), ], ) def test_reach_helper( control_mode, max_position_change: float, speed_limit_threshold_mult: Optional[float], ) -> None: """Test that a given robot can reach certain positions, and fail to reach some under certain speed requirements. :param control_mode: Robot control mode. :param max_position_change: Max position change as expected by UR arms. :param speed_limit_threshold_mult: If not None, the test will check that the actual speeds achieved during the reach efforts do not exceed the expected speed plus a little margin, as defined by this multiplier. If None, the speed check is not performed (TCP arm does not currently properly report speeds, since it doesn't have the proper actuators to perform dynamics, so it's a case where we specify None). """ # these positions are 4 corners recorded empirically. All of them should be safely reachable in the order # specified, but might not be if the order changes positions4 = [ TABLETOP_EXPERIMENT_INITIAL_POS, np.deg2rad(np.array([165, -55, 90, -110, -225, 100])), np.deg2rad(np.array([120, -20, 100, -135, -245, 115])), np.deg2rad(np.array([130, -15, 75, -110, -240, 125])), ] # this position is equal to the second position in the previous array, with a wrist rotation far away from # the initial position far_wrist_pos = np.deg2rad(np.array([165, -55, 90, -110, -225, 300])) composite_robot = _build_robot( control_mode=control_mode, max_position_change=max_position_change ) arm = composite_robot.robots[0] arm.autostep = True assert isinstance(arm, Arm) # - - - - - - - - - - - - - - - - # try to reach several reachable positions # - - - - - - - - - - - - - - - - shared_speed = np.deg2rad(30) for idx, pos in enumerate(positions4): debug_recorder = ReachHelperDebugRecorder(robot=arm) reach_ret = reach_helper.reach_position( arm, pos, speed_units_per_sec=shared_speed, timeout=10, minimum_time_to_move=6, debug_recorder=debug_recorder, ) assert reach_ret.reached if speed_limit_threshold_mult is not None: assert_speed_is_ok( debug_recorder, shared_speed, shared_speed * speed_limit_threshold_mult ) # - - - - - - - - - - - - - - - - # reach initial position again # - - - - - - - - - - - - - - - - debug_recorder = ReachHelperDebugRecorder(robot=arm) reach_ret = reach_helper.reach_position( arm, TABLETOP_EXPERIMENT_INITIAL_POS, speed_units_per_sec=shared_speed, timeout=10, minimum_time_to_move=6, debug_recorder=debug_recorder, ) assert reach_ret.reached if speed_limit_threshold_mult is not None: assert_speed_is_ok( debug_recorder, shared_speed, shared_speed * speed_limit_threshold_mult ) # - - - - - - - - - - - - - - - - # fail due to timeout # - - - - - - - - - - - - - - - - try: debug_recorder = ReachHelperDebugRecorder(robot=arm) reach_ret = reach_helper.reach_position( arm, far_wrist_pos, speed_units_per_sec=shared_speed, timeout=10, minimum_time_to_move=6, debug_recorder=debug_recorder, ) assert reach_ret.reached except RuntimeError as re: assert str(re).startswith( "Some controls won't reach their target before the timeout" ) # - - - - - - - - - - - - - - - - # attempt the same motion, with a faster speed for the wrist # - - - - - - - - - - - - - - - - debug_recorder = ReachHelperDebugRecorder(robot=arm) slow = np.deg2rad(30) fast = np.deg2rad(60) fast_wrist_speed = np.asarray([*np.repeat(slow, 5), fast]) reach_ret = reach_helper.reach_position( arm, far_wrist_pos, speed_units_per_sec=fast_wrist_speed, timeout=10, minimum_time_to_move=6, debug_recorder=debug_recorder, ) assert reach_ret.reached if speed_limit_threshold_mult is not None: speed_limit_threshold_with_wrist = fast_wrist_speed * speed_limit_threshold_mult assert_speed_is_ok( debug_recorder, fast_wrist_speed, speed_limit_threshold_with_wrist )
16,752
32.844444
117
py
robogym
robogym-master/robogym/envs/rearrange/tests/test_robot_polymorphism.py
import pytest from robogym.envs.rearrange.blocks import make_env from robogym.robot.composite.ur_gripper_arm import ( MujocoIdealURGripperCompositeRobot as IdealDynamicsCls, ) from robogym.robot.composite.ur_gripper_arm import ( MujocoURTcpJointGripperCompositeRobot as JointDynamicsCls, ) from robogym.robot.robot_interface import ( ControlMode, RobotControlParameters, TcpSolverMode, ) from robogym.robot.ur16e.mujoco.free_dof_tcp_arm import ( FreeRollYawTcpArm, FreeWristTcpArm, ) def test_rearrange_defaults(): from robogym.robot.composite.ur_gripper_arm import ( MujocoURTcpJointGripperCompositeRobot, ) env = make_env() assert isinstance(env.robot, MujocoURTcpJointGripperCompositeRobot) assert ( env.parameters.robot_control_params.max_position_change == RobotControlParameters.default_max_pos_change_for_solver( control_mode=ControlMode.TCP_ROLL_YAW, tcp_solver_mode=TcpSolverMode.MOCAP_IK, ) ) assert env.parameters.robot_control_params.arm_reset_controller_error assert env.parameters.robot_control_params.control_mode is ControlMode.TCP_ROLL_YAW assert env.parameters.robot_control_params.tcp_solver_mode is TcpSolverMode.MOCAP_IK assert env.action_space.shape == (6,) @pytest.mark.parametrize( "control_mode, expected_action_dims, tcp_solver_mode, expected_main_robot, expected_helper_arm", [ ( ControlMode.TCP_WRIST, 5, TcpSolverMode.MOCAP, IdealDynamicsCls, FreeWristTcpArm, ), ( ControlMode.TCP_WRIST, 5, TcpSolverMode.MOCAP_IK, JointDynamicsCls, FreeWristTcpArm, ), ( ControlMode.TCP_ROLL_YAW, 6, TcpSolverMode.MOCAP, IdealDynamicsCls, FreeRollYawTcpArm, ), ( ControlMode.TCP_ROLL_YAW, 6, TcpSolverMode.MOCAP_IK, JointDynamicsCls, FreeRollYawTcpArm, ), ], ) def test_rearrange_with_ur_tcp( control_mode, expected_action_dims, tcp_solver_mode, expected_main_robot, expected_helper_arm, ): env = make_env( parameters=dict( robot_control_params=dict( control_mode=control_mode, tcp_solver_mode=tcp_solver_mode, max_position_change=0.1, ) ) ) assert isinstance(env.robot, expected_main_robot) assert isinstance(env.robot.robots[0].controller_arm, expected_helper_arm) assert env.robot.robots[0].max_position_change == 0.1 assert env.robot.robots[1].max_position_change is None assert env.action_space.shape == (expected_action_dims,) assert env.robot.autostep is False, "Robot should not be in autostep mode" def test_rearrange_sim_defaults(): env = make_env( parameters=dict( robot_control_params=dict( control_mode=ControlMode.TCP_WRIST, tcp_solver_mode=TcpSolverMode.MOCAP, ), ) ) assert env.robot.autostep is False arm_robot = env.robot.robots[0] assert ( arm_robot.simulation == arm_robot.controller_arm.simulation ), "Simulation should be shared" assert ( arm_robot.controller_arm.autostep is False ), "Controller arm is not allowed to autostep" def test_rearrange_with_ur_joint(): from robogym.robot.composite.ur_gripper_arm import ( MujocoURJointGripperCompositeRobot, ) env = make_env( parameters=dict( robot_control_params=dict( control_mode=ControlMode.JOINT, max_position_change=2.4, ) ) ) assert isinstance(env.robot, MujocoURJointGripperCompositeRobot) assert env.robot.robots[0].max_position_change == 2.4 assert env.robot.robots[1].max_position_change is None assert env.parameters.robot_control_params.control_mode == ControlMode.JOINT assert env.action_space.shape == (7,)
4,098
29.819549
100
py
robogym
robogym-master/robogym/envs/rearrange/simulation/base.py
from collections import namedtuple from contextlib import contextmanager from typing import Any, Dict, Generic, List, Optional, Tuple, Type, TypeVar, Union import attr import numpy as np from gym.envs.robotics import rotations from mujoco_py import const from robogym.envs.rearrange.common.utils import ( PlacementArea, geom_ids_of_body, get_all_vertices, mesh_vert_range_of_geom, ) from robogym.mujoco.mujoco_xml import MujocoXML from robogym.mujoco.simulation_interface import ( SimulationInterface, SimulationParameters, ) from robogym.randomization.env import build_randomizable_param from robogym.robot.composite.ur_gripper_arm import build_composite_robot from robogym.robot.robot_interface import RobotControlParameters from robogym.robot.ur16e.mujoco.simulation.base import ArmSimulationInterface from robogym.utils import rotation class Meta(type): @classmethod def __prepare__(mcs, name, bases, **kwds): """ A metaclass to force slots to be present in all subclasses. This is necessary to guarantee update always work correctly for all subclasses. See https://docs.python.org/2.5/ref/slots.html for details about __slots__ """ super_prepared = super().__prepare__(mcs, name, bases, **kwds) super_prepared["__slots__"] = () return super_prepared @attr.s(auto_attribs=True) class ObjectGroupConfig: # Total number of objects with this config. count: int = 1 object_ids: List[int] = [0] # Scale for object. scale: float = 1.0 # Material args for each object. They are defined as mapping from tag name # to property values. material_args: Dict[str, Dict[str, Any]] = {} # color in RGBA color: np.ndarray = attr.ib( default=np.array([1.0, 1.0, 1.0, 0.2]), converter=np.array ) # type: ignore @color.validator def validate_color(self, _, value): assert isinstance(value, np.ndarray) and value.shape == (4,) @attr.s(auto_attribs=True) class RearrangeSimParameters(SimulationParameters): num_objects: int = build_randomizable_param(1, low=1, high=32) # The object size in half-size (as per Mujoco convention). object_size: float = build_randomizable_param(0.0254, low=0.01, high=0.1) # If not set, we use num_objects as max_num_objects. max_num_objects: Optional[int] = None # Max percent of table area to use. used_table_portion: float = build_randomizable_param(1.0, low=0.4, high=1.0) # Max number of times for placement retry. To place multiple objects, placement algorithm # place each object one by one. Whenever placing a new object is failed the placement # algorithm retry `max_placement_retry_per_object` times and if it still fails it start over # from the first object. The placement can start over for `max_placement_retry` times. max_placement_retry: int = 100 max_placement_retry_per_object: int = 20 # The `goal_distance_ratio` is used to decrease distance from object position to goal position # after uniformly sampling the goal. The decreased distance will be `goal_distance_ratio * # original_distance`. The distance cannot be decreased below `goal_distance_min`. goal_distance_ratio: float = build_randomizable_param(1.0, low=0.0, high=1.0) goal_distance_min: float = 0.06 # The offset put on the relative positional distance between target and object. This can be # used to make the success threshold for object position different less strict. By adding # negative offset to relative positional distance, we can enjoy the effect of increasing the # success threshold by -goal_pos_offset. goal_pos_offset: float = build_randomizable_param(0.0, low=-0.04, high=0.0) # The weight put on the relative rotational distance between target and object. This can # be used to smoothly interpolate between not caring about rotational goals (when value = 0) # to fully caring about them (when value = 1). goal_rot_weight: float = build_randomizable_param(1.0, low=0.0, high=1.0) # Height of reach target object above the table, curriculum from high to low # helps policy learn to handle safety plane in z. target_height: float = build_randomizable_param(0.1, low=0.0, high=0.2) # Collection of penalties to impose on sim # Penalties are defined as positive numbers and are subtracted from # the reward. penalty: dict = dict( table_collision=0.0, objects_off_table=1.0, wrist_collision=0.0 ) # for camera view randomization (fov, pos and quat) camera_fovy_radius: float = build_randomizable_param(0.0, low=0, high=0.1) camera_pos_radius: float = build_randomizable_param(0.0, low=0, high=0.01) # about 5 degrees camera_quat_radius: float = build_randomizable_param(0.0, low=0, high=0.09) # Whether we should cast shadows. This is disabled by default because it slows down rendering # signficantly when using envs with custom meshes. We enable it for sim2real experiments. cast_shadows: bool = False # Lighting randomizations. light_pos_range: float = build_randomizable_param(0.0, low=0.0, high=0.8) light_ambient_intensity: float = build_randomizable_param(0.1, low=0.1, high=0.7) light_diffuse_intensity: float = build_randomizable_param(0.4, low=0.1, high=0.7) # Objects assigned with the same group id should be visually same (same shape, size, color). # We always assume group id starting from 0 and new ones are assigned incrementally. object_groups: List[ObjectGroupConfig] = None # type: ignore def __attrs_post_init__(self): # Assign default value to object_groups if empty. Hard to use @object_groups.default here # as it depends on self.num_objects and the order is messed up in different subclasses. if self.object_groups is None: self.object_groups = [ ObjectGroupConfig(count=1, object_ids=[obj_id]) for obj_id in range(self.num_objects) ] PType = TypeVar("PType", bound=RearrangeSimParameters) class RearrangeSimulationInterface( ArmSimulationInterface, Generic[PType], metaclass=Meta ): """ Creates a SimulationInterface with a rearrange-compatible robot-gripper and a table setup. Subclass this and implement make_objects_xml() to create other tasks. """ # For rearrange task, we recreate simulation during environment reset, in order to avoid # environment component still referring to stale simulation instance, an update() method # is added to allow updating simulation in place. For update() to work properly # (called when underlying MjModel / XML is changed), the instance variables to be updated # must be registered somewhere (for simplicity, all instance variables are assumed to be # simulation dependent, and thus require updating). We use __slots__ to register the instance # variables. So you will need to add all simulation instance variables to slots, # or you'll get an error. __slots__ = ["robot", "simulation_params", "control_param", "initial_values"] def __init__( self, sim, robot_control_params: RobotControlParameters, simulation_params: PType, ): super().__init__(sim, robot_control_params=robot_control_params) self.simulation_params = simulation_params self.robot = build_composite_robot( robot_control_params=robot_control_params, simulation=self ) for i in range(self.num_objects): self.register_joint_group(f"object{i}", prefix=[f"object{i}:"]) # Verify the qpos and qvel arrays are the proper lengths (there was previously a bug # which caused this to not be the case when > 10 objects existed). assert len(self.get_qpos(f"object{i}")) == 7 assert len(self.get_qvel(f"object{i}")) == 6 self.initial_values = dict() self.initial_values["camera_fovy"] = self.mj_sim.model.cam_fovy.copy() self.initial_values["camera_pos"] = self.mj_sim.model.cam_pos.copy() self.initial_values["camera_quat"] = self.mj_sim.model.cam_quat.copy() self.set_object_colors() self.mj_sim.model.light_castshadow[:] = ( 1.0 if simulation_params.cast_shadows else 0.0 ) @property def num_objects(self): return self.simulation_params.num_objects @property def object_size(self): return self.simulation_params.object_size @property def goal_distance_ratio(self): return self.simulation_params.goal_distance_ratio @property def goal_distance_min(self): return self.simulation_params.goal_distance_min @property def goal_pos_offset(self): return self.simulation_params.goal_pos_offset @property def goal_rot_weight(self): return self.simulation_params.goal_rot_weight @property def max_num_objects(self): return ( self.simulation_params.max_num_objects or self.simulation_params.num_objects ) @property def used_table_portion(self): return self.simulation_params.used_table_portion @property def max_placement_retry(self): return self.simulation_params.max_placement_retry @property def max_placement_retry_per_object(self): return self.simulation_params.max_placement_retry_per_object @property def object_groups(self): return self.simulation_params.object_groups @property def num_groups(self): return len(self.object_groups) @classmethod def _sanity_check_object_groups(cls, sim_params: PType): # sanity check assert sim_params.object_groups assert ( sum([g.count for g in sim_params.object_groups]) == sim_params.num_objects ) assert [i for g in sim_params.object_groups for i in g.object_ids] == list( range(sim_params.num_objects) ) @classmethod def build( cls, robot_control_params: RobotControlParameters, n_substeps: int = 20, mujoco_timestep: float = 0.002, simulation_params: Optional[ PType ] = None, # optional is required to keep parent signature compatibility ): assert ( simulation_params is not None ) # we do not actually support calling without valid params xml = cls.make_xml(simulation_params, mujoco_timestep) xml = cls.make_robot_xml(xml, robot_control_params) return cls( xml.build(nsubsteps=n_substeps), robot_control_params=robot_control_params, simulation_params=simulation_params, ) @classmethod def make_xml(cls, simulation_params: PType, mujoco_timestep: float): cls._sanity_check_object_groups(simulation_params) xml = cls.make_world_xml( simulation_params=simulation_params, contact_params={}, mujoco_timestep=mujoco_timestep, ) object_and_target_xmls = cls.make_objects_xml(xml, simulation_params) object_group_ids = [ i for i, obj_group in enumerate(simulation_params.object_groups) for _ in range(obj_group.count) ] for group_id, (obj_xml, target_xml) in zip( object_group_ids, object_and_target_xmls ): obj_xml.set_objects_attrs( simulation_params.object_groups[group_id].material_args ) xml.append(obj_xml) xml.append(target_xml) return xml @classmethod def make_world_xml(cls, *, mujoco_timestep: float, **kwargs): return super().make_world_xml( contact_params=dict( njmax=2000, nconmax=500, nuserdata=2000, nuser_actuator=16 ), mujoco_timestep=mujoco_timestep, ) @classmethod def make_objects_xml( cls, xml, simulation_params: PType ) -> List[Tuple[MujocoXML, MujocoXML]]: """ Return list of (object xml, target xml) tuples. """ return [] def update(self, other: "RearrangeSimulationInterface"): """ Update simulation state from other simulation instance. This is implemented by recursive set slot attributes along the ancestor chain. """ self.mj_sim.set_stale() # Mark current MjSim instance as stale. return self._update(other, self.__class__) def _update(self, other, current_class: Type[SimulationInterface]): """ Helper function to recursively set slots. """ for slot in current_class.__slots__: setattr(self, slot, getattr(other, slot)) if current_class != SimulationInterface: parent_class = current_class.__bases__[0] assert issubclass(parent_class, SimulationInterface) self._update(other, parent_class) @contextmanager def hide_target(self, hide_robot=False): """ A context manager in scope of which all target objects are hidden. """ return self._hide_geoms( hide_targets=True, hide_objects=False, hide_robot=hide_robot ) @contextmanager def hide_objects(self, hide_robot=False): """ A context manager in scope of which all objects and target objects are hidden. """ return self._hide_geoms( hide_targets=True, hide_objects=True, hide_robot=hide_robot ) def _hide_geoms(self, hide_targets=False, hide_objects=False, hide_robot=False): sim = self.mj_sim geom_ids_to_hide = [] # Hide sites. site_rgba = sim.model.site_rgba.copy() sim.model.site_rgba[:] = np.zeros_like(site_rgba) if hide_targets: # Hide targets target_ids = [ target_id for i in range(self.num_objects) for target_id in geom_ids_of_body(sim, f"target:object{i}") ] assert len(target_ids) > 0 geom_ids_to_hide += target_ids if hide_objects: # Hide targets object_ids = [ target_id for i in range(self.num_objects) for target_id in geom_ids_of_body(sim, f"object{i}") ] assert len(object_ids) > 0 geom_ids_to_hide += object_ids if hide_robot: robot_geom_ids = [ sim.model.geom_name2id(name) for name in sim.model.geom_names if name.startswith("robot0:") ] geom_ids_to_hide += robot_geom_ids geom_rgba = sim.model.geom_rgba.copy() sim.model.geom_rgba[geom_ids_to_hide, -1] = 0.0 yield # If sim becomes stale (e.g. because of reset while being yield), we don't have to reset # it to the original state if not sim.is_stale(): # Restore sites and targets sim.model.geom_rgba[:] = geom_rgba sim.model.site_rgba[:] = site_rgba ############################################################## # Methods to get object related observations. def get_object_pos(self, pad=True) -> np.ndarray: """ Get position for all objects. """ return self._get_object_obs(self.mj_sim.data.get_body_xpos, pad=pad) def get_object_rel_pos(self) -> np.ndarray: """ Get position for all objects relative to the gripper position. """ gripper_pos = self.robot.observe().tcp_xyz() # type: ignore return self._get_object_obs( lambda n: self.mj_sim.data.get_body_xpos(n) - gripper_pos ) def get_object_quat(self, pad=True) -> np.ndarray: """ Get rotation in quaternion for all objects. """ return self._get_object_obs( lambda n: rotation.quat_normalize( rotations.mat2quat(self.mj_sim.data.get_body_xmat(n)) ), pad=pad, ) def get_object_rot(self, pad=True) -> np.ndarray: """ Get rotation in euler angles for all objects. """ return self._get_object_obs( lambda n: rotations.normalize_angles( rotations.mat2euler(self.mj_sim.data.get_body_xmat(n)) ), pad=pad, ) def get_object_vel_pos(self): """ Get position velocity for all objects relative to tooltip velocity. """ robot_obs = self.robot.observe() tooltip_vel = robot_obs.tcp_vel() return self._get_object_obs( lambda n: self.mj_sim.data.get_body_xvelp(n) - tooltip_vel ) def get_object_vel_rot(self): """ Get rotation velocity for all objects. """ return self._get_object_obs(lambda n: self.mj_sim.data.get_body_xvelr(n)) def get_target_pos(self, pad=True) -> np.ndarray: """ Get target position for all objects. """ return self._get_target_obs(self.mj_sim.data.get_body_xpos, pad=pad) def get_target_quat(self, pad=True) -> np.ndarray: """ Get target rotation in quaternion for all objects. """ return self._get_target_obs( lambda n: rotation.quat_normalize( rotations.mat2quat(self.mj_sim.data.get_body_xmat(n)) ), pad=pad, ) def get_target_rot(self, pad=True) -> np.ndarray: """ Get target rotation in euler angles for all objects. """ return self._get_target_obs( lambda n: rotations.mat2euler(self.mj_sim.data.get_body_xmat(n)), pad=pad ) def get_object_bounding_box_sizes(self, pad=True) -> np.ndarray: return self._get_object_obs(lambda n: self._get_bounding_box(n)[1], pad=pad) def get_object_vertices(self, subdivide_threshold=None) -> List[np.ndarray]: """ Get vertices for all objects. :param subdivide_threshold: If specified, subdivide mesh according to this threshold. """ return [ get_all_vertices( self.mj_sim, f"object{i}", subdivide_threshold=subdivide_threshold ) for i in range(self.num_objects) ] def get_target_vertices(self, subdivide_threshold=None) -> List[np.ndarray]: """ Get vertices for all objects. :param subdivide_threshold: If specified, subdivide mesh according to this threshold. """ return [ get_all_vertices( self.mj_sim, f"target:object{i}", subdivide_threshold=subdivide_threshold, ) for i in range(self.num_objects) ] def get_object_damping(self) -> np.ndarray: """ Get dumping value for each object """ def _get_object_damping(object_name): joint_name = f"{object_name}:joint" joint_id = self.mj_sim.model.joint_name2id(joint_name) dof_ids = [ idx for idx in range(self.mj_sim.model.nv) if self.mj_sim.model.dof_jntid[idx] == joint_id ] return self.mj_sim.model.dof_damping[dof_ids] return self._get_object_obs(_get_object_damping, pad=False) def get_gripper_geom_ids(self) -> List[int]: """ Get gripper geom ids for the two gripper contacts """ def _get_geom_id(name): return self.mj_sim.model.geom_name2id(name) # Looking for UR gripper l_finger_geom_id = _get_geom_id("robot0:left_contact_v") r_finger_geom_id = _get_geom_id("robot0:right_contact_v") return [l_finger_geom_id, r_finger_geom_id] def get_wrist_cam_collisions(self): """ Get geometries contacted by the wrist camera. Group these geometries into categories of bodies - namely the environment table_collision_plane, the robot itself, or other objects. """ geom_id = self.mj_sim.model.geom_name2id("robot0:wrist_cam_collision_sphere") contacts = {"table_collision_plane": False, "robot": False, "object": False} def _map_contact_to_group(geom: Optional[str]): """ Map the name of a geometry to the type of contact (table_collision_plane, robot, or object). Note that in holdout envs many objects don't have names (represented as None). """ if geom == "table_collision_plane": return geom elif geom is not None and geom.startswith("robot0:"): return "robot" return "object" for i in range(self.mj_sim.data.ncon): c = self.mj_sim.data.contact[i] geoms = [c.geom1, c.geom2] if geom_id in geoms: geoms.remove(geom_id) geom_name = self.mj_sim.model.geom_id2name(geoms[0]) contacts[_map_contact_to_group(geom_name)] = True contacts["any"] = any(contacts.values()) return contacts def get_object_gripper_contact( self, other_geom_ids: Optional[List[int]] = None, dist_cutoff: float = 1.0e-5, pad: bool = True, ) -> np.ndarray: """ Check whether each object has contact with the provided geom ids. :param other_geom_ids: If none, use the left and right gripper by default. :param dist_cutoff: Only when the contact penetration is smaller than this threshold, the contact is counted. This threshold should be small. Note: The distances this is compared to are all negative; the default setting of 1e-5 means we include all contacts (is equivalent to setting this to 0). :param pad: whether pad the results to have the length same as max_num_objects. :return: a numpy array of shape [num objects, len(other_geom_ids)], in which each value is binary, 1 meaning having contact and 0 no contact. """ if other_geom_ids is None: other_geom_ids = self.get_gripper_geom_ids() contact_dict: Dict[int, set] = {geom_id: set() for geom_id in other_geom_ids} # Only mjData.ncon elements are in data.contact at a given time. # The rest is left over from previous iterations and is not used. for i in range(self.mj_sim.data.ncon): c = self.mj_sim.data.contact[i] if c.dist < dist_cutoff: if c.geom1 in other_geom_ids: contact_dict[c.geom1].add(c.geom2) if c.geom2 in other_geom_ids: contact_dict[c.geom2].add(c.geom1) def _get_object_contact(object_name): geom_ids = geom_ids_of_body(self.mj_sim, object_name) return [ float(any(i in contact_dict[other_id] for i in geom_ids)) for other_id in other_geom_ids ] return self._get_object_obs(_get_object_contact, pad=pad) def get_light_positions(self) -> np.ndarray: return self.mj_sim.model.light_pos def get_object_colors(self, pad=True) -> np.ndarray: """Get object colors. This logic works, assuming we only assign a single color to one object. """ return self._get_object_obs( lambda n: self.mj_sim.model.geom_rgba[geom_ids_of_body(self.mj_sim, n)[0]], pad=pad, ) ############################################################## # Methods related to objects state. def set_target_pos(self, target_positions: np.ndarray): assert target_positions.shape == (self.num_objects, 3), ( f"Incorrect target_positions.shape {target_positions.shape}, " f"which should be {(self.num_objects, 3)}." ) for i in range(self.num_objects): target_id = self.mj_sim.model.body_name2id(f"target:object{i}") self.mj_sim.model.body_pos[target_id][:] = target_positions[i] def set_target_quat(self, target_quats: np.ndarray): assert target_quats.shape == (self.num_objects, 4), ( f"Incorrect target_quats.shape {target_quats.shape}, " f"which should be {(self.num_objects, 4)}." ) target_quats = rotation.quat_normalize(target_quats) for i in range(self.num_objects): target_id = self.mj_sim.model.body_name2id(f"target:object{i}") self.mj_sim.model.body_quat[target_id][:] = target_quats[i] def set_target_rot(self, target_rots: np.ndarray): assert target_rots.shape == (self.num_objects, 3), ( f"Incorrect target_rots.shape {target_rots.shape}, " f"which should be {(self.num_objects, 3)}." ) self.set_target_quat(rotation.euler2quat(target_rots)) def set_object_pos(self, object_positions: np.ndarray): assert object_positions.shape == (self.num_objects, 3), ( f"Incorrect object_positions.shape {object_positions.shape}, " f"which should be {(self.num_objects, 3)}." ) for i in range(self.num_objects): joint_name = f"object{i}:joint" joint_qpos = self.mj_sim.data.get_joint_qpos(joint_name) joint_qpos[:3] = object_positions[i] self.mj_sim.data.set_joint_qpos(joint_name, joint_qpos) def set_object_quat(self, object_quats: np.ndarray): assert object_quats.shape == (self.num_objects, 4), ( f"Incorrect object_quats.shape {object_quats.shape}, " f"which should be {(self.num_objects, 4)}." ) object_quats = rotation.quat_normalize(object_quats) for i in range(self.num_objects): joint_name = f"object{i}:joint" joint_qpos = self.mj_sim.data.get_joint_qpos(joint_name) joint_qpos[3:] = object_quats[i] self.mj_sim.data.set_joint_qpos(joint_name, joint_qpos) def set_object_rot(self, object_rots: np.ndarray): assert object_rots.shape == (self.num_objects, 3), ( f"Incorrect object_rots.shape {object_rots.shape}, " f"which should be {(self.num_objects, 3)}." ) self.set_object_quat(rotation.euler2quat(object_rots)) def rescale_object_sizes(self, object_scales): assert ( len(object_scales) == self.num_objects ), f"Incorrect number of scales: {len(object_scales)}, should be {self.num_objects}." for i in range(self.num_objects): object_scale = object_scales[i] self._rescale_object(f"object{i}", object_scale) self._rescale_object(f"target:object{i}", object_scale) def _rescale_object(self, object_name, object_scale): geom_ids = geom_ids_of_body(self.mj_sim, object_name) for geom_id in geom_ids: self.mj_sim.model.geom_pos[geom_id, :] *= object_scale if self.mj_sim.model.geom_type[geom_id] == const.GEOM_MESH: self.mj_sim.model.mesh_vert[ mesh_vert_range_of_geom(self.mj_sim, geom_id) ] *= object_scale else: self.mj_sim.model.geom_size[geom_id, :] *= object_scale def set_object_colors(self, colors=None): """ Set color for each object and its corresponding target. If colors are not provided, use default color in current model. """ assert ( colors is None or len(colors) == self.num_objects ), f"Incorrect number of colors: {len(colors)}, should be {self.num_objects}." for i in range(self.num_objects): object_geom_ids = geom_ids_of_body(self.mj_sim, f"object{i}") target_geom_ids = geom_ids_of_body(self.mj_sim, f"target:object{i}") if colors is not None: color = list(colors[i]) self.mj_sim.model.geom_rgba[object_geom_ids, :] = color self.mj_sim.model.geom_rgba[target_geom_ids, :] = color self.mj_sim.model.geom_rgba[target_geom_ids, -1] = 0.2 def set_object_damping(self, damping: Union[float, np.ndarray]): if isinstance(damping, float): damping = np.full(self.num_objects, damping) assert len(damping) == self.num_objects, ( f"Incorrect number of objects: {len(damping)}, " f"should be {self.num_objects}." ) for i in range(self.num_objects): joint_name = f"object{i}:joint" joint_id = self.mj_sim.model.joint_name2id(joint_name) dof_ids = [ idx for idx in range(self.mj_sim.model.nv) if self.mj_sim.model.dof_jntid[idx] == joint_id ] self.mj_sim.model.dof_damping[dof_ids] = damping[i] self.forward() def set_lighting( self, positions: np.ndarray, directions: np.ndarray, headlight_diffuse: float, headlight_ambient: float, ): n_lights = len(self.mj_sim.model.light_pos) assert n_lights == len(positions) == len(directions) self.mj_sim.model.light_pos[:] = positions self.mj_sim.model.light_dir[:] = directions self.mj_sim.model.vis.headlight.diffuse[:] = headlight_diffuse self.mj_sim.model.vis.headlight.ambient[:] = headlight_ambient def reset_camera(self, fov_delta, pos_delta, quat_delta): nc = len(self.initial_values["camera_fovy"]) for i in range(nc): self.mj_sim.model.cam_fovy[i] = ( self.initial_values["camera_fovy"][i] + fov_delta[i] ) self.mj_sim.model.cam_pos[i] = ( self.initial_values["camera_pos"][i] + pos_delta[i] ) self.mj_sim.model.cam_quat[i] = rotations.quat_mul( self.initial_values["camera_quat"][i], quat_delta[i] ) ############################################################## # Methods related to object placement. def check_objects_off_table( self, object_pos: np.ndarray, hor_margin: float = 0.0 ) -> np.ndarray: """ Calculate, per object, if object is off the table :param object_pos: matrix of object positions (num_objects, 3) :param hor_margin: how much margin of error we consider in the horizontal projection (x,y) before saying whether an object is out of the table :return: np.ndarray of shape (num_objects) with bolean values if objects are off the table """ assert object_pos.shape == (self.num_objects, 3) table_pos, table_size, table_height = self.get_table_dimensions() min_x, min_y, _ = table_pos - table_size max_x, max_y, _ = table_pos + table_size # Stack per dimension instead of per object x_pos, y_pos, z_pos = np.stack(object_pos, axis=-1) return np.logical_or.reduce( ( z_pos < table_height * 0.75, x_pos < min_x - hor_margin, x_pos > max_x + hor_margin, y_pos < min_y - hor_margin, y_pos > max_y + hor_margin, ) ) def extract_placement_area_boundary(self) -> tuple: """Extract the boundary of the placement area in 3d space. """ table_pos, table_size, table_height = self.get_table_dimensions() placement_area = self.get_placement_area() size = np.array(placement_area.size) / 2 pos = np.array(placement_area.offset) + table_pos - table_size + size min_x, min_y, min_z = pos - size max_x, max_y, max_z = pos + size return (min_x, min_y, min_z, max_x, max_y, max_z) def check_objects_in_placement_area( self, object_pos: np.ndarray, margin: float = 0.02, soft: bool = False, placement_area_boundary: Optional[tuple] = None, ) -> np.array: """ Calculate, per object, if object is within the placement area. If yes it is 1.0 otherwise 0.0. :param object_pos: matrix of object positions of shape (max_num_objects, 3) or (num_objects, 3). :param margin: how much margin of error we consider in all three dimensions. :param soft: if true, we will label an object within the margin area stochastically. :param placement_area_boundary: min & max value in each dimension in 3D space. If not provided, we would calculate it on the fly. :return: np.ndarray of shape (object_pos.shape[0], ) with boolean values if objects are within the placement area. Returns True per object if it is in the placement area. """ if object_pos.shape[0] == self.max_num_objects: assert object_pos.shape == (self.max_num_objects, 3) object_pos = object_pos[: self.num_objects] pad = True else: assert object_pos.shape == (self.num_objects, 3) pad = False if placement_area_boundary is None: placement_area_boundary = self.extract_placement_area_boundary() min_x, min_y, min_z, max_x, max_y, max_z = placement_area_boundary val_min = np.array([min_x, min_y, min_z]) val_max = np.array([max_x, max_y, max_z]) # Compute the distance per dimension to the placement boundary if out of the area. dist = np.maximum(object_pos - val_max, val_min - object_pos) dist = np.maximum(dist, np.zeros_like(dist)) assert dist.shape == (self.num_objects, 3) and np.all(dist >= 0.0) max_dist = np.max(dist, axis=-1) assert max_dist.shape == (self.num_objects,) if soft: mask_proba = np.clip(max_dist / margin, 0.0, 1.0) mask = np.random.random() > mask_proba else: mask = max_dist < margin if pad: padding = np.array( [True] * (self.max_num_objects - self.num_objects), dtype=np.bool ) mask = np.concatenate([mask, padding]) assert mask.shape == (self.max_num_objects,) else: assert mask.shape == (self.num_objects,) return mask @classmethod def compute_table_dimension(cls, table_pos, table_size): table_height = table_size[-1] + table_pos[-1] return table_pos, table_size, table_height @classmethod def get_table_dimensions_from_xml(cls, xml): """Get dimensions of the table in the world.""" # note that this makes a few assumptions on the base xml returned # by make_world_xml. If that XML changes, then this might break... table_geom_el = xml.root_element.find(".//geom[@name='table']") assert table_geom_el is not None, "Couldn't find table geom in XML" table_size = np.fromstring(table_geom_el.attrib["size"], sep=" ") table_body_el = xml.root_element.find(".//body[@name='table']") assert table_body_el is not None, "Couldn't find table body in XML" table_pos = np.fromstring(table_body_el.attrib["pos"], sep=" ") return cls.compute_table_dimension(table_pos, table_size) def get_table_dimensions(self): """ Returns the dimensions of the table: First position, then size (as half-size, as per MuJoCo contentions) and finally the table height explicitly. """ table_geom_id = self.mj_sim.model.geom_name2id("table") table_size = self.mj_sim.model.geom_size[table_geom_id].copy() table_body_id = self.mj_sim.model.body_name2id("table") table_pos = self.mj_sim.model.body_pos[table_body_id].copy() return self.compute_table_dimension(table_pos, table_size) def _get_bounding_box(self, object_name: str) -> Tuple: """ Returns the bounding box for one objects as a tuple of (positive, half size), where both positive and half size are np.array of shape (3,). """ raise NotImplementedError() def get_object_bounding_boxes(self) -> np.ndarray: """ Returns bounding boxes for all the objects as an np.array of shape (num_objects, 2, 3). where [:, 0, :] contains the center position of the bounding box in Cartesian space relative to the body's frame of reference and where [:, 1, :] contains the half-width, half-height, and half-depth of the object (as per Mujoco convention). The reason why we return a position here is that more complicated bodies will have a bounding box that is not necessarily at the center of the body itself. This is the case for objects that consist of meshes, for example. This method needs to be implemented by the concrete simulation since Mujoco does not support computing bounding boxes itself. """ return self._get_object_obs(self._get_bounding_box, pad=False) def get_target_bounding_boxes(self) -> np.ndarray: """ Same as get_object_bounding_boxes(), but returns the bounding boxes for target objects. """ return self._get_target_obs(self._get_bounding_box, pad=False) def get_object_bounding_boxes_in_table_coordinates(self) -> np.ndarray: """ The default bounding box has position readings in its own coordinate system. The method shifts the positions into the table environment. """ bboxes = self.get_object_bounding_boxes().copy() # shape: (num_objects, 2, 3) bboxes[:, 0, :] += self.get_object_pos(pad=False).copy() return bboxes def get_target_bounding_boxes_in_table_coordinates(self) -> np.ndarray: """ Same as get_shifted_object_bounding_boxes(), but works for target objects. """ bboxes = self.get_target_bounding_boxes().copy() # shape: (num_objects, 2, 3) bboxes[:, 0, :] += self.get_target_pos(pad=False).copy() return bboxes @classmethod def get_table_setting( cls, table_size: np.ndarray, num_objects: int, used_table_portion: float ): # place blocks and the targets randomly on the table # For curriculum, we use small centric region of the table to place objects. This # centric region is set by "used_table_portion". table_size_x, table_size_y = table_size[:2] * 2 minimum_table_portion = num_objects * 0.1 used_table_portion = np.clip(used_table_portion, minimum_table_portion, 1.0) return table_size_x, table_size_y, used_table_portion def get_placement_area(self) -> PlacementArea: table_pos, table_size, table_height = self.get_table_dimensions() table_size_x, table_size_y, used_table_portion = self.get_table_setting( table_size, self.num_objects, self.used_table_portion ) assert used_table_portion <= 1.0 place_size_x = 0.5 * table_size_x * used_table_portion place_size_y = 0.38 * table_size_y * used_table_portion place_size_z = 0.26 offset_x = 0.5 * table_size_x - place_size_x / 2.0 offset_y = 0.44 * table_size_y - place_size_y / 2.0 offset_z = 2 * table_size[2] return PlacementArea( offset=(offset_x, offset_y, offset_z), size=(place_size_x, place_size_y, place_size_z), ) ############################################################## # Fully internal methods. Maybe overloaded by sub classes. def _get_object_obs_with_prefix(self, obs_func, *, prefix, pad) -> np.ndarray: obs = np.asarray( [obs_func(f"{prefix}object{i}") for i in range(self.num_objects)] ) if pad: assert len(obs.shape) == 2, f"Unexpected obs shape {obs.shape}" padded_obs = np.zeros((self.max_num_objects, obs.shape[-1])) padded_obs[: obs.shape[0]] = obs obs = padded_obs return obs def _get_object_obs(self, obs_func, pad=True) -> np.ndarray: return self._get_object_obs_with_prefix(obs_func, prefix="", pad=pad) def _get_target_obs(self, obs_func, pad=True) -> np.ndarray: return self._get_object_obs_with_prefix(obs_func, prefix="target:", pad=pad) @contextmanager def override_object_state(self, obj_pos, obj_rot): """ A context manager that temporarily overrides object state. """ cached_obj_pos = self.get_object_pos(pad=False) cached_obj_quat = self.get_object_quat(pad=False) self.set_object_pos(obj_pos) self.set_object_rot(obj_rot) self.forward() yield self.set_object_pos(cached_obj_pos) self.set_object_quat(cached_obj_quat) self.forward() def get_state(self): """ Returns a copy of the simulator state. """ data = self.mj_sim.data return ExtendedSimState( time=data.time, qpos=data.qpos.copy(), qvel=data.qvel.copy(), qacc=data.qacc.copy(), ctrl=data.ctrl.copy(), actuator_force=data.actuator_force.copy(), sensordata=data.sensordata.copy(), udd_state={}, ) class ExtendedSimState( namedtuple( "MjSimState", "time qpos qvel qacc ctrl actuator_force sensordata udd_state" ) ): pass
41,540
37.750933
104
py
robogym
robogym-master/robogym/envs/rearrange/simulation/composer.py
import abc import logging import os from copy import deepcopy from typing import Dict, List, Optional, Tuple, Union import attr import numpy as np from robogym.envs.rearrange.common.utils import ( find_stls, get_mesh_bounding_box, make_composed_mesh_object, make_target, ) from robogym.envs.rearrange.simulation.base import ( ObjectGroupConfig, RearrangeSimParameters, RearrangeSimulationInterface, ) from robogym.mujoco.mujoco_xml import ASSETS_DIR, MujocoXML from robogym.randomization.env import build_randomizable_param logger = logging.getLogger(__file__) class Composer: def __init__(self, random_state: np.random.RandomState = None): if random_state is None: random_state = np.random.RandomState() self._random_state = random_state def reset(self): pass @abc.abstractmethod def sample(self, name: str, num_geoms: int, object_size: float) -> MujocoXML: """Samples a single, composed object with the given name, number of geoms, and total object size. :param name: The name of the object :param num_geoms: The number of geoms to be composed :param object_size: In half-size, as per Mujoco convenient """ raise NotImplementedError @abc.abstractmethod def get_bounding_box(self, sim, object_name) -> Tuple[float, float]: """Computes the bounding box for a single, composed object as identified by its name. """ raise NotImplementedError class RandomMeshComposer(Composer): PRIMITIVES_CACHE: Dict[str, List[str]] = {} YCB_ASSET_PATH = os.path.join(ASSETS_DIR, "stls", "ycb") GEOM_ASSET_PATH = os.path.join(ASSETS_DIR, "stls", "geom") def __init__(self, random_state=None, mesh_path: Optional[Union[list, str]] = None): super().__init__(random_state=random_state) if mesh_path is None: # Default to both YCB meshes and geoms self._mesh_paths = [self.YCB_ASSET_PATH, self.GEOM_ASSET_PATH] elif isinstance(mesh_path, str): self._mesh_paths = [mesh_path] else: assert isinstance(mesh_path, list) self._mesh_paths = mesh_path # Find meshes (and cache for performance). for path in self._mesh_paths: if path not in self.PRIMITIVES_CACHE: self.PRIMITIVES_CACHE[path] = find_stls(path) self._meshes = {p: self.PRIMITIVES_CACHE[p] for p in self._mesh_paths} assert ( sum(map(len, self._meshes.values())) > 0 ), f"Did not find any .stl files in {self._mesh_paths}" def _sample_primitives(self, num_geoms: int) -> List[str]: chosen_primitives = [] for _ in range(num_geoms): chosen_path = self._random_state.choice(self._mesh_paths) chosen_primitives.append( self._random_state.choice(self._meshes[chosen_path]) ) return chosen_primitives def sample(self, name: str, num_geoms: int, object_size: float) -> MujocoXML: chosen_primitives = self._sample_primitives(num_geoms) chosen_attachment = self._random_state.choice(["random", "last"]) return make_composed_mesh_object( name, chosen_primitives, self._random_state, mesh_size_range=(0.01, 0.1), object_size=object_size, attachment=chosen_attachment, ) def get_bounding_box(self, sim, object_name) -> Tuple[float, float]: pos, size = get_mesh_bounding_box(sim, object_name) return pos, size def composer_converter(s: str) -> Composer: """ Converts string -> Composer for a predefined set of composers. """ if s == "geom": return RandomMeshComposer(mesh_path=RandomMeshComposer.GEOM_ASSET_PATH) elif s == "mesh": return RandomMeshComposer(mesh_path=RandomMeshComposer.YCB_ASSET_PATH) elif s == "mixed": return RandomMeshComposer() else: raise ValueError() @attr.s(auto_attribs=True) class ComposerObjectGroupConfig(ObjectGroupConfig): num_geoms: int = 1 @attr.s(auto_attribs=True) class ComposerRearrangeSimParameters(RearrangeSimParameters): # Overwrite the object group config type. object_groups: List[ComposerObjectGroupConfig] = None # type: ignore def __attrs_post_init__(self): if self.object_groups is None: self.object_groups = [ ComposerObjectGroupConfig(count=1, object_ids=[obj_id]) for obj_id in range(self.num_objects) ] # Num. of geoms to use to compose one object. num_max_geoms: int = build_randomizable_param(1, low=1, high=20) # The type of object composer to be used. composer: Composer = attr.ib( # type: ignore default="mixed", converter=composer_converter, # type: ignore ) class ComposerRearrangeSim( RearrangeSimulationInterface[ComposerRearrangeSimParameters] ): """ Move around a randomly generated object of different colors on the table. Each object is composed by multiple connected geoms. """ @property def object_size(self): return self.simulation_params.object_size @property def num_max_geoms(self): return self.simulation_params.num_max_geoms @classmethod def make_objects_xml(cls, xml, simulation_params: ComposerRearrangeSimParameters): composer = simulation_params.composer composer.reset() xmls = [] for obj_group in simulation_params.object_groups: first_obj_id = obj_group.object_ids[0] object_xml = composer.sample( f"object{first_obj_id}", obj_group.num_geoms, simulation_params.object_size, ) xmls.append((object_xml, make_target(object_xml))) for j in obj_group.object_ids[1:]: copied_object_xml = deepcopy(object_xml) copied_object_xml.replace_name(f"object{first_obj_id}", f"object{j}") xmls.append((copied_object_xml, make_target(copied_object_xml))) assert len(xmls) == simulation_params.num_objects return xmls def _get_bounding_box(self, object_name): composer = self.simulation_params.composer return composer.get_bounding_box(self.mj_sim, object_name)
6,397
32.851852
93
py
robogym
robogym-master/robogym/envs/rearrange/simulation/chessboard.py
from robogym.envs.rearrange.simulation.mesh import ( MeshRearrangeSim, MeshRearrangeSimParameters, ) from robogym.mujoco.mujoco_xml import MujocoXML CHESSBOARD_XML = """ <mujoco> <asset> <texture name="chessboard_texture" type="2d" builtin="checker" rgb1="0.616 0.341 0.106" rgb2="0.902 0.8 0.671" width="300" height="300"> </texture> <material name="chessboard_mat" texture="chessboard_texture" texrepeat="{n_obj} {n_obj}" texuniform="false"> </material> </asset> <worldbody> <body pos="1.3 0.75 0.4" name="chessboard"> <geom name="chessboard" size="0.16 0.16 0.001" type="box" contype="0" conaffinity="0" material="chessboard_mat"> </geom> </body> </worldbody> </mujoco> """ class ChessboardRearrangeSim(MeshRearrangeSim): """ Rearrange a chessboard. """ @classmethod def make_world_xml( cls, *, mujoco_timestep: float, simulation_params=None, **kwargs ): if simulation_params is None: simulation_params = MeshRearrangeSimParameters() xml = super().make_world_xml( simulation_params=simulation_params, mujoco_timestep=mujoco_timestep, **kwargs ) xml.append( MujocoXML.from_string( CHESSBOARD_XML.format(n_obj=simulation_params.num_objects // 2) ) ) return xml
1,540
26.517857
90
py
robogym
robogym-master/robogym/envs/rearrange/simulation/holdout.py
from typing import Any, Dict, List, Type, TypeVar import attr import numpy as np from robogym.envs.rearrange.common.utils import get_mesh_bounding_box from robogym.envs.rearrange.simulation.base import ( RearrangeSimParameters, RearrangeSimulationInterface, ) from robogym.mujoco.mujoco_xml import MujocoXML from robogym.randomization.env import build_randomizable_param @attr.s(auto_attribs=True) class ObjectConfig: # xml path relative to robogym/assets/xmls folder xml_path: str = attr.ib() # Map between tag name to property values. # for example # { # "geom": { # "size": 0.01, # "rgba": [0.5, 0.5, 0.5, 1.0], # } # } tag_args: Dict[str, Dict[str, Any]] = {} # Same format as tag_args. Can be used to # specify material related physical properties. material_args: Dict[str, Dict[str, Any]] = {} OType = TypeVar("OType", bound=ObjectConfig) def convert_object_configs(object_config_type: Type[OType], data: Any) -> List[OType]: object_configs = [] for config in data: if isinstance(config, object_config_type): object_configs.append(config) else: assert isinstance(config, dict) object_configs.append(object_config_type(**config)) return object_configs @attr.s(auto_attribs=True) class SceneObjectConfig(ObjectConfig): """ Configs for static object in the scene. These observes will not be part of state observation and goal and will by default have collision disabled. """ # Position (x, y, z) of the object on the table which is defined as: # x: X position in range of [0, 1] relative to top left corner (-x, -y) of placement area. # y: Y position in range of [0, 1] relative to top left corner (-x, -y) of placement area . # z: Z position in meters relative to table surface. pos: List[float] = [0.0, 0.0, 0.0] # Rotation of the object. quat: List[float] = [1.0, 0.0, 0.0, 0.0] def convert_scene_object_config(data: Any) -> List[SceneObjectConfig]: return convert_object_configs(SceneObjectConfig, data) @attr.s(auto_attribs=True) class TaskObjectConfig(ObjectConfig): """ Configs for objects which are part of the task. """ # Total number of this object in the env. count: int = 1 def convert_task_object_config(data: Any) -> List[TaskObjectConfig]: return convert_object_configs(TaskObjectConfig, data) @attr.s(auto_attribs=True) class HoldoutRearrangeSimParameters(RearrangeSimParameters): scene_object_configs: List[SceneObjectConfig] = attr.ib( default=[], converter=convert_scene_object_config ) task_object_configs: List[TaskObjectConfig] = attr.ib( default=[TaskObjectConfig(xml_path="object/tests/block.xml")], converter=convert_task_object_config, ) shared_settings: str = attr.ib(default="", converter=str) num_objects: int = build_randomizable_param(low=1, high=32) @num_objects.default def default_num_objects(self): return self._num_objects() @num_objects.validator def validate_num_objects(self, _, value): if value > self._num_objects(): raise ValueError( f"Too many objects {value}, only {self._num_objects()} " f"objects are defined in config" ) def _num_objects(self): return sum(o.count for o in self.task_object_configs) class HoldoutRearrangeSim(RearrangeSimulationInterface[HoldoutRearrangeSimParameters]): """ Simulation class for holdout envs. """ @classmethod def _make_object_xml(cls, object_id: int, config: ObjectConfig): object_name = f"object{object_id}" xml = ( MujocoXML.parse(config.xml_path) .set_objects_attr(tag="joint", name="joint") .add_name_prefix(f"{object_name}:", exclude_attribs=["class"]) .set_objects_attr(tag="body", name=object_name) ) xml.set_objects_attrs(config.tag_args) xml.set_objects_attrs(config.material_args) return xml @classmethod def _make_scene_object_xml( cls, object_id: int, config: SceneObjectConfig, table_dims ): xml = cls._make_object_xml(object_id, config) table_pos, table_size, table_height = table_dims pos = np.array(config.pos) x, y, _ = table_pos + table_size * (pos * 2 - 1) z = table_height + pos[-1] xml = ( xml.add_name_prefix("scene:", exclude_attribs=["class"]) .set_objects_attr(tag="body", pos=[x, y, z]) .set_objects_attr(tag="body", quat=config.quat) .set_objects_attr(tag="geom", contype=0, conaffinity=0) ) return xml @classmethod def make_objects_xml(cls, xml, simulation_params): xmls = [] num_objects = simulation_params.num_objects object_id = 0 for object_config in simulation_params.task_object_configs[:num_objects]: for _ in range(object_config.count): obj_xml = cls._make_object_xml(object_id, object_config) target_xml = ( cls._make_object_xml(object_id, object_config) .remove_objects_by_tag("joint") .remove_objects_by_tag("mesh") # Target can reuse same mesh. .remove_objects_by_tag( "material" ) # Target can reuse same material. .add_name_prefix( "target:", exclude_attribs=["mesh", "material", "class"] ) .set_objects_attr(tag="geom", contype=0, conaffinity=0) ) xmls.append((obj_xml, target_xml)) object_id += 1 return xmls @classmethod def make_world_xml( cls, *, mujoco_timestep: float, simulation_params=None, **kwargs ): if simulation_params is None: simulation_params = HoldoutRearrangeSimParameters() world_xml = super().make_world_xml( simulation_params=simulation_params, mujoco_timestep=mujoco_timestep ) table_dims = cls.get_table_dimensions_from_xml(world_xml) for object_id, object_config in enumerate( simulation_params.scene_object_configs ): world_xml.append( cls._make_scene_object_xml(object_id, object_config, table_dims,) ) if simulation_params.shared_settings: world_xml.append(MujocoXML.parse(simulation_params.shared_settings)) return world_xml def _get_bounding_box(self, object_name): return get_mesh_bounding_box(self.mj_sim, object_name)
6,775
32.215686
95
py
robogym
robogym-master/robogym/envs/rearrange/simulation/mesh.py
from typing import List, Optional import attr from robogym.envs.rearrange.common.utils import ( get_mesh_bounding_box, make_mesh_object, make_target, ) from robogym.envs.rearrange.simulation.base import ( ObjectGroupConfig, RearrangeSimParameters, RearrangeSimulationInterface, ) @attr.s(auto_attribs=True) class MeshObjectGroupConfig(ObjectGroupConfig): # Mesh files for constructing objects mesh_files: List[str] = ["placeholder.stl"] @attr.s(auto_attribs=True) class MeshRearrangeSimParameters(RearrangeSimParameters): # Overwrite the object group config type. object_groups: List[MeshObjectGroupConfig] = None # type: ignore def __attrs_post_init__(self): if self.object_groups is None: self.object_groups = [ MeshObjectGroupConfig(count=1, object_ids=[obj_id]) for obj_id in range(self.num_objects) ] # Mesh files for each object. If not specified default placeholder # mesh will be used. mesh_files: Optional[List[List[str]]] = None # Global scale factor of mesh mesh_scale: float = 1.0 class MeshRearrangeSim(RearrangeSimulationInterface[MeshRearrangeSimParameters]): """ Move around a object generated by customized meshes on the table. The meshes can be selected from YCB or ShapeNet dataset. """ @classmethod def make_objects_xml(cls, xml, simulation_params: MeshRearrangeSimParameters): xmls = [] for obj_group in simulation_params.object_groups: # Use a placeholder stl is no mesh files specified in parameters if no mesh files # are defined. This should only happen during environment creation. for i in obj_group.object_ids: object_xml = make_mesh_object( f"object{i}", obj_group.mesh_files, scale=obj_group.scale * simulation_params.mesh_scale, ) xmls.append((object_xml, make_target(object_xml))) assert len(xmls) == simulation_params.num_objects return xmls def _get_bounding_box(self, object_name): return get_mesh_bounding_box(self.mj_sim, object_name)
2,227
31.764706
93
py
robogym
robogym-master/robogym/envs/rearrange/simulation/wordblocks.py
from robogym.envs.rearrange.common.utils import get_block_bounding_box, make_target from robogym.envs.rearrange.simulation.base import RearrangeSimulationInterface from robogym.mujoco.mujoco_xml import ASSETS_DIR, MujocoXML class WordBlocksSim(RearrangeSimulationInterface): """ reuse the OPENAI character meshes (used for block cube) """ @classmethod def make_objects_xml(cls, xml, simulation_params): def get_cube_mesh(c) -> str: return f"""<mesh name="object:letter_{c}" file="{ASSETS_DIR}/stls/openai_cube/{c}.stl" />""" def get_cube_body(idx, c) -> str: color = "0.71 0.61 0.3" letter_material = "cube:letter_white" return f""" <mujoco> <worldbody> <body name="object{idx}"> <joint name="object{idx}:joint" type="free"/> <geom name="object{idx}" size="0.0285 0.0285 0.0285" type="box" rgba="{color} 1" /> <body name="object:letter_{c}:face_top" pos="0 0 0.0285"> <geom name="object:letter_{c}" pos="0 0 -0.0009" quat="0.499998 0.5 -0.500002 0.5" type="mesh" material="{letter_material}" mesh="object:letter_{c}" /> </body> </body> </worldbody> </mujoco> """ letter_meshes = "\n".join([get_cube_mesh(c) for c in "OPENAI"]) assets_xml = f""" <mujoco> <asset> <material name="cube:top_background" specular="1" shininess="0.3" /> <material name="cube:letter" specular="1" shininess="0.3" rgba="0. 0. 1 1"/> <material name="cube:letter_white" specular="1" shininess="0.3" rgba="1 1 1 1"/> {letter_meshes} </asset> </mujoco> """ xml.append(MujocoXML.from_string(assets_xml)) xmls = [] for idx, c in enumerate("OPENAI"): if idx >= simulation_params.num_objects: break object_xml = MujocoXML.from_string(get_cube_body(idx, c)) xmls.append((object_xml, make_target(object_xml))) return xmls def _get_bounding_box(self, object_name): return get_block_bounding_box(self.mj_sim, object_name)
2,129
33.918033
167
py
robogym
robogym-master/robogym/envs/rearrange/simulation/dominos.py
import attr import numpy as np from robogym.envs.rearrange.common.utils import ( get_block_bounding_box, make_blocks_and_targets, ) from robogym.envs.rearrange.simulation.base import ( RearrangeSimParameters, RearrangeSimulationInterface, ) from robogym.randomization.env import build_randomizable_param @attr.s(auto_attribs=True) class DominosRearrangeSimParameters(RearrangeSimParameters): # How "skewed" the domino is. A bigger value corresponds to a thinner and taller domino. domino_eccentricity: float = build_randomizable_param(1.5, low=1.0, high=4.5) # The proportion compared to `object_size` to distance the dominos from each other domino_distance_mul: float = build_randomizable_param(4, low=2.0, high=5.0) num_objects: int = build_randomizable_param(5, low=1, high=8) class DominosRearrangeSim(RearrangeSimulationInterface[DominosRearrangeSimParameters]): """ Move around a dominos of different colors on the table. Similar to BlockRearrangeEnv, but with dominos in a circle arc position. """ @classmethod def make_objects_xml(cls, xml, simulation_params: DominosRearrangeSimParameters): skewed_object_size = simulation_params.object_size * np.array( [ 1 / simulation_params.domino_eccentricity, 1, 1 * simulation_params.domino_eccentricity, ] ) return make_blocks_and_targets( simulation_params.num_objects, skewed_object_size ) def _get_bounding_box(self, object_name): return get_block_bounding_box(self.mj_sim, object_name) @property def domino_eccentricity(self): return self.simulation_params.domino_eccentricity
1,746
32.596154
92
py
robogym
robogym-master/robogym/envs/rearrange/simulation/blocks.py
import attr from robogym.envs.rearrange.common.utils import ( get_block_bounding_box, make_blocks_and_targets, ) from robogym.envs.rearrange.simulation.base import ( RearrangeSimParameters, RearrangeSimulationInterface, ) @attr.s(auto_attribs=True) class BlockRearrangeSimParameters(RearrangeSimParameters): # Appearance of the block. 'standard' blocks have plane faces without any texture or mark. # 'openai' blocks have ['O', 'P', 'E', 'N', 'A', 'I'] in each face. block_appearance: str = attr.ib( default="standard", validator=attr.validators.in_(["standard", "openai"]) ) class BlockRearrangeSim(RearrangeSimulationInterface[BlockRearrangeSimParameters]): """ Move around a blocks of different colors on the table. """ @classmethod def make_objects_xml(cls, xml, simulation_params: BlockRearrangeSimParameters): return make_blocks_and_targets( simulation_params.num_objects, simulation_params.object_size, appearance=simulation_params.block_appearance, ) def _get_bounding_box(self, object_name): return get_block_bounding_box(self.mj_sim, object_name)
1,188
31.135135
94
py
robogym
robogym-master/robogym/envs/rearrange/goals/object_stack_goal.py
from typing import Dict, Tuple, Union import numpy as np from numpy.random import RandomState from robogym.envs.rearrange.common.utils import place_objects_with_no_constraint from robogym.envs.rearrange.goals.object_state import GoalArgs, ObjectStateGoal from robogym.envs.rearrange.simulation.base import RearrangeSimulationInterface from robogym.utils import rotation class ObjectStackGoal(ObjectStateGoal): def __init__( self, mujoco_simulation: RearrangeSimulationInterface, args: Union[Dict, GoalArgs] = GoalArgs(), fixed_order: bool = True, ): """ :param fixed_order: whether goal requires objects stacked in a random order. """ super().__init__(mujoco_simulation, args) self.fixed_order = fixed_order def _sample_next_goal_positions( self, random_state: RandomState ) -> Tuple[np.ndarray, bool]: # place only bottom object bottom_positions, goal_valid = place_objects_with_no_constraint( self.mujoco_simulation.get_object_bounding_boxes()[:1], self.mujoco_simulation.get_table_dimensions(), self.mujoco_simulation.get_placement_area(), max_placement_trial_count=self.mujoco_simulation.max_placement_retry, max_placement_trial_count_per_object=self.mujoco_simulation.max_placement_retry_per_object, random_state=random_state, ) goal_positions = np.repeat( bottom_positions, self.mujoco_simulation.num_objects, axis=0 ) object_size = self.mujoco_simulation.simulation_params.object_size block_orders = list(range(self.mujoco_simulation.num_objects)) if not self.fixed_order: random_state.shuffle(block_orders) bottom_block_idx = block_orders[0] goal_positions[bottom_block_idx] = bottom_positions[0] for i in range(1, self.mujoco_simulation.num_objects): new_pos = bottom_positions[0].copy() new_pos[2] += i * object_size * 2 goal_positions[block_orders[i]] = new_pos return goal_positions, goal_valid def is_object_grasped(self): grasped = self.mujoco_simulation.get_object_gripper_contact() # in teleop, somehow we could grasp object with mujoco detecting only one gripper touched the object. return np.array([x[0] + x[1] for x in grasped]) def relative_goal(self, goal_state: dict, current_state: dict) -> dict: gripper_pos = current_state["obj_pos"] - current_state["gripper_pos"] obj_pos = goal_state["obj_pos"] - current_state["obj_pos"] return { "obj_pos": obj_pos, "gripper_pos": gripper_pos, "obj_rot": self.rot_dist_func(goal_state, current_state), } def current_state(self) -> dict: gripper_pos = self.mujoco_simulation.mj_sim.data.get_site_xpos( "robot0:grip" ).copy() gripper_pos = np.array([gripper_pos]) current_state = super().current_state() current_state.update( {"gripper_pos": gripper_pos, "grasped": self.is_object_grasped()} ) return current_state def goal_distance(self, goal_state: dict, current_state: dict) -> dict: relative_goal = self.relative_goal(goal_state, current_state) pos_distances = np.linalg.norm(relative_goal["obj_pos"], axis=-1) gripper_distances = np.linalg.norm(relative_goal["gripper_pos"], axis=-1) rot_distances = rotation.quat_magnitude( rotation.quat_normalize(rotation.euler2quat(relative_goal["obj_rot"])) ) return { "relative_goal": relative_goal.copy(), "gripper_pos": gripper_distances, "obj_pos": pos_distances, "obj_rot": rot_distances, "grasped": current_state["grasped"], }
3,892
38.72449
109
py
robogym
robogym-master/robogym/envs/rearrange/goals/train_state.py
import logging from typing import Tuple import numpy as np from numpy.random import RandomState from robogym.envs.rearrange.common.utils import place_targets_with_goal_distance_ratio from robogym.envs.rearrange.goals.object_state import ObjectStateGoal logger = logging.getLogger(__name__) def move_one_object_to_the_air_with_restrictions( current_placement: np.ndarray, height_range: Tuple[float, float], object_size: float, random_state: np.random.RandomState, pickup_proba: float = 0.0, stacking_proba: float = 0.0, goal_distance_ratio: float = 1.0, ) -> np.ndarray: """ Modify current_placement to move one object to the air. Set height w.r.t goal_distance_ratio too. With probability `pickup_proba`, we will randomly move one object up into the air. Otherwise do nothing. The pickup height is discounted by `goal_distance_ratio`. """ assert 0.0 <= pickup_proba + stacking_proba <= 1.0 if pickup_proba + stacking_proba == 0: return current_placement logger.info( f"Move one object to the air with restrictions " f"(goal_distance_ratio={goal_distance_ratio} " f"pickup_proba={pickup_proba} stacking_proba={stacking_proba})" ) p = random_state.random() if p > pickup_proba + stacking_proba: # rearrange task: do nothing. return current_placement elif p < pickup_proba: # pick up task min_h, max_h = height_range height = random_state.uniform(low=min_h, high=max_h) n_objects = current_placement.shape[0] target_i = random_state.randint(n_objects) # The height of a pick-and-place goal is set w.r.t the goal distance too. current_placement[target_i, -1] += height * goal_distance_ratio return current_placement else: # stacking task n_objects = current_placement.shape[0] if n_objects >= 2: # Randomly pick block indices for building a tower of size [2, n_objects]. tower_size = random_state.randint(2, n_objects + 1) obj_indices = np.random.choice( list(range(n_objects)), size=tower_size, replace=False ) assert len(obj_indices) > 1 logger.info( f"Building a tower of size {tower_size} with object indices {obj_indices} ..." ) target_i = obj_indices[0] for height, i in enumerate(obj_indices[1:]): current_placement[i, 0] = current_placement[target_i, 0] current_placement[i, 1] = current_placement[target_i, 1] current_placement[i, 2] += object_size * (height + 1) * 2 return current_placement class TrainStateGoal(ObjectStateGoal): """ This is a goal state generator for the training environment. The goal is placed wrt a goal_distance restriction. """ def _sample_next_goal_positions( self, random_state: RandomState ) -> Tuple[np.ndarray, bool]: placement, is_valid = place_targets_with_goal_distance_ratio( self.mujoco_simulation.get_object_bounding_boxes(), self.mujoco_simulation.get_table_dimensions(), self.mujoco_simulation.get_placement_area(), self.mujoco_simulation.get_object_pos()[ : self.mujoco_simulation.num_objects ], goal_distance_ratio=self.mujoco_simulation.goal_distance_ratio, goal_distance_min=self.mujoco_simulation.goal_distance_min, max_placement_trial_count=self.mujoco_simulation.max_placement_retry, max_placement_trial_count_per_object=self.mujoco_simulation.max_placement_retry_per_object, random_state=random_state, ) placement = move_one_object_to_the_air_with_restrictions( placement, height_range=self.args.height_range, object_size=self.mujoco_simulation.simulation_params.object_size, random_state=random_state, pickup_proba=self.args.pickup_proba, stacking_proba=self.args.stacking_proba, goal_distance_ratio=self.mujoco_simulation.goal_distance_ratio, ) return placement, is_valid
4,256
36.342105
103
py
robogym
robogym-master/robogym/envs/rearrange/goals/holdout_object_state.py
import os from typing import List import attr import numpy as np from numpy.random import RandomState from robogym.envs.rearrange.goals.object_state import GoalArgs, ObjectStateGoal from robogym.envs.rearrange.holdouts import STATE_DIR from robogym.envs.rearrange.simulation.base import RearrangeSimulationInterface @attr.s(auto_attribs=True) class HoldoutGoalArgs(GoalArgs): randomize_goal_rot: bool = True # Path for each goal state. If multiple paths are # provided, goal generation will round robin through # all these states. goal_state_paths: List[str] = [] class HoldoutObjectStateGoal(ObjectStateGoal): def __init__( self, mujoco_simulation: RearrangeSimulationInterface, args: HoldoutGoalArgs = HoldoutGoalArgs(), ): super().__init__(mujoco_simulation, args=args) self.goal_pos = [] self.goal_quat = [] for goal_state_path in args.goal_state_paths: goal_state = np.load(os.path.join(STATE_DIR, goal_state_path)) self.goal_pos.append( goal_state["obj_pos"][: self.mujoco_simulation.num_objects] ) self.goal_quat.append( goal_state["obj_quat"][: self.mujoco_simulation.num_objects] ) self.goal_idx = 0 def next_goal(self, random_state: RandomState, current_state: dict): goal = super().next_goal(random_state, current_state) if self.goal_idx >= len(self.goal_pos): self.goal_idx = 0 return goal def _sample_next_goal_positions(self, random_state: RandomState): if len(self.goal_pos) > 0: return self.goal_pos[self.goal_idx], True else: return super()._sample_next_goal_positions(random_state) def _sample_next_goal_orientations(self, random_state: RandomState): if len(self.goal_quat) > 0: return self.goal_quat[self.goal_idx] else: return super()._sample_next_goal_orientations(random_state) def goal_distance(self, goal_state: dict, current_state: dict) -> dict: dist = super().goal_distance(goal_state, current_state) # calculate relative positions, # this logic does NOT handle duplicate objects. if self.mujoco_simulation.num_groups == self.mujoco_simulation.num_objects: goal_pos, cur_pos = goal_state["obj_pos"], current_state["obj_pos"] anchor_idx = np.argmin(goal_pos[:, 2]) target_rel_pos = goal_pos - goal_pos[anchor_idx] + cur_pos[anchor_idx] dist["rel_dist"] = np.linalg.norm(cur_pos - target_rel_pos, axis=1) return dist
2,662
34.506667
83
py
robogym
robogym-master/robogym/envs/rearrange/goals/attached_block_state.py
from typing import Tuple import numpy as np from numpy.random import RandomState from robogym.envs.rearrange.common.utils import place_targets_with_fixed_position from robogym.envs.rearrange.goals.object_state import ObjectStateGoal class AttachedBlockStateGoal(ObjectStateGoal): """ This is a goal state generator for the advanced blocks environment, where the goal configuration of the blocks are highly structured and blocks are tightly attached to each other. """ def _sample_next_goal_positions( self, random_state: RandomState ) -> Tuple[np.ndarray, bool]: # Set all the goals to the initial rotation first. self.mujoco_simulation.set_target_quat(np.array([[1, 0, 0, 0]] * 8)) self.mujoco_simulation.forward() # Set position of blocks block_size = self.mujoco_simulation.simulation_params.object_size width, height, _ = self.mujoco_simulation.get_placement_area().size # Note that block_size and rel_w, rel_h are all half of the block size rel_w, rel_h = block_size / width, block_size / height # offset for making blocks to be attached to each other offset_w, offset_h = rel_w * 2, rel_h * 2 # Expected configuration # [ ][ ] # [ ][ ][ ][ ] # [ ][ ] block_config = random_state.permutation( [ [offset_w, 0], [offset_w * 2, 0], [0, offset_h], [offset_w, offset_h], [offset_w * 2, offset_h], [offset_w * 3, offset_h], [offset_w, offset_h * 2], [offset_w * 2, offset_h * 2], ] ) # Now randomly place the overall config in the placement area config_w, config_h = block_config.max(axis=0) margin_w, margin_h = 1.0 - config_w - rel_w, 1.0 - config_h - rel_h ori_x, ori_y = random_state.uniform( low=(rel_w, rel_h), high=(margin_w, margin_h) ) # Randomize the position of the entire block configuration. block_config += np.array([[ori_x, ori_y]]) # Then place the objects as designed. return place_targets_with_fixed_position( self.mujoco_simulation.get_object_bounding_boxes(), self.mujoco_simulation.get_table_dimensions(), self.mujoco_simulation.get_placement_area(), block_config, )
2,471
34.826087
98
py
robogym
robogym-master/robogym/envs/rearrange/goals/pickandplace.py
from typing import Dict, Tuple, Union import numpy as np from numpy.random import RandomState from robogym.envs.rearrange.goals.object_state import GoalArgs, ObjectStateGoal from robogym.envs.rearrange.simulation.base import RearrangeSimulationInterface class PickAndPlaceGoal(ObjectStateGoal): def __init__( self, mujoco_simulation: RearrangeSimulationInterface, args: Union[Dict, GoalArgs] = GoalArgs(), height_range: Tuple[float, float] = (0.05, 0.25), ): super().__init__(mujoco_simulation, args) self.height_range = height_range def _sample_next_goal_positions( self, random_state: RandomState ) -> Tuple[np.ndarray, bool]: placement, is_valid = super()._sample_next_goal_positions(random_state) placement = move_one_object_to_the_air( current_placement=placement, height_range=self.height_range, random_state=random_state, ) return placement, is_valid def move_one_object_to_the_air( current_placement: np.ndarray, height_range: Tuple[float, float], random_state: np.random.RandomState, ) -> np.ndarray: """ Modify current_placement to move one object to the air. :param current_placement: np.ndarray of size (num_objects, 3) where columns are x, y, z coordinates of objects relative to the world frame. :param height_range: One object is moved along z direction to have height from table in a range (min_height, max_height). Height is randomly sampled. :param random_state: numpy RandomState to use for sampling :return: modified object placement. np.ndarray of (num_objects, 3) where columns are x, y, z coordinates of objects relative to the world frame. """ n_objects = current_placement.shape[0] min_h, max_h = height_range height = random_state.uniform(low=min_h, high=max_h) target_i = random_state.randint(n_objects) current_placement[target_i, -1] += height return current_placement
2,037
34.754386
96
py
robogym
robogym-master/robogym/envs/rearrange/goals/object_reach_goal.py
from typing import Dict, Tuple, Union import numpy as np from numpy.random import RandomState from robogym.envs.rearrange.common.utils import place_objects_with_no_constraint from robogym.envs.rearrange.goals.object_state import GoalArgs, ObjectStateGoal from robogym.envs.rearrange.simulation.base import RearrangeSimulationInterface class ObjectReachGoal(ObjectStateGoal): def __init__( self, mujoco_simulation: RearrangeSimulationInterface, args: Union[Dict, GoalArgs] = GoalArgs(), ): super().__init__(mujoco_simulation, args=args) assert ( self.mujoco_simulation.num_objects == 1 ), "reach only supports one objects" self.mujoco_simulation: RearrangeSimulationInterface = mujoco_simulation def _sample_next_goal_positions( self, random_state: RandomState ) -> Tuple[np.ndarray, bool]: goal_positions, goal_valid = place_objects_with_no_constraint( self.mujoco_simulation.get_object_bounding_boxes(), self.mujoco_simulation.get_table_dimensions(), self.mujoco_simulation.get_placement_area(), max_placement_trial_count=self.mujoco_simulation.max_placement_retry, max_placement_trial_count_per_object=self.mujoco_simulation.max_placement_retry_per_object, random_state=random_state, ) self.mujoco_simulation.set_object_pos(goal_positions) # set reach target to specified height above the table. goal_positions[0][2] += self.mujoco_simulation.simulation_params.target_height return goal_positions, goal_valid def current_state(self) -> dict: """ Here we use gripper position as realized goal state, so the goal distance is distance betweeen gripper and goal position. """ gripper_pos = self.mujoco_simulation.mj_sim.data.get_site_xpos( "robot0:grip" ).copy() obj_pos = np.array([gripper_pos]) return dict( obj_pos=obj_pos, obj_rot=np.zeros_like(obj_pos) ) # We don't care about rotation. class DeterministicReachGoal(ObjectReachGoal): """ Reach goal generator with a deterministic sequence of goal positions. """ def __init__( self, mujoco_simulation: RearrangeSimulationInterface, args: Union[Dict, GoalArgs] = GoalArgs(), ): super().__init__(mujoco_simulation, args=args) p0 = np.array([1.50253879, 0.36960144, 0.5170952]) p1 = np.array([1.32253879, 0.53960144, 0.5170952]) self.idx = 0 self.all_positions = [p0, p1] def _sample_next_goal_positions( self, random_state: RandomState ) -> Tuple[np.ndarray, bool]: self.idx = (self.idx + 1) % len(self.all_positions) goal_pos = self.all_positions[self.idx] goal_positions = np.array([goal_pos]) self.mujoco_simulation.set_object_pos(goal_positions) goal_positions[0][2] += self.mujoco_simulation.simulation_params.target_height return goal_positions, True
3,083
36.156627
103
py
robogym
robogym-master/robogym/envs/rearrange/goals/dominos.py
from typing import Optional, Tuple import numpy as np from numpy.random import RandomState from robogym.envs.rearrange.common.utils import PlacementArea from robogym.envs.rearrange.goals.object_state import ObjectStateGoal from robogym.utils import rotation MAX_RETRY = 1000 class DominoStateGoal(ObjectStateGoal): """ This is a goal state generator for the dominos environment only, it does a lot of math to place the dominos (skewed blocks) into a circle arc. """ @classmethod def _adjust_and_check_fit( cls, num_objects: int, target_bounding_boxes: np.ndarray, positions: np.ndarray, placement_area: PlacementArea, random_state: RandomState, ) -> Tuple[bool, Optional[np.ndarray]]: """ This method will check if the current `target_bounding_boxes` and `positions` can fit in the table and if so, will return a new array of positions randomly sampled inside of the `placement_area` """ width, height, _ = placement_area.size half_sizes = target_bounding_boxes[:, 1, :] max_x, max_y, _ = np.max(positions + half_sizes, axis=0) min_x, min_y, _ = np.min(positions - half_sizes, axis=0) size_x, size_y = max_x - min_x, max_y - min_y if size_x < width and size_y < height: # Sample a random offset of the "remaning area" delta_x = -min_x + random_state.random() * (width - size_x) delta_y = -min_y + random_state.random() * (height - size_y) return ( True, positions + np.tile(np.array([delta_x, delta_y, 0]), (num_objects, 1)), ) return False, None # Internal method def _create_new_domino_position_and_rotation( self, random_state: RandomState ) -> Tuple[Optional[np.ndarray], Optional[np.ndarray]]: """ This method will attempt at creating a new setup of dominos. The setup is to have the dominos be equally spaced across a circle arc :return: Tuple[proposed_positions, proposed_angles] proposed_positions: np.ndarray of shape (num_objects, 3) with proposed target positions, or None if placement fails proposed_angles: np.ndarray of shape (num_objects,) with proposed target angles, or None if placement fails """ num_objects = self.mujoco_simulation.num_objects for _ in range(MAX_RETRY): # Offset that the whole domino chain is rotated by, this rotate the whole arc of dominos globally proposed_offset = random_state.random() * np.pi # Angle between the rotation of one domino and the next. Random angle offset between -pi/8 and pi/8 proposed_delta = random_state.random() * (np.pi / 4.0) - (np.pi / 8.0) # Angles each domino will be rotated respectively proposed_angles = np.array(range(num_objects)) * proposed_delta + ( proposed_offset + proposed_delta / 2 ) # Set target quat so that the computation for `get_target_bounding_boxes` is correct self._set_target_quat(num_objects, proposed_angles) angles_between_objects = ( np.array(range(1, 1 + num_objects)) * proposed_delta + proposed_offset ) object_distance = ( self.mujoco_simulation.simulation_params.object_size * self.mujoco_simulation.simulation_params.domino_distance_mul ) x = np.cumsum(np.cos(angles_between_objects)) * object_distance y = np.cumsum(np.sin(angles_between_objects)) * object_distance # Proposed positions proposed_positions = np.zeros((num_objects, 3)) # Copy the z axis values: target_bounding_boxes = ( self.mujoco_simulation.get_target_bounding_boxes() ) # List[obj_pos, obj_size] proposed_positions[:, 2] = target_bounding_boxes[:, 1, 2] for target_idx in range(num_objects): # First target will be at (0, 0) and the remaning targets will be offset from that if target_idx > 0: proposed_positions[target_idx] += np.array( [x[target_idx - 1], y[target_idx - 1], 0] ) is_valid, proposed_positions = self._adjust_and_check_fit( num_objects, target_bounding_boxes, proposed_positions, self.mujoco_simulation.get_placement_area(), random_state, ) if is_valid and proposed_positions is not None: return proposed_positions, proposed_angles # Mark failure to fit goal positions return None, None def _sample_next_goal_positions( self, random_state: RandomState ) -> Tuple[np.ndarray, bool]: num_objects = self.mujoco_simulation.num_objects ( proposed_positions, proposed_angles, ) = self._create_new_domino_position_and_rotation(random_state) if proposed_positions is None or proposed_angles is None: # The `False` will show this is not a valid goal position return np.zeros((num_objects, 3)), False # Add the needed offsets ( table_pos, table_size, table_height, ) = self.mujoco_simulation.get_table_dimensions() placement_area = self.mujoco_simulation.get_placement_area() start_x, start_y, _ = table_pos - table_size start_x += placement_area.offset[0] start_y += placement_area.offset[1] return_value = proposed_positions + np.tile( [start_x, start_y, table_height], (num_objects, 1) ) return return_value, True def _set_target_quat(self, num_objects: int, proposed_angles: np.ndarray) -> None: proposed_quaternions = rotation.quat_from_angle_and_axis( angle=proposed_angles, axis=np.array([[0, 0, 1.0]] * num_objects) ) self.mujoco_simulation.set_target_quat(proposed_quaternions) self.mujoco_simulation.forward()
6,248
38.301887
127
py
robogym
robogym-master/robogym/envs/rearrange/goals/object_state_fixed.py
from typing import Dict, Optional, Tuple, Union import numpy as np from numpy.random import RandomState from robogym.envs.rearrange.common.utils import place_targets_with_fixed_position from robogym.envs.rearrange.goals.object_state import GoalArgs, ObjectStateGoal from robogym.envs.rearrange.simulation.base import RearrangeSimulationInterface class ObjectFixedStateGoal(ObjectStateGoal): def __init__( self, mujoco_simulation: RearrangeSimulationInterface, args: Union[Dict, GoalArgs], relative_placements: np.ndarray, init_quats: Optional[np.ndarray] = None, ): """ Always return fixed goal state for each object. :param relative_placements: the relative position of each object, relative to the placement area. Each dimension is a ratio between [0, 1]. :param init_quats: the desired quat of each object. """ super().__init__(mujoco_simulation, args) if init_quats is None: init_quats = np.array([[1, 0, 0, 0]] * self.mujoco_simulation.num_objects) assert relative_placements.shape == (self.mujoco_simulation.num_objects, 2) assert init_quats.shape == (self.mujoco_simulation.num_objects, 4) self.relative_placements = relative_placements self.init_quats = init_quats def _sample_next_goal_positions( self, random_state: RandomState ) -> Tuple[np.ndarray, bool]: # Set all the goals to the initial rotation first. quats = np.array(self.init_quats) self.mujoco_simulation.set_target_quat(quats) self.mujoco_simulation.forward() # Then place the objects as designed. return place_targets_with_fixed_position( self.mujoco_simulation.get_object_bounding_boxes(), self.mujoco_simulation.get_table_dimensions(), self.mujoco_simulation.get_placement_area(), self.relative_placements, )
1,975
36.283019
105
py
robogym
robogym-master/robogym/envs/rearrange/goals/object_state.py
from copy import deepcopy from typing import Callable, Dict, List, Optional, Tuple, Union import attr import numpy as np from numpy.random import RandomState from robogym.envs.rearrange.common.utils import ( place_objects_in_grid, place_objects_with_no_constraint, stabilize_objects, update_object_z_coordinate, ) from robogym.envs.rearrange.simulation.base import RearrangeSimulationInterface from robogym.goal.goal_generator import GoalGenerator from robogym.utils import rotation from robogym.utils.icp import ICP PARALLEL_QUATS = [rotation.euler2quat(x) for x in rotation.get_parallel_rotations()] PARALLEL_QUATS_180 = [ rotation.euler2quat(x) for x in rotation.get_parallel_rotations_180() ] def euler_angle_difference_single_pair( q1: np.ndarray, q2: np.ndarray, parallel_quats: List[np.ndarray] ) -> np.ndarray: assert q1.shape == q2.shape == (4,) if np.allclose(q1, q2): return np.zeros(3) diffs = np.array( [ rotation.quat_difference(rotation.quat_mul(q1, parallel_quat), q2) for parallel_quat in parallel_quats ] ) dists = rotation.quat_magnitude(diffs) indices = np.argmin(dists, axis=0) return rotation.quat2euler(diffs[indices]) def euler_angle_difference( goal_state: dict, current_state: dict, mode: str ) -> np.ndarray: """ This method applies - all 24 possible mod 90 degree rotations to given euler angle (if mode = 'mod90'); - or, all 4 possible mod 180 degree rotations to given euler angle (if mode = 'mod180'). and return the one with minimum quat distance. """ assert mode in ("mod90", "mod180") parallel_quats = PARALLEL_QUATS if mode == "mod90" else PARALLEL_QUATS_180 q1 = rotation.euler2quat(goal_state["obj_rot"]) q2 = rotation.euler2quat(current_state["obj_rot"]) return np.array( [ euler_angle_difference_single_pair(q1[i], q2[i], parallel_quats) for i in range(q1.shape[0]) ] ) def full_euler_angle_difference(goal_state: dict, current_state: dict): return rotation.subtract_euler(goal_state["obj_rot"], current_state["obj_rot"]) def _random_quat_along_z(num_objects: int, random_state: RandomState): """ Internal helper function generating random rotation quat along z axis """ quat = rotation.quat_from_angle_and_axis( angle=random_state.uniform(low=0.0, high=2.0 * np.pi, size=num_objects), axis=np.array([[0, 0, 1.0]] * num_objects), ) return quat def randomize_quaternion_along_z( mujoco_simulation: RearrangeSimulationInterface, random_state: RandomState ): """ Rotate goal along z axis and return the rotated quat of the goal """ quat = _random_quat_along_z(mujoco_simulation.num_objects, random_state) return rotation.quat_mul(quat, mujoco_simulation.get_target_quat(pad=False)) def randomize_quaternion_block( mujoco_simulation: RearrangeSimulationInterface, random_state: RandomState ): """ Rotate goal and return the rotated quat of the goal. Assuming objects are blocks, this function randomly choose any face of the block as top face, and rotate it along z axis """ num_objects = mujoco_simulation.num_objects z_quat = _random_quat_along_z(num_objects, random_state) face_quat_indices = random_state.randint( low=0, high=len(PARALLEL_QUATS), size=num_objects ) face_quat = np.array([PARALLEL_QUATS[i] for i in face_quat_indices]) target_quat = mujoco_simulation.get_target_quat(pad=False) return rotation.quat_mul(z_quat, rotation.quat_mul(target_quat, face_quat)) def randomize_quaternion_full( mujoco_simulation: RearrangeSimulationInterface, random_state: RandomState ): """ Rotate goal in any orientation and return the rotated quat of the goal. The goal may be in an unstable position depending on the shape of the objects. """ quat = np.array( [ rotation.uniform_quat(random_state) for _ in range(mujoco_simulation.num_objects) ] ) return rotation.quat_mul(quat, mujoco_simulation.get_target_quat(pad=False)) @attr.s(auto_attribs=True) class GoalArgs: # If true randomize goal orientation. randomize_goal_rot: bool = False # Type of rotation distance calculation for goal. rot_dist_type: str = attr.ib( default="full", validator=attr.validators.in_(["full", "mod90", "mod180", "icp"]), ) # Type of rotation randomization for goal. # z_axis: randomize rotation along z axis # block: assume the object is box. first randomize face direction and then rotate along z axis # full: fully rotate object in any direction rot_randomize_type: str = attr.ib( default="z_axis", validator=attr.validators.in_(["z_axis", "block", "full"]) ) # Max number of vertices to sample from object body for icp calculation. icp_max_num_vertices: int = 500 # Threshold for nearest neighbor error for icp. The absolute threshold value # is defined as bounding_box_size * error_threshold icp_error_threshold: float = 0.15 # If true, check the bounding box IoU before calling ICP rot distance measure. icp_use_bbox_precheck: bool = False # If true, step simulation to stabilize goal objects. stabilize_goal: bool = False # whether to render robot in the goal image p_goal_hide_robot: float = 1.0 # If true, when calling check_objects_in_placement_area(), we will label an object # within the margin area stochastically. soft_mask: bool = False # The margin of error we consider when calling check_objects_in_placement_area(). mask_margin: float = 0.02 @property def goal_hide_robot(self) -> bool: return np.random.rand() < self.p_goal_hide_robot # Parameters for adding pick-and-place and stacking goals into blocks training env. height_range: Tuple[float, float] = (0.05, 0.25) pickup_proba: float = 0.0 stacking_proba: float = 0.0 class ObjectStateGoal(GoalGenerator): """ This is the default goal state generator for the rearrangement task. The goal can be places everywhere on the table without restrictions. """ def __init__( self, mujoco_simulation: RearrangeSimulationInterface, args: Union[Dict, GoalArgs] = GoalArgs(), ): """ :param mujoco_simulation: The mujoco simulation instance. :param args: All goal related arguments. """ self.mujoco_simulation = mujoco_simulation if isinstance(args, GoalArgs): self.args = args else: assert isinstance(args, dict) self.args = GoalArgs(**args) rot_dist_funcs: Dict[str, Callable[[dict, dict], np.ndarray]] = { "full": full_euler_angle_difference, "mod90": lambda g1, g2: euler_angle_difference(g1, g2, "mod90"), "mod180": lambda g1, g2: euler_angle_difference(g1, g2, "mod180"), "icp": self._icp_euler_angle_difference, } self.rot_dist_func = rot_dist_funcs[self.args.rot_dist_type] rot_randomize_funcs: Dict[ str, Callable[[RearrangeSimulationInterface, RandomState], np.ndarray] ] = { "z_axis": randomize_quaternion_along_z, "block": randomize_quaternion_block, "full": randomize_quaternion_full, } self.rot_randomize_func = rot_randomize_funcs[self.args.rot_randomize_type] # Only used for vertices sampling self._vertices_random_state = np.random.RandomState(seed=0) super().__init__() def _bounding_box_ious(self, goal_state: Dict, current_state: Dict) -> List[float]: """ For each object, check the object bounding boxes of the object and the target, and then compute the overlap (IoU = interaction over union) between two top-down views of these two boxes. :returns: a list of object-target bounding box IoU metrics, one per object. """ assert ( "bounding_box" in current_state ), "Current object bounding box is not available in goal state" assert ( "bounding_box" in goal_state ), "Target object bounding box is not available in goal state" bbox_ious = [] for i in range(self.mujoco_simulation.num_objects): opos, (ox, oy, oz) = current_state["bounding_box"][i] tpos, (tx, ty, tz) = goal_state["bounding_box"][i] # (x1, y1) is top left corner and (x2, y2) is the bottom right corner. x1 = max(opos[0] - ox, tpos[0] - tx) y1 = min(opos[1] + oy, tpos[1] + ty) x2 = min(opos[0] + ox, tpos[0] + tx) y2 = max(opos[1] - oy, tpos[1] - ty) inter_area = abs(max((x2 - x1, 0)) * max((y1 - y2), 0)) if inter_area == 0: iou = 0.0 else: oarea = ox * oy * 4 tarea = tx * ty * 4 iou = inter_area / (oarea + tarea - inter_area) bbox_ious.append(iou) return bbox_ious def _icp_euler_angle_difference(self, goal_state: dict, current_state: dict): assert ( "vertices" in current_state ), "vertices not available in current goal state" assert "icp" in goal_state, "ICP not available in target goal state" angles = np.zeros_like(current_state["obj_rot"]) if self.args.icp_use_bbox_precheck: bbox_ious = self._bounding_box_ious(goal_state, current_state) else: bbox_ious = np.ones(self.mujoco_simulation.num_objects) for i, (ov, icp, bbox_iou) in enumerate( zip(current_state["vertices"], goal_state["icp"], bbox_ious,) ): # Use an arbitrarily large rotation distance as a default value. angles[i] = [np.pi / 2, np.pi / 2, np.pi / 2] if bbox_iou > 0.75: # Use ICP to compute the rotation distance only when the bounding box IoU is # large enough. Note that this check only makes sense for sparse reward. # In the foreseen future, it is very unlikely we will use dense reward. # Randomly sample vertices from object. ov_indices = self._vertices_random_state.permutation(ov.shape[0])[ : self.args.icp_max_num_vertices ] mat = icp.compute(ov[ov_indices]) if mat is not None: angles[i] = rotation.mat2euler(mat) return angles def _stablize_goal_objects(self): # read current object position and rotation. object_pos = self.mujoco_simulation.get_object_pos(pad=False).copy() object_quat = self.mujoco_simulation.get_object_quat(pad=False).copy() # set object pos/rot as target pos/rot self.mujoco_simulation.set_object_pos( self.mujoco_simulation.get_target_pos(pad=False) ) self.mujoco_simulation.set_object_quat( self.mujoco_simulation.get_target_quat(pad=False) ) self.mujoco_simulation.forward() # Recompute z position of objects based on new bounding box computed from new orientation updated = update_object_z_coordinate( self.mujoco_simulation.get_object_pos(pad=False), # Do not use target_bounding_boxes here because we stabilize target by copying its # state to object before stabilizing it. self.mujoco_simulation.get_object_bounding_boxes(), self.mujoco_simulation.get_table_dimensions(), ) self.mujoco_simulation.set_object_pos(updated) self.mujoco_simulation.forward() stabilize_objects(self.mujoco_simulation) # read and set stabilized goal pos/rot self.mujoco_simulation.set_target_pos( self.mujoco_simulation.get_object_pos(pad=False) ) self.mujoco_simulation.set_target_rot( self.mujoco_simulation.get_object_rot(pad=False) ) self.mujoco_simulation.forward() # restore object pos/rot back to original self.mujoco_simulation.set_object_pos(object_pos) self.mujoco_simulation.set_object_quat(object_quat) self.mujoco_simulation.forward() def _update_simulation_for_next_goal( self, random_state: RandomState ) -> Tuple[bool, Dict[str, np.ndarray]]: """ Sample new goal configs and returns a tuple of: - a bool flag whether the goal is valid. - the new goal config. """ # Sample target object orientations. if self.args.randomize_goal_rot: self._randomize_goal_orientation(random_state) # Sample target object positions. goal_positions, goal_valid = self._sample_next_goal_positions(random_state) if goal_valid: self.mujoco_simulation.set_target_pos(goal_positions) self.mujoco_simulation.forward() if self.args.stabilize_goal: self._stablize_goal_objects() goal = { "obj_pos": self.mujoco_simulation.get_target_pos().copy(), "obj_rot": self.mujoco_simulation.get_target_rot().copy(), } return goal_valid, goal def next_goal(self, random_state: RandomState, current_state: dict) -> dict: """ Set goal position for each object and get goal dict. """ goal_valid, goal_dict = self._update_simulation_for_next_goal(random_state) target_pos = goal_dict["obj_pos"] target_rot = goal_dict["obj_rot"] num_objects = self.mujoco_simulation.num_objects target_on_table = not self.mujoco_simulation.check_objects_off_table( target_pos[:num_objects] ).any() # Compute which of the goals is within the target placement area. Pad this to include # observations for up to max_num_objects (default to `1.0` for empty slots). # If an object is out of the placement, the corresponding position in the mask is 0.0. in_placement_area = self.mujoco_simulation.check_objects_in_placement_area( target_pos, margin=self.args.mask_margin, soft=self.args.soft_mask ) assert in_placement_area.shape == (target_pos.shape[0],) # Create qpos for goal state: based on the current qpos but overwrite the object # positions to desired positions. num_objects = self.mujoco_simulation.num_objects qpos_goal = self.mujoco_simulation.qpos.copy() for i in range(num_objects): qpos_idx = self.mujoco_simulation.mj_sim.model.get_joint_qpos_addr( f"object{i}:joint" )[0] qpos_goal[qpos_idx: qpos_idx + 3] = target_pos[i].copy() qpos_goal[qpos_idx + 3: qpos_idx + 7] = rotation.euler2quat(target_rot[i]) goal_invalid_reason: Optional[str] = None if not goal_valid: goal_invalid_reason = "Goal placement is invalid" elif not target_on_table: goal_invalid_reason = "Some goal objects are off the table." goal = { "obj_pos": target_pos.copy(), "obj_rot": target_rot.copy(), "qpos_goal": qpos_goal.copy(), "goal_valid": goal_valid and target_on_table, "goal_in_placement_area": in_placement_area.all(), "goal_objects_in_placement_area": in_placement_area.copy(), "goal_invalid_reason": goal_invalid_reason, } if self.args.rot_dist_type == "icp": goal["vertices"] = deepcopy(self.mujoco_simulation.get_target_vertices()) goal["icp"] = [ ICP(vertices, error_threshold=self.args.icp_error_threshold) for vertices in self.mujoco_simulation.get_target_vertices( # Multiple by 2 because in theory max distance between # a vertices and it's closest neighbor should be ~edge length / 2. subdivide_threshold=self.args.icp_error_threshold * 2 ) ] if self.args.icp_use_bbox_precheck: goal[ "bounding_box" ] = ( self.mujoco_simulation.get_target_bounding_boxes_in_table_coordinates().copy() ) return goal def _randomize_goal_orientation(self, random_state: RandomState): rotated_quat = self._sample_next_goal_orientations(random_state) self.mujoco_simulation.set_target_quat(rotated_quat) self.mujoco_simulation.forward() def _sample_next_goal_positions( self, random_state: RandomState ) -> Tuple[np.ndarray, bool]: placement, is_valid = place_objects_in_grid( self.mujoco_simulation.get_object_bounding_boxes(), self.mujoco_simulation.get_table_dimensions(), self.mujoco_simulation.get_placement_area(), random_state=random_state, max_num_trials=self.mujoco_simulation.max_placement_retry, ) if not is_valid: # Fall back to random placement, which works better for envs with more irregular # objects (e.g. ycb-8 with no mesh normalization). return place_objects_with_no_constraint( self.mujoco_simulation.get_object_bounding_boxes(), self.mujoco_simulation.get_table_dimensions(), self.mujoco_simulation.get_placement_area(), max_placement_trial_count=self.mujoco_simulation.max_placement_retry, max_placement_trial_count_per_object=self.mujoco_simulation.max_placement_retry_per_object, random_state=random_state, ) else: return placement, is_valid def _sample_next_goal_orientations(self, random_state: RandomState) -> np.ndarray: """ Sample goal orientation in quaternion """ return self.rot_randomize_func(self.mujoco_simulation, random_state) def current_state(self) -> dict: """ Extract current cube goal state """ state = { "obj_pos": self.mujoco_simulation.get_object_pos().copy(), "obj_rot": self.mujoco_simulation.get_object_rot().copy(), "qpos": self.mujoco_simulation.qpos.copy(), } if self.args.rot_dist_type == "icp": state["vertices"] = deepcopy(self.mujoco_simulation.get_object_vertices()) state["icp"] = [ ICP(vertices, error_threshold=self.args.icp_error_threshold) for vertices in self.mujoco_simulation.get_object_vertices( # Multiple by 2 because in theory max distance between # a vertices and it's closest neighbor should be ~edge length / 2. subdivide_threshold=self.args.icp_error_threshold * 2 ) ] if self.args.icp_use_bbox_precheck: state[ "bounding_box" ] = ( self.mujoco_simulation.get_target_bounding_boxes_in_table_coordinates().copy() ) return state def relative_goal(self, goal_state: dict, current_state: dict) -> dict: goal_pos = goal_state["obj_pos"] obj_pos = current_state["obj_pos"] if self.mujoco_simulation.num_objects == self.mujoco_simulation.num_groups: # All the objects are different. relative_obj_pos = goal_pos - obj_pos relative_obj_rot = self.rot_dist_func(goal_state, current_state) else: # per object relative pos & rot distance. rel_pos_dict = {} rel_rot_dict = {} def get_rel_rot(target_obj_id, curr_obj_id): group_goal_state = {"obj_rot": goal_state["obj_rot"][[target_obj_id]]} group_current_state = { "obj_rot": current_state["obj_rot"][[curr_obj_id]] } if self.args.rot_dist_type == "icp": group_goal_state["icp"] = [goal_state["icp"][target_obj_id]] group_current_state["vertices"] = [ current_state["vertices"][curr_obj_id] ] return self.rot_dist_func(group_goal_state, group_current_state)[0] for group_id, obj_group in enumerate(self.mujoco_simulation.object_groups): object_ids = obj_group.object_ids # Duplicated objects share the same group id. # Within each group we match objects with goals according to position in a greedy # fashion. Note that we ignore object rotation during matching. if len(object_ids) == 1: object_id = object_ids[0] rel_pos_dict[object_id] = goal_pos[object_id] - obj_pos[object_id] rel_rot_dict[object_id] = get_rel_rot(object_id, object_id) else: n = len(object_ids) # find the optimal pair matching through greedy. # TODO: may consider switching to `scipy.optimize.linear_sum_assignment` assert obj_pos.shape == goal_pos.shape dist = np.linalg.norm( np.expand_dims(obj_pos[object_ids], 1) - np.expand_dims(goal_pos[object_ids], 0), axis=-1, ) assert dist.shape == (n, n) for _ in range(n): i, j = np.unravel_index(np.argmin(dist, axis=None), dist.shape) rel_pos_dict[object_ids[i]] = ( goal_pos[object_ids[j]] - obj_pos[object_ids[i]] ) rel_rot_dict[object_ids[i]] = get_rel_rot( object_ids[j], object_ids[i] ) # once we select a pair of match (i, j), wipe out their distance info. dist[i, :] = np.inf dist[:, j] = np.inf assert ( len(rel_pos_dict) == len(rel_rot_dict) == self.mujoco_simulation.num_objects ) rel_pos = np.array( [rel_pos_dict[i] for i in range(self.mujoco_simulation.num_objects)] ) rel_rot = np.array( [rel_rot_dict[i] for i in range(self.mujoco_simulation.num_objects)] ) assert len(rel_pos.shape) == len(rel_rot.shape) == 2 # padding zeros for the final output. relative_obj_pos = np.zeros( (self.mujoco_simulation.max_num_objects, rel_pos.shape[-1]) ) relative_obj_rot = np.zeros( (self.mujoco_simulation.max_num_objects, rel_rot.shape[-1]) ) relative_obj_pos[: rel_pos.shape[0]] = rel_pos relative_obj_rot[: rel_rot.shape[0]] = rel_rot # normalize angles relative_obj_rot = rotation.normalize_angles(relative_obj_rot) return { "obj_pos": relative_obj_pos.copy(), "obj_rot": relative_obj_rot.copy(), } def goal_distance(self, goal_state: dict, current_state: dict) -> dict: relative_goal = self.relative_goal(goal_state, current_state) pos_distances = np.linalg.norm(relative_goal["obj_pos"], axis=-1) rot_distances = rotation.quat_magnitude( rotation.quat_normalize(rotation.euler2quat(relative_goal["obj_rot"])) ) return { "relative_goal": relative_goal, "obj_pos": np.maximum( pos_distances + self.mujoco_simulation.goal_pos_offset, 0 ), # L2 dist "obj_rot": self.mujoco_simulation.goal_rot_weight * rot_distances, # quat magnitude }
24,160
39.268333
107
py
robogym
robogym-master/robogym/envs/tests/test_wrapper_compositions.py
from copy import deepcopy from robogym.wrappers.named_wrappers import edit_wrappers def test_edit_wrappers(): test_wrappers = [ ["StopOnFallWrapper"], ["RandomizedActionLatency"], ["RandomizedCubeSizeWrapper"], ["RandomizedBodyInertiaWrapper"], ["RandomizedTimestepWrapper"], ["RandomizedFrictionWrapper"], ["RandomizedGravityWrapper"], ["RandomizedWindWrapper"], ] test_wrappers_insert_above_query = [ ["RandomizedCubeSizeWrapper", ["TESTWRAPPER1", {"arg1": "yayyy"}]], ["RandomizedFrictionWrapper", ["TESTWRAPPER2", {"arg2": "yayyy"}]], ] test_wrappers_insert_above_answer = [ ["StopOnFallWrapper"], ["RandomizedActionLatency"], ["TESTWRAPPER1", {"arg1": "yayyy"}], ["RandomizedCubeSizeWrapper"], ["RandomizedBodyInertiaWrapper"], ["RandomizedTimestepWrapper"], ["TESTWRAPPER2", {"arg2": "yayyy"}], ["RandomizedFrictionWrapper"], ["RandomizedGravityWrapper"], ["RandomizedWindWrapper"], ] test_wrappers_insert_below_query = [ ["RandomizedCubeSizeWrapper", ["TESTWRAPPER1", {"arg1": "yayyy"}]], ["RandomizedFrictionWrapper", ["TESTWRAPPER2", {"arg2": "yayyy"}]], ] test_wrappers_insert_below_answer = [ ["StopOnFallWrapper"], ["RandomizedActionLatency"], ["RandomizedCubeSizeWrapper"], ["TESTWRAPPER1", {"arg1": "yayyy"}], ["RandomizedBodyInertiaWrapper"], ["RandomizedTimestepWrapper"], ["RandomizedFrictionWrapper"], ["TESTWRAPPER2", {"arg2": "yayyy"}], ["RandomizedGravityWrapper"], ["RandomizedWindWrapper"], ] test_wrappers_delete_query = [ "RandomizedBodyInertiaWrapper", "RandomizedFrictionWrapper", ] test_wrappers_delete_answer = [ ["StopOnFallWrapper"], ["RandomizedActionLatency"], ["RandomizedCubeSizeWrapper"], ["RandomizedTimestepWrapper"], ["RandomizedGravityWrapper"], ["RandomizedWindWrapper"], ] test_wrappers_replace_query = [ ["RandomizedBodyInertiaWrapper", ["TESTWRAPPER1", {"arg1": "yayyy"}]], ["RandomizedFrictionWrapper", ["TESTWRAPPER2", {"arg2": "yayyy"}]], ] test_wrappers_replace_answer = [ ["StopOnFallWrapper"], ["RandomizedActionLatency"], ["RandomizedCubeSizeWrapper"], ["TESTWRAPPER1", {"arg1": "yayyy"}], ["RandomizedTimestepWrapper"], ["TESTWRAPPER2", {"arg2": "yayyy"}], ["RandomizedGravityWrapper"], ["RandomizedWindWrapper"], ] assert ( edit_wrappers( wrappers=deepcopy(test_wrappers), insert_above=test_wrappers_insert_above_query, ) == test_wrappers_insert_above_answer ) assert ( edit_wrappers( wrappers=deepcopy(test_wrappers), insert_below=test_wrappers_insert_below_query, ) == test_wrappers_insert_below_answer ) assert ( edit_wrappers( wrappers=deepcopy(test_wrappers), delete=test_wrappers_delete_query ) == test_wrappers_delete_answer ) assert ( edit_wrappers( wrappers=deepcopy(test_wrappers), replace=test_wrappers_replace_query ) == test_wrappers_replace_answer )
3,397
31.056604
81
py
robogym
robogym-master/robogym/viewer/env_viewer.py
import time from copy import deepcopy from typing import List, Union import glfw import numpy as np from gym.spaces import Box, MultiDiscrete from mujoco_py import MjViewer, const, ignore_mujoco_warnings from robogym.utils.misc import pretty class EnvViewer(MjViewer): def __init__(self, env): self.env = env self.elapsed = [0] self.env.reset() self.seed = strip_seed(self.env.seed()) super().__init__(self.env.unwrapped.sim) self.num_action = self.env.action_space.shape[0] # Needed for gym 0.10.8. # TODO: Next 3 lines can be removed in gym >= 0.12.4 if isinstance(self.num_action, tuple): assert len(self.num_action) == 1 self.num_action = self.num_action[0] self.action_mod_index = 0 self.action = self.zero_action(self.env.action_space) self.last_step_result = None def zero_action(self, action_space): if isinstance(action_space, Box): return np.zeros(action_space.shape[0]) elif isinstance(action_space, MultiDiscrete): return action_space.nvec // 2 # assume middle element is "no action" action def env_reset(self): start = time.time() # get the seed before calling env.reset(), so we display the one # that was used for the reset. self.seed = strip_seed(self.env.seed()) self.env.reset() self.elapsed.append(time.time() - start) self.update_sim(self.env.unwrapped.sim) def env_reset_goal(self): start = time.time() # get the seed before calling env.reset(), so we display the one # that was used for the reset. self.seed = strip_seed(self.env.seed()) self.env.reset_goal() self.elapsed.append(time.time() - start) self.update_sim(self.env.unwrapped.sim) def key_callback(self, window, key, scancode, action, mods): # Trigger on keyup only: if action != glfw.RELEASE: return if key == glfw.KEY_ESCAPE: self.env.close() # Increment experiment seed elif key == glfw.KEY_N: self.seed += 1 self.env.seed(self.seed) self.env_reset() self.action = self.zero_action(self.env.action_space) elif key == glfw.KEY_G: self.env_reset_goal() self.action = self.zero_action(self.env.action_space) # Decrement experiment trial elif key == glfw.KEY_P: self.seed = max(self.seed - 1, 0) self.env.seed(self.seed) self.env_reset() self.action = self.zero_action(self.env.action_space) if key == glfw.KEY_A: if isinstance(self.env.action_space, Box): self.action[self.action_mod_index] -= 0.05 elif isinstance(self.env.action_space, MultiDiscrete): self.action[self.action_mod_index] = max( 0, self.action[self.action_mod_index] - 1 ) elif key == glfw.KEY_Z: if isinstance(self.env.action_space, Box): self.action[self.action_mod_index] += 0.05 elif isinstance(self.env.action_space, MultiDiscrete): self.action[self.action_mod_index] = min( self.env.action_space.nvec[self.action_mod_index] - 1, self.action[self.action_mod_index] + 1, ) elif key == glfw.KEY_K: self.action_mod_index = (self.action_mod_index + 1) % self.num_action elif key == glfw.KEY_J: self.action_mod_index = (self.action_mod_index - 1) % self.num_action elif key == glfw.KEY_B: if self._has_debug_option(): self.env.unwrapped.parameters.debug = ( not self.env.unwrapped.parameters.debug ) super().key_callback(window, key, scancode, action, mods) def render(self): super().render() # Display applied external forces. self.vopt.flags[8] = 1 def _has_debug_option(self): if not hasattr(self.env.unwrapped, "parameters"): return False return hasattr(self.env.unwrapped.parameters, "debug") def _get_action(self): return self.action def process_events(self): """ A hook for subclasses to process additional events. This method is called right before updating the simulation. """ pass def run(self, once=False): while True: self.process_events() self.update_sim(self.env.unwrapped.sim) self.add_extra_menu() with ignore_mujoco_warnings(): obs, reward, done, info = self._run_step(self._get_action()) self.last_step_result = deepcopy((obs, reward, done, info)) self.add_overlay(const.GRID_BOTTOMRIGHT, "done", str(done)) self.render() self.update_aux_display() if once: return def _run_step(self, action): return self.env.step(action) def add_extra_menu(self): self.add_overlay( const.GRID_TOPRIGHT, "Reset env; (current seed: {})".format(self.seed), "N - next / P - previous ", ) self.add_overlay(const.GRID_TOPRIGHT, "Apply action", "A (-0.05) / Z (+0.05)") self.add_overlay( const.GRID_TOPRIGHT, "on action index %d out %d" % (self.action_mod_index, self.num_action), "J / K", ) if self._has_debug_option(): self.add_overlay( const.GRID_TOPRIGHT, "De[b]ug", str(self.env.unwrapped.parameters.debug) ) self.add_overlay( const.GRID_BOTTOMRIGHT, "Reset took", "%.2f sec." % (sum(self.elapsed) / len(self.elapsed)), ) self.add_overlay(const.GRID_BOTTOMRIGHT, "Action", pretty(self.action)) def update_aux_display(self): """ Update an auxiliary display/output; called every step after sim has been updated. """ pass def strip_seed(seed: Union[List[int], int]) -> int: """ Takes 1-element long list and returns it's element. Used to turn a single element list of seeds to its value. """ if isinstance(seed, list): assert len(seed) == 1, "Expected list of length 1." return seed[0] return seed
6,462
34.905556
97
py
robogym
robogym-master/robogym/viewer/robot_control_viewer.py
import logging import glfw import numpy as np from gym.spaces import MultiDiscrete from mujoco_py import const from robogym.robot.composite.controllers.ur_gripper_arm import ( Direction, URGripperArmController, ) from robogym.utils.misc import pretty from robogym.viewer.env_viewer import EnvViewer logger = logging.getLogger(__name__) class RobotControlViewer(EnvViewer): """ A viewer which support controlling the robot via keyboard control. The key bindings are as follows: Key binds in EnvViewer (unless override) + - UP/DOWN/LEFT/RIGHT: Go backward/forward/left/right. - Z/X: Go down/up. - C/V: Close/open gripper. - Q/W: Rotate wrist CW/CCW. - Y/U: Tilt the wrist. - -/=: Slow down/speed up gripper moving. """ def __init__(self, env): assert isinstance(env.action_space, MultiDiscrete), ( f"This viewer only works with env with discrete action space, " f"got {env.action_space} instead." ) self.controller = URGripperArmController(env.unwrapped) super().__init__(env) def key_callback(self, window, key, scancode, action, mods): if action == glfw.PRESS: self._press_key_callback(window, key, scancode, mods) elif action == glfw.RELEASE: self._release_key_callback(window, key, scancode, mods) def _press_key_callback(self, window, key, scancode, mods): """ Key callback on press action. """ if key == glfw.KEY_X: self.action = self._discretize(self.controller.move_z(Direction.NEG)) elif key == glfw.KEY_Z: self.action = self._discretize(self.controller.move_z(Direction.POS)) elif key == glfw.KEY_V: self.action = self._discretize(self.controller.move_gripper(Direction.NEG)) elif key == glfw.KEY_C: self.action = self._discretize(self.controller.move_gripper(Direction.POS)) elif key == glfw.KEY_UP: self.action = self._discretize(self.controller.move_x(Direction.NEG)) elif key == glfw.KEY_DOWN: self.action = self._discretize(self.controller.move_x(Direction.POS)) elif key == glfw.KEY_LEFT: self.action = self._discretize(self.controller.move_y(Direction.NEG)) elif key == glfw.KEY_RIGHT: self.action = self._discretize(self.controller.move_y(Direction.POS)) elif key == glfw.KEY_Q: self.action = self._discretize(self.controller.rotate_wrist(Direction.POS)) elif key == glfw.KEY_W: self.action = self._discretize(self.controller.rotate_wrist(Direction.NEG)) elif key == glfw.KEY_Y: self.action = self._discretize(self.controller.tilt_gripper(Direction.POS)) elif key == glfw.KEY_U: self.action = self._discretize(self.controller.tilt_gripper(Direction.NEG)) else: super().key_callback(window, key, scancode, glfw.PRESS, mods) def _release_key_callback(self, window, key, scancode, mods): self.action = self.zero_action(self.env.action_space) if key == glfw.KEY_MINUS: self.controller.speed_down() elif key == glfw.KEY_EQUAL: self.controller.speed_up() elif key in [ glfw.KEY_Z, glfw.KEY_X, glfw.KEY_C, glfw.KEY_V, glfw.KEY_UP, glfw.KEY_DOWN, glfw.KEY_LEFT, glfw.KEY_RIGHT, ]: # Don't respond on release for sticky control keys. return else: super().key_callback(window, key, scancode, glfw.RELEASE, mods) def _discretize(self, action): """ This assumes the env uses discretized action which is true for all rearrang envs. """ return ((action + 1) * self.env.action_space.nvec / 2).astype(np.int32) def add_extra_menu(self): self.add_overlay( const.GRID_TOPRIGHT, "De[b]ug", str(self.env.unwrapped.parameters.debug) ) self.add_overlay( const.GRID_TOPRIGHT, "Go backward/forward/left/right", "[up]/[down]/[left]/[right] arrow", ) self.add_overlay(const.GRID_TOPRIGHT, "Go up/down", "[Z]/[X]") self.add_overlay(const.GRID_TOPRIGHT, "Open/Close gripper", "[V]/[C]") self.add_overlay(const.GRID_TOPRIGHT, "Rotate wrist CW/CCW", "[Q]/[W]") self.add_overlay(const.GRID_TOPRIGHT, "Tilt Wrist", "[Y]/[U]") self.add_overlay(const.GRID_TOPRIGHT, "Slow down/Speed up", "[-]/[=]") self.add_overlay( const.GRID_BOTTOMRIGHT, "Reset took", "%.2f sec." % (sum(self.elapsed) / len(self.elapsed)), ) self.add_overlay(const.GRID_BOTTOMRIGHT, "Action", pretty(self._get_action())) self.add_overlay( const.GRID_BOTTOMRIGHT, "Control Mode", str(self.env.unwrapped.parameters.robot_control_params.control_mode.value), ) self.add_overlay( const.GRID_BOTTOMRIGHT, "TCP Solver Mode", str( self.env.unwrapped.parameters.robot_control_params.tcp_solver_mode.value ), ) gripper_force = self.controller.get_gripper_actuator_force() if gripper_force is not None: self.add_overlay( const.GRID_BOTTOMRIGHT, "Gripper Force", "%.2f" % gripper_force ) # - - - - > re-grasp regrasp = self.controller.get_gripper_regrasp_status() regrasp_str = "Unknown" if regrasp is not None: regrasp_str = "ON!" if regrasp else "Off" self.add_overlay(const.GRID_BOTTOMRIGHT, "Gripper Auto Re-grasp", regrasp_str) # < - - - - re-grasp self.add_overlay( const.GRID_BOTTOMRIGHT, "Wrist Angle", str(np.rad2deg(self.env.observe()["robot_joint_pos"][5])), ) if self.last_step_result: obs, reward, done, info = self.last_step_result self.add_overlay( const.GRID_TOPRIGHT, "Is goal achieved?", str(bool(obs["is_goal_achieved"].item())), ) for k, v in info.get("goal_max_dist", {}).items(): self.add_overlay(const.GRID_TOPRIGHT, f"max_goal_dist_{k}", f"{v:.2f}") if info.get("wrist_cam_contacts", {}): contacts = info["wrist_cam_contacts"] self.add_overlay( const.GRID_TOPRIGHT, "wrist_cam_collision", str(any(contacts.values())), ) active_contacts = [ contact_obj for contact_obj, contact_st in contacts.items() if contact_st ] self.add_overlay( const.GRID_TOPRIGHT, "wrist_cam_contacts", str(active_contacts) )
7,040
37.059459
89
py
robogym
robogym-master/robogym/viewer/holdout_creation_viewer.py
import os from collections import deque from datetime import datetime import glfw import numpy as np from mujoco_py import const from robogym.envs.rearrange.holdouts import STATE_DIR from robogym.viewer.robot_control_viewer import RobotControlViewer class HoldoutCreationViewer(RobotControlViewer): """ Viewer which can be used to create hold out env for rearrange. The key bindings are as follows: Key binds in RobotControlViewer + - K: Save current state as initial state. - L: Save current state as goal state. - <: Go back 1 second and pause. """ def __init__(self, env, name): super().__init__(env) self.name = name self.state_dir = os.path.join(STATE_DIR, name) self.state_buffer = deque(maxlen=100) self.buffer_interval_s = 1 def env_reset(self): super().env_reset() self.state_buffer.clear() def add_extra_menu(self): super().add_extra_menu() self.add_overlay( const.GRID_TOPRIGHT, "Save current state as initial state", "[K]" ) self.add_overlay(const.GRID_TOPRIGHT, "Save current state as goal state", "[L]") self.add_overlay(const.GRID_TOPRIGHT, "Go back 1 second", "[<]") def _release_key_callback(self, window, key, scancode, mods): if key == glfw.KEY_K: self._save_state("initial_state") elif key == glfw.KEY_L: self._save_state("goal_state") elif key == glfw.KEY_COMMA: self._revert() else: super()._release_key_callback(window, key, scancode, mods) def _save_state(self, filename_prefix): mujoco_simulation = self.env.unwrapped.mujoco_simulation data = { "obj_pos": mujoco_simulation.get_object_pos(pad=False), "obj_quat": mujoco_simulation.get_object_quat(pad=False), } os.makedirs(self.state_dir, exist_ok=True) path = os.path.join( self.state_dir, f"{filename_prefix}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.npz", ) np.savez(path, **data) print(f"State saved to {path}") def _run_step(self, action): # Don't push new checkpoint immediately after revert. if ( not self.state_buffer or self.state_buffer[-1].time < self.sim.data.time - self.buffer_interval_s ): self.state_buffer.append(self.sim.get_state()) return super()._run_step(action) def _revert(self): """ Revert one checkpoint back. """ if self.state_buffer: state = self.state_buffer.pop() self.sim.set_state(state) self.sim.forward() self._paused = True def render(self): with self.env.unwrapped.mujoco_simulation.hide_target(): super().render()
2,879
29
88
py
robogym
robogym-master/robogym/observation/image.py
import abc from typing import Dict import numpy as np from robogym.observation.common import Observation, ObservationProvider class ImageObservationProvider(ObservationProvider, abc.ABC): """ Interface for observation provider which can provide rendered image. """ @property @abc.abstractmethod def images(self) -> Dict[str, np.ndarray]: pass class ImageObservation(Observation[ImageObservationProvider]): """ Observation class which provides image observation. """ def get(self): return self.provider.images class MobileImageObservationProvider(ObservationProvider, abc.ABC): """ Interface for observation provider for mobile camera images. """ @property @abc.abstractmethod def mobile_images(self) -> Dict[str, np.ndarray]: pass class MobileImageObservation(Observation[MobileImageObservationProvider]): """ Observation class which provides mobile image observation. """ def get(self): return self.provider.mobile_images
1,049
21.340426
74
py
robogym
robogym-master/robogym/observation/goal.py
import abc from copy import deepcopy from typing import Callable, Dict, Optional, TypeVar import numpy as np from robogym.observation.common import Observation, ObservationProvider, SyncType from robogym.observation.image import ImageObservationProvider class GoalObservationProvider(ObservationProvider): """ Provider for observations coming from target goal state. """ def __init__(self, get_goal: Callable[[], dict]): self.get_goal_info = get_goal def sync(self): """ Goal is property of environment so getting it doesn't come with any extra cost. We can just always return latest goal. """ pass @property def goal(self): goal_info = deepcopy(self.get_goal_info()[2]) goal_dict = goal_info.pop("goal") goal_dict.update(goal_info) return goal_dict @property def is_successful(self): return np.array([self.get_goal_info()[1]], dtype=np.int32) class GoalImageObservationProvider( GoalObservationProvider, ImageObservationProvider, abc.ABC ): def __init__(self, get_goal: Callable[[], dict]): GoalObservationProvider.__init__(self, get_goal) ImageObservationProvider.__init__(self) class GoalRenderedImageObservationProvider(GoalImageObservationProvider, abc.ABC): """ Goal observation provider with images rendered for goal state. """ # We only need to re-render goal image at reset_goal. SYNC_TYPE = SyncType.RESET_GOAL def __init__( self, get_goal: Callable[[], dict], goal_qpos_key: str, ): """ :param get_goal: The function to get latest goal information. :param goal_qpos_key: The key to fetch goal qpos from goal dict. """ super().__init__(get_goal) self.goal_qpos_key = goal_qpos_key # Numpy array of goal image of shape (n cameras, image_size, image_size, 3) self._goal_images: Optional[np.ndarray] = None def sync(self): super().sync() self._goal_images = self._render_goal_images(self.goal[self.goal_qpos_key]) @property def images(self) -> np.ndarray: """ Return numpy array of the goal image. """ assert self._goal_images is not None, "Goal image not rendered yet." return self._goal_images @abc.abstractmethod def _render_goal_images(self, goal_qpos) -> Dict[str, np.ndarray]: pass class GoalRealImageObservationProvider(GoalImageObservationProvider): """ Goal observation provider with images directly from goal dict. """ SYNC_TYPE = SyncType.RESET_GOAL def __init__(self, get_goal: Callable[[], dict], goal_image_key: str): """ :param get_goal: The function to get latest goal information. :param goal_image_key: The key to fetch goal image from goal dict. """ super().__init__(get_goal) self.goal_image_key = goal_image_key @property def images(self) -> np.ndarray: return self.goal[self.goal_image_key] PType = TypeVar("PType", bound=GoalObservationProvider) class GoalObservation(Observation[PType], abc.ABC): """ Observation which derives from another observation. There is no strong reason to have this but there are cases where we keep redundant observations in order to be backward compatible with old policies. This class provides a simple way to create new observation based on existing observation. """ pass
3,505
28.965812
84
py
robogym
robogym-master/robogym/observation/dummy_vision.py
import abc from typing import Callable, Generic, List import numpy as np from robogym.observation.goal import GoalRenderedImageObservationProvider from robogym.observation.image import ImageObservationProvider from robogym.robot_env import SType class DummyVisionObservationProvider(ImageObservationProvider, Generic[SType], abc.ABC): """ Image observation provider which produces a placeholder vision observation so that the gym env using it has the proper observatin space. This can be replacaed by a Mujoco provider to use rendered Mujoco images. """ def __init__( self, camera_names: List[str], image_size: int, ): super().__init__() self._images = np.zeros((len(camera_names), image_size, image_size, 3)) @property def images(self): return self._images def sync(self): pass class DummyVisionGoalObservationProvider( GoalRenderedImageObservationProvider, Generic[SType], abc.ABC ): """ Goal image observation provider which produces a dummy vision goal so that the gym env using it has the proper observation space. """ def __init__( self, get_goal: Callable[[], dict], goal_qpos_key: str, camera_names: List[str], image_size: int, ): super().__init__(get_goal, goal_qpos_key) self._goal_images = np.zeros((len(camera_names), image_size, image_size, 3)) @property def goal_images(self): return self._goal_images def _render_goal_images(self, goal_qpos): return self._goal_images
1,583
27.8
113
py
robogym
robogym-master/robogym/observation/mujoco.py
import abc from typing import Generic, TypeVar import numpy as np from robogym.mujoco.simulation_interface import SimulationInterface from robogym.observation.common import Observation, ObservationProvider SType = TypeVar("SType", bound=SimulationInterface) class MujocoObservationProvider(ObservationProvider, Generic[SType]): """ Provider for observation coming from Mujoco. """ def __init__( self, mujoco_simulation: SType, ): self.mujoco_simulation = mujoco_simulation def sync(self): """ To sync observation from Mujoco simulation, we just need to forward the simulation. """ self.mujoco_simulation.forward() class MujocoObservation(Observation[MujocoObservationProvider[SType]], abc.ABC): """ Interface for all observation coming from Mujoco. """ class MujocoQposObservation(MujocoObservation): """ Implement mujoco base qpos observation. """ def get(self) -> np.ndarray: """ Return mujoco qpos, excluding target joints. """ qpos_obs = self.provider.mujoco_simulation.qpos qpos_obs[self.provider.mujoco_simulation.qpos_idxs["target_all_joints"]] = 0.0 return qpos_obs class MujocoQvelObservation(MujocoObservation): """ Implement mujoco base qvel observation. """ def get(self) -> np.ndarray: """ Return mujoco qvel, excluding target joints. """ qvel_obs = self.provider.mujoco_simulation.qvel qvel_obs[self.provider.mujoco_simulation.qvel_idxs["target_all_joints"]] = 0.0 return qvel_obs
1,630
25.306452
86
py
robogym
robogym-master/robogym/observation/common.py
import abc from enum import Enum from typing import Generic, TypeVar import numpy as np class SyncType(Enum): """ Enum which determines how frequent sync() will be called for given observation provider. This can be used to control when given observation will change. There are 3 different sync types: STEP: sync() will be called every step. This is the most common uses case and default. Observation provider with STEP sync type will sync observation data every step thus result corresponding observation to change every step. RESET_GOAL: sync() will be called only when a new goal is generated. This can be used to define observations which are constant for each goal. A typical use case of this sync type is goal related observations e.g. goal_images RESET: Sync() will be called only during environment reset. This can be used to define observations which are constant for each episode. Use cases for this sync type can be environment constants or per episode noises. Note: SyncType with smaller value is considered as subset of SyncType with larger value. For example, STEP sync type will also be called during goal reset and RESET_GOAL will also be called during env reset. """ STEP = 0 # Sync every step. RESET_GOAL = 1 # Sync only during reset goal. RESET = 2 # Sync only during reset. class ObservationProvider(abc.ABC): """ Top level interface for observation provider which has two main responsibilities: 1. Fetch raw data from observation source at beginning of each environment step. 2. Provide cached data for observation interface. To implement this interface properly, you should make sure that you: 1. Implement sync to fetch fresh data from observation source and cache it. 2. Expose cached data via some public method which can be consumed by observation interface. There are two optional optional methods that can also be implemented to: 1. Allow recording wrapper to read data for each step. 2. Allow communication with simulation after each reset. No public method other than sync should be allowed fetch data from observation source. """ SYNC_TYPE = SyncType.STEP # Sync type for this observation provider. @abc.abstractmethod def sync(self) -> None: """ Sync data from source. This method will only be called at the beginning of each environment step. This should be the only public method which involves data fetching from observation source. """ pass def reset(self) -> None: """ Reset internal state of this observation provider. Will be called during environment reset. """ pass def record_data(self) -> dict: """ Return data which is needed by recording wrapper. """ return {} PType = TypeVar("PType", bound=ObservationProvider) class Observation(abc.ABC, Generic[PType]): """ Top level interface for observation which is responsible for return data for each keyed environment observation. The interface can be subclassed to implement observation which comes from different sources. """ def __init__(self, provider: PType): self.provider = provider @abc.abstractmethod def get(self) -> np.ndarray: """ Returns data for this observation which will be provided directly to the policy. Note: This method should be implemented on the assumption that underlying raw data is already fetched, which means the implementation of this method should 1. Fast i.e. no network communication. 2. Readonly i.e. shouldn't change internal state of the environment. 3. Idempotent i.e. calling this method twice in a row should always return same result Returns data for this observation. """ pass def reset(self): """ This method is called during environment initialization or reset. Most observations don't need to do anything here except those which need to update simulation state during reset. """ pass def record_data(self) -> dict: """ Return data which is needed by recording wrapper. """ return {}
4,389
33.296875
91
py
robogym
robogym-master/robogym/scripts/examine.py
#!/usr/bin/env python3 import logging import click from robogym.envs.rearrange.common.base import RearrangeEnv from robogym.utils.env_utils import load_env from robogym.utils.parse_arguments import parse_arguments from robogym.viewer.env_viewer import EnvViewer from robogym.viewer.robot_control_viewer import RobotControlViewer logger = logging.getLogger(__name__) @click.command() @click.argument("argv", nargs=-1, required=False) @click.option( "--teleoperate", is_flag=True, help="If true, loads environment in teleop mode. Teleop mode is only supported for rearrange environments with TCP robot control modes", ) def main(argv, teleoperate): """ examine.py is used to display environments. \b Example uses: ./examine.py dactyl/full_perpendicular.py : displays environment full_perpendicular from envs/dactyl/full_perpendicular.py ./examine.py rearrange/blocks.py --teleoperate : loads BlocksRearrangeEnv in teleoperate mode such that the robot can be teleoperated via the keyboard. """ names, kwargs = parse_arguments(argv) assert len(names) == 1, "Expected a single argument for the environment." env_name = names[0] env, args_remaining = load_env(env_name, return_args_remaining=True, **kwargs) assert env is not None, print( '"{}" doesn\'t seem to be a valid environment'.format(env_name) ) if teleoperate: teleop_compatible = ( isinstance(env.unwrapped, RearrangeEnv) and env.parameters.robot_control_params.is_tcp_controlled() ) assert ( teleop_compatible ), "Teleoperation is only supported for rearrange environments with TCP control modes." viewer = RobotControlViewer if teleoperate else EnvViewer viewer(env).run() if __name__ == "__main__": # This ensures that we spawn new processes instead of forking. This is necessary # rendering has to be in spawned process. GUI cannot be in a forked process. # set_start_method('spawn', force=True) logging.getLogger("").handlers = [] logging.basicConfig(format="%(asctime)s %(message)s", level=logging.INFO) main()
2,172
35.216667
159
py
robogym
robogym-master/robogym/scripts/create_holdout.py
#!/usr/bin/env python3 import os import click from robogym.utils.env_utils import load_env from robogym.utils.parse_arguments import parse_arguments from robogym.viewer.holdout_creation_viewer import HoldoutCreationViewer @click.command() @click.argument("argv", nargs=-1, required=True) def main(argv): """ Create holdout env using given config. This script is only supported for rearrange environment. Example usage: python scripts/create_holdout.py envs/rearrange/holdouts/configs/sample.jsonnet """ create_holdout(argv) def create_holdout(argv): names, kwargs = parse_arguments(argv) config_path = names[0] env = load_env(f"{config_path}::make_env", **kwargs) name = os.path.splitext(os.path.basename(config_path))[0] viewer = HoldoutCreationViewer(env, name) viewer.run() if __name__ == "__main__": main()
878
22.756757
83
py
robogym
robogym-master/robogym/tests/test_robot_env.py
import attr from robogym.robot_env import build_nested_attr def test_build_nested_attr(): @attr.s(auto_attribs=True) class NestedParameters: a: int = 0 b: int = 1 @attr.s(auto_attribs=True) class Parameters: nested: NestedParameters = build_nested_attr(NestedParameters) @attr.s(auto_attribs=True) class ParametersOverload(Parameters): nested: NestedParameters = build_nested_attr( NestedParameters, default=dict(a=2) ) parameters = Parameters() assert isinstance(parameters.nested, NestedParameters) assert parameters.nested.a == 0 assert parameters.nested.b == 1 parameters = Parameters(nested={"a": 2}) assert isinstance(parameters.nested, NestedParameters) assert parameters.nested.a == 2 assert parameters.nested.b == 1 parameters = ParametersOverload() assert parameters.nested.a == 2 assert parameters.nested.b == 1 parameters = ParametersOverload(nested={"a": 3}) assert parameters.nested.a == 3 assert parameters.nested.b == 1 parameters = ParametersOverload(nested={"b": 3}) assert parameters.nested.a == 2 assert parameters.nested.b == 3
1,203
27
70
py
robogym
robogym-master/robogym/goal/goal_generator.py
from abc import ABC, abstractmethod from typing import Any, Dict, Set from numpy.random import RandomState class GoalGenerator(ABC): """ Interface for goal generation Goals are represented as states in which the environment must get. Usually, only a subset of the full state vector (or "qpos" in Mujoco-terms) determines the goal. For example, for cube-flipping tasks only the orientation (quaternion) of the cube matters, the position of the ShadowHand joints do not. The GoalGenerator interface requires two goal state dicts {goal_name: state}, where the state is usually a scalar or numpy.ndarray representing some subset of the full state (like the pose of the robot or a position of an object in the environment). The two dicts are: - current_state: current state of the environment - goal_state: the state in which the goal has been achieved The environment will use the goal_distance() method and compare it to a threshold to determine if the goal_state has been achieved. """ def __init__(self): # reached_terminal_state is used for longer sequences of goals to signal that the final # goal state has been reached. self.reached_terminal_state = False @abstractmethod def next_goal(self, random_state: RandomState, current_state: dict) -> dict: """ Generate a new goal from current cube goal state """ raise NotImplementedError @abstractmethod def current_state(self) -> dict: """ Extract current cube goal state """ raise NotImplementedError @abstractmethod def relative_goal(self, goal_state: dict, current_state: dict) -> dict: """ Calculate a difference in the 'goal space' between current state and the target goal. For example, for a (x, y, z) position this might be the vector from the current_state to the goal_state (goal_state - current_state). The magnitude of the relative_goal is often used as the goal_distance. """ raise NotImplementedError @abstractmethod def goal_distance(self, goal_state: dict, current_state: dict) -> Dict[str, Any]: """ Distance from the current goal to the target state. """ raise NotImplementedError def goal_types(self) -> Set[str]: """Returns the set of goal types supported by this goal generator""" return {"generic"} def goal_reachable(self, goal_state: dict, current_state: dict) -> bool: """ Return if target goal state is reachable from current state. """ return True def reset(self, random_state: RandomState) -> None: """ Reset state of the goal generator. Will be called when env is reset. """ self.reached_terminal_state = False
2,784
39.362319
98
py
robogym
robogym-master/robogym/robot/robot_interface.py
import abc from enum import Enum from typing import Any, Dict, Optional import attr import numpy as np class ControlMode(Enum): """ Control mode. Defines the action space of a particular robot. """ TCP_WRIST = "tcp+wrist" # TCP control with wrist rotation TCP_ROLL_YAW = "tcp+roll+yaw" # TCP control with roll and yaw rotation enabled. JOINT = "joint" # Joint control def is_tcp_controlled(self): return self in [ControlMode.TCP_WRIST, ControlMode.TCP_ROLL_YAW] class TcpSolverMode(Enum): """ Mode of actuation used. This does not have to match control_mode as long as there is a known transformation from one control mode to another actuation mode. """ MOCAP = "mocap" MOCAP_IK = "mocap_ik" @attr.s(auto_attribs=True) class RobotControlParameters: """ Robot control parameters – defined as parameters since max_position_change can be subject to ADR randomization """ MOCAP_DEFAULT_MAX_POSITION_CHANGE = 0.05 MOCAP_RESET_DEFAULT_MAX_POSITION_CHANGE = 0.1 JOINT_CONTROL_DEFAULT_MAX_POSITION_CHANGE = 2.4 # robot control mode. Supported modes are # joint: Joint position control # tcp: Tool center point control control_mode: ControlMode = attr.ib( default=ControlMode.TCP_ROLL_YAW, validator=attr.validators.in_(ControlMode), converter=ControlMode, ) # hard constraints on maximum position change per step on a given action dimension. # for joint control, it limits position change per joint # for TCP control, it is interpreted as a multiplier # on the commanded absolute tool position and rotation max_position_change: Optional[float] = None tcp_solver_mode: TcpSolverMode = attr.ib( default=TcpSolverMode.MOCAP_IK, validator=attr.validators.in_(TcpSolverMode), converter=TcpSolverMode, ) # subdirectory of the joint calibration path to load while making the arm xml arm_joint_calibration_path: str = attr.ib( default="cascaded_pi", validator=attr.validators.in_(["cascaded_pi", "pid"]) ) # when set, resets controller error on every action between main and controller simulations arm_reset_controller_error: bool = True # whether or not to use the force limiter use_force_limiter: bool = True # when set, enables regrasp logic for gripper enable_gripper_regrasp: bool = False def is_joint_actuated(self): return ( self.control_mode is ControlMode.JOINT or self.tcp_solver_mode is TcpSolverMode.MOCAP_IK ) def is_tcp_controlled(self): return self.control_mode.is_tcp_controlled() def requires_solver_sim(self): """ If a robot is joint actuated but TCP controlled, we need to build a solver simulation that will perform the conversion from the TCP action space to the joint actuation space. :return: """ return self.is_joint_actuated() and self.is_tcp_controlled() def get_controller_arm_solver_mode(self): """ For mocap_ik mode, we need to specify that the controller arm will be using mocap. For now, we dynamically make the correction here. :return: """ if self.tcp_solver_mode is TcpSolverMode.MOCAP_IK: return TcpSolverMode.MOCAP return self.tcp_solver_mode @staticmethod def default_max_pos_change_for_solver( *, control_mode: ControlMode, tcp_solver_mode: TcpSolverMode, arm_reset_controller_error: bool = True ) -> float: """ Returns a default max position change scaling that is appropriate for the selected control parameters. :return: A recommended value for max_pos_change """ if control_mode is ControlMode.JOINT: return ( RobotControlParameters.JOINT_CONTROL_DEFAULT_MAX_POSITION_CHANGE ) # per joint elif tcp_solver_mode is TcpSolverMode.MOCAP: return RobotControlParameters.MOCAP_DEFAULT_MAX_POSITION_CHANGE elif tcp_solver_mode is TcpSolverMode.MOCAP_IK: if arm_reset_controller_error: return RobotControlParameters.MOCAP_RESET_DEFAULT_MAX_POSITION_CHANGE else: return RobotControlParameters.MOCAP_DEFAULT_MAX_POSITION_CHANGE else: raise ValueError( "No default is defined for the given parameter combination." ) class RobotObservation(abc.ABC): """ Interface for the single observation of the shadow hand. Observation object owns and manages a set of data that constitutes an "observation", and exposes a number of methods to extract commonly used fields (like joint positions or actuator effort). All fields in a single observation object come as much as possible from a single moment in time (as much as the hardware allows, as different sensors may have different sampling rates). """ @abc.abstractmethod def joint_positions(self) -> np.ndarray: """ Return observed joint angles (in rad) :returns array of joint angles (one for each joint) """ pass @abc.abstractmethod def joint_velocities(self) -> np.ndarray: """ Return observed joint velocities (in rad/s) :returns array of joint velocities (one for each joint) """ pass @abc.abstractmethod def timestamp(self) -> float: """ Time in seconds since some unspecified event in the past. Useful for comparing time passed between observations. """ pass class Robot(abc.ABC): """ High level API for controlling a general robot. """ @classmethod @abc.abstractmethod def actuators(cls) -> np.ndarray: """ Return an array containing the names the actuators of the robot. """ pass @abc.abstractmethod def get_name(self) -> str: """Returns a name, expected to uniquely identify this robot within our environments. Examples would be: ALPHA, EPSILON, etc. for hands, and UR16e-ONE for UR16 arms.""" pass @abc.abstractmethod def actuator_ctrl_range_upper_bound(self) -> np.ndarray: """ Returns the upper bound of actuator control range in radians. """ pass @abc.abstractmethod def actuator_ctrl_range_lower_bound(self) -> np.ndarray: """ Returns the lower bound of actuator control range in radians. """ pass @classmethod @abc.abstractmethod def joint_positions_to_control(cls, joint_pos: np.ndarray) -> np.ndarray: """ Transform a position into a control input :param joint_pos: :return: control array """ pass @property def max_position_change(self): """ Maximum allowable position change per step :return: """ pass def actuation_range(self, relative_action: bool) -> np.ndarray: """ Returns the an array of actuation ranges per joint. By default, it returns the range defined by the upper and lower bounds of the control ranges. """ base_range = ( self.actuator_ctrl_range_upper_bound() - self.actuator_ctrl_range_lower_bound() ) / 2.0 if relative_action and self.max_position_change: return np.minimum(base_range, self.max_position_change) return base_range def is_position_control_valid(self, control: np.ndarray) -> bool: """ Check if position control vector is within (inclusive) supported ranges and of correct shape. """ return ( control.shape == self.actuator_ctrl_range_upper_bound().shape and np.all(control >= self.actuator_ctrl_range_lower_bound() - 1e-6) and np.all(control <= self.actuator_ctrl_range_upper_bound() + 1e-6) ) def get_current_position(self) -> np.ndarray: return self.observe().joint_positions() def denormalize_position_control( self, position_control: np.ndarray, relative_action: bool = False, ) -> np.ndarray: """ Transform position control from the [-1,+1] range into supported joint position range in radians, where 0 represents the midpoint between two extreme positions. :param position_control: The normalized position control from [-1,+1] range. :param relative_action: If true, map current joint position to center of the normalized position control which means hand will not move if position_control is zero. Otherwise map center of actuator control range to center of the normalized position control. """ if relative_action: joint_positions = self.get_current_position() actuation_center = self.joint_positions_to_control(joint_positions) else: actuation_center = ( self.actuator_ctrl_range_upper_bound() + self.actuator_ctrl_range_lower_bound() ) / 2.0 ctrl = actuation_center + position_control * self.actuation_range( relative_action ) return np.clip( ctrl, self.actuator_ctrl_range_lower_bound(), self.actuator_ctrl_range_upper_bound(), ) def zero_control(self) -> np.ndarray: """ Return an array representing a zero actuator control vector (in rad). Zero positions represent a flat, straightened out hand. """ return np.zeros(len(self.actuators()), dtype=np.float) def get_control_time_delta(self) -> float: """Returns the time slice the robot desires to be controlled under. This is indicative of the frequency that a robot wants to be controlled under. :return: The time slice the robot desires to be controlled under. """ return 0.0 ############################################################################################## # ROBOT INTERFACE ABSTRACT METHODS @abc.abstractmethod def set_position_control(self, control: np.ndarray) -> None: """ Set actuator position control vector. Each coordinate of this vector is the desired joint angle (or sum of joint angles for coupled joints). Internal robot controller then chooses the right force to achieve that position. Both control modes are mutually exclusive and turning on one turns off the other. :param control: 20-element array of actuator control (target joint angles in radians) """ pass @abc.abstractmethod def observe(self) -> RobotObservation: """ Return the "observation" object which contains all the most recent, contemporaneous observations of the state of the robotic hand. """ pass def on_observations_updated(self, new_observations: Dict[str, Any]) -> None: """Event to notify the robot that new observations have been collected. This should be expected to happen once at the start of the tick, so that all robots can synchronize their simulations accordingly, specially with respect to real observations. If required, robots could also cache these observations if they needed them during the tick, this preventing them from calling observe(), which might return (for real robots) a new observation mid-tick. :param new_observations: New observations collected. """ pass @classmethod def joints(cls) -> np.ndarray: """ Return the joint space of the robot. Defaults to the actuator space by default. """ return cls.actuators() def reset(self) -> None: """ Reset robot state. :return: """ pass
12,017
34.140351
118
py
robogym
robogym-master/robogym/robot/factories.py
from typing import Callable, Optional import numpy as np from robogym.robot.robot_interface import ControlMode, RobotControlParameters from robogym.robot.ur16e.mujoco.free_dof_tcp_arm import ( FreeDOFTcpArm, FreeRollYawTcpArm, FreeWristTcpArm, ) from robogym.robot.ur16e.mujoco.simulation.base import ArmSimulationInterface def build_tcp_controller( robot_control_params: RobotControlParameters, simulation: ArmSimulationInterface, initial_qpos: Optional[np.ndarray], autostep: bool = False, ) -> FreeDOFTcpArm: """ :param robot_control_params: :param simulation: Solver simulation. :param initial_qpos: Initial state for the solver robot. :param autostep: :return: """ assert robot_control_params.is_tcp_controlled() robot_cls: Optional[Callable[..., FreeDOFTcpArm]] = None if robot_control_params.control_mode is ControlMode.TCP_WRIST: robot_cls = FreeWristTcpArm elif robot_control_params.control_mode is ControlMode.TCP_ROLL_YAW: robot_cls = FreeRollYawTcpArm else: raise ValueError("Unknown control mode for TCP.") robot = robot_cls( simulation=simulation, initial_qpos=initial_qpos, robot_control_params=robot_control_params, autostep=autostep, ) assert isinstance(robot, FreeDOFTcpArm) return robot
1,361
28.608696
77
py
robogym
robogym-master/robogym/robot/control/tcp/mocap_solver.py
from typing import Optional import numpy as np from gym.envs.robotics import utils from robogym.mujoco.simulation_interface import SimulationInterface from robogym.robot.control.tcp.solver import PrincipalAxis, Solver from robogym.utils import rotation class MocapSolver(Solver): """ A TCP solver class that uses Mujoco's mocap weld to track and apply TCP control. """ JOINT_MAPPING = { PrincipalAxis.PITCH: 5, } def __init__( self, simulation: SimulationInterface, body_name: str, robot_prefix: str, quat_dof_dims: np.ndarray, alignment_axis: Optional[PrincipalAxis], ): super().__init__( simulation, body_name, robot_prefix, quat_dof_dims, alignment_axis ) def get_tcp_quat(self, ctrl: np.ndarray) -> np.ndarray: assert len(ctrl) == len( self.dof_dims ), f"Unexpected control dim {len(ctrl)}, should be {len(self.dof_dims)}" euler = np.zeros(3) euler[self.dof_dims_axes] = ctrl quat = rotation.euler2quat(euler) gripper_quat = self.mj_sim.data.get_body_xquat(self.body_name) if self.alignment_axis is not None: return ( self.align_axis( rotation.quat_mul(gripper_quat, quat), self.alignment_axis.value ) - gripper_quat ) return rotation.quat_mul(gripper_quat, quat) - gripper_quat def set_action(self, action: np.ndarray) -> None: utils.mocap_set_action(self.mj_sim, action) def reset(self): utils.reset_mocap_welds(self.mj_sim) utils.reset_mocap2body_xpos(self.mj_sim) @staticmethod def align_axis(cmd_quat, axis): """ Align quaternion into given axes """ alignment = np.zeros(3) alignment[axis] = 1 mtx = rotation.quat2mat(cmd_quat) # Axis that is the closest (by dotproduct) to alignment axis_nr = np.abs((alignment.T @ mtx)).argmax() # Axis of the cmd_quat axis = mtx[:, axis_nr] axis = axis * np.sign(axis @ alignment) difference_quat = rotation.vectors2quat(axis, alignment) return rotation.quat_mul(difference_quat, cmd_quat)
2,266
29.226667
84
py
robogym
robogym-master/robogym/robot/control/tcp/force_based_tcp_control_limiter.py
from typing import Tuple import numpy as np from robogym.robot.utils.logistic_functions import clipped_logistic_sigmoid LOGISTIC_ALPHA_PARAMETER = ( 0.81 # the 0.81 value for the sigmoid is a relatively slow transition ) MAXIMUM_TCP_FORCE_TORQUE = 40 # Newtons TRIGGER_FORCE_TORQUE_THRESHOLD = ( MAXIMUM_TCP_FORCE_TORQUE * 0.50 ) # % of max force to start scaling MINIMUM_SCALING_FACTOR = ( 0.0 # The minimum value -- between zero and one -- to scale the force by ) # Typical values for this are between 5% to 0.1% (0.05 to 0.001) OVER_MAX_REVERSE_SCALE = ( -0.1 ) # If the force is over MAXIMUM_TCP_FORCE_TORQUE, how much to reverse scale the force # Keep in mind this is a scale, so it will be multiplied by the current control, # not the current force. Something interesting to try could be to reverse scale by # the amount that the force is over the maximum (up to max_position_change) but this # is a bit more complicated to implement so we chose to keep things simple for now assert np.sign(OVER_MAX_REVERSE_SCALE) == -1 def get_element_wise_tcp_control_limits( tcp_force_and_torque_measured: np.ndarray, reverse_over_max: bool = True ) -> Tuple[np.ndarray, bool]: """ Takes the TCP force and uses a max_force threshold to scale the input values to limit them based on a logistic sigmoid. The limiting starts at TRIGGER_FORCE_TORQUE_THRESHOLD and goes to MINIMUM_SCALING_FACTOR at MAXIMUM_TCP_FORCE_TORQUE. We use MINIMUM_SCALING_FACTOR in order to prevent the output from getting the controls in a place where the robot cannot move out :param tcp_force_and_torque_measured: force measured on the arm's TCP as a 1x6 array (x, y, z, roll, pitch, yaw) :return: Tuple of 1. scales (1x6 nparray) - a scaling factor (0 to 1) for the control 1x6 np.ndarray (x, y, z, roll, pitch, yaw) 2. triggered (bool) - a bool which is true if any of the forces were above the trigger force """ force_and_torque_scales = np.ones_like(tcp_force_and_torque_measured) force_and_torque_over_threshold_mask = ( tcp_force_and_torque_measured > TRIGGER_FORCE_TORQUE_THRESHOLD ) # return a value ranging from 0 to 1 from the clipped logistic sigmoid # the 0.81 value for the sigmoid is a relatively slow transition exponential_scaler = clipped_logistic_sigmoid( ( np.maximum( ( MAXIMUM_TCP_FORCE_TORQUE - tcp_force_and_torque_measured[ force_and_torque_over_threshold_mask ] ), 0, ) / (MAXIMUM_TCP_FORCE_TORQUE - TRIGGER_FORCE_TORQUE_THRESHOLD) ), LOGISTIC_ALPHA_PARAMETER, ) # scale the 0 to 1 range to 0 to (1 - MINIMUM_SCALING_FACTOR) and # then shift up by MINIMUM_SCALING_FACTOR force_and_torque_scales[force_and_torque_over_threshold_mask] = ( exponential_scaler * (1.0 - MINIMUM_SCALING_FACTOR) + MINIMUM_SCALING_FACTOR ) # if enabled, reverse the controls by a scaling factor that is negative if reverse_over_max: force_and_torque_over_maximum_mask = ( tcp_force_and_torque_measured > MAXIMUM_TCP_FORCE_TORQUE ) force_and_torque_scales[ force_and_torque_over_maximum_mask ] = OVER_MAX_REVERSE_SCALE return force_and_torque_scales, any(force_and_torque_over_threshold_mask)
3,478
39.929412
122
py
robogym
robogym-master/robogym/robot/control/tcp/solver.py
import abc from enum import Enum from typing import Dict, Optional import numpy as np from robogym.mujoco.simulation_interface import SimulationInterface class PrincipalAxis(Enum): ROLL = 0 PITCH = 2 YAW = 1 class Solver(abc.ABC): """ TCP Solver Base. """ JOINT_MAPPING: Dict[PrincipalAxis, int] = {} def __init__( self, simulation: SimulationInterface, body_name: str, robot_prefix: str, quat_dof_dims: np.ndarray, alignment_axis: Optional[PrincipalAxis], ): """ :param simulation: Mujoco SimulationInterface :param quat_dof_dims: Quaternion dimensions that are beng controlled :param body_name: Body name that is controlled by TCP :param alignment_axis: Alignment axis to force align quaternion to. """ self.simulation = simulation self.body_name = body_name self.robot_prefix = robot_prefix self.dof_dims = quat_dof_dims self.dof_dims_axes = [axis.value for axis in quat_dof_dims] self.alignment_axis = alignment_axis @abc.abstractmethod def get_tcp_quat(self, quat_ctrl: np.ndarray) -> np.ndarray: """ Returns a relative TCP quaternion to be applied given quat control :param quat_ctrl: Relative quaternion control array :return: """ pass @abc.abstractmethod def set_action(self, action: np.ndarray) -> None: """ Sets 6-DOF TCP action via an underlying controller :param action: :return: """ pass def get_joint_mapping(self) -> np.ndarray: """ Map DOF dimensions to joints if we should restrict this DOF based on a joint range. :return: list of joint ids or None that correspond to dof_dims_axes. """ return np.array( [self.JOINT_MAPPING.get(dof_dimension) for dof_dimension in self.dof_dims] ) @abc.abstractmethod def reset(self) -> None: """ Reset TCP solver state. """ pass @property def mj_sim(self): """ MuJoCo MjSim simulation object """ return self.simulation.mj_sim
2,220
25.440476
91
py
robogym
robogym-master/robogym/robot/control/tcp/test/test_solver.py
import numpy as np import pytest from robogym.envs.rearrange.blocks import make_env from robogym.robot.robot_interface import ControlMode, TcpSolverMode from robogym.robot.ur16e.mujoco.free_dof_tcp_arm import FreeDOFTcpArm from robogym.utils import rotation def _build_env(control_mode, tcp_solver_mode): env = make_env( starting_seed=0, parameters=dict( robot_control_params=dict( control_mode=ControlMode(control_mode), tcp_solver_mode=tcp_solver_mode, ), n_random_initial_steps=0, ), ) env.reset() return env def _build_arm(control_mode, tcp_solver_mode): env = _build_env(control_mode=control_mode, tcp_solver_mode=tcp_solver_mode) return env.mujoco_simulation.robot.robots[0].controller_arm, env @pytest.mark.parametrize( "control_mode, tcp_solver_mode, expected_dims", [("tcp+wrist", "mocap", [5]), ("tcp+roll+yaw", "mocap", [None, 5])], ) def test_get_joint_mapping( control_mode: str, tcp_solver_mode: str, expected_dims: np.ndarray ): arm, _ = _build_arm(control_mode=control_mode, tcp_solver_mode=tcp_solver_mode) solver = arm.solver mapping = solver.get_joint_mapping() assert np.array_equal(mapping, expected_dims) def calculate_quat_adjustment_due_to_axis_alignment( from_quat: np.ndarray, aligned_axis_index: int ): """Compute what adjustment quat we would have to provide from the given quat, so that it is aligned with the axis defined by the alignment axis index. :param from_quat: Quaternion to align. :param aligned_axis_index: Index of the euler axis to align to. :return: Quaternion we would have to apply to the given quaternion so that it aligns with the given euler axis. """ # test vector is the alignment axis test_vector = np.zeros(3) test_vector[aligned_axis_index] = 1.0 # calculate the deviation with respect to the alignment axis current_vector = rotation.quat_rot_vec(from_quat, test_vector) dot_product = np.dot(current_vector, test_vector) # now, we would expect the code to rotate from current_vector to +-test_vector, with +-test_vector being # the closest one to current_vector. test_vector *= np.sign(dot_product) # expected rotation would be the angle_diff along the axis perpendicular to both vectors angle_diff = np.arccos(np.abs(dot_product)) axis_of_rotation = np.cross(current_vector, test_vector) adjustment = rotation.quat_from_angle_and_axis( angle=angle_diff, axis=axis_of_rotation ) return adjustment def do_test_solver_quat_response_vs_test_response( arm: FreeDOFTcpArm, desired_control: np.ndarray, tcp_solver_mode: TcpSolverMode ): """Helper function that tests (via assertions) that when we feed a certain control to a solver, we get the expected delta quaternion as response. :param arm: Arm. :param desired_control: Control to send to the solver. :param tcp_solver_mode: Tcp solver mode used to create the arm (so that we can understand expectations) :return: None. Asserts the conditions internally. """ # compute the control quat from the desired control euler_control = np.zeros(3) for control_idx, dimension in enumerate(arm.DOF_DIMS): euler_control[dimension.value] = desired_control[control_idx] quat_ctrl = rotation.euler2quat(euler_control) # - - - - - - - - - - - - - - - - - - - - # Ask the solver to compute the delta # - - - - - - - - - - - - - - - - - - - - solver_delta_quat = arm.solver.get_tcp_quat(desired_control) # - - - - - - - - - - - - - - - - - - - - # Compute expectations and compare # - - - - - - - - - - - - - - - - - - - - assert tcp_solver_mode is TcpSolverMode.MOCAP # compute the quaternion we would get with the control current_rot_quat = rotation.euler2quat(arm.observe().tcp_rot()) target_quaternion = rotation.quat_mul(current_rot_quat, quat_ctrl) # if we have an alignment axis, compute its adjustment due to alignment if arm.solver.alignment_axis is not None: adjustment = calculate_quat_adjustment_due_to_axis_alignment( from_quat=target_quaternion, aligned_axis_index=arm.solver.alignment_axis.value, ) # apply the adjustment to the target quaternion target_quaternion = rotation.quat_mul(adjustment, target_quaternion) # mocap reports a relative quaternion with respect to the current quaternion via subtraction. # Replicate that here. Note that we apply the adjustment to the target_quaternion, but then we return # relative with respect to the current quaternion (relative via subtraction) test_delta = target_quaternion - current_rot_quat # - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Assert expectation # - - - - - - - - - - - - - - - - - - - - - - - - - - - - # The expectation here is that applying the delta to the current rotation yields the same rotation in both # cases, unit-test vs tested code. Note however that we can't compare deltas directly because if the # original quaternions are equivalent, but not identical, the subtraction makes them non-comparable! # For example: # q1 - q != q2 - q, if q1 and q2 are equivalent but not identical # This happens for example for: # q1 = euler2quat( [-180, 0, 170.396] ) = [ 0.417 -0.832 0.327 0.164] # q2 = euler2quat( [ 180, 0, 170.396] ) = [ 0.417 0.832 -0.327 0.164] # which is exactly what we have in this unit-test for zero_control. # So we can't do just do 'assert test_delta == solver_delta_quat', we have to compare the resulting target quat # compute what the resulting rotation would be after we re-add the rotation to the delta expected_quat = current_rot_quat + test_delta obtained_quat = current_rot_quat + solver_delta_quat # calculate the rotational difference, which we expect to be 0 difference_quat = rotation.quat_difference(expected_quat, obtained_quat) difference_euler = rotation.quat2euler(difference_quat) assert np.allclose(np.zeros(3), difference_euler, atol=1e-5) @pytest.mark.parametrize( "control_mode, tcp_solver_mode", [("tcp+wrist", TcpSolverMode.MOCAP), ("tcp+roll+yaw", TcpSolverMode.MOCAP)], ) def test_zero_control(control_mode: str, tcp_solver_mode: TcpSolverMode): """ Test that when we apply zero control to an arm, we obtain the expected delta quaternion from the arm's solver. """ tcp_solver_mode_str = tcp_solver_mode.value arm, _ = _build_arm(control_mode=control_mode, tcp_solver_mode=tcp_solver_mode_str) zero_quat_ctrl = np.zeros_like(arm.DOF_DIMS, dtype=np.float32) do_test_solver_quat_response_vs_test_response( arm=arm, desired_control=zero_quat_ctrl, tcp_solver_mode=tcp_solver_mode ) @pytest.mark.parametrize( "control_mode, tcp_solver_mode", [("tcp+wrist", TcpSolverMode.MOCAP), ("tcp+roll+yaw", TcpSolverMode.MOCAP)], ) def test_wrist_rotations(control_mode: str, tcp_solver_mode: TcpSolverMode): """ Test that when we apply controls with rotations along the wrist dimension to an arm, we obtain the expected delta quaternion from the arm's solver. """ tcp_solver_mode_str = tcp_solver_mode.value arm, _ = _build_arm(control_mode=control_mode, tcp_solver_mode=tcp_solver_mode_str) # test several rotations (since the arm doesn't move we can actually test several transformations at once) test_rotations = [ np.deg2rad(30), np.deg2rad(60), np.deg2rad(90), np.deg2rad(160), np.deg2rad(180), ] for rot in test_rotations: # POSITIVE ROTATION desired_ctrl = np.zeros_like(arm.DOF_DIMS, dtype=np.float32) desired_ctrl[-1] = rot # wrist is the last dimension # check that the rotation meets expectations do_test_solver_quat_response_vs_test_response( arm=arm, desired_control=desired_ctrl, tcp_solver_mode=tcp_solver_mode ) # NEGATIVE ROTATION desired_ctrl_neg = np.zeros_like(arm.DOF_DIMS, dtype=np.float32) desired_ctrl_neg[-1] = -rot # wrist is the last dimension (opposite rotation) # check that the rotation meets expectations do_test_solver_quat_response_vs_test_response( arm=arm, desired_control=desired_ctrl_neg, tcp_solver_mode=tcp_solver_mode ) @pytest.mark.parametrize( "control_mode, tcp_solver_mode", [("tcp+roll+yaw", TcpSolverMode.MOCAP)] ) def test_quat_second_dof_rotation(control_mode: str, tcp_solver_mode: TcpSolverMode): """ Test that when we apply controls with rotations along the first dimension to an arm, we obtain the expected delta quaternion from the arm's solver. """ tcp_solver_mode_str = tcp_solver_mode.value arm, _ = _build_arm(control_mode=control_mode, tcp_solver_mode=tcp_solver_mode_str) # test several rotations (since the arm doesn't move we can actually test several transformations at once) test_rotations = [ np.deg2rad(30), np.deg2rad(60), np.deg2rad(90), np.deg2rad(160), np.deg2rad(180), ] for rot in test_rotations: # POSITIVE ROTATION desired_ctrl = np.zeros_like(arm.DOF_DIMS, dtype=np.float32) desired_ctrl[0] = rot # first dimension # check that the rotation meets expectations do_test_solver_quat_response_vs_test_response( arm=arm, desired_control=desired_ctrl, tcp_solver_mode=tcp_solver_mode ) # NEGATIVE ROTATION desired_ctrl_neg = np.zeros_like(arm.DOF_DIMS, dtype=np.float32) desired_ctrl_neg[0] = -rot # first dimension # check that the rotation meets expectations do_test_solver_quat_response_vs_test_response( arm=arm, desired_control=desired_ctrl_neg, tcp_solver_mode=tcp_solver_mode )
9,959
41.025316
117
py
robogym
robogym-master/robogym/robot/control/tcp/test/test_force_based_tcp_control_limiter.py
import numpy as np import pytest from robogym.robot.control.tcp.force_based_tcp_control_limiter import ( MAXIMUM_TCP_FORCE_TORQUE, MINIMUM_SCALING_FACTOR, OVER_MAX_REVERSE_SCALE, TRIGGER_FORCE_TORQUE_THRESHOLD, get_element_wise_tcp_control_limits, ) def compute_expected_trigger_state(): """ Use the values printed out by this function to adjust the values in test_get_joint_mapping(). """ forces = np.array([float(i) for i in range(100)]) scales = [] triggers = [] for force in forces: scale, trigger = get_element_wise_tcp_control_limits(np.ones(6) * force) scales.append(scale[0]) triggers.append(trigger) print( *[ f"\tForce: {forces[i]}\t Scale: {scales[i]}\t Triggered: {triggers[i]}\n" for i, _ in enumerate(forces) ] ) @pytest.mark.parametrize( "force_torque, expected_scales, expected_trigger_state", [ (np.ones(6) * TRIGGER_FORCE_TORQUE_THRESHOLD - 1.0, np.ones(6) * 1.0, False), (np.ones(6) * TRIGGER_FORCE_TORQUE_THRESHOLD, np.ones(6) * 1.0, False), ( np.ones(6) * TRIGGER_FORCE_TORQUE_THRESHOLD + 1.0, np.ones(6) * 0.9925695, True, ), (np.ones(6) * MAXIMUM_TCP_FORCE_TORQUE - 1.0, np.ones(6) * 0.00743045, True), ( np.ones(6) * MAXIMUM_TCP_FORCE_TORQUE, np.ones(6) * MINIMUM_SCALING_FACTOR, True, ), ( np.ones(6) * MAXIMUM_TCP_FORCE_TORQUE + 1.0, np.ones(6) * OVER_MAX_REVERSE_SCALE, True, ), ( np.ones(6) * MAXIMUM_TCP_FORCE_TORQUE * 2.0, np.ones(6) * OVER_MAX_REVERSE_SCALE, True, ), ( np.array([0.0, 0.0, 0.0, MAXIMUM_TCP_FORCE_TORQUE, 0.0, 0.0]), np.array([1.0, 1.0, 1.0, MINIMUM_SCALING_FACTOR, 1.0, 1.0]), True, ), ], ) def test_get_joint_mapping( force_torque: np.ndarray, expected_scales: np.ndarray, expected_trigger_state: bool ): scales, triggered = get_element_wise_tcp_control_limits(force_torque) assert np.allclose(scales, expected_scales) assert triggered == expected_trigger_state
2,249
30.25
97
py
robogym
robogym-master/robogym/robot/composite/composite_robot.py
import abc from typing import Any, Callable, Dict, Generic, List, Optional, Type, TypeVar, cast import numpy as np from robogym.mujoco.simulation_interface import SimulationInterface from robogym.robot.robot_interface import RobotControlParameters, RobotObservation from robogym.robot_env import Robot OType = TypeVar("OType", bound=RobotObservation) class CompositeRobot(Robot, Generic[OType], abc.ABC): """ A composite robot that implements the Robot interface. """ ROBOT_CLS: List[Type[Robot]] = [] def __init__( self, simulation: SimulationInterface, solver_simulation: Optional[SimulationInterface], robot_control_params: RobotControlParameters, robot_prefix="robot0:", autostep=False, ): """ :param simulation: simulation interface that supports all robots that belong to the class :param robot_control_params: Robot control parameters :param robot_prefix: prefix to add to the joint names while constructing the mujoco simulation :param autostep: when true, calls step() on the simulation whenever a control is set. this should only be used when the Robot is being controlled without a simulationrunner in the loop. """ robot_cls = cast(List[Callable[..., Robot]], self.ROBOT_CLS) self.robots = [ robot( simulation=simulation, solver_simulation=solver_simulation, robot_control_params=robot_control_params, robot_prefix=robot_prefix, autostep=False, ) for robot in robot_cls ] self.autostep = autostep self.simulation = simulation self.action_space_partition = [ len(robot.zero_control()) for robot in self.robots ] OBS_LABEL: List[str] = [] OBS_CLS: Optional[Type[OType]] = None def get_name(self) -> str: return "composite-robot" def zero_control(self) -> np.ndarray: return np.concatenate([robot.zero_control() for robot in self.robots]) @classmethod def actuators(cls) -> np.ndarray: return np.asarray([robot.actuators() for robot in cls.ROBOT_CLS]) @classmethod def joints(cls) -> np.ndarray: return np.asarray([robot.joints() for robot in cls.ROBOT_CLS]) def denormalize_position_control( self, position_control: np.ndarray, relative_action: bool = False, ) -> np.ndarray: offset = 0 denormalized_control = [] for i, robot in enumerate(self.robots): res = robot.denormalize_position_control( position_control=position_control[ offset: offset + self.action_space_partition[i] ], relative_action=relative_action, ) denormalized_control.append(res) offset += self.action_space_partition[i] return np.concatenate(denormalized_control) def actuator_ctrl_range_upper_bound(self) -> np.ndarray: return np.concatenate( [robot.actuator_ctrl_range_upper_bound() for robot in self.robots] ) def actuator_ctrl_range_lower_bound(self) -> np.ndarray: return np.concatenate( [robot.actuator_ctrl_range_lower_bound() for robot in self.robots] ) def set_position_control(self, control: np.ndarray) -> None: offset = 0 for i, robot in enumerate(self.robots): robot.set_position_control( control=control[offset: offset + self.action_space_partition[i]] ) offset += self.action_space_partition[i] if self.autostep: self.simulation.mj_sim.step() def observe(self) -> OType: obs_cls = cast(Callable[..., OType], self.OBS_CLS) return obs_cls( robot_obs={k: v.observe() for k, v in zip(self.OBS_LABEL, self.robots)} ) @classmethod def joint_positions_to_control(cls, joint_pos: np.ndarray): offset = 0 control = [] joint_space = [len(x) for x in cls.joints()] for i, robot in enumerate(cls.ROBOT_CLS): res = robot.joint_positions_to_control( joint_pos=joint_pos[offset: offset + joint_space[i]] ) control.append(res) offset += joint_space[i] return np.concatenate(control) @property def max_position_change(self): raise NotImplementedError def reset(self) -> None: for robot in self.robots: robot.reset() def on_observations_updated(self, new_observations: Dict[str, Any]) -> None: """Event to notify the robot that new observations have been collected. See parents for more detailed documentation. Overridden to pass the event to the child robots. :param new_observations: New observations collected. """ for robot in self.robots: robot.on_observations_updated(new_observations=new_observations)
5,065
33.69863
109
py
robogym
robogym-master/robogym/robot/composite/ur_gripper_arm.py
from copy import deepcopy from typing import Callable, Dict, Optional import numpy as np from robogym.mujoco.simulation_interface import SimulationInterface from robogym.robot.composite.composite_robot import CompositeRobot from robogym.robot.gripper.mujoco.mujoco_robotiq_gripper import MujocoRobotiqGripper from robogym.robot.robot_interface import ( Robot, RobotControlParameters, RobotObservation, TcpSolverMode, ) from robogym.robot.ur16e.mujoco.ideal_joint_controlled_tcp_arm import ( IdealJointControlledTcpArm, ) from robogym.robot.ur16e.mujoco.joint_controlled_arm import JointControlledArm from robogym.robot.ur16e.mujoco.joint_controlled_tcp_arm import JointControlledTcpArm from robogym.robot.ur16e.mujoco.simulation.base import ArmSimulationInterface class MujocoURGripperCompositeObservation(RobotObservation): def __init__(self, robot_obs: Dict[str, RobotObservation]): self.robot_obs = robot_obs def gripper_aperture(self) -> np.ndarray: """:return: Gripper's linear position of the fingers, like its actuator position.""" return self.robot_obs["gripper"].joint_positions() def joint_positions(self) -> np.ndarray: return self.robot_obs["arm"].joint_positions() def joint_velocities(self) -> np.ndarray: return self.robot_obs["arm"].joint_velocities() def tcp_xyz(self) -> np.ndarray: """ :return: Tooltip position in Cartesian coordinate space """ return self.robot_obs["arm"].tcp_xyz() # type: ignore def tcp_vel(self) -> np.ndarray: """ :return: Tooltip velocity in Cartesian coordinate space """ return self.robot_obs["arm"].tcp_vel() # type: ignore def tcp_rot(self) -> np.ndarray: """ :return: Tooltip velocity in Cartesian coordinate space """ return self.robot_obs["arm"].tcp_rot() # type: ignore def tcp_force(self) -> np.ndarray: """ :return: TCP force in world coordinates """ return self.robot_obs["arm"].tcp_force() # type: ignore def tcp_torque(self) -> np.ndarray: """ :return: TCP torque in world coordinates """ return self.robot_obs["arm"].tcp_torque() # type: ignore def is_in_safety_stop(self) -> bool: """ :return: True if the arm is in a safety stop, False otherwise. """ return self.robot_obs["arm"].is_in_safety_stop() # type: ignore def gripper_qpos(self) -> np.ndarray: """ :return: Gripper joint positions """ return self.robot_obs["gripper"].joint_positions() def gripper_vel(self) -> np.ndarray: """ :return: Gripper joint velocities """ return self.robot_obs["gripper"].joint_velocities() def gripper_controls(self) -> np.ndarray: """:return: Gripper's linear target position.""" return self.robot_obs["gripper"].joint_controls() # type: ignore def timestamp(self) -> float: return self.robot_obs["arm"].timestamp() class URGripperCompositeRobot(CompositeRobot): OBS_LABEL = ["arm", "gripper"] OBS_CLS = MujocoURGripperCompositeObservation class MujocoURTcpJointGripperCompositeRobot(URGripperCompositeRobot): ROBOT_CLS = [JointControlledTcpArm, MujocoRobotiqGripper] class MujocoURJointGripperCompositeRobot(URGripperCompositeRobot): ROBOT_CLS = [JointControlledArm, MujocoRobotiqGripper] class MujocoIdealURGripperCompositeRobot(URGripperCompositeRobot): ROBOT_CLS = [IdealJointControlledTcpArm, MujocoRobotiqGripper] def build_composite_robot( robot_control_params: RobotControlParameters, simulation: SimulationInterface ): robot_cls: Optional[Callable[..., Robot]] = None solver_simulation: Optional[SimulationInterface] = None if robot_control_params.requires_solver_sim(): solver_simulation = build_solver_sim( robot_control_params=robot_control_params, n_substeps=simulation.n_substeps, mujoco_timestep=simulation.mj_sim.model.opt.timestep, ) robot_cls = ( MujocoURTcpJointGripperCompositeRobot # JointActuated, TCPControlled ) elif robot_control_params.is_tcp_controlled(): solver_simulation = simulation robot_cls = MujocoIdealURGripperCompositeRobot # MocapActuated, TCPControlled elif robot_control_params.is_joint_actuated(): robot_cls = MujocoURJointGripperCompositeRobot # JointActuated, JointControlled else: raise ValueError( f"Unknown combination of robot_control_params to " f"build a composite robot: {robot_control_params}" ) assert robot_cls robot = robot_cls( simulation=simulation, robot_control_params=robot_control_params, solver_simulation=solver_simulation, ) assert isinstance(robot, Robot) return robot def build_solver_sim( robot_control_params: RobotControlParameters, n_substeps: int, mujoco_timestep: float, ) -> ArmSimulationInterface: solver_sim_params = deepcopy(robot_control_params) if solver_sim_params.tcp_solver_mode is TcpSolverMode.MOCAP_IK: solver_sim_params.tcp_solver_mode = TcpSolverMode.MOCAP return ArmSimulationInterface.build( robot_control_params=solver_sim_params, n_substeps=n_substeps, mujoco_timestep=mujoco_timestep, )
5,458
32.906832
92
py
robogym
robogym-master/robogym/robot/composite/controllers/ur_gripper_arm.py
import logging from enum import Enum from typing import Optional import numpy as np from robogym.robot.composite.ur_gripper_arm import URGripperCompositeRobot from robogym.robot.gripper.mujoco.mujoco_robotiq_gripper import MujocoRobotiqGripper from robogym.robot.ur16e.mujoco.free_dof_tcp_arm import FreeRollYawTcpArm from robogym.robot_env import RobotEnv class Direction(Enum): POS: int = 1 NEG: int = -1 class URGripperArmController: """ Controller to convert human interpretable action into relative action control. This controller assumes relative action control vector in [-1, 1] of [mocap_x, mocap_y, mocap_z, wrist_joint_angle, gripper_joint_angle] """ # The max speed. MAX_SPEED = 1.0 # The minimum speed. MIN_SPEED = 0.0 SPEED_CHANGE_PERCENT = 0.2 def __init__(self, env: RobotEnv): self._speeds = np.array([0.3, 0.5, 0.3]) assert isinstance(env.robot, URGripperCompositeRobot) self.env = env @property def robot(self): return self.env.robot @property def arm_speed(self): """ The speed that arm moves. """ return self._speeds[0] @property def wrist_speed(self): """ The speed that wrist rotates. """ return self._speeds[1] @property def gripper_speed(self): """ The speed that gripper opens/closes. """ return self._speeds[2] def zero_control(self): """ Returns zero control, meaning gripper shouldn't move by applying this action. """ return self.robot.zero_control() def speed_up(self): """ Increase gripper moving speed. """ self._speeds = np.minimum( self._speeds * (1 + self.SPEED_CHANGE_PERCENT), self.MAX_SPEED ) def speed_down(self): """ Decrease gripper moving speed. """ self._speeds = np.maximum( self._speeds * (1 - self.SPEED_CHANGE_PERCENT), self.MIN_SPEED ) def move_x(self, direction: Direction) -> np.ndarray: """ Move gripper along x axis. """ return self._move(0, direction) def move_y(self, direction: Direction) -> np.ndarray: """ Move gripper along y axis. """ return self._move(1, direction) def move_z(self, direction: Direction) -> np.ndarray: """ Move gripper along z axis. """ return self._move(2, direction) def _move(self, axis: int, direction: Direction): """ Move gripper along given axis and direction. """ ctrl = self.zero_control() ctrl[axis] = self.arm_speed * direction.value return ctrl def move_gripper(self, direction: Direction): """ Open/close gripper. """ ctrl = self.zero_control() ctrl[-1] = self.gripper_speed * direction.value return ctrl def tilt_gripper(self, direction: Direction) -> np.ndarray: """ Tilt the gripper """ ctrl = self.zero_control() if not isinstance(self.robot.robots[0].controller_arm, FreeRollYawTcpArm): logging.warning( "This robot doesn't support tilting gripper, skip this action." ) return ctrl ctrl[-3] = self.arm_speed * direction.value return ctrl def rotate_wrist(self, direction: Direction) -> np.ndarray: """ Rotate the wrist joint. """ ctrl = self.zero_control() ctrl[-2] = self.wrist_speed * direction.value return ctrl def get_gripper_actuator_force(self) -> Optional[float]: """ Get actuator force for the gripper. """ gripper = self.robot.robots[1] if isinstance(gripper, MujocoRobotiqGripper): return gripper.simulation.mj_sim.data.actuator_force[gripper.actuator_id] else: return None def get_gripper_regrasp_status(self) -> Optional[bool]: """Returns True if re-grasp feature is ON for the gripper, False if it's OFF, and None if the gripper does not report the status of the re-grasp feature, or it does not have that feature. :return: True if re-grasp feature is ON for the gripper, False if it's OFF, and None if the gripper does not report the status of the re-grasp feature, or it does not have that feature. """ status: Optional[bool] gripper = self.robot.robots[1] if not hasattr(gripper, "regrasp_enabled"): return None elif gripper.regrasp_enabled: is_currently_regrasping = gripper.regrasp_helper.regrasp_command is not None status = is_currently_regrasping else: status = None return status
4,885
27.08046
114
py
robogym
robogym-master/robogym/robot/composite/controllers/test/test_controller.py
from robogym.envs.rearrange.blocks import make_env from robogym.robot.composite.controllers.ur_gripper_arm import URGripperArmController def test_sim_controller_status(): env = make_env() controller = URGripperArmController(env) assert controller.get_gripper_regrasp_status() is None def test_sim_controller_with_regrasp(): env = make_env( parameters=dict(robot_control_params=dict(enable_gripper_regrasp=True,)) ) controller = URGripperArmController(env) assert controller.get_gripper_regrasp_status() is False
552
31.529412
85
py
robogym
robogym-master/robogym/robot/gripper/mujoco/mujoco_robotiq_gripper.py
import numpy as np from robogym.mujoco.simulation_interface import SimulationInterface from robogym.robot.gripper.mujoco.regrasp_helper import RegraspHelper from robogym.robot.robot_interface import ( Robot, RobotControlParameters, RobotObservation, ) class MujocoObservation(RobotObservation): """ UR Arm observation coming from the MuJoCo simulation """ def __init__( self, simulation: SimulationInterface, joint_group: str, actuator_id: int, ): self._time = simulation.mj_sim.data.time sim = simulation.mj_sim self._joint_positions = simulation.get_qpos(joint_group).copy() self._joint_controls = sim.data.ctrl[actuator_id: actuator_id + 1].copy() self._joint_vel = simulation.get_qvel(joint_group).copy() def joint_positions(self) -> np.ndarray: return self._joint_positions def joint_controls(self) -> np.ndarray: return self._joint_controls def joint_velocities(self) -> np.ndarray: return self._joint_vel def timestamp(self) -> float: return self._time class MujocoRobotiqGripper(Robot): """ Mujoco implementation of a 1-DOF RobotIQ 2f-85 gripper. """ ACTUATORS = ["A_J1"] JOINTS = ["r_gripper_RJ0_outer"] def __init__( self, simulation: SimulationInterface, robot_control_params: RobotControlParameters, robot_prefix="robot0:", autostep=False, **kwargs ): """ :param simulation: simulation interface for the mujoco shadow hand xml :param hand_prefix: prefix to add to the joint names while constructing the mujoco simulation :param autostep: when true, calls step() on the simulation whenever a control is set. this should only be used only when the Robot is being controlled without a simulationrunner in the loop. """ self.simulation = simulation self.robot_prefix = robot_prefix self.autostep = autostep self.joint_group = robot_prefix + "gripper_joint_angles" self.simulation.register_joint_group( self.joint_group, prefix=[robot_prefix + "r_gripper_RJ0_outer"] ) # assert max_position_change > 0.0, f"Position multiplier must be a positive number" # For now, we do not constrain gripper motion. self._max_position_change = None self.actuator_id = self.mj_sim.model.actuator_name2id( robot_prefix + "r_gripper_finger_joint" ) # set a consistent initial control to prevent drifting at the start of the simulation # otherwise the robot will try to go to the last control set, which may not be the same as the position) # Since qpos is not set directly for gripper, simply set the ctrl to whatever position we have now self.mj_sim.data.ctrl[self.actuator_id] = simulation.get_qpos( self.joint_group ).copy() self.regrasp_helper = None if robot_control_params.enable_gripper_regrasp: self.regrasp_helper = RegraspHelper( initial_position=self.observe().joint_positions() ) def get_control_time_delta(self) -> float: """Returns the delta that the robot wants to be controlled under, by matching it with its mujoco simulation step delta. :return: Returns the delta that the robot wants to be controlled under, by matching it with its mujoco simulation step delta. """ dt = self.mj_sim.nsubsteps * self.mj_sim.model.opt.timestep return dt def get_name(self) -> str: return "robotiq-2f-85" @property def max_position_change(self): return self._max_position_change @classmethod def actuators(cls) -> np.ndarray: return np.asarray(cls.ACTUATORS) @classmethod def joints(cls) -> np.ndarray: return np.asarray(cls.JOINTS) def actuator_ctrl_range_upper_bound(self) -> np.ndarray: # We use control range in xml instead of constants to take into account # ADR randomization for joint limit. return np.asarray([self.mj_sim.model.actuator_ctrlrange[self.actuator_id, 1]]) def actuator_ctrl_range_lower_bound(self) -> np.ndarray: # We use control range in xml instead of constants to take into account # ADR randomization for joint limit. return np.asarray([self.mj_sim.model.actuator_ctrlrange[self.actuator_id, 0]]) @classmethod def joint_positions_to_control(cls, joint_pos: np.ndarray) -> np.ndarray: # Only one joint is actuated among the six return joint_pos @property def mj_sim(self): """ MuJoCo MjSim simulation object """ return self.simulation.mj_sim @property def regrasp_enabled(self): return self.regrasp_helper is not None def get_current_position(self): return self.mj_sim.data.ctrl[self.actuator_id] def denormalize_position_control( self, position_control: np.ndarray, relative_action: bool = False, ) -> np.ndarray: """ Transform position control from the [-1,+1] range into supported joint position range in radians, where 0 represents the midpoint between two extreme positions. NOTE: Overriden in MujocoRobotiqGripper to add re-grasping capabilities. Re-grasping means that when the gripper detects backdrive due to neutral commands, it will try itself to re-issue a previous command that is deemed as more desirable than the backdrive result. :param position_control: The normalized position control from [-1,+1] range. :param relative_action: If true, map current joint position to center of the normalized position control which means hand will not move if position_control is zero. Otherwise map center of actuator control range to center of the normalized position control. """ default_control = super().denormalize_position_control( position_control=position_control, relative_action=relative_action ) # absolute control does not need re-grasp if not relative_action or not self.regrasp_enabled: return default_control assert self.regrasp_helper return self.regrasp_helper.compute_regrasp_control( position_control=position_control, default_control=default_control, current_position=self.observe().joint_positions(), ) def sync_to(self, joint_positions: np.ndarray, joint_controls: np.ndarray) -> None: """Update this gripper to the given position and control. Update from values rather than observations so that we can sync from any observation providers. :param joint_positions: Gripper position (currently an array of 1 float linear displacement.) :param joint_controls: Gripper control target (currently an array of 1 float linear displacement). Useful if this gripper is not controlled during the step. """ self.simulation.set_qpos(self.joint_group, joint_positions) self.set_position_control(joint_controls) def set_position_control(self, control: np.ndarray) -> None: self.mj_sim.data.ctrl[self.actuator_id] = control[0] if self.autostep: self.mj_sim.step() def observe(self) -> MujocoObservation: return MujocoObservation(self.simulation, self.joint_group, self.actuator_id)
7,536
38.051813
121
py
robogym
robogym-master/robogym/robot/gripper/mujoco/regrasp_helper.py
from typing import List, Optional import numpy as np class RegraspHelper: """ A helper that attempts to facilitate persistent object grasping by a gripper. When the helper detects backdrive due to neutral commands preceded by a close command on the gripper, it will re-issue the previous command that is deemed as more desirable than the backdrive result to prevent objects slipping due to incomplete grasping control. """ def __init__(self, initial_position: np.ndarray): self.regrasp_command = None # current command that we issue so that we re-grasp self.prev_obs_position = ( initial_position # previous joint observation (=current val) ) self.last_nonzero_cmd_direction = None # last user desired trajectory self.last_nonzero_obs_direction = None # last actual trajectory self.prev_action = None # last command self.second_prev_action = None # second to last command self.debug_regrasp = ( False # set this to True to print debug information for re-grasping ) if self.debug_regrasp: self.debug_desired_action_history: List[float] = [] self.debug_desired_action_dir_history: List[str] = [] self.debug_observed_pos_history: List[float] = [] self.debug_observed_pos_dir_history: List[str] = [] self.debug_returned_ctrl_history: List[np.ndarray] = [] @staticmethod def debug_dir_to_string(direction: Optional[float]): """For debugging only, given a float representing a direction, return a human friendly string. :param direction: Positive for Closing, Negative for Opening and zero for Keeping. None is also accepted. :return: String representation of the float interpreted as a direction. """ if direction is None: return "None" elif direction == 0: return "Keep" elif direction > 0: return "Close" elif direction < 0: return "Open" @staticmethod def debug_add_to_history( history: List, item: object, max_history: float = 20 ) -> None: """For debugging only. Adds the given item to the given list, and removes the first object if the list length becomes bigger than the max history limit. This method will pop at most one item, so it expects max history limit to be constant. :param history: List to add the item. :param item: Item to add. :param max_history: Limit for the list. This method will pop one item if the list exceeds this limit after adding the item. """ history.append(item) if len(history) > max_history: history.pop(0) def debug_print_regrasp_history(self) -> None: """Pretty print the history of debug variables that help debug regrasp.""" print("- - - - -") print( f"DesCmdHist : {['{0:0.5f}'.format(i) for i in self.debug_desired_action_history]}" ) print(f"DesCmdDirHist: {self.debug_desired_action_dir_history}") print( f"ObsPosHist : {['{0:0.5f}'.format(i) for i in self.debug_observed_pos_history]}" ) print(f"ObsPosDirHist: {self.debug_observed_pos_dir_history}") print( f"PrevReturns : {['{0:0.5f}'.format(i) for i in self.debug_returned_ctrl_history]}" ) def compute_regrasp_control( self, position_control: np.ndarray, default_control: np.ndarray, current_position: np.ndarray, ) -> np.ndarray: """ Computes control override if applicable given the current state of gripper and controls :param position_control: Applied absolute position control :param default_control: Computed default denormalized control that would apply without re-grasp correction :param current_position: Current gripper joint position reading :return: re-grasp corrected control """ # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # 1) Compute variables that will help us make the re-grasp decision # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # note some of these variables are not used, but its code is reflected for completeness purposes # current position delta assert self.prev_obs_position is not None obs_move = current_position - self.prev_obs_position obs_direction = ( 0.0 if np.allclose(obs_move, 0, atol=1e-5) else np.sign(obs_move) ) # what does the user want to do now? user_wants_to_open = position_control < 0.0 user_wants_to_close = position_control > 0.0 user_wants_to_keep = position_control == 0.0 # what did the user want to do last # user_last_trajectory_was_opening = self.last_nonzero_cmd_direction and self.last_nonzero_cmd_direction < 0.0 user_last_trajectory_was_closing = ( self.last_nonzero_cmd_direction and self.last_nonzero_cmd_direction > 0.0 ) # what is the gripper doing now? (note this is influenced by the previous command, not the desired command) gripper_is_opening = obs_direction < 0.0 # gripper_is_closing = obs_direction > 0.0 # gripper_is_still = obs_direction == 0.0 # what was the gripper last trajectory # gripper_was_opening_or_still = self.last_nonzero_obs_direction and self.last_nonzero_obs_direction < 0.0 gripper_was_closing_or_still = ( self.last_nonzero_obs_direction and self.last_nonzero_obs_direction > 0.0 ) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # 2) If we are currently regrasping, we have special handling to do first # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - is_regrasping = self.regrasp_command is not None if is_regrasping: if user_wants_to_open: # stop re-grasping self.regrasp_command = None elif user_wants_to_close: # if the user wants to close, let the code continue down. The default behavior for the algorithm # will compute the user desired control, and compare it to the regrasp, actually enacting the # user one if re-grasping would have been a worse command (in terms of closing the gripper) pass else: # directly continue re-issuing the same command we decided when we started re-grasping return self.regrasp_command # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # 3) This is where we decide if we should re-grasp # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # we want to regrasp if all of these are true: # 1) the user wants to close or keep the position # 2) the last thing the user wanted to do was closing the gripper (not opening). Being still is ignored here * # 3) the gripper was indeed closing or staying still after closing # 4) the gripper is now opening # Since it was closing, and now opening, and the user wants to close or keep closed, and the gripper did already # try to close, the fact that everything says that it should be closing, but it is actually opening, hints # at an external force trying to open it, and we asumme here that is backdrive. # # * note on (2). The reason why this matters is because if the user wanted to open, we would expect the gripper # to open some time after that user command (typically 1-n ticks later depending on current momementum.) Just # because the user wants to close now we can't expect the gripper to close. In order to expect the gripper # to close or keep closed, we must require that the last intention was to close from a more open position. user_wants_to_close_or_keep = user_wants_to_close or user_wants_to_keep user_expects_close_or_keep = ( user_wants_to_close_or_keep and user_last_trajectory_was_closing ) if ( user_expects_close_or_keep and gripper_was_closing_or_still and gripper_is_opening ): # This is the command that we will issue as part of the regrasp. Note that instead we could calculate # force applied on the object. In this case, what we do is re-issue the last command that led to # a positive move / closing the gripper. Since the last command led to opening now, we must use at # least the second to last, which given our algorithm that requires past trajectories, we can guarantee # that it exists by now. assert self.second_prev_action is not None self.regrasp_command = self.second_prev_action # now print debug information so that we know that we are regrasping (if debug is required) if self.debug_regrasp: print( f"user wants to : {self.debug_dir_to_string(position_control[0])}" ) print(f"gripper is : {self.debug_dir_to_string(obs_direction)}") self.debug_print_regrasp_history() print("This is an undesired opening!! Enabling re-grasp:") print( f"We would like to keep {self.prev_obs_position}, and will reissue {self.regrasp_command} for it" ) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # 4) Compare re-grasping command to what the user wants to do # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # if we have a re-grasp command, we will keep it if it's better than the user one if self.regrasp_command is None: returned_control = default_control else: # check if the user command is better, and if so update regrasp to the new command user_is_better = default_control[0] > self.regrasp_command[0] if user_is_better: if self.debug_regrasp: print( f"The user command {default_control} is better than {self.regrasp_command}, will update it." ) self.regrasp_command = default_control returned_control = self.regrasp_command # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # 5) Update cached values to help next frame make the re-grasp decision # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - command_direction = ( None if np.allclose(position_control, 0, atol=1e-5) else np.sign(position_control) ) # user trajectory if command_direction != 0.0: self.last_nonzero_cmd_direction = command_direction # observations and observation trajectory self.prev_obs_position = current_position if obs_direction != 0.0: self.last_nonzero_obs_direction = obs_direction # actual actions that are returned self.second_prev_action = self.prev_action self.prev_action = returned_control # update history only if we are debugging if self.debug_regrasp: self.debug_add_to_history( self.debug_desired_action_history, position_control[0] ) self.debug_add_to_history( self.debug_desired_action_dir_history, self.debug_dir_to_string(command_direction), ) self.debug_add_to_history( self.debug_observed_pos_history, current_position[0] ) self.debug_add_to_history( self.debug_observed_pos_dir_history, self.debug_dir_to_string(obs_direction), ) self.debug_add_to_history( self.debug_returned_ctrl_history, returned_control[0] ) return returned_control
12,319
47.125
120
py
robogym
robogym-master/robogym/robot/shadow_hand/hand_utils.py
from typing import Optional import numpy as np from robogym.robot.shadow_hand.hand_interface import ( ACTUATOR_CTRLRANGE, ACTUATOR_GROUPS, ACTUATORS, ) def denormalize_by_limit(interpolation, limits): """ Scale numbers between -1 and 1 into the given limits, keeping 0 point fixed """ final_values = limits[:, 1] * interpolation final_values[interpolation < 0] = (limits[:, 0] * np.abs(interpolation))[ interpolation < 0 ] return final_values def normalize_by_limits(values, limits): """ Scale values from the range of supplied limits into the [-1, 1] range, keeping 0 point fixed """ final_values = values / limits[:, 1] final_values[values < 0] = (np.abs(values) / limits[:, 0])[values < 0] return final_values def separate_group_control( control: np.ndarray, group_name: Optional[str] ) -> np.ndarray: """ Transforms specified control vector by separating given actuator group on a way to minimize probability of hand elements colliding when moving actuators within that group """ assert control is not None assert (group_name in ACTUATOR_GROUPS) or (group_name is None) # We don't have to do anything to separate a wrist if group_name is None or group_name == "WR": return control limit_id = 0 for finger in ["LF", "RF", "MF", "FF"]: actuator_name = f"A_{finger}J3" actuator_id = ACTUATORS.index(actuator_name) if finger == group_name: limit_id = 1 else: control[actuator_id] = ACTUATOR_CTRLRANGE[actuator_name][limit_id] return control
1,637
27.736842
87
py
robogym
robogym-master/robogym/robot/shadow_hand/hand_forward_kinematics.py
import numpy as np from robogym.mujoco.forward_kinematics import ForwardKinematics from robogym.mujoco.mujoco_xml import MujocoXML from robogym.robot.shadow_hand import hand_interface FINGERTIP_SITE_NAMES = [ "S_fftip", "S_mftip", "S_rftip", "S_lftip", "S_thtip", ] REFERENCE_SITE_NAMES = [ "phasespace_ref0", "phasespace_ref1", "phasespace_ref2", ] HAND_KINEMATICS = ForwardKinematics.prepare( MujocoXML.parse("robot/shadowhand/main.xml"), "hand_mount", [1.0, 1.25, 0.15], [np.pi / 2, 0, np.pi], REFERENCE_SITE_NAMES + FINGERTIP_SITE_NAMES, hand_interface.JOINTS, ) ZERO_JOINT_POSITIONS = HAND_KINEMATICS.compute(np.zeros(len(hand_interface.JOINTS))) REFERENCE_POSITIONS = ZERO_JOINT_POSITIONS[:3] def hand_forward_kinematics(qpos, return_joint_pos=False): """ Calculate forward kinematics of the hand """ return HAND_KINEMATICS.compute(qpos, return_joint_pos)[3:] def get_relative_positions(fingertips_xpos, reference_xpos=REFERENCE_POSITIONS): """ Return positions relative to the reference points """ fingertips_xpos = fingertips_xpos.copy() reference_xpos = reference_xpos.copy() fingertips_xpos -= reference_xpos[1] reference_xpos -= reference_xpos[1] # This point makes other two orthogonal. for idx in [0, 2]: reference_xpos[idx] /= np.sqrt(np.sum(np.square(reference_xpos[idx]))) ort = np.cross(reference_xpos[0], reference_xpos[2]) m = np.transpose(np.array([reference_xpos[0], ort, reference_xpos[2]])) return np.matmul(fingertips_xpos, m) def compute_forward_kinematics_fingertips( joint_positions, reference_xpos=REFERENCE_POSITIONS, return_joint_pos=False ) -> np.ndarray: """ Compute fingertip positions using forward kinematics from joint angles. :returns 5x3-element array of current fingertip positions (5 fingertips in 3D) """ fingertip_absolute_positions = hand_forward_kinematics( joint_positions, return_joint_pos=return_joint_pos ) return get_relative_positions( fingertip_absolute_positions, reference_xpos=reference_xpos )
2,123
30.235294
84
py
robogym
robogym-master/robogym/robot/shadow_hand/hand_interface.py
import abc from typing import Dict, Iterable, List, Optional, Set import numpy as np from robogym.robot.lib.parameter_configurer import ParameterConfigurer from robogym.robot.robot_interface import Robot, RobotObservation ACTUATORS = [ "A_WRJ1", # actuator_id 00, horizontal wrist movement "A_WRJ0", # actuator_id 01, vertical wrist movement "A_FFJ3", # actuator_id 02, horizontal finger movement "A_FFJ2", # actuator_id 03, vertical finger movement "A_FFJ1", # actuator_id 04, vertical finger movement, bending coupled joints "A_MFJ3", # actuator_id 05, horizontal finger movement "A_MFJ2", # actuator_id 06, vertical finger movement "A_MFJ1", # actuator_id 07, vertical finger movement, bending coupled joints "A_RFJ3", # actuator_id 08, horizontal finger movement "A_RFJ2", # actuator_id 09, vertical finger movement "A_RFJ1", # actuator_id 10, vertical finger movement, bending coupled joints "A_LFJ4", # actuator_id 11, vertical finger movement toward the center of the palm "A_LFJ3", # actuator_id 12, horizontal finger movement "A_LFJ2", # actuator_id 13, vertical finger movement "A_LFJ1", # actuator_id 14, vertical finger movement, bending coupled joints "A_THJ4", # actuator_id 15, rotational movement of the thumb "A_THJ3", # actuator_id 16, bending thumb "A_THJ2", # actuator_id 17, bending thumb "A_THJ1", # actuator_id 18, bending thumb "A_THJ0", # actuator_id 19, bending thumb ] """ Each actuator is a motor inside of a robotic hand pulling on two tendons - one on one side and one on the other. """ FINGERS: List[str] = [ "FF", # first finger "MF", # middle finger "RF", # ring finger "LF", # little finger "TH", # thumb ] """ Names of fingers of the hand. Order of fingers on this list MUST NOT change, because it is used for indexing and identifiers. """ ACTUATOR_GROUPS: Dict[str, List[str]] = { "WR": ["A_WRJ1", "A_WRJ0"], "FF": ["A_FFJ3", "A_FFJ2", "A_FFJ1"], "MF": ["A_MFJ3", "A_MFJ2", "A_MFJ1"], "RF": ["A_RFJ3", "A_RFJ2", "A_RFJ1"], "LF": ["A_LFJ4", "A_LFJ3", "A_LFJ2", "A_LFJ1"], "TH": ["A_THJ4", "A_THJ3", "A_THJ2", "A_THJ1", "A_THJ0"], } """ Actuators grouped by their belonging to the same physical part. """ def actuator2group(actuator: str) -> str: """ Return name of the group actuator belongs to. :param actuator: name of the actuator :return: name of the group """ assert actuator in ACTUATORS, f"{actuator} is not a valid actuator name" return actuator[-4:-2] def joint2group(joint: str) -> str: """ Return name of the group joint belongs to. :param joint: name of the joint :return: name of the group """ assert joint in JOINTS, f"{joint} is not a valid joint name" return joint[-4:-2] def filter_actuator_groups(actuators: Optional[Iterable[str]]) -> Dict[str, List[str]]: """ Return new actuator groups that contains only provided actuators. Actuator group is filtered out if and only if there is no actuator from the provided collection of actuators belonging to the actuator group. Actuators of remaining actuator groups are filtered out as well to include only specified actuators. :param actuators: actuators to include; each actuator is a string exactly matching actuator name from shadow_hand.ACTUATORS :return: list of new filtered recording groups """ actuators = set(actuators) if actuators else set() filtered_actuator_groups = {} for group_name, group_actuators in ACTUATOR_GROUPS.items(): if not actuators: filtered_actuator_groups[group_name] = group_actuators.copy() elif not set(group_actuators).isdisjoint(actuators): filtered_actuator_groups[group_name] = [ actuator for actuator in group_actuators if actuator in actuators ] return filtered_actuator_groups JOINTS = [ "WRJ1", # joint_id 00, actuator_id 00 "WRJ0", # joint_id 01, actuator_id 01 "FFJ3", # joint_id 02, actuator_id 02 "FFJ2", # joint_id 03, actuator_id 03 "FFJ1", # joint_id 04, actuator_id 04, tendon "FFT1", coupled joint "FFJ0", # joint_id 05, actuator_id 04, tendon "FFT1", coupled joint "MFJ3", # joint_id 06, actuator_id 05 "MFJ2", # joint_id 07, actuator_id 06 "MFJ1", # joint_id 08, actuator_id 07, tendon "MFT1", coupled joint "MFJ0", # joint_id 09, actuator_id 07, tendon "MFT1", coupled joint "RFJ3", # joint_id 10, actuator_id 08 "RFJ2", # joint_id 11, actuator_id 09 "RFJ1", # joint_id 12, actuator_id 10, tendon "RFT1", coupled joint "RFJ0", # joint_id 13, actuator_id 10, tendon "RFT1", coupled joint "LFJ4", # joint_id 14, actuator_id 11 "LFJ3", # joint_id 15, actuator_id 12 "LFJ2", # joint_id 16, actuator_id 13 "LFJ1", # joint_id 17, actuator_id 14, tendon "LFT1", coupled joint "LFJ0", # joint_id 18, actuator_id 14, tendon "LFT1", coupled joint "THJ4", # joint_id 19, actuator_id 15 "THJ3", # joint_id 20, actuator_id 16 "THJ2", # joint_id 21, actuator_id 17 "THJ1", # joint_id 22, actuator_id 18 "THJ0", # joint_id 23, actuator_id 19 ] """ Robotic hand joints are mechanical "hinge" joints that represent degrees of freedom of the robot. Acronyms used: WR - Wrist FF - First Finger MF - Middle Finger RF - Ring Finger LF - Little Finger TH - Thumb Joints are numbered from fingertip to the palm - e.g. FFJ0 is the first knuckle, FFJ1 is the second knuckle etc. First two joints of each of the main fingers are coupled - which means there is only one actuator controlling them by a single tendon. """ ACTUATOR_CTRLRANGE = { "A_WRJ1": [-0.4887, 0.1396], # DEGREES (-28, 8) "A_WRJ0": [-0.6981, 0.4887], # DEGREES (-40, 28) "A_FFJ3": [-0.3491, 0.3491], # DEGREES (-20, 20) "A_FFJ2": [0.0, 1.5708], # DEGREES (0, 90) "A_FFJ1": [0.0, 3.1416], # DEGREES (0, 180) "A_MFJ3": [-0.3491, 0.3491], # DEGREES (-20, 20) "A_MFJ2": [0.0, 1.5708], # DEGREES (0, 90) "A_MFJ1": [0.0, 3.1416], # DEGREES (0, 180) "A_RFJ3": [-0.3491, 0.3491], # DEGREES (-20, 20) "A_RFJ2": [0.0, 1.5708], # DEGREES (0, 90) "A_RFJ1": [0.0, 3.1416], # DEGREES (0, 180) "A_LFJ4": [0.0, 0.7854], # DEGREES (0, 45) "A_LFJ3": [-0.3491, 0.3491], # DEGREES (-20, 20) "A_LFJ2": [0.0, 1.5708], # DEGREES (0, 90) "A_LFJ1": [0.0, 3.1416], # DEGREES (0, 180) "A_THJ4": [-1.0472, 1.0472], # DEGREES (-60, 60) "A_THJ3": [0.0, 1.2217], # DEGREES (0, 70) "A_THJ2": [-0.2094, 0.2094], # DEGREES (-12, 12) "A_THJ1": [-0.5236, 0.5236], # DEGREES (-30, 30) "A_THJ0": [-1.5708, 0.0], # DEGREES (-90, 0) } """ Ranges, in radians, of what robotic joints can safely reach """ ACTUATOR_CTRLRANGE_LOWER_BOUND = np.array( [ACTUATOR_CTRLRANGE[key][0] for key in ACTUATORS] ) """ Actuator position controls vector for the lower bound of actuator control range. """ ACTUATOR_CTRLRANGE_UPPER_BOUND = np.array( [ACTUATOR_CTRLRANGE[key][1] for key in ACTUATORS] ) """ Actuator position controls vector for the upper bound of actuator control range. """ ACTUATOR_JOINT_MAPPING: Dict[str, List[str]] = { "A_WRJ1": ["WRJ1"], "A_WRJ0": ["WRJ0"], "A_FFJ3": ["FFJ3"], "A_FFJ2": ["FFJ2"], "A_FFJ1": ["FFJ1", "FFJ0"], # Coupled joints "A_MFJ3": ["MFJ3"], "A_MFJ2": ["MFJ2"], "A_MFJ1": ["MFJ1", "MFJ0"], # Coupled joints "A_RFJ3": ["RFJ3"], "A_RFJ2": ["RFJ2"], "A_RFJ1": ["RFJ1", "RFJ0"], # Coupled joints "A_LFJ4": ["LFJ4"], "A_LFJ3": ["LFJ3"], "A_LFJ2": ["LFJ2"], "A_LFJ1": ["LFJ1", "LFJ0"], # Coupled joints "A_THJ4": ["THJ4"], "A_THJ3": ["THJ3"], "A_THJ2": ["THJ2"], "A_THJ1": ["THJ1"], "A_THJ0": ["THJ0"], } """ One-to-many mapping between actuators and actuated joints. Some actuators act on a single joint while others are connected to two joints (so called "coupled" joints). """ JOINT_ACTUATOR_MAPPING = { k: v for k, vlist in ACTUATOR_JOINT_MAPPING.items() for v in vlist } """ Reverse of the ACTUATOR_JOINT_MAPPING """ JOINT_LIMITS: Dict[str, np.ndarray] = {} for actuator, ctrlrange in ACTUATOR_CTRLRANGE.items(): joints = ACTUATOR_JOINT_MAPPING[actuator] for joint in joints: JOINT_LIMITS[joint] = np.array(ctrlrange) / len(joints) """ Joint limits in radian are derived from ACTUATOR_CTRLRANGE. The coupled joints share the full ctrlrange of *FJ1 and thus we divide the range by half. Shadow official joint limits for *FJ0 and *FJ1 are [0, 90] degree. See page 7 in https://www.shadowrobot.com/wp-content/uploads/shadow_dexterous_hand_technical_specification_E_20190221.pdf """ def _compute_projection_matrices(): """ compute matrices that project joint positions to actuator control and vice versa """ position_control_matrix = np.zeros((20, 24)) control_to_position_matrix = np.zeros((24, 20)) actuator_ids = dict(zip(ACTUATORS, range(len(ACTUATORS)))) joint_ids = dict(zip(JOINTS, range(len(JOINTS)))) for actuator_name, joint_names in ACTUATOR_JOINT_MAPPING.items(): value = 1.0 / len(joint_names) actuator_id = actuator_ids[actuator_name] joint_id_array = np.array([joint_ids[j] for j in joint_names]) position_control_matrix[actuator_id, joint_id_array] = 1.0 control_to_position_matrix[joint_id_array, actuator_id] = value return position_control_matrix, control_to_position_matrix # Some useful precomputed constants POSITION_TO_CONTROL_MATRIX, CONTROL_TO_POSITION_MATRIX = _compute_projection_matrices() def matching_actuators(actuator_pattern: Optional[str] = None) -> Set[str]: """ Returns names of actuators matching given actuator_pattern. The actuator pattern is a comma-separated list of actuator names or prefixes, for example "A_FFJ0,WRJ1,THJ0", or "FF". """ if actuator_pattern is None: return set(ACTUATORS) actuator_pattern = actuator_pattern.upper().strip() prefixes = actuator_pattern.split(",") matches = set() for actuator in ACTUATORS: for prefix in prefixes: # Forgive user is they forgot to add A_ prefix. if actuator.startswith(prefix) or actuator.startswith("A_" + prefix): matches.add(actuator) break return matches class Observation(RobotObservation): """ Interface for the single observation of the shadow hand. Observation object owns and manages a set of data that constitutes an "observation", and exposes a number of methods to extract commonly used fields (like joint positions or actuator effort). All fields in a single observation object come as much as possible from a single moment in time (as much as the hardware allows, as different sensors may have different sampling rates). """ @abc.abstractmethod def joint_velocities(self) -> np.ndarray: """ Return observed joint velocities (in rad/s) :returns 24-element array (one for each joint) of joint velocities """ pass @abc.abstractmethod def actuator_effort(self) -> np.ndarray: """ Return observed actuator effort normalized to the -1 to 1 range (1 means maximum effort). Effort is a unitless number proportional to the force exerted by that actuator, but the actual proportionality constant is not known. Effort is normalized based on maximum force limit of each actuator. Sign of the force indicates direction of the applied force - positive (negative) sign indicate force applied towards maximum (minimum) joint position(s). :return 20-element array (one for each actuator) of actuator efforts """ pass @abc.abstractmethod def fingertip_positions(self) -> np.ndarray: """ Return observed fingertip positions in meters measured in a coordinate system spanned by the three reference points on the hand mount. Finger ordering is: First Finger, Middle Finger, Ring Finger, Little Finger, Thumb :returns 5x3-element array of fingertip positions (5 fingertips in 3D) """ pass class Hand(Robot, abc.ABC): """ High level API for controlling Shadow Dexterous Hand E1 Series. It allows manipulation of the hand in real time and making observations about the state of the hand. This interface allows to control physical and simulated hands depending on the implementation. An important distinction here that because of existence of coupled joints there is more joints than actuators and some of the actuators act on multiple joints. The control values for such actuators is a sum of positions of individual joints, and that's the only value we can control. With that in mind the hand can be controlled in two separate ways: - Via position control, where desired joint positions (or sums of joint positions) are specified to the internal controller. Controller then chooses the right force for each actuator to reach these positions. - Directly via desired effort - that allows us to specify an effort value (proportional to force) for each actuator directly. Both control modes are mutually exclusive and turning on one turns off the other. """ ############################################################################################## # HAND INTERFACE UTILITY METHODS @classmethod def zero_joint_positions(cls) -> np.ndarray: """ Return an array representing zero joint positions (in rad). Zero positions represent a flat, straightened out hand. """ return np.zeros(len(JOINTS), dtype=np.float) @classmethod def zero_control(cls) -> np.ndarray: """ Return an array representing a zero actuator control vector (in rad). """ return np.zeros(len(cls.actuators()), dtype=np.float) @classmethod def actuators(cls) -> np.ndarray: return ACTUATORS @classmethod def zero_effort_control(cls) -> np.ndarray: """ Return an array representing a zero actuator effort control vector. """ return np.zeros(len(ACTUATORS), dtype=np.float) @classmethod def control_to_joint_positions(cls, control: np.ndarray) -> np.ndarray: """ Transform 20-dimensional (position) control to 24-dimensional joint positions. Coupled control values are divided evenly among connected joints. """ return CONTROL_TO_POSITION_MATRIX @ control @classmethod def joint_positions_to_control(cls, joint_pos: np.ndarray) -> np.ndarray: """ Transform 24-dimensional joint positions to 20-dimensional (position) control vector Coupled control values are sums of connected joints. """ return POSITION_TO_CONTROL_MATRIX @ joint_pos def normalize_position_control(self, position_control: np.ndarray) -> np.ndarray: """ Transform position control from the supported joint position range in radians into [-1, +1] range, where 0 represents the midpoint between two extreme positions. """ bounds = ( self.actuator_ctrl_range_upper_bound() - self.actuator_ctrl_range_lower_bound() ) return ( position_control - self.actuator_ctrl_range_lower_bound() ) / bounds * 2 - 1 @classmethod def is_effort_control_valid(cls, control: np.ndarray) -> bool: """ Check if effort control vector is within (inclusive) supported ranges and of correct shape """ return ( control.shape == ACTUATOR_CTRLRANGE_LOWER_BOUND.shape and np.all(control >= -1.0) and np.all(control <= 1.0) ) @classmethod def clip_position_control(cls, control: np.ndarray) -> np.ndarray: """ Clip (position) control vector to (inclusive) supported ranges """ return np.clip( control, ACTUATOR_CTRLRANGE_LOWER_BOUND, ACTUATOR_CTRLRANGE_UPPER_BOUND ) @classmethod def clip_effort_control(cls, control: np.ndarray) -> np.ndarray: """ Clip effort vector to (inclusive) supported ranges """ return np.clip(control, -1.0, 1.0) @classmethod def joint_array_to_dict(cls, values: np.ndarray) -> dict: """ Convert array of joint readings into a dictionary """ return dict(zip(JOINTS, values)) @classmethod def actuator_array_to_dict(cls, values: np.ndarray) -> dict: """ Convert array of actuator control into a dictionary """ return dict(zip(ACTUATORS, values)) @classmethod def actuator_dict_to_array(cls, data: dict) -> np.ndarray: """ Convert a dictionary of actuator data into an array """ return np.array([data[a] for a in ACTUATORS]) @classmethod def joint_dict_to_array(cls, data: dict) -> np.ndarray: """ Convert a dictionary of joint data into an array """ return np.array([data[a] for a in JOINTS]) @abc.abstractmethod def parameter_manager(self) -> ParameterConfigurer: """ Returns an instance of ParameterConfigurer that can be used to dynamically set parameters of the Hand """ pass def parameter_bounds(self, actuator: str): """Get valid parameter bounds for the given actuator.""" return self.parameter_manager().parameter_bounds(actuator) def current_parameters(self, actuator: str) -> Dict[str, float]: """Get current parameters for the given actuator.""" return self.parameter_manager().current_parameters(actuator) def set_parameters(self, actuator: str, assignments: Dict[str, float]): """Set parameters for the given actuator.""" self.parameter_manager().set_parameters(actuator, assignments) def export_parameters(self): """Export current parameters. For example, save parameters to XML or JSON configuration file.""" return self.parameter_manager().export_parameters() @abc.abstractmethod def observe(self) -> Observation: """ Return the "observation" object which contains all the most recent, contemporaneous observations of the state of the robotic hand. """ pass @abc.abstractmethod def set_effort_control(self, control: np.ndarray) -> None: """ Set desired actuator effort vector. Each coordinate of this vector is the desired normalized effort value between -1 and 1 for each motor. Effort is a unitless number proportional to the force exerted by that actuator, but the actual proportionality constant is not known. Effort is normalized based on maximum force limit of each actuator. Sign of the force indicates direction of the applied force - positive (negative) sign indicate force applied towards maximum (minimum) joint position(s). Both control modes are mutually exclusive and turning on one turns off the other. :param control: 20-element array of actuator force control """ pass
19,325
36.453488
121
py
robogym
robogym-master/robogym/robot/shadow_hand/mujoco/parameter_manager.py
from typing import Dict from robogym.robot.lib.parameter_configurer import ParameterConfigurer from robogym.robot.shadow_hand.hand_interface import ( ACTUATOR_JOINT_MAPPING, ACTUATORS, JOINTS, ) class MuJoCoParameterManager(ParameterConfigurer): def __init__(self, sim): self.mj_sim = sim def set_parameters(self, actuator: str, assignments: Dict[str, float]): assert actuator in ACTUATORS actuator_id = self.mj_sim.model.actuator_name2id(actuator) # Based on http://www.mujoco.org/book/XMLreference.html#position. # second value in biasprm should be equal to -kp (first value of gainprm) # for actuators of "position" type. self.mj_sim.model.actuator_gainprm[actuator_id][0] = assignments[ "actuator_gainprm_kp" ] self.mj_sim.model.actuator_gainprm[actuator_id][1] = assignments[ "actuator_gainprm_ti" ] self.mj_sim.model.actuator_gainprm[actuator_id][2] = assignments[ "actuator_gainprm_iclamp" ] self.mj_sim.model.actuator_gainprm[actuator_id][3] = assignments[ "actuator_gainprm_td" ] self.mj_sim.model.actuator_gainprm[actuator_id][4] = assignments[ "actuator_gainprm_dsmooth" ] self.mj_sim.model.actuator_gainprm[actuator_id][5] = assignments[ "actuator_gainprm_error_deadband" ] self.mj_sim.model.actuator_forcerange[actuator_id][0] = -assignments[ "actuator_forcerange" ] self.mj_sim.model.actuator_forcerange[actuator_id][1] = assignments[ "actuator_forcerange" ] if self._has_spring_tendon(actuator): tendon = self._spring_tendon_name(actuator) tendon_id = self.mj_sim.model.tendon_name2id(tendon) self.mj_sim.model.tendon_stiffness[tendon_id] = assignments[ "tendon_stiffness" ] self.mj_sim.model.tendon_lengthspring[tendon_id] = assignments[ "tendon_lengthspring" ] self.mj_sim.model.tendon_range[tendon_id][1] = assignments["tendon_range"] for joint in ACTUATOR_JOINT_MAPPING[actuator]: geom = f"coupling_{joint}_pulley" geom_id = self.mj_sim.model.geom_name2id(geom) self.mj_sim.model.geom_size[geom_id][0] = assignments[ f"{joint}_tendon_geom_0" ] for joint in ACTUATOR_JOINT_MAPPING[actuator]: joint_id = self.mj_sim.model.joint_name2id(joint) self.mj_sim.model.dof_damping[joint_id] = assignments[ f"{joint}_dof_damping" ] self.mj_sim.model.jnt_range[joint_id][0] = assignments[ f"{joint}_jnt_range_0" ] self.mj_sim.model.jnt_range[joint_id][1] = assignments[ f"{joint}_jnt_range_1" ] def current_parameters(self, actuator: str): assert actuator in ACTUATORS assignments = {} actuator_id = ACTUATORS.index(actuator) assignments["actuator_gainprm_kp"] = self.mj_sim.model.actuator_gainprm[ actuator_id ][0] assignments["actuator_gainprm_ti"] = self.mj_sim.model.actuator_gainprm[ actuator_id ][1] assignments["actuator_gainprm_iclamp"] = self.mj_sim.model.actuator_gainprm[ actuator_id ][2] assignments["actuator_gainprm_td"] = self.mj_sim.model.actuator_gainprm[ actuator_id ][3] assignments["actuator_gainprm_dsmooth"] = self.mj_sim.model.actuator_gainprm[ actuator_id ][4] assignments[ "actuator_gainprm_error_deadband" ] = self.mj_sim.model.actuator_gainprm[actuator_id][5] assignments["actuator_forcerange"] = self.mj_sim.model.actuator_forcerange[ actuator_id ][1] if self._has_spring_tendon(actuator): tendon = self._spring_tendon_name(actuator) tendon_id = self.mj_sim.model.tendon_name2id(tendon) assignments["tendon_stiffness"] = self.mj_sim.model.tendon_stiffness[ tendon_id ] assignments["tendon_lengthspring"] = self.mj_sim.model.tendon_lengthspring[ tendon_id ] assignments["tendon_range"] = self.mj_sim.model.tendon_range[tendon_id][1] for joint in ACTUATOR_JOINT_MAPPING[actuator]: geom = f"coupling_{joint}_pulley" geom_id = self.mj_sim.model.geom_name2id(geom) assignments[f"{joint}_tendon_geom_0"] = self.mj_sim.model.geom_size[ geom_id ][0] for joint in ACTUATOR_JOINT_MAPPING[actuator]: joint_id = JOINTS.index(joint) assignments[f"{joint}_dof_damping"] = self.mj_sim.model.dof_damping[ joint_id ] assignments[f"{joint}_jnt_range_0"] = self.mj_sim.model.jnt_range[joint_id][ 0 ] assignments[f"{joint}_jnt_range_1"] = self.mj_sim.model.jnt_range[joint_id][ 1 ] return assignments def parameter_bounds(self, actuator: str): assert actuator in ACTUATORS bounds = {} actuator_id = self.mj_sim.model.actuator_name2id(actuator) bounds["actuator_gainprm_kp"] = [ 0.25 * self.mj_sim.model.actuator_gainprm[actuator_id][0], 4 * self.mj_sim.model.actuator_gainprm[actuator_id][0], ] bounds["actuator_gainprm_ti"] = [ 0.25 * self.mj_sim.model.actuator_gainprm[actuator_id][1], 4 * self.mj_sim.model.actuator_gainprm[actuator_id][1] + 10.0, ] bounds["actuator_gainprm_iclamp"] = [ 0.25 * self.mj_sim.model.actuator_gainprm[actuator_id][2], 4 * self.mj_sim.model.actuator_gainprm[actuator_id][2] + 10.0, ] bounds["actuator_gainprm_td"] = [ 0.25 * self.mj_sim.model.actuator_gainprm[actuator_id][3], 4 * self.mj_sim.model.actuator_gainprm[actuator_id][3] + 0.1, ] bounds["actuator_gainprm_dsmooth"] = [ 0.0, 0.2, ] bounds["actuator_gainprm_error_deadband"] = [ 0, 0.03, ] # Note that force range min is equal to minus force range max, # thus we will be optimizing only one parameter. bounds["actuator_forcerange"] = [ 0.25 * self.mj_sim.model.actuator_forcerange[actuator_id][1], 4 * self.mj_sim.model.actuator_forcerange[actuator_id][1], ] if self._has_spring_tendon(actuator): tendon = self._spring_tendon_name(actuator) tendon_id = self.mj_sim.model.tendon_name2id(tendon) bounds["tendon_stiffness"] = [ 0.25 * self.mj_sim.model.tendon_stiffness[tendon_id], 4 * self.mj_sim.model.tendon_stiffness[tendon_id], ] bounds["tendon_lengthspring"] = [0.035, 0.075] bounds["tendon_range"] = [ 0.75 * self.mj_sim.model.tendon_range[tendon_id][1], 1.25 * self.mj_sim.model.tendon_range[tendon_id][1], ] for joint in ACTUATOR_JOINT_MAPPING[actuator]: geom = f"coupling_{joint}_pulley" geom_id = self.mj_sim.model.geom_name2id(geom) bounds[f"{joint}_tendon_geom_0"] = [ 0.5 * self.mj_sim.model.geom_size[geom_id][0], 1.5 * self.mj_sim.model.geom_size[geom_id][0], ] for joint in ACTUATOR_JOINT_MAPPING[actuator]: joint_id = self.mj_sim.model.joint_name2id(joint) bounds[f"{joint}_dof_damping"] = [0.01, 0.75] bounds[f"{joint}_jnt_range_0"] = [ self.mj_sim.model.jnt_range[joint_id][0] - 0.25, self.mj_sim.model.jnt_range[joint_id][0] + 0.25, ] bounds[f"{joint}_jnt_range_1"] = [ self.mj_sim.model.jnt_range[joint_id][1] - 0.25, self.mj_sim.model.jnt_range[joint_id][1] + 0.25, ] return bounds def _has_spring_tendon(self, actuator): return actuator in ["A_FFJ1", "A_MFJ1", "A_RFJ1", "A_LFJ1"] def _spring_tendon_name(self, actuator): assert self._has_spring_tendon( actuator ), f"{actuator} does not have spring tendon" return actuator.replace("A_", "")[:-2] + "T2"
8,648
38.857143
88
py
robogym
robogym-master/robogym/robot/shadow_hand/mujoco/shadow_hand_simulation.py
import numpy as np from robogym.mujoco.mujoco_xml import MujocoXML from robogym.mujoco.simulation_interface import SimulationInterface from robogym.robot.shadow_hand.mujoco.mujoco_shadow_hand import MuJoCoShadowHand class ShadowHandSimulation(SimulationInterface): """ MuJoCo simulation containing only the shadow hand """ # Robot hand xml HAND_XML = "robot/shadowhand/main.xml" # Just a floor FLOOR_XML = "floor/basic_floor.xml" # XML with default light LIGHT_XML = "light/default.xml" @classmethod def build( cls, n_substeps: int = 10, timestep: float = 0.008, name_prefix: str = "robot0:" ): """ Construct MjSim object for this simulation :param name_prefix - to append to names of all objects in the MuJoCo model of the hand; by default no prefix is appended. """ xml = MujocoXML() xml.add_default_compiler_directive() max_contacts_params = dict(njmax=2000, nconmax=200) xml.append( MujocoXML.parse(cls.FLOOR_XML).set_named_objects_attr( "floor", tag="body", pos=[1, 1, 0] ) ) xml.append( MujocoXML.parse(cls.HAND_XML) .add_name_prefix(name_prefix) .set_objects_attr(tag="size", **max_contacts_params) .set_objects_attr(tag="option", timestep=timestep) .set_named_objects_attr( f"{name_prefix}hand_mount", tag="body", pos=[1.0, 1.25, 0.15], euler=[np.pi / 2, 0, np.pi], ) .remove_objects_by_name(f"{name_prefix}annotation:outer_bound") # Remove hand base free joint so that hand is immovable .remove_objects_by_name(f"{name_prefix}hand_base") ) xml.append(MujocoXML.parse(cls.LIGHT_XML)) return cls(sim=xml.build(nsubsteps=n_substeps), hand_prefix=name_prefix) def __init__(self, sim, hand_prefix="robot0:"): super().__init__(sim) self.enable_pid() self.shadow_hand = MuJoCoShadowHand(self, hand_prefix=hand_prefix)
2,144
32
95
py
robogym
robogym-master/robogym/robot/shadow_hand/mujoco/mujoco_shadow_hand.py
import numpy as np from mujoco_py.generated import const from robogym.mujoco.simulation_interface import SimulationInterface from robogym.robot.shadow_hand.hand_forward_kinematics import ( FINGERTIP_SITE_NAMES, REFERENCE_SITE_NAMES, get_relative_positions, ) from robogym.robot.shadow_hand.hand_interface import ACTUATORS, Hand, Observation from robogym.robot.shadow_hand.hand_utils import ( denormalize_by_limit, normalize_by_limits, ) from robogym.robot.shadow_hand.mujoco.parameter_manager import MuJoCoParameterManager class MuJoCoObservation(Observation): """ Shadow Hand observation coming from the MuJoCo simulation """ def __init__( self, simulation: SimulationInterface, hand_prefix: str, joint_group: str ): fingers = np.array( [ simulation.mj_sim.data.get_site_xpos(hand_prefix + site) for site in FINGERTIP_SITE_NAMES ] ) reference = np.array( [ simulation.mj_sim.data.get_site_xpos(hand_prefix + site) for site in REFERENCE_SITE_NAMES ] ) self._fingertip_positions = get_relative_positions(fingers, reference) self._joint_positions = simulation.get_qpos(joint_group).copy() self._joint_vel = simulation.get_qvel(joint_group).copy() self._time = simulation.mj_sim.data.time self._force_limits = simulation.mj_sim.model.actuator_forcerange.copy() self._actuator_force = normalize_by_limits( simulation.mj_sim.data.actuator_force, self._force_limits ) def joint_positions(self) -> np.ndarray: return self._joint_positions def joint_velocities(self) -> np.ndarray: return self._joint_vel def actuator_effort(self) -> np.ndarray: return self._actuator_force def timestamp(self) -> float: return self._time def fingertip_positions(self) -> np.ndarray: return self._fingertip_positions class MuJoCoShadowHand(Hand): """ MuJoCo interface to interact with robotic Shadow Hand """ def get_name(self) -> str: return "unnamed-mujoco-shadowhand" def __init__( self, simulation: SimulationInterface, hand_prefix="robot0:", autostep=False ): """ :param simulation: simulation interface for the MuJoCo shadow hand xml :param hand_prefix: Prefix to add to the joint names while constructing the MuJoCo simulation :param autostep: When true, calls step() on the simulation whenever a control is set. This should only be used only when the MuJoCoShadowHand is being controlled without a SimulationRunner in the loop. """ self.simulation = simulation self.hand_prefix = hand_prefix self.autostep = autostep self.joint_group = hand_prefix + "hand_joint_angles" self.simulation.register_joint_group(self.joint_group, prefix=hand_prefix) self._parameter_manager = MuJoCoParameterManager(self.mj_sim) assert self.mj_sim.model.nu == len( ACTUATORS ), "Action space must have compatible shape" # Are we in the joint control mode or in the force control mode? self.joint_control_mode = True self.force_limits = self.mj_sim.model.actuator_forcerange.copy() # Store copies of parameters in the initial state self.gainprm_copy = self.mj_sim.model.actuator_gainprm.copy() self.biasprm_copy = self.mj_sim.model.actuator_biasprm.copy() self.ctrlrange_copy = self.mj_sim.model.actuator_ctrlrange.copy() def parameter_manager(self): return self._parameter_manager def actuator_ctrl_range_upper_bound(self) -> np.ndarray: # We use control range in xml instead of constants to take into account # ADR randomization for joint limit. return self.mj_sim.model.actuator_ctrlrange[:, 1] def actuator_ctrl_range_lower_bound(self) -> np.ndarray: # We use control range in xml instead of constants to take into account # ADR randomization for joint limit. return self.mj_sim.model.actuator_ctrlrange[:, 0] @property def mj_sim(self): """ MuJoCo MjSim simulation object """ return self.simulation.mj_sim def set_position_control(self, control: np.ndarray) -> None: assert self.is_position_control_valid(control), f"Invalid control: {control}" if not self.joint_control_mode: # Need to change the parameters of the motors # state. self.mj_sim.model.actuator_gaintype[:] = const.GAIN_USER self.mj_sim.model.actuator_biastype[:] = const.BIAS_USER self.mj_sim.model.actuator_gainprm[:] = self.gainprm_copy self.mj_sim.model.actuator_biasprm[:] = self.biasprm_copy self.mj_sim.model.actuator_ctrlrange[:] = self.ctrlrange_copy self.joint_control_mode = True self.mj_sim.data.ctrl[:] = control if self.autostep: self.mj_sim.step() def set_effort_control(self, control: np.ndarray) -> None: if self.joint_control_mode: # Need to change the parameters of the motors self.mj_sim.model.actuator_gaintype[:] = const.GAIN_FIXED self.mj_sim.model.actuator_biastype[:] = const.BIAS_NONE self.mj_sim.model.actuator_gainprm[:, 0] = 1.0 self.mj_sim.model.actuator_biasprm[:] = 0 self.mj_sim.model.actuator_ctrlrange[:] = np.array([[-1.0, 1.0]]) self.joint_control_mode = False # Transform 0 and 1 into force limits force_applied = denormalize_by_limit(control, self.force_limits) self.mj_sim.data.ctrl[:] = force_applied if self.autostep: self.mj_sim.step() def observe(self) -> Observation: return MuJoCoObservation(self.simulation, self.hand_prefix, self.joint_group)
5,982
36.39375
101
py
robogym
robogym-master/robogym/robot/shadow_hand/test/test_hand_interface.py
import numpy as np from robogym.robot.shadow_hand.hand_interface import ( ACTUATOR_CTRLRANGE, ACTUATOR_GROUPS, ACTUATOR_JOINT_MAPPING, ACTUATORS, CONTROL_TO_POSITION_MATRIX, POSITION_TO_CONTROL_MATRIX, actuator2group, filter_actuator_groups, joint2group, matching_actuators, ) from robogym.robot.shadow_hand.mujoco.shadow_hand_simulation import ShadowHandSimulation def test_matching_actuators(): def verify(pattern, expected): assert matching_actuators(pattern) == expected verify(None, set(ACTUATORS)) verify("wrj0", {"A_WRJ0"}) verify("A_wrj0", {"A_WRJ0"}) verify("FFJ1", {"A_FFJ1"}) verify("WRJ0", {"A_WRJ0"}) verify("wRj", {"A_WRJ1", "A_WRJ0"}) verify("WRJ", {"A_WRJ1", "A_WRJ0"}) verify( "WRJ,A_MFJ1,RFJ", {"A_WRJ1", "A_WRJ0", "A_MFJ1", "A_RFJ3", "A_RFJ2", "A_RFJ1"} ) def test_actuator2group(): for actuator in ACTUATORS: group = actuator2group(actuator) assert actuator in ACTUATOR_GROUPS[group] def test_joint2group(): for actuator in ACTUATORS: for joint in ACTUATOR_JOINT_MAPPING[actuator]: group = joint2group(joint) assert actuator in ACTUATOR_GROUPS[group] def test_filter_actuator_groups(): assert filter_actuator_groups(None) == ACTUATOR_GROUPS assert filter_actuator_groups([]) == ACTUATOR_GROUPS assert filter_actuator_groups(["A_FFJ1", "A_LFJ2", "A_LFJ3"]) == { "FF": ["A_FFJ1"], "LF": ["A_LFJ3", "A_LFJ2"], } def test_control_ranges(): """ Check if control ranges match between MuJoCo sim and RoboticHand interface """ sim = ShadowHandSimulation.build() mujoco_ctrlrange = sim.mj_sim.model.actuator_ctrlrange.copy() hand_ctrlrange = np.array([ACTUATOR_CTRLRANGE[a] for a in ACTUATORS]) assert np.linalg.norm(mujoco_ctrlrange - hand_ctrlrange) < 1e-8 def test_joint_projection(): """ Make sure that transforming joint positions to control vector and back preserves the values """ m1 = POSITION_TO_CONTROL_MATRIX @ CONTROL_TO_POSITION_MATRIX assert np.linalg.norm(m1 - np.eye(20)) < 1e-8 def test_normalize_position(): """ Test if position normalization works as expected, """ sim = ShadowHandSimulation.build() hand = sim.shadow_hand for i in range(10): # Test ten times position = np.random.uniform(-1.0, 1.0, size=len(ACTUATORS)) scaled = hand.denormalize_position_control(position) assert hand.is_position_control_valid(scaled) unscaled = hand.normalize_position_control(scaled) assert np.linalg.norm(position - unscaled) < 1e-8
2,656
29.54023
88
py
robogym
robogym-master/robogym/robot/shadow_hand/test/test_mujoco_hand.py
import mock import numpy as np from robogym.robot.shadow_hand.hand_forward_kinematics import ( compute_forward_kinematics_fingertips, ) from robogym.robot.shadow_hand.hand_interface import ( ACTUATOR_CTRLRANGE, ACTUATOR_CTRLRANGE_LOWER_BOUND, ACTUATOR_CTRLRANGE_UPPER_BOUND, ACTUATOR_GROUPS, ACTUATORS, ) from robogym.robot.shadow_hand.hand_utils import separate_group_control from robogym.robot.shadow_hand.mujoco.mujoco_shadow_hand import MuJoCoShadowHand from robogym.robot.shadow_hand.mujoco.shadow_hand_simulation import ShadowHandSimulation def test_mujoco_forward_kinematics(): """ Make sure forward kinematics we calculate agree with mujoco values """ simulation = ShadowHandSimulation.build() hand = simulation.shadow_hand for i in range(5): position = np.random.uniform(-1.0, 1.0, size=len(ACTUATORS)) scaled = hand.denormalize_position_control(position) hand.set_position_control(scaled) # Make sure simulation has enough time to reach position for _ in range(100): simulation.step() observation = hand.observe() computed_fingertips = compute_forward_kinematics_fingertips( observation.joint_positions() ) assert ( np.abs(observation.fingertip_positions() - computed_fingertips) < 1e-6 ).all() def test_mujoco_move_hand(): """ Test if we can move and observe mujoco hand """ simulation = ShadowHandSimulation.build() hand = simulation.shadow_hand for actuator_group in sorted(ACTUATOR_GROUPS.keys()): for actuator in ACTUATOR_GROUPS[actuator_group]: position_control = hand.zero_control() position_control = separate_group_control(position_control, actuator_group) random_value = np.random.uniform(0.0, 1.0) lower_bound = ACTUATOR_CTRLRANGE[actuator][0] upper_bound = ACTUATOR_CTRLRANGE[actuator][1] position_control[ACTUATORS.index(actuator)] = ( random_value * (upper_bound - lower_bound) + lower_bound ) hand.set_position_control(position_control) # Make sure simulation has enough time to reach position for _ in range(100): simulation.step() observation = hand.observe() positions_observed = hand.joint_positions_to_control( observation.joint_positions() ) error = positions_observed - position_control assert (np.rad2deg(np.abs(error)) < 7.5).all() def test_mujoco_effort_move(): """ Test if mujoco effort control works """ simulation = ShadowHandSimulation.build() hand = simulation.shadow_hand # Actuators that we can safely steer using effort control # Actuators J3 for each finger are special in a way, that until # we really try to separate the fingers, they're super likely to # collide with other fingers, preventing them from reaching desired position safe_actuators = [ "A_WRJ1", # 0 "A_WRJ0", # 1 # "A_FFJ3", # 2 "A_FFJ2", # 3 "A_FFJ1", # 4 # "A_MFJ3", # 5 "A_MFJ2", # 6 "A_MFJ1", # 7 # "A_RFJ3", # 8 "A_RFJ2", # 9 "A_RFJ1", # 10 "A_LFJ4", # 11 # "A_LFJ3", # 12 "A_LFJ2", # 13 "A_LFJ1", # 14 "A_THJ4", # 15 "A_THJ3", # 16 "A_THJ2", # 17 "A_THJ1", # 18 "A_THJ0", # 19 ] for selected_actuator in safe_actuators: for selected_force in [-1.0, 1.0]: actuator_index = ACTUATORS.index(selected_actuator) effort_control = hand.zero_control() effort_control[actuator_index] = selected_force # Maximum positive effort hand.set_effort_control(effort_control) # Make sure simulation has enough time to reach position for _ in range(100): simulation.step() observation = hand.observe() # Switch back to position control. hand.set_position_control(hand.zero_control()) pos_in_rad = hand.joint_positions_to_control(observation.joint_positions()) pos_normalized = np.clip( hand.normalize_position_control(pos_in_rad), -1.0, 1.0 ) # We would expect to reach joint limit error = pos_normalized[actuator_index] - selected_force assert np.abs(error) < 0.1 def test_autostep(): mock_sim = mock.MagicMock() mock_sim.mj_sim.model.nu = len(ACTUATORS) mock_sim.mj_sim.model.actuator_ctrlrange = np.array( np.transpose([ACTUATOR_CTRLRANGE_LOWER_BOUND, ACTUATOR_CTRLRANGE_UPPER_BOUND]) ) hand = MuJoCoShadowHand(simulation=mock_sim, autostep=True,) mock_step = mock.Mock() mock_sim.mj_sim.step = mock_step hand.set_position_control(hand.zero_control()) mock_step.assert_called_once() mock_step.reset_mock() hand.set_effort_control(np.zeros_like(hand.zero_control())) mock_step.assert_called_once()
5,149
31.802548
88
py
robogym
robogym-master/robogym/robot/test/test_robot_interface.py
import mock import numpy as np import pytest from robogym.envs.rearrange.blocks import BlockRearrangeSim, BlockRearrangeSimParameters from robogym.robot.robot_interface import ( ControlMode, RobotControlParameters, TcpSolverMode, ) def _build_arm(control_mode, max_position_change, tcp_solver_mode=TcpSolverMode.MOCAP): sim = BlockRearrangeSim.build( n_substeps=1, simulation_params=BlockRearrangeSimParameters(), robot_control_params=RobotControlParameters( control_mode=control_mode, max_position_change=max_position_change, tcp_solver_mode=tcp_solver_mode, ), ) return sim.robot.robots[0] @pytest.mark.parametrize( "max_position_change,expected_command", [ (None, [6.1959, 6.1959, 2.8, 6.1959, 6.1959, 2.312561]), (2.5, [2.5, 2.5, 2.5, 2.5, 2.5, 2.312561]), ([1.0, 1.0, 1.0, 0.5, 0.5, 9.0], [1.0, 1.0, 1.0, 0.5, 0.5, 2.312561]), ], ) def test_actuation_range_with_rel_action(max_position_change, expected_command): arm = _build_arm(ControlMode.JOINT.value, max_position_change) assert np.allclose(arm.actuation_range(relative_action=True), expected_command) @pytest.mark.parametrize( "max_position_change", [None, 3.0, [1.0, 1.0, 1.0, 0.5, 0.5, 9.0]] ) def test_actuation_range_with_abs_action(max_position_change): """ Absolute actions should ignore max_position_change command.""" arm = _build_arm(ControlMode.JOINT.value, max_position_change) assert np.allclose( arm.actuation_range(relative_action=False), [6.1959, 6.1959, 2.8, 6.1959, 6.1959, 2.312561], ) def test_composite_autostep(): from robogym.robot.composite.ur_gripper_arm import ( MujocoURJointGripperCompositeRobot, ) sim = mock.MagicMock() robot = MujocoURJointGripperCompositeRobot( simulation=sim, solver_simulation=sim, robot_control_params=RobotControlParameters(max_position_change=0.05), autostep=True, ) assert sim.mj_sim.step.call_count == 0 robot.set_position_control(np.zeros(7)) assert sim.mj_sim.step.call_count == 1 def test_free_wrist_composite(): arm = _build_arm( control_mode=ControlMode.TCP_WRIST, max_position_change=0.05, tcp_solver_mode=TcpSolverMode.MOCAP_IK, ) for applied_ctrl in [-1, 0, 1]: expected_change_deg = 30 * applied_ctrl new_pos = arm.denormalize_position_control( np.concatenate((np.zeros(3), [applied_ctrl])), relative_action=True ) assert np.isclose(new_pos[-1], np.deg2rad(expected_change_deg), atol=1e-7)
2,653
30.975904
88
py
robogym
robogym-master/robogym/robot/utils/measurement_units.py
"""Module to provide functionality related to measurement units, since not all robots work with angles or in radians, and other components may want to provide hybrid data representations, such as plots or reports.""" from __future__ import annotations from enum import Enum import numpy as np class MeasurementUnit(Enum): """Units of measurement known to this check.""" # values are important since they are pickled RADIANS = 1 DEGREES = 2 METERS = 3 MILLIMETERS = 4 SECONDS = 5 MILLISECONDS = 6 def shortname(self): if self == MeasurementUnit.RADIANS: return "rad" elif self == MeasurementUnit.DEGREES: return "deg" elif self == MeasurementUnit.METERS: return "m" elif self == MeasurementUnit.MILLIMETERS: return "mm" elif self == MeasurementUnit.SECONDS: return "s" elif self == MeasurementUnit.MILLISECONDS: return "ms" raise RuntimeError(f"Shortname for '{self}' is not specified") def convert_to(self, data: np.ndarray, to_units: MeasurementUnit) -> np.ndarray: """Poor man's conversion from self units to 'to_units' for supported parts. It may only support a subset of all possible conversions, and will raise an error if the requested one is not supported. :param data: Data to convert. :param to_units: Units to convert to. :return: Result of converting the data to the new units, from the current units. :raises RuntimeError: If the conversion pair is not supported. """ if self == to_units: return data if self == MeasurementUnit.RADIANS and to_units == MeasurementUnit.DEGREES: return np.rad2deg(data) elif self == MeasurementUnit.DEGREES and to_units == MeasurementUnit.RADIANS: return np.deg2rad(data) elif self == MeasurementUnit.METERS and to_units == MeasurementUnit.MILLIMETERS: return np.multiply(data, 1000) elif self == MeasurementUnit.MILLIMETERS and to_units == MeasurementUnit.METERS: return np.multiply(data, 1e-3) elif ( self == MeasurementUnit.SECONDS and to_units == MeasurementUnit.MILLISECONDS ): return np.multiply(data, 1000) raise RuntimeError(f"Can't convert between units from {self} to {to_units}")
2,415
38.606557
117
py
robogym
robogym-master/robogym/robot/utils/reach_helper.py
"""Provides utilities to command reaching a specified position in the robot, and waiting for its completion.""" from __future__ import annotations import enum import logging import os import time from dataclasses import dataclass from typing import Callable, List, Optional, Union import matplotlib.pyplot as plt import numpy as np from robogym.robot.robot_interface import Robot, RobotObservation from robogym.robot.utils.measurement_units import MeasurementUnit logger = logging.getLogger(__name__) @dataclass class ReachResult: """Final result of a command to reach position.""" reached: bool # Whether the destination was reached when the action ended (it can time out) robot_stopped: bool # Whether the robot was considered as stopped (not moving) when the action ended desired_joint_positions: np.ndarray # desired destination last_joint_positions: np.ndarray # last observed positions for all actuators/joints last_joint_velocities: np.ndarray # last observed velocities for all actuators/joints position_threshold: float # threshold to consider positions as reached (against the goal) velocity_threshold: float # threshold to consider velocities as stopped (against 0) @staticmethod def _error_message_line(name, error, threshold, units: MeasurementUnit): """Provides a single line message for an actuator that has failed with the given params.""" return f"Actuator {name} with error abs({error:.4f}) {units.name} > threshold {threshold:.4f} {units.name}" def _failed_actuators(self, robot: Robot): """Returns a dictionary of failed actuators, with their name as the key, and the error as value.""" actuators = robot.actuators() assert len(actuators) == len(self.last_joint_positions) error_per_failed_actuators = {} errors_per_actuator = self.last_joint_positions - self.desired_joint_positions for act_idx, error in enumerate(errors_per_actuator): if np.abs(error) > self.position_threshold: # this actuator failed actuator_name = actuators[act_idx] error_per_failed_actuators[actuator_name] = error return error_per_failed_actuators def error_message( self, robot: Robot, units: MeasurementUnit = MeasurementUnit.RADIANS ): """Format a nice error message if position was not reached successfully.""" failed_acts_dict = self._failed_actuators(robot) line_per_actuator = [ self.__class__._error_message_line( name, failed_acts_dict[name], self.position_threshold, units ) for name in robot.actuators() if name in failed_acts_dict ] return ( "Positions not reached successfully:\n - " + "\n - ".join(line_per_actuator) + "\n" if len(line_per_actuator) > 0 else "" ) @dataclass class ReachHelperConfigParameters: """Configuration parameters that should not change between runs to reach different positions, they are more related to the robot that will be reaching the positions, than to the individual attempt. See related class ReachHelperRunParameters.""" reached_position_threshold: float # position threshold to consider the target as reached stopped_velocity_threshold: float # velocity threshold to consider the robot as stopped stopped_stable_time: float # how long (in seconds) we have to wait stopped to declare speed as stable safety_speed_limit: float # speed that is considered safe, and that will throw an error if exceeded minimum_time_to_move: float # time that the robot can be stopped after the command without thinking it failed @dataclass class ReachHelperRunParameters: """Parameters that can depend on how far the target position is, or how quickly we want to reach the position. See related class ReachHelperConfigParameters.""" timeout: float # how long we allow the robot to move at max max_speed_per_sec: Union[float, np.ndarray] # max speed shared or per control class PlotOutput(enum.Flag): """Where the plot output can be sent to.""" DISABLED = enum.auto() SCREEN = enum.auto() FILE = enum.auto() SCREEN_AND_FILE = SCREEN | FILE def is_enabled(self) -> bool: return self != PlotOutput.DISABLED class ReachHelperDebugRecorder: """Class to record each delta that is sent to the robot, along with logs or other useful information, for debugging purposes.""" def __init__(self, robot: Robot): self.robot = robot self.timestamps: List[float] = [] self.commanded: List[np.ndarray] = [] self.obs_pos: List[np.ndarray] = [] self.obs_vel: List[np.ndarray] = [] self.logs: List[str] = [] self.obs_helper_pos: List[np.ndarray] = [] def add_log(self, log_entry: str) -> None: """Adds the given string as a log entry to this recorder, so that it can be logged later if required. :param log_entry: String to add as a log entry to this record. """ self.logs.append(f"{time.time()} [reach_helper] {log_entry}") def add_sample(self, timestamp, command, obs_pos, obs_vel, obs_helper_pos) -> None: """Add a delta to the collection. :param timestamp: Timestamp at which the delta happened. :param command: Commanded position. :param obs_pos: Observed position from the robot (all actuators). :param obs_vel: Observed velocity from the robot (all actuators). :param obs_helper_pos: Observed position from the helper robot (all actuators) if any. """ self.timestamps.append(timestamp) self.commanded.append(command) self.obs_pos.append(obs_pos) self.obs_vel.append(obs_vel) if obs_helper_pos is not None: self.obs_helper_pos.append(obs_helper_pos) def dump_logs(self) -> None: """Sends all log entries in the instance to the logger.""" for entry in self.logs: logger.info(entry) def plot_pos_and_vel_for_actuator( self, actuator_index: int, output: PlotOutput, data_unit: MeasurementUnit, plot_unit: MeasurementUnit, debug_reach_try_id: str, ) -> None: """Plots the commanded position, and observed positions and velocities for the given actuator over the deltas that have been provided by the reach helper to the robot. :param actuator_index: Index of the actuator within the collected data to plot. :param output: Where to send the plot. :param data_unit: Unit the data was collected in. :param plot_unit: Unit we want to visualize that data (must be related to data_unit). :param debug_reach_try_id: Identifier of the reach helper attempt whose plot we are showing (sets title). """ assert output.is_enabled() n_rows = 1 n_cols = 2 fig, axes = plt.subplots(n_rows, n_cols, figsize=(14, n_rows * 4)) plt.suptitle( f"Try:{debug_reach_try_id} - Actuator:{self.robot.actuators()[actuator_index]}" ) qpos_axis = axes[0] qvel_axis = axes[1] commanded_plot_data = data_unit.convert_to( np.asarray(self.commanded), plot_unit ) obs_pos_plot_data = data_unit.convert_to(np.asarray(self.obs_pos), plot_unit) obs_vel_plot_data = data_unit.convert_to(np.asarray(self.obs_vel), plot_unit) if len(self.obs_helper_pos) > 0: obs_helper_pos_data = data_unit.convert_to( np.asarray(self.obs_helper_pos), plot_unit ) else: obs_helper_pos_data = None # plot cmd, qpos size = 3 qpos_axis.plot( self.timestamps, commanded_plot_data[:, actuator_index], marker=4, color="purple", ms=size, linestyle="--", label="commanded", ) qpos_axis.plot( self.timestamps, obs_pos_plot_data[:, actuator_index], marker="+", color="blue", ms=size, label="measured pos", ) if obs_helper_pos_data is not None: qpos_axis.plot( self.timestamps, obs_helper_pos_data[:, actuator_index], marker="+", color="orange", ms=size, label="helper pos", ) qpos_axis.legend() qpos_axis.grid() # plot qvel qvel_axis.plot( self.timestamps, obs_vel_plot_data[:, actuator_index], marker="+", color="blue", ms=size, label="measured vel", ) qvel_axis.legend() qvel_axis.grid() # output: record file if (output & PlotOutput.FILE).value != 0: folder = "reach_helper_images/" os.makedirs(folder, exist_ok=True) fig_name = f"reach_helper_{debug_reach_try_id}_jnt_{actuator_index}.png" fig_path = os.path.join(folder, fig_name) logger.info(f"Note: Reach helper debug saving plot '{fig_path}'") plt.savefig(fig_path) class ReachHelper: """This class can be configured to command and keep track of a robot as it moves towards a goal destination.""" # Useful type definitions ObservationList = List[RobotObservation] def __init__(self, robot: Robot, config: ReachHelperConfigParameters): """ Constructor. :param robot: Robot interface that will perform the movements. :param config: Parameters the configure the helper. These parameters are considered to be stable even if you reach different positions over the lifetime of the helper. """ self.robot = robot self.config = config # Current state self.start_time: float self.robot_stopped_at: float self.observation: RobotObservation self.reset() def reset(self) -> None: """Reset internal state of the util, ignoring any previous movements performed.""" self.observation = self.robot.observe() self.start_time = self.observation.timestamp() self.robot_stopped_at = -1.0 # not stopped def _observe(self, buffer: Optional[ObservationList] = None) -> RobotObservation: """Make an observation on the robot, and update internal state, appending it to the buffer if provided. :param buffer: List of observations to append the newly observed one. :return: A newly observed robot observation. """ self.observation = self.robot.observe() if buffer is not None: buffer.append(self.observation) return self.observation def _set_position_control(self, position_control: np.ndarray) -> None: """Set position control for the underlying robot. :param position_control: Array of desired position for each joint (control) in the robot. """ self.robot.set_position_control(position_control) def _is_position_reached(self, position_control: np.ndarray) -> bool: """Returns whether joint (control) positions are close to a specified value, with closeness defined by the position threshold set in the constructor.""" obs_control_positions = self.robot.joint_positions_to_control( self.observation.joint_positions() ) position_errors = obs_control_positions - position_control return (np.abs(position_errors) <= self.config.reached_position_threshold).all() def _is_robot_stopped_and_stable(self) -> bool: """Returns whether joint velocity has stabilized to a low value, defined by the velocity threshold set in the constructor.""" joint_velocity = self.observation.joint_velocities() is_currently_stopped = ( np.abs(joint_velocity) <= self.config.stopped_velocity_threshold ).all() # calculate whether stable is_stable = False if is_currently_stopped: # we are stopped, if time of stop not set, set now if self.robot_stopped_at < self.start_time: self.robot_stopped_at = self.observation.timestamp() # check if we have reached stability according to the threshold is_stable = ( self.observation.timestamp() - self.robot_stopped_at ) >= self.config.stopped_stable_time else: # not currently stopped, clear stop time self.robot_stopped_at = -1.0 return is_currently_stopped and is_stable def reach( self, target_position_control: np.ndarray, *, run_params: ReachHelperRunParameters, debug_recorder: Optional[ReachHelperDebugRecorder] = None, iteration_callback: Optional[Callable[[], None]] = None, ) -> ReachResult: """Move the robot to the desired position (control). Block until the robot stops moving or time out occurs. :param target_position_control: Target positions (controls) of the robot. :param run_params: Parameters that configure this execution of a move. These parameters are considered to be potentially different per run, since the target position or the trajectory may have different requirements. :param debug_recorder: Optional instance where records will be added so that they can be inspected outside this function. :param iteration_callback: Optional callback to call on each iteration of the reach helper. This iteration timing depends on whether the robot is simulated or real, but should it match the control delta configured for physical robots, or the simulation step size for simulated robots. """ # - - - - - - - - - - - - - - - - - - - - - - - - # DEBUG OPTIONS: # a) set debug_enable_logs to True to get logs printed # b) set debug_enable_logs to the desired PlotOutput value to generate plots # b.1) set debug_plots_data_unit to the measurement unit the data is collected at # b.2) set debug_plots_view_unit to the measurement unit you want to visualize the data debug_enable_logs = False debug_plots_output = PlotOutput.DISABLED debug_plots_data_unit = MeasurementUnit.RADIANS debug_plots_view_unit = MeasurementUnit.DEGREES debug_reach_try_id = str(time.time()) # - - - - - - - - - - - - - - - - - - - - - - - - # Current implementations of robots (eg: ur16e) expect to be controlled regularly, rather than # being sent the target position. Although some hardware may support the latter (ur16e's can through move # functions, instead of servoJ functions), this helper will try to command with linear interpolation on # small deltas. delta_secs = self.robot.get_control_time_delta() if delta_secs <= 0.0: raise RuntimeError( "Failed to obtain control delta from robot. Can't reach position." ) self._observe() local_start_time = self.observation.timestamp() # unfortunately, we can't use zero_control to know the shape of the controls, since UR TCP controlled arms # are switching to Joint control for the helper, while zero_control is a class method. Use current control # instead of zero_control to expand the speed to the correct shape current_control = self.robot.joint_positions_to_control( self.observation.joint_positions() ) # compute max speed per control if specified as float, otherwise simply grab if isinstance(run_params.max_speed_per_sec, float): max_speed_per_sec_per_control = np.full( current_control.shape, run_params.max_speed_per_sec ) else: max_speed_per_sec_per_control = run_params.max_speed_per_sec # check that no speed violates the safety limit if np.any(max_speed_per_sec_per_control > self.config.safety_speed_limit): raise RuntimeError( f"Speed is above limit, aborting reach: " f"{max_speed_per_sec_per_control} > {self.config.safety_speed_limit}" ) # calculate the position deltas we will use to feed to the robot smaller offsets max_speed_per_delta_per_control = delta_secs * max_speed_per_sec_per_control control_distance = target_position_control - current_control generated_deltas_list: List[np.ndarray] = [] max_computed_steps = 0 controls_that_will_timeout = [] # we allow each control to move as fast as possible up to its max speed. for control_idx in range(len(target_position_control)): # calculate how long it takes for this control to reach its destination distance_i = np.abs(control_distance[control_idx]) max_speed_i = max_speed_per_delta_per_control[control_idx] # if there's only one step, linspace will generate as output only the current value, not the target. Make # sure that we at least get 2 steps so that we have the target in the output too. So although the formula # would be: # steps_at_max_speed_i = int(distance_i / max_speed_i) + 1 # add 2 instead of 1. This covers the case of the distance being smaller than the max speed per delta, # which would yield 0+1 steps needed, thus not moving. Not moving is an issue when the distance between # the current delta and the target is smaller than the max speed, but larger than the reach threshold. steps_at_max_speed_i = int(distance_i / max_speed_i) + 2 # generate the curve for this control position_deltas_i = np.linspace( current_control[control_idx], target_position_control[control_idx], steps_at_max_speed_i, ) generated_deltas_list.append(position_deltas_i) # record the max because that's the length that we need all arrays to be expanded to if steps_at_max_speed_i > max_computed_steps: max_computed_steps = steps_at_max_speed_i # if we know that a control is not fast enough (it will timeout), flag now required_time = ( steps_at_max_speed_i * delta_secs ) + self.config.stopped_stable_time if required_time > run_params.timeout: msg = f"{control_idx} | distance:{distance_i}, speed:{max_speed_i}/sec, requiredTime:{required_time}sec" controls_that_will_timeout.append(msg) # if we know that at least one control will not reach the target, fail now before trying if len(controls_that_will_timeout) > 0: raise RuntimeError( f"Some controls won't reach their target before the timeout {run_params.timeout} sec: " f"\nControlIdx:{controls_that_will_timeout}, with " f"\nTarget : {target_position_control}" f"\nCurrent : {current_control}" f"\nMaxSpeed: [setting ] {run_params.max_speed_per_sec}" f"\nMaxSpeed: [per_ctrl] {max_speed_per_sec_per_control}" ) # pad each control to match the size of the longest control generated_deltas_padded = [] for delta_i in generated_deltas_list: pad = max_computed_steps - len(delta_i) if pad > 0: padded_delta_i = np.concatenate( (delta_i, np.full((pad,), delta_i[-1], dtype=delta_i.dtype)) ) generated_deltas_padded.append(padded_delta_i) else: generated_deltas_padded.append(delta_i) # transpose deltas to the correct control shape generated_deltas = np.transpose(np.asarray(generated_deltas_padded)) next_delta = ( 1 if len(generated_deltas) > 1 else 0 ) # can skip 0, since it's the same as current control if debug_recorder is None: debug_recorder = ReachHelperDebugRecorder(robot=self.robot) next_tick_sec = time.time() elapsed_time = 0.0 robot_autosteps = getattr(self.robot, "autostep", False) robot_runs_in_real_time = not robot_autosteps while elapsed_time < run_params.timeout: def add_debug_log(reason: str) -> None: """Mini-helper function to add an entry that will be logged if requested or if reach fails. :param reason: Reason why we are logging the entry. """ old_precision = np.get_printoptions()["precision"] np.set_printoptions(precision=3, suppress=True) obspos = self.robot.joint_positions_to_control( self.observation.joint_positions() ) obsvel = self.observation.joint_velocities() distance = target_position_control - obspos log_entry = ( f"{elapsed_time:.3f}) {reason} | " f"Stopped:{self._is_robot_stopped_and_stable()}, " f"Reached:{self._is_position_reached(target_position_control)}, " f"Delta:{delta_secs} sec, " f"RunRealTime:{robot_runs_in_real_time}" f"\nMaxSpeed:{max_speed_per_delta_per_control}/step | " f"{run_params.max_speed_per_sec}/sec, " f"\nTarget :{target_position_control}, Distance: {distance}" f"\nNext cmd :{next_position}" f"\nObsPos :{obspos}" f"\nObsVel :{obsvel}" f"\n" ) assert debug_recorder is not None debug_recorder.add_log(log_entry) np.set_printoptions(precision=old_precision, suppress=False) # wait until it's time to control the robot: # for physical or remote robots, we wait real time with a resolution of nanoseconds, since the real robot # or the remote server both run at real time rates. For mujoco/simulated robots, which don't run at real # time rate, we only support auto-stepping ones at the moment (we could also tick the simulation.) Note # that since we break down steps based on `self.robot.get_control_time_delta()`, but we tick each frame # for auto-stepping robots, for the deltas to match, `self.robot.get_control_time_delta()` should be # equal to the time it elapses with one call to `_set_position_control()`. Otherwise we will be sending # deltas scoped for the robot delta, at simulation delta rates. if robot_runs_in_real_time: tick_time_sec = time.time() remaining_delta = next_tick_sec - tick_time_sec if remaining_delta > 0: time.sleep(remaining_delta) next_tick_sec = ( next_tick_sec + delta_secs ) # update when the next tick will be # observe self._observe() # check if we have actually reached the destination with the robot stopped if self._is_robot_stopped_and_stable(): # if we have not reached the goal, check whether we have moved at all (via minimum_time_to_move) is_position_reached = self._is_position_reached(target_position_control) has_minimum_time_passed = ( elapsed_time >= self.config.minimum_time_to_move ) if is_position_reached or has_minimum_time_passed: # robot is not moving after min, either we reached the destination or robot will not move at all add_debug_log("ExitCond") break # send command to move as much as possible during a delta next_position = generated_deltas[next_delta] next_delta = ( next_delta if next_delta == len(generated_deltas) - 1 else next_delta + 1 ) self._set_position_control(next_position) elapsed_time = self.observation.timestamp() - local_start_time obs_helper_pos = None if hasattr(self.robot, "get_helper_robot"): obs_helper_pos = ( self.robot.get_helper_robot().observe().joint_positions() ) # type:ignore add_debug_log("TickEnd") debug_recorder.add_sample( elapsed_time, next_position, self.robot.joint_positions_to_control( self.observation.joint_positions() ), self.observation.joint_velocities(), obs_helper_pos=obs_helper_pos, ) # call the iteration callback now if iteration_callback is not None: iteration_callback() # Just format and return the result of reach operation observed_control_positions = self.robot.joint_positions_to_control( self.observation.joint_positions() ) observed_joint_velocities = self.observation.joint_velocities() is_position_reached = self._is_position_reached(target_position_control) is_robot_stopped = self._is_robot_stopped_and_stable() # if we failed, configure logs and plots so that they get dumped if not is_position_reached: logger.info( "*** ReachHelper did not reach its destination. Will dump logs and plots automatically." ) debug_enable_logs = True if not debug_plots_output.is_enabled(): debug_plots_output = PlotOutput.FILE # log if required if debug_enable_logs: debug_recorder.dump_logs() # plot if required if debug_plots_output.is_enabled(): for act_index, act in enumerate(self.robot.actuators()): debug_recorder.plot_pos_and_vel_for_actuator( act_index, debug_plots_output, debug_plots_data_unit, debug_plots_view_unit, debug_reach_try_id, ) # output: display all to screen now (if required) if (debug_plots_output & PlotOutput.SCREEN).value != 0: plt.show() return ReachResult( reached=is_position_reached, robot_stopped=is_robot_stopped, desired_joint_positions=target_position_control, last_joint_positions=observed_control_positions, last_joint_velocities=observed_joint_velocities, position_threshold=self.config.reached_position_threshold, velocity_threshold=self.config.stopped_velocity_threshold, ) def reach_position( robot: Robot, position_control: np.ndarray, *, timeout: float = 10.0, minimum_time_to_move: float = 2.0, speed_units_per_sec: Optional[Union[float, np.ndarray]] = None, position_threshold: Optional[float] = None, measurement_unit: MeasurementUnit = MeasurementUnit.RADIANS, debug_recorder: Optional[ReachHelperDebugRecorder] = None, iteration_callback: Optional[Callable[[], None]] = None, ) -> ReachResult: """Perform given movement of a hand to desired position. :param robot: Robot interface that will perform the movements. :param position_control: Target positions for actuators in the robot. Note that the target position needs to be in the same units specified by the 'measurement_unit' parameter. :param timeout: Maximum time allowed to reach the target positions and stop the robot, before we consider it failed. In seconds. :param minimum_time_to_move: If we haven't reached target positions, wait at least for this amount of time for the joints to start moving, before thinking the robot will never move. In seconds. :param speed_units_per_sec: If specified as float or np.array, the speed at which we want to generate deltas to move the robot (similar to the expected robot output speed). If not provided, it is set to a sensitive speed that depends on the 'measurement_unit' parameter. If specified as float, the speed is shared among all controls. If specified as np.array, the shape must match the shape of the controls, so that each speed limit applies to one control. :param position_threshold: If specified, the threshold in position so that we can claimed that we have reached the target position. If not provided, a default one will be set for the measurement unit provided. :param measurement_unit: Measurement unit the robot actuators operate in. :param debug_recorder: Optional instance where records will be added so that they can be inspected outside this function. :param iteration_callback: Optional callback to call on each iteration of the reach helper. This iteration timing depends on whether the robot is simulated or real, but should it match the control delta configured for physical robots, or the simulation step size for simulated robots. :return: Result of the reach operation. See class for more details. """ # default parameters depend on measurement unit default_config = { MeasurementUnit.RADIANS: ReachHelperConfigParameters( reached_position_threshold=np.deg2rad(1), stopped_velocity_threshold=np.deg2rad(1), stopped_stable_time=0.5, safety_speed_limit=np.deg2rad(60), minimum_time_to_move=0.0, ), MeasurementUnit.METERS: ReachHelperConfigParameters( reached_position_threshold=0.005, stopped_velocity_threshold=0.001, stopped_stable_time=0.5, safety_speed_limit=0.050, minimum_time_to_move=0.0, ), } default_run_params = { MeasurementUnit.RADIANS: ReachHelperRunParameters( timeout=0.0, max_speed_per_sec=np.deg2rad(30) ), MeasurementUnit.METERS: ReachHelperRunParameters( timeout=0.0, max_speed_per_sec=0.025 ), } # get default config and override as needed cur_config = default_config[measurement_unit] cur_config.minimum_time_to_move = minimum_time_to_move cur_config.reached_position_threshold = ( cur_config.reached_position_threshold if position_threshold is None else position_threshold ) # get default run params and override as needed run_params = default_run_params[measurement_unit] run_params.timeout = timeout # speed is complicated, allow first setting from argument passed to this method. If not set, ask the robot if # it has one (since each robot could have a different one), otherwise use the default one that was configured here # for the measurement unit if speed_units_per_sec is not None: run_params.max_speed_per_sec = speed_units_per_sec elif hasattr(robot, "get_default_reach_helper_speed"): run_params.max_speed_per_sec = robot.get_default_reach_helper_speed() # type: ignore # reach_helper does not support mixed control units at this moment. For example, for TCP controlled robots it # would need to move TCP xyz (meters/millimeters) and TCP rot (radians/degrees). For now, identify the issue and # hack those robots so that instead the use Joint commands. This will change in the future, but allows # requesting a Joint destination for TCP controlled arms assert hasattr(robot, "switch_to_joint_control") == hasattr( robot, "switch_to_tcp_control" ) if hasattr(robot, "switch_to_joint_control"): robot.switch_to_joint_control() # type: ignore try: reach_helper = ReachHelper(robot, config=cur_config) ret_val = reach_helper.reach( target_position_control=position_control, run_params=run_params, debug_recorder=debug_recorder, iteration_callback=iteration_callback, ) finally: # restore tcp control mode if hasattr(robot, "switch_to_tcp_control"): robot.switch_to_tcp_control() # type: ignore return ret_val def reach_wrist_angle( robot: Robot, wrist_angle: float, Kp: int = 1, max_steps=100, speed_limit: float = np.deg2rad(30), atol=1e-2, ) -> bool: """ Helper for a FreeWristTcpArm robot to achieve a desired wrist position. Since wrist control is relative and no position controllers exist, this is done using a simple proportional control. :param robot: a FreeWristTcpArm robot :param robot: wrist displacement limit in radians per step :param wrist_angle: desired absolute wrist angle :param Kp: Proportional gain coefficient :param max_steps: Maximum steps for reach :param atol: Absolute tolerance for rech result :return: Reach state """ step = 0 ctrl = robot.zero_control() error = wrist_angle - robot.observe().joint_positions()[-1] reached = np.abs(error) < atol while step < max_steps and not reached: angle_ctrl = Kp * np.clip(error, -speed_limit, speed_limit) ctrl[-1] = angle_ctrl robot.set_position_control(ctrl) error = wrist_angle - robot.observe().joint_positions()[-1] reached = np.abs(error) < atol step += 1 return reached
34,011
43.576671
120
py
robogym
robogym-master/robogym/robot/utils/robot_utils.py
"""Utilities that expand robot interface's capabilities, but that do not necessarily belong to the interface itself.""" from typing import Dict, Iterable, Optional, Type import numpy as np from robogym.robot.robot_interface import Robot def denormalize_actions( robot: Robot, input_actions: Iterable[Dict[str, float]], defaults: Optional[np.ndarray] = None, ) -> np.ndarray: """ Transform position control from the [-1,+1] range into supported joint position range in radians, where 0 represents the midpoint between two extreme positions, for the supplied actuators only, using default values for non-supplied actuators. To supply the actuators to denormalize, provide a dictionary or a batch of dictionaries with the actuator as the key, and the [-1,+1] value as entry value. :param robot: Robot for which we want to denormalize actions. :param input_actions: Batch of dictionaries with actuator as key, and normalized value as value. :param defaults: Default values for actuators not specified in actions. 0 if not set. :return: Batch of arrays with denormalized values for actuators specified in the dictionary and 0 for actuators not specified in the dictionary. """ robot_actuators = robot.actuators() if defaults is None: defaults = robot.zero_control() assert defaults.shape == (len(robot_actuators),) ctrls = [] # for each entry in the batch for action_overrides in input_actions: # create array with desired values for specified actuators normal_positions = np.zeros(len(robot_actuators)) for actuator, value in action_overrides.items(): assert actuator in robot_actuators actuator_id = robot_actuators.index(actuator) normal_positions[actuator_id] = value # denormalize array denormalized_positions = robot.denormalize_position_control(normal_positions) # generate output with denormalized positions only for controls that were specified, and default otherwise ctrl = defaults.copy() for actuator in action_overrides: actuator_id = robot_actuators.index(actuator) ctrl[actuator_id] = denormalized_positions[actuator_id] ctrls.append(ctrl) return np.asarray(ctrls) def find_robot_by_class( top_robot: Robot, desired_class: Type[Robot] ) -> Optional[Robot]: """Examines the given robot to retrieve the first instance that matches the specified desired class. This includes searching in the children of a CompositeRobot. :param top_robot: Robot to search in. This robot can also match the desired class. :param desired_class: Desired specific class we are searching for. :return: First robot found that matches the desired class, or None if no matches are found. """ desired_robot = None from robogym.robot.composite.composite_robot import CompositeRobot if isinstance(top_robot, CompositeRobot): for internal_robot in top_robot.robots: if isinstance(internal_robot, desired_class): desired_robot = internal_robot break elif isinstance(top_robot, desired_class): desired_robot = top_robot return desired_robot
3,272
39.407407
119
py
robogym
robogym-master/robogym/robot/utils/logistic_functions.py
""" Logistic functions Function List: 1. logistic_sigmoid(x: float, a: float) -> float: calculate the normalized logistic sigmoid with slope parameter a 2. clipped_logistic_sigmoid(x: float, a: float) -> float: calculate the normalized logistic sigmoid with slope parameter a clipped to a [0, 1] output range """ import numpy as np def logistic_sigmoid(x: float, a: float) -> float: """ Calculates the normalized logistic sigmoid as a function of x with parameterization on a This function will be symmetric about 0.5 :param x: input value for calculation. Range: -inf to inf will not clip at values to 0 and 1 outside of the 0 to 1 input range :param a: value of the slope of the sigmoid. Values range from 0.5 for slope ~ 1 to 1.0 for slope ~ infinity. There's very little signal at a < 0.5 :return: the value of the normalized logistic sigmoid at x """ # set epsilon to be small. this is so we don't have divide by zero conditions epsilon: float = 0.0001 # clip a to be between (0 + epsilon) and (1 - epsilon) min_param_a: float = 0.0 + epsilon max_param_a: float = 1.0 - epsilon a = np.maximum(min_param_a, np.minimum(max_param_a, a)) # set a to be asymptotic at 1 and zero at 0 a = 1 / (1 - a) - 1 # calculate the numerator and denominator terms for the normalized sigmoid A: float = 1.0 / (1.0 + np.exp(0 - ((x - 0.5) * a * 2.0))) B: float = 1.0 / (1.0 + np.exp(a)) C: float = 1.0 / (1.0 + np.exp(0 - a)) y: float = (A - B) / (C - B) return y def clipped_logistic_sigmoid(x: float, a: float) -> float: """ Calculates the normalized logistic sigmoid as a function of x with parameterization on a This function will be symmetric about 0.5 :param x: input value for calculation range: Range: -inf to inf, effective range 0 to 1 will output 0 for values below 0 and 1 for values above 1 :param a: value of the slope of the sigmoid. Values range from 0.5 for slope ~ 1 to 1.0 for slope ~ infinity. There's very little signal at a < 0.5 :return: the value of the normalized logistic sigmoid at x """ # clip values below zero and above one x = np.maximum(x, 0.0) x = np.minimum(x, 1.0) # set epsilon to be small. this is so we don't have divide by zero conditions epsilon: float = 0.0001 # clip a to be between (0 + epsilon) and (1 - epsilon) min_param_a: float = 0.0 + epsilon max_param_a: float = 1.0 - epsilon a = np.maximum(min_param_a, np.minimum(max_param_a, a)) # set a to be asymptotic at 1 and zero at 0 a = 1 / (1 - a) - 1 # calculate the numerator and denominator terms for the normalized sigmoid A: float = 1.0 / (1.0 + np.exp(0 - ((x - 0.5) * a * 2.0))) B: float = 1.0 / (1.0 + np.exp(a)) C: float = 1.0 / (1.0 + np.exp(0 - a)) y: float = (A - B) / (C - B) return y
2,944
37.246753
99
py
robogym
robogym-master/robogym/robot/utils/tests/test_reach_helper.py
"""Unit tests for Reach Helper.""" import logging import time from typing import Union import numpy as np from robogym.robot.utils import reach_helper from robogym.robot.utils.measurement_units import MeasurementUnit from robogym.robot.utils.reach_helper import ReachHelperDebugRecorder logger = logging.getLogger(__name__) def assert_speed_is_ok( _debug_recorder: ReachHelperDebugRecorder, _expected_speed: Union[float, np.ndarray], _speed_limit_threshold: Union[float, np.ndarray], ) -> None: """This function inspects the speed samples from the given recorder (for all controls), and asserts whether all are within the desired speed limit. :param _debug_recorder: Recorder to check velocity samples. :param _expected_speed: Speed limit that we set in the reach helper for the command generation. :param _speed_limit_threshold: Small threshold that the robot would potentially pass above the commanded expected speed, since reaction time will have a catch-up effect on the robot, which may cause speed to increase over the commanded speed briefly. """ # prepare speed limit actuator_count = len(_debug_recorder.robot.actuators()) if np.isscalar(_expected_speed): _expected_speed = np.full(actuator_count, _expected_speed) if np.isscalar(_speed_limit_threshold): _speed_limit_threshold = np.full(actuator_count, _speed_limit_threshold) speed_limit = _expected_speed + _speed_limit_threshold # compare observed vs limit max_obs_speed_per_control = np.max(np.abs(_debug_recorder.obs_vel), axis=0) limit_ok_per_control = max_obs_speed_per_control < speed_limit was_speed_ok = np.alltrue(limit_ok_per_control) # assert/print relevant info random_id = str(time.time()) if not was_speed_ok: logger.info( "Speed limit violation, will dump plots of the samples for debugging:" ) for act_idx in range(len(_debug_recorder.obs_pos[0])): _debug_recorder.plot_pos_and_vel_for_actuator( act_idx, reach_helper.PlotOutput.FILE, MeasurementUnit.RADIANS, MeasurementUnit.DEGREES, f"test_reach_helper_{random_id}", ) assert ( was_speed_ok ), f"Speed limit violation: \n{max_obs_speed_per_control} \nvs \n{speed_limit}" def _build_reach_helper_test_robot(max_position_change=0.020): from gym.envs.robotics import utils from robogym.envs.rearrange.simulation.blocks import ( BlockRearrangeSim, BlockRearrangeSimParameters, ) from robogym.robot.robot_interface import ControlMode, RobotControlParameters sim = BlockRearrangeSim.build( n_substeps=20, robot_control_params=RobotControlParameters( control_mode=ControlMode.TCP_WRIST.value, max_position_change=max_position_change, ), simulation_params=BlockRearrangeSimParameters(), ) # reset mocap welds if any. This is actually needed for TCP arms to move utils.reset_mocap_welds(sim.mj_sim) # extract arm since CompositeRobots are not fully supported by reach_helper composite_robot = sim.robot arm = composite_robot.robots[0] arm.autostep = True return arm def test_curve_generation_two_steps() -> None: """This test is used to verify a bugfix. The bug was that if a target's distance is too close to the current position (closer than the max speed), the curve would only generate one step for the actuator, and the step would be for the current position, not for the target position. Bugfix: reach helper should generate at least two steps. """ robot = _build_reach_helper_test_robot() cur_pos = robot.observe().joint_positions() # calculate the small step that was bugged control_delta = robot.get_control_time_delta() max_speed = np.deg2rad(60) max_change_per_step = max_speed * control_delta offset_that_was_bugged = max_change_per_step - np.deg2rad( 0.01 ) # offset needs to be below max_change_per_step position_threshold = offset_that_was_bugged - np.deg2rad( 0.01 ) # threshold needs to be below the offset assert position_threshold < offset_that_was_bugged target_pos = cur_pos.copy() target_pos[0] += offset_that_was_bugged ret_i = reach_helper.reach_position( robot, target_pos, speed_units_per_sec=max_speed, position_threshold=position_threshold, ) assert ret_i.reached
4,558
36.677686
114
py
robogym
robogym-master/robogym/robot/lib/parameter_configurer.py
from typing import Dict class ParameterConfigurer: def parameter_bounds(self, actuator: str): """Get valid parameter bounds for the given actuator.""" pass def current_parameters(self, actuator: str) -> Dict[str, float]: """Get current parameters for the given actuator.""" pass def set_parameters(self, actuator: str, assignments: Dict[str, float]): """Set parameters for the given actuator.""" pass def export_parameters(self): """Export current parameters. For example, save parameters to XML or JSON configuration file.""" pass
626
27.5
75
py
robogym
robogym-master/robogym/robot/ur16e/arm_interface.py
import abc from typing import Optional import numpy as np from robogym.robot.robot_interface import Robot ACTUATOR_CTRLRANGE = { "A_J1": [-6.1959, 6.1959], # DEGREES (-355, 355) "A_J2": [-6.1959, 6.1959], # DEGREES (-355, 355) "A_J3": [-2.7925, 2.7925], # DEGREES (-160, 160) "A_J4": [-6.1959, 6.1959], # DEGREES (-355, 355) "A_J5": [-6.1959, 6.1959], # DEGREES (-355, 355) "A_J6": [-6.1959, 6.1959], # DEGREES (-355, 355) } ACTUATORS = [ "A_J1", "A_J2", "A_J3", "A_J4", "A_J5", "A_J6", ] # A good initial setting for Arm joint angles for a tabletop experiment performed with # the UR arm TABLETOP_EXPERIMENT_INITIAL_POS = np.deg2rad(np.array([135, -90, 135, -100, -240, 135])) ACTUATOR_CTRLRANGE_LOWER_BOUND = np.array( [ACTUATOR_CTRLRANGE[key][0] for key in ACTUATORS] ) """ Actuator position controls vector for the lower bound of actuator control range. """ ACTUATOR_CTRLRANGE_UPPER_BOUND = np.array( [ACTUATOR_CTRLRANGE[key][1] for key in ACTUATORS] ) """ Actuator position controls vector for the upper bound of actuator control range. """ """ Force threshold in Newtons to apply to robot for safety stops. """ SAFETY_STOP_FORCE_THRESHOLD = 150 class Arm(Robot, abc.ABC): # speed limit for joints/actuators that we want to move slowly SLOW_ACTUATOR_SPEED = np.deg2rad(30) # speed limit for joints/actuators that we want to move faster FAST_ACTUATOR_SPEED = np.deg2rad(60) # reach_helper format for speed limits, one per actuator/joint REACH_HELPER_DEFAULT_SPEED = np.asarray( [*np.repeat(SLOW_ACTUATOR_SPEED, 5), FAST_ACTUATOR_SPEED] ) @classmethod def actuators(cls) -> np.ndarray: return np.asarray(ACTUATORS) @classmethod def joint_positions_to_control(cls, joint_pos: np.ndarray) -> np.ndarray: return joint_pos def actuator_ctrl_range_upper_bound(self) -> np.ndarray: return ACTUATOR_CTRLRANGE_UPPER_BOUND def actuator_ctrl_range_lower_bound(self) -> np.ndarray: return ACTUATOR_CTRLRANGE_LOWER_BOUND def get_default_reach_helper_speed(self) -> np.ndarray: """Returns the speed per actuator that the reach helper should use unless configured to use something different. Note that it's specified as joint/actuator speed since all UR arms are used with joint control under reach helper control. :return: The speed per joint that the reach helper should use unless configured to use something different. """ return self.REACH_HELPER_DEFAULT_SPEED def get_robot_transform(self) -> Optional[np.ndarray]: """Return robot current configured world transformation (if any). For mujoco robot this can be the world coordinates of the base of the robot. Physical robots return their observations in local coordinates. However, we generally want the coordinates to be in mujoco space. This is more a convention for our convenience, since debugging coordinates in world space can be more comfortable. This transformation allows us to return the observations in world space from the robot itself, without having to replicate transformation in all systems that consume world coordinates. Note however that there is no such thing as world coordinates for physical robots unless an origin is defined for 'world'. That is what we do here, and it generally matches that of an environment. :return: Return robot current configured world transformation (if any). For mujoco robot this can be the world coordinates of the base of the robot. """ return None
3,669
36.835052
115
py
robogym
robogym-master/robogym/robot/ur16e/mujoco/joint_controlled_arm.py
from typing import Optional import numpy as np from robogym.mujoco.simulation_interface import SimulationInterface from robogym.robot.robot_interface import RobotControlParameters, RobotObservation from robogym.robot.ur16e.arm_interface import ( SAFETY_STOP_FORCE_THRESHOLD, TABLETOP_EXPERIMENT_INITIAL_POS, Arm, ) from robogym.robot.ur16e.mujoco.simulation.base import ArmSimulationInterface from robogym.utils import rotation FINGERTIP_SITE_NAME = "ur_centerplate" TCP_BODY_NAME = "gripper_tcp" class MujocoObservation(RobotObservation): """ UR Arm observation coming from the MuJoCo simulation """ def __init__( self, simulation: SimulationInterface, hand_prefix: str, joint_group: str ): sim = simulation.mj_sim self._joint_positions = simulation.get_qpos(joint_group).copy() self._joint_controls = sim.data.ctrl[:6] self._time = sim.data.time self._joint_velocities = simulation.get_qvel(joint_group).copy() self._tcp_xyz = sim.data.get_body_xpos(f"{hand_prefix}{TCP_BODY_NAME}").copy() self._tcp_vel = sim.data.get_body_xvelp(f"{hand_prefix}{TCP_BODY_NAME}").copy() quat = sim.data.get_body_xquat(f"{hand_prefix}{TCP_BODY_NAME}").copy() self._tcp_rot = rotation.quat2euler(quat) sensordata = sim.data.sensordata.copy() force_sensor_id = simulation.mj_sim.model.sensor_name2id("toolhead_force") sensor_adr = sim.model.sensor_adr[force_sensor_id] sensor_dim = sim.model.sensor_dim[force_sensor_id] self._tcp_force = sensordata[sensor_adr: sensor_adr + sensor_dim] torque_sensor_id = simulation.mj_sim.model.sensor_name2id("toolhead_torque") sensor_adr = sim.model.sensor_adr[torque_sensor_id] sensor_dim = sim.model.sensor_dim[torque_sensor_id] self._tcp_torque = sensordata[sensor_adr: sensor_adr + sensor_dim] def timestamp(self): return self._time def joint_positions(self) -> np.ndarray: return self._joint_positions def joint_controls(self) -> np.ndarray: return self._joint_controls def joint_velocities(self) -> np.ndarray: return self._joint_velocities def tcp_xyz(self) -> np.ndarray: """ :return: Tooltip position in the Cartesian coordinate space.""" return self._tcp_xyz def tcp_vel(self) -> np.ndarray: """ :return: Tooltip velocity in the Cartesian coordinate space.""" return self._tcp_vel def tcp_rot(self) -> np.ndarray: """Rotation in euler angles.""" return self._tcp_rot def tcp_force(self) -> np.ndarray: """:return: TCP force in world coordinates.""" return self._tcp_force def tcp_torque(self) -> np.ndarray: """:return: TCP torque in world coordinates.""" return self._tcp_torque def is_in_safety_stop(self) -> bool: """Returns always false since mujoco arms don't currently have safety stops. :return: True if the arm is in a safety stop, False otherwise. """ tcp_force = self.tcp_force() return np.linalg.norm(tcp_force) > SAFETY_STOP_FORCE_THRESHOLD class JointControlledArm(Arm): """ Mujoco implementation of a joint-actuated UR 16e arm. """ def __init__( self, simulation: ArmSimulationInterface, robot_control_params: RobotControlParameters, robot_prefix="robot0:", autostep=False, **kwargs, ): """ :param simulation: simulation interface for the mujoco UR arm :param robot_control_params: Robot control parameters :param robot_prefix: prefix to add to the joint names while constructing the mujoco simulation :param autostep: when true, calls step() on the simulation whenever a control is set. this should only be used only when the Robot is being controlled without a simulationrunner in the loop. """ self.simulation = simulation self.robot_prefix = robot_prefix self.autostep = autostep self.joint_group = robot_prefix + "arm_joint_angles" self.simulation.register_joint_group( self.joint_group, prefix=robot_prefix + "J" ) self.set_simulation_start_position(TABLETOP_EXPERIMENT_INITIAL_POS) self._max_position_change = robot_control_params.max_position_change # Note: This could be automatically set for all simulated robots using keyframes from the xml, but it would # still require the Simulation to know which keyframe to apply (eg: default, experiment, phys_check, ..) # See http://www.mujoco.org/book/XMLreference.html#keyframe def set_simulation_start_position(self, pos: np.ndarray) -> None: """Sets simulation qpos and ctrl. Intended to be used as a way to set the initial position for the arm in the mujoco simulation. :param pos: Joint positions, also set in the controls. """ self.simulation.set_qpos(self.joint_group, pos) self.mj_sim.data.ctrl[ :6 ] = pos # otherwise the robot will try to go to the last control set if not commanded def get_control_time_delta(self) -> float: """Returns the delta that the robot wants to be controlled under, by matching it with its mujoco simulation step delta. :return: Returns the delta that the robot wants to be controlled under, by matching it with its mujoco simulation step delta. """ dt = self.mj_sim.nsubsteps * self.mj_sim.model.opt.timestep return dt def get_robot_transform(self) -> Optional[np.ndarray]: """Return the robot transformation wrt its mujoco world. Coordinates are (xyz + rot_quat). :return: Return the robot transformation wrt its mujoco world. """ robot_xyz = self.mj_sim.data.get_body_xpos( f"{self.robot_prefix}base_link" ).copy() robot_quat = self.mj_sim.data.get_body_xquat( f"{self.robot_prefix}base_link" ).copy() return np.concatenate((robot_xyz, robot_quat)) def get_name(self) -> str: """Returns a name, expected to uniquely identify this robot within our environments. Examples would be: ALPHA, EPSILON, etc. for hands, and UR16e-ONE for UR16 arms.""" return "mujoco-ur16e" # note that all mujoco arms will have the same name def actuator_ctrl_range_upper_bound(self) -> np.ndarray: # We use control range in xml instead of constants to take into account # ADR randomization for joint limit. return self.mj_sim.model.actuator_ctrlrange[:6, 1] def actuator_ctrl_range_lower_bound(self) -> np.ndarray: # We use control range in xml instead of constants to take into account # ADR randomization for joint limit. return self.mj_sim.model.actuator_ctrlrange[:6, 0] @property def mj_sim(self): """ MuJoCo MjSim simulation object """ return self.simulation.mj_sim @property def max_position_change(self): return self._max_position_change def set_position_control(self, control: np.ndarray) -> None: self.mj_sim.data.ctrl[:6] = control if self.autostep: self.mj_sim.step() def observe(self) -> MujocoObservation: return MujocoObservation(self.simulation, self.robot_prefix, self.joint_group) def reset(self) -> None: self.set_simulation_start_position(TABLETOP_EXPERIMENT_INITIAL_POS)
7,534
38.450262
121
py
robogym
robogym-master/robogym/robot/ur16e/mujoco/free_dof_tcp_arm.py
from typing import Dict, List, Optional import numpy as np from robogym.robot.control.tcp.mocap_solver import MocapSolver from robogym.robot.control.tcp.solver import PrincipalAxis from robogym.robot.robot_interface import RobotControlParameters, TcpSolverMode from robogym.robot.ur16e.arm_interface import Arm from robogym.robot.ur16e.mujoco.joint_controlled_arm import MujocoObservation from robogym.robot.ur16e.mujoco.simulation.base import ArmSimulationInterface # speed factors that are scaled by the max_position_change. DOF_DIM_SPEED_SCALE: Dict[PrincipalAxis, float] = { PrincipalAxis.ROLL: np.deg2rad(200), PrincipalAxis.PITCH: np.deg2rad(600), PrincipalAxis.YAW: np.deg2rad(300), } class FreeDOFTcpArm(Arm): """ Mujoco implementation of a tool center point (TCP) actuated UR 16e arm with a user-defined set of quaternion DOFs. """ JOINT_DRIFT_THRESHOLD = np.deg2rad( 1 ) # an additional buffer to prevent us from hitting joint range DOF_DIMS: List[PrincipalAxis] = [] ALIGN_AXIS: Optional[PrincipalAxis] = None def __init__( self, simulation: ArmSimulationInterface, robot_control_params: RobotControlParameters, initial_qpos: Optional[List], robot_prefix="robot0:", autostep=False, ): """ :param simulation: simulation interface for the mujoco robot. :param robot_control_params: Robot control parameters :param initial_qpos: The initial valueto be applied to the simulation. :param robot_prefix: prefix to add to the joint names while constructing the mujoco simulation. :param autostep: when true, calls step() on the simulation whenever a control is set. this should only be used only when the Robot is being controlled without a simulation runner in the loop. """ super().__init__() self.simulation = simulation self.robot_prefix = robot_prefix self.autostep = autostep self.joint_group = robot_prefix + "arm_joint_angles" self.simulation.register_joint_group( self.joint_group, prefix=robot_prefix + "J" ) if initial_qpos is not None: self.simulation.set_qpos(self.joint_group, initial_qpos) self.simulation.forward() assert ( robot_control_params.max_position_change and robot_control_params.max_position_change > 0.0 ), "Position multiplier must be a positive number" self._max_position_change = robot_control_params.max_position_change self.speed_per_dof_dim = [ DOF_DIM_SPEED_SCALE[axis] * self._max_position_change for axis in self.DOF_DIMS ] self.is_in_joint_control_mode = False tcp_solver_mode = robot_control_params.tcp_solver_mode assert ( tcp_solver_mode is TcpSolverMode.MOCAP ), f"Invalid solver mode: {tcp_solver_mode}" self.solver = MocapSolver( simulation=self.simulation, body_name="robot0:gripper_tcp", robot_prefix=self.robot_prefix, quat_dof_dims=self.DOF_DIMS, alignment_axis=self.ALIGN_AXIS, ) def get_name(self) -> str: return "unnamed-mujoco-ur16e-tcp-arm" def switch_to_joint_control(self) -> None: """Set flag so that commands are now interpreted as joint space commands. See reach_helper for details on why this is necessary.""" self.is_in_joint_control_mode = True def switch_to_tcp_control(self) -> None: """Set flag so that commands are now interpreted as TCP space commands. See reach_helper for details on why this is necessary.""" self.is_in_joint_control_mode = False @property def mj_sim(self): """ MuJoCo MjSim simulation object """ return self.simulation.mj_sim def get_control_time_delta(self) -> float: """Returns the delta that the robot wants to be controlled under, by matching it with its mujoco simulation step delta. :return: Returns the delta that the robot wants to be controlled under, by matching it with its mujoco simulation step delta. """ dt = self.mj_sim.nsubsteps * self.mj_sim.model.opt.timestep return dt def zero_control(self): return np.zeros(3 + len(self.DOF_DIMS)) def get_robot_transform(self) -> Optional[np.ndarray]: """Return the robot transformation wrt its mujoco world. Coordinates are (xyz + rot_quat). :return: Return the robot transformation wrt its mujoco world. """ robot_xyz = self.mj_sim.data.get_body_xpos( f"{self.robot_prefix}base_link" ).copy() robot_quat = self.mj_sim.data.get_body_xquat( f"{self.robot_prefix}base_link" ).copy() return np.concatenate((robot_xyz, robot_quat)) def constrain_quat_ctrl(self, ctrl: np.ndarray): """ Constrain quat control if the solver defines a mapping between control dimensions and joints :param ctrl: :return: """ joint_ids = self.solver.get_joint_mapping() if not any(joint_ids): return ctrl joint_ids_mask = [i for i, v in enumerate(joint_ids) if v is not None] joint_mask = np.array(joint_ids[joint_ids_mask], dtype=np.int8) joint_pos = self.observe().joint_positions()[joint_mask] ctrl[joint_ids_mask] = np.clip( ctrl[joint_ids_mask], self.actuator_ctrl_range_lower_bound()[joint_mask] + self.JOINT_DRIFT_THRESHOLD - joint_pos, self.actuator_ctrl_range_upper_bound()[joint_mask] - self.JOINT_DRIFT_THRESHOLD - joint_pos, ) return ctrl @property def max_position_change(self): return self._max_position_change def denormalize_position_control( self, position_control: np.ndarray, relative_action: bool = False, ) -> np.ndarray: # if in joint control, delegate on parent if self.is_in_joint_control_mode: raise NotImplementedError( "Denormalization is not implemented with joint controls." ) if relative_action and self.max_position_change is not None: return np.concatenate( ( position_control[:3] * self.max_position_change, np.multiply(position_control[3:], self.speed_per_dof_dim), ) ) else: return position_control def set_position_control(self, control: np.ndarray) -> None: # if in joint control, directly apply to the position if self.is_in_joint_control_mode: self.mj_sim.data.qpos[:6] = control if self.autostep: self.solver.reset() self.mj_sim.step() return # Arm action space is TCP position [x,y,z] + arm wrist angle. assert control.shape == ( len(self.zero_control()), ), f"{control} vs {self.zero_control()}" pos, angle = np.split(control, (3,)) angle = self.constrain_quat_ctrl(angle) quat_ctrl = self.solver.get_tcp_quat(angle) agg_control = np.concatenate([pos, quat_ctrl]) agg_control = np.array(agg_control, dtype=np.double) self.solver.set_action(agg_control) if self.autostep: self.mj_sim.step() def observe(self) -> MujocoObservation: return MujocoObservation(self.simulation, self.robot_prefix, self.joint_group) def get_joint_state(self) -> np.ndarray: return self.observe().joint_positions() def sync_to( self, joint_positions: np.ndarray, joint_controls: Optional[np.ndarray] ): """Update this arm to the given position and control. Update from values rather than observations so that we can sync from any observation providers. :param joint_positions: Arm position. :param joint_controls: Arm control target. Currently unused since this arm will be controlled during the tick. """ self.simulation.set_qpos(self.joint_group, joint_positions) self.mj_sim.forward() def reset(self) -> None: self.solver.reset() def actuator_ctrl_range_upper_bound(self) -> np.ndarray: # We use the joint range in xml since there are no actuators for this arm. return self.mj_sim.model.jnt_range[:6, 1] def actuator_ctrl_range_lower_bound(self) -> np.ndarray: # We use the joint range in xml since there are no actuators for this arm. return self.mj_sim.model.jnt_range[:6, 0] class FreeWristTcpArm(FreeDOFTcpArm): DOF_DIMS = [PrincipalAxis.PITCH] # WARNING: We share here the notation RPY with PrincipalAxis, but current code may use this wrt world axes, which # don't necessarily map those of the arm/tcp/gripper. # TODO Fix this alignment disparity ALIGN_AXIS = PrincipalAxis.PITCH class FreeRollYawTcpArm(FreeDOFTcpArm): """ TCP with DOF for roll and yaw. This mode currently is only supported using the MocapJoint solver. """ DOF_DIMS = [PrincipalAxis.ROLL, PrincipalAxis.PITCH]
9,329
35.588235
121
py
robogym
robogym-master/robogym/robot/ur16e/mujoco/ideal_joint_controlled_tcp_arm.py
from typing import Optional import numpy as np from robogym.mujoco.simulation_interface import SimulationInterface from robogym.robot.factories import build_tcp_controller from robogym.robot.robot_interface import RobotControlParameters from robogym.robot.ur16e.arm_interface import TABLETOP_EXPERIMENT_INITIAL_POS, Arm from robogym.robot.ur16e.mujoco.free_dof_tcp_arm import FreeDOFTcpArm from robogym.robot.ur16e.mujoco.joint_controlled_arm import MujocoObservation from robogym.robot.ur16e.mujoco.simulation.base import ArmSimulationInterface class IdealJointControlledTcpArm(Arm): """ An "ideal" joint controlled arm that can immediately achieve the positions that are achieved by its controller_arm. """ def __init__( self, simulation: SimulationInterface, robot_control_params: RobotControlParameters, solver_simulation: ArmSimulationInterface, robot_prefix="robot0:", autostep=False, ): """ :param simulation: simulation interface for the mujoco UR arm :param robot_control_params: Robot control parameters :param robot_prefix: prefix to add to the joint names while constructing the mujoco simulation :param autostep: when true, calls step() on the simulation whenever a control is set. this should only be used only when the Robot is being controlled without a simulationrunner in the loop. """ assert robot_control_params.is_tcp_controlled() self.simulation = simulation self.robot_prefix = robot_prefix self.autostep = autostep self.joint_group = robot_prefix + "arm_joint_angles" self.simulation.register_joint_group( self.joint_group, prefix=robot_prefix + "J" ) self._max_position_change = robot_control_params.max_position_change self.simulation.set_qpos(self.joint_group, TABLETOP_EXPERIMENT_INITIAL_POS) # Currently, we use the same simulation instance between this class and its controller # arm, therefore, the controller_arm is never allowed to autostep to avoid double-stepping # sim. self.controller_arm: FreeDOFTcpArm = build_tcp_controller( robot_control_params=robot_control_params, initial_qpos=self.simulation.get_qpos(self.joint_group), simulation=solver_simulation, autostep=False, ) self._is_in_joint_control_mode = False def set_simulation_start_position(self, pos: np.ndarray) -> None: """Sets simulation qpos (there are no actuators). :param pos: Joint positions, also set in the controls. """ self.simulation.set_qpos(self.joint_group, pos) self.mj_sim.forward() def set_position_control(self, control: np.ndarray) -> None: if self.is_in_joint_control_mode: self.simulation.set_qpos(self.joint_group, control) else: self.controller_arm.set_position_control(control) if self.autostep: self.mj_sim.step() if self.is_in_joint_control_mode: self.controller_arm.reset() def get_name(self) -> str: return "mujoco-ideal-arm" def observe(self) -> MujocoObservation: return MujocoObservation(self.simulation, self.robot_prefix, self.joint_group) def zero_control(self) -> np.ndarray: return self.controller_arm.zero_control() @property def is_in_joint_control_mode(self): return self._is_in_joint_control_mode def switch_to_joint_control(self) -> None: """Set flag so that commands are now interpreted as joint space commands. See reach_helper for details on why this is necessary.""" self._is_in_joint_control_mode = True def switch_to_tcp_control(self) -> None: """Set flag so that commands are now interpreted as TCP space commands. See reach_helper for details on why this is necessary.""" self._is_in_joint_control_mode = False def denormalize_position_control( self, position_control: np.ndarray, relative_action: bool = False, ) -> np.ndarray: return self.controller_arm.denormalize_position_control( position_control, relative_action ) def get_control_time_delta(self) -> float: """Returns the delta that the robot wants to be controlled under, by matching it with its mujoco simulation step delta. :return: Returns the delta that the robot wants to be controlled under, by matching it with its mujoco simulation step delta. """ dt = self.mj_sim.nsubsteps * self.mj_sim.model.opt.timestep return dt def get_robot_transform(self) -> Optional[np.ndarray]: return self.controller_arm.get_robot_transform() @property def mj_sim(self): """ MuJoCo MjSim simulation object """ return self.simulation.mj_sim @property def max_position_change(self): return self._max_position_change def reset(self): self.simulation.set_qpos(self.joint_group, TABLETOP_EXPERIMENT_INITIAL_POS) self.controller_arm.reset() def actuator_ctrl_range_upper_bound(self) -> np.ndarray: # We use the joint range in xml since there are no actuators for this arm. return self.controller_arm.actuator_ctrl_range_upper_bound() def actuator_ctrl_range_lower_bound(self) -> np.ndarray: # We use the joint range in xml since there are no actuators for this arm. return self.controller_arm.actuator_ctrl_range_lower_bound()
5,619
38.027778
121
py
robogym
robogym-master/robogym/robot/ur16e/mujoco/joint_controlled_tcp_arm.py
from typing import Any, Dict, Optional import numpy as np from robogym.robot.factories import build_tcp_controller from robogym.robot.robot_interface import RobotControlParameters from robogym.robot.ur16e.mujoco.free_dof_tcp_arm import FreeDOFTcpArm from robogym.robot.ur16e.mujoco.joint_controlled_arm import JointControlledArm from robogym.robot.ur16e.mujoco.simulation.base import ArmSimulationInterface class JointControlledTcpArm(JointControlledArm): """ Mujoco implementation of a joint-actuated UR 16e arm. """ def __init__( self, simulation: ArmSimulationInterface, robot_control_params: RobotControlParameters, solver_simulation: ArmSimulationInterface, robot_prefix="robot0:", autostep=False, controller_autostep=True, ): """ :param simulation: simulation interface for the mujoco UR arm :param robot_control_params: Robot control parameters :param robot_prefix: prefix to add to the joint names while constructing the mujoco simulation :param autostep: when true, calls step() on the simulation whenever a control is set. this should only be used only when the Robot is being controlled without a simulationrunner in the loop. :param controller_autostep: whether the controller arm should autostep. For joint controlled TCP arm, this is set to true by default as we always want the inner sim to be autostepping when a command is applied as it has a separate solver_simulation that will not be stepped by the main env loop. """ assert robot_control_params.is_tcp_controlled() super().__init__( simulation=simulation, robot_control_params=robot_control_params, robot_prefix=robot_prefix, autostep=autostep, ) inner_tcp_solver_mode = robot_control_params.get_controller_arm_solver_mode() inner_params = RobotControlParameters( max_position_change=robot_control_params.max_position_change, control_mode=robot_control_params.control_mode, tcp_solver_mode=inner_tcp_solver_mode, ) self.controller_arm: FreeDOFTcpArm = build_tcp_controller( robot_control_params=inner_params, initial_qpos=self.simulation.get_qpos(self.joint_group), simulation=solver_simulation, autostep=controller_autostep, ) self.reset_controller_error = robot_control_params.arm_reset_controller_error def get_name(self) -> str: return "mujoco-joint-controlled-tcp-arm" @property def is_in_joint_control_mode(self): return self.controller_arm.is_in_joint_control_mode def zero_control(self) -> np.ndarray: return self.controller_arm.zero_control() def get_robot_transform(self) -> Optional[np.ndarray]: return self.controller_arm.get_robot_transform() def denormalize_position_control( self, position_control: np.ndarray, relative_action: bool = False, ) -> np.ndarray: return self.controller_arm.denormalize_position_control( position_control, relative_action ) def get_helper_robot(self): """Retrieve the internal controller robot. External users should only query things, not cause modifications. :return: The internal controller robot. """ return self.controller_arm def set_position_control(self, control: np.ndarray) -> None: if self.reset_controller_error: self.controller_arm.sync_to( joint_positions=self.observe().joint_positions(), joint_controls=None ) self.controller_arm.set_position_control(control) control = self.controller_arm.get_joint_state() super().set_position_control(control) def reset(self) -> None: super().reset() self.controller_arm.reset() def switch_to_joint_control(self) -> None: """Set flag so that commands are now interpreted as joint space commands. See reach_helper for details on why this is necessary.""" self.controller_arm.switch_to_joint_control() def switch_to_tcp_control(self) -> None: """Set flag so that commands are now interpreted as TCP space commands. See reach_helper for details on why this is necessary.""" self.controller_arm.switch_to_tcp_control() def on_observations_updated(self, new_observations: Dict[str, Any]) -> None: """Event to notify the robot that new observations have been collected. See parents for more detailed documentation. Overridden here so that we update sub-simulations for TCP controlled arms that have them. :param new_observations: New observations collected. """ # update the gripper in the controller arm's simulation if needed with the new observations for this step if self.controller_arm: pos = new_observations["gripper_qpos"] ctrl = new_observations["gripper_controls"] self.controller_arm.simulation.gripper.sync_to( joint_positions=pos, joint_controls=ctrl )
5,235
39.276923
116
py
robogym
robogym-master/robogym/robot/ur16e/mujoco/simulation/base.py
from robogym.envs.rearrange.common.utils import geom_ids_of_body from robogym.mujoco.mujoco_xml import MujocoXML from robogym.mujoco.simulation_interface import SimulationInterface from robogym.robot.gripper.mujoco.mujoco_robotiq_gripper import MujocoRobotiqGripper from robogym.robot.robot_interface import RobotControlParameters class ArmSimulationInterface(SimulationInterface): """ Creates a SimulationInterface with a rearrange-compatible robot-gripper and a table setup. Subclass this and implement make_objects_xml() to create other tasks. """ DEFAULT_RENDER_SIZE = 100 BASE_XML = "robot/ur16e/base.xml" def __init__( self, sim, robot_control_params: RobotControlParameters, ): super().__init__(sim) self.register_joint_group("robot", prefix=["robot0:"]) self.register_joint_group( "gripper", prefix=["robot0:r_gripper", "robot0:l_gripper"] ) self.control_param = robot_control_params self.enable_pid() # initialize a gripper in sim so that it can be used to sync state if we need to. self._gripper = MujocoRobotiqGripper( simulation=self, robot_control_params=robot_control_params, autostep=False ) # Hide mocap since not very helpful and clutters vision. mocap_id = self.mj_sim.model.body_name2id("robot0:mocap") mocap_geom_start_id = self.mj_sim.model.body_geomadr[mocap_id] mocap_geom_end_id = ( mocap_geom_start_id + self.mj_sim.model.body_geomnum[mocap_id] ) for geom_id in range(mocap_geom_start_id, mocap_geom_end_id): self.mj_sim.model.geom_rgba[geom_id, :] = 0.0 self.geom_ids = [] self.gripper_bodies = [ "robot0:gripper_base", "left_gripper", "left_inner_follower", "left_outer_driver", "right_gripper", "right_inner_follower", "right_outer_driver", ] # Get the geom ids of all the bodies that make up the gripper for gripper_body in self.gripper_bodies: self.geom_ids.extend(geom_ids_of_body(self.mj_sim, gripper_body)) @classmethod def build( cls, robot_control_params: RobotControlParameters, n_substeps=40, mujoco_timestep=0.001, ): xml = cls.make_world_xml( contact_params=dict(njmax=200, nconmax=200, nuserdata=200), mujoco_timestep=mujoco_timestep, ) xml = ArmSimulationInterface.make_robot_xml(xml, robot_control_params) return cls( xml.build(nsubsteps=n_substeps), robot_control_params=robot_control_params, ) @classmethod def make_world_xml(cls, *, contact_params: dict, mujoco_timestep: float, **kwargs): return ( MujocoXML.parse(cls.BASE_XML) .set_objects_attr(tag="option", timestep=mujoco_timestep) .set_objects_attr(tag="size", **contact_params) .add_default_compiler_directive() ) @classmethod def make_robot_xml(cls, xml, robot_control_params): if robot_control_params.is_joint_actuated(): # Modifying xml is required because setting eq_active only was not enough to fully # disable the mocap weld constraint. In my tests, setting eq_active to false would # disable the constraint, but somehow the arm would not move when the joints were # commanded. Removing from xml here seems to have the right effect. xml.remove_objects_by_name("mocap_weld") # Also add the actuations that are removed in the xml by default (since TCP does # not need them). joint_subdir = robot_control_params.arm_joint_calibration_path xml.append( MujocoXML.parse( f"robot/ur16e/jointspec/calibrations/{joint_subdir}/ur16e_ik_class.xml" ) ) xml.append( MujocoXML.parse( f"robot/ur16e/jointspec/calibrations/{joint_subdir}/joint_actuations.xml" ) ) else: # If not joint control mode or ik solver mode, use mocap defaults for joint parameters xml.append(MujocoXML.parse("robot/ur16e/jointspec/ur16e_mocap_class.xml")) # Add gripper actuators now (after joint actuators if required). xml.append(MujocoXML.parse("robot/ur16e/gripper_actuators.xml")) return xml @property def gripper(self): return self._gripper def render( self, width=DEFAULT_RENDER_SIZE, height=DEFAULT_RENDER_SIZE, *, camera_name="vision_cam_front", depth=False, mode="offscreen", device_id=-1, ): data = super().render( width=width, height=height, camera_name=camera_name, depth=depth, mode=mode, device_id=device_id, ) # original image is upside-down, so flip it return data[::-1, :, :] def get_gripper_table_contact(self) -> bool: """ Determine if any part of the gripper is touching the table by checking if there is a collision between the table_collision_plane id and any gripper geom id. """ contacts = [] gripper_table_contact = False # Sweep through all mj_sim contacts for i in range(self.mj_sim.data.ncon): c = self.mj_sim.data.contact[i] # Check if any of the contacts involve at gripper geom id, append them to contacts: if c.geom1 in self.geom_ids: contacts.append(c.geom2) elif c.geom2 in self.geom_ids: contacts.append(c.geom1) # Check if any of the contacts correspond to the `table` id: for contact in contacts: contact_name = self.mj_sim.model.geom_id2name(contact) if contact_name == "table_collision_plane": gripper_table_contact = True return gripper_table_contact
6,167
35.714286
98
py
robogym
robogym-master/robogym/worldgen/parser/const.py
# Automatically generated. Do not modify! """ We represent XML as OrderedDict and lists. Some nodes have OrderedDict value (mostly top-lever such as worldbody. some nodes have list values (mostly lower level). However, MuJoCo is not consistent with it. We automatically checked in many XMLs if given values occur once (then, they are converted to OrderedDict) or multiple times (then, they are converted to list). script get_const.py determines it, and writes result to const.py. Value in variable list_types describes nodes that of a type list. Moreover, same arguments are indeed floats, but given XML might store them as ints, e.g. pos = "1 1 1". Here we determine actuall datatype. """ list_types = set( [ "actuatorfrc", "body", "default", "exclude", "fixed", "geom", "include", "joint", "jointpos", "light", "material", "mesh", "motor", "general", "pair", "position", "site", "texture", "touch", "weld", ] ) float_arg_types = set( [ "@armature", "@axis", "@axisangle", "@coef", "@ctrlrange", "@damping", "@density", "@diaginertia", "@diffuse", "@dir", "@euler", "@force", "@forcerange", "@fovy", "@friction", "@frictionloss", "@fromto", "@gear", "@kp", "@margin", "@markrgb", "@mass", "@polycoef", "@pos", "@quat", "@random", "@range", "@ref", "@reflectance", "@rgb1", "@rgb2", "@rgba", "@scale", "@shininess", "@size", "@solimp", "@solimplimit", "@solref", "@solreflimit", "@specular", "@stiffness", "@timestep", "@transformation", ] )
1,966
21.101124
74
py