_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3 values | text stringlengths 75 19.8k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q34300 | SawyerStack.staged_rewards | train | def staged_rewards(self):
"""
Helper function to return staged rewards based on current physical states.
Returns:
r_reach (float): reward for reaching and grasping
r_lift (float): reward for lifting and aligning
r_stack (float): reward for stacking
"""
# reaching is successful when the gripper site is close to
# the center of the cube
cubeA_pos = self.sim.data.body_xpos[self.cubeA_body_id]
cubeB_pos = self.sim.data.body_xpos[self.cubeB_body_id]
gripper_site_pos = self.sim.data.site_xpos[self.eef_site_id]
dist = np.linalg.norm(gripper_site_pos - cubeA_pos)
r_reach = (1 - np.tanh(10.0 * dist)) * 0.25
# collision checking
touch_left_finger = False
touch_right_finger = False
touch_cubeA_cubeB = False
for i in range(self.sim.data.ncon):
c = self.sim.data.contact[i]
if c.geom1 in self.l_finger_geom_ids and c.geom2 == self.cubeA_geom_id:
touch_left_finger = True
if c.geom1 == self.cubeA_geom_id and c.geom2 in self.l_finger_geom_ids:
touch_left_finger = True
if c.geom1 in self.r_finger_geom_ids and c.geom2 == self.cubeA_geom_id:
touch_right_finger = True
if c.geom1 == self.cubeA_geom_id and c.geom2 in self.r_finger_geom_ids:
touch_right_finger = True
if c.geom1 == self.cubeA_geom_id and c.geom2 == self.cubeB_geom_id:
touch_cubeA_cubeB = True
if c.geom1 == self.cubeB_geom_id and c.geom2 == self.cubeA_geom_id:
touch_cubeA_cubeB = True
# additional grasping reward
if touch_left_finger and touch_right_finger:
r_reach += 0.25
# lifting is successful when the cube is above the table top
# by a margin
cubeA_height = cubeA_pos[2]
table_height = self.table_full_size[2]
cubeA_lifted = cubeA_height > table_height + 0.04
r_lift = 1.0 if cubeA_lifted else 0.0
# Aligning is successful when cubeA is right above cubeB
if cubeA_lifted:
horiz_dist = np.linalg.norm(
np.array(cubeA_pos[:2]) - np.array(cubeB_pos[:2])
)
r_lift += 0.5 * (1 - np.tanh(horiz_dist))
# stacking is successful when the block is lifted and
# the gripper is not holding the object
r_stack = 0
not_touching = not touch_left_finger and not touch_right_finger
if not_touching and r_lift > 0 and touch_cubeA_cubeB:
r_stack = 2.0
return (r_reach, r_lift, r_stack) | python | {
"resource": ""
} |
q34301 | NutAssemblyTask.merge_objects | train | def merge_objects(self, mujoco_objects):
"""Adds physical objects to the MJCF model."""
self.mujoco_objects = mujoco_objects
self.objects = {} # xml manifestation
self.max_horizontal_radius = 0
for obj_name, obj_mjcf in mujoco_objects.items():
self.merge_asset(obj_mjcf)
# Load object
obj = obj_mjcf.get_collision(name=obj_name, site=True)
obj.append(new_joint(name=obj_name, type="free", damping="0.0005"))
self.objects[obj_name] = obj
self.worldbody.append(obj)
self.max_horizontal_radius = max(
self.max_horizontal_radius, obj_mjcf.get_horizontal_radius()
) | python | {
"resource": ""
} |
q34302 | Gripper.hide_visualization | train | def hide_visualization(self):
"""
Hides all visualization geoms and sites.
This should be called before rendering to agents
"""
for site_name in self.visualization_sites:
site = self.worldbody.find(".//site[@name='{}']".format(site_name))
site.set("rgba", "0 0 0 0")
for geom_name in self.visualization_geoms:
geom = self.worldbody.find(".//geom[@name='{}']".format(geom_name))
geom.set("rgba", "0 0 0 0") | python | {
"resource": ""
} |
q34303 | BaxterLift._load_model | train | def _load_model(self):
"""
Loads the arena and pot object.
"""
super()._load_model()
self.mujoco_robot.set_base_xpos([0, 0, 0])
# load model for table top workspace
self.mujoco_arena = TableArena(
table_full_size=self.table_full_size, table_friction=self.table_friction
)
if self.use_indicator_object:
self.mujoco_arena.add_pos_indicator()
# The sawyer robot has a pedestal, we want to align it with the table
self.mujoco_arena.set_origin([0.45 + self.table_full_size[0] / 2, 0, 0])
# task includes arena, robot, and objects of interest
self.model = TableTopTask(
self.mujoco_arena,
self.mujoco_robot,
self.mujoco_objects,
self.object_initializer,
)
self.model.place_objects() | python | {
"resource": ""
} |
q34304 | BaxterLift._pot_quat | train | def _pot_quat(self):
"""Returns the orientation of the pot."""
return T.convert_quat(self.sim.data.body_xquat[self.cube_body_id], to="xyzw") | python | {
"resource": ""
} |
q34305 | BaxterLift._check_success | train | def _check_success(self):
"""
Returns True if task is successfully completed
"""
# cube is higher than the table top above a margin
cube_height = self.sim.data.body_xpos[self.cube_body_id][2]
table_height = self.table_full_size[2]
return cube_height > table_height + 0.10 | python | {
"resource": ""
} |
q34306 | DataCollectionWrapper._start_new_episode | train | def _start_new_episode(self):
"""
Bookkeeping to do at the start of each new episode.
"""
# flush any data left over from the previous episode if any interactions have happened
if self.has_interaction:
self._flush()
# timesteps in current episode
self.t = 0
self.has_interaction = False | python | {
"resource": ""
} |
q34307 | DataCollectionWrapper._flush | train | def _flush(self):
"""
Method to flush internal state to disk.
"""
t1, t2 = str(time.time()).split(".")
state_path = os.path.join(self.ep_directory, "state_{}_{}.npz".format(t1, t2))
if hasattr(self.env, "unwrapped"):
env_name = self.env.unwrapped.__class__.__name__
else:
env_name = self.env.__class__.__name__
np.savez(
state_path,
states=np.array(self.states),
action_infos=self.action_infos,
env=env_name,
)
self.states = []
self.action_infos = [] | python | {
"resource": ""
} |
q34308 | MujocoXML.resolve_asset_dependency | train | def resolve_asset_dependency(self):
"""
Converts every file dependency into absolute path so when we merge we don't break things.
"""
for node in self.asset.findall("./*[@file]"):
file = node.get("file")
abs_path = os.path.abspath(self.folder)
abs_path = os.path.join(abs_path, file)
node.set("file", abs_path) | python | {
"resource": ""
} |
q34309 | MujocoXML.create_default_element | train | def create_default_element(self, name):
"""
Creates a <@name/> tag under root if there is none.
"""
found = self.root.find(name)
if found is not None:
return found
ele = ET.Element(name)
self.root.append(ele)
return ele | python | {
"resource": ""
} |
q34310 | MujocoXML.merge | train | def merge(self, other, merge_body=True):
"""
Default merge method.
Args:
other: another MujocoXML instance
raises XML error if @other is not a MujocoXML instance.
merges <worldbody/>, <actuator/> and <asset/> of @other into @self
merge_body: True if merging child bodies of @other. Defaults to True.
"""
if not isinstance(other, MujocoXML):
raise XMLError("{} is not a MujocoXML instance.".format(type(other)))
if merge_body:
for body in other.worldbody:
self.worldbody.append(body)
self.merge_asset(other)
for one_actuator in other.actuator:
self.actuator.append(one_actuator)
for one_equality in other.equality:
self.equality.append(one_equality)
for one_contact in other.contact:
self.contact.append(one_contact)
for one_default in other.default:
self.default.append(one_default) | python | {
"resource": ""
} |
q34311 | MujocoXML.get_model | train | def get_model(self, mode="mujoco_py"):
"""
Returns a MjModel instance from the current xml tree.
"""
available_modes = ["mujoco_py"]
with io.StringIO() as string:
string.write(ET.tostring(self.root, encoding="unicode"))
if mode == "mujoco_py":
from mujoco_py import load_model_from_xml
model = load_model_from_xml(string.getvalue())
return model
raise ValueError(
"Unkown model mode: {}. Available options are: {}".format(
mode, ",".join(available_modes)
)
) | python | {
"resource": ""
} |
q34312 | MujocoXML.get_xml | train | def get_xml(self):
"""
Returns a string of the MJCF XML file.
"""
with io.StringIO() as string:
string.write(ET.tostring(self.root, encoding="unicode"))
return string.getvalue() | python | {
"resource": ""
} |
q34313 | MujocoXML.save_model | train | def save_model(self, fname, pretty=False):
"""
Saves the xml to file.
Args:
fname: output file location
pretty: attempts!! to pretty print the output
"""
with open(fname, "w") as f:
xml_str = ET.tostring(self.root, encoding="unicode")
if pretty:
# TODO: get a better pretty print library
parsed_xml = xml.dom.minidom.parseString(xml_str)
xml_str = parsed_xml.toprettyxml(newl="")
f.write(xml_str) | python | {
"resource": ""
} |
q34314 | MujocoXML.merge_asset | train | def merge_asset(self, other):
"""
Useful for merging other files in a custom logic.
"""
for asset in other.asset:
asset_name = asset.get("name")
asset_type = asset.tag
# Avoids duplication
pattern = "./{}[@name='{}']".format(asset_type, asset_name)
if self.asset.find(pattern) is None:
self.asset.append(asset) | python | {
"resource": ""
} |
q34315 | GymWrapper._flatten_obs | train | def _flatten_obs(self, obs_dict, verbose=False):
"""
Filters keys of interest out and concatenate the information.
Args:
obs_dict: ordered dictionary of observations
"""
ob_lst = []
for key in obs_dict:
if key in self.keys:
if verbose:
print("adding key: {}".format(key))
ob_lst.append(obs_dict[key])
return np.concatenate(ob_lst) | python | {
"resource": ""
} |
q34316 | PickPlaceTask.merge_visual | train | def merge_visual(self, mujoco_objects):
"""Adds visual objects to the MJCF model."""
self.visual_obj_mjcf = []
for obj_name, obj_mjcf in mujoco_objects.items():
self.merge_asset(obj_mjcf)
# Load object
obj = obj_mjcf.get_visual(name=obj_name, site=False)
self.visual_obj_mjcf.append(obj)
self.worldbody.append(obj) | python | {
"resource": ""
} |
q34317 | PickPlaceTask.place_visual | train | def place_visual(self):
"""Places visual objects randomly until no collisions or max iterations hit."""
index = 0
bin_pos = string_to_array(self.bin2_body.get("pos"))
bin_size = self.bin_size
for _, obj_mjcf in self.visual_objects:
bin_x_low = bin_pos[0]
bin_y_low = bin_pos[1]
if index == 0 or index == 2:
bin_x_low -= bin_size[0] / 2
if index < 2:
bin_y_low -= bin_size[1] / 2
bin_x_high = bin_x_low + bin_size[0] / 2
bin_y_high = bin_y_low + bin_size[1] / 2
bottom_offset = obj_mjcf.get_bottom_offset()
bin_range = [bin_x_low + bin_x_high, bin_y_low + bin_y_high, 2 * bin_pos[2]]
bin_center = np.array(bin_range) / 2.0
pos = bin_center - bottom_offset
self.visual_obj_mjcf[index].set("pos", array_to_string(pos))
index += 1 | python | {
"resource": ""
} |
q34318 | SawyerLift._load_model | train | def _load_model(self):
"""
Loads an xml model, puts it in self.model
"""
super()._load_model()
self.mujoco_robot.set_base_xpos([0, 0, 0])
# load model for table top workspace
self.mujoco_arena = TableArena(
table_full_size=self.table_full_size, table_friction=self.table_friction
)
if self.use_indicator_object:
self.mujoco_arena.add_pos_indicator()
# The sawyer robot has a pedestal, we want to align it with the table
self.mujoco_arena.set_origin([0.16 + self.table_full_size[0] / 2, 0, 0])
# initialize objects of interest
cube = BoxObject(
size_min=[0.020, 0.020, 0.020], # [0.015, 0.015, 0.015],
size_max=[0.022, 0.022, 0.022], # [0.018, 0.018, 0.018])
rgba=[1, 0, 0, 1],
)
self.mujoco_objects = OrderedDict([("cube", cube)])
# task includes arena, robot, and objects of interest
self.model = TableTopTask(
self.mujoco_arena,
self.mujoco_robot,
self.mujoco_objects,
initializer=self.placement_initializer,
)
self.model.place_objects() | python | {
"resource": ""
} |
q34319 | MujocoPyRenderer.set_camera | train | def set_camera(self, camera_id):
"""
Set the camera view to the specified camera ID.
"""
self.viewer.cam.fixedcamid = camera_id
self.viewer.cam.type = const.CAMERA_FIXED | python | {
"resource": ""
} |
q34320 | MujocoPyRenderer.add_keypress_callback | train | def add_keypress_callback(self, key, fn):
"""
Allows for custom callback functions for the viewer. Called on key down.
Parameter 'any' will ensure that the callback is called on any key down,
and block default mujoco viewer callbacks from executing, except for
the ESC callback to close the viewer.
"""
self.viewer.keypress[key].append(fn) | python | {
"resource": ""
} |
q34321 | MujocoPyRenderer.add_keyup_callback | train | def add_keyup_callback(self, key, fn):
"""
Allows for custom callback functions for the viewer. Called on key up.
Parameter 'any' will ensure that the callback is called on any key up,
and block default mujoco viewer callbacks from executing, except for
the ESC callback to close the viewer.
"""
self.viewer.keyup[key].append(fn) | python | {
"resource": ""
} |
q34322 | MujocoPyRenderer.add_keyrepeat_callback | train | def add_keyrepeat_callback(self, key, fn):
"""
Allows for custom callback functions for the viewer. Called on key repeat.
Parameter 'any' will ensure that the callback is called on any key repeat,
and block default mujoco viewer callbacks from executing, except for
the ESC callback to close the viewer.
"""
self.viewer.keyrepeat[key].append(fn) | python | {
"resource": ""
} |
q34323 | DemoSamplerWrapper.reset | train | def reset(self):
"""
Logic for sampling a state from the demonstration and resetting
the simulation to that state.
"""
state = self.sample()
if state is None:
# None indicates that a normal env reset should occur
return self.env.reset()
else:
if self.need_xml:
# reset the simulation from the model if necessary
state, xml = state
self.env.reset_from_xml_string(xml)
if isinstance(state, tuple):
state = state[0]
# force simulator state to one from the demo
self.sim.set_state_from_flattened(state)
self.sim.forward()
return self.env._get_observation() | python | {
"resource": ""
} |
q34324 | DemoSamplerWrapper.sample | train | def sample(self):
"""
This is the core sampling method. Samples a state from a
demonstration, in accordance with the configuration.
"""
# chooses a sampling scheme randomly based on the mixing ratios
seed = random.uniform(0, 1)
ratio = np.cumsum(self.scheme_ratios)
ratio = ratio > seed
for i, v in enumerate(ratio):
if v:
break
sample_method = getattr(self, self.sample_method_dict[self.sampling_schemes[i]])
return sample_method() | python | {
"resource": ""
} |
q34325 | DemoSamplerWrapper._xml_for_episode_index | train | def _xml_for_episode_index(self, ep_ind):
"""
Helper method to retrieve the corresponding model xml string
for the passed episode index.
"""
# read the model xml, using the metadata stored in the attribute for this episode
model_file = self.demo_file["data/{}".format(ep_ind)].attrs["model_file"]
model_path = os.path.join(self.demo_path, "models", model_file)
with open(model_path, "r") as model_f:
model_xml = model_f.read()
return model_xml | python | {
"resource": ""
} |
q34326 | to_int16 | train | def to_int16(y1, y2):
"""Convert two 8 bit bytes to a signed 16 bit integer."""
x = (y1) | (y2 << 8)
if x >= 32768:
x = -(65536 - x)
return x | python | {
"resource": ""
} |
q34327 | scale_to_control | train | def scale_to_control(x, axis_scale=350., min_v=-1.0, max_v=1.0):
"""Normalize raw HID readings to target range."""
x = x / axis_scale
x = min(max(x, min_v), max_v)
return x | python | {
"resource": ""
} |
q34328 | SpaceMouse.get_controller_state | train | def get_controller_state(self):
"""Returns the current state of the 3d mouse, a dictionary of pos, orn, grasp, and reset."""
dpos = self.control[:3] * 0.005
roll, pitch, yaw = self.control[3:] * 0.005
self.grasp = self.control_gripper
# convert RPY to an absolute orientation
drot1 = rotation_matrix(angle=-pitch, direction=[1., 0, 0], point=None)[:3, :3]
drot2 = rotation_matrix(angle=roll, direction=[0, 1., 0], point=None)[:3, :3]
drot3 = rotation_matrix(angle=yaw, direction=[0, 0, 1.], point=None)[:3, :3]
self.rotation = self.rotation.dot(drot1.dot(drot2.dot(drot3)))
return dict(
dpos=dpos, rotation=self.rotation, grasp=self.grasp, reset=self._reset_state
) | python | {
"resource": ""
} |
q34329 | SpaceMouse.run | train | def run(self):
"""Listener method that keeps pulling new messages."""
t_last_click = -1
while True:
d = self.device.read(13)
if d is not None and self._enabled:
if d[0] == 1: ## readings from 6-DoF sensor
self.y = convert(d[1], d[2])
self.x = convert(d[3], d[4])
self.z = convert(d[5], d[6]) * -1.0
self.roll = convert(d[7], d[8])
self.pitch = convert(d[9], d[10])
self.yaw = convert(d[11], d[12])
self._control = [
self.x,
self.y,
self.z,
self.roll,
self.pitch,
self.yaw,
]
elif d[0] == 3: ## readings from the side buttons
# press left button
if d[1] == 1:
t_click = time.time()
elapsed_time = t_click - t_last_click
t_last_click = t_click
self.single_click_and_hold = True
# release left button
if d[1] == 0:
self.single_click_and_hold = False
# right button is for reset
if d[1] == 2:
self._reset_state = 1
self._enabled = False
self._reset_internal_state() | python | {
"resource": ""
} |
q34330 | Robot.add_gripper | train | def add_gripper(self, arm_name, gripper):
"""
Mounts gripper to arm.
Throws error if robot already has a gripper or gripper type is incorrect.
Args:
arm_name (str): name of arm mount
gripper (MujocoGripper instance): gripper MJCF model
"""
if arm_name in self.grippers:
raise ValueError("Attempts to add multiple grippers to one body")
arm_subtree = self.worldbody.find(".//body[@name='{}']".format(arm_name))
for actuator in gripper.actuator:
if actuator.get("name") is None:
raise XMLError("Actuator has no name")
if not actuator.get("name").startswith("gripper"):
raise XMLError(
"Actuator name {} does not have prefix 'gripper'".format(
actuator.get("name")
)
)
for body in gripper.worldbody:
arm_subtree.append(body)
self.merge(gripper, merge_body=False)
self.grippers[arm_name] = gripper | python | {
"resource": ""
} |
q34331 | Arena.set_origin | train | def set_origin(self, offset):
"""Applies a constant offset to all objects."""
offset = np.array(offset)
for node in self.worldbody.findall("./*[@pos]"):
cur_pos = string_to_array(node.get("pos"))
new_pos = cur_pos + offset
node.set("pos", array_to_string(new_pos)) | python | {
"resource": ""
} |
q34332 | Arena.add_pos_indicator | train | def add_pos_indicator(self):
"""Adds a new position indicator."""
body = new_body(name="pos_indicator")
body.append(
new_geom(
"sphere",
[0.03],
rgba=[1, 0, 0, 0.5],
group=1,
contype="0",
conaffinity="0",
)
)
body.append(new_joint(type="free", name="pos_indicator"))
self.worldbody.append(body) | python | {
"resource": ""
} |
q34333 | TableArena.table_top_abs | train | def table_top_abs(self):
"""Returns the absolute position of table top"""
table_height = np.array([0, 0, self.table_full_size[2]])
return string_to_array(self.floor.get("pos")) + table_height | python | {
"resource": ""
} |
q34334 | BaxterEnv._reset_internal | train | def _reset_internal(self):
"""Resets the pose of the arm and grippers."""
super()._reset_internal()
self.sim.data.qpos[self._ref_joint_pos_indexes] = self.mujoco_robot.init_qpos
if self.has_gripper_right:
self.sim.data.qpos[
self._ref_joint_gripper_right_actuator_indexes
] = self.gripper_right.init_qpos
if self.has_gripper_left:
self.sim.data.qpos[
self._ref_joint_gripper_left_actuator_indexes
] = self.gripper_left.init_qpos | python | {
"resource": ""
} |
q34335 | BaxterEnv._get_reference | train | def _get_reference(self):
"""Sets up references for robots, grippers, and objects."""
super()._get_reference()
# indices for joints in qpos, qvel
self.robot_joints = list(self.mujoco_robot.joints)
self._ref_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.robot_joints
]
self._ref_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.robot_joints
]
if self.use_indicator_object:
ind_qpos = self.sim.model.get_joint_qpos_addr("pos_indicator")
self._ref_indicator_pos_low, self._ref_indicator_pos_high = ind_qpos
ind_qvel = self.sim.model.get_joint_qvel_addr("pos_indicator")
self._ref_indicator_vel_low, self._ref_indicator_vel_high = ind_qvel
self.indicator_id = self.sim.model.body_name2id("pos_indicator")
# indices for grippers in qpos, qvel
if self.has_gripper_left:
self.gripper_left_joints = list(self.gripper_left.joints)
self._ref_gripper_left_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.gripper_left_joints
]
self._ref_gripper_left_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.gripper_left_joints
]
self.left_eef_site_id = self.sim.model.site_name2id("l_g_grip_site")
if self.has_gripper_right:
self.gripper_right_joints = list(self.gripper_right.joints)
self._ref_gripper_right_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.gripper_right_joints
]
self._ref_gripper_right_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.gripper_right_joints
]
self.right_eef_site_id = self.sim.model.site_name2id("grip_site")
# indices for joint pos actuation, joint vel actuation, gripper actuation
self._ref_joint_pos_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("pos")
]
self._ref_joint_vel_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("vel")
]
if self.has_gripper_left:
self._ref_joint_gripper_left_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("gripper_l")
]
if self.has_gripper_right:
self._ref_joint_gripper_right_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("gripper_r")
]
if self.has_gripper_right:
# IDs of sites for gripper visualization
self.eef_site_id = self.sim.model.site_name2id("grip_site")
self.eef_cylinder_id = self.sim.model.site_name2id("grip_site_cylinder") | python | {
"resource": ""
} |
q34336 | BaxterEnv.move_indicator | train | def move_indicator(self, pos):
"""Moves the position of the indicator object to @pos."""
if self.use_indicator_object:
self.sim.data.qpos[
self._ref_indicator_pos_low : self._ref_indicator_pos_low + 3
] = pos | python | {
"resource": ""
} |
q34337 | BaxterEnv._post_action | train | def _post_action(self, action):
"""Optionally performs gripper visualization after the actions."""
ret = super()._post_action(action)
self._gripper_visualization()
return ret | python | {
"resource": ""
} |
q34338 | BaxterEnv.set_robot_joint_positions | train | def set_robot_joint_positions(self, jpos):
"""
Helper method to force robot joint positions to the passed values.
"""
self.sim.data.qpos[self._ref_joint_pos_indexes] = jpos
self.sim.forward() | python | {
"resource": ""
} |
q34339 | Baxter.set_base_xpos | train | def set_base_xpos(self, pos):
"""Places the robot on position @pos."""
node = self.worldbody.find("./body[@name='base']")
node.set("pos", array_to_string(pos - self.bottom_offset)) | python | {
"resource": ""
} |
q34340 | _get_size | train | def _get_size(size,
size_max,
size_min,
default_max,
default_min):
"""
Helper method for providing a size,
or a range to randomize from
"""
if len(default_max) != len(default_min):
raise ValueError('default_max = {} and default_min = {}'
.format(str(default_max), str(default_min)) +
' have different lengths')
if size is not None:
if (size_max is not None) or (size_min is not None):
raise ValueError('size = {} overrides size_max = {}, size_min = {}'
.format(size, size_max, size_min))
else:
if size_max is None:
size_max = default_max
if size_min is None:
size_min = default_min
size = np.array([np.random.uniform(size_min[i], size_max[i])
for i in range(len(default_max))])
return size | python | {
"resource": ""
} |
q34341 | _get_randomized_range | train | def _get_randomized_range(val,
provided_range,
default_range):
"""
Helper to initialize by either value or a range
Returns a range to randomize from
"""
if val is None:
if provided_range is None:
return default_range
else:
return provided_range
else:
if provided_range is not None:
raise ValueError('Value {} overrides range {}'
.format(str(val), str(provided_range)))
return [val] | python | {
"resource": ""
} |
q34342 | gripper_factory | train | def gripper_factory(name):
"""
Genreator for grippers
Creates a Gripper instance with the provided name.
Args:
name: the name of the gripper class
Returns:
gripper: Gripper instance
Raises:
XMLError: [description]
"""
if name == "TwoFingerGripper":
return TwoFingerGripper()
if name == "LeftTwoFingerGripper":
return LeftTwoFingerGripper()
if name == "PR2Gripper":
return PR2Gripper()
if name == "RobotiqGripper":
return RobotiqGripper()
if name == "PushingGripper":
return PushingGripper()
if name == "RobotiqThreeFingerGripper":
return RobotiqThreeFingerGripper()
raise ValueError("Unkown gripper name {}".format(name)) | python | {
"resource": ""
} |
q34343 | Keyboard._display_controls | train | def _display_controls(self):
"""
Method to pretty print controls.
"""
def print_command(char, info):
char += " " * (10 - len(char))
print("{}\t{}".format(char, info))
print("")
print_command("Keys", "Command")
print_command("q", "reset simulation")
print_command("spacebar", "toggle gripper (open/close)")
print_command("w-a-s-d", "move arm horizontally in x-y plane")
print_command("r-f", "move arm vertically")
print_command("z-x", "rotate arm about x-axis")
print_command("t-g", "rotate arm about y-axis")
print_command("c-v", "rotate arm about z-axis")
print_command("ESC", "quit")
print("") | python | {
"resource": ""
} |
q34344 | Keyboard._reset_internal_state | train | def _reset_internal_state(self):
"""
Resets internal state of controller, except for the reset signal.
"""
self.rotation = np.array([[-1., 0., 0.], [0., 1., 0.], [0., 0., -1.]])
self.pos = np.zeros(3) # (x, y, z)
self.last_pos = np.zeros(3)
self.grasp = False | python | {
"resource": ""
} |
q34345 | Keyboard.get_controller_state | train | def get_controller_state(self):
"""Returns the current state of the keyboard, a dictionary of pos, orn, grasp, and reset."""
dpos = self.pos - self.last_pos
self.last_pos = np.array(self.pos)
return dict(
dpos=dpos,
rotation=self.rotation,
grasp=int(self.grasp),
reset=self._reset_state,
) | python | {
"resource": ""
} |
q34346 | Keyboard.on_press | train | def on_press(self, window, key, scancode, action, mods):
"""
Key handler for key presses.
"""
# controls for moving position
if key == glfw.KEY_W:
self.pos[0] -= self._pos_step # dec x
elif key == glfw.KEY_S:
self.pos[0] += self._pos_step # inc x
elif key == glfw.KEY_A:
self.pos[1] -= self._pos_step # dec y
elif key == glfw.KEY_D:
self.pos[1] += self._pos_step # inc y
elif key == glfw.KEY_F:
self.pos[2] -= self._pos_step # dec z
elif key == glfw.KEY_R:
self.pos[2] += self._pos_step # inc z
# controls for moving orientation
elif key == glfw.KEY_Z:
drot = rotation_matrix(angle=0.1, direction=[1., 0., 0.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates x
elif key == glfw.KEY_X:
drot = rotation_matrix(angle=-0.1, direction=[1., 0., 0.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates x
elif key == glfw.KEY_T:
drot = rotation_matrix(angle=0.1, direction=[0., 1., 0.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates y
elif key == glfw.KEY_G:
drot = rotation_matrix(angle=-0.1, direction=[0., 1., 0.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates y
elif key == glfw.KEY_C:
drot = rotation_matrix(angle=0.1, direction=[0., 0., 1.])[:3, :3]
self.rotation = self.rotation.dot(drot) # rotates z
elif key == glfw.KEY_V:
drot = rotation_matrix(angle=-0.1, direction=[0., 0., 1.])[:3, :3]
self.rotation = self.rotation.dot(drot) | python | {
"resource": ""
} |
q34347 | Keyboard.on_release | train | def on_release(self, window, key, scancode, action, mods):
"""
Key handler for key releases.
"""
# controls for grasping
if key == glfw.KEY_SPACE:
self.grasp = not self.grasp # toggle gripper
# user-commanded reset
elif key == glfw.KEY_Q:
self._reset_state = 1
self._enabled = False
self._reset_internal_state() | python | {
"resource": ""
} |
q34348 | xml_path_completion | train | def xml_path_completion(xml_path):
"""
Takes in a local xml path and returns a full path.
if @xml_path is absolute, do nothing
if @xml_path is not absolute, load xml that is shipped by the package
"""
if xml_path.startswith("/"):
full_path = xml_path
else:
full_path = os.path.join(robosuite.models.assets_root, xml_path)
return full_path | python | {
"resource": ""
} |
q34349 | postprocess_model_xml | train | def postprocess_model_xml(xml_str):
"""
This function postprocesses the model.xml collected from a MuJoCo demonstration
in order to make sure that the STL files can be found.
"""
path = os.path.split(robosuite.__file__)[0]
path_split = path.split("/")
# replace mesh and texture file paths
tree = ET.fromstring(xml_str)
root = tree
asset = root.find("asset")
meshes = asset.findall("mesh")
textures = asset.findall("texture")
all_elements = meshes + textures
for elem in all_elements:
old_path = elem.get("file")
if old_path is None:
continue
old_path_split = old_path.split("/")
ind = max(
loc for loc, val in enumerate(old_path_split) if val == "robosuite"
) # last occurrence index
new_path_split = path_split + old_path_split[ind + 1 :]
new_path = "/".join(new_path_split)
elem.set("file", new_path)
return ET.tostring(root, encoding="utf8").decode("utf8") | python | {
"resource": ""
} |
q34350 | BaxterIKController.sync_ik_robot | train | def sync_ik_robot(self, joint_positions, simulate=False, sync_last=True):
"""
Force the internal robot model to match the provided joint angles.
Args:
joint_positions (list): a list or flat numpy array of joint positions.
simulate (bool): If True, actually use physics simulation, else
write to physics state directly.
sync_last (bool): If False, don't sync the last joint angle. This
is useful for directly controlling the roll at the end effector.
"""
num_joints = len(joint_positions)
if not sync_last:
num_joints -= 1
for i in range(num_joints):
if simulate:
p.setJointMotorControl2(
self.ik_robot,
self.actual[i],
p.POSITION_CONTROL,
targetVelocity=0,
targetPosition=joint_positions[i],
force=500,
positionGain=0.5,
velocityGain=1.,
)
else:
# Note that we use self.actual[i], and not i
p.resetJointState(self.ik_robot, self.actual[i], joint_positions[i]) | python | {
"resource": ""
} |
q34351 | BaxterIKController.bullet_base_pose_to_world_pose | train | def bullet_base_pose_to_world_pose(self, pose_in_base):
"""
Convert a pose in the base frame to a pose in the world frame.
Args:
pose_in_base: a (pos, orn) tuple.
Returns:
pose_in world: a (pos, orn) tuple.
"""
pose_in_base = T.pose2mat(pose_in_base)
base_pos_in_world = np.array(p.getBasePositionAndOrientation(self.ik_robot)[0])
base_orn_in_world = np.array(p.getBasePositionAndOrientation(self.ik_robot)[1])
base_pose_in_world = T.pose2mat((base_pos_in_world, base_orn_in_world))
pose_in_world = T.pose_in_A_to_pose_in_B(
pose_A=pose_in_base, pose_A_in_B=base_pose_in_world
)
return T.mat2pose(pose_in_world) | python | {
"resource": ""
} |
q34352 | BaxterIKController.clip_joint_velocities | train | def clip_joint_velocities(self, velocities):
"""
Clips joint velocities into a valid range.
"""
for i in range(len(velocities)):
if velocities[i] >= 1.0:
velocities[i] = 1.0
elif velocities[i] <= -1.0:
velocities[i] = -1.0
return velocities | python | {
"resource": ""
} |
q34353 | BaxterPegInHole._load_model | train | def _load_model(self):
"""
Loads the peg and the hole models.
"""
super()._load_model()
self.mujoco_robot.set_base_xpos([0, 0, 0])
# Add arena and robot
self.model = MujocoWorldBase()
self.arena = EmptyArena()
if self.use_indicator_object:
self.arena.add_pos_indicator()
self.model.merge(self.arena)
self.model.merge(self.mujoco_robot)
# Load hole object
self.hole_obj = self.hole.get_collision(name="hole", site=True)
self.hole_obj.set("quat", "0 0 0.707 0.707")
self.hole_obj.set("pos", "0.11 0 0.18")
self.model.merge_asset(self.hole)
self.model.worldbody.find(".//body[@name='left_hand']").append(self.hole_obj)
# Load cylinder object
self.cyl_obj = self.cylinder.get_collision(name="cylinder", site=True)
self.cyl_obj.set("pos", "0 0 0.15")
self.model.merge_asset(self.cylinder)
self.model.worldbody.find(".//body[@name='right_hand']").append(self.cyl_obj)
self.model.worldbody.find(".//geom[@name='cylinder']").set("rgba", "0 1 0 1") | python | {
"resource": ""
} |
q34354 | BaxterPegInHole._compute_orientation | train | def _compute_orientation(self):
"""
Helper function to return the relative positions between the hole and the peg.
In particular, the intersection of the line defined by the peg and the plane
defined by the hole is computed; the parallel distance, perpendicular distance,
and angle are returned.
"""
cyl_mat = self.sim.data.body_xmat[self.cyl_body_id]
cyl_mat.shape = (3, 3)
cyl_pos = self.sim.data.body_xpos[self.cyl_body_id]
hole_pos = self.sim.data.body_xpos[self.hole_body_id]
hole_mat = self.sim.data.body_xmat[self.hole_body_id]
hole_mat.shape = (3, 3)
v = cyl_mat @ np.array([0, 0, 1])
v = v / np.linalg.norm(v)
center = hole_pos + hole_mat @ np.array([0.1, 0, 0])
t = (center - cyl_pos) @ v / (np.linalg.norm(v) ** 2)
d = np.linalg.norm(np.cross(v, cyl_pos - center)) / np.linalg.norm(v)
hole_normal = hole_mat @ np.array([0, 0, 1])
return (
t,
d,
abs(
np.dot(hole_normal, v) / np.linalg.norm(hole_normal) / np.linalg.norm(v)
),
) | python | {
"resource": ""
} |
q34355 | BaxterPegInHole._check_success | train | def _check_success(self):
"""
Returns True if task is successfully completed.
"""
t, d, cos = self._compute_orientation()
return d < 0.06 and t >= -0.12 and t <= 0.14 and cos > 0.95 | python | {
"resource": ""
} |
q34356 | mat2euler | train | def mat2euler(rmat, axes="sxyz"):
"""
Converts given rotation matrix to euler angles in radian.
Args:
rmat: 3x3 rotation matrix
axes: One of 24 axis sequences as string or encoded tuple
Returns:
converted euler angles in radian vec3 float
"""
try:
firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
except (AttributeError, KeyError):
firstaxis, parity, repetition, frame = axes
i = firstaxis
j = _NEXT_AXIS[i + parity]
k = _NEXT_AXIS[i - parity + 1]
M = np.array(rmat, dtype=np.float32, copy=False)[:3, :3]
if repetition:
sy = math.sqrt(M[i, j] * M[i, j] + M[i, k] * M[i, k])
if sy > EPS:
ax = math.atan2(M[i, j], M[i, k])
ay = math.atan2(sy, M[i, i])
az = math.atan2(M[j, i], -M[k, i])
else:
ax = math.atan2(-M[j, k], M[j, j])
ay = math.atan2(sy, M[i, i])
az = 0.0
else:
cy = math.sqrt(M[i, i] * M[i, i] + M[j, i] * M[j, i])
if cy > EPS:
ax = math.atan2(M[k, j], M[k, k])
ay = math.atan2(-M[k, i], cy)
az = math.atan2(M[j, i], M[i, i])
else:
ax = math.atan2(-M[j, k], M[j, j])
ay = math.atan2(-M[k, i], cy)
az = 0.0
if parity:
ax, ay, az = -ax, -ay, -az
if frame:
ax, az = az, ax
return vec((ax, ay, az)) | python | {
"resource": ""
} |
q34357 | pose2mat | train | def pose2mat(pose):
"""
Converts pose to homogeneous matrix.
Args:
pose: a (pos, orn) tuple where pos is vec3 float cartesian, and
orn is vec4 float quaternion.
Returns:
4x4 homogeneous matrix
"""
homo_pose_mat = np.zeros((4, 4), dtype=np.float32)
homo_pose_mat[:3, :3] = quat2mat(pose[1])
homo_pose_mat[:3, 3] = np.array(pose[0], dtype=np.float32)
homo_pose_mat[3, 3] = 1.
return homo_pose_mat | python | {
"resource": ""
} |
q34358 | pose_inv | train | def pose_inv(pose):
"""
Computes the inverse of a homogenous matrix corresponding to the pose of some
frame B in frame A. The inverse is the pose of frame A in frame B.
Args:
pose: numpy array of shape (4,4) for the pose to inverse
Returns:
numpy array of shape (4,4) for the inverse pose
"""
# Note, the inverse of a pose matrix is the following
# [R t; 0 1]^-1 = [R.T -R.T*t; 0 1]
# Intuitively, this makes sense.
# The original pose matrix translates by t, then rotates by R.
# We just invert the rotation by applying R-1 = R.T, and also translate back.
# Since we apply translation first before rotation, we need to translate by
# -t in the original frame, which is -R-1*t in the new frame, and then rotate back by
# R-1 to align the axis again.
pose_inv = np.zeros((4, 4))
pose_inv[:3, :3] = pose[:3, :3].T
pose_inv[:3, 3] = -pose_inv[:3, :3].dot(pose[:3, 3])
pose_inv[3, 3] = 1.0
return pose_inv | python | {
"resource": ""
} |
q34359 | _skew_symmetric_translation | train | def _skew_symmetric_translation(pos_A_in_B):
"""
Helper function to get a skew symmetric translation matrix for converting quantities
between frames.
"""
return np.array(
[
0.,
-pos_A_in_B[2],
pos_A_in_B[1],
pos_A_in_B[2],
0.,
-pos_A_in_B[0],
-pos_A_in_B[1],
pos_A_in_B[0],
0.,
]
).reshape((3, 3)) | python | {
"resource": ""
} |
q34360 | vel_in_A_to_vel_in_B | train | def vel_in_A_to_vel_in_B(vel_A, ang_vel_A, pose_A_in_B):
"""
Converts linear and angular velocity of a point in frame A to the equivalent in frame B.
Args:
vel_A: 3-dim iterable for linear velocity in A
ang_vel_A: 3-dim iterable for angular velocity in A
pose_A_in_B: numpy array of shape (4,4) corresponding to the pose of A in frame B
Returns:
vel_B, ang_vel_B: two numpy arrays of shape (3,) for the velocities in B
"""
pos_A_in_B = pose_A_in_B[:3, 3]
rot_A_in_B = pose_A_in_B[:3, :3]
skew_symm = _skew_symmetric_translation(pos_A_in_B)
vel_B = rot_A_in_B.dot(vel_A) + skew_symm.dot(rot_A_in_B.dot(ang_vel_A))
ang_vel_B = rot_A_in_B.dot(ang_vel_A)
return vel_B, ang_vel_B | python | {
"resource": ""
} |
q34361 | force_in_A_to_force_in_B | train | def force_in_A_to_force_in_B(force_A, torque_A, pose_A_in_B):
"""
Converts linear and rotational force at a point in frame A to the equivalent in frame B.
Args:
force_A: 3-dim iterable for linear force in A
torque_A: 3-dim iterable for rotational force (moment) in A
pose_A_in_B: numpy array of shape (4,4) corresponding to the pose of A in frame B
Returns:
force_B, torque_B: two numpy arrays of shape (3,) for the forces in B
"""
pos_A_in_B = pose_A_in_B[:3, 3]
rot_A_in_B = pose_A_in_B[:3, :3]
skew_symm = _skew_symmetric_translation(pos_A_in_B)
force_B = rot_A_in_B.T.dot(force_A)
torque_B = -rot_A_in_B.T.dot(skew_symm.dot(force_A)) + rot_A_in_B.T.dot(torque_A)
return force_B, torque_B | python | {
"resource": ""
} |
q34362 | rotation_matrix | train | def rotation_matrix(angle, direction, point=None):
"""
Returns matrix to rotate about axis defined by point and direction.
Examples:
>>> angle = (random.random() - 0.5) * (2*math.pi)
>>> direc = numpy.random.random(3) - 0.5
>>> point = numpy.random.random(3) - 0.5
>>> R0 = rotation_matrix(angle, direc, point)
>>> R1 = rotation_matrix(angle-2*math.pi, direc, point)
>>> is_same_transform(R0, R1)
True
>>> R0 = rotation_matrix(angle, direc, point)
>>> R1 = rotation_matrix(-angle, -direc, point)
>>> is_same_transform(R0, R1)
True
>>> I = numpy.identity(4, numpy.float32)
>>> numpy.allclose(I, rotation_matrix(math.pi*2, direc))
True
>>> numpy.allclose(2., numpy.trace(rotation_matrix(math.pi/2,
... direc, point)))
True
"""
sina = math.sin(angle)
cosa = math.cos(angle)
direction = unit_vector(direction[:3])
# rotation matrix around unit vector
R = np.array(
((cosa, 0.0, 0.0), (0.0, cosa, 0.0), (0.0, 0.0, cosa)), dtype=np.float32
)
R += np.outer(direction, direction) * (1.0 - cosa)
direction *= sina
R += np.array(
(
(0.0, -direction[2], direction[1]),
(direction[2], 0.0, -direction[0]),
(-direction[1], direction[0], 0.0),
),
dtype=np.float32,
)
M = np.identity(4)
M[:3, :3] = R
if point is not None:
# rotation not around origin
point = np.array(point[:3], dtype=np.float32, copy=False)
M[:3, 3] = point - np.dot(R, point)
return M | python | {
"resource": ""
} |
q34363 | make_pose | train | def make_pose(translation, rotation):
"""
Makes a homogenous pose matrix from a translation vector and a rotation matrix.
Args:
translation: a 3-dim iterable
rotation: a 3x3 matrix
Returns:
pose: a 4x4 homogenous matrix
"""
pose = np.zeros((4, 4))
pose[:3, :3] = rotation
pose[:3, 3] = translation
pose[3, 3] = 1.0
return pose | python | {
"resource": ""
} |
q34364 | get_pose_error | train | def get_pose_error(target_pose, current_pose):
"""
Computes the error corresponding to target pose - current pose as a 6-dim vector.
The first 3 components correspond to translational error while the last 3 components
correspond to the rotational error.
Args:
target_pose: a 4x4 homogenous matrix for the target pose
current_pose: a 4x4 homogenous matrix for the current pose
Returns:
A 6-dim numpy array for the pose error.
"""
error = np.zeros(6)
# compute translational error
target_pos = target_pose[:3, 3]
current_pos = current_pose[:3, 3]
pos_err = target_pos - current_pos
# compute rotational error
r1 = current_pose[:3, 0]
r2 = current_pose[:3, 1]
r3 = current_pose[:3, 2]
r1d = target_pose[:3, 0]
r2d = target_pose[:3, 1]
r3d = target_pose[:3, 2]
rot_err = 0.5 * (np.cross(r1, r1d) + np.cross(r2, r2d) + np.cross(r3, r3d))
error[:3] = pos_err
error[3:] = rot_err
return error | python | {
"resource": ""
} |
q34365 | make | train | def make(env_name, *args, **kwargs):
"""Try to get the equivalent functionality of gym.make in a sloppy way."""
if env_name not in REGISTERED_ENVS:
raise Exception(
"Environment {} not found. Make sure it is a registered environment among: {}".format(
env_name, ", ".join(REGISTERED_ENVS)
)
)
return REGISTERED_ENVS[env_name](*args, **kwargs) | python | {
"resource": ""
} |
q34366 | MujocoEnv.initialize_time | train | def initialize_time(self, control_freq):
"""
Initializes the time constants used for simulation.
"""
self.cur_time = 0
self.model_timestep = self.sim.model.opt.timestep
if self.model_timestep <= 0:
raise XMLError("xml model defined non-positive time step")
self.control_freq = control_freq
if control_freq <= 0:
raise SimulationError(
"control frequency {} is invalid".format(control_freq)
)
self.control_timestep = 1. / control_freq | python | {
"resource": ""
} |
q34367 | MujocoEnv.reset | train | def reset(self):
"""Resets simulation."""
# TODO(yukez): investigate black screen of death
# if there is an active viewer window, destroy it
self._destroy_viewer()
self._reset_internal()
self.sim.forward()
return self._get_observation() | python | {
"resource": ""
} |
q34368 | MujocoEnv.step | train | def step(self, action):
"""Takes a step in simulation with control command @action."""
if self.done:
raise ValueError("executing action in terminated episode")
self.timestep += 1
self._pre_action(action)
end_time = self.cur_time + self.control_timestep
while self.cur_time < end_time:
self.sim.step()
self.cur_time += self.model_timestep
reward, done, info = self._post_action(action)
return self._get_observation(), reward, done, info | python | {
"resource": ""
} |
q34369 | MujocoEnv._post_action | train | def _post_action(self, action):
"""Do any housekeeping after taking an action."""
reward = self.reward(action)
# done if number of elapsed timesteps is greater than horizon
self.done = (self.timestep >= self.horizon) and not self.ignore_done
return reward, self.done, {} | python | {
"resource": ""
} |
q34370 | MujocoEnv.reset_from_xml_string | train | 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() | python | {
"resource": ""
} |
q34371 | MujocoEnv.find_contacts | train | def find_contacts(self, geoms_1, geoms_2):
"""
Finds contact between two geom groups.
Args:
geoms_1: a list of geom names (string)
geoms_2: another list of geom names (string)
Returns:
iterator of all contacts between @geoms_1 and @geoms_2
"""
for contact in self.sim.data.contact[0 : self.sim.data.ncon]:
# check contact geom in geoms
c1_in_g1 = self.sim.model.geom_id2name(contact.geom1) in geoms_1
c2_in_g2 = self.sim.model.geom_id2name(contact.geom2) in geoms_2
# check contact geom in geoms (flipped)
c2_in_g1 = self.sim.model.geom_id2name(contact.geom2) in geoms_1
c1_in_g2 = self.sim.model.geom_id2name(contact.geom1) in geoms_2
if (c1_in_g1 and c2_in_g2) or (c1_in_g2 and c2_in_g1):
yield contact | python | {
"resource": ""
} |
q34372 | SawyerEnv._reset_internal | train | def _reset_internal(self):
"""
Sets initial pose of arm and grippers.
"""
super()._reset_internal()
self.sim.data.qpos[self._ref_joint_pos_indexes] = self.mujoco_robot.init_qpos
if self.has_gripper:
self.sim.data.qpos[
self._ref_joint_gripper_actuator_indexes
] = self.gripper.init_qpos | python | {
"resource": ""
} |
q34373 | SawyerEnv._get_reference | train | def _get_reference(self):
"""
Sets up necessary reference for robots, grippers, and objects.
"""
super()._get_reference()
# indices for joints in qpos, qvel
self.robot_joints = list(self.mujoco_robot.joints)
self._ref_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.robot_joints
]
self._ref_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.robot_joints
]
if self.use_indicator_object:
ind_qpos = self.sim.model.get_joint_qpos_addr("pos_indicator")
self._ref_indicator_pos_low, self._ref_indicator_pos_high = ind_qpos
ind_qvel = self.sim.model.get_joint_qvel_addr("pos_indicator")
self._ref_indicator_vel_low, self._ref_indicator_vel_high = ind_qvel
self.indicator_id = self.sim.model.body_name2id("pos_indicator")
# indices for grippers in qpos, qvel
if self.has_gripper:
self.gripper_joints = list(self.gripper.joints)
self._ref_gripper_joint_pos_indexes = [
self.sim.model.get_joint_qpos_addr(x) for x in self.gripper_joints
]
self._ref_gripper_joint_vel_indexes = [
self.sim.model.get_joint_qvel_addr(x) for x in self.gripper_joints
]
# indices for joint pos actuation, joint vel actuation, gripper actuation
self._ref_joint_pos_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("pos")
]
self._ref_joint_vel_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("vel")
]
if self.has_gripper:
self._ref_joint_gripper_actuator_indexes = [
self.sim.model.actuator_name2id(actuator)
for actuator in self.sim.model.actuator_names
if actuator.startswith("gripper")
]
# IDs of sites for gripper visualization
self.eef_site_id = self.sim.model.site_name2id("grip_site")
self.eef_cylinder_id = self.sim.model.site_name2id("grip_site_cylinder") | python | {
"resource": ""
} |
q34374 | SawyerEnv._pre_action | train | def _pre_action(self, action):
"""
Overrides the superclass method to actuate the robot with the
passed joint velocities and gripper control.
Args:
action (numpy array): The control to apply to the robot. The first
@self.mujoco_robot.dof dimensions should be the desired
normalized joint velocities and if the robot has
a gripper, the next @self.gripper.dof dimensions should be
actuation controls for the gripper.
"""
# clip actions into valid range
assert len(action) == self.dof, "environment got invalid action dimension"
low, high = self.action_spec
action = np.clip(action, low, high)
if self.has_gripper:
arm_action = action[: self.mujoco_robot.dof]
gripper_action_in = action[
self.mujoco_robot.dof : self.mujoco_robot.dof + self.gripper.dof
]
gripper_action_actual = self.gripper.format_action(gripper_action_in)
action = np.concatenate([arm_action, gripper_action_actual])
# rescale normalized action to control ranges
ctrl_range = self.sim.model.actuator_ctrlrange
bias = 0.5 * (ctrl_range[:, 1] + ctrl_range[:, 0])
weight = 0.5 * (ctrl_range[:, 1] - ctrl_range[:, 0])
applied_action = bias + weight * action
self.sim.data.ctrl[:] = applied_action
# gravity compensation
self.sim.data.qfrc_applied[
self._ref_joint_vel_indexes
] = self.sim.data.qfrc_bias[self._ref_joint_vel_indexes]
if self.use_indicator_object:
self.sim.data.qfrc_applied[
self._ref_indicator_vel_low : self._ref_indicator_vel_high
] = self.sim.data.qfrc_bias[
self._ref_indicator_vel_low : self._ref_indicator_vel_high
] | python | {
"resource": ""
} |
q34375 | collect_random_trajectory | train | def collect_random_trajectory(env, timesteps=1000):
"""Run a random policy to collect trajectories.
The rollout trajectory is saved to files in npz format.
Modify the DataCollectionWrapper wrapper to add new fields or change data formats.
"""
obs = env.reset()
dof = env.dof
for t in range(timesteps):
action = 0.5 * np.random.randn(dof)
obs, reward, done, info = env.step(action)
env.render()
if t % 100 == 0:
print(t) | python | {
"resource": ""
} |
q34376 | playback_trajectory | train | def playback_trajectory(env, ep_dir):
"""Playback data from an episode.
Args:
ep_dir: The path to the directory containing data for an episode.
"""
# first reload the model from the xml
xml_path = os.path.join(ep_dir, "model.xml")
with open(xml_path, "r") as f:
env.reset_from_xml_string(f.read())
state_paths = os.path.join(ep_dir, "state_*.npz")
# read states back, load them one by one, and render
t = 0
for state_file in sorted(glob(state_paths)):
print(state_file)
dic = np.load(state_file)
states = dic["states"]
for state in states:
env.sim.set_state_from_flattened(state)
env.sim.forward()
env.render()
t += 1
if t % 100 == 0:
print(t) | python | {
"resource": ""
} |
q34377 | IKWrapper.set_robot_joint_positions | train | def set_robot_joint_positions(self, positions):
"""
Overrides the function to set the joint positions directly, since we need to notify
the IK controller of the change.
"""
self.env.set_robot_joint_positions(positions)
self.controller.sync_state() | python | {
"resource": ""
} |
q34378 | IKWrapper._make_input | train | def _make_input(self, action, old_quat):
"""
Helper function that returns a dictionary with keys dpos, rotation from a raw input
array. The first three elements are taken to be displacement in position, and a
quaternion indicating the change in rotation with respect to @old_quat.
"""
return {
"dpos": action[:3],
# IK controller takes an absolute orientation in robot base frame
"rotation": T.quat2mat(T.quat_multiply(old_quat, action[3:7])),
} | python | {
"resource": ""
} |
q34379 | RedisPublisher.fetch_message | train | def fetch_message(self, request, facility, audience='any'):
"""
Fetch the first message available for the given ``facility`` and ``audience``, if it has
been persisted in the Redis datastore.
The current HTTP ``request`` is used to determine to whom the message belongs.
A unique string is used to identify the bucket's ``facility``.
Determines the ``audience`` to check for the message. Must be one of ``broadcast``,
``group``, ``user``, ``session`` or ``any``. The default is ``any``, which means to check
for all possible audiences.
"""
prefix = self.get_prefix()
channels = []
if audience in ('session', 'any',):
if request and request.session:
channels.append('{prefix}session:{0}:{facility}'.format(request.session.session_key, prefix=prefix, facility=facility))
if audience in ('user', 'any',):
if is_authenticated(request):
channels.append('{prefix}user:{0}:{facility}'.format(request.user.get_username(), prefix=prefix, facility=facility))
if audience in ('group', 'any',):
try:
if is_authenticated(request):
groups = request.session['ws4redis:memberof']
channels.extend('{prefix}group:{0}:{facility}'.format(g, prefix=prefix, facility=facility)
for g in groups)
except (KeyError, AttributeError):
pass
if audience in ('broadcast', 'any',):
channels.append('{prefix}broadcast:{facility}'.format(prefix=prefix, facility=facility))
for channel in channels:
message = self._connection.get(channel)
if message:
return message | python | {
"resource": ""
} |
q34380 | RedisSubscriber.set_pubsub_channels | train | def set_pubsub_channels(self, request, channels):
"""
Initialize the channels used for publishing and subscribing messages through the message queue.
"""
facility = request.path_info.replace(settings.WEBSOCKET_URL, '', 1)
# initialize publishers
audience = {
'users': 'publish-user' in channels and [SELF] or [],
'groups': 'publish-group' in channels and [SELF] or [],
'sessions': 'publish-session' in channels and [SELF] or [],
'broadcast': 'publish-broadcast' in channels,
}
self._publishers = set()
for key in self._get_message_channels(request=request, facility=facility, **audience):
self._publishers.add(key)
# initialize subscribers
audience = {
'users': 'subscribe-user' in channels and [SELF] or [],
'groups': 'subscribe-group' in channels and [SELF] or [],
'sessions': 'subscribe-session' in channels and [SELF] or [],
'broadcast': 'subscribe-broadcast' in channels,
}
self._subscription = self._connection.pubsub()
for key in self._get_message_channels(request=request, facility=facility, **audience):
self._subscription.subscribe(key) | python | {
"resource": ""
} |
q34381 | RedisSubscriber.send_persisted_messages | train | def send_persisted_messages(self, websocket):
"""
This method is called immediately after a websocket is openend by the client, so that
persisted messages can be sent back to the client upon connection.
"""
for channel in self._subscription.channels:
message = self._connection.get(channel)
if message:
websocket.send(message) | python | {
"resource": ""
} |
q34382 | RedisSubscriber.get_file_descriptor | train | def get_file_descriptor(self):
"""
Returns the file descriptor used for passing to the select call when listening
on the message queue.
"""
return self._subscription.connection and self._subscription.connection._sock.fileno() | python | {
"resource": ""
} |
q34383 | RedisSubscriber.release | train | def release(self):
"""
New implementation to free up Redis subscriptions when websockets close. This prevents
memory sap when Redis Output Buffer and Output Lists build when websockets are abandoned.
"""
if self._subscription and self._subscription.subscribed:
self._subscription.unsubscribe()
self._subscription.reset() | python | {
"resource": ""
} |
q34384 | default | train | def default(request):
"""
Adds additional context variables to the default context.
"""
protocol = request.is_secure() and 'wss://' or 'ws://'
heartbeat_msg = settings.WS4REDIS_HEARTBEAT and '"{0}"'.format(settings.WS4REDIS_HEARTBEAT) or 'null'
context = {
'WEBSOCKET_URI': protocol + request.get_host() + settings.WEBSOCKET_URL,
'WS4REDIS_HEARTBEAT': mark_safe(heartbeat_msg),
}
return context | python | {
"resource": ""
} |
q34385 | WebSocket._decode_bytes | train | def _decode_bytes(self, bytestring):
"""
Internal method used to convert the utf-8 encoded bytestring into unicode.
If the conversion fails, the socket will be closed.
"""
if not bytestring:
return u''
try:
return bytestring.decode('utf-8')
except UnicodeDecodeError:
self.close(1007)
raise | python | {
"resource": ""
} |
q34386 | WebSocket.handle_close | train | def handle_close(self, header, payload):
"""
Called when a close frame has been decoded from the stream.
:param header: The decoded `Header`.
:param payload: The bytestring payload associated with the close frame.
"""
if not payload:
self.close(1000, None)
return
if len(payload) < 2:
raise WebSocketError('Invalid close frame: {0} {1}'.format(header, payload))
rv = payload[:2]
if six.PY2:
code = struct.unpack('!H', str(rv))[0]
else:
code = struct.unpack('!H', bytes(rv))[0]
payload = payload[2:]
if payload:
validator = Utf8Validator()
val = validator.validate(payload)
if not val[0]:
raise UnicodeError
if not self._is_valid_close_code(code):
raise WebSocketError('Invalid close code {0}'.format(code))
self.close(code, payload) | python | {
"resource": ""
} |
q34387 | WebSocket.read_frame | train | def read_frame(self):
"""
Block until a full frame has been read from the socket.
This is an internal method as calling this will not cleanup correctly
if an exception is called. Use `receive` instead.
:return: The header and payload as a tuple.
"""
header = Header.decode_header(self.stream)
if header.flags:
raise WebSocketError
if not header.length:
return header, ''
try:
payload = self.stream.read(header.length)
except socket_error:
payload = ''
except Exception:
logger.debug("{}: {}".format(type(e), six.text_type(e)))
payload = ''
if len(payload) != header.length:
raise WebSocketError('Unexpected EOF reading frame payload')
if header.mask:
payload = header.unmask_payload(payload)
return header, payload | python | {
"resource": ""
} |
q34388 | WebSocket.read_message | train | def read_message(self):
"""
Return the next text or binary message from the socket.
This is an internal method as calling this will not cleanup correctly
if an exception is called. Use `receive` instead.
"""
opcode = None
message = None
while True:
header, payload = self.read_frame()
f_opcode = header.opcode
if f_opcode in (self.OPCODE_TEXT, self.OPCODE_BINARY):
# a new frame
if opcode:
raise WebSocketError("The opcode in non-fin frame is expected to be zero, got {0!r}".format(f_opcode))
# Start reading a new message, reset the validator
self.utf8validator.reset()
self.utf8validate_last = (True, True, 0, 0)
opcode = f_opcode
elif f_opcode == self.OPCODE_CONTINUATION:
if not opcode:
raise WebSocketError("Unexpected frame with opcode=0")
elif f_opcode == self.OPCODE_PING:
self.handle_ping(header, payload)
continue
elif f_opcode == self.OPCODE_PONG:
self.handle_pong(header, payload)
continue
elif f_opcode == self.OPCODE_CLOSE:
self.handle_close(header, payload)
return
else:
raise WebSocketError("Unexpected opcode={0!r}".format(f_opcode))
if opcode == self.OPCODE_TEXT:
self.validate_utf8(payload)
if six.PY3:
payload = payload.decode()
if message is None:
message = six.text_type() if opcode == self.OPCODE_TEXT else six.binary_type()
message += payload
if header.fin:
break
if opcode == self.OPCODE_TEXT:
if six.PY2:
self.validate_utf8(message)
else:
self.validate_utf8(message.encode())
return message
else:
return bytearray(message) | python | {
"resource": ""
} |
q34389 | WebSocket.close | train | def close(self, code=1000, message=''):
"""
Close the websocket and connection, sending the specified code and
message. The underlying socket object is _not_ closed, that is the
responsibility of the initiator.
"""
try:
message = self._encode_bytes(message)
self.send_frame(
struct.pack('!H%ds' % len(message), code, message),
opcode=self.OPCODE_CLOSE)
except WebSocketError:
# Failed to write the closing frame but it's ok because we're
# closing the socket anyway.
logger.debug("Failed to write closing frame -> closing socket")
finally:
logger.debug("Closed WebSocket")
self._closed = True
self.stream = None | python | {
"resource": ""
} |
q34390 | Header.decode_header | train | def decode_header(cls, stream):
"""
Decode a WebSocket header.
:param stream: A file like object that can be 'read' from.
:returns: A `Header` instance.
"""
read = stream.read
data = read(2)
if len(data) != 2:
raise WebSocketError("Unexpected EOF while decoding header")
first_byte, second_byte = struct.unpack('!BB', data)
header = cls(
fin=first_byte & cls.FIN_MASK == cls.FIN_MASK,
opcode=first_byte & cls.OPCODE_MASK,
flags=first_byte & cls.HEADER_FLAG_MASK,
length=second_byte & cls.LENGTH_MASK)
has_mask = second_byte & cls.MASK_MASK == cls.MASK_MASK
if header.opcode > 0x07:
if not header.fin:
raise WebSocketError('Received fragmented control frame: {0!r}'.format(data))
# Control frames MUST have a payload length of 125 bytes or less
if header.length > 125:
raise FrameTooLargeException('Control frame cannot be larger than 125 bytes: {0!r}'.format(data))
if header.length == 126:
# 16 bit length
data = read(2)
if len(data) != 2:
raise WebSocketError('Unexpected EOF while decoding header')
header.length = struct.unpack('!H', data)[0]
elif header.length == 127:
# 64 bit length
data = read(8)
if len(data) != 8:
raise WebSocketError('Unexpected EOF while decoding header')
header.length = struct.unpack('!Q', data)[0]
if has_mask:
mask = read(4)
if len(mask) != 4:
raise WebSocketError('Unexpected EOF while decoding header')
header.mask = mask
return header | python | {
"resource": ""
} |
q34391 | Header.encode_header | train | def encode_header(cls, fin, opcode, mask, length, flags):
"""
Encodes a WebSocket header.
:param fin: Whether this is the final frame for this opcode.
:param opcode: The opcode of the payload, see `OPCODE_*`
:param mask: Whether the payload is masked.
:param length: The length of the frame.
:param flags: The RSV* flags.
:return: A bytestring encoded header.
"""
first_byte = opcode
second_byte = 0
if six.PY2:
extra = ''
else:
extra = b''
if fin:
first_byte |= cls.FIN_MASK
if flags & cls.RSV0_MASK:
first_byte |= cls.RSV0_MASK
if flags & cls.RSV1_MASK:
first_byte |= cls.RSV1_MASK
if flags & cls.RSV2_MASK:
first_byte |= cls.RSV2_MASK
# now deal with length complexities
if length < 126:
second_byte += length
elif length <= 0xffff:
second_byte += 126
extra = struct.pack('!H', length)
elif length <= 0xffffffffffffffff:
second_byte += 127
extra = struct.pack('!Q', length)
else:
raise FrameTooLargeException
if mask:
second_byte |= cls.MASK_MASK
extra += mask
if six.PY3:
return bytes([first_byte, second_byte]) + extra
return chr(first_byte) + chr(second_byte) + extra | python | {
"resource": ""
} |
q34392 | store_groups_in_session | train | def store_groups_in_session(sender, user, request, **kwargs):
"""
When a user logs in, fetch its groups and store them in the users session.
This is required by ws4redis, since fetching groups accesses the database, which is a blocking
operation and thus not allowed from within the websocket loop.
"""
if hasattr(user, 'groups'):
request.session['ws4redis:memberof'] = [g.name for g in user.groups.all()] | python | {
"resource": ""
} |
q34393 | RedisStore.publish_message | train | def publish_message(self, message, expire=None):
"""
Publish a ``message`` on the subscribed channel on the Redis datastore.
``expire`` sets the time in seconds, on how long the message shall additionally of being
published, also be persisted in the Redis datastore. If unset, it defaults to the
configuration settings ``WS4REDIS_EXPIRE``.
"""
if expire is None:
expire = self._expire
if not isinstance(message, RedisMessage):
raise ValueError('message object is not of type RedisMessage')
for channel in self._publishers:
self._connection.publish(channel, message)
if expire > 0:
self._connection.setex(channel, expire, message) | python | {
"resource": ""
} |
q34394 | uWSGIWebsocket.get_file_descriptor | train | def get_file_descriptor(self):
"""Return the file descriptor for the given websocket"""
try:
return uwsgi.connection_fd()
except IOError as e:
self.close()
raise WebSocketError(e) | python | {
"resource": ""
} |
q34395 | StereoPair.get_frames_singleimage | train | def get_frames_singleimage(self):
"""
Get current left and right frames from a single image,
by splitting the image in half.
"""
frame = self.captures[0].read()[1]
height, width, colors = frame.shape
left_frame = frame[:, :width/2, :]
right_frame = frame[:, width/2:, :]
return [left_frame, right_frame] | python | {
"resource": ""
} |
q34396 | StereoPair.show_frames | train | def show_frames(self, wait=0):
"""
Show current frames from cameras.
``wait`` is the wait interval in milliseconds before the window closes.
"""
for window, frame in zip(self.windows, self.get_frames()):
cv2.imshow(window, frame)
cv2.waitKey(wait) | python | {
"resource": ""
} |
q34397 | ChessboardFinder.get_chessboard | train | def get_chessboard(self, columns, rows, show=False):
"""
Take a picture with a chessboard visible in both captures.
``columns`` and ``rows`` should be the number of inside corners in the
chessboard's columns and rows. ``show`` determines whether the frames
are shown while the cameras search for a chessboard.
"""
found_chessboard = [False, False]
while not all(found_chessboard):
frames = self.get_frames()
if show:
self.show_frames(1)
for i, frame in enumerate(frames):
(found_chessboard[i],
corners) = cv2.findChessboardCorners(frame, (columns, rows),
flags=cv2.CALIB_CB_FAST_CHECK)
return frames | python | {
"resource": ""
} |
q34398 | CalibratedPair.get_frames | train | def get_frames(self):
"""Rectify and return current frames from cameras."""
frames = super(CalibratedPair, self).get_frames()
return self.calibration.rectify(frames) | python | {
"resource": ""
} |
q34399 | CalibratedPair.get_point_cloud | train | def get_point_cloud(self, pair):
"""Get 3D point cloud from image pair."""
disparity = self.block_matcher.get_disparity(pair)
points = self.block_matcher.get_3d(disparity,
self.calibration.disp_to_depth_mat)
colors = cv2.cvtColor(pair[0], cv2.COLOR_BGR2RGB)
return PointCloud(points, colors) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.