simple_grasp_learner.py
Go to the documentation of this file.
00001 #! /usr/bin/python
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 # from pr2_gripper_reactive_approach.controller_manager import ControllerManager
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 #SETUP_POS = (0.62, 0.0, 0.035)
00042 #SETUP_POS_ANGS = [-0.6260155429349421, -0.53466276262236689, -1.9803303473514324, -1.1593322538276705, -0.89803655400181404, -1.4467120153069799, -2.728422563953746]
00043 #MAX_JERK = 0.2
00044 NUM_X = 7#3#9#7 #4#7
00045 NUM_Y = 11#3#15#9 #4#20
00046 NUM_N = 3 #4
00047 NUM_ROT = 6
00048 # near to far, left to right
00049 RECT = ((0.45, 0.25), (0.70, -0.25))#((0.4, 0.35), (0.8, -0.35))#((0.45, 0.10), (0.65, -0.10))#((0.4, 0.20), (0.7, -0.20))#((0.4, 0.35), (0.8, -0.35)) #((0.55, 0.10), (0.7, -0.10)) #((0.4, -0.77), (0.75, 0.23))
00050 
00051 ARM = 0 # right arm
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 # 0.15
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 # 0.15
00065 
00066 STD_DEV = 2.3 #3.5 #1.9
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 #["accelerometer"]
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 #                 "joint_efforts" ] #["joint_angles"]#["joint_velocities"] #["r_finger_periph_pressure"] #["joint_efforts"] #["joint_angles"]
00092 ##STD_DEV_DICT = None
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 # Transforms the given position by the offset position in the given quaternion
00170 # rotation frame
00171 #
00172 # @param pos the current positions
00173 # @param quat quaternion representing the rotation of the frame
00174 # @param off_point offset to move the position inside the quat's frame
00175 # @return the new position as a matrix column
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 # def get_setup_pos_angs():
00184 #     arms = PR2Arms()
00185 #     arms.move_arm(ARM, SETUP_POS, rotY(np.pi / 2.), 4.)
00186 #     arms.wait_for_arm_completion(ARM)
00187 #     print arms.get_joint_angles(ARM)
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 #       if not setup:
00254 #           # Move to setup position in the middle of the grasp space
00255 #           print "Setting up"
00256 #           arms.set_joint_angles(ARM, SETUP_POS_ANGS, 3.)
00257 #           arms.wait_for_arm_completion(ARM)
00258 #           rospy.sleep(0.5)
00259 #           setup = True
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             # grasp_configs += [(xy, None)]
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     #    if restart:
00318     #        grasp_data = load_pickle(GRASP_DATA)
00319     #        grasp_xyr_list = zip(*grasp_data)[0]
00320     #    else:
00321     #        grasp_xyr_list = get_xy_list()
00322     #        grasp_data = []
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         # if c < 257:
00333         #     continue
00334         if rospy.is_shutdown():
00335             return
00336         print "---------------------------------------------------"
00337         print "%1.2f completion" % (float(c) / len(grasp_xyr_list))
00338         zeros = None
00339         # Do grasping num_n times
00340         for i in range(NUM_N):
00341             pauser(ki)
00342 
00343             # Move to grasp position
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                     # wait for a bit to get the zeros here
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                 # start gathering data
00360                 apm.start_training()
00361                 # move arm down
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         # can't move to initial position
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             # grasp_data += [(xyr, None, apm.datasets, models, zeros)]
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     #save_pickle(grasp_data, GRASP_DATA_FILE)
00395     save_pickle(grasp_index, GRASP_DATA_INDEX_FILE)
00396     print "Data save complete"
00397     return None #grasp_data
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     # save_pickle(ret, GRASP_MODELS_FILE)
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                             # for loop around
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                 # find the average case over the several runs
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 # def test_monitor(grasp_data):
00487 #     apm = ArmPerceptionMonitor(ARM)
00488 #     j = 0
00489 #     while grasp_data[j][1] is None:
00490 #         j += 1
00491 #     apm.models = grasp_data[j][3]
00492 #     def print_warn():
00493 #         print "Warning! Outside model"
00494 #     apm.begin_monitoring(contingency=print_warn)
00495 #     raw_input()
00496 #     apm.end_monitoring()
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     #apm.datasets = grasp[2]
00534     #apm.models = grasp[3]
00535     #apm.model_zeros = grasp[4]
00536     #print "Model zeros:", grasp[4]
00537 
00538     print "Beginning grasp"
00539 
00540     result = "no solution"
00541     iters = 0
00542     while True:
00543         # Move to grasp position
00544         print "Moving to initial grasp position"
00545         # cm.command_joint_trajectory([grasp[1]], SETUP_VELOCITY, blocking = True)
00546 
00547         # print "Moving to final grasp position"
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             # open gripper
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         #if zeros is None:
00559         # zeros = apm.get_zeros(0.6)
00560         # print "Current zeros:", zeros
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             # start gathering data
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         # move arm down
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             # Jiggle it to see if it works
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             # Tried too many times
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     #upward_lift(cm, grasp_pose, block=True)
00674     print "Grasp complete!"
00675     
00676     return grasp, avg_list, col.collided, zeros
00677 
00678 # def perform_template_grasp(grasp):
00679 #     cm = ControllerManager(armc)
00680 #     apm = ArmPerceptionMonitor(ARM, percept_mon_list=["accelerometer"])
00681 # 
00682 #     apm.datasets = grasp[2]
00683 #     apm.models = grasp[3]
00684 # 
00685 #     # Move to grasp position
00686 #     print "Moving to grasp position"
00687 #     cm.command_joint(grasp[1])
00688 #     cm.wait_joint_trajectory_done()
00689 #     rospy.sleep(0.5)
00690 # 
00691 #     goal_pose = create_goal_pose(grasp[0][0], grasp[0][1], HOVER_Z - GRASP_DIST)
00692 # 
00693 #     # start gathering data
00694 #     def print_collision():
00695 #         print "Collision!"
00696 #         cm.freeze_arm()
00697 #     apm.begin_monitoring(contingency=print_collision, window_size=MONITOR_WINDOW)
00698 # 
00699 #     # move arm down
00700 #     print "Moving arm down"
00701 #     downward_grasp(cm, goal_pose, block = False)
00702 #     cm.wait_joint_trajectory_done()
00703 #     print "Finished moving arm"
00704 # 
00705 #     avg_list = apm.end_monitoring()
00706 #     rospy.sleep(0.5)
00707 # 
00708 #     return avg_list
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         # print "monitor_data", monitor_data
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             # mmax += graph_means[w] + graph_devs[w] * std_dev + noise_dev_term 
00769             #                                                                  + tol_thresh]
00770             # mmin += [graph_means[w] - graph_devs[w] * std_dev - noise_dev_term
00771             #                                                                  - tol_thresh]
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                     # s_mag = [np.sqrt(x[1][0]**2 + x[1][1]**2 + x[1][2]**2) for x in stream]
00779                     # plt.plot(s_mag,colors[cnum])
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                 # add_vals = [zip_monitor[indicies[k]][0]] * len_diff
00791                 print len_diff
00792                 g = np.array(add_vals + list(zip_monitor[indicies[k]]))
00793                 # g += grasp[4][percept][indicies[k]] - monitor_zeros[i][percept][indicies[k]]
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             # plt.plot(mmax[k], colors[1])
00799             # plt.plot(mmin[k], colors[1])
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     # This function proves that adding more than 3-4 grasps per location is unnecessary
00810     # Grasping trajectories are very repeatable given a specific grasping location.
00811     # The issue comes from more from shifting of the actual trajectory from expected
00812     # given a grasping location just a few cm off.  The models can handle the trajectory
00813     # so long as it is not much more than 5cm away from the training model.
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         # print "bounding box:", object_bounding_box
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         # position is half of height
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             # Get better look
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                 # for loop around
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     # save_pickle(compute_sqr_diff_map(), SQR_DIFF_MAP)
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                 # for loop around
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             #"model" : grasp, 
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 # def dynamic_parameter_tune(alpha = 0.1, dev_seed = 1.2, seed_dict=None):
01257 #     global STD_DEV_DICT
01258 #     x_old = { "accelerometer" : [dev_seed]*3,
01259 #               "joint_angles" : [dev_seed]*7,
01260 #               "joint_velocities" : [dev_seed]*7,
01261 #               "joint_efforts" : [dev_seed]*7,
01262 #               "r_finger_periph_pressure" : [dev_seed]*6,
01263 #               "r_finger_pad_pressure" : [dev_seed]*15, 
01264 #               "l_finger_periph_pressure" : [dev_seed]*6,
01265 #               "l_finger_pad_pressure" : [dev_seed]*15, ]
01266 #     for k in STD_DEV_DICT:
01267 #         STD_DEV_DICT[k] = np.array(STD_DEV_DICT[k])
01268 #     test_data = load_pickle(TEST_DATA_FILE)
01269 #     apm = ArmPerceptionMonitor(ARM, percept_mon_list=PERCEPT_GRASP_LIST)
01270 #     def F(x):
01271 #         sum = 0.
01272 #         for k in x:
01273 #             sum += np.sum(x[k])
01274 #         global STD_DEV_DICT
01275 #         STD_DEV_DICT = x
01276 #         print "Evaluating:", x
01277 #         fp = calc_false_pos(test_data=test_data)
01278 #         print "False positive rate:", fp
01279 #         return fp + alpha * sum
01280 #     def add_x(x, delta, step):
01281 #         
01282 #     def get_grad(x_old, F_old, x_new, F_new):
01283 #         grad = {}
01284 #         for k in old:
01285 #             grad[k] = (F_new - F_old) / (new[k] - old[k])
01286 # 
01287 #     step = 0.2
01288 #     F_old = F(x_old)
01289 #     x_new = copy.deepcopy(x_old)
01290 #     for k in x_new:
01291 #         x_new[k] += step
01292 #     F_new = F(x_new)
01293 #     
01294 # 
01295 #     for k in
01296 # 
01297 #     
01298 #     for dev in devs:
01299 #         fp = calc_false_pos(test_data=test_data)
01300 #         print "std dev:", dev
01301 #         fp_rate += [fp]
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                     #(trans, rot) = tf_listener.lookupTransform(msg.header.frame_id, frame, now)
01341                     #pt = [msg.point.x - trans[0], msg.point.y - trans[1], msg.point.z - trans[2]]
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 #   joints = [-0.1, -0.15, -1.2, -0.7, 0., -0.2, 0.]
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 #   x, y, z = 0.7, 0.0, -0.3
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 #   x, y, z = 1.2, 0.0, 0.3
01423     point_head([x,y,z+0.2], block = True)
01424     # hand_over_object(x, y, z, cm, apm)
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 # def double_click_listener(self, msg):
01449 #     """
01450 #     Waits until a double click message is sent, then executes appropriate pick
01451 #     or place operation.  Uses latest cursor3d message.
01452 #     
01453 #     @param msg: Latest cursor3d message
01454 #     @type  msg: PointStamped
01455 #     """
01456 #     pt = self.latest_cursor
01457 #     if pt == None:
01458 #         return
01459 #     dclick_delay = rospy.Time.now().to_sec() - self.latest_cursor.header.stamp.to_sec()
01460 #     if dclick_delay < MAX_DELAY:
01461 #         rospy.loginfo("cursor3d target acquired.")
01462 #         self.papm.tf_listener.waitForTransform(self.latest_cursor.header.frame_id, "base_footprint", rospy.Time.now(), rospy.Duration(4.0))
01463 #         pt_loc = self.papm.tf_listener.transformPoint('base_footprint', pt)
01464 # 
01465 #         if not self.hasobject:
01466 #             success = lp.pick_up_object_near_point(pt_loc)
01467 #             if success:
01468 #                 rospy.loginfo("Success with pickup! Waiting for target placement...")
01469 #                 self.hasobject = True
01470 #             else:
01471 #                 rospy.loginfo("Failure. Exiting...")
01472 #                 rospy.signal_shutdown("SS")
01473 #         else:
01474 #             target_pose = create_pose_stamped([pt_loc.point.x, pt_loc.point.y, pt_loc.point.z, 0.0, 0.0, 0.0, 1.0],
01475 #                                              'base_link')
01476 #             success = lp.place_object((RECT_DIM_X, RECT_DIM_Y), target_pose)
01477 #             if success:
01478 #                 rospy.loginfo("Success with placement! Exiting...")
01479 #             else:
01480 #                 rospy.loginfo("Failure placing. Exiting...")
01481 #             rospy.signal_shutdown("SS")
01482 
01483 
01484 def main():
01485     rospy.init_node(node_name)
01486     # rospy.on_shutdown(die)
01487     setup_package_loc()
01488     ki = KeyboardInput()
01489 
01490     #x, y, z = get_laser_dclick()
01491     #laser_interface_demo()
01492     #return 0
01493 
01494     generate_space_models()
01495     return 0
01496 
01497     # grasp_data = load_pickle(GRASP_DATA_FILE)
01498     # for grasp in grasp_data:
01499     #     for k in grasp[2]:
01500     #         print len(grasp[2][k][0])
01501     # return
01502 
01503     # write_index_file()
01504     # return 0
01505 
01506     #visualize_objs()
01507     #return 0
01508 
01509     # grasp_data = collect_grasp_data(ki, generate_models=False, skip_grasp=False)
01510     # return 0
01511 
01512     # process_data() #load_pickle(GRASP_DATA_FILE)) #load_pickle(GRASP_DATA_FILE))
01513     # return 0
01514 
01515     #trim_test_data()
01516     # return 0
01517 
01518     # apm = ArmPerceptionMonitor(ARM, percept_mon_list=PERCEPT_GRASP_LIST) 
01519     # resample_split_model_data(apm)
01520     # return 0
01521 
01522     #split_model_data()
01523     #return 0
01524 
01525     # print get_grasp_model(0., 0.)
01526     # return 0
01527 
01528     #grasp_demo()
01529     #return 0
01530 
01531     #test_random_grasps(250)
01532     #return 0 
01533 
01534     # grasp = calc_model(0.6, 0.0, 0.08)
01535     # display_grasp_data([grasp], "accelerometer")
01536     # return 0
01537 
01538     #global STD_DEV_DICT
01539     #xdev = 2.5
01540     #devs = np.linspace(1.5, 4., 18)
01541     #fp_rate = []
01542     #test_data = load_pickle(TEST_DATA_FILE)
01543     #for dev in devs:
01544     #    STD_DEV_DICT = {"accelerometer" : [xdev, dev, dev] }
01545     #    fp = calc_false_pos(test_data=test_data)
01546     #    print "std dev:", dev
01547     #    fp_rate += [fp]
01548 
01549     #print devs
01550     #print fp_rate
01551     #return 0
01552     
01553     #monitor_data = []
01554     #grasp_data = load_data_and_generate(load_pickle(GRASP_DATA_FILE))
01555     #save_pickle(grasp_data, GRASP_DATA_FILE)
01556     #grasp_data = load_pickle(GRASP_DATA_FILE)
01557     #display_grasp_data(grasp_data[0], "accelerometer", monitor_data=monitor_data, rows=1)
01558     #return 0
01559 
01560     # print detect_tabletop_objects()
01561     # return 0
01562 
01563     # sqr_diff_viz()
01564     # return 0
01565 
01566     # get_setup_pos_angs()
01567     # print_configs(load_pickle(GRASP_CONFIGS_FILE))
01568 
01569     # save_grasp_configurations()
01570     # return 0
01571     # import random
01572     # data = load_pickle(GRASP_CONFIGS_FILE)
01573     # random.shuffle(data)
01574 
01575     cm = ControllerManager(armc)
01576     apm = ArmPerceptionMonitor(ARM, percept_mon_list=PERCEPT_GRASP_LIST) 
01577 
01578     #monitor_pressure()
01579     #return 0
01580 
01581     # while not rospy.is_shutdown():
01582     #     x, y, z = get_laser_dclick(cm.tf_listener)
01583     #     if x > 0.92 and z > 0.04:
01584     #         point_head([x, y, z], block = False)
01585     #         hand_over_object(x, y, z + 0.1, cm, apm)
01586     #         monitor_pressure()
01587     #         open_gripper(cm=cm)
01588     # return 0
01589 
01590     # data = load_pickle(GRASP_CONFIGS_FILE)
01591     # new_data = []
01592     # xys = get_xy_list()
01593     # for grasp in data:
01594     #     for xy in xys:
01595     #         if np.allclose(xy, grasp[0]):
01596     #             new_data += [grasp]
01597 
01598     # print "length:", len(new_data)
01599     # collect_grasp_data(new_data)
01600     # collect_grasp_data(load_pickle(GRASP_CONFIGS_FILE))
01601     # return 0
01602     # trim_bad_grasps("gcb2.pickle")
01603     # return 0
01604     # save_current_zeros()
01605     # return 0
01606     # test_num_samples()
01607     # return 0
01608 
01609     # print "Generating data"
01610     # grasp_data = load_data_and_generate(load_pickle(GRASP_DATA_FILE))
01611     # save_pickle(grasp_data, GRASP_DATA_FILE)
01612     # print "Done generating data"
01613     # return 0
01614 
01615     # grasp_data = load_pickle(GRASP_MODELS_FILE)
01616     #grasp = get_grasp_model(0., 0.)
01617 
01618     # monitor_data += [grasp_closest_object(0.48, 0.07, cm=cm, apm=apm)]
01619     # monitor_data += [grasp_closest_object(grasp_data, 0.48, 0.07, cm=cm, apm=apm)]
01620     # grasp_data = load_pickle(GRASP_DATA_FILE)
01621     # print grasp_data[0][0]
01622     # monitor_data = perform_template_grasp(grasp_data[0])
01623     # display_grasp_data(grasp_data, "accelerometer", monitor_data=monitor_data, rows=1)
01624     # display_grasp_data(grasp_data, "r_finger_periph_pressure", rows=1)
01625     # monitor_data = perform_grasp(grasp_data, .58, .14, gripper_rot = 0.)
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         #move_to_setup(cm)
01641         if rospy.is_shutdown():
01642             break
01643         #x, y, rot = random.uniform(.45, .65), random.uniform(-.2, .2), random.uniform(0., 3.14)
01644 
01645         if False:
01646             #rot = 0.
01647             #global STD_DEV_DICT
01648             #STD_DEV_DICT = None
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                                                #grasp_data = grasp_data,
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             # print monitor_data[-3:]
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     # if False:
01710     #     new_grasp = get_grasp_model(x+.05, y)
01711     #     if new_grasp is not None:
01712     #         grasps += [new_grasp] 
01713     #     new_grasp = get_grasp_model(x-.05, y)
01714     #     if new_grasp is not None:
01715     #         grasps += [new_grasp] 
01716     #     new_grasp = get_grasp_model(x, y+.05)
01717     #     if new_grasp is not None:
01718     #         grasps += [new_grasp] 
01719     #     new_grasp = get_grasp_model(x, y-.05)
01720     #     if new_grasp is not None:
01721     #         grasps += [new_grasp] 
01722 
01723     # new_monitor_data = []
01724     # for j in range(len(monitor_data)):
01725     #     ret_mon = []
01726     #     for i in range(len(monitor_data[j]["accelerometer"])):
01727     #         ret_mon += [np.sqrt(monitor_data[j]["accelerometer"][i][1] ** 2 + monitor_data[j]["accelerometer"][i][2] ** 2)]
01728     #     new_monitor_data += [np.array(ret_mon)]
01729 
01730     # for i in range(3000):
01731     #     monitor_data[0]["accelerometer"][i][1] = new_monitor_data[0][i] - new_monitor_data[1][i]
01732     #     monitor_data[1]["accelerometer"][i][1] = 0.
01733     #     monitor_data[2]["accelerometer"][i][1] = 0.
01734 
01735     # monitor_data += [perform_grasp(grasp_data, .55, .15, gripper_rot = 0., is_place=True)]
01736     # monitor_data += [perform_grasp(grasp_data, .56, .10, gripper_rot = 0.)]
01737     # monitor_data += [perform_grasp(grasp_data, .57, .10, gripper_rot = 0.)]
01738     # monitor_data += [perform_grasp(grasp_data, .58, .10, gripper_rot = 0.)]
01739 
01740     # for i in range(2):
01741     #     monitor_data += [perform_grasp(grasp_data, .55, .10, gripper_rot = 0., cm=cm, apm=apm)]
01742     #     monitor_data += [perform_grasp(grasp_data, .55, .15, gripper_rot = 0., is_place=True, cm=cm, apm=apm)]
01743     #     monitor_data += [perform_grasp(grasp_data, .55, .15, gripper_rot = 0., cm=cm, apm=apm)]
01744     #     monitor_data += [perform_grasp(grasp_data, .55, .10, gripper_rot = 0., is_place=True, cm=cm, apm=apm)]
01745     # monitor_data += [perform_grasp(grasp_data, .55, .10, z=HOVER_Z-0.14, gripper_rot = 0., is_place=False, cm=cm, apm=apm)]
01746     display_grasp_data(grasps, "accelerometer", monitor_data=monitor_data)
01747     raw_input()
01748     open_gripper(cm=cm)
01749     # test_monitor(load_pickle(GRASP_DATA_FILE))
01750     return 0
01751 
01752 if __name__ == "__main__":
01753     sys.exit(main())
01754     


kelsey_sandbox
Author(s): kelsey
autogenerated on Wed Nov 27 2013 11:52:04