本文整理汇总了Python中mujoco_py.MjSim方法的典型用法代码示例。如果您正苦于以下问题:Python mujoco_py.MjSim方法的具体用法?Python mujoco_py.MjSim怎么用?Python mujoco_py.MjSim使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mujoco_py
的用法示例。
在下文中一共展示了mujoco_py.MjSim方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
def __init__(self, model_path, _hp):
self._frame_height = _hp.viewer_image_height
self._frame_width = _hp.viewer_image_width
self._model_path = model_path
self.sim = MjSim(load_model_from_path(self._model_path))
self._base_adim, self._base_sdim = None, None #state/action dimension of Mujoco control
self._adim, self._sdim = None, None #state/action dimension presented to agent
self.num_objects, self._n_joints = None, None
self._goal_obj_pose = None
self._goaldistances = []
self._ncam = _hp.ncam
self.cameras = ['cam{}'.format(i) for i in range(self._ncam)]
self._last_obs = None
self._hp = _hp
self._save_buffer = []
示例2: _init_scene_iseg
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
def _init_scene_iseg(
sim: mujoco_py.MjSim, world_xml: ET.Element,
height: int) -> mujoco_py.MjSim:
"""
Initialize the scene for instance segmentation rendering.
"""
for obj_id in range(1, height+1):
# get geom
mj_geom_name = 'shape_%s' % obj_id
mj_geom_id = sim.model.geom_name2id(mj_geom_name)
# set color
sim.model.geom_rgba[mj_geom_id] = np.array(ISEG_COLOR_CODES[obj_id], dtype=np.float32)
# advance simulation by one step to update rendering
sim.step()
return sim
# ---------- rendering setup ----------
示例3: _render_rgb
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
def _render_rgb(
sim: mujoco_py.MjSim,
camera: str, render_height: int, render_width: int,
world_xml: ET.Element):
lm = LightModder(sim)
cam_names = [c.attrib['name'] for c in world_xml.findall(".//camera")]
# lights off for all other cameras except the recording one
for cam in cam_names:
light_name = _get_cam_light_name(cam)
if light_name in sim.model.light_names:
lm.set_active(light_name, 1 if cam == camera else 0)
# take screenshot
frame = sim.render(render_width * 2, render_height, camera_name=camera)
# reset camera lights
for cam in cam_names:
light_name = _get_cam_light_name(cam)
if light_name in sim.model.light_names:
lm.set_active(light_name, 1)
return frame
示例4: _load_simulation
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
def _load_simulation(self, model_handle: Any) -> Any:
"""Loads the simulation from the given model handle.
Args:
model_handle: Path to the Mujoco XML file to load.
Returns:
A mujoco_py MjSim object.
"""
if isinstance(model_handle, str):
if not os.path.isfile(model_handle):
raise ValueError(
'[MjPySimScene] Invalid model file path: {}'.format(
model_handle))
model = mujoco_py.load_model_from_path(model_handle)
sim = mujoco_py.MjSim(model)
else:
raise NotImplementedError(model_handle)
return sim
示例5: __init__
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
def __init__(self, model_path, frame_skip):
if not path.exists(model_path):
raise IOError("File %s does not exist" % model_path)
self.frame_skip = frame_skip
self.model = mujoco_py.load_model_from_path(model_path)
self.sim = mujoco_py.MjSim(self.model)
self.data = self.sim.data
self.viewer = None
self._viewers = {}
self.metadata = {
'render.modes': ['human'],
'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()
示例6: _reset_internal
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
def _reset_internal(self):
"""Resets simulation internal configurations."""
# instantiate simulation from MJCF model
self._load_model()
self.mjpy_model = self.model.get_model(mode="mujoco_py")
self.sim = MjSim(self.mjpy_model)
self.initialize_time(self.control_freq)
# create visualization screen or renderer
if self.has_renderer and self.viewer is None:
self.viewer = MujocoPyRenderer(self.sim)
self.viewer.viewer.vopt.geomgroup[0] = (
1 if self.render_collision_mesh else 0
)
self.viewer.viewer.vopt.geomgroup[1] = 1 if self.render_visual_mesh else 0
# hiding the overlay speeds up rendering significantly
self.viewer.viewer._hide_overlay = True
elif self.has_offscreen_renderer:
if self.sim._render_context_offscreen is None:
render_context = MjRenderContextOffscreen(self.sim)
self.sim.add_render_context(render_context)
self.sim._render_context_offscreen.vopt.geomgroup[0] = (
1 if self.render_collision_mesh else 0
)
self.sim._render_context_offscreen.vopt.geomgroup[1] = (
1 if self.render_visual_mesh else 0
)
# additional housekeeping
self.sim_state_initial = self.sim.get_state()
self._get_reference()
self.cur_time = 0
self.timestep = 0
self.done = False
示例7: reset_from_xml_string
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
def reset_from_xml_string(self, xml_string):
"""Reloads the environment from an XML description of the environment."""
# if there is an active viewer window, destroy it
self.close()
# load model from xml
self.mjpy_model = load_model_from_xml(xml_string)
self.sim = MjSim(self.mjpy_model)
self.initialize_time(self.control_freq)
if self.has_renderer and self.viewer is None:
self.viewer = MujocoPyRenderer(self.sim)
self.viewer.viewer.vopt.geomgroup[0] = (
1 if self.render_collision_mesh else 0
)
self.viewer.viewer.vopt.geomgroup[1] = 1 if self.render_visual_mesh else 0
# hiding the overlay speeds up rendering significantly
self.viewer.viewer._hide_overlay = True
elif self.has_offscreen_renderer:
render_context = MjRenderContextOffscreen(self.sim)
render_context.vopt.geomgroup[0] = 1 if self.render_collision_mesh else 0
render_context.vopt.geomgroup[1] = 1 if self.render_visual_mesh else 0
self.sim.add_render_context(render_context)
self.sim_state_initial = self.sim.get_state()
self._get_reference()
self.cur_time = 0
self.timestep = 0
self.done = False
# necessary to refresh MjData
self.sim.forward()
示例8: start_simulation
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
def start_simulation(self):
"""
Starts simulation of the test world
"""
model = self.world.get_model(mode="mujoco_py")
self.sim = MjSim(model)
if self.render:
self.viewer = MjViewer(self.sim)
self.sim_state = self.sim.get_state()
# For gravity correction
gravity_corrected = ["gripper_z_joint"]
self._gravity_corrected_qvels = [
self.sim.model.get_joint_qvel_addr(x) for x in gravity_corrected
]
self.gripper_z_id = self.sim.model.actuator_name2id("gripper_z")
self.gripper_z_is_low = False
self.gripper_joint_ids = [
self.sim.model.actuator_name2id("gripper_" + x)
for x in self.gripper.joints
]
self.gripper_open_action = self.gripper.format_action([1])
self.gripper_closed_action = self.gripper.format_action(
[-1]
)
self.gripper_is_closed = True
self.object_id = self.sim.model.body_name2id("object")
object_default_pos = self.sim.data.body_xpos[self.object_id]
self.object_default_pos = np.array(object_default_pos,
copy=True)
self.reset()
self.simulation_ready = True
示例9: __init__
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
def __init__(self,
sim: MjSim,
camera_name: str=None,
screenshot_dir: str='/tmp/mujoco_screens'):
self._sim = sim
self._camera_name = camera_name
self._screenshot_dir = screenshot_dir
self._screenshots = []
self._image_name = "image_%04d.png"
self._time_last_screen = -inf
self._frames_per_second = 5
示例10: env_init
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
def env_init(render = False):
camera_name = 'camera_main'
model = load_model_from_path(JACO_MODEL_PATH)
sim = MjSim(model)
control_scheme = CustomControlScheme(sim.data.ctrl)
if render:
viewer = CustomMjViewer(sim,
control_scheme,
camera_name=camera_name)
else:
viewer= False
return model,sim,control_scheme,viewer
示例11: __init__
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
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'),
))
示例12: __init__
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
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()
示例13: get_sim
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
def get_sim(self):
self.placements = OrderedDict()
self.placements["top"] = {"origin": np.zeros(3),
"size": self.world_params.size}
name_indexes = OrderedDict()
self.to_names(name_indexes)
res = self.compile(self.random_state, world_params=self.world_params)
if not res:
raise FullVirtualWorldException('Failed to compile world')
self.set_absolute_position((0, 0, 0)) # Recursively set all positions
xml_dict = self.to_xml_dict()
xinit_dict = self.to_xinit()
udd_callbacks = self.to_udd_callback()
xml = unparse_dict(xml_dict)
model = load_model_from_xml(xml)
sim = MjSim(model, nsubsteps=self.world_params.num_substeps)
for name, value in xinit_dict.items():
sim.data.set_joint_qpos(name, value)
# Places mocap where related bodies are.
if sim.model.nmocap > 0 and sim.model.eq_data is not None:
for i in range(sim.model.eq_data.shape[0]):
if sim.model.eq_type[i] == const.EQ_WELD:
sim.model.eq_data[i, :] = np.array(
[0., 0., 0., 1., 0., 0., 0.])
udd_callbacks = (udd_callbacks or [])
if udd_callbacks is not None and len(udd_callbacks) > 0:
def merged_udd_callback(sim):
ret = {}
for udd_callback in udd_callbacks:
ret.update(udd_callback(sim))
return ret
sim.udd_callback = merged_udd_callback
return sim
示例14: _init_scene_vseg
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
def _init_scene_vseg(
sim: mujoco_py.MjSim, world_xml: ET.Element,
height: int, violations: set) -> mujoco_py.MjSim:
"""
Initialize the scene for violation segmentation rendering.
"""
pivot_point = height + 1
for obj_id in range(1, height+1):
# determine pivot point
if obj_id in violations:
pivot_point = obj_id
# get geom
mj_geom_name = 'shape_%s' % obj_id
mj_geom_id = sim.model.geom_name2id(mj_geom_name)
# determine color
if obj_id < pivot_point: # stable lower part
sim.model.geom_rgba[mj_geom_id] = np.array(VSEG_COLOR_CODES[1], dtype=np.float32)
elif obj_id == pivot_point: # violating object
sim.model.geom_rgba[mj_geom_id] = np.array(VSEG_COLOR_CODES[2], dtype=np.float32)
elif obj_id == pivot_point + 1: # object above violation
sim.model.geom_rgba[mj_geom_id] = np.array(VSEG_COLOR_CODES[3], dtype=np.float32)
elif obj_id > pivot_point + 1: # unstable upper part
sim.model.geom_rgba[mj_geom_id] = np.array(VSEG_COLOR_CODES[4], dtype=np.float32)
# advance simulation by one step to update rendering
sim.step()
return sim
示例15: _setup_render_rgb
# 需要导入模块: import mujoco_py [as 别名]
# 或者: from mujoco_py import MjSim [as 别名]
def _setup_render_rgb(sim: mujoco_py.MjSim) -> mujoco_py.MjSim:
# create copy of simulation to customize rendering context
# flags defined in mjvisualize.h
render_sim = mujoco_py.MjSim(sim.model)
render_sim.set_state(sim.get_state())
render_ctx = mujoco_py.MjRenderContextOffscreen(render_sim)
render_ctx.scn.stereo = 2 # side-by-side rendering
return render_sim