text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _post_action(self, action):
"""Optionally performs gripper visualization after the actions.""" |
ret = super()._post_action(action)
self._gripper_visualization()
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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("") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)
),
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rotation_matrix(angle, direction, point=None):
""" Returns matrix to rotate about axis defined by point and direction. Examples: True True True 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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, {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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])),
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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()] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_frames(self):
"""Rectify and return current frames from cameras.""" |
frames = super(CalibratedPair, self).get_frames()
return self.calibration.rectify(frames) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_settings(self, settings):
"""Load settings from file""" |
with open(settings) as settings_file:
settings_dict = simplejson.load(settings_file)
for key, value in settings_dict.items():
self.__setattr__(key, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_settings(self, settings_file):
"""Save block matcher settings to a file object""" |
settings = {}
for parameter in self.parameter_maxima:
settings[parameter] = self.__getattribute__(parameter)
with open(settings_file, "w") as settings_file:
simplejson.dump(settings, settings_file) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_range(self, value):
"""Set private ``_search_range`` and reset ``_block_matcher``.""" |
if value == 0 or not value % 16:
self._search_range = value
else:
raise InvalidSearchRangeError("Search range must be a multiple of "
"16.")
self._replace_bm() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def window_size(self, value):
"""Set private ``_window_size`` and reset ``_block_matcher``.""" |
if (value > 4 and
value < self.parameter_maxima["window_size"] and
value % 2):
self._window_size = value
else:
raise InvalidWindowSizeError("Window size must be an odd number "
"between 0 and {}.".format(
self.parameter_maxima["window_size"] + 1))
self._replace_bm() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stereo_bm_preset(self, value):
"""Set private ``_stereo_bm_preset`` and reset ``_block_matcher``.""" |
if value in (cv2.STEREO_BM_BASIC_PRESET,
cv2.STEREO_BM_FISH_EYE_PRESET,
cv2.STEREO_BM_NARROW_PRESET):
self._bm_preset = value
else:
raise InvalidBMPresetError("Stereo BM preset must be defined as "
"cv2.STEREO_BM_*_PRESET.")
self._replace_bm() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def numDisparities(self, value):
"""Set private ``_num_disp`` and reset ``_block_matcher``.""" |
if value > 0 and value % 16 == 0:
self._num_disp = value
else:
raise InvalidNumDisparitiesError("numDisparities must be a "
"positive integer evenly "
"divisible by 16.")
self._replace_bm() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SADWindowSize(self, value):
"""Set private ``_sad_window_size`` and reset ``_block_matcher``.""" |
if value >= 1 and value <= 11 and value % 2:
self._sad_window_size = value
else:
raise InvalidSADWindowSizeError("SADWindowSize must be odd and "
"between 1 and 11.")
self._replace_bm() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uniquenessRatio(self, value):
"""Set private ``_uniqueness`` and reset ``_block_matcher``.""" |
if value >= 5 and value <= 15:
self._uniqueness = value
else:
raise InvalidUniquenessRatioError("Uniqueness ratio must be "
"between 5 and 15.")
self._replace_bm() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def speckleWindowSize(self, value):
"""Set private ``_speckle_window_size`` and reset ``_block_matcher``.""" |
if value >= 0 and value <= 200:
self._speckle_window_size = value
else:
raise InvalidSpeckleWindowSizeError("Speckle window size must be 0 "
"for disabled checks or "
"between 50 and 200.")
self._replace_bm() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def speckleRange(self, value):
"""Set private ``_speckle_range`` and reset ``_block_matcher``.""" |
if value >= 0:
self._speckle_range = value
else:
raise InvalidSpeckleRangeError("Speckle range cannot be negative.")
self._replace_bm() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def P1(self, value):
"""Set private ``_P1`` and reset ``_block_matcher``.""" |
if value < self.P2:
self._P1 = value
else:
raise InvalidFirstDisparityChangePenaltyError("P1 must be less "
"than P2.")
self._replace_bm() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.