hrl_manipulation.py
Go to the documentation of this file.
00001 #! /usr/bin/python
00002 #
00003 # Copyright (c) 2009, Georgia Tech Research Corporation
00004 # All rights reserved.
00005 #
00006 # Redistribution and use in source and binary forms, with or without
00007 # modification, are permitted provided that the following conditions are met:
00008 #     * Redistributions of source code must retain the above copyright
00009 #       notice, this list of conditions and the following disclaimer.
00010 #     * Redistributions in binary form must reproduce the above copyright
00011 #       notice, this list of conditions and the following disclaimer in the
00012 #       documentation and/or other materials provided with the distribution.
00013 #     * Neither the name of the Georgia Tech Research Corporation nor the
00014 #       names of its contributors may be used to endorse or promote products
00015 #       derived from this software without specific prior written permission.
00016 #
00017 # THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
00018 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
00019 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
00020 # DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
00021 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00022 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
00023 # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
00024 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
00025 # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
00026 # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00027 #
00028 #Based on some code by Kaijen, modified heavily by Marc Killpack
00029 
00030 
00031 import roslib
00032 roslib.load_manifest('pr2_playpen')
00033 roslib.load_manifest('pr2_grasp_behaviors')
00034 import rospy
00035 import actionlib
00036 import hrl_pr2_lib.pressure_listener as pl
00037 from object_manipulator.convert_functions import *
00038 from pr2_playpen.srv import Playpen
00039 from pr2_playpen.srv import Conveyor
00040 from pr2_playpen.srv import Check
00041 from pr2_playpen.srv import Train
00042 from UI_segment_object.srv import Save
00043 #from pr2_overhead_grasping.msg import *
00044 from pr2_grasp_behaviors.msg import *
00045 import os
00046 import datetime
00047 import cPickle
00048 
00049 import math
00050 import numpy as np
00051 
00052 class HRLControllerPlaypen():
00053 
00054     def __init__(self):
00055         print "waiting for conveyor"
00056         rospy.wait_for_service('playpen')
00057         rospy.wait_for_service('conveyor')
00058         print "started conveyor and playpen"
00059         self.playpen = rospy.ServiceProxy('playpen', Playpen)
00060         self.conveyor = rospy.ServiceProxy('conveyor', Conveyor)
00061         self.objects_dist = [0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,
00062                              0.13, 0.13, 0.13]
00063 
00064         self.tries = 0
00065         self.successes = 0
00066 
00067         self.r_grip_press = pl.PressureListener(topic='/pressure/r_gripper_motor')
00068         self.l_grip_press = pl.PressureListener(topic='/pressure/l_gripper_motor')
00069 
00070         self.grasp_client = [None, None]
00071         self.grasp_setup_client = [None, None]
00072 
00073         self.grasp_client[0] = actionlib.SimpleActionClient('r_overhead_grasp', OverheadGraspAction)
00074         self.grasp_client[0].wait_for_server()
00075         
00076         self.grasp_setup_client[0] = actionlib.SimpleActionClient('r_overhead_grasp_setup', OverheadGraspSetupAction)
00077         self.grasp_setup_client[0].wait_for_server()
00078         self.grasp_client[1] = actionlib.SimpleActionClient('l_overhead_grasp', OverheadGraspAction)
00079         self.grasp_client[1].wait_for_server()
00080         self.grasp_setup_client[1] = actionlib.SimpleActionClient('l_overhead_grasp_setup', OverheadGraspSetupAction)
00081         self.grasp_setup_client[1].wait_for_server()
00082 
00083     def move_to_side(self, whicharm, open_gripper=False):
00084         rospy.loginfo("moving the arms to the side")
00085         setup_goal = OverheadGraspSetupGoal()
00086         setup_goal.disable_head = True
00087         setup_goal.open_gripper = open_gripper
00088         self.grasp_setup_client[whicharm].send_goal(setup_goal)
00089         self.grasp_setup_client[whicharm].wait_for_result()
00090 
00091     #pick up the nearest object to PointStamped target_point with whicharm 
00092     #(0=right, 1=left)
00093     def pick_up_object_near_point(self, target_point, whicharm):
00094         self.move_to_side(whicharm, False)
00095 #############once is it positioned, we don't want to move the head at all !!!#############
00096 #        rospy.loginfo("pointing the head at the target point")
00097 #        self.papm.point_head(get_xyz(target_point.point),
00098 #                             target_point.header.frame_id)
00099 #########################################################################################        
00100         rospy.loginfo("picking up the nearest object to the target point")
00101         ############################################################
00102         # Creating grasp grasp_goal
00103         grasp_goal = OverheadGraspGoal()
00104         grasp_goal.is_grasp = True
00105         grasp_goal.disable_head = True
00106         grasp_goal.disable_coll = False
00107         grasp_goal.grasp_type=OverheadGraspGoal.VISION_GRASP
00108         grasp_goal.grasp_params = [0] * 3
00109         grasp_goal.grasp_params[0] = target_point.point.x
00110         grasp_goal.grasp_params[1] = target_point.point.y
00111         grasp_goal.behavior_name = "overhead_grasp"
00112         grasp_goal.sig_level = 0.999
00113         ############################################################
00114 
00115         self.grasp_client[whicharm].send_goal(grasp_goal)
00116         self.grasp_client[whicharm].wait_for_result()
00117         result = self.grasp_client[whicharm].get_result()
00118         success = (result.grasp_result == "Object grasped")
00119 
00120         if success:
00121             rospy.loginfo("pick-up was successful!  Moving arm to side")
00122             resetup_goal = OverheadGraspSetupGoal()
00123             resetup_goal.disable_head = True
00124             self.grasp_setup_client[whicharm].send_goal(resetup_goal)
00125             self.grasp_setup_client[whicharm].wait_for_result()
00126         else:
00127             rospy.loginfo("pick-up failed.")
00128 
00129         return success
00130 
00131 
00132     #place the object held in whicharm (0=right, 1=left) down in the 
00133     #place rectangle defined by place_rect_dims (x,y) 
00134     #and place_rect_center (PoseStamped)
00135     def place_object(self, whicharm, place_rect_dims, place_rect_center):
00136 
00137         rospy.loginfo("putting down the object in the r gripper")
00138 
00139         ############################################################
00140         # Creating place goal
00141         grasp_goal = OverheadGraspGoal()
00142         grasp_goal.is_grasp = False
00143         grasp_goal.disable_head = True
00144         grasp_goal.disable_coll = False
00145         grasp_goal.grasp_type=OverheadGraspGoal.MANUAL_GRASP
00146         grasp_goal.grasp_params = [0] * 3
00147         grasp_goal.grasp_params[0] = place_rect_center.pose.position.x
00148         grasp_goal.grasp_params[1] = place_rect_center.pose.position.y
00149         grasp_goal.behavior_name = "overhead_grasp"
00150         grasp_goal.sig_level = 0.999
00151         ############################################################
00152 
00153         self.grasp_client[whicharm].send_goal(grasp_goal)
00154         self.grasp_client[whicharm].wait_for_result()
00155         result = self.grasp_client[whicharm].get_result()
00156         success = (result.grasp_result == "Object placed")
00157 
00158         if success:
00159             rospy.loginfo("place returned success")
00160         else:
00161             rospy.loginfo("place returned failure")
00162         return success
00163 
00164 
00165 if __name__ == "__main__":
00166     import optparse
00167     p = optparse.OptionParser()
00168 
00169     p.add_option('--path', action='store', dest='path_save',type='string',
00170                  default=None, help='this is path to directory for saving files')
00171 
00172     opt, args = p.parse_args()
00173 
00174     rospy.init_node('simple_pick_and_place_example')
00175     hcp = HRLControllerPlaypen()
00176 
00177     #adjust for your table 
00178     table_height = 0.529
00179     date = datetime.datetime.now()
00180 
00181     f_name = date.strftime("%Y-%m-%d_%H-%M-%S")
00182 
00183     if opt.path_save == None:
00184         print "Not logging or saving data from playpen"
00185         SAVE = False
00186     else:
00187         save_dir = opt.path_save+f_name
00188         print "Logging and saving playpen data in :", save_dir
00189         SAVE = True
00190     
00191 
00192     if SAVE == True:
00193         os.mkdir(save_dir)
00194 
00195 #print "CHECING FOR DIRECTORY :  ", os.getcwd()+'/../../data/'+f_name
00196     #.5 m in front of robot, centered
00197     target_point_xyz = [.625, 0, table_height]   #this is currently an approximation/hack should use ar tag
00198     target_point = create_point_stamped(target_point_xyz, 'base_link')
00199     arm = 0
00200     rospy.wait_for_service('playpen_train')
00201     rospy.wait_for_service('playpen_check_success')
00202     if SAVE == True:
00203         # rospy.wait_for_service('playpen_save_pt_cloud')
00204         # rospy.wait_for_service('playpen_save_image')
00205         rospy.wait_for_service('pr2_save_pt_cloud')
00206         rospy.wait_for_service('pr2_save_image')
00207 
00208     try:
00209         train = rospy.ServiceProxy('playpen_train', Train)
00210         check_success = rospy.ServiceProxy('playpen_check_success', Check)
00211         if SAVE == True:
00212             save_pr2_cloud = rospy.ServiceProxy('pr2_save_pt_cloud', Save)
00213             save_pr2_image = rospy.ServiceProxy('pr2_save_image', Save)
00214             # save_playpen_cloud = rospy.ServiceProxy('playpen_save_pt_cloud', Save)
00215             # save_playpen_image = rospy.ServiceProxy('playpen_save_image', Save)
00216     except rospy.ServiceException, e:
00217         print "Service call failed: %s"%e
00218 
00219     print "moving arms to side"
00220     hcp.move_to_side(0, False)
00221     hcp.move_to_side(1, False)
00222     print "done moving arms, sleeping ..."
00223     
00224     rospy.sleep(15)
00225     print "done sleeping, now training for table top"
00226 
00227     num_samples = train('table')
00228     for i in xrange(len(hcp.objects_dist)):
00229         try:
00230             if SAVE==True:
00231                 file_handle = open(save_dir+'/object'+str(i).zfill(3)+'.pkl', 'w')
00232             data = {}
00233             hcp.playpen(0)
00234             hcp.conveyor(hcp.objects_dist[i])
00235 
00236             data['success'] = []
00237             data['frames'] = []
00238             data['pressure'] = {}
00239             data['pressure']['which_arm'] = []
00240             data['pressure']['data'] = []
00241 
00242             start_time = rospy.get_time()
00243             # while hcp.tries<3:
00244             while rospy.get_time()-start_time < 100.0:
00245                 print "arm is ", arm
00246                 hcp.move_to_side(arm, True)
00247                 rospy.sleep(7)
00248                 if SAVE == True:
00249                     save_pr2_cloud(save_dir+'/object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_before_pr2.pcd')
00250                     save_pr2_image(save_dir+'/object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_before_pr2.png')
00251                 # save_playpen_cloud(playpen_dir+'object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_before_playpen.pcd')
00252                 # save_playpen_image(playpen_dir+'object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_before_playpen.png')
00253                 num_samples = train('object')
00254                 print "attempting to pick up the object"
00255                 success = hcp.pick_up_object_near_point(target_point, arm)
00256                 print "starting to move arm to side at :", rospy.get_time()
00257                 hcp.move_to_side(arm, False)
00258                 print "moved past move to side arm command at :", rospy.get_time()
00259                 results = []
00260                 
00261                 print "sleeping for 10 seconds, is this necessary ..."
00262                 rospy.sleep(10)
00263                 num_samples = 7
00264                 for j in xrange(num_samples):
00265                    results.append(check_success('').result)
00266                 results.sort()
00267                 print "results are :", results
00268                 print "index into result is :", int(num_samples/2)
00269                 if results[int(num_samples/2)] == 'table':
00270                    success = True
00271                    data['success'].append(success)
00272                 elif results[int(num_samples/2)] == 'object':
00273                    success = False
00274                    data['success'].append(success)
00275                 else:
00276                    success = None
00277                    #hcp.tries = hcp.tries-1 # this is to compensate for failures in perception hopefully
00278 
00279                 print "SUCCESS IS :", success
00280 
00281                 if SAVE == True:
00282                     save_pr2_cloud(save_dir+'/object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_after_pr2.pcd')
00283                     save_pr2_image(save_dir+'/object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_after_pr2.png')
00284                 # save_playpen_cloud(playpen_dir+'object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_after_playpen.pcd')
00285                 # save_playpen_image(playpen_dir+'object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_after_playpen.png')
00286 
00287                 if success:
00288                     hcp.successes=hcp.successes + 1
00289                     #square of size 30 cm by 30 cm
00290                     place_rect_dims = [.1, .1]
00291                     
00292                     inside = False
00293                     while inside == False:
00294                         x = np.random.uniform(-0.18, 0.18, 1)[0]
00295                         y = np.random.uniform(-0.18, 0.18, 1)[0]
00296                         if math.sqrt(x*x+y*y) <= 0.18:
00297                             inside = True
00298                 
00299                     center_xyz = [.625+x, y, table_height+.10]
00300 
00301 
00302                     #aligned with axes of frame_id
00303                     center_quat = [0,0,0,1]
00304                     place_rect_center = create_pose_stamped(center_xyz+center_quat,
00305                                                             'base_link')
00306 
00307                     hcp.place_object(arm, place_rect_dims, place_rect_center)
00308 
00309                 hcp.move_to_side(arm, True)
00310                 arm = arm.__xor__(1)
00311                 hcp.tries = hcp.tries+1
00312 
00313             hcp.playpen(1)
00314             hcp.successes = 0
00315             hcp.tries = 0
00316             cPickle.dump(data, file_handle)
00317             file_handle.close()
00318             hcp.playpen(0)
00319 
00320         except:
00321             print "failed for object"
00322             


pr2_playpen
Author(s): Marc Killpack / mkillpack3@gatech.edu, Advisor: Prof. Charlie Kemp, Lab: Healthcare Robotics Lab at Georgia Tech
autogenerated on Wed Nov 27 2013 12:18:32