def test_xml_from_path(): model = load_model_from_path("mujoco_py/tests/test.xml") sim = MjSim(model) xml = model.get_xml() assert xml.find("blabla") > -1, "include should be embeeded" assert xml.find("include") == - \ 1, "include should be parsed and not present"
def test_viewer(): model = load_model_from_path("mujoco_py/tests/test.xml") sim = MjSim(model) viewer = MjViewer(sim) for _ in range(100): sim.step() viewer.render()
def __init__(self, model_path, frame_skip): if model_path.startswith("/"): fullpath = model_path else: fullpath = os.path.join(os.path.dirname(__file__), "assets", model_path) if not path.exists(fullpath): raise IOError("File %s does not exist" % fullpath) self.frame_skip = frame_skip self.model = mujoco_py.load_model_from_path(fullpath) self.sim = mujoco_py.MjSim(self.model) self.data = self.sim.data self.viewer = None self.metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.init_qpos = self.sim.data.qpos.ravel().copy() self.init_qvel = self.sim.data.qvel.ravel().copy() observation, _reward, done, _info = self.step(np.zeros(self.model.nu)) assert not done self.obs_dim = observation.size bounds = self.model.actuator_ctrlrange.copy() low = bounds[:, 0] high = bounds[:, 1] self.action_space = spaces.Box(low=low, high=high) high = np.inf*np.ones(self.obs_dim) low = -high self.observation_space = spaces.Box(low, high) self.seed()
def __init__(self, model_path, initial_qpos, n_actions, n_substeps): if model_path.startswith('/'): fullpath = model_path else: fullpath = os.path.join(os.path.dirname(__file__), 'assets', model_path) if not os.path.exists(fullpath): raise IOError('File {} does not exist'.format(fullpath)) model = mujoco_py.load_model_from_path(fullpath) self.sim = mujoco_py.MjSim(model, nsubsteps=n_substeps) self.viewer = None self.metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.seed() self._env_setup(initial_qpos=initial_qpos) self.initial_state = copy.deepcopy(self.sim.get_state()) self.goal = self._sample_goal() obs = self._get_obs() self.action_space = spaces.Box(-1., 1., shape=(n_actions,), dtype='float32') self.observation_space = spaces.Dict(dict( desired_goal=spaces.Box(-np.inf, np.inf, shape=obs['achieved_goal'].shape, dtype='float32'), achieved_goal=spaces.Box(-np.inf, np.inf, shape=obs['achieved_goal'].shape, dtype='float32'), observation=spaces.Box(-np.inf, np.inf, shape=obs['observation'].shape, dtype='float32'), ))
def _load_model(self, xml_path): if not xml_path.startswith('/'): xml_path = os.path.join(os.path.dirname(__file__), 'assets', 'xml', xml_path) if not os.path.exists(xml_path): raise IOError('Model file ({}) does not exist'.format(xml_path)) model = mujoco_py.load_model_from_path(xml_path) self._frame_skip = self._env_config["frame_skip"] self.sim = mujoco_py.MjSim(model, nsubsteps=self._frame_skip) self.model = self.sim.model self.data = self.sim.data self._viewer = None # State logger.info('initial qpos: {}'.format(self.sim.data.qpos.ravel())) logger.info('initial qvel: {}'.format(self.sim.data.qvel.ravel())) # Action num_actions = self.sim.model.nu is_limited = self.sim.model.actuator_ctrllimited.ravel().astype( np.bool) control_range = self.sim.model.actuator_ctrlrange minima = np.full(num_actions, fill_value=-np.inf, dtype=np.float) maxima = np.full(num_actions, fill_value=np.inf, dtype=np.float) minima[is_limited], maxima[is_limited] = control_range[is_limited].T logger.info('is_limited: {}'.format(is_limited)) logger.info('control_range: {}'.format(control_range[is_limited].T)) self.action_space = spaces.Dict([('default', spaces.Box(low=minima, high=maxima, dtype=np.float32))]) # Camera self._camera_name = 'cam0' self._camera_id = self.sim.model.camera_names.index(self._camera_name)
def __init__(self, low_ctrl, high_ctrl, env_path=env_path, low_ctrl_config=None, arm_name="RightArm", desired_joints=None, isdraw=False): self.world = mujoco_py.load_model_from_path(env_path) self.sim = mujoco_py.MjSim(self.world) high_ctrl.motion_duration = 1.8 self.high_ctrl = high_ctrl self.high_ctrl.low_ctrl = low_ctrl(model=self.world, sim=self.sim, config=low_ctrl_config, \ arm_name=arm_name, desired_joints=desired_joints) self.isdraw = isdraw if self.isdraw: self.viewer = mujoco_py.MjViewer(self.sim) self.viewer._paused = True self.init_joints = np.array([0.2, -0.2, 0, 0, 1.8, 3.14, 0, 0]) self.is_ball_pos_change = False
def __init__(self, fullpath, frame_skip, rgb_rendering_tracking=True): # allow full_path to be an arbitrary path if not os.path.exists(fullpath): raise IOError("File %s does not exist" % fullpath) self.frame_skip = frame_skip self.model = mujoco_py.load_model_from_path(fullpath) self.sim = mujoco_py.MjSim(self.model) self.data = self.sim.data self.viewer = None self.rgb_rendering_tracking = rgb_rendering_tracking self._viewers = {} self.metadata = { 'render.modes': ['human', 'rgb_array', 'depth_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.init_qpos = self.sim.data.qpos.ravel().copy() self.init_qvel = self.sim.data.qvel.ravel().copy() self._set_action_space() action = self.action_space.sample() observation, _reward, done, _info = self.step(action) assert not done self._set_observation_space(observation) self.seed()
def __init__(self, sparse_reward=False, horizon=200): self.goal_idx = 0 #np.random.randint(0, 4) self.goal_one_hot = np.array([0, 0, 0, 0]) self.goal_one_hot[self.goal_idx] = 1 self.sparse_reward = sparse_reward model = load_model_from_path("envs/ReacherDistractor.xml") sim = MjSim(model) self.sim = sim viewer = MjViewer(sim) self.init_state = sim.get_state() self.model = model self.viewer = viewer self.action_dim = len(self.sim.data.ctrl) self.obs_dim = len(self.get_obs()) high = np.array([np.inf] * self.obs_dim) # self.action_space = spaces.Box(np.array([-1, -1, -1, -1]), np.array([1, 1, 1, 1]), dtype=np.float32) self.observation_space = spaces.Box(-high, high, dtype=np.float32) high = np.array([2.0] * self.action_dim) self.action_space = spaces.Box(-high, high, dtype=np.float32) self.metadata = None self.horizon = horizon self.cur_step = 0
def run(): model = load_model_from_path("/Users/zachyamaoka/Documents/de3_group_project/sim/falling_bar.xml") # model = load_model_from_path("/Users/zachyamaoka/Documents/de3_group_project/sim/6_Bar.xml") sim = MjSim(model) viewer = MjViewer(sim) t = 0 vel_data = [] pos_data = [] acc_data = [] time = [] while True: # sim.data.ctrl[0] = math.cos(t / 10.) * 0.01 # sim.data.ctrl[1] = math.sin(t / 10.) * 0.01 time.append(t*0.01) t += 1 # sim.step() viewer.render() if t > 400: break if t > 100 and os.getenv('TESTING') is not None: break
def __init__(self, model_path, frame_skip, device_id=-1, automatically_set_spaces=False): if model_path.startswith("/"): fullpath = model_path else: fullpath = os.path.join(os.path.dirname(__file__), "assets", model_path) if not path.exists(fullpath): raise IOError("File %s does not exist" % fullpath) self.frame_skip = frame_skip self.model = mujoco_py.load_model_from_path(fullpath) self.sim = mujoco_py.MjSim(self.model) self.data = self.sim.data self.viewer = None self.metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } if device_id == -1 and 'gpu_id' in os.environ: device_id =int(os.environ['gpu_id']) self.device_id = device_id self.init_qpos = self.sim.data.qpos.ravel().copy() self.init_qvel = self.sim.data.qvel.ravel().copy() if automatically_set_spaces: observation, _reward, done, _info = self.step(np.zeros(self.model.nu)) assert not done self.obs_dim = observation.size bounds = self.model.actuator_ctrlrange.copy() low = bounds[:, 0] high = bounds[:, 1] self.action_space = spaces.Box(low=low, high=high) high = np.inf*np.ones(self.obs_dim) low = -high self.observation_space = spaces.Box(low, high) self.seed()
def __init__(self, model_path, frame_skip, N): if model_path.startswith("/"): fullpath = model_path else: fullpath = os.path.join(os.path.dirname(mujoco_env.__file__), "assets", model_path) if not path.exists(fullpath): raise IOError("File %s does not exist" % fullpath) self.frame_skip = frame_skip self.model = mjc.load_model_from_path(fullpath) self.sim = mjc.MjSim(self.model) self.data = self.sim.data self.viewer = None self._viewers = {} #### parallel self.N = N self.pool = mjc.MjSimPool.create_from_sim(self.sim, self.N) #### self.metadata = { 'render.modes': ['human', 'rgb_array', 'depth_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.init_qpos = self.sim.data.qpos.ravel().copy() self.init_qvel = self.sim.data.qvel.ravel().copy() self._set_action_space() action = self.action_space.sample() observation, _reward, done, _info = self.step(action) assert not done.any() self._set_observation_space(observation) self.seed()
def __init__(self, model_path, frame_skip, rgb_rendering_tracking=False): if model_path.startswith("/"): fullpath = model_path else: fullpath = os.path.join(os.path.dirname(__file__), "assets", model_path) if not path.exists(fullpath): raise IOError("File %s does not exist" % fullpath) self.frame_skip = frame_skip self.model = mujoco_py.load_model_from_path(fullpath) self.sim = mujoco_py.MjSim(self.model) self.data = self.sim.data self.viewer = None self._viewers = {} self.rgb_rendering_tracking = rgb_rendering_tracking self.metadata = { 'render.modes': ['human', 'rgb_array', 'depth_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.init_qpos = self.sim.data.qpos.ravel().copy() self.init_qvel = self.sim.data.qvel.ravel().copy() observation, _reward, done, _info = self.step(np.zeros(self.model.nu)) assert not done self.obs_dim = observation.size bounds = self.model.actuator_ctrlrange.copy() low = bounds[:, 0] high = bounds[:, 1] self.action_space = spaces.Box(low=low, high=high, dtype=np.float32) high = np.inf * np.ones(self.obs_dim) low = -high self.observation_space = spaces.Box(low, high, dtype=np.float32) self.seed()
def __init__(self, model_path, frame_skip): if model_path.startswith("/"): fullpath = model_path else: fullpath = os.path.join(os.path.dirname(__file__), "assets", model_path) if not path.exists(fullpath): raise IOError("File %s does not exist" % fullpath) self.frame_skip = frame_skip self.model = mujoco_py.load_model_from_path(fullpath) self.sim = mujoco_py.MjSim(self.model) self.data = self.sim.data self.viewer = None self._viewers = {} self.metadata = { 'render.modes': ['human', 'rgb_array', 'depth_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } # self.seed() self.init_qpos = self.sim.data.qpos.ravel().copy() self.init_qvel = self.sim.data.qvel.ravel().copy() # self.goal = self._sample_goal() self._set_action_space() ### because of this, we don't get our defined initial condn so we'll have to enforce them at last in __init__ of env itself action = self.action_space.sample() observation, _reward, done, _info = self.step(action) assert not done self.set_state(self.init_qpos, self.init_qvel) ### enforcing initial state self._set_observation_space(observation)
def __init__(self, model_path, initial_qpos, n_actions, n_substeps): if model_path.startswith('/'): fullpath = model_path else: fullpath = os.path.join(os.path.dirname(__file__), 'assets', model_path) if not os.path.exists(fullpath): raise IOError('File {} does not exist'.format(fullpath)) model = mujoco_py.load_model_from_path(fullpath) self.sim = mujoco_py.MjSim(model, nsubsteps=n_substeps) self.viewer = None self.metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.seed() self._env_setup(initial_qpos=initial_qpos) self.initial_state = copy.deepcopy(self.sim.get_state()) self.goal = self._sample_goal() obs = self._get_obs()['observation'] self.action_space = spaces.Box(-1., 1., shape=(n_actions, ), dtype='float32') # self.observation_space = spaces.Dict(dict( # desired_goal=spaces.Box(-np.inf, np.inf, shape=obs['achieved_goal'].shape, dtype='float32'), # achieved_goal=spaces.Box(-np.inf, np.inf, shape=obs['achieved_goal'].shape, dtype='float32'), # observation=spaces.Box(-np.inf, np.inf, shape=obs['observation'].shape, dtype='float32'), # )) self.observation_space = spaces.Box(-np.inf, np.inf, shape=obs.shape, dtype='float32')
def _re_init(self, xml): # TODO: Now, likely needs rank randomized_path = os.path.join(self.xml_dir, "randomizedgen3.xml") with open(randomized_path, 'wb') as fp: fp.write(xml.encode()) fp.flush() try: self.model = mujoco_py.load_model_from_path(randomized_path) except: print("Unable to load the xml file") self.sim = mujoco_py.MjSim(self.model, nsubsteps=self.n_substeps) self.modder = TextureModder(self.sim) self.visual_randomize = True self.metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self._env_setup(initial_qpos=self.initial_qpos) self.initial_state = copy.deepcopy(self.sim.get_state()) # self.initial_state = copy.deepcopy(self.sim.get_state()) # self.data = self.sim.data # self.init_qpos = self.data.qpos.ravel().copy() # self.init_qvel = self.data.qvel.ravel().copy() # # observation = self.reset() # #observation, _reward, done, _info = self.step(np.zeros(4)) # #assert not done if self.viewer: self.viewer.update_sim(self.sim)
def __init__(self, frame_skip=10, viewer=True): self.frame_skip = frame_skip model_path = './assets/franka_throw.xml' self.model = load_model_from_path(model_path) self.sim = MjSim(self.model, nsubsteps=frame_skip) self.data = self.sim.data if viewer: self.viewer = MjViewer(self.sim) self.act_mid = np.mean(self.model.actuator_ctrlrange, axis=1) self.act_rng = 0.5 * (self.model.actuator_ctrlrange[:, 1] - self.model.actuator_ctrlrange[:, 0]) nu = len(self.act_rng) self.action_space = Box(low=-1., high=1., shape=(nu, ), dtype=np.float32) ob = self.get_obs(self.data) self.observation_space = Box(low=-np.inf, high=np.inf, shape=(len(ob), ), dtype=np.float32) self.obj_bid = self.model.body_name2id('object') self.grasp_sid = self.model.site_name2id('grasp') self.targ_sid = self.model.site_name2id('target') ## -- From the franka examples : 0, -M_PI_4, 0, -3 * M_PI_4, 0, M_PI_2, M_PI_4 self.init_pose = np.array( [0., -np.pi / 4, 0., -3. * np.pi / 4, 0., np.pi / 2, np.pi / 4]) init_pose = np.concatenate([self.init_pose, [0]]) self.def_action = (init_pose - self.act_mid) / self.act_rng * 0
def __init__(self, animate=False, sim=None): if sim is not None: self.sim = sim self.model = self.sim.model else: self.modelpath = AntFeelersMjc.MODELPATH self.model = mujoco_py.load_model_from_path(self.modelpath) self.sim = mujoco_py.MjSim(self.model) self.model.opt.timestep = 0.02 self.N_boxes = 4 self.max_steps = 600 # Environment dimensions self.q_dim = self.sim.get_state().qpos.shape[0] self.qvel_dim = self.sim.get_state().qvel.shape[0] self.obs_dim = self.q_dim + self.qvel_dim - 7 * self.N_boxes - 6 * self.N_boxes + 7 - 2 self.act_dim = self.sim.data.actuator_length.shape[0] # Environent inner parameters self.viewer = None self.step_ctr = 0 self.joints_rads_low = np.array([-0.7, 0.8] * 4 + [-1, -1, -1, -1]) self.joints_rads_high = np.array([0.7, 1.4] * 4 + [1, 1, 1, 1]) self.joints_rads_diff = self.joints_rads_high - self.joints_rads_low self.target_dist = 0 self.done = False # Initial methods if animate: self.setupcam() self.reset()
def __init__(self): # super(lab_env, self).__init__(env) # 导入xml文档 self.model = load_model_from_path("assets/simpleEE_4box.xml") # 调用MjSim构建一个basic simulation self.sim = MjSim(model=self.model) self.sim = MjSim(self.model) self.viewer = MjViewer(self.sim) self.viewer._run_speed = 0.001 self.timestep = 0 # Sawyer Peg #self.init_qpos = np.array([-0.305, -0.83, 0.06086, 1.70464, -0.02976, 0.62496, -0.04712]) # Flexiv Peg self.init_qpos = np.array([-0.22, -0.43, 0.449, -2, -0.25, 0.799, 0.99]) for i in range(len(self.sim.data.qpos)): self.sim.data.qpos[i] = self.init_qpos[i] self.testQposFromSitePose( (np.array([0.57, 0.075, 0.08]), np.array([0.000000e+00, 1.000000e+00, 0.000000e+00, 6.123234e-17])), _INPLACE, True) print(self.sim.data.ctrl) print(self.sim.data.qpos)
def __init__(self, model_path, initial_qpos, n_actions, n_substeps): if model_path.startswith('/'): fullpath = model_path else: fullpath = os.path.join(os.path.dirname(__file__), 'assets', model_path) if not os.path.exists(fullpath): raise IOError('File {} does not exist'.format(fullpath)) model = mujoco_py.load_model_from_path(fullpath) self.sim = mujoco_py.MjSim(model, nsubsteps=n_substeps) self.renderer = MjRenderContextOffscreen(self.sim, device_id=get_gpu_id()) self.viewer = None self.metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.seed() self._env_setup(initial_qpos=initial_qpos) self.initial_state = copy.deepcopy(self.sim.get_state()) self.goal = self._sample_goal() obs = self._get_obs() self.action_space = spaces.Box(-1., 1., shape=(n_actions, ), dtype='float32') self.observation_space = {} for key, value in obs.items(): self.observation_space[key] = spaces.Box(-np.inf, np.inf, shape=value.shape, dtype=value.dtype)
def __init__( self, model_path, frame_skip=1, model_path_is_local=True, automatically_set_obs_and_action_space=False, ): if model_path_is_local: model_path = get_asset_xml(model_path) if automatically_set_obs_and_action_space: mujoco_env.MujocoEnv.__init__(self, model_path, frame_skip) else: """ Code below is copy/pasted from MujocoEnv's __init__ function. """ if model_path.startswith("/"): fullpath = model_path else: fullpath = os.path.join(os.path.dirname(__file__), "assets", model_path) if not path.exists(fullpath): raise IOError("File %s does not exist" % fullpath) self.frame_skip = frame_skip self.model = mujoco_py.load_model_from_path(fullpath) self.sim = mujoco_py.MjSim(self.model) self.data = self.sim.data self.viewer = None self.metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.init_qpos = self.sim.data.qpos.ravel().copy() self.init_qvel = self.sim.data.qvel.ravel().copy() self.seed()
def __init__(self, model_path, initial_qpos, n_actions, n_substeps): if model_path.startswith('/'): fullpath = model_path else: print(os.path.dirname(__file__)) fullpath = os.path.join(os.path.dirname(__file__), 'assets', model_path) if not os.path.exists(fullpath): raise IOError('File {} does not exist'.format(fullpath)) model = mujoco_py.load_model_from_path(fullpath) self.sim = mujoco_py.MjSim(model, nsubsteps=n_substeps) self.viewer = None self._viewers = {} self.metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.seed() self._env_setup(initial_qpos=initial_qpos) self.initial_state = copy.deepcopy(self.sim.get_state()) obs = self._get_obs() self.action_space = spaces.Box(-1., 1., shape=(n_actions, ), dtype='float32') # Use discrete action space instead #self.action_space = spaces.MultiDiscrete(list(np.zeros(n_actions) + 11)) self.observation_space = spaces.Dict( OrderedDict(observation=spaces.Box(-np.inf, np.inf, shape=obs['observation'].shape, dtype='float32')))
def __init__(self, model_path, initial_pos_dict, skip_frame): if model_path.startswith("/"): fullpath = model_path else: fullpath = path.join(path.dirname(__file__), "assets", model_path) if not path.exists(fullpath): raise IOError("File %s does not exist" % fullpath) self.model = mujoco_py.load_model_from_path(fullpath) self.sim = mujoco_py.MjSim(self.model, nsubsteps=skip_frame) self.data = self.sim.data self.viewer = None self.metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.action_space = self._get_action_space() self.observation_space = self._get_observation_space() self.seed() self.set_pos_by_dict(initial_pos_dict) self.initial_state = copy.deepcopy(self.sim.get_state())
def gen_robot_configs(ref_file, robot_num, vars_to_change, param_var_num, skip_geom, root_save_dir): pre_gen_params = pre_gen_robot_params(vars_to_change=vars_to_change, param_var_num=param_var_num) joint_sites = ['j0', 'j1', 'j2', 'j3', 'j4', 'j5', 'j6'] for idx in tqdm(range(robot_num)): model = load_model_from_path(ref_file) sim = MjSim(model) valid_joint_sites = [ el for el in joint_sites if el in sim.model._site_name2id ] valid_joints_num = len(valid_joint_sites) robot_param_random_sample(sim, vars_to_change, pre_gen_params, valid_joints_num, skip_geom) sim.model.vis.map.znear = 0.02 sim.model.vis.map.zfar = 50.0 sim.reset() robot_id = int(re.findall(r'\d+', ref_file.split('/')[-1])[0]) save_dir = os.path.join( root_save_dir, '%d_dof_%d_%d' % (valid_joints_num, robot_id, idx)) os.makedirs(save_dir, exist_ok=True) with open(os.path.join(save_dir, 'robot.xml'), 'w') as f: sim.save(f, keep_inertials=True)
def __init__(self, model_path, frame_skip): if model_path.startswith("/"): fullpath = model_path else: fullpath = os.path.join(os.path.dirname(__file__), "assets", model_path) if not path.exists(fullpath): raise IOError("File %s does not exist" % fullpath) self.frame_skip = frame_skip self.model = load_model_from_path(fullpath) self.sim = MjSim(self.model) self.data = self.sim.data self._seed() self.metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.mujoco_render_frames = False self.init_qpos = self.data.qpos.ravel().copy() self.init_qvel = self.data.qvel.ravel().copy() observation, _reward, done, _info = self._step(np.zeros(self.model.nu)) assert not done self.obs_dim = np.sum([o.size for o in observation]) if type(observation) is tuple else observation.size bounds = self.model.actuator_ctrlrange.copy() low = bounds[:, 0] high = bounds[:, 1] self.action_space = spaces.Box(low, high) high = np.inf*np.ones(self.obs_dim) low = -high self.observation_space = spaces.Box(low, high) self.sim.forward()
def __init__(self, model_path, initial_qpos, n_actions, n_substeps, **kwargs): model = mujoco_py.load_model_from_path(fullpath_from_rel(model_path)) self.sim = mujoco_py.MjSim(model, nsubsteps=n_substeps) self.viewer = None self.metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.seed() self._env_setup(initial_qpos=initial_qpos) self.initial_state = copy.deepcopy(self.sim.get_state()) self.goal = self._sample_goal() obs = self._get_obs() self.action_space = spaces.Box(-1., 1., shape=(n_actions, ), dtype='float32') self.observation_space = spaces.Dict( dict( desired_goal=spaces.Box(-np.inf, np.inf, shape=obs['achieved_goal'].shape, dtype='float32'), achieved_goal=spaces.Box(-np.inf, np.inf, shape=obs['achieved_goal'].shape, dtype='float32'), observation=spaces.Box(-np.inf, np.inf, shape=obs['observation'].shape, dtype='float32'), ))
def make_env(self): self.viewer = None if self.fixed: self.rnd_len = -0.6 else: self.rnd_len = -(0.4 + np.random.rand() * 0.9) # Generate new xml self.generate_new(self.rnd_len) while True: try: self.model = mujoco_py.load_model_from_path(self.modelpath) break except Exception: "Retrying xml" self.sim = mujoco_py.MjSim(self.model) self.model.opt.timestep = 0.02 # Environment dimensions self.q_dim = self.sim.get_state().qpos.shape[0] self.qvel_dim = self.sim.get_state().qvel.shape[0]
def __init__(self, model_path, initial_qpos, n_actions, n_substeps, seed, success_reward, action_rate): if model_path.startswith('/'): fullpath = model_path else: fullpath = os.path.join(os.path.dirname(__file__), 'assets', model_path) if not os.path.exists(fullpath): raise IOError('File {} does not exist'.format(fullpath)) model = mujoco_py.load_model_from_path(fullpath) self.sim = mujoco_py.MjSim(model, nsubsteps=n_substeps) self.viewer = None self._viewers = {} self.metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.action_rate = action_rate self.seed(seed) self._env_setup(initial_qpos=initial_qpos) self.initial_state = copy.deepcopy(self.sim.get_state()) self.success_reward = success_reward self.goal = self._sample_goal() obs = self._get_obs() self.action_space = spaces.Box(-1., 1., shape=(n_actions, ), dtype='float32') #self.action_space = spaces.Box(-2., 2., shape=(n_actions,), dtype='float64') self.observation_space = convert_observation_to_space( np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]).astype('float64')) self.last_obs = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) '''
def __init__(self, filepath, random_params={}, gpu_render=False, gui=False, display_data=False): self.model = load_model_from_path(filepath) self.sim = MjSim(self.model) self.filepath = filepath self.gui = gui self.display_data = display_data # Take the default random params and update anything we need self.RANDOM_PARAMS = {} self.RANDOM_PARAMS.update(random_params) if gpu_render: self.viewer = MjViewer(self.sim) else: self.viewer = None # Get start state of params to slightly jitter later self.START_GEOM_POS = self.model.geom_pos.copy() self.START_GEOM_SIZE = self.model.geom_size.copy() self.START_GEOM_QUAT = self.model.geom_quat.copy() self.START_BODY_POS = self.model.body_pos.copy() self.START_BODY_QUAT = self.model.body_quat.copy() self.START_MATID = self.model.geom_matid.copy() #self.FLOOR_OFFSET = self.model.body_pos[self.model.body_name2id('floor')] self.tex_modder = TextureModder(self.sim) self.tex_modder.whiten_materials( ) # ensures materials won't impact colors self.cam_modder = CameraModder(self.sim) self.light_modder = LightModder(self.sim) self.start_obj_pose = self.sim.data.get_joint_qpos( 'object:joint').copy()
def __init__(self): self.model = mj.load_model_from_path("./slip/slip.xml") self.sim = mj.MjSim(self.model, nsubsteps=FRAMESKIP) self.vis = mj.MjViewerBasic(self.sim) self.vis.cam.trackbodyid = 2 self.vis.cam.distance = self.model.stat.extent * 0.75 self.vis.cam.lookat[2] = 1.15 self.vis.cam.elevation = -20 self.desired_speed = random.choice([-2, 2]) #obs_vec = np.concatenate([self.sim.data.qpos.flat[1:], np.clip(self.sim.data.qvel.flat, -10, 10)]) obs_vec = np.concatenate([ self.sim.data.qpos.flat[1:], np.clip(self.sim.data.qvel.flat, -10, 10) ]) obs_vec = np.append(obs_vec, self.desired_speed) self.observation_space = np.zeros(len(obs_vec)) self.action_space = np.zeros(2) self.dt = self.model.opt.timestep * FRAMESKIP self.avg_spd = 0 self.step_ctr = 1
def __init__(self, model_path, frame_skip): if model_path.startswith("/"): fullpath = model_path else: fullpath = os.path.join(os.path.dirname(__file__), "assets", model_path) if not path.exists(fullpath): raise IOError("File %s does not exist" % fullpath) self.frame_skip = frame_skip self.model = mujoco_py.load_model_from_path(fullpath) self.sim = mujoco_py.MjSim(self.model) self.data = self.sim.data self.viewer = None self._viewers = {} self.integral = 0 self.action_record = [0.0, 0.0, 0.0] self.metadata = { 'render.modes': ['human', 'rgb_array', 'depth_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.init_qpos = self.sim.data.qpos.ravel().copy() self.init_qvel = self.sim.data.qvel.ravel().copy() self._set_action_space() action = [0.0, 0.0, 0.0] #this is the environment for 3 actuators such as hopper observation, _reward, done, _info = self.step(action) assert not done self._set_observation_space(observation) self.seed()
def __init__(self, model_path, num_substeps=75): if model_path.startswith("/"): fullpath = model_path else: fullpath = osp.join(osp.dirname(__file__), "assets", model_path) if not osp.exists(fullpath): raise IOError("File %s does not exist" % fullpath) else: pass # print("Loading model %s"%osp.basename(model_path)) model = mujoco_py.load_model_from_path(fullpath) self.sim = mujoco_py.MjSim(model, nsubsteps=num_substeps) self.data = self.sim.data self.viewer = None self.metadata = { 'render.modes': ['human', 'rgb_array'], 'video.frames_per_second': int(np.round(1.0 / self.dt)) } self.seed() # limits of motion with some safety limits self.target_range_min = np.array([0.3, 0.0, 0.08]) + 0.05 self.target_range_max = np.array([0.8, 0.6, 0.25]) - 0.05 self.initial_qpos = { 'left_s0': -0.08, 'left_s1': -1.0, 'left_e0': -1.19, 'left_e1': 1.94, 'left_w0': 0.67, 'left_w1': 1.03, 'left_w2': -0.5 }
def main(): # Image size for rendering IMAGE_WIDTH = 255 IMAGE_HEIGHT = 255 # Number of frames to render per sim N_FRAMES = 100 # Number of sims to run in parallel (assumes one per GPU), # so N_SIMS=2 assumes there are 2 GPUs available. N_SIMS = 2 pool = MjRenderPool(load_model_from_path("xmls/tosser.xml"), device_ids=N_SIMS) print("main(): start benchmarking", flush=True) start_t = perf_counter() for _ in range(N_FRAMES): pool.render(IMAGE_WIDTH, IMAGE_HEIGHT) t = perf_counter() - start_t print("Completed in %.1fs: %.3fms, %.1f FPS" % ( t, t / (N_FRAMES * N_SIMS) * 1000, (N_FRAMES * N_SIMS) / t), flush=True) print("main(): finished", flush=True)
def __init__(self, high_ctrl, low_ctrl, env_path, low_ctrl_config=None, arm_name="RightArm", desired_joints=None, isdraw=False): self.world = mujoco_py.load_model_from_path(env_path) self.sim = mujoco_py.MjSim(self.world) high_ctrl.motion_duration = 1.6 self.high_ctrl = high_ctrl self.high_ctrl.low_ctrl = low_ctrl(model=self.world, sim=self.sim, config=low_ctrl_config, \ arm_name=arm_name, desired_joints=desired_joints) self.isdraw = isdraw if self.isdraw: self.viewer = mujoco_py.MjViewer(self.sim) self.viewer._paused = True self.init_joints = INIT_JOINT_POS self.is_ball_pos_change = False self.is_data_collection = False
""" # Serialization/Deserialization of Models Sometimes its useful to send a mujoco model over the network, or save it to a file with all assets embedded. """ import mujoco_py # The binary MJB format is preferable, since it includes assets like # textures and meshes. model = mujoco_py.load_model_from_path("xmls/claw.xml") mjb_bytestring = model.get_mjb() model_from_binary = mujoco_py.load_model_from_mjb(mjb_bytestring) assert model.nbody == model_from_binary.nbody # XML is preferable to MJB when readability and backward compatibility are # important. xml_string = model.get_xml() model_from_xml = mujoco_py.load_model_from_xml(xml_string) assert model.nbody == model_from_xml.nbody
def simulationInit(path="inverted_pendulum.xml"): model = load_model_from_path(path) real_sim = MjSim(model) return real_sim
def _index_model(self, xml_filepath=None, mjmodel=None): assert (not (mjmodel is None and xml_filepath is None)) if mjmodel is not None: self.mjmodel = mjmodel elif xml_filepath is not None: self.mjmodel = load_model_from_path(xml_filepath)
#!/usr/bin/env python3 """ Shows how to use render callback. """ from mujoco_py import load_model_from_path, MjSim, MjViewer from mujoco_py.modder import TextureModder import os modder = None def render_callback(sim, viewer): global modder if modder is None: modder = TextureModder(sim) for name in sim.model.geom_names: modder.rand_all(name) model = load_model_from_path("xmls/fetch/main.xml") sim = MjSim(model, render_callback=render_callback) viewer = MjViewer(sim) t = 0 while True: viewer.render() t += 1 if t > 100 and os.getenv('TESTING') is not None: break