00001
00002 import numpy as np, math
00003 import sys
00004 import os
00005 from threading import RLock
00006 import threading
00007
00008 import roslib; roslib.load_manifest('hrl_pr2_lib')
00009 import rospy
00010
00011 import actionlib
00012
00013 from std_msgs.msg import String
00014 from geometry_msgs.msg import Point, Pose, Quaternion, PoseStamped, PointStamped
00015
00016 import random
00017 import hrl_lib.util
00018 from hrl_lib.rutils import GenericListener
00019 import hrl_lib.viz as viz
00020 from hrl_lib import tf_utils
00021 from hrl_lib.keyboard_input import KeyboardInput
00022 from hrl_lib.transforms import rotX, rotY, rotZ
00023 from hrl_lib.data_process import signal_list_variance
00024 from tf.transformations import *
00025 from hrl_pr2_lib.pr2_arms import PR2Arms
00026 from hrl_pr2_lib.perception_monitor import ArmPerceptionMonitor, generate_mean_grasp
00027 from visualization_msgs.msg import MarkerArray, Marker
00028 import dynamic_reconfigure.client
00029 import tf
00030
00031
00032 from hrl_pr2_lib.hrl_controller_manager import HRLControllerManager as ControllerManager
00033 from pr2_controllers_msgs.msg import JointTrajectoryGoal, PointHeadAction, PointHeadGoal
00034 import object_manipulator.convert_functions as cf
00035 from object_manipulator.cluster_bounding_box_finder import ClusterBoundingBoxFinder
00036 from tabletop_object_detector.srv import TabletopDetection
00037 from tabletop_object_detector.msg import TabletopDetectionResult
00038
00039 from laser_interface.pkg import CURSOR_TOPIC, MOUSE_DOUBLE_CLICK_TOPIC
00040
00041
00042
00043
00044 NUM_X = 7
00045 NUM_Y = 11
00046 NUM_N = 3
00047 NUM_ROT = 6
00048
00049 RECT = ((0.45, 0.25), (0.70, -0.25))
00050
00051 ARM = 0
00052 if ARM == 0:
00053 armc = 'r'
00054 else:
00055 armc = 'l'
00056 HOVER_Z = -0.10
00057 GRASP_DIST = 0.30
00058 GRASP_VELOCITY = 0.28
00059 GRIPPER_POINT = np.array([0.23, 0.0, 0.0])
00060 JOINTS_BIAS = [0., -.25, -1., 0., 0., 0.5, 0.]
00061 BIAS_RADIUS = 0.012
00062
00063 GRASP_TIME = 2.0
00064 SETUP_VELOCITY = 0.4
00065
00066 STD_DEV = 2.3
00067 NOISE_DEV = 0.0
00068 DETECT_ERROR = -0.02
00069 STD_DEV_DICT = { "accelerometer" : np.array([2.4, 2.9, 2.9]),
00070 "joint_angles" : np.array([2.8, 2.8, 3.8, 2.8, 400.0, 1.25, 400.0]),
00071 "joint_efforts" : np.array([30.0, 15.0, 11.0, 16.0, 12.0, 3.0, 125.0]),
00072 "joint_velocities" : np.array([3.4, 6.4, 18.4, 3.4, 3.4, 3.4, 3.4]),
00073 "r_finger_periph_pressure" : np.array([60.0]*6),
00074 "r_finger_pad_pressure" : np.array([60.0]*15),
00075 "l_finger_periph_pressure" : np.array([60.0]*6),
00076 "l_finger_pad_pressure" : np.array([60.0]*15) }
00077 TOL_THRESH_DICT = { "accelerometer" : np.array([0.3, 0.3, 0.3]),
00078 "joint_velocities" : np.array([0.45]*7),
00079 "joint_angles" : np.array([0.05, 0.05, 0.05, 0.05, 0.05, 0.04, 0.05]),
00080 "joint_efforts" : np.array([3.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]),
00081 "r_finger_periph_pressure" : np.array([10.0]*6),
00082 "r_finger_pad_pressure" : np.array([10.0]*15),
00083 "l_finger_periph_pressure" : np.array([10.0]*6),
00084 "l_finger_pad_pressure" : np.array([10.0]*15) }
00085 PERCEPT_MON_LIST = None
00086 PERCEPT_GRASP_LIST = None
00087 PRESSURE_LIST =["r_finger_periph_pressure",
00088 "r_finger_pad_pressure",
00089 "l_finger_periph_pressure",
00090 "l_finger_pad_pressure"]
00091
00092
00093 MONITOR_WINDOW = 50
00094
00095 PICKLES_LOC = "//src//hrl_pr2_lib//pickles//"
00096 GRASP_CONFIGS_FILE = "grasp_configs.pickle"
00097 GRASP_DATA_FILE = "grasp_data.pickle"
00098 GRASP_MODELS_FILE = "grasp_models.pickle"
00099 GRASP_MODELS_TRIMMED_FILE = "grasp_models_trimmed.pickle"
00100 ZEROS_FILE = "current_zeros.pickle"
00101 SQR_DIFF_MAP = "sqr_diff_map.pickle"
00102 GRASP_IND_PREFIX = "model_indexed//grasp_model"
00103 GRASP_INDEX_FILE = "model_indexed//grasp_model_index.pickle"
00104 GRASP_DATA_INDEX_FILE = "data_indexed//grasp_data_index.pickle"
00105 GRASP_DATA_PREFIX = "data_indexed//grasp_data"
00106 TEST_DATA_FILE = "test_data.pickle"
00107
00108 node_name = "simple_grasp_learner"
00109
00110 def log(str):
00111 rospy.loginfo(node_name + ": " + str)
00112
00113 def load_pickle(fn):
00114 global PACKAGE_LOC
00115 return hrl_lib.util.load_pickle(PACKAGE_LOC + PICKLES_LOC + fn)
00116
00117 def save_pickle(p, fn):
00118 global PACKAGE_LOC
00119 hrl_lib.util.save_pickle(p, PACKAGE_LOC + PICKLES_LOC + fn)
00120
00121 def file_exists(fn):
00122 global PACKAGE_LOC
00123 return os.path.exists(PACKAGE_LOC + PICKLES_LOC + fn)
00124
00125 def setup_package_loc():
00126 global PACKAGE_LOC
00127 import os
00128 grep = os.popen("rospack find hrl_pr2_lib|grep hrl_pr2_lib")
00129 PACKAGE_LOC = grep.readlines()[0].rstrip()
00130
00131 def save_parameters(param_filename):
00132 params = { "ARM" : ARM,
00133 "NUM_X" : NUM_X,
00134 "NUM_Y" : NUM_Y,
00135 "NUM_N" : NUM_N,
00136 "NUM_ROT" : NUM_ROT,
00137 "RECT" : RECT,
00138 "HOVER_Z" : HOVER_Z,
00139 "GRASP_DIST" : GRASP_DIST,
00140 "GRASP_TIME" : GRASP_TIME,
00141 "GRASP_VELOCITY" : GRASP_VELOCITY,
00142 "SETUP_VELOCITY" : SETUP_VELOCITY,
00143 "STD_DEV" : STD_DEV,
00144 "NOISE_DEV" : NOISE_DEV,
00145 "GRIPPER_POINT" : GRIPPER_POINT,
00146 "JOINTS_BIAS" : JOINTS_BIAS,
00147 "BIAS_RADIUS" : BIAS_RADIUS,
00148 "DETECT_ERROR" : DETECT_ERROR,
00149 "STD_DEV_DICT" : STD_DEV_DICT,
00150 "PICKLES_LOC" : PICKLES_LOC,
00151 "GRASP_CONFIGS_FILE" : GRASP_CONFIGS_FILE,
00152 "GRASP_DATA_FILE" : GRASP_DATA_FILE,
00153 "GRASP_MODELS_FILE" : GRASP_MODELS_FILE,
00154 "ZEROS_FILE" : ZEROS_FILE,
00155 "SQR_DIFF_MAP" : SQR_DIFF_MAP,
00156 "GRASP_IND_PREFIX" : GRASP_IND_PREFIX,
00157 "GRASP_INDEX_FILE" : GRASP_INDEX_FILE,
00158 "TEST_DATA_FILE" : TEST_DATA_FILE,
00159 "MONITOR_WINDOW" : MONITOR_WINDOW,
00160 "PERCEPT_MON_LIST" : PERCEPT_MON_LIST }
00161 save_pickle(params, param_filename)
00162
00163 def load_parameters():
00164 params = load_pickle(param_filename)
00165 for k in params:
00166 globals()[k] = params[k]
00167
00168
00169
00170
00171
00172
00173
00174
00175
00176 def transform_in_frame(pos, quat, off_point):
00177 invquatmat = np.mat(quaternion_matrix(quat))
00178 invquatmat[0:3,3] = np.mat(pos).T
00179 trans = np.matrix([off_point[0],off_point[1],off_point[2],1.]).T
00180 transpos = invquatmat * trans
00181 return transpos.T.A[0,0:3]
00182
00183
00184
00185
00186
00187
00188
00189 def get_xyr_list():
00190 grasp_xyr_list = []
00191 for x in np.linspace(RECT[0][0], RECT[1][0], NUM_X):
00192 for y in np.linspace(RECT[0][1], RECT[1][1], NUM_Y):
00193 for r in np.linspace(0., np.pi, NUM_ROT+1)[0:-1]:
00194 grasp_xyr_list += [(x,y,r)]
00195 return grasp_xyr_list
00196
00197
00198 def create_gripper_pose(x, y, z, quat):
00199 point = [x, y, z]
00200 point = transform_in_frame(point, np.array(quat), -GRIPPER_POINT).tolist()
00201 pose = point + quat
00202 goal_pose = cf.create_pose_stamped(pose, "torso_lift_link")
00203 goal_pose.header.stamp = rospy.Time.now()
00204 return goal_pose
00205
00206 def get_gripper_pose(gripper_rot):
00207 gripper_rot = normalize_rot(gripper_rot)
00208 quat1 = quaternion_about_axis(np.pi/2., (0, 1, 0))
00209 quat2 = quaternion_about_axis(gripper_rot, (0, 0, 1))
00210 quat = quaternion_multiply(quat2, quat1)
00211 return quat
00212
00213 def create_goal_pose(x, y, z, gripper_pose):
00214 point = [x, y, z]
00215 point = transform_in_frame(point, gripper_pose, -GRIPPER_POINT).tolist()
00216 pose = point + gripper_pose.tolist()
00217 goal_pose = cf.create_pose_stamped(pose, "torso_lift_link")
00218 goal_pose.header.stamp = rospy.Time.now()
00219 return goal_pose
00220
00221 def move_to_grasp_pos(cm, grasp_pose, block=True):
00222 grasp_pose.header.stamp = rospy.Time.now()
00223 cm.move_cartesian_ik(grasp_pose, collision_aware = False, blocking = block,
00224 step_size = .005, pos_thres = .02, rot_thres = .1,
00225 settling_time = rospy.Duration(1.0),
00226 vel = SETUP_VELOCITY)
00227
00228 def upward_lift(cm, grasp_pose, block=True):
00229 grasp_pose.header.stamp = rospy.Time.now()
00230 cm.move_cartesian_ik(grasp_pose, collision_aware = False, blocking = block,
00231 step_size = .005, pos_thres = .02, rot_thres = .1,
00232 settling_time = rospy.Duration(1.0),
00233 vel = GRASP_VELOCITY,
00234 joints_bias = -np.array(JOINTS_BIAS), bias_radius = BIAS_RADIUS)
00235
00236 def downward_grasp(cm, goal_pose, block=True):
00237 goal_pose.header.stamp = rospy.Time.now()
00238 return cm.move_cartesian_ik(goal_pose, collision_aware = False, blocking = block,
00239 step_size = .005, pos_thres = .02, rot_thres = .1,
00240 settling_time = rospy.Duration(GRASP_TIME),
00241 joints_bias = JOINTS_BIAS, bias_radius = BIAS_RADIUS,
00242 vel = GRASP_VELOCITY)
00243
00244
00245 def save_grasp_configurations():
00246 arms = PR2Arms()
00247
00248 grasp_xyr_list = get_xy_list()
00249 grasp_configs = []
00250 setup = False
00251
00252 for xy in grasp_xyr_list:
00253
00254
00255
00256
00257
00258
00259
00260
00261 if arms.can_move_arm(ARM, [xy[0], xy[1], HOVER_Z], rotY(np.pi / 2.)):
00262 print "Moving to pos (%1.2f, %1.2f)" % xy
00263 arms.grasp_biased_move_arm(ARM, [xy[0], xy[1], HOVER_Z], rotY(np.pi / 2.), 3.)
00264 arms.wait_for_arm_completion(ARM)
00265 rospy.sleep(0.5)
00266 angs = arms.get_joint_angles(ARM)
00267 grasp_configs += [(xy, angs)]
00268 setup = False
00269 else:
00270 print "Can't move to to pos (%1.2f, %1.2f)" % xy
00271
00272
00273 save_pickle(grasp_configs, GRASP_CONFIGS_FILE)
00274 print "Configurations:"
00275 print_configs(grasp_configs)
00276
00277 def print_configs(grasp_configs):
00278 for config in grasp_configs:
00279 if config[1] is not None:
00280 print "(%1.2f, %1.2f):" % config[0], ", ".join(["%1.2f" % x for x in config[1]])
00281 else:
00282 print "(%1.2f, %1.2f):" % config[0], "No config"
00283
00284 def trim_bad_grasps(filename):
00285 grasp_configs = load_pickle(filename)
00286 print_configs(grasp_configs)
00287 new_configs = []
00288 for config in grasp_configs:
00289 if config[1] is not None:
00290 new_configs += [config]
00291 print_configs(new_configs)
00292 save_pickle(new_configs, filename)
00293
00294 def pauser(ki):
00295 if ki.kbhit():
00296 ch = ki.getch()
00297 if ch == 'p':
00298 print "PAUSED"
00299 while not rospy.is_shutdown() and ch != 'c':
00300 ch = ki.getch()
00301 rospy.sleep(0.1)
00302 print "CONTINUING"
00303
00304 def write_index_file(prefix = GRASP_DATA_PREFIX, index = GRASP_DATA_INDEX_FILE):
00305 grasp_xyr_list = get_xyr_list()
00306 grasps = []
00307 for xyr in grasp_xyr_list:
00308 filename = prefix + "%04d-%04d-%04d.pickle" % (int(xyr[0]*100),int(xyr[1]*100),int(xyr[2]*100))
00309 if file_exists(filename):
00310 grasps.append([xyr, filename])
00311 save_pickle(grasps, index)
00312
00313 def collect_grasp_data(ki, generate_models=False, skip_grasp=False):
00314 cm = ControllerManager(armc)
00315 apm = ArmPerceptionMonitor(ARM, tf_listener=cm.tf_listener, percept_mon_list=None)
00316
00317
00318
00319
00320
00321
00322
00323 grasp_xyr_list = get_xyr_list()
00324 grasp_data = []
00325 grasp_index = []
00326
00327 print "Opening gripper"
00328 cm.command_gripper(0.08, -1.0, False)
00329 cm.gripper_action_client.wait_for_result(rospy.Duration(4.0))
00330
00331 for c, xyr in enumerate(grasp_xyr_list):
00332
00333
00334 if rospy.is_shutdown():
00335 return
00336 print "---------------------------------------------------"
00337 print "%1.2f completion" % (float(c) / len(grasp_xyr_list))
00338 zeros = None
00339
00340 for i in range(NUM_N):
00341 pauser(ki)
00342
00343
00344 print "Moving to grasp position (%1.2f, %1.2f, %1.2f)" % xyr
00345 grasp_pose = create_goal_pose(xyr[0], xyr[1], HOVER_Z, get_gripper_pose(xyr[2]))
00346 setup_result = cm.move_arm_pose_biased(grasp_pose, JOINTS_BIAS, SETUP_VELOCITY,
00347 blocking = True)
00348 rospy.sleep(0.5)
00349 if skip_grasp:
00350 break
00351 if setup_result is not None:
00352 if zeros is None:
00353
00354 rospy.sleep(0.5)
00355 zeros = apm.get_zeros(0.6)
00356
00357 goal_pose = create_goal_pose(xyr[0], xyr[1],
00358 HOVER_Z - GRASP_DIST, get_gripper_pose(xyr[2]))
00359
00360 apm.start_training()
00361
00362 print "Moving arm down"
00363 sttime = rospy.Time.now().to_sec()
00364 result = downward_grasp(cm, goal_pose, block=True)
00365 endtime = rospy.Time.now().to_sec()
00366 print "dur:", endtime - sttime
00367 print result
00368 print "Finished moving arm"
00369 length = apm.stop_training()
00370 print "length:", length
00371 print "len/dur", length / (endtime - sttime)
00372 rospy.sleep(0.5)
00373 else:
00374 break
00375
00376
00377 if setup_result is None or skip_grasp:
00378 continue
00379
00380 fn = None
00381 if result != "no solution" and generate_models:
00382 models = apm.generate_models()
00383 else:
00384 models = None
00385 if result != "no solution":
00386
00387 fn = save_grasp([xyr, None, apm.datasets, models, zeros], GRASP_DATA_PREFIX)
00388 else:
00389 print "Grasp Failed, not adding data"
00390 grasp_index.append([xyr, fn])
00391 apm.clear_vars()
00392
00393 print "Saving Data"
00394
00395 save_pickle(grasp_index, GRASP_DATA_INDEX_FILE)
00396 print "Data save complete"
00397 return None
00398
00399 def load_data_and_generate(grasp_data):
00400 ret = []
00401 n = 0
00402 for grasp in grasp_data:
00403 apm = ArmPerceptionMonitor(ARM, percept_mon_list=PERCEPT_MON_LIST)
00404 apm.datasets = grasp[2]
00405 apm.generate_models()
00406 ret += [(grasp[0], grasp[1], grasp[2], apm.models, grasp[4])]
00407 n += 1
00408 print "Generated %d models" % (n)
00409
00410 return ret
00411
00412 def generate_space_models():
00413 mean_grasps = []
00414 grasps = []
00415 grasp_xyr_list = get_xyr_list()
00416 for grasp in grasp_data:
00417 mean_grasps.append([grasp[0], generate_mean_grasp(grasp[2])])
00418
00419 def dist1(o):
00420 return np.fabs(o[0][0] - x) + np.fabs(o[0][1] - y)
00421
00422 xs = (RECT[1][0] - RECT[0][0]) / (NUM_X - 1)
00423 ys = (RECT[0][1] - RECT[1][1]) / (NUM_Y - 1)
00424 rs = np.pi / NUM_R
00425 st = [RECT[0][0] + xs/2., RECT[1][1] + ys/2., rs]
00426 num_gen = 0
00427 for i in range(NUM_X - 1):
00428 for j in range(NUM_Y - 1):
00429 for k in range(NUM_R):
00430 print "Number of models generated:", num_gen
00431 num_gen += 1
00432 pauser()
00433 close_models = []
00434 def dist1(o):
00435 return np.fabs(o[0][0] - st[0]) + np.fabs(o[0][1] - st[1])
00436 def rotdist(o):
00437 if np.allclose(o[0][2], 0.0):
00438
00439 return min(np.fabs(np.pi - st[2]), np.fabs(0. - st[2]))
00440 else:
00441 return np.fabs(o[0][2] - st[2])
00442 for i, dist in enumerate(map(dist1, mean_grasps)):
00443 if np.allclose(dist, (xs/2. + ys/2.), 0.0001) and np.allclose(rotdist(xyr_index[i]), rs/2., 0.0001):
00444 close_models += [mean_grasps[i]]
00445
00446 if len(close_models) < 5:
00447 print "Rejecting %1.2f, %1.2f, %1.2f with number close models = %d", (
00448 st[0], st[1], st[2], len(close_models))
00449 continue
00450
00451
00452 models = {}
00453 for p in close_models:
00454 lens = [len(m) for m in close_models[p]]
00455 max_len = np.max(lens)
00456 signals = zip(*close_models[p])
00457 ammodels, vmodels = [], []
00458 for signal in signals:
00459 avg_means_model = np.array([0.] * max_len)
00460 sqr_means_model = np.array([0.] * max_len)
00461 for i in range(max_len):
00462 n = 0
00463 for j in range(len(signal)):
00464 if i < len(signal[j]):
00465 avg_means_model[i] += close_models[j][i]
00466 sqr_means_model[i] += close_models[j][i] ** 2
00467 n += 1
00468 avg_means_model[i] /= n
00469 sqr_means_model[i] /= n
00470
00471 vars_model = signal_smooth(sqr_means_model, 30) - avg_means_model
00472 ammodels.append(avg_means_model)
00473 vmodels.append(vars_model)
00474
00475 models[p] = {}
00476 models[p]["mean"] = zip(*ammodels)
00477 models[p]["variance"] = zip(*vmodels)
00478
00479 grasp = [st, None, None, models, None]
00480 save_grasp(grasp, GRASP_IND_PREFIX)
00481
00482 st[2] += rs
00483 st[1] += ys
00484 st[0] += xs
00485
00486
00487
00488
00489
00490
00491
00492
00493
00494
00495
00496
00497
00498 def save_current_zeros(filename=ZEROS_FILE):
00499 apm = ArmPerceptionMonitor(ARM, percept_mon_list=PERCEPT_MON_LIST)
00500 zeros = apm.get_zeros()
00501 print "Zeros:", zeros
00502 save_pickle(zeros, filename)
00503
00504 def load_current_zeros(filename=ZEROS_FILE):
00505 return load_pickle(filename)
00506
00507 def is_obj_in_gripper(cm=None):
00508 if cm is None:
00509 cm = ControllerManager(armc)
00510 return cm.get_current_gripper_opening() > 0.01
00511
00512 def open_gripper(cm=None, blocking = False):
00513 if cm is None:
00514 cm = ControllerManager(armc)
00515 cm.command_gripper(0.08, -1.0, False)
00516 if blocking:
00517 cm.gripper_action_client.wait_for_result(rospy.Duration(4.0))
00518
00519 def perform_grasp(x, y, z=None, gripper_rot = np.pi / 2., grasp=None, is_place=False,
00520 is_grasp=True, collide = True, return_pose=True,
00521 zeros = None, grasp_data=None, cm=None, apm=None):
00522 print "Performing grasp (%1.2f, %1.2f), rotation: %1.2f" % (x, y, gripper_rot)
00523 gripper_rot = normalize_rot(gripper_rot)
00524
00525 if cm is None:
00526 cm = ControllerManager(armc)
00527 if apm is None:
00528 apm = ArmPerceptionMonitor(ARM, percept_mon_list=PERCEPT_GRASP_LIST)
00529
00530 if grasp is None:
00531 grasp = get_grasp_model(x, y, gripper_rot, grasp_data = grasp_data)
00532
00533
00534
00535
00536
00537
00538 print "Beginning grasp"
00539
00540 result = "no solution"
00541 iters = 0
00542 while True:
00543
00544 print "Moving to initial grasp position"
00545
00546
00547
00548 grasp_pose = create_goal_pose(x, y, HOVER_Z, get_gripper_pose(gripper_rot))
00549 cm.move_arm_pose_biased(grasp_pose, JOINTS_BIAS, SETUP_VELOCITY, blocking = False)
00550 if not is_place and is_grasp:
00551
00552 print "Opening gripper"
00553 cm.command_gripper(0.08, -1.0, False)
00554 cm.gripper_action_client.wait_for_result(rospy.Duration(2.0))
00555 cm.wait_joint_trajectory_done()
00556 rospy.sleep(0.5)
00557
00558
00559
00560
00561
00562 goal_pose = create_goal_pose(x, y, HOVER_Z - GRASP_DIST, get_gripper_pose(gripper_rot))
00563
00564 class Collision():
00565 def __init__(self):
00566 self.collided = False
00567
00568 def on_collision(self):
00569 print "Collision!"
00570 self.collided = True
00571 while not cm.check_joint_trajectory_done():
00572 cm.joint_action_client.cancel_all_goals()
00573 rospy.sleep(0.01)
00574 if rospy.is_shutdown():
00575 return None
00576 col = Collision()
00577 def rotate_acceleration(data):
00578 return data
00579 data -= zeros["accelerometer"]
00580 a = gripper_rot
00581 data[1] = np.cos(a) * data[1] - np.sin(a) * data[2]
00582 data[2] = np.sin(a) * data[1] + np.cos(a) * data[2]
00583 data += zeros["accelerometer"]
00584 return data
00585
00586 transforms = { "accelerometer" : rotate_acceleration }
00587
00588 while not rospy.is_shutdown() and len(grasp) < 5:
00589 rospy.sleep(0.1)
00590
00591 apm.begin_monitoring(grasp[3],
00592 model_zeros = grasp[4],
00593 contingency=col.on_collision, window_size=MONITOR_WINDOW,
00594 current_zeros=zeros, std_dev_default=STD_DEV,
00595 std_dev_dict = STD_DEV_DICT,
00596 tol_thresh_dict = TOL_THRESH_DICT,
00597 noise_dev_default=NOISE_DEV, collide=collide,
00598 transform_dict = transforms)
00599
00600 print "Moving arm down"
00601 startt = rospy.Time.now().to_sec()
00602 result = downward_grasp(cm, goal_pose, block = False)
00603 print "Grasp result:", result
00604 if result == "no solution":
00605
00606 apm.end_monitoring()
00607 dx = random.uniform(-0.015, 0.015)
00608 dy = random.uniform(-0.015, 0.015)
00609 x += dx
00610 y += dy
00611 iters += 1
00612
00613 if iters == 4:
00614 print "Cannot find IK solution!!!" * 8
00615 return
00616 else:
00617 continue
00618 else:
00619 break
00620
00621 if z is None:
00622 while not cm.check_joint_trajectory_done():
00623 if col.collided:
00624 cm.joint_action_client.cancel_all_goals()
00625 rospy.sleep(0.01)
00626 if rospy.is_shutdown():
00627 return None
00628 else:
00629 while not cm.check_joint_trajectory_done():
00630 if col.collided:
00631 cm.joint_action_client.cancel_all_goals()
00632 wrist_pose = cm.get_current_wrist_pose_stamped("torso_lift_link")
00633 p = wrist_pose.pose.position
00634 o = wrist_pose.pose.orientation
00635 affector_pos = transform_in_frame([p.x, p.y, p.z],
00636 [o.x, o.y, o.z, o.w], GRIPPER_POINT)
00637 if affector_pos[2] <= z:
00638 print "Reached z position"
00639 print "Affector position:", affector_pos
00640 while not cm.check_joint_trajectory_done():
00641 cm.joint_action_client.cancel_all_goals()
00642 rospy.sleep(0.01)
00643 break
00644 rospy.sleep(0.01)
00645 if rospy.is_shutdown():
00646 return None
00647
00648 endt = rospy.Time.now().to_sec()
00649 print "Grasp duration:", startt - endt
00650 print "Finished moving arm"
00651
00652 avg_list = apm.end_monitoring()
00653 rospy.sleep(0.1)
00654 global z_sum
00655 for k in apm.z_avg:
00656 if not k in z_sum:
00657 z_sum[k] = np.copy(apm.z_avg[k])
00658 else:
00659 z_sum[k] += apm.z_avg[k]
00660
00661 if not is_place and is_grasp:
00662 print "Closing gripper"
00663 cm.command_gripper(0.0, 30.0, True)
00664 print "Gripper closed"
00665 elif is_place:
00666 print "Opening gripper"
00667 cm.command_gripper(0.08, -1.0, True)
00668 print "Gripper opened"
00669
00670 if return_pose and is_grasp:
00671 print "Moving back to grasp position"
00672 cm.move_arm_pose_biased(grasp_pose, JOINTS_BIAS, SETUP_VELOCITY, blocking = True)
00673
00674 print "Grasp complete!"
00675
00676 return grasp, avg_list, col.collided, zeros
00677
00678
00679
00680
00681
00682
00683
00684
00685
00686
00687
00688
00689
00690
00691
00692
00693
00694
00695
00696
00697
00698
00699
00700
00701
00702
00703
00704
00705
00706
00707
00708
00709
00710 def display_grasp_data(grasps, percept="accelerometer", indicies=range(3),
00711 std_dev=STD_DEV, noise_dev_add=NOISE_DEV, monitor_data=[],
00712 std_dev_dict=STD_DEV_DICT,
00713 tol_thresh_dict=TOL_THRESH_DICT,
00714 model_zeros=None, monitor_zeros=None,
00715 plot_data=False, colors=None):
00716 import matplotlib.pyplot as plt
00717 if colors is None:
00718 colors = ['r', 'b', 'g', 'c']
00719 j = 0
00720 rows = len(grasps)
00721 cols = len(indicies)
00722 for i, grasp in enumerate(grasps):
00723 models = grasp[3]
00724 means = models[percept]["mean"]
00725 vars = models[percept]["variance"]
00726 maxs = models[percept]["max"]
00727 mins = models[percept]["min"]
00728 if "smoothed_signals" in models[percept]:
00729 signals = models[percept]["smoothed_signals"]
00730 zip_signals = [ zip(*sig) for sig in signals ]
00731 else:
00732 signals = None
00733 zip_signals = []
00734 if "noise_variance" in models[percept]:
00735 noise_var = models[percept]["noise_variance"]
00736 noise_dev = np.sqrt(noise_var)
00737 else:
00738 noise_var = None
00739 noise_dev = None
00740 print "noise variance", noise_var
00741
00742 zip_means = np.array(zip(*means))
00743 zip_vars = np.array(zip(*vars))
00744 zip_maxs = np.array(zip(*maxs))
00745 zip_mins = np.array(zip(*mins))
00746
00747 zip_monitors = []
00748 for d in monitor_data:
00749 zip_monitors += [zip(*d[percept])]
00750 graph_means, graph_devs, mmax, mmin = [], [], [], []
00751 for w in indicies:
00752 graph_means += [zip_means[w]]
00753 graph_devs += [np.sqrt(zip_vars[w])]
00754
00755 if std_dev_dict is not None and percept in std_dev_dict:
00756 std_dev = std_dev_dict[percept][w]
00757 if tol_thresh_dict is not None and percept in tol_thresh_dict:
00758 tol_thresh = tol_thresh_dict[percept][w]
00759 else:
00760 tol_thresh = 0.
00761
00762 if noise_dev is not None:
00763 noise_dev_term = noise_dev[w] * noise_dev_add
00764 else:
00765 noise_dev_term = 0.
00766
00767
00768
00769
00770
00771
00772
00773 for k in range(len(indicies)):
00774 plt.subplot(rows, cols, i*cols + 1 + k)
00775 cnum = 0
00776 if plot_data:
00777 for stream in grasp[2][percept]:
00778
00779
00780 plt.plot([x[1][k] for x in stream],colors[cnum])
00781 cnum += 1
00782 cnum %= len(colors)
00783 for sig in zip_signals:
00784 if indicies[k] < len(sig):
00785 plt.plot(sig[indicies[k]], colors[2])
00786 if i < len(zip_monitors):
00787 zip_monitor = zip_monitors[i]
00788 len_diff = len(graph_means[k]) - len(zip_monitor[indicies[k]])
00789 add_vals = [zip_monitor[indicies[k]][0]] * MONITOR_WINDOW
00790
00791 print len_diff
00792 g = np.array(add_vals + list(zip_monitor[indicies[k]]))
00793
00794 plt.plot(g.tolist(),colors[3])
00795 plt.plot(graph_means[k], colors[0])
00796 plt.plot(zip_maxs[indicies[k]], colors[1])
00797 plt.plot(zip_mins[indicies[k]], colors[1])
00798
00799
00800 plt.title("%1.2f, %1.2f: coord %d" % (grasp[0][0], grasp[0][1], k))
00801 j += 1
00802
00803 plt.show()
00804
00805 def die():
00806 sys.exit()
00807
00808 def test_num_samples(percept="accelerometer"):
00809
00810
00811
00812
00813
00814
00815 grasp_data = load_pickle(GRASP_DATA_FILE)[0:1]
00816 data_list = grasp_data[0][2][percept]
00817 for i in [3, 6, 9]:
00818 apm = ArmPerceptionMonitor(ARM, percept_mon_list=PERCEPT_MON_LIST)
00819 grasp_data[0][2][percept] = data_list[0:i+1]
00820 apm.datasets = grasp_data[0][2]
00821 apm.generate_models()
00822 grasp_data[0][3][percept] = apm.models[percept]
00823 if i != 3:
00824 colors = ['m', 'y', 'k', 'r']
00825 else:
00826 colors = None
00827 display_grasp_data(grasp_data, percept, rows=1)
00828
00829 def detect_tabletop_objects():
00830 cbbf = ClusterBoundingBoxFinder()
00831 object_detector = rospy.ServiceProxy("/object_detection", TabletopDetection)
00832 detects = object_detector(True, False).detection
00833 object_detector.close()
00834 if detects.result != 4:
00835 print "Detection failed (err %d)" % (detects.result)
00836 return []
00837 table_z = detects.table.pose.pose.position.z
00838 objects = []
00839 for cluster in detects.clusters:
00840 (object_points,
00841 object_bounding_box_dims,
00842 object_bounding_box,
00843 object_to_base_link_frame,
00844 object_to_cluster_frame) = cbbf.find_object_frame_and_bounding_box(cluster)
00845
00846 (object_pos, object_quat) = cf.mat_to_pos_and_quat(object_to_cluster_frame)
00847 angs = euler_from_quaternion(object_quat)
00848 print "angs:", angs
00849
00850 object_pos[2] = table_z + object_bounding_box[1][2] / 2. + DETECT_ERROR
00851 print "pos:", object_pos
00852 print "table_z:", table_z
00853 objects += [[object_pos, angs[2]]]
00854 return objects
00855
00856 def grasp_object(obj, grasp=None, collide=True, is_place=False, zeros=None, cm=None, apm=None):
00857 if collide:
00858 return perform_grasp(obj[0][0], obj[0][1], is_place=is_place,
00859 gripper_rot=obj[1], grasp=grasp, zeros=zeros, cm=cm, apm=apm)
00860 else:
00861 return perform_grasp(obj[0][0], obj[0][1], z=obj[0][2], is_place=is_place,
00862 gripper_rot=obj[1], grasp=grasp, zeros=zeros, cm=cm, apm=apm)
00863
00864 def grasp_closest_object(x, y, grasp=None, collide=True, repeat=True, zeros=None, cm=None, apm=None):
00865 def dist(o):
00866 return (o[0][0] - x) ** 2 + (o[0][1] - y) ** 2
00867
00868 grasped = False
00869 num_tries = 0
00870
00871 point_head([x,y,-0.2])
00872
00873 while not grasped and num_tries < 4:
00874 print "Detect in"
00875 change_projector_mode(True)
00876 rospy.sleep(0.6)
00877 detect_tries = 0
00878 objects = None
00879 while (objects is None or len(objects) == 0):
00880 objects = detect_tabletop_objects()
00881 rospy.sleep(0.6)
00882 detect_tries += 1
00883 if detect_tries == 3 and (objects is None or len(objects) == 0):
00884 print "Cannot detect any objects"
00885 return None, None, None, None, None
00886 print "Detect out"
00887 if len(objects) > 0:
00888 obj = min(objects, key=dist)
00889
00890
00891 if True:
00892 point_head(obj[0])
00893 rospy.sleep(0.2)
00894 print "Detect2 in"
00895 objects = detect_tabletop_objects()
00896 print "Detect2 out"
00897 obj = min(objects, key=dist)
00898
00899 change_projector_mode(False)
00900 (grasp, avg_list, collided, zeros) = grasp_object(obj, grasp=grasp,
00901 collide=collide, zeros=zeros, cm=cm, apm=apm)
00902 rospy.sleep(0.2)
00903 grasped = is_obj_in_gripper(cm)
00904 if repeat and not grasped:
00905 num_tries += 1
00906 continue
00907 if grasped:
00908 print "Grasp success!"
00909 return obj, grasp, avg_list, collided, zeros
00910 else:
00911 print "Grasp failure"
00912 return obj, grasp, avg_list, collided, zeros
00913 else:
00914 print "No objects near point"
00915 return None, None, None, None, None
00916
00917 def grasp_demo():
00918 cm = ControllerManager(armc)
00919 apm = ArmPerceptionMonitor(ARM, percept_mon_list=PERCEPT_MON_LIST)
00920 grasps, avg_lists = [], []
00921 (obj1, grasp, avg_list, collided, zeros) = grasp_closest_object(0.45, 0.1, cm=cm, apm=apm)
00922 grasps += [grasp]
00923 avg_lists += [avg_list]
00924 obj1pl = [[obj1[0][0], obj1[0][1] - 0.18], obj1[1]]
00925 (grasp, avg_list, collided, zeros) = grasp_object(obj1pl, is_place=True, zeros=zeros, cm=cm, apm=apm)
00926 grasps += [grasp]
00927 avg_lists += [avg_list]
00928 (obj2, grasp, avg_list, collided, zeros) = grasp_closest_object(0.7, 0.1, zeros=zeros, cm=cm, apm=apm)
00929 grasps += [grasp]
00930 avg_lists += [avg_list]
00931 (grasp, avg_list, collided, zeros) = grasp_object(obj1, is_place=True, zeros=zeros, cm=cm, apm=apm)
00932 grasps += [grasp]
00933 avg_lists += [avg_list]
00934 (obj3, grasp, avg_list, collided, zeros) = grasp_closest_object(obj1pl[0][0], obj1pl[0][1], zeros=zeros, cm=cm, apm=apm)
00935 grasps += [grasp]
00936 avg_lists += [avg_list]
00937 (grasp, avg_list, collided, zeros) = grasp_object(obj2, is_place=True, zeros=zeros, cm=cm, apm=apm)
00938 grasps += [grasp]
00939 avg_lists += [avg_list]
00940 display_grasp_data(grasps[0:3], "accelerometer", monitor_data=avg_lists[0:3])
00941 display_grasp_data(grasps[3:-1], "accelerometer", monitor_data=avg_lists[3:-1])
00942
00943 def trim_test_data(grasp_data=None):
00944 if grasp_data is None:
00945 grasp_data = load_pickle(GRASP_DATA_FILE)
00946 new_data = []
00947 for grasp in grasp_data:
00948 new_data += [(grasp[0], grasp[1], None, grasp[3], grasp[4])]
00949 save_pickle(new_data, GRASP_MODELS_FILE)
00950 return new_data
00951
00952 def save_grasp(grasp, prefix):
00953 filename = prefix + "%04d-%04d-%04d.pickle" % (int(grasp[0][0]*100),int(grasp[0][1]*100),int(grasp[0][2]*100))
00954 save_pickle(grasp, filename)
00955 return filename
00956
00957 def split_model_data(data=None):
00958 if data is None:
00959 data = load_pickle(GRASP_MODELS_FILE)
00960 xyr_index = []
00961 n = 1
00962 for grasp in data:
00963 filename = GRASP_IND_PREFIX + "%03d-%03d-%03d.pickle" % (int(grasp[0][0]*100),int(grasp[0][1]*100),int(grasp[0][2]*100))
00964 xyr_index += [[grasp[0], filename]]
00965 save_pickle(grasp, filename)
00966 n += 1
00967 save_pickle(xyr_index, GRASP_INDEX_FILE)
00968
00969 def resample_split_model_data(apm, models=None, sampling_rate=4):
00970 if models is None:
00971 models = load_pickle(GRASP_MODELS_FILE)
00972 new_models = []
00973 for model in models:
00974 new_model = apm.resample_and_thin_data(model[3], sampling_rate)
00975 new_models.append([model[0], None, None, new_model, model[4]])
00976 split_model_data(new_models)
00977
00978 def normalize_rot(gripper_rot):
00979 while gripper_rot >= np.pi:
00980 gripper_rot -= np.pi
00981 while gripper_rot < 0.:
00982 gripper_rot += np.pi
00983 return gripper_rot
00984
00985 def grasp_loader(filename):
00986 class GLoader(threading.Thread):
00987 def __init__(self):
00988 threading.Thread.__init__(self)
00989 self.grasp = []
00990
00991 def run(self):
00992 tg = load_pickle(filename)
00993 for v in tg:
00994 self.grasp.append(v)
00995
00996 gl = GLoader()
00997 gl.start()
00998 return gl.grasp
00999
01000 def load_grasp(xyr, xyr_index = GRASP_DATA_INDEX_FILE):
01001 return get_grasp_model(xyr[0], xyr[1], xyr[2], xyr_index = xyr_index, no_wait=False)
01002
01003 def get_grasp_model(x, y, r, xyr_index = None, grasp_data = None, no_wait = True):
01004 r = normalize_rot(r)
01005 if grasp_data is None:
01006 if xyr_index is None:
01007 xyr_index = load_pickle(GRASP_INDEX_FILE)
01008 else:
01009 xyr_index = grasp_data
01010 if len(xyr_index) > 0:
01011 def dist(o):
01012 if np.allclose(o[0][2], 0.0):
01013
01014 rot_dist = min((np.pi - r) ** 2, (0. - r) ** 2)
01015 else:
01016 rot_dist = (o[0][2] - r) ** 2
01017 return (o[0][0] - x) ** 2 + (o[0][1] - y) ** 2 + rot_dist
01018 xyr = min(xyr_index, key=dist)
01019 print "Distance to grasp model:", dist(xyr), "rotation diff:", xyr[0][2] - r
01020 if grasp_data is None:
01021 if not no_wait:
01022 return load_pickle(xyr[1])
01023
01024 return grasp_loader(xyr[1])
01025 else:
01026 return xyr
01027 else:
01028 print "Bad index file"
01029 return None
01030
01031 def load_grasp(x, y, r, xyr_index = None):
01032 if xyr_index is None:
01033 xyr_index = load_pickle(GRASP_INDEX_FILE)
01034 for xyr in xyr_index:
01035 if np.allclose([x, y, r], xyr[0]):
01036 return load_pickle(xyr[1])
01037 return None
01038
01039 def compute_sqr_diff_map(percept="accelerometer"):
01040 xys = get_xy_list()
01041 def get_xy(i, j):
01042 return xys[i * NUM_Y + j]
01043 def model_sqr_err(m1, xy, i, j):
01044 n = 0
01045 sum = 0.
01046 cxy = get_xy(i, j)
01047 g2 = get_grasp_model(cxy[0], cxy[1])
01048 if np.allclose(g2[0], xy):
01049 return [-1.]
01050 m2 = g2[3][percept]["mean"]
01051 for i in range(min(len(m1),len(m2))):
01052 sum += (m1[i] - m2[i]) ** 2
01053 n += 1
01054 return sum / n
01055 xy_index = load_pickle(GRASP_INDEX_FILE)
01056 if len(xys) > 0:
01057 map = []
01058 for i in range(NUM_X):
01059 map += [[]]
01060 for j in range(NUM_Y):
01061 cen_xy = get_xy(i, j)
01062 cen_grasp = get_grasp_model(cen_xy[0], cen_xy[1])
01063 cen_grasp_model = cen_grasp[3][percept]["mean"]
01064 if not np.allclose(cen_xy, cen_grasp[0]):
01065 map[-1] += [0.]
01066 continue
01067 else:
01068 err = 0.
01069 n = 0
01070 new_err = model_sqr_err(cen_grasp_model, cen_xy, i+1, j)
01071 if new_err[0] != -1.:
01072 err += new_err
01073 n += 1
01074 new_err = model_sqr_err(cen_grasp_model, cen_xy, i-1, j)
01075 if new_err[0] != -1.:
01076 err += new_err
01077 n += 1
01078 new_err = model_sqr_err(cen_grasp_model, cen_xy, i, j+1)
01079 if new_err[0] != -1.:
01080 err += new_err
01081 n += 1
01082 new_err = model_sqr_err(cen_grasp_model, cen_xy, i, j-1)
01083 if new_err[0] != -1.:
01084 err += new_err
01085 n += 1
01086 err = np.linalg.norm(err) ** 2 / len(err)
01087 if n > 0:
01088 map[-1] += [err / n]
01089 else:
01090 map[-1] += [0.]
01091 return map
01092 else:
01093 print "Bad index file"
01094 return None
01095
01096 def sqr_diff_viz():
01097
01098 map = load_pickle(SQR_DIFF_MAP)
01099 map.reverse()
01100 maxarg = max([max(row) for row in map])
01101 print np.mat(map)
01102 for i in range(len(map)):
01103 for j in range(len(map[i])):
01104 if map[i][j] == -1.:
01105 map[i][j] = maxarg*1.5
01106 import matplotlib.pyplot as plt
01107 fig = plt.figure()
01108 ax = fig.add_subplot(111)
01109 ax.matshow(map)
01110 plt.show()
01111
01112 def process_data(grasp_data=None):
01113 print "Loading data"
01114 if grasp_data is None:
01115 grasp_data = load_pickle(GRASP_DATA_FILE)
01116 print "Data loaded, generating models"
01117 grasp_data = load_data_and_generate(grasp_data)
01118 print "Saving models"
01119 print "Trimming test data"
01120 model_data = trim_test_data(grasp_data)
01121 print "Splitting models"
01122 split_model_data(model_data)
01123 print "Done processing data"
01124
01125 def calc_model(x, y, r, window_len= 200, samples=50, xyr_index = None, resample = 10):
01126 if xyr_index is None:
01127 xyr_index = load_pickle(GRASP_INDEX_FILE)
01128 xs = (RECT[1][0] - RECT[0][0]) / (NUM_X - 1)
01129 ys = (RECT[0][1] - RECT[1][1]) / (NUM_Y - 1)
01130 rs = np.pi / NUM_ROT
01131 def dist1(o):
01132 return np.fabs(o[0][0] - x) + np.fabs(o[0][1] - y)
01133 def dist2(o):
01134 return (o[0][0] - x) ** 2 + (o[0][1] - y) ** 2
01135 def rotdist(o):
01136 if np.allclose(o[0][2], 0.0):
01137
01138 return min(np.fabs(np.pi - r), np.fabs(0. - r))
01139 else:
01140 return np.fabs(o[0][2] - r)
01141
01142 n = 1
01143
01144 close_models = []
01145 for i, dist in enumerate(map(dist1, xyr_index)):
01146 if np.allclose([x, y, r], xyr_index[i][0]):
01147 close_models = [[xyr_index[i][0], load_pickle(xyr_index[i][1])]]
01148 break
01149 if dist < xs + ys and rotdist(xyr_index[i]) < rs:
01150 close_models += [[xyr_index[i][0], load_pickle(xyr_index[i][1])]]
01151
01152 ret_models = {}
01153
01154 for k in close_models[0][1][3]:
01155 close_stream_means = []
01156 minlen = min([len(cm[1][3][k]["mean"]) for cm in close_models])
01157 for close_model in close_models:
01158 mean = close_model[1][3][k]["mean"][0:minlen]
01159 stream_means = zip(*mean)
01160 close_stream_means += [[close_model[0], np.array(stream_means)]]
01161
01162 expected_means, expected_vars = [], []
01163 for i in range(len(close_stream_means[0][1])):
01164 close_signals = []
01165 sum = np.array([0.]*len(close_stream_means[0][1][0]))
01166 distsum = 0.
01167 for close_stream in close_stream_means:
01168 close_signals += [close_stream[1][i]]
01169 dist = dist2(close_stream)
01170 sum += close_stream[1][i] / dist
01171 distsum += 1. / dist
01172 expected_mean = sum / distsum
01173 expected_var = signal_list_variance(close_signals, expected_mean,
01174 window_len, samples,
01175 resample)
01176 expected_means += [expected_mean[::resample]]
01177 expected_vars += [expected_var]
01178
01179 ret_model = { "mean" : zip(*expected_means), "variance" : zip(*expected_vars) }
01180 ret_models[k] = ret_model
01181 return [[x, y, r], None, None, ret_models, None]
01182
01183
01184 def random_grasp():
01185 xs = (RECT[1][0] - RECT[0][0]) / (NUM_X - 1)
01186 ys = (RECT[0][1] - RECT[1][1]) / (NUM_Y - 1)
01187 x = random.uniform(RECT[0][0]-xs/2., RECT[1][0]+xs/2.)
01188 y = random.uniform(RECT[1][1]-ys/2., RECT[0][1]+ys/2.)
01189 r = random.uniform(0., np.pi)
01190 return x, y, r
01191
01192 def random_known_grasp():
01193 xyr_index = load_pickle(GRASP_INDEX_FILE)
01194 ind = random.randint(0,len(xyr_index)-1)
01195 return xyr_index[ind][0]
01196
01197 def test_random_grasps(num_grasps=100):
01198 cm = ControllerManager(armc)
01199 apm = ArmPerceptionMonitor(ARM, percept_mon_list=PERCEPT_GRASP_LIST)
01200 monitor_data = []
01201 grasps = []
01202 collided_list = []
01203 num_collided = 0
01204 test_data = []
01205 zeros = None
01206 open_gripper(cm=cm)
01207
01208 for i in range(num_grasps):
01209 if rospy.is_shutdown():
01210 break
01211 x, y, rot = random_grasp()
01212
01213 (grasp, monitor, collided, zeros) = perform_grasp(x, y, gripper_rot = rot,
01214 collide=False, is_grasp = False,
01215 zeros=zeros, cm=cm, apm=apm)
01216 test_data += [{"loc" : (x, y, rot),
01217
01218 "monitor" : monitor,
01219 "collided" : collided,
01220 "zeros" : zeros}]
01221
01222 if collided:
01223 print "COLLIDED\n"*10
01224 num_collided += 1
01225
01226 print "Accuracy: %d collisions out of %d grasps (%1.2f)" % (num_collided, num_grasps, 1. - float(num_collided) / num_grasps)
01227 save_pickle(test_data, TEST_DATA_FILE)
01228
01229 def calc_false_pos(test_data=None, xyr_index=None, apm=None):
01230 if test_data is None:
01231 test_data = load_pickle(TEST_DATA_FILE)
01232 if apm is None:
01233 apm = ArmPerceptionMonitor(ARM, percept_mon_list=PERCEPT_GRASP_LIST)
01234 num_collisions = 0
01235 indicies = {}
01236 for test in test_data:
01237 model = get_grasp_model(test["loc"][0], test["loc"][1], test["loc"][2],
01238 xyr_index=xyr_index)
01239 collision = apm.simulate_monitoring(test["monitor"], models=model[3],
01240 model_zeros = test["zeros"],
01241 window_size=MONITOR_WINDOW,
01242 std_dev_default=STD_DEV,
01243 std_dev_dict = STD_DEV_DICT,
01244 tol_thresh_dict = TOL_THRESH_DICT,
01245 noise_dev_default=NOISE_DEV)
01246 if collision is not None:
01247 num_collisions += 1
01248 k, index, diff = collision
01249 if not k in indicies:
01250 indicies[k] = [0]*len(model[3][k]["mean"][0])
01251 indicies[k][index] += 1
01252 print "Accuracy: %d collisions out of %d grasps (%1.2f)" % (num_collisions, len(test_data), 1. - float(num_collisions) / len(test_data))
01253 print indicies
01254 return float(num_collisions) / len(test_data)
01255
01256
01257
01258
01259
01260
01261
01262
01263
01264
01265
01266
01267
01268
01269
01270
01271
01272
01273
01274
01275
01276
01277
01278
01279
01280
01281
01282
01283
01284
01285
01286
01287
01288
01289
01290
01291
01292
01293
01294
01295
01296
01297
01298
01299
01300
01301
01302
01303 def visualize_objs():
01304 objs = detect_tabletop_objects()
01305 pubm = rospy.Publisher('grasp_obj_positions', Marker)
01306 pubma = rospy.Publisher('grasp_obj_positions_array', MarkerArray)
01307 markers = []
01308 for obj in objs:
01309 pos, angle = np.mat(obj[0]).T, obj[1]
01310 marker = viz.single_marker(pos, np.mat(quaternion_about_axis(angle, (0, 0, 1))).T, "arrow", "torso_lift_link")
01311 marker.header.stamp = rospy.Time.now()
01312 markers.append(marker)
01313 pubm.publish(marker)
01314 ma = MarkerArray(markers)
01315 i = 0
01316 while not rospy.is_shutdown():
01317 pubm.publish(markers[i])
01318 rospy.sleep(2.1)
01319 i = (i + 1) % len(markers)
01320 print objs
01321 rospy.spin()
01322
01323 def get_laser_dclick(tf_listener, frame = "/torso_lift_link", delay_time = 3.0):
01324 c3d_lis = GenericListener("c3dlisnode", PointStamped, CURSOR_TOPIC, 10.0)
01325 dc_lis = GenericListener("dclisnode", String, MOUSE_DOUBLE_CLICK_TOPIC, 10.0)
01326 print "Waiting for laser click..."
01327 while not rospy.is_shutdown():
01328 if dc_lis.read(allow_duplication = False, willing_to_wait = False) is not None:
01329 print "DC"
01330 msg = c3d_lis.read(allow_duplication = True, willing_to_wait = False)
01331 print msg
01332 if msg is not None:
01333 if rospy.Time.now().to_sec() - msg.header.stamp.to_sec() <= delay_time:
01334 now = rospy.Time.now()
01335 tf_listener.waitForTransform(msg.header.frame_id, frame,
01336 now, rospy.Duration(4.0))
01337 tfmat = tf_utils.transform(frame, msg.header.frame_id, tf_listener)
01338 tfmat *= np.mat([[msg.point.x], [msg.point.y], [msg.point.z], [1.0]])
01339 pt = tfmat[0:3,3]
01340
01341
01342 print "pt", pt
01343 return pt[0,0], pt[1,0], pt[2,0]
01344 rospy.sleep(0.01)
01345 return None
01346
01347 def point_head(point, velocity = 0.6, frame="/torso_lift_link", block = True):
01348 head_action_client = actionlib.SimpleActionClient("/head_traj_controller/point_head_action", PointHeadAction)
01349 head_action_client.wait_for_server()
01350 goal = PointHeadGoal()
01351 goal.target = cf.create_point_stamped(point, frame)
01352 goal.pointing_frame = "/narrow_stereo_optical_frame"
01353 goal.max_velocity = velocity
01354
01355 head_action_client.send_goal(goal)
01356
01357 if not block:
01358 return 0
01359
01360 finished_within_time = head_action_client.wait_for_result(rospy.Duration(20))
01361 if not finished_within_time:
01362 head_action_client.cancel_goal()
01363 rospy.logerr("timed out when asking the head to point to a new goal")
01364 return 0
01365
01366 return 1
01367
01368 def hand_over_object(x, y, z, cm, apm, offset = 0.2, blocking = True):
01369 pt = np.array([x,y,z])
01370 quat = quaternion_about_axis(0.9, (0, 0, 1))
01371 dist = np.linalg.norm(pt)
01372 start_angles = cm.get_current_arm_angles()
01373 print start_angles
01374 ptnorm = pt / dist
01375 dist -= offset
01376 joints = None
01377 while not rospy.is_shutdown() and pt[0] > 0.2:
01378 pt = dist * ptnorm
01379 print "dist", dist
01380 pose = create_gripper_pose(pt[0], pt[1], pt[2], quat.tolist())
01381 print pose
01382
01383
01384 HANDOFF_BIAS = [0., -.25, -100., 200., 0.0, 200.0, 0.]
01385 joints = cm.ik_utilities.run_biased_ik(pose, HANDOFF_BIAS, num_iters=30)
01386 if joints is not None:
01387 break
01388 dist -= 0.1
01389
01390 cm.command_joint_trajectory([joints], 0.27, blocking = blocking)
01391
01392
01393 def change_projector_mode(on):
01394 client = dynamic_reconfigure.client.Client("camera_synchronizer_node")
01395 node_config = client.get_configuration()
01396 node_config["projector_mode"] = 2
01397 if on:
01398 node_config["narrow_stereo_trig_mode"] = 3
01399 else:
01400 node_config["narrow_stereo_trig_mode"] = 4
01401 client.update_configuration(node_config)
01402
01403 def move_to_setup(cm, blocking = True):
01404 joints = [-0.62734204881265387, -0.34601608409943324, -1.4620635485239604, -1.2729772622637399, -7.5123303230158518, -1.5570651396529178, -5.5929916630672727]
01405 cm.command_joint_trajectory([joints], 0.62, blocking = blocking)
01406
01407
01408 def laser_interface_demo():
01409 cm = ControllerManager(armc)
01410 apm = ArmPerceptionMonitor(ARM, percept_mon_list=PERCEPT_GRASP_LIST)
01411
01412 move_to_setup(cm)
01413
01414 x, y, z = get_laser_dclick(cm.tf_listener)
01415
01416 point_head([x,y,z], block = True)
01417
01418 grasp_closest_object(x, y, cm=cm, apm=apm)
01419 change_projector_mode(on=False)
01420
01421 x, y, z = get_laser_dclick(cm.tf_listener)
01422
01423 point_head([x,y,z+0.2], block = True)
01424
01425
01426 def monitor_pressure():
01427 apm = ArmPerceptionMonitor(ARM, percept_mon_list=PRESSURE_LIST)
01428 rospy.sleep(1.0)
01429
01430 models = {}
01431 for k in PRESSURE_LIST:
01432 if "periph" in k:
01433 models[k] = {}
01434 models[k]["mean"] = np.array([np.array([0.]*6)])
01435 models[k]["variance"] = np.array([np.array([40.]*6)])
01436 if "pad" in k:
01437 models[k] = {}
01438 models[k]["mean"] = np.array([np.array([0.]*15)])
01439 models[k]["variance"] = np.array([np.array([40.]*15)])
01440
01441 apm.begin_monitoring(models, only_pressure=True)
01442 print "Monitoring pressure..."
01443 while not rospy.is_shutdown() and not apm.failure:
01444 rospy.sleep(0.01)
01445 print "Pressure triggered"
01446
01447
01448
01449
01450
01451
01452
01453
01454
01455
01456
01457
01458
01459
01460
01461
01462
01463
01464
01465
01466
01467
01468
01469
01470
01471
01472
01473
01474
01475
01476
01477
01478
01479
01480
01481
01482
01483
01484 def main():
01485 rospy.init_node(node_name)
01486
01487 setup_package_loc()
01488 ki = KeyboardInput()
01489
01490
01491
01492
01493
01494 generate_space_models()
01495 return 0
01496
01497
01498
01499
01500
01501
01502
01503
01504
01505
01506
01507
01508
01509
01510
01511
01512
01513
01514
01515
01516
01517
01518
01519
01520
01521
01522
01523
01524
01525
01526
01527
01528
01529
01530
01531
01532
01533
01534
01535
01536
01537
01538
01539
01540
01541
01542
01543
01544
01545
01546
01547
01548
01549
01550
01551
01552
01553
01554
01555
01556
01557
01558
01559
01560
01561
01562
01563
01564
01565
01566
01567
01568
01569
01570
01571
01572
01573
01574
01575 cm = ControllerManager(armc)
01576 apm = ArmPerceptionMonitor(ARM, percept_mon_list=PERCEPT_GRASP_LIST)
01577
01578
01579
01580
01581
01582
01583
01584
01585
01586
01587
01588
01589
01590
01591
01592
01593
01594
01595
01596
01597
01598
01599
01600
01601
01602
01603
01604
01605
01606
01607
01608
01609
01610
01611
01612
01613
01614
01615
01616
01617
01618
01619
01620
01621
01622
01623
01624
01625
01626 open_gripper(cm = cm)
01627
01628 monitor_data = []
01629 monitor_zeros = []
01630 grasps = []
01631 collided_list = []
01632 num_grasps = 100
01633 num_collided = 0
01634 zeros = None
01635 global z_sum
01636 z_sum = {}
01637
01638 for i in range(num_grasps):
01639 point_head([0.5, 0.0, -0.2], block=False)
01640
01641 if rospy.is_shutdown():
01642 break
01643
01644
01645 if False:
01646
01647
01648
01649 if False:
01650 x, y, rot = random_grasp()
01651 else:
01652 x, y, rot = random_known_grasp()
01653 (grasp, monitor, collided, zeros) = perform_grasp(x, y, gripper_rot = rot,
01654 collide=True, is_grasp = False,
01655
01656 zeros=zeros, cm=cm, apm=apm)
01657 elif False:
01658 x, y = 0.5, 0.0
01659 (obj, grasp, monitor, collided, zeros) = grasp_closest_object(x, y, collide=True, zeros=zeros, cm=cm, apm=apm)
01660 rospy.sleep(0.3)
01661 if is_obj_in_gripper(cm):
01662 x, y, rot = random_grasp()
01663 perform_grasp(x, y, gripper_rot=rot, zeros = zeros, collide=True, is_place=True,
01664 cm=cm, apm=apm)
01665 else:
01666 obj = None
01667 while obj is None:
01668 x, y, z = get_laser_dclick(cm.tf_listener)
01669 (obj, grasp, monitor, collided, zeros) = grasp_closest_object(x, y, collide=True, zeros=zeros, cm=cm, apm=apm)
01670 x, y, z = get_laser_dclick(cm.tf_listener)
01671 print " X Y Z"
01672 print x, y, z
01673 if x > 0.92 and z > 0.04:
01674 point_head([x, y, z], block = False)
01675 hand_over_object(x, y, z + 0.1, cm, apm)
01676 monitor_pressure()
01677 open_gripper(cm=cm)
01678 else:
01679 perform_grasp(x, y, gripper_rot=obj[1], zeros = zeros, collide=True, is_place=True,
01680 cm=cm, apm=apm)
01681 move_to_setup(cm, blocking = False)
01682 grasps += [grasp]
01683 monitor_data += [monitor]
01684 collided_list += [collided]
01685 monitor_zeros += [zeros]
01686
01687 if collided:
01688 print "COLLIDED"
01689 print "COLLIDED"
01690 print "COLLIDED"
01691 num_collided += 1
01692
01693 rospy.sleep(2.0)
01694 if ki.kbhit():
01695 if PERCEPT_GRASP_LIST is None:
01696 percept = "joint_efforts"
01697 else:
01698 percept = PERCEPT_GRASP_LIST[0]
01699 display_grasp_data(grasps[-3:], percept, monitor_data=monitor_data[-3:], monitor_zeros=monitor_zeros[-3:])
01700
01701 break
01702
01703 print "Accuracy: %d collisions out of %d grasps (%1.2f)" % (num_collided, num_grasps, 1. - float(num_collided) / num_grasps)
01704 test_data = [grasps, monitor_data, collided_list]
01705 for k in z_sum:
01706 print z_sum[k] / num_grasps
01707 return 0
01708 save_pickle(test_data, "test_runs.pickle")
01709
01710
01711
01712
01713
01714
01715
01716
01717
01718
01719
01720
01721
01722
01723
01724
01725
01726
01727
01728
01729
01730
01731
01732
01733
01734
01735
01736
01737
01738
01739
01740
01741
01742
01743
01744
01745
01746 display_grasp_data(grasps, "accelerometer", monitor_data=monitor_data)
01747 raw_input()
01748 open_gripper(cm=cm)
01749
01750 return 0
01751
01752 if __name__ == "__main__":
01753 sys.exit(main())
01754