hexsha
stringlengths
40
40
repo
stringlengths
7
114
path
stringlengths
4
124
license
listlengths
1
9
language
stringclasses
1 value
identifier
stringlengths
1
71
return_type
stringlengths
1
749
original_string
stringlengths
76
22.7k
original_docstring
stringlengths
16
7.61k
docstring
stringlengths
16
2.47k
docstring_tokens
listlengths
6
477
code
stringlengths
14
10.2k
code_tokens
listlengths
6
996
short_docstring
stringlengths
2
644
short_docstring_tokens
listlengths
1
116
comment
listlengths
1
89
parameters
listlengths
0
64
docstring_params
dict
6c74ee643589a48ea028e071c8ab35c1aa0e063a
gautams3/deformable-ravens
ravens/gripper.py
[ "Apache-2.0" ]
Python
release
null
def release(self): """ If suction off, detect contact between gripper and objects. If suction on, detect contact between picked object and other objects. """ if self.activated: self.activated = False # Release gripped rigid object (if any). if...
If suction off, detect contact between gripper and objects. If suction on, detect contact between picked object and other objects.
If suction off, detect contact between gripper and objects. If suction on, detect contact between picked object and other objects.
[ "If", "suction", "off", "detect", "contact", "between", "gripper", "and", "objects", ".", "If", "suction", "on", "detect", "contact", "between", "picked", "object", "and", "other", "objects", "." ]
def release(self): if self.activated: self.activated = False if self.contact_constraint is not None: try: p.removeConstraint(self.contact_constraint) self.contact_constraint = None except: pass ...
[ "def", "release", "(", "self", ")", ":", "if", "self", ".", "activated", ":", "self", ".", "activated", "=", "False", "if", "self", ".", "contact_constraint", "is", "not", "None", ":", "try", ":", "p", ".", "removeConstraint", "(", "self", ".", "contac...
If suction off, detect contact between gripper and objects.
[ "If", "suction", "off", "detect", "contact", "between", "gripper", "and", "objects", "." ]
[ "\"\"\"\n If suction off, detect contact between gripper and objects.\n If suction on, detect contact between picked object and other objects.\n \"\"\"", "# Release gripped rigid object (if any).", "# Release gripped deformable object (if any)." ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
6c74ee643589a48ea028e071c8ab35c1aa0e063a
gautams3/deformable-ravens
ravens/gripper.py
[ "Apache-2.0" ]
Python
detect_contact
<not_specific>
def detect_contact(self, def_IDs): """ If suction off, detect contact between gripper and objects. If suction on, detect contact between picked object and other objects. :def_IDs: a list of IDs of deformable objects. Since it may be computationally heavy to check, if we have any...
If suction off, detect contact between gripper and objects. If suction on, detect contact between picked object and other objects. :def_IDs: a list of IDs of deformable objects. Since it may be computationally heavy to check, if we have any contact points with rigid we just ret...
If suction off, detect contact between gripper and objects. If suction on, detect contact between picked object and other objects.
[ "If", "suction", "off", "detect", "contact", "between", "gripper", "and", "objects", ".", "If", "suction", "on", "detect", "contact", "between", "picked", "object", "and", "other", "objects", "." ]
def detect_contact(self, def_IDs): body, link = self.body, 0 if self.activated and self.contact_constraint is not None: try: info = p.getConstraintInfo(self.contact_constraint) body, link = info[2], info[3] except: self.contact_cons...
[ "def", "detect_contact", "(", "self", ",", "def_IDs", ")", ":", "body", ",", "link", "=", "self", ".", "body", ",", "0", "if", "self", ".", "activated", "and", "self", ".", "contact_constraint", "is", "not", "None", ":", "try", ":", "info", "=", "p",...
If suction off, detect contact between gripper and objects.
[ "If", "suction", "off", "detect", "contact", "between", "gripper", "and", "objects", "." ]
[ "\"\"\"\n If suction off, detect contact between gripper and objects.\n If suction on, detect contact between picked object and other objects.\n\n :def_IDs: a list of IDs of deformable objects. Since it may be\n computationally heavy to check, if we have any contact points with\n ...
[ { "param": "self", "type": null }, { "param": "def_IDs", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "def_IDs", "type": null, "docstring": null, "docstring_tokens"...
6c74ee643589a48ea028e071c8ab35c1aa0e063a
gautams3/deformable-ravens
ravens/gripper.py
[ "Apache-2.0" ]
Python
detect_contact_def
<not_specific>
def detect_contact_def(self, gripper_position, defId): """Detect contact, when dealing with deformables. We may want to speed this up if it is a bottleneck. Returns a binary signal of whether there exists _any_ vertex within the threshold. Note with collisionMargin=0.004, I am getting m...
Detect contact, when dealing with deformables. We may want to speed this up if it is a bottleneck. Returns a binary signal of whether there exists _any_ vertex within the threshold. Note with collisionMargin=0.004, I am getting most cloth vertices (for ClothFlat) to settle at ~0.004m hi...
Detect contact, when dealing with deformables. We may want to speed this up if it is a bottleneck. Returns a binary signal of whether there exists _any_ vertex within the threshold. Note with collisionMargin=0.004, I am getting most cloth vertices (for ClothFlat) to settle at ~0.004m high.
[ "Detect", "contact", "when", "dealing", "with", "deformables", ".", "We", "may", "want", "to", "speed", "this", "up", "if", "it", "is", "a", "bottleneck", ".", "Returns", "a", "binary", "signal", "of", "whether", "there", "exists", "_any_", "vertex", "with...
def detect_contact_def(self, gripper_position, defId): _, vert_pos_l = p.getMeshData(defId, -1, flags=p.MESH_DATA_SIMULATION_MESH) distances_np = gripper_position - np.array(vert_pos_l) assert len(distances_np.shape) == 2, distances_np.shape distances_L2 = np.linalg.norm(distances_np, ax...
[ "def", "detect_contact_def", "(", "self", ",", "gripper_position", ",", "defId", ")", ":", "_", ",", "vert_pos_l", "=", "p", ".", "getMeshData", "(", "defId", ",", "-", "1", ",", "flags", "=", "p", ".", "MESH_DATA_SIMULATION_MESH", ")", "distances_np", "="...
Detect contact, when dealing with deformables.
[ "Detect", "contact", "when", "dealing", "with", "deformables", "." ]
[ "\"\"\"Detect contact, when dealing with deformables.\n\n We may want to speed this up if it is a bottleneck. Returns a binary\n signal of whether there exists _any_ vertex within the threshold.\n Note with collisionMargin=0.004, I am getting most cloth vertices\n (for ClothFlat) to sett...
[ { "param": "self", "type": null }, { "param": "gripper_position", "type": null }, { "param": "defId", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "gripper_position", "type": null, "docstring": null, "docstrin...
6c74ee643589a48ea028e071c8ab35c1aa0e063a
gautams3/deformable-ravens
ravens/gripper.py
[ "Apache-2.0" ]
Python
check_grasp
<not_specific>
def check_grasp(self): """Check a grasp for picking success. If picking fails, then robot doesn't do the place action. For rigid items: index 2 in getConstraintInfo returns childBodyUniqueId. For deformables, check the length of the anchors. """ pick_deformable = False ...
Check a grasp for picking success. If picking fails, then robot doesn't do the place action. For rigid items: index 2 in getConstraintInfo returns childBodyUniqueId. For deformables, check the length of the anchors.
Check a grasp for picking success. If picking fails, then robot doesn't do the place action. For rigid items: index 2 in getConstraintInfo returns childBodyUniqueId. For deformables, check the length of the anchors.
[ "Check", "a", "grasp", "for", "picking", "success", ".", "If", "picking", "fails", "then", "robot", "doesn", "'", "t", "do", "the", "place", "action", ".", "For", "rigid", "items", ":", "index", "2", "in", "getConstraintInfo", "returns", "childBodyUniqueId",...
def check_grasp(self): pick_deformable = False if self.def_grip_anchors is not None: pick_deformable = len(self.def_grip_anchors) > 0 return (not self.contact_constraint is None) or pick_deformable
[ "def", "check_grasp", "(", "self", ")", ":", "pick_deformable", "=", "False", "if", "self", ".", "def_grip_anchors", "is", "not", "None", ":", "pick_deformable", "=", "len", "(", "self", ".", "def_grip_anchors", ")", ">", "0", "return", "(", "not", "self",...
Check a grasp for picking success.
[ "Check", "a", "grasp", "for", "picking", "success", "." ]
[ "\"\"\"Check a grasp for picking success.\n\n If picking fails, then robot doesn't do the place action. For rigid\n items: index 2 in getConstraintInfo returns childBodyUniqueId. For\n deformables, check the length of the anchors.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
1a5169920c0452072c78502e23d3486d19b0c06a
gautams3/deformable-ravens
load.py
[ "Apache-2.0" ]
Python
load
<not_specific>
def load(path, iepisode, field): """Adapted from `dataset.py` so we can sample goal images. Just including some logic to extract the episode automatically based on the index `iepisode`, so we don't need to know the length in advance. """ field_path = os.path.join(path, field) data_list = [os.pat...
Adapted from `dataset.py` so we can sample goal images. Just including some logic to extract the episode automatically based on the index `iepisode`, so we don't need to know the length in advance.
Adapted from `dataset.py` so we can sample goal images. Just including some logic to extract the episode automatically based on the index `iepisode`, so we don't need to know the length in advance.
[ "Adapted", "from", "`", "dataset", ".", "py", "`", "so", "we", "can", "sample", "goal", "images", ".", "Just", "including", "some", "logic", "to", "extract", "the", "episode", "automatically", "based", "on", "the", "index", "`", "iepisode", "`", "so", "w...
def load(path, iepisode, field): field_path = os.path.join(path, field) data_list = [os.path.join(field_path, x) for x in os.listdir(field_path)] fname = [x for x in data_list if f'{iepisode:06d}' in x] assert len(fname) == 1, fname fname = fname[0] return pickle.load(open(fname, 'rb'))
[ "def", "load", "(", "path", ",", "iepisode", ",", "field", ")", ":", "field_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "field", ")", "data_list", "=", "[", "os", ".", "path", ".", "join", "(", "field_path", ",", "x", ")", "for"...
Adapted from `dataset.py` so we can sample goal images.
[ "Adapted", "from", "`", "dataset", ".", "py", "`", "so", "we", "can", "sample", "goal", "images", "." ]
[ "\"\"\"Adapted from `dataset.py` so we can sample goal images. Just including\n some logic to extract the episode automatically based on the index\n `iepisode`, so we don't need to know the length in advance.\n \"\"\"" ]
[ { "param": "path", "type": null }, { "param": "iepisode", "type": null }, { "param": "field", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "iepisode", "type": null, "docstring": null, "docstring_tokens...
1a5169920c0452072c78502e23d3486d19b0c06a
gautams3/deformable-ravens
load.py
[ "Apache-2.0" ]
Python
debug_time_step
null
def debug_time_step(t, epidx, obs, act, extras, goal=None): """Save images and other stuff from time `t` in episode `epidx`.""" pth = 'tmp' tt = str(t).zfill(2) # Convert from BGR to RGB to match what we see in the GUI. def save(fname, c_img): cv2.imwrite(fname, img=cv2.cvtColor(c_img, cv2....
Save images and other stuff from time `t` in episode `epidx`.
Save images and other stuff from time `t` in episode `epidx`.
[ "Save", "images", "and", "other", "stuff", "from", "time", "`", "t", "`", "in", "episode", "`", "epidx", "`", "." ]
def debug_time_step(t, epidx, obs, act, extras, goal=None): pth = 'tmp' tt = str(t).zfill(2) def save(fname, c_img): cv2.imwrite(fname, img=cv2.cvtColor(c_img, cv2.COLOR_BGR2RGB)) for img_idx, c_img in enumerate(obs['color']): fname = join(pth, f'ep_{epidx}_t{tt}_cimg_{img_idx}.png') ...
[ "def", "debug_time_step", "(", "t", ",", "epidx", ",", "obs", ",", "act", ",", "extras", ",", "goal", "=", "None", ")", ":", "pth", "=", "'tmp'", "tt", "=", "str", "(", "t", ")", ".", "zfill", "(", "2", ")", "def", "save", "(", "fname", ",", ...
Save images and other stuff from time `t` in episode `epidx`.
[ "Save", "images", "and", "other", "stuff", "from", "time", "`", "t", "`", "in", "episode", "`", "epidx", "`", "." ]
[ "\"\"\"Save images and other stuff from time `t` in episode `epidx`.\"\"\"", "# Convert from BGR to RGB to match what we see in the GUI.", "# Save current color images from camera angles and the fused version.", "# (If applicable) save the goal color images.", "# Print the action.", "# Attention. (Well, a...
[ { "param": "t", "type": null }, { "param": "epidx", "type": null }, { "param": "obs", "type": null }, { "param": "act", "type": null }, { "param": "extras", "type": null }, { "param": "goal", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "t", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "epidx", "type": null, "docstring": null, "docstring_tokens": [],...
1a5169920c0452072c78502e23d3486d19b0c06a
gautams3/deformable-ravens
load.py
[ "Apache-2.0" ]
Python
rollout
<not_specific>
def rollout(agent, env, task, goal_conditioned, args, num_finished, debug=False): """Standard gym environment rollout. Adding more debugging options (enable with debug=True), such as printing the pose and saving the images and heatmaps. We can also run `dataset.py` and see goal images in the `goals_out...
Standard gym environment rollout. Adding more debugging options (enable with debug=True), such as printing the pose and saving the images and heatmaps. We can also run `dataset.py` and see goal images in the `goals_out` directory. :goal_conditioned: a boolean to check if we have goal-conditioning. ...
Standard gym environment rollout. Adding more debugging options (enable with debug=True), such as printing the pose and saving the images and heatmaps. We can also run `dataset.py` and see goal images in the `goals_out` directory.
[ "Standard", "gym", "environment", "rollout", ".", "Adding", "more", "debugging", "options", "(", "enable", "with", "debug", "=", "True", ")", "such", "as", "printing", "the", "pose", "and", "saving", "the", "images", "and", "heatmaps", ".", "We", "can", "a...
def rollout(agent, env, task, goal_conditioned, args, num_finished, debug=False): if debug: if not os.path.exists('tmp/'): os.makedirs('tmp/') print('') start_t = 0 if args.agent in ['gt_state', 'gt_state_2_step']: start_t = 1 episode = [] total_reward = 0 if ...
[ "def", "rollout", "(", "agent", ",", "env", ",", "task", ",", "goal_conditioned", ",", "args", ",", "num_finished", ",", "debug", "=", "False", ")", ":", "if", "debug", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "'tmp/'", ")", ":", "o...
Standard gym environment rollout.
[ "Standard", "gym", "environment", "rollout", "." ]
[ "\"\"\"Standard gym environment rollout.\n\n Adding more debugging options (enable with debug=True), such as printing\n the pose and saving the images and heatmaps. We can also run `dataset.py`\n and see goal images in the `goals_out` directory.\n\n :goal_conditioned: a boolean to check if we have goal-...
[ { "param": "agent", "type": null }, { "param": "env", "type": null }, { "param": "task", "type": null }, { "param": "goal_conditioned", "type": null }, { "param": "args", "type": null }, { "param": "num_finished", "type": null }, { "param":...
{ "returns": [], "raises": [], "params": [ { "identifier": "agent", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": [...
1a5169920c0452072c78502e23d3486d19b0c06a
gautams3/deformable-ravens
load.py
[ "Apache-2.0" ]
Python
ignore_this_demo
<not_specific>
def ignore_this_demo(args, reward, t, last_extras): """In some cases, we should filter out demonstrations. Filter for if t == 0, which means the initial state was a success, and also if we have exit_gracefully, which means for the bag-items tasks, it may not have had visible item(s) at the start, for s...
In some cases, we should filter out demonstrations. Filter for if t == 0, which means the initial state was a success, and also if we have exit_gracefully, which means for the bag-items tasks, it may not have had visible item(s) at the start, for some reason.
In some cases, we should filter out demonstrations. Filter for if t == 0, which means the initial state was a success, and also if we have exit_gracefully, which means for the bag-items tasks, it may not have had visible item(s) at the start, for some reason.
[ "In", "some", "cases", "we", "should", "filter", "out", "demonstrations", ".", "Filter", "for", "if", "t", "==", "0", "which", "means", "the", "initial", "state", "was", "a", "success", "and", "also", "if", "we", "have", "exit_gracefully", "which", "means"...
def ignore_this_demo(args, reward, t, last_extras): ignore = (t == 0) if 'exit_gracefully' in last_extras: assert last_extras['exit_gracefully'] return True return ignore
[ "def", "ignore_this_demo", "(", "args", ",", "reward", ",", "t", ",", "last_extras", ")", ":", "ignore", "=", "(", "t", "==", "0", ")", "if", "'exit_gracefully'", "in", "last_extras", ":", "assert", "last_extras", "[", "'exit_gracefully'", "]", "return", "...
In some cases, we should filter out demonstrations.
[ "In", "some", "cases", "we", "should", "filter", "out", "demonstrations", "." ]
[ "\"\"\"In some cases, we should filter out demonstrations.\n\n Filter for if t == 0, which means the initial state was a success, and\n also if we have exit_gracefully, which means for the bag-items tasks, it\n may not have had visible item(s) at the start, for some reason.\n \"\"\"" ]
[ { "param": "args", "type": null }, { "param": "reward", "type": null }, { "param": "t", "type": null }, { "param": "last_extras", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "args", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "reward", "type": null, "docstring": null, "docstring_tokens":...
7f8815b3761deea061ba8bffc2da724c866803d5
gautams3/deformable-ravens
ravens/environment.py
[ "Apache-2.0" ]
Python
step_simulation
null
def step_simulation(self): """Adding optional hertz parameter for better cloth physics. From our discussion with Erwin, we should just set time.sleep(0.001), or even consider removing it all together. It's mainly for us to visualize PyBullet with the GUI to make it not move too fast ...
Adding optional hertz parameter for better cloth physics. From our discussion with Erwin, we should just set time.sleep(0.001), or even consider removing it all together. It's mainly for us to visualize PyBullet with the GUI to make it not move too fast
Adding optional hertz parameter for better cloth physics. From our discussion with Erwin, we should just set time.sleep(0.001), or even consider removing it all together. It's mainly for us to visualize PyBullet with the GUI to make it not move too fast
[ "Adding", "optional", "hertz", "parameter", "for", "better", "cloth", "physics", ".", "From", "our", "discussion", "with", "Erwin", "we", "should", "just", "set", "time", ".", "sleep", "(", "0", ".", "001", ")", "or", "even", "consider", "removing", "it", ...
def step_simulation(self): p.setTimeStep(1.0 / self.hz) while True: if self.running: p.stepSimulation() if self.ee is not None: self.ee.step() time.sleep(0.001)
[ "def", "step_simulation", "(", "self", ")", ":", "p", ".", "setTimeStep", "(", "1.0", "/", "self", ".", "hz", ")", "while", "True", ":", "if", "self", ".", "running", ":", "p", ".", "stepSimulation", "(", ")", "if", "self", ".", "ee", "is", "not", ...
Adding optional hertz parameter for better cloth physics.
[ "Adding", "optional", "hertz", "parameter", "for", "better", "cloth", "physics", "." ]
[ "\"\"\"Adding optional hertz parameter for better cloth physics.\n\n From our discussion with Erwin, we should just set time.sleep(0.001),\n or even consider removing it all together. It's mainly for us to\n visualize PyBullet with the GUI to make it not move too fast\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7f8815b3761deea061ba8bffc2da724c866803d5
gautams3/deformable-ravens
ravens/environment.py
[ "Apache-2.0" ]
Python
is_static
<not_specific>
def is_static(self): """Checks if env is static, used for checking if action finished. However, this won't work in PyBullet (at least v2.8.4) since soft bodies cause this code to hang. Therefore, look at the task's `def_IDs` list, which by design will have all IDs of soft bodies. ...
Checks if env is static, used for checking if action finished. However, this won't work in PyBullet (at least v2.8.4) since soft bodies cause this code to hang. Therefore, look at the task's `def_IDs` list, which by design will have all IDs of soft bodies. Furthermore, for the bag tasks...
Checks if env is static, used for checking if action finished. However, this won't work in PyBullet (at least v2.8.4) since soft bodies cause this code to hang. Therefore, look at the task's `def_IDs` list, which by design will have all IDs of soft bodies. Furthermore, for the bag tasks, the beads generally move around...
[ "Checks", "if", "env", "is", "static", "used", "for", "checking", "if", "action", "finished", ".", "However", "this", "won", "'", "t", "work", "in", "PyBullet", "(", "at", "least", "v2", ".", "8", ".", "4", ")", "since", "soft", "bodies", "cause", "t...
def is_static(self): if self.is_softbody_env(): assert len(self.task.def_IDs) > 0, 'Did we forget to add to def_IDs?' v = [np.linalg.norm(p.getBaseVelocity(i)[0]) for i in self.objects if i not in self.task.def_IDs] else: v = [np.linalg.norm(p.getB...
[ "def", "is_static", "(", "self", ")", ":", "if", "self", ".", "is_softbody_env", "(", ")", ":", "assert", "len", "(", "self", ".", "task", ".", "def_IDs", ")", ">", "0", ",", "'Did we forget to add to def_IDs?'", "v", "=", "[", "np", ".", "linalg", "."...
Checks if env is static, used for checking if action finished.
[ "Checks", "if", "env", "is", "static", "used", "for", "checking", "if", "action", "finished", "." ]
[ "\"\"\"Checks if env is static, used for checking if action finished.\n\n However, this won't work in PyBullet (at least v2.8.4) since soft\n bodies cause this code to hang. Therefore, look at the task's\n `def_IDs` list, which by design will have all IDs of soft bodies.\n Furthermore, f...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7f8815b3761deea061ba8bffc2da724c866803d5
gautams3/deformable-ravens
ravens/environment.py
[ "Apache-2.0" ]
Python
reset
<not_specific>
def reset(self, task, last_info=None, disable_render_load=True): """Sets up PyBullet, loads models, resets the specific task. We do a step() call with act=None at the end. This will only return an empty obs dict, obs={}. For some tasks where the reward could be nonzero at the start, we ...
Sets up PyBullet, loads models, resets the specific task. We do a step() call with act=None at the end. This will only return an empty obs dict, obs={}. For some tasks where the reward could be nonzero at the start, we can report the reward shown here. Args: last_info: Only...
Sets up PyBullet, loads models, resets the specific task. We do a step() call with act=None at the end. This will only return an empty obs dict, obs={}. For some tasks where the reward could be nonzero at the start, we can report the reward shown here.
[ "Sets", "up", "PyBullet", "loads", "models", "resets", "the", "specific", "task", ".", "We", "do", "a", "step", "()", "call", "with", "act", "=", "None", "at", "the", "end", ".", "This", "will", "only", "return", "an", "empty", "obs", "dict", "obs", ...
def reset(self, task, last_info=None, disable_render_load=True): self.pause() self.task = task self.objects = [] self.fixed_objects = [] if self.use_new_deformable: p.resetSimulation(p.RESET_USE_DEFORMABLE_WORLD) else: p.resetSimulation() p...
[ "def", "reset", "(", "self", ",", "task", ",", "last_info", "=", "None", ",", "disable_render_load", "=", "True", ")", ":", "self", ".", "pause", "(", ")", "self", ".", "task", "=", "task", "self", ".", "objects", "=", "[", "]", "self", ".", "fixed...
Sets up PyBullet, loads models, resets the specific task.
[ "Sets", "up", "PyBullet", "loads", "models", "resets", "the", "specific", "task", "." ]
[ "\"\"\"Sets up PyBullet, loads models, resets the specific task.\n\n We do a step() call with act=None at the end. This will only return\n an empty obs dict, obs={}. For some tasks where the reward could be\n nonzero at the start, we can report the reward shown here.\n\n Args:\n ...
[ { "param": "self", "type": null }, { "param": "task", "type": null }, { "param": "last_info", "type": null }, { "param": "disable_render_load", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "task", "type": null, "docstring": null, "docstring_tokens": [...
7f8815b3761deea061ba8bffc2da724c866803d5
gautams3/deformable-ravens
ravens/environment.py
[ "Apache-2.0" ]
Python
step
<not_specific>
def step(self, act=None): """Execute action with specified primitive. For each episode (training, loading, etc.), this is normally called the first time from `env.reset()` above, with NO action, and returns an EMPTY observation. Then, it's called a SECOND time with an action that lacks ...
Execute action with specified primitive. For each episode (training, loading, etc.), this is normally called the first time from `env.reset()` above, with NO action, and returns an EMPTY observation. Then, it's called a SECOND time with an action that lacks a primitive (set to None, eve...
Execute action with specified primitive. For each episode (training, loading, etc.), this is normally called the first time from `env.reset()` above, with NO action, and returns an EMPTY observation. Then, it's called a SECOND time with an action that lacks a primitive (set to None, even though the key exists). But, th...
[ "Execute", "action", "with", "specified", "primitive", ".", "For", "each", "episode", "(", "training", "loading", "etc", ".", ")", "this", "is", "normally", "called", "the", "first", "time", "from", "`", "env", ".", "reset", "()", "`", "above", "with", "...
def step(self, act=None): if act and act['primitive']: success = self.primitives[act['primitive']](**act['params']) if (not success) or self.task.exit_gracefully: _, reward_extras = self.task.reward() info = self.info reward_extras['task.do...
[ "def", "step", "(", "self", ",", "act", "=", "None", ")", ":", "if", "act", "and", "act", "[", "'primitive'", "]", ":", "success", "=", "self", ".", "primitives", "[", "act", "[", "'primitive'", "]", "]", "(", "**", "act", "[", "'params'", "]", "...
Execute action with specified primitive.
[ "Execute", "action", "with", "specified", "primitive", "." ]
[ "\"\"\"Execute action with specified primitive.\n\n For each episode (training, loading, etc.), this is normally called the first\n time from `env.reset()` above, with NO action, and returns an EMPTY observation.\n Then, it's called a SECOND time with an action that lacks a primitive (set to\n ...
[ { "param": "self", "type": null }, { "param": "act", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "act", "type": null, "docstring": null, "docstring_tokens": []...
7f8815b3761deea061ba8bffc2da724c866803d5
gautams3/deformable-ravens
ravens/environment.py
[ "Apache-2.0" ]
Python
render
<not_specific>
def render(self, config): """Render RGB-D image with specified configuration.""" # Compute OpenGL camera settings. lookdir = np.array([0, 0, 1]).reshape(3, 1) updir = np.array([0, -1, 0]).reshape(3, 1) rotation = p.getMatrixFromQuaternion(config['rotation']) rotm = np.ar...
Render RGB-D image with specified configuration.
Render RGB-D image with specified configuration.
[ "Render", "RGB", "-", "D", "image", "with", "specified", "configuration", "." ]
def render(self, config): lookdir = np.array([0, 0, 1]).reshape(3, 1) updir = np.array([0, -1, 0]).reshape(3, 1) rotation = p.getMatrixFromQuaternion(config['rotation']) rotm = np.array(rotation).reshape(3, 3) lookdir = (rotm @ lookdir).reshape(-1) updir = (rotm @ updir)....
[ "def", "render", "(", "self", ",", "config", ")", ":", "lookdir", "=", "np", ".", "array", "(", "[", "0", ",", "0", ",", "1", "]", ")", ".", "reshape", "(", "3", ",", "1", ")", "updir", "=", "np", ".", "array", "(", "[", "0", ",", "-", "1...
Render RGB-D image with specified configuration.
[ "Render", "RGB", "-", "D", "image", "with", "specified", "configuration", "." ]
[ "\"\"\"Render RGB-D image with specified configuration.\"\"\"", "# Compute OpenGL camera settings.", "# Notes: 1) FOV is vertical FOV 2) aspect must be float", "# Render with OpenGL camera settings.", "# Get color image.", "# remove alpha channel", "# Get depth image.", "# Get segmentation image." ]
[ { "param": "self", "type": null }, { "param": "config", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "config", "type": null, "docstring": null, "docstring_tokens":...
7f8815b3761deea061ba8bffc2da724c866803d5
gautams3/deformable-ravens
ravens/environment.py
[ "Apache-2.0" ]
Python
movej
<not_specific>
def movej(self, targj, speed=0.01, t_lim=20): """Move UR5 to target joint configuration.""" t0 = time.time() while (time.time() - t0) < t_lim: currj = [p.getJointState(self.ur5, i)[0] for i in self.joints] currj = np.array(currj) diffj = targj - currj ...
Move UR5 to target joint configuration.
Move UR5 to target joint configuration.
[ "Move", "UR5", "to", "target", "joint", "configuration", "." ]
def movej(self, targj, speed=0.01, t_lim=20): t0 = time.time() while (time.time() - t0) < t_lim: currj = [p.getJointState(self.ur5, i)[0] for i in self.joints] currj = np.array(currj) diffj = targj - currj if all(np.abs(diffj) < 1e-2): retu...
[ "def", "movej", "(", "self", ",", "targj", ",", "speed", "=", "0.01", ",", "t_lim", "=", "20", ")", ":", "t0", "=", "time", ".", "time", "(", ")", "while", "(", "time", ".", "time", "(", ")", "-", "t0", ")", "<", "t_lim", ":", "currj", "=", ...
Move UR5 to target joint configuration.
[ "Move", "UR5", "to", "target", "joint", "configuration", "." ]
[ "\"\"\"Move UR5 to target joint configuration.\"\"\"", "# Move with constant velocity" ]
[ { "param": "self", "type": null }, { "param": "targj", "type": null }, { "param": "speed", "type": null }, { "param": "t_lim", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "targj", "type": null, "docstring": null, "docstring_tokens": ...
7f8815b3761deea061ba8bffc2da724c866803d5
gautams3/deformable-ravens
ravens/environment.py
[ "Apache-2.0" ]
Python
movep
<not_specific>
def movep(self, pose, speed=0.01): """Move UR5 to target end effector pose.""" # # Keep joint angles between -180/+180 # targj[5] = ((targj[5] + np.pi) % (2 * np.pi) - np.pi) targj = self.solve_IK(pose) return self.movej(targj, speed, self.t_lim)
Move UR5 to target end effector pose.
Move UR5 to target end effector pose.
[ "Move", "UR5", "to", "target", "end", "effector", "pose", "." ]
def movep(self, pose, speed=0.01): targj = self.solve_IK(pose) return self.movej(targj, speed, self.t_lim)
[ "def", "movep", "(", "self", ",", "pose", ",", "speed", "=", "0.01", ")", ":", "targj", "=", "self", ".", "solve_IK", "(", "pose", ")", "return", "self", ".", "movej", "(", "targj", ",", "speed", ",", "self", ".", "t_lim", ")" ]
Move UR5 to target end effector pose.
[ "Move", "UR5", "to", "target", "end", "effector", "pose", "." ]
[ "\"\"\"Move UR5 to target end effector pose.\"\"\"", "# # Keep joint angles between -180/+180", "# targj[5] = ((targj[5] + np.pi) % (2 * np.pi) - np.pi)" ]
[ { "param": "self", "type": null }, { "param": "pose", "type": null }, { "param": "speed", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pose", "type": null, "docstring": null, "docstring_tokens": [...
7f8815b3761deea061ba8bffc2da724c866803d5
gautams3/deformable-ravens
ravens/environment.py
[ "Apache-2.0" ]
Python
pick_place
<not_specific>
def pick_place(self, pose0, pose1): """Execute pick and place primitive. Standard ravens tasks use the `delta` vector to lower the gripper until it makes contact with something. With deformables, however, we need to consider cases when the gripper could detect a rigid OR a soft ...
Execute pick and place primitive. Standard ravens tasks use the `delta` vector to lower the gripper until it makes contact with something. With deformables, however, we need to consider cases when the gripper could detect a rigid OR a soft body (cloth or bag); it should grip the first i...
Execute pick and place primitive. Standard ravens tasks use the `delta` vector to lower the gripper until it makes contact with something. With deformables, however, we need to consider cases when the gripper could detect a rigid OR a soft body (cloth or bag); it should grip the first item it touches. This is handled i...
[ "Execute", "pick", "and", "place", "primitive", ".", "Standard", "ravens", "tasks", "use", "the", "`", "delta", "`", "vector", "to", "lower", "the", "gripper", "until", "it", "makes", "contact", "with", "something", ".", "With", "deformables", "however", "we...
def pick_place(self, pose0, pose1): speed = 0.01 delta_z = -0.001 prepick_z = 0.3 postpick_z = 0.3 preplace_z = 0.3 pause_place = 0.0 final_z = 0.3 if hasattr(self.task, 'primitive_params'): ts = self.task.task_stage if 'prepick_z' ...
[ "def", "pick_place", "(", "self", ",", "pose0", ",", "pose1", ")", ":", "speed", "=", "0.01", "delta_z", "=", "-", "0.001", "prepick_z", "=", "0.3", "postpick_z", "=", "0.3", "preplace_z", "=", "0.3", "pause_place", "=", "0.0", "final_z", "=", "0.3", "...
Execute pick and place primitive.
[ "Execute", "pick", "and", "place", "primitive", "." ]
[ "\"\"\"Execute pick and place primitive.\n\n Standard ravens tasks use the `delta` vector to lower the gripper\n until it makes contact with something. With deformables, however, we\n need to consider cases when the gripper could detect a rigid OR a\n soft body (cloth or bag); it should ...
[ { "param": "self", "type": null }, { "param": "pose0", "type": null }, { "param": "pose1", "type": null } ]
{ "returns": [ { "docstring": "A bool indicating whether the action succeeded or not, via\nchecking the sequence of movep calls. If any movep failed, then\nself.step() will terminate the episode after this action.", "docstring_tokens": [ "A", "bool", "indicating", "whet...
7f8815b3761deea061ba8bffc2da724c866803d5
gautams3/deformable-ravens
ravens/environment.py
[ "Apache-2.0" ]
Python
is_new_cable_env
<not_specific>
def is_new_cable_env(self): """I want a way to track new cable-related stuff alone.""" return (isinstance(self.task, tasks.names['cable-shape']) or isinstance(self.task, tasks.names['cable-shape-notarget']) or isinstance(self.task, tasks.names['cable-line-notarget']) or ...
I want a way to track new cable-related stuff alone.
I want a way to track new cable-related stuff alone.
[ "I", "want", "a", "way", "to", "track", "new", "cable", "-", "related", "stuff", "alone", "." ]
def is_new_cable_env(self): return (isinstance(self.task, tasks.names['cable-shape']) or isinstance(self.task, tasks.names['cable-shape-notarget']) or isinstance(self.task, tasks.names['cable-line-notarget']) or isinstance(self.task, tasks.names['cable-ring']) or ...
[ "def", "is_new_cable_env", "(", "self", ")", ":", "return", "(", "isinstance", "(", "self", ".", "task", ",", "tasks", ".", "names", "[", "'cable-shape'", "]", ")", "or", "isinstance", "(", "self", ".", "task", ",", "tasks", ".", "names", "[", "'cable-...
I want a way to track new cable-related stuff alone.
[ "I", "want", "a", "way", "to", "track", "new", "cable", "-", "related", "stuff", "alone", "." ]
[ "\"\"\"I want a way to track new cable-related stuff alone.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7f8815b3761deea061ba8bffc2da724c866803d5
gautams3/deformable-ravens
ravens/environment.py
[ "Apache-2.0" ]
Python
is_cloth_env
<not_specific>
def is_cloth_env(self): """Keep this updated when I adjust environment names.""" return (isinstance(self.task, tasks.names['cloth-flat']) or isinstance(self.task, tasks.names['cloth-flat-notarget']) or isinstance(self.task, tasks.names['cloth-cover']))
Keep this updated when I adjust environment names.
Keep this updated when I adjust environment names.
[ "Keep", "this", "updated", "when", "I", "adjust", "environment", "names", "." ]
def is_cloth_env(self): return (isinstance(self.task, tasks.names['cloth-flat']) or isinstance(self.task, tasks.names['cloth-flat-notarget']) or isinstance(self.task, tasks.names['cloth-cover']))
[ "def", "is_cloth_env", "(", "self", ")", ":", "return", "(", "isinstance", "(", "self", ".", "task", ",", "tasks", ".", "names", "[", "'cloth-flat'", "]", ")", "or", "isinstance", "(", "self", ".", "task", ",", "tasks", ".", "names", "[", "'cloth-flat-...
Keep this updated when I adjust environment names.
[ "Keep", "this", "updated", "when", "I", "adjust", "environment", "names", "." ]
[ "\"\"\"Keep this updated when I adjust environment names.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7f8815b3761deea061ba8bffc2da724c866803d5
gautams3/deformable-ravens
ravens/environment.py
[ "Apache-2.0" ]
Python
is_bag_env
<not_specific>
def is_bag_env(self): """Keep this updated when I adjust environment names.""" return (isinstance(self.task, tasks.names['bag-alone-open']) or isinstance(self.task, tasks.names['bag-items-easy']) or isinstance(self.task, tasks.names['bag-items-hard']) or i...
Keep this updated when I adjust environment names.
Keep this updated when I adjust environment names.
[ "Keep", "this", "updated", "when", "I", "adjust", "environment", "names", "." ]
def is_bag_env(self): return (isinstance(self.task, tasks.names['bag-alone-open']) or isinstance(self.task, tasks.names['bag-items-easy']) or isinstance(self.task, tasks.names['bag-items-hard']) or isinstance(self.task, tasks.names['bag-color-goal']))
[ "def", "is_bag_env", "(", "self", ")", ":", "return", "(", "isinstance", "(", "self", ".", "task", ",", "tasks", ".", "names", "[", "'bag-alone-open'", "]", ")", "or", "isinstance", "(", "self", ".", "task", ",", "tasks", ".", "names", "[", "'bag-items...
Keep this updated when I adjust environment names.
[ "Keep", "this", "updated", "when", "I", "adjust", "environment", "names", "." ]
[ "\"\"\"Keep this updated when I adjust environment names.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
9552039ba941bc587c0bb9d09d5ea50879693890
gautams3/deformable-ravens
ravens/tasks/task.py
[ "Apache-2.0" ]
Python
params_no_rots
<not_specific>
def params_no_rots(self, vertex_pos, target_pos, overshoot): """Helper to handle common pick-place code for the oracle policy. We often have this patten: vertex positions and target positions in 2D, and then potentially slightly overshoot the target. For example, with cloth it's helpful...
Helper to handle common pick-place code for the oracle policy. We often have this patten: vertex positions and target positions in 2D, and then potentially slightly overshoot the target. For example, with cloth it's helpful to do this since otherwise the physics will favor the cloth 're...
Helper to handle common pick-place code for the oracle policy. We often have this patten: vertex positions and target positions in 2D, and then potentially slightly overshoot the target. For example, with cloth it's helpful to do this since otherwise the physics will favor the cloth 'resetting' to its original state. G...
[ "Helper", "to", "handle", "common", "pick", "-", "place", "code", "for", "the", "oracle", "policy", ".", "We", "often", "have", "this", "patten", ":", "vertex", "positions", "and", "target", "positions", "in", "2D", "and", "then", "potentially", "slightly", ...
def params_no_rots(self, vertex_pos, target_pos, overshoot): p0 = (vertex_pos[0], vertex_pos[1], 0.001) p1 = (target_pos[0], target_pos[1], 0.001) direction = np.float32(p0) - np.float32(p1) length = np.linalg.norm(direction) direction = direction / length new_p0 = np.flo...
[ "def", "params_no_rots", "(", "self", ",", "vertex_pos", ",", "target_pos", ",", "overshoot", ")", ":", "p0", "=", "(", "vertex_pos", "[", "0", "]", ",", "vertex_pos", "[", "1", "]", ",", "0.001", ")", "p1", "=", "(", "target_pos", "[", "0", "]", "...
Helper to handle common pick-place code for the oracle policy.
[ "Helper", "to", "handle", "common", "pick", "-", "place", "code", "for", "the", "oracle", "policy", "." ]
[ "\"\"\"Helper to handle common pick-place code for the oracle policy.\n\n We often have this patten: vertex positions and target positions in\n 2D, and then potentially slightly overshoot the target. For example,\n with cloth it's helpful to do this since otherwise the physics will\n fav...
[ { "param": "self", "type": null }, { "param": "vertex_pos", "type": null }, { "param": "target_pos", "type": null }, { "param": "overshoot", "type": null } ]
{ "returns": [ { "docstring": "Dict for the action with 'pose0' and 'pose1' keys.", "docstring_tokens": [ "Dict", "for", "the", "action", "with", "'", "pose0", "'", "and", "'", "pose1", "'", "keys",...
9552039ba941bc587c0bb9d09d5ea50879693890
gautams3/deformable-ravens
ravens/tasks/task.py
[ "Apache-2.0" ]
Python
done
<not_specific>
def done(self): """Check if the task is done AND has not failed. To be clear: for normal Ravens envs, `self.total_rewards` represents the sum of deltas, or the sum of the `reward` returned by `reward()` defined above. Think of it as the "true reward at this moment." I follow thi...
Check if the task is done AND has not failed. To be clear: for normal Ravens envs, `self.total_rewards` represents the sum of deltas, or the sum of the `reward` returned by `reward()` defined above. Think of it as the "true reward at this moment." I follow this convention for custom env...
Check if the task is done AND has not failed. For multi-step tasks such as `cloth-cover-item`, one must need to accomplish all stages correctly. (08 Sept 2020): I added self.exit_gracefully, which will help us quickly exit if the demo has failed, but this is not handled here. (14 Sept 2020) We want self.done to retu...
[ "Check", "if", "the", "task", "is", "done", "AND", "has", "not", "failed", ".", "For", "multi", "-", "step", "tasks", "such", "as", "`", "cloth", "-", "cover", "-", "item", "`", "one", "must", "need", "to", "accomplish", "all", "stages", "correctly", ...
def done(self): zone_done, goal_done, cable_done, cov_done, bag_done = \ False, False, False, False, False if self.metric == 'zone': zone_done = self.total_rewards == 1 elif self.metric == 'cable-target': cable_done = self.total_rewards == 1 elif s...
[ "def", "done", "(", "self", ")", ":", "zone_done", ",", "goal_done", ",", "cable_done", ",", "cov_done", ",", "bag_done", "=", "False", ",", "False", ",", "False", ",", "False", ",", "False", "if", "self", ".", "metric", "==", "'zone'", ":", "zone_done...
Check if the task is done AND has not failed.
[ "Check", "if", "the", "task", "is", "done", "AND", "has", "not", "failed", "." ]
[ "\"\"\"Check if the task is done AND has not failed.\n\n To be clear: for normal Ravens envs, `self.total_rewards` represents\n the sum of deltas, or the sum of the `reward` returned by `reward()`\n defined above. Think of it as the \"true reward at this moment.\" I\n follow this convent...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
9552039ba941bc587c0bb9d09d5ea50879693890
gautams3/deformable-ravens
ravens/tasks/task.py
[ "Apache-2.0" ]
Python
fill_template
<not_specific>
def fill_template(self, template, replace): """Read template file and replace string keys. The replace[field] needs to be a tuple. Use (item,) for a single item, but you can combine keys with NAMEX where X starts from 0. """ filepath = os.path.dirname(os.path.abspath(__file__)) ...
Read template file and replace string keys. The replace[field] needs to be a tuple. Use (item,) for a single item, but you can combine keys with NAMEX where X starts from 0.
Read template file and replace string keys. The replace[field] needs to be a tuple. Use (item,) for a single item, but you can combine keys with NAMEX where X starts from 0.
[ "Read", "template", "file", "and", "replace", "string", "keys", ".", "The", "replace", "[", "field", "]", "needs", "to", "be", "a", "tuple", ".", "Use", "(", "item", ")", "for", "a", "single", "item", "but", "you", "can", "combine", "keys", "with", "...
def fill_template(self, template, replace): filepath = os.path.dirname(os.path.abspath(__file__)) template = os.path.join(filepath, '..', template) with open(template, 'r') as file: fdata = file.read() for field in replace: for i in range(len(replace[field])): ...
[ "def", "fill_template", "(", "self", ",", "template", ",", "replace", ")", ":", "filepath", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", "template", "=", "os", ".", "path", ".", "join", ...
Read template file and replace string keys.
[ "Read", "template", "file", "and", "replace", "string", "keys", "." ]
[ "\"\"\"Read template file and replace string keys.\n\n The replace[field] needs to be a tuple. Use (item,) for a single\n item, but you can combine keys with NAMEX where X starts from 0.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "template", "type": null }, { "param": "replace", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "template", "type": null, "docstring": null, "docstring_tokens...
9552039ba941bc587c0bb9d09d5ea50879693890
gautams3/deformable-ravens
ravens/tasks/task.py
[ "Apache-2.0" ]
Python
random_pose
<not_specific>
def random_pose(self, env, object_size, hard_code=False): """Get random collision-free pose in workspace bounds for object. For tasks like sweeping to a zone target, generates a target zone at random, then later generates items to be swept in it. The second step requires free space to a...
Get random collision-free pose in workspace bounds for object. For tasks like sweeping to a zone target, generates a target zone at random, then later generates items to be swept in it. The second step requires free space to avoid being within the zone. The `mask` defines a distributio...
Get random collision-free pose in workspace bounds for object. For tasks like sweeping to a zone target, generates a target zone at random, then later generates items to be swept in it. The second step requires free space to avoid being within the zone. The `mask` defines a distribution over pixels in the 320x160 top-...
[ "Get", "random", "collision", "-", "free", "pose", "in", "workspace", "bounds", "for", "object", ".", "For", "tasks", "like", "sweeping", "to", "a", "zone", "target", "generates", "a", "target", "zone", "at", "random", "then", "later", "generates", "items", ...
def random_pose(self, env, object_size, hard_code=False): plane_id = 1 max_size = np.sqrt(object_size[0]**2 + object_size[1]**2) erode_size = int(np.round(max_size / self.pixel_size)) colormap, heightmap, object_mask = self.get_object_masks(env) mask = np.uint8(object_mask == pla...
[ "def", "random_pose", "(", "self", ",", "env", ",", "object_size", ",", "hard_code", "=", "False", ")", ":", "plane_id", "=", "1", "max_size", "=", "np", ".", "sqrt", "(", "object_size", "[", "0", "]", "**", "2", "+", "object_size", "[", "1", "]", ...
Get random collision-free pose in workspace bounds for object.
[ "Get", "random", "collision", "-", "free", "pose", "in", "workspace", "bounds", "for", "object", "." ]
[ "\"\"\"Get random collision-free pose in workspace bounds for object.\n\n For tasks like sweeping to a zone target, generates a target zone at\n random, then later generates items to be swept in it. The second step\n requires free space to avoid being within the zone.\n\n The `mask` defi...
[ { "param": "self", "type": null }, { "param": "env", "type": null }, { "param": "object_size", "type": null }, { "param": "hard_code", "type": null } ]
{ "returns": [ { "docstring": "used to convert from base / root link (I\nthink) to where the object (or zone) should be located. The\nposition must be sampled from the workspace, which is why\nenvironments with target zones have the zones sampled on the\nworkstation. The rotation is only applied on the z-ax...
9552039ba941bc587c0bb9d09d5ea50879693890
gautams3/deformable-ravens
ravens/tasks/task.py
[ "Apache-2.0" ]
Python
apply
<not_specific>
def apply(self, pose, position): """Daniel: apply a rigid body transformation on `position` by `pose`. The `pose` has the rotation matrix and translation vector. Apply the rotation matrix on `position` and then translate. Example: used in cables env to sequentially translate each bead i...
Daniel: apply a rigid body transformation on `position` by `pose`. The `pose` has the rotation matrix and translation vector. Apply the rotation matrix on `position` and then translate. Example: used in cables env to sequentially translate each bead in the cable. Returns a *position*, ...
apply a rigid body transformation on `position` by `pose`. The `pose` has the rotation matrix and translation vector. Apply the rotation matrix on `position` and then translate. Example: used in cables env to sequentially translate each bead in the cable. Returns a *position*, not a pose (no orientation).
[ "apply", "a", "rigid", "body", "transformation", "on", "`", "position", "`", "by", "`", "pose", "`", ".", "The", "`", "pose", "`", "has", "the", "rotation", "matrix", "and", "translation", "vector", ".", "Apply", "the", "rotation", "matrix", "on", "`", ...
def apply(self, pose, position): position = np.float32(position) position_shape = position.shape position = np.float32(position).reshape(3, -1) rotation = np.float32(p.getMatrixFromQuaternion(pose[1])).reshape(3, 3) translation = np.float32(pose[0]).reshape(3, 1) position...
[ "def", "apply", "(", "self", ",", "pose", ",", "position", ")", ":", "position", "=", "np", ".", "float32", "(", "position", ")", "position_shape", "=", "position", ".", "shape", "position", "=", "np", ".", "float32", "(", "position", ")", ".", "reshap...
Daniel: apply a rigid body transformation on `position` by `pose`.
[ "Daniel", ":", "apply", "a", "rigid", "body", "transformation", "on", "`", "position", "`", "by", "`", "pose", "`", "." ]
[ "\"\"\"Daniel: apply a rigid body transformation on `position` by `pose`.\n\n The `pose` has the rotation matrix and translation vector. Apply the\n rotation matrix on `position` and then translate. Example: used in\n cables env to sequentially translate each bead in the cable.\n\n Retur...
[ { "param": "self", "type": null }, { "param": "pose", "type": null }, { "param": "position", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pose", "type": null, "docstring": null, "docstring_tokens": [...
fa696e30f5de82c9e1f7c6cb76a250b9a299197f
gautams3/deformable-ravens
ravens/agents/gt_state.py
[ "Apache-2.0" ]
Python
extract_x_y_theta
<not_specific>
def extract_x_y_theta(self, object_info, t_worldaug_world=None, preserve_theta=False, softbody=False): """Given either object OR action pose info, return stuff to put in GT observation. Note: only called from within this class and 2-step case via subclassing. During training, there is normally ...
Given either object OR action pose info, return stuff to put in GT observation. Note: only called from within this class and 2-step case via subclassing. During training, there is normally data augmentation applied, so t_worldaug_world is NOT None, and augmentation is applied as if the 'image' ...
Given either object OR action pose info, return stuff to put in GT observation. Note: only called from within this class and 2-step case via subclassing. During training, there is normally data augmentation applied, so t_worldaug_world is NOT None, and augmentation is applied as if the 'image' were adjusted. However, ...
[ "Given", "either", "object", "OR", "action", "pose", "info", "return", "stuff", "to", "put", "in", "GT", "observation", ".", "Note", ":", "only", "called", "from", "within", "this", "class", "and", "2", "-", "step", "case", "via", "subclassing", ".", "Du...
def extract_x_y_theta(self, object_info, t_worldaug_world=None, preserve_theta=False, softbody=False): if (self.task in TASKS_SOFT) and (len(object_info) == 2) and softbody: nb_vertices, vert_pos_l = object_info assert nb_vertices == 100, f'We should be using 100 vertices but have: {nb_v...
[ "def", "extract_x_y_theta", "(", "self", ",", "object_info", ",", "t_worldaug_world", "=", "None", ",", "preserve_theta", "=", "False", ",", "softbody", "=", "False", ")", ":", "if", "(", "self", ".", "task", "in", "TASKS_SOFT", ")", "and", "(", "len", "...
Given either object OR action pose info, return stuff to put in GT observation.
[ "Given", "either", "object", "OR", "action", "pose", "info", "return", "stuff", "to", "put", "in", "GT", "observation", "." ]
[ "\"\"\"Given either object OR action pose info, return stuff to put in GT observation.\n Note: only called from within this class and 2-step case via subclassing.\n\n During training, there is normally data augmentation applied, so t_worldaug_world\n is NOT None, and augmentation is applied as ...
[ { "param": "self", "type": null }, { "param": "object_info", "type": null }, { "param": "t_worldaug_world", "type": null }, { "param": "preserve_theta", "type": null }, { "param": "softbody", "type": null } ]
{ "returns": [ { "docstring": "object_x_y_theta, pos, quat: the first is an SE(2) pose and parameterized by\nthree numbers, the xy position and a scalar rotation `theta`. In case we have\na cloth, I'm not returning anything after that (no pos or quat) so that if we\nuse the older API for cloth (which we sho...
fa696e30f5de82c9e1f7c6cb76a250b9a299197f
gautams3/deformable-ravens
ravens/agents/gt_state.py
[ "Apache-2.0" ]
Python
info_to_gt_obs
<not_specific>
def info_to_gt_obs(self, info, t_worldaug_world=None, goal=None): """Daniel: from info dict of IDs, create the observation for GT models. Assumes `info` consists of just PyBullet object IDs. Creates a numpy array from combining the `object_x_y_theta` from all IDs, and potentially add more ...
Daniel: from info dict of IDs, create the observation for GT models. Assumes `info` consists of just PyBullet object IDs. Creates a numpy array from combining the `object_x_y_theta` from all IDs, and potentially add more info based on if using box dimensions or colors; see `__init__()` above. ...
from info dict of IDs, create the observation for GT models. Assumes `info` consists of just PyBullet object IDs. Creates a numpy array from combining the `object_x_y_theta` from all IDs, and potentially add more info based on if using box dimensions or colors; see `__init__()` above. For soft body tasks, we should ha...
[ "from", "info", "dict", "of", "IDs", "create", "the", "observation", "for", "GT", "models", ".", "Assumes", "`", "info", "`", "consists", "of", "just", "PyBullet", "object", "IDs", ".", "Creates", "a", "numpy", "array", "from", "combining", "the", "`", "...
def info_to_gt_obs(self, info, t_worldaug_world=None, goal=None): info = self.remove_nonint_keys(info) if goal is not None: g_info = self.remove_nonint_keys(goal['info']) else: g_info = {} observation_vector = [] object_keys = sorted(info.keys()) f...
[ "def", "info_to_gt_obs", "(", "self", ",", "info", ",", "t_worldaug_world", "=", "None", ",", "goal", "=", "None", ")", ":", "info", "=", "self", ".", "remove_nonint_keys", "(", "info", ")", "if", "goal", "is", "not", "None", ":", "g_info", "=", "self"...
Daniel: from info dict of IDs, create the observation for GT models.
[ "Daniel", ":", "from", "info", "dict", "of", "IDs", "create", "the", "observation", "for", "GT", "models", "." ]
[ "\"\"\"Daniel: from info dict of IDs, create the observation for GT models.\n\n Assumes `info` consists of just PyBullet object IDs. Creates a numpy array\n from combining the `object_x_y_theta` from all IDs, and potentially add more\n info based on if using box dimensions or colors; see `__ini...
[ { "param": "self", "type": null }, { "param": "info", "type": null }, { "param": "t_worldaug_world", "type": null }, { "param": "goal", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "info", "type": null, "docstring": null, "docstring_tokens": [...
fa696e30f5de82c9e1f7c6cb76a250b9a299197f
gautams3/deformable-ravens
ravens/agents/gt_state.py
[ "Apache-2.0" ]
Python
act_to_gt_act
<not_specific>
def act_to_gt_act(self, act, t_worldaug_world=None, transform_params=None): """Daniel: similarly, from action, create the appropriate ground truth action. This may involve a transformation if doing data augmentation. Comment from Andy/Pete: dont update theta due to suction invariance to theta ...
Daniel: similarly, from action, create the appropriate ground truth action. This may involve a transformation if doing data augmentation. Comment from Andy/Pete: dont update theta due to suction invariance to theta
similarly, from action, create the appropriate ground truth action. This may involve a transformation if doing data augmentation. Comment from Andy/Pete: dont update theta due to suction invariance to theta
[ "similarly", "from", "action", "create", "the", "appropriate", "ground", "truth", "action", ".", "This", "may", "involve", "a", "transformation", "if", "doing", "data", "augmentation", ".", "Comment", "from", "Andy", "/", "Pete", ":", "dont", "update", "theta"...
def act_to_gt_act(self, act, t_worldaug_world=None, transform_params=None): pick_se2, _, _ = self.extract_x_y_theta(act['params']['pose0'], t_worldaug_world, preserve_theta=True) place_se2, _, _ = self.extract_x_y_theta(act['params']['pose1'], t_worldaug_world, preserve_theta=True) return np.hst...
[ "def", "act_to_gt_act", "(", "self", ",", "act", ",", "t_worldaug_world", "=", "None", ",", "transform_params", "=", "None", ")", ":", "pick_se2", ",", "_", ",", "_", "=", "self", ".", "extract_x_y_theta", "(", "act", "[", "'params'", "]", "[", "'pose0'"...
Daniel: similarly, from action, create the appropriate ground truth action.
[ "Daniel", ":", "similarly", "from", "action", "create", "the", "appropriate", "ground", "truth", "action", "." ]
[ "\"\"\"Daniel: similarly, from action, create the appropriate ground truth action.\n\n This may involve a transformation if doing data augmentation.\n Comment from Andy/Pete: dont update theta due to suction invariance to theta\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "act", "type": null }, { "param": "t_worldaug_world", "type": null }, { "param": "transform_params", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "act", "type": null, "docstring": null, "docstring_tokens": []...
fa696e30f5de82c9e1f7c6cb76a250b9a299197f
gautams3/deformable-ravens
ravens/agents/gt_state.py
[ "Apache-2.0" ]
Python
init_model
null
def init_model(self, dataset): """Initialize self.model, including normalization parameters.""" self.set_max_obs_vector_length(dataset) # Get obs dim and action dim (3 for pick, 3 for place), initialize model. if self.goal_conditioned: _, _, info, goal = dataset.random_sampl...
Initialize self.model, including normalization parameters.
Initialize self.model, including normalization parameters.
[ "Initialize", "self", ".", "model", "including", "normalization", "parameters", "." ]
def init_model(self, dataset): self.set_max_obs_vector_length(dataset) if self.goal_conditioned: _, _, info, goal = dataset.random_sample(goal_images=True) obs_vector = self.info_to_gt_obs(info, goal=goal) else: _, _, info = dataset.random_sample() ...
[ "def", "init_model", "(", "self", ",", "dataset", ")", ":", "self", ".", "set_max_obs_vector_length", "(", "dataset", ")", "if", "self", ".", "goal_conditioned", ":", "_", ",", "_", ",", "info", ",", "goal", "=", "dataset", ".", "random_sample", "(", "go...
Initialize self.model, including normalization parameters.
[ "Initialize", "self", ".", "model", "including", "normalization", "parameters", "." ]
[ "\"\"\"Initialize self.model, including normalization parameters.\"\"\"", "# Get obs dim and action dim (3 for pick, 3 for place), initialize model.", "# Sample points from the data to get reasonable mean / std values." ]
[ { "param": "self", "type": null }, { "param": "dataset", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "dataset", "type": null, "docstring": null, "docstring_tokens"...
fa696e30f5de82c9e1f7c6cb76a250b9a299197f
gautams3/deformable-ravens
ravens/agents/gt_state.py
[ "Apache-2.0" ]
Python
train
<not_specific>
def train(self, dataset, num_iter, writer, validation_dataset=None): """Train on dataset for a specific number of iterations. Daniel: not testing with validation, argument copied over from ravens. Naively, we can train with MSE, but better to use a mixture model (MDN) since the output s...
Train on dataset for a specific number of iterations. Daniel: not testing with validation, argument copied over from ravens. Naively, we can train with MSE, but better to use a mixture model (MDN) since the output should be multi-modal; could be several pick points, and several placing points ...
Train on dataset for a specific number of iterations. Daniel: not testing with validation, argument copied over from ravens. Naively, we can train with MSE, but better to use a mixture model (MDN) since the output should be multi-modal; could be several pick points, and several placing points wrt those pick points. Al...
[ "Train", "on", "dataset", "for", "a", "specific", "number", "of", "iterations", ".", "Daniel", ":", "not", "testing", "with", "validation", "argument", "copied", "over", "from", "ravens", ".", "Naively", "we", "can", "train", "with", "MSE", "but", "better", ...
def train(self, dataset, num_iter, writer, validation_dataset=None): if self.model is None: self.init_model(dataset) if self.USE_MDN: loss_criterion = mdn_utils.mdn_loss else: loss_criterion = tf.keras.losses.MeanSquaredError() @tf.function def...
[ "def", "train", "(", "self", ",", "dataset", ",", "num_iter", ",", "writer", ",", "validation_dataset", "=", "None", ")", ":", "if", "self", ".", "model", "is", "None", ":", "self", ".", "init_model", "(", "dataset", ")", "if", "self", ".", "USE_MDN", ...
Train on dataset for a specific number of iterations.
[ "Train", "on", "dataset", "for", "a", "specific", "number", "of", "iterations", "." ]
[ "\"\"\"Train on dataset for a specific number of iterations.\n\n Daniel: not testing with validation, argument copied over from ravens. Naively,\n we can train with MSE, but better to use a mixture model (MDN) since the output\n should be multi-modal; could be several pick points, and several p...
[ { "param": "self", "type": null }, { "param": "dataset", "type": null }, { "param": "num_iter", "type": null }, { "param": "writer", "type": null }, { "param": "validation_dataset", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "dataset", "type": null, "docstring": null, "docstring_tokens"...
fa696e30f5de82c9e1f7c6cb76a250b9a299197f
gautams3/deformable-ravens
ravens/agents/gt_state.py
[ "Apache-2.0" ]
Python
act
<not_specific>
def act(self, obs, info, goal=None): """Run inference and return best action.""" act = {'camera_config': self.camera_config, 'primitive': None} # Get observations and run predictions (second part just for visualization). if self.goal_conditioned: gt_obs = self.info_to_gt_obs...
Run inference and return best action.
Run inference and return best action.
[ "Run", "inference", "and", "return", "best", "action", "." ]
def act(self, obs, info, goal=None): act = {'camera_config': self.camera_config, 'primitive': None} if self.goal_conditioned: gt_obs = self.info_to_gt_obs(info, goal=goal) gt_act_center = self.info_to_gt_obs(info, goal=goal) else: gt_obs = self.info_to_gt_obs(...
[ "def", "act", "(", "self", ",", "obs", ",", "info", ",", "goal", "=", "None", ")", ":", "act", "=", "{", "'camera_config'", ":", "self", ".", "camera_config", ",", "'primitive'", ":", "None", "}", "if", "self", ".", "goal_conditioned", ":", "gt_obs", ...
Run inference and return best action.
[ "Run", "inference", "and", "return", "best", "action", "." ]
[ "\"\"\"Run inference and return best action.\"\"\"", "# Get observations and run predictions (second part just for visualization).", "#prediction = mdn_utils.pick_max_mean(pi, mu, var)", "# unbatch", "# Just go exactly to objects, predicted. Daniel: adding 1 rotation inference case.", "# idx 2", "# idx ...
[ { "param": "self", "type": null }, { "param": "obs", "type": null }, { "param": "info", "type": null }, { "param": "goal", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "obs", "type": null, "docstring": null, "docstring_tokens": []...
34f37ec93172cf68794b7788dbe41e68d9959cf8
gautams3/deformable-ravens
ravens/tasks/defs_cables.py
[ "Apache-2.0" ]
Python
add_cable
null
def add_cable(self, env, size_range, info={}, cable_idx=0, direction='z', max_force=100): """Add a cable like Andy does it in his cable environment. Add each `part_id` to (a) env.objects, (b) object_points, (c) _IDs, and (d) cable_bead_IDs. For (b) it is because, like the sweeping e...
Add a cable like Andy does it in his cable environment. Add each `part_id` to (a) env.objects, (b) object_points, (c) _IDs, and (d) cable_bead_IDs. For (b) it is because, like the sweeping env, the demonstrator detects the one farthest from the goal to use as the pick, and `object_point...
Add a cable like Andy does it in his cable environment. When iterating through the number of parts, ensure that the given cable is _separate_ from prior cables, in case there are more than one. ALL beads are put in the `env.objects` list. The zone_range is used because we need the cables to start outside of the zone....
[ "Add", "a", "cable", "like", "Andy", "does", "it", "in", "his", "cable", "environment", ".", "When", "iterating", "through", "the", "number", "of", "parts", "ensure", "that", "the", "given", "cable", "is", "_separate_", "from", "prior", "cables", "in", "ca...
def add_cable(self, env, size_range, info={}, cable_idx=0, direction='z', max_force=100): num_parts = self.num_parts radius = self.radius length = self.length color = self.colors[cable_idx] + [1] color_end = U.COLORS['yellow'] + [1] distance = length / num_par...
[ "def", "add_cable", "(", "self", ",", "env", ",", "size_range", ",", "info", "=", "{", "}", ",", "cable_idx", "=", "0", ",", "direction", "=", "'z'", ",", "max_force", "=", "100", ")", ":", "num_parts", "=", "self", ".", "num_parts", "radius", "=", ...
Add a cable like Andy does it in his cable environment.
[ "Add", "a", "cable", "like", "Andy", "does", "it", "in", "his", "cable", "environment", "." ]
[ "\"\"\"Add a cable like Andy does it in his cable environment.\n\n Add each `part_id` to (a) env.objects, (b) object_points, (c) _IDs,\n and (d) cable_bead_IDs. For (b) it is because, like the sweeping env,\n the demonstrator detects the one farthest from the goal to use as the\n pick, a...
[ { "param": "self", "type": null }, { "param": "env", "type": null }, { "param": "size_range", "type": null }, { "param": "info", "type": null }, { "param": "cable_idx", "type": null }, { "param": "direction", "type": null }, { "param": "max...
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": []...
34f37ec93172cf68794b7788dbe41e68d9959cf8
gautams3/deformable-ravens
ravens/tasks/defs_cables.py
[ "Apache-2.0" ]
Python
add_cable_ring
<not_specific>
def add_cable_ring(self, env, info={}, cable_idx=0): """Add a cable, but make it connected at both ends to form a ring. For consistency, add each `part_id` to various information tracking lists and dictionaries (see `add_cable` documentation). :cable_idx: Used for environments with mor...
Add a cable, but make it connected at both ends to form a ring. For consistency, add each `part_id` to various information tracking lists and dictionaries (see `add_cable` documentation). :cable_idx: Used for environments with more than one cable. :info: Stores relevant stuff, such as ...
Add a cable, but make it connected at both ends to form a ring. For consistency, add each `part_id` to various information tracking lists and dictionaries .
[ "Add", "a", "cable", "but", "make", "it", "connected", "at", "both", "ends", "to", "form", "a", "ring", ".", "For", "consistency", "add", "each", "`", "part_id", "`", "to", "various", "information", "tracking", "lists", "and", "dictionaries", "." ]
def add_cable_ring(self, env, info={}, cable_idx=0): def rad_to_deg(rad): return (rad * 180.0) / np.pi def get_discretized_rotations(num_rotations): theta = i * (2 * np.pi) / num_rotations return (theta, rad_to_deg(theta)) num_parts = self.num_parts ra...
[ "def", "add_cable_ring", "(", "self", ",", "env", ",", "info", "=", "{", "}", ",", "cable_idx", "=", "0", ")", ":", "def", "rad_to_deg", "(", "rad", ")", ":", "return", "(", "rad", "*", "180.0", ")", "/", "np", ".", "pi", "def", "get_discretized_ro...
Add a cable, but make it connected at both ends to form a ring.
[ "Add", "a", "cable", "but", "make", "it", "connected", "at", "both", "ends", "to", "form", "a", "ring", "." ]
[ "\"\"\"Add a cable, but make it connected at both ends to form a ring.\n\n For consistency, add each `part_id` to various information tracking\n lists and dictionaries (see `add_cable` documentation).\n\n :cable_idx: Used for environments with more than one cable.\n :info: Stores relevan...
[ { "param": "self", "type": null }, { "param": "env", "type": null }, { "param": "info", "type": null }, { "param": "cable_idx", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": []...
34f37ec93172cf68794b7788dbe41e68d9959cf8
gautams3/deformable-ravens
ravens/tasks/defs_cables.py
[ "Apache-2.0" ]
Python
add_random_box
<not_specific>
def add_random_box(self, env): """Generate randomly shaped box, from aligning env.""" box_size = self.random_size(0.05, 0.15, 0.05, 0.15, 0.01, 0.06) box_pose = self.random_pose(env, box_size) box_template = 'assets/box/box-template.urdf' box_urdf = self.fill_template(box_templat...
Generate randomly shaped box, from aligning env.
Generate randomly shaped box, from aligning env.
[ "Generate", "randomly", "shaped", "box", "from", "aligning", "env", "." ]
def add_random_box(self, env): box_size = self.random_size(0.05, 0.15, 0.05, 0.15, 0.01, 0.06) box_pose = self.random_pose(env, box_size) box_template = 'assets/box/box-template.urdf' box_urdf = self.fill_template(box_template, {'DIM': box_size}) box_id = env.add_object(box_urdf,...
[ "def", "add_random_box", "(", "self", ",", "env", ")", ":", "box_size", "=", "self", ".", "random_size", "(", "0.05", ",", "0.15", ",", "0.05", ",", "0.15", ",", "0.01", ",", "0.06", ")", "box_pose", "=", "self", ".", "random_pose", "(", "env", ",", ...
Generate randomly shaped box, from aligning env.
[ "Generate", "randomly", "shaped", "box", "from", "aligning", "env", "." ]
[ "\"\"\"Generate randomly shaped box, from aligning env.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "env", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": []...
34f37ec93172cf68794b7788dbe41e68d9959cf8
gautams3/deformable-ravens
ravens/tasks/defs_cables.py
[ "Apache-2.0" ]
Python
area_thresh
<not_specific>
def area_thresh(self): """Only if we are using the cable-ring environment... So far I think using 0.8 or higher might be too hard because moving the ring to the target can cause other areas to decrease. """ return 0.75
Only if we are using the cable-ring environment... So far I think using 0.8 or higher might be too hard because moving the ring to the target can cause other areas to decrease.
Only if we are using the cable-ring environment So far I think using 0.8 or higher might be too hard because moving the ring to the target can cause other areas to decrease.
[ "Only", "if", "we", "are", "using", "the", "cable", "-", "ring", "environment", "So", "far", "I", "think", "using", "0", ".", "8", "or", "higher", "might", "be", "too", "hard", "because", "moving", "the", "ring", "to", "the", "target", "can", "cause", ...
def area_thresh(self): return 0.75
[ "def", "area_thresh", "(", "self", ")", ":", "return", "0.75" ]
Only if we are using the cable-ring environment...
[ "Only", "if", "we", "are", "using", "the", "cable", "-", "ring", "environment", "..." ]
[ "\"\"\"Only if we are using the cable-ring environment...\n\n So far I think using 0.8 or higher might be too hard because moving\n the ring to the target can cause other areas to decrease.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
34f37ec93172cf68794b7788dbe41e68d9959cf8
gautams3/deformable-ravens
ravens/tasks/defs_cables.py
[ "Apache-2.0" ]
Python
reset
null
def reset(self, env, last_info=None): """Reset to start an episode. If generating training data for goal-conditioned Transporters with `main.py` or goal images using `generate_goals.py`, then call the superclass. The code already puts the bead poses inside `info`. For this env i...
Reset to start an episode. If generating training data for goal-conditioned Transporters with `main.py` or goal images using `generate_goals.py`, then call the superclass. The code already puts the bead poses inside `info`. For this env it's IDs 4 through 27 (for 24 beads) but I scale i...
Reset to start an episode. If generating training data for goal-conditioned Transporters with `main.py` or goal images using `generate_goals.py`, then call the superclass. The code already puts the bead poses inside `info`. For this env it's IDs 4 through 27 (for 24 beads) but I scale it based on num_parts in case we c...
[ "Reset", "to", "start", "an", "episode", ".", "If", "generating", "training", "data", "for", "goal", "-", "conditioned", "Transporters", "with", "`", "main", ".", "py", "`", "or", "goal", "images", "using", "`", "generate_goals", ".", "py", "`", "then", ...
def reset(self, env, last_info=None): super().reset(env) if self.goal_cond_testing: assert last_info is not None self.goal['places'] = self._get_goal_info(last_info)
[ "def", "reset", "(", "self", ",", "env", ",", "last_info", "=", "None", ")", ":", "super", "(", ")", ".", "reset", "(", "env", ")", "if", "self", ".", "goal_cond_testing", ":", "assert", "last_info", "is", "not", "None", "self", ".", "goal", "[", "...
Reset to start an episode.
[ "Reset", "to", "start", "an", "episode", "." ]
[ "\"\"\"Reset to start an episode.\n\n If generating training data for goal-conditioned Transporters with\n `main.py` or goal images using `generate_goals.py`, then call the\n superclass. The code already puts the bead poses inside `info`. For\n this env it's IDs 4 through 27 (for 24 bead...
[ { "param": "self", "type": null }, { "param": "env", "type": null }, { "param": "last_info", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": []...
34f37ec93172cf68794b7788dbe41e68d9959cf8
gautams3/deformable-ravens
ravens/tasks/defs_cables.py
[ "Apache-2.0" ]
Python
_get_goal_info
<not_specific>
def _get_goal_info(self, last_info): """Used to determine the goal given the last `info` dict.""" start_ID = 4 end_ID = start_ID + self.num_parts places = {} for ID in range(start_ID, end_ID): assert ID in last_info, f'something went wrong with ID={ID}' po...
Used to determine the goal given the last `info` dict.
Used to determine the goal given the last `info` dict.
[ "Used", "to", "determine", "the", "goal", "given", "the", "last", "`", "info", "`", "dict", "." ]
def _get_goal_info(self, last_info): start_ID = 4 end_ID = start_ID + self.num_parts places = {} for ID in range(start_ID, end_ID): assert ID in last_info, f'something went wrong with ID={ID}' position, _, _ = last_info[ID] places[ID] = (position, (0, ...
[ "def", "_get_goal_info", "(", "self", ",", "last_info", ")", ":", "start_ID", "=", "4", "end_ID", "=", "start_ID", "+", "self", ".", "num_parts", "places", "=", "{", "}", "for", "ID", "in", "range", "(", "start_ID", ",", "end_ID", ")", ":", "assert", ...
Used to determine the goal given the last `info` dict.
[ "Used", "to", "determine", "the", "goal", "given", "the", "last", "`", "info", "`", "dict", "." ]
[ "\"\"\"Used to determine the goal given the last `info` dict.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "last_info", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "last_info", "type": null, "docstring": null, "docstring_token...
cb75751c2dd46752fb45c7d29f397d2f9b0239f7
gautams3/deformable-ravens
ravens/utils.py
[ "Apache-2.0" ]
Python
transform_pointcloud
<not_specific>
def transform_pointcloud(points, transform): """Apply rigid transformation to 3D pointcloud. Args: points: HxWx3 float array of 3D points in camera coordinates. transform: 4x4 float array representing a rigid transformation matrix. Returns: points: HxWx3 float array of transformed 3D poi...
Apply rigid transformation to 3D pointcloud. Args: points: HxWx3 float array of 3D points in camera coordinates. transform: 4x4 float array representing a rigid transformation matrix. Returns: points: HxWx3 float array of transformed 3D points.
Apply rigid transformation to 3D pointcloud.
[ "Apply", "rigid", "transformation", "to", "3D", "pointcloud", "." ]
def transform_pointcloud(points, transform): padding = ((0, 0), (0, 0), (0, 1)) homogen_points = np.pad(points.copy(), padding, 'constant', constant_values=1) for i in range(3): points[..., i] = np.sum(transform[i, :] * homogen_points, axis=-1) return points
[ "def", "transform_pointcloud", "(", "points", ",", "transform", ")", ":", "padding", "=", "(", "(", "0", ",", "0", ")", ",", "(", "0", ",", "0", ")", ",", "(", "0", ",", "1", ")", ")", "homogen_points", "=", "np", ".", "pad", "(", "points", "."...
Apply rigid transformation to 3D pointcloud.
[ "Apply", "rigid", "transformation", "to", "3D", "pointcloud", "." ]
[ "\"\"\"Apply rigid transformation to 3D pointcloud.\n\n Args:\n points: HxWx3 float array of 3D points in camera coordinates.\n transform: 4x4 float array representing a rigid transformation matrix.\n\n Returns:\n points: HxWx3 float array of transformed 3D points.\n \"\"\"" ]
[ { "param": "points", "type": null }, { "param": "transform", "type": null } ]
{ "returns": [ { "docstring": "HxWx3 float array of transformed 3D points.", "docstring_tokens": [ "HxWx3", "float", "array", "of", "transformed", "3D", "points", "." ], "type": "points" } ], "raises": [], "params": ...
cb75751c2dd46752fb45c7d29f397d2f9b0239f7
gautams3/deformable-ravens
ravens/utils.py
[ "Apache-2.0" ]
Python
reconstruct_heightmaps
<not_specific>
def reconstruct_heightmaps(color, depth, configs, bounds, pixel_size): """Reconstruct top-down heightmap views from multiple 3D pointclouds. The color and depth are np.arrays or lists, where the leading dimension or list wraps around differnet viewpoints. So, if the np.array shape is (3,480,640,3), the...
Reconstruct top-down heightmap views from multiple 3D pointclouds. The color and depth are np.arrays or lists, where the leading dimension or list wraps around differnet viewpoints. So, if the np.array shape is (3,480,640,3), then the leading '3' denotes the number of camera views. TODO: documentation...
Reconstruct top-down heightmap views from multiple 3D pointclouds. The color and depth are np.arrays or lists, where the leading dimension or list wraps around differnet viewpoints. So, if the np.array shape is (3,480,640,3), then the leading '3' denotes the number of camera views. documentation.
[ "Reconstruct", "top", "-", "down", "heightmap", "views", "from", "multiple", "3D", "pointclouds", ".", "The", "color", "and", "depth", "are", "np", ".", "arrays", "or", "lists", "where", "the", "leading", "dimension", "or", "list", "wraps", "around", "differ...
def reconstruct_heightmaps(color, depth, configs, bounds, pixel_size): heightmaps, colormaps = [], [] for color, depth, config in zip(color, depth, configs): intrinsics = np.array(config['intrinsics']).reshape(3, 3) xyz = get_pointcloud(depth, intrinsics) position = np.array(config['posi...
[ "def", "reconstruct_heightmaps", "(", "color", ",", "depth", ",", "configs", ",", "bounds", ",", "pixel_size", ")", ":", "heightmaps", ",", "colormaps", "=", "[", "]", ",", "[", "]", "for", "color", ",", "depth", ",", "config", "in", "zip", "(", "color...
Reconstruct top-down heightmap views from multiple 3D pointclouds.
[ "Reconstruct", "top", "-", "down", "heightmap", "views", "from", "multiple", "3D", "pointclouds", "." ]
[ "\"\"\"Reconstruct top-down heightmap views from multiple 3D pointclouds.\n\n The color and depth are np.arrays or lists, where the leading dimension\n or list wraps around differnet viewpoints. So, if the np.array shape is\n (3,480,640,3), then the leading '3' denotes the number of camera views.\n\n TO...
[ { "param": "color", "type": null }, { "param": "depth", "type": null }, { "param": "configs", "type": null }, { "param": "bounds", "type": null }, { "param": "pixel_size", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "color", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "depth", "type": null, "docstring": null, "docstring_tokens":...
cb75751c2dd46752fb45c7d29f397d2f9b0239f7
gautams3/deformable-ravens
ravens/utils.py
[ "Apache-2.0" ]
Python
pixel_to_position
<not_specific>
def pixel_to_position(pixel, height, bounds, pixel_size, skip_height=False): """Convert from pixel location on heightmap to 3D position.""" u, v = pixel x = bounds[0, 0] + v * pixel_size y = bounds[1, 0] + u * pixel_size if not skip_height: z = bounds[2, 0] + height[u, v] else: z...
Convert from pixel location on heightmap to 3D position.
Convert from pixel location on heightmap to 3D position.
[ "Convert", "from", "pixel", "location", "on", "heightmap", "to", "3D", "position", "." ]
def pixel_to_position(pixel, height, bounds, pixel_size, skip_height=False): u, v = pixel x = bounds[0, 0] + v * pixel_size y = bounds[1, 0] + u * pixel_size if not skip_height: z = bounds[2, 0] + height[u, v] else: z = 0.0 return (x, y, z)
[ "def", "pixel_to_position", "(", "pixel", ",", "height", ",", "bounds", ",", "pixel_size", ",", "skip_height", "=", "False", ")", ":", "u", ",", "v", "=", "pixel", "x", "=", "bounds", "[", "0", ",", "0", "]", "+", "v", "*", "pixel_size", "y", "=", ...
Convert from pixel location on heightmap to 3D position.
[ "Convert", "from", "pixel", "location", "on", "heightmap", "to", "3D", "position", "." ]
[ "\"\"\"Convert from pixel location on heightmap to 3D position.\"\"\"" ]
[ { "param": "pixel", "type": null }, { "param": "height", "type": null }, { "param": "bounds", "type": null }, { "param": "pixel_size", "type": null }, { "param": "skip_height", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "pixel", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "height", "type": null, "docstring": null, "docstring_tokens"...
cb75751c2dd46752fb45c7d29f397d2f9b0239f7
gautams3/deformable-ravens
ravens/utils.py
[ "Apache-2.0" ]
Python
position_to_pixel
<not_specific>
def position_to_pixel(position, bounds, pixel_size): """Convert from 3D position to pixel location on heightmap.""" u = int(np.round((position[1] - bounds[1, 0]) / pixel_size)) v = int(np.round((position[0] - bounds[0, 0]) / pixel_size)) return (u, v)
Convert from 3D position to pixel location on heightmap.
Convert from 3D position to pixel location on heightmap.
[ "Convert", "from", "3D", "position", "to", "pixel", "location", "on", "heightmap", "." ]
def position_to_pixel(position, bounds, pixel_size): u = int(np.round((position[1] - bounds[1, 0]) / pixel_size)) v = int(np.round((position[0] - bounds[0, 0]) / pixel_size)) return (u, v)
[ "def", "position_to_pixel", "(", "position", ",", "bounds", ",", "pixel_size", ")", ":", "u", "=", "int", "(", "np", ".", "round", "(", "(", "position", "[", "1", "]", "-", "bounds", "[", "1", ",", "0", "]", ")", "/", "pixel_size", ")", ")", "v",...
Convert from 3D position to pixel location on heightmap.
[ "Convert", "from", "3D", "position", "to", "pixel", "location", "on", "heightmap", "." ]
[ "\"\"\"Convert from 3D position to pixel location on heightmap.\"\"\"" ]
[ { "param": "position", "type": null }, { "param": "bounds", "type": null }, { "param": "pixel_size", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "position", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "bounds", "type": null, "docstring": null, "docstring_toke...
cb75751c2dd46752fb45c7d29f397d2f9b0239f7
gautams3/deformable-ravens
ravens/utils.py
[ "Apache-2.0" ]
Python
unproject_vectorized
np.ndarray
def unproject_vectorized(uv_coordinates: np.ndarray, depth_values: np.ndarray, intrinsic: np.ndarray, distortion: np.ndarray) -> np.ndarray: """Vectorized version of unproject(), for N points. Args: uv_coordinates: pixel coordinates to unproject of shape (n, 2)...
Vectorized version of unproject(), for N points. Args: uv_coordinates: pixel coordinates to unproject of shape (n, 2). depth_values: depth values corresponding index-wise to the uv_coordinates of shape (n). intrinsic: array of shape (3, 3). This is typically the return value of intrinsics_to_...
Vectorized version of unproject(), for N points.
[ "Vectorized", "version", "of", "unproject", "()", "for", "N", "points", "." ]
def unproject_vectorized(uv_coordinates: np.ndarray, depth_values: np.ndarray, intrinsic: np.ndarray, distortion: np.ndarray) -> np.ndarray: cam_mtx = intrinsic cam_dist = np.array(distortion) points_undistorted = cv2.undistortPoints( uv_coordinates.resh...
[ "def", "unproject_vectorized", "(", "uv_coordinates", ":", "np", ".", "ndarray", ",", "depth_values", ":", "np", ".", "ndarray", ",", "intrinsic", ":", "np", ".", "ndarray", ",", "distortion", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", "...
Vectorized version of unproject(), for N points.
[ "Vectorized", "version", "of", "unproject", "()", "for", "N", "points", "." ]
[ "\"\"\"Vectorized version of unproject(), for N points.\n\n Args:\n uv_coordinates: pixel coordinates to unproject of shape (n, 2).\n depth_values: depth values corresponding index-wise to the uv_coordinates of\n shape (n).\n intrinsic: array of shape (3, 3). This is typically the return value\n ...
[ { "param": "uv_coordinates", "type": "np.ndarray" }, { "param": "depth_values", "type": "np.ndarray" }, { "param": "intrinsic", "type": "np.ndarray" }, { "param": "distortion", "type": "np.ndarray" } ]
{ "returns": [ { "docstring": "xyz coordinates in camera frame of shape (n, 3).", "docstring_tokens": [ "xyz", "coordinates", "in", "camera", "frame", "of", "shape", "(", "n", "3", ")", "." ], "...
cb75751c2dd46752fb45c7d29f397d2f9b0239f7
gautams3/deformable-ravens
ravens/utils.py
[ "Apache-2.0" ]
Python
unproject_depth_vectorized
np.ndarray
def unproject_depth_vectorized(im_depth: np.ndarray, depth_dist: np.ndarray, camera_mtx: np.ndarray, camera_dist: np.ndarray) -> np.ndarray: """Unproject depth image into 3D point cloud, using calibration. Args: im_depth: raw depth image, pre-calibr...
Unproject depth image into 3D point cloud, using calibration. Args: im_depth: raw depth image, pre-calibration of shape (height, width). depth_dist: depth distortion parameters of shape (8,) camera_mtx: intrinsics matrix of shape (3, 3). This is typically the return value of intrinsics_to_matrix. ...
Unproject depth image into 3D point cloud, using calibration.
[ "Unproject", "depth", "image", "into", "3D", "point", "cloud", "using", "calibration", "." ]
def unproject_depth_vectorized(im_depth: np.ndarray, depth_dist: np.ndarray, camera_mtx: np.ndarray, camera_dist: np.ndarray) -> np.ndarray: h, w = im_depth.shape u_map, v_map = np.meshgrid(np.linspace(0, w - 1, w), np.linspace(0, h - 1, h)) adjusted_d...
[ "def", "unproject_depth_vectorized", "(", "im_depth", ":", "np", ".", "ndarray", ",", "depth_dist", ":", "np", ".", "ndarray", ",", "camera_mtx", ":", "np", ".", "ndarray", ",", "camera_dist", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", "...
Unproject depth image into 3D point cloud, using calibration.
[ "Unproject", "depth", "image", "into", "3D", "point", "cloud", "using", "calibration", "." ]
[ "\"\"\"Unproject depth image into 3D point cloud, using calibration.\n\n Args:\n im_depth: raw depth image, pre-calibration of shape (height, width).\n depth_dist: depth distortion parameters of shape (8,)\n camera_mtx: intrinsics matrix of shape (3, 3). This is typically the return\n value of intrin...
[ { "param": "im_depth", "type": "np.ndarray" }, { "param": "depth_dist", "type": "np.ndarray" }, { "param": "camera_mtx", "type": "np.ndarray" }, { "param": "camera_dist", "type": "np.ndarray" } ]
{ "returns": [ { "docstring": "numpy array of shape [3, H*W]. each column is xyz coordinates", "docstring_tokens": [ "numpy", "array", "of", "shape", "[", "3", "H", "*", "W", "]", ".", "each", "colu...
cb75751c2dd46752fb45c7d29f397d2f9b0239f7
gautams3/deformable-ravens
ravens/utils.py
[ "Apache-2.0" ]
Python
sample_distribution
<not_specific>
def sample_distribution(prob, n_samples=1): """Sample data point from a custom distribution.""" flat_prob = np.ndarray.flatten(prob) / np.sum(prob) rand_ind = np.random.choice( np.arange(len(flat_prob)), n_samples, p=flat_prob, replace=False) rand_ind_coords = np.array(np.unravel_index(rand_ind,...
Sample data point from a custom distribution.
Sample data point from a custom distribution.
[ "Sample", "data", "point", "from", "a", "custom", "distribution", "." ]
def sample_distribution(prob, n_samples=1): flat_prob = np.ndarray.flatten(prob) / np.sum(prob) rand_ind = np.random.choice( np.arange(len(flat_prob)), n_samples, p=flat_prob, replace=False) rand_ind_coords = np.array(np.unravel_index(rand_ind, prob.shape)).T return np.int32(rand_ind_coords.sque...
[ "def", "sample_distribution", "(", "prob", ",", "n_samples", "=", "1", ")", ":", "flat_prob", "=", "np", ".", "ndarray", ".", "flatten", "(", "prob", ")", "/", "np", ".", "sum", "(", "prob", ")", "rand_ind", "=", "np", ".", "random", ".", "choice", ...
Sample data point from a custom distribution.
[ "Sample", "data", "point", "from", "a", "custom", "distribution", "." ]
[ "\"\"\"Sample data point from a custom distribution.\"\"\"" ]
[ { "param": "prob", "type": null }, { "param": "n_samples", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "prob", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "n_samples", "type": null, "docstring": null, "docstring_token...
cb75751c2dd46752fb45c7d29f397d2f9b0239f7
gautams3/deformable-ravens
ravens/utils.py
[ "Apache-2.0" ]
Python
check_transform
<not_specific>
def check_transform(image, pixel, transform): """Valid transform only if pixel locations are still in FoV after transform.""" new_pixel = np.flip(np.int32(np.round(np.dot(transform, np.float32( [pixel[1], pixel[0], 1.]).reshape(3, 1))))[:2].squeeze()) valid = np.all(new_pixel >= 0) and new_pixel[0] ...
Valid transform only if pixel locations are still in FoV after transform.
Valid transform only if pixel locations are still in FoV after transform.
[ "Valid", "transform", "only", "if", "pixel", "locations", "are", "still", "in", "FoV", "after", "transform", "." ]
def check_transform(image, pixel, transform): new_pixel = np.flip(np.int32(np.round(np.dot(transform, np.float32( [pixel[1], pixel[0], 1.]).reshape(3, 1))))[:2].squeeze()) valid = np.all(new_pixel >= 0) and new_pixel[0] < image.shape[ 0] and new_pixel[1] < image.shape[1] return valid, new_pi...
[ "def", "check_transform", "(", "image", ",", "pixel", ",", "transform", ")", ":", "new_pixel", "=", "np", ".", "flip", "(", "np", ".", "int32", "(", "np", ".", "round", "(", "np", ".", "dot", "(", "transform", ",", "np", ".", "float32", "(", "[", ...
Valid transform only if pixel locations are still in FoV after transform.
[ "Valid", "transform", "only", "if", "pixel", "locations", "are", "still", "in", "FoV", "after", "transform", "." ]
[ "\"\"\"Valid transform only if pixel locations are still in FoV after transform.\"\"\"" ]
[ { "param": "image", "type": null }, { "param": "pixel", "type": null }, { "param": "transform", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "image", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pixel", "type": null, "docstring": null, "docstring_tokens":...
a1d8f38472c9af4a84de9b198e8ea30a6c30c1c0
gautams3/deformable-ravens
ravens/agents/regression.py
[ "Apache-2.0" ]
Python
train
<not_specific>
def train(self, dataset, num_iter, writer): """Train on dataset for a specific number of iterations.""" @tf.function def pick_train_step(model, optim, in_tensor, yxtheta, loss_criterion): with tf.GradientTape() as tape: output = model(in_tensor) loss ...
Train on dataset for a specific number of iterations.
Train on dataset for a specific number of iterations.
[ "Train", "on", "dataset", "for", "a", "specific", "number", "of", "iterations", "." ]
def train(self, dataset, num_iter, writer): @tf.function def pick_train_step(model, optim, in_tensor, yxtheta, loss_criterion): with tf.GradientTape() as tape: output = model(in_tensor) loss = loss_criterion(yxtheta, output) grad = tape.gradient(lo...
[ "def", "train", "(", "self", ",", "dataset", ",", "num_iter", ",", "writer", ")", ":", "@", "tf", ".", "function", "def", "pick_train_step", "(", "model", ",", "optim", ",", "in_tensor", ",", "yxtheta", ",", "loss_criterion", ")", ":", "with", "tf", "....
Train on dataset for a specific number of iterations.
[ "Train", "on", "dataset", "for", "a", "specific", "number", "of", "iterations", "." ]
[ "\"\"\"Train on dataset for a specific number of iterations.\"\"\"", "# Get heightmap from RGB-D images.", "#self.show_images(colormap, heightmap)", "# Get training labels from data sample.", "# (spatially distributed on object) get actions from oracle distribution", "#pose0, pose1 = act['params']['pose0'...
[ { "param": "self", "type": null }, { "param": "dataset", "type": null }, { "param": "num_iter", "type": null }, { "param": "writer", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "dataset", "type": null, "docstring": null, "docstring_tokens"...
a1d8f38472c9af4a84de9b198e8ea30a6c30c1c0
gautams3/deformable-ravens
ravens/agents/regression.py
[ "Apache-2.0" ]
Python
act
<not_specific>
def act(self, obs, info): """Run inference and return best action given visual observations.""" self.pick_regression_model.set_batch_size(1) self.place_regression_model.set_batch_size(1) act = {'camera_config': self.camera_config, 'primitive': None} if not obs: return...
Run inference and return best action given visual observations.
Run inference and return best action given visual observations.
[ "Run", "inference", "and", "return", "best", "action", "given", "visual", "observations", "." ]
def act(self, obs, info): self.pick_regression_model.set_batch_size(1) self.place_regression_model.set_batch_size(1) act = {'camera_config': self.camera_config, 'primitive': None} if not obs: return act colormap, heightmap = self.get_heightmap(obs, self.camera_config)...
[ "def", "act", "(", "self", ",", "obs", ",", "info", ")", ":", "self", ".", "pick_regression_model", ".", "set_batch_size", "(", "1", ")", "self", ".", "place_regression_model", ".", "set_batch_size", "(", "1", ")", "act", "=", "{", "'camera_config'", ":", ...
Run inference and return best action given visual observations.
[ "Run", "inference", "and", "return", "best", "action", "given", "visual", "observations", "." ]
[ "\"\"\"Run inference and return best action given visual observations.\"\"\"", "# Get heightmap from RGB-D images.", "# Concatenate color with depth images.", "# input_image = np.concatenate((colormap,", "# heightmap[..., None],", "# heightmap[.....
[ { "param": "self", "type": null }, { "param": "obs", "type": null }, { "param": "info", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "obs", "type": null, "docstring": null, "docstring_tokens": []...
0aafbd728ded3c727fb9518d2ce6a2c0e234ddaa
gautams3/deformable-ravens
ravens/models/transport_goal.py
[ "Apache-2.0" ]
Python
forward
<not_specific>
def forward(self, in_img, goal_img, p, apply_softmax=True): """Forward pass of our goal-conditioned Transporter. Relevant shapes and info: in_img and goal_img: (320,160,6) p: integer pixels on in_img, e.g., [158, 30] self.padding: [[32,32],[32,32],0,0]], with shape ...
Forward pass of our goal-conditioned Transporter. Relevant shapes and info: in_img and goal_img: (320,160,6) p: integer pixels on in_img, e.g., [158, 30] self.padding: [[32,32],[32,32],0,0]], with shape (3,2) Run input through all three networks, to get output of t...
Forward pass of our goal-conditioned Transporter. Relevant shapes and info. Run input through all three networks, to get output of the same shape, except that the last channel is 3 (output_dim). Then, the output for one stream has the convolutional kernels for another. I actually think cropping after the query netw...
[ "Forward", "pass", "of", "our", "goal", "-", "conditioned", "Transporter", ".", "Relevant", "shapes", "and", "info", ".", "Run", "input", "through", "all", "three", "networks", "to", "get", "output", "of", "the", "same", "shape", "except", "that", "the", "...
def forward(self, in_img, goal_img, p, apply_softmax=True): assert in_img.shape == goal_img.shape, f'{in_img.shape}, {goal_img.shape}' input_unproc = np.pad(in_img, self.padding, mode='constant') input_data = self.preprocess(input_unproc.copy()) input_shape = (1,) + in...
[ "def", "forward", "(", "self", ",", "in_img", ",", "goal_img", ",", "p", ",", "apply_softmax", "=", "True", ")", ":", "assert", "in_img", ".", "shape", "==", "goal_img", ".", "shape", ",", "f'{in_img.shape}, {goal_img.shape}'", "input_unproc", "=", "np", "."...
Forward pass of our goal-conditioned Transporter.
[ "Forward", "pass", "of", "our", "goal", "-", "conditioned", "Transporter", "." ]
[ "\"\"\"Forward pass of our goal-conditioned Transporter.\n\n Relevant shapes and info:\n\n in_img and goal_img: (320,160,6)\n p: integer pixels on in_img, e.g., [158, 30]\n self.padding: [[32,32],[32,32],0,0]], with shape (3,2)\n\n Run input through all three networks,...
[ { "param": "self", "type": null }, { "param": "in_img", "type": null }, { "param": "goal_img", "type": null }, { "param": "p", "type": null }, { "param": "apply_softmax", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "in_img", "type": null, "docstring": null, "docstring_tokens":...
0aafbd728ded3c727fb9518d2ce6a2c0e234ddaa
gautams3/deformable-ravens
ravens/models/transport_goal.py
[ "Apache-2.0" ]
Python
visualize_logits
null
def visualize_logits(self, logits, name): """Given logits (BEFORE tf.nn.convolution), get a heatmap. Here we apply a softmax to make it more human-readable. However, the tf.nn.convolution with the learned kernels happens without a softmax on the logits. [Update: wait, then why should we...
Given logits (BEFORE tf.nn.convolution), get a heatmap. Here we apply a softmax to make it more human-readable. However, the tf.nn.convolution with the learned kernels happens without a softmax on the logits. [Update: wait, then why should we have a softmax, then? I forgot why we did th...
Given logits (BEFORE tf.nn.convolution), get a heatmap. Here we apply a softmax to make it more human-readable. However, the tf.nn.convolution with the learned kernels happens without a softmax on the logits. [Update: wait, then why should we have a softmax, then. I forgot why we did this ...]
[ "Given", "logits", "(", "BEFORE", "tf", ".", "nn", ".", "convolution", ")", "get", "a", "heatmap", ".", "Here", "we", "apply", "a", "softmax", "to", "make", "it", "more", "human", "-", "readable", ".", "However", "the", "tf", ".", "nn", ".", "convolu...
def visualize_logits(self, logits, name): original_shape = logits.shape logits = tf.reshape(logits, (1, np.prod(original_shape))) vis_transport = np.float32(logits).reshape(original_shape) vis_transport = vis_transport[0] vis_transport = vis_transport - np.min(vis_transport) ...
[ "def", "visualize_logits", "(", "self", ",", "logits", ",", "name", ")", ":", "original_shape", "=", "logits", ".", "shape", "logits", "=", "tf", ".", "reshape", "(", "logits", ",", "(", "1", ",", "np", ".", "prod", "(", "original_shape", ")", ")", "...
Given logits (BEFORE tf.nn.convolution), get a heatmap.
[ "Given", "logits", "(", "BEFORE", "tf", ".", "nn", ".", "convolution", ")", "get", "a", "heatmap", "." ]
[ "\"\"\"Given logits (BEFORE tf.nn.convolution), get a heatmap.\n\n Here we apply a softmax to make it more human-readable. However, the\n tf.nn.convolution with the learned kernels happens without a softmax\n on the logits. [Update: wait, then why should we have a softmax,\n then? I forg...
[ { "param": "self", "type": null }, { "param": "logits", "type": null }, { "param": "name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "logits", "type": null, "docstring": null, "docstring_tokens":...
5b9dd52f7225cee1ee08ef3b0e7fc62d4576b9e7
gautams3/deformable-ravens
ravens/models/resnet.py
[ "Apache-2.0" ]
Python
identity_block
<not_specific>
def identity_block(input_tensor, kernel_size, filters, stage, block, activation=True, include_batchnorm=False): """The identity block is the block that has no conv layer at shortcut. # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer ...
The identity block is the block that has no conv layer at shortcut. # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the filters of 3 conv layer at main path stage: integer, curren...
The identity block is the block that has no conv layer at shortcut. Returns Output tensor for the block.
[ "The", "identity", "block", "is", "the", "block", "that", "has", "no", "conv", "layer", "at", "shortcut", ".", "Returns", "Output", "tensor", "for", "the", "block", "." ]
def identity_block(input_tensor, kernel_size, filters, stage, block, activation=True, include_batchnorm=False): filters1, filters2, filters3 = filters batchnorm_axis = 3 conv_name_base = 'res' + str(stage) + block + '_branch' bn_name_base = 'bn' + str(stage) + block + '_branch' x = tf.keras.layers.C...
[ "def", "identity_block", "(", "input_tensor", ",", "kernel_size", ",", "filters", ",", "stage", ",", "block", ",", "activation", "=", "True", ",", "include_batchnorm", "=", "False", ")", ":", "filters1", ",", "filters2", ",", "filters3", "=", "filters", "bat...
The identity block is the block that has no conv layer at shortcut.
[ "The", "identity", "block", "is", "the", "block", "that", "has", "no", "conv", "layer", "at", "shortcut", "." ]
[ "\"\"\"The identity block is the block that has no conv layer at shortcut.\n\n # Arguments\n input_tensor: input tensor\n kernel_size: default 3, the kernel size of\n middle conv layer at main path\n filters: list of integers, the filters of 3 conv layer at main path\n stag...
[ { "param": "input_tensor", "type": null }, { "param": "kernel_size", "type": null }, { "param": "filters", "type": null }, { "param": "stage", "type": null }, { "param": "block", "type": null }, { "param": "activation", "type": null }, { "p...
{ "returns": [], "raises": [], "params": [ { "identifier": "input_tensor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "kernel_size", "type": null, "docstring": null, "docst...
5b9dd52f7225cee1ee08ef3b0e7fc62d4576b9e7
gautams3/deformable-ravens
ravens/models/resnet.py
[ "Apache-2.0" ]
Python
ResNet43_8s
<not_specific>
def ResNet43_8s(input_shape, output_dim, include_batchnorm=False, batchnorm_axis=3, prefix='', cutoff_early=False): """Daniel: produces an hourglass FCN network, adapted to CoRL submission size. Regarding shapes, look at: https://www.tensorflow.org/api_docs/python/tf/keras/Input [excludes batch size] Here ...
Daniel: produces an hourglass FCN network, adapted to CoRL submission size. Regarding shapes, look at: https://www.tensorflow.org/api_docs/python/tf/keras/Input [excludes batch size] Here are the shape patterns, where I print shapes for the input, and after each conv_block or Conv2D call. Attention: (...
produces an hourglass FCN network, adapted to CoRL submission size. Transport, query module, assumes cropping beforehand. Here I ignore output after identity blocks, which produce tensors of the same size. Parameters
[ "produces", "an", "hourglass", "FCN", "network", "adapted", "to", "CoRL", "submission", "size", ".", "Transport", "query", "module", "assumes", "cropping", "beforehand", ".", "Here", "I", "ignore", "output", "after", "identity", "blocks", "which", "produce", "te...
def ResNet43_8s(input_shape, output_dim, include_batchnorm=False, batchnorm_axis=3, prefix='', cutoff_early=False): input_data = tf.keras.layers.Input(shape=input_shape) x = tf.keras.layers.Conv2D(64, (3, 3), strides=(1, 1), padding='same', kernel_initializer='glorot_uniform', name=prefix + 'conv1')(input_data)...
[ "def", "ResNet43_8s", "(", "input_shape", ",", "output_dim", ",", "include_batchnorm", "=", "False", ",", "batchnorm_axis", "=", "3", ",", "prefix", "=", "''", ",", "cutoff_early", "=", "False", ")", ":", "input_data", "=", "tf", ".", "keras", ".", "layers...
Daniel: produces an hourglass FCN network, adapted to CoRL submission size.
[ "Daniel", ":", "produces", "an", "hourglass", "FCN", "network", "adapted", "to", "CoRL", "submission", "size", "." ]
[ "\"\"\"Daniel: produces an hourglass FCN network, adapted to CoRL submission size.\n\n Regarding shapes, look at: https://www.tensorflow.org/api_docs/python/tf/keras/Input [excludes batch size]\n Here are the shape patterns, where I print shapes for the input, and after each conv_block or Conv2D call.\n\n ...
[ { "param": "input_shape", "type": null }, { "param": "output_dim", "type": null }, { "param": "include_batchnorm", "type": null }, { "param": "batchnorm_axis", "type": null }, { "param": "prefix", "type": null }, { "param": "cutoff_early", "type": ...
{ "returns": [], "raises": [], "params": [ { "identifier": "input_shape", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "output_dim", "type": null, "docstring": null, "docstri...
a793edf751328666028af50cf3fa666f38d140d3
gautams3/deformable-ravens
ravens/dataset.py
[ "Apache-2.0" ]
Python
_change_name
<not_specific>
def _change_name(self, suff, info_extra): """Depending on the env, make changes to image suffix `suff`.""" if 'cable-ring' in self.path: i1 = info_extra['convex_hull_area'] i2 = info_extra['best_possible_area'] f = i1 / i2 suff = suff.replace('.png', ...
Depending on the env, make changes to image suffix `suff`.
Depending on the env, make changes to image suffix `suff`.
[ "Depending", "on", "the", "env", "make", "changes", "to", "image", "suffix", "`", "suff", "`", "." ]
def _change_name(self, suff, info_extra): if 'cable-ring' in self.path: i1 = info_extra['convex_hull_area'] i2 = info_extra['best_possible_area'] f = i1 / i2 suff = suff.replace('.png', f'-area-{i1:0.3f}-best-{i2:0.3f}-FRAC-{f:0.3f}.png') ...
[ "def", "_change_name", "(", "self", ",", "suff", ",", "info_extra", ")", ":", "if", "'cable-ring'", "in", "self", ".", "path", ":", "i1", "=", "info_extra", "[", "'convex_hull_area'", "]", "i2", "=", "info_extra", "[", "'best_possible_area'", "]", "f", "="...
Depending on the env, make changes to image suffix `suff`.
[ "Depending", "on", "the", "env", "make", "changes", "to", "image", "suffix", "`", "suff", "`", "." ]
[ "\"\"\"Depending on the env, make changes to image suffix `suff`.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "suff", "type": null }, { "param": "info_extra", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "suff", "type": null, "docstring": null, "docstring_tokens": [...
a793edf751328666028af50cf3fa666f38d140d3
gautams3/deformable-ravens
ravens/dataset.py
[ "Apache-2.0" ]
Python
_save_images
null
def _save_images(self, episode_len, color_l, depth_l, info_l, outdir, i_ep): """For each item (timestep) in this episode, save relevant images.""" for t in range(episode_len): assert color_l[t].shape == (3, 480, 640, 3), color_l[t].shape assert depth_l[t].shape == (3, 480, 640),...
For each item (timestep) in this episode, save relevant images.
For each item (timestep) in this episode, save relevant images.
[ "For", "each", "item", "(", "timestep", ")", "in", "this", "episode", "save", "relevant", "images", "." ]
def _save_images(self, episode_len, color_l, depth_l, info_l, outdir, i_ep): for t in range(episode_len): assert color_l[t].shape == (3, 480, 640, 3), color_l[t].shape assert depth_l[t].shape == (3, 480, 640), depth_l[t].shape info = info_l[t] info_r = info['extra...
[ "def", "_save_images", "(", "self", ",", "episode_len", ",", "color_l", ",", "depth_l", ",", "info_l", ",", "outdir", ",", "i_ep", ")", ":", "for", "t", "in", "range", "(", "episode_len", ")", ":", "assert", "color_l", "[", "t", "]", ".", "shape", "=...
For each item (timestep) in this episode, save relevant images.
[ "For", "each", "item", "(", "timestep", ")", "in", "this", "episode", "save", "relevant", "images", "." ]
[ "\"\"\"For each item (timestep) in this episode, save relevant images.\"\"\"", "# Recall that I added 'extras' to the info dict at each time.", "# We saved three color/depth images per time step.", "# Andy uses U.reconstruct_heightmap(color, depth, configs, ...)", "# Save image that combines the interesting...
[ { "param": "self", "type": null }, { "param": "episode_len", "type": null }, { "param": "color_l", "type": null }, { "param": "depth_l", "type": null }, { "param": "info_l", "type": null }, { "param": "outdir", "type": null }, { "param": "i...
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "episode_len", "type": null, "docstring": null, "docstring_tok...
6407ae1b005c3df54361642a0c9341bdab9e01b5
gautams3/deformable-ravens
ravens/tasks/defs_cloth.py
[ "Apache-2.0" ]
Python
compute_pixel_IoU_coverage
<not_specific>
def compute_pixel_IoU_coverage(self): """Computes IoU and coverage based on pixels. Use: `self.target_hull` and `self.current_hull`. For the former: values of 255 refer to the area contained within the zone (and includes the zone itself, FWIW). For the latter: segment to detect ...
Computes IoU and coverage based on pixels. Use: `self.target_hull` and `self.current_hull`. For the former: values of 255 refer to the area contained within the zone (and includes the zone itself, FWIW). For the latter: segment to detect the workspace OR the zone ID. Then use numpy and/...
Computes IoU and coverage based on pixels. NOTE I: assumes cloth can be segmented by detecting the workspace and zone lines, and that any pixel OTHER than those belongs to cloth. NOTE II: IoU and coverage are computed in the same way, except that the former divides by the union, the latter divides by just the goal.
[ "Computes", "IoU", "and", "coverage", "based", "on", "pixels", ".", "NOTE", "I", ":", "assumes", "cloth", "can", "be", "segmented", "by", "detecting", "the", "workspace", "and", "zone", "lines", "and", "that", "any", "pixel", "OTHER", "than", "those", "bel...
def compute_pixel_IoU_coverage(self): _, _, object_mask = self.get_object_masks(self.env) IDs = [1, self.zone_ID] mask = np.isin(object_mask, test_elements=IDs) idx_0s = (mask == 0) idx_1s = (mask == 1) mask[idx_0s] = 1 mask[idx_1s] = 0 cloth_mask_bool =...
[ "def", "compute_pixel_IoU_coverage", "(", "self", ")", ":", "_", ",", "_", ",", "object_mask", "=", "self", ".", "get_object_masks", "(", "self", ".", "env", ")", "IDs", "=", "[", "1", ",", "self", ".", "zone_ID", "]", "mask", "=", "np", ".", "isin",...
Computes IoU and coverage based on pixels.
[ "Computes", "IoU", "and", "coverage", "based", "on", "pixels", "." ]
[ "\"\"\"Computes IoU and coverage based on pixels.\n\n Use: `self.target_hull` and `self.current_hull`. For the former:\n values of 255 refer to the area contained within the zone (and\n includes the zone itself, FWIW). For the latter: segment to detect\n the workspace OR the zone ID. The...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
6407ae1b005c3df54361642a0c9341bdab9e01b5
gautams3/deformable-ravens
ravens/tasks/defs_cloth.py
[ "Apache-2.0" ]
Python
is_item_covered
<not_specific>
def is_item_covered(self): """For cloth-cover, if it's covered, it should NOT be in the mask.""" _, _, object_mask = self.get_object_masks(self.env) assert len(self.block_IDs) == 1, self.block_IDs block = self.block_IDs[0] return 1 - float(block in object_mask)
For cloth-cover, if it's covered, it should NOT be in the mask.
For cloth-cover, if it's covered, it should NOT be in the mask.
[ "For", "cloth", "-", "cover", "if", "it", "'", "s", "covered", "it", "should", "NOT", "be", "in", "the", "mask", "." ]
def is_item_covered(self): _, _, object_mask = self.get_object_masks(self.env) assert len(self.block_IDs) == 1, self.block_IDs block = self.block_IDs[0] return 1 - float(block in object_mask)
[ "def", "is_item_covered", "(", "self", ")", ":", "_", ",", "_", ",", "object_mask", "=", "self", ".", "get_object_masks", "(", "self", ".", "env", ")", "assert", "len", "(", "self", ".", "block_IDs", ")", "==", "1", ",", "self", ".", "block_IDs", "bl...
For cloth-cover, if it's covered, it should NOT be in the mask.
[ "For", "cloth", "-", "cover", "if", "it", "'", "s", "covered", "it", "should", "NOT", "be", "in", "the", "mask", "." ]
[ "\"\"\"For cloth-cover, if it's covered, it should NOT be in the mask.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
6407ae1b005c3df54361642a0c9341bdab9e01b5
gautams3/deformable-ravens
ravens/tasks/defs_cloth.py
[ "Apache-2.0" ]
Python
add_zone
null
def add_zone(self, env, zone_pose=None): """Adds a square target (green) zone. To handle goal-conditioned cloth flattening, we save `zone_pose` and provide it as input, to avoid re-sampling. This means starting cloth states are sampled at a correct distance, and that the same IoU ...
Adds a square target (green) zone. To handle goal-conditioned cloth flattening, we save `zone_pose` and provide it as input, to avoid re-sampling. This means starting cloth states are sampled at a correct distance, and that the same IoU metric can be used as the reward.
Adds a square target (green) zone. To handle goal-conditioned cloth flattening, we save `zone_pose` and provide it as input, to avoid re-sampling. This means starting cloth states are sampled at a correct distance, and that the same IoU metric can be used as the reward.
[ "Adds", "a", "square", "target", "(", "green", ")", "zone", ".", "To", "handle", "goal", "-", "conditioned", "cloth", "flattening", "we", "save", "`", "zone_pose", "`", "and", "provide", "it", "as", "input", "to", "avoid", "re", "-", "sampling", ".", "...
def add_zone(self, env, zone_pose=None): zone_template = 'assets/zone/zone-template.urdf' replace = {'LENGTH': (self._zone_scale, self._zone_scale)} zone_urdf = self.fill_template(zone_template, replace) if zone_pose is not None: self.zone_pose = zone_pose else: ...
[ "def", "add_zone", "(", "self", ",", "env", ",", "zone_pose", "=", "None", ")", ":", "zone_template", "=", "'assets/zone/zone-template.urdf'", "replace", "=", "{", "'LENGTH'", ":", "(", "self", ".", "_zone_scale", ",", "self", ".", "_zone_scale", ")", "}", ...
Adds a square target (green) zone.
[ "Adds", "a", "square", "target", "(", "green", ")", "zone", "." ]
[ "\"\"\"Adds a square target (green) zone.\n\n To handle goal-conditioned cloth flattening, we save `zone_pose` and\n provide it as input, to avoid re-sampling. This means starting cloth\n states are sampled at a correct distance, and that the same IoU\n metric can be used as the reward.\...
[ { "param": "self", "type": null }, { "param": "env", "type": null }, { "param": "zone_pose", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": []...
6407ae1b005c3df54361642a0c9341bdab9e01b5
gautams3/deformable-ravens
ravens/tasks/defs_cloth.py
[ "Apache-2.0" ]
Python
add_cloth
<not_specific>
def add_cloth(self, env, base_pos, base_orn): """Adding a cloth from an .obj file.""" cloth_id = p.loadSoftBody( fileName=self._f_cloth, basePosition=base_pos, baseOrientation=base_orn, collisionMargin=self._collisionMargin, ...
Adding a cloth from an .obj file.
Adding a cloth from an .obj file.
[ "Adding", "a", "cloth", "from", "an", ".", "obj", "file", "." ]
def add_cloth(self, env, base_pos, base_orn): cloth_id = p.loadSoftBody( fileName=self._f_cloth, basePosition=base_pos, baseOrientation=base_orn, collisionMargin=self._collisionMargin, scale=self._cloth_scale, mass=s...
[ "def", "add_cloth", "(", "self", ",", "env", ",", "base_pos", ",", "base_orn", ")", ":", "cloth_id", "=", "p", ".", "loadSoftBody", "(", "fileName", "=", "self", ".", "_f_cloth", ",", "basePosition", "=", "base_pos", ",", "baseOrientation", "=", "base_orn"...
Adding a cloth from an .obj file.
[ "Adding", "a", "cloth", "from", "an", ".", "obj", "file", "." ]
[ "\"\"\"Adding a cloth from an .obj file.\"\"\"", "# Only if using more recent PyBullet versions.", "# For tracking IDs and consistency with existing ravens code.", "# To help environment pick-place method track all deformables.", "# Sanity checks." ]
[ { "param": "self", "type": null }, { "param": "env", "type": null }, { "param": "base_pos", "type": null }, { "param": "base_orn", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": []...
6407ae1b005c3df54361642a0c9341bdab9e01b5
gautams3/deformable-ravens
ravens/tasks/defs_cloth.py
[ "Apache-2.0" ]
Python
_sample_cloth_orientation
<not_specific>
def _sample_cloth_orientation(self): """Sample the bag (and let it drop) to get interesting starting states.""" orn = [self._base_orn[0] + np.random.normal(loc=0.0, scale=self._scalex), self._base_orn[1] + np.random.normal(loc=0.0, scale=self._scaley), self._base_orn[2] + n...
Sample the bag (and let it drop) to get interesting starting states.
Sample the bag (and let it drop) to get interesting starting states.
[ "Sample", "the", "bag", "(", "and", "let", "it", "drop", ")", "to", "get", "interesting", "starting", "states", "." ]
def _sample_cloth_orientation(self): orn = [self._base_orn[0] + np.random.normal(loc=0.0, scale=self._scalex), self._base_orn[1] + np.random.normal(loc=0.0, scale=self._scaley), self._base_orn[2] + np.random.normal(loc=0.0, scale=self._scalez),] return p.getQuaternionFromEu...
[ "def", "_sample_cloth_orientation", "(", "self", ")", ":", "orn", "=", "[", "self", ".", "_base_orn", "[", "0", "]", "+", "np", ".", "random", ".", "normal", "(", "loc", "=", "0.0", ",", "scale", "=", "self", ".", "_scalex", ")", ",", "self", ".", ...
Sample the bag (and let it drop) to get interesting starting states.
[ "Sample", "the", "bag", "(", "and", "let", "it", "drop", ")", "to", "get", "interesting", "starting", "states", "." ]
[ "\"\"\"Sample the bag (and let it drop) to get interesting starting states.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
6407ae1b005c3df54361642a0c9341bdab9e01b5
gautams3/deformable-ravens
ravens/tasks/defs_cloth.py
[ "Apache-2.0" ]
Python
reset
null
def reset(self, env, last_info=None): """Reset to start an episode. Call the superclass to generate as usual, and then remove the zone here. Requires care in `environment.py` to avoid iterating over invalid IDs, and we need the zone in the superclass for many reasons. If loadin...
Reset to start an episode. Call the superclass to generate as usual, and then remove the zone here. Requires care in `environment.py` to avoid iterating over invalid IDs, and we need the zone in the superclass for many reasons. If loading goal images, we cannot just override self.targe...
Reset to start an episode. Call the superclass to generate as usual, and then remove the zone here. Requires care in `environment.py` to avoid iterating over invalid IDs, and we need the zone in the superclass for many reasons. If loading goal images, we cannot just override self.target_hull_bool because that means th...
[ "Reset", "to", "start", "an", "episode", ".", "Call", "the", "superclass", "to", "generate", "as", "usual", "and", "then", "remove", "the", "zone", "here", ".", "Requires", "care", "in", "`", "environment", ".", "py", "`", "to", "avoid", "iterating", "ov...
def reset(self, env, last_info=None): zone_pose = None if last_info is not None: zone_pose = last_info['sampled_zone_pose'] super().reset(env, zone_pose=zone_pose) p.removeBody(self.zone_ID)
[ "def", "reset", "(", "self", ",", "env", ",", "last_info", "=", "None", ")", ":", "zone_pose", "=", "None", "if", "last_info", "is", "not", "None", ":", "zone_pose", "=", "last_info", "[", "'sampled_zone_pose'", "]", "super", "(", ")", ".", "reset", "(...
Reset to start an episode.
[ "Reset", "to", "start", "an", "episode", "." ]
[ "\"\"\"Reset to start an episode.\n\n Call the superclass to generate as usual, and then remove the zone\n here. Requires care in `environment.py` to avoid iterating over\n invalid IDs, and we need the zone in the superclass for many reasons.\n\n If loading goal images, we cannot just ov...
[ { "param": "self", "type": null }, { "param": "env", "type": null }, { "param": "last_info", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": []...
dc734e3854df3efa40d9312c1e9d2a749225cd04
gautams3/deformable-ravens
generate_goals.py
[ "Apache-2.0" ]
Python
rollout
<not_specific>
def rollout(agent, env, task): """Standard gym environment rollout, following as in main.py.""" episode = [] total_reward = 0 obs = env.reset(task) info = env.info for t in range(task.max_steps): act = agent.act(obs, info) if len(obs) > 0 and act['primitive']: episode...
Standard gym environment rollout, following as in main.py.
Standard gym environment rollout, following as in main.py.
[ "Standard", "gym", "environment", "rollout", "following", "as", "in", "main", ".", "py", "." ]
def rollout(agent, env, task): episode = [] total_reward = 0 obs = env.reset(task) info = env.info for t in range(task.max_steps): act = agent.act(obs, info) if len(obs) > 0 and act['primitive']: episode.append((obs, act, info)) (obs, reward, done, info) = env.ste...
[ "def", "rollout", "(", "agent", ",", "env", ",", "task", ")", ":", "episode", "=", "[", "]", "total_reward", "=", "0", "obs", "=", "env", ".", "reset", "(", "task", ")", "info", "=", "env", ".", "info", "for", "t", "in", "range", "(", "task", "...
Standard gym environment rollout, following as in main.py.
[ "Standard", "gym", "environment", "rollout", "following", "as", "in", "main", ".", "py", "." ]
[ "\"\"\"Standard gym environment rollout, following as in main.py.\"\"\"" ]
[ { "param": "agent", "type": null }, { "param": "env", "type": null }, { "param": "task", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "agent", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": [...
dc734e3854df3efa40d9312c1e9d2a749225cd04
gautams3/deformable-ravens
generate_goals.py
[ "Apache-2.0" ]
Python
is_goal_conditioned
<not_specific>
def is_goal_conditioned(args): """ Be careful with checking this condition. See `load.py`. Here, we just check the task name. """ goal_tasks = ['insertion-goal', 'cable-shape-notarget', 'cable-line-notarget', 'cloth-flat-notarget', 'bag-color-goal'] return (args.task in goal_tasks)
Be careful with checking this condition. See `load.py`. Here, we just check the task name.
Be careful with checking this condition.
[ "Be", "careful", "with", "checking", "this", "condition", "." ]
def is_goal_conditioned(args): goal_tasks = ['insertion-goal', 'cable-shape-notarget', 'cable-line-notarget', 'cloth-flat-notarget', 'bag-color-goal'] return (args.task in goal_tasks)
[ "def", "is_goal_conditioned", "(", "args", ")", ":", "goal_tasks", "=", "[", "'insertion-goal'", ",", "'cable-shape-notarget'", ",", "'cable-line-notarget'", ",", "'cloth-flat-notarget'", ",", "'bag-color-goal'", "]", "return", "(", "args", ".", "task", "in", "goal_...
Be careful with checking this condition.
[ "Be", "careful", "with", "checking", "this", "condition", "." ]
[ "\"\"\"\n Be careful with checking this condition. See `load.py`.\n Here, we just check the task name.\n \"\"\"" ]
[ { "param": "args", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "args", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
dc734e3854df3efa40d9312c1e9d2a749225cd04
gautams3/deformable-ravens
generate_goals.py
[ "Apache-2.0" ]
Python
ignore_this_demo
<not_specific>
def ignore_this_demo(args, demo_reward, t, last_extras): """In some cases, we should filter out demonstrations. Filter for if t == 0, which means the initial state was a success. Also, for the bag envs, if we end up in a catastrophic state, I exit gracefully and we should avoid those demos (they won't ...
In some cases, we should filter out demonstrations. Filter for if t == 0, which means the initial state was a success. Also, for the bag envs, if we end up in a catastrophic state, I exit gracefully and we should avoid those demos (they won't have images we need for the dataset anyway).
In some cases, we should filter out demonstrations. Filter for if t == 0, which means the initial state was a success. Also, for the bag envs, if we end up in a catastrophic state, I exit gracefully and we should avoid those demos (they won't have images we need for the dataset anyway).
[ "In", "some", "cases", "we", "should", "filter", "out", "demonstrations", ".", "Filter", "for", "if", "t", "==", "0", "which", "means", "the", "initial", "state", "was", "a", "success", ".", "Also", "for", "the", "bag", "envs", "if", "we", "end", "up",...
def ignore_this_demo(args, demo_reward, t, last_extras): ignore = (t == 0) if 'exit_gracefully' in last_extras: assert last_extras['exit_gracefully'] return True if (args.task in ['bag-color-goal']) and demo_reward <= 0.5: return True return False
[ "def", "ignore_this_demo", "(", "args", ",", "demo_reward", ",", "t", ",", "last_extras", ")", ":", "ignore", "=", "(", "t", "==", "0", ")", "if", "'exit_gracefully'", "in", "last_extras", ":", "assert", "last_extras", "[", "'exit_gracefully'", "]", "return"...
In some cases, we should filter out demonstrations.
[ "In", "some", "cases", "we", "should", "filter", "out", "demonstrations", "." ]
[ "\"\"\"In some cases, we should filter out demonstrations.\n\n Filter for if t == 0, which means the initial state was a success.\n Also, for the bag envs, if we end up in a catastrophic state, I exit\n gracefully and we should avoid those demos (they won't have images we\n need for the dataset anyway)....
[ { "param": "args", "type": null }, { "param": "demo_reward", "type": null }, { "param": "t", "type": null }, { "param": "last_extras", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "args", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "demo_reward", "type": null, "docstring": null, "docstring_tok...
756ed8495366dd61bb7762b99d09dfc77248b91f
gautams3/deformable-ravens
ravens/models/transport.py
[ "Apache-2.0" ]
Python
train
<not_specific>
def train(self, in_img, p, q, theta): """Transport pixel p to pixel q. Args: input: depth_image: p: pixel (y, x) q: pixel (y, x) Returns: A `Tensor`. Has the same type as `input`. Daniel: the `in_img` will include the colo...
Transport pixel p to pixel q. Args: input: depth_image: p: pixel (y, x) q: pixel (y, x) Returns: A `Tensor`. Has the same type as `input`. Daniel: the `in_img` will include the color and depth. Much is similar to the atten...
Transport pixel p to pixel q. the `in_img` will include the color and depth. Much is similar to the attention model if we're not using the per-pixel loss: (a) forward pass, (b) get angle discretizations [though we set only 1 rotation for the picking model], (c) make the label consider rotations in the last axis, but o...
[ "Transport", "pixel", "p", "to", "pixel", "q", ".", "the", "`", "in_img", "`", "will", "include", "the", "color", "and", "depth", ".", "Much", "is", "similar", "to", "the", "attention", "model", "if", "we", "'", "re", "not", "using", "the", "per", "-...
def train(self, in_img, p, q, theta): self.metric.reset_states() with tf.GradientTape() as tape: output = self.forward(in_img, p, apply_softmax=False) itheta = theta / (2 * np.pi / self.num_rotations) itheta = np.int32(np.round(itheta)) % self.num_rotations ...
[ "def", "train", "(", "self", ",", "in_img", ",", "p", ",", "q", ",", "theta", ")", ":", "self", ".", "metric", ".", "reset_states", "(", ")", "with", "tf", ".", "GradientTape", "(", ")", "as", "tape", ":", "output", "=", "self", ".", "forward", "...
Transport pixel p to pixel q. Args: input: depth_image: p: pixel (y, x) q: pixel (y, x) Returns: A `Tensor`.
[ "Transport", "pixel", "p", "to", "pixel", "q", ".", "Args", ":", "input", ":", "depth_image", ":", "p", ":", "pixel", "(", "y", "x", ")", "q", ":", "pixel", "(", "y", "x", ")", "Returns", ":", "A", "`", "Tensor", "`", "." ]
[ "\"\"\"Transport pixel p to pixel q.\n\n Args:\n input:\n depth_image:\n p: pixel (y, x)\n q: pixel (y, x)\n Returns:\n A `Tensor`. Has the same type as `input`.\n\n Daniel: the `in_img` will include the color and depth. Much is\n ...
[ { "param": "self", "type": null }, { "param": "in_img", "type": null }, { "param": "p", "type": null }, { "param": "q", "type": null }, { "param": "theta", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "in_img", "type": null, "docstring": null, "docstring_tokens":...
756ed8495366dd61bb7762b99d09dfc77248b91f
gautams3/deformable-ravens
ravens/models/transport.py
[ "Apache-2.0" ]
Python
visualize_logits
null
def visualize_logits(self, logits): """Given logits (BEFORE tf.nn.convolution), get heatmap. Here we apply a softmax to make it more human-readable. However, the tf.nn.convolution with the learned kernels happens without a softmax on the logits. """ original_shape = logi...
Given logits (BEFORE tf.nn.convolution), get heatmap. Here we apply a softmax to make it more human-readable. However, the tf.nn.convolution with the learned kernels happens without a softmax on the logits.
Given logits (BEFORE tf.nn.convolution), get heatmap. Here we apply a softmax to make it more human-readable. However, the tf.nn.convolution with the learned kernels happens without a softmax on the logits.
[ "Given", "logits", "(", "BEFORE", "tf", ".", "nn", ".", "convolution", ")", "get", "heatmap", ".", "Here", "we", "apply", "a", "softmax", "to", "make", "it", "more", "human", "-", "readable", ".", "However", "the", "tf", ".", "nn", ".", "convolution", ...
def visualize_logits(self, logits): original_shape = logits.shape logits = tf.reshape(logits, (1, np.prod(original_shape))) logits = tf.nn.softmax(logits) vis_transport = np.float32(logits).reshape(original_shape) vis_transport = vis_transport[0] vis_transport = vis_trans...
[ "def", "visualize_logits", "(", "self", ",", "logits", ")", ":", "original_shape", "=", "logits", ".", "shape", "logits", "=", "tf", ".", "reshape", "(", "logits", ",", "(", "1", ",", "np", ".", "prod", "(", "original_shape", ")", ")", ")", "logits", ...
Given logits (BEFORE tf.nn.convolution), get heatmap.
[ "Given", "logits", "(", "BEFORE", "tf", ".", "nn", ".", "convolution", ")", "get", "heatmap", "." ]
[ "\"\"\"Given logits (BEFORE tf.nn.convolution), get heatmap.\n\n Here we apply a softmax to make it more human-readable. However, the\n tf.nn.convolution with the learned kernels happens without a softmax\n on the logits.\n \"\"\"", "# Only if we're saving with cv2.imwrite", "#vis_tr...
[ { "param": "self", "type": null }, { "param": "logits", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "logits", "type": null, "docstring": null, "docstring_tokens":...
99cd2f14d228db24ac2914bb61df8d4193c17bca
gautams3/deformable-ravens
ravens/models/regression.py
[ "Apache-2.0" ]
Python
train_place_conditioned_on_pick
<not_specific>
def train_place_conditioned_on_pick(self, in_img, p, q, theta): """ Regress pixel p to pixel q. Args: input: p: pixel (y, x) q: pixel (y, x) """ self.metric.reset_states() with tf.GradientTape() as tape: output = self.fo...
Regress pixel p to pixel q. Args: input: p: pixel (y, x) q: pixel (y, x)
Regress pixel p to pixel q.
[ "Regress", "pixel", "p", "to", "pixel", "q", "." ]
def train_place_conditioned_on_pick(self, in_img, p, q, theta): self.metric.reset_states() with tf.GradientTape() as tape: output = self.forward(in_img) delta_pixel = np.array(q) - np.array(p) yxtheta = np.array([delta_pixel[0], delta_pixel[1], theta]) los...
[ "def", "train_place_conditioned_on_pick", "(", "self", ",", "in_img", ",", "p", ",", "q", ",", "theta", ")", ":", "self", ".", "metric", ".", "reset_states", "(", ")", "with", "tf", ".", "GradientTape", "(", ")", "as", "tape", ":", "output", "=", "self...
Regress pixel p to pixel q.
[ "Regress", "pixel", "p", "to", "pixel", "q", "." ]
[ "\"\"\"\n Regress pixel p to pixel q.\n Args:\n input:\n p: pixel (y, x)\n q: pixel (y, x)\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "in_img", "type": null }, { "param": "p", "type": null }, { "param": "q", "type": null }, { "param": "theta", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "in_img", "type": null, "docstring": null, "docstring_tokens":...
d3f56d0a421fe53cb37137680db81252b7576991
gautams3/deformable-ravens
ravens/agents/conv_mlp.py
[ "Apache-2.0" ]
Python
train
<not_specific>
def train(self, dataset, num_iter, writer, validation_dataset): """Train on dataset for a specific number of iterations.""" VALIDATION_RATE = 100 @tf.function def pick_train_step(model, optim, in_tensor, yxtheta, loss_criterion): with tf.GradientTape() as tape: ...
Train on dataset for a specific number of iterations.
Train on dataset for a specific number of iterations.
[ "Train", "on", "dataset", "for", "a", "specific", "number", "of", "iterations", "." ]
def train(self, dataset, num_iter, writer, validation_dataset): VALIDATION_RATE = 100 @tf.function def pick_train_step(model, optim, in_tensor, yxtheta, loss_criterion): with tf.GradientTape() as tape: output = model(in_tensor) loss = loss_criterion(yx...
[ "def", "train", "(", "self", ",", "dataset", ",", "num_iter", ",", "writer", ",", "validation_dataset", ")", ":", "VALIDATION_RATE", "=", "100", "@", "tf", ".", "function", "def", "pick_train_step", "(", "model", ",", "optim", ",", "in_tensor", ",", "yxthe...
Train on dataset for a specific number of iterations.
[ "Train", "on", "dataset", "for", "a", "specific", "number", "of", "iterations", "." ]
[ "\"\"\"Train on dataset for a specific number of iterations.\"\"\"", "# Compute train loss", "# Compute valid loss" ]
[ { "param": "self", "type": null }, { "param": "dataset", "type": null }, { "param": "num_iter", "type": null }, { "param": "writer", "type": null }, { "param": "validation_dataset", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "dataset", "type": null, "docstring": null, "docstring_tokens"...
d3f56d0a421fe53cb37137680db81252b7576991
gautams3/deformable-ravens
ravens/agents/conv_mlp.py
[ "Apache-2.0" ]
Python
act
<not_specific>
def act(self, obs, gt_act, info): """Run inference and return best action given visual observations.""" self.regression_model.set_batch_size(1) act = {'camera_config': self.camera_config, 'primitive': None} if not obs: return act # Get heightmap from RGB-D images. ...
Run inference and return best action given visual observations.
Run inference and return best action given visual observations.
[ "Run", "inference", "and", "return", "best", "action", "given", "visual", "observations", "." ]
def act(self, obs, gt_act, info): self.regression_model.set_batch_size(1) act = {'camera_config': self.camera_config, 'primitive': None} if not obs: return act colormap, heightmap = self.get_heightmap(obs, self.camera_config) input_image = np.concatenate((colormap, ...
[ "def", "act", "(", "self", ",", "obs", ",", "gt_act", ",", "info", ")", ":", "self", ".", "regression_model", ".", "set_batch_size", "(", "1", ")", "act", "=", "{", "'camera_config'", ":", "self", ".", "camera_config", ",", "'primitive'", ":", "None", ...
Run inference and return best action given visual observations.
[ "Run", "inference", "and", "return", "best", "action", "given", "visual", "observations", "." ]
[ "\"\"\"Run inference and return best action given visual observations.\"\"\"", "# Get heightmap from RGB-D images.", "# Concatenate color with depth images.", "# or just use rgb", "#input_image = colormap[None, ...]", "# Regression", "#prediction = mdn_utils.pick_max_mean(pi, mu, var)" ]
[ { "param": "self", "type": null }, { "param": "obs", "type": null }, { "param": "gt_act", "type": null }, { "param": "info", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "obs", "type": null, "docstring": null, "docstring_tokens": []...
892b8903a295a2c434c6cb4740082433af7abfdb
gautams3/deformable-ravens
ravens/tasks/defs_bags.py
[ "Apache-2.0" ]
Python
add_cable_ring
null
def add_cable_ring(self, env, bag_id=None): """Make the cable beads coincide with the vertices of the top ring. This should lead to better physics and will make it easy for an algorithm to see the bag's top ring. Please see the cable-ring env for details, or `scratch/cable_ring_MWE.py`....
Make the cable beads coincide with the vertices of the top ring. This should lead to better physics and will make it easy for an algorithm to see the bag's top ring. Please see the cable-ring env for details, or `scratch/cable_ring_MWE.py`. Notable differences (or similarities) between ...
Make the cable beads coincide with the vertices of the top ring. This should lead to better physics and will make it easy for an algorithm to see the bag's top ring. Please see the cable-ring env for details, or `scratch/cable_ring_MWE.py`. Notable differences (or similarities) between this and `dan_cables.py`. (1) We...
[ "Make", "the", "cable", "beads", "coincide", "with", "the", "vertices", "of", "the", "top", "ring", ".", "This", "should", "lead", "to", "better", "physics", "and", "will", "make", "it", "easy", "for", "an", "algorithm", "to", "see", "the", "bag", "'", ...
def add_cable_ring(self, env, bag_id=None): num_parts = len(self._top_ring_idxs) radius = 0.005 color = U.COLORS['blue'] + [1] beads = [] bead_positions_l = [] part_shape = p.createCollisionShape(p.GEOM_BOX, halfExtents=[radius]*3) part_visual = p.createVisualShap...
[ "def", "add_cable_ring", "(", "self", ",", "env", ",", "bag_id", "=", "None", ")", ":", "num_parts", "=", "len", "(", "self", ".", "_top_ring_idxs", ")", "radius", "=", "0.005", "color", "=", "U", ".", "COLORS", "[", "'blue'", "]", "+", "[", "1", "...
Make the cable beads coincide with the vertices of the top ring.
[ "Make", "the", "cable", "beads", "coincide", "with", "the", "vertices", "of", "the", "top", "ring", "." ]
[ "\"\"\"Make the cable beads coincide with the vertices of the top ring.\n\n This should lead to better physics and will make it easy for an\n algorithm to see the bag's top ring. Please see the cable-ring env\n for details, or `scratch/cable_ring_MWE.py`. Notable differences\n (or simila...
[ { "param": "self", "type": null }, { "param": "env", "type": null }, { "param": "bag_id", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": []...
892b8903a295a2c434c6cb4740082433af7abfdb
gautams3/deformable-ravens
ravens/tasks/defs_bags.py
[ "Apache-2.0" ]
Python
add_bag
<not_specific>
def add_bag(self, env, base_pos, base_orn, bag_color='yellow'): """Adding a bag from an .obj file.""" bag_id = p.loadSoftBody( fileName=self._f_bag, basePosition=base_pos, baseOrientation=base_orn, collisionMargin=self._collisionMargin, ...
Adding a bag from an .obj file.
Adding a bag from an .obj file.
[ "Adding", "a", "bag", "from", "an", ".", "obj", "file", "." ]
def add_bag(self, env, base_pos, base_orn, bag_color='yellow'): bag_id = p.loadSoftBody( fileName=self._f_bag, basePosition=base_pos, baseOrientation=base_orn, collisionMargin=self._collisionMargin, scale=self._bag_scale, ...
[ "def", "add_bag", "(", "self", ",", "env", ",", "base_pos", ",", "base_orn", ",", "bag_color", "=", "'yellow'", ")", ":", "bag_id", "=", "p", ".", "loadSoftBody", "(", "fileName", "=", "self", ".", "_f_bag", ",", "basePosition", "=", "base_pos", ",", "...
Adding a bag from an .obj file.
[ "Adding", "a", "bag", "from", "an", ".", "obj", "file", "." ]
[ "\"\"\"Adding a bag from an .obj file.\"\"\"", "# Only if using more recent PyBullet versions.", "# For tracking IDs and consistency with existing ravens code.", "# To help environment pick-place method track all deformables." ]
[ { "param": "self", "type": null }, { "param": "env", "type": null }, { "param": "base_pos", "type": null }, { "param": "base_orn", "type": null }, { "param": "bag_color", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": []...
892b8903a295a2c434c6cb4740082433af7abfdb
gautams3/deformable-ravens
ravens/tasks/defs_bags.py
[ "Apache-2.0" ]
Python
_sample_bag_orientation
<not_specific>
def _sample_bag_orientation(self): """Sample the bag (and let it drop) to get interesting starting states.""" orn = [self._base_orn[0] + np.random.normal(loc=0.0, scale=self._scale), self._base_orn[1] + np.random.normal(loc=0.0, scale=self._scale), self._base_orn[2] + np.ra...
Sample the bag (and let it drop) to get interesting starting states.
Sample the bag (and let it drop) to get interesting starting states.
[ "Sample", "the", "bag", "(", "and", "let", "it", "drop", ")", "to", "get", "interesting", "starting", "states", "." ]
def _sample_bag_orientation(self): orn = [self._base_orn[0] + np.random.normal(loc=0.0, scale=self._scale), self._base_orn[1] + np.random.normal(loc=0.0, scale=self._scale), self._base_orn[2] + np.random.normal(loc=0.0, scale=self._scale),] return p.getQuaternionFromEuler(o...
[ "def", "_sample_bag_orientation", "(", "self", ")", ":", "orn", "=", "[", "self", ".", "_base_orn", "[", "0", "]", "+", "np", ".", "random", ".", "normal", "(", "loc", "=", "0.0", ",", "scale", "=", "self", ".", "_scale", ")", ",", "self", ".", "...
Sample the bag (and let it drop) to get interesting starting states.
[ "Sample", "the", "bag", "(", "and", "let", "it", "drop", ")", "to", "get", "interesting", "starting", "states", "." ]
[ "\"\"\"Sample the bag (and let it drop) to get interesting starting states.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
892b8903a295a2c434c6cb4740082433af7abfdb
gautams3/deformable-ravens
ravens/tasks/defs_bags.py
[ "Apache-2.0" ]
Python
understand_bag_top_ring
<not_specific>
def understand_bag_top_ring(self, env, base_pos): """By our circular bag design, there exists a top ring file. Reading it gives us several important pieces of information. We assign to: _top_ring_idxs: indices of the vertices (out of entire bag). _top_ring_posi: their starting ...
By our circular bag design, there exists a top ring file. Reading it gives us several important pieces of information. We assign to: _top_ring_idxs: indices of the vertices (out of entire bag). _top_ring_posi: their starting xyz positions (BEFORE simulation or applying ...
By our circular bag design, there exists a top ring file. Reading it gives us several important pieces of information. We assign to. indices of the vertices (out of entire bag). _top_ring_posi: their starting xyz positions (BEFORE simulation or applying pose transformations). This way we can get the area of the circle...
[ "By", "our", "circular", "bag", "design", "there", "exists", "a", "top", "ring", "file", ".", "Reading", "it", "gives", "us", "several", "important", "pieces", "of", "information", ".", "We", "assign", "to", ".", "indices", "of", "the", "vertices", "(", ...
def understand_bag_top_ring(self, env, base_pos): self._top_ring_f = (self._f_bag).replace('.obj', '_top_ring.txt') self._top_ring_f = os.path.join('ravens', self._top_ring_f) self._top_ring_idxs = [] self._top_ring_posi = [] with open(self._top_ring_f, 'r') as fh: ...
[ "def", "understand_bag_top_ring", "(", "self", ",", "env", ",", "base_pos", ")", ":", "self", ".", "_top_ring_f", "=", "(", "self", ".", "_f_bag", ")", ".", "replace", "(", "'.obj'", ",", "'_top_ring.txt'", ")", "self", ".", "_top_ring_f", "=", "os", "."...
By our circular bag design, there exists a top ring file.
[ "By", "our", "circular", "bag", "design", "there", "exists", "a", "top", "ring", "file", "." ]
[ "\"\"\"By our circular bag design, there exists a top ring file.\n\n Reading it gives us several important pieces of information. We assign to:\n\n _top_ring_idxs: indices of the vertices (out of entire bag).\n _top_ring_posi: their starting xyz positions (BEFORE simulation\n ...
[ { "param": "self", "type": null }, { "param": "env", "type": null }, { "param": "base_pos", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": []...
892b8903a295a2c434c6cb4740082433af7abfdb
gautams3/deformable-ravens
ravens/tasks/defs_bags.py
[ "Apache-2.0" ]
Python
_apply_small_force
null
def _apply_small_force(self, num_iters, fx=10, fy=10, fz=8): """A small force to perturb the starting bag.""" # First bag. Assume that 32 beads are in one bag. bead_idx = np.random.randint(len(self.cable_bead_IDs)) bead_id = self.cable_bead_IDs[bead_idx] fx_1 = np.random.randint...
A small force to perturb the starting bag.
A small force to perturb the starting bag.
[ "A", "small", "force", "to", "perturb", "the", "starting", "bag", "." ]
def _apply_small_force(self, num_iters, fx=10, fy=10, fz=8): bead_idx = np.random.randint(len(self.cable_bead_IDs)) bead_id = self.cable_bead_IDs[bead_idx] fx_1 = np.random.randint(low=-fx, high=fx + 1) fy_1 = np.random.randint(low=-fy, high=fy + 1) if len(self.cable_bead_IDs) > ...
[ "def", "_apply_small_force", "(", "self", ",", "num_iters", ",", "fx", "=", "10", ",", "fy", "=", "10", ",", "fz", "=", "8", ")", ":", "bead_idx", "=", "np", ".", "random", ".", "randint", "(", "len", "(", "self", ".", "cable_bead_IDs", ")", ")", ...
A small force to perturb the starting bag.
[ "A", "small", "force", "to", "perturb", "the", "starting", "bag", "." ]
[ "\"\"\"A small force to perturb the starting bag.\"\"\"", "# First bag. Assume that 32 beads are in one bag.", "# Second bag if necessary." ]
[ { "param": "self", "type": null }, { "param": "num_iters", "type": null }, { "param": "fx", "type": null }, { "param": "fy", "type": null }, { "param": "fz", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "num_iters", "type": null, "docstring": null, "docstring_token...
892b8903a295a2c434c6cb4740082433af7abfdb
gautams3/deformable-ravens
ravens/tasks/defs_bags.py
[ "Apache-2.0" ]
Python
determine_task_stage
<not_specific>
def determine_task_stage(self, colormap=None, heightmap=None, object_mask=None, visible_beads=None): """Get the task stage in a consistent manner among different policies. When training an oracle policy, we can determine the training stage, which is critical because...
Get the task stage in a consistent manner among different policies. When training an oracle policy, we can determine the training stage, which is critical because of this task's particular quirks in requiring different action parameters (particularly height of the pull) for each stage. ...
Get the task stage in a consistent manner among different policies. When training an oracle policy, we can determine the training stage, which is critical because of this task's particular quirks in requiring different action parameters (particularly height of the pull) for each stage. One option is to use this method ...
[ "Get", "the", "task", "stage", "in", "a", "consistent", "manner", "among", "different", "policies", ".", "When", "training", "an", "oracle", "policy", "we", "can", "determine", "the", "training", "stage", "which", "is", "critical", "because", "of", "this", "...
def determine_task_stage(self, colormap=None, heightmap=None, object_mask=None, visible_beads=None): if self.task_stage == 2 and (len(self.items_in_bag_IDs) == len(self.item_IDs)): self.task_stage = 3 return (True, None) elif self.task_stage == 3: ...
[ "def", "determine_task_stage", "(", "self", ",", "colormap", "=", "None", ",", "heightmap", "=", "None", ",", "object_mask", "=", "None", ",", "visible_beads", "=", "None", ")", ":", "if", "self", ".", "task_stage", "==", "2", "and", "(", "len", "(", "...
Get the task stage in a consistent manner among different policies.
[ "Get", "the", "task", "stage", "in", "a", "consistent", "manner", "among", "different", "policies", "." ]
[ "\"\"\"Get the task stage in a consistent manner among different policies.\n\n When training an oracle policy, we can determine the training stage,\n which is critical because of this task's particular quirks in\n requiring different action parameters (particularly height of the\n pull) ...
[ { "param": "self", "type": null }, { "param": "colormap", "type": null }, { "param": "heightmap", "type": null }, { "param": "object_mask", "type": null }, { "param": "visible_beads", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "colormap", "type": null, "docstring": null, "docstring_tokens...
892b8903a295a2c434c6cb4740082433af7abfdb
gautams3/deformable-ravens
ravens/tasks/defs_bags.py
[ "Apache-2.0" ]
Python
add_random_box
<not_specific>
def add_random_box(self, env, max_total_dims): """Generate randomly shaped box, from aligning env. Make rand_x and rand_y add up to the max_total. Also, the aligning env uses a box with mass 0.1, but we can make ours lighter. But, will it cause the block to bounce too much when inserted...
Generate randomly shaped box, from aligning env. Make rand_x and rand_y add up to the max_total. Also, the aligning env uses a box with mass 0.1, but we can make ours lighter. But, will it cause the block to bounce too much when inserted in the bag? Also returning the object size, so w...
Generate randomly shaped box, from aligning env. Also returning the object size, so we can use it for later. Use to control how long we can make boxes. I would keep this value at a level making these boxes comparable to the cubes, if not smaller, used in bag-items-easy.
[ "Generate", "randomly", "shaped", "box", "from", "aligning", "env", ".", "Also", "returning", "the", "object", "size", "so", "we", "can", "use", "it", "for", "later", ".", "Use", "to", "control", "how", "long", "we", "can", "make", "boxes", ".", "I", "...
def add_random_box(self, env, max_total_dims): min_val = 0.015 assert min_val*2 <= max_total_dims, min_val rand_x = np.random.uniform(min_val, max_total_dims - min_val) rand_y = max_total_dims - rand_x box_size = (rand_x, rand_y, 0.03) box_pose = self.random_pose(env, box...
[ "def", "add_random_box", "(", "self", ",", "env", ",", "max_total_dims", ")", ":", "min_val", "=", "0.015", "assert", "min_val", "*", "2", "<=", "max_total_dims", ",", "min_val", "rand_x", "=", "np", ".", "random", ".", "uniform", "(", "min_val", ",", "m...
Generate randomly shaped box, from aligning env.
[ "Generate", "randomly", "shaped", "box", "from", "aligning", "env", "." ]
[ "\"\"\"Generate randomly shaped box, from aligning env.\n\n Make rand_x and rand_y add up to the max_total. Also, the aligning\n env uses a box with mass 0.1, but we can make ours lighter. But, will\n it cause the block to bounce too much when inserted in the bag?\n\n Also returning the ...
[ { "param": "self", "type": null }, { "param": "env", "type": null }, { "param": "max_total_dims", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": []...
892b8903a295a2c434c6cb4740082433af7abfdb
gautams3/deformable-ravens
ravens/tasks/defs_bags.py
[ "Apache-2.0" ]
Python
determine_task_stage
<not_specific>
def determine_task_stage(self, colormap=None, heightmap=None, object_mask=None, visible_beads=None): """Get the task stage in a consistent manner among different policies. When training an oracle policy, we can determine the training stage, which is critical because...
Get the task stage in a consistent manner among different policies. When training an oracle policy, we can determine the training stage, which is critical because of this task's particular quirks in requiring different action parameters (particularly height of the pull) for each stage. ...
Get the task stage in a consistent manner among different policies. When training an oracle policy, we can determine the training stage, which is critical because of this task's particular quirks in requiring different action parameters (particularly height of the pull) for each stage. One option is to use this method ...
[ "Get", "the", "task", "stage", "in", "a", "consistent", "manner", "among", "different", "policies", ".", "When", "training", "an", "oracle", "policy", "we", "can", "determine", "the", "training", "stage", "which", "is", "critical", "because", "of", "this", "...
def determine_task_stage(self, colormap=None, heightmap=None, object_mask=None, visible_beads=None): if self.task_stage == 2 and (len(self.items_in_bag_IDs) == len(self.item_IDs)): self.task_stage = 3 return (True, None) elif self.task_stage == 3: ...
[ "def", "determine_task_stage", "(", "self", ",", "colormap", "=", "None", ",", "heightmap", "=", "None", ",", "object_mask", "=", "None", ",", "visible_beads", "=", "None", ")", ":", "if", "self", ".", "task_stage", "==", "2", "and", "(", "len", "(", "...
Get the task stage in a consistent manner among different policies.
[ "Get", "the", "task", "stage", "in", "a", "consistent", "manner", "among", "different", "policies", "." ]
[ "\"\"\"Get the task stage in a consistent manner among different policies.\n\n When training an oracle policy, we can determine the training stage,\n which is critical because of this task's particular quirks in\n requiring different action parameters (particularly height of the\n pull) ...
[ { "param": "self", "type": null }, { "param": "colormap", "type": null }, { "param": "heightmap", "type": null }, { "param": "object_mask", "type": null }, { "param": "visible_beads", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "colormap", "type": null, "docstring": null, "docstring_tokens...
892b8903a295a2c434c6cb4740082433af7abfdb
gautams3/deformable-ravens
ravens/tasks/defs_bags.py
[ "Apache-2.0" ]
Python
add_block
<not_specific>
def add_block(self, env, block_name, max_total_dims): """Generate randomly shaped block for the goal based task. Similar to the random block method used for bag-items-hard. env uses a box with mass 0.1, but we can make ours lighter. But, will it cause the block to bounce too much when i...
Generate randomly shaped block for the goal based task. Similar to the random block method used for bag-items-hard. env uses a box with mass 0.1, but we can make ours lighter. But, will it cause the block to bounce too much when inserted in the bag? Also returning the object size, so w...
Generate randomly shaped block for the goal based task. Similar to the random block method used for bag-items-hard. env uses a box with mass 0.1, but we can make ours lighter. Also returning the object size, so we can use it for later.
[ "Generate", "randomly", "shaped", "block", "for", "the", "goal", "based", "task", ".", "Similar", "to", "the", "random", "block", "method", "used", "for", "bag", "-", "items", "-", "hard", ".", "env", "uses", "a", "box", "with", "mass", "0", ".", "1", ...
def add_block(self, env, block_name, max_total_dims): box_size = (0.045, 0.045, 0.030) box_pose = self.random_pose(env, box_size) box_template = 'assets/box/box-template.urdf' box_urdf = self.fill_template(box_template, {'DIM': box_size}) box_id = env.add_object(box_urdf, box_p...
[ "def", "add_block", "(", "self", ",", "env", ",", "block_name", ",", "max_total_dims", ")", ":", "box_size", "=", "(", "0.045", ",", "0.045", ",", "0.030", ")", "box_pose", "=", "self", ".", "random_pose", "(", "env", ",", "box_size", ")", "box_template"...
Generate randomly shaped block for the goal based task.
[ "Generate", "randomly", "shaped", "block", "for", "the", "goal", "based", "task", "." ]
[ "\"\"\"Generate randomly shaped block for the goal based task.\n\n Similar to the random block method used for bag-items-hard.\n env uses a box with mass 0.1, but we can make ours lighter. But, will\n it cause the block to bounce too much when inserted in the bag?\n\n Also returning the ...
[ { "param": "self", "type": null }, { "param": "env", "type": null }, { "param": "block_name", "type": null }, { "param": "max_total_dims", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": []...
892b8903a295a2c434c6cb4740082433af7abfdb
gautams3/deformable-ravens
ravens/tasks/defs_bags.py
[ "Apache-2.0" ]
Python
is_item_in_bag
<not_specific>
def is_item_in_bag(self): """Used to determine reward. We want item to be inside the bag hull. Actually, first detect bead visibility. If we can't see any then we should just return 0 because that means we've messed up somewhere. Returns an info dict, which has 'reward' keyword. ...
Used to determine reward. We want item to be inside the bag hull. Actually, first detect bead visibility. If we can't see any then we should just return 0 because that means we've messed up somewhere. Returns an info dict, which has 'reward' keyword.
Used to determine reward. We want item to be inside the bag hull. Actually, first detect bead visibility. If we can't see any then we should just return 0 because that means we've messed up somewhere. Returns an info dict, which has 'reward' keyword.
[ "Used", "to", "determine", "reward", ".", "We", "want", "item", "to", "be", "inside", "the", "bag", "hull", ".", "Actually", "first", "detect", "bead", "visibility", ".", "If", "we", "can", "'", "t", "see", "any", "then", "we", "should", "just", "retur...
def is_item_in_bag(self): result = {'exit_early': False, 'frac_in_target_bag': 0.0, 'frac_in_distract_bag': 0.0} colormap, heightmap, object_mask = self.get_object_masks(self.env) visible_beads = [] for bead in self.cable_bead_target_bag_IDs: ...
[ "def", "is_item_in_bag", "(", "self", ")", ":", "result", "=", "{", "'exit_early'", ":", "False", ",", "'frac_in_target_bag'", ":", "0.0", ",", "'frac_in_distract_bag'", ":", "0.0", "}", "colormap", ",", "heightmap", ",", "object_mask", "=", "self", ".", "ge...
Used to determine reward.
[ "Used", "to", "determine", "reward", "." ]
[ "\"\"\"Used to determine reward. We want item to be inside the bag hull.\n\n Actually, first detect bead visibility. If we can't see any then we should\n just return 0 because that means we've messed up somewhere.\n\n Returns an info dict, which has 'reward' keyword.\n \"\"\"", "# Dete...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
892b8903a295a2c434c6cb4740082433af7abfdb
gautams3/deformable-ravens
ravens/tasks/defs_bags.py
[ "Apache-2.0" ]
Python
determine_task_stage
<not_specific>
def determine_task_stage(self, colormap=None, heightmap=None, object_mask=None, visible_beads=None): """Get the task stage in a consistent manner among different policies. This should be easier as compared to the bag-items since we only handle two task stages (and w...
Get the task stage in a consistent manner among different policies. This should be easier as compared to the bag-items since we only handle two task stages (and we don't have drastically different action params).
Get the task stage in a consistent manner among different policies. This should be easier as compared to the bag-items since we only handle two task stages (and we don't have drastically different action params).
[ "Get", "the", "task", "stage", "in", "a", "consistent", "manner", "among", "different", "policies", ".", "This", "should", "be", "easier", "as", "compared", "to", "the", "bag", "-", "items", "since", "we", "only", "handle", "two", "task", "stages", "(", ...
def determine_task_stage(self, colormap=None, heightmap=None, object_mask=None, visible_beads=None): if self.task_stage == 2: print('ON TASK STAGE 2, still here, should not normally happen...') return (True, None) BUF = 0.025 cable_IDs = np.ar...
[ "def", "determine_task_stage", "(", "self", ",", "colormap", "=", "None", ",", "heightmap", "=", "None", ",", "object_mask", "=", "None", ",", "visible_beads", "=", "None", ")", ":", "if", "self", ".", "task_stage", "==", "2", ":", "print", "(", "'ON TAS...
Get the task stage in a consistent manner among different policies.
[ "Get", "the", "task", "stage", "in", "a", "consistent", "manner", "among", "different", "policies", "." ]
[ "\"\"\"Get the task stage in a consistent manner among different policies.\n\n This should be easier as compared to the bag-items since we only handle\n two task stages (and we don't have drastically different action params).\n \"\"\"", "# Hand-tuned, if too small the agent won't open the bag...
[ { "param": "self", "type": null }, { "param": "colormap", "type": null }, { "param": "heightmap", "type": null }, { "param": "object_mask", "type": null }, { "param": "visible_beads", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "colormap", "type": null, "docstring": null, "docstring_tokens...
502c83dde41cd58ae0dfcc7819f5689315b1fecd
jtz/Bitcoin-Trading-Simulator
SimulatedTrading.py
[ "MIT" ]
Python
record_into_file
null
def record_into_file(self, btc_price): """Record account status into file.""" # total bitcoin value according to current price btc_value = btc_price * self.__current_amount # total asset value according to current price total_value = btc_value + self.__current_cash ...
Record account status into file.
Record account status into file.
[ "Record", "account", "status", "into", "file", "." ]
def record_into_file(self, btc_price): btc_value = btc_price * self.__current_amount total_value = btc_value + self.__current_cash record = [datetime.now().strftime("%Y-%m-%d,%H:%M:%S"),\ str(total_value), str(self.__current_cash), str(btc_value),\ str(self.__cu...
[ "def", "record_into_file", "(", "self", ",", "btc_price", ")", ":", "btc_value", "=", "btc_price", "*", "self", ".", "__current_amount", "total_value", "=", "btc_value", "+", "self", ".", "__current_cash", "record", "=", "[", "datetime", ".", "now", "(", ")"...
Record account status into file.
[ "Record", "account", "status", "into", "file", "." ]
[ "\"\"\"Record account status into file.\"\"\"", "# total bitcoin value according to current price\r", "# total asset value according to current price\r", "# set items to record\r", "# open file and write record\r" ]
[ { "param": "self", "type": null }, { "param": "btc_price", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "btc_price", "type": null, "docstring": null, "docstring_token...
502c83dde41cd58ae0dfcc7819f5689315b1fecd
jtz/Bitcoin-Trading-Simulator
SimulatedTrading.py
[ "MIT" ]
Python
simulated_trading_main
null
def simulated_trading_main(self): """Prompt user to select actions in the submenu.""" simulated_trading = SimulatedTrading() # check if need to initialize the trading account file_exist = simulated_trading.check_file_exist() if not file_exist: simulated_trading...
Prompt user to select actions in the submenu.
Prompt user to select actions in the submenu.
[ "Prompt", "user", "to", "select", "actions", "in", "the", "submenu", "." ]
def simulated_trading_main(self): simulated_trading = SimulatedTrading() file_exist = simulated_trading.check_file_exist() if not file_exist: simulated_trading.setup_account() while True: select_str = input("Here is the Simulated Trading Menu: \n" ...
[ "def", "simulated_trading_main", "(", "self", ")", ":", "simulated_trading", "=", "SimulatedTrading", "(", ")", "file_exist", "=", "simulated_trading", ".", "check_file_exist", "(", ")", "if", "not", "file_exist", ":", "simulated_trading", ".", "setup_account", "(",...
Prompt user to select actions in the submenu.
[ "Prompt", "user", "to", "select", "actions", "in", "the", "submenu", "." ]
[ "\"\"\"Prompt user to select actions in the submenu.\"\"\"", "# check if need to initialize the trading account\r", "# prompt user to select actions in the submenu\r", "# start validate input\r", "# 1 - Start Simulate Trading\r", "# 2 - View Trading History \r", "# 3 - Exit \r" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4d4f47503d58ae5c242a31467a7c59bfbdea9a51
jtz/Bitcoin-Trading-Simulator
PriceHistory.py
[ "MIT" ]
Python
view_historical_price
<not_specific>
def view_historical_price(self, interval): """Return text description of the historical price.""" self.interval = interval # view history for one day if self.interval == "one": self.df_one = self.get_historical_price("one") # get a summary info...
Return text description of the historical price.
Return text description of the historical price.
[ "Return", "text", "description", "of", "the", "historical", "price", "." ]
def view_historical_price(self, interval): self.interval = interval if self.interval == "one": self.df_one = self.get_historical_price("one") df_info = self.df_one.describe().round(2) return ("\nPrice History on {}: \n" ...
[ "def", "view_historical_price", "(", "self", ",", "interval", ")", ":", "self", ".", "interval", "=", "interval", "if", "self", ".", "interval", "==", "\"one\"", ":", "self", ".", "df_one", "=", "self", ".", "get_historical_price", "(", "\"one\"", ")", "df...
Return text description of the historical price.
[ "Return", "text", "description", "of", "the", "historical", "price", "." ]
[ "\"\"\"Return text description of the historical price.\"\"\"", "# view history for one day\r", "# get a summary info of one day data frame\r", "# round all data to two decimal places\r", "# view history for a period \r", "# get a summary info of a period data frame\r" ]
[ { "param": "self", "type": null }, { "param": "interval", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "interval", "type": null, "docstring": null, "docstring_tokens...
4d4f47503d58ae5c242a31467a7c59bfbdea9a51
jtz/Bitcoin-Trading-Simulator
PriceHistory.py
[ "MIT" ]
Python
price_chart
null
def price_chart(self, interval): """Get candlestick chart of historical price.""" self.interval = interval # get candlestick chart from one day dataframe if self.interval == "one": view_history = self.view_historical_price("one") ...
Get candlestick chart of historical price.
Get candlestick chart of historical price.
[ "Get", "candlestick", "chart", "of", "historical", "price", "." ]
def price_chart(self, interval): self.interval = interval if self.interval == "one": view_history = self.view_historical_price("one") mpf.plot(self.df_one, type="candle", style="yahoo",\ title=" Bitcoi...
[ "def", "price_chart", "(", "self", ",", "interval", ")", ":", "self", ".", "interval", "=", "interval", "if", "self", ".", "interval", "==", "\"one\"", ":", "view_history", "=", "self", ".", "view_historical_price", "(", "\"one\"", ")", "mpf", ".", "plot",...
Get candlestick chart of historical price.
[ "Get", "candlestick", "chart", "of", "historical", "price", "." ]
[ "\"\"\"Get candlestick chart of historical price.\"\"\"", "# get candlestick chart from one day dataframe\r", "# print info of one day price history\r", "# get candlestick chart from period dataframe\r", "# print summary of period price history\r" ]
[ { "param": "self", "type": null }, { "param": "interval", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "interval", "type": null, "docstring": null, "docstring_tokens...
4d4f47503d58ae5c242a31467a7c59bfbdea9a51
jtz/Bitcoin-Trading-Simulator
PriceHistory.py
[ "MIT" ]
Python
price_history_main
null
def price_history_main(self): """Prompt user to select actions in the submenu.""" while True: # prompt user to select actions in the submenu select_str = input("Here is the Historical Price Menu: \n" "1 - View Historical Price For A Day \n" ...
Prompt user to select actions in the submenu.
Prompt user to select actions in the submenu.
[ "Prompt", "user", "to", "select", "actions", "in", "the", "submenu", "." ]
def price_history_main(self): while True: select_str = input("Here is the Historical Price Menu: \n" "1 - View Historical Price For A Day \n" "2 - View Historical Price For A Period \n" "3 - Exit View Histor...
[ "def", "price_history_main", "(", "self", ")", ":", "while", "True", ":", "select_str", "=", "input", "(", "\"Here is the Historical Price Menu: \\n\"", "\"1 - View Historical Price For A Day \\n\"", "\"2 - View Historical Price For A Period \\n\"", "\"3 - Exit View Historical Price ...
Prompt user to select actions in the submenu.
[ "Prompt", "user", "to", "select", "actions", "in", "the", "submenu", "." ]
[ "\"\"\"Prompt user to select actions in the submenu.\"\"\"", "# prompt user to select actions in the submenu\r", "# start validate input\r", "# 1 - View Historical Price For One Day\r", "# 2 - View Historical Price For A Period \r", "# 3 - Exit \r" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ad6f0cb3eb34ef6aad08821e5982cb6876daec11
oriern/SuperPAL
utils.py
[ "MIT" ]
Python
hashhex
<not_specific>
def hashhex(s): """Returns a heximal formated SHA1 hash of the input string.""" s = s.encode('utf-8') h = hashlib.sha1() h.update(s) return h.hexdigest()
Returns a heximal formated SHA1 hash of the input string.
Returns a heximal formated SHA1 hash of the input string.
[ "Returns", "a", "heximal", "formated", "SHA1", "hash", "of", "the", "input", "string", "." ]
def hashhex(s): s = s.encode('utf-8') h = hashlib.sha1() h.update(s) return h.hexdigest()
[ "def", "hashhex", "(", "s", ")", ":", "s", "=", "s", ".", "encode", "(", "'utf-8'", ")", "h", "=", "hashlib", ".", "sha1", "(", ")", "h", ".", "update", "(", "s", ")", "return", "h", ".", "hexdigest", "(", ")" ]
Returns a heximal formated SHA1 hash of the input string.
[ "Returns", "a", "heximal", "formated", "SHA1", "hash", "of", "the", "input", "string", "." ]
[ "\"\"\"Returns a heximal formated SHA1 hash of the input string.\"\"\"" ]
[ { "param": "s", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "s", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ad6f0cb3eb34ef6aad08821e5982cb6876daec11
oriern/SuperPAL
utils.py
[ "MIT" ]
Python
read_csv_data
<not_specific>
def read_csv_data(csv_file): """ Reader to parse the csv file""" data = [] with open(args.input_file_path, encoding='utf-8', errors='ignore') as f: csv_reader = csv.reader(f, delimiter=',') for ind, row in enumerate(csv_reader): if ind == 0: header = row ...
Reader to parse the csv file
Reader to parse the csv file
[ "Reader", "to", "parse", "the", "csv", "file" ]
def read_csv_data(csv_file): data = [] with open(args.input_file_path, encoding='utf-8', errors='ignore') as f: csv_reader = csv.reader(f, delimiter=',') for ind, row in enumerate(csv_reader): if ind == 0: header = row else: data.append(row...
[ "def", "read_csv_data", "(", "csv_file", ")", ":", "data", "=", "[", "]", "with", "open", "(", "args", ".", "input_file_path", ",", "encoding", "=", "'utf-8'", ",", "errors", "=", "'ignore'", ")", "as", "f", ":", "csv_reader", "=", "csv", ".", "reader"...
Reader to parse the csv file
[ "Reader", "to", "parse", "the", "csv", "file" ]
[ "\"\"\" Reader to parse the csv file\"\"\"" ]
[ { "param": "csv_file", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "csv_file", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ad6f0cb3eb34ef6aad08821e5982cb6876daec11
oriern/SuperPAL
utils.py
[ "MIT" ]
Python
read_generic_file
<not_specific>
def read_generic_file(filepath): """ reads any generic text file into list containing one line as element """ text = [] with open(filepath, 'r') as f: for line in f.read().splitlines(): text.append(line.strip()) return text
reads any generic text file into list containing one line as element
reads any generic text file into list containing one line as element
[ "reads", "any", "generic", "text", "file", "into", "list", "containing", "one", "line", "as", "element" ]
def read_generic_file(filepath): text = [] with open(filepath, 'r') as f: for line in f.read().splitlines(): text.append(line.strip()) return text
[ "def", "read_generic_file", "(", "filepath", ")", ":", "text", "=", "[", "]", "with", "open", "(", "filepath", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ".", "read", "(", ")", ".", "splitlines", "(", ")", ":", "text", ".", "appen...
reads any generic text file into list containing one line as element
[ "reads", "any", "generic", "text", "file", "into", "list", "containing", "one", "line", "as", "element" ]
[ "\"\"\" reads any generic text file into\n list containing one line as element\n \"\"\"" ]
[ { "param": "filepath", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "filepath", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ad6f0cb3eb34ef6aad08821e5982cb6876daec11
oriern/SuperPAL
utils.py
[ "MIT" ]
Python
calculate_metric_scores
<not_specific>
def calculate_metric_scores(cands, refs): """ calculate Rouge-1 precision, Bert precision and Entailment Scores """ # calculate rouge-1 precision rouge = Rouge() rouge1_p = [] for r, c in tqdm(zip(refs, cands)): r = " ".join(list(nlp_parser.tokenize(r))).lower() c = " ".join(...
calculate Rouge-1 precision, Bert precision and Entailment Scores
calculate Rouge-1 precision, Bert precision and Entailment Scores
[ "calculate", "Rouge", "-", "1", "precision", "Bert", "precision", "and", "Entailment", "Scores" ]
def calculate_metric_scores(cands, refs): rouge = Rouge() rouge1_p = [] for r, c in tqdm(zip(refs, cands)): r = " ".join(list(nlp_parser.tokenize(r))).lower() c = " ".join(list(nlp_parser.tokenize(c))).lower() scores = rouge.get_scores(c, r)[0] rouge1_p.append(round(scores['r...
[ "def", "calculate_metric_scores", "(", "cands", ",", "refs", ")", ":", "rouge", "=", "Rouge", "(", ")", "rouge1_p", "=", "[", "]", "for", "r", ",", "c", "in", "tqdm", "(", "zip", "(", "refs", ",", "cands", ")", ")", ":", "r", "=", "\" \"", ".", ...
calculate Rouge-1 precision, Bert precision and Entailment Scores
[ "calculate", "Rouge", "-", "1", "precision", "Bert", "precision", "and", "Entailment", "Scores" ]
[ "\"\"\" calculate Rouge-1 precision, Bert precision\n and Entailment Scores\n \"\"\"", "# calculate rouge-1 precision", "# calculate bert precision", "## calculate entaiment score", "# 'http://nlp1.cs.unc.edu:5003/roberta_mnli_classifier'" ]
[ { "param": "cands", "type": null }, { "param": "refs", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cands", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "refs", "type": null, "docstring": null, "docstring_tokens": ...
ad6f0cb3eb34ef6aad08821e5982cb6876daec11
oriern/SuperPAL
utils.py
[ "MIT" ]
Python
generate_scu
<not_specific>
def generate_scu(sentence, max_scus=5): """ Given a scu sentence retrieve SCUs""" srl = predictor.predict(sentence=sentence['scuSentence']) # ipdb.set_trace() scus = srl['verbs'] scu_list = [] tokens = srl['words'] for scu in scus: tags = scu['tags'] words = [] if no...
Given a scu sentence retrieve SCUs
Given a scu sentence retrieve SCUs
[ "Given", "a", "scu", "sentence", "retrieve", "SCUs" ]
def generate_scu(sentence, max_scus=5): srl = predictor.predict(sentence=sentence['scuSentence']) scus = srl['verbs'] scu_list = [] tokens = srl['words'] for scu in scus: tags = scu['tags'] words = [] if not ("B-ARG1" in tags or "B-ARG2" in tags or "B-ARG0" in tags): ...
[ "def", "generate_scu", "(", "sentence", ",", "max_scus", "=", "5", ")", ":", "srl", "=", "predictor", ".", "predict", "(", "sentence", "=", "sentence", "[", "'scuSentence'", "]", ")", "scus", "=", "srl", "[", "'verbs'", "]", "scu_list", "=", "[", "]", ...
Given a scu sentence retrieve SCUs
[ "Given", "a", "scu", "sentence", "retrieve", "SCUs" ]
[ "\"\"\" Given a scu sentence retrieve SCUs\"\"\"", "# ipdb.set_trace()", "# if \"ARG0\" in tag or \"ARG1\" in tag or \"V\" in tag:", "# select the best SCU", "# sort SCUs based on their length and select middle one", "# print(f\"Best SCU:::{scu_list[int(len(scu_list)/2)]}\")", "# return scu_list[int(len...
[ { "param": "sentence", "type": null }, { "param": "max_scus", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "sentence", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "max_scus", "type": null, "docstring": null, "docstring_to...
ad6f0cb3eb34ef6aad08821e5982cb6876daec11
oriern/SuperPAL
utils.py
[ "MIT" ]
Python
generate_scu_oie
<not_specific>
def generate_scu_oie(sentence, max_scus=5, doc_summ='summ'): """ Given a scu sentence retrieve SCUs""" if doc_summ=='summ': KEY_sent = 'scuSentence' KEY_sent_char_idx = 'scuSentCharIdx' KEY_scu_text = 'scuText' KEY_scu_offset = 'scuOffsets' else: KEY_sent = 'docSentT...
Given a scu sentence retrieve SCUs
Given a scu sentence retrieve SCUs
[ "Given", "a", "scu", "sentence", "retrieve", "SCUs" ]
def generate_scu_oie(sentence, max_scus=5, doc_summ='summ'): if doc_summ=='summ': KEY_sent = 'scuSentence' KEY_sent_char_idx = 'scuSentCharIdx' KEY_scu_text = 'scuText' KEY_scu_offset = 'scuOffsets' else: KEY_sent = 'docSentText' KEY_sent_char_idx = 'docSentCharId...
[ "def", "generate_scu_oie", "(", "sentence", ",", "max_scus", "=", "5", ",", "doc_summ", "=", "'summ'", ")", ":", "if", "doc_summ", "==", "'summ'", ":", "KEY_sent", "=", "'scuSentence'", "KEY_sent_char_idx", "=", "'scuSentCharIdx'", "KEY_scu_text", "=", "'scuText...
Given a scu sentence retrieve SCUs
[ "Given", "a", "scu", "sentence", "retrieve", "SCUs" ]
[ "\"\"\" Given a scu sentence retrieve SCUs\"\"\"", "# ipdb.set_trace()", "#if list is empty", "# if \"ARG0\" in tag or \"ARG1\" in tag or \"V\" in tag:", "# if len(words) <= 3:", "# continue", "# select the best SCU", "# sort SCUs based on their length and select middle one", "# print(f\"Best SC...
[ { "param": "sentence", "type": null }, { "param": "max_scus", "type": null }, { "param": "doc_summ", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "sentence", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "max_scus", "type": null, "docstring": null, "docstring_to...
ad6f0cb3eb34ef6aad08821e5982cb6876daec11
oriern/SuperPAL
utils.py
[ "MIT" ]
Python
generate_scu_oie_multiSent
<not_specific>
def generate_scu_oie_multiSent(sentences, doc_summ='summ'): """ Given a scu sentence retrieve SCUs""" if doc_summ=='summ': KEY_sent = 'scuSentence' KEY_sent_char_idx = 'scuSentCharIdx' KEY_scu_text = 'scuText' KEY_scu_offset = 'scuOffsets' else: KEY_sent = 'docSentTe...
Given a scu sentence retrieve SCUs
Given a scu sentence retrieve SCUs
[ "Given", "a", "scu", "sentence", "retrieve", "SCUs" ]
def generate_scu_oie_multiSent(sentences, doc_summ='summ'): if doc_summ=='summ': KEY_sent = 'scuSentence' KEY_sent_char_idx = 'scuSentCharIdx' KEY_scu_text = 'scuText' KEY_scu_offset = 'scuOffsets' else: KEY_sent = 'docSentText' KEY_sent_char_idx = 'docSentCharIdx...
[ "def", "generate_scu_oie_multiSent", "(", "sentences", ",", "doc_summ", "=", "'summ'", ")", ":", "if", "doc_summ", "==", "'summ'", ":", "KEY_sent", "=", "'scuSentence'", "KEY_sent_char_idx", "=", "'scuSentCharIdx'", "KEY_scu_text", "=", "'scuText'", "KEY_scu_offset", ...
Given a scu sentence retrieve SCUs
[ "Given", "a", "scu", "sentence", "retrieve", "SCUs" ]
[ "\"\"\" Given a scu sentence retrieve SCUs\"\"\"", "#adaptation for srl", "# oies = []", "# for sentence in sentences:", "# oies.append(predictor.predict(sentence = sentence[KEY_sent] ))", "# ipdb.set_trace()", "# if list is empty", "# if sentence[KEY_sent] =='Johnson\\'s new TV show, ``The Magic...
[ { "param": "sentences", "type": null }, { "param": "doc_summ", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "sentences", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "doc_summ", "type": null, "docstring": null, "docstring_t...
ad6f0cb3eb34ef6aad08821e5982cb6876daec11
oriern/SuperPAL
utils.py
[ "MIT" ]
Python
word_aligner
<not_specific>
def word_aligner(sent1, sent2): """ wrapper which calls the monolingual word aligner and gives the alignment scores between sent1 and sent2 """ ## tokenize sent1_tok = " ".join(list(nlp_parser.tokenize(sent1))) sent2_tok = " ".join(list(nlp_parser.tokenize(sent2))) ## create a subproces...
wrapper which calls the monolingual word aligner and gives the alignment scores between sent1 and sent2
wrapper which calls the monolingual word aligner and gives the alignment scores between sent1 and sent2
[ "wrapper", "which", "calls", "the", "monolingual", "word", "aligner", "and", "gives", "the", "alignment", "scores", "between", "sent1", "and", "sent2" ]
def word_aligner(sent1, sent2): sent1_tok = " ".join(list(nlp_parser.tokenize(sent1))) sent2_tok = " ".join(list(nlp_parser.tokenize(sent2))) process = subprocess.Popen(['python2', 'predict_align.py', '--s1', sent1_tok, '--s2', sent2_tok], stdout=subprocess.PIPE, ...
[ "def", "word_aligner", "(", "sent1", ",", "sent2", ")", ":", "sent1_tok", "=", "\" \"", ".", "join", "(", "list", "(", "nlp_parser", ".", "tokenize", "(", "sent1", ")", ")", ")", "sent2_tok", "=", "\" \"", ".", "join", "(", "list", "(", "nlp_parser", ...
wrapper which calls the monolingual word aligner and gives the alignment scores between sent1 and sent2
[ "wrapper", "which", "calls", "the", "monolingual", "word", "aligner", "and", "gives", "the", "alignment", "scores", "between", "sent1", "and", "sent2" ]
[ "\"\"\" wrapper which calls the monolingual\n word aligner and gives the alignment scores between\n sent1 and sent2\n \"\"\"", "## tokenize", "## create a subprocess to call the word aligner", "## parse the output" ]
[ { "param": "sent1", "type": null }, { "param": "sent2", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "sent1", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sent2", "type": null, "docstring": null, "docstring_tokens":...
23d99ad3f669d5fa3e975165921c0678aaacef69
WildMeOrg/wbia-plugin-lca
setup.py
[ "Apache-2.0" ]
Python
parse_version
<not_specific>
def parse_version(fpath='wbia_lca/__init__.py'): """ Statically parse the version number from a python file """ import ast if not exists(fpath): raise ValueError('fpath={!r} does not exist'.format(fpath)) with open(fpath, 'r') as file_: sourcecode = file_.read() pt = ast.p...
Statically parse the version number from a python file
Statically parse the version number from a python file
[ "Statically", "parse", "the", "version", "number", "from", "a", "python", "file" ]
def parse_version(fpath='wbia_lca/__init__.py'): import ast if not exists(fpath): raise ValueError('fpath={!r} does not exist'.format(fpath)) with open(fpath, 'r') as file_: sourcecode = file_.read() pt = ast.parse(sourcecode) class VersionVisitor(ast.NodeVisitor): def visit_...
[ "def", "parse_version", "(", "fpath", "=", "'wbia_lca/__init__.py'", ")", ":", "import", "ast", "if", "not", "exists", "(", "fpath", ")", ":", "raise", "ValueError", "(", "'fpath={!r} does not exist'", ".", "format", "(", "fpath", ")", ")", "with", "open", "...
Statically parse the version number from a python file
[ "Statically", "parse", "the", "version", "number", "from", "a", "python", "file" ]
[ "\"\"\"\n Statically parse the version number from a python file\n\n\n \"\"\"" ]
[ { "param": "fpath", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "fpath", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
728c7dbf236b851027fba228628b4be61ca27366
atreyasha/memory-daemon
mem_daemon_mail.py
[ "MIT" ]
Python
sendMail
null
def sendMail(receiver, sender, password, text, smtp, port, threshold, col_log, selfie): """ Function to send out email based on output of mem_daemon Args: receiver (str): comma-separated receiver email address(es) sender (str): sender email adress password (str): plaint...
Function to send out email based on output of mem_daemon Args: receiver (str): comma-separated receiver email address(es) sender (str): sender email adress password (str): plaintext password for sender (unsafe) text (str): proc string to display for process termination ...
Function to send out email based on output of mem_daemon
[ "Function", "to", "send", "out", "email", "based", "on", "output", "of", "mem_daemon" ]
def sendMail(receiver, sender, password, text, smtp, port, threshold, col_log, selfie): subject_1 = "[Process Termination Notification] " subject_0 = "[RAM Threshold Notification] " pre_text_1 = ('Dear User,\n\n`{}` was terminated on {} as the total used ' 'RAM threshold of {}...
[ "def", "sendMail", "(", "receiver", ",", "sender", ",", "password", ",", "text", ",", "smtp", ",", "port", ",", "threshold", ",", "col_log", ",", "selfie", ")", ":", "subject_1", "=", "\"[Process Termination Notification] \"", "subject_0", "=", "\"[RAM Threshold...
Function to send out email based on output of mem_daemon
[ "Function", "to", "send", "out", "email", "based", "on", "output", "of", "mem_daemon" ]
[ "\"\"\"\n Function to send out email based on output of mem_daemon\n\n Args:\n receiver (str): comma-separated receiver email address(es)\n sender (str): sender email adress\n password (str): plaintext password for sender (unsafe)\n text (str): proc string to display for process te...
[ { "param": "receiver", "type": null }, { "param": "sender", "type": null }, { "param": "password", "type": null }, { "param": "text", "type": null }, { "param": "smtp", "type": null }, { "param": "port", "type": null }, { "param": "threshol...
{ "returns": [], "raises": [], "params": [ { "identifier": "receiver", "type": null, "docstring": "comma-separated receiver email address(es)", "docstring_tokens": [ "comma", "-", "separated", "receiver", "email", "address", "(", ...
68315ff74f5476cf3242794e0083c0b9336c67ab
DTAIEB/Thoughtful-Data-Science
chapter 7/sampleCode4.py
[ "Apache-2.0" ]
Python
start_stream
<not_specific>
def start_stream(queries): "Asynchronously start a new Twitter stream" stream = Stream(auth, RawTweetsListener()) stream.filter(track=queries, async=True) return stream
Asynchronously start a new Twitter stream
Asynchronously start a new Twitter stream
[ "Asynchronously", "start", "a", "new", "Twitter", "stream" ]
def start_stream(queries): stream = Stream(auth, RawTweetsListener()) stream.filter(track=queries, async=True) return stream
[ "def", "start_stream", "(", "queries", ")", ":", "stream", "=", "Stream", "(", "auth", ",", "RawTweetsListener", "(", ")", ")", "stream", ".", "filter", "(", "track", "=", "queries", ",", "async", "=", "True", ")", "return", "stream" ]
Asynchronously start a new Twitter stream
[ "Asynchronously", "start", "a", "new", "Twitter", "stream" ]
[ "\"Asynchronously start a new Twitter stream\"" ]
[ { "param": "queries", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "queries", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
6b265c7c4ba7a60a1de1ab90b63e7f850a2efb4b
DTAIEB/Thoughtful-Data-Science
chapter 5/sampleCode6.py
[ "Apache-2.0" ]
Python
doGetNextData
null
def doGetNextData(self): """Return the next batch of data from the underlying stream. Accepted return values are: 1. (x,y): tuple of list/numpy arrays representing the x and y axis 2. pandas dataframe 3. y: list/numpy array representing the y axis. In this case, the x axis is automatically created ...
Return the next batch of data from the underlying stream. Accepted return values are: 1. (x,y): tuple of list/numpy arrays representing the x and y axis 2. pandas dataframe 3. y: list/numpy array representing the y axis. In this case, the x axis is automatically created 4. pandas serie: similar to ...
Return the next batch of data from the underlying stream. Accepted return values are: 1. (x,y): tuple of list/numpy arrays representing the x and y axis 2. pandas dataframe 3. y: list/numpy array representing the y axis. In this case, the x axis is automatically created 4. pandas serie: similar to #3 5. json 6. geojson...
[ "Return", "the", "next", "batch", "of", "data", "from", "the", "underlying", "stream", ".", "Accepted", "return", "values", "are", ":", "1", ".", "(", "x", "y", ")", ":", "tuple", "of", "list", "/", "numpy", "arrays", "representing", "the", "x", "and",...
def doGetNextData(self): Pass
[ "def", "doGetNextData", "(", "self", ")", ":", "Pass" ]
Return the next batch of data from the underlying stream.
[ "Return", "the", "next", "batch", "of", "data", "from", "the", "underlying", "stream", "." ]
[ "\"\"\"Return the next batch of data from the underlying stream. \n Accepted return values are:\n 1. (x,y): tuple of list/numpy arrays representing the x and y axis\n 2. pandas dataframe\n 3. y: list/numpy array representing the y axis. In this case, the x axis is automatically created\n 4. pandas se...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
f854662f0a97cb28a17cd5869b6efad3bf2ebe36
DTAIEB/Thoughtful-Data-Science
chapter 7/sampleCode17.py
[ "Apache-2.0" ]
Python
start_streaming_dataframe
<not_specific>
def start_streaming_dataframe(output_dir): "Start a Spark Streaming DataFrame from a file source" schema = StructType( [StructField(f["name"], f["type"], True) for f in field_metadata] ) return spark.readStream \ .csv( output_dir, schema=schema, multiL...
Start a Spark Streaming DataFrame from a file source
Start a Spark Streaming DataFrame from a file source
[ "Start", "a", "Spark", "Streaming", "DataFrame", "from", "a", "file", "source" ]
def start_streaming_dataframe(output_dir): schema = StructType( [StructField(f["name"], f["type"], True) for f in field_metadata] ) return spark.readStream \ .csv( output_dir, schema=schema, multiLine = True, timestampFormat = 'EEE MMM dd kk:mm...
[ "def", "start_streaming_dataframe", "(", "output_dir", ")", ":", "schema", "=", "StructType", "(", "[", "StructField", "(", "f", "[", "\"name\"", "]", ",", "f", "[", "\"type\"", "]", ",", "True", ")", "for", "f", "in", "field_metadata", "]", ")", "return...
Start a Spark Streaming DataFrame from a file source
[ "Start", "a", "Spark", "Streaming", "DataFrame", "from", "a", "file", "source" ]
[ "\"Start a Spark Streaming DataFrame from a file source\"" ]
[ { "param": "output_dir", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "output_dir", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
1a0aae4684fdc8a4e95c539d2103a6ccb6746187
DTAIEB/Thoughtful-Data-Science
chapter 7/sampleCode33.py
[ "Apache-2.0" ]
Python
start_streaming_dataframe
<not_specific>
def start_streaming_dataframe(): "Start a Spark Streaming DataFrame from a Kafka Input source" schema = StructType( [StructField(f["name"], f["type"], True) for f in field_metadata] ) kafka_options = { "kafka.ssl.protocol":"TLSv1.2", "kafka.ssl.enabled.protocols":"TLSv1.2", ...
Start a Spark Streaming DataFrame from a Kafka Input source
Start a Spark Streaming DataFrame from a Kafka Input source
[ "Start", "a", "Spark", "Streaming", "DataFrame", "from", "a", "Kafka", "Input", "source" ]
def start_streaming_dataframe(): schema = StructType( [StructField(f["name"], f["type"], True) for f in field_metadata] ) kafka_options = { "kafka.ssl.protocol":"TLSv1.2", "kafka.ssl.enabled.protocols":"TLSv1.2", "kafka.ssl.endpoint.identification.algorithm":"HTTPS", ...
[ "def", "start_streaming_dataframe", "(", ")", ":", "schema", "=", "StructType", "(", "[", "StructField", "(", "f", "[", "\"name\"", "]", ",", "f", "[", "\"type\"", "]", ",", "True", ")", "for", "f", "in", "field_metadata", "]", ")", "kafka_options", "=",...
Start a Spark Streaming DataFrame from a Kafka Input source
[ "Start", "a", "Spark", "Streaming", "DataFrame", "from", "a", "Kafka", "Input", "source" ]
[ "\"Start a Spark Streaming DataFrame from a Kafka Input source\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
dcada2d2a62be09e92fc5640296db9fe3d650817
DTAIEB/Thoughtful-Data-Science
chapter 7/sampleCode18.py
[ "Apache-2.0" ]
Python
start_parquet_streaming_query
<not_specific>
def start_parquet_streaming_query(csv_sdf): """ Create and run a streaming query from a Structured DataFrame outputing the results into a parquet database """ streaming_query = csv_sdf \ .writeStream \ .format("parquet") \ .option("path", os.path.join(root_dir, "output_parquet")) ...
Create and run a streaming query from a Structured DataFrame outputing the results into a parquet database
Create and run a streaming query from a Structured DataFrame outputing the results into a parquet database
[ "Create", "and", "run", "a", "streaming", "query", "from", "a", "Structured", "DataFrame", "outputing", "the", "results", "into", "a", "parquet", "database" ]
def start_parquet_streaming_query(csv_sdf): streaming_query = csv_sdf \ .writeStream \ .format("parquet") \ .option("path", os.path.join(root_dir, "output_parquet")) \ .trigger(processingTime="2 seconds") \ .option("checkpointLocation", os.path.join(root_dir, "output_chkpt")) \ ....
[ "def", "start_parquet_streaming_query", "(", "csv_sdf", ")", ":", "streaming_query", "=", "csv_sdf", ".", "writeStream", ".", "format", "(", "\"parquet\"", ")", ".", "option", "(", "\"path\"", ",", "os", ".", "path", ".", "join", "(", "root_dir", ",", "\"out...
Create and run a streaming query from a Structured DataFrame outputing the results into a parquet database
[ "Create", "and", "run", "a", "streaming", "query", "from", "a", "Structured", "DataFrame", "outputing", "the", "results", "into", "a", "parquet", "database" ]
[ "\"\"\"\n Create and run a streaming query from a Structured DataFrame \n outputing the results into a parquet database\n \"\"\"" ]
[ { "param": "csv_sdf", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "csv_sdf", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
fda17cb91688d92c692982803b574cd2ad815012
DTAIEB/Thoughtful-Data-Science
chapter 7/sampleCode1.py
[ "Apache-2.0" ]
Python
flush_buffer_if_needed
null
def flush_buffer_if_needed(self): "Check the buffer capacity and write to a new file if needed" length = len(self.buffered_data) if length > 0 and length % 10 == 0: with open(os.path.join( output_dir, "tweets{}.csv".format(self.counter)), "w") as fs: self.counter += 1...
Check the buffer capacity and write to a new file if needed
Check the buffer capacity and write to a new file if needed
[ "Check", "the", "buffer", "capacity", "and", "write", "to", "a", "new", "file", "if", "needed" ]
def flush_buffer_if_needed(self): length = len(self.buffered_data) if length > 0 and length % 10 == 0: with open(os.path.join( output_dir, "tweets{}.csv".format(self.counter)), "w") as fs: self.counter += 1 csv_writer = csv.DictWriter( fs, fieldnames = fieldna...
[ "def", "flush_buffer_if_needed", "(", "self", ")", ":", "length", "=", "len", "(", "self", ".", "buffered_data", ")", "if", "length", ">", "0", "and", "length", "%", "10", "==", "0", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "o...
Check the buffer capacity and write to a new file if needed
[ "Check", "the", "buffer", "capacity", "and", "write", "to", "a", "new", "file", "if", "needed" ]
[ "\"Check the buffer capacity and write to a new file if needed\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
94e1d7c7ccff98c0726cf62631ddb3ad4f159f0d
DTAIEB/Thoughtful-Data-Science
chapter 7/sampleCode16.py
[ "Apache-2.0" ]
Python
start_stream
<not_specific>
def start_stream(queries): "Asynchronously start a new Twitter stream" stream = Stream(auth, RawTweetsListener()) stream.filter(track=queries, languages=["en"], async=True) return stream
Asynchronously start a new Twitter stream
Asynchronously start a new Twitter stream
[ "Asynchronously", "start", "a", "new", "Twitter", "stream" ]
def start_stream(queries): stream = Stream(auth, RawTweetsListener()) stream.filter(track=queries, languages=["en"], async=True) return stream
[ "def", "start_stream", "(", "queries", ")", ":", "stream", "=", "Stream", "(", "auth", ",", "RawTweetsListener", "(", ")", ")", "stream", ".", "filter", "(", "track", "=", "queries", ",", "languages", "=", "[", "\"en\"", "]", ",", "async", "=", "True",...
Asynchronously start a new Twitter stream
[ "Asynchronously", "start", "a", "new", "Twitter", "stream" ]
[ "\"Asynchronously start a new Twitter stream\"" ]
[ { "param": "queries", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "queries", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
f648fa7f2db64201644eb5a37143ea7885e9852d
vliz-be-opsci/pykg2tbl
pykg2tbl/service.py
[ "MIT" ]
Python
as_csv
null
def as_csv(self, fileoutputlocation:str, sep:str=","): """ convert and outputs csv file from result query :param fileoutputlocation: location + filename where the csv should be written to. :param sep: delimiter that should be used for writing the csv file. """ #...
convert and outputs csv file from result query :param fileoutputlocation: location + filename where the csv should be written to. :param sep: delimiter that should be used for writing the csv file.
convert and outputs csv file from result query
[ "convert", "and", "outputs", "csv", "file", "from", "result", "query" ]
def as_csv(self, fileoutputlocation:str, sep:str=","): f = open(fileoutputlocation, 'w', newline="") writer = csv.DictWriter(f, self._data[0].keys(),delimiter=sep) for row in self._data: writer.writerow(row) f.close()
[ "def", "as_csv", "(", "self", ",", "fileoutputlocation", ":", "str", ",", "sep", ":", "str", "=", "\",\"", ")", ":", "f", "=", "open", "(", "fileoutputlocation", ",", "'w'", ",", "newline", "=", "\"\"", ")", "writer", "=", "csv", ".", "DictWriter", "...
convert and outputs csv file from result query
[ "convert", "and", "outputs", "csv", "file", "from", "result", "query" ]
[ "\"\"\"\n convert and outputs csv file from result query\n \n :param fileoutputlocation: location + filename where the csv should be written to.\n :param sep: delimiter that should be used for writing the csv file. \n \"\"\"", "# open the file in the write mode", "# create the...
[ { "param": "self", "type": null }, { "param": "fileoutputlocation", "type": "str" }, { "param": "sep", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "fileoutputlocation", "type": "str", "docstring": "location + filena...