code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
#
#
# Copyright (c) 2010, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import mekabot.hrl_robot as hr
import hrl_lib.util as ut, hrl_lib.transforms as tr
import math, numpy as np
import copy
import sys
sys.path.append('../')
import compliant_trajectories as ct
import segway_motion_calc as smc
def compute_workspace(z, hook_angle):
firenze = hr.M3HrlRobot(connect=False)
rot_mat = tr.Rz(hook_angle)*tr.Rx(math.radians(0))*tr.Ry(math.radians(-90))
delta_list = [math.radians(d) for d in [0.,0.,0.,0.,10.,10.,10.]]
x_list,y_list = [],[]
if z < -0.4:
xmin = 0.10
xmax = 0.65
else:
xmin = 0.15
xmax = 0.65
for x in np.arange(xmin,xmax,.01):
for y in np.arange(-0.1,-0.50,-0.01):
if x<0.3 and y>-0.2:
continue
q = firenze.IK('right_arm',np.matrix([x,y,z]).T,rot_mat)
if q != None and firenze.within_physical_limits_right(q,delta_list)==True:
x_list.append(x)
y_list.append(y)
return np.matrix([x_list,y_list])
def create_workspace_dict():
dd = {}
ha_list = [math.radians(d) for d in [0.,90.,-90.]]
for ha in ha_list:
d = {}
for z in np.arange(-0.1,-0.55,-0.01):
print 'z:',z
pts2d = compute_workspace(z,hook_angle=ha)
d[z] = pts2d
dd[ha] = {}
dd[ha]['pts'] = d
ut.save_pickle(dd,'workspace_dict_'+ut.formatted_time()+'.pkl')
def create_workspace_boundary(pkl_name):
dd = ut.load_pickle(pkl_name)
for ha in dd.keys():
pts_dict = dd[ha]['pts']
bndry_dict = {}
for z in pts_dict.keys():
print 'z:',z
wrkspc = pts_dict[z]
if wrkspc.shape[1] < 100:
pts_dict.pop(z)
continue
bndry = smc.compute_boundary(wrkspc)
bndry_dict[z] = bndry
dd[ha]['bndry'] = bndry_dict
ut.save_pickle(dd, pkl_name)
create_workspace_dict()
#if len(sys.argv) != 2:
# print 'Usage:', sys.argv[0], '<wrkspc dict pkl>'
# print 'Exiting ...'
# sys.exit()
#create_workspace_boundary(sys.argv[1])
| [
[
1,
0,
0.2963,
0.0093,
0,
0.66,
0,
4,
0,
1,
0,
0,
4,
0,
0
],
[
1,
0,
0.3056,
0.0093,
0,
0.66,
0.0909,
775,
0,
2,
0,
0,
775,
0,
0
],
[
1,
0,
0.3241,
0.0093,
0,
0.66... | [
"import mekabot.hrl_robot as hr",
"import hrl_lib.util as ut, hrl_lib.transforms as tr",
"import math, numpy as np",
"import copy",
"import sys",
"sys.path.append('../')",
"import compliant_trajectories as ct",
"import segway_motion_calc as smc",
"def compute_workspace(z, hook_angle):\n firenze =... |
#
#
# Copyright (c) 2010, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import hrl_lib.util as ut
import matplotlib_util.util as mpu
import math, numpy as np
import sys
def plot_workspace(pts,ha,z):
if pts.shape[1] == 0:
return
mpu.figure()
good_location = pts.mean(1)
mpu.plot_yx(pts[1,:].A1,pts[0,:].A1,label='ha:%.1f'%(math.degrees(ha)),
axis='equal',linewidth=0)
mpu.plot_yx(good_location[1,:].A1,good_location[0,:].A1,
axis='equal',linewidth=0,scatter_size=90,color='k')
mpu.savefig('z%.2f_ha%.1f.png'%(z,math.degrees(ha)))
argv = sys.argv
fname = sys.argv[1]
dd = ut.load_pickle(fname)
color_list = ['b','y','g']
i = 0
mpu.figure(dpi=100)
for ha in dd.keys():
d = dd[ha]
l = []
key_list = d['pts'].keys()
for k in key_list:
pts = d['pts'][k]
l.append(pts.shape[1])
#plot_workspace(pts,ha,k)
ll = zip(key_list,l)
ll.sort()
key_list,l = zip(*ll)
if ha == 0:
label = 'Hook Left'
elif abs(ha-math.pi/2) < 0.01:
label = 'Hook Down'
continue
else:
label = 'Hook Up'
mpu.plot_yx(key_list,l,axis=None,label=label, color=color_list[i],
xlabel='\# of points with IK soln',
ylabel='Height (m)', scatter_size=8)
i += 1
max_idx = np.argmax(l)
good_height = key_list[max_idx]
print 'good_height:', good_height
mpu.plot_yx([good_height],[l[max_idx]],axis=None,
color='r', xlabel='\# of points with IK soln',
ylabel='Height (m)', scatter_size=8)
d['height'] = good_height
#ut.save_pickle(dd,fname)
#mpu.legend()
#mpu.savefig('workspace_npts.png')
#mpu.show()
| [
[
1,
0,
0.3368,
0.0105,
0,
0.66,
0,
775,
0,
1,
0,
0,
775,
0,
0
],
[
1,
0,
0.3474,
0.0105,
0,
0.66,
0.0909,
781,
0,
1,
0,
0,
781,
0,
0
],
[
1,
0,
0.3579,
0.0105,
0,
... | [
"import hrl_lib.util as ut",
"import matplotlib_util.util as mpu",
"import math, numpy as np",
"import sys",
"def plot_workspace(pts,ha,z):\n if pts.shape[1] == 0:\n return\n mpu.figure()\n good_location = pts.mean(1)\n mpu.plot_yx(pts[1,:].A1,pts[0,:].A1,label='ha:%.1f'%(math.degrees(ha)... |
#
#
# Copyright (c) 2010, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import numpy as np
import hrl_lib.util as ut
#---- X axis -----
#p = ut.load_pickle('eq_pos_2010May01_213254.pkl')
#d = ut.load_pickle('stiffness_2010May01_213323.pkl')
#n = 0
#--- Y axis ----
#p = ut.load_pickle('eq_pos_2010May01_213832.pkl')
#d = ut.load_pickle('stiffness_2010May01_213907.pkl')
#n = 1
#--- Z axis
p = ut.load_pickle('eq_pos_2010May01_214434.pkl')
d = ut.load_pickle('stiffness_2010May01_214512.pkl')
n = 2
pos_list = d['pos_list']
force_list = d['force_list']
stiff_list = []
for pos,force in zip(pos_list,force_list):
dx = pos[n,0]-p[n,0]
f = force[n,0]
print 'force:',f
print 'dx:',dx
stiff_list.append(f/dx)
print stiff_list
| [
[
1,
0,
0.4844,
0.0156,
0,
0.66,
0,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.5,
0.0156,
0,
0.66,
0.1111,
775,
0,
1,
0,
0,
775,
0,
0
],
[
14,
0,
0.7188,
0.0156,
0,
0.... | [
"import numpy as np",
"import hrl_lib.util as ut",
"p = ut.load_pickle('eq_pos_2010May01_214434.pkl')",
"d = ut.load_pickle('stiffness_2010May01_214512.pkl')",
"n = 2",
"pos_list = d['pos_list']",
"force_list = d['force_list']",
"stiff_list = []",
"for pos,force in zip(pos_list,force_list):\n dx ... |
#
#
# Copyright (c) 2010, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import m3.toolbox as m3t
import mekabot.hrl_robot as hr
import time
import math, numpy as np
import hrl_lib.util as ut, hrl_lib.transforms as tr
def record_initial(firenze):
equilibrium_pos_list = []
for i in range(50):
equilibrium_pos_list.append(firenze.end_effector_pos('right_arm'))
eq_pos = np.column_stack(equilibrium_pos_list).mean(1)
ut.save_pickle(eq_pos,'eq_pos_'+ut.formatted_time()+'.pkl')
firenze.bias_wrist_ft('right_arm')
def record_joint_displacements():
print 'hit ENTER to start the recording process'
k=m3t.get_keystroke()
pos_list = []
force_list = []
while k == '\r':
print 'hit ENTER to record configuration, something else to exit'
k=m3t.get_keystroke()
firenze.proxy.step()
pos_list.append(firenze.end_effector_pos('right_arm'))
force_list.append(firenze.get_wrist_force('right_arm', base_frame=True))
ut.save_pickle({'pos_list':pos_list,'force_list':force_list},'stiffness_'+ut.formatted_time()+'.pkl')
firenze.stop()
if __name__ == '__main__':
settings_r = hr.MekaArmSettings(stiffness_list=[0.1939,0.6713,0.997,0.7272,0.75])
firenze = hr.M3HrlRobot(connect = True, right_arm_settings = settings_r)
print 'hit a key to power up the arms.'
k = m3t.get_keystroke()
firenze.power_on()
print 'hit a key to test IK'
k = m3t.get_keystroke()
rot = tr.Ry(math.radians(-90))
p = np.matrix([0.3,-0.40,-0.2]).T
firenze.motors_on()
#firenze.go_cartesian('right_arm', p, rot)
# jep from springloaded door, trial 15
jep = [-0.30365041761032346, 0.3490658503988659, 0.59866827092412689, 1.7924513637028943, 0.4580617747379146, -0.13602429148726047, -0.48610218950666179]
firenze.go_jointangles('right_arm', jep)
print 'hit a key to record equilibrium position'
k = m3t.get_keystroke()
record_initial(firenze)
record_joint_displacements()
print 'hit a key to end everything'
k = m3t.get_keystroke()
firenze.stop()
| [
[
1,
0,
0.31,
0.01,
0,
0.66,
0,
478,
0,
1,
0,
0,
478,
0,
0
],
[
1,
0,
0.32,
0.01,
0,
0.66,
0.1429,
4,
0,
1,
0,
0,
4,
0,
0
],
[
1,
0,
0.33,
0.01,
0,
0.66,
0.2857... | [
"import m3.toolbox as m3t",
"import mekabot.hrl_robot as hr",
"import time",
"import math, numpy as np",
"import hrl_lib.util as ut, hrl_lib.transforms as tr",
"def record_initial(firenze):\n equilibrium_pos_list = []\n for i in range(50):\n equilibrium_pos_list.append(firenze.end_effector_po... |
#
#
# Copyright (c) 2010, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import scipy.optimize as so
import math, numpy as np
import pylab as pl
import sys, optparse, time
import copy
from enthought.mayavi import mlab
import mekabot.hrl_robot as hr
import mekabot.coord_frames as mcf
import matplotlib_util.util as mpu
#import util as ut
import roslib; roslib.load_manifest('2010_icra_epc_pull')
import hrl_lib.util as ut, hrl_lib.transforms as tr
import hrl_tilting_hokuyo.display_3d_mayavi as d3m
import segway_motion_calc as smc
class JointTrajectory():
''' class to store joint trajectories.
data only - use for pickling.
'''
def __init__(self):
self.time_list = [] # time in seconds
self.q_list = [] #each element is a list of 7 joint angles.
self.qdot_list = [] #each element is a list of 7 joint angles.
self.qdotdot_list = [] #each element is a list of 7 joint angles.
## class to store trajectory of a coord frame executing planar motion (x,y,a)
#data only - use for pickling
class PlanarTajectory():
def __init__(self):
self.time_list = [] # time in seconds
self.x_list = []
self.y_list = []
self.a_list = []
class CartesianTajectory():
''' class to store trajectory of cartesian points.
data only - use for pickling
'''
def __init__(self):
self.time_list = [] # time in seconds
self.p_list = [] #each element is a list of 3 coordinates
self.v_list = [] #each element is a list of 3 coordinates (velocity)
class ForceTrajectory():
''' class to store time evolution of the force at the end effector.
data only - use for pickling
'''
def __init__(self):
self.time_list = [] # time in seconds
self.f_list = [] #each element is a list of 3 coordinates
##
# @param traj - JointTrajectory
# @return CartesianTajectory after performing FK on traj to compute
# cartesian position, velocity
def joint_to_cartesian(traj):
firenze = hr.M3HrlRobot(connect=False)
pts = []
cart_vel = []
for i in range(len(traj.q_list)):
q = traj.q_list[i]
p = firenze.FK('right_arm', q)
pts.append(p.A1.tolist())
if traj.qdot_list != []:
qdot = traj.qdot_list[i]
jac = firenze.Jac('right_arm', q)
vel = jac * np.matrix(qdot).T
cart_vel.append(vel.A1[0:3].tolist())
ct = CartesianTajectory()
ct.time_list = copy.copy(traj.time_list)
ct.p_list = copy.copy(pts)
ct.v_list = copy.copy(cart_vel)
#return np.matrix(pts).T
return ct
def plot_forces_quiver(pos_traj,force_traj,color='k'):
import arm_trajectories as at
#if traj.__class__ == at.JointTrajectory:
if isinstance(pos_traj,at.JointTrajectory):
pos_traj = joint_to_cartesian(pos_traj)
pts = np.matrix(pos_traj.p_list).T
label_list = ['X coord (m)', 'Y coord (m)', 'Z coord (m)']
x = pts[0,:].A1.tolist()
y = pts[1,:].A1.tolist()
forces = np.matrix(force_traj.f_list).T
u = (-1*forces[0,:]).A1.tolist()
v = (-1*forces[1,:]).A1.tolist()
pl.quiver(x,y,u,v,width=0.002,color=color,scale=100.0)
# pl.quiver(x,y,u,v,width=0.002,color=color)
pl.axis('equal')
##
# @param xaxis - x axis for the graph (0,1 or 2)
# @param zaxis - for a 3d plot. not implemented.
def plot_cartesian(traj, xaxis=None, yaxis=None, zaxis=None, color='b',label='_nolegend_',
linewidth=2, scatter_size=10, plot_velocity=False):
import arm_trajectories as at
#if traj.__class__ == at.JointTrajectory:
if isinstance(traj,at.JointTrajectory):
traj = joint_to_cartesian(traj)
pts = np.matrix(traj.p_list).T
label_list = ['X coord (m)', 'Y coord (m)', 'Z coord (m)']
x = pts[xaxis,:].A1.tolist()
y = pts[yaxis,:].A1.tolist()
if plot_velocity:
vels = np.matrix(traj.v_list).T
xvel = vels[xaxis,:].A1.tolist()
yvel = vels[yaxis,:].A1.tolist()
if zaxis == None:
mpu.plot_yx(y, x, color, linewidth, '-', scatter_size, label,
axis = 'equal', xlabel = label_list[xaxis],
ylabel = label_list[yaxis],)
if plot_velocity:
mpu.plot_quiver_yxv(y, x, np.matrix([xvel,yvel]),
width = 0.001, scale = 1.)
mpu.legend()
else:
from numpy import array
from enthought.mayavi.api import Engine
engine = Engine()
engine.start()
if len(engine.scenes) == 0:
engine.new_scene()
z = pts[zaxis,:].A1.tolist()
time_list = [t-traj.time_list[0] for t in traj.time_list]
mlab.plot3d(x,y,z,time_list,tube_radius=None,line_width=4)
mlab.axes()
mlab.xlabel(label_list[xaxis])
mlab.ylabel(label_list[yaxis])
mlab.zlabel(label_list[zaxis])
mlab.colorbar(title='Time')
# -------------------------------------------
axes = engine.scenes[0].children[0].children[0].children[1]
axes.axes.position = array([ 0., 0.])
axes.axes.label_format = '%-#6.2g'
axes.title_text_property.font_size=4
## compute the force that the arm would apply given the stiffness matrix
# @param q_actual_traj - Joint Trajectory (actual angles.)
# @param q_eq_traj - Joint Trajectory (equilibrium point angles.)
# @param torque_traj - JointTrajectory (torques measured at the joints.)
# @param rel_stiffness_list - list of 5 elements (stiffness numbers for the joints.)
# @return lots of things, look at the code.
def compute_forces(q_actual_traj,q_eq_traj,torque_traj,rel_stiffness_list):
firenze = hr.M3HrlRobot(connect=False)
d_gains_list_mN_deg_sec = [-100,-120,-15,-25,-1.25]
d_gains_list = [180./1000.*s/math.pi for s in d_gains_list_mN_deg_sec]
stiff_list_mNm_deg = [1800,1300,350,600,60]
stiff_list_Nm_rad = [180./1000.*s/math.pi for s in stiff_list_mNm_deg]
# stiffness_settings = [0.15,0.7,0.8,0.8,0.8]
# dia = np.array(stiffness_settings) * np.array(stiff_list_Nm_rad)
dia = np.array(rel_stiffness_list) * np.array(stiff_list_Nm_rad)
k_q = np.matrix(np.diag(dia))
dia_inv = 1./dia
k_q_inv = np.matrix(np.diag(dia_inv))
actual_cart = joint_to_cartesian(q_actual_traj)
eq_cart = joint_to_cartesian(q_eq_traj)
force_traj_jacinv = ForceTrajectory()
force_traj_stiff = ForceTrajectory()
force_traj_torque = ForceTrajectory()
k_cart_list = []
for q_actual,q_dot,q_eq,actual_pos,eq_pos,t,tau_m in zip(q_actual_traj.q_list,q_actual_traj.qdot_list,q_eq_traj.q_list,actual_cart.p_list,eq_cart.p_list,q_actual_traj.time_list,torque_traj.q_list):
q_eq = firenze.clamp_to_physical_joint_limits('right_arm',q_eq)
q_delta = np.matrix(q_actual).T - np.matrix(q_eq).T
tau = k_q * q_delta[0:5,0] - np.matrix(np.array(d_gains_list)*np.array(q_dot)[0:5]).T
x_delta = np.matrix(actual_pos).T - np.matrix(eq_pos).T
jac_full = firenze.Jac('right_arm',q_actual)
jac = jac_full[0:3,0:5]
jac_full_eq = firenze.Jac('right_arm',q_eq)
jac_eq = jac_full_eq[0:3,0:5]
k_cart = np.linalg.inv((jac_eq*k_q_inv*jac_eq.T)) # calculating stiff matrix using Jacobian for eq pt.
k_cart_list.append(k_cart)
pseudo_inv_jac = np.linalg.inv(jac_full*jac_full.T)*jac_full
tau_full = np.row_stack((tau,np.matrix(tau_m[5:7]).T))
#force = (-1*pseudo_inv_jac*tau_full)[0:3]
force = -1*pseudo_inv_jac[0:3,0:5]*tau
force_traj_jacinv.f_list.append(force.A1.tolist())
force_traj_stiff.f_list.append((k_cart*x_delta).A1.tolist())
force_traj_torque.f_list.append((pseudo_inv_jac*np.matrix(tau_m).T)[0:3].A1.tolist())
return force_traj_jacinv,force_traj_stiff,force_traj_torque,k_cart_list
## return two lists containing the radial and tangential components of the forces.
# @param f_list - list of forces. (each force is a list of 2 or 3 floats)
# @param p_list - list of positions. (each position is a list of 2 or 3 floats)
# @param cx - x coord of the center of the circle.
# @param cy - y coord of the center of the circle.
# @return list of magnitude of radial component, list of magnitude tangential component.
def compute_radial_tangential_forces(f_list,p_list,cx,cy):
f_rad_l,f_tan_l = [],[]
for f,p in zip(f_list,p_list):
rad_vec = np.array([p[0]-cx,p[1]-cy])
rad_vec = rad_vec/np.linalg.norm(rad_vec)
f_vec = np.array([f[0],f[1]])
f_rad_mag = np.dot(f_vec,rad_vec)
f_tan_mag = np.linalg.norm(f_vec-rad_vec*f_rad_mag)
f_rad_mag = abs(f_rad_mag)
f_rad_l.append(f_rad_mag)
f_tan_l.append(f_tan_mag)
return f_rad_l,f_tan_l
## find the x and y coord of the center of the circle and the radius that
# best matches the data.
# @param rad_guess - guess for the radius of the circle
# @param x_guess - guess for x coord of center
# @param y_guess - guess for y coord of center.
# @param pts - 2xN np matrix of points.
# @param method - optimization method. ('fmin' or 'fmin_bfgs')
# @param verbose - passed onto the scipy optimize functions. whether to print out the convergence info.
# @return r,x,y (radius, x and y coord of the center of the circle)
def fit_circle(rad_guess,x_guess,y_guess,pts,method,verbose=True):
def error_function(params):
center = np.matrix((params[0],params[1])).T
rad = params[2]
#print 'pts.shape', pts.shape
#print 'center.shape', center.shape
#print 'ut.norm(pts-center).shape',ut.norm(pts-center).shape
err = ut.norm(pts-center).A1 - rad
res = np.dot(err,err)
return res
params_1 = [x_guess,y_guess,rad_guess]
if method == 'fmin':
r = so.fmin(error_function,params_1,xtol=0.0002,ftol=0.000001,full_output=1,disp=verbose)
opt_params_1,fopt_1 = r[0],r[1]
elif method == 'fmin_bfgs':
r = so.fmin_bfgs(error_function, params_1, full_output=1,
disp = verbose, gtol=1e-5)
opt_params_1,fopt_1 = r[0],r[1]
else:
raise RuntimeError('unknown method: '+method)
params_2 = [x_guess,y_guess+2*rad_guess,rad_guess]
if method == 'fmin':
r = so.fmin(error_function,params_2,xtol=0.0002,ftol=0.000001,full_output=1,disp=verbose)
opt_params_2,fopt_2 = r[0],r[1]
elif method == 'fmin_bfgs':
r = so.fmin_bfgs(error_function, params_2, full_output=1,
disp = verbose, gtol=1e-5)
opt_params_2,fopt_2 = r[0],r[1]
else:
raise RuntimeError('unknown method: '+method)
if fopt_2<fopt_1:
return opt_params_2[2],opt_params_2[0],opt_params_2[1]
else:
return opt_params_1[2],opt_params_1[0],opt_params_1[1]
## changes the cartesian trajectory to put everything in the same frame.
# NOTE - velocity transformation does not work if the segway is also
# moving. This is because I am not logging the velocity of the segway.
# @param pts - CartesianTajectory
# @param st - object of type PlanarTajectory (segway trajectory)
# @return CartesianTajectory
def account_segway_motion(cart_traj,st):
ct = CartesianTajectory()
for i in range(len(cart_traj.p_list)):
x,y,a = st.x_list[i], st.y_list[i], st.a_list[i]
p_tl = np.matrix(cart_traj.p_list[i]).T
p_ts = smc.tsTtl(p_tl, x, y, a)
p = p_ts
ct.p_list.append(p.A1.tolist())
# this is incorrect. I also need to use the velocity of the
# segway. Unclear whether this is useful right now, so not
# implementing it. (Advait. Jan 6, 2010.)
if cart_traj.v_list != []:
v_tl = np.matrix(cart_traj.v_list[i]).T
v_ts = smc.tsRtl(v_tl, a)
ct.v_list.append(v_ts.A1.tolist())
ct.time_list = copy.copy(cart_traj.time_list)
return ct
# @param cart_traj - CartesianTajectory
# @param z_l - list of zenither heights
# @return CartesianTajectory
def account_zenithering(cart_traj, z_l):
ct = CartesianTajectory()
h_start = z_l[0]
for i in range(len(cart_traj.p_list)):
h = z_l[i]
p = cart_traj.p_list[i]
p[2] += h - h_start
ct.p_list.append(p)
# this is incorrect. I also need to use the velocity of the
# zenither. Unclear whether this is useful right now, so not
# implementing it. (Advait. Jan 6, 2010.)
if cart_traj.v_list != []:
ct.v_list.append(cart_traj.v_list[i])
ct.time_list = copy.copy(cart_traj.time_list)
return ct
##
# remove the parts of the trjectory in which the hook is not moving.
# @param ct - cartesian trajectory of the end effector in the world frame.
# @return 2xN np matrix, reject_idx
def filter_cartesian_trajectory(ct):
pts_list = ct.p_list
ee_start_pos = pts_list[0]
l = [pts_list[0]]
for i, p in enumerate(pts_list[1:]):
l.append(p)
pts_2d = (np.matrix(l).T)[0:2,:]
st_pt = pts_2d[:,0]
end_pt = pts_2d[:,-1]
dist_moved = np.linalg.norm(st_pt-end_pt)
#if dist_moved < 0.1:
if dist_moved < 0.03:
reject_idx = i
pts_2d = pts_2d[:,reject_idx:]
return pts_2d, reject_idx
##
# remove the parts of the trjectory in which the hook slipped off
# @param ct - cartesian trajectory of the end effector in the world frame.
# @param ft - force trajectory
# @return cartesian trajectory with the zero force end part removed, force trajectory
def filter_trajectory_force(ct, ft):
vel_list = copy.copy(ct.v_list)
pts_list = copy.copy(ct.p_list)
time_list = copy.copy(ct.time_list)
ft_list = copy.copy(ft.f_list)
f_mag_list = ut.norm(np.matrix(ft.f_list).T).A1.tolist()
if len(pts_list) != len(f_mag_list):
print 'arm_trajectories.filter_trajectory_force: force and end effector lists are not of the same length.'
print 'Exiting ...'
sys.exit()
n_pts = len(pts_list)
i = n_pts - 1
hook_slip_off_threshold = 1.5 # from compliant_trajectories.py
while i > 0:
if f_mag_list[i] < hook_slip_off_threshold:
pts_list.pop()
time_list.pop()
ft_list.pop()
if vel_list != []:
vel_list.pop()
else:
break
i -= 1
ct2 = CartesianTajectory()
ct2.time_list = time_list
ct2.p_list = pts_list
ct2.v_list = vel_list
ft2 = ForceTrajectory()
ft2.time_list = copy.copy(time_list)
ft2.f_list = ft_list
return ct2, ft2
if __name__ == '__main__':
p = optparse.OptionParser()
p.add_option('-f', action='store', type='string', dest='fname',
help='pkl file to use.', default='')
p.add_option('--xy', action='store_true', dest='xy',
help='plot the x and y coordinates of the end effector.')
p.add_option('--yz', action='store_true', dest='yz',
help='plot the y and z coordinates of the end effector.')
p.add_option('--xz', action='store_true', dest='xz',
help='plot the x and z coordinates of the end effector.')
p.add_option('--plot_ellipses', action='store_true', dest='plot_ellipses',
help='plot the stiffness ellipse in the x-y plane')
p.add_option('--pfc', action='store_true', dest='pfc',
help='plot the radial and tangential components of the force.')
p.add_option('--pmf', action='store_true', dest='pmf',
help='plot things with the mechanism alinged with the axes.')
p.add_option('--pff', action='store_true', dest='pff',
help='plot the force field corresponding to a stiffness ellipse.')
p.add_option('--pev', action='store_true', dest='pev',
help='plot the stiffness ellipses for different combinations of the rel stiffnesses.')
p.add_option('--plot_forces', action='store_true', dest='plot_forces',
help='plot the force in the x-y plane')
p.add_option('--plot_forces_error', action='store_true', dest='plot_forces_error',
help='plot the error between the computed and measured (ATI) forces in the x-y plane')
p.add_option('--xyz', action='store_true', dest='xyz',
help='plot in 3d the coordinates of the end effector.')
p.add_option('-r', action='store', type='float', dest='rad',
help='radius of the joint.', default=None)
p.add_option('--noshow', action='store_true', dest='noshow',
help='do not display the figure (use while saving figures to disk)')
p.add_option('--exptplot', action='store_true', dest='exptplot',
help='put all the graphs of an experiment as subplots.')
p.add_option('--sturm', action='store_true', dest='sturm',
help='make log files to send to sturm')
p.add_option('--icra_presentation_plot', action='store_true',
dest='icra_presentation_plot',
help='plot explaining CEP update.')
opt, args = p.parse_args()
fname = opt.fname
xy_flag = opt.xy
yz_flag = opt.yz
xz_flag = opt.xz
plot_forces_flag = opt.plot_forces
plot_ellipses_flag = opt.plot_ellipses
plot_forces_error_flag = opt.plot_forces_error
plot_force_components_flag = opt.pfc
plot_force_field_flag = opt.pff
plot_mechanism_frame = opt.pmf
xyz_flag = opt.xyz
rad = opt.rad
show_fig = not(opt.noshow)
plot_ellipses_vary_flag = opt.pev
expt_plot = opt.exptplot
sturm_output = opt.sturm
if plot_ellipses_vary_flag:
show_fig=False
i = 0
ratio_list1 = [0.1,0.3,0.5,0.7,0.9] # coarse search
ratio_list2 = [0.1,0.3,0.5,0.7,0.9] # coarse search
ratio_list3 = [0.1,0.3,0.5,0.7,0.9] # coarse search
# ratio_list1 = [0.7,0.8,0.9,1.0]
# ratio_list2 = [0.7,0.8,0.9,1.0]
# ratio_list3 = [0.3,0.4,0.5,0.6,0.7]
# ratio_list1 = [1.0,2.,3.0]
# ratio_list2 = [1.,2.,3.]
# ratio_list3 = [0.3,0.4,0.5,0.6,0.7]
inv_mean_list,std_list = [],[]
x_l,y_l,z_l = [],[],[]
s0 = 0.2
#s0 = 0.4
for s1 in ratio_list1:
for s2 in ratio_list2:
for s3 in ratio_list3:
i += 1
s_list = [s0,s1,s2,s3,0.8]
#s_list = [s1,s2,s3,s0,0.8]
print '################## s_list:', s_list
m,s = plot_stiff_ellipse_map(s_list,i)
inv_mean_list.append(1./m)
std_list.append(s)
x_l.append(s1)
y_l.append(s2)
z_l.append(s3)
ut.save_pickle({'x_l':x_l,'y_l':y_l,'z_l':z_l,'inv_mean_list':inv_mean_list,'std_list':std_list},
'stiff_dict_'+ut.formatted_time()+'.pkl')
d3m.plot_points(np.matrix([x_l,y_l,z_l]),scalar_list=inv_mean_list,mode='sphere')
mlab.axes()
d3m.show()
sys.exit()
if fname=='':
print 'please specify a pkl file (-f option)'
print 'Exiting...'
sys.exit()
d = ut.load_pickle(fname)
actual_cartesian_tl = joint_to_cartesian(d['actual'])
actual_cartesian = account_segway_motion(actual_cartesian_tl,d['segway'])
if d.has_key('zenither_list'):
actual_cartesian = account_zenithering(actual_cartesian,
d['zenither_list'])
eq_cartesian_tl = joint_to_cartesian(d['eq_pt'])
eq_cartesian = account_segway_motion(eq_cartesian_tl, d['segway'])
if d.has_key('zenither_list'):
eq_cartesian = account_zenithering(eq_cartesian, d['zenither_list'])
cartesian_force_clean, _ = filter_trajectory_force(actual_cartesian,
d['force'])
pts_2d, reject_idx = filter_cartesian_trajectory(cartesian_force_clean)
if rad != None:
#rad = 0.39 # lab cabinet recessed.
#rad = 0.42 # kitchen cabinet
#rad = 0.80 # lab glass door
pts_list = actual_cartesian.p_list
eq_pts_list = eq_cartesian.p_list
ee_start_pos = pts_list[0]
x_guess = ee_start_pos[0]
y_guess = ee_start_pos[1] - rad
print 'before call to fit_rotary_joint'
force_list = d['force'].f_list
if sturm_output:
str_parts = fname.split('.')
sturm_file_name = str_parts[0]+'_sturm.log'
print 'Sturm file name:', sturm_file_name
sturm_file = open(sturm_file_name,'w')
sturm_pts = cartesian_force_clean.p_list
print 'len(sturm_pts):', len(sturm_pts)
print 'len(pts_list):', len(pts_list)
for i,p in enumerate(sturm_pts[1:]):
sturm_file.write(" ".join(map(str,p)))
sturm_file.write('\n')
sturm_file.write('\n')
sturm_file.close()
rad_guess = rad
rad, cx, cy = fit_circle(rad_guess,x_guess,y_guess,pts_2d,
method='fmin_bfgs',verbose=False)
c_ts = np.matrix([cx, cy, 0.]).T
start_angle = tr.angle_within_mod180(math.atan2(pts_2d[0,1]-cy,
pts_2d[0,0]-cx) - math.pi/2)
end_angle = tr.angle_within_mod180(math.atan2(pts_2d[-1,1]-cy,
pts_2d[-1,0]-cx) - math.pi/2)
mpu.plot_circle(cx, cy, rad, start_angle, end_angle,
label='Actual\_opt', color='r')
if opt.icra_presentation_plot:
mpu.set_figure_size(30,20)
rad = 1.0
x_guess = pts_2d[0,0]
y_guess = pts_2d[1,0] - rad
rad_guess = rad
rad, cx, cy = fit_circle(rad_guess,x_guess,y_guess,pts_2d,
method='fmin_bfgs',verbose=False)
print 'Estimated rad, cx, cy:', rad, cx, cy
start_angle = tr.angle_within_mod180(math.atan2(pts_2d[1,0]-cy,
pts_2d[0,0]-cx) - math.pi/2)
end_angle = tr.angle_within_mod180(math.atan2(pts_2d[1,-1]-cy,
pts_2d[0,-1]-cx) - math.pi/2)
subsample_ratio = 1
pts_2d_s = pts_2d[:,::subsample_ratio]
cep_force_clean, force_new = filter_trajectory_force(eq_cartesian,
d['force'])
cep_2d = np.matrix(cep_force_clean.p_list).T[0:2,reject_idx:]
# first draw the entire CEP and end effector trajectories
mpu.figure()
mpu.plot_yx(pts_2d_s[1,:].A1, pts_2d_s[0,:].A1, color='b',
label = 'FK', axis = 'equal', alpha = 1.0,
scatter_size=7, linewidth=0, marker='x',
marker_edge_width = 1.5)
cep_2d_s = cep_2d[:,::subsample_ratio]
mpu.plot_yx(cep_2d_s[1,:].A1, cep_2d_s[0,:].A1, color='g',
label = 'CEP', axis = 'equal', alpha = 1.0,
scatter_size=10, linewidth=0, marker='+',
marker_edge_width = 1.5)
mpu.plot_circle(cx, cy, rad, start_angle, end_angle,
label='Estimated Kinematics', color='r',
alpha=0.7)
mpu.plot_radii(cx, cy, rad, start_angle, end_angle,
interval=end_angle-start_angle, color='r',
alpha=0.7)
mpu.legend()
mpu.savefig('one.png')
# now zoom in to a small region to show the force
# decomposition.
zoom_location = 10
pts_2d_zoom = pts_2d[:,:zoom_location]
cep_2d_zoom = cep_2d[:,:zoom_location]
mpu.figure()
mpu.plot_yx(pts_2d_zoom[1,:].A1, pts_2d_zoom[0,:].A1, color='b',
label = 'FK', axis = 'equal', alpha = 1.0,
scatter_size=7, linewidth=0, marker='x',
marker_edge_width = 1.5)
mpu.plot_yx(cep_2d_zoom[1,:].A1, cep_2d_zoom[0,:].A1, color='g',
label = 'CEP', axis = 'equal', alpha = 1.0,
scatter_size=10, linewidth=0, marker='+',
marker_edge_width = 1.5)
mpu.pl.xlim(0.28, 0.47)
mpu.legend()
mpu.savefig('two.png')
rad, cx, cy = fit_circle(1.0,x_guess,y_guess,pts_2d_zoom,
method='fmin_bfgs',verbose=False)
print 'Estimated rad, cx, cy:', rad, cx, cy
start_angle = tr.angle_within_mod180(math.atan2(pts_2d[1,0]-cy,
pts_2d[0,0]-cx) - math.pi/2)
end_angle = tr.angle_within_mod180(math.atan2(pts_2d_zoom[1,-1]-cy,
pts_2d_zoom[0,-1]-cx) - math.pi/2)
mpu.plot_circle(cx, cy, rad, start_angle, end_angle,
label='Estimated Kinematics', color='r',
alpha=0.7)
mpu.pl.xlim(0.28, 0.47)
mpu.legend()
mpu.savefig('three.png')
current_pos = pts_2d_zoom[:,-1]
radial_vec = current_pos - np.matrix([cx,cy]).T
radial_vec = radial_vec / np.linalg.norm(radial_vec)
tangential_vec = np.matrix([[0,-1],[1,0]]) * radial_vec
mpu.plot_quiver_yxv([pts_2d_zoom[1,-1]],
[pts_2d_zoom[0,-1]],
radial_vec, scale=10., width = 0.002)
rad_text_loc = pts_2d_zoom[:,-1] + np.matrix([0.001,0.01]).T
mpu.pl.text(rad_text_loc[0,0], rad_text_loc[1,0], '\huge{$\hat v_{rad}$}')
mpu.plot_quiver_yxv([pts_2d_zoom[1,-1]],
[pts_2d_zoom[0,-1]],
tangential_vec, scale=10., width = 0.002)
tan_text_loc = pts_2d_zoom[:,-1] + np.matrix([-0.012, -0.011]).T
mpu.pl.text(tan_text_loc[0,0], tan_text_loc[1,0], s = '\huge{$\hat v_{tan}$}')
mpu.pl.xlim(0.28, 0.47)
mpu.legend()
mpu.savefig('four.png')
wrist_force = -np.matrix(force_new.f_list[zoom_location]).T
frad = (wrist_force[0:2,:].T * radial_vec)[0,0] * radial_vec
mpu.plot_quiver_yxv([pts_2d_zoom[1,-1]],
[pts_2d_zoom[0,-1]],
wrist_force, scale=50., width = 0.002,
color='y')
wf_text = rad_text_loc + np.matrix([-0.05,0.015]).T
mpu.pl.text(wf_text[0,0], wf_text[1,0], color='y',
fontsize = 15, s = 'Wrist Force')
mpu.plot_quiver_yxv([pts_2d_zoom[1,-1]],
[pts_2d_zoom[0,-1]],
frad, scale=50., width = 0.002,
color='y')
frad_text = rad_text_loc + np.matrix([0.,0.015]).T
mpu.pl.text(frad_text[0,0], frad_text[1,0], color='y', s = '\huge{$\hat F_{rad}$}')
mpu.pl.xlim(0.28, 0.47)
mpu.legend()
mpu.savefig('five.png')
frad = (wrist_force[0:2,:].T * radial_vec)[0,0]
hook_force_motion = -(frad - 5) * radial_vec * 0.001
tangential_motion = 0.01 * tangential_vec
total_cep_motion = hook_force_motion + tangential_motion
mpu.plot_quiver_yxv([cep_2d_zoom[1,-1]],
[cep_2d_zoom[0,-1]],
hook_force_motion, scale=0.1, width = 0.002)
hw_text = cep_2d_zoom[:,-1] + np.matrix([-0.002,-0.012]).T
mpu.pl.text(hw_text[0,0], hw_text[1,0], color='k', fontsize=14,
s = '$h[t]$ = $0.1cm/N \cdot (|\hat{F}_{rad}|-5N) \cdot \hat{v}_{rad}$')
mpu.pl.xlim(0.28, 0.47)
mpu.legend()
mpu.savefig('six.png')
mpu.plot_quiver_yxv([cep_2d_zoom[1,-1]],
[cep_2d_zoom[0,-1]],
tangential_motion, scale=0.1, width = 0.002)
mw_text = cep_2d_zoom[:,-1] + np.matrix([-0.038,0.001]).T
mpu.pl.text(mw_text[0,0], mw_text[1,0], color='k', fontsize=14,
s = '$m[t]$ = $1cm \cdot \hat{v}_{tan}$')
mpu.pl.xlim(0.28, 0.47)
mpu.legend()
mpu.savefig('seven.png')
mpu.plot_quiver_yxv([cep_2d_zoom[1,-1]],
[cep_2d_zoom[0,-1]],
total_cep_motion, scale=0.1, width = 0.002)
cep_text = cep_2d_zoom[:,-1] + np.matrix([-0.058,-0.013]).T
mpu.pl.text(cep_text[0,0], cep_text[1,0], color='k', fontsize=14,
s = '$x_{eq}[t]$ = &x_{eq}[t-1] + m[t] + h[t]$')
mpu.pl.xlim(0.28, 0.47)
mpu.legend()
mpu.savefig('eight.png')
new_cep = cep_2d_zoom[:,-1] + total_cep_motion
mpu.plot_yx(new_cep[1,:].A1, new_cep[0,:].A1, color='g',
axis = 'equal', alpha = 1.0,
scatter_size=10, linewidth=0, marker='+',
marker_edge_width = 1.5)
mpu.pl.xlim(0.28, 0.47)
mpu.legend()
mpu.savefig('nine.png')
#mpu.plot_radii(cx, cy, rad, start_angle, end_angle,
# interval=end_angle-start_angle, color='r',
# alpha=0.7)
if plot_mechanism_frame:
if expt_plot:
pl.subplot(231)
# transform points so that the mechanism is in a fixed position.
start_pt = actual_cartesian.p_list[0]
x_diff = start_pt[0] - cx
y_diff = start_pt[1] - cy
angle = math.atan2(y_diff,x_diff) - math.radians(90)
rot_mat = tr.Rz(angle)[0:2,0:2]
translation_mat = np.matrix([cx,cy]).T
robot_width,robot_length = 0.1,0.2
robot_x_list = [-robot_width/2,-robot_width/2,robot_width/2,robot_width/2,-robot_width/2]
robot_y_list = [-robot_length/2,robot_length/2,robot_length/2,-robot_length/2,-robot_length/2]
robot_mat = rot_mat*(np.matrix([robot_x_list,robot_y_list]) - translation_mat)
mpu.plot_yx(robot_mat[1,:].A1,robot_mat[0,:].A1,linewidth=2,scatter_size=0,
color='k',label='torso', axis='equal')
pts2d_actual = (np.matrix(actual_cartesian.p_list).T)[0:2]
pts2d_actual_t = rot_mat *(pts2d_actual - translation_mat)
mpu.plot_yx(pts2d_actual_t[1,:].A1,pts2d_actual_t[0,:].A1,scatter_size=20,label='FK',
axis = 'equal')
end_pt = pts2d_actual_t[:,-1]
end_angle = tr.angle_within_mod180(math.atan2(end_pt[1,0],end_pt[0,0])-math.radians(90))
mpu.plot_circle(0,0,rad,0.,end_angle,label='Actual_opt',color='r')
mpu.plot_radii(0,0,rad,0.,end_angle,interval=math.radians(15),color='r')
pl.legend(loc='best')
pl.axis('equal')
if not(expt_plot):
str_parts = fname.split('.')
fig_name = str_parts[0]+'_robot_pose.png'
pl.savefig(fig_name)
pl.figure()
else:
pl.subplot(232)
pl.text(0.1,0.15,d['info'])
pl.text(0.1,0.10,'control: '+d['strategy'])
pl.text(0.1,0.05,'robot angle: %.2f'%math.degrees(angle))
pl.text(0.1,0,'optimized radius: %.2f'%rad_opt)
pl.text(0.1,-0.05,'radius used: %.2f'%rad)
pl.text(0.1,-0.10,'opening angle: %.2f'%math.degrees(end_angle))
s_list = d['stiffness'].stiffness_list
s_scale = d['stiffness'].stiffness_scale
sl = [min(s*s_scale,1.0) for s in s_list]
pl.text(0.1,-0.15,'stiffness list: %.2f, %.2f, %.2f, %.2f'%(sl[0],sl[1],sl[2],sl[3]))
pl.text(0.1,-0.20,'stop condition: '+d['result'])
time_dict = d['time_dict']
pl.text(0.1,-0.25,'time to hook: %.2f'%(time_dict['before_hook']-time_dict['before_pull']))
pl.text(0.1,-0.30,'time to pull: %.2f'%(time_dict['before_pull']-time_dict['after_pull']))
pl.ylim(-0.45,0.25)
if not(expt_plot):
pl.figure()
if xy_flag:
st_pt = pts_2d[:,0]
end_pt = pts_2d[:,-1]
# if rad != None:
# start_angle = tr.angle_within_mod180(math.atan2(st_pt[1,0]-cy,st_pt[0,0]-cx) - math.radians(90))
# end_angle = tr.angle_within_mod180(math.atan2(end_pt[1,0]-cy,end_pt[0,0]-cx) - math.radians(90))
#
# print 'start_angle, end_angle:', math.degrees(start_angle), math.degrees(end_angle)
# print 'angle through which mechanism turned:', math.degrees(end_angle-start_angle)
if expt_plot:
pl.subplot(233)
plot_cartesian(actual_cartesian, xaxis=0, yaxis=1, color='b',
label='FK', plot_velocity=False)
plot_cartesian(eq_cartesian, xaxis=0,yaxis=1,color='g',label='Eq Point')
#leg = pl.legend(loc='best',handletextsep=0.020,handlelen=0.003,labelspacing=0.003)
#leg.draw_frame(False)
elif yz_flag:
plot_cartesian(actual_cartesian,xaxis=1,yaxis=2,color='b',label='FK')
plot_cartesian(eq_cartesian, xaxis=1,yaxis=2,color='g',label='Eq Point')
elif xz_flag:
plot_cartesian(actual_cartesian,xaxis=0,yaxis=2,color='b',label='FK')
plot_cartesian(eq_cartesian, xaxis=0,yaxis=2,color='g',label='Eq Point')
if plot_forces_flag or plot_forces_error_flag or plot_ellipses_flag or plot_force_components_flag or plot_force_field_flag:
arm_stiffness_list = d['stiffness'].stiffness_list
scale = d['stiffness'].stiffness_scale
asl = [min(scale*s,1.0) for s in arm_stiffness_list]
ftraj_jinv,ftraj_stiff,ftraj_torque,k_cart_list=compute_forces(d['actual'],d['eq_pt'],
d['torque'],asl)
if plot_forces_flag:
plot_forces_quiver(actual_cartesian,d['force'],color='k')
#plot_forces_quiver(actual_cartesian,ftraj_jinv,color='y')
#plot_forces_quiver(actual_cartesian,ftraj_stiff,color='y')
if plot_ellipses_flag:
#plot_stiff_ellipses(k_cart_list,actual_cartesian)
if expt_plot:
subplotnum=234
else:
pl.figure()
subplotnum=111
plot_stiff_ellipses(k_cart_list,eq_cartesian,subplotnum=subplotnum)
if plot_forces_error_flag:
plot_error_forces(d['force'].f_list,ftraj_jinv.f_list)
#plot_error_forces(d['force'].f_list,ftraj_stiff.f_list)
if plot_force_components_flag:
p_list = actual_cartesian.p_list
cx = 45.
cy = -0.3
frad_list,ftan_list = compute_radial_tangential_forces(d['force'].f_list,p_list,cx,cy)
if expt_plot:
pl.subplot(235)
else:
pl.figure()
time_list = d['force'].time_list
time_list = [t-time_list[0] for t in time_list]
x_coord_list = np.matrix(p_list)[:,0].A1.tolist()
mpu.plot_yx(frad_list,x_coord_list,scatter_size=50,color=time_list,cb_label='time',axis=None)
pl.xlabel('x coord of end effector (m)')
pl.ylabel('magnitude of radial force (N)')
pl.title(d['info'])
if expt_plot:
pl.subplot(236)
else:
pl.figure()
mpu.plot_yx(ftan_list,x_coord_list,scatter_size=50,color=time_list,cb_label='time',axis=None)
pl.xlabel('x coord of end effector (m)')
pl.ylabel('magnitude of tangential force (N)')
pl.title(d['info'])
if plot_force_field_flag:
plot_stiffness_field(k_cart_list[0],plottitle='start')
plot_stiffness_field(k_cart_list[-1],plottitle='end')
str_parts = fname.split('.')
if d.has_key('strategy'):
addon = ''
if opt.xy:
addon = '_xy'
if opt.xz:
addon = '_xz'
fig_name = str_parts[0]+'_'+d['strategy']+addon+'.png'
else:
fig_name = str_parts[0]+'_res.png'
if expt_plot:
f = pl.gcf()
curr_size = f.get_size_inches()
f.set_size_inches(curr_size[0]*2,curr_size[1]*2)
f.savefig(fig_name)
if show_fig:
pl.show()
else:
print '################################'
print 'show_fig is FALSE'
if not(expt_plot):
pl.savefig(fig_name)
if xyz_flag:
plot_cartesian(traj, xaxis=0,yaxis=1,zaxis=2)
mlab.show()
| [
[
1,
0,
0.0347,
0.0011,
0,
0.66,
0,
359,
0,
1,
0,
0,
359,
0,
0
],
[
1,
0,
0.0369,
0.0011,
0,
0.66,
0.0357,
526,
0,
2,
0,
0,
526,
0,
0
],
[
1,
0,
0.038,
0.0011,
0,
0... | [
"import scipy.optimize as so",
"import math, numpy as np",
"import pylab as pl",
"import sys, optparse, time",
"import copy",
"from enthought.mayavi import mlab",
"import mekabot.hrl_robot as hr",
"import mekabot.coord_frames as mcf",
"import matplotlib_util.util as mpu",
"import roslib; roslib.lo... |
#
#
# Copyright (c) 2010, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import sys, time, os, optparse
import math, numpy as np
import copy
import mekabot.coord_frames as mcf
import compliant_trajectories as ct
import m3.toolbox as m3t
import roslib; roslib.load_manifest('2010_icra_epc_pull')
import hrl_lib.util as ut
import hrl_lib.transforms as tr
if __name__=='__main__':
p = optparse.OptionParser()
p.add_option('--ha', action='store', dest='ha',type='float',
default=None,help='hook angle (degrees).')
p.add_option('--ft', action='store', dest='ft',type='float',
default=80.,help='force threshold (Newtons). [default 80.]')
p.add_option('--info', action='store', type='string', dest='info_string',
help='string to save in the pkl log.', default='')
p.add_option('--pull_fixed', action='store_true', dest='pull_fixed',
help='pull with the segway stationary')
p.add_option('--lead', action='store_true', dest='lead',
help='move the segway while pulling')
p.add_option('--lpi', action='store_true', dest='lpi',
help='use the laser pointer interface to designate hooking location')
p.add_option('-p', action='store', dest='p',type='int',
default=2,help='position number')
p.add_option('-z', action='store', dest='z',type='float',
default=1.0,help='zenither height')
p.add_option('--sa', action='store', dest='sa',type='float',
default=0.0,help='servo angle at which to take camera image (DEGREES)')
p.add_option('--sliding_left', action='store_true',
dest='sliding_left',
help='defining the initial motion of the hook.')
p.add_option('--use_jacobian', action='store_true',
dest='use_jacobian',
help='assume that kinematics estimation gives a jacobian')
opt, args = p.parse_args()
ha = opt.ha
z = opt.z
sa = opt.sa
ft = opt.ft
info_string = opt.info_string
lead_flag = opt.lead
lpi_flag = opt.lpi
pull_fixed_flag = opt.pull_fixed
move_segway_flag = not pull_fixed_flag
pnum = opt.p
arm = 'right_arm'
try:
if ha == None:
print 'please specify hook angle (--ha)'
print 'Exiting...'
sys.exit()
cmg = ct.CompliantMotionGenerator(move_segway = move_segway_flag,
use_right_arm = True,
use_left_arm = False)
if lead_flag:
sys.path.append(os.environ['HRLBASEPATH']+'/src/projects/lead')
import lead
print 'hit a key to start leading.'
k=m3t.get_keystroke()
cmg.firenze.power_on()
if move_segway_flag:
mec = cmg.segway_command_node
else:
import segway_omni.segway as segway
mec = segway.Mecanum()
zed = cmg.z
import mekabot.hrl_robot as hr
settings_lead = hr.MekaArmSettings(stiffness_list=[0.2,0.3,0.3,0.5,0.8])
cmg.firenze.set_arm_settings(settings_lead,None)
follower = lead.Lead(cmg.firenze,'right_arm',mec,zed,
max_allowable_height=zed.calib['max_height'],
init_height = zed.get_position_meters())
qr = [0, 0, 0, math.pi/2, -(math.radians(ha)-ct.hook_3dprint_angle), 0, 0]
follower.start_lead_thread(qr=qr)
print 'hit a key to start hook and pull.'
k=m3t.get_keystroke()
follower.stop()
cmg.firenze.set_arm_settings(cmg.settings_stiff,None)
cmg.firenze.step()
cmg.firenze.pose_robot('right_arm')
print 'Hit ENTER to reposition the robot'
k=m3t.get_keystroke()
if k!='\r':
print 'You did not press ENTER.'
print 'Exiting ...'
sys.exit()
hook_location = cmg.firenze.end_effector_pos('right_arm')
pull_loc = cmg.reposition_robot(hook_location)
elif lpi_flag:
import lpi
# import point_cloud_features.pointcloud_features as ppf
import hrl_tilting_hokuyo.processing_3d as p3d
# pc_feat = ppf.PointcloudFeatureExtractor(ros_init_node=False)
cmg.z.torque_move_position(1.0)
cmg.firenze.power_on()
cmg.movement_posture()
if z<0.5:
print 'desired zenither height of %.2f is unsafe.'%(z)
print 'Exiting...'
sys.exit()
hook_location = None
#z_list = [1.0,0.5]
z_list = [opt.z]
i = 0
while hook_location == None:
if i == len(z_list):
print 'Did not get a click. Exiting...'
sys.exit()
z = z_list[i]
cmg.z.torque_move_position(z)
hook_location = lpi.select_location(cmg.cam,cmg.thok,math.radians(sa))
i += 1
hl_thok0 = mcf.thok0Tglobal(hook_location)
hl_torso = mcf.torsoTglobal(hook_location)
t_begin = time.time()
angle = 0.
pull_loc,residual_angle = cmg.reposition_robot(hl_torso,angle,math.radians(ha),
position_number=pnum)
print 'pull_loc:',pull_loc.A1.tolist()
starting_location = copy.copy(hl_torso)
starting_angle = -angle
pose_dict = {}
pose_dict['loc'] = starting_location
pose_dict['angle'] = angle
pose_dict['residual_angle'] = residual_angle
pose_dict['position_number'] = pnum
if opt.sliding_left:
thresh = 2.
else:
thresh = 5.
res, jep = cmg.search_and_hook(arm, math.radians(ha),
pull_loc, residual_angle, thresh)
print 'result of search and hook:', res
if res != 'got a hook':
print 'Did not get a hook.'
print 'Exiting...'
sys.exit()
elif pull_fixed_flag:
print 'hit a key to power up the arms.'
k=m3t.get_keystroke()
cmg.firenze.power_on()
t_begin = time.time()
pull_loc = np.matrix([0.55, -0.2, -.23]).T
if opt.sliding_left:
thresh = 2.
else:
thresh = 5.
res, jep = cmg.search_and_hook(arm, math.radians(ha),
pull_loc, 0., thresh)
print 'result of search and hook:', res
if res != 'got a hook':
print 'Did not get a hook.'
print 'Exiting...'
sys.exit()
residual_angle = 0.
pose_dict = {}
else:
raise RuntimeError('Unsupported. Advait Jan 02, 2010.')
if opt.use_jacobian:
kinematics_estimation = 'jacobian'
else:
kinematics_estimation = 'rotation_center'
t_pull = time.time()
cmg.pull(arm, math.radians(ha), residual_angle, ft, jep,
strategy = 'control_radial_force',
info_string=info_string, cep_vel = 0.10,
kinematics_estimation=kinematics_estimation,
pull_left = opt.sliding_left)
t_end = time.time()
pose_dict['t0'] = t_begin
pose_dict['t1'] = t_pull
pose_dict['t2'] = t_end
ut.save_pickle(pose_dict,'pose_dict_'+ut.formatted_time()+'.pkl')
print 'hit a key to end everything'
k=m3t.get_keystroke()
cmg.stop()
except: # catch all exceptions, stop and re-raise them
print 'Hello, Mr. Exception'
cmg.stop()
raise
| [
[
1,
0,
0.1301,
0.0041,
0,
0.66,
0,
509,
0,
4,
0,
0,
509,
0,
0
],
[
1,
0,
0.1341,
0.0041,
0,
0.66,
0.1,
526,
0,
2,
0,
0,
526,
0,
0
],
[
1,
0,
0.1382,
0.0041,
0,
0.6... | [
"import sys, time, os, optparse",
"import math, numpy as np",
"import copy",
"import mekabot.coord_frames as mcf",
"import compliant_trajectories as ct",
"import m3.toolbox as m3t",
"import roslib; roslib.load_manifest('2010_icra_epc_pull')",
"import roslib; roslib.load_manifest('2010_icra_epc_pull')"... |
#
#
# Copyright (c) 2010, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import roslib
roslib.load_manifest('equilibrium_point_control')
import numpy as np, math
import scipy.optimize as so
import scipy.ndimage as ni
import matplotlib_util.util as mpu
import hrl_lib.util as ut
import hrl_lib.transforms as tr
import hrl_hokuyo.hokuyo_processing as hp
import mekabot.coord_frames as mcf
import util as uto
from opencv.highgui import *
##
# @param pts - 2xN np matrix
# @return r,theta (two 1D np arrays)
def cartesian_to_polar(pts):
r = ut.norm(pts).A1
theta = np.arctan2(pts[1,:],pts[0,:]).A1
return r,theta
##
# @param r - 1D np array
# @param theta - 1D np array (RADIANS)
# @return 2xN np matrix of cartesian points
def polar_to_cartesian(r,theta):
x = r*np.cos(theta)
y = r*np.sin(theta)
return np.matrix(np.row_stack((x,y)))
##
# mx,my,ma - motion of the robot
# cx,cy - axis of mechanism in robot frame.
# start_angle,end_angle - between 0 and 2*pi
def point_contained(mx,my,ma,cx,cy,rad,pts,start_angle,end_angle,buffer):
if abs(mx)>0.2 or abs(my)>0.2 or abs(ma)>math.radians(40):
# print 'too large a motion for point_contained'
return np.array([[]])
pts_t = pts + np.matrix([mx,my]).T
pts_t = tr.Rz(-ma)[0:2,0:2]*pts_t
r,t = cartesian_to_polar(pts_t-np.matrix([cx,cy]).T)
t = np.mod(t,math.pi*2) # I want theta to be b/w 0 and 2pi
if start_angle<end_angle:
f = np.row_stack((r<rad+buffer,r>rad-buffer/2.,t<end_angle,t>start_angle))
else:
f = np.row_stack((r<rad+buffer,r>rad-buffer/2.,t<start_angle,t>end_angle))
idxs = np.where(np.all(f,0))
r_filt = r[idxs]
t_filt = t[idxs]
return polar_to_cartesian(r_filt,t_filt)+np.matrix([cx,cy]).T
def optimize_position(cx,cy,rad,curr_pos,eq_pos,pts,bndry,start_angle,
end_angle,buffer,tangential_force):
scale_x,scale_y,scale_a = 1.,1.,1.
b = min(abs(tangential_force),60.)
if end_angle>start_angle:
# min_alpha = math.radians(30)
max_alpha = math.radians(90)
else:
# min_alpha = math.radians(-150)
max_alpha = math.radians(-90)
min_alpha = max_alpha - math.radians(60-b*0.7)
dist_moved_weight = 0.4 - 0.3*b/60.
alpha_weight = 0.4+1.0*b/60.
bndry_weight = 1.
pts_in_weight = 1.
print 'OPTIMIZE_POSITION'
print 'start_angle:', math.degrees(start_angle)
print 'end_angle:', math.degrees(end_angle)
print 'tangential_force:', tangential_force
def error_function(params):
mx,my,ma = params[0],params[1],params[2]
mx,my,ma = mx/scale_x,my/scale_y,ma/scale_a
#x,y = params[0],params[1]
pts_in = point_contained(mx,my,ma,cx,cy,rad,pts,
start_angle,end_angle,buffer)
p = tr.Rz(ma)*curr_pos-np.matrix([mx,my,0.]).T
p_eq = tr.Rz(ma)*eq_pos-np.matrix([mx,my,0.]).T
dist_moved = math.sqrt(mx*mx+my*my)+abs(ma)*0.2
dist_bndry = dist_from_boundary(p_eq,bndry,pts)
alpha = math.pi-(start_angle-ma)
if alpha<min_alpha:
alpha_cost = min_alpha-alpha
elif alpha>max_alpha:
alpha_cost = alpha-max_alpha
else:
alpha_cost = 0.
alpha_cost = alpha_cost * alpha_weight
move_cost = dist_moved * dist_moved_weight
bndry_cost = dist_bndry * bndry_weight
pts_in_cost = pts_in.shape[1]/1000. * pts_in_weight
# print '---------------------------------'
# print 'alpha:',math.degrees(alpha)
# print 'alpha_cost:',alpha_cost
# print 'mx,my:',mx,my
# print 'dist_moved:',dist_moved
# print 'dist_bndry:',dist_bndry
# print 'pts_in.shape[1]:',pts_in.shape[1]
# print 'move_cost:', move_cost
# print 'bndry_cost:',bndry_cost
# print 'pts_in_cost:',pts_in_cost
# return -pts_in.shape[1]+dist_moved - bndry_cost
err = -pts_in_cost-bndry_cost+move_cost+alpha_cost
# print 'error function value:',err
return err
params_1 = [0.,0.,0.]
res = so.fmin_bfgs(error_function,params_1,full_output=1)
r,f = res[0],res[1]
# r,f,d = so.fmin_l_bfgs_b(error_function,params_1,approx_grad=True,
# bounds=[(-0.1*scale_x,0.1*scale_x),
# (-0.1*scale_y,0.1*scale_y),
# (-math.radians(15)*scale_a,
# math.radians(15)*scale_a)],
# m=10, factr=10000000.0,
# pgtol=1.0000000000000001e-05,
# epsilon=0.0001, iprint=-1,
# maxfun=1000)
opt_params = r
# print 'optimized value:',f
mx,my,ma = opt_params[0]/scale_x,opt_params[1]/scale_y,\
opt_params[2]/scale_a
error_function(opt_params)
return mx,my,ma
#return opt_params[0],opt_params[1]
##
# compute the boundary of the 2D points. Making assumptions about
# the density of the points, tested with workspace_dict only.
# @param pts - 2xN np matrix
def compute_boundary(pts):
npim1,nx,ny,br = hp.xy_map_to_np_image(pts,m_per_pixel=0.01,dilation_count=0,padding=10)
npim1 = npim1/255
npim = np.zeros(npim1.shape,dtype='int')
npim[:,:] = npim1[:,:]
connect_structure = np.empty((3,3),dtype='int')
connect_structure[:,:] = 1
erim = ni.binary_erosion(npim,connect_structure,iterations=1)
bim = npim-erim
tup = np.where(bim>0)
bpts = np.row_stack((nx-tup[0],ny-tup[1]))*0.01 + br
# cvim = uto.np2cv(bim)
# cvSaveImage('boundary.png',cvim)
return np.matrix(bpts)
##
#return 2x1 vector from closest boundary point
def vec_from_boundary(curr_pos,bndry):
p = curr_pos[0:2,:]
v = p-bndry
min_idx = np.argmin(ut.norm(v))
return v[:,min_idx]
##
#return distance from boundary. (-ve if outside the boundary)
# @param curr_pos - can be 3x1 np matrix
# @param bndry - boundary (2xN np matrix)
# @param pts - 2xN np matrix. pts whose boundary is bndry
def dist_from_boundary(curr_pos,bndry,pts):
mv = vec_from_boundary(curr_pos,bndry)
# spoly = sg.Polygon((bndry.T).tolist())
# spt = sg.Point(curr_pos[0,0],curr_pos[1,0])
d = np.linalg.norm(mv)
p = curr_pos[0:2,:]
v = p-pts
min_dist = np.min(ut.norm(v))
# print 'min_dist,d:',min_dist,d
# print 'min_dist >= d',min_dist >= d-0.001
if min_dist >= d-0.001:
# print 'I predict outside workspace'
d = -d
# if spoly.contains(spt) == False:
# print 'Shapely predicts outside workspace'
# d = -d
return d
##
# @param curr_pos - current location of end effector. 3x1 np matrix
# @param bndry - workspace boundary. 2xN np matrix
def close_to_boundary(curr_pos,bndry,pts,dist_thresh):
min_dist = dist_from_boundary(curr_pos,bndry,pts)
return min_dist <= dist_thresh
def visualize_boundary():
d = ut.load_pickle('../../pkls/workspace_dict_2009Sep03_010426.pkl')
z = -0.23
k = d.keys()
k_idx = np.argmin(np.abs(np.array(k)-z))
pts = d[k[k_idx]]
bpts = compute_boundary(pts)
cl_list = []
for pt in pts.T:
if close_to_boundary(pt.T,bpts,dist_thresh=0.05)==True:
cl_list.append(pt.A1.tolist())
clpts = np.matrix(cl_list).T
print 'clpts.shape:', clpts.shape
mpu.plot_yx(pts[1,:].A1,pts[0,:].A1,linewidth=0)
mpu.plot_yx(clpts[1,:].A1,clpts[0,:].A1,linewidth=0,color='r')
mpu.plot_yx(bpts[1,:].A1,bpts[0,:].A1,linewidth=0,color='y')
mpu.show()
## transform from torso start to torso local frame.
# @param pts - 3xN np matrix in ts coord frame.
# @param x,y,a - motion of the segway (in the ms frame)
# @return pts_tl
def tlTts(pts_ts,x,y,a):
pts_ms = mcf.mecanumTglobal(mcf.globalTtorso(pts_ts))
v_org_ms = np.matrix([x,y,0.]).T
pts_ml = tr.Rz(a)*(pts_ms-v_org_ms)
pts_tl = mcf.torsoTglobal(mcf.globalTmecanum(pts_ml))
return pts_tl
## transform from torso local to torso start frame.
# @param pts - 3xN np matrix in tl coord frame.
# @param x,y,a - motion of the segway (in the ms frame)
# @return pts_ts
def tsTtl(pts_tl,x,y,a):
pts_ml = mcf.mecanumTglobal(mcf.globalTtorso(pts_tl))
v_org_ms = np.matrix([x,y,0.]).T
pts_ms = tr.Rz(-a) * pts_ml + v_org_ms
pts_ts = mcf.torsoTglobal(mcf.globalTmecanum(pts_ms))
return pts_ts
## rotate vector from torso local to torso start frame.
# @param vecs_tl - 3xN np matrix in tl coord frame.
# @param a - motion of the segway (in the ms frame)
# @return vecs_ts
def tsRtl(vecs_tl, a):
vecs_ml = mcf.mecanumTglobal(mcf.globalTtorso(vecs_tl, True), True)
vecs_ms = tr.Rz(-a) * vecs_ml
vecs_ts = mcf.torsoTglobal(mcf.globalTmecanum(vecs_ms, True), True)
return vecs_ts
## rotate vector from torso local to torso start frame.
# @param vecs_tl - 3xN np matrix in tl coord frame.
# @param a - motion of the segway (in the ms frame)
# @return vecs_ts
def tlRts(vecs_ts, a):
vecs_ms = mcf.mecanumTglobal(mcf.globalTtorso(vecs_ts, True), True)
vecs_ml = tr.Rz(a) * vecs_ms
vecs_tl = mcf.torsoTglobal(mcf.globalTmecanum(vecs_ml, True), True)
return vecs_tl
def pts_within_dist(p,pts,min_dist,max_dist):
v = p-pts
d_arr = ut.norm(v).A1
idxs = np.where(np.all(np.row_stack((d_arr<max_dist,d_arr>min_dist)),axis=0))
pts_within = pts[:,idxs[0]]
return pts_within
## apologies for the poor name. computes the translation of the torso
# frame that move the eq pt away from closest boundary and rotate such
# that local x axis is perp to mechanism returns 2x1 np matrix, angle
def segway_motion_repulse(curr_pos_tl, eq_pt_tl,bndry, all_pts):
bndry_dist_eq = dist_from_boundary(eq_pt_tl,bndry,all_pts) # signed
bndry_dist_ee = dist_from_boundary(curr_pos_tl,bndry,all_pts) # signed
if bndry_dist_ee < bndry_dist_eq:
p = curr_pos_tl[0:2,:]
bndry_dist = bndry_dist_ee
else:
p = eq_pt_tl[0:2,:]
bndry_dist = bndry_dist_eq
# p = eq_pt_tl[0:2,:]
pts_close = pts_within_dist(p,bndry,0.002,0.07)
v = p-pts_close
d_arr = ut.norm(v).A1
v = v/d_arr
v = v/d_arr # inverse distance weight
resultant = v.sum(1)
res_norm = np.linalg.norm(resultant)
resultant = resultant/res_norm
tvec = -resultant
if bndry_dist < 0.:
tvec = -tvec # eq pt was outside workspace polygon.
if abs(bndry_dist)<0.01 or res_norm<0.01:
# internal external test fails so falling back on
# going to mean.
m = all_pts.mean(1)
tvec = m-p
tvec = -tvec/np.linalg.norm(tvec)
dist_move = 0.
if bndry_dist > 0.05:
dist_move = 0.
else:
dist_move = 1.
tvec = tvec*dist_move # tvec is either a unit vec or zero vec.
return tvec
if __name__ == '__main__':
#d = ut.load_pickle('workspace_dict_2009Sep03_221107.pkl')
d = ut.load_pickle('../../pkls/workspace_dict_2009Sep05_200116.pkl')
z = -0.23
k = d.keys()
k_idx = np.argmin(np.abs(np.array(k)-z))
pts = d[k[k_idx]]
# visualize_boundary()
for kk in k:
pts = d[kk]
bpts = compute_boundary(pts)
cx,cy = 0.7,-0.6
rad = 0.4
# pts_in = point_contained(cx,cy,0.,rad,pts,
# start_angle=math.radians(140),
# end_angle=math.radians(190))
mpu.figure()
mpu.plot_yx(pts[1,:].A1,pts[0,:].A1,linewidth=0)
mpu.plot_yx(bpts[1,:].A1,bpts[0,:].A1,linewidth=0,color='y')
# mpu.plot_yx(pts_in[1,:].A1,pts_in[0,:].A1,linewidth=0,color='g')
# mpu.plot_yx([cy],[cx],linewidth=0,color='r')
mpu.show()
### apologies for the poor name. computes the translation and rotation
## of the torso frame that move the eq pt away from closest boundary
## and rotate such that local x axis is perp to mechanism
## returns 2x1 np matrix, angle
#def segway_motion_repulse(curr_pos_tl,cx_tl,cy_tl,cy_ts,start_pos_ts,
# eq_pt_tl,bndry):
# vec_bndry = vec_from_boundary(eq_pt_tl,bndry)
# dist_boundary = np.linalg.norm(vec_bndry)
# vec_bndry = vec_bndry/dist_boundary
#
# radial_vec_tl = curr_pos_tl[0:2]-np.matrix([cx_tl,cy_tl]).T
# radial_angle = math.atan2(radial_vec_tl[1,0],radial_vec_tl[0,0])
# if cy_ts<start_pos_ts[1,0]:
# err = radial_angle-math.pi/2
# else:
# err = radial_angle +math.pi/2
#
# a_torso = err
# dist_move = max(0.15-dist_boundary,0.)
# if dist_move < 0.04:
# dist_move = 0.
# hook_translation_tl = -vec_bndry*dist_move
#
## print 'vec_bndry:',vec_bndry.A1.tolist()
## print 'dist_boundary:',dist_boundary
#
# return hook_translation_tl,a_torso
| [
[
1,
0,
0.0794,
0.0025,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0819,
0.0025,
0,
0.66,
0.037,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0893,
0.0025,
0,
0.6... | [
"import roslib",
"roslib.load_manifest('equilibrium_point_control')",
"import numpy as np, math",
"import scipy.optimize as so",
"import scipy.ndimage as ni",
"import matplotlib_util.util as mpu",
"import hrl_lib.util as ut",
"import hrl_lib.transforms as tr",
"import hrl_hokuyo.hokuyo_processing as... |
#
#
# Copyright (c) 2010, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import roslib; roslib.load_manifest('2010_icra_epc_pull')
import rospy
from 2010_icra_epc_pull.msg import MechanismKinematicsRot
from geometry_msgs.msg import Point32
import arm_trajectories as at
from threading import RLock
import numpy as np
import time
##
# fit circle to the trajectory, publish the computed kinematics.
# @param cartesian_pts_list - list of 3-tuples. trajectory of the mechanism
# @param pbshr - publisher for the MechanismKinematics message
# @param lock - to make list operations thread safe. (there is a callback too.)
def circle_estimator(cartesian_pts_list, pbshr, lock):
lock.acquire()
n_pts = len(cartesian_pts_list)
pts_2d = (np.matrix(cartesian_pts_list).T)[0:2,:]
lock.release()
if n_pts<2:
time.sleep(0.1)
#pbshr.publish(mk) # don't publish anything.
return
st = pts_2d[:,0]
now = pts_2d[:,-1]
mk = MechanismKinematicsRot()
mk.cx = 0.5
mk.cy = -3.5
mk.cz = cartesian_pts_list[0][2]
mk.rad = 10.
dist_moved = np.linalg.norm(st-now)
if dist_moved<=0.1:
reject_pts_num = n_pts
else:
reject_pts_num = 1
if dist_moved<=0.15:
time.sleep(0.1)
pbshr.publish(mk)
return
# pts_2d = (np.matrix(cartesian_pts_list).T)[0:2,:]
pts_2d = pts_2d[:,reject_pts_num:]
rad = 1.0
#start_pos = np.matrix(cartesian_pts_list[0]).T
start_pos = st
rad,cx,cy = at.fit_circle(rad, start_pos[0,0], start_pos[1,0]-rad,
pts_2d, method='fmin_bfgs', verbose=False)
mk.cx = cx
mk.cy = cy
mk.rad = rad
pbshr.publish(mk)
# append the point to the trajectory
def trajectory_cb(pt32, tup):
cp_list, lock = tup
lock.acquire()
cp_list.append([pt32.x, pt32.y, pt32.z])
lock.release()
if __name__ == '__main__':
cartesian_points_list = []
lock = RLock()
rospy.init_node('kinematics_estimator_least_sq')
mech_kin_pub = rospy.Publisher('mechanism_kinematics_rot',
MechanismKinematicsRot)
rospy.Subscriber('mechanism_trajectory', Point32, trajectory_cb,
(cartesian_points_list, lock))
print 'Begin'
while not rospy.is_shutdown():
circle_estimator(cartesian_points_list, mech_kin_pub, lock)
time.sleep(0.01)
print 'End'
| [
[
1,
0,
0.2735,
0.0085,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.2735,
0.0085,
0,
0.66,
0.1,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.2821,
0.0085,
0,
0.66,... | [
"import roslib; roslib.load_manifest('2010_icra_epc_pull')",
"import roslib; roslib.load_manifest('2010_icra_epc_pull')",
"import rospy",
"from geometry_msgs.msg import Point32",
"import arm_trajectories as at",
"from threading import RLock",
"import numpy as np",
"import time",
"def circle_estimato... |
#
#
# Copyright (c) 2010, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import sys,os
sys.path.append(os.environ['HRLBASEPATH']+'/usr/advait/LPI')
import cam_utm_lpi as cul
import hrl_lib.util as ut
import hrl_lib.transforms as tr
import mekabot.coord_frames as mcf
import math, numpy as np
import util as uto
import tilting_hokuyo.processing_3d as p3d
import camera_config as cc
## returns selected location in global coord frame.
# @param angle - angle at which to take image, and about which to take
# a 3D scan.
def select_location(c,thok,angle):
thok.servo.move_angle(angle)
cvim = c.get_frame()
cvim = c.get_frame()
cvim = c.get_frame()
im_angle = thok.servo.read_angle()
tilt_angles = (math.radians(-20)+angle,math.radians(30)+angle)
pos_list,scan_list = thok.scan(tilt_angles,speed=math.radians(10))
m = p3d.generate_pointcloud(pos_list,scan_list,math.radians(-60), math.radians(60),
0.0,-0.055)
pts = mcf.utmcam0Tglobal(mcf.globalTthok0(m),im_angle)
cam_params = cc.camera_parameters['mekabotUTM']
fx = cam_params['focal_length_x_in_pixels']
fy = cam_params['focal_length_y_in_pixels']
cx,cy = cam_params['optical_center_x_in_pixels'],cam_params['optical_center_y_in_pixels']
cam_proj_mat = np.matrix([[fx, 0, cx],
[0, fy, cy],
[0, 0, 1]])
cvim,pts2d = cul.project_points_in_image(cvim,pts,cam_proj_mat)
cp = cul.get_click_location(cvim)
print 'Clicked location:', cp
if cp == None:
return None
idx = cul.get_index(pts2d.T,cp)
pt3d = pts[:,idx]
pt_interest = mcf.globalTutmcam0(pt3d,im_angle)
hl_thok0 = mcf.thok0Tglobal(pt_interest)
l1,l2 = 0.0,-0.055
d = {}
d['pt'] = hl_thok0
d['pos_list'],d['scan_list'] = pos_list,scan_list
d['l1'],d['l2'] = l1,l2
d['img'] = uto.cv2np(cvim)
ut.save_pickle(d,'hook_plane_scan_'+ut.formatted_time()+'.pkl')
return pt_interest
if __name__ == '__main__':
import camera
import hokuyo.hokuyo_scan as hs
import tilting_hokuyo.tilt_hokuyo_servo as ths
hok = hs.Hokuyo('utm',0,flip=True,ros_init_node=True)
thok = ths.tilt_hokuyo('/dev/robot/servo0',5,hok,l1=0.,l2=-0.055)
cam = camera.Camera('mekabotUTM')
for i in range(10):
cam.get_frame()
pt = select_location(cam,thok)
print 'Selected location in global coordinates:', pt.A1.tolist()
| [
[
1,
0,
0.301,
0.0097,
0,
0.66,
0,
509,
0,
2,
0,
0,
509,
0,
0
],
[
8,
0,
0.3107,
0.0097,
0,
0.66,
0.0909,
243,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.3204,
0.0097,
0,
0.6... | [
"import sys,os",
"sys.path.append(os.environ['HRLBASEPATH']+'/usr/advait/LPI')",
"import cam_utm_lpi as cul",
"import hrl_lib.util as ut",
"import hrl_lib.transforms as tr",
"import mekabot.coord_frames as mcf",
"import math, numpy as np",
"import util as uto",
"import tilting_hokuyo.processing_3d a... |
#!/usr/bin/python
import sys, os
sys.path.append(os.environ['HRLBASEPATH']+'/src/libraries/')
import cameras.dragonfly as dr
import roslib; roslib.load_manifest('modeling_forces')
import rospy
import cv
from collections import deque
import time
import math, numpy as np
import glob
import hrl_lib.util as ut
import hrl_camera.ros_camera as rc
def got_pose_cb(data, got_pose_dict):
if len(data.objects) != 2:
got_pose_dict['pose_fail'] = True
else:
got_pose_dict['pose_fail'] = False
got_pose_dict['flag'] = True
if __name__ == '__main__':
import optparse
p = optparse.OptionParser()
p.add_option('-l', '--log', action='store_true', dest='log', help='log FT data')
p.add_option('-p', '--pub', action='store_true', dest='pub',
help='publish over ROS')
p.add_option('-c', '--conv', action='store_true', dest='avi_to_pngs',
help='convert avi to pngs')
p.add_option('-b', '--bad', action='store_true', dest='bad',
help='find the images on which checker tracking failed.')
p.add_option('-d', '--dir', action='store', default='',
type='string', dest='dir', help='directory with images')
p.add_option('-i', '--images_only', action='store_true',
dest='images_only', help='work with images (no pkl)')
p.add_option('-s', '--single_im', action='store', default='',
type='string', dest='single_fname', help='work with one image')
opt, args = p.parse_args()
camera_name = 'remote_head'
if opt.pub:
import cv
from cv_bridge.cv_bridge import CvBridge, CvBridgeError
from std_msgs.msg import String
from std_msgs.msg import Empty
from sensor_msgs.msg import Image
from sensor_msgs.msg import CameraInfo
from checkerboard_detector.msg import ObjectDetection
rospy.init_node('publish_log_images', anonymous=True)
if opt.single_fname != '':
im_name_list = [opt.single_fname for i in range(10)]
time_list = [time.time() for i in range(10)]
elif opt.images_only:
im_name_list = glob.glob(opt.dir+'/*.png')
#im_name_list = glob.glob(opt.dir+'/*.jpg')
im_name_list.sort()
time_list = [1 for i in range(len(im_name_list))]
else:
l = glob.glob(opt.dir+'/handheld_pull_log*.pkl')
if l == []:
raise RuntimeError('%s does not have a handheld_pull_log'%opt.dir)
pkl_name = l[0]
d = ut.load_pickle(pkl_name)
im_name_list = glob.glob(opt.dir+'/0*.png')
im_name_list.sort()
time_list = d['time_list']
import camera_config as cc
cp = cc.camera_parameters[camera_name]
m = np.array([ [ cp['focal_length_x_in_pixels'], 0.,
cp['optical_center_x_in_pixels'], 0. ],
[ 0., cp['focal_length_y_in_pixels'],
cp['optical_center_y_in_pixels'], 0. ],
[ 0., 0., 1., 0.] ])
intrinsic_list = [m[0,0], m[0,1], m[0,2], 0.0,
m[1,0], m[1,1], m[1,2], 0.0,
m[2,0], m[2,1], m[2,2], 0.0]
topic_name = 'cvcamera_' + camera_name
image_pub = rospy.Publisher(topic_name, Image)
config_pub = rospy.Publisher(topic_name+'_info', CameraInfo)
ch_pub = rospy.Publisher('/checker_to_poses/trigger', Empty)
time.sleep(0.5)
bridge = CvBridge()
got_pose_dict = {'flag': False, 'pose_fail': False}
topic_name_cb = '/checkerdetector/ObjectDetection'
rospy.Subscriber(topic_name_cb, ObjectDetection, got_pose_cb,
got_pose_dict)
failed_im_list = [] # list of filenames on which checkboard detection failed.
n_images = len(im_name_list)
for i in range(n_images):
name = im_name_list[i]
cv_im = cv.LoadImage(name)
rosimage = bridge.cv_to_imgmsg(cv_im, "bgr8")
rosimage.header.stamp = rospy.Time.from_sec(time_list[i])
image_pub.publish(rosimage)
config_pub.publish(CameraInfo(P=intrinsic_list))
t_st = time.time()
while got_pose_dict['flag'] == False:
time.sleep(0.5)
if (time.time()-t_st) > 10.:
break
if got_pose_dict['pose_fail'] == True:
failed_im_list.append(name)
time.sleep(0.5)
got_pose_dict['flag'] = False
got_pose_dict['pose_fail'] = False
if rospy.is_shutdown():
break
print 'Number of images:', n_images
ch_pub.publish() # send trigger to the ft logger.
ut.save_pickle(failed_im_list, 'checker_fail_list.pkl')
if opt.log:
from opencv.cv import *
from opencv.highgui import *
from std_msgs.msg import Empty
rospy.init_node('image logger', anonymous=True)
ft_pub = rospy.Publisher('/ftlogger/trigger', Empty)
cam = dr.dragonfly2(camera_name)
cam.set_frame_rate(30)
cam.set_brightness(0, 651, 0, 65)
for i in range(10):
im = cam.get_frame_debayered() # undistorting slows down frame rate
im_list = deque()
time_list = []
cvNamedWindow('Image Logging', CV_WINDOW_AUTOSIZE)
print 'Started the loop.'
print 'Hit a to start logging, ESC to exit and save pkl'
log_images = False
while not rospy.is_shutdown():
kp = cvWaitKey(1)
if (type(kp) == str and kp == '\x1b') or (type(kp) != str and kp & 255 == 27): # ESC then exit.
t1 = time.time()
ft_pub.publish() # send trigger to the ft logger.
break
if (type(kp) == str and kp == 'a') or (type(kp) != str and kp & 255 == 97): # a to start logging.
log_images = True
t0 = time.time()
ft_pub.publish() # send trigger to the ft logger.
print 'started logging'
im = cam.get_frame_debayered() # undistorting slows down frame rate
if log_images:
time_list.append(time.time())
im_list.append(cvCloneImage(im))
print 'frame rate:', len(time_list)/(t1-t0)
print 'before saving the pkl'
d = {}
t_string = ut.formatted_time()
video_name = 'mechanism_video_'+t_string+'.avi'
vwr = cvCreateVideoWriter(video_name, CV_FOURCC('I','4','2','0'),
30, cvGetSize(im_list[0]), True)
t0 = time.time()
im_name_list = []
time_stamp = ut.formatted_time()
for im in im_list:
cvWriteFrame(vwr, im)
time.sleep(.01) #Important to keep force torque server
#from restarting
t1 = time.time()
print 'disk writing rate:', len(time_list)/(t1-t0)
d['time_list'] = time_list
d['video_name'] = video_name
fname = 'handheld_pull_log_' + t_string + '.pkl'
ut.save_pickle(d, fname)
print 'Done saving the pkl'
if opt.avi_to_pngs:
from opencv.cv import *
from opencv.highgui import *
import util
import camera_config as cc
cp = cc.camera_parameters[camera_name]
size = (int(cp['calibration_image_width']), int(cp['calibration_image_height']))
color = cp['color']
intrinsic_cvmat = cvCreateMat(3,3,cv.CV_32FC1)
distortion_cvmat = cvCreateMat(1,4,cv.CV_32FC1)
imat_np = np.array([[cp['focal_length_x_in_pixels'],0,
cp['optical_center_x_in_pixels']],
[0,cp['focal_length_y_in_pixels'],
cp['optical_center_y_in_pixels']],
[0,0,1]])
intrinsic_cvmat = util.numpymat2cvmat(imat_np)
dmat_np = np.array([[cp['lens_distortion_radial_1'],
cp['lens_distortion_radial_2'],
cp['lens_distortion_tangential_1'],
cp['lens_distortion_tangential_2']]])
distortion_cvmat = util.numpymat2cvmat(dmat_np)
undistort_mapx = cvCreateImage(size, IPL_DEPTH_32F, 1)
undistort_mapy = cvCreateImage(size, IPL_DEPTH_32F, 1)
cvInitUndistortMap(intrinsic_cvmat, distortion_cvmat,
undistort_mapx, undistort_mapy)
if color == True:
undistort_image = cvCreateImage(size, IPL_DEPTH_8U, 3)
else:
undistort_image = cvCreateImage(size, IPL_DEPTH_8U, 1)
#pkl_name = glob.glob(opt.dir+'/handheld_pull_log*.pkl')[0]
#d = ut.load_pickle(pkl_name)
#video_name = opt.dir+'/'+d['video_name']
#time_list = d['time_list']
video_name = glob.glob(opt.dir + 'mechanism_video*.avi')[0]
cap = cvCreateFileCapture(video_name)
#for i in range(len(time_list)):
i = 0
while True:
cvim = cvQueryFrame(cap)
if cvim == None:
break
cvFlip(cvim, cvim)
# undistort the image
cvRemap(cvim, undistort_image, undistort_mapx, undistort_mapy,
CV_INTER_LINEAR, cvScalarAll(0))
nm = opt.dir+'/%05d.png'%i
print 'Saving', nm
cvSaveImage(nm, undistort_image)
i += 1
if opt.bad:
import cv
l = ut.load_pickle(opt.dir+'/checker_fail_list.pkl')
display = False
if display:
wnd = 'Checker Fail Images'
cv.NamedWindow(wnd, cv.CV_WINDOW_AUTOSIZE)
else:
save_dir = opt.dir+'/checker_fail/'
os.system('mkdir %s'%save_dir)
for nm in l:
name = opt.dir+'/'+nm
cv_im = cv.LoadImage(name)
if display:
cv.ShowImage(wnd, cv_im)
cv.WaitKey(0)
else:
save_dir = os.path.normpath(save_dir)
# print 'save_dir:', save_dir
file_name = '_'.join(save_dir.split('/')) + '_%s'%os.path.normpath(nm)
print 'file_name:', file_name
cv.SaveImage(save_dir + '/' + file_name, cv_im)
| [
[
1,
0,
0.0103,
0.0034,
0,
0.66,
0,
509,
0,
2,
0,
0,
509,
0,
0
],
[
8,
0,
0.0137,
0.0034,
0,
0.66,
0.0714,
243,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0172,
0.0034,
0,
0.... | [
"import sys, os",
"sys.path.append(os.environ['HRLBASEPATH']+'/src/libraries/')",
"import cameras.dragonfly as dr",
"import roslib; roslib.load_manifest('modeling_forces')",
"import roslib; roslib.load_manifest('modeling_forces')",
"import rospy",
"import cv",
"from collections import deque",
"impor... |
#
# Assumes that all the logs are in one folder with the file names
# giving the different mechanisms, trial number, open or close etc.
#
import commands
import os
import os.path as pt
import glob
import math, numpy as np
import scipy.signal as ss
import scipy.cluster as clus
import roslib; roslib.load_manifest('modeling_forces')
import modeling_forces.mf_common as mfc
import matplotlib_util.util as mpu
import hrl_lib.util as ut
import scipy.stats as st
import pylab as pb
#import mdp
class pca_plot_gui():
def __init__(self, legend_list, mech_vec_list, proj_mat, dir_list, mn):
self.legend_list = legend_list
self.mech_vec_list = mech_vec_list
self.proj_mat = proj_mat
self.dir_list = dir_list
self.mn = mn
def pick_cb(self, event):
if 'shift' != event.key:
return
selected = np.matrix([event.xdata, event.ydata]).T
# print 'selected', selected.A1
min_list = []
for i, v in enumerate(self.mech_vec_list):
p = self.proj_mat[:, 0:2].T * (v-self.mn)
min_list.append(np.min(ut.norm(p-selected)))
mech_idx = np.argmin(min_list)
print 'Selected mechanism was:', self.legend_list[mech_idx]
plot_tangential_force(self.dir_list[mech_idx], all_trials = True, open = True)
# mpu.figure()
# n_dim = 7
# reconstruction = self.proj_mat[:, 0:n_dim] * (self.proj_mat[:, 0:n_dim].T * (self.mech_vec_list[mech_idx] - self.mn)) + self.mn
# di = extract_pkls(self.dir_list[mech_idx])
# nm = get_mech_name(self.dir_list[mech_idx])
# for i in range(reconstruction.shape[1]):
# mpu.plot_yx(reconstruction[:,i].A1, color=mpu.random_color(),
# plot_title=nm+': %d components'%n_dim)
# mpu.legend()
# mpu.figure()
# plot_velocity(self.dir_list[mech_idx])
mpu.show()
##
# list all the mechanisms in dir_list and allow user to type the
# numbers of the desired mechanisms.
# @return list of paths to the selected mechanisms.
def input_mechanism_list(dir_list):
mech_list = []
for i, m in enumerate(dir_list):
t = m.split('/')
mech = t[-1]
if mech == '':
mech = t[-2]
mech_list.append(mech)
print '%d. %s'%(i, mech)
print ''
print 'Enter mechanism numbers that you want to plot'
s = raw_input()
num_list = map(int, s.split(' '))
chosen_list = []
for n in num_list:
chosen_list.append(dir_list[n])
return chosen_list
##
# remove pkls in which the forces are unreasonable large or small
def clean_data_forces(dir):
l = commands.getoutput('find %s/ -name "*mechanism_trajectories*.pkl"'%dir).splitlines()
for pkl in l:
cmd1 = 'rm -f %s'%pkl
cmd2 = 'svn rm %s'%pkl
d = ut.load_pickle(pkl)
radial_mech = d['force_rad_list']
tangential_mech = d['force_tan_list']
if len(radial_mech) == 0 or len(tangential_mech) == 0:
os.system(cmd1)
os.system(cmd2)
continue
max_force = max(np.max(np.abs(radial_mech)),
np.max(np.abs(tangential_mech)))
if max_force > 120.:
os.system(cmd1)
os.system(cmd2)
n_points = len(radial_mech)
if n_points < 50:
os.system(cmd1)
os.system(cmd2)
if d.has_key('radius'):
r = d['radius']
if r != -1:
ang = np.degrees(d['mechanism_x'])
if np.max(ang) < 20.:
os.system(cmd1)
os.system(cmd2)
if d.has_key('time_list'):
t_l = d['time_list']
time_diff_l = np.array(t_l[1:]) - np.array(t_l[0:-1])
if len(time_diff_l) == 0:
os.system(cmd1)
os.system(cmd2)
continue
max_time_diff = np.max(time_diff_l)
if max_time_diff > 0.3:
print 'max time difference between consec readings:', max_time_diff
os.system(cmd1)
os.system(cmd2)
##
# @param dir_name - directory containing the pkls.
# @param all_trials - plot force for all the trials.
# @param open - Boolean (open or close trial)
# @param filter_speed - mech vel above this will be ignored. for
# ROTARY joints only, radians/sec
def plot_tangential_force(dir_name, all_trials, open = True,
filter_speed=math.radians(100)):
mpu.set_figure_size(4.,4.)
fig1 = mpu.figure()
# fig2 = mpu.figure()
# fig3 = mpu.figure()
if open:
trial = 'open'
else:
trial = 'close'
d = extract_pkls(dir_name, open)
mech_name = get_mech_name(dir_name)
traj_vel_list = []
for i,ftan_l in enumerate(d['ftan_l_l']):
mech_x = d['mechx_l_l'][i]
if d['typ'] == 'rotary':
max_angle = math.radians(30)
type = 'rotary'
else:
max_angle = 0.3
type = 'prismatic'
traj_vel = compute_average_velocity(mech_x, d['time_l_l'][i], max_angle, type)
print 'traj_vel:', traj_vel
if traj_vel == -1:
continue
traj_vel_list.append(traj_vel)
#vel_color_list = ['r', 'g', 'b', 'y', 'k']
#vel_color_list = ['#000000', '#A0A0A0', '#D0D0D0', '#E0E0E0', '#F0F0F0']
#vel_color_list = ['#000000', '#00A0A0', '#00D0D0', '#00E0E0', '#00F0F0']
#vel_color_list = [ '#%02X%02X%02X'%(r,g,b) for (r,g,b) in [(95, 132, 53), (81, 193, 79), (28, 240, 100), (196, 251, 100)]]
vel_color_list = [ '#%02X%02X%02X'%(r,g,b) for (r,g,b) in [(95, 132, 53), (28, 240, 100), (196, 251, 100)]]
traj_vel_sorted = np.sort(traj_vel_list).tolist()
sorted_color_list = []
sorted_scatter_list = []
i = 0
v_prev = traj_vel_sorted[0]
legend_list = []
if d['typ'] == 'rotary':
l = '%.1f'%math.degrees(v_prev)
thresh = math.radians(5)
else:
l = '%.02f'%(v_prev)
thresh = 0.05
t_v = v_prev
v_threshold = 1000.
for j,v in enumerate(traj_vel_sorted):
if (v - v_prev) > thresh:
if d['typ'] == 'rotary':
l = l + ' to %.1f deg/sec'%math.degrees(t_v)
else:
l = l + ' to %.1f m/s'%t_v
legend_list.append(l)
if d['typ'] == 'rotary':
l = '%.1f'%math.degrees(v)
else:
l = '%.02f'%(v)
i += 1
if i >= 2:
v_threshold = min(v_threshold, v)
if d['typ'] == 'rotary':
print 'v_threshold:', math.degrees(v_threshold)
else:
print 'v_threshold:', v_threshold
if i == len(vel_color_list):
i -= 1
v_prev = v
else:
legend_list.append('__nolegend__')
t_v = v
sorted_color_list.append(vel_color_list[i])
if d['typ'] == 'rotary':
l = l + ' to %.1f deg/sec'%math.degrees(t_v)
else:
l = l + ' to %.1f m/s'%t_v
legend_list.append(l)
legend_list = legend_list[1:]
giant_list = []
mpu.set_figure_size(3.,3.)
for i,ftan_l in enumerate(d['ftan_l_l']):
mech_x = d['mechx_l_l'][i]
trial_num = str(d['trial_num_l'][i])
color = None
scatter_size = None
traj_vel = compute_average_velocity(mech_x, d['time_l_l'][i],
max_angle, d['typ'])
if traj_vel == -1:
continue
if traj_vel >= v_threshold:
continue
color = sorted_color_list[traj_vel_sorted.index(traj_vel)]
legend = legend_list[traj_vel_sorted.index(traj_vel)]
if d['typ'] == 'rotary':
#traj_vel = compute_trajectory_velocity(mech_x,d['time_l_l'][i],1)
#if traj_vel >= filter_speed:
# continue
mech_x_degrees = np.degrees(mech_x)
xlabel = 'angle (degrees)'
ylabel = '$f_{tan}$ (N)'
else:
mech_x_degrees = mech_x
xlabel = 'distance (meters)'
ylabel = 'Opening force (N)'
# n_skip = 65
# print '>>>>>>>>>>>>> WARNING BEGIN <<<<<<<<<<<<<<<<<'
# print 'not plotting the last ', n_skip, 'data points for drawers'
# print '>>>>>>>>>>>>> WARNING END <<<<<<<<<<<<<<<<<'
n_skip = 1
mech_x_degrees = mech_x_degrees[:-n_skip]
ftan_l = ftan_l[:-n_skip]
mpu.figure(fig1.number)
#color, scatter_size = None, None
scatter_size = None
if color == None:
color = mpu.random_color()
if scatter_size == None:
scatter_size = 1
giant_list.append((traj_vel, ftan_l, mech_x_degrees, color, legend, xlabel, ylabel, trial_num))
giant_list_sorted = reversed(sorted(giant_list))
for traj_vel, ftan_l, mech_x_degrees, color, legend, xlabel, ylabel, trial_num in giant_list_sorted:
mpu.plot_yx(ftan_l, mech_x_degrees, axis=None,
plot_title= '\huge{%s: %s}'%(mech_name, trial), xlabel=xlabel,
ylabel = ylabel, color = color,
#scatter_size = 5, linewidth = 1, label=trial_num)
scatter_size = scatter_size, linewidth = 1, label=legend)
print '>>>>>>>>>> number of trials <<<<<<<<<<<', len(giant_list)
mpu.figure(fig1.number)
# mpu.legend(display_mode='less_space')
def radial_tangential_ratio(dir_name):
d = extract_pkls(dir_name, open=True)
nm = get_mech_name(dir_name)
frad_ll = d['frad_l_l']
mechx_ll = d['mechx_l_l']
mpu.figure()
for i,ftan_l in enumerate(d['ftan_l_l']):
frad_l = frad_ll[i]
rad_arr = np.array(np.abs(frad_l))
tan_arr = np.array(np.abs(ftan_l))
idxs = np.where(np.logical_and(rad_arr > 0.1, tan_arr > 0.1))
ratio = np.divide(rad_arr[idxs], tan_arr[idxs])
mpu.plot_yx(ratio, np.degrees(np.array(mechx_ll[i])[idxs]),
color = mpu.random_color(), plot_title=nm,
ylabel='radial/tangential', xlabel='Angle (degrees)')
##
# get mechanism name from the directory name.
def get_mech_name(d):
t = d.split('/')
mech_name = t[-1]
if mech_name == '':
mech_name = t[-2]
return mech_name
##
# get all the information from all the pkls in one directory.
# ASSUMES - all pkls are of the same mechanism (same radius, type ...)
# @param open - extract info for opening trials
def extract_pkls(d, open=True, quiet = False, ignore_moment_list=False):
if open:
trial = 'open'
else:
trial = 'close'
l = glob.glob(d+'/*'+trial+'*mechanism_trajectories*.pkl')
l.sort()
ftan_l_l, frad_l_l, mechx_l_l = [], [], []
time_l_l, trial_num_l = [], []
moment_l_l = []
typ, rad = None, None
for p in l:
d = ut.load_pickle(p)
if d.has_key('radius'):
rad = d['radius']
else:
rad = -1
# if quiet == False:
# print p, 'does not have radius'
# return None
if rad != -1:
#moment_l_l.append((np.array(ftan_l_l[-1]) * rad).tolist())
if d.has_key('moment_list'):
moment_l_l.append(d['moment_list'])
else:
# if quiet == False:
# print p, 'does not have moment_list'
# continue
moment_l_l.append([0 for i in range(len(d['force_rad_list']))])
trial_num = p.split('_')[-5]
trial_num_l.append(int(trial_num))
frad_l_l.append(d['force_rad_list'])
ftan_l_l.append(d['force_tan_list'])
if d.has_key('mech_type'):
typ = d['mech_type']
else:
if quiet == False:
print p, 'does not have mech_typ'
return None
mechx_l_l.append(d['mechanism_x'])
if d.has_key('time_list'):
t_l = d['time_list']
else:
t_l = [0.03*i for i in range(len(ftan_l_l))]
#if quiet == False:
# print p, 'does not have time_list'
#return None
time_l_l.append((np.array(t_l)-t_l[0]).tolist())
r = {}
r['ftan_l_l'] = ftan_l_l
r['frad_l_l'] = frad_l_l
r['mechx_l_l'] = mechx_l_l
r['typ'] = typ
r['rad'] = rad
r['time_l_l'] = time_l_l
r['trial_num_l'] = trial_num_l
r['moment_l_l'] = moment_l_l
return r
##
# take max force magnitude within a bin size
# @param bin_size - depends on the units of poses_list
# @param fn - function to apply to the binned force values (e.g. max, min)
# @param ignore_empty - if True then empty bins are ignored. Else the
# value of an empty bin is set to None.
# @param max_pose - maximum value of pose to use if None then derived
# from poses_list
# @param empty_value - what to fill in an empty bin (None, np.nan etc.)
def bin(poses_list, ftan_list, bin_size, fn, ignore_empty,
max_pose=None, empty_value = None):
if max_pose == None:
max_dist = max(poses_list)
else:
max_dist = max_pose
poses_array = np.array(poses_list)
binned_poses_array = np.arange(0., max_dist, bin_size)
binned_force_list = []
binned_poses_list = []
ftan_array = np.array(ftan_list)
for i in range(binned_poses_array.shape[0]-1):
idxs = np.where(np.logical_and(poses_array>=binned_poses_array[i],
poses_array<binned_poses_array[i+1]))
if idxs[0].shape[0] != 0:
binned_poses_list.append(binned_poses_array[i])
binned_force_list.append(fn(ftan_array[idxs]))
elif ignore_empty == False:
binned_poses_list.append(binned_poses_array[i])
binned_force_list.append(empty_value)
return binned_poses_list, binned_force_list
##
# makes a scatter plot with the radius along the x axis and the max
# force along the y-axis. different color for each mechanism
# @param dir_name - directory containing the pkls.
def max_force_radius_scatter(dir_name_list, open=True):
mpu.figure()
if open:
trial = 'Opening'
else:
trial = 'Closing'
for d in dir_name_list:
nm = get_mech_name(d)
print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
print 'MECHANISM:', nm
print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
ftan_l_l, frad_l_l, mechx_l_l, typ, rad = extract_pkls(d, open)
fl, rl = [], []
for n in range(len(ftan_l_l)):
fmax = np.max(np.abs(ftan_l_l[n]))
print 'fmax:', fmax
fl.append(fmax)
rl.append(rad)
print 'Aloha'
print 'len(fl)', len(fl)
print 'len(rl)', len(rl)
#mpu.plot_yx(fl, rl)
plot_title = 'Scatter plot for %s trials'%trial
mpu.plot_yx(fl, rl, color=mpu.random_color(), label=nm,
axis=None, linewidth=0, xlabel='Radius (m)',
ylabel='Maximum Force (N)', plot_title=plot_title)
mpu.legend()
# use all the values of all the bins for all the trials.
# @param plot_type - 'tangential', 'magnitude', 'radial'
def errorbar_one_mechanism(dir_name, open=True, new_figure=True,
filter_speed = math.radians(100),
plot_type='tangential', color=None,
label = None):
if new_figure:
mpu.figure()
nm = get_mech_name(dir_name)
d = extract_pkls(dir_name, open)
ftan_l_l = d['ftan_l_l']
frad_l_l = d['frad_l_l']
mechx_l_l = d['mechx_l_l']
time_l_l = d['time_l_l']
typ = d['typ']
rad = d['rad']
fn = list
binned_mechx_l = []
binned_ftan_ll = []
use_trials_list = []
if plot_type == 'radial':
force_l_l = frad_l_l
if plot_type == 'tangential':
force_l_l = ftan_l_l
if plot_type == 'magnitude':
force_l_l = []
for ta, ra in zip(ftan_l_l, frad_l_l):
force_l_l.append(ut.norm(np.matrix([ta, ra])).A1.tolist())
n_trials = len(force_l_l)
for i in range(n_trials):
if typ == 'rotary':
traj_vel = compute_trajectory_velocity(mechx_l_l[i],
time_l_l[i], 1)
if traj_vel >= filter_speed:
continue
t, f = bin(mechx_l_l[i], force_l_l[i], math.radians(1.),
fn, ignore_empty=False, max_pose=math.radians(60))
if typ == 'prismatic':
t, f = bin(mechx_l_l[i], force_l_l[i], 0.01,
fn, ignore_empty=False, max_pose=0.5)
if len(t) > len(binned_mechx_l):
binned_mechx_l = t
binned_ftan_ll.append(f)
use_trials_list.append(i)
n_trials = len(binned_ftan_ll)
n_bins = len(binned_mechx_l)
force_list_combined = [[] for i in binned_mechx_l]
for i in range(n_trials):
force_l = binned_ftan_ll[i]
for j,p in enumerate(binned_mechx_l):
if force_l[j] != None:
if open:
if j < 5:
force_list_combined[j].append(max(force_l[j]))
continue
else:
if (n_trials-j) < 5:
force_list_combined[j].append(min(force_l[j]))
continue
force_list_combined[j] += force_l[j]
plot_mechx_l = []
mean_l, std_l = [], []
for i,p in enumerate(binned_mechx_l):
f_l = force_list_combined[i]
if len(f_l) == 0:
continue
plot_mechx_l.append(p)
mean_l.append(np.mean(f_l))
std_l.append(np.std(f_l))
if open:
trial = 'Open'
else:
trial = 'Close'
n_sigma = 1
if typ == 'rotary':
x_l = np.degrees(plot_mechx_l)
xlabel='\huge{Angle (degrees)}'
else:
x_l = plot_mechx_l
xlabel='Distance (m)'
std_arr = np.array(std_l) * n_sigma
if color == None:
color = mpu.random_color()
if label == None:
label= nm+' '+plot_type
mpu.plot_errorbar_yx(mean_l, std_arr, x_l, linewidth=1, color=color,
plot_title='\huge{Mean \& %d$\sigma$}'%(n_sigma),
xlabel=xlabel, label=label,
ylabel='\huge{Force (N)}')
mpu.legend()
# take the max of each bin.
def errorbar_one_mechanism_max(dir_name, open=True,
filter_speed=math.radians(100.)):
# mpu.figure()
nm = get_mech_name(dir_name)
d = extract_pkls(dir_name, open)
ftan_l_l = d['ftan_l_l']
frad_l_l = d['frad_l_l']
mechx_l_l = d['mechx_l_l']
time_l_l = d['time_l_l']
typ = d['typ']
rad = d['rad']
fn = max
if open == False:
fn = min
binned_mechx_l = []
binned_ftan_ll = []
use_trials_list = []
n_trials = len(ftan_l_l)
for i in range(n_trials):
if typ == 'rotary':
traj_vel = compute_trajectory_velocity(mechx_l_l[i],
time_l_l[i], 1)
if traj_vel >= filter_speed:
continue
t, f = bin(mechx_l_l[i], ftan_l_l[i], math.radians(1.),
fn, ignore_empty=False, max_pose=math.radians(60))
if typ == 'prismatic':
t, f = bin(mechx_l_l[i], ftan_l_l[i], 0.01,
fn, ignore_empty=False, max_pose=0.5)
if len(t) > len(binned_mechx_l):
binned_mechx_l = t
binned_ftan_ll.append(f)
use_trials_list.append(i)
binned_ftan_arr = np.array(binned_ftan_ll)
plot_mechx_l = []
mean_l, std_l = [], []
for i,p in enumerate(binned_mechx_l):
f_l = []
for j in range(len(use_trials_list)):
if binned_ftan_arr[j,i] != None:
f_l.append(binned_ftan_arr[j,i])
if len(f_l) == 0:
continue
plot_mechx_l.append(p)
mean_l.append(np.mean(f_l))
std_l.append(np.std(f_l))
xlabel = 'Angle (degrees)'
if open:
trial = 'Open'
else:
trial = 'Close'
n_sigma = 1
std_arr = np.array(std_l) * n_sigma
mpu.plot_errorbar_yx(mean_l, std_arr, np.degrees(plot_mechx_l),
linewidth=1, plot_title=nm+': '+trial,
xlabel='Angle (degrees)',
label='Mean \& %d$\sigma$'%(n_sigma),
ylabel='Tangential Force (N)',
color='y')
mpu.legend()
def plot_opening_distances_drawers(dir_name_list):
mpu.figure()
for d in dir_name_list:
nm = get_mech_name(d)
ftan_l_l, frad_l_l, mechx_l_l, typ, rad = extract_pkls(d)
if rad != -1:
# ignoring the cabinet doors.
continue
# print 'Aloha'
# import pdb; pdb.set_trace()
dist_opened_list = []
for x_l in mechx_l_l:
dist_opened_list.append(x_l[-1] - x_l[0])
plot_title = 'Opening distance for drawers'
mpu.plot_yx(dist_opened_list, color=mpu.random_color(), label=nm,
axis=None, linewidth=0, xlabel='Nothing',
ylabel='Distance opened', plot_title=plot_title)
mpu.legend()
def handle_height_histogram(dir_name_list, plot_title=''):
mean_height_list = []
for d in dir_name_list:
nm = get_mech_name(d)
pkl = glob.glob(d+'/mechanism_calc_dict.pkl')
if pkl == []:
print 'Mechanism "%s" does not have a mechanism_calc_dict'%nm
continue
pkl = pkl[0]
mech_calc_dict = ut.load_pickle(pkl)
hb = mech_calc_dict['handle_bottom']
ht = mech_calc_dict['handle_top']
mean_height_list.append((hb+ht)/2.)
#max_height = np.max(mean_height_list)
max_height = 2.0
bin_width = 0.1
bins = np.arange(0.-bin_width/2., max_height+2*bin_width, bin_width)
hist, bin_edges = np.histogram(np.array(mean_height_list), bins)
mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
width=bin_width*0.8, plot_title=plot_title,
xlabel='Height (meters)', ylabel='\# of mechanisms')
def plot_handle_height(dir_name_list, plot_title):
mpu.figure()
for d in dir_name_list:
nm = get_mech_name(d)
pkl = glob.glob(d+'/mechanism_calc_dict.pkl')
if pkl == []:
print 'Mechanism "%s" does not have a mechanism_calc_dict'%nm
continue
pkl = pkl[0]
mech_calc_dict = ut.load_pickle(pkl)
hb = mech_calc_dict['handle_bottom']
ht = mech_calc_dict['handle_top']
di = extract_pkls(d, open=True)
ftan_l_l = di['ftan_l_l']
frad_l_l = di['frad_l_l']
mechx_l_l = di['mechx_l_l']
time_l_l = di['time_l_l']
typ = di['typ']
rad = di['rad']
# ftan_l_l, frad_l_l, mechx_l_l, typ, rad = extract_pkls(d,
# open=True)
fl, hl = [], []
for n in range(len(ftan_l_l)):
fmax = np.max(np.abs(ftan_l_l[n][0:-50]))
fl.append(fmax)
fl.append(fmax)
hl.append(ht)
hl.append(hb)
mpu.plot_yx(hl, fl, color=mpu.random_color(), label=nm,
axis=None, linewidth=0, xlabel='Max opening force',
ylabel='Handle Height (m)', plot_title=plot_title)
mpu.legend()
def distance_of_handle_from_edges():
pass
def plot_handle_height_no_office():
opt = commands.getoutput('cd aggregated_pkls_Feb11; ls --ignore=*HSI* --ignore=*HRL* --ignore=a.py')
d_list = opt.splitlines()
dir_list = []
for d in d_list:
dir_list.append('aggregated_pkls_Feb11/'+d)
plot_title = 'Only homes. Excluding Offices'
plot_handle_height(dir_list[0:], plot_title)
def plot_handle_height_no_fridge_no_freezer():
opt = commands.getoutput('cd aggregated_pkls_Feb11; ls --ignore=*refrigerator* --ignore=*freezer* --ignore=a.py')
d_list = opt.splitlines()
dir_list = []
for d in d_list:
dir_list.append('aggregated_pkls_Feb11/'+d)
plot_title = 'Excluding Refrigerators and Freezers'
plot_handle_height(dir_list[0:], plot_title)
##
# returns the median of the velocity.
def compute_velocity(mech_x, time_list, smooth_window):
x = np.array(mech_x)
t = np.array(time_list)
kin_info = {'disp_mech_coord_arr': np.array(mech_x),
'mech_time_arr': np.array(time_list)}
vel_arr = mfc.velocity(kin_info, smooth_window)
return vel_arr
##
# mech_x must be in RADIANS.
def compute_trajectory_velocity(mech_x, time_list, smooth_window):
vel_arr = compute_velocity(mech_x, time_list, smooth_window)
filt_vel_arr = vel_arr[np.where(vel_arr>math.radians(2.))]
median_vel = np.median(filt_vel_arr)
return median_vel
##
# compute the average velocity = total angle / total time.
def compute_average_velocity(mech_x, time_list, max_angle, type):
reject_num = 20
if len(mech_x) < reject_num:
return -1
mech_x = mech_x[reject_num:]
time_list = time_list[reject_num:]
if mech_x[-1] < max_angle:
return -1
if type == 'rotary':
start_angle = math.radians(1)
elif type == 'prismatic':
start_angle = 0.01
mech_x = np.array(mech_x)
start_idx = np.where(mech_x > start_angle)[0][0]
end_idx = np.where(mech_x > max_angle)[0][0]
start_x = mech_x[start_idx]
end_x = mech_x[end_idx]
start_time = time_list[start_idx]
end_time = time_list[end_idx]
avg_vel = (end_x - start_x) / (end_time - start_time)
return avg_vel
def plot_velocity(dir_name):
d = extract_pkls(dir_name, True)
vel_fig = mpu.figure()
acc_fig = mpu.figure()
for i,time_list in enumerate(d['time_l_l']):
mechx_l = d['mechx_l_l'][i]
mechx_l, vel, acc, time_list = mfc.kinematic_params(mechx_l, time_list, 10)
vel_arr = np.array(vel)
acc_arr = np.array(acc)
trial_num = d['trial_num_l'][i]
xarr = np.array(mechx_l)
idxs = np.where(np.logical_and(xarr < math.radians(20.),
xarr > math.radians(1.)))
color=mpu.random_color()
mpu.figure(vel_fig.number)
mpu.plot_yx(np.degrees(vel_arr[idxs]),
np.degrees(xarr[idxs]), color=color,
label='%d velocity'%trial_num, scatter_size=0)
mpu.legend()
mpu.figure(acc_fig.number)
mpu.plot_yx(np.degrees(acc_arr[idxs]), np.degrees(xarr[idxs]), color=color,
label='%d acc'%trial_num, scatter_size=0)
mpu.legend()
##
# l list of trials with which to correlate c1
# trial is a list of forces (each element is the max force or some
# other representative value for a given angle)
# lab_list - list of labels
def correlate_trials(c1, l, lab_list):
mpu.figure()
x = 0
corr_list = []
x_l = []
for i,c2 in enumerate(l):
res = ss.correlate(np.array(c1), np.array(c2), 'valid')[0]
r1 = ss.correlate(np.array(c1), np.array(c1), 'valid')[0]
r2 = ss.correlate(np.array(c2), np.array(c2), 'valid')[0]
res = res/math.sqrt(r1*r2) # cross correlation coefficient http://www.staff.ncl.ac.uk/oliver.hinton/eee305/Chapter6.pdf
if i == 0 or lab_list[i] == lab_list[i-1]:
corr_list.append(res)
x_l.append(x)
else:
mpu.plot_yx(corr_list, x_l, color=mpu.random_color(),
label=lab_list[i-1], xlabel='Nothing',
ylabel='Cross-Correlation Coefficient')
corr_list = []
x_l = []
x += 1
mpu.plot_yx(corr_list, x_l, color=mpu.random_color(),
label=lab_list[i-1])
mpu.legend()
##
# plot errorbars showing 1 sigma for tangential component of the force
# and the total magnitude of the force. (Trying to verify that what we
# are capturing using our setup is consistent across people)
def compare_tangential_total_magnitude(dir):
mpu.figure()
errorbar_one_mechanism(dir, open = True,
filter_speed = math.radians(30),
plot_type = 'magnitude',
new_figure = False, color='y',
label = '\huge{$\hat F_{normal}$}')
errorbar_one_mechanism(dir, open = True,
filter_speed = math.radians(30),
plot_type = 'tangential', color='b',
new_figure = False,
label = '\huge{$||\hat F_{normal} + \hat F_{plane}||$}')
def max_force_vs_velocity(dir):
di = extract_pkls(dir, open)
ftan_l_l = di['ftan_l_l']
frad_l_l = di['frad_l_l']
mechx_l_l = di['mechx_l_l']
time_l_l = di['time_l_l']
typ = di['typ']
rad = di['rad']
nm = get_mech_name(dir)
# mpu.figure()
color = mpu.random_color()
mfl = []
tvl = []
for i in range(len(ftan_l_l)):
xarr = np.array(mechx_l_l[i])
idxs = np.where(np.logical_and(xarr < math.radians(20.),
xarr > math.radians(1.)))
max_force = np.max(np.array(ftan_l_l[i])[idxs])
mechx_short = np.array(mechx_l_l[i])[idxs]
time_short = np.array(time_l_l[i])[idxs]
vel_arr = compute_velocity(mechx_l_l[i], time_l_l[i], 5)
#vel_arr = compute_velocity(mechx_short[i], time_l_l[i], 5)
vel_short = vel_arr[idxs]
traj_vel = np.max(vel_short)
#acc_arr = compute_velocity(vel_arr, time_l_l[i], 1)
#traj_vel = np.max(acc_arr)
#traj_vel = compute_trajectory_velocity(mechx_short, time_short, 1)
mfl.append(max_force)
tvl.append(traj_vel)
mpu.plot_yx(mfl, tvl, color = color,
xlabel = 'Trajectory vel', label = nm,
ylabel = 'Max tangential force', linewidth=0)
mpu.legend()
def mechanism_radius_histogram(dir_list, color='b'):
rad_list = []
for d in dir_list:
nm = get_mech_name(d)
pkl = glob.glob(d+'/mechanism_info.pkl')
if pkl == []:
print 'Mechanism "%s" does not have a mechanism_info_dict'%nm
continue
pkl = pkl[0]
md = ut.load_pickle(pkl)
if md['radius'] != -1:
rad_list.append(md['radius'])
max_radius = np.max(rad_list)
print 'Rad list:', rad_list
bin_width = 0.05
bins = np.arange(0.-bin_width/2., max_radius+2*bin_width, bin_width)
hist, bin_edges = np.histogram(np.array(rad_list), bins)
print 'Bin Edges:', bin_edges
print 'Hist:', hist
h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
width=0.8*bin_width, xlabel='Radius(meters)',
ylabel='\# of mechanisms',
plot_title='Histogram of radii of rotary mechanisms',
color=color)
return h
def make_vector(mechx, ftan_l, lim, bin_size):
t, f = bin(mechx, ftan_l, bin_size, max,
ignore_empty=False, max_pose=lim,
empty_value = np.nan)
f = np.array(f)
t = np.array(t)
clean_idx = np.where(np.logical_not(np.isnan(f)))
miss_idx = np.where(np.isnan(f))
if len(miss_idx[0]) > 0:
fclean = f[clean_idx]
mechx_clean = t[clean_idx]
mechx_miss = t[miss_idx]
f_inter = mfc.interpolate_1d(mechx_clean, fclean, mechx_miss)
f[np.where(np.isnan(f))] = f_inter
#import pdb
#pdb.set_trace()
return np.matrix(f).T
# this makes the vector unit norm before returning it. Currently, this
# function is only used for PCA.
def make_vector_mechanism(dir, use_moment = False):
print '>>>>>>>>>>>>>>>>>>>>>>'
print 'dir:', dir
di = extract_pkls(dir)
ftan_l_l = di['ftan_l_l']
frad_l_l = di['frad_l_l']
mechx_l_l = di['mechx_l_l']
time_l_l = di['time_l_l']
moment_l_l = di['moment_l_l']
typ = di['typ']
rad = di['rad']
n_trials = len(ftan_l_l)
vec_list = []
tup_list = []
for i in range(n_trials):
if typ == 'rotary':
if use_moment:
torque_l = moment_l_l[i]
else:
torque_l = ftan_l_l[i]
if len(mechx_l_l[i]) < 30:
continue
v = make_vector(mechx_l_l[i], torque_l, lim = math.radians(50.),
bin_size = math.radians(1))
max_angle = math.radians(30)
if typ == 'prismatic':
v = make_vector(mechx_l_l[i], ftan_l_l[i], lim = 0.25,
bin_size = 0.01)
traj_vel = compute_average_velocity(mechx_l_l[i], time_l_l[i], max_angle, typ)
if traj_vel == -1:
continue
#v = v / np.linalg.norm(v)
vec_list.append(v)
tup_list.append((traj_vel,v))
if len(vec_list) <= 1:
return None
tup_list.sort()
[vel_list, vec_list] = zip(*tup_list)
v_prev = vel_list[0]
t_v = v_prev
thresh = math.radians(5)
i = 0
ret_list = []
for j,v in enumerate(vel_list):
if (v - v_prev) > thresh:
i += 1
if i >= 2:
break
v_prev = v
ret_list.append(vec_list[j])
print 'Number of trials:', len(ret_list)
# selecting only the slowest three trials.
# tup_list.sort()
# if len(tup_list) > 3:
# [acc_list, v_list] = zip(*tup_list)
# return np.column_stack(v_list[0:3])
return np.column_stack(ret_list)
##
# one of the figures for the paper.
# showing that different classes have different clusters.
def different_classes_rotary(dir_list):
mech_vec_list = []
legend_list = []
for d in dir_list:
di = extract_pkls(d)
if di == None:
continue
if di.has_key('typ'):
typ = di['typ']
if typ != 'rotary':
#if typ != 'prismatic':
continue
else:
continue
v = make_vector_mechanism(d)
if v == None:
continue
mech_vec_list.append(v)
legend_list.append(get_mech_name(d))
all_vecs = np.column_stack(mech_vec_list)
print '>>>>>>>>> all_vecs.shape <<<<<<<<<<<<<', all_vecs.shape
U, s, _ = np.linalg.svd(np.cov(all_vecs))
mn = np.mean(all_vecs, 1).A1
mpu.set_figure_size(3.,3.)
mpu.figure()
proj_mat = U[:, 0:2]
legend_made_list = [False, False, False]
for i, v in enumerate(mech_vec_list):
p = proj_mat.T * (v - np.matrix(mn).T)
if np.any(p[0,:].A1<0):
print 'First principal component < 0 for some trial of:', legend_list[i]
color = mpu.random_color()
if 'ree' in legend_list[i]:
#color = 'g'
color = '#66FF33'
if legend_made_list[0] == False:
label = 'Freezers'
legend_made_list[0] = True
else:
label = '__nolegend__'
print 'SHAPE:', p.shape
print 'p:', p
elif 'ge' in legend_list[i]:
color = '#FF6633'
#color = 'y'
if legend_made_list[1] == False:
label = 'Refrigerators'
legend_made_list[1] = True
else:
label = '__nolegend__'
else:
#color = 'b'
color = '#3366FF'
if legend_made_list[2] == False:
#label = '\\flushleft Cabinets, Spring \\\\*[-2pt] Loaded Doors'
label = 'Cabinets'
legend_made_list[2] = True
else:
label = '__nolegend__'
mpu.pl.scatter(p[0,:].A1, p[1,:].A1, color = color, s = 15,
label = label)
mpu.pl.xlabel('First Principle Component')
mpu.pl.ylabel('Second Principle Component')
mpu.pl.axis('equal')
mpu.pl.axhline(y=0., color = 'k', ls='--')
mpu.pl.axvline(x=0., color = 'k', ls='--')
#mpu.legend(loc='upper center', display_mode = 'less_space', draw_frame = True)
mpu.legend(loc='center left', display_mode = 'less_space', draw_frame = True)
mpu.figure()
mn = np.mean(all_vecs, 1).A1
mn = mn/np.linalg.norm(mn)
mpu.plot_yx(mn, color = '#FF3300',
label = 'mean (normalized)', scatter_size=7)
c_list = ['#00CCFF', '#643DFF']
for i in range(2):
mpu.plot_yx(U[:,i].flatten(), color = c_list[i],
label = 'Eigenvector %d'%(i+1), scatter_size=7)
mpu.pl.axhline(y=0., color = 'k', ls='--')
mpu.legend(display_mode = 'less_space', draw_frame=False)
mpu.show()
##
# makes a scatter plot with the radius along the x axis and the max
# force along the y-axis. different color for each mechanism
# @param dir_name - directory containing the pkls.
def max_force_hist(dir_name_list, open=True, type=''):
if open:
trial = 'Opening'
else:
trial = 'Closing'
fls, freezer_list, fridge_list, springloaded_list = [],[],[],[]
broiler_list = []
num_mech = 0
lens = []
max_angle = math.radians(15.)
max_dist = 0.1
for d in dir_name_list:
nm = get_mech_name(d)
ep = extract_pkls(d, open, ignore_moment_list=True)
if ep == None:
continue
ftan_l_l = ep['ftan_l_l']
frad_l_l = ep['frad_l_l']
mechx_l_l = ep['mechx_l_l']
typ = ep['typ']
rad = ep['rad']
fl, rl = [], []
for n in range(len(ftan_l_l)):
ftan_l = ftan_l_l[n]
mechx_a = np.array(mechx_l_l[n])
if type == 'prismatic':
indices = np.where(mechx_a < max_dist)[0]
else:
indices = np.where(mechx_a < max_angle)[0]
if len(indices) > 0:
ftan_l = np.array(ftan_l)[indices].tolist()
fmax = np.max(np.abs(ftan_l))
fl.append(fmax)
rl.append(rad)
#fmax_max = np.max(fl)
fmax_max = np.min(fl)
if type == 'rotary':
if 'ree' in nm:
freezer_list.append(fmax_max)
elif 'naveen_microwave' in nm:
# putting microwave in freezers
freezer_list.append(fmax_max)
if fmax_max < 5.:
print 'nm:', nm
elif 'ge' in nm:
fridge_list.append(fmax_max)
elif fmax > 60.:
springloaded_list.append(fmax_max)
else:
if 'ven' in nm:
broiler_list.append(fmax_max)
if fmax_max > 10.:
print 'nm:', nm, 'fmax:', fmax_max
fls.append(fmax_max)
num_mech += 1
lens.append(len(fl))
if len(fls) > 0:
max_force = np.max(fls)
bin_width = 2.5
bins = np.arange(0.-bin_width/2., max_force+2*bin_width, bin_width)
if type == 'rotary':
mpu.set_figure_size(3.,4.)
mpu.figure()
hist, bin_edges = np.histogram(fls, bins)
h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
width=0.8*bin_width, xlabel='Force (Newtons)',
ylabel='\# of mechanisms',
color='b', label='Cabinets')
max_freq = np.max(hist)
hist, bin_edges = np.histogram(freezer_list + fridge_list, bins)
h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
width=0.8*bin_width, xlabel='Force (Newtons)',
ylabel='\# of mechanisms',
color='y', label='Appliances')
hist, bin_edges = np.histogram(springloaded_list, bins)
h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
width=0.8*bin_width, xlabel='Force (Newtons)',
ylabel='\# of mechanisms',
color='g', label='Spring Loaded Doors')
mpu.pl.xticks(np.arange(0.,max_force+2*bin_width, 10.))
mpu.legend(display_mode='less_space', handlelength=1.)
pb.xlim(-bin_width, max_force+bin_width)
pb.ylim(0, max_freq+0.5)
else:
mpu.set_figure_size(3.,4.)
mpu.figure()
hist, bin_edges = np.histogram(fls, bins)
h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
width=0.8*bin_width, xlabel='Force (Newtons)',
ylabel='\# of mechanisms',
color='b', label='Drawers')
max_freq = np.max(hist)
hist, bin_edges = np.histogram(broiler_list, bins)
h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
width=0.8*bin_width, xlabel='Force (Newtons)',
ylabel='\# of mechanisms',
color='y', label='Broilers')
mpu.figure()
bin_width = 2.5
bins = np.arange(0.-bin_width/2., max_force+2*bin_width, bin_width)
hist, bin_edges = np.histogram(fls, bins)
h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
width=0.8*bin_width, xlabel='Force (Newtons)',
ylabel='\# of mechanisms',
color='b', label='All')
mpu.legend()
pb.xlim(-bin_width, max_force+bin_width)
pb.ylim(0, np.max(hist)+1)
mpu.pl.xticks(np.arange(0.,max_force+2*bin_width, 5.))
mpu.pl.yticks(np.arange(0.,np.max(hist)+0.5, 1.))
else:
print "OH NO! FLS <= 0"
def dimen_reduction_mechanisms(dir_list, dimen = 2):
mech_vec_list = []
legend_list = []
dir_list = filter_dir_list(dir_list)
dir_list_new = []
for d in dir_list:
v = make_vector_mechanism(d)
if v == None:
continue
print 'v.shape:', v.shape
mech_vec_list.append(v)
legend_list.append(get_mech_name(d))
dir_list_new.append(d)
all_vecs = np.column_stack(mech_vec_list)
#U, s, _ = np.linalg.svd(np.cov(all_vecs))
normalized_all_vecs = all_vecs
print '>>>>>>>>>>>> all_vecs.shape <<<<<<<<<<<<<<<', all_vecs.shape
#normalized_all_vecs = (all_vecs - all_vecs.mean(1))
#Rule this out as it places equal value on the entire trajectory but we want
#to focus modeling efforts on the beginning of the trajectory
#normalized_all_vecs = normalized_all_vecs / np.std(normalized_all_vecs, 1)
#Removes the effect of force scaling... not sure if we want this
#normalized_all_vecs = normalized_all_vecs / ut.norm(normalized_all_vecs)
U, s, _ = np.linalg.svd(np.cov((normalized_all_vecs)))
perc_account = np.cumsum(s) / np.sum(s)
mpu.plot_yx([0]+list(perc_account))
mpu.set_figure_size(5.,5.)
mpu.figure()
mn = np.mean(all_vecs, 1).A1
mpu.plot_yx(mn/np.linalg.norm(mn), color = '#FF3300',
label = 'mean (normalized)', scatter_size=5)
c_list = ['#%02x%02x%02x'%(r,g,b) for (r,g,b) in [(152, 32, 176), (23,94,16)]]
c_list = ['#00CCFF', '#643DFF']
for i in range(2):
mpu.plot_yx(U[:,i].flatten(), color = c_list[i],
label = 'Eigenvector %d'%(i+1), scatter_size=5)
mpu.pl.axhline(y=0., color = 'k')
mpu.legend(display_mode='less_space')
if dimen == 2:
fig = mpu.figure()
proj_mat = U[:, 0:2]
for i, v in enumerate(mech_vec_list[:]):
p = proj_mat.T * (v - np.matrix(mn).T)
color = mpu.random_color()
label = legend_list[i]
mpu.plot_yx(p[1,:].A1, p[0,:].A1, color = color,
linewidth = 0, label = label,
xlabel='\huge{First Principle Component}',
ylabel='\huge{Second Principle Component}',
axis = 'equal', picker=0.5)
mpu.pl.axhline(y=0., color = 'k', ls='--')
mpu.pl.axvline(x=0., color = 'k', ls='--')
mpu.legend()
ppg = pca_plot_gui(legend_list, mech_vec_list, U,
dir_list_new, np.matrix(mn).T)
fig.canvas.mpl_connect('button_press_event', ppg.pick_cb)
mpu.show()
def filter_dir_list(dir_list, typ = 'rotary', name = None):
filt_list = []
for d in dir_list:
nm = get_mech_name(d)
if name != None:
if name not in nm:
continue
# trial = 'open'
# l = glob.glob(d+'/*'+trial+'*mechanism_trajectories*.pkl')
# di = ut.load_pickle(l[0])
# m_typ = di['typ']
# if m_typ != typ:
# continue
# filt_list.append(d)
di = extract_pkls(d, quiet=True)
if di == None:
continue
if di.has_key('typ'):
m_typ = di['typ']
if m_typ != typ:
continue
filt_list.append(d)
else:
continue
return filt_list
if __name__ == '__main__':
import optparse
p = optparse.OptionParser()
p.add_option('-d', '--dir', action='store', default='',
type='string', dest='dir', help='directory with logged data')
p.add_option('--check_data', action='store_true', dest='check_data',
help='count the number of trajectories for each mechanism')
p.add_option('--rearrange', action='store_true', dest='rearrange',
help='rearrange aggregated pkls into separate folders for each mechanism')
p.add_option('--clean', action='store_true', dest='clean',
help='remove pkls with corrupted data')
p.add_option('--max_force_hist', action='store_true',
dest='max_force_hist', help='histogram of max forces')
p.add_option('--max_force_radius_scatter', action='store_true',
dest='max_force_radius_scatter', help='scatter plot of max force vs radius')
p.add_option('--opening_distances_drawers', action='store_true',
dest='opening_distances_drawers', help='opening distances for drawers')
p.add_option('--plot_handle_height', action='store_true',
dest='plot_handle_height', help='handle height above the ground')
p.add_option('--plot_radius', action='store_true',
dest='plot_radius', help='histogram of radii of the mechanisms')
p.add_option('--correlate', action='store_true',
dest='correlate', help='correlation across different trials')
p.add_option('--consistent_across_people', action='store_true',
dest='consistent_across_people',
help='plot mean and std for tangential and total magnitude of the force')
p.add_option('--dimen_reduc', action='store_true',
dest='dimen_reduc', help='try dimen reduction')
p.add_option('--independence', action='store_true',
dest='independence', help='test for conditional independence')
p.add_option('--mech_models', action='store_true',
dest='mech_models', help='fit mechanical models to data')
p.add_option('--different_classes_rotary', action='store_true',
dest='different_classes_rotary',
help='scatter plot showing the differnt mechanism classes')
opt, args = p.parse_args()
dir_list = commands.getoutput('ls -d %s/*/'%(opt.dir)).splitlines()
# drawers = 0
# cabinets = 0
# for d in dir_list:
# nm = get_mech_name(d)
# di = extract_pkls(d)
# if di == None:
# print 'di was None for:', nm
# continue
# if di['rad'] == -1:
# drawers += 1
# else:
# cabinets += 1
#
# print 'drawers:', drawers
# print 'cabinets:', cabinets
# import sys; sys.exit()
if opt.clean:
clean_data_forces(opt.dir)
elif opt.rearrange:
# listing all the different mechanisms
pkl_list = commands.getoutput('ls %s/*.pkl'%(opt.dir)).splitlines()
mech_name_list = []
for p in pkl_list:
nm = '_'.join(p.split('/')[-1].split('_')[:-5])
print 'p:', p
print 'nm:', nm
mech_name_list.append(nm)
mech_name_list = list(set(mech_name_list))
print 'List of unique mechanisms:', mech_name_list
for mech_name in mech_name_list:
nm = '%s/%s'%(opt.dir, mech_name)
os.system('mkdir %s'%nm)
os.system('mv %s/*%s*.pkl %s'%(opt.dir, mech_name, nm))
elif opt.check_data:
mech_list = []
for i, m in enumerate(dir_list):
t = m.split('/')
mech = t[-1]
if mech == '':
mech = t[-2]
mech_list.append(mech)
print '%d. %s'%(i, mech)
for i,d in enumerate(dir_list):
mech_nm = mech_list[i]
print '------------------------------------'
print 'Mechanism name:', mech_nm
for trial in ['open', 'close']:
l = glob.glob(d+'/*'+trial+'*mechanism_trajectories*.pkl')
l.sort()
print 'Number of %s trials: %d'%(trial, len(l))
elif opt.max_force_radius_scatter:
max_force_radius_scatter(dir_list[0:], open=True)
max_force_radius_scatter(dir_list[0:], open=False)
mpu.show()
elif opt.max_force_hist:
print 'Found %d mechanisms' % len(dir_list[0:])
max_force_hist(filter_dir_list(dir_list[0:], typ='rotary'), open=True, type='rotary')
max_force_hist(filter_dir_list(dir_list[0:], typ='prismatic'), open=True, type='prismatic')
mpu.show()
elif opt.opening_distances_drawers:
plot_opening_distances_drawers(dir_list[0:])
mpu.show()
elif opt.plot_radius:
l1 = filter_dir_list(dir_list, name='ree')
l2 = filter_dir_list(dir_list, name='ge')
print 'LEN:', len(filter_dir_list(dir_list, name=None))
bar1 = mechanism_radius_histogram(filter_dir_list(dir_list, name=None))
bar2 = mechanism_radius_histogram(l1+l2, color='y')
labels = ['Other', 'Freezers and Refrigerators']
mpu.pl.legend([bar1[0],bar2[0]], labels, loc='best')
mpu.show()
elif opt.plot_handle_height:
#plot_title = 'Opening force at different heights'
#plot_handle_height(dir_list[:], plot_title)
#plot_handle_height_no_fridge_no_freezer()
# plot_handle_height_no_office()
#handle_height_histogram(dir_list, plot_title='Homes excluding \n refrigerators and freezers')
#handle_height_histogram(filter_dir_list(dir_list, name='ge'),
# plot_title = 'Refrigerators')
handle_height_histogram(filter_dir_list(dir_list, name='ree'),
plot_title = 'Freezers')
mpu.show()
elif opt.correlate:
cl = []
lab_list = []
ch_list = input_mechanism_list(dir_list)
for i, d in enumerate(ch_list):
nm = get_mech_name(d)
di = extract_pkls(d, open)
ftan_l_l = di['ftan_l_l']
frad_l_l = di['frad_l_l']
mechx_l_l = di['mechx_l_l']
time_l_l = di['time_l_l']
typ = di['typ']
rad = di['rad']
#ftan_l_l, frad_l_l, mechx_l_l, typ, rad = extract_pkls(d, open)
for j in range(len(ftan_l_l)):
if typ == 'rotary':
traj_vel = compute_trajectory_velocity(mechx_l_l[j],time_l_l[j],1)
if traj_vel > math.radians(30):
continue
t, f = bin(mechx_l_l[j], ftan_l_l[j], math.radians(1.),
max, ignore_empty=True, max_pose=math.radians(60))
if typ == 'prismatic':
t, f = bin(mechx_l_l[j], ftan_l_l[j], 0.01,
max, ignore_empty=True, max_pose=0.3)
cl.append(f)
lab_list.append(nm)
correlate_trials(cl[0], cl[:], lab_list)
mpu.show()
elif opt.consistent_across_people:
ch_list = input_mechanism_list(dir_list)
for dir in ch_list:
compare_tangential_total_magnitude(dir)
mpu.show()
elif opt.different_classes_rotary:
different_classes_rotary(dir_list)
elif opt.independence:
test_independence_mechanism(dir_list)
elif opt.dimen_reduc:
#ch_list = input_mechanism_list(dir_list)
#dimen_reduction_mechanisms(ch_list)
#dimen_reduction_mechanisms(filter_dir_list(dir_list, name='HSI_Suite_210_brown_cabinet_right'))
dimen_reduction_mechanisms(dir_list)
elif opt.mech_models:
dir = filter_dir_list(dir_list,
name='patient_room_door')[0]
d = extract_pkls(dir, True)
trial_num_list = d['trial_num_l']
states_l = []
xarr_l = []
varr_l = []
aarr_l = []
forces_l = []
for i, n in enumerate(trial_num_list):
print 'i:', i
# if i != 5:
# continue
#trial_idx = trial_num_list.index()
mechx_l = d['mechx_l_l'][i]
time_list = d['time_l_l'][i]
forces = np.matrix(d['ftan_l_l'][i])
radius = d['rad']
window_len = 15
mechx_l, vel, acc, time_list = mfc.kinematic_params(mechx_l, time_list, window_len)
xarr = np.array(mechx_l)
idxs = np.where(np.logical_and(xarr > math.radians(1), xarr < math.radians(15)))
# smooth x
forces = forces[0, window_len-1:-window_len+1]
#compute vel
forces = forces[0, 1:-1]
# smooth vel
forces = forces[0, window_len-1:-window_len+1]
# compute acc
forces = forces[0, 1:-1]
# smooth acc
forces = forces[0, window_len-1:-window_len+1]
forces = forces[0, idxs[0]]
xarr = np.matrix(xarr[idxs])
varr = np.matrix(np.array(vel)[idxs])
aarr = np.matrix(np.array(acc)[idxs])
xarr_l.append(xarr)
varr_l.append(varr)
aarr_l.append(aarr)
forces_l.append(forces)
#import pdb
#pdb.set_trace()
#door_smd = mfd.DoorSpringMassDamper(radius, k=0., mass=0, damp=0., const=0, noise_cov=0.)
door_smd = mfd.DoorMassDamper(radius)
ones = np.ones(xarr.shape[1])
states_l.append(np.matrix(np.row_stack((xarr, varr, aarr, ones))))
states = np.column_stack(states_l)
forces = np.column_stack(forces_l)
acc_arr = states[2,:].A1
farr = forces.A1
# import pdb; pdb.set_trace()
print 'farr:', farr
print 'acc_arr:', acc_arr
mass = np.mean(np.divide(farr, acc_arr))
print 'mass:', mass
#door_smd = door_smd.fit(states, forces.T)
door_smd = door_smd.fit(states[[1,2],:], forces.T)
print 'fitted model', door_smd
for i in range(len(xarr_l)):
forces = forces_l[i]
xarr = xarr_l[i]
varr = varr_l[i]
aarr = aarr_l[i]
predicted_forces = door_smd.predict(states_l[i][[1,2],:])
predicted_forces_mass = mass * states_l[i][2,:].A1
mpu.figure()
mpu.plot_yx(forces.A1, np.degrees(xarr.A1), label='actual', color='g')
mpu.plot_yx(predicted_forces.A1, np.degrees(xarr.A1), label='predicted SMD', color='b')
mpu.plot_yx(predicted_forces_mass, np.degrees(xarr.A1), label='predicted (mass only)', color='r')
mpu.plot_yx(np.degrees(varr.A1), np.degrees(xarr.A1), label='vel', color=mpu.random_color())
mpu.plot_yx(np.degrees(aarr.A1), np.degrees(xarr.A1), label='acel', color=mpu.random_color())
mpu.legend()
#mpu.show()
#plot_velocity(dir)
mpu.show()
else:
# filt_list = filter_dir_list(dir_list)
# for dir in filt_list:
# max_force_vs_velocity(dir)
# mpu.show()
d_list = input_mechanism_list(dir_list)
# d_list = filter_dir_list(dir_list, typ='prismatic')
# mpu.figure()
traj_vel_l = []
for dir in d_list:
#make_vector_mechanism(dir)
# vel_l = []
# nm = get_mech_name(dir)
# print '>>>>>>>>>> nm:', nm
# d = extract_pkls(dir, ignore_moment_list=True)
# for i, mech_x in enumerate(d['mechx_l_l']):
# time_list = d['time_l_l'][i]
# #v = compute_average_velocity(mech_x, time_list, max_angle=math.radians(30), type='rotary')
# v = compute_average_velocity(mech_x, time_list, max_angle=0.2, type='prismatic')
# print 'v:', v
# if v == -1:
# continue
# vel_l.append(v)
# sorted_vel_l = sorted(vel_l)
# if len(sorted_vel_l) > 6:
# vel_l = sorted_vel_l[0:6]
# else:
# vel_l = sorted_vel_l
# traj_vel_l += vel_l
#
# #print 'mean angular velocity:', math.degrees(np.mean(traj_vel_l))
# #print 'std angular velocity:', math.degrees(np.std(traj_vel_l))
#
# print 'mean angular velocity:', np.mean(traj_vel_l)
# print 'std angular velocity:', np.std(traj_vel_l)
#plot_tangential_force(dir, all_trials = True, open = True,
# filter_speed = math.radians(30))
plot_tangential_force(dir, all_trials = True, open = True)
# nm = get_mech_name(dir)
# mpu.savefig(nm+'_grayscale.png')
# print 'Aloha ', nm
#radial_tangential_ratio(dir)
mpu.show()
| [
[
1,
0,
0.0037,
0.0006,
0,
0.66,
0,
760,
0,
1,
0,
0,
760,
0,
0
],
[
1,
0,
0.0043,
0.0006,
0,
0.66,
0.0222,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0049,
0.0006,
0,
... | [
"import commands",
"import os",
"import os.path as pt",
"import glob",
"import math, numpy as np",
"import scipy.signal as ss",
"import scipy.cluster as clus",
"import roslib; roslib.load_manifest('modeling_forces')",
"import roslib; roslib.load_manifest('modeling_forces')",
"import modeling_force... |
import roslib; roslib.load_manifest('modeling_forces')
import rospy
import hrl_lib.util as ut
import hrl_lib.transforms as tr
import matplotlib_util.util as mpu
import hrl_tilting_hokuyo.display_3d_mayavi as d3m
import modeling_forces.smooth as mfs
import kinematics_estimation as ke
import glob
import math, numpy as np
import sys
##
# plot to ensure that the time stamps in the different logs are
# reasonable.
# TODO - check for the rates too.
def check_time_sync(ft_time_list, mechanism_time_list, hand_time_list):
mpu.plot_yx(np.zeros(len(ft_time_list))+1, ft_time_list,
color = mpu.random_color(), label='ft\_time\_list',
axis=None, linewidth=0.5, scatter_size=10)
mpu.plot_yx(np.zeros(len(mechanism_time_list))+2, mechanism_time_list,
color = mpu.random_color(), label='mechanism\_time\_list',
axis=None, linewidth=0.5, scatter_size=10)
mpu.plot_yx(np.zeros(len(hand_time_list))+3, hand_time_list,
color = mpu.random_color(), label='hand\_time\_list',
axis=None, linewidth=0.5, scatter_size=10)
mpu.legend()
# mpu.show()
##
#
# @return single dict with ft_list, mech_pose_lists, hand_pose_lists
# and ONE time_list
def synchronize(ft_dict, mechanism_dict, hand_dict):
ft_time_arr = np.array(ft_dict['time_list'])
mech_time_arr = np.array(mechanism_dict['time_list'])
hand_time_arr = np.array(hand_dict['time_list'])
print 'ft_time_arr.shape:', ft_time_arr.shape
print 'mech_time_arr.shape:', mech_time_arr.shape
print 'hand_time_arr.shape:', hand_time_arr.shape
start_time = max(ft_time_arr[0], mech_time_arr[0],
hand_time_arr[0])
end_time = min(ft_time_arr[-1], mech_time_arr[-1],
hand_time_arr[-1])
t1_arr = mech_time_arr[np.where(np.logical_and(mech_time_arr >= start_time,
mech_time_arr <= end_time))]
t2_arr = hand_time_arr[np.where(np.logical_and(hand_time_arr >= start_time,
hand_time_arr <= end_time))]
#time_arr = np.arange(start_time, end_time, 0.03) # 30ms
n_times = min(len(t1_arr), len(t2_arr))
time_arr_list = []
i, j = 0, 0
while True:
if t1_arr[i] == t2_arr[j]:
time_arr_list.append(t1_arr[i])
i += 1
j += 1
elif t1_arr[i] > t2_arr[j]:
j += 1
else:
i += 1
if j == n_times or i == n_times:
break
time_arr = np.array(time_arr_list)
tstep_size = .03333333333
uniform_time = np.cumsum(np.round((time_arr[1:] - time_arr[:-1]) / tstep_size) * tstep_size)
uniform_time = np.concatenate((np.array([0]), uniform_time))
uniform_time = uniform_time + time_arr_list[0]
time_arr = uniform_time
# adding a 50ms bias. see modeling_forces/image_ft_sync_test
ft_time_arr = ft_time_arr + 0.05
raw_ft_arr = np.array(ft_dict['ft_list']).T
window_len = 3
sm_ft_l = []
for i in range(raw_ft_arr.shape[0]):
s = mfs.smooth(raw_ft_arr[i,:], window_len,'blackman')
sm_ft_l.append(s.tolist())
# smooth truncates the array
if window_len != 1:
ft_time_arr = ft_time_arr[window_len-1:-window_len+1]
raw_ft_arr = (np.array(sm_ft_l).T).tolist()
raw_mech_pos_arr = mechanism_dict['pos_list']
raw_mech_rot_arr = mechanism_dict['rot_list']
raw_hand_pos_arr = hand_dict['pos_list']
raw_hand_rot_arr = hand_dict['rot_list']
raw_arr_list = [raw_ft_arr, raw_mech_pos_arr, raw_mech_rot_arr,
raw_hand_pos_arr, raw_hand_rot_arr]
time_arr_list = [ft_time_arr, mech_time_arr, mech_time_arr,
hand_time_arr, hand_time_arr]
n_arr = len(raw_arr_list)
ft_list = []
mech_pos_list, mech_rot_list = [], []
hand_pos_list, hand_rot_list = [], []
acc_list = [ft_list, mech_pos_list, mech_rot_list, hand_pos_list,
hand_rot_list]
key_list = ['ft_list', 'mech_pos_list', 'mech_rot_list',
'hand_pos_list', 'hand_rot_list']
for i in range(time_arr.shape[0]):
t = time_arr[i]
for j in range(n_arr):
# nearest neighbor interpolation
min_idx = np.argmin(np.abs(time_arr_list[j] - t))
acc_list[j].append(raw_arr_list[j][min_idx])
d = {}
d['time_list'] = time_arr.tolist()
for i in range(n_arr):
d[key_list[i]] = acc_list[i]
return d
#--------------- functions that operate on combined pkl ----------------------
##
# transform forces to camera coord frame.
# @param hand_rot_matrix - rotation matrix for camera to hand checker.
# @param hand_pos_matrix - position of hand checkerboard in camera coord frame.
# @param mech_pos_matrix - position of mechanism checkerboard in camera coord frame.
# @param number - checkerboard number (1, 2, 3 or 4)
def ft_to_camera(force_tool, hand_rot_matrix, hand_pos_matrix, mech_pos_matrix, number):
# hc == hand checkerboard
hc_rot_tool = tr.Rx(math.radians(90)) * tr.Ry(math.radians(180.)) * tr.Rz(math.radians(30.))
while number != 1:
hc_rot_tool = tr.Ry(math.radians(90.)) * hc_rot_tool
number = number-1
force_hc = hc_rot_tool * force_tool
p_hc_ft = np.matrix([0.04, 0.01, 0.09]).T # vector from hook checkerboard origin to the base of the FT sensor in hook checker coordinates.
# vec from FT sensor to mechanism checker origin in camera coordinates.
p_ft_mech = -hand_pos_matrix + mech_pos_matrix - hand_rot_matrix * p_hc_ft
force_cam = hand_rot_matrix * force_hc # force at hook base in camera coordinates
moment_cam = hand_rot_matrix * moment_hc
force_at_mech_origin = force_cam
moment_at_mech_origin = moment_cam + np.matrix(np.cross(-p_ft_mech.A1, force_cam.A1)).T
return hand_rot_matrix * force_hc
##
# transform force to camera coord frame.
def ft_to_camera_3(force_tool, moment_tool, hand_rot_matrix, number,
return_moment_cam = False):
# hc == hand checkerboard
hc_rot_tool = tr.Rx(math.radians(90)) * tr.Ry(math.radians(180.)) * tr.Rz(math.radians(30.))
while number != 1:
hc_rot_tool = tr.Ry(math.radians(90.)) * hc_rot_tool
number = number-1
force_hc = hc_rot_tool * force_tool
moment_hc = hc_rot_tool * moment_tool
p_ft_hooktip = np.matrix([0.0, -0.08, 0.00]).T # vector from FT sensor to the tip of the hook in hook checker coordinates.
# p_ft_hooktip = np.matrix([0.0, -0.08 - 0.034, 0.00]).T # vector from FT sensor to the tip of the hook in hook checker coordinates.
p_ft_hooktip = hand_rot_matrix * p_ft_hooktip
force_cam = hand_rot_matrix * force_hc # force at hook base in camera coordinates
moment_cam = hand_rot_matrix * moment_hc
force_at_hook_tip = force_cam
moment_at_hook_tip = moment_cam + np.matrix(np.cross(-p_ft_hooktip.A1, force_cam.A1)).T
# if np.linalg.norm(moment_at_hook_tip) > 0.7:
# import pdb; pdb.set_trace()
if return_moment_cam:
return force_at_hook_tip, moment_at_hook_tip, moment_cam
else:
return force_at_hook_tip, moment_at_hook_tip
def plot(combined_dict, savefig):
plot_trajectories(combined_dict)
# tup = ke.init_ros_node()
# mech_rot_list = compute_mech_rot_list(combined_dict, tup)
# combined_dict['mech_rot_list'] = mech_rot_list
# plot_trajectories(combined_dict)
cd = combined_dict
ft_mat = np.matrix(cd['ft_list']).T
force_mat = ft_mat[0:3, :]
mpu.plot_yx(ut.norm(force_mat).A1, cd['time_list'])
mpu.show()
# plot_forces(combined_dict)
# if savefig:
# d3m.savefig(opt.dir+'/trajectory_check.png', size=(900, 800))
# else:
# d3m.show()
##
# @param pts - 3xN np matrix
def project_points_plane(pts):
# import mdp
# p = mdp.nodes.PCANode(svd=True)
# p.train((pts-np.mean(pts, 1)).T.A)
# print 'min mdp:', p.get_projmatrix()
#
# U, s , _ = np.linalg.svd(np.cov(pts))
# print 'min svd:', U[:,2]
eval, evec = np.linalg.eig(np.cov(pts))
min_idx = np.argmin(eval)
min_evec = np.matrix(evec[:,min_idx]).T
if min_evec[1,0] > 0:
min_evec = min_evec * -1
print 'min evec:', min_evec
pts_proj = pts - np.multiply((min_evec.T * pts), min_evec)
return pts_proj, min_evec
##
# use method 1 to compute the mechanism angle from combined dict.
# method 1 - angle between the x axis of checkerboard coord frame.
# @return list of mechanism angles.
def compute_mech_angle_1(cd, axis_direc=None):
mech_rot = cd['mech_rot_list']
directions_x = (np.row_stack(mech_rot)[:,0]).T.reshape(len(mech_rot), 3).T
if axis_direc != None:
directions_x = directions_x - np.multiply(axis_direc.T * directions_x,
axis_direc)
directions_x = directions_x/ut.norm(directions_x)
start_normal = directions_x[:,0]
mech_angle = np.arccos(start_normal.T * directions_x).A1.tolist()
return mech_angle
##
# use method 2 to compute the mechanism angle from combined dict.
# method 2 - fit a circle to estimate location of axis of rotation and
# radius. Then use that to compute the angle of the mechanism.
# @return list of mechanism angles.
def compute_mech_angle_2(cd, tup, project_plane=False):
pos_mat = np.column_stack(cd['mech_pos_list'])
if project_plane:
pts_proj, min_evec = project_points_plane(pos_arr)
pos_arr = pts_proj
kin_dict = ke.fit(pos_mat, tup)
center = np.matrix((kin_dict['cx'], kin_dict['cy'],
kin_dict['cz'])).T
directions_x = pos_mat - center
directions_x = directions_x / ut.norm(directions_x)
start_normal = directions_x[:,0]
#mech_angle = np.arccos(start_normal.T * directions_x).A1.tolist()
ct = (start_normal.T * directions_x).A1
st = ut.norm(np.matrix(np.cross(start_normal.A1, directions_x.T.A)).T).A1
mech_angle = np.arctan2(st, ct).tolist()
return mech_angle
def compute_mech_rot_list(cd, tup, project_plane=False):
pos_arr = np.column_stack(cd['mech_pos_list'])
rot_list = cd['mech_rot_list']
directions_y = (np.row_stack(rot_list)[:,1]).T.reshape(len(rot_list), 3).T
start_y = directions_y[:,0]
pts_proj, y_mech = project_points_plane(pos_arr)
if np.dot(y_mech.T, start_y.A1) < 0:
print 'Negative hai boss'
y_mech = -1 * y_mech
if project_plane:
pos_arr = pts_proj
kin_dict = ke.fit(np.matrix(pos_arr), tup)
center = np.array((kin_dict['cx'], kin_dict['cy'],
kin_dict['cz'])).T
print 'pos_arr[:,0]', pos_arr[:,0]
print 'center:', center
directions_x = (np.row_stack(rot_list)[:,0]).T.reshape(len(rot_list), 3).T
start_x = directions_x[:,0]
directions_x = np.matrix(pos_arr) - np.matrix(center).T.A
directions_x = directions_x / ut.norm(directions_x)
if np.dot(directions_x[:,0].A1, start_x.A1) < 0:
print 'Negative hai boss'
directions_x = -1 * directions_x
mech_rot_list = []
for i in range(len(rot_list)):
x = -directions_x[:, i]
y = np.matrix(y_mech)
z = np.matrix(np.cross(x.A1, y.A1)).T
rot_mat = np.column_stack((x, y, z))
mech_rot_list.append(rot_mat)
# return mech_rot_list
return rot_list
##
# @param tup - if None then use method 1 else use method 2 to
# compute mech angle.
# @return 1d array (radial force), 1d array (tangential force), list of mechanism angles, type ('rotary' or 'prismatic')
def compute_mechanism_properties(combined_dict, bias_ft = False,
tup = None, cd_pkl_name = None):
cd = combined_dict
force_cam, moment_cam, _ = fts_to_camera(combined_dict)
moment_contact_l = None
if bias_ft:
print 'Biasing magnitude:', np.linalg.norm(force_cam[:,0])
force_cam = force_cam - force_cam[:,0]
moment_cam = moment_cam - moment_cam[:,0]
if cd['radius'] != -1:
if tup == None:
mech_angle = compute_mech_angle_1(cd)
else:
mech_angle = compute_mech_angle_2(cd, tup)
# compute new mech_rot_list. used for factoring the forces.
mech_rot_list = compute_mech_rot_list(combined_dict, tup)
combined_dict['mech_rot_list'] = mech_rot_list
hook_tip_l = compute_hook_tip_trajectory(cd)
hand_mat = np.column_stack(hook_tip_l)
for i,f in enumerate(force_cam.T):
fmag = np.linalg.norm(f)
if fmag > 1.0:
break
end_idx = np.argmax(mech_angle)
hand_mat_short = hand_mat[:,i:end_idx]
kin_dict = ke.fit(hand_mat_short, tup)
center_hand = np.matrix((kin_dict['cx'], kin_dict['cy'],
kin_dict['cz'])).T
radius_hand = kin_dict['r']
center_mech_coord = mech_rot_list[0].T * center_hand
start_mech_coord = mech_rot_list[0].T * hand_mat_short[:,0]
opens_right = False
if start_mech_coord[0,0] < center_mech_coord[0,0]:
print 'Opens Right'
opens_right = True
# radial vectors.
radial_mat = hand_mat - center_hand
radial_mat = radial_mat / ut.norm(radial_mat)
_, nrm_hand = project_points_plane(hand_mat_short)
if np.dot(nrm_hand.A1, mech_rot_list[0][:,1].A1) < 0:
nrm_hand = -1 * nrm_hand
if opens_right == False:
nrm_hand = -1 * nrm_hand
frad_l = []
ftan_l = []
moment_contact_l = []
for i, f in enumerate(force_cam.T):
f = f.T
m = (moment_cam[:,i].T * nrm_hand)[0,0]
moment_contact_l.append(m)
tvec = np.matrix(np.cross(nrm_hand.A1, radial_mat[:,i].A1)).T
ftan = (f.T * tvec)[0,0]
ftan_l.append(ftan)
frad = np.linalg.norm(f - tvec * ftan)
#frad = (f_cam.T*radial_mat[:,i])[0,0]
frad_l.append(abs(frad))
typ = 'rotary'
else:
pos_mat = np.column_stack(cd['mech_pos_list'])
mech_angle = ut.norm(pos_mat-pos_mat[:,0]).A1.tolist()
#print 'mech_angle:', mech_angle
typ = 'prismatic'
moment_axis_list = None
frad_l = []
ftan_l = []
moment_contact_l = []
rot_list = cd['mech_rot_list']
directions_z = (np.row_stack(rot_list)[:,2]).T.reshape(len(rot_list), 3).T
for i, f in enumerate(force_cam.T):
f = f.T
tvec = np.matrix(directions_z[:,i])
ftan = (f.T * tvec)[0,0]
ftan_l.append(ftan)
frad = np.linalg.norm(f - tvec * ftan)
#frad = (f_cam.T*radial_mat[:,i])[0,0]
frad_l.append(abs(frad))
radius_hand = 10.
ut.save_pickle(combined_dict, cd_pkl_name)
return np.array(frad_l), np.array(ftan_l), mech_angle, typ, \
np.array(ftan_l)*radius_hand, np.array(moment_contact_l)
def plot_radial_tangential(mech_dict, savefig, fig_name=''):
radial_mech = mech_dict['force_rad_list']
tangential_mech = mech_dict['force_tan_list']
typ = mech_dict['mech_type']
mech_x = mech_dict['mechanism_x']
if typ == 'rotary':
mech_x_degrees = np.degrees(mech_x)
xlabel = 'angle (degrees)'
else:
mech_x_degrees = mech_x
xlabel = 'distance (meters)'
mpu.pl.clf()
mpu.plot_yx(radial_mech, mech_x_degrees, axis=None, label='radial force',
xlabel=xlabel, ylabel='N', color='r')
mpu.plot_yx(tangential_mech, mech_x_degrees, axis=None, label='tangential force',
xlabel=xlabel, ylabel='N', color='g')
mpu.legend()
if typ == 'rotary':
mpu.figure()
rad = mech_dict['radius']
torques_1 = rad * np.array(tangential_mech)
torques_3 = np.array(mech_dict['moment_tip_list']) + torques_1
mpu.plot_yx(torques_1, mech_x_degrees, axis=None,
label='torque from tangential',
xlabel=xlabel, ylabel='moment', color='r')
mpu.plot_yx(torques_3, mech_x_degrees, axis=None,
label='total torque',
xlabel=xlabel, ylabel='moment', color='y')
mpu.legend()
if savefig:
mpu.savefig(opt.dir+'/%s_force_components.png'%fig_name)
else:
mpu.show()
##
# returns force and moment at the tip of the hook in camera
# coordinates.
def fts_to_camera(combined_dict):
cd = combined_dict
number = cd['hook_checker_number']
hand_rot = cd['hand_rot_list']
hand_pos = cd['hand_pos_list']
ft_mat = np.matrix(cd['ft_list']).T # 6xN np matrix
force_mat = ft_mat[0:3, :]
moment_mat = ft_mat[3:6, :]
n_forces = force_mat.shape[1]
force_cam_list = []
moment_cam_list = []
moment_base_list = []
for i in range(n_forces):
f,m,m_base = ft_to_camera_3(force_mat[:,i], moment_mat[:,i], hand_rot[i],
number, return_moment_cam = True)
force_cam_list.append(f)
moment_cam_list.append(m)
moment_base_list.append(m_base)
force_cam = np.column_stack(force_cam_list)
moment_cam = np.column_stack(moment_cam_list)
moment_base = np.column_stack(moment_base_list)
return force_cam, moment_cam, moment_base
def plot_forces(combined_dict):
cd = combined_dict
hand_mat = np.column_stack(cd['hand_pos_list'])
hand_rot = cd['hand_rot_list']
mech_mat = np.column_stack(cd['mech_pos_list'])
mech_rot = cd['mech_rot_list']
directions_x = (np.row_stack(mech_rot)[:,0]).T.reshape(len(mech_rot), 3).T
force_cam, moment_cam, _ = fts_to_camera(combined_dict)
d3m.plot_points(hand_mat, color = (1.,0.,0.), mode='sphere')
d3m.plot_points(mech_mat, color = (0.,0.,1.), mode='sphere')
d3m.plot_normals(mech_mat, directions_x, color=(1.,0,0.))
# d3m.plot_normals(mech_mat, force_mat, color=(0.,1,0.))
d3m.plot_normals(mech_mat, force_cam, color=(0.,0,1.))
def plot_trajectories(combined_dict):
cd = combined_dict
hand_mat = np.column_stack(cd['hand_pos_list'])
hand_rot = cd['hand_rot_list']
directions_x = (np.row_stack(hand_rot)[:,0]).T.reshape(len(hand_rot), 3).T
directions_y = (np.row_stack(hand_rot)[:,1]).T.reshape(len(hand_rot), 3).T
directions_z = (np.row_stack(hand_rot)[:,2]).T.reshape(len(hand_rot), 3).T
#d3m.white_bg()
d3m.plot_points(hand_mat, color = (1.,0.,0.), mode='sphere',
scale_factor = 0.005)
d3m.plot_normals(hand_mat, directions_x, color=(1.,0,0.),
scale_factor = 0.02)
d3m.plot_normals(hand_mat, directions_y, color=(0.,1,0.),
scale_factor = 0.02)
d3m.plot_normals(hand_mat, directions_z, color=(0.,0,1.),
scale_factor = 0.02)
mech_mat = np.column_stack(cd['mech_pos_list'])
mech_rot = cd['mech_rot_list']
directions_x = (np.row_stack(mech_rot)[:,0]).T.reshape(len(mech_rot), 3).T
directions_y = (np.row_stack(mech_rot)[:,1]).T.reshape(len(hand_rot), 3).T
directions_z = (np.row_stack(mech_rot)[:,2]).T.reshape(len(mech_rot), 3).T
d3m.plot_points(mech_mat[:,0:1], color = (0.,0.,0.), mode='sphere',
scale_factor = 0.01)
d3m.plot_points(mech_mat, color = (0.,0.,1.), mode='sphere',
scale_factor = 0.005)
d3m.plot_normals(mech_mat, directions_x, color=(1.,0,0.),
scale_factor = 0.02)
d3m.plot_normals(mech_mat, directions_y, color=(0.,1,0.),
scale_factor = 0.02)
d3m.plot_normals(mech_mat, directions_z, color=(0.,0,1.),
scale_factor = 0.02)
m = np.mean(mech_mat, 1)
d3m.mlab.view(azimuth=-120, elevation=60, distance=1.60,
focalpoint=(m[0,0], m[1,0], m[2,0]))
##
# @return list of hook tip coodinates in camera coordinate frame.
def compute_hook_tip_trajectory(combined_dict):
cd = combined_dict
hand_mat = np.column_stack(cd['hand_pos_list'])
hand_rot_l = cd['hand_rot_list']
directions_x = (np.row_stack(hand_rot_l)[:,0]).T.reshape(len(hand_rot_l), 3).T
directions_y = (np.row_stack(hand_rot_l)[:,1]).T.reshape(len(hand_rot_l), 3).T
directions_z = (np.row_stack(hand_rot_l)[:,2]).T.reshape(len(hand_rot_l), 3).T
hand_pos_list = cd['hand_pos_list']
hook_tip_l = []
for i,p in enumerate(hand_pos_list): # p - hook checker origin in camera coordinates.
hc_P_hc_hooktip = np.matrix([0.035, -0.0864, 0.09]).T # vector from hook checkerboard origin to the tip of the hook in hook checker coordinates.
cam_P_hc_hooktip = hand_rot_l[i] * hc_P_hc_hooktip
hook_tip_l.append(p + cam_P_hc_hooktip)
return hook_tip_l
##
# take the open + close trajectory and split it into two separate
# trajectories and save them as pkls.
def split_open_close(rad, tan, ang, typ, mech_radius, time_list,
moment_axis, moment_tip):
ang = np.array(ang)
incr = ang[1:] - ang[:-1]
n_pts = ang.shape[0] - 2 #ignoring first and last readings.
rad_l, tan_l, ang_l = [], [], []
for i in range(n_pts):
if typ == 'rotary':
sgn = incr[i] * incr[i+1]
mag = abs(incr[i] - incr[i+1])
if sgn < 0 and mag > math.radians(10):
continue
rad_l.append(rad[i+1])
tan_l.append(tan[i+1])
ang_l.append(ang[i+1])
else:
# no cleanup for prismatic joints, for now
rad_l.append(rad[i+1])
tan_l.append(tan[i+1])
ang_l.append(ang[i+1])
rad, tan, ang = rad_l, tan_l, ang_l
max_idx = np.argmax(ang)
d_open = {'force_rad_list': rad[:max_idx+1],
'force_tan_list': tan[:max_idx+1],
'mechanism_x': ang[:max_idx+1], 'mech_type': typ,
'radius': mech_radius,
'time_list': time_list[:max_idx+1]}
if moment_tip != None:
d_open['moment_tip_list'] = moment_tip[:max_idx+1]
d_open['moment_list'] = moment_axis[:max_idx+1]
ut.save_pickle(d_open, opt.dir + '/open_mechanism_trajectories_handhook.pkl')
d_close = {'force_rad_list': rad[max_idx+1:],
'force_tan_list': tan[max_idx+1:],
'mechanism_x': ang[max_idx+1:], 'mech_type': typ,
'radius': mech_radius,
'time_list': time_list[max_idx+1:]}
if moment_tip != None:
d_open['moment_tip_list'] = moment_tip[max_idx+1:]
d_open['moment_list'] = moment_axis[max_idx+1:]
ut.save_pickle(d_close, opt.dir + '/close_mechanism_trajectories_handhook.pkl')
def plot_hooktip_trajectory_and_force(cd):
hook_tip_l = compute_hook_tip_trajectory(cd)
# plot trajectory in 3D.
d3m.white_bg()
d3m.plot_points(np.column_stack(hook_tip_l), color = (1.,0.,0.), mode='sphere',
scale_factor = 0.005)
# d3m.plot_points(mech_proj[:,0:1], color = (0.,0.,0.), mode='sphere',
# scale_factor = 0.01)
# d3m.plot_points(mech_proj, color = (0.,0.,1.), mode='sphere',
# scale_factor = 0.005)
# d3m.plot(np.column_stack((mech_proj[:,-1],center_mech, mech_proj[:,0])),
# color = (0.,0.,1.))
# d3m.plot(np.column_stack((hand_proj[:,-1],center_hand, hand_proj[:,0])),
# color = (1.,0.,0.))
d3m.show()
##
# sanity check - fitting circle to mechanism and hook tip
# trajectories, computing the angle between the initial radial
# direction of the mechanism and the radial directions for the hook
# tip. This angle starts out at a slightly positive angle. I'm
# assuming that this corresponds to the fact that the handle sticks
# out from the cabinet door. What makes me nervous is that I am still
# fitting two different circles to the mechanism and hook
# trajectories.
def compare_tip_mechanism_trajectories(mech_mat, hand_mat):
# hand_proj, nrm_hand = project_points_plane(hand_mat)
# mech_proj, nrm_mech = project_points_plane(mech_mat)
hand_proj = hand_mat
mech_proj = mech_mat
kin_dict = ke.fit(hand_proj, tup)
print 'kin_dict from hook tip:', kin_dict
print 'measured radius:', cd['radius']
center_hand = np.matrix((kin_dict['cx'], kin_dict['cy'],
kin_dict['cz'])).T
kin_dict = ke.fit(mech_proj, tup)
print 'kin_dict from mechanism:', kin_dict
center_mech = np.matrix((kin_dict['cx'], kin_dict['cy'],
kin_dict['cz'])).T
# working with the projected coordinates.
directions_hand = hand_proj - center_hand
directions_hand = directions_hand / ut.norm(directions_hand)
directions_mech = mech_proj - center_mech
directions_mech = directions_mech / ut.norm(directions_mech)
start_normal = directions_mech[:,0]
print 'directions_mech[:,0]', directions_mech[:,0].A1
print 'directions_hand[:,0]', directions_hand[:,0].A1
ct = (start_normal.T * directions_hand).A1
st = ut.norm(np.matrix(np.cross(start_normal.A1, directions_hand.T.A)).T).A1
mech_angle = np.arctan2(st, ct).tolist()
#mech_angle = np.arccos(start_normal.T * directions_hand).A1.tolist()
mpu.plot_yx(np.degrees(mech_angle))
mpu.show()
# plot trajectory in 3D.
d3m.white_bg()
d3m.plot_points(hand_proj, color = (1.,0.,0.), mode='sphere',
scale_factor = 0.005)
d3m.plot_points(mech_proj[:,0:1], color = (0.,0.,0.), mode='sphere',
scale_factor = 0.01)
d3m.plot_points(mech_proj, color = (0.,0.,1.), mode='sphere',
scale_factor = 0.005)
d3m.plot(np.column_stack((mech_proj[:,-1],center_mech, mech_proj[:,0])),
color = (0.,0.,1.))
d3m.plot(np.column_stack((hand_proj[:,-1],center_hand, hand_proj[:,0])),
color = (1.,0.,0.))
d3m.show()
def angle_between_hooktip_mechanism_radial_vectors(mech_mat, hand_mat):
kin_dict = ke.fit(hand_mat, tup)
print 'kin_dict from hook tip:', kin_dict
print 'measured radius:', cd['radius']
center_hand = np.matrix((kin_dict['cx'], kin_dict['cy'],
kin_dict['cz'])).T
kin_dict = ke.fit(mech_mat, tup)
print 'kin_dict from mechanism:', kin_dict
center_mech = np.matrix((kin_dict['cx'], kin_dict['cy'],
kin_dict['cz'])).T
# working with the projected coordinates.
directions_hand = hand_mat - center_hand
directions_hand = directions_hand / ut.norm(directions_hand)
directions_mech = mech_mat - center_mech
directions_mech = directions_mech / ut.norm(directions_mech)
#import pdb; pdb.set_trace()
ang = np.degrees(np.arccos(np.sum(np.multiply(directions_mech, directions_hand), 0))).A1
mpu.plot_yx(ang, label = 'angle between hooktip-radial and mechanism radial')
mpu.legend()
mpu.show()
def split_forces_hooktip_test(hand_mat):
kin_dict = ke.fit(hand_mat, tup)
center_hand = np.matrix((kin_dict['cx'], kin_dict['cy'],
kin_dict['cz'])).T
print 'kin_dict:', kin_dict
# radial vectors.
radial_mat = hand_mat - center_hand
radial_mat = radial_mat / ut.norm(radial_mat)
# cannot use hook tip to compute mechanism angle because I
# don't have a way of knowing when the hook starts opening the
# mechanism. (Think hook makes contact with door, moves in
# freespace and then makes contact with the handle.)
#start_rad = radial_mat[:,0]
#ct = (start_rad.T * radial_mat).A1
#st = ut.norm(np.matrix(np.cross(start_rad.A1, radial_mat.T.A)).T).A1
#mech_angle_l = np.arctan2(st, ct).tolist()
_, nrm_hand = project_points_plane(hand_mat)
print 'nrm_hand:', nrm_hand.A1
f_cam_l = []
m_cam_l = []
m_base_l = []
frad_l = []
ftan_l = []
hook_num = cd['hook_checker_number']
print 'hook_num:', hook_num
for i, f in enumerate(force_mat.T):
f = f.T
m = moment_mat[:,i]
f_cam, m_cam, m_base = ft_to_camera_3(f, m, hook_rot_l[i], hook_num,
return_moment_cam = True)
f_cam_l.append(f_cam)
m_cam_l.append(abs((m_cam.T*nrm_hand)[0,0]))
m_base_l.append(abs((m_base.T*nrm_hand)[0,0]))
#m_base_l.append(np.linalg.norm(f))
tangential_vec = np.matrix(np.cross(radial_mat[:,i].A1, nrm_hand.A1)).T
ftan = (f_cam.T * tangential_vec)[0,0]
ftan_l.append(ftan)
#frad = np.linalg.norm(f_cam - tangential_vec * ftan)
frad = (f_cam.T*radial_mat[:,i])[0,0]
frad_l.append(abs(frad))
fig1 = mpu.figure()
mech_ang_deg = np.degrees(mech_angle_l)
mpu.plot_yx(ftan_l, mech_ang_deg, label='Tangential Force (hook tip)', color='b')
mpu.plot_yx(frad_l, mech_ang_deg, label='Radial Force (hook tip)', color='y')
mech_pkl_name = glob.glob(opt.dir + '/open_mechanism_trajectories_*.pkl')[0]
md = ut.load_pickle(mech_pkl_name)
radial_mech = md['force_rad_list']
tangential_mech = md['force_tan_list']
mech_x = np.degrees(md['mechanism_x'])
mpu.plot_yx(tangential_mech, mech_x, label='Tangential Force (mechanism checker)', color='g')
mpu.plot_yx(radial_mech, mech_x, label='Radial Force (mechanism checker)', color='r')
mpu.legend()
fig2 = mpu.figure()
mpu.plot_yx(m_cam_l, mech_ang_deg, label='\huge{$m_{axis}$}')
mpu.plot_yx(m_base_l, mech_ang_deg, label='\huge{$m^s$}',
color = 'r')
mpu.legend()
mpu.show()
if __name__ == '__main__':
import optparse
p = optparse.OptionParser()
p.add_option('-d', '--dir', action='store', default='',
type='string', dest='dir', help='directory with logged data')
p.add_option('-t', '--time_check', action='store_true', dest='tc',
help='plot to check the consistency of time stamps')
p.add_option('-s', '--sync', action='store_true', dest='sync',
help='time synchronize poses, forces etc.')
p.add_option('--split', action='store_true', dest='split_forces',
help='split forces into radial and tangential and save in a pickle')
p.add_option('--savefig', action='store_true', dest='savefig',
help='save the plot instead of showing it.')
p.add_option('-c', '--cd', action='store_true', dest='cd',
help='work with the combined dict')
p.add_option('-f', '--force', action='store_true', dest='force',
help='plot radial and tangential force')
p.add_option('--mech_prop_ros', action='store_true',
dest='mech_prop_ros',
help='plot radial and tangential force')
p.add_option('--moment_test', action='store_true',
dest='moment_test',
help='trying to compute moment about the joint axis.')
p.add_option('--hook_tip_test', action='store_true',
dest='hook_tip_test',
help='plot trajectory of hook tip for debugging etc.')
opt, args = p.parse_args()
if opt.dir == '':
raise RuntimeError('Need a directory to work with (-d or --dir)')
if opt.force:
mech_pkl_name = glob.glob(opt.dir + '/open_mechanism_trajectories_*.pkl')[0]
md = ut.load_pickle(mech_pkl_name)
plot_radial_tangential(md, opt.savefig, 'open')
# mech_pkl_name = glob.glob(opt.dir + '/close_mechanism_trajectories_handhook.pkl')[0]
# md = ut.load_pickle(mech_pkl_name)
# plot_radial_tangential(md, opt.savefig, 'close')
ft_pkl = glob.glob(opt.dir + '/ft_log*.pkl')[0]
poses_pkl = glob.glob(opt.dir + '/poses_dict*.pkl')[0]
ft_dict = ut.load_pickle(ft_pkl)
poses_dict = ut.load_pickle(poses_pkl)
mechanism_dict = poses_dict['mechanism']
hand_dict = poses_dict['hand']
ft_time_list = ft_dict['time_list']
mechanism_time_list = mechanism_dict['time_list']
hand_time_list = hand_dict['time_list']
if opt.tc:
check_time_sync(ft_time_list, mechanism_time_list, hand_time_list)
if opt.savefig:
mpu.savefig(opt.dir+'/time_check.png')
else:
mpu.show()
if opt.sync:
print 'Begin synchronize'
d = synchronize(ft_dict, mechanism_dict, hand_dict)
print 'End synchronize'
#ut.save_pickle(d, opt.dir+'/combined_log'+ut.formatted_time()+'.pkl')
ut.save_pickle(d, opt.dir+'/combined_log.pkl')
print 'Saved pickle'
if opt.cd:
cd = ut.load_pickle(glob.glob(opt.dir + '/combined_log*.pkl')[0])
plot(cd, opt.savefig)
if opt.mech_prop_ros:
import mechanism_analyse as ma
cd = ut.load_pickle(glob.glob(opt.dir + '/combined_log*.pkl')[0])
tup = ke.init_ros_node()
ma2 = compute_mech_angle_2(cd, tup, project_plane=False)
ma1 = compute_mech_angle_1(cd)
ma3 = compute_mech_angle_2(cd, tup, project_plane=True)
# ma4 = compute_mech_angle_1(cd, min_evec)
lab1 = 'orientation only'
lab2 = 'checker origin position + circle fit'
lab3 = 'checker origin position + PCA projection + circle fit'
# lab4 = 'PCA projection + orientation'
mpu.figure()
mpu.plot_yx(np.degrees(ma3), color='r', label=lab3,
linewidth = 1, scatter_size = 5)
mpu.plot_yx(np.degrees(ma2), color='b', label=lab2,
linewidth = 1, scatter_size = 5)
mpu.plot_yx(np.degrees(ma1), color='y', label=lab1,
linewidth = 1, scatter_size = 5)
mpu.legend()
vel3 = ma.compute_velocity(ma3, cd['time_list'], 1)
vel2 = ma.compute_velocity(ma2, cd['time_list'], 1)
vel1 = ma.compute_velocity(ma1, cd['time_list'], 1)
mpu.figure()
mpu.plot_yx(np.degrees(vel3), np.degrees(ma3), color='r',
label=lab3, linewidth = 1, scatter_size = 5)
mpu.plot_yx(np.degrees(vel2), np.degrees(ma2), color='b',
label=lab2, linewidth = 1, scatter_size = 5)
mpu.plot_yx(np.degrees(vel1), np.degrees(ma1), color='y',
label=lab1, linewidth = 1, scatter_size = 5)
mpu.legend()
# acc3 = ma.compute_velocity(vel3, cd['time_list'], 1)
# mpu.figure()
# mpu.plot_yx(np.degrees(acc3), np.degrees(ma3), color='r',
# label=lab3, linewidth = 1, scatter_size = 5)
# mpu.legend()
mpu.show()
if opt.split_forces:
tup = ke.init_ros_node()
pkl_name = glob.glob(opt.dir + '/combined_log*.pkl')[0]
mech_pkl_name = glob.glob(opt.dir + '/mechanism_info*.pkl')[0]
md = ut.load_pickle(mech_pkl_name)
cd = ut.load_pickle(pkl_name)
cd['hook_checker_number'] = md['checkerboard_number']
cd['radius'] = md['radius']
rad, tan, ang, typ, moment_axis, moment_tip = compute_mechanism_properties(cd,
bias_ft=True, tup=tup,
cd_pkl_name = pkl_name)
split_open_close(rad, tan, ang, typ, md['radius'],
cd['time_list'], moment_axis, moment_tip)
if opt.moment_test:
tup = ke.init_ros_node()
pkl_name = glob.glob(opt.dir + '/combined_log*.pkl')[0]
mech_pkl_name = glob.glob(opt.dir + '/mechanism_info*.pkl')[0]
md = ut.load_pickle(mech_pkl_name)
cd = ut.load_pickle(pkl_name)
cd['hook_checker_number'] = md['checkerboard_number']
cd['radius'] = md['radius']
rad, tan, ang, typ, moment_axis, moment_tip = compute_mechanism_properties(cd,
bias_ft=True, tup=tup,
cd_pkl_name = pkl_name)
ang = np.array(ang)
incr = ang[1:] - ang[:-1]
n_pts = ang.shape[0] - 2 #ignoring first and last readings.
rad_l, tan_l, ang_l = [], [], []
for i in range(n_pts):
if typ == 'rotary':
sgn = incr[i] * incr[i+1]
mag = abs(incr[i] - incr[i+1])
if sgn < 0 and mag > math.radians(10):
continue
rad_l.append(rad[i+1])
tan_l.append(tan[i+1])
ang_l.append(ang[i+1])
else:
# no cleanup for prismatic joints, for now
rad_l.append(rad[i+1])
tan_l.append(tan[i+1])
ang_l.append(ang[i+1])
rad, tan, ang = rad_l, tan_l, ang_l
max_idx = np.argmax(ang)
rad = np.array(rad[:max_idx+1])
tan = np.array(tan[:max_idx+1])
ang = np.array(ang[:max_idx+1])
moment_axis = np.array(moment_axis[:max_idx+1])
moment_tip = np.array(moment_tip[:max_idx+1])
fig1 = mpu.figure()
mpu.plot_yx(tan * cd['radius'], np.degrees(ang), label = 'Moment from Tangential Force',
color = 'b')
mpu.plot_yx(moment_axis, np.degrees(ang), label = 'Computed Moment',
color = 'g')
mpu.plot_yx(moment_tip, np.degrees(ang), label = 'Computed Moment using tip model',
color = 'y')
mpu.legend()
mpu.show()
if opt.hook_tip_test:
tup = ke.init_ros_node()
pkl_name = glob.glob(opt.dir + '/combined_log*.pkl')[0]
mech_pkl_name = glob.glob(opt.dir + '/mechanism_info*.pkl')[0]
md = ut.load_pickle(mech_pkl_name)
cd = ut.load_pickle(pkl_name)
cd['hook_checker_number'] = md['checkerboard_number']
cd['radius'] = md['radius']
hook_tip_l = compute_hook_tip_trajectory(cd)
hook_rot_l = cd['hand_rot_list']
mech_mat = np.column_stack(cd['mech_pos_list'])
hand_mat = np.column_stack(hook_tip_l)
ft_mat = np.matrix(cd['ft_list']).T # 6xN np matrix
force_mat = ft_mat[0:3, :]
# force_mat = force_mat - force_mat[:,0]
moment_mat = ft_mat[3:6, :]
# moment_mat = moment_mat - moment_mat[:,0]
for i,f in enumerate(force_mat.T):
fmag = np.linalg.norm(f)
if fmag > 1.0:
print 'i:', i
break
mech_angle_l = compute_mech_angle_2(cd, tup, project_plane=False)
end_idx = np.argmax(mech_angle_l)
hand_mat = hand_mat[:,i:end_idx]
mech_mat = mech_mat[:,i:end_idx]
force_mat = force_mat[:,i:end_idx]
moment_mat = moment_mat[:,i:end_idx]
hook_rot_l = hook_rot_l[i:end_idx]
mech_angle_l = mech_angle_l[i:end_idx]
compare_tip_mechanism_trajectories(mech_mat[:,i:], hand_mat[:,i:])
#angle_between_hooktip_mechanism_radial_vectors(mech_mat, hand_mat)
#plot moment at hook ti and base.
#split_forces_hooktip_test(hand_mat)
| [
[
1,
0,
0.002,
0.001,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.002,
0.001,
0,
0.66,
0.0312,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.003,
0.001,
0,
0.66,
... | [
"import roslib; roslib.load_manifest('modeling_forces')",
"import roslib; roslib.load_manifest('modeling_forces')",
"import rospy",
"import hrl_lib.util as ut",
"import hrl_lib.transforms as tr",
"import matplotlib_util.util as mpu",
"import hrl_tilting_hokuyo.display_3d_mayavi as d3m",
"import modeli... |
#
# Subscribe to ObjectDetection message and convert a pickle.
#
#
#
import roslib; roslib.load_manifest('modeling_forces')
import rospy
from checkerboard_detector.msg import ObjectDetection
import hrl_lib.util as ut
import hrl_lib.transforms as tr
from std_msgs.msg import Empty
import numpy as np
import time
def pose_cb(data, d):
global t_pose_cb
t_pose_cb = time.time()
for obj in data.objects:
p = obj.pose.position
pos = np.matrix([p.x, p.y, p.z]).T
q = obj.pose.orientation
rot = tr.quaternion_to_matrix([q.x, q.y, q.z, q.w])
t = data.header.stamp.to_sec()
d[obj.type]['pos_list'].append(pos)
d[obj.type]['rot_list'].append(rot)
d[obj.type]['time_list'].append(t)
print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
print 'pos:', pos.T
print 'rot:', rot
def got_trigger_cb(data, d):
d['flag'] = True
if __name__ == '__main__':
print 'Hello World.'
rospy.init_node('checkerboard_poses_to_pickle', anonymous=False)
topic_name = '/checkerdetector/ObjectDetection'
d = {'mechanism': {}, 'hand': {}}
d['mechanism'] = {'pos_list': [], 'rot_list': [], 'time_list': []}
d['hand'] = {'pos_list': [], 'rot_list': [], 'time_list': []}
rospy.Subscriber(topic_name, ObjectDetection, pose_cb, d)
got_trigger_dict = {'flag': False}
rospy.Subscriber('/checker_to_poses/trigger', Empty, got_trigger_cb,
got_trigger_dict)
global t_pose_cb
t_pose_cb = time.time()
while got_trigger_dict['flag'] == False:
time.sleep(0.05)
if (time.time() - t_pose_cb) > 60.:
raise RuntimeError('haven\'t received a pose_cb in 60 secs')
# rospy.spin()
print 'Number of poses:', len(d['mechanism']['time_list'])
#ut.save_pickle(d, 'poses_dict_'+ut.formatted_time()+'.pkl')
ut.save_pickle(d, 'poses_dict.pkl')
| [
[
1,
0,
0.1096,
0.0137,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.1096,
0.0137,
0,
0.66,
0.0909,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.1233,
0.0137,
0,
0.... | [
"import roslib; roslib.load_manifest('modeling_forces')",
"import roslib; roslib.load_manifest('modeling_forces')",
"import rospy",
"from checkerboard_detector.msg import ObjectDetection",
"import hrl_lib.util as ut",
"import hrl_lib.transforms as tr",
"from std_msgs.msg import Empty",
"import numpy a... |
import roslib; roslib.load_manifest('modeling_forces')
import rospy
from geometry_msgs.msg import Point32
from articulation_msgs.msg import ModelMsg
from articulation_msgs.msg import TrackMsg
from geometry_msgs.msg import Pose, Point, Quaternion
from threading import RLock
import numpy as np
import time
def model_cb(data, kin_dict):
print 'model_cb called'
if data.name == 'rotational':
for p in data.params:
if p.name == 'rot_center.x':
cx = p.value
if p.name == 'rot_center.y':
cy = p.value
if p.name == 'rot_center.z':
cz = p.value
if p.name == 'rot_radius':
r = p.value
kin_dict['typ'] = 'rotational'
kin_dict['cx'] = cx
kin_dict['cy'] = cy
kin_dict['cz'] = cz
kin_dict['r'] = r
if data.name == 'prismatic':
for p in data.params:
if p.name == 'prismatic_dir.x':
dx = p.value
if p.name == 'prismatic_dir.y':
dy = p.value
if p.name == 'prismatic_dir.z':
dz = p.value
kin_dict['typ'] = 'prismatic'
kin_dict['direc'] = [dx, dy, dz]
kin_dict['got_model'] = True
##
# fit either a circle or a linear model.
# @param pts - 3xN np matrix of points.
# @return dictionary with kinematic params. (see model_cb)
def fit(pts, tup):
kin_dict, track_pub = tup
track_msg = TrackMsg()
track_msg.header.stamp = rospy.get_rostime()
track_msg.header.frame_id = '/'
track_msg.track_type = TrackMsg.TRACK_POSITION_ONLY
kin_dict['got_model'] = False
for pt in pts.T:
p = pt.A1.tolist()
pose = Pose(Point(0, 0, 0), Quaternion(0, 0, 0, 1))
pose.position.x = p[0]
pose.position.y = p[1]
pose.position.z = p[2]
track_msg.pose.append(pose)
rospy.sleep(0.1)
track_pub.publish(track_msg)
while kin_dict['got_model'] == False:
rospy.sleep(0.01)
return kin_dict
def init_ros_node():
rospy.init_node('kinematics_estimation_sturm')
track_pub = rospy.Publisher('track', TrackMsg)
kin_dict = {}
track_msg = TrackMsg()
rospy.Subscriber('model', ModelMsg, model_cb,
kin_dict)
return kin_dict, track_pub
if __name__ == '__main__':
init_ros_node()
rospy.spin()
| [
[
1,
0,
0.0238,
0.0119,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0238,
0.0119,
0,
0.66,
0.0769,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0357,
0.0119,
0,
0.... | [
"import roslib; roslib.load_manifest('modeling_forces')",
"import roslib; roslib.load_manifest('modeling_forces')",
"import rospy",
"from geometry_msgs.msg import Point32",
"from articulation_msgs.msg import ModelMsg",
"from articulation_msgs.msg import TrackMsg",
"from geometry_msgs.msg import Pose, Po... |
import math, numpy as np
import glob
import roslib; roslib.load_manifest('hrl_tilting_hokuyo')
import hrl_tilting_hokuyo.display_3d_mayavi as d3m
import matplotlib_util.util as mpu
import hrl_lib.util as ut
if __name__ == '__main__':
import optparse
p = optparse.OptionParser()
p.add_option('-f', '--fname', action='store', default='',
type='string', dest='fname', help='pkl with logged data')
p.add_option('-d', '--dir', action='store', default='',
type='string', dest='dir', help='directory with logged data')
opt, args = p.parse_args()
if opt.dir != '':
poses_pkl = glob.glob(opt.dir + '/poses_dict*.pkl')[0]
d = ut.load_pickle(poses_pkl)
elif opt.fname != '':
d = ut.load_pickle(opt.fname)
else:
raise RuntimeError('need either -d or -f')
hand_list = d['hand']['pos_list']
hand_rot = d['hand']['rot_list']
if hand_list != []:
hand_mat = np.column_stack(hand_list)
print 'hand_mat.shape', hand_mat.shape
d3m.plot_points(hand_mat, color = (1.,0.,0.), mode='sphere')
directions_x = (np.row_stack(hand_rot)[:,0]).T.reshape(len(hand_rot), 3).T
directions_z = (np.row_stack(hand_rot)[:,2]).T.reshape(len(hand_rot), 3).T
#print 'directions.shape', directions_x.shape
#print 'hand_mat.shape', hand_mat.shape
#mpu.plot_yx(ut.norm(directions).A1, axis=None)
#mpu.show()
#mpu.plot_yx(ut.norm(hand_mat[:, 1:] - hand_mat[:, :-1]).A1, axis=None)
#mpu.show()
d3m.plot_normals(hand_mat, directions_x, color=(1.,0,0.))
d3m.plot_normals(hand_mat, directions_z, color=(0.,0,1.))
mechanism_list = d['mechanism']['pos_list']
mechanism_rot = d['mechanism']['rot_list']
#mechanism_list = []
if mechanism_list != []:
mechanism_mat = np.column_stack(mechanism_list)
print 'mechanism_mat.shape', mechanism_mat.shape
d3m.plot_points(mechanism_mat, color = (0.,0.,1.), mode='sphere')
#d3m.plot_points(mechanism_mat, color = (0.,0.,1.), mode='sphere')
c = np.row_stack(mechanism_rot)[:,2]
directions = c.T.reshape(len(mechanism_rot), 3).T
print 'directions.shape', directions.shape
print 'mechanism_mat.shape', mechanism_mat.shape
d3m.plot_normals(mechanism_mat, directions, color=(0,0,1.))
d3m.show()
# mpu.plot_yx(pos_mat[0,:].A1, pos_mat[1,:].A1)
# mpu.show()
| [
[
1,
0,
0.0286,
0.0143,
0,
0.66,
0,
526,
0,
2,
0,
0,
526,
0,
0
],
[
1,
0,
0.0429,
0.0143,
0,
0.66,
0.1429,
958,
0,
1,
0,
0,
958,
0,
0
],
[
1,
0,
0.0714,
0.0143,
0,
... | [
"import math, numpy as np",
"import glob",
"import roslib; roslib.load_manifest('hrl_tilting_hokuyo')",
"import roslib; roslib.load_manifest('hrl_tilting_hokuyo')",
"import hrl_tilting_hokuyo.display_3d_mayavi as d3m",
"import matplotlib_util.util as mpu",
"import hrl_lib.util as ut",
"if __name__ == ... |
import commands
import os
def aggregate_plots(dir, name_list, extension_list):
n = len(name_list)
for i in range(n):
#for nm in name_list:
nm = name_list[i]
ex = extension_list[i]
pngs_list = commands.getoutput('find %s/0* -name "*%s.%s"'%(dir, nm, ex))
pngs_list = pngs_list.splitlines()
st = '%s/%s'%(dir, nm)
os.system('rm -rf %s'%st) # remove previously existing directory.
os.system('mkdir %s'%st)
for p in pngs_list:
sp = p.split('/')
fname = str.join('_',sp[1:])
print 'saving ', fname
os.system('cp %s %s'%(p, st+'/'+fname))
if __name__ == '__main__':
import optparse
p = optparse.OptionParser()
p.add_option('-d', '--dir', action='store', default='',
type='string', dest='dir', help='directory with logged data')
p.add_option('-a', '--agg', action='store_true', dest='agg',
help='aggregate plots from different trials into one folder for comparison')
opt, args = p.parse_args()
if opt.dir == '':
raise RuntimeError('Need a directory to work with (-d or --dir)')
if opt.agg:
name_list = ['mechanism_trajectories_handhook']
extension_list = ['pkl']
# name_list = ['trajectory_check', 'force_components',
# 'mechanism_trajectories_handhook', 'poses_dict']
# extension_list = ['png', 'png', 'pkl', 'pkl']
aggregate_plots(opt.dir, name_list, extension_list)
| [
[
1,
0,
0.0426,
0.0213,
0,
0.66,
0,
760,
0,
1,
0,
0,
760,
0,
0
],
[
1,
0,
0.0638,
0.0213,
0,
0.66,
0.3333,
688,
0,
1,
0,
0,
688,
0,
0
],
[
2,
0,
0.2979,
0.3617,
0,
... | [
"import commands",
"import os",
"def aggregate_plots(dir, name_list, extension_list):\n n = len(name_list)\n for i in range(n):\n #for nm in name_list:\n nm = name_list[i]\n ex = extension_list[i]\n pngs_list = commands.getoutput('find %s/0* -name \"*%s.%s\"'%(dir, nm, ex))\n ... |
# print 'Following are the key that you can use:'
# print '1. Hit ESC to end'
# print '2. Hit - to decrease the size of the image'
# print '3. Hit + (without the shift key) to increase the image size'
# print '4. Hit c to detect chessboard corners'
import sys, time
import numpy as np, math
import glob, commands
import roslib; roslib.load_manifest('modeling_forces')
import cv
from cv_bridge.cv_bridge import CvBridge, CvBridgeError
import hrl_lib.util as ut
# call func on the 8 neighbors of x,y and on x,y
def call_neighborhood(func,func_params,x,y):
func(x+0,y+0,*func_params)
func(x+1,y+0,*func_params)
func(x+1,y-1,*func_params)
func(x+0,y-1,*func_params)
func(x-1,y-1,*func_params)
func(x-1,y+0,*func_params)
func(x-1,y+1,*func_params)
func(x-0,y+1,*func_params)
func(x+1,y+1,*func_params)
def on_mouse(event, x, y, flags, param):
im, clicked_list = param[0], param[1]
scale_factor = param[2]
if event == cv.CV_EVENT_LBUTTONDOWN:
#call_neighborhood(cv.SetPixel,(im,(255,0,0)),x,y)
clicked_list.append((x/scale_factor, y/scale_factor)) # these are in mm
def annotate_image(cv_im, mech_info_dict, dir):
#cv_im = cv.LoadImage(sys.argv[1], cv.CV_LOAD_IMAGE_GRAYSCALE)
size = cv.GetSize(cv_im)
print 'Image size:', size[0], size[1] # col, row
wnd = 'Image Annotate'
cv.NamedWindow(wnd, cv.CV_WINDOW_AUTOSIZE)
disp_im = cv.CloneImage(cv_im)
new_size = (size[0]/2, size[1]/2)
scale_factor = 1
checker_origin_height = mech_info_dict['height']
# chesscoard corners mat
cb_dims = (5, 8) # checkerboard dims. (x, y)
sq_sz = 19 # size of checkerboard in real units.
cb_offset = 500,500
cb_coords = cv.CreateMat(2, cb_dims[0]*cb_dims[1], cv.CV_64FC1)
n = 0
for r in range(cb_dims[1]):
for c in range(cb_dims[0]):
cb_coords[0,n] = c*sq_sz + cb_offset[0] # x coord
cb_coords[1,n] = r*sq_sz + cb_offset[1] # y coord
n += 1
clicked_list = []
recreate_image = False
mechanism_calc_state = 0
mechanism_calc_dict = {}
while True:
for p in clicked_list:
x,y = p[0]*scale_factor, p[1]*scale_factor
cv.Circle(disp_im, (x,y), 3, (255,0,0))
cv.ShowImage(wnd, disp_im)
k = cv.WaitKey(10)
k = k%256
if k == 27:
# ESC
break
elif k == ord('='):
# + key without the shift
scale_factor = scale_factor*1.2
recreate_image = True
elif k == ord('-'):
# - key
scale_factor = scale_factor/1.2
recreate_image = True
elif k == ord('c'):
# find chessboard corners.
succ, corners = cv.FindChessboardCorners(disp_im, cb_dims)
if succ == 0:
print 'Chessboard detection FAILED.'
else:
# chessboard detection was successful
cv.DrawChessboardCorners(disp_im, cb_dims, corners, succ)
cb_im = cv.CreateMat(2, cb_dims[0]*cb_dims[1], cv.CV_64FC1)
corners_mat = np.array(corners).T
n = 0
for r in range(cb_dims[1]):
for c in range(cb_dims[0]):
cb_im[0,n] = corners_mat[0,n] # x coord
cb_im[1,n] = corners_mat[1,n] # y coord
n += 1
H = cv.CreateMat(3, 3, cv.CV_64FC1)
H1 = cv.FindHomography(cb_im, cb_coords, H)
Hnp = np.reshape(np.fromstring(H1.tostring()), (3,3))
print 'Homography:'
print Hnp
d = cv.CloneImage(disp_im)
cv.WarpPerspective(d, disp_im, H1, cv.CV_WARP_FILL_OUTLIERS)
cv_im = cv.CloneImage(disp_im)
elif k == ord('1'):
# calculate width of the mechanism
del clicked_list[:]
cv.SetMouseCallback(wnd, on_mouse, (disp_im, clicked_list, scale_factor))
recreate_image = True
print 'Click on two endpoints to mark the width of the mechanism'
mechanism_calc_state = 1
elif k == ord('2'):
# distance of handle from the hinge
del clicked_list[:]
cv.SetMouseCallback(wnd, on_mouse, (disp_im, clicked_list, scale_factor))
recreate_image = True
print 'Click on handle and hinge to compute distance of handle from hinge.'
mechanism_calc_state = 2
elif k == ord('3'):
# height of the handle above the ground
del clicked_list[:]
cv.SetMouseCallback(wnd, on_mouse, (disp_im, clicked_list, scale_factor))
recreate_image = True
print 'Click on handle top and bottom to compute height of handle above the ground.'
mechanism_calc_state = 3
elif k == ord('4'):
# top and bottom edge of the mechanism
del clicked_list[:]
cv.SetMouseCallback(wnd, on_mouse, (disp_im, clicked_list, scale_factor))
recreate_image = True
print 'Click on top and bottom edges of the mechanism.'
mechanism_calc_state = 4
elif k ==ord('d'):
# display the calculated values
print 'mechanism_calc_dict:', mechanism_calc_dict
print 'mech_info_dict:', mech_info_dict
elif k == ord('s'):
# save the pkl
ut.save_pickle(mechanism_calc_dict, dir+'/mechanism_calc_dict.pkl')
print 'Saved the pickle'
#elif k != -1:
elif k != 255:
print 'k:', k
if recreate_image:
new_size = (int(size[0]*scale_factor),
int(size[1]*scale_factor))
disp_im = cv.CreateImage(new_size, cv_im.depth, cv_im.nChannels)
cv.Resize(cv_im, disp_im)
cv.SetMouseCallback(wnd, on_mouse, (disp_im, clicked_list, scale_factor))
recreate_image = False
if len(clicked_list) == 2:
if mechanism_calc_state == 1:
w = abs(clicked_list[0][0] - clicked_list[1][0])
print 'Width in mm:', w
mechanism_calc_dict['mech_width'] = w/1000.
if mechanism_calc_state == 2:
w = abs(clicked_list[0][0] - clicked_list[1][0])
print 'Width in mm:', w
mechanism_calc_dict['handle_hinge_dist'] = w/1000.
if mechanism_calc_state == 3:
p1, p2 = clicked_list[0], clicked_list[1]
h1 = (cb_offset[1] - p1[1])/1000. + checker_origin_height
h2 = (cb_offset[1] - p2[1])/1000. + checker_origin_height
mechanism_calc_dict['handle_top'] = max(h1, h2)
mechanism_calc_dict['handle_bottom'] = min(h1, h2)
if mechanism_calc_state == 4:
p1, p2 = clicked_list[0], clicked_list[1]
h1 = (cb_offset[1] - p1[1])/1000. + checker_origin_height
h2 = (cb_offset[1] - p2[1])/1000. + checker_origin_height
mechanism_calc_dict['mechanism_top'] = max(h1, h2)
mechanism_calc_dict['mechanism_bottom'] = min(h1, h2)
mechanism_calc_state = 0
if __name__ == '__main__':
import optparse
p = optparse.OptionParser()
p.add_option('-d', '--dir', action='store', default='',
type='string', dest='dir', help='mechanism directory')
opt, args = p.parse_args()
# dir_list = commands.getoutput('ls -d %s/*/'%(opt.dir)).splitlines()
# dir_list = dir_list[:]
# for direc in dir_list:
img_list = glob.glob(opt.dir+'/*.jpg')
mech_info_dict = ut.load_pickle(opt.dir+'/mechanism_info.pkl')
for img in img_list:
cv_im = cv.LoadImage(img)
annotate_image(cv_im, mech_info_dict, opt.dir)
sys.exit()
# cv.DestroyAllWindows()
#print 'k:', chr(k)
| [
[
1,
0,
0.034,
0.0049,
0,
0.66,
0,
509,
0,
2,
0,
0,
509,
0,
0
],
[
1,
0,
0.0388,
0.0049,
0,
0.66,
0.0909,
954,
0,
2,
0,
0,
954,
0,
0
],
[
1,
0,
0.0437,
0.0049,
0,
0... | [
"import sys, time",
"import numpy as np, math",
"import glob, commands",
"import roslib; roslib.load_manifest('modeling_forces')",
"import roslib; roslib.load_manifest('modeling_forces')",
"import cv",
"from cv_bridge.cv_bridge import CvBridge, CvBridgeError",
"import hrl_lib.util as ut",
"def call_... |
import csv
import numpy as np
import pylab as pb
import matplotlib_util.util as mpu
def load_data():
mk = csv.reader(open('Mechanism Kinematics.csv', 'U'))
data = []
for r in mk:
data.append(r)
return data
##
# Deal with repetition
def expand(data, keys):
repetition_idx = np.where(np.array(keys) == 'repetition')[0]
data[repetition_idx] = [int(e) for e in data[repetition_idx]]
repeated_data = []
for i in range(len(data)):
repeated_data.append([])
for current_instance in range(len(data[0])):
if data[repetition_idx][current_instance] > 1:
for rep in range(1, data[repetition_idx][current_instance]):
for l, rl in zip(data, repeated_data):
rl.append(l[current_instance])
for l, rl in zip(data, repeated_data):
l += rl
data.pop(repetition_idx)
keys.pop(repetition_idx)
return data
def test_expand():
data = [['a', 'b', 'c'], ['A', 'B', 'C'], [1, 4, 10]]
keys = ['letters', 'LETTERS', 'repetition']
new_data = expand(data, keys)
print new_data
def extract_keys(csv_data, keys):
format = csv_data[1]
indices = []
llists = []
for k in keys:
indices.append(np.where(np.array(format) == k)[0])
llists.append([])
for i in range(2, len(csv_data)):
if len(csv_data[i]) == 0:
break
if len(csv_data[i][indices[0]]) > 0:
for lidx, data_idx in enumerate(indices):
llists[lidx].append(csv_data[i][data_idx])
return llists
def plot_radii(csv_data, color='#3366FF'):
keys = ['radius', 'type', 'name', 'repetition']
llists = expand(extract_keys(csv_data, keys), keys)
rad_list = np.array([float(r) for r in llists[0]]) / 100.0
types = llists[1]
names = np.array(llists[2])
all_types = set(types)
print 'Radii types', all_types
types_arr = np.array(types)
# np.where(types_arr == 'C')
cabinet_rad_list = rad_list[np.where(types_arr == 'C')[0]]
others_rad_list = rad_list[np.where(types_arr != 'C')[0]]
other_names = names[np.where(types_arr != 'C')[0]]
print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
print 'radii other names'
for i, n in enumerate(other_names):
print n, others_rad_list[i]
print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
rad_lists = [rad_list, cabinet_rad_list, others_rad_list]
titles = ['Radii of Rotary Mechanisms', 'Radii of Cabinets', 'Radii of Other Mechanisms']
bin_width = 0.05
max_radius = np.max(rad_list)
print 'MIN RADIUS', np.min(rad_list)
print 'MAX RADIUS', max_radius
mpu.set_figure_size(5.,5.)
for idx, radii in enumerate(rad_lists):
f = pb.figure()
f.set_facecolor('w')
bins = np.arange(0.-bin_width/2., max_radius+2*bin_width, bin_width)
hist, bin_edges = np.histogram(radii, bins)
h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
width=0.8*bin_width, xlabel='Radius (meters)',
ylabel='\# of mechanisms',
plot_title=titles[idx],
color=color, label='All')
pb.xlim(.1, 1.)
pb.ylim(0, 55)
mpu.legend(display_mode = 'less_space', handlelength=1.)
#-- different classes in different colors in the same histogram.
f = pb.figure()
f.set_facecolor('w')
bins = np.arange(0.-bin_width/2., max_radius+2*bin_width, bin_width)
hist, bin_edges = np.histogram(rad_lists[0], bins)
h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
width=0.8*bin_width, xlabel='Radius (meters)',
ylabel='\# of mechanisms',
plot_title=titles[1],
color='g', label='Cabinets')
hist, bin_edges = np.histogram(rad_lists[2], bins)
h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
width=0.8*bin_width, xlabel='Radius (meters)',
ylabel='\# of mechanisms',
plot_title='Cabinets and Other Mechanisms',
color='y', label='Other')
pb.xlim(.1, 1.)
pb.ylim(0, 55)
mpu.legend(display_mode = 'less_space', handlelength=1.)
color_list = ['g', 'b', 'r']
marker_list = ['s', '^', 'v']
label_list = ['All', 'Cabinets', 'Other']
scatter_size_list = [8, 5, 5]
mpu.set_figure_size(5.,5.)
mpu.figure()
for idx, radii in enumerate(rad_lists):
bins = np.arange(0.-bin_width/2., max_radius+2*bin_width, bin_width)
hist, bin_edges = np.histogram(radii, bins)
bin_midpoints = np.arange(0., max_radius+bin_width, bin_width)
mpu.plot_yx(hist, bin_midpoints, color = color_list[idx],
alpha = 0.6, marker = marker_list[idx],
scatter_size = scatter_size_list[idx], xlabel='Radius (meters)',
ylabel='\# of mechanisms', label = label_list[idx])
mpu.legend(display_mode = 'less_space')
def plot_opening(csv_data):
keys = ['distance', 'type', 'repetition']
llists = expand(extract_keys(csv_data, keys), keys)
dists = np.array([float(f) for f in llists[0]])/100.
types = llists[1]
types_arr = np.array(types)
drawer_dists = dists[np.where(types_arr == 'R')[0]]
other_dists = dists[np.where(types_arr != 'R')[0]]
print 'Opening distances types', set(types)
bin_width = 0.02
bins = np.arange(-bin_width/2., np.max(dists)+2*bin_width, bin_width)
dists_list = [dists]#, drawer_dists, other_dists]
titles = ['Opening Distances of Drawers']#, 'drawer', 'other']
# print 'Total number of drawers:', len(dists)
mpu.set_figure_size(5.,4.)
for idx, d in enumerate(dists_list):
f = pb.figure()
f.set_facecolor('w')
hist, bin_edges = np.histogram(d, bins)
#import pdb; pdb.set_trace()
mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
width=0.8*bin_width, xlabel='Opening Distance (meters)',
ylabel='\# of Mechanisms',
plot_title=titles[idx], color='#3366FF')
# pb.xticks(bins[np.where(bins > np.min(dists))[0][0]-2:-1])
# pb.yticks(range(0, 26, 5))
# pb.ylim(0, 25)
def handle_height_histogram(mean_height_list, plot_title='', color='#3366FF', max_height=2.5, bin_width=.1, ymax=35):
bins = np.arange(0.-bin_width/2., max_height+2*bin_width, bin_width)
hist, bin_edges = np.histogram(np.array(mean_height_list), bins)
f = pb.figure()
f.set_facecolor('w')
f.subplots_adjust(bottom=.16, top=.86)
mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
width=bin_width*0.8, plot_title=plot_title,
xlabel='Height (meters)', ylabel='\# of mechanisms', color=color)
pb.xlim(0, max_height)
pb.ylim(0, ymax)
def handle_height_histogram_advait(mean_height_list, plot_title='',
color='#3366FF', max_height=2.2, bin_width=.1, ymax=35,
new_figure = True, label = '__no_legend__'):
if new_figure:
mpu.set_figure_size(5.,4.)
# f = mpu.figure()
# f.subplots_adjust(bottom=.25, top=.99, right=0.99, left=0.12)
bins = np.arange(0.-bin_width/2., max_height+2*bin_width, bin_width)
hist, bin_edges = np.histogram(np.array(mean_height_list), bins)
h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
width=bin_width*0.8, plot_title=plot_title,
xlabel='Height (meters)', ylabel='\# of mechanisms', color=color, label = label)
pb.xlim(0, max_height)
pb.ylim(0, ymax)
return h
def plot_rotary_heights(csv_data):
keys = ['radius', 'bottom', 'top', 'type', 'name', 'repetition']
llists = expand(extract_keys(csv_data, keys), keys)
types = llists[3]
names = np.array(llists[4])
print 'Handle bottom edge types', set(types)
bottom_pts = np.array([float(f) for f in llists[1]])/100.
top_pts = []
for i,f in enumerate(llists[2]):
if f == '':
f = llists[1][i]
top_pts.append(float(f)/100.)
top_pts = np.array(top_pts)
print 'total number of doors:', len(top_pts)
mid_pts = (bottom_pts + top_pts)/2.
types_arr = np.array(types)
cabinet_mid_pts = mid_pts[np.where(types_arr == 'C')[0]]
other_mid_pts = mid_pts[np.where(types_arr != 'C')[0]]
other_names = names[np.where(types_arr != 'C')[0]]
print 'other names', other_names
# Hai, Advait apologizes for changing code without making a copy.
# He didn't realise. He'll make a copy from an earlier revision in
# subversion soon.
ymax = 85
handle_height_histogram_advait(mid_pts, plot_title='Handle Heights', ymax=ymax, label = 'All')
mpu.legend(display_mode = 'less_space', handlelength=1.)
handle_height_histogram_advait(mid_pts, plot_title='Handle Heights', ymax=ymax, color = 'g', label = 'Cabinets')
handle_height_histogram_advait(other_mid_pts, plot_title='Handle Heights', ymax=ymax, color = 'y', new_figure = False, label = 'Other')
mpu.legend(display_mode = 'less_space', handlelength=1.)
def plot_prismatic_heights(csv_data):
keys = ['distance', 'bottom', 'top', 'type', 'name', 'home', 'repetition']
llists = expand(extract_keys(csv_data, keys), keys)
types = llists[3]
names = np.array(llists[4])
home = np.array(llists[5])
print 'Handle bottom edge types', set(types)
bottom_pts = np.array([float(f) for f in llists[1]])/100.
top_pts = []
for i,f in enumerate(llists[2]):
if f == '':
f = llists[1][i]
top_pts.append(float(f)/100.)
top_pts = np.array(top_pts)
mid_pts = (bottom_pts + top_pts)/2.
types_arr = np.array(types)
max_height = np.max(bottom_pts)
sort_order = np.argsort(bottom_pts)
names = names[sort_order]
bottom_pts = bottom_pts[sort_order]
home = home[sort_order]
for i, name in enumerate(names):
print home[i], name, bottom_pts[i]
handle_height_histogram(bottom_pts, plot_title='Heights of Handle Lower Edge (Drawers)', max_height = max_height)
max_height = np.max(mid_pts)
handle_height_histogram_advait(mid_pts, plot_title='Handle Heights', max_height = max_height+0.1, ymax=43)
#test_expand()
csv_data = load_data()
plot_prismatic_heights(csv_data)
#plot_radii(csv_data)
plot_rotary_heights(csv_data)
#plot_opening(csv_data)
pb.show()
| [
[
1,
0,
0.0037,
0.0037,
0,
0.66,
0,
312,
0,
1,
0,
0,
312,
0,
0
],
[
1,
0,
0.0074,
0.0037,
0,
0.66,
0.0588,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.0112,
0.0037,
0,
... | [
"import csv",
"import numpy as np",
"import pylab as pb",
"import matplotlib_util.util as mpu",
"def load_data():\n mk = csv.reader(open('Mechanism Kinematics.csv', 'U'))\n data = []\n for r in mk:\n data.append(r)\n\n return data",
" mk = csv.reader(open('Mechanism Kinematics.csv', ... |
#!/usr/bin/python
import roslib; roslib.load_manifest('modeling_forces')
import rospy
import force_torque.FTClient as ftc
import hrl_lib.util as ut
from std_msgs.msg import Empty
import time
import numpy as np
import glob
##
# make an appropriate plot.
# @param d - dictionary saved in the pkl
def plot_ft(d):
ft_list = d['ft_list']
time_list = d['time_list']
ft_mat = np.matrix(ft_list).T # 6xN np matrix
force_mat = ft_mat[0:3, :]
tarray = np.array(time_list)
print 'average rate', 1. / np.mean(tarray[1:] - tarray[:-1])
time_list = (tarray - tarray[0]).tolist()
print len(time_list)
force_mag_l = ut.norm(force_mat).A1.tolist()
#for i,f in enumerate(force_mag_l):
# if f > 15:
# break
#force_mag_l = force_mag_l[i:]
#time_list = time_list[i:]
mpu.plot_yx(force_mag_l, time_list, axis=None, label='Force Magnitude',
xlabel='Time(seconds)', ylabel='Force Magnitude (N)',
color = mpu.random_color())
def got_trigger_cb(data, d):
d['flag'] = True
if __name__ == '__main__':
import optparse
p = optparse.OptionParser()
p.add_option('-l', '--log', action='store_true', dest='log', help='log FT data')
p.add_option('-p', '--plot', action='store_true', dest='plot', help='plot FT data')
p.add_option('-r', '--ros', action='store_true', dest='ros',
help='start and stop logging messages over ROS.')
p.add_option('-a', '--all', action='store_true', dest='all',
help='plot all the pkls in a single plot')
p.add_option('-f', '--fname', action='store', default='',
type='string', dest='fname', help='pkl with logged data')
opt, args = p.parse_args()
if opt.log:
client = ftc.FTClient('/force_torque_ft2')
l = []
time_list = []
if opt.ros:
topic_name_cb = '/ftlogger/trigger'
got_trigger_dict = {'flag': False}
rospy.Subscriber(topic_name_cb, Empty, got_trigger_cb,
got_trigger_dict)
while got_trigger_dict['flag'] == False:
time.sleep(0.05)
got_trigger_dict['flag'] = False
while not rospy.is_shutdown():
ft, t_msg = client.read(fresh=True, with_time_stamp=True)
if ft != None:
l.append(ft.A1.tolist())
time_list.append(t_msg)
if got_trigger_dict['flag'] == True:
break
time.sleep(1/1000.0)
else:
print 'Sleeping for 5 seconds.'
time.sleep(5.)
print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
print 'BEGIN'
print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
client.bias()
t_start = time.time()
t_now = time.time()
logging_time = 5.
while (t_now - t_start) < logging_time:
ft, t_msg = client.read(fresh=True, with_time_stamp=True)
t_now = time.time()
if ft != None:
l.append(ft.A1.tolist())
time_list.append(t_msg)
time.sleep(1/1000.0)
print 'saving the pickle'
d = {}
d['ft_list'] = l
d['time_list'] = time_list
fname = 'ft_log_'+ut.formatted_time()+'.pkl'
ut.save_pickle(d, fname)
if opt.plot:
import matplotlib_util.util as mpu
if opt.fname == '' and (not opt.all):
raise RuntimeError('need a pkl name (-f or --fname) or --all')
if opt.all:
fname_list = glob.glob('ft_log*.pkl')
else:
fname_list = [opt.fname]
for fname in fname_list:
d = ut.load_pickle(fname)
plot_ft(d)
mpu.legend()
mpu.show()
| [
[
1,
0,
0.0233,
0.0078,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0233,
0.0078,
0,
0.66,
0.0909,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.031,
0.0078,
0,
0.6... | [
"import roslib; roslib.load_manifest('modeling_forces')",
"import roslib; roslib.load_manifest('modeling_forces')",
"import rospy",
"import force_torque.FTClient as ftc",
"import hrl_lib.util as ut",
"from std_msgs.msg import Empty",
"import time",
"import numpy as np",
"import glob",
"def plot_ft... |
import commands
import sys, os
import glob
l1 = glob.glob('data_1tb/*/mechanism_info.pkl')
l2 = []
for d in l1:
l2.append('/'.join(['aggregated_pkls_Feb11']+d.split('/')[1:]))
for d1,d2 in zip(l1,l2):
os.system('cp %s %s'%(d1, d2))
| [
[
1,
0,
0.1538,
0.0769,
0,
0.66,
0,
760,
0,
1,
0,
0,
760,
0,
0
],
[
1,
0,
0.2308,
0.0769,
0,
0.66,
0.1667,
509,
0,
2,
0,
0,
509,
0,
0
],
[
1,
0,
0.3077,
0.0769,
0,
... | [
"import commands",
"import sys, os",
"import glob",
"l1 = glob.glob('data_1tb/*/mechanism_info.pkl')",
"l2 = []",
"for d in l1:\n l2.append('/'.join(['aggregated_pkls_Feb11']+d.split('/')[1:]))",
" l2.append('/'.join(['aggregated_pkls_Feb11']+d.split('/')[1:]))",
"for d1,d2 in zip(l1,l2):\n o... |
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Author: Advait Jain
import roslib; roslib.load_manifest('2009_humanoids_epc_pull')
import scipy.optimize as so
import math, numpy as np
import pylab as pl
import sys, optparse, time
import copy
from enthought.mayavi import mlab
import mekabot.hrl_robot as hr
#import util as ut
import hrl_lib.util as ut, hrl_lib.transforms as tr
import matplotlib_util.util as mpu
import hrl_tilting_hokuyo.display_3d_mayavi as d3m
#import shapely.geometry as sg
class JointTrajectory():
''' class to store joint trajectories.
data only - use for pickling.
'''
def __init__(self):
self.time_list = [] # time in seconds
self.q_list = [] #each element is a list of 7 joint angles.
self.qdot_list = [] #each element is a list of 7 joint angles.
class CartesianTajectory():
''' class to store trajectory of cartesian points.
data only - use for pickling
'''
def __init__(self):
self.time_list = [] # time in seconds
self.p_list = [] #each element is a list of 3 coordinates
class ForceTrajectory():
''' class to store time evolution of the force at the end effector.
data only - use for pickling
'''
def __init__(self):
self.time_list = [] # time in seconds
self.f_list = [] #each element is a list of 3 coordinates
def joint_to_cartesian(traj):
''' traj - JointTrajectory
returns CartesianTajectory after performing FK on traj.
'''
firenze = hr.M3HrlRobot(connect=False)
pts = []
for q in traj.q_list:
p = firenze.FK('right_arm',q)
pts.append(p.A1.tolist())
ct = CartesianTajectory()
ct.time_list = copy.copy(traj.time_list)
ct.p_list = copy.copy(pts)
#return np.matrix(pts).T
return ct
def plot_forces_quiver(pos_traj,force_traj,color='k'):
import arm_trajectories as at
#if traj.__class__ == at.JointTrajectory:
if isinstance(pos_traj,at.JointTrajectory):
pos_traj = joint_to_cartesian(pos_traj)
pts = np.matrix(pos_traj.p_list).T
label_list = ['X coord (m)', 'Y coord (m)', 'Z coord (m)']
x = pts[0,:].A1.tolist()
y = pts[1,:].A1.tolist()
forces = np.matrix(force_traj.f_list).T
u = (-1*forces[0,:]).A1.tolist()
v = (-1*forces[1,:]).A1.tolist()
pl.quiver(x,y,u,v,width=0.002,color=color,scale=100.0)
# pl.quiver(x,y,u,v,width=0.002,color=color)
pl.axis('equal')
def plot_cartesian(traj,xaxis=None,yaxis=None,zaxis=None,color='b',label='_nolegend_',
linewidth=2,scatter_size=20):
''' xaxis - x axis for the graph (0,1 or 2)
zaxis - for a 3d plot. not implemented.
'''
import arm_trajectories as at
#if traj.__class__ == at.JointTrajectory:
if isinstance(traj,at.JointTrajectory):
traj = joint_to_cartesian(traj)
pts = np.matrix(traj.p_list).T
label_list = ['X coord (m)', 'Y coord (m)', 'Z coord (m)']
x = pts[xaxis,:].A1.tolist()
y = pts[yaxis,:].A1.tolist()
if zaxis == None:
pl.plot(x,y,c=color,linewidth=linewidth,label=label)
pl.scatter(x,y,c=color,s=scatter_size,label='_nolegend_', linewidths=0)
pl.xlabel(label_list[xaxis])
pl.ylabel(label_list[yaxis])
pl.legend(loc='best')
pl.axis('equal')
else:
from numpy import array
from enthought.mayavi.api import Engine
engine = Engine()
engine.start()
if len(engine.scenes) == 0:
engine.new_scene()
z = pts[zaxis,:].A1.tolist()
time_list = [t-traj.time_list[0] for t in traj.time_list]
mlab.plot3d(x,y,z,time_list,tube_radius=None,line_width=4)
mlab.axes()
mlab.xlabel(label_list[xaxis])
mlab.ylabel(label_list[yaxis])
mlab.zlabel(label_list[zaxis])
mlab.colorbar(title='Time')
# -------------------------------------------
axes = engine.scenes[0].children[0].children[0].children[1]
axes.axes.position = array([ 0., 0.])
axes.axes.label_format = '%-#6.2g'
axes.title_text_property.font_size=4
## compute the force that the arm would apply given the stiffness matrix
# @param q_actual_traj - Joint Trajectory (actual angles.)
# @param q_eq_traj - Joint Trajectory (equilibrium point angles.)
# @param torque_traj - JointTrajectory (torques measured at the joints.)
# @param rel_stiffness_list - list of 5 elements (stiffness numbers for the joints.)
# @return lots of things, look at the code.
def compute_forces(q_actual_traj,q_eq_traj,torque_traj,rel_stiffness_list):
firenze = hr.M3HrlRobot(connect=False)
d_gains_list_mN_deg_sec = [-100,-120,-15,-25,-1.25]
d_gains_list = [180./1000.*s/math.pi for s in d_gains_list_mN_deg_sec]
stiff_list_mNm_deg = [1800,1300,350,600,60]
stiff_list_Nm_rad = [180./1000.*s/math.pi for s in stiff_list_mNm_deg]
# stiffness_settings = [0.15,0.7,0.8,0.8,0.8]
# dia = np.array(stiffness_settings) * np.array(stiff_list_Nm_rad)
dia = np.array(rel_stiffness_list) * np.array(stiff_list_Nm_rad)
k_q = np.matrix(np.diag(dia))
dia_inv = 1./dia
k_q_inv = np.matrix(np.diag(dia_inv))
actual_cart = joint_to_cartesian(q_actual_traj)
eq_cart = joint_to_cartesian(q_eq_traj)
force_traj_jacinv = ForceTrajectory()
force_traj_stiff = ForceTrajectory()
force_traj_torque = ForceTrajectory()
k_cart_list = []
for q_actual,q_dot,q_eq,actual_pos,eq_pos,t,tau_m in zip(q_actual_traj.q_list,q_actual_traj.qdot_list,q_eq_traj.q_list,actual_cart.p_list,eq_cart.p_list,q_actual_traj.time_list,torque_traj.q_list):
q_eq = firenze.clamp_to_physical_joint_limits('right_arm',q_eq)
q_delta = np.matrix(q_actual).T - np.matrix(q_eq).T
tau = k_q * q_delta[0:5,0] - np.matrix(np.array(d_gains_list)*np.array(q_dot)[0:5]).T
x_delta = np.matrix(actual_pos).T - np.matrix(eq_pos).T
jac_full = firenze.Jac('right_arm',q_actual)
jac = jac_full[0:3,0:5]
jac_full_eq = firenze.Jac('right_arm',q_eq)
jac_eq = jac_full_eq[0:3,0:5]
k_cart = np.linalg.inv((jac_eq*k_q_inv*jac_eq.T)) # calculating stiff matrix using Jacobian for eq pt.
k_cart_list.append(k_cart)
pseudo_inv_jac = np.linalg.inv(jac_full*jac_full.T)*jac_full
tau_full = np.row_stack((tau,np.matrix(tau_m[5:7]).T))
#force = (-1*pseudo_inv_jac*tau_full)[0:3]
force = -1*pseudo_inv_jac[0:3,0:5]*tau
force_traj_jacinv.f_list.append(force.A1.tolist())
force_traj_stiff.f_list.append((k_cart*x_delta).A1.tolist())
force_traj_torque.f_list.append((pseudo_inv_jac*np.matrix(tau_m).T)[0:3].A1.tolist())
return force_traj_jacinv,force_traj_stiff,force_traj_torque,k_cart_list
## return two lists containing the radial and tangential components of the forces.
# @param f_list - list of forces. (each force is a list of 2 or 3 floats)
# @param p_list - list of positions. (each position is a list of 2 or 3 floats)
# @param cx - x coord of the center of the circle.
# @param cy - y coord of the center of the circle.
# @return list of magnitude of radial component, list of magnitude tangential component.
def compute_radial_tangential_forces(f_list,p_list,cx,cy):
f_rad_l,f_tan_l = [],[]
for f,p in zip(f_list,p_list):
rad_vec = np.array([p[0]-cx,p[1]-cy])
rad_vec = rad_vec/np.linalg.norm(rad_vec)
f_vec = np.array([f[0],f[1]])
f_rad_mag = np.dot(f_vec,rad_vec)
f_tan_mag = np.linalg.norm(f_vec-rad_vec*f_rad_mag)
f_rad_mag = abs(f_rad_mag)
f_rad_l.append(f_rad_mag)
f_tan_l.append(f_tan_mag)
return f_rad_l,f_tan_l
def plot_error_forces(measured_list,calc_list):
err_x, err_y = [],[]
err_rel_x, err_rel_y = [],[]
mag_x, mag_y = [],[]
for m,c in zip(measured_list,calc_list):
err_x.append(abs(m[0]-c[0]))
err_rel_x.append(abs(m[0]-c[0])/abs(m[0])*100)
#err_rel_x.append(ut.bound(abs(m[0]-c[0])/abs(m[0])*100,100,0))
mag_x.append(abs(m[0]))
err_y.append(abs(m[1]-c[1]))
err_rel_y.append(abs(m[1]-c[1])/abs(m[1])*100)
#err_rel_y.append(ut.bound(abs(m[1]-c[1])/abs(m[1])*100,100,0))
mag_y.append(abs(m[1]))
x_idx = range(len(err_x))
zero = [0 for i in x_idx]
fig = pl.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.plot(zero,c='k',linewidth=1,label='_nolegend_')
l1 = ax1.plot(err_x,c='b',linewidth=1,label='absolute error')
ax1.scatter(x_idx,err_x,c='b',s=10,label='_nolegend_', linewidths=0)
l2 = ax1.plot(mag_x,c='g',linewidth=1,label='magnitude')
ax1.scatter(x_idx,mag_x,c='g',s=10,label='_nolegend_', linewidths=0)
l3 = ax2.plot(err_rel_x,c='r',linewidth=1,label='relative error %')
ax1.set_ylim(0,15)
ax2.set_ylim(0,100)
ax1.set_xlabel('measurement number')
ax1.set_ylabel('x component of force (N)')
ax2.set_ylabel('percentage error')
ax1.yaxis.set_label_coords(-0.3,0.5)
ax2.yaxis.set_label_coords(-0.3,0.5)
leg = pl.legend([l1,l2,l3],['absolute error','magnitude','rel error %'],loc='upper left',
handletextsep=0.015,handlelen=0.003,labelspacing=0.003)
fig = pl.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.plot(zero,c='k',linewidth=1)
l1 = ax1.plot(err_y,c='b',linewidth=1)
ax1.scatter(x_idx,err_y,c='b',s=10, linewidths=0)
l2 = ax1.plot(mag_y,c='g',linewidth=1)
ax1.scatter(x_idx,mag_y,c='g',s=10,linewidths=0)
l3 = ax2.plot(err_rel_y,c='r',linewidth=1)
ax1.set_ylim(0,15)
ax2.set_ylim(0,100)
ax1.yaxis.set_label_coords(-0.3,0.5)
ax2.yaxis.set_label_coords(-0.3,0.5)
ax1.set_xlabel('measurement number')
ax1.set_ylabel('y component of force (N)')
ax2.set_ylabel('percentage error')
#pl.legend(loc='best')
leg = pl.legend([l1,l2,l3],['absolute error','magnitude','rel error %'],loc='upper left',
handletextsep=0.015,handlelen=0.003,labelspacing=0.003)
# pl.figure()
# pl.plot(zero,c='k',linewidth=0.5,label='_nolegend_')
# pl.plot(err_y,c='b',linewidth=1,label='error')
# pl.plot(err_rel_y,c='r',linewidth=1,label='relative error %')
# pl.scatter(x_idx,err_y,c='b',s=10,label='_nolegend_', linewidths=0)
# pl.plot(mag_y,c='g',linewidth=1,label='magnitude')
# pl.scatter(x_idx,mag_y,c='g',s=10,label='_nolegend_', linewidths=0)
#
# pl.xlabel('measurement number')
# pl.ylabel('y component of force (N)')
# pl.legend(loc='best')
# pl.axis('equal')
def plot_stiff_ellipses(k_cart_list,pos_traj,skip=10,subplotnum=111):
import arm_trajectories as at
if isinstance(pos_traj,at.JointTrajectory):
pos_traj = joint_to_cartesian(pos_traj)
pts = np.matrix(pos_traj.p_list).T
x_l = pts[0,:].A1.tolist()
y_l = pts[1,:].A1.tolist()
from pylab import figure, show, rand
from matplotlib.patches import Ellipse
ells = []
scale = 25000.
ratio_list = []
for k_c,x,y in zip(k_cart_list[::skip],x_l[::skip],y_l[::skip]):
w,v = np.linalg.eig(k_c[0:2,0:2])
w_abs = np.abs(w)
major_axis = np.max(w_abs)
minor_axis = np.min(w_abs)
print 'major, minor:',major_axis,minor_axis
# print 'k_c:', k_c
ratio_list.append(major_axis/minor_axis)
ells.append(Ellipse(np.array([x,y]),width=w[0]/scale,height=w[1]/scale,angle=math.degrees(math.atan2(v[1,0],v[0,0]))))
ells[-1].set_lw(2)
#fig = pl.figure()
#ax = fig.add_subplot(111, aspect='equal')
ax = pl.subplot(subplotnum, aspect='equal')
for e in ells:
ax.add_artist(e)
#e.set_clip_box(ax.bbox)
#e.set_alpha(1.)
e.set_facecolor(np.array([1,1,1]))
plot_cartesian(pos_traj,xaxis=0,yaxis=1,color='b',
linewidth=0.0,scatter_size=0)
# plot_cartesian(pos_traj,xaxis=0,yaxis=1,color='b',label='Eq Point',
# linewidth=1.5,scatter_size=0)
# plot_cartesian(d['actual'],xaxis=0,yaxis=1,color='b',label='FK',
# linewidth=1.5,scatter_size=0)
# plot_cartesian(d['eq_pt'], xaxis=0,yaxis=1,color='g',label='Eq Point',
# linewidth=1.5,scatter_size=0)
mean_ratio = np.mean(np.array(ratio_list))
std_ratio = np.std(np.array(ratio_list))
return mean_ratio,std_ratio
# plot the force field in the xy plane for the stiffness matrix k_cart.
## @param k_cart: 3x3 cartesian space stiffness matrix.
def plot_stiffness_field(k_cart,plottitle=''):
n_points = 20
ang_step = math.radians(360)/n_points
x_list = []
y_list = []
u_list = []
v_list = []
k_cart = k_cart[0:2,0:2]
for i in range(n_points):
ang = i*ang_step
for r in [0.5,1.,1.5]:
dx = r*math.cos(ang)
dy = r*math.sin(ang)
dtau = -k_cart*np.matrix([dx,dy]).T
x_list.append(dx)
y_list.append(dy)
u_list.append(dtau[0,0])
v_list.append(dtau[1,0])
pl.figure()
# mpu.plot_circle(0,0,1.0,0.,math.radians(360))
mpu.plot_radii(0,0,1.5,0.,math.radians(360),interval=ang_step,color='r')
pl.quiver(x_list,y_list,u_list,v_list,width=0.002,color='k',scale=None)
pl.axis('equal')
pl.title(plottitle)
def plot_stiff_ellipse_map(stiffness_list,num):
firenze = hr.M3HrlRobot(connect=False)
hook_3dprint_angle = math.radians(20-2.54)
rot_mat = tr.Rz(0.-hook_3dprint_angle)*tr.Ry(math.radians(-90))
d_gains_list_mN_deg_sec = [-100,-120,-15,-25,-1.25]
d_gains_list = [180./1000.*s/math.pi for s in d_gains_list_mN_deg_sec]
stiff_list_mNm_deg = [1800,1300,350,600,60]
stiff_list_Nm_rad = [180./1000.*s/math.pi for s in stiff_list_mNm_deg]
dia = np.array(stiffness_list) * np.array(stiff_list_Nm_rad)
k_q = np.matrix(np.diag(dia))
dia_inv = 1./dia
k_q_inv = np.matrix(np.diag(dia_inv))
s0,s1,s2,s3 = stiffness_list[0],stiffness_list[1],stiffness_list[2],stiffness_list[3]
i=0
#for z in np.arange(-0.1,-0.36,-0.05):
for z in np.arange(-0.23,-0.27,-0.05):
pl.figure()
k_cart_list = []
pos_traj = CartesianTajectory()
for x in np.arange(0.25,0.56,0.05):
for y in np.arange(-0.15,-0.56,-0.05):
if math.sqrt(x**2+y**2)>0.55:
continue
q = firenze.IK('right_arm',np.matrix([x,y,z]).T,rot_mat)
if q == None:
continue
jac_full = firenze.Jac('right_arm',q)
jac = jac_full[0:3,0:5]
k_cart = np.linalg.inv((jac*k_q_inv*jac.T))
k_cart_list.append(k_cart)
pos_traj.p_list.append([x,y,z])
pos_traj.time_list.append(0.1)
if len(pos_traj.p_list)>0:
ret = plot_stiff_ellipses(k_cart_list,pos_traj,skip=1)
pl.axis('equal')
pl.legend(loc='best')
title_string = 'z: %.2f stiff:[%.1f,%.1f,%.1f,%.1f]'%(z,s0,s1,s2,s3)
pl.title(title_string)
i+=1
pl.savefig('ellipses_%03d_%03d.png'%(num,i))
return ret
def compute_workspace(z,plot=False,wrist_roll_angle=math.radians(0),subplotnum=None,title=''):
firenze = hr.M3HrlRobot(connect=False)
# hook_3dprint_angle = math.radians(20-2.54)
# rot_mat = tr.Rz(math.radians(-90.)-hook_3dprint_angle)*tr.Ry(math.radians(-90))
rot_mat = tr.Rz(wrist_roll_angle)*tr.Ry(math.radians(-90))
x_list,y_list = [],[]
for x in np.arange(0.15,0.65,0.02):
for y in np.arange(-0.05,-0.65,-0.02):
q = firenze.IK('right_arm',np.matrix([x,y,z]).T,rot_mat)
if q != None:
x_list.append(x)
y_list.append(y)
if len(x_list) > 2:
multipoint = sg.Point(x_list[0],y_list[0])
for x,y in zip(x_list[1:],y_list[1:]):
multipoint = multipoint.union(sg.Point(x,y))
hull = multipoint.convex_hull
if plot:
coords_seq = hull.boundary.coords
hull_x_list,hull_y_list = [],[]
for c in coords_seq:
hull_x_list.append(c[0])
hull_y_list.append(c[1])
mpu.plot_yx(y_list,x_list,linewidth=0,subplotnum=subplotnum,axis='equal',
plot_title=title)
mpu.plot_yx(hull_y_list,hull_x_list,linewidth=2,subplotnum=subplotnum,axis='equal')
return hull,len(x_list)
else:
return None,None
def diff_roll_angles():
pl.subplot(211,aspect='equal')
# search along z coord and make a histogram of the areas
def compute_workspace_z():
n_points_list,area_list,z_list = [],[],[]
#for z in np.arange(-0.1,-0.36,-0.02):
#for z in np.arange(-0.05,-0.35,-0.01):
for z in np.arange(-0.15,-0.155,-0.01):
pl.figure()
hull,n_points = compute_workspace(z,plot=True)
pl.title('z: %.2f'%(z))
pl.savefig('z_%.2f.png'%(z))
# hull,n_points = compute_workspace(z,plot=False)
if hull != None:
area_list.append(hull.area)
z_list.append(z)
n_points_list.append(n_points)
coords_seq = hull.boundary.coords
hull_x_list,hull_y_list = [],[]
for c in coords_seq:
hull_x_list.append(c[0])
hull_y_list.append(c[1])
pl.figure()
mpu.plot_yx(area_list,z_list,linewidth=2,label='area')
pl.savefig('hist_area.png')
pl.figure()
mpu.plot_yx(n_points_list,z_list,linewidth=2,color='g',label='n_points')
# pl.legend(loc='best')
pl.xlabel('Z coordinate (m)')
pl.ylabel('# points')
pl.savefig('hist_points.png')
## find the x and y coord of the center of the circle of given radius that
# best matches the data.
# @param rad - radius of the circle (not optimized)
# @param x_guess - guess for x coord of center
# @param y_guess - guess for y coord of center.
# @param pts - 2xN np matrix of points.
# @return x,y (x and y coord of the center of the circle)
def fit_rotary_joint(rad,x_guess,y_guess,pts):
def error_function(params):
center = np.matrix((params[0],params[1])).T
#print 'pts.shape', pts.shape
#print 'center.shape', center.shape
#print 'ut.norm(pts-center).shape',ut.norm(pts-center).shape
err = ut.norm(pts-center).A1 - rad
res = np.dot(err,err)
return res
params_1 = [x_guess,y_guess]
r = so.fmin_bfgs(error_function,params_1,full_output=1)
opt_params_1,f_opt_1 = r[0],r[1]
params_2 = [x_guess,y_guess+2*rad]
r = so.fmin_bfgs(error_function,params_2,full_output=1)
opt_params_2,f_opt_2 = r[0],r[1]
if f_opt_2<f_opt_1:
return opt_params_2[0],opt_params_2[1]
else:
return opt_params_1[0],opt_params_1[1]
## find the x and y coord of the center of the circle and the radius that
# best matches the data.
# @param rad_guess - guess for the radius of the circle
# @param x_guess - guess for x coord of center
# @param y_guess - guess for y coord of center.
# @param pts - 2xN np matrix of points.
# @param method - optimization method. ('fmin' or 'fmin_bfgs')
# @param verbose - passed onto the scipy optimize functions. whether to print out the convergence info.
# @return r,x,y (radius, x and y coord of the center of the circle)
def fit_circle(rad_guess,x_guess,y_guess,pts,method,verbose=True):
def error_function(params):
center = np.matrix((params[0],params[1])).T
rad = params[2]
#print 'pts.shape', pts.shape
#print 'center.shape', center.shape
#print 'ut.norm(pts-center).shape',ut.norm(pts-center).shape
err = ut.norm(pts-center).A1 - rad
res = np.dot(err,err)
return res
params_1 = [x_guess,y_guess,rad_guess]
if method == 'fmin':
r = so.fmin(error_function,params_1,xtol=0.0002,ftol=0.000001,full_output=1,disp=verbose)
opt_params_1,fopt_1 = r[0],r[1]
elif method == 'fmin_bfgs':
r = so.fmin_bfgs(error_function,params_1,full_output=1,disp=verbose)
opt_params_1,fopt_1 = r[0],r[1]
else:
raise RuntimeError('unknown method: '+method)
params_2 = [x_guess,y_guess+2*rad_guess,rad_guess]
if method == 'fmin':
r = so.fmin(error_function,params_2,xtol=0.0002,ftol=0.000001,full_output=1,disp=verbose)
opt_params_2,fopt_2 = r[0],r[1]
elif method == 'fmin_bfgs':
r = so.fmin_bfgs(error_function,params_2,full_output=1,disp=verbose)
opt_params_2,fopt_2 = r[0],r[1]
else:
raise RuntimeError('unknown method: '+method)
if fopt_2<fopt_1:
return opt_params_2[2],opt_params_2[0],opt_params_2[1]
else:
return opt_params_1[2],opt_params_1[0],opt_params_1[1]
if __name__ == '__main__':
p = optparse.OptionParser()
p.add_option('-f', action='store', type='string', dest='fname',
help='pkl file to use.', default='')
p.add_option('--xy', action='store_true', dest='xy',
help='plot the x and y coordinates of the end effector.')
p.add_option('--yz', action='store_true', dest='yz',
help='plot the y and z coordinates of the end effector.')
p.add_option('--xz', action='store_true', dest='xz',
help='plot the x and z coordinates of the end effector.')
p.add_option('--plot_ellipses', action='store_true', dest='plot_ellipses',
help='plot the stiffness ellipse in the x-y plane')
p.add_option('--pfc', action='store_true', dest='pfc',
help='plot the radial and tangential components of the force.')
p.add_option('--pmf', action='store_true', dest='pmf',
help='plot things with the mechanism alinged with the axes.')
p.add_option('--pff', action='store_true', dest='pff',
help='plot the force field corresponding to a stiffness ellipse.')
p.add_option('--pev', action='store_true', dest='pev',
help='plot the stiffness ellipses for different combinations of the rel stiffnesses.')
p.add_option('--plot_forces', action='store_true', dest='plot_forces',
help='plot the force in the x-y plane')
p.add_option('--plot_forces_error', action='store_true', dest='plot_forces_error',
help='plot the error between the computed and measured (ATI) forces in the x-y plane')
p.add_option('--xyz', action='store_true', dest='xyz',
help='plot in 3d the coordinates of the end effector.')
p.add_option('-r', action='store', type='float', dest='rad',
help='radius of the joint.', default=None)
p.add_option('--rad_fix', action='store_true', dest='rad_fix',
help='do not optimize for the radius.')
p.add_option('--noshow', action='store_true', dest='noshow',
help='do not display the figure (use while saving figures to disk)')
p.add_option('--exptplot', action='store_true', dest='exptplot',
help='put all the graphs of an experiment as subplots.')
p.add_option('--pwf', action='store_true', dest='pwf',
help='plot the workspace at some z coord.')
opt, args = p.parse_args()
fname = opt.fname
xy_flag = opt.xy
yz_flag = opt.yz
xz_flag = opt.xz
plot_forces_flag = opt.plot_forces
plot_ellipses_flag = opt.plot_ellipses
plot_forces_error_flag = opt.plot_forces_error
plot_force_components_flag = opt.pfc
plot_force_field_flag = opt.pff
plot_mechanism_frame = opt.pmf
xyz_flag = opt.xyz
rad = opt.rad
show_fig = not(opt.noshow)
plot_ellipses_vary_flag = opt.pev
expt_plot = opt.exptplot
rad_fix = opt.rad_fix
plot_workspace_flag = opt.pwf
if plot_workspace_flag:
compute_workspace_z()
# hull = compute_workspace(z=-0.22,plot=True)
# pl.show()
if plot_ellipses_vary_flag:
show_fig=False
i = 0
ratio_list1 = [0.1,0.3,0.5,0.7,0.9] # coarse search
ratio_list2 = [0.1,0.3,0.5,0.7,0.9] # coarse search
ratio_list3 = [0.1,0.3,0.5,0.7,0.9] # coarse search
# ratio_list1 = [0.7,0.8,0.9,1.0]
# ratio_list2 = [0.7,0.8,0.9,1.0]
# ratio_list3 = [0.3,0.4,0.5,0.6,0.7]
# ratio_list1 = [1.0,2.,3.0]
# ratio_list2 = [1.,2.,3.]
# ratio_list3 = [0.3,0.4,0.5,0.6,0.7]
inv_mean_list,std_list = [],[]
x_l,y_l,z_l = [],[],[]
s0 = 0.2
#s0 = 0.4
for s1 in ratio_list1:
for s2 in ratio_list2:
for s3 in ratio_list3:
i += 1
s_list = [s0,s1,s2,s3,0.8]
#s_list = [s1,s2,s3,s0,0.8]
print '################## s_list:', s_list
m,s = plot_stiff_ellipse_map(s_list,i)
inv_mean_list.append(1./m)
std_list.append(s)
x_l.append(s1)
y_l.append(s2)
z_l.append(s3)
ut.save_pickle({'x_l':x_l,'y_l':y_l,'z_l':z_l,'inv_mean_list':inv_mean_list,'std_list':std_list},
'stiff_dict_'+ut.formatted_time()+'.pkl')
d3m.plot_points(np.matrix([x_l,y_l,z_l]),scalar_list=inv_mean_list,mode='sphere')
mlab.axes()
d3m.show()
sys.exit()
if fname=='':
print 'please specify a pkl file (-f option)'
print 'Exiting...'
sys.exit()
d = ut.load_pickle(fname)
actual_cartesian = joint_to_cartesian(d['actual'])
eq_cartesian = joint_to_cartesian(d['eq_pt'])
for p in actual_cartesian.p_list:
print p[0],p[1],p[2]
if rad != None:
#rad = 0.39 # lab cabinet recessed.
#rad = 0.42 # kitchen cabinet
#rad = 0.80 # lab glass door
pts_list = actual_cartesian.p_list
ee_start_pos = pts_list[0]
x_guess = ee_start_pos[0]
y_guess = ee_start_pos[1] - rad
print 'before call to fit_rotary_joint'
pts_2d = (np.matrix(pts_list).T)[0:2,:]
t0 = time.time()
if rad_fix:
rad_guess = 0.9
else:
rad_guess = rad
rad_fmin,cx,cy = fit_circle(rad_guess,x_guess,y_guess,pts_2d[:,0:-4],method='fmin')
t1 = time.time()
rad_opt,cx,cy = fit_circle(rad_guess,x_guess,y_guess,pts_2d[:,0:-4],method='fmin_bfgs')
t2 = time.time()
print 'after fit_rotary_joint'
print 'optimized radius:', rad_opt
print 'optimized radius fmin:', rad_fmin
print 'time to bfgs:', t2-t1
print 'time to fmin:', t1-t0
if rad_fix:
cx,cy = fit_rotary_joint(rad,x_guess,y_guess,pts_2d[:,0:-4])
else:
rad = rad_opt
if plot_mechanism_frame:
if expt_plot:
pl.subplot(231)
# transform points so that the mechanism is in a fixed position.
start_pt = actual_cartesian.p_list[0]
x_diff = start_pt[0] - cx
y_diff = start_pt[1] - cy
angle = math.atan2(y_diff,x_diff) - math.radians(90)
rot_mat = tr.Rz(angle)[0:2,0:2]
translation_mat = np.matrix([cx,cy]).T
robot_width,robot_length = 0.1,0.2
robot_x_list = [-robot_width/2,-robot_width/2,robot_width/2,robot_width/2,-robot_width/2]
robot_y_list = [-robot_length/2,robot_length/2,robot_length/2,-robot_length/2,-robot_length/2]
robot_mat = rot_mat*(np.matrix([robot_x_list,robot_y_list]) - translation_mat)
mpu.plot_yx(robot_mat[1,:].A1,robot_mat[0,:].A1,linewidth=2,scatter_size=0,
color='k',label='torso')
pts2d_actual = (np.matrix(actual_cartesian.p_list).T)[0:2]
pts2d_actual_t = rot_mat *(pts2d_actual - translation_mat)
mpu.plot_yx(pts2d_actual_t[1,:].A1,pts2d_actual_t[0,:].A1,scatter_size=20,label='FK')
end_pt = pts2d_actual_t[:,-1]
end_angle = tr.angle_within_mod180(math.atan2(end_pt[1,0],end_pt[0,0])-math.radians(90))
mpu.plot_circle(0,0,rad,0.,end_angle,label='Actual_opt',color='r')
mpu.plot_radii(0,0,rad,0.,end_angle,interval=math.radians(15),color='r')
pl.legend(loc='best')
pl.axis('equal')
if not(expt_plot):
str_parts = fname.split('.')
fig_name = str_parts[0]+'_robot_pose.png'
pl.savefig(fig_name)
pl.figure()
else:
pl.subplot(232)
pl.text(0.1,0.15,d['info'])
pl.text(0.1,0.10,'control: '+d['strategy'])
pl.text(0.1,0.05,'robot angle: %.2f'%math.degrees(angle))
pl.text(0.1,0,'optimized radius: %.2f'%rad_opt)
pl.text(0.1,-0.05,'radius used: %.2f'%rad)
pl.text(0.1,-0.10,'opening angle: %.2f'%math.degrees(end_angle))
s_list = d['stiffness'].stiffness_list
s_scale = d['stiffness'].stiffness_scale
sl = [min(s*s_scale,1.0) for s in s_list]
pl.text(0.1,-0.15,'stiffness list: %.2f, %.2f, %.2f, %.2f'%(sl[0],sl[1],sl[2],sl[3]))
pl.text(0.1,-0.20,'stop condition: '+d['result'])
time_dict = d['time_dict']
pl.text(0.1,-0.25,'time to hook: %.2f'%(time_dict['before_hook']-time_dict['before_pull']))
pl.text(0.1,-0.30,'time to pull: %.2f'%(time_dict['before_pull']-time_dict['after_pull']))
pl.ylim(-0.45,0.25)
if not(expt_plot):
pl.figure()
if xy_flag:
st_pt = pts_2d[:,0]
start_angle = tr.angle_within_mod180(math.atan2(st_pt[1,0]-cy,st_pt[0,0]-cx) - math.radians(90))
end_pt = pts_2d[:,-1]
end_angle = tr.angle_within_mod180(math.atan2(end_pt[1,0]-cy,end_pt[0,0]-cx) - math.radians(90))
print 'start_angle, end_angle:', math.degrees(start_angle), math.degrees(end_angle)
print 'angle through which mechanism turned:', math.degrees(end_angle-start_angle)
if expt_plot:
pl.subplot(233)
plot_cartesian(actual_cartesian,xaxis=0,yaxis=1,color='b',label='End Effector Trajectory')
plot_cartesian(eq_cartesian, xaxis=0,yaxis=1,color='g',label='Eq Point')
mpu.plot_circle(cx,cy,rad,start_angle,end_angle,label='Estimated Kinematics',color='r')
# if rad<0.6:
# mpu.plot_radii(cx,cy,rad,start_angle,end_angle,interval=math.radians(100),color='r')
# pl.title(d['info'])
leg = pl.legend(loc='best')#,handletextsep=0.020,handlelen=0.003,labelspacing=0.003)
leg.draw_frame(False)
ax = pl.gca()
ax.set_xlim(ax.get_xlim()[::-1])
ax.set_ylim(ax.get_ylim()[::-1])
force_traj = d['force']
forces = np.matrix(force_traj.f_list).T
force_mag = ut.norm(forces)
print 'force_mag:', force_mag.A1
elif yz_flag:
plot_cartesian(actual_cartesian,xaxis=1,yaxis=2,color='b',label='FK')
plot_cartesian(eq_cartesian, xaxis=1,yaxis=2,color='g',label='Eq Point')
elif xz_flag:
plot_cartesian(actual_cartesian,xaxis=0,yaxis=2,color='b',label='FK')
plot_cartesian(eq_cartesian, xaxis=0,yaxis=2,color='g',label='Eq Point')
if plot_forces_flag or plot_forces_error_flag or plot_ellipses_flag or plot_force_components_flag or plot_force_field_flag:
arm_stiffness_list = d['stiffness'].stiffness_list
scale = d['stiffness'].stiffness_scale
asl = [min(scale*s,1.0) for s in arm_stiffness_list]
ftraj_jinv,ftraj_stiff,ftraj_torque,k_cart_list=compute_forces(d['actual'],d['eq_pt'],
d['torque'],asl)
if plot_forces_flag:
plot_forces_quiver(actual_cartesian,d['force'],color='k')
plot_forces_quiver(actual_cartesian,ftraj_jinv,color='y')
#plot_forces_quiver(actual_cartesian,ftraj_stiff,color='y')
if plot_ellipses_flag:
#plot_stiff_ellipses(k_cart_list,actual_cartesian)
if expt_plot:
subplotnum=234
else:
pl.figure()
subplotnum=111
plot_stiff_ellipses(k_cart_list,eq_cartesian,subplotnum=subplotnum)
if plot_forces_error_flag:
plot_error_forces(d['force'].f_list,ftraj_jinv.f_list)
#plot_error_forces(d['force'].f_list,ftraj_stiff.f_list)
if plot_force_components_flag:
p_list = actual_cartesian.p_list
frad_list,ftan_list = compute_radial_tangential_forces(d['force'].f_list,p_list,cx,cy)
if expt_plot:
pl.subplot(235)
else:
pl.figure()
time_list = d['force'].time_list
time_list = [t-time_list[0] for t in time_list]
x_coord_list = np.matrix(p_list)[:,0].A1.tolist()
mpu.plot_yx(frad_list,x_coord_list,scatter_size=50,color=time_list,cb_label='time')
pl.xlabel('x coord of end effector (m)')
pl.ylabel('magnitude of radial force (N)')
pl.title(d['info'])
if expt_plot:
pl.subplot(236)
else:
pl.figure()
mpu.plot_yx(ftan_list,x_coord_list,scatter_size=50,color=time_list,cb_label='time')
pl.xlabel('x coord of end effector (m)')
pl.ylabel('magnitude of tangential force (N)')
pl.title(d['info'])
if plot_force_field_flag:
plot_stiffness_field(k_cart_list[0],plottitle='start')
plot_stiffness_field(k_cart_list[-1],plottitle='end')
if expt_plot:
f = pl.gcf()
curr_size = f.get_size_inches()
f.set_size_inches(curr_size[0]*2,curr_size[1]*2)
str_parts = fname.split('.')
if d.has_key('strategy'):
fig_name = str_parts[0]+'_'+d['strategy']+'.png'
else:
fig_name = str_parts[0]+'_res.png'
f.savefig(fig_name)
if show_fig:
pl.show()
else:
print '################################'
print 'show_fig is FALSE'
if xyz_flag:
plot_cartesian(traj, xaxis=0,yaxis=1,zaxis=2)
mlab.show()
| [
[
1,
0,
0.0332,
0.0011,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0332,
0.0011,
0,
0.66,
0.0345,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0354,
0.0011,
0,
0.... | [
"import roslib; roslib.load_manifest('2009_humanoids_epc_pull')",
"import roslib; roslib.load_manifest('2009_humanoids_epc_pull')",
"import scipy.optimize as so",
"import math, numpy as np",
"import pylab as pl",
"import sys, optparse, time",
"import copy",
"from enthought.mayavi import mlab",
"impo... |
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Author: Advait Jain
import m3.toolbox as m3t
import hokuyo.hokuyo_scan as hs
import tilting_hokuyo.tilt_hokuyo_servo as ths
import mekabot.hrl_robot as hr
import hrl_lib.util as ut, hrl_lib.transforms as tr
import util as uto
import camera
import sys, time, os, optparse
import math, numpy as np
import copy
import arm_trajectories as at
from opencv.cv import *
from opencv.highgui import *
from threading import RLock
import threading
hook_3dprint_angle = math.radians(20-2.54)
class CompliantMotionGenerator(threading.Thread):
''' a specific form of compliant motion.
class name might be inappropriate.
'''
def __init__(self):
# stiffness in Nm/rad: [20,50,15,25]
self.settings_r = hr.MekaArmSettings(stiffness_list=[0.1939,0.6713,0.748,0.7272,0.8])
# self.settings_r = hr.MekaArmSettings(stiffness_list=[0.2,1.0,1.0,0.4,0.8])
self.settings_stiff = hr.MekaArmSettings(stiffness_list=[0.8,1.0,1.0,1.0,0.8])
self.firenze = hr.M3HrlRobot(connect=True,right_arm_settings=self.settings_stiff)
self.hok = hs.Hokuyo('utm',0,flip=True)
self.thok = ths.tilt_hokuyo('/dev/robot/servo0',5,self.hok,l1=0.,l2=-0.055)
self.cam = camera.Camera('mekabotUTM')
self.set_camera_settings()
self.fit_circle_lock = RLock()
threading.Thread.__init__(self)
def run(self):
self.circle_estimator()
def stop(self):
self.run_fit_circle_thread = False
self.firenze.stop()
## pose the arm by moving the end effector to the hookable location.
# @param hook_angle - RADIANS(0, -90, 90 etc.)
# 0 - horizontal, -pi/2 hook points up, +pi/2 hook points down
def pose_arm(self,hook_angle):
print 'press ENTER to pose the robot.'
k=m3t.get_keystroke()
if k!='\r':
print 'You did not press ENTER.'
return
# settings_r_orig = copy.copy(self.firenze.arm_settings['right_arm'])
settings_torque_gc = hr.MekaArmSettings(stiffness_list=[0.,0.,0.,0.,0.],control_mode='torque_gc')
self.firenze.set_arm_settings(settings_torque_gc,None)
self.firenze.step()
print 'hit ENTER to end posing, something else to exit'
k=m3t.get_keystroke()
p = self.firenze.end_effector_pos('right_arm')
q = self.firenze.get_joint_angles('right_arm')
# self.firenze.set_arm_settings(settings_r_orig,None)
self.firenze.set_arm_settings(self.settings_stiff,None)
self.firenze.set_joint_angles('right_arm',q)
self.firenze.step()
self.firenze.set_joint_angles('right_arm',q)
self.firenze.step()
rot_mat = tr.Rz(hook_angle-hook_3dprint_angle)*tr.Ry(math.radians(-90))
self.firenze.go_cartesian('right_arm',p,rot_mat,speed=0.1)
print 'hit ENTER after making finer adjustment, something else to exit'
k=m3t.get_keystroke()
p = self.firenze.end_effector_pos('right_arm')
q = self.firenze.get_joint_angles('right_arm')
self.firenze.set_joint_angles('right_arm',q)
self.firenze.step()
def set_camera_settings(self):
self.cam.set_frame_rate(30)
self.cam.set_auto()
self.cam.set_gamma(1)
self.cam.set_whitebalance(r_val=512,b_val=544)
def compliant_motion(self,equi_pt_generator,time_step,rapid_call_func=None):
''' equi_pt_generator: function that returns stop,q
q: list of 7 joint angles
stop: string which is '' for compliant motion to continue
rapid_call_func: called in the time between calls to the equi_pt_generator
can be used for logging, safety etc.
returns stop
stop: string which is '' for compliant motion to continue
time_step: time between successive calls to equi_pt_generator
returns stop (the string which has the reason why the compliant motion stopped.)
'''
stop,q = equi_pt_generator()
while stop == '':
self.firenze.set_joint_angles('right_arm',q)
t1 = time.time()
t_end = t1+time_step
while t1<t_end:
self.firenze.step()
if rapid_call_func != None:
stop = rapid_call_func()
if stop != '':
break
t1 = time.time()
if stop != '':
break
stop,q = equi_pt_generator()
return stop
## log the joint angles, equi pt joint angles and forces.
def log_state(self):
t_now = time.time()
q_now = self.firenze.get_joint_angles('right_arm')
qdot_now = self.firenze.get_joint_velocities('right_arm')
tau_now = self.firenze.get_joint_torques('right_arm')
self.jt_torque_trajectory.q_list.append(tau_now)
self.jt_torque_trajectory.time_list.append(t_now)
self.pull_trajectory.q_list.append(q_now)
self.pull_trajectory.qdot_list.append(qdot_now)
self.pull_trajectory.time_list.append(t_now)
#self.eq_pt_trajectory.p_list.append(self.eq_pt_cartesian.A1.tolist())
self.eq_pt_trajectory.q_list.append(self.q_guess) # see equi_pt_generator - q_guess is the config for the eq point.
self.eq_pt_trajectory.time_list.append(t_now)
wrist_force = self.firenze.get_wrist_force('right_arm',base_frame=True)
self.force_trajectory.f_list.append(wrist_force.A1.tolist())
self.force_trajectory.time_list.append(t_now)
def common_stopping_conditions(self):
stop = ''
if self.q_guess == None:
stop = 'IK fail'
wrist_force = self.firenze.get_wrist_force('right_arm',base_frame=True)
mag = np.linalg.norm(wrist_force)
if mag > self.eq_force_threshold:
stop = 'force exceed'
if mag < 1.2 and self.hooked_location_moved:
if (self.prev_force_mag - mag) > 10.:
stop = 'slip: force step decrease and below thresold.'
else:
self.slip_count += 1
else:
self.slip_count = 0
if self.slip_count == 4:
stop = 'slip: force below threshold for too long.'
curr_pos = self.firenze.FK('right_arm',self.pull_trajectory.q_list[-1])
if curr_pos[0,0]<0.27 and curr_pos[1,0]>-0.2:
stop = 'danger of self collision'
return stop
def update_eq_point(self,motion_vec,step_size):
next_pt = self.eq_pt_cartesian + step_size * motion_vec
rot_mat = self.eq_IK_rot_mat
# self.q_guess[1] += math.radians(1)
q_eq = self.firenze.IK('right_arm',next_pt,rot_mat,self.q_guess)
self.eq_pt_cartesian = next_pt
self.q_guess = q_eq
return q_eq
def circle_estimator(self):
self.run_fit_circle_thread = True
print 'Starting the circle estimating thread.'
while self.run_fit_circle_thread:
self.fit_circle_lock.acquire()
if len(self.cartesian_pts_list)==0:
self.fit_circle_lock.release()
continue
pts_2d = (np.matrix(self.cartesian_pts_list).T)[0:2,:]
self.fit_circle_lock.release()
rad = self.rad_guess
start_pos = self.firenze.FK('right_arm',self.pull_trajectory.q_list[0])
rad,cx,cy = at.fit_circle(rad,start_pos[0,0],start_pos[1,0]-rad,pts_2d,method='fmin_bfgs',verbose=False)
rad = ut.bound(rad,3.0,0.1)
self.fit_circle_lock.acquire()
self.cx = cx
self.cy = cy
# self.rad = rad
self.fit_circle_lock.release()
print 'Ended the circle estimating thread.'
## constantly update the estimate of the kinematics and move the
# equilibrium point along the tangent of the estimated arc, and
# try to keep the radial force constant.
def equi_pt_generator_control_radial_force(self):
self.log_state()
q_eq = self.update_eq_point(self.eq_motion_vec,0.01)
stop = self.common_stopping_conditions()
wrist_force = self.firenze.get_wrist_force('right_arm',base_frame=True)
mag = np.linalg.norm(wrist_force)
start_pos = self.firenze.FK('right_arm',self.pull_trajectory.q_list[0])
curr_pos = self.firenze.FK('right_arm',self.pull_trajectory.q_list[-1])
if (start_pos[0,0]-curr_pos[0,0])>0.09 and self.hooked_location_moved==False:
# change the force threshold once the hook has started pulling.
self.hooked_location_moved = True
self.eq_force_threshold = ut.bound(mag+30.,20.,80.)
self.piecewise_force_threshold = ut.bound(mag+5.,0.,80.)
self.fit_circle_lock.acquire()
self.cartesian_pts_list.append(curr_pos.A1.tolist())
self.fit_circle_lock.release()
# find tangential direction.
radial_vec = curr_pos[0:2]-np.matrix([self.cx,self.cy]).T
radial_vec = radial_vec/np.linalg.norm(radial_vec)
tan_x,tan_y = -radial_vec[1,0],radial_vec[0,0]
if tan_x >0.:
tan_x = -tan_x
tan_y = -tan_y
self.eq_motion_vec = np.matrix([tan_x,tan_y,0.]).T
f_vec = -1*np.array([wrist_force[0,0],wrist_force[1,0]])
f_rad_mag = np.dot(f_vec,radial_vec.A1)
#if f_rad_mag>10.:
if f_rad_mag>5.:
self.eq_motion_vec[0:2] -= radial_vec/2. * self.hook_maintain_dist_plane/0.05
else:
self.eq_motion_vec[0:2] += radial_vec/2. * self.hook_maintain_dist_plane/0.05
self.prev_force_mag = mag
return stop,q_eq
## moves eq point along the -x axis.
def equi_pt_generator_line(self):
self.log_state()
#q_eq = self.update_eq_point(self.eq_motion_vec,0.005)
q_eq = self.update_eq_point(self.eq_motion_vec,0.010)
stop = self.common_stopping_conditions()
wrist_force = self.firenze.get_wrist_force('right_arm',base_frame=True)
mag = np.linalg.norm(wrist_force)
start_pos = self.firenze.FK('right_arm',self.pull_trajectory.q_list[0])
curr_pos = self.firenze.FK('right_arm',self.pull_trajectory.q_list[-1])
if (start_pos[0,0]-curr_pos[0,0])>0.09 and self.hooked_location_moved==False:
# change the force threshold once the hook has started pulling.
self.hooked_location_moved = True
self.eq_force_threshold = ut.bound(mag+15.,20.,80.)
self.prev_force_mag = mag
return stop,q_eq
## move the end effector to properly hook onto the world
# direction of motion governed by the hook angle.
# @param hook_angle - angle of hook in RADIANS (see pose_arm or pull for details.)
def get_firm_hook(self, hook_angle):
rot_mat = tr.Rz(hook_angle-hook_3dprint_angle)*tr.Ry(math.radians(-90))
# move in the +x until contact.
vec = np.matrix([0.08,0.,0.]).T
self.firenze.move_till_hit('right_arm',vec=vec,force_threshold=2.0,rot=rot_mat,
speed=0.05)
# now move in direction of hook.
vec = tr.rotX(-hook_angle) * np.matrix([0.,0.05,0.]).T
self.firenze.move_till_hit('right_arm',vec=vec,force_threshold=5.0,rot=rot_mat,
speed=0.05,bias_FT=False)
self.firenze.set_arm_settings(self.settings_r,None)
self.firenze.step()
def pull(self,hook_angle,force_threshold,use_utm=False,use_camera=False,strategy='line_neg_x',
pull_loc=None, info_string=''):
''' force_threshold - max force at which to stop pulling.
hook_angle - radians(0, -90, 90 etc.)
0 - horizontal, -pi/2 hook points up, +pi/2 hook points down
use_utm - to take 3D scans or not.
use_camera - to take pictures from the camera or not.
strategy - 'line_neg_x': move eq point along -x axis.
'piecewise_linear': try and estimate circle and move along it.
'control_radial_force': try and keep the radial force constant
'control_radial_dist'
pull_loc - 3x1 np matrix of location for pulling. If None then arm will go into
gravity comp and user can show the location.
info_string - string saved with key 'info' in the pkl.
'''
if use_utm:
self.firenze.step()
armconfig1 = self.firenze.get_joint_angles('right_arm')
plist1,slist1 = self.scan_3d()
if use_camera:
cam_plist1, cam_imlist1 = self.image_region()
else:
cam_plist1,cam_imlist1 = None,None
rot_mat = tr.Rz(hook_angle-hook_3dprint_angle)*tr.Ry(math.radians(-90))
if pull_loc == None:
self.pose_arm(hook_angle)
pull_loc = self.firenze.end_effector_pos('right_arm')
ut.save_pickle(pull_loc,'pull_loc_'+info_string+'_'+ut.formatted_time()+'.pkl')
else:
pt1 = copy.copy(pull_loc)
pt1[0,0] = pt1[0,0]-0.1
print 'pt1:', pt1.A1
print 'pull_loc:', pull_loc.A1
self.firenze.go_cartesian('right_arm',pt1,rot_mat,speed=0.2)
self.firenze.go_cartesian('right_arm',pull_loc,rot_mat,speed=0.07)
print 'press ENTER to pull'
k=m3t.get_keystroke()
if k != '\r':
return
time_dict = {}
time_dict['before_hook'] = time.time()
print 'first getting a good hook'
self.get_firm_hook(hook_angle)
time.sleep(0.5)
time_dict['before_pull'] = time.time()
print 'pull begins'
stiffness_scale = self.settings_r.stiffness_scale
vec = tr.rotX(-hook_angle) * np.matrix([0.,0.05/stiffness_scale,0.]).T
self.keep_hook_vec = vec
self.hook_maintain_dist_plane = np.dot(vec.A1,np.array([0.,1.,0.]))
self.eq_pt_cartesian = self.firenze.end_effector_pos('right_arm') + vec
q_eq = self.firenze.IK('right_arm',self.eq_pt_cartesian,rot_mat)
self.firenze.go_jointangles('right_arm',q_eq,speed=math.radians(30))
self.q_guess = q_eq
# self.q_guess = self.firenze.get_joint_angles('right_arm')
self.pull_trajectory = at.JointTrajectory()
self.jt_torque_trajectory = at.JointTrajectory()
self.eq_pt_trajectory = at.JointTrajectory()
self.force_trajectory = at.ForceTrajectory()
self.firenze.step()
start_config = self.firenze.get_joint_angles('right_arm')
self.eq_IK_rot_mat = rot_mat # for equi pt generators.
self.eq_force_threshold = force_threshold
self.hooked_location_moved = False # flag to indicate when the hooking location started moving.
self.prev_force_mag = np.linalg.norm(self.firenze.get_wrist_force('right_arm'))
self.eq_motion_vec = np.matrix([-1.,0.,0.]).T
self.slip_count = 0
if strategy == 'line_neg_x':
result = self.compliant_motion(self.equi_pt_generator_line,0.025)
elif strategy == 'control_radial_force':
self.cartesian_pts_list = []
self.piecewise_force_threshold = force_threshold
self.rad_guess = 1.0
self.cx = 0.6
self.cy = -self.rad_guess
self.start() # start the circle estimation thread
result = self.compliant_motion(self.equi_pt_generator_control_radial_force,0.025)
else:
raise RuntimeError('unknown pull strategy: ', strategy)
if result == 'slip: force step decrease' or result == 'danger of self collision':
self.firenze.motors_off()
print 'powered off the motors.'
print 'Compliant motion result:', result
print 'Original force threshold:', force_threshold
print 'Adapted force threshold:', self.eq_force_threshold
time_dict['after_pull'] = time.time()
d = {'actual': self.pull_trajectory, 'eq_pt': self.eq_pt_trajectory,
'force': self.force_trajectory, 'torque': self.jt_torque_trajectory,
'stiffness': self.firenze.arm_settings['right_arm'],
'info': info_string, 'force_threshold': force_threshold,
'eq_force_threshold': self.eq_force_threshold, 'hook_angle':hook_angle,
'result':result,'strategy':strategy,'time_dict':time_dict}
self.firenze.step()
armconfig2 = self.firenze.get_joint_angles('right_arm')
if use_utm:
plist2,slist2 = self.scan_3d()
d['start_config']=start_config
d['armconfig1']=armconfig1
d['armconfig2']=armconfig2
d['l1'],d['l2']=0.,-0.055
d['scanlist1'],d['poslist1']=slist1,plist1
d['scanlist2'],d['poslist2']=slist2,plist2
d['cam_plist1']=cam_plist1
d['cam_imlist1']=cam_imlist1
ut.save_pickle(d,'pull_trajectories_'+d['info']+'_'+ut.formatted_time()+'.pkl')
def scan_3d(self):
tilt_angles = (math.radians(20),math.radians(70))
pos_list,scan_list = self.thok.scan(tilt_angles,speed=math.radians(10),save_scan=False)
return pos_list,scan_list
def save_frame(self):
cvim = self.cam.get_frame()
cvSaveImage('im_'+ut.formatted_time()+'.png',cvim)
def image_region(self):
''' takes images from the UTM camera at different angles.
returns list of servo angles, list of images.
images are numpy images. so that they can be pickled.
'''
im_list = []
p_list = []
for cmd_ang in [0,30,45]:
self.thok.servo.move_angle(math.radians(cmd_ang))
cvim = self.cam.get_frame()
cvim = self.cam.get_frame()
im_list.append(uto.cv2np(cvim,format='BGR'))
p_list.append(self.thok.servo.read_angle())
self.thok.servo.move_angle(math.radians(0))
return p_list,im_list
def test_IK(rot_mat):
''' try out the IK at a number of different cartesian
points in the workspace, with the given rotation
matrix for the end effector.
'''
print 'press ENTER to start.'
k=m3t.get_keystroke()
while k=='\r':
p = firenze.end_effector_pos('right_arm')
firenze.go_cartesian('right_arm',p,rot_mat,speed=0.1)
firenze.step()
print 'press ENTER to save joint angles.'
k=m3t.get_keystroke()
if k == '\r':
firenze.step()
q = firenze.get_joint_angles('right_arm')
ut.save_pickle(q,'arm_config_'+ut.formatted_time()+'.pkl')
print 'press ENTER for next IK test. something else to exit.'
k=m3t.get_keystroke()
def test_elbow_angle():
firenze = hr.M3HrlRobot(connect=False)
hook_3dprint_angle = math.radians(20-2.54)
rot_mat = tr.Rz(math.radians(-90.)-hook_3dprint_angle)*tr.Ry(math.radians(-90))
x_list = [0.55,0.45,0.35]
y = -0.2
z = -0.23
for x in x_list:
p0 = np.matrix([x,y,z]).T
q = firenze.IK('right_arm',p0,rot_mat)
# q[1] = math.radians(15)
# q = firenze.IK('right_arm',p0,rot_mat,q_guess = q)
elbow_angle = firenze.elbow_plane_angle('right_arm',q)
print '---------------------------------------'
print 'ee position:', p0.A1
# print 'joint angles:', q
print 'elbow_angle:', math.degrees(elbow_angle)
if __name__=='__main__':
p = optparse.OptionParser()
p.add_option('--ik_single_pos', action='store_true', dest='ik_single_pos',
help='test IK at a single position.')
p.add_option('--ik_test', action='store_true', dest='ik_test',
help='test IK in a loop.')
p.add_option('--pull', action='store_true', dest='pull',
help='pull with hook up (name will be changed later).')
p.add_option('--pull_pos', action='store', type='string', dest='pull_pos_pkl',
help='pkl file with 3D coord of point to start pulling at.', default='')
p.add_option('--firm_hook', action='store_true', dest='firm_hook',
help='test getting a firm hook on things.')
p.add_option('--scan', action='store_true', dest='scan',
help='take and save 3D scans. specify --pull also.')
p.add_option('--camera', action='store_true', dest='camera',
help='take and save images from UTM camera. specify --pull also.')
p.add_option('--ha', action='store', dest='ha',type='float',
default=None,help='hook angle (degrees).')
p.add_option('--ft', action='store', dest='ft',type='float',
default=None,help='force threshold (Newtons).')
p.add_option('--info', action='store', type='string', dest='info_string',
help='string to save in the pkl log.', default='')
p.add_option('--ve', action='store_true', dest='ve',
help='vary experiment. (vary stiffness settings and repeatedly pull)')
p.add_option('--eaf', action='store_true', dest='eaf',
help='test elbow angle finding with the horizontal plane.')
opt, args = p.parse_args()
ik_single_pos_flag = opt.ik_single_pos
test_ik_flag = opt.ik_test
pull_flag = opt.pull
pull_pos_pkl = opt.pull_pos_pkl
firm_hook_flag = opt.firm_hook
scan_flag = opt.scan
camera_flag = opt.camera
ha = opt.ha
ft = opt.ft
info_string = opt.info_string
vary_expt_flag = opt.ve
elbow_angle_flag = opt.eaf
try:
if vary_expt_flag:
stiff_scale_list = [1.0,1.2,0.8]
if pull_pos_pkl != '':
pull_loc = ut.load_pickle(pull_pos_pkl)
else:
raise RuntimeError('Need to specify a pull_pos with vary_expt')
cmg = CompliantMotionGenerator()
print 'hit a key to power up the arms.'
k=m3t.get_keystroke()
cmg.firenze.power_on()
#for strategy in ['line_neg_x','control_radial_force']:
for strategy in ['line_neg_x','control_radial_dist','control_radial_force']:
#for strategy in ['line_neg_x']:
#for strategy in ['piecewise_linear']:
for s_scale in stiff_scale_list:
cmg.settings_r.stiffness_scale = s_scale
cmg.pull(math.radians(ha), ft,use_utm=scan_flag,use_camera=camera_flag,
strategy=strategy,pull_loc=pull_loc,info_string=info_string)
cmg.firenze.maintain_configuration()
cmg.firenze.motors_on()
cmg.firenze.set_arm_settings(cmg.settings_stiff,None)
time.sleep(0.5)
print 'hit a key to end everything'
k=m3t.get_keystroke()
cmg.firenze.stop()
sys.exit()
if pull_flag or firm_hook_flag:
if ha == None:
print 'please specify hook angle (--ha)'
print 'Exiting...'
sys.exit()
if ft == None and pull_flag:
print 'please specify force threshold (--ft) along with --pull'
print 'Exiting...'
sys.exit()
cmg = CompliantMotionGenerator()
print 'hit a key to power up the arms.'
k=m3t.get_keystroke()
cmg.firenze.power_on()
if pull_flag:
if pull_pos_pkl != '':
pull_loc = ut.load_pickle(pull_pos_pkl)
else:
pull_loc = None
# cmg.pull(math.radians(ha), ft,use_utm=scan_flag,use_camera=camera_flag,
# strategy = 'control_radial_dist',pull_loc=pull_loc,info_string=info_string)
# cmg.pull(math.radians(ha), ft,use_utm=scan_flag,use_camera=camera_flag,
# strategy = 'piecewise_linear',pull_loc=pull_loc,info_string=info_string)
cmg.pull(math.radians(ha), ft,use_utm=scan_flag,use_camera=camera_flag,
strategy = 'control_radial_force',pull_loc=pull_loc,info_string=info_string)
# cmg.pull(math.radians(ha), ft,use_utm=scan_flag,use_camera=camera_flag,
# strategy = 'line_neg_x',pull_loc=pull_loc,info_string=info_string)
if firm_hook_flag:
hook_angle = math.radians(ha)
p = np.matrix([0.3,-0.25,-0.2]).T
rot_mat = tr.Rz(hook_angle-hook_3dprint_angle)*tr.Ry(math.radians(-90))
cmg.firenze.go_cartesian('right_arm',p,rot_mat,speed=0.1)
print 'hit a key to get a firm hook.'
k=m3t.get_keystroke()
cmg.get_firm_hook(hook_angle)
print 'hit a key to end everything'
k=m3t.get_keystroke()
cmg.stop()
# cmg = CompliantMotionGenerator()
# print 'hit a key to test IK'
# k=m3t.get_keystroke()
# cmg.get_firm_hook(ha)
#----------- non-class functions test --------------------
if elbow_angle_flag:
test_elbow_angle()
if ik_single_pos_flag or test_ik_flag:
if ha == None:
raise RuntimeError('You need to specify a hooking angle (--ha)')
settings_r = hr.MekaArmSettings(stiffness_list=[0.15,0.7,0.8,0.8,0.8])
firenze = hr.M3HrlRobot(connect=True,right_arm_settings=settings_r)
print 'hit a key to power up the arms.'
k=m3t.get_keystroke()
firenze.power_on()
print 'hit a key to test IK'
k=m3t.get_keystroke()
#p = np.matrix([0.26,-0.25,-0.25]).T
p = np.matrix([0.45,-0.2,-0.23]).T
rot_mat = tr.Rz(math.radians(ha)-hook_3dprint_angle)*tr.Ry(math.radians(-90))
#rot_mat = tr.Rz(math.radians(0))*tr.Ry(math.radians(-90))
firenze.go_cartesian('right_arm',p,rot_mat,speed=0.1)
if test_ik_flag:
rot_mat = tr.Rz(math.radians(-110))*tr.Ry(math.radians(-90))
#rot_mat = tr.Rz(math.radians(0))*tr.Ry(math.radians(-90))
test_IK(rot_mat)
print 'hit a key to end everything'
k=m3t.get_keystroke()
firenze.stop()
except (KeyboardInterrupt, SystemExit):
cmg.stop()
| [
[
1,
0,
0.0444,
0.0015,
0,
0.66,
0,
478,
0,
1,
0,
0,
478,
0,
0
],
[
1,
0,
0.0473,
0.0015,
0,
0.66,
0.0526,
464,
0,
1,
0,
0,
464,
0,
0
],
[
1,
0,
0.0488,
0.0015,
0,
... | [
"import m3.toolbox as m3t",
"import hokuyo.hokuyo_scan as hs",
"import tilting_hokuyo.tilt_hokuyo_servo as ths",
"import mekabot.hrl_robot as hr",
"import hrl_lib.util as ut, hrl_lib.transforms as tr",
"import util as uto",
"import camera",
"import sys, time, os, optparse",
"import math, numpy as np... |
import roslib
roslib.load_manifest("phantom_omni")
import rospy
import tf
import math
from geometry_msgs.msg import PoseStamped
import pdb
rospy.init_node("long_tip_pose_publisher")
pub = rospy.Publisher('pr2_right', PoseStamped)
r = rospy.Rate(60)
while not rospy.is_shutdown():
ps = PoseStamped()
ps.header.frame_id = 'omni1_link6'
ps.header.stamp = rospy.get_rostime()
ps.pose.position.x = -.134
ps.pose.position.y = 0
ps.pose.position.z = 0
q = tf.transformations.quaternion_from_euler(0, math.pi, 0)
ps.pose.orientation.x = q[0]
ps.pose.orientation.y = q[1]
ps.pose.orientation.z = q[2]
ps.pose.orientation.w = q[3]
pub.publish(ps)
r.sleep()
| [
[
1,
0,
0.0333,
0.0333,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0667,
0.0333,
0,
0.66,
0.1,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.1,
0.0333,
0,
0.66,
... | [
"import roslib",
"roslib.load_manifest(\"phantom_omni\")",
"import rospy",
"import tf",
"import math",
"from geometry_msgs.msg import PoseStamped",
"import pdb",
"rospy.init_node(\"long_tip_pose_publisher\")",
"pub = rospy.Publisher('pr2_right', PoseStamped)",
"r = rospy.Rate(60)",
"while not ro... |
import roslib
roslib.load_manifest("phantom_omni")
import rospy
import tf
import tf.transformations as tr
from geometry_msgs.msg import PoseStamped
from geometry_msgs.msg import Pose
from geometry_msgs.msg import Wrench
import math
import numpy as np
def tf2mat(tf_trans):
(trans, rot) = tf_trans
return np.matrix(tr.translation_matrix(trans)) * np.matrix(tr.quaternion_matrix(rot))
def mat2pose(m):
trans = tr.translation_from_matrix(m)
rot = tr.quaternion_from_matrix(m)
p = Pose()
p.position.x = trans[0]
p.position.y = trans[1]
p.position.z = trans[2]
p.orientation.x = rot[0]
p.orientation.y = rot[1]
p.orientation.z = rot[2]
p.orientation.w = rot[3]
return p
rospy.init_node("omni_potential_well")
wpub = rospy.Publisher('force_feedback', Wrench)
r = rospy.Rate(100)
listener = tf.TransformListener()
listener.waitForTransform("/world", "/omni1_link6", rospy.Time(), rospy.Duration(4.0))
listener.waitForTransform("/world", "/sensable", rospy.Time(), rospy.Duration(4.0))
print 'running.'
well_center = None
angle = 0.;
while not rospy.is_shutdown():
w_T_6 = tf2mat(listener.lookupTransform('/world', '/omni1_link6', rospy.Time(0)))
qm = np.matrix(tr.quaternion_matrix(tr.quaternion_from_euler(0, math.pi, 0)))
tm = np.matrix(tr.translation_matrix([-.134, 0, 0]))
tip_6 = tm * qm
tip_world = w_T_6 * tip_6
pos = np.matrix(tr.translation_from_matrix(tip_world)).T
force_world = (w_T_6[0:3,0:3] * np.matrix([-2., 0, 0]).T)
trans, rot = listener.lookupTransform('/sensable', '/world', rospy.Time(0))
quat_mat = np.matrix(tr.quaternion_matrix(rot))
force_sensable = quat_mat[0:3, 0:3] * force_world
wr = Wrench()
angle = np.radians(.3) + angle
wr.force.x = force_sensable[0]
wr.force.y = force_sensable[1]
wr.force.z = force_sensable[2]
print wr.force.z
wpub.publish(wr)
r.sleep()
#ps = PoseStamped()
#ps.header.frame_id = 'sensable'
#ps.header.stamp = rospy.get_rostime()
#ps.pose = mat2pose(tip_world)
#pub.publish(ps)
#print force_sensable.T
#if well_center == None:
# well_center = pos
#else:
# trans, rot = listener.lookupTransform('/world', '/sensable', rospy.Time(0))
# quat_mat = np.matrix(tr.quaternion_matrix(rot))
# dir = -(well_center - pos)
# mag = np.linalg.norm(dir)
# dir = dir / mag
# mag = np.min(mag*10., 5)
# print dir.T, mag
# force_world = dir * mag
# force_sensable = quat_mat[0:3, 0:3] * force_world
# wr = Wrench()
# wr.force.x = force_sensable[0]
# wr.force.y = force_sensable[1]
# wr.force.z = force_sensable[2]
# wpub.publish(wr)
#ps = PoseStamped()
#ps.header.frame_id = 'world'
#ps.header.stamp = rospy.get_rostime()
#ps.pose = mat2pose(tip_world)
#pub.publish(ps)
#r.sleep()
#Input force in link6's frame
#Output force in omni base frame
#wr = Wrench()
#wr.force.x = np.random.rand()*2 - 1
#wr.force.y = np.random.rand()*2 - 1
#wr.force.z = np.random.rand()*2 - 1
#wpub.publish(wr)
| [
[
1,
0,
0.0071,
0.0071,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0142,
0.0071,
0,
0.66,
0.0476,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0213,
0.0071,
0,
0.... | [
"import roslib",
"roslib.load_manifest(\"phantom_omni\")",
"import rospy",
"import tf",
"import tf.transformations as tr",
"from geometry_msgs.msg import PoseStamped",
"from geometry_msgs.msg import Pose",
"from geometry_msgs.msg import Wrench",
"import math",
"import numpy as np",
"def tf2mat(t... |
import roslib
roslib.load_manifest("phantom_omni")
import rospy
import tf
import tf.transformations as tr
from geometry_msgs.msg import PoseStamped
from geometry_msgs.msg import Pose
from geometry_msgs.msg import Wrench
import math
import numpy as np
def tf2mat(tf_trans):
(trans, rot) = tf_trans
return np.matrix(tr.translation_matrix(trans)) * np.matrix(tr.quaternion_matrix(rot))
def mat2pose(m):
trans = tr.translation_from_matrix(m)
rot = tr.quaternion_from_matrix(m)
p = Pose()
p.position.x = trans[0]
p.position.y = trans[1]
p.position.z = trans[2]
p.orientation.x = rot[0]
p.orientation.y = rot[1]
p.orientation.z = rot[2]
p.orientation.w = rot[3]
return p
rospy.init_node("omni_potential_well")
wpub = rospy.Publisher('force_feedback', Wrench)
r = rospy.Rate(1000)
#listener = tf.TransformListener()
#listener.waitForTransform("/world", "/omni1_link6", rospy.Time(), rospy.Duration(4.0))
#listener.waitForTransform("/world", "/sensable", rospy.Time(), rospy.Duration(4.0))
print 'running.'
well_center = None
angle = 0.;
while not rospy.is_shutdown():
#w_T_6 = tf2mat(listener.lookupTransform('/world', '/omni1_link6', rospy.Time(0)))
#qm = np.matrix(tr.quaternion_matrix(tr.quaternion_from_euler(0, math.pi, 0)))
#tm = np.matrix(tr.translation_matrix([-.134, 0, 0]))
#tip_6 = tm * qm
#tip_world = w_T_6 * tip_6
#pos = np.matrix(tr.translation_from_matrix(tip_world)).T
#force_world = (w_T_6[0:3,0:3] * np.matrix([-2., 0, 0]).T)
#trans, rot = listener.lookupTransform('/sensable', '/world', rospy.Time(0))
#quat_mat = np.matrix(tr.quaternion_matrix(rot))
#force_sensable = quat_mat[0:3, 0:3] * force_world
wr = Wrench()
angle = np.radians(.3) + angle
wr.force.x = 0#force_sensable[0]
wr.force.y = 0#force_sensable[1]
wr.force.z = np.sin(angle) * 3#force_sensable[2]
print wr.force.z
wpub.publish(wr)
r.sleep()
#ps = PoseStamped()
#ps.header.frame_id = 'sensable'
#ps.header.stamp = rospy.get_rostime()
#ps.pose = mat2pose(tip_world)
#pub.publish(ps)
#print force_sensable.T
#if well_center == None:
# well_center = pos
#else:
# trans, rot = listener.lookupTransform('/world', '/sensable', rospy.Time(0))
# quat_mat = np.matrix(tr.quaternion_matrix(rot))
# dir = -(well_center - pos)
# mag = np.linalg.norm(dir)
# dir = dir / mag
# mag = np.min(mag*10., 5)
# print dir.T, mag
# force_world = dir * mag
# force_sensable = quat_mat[0:3, 0:3] * force_world
# wr = Wrench()
# wr.force.x = force_sensable[0]
# wr.force.y = force_sensable[1]
# wr.force.z = force_sensable[2]
# wpub.publish(wr)
#ps = PoseStamped()
#ps.header.frame_id = 'world'
#ps.header.stamp = rospy.get_rostime()
#ps.pose = mat2pose(tip_world)
#pub.publish(ps)
#r.sleep()
#Input force in link6's frame
#Output force in omni base frame
#wr = Wrench()
#wr.force.x = np.random.rand()*2 - 1
#wr.force.y = np.random.rand()*2 - 1
#wr.force.z = np.random.rand()*2 - 1
#wpub.publish(wr)
| [
[
1,
0,
0.0059,
0.0059,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0118,
0.0059,
0,
0.66,
0.0556,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0178,
0.0059,
0,
0.... | [
"import roslib",
"roslib.load_manifest(\"phantom_omni\")",
"import rospy",
"import tf",
"import tf.transformations as tr",
"from geometry_msgs.msg import PoseStamped",
"from geometry_msgs.msg import Pose",
"from geometry_msgs.msg import Wrench",
"import math",
"import numpy as np",
"def tf2mat(t... |
import roslib
roslib.load_manifest("phantom_omni")
import rospy
import tf
import tf.transformations as tr
from geometry_msgs.msg import PoseStamped
from geometry_msgs.msg import Pose
from geometry_msgs.msg import Wrench
import math
import numpy as np
def tf2mat(tf_trans):
(trans, rot) = tf_trans
return np.matrix(tr.translation_matrix(trans)) * np.matrix(tr.quaternion_matrix(rot))
def mat2pose(m):
trans = tr.translation_from_matrix(m)
rot = tr.quaternion_from_matrix(m)
p = Pose()
p.position.x = trans[0]
p.position.y = trans[1]
p.position.z = trans[2]
p.orientation.x = rot[0]
p.orientation.y = rot[1]
p.orientation.z = rot[2]
p.orientation.w = rot[3]
return p
rospy.init_node("pr2_force_feedback")
pub = rospy.Publisher('pr2_master', PoseStamped)
wpub = rospy.Publisher('force_feedback', Wrench)
r = rospy.Rate(60)
listener = tf.TransformListener()
listener.waitForTransform("/world", "/omni1_link6", rospy.Time(), rospy.Duration(4.0))
print 'running.'
while not rospy.is_shutdown():
w_T_6 = tf2mat(listener.lookupTransform('/world', '/omni1_link6', rospy.Time(0)))
qm = np.matrix(tr.quaternion_matrix(tr.quaternion_from_euler(0, math.pi, 0)))
tm = np.matrix(tr.translation_matrix([-.134, 0, 0]))
tip_6 = tm * qm
tip_world = w_T_6 * tip_6
ps = PoseStamped()
ps.header.frame_id = 'world'
ps.header.stamp = rospy.get_rostime()
ps.pose = mat2pose(tip_world)
pub.publish(ps)
r.sleep()
#Input force in link6's frame
#Output force in omni base frame
#wr = Wrench()
#wr.force.x = np.random.rand()*2 - 1
#wr.force.y = np.random.rand()*2 - 1
#wr.force.z = np.random.rand()*2 - 1
#wpub.publish(wr)
wr = Wrench()
wr.force.x = 0
wr.force.y = 0
wr.force.z = 0
wpub.publish(wr)
| [
[
1,
0,
0.0147,
0.0147,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0294,
0.0147,
0,
0.66,
0.0526,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0441,
0.0147,
0,
0.... | [
"import roslib",
"roslib.load_manifest(\"phantom_omni\")",
"import rospy",
"import tf",
"import tf.transformations as tr",
"from geometry_msgs.msg import PoseStamped",
"from geometry_msgs.msg import Pose",
"from geometry_msgs.msg import Wrench",
"import math",
"import numpy as np",
"def tf2mat(t... |
import roslib
roslib.load_manifest("phantom_omni")
import rospy
import tf
import tf.transformations as tr
import hrl_lib.tf_utils as tfu
from geometry_msgs.msg import PoseStamped
from geometry_msgs.msg import Pose
from geometry_msgs.msg import Wrench
import math
import numpy as np
rospy.init_node("omni_potential_well")
wpub = rospy.Publisher('omni1_force_feedback', Wrench)
def pose_cb(ps):
m_f, frame = tfu.posestamped_as_matrix(ps)
m_o1 = tfu.transform('/omni1', frame, listener) * m_f
ee_point = np.matrix(tr.translation_from_matrix(m_o1)).T
center = np.matrix([-.10, 0, .30]).T
dif = 30*(center - ee_point)
#force_dir = dif / np.linalg.norm(dif)
force_o1 = dif #force_dir * np.sum(np.power(dif, 2))
force_s = tfu.transform('/omni1_sensable', '/omni1', listener) * np.row_stack((force_o1, np.matrix([1.])))
print np.linalg.norm(center - ee_point)
wr = Wrench()
wr.force.x = force_s[0]
wr.force.y = force_s[1]
wr.force.z = force_s[2]
wpub.publish(wr)
rospy.Subscriber('/omni1_pose', PoseStamped, pose_cb)
r = rospy.Rate(1)
listener = tf.TransformListener()
listener.waitForTransform("/omni1", "/omni1_sensable", rospy.Time(), rospy.Duration(4.0))
listener.waitForTransform("/omni1", "/omni1_link6", rospy.Time(), rospy.Duration(4.0))
print 'running.'
well_center = None
while not rospy.is_shutdown():
r.sleep()
#get current pose of the tip, subtract it from a center, rotate this into the sensable frame
#tip_omni1 = w_T_6 * tip_6
#force_omni1 = (w_T_6[0:3,0:3] * np.matrix([-2., 0, 0]).T)
#force_sensable = transform('/omni1_sensable', '/omni1', listener) * force_omni1
#wr = Wrench()
#wr.force.x = force_sensable[0]
#wr.force.y = force_sensable[1]
#wr.force.z = force_sensable[2]
#print wr.force.z
#wpub.publish(wr)
#qm = tfu.quaternion_from_matrix(tr.quaternion_from_euler(0, math.pi, 0))
#tm = tfu.translation_matrix([-.134, 0, 0])
#tip_6 = tm * qm
#tip_omni1 = w_T_6 * tip_6
#trans, rot = listener.lookupTransform('/omni1_sensable', '/omni1', rospy.Time(0))
#quat_mat = np.matrix(tr.quaternion_matrix(rot))
#force_sensable = quat_mat[0:3, 0:3] * force_omni1
#def tf2mat(tf_trans):
# (trans, rot) = tf_trans
# return np.matrix(tr.translation_matrix(trans)) * np.matrix(tr.quaternion_matrix(rot))
#def mat2pose(m):
# trans = tr.translation_from_matrix(m)
# rot = tr.quaternion_from_matrix(m)
# p = Pose()
# p.position.x = trans[0]
# p.position.y = trans[1]
# p.position.z = trans[2]
# p.orientation.x = rot[0]
# p.orientation.y = rot[1]
# p.orientation.z = rot[2]
# p.orientation.w = rot[3]
# return p
| [
[
1,
0,
0.009,
0.009,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.018,
0.009,
0,
0.66,
0.0476,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.027,
0.009,
0,
0.66,
... | [
"import roslib",
"roslib.load_manifest(\"phantom_omni\")",
"import rospy",
"import tf",
"import tf.transformations as tr",
"import hrl_lib.tf_utils as tfu",
"from geometry_msgs.msg import PoseStamped",
"from geometry_msgs.msg import Pose",
"from geometry_msgs.msg import Wrench",
"import math",
"... |
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import roslib; roslib.load_manifest('hrl_tilting_hokuyo')
from enthought.mayavi import mlab
import sys,os,time
import optparse
import hrl_lib.util as ut
import numpy as np, math
color_list = [(1.,1.,1.),(1.,0.,0.),(0.,1.,0.),(0.,0.,1.),(1.,1.,0.),(1.,0.,1.),\
(0.,1.,1.),(0.5,1.,0.5),(1.,0.5,0.5)]
##
# make a figure with a white background.
def white_bg():
mlab.figure(fgcolor = (0,0,0), bgcolor = (1,1,1))
##
# save plot as a png
# @param name - file name
# size - (r,c) e.g. (1024, 768)
def savefig(name, size):
mlab.savefig(name, size=size)
## plot 3D points connected to each other
#
# Check mlab.points3d documentation for details.
# @param pts - 3xN numpy matrix of points.
# @param color - 3 tuple of color. (float b/w 0 and 1)
# @param mode - how to display the points ('point','sphere','cube' etc.)
# @param scale_fator - controls size of the spheres. not sure what it means.
def plot(pts,color=(1.,1.,1.), scalar_list=None):
if scalar_list != None:
mlab.plot3d(pts[0,:].A1,pts[1,:].A1,pts[2,:].A1,scalar_list,
representation = 'wireframe', tube_radius = None)
mlab.colorbar()
else:
mlab.plot3d(pts[0,:].A1,pts[1,:].A1,pts[2,:].A1,color=color,
representation = 'wireframe', tube_radius = None)
## plot 3D points as a cloud.
#
# Check mlab.points3d documentation for details.
# @param pts - 3xN numpy matrix of points.
# @param color - 3 tuple of color. (float b/w 0 and 1)
# @param mode - how to display the points ('point','sphere','cube' etc.)
# @param scale_fator - controls size of the spheres. not sure what it means.
def plot_points(pts,color=(1.,1.,1.),mode='point',scale_factor=0.01,scalar_list=None):
if scalar_list != None:
mlab.points3d(pts[0,:].A1,pts[1,:].A1,pts[2,:].A1,scalar_list,mode=mode,scale_factor=scale_factor)
mlab.colorbar()
else:
mlab.points3d(pts[0,:].A1,pts[1,:].A1,pts[2,:].A1,mode=mode,color=color,scale_factor=scale_factor)
## Use mayavi2 to plot normals, and curvature of a point cloud.
# @param pts - 3xN np matrix
# @param normals - 3xN np matrix of surface normals at the points in pts.
# @param curvature - list of curvatures.
# @param mask_points - how many point to skip while drawint the normals
# @param color - of the arrows
# @param scale_factor - modulate size of arrows.
#
# Surface normals are plotted as arrows at the pts, curvature is colormapped and
# shown as spheres. The radius of the sphere also indicates the magnitude
# of the curvature. If curvature is None then it is not plotted. The pts
# are then displayed as pixels.
def plot_normals(pts, normals, curvature=None, mask_points=1,
color=(0.,1.,0.), scale_factor = 0.1):
x = pts[0,:].A1
y = pts[1,:].A1
z = pts[2,:].A1
u = normals[0,:].A1
v = normals[1,:].A1
w = normals[2,:].A1
if curvature != None:
curvature = np.array(curvature)
#idxs = np.where(curvature>0.03)
#mlab.points3d(x[idxs],y[idxs],z[idxs],curvature[idxs],mode='sphere',scale_factor=0.1,mask_points=1)
mlab.points3d(x,y,z,curvature,mode='sphere',scale_factor=0.1,mask_points=1, color=color)
# mlab.points3d(x,y,z,mode='point')
mlab.colorbar()
else:
mlab.points3d(x,y,z,mode='point')
mlab.quiver3d(x, y, z, u, v, w, mask_points=mask_points,
scale_factor=scale_factor, color=color)
# mlab.axes()
## Plot a yellow cuboid.
# cuboid is defined by 12 tuples of corners that define the 12 edges,
# as returned by occupancy_grig.grid_lines() function.
def plot_cuboid(corner_tups):
for tup in corner_tups:
p1 = tup[0]
p2 = tup[1]
mlab.plot3d([p1[0,0],p2[0,0]],[p1[1,0],p2[1,0]],
[p1[2,0],p2[2,0]],color=(1.,1.,0.),
representation='wireframe',tube_radius=None)
## show the plot.
# call this function after plotting everything.
def show():
mlab.show()
if __name__ == '__main__':
p = optparse.OptionParser()
p.add_option('-c', action='store', type='string', dest='pts_pkl',
help='pkl file with 3D points')
p.add_option('-f', action='store', type='string', dest='dict_pkl',
help='pkl file with 3D dict')
p.add_option('--save_cloud', action='store_true', dest='save_cloud',
help='pickle the point cloud (3xN matrix)')
p.add_option('--pan_angle', action='store', type='float',
dest='max_pan_angle', default=60.0,
help='angle in DEGREES. points b/w (-pan_angle and +pan_angle) are displayed. [default=60.]')
p.add_option('--max_dist', action='store', type='float',
dest='max_dist', default=3.0,
help='maximum distance (meters). Points further than this are discarded. [default=3.]')
opt, args = p.parse_args()
pts_pkl_fname = opt.pts_pkl
dict_pkl_fname = opt.dict_pkl
save_cloud_flag = opt.save_cloud
max_pan_angle = opt.max_pan_angle
max_dist = opt.max_dist
if pts_pkl_fname != None:
pts = ut.load_pickle(pts_pkl_fname)
elif dict_pkl_fname != None:
import tilting_hokuyo.processing_3d as p3d
dict = ut.load_pickle(dict_pkl_fname)
pts = p3d.generate_pointcloud(dict['pos_list'],dict['scan_list'],
math.radians(-max_pan_angle),
math.radians(max_pan_angle),
dict['l1'],dict['l2'],
min_tilt=math.radians(-90),max_tilt=math.radians(90))
else:
print 'Specify either a pts pkl or a dict pkl (-c or -f)'
print 'Exiting...'
sys.exit()
dist_mat = ut.norm(pts)
idxs = np.where(dist_mat<max_dist)[1]
print 'pts.shape', pts.shape
pts = pts[:,idxs.A1]
print 'pts.shape', pts.shape
if save_cloud_flag:
ut.save_pickle(pts,'numpy_pc_'+ut.formatted_time()+'.pkl')
plot_points(pts)
mlab.show()
| [
[
1,
0,
0.1562,
0.0052,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.1562,
0.0052,
0,
0.66,
0.0667,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.1667,
0.0052,
0,
0.... | [
"import roslib; roslib.load_manifest('hrl_tilting_hokuyo')",
"import roslib; roslib.load_manifest('hrl_tilting_hokuyo')",
"from enthought.mayavi import mlab",
"import sys,os,time",
"import optparse",
"import hrl_lib.util as ut",
"import numpy as np, math",
"color_list = [(1.,1.,1.),(1.,0.,0.),(0.,1.,0... |
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import roslib; roslib.load_manifest('hrl_tilting_hokuyo')
import time
import sys, optparse
import numpy as np, math
import hrl_lib.util as ut
import robotis.robotis_servo as rs
import hrl_hokuyo.hokuyo_scan as hs
class tilt_hokuyo():
def __init__(self, dev_name, servo_id, hokuyo, baudrate=57600, l1=0.,l2=0.035, camera_name=None):
''' dev_name - name of serial device of the servo controller (e.g. '/dev/robot/servo0')
servo_id - 2,3,4 ... (2 to 253)
hokuyo - Hokuyo object.
baudrate - for the servo controller.
camera_name - name of the
'''
self.servo = rs.robotis_servo(dev_name,servo_id,baudrate)
self.hokuyo = hokuyo
self.l1 = l1
self.l2 = l2
def scan(self, range, speed, save_scan=False,avg=1, _max_retries=0):
''' range - (start,end) in radians
speed - scan speed in radians/sec
save_scan - save a dict of pos_list,scan_list,l1,l2
avg - average scans from the hokuyo.
returns pos_list,scan_list. list of angles and HokuyoScans
'''
ramp_up_angle = math.radians(5)
if abs(range[0])+ramp_up_angle > math.radians(95) or \
abs(range[1])+ramp_up_angle > math.radians(95):
print 'tilt_hokuyo_servo.scan:bad angles- ',math.degrees(range[0]),math.degrees(range[1])
min_angle = min(range[0],range[1])
max_angle = max(range[0],range[1])
# if max_angle>math.radians(60.5):
# print 'tilt_hokuyo_servo.scan: maximum angle is too high, will graze bottom plate of mount. angle:', math.degrees(max_angle)
# sys.exit()
self.servo.move_angle(range[0]+np.sign(range[0])*ramp_up_angle)
# time.sleep(0.05)
# while(self.servo.is_moving()):
# continue
self.servo.move_angle(range[1]+np.sign(range[1])*ramp_up_angle,speed,blocking=False)
#self.servo.move_angle(range[1], speed)
time.sleep(0.05)
t1 = time.time()
pos_list = []
scan_list = []
while self.servo.is_moving():
pos = self.servo.read_angle()
#print 'h6', pos
if pos < min_angle or pos > max_angle:
continue
pos_list.append(pos)
plane_scan = self.hokuyo.get_scan(avoid_duplicate=True,remove_graze=True,avg=avg)
scan_list.append(plane_scan)
t2 = time.time()
self.servo.move_angle(0)
if save_scan:
date_name = ut.formatted_time()
dict = {'pos_list': pos_list,'scan_list': scan_list,
'l1': self.l1, 'l2': self.l2}
ut.save_pickle(dict,date_name+'_dict.pkl')
runtime = t2 - t1
expected_number_scans = 19.0 * runtime * (1.0/avg)
scan_threshold = expected_number_scans - expected_number_scans*.2
if len(scan_list) < scan_threshold:
print 'tilt_hokuyo_servo.scan: WARNING! Expected at least %d scans but got only %d scans.' % (expected_number_scans, len(scan_list))
print 'tilt_hokuyo_servo.scan: trying again.. retries:', _max_retries
if _max_retries > 0:
return self.scan(range, speed, save_scan, avg, _max_retries = _max_retries-1)
else:
print 'tilt_hokuyo_servo.scan: returning anyway'
print 'tilt_hokuyo_servo.scan: got %d scans over range %f with speed %f.' % (len(scan_list), (max_angle - min_angle), speed)
return pos_list,scan_list
def scan_around_pt(self,pt,speed=math.radians(5)):
''' pt - in thok coord frame.
this function scans in a fixed range.
returns pos_lit,scan_list
'''
ang1 = math.radians(40)
ang2 = math.radians(0)
tilt_angles = (ang1,ang2)
pos_list,scan_list = self.scan(tilt_angles,speed=speed)
return pos_list,scan_list
if __name__ == '__main__':
# urg mount - l1=0.06, l2=0.05
# utm - l1 = 0.0, l2 = 0.035
p = optparse.OptionParser()
p.add_option('-d', action='store', type='string', dest='servo_dev_name',
default='/dev/robot/servo0', help='servo device string. [default= /dev/robot/servo0]')
p.add_option('-t', action='store', type='string', dest='hokuyo_type',default='utm',
help='hokuyo_type. urg or utm [default=utm]')
p.add_option('-n', action='store', type='int', dest='hokuyo_number', default=0,
help='hokuyo number. 0,1,2 ... [default=0]')
p.add_option('--save_scan',action='store_true',dest='save_scan',
help='save the scan [dict and cloud]')
p.add_option('--speed', action='store', type='float', dest='scan_speed',
help='scan speed in deg/s.[default=5]',default=5.)
p.add_option('--ang0', action='store', type='float', dest='ang0',
help='starting tilt angle for scan (degrees). [default=20]', default=20.0)
p.add_option('--ang1', action='store', type='float', dest='ang1',
help='ending tilt angle for scan (degrees). default=[-20]', default=-20.0)
p.add_option('--id', action='store', type='int', dest='servo_id', default=2,
help='servo id 1,2 ... [default=2]')
p.add_option('--l2', action='store', type='float', dest='l2', help='l2 (in meters) [0.035 for ElE, -0.055 for mekabot]')
p.add_option('--flip', action='store_true', dest='flip',help='flip the hokuyo scan')
opt, args = p.parse_args()
hokuyo_type = opt.hokuyo_type
hokuyo_number = opt.hokuyo_number
servo_dev_name = opt.servo_dev_name
save_scan = opt.save_scan
scan_speed = math.radians(opt.scan_speed)
ang0 = opt.ang0
ang1 = opt.ang1
servo_id = opt.servo_id
l2 = opt.l2
if l2==None:
print 'please specify l2. do -h for details.'
print 'Exiting...'
sys.exit()
flip = opt.flip
if hokuyo_type == 'utm':
h = hs.Hokuyo('utm',hokuyo_number,flip=flip)
elif hokuyo_type == 'urg':
h = hs.Hokuyo('urg',hokuyo_number,flip=flip)
else:
print 'unknown hokuyo type: ', hokuyo_type
thok = tilt_hokuyo(servo_dev_name,servo_id,h,l1=0.,l2=l2)
tilt_angles = (math.radians(ang0),math.radians(ang1))
pos_list,scan_list = thok.scan(tilt_angles,speed=scan_speed,save_scan=save_scan)
sys.exit() # to kill the hokuyo thread.
| [
[
1,
0,
0.1571,
0.0052,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.1571,
0.0052,
0,
0.66,
0.1111,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.1675,
0.0052,
0,
0.... | [
"import roslib; roslib.load_manifest('hrl_tilting_hokuyo')",
"import roslib; roslib.load_manifest('hrl_tilting_hokuyo')",
"import time",
"import sys, optparse",
"import numpy as np, math",
"import hrl_lib.util as ut",
"import robotis.robotis_servo as rs",
"import hrl_hokuyo.hokuyo_scan as hs",
"clas... |
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import roslib; roslib.load_manifest('hrl_tilting_hokuyo')
import hrl_hokuyo.hokuyo_processing as hp
import sys, optparse, os
import hrl_lib.util as ut
import hrl_lib.transforms as tr
import numpy as np,math
import time
import display_3d_mayavi as d3m
import occupancy_grid_3d as og3d
import scipy.ndimage as ni
import copy
import pylab as pl
color_list = [(1.,1.,0),(1.,0,0),(0,1.,1.),(0,1.,0),(0,0,1.),(0,0.4,0.4),(0.4,0.4,0),
(0.4,0,0.4),(0.4,0.8,0.4),(0.8,0.4,0.4),(0.4,0.4,0.8),(0.4,0,0.8),(0,0.8,0.4),
(0,0.4,0.8),(0.8,0,0.4),(0.4,0,0.4),(1.,0.6,0.02) ]
#--------------------- utility functions -------------
##returns points that are within the cuboid formed by tlb and brf.
# @param pts - 3xN numpy matrix
# @param tlb, brf - 3x1 np matrix. bottom-right-front and top-left-back
# @return 3xM numpy matrix
def points_within_cuboid(pts,brf,tlb):
idx = np.where(np.min(np.multiply(pts>brf,pts<tlb),0))[1]
if idx.shape[1] == 0:
within_pts = np.empty((3,0))
else:
within_pts = pts[:,idx.A1.tolist()]
return within_pts
def generate_pointcloud(pos_list, scan_list, min_angle, max_angle, l1, l2,save_scan=False,
max_dist=np.Inf, min_dist=-np.Inf,min_tilt=-np.Inf,max_tilt=np.Inf, get_intensities=False, reject_zero_ten=True):
''' pos_list - list of motor positions (in steps)
scan_list - list of UrgScan objects at the corres positions.
l1,l2 - parameterizing the transformation (doc/ folder)
save_scan - pickle 3xN numpy matrix of points.
max_dist - ignore points at distance > max_dist
min_dist - ignore points at distance < max_dist
min_tilt, max_tilt - min and max tilt angles (radians)
+ve tilts the hokuyo down.
get_intensites - additionally return intensity values
returns 3xN numpy matrix of 3d coords of the points, returns (3xN, 1xN) including the intensity values if get_intensites=True
'''
t0 = time.time()
allpts = []
allintensities = []
pos_arr = np.array(pos_list)
scan_arr = np.array(scan_list)
idxs = np.where(np.multiply(pos_arr<=max_tilt,pos_arr>=min_tilt))
pos_list = pos_arr[idxs].tolist()
scan_list = scan_arr[idxs].tolist()
n_scans = len(scan_list)
if n_scans>1:
scan_list = copy.deepcopy(scan_list)
# remove graze in across scans.
ranges_mat = []
for s in scan_list:
ranges_mat.append(s.ranges.T)
ranges_mat = np.column_stack(ranges_mat)
start_index = hp.angle_to_index(scan_list[0],min_angle)
end_index = hp.angle_to_index(scan_list[0],max_angle)
for r in ranges_mat[start_index:end_index+1]:
hp.remove_graze_effect(r,np.matrix(pos_list),skip=1,graze_angle_threshold=math.radians(169.))
for i,s in enumerate(scan_list):
s.ranges = ranges_mat[:,i].T
for p,s in zip(pos_list,scan_list):
mapxydata = hp.get_xy_map(s,min_angle,max_angle,max_dist=max_dist,min_dist=min_dist,reject_zero_ten=reject_zero_ten,sigmoid_hack=True,get_intensities=get_intensities) # pts is 2xN
if get_intensities == True:
pts, intensities = mapxydata
allintensities.append(intensities)
else:
pts = mapxydata
pts = np.row_stack((pts,np.zeros(pts.shape[1]))) # pts is now 3xN
pts = tr.Ry(-p)*(pts+np.matrix((l1,0,-l2)).T)
allpts.append(pts)
allpts = np.column_stack(allpts)
if save_scan:
date_name = ut.formatted_time()
ut.save_pickle(allpts,date_name+'_cloud.pkl')
t1 = time.time()
# print 'Time to generate point cloud:', t1-t0
# allpts = tr.rotZ(math.radians(5))*allpts
if get_intensities == True:
allintensities = np.column_stack(allintensities)
return allpts, allintensities
else:
return allpts
#----------------------- navigation functions -----------------
def max_fwd_without_collision(all_pts,z_height,max_dist,display_list=None):
''' find the max distance that it is possible to move fwd by
without collision.
all_pts - 3xN matrix of 3D points in thok frame.
z - height of zenither while taking the scan.
max_dist - how far do I want to check for a possible collision.
returns max_dist that the thok can be moved fwd without collision.
'''
brf = np.matrix([0.2,-0.4,-z_height-0.1]).T
tlb = np.matrix([max_dist, 0.4,-z_height+1.8]).T
resolution = np.matrix([0.05,0.05,0.02]).T
gr = og3d.occupancy_grid_3d(brf,tlb,resolution)
gr.fill_grid(all_pts)
gr.to_binary(4)
ground_z = tr.thok0Tglobal(np.matrix([0,0,-z_height]).T)[2,0]
# gr.remove_horizontal_plane(hmax=ground_z+0.1)
gr.remove_horizontal_plane(extra_layers=2)
collide_pts = np.row_stack(np.where(gr.grid!=0))
x_coords = collide_pts[0]
# print x_coords
if x_coords.shape[0] == 0:
max_x = max_dist
# height_mat = np.arrary([np.Inf])
else:
max_x_gr = np.min(x_coords)
# height_mat = collide_pts[1,np.where(x_coords==max_x_gr)[0]]
# height_mat = height_mat*gr.resolution[2,0]+gr.brf[2,0]
max_x = max_x_gr*gr.resolution[0,0]+gr.brf[0,0]
if display_list != None:
collide_grid = gr.grid_to_points()
display_list.append(pu.PointCloud(all_pts,(200,200,200)))
display_list.append(pu.CubeCloud(collide_grid,(200,200,200),resolution))
display_list.append(pu.CubeCloud(np.matrix((max_x,0.,0.)).T,(0,0,200),size=np.matrix([0.05,.05,0.05]).T))
# return max_x,np.matrix(height_mat)
return max_x
def find_goto_point_surface_1(grid,pt,display_list=None):
''' returns p_erratic,p_edge,surface_height
p_erratic - point where the erratic's origin should go to. (in thok0 frame)
p_edge - point on the edge closest to pt.
p_erratic,p_edge are 3x1 matrices.
surface_height - in thok0 coord frame.
'''
pt_thok = pt
# everything is happening in the thok coord frame.
close_pt,approach_vector = find_approach_direction(grid,pt_thok,display_list)
if close_pt == None:
return None,None,None
# move perpendicular to approach direction.
# lam = -(close_pt[0:2,0].T*approach_vector)[0,0]
# lam = min(lam,-0.3) # atleast 0.3m from the edge.
lam = -0.4
goto_pt = close_pt[0:2,0] + lam*approach_vector # this is where I want the utm
# to be
err_to_thok = tr.erraticTglobal(tr.globalTthok0(np.matrix([0,0,0]).T))
goto_pt_erratic = -err_to_thok[0,0]*approach_vector + goto_pt # this is NOT
# general. It uses info about the two frames. If frames move, bad
# things can happen.
if display_list != None:
display_list.append(pu.CubeCloud(np.row_stack((goto_pt,close_pt[2,0])),color=(0,250,250), size=(0.012,0.012,0.012)))
display_list.append(pu.Line(np.row_stack((goto_pt,close_pt[2,0])).A1,close_pt.A1,color=(255,20,0)))
p_erratic = np.row_stack((goto_pt_erratic,np.matrix((close_pt[2,0]))))
print 'p_erratic in thok0:', p_erratic.T
return p_erratic,close_pt,close_pt[2,0]
#------------------ surface orientation ----------------
def find_closest_pt_index(pts2d,pt):
''' returns index (of pts2d) of closest point to pt.
pts2d - 2xN matrix, pt - 2x1 matrix
'''
pt_to_edge_dists = ut.norm(pts2d-pt)
closest_pt_index = np.argmin(pt_to_edge_dists)
return closest_pt_index
def find_closest_pt(pts2d,pt,pt_closer=False):
''' returns closest point to edge (2x1 matrix)
can return None also
'''
dist_pt = np.linalg.norm(pt[0:2,0])
pts2d_r = ut.norm(pts2d)
pts2d_a = np.arctan2(pts2d[1,:],pts2d[0,:])
if pt_closer == False:
k_idxs = np.where(pts2d_r<=dist_pt)
else:
k_idxs = np.where(pts2d_r>dist_pt)
pts2d_r = pts2d_r[k_idxs]
pts2d_a = pts2d_a[k_idxs]
pts2d = ut.cart_of_pol(np.matrix(np.row_stack((pts2d_r,pts2d_a))))
if pt_closer == False:
edge_to_pt = pt[0:2,0]-pts2d
else:
edge_to_pt = pts2d-pt[0:2,0]
edge_to_pt_a = np.arctan2(edge_to_pt[1,:],edge_to_pt[0,:])
keep_idxs = np.where(np.abs(edge_to_pt_a)<math.radians(70))[1].A1
if keep_idxs.shape[0] == 0:
return None
pts2d = pts2d[:,keep_idxs]
# pt_to_edge_dists = ut.norm(pts2d-pt[0:2,0])
# closest_pt_index = np.argmin(pt_to_edge_dists)
closest_pt_index = find_closest_pt_index(pts2d,pt[0:2,0])
closest_pt = pts2d[:,closest_pt_index]
return closest_pt
def pushback_edge(pts2d,pt):
''' push pt away from the edge defined by pts2d.
pt - 2x1, pts2d - 2xN
returns the pushed point.
'''
closest_idx = find_closest_pt_index(pts2d,pt)
n_push_points = min(min(5,pts2d.shape[1]-closest_idx-1),closest_idx)
if closest_idx<n_push_points or (pts2d.shape[1]-closest_idx-1)<n_push_points:
print 'processing_3d.pushback_edge: pt is too close to the ends of the pts2d array.'
return None
edge_to_pt = pt-pts2d[:,closest_idx-n_push_points:closest_idx+n_push_points]
edge_to_pt_r = ut.norm(edge_to_pt)
edge_to_pt_a = np.arctan2(edge_to_pt[1,:],edge_to_pt[0,:])
non_zero_idxs = np.where(edge_to_pt_r>0.005)
edge_to_pt_r = edge_to_pt_r[non_zero_idxs]
edge_to_pt_r[0,:] = 1
edge_to_pt_a = edge_to_pt_a[non_zero_idxs]
edge_to_pt_unit = ut.cart_of_pol(np.row_stack((edge_to_pt_r,edge_to_pt_a)))
push_vector = edge_to_pt_unit.mean(1)
push_vector = push_vector/np.linalg.norm(push_vector)
print 'push_vector:', push_vector.T
pt_pushed = pt + push_vector*0.05
return pt_pushed
## figure out a good direction to approach the surface.
# @param grid - occupancy grid (binary) around the point of interest.
# assumes that it has a surface.
# @param pt - 3d point which has to be approached.
# @param display_list - if display_list are lists then point clouds etc. are added
# for visualisation.
#
# @return - closest_pt,approach_vector.
def find_approach_direction(grid,pt,display_list=None):
z_plane,max_count = grid.argmax_z(search_up=True)
z_plane_meters = z_plane*grid.resolution[2,0]+grid.brf[2,0]
l = grid.find_plane_indices(assume_plane=True)
print '------------ min(l)',min(l)
z_plane_argmax,max_count = grid.argmax_z(search_up=False)
z_plane_below = max(0,z_plane_argmax-5)
print 'z_plane_argmax',z_plane_argmax
print 'z_plane_below',z_plane_below
print 'l:',l
# l = range(z_plane_below,z_plane)+l
copy_grid = copy.deepcopy(grid)
plane_slices = grid.grid[:,:,l]
copy_grid.grid[:,:,:] = 0
copy_grid.grid[:,:,l] = copy.copy(plane_slices)
#display_list.append(pu.PointCloud(copy_grid.grid_to_points(),color=(0,0,255)))
#plane_pts = copy_grid.grid_to_points()
grid_2d = np.max(grid.grid[:,:,l],2)
grid_2d = ni.binary_dilation(grid_2d,iterations=4) # I want 4-connectivity while filling holes.
grid_2d = ni.binary_fill_holes(grid_2d) # I want 4-connectivity while filling holes.
labeled_arr,n_labels = ni.label(grid_2d)
labels_list = range(1,n_labels+1)
count_objects = ni.sum(grid_2d,labeled_arr,labels_list)
if n_labels == 1:
count_objects = [count_objects]
max_label = np.argmax(np.matrix(count_objects))
grid_2d[np.where(labeled_arr!=max_label+1)] = 0
# connect_structure = np.empty((3,3),dtype='int')
# connect_structure[:,:] = 1
# eroded_2d = ni.binary_erosion(grid_2d,connect_structure,iterations=4)
# eroded_2d = ni.binary_erosion(grid_2d)
# grid_2d = grid_2d-eroded_2d
labeled_arr_3d = copy_grid.grid.swapaxes(2,0)
labeled_arr_3d = labeled_arr_3d.swapaxes(1,2)
labeled_arr_3d = labeled_arr_3d*grid_2d
labeled_arr_3d = labeled_arr_3d.swapaxes(2,0)
labeled_arr_3d = labeled_arr_3d.swapaxes(1,0)
copy_grid.grid = labeled_arr_3d
pts3d = copy_grid.grid_to_points()
pts2d = pts3d[0:2,:]
dist_pt = np.linalg.norm(pt[0:2,0])
pts2d_r = ut.norm(pts2d)
pts2d_a = np.arctan2(pts2d[1,:],pts2d[0,:])
max_angle = np.max(pts2d_a)
min_angle = np.min(pts2d_a)
max_angle = min(max_angle,math.radians(50))
min_angle = max(min_angle,math.radians(-50))
ang_res = math.radians(1.)
n_bins = int((max_angle-min_angle)/ang_res)
print 'n_bins:', n_bins
n_bins = min(50,n_bins)
# n_bins=50
ang_res = (max_angle-min_angle)/n_bins
print 'n_bins:', n_bins
angle_list = []
range_list = []
for i in range(n_bins):
angle = min_angle+ang_res*i
idxs = np.where(np.multiply(pts2d_a<(angle+ang_res/2.),pts2d_a>(angle-ang_res/2.)))
r_mat = pts2d_r[idxs]
a_mat = pts2d_a[idxs]
if r_mat.shape[1] == 0:
continue
min_idx = np.argmin(r_mat.A1)
range_list.append(r_mat[0,min_idx])
angle_list.append(a_mat[0,min_idx])
if range_list == []:
print 'processing_3d.find_approach_direction: No edge points found'
return None,None
pts2d = ut.cart_of_pol(np.matrix(np.row_stack((range_list,angle_list))))
closest_pt_1 = find_closest_pt(pts2d,pt,pt_closer=False)
if closest_pt_1 == None:
dist1 = np.Inf
else:
approach_vector_1 = pt[0:2,0] - closest_pt_1
dist1 = np.linalg.norm(approach_vector_1)
approach_vector_1 = approach_vector_1/dist1
closest_pt_2 = find_closest_pt(pts2d,pt,pt_closer=True)
if closest_pt_2 == None:
dist2 = np.Inf
else:
approach_vector_2 = closest_pt_2 - pt[0:2,0]
dist2 = np.linalg.norm(approach_vector_2)
approach_vector_2 = approach_vector_2/dist2
if dist1 == np.Inf and dist2 == np.Inf:
approach_vector_1 = np.matrix([1.,0.,0.]).T
approach_vector_2 = np.matrix([1.,0.,0.]).T
print 'VERY STRANGE: processing_3d.find_approach_direction: both distances are Inf'
if dist1<0.05 or dist2<0.05:
print 'dist1,dist2:',dist1,dist2
t_pt = copy.copy(pt)
if dist1<dist2 and dist1<0.02:
t_pt[0,0] += 0.05
elif dist2<0.02:
t_pt[0,0] -= 0.05
#pt_new = pushback_edge(pts2d,pt[0:2,0])
pt_new = pushback_edge(pts2d,t_pt[0:2,0])
if display_list != None:
pt_new_3d = np.row_stack((pt_new,np.matrix([z_plane_meters])))
display_list.append(pu.CubeCloud(pt_new_3d,color=(200,000,0),size=(0.009,0.009,0.009)))
closest_pt_1 = find_closest_pt(pts2d,pt_new,pt_closer=False)
if closest_pt_1 == None:
dist1 = np.Inf
else:
approach_vector_1 = pt_new - closest_pt_1
dist1 = np.linalg.norm(approach_vector_1)
approach_vector_1 = approach_vector_1/dist1
closest_pt_2 = find_closest_pt(pts2d,pt_new,pt_closer=True)
if closest_pt_2 == None:
dist2 = np.Inf
else:
approach_vector_2 = closest_pt_2 - pt_new
dist2 = np.linalg.norm(approach_vector_2)
approach_vector_2 = approach_vector_2/dist2
print '----------- dist1,dist2:',dist1,dist2
if dist2<dist1:
closest_pt = closest_pt_2
approach_vector = approach_vector_2
else:
closest_pt = closest_pt_1
approach_vector = approach_vector_1
print '----------- approach_vector:',approach_vector.T
closest_pt = np.row_stack((closest_pt,np.matrix([z_plane_meters])))
if display_list != None:
z = np.matrix(np.empty((1,pts2d.shape[1])))
z[:,:] = z_plane_meters
pts3d_front = np.row_stack((pts2d,z))
display_list.append(pu.CubeCloud(closest_pt,color=(255,255,0),size=(0.020,0.020,0.020)))
display_list.append(pu.CubeCloud(pts3d_front,color=(255,0,255),size=grid.resolution))
#display_list.append(pu.CubeCloud(pts3d,color=(0,255,0)))
return closest_pt,approach_vector
#------------------- for doors ---------------------
def vertical_plane_points(grid):
''' changes grid
'''
plane_indices,ver_plane_slice = grid.remove_vertical_plane()
grid.grid[:,:,:] = 0
grid.grid[plane_indices,:,:] = ver_plane_slice
## returns door handle points in the thok coord frame.
def find_door_handle(grid,pt,list = None,rotation_angle=math.radians(0.),
occupancy_threshold=None,resolution=None):
grid.remove_vertical_plane()
pts = grid.grid_to_points()
rot_mat = tr.Rz(rotation_angle)
t_pt = rot_mat*pt
brf = t_pt+np.matrix([-0.2,-0.3,-0.2]).T
tlb = t_pt+np.matrix([0.2, 0.3,0.2]).T
#resolution = np.matrix([0.02,0.0025,0.02]).T
grid = og3d.occupancy_grid_3d(brf,tlb,resolution,rotation_z=rotation_angle)
if pts.shape[1] == 0:
return None
grid.fill_grid(tr.Rz(rotation_angle)*pts)
grid.to_binary(occupancy_threshold)
labeled_arr,n_labels = grid.find_objects()
if list == None:
object_points_list = []
else:
object_points_list = list
for l in range(n_labels):
pts = grid.labeled_array_to_points(labeled_arr,l+1)
obj_height = np.max(pts[2,:])-np.min(pts[2,:])
print 'object_height:', obj_height
if obj_height > 0.1:
#remove the big objects
grid.grid[np.where(labeled_arr==l+1)] = 0
connect_structure = np.empty((3,3,3),dtype='int')
connect_structure[:,:,:] = 0
connect_structure[1,:,1] = 1
# dilate away - actual width of the door handle is not affected
# because that I will get from the actual point cloud!
grid.grid = ni.binary_dilation(grid.grid,connect_structure,iterations=7)
labeled_arr,n_labels = grid.find_objects()
for l in range(n_labels):
pts = grid.labeled_array_to_points(labeled_arr,l+1)
pts2d = pts[1:3,:] # only the y-z coordinates.
obj_width = (pts2d.max(1)-pts2d.min(1))[0,0]
print 'processing_3d.find_door_handle: object width = ', obj_width
if obj_width < 0.05:
continue
pts2d_zeromean = pts2d-pts2d.mean(1)
e_vals,e_vecs = np.linalg.eig(pts2d_zeromean*pts2d_zeromean.T)
max_index = np.argmax(e_vals)
max_evec = e_vecs[:,max_index]
ang = math.atan2(max_evec[1,0],max_evec[0,0])
print 'processing_3d.find_door_handle: ang = ', math.degrees(ang)
if (ang>math.radians(45) and ang<math.radians(135)) or \
(ang>math.radians(-135) and ang<math.radians(-45)):
# assumption is that door handles are horizontal.
continue
object_points_list.append(pts)
print 'processing_3d.find_door_handle: found %d objects'%(len(object_points_list))
closest_obj = find_closest_object(object_points_list,pt)
return closest_obj
#--------------------- segmentation ---------------------
def find_closest_object(obj_pts_list,pt,return_idx=False):
''' obj_pts_list - list of 3xNi matrices of points.
pt - point of interest. (3x1) matrix.
return_idx - whether to return the index (in obj_pts_list) of
the closest object.
returns 3xNj matrix of points which is the closest object to pt.
None if obj_pts_list is empty.
'''
min_dist_list = []
for obj_pts in obj_pts_list:
min_dist_list.append(np.min(ut.norm(obj_pts-pt)))
if obj_pts_list == []:
return None
min_idx = np.argmin(np.matrix(min_dist_list))
cl_obj = obj_pts_list[min_idx]
print 'processing_3d.find_closest_object: closest_object\'s centroid',cl_obj.mean(1).T
if return_idx:
return cl_obj,min_idx
return cl_obj
def segment_objects_points(grid,return_labels_list=False,
twod=False):
''' grid - binary occupancy grid.
returns list of 3xNi numpy matrices where Ni is the number of points
in the ith object. Point refers to center of the cell of occupancy grid.
return_labels_list - return a list of labels of the objects in
the grid.
returns None if there is no horizontal surface
'''
labeled_arr,n_labels = grid.segment_objects(twod=twod)
if n_labels == None:
# there is no surface, so segmentation does not make sense.
return None
object_points_list = []
labels_list = []
for l in range(n_labels):
pts = grid.labeled_array_to_points(labeled_arr,l+1)
pts_zeromean = pts-pts.mean(1)
e_vals,e_vecs = np.linalg.eig(pts_zeromean*pts_zeromean.T)
max_index = np.argmax(e_vals)
max_evec = e_vecs[:,max_index]
print 'max eigen vector:', max_evec.T
pts_1d = max_evec.T * pts
size = pts_1d.max() - pts_1d.min()
print 'size:', size
print 'n_points:', pts.shape[1]
ppsoe = pts.shape[1]/(e_vals[0]+e_vals[1]+e_vals[2])
print 'points per sum of eigenvalues:',ppsoe
# if ppsoe<5000:
# continue
if size<0.05 or size>0.5: #TODO - figure out a good threshold.
continue
object_points_list.append(pts)
labels_list.append(l+1)
if return_labels_list:
return object_points_list, labels_list
return object_points_list
def create_grid(brf,tlb,resolution,pos_list,scan_list,l1,l2,
display_flag=False,show_pts=True,rotation_angle=0.,
occupancy_threshold=1):
''' rotation angle - about the Z axis.
'''
max_dist = np.linalg.norm(tlb) + 0.2
min_dist = brf[0,0]
min_angle,max_angle=math.radians(-60),math.radians(60)
all_pts = generate_pointcloud(pos_list, scan_list, min_angle, max_angle, l1, l2,
max_dist=max_dist,min_dist=min_dist)
rot_mat = tr.Rz(rotation_angle)
all_pts_rot = rot_mat*all_pts
gr = og3d.occupancy_grid_3d(brf,tlb,resolution,rotation_z=rotation_angle)
gr.fill_grid(all_pts_rot)
gr.to_binary(occupancy_threshold)
if display_flag == True:
if show_pts:
d3m.plot_points(all_pts,color=(0.,0.,0.))
cube_tups = gr.grid_lines(rotation_angle=rotation_angle)
d3m.plot_cuboid(cube_tups)
return gr
def create_vertical_plane_grid(pt,pos_list,scan_list,l1,l2,rotation_angle,display_list=None):
rot_mat = tr.Rz(rotation_angle)
t_pt = rot_mat*pt
brf = t_pt+np.matrix([-0.2,-0.3,-0.2]).T
tlb = t_pt+np.matrix([0.2, 0.3,0.2]).T
resolution = np.matrix([0.005,0.02,0.02]).T
return create_grid(brf,tlb,resolution,pos_list,scan_list,l1,l2,display_list,rotation_angle=rotation_angle,occupancy_threshold=1)
def create_scooping_grid(pt,pos_list,scan_list,l1,l2,display_flag=False):
brf = pt+np.matrix([-0.15,-0.4,-0.2]).T
brf[0,0] = max(0.07,brf[0,0])
tlb = pt+np.matrix([0.25, 0.4,0.2]).T
resolution = np.matrix([0.01,0.01,0.0025]).T
return create_grid(brf,tlb,resolution,pos_list,scan_list,l1,l2,display_flag)
def create_segmentation_grid(pt,pos_list,scan_list,l1,l2,display_flag=False):
brf = pt+np.matrix([-0.15,-0.2,-0.2]).T
brf[0,0] = max(0.07,brf[0,0])
tlb = pt+np.matrix([0.25, 0.2,0.2]).T
# brf = np.matrix([0.05,-0.3,-0.2]).T
# tlb = np.matrix([0.5, 0.3,0.1]).T
# resolution = np.matrix([0.005,0.005,0.005]).T
# resolution = np.matrix([0.005,0.005,0.0025]).T
resolution = np.matrix([0.01,0.01,0.0025]).T
# resolution = np.matrix([0.01,0.01,0.001]).T
return create_grid(brf,tlb,resolution,pos_list,scan_list,l1,l2,display_flag)
def create_approach_grid(pt,pos_list,scan_list,l1,l2,display_list=None,show_pts=True):
brf = pt + np.matrix([-0.5,-0.2,-0.3]).T
brf[0,0] = max(0.10,brf[0,0])
tlb = pt + np.matrix([0.3, 0.2,0.2]).T
# resolution = np.matrix([0.005,0.005,0.005]).T
resolution = np.matrix([0.01,0.01,0.0025]).T
# resolution = np.matrix([0.01,0.01,0.001]).T
return create_grid(brf,tlb,resolution,pos_list,scan_list,l1,l2,display_list,show_pts)
def create_overhead_grasp_choice_grid(pt,pos_list,scan_list,l1,l2,far_dist,display_list=None):
# y_pos = max(pt[1,0]+0.1,0.1)
# y_neg = min(pt[1,0]-0.1,-0.1)
#
# brf = np.matrix([0.2,y_neg,0.0]).T
# tlb = np.matrix([pt[0,0]+far_dist,y_pos,pt[2,0]+0.75]).T
#
# resolution = np.matrix([0.02,0.02,0.02]).T
y_pos = 0.1
y_neg = -0.1
r = np.linalg.norm(pt[0:2,0])
brf = np.matrix([0.25,y_neg,0.0]).T
tlb = np.matrix([r+far_dist,y_pos,pt[2,0]+0.75]).T
resolution = np.matrix([0.02,0.02,0.02]).T
rotation_angle = math.atan2(pt[1,0],pt[0,0])
print 'rotation_angle:', math.degrees(rotation_angle)
gr = create_grid(brf,tlb,resolution,pos_list,scan_list,l1,l2,display_list,rotation_angle=rotation_angle)
if display_list != None:
collide_pts = gr.grid_to_points()
if collide_pts.shape[1] > 0:
collide_pts = tr.Rz(rotation_angle).T*gr.grid_to_points()
display_list.insert(0,pu.PointCloud(collide_pts,color=(0,0,0)))
return gr
def overhead_grasp_collision(pt,grid):
print 'collision points:', grid.grid.sum()
if grid.grid.sum()>15:
return True
else:
return False
def grasp_location_on_object(obj,display_list=None):
''' obj - 3xN numpy matrix of points of the object.
'''
pts_2d = obj[0:2,:]
centroid_2d = pts_2d.mean(1)
pts_2d_zeromean = pts_2d-centroid_2d
e_vals,e_vecs = np.linalg.eig(pts_2d_zeromean*pts_2d_zeromean.T)
# get the min size
min_index = np.argmin(e_vals)
min_evec = e_vecs[:,min_index]
print 'min eigenvector:', min_evec.T
pts_1d = min_evec.T * pts_2d
min_size = pts_1d.max() - pts_1d.min()
print 'spread along min eigenvector:', min_size
max_height = obj[2,:].max()
tlb = obj.max(1)
brf = obj.min(1)
print 'tlb:', tlb.T
print 'brf:', brf.T
resolution = np.matrix([0.005,0.005,0.005]).T
gr = og3d.occupancy_grid_3d(brf,tlb,resolution)
gr.fill_grid(obj)
gr.to_binary(1)
obj = gr.grid_to_points()
grid_2d = gr.grid.max(2)
grid_2d_filled = ni.binary_fill_holes(grid_2d)
gr.grid[:,:,0] = gr.grid[:,:,0]+grid_2d_filled-grid_2d
p = np.matrix(np.row_stack(np.where(grid_2d_filled==1))).astype('float')
p[0,:] = p[0,:]*gr.resolution[0,0]
p[1,:] = p[1,:]*gr.resolution[1,0]
p += gr.brf[0:2,0]
print 'new mean:', p.mean(1).T
print 'centroid_2d:', centroid_2d.T
centroid_2d = p.mean(1)
if min_size<0.12:
# grasp at centroid.
grasp_point = np.row_stack((centroid_2d,np.matrix([max_height+gr.resolution[2,0]*2])))
# grasp_point[2,0] = max_height
gripper_angle = -math.atan2(-min_evec[0,0],min_evec[1,0])
grasp_vec = min_evec
if display_list != None:
max_index = np.argmax(e_vals)
max_evec = e_vecs[:,max_index]
pts_1d = max_evec.T * pts_2d
max_size = pts_1d.max() - pts_1d.min()
v = np.row_stack((max_evec,np.matrix([0.])))
max_end_pt1 = grasp_point + v*max_size/2.
max_end_pt2 = grasp_point - v*max_size/2.
display_list.append(pu.Line(max_end_pt1,max_end_pt2,color=(0,0,0)))
else:
#----- more complicated grasping location finder.
for i in range(gr.grid_shape[2,0]):
gr.grid[:,:,i] = gr.grid[:,:,i]*(i+1)
height_map = gr.grid.max(2) * gr.resolution[2,0]
# print height_map
print 'height std deviation:',math.sqrt(height_map[np.where(height_map>0.)].var())
# connect_structure = np.empty((3,3),dtype='int')
# connect_structure[:,:] = 1
# for i in range(gr.grid_shape[2,0]):
# slice = gr.grid[:,:,i]
# slice_filled = ni.binary_fill_holes(slice)
# slice_edge = slice_filled - ni.binary_erosion(slice_filled,connect_structure)
# gr.grid[:,:,i] = slice_edge*(i+1)
#
# height_map = gr.grid.max(2) * gr.resolution[2,0]
# # print height_map
# print 'contoured height std deviation:',math.sqrt(height_map[np.where(height_map>0.)].var())
#
high_pts_2d = obj[0:2,np.where(obj[2,:]>max_height-0.005)[1].A1]
#high_pts_1d = min_evec.T * high_pts_2d
high_pts_1d = ut.norm(high_pts_2d)
idx1 = np.argmin(high_pts_1d)
pt1 = high_pts_2d[:,idx1]
idx2 = np.argmax(high_pts_1d)
pt2 = high_pts_2d[:,idx2]
if np.linalg.norm(pt1)<np.linalg.norm(pt2):
grasp_point = np.row_stack((pt1,np.matrix([max_height])))
else:
grasp_point = np.row_stack((pt2,np.matrix([max_height])))
vec = centroid_2d-grasp_point[0:2,0]
gripper_angle = -math.atan2(-vec[0,0],vec[1,0])
grasp_vec = vec/np.linalg.norm(vec)
if display_list != None:
pt1 = np.row_stack((pt1,np.matrix([max_height])))
pt2 = np.row_stack((pt2,np.matrix([max_height])))
# display_list.insert(0,pu.CubeCloud(pt1,(0,0,200),size=(0.005,0.005,0.005)))
# display_list.insert(0,pu.CubeCloud(pt2,(200,0,200),size=(0.005,0.005,0.005)))
if display_list != None:
pts = gr.grid_to_points()
size = resolution
# size = resolution*2
# size[2,0] = size[2,0]*2
#display_list.insert(0,pu.PointCloud(pts,(200,0,0)))
display_list.append(pu.CubeCloud(pts,color=(200,0,0),size=size))
display_list.append(pu.CubeCloud(grasp_point,(0,200,200),size=(0.007,0.007,0.007)))
v = np.row_stack((grasp_vec,np.matrix([0.])))
min_end_pt1 = grasp_point + v*min_size/2.
min_end_pt2 = grasp_point - v*min_size/2.
max_evec = np.matrix((min_evec[1,0],-min_evec[0,0])).T
pts_1d = max_evec.T * pts_2d
max_size = pts_1d.max() - pts_1d.min()
display_list.append(pu.Line(min_end_pt1,min_end_pt2,color=(0,255,0)))
return grasp_point,gripper_angle
#---------------------- testing functions -------------------
def test_vertical_plane_finding():
display_list = []
rot_angle = dict['rot_angle']
gr = create_vertical_plane_grid(pt,pos_list,scan_list,l1,l2,rotation_angle=rot_angle,
display_list=display_list)
vertical_plane_points(gr)
plane_cloud = pu.PointCloud(gr.grid_to_points(),color=(0,150,0))
display_list.insert(0,plane_cloud)
po3d.run(display_list)
def test_find_door_handle():
display_list = []
rot_angle = dict['rot_angle']
# pt[2,0] += 0.15
print 'pt:',pt.A1.tolist()
gr = create_vertical_plane_grid(pt,pos_list,scan_list,l1,l2,rotation_angle=rot_angle,
display_list=display_list)
grid_pts_cloud = pu.PointCloud(gr.grid_to_points(),(0,0,255))
display_list.insert(0,grid_pts_cloud)
copy_gr = copy.deepcopy(gr)
obj_pts_list = []
print 'pt:',pt.A1.tolist()
# Do I want to change the occupancy threshold when I'm closer? (see the old function test_find_door_handle_close)
handle_object = find_door_handle(gr,pt,obj_pts_list,rotation_angle=rot_angle,
occupancy_threshold=1,resolution=np.matrix([0.02,0.0025,0.02]).T)
copy_gr.remove_vertical_plane()
stickout_pts_cloud = pu.PointCloud(copy_gr.grid_to_points(),(100,100,100))
display_list.insert(0,stickout_pts_cloud)
for i,obj_pts in enumerate(obj_pts_list):
print 'mean:', obj_pts.mean(1).A1.tolist()
size = [0.02,0.0025,0.02] # look at param for find_door_handle
# size=gr.resolution.A1.tolist()
size[0] = size[0]*2
size[1] = size[1]*2
# size[2] = size[2]*2
display_list.append(pu.CubeCloud(obj_pts,color=color_list[i%len(color_list)],size=size))
laser_point_cloud = pu.CubeCloud(pt,color=(0,200,0),size=(0.005,0.005,0.005))
po3d.run(display_list)
#po3d.save(display_list, raw_name+'.png')
def test_segmentation():
gr = create_segmentation_grid(pt,pos_list,scan_list,l1,l2,
display_flag=True)
obj_pts_list = segment_objects_points(gr)
if obj_pts_list == None:
print 'There is no plane'
obj_pts_list = []
pts = gr.grid_to_points()
d3m.plot_points(pts,color=(1.,1.,1.))
d3m.plot_points(pt,color=(0,1,0.),mode='sphere')
for i,obj_pts in enumerate(obj_pts_list):
size=gr.resolution.A1.tolist()
size[2] = size[2]*2
d3m.plot_points(obj_pts,color=color_list[i%len(color_list)])
# display_list.append(pu.CubeCloud(obj_pts,color=color_list[i%len(color_list)],size=size))
#display_list.insert(0,pu.PointCloud(obj_pts,color=color_list[i%len(color_list)]))
print 'mean:', obj_pts.mean(1).T
d3m.show()
def test_grasp_location_on_object():
display_list = []
# display_list = None
gr = create_segmentation_grid(pt,pos_list,scan_list,l1,l2,display_list=display_list)
obj_pts_list = segment_objects_points(gr)
closest_obj = find_closest_object(obj_pts_list,pt)
grasp_location_on_object(closest_obj,display_list)
po3d.run(display_list)
def test_plane_finding():
''' visualize plane finding.
'''
# brf = pt + np.matrix([-0.4,-0.2,-0.3]).T
# brf[0,0] = max(brf[0,0],0.05)
# print 'brf:', brf.T
#
# tlb = pt + np.matrix([0.3, 0.2,0.3]).T
# resolution = np.matrix([0.01,0.01,0.0025]).T
brf = pt+np.matrix([-0.15,-0.25,-0.2]).T
brf[0,0] = max(0.07,brf[0,0])
tlb = pt+np.matrix([0.25, 0.25,0.2]).T
resolution = np.matrix([0.01,0.01,0.0025]).T
max_dist = np.linalg.norm(tlb) + 0.2
min_dist = brf[0,0]
all_pts = generate_pointcloud(pos_list, scan_list, min_angle, max_angle, l1, l2,save_scan=False,
max_dist=max_dist,min_dist=min_dist)
#max_dist=2.0,min_dist=min_dist)
gr = og3d.occupancy_grid_3d(brf,tlb,resolution)
gr.fill_grid(all_pts)
gr.to_binary(1)
l = gr.find_plane_indices(assume_plane=True)
z_min = min(l)*gr.resolution[2,0]+gr.brf[2,0]
z_max = max(l)*gr.resolution[2,0]+gr.brf[2,0]
print 'height of plane:', (z_max+z_min)/2
pts = gr.grid_to_points()
plane_pts_bool = np.multiply(pts[2,:]>=z_min,pts[2,:]<=z_max)
plane_pts = pts[:,np.where(plane_pts_bool)[1].A1.tolist()]
above_pts =pts[:,np.where(pts[2,:]>z_max)[1].A1.tolist()]
below_pts =pts[:,np.where(pts[2,:]<z_min)[1].A1.tolist()]
d3m.plot_points(pt,color=(0,1,0.),mode='sphere')
d3m.plot_points(plane_pts,color=(0,0,1.))
d3m.plot_points(above_pts,color=(1.0,1.0,1.0))
d3m.plot_points(below_pts,color=(1.,0.,0.))
cube_tups = gr.grid_lines()
d3m.plot_cuboid(cube_tups)
d3m.show()
def test_approach():
display_list=[]
# gr = create_approach_grid(pt,pos_list,scan_list,l1,l2,display_list=display_list,show_pts=False)
gr = create_approach_grid(pt,pos_list,scan_list,l1,l2,display_list=display_list,show_pts=True)
t0 = time.time()
p_erratic,p_edge,h = find_goto_point_surface_1(gr,pt,display_list)
t1 = time.time()
print 'aaaaaaaaaaaaaah:', t1-t0
l = gr.find_plane_indices(assume_plane=True)
z_min = min(l)*gr.resolution[2,0]+gr.brf[2,0]
z_max = max(l)*gr.resolution[2,0]+gr.brf[2,0]
print 'height of plane:', (z_max+z_min)/2
print 'height of surface in thok0 coord frame:', h
print 'p_erratic in thok0:', p_erratic.T
display_list.append(pu.CubeCloud(pt,color=(0,255,0),size=(0.018,0.018,0.018)))
# display_list.append(pu.CubeCloud(p_erratic,color=(0,250,250),size=(0.007,0.007,0.007)))
display_list.insert(0,pu.PointCloud(gr.grid_to_points(),color=(100,100,100)))
po3d.run(display_list)
def test_max_forward():
max_dist = math.sqrt(pt[0,0]**2+pt[1,0]**2+2.0**1) + 0.3
# max_dist = np.linalg.norm(pt[0:2]+0.3)
min_angle,max_angle=math.radians(-40),math.radians(40)
all_pts = generate_pointcloud(pos_list, scan_list, min_angle, max_angle, l1, l2, max_dist=max_dist,
min_tilt=math.radians(-90))
display_list = []
max_x = max_fwd_without_collision(all_pts,0.20,max_dist,display_list)
po3d.run(display_list)
# print 'height_mat:', height_mat
print 'max_x:', max_x
dict = {'pos_list':pos_list, 'scan_list':scan_list,'l1':l1, 'l2':l2, 'pt':pt}
# ut.save_pickle(dict,ut.formatted_time()+'_fwd_dict.pkl')
def test_choose_grasp_strategy():
display_list = []
far_dist = 0.15
pt[1,0] += 0.0
gr = create_overhead_grasp_choice_grid(pt,pos_list,scan_list,l1,l2,far_dist,display_list)
print 'overhead collide?',overhead_grasp_collision(pt,gr)
display_list.append(pu.CubeCloud(pt,color=(0,200,0),size=(0.005,0.005,0.005)))
# pts = generate_pointcloud(pos_list, scan_list, min_angle, max_angle, l1, l2,save_scan=False,
# #max_dist=max_dist,min_dist=min_dist)
# max_dist=2.0,min_dist=0.1)
# display_list.append(pu.PointCloud(pts,color=(100,100,100)))
po3d.run(display_list)
def test_different_surfaces():
display_list = []
# all_pts = generate_pointcloud(pos_list, scan_list, math.radians(-40), math.radians(40), l1, l2,save_scan=False,
# max_dist=np.Inf, min_dist=-np.Inf,min_tilt=-np.Inf,max_tilt=np.Inf)
## pts = all_pts[:,np.where(np.multiply(all_pts[0,:]>0.1,all_pts[0,:]<0.4))[1].A1]
## pts = pts[:,np.where(np.multiply(pts[1,:]<0.3,pts[1,:]>-0.3))[1].A1]
## pts = pts[:,np.where(pts[2,:]>-0.2)[1].A1]
## display_list.append(pu.PointCloud(pts,color=(0,200,0)))
# display_list.append(pu.PointCloud(all_pts,color=(200,0,0)))
#
# brf = np.matrix([0.05,-0.35,-0.2]).T
# tlb = np.matrix([0.5, 0.35,0.0]).T
# resolution = np.matrix([0.01,0.01,0.0025]).T
# gr = og3d.occupancy_grid_3d(brf,tlb,resolution)
# gr.fill_grid(all_pts)
# gr.to_binary(1)
# gr = create_segmentation_grid(pt,pos_list,scan_list,l1,l2,display_list)
gr = create_approach_grid(pt,pos_list,scan_list,l1,l2,display_list)
l = gr.find_plane_indices(assume_plane=True)
max_index = min(max(l)+5,gr.grid_shape[2,0]-1)
min_index = max(min(l)-5,0)
l = range(min_index,max_index+1)
n_points_list = []
height_list = []
for idx in l:
n_points_list.append(gr.grid[:,:,idx].sum())
height_list.append(idx*gr.resolution[2,0]+gr.brf[2,0])
pl.bar(height_list,n_points_list,width=gr.resolution[2,0],linewidth=0,align='center',color='y')
max_occ = max(n_points_list)
thresh = max_occ/5
xmin,xmax = pl.xlim()
t = pl.axis()
t = (xmin+0.0017,xmax-0.001,t[2],t[3]+50)
# pl.plot([height_list[0],height_list[-1]],[thresh,thresh],c='r')
pl.plot([xmin,xmax],[thresh,thresh],c='b')
pl.title('Histogram of number of points vs z-coordinate of points')
pl.xlabel('z-coordinate (relative to the laser range finder) (meters)')
pl.ylabel('Number of points')
pl.axis(t)
pl.savefig(pkl_file_name+'.png')
# pl.show()
# print 'Mean:', pts.mean(1).T
# pts_zeromean = pts-pts.mean(1)
# n_points = pts.shape[1]
# print 'n_points:', n_points
# e_vals,e_vecs = np.linalg.eig(pts_zeromean*pts_zeromean.T/n_points)
#
# min_index = np.argmin(e_vals)
# min_evec = e_vecs[:,min_index]
# print 'min eigenvector:', min_evec.T
# print 'min eigenvalue:', e_vals[min_index]
# pts_1d = min_evec.T * pts
# size = pts_1d.max() - pts_1d.min()
# print 'spread along min eigenvector:', size
# po3d.run(display_list)
def test_occ_grid():
gr = create_approach_grid(pt,pos_list,scan_list,l1,l2,display_list=None,show_pts=True)
pts = gr.grid_to_points()
display_list=[]
display_list.append(pu.CubeCloud(pt,color=(0,255,0),size=(0.007,0.007,0.007)))
display_list.append(pu.PointCloud(pts,color=(200,0,0)))
po3d.run(display_list)
if __name__ == '__main__':
p = optparse.OptionParser()
p.add_option('-f', action='store', type='string', dest='pkl_file_name',
help='file.pkl File with the scan,pos dict.')
p.add_option('--all_pts', action='store_true', dest='show_all_pts',
help='show all the points in light grey')
opt, args = p.parse_args()
pkl_file_name = opt.pkl_file_name
show_full_cloud = opt.show_all_pts
str_parts = pkl_file_name.split('.')
raw_name = str_parts[-2]
str_parts = raw_name.split('/')
raw_name = str_parts[-1]
dict = ut.load_pickle(pkl_file_name)
pos_list = dict['pos_list']
scan_list = dict['scan_list']
min_angle = math.radians(-40)
max_angle = math.radians(40)
l1 = dict['l1']
l2 = dict['l2']
# l2 = -0.055
# l2 = 0.035
if dict.has_key('pt'):
pt = dict['pt']
print 'dict has key pt'
else:
print 'dict does NOT have key pt'
pt = np.matrix([0.35,0.0,-0.3]).T
dict['pt'] = pt
ut.save_pickle(dict,pkl_file_name)
# charlie_nih()
# test_grasp_location_on_object()
# test_find_door_handle()
# test_vertical_plane_finding_close()
# test_vertical_plane_finding()
test_segmentation()
# test_plane_finding()
# test_max_forward()
# test_approach()
# test_choose_grasp_strategy()
# test_different_surfaces()
# test_occ_grid()
| [
[
1,
0,
0.0261,
0.0009,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0261,
0.0009,
0,
0.66,
0.0227,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.027,
0.0009,
0,
0.6... | [
"import roslib; roslib.load_manifest('hrl_tilting_hokuyo')",
"import roslib; roslib.load_manifest('hrl_tilting_hokuyo')",
"import hrl_hokuyo.hokuyo_processing as hp",
"import sys, optparse, os",
"import hrl_lib.util as ut",
"import hrl_lib.transforms as tr",
"import numpy as np,math",
"import time",
... |
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import sys, optparse, os
import time
import math, numpy as np
import scipy.ndimage as ni
import copy
import hrl_lib.util as ut, hrl_lib.transforms as tr
## subtract occupancy grids. og1 = og1-og2
#
# @param og1 - occupancy_grid_3d object.
# @param og2 - occupancy_grid_3d object.
#
#will position og2 at an appropriate location within og1 (hopefully)
#will copy points in og2 but not in og1 into og1
#
# points corresponding to the gird cells whose occupancy drops to
# zero will still be in grid_points_list
#UNTESTED:
# * subtracting grids of different sizes.
# * how the rotation_z of the occupancy grid will affect things.
def subtract(og1,og2):
if np.all(og1.resolution==og2.resolution) == False:
print 'occupancy_grid_3d.subtract: The resolution of the two grids is not the same.'
print 'res1, res2:', og1.resolution.A1.tolist(), og2.resolution.A1.tolist()
print 'Exiting...'
sys.exit()
sub_tlb = og2.tlb
sub_brf = og2.brf
sub_tlb_idx = np.round((sub_tlb-og1.brf)/og1.resolution)
sub_brf_idx = np.round((sub_brf-og1.brf)/og1.resolution)
x_s,y_s,z_s = int(sub_brf_idx[0,0]),int(sub_brf_idx[1,0]),int(sub_brf_idx[2,0])
x_e,y_e,z_e = int(sub_tlb_idx[0,0]),int(sub_tlb_idx[1,0]),int(sub_tlb_idx[2,0])
x_e = min(x_e+1,og1.grid_shape[0,0])
y_e = min(y_e+1,og1.grid_shape[1,0])
z_e = min(z_e+1,og1.grid_shape[2,0])
sub_grid = og1.grid[x_s:x_e,y_s:y_e,z_s:z_e]
if np.any(og1.grid_shape!=og2.grid_shape):
print '#############################################################################'
print 'WARNING: occupancy_grid_3d.subtract has not been tested for grids of different sizes.'
print '#############################################################################'
sub_grid = sub_grid-og2.grid
sub_grid = np.abs(sub_grid) # for now.
og1.grid[x_s:x_e,y_s:y_e,z_s:z_e] = sub_grid
idxs = np.where(sub_grid>=1)
shp = og2.grid_shape
list_idxs = (idxs[0]+idxs[1]*shp[0,0]+idxs[2]*shp[0,0]*shp[1,0]).tolist()
og1_list_idxs = (idxs[0]+x_s+(idxs[1]+y_s)*shp[0,0]+(idxs[2]+z_s)*shp[0,0]*shp[1,0]).tolist()
og1_list_len = len(og1.grid_points_list)
for og1_pts_idxs,pts_idxs in zip(og1_list_idxs,list_idxs):
if og1_pts_idxs<og1_list_len:
og1.grid_points_list[og1_pts_idxs] += og2.grid_points_list[pts_idxs]
## class which implements the occupancy grid
class occupancy_grid_3d():
##
# @param brf - 3x1 matrix. Bottom Right Front.
# @param tlb - 3x1 matrix (coord of center of the top left back cell)
# @param resolution - 3x1 matrix. size of each cell (in meters) along
# the different directions.
def __init__(self, brf, tlb, resolution, rotation_z=math.radians(0.)):
#print np.round((tlb-brf)/resolution).astype('int')+1
self.grid = np.zeros(np.round((tlb-brf)/resolution).astype('int')+1,dtype='int')
self.tlb = tlb
self.brf = brf
self.grid_shape = np.matrix(self.grid.shape).T
self.resolution = resolution
n_cells = self.grid.shape[0]*self.grid.shape[1]*self.grid.shape[2]
self.grid_points_list = [[] for i in range(n_cells)]
self.rotation_z = rotation_z
## returns list of 8 tuples of 3x1 points which form the edges of the grid.
# Useful for displaying the extents of the volume of interest (VOI).
# @return list of 8 tuples of 3x1 points which form the edges of the grid.
def grid_lines(self, rotation_angle=0.):
grid_size = np.multiply(self.grid_shape,self.resolution)
rot_mat = tr.rotZ(rotation_angle)
p5 = self.tlb
p6 = p5+np.matrix([0.,-grid_size[1,0],0.]).T
p8 = p5+np.matrix([0.,0.,-grid_size[2,0]]).T
p7 = p8+np.matrix([0.,-grid_size[1,0],0.]).T
p3 = self.brf
p4 = p3+np.matrix([0.,grid_size[1,0],0.]).T
p2 = p3+np.matrix([0.,0.,grid_size[2,0]]).T
p1 = p2+np.matrix([0.,grid_size[1,0],0.]).T
p1 = rot_mat*p1
p2 = rot_mat*p2
p3 = rot_mat*p3
p4 = rot_mat*p4
p5 = rot_mat*p5
p6 = rot_mat*p6
p7 = rot_mat*p7
p8 = rot_mat*p8
l = [(p1,p2),(p1,p4),(p2,p3),(p3,p4),(p5,p6),(p6,p7),(p7,p8),(p8,p5),(p1,p5),(p2,p6),(p4,p8),(p3,p7)]
#l = [(p5,p6),(p5,p3),(p1,p2)]
return l
## fill the occupancy grid.
# @param pts - 3xN matrix of points.
# @param ignore_z - not use the z coord of the points. grid will be like a 2D grid.
#
#each cell of the grid gets filled the number of points that fall in the cell.
def fill_grid(self,pts,ignore_z=False):
if ignore_z:
idx = np.where(np.min(np.multiply(pts[0:2,:]>self.brf[0:2,:],
pts[0:2,:]<self.tlb[0:2,:]),0))[1]
else:
idx = np.where(np.min(np.multiply(pts[0:3,:]>self.brf,pts[0:3,:]<self.tlb),0))[1]
if idx.shape[1] == 0:
print 'aha!'
return
pts = pts[:,idx.A1.tolist()]
# Find coordinates
p_all = np.round((pts[0:3,:]-self.brf)/self.resolution)
# Rotate points
pts[0:3,:] = tr.Rz(self.rotation_z).T*pts[0:3,:]
for i,p in enumerate(p_all.astype('int').T):
if ignore_z:
p[0,2] = 0
if np.any(p<0) or np.any(p>=self.grid_shape.T):
continue
tup = tuple(p.A1)
self.grid_points_list[
tup[0] + self.grid_shape[0,0] *
tup[1] + self.grid_shape[0,0] *
self.grid_shape[1,0] *
tup[2]].append(pts[:,i])
self.grid[tuple(p.A1)] += 1
def to_binary(self,thresh=1):
''' all cells with occupancy>=thresh set to 1, others set to 0.
'''
filled = (self.grid>=thresh)
self.grid[np.where(filled==True)] = 1
self.grid[np.where(filled==False)] = 0
def argmax_z(self,index_min=-np.Inf,index_max=np.Inf,search_up=False,search_down=False):
''' searches in the z direction for maximum number of cells with occupancy==1
call this function after calling to_binary()
returns index.
'''
index_min = int(max(index_min,0))
index_max = int(min(index_max,self.grid_shape[2,0]-1))
z_count_mat = []
#for i in xrange(self.grid_shape[2,0]):
for i in xrange(index_min,index_max+1):
z_count_mat.append(np.where(self.grid[:,:,i]==1)[0].shape[0])
if z_count_mat == []:
return None
z_count_mat = np.matrix(z_count_mat).T
max_z = np.argmax(z_count_mat)
max_count = z_count_mat[max_z,0]
max_z += index_min
print '#### max_count:', max_count
if search_up:
max_z_temp = max_z
for i in range(1,5):
#if (z_count_mat[max_z+i,0]*3.0)>max_count: #A
#if (z_count_mat[max_z+i,0]*8.0)>max_count: #B
if (max_z+i)>index_max:
break
if (z_count_mat[max_z+i-index_min,0]*5.0)>max_count: #B'
max_z_temp = max_z+i
max_z = max_z_temp
if search_down:
max_z_temp = max_z
for i in range(1,5):
if (max_z-i)<index_min:
break
if (max_z-i)>index_max:
continue
if (z_count_mat[max_z-i-index_min,0]*5.0)>max_count:
max_z_temp = max_z-i
max_z = max_z_temp
return max_z,max_count
def find_plane_indices(self,hmin=-np.Inf,hmax=np.Inf,assume_plane=False):
''' assume_plane - always return something.
returns list of indices (z) corrresponding to horizontal plane points.
returns [] if there is no plane
'''
index_min = int(max(round((hmin-self.brf[2,0])/self.resolution[2,0]),0))
index_max = int(min(round((hmax-self.brf[2,0])/self.resolution[2,0]),self.grid_shape[2,0]-1))
z_plane,max_count = self.argmax_z(index_min,index_max,search_up=True)
if z_plane == None:
print 'oink oink.'
return []
#---------- A
# extra_remove_meters = 0.01
# n_more_to_remove = int(round(extra_remove_meters/self.resolution[2,0]))
# l = range(max(z_plane-n_more_to_remove-1,0),
# min(z_plane+n_more_to_remove+1,self.grid_shape[2,0]-1))
#---------- B
extra_remove_meters = 0.005
n_more_to_remove = int(round(extra_remove_meters/self.resolution[2,0]))
l = range(max(z_plane-10,0),
min(z_plane+n_more_to_remove+1,self.grid_shape[2,0]-1))
# figure out whether this is indeed a plane.
if assume_plane == False:
n_more = int(round(0.1/self.resolution[2,0]))
l_confirm = l+ range(max(l),min(z_plane+n_more+1,self.grid_shape[2,0]-1))
grid_2d = np.max(self.grid[:,:,l],2)
n_plane_cells = grid_2d.sum()
grid_2d = ni.binary_fill_holes(grid_2d) # I want 4-connectivity while filling holes.
n_plane_cells = grid_2d.sum()
min_plane_pts_threshold = (self.grid_shape[0,0]*self.grid_shape[1,0])/4
print '###n_plane_cells:', n_plane_cells
print 'min_plane_pts_threshold:', min_plane_pts_threshold
print 'find_plane_indices grid shape:',self.grid_shape.T
if n_plane_cells < min_plane_pts_threshold:
print 'occupancy_grid_3d.find_plane_indices: There is no plane.'
print 'n_plane_cells:', n_plane_cells
print 'min_plane_pts_threshold:', min_plane_pts_threshold
l = []
return l
## get centroids of all the occupied cells as a 3xN np matrix
# @param occupancy_threshold - number of points in a cell for it to be "occupied"
# @return 3xN matrix of 3d coord of the cells which have occupancy >= occupancy_threshold
def grid_to_centroids(self,occupancy_threshold=1):
p = np.matrix(np.row_stack(np.where(self.grid>=occupancy_threshold))).astype('float')
p[0,:] = p[0,:]*self.resolution[0,0]
p[1,:] = p[1,:]*self.resolution[1,0]
p[2,:] = p[2,:]*self.resolution[2,0]
p += self.brf
return p
def grid_to_points(self,array=None,occupancy_threshold=1):
''' array - if not None then this will be used instead of self.grid
returns 3xN matrix of 3d coord of the cells which have occupancy >= occupancy_threshold
'''
if array == None:
array = self.grid
idxs = np.where(array>=occupancy_threshold)
list_idxs = (idxs[0]+idxs[1]*self.grid_shape[0,0]+idxs[2]*self.grid_shape[0,0]*self.grid_shape[1,0]).tolist()
l = []
for pts_idxs in list_idxs:
l += self.grid_points_list[pts_idxs]
if l == []:
p = np.matrix([])
else:
p = np.column_stack(l)
return p
def labeled_array_to_points(self,array,label):
''' returns coordinates of centers of grid cells corresponding to
label as a 3xN matrix.
'''
idxs = np.where(array==label)
list_idxs = (idxs[0]+idxs[1]*self.grid_shape[0,0]+idxs[2]*self.grid_shape[0,0]*self.grid_shape[1,0]).tolist()
l = []
for pts_idxs in list_idxs:
l += self.grid_points_list[pts_idxs]
if l == []:
p = np.matrix([])
else:
p = np.column_stack(l)
return p
def remove_vertical_plane(self):
''' removes plane parallel to the YZ plane.
changes grid.
returns plane_indices, slice corresponding to the vertical plane.
points behind the plane are lost for ever!
'''
self.grid = self.grid.swapaxes(2,0)
self.grid_shape = np.matrix(self.grid.shape).T
# z_max_first,max_count = self.argmax_z(search_up=False)
# z_max_second,max_count_second = self.argmax_z(index_min=z_max_first+int(round(0.03/self.resolution[0,0])) ,search_up=False)
z_max_first,max_count = self.argmax_z(search_down=False)
z_max_second,max_count_second = self.argmax_z(index_min=z_max_first+int(round(0.035/self.resolution[0,0])) ,search_down=False)
z_max_first,max_count = self.argmax_z(search_down=False)
#z_max = self.argmax_z(search_up=True)
if (max_count_second*1./max_count) > 0.3:
z_max = z_max_second
else:
z_max = z_max_first
print 'z_max_first', z_max_first
print 'z_max_second', z_max_second
print 'z_max', z_max
more = int(round(0.03/self.resolution[0,0]))
plane_indices = range(max(0,z_max-more),min(z_max+more,self.grid_shape[2,0]))
self.grid = self.grid.swapaxes(2,0)
self.grid_shape = np.matrix(self.grid.shape).T
ver_plane_slice = self.grid[plane_indices,:,:]
self.grid[plane_indices,:,:] = 0
max_x = max(plane_indices)
behind_indices = range(max_x,self.grid_shape[0,0])
self.grid[behind_indices,:,:] = 0
return plane_indices,ver_plane_slice
def remove_horizontal_plane(self, remove_below=True,hmin=-np.Inf,hmax=np.Inf,
extra_layers=0):
''' call after to_binary()
removes points corresponding to the horizontal plane from the grid.
remove_below - remove points below the plane also.
hmin,hmax - min and max possible height of the plane. (meters)
This function changes grid.
extra_layers - number of layers above the plane to remove. Sometimes
I want to be over zealous while removing plane points.
e.g. max_fwd_without_collision
it returns the slice which has been set to zero, in case you want to
leave the grid unchanged.
'''
l = self.find_plane_indices(hmin,hmax)
if l == []:
print 'occupancy_grid_3d.remove_horizontal_plane: No plane found.'
return None,l
add_num = min(10,self.grid_shape[2,0]-max(l)-1)
max_l = max(l)+add_num
l_edge = l+range(max(l),max_l+1)
grid_2d = np.max(self.grid[:,:,l_edge],2)
# grid_2d = ni.binary_dilation(grid_2d,iterations=1) # I want 4-connectivity while filling holes.
grid_2d = ni.binary_fill_holes(grid_2d) # I want 4-connectivity while filling holes.
connect_structure = np.empty((3,3),dtype='int')
connect_structure[:,:] = 1
eroded_2d = ni.binary_erosion(grid_2d,connect_structure,iterations=2)
grid_2d = grid_2d-eroded_2d
idxs = np.where(grid_2d!=0)
if max_l>max(l):
for i in range(min(5,add_num)):
self.grid[idxs[0],idxs[1],max(l)+i+1] = 0
if remove_below:
l = range(0,min(l)+1)+l
max_z = max(l)
for i in range(extra_layers):
l.append(max_z+i+1)
l_edge = l+range(max(l),max_l+1)
plane_and_below_pts = self.grid[:,:,l_edge]
self.grid[:,:,l] = 0 # set occupancy to zero.
return plane_and_below_pts,l_edge
def segment_objects(self, twod=False):
''' segments out objects after removing the plane.
call after calling to_binary.
returns labelled_array,n_labels
labelled_array - same dimen as occupancy grid, each object has a different label.
'''
plane_and_below_pts,l = self.remove_horizontal_plane(extra_layers=0)
if l == []:
print 'occupancy_grid_3d.segment_objects: There is no plane.'
return None,None
if twod == False:
labelled_arr,n_labels = self.find_objects()
else:
labelled_arr,n_labels = self.find_objects_2d()
self.grid[:,:,l] = plane_and_below_pts
return labelled_arr,n_labels
def find_objects_2d(self):
''' projects all points into the xy plane and then performs
segmentation by region growing.
'''
connect_structure = np.empty((3,3),dtype='int')
connect_structure[:,:] = 1
grid_2d = np.max(self.grid[:,:,:],2)
# grid_2d = ni.binary_erosion(grid_2d)
# grid_2d = ni.binary_erosion(grid_2d,connect_structure)
labeled_arr,n_labels = ni.label(grid_2d,connect_structure)
print 'found %d objects'%(n_labels)
labeled_arr_3d = self.grid.swapaxes(2,0)
labeled_arr_3d = labeled_arr_3d.swapaxes(1,2)
print 'labeled_arr.shape:',labeled_arr.shape
print 'labeled_arr_3d.shape:',labeled_arr_3d.shape
labeled_arr_3d = labeled_arr_3d*labeled_arr
labeled_arr_3d = labeled_arr_3d.swapaxes(2,0)
labeled_arr_3d = labeled_arr_3d.swapaxes(1,0)
labeled_arr = labeled_arr_3d
# I still want to count cells in 3d (thin but tall objects.)
if n_labels > 0:
labels_list = range(1,n_labels+1)
#count_objects = ni.sum(grid_2d,labeled_arr,labels_list)
count_objects = ni.sum(self.grid,labeled_arr,labels_list)
if n_labels == 1:
count_objects = [count_objects]
t0 = time.time()
new_labels_list = []
for c,l in zip(count_objects,labels_list):
if c > 3:
new_labels_list.append(l)
else:
labeled_arr[np.where(labeled_arr == l)] = 0
# relabel stuff
for nl,l in enumerate(new_labels_list):
labeled_arr[np.where(labeled_arr == l)] = nl+1
n_labels = len(new_labels_list)
t1 = time.time()
print 'time:', t1-t0
print 'found %d objects'%(n_labels)
# return labeled_arr,n_labels
return labeled_arr_3d,n_labels
def find_objects(self):
''' region growing kind of thing for segmentation. Useful if plane has been removed.
'''
connect_structure = np.empty((3,3,3),dtype='int')
grid = copy.copy(self.grid)
connect_structure[:,:,:] = 0
connect_structure[1,1,:] = 1
iterations = int(round(0.005/self.resolution[2,0]))
# iterations=5
#grid = ni.binary_closing(grid,connect_structure,iterations=iterations)
connect_structure[:,:,:] = 1
labeled_arr,n_labels = ni.label(grid,connect_structure)
print 'ho!'
print 'found %d objects'%(n_labels)
if n_labels == 0:
return labeled_arr,n_labels
labels_list = range(1,n_labels+1)
count_objects = ni.sum(grid,labeled_arr,labels_list)
if n_labels == 1:
count_objects = [count_objects]
# t0 = time.time()
# remove_labels = np.where(np.matrix(count_objects) <= 5)[1].A1.tolist()
# for r in remove_labels:
# labeled_arr[np.where(labeled_arr == r)] = 0
# t1 = time.time()
# labeled_arr,n_labels = ni.label(labeled_arr,connect_structure)
# print 'time:', t1-t0
t0 = time.time()
new_labels_list = []
for c,l in zip(count_objects,labels_list):
if c > 3:
new_labels_list.append(l)
else:
labeled_arr[np.where(labeled_arr == l)] = 0
# relabel stuff
for nl,l in enumerate(new_labels_list):
labeled_arr[np.where(labeled_arr == l)] = nl+1
n_labels = len(new_labels_list)
t1 = time.time()
print 'time:', t1-t0
print 'found %d objects'%(n_labels)
return labeled_arr,n_labels
if __name__ == '__main__':
import pygame_opengl_3d_display as po3d
import hokuyo.pygame_utils as pu
import processing_3d as p3d
p = optparse.OptionParser()
p.add_option('-f', action='store', type='string', dest='pkl_file_name',
help='file.pkl File with the scan,pos dict.',default=None)
p.add_option('-c', action='store', type='string', dest='pts_pkl',
help='pkl file with 3D points',default=None)
opt, args = p.parse_args()
pts_pkl = opt.pts_pkl
pkl_file_name = opt.pkl_file_name
#-------------- simple test ---------------
# gr = occupancy_grid_3d(np.matrix([0.,0.,0]).T, np.matrix([1.,1.,1]).T,
# np.matrix([1,1,1]).T)
# pts = np.matrix([[1.1,0,-0.2],[0,0,0],[0.7,0.7,0.3],[0.6,0.8,-0.2]]).T
# gr.fill_grid(pts)
## print gr.grid
resolution = np.matrix([0.01,0.01,0.01]).T
gr = occupancy_grid_3d(np.matrix([0.45,-0.5,-1.0]).T, np.matrix([0.65,0.05,-0.2]).T,
resolution)
if pts_pkl != None:
pts = ut.load_pickle(pts_pkl)
elif pkl_file_name != None:
dict = ut.load_pickle(pkl_file_name)
pos_list = dict['pos_list']
scan_list = dict['scan_list']
min_angle = math.radians(-40)
max_angle = math.radians(40)
l1 = dict['l1']
l2 = dict['l2']
pts = p3d.generate_pointcloud(pos_list, scan_list, min_angle, max_angle, l1, l2)
else:
print 'specify a pkl file -c or -f'
print 'Exiting...'
sys.exit()
print 'started filling the grid'
t0 = time.time()
gr.fill_grid(pts)
t1 = time.time()
print 'time to fill the grid:', t1-t0
#grid_pts = gr.grid_to_points()
grid_pts = gr.grid_to_centroids()
## print grid_pts
cloud = pu.CubeCloud(grid_pts,(0,0,0),(resolution/2).A1.tolist())
pc = pu.PointCloud(pts,(100,100,100))
lc = pu.LineCloud(gr.grid_lines(),(100,100,0))
po3d.run([cloud,pc,lc])
| [
[
1,
0,
0.0489,
0.0016,
0,
0.66,
0,
509,
0,
3,
0,
0,
509,
0,
0
],
[
1,
0,
0.0506,
0.0016,
0,
0.66,
0.125,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.0538,
0.0016,
0,
0... | [
"import sys, optparse, os",
"import time",
"import math, numpy as np",
"import scipy.ndimage as ni",
"import copy",
"import hrl_lib.util as ut, hrl_lib.transforms as tr",
"def subtract(og1,og2):\n\n if np.all(og1.resolution==og2.resolution) == False:\n print('occupancy_grid_3d.subtract: The re... |
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
## author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import roslib; roslib.load_manifest('zenither')
import rospy
from hrl_msgs.msg import FloatArray
from threading import RLock
class ZenitherClient():
def __init__(self, init_ros_node = False,
zenither_pose_topic = 'zenither_pose'):
if init_ros_node:
rospy.init_node('ZenitherClient')
self.h = None
self.lock = RLock()
rospy.Subscriber(zenither_pose_topic, FloatArray, self.pose_cb)
def pose_cb(self, fa):
self.lock.acquire()
self.h = fa.data[0]
self.lock.release()
def height(self):
self.lock.acquire()
h = self.h
self.lock.release()
return h
if __name__ == '__main__':
zc = ZenitherClient(init_ros_node = True)
while not rospy.is_shutdown():
print 'h:', zc.height()
rospy.sleep(0.1)
| [
[
1,
0,
0.4746,
0.0169,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.4746,
0.0169,
0,
0.66,
0.1667,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.4915,
0.0169,
0,
0.... | [
"import roslib; roslib.load_manifest('zenither')",
"import roslib; roslib.load_manifest('zenither')",
"import rospy",
"from hrl_msgs.msg import FloatArray",
"from threading import RLock",
"class ZenitherClient():\n def __init__(self, init_ros_node = False,\n zenither_pose_topic = 'zenit... |
#!/usr/bin/python
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# ROS wrapper for zenither.
## author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
## author Travis Deyle (Healthcare Robotics Lab, Georgia Tech.)
from threading import RLock
import roslib
roslib.load_manifest('zenither')
import zenither_config as zc
import rospy
from hrl_srvs.srv import Float_Int
from hrl_msgs.msg import FloatArray
class ZenitherClient():
def __init__(self, robot):
try:
rospy.init_node('ZenitherClient')
rospy.logout('ZenitherServer: Initialized Node')
except rospy.ROSException:
pass
if robot not in zc.calib:
raise RuntimeError('unknown robot')
self.calib = zc.calib[robot]
srv = '/zenither/move_position'
rospy.wait_for_service(srv)
self.move_position = rospy.ServiceProxy(srv, Float_Int)
srv = '/zenither/stop'
rospy.wait_for_service(srv)
self.stop = rospy.ServiceProxy(srv, Float_Int)
srv = '/zenither/apply_torque'
rospy.wait_for_service(srv)
self.apply_torque = rospy.ServiceProxy(srv, Float_Int)
srv = '/zenither/torque_move_position'
rospy.wait_for_service(srv)
self.torque_move_position = rospy.ServiceProxy(srv, Float_Int)
zenither_pose_topic = 'zenither_pose'
self.h = None
self.lock = RLock()
rospy.Subscriber(zenither_pose_topic, FloatArray, self.pose_cb)
#---------- functions to send zenither commands. -------------
def estop(self):
self.stop(0)
def zenith(self, torque=None):
if torque == None:
torque=self.calib['zenith_torque']
self.apply_torque(torque)
def nadir(self, torque=None):
if torque == None:
torque=self.calib['nadir_torque']
self.apply_torque(torque)
#--------- zenither height functions --------------
def pose_cb(self, fa):
self.lock.acquire()
self.h = fa.data[0]
self.lock.release()
## return the current height of the zenither.
def height(self):
self.lock.acquire()
h = self.h
self.lock.release()
return h
if __name__ == '__main__':
import time
cl = ZenitherClient('HRL2')
cl.zenith()
time.sleep(0.5)
cl.estop()
| [
[
1,
0,
0.2845,
0.0086,
0,
0.66,
0,
83,
0,
1,
0,
0,
83,
0,
0
],
[
1,
0,
0.3017,
0.0086,
0,
0.66,
0.125,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.3103,
0.0086,
0,
0.6... | [
"from threading import RLock",
"import roslib",
"roslib.load_manifest('zenither')",
"import zenither_config as zc",
"import rospy",
"from hrl_srvs.srv import Float_Int",
"from hrl_msgs.msg import FloatArray",
"class ZenitherClient():\n def __init__(self, robot):\n try:\n rospy.ini... |
calib = {
'El-E': {
'robot': 'El-E',
'pos_factor': 0.9144 / (183897 - 1250),
'vel_factor': 0.9144 / (183897 - 1250) / 20,
'acc_factor': 0.9144 / (183897 - 1250),
'POS_MAX': 0.9,
'VEL_DEFAULT': 1.5,
'VEL_MAX': 4.0,
'ACC_DEFAULT':0.0002,
'ACC_MAX':0.001,
'ZERO_BIAS':-0.004,
'HAS_BRAKE':True,
'nadir_torque': 0,
'zenith_torque': 200,
'down_fast_torque': 0,
'down_slow_torque': 50,
'down_snail_torque': 60,
'up_fast_torque': 300,
'up_slow_torque': 250,
'up_snail_torque': 200,
'max_height': 0.89,
'min_height': 0.005
},
'HRL2': {
#-------- Cressel's explanation -------------------------
# max speed for size 40 1m actuator is 1400rpm / 0.45m/s
# conversion for velocity 536.87633 cnts/s / rpm
# 536.87633*1400/0.45 # cnts/s / m/s (0.5,-540179)(0.0,0)
# close but not there yet
#-------- Advait's explanation
# 1 rev of zenither = 20mm (from festo manual, page 10)
# 1 rev of animatics servo = 2000 encoder counts (pg 6, section 1.0 of the animatics manual)
# a gear reduction of 10 (I think I remember Cressel mentioning this).
# => 20000 counts = 20mm or 1 count = 1/1000,000 meters
#
'robot': 'HRL2',
'pos_factor': 1.0/ (-1000000), # Advait - Apr 27, 2009
'POS_MAX': 0.96, # Advait - Feb 17, 2009
'ZERO_BIAS':0.28,
'HAS_BRAKE':True,
'nadir_torque': 3,
'zenith_torque': 400,
'down_fast_torque': 0,
'down_slow_torque': 3,
'down_snail_torque': 5,
'up_fast_torque': 450,
'up_slow_torque': 400,
'up_snail_torque': 300,
'zero_vel_torque': 90,
'max_height': 1.32,
'min_height': 0.29
},
'test_rig': {
#-------- Advait's explanation
# 1 rev of zenither = 10mm (from festo manual, page 10)
# 1 rev of animatics servo = 2000 encoder counts (pg 6, section 1.0 of the animatics manual)
# => 2000 counts = 10mm or 1 count = 1/200,000 meters
#
# for vel_factor and acc_factor, see Page 8 of Animatics manual
#
'robot': 'test_rig',
'pos_factor': 1.0 /200000,
'vel_factor': 1.0/(32212.578*100),
'acc_factor': 1.0/(7.9166433*100),
'POS_MAX': 0.9,
'VEL_DEFAULT': 0.2,
'VEL_MAX': 0.4,
'ACC_DEFAULT':0.5,
'ACC_MAX':10.0,
'ZERO_BIAS':0.0,
'HAS_BRAKE':False,
'nadir_torque': -150,
'zenith_torque': 150,
'max_height': 0.9,
'min_height': 0.005
},
}
| [
[
14,
0,
0.5,
0.9643,
0,
0.66,
0,
147,
0,
0,
0,
0,
0,
6,
0
]
] | [
"calib = {\n 'El-E': {\n 'robot': 'El-E',\n 'pos_factor': 0.9144 / (183897 - 1250),\n 'vel_factor': 0.9144 / (183897 - 1250) / 20,\n 'acc_factor': 0.9144 / (183897 - 1250),\n 'POS_MAX': 0.9,\n 'VEL_DEFAULT': 1.5,"
] |
__all__ = [
'zenither',
'lib_zenither',
'ros_zenither_server',
'ros_zenither_client'
]
| [
[
14,
0,
0.5833,
1,
0,
0.66,
0,
272,
0,
0,
0,
0,
0,
5,
0
]
] | [
"__all__ = [\n'zenither',\n'lib_zenither',\n'ros_zenither_server',\n'ros_zenither_client'\n]"
] |
#!/usr/bin/python
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
## author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
## author Travis Deyle (Healthcare Robotics Lab, Georgia Tech.)
## author Hai Nguyen (Healthcare Robotics Lab, Georgia Tech.)
import roslib
roslib.load_manifest('zenither')
import rospy
from hrl_srvs.srv import Float_Int
import time
import sys
class ZenitherServer():
def __init__(self, zenither):
try:
rospy.init_node('ZenitherServer')
rospy.logout('ZenitherServer: Initialized Node')
except rospy.ROSException:
pass
self.zenither = zenither
self.smp = rospy.Service('/zenither/move_position', Float_Int,
self.move_position)
self.ss = rospy.Service('/zenither/stop', Float_Int,
self.estop)
self.sat = rospy.Service('/zenither/apply_torque', Float_Int,
self.apply_torque)
self.stmp = rospy.Service('/zenither/torque_move_position',
Float_Int, self.torque_move_position)
def move_position(self, msg):
print 'move_position is UNTESTED'
#self.zenither.move_position( msg.value )
return True
def apply_torque(self, req):
self.zenither.nadir(req.value)
return True
def estop(self, req):
self.zenither.estop()
return True
def torque_move_position(self, req):
self.zenither.torque_move_position(req.value)
return True
if __name__ == '__main__':
import zenither.zenither as zenither
z = zenither.Zenither('HRL2', pose_read_thread = True)
zs = ZenitherServer(z)
rospy.spin()
# rosservice call /zenither/move_position 0.3
| [
[
1,
0,
0.3882,
0.0118,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.4,
0.0118,
0,
0.66,
0.1429,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.4118,
0.0118,
0,
0.66,... | [
"import roslib",
"roslib.load_manifest('zenither')",
"import rospy",
"from hrl_srvs.srv import Float_Int",
"import time",
"import sys",
"class ZenitherServer():\n def __init__(self, zenither):\n try:\n rospy.init_node('ZenitherServer')\n rospy.logout('ZenitherServer: Init... |
#!/usr/bin/python
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Cressel Anderson (Healthcare Robotics Lab, Georgia Tech.)
# \author Marc Killpack (Healthcare Robotics Lab, Georgia Tech.)
import pygame
import pygame.joystick
import sys, optparse
import segway_command as sc
import time as time
import roslib
roslib.load_manifest('segway_omni')
import rospy
import hrl_lib.util as ut
import numpy as np
from pygame.locals import *
if __name__=='__main__':
p = optparse.OptionParser()
p.add_option('-z', action='store_true', dest='zenither',
help='control the zenither also')
opt, args = p.parse_args()
zenither_flag = opt.zenither
if zenither_flag:
import zenither.zenither as zenither
z = zenither.Zenither(robot='HRL2')
cmd_node = sc.SegwayCommand()
max_xvel = 0.18
max_yvel = 0.15
max_speed = 0.18 # don't exceed 0.18 under any condition.
max_avel = 0.18
xvel = 0.0
yvel = 0.0
avel = 0.0
#init pygame
pygame.init()
#joystick_status
joystick_count = pygame.joystick.get_count()
print "Joysticks found: %d\n" % joystick_count
try:
js = pygame.joystick.Joystick(0)
js.init()
except pygame.error:
print "joystick error"
js = None
js_status = js.get_init()
print js_status
screen = pygame.display.set_mode((320,80))
pygame.display.set_caption('Snozzjoy')
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250,250,250))
x=0.
y=0.
a=0.
len = 5
xvel_history = np.matrix(np.zeros([len,1]))
connected = False
while not rospy.is_shutdown():
move_zenither_flag=False
for event in pygame.event.get():
if (event.type == JOYAXISMOTION):
if event.axis == 0: #left pedal
x = -0.5 * event.value - 0.5
elif event.axis == 1 and x == 0: #right pedal
x = 0.5 * event.value + 0.5
if event.axis == 2:
a = event.value
print 'event.axis: ',event.axis,'event.value: ',event.value
# elif (event.type == JOYBUTTONDOWN):
# if zenither_flag:
# if(event.button == 0):
# z.zenith(z.calib['up_slow_torque'])
# move_zenither_flag=True
# if(event.button == 1):
# z.nadir(z.calib['down_snail_torque'])
# move_zenither_flag=True
if x == 0 and y == 0 and a ==0:
connected = True
# detect a joystick disconnect
try:
js.quit()
js.init()
except pygame.error:
print "joystick error"
rospy.signal_shutdown()
# if zenither_flag and (move_zenither_flag == False):
# z.estop()
#send segway commands
if connected:
xvel = x*max_xvel
# xvel_history[0:(len-1)] = xvel_history[1:len]
# xvel_history[(len-1)] = xvel
# xvel = np.mean(xvel_history)
yvel = y*max_yvel
avel = a*max_avel
vel_vec = np.matrix([xvel,yvel]).T
vel_mag = np.linalg.norm(vel_vec)
speed = ut.bound(vel_mag,max_speed,0.)
if speed >= 0.05:
vel_vec = vel_vec*speed/vel_mag
xvel,yvel = vel_vec[0,0],vel_vec[1,0]
cmd_node.set_velocity(xvel,yvel,avel)
print '*******xvel=',xvel,'; avel=',avel
# stop the segway
cmd_node.set_velocity(0.,0.,0.)
| [
[
1,
0,
0.1951,
0.0061,
0,
0.66,
0,
87,
0,
1,
0,
0,
87,
0,
0
],
[
1,
0,
0.2012,
0.0061,
0,
0.66,
0.0909,
115,
0,
1,
0,
0,
115,
0,
0
],
[
1,
0,
0.2073,
0.0061,
0,
0.... | [
"import pygame",
"import pygame.joystick",
"import sys, optparse",
"import segway_command as sc",
"import time as time",
"import roslib",
"roslib.load_manifest('segway_omni')",
"import rospy",
"import hrl_lib.util as ut",
"import numpy as np",
"from pygame.locals import *",
"if __name__=='__ma... |
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Cressel Anderson (Healthcare Robotics Lab, Georgia Tech.)
import usb
import pickle
import time
import numpy as np
import math
import struct
class Mecanum_Properties():
def __init__( self ):
self.r1 = .2032/2. # 8in wheels
self.r2 = .2032/2. # 8in wheels
self.R = 4*2.54/100 # wheel radius in meters
self.la = .6223/2 # 1/2 width of the base
self.lb = .33655/2 # 1/2 length of the base
class Mecanum( Mecanum_Properties ):
def __init__( self ):
self.segway_front = Segway( side='front')
self.segway_back = Segway( side='back' )
Mecanum_Properties.__init__(self)
self.get_status()
def set_velocity( self, xvel, yvel, avel ):
"""xvel and yvel should be in m/s and avel should be rad/s"""
yvel = -yvel
R = self.R
la = self.la
lb = self.lb
# eq. 17 from Knematic modeling for feedback control of an
# omnidirectional wheeled mobile robot by Muir and Neuman at
# CMU
J = 1/R * np.matrix([-1,1, (la + lb),
1,1,-(la + lb),
-1,1,-(la + lb),
1,1, (la + lb) ]).reshape(4,3)
# their coordinate frame is rotated
dP = np.matrix( [ -yvel, -xvel, avel] ).T
w = J*dP
# they use a goofy ordering
flw = w[1,0]
frw = w[0,0]
blw = w[2,0]
brw = w[3,0]
front_cmd = self.segway_front.send_wheel_velocities( flw, frw )
back_cmd = self.segway_back.send_wheel_velocities( blw, brw )
if front_cmd == False or back_cmd == False:
print 'Velocities out of spec: ',flw,frw,blw,brw
print 'Perhaps we should consider sending the max command so motion doesn\'t hang.'
def stop(self):
self.set_velocity(0.,0.,0.)
def get_status( self ):
pass
class Segway_Properties():
def __init__( self ):
self._integrated_wheel_displacement = 24372/(2*math.pi) # countsp / rad
#vv = 39 # countsp/sec / count_velocity --- original
#tv = 19 # countsp/sec / count_velocity --- original
vv = 39 # countsp/sec / count_velocity
tv = 22 # countsp/sec / count_velocity
self._V_vel = vv /self._integrated_wheel_displacement # rad/sec / count_velocity
self._T_vel = tv /self._integrated_wheel_displacement # rad/sec / count_velocity
# w = | a b | * V
# | c d |
a = self._V_vel
b = self._T_vel
c = self._V_vel
d = -self._T_vel
self.A = np.matrix([a,b,c,d]).reshape(2,2)
self.A_inv = 1/(a*b-c*d) * np.matrix([ d, -b, -c, a ]).reshape(2,2)
# w = A*V
# V = A_inv*w
# in addition to what should command the platform velocities should be
self._power_base_battery_voltage = 1/4. #(volt)/count
self._ui_battery_voltage = .0125 #(volt)/count
self._ui_battery_voltage_offset = 1.4 #volts
class Segway( Segway_Properties ):
def __init__( self, side='front' ):
"""side should be 'front' or 'back'"""
Segway_Properties.__init__(self)
self.side = side
self.segway = None
self.connect()
self.pitch_ang = 0
self.pitch_rate = 0
self.yaw_ang = 0
self.yaw_rate = 0
self.LW_vel = 0
self.RW_vel = 0
self.yaw_rate = 0
self.servo_frames = 0
self.integrated_wheel_displacement_left = 0
self.integrated_wheel_displacement_right = 0
self.integrated_for_aft_displacement = 0
self.integrated_yaw_displacement = 0
self.left_motor_torque = 0
self.right_motor_torque = 0
self.operational_mode = 0
self.controller_gain_schedule = 0
self.ui_battery_voltage = 0
self.power_base_battery_voltage = 0
self.velocity_commanded = 0
self.turn_commanded = 0
def connect(self):
buses = usb.busses()
segway_handle_list = []
for bus in buses:
for device in bus.devices:
if device.idVendor == 1027 and device.idProduct == 59177:
h = device.open()
serial_num = int(h.getString(3,10))
if serial_num == 215:
if self.side == 'front':
print 'Connected to front segway'
self.segway = h
self.segway.claimInterface(0)
elif serial_num == 201:
if self.side == 'back':
print 'Connected to rear segway'
self.segway = h
self.segway.claimInterface(0)
else:
raise RuntimeError( 'Unknown_segway connected.' +
' Serial Number is ',serial_num )
def calc_checksum(self, msg):
checksum = 0
for byt in msg:
checksum = (checksum+byt)%65536
checksum_hi = checksum >> 8
checksum &= 0xff
checksum = (checksum+checksum_hi)%65536
checksum_hi = checksum >> 8
checksum &= 0xff
checksum = (checksum+checksum_hi)%65536
checksum = (~checksum+1)&0xff
return checksum
def compose_velocity_cmd(self,linvel,angvel):
byt_hi = 0x04
byt_lo = 0x13
if self.side == 'back': # because the front segway is
linvel = -linvel # turned around
linvel_counts = int(linvel)
angvel_counts = int(angvel)
if abs(linvel_counts)>1176:
print 'connect.compose_velocity_cmd: Linear velocity is too high. counts: %d'%linvel
return []
if abs(angvel_counts)>1024:
print 'connect.compose_velocity_cmd: Angular velocity is too high. counts: %d'%angvel
return []
usb_msg_fixed = [0xf0,0x55,0x00,0x00,0x00,0x00,byt_hi,byt_lo,0x00]
can_vel_msg = [(linvel_counts>>8)&0xff,linvel_counts&0xff,(angvel_counts>>8)&0xff,angvel_counts&0xff,0x00,0x00,0x00,0x00]
msg_send = usb_msg_fixed + can_vel_msg
msg_send.append(self.calc_checksum(msg_send))
return msg_send
def send_command(self, linvel0, angvel0 ):
msg0 = self.compose_velocity_cmd(linvel0,angvel0)
if msg0 == []:
return False
for i in range(1):
self.segway.bulkWrite(0x02,msg0)
def send_wheel_velocities( self, lvel, rvel ):
w = np.matrix([lvel,rvel]).T
V = self.A_inv*w
#print 'V = ',V
xv = V[0,0]
tv = V[1,0]
#print 'Left vel = ',lvel
#print 'Right vel = ',rvel
#print 'Forward command = ',xv
#print 'Turn command = ',tv
return self.send_command( xv, tv )
def parse_usb_cmd(self,msg):
if len(msg) < 18:
return
if self.calc_checksum(msg[:-1]) != msg[-1]:
#got garbage rejecting
return
id = ((msg[4]<<3)|((msg[5]>>5)&7))&0xfff
data = msg[9:17]
if id == 0x400:
# unused
pass
elif id == 0x401:
self.pitch_ang = self._2_bytes( data[0], data[1] )
self.pitch_rate = self._2_bytes( data[2], data[3] )
self.yaw_ang = self._2_bytes( data[4], data[5] )
self.yaw_rate = self._2_bytes( data[6], data[7] )
elif id == 0x402:
self.LW_vel = self._2_bytes( data[0], data[1] )#/self._LW_vel
self.RW_vel = self._2_bytes( data[2], data[3] )#/self._RW_vel
self.yaw_rate = self._2_bytes( data[4], data[5] )
self.servo_frames = self._2_bytes_unsigned( data[6], data[7] )
elif id == 0x403:
self.integrated_wheel_displacement_left = self._4_bytes(data[2],data[3],data[0],data[1])
self.integrated_wheel_displacement_right = self._4_bytes(data[6],data[7],data[4],data[5])
pass
elif id == 0x404:
self.integrated_for_aft_displacement = self._4_bytes(data[2],data[3],data[0],data[1])
self.integrated_yaw_displacement = self._4_bytes(data[6],data[7],data[4],data[5])
elif id == 0x405:
self.left_motor_torque = self._2_bytes( data[0], data[1] )
self.right_motor_torque = self._2_bytes( data[2], data[3] )
elif id == 0x406:
self.operational_mode = self._2_bytes( data[0], data[1] )
self.controller_gain_schedule = self._2_bytes( data[2], data[3] )
self.ui_battery_voltage = self._2_bytes( data[4], data[5] )*self._ui_battery_voltage + self._ui_battery_voltage_offset
self.power_base_battery_voltage = self._2_bytes( data[6], data[7] )*self._power_base_battery_voltage
elif id == 0x407:
self.velocity_commanded = self._2_bytes( data[0], data[1] )#/self._LW_vel
self.turn_commanded = self._2_bytes( data[2], data[3] )
elif msg[1] == 0x00:
# print 'heartbeat id = ',hex(msg[6]),hex(msg[7])
pass
elif id == 0x680:
# CU Status Message
pass
else:
#print 'no message parsed:', hex(id)
pass
def _2_bytes( self,high, low ):
return struct.unpack('>h',chr(high)+chr(low))[0]
def _2_bytes_unsigned( self,high, low ):
return struct.unpack('>H',chr(high)+chr(low))[0]
def _4_bytes( self,highhigh, lowhigh, highlow, lowlow ):
return struct.unpack('>l',chr(highhigh)+chr(lowhigh)+chr(highlow)+chr(lowlow))[0]
def clear_read(self):
rd = self.segway.bulkRead(0x81,1000)
def read(self):
before = time.time()
rd = self.segway.bulkRead(0x81,9*(18+2))
msg = [(a & 0xff) for a in rd]
i=0
while 1:
try:
msg.pop(i*62)
msg.pop(i*62)
i += 1
except IndexError:
break
#find the start
idx1 = msg.index(0xf0)
if msg[idx1+18] != 0xf0:
# if this is not the start of a message get rid of the bad start
msg = msg[idx1+1:]
else:
# we found the start
while len(msg) > 17:
try:
single_msg = msg[idx1:idx1+18]
if (single_msg[1] == 0x55 and single_msg[2] == 0xaa) or single_msg[1] == 0x00:
self.parse_usb_cmd(single_msg)
msg = msg[18:]
except IndexError:
break
def print_feedback( self ):
print 'self.integrated_wheel_displacement_left = ',self.integrated_wheel_displacement_left
print 'self.integrated_wheel_displacement_right = ',self.integrated_wheel_displacement_right
print 'self.LW_vel = ',self.LW_vel
print 'self.RW_vel = ',self.RW_vel
print 'frame = ',self.servo_frames
print 'self.velocity_commanded = ',self.velocity_commanded
print 'self.turn_commanded = ',self.turn_commanded
#print 'self.yaw_rate = ',self.yaw_rate
if __name__ == '__main__':
import segway
seg= segway.Segway()
seg.clear_read()
# send_command_fixed(segway_rear)
rrates = []
lrates = []
for vel in range(31):
linvel = 2000.*(vel)/30 - 1000.
angvel = 0.
start = time.time()
last = start
lastwrite = start
lastread = start
while 1:
# seg.send_command(200,0.0)
# seg.send_wheel_velocities(100.0,100.0)
if time.time() - lastwrite > 0.1:
print 'loop 1',time.time() - start
#seg.send_command( linvel, angvel )
lastwrite = time.time()
#seg.send_platform_velocities( 0,0 )
seg.send_wheel_velocities(1.,1.)
if time.time() - lastread > 0.01:
seg.read()
lastread = time.time()
#seg.print_feedback()
if time.time() - start > 2.0:
break
left_start = seg.integrated_wheel_displacement_left
right_start = seg.integrated_wheel_displacement_right
first_points = time.time()
while 1:
# seg.send_command(200,0.0)
# seg.send_wheel_velocities(100.0,100.0)
if time.time() - lastwrite > 0.1:
print 'loop 1.5',time.time() - start
#seg.send_command( linvel, angvel )
lastwrite = time.time()
#seg.send_platform_velocities( 0,0 )
seg.send_wheel_velocities(1.,1.)
if time.time() - lastread > 0.01:
seg.read()
lastread = time.time()
#seg.print_feedback()
if time.time() - start > 5.0:
break
left_stop = seg.integrated_wheel_displacement_left
right_stop = seg.integrated_wheel_displacement_right
last_points = time.time()
diff = last_points - first_points
print 'Time: ',diff
print 'left rate: ',(left_stop - left_start)/diff
print 'right rate: ',(right_stop - right_start)/diff
rrates.append(((right_stop - right_start)/diff,linvel))
lrates.append(((left_stop - left_start)/diff,linvel))
while 1:
if time.time() - lastread > 0.01:
seg.read()
lastread = time.time()
#seg.print_feedback()
if seg.LW_vel ==0 and seg.RW_vel == 0:
break
print 'rrates:',rrates
print 'lrates:',lrates
import pylab
x = []
y = []
x1 = []
y1 = []
for a, b in rrates:
x.append(b)
y.append(a)
for a, b in lrates:
x1.append(b)
y1.append(a)
pylab.plot(x,y,x1,y1)
pylab.show()
#while 1:
# print 'loop 2'
# seg.read()
#seg.print_feedback()
# print 'time: ', time.time()-start
# if seg.LW_vel == 0 and seg.RW_vel == 0:
# break
# print 'total time: ', time.time()-start
# print 'time to stop: ', time.time()-stop
# msg = []
# while True:
# msg += list(handle_rmp0.bulkRead(0x81,100))
# idx1 = msg.index(0xf0)
# idx2 = msg.index(0xf0,idx1+1)
# if idx2-idx1 == 18:
# single_msg = msg[idx1:idx2]
# if single_msg[1] == 0x55 and single_msg[2] == 0xaa:
# parse_usb_cmd(single_msg)
#
# msg = msg[idx2:]
| [
[
1,
0,
0.0625,
0.0022,
0,
0.66,
0,
856,
0,
1,
0,
0,
856,
0,
0
],
[
1,
0,
0.0647,
0.0022,
0,
0.66,
0.1,
848,
0,
1,
0,
0,
848,
0,
0
],
[
1,
0,
0.0668,
0.0022,
0,
0.6... | [
"import usb",
"import pickle",
"import time",
"import numpy as np",
"import math",
"import struct",
"class Mecanum_Properties():\n def __init__( self ):\n self.r1 = .2032/2. # 8in wheels\n self.r2 = .2032/2. # 8in wheels\n \n self.R = 4*2.54/100 # wheel radius in meters\n ... |
#! /usr/bin/python
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Hai Nguyen (Healthcare Robotics Lab, Georgia Tech.)
# \author Marc Killpack (Healthcare Robotics Lab, Georgia Tech.)
import roslib; roslib.load_manifest('hrl_segway_omni')
from hrl_lib.msg import PlanarBaseVel
from geometry_msgs.msg import Twist
import rospy
import segway
import numpy as np
def callback(cmd):
#print 'segway_node:', cmd.xvel, cmd.yvel, cmd.angular_velocity
mecanum.set_velocity(cmd.xvel, cmd.yvel, cmd.angular_velocity)
def callback_ros(cmd):
#print 'segway_node:', cmd.linear.x, cmd.linear.y, cmd.angular.z
avel = cmd.angular.z * 0.5
avel = np.clip(avel,-0.2,0.2)
mecanum.set_velocity(cmd.linear.x, cmd.linear.y, avel)
rospy.init_node("segway_node", anonymous=False)
rospy.Subscriber("base", PlanarBaseVel, callback, None, 1)
rospy.Subscriber("cmd_vel", Twist, callback_ros, None, 1)
#mecanum = segway.Mecanum(init_ros_node=False)
mecanum = segway.Mecanum()
rospy.spin()
| [
[
1,
0,
0.566,
0.0189,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.566,
0.0189,
0,
0.66,
0.0769,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.5849,
0.0189,
0,
0.66... | [
"import roslib; roslib.load_manifest('hrl_segway_omni')",
"import roslib; roslib.load_manifest('hrl_segway_omni')",
"from hrl_lib.msg import PlanarBaseVel",
"from geometry_msgs.msg import Twist",
"import rospy",
"import segway",
"import numpy as np",
"def callback(cmd):\n #print 'segway_node:', cmd... |
#!/usr/bin/python
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
# \author Cressel Anderson (Healthcare Robotics Lab, Georgia Tech.)
# \author Hai Nguyen (Healthcare Robotics Lab, Georgia Tech.)
import roslib; roslib.load_manifest('force_torque')
import rospy
from hrl_msgs.msg import FloatArray
#import hrl_lib.rutils as ru
import AMTIForce2 as af
import threading
import time
#import rutils as ru
class AMTIForceServer(threading.Thread):
def __init__(self, device_path, str_id):
threading.Thread.__init__(self)
try:
rospy.init_node('AMTIForceServer')
print 'AMTIForceServer: ros is up!'
except rospy.ROSException:
pass
print 'AMTIForceServer: connecting to', device_path
self.force_plate = af.AMTI_force(device_path)
name = 'force_torque_' + str_id
print 'AMTIForceServer: publishing', name, 'with type FloatArray'
self.channel = rospy.Publisher(name, FloatArray, tcp_nodelay=True)
def broadcast(self):
print 'AMTIForceServer: started!'
while not rospy.is_shutdown():
time.sleep(1/5000.0)
self.channel.publish(FloatArray(None, self.force_plate.read().T.tolist()[0]))
#DEPRECATED, use FTClient from ROSFTSensor with id = 0
#def AMTIForceClient():
# return ru.FloatArrayListener('AMTIForceClient', 'force_plate', 100.0)
#import roslib; roslib.load_manifest('force_torque')
#import force_torque.ROSAMTIForce as ft
if __name__ == '__main__':
import optparse
p = optparse.OptionParser()
p.add_option('--path', action='store', default='/dev/robot/force_plate0', type = 'string',
dest='path', help='path to force torque device in (linux)')
p.add_option('--name', action='store', default='ft1', type='string',
dest='name', help='name given to FTSensor')
opt, args = p.parse_args()
server = AMTIForceServer(opt.path, opt.name)
server.broadcast()
| [
[
1,
0,
0.3929,
0.0119,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.3929,
0.0119,
0,
0.66,
0.125,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.4048,
0.0119,
0,
0.6... | [
"import roslib; roslib.load_manifest('force_torque')",
"import roslib; roslib.load_manifest('force_torque')",
"import rospy",
"from hrl_msgs.msg import FloatArray",
"import AMTIForce2 as af",
"import threading",
"import time",
"class AMTIForceServer(threading.Thread):\n def __init__(self, device_pa... |
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
# \author Cressel Anderson (Healthcare Robotics Lab, Georgia Tech.)
# \author Hai Nguyen (Healthcare Robotics Lab, Georgia Tech.)
import time, os, copy
import serial, numpy as np
import threading
from threading import RLock
class AMTI_force:
def __init__(self, dev_name="/dev/robot/force_plate0", broadcast=True):
self.dev_name = dev_name
self.serial_dev = open_serial(dev_name, 57600)
self.offset = None
if not self._reset():
while not self._reset():
time.sleep(50/1000.0)
self.last_value = self._read_once()
def read(self):
reading = self._read_once()
while (reading == self.last_value).all():
time.sleep(8/1000.0)
reading = self._read_once()
return reading
def _reset(self):
self.serial_dev.write('R')
self.serial_dev.flushInput()
self.serial_dev.flushOutput()
self.serial_dev.write('Q')
x = self.serial_dev.read(1)
print 'AMTI_force._reset: resetting.'
return x == 'U'
def _read_once(self):
#Read until succeeds
while True:
x = self.serial_dev.read(24)
if len(x) > 0:
ret, error = stream_to_values(x)
ret[0,0] = 4.448221628254617 * ret[0,0]
ret[1,0] = 4.448221628254617 * ret[1,0]
ret[2,0] = 4.448221628254617 * ret[2,0]
ret[3,0] = 4.448221628254617 * 0.0254 * ret[3,0]
ret[4,0] = 4.448221628254617 * 0.0254 * ret[4,0]
ret[5,0] = 4.448221628254617 * 0.0254 * ret[5,0]
if error:
time.sleep(50/1000.0)
self._reset()
else:
ft_vector = ret
ft_vector[0,0] = -ft_vector[0,0] * 1.8
ft_vector[1,0] = ft_vector[1,0] * 1.7
ft_vector[2,0] = -ft_vector[2,0]
ft_vector[3,0] = -ft_vector[3,0]
ft_vector[5,0] = -ft_vector[5,0]
return ft_vector
COEFF_MAT = np.matrix([[ 0.0032206,-0.0000321,0.0003082,-0.0032960,-0.0000117,-0.0002678,0.0032446,0.0000940,0.0001793,-0.0031230,-0.0000715,-0.0002365],
[ -0.0001470,0.0032134,0.0004389,0.0000222,0.0032134,0.0003946,0.0000684,-0.0031486,0.0000523,-0.0000209,-0.0031797,-0.0001470],
[ -0.0006416,-0.0005812,-0.0087376,-0.0006207,-0.0005215,-0.0086779,-0.0006731,-0.0008607,-0.0087900,-0.0005766,-0.0007237,-0.0084300],
[ 0.0000000,0.0000000,-0.0279669,0.0000000,0.0000000,-0.0269454,0.0000000,0.0000000,0.0281477,0.0000000,0.0000000,0.0268347],
[ 0.0000000,0.0000000,0.0273877,0.0000000,0.0000000,-0.0269034,0.0000000,0.0000000,0.0278664,0.0000000,0.0000000,-0.0272117],
[ -0.0123918,0.0124854,0.0000917,0.0126818,-0.0124854,0.0000911,0.0124843,-0.0122338,0.0000923,-0.0120165,0.0123544,0.0000885]])
def open_serial(dev_name, baudrate):
serial_dev = serial.Serial(dev_name, timeout=4.)
serial_dev.setBaudrate(baudrate)
serial_dev.setParity('N')
serial_dev.setStopbits(1)
serial_dev.open()
serial_dev.flushOutput()
serial_dev.flushInput()
serial_dev.write('R')
time.sleep(1.)
if(serial_dev == None):
raise RuntimeError("AMTI_force: Serial port not found!\n")
return serial_dev
def stream_to_values(data):
val = np.matrix(np.zeros((12,1)))
val[0,0] = ord(data[0]) + 256*(ord(data[1])%16)
val[1,0] = ord(data[2]) + 256*(ord(data[3])%16)
val[2,0] = ord(data[4]) + 256*(ord(data[5])%16)
val[3,0] = ord(data[6]) + 256*(ord(data[7])%16)
val[4,0] = ord(data[8]) + 256*(ord(data[9])%16)
val[5,0] = ord(data[10]) + 256*(ord(data[11])%16)
val[6,0] = ord(data[12]) + 256*(ord(data[13])%16)
val[7,0] = ord(data[14]) + 256*(ord(data[15])%16)
val[8,0] = ord(data[16]) + 256*(ord(data[17])%16)
val[9,0] = ord(data[18]) + 256*(ord(data[19])%16)
val[10,0] = ord(data[20]) + 256*(ord(data[21])%16)
val[11,0] = ord(data[22]) + 256*(ord(data[23])%16)
error = ord(data[1])/16 != 0 or ord(data[3])/16 != 1 or ord(data[5])/16 != 2 or \
ord(data[7])/16 != 3 or ord(data[9])/16 != 4 or ord(data[11])/16 != 5 or\
ord(data[13])/16 != 6 or ord(data[15])/16 != 7 or ord(data[17])/16 != 8 or \
ord(data[19])/16 != 9 or ord(data[21])/16 != 10 or ord(data[23])/16 != 11
return COEFF_MAT * val, error
| [
[
1,
0,
0.2462,
0.0077,
0,
0.66,
0,
654,
0,
3,
0,
0,
654,
0,
0
],
[
1,
0,
0.2538,
0.0077,
0,
0.66,
0.1429,
601,
0,
2,
0,
0,
601,
0,
0
],
[
1,
0,
0.2615,
0.0077,
0,
... | [
"import time, os, copy",
"import serial, numpy as np",
"import threading",
"from threading import RLock",
"class AMTI_force:\n def __init__(self, dev_name=\"/dev/robot/force_plate0\", broadcast=True):\n self.dev_name = dev_name\n self.serial_dev = open_serial(dev_name, 57600)\n sel... |
import roslib; roslib.load_manifest('hrl_lib')
import rospy
import std_srvs.srv as srv
from hrl_msgs.msg import FloatArray
import time
def cb( msg ):
print 'Received msg: ', msg, '\n\tType: ', msg.__class__
return
x = 3.0
rospy.init_node('trial_subscriber')
sub = rospy.Subscriber('trial_pub', FloatArray, cb)
while not rospy.is_shutdown():
rospy.spin()
| [
[
1,
0,
0.0588,
0.0588,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0588,
0.0588,
0,
0.66,
0.1,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.1176,
0.0588,
0,
0.66,... | [
"import roslib; roslib.load_manifest('hrl_lib')",
"import roslib; roslib.load_manifest('hrl_lib')",
"import rospy",
"import std_srvs.srv as srv",
"from hrl_msgs.msg import FloatArray",
"import time",
"def cb( msg ):\n print('Received msg: ', msg, '\\n\\tType: ', msg.__class__)\n return",
" pr... |
#!/usr/bin/python
import roslib
roslib.load_manifest('force_torque')
import rospy
from geometry_msgs.msg import Vector3Stamped
from threading import RLock
## 1D kalman filter update.
def kalman_update(xhat, P, Q, R, z):
#time update
xhatminus = xhat
Pminus = P + Q
#measurement update
K = Pminus / (Pminus + R)
xhat = xhatminus + K * (z-xhatminus)
P = (1-K) * Pminus
return xhat, P
class FTRelay:
def __init__(self):
self.lock = RLock()
self.fresh = False
def set_ft(self, value, time_acquired):
self.lock.acquire()
self.data = value, time_acquired
self.fresh = True
self.lock.release()
#print 'got', value, time_acquired
def get_msg(self):
r = None
self.lock.acquire()
if self.fresh:
self.fresh = False
r = self.data
self.lock.release()
return r
def FTread_to_Force( ftval, frame_id ):
retval = Vector3Stamped()
retval.header.stamp = rospy.rostime.get_rostime()
retval.header.frame_id = frame_id
retval.vector.x = ftval[0]
retval.vector.y = ftval[1]
retval.vector.z = ftval[2]
return retval
if __name__ == '__main__':
import roslib; roslib.load_manifest('force_torque')
import rospy
from force_torque.srv import *
from hrl_msgs.msg import FloatArray as FloatArray
import hrl_lib.rutils as ru
import time
import force_torque.FTSensor as ftc
import numpy as np
import optparse
p = optparse.OptionParser()
p.add_option('--name', action='store', default='ft1', type='string',
dest='name', help='name given to FTSensor')
opt, args = p.parse_args()
node_name = 'FTRelay_' + opt.name
ft_channel_name = 'force_torque_' + opt.name
service_name = node_name + '_set_ft'
print node_name + ': serving service', service_name
ftserver = FTRelay()
rospy.init_node(node_name)
rospy.Service(service_name, StringService,
ru.wrap(ftserver.set_ft, ['value', 'time'],
response=StringServiceResponse))
channel = rospy.Publisher(ft_channel_name, FloatArray, tcp_nodelay=True)
channel2 = rospy.Publisher(ft_channel_name + '_raw', FloatArray, tcp_nodelay=True)
chan_vec3 = rospy.Publisher(ft_channel_name + '_Vec3', Vector3Stamped, tcp_nodelay=True)
print node_name + ': publishing on channel', ft_channel_name
P_force = [1., 1., 1.]
xhat_force = [0., 0., 0., 0., 0., 0.]
while not rospy.is_shutdown():
msg = ftserver.get_msg()
if msg is not None:
data, tme = msg
ftvalue = ftc.binary_to_ft(data)
ftvalue = np.array(ftvalue)
for i in range(3):
xhat, p = kalman_update(xhat_force[i], P_force[i],
1e-3, 0.04, ftvalue[i])
P_force[i] = p
xhat_force[i] = xhat
#ftvalue[i] = xhat
xhat_force[3] = ftvalue[3]
xhat_force[4] = ftvalue[4]
xhat_force[5] = ftvalue[5]
ftvalue = ftvalue.tolist()
channel.publish(FloatArray(rospy.Header(stamp=rospy.Time.from_seconds(tme)),
xhat_force))
channel2.publish(FloatArray(rospy.Header(stamp=rospy.Time.from_seconds(tme)), ftvalue))
chan_vec3.publish( FTread_to_Force( ftvalue, opt.name ))
#times.append(time.time())
#else:
# time.sleep(1/5000.0)
time.sleep(1/5000.0)
#import pylab as pl
#import numpy as np
#a = np.array(times)
#pl.plot(a[1:] - a[:-1], '.')
#pl.show()
| [
[
1,
0,
0.0159,
0.0079,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0238,
0.0079,
0,
0.66,
0.125,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0317,
0.0079,
0,
0.6... | [
"import roslib",
"roslib.load_manifest('force_torque')",
"import rospy",
"from geometry_msgs.msg import Vector3Stamped",
"from threading import RLock",
"def kalman_update(xhat, P, Q, R, z):\n #time update\n xhatminus = xhat\n Pminus = P + Q\n #measurement update\n K = Pminus / (Pminus + R)\... |
#!/usr/bin/python
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
# \author Cressel Anderson (Healthcare Robotics Lab, Georgia Tech.)
# \author Hai Nguyen (Healthcare Robotics Lab, Georgia Tech.)
import roslib; roslib.load_manifest('force_torque')
import rospy
import hrl_lib.rutils as ru
import hrl_lib.util as ut
from hrl_msgs.msg import FloatArray
from geometry_msgs.msg import WrenchStamped
import numpy as np
##
# Corresponding client class
class FTClient(ru.GenericListener):
def __init__(self, topic_name, netft=False):
if netft:
def msg_converter(msg):
fx, fy, fz = msg.wrench.force.x, msg.wrench.force.y, msg.wrench.force.z
tx, ty, tz = msg.wrench.torque.x, msg.wrench.torque.y, msg.wrench.torque.z
msg_time = rospy.get_time()
return -np.matrix([fx, fy, fz, tx, ty, tz]).T, msg_time
msg_type=WrenchStamped
else:
def msg_converter(msg):
m = np.matrix(msg.data, 'f').T
msg_time = msg.header.stamp.to_time()
return m, msg_time
msg_type = FloatArray
ru.GenericListener.__init__(self, 'FTClient', msg_type,
topic_name, 50.0,
message_extractor = msg_converter,
queue_size = None)
self.bias_val = np.matrix([0, 0, 0, 0, 0, 0.]).T
##
# Read a force torque value
# @param avg how many force torque value to average
# @param without_bias
# @param fresh
# @param with_time_stamp
# @return an averaged force torque value (6x1 matrix)
def read(self, avg=1, without_bias=False, fresh=False, with_time_stamp=False):
assert(avg > 0)
if avg > 1:
fresh = True
if with_time_stamp:
raise RuntimeError('Can\'t request averaging and timestamping at the same time')
rs = []
for i in range(avg):
if fresh:
r, msg_time = ru.GenericListener.read(self, allow_duplication=False, willing_to_wait=True)
else:
r, msg_time = ru.GenericListener.read(self, allow_duplication=True, willing_to_wait=False)
rs.append(r)
readings = ut.list_mat_to_mat(rs, axis=1)
if not without_bias:
#print 'readiings.mean(1)', readings.mean(1)
#print 'self.bias_val', self.bias_val
ret = readings.mean(1) - self.bias_val
else:
ret = readings.mean(1)
if with_time_stamp:
return ret, msg_time
else:
return ret
def bias(self):
print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
print 'BIASING FT'
print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
b_list = []
for i in range(20):
r, msg_time = ru.GenericListener.read(self, allow_duplication=False, willing_to_wait=True)
b_list.append(r)
if b_list[0] != None:
r = np.mean(np.column_stack(b_list), 1)
self.bias_val = r
print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
print 'DONE biasing ft'
print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
if __name__ == '__main__':
import optparse
import time
p = optparse.OptionParser()
p.add_option('-t', action='store', default='force_torque_ft1', type='string',
dest='topic', help='which topic to listen to (default force_torque_ft1)')
p.add_option('--netft', action='store_true', dest='netft',
help='is this a NetFT sensor')
opt, args = p.parse_args()
client = FTClient(opt.topic, opt.netft)
client.bias()
while not rospy.is_shutdown():
el = client.read()
if el != None:
#print np.linalg.norm(el.T)
f = el.A1
print ' %.2f %.2f %.2f'%(f[0], f[1], f[2])
time.sleep(1/100.0)
| [
[
1,
0,
0.2162,
0.0068,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.2162,
0.0068,
0,
0.66,
0.1111,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.223,
0.0068,
0,
0.6... | [
"import roslib; roslib.load_manifest('force_torque')",
"import roslib; roslib.load_manifest('force_torque')",
"import rospy",
"import hrl_lib.rutils as ru",
"import hrl_lib.util as ut",
"from hrl_msgs.msg import FloatArray",
"from geometry_msgs.msg import WrenchStamped",
"import numpy as np",
"class... |
#!/usr/bin/python
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
# \author Cressel Anderson (Healthcare Robotics Lab, Georgia Tech.)
# \author Hai Nguyen (Healthcare Robotics Lab, Georgia Tech.)
import roslib; roslib.load_manifest('force_torque')
import rospy
from hrl_msgs.msg import FloatArray
#import hrl_lib.rutils as ru
import AMTIForce2 as af
import threading
import time
#import rutils as ru
class AMTIForceServer(threading.Thread):
def __init__(self, device_path, str_id):
threading.Thread.__init__(self)
try:
rospy.init_node('AMTIForceServer')
print 'AMTIForceServer: ros is up!'
except rospy.ROSException:
pass
print 'AMTIForceServer: connecting to', device_path
self.force_plate = af.AMTI_force(device_path)
name = 'force_torque_' + str_id
print 'AMTIForceServer: publishing', name, 'with type FloatArray'
self.channel = rospy.Publisher(name, FloatArray, tcp_nodelay=True)
def broadcast(self):
print 'AMTIForceServer: started!'
while not rospy.is_shutdown():
time.sleep(1/5000.0)
self.channel.publish(FloatArray(None, self.force_plate.read().T.tolist()[0]))
#DEPRECATED, use FTClient from ROSFTSensor with id = 0
#def AMTIForceClient():
# return ru.FloatArrayListener('AMTIForceClient', 'force_plate', 100.0)
#import roslib; roslib.load_manifest('force_torque')
#import force_torque.ROSAMTIForce as ft
if __name__ == '__main__':
import optparse
p = optparse.OptionParser()
p.add_option('--path', action='store', default='/dev/robot/force_plate0', type = 'string',
dest='path', help='path to force torque device in (linux)')
p.add_option('--name', action='store', default='ft1', type='string',
dest='name', help='name given to FTSensor')
opt, args = p.parse_args()
server = AMTIForceServer(opt.path, opt.name)
server.broadcast()
| [
[
1,
0,
0.3929,
0.0119,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.3929,
0.0119,
0,
0.66,
0.125,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.4048,
0.0119,
0,
0.6... | [
"import roslib; roslib.load_manifest('force_torque')",
"import roslib; roslib.load_manifest('force_torque')",
"import rospy",
"from hrl_msgs.msg import FloatArray",
"import AMTIForce2 as af",
"import threading",
"import time",
"class AMTIForceServer(threading.Thread):\n def __init__(self, device_pa... |
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
# \author Cressel Anderson (Healthcare Robotics Lab, Georgia Tech.)
# \author Hai Nguyen (Healthcare Robotics Lab, Georgia Tech.)
| [] | [] |
import roslib; roslib.load_manifest('hrl_lib')
import rospy
import std_srvs.srv as srv
from hrl_msgs.msg import FloatArray
import time
x = 3.0
rospy.init_node('trial_publisher')
pub = rospy.Publisher( 'trial_pub', FloatArray)
while not rospy.is_shutdown():
x += 0.1
fa = FloatArray()
fa.data = [ x, x+1.0, x+2.0 ]
pub.publish( fa )
time.sleep( 0.3 )
| [
[
1,
0,
0.0625,
0.0625,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0625,
0.0625,
0,
0.66,
0.1111,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.125,
0.0625,
0,
0.6... | [
"import roslib; roslib.load_manifest('hrl_lib')",
"import roslib; roslib.load_manifest('hrl_lib')",
"import rospy",
"import std_srvs.srv as srv",
"from hrl_msgs.msg import FloatArray",
"import time",
"x = 3.0",
"rospy.init_node('trial_publisher')",
"pub = rospy.Publisher( 'trial_pub', FloatArray)",
... |
#!/usr/bin/python
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
# \author Cressel Anderson (Healthcare Robotics Lab, Georgia Tech.)
# \author Hai Nguyen (Healthcare Robotics Lab, Georgia Tech.)
import roslib; roslib.load_manifest('force_torque')
import rospy
import hrl_lib.rutils as ru
import hrl_lib.util as ut
from hrl_msgs.msg import FloatArray
from geometry_msgs.msg import WrenchStamped
import numpy as np
##
# Corresponding client class
class FTClient(ru.GenericListener):
def __init__(self, topic_name, netft=False):
if netft:
def msg_converter(msg):
fx, fy, fz = msg.wrench.force.x, msg.wrench.force.y, msg.wrench.force.z
tx, ty, tz = msg.wrench.torque.x, msg.wrench.torque.y, msg.wrench.torque.z
msg_time = rospy.get_time()
return -np.matrix([fx, fy, fz, tx, ty, tz]).T, msg_time
msg_type=WrenchStamped
else:
def msg_converter(msg):
m = np.matrix(msg.data, 'f').T
msg_time = msg.header.stamp.to_time()
return m, msg_time
msg_type = FloatArray
ru.GenericListener.__init__(self, 'FTClient', msg_type,
topic_name, 50.0,
message_extractor = msg_converter,
queue_size = None)
self.bias_val = np.matrix([0, 0, 0, 0, 0, 0.]).T
##
# Read a force torque value
# @param avg how many force torque value to average
# @param without_bias
# @param fresh
# @param with_time_stamp
# @return an averaged force torque value (6x1 matrix)
def read(self, avg=1, without_bias=False, fresh=False, with_time_stamp=False):
assert(avg > 0)
if avg > 1:
fresh = True
if with_time_stamp:
raise RuntimeError('Can\'t request averaging and timestamping at the same time')
rs = []
for i in range(avg):
if fresh:
r, msg_time = ru.GenericListener.read(self, allow_duplication=False, willing_to_wait=True)
else:
r, msg_time = ru.GenericListener.read(self, allow_duplication=True, willing_to_wait=False)
rs.append(r)
readings = ut.list_mat_to_mat(rs, axis=1)
if not without_bias:
#print 'readiings.mean(1)', readings.mean(1)
#print 'self.bias_val', self.bias_val
ret = readings.mean(1) - self.bias_val
else:
ret = readings.mean(1)
if with_time_stamp:
return ret, msg_time
else:
return ret
def bias(self):
print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
print 'BIASING FT'
print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
b_list = []
for i in range(20):
r, msg_time = ru.GenericListener.read(self, allow_duplication=False, willing_to_wait=True)
b_list.append(r)
if b_list[0] != None:
r = np.mean(np.column_stack(b_list), 1)
self.bias_val = r
print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
print 'DONE biasing ft'
print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
if __name__ == '__main__':
import optparse
import time
p = optparse.OptionParser()
p.add_option('-t', action='store', default='force_torque_ft1', type='string',
dest='topic', help='which topic to listen to (default force_torque_ft1)')
p.add_option('--netft', action='store_true', dest='netft',
help='is this a NetFT sensor')
opt, args = p.parse_args()
client = FTClient(opt.topic, opt.netft)
client.bias()
while not rospy.is_shutdown():
el = client.read()
if el != None:
#print np.linalg.norm(el.T)
f = el.A1
print ' %.2f %.2f %.2f'%(f[0], f[1], f[2])
time.sleep(1/100.0)
| [
[
1,
0,
0.2162,
0.0068,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.2162,
0.0068,
0,
0.66,
0.1111,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.223,
0.0068,
0,
0.6... | [
"import roslib; roslib.load_manifest('force_torque')",
"import roslib; roslib.load_manifest('force_torque')",
"import rospy",
"import hrl_lib.rutils as ru",
"import hrl_lib.util as ut",
"from hrl_msgs.msg import FloatArray",
"from geometry_msgs.msg import WrenchStamped",
"import numpy as np",
"class... |
#!/usr/bin/python
import roslib
roslib.load_manifest('force_torque')
import rospy
from geometry_msgs.msg import Vector3Stamped
from threading import RLock
## 1D kalman filter update.
def kalman_update(xhat, P, Q, R, z):
#time update
xhatminus = xhat
Pminus = P + Q
#measurement update
K = Pminus / (Pminus + R)
xhat = xhatminus + K * (z-xhatminus)
P = (1-K) * Pminus
return xhat, P
class FTRelay:
def __init__(self):
self.lock = RLock()
self.fresh = False
def set_ft(self, value, time_acquired):
self.lock.acquire()
self.data = value, time_acquired
self.fresh = True
self.lock.release()
#print 'got', value, time_acquired
def get_msg(self):
r = None
self.lock.acquire()
if self.fresh:
self.fresh = False
r = self.data
self.lock.release()
return r
def FTread_to_Force( ftval, frame_id ):
retval = Vector3Stamped()
retval.header.stamp = rospy.rostime.get_rostime()
retval.header.frame_id = frame_id
retval.vector.x = ftval[0]
retval.vector.y = ftval[1]
retval.vector.z = ftval[2]
return retval
if __name__ == '__main__':
import roslib; roslib.load_manifest('force_torque')
import rospy
from force_torque.srv import *
from hrl_msgs.msg import FloatArray as FloatArray
import hrl_lib.rutils as ru
import time
import force_torque.FTSensor as ftc
import numpy as np
import optparse
p = optparse.OptionParser()
p.add_option('--name', action='store', default='ft1', type='string',
dest='name', help='name given to FTSensor')
opt, args = p.parse_args()
node_name = 'FTRelay_' + opt.name
ft_channel_name = 'force_torque_' + opt.name
service_name = node_name + '_set_ft'
print node_name + ': serving service', service_name
ftserver = FTRelay()
rospy.init_node(node_name)
rospy.Service(service_name, StringService,
ru.wrap(ftserver.set_ft, ['value', 'time'],
response=StringServiceResponse))
channel = rospy.Publisher(ft_channel_name, FloatArray, tcp_nodelay=True)
channel2 = rospy.Publisher(ft_channel_name + '_raw', FloatArray, tcp_nodelay=True)
chan_vec3 = rospy.Publisher(ft_channel_name + '_Vec3', Vector3Stamped, tcp_nodelay=True)
print node_name + ': publishing on channel', ft_channel_name
P_force = [1., 1., 1.]
xhat_force = [0., 0., 0., 0., 0., 0.]
while not rospy.is_shutdown():
msg = ftserver.get_msg()
if msg is not None:
data, tme = msg
ftvalue = ftc.binary_to_ft(data)
ftvalue = np.array(ftvalue)
for i in range(3):
xhat, p = kalman_update(xhat_force[i], P_force[i],
1e-3, 0.04, ftvalue[i])
P_force[i] = p
xhat_force[i] = xhat
#ftvalue[i] = xhat
xhat_force[3] = ftvalue[3]
xhat_force[4] = ftvalue[4]
xhat_force[5] = ftvalue[5]
ftvalue = ftvalue.tolist()
channel.publish(FloatArray(rospy.Header(stamp=rospy.Time.from_seconds(tme)),
xhat_force))
channel2.publish(FloatArray(rospy.Header(stamp=rospy.Time.from_seconds(tme)), ftvalue))
chan_vec3.publish( FTread_to_Force( ftvalue, opt.name ))
#times.append(time.time())
#else:
# time.sleep(1/5000.0)
time.sleep(1/5000.0)
#import pylab as pl
#import numpy as np
#a = np.array(times)
#pl.plot(a[1:] - a[:-1], '.')
#pl.show()
| [
[
1,
0,
0.0159,
0.0079,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0238,
0.0079,
0,
0.66,
0.125,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0317,
0.0079,
0,
0.6... | [
"import roslib",
"roslib.load_manifest('force_torque')",
"import rospy",
"from geometry_msgs.msg import Vector3Stamped",
"from threading import RLock",
"def kalman_update(xhat, P, Q, R, z):\n #time update\n xhatminus = xhat\n Pminus = P + Q\n #measurement update\n K = Pminus / (Pminus + R)\... |
import pygame
import pygame.locals
import numpy as np
import time
import copy
#------ Slider class is code copied from the internet. (http://www.pygame.org/project/668/)
class Slider(object):
#Constructs the object
def __init__(self, pos, value=0):
self.pos = pos
self.size = (275,15)
self.bar = pygame.Surface((275, 15))
self.bar.fill((200, 200, 200))
self.slider = pygame.Surface((20, 15))
self.slider.fill((230, 230, 230))
pygame.draw.rect(self.bar, (0, 0, 0), (0, 0, 275, 15), 2)
pygame.draw.rect(self.slider, (0, 0, 0), (-1, -1, 20, 15), 2)
self.slider.set_at((19, 14), (0, 0, 0))
self.brect = self.bar.get_rect(topleft = pos)
self.srect = self.slider.get_rect(topleft = pos)
self.srect.left = value+pos[0]
self.clicked = False
self.value = value
self.font_size = 15
self.font = pygame.font.SysFont("Times New Roman", self.font_size)
self.text = ''
def set_text(self, text):
''' set the text to be displayed below the slider
'''
self.text = text
#Called once every frame
def update(self):
mousebutton = pygame.mouse.get_pressed()
cursor = pygame.locals.Rect(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1], 1, 1)
if cursor.colliderect(self.brect):
if mousebutton[0]:
self.clicked = True
else:
self.clicked = False
if not mousebutton[0]:
self.clicked = False
if self.clicked:
self.srect.center = cursor.center
self.srect.clamp_ip(self.brect)
self.value = self.srect.left - self.brect.left
#Draws the slider
def render(self, surface):
surface.blit(self.bar, self.brect)
surface.blit(self.slider, self.srect)
ren = self.font.render(self.text,1,(0,0,0))
surface.blit(ren, (self.pos[0], self.pos[1]+self.font_size+2))
| [
[
1,
0,
0.0169,
0.0169,
0,
0.66,
0,
87,
0,
1,
0,
0,
87,
0,
0
],
[
1,
0,
0.0339,
0.0169,
0,
0.66,
0.2,
515,
0,
1,
0,
0,
515,
0,
0
],
[
1,
0,
0.0508,
0.0169,
0,
0.66,... | [
"import pygame",
"import pygame.locals",
"import numpy as np",
"import time",
"import copy",
"class Slider(object):\n\n #Constructs the object\n def __init__(self, pos, value=0):\n self.pos = pos\n self.size = (275,15)\n\n self.bar = pygame.Surface((275, 15))",
" def __init... |
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
# functions to use scans from hokuyos.
import roslib
roslib.load_manifest('hrl_hokuyo')
import pygame
import pygame.locals
import hokuyo_scan as hs
import hrl_lib.transforms as tr
import hrl_lib.util as ut
#import util as uto
import math, numpy as np
import scipy.ndimage as ni
import pylab as pl
import sys, time
import optparse
import copy
import pygame_utils as pu
# Need to switch to Willow's OpenCV 2.0 python bindings at some point of time.
# from opencv.cv import *
# from opencv.highgui import *
from ctypes import POINTER
MAX_DIST=1.0
# pixel coordinates of origin
org_x,org_y = 320,240+150
color_list = [(255,255,0),(255,0,0),(0,255,255),(0,255,0),(0,0,255),(0,100,100),(100,100,0),
(100,0,100),(100,200,100),(200,100,100),(100,100,200),(100,0,200),(0,200,100),
(0,0,0),(0,100,200),(200,0,100),(100,0,100),(255,152,7) ]
def angle_to_index(scan, angle):
''' returns index corresponding to angle (radians).
'''
return int(min(scan.n_points-1, max(0.,int(round((angle-scan.start_angle)/scan.angular_res)))))
def index_to_angle(scan, index):
''' returns angle (radians) corresponding to index.
'''
return scan.start_angle+index*scan.angular_res
def get_xy_map(scan,start_angle=math.radians(-360),end_angle=math.radians(360),reject_zero_ten=True,max_dist=np.Inf,min_dist=-np.Inf,sigmoid_hack=False, get_intensities=False):
""" start_angle - starting angle for points to be considered (hokuyo coord)
end_angle - ending angle in hokuyo coord frame.
scan - object of class HokuyoScan
reject_zero_ten - ignore points at 0 or 10. meters
returns - 2xN matrix, if get_intensities=True returns (2xN matrix, 1xN matrix)
"""
start_index = angle_to_index(scan,start_angle)
end_index = angle_to_index(scan,end_angle)
if sigmoid_hack:
#------ sigmoid hack to increase ranges of points with small range(<0.3) ----
# short_range_idxs = np.where(scan.ranges<0.3)
# scan.ranges[short_range_idxs] = scan.ranges[short_range_idxs]*1.05
#--- test1
# scan.ranges = np.multiply(scan.ranges, 1+(1-np.divide(1.,1+np.power(np.e,-5*(scan.ranges-0.3))))*0.1)
#--- test2
scan.ranges = np.multiply(scan.ranges, 1+(1-np.divide(1.,1+np.power(np.e,-5*(scan.ranges-0.2))))*0.20)
#--- test3
# scan.ranges = np.multiply(scan.ranges, 1+(1-np.divide(1.,1+np.power(np.e,-5*(scan.ranges-0.3))))*0.2)
#--- test4
# scan.ranges = np.multiply(scan.ranges, 1+(1-np.divide(1.,1+np.power(np.e,-5*(scan.ranges-0.25))))*0.15)
#------------------
xy_map = np.matrix(np.row_stack((np.multiply(scan.ranges,np.cos(scan.angles)),
np.multiply(scan.ranges,np.sin(scan.angles))*-1)))
sub_range = scan.ranges[:,start_index:end_index+1]
keep_condition = np.multiply(sub_range<=max_dist,sub_range>=min_dist)
if reject_zero_ten == True:
keep_condition = np.multiply(keep_condition,np.multiply(sub_range > 0.01,sub_range <= 10.))
xy_map = xy_map[:,start_index:end_index+1]
idxs = np.where(keep_condition)
xy_map = np.row_stack((xy_map[idxs],xy_map[idxs[0]+1,idxs[1]]))
if get_intensities == True:
intensities = scan.intensities[:,start_index:end_index+1]
intensities = intensities[idxs]
return xy_map, intensities
else:
return xy_map
def connected_components(p, dist_threshold):
''' p - 2xN numpy matrix of euclidean points points (indices give neighbours).
dist_threshold - max distance between two points in the same connected component.
typical value is .02 meters
returns a list of (p1,p2, p1_index, p2_index): (start euclidean point, end euclidean point, start index, end index)
p1 and p2 are 2X1 matrices
'''
nPoints = p.shape[1]
q = p[:,0:nPoints-1]
r = p[:,1:nPoints]
diff = r-q
dists = ut.norm(diff).T
idx = np.where(dists>dist_threshold) # boundaries of the connected components
end_list = idx[0].A1.tolist()
end_list.append(nPoints-1)
cc_list = []
start = 0
for i in end_list:
cc_list.append((p[:,start], p[:,i], start, i))
start = i+1
return cc_list
def find_objects(scan, max_dist, max_size, min_size, min_angle, max_angle,
connect_dist_thresh, all_pts=False):
''' max_dist - objects with centroid greater than max_dist will be ignored. (meters)
max_size - objects greater than this are ignored. (meters)
min_size - smaller than this are ignored (meters)
min_angle, max_angle - part of scan to consider.
connect_dist_thresh - points in scan greater than this will be treated as separate
connected components.
all_pts == True:
returns [ np matrix: 2xN1, 2xN2 ...] each matrix consists of all the points in the object.
all_pts == False:
returns list of (p,q,centroid): (end points,object centroid (2x1 matrices.))
'''
xy_map = get_xy_map(scan,min_angle,max_angle)
cc_list = connected_components(xy_map,connect_dist_thresh)
object_list = []
all_pts_list = []
for i,(p,q,p_idx,q_idx) in enumerate(cc_list):
object_pts = xy_map[:,p_idx:q_idx+1]
centroid = object_pts.sum(1)/(q_idx-p_idx+1)
size = np.linalg.norm(p-q)
if size>max_size:
continue
if size<min_size:
continue
if np.linalg.norm(centroid) > max_dist:
continue
object_list.append((p,q,centroid))
all_pts_list.append(object_pts)
if all_pts == True:
return all_pts_list
else:
return object_list
def find_closest_object_point(scan, pt_interest=np.matrix([0.,0.]).T, min_angle=math.radians(-60),
max_angle=math.radians(60),max_dist=0.6,min_size=0.01,max_size=0.3):
''' returns 2x1 matrix - centroid of connected component in hokuyo frame closest to pt_interest
pt_interest - 2x1 matrix in hokuyo coord frame.
None if no object found.
'''
obj_list = find_objects(scan,max_dist,max_size,min_size,min_angle,max_angle,
connect_dist_thresh=0.02, all_pts=True)
if obj_list == []:
return None
min_dist_list = []
for pts in obj_list:
min_dist_list.append(np.min(ut.norm(pts-pt_interest)))
min_idx = np.argmin(np.matrix(min_dist_list))
return obj_list[min_idx].mean(1)
def remove_graze_effect(ranges, angles, skip=1, graze_angle_threshold=math.radians(169.)):
''' ranges,angles - 1xN numpy matrix
skip - which two rays to consider.
this function changes ranges.
'''
nPoints = ranges.shape[1]
p = ranges[:,0:nPoints-(1+skip)]
q = ranges[:,(1+skip):nPoints]
d_mat = np.abs(p-q)
angles_diff = np.abs(angles[:,(1+skip):nPoints]-angles[:,0:nPoints-(1+skip)])
l_mat = np.max(np.row_stack((p,q)),0)
l_mat = np.multiply(l_mat,np.sin(angles_diff))/math.sin(graze_angle_threshold)
thresh_exceed = d_mat>l_mat
l1_greater = p>q
idx_remove_1 = np.where(np.all(np.row_stack((thresh_exceed,l1_greater)),0))
idx_remove_2 = np.where(np.all(np.row_stack((thresh_exceed,1-l1_greater)),0))
# print 'idx_remove_1:', idx_remove_1
p[idx_remove_1] = 1000.
q[idx_remove_2] = 1000.
def remove_graze_effect_scan(scan, graze_angle_threshold=math.radians(169.)):
''' changes scan
'''
remove_graze_effect(scan.ranges,scan.angles,1,graze_angle_threshold)
def subtract_scans(scan2,scan1,threshold=0.01):
if scan1.ranges.shape != scan2.ranges.shape:
print 'hokuyo_processing.subtract_scans: the two scan.ranges have different shapes.'
print 'remember to pass remove_graze_effect = False'
print 'Exiting...'
sys.exit()
diff_range = scan2.ranges-scan1.ranges
idxs = np.where(np.abs(diff_range)<threshold)
#idxs = np.where(np.abs(diff_range)<0.04)
# idxs = np.where(np.abs(diff_range)<0.01)
# idxs = np.where(np.abs(diff_range)<0.005)
hscan = hs.HokuyoScan(scan2.hokuyo_type,scan2.angular_res,
scan2.max_range,scan2.min_range,
scan2.start_angle,scan2.end_angle)
hscan.ranges = copy.copy(scan2.ranges)
hscan.ranges[idxs] = 0.
return hscan
def find_door(start_pts_list,end_pts_list,pt_interest=None):
''' returns [p1x,p1y], [p2x,p2y] ([],[] if no door found)
returns line closest to the pt_interest.
pt_interest - 2x1 matrix
'''
if start_pts_list == []:
return [],[]
# print 'start_pts_list,end_pts_list',start_pts_list,end_pts_list
start_pts = np.matrix(start_pts_list).T
end_pts = np.matrix(end_pts_list).T
line_vecs = end_pts-start_pts
line_vecs_ang = np.arctan2(line_vecs[1,:],line_vecs[0,:])
idxs = np.where(np.add(np.multiply(line_vecs_ang>math.radians(45),
line_vecs_ang<math.radians(135)),
np.multiply(line_vecs_ang<math.radians(-45),
line_vecs_ang>math.radians(-135))
) > 0
)[1].A1.tolist()
if idxs == []:
return [],[]
start_pts = start_pts[:,idxs]
end_pts = end_pts[:,idxs]
# print 'start_pts,end_pts',start_pts.A1.tolist(),end_pts.A1.tolist()
if pt_interest == None:
print 'hokuyo_processing.find_door: pt_interest in None so returning the longest line.'
length = ut.norm(end_pts-start_pts)
longest_line_idx = np.argmax(length)
vec_door = (end_pts-start_pts)[:,longest_line_idx]
return start_pts[:,longest_line_idx].A1.tolist(),end_pts[:,longest_line_idx].A1.tolist()
else:
v = end_pts-start_pts
q_dot_v = pt_interest.T*v
p1_dot_v = np.sum(np.multiply(start_pts,v),0)
v_dot_v = ut.norm(v)
lam = np.divide((q_dot_v-p1_dot_v),v_dot_v)
r = start_pts + np.multiply(lam,v)
dist = ut.norm(pt_interest-r)
edge_idxs = np.where(np.multiply(lam>1.,lam<0.))[1].A1.tolist()
min_end_dist = np.minimum(ut.norm(start_pts-pt_interest),ut.norm(end_pts-pt_interest))
dist[:,edge_idxs] = min_end_dist[:,edge_idxs]
# dist - distance of closest point within the line segment
# or distance of the closest end point.
# keep line segments that are within some distance threshold.
keep_idxs = np.where(dist<0.5)[1].A1.tolist()
if len(keep_idxs) == 0:
return [],[]
start_pts = start_pts[:,keep_idxs]
end_pts = end_pts[:,keep_idxs]
# find distance from the robot and select furthest line.
p_robot = np.matrix([0.,0.]).T
v = end_pts-start_pts
q_dot_v = p_robot.T*v
p1_dot_v = np.sum(np.multiply(start_pts,v),0)
v_dot_v = ut.norm(v)
lam = np.divide((q_dot_v-p1_dot_v),v_dot_v)
r = start_pts + np.multiply(lam,v)
dist = ut.norm(p_robot-r)
door_idx = np.argmax(dist)
return start_pts[:,door_idx].A1.tolist(),end_pts[:,door_idx].A1.tolist()
def xy_map_to_np_image(xy_map,m_per_pixel,dilation_count=0,padding=50):
''' returns binary numpy image. (255 for occupied
pixels, 0 for unoccupied)
2d array
'''
min_x = np.min(xy_map[0,:])
max_x = np.max(xy_map[0,:])
min_y = np.min(xy_map[1,:])
max_y = np.max(xy_map[1,:])
br = np.matrix([min_x,min_y]).T
n_x = int(round((max_x-min_x)/m_per_pixel)) + padding
n_y = int(round((max_y-min_y)/m_per_pixel)) + padding
img = np.zeros((n_x+padding,n_y+padding),dtype='int')
occupied_pixels = np.matrix([n_x,n_y]).T - np.round((xy_map-br)/m_per_pixel).astype('int')
if dilation_count == 0:
img[(occupied_pixels[0,:],occupied_pixels[1,:])] = 255
else:
img[(occupied_pixels[0,:],occupied_pixels[1,:])] = 1
connect_structure = np.empty((3,3),dtype='int')
connect_structure[:,:] = 1
img = ni.binary_closing(img,connect_structure,iterations=dilation_count)
img = ni.binary_dilation(img,connect_structure,iterations=1)
img = img*255
return img,n_x,n_y,br
def xy_map_to_cv_image(xy_map,m_per_pixel,dilation_count=0,padding=10):
np_im,n_x,n_y,br = xy_map_to_np_image(xy_map,m_per_pixel,dilation_count,padding)
cv_im = uto.np2cv(np_im)
return cv_im,n_x,n_y,br
def hough_lines(xy_map,save_lines=False):
''' xy_map - 2xN matrix of points.
returns start_list, end_list. [[p1x,p1y],[p2x,p2y]...],[[q1x,q1y]...]
[],[] if no lines were found.
'''
# save_lines=True
m_per_pixel = 0.005
img_cv,n_x,n_y,br = xy_map_to_cv_image(xy_map,m_per_pixel,dilation_count=1,padding=50)
time_str = str(time.time())
# for i in range(3):
# cvSmooth(img_cv,img_cv,CV_GAUSSIAN,3,3)
# cvSaveImage('aloha'+str(time.time())+'.png',img_cv)
storage = cvCreateMemStorage(0)
method = CV_HOUGH_PROBABILISTIC
rho = max(int(round(0.01/m_per_pixel)),1)
rho = 1
theta = math.radians(1)
min_line_length = int(0.3/m_per_pixel)
max_gap = int(0.1/m_per_pixel)
n_points_thresh = int(0.2/m_per_pixel)
# cvCanny(img_cv,img_cv,50,200)
# cvSaveImage('aloha.png',img_cv)
lines = cvHoughLines2(img_cv, storage, method, rho, theta, n_points_thresh, min_line_length, max_gap)
if lines.total == 0:
return [],[]
pts_start = np.zeros((2, lines.total))
pts_end = np.zeros((2, lines.total))
if save_lines:
color_dst = cvCreateImage( cvGetSize(img_cv), 8, 3 )
cvCvtColor( img_cv, color_dst, CV_GRAY2BGR )
n_lines = lines.total
for idx, line in enumerate(lines.asarrayptr(POINTER(CvPoint))):
pts_start[0, idx] = line[0].y
pts_start[1, idx] = line[0].x
pts_end[0, idx] = line[1].y
pts_end[1, idx] = line[1].x
if save_lines:
pts_start_pixel = pts_start
pts_end_pixel = pts_end
pts_start = (np.matrix([n_x,n_y]).T - pts_start)*m_per_pixel + br
pts_end = (np.matrix([n_x,n_y]).T - pts_end)*m_per_pixel + br
along_vec = pts_end - pts_start
along_vec = along_vec/ut.norm(along_vec)
ang_vec = np.arctan2(-along_vec[0,:],along_vec[1,:])
res_list = []
keep_indices = []
for i in range(n_lines):
ang = ang_vec[0,i]
if ang>math.radians(90):
ang = ang - math.radians(180)
if ang<math.radians(-90):
ang = ang + math.radians(180)
rot_mat = tr.Rz(ang)[0:2,0:2]
st = rot_mat*pts_start[:,i]
en = rot_mat*pts_end[:,i]
pts = rot_mat*xy_map
x_all = pts[0,:]
y_all = pts[1,:]
min_x = min(st[0,0],en[0,0]) - 0.1
max_x = max(st[0,0],en[0,0]) + 0.1
min_y = min(st[1,0],en[1,0]) + 0.01
max_y = max(st[1,0],en[1,0]) - 0.01
keep = np.multiply(np.multiply(x_all>min_x,x_all<max_x),
np.multiply(y_all>min_y,y_all<max_y))
xy_sub = xy_map[:,np.where(keep)[1].A1.tolist()]
if xy_sub.shape[1] == 0:
continue
a,b,res = uto.fitLine_highslope(xy_sub[0,:].T, xy_sub[1,:].T)
if res<0.0002:
res_list.append(res)
keep_indices.append(i)
if keep_indices == []:
return [],[]
pts_start = pts_start[:,keep_indices]
pts_end = pts_end[:,keep_indices]
print 'number of lines:', len(keep_indices)
if save_lines:
ut.save_pickle(res_list,'residual_list_'+time_str+'.pkl')
for i, idx in enumerate(keep_indices):
s = pts_start_pixel[:,idx]
e = pts_end_pixel[:,idx]
cvLine(color_dst, cvPoint(int(s[1]),int(s[0])), cvPoint(int(e[1]),int(e[0])), CV_RGB(*(color_list[i])),
3, 8)
cvSaveImage('lines_'+time_str+'.png',color_dst)
# cvReleaseMemStorage(storage)
return pts_start.T.tolist(),pts_end.T.tolist()
#------------- displaying in pygame -----------
def pixel_to_real(x,y, max_dist):
''' pixel to hokuyo
x,y - NX1 matrices (N points)
max_dist - dist which will be drawn at row 0
'''
return (org_y-y)*max_dist/400.,(org_x-x)*max_dist/400.
# return org_x-(400./max_dist)*y, org_y-(400./max_dist)*x
def coord(x,y, max_dist):
'''hokuyo coord frame to pixel (x,y) - floats
x,y - NX1 matrices (N points)
max_dist - dist which will be drawn at row 0
'''
return org_x-(400./max_dist)*y, org_y-(400./max_dist)*x
def draw_points(srf,x,y,color,max_dist,step=1):
''' step - set > 1 if you don't want to draw all the points.
'''
if len(x.A1) == 0:
return
x_pixel, y_pixel = coord(x.T,y.T,max_dist)
for i in range(0,x_pixel.shape[0],step):
pygame.draw.circle(srf, color, (int(x_pixel[i,0]+0.5), int(y_pixel[i,0]+0.5)), 2, 0)
def draw_hokuyo_scan(srf, scan, ang1, ang2, color, reject_zero_ten=True,step=1):
''' reject_zero_ten - don't show points with 0 or 10. range readings.
step - set > 1 if you don't want to draw all the points.
'''
pts = get_xy_map(scan, ang1, ang2, reject_zero_ten=reject_zero_ten)
# pts = get_xy_map(scan, reject_zero_ten=reject_zero_ten)
max_dist = MAX_DIST
draw_points(srf,pts[0,:],pts[1,:],color,max_dist,step=step)
def test_connected_comps(srf, scan):
#colors_list = [(200,0,0), (0,255,0), (100,100,0), (100,0,100), (0,100,100)]
n_colors = len(color_list)
cc_list = connected_components(get_xy_map(scan,math.radians(-60),math.radians(60)),0.03)
# draw the connected components as lines
for i,(p,q,p_idx,q_idx) in enumerate(cc_list):
c1,c2 = p.A1.tolist(),q.A1.tolist()
c1,c2 = coord(c1[0],c1[1], max_dist=MAX_DIST), coord(c2[0],c2[1], max_dist=MAX_DIST)
pygame.draw.line(srf,color_list[i%n_colors],c1,c2,2)
def test_find_objects(srf, scan):
obj_list = find_objects(scan, max_dist=0.6, max_size=0.3, min_size=0.01,
min_angle=math.radians(-60), max_angle=math.radians(60),
connect_dist_thresh=0.02)
print 'number of objects:', len(obj_list)
#colors_list = [(200,0,0), (0,255,0), (100,100,0), (100,0,100), (0,100,100)]
for i,(p,q,c) in enumerate(obj_list):
if i>4:
break
c1,c2 = p.A1.tolist(),q.A1.tolist()
c1,c2 = coord(c1[0],c1[1], max_dist=MAX_DIST), coord(c2[0],c2[1], max_dist=MAX_DIST)
pygame.draw.line(srf,color_list[i],c1,c2,2)
def test_find_closest_object_point(srf, scan):
pt_interest = np.matrix([0.,0.]).T
# pt_interest = np.matrix([0.3,-0.04]).T
p = find_closest_object_point(scan, pt_interest)
if p == None:
return
c1,c2 = coord(p[0,0],p[1,0], max_dist=MAX_DIST)
pygame.draw.circle(srf, (0,200,0), (c1,c2), 3, 0)
c1,c2 = coord(pt_interest[0,0],pt_interest[1,0], max_dist=MAX_DIST)
pygame.draw.circle(srf, (200,200,0), (c1,c2), 3, 0)
def tune_graze_effect_init():
sl = pu.Slider((340, 20), 10)
return sl
def tune_graze_effect_update(sl, srf, scan):
sl.update()
val = sl.value/255.
angle = 160+val*20
remove_graze_effect_scan(scan,graze_angle_threshold=math.radians(angle))
draw_hokuyo_scan(srf,scan,math.radians(-90), math.radians(90),color=(200,0,0),reject_zero_ten=False)
points_removed = np.where(np.matrix(scan.ranges)>10.)[0].shape[1]
sl.set_text('angle: %.2f, points_removed: %d'%(angle, points_removed))
sl.render(srf)
if sl.clicked:
return True
else:
return False
def test_find_handle_init():
fr = np.matrix([1.28184669,0.05562259]).T
bl = np.matrix([1.19585711,-0.06184923]).T
max_dist = MAX_DIST
x_fr, y_fr = coord(fr[0,0],fr[1,0],max_dist)
x_bl, y_bl = coord(bl[0,0],bl[1,0],max_dist)
pygame.draw.rect(srf,(200,0,200),pygame.Rect(x_bl,y_bl,x_fr-x_bl,y_fr-y_bl),1)
cv_handle_template = create_handle_template(dict['scan'],dict['bk_lt'],dict['fr_rt'])
def test_find_lines():
pts = get_xy_map(scan,math.radians(-60),math.radians(60))
p_start_list,p_end_list = hough_lines(pts)
if p_start_list == []:
return
#------- to test door finding ----------
# p_start,p_end = find_door(p_start_list,p_end_list)
# if p_start == []:
# return
# p_start_list,p_end_list = [p_start],[p_end]
n_colors = len(color_list)
for i,(p1,p2) in enumerate(zip(p_start_list,p_end_list)):
c1,c2 = coord(p1[0],p1[1], max_dist=MAX_DIST), coord(p2[0],p2[1], max_dist=MAX_DIST)
pygame.draw.line(srf,color_list[i%n_colors],c1,c2,2)
if __name__ == '__main__':
p = optparse.OptionParser()
p.add_option('-t', action='store', type='string', dest='hokuyo_type',
help='hokuyo_type. urg or utm')
p.add_option('-a', action='store', type='int', dest='avg',
help='number of scans to average', default=1)
p.add_option('-n', action='store', type='int', dest='hokuyo_number',
help='hokuyo number. 0,1,2 ...')
p.add_option('-f', action='store_true', dest='flip',
help='flip the hokuyo scan')
p.add_option('--ang_range', type='float', dest='ang_range',
help='max angle of the ray to display (degrees)',
default=360.)
opt, args = p.parse_args()
hokuyo_type = opt.hokuyo_type
hokuyo_number = opt.hokuyo_number
avg_number = opt.avg
flip = opt.flip
ang_range = opt.ang_range
ang_range = math.radians(ang_range)
#------- which things to test ---------
test_graze_effect_flag = False
test_find_objects_flag = False
test_find_closest_object_point_flag = False
test_show_change_flag = False
test_find_lines_flag = False
#--------------------------------------
# Initialize pygame
# pygame.init()
# Open a display
srf = pygame.display.set_mode((640,480))
pygame.display.set_caption(hokuyo_type+' '+str(hokuyo_number))
fps = 100
loopFlag = True
clk = pygame.time.Clock()
if hokuyo_type == 'utm':
h = hs.Hokuyo('utm',hokuyo_number,start_angle=-ang_range,
end_angle=ang_range,flip=flip)
elif hokuyo_type == 'urg':
h = hs.Hokuyo('urg',hokuyo_number,flip=flip)
else:
print 'unknown hokuyo type: ', hokuyo_type
print 'Exiting...'
sys.exit()
# scan1 = h.get_scan(avoid_duplicate=True)
# sys.exit()
#---------- initializations -------------
if test_graze_effect_flag:
sl = tune_graze_effect_init()
#--------- and now loop -----------
if test_show_change_flag:
scan_prev = h.get_scan(avoid_duplicate=True, avg=avg_number, remove_graze=False)
n_ch_pts_list = []
while loopFlag:
widget_clicked = False
# Clear the screen
srf.fill((255,255,255))
# Draw the urg
pygame.draw.circle(srf, (200,0,0), (org_x,org_y), 10, 0)
#display all the points
if test_graze_effect_flag or test_show_change_flag:
# here we don't want any filtering on the scan.
scan = h.get_scan(avoid_duplicate=True, avg=avg_number, remove_graze=False)
else:
scan = h.get_scan(avoid_duplicate=True, avg=avg_number, remove_graze=True)
if test_show_change_flag == False:
#draw_hokuyo_scan(srf,scan,math.radians(-70), math.radians(70),color=(0,0,200))
#draw_hokuyo_scan(srf,scan,math.radians(-90), math.radians(90),color=(0,0,200))
draw_hokuyo_scan(srf,scan,math.radians(-135),math.radians(135),color=(0,0,200))
else:
diff_scan = subtract_scans(scan,scan_prev)
scan_prev = scan
pts = get_xy_map(diff_scan,math.radians(-40), math.radians(40),reject_zero_ten=True)
n_ch_pts_list.append(pts.shape[1])
max_dist = MAX_DIST
draw_points(srf,pts[0,:],pts[1,:],color=(0,200,0),max_dist=max_dist)
# test_connected_comps(srf, scan)
if test_find_objects_flag:
test_find_objects(srf, scan)
if test_find_closest_object_point_flag:
test_find_closest_object_point(srf, scan)
if test_graze_effect_flag:
widget_clicked |= tune_graze_effect_update(sl,srf, scan)
if test_find_lines_flag:
test_find_lines()
pygame.display.flip()
events = pygame.event.get()
for e in events:
if e.type==pygame.locals.QUIT:
loopFlag=False
if e.type==pygame.locals.KEYDOWN:
if e.key == 27: # Esc
loopFlag=False
if widget_clicked == False:
if e.type==pygame.locals.MOUSEMOTION:
if e.buttons[0] == 1:
# left button
org_x += e.rel[0]
org_y += e.rel[1]
if e.buttons[2] == 1:
# right button
MAX_DIST *= (1+e.rel[1]*0.01)
MAX_DIST = max(MAX_DIST,0.1)
# Try to keep the specified framerate
clk.tick(fps)
if test_show_change_flag:
ut.save_pickle(n_ch_pts_list,ut.formatted_time()+'_ch_pts_list.pkl')
| [
[
1,
0,
0.0477,
0.0014,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0491,
0.0014,
0,
0.66,
0.0238,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0519,
0.0014,
0,
0.... | [
"import roslib",
"roslib.load_manifest('hrl_hokuyo')",
"import pygame",
"import pygame.locals",
"import hokuyo_scan as hs",
"import hrl_lib.transforms as tr",
"import hrl_lib.util as ut",
"import math, numpy as np",
"import scipy.ndimage as ni",
"import pylab as pl",
"import sys, time",
"impor... |
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import math, numpy as np
import sys, time
NAME = 'utm_python_listener'
import roslib; roslib.load_manifest('hrl_hokuyo')
import rospy
from sensor_msgs.msg import LaserScan
from threading import RLock
import hokuyo_processing as hp
import copy
import numpy as np
class HokuyoScan():
''' This class has the data of a laser scan.
'''
def __init__(self,hokuyo_type,angular_res,max_range,min_range,start_angle,end_angle):
''' hokuyo_type - 'urg', 'utm'
angular_res - angle (radians) between consecutive points in the scan.
min_range, max_range - in meters
ranges,angles,intensities - 1xn_points numpy matrix.
'''
self.hokuyo_type = hokuyo_type
self.angular_res = angular_res
self.max_range = max_range
self.min_range = min_range
self.start_angle = start_angle
self.end_angle = end_angle
self.n_points = int((end_angle-start_angle)/angular_res)+1
self.ranges = None
self.intensities = None
self.angles = []
for i in xrange(self.n_points):
self.angles.append(hp.index_to_angle(self,i))
self.angles = np.matrix(self.angles)
class Urg():
''' get a scan from urg using player.
'''
def __init__(self, urg_number,start_angle=None,end_angle=None, host='localhost', port=6665):
''' host, port - hostname and port of the player server
'''
import player_functions as pf
import playerc as pl
self.player_client = pf.player_connect(host,port)
self.laser = pl.playerc_laser(self.player_client, urg_number)
if self.laser.subscribe(pl.PLAYERC_OPEN_MODE) != 0:
raise RuntimeError("hokuyo_scan.Urg.__init__: Unable to connect to urg!\n")
for i in range(10):
self.player_client.read()
start_angle_fullscan = -math.radians(654./2*0.36)
end_angle_fullscan = math.radians(654./2*0.36)
if start_angle == None or start_angle<start_angle_fullscan:
start_angle_subscan = start_angle_fullscan
else:
start_angle_subscan = start_angle
if end_angle == None or end_angle>end_angle_fullscan:
end_angle_subscan = end_angle_fullscan
else:
end_angle_subscan = end_angle
ang_res = math.radians(0.36)
self.start_index_fullscan=(start_angle_subscan-start_angle_fullscan)/ang_res
self.end_index_fullscan=(end_angle_subscan-start_angle_fullscan)/ang_res
self.hokuyo_scan = HokuyoScan(hokuyo_type = 'urg', angular_res = math.radians(0.36),
max_range = 4.0, min_range = 0.2,
start_angle=start_angle_subscan,
end_angle=end_angle_subscan)
def get_scan(self, avoid_duplicate=False):
''' avoid_duplicate - avoids duplicates caused by querying player faster than it
can get new scans.
'''
curr_ranges = self.hokuyo_scan.ranges
for i in range(10): # I get a new scan by the time i=4
if self.player_client.read() == None:
raise RuntimeError('hokuyo_scan.Urg.get_scan: player_client.read() returned None.\n')
sub_ranges = np.matrix(self.laser.ranges[self.start_index_fullscan:self.end_index_fullscan+1])
if avoid_duplicate == False or np.any(curr_ranges != sub_ranges):
# got a fresh scan from player.
break
self.hokuyo_scan.ranges = sub_ranges
return copy.copy(self.hokuyo_scan)
class Utm():
''' get a scan from a UTM using ROS
'''
def __init__(self, utm_number,start_angle=None,end_angle=None,ros_init_node=True):
hokuyo_node_name = '/utm%d'%utm_number
# max_ang = rospy.get_param(hokuyo_node_name+'/max_ang')
# min_ang = rospy.get_param(hokuyo_node_name+'/min_ang')
# start_angle_fullscan = min_ang
# end_angle_fullscan = max_ang
# print 'max_angle:', math.degrees(max_ang)
# print 'min_angle:', math.degrees(min_ang)
max_ang_degrees = rospy.get_param(hokuyo_node_name+'/max_ang_degrees')
min_ang_degrees = rospy.get_param(hokuyo_node_name+'/min_ang_degrees')
start_angle_fullscan = math.radians(min_ang_degrees)
end_angle_fullscan = math.radians(max_ang_degrees)
# This is actually determined by the ROS node params and not the UTM.
# start_angle_fullscan = -math.radians(1080./2*0.25) #270deg
# end_angle_fullscan = math.radians(1080./2*0.25)
# start_angle_fullscan = -math.radians(720./2*0.25) #180deg
# end_angle_fullscan = math.radians(720./2*0.25)
# start_angle_fullscan = -math.radians(559./2*0.25) #140deg
# end_angle_fullscan = math.radians(559./2*0.25)
if start_angle == None or start_angle<start_angle_fullscan:
start_angle_subscan = start_angle_fullscan
else:
start_angle_subscan = start_angle
if end_angle == None or end_angle>end_angle_fullscan:
end_angle_subscan = end_angle_fullscan
else:
end_angle_subscan = end_angle
ang_res = math.radians(0.25)
self.start_index_fullscan=int(round((start_angle_subscan-start_angle_fullscan)/ang_res))
self.end_index_fullscan=int(round((end_angle_subscan-start_angle_fullscan)/ang_res))
self.hokuyo_scan = HokuyoScan(hokuyo_type = 'utm', angular_res = math.radians(0.25),
max_range = 10.0, min_range = 0.1,
start_angle=start_angle_subscan,
end_angle=end_angle_subscan)
self.lock = RLock()
self.lock_init = RLock()
self.connected_to_ros = False
self.ranges,self.intensities = None,None
if ros_init_node:
try:
print 'Utm: init ros node.'
rospy.init_node(NAME, anonymous=True)
except rospy.ROSException, e:
print 'Utm: rospy already initialized. Got message', e
pass
rospy.Subscriber("utm%d_scan"%(utm_number), LaserScan,
self.callback, queue_size = 1)
def callback(self, scan):
self.lock.acquire()
self.connected_to_ros = True
self.ranges = np.matrix(scan.ranges[self.start_index_fullscan:self.end_index_fullscan+1])
self.intensities = np.matrix(scan.intensities[self.start_index_fullscan:self.end_index_fullscan+1])
self.lock.release()
def get_scan(self, avoid_duplicate=False):
while self.connected_to_ros == False:
pass
while not rospy.is_shutdown():
self.lock.acquire()
if avoid_duplicate == False or np.any(self.hokuyo_scan.ranges!=self.ranges):
# got a fresh scan from ROS
self.hokuyo_scan.ranges = copy.copy(self.ranges)
self.hokuyo_scan.intensities = copy.copy(self.intensities)
self.lock.release()
break
self.lock.release()
time.sleep(0.001)
return copy.copy(self.hokuyo_scan)
class Hokuyo():
''' common class for getting scans from both urg and utm.
'''
def __init__(self, hokuyo_type, hokuyo_number, start_angle=None,
end_angle=None, flip=False, ros_init_node=True):
''' hokuyo_type - 'urg', 'utm'
- 'utm' requires ros revision 2536
ros-kg revision 5612
hokuyo_number - 0,1,2 ...
start_angle, end_angle - unoccluded part of the scan. (radians)
flip - whether to flip the scans (hokuyo upside-down)
'''
self.hokuyo_type = hokuyo_type
self.flip = flip
if hokuyo_type == 'urg':
self.hokuyo = Urg(hokuyo_number,start_angle,end_angle)
elif hokuyo_type == 'utm':
self.hokuyo = Utm(hokuyo_number,start_angle,end_angle,ros_init_node=ros_init_node)
else:
raise RuntimeError('hokuyo_scan.Hokuyo.__init__: Unknown hokuyo type: %s\n'%(hokuyo_type))
def get_scan(self, avoid_duplicate=False, avg=1, remove_graze=True):
''' avoid_duplicate - prevent duplicate scans which will happen if get_scan is
called at a rate faster than the scanning rate of the hokuyo.
avoid_duplicate == True, get_scan will block till new scan is received.
(~.2s for urg and 0.05s for utm)
'''
l = []
l2 = []
for i in range(avg):
hscan = self.hokuyo.get_scan(avoid_duplicate)
l.append(hscan.ranges)
l2.append(hscan.intensities)
ranges_mat = np.row_stack(l)
ranges_mat[np.where(ranges_mat==0)] = -1000. # make zero pointvery negative
ranges_avg = (ranges_mat.sum(0)/avg)
if self.flip:
ranges_avg = np.fliplr(ranges_avg)
hscan.ranges = ranges_avg
intensities_mat = np.row_stack(l2)
if self.hokuyo_type == 'utm':
hscan.intensities = (intensities_mat.sum(0)/avg)
if remove_graze:
if self.hokuyo_type=='utm':
hp.remove_graze_effect_scan(hscan)
else:
print 'hokuyo_scan.Hokuyo.get_scan: hokuyo type is urg, but remove_graze is True'
return hscan
if __name__ == '__main__':
import pylab as pl
# h = Hokuyo('urg', 0)
h = Hokuyo('utm', 0, flip=True)
print 'getting first scan'
scan1 = h.get_scan(avoid_duplicate=True)
# hp.get_xy_map(scan1)
t_list = []
for i in range(200):
t0 = time.time()
scan2 = h.get_scan(avoid_duplicate=True,avg=1,remove_graze=False)
# scan = h.get_scan(avoid_duplicate=False)
t1 = time.time()
print t1-t0, scan1==scan2
t_list.append(t1-t0)
scan1=scan2
print scan1.ranges.shape
print scan1.angles.shape
# t_mat = np.matrix(t_list)
# print '#################################################'
# print 'mean time between scans:', t_mat.mean()
# print 'standard deviation:', np.std(t_mat)
pl.plot(t_list)
pl.show()
| [
[
1,
0,
0.0055,
0.0055,
0,
0.66,
0,
526,
0,
2,
0,
0,
526,
0,
0
],
[
1,
0,
0.011,
0.0055,
0,
0.66,
0.0769,
509,
0,
2,
0,
0,
509,
0,
0
],
[
1,
0,
0.022,
0.0055,
0,
0.... | [
"import math, numpy as np",
"import sys, time",
"import roslib; roslib.load_manifest('hrl_hokuyo')",
"import roslib; roslib.load_manifest('hrl_hokuyo')",
"import rospy",
"from sensor_msgs.msg import LaserScan",
"from threading import RLock",
"import hokuyo_processing as hp",
"import copy",
"import... |
import math
# home position in encoder ticks for the servo.
servo_param = {
# 1: { # Default for new servo. Please issue 'new_servo.write_id(new_id)' and setup your own home position!
# 'home_encoder': 351
# },
2: { # Tilting Hokuyo on El-E
'home_encoder': 446
},
3: { # RFID Antenna Left Tilt
'home_encoder': 377
},
4: { # RFID Antenna Right Tilt
'home_encoder': 330
},
5: { # Tilting kinect on Cody
'home_encoder': 447,
'max_ang': math.radians(55.),
'min_ang': math.radians(-80.)
},
6: { # EL-E stereohead Pan
'home_encoder': 500,
'max_ang': math.radians(90.),
'min_ang': math.radians(-90.)
},
7: { # EL-E safetyscreen tilt.
'home_encoder': 373
},
11: { # RFID Left Pan
'home_encoder': 430,
'max_ang': math.radians( 141.0 ),
'min_ang': math.radians( -31.0 )
},
12: { # RFID Left Tilt
'home_encoder': 507,
'max_ang': math.radians( 46.0 ),
'min_ang': math.radians( -36.0 )
},
13: { # RFID Right Pan
'home_encoder': 583,
'max_ang': math.radians( 31.0 ),
'min_ang': math.radians( -141.0 )
},
14: { # RFID Right Tilt
'home_encoder': 504,
'max_ang': math.radians( 46.0 ),
'min_ang': math.radians( -36.0 )
},
15: { # Ear Flap on RFID El-E Right
'home_encoder': 498
},
16: { # Pan Antenna on RFID El-E Left
'home_encoder': 365
},
17: { # Tilt Antenna on RFID El-E Left
'home_encoder': 504
},
18: { # EL-E stereohead Tilt
'home_encoder': 495,
'max_ang': math.radians(60.),
'min_ang': math.radians(-20.)
},
19: { # Desktop System UTM
'home_encoder': 633,
'flipped': True
},
20: { # Desktop System Tilt
'home_encoder': 381
},
21: { # Desktop System Pan
'home_encoder': 589
},
22: { # Desktop System Roll
'home_encoder': 454
},
23: { # Dinah Top
'home_encoder': 379
},
24: { # Dinah Bottom
'home_encoder': 365
},
25: { # Meka top Pan
'home_encoder': 500
},
26: { # Meka top Tilt
'home_encoder': 400
},
27: { # PR2 RFID Right Pan
'home_encoder': 512
},
28: { # PR2 RFID Right Tilt
'home_encoder': 506
},
29: { # PR2 RFID Left Pan
'home_encoder': 544
},
30: { # PR2 RFID Left Tilt
'home_encoder': 500
},
31: { # Playpen open/close
'home_encoder': 381
},
32: { # Conveyor for playpen
'home_encoder': 1
}
}
| [
[
1,
0,
0.0092,
0.0092,
0,
0.66,
0,
526,
0,
1,
0,
0,
526,
0,
0
],
[
14,
0,
0.5183,
0.9541,
0,
0.66,
1,
241,
0,
0,
0,
0,
0,
6,
14
]
] | [
"import math",
"servo_param = {\n# 1: { # Default for new servo. Please issue 'new_servo.write_id(new_id)' and setup your own home position!\n# 'home_encoder': 351\n# }, \n 2: { # Tilting Hokuyo on El-E\n 'home_encoder': 446\n }, \n ... |
__all__ = [
'robotis_servo',
'lib_robotis',
'ros_robotis',
'servo_config'
]
| [
[
14,
0,
0.5833,
1,
0,
0.66,
0,
272,
0,
0,
0,
0,
0,
5,
0
]
] | [
"__all__ = [\n'robotis_servo',\n'lib_robotis',\n'ros_robotis',\n'servo_config'\n]"
] |
#!/usr/bin/python
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
## Controlling Robotis Dynamixel RX-28 & RX-64 servos from python
## using the USB2Dynamixel adaptor.
## Authors: Travis Deyle & Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
# ROS imports
import roslib
roslib.load_manifest('robotis')
import rospy
from std_msgs.msg import Float64
from robotis.srv import None_Float
from robotis.srv import None_FloatResponse
from robotis.srv import MoveAng
from robotis.srv import MoveAngResponse
from robotis.srv import None_Int32
from robotis.srv import None_Int32Response
import robotis.lib_robotis as rs
import time
import math
from threading import Thread
class ROS_Robotis_Server():
# This class provides ROS services for a select few lib_robotis functions
def __init__(self, servo = None, name = '' ):
if servo == None:
raise RuntimeError( 'ROS_Robotis_Servo: No servo specified for server.\n' )
self.servo = servo
self.name = name
try:
rospy.init_node( 'robotis_servo_' + self.name )
except rospy.ROSException:
pass
#self.servo.disable_torque()
rospy.logout( 'ROS_Robotis_Servo: Starting Server /robotis/servo_' + self.name )
self.channel = rospy.Publisher('/robotis/servo_' + self.name, Float64)
self.__service_ang = rospy.Service('/robotis/servo_' + name + '_readangle',
None_Float, self.__cb_readangle)
self.__service_ismove = rospy.Service('/robotis/servo_' + name + '_ismoving',
None_Int32, self.__cb_ismoving)
self.__service_moveang = rospy.Service('/robotis/servo_' + name + '_moveangle',
MoveAng, self.__cb_moveangle)
def __cb_readangle( self, request ):
ang = self.update_server()
return None_FloatResponse( ang )
def __cb_ismoving( self, request ):
status = self.servo.is_moving()
return None_Int32Response( int(status) )
def __cb_moveangle( self, request ):
ang = request.angle
angvel = request.angvel
blocking = bool( request.blocking )
self.servo.move_angle( ang, angvel, blocking )
return MoveAngResponse()
def update_server(self):
ang = self.servo.read_angle()
self.channel.publish( Float64(ang) )
return ang
class ROS_Robotis_Poller( Thread ):
# A utility class that will setup and poll a number of ROS_Robotis_Servos on one USB2Dynamixel
def __init__( self, dev_name, ids, names ):
Thread.__init__(self)
self.should_run = True
self.dev_name = dev_name
self.ids = ids
self.names = names
for n in self.names:
rospy.logout( 'ROS_Robotis_Servo: Starting Up /robotis/servo_' + n + ' on ' + self.dev_name )
self.dyn = rs.USB2Dynamixel_Device( self.dev_name )
self.servos = [ rs.Robotis_Servo( self.dyn, i ) for i in self.ids ]
self.ros_servers = [ ROS_Robotis_Server( s, n ) for s,n in zip( self.servos, self.names ) ]
rospy.logout( 'ROS_Robotis_Servo: Setup Complete on ' + self.dev_name )
self.start()
def run( self ):
while self.should_run and not rospy.is_shutdown():
[ s.update_server() for s in self.ros_servers ]
time.sleep(0.001)
for n in self.names:
rospy.logout( 'ROS_Robotis_Servo: Shutting Down /robotis/servo_' + n + ' on ' + self.dev_name )
def stop(self):
self.should_run = False
self.join(3)
if (self.isAlive()):
raise RuntimeError("ROS_Robotis_Servo: unable to stop thread")
class ROS_Robotis_Client():
# Provides access to the ROS services in the server.
def __init__(self, name = '' ):
self.name = name
rospy.wait_for_service('/robotis/servo_' + name + '_readangle')
rospy.wait_for_service('/robotis/servo_' + name + '_ismoving')
rospy.wait_for_service('/robotis/servo_' + name + '_moveangle')
self.__service_ang = rospy.ServiceProxy('/robotis/servo_' + name + '_readangle',
None_Float)
self.__service_ismove = rospy.ServiceProxy('/robotis/servo_' + name + '_ismoving',
None_Int32)
self.__service_moveang = rospy.ServiceProxy('/robotis/servo_' + name + '_moveangle',
MoveAng)
def read_angle( self ):
resp = self.__service_ang()
ang = resp.value
return ang
def is_moving( self ):
resp = self.__service_ismove()
return bool( resp.value )
def move_angle( self, ang, angvel = math.radians(50), blocking = True ):
self.__service_moveang( ang, angvel, int(blocking) )
if __name__ == '__main__':
print 'Sample Server: '
# Important note: You cannot (!) use the same device (dyn) in another
# process. The device is only "thread-safe" within the same
# process (i.e. between servos (and callbacks) instantiated
# within that process)
# NOTE: If you are going to be polling the servers as in the snippet
# below, I recommen using a poller! See "SAMPLE POLLER" below.
dev_name = '/dev/robot/servo_left'
ids = [11, 12]
names = ['pan', 'tilt']
dyn = rs.USB2Dynamixel_Device( dev_name )
servos = [ rs.Robotis_Servo( dyn, i ) for i in ids ]
ros_servers = [ ROS_Robotis_Server( s, n ) for s,n in zip( servos, names ) ]
try:
while not rospy.is_shutdown():
[ s.update_server() for s in ros_servers ]
time.sleep(0.001)
except:
pass
for n in names:
print 'ROS_Robotis_Servo: Shutting Down /robotis/servo_'+n
## SAMPLE POLLER
# The above example just constantly polls all the servos, while also
# making the services available. This generally useful code is
# encapsulated in a more general poller class (which also has nicer
# shutdown / restart properties). Thus, the above example is best used as:
# ROS_Robotis_Poller( '/dev/robot/servo_left', [11,12], ['pan', 'tilt'] )
## SAMPLE CLIENTS:
# tilt = ROS_Robotis_Client( 'tilt' )
# tilt.move_angle( math.radians( 0 ), math.radians(10), blocking=False)
# while tilt.is_moving():
# print 'Tilt is moving'
# pan = ROS_Robotis_Client( 'pan' )
# pan.move_angle( math.radians( 0 ), math.radians(10), blocking=False)
# while pan.is_moving():
# print 'pan is moving'
| [
[
1,
0,
0.1629,
0.0045,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.1674,
0.0045,
0,
0.66,
0.0588,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.1719,
0.0045,
0,
0.... | [
"import roslib",
"roslib.load_manifest('robotis')",
"import rospy",
"from std_msgs.msg import Float64",
"from robotis.srv import None_Float",
"from robotis.srv import None_FloatResponse",
"from robotis.srv import MoveAng",
"from robotis.srv import MoveAngResponse",
"from robotis.srv import None_Int3... |
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import roslib; roslib.load_manifest('pan_tilt_robotis')
import time
import sys, optparse
import numpy as np, math
import hrl_lib.util as ut
import robotis.robotis_servo as rs
class PanTilt():
## Assumes that both pan and tilt servos are controlled using the
# same usb2dynamixel adaptor.
# @param dev_name - name of serial device of the servo controller (e.g. '/dev/robot/servo0')
# @param pan_id - servo id for the pan Robotis servo.
# @param pan_id - servo id for the tilt Robotis servo.
# @param baudrate - for the servo controller (usb2dynamixel)
# @param pan_speed - max pan speed (radians/sec)
# @param tilt_speed - max tilt speed (radians/sec)
def __init__(self, dev_name, pan_id, tilt_id, baudrate=57600,
pan_speed = math.radians(180),
tilt_speed = math.radians(180)):
self.pan_servo = rs.robotis_servo(dev_name,pan_id,baudrate,
max_speed = pan_speed)
self.tilt_servo = rs.robotis_servo(dev_name,tilt_id,baudrate,
max_speed = tilt_speed)
self.max_pan = self.pan_servo.max_ang
self.min_pan = self.pan_servo.min_ang
self.max_tilt = self.tilt_servo.max_ang
self.min_tilt = self.tilt_servo.min_ang
## return (pan,tilt) angles in RADIANS.
def get_pan_tilt(self):
pan = self.pan_servo.read_angle()
tilt = self.tilt_servo.read_angle()
return pan, -tilt
## set (pan,tilt) angles in RADIANS.
# blocks until the pan and tilt angles are attained.
# @param pan - pan angle (RADIANS)
# @param tilt - tilt angle (RADIANS)
def set_pan_tilt(self, pan, tilt, speed=math.radians(180)):
self.pan_servo.move_angle(pan, angvel=speed, blocking=False)
self.tilt_servo.move_angle(tilt, angvel=speed, blocking=True)
self.pan_servo.move_angle(pan, angvel=speed, blocking=True)
## new pan,tilt = current pan,tilt + pan_d,tilt_d
# blocks until the pan and tilt angles are attained.
# @param pan - pan angle (RADIANS)
# @param tilt - tilt angle (RADIANS)
def set_pan_tilt_delta(self,pan_d,tilt_d):
p,t = self.get_pan_tilt()
self.set_pan_tilt(p+pan_d,t+tilt_d)
def set_ptz_angles_rad(self, pan, tilt):
print 'pan_tilt.set_ptz_angles_rad: WARNING this function has been deprecated. use set_pan_tilt'
self.set_pan_tilt(pan, tilt)
def set_ptz_values(self, pan, tilt, blocking=True):
print 'pan_tilt.set_ptz_values: WARNING this function has been deprecated. use set_pan_tilt'
self.set_pan_tilt(pan, tilt)
def get_ptz_angles_rad(self):
print 'pan_tilt.get_ptz_angles_rad: WARNING this function has been deprecated. use set_pan_tilt'
return self.get_pan_tilt()
def get_ptz_values(self):
print 'pan_tilt.get_ptz_values: WARNING this function has been deprecated. use set_pan_tilt'
p, t = self.get_pan_tilt()
#return p, t
return math.degrees(p), math.degrees(t)
if __name__ == '__main__':
p = optparse.OptionParser()
p.add_option('-d', action='store', type='string', dest='servo_dev_name',
default='/dev/robot/pan_tilt0', help='servo device string. [default= /dev/robot/pan_tilt0]')
p.add_option('--pan_id', action='store', type='int', dest='pan_id',
help='id of the pan servo',default=None)
p.add_option('--tilt_id', action='store', type='int', dest='tilt_id',
help='id of the tilt servo',default=None)
p.add_option('--pan', action='store', type='float', dest='pan',
help='pan angle (degrees).',default=None)
p.add_option('--tilt', action='store', type='float', dest='tilt',
help='tilt angle (degrees).',default=None)
opt, args = p.parse_args()
servo_dev_name = opt.servo_dev_name
pan_id = opt.pan_id
tilt_id = opt.tilt_id
pan = opt.pan
tilt = opt.tilt
if pan_id == None:
print 'Please provide a pan_id'
print 'Exiting...'
sys.exit()
if tilt_id == None:
print 'Please provide a tilt_id'
print 'Exiting...'
sys.exit()
if pan == None:
print 'Please provide a pan (angle)'
print 'Exiting...'
sys.exit()
if tilt == None:
print 'Please provide a tilt (angle)'
print 'Exiting...'
sys.exit()
ptu = PanTilt(servo_dev_name,pan_id,tilt_id)
ptu.set_pan_tilt(math.radians(pan),math.radians(tilt))
# For EL-E:
# python pan_tilt.py -d /dev/robot/servos_pan_tilt_hat --pan_id=6 --tilt_id=18 --pan=0 --tilt=0
| [
[
1,
0,
0.1923,
0.0064,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.1923,
0.0064,
0,
0.66,
0.125,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.2051,
0.0064,
0,
0.6... | [
"import roslib; roslib.load_manifest('pan_tilt_robotis')",
"import roslib; roslib.load_manifest('pan_tilt_robotis')",
"import time",
"import sys, optparse",
"import numpy as np, math",
"import hrl_lib.util as ut",
"import robotis.robotis_servo as rs",
"class PanTilt():\n \n ## Assumes that both ... |
import time
import sys, os, copy
import numpy as np, math
import scipy.ndimage as ni
class occupancy_grid_3d():
##
# @param resolution - 3x1 matrix. size of each cell (in meters) along
# the different directions.
def __init__(self, center, size, resolution, data,
occupancy_threshold, to_binary = True):
self.grid_shape = size/resolution
tlb = center + size/2
brf = center + size/2
self.size = size
self.grid = np.reshape(data, self.grid_shape)
self.grid_shape = np.matrix(self.grid.shape).T
self.resolution = resolution
self.center = center
if to_binary:
self.to_binary(occupancy_threshold)
## binarize the grid
# @param occupancy_threshold - voxels with occupancy less than this are set to zero.
def to_binary(self, occupancy_threshold):
filled = (self.grid >= occupancy_threshold)
self.grid[np.where(filled==True)] = 1
self.grid[np.where(filled==False)] = 0
##
# @param array - if not None then this will be used instead of self.grid
# @return 3xN matrix of 3d coord of the cells which have occupancy = 1
def grid_to_points(self, array=None):
if array == None:
array = self.grid
idxs = np.where(array == 1)
x_idx = idxs[0]
y_idx = idxs[1]
z_idx = idxs[2]
x = x_idx * self.resolution[0,0] + self.center[0,0] - self.size[0,0]/2
y = y_idx * self.resolution[1,0] + self.center[1,0] - self.size[1,0]/2
z = z_idx * self.resolution[2,0] + self.center[2,0] - self.size[2,0]/2
return np.matrix(np.row_stack([x,y,z]))
## 27-connected components.
# @param threshold - min allowed size of connected component
def connected_comonents(self, threshold):
connect_structure = np.ones((3,3,3), dtype='int')
grid = self.grid
labeled_arr, n_labels = ni.label(grid, connect_structure)
if n_labels == 0:
return labeled_arr, n_labels
labels_list = range(1,n_labels+1)
count_objects = ni.sum(grid, labeled_arr, labels_list)
if n_labels == 1:
count_objects = [count_objects]
t0 = time.time()
new_labels_list = []
for c,l in zip(count_objects, labels_list):
if c > threshold:
new_labels_list.append(l)
else:
labeled_arr[np.where(labeled_arr == l)] = 0
# relabel stuff
for nl,l in enumerate(new_labels_list):
labeled_arr[np.where(labeled_arr == l)] = nl+1
n_labels = len(new_labels_list)
t1 = time.time()
print 'time:', t1-t0
return labeled_arr, n_labels
if __name__ == '__main__':
print 'Hello World'
| [
[
1,
0,
0.0225,
0.0112,
0,
0.66,
0,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.0337,
0.0112,
0,
0.66,
0.2,
509,
0,
3,
0,
0,
509,
0,
0
],
[
1,
0,
0.0449,
0.0112,
0,
0.6... | [
"import time",
"import sys, os, copy",
"import numpy as np, math",
"import scipy.ndimage as ni",
"class occupancy_grid_3d():\n\n ##\n # @param resolution - 3x1 matrix. size of each cell (in meters) along\n # the different directions.\n def __init__(self, center, size, resolut... |
import sys
import numpy as np, math
import add_cylinder as ac
import online_collision_detection as ocd
import roslib; roslib.load_manifest('arm_navigation_tutorials')
import rospy
from mapping_msgs.msg import CollisionObject
from visualization_msgs.msg import Marker
import hrl_lib.transforms as tr
import hrl_lib.viz as hv
roslib.load_manifest('hrl_pr2_lib')
import hrl_pr2_lib.pr2_arms as pa
roslib.load_manifest('force_torque') # hack by Advait
import force_torque.FTClient as ftc
import tf
class object_ft_sensors():
def __init__(self):
self.obj1_ftc = ftc.FTClient('force_torque_ft2')
self.tf_lstnr = tf.TransformListener()
def get_forces(self, bias = True):
# later I might be looping over all the different objects,
# returning a dictionary of <object_id: force_vector>
f = self.obj1_ftc.read(without_bias = not bias)
f = f[0:3, :]
trans, quat = self.tf_lstnr.lookupTransform('/torso_lift_link',
'/ft2',
rospy.Time(0))
rot = tr.quaternion_to_matrix(quat)
f = rot * f
return -f # the negative is intentional (Advait, Nov 24. 2010.)
def bias_fts(self):
self.obj1_ftc.bias()
def get_arrow_text_markers(p, f, frame, m_id, duration):
t_now = rospy.Time.now()
q = hv.arrow_direction_to_quat(f)
arrow_len = np.linalg.norm(f) * 0.04
scale = (arrow_len, 0.2, 0.2)
m1 = hv.single_marker(p, q, 'arrow', frame, scale, m_id = m_id,
duration = duration)
m1.header.stamp = t_now
m2 = hv.single_marker(p, q, 'text_view_facing', frame,
(0.1, 0.1, 0.1), m_id = m_id+1,
duration = duration, color=(1.,0.,0.,1.))
m2.text = '%.1f N'%(np.linalg.norm(f))
m2.header.stamp = t_now
return m1, m2
if __name__ == '__main__':
rospy.init_node('force_visualize_test')
marker_pub = rospy.Publisher('/skin/viz_marker', Marker)
fts = object_ft_sensors()
fts.bias_fts()
pr2_arms = pa.PR2Arms()
r_arm, l_arm = 0, 1
arm = r_arm
while not rospy.is_shutdown():
f = fts.get_forces()
p, r = pr2_arms.end_effector_pos(arm)
m1, m2 = get_arrow_text_markers(p, f, 'torso_lift_link', 0, 1.)
marker_pub.publish(m1)
marker_pub.publish(m2)
rospy.sleep(0.1)
| [
[
1,
0,
0.0225,
0.0112,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0337,
0.0112,
0,
0.66,
0.0556,
954,
0,
2,
0,
0,
954,
0,
0
],
[
1,
0,
0.0562,
0.0112,
0,
... | [
"import sys",
"import numpy as np, math",
"import add_cylinder as ac",
"import online_collision_detection as ocd",
"import roslib; roslib.load_manifest('arm_navigation_tutorials')",
"import roslib; roslib.load_manifest('arm_navigation_tutorials')",
"import rospy",
"from mapping_msgs.msg import Collisi... |
import roslib; roslib.load_manifest('arm_navigation_tutorials')
import sys
import rospy
from planning_environment_msgs.srv import GetStateValidity
from planning_environment_msgs.srv import GetStateValidityRequest
if __name__ == '__main__':
rospy.init_node('get_state_validity_python')
srv_nm = 'environment_server_right_arm/get_state_validity'
rospy.wait_for_service(srv_nm)
get_state_validity = rospy.ServiceProxy(srv_nm, GetStateValidity)
req = GetStateValidityRequest()
req.robot_state.joint_state.name = ['r_shoulder_pan_joint',
'r_shoulder_lift_joint',
'r_upper_arm_roll_joint',
'r_elbow_flex_joint',
'r_forearm_roll_joint',
'r_wrist_flex_joint',
'r_wrist_roll_joint']
req.robot_state.joint_state.position = [0.] * 7
req.robot_state.joint_state.position[0] = 0.4
req.robot_state.joint_state.position[3] = -0.4
req.robot_state.joint_state.header.stamp = rospy.Time.now()
req.check_collisions = True
res = get_state_validity.call(req)
if res.error_code.val == res.error_code.SUCCESS:
rospy.loginfo('Requested state is not in collision')
else:
rospy.loginfo('Requested state is in collision. Error code: %d'%(res.error_code.val))
| [
[
1,
0,
0.05,
0.025,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.05,
0.025,
0,
0.66,
0.1667,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.075,
0.025,
0,
0.66,
... | [
"import roslib; roslib.load_manifest('arm_navigation_tutorials')",
"import roslib; roslib.load_manifest('arm_navigation_tutorials')",
"import sys",
"import rospy",
"from planning_environment_msgs.srv import GetStateValidity",
"from planning_environment_msgs.srv import GetStateValidityRequest",
"if __nam... |
import sys
import numpy as np, math
import add_cylinder as ac
import online_collision_detection as ocd
import force_visualize_test as fvt
import roslib; roslib.load_manifest('arm_navigation_tutorials')
import rospy
from mapping_msgs.msg import CollisionObject
from visualization_msgs.msg import Marker
import hrl_lib.viz as hv
roslib.load_manifest('hrl_pr2_lib')
import hrl_pr2_lib.pr2_arms as pa
def contact_info_list_to_dict(cont_info_list):
ci = cont_info_list[0]
frm = ci.header.frame_id
# print 'frame:', frm
b1 = ci.contact_body_1
b2 = ci.contact_body_2
contact_dict = {}
pts_list = []
for ci in cont_info_list:
if frm != ci.header.frame_id:
rospy.logerr('initial frame_id: %s and current frame_id: %s'%(frm, ci.header.frame_id))
b1 = ci.contact_body_1
b2 = ci.contact_body_2
two_bodies = b1 + '+' + b2
if two_bodies not in contact_dict:
contact_dict[two_bodies] = []
contact_dict[two_bodies].append((ci.position.x, ci.position.y, ci.position.z))
return contact_dict
def visualize_contact_dict(cd, marker_pub, fts):
color_list = [(1.,0.,0.), (0.,1.,0.), (0.,0.,1.), (1.,1.,0.),
(1.,0.,1.), (0.,1.,1.), (0.5,1.,0.), (0.5,0.,1.),
(0.,0.5,1.) ]
pts_list = []
cs_list = []
marker_list = []
for i, k in enumerate(cd.keys()):
pts = np.matrix(cd[k]).T
c = color_list[i]
cs = np.ones((4, pts.shape[1]))
cs[0,:] = c[0]
cs[1,:] = c[1]
cs[2,:] = c[2]
pts_list.append(pts)
cs_list.append(cs)
print '# of contact points:', pts.shape[1]
mn = np.mean(pts, 1)
f = fts.get_forces()
m1, m2 = fvt.get_arrow_text_markers(mn, f, 'base_footprint',
m_id = 2*i+1, duration=0.5)
marker_pub.publish(m1)
marker_pub.publish(m2)
m = hv.list_marker(np.column_stack(pts_list),
np.column_stack(cs_list), (0.01, 0.01, 0.01),
'points', 'base_footprint', duration=1.0,
m_id=0)
t_now = rospy.Time.now()
m.header.stamp = t_now
marker_pub.publish(m)
for m in marker_list:
m.header.stamp = rospy.Time.now()
marker_pub.publish(m)
if __name__ == '__main__':
rospy.init_node('pr2_skin_simulate')
pub = rospy.Publisher('collision_object', CollisionObject)
marker_pub = rospy.Publisher('/skin/viz_marker', Marker)
fts = fvt.object_ft_sensors()
fts.bias_fts()
pr2_arms = pa.PR2Arms()
r_arm, l_arm = 0, 1
arm = r_arm
raw_input('Touch the object and then hit ENTER.')
ee_pos, ee_rot = pr2_arms.end_effector_pos(arm)
print 'ee_pos:', ee_pos.flatten()
print 'ee_pos.shape:', ee_pos.shape
trans, quat = pr2_arms.tf_lstnr.lookupTransform('/base_footprint',
'/torso_lift_link', rospy.Time(0))
height = ee_pos[2] + trans[2]
ee_pos[2] = -trans[2]
ac.add_cylinder('pole', ee_pos, 0.02, height, '/torso_lift_link', pub)
rospy.loginfo('Now starting the loop where I get contact locations.')
col_det = ocd.online_collision_detector()
while not rospy.is_shutdown():
rospy.sleep(0.1)
res = col_det.check_validity(pr2_arms, arm)
if res.error_code.val == res.error_code.SUCCESS:
rospy.loginfo('No contact')
else:
contact_dict = contact_info_list_to_dict(res.contacts)
print 'contact_dict.keys:', contact_dict.keys()
visualize_contact_dict(contact_dict, marker_pub, fts)
| [
[
1,
0,
0.0172,
0.0086,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0259,
0.0086,
0,
0.66,
0.0667,
954,
0,
2,
0,
0,
954,
0,
0
],
[
1,
0,
0.0431,
0.0086,
0,
... | [
"import sys",
"import numpy as np, math",
"import add_cylinder as ac",
"import online_collision_detection as ocd",
"import force_visualize_test as fvt",
"import roslib; roslib.load_manifest('arm_navigation_tutorials')",
"import roslib; roslib.load_manifest('arm_navigation_tutorials')",
"import rospy",... |
import roslib; roslib.load_manifest('arm_navigation_tutorials')
import sys
import rospy
from mapping_msgs.msg import CollisionObject
from mapping_msgs.msg import CollisionObjectOperation
from geometric_shapes_msgs.msg import Shape
from geometry_msgs.msg import Pose
def add_cylinder(id, bottom, radius, height, frameid, pub):
cylinder_object = CollisionObject()
cylinder_object.id = id
cylinder_object.operation.operation = CollisionObjectOperation.ADD
cylinder_object.header.frame_id = frameid
cylinder_object.header.stamp = rospy.Time.now()
shp = Shape()
shp.type = Shape.CYLINDER
shp.dimensions = [0, 0]
shp.dimensions[0] = radius
shp.dimensions[1] = height
pose = Pose()
pose.position.x = bottom[0]
pose.position.y = bottom[1]
pose.position.z = bottom[2] + height/2.
pose.orientation.x = 0
pose.orientation.y = 0
pose.orientation.z = 0
pose.orientation.w = 1
cylinder_object.shapes.append(shp)
cylinder_object.poses.append(pose)
pub.publish(cylinder_object)
if __name__ == '__main__':
rospy.init_node('add_cylinder_python')
pub = rospy.Publisher('collision_object', CollisionObject)
rospy.sleep(2.)
add_cylinder('pole', (0.6, -0.6, 0.), 0.1, 0.75, 'base_link', pub)
rospy.loginfo('Should have published')
rospy.sleep(2.)
| [
[
1,
0,
0.04,
0.02,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.04,
0.02,
0,
0.66,
0.1111,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.06,
0.02,
0,
0.66,
0.22... | [
"import roslib; roslib.load_manifest('arm_navigation_tutorials')",
"import roslib; roslib.load_manifest('arm_navigation_tutorials')",
"import sys",
"import rospy",
"from mapping_msgs.msg import CollisionObject",
"from mapping_msgs.msg import CollisionObjectOperation",
"from geometric_shapes_msgs.msg imp... |
import roslib; roslib.load_manifest('arm_navigation_tutorials')
import sys
import rospy
import hrl_lib.transforms as tr
from planning_environment_msgs.srv import GetStateValidity
from planning_environment_msgs.srv import GetStateValidityRequest
from sensor_msgs.msg import JointState
roslib.load_manifest('hrl_pr2_lib')
import hrl_pr2_lib.pr2_arms as pa
class online_collision_detector():
def __init__(self):
srv_nm = 'environment_server_right_arm/get_state_validity'
rospy.wait_for_service(srv_nm)
self.state_validator = rospy.ServiceProxy(srv_nm, GetStateValidity,
persistent=True)
def check_validity(self, pr2_arms, arm):
q = pr2_arms.get_joint_angles(arm)
joint_nm_list = ['r_shoulder_pan_joint', 'r_shoulder_lift_joint',
'r_upper_arm_roll_joint', 'r_elbow_flex_joint',
'r_forearm_roll_joint', 'r_wrist_flex_joint',
'r_wrist_roll_joint']
req = GetStateValidityRequest()
req.robot_state.joint_state.name = joint_nm_list
req.robot_state.joint_state.position = q
req.robot_state.joint_state.header.stamp = rospy.Time.now()
req.check_collisions = True
res = self.state_validator.call(req)
return res
if __name__ == '__main__':
rospy.init_node('get_state_validity_python')
pr2_arms = pa.PR2Arms()
r_arm, l_arm = 0, 1
arm = r_arm
col_det = online_collision_detector()
while not rospy.is_shutdown():
rospy.sleep(0.1)
res = col_det.check_validity(pr2_arms, arm)
if res.error_code.val == res.error_code.SUCCESS:
rospy.loginfo('Requested state is not in collision')
else:
rospy.loginfo('Requested state is in collision. Error code: %d'%(res.error_code.val))
| [
[
1,
0,
0.0333,
0.0167,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0333,
0.0167,
0,
0.66,
0.0909,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.05,
0.0167,
0,
0.66... | [
"import roslib; roslib.load_manifest('arm_navigation_tutorials')",
"import roslib; roslib.load_manifest('arm_navigation_tutorials')",
"import sys",
"import rospy",
"import hrl_lib.transforms as tr",
"from planning_environment_msgs.srv import GetStateValidity",
"from planning_environment_msgs.srv import ... |
#
# Copyright (c) 2010, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Author: Advait Jain (advait@cc.gatech.edu), Healthcare Robotics Lab, Georgia Tech
import roslib; roslib.load_manifest('arm_navigation_tutorials')
import sys
import rospy
from planning_environment_msgs.srv import GetStateValidity
from planning_environment_msgs.srv import GetStateValidityRequest
if __name__ == '__main__':
rospy.init_node('get_state_validity_python')
srv_nm = 'environment_server_right_arm/get_state_validity'
rospy.wait_for_service(srv_nm)
get_state_validity = rospy.ServiceProxy(srv_nm, GetStateValidity)
req = GetStateValidityRequest()
req.robot_state.joint_state.name = ['r_shoulder_pan_joint',
'r_shoulder_lift_joint',
'r_upper_arm_roll_joint',
'r_elbow_flex_joint',
'r_forearm_roll_joint',
'r_wrist_flex_joint',
'r_wrist_roll_joint']
req.robot_state.joint_state.position = [0.] * 7
req.robot_state.joint_state.position[0] = 0.4
req.robot_state.joint_state.position[3] = -0.4
req.robot_state.joint_state.header.stamp = rospy.Time.now()
req.check_collisions = True
res = get_state_validity.call(req)
if res.error_code.val == res.error_code.SUCCESS:
rospy.loginfo('Requested state is not in collision')
else:
rospy.loginfo('Requested state is in collision. Error code: %d'%(res.error_code.val))
| [
[
1,
0,
0.4412,
0.0147,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.4412,
0.0147,
0,
0.66,
0.1667,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.4559,
0.0147,
0,
0.... | [
"import roslib; roslib.load_manifest('arm_navigation_tutorials')",
"import roslib; roslib.load_manifest('arm_navigation_tutorials')",
"import sys",
"import rospy",
"from planning_environment_msgs.srv import GetStateValidity",
"from planning_environment_msgs.srv import GetStateValidityRequest",
"if __nam... |
#
# Copyright (c) 2010, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Author: Advait Jain (advait@cc.gatech.edu), Healthcare Robotics Lab, Georgia Tech
import roslib; roslib.load_manifest('arm_navigation_tutorials')
import sys
import rospy
from mapping_msgs.msg import CollisionObject
from mapping_msgs.msg import CollisionObjectOperation
from geometric_shapes_msgs.msg import Shape
from geometry_msgs.msg import Pose
def add_cylinder(id, bottom, radius, height, frameid):
cylinder_object = CollisionObject()
cylinder_object.id = id
cylinder_object.operation.operation = CollisionObjectOperation.ADD
cylinder_object.header.frame_id = frameid
cylinder_object.header.stamp = rospy.Time.now()
shp = Shape()
shp.type = Shape.CYLINDER
shp.dimensions = [0, 0]
shp.dimensions[0] = radius
shp.dimensions[1] = height
pose = Pose()
pose.position.x = bottom[0]
pose.position.y = bottom[1]
pose.position.z = bottom[2] + height/2.
pose.orientation.x = 0
pose.orientation.y = 0
pose.orientation.z = 0
pose.orientation.w = 1
cylinder_object.shapes.append(shp)
cylinder_object.poses.append(pose)
pub.publish(cylinder_object)
if __name__ == '__main__':
rospy.init_node('add_cylinder_python')
pub = rospy.Publisher('collision_object', CollisionObject)
rospy.sleep(2.)
add_cylinder('pole', (0.6, -0.6, 0.), 0.1, 0.75, 'base_link')
rospy.loginfo('Should have published')
rospy.sleep(2.)
| [
[
1,
0,
0.3924,
0.0127,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.3924,
0.0127,
0,
0.66,
0.1111,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.4051,
0.0127,
0,
0.... | [
"import roslib; roslib.load_manifest('arm_navigation_tutorials')",
"import roslib; roslib.load_manifest('arm_navigation_tutorials')",
"import sys",
"import rospy",
"from mapping_msgs.msg import CollisionObject",
"from mapping_msgs.msg import CollisionObjectOperation",
"from geometric_shapes_msgs.msg imp... |
import PyKDL as kdl
import numpy as np, math
import roslib; roslib.load_manifest('pr2_arms_kdl')
import rospy
import hrl_lib.kdl_utils as ku
class PR2_arm_kdl():
def __init__(self):
self.right_chain = self.create_right_chain()
fk, ik_v, ik_p = self.create_solvers(self.right_chain)
self.right_fk = fk
self.right_ik_v = ik_v
self.right_ik_p = ik_p
def create_right_chain(self):
ch = kdl.Chain()
self.right_arm_base_offset_from_torso_lift_link = np.matrix([0., -0.188, 0.]).T
# shoulder pan
ch.addSegment(kdl.Segment(kdl.Joint(kdl.Joint.RotZ),kdl.Frame(kdl.Vector(0.1,0.,0.))))
# shoulder lift
ch.addSegment(kdl.Segment(kdl.Joint(kdl.Joint.RotY),kdl.Frame(kdl.Vector(0.,0.,0.))))
# upper arm roll
ch.addSegment(kdl.Segment(kdl.Joint(kdl.Joint.RotX),kdl.Frame(kdl.Vector(0.4,0.,0.))))
# elbox flex
ch.addSegment(kdl.Segment(kdl.Joint(kdl.Joint.RotY),kdl.Frame(kdl.Vector(0.0,0.,0.))))
# forearm roll
ch.addSegment(kdl.Segment(kdl.Joint(kdl.Joint.RotX),kdl.Frame(kdl.Vector(0.321,0.,0.))))
# wrist flex
ch.addSegment(kdl.Segment(kdl.Joint(kdl.Joint.RotY),kdl.Frame(kdl.Vector(0.,0.,0.))))
# wrist roll
ch.addSegment(kdl.Segment(kdl.Joint(kdl.Joint.RotX),kdl.Frame(kdl.Vector(0.,0.,0.))))
return ch
def create_solvers(self, ch):
fk = kdl.ChainFkSolverPos_recursive(ch)
ik_v = kdl.ChainIkSolverVel_pinv(ch)
ik_p = kdl.ChainIkSolverPos_NR(ch, fk, ik_v)
return fk, ik_v, ik_p
def FK_kdl(self, arm, q, link_number):
if arm == 'right_arm':
fk = self.right_fk
endeffec_frame = kdl.Frame()
kinematics_status = fk.JntToCart(q, endeffec_frame,
link_number)
if kinematics_status >= 0:
return endeffec_frame
else:
rospy.loginfo('Could not compute forward kinematics.')
return None
else:
msg = '%s arm not supported.'%(arm)
rospy.logerr(msg)
raise RuntimeError(msg)
## returns point in torso lift link.
def FK_all(self, arm, q, link_number = 7):
q = self.pr2_to_kdl(q)
frame = self.FK_kdl(arm, q, link_number)
pos = frame.p
pos = ku.kdl_vec_to_np(pos)
pos = pos + self.right_arm_base_offset_from_torso_lift_link
m = frame.M
rot = ku.kdl_rot_to_np(m)
return pos, rot
def kdl_to_pr2(self, q):
if q == None:
return None
q_pr2 = [0] * 7
q_pr2[0] = q[0]
q_pr2[1] = q[1]
q_pr2[2] = q[2]
q_pr2[3] = q[3]
q_pr2[4] = q[4]
q_pr2[5] = q[5]
q_pr2[6] = q[6]
return q_pr2
def pr2_to_kdl(self, q):
if q == None:
return None
n = len(q)
q_kdl = kdl.JntArray(n)
for i in range(n):
q_kdl[i] = q[i]
return q_kdl
if __name__ == '__main__':
roslib.load_manifest('hrl_pr2_lib')
import hrl_pr2_lib.pr2_arms as pa
import hrl_lib.viz as hv
from visualization_msgs.msg import Marker
rospy.init_node('kdl_pr2_test')
marker_pub = rospy.Publisher('/kdl_pr2_arms/viz_marker', Marker)
pr2_arms = pa.PR2Arms(gripper_point=(0.,0.,0.))
pr2_kdl = PR2_arm_kdl()
r_arm, l_arm = 0, 1
while not rospy.is_shutdown():
q = pr2_arms.get_joint_angles(r_arm)
p, r = pr2_kdl.FK_all('right_arm', q, 7)
m = hv.create_frame_marker(p, r, 0.3, 'torso_lift_link')
time_stamp = rospy.Time.now()
m.header.stamp = time_stamp
marker_pub.publish(m)
rospy.sleep(0.1)
| [
[
1,
0,
0.0085,
0.0085,
0,
0.66,
0,
198,
0,
1,
0,
0,
198,
0,
0
],
[
1,
0,
0.0254,
0.0085,
0,
0.66,
0.1429,
954,
0,
2,
0,
0,
954,
0,
0
],
[
1,
0,
0.0424,
0.0085,
0,
... | [
"import PyKDL as kdl",
"import numpy as np, math",
"import roslib; roslib.load_manifest('pr2_arms_kdl')",
"import roslib; roslib.load_manifest('pr2_arms_kdl')",
"import rospy",
"import hrl_lib.kdl_utils as ku",
"class PR2_arm_kdl():\n\n def __init__(self):\n self.right_chain = self.create_righ... |
import numpy as np, math
import roslib; roslib.load_manifest('point_cloud_ros')
import rospy
import hrl_tilting_hokuyo.display_3d_mayavi as d3m
from point_cloud_ros.msg import OccupancyGrid
import point_cloud_ros.occupancy_grid as pog
## convert OccupancyGrid message to the occupancy_grid_3d object.
# @param to_binary - want the occupancy grid to be binarified.
# @return occupancy_grid_3d object
def og_msg_to_og3d(og, to_binary=True):
c = np.matrix([og.center.x, og.center.y, og.center.z]).T
s = np.matrix([og.grid_size.x, og.grid_size.y, og.grid_size.z]).T
r = np.matrix([og.resolution.x, og.resolution.y, og.resolution.z]).T
og3d = pog.occupancy_grid_3d(c, s, r, np.array(og.data),
og.occupancy_threshold, to_binary = to_binary)
return og3d
## convert occupancy_grid_3d object to OccupancyGrid message.
# sets the frame to base_link and stamp to the current time.
# @return OccupancyGrid object
def og3d_to_og_msg(og3d):
og = OccupancyGrid()
og.center.x = og3d.center[0,0]
og.center.y = og3d.center[1,0]
og.center.z = og3d.center[2,0]
og.grid_size.x = og3d.size[0,0]
og.grid_size.y = og3d.size[1,0]
og.grid_size.z = og3d.size[2,0]
og.resolution.x = og3d.resolution[0,0]
og.resolution.y = og3d.resolution[1,0]
og.resolution.z = og3d.resolution[2,0]
og.occupancy_threshold = 1
og.data = og3d.grid.flatten().tolist()
og.header.frame_id = 'base_link'
og.header.stamp = rospy.rostime.get_rostime()
return og
## create an OccupancyGrid msg object for the purpose of setting the
# grid parameters for pc_to_og node.
# @param center - 3x1 np matrix.
# @param size - 3x1 np matrix.
# @param resolution - 3x1 np matrix.
# @param occupancy_threshold - integer
# @param frame_id - string.
def og_param_msg(center, size, resolution, occupancy_threshold, frame_id):
og = OccupancyGrid()
og.center.x = center[0,0]
og.center.y = center[1,0]
og.center.z = center[2,0]
og.grid_size.x = size[0,0]
og.grid_size.y = size[1,0]
og.grid_size.z = size[2,0]
og.resolution.x = resolution[0,0]
og.resolution.y = resolution[1,0]
og.resolution.z = resolution[2,0]
og.occupancy_threshold = occupancy_threshold
og.header.frame_id = frame_id
og.header.stamp = rospy.rostime.get_rostime()
return og
if __name__ == '__main__':
rospy.init_node('og_sample_python')
param_list = [None, False]
rospy.Subscriber('occupancy_grid', OccupancyGrid, cb, param_list)
rospy.logout('Ready')
while not rospy.is_shutdown():
if param_list[1] == True:
og3d = param_list[0]
print 'grid_shape:', og3d.grid.shape
pts = og3d.grid_to_points()
print pts.shape
break
rospy.sleep(0.1)
d3m.plot_points(pts)
d3m.show()
| [
[
1,
0,
0.0217,
0.0109,
0,
0.66,
0,
954,
0,
2,
0,
0,
954,
0,
0
],
[
1,
0,
0.0435,
0.0109,
0,
0.66,
0.1,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0435,
0.0109,
0,
0.6... | [
"import numpy as np, math",
"import roslib; roslib.load_manifest('point_cloud_ros')",
"import roslib; roslib.load_manifest('point_cloud_ros')",
"import rospy",
"import hrl_tilting_hokuyo.display_3d_mayavi as d3m",
"from point_cloud_ros.msg import OccupancyGrid",
"import point_cloud_ros.occupancy_grid as... |
#!/usr/bin/python
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
## Testing point_cloud_mapping from python
## author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import roslib; roslib.load_manifest('point_cloud_ros')
import rospy
from sensor_msgs.msg import PointCloud
from geometry_msgs.msg import Point32
import numpy as np, math
from numpy import pi
import sys, os, optparse, time
import copy
import hrl_lib.util as ut
import point_cloud_ros.point_cloud_utils as pcu
from enthought.mayavi import mlab
def SphereToCart(rho, theta, phi):
x = rho * np.sin(phi) * np.cos(theta)
y = rho * np.sin(phi) * np.sin(theta)
z = rho * np.cos(phi)
return (x,y,z)
def generate_sphere():
pts = 4e3
theta = np.random.rand(pts) * 2*pi
phi = np.random.rand(pts) * pi
rho = 1*np.ones(len(theta))
x,y,z = SphereToCart(rho,theta,phi)
pts = np.matrix(np.row_stack((x,y,z)))
return pcu.np_points_to_ros(pts)
def plot_cloud(pts):
x = pts[0,:].A1
y = pts[1,:].A1
z = pts[2,:].A1
mlab.points3d(x,y,z,mode='point')
mlab.show()
def plot_normals(pts,normals,curvature=None):
x = pts[0,:].A1
y = pts[1,:].A1
z = pts[2,:].A1
u = normals[0,:].A1
v = normals[1,:].A1
w = normals[2,:].A1
if curvature != None:
#mlab.points3d(x,y,z,curvature,mode='point',scale_factor=1.0)
mlab.points3d(x,y,z,curvature,mode='sphere',scale_factor=0.1,mask_points=1)
mlab.colorbar()
else:
mlab.points3d(x,y,z,mode='point')
mlab.quiver3d(x,y,z,u,v,w,mask_points=16,scale_factor=0.1)
# mlab.axes()
mlab.show()
def downsample_cb(cloud_down):
print 'downsample_cb got called.'
pts = ros_pts_to_np(cloud_down.pts)
x = pts[0,:].A1
y = pts[1,:].A1
z = pts[2,:].A1
mlab.points3d(x,y,z,mode='point')
mlab.show()
def normals_cb(normals_cloud):
print 'normals_cb got called.'
d = {}
t0 = time.time()
pts = ros_pts_to_np(normals_cloud.pts)
t1 = time.time()
print 'time to go from ROS point cloud to np matrx:', t1-t0
d['pts'] = pts
if normals_cloud.chan[0].name != 'nx':
print '################################################################################'
print 'synthetic_point_clouds.normals_cloud: DANGER DANGER normals_cloud.chan[0] is NOT nx, it is:', normals_cloud.chan[0].name
print 'Exiting...'
print '################################################################################'
sys.exit()
normals_list = []
for i in range(3):
normals_list.append(normals_cloud.chan[i].vals)
d['normals'] = np.matrix(normals_list)
d['curvature'] = normals_cloud.chan[3].vals
print 'd[\'pts\'].shape:', d['pts'].shape
print 'd[\'normals\'].shape:', d['normals'].shape
ut.save_pickle(d, 'normals_cloud_'+ut.formatted_time()+'.pkl')
if __name__ == '__main__':
p = optparse.OptionParser()
p.add_option('--sphere', action='store_true', dest='sphere',
help='sample a sphere and publish the point cloud')
p.add_option('--plot', action='store_true', dest='plot',
help='plot the result')
p.add_option('-f', action='store', type='string',dest='fname',
default=None, help='pkl file with the normals.')
p.add_option('--pc', action='store', type='string',dest='pc_fname',
default=None, help='pkl file with 3xN numpy matrix (numpy point cloud).')
opt, args = p.parse_args()
sphere_flag = opt.sphere
plot_flag = opt.plot
fname = opt.fname
pc_fname = opt.pc_fname
if sphere_flag or pc_fname!=None:
rospy.init_node('point_cloud_tester', anonymous=True)
pub = rospy.Publisher("tilt_laser_cloud", PointCloud)
rospy.Subscriber("cloud_normals", PointCloud, normals_cb)
rospy.Subscriber("cloud_downsampled", PointCloud, downsample_cb)
time.sleep(1)
if sphere_flag:
pc = generate_sphere()
if pc_fname != None:
pts = ut.load_pickle(pc_fname)
print 'before np_points_to_ros'
t0 = time.time()
pc = pcu.np_points_to_ros(pts)
t1 = time.time()
print 'time to go from numpy to ros:', t1-t0
t0 = time.time()
pcu.ros_pointcloud_to_np(pc)
t1 = time.time()
print 'time to go from ros to numpy:', t1-t0
pub.publish(pc)
rospy.spin()
if plot_flag:
if fname == None:
print 'Please give a pkl file for plotting (-f option)'
print 'Exiting...'
sys.exit()
d = ut.load_pickle(fname)
plot_normals(d['pts'],d['normals'],d['curvature'])
| [
[
1,
0,
0.1737,
0.0053,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.1737,
0.0053,
0,
0.66,
0.0556,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.1842,
0.0053,
0,
0.... | [
"import roslib; roslib.load_manifest('point_cloud_ros')",
"import roslib; roslib.load_manifest('point_cloud_ros')",
"import rospy",
"from sensor_msgs.msg import PointCloud",
"from geometry_msgs.msg import Point32",
"import numpy as np, math",
"from numpy import pi",
"import sys, os, optparse, time",
... |
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import sys, optparse, os
import time
import math, numpy as np
import scipy.ndimage as ni
import copy
import hrl_lib.util as ut, hrl_lib.transforms as tr
## subtract occupancy grids. og1 = og1-og2
#
# @param og1 - occupancy_grid_3d object.
# @param og2 - occupancy_grid_3d object.
#
#will position og2 at an appropriate location within og1 (hopefully)
#will copy points in og2 but not in og1 into og1
#
# points corresponding to the gird cells whose occupancy drops to
# zero will still be in grid_points_list
#UNTESTED:
# * subtracting grids of different sizes.
# * how the rotation_z of the occupancy grid will affect things.
def subtract(og1,og2):
if np.all(og1.resolution==og2.resolution) == False:
print 'occupancy_grid_3d.subtract: The resolution of the two grids is not the same.'
print 'res1, res2:', og1.resolution.A1.tolist(), og2.resolution.A1.tolist()
print 'Exiting...'
sys.exit()
sub_tlb = og2.tlb
sub_brf = og2.brf
sub_tlb_idx = np.round((sub_tlb-og1.brf)/og1.resolution)
sub_brf_idx = np.round((sub_brf-og1.brf)/og1.resolution)
x_s,y_s,z_s = int(sub_brf_idx[0,0]),int(sub_brf_idx[1,0]),int(sub_brf_idx[2,0])
x_e,y_e,z_e = int(sub_tlb_idx[0,0]),int(sub_tlb_idx[1,0]),int(sub_tlb_idx[2,0])
x_e = min(x_e+1,og1.grid_shape[0,0])
y_e = min(y_e+1,og1.grid_shape[1,0])
z_e = min(z_e+1,og1.grid_shape[2,0])
sub_grid = og1.grid[x_s:x_e,y_s:y_e,z_s:z_e]
if np.any(og1.grid_shape!=og2.grid_shape):
print '#############################################################################'
print 'WARNING: occupancy_grid_3d.subtract has not been tested for grids of different sizes.'
print '#############################################################################'
sub_grid = sub_grid-og2.grid
sub_grid = np.abs(sub_grid) # for now.
og1.grid[x_s:x_e,y_s:y_e,z_s:z_e] = sub_grid
idxs = np.where(sub_grid>=1)
shp = og2.grid_shape
list_idxs = (idxs[0]+idxs[1]*shp[0,0]+idxs[2]*shp[0,0]*shp[1,0]).tolist()
og1_list_idxs = (idxs[0]+x_s+(idxs[1]+y_s)*shp[0,0]+(idxs[2]+z_s)*shp[0,0]*shp[1,0]).tolist()
og1_list_len = len(og1.grid_points_list)
for og1_pts_idxs,pts_idxs in zip(og1_list_idxs,list_idxs):
if og1_pts_idxs<og1_list_len:
og1.grid_points_list[og1_pts_idxs] += og2.grid_points_list[pts_idxs]
## class which implements the occupancy grid
class occupancy_grid_3d():
##
# @param brf - 3x1 matrix. Bottom Right Front.
# @param tlb - 3x1 matrix (coord of center of the top left back cell)
# @param resolution - 3x1 matrix. size of each cell (in meters) along
# the different directions.
def __init__(self, brf, tlb, resolution, rotation_z=math.radians(0.)):
#print np.round((tlb-brf)/resolution).astype('int')+1
self.grid = np.zeros(np.round((tlb-brf)/resolution).astype('int')+1,dtype='int')
self.tlb = tlb
self.brf = brf
self.grid_shape = np.matrix(self.grid.shape).T
self.resolution = resolution
n_cells = self.grid.shape[0]*self.grid.shape[1]*self.grid.shape[2]
self.grid_points_list = [[] for i in range(n_cells)]
self.rotation_z = rotation_z
## returns list of 8 tuples of 3x1 points which form the edges of the grid.
# Useful for displaying the extents of the volume of interest (VOI).
# @return list of 8 tuples of 3x1 points which form the edges of the grid.
def grid_lines(self, rotation_angle=0.):
grid_size = np.multiply(self.grid_shape,self.resolution)
rot_mat = tr.rotZ(rotation_angle)
p5 = self.tlb
p6 = p5+np.matrix([0.,-grid_size[1,0],0.]).T
p8 = p5+np.matrix([0.,0.,-grid_size[2,0]]).T
p7 = p8+np.matrix([0.,-grid_size[1,0],0.]).T
p3 = self.brf
p4 = p3+np.matrix([0.,grid_size[1,0],0.]).T
p2 = p3+np.matrix([0.,0.,grid_size[2,0]]).T
p1 = p2+np.matrix([0.,grid_size[1,0],0.]).T
p1 = rot_mat*p1
p2 = rot_mat*p2
p3 = rot_mat*p3
p4 = rot_mat*p4
p5 = rot_mat*p5
p6 = rot_mat*p6
p7 = rot_mat*p7
p8 = rot_mat*p8
l = [(p1,p2),(p1,p4),(p2,p3),(p3,p4),(p5,p6),(p6,p7),(p7,p8),(p8,p5),(p1,p5),(p2,p6),(p4,p8),(p3,p7)]
#l = [(p5,p6),(p5,p3),(p1,p2)]
return l
## fill the occupancy grid.
# @param pts - 3xN matrix of points.
# @param ignore_z - not use the z coord of the points. grid will be like a 2D grid.
#
#each cell of the grid gets filled the number of points that fall in the cell.
def fill_grid(self,pts,ignore_z=False):
if ignore_z:
idx = np.where(np.min(np.multiply(pts[0:2,:]>self.brf[0:2,:],
pts[0:2,:]<self.tlb[0:2,:]),0))[1]
else:
idx = np.where(np.min(np.multiply(pts[0:3,:]>self.brf,pts[0:3,:]<self.tlb),0))[1]
if idx.shape[1] == 0:
print 'aha!'
return
pts = pts[:,idx.A1.tolist()]
# Find coordinates
p_all = np.round((pts[0:3,:]-self.brf)/self.resolution)
# Rotate points
pts[0:3,:] = tr.Rz(self.rotation_z).T*pts[0:3,:]
for i,p in enumerate(p_all.astype('int').T):
if ignore_z:
p[0,2] = 0
if np.any(p<0) or np.any(p>=self.grid_shape.T):
continue
tup = tuple(p.A1)
self.grid_points_list[
tup[0] + self.grid_shape[0,0] *
tup[1] + self.grid_shape[0,0] *
self.grid_shape[1,0] *
tup[2]].append(pts[:,i])
self.grid[tuple(p.A1)] += 1
def to_binary(self,thresh=1):
''' all cells with occupancy>=thresh set to 1, others set to 0.
'''
filled = (self.grid>=thresh)
self.grid[np.where(filled==True)] = 1
self.grid[np.where(filled==False)] = 0
def argmax_z(self,index_min=-np.Inf,index_max=np.Inf,search_up=False,search_down=False):
''' searches in the z direction for maximum number of cells with occupancy==1
call this function after calling to_binary()
returns index.
'''
index_min = int(max(index_min,0))
index_max = int(min(index_max,self.grid_shape[2,0]-1))
z_count_mat = []
#for i in xrange(self.grid_shape[2,0]):
for i in xrange(index_min,index_max+1):
z_count_mat.append(np.where(self.grid[:,:,i]==1)[0].shape[0])
if z_count_mat == []:
return None
z_count_mat = np.matrix(z_count_mat).T
max_z = np.argmax(z_count_mat)
max_count = z_count_mat[max_z,0]
max_z += index_min
print '#### max_count:', max_count
if search_up:
max_z_temp = max_z
for i in range(1,5):
#if (z_count_mat[max_z+i,0]*3.0)>max_count: #A
#if (z_count_mat[max_z+i,0]*8.0)>max_count: #B
if (max_z+i)>index_max:
break
if (z_count_mat[max_z+i-index_min,0]*5.0)>max_count: #B'
max_z_temp = max_z+i
max_z = max_z_temp
if search_down:
max_z_temp = max_z
for i in range(1,5):
if (max_z-i)<index_min:
break
if (max_z-i)>index_max:
continue
if (z_count_mat[max_z-i-index_min,0]*5.0)>max_count:
max_z_temp = max_z-i
max_z = max_z_temp
return max_z,max_count
def find_plane_indices(self,hmin=-np.Inf,hmax=np.Inf,assume_plane=False):
''' assume_plane - always return something.
returns list of indices (z) corrresponding to horizontal plane points.
returns [] if there is no plane
'''
index_min = int(max(round((hmin-self.brf[2,0])/self.resolution[2,0]),0))
index_max = int(min(round((hmax-self.brf[2,0])/self.resolution[2,0]),self.grid_shape[2,0]-1))
z_plane,max_count = self.argmax_z(index_min,index_max,search_up=True)
if z_plane == None:
print 'oink oink.'
return []
#---------- A
# extra_remove_meters = 0.01
# n_more_to_remove = int(round(extra_remove_meters/self.resolution[2,0]))
# l = range(max(z_plane-n_more_to_remove-1,0),
# min(z_plane+n_more_to_remove+1,self.grid_shape[2,0]-1))
#---------- B
extra_remove_meters = 0.005
n_more_to_remove = int(round(extra_remove_meters/self.resolution[2,0]))
l = range(max(z_plane-10,0),
min(z_plane+n_more_to_remove+1,self.grid_shape[2,0]-1))
# figure out whether this is indeed a plane.
if assume_plane == False:
n_more = int(round(0.1/self.resolution[2,0]))
l_confirm = l+ range(max(l),min(z_plane+n_more+1,self.grid_shape[2,0]-1))
grid_2d = np.max(self.grid[:,:,l],2)
n_plane_cells = grid_2d.sum()
grid_2d = ni.binary_fill_holes(grid_2d) # I want 4-connectivity while filling holes.
n_plane_cells = grid_2d.sum()
min_plane_pts_threshold = (self.grid_shape[0,0]*self.grid_shape[1,0])/4
print '###n_plane_cells:', n_plane_cells
print 'min_plane_pts_threshold:', min_plane_pts_threshold
print 'find_plane_indices grid shape:',self.grid_shape.T
if n_plane_cells < min_plane_pts_threshold:
print 'occupancy_grid_3d.find_plane_indices: There is no plane.'
print 'n_plane_cells:', n_plane_cells
print 'min_plane_pts_threshold:', min_plane_pts_threshold
l = []
return l
## get centroids of all the occupied cells as a 3xN np matrix
# @param occupancy_threshold - number of points in a cell for it to be "occupied"
# @return 3xN matrix of 3d coord of the cells which have occupancy >= occupancy_threshold
def grid_to_centroids(self,occupancy_threshold=1):
p = np.matrix(np.row_stack(np.where(self.grid>=occupancy_threshold))).astype('float')
p[0,:] = p[0,:]*self.resolution[0,0]
p[1,:] = p[1,:]*self.resolution[1,0]
p[2,:] = p[2,:]*self.resolution[2,0]
p += self.brf
return p
def grid_to_points(self,array=None,occupancy_threshold=1):
''' array - if not None then this will be used instead of self.grid
returns 3xN matrix of 3d coord of the cells which have occupancy >= occupancy_threshold
'''
if array == None:
array = self.grid
idxs = np.where(array>=occupancy_threshold)
list_idxs = (idxs[0]+idxs[1]*self.grid_shape[0,0]+idxs[2]*self.grid_shape[0,0]*self.grid_shape[1,0]).tolist()
l = []
for pts_idxs in list_idxs:
l += self.grid_points_list[pts_idxs]
if l == []:
p = np.matrix([])
else:
p = np.column_stack(l)
return p
def labeled_array_to_points(self,array,label):
''' returns coordinates of centers of grid cells corresponding to
label as a 3xN matrix.
'''
idxs = np.where(array==label)
list_idxs = (idxs[0]+idxs[1]*self.grid_shape[0,0]+idxs[2]*self.grid_shape[0,0]*self.grid_shape[1,0]).tolist()
l = []
for pts_idxs in list_idxs:
l += self.grid_points_list[pts_idxs]
if l == []:
p = np.matrix([])
else:
p = np.column_stack(l)
return p
def remove_vertical_plane(self):
''' removes plane parallel to the YZ plane.
changes grid.
returns plane_indices, slice corresponding to the vertical plane.
points behind the plane are lost for ever!
'''
self.grid = self.grid.swapaxes(2,0)
self.grid_shape = np.matrix(self.grid.shape).T
# z_max_first,max_count = self.argmax_z(search_up=False)
# z_max_second,max_count_second = self.argmax_z(index_min=z_max_first+int(round(0.03/self.resolution[0,0])) ,search_up=False)
z_max_first,max_count = self.argmax_z(search_down=False)
z_max_second,max_count_second = self.argmax_z(index_min=z_max_first+int(round(0.035/self.resolution[0,0])) ,search_down=False)
z_max_first,max_count = self.argmax_z(search_down=False)
#z_max = self.argmax_z(search_up=True)
if (max_count_second*1./max_count) > 0.3:
z_max = z_max_second
else:
z_max = z_max_first
print 'z_max_first', z_max_first
print 'z_max_second', z_max_second
print 'z_max', z_max
more = int(round(0.03/self.resolution[0,0]))
plane_indices = range(max(0,z_max-more),min(z_max+more,self.grid_shape[2,0]))
self.grid = self.grid.swapaxes(2,0)
self.grid_shape = np.matrix(self.grid.shape).T
ver_plane_slice = self.grid[plane_indices,:,:]
self.grid[plane_indices,:,:] = 0
max_x = max(plane_indices)
behind_indices = range(max_x,self.grid_shape[0,0])
self.grid[behind_indices,:,:] = 0
return plane_indices,ver_plane_slice
def remove_horizontal_plane(self, remove_below=True,hmin=-np.Inf,hmax=np.Inf,
extra_layers=0):
''' call after to_binary()
removes points corresponding to the horizontal plane from the grid.
remove_below - remove points below the plane also.
hmin,hmax - min and max possible height of the plane. (meters)
This function changes grid.
extra_layers - number of layers above the plane to remove. Sometimes
I want to be over zealous while removing plane points.
e.g. max_fwd_without_collision
it returns the slice which has been set to zero, in case you want to
leave the grid unchanged.
'''
l = self.find_plane_indices(hmin,hmax)
if l == []:
print 'occupancy_grid_3d.remove_horizontal_plane: No plane found.'
return None,l
add_num = min(10,self.grid_shape[2,0]-max(l)-1)
max_l = max(l)+add_num
l_edge = l+range(max(l),max_l+1)
grid_2d = np.max(self.grid[:,:,l_edge],2)
# grid_2d = ni.binary_dilation(grid_2d,iterations=1) # I want 4-connectivity while filling holes.
grid_2d = ni.binary_fill_holes(grid_2d) # I want 4-connectivity while filling holes.
connect_structure = np.empty((3,3),dtype='int')
connect_structure[:,:] = 1
eroded_2d = ni.binary_erosion(grid_2d,connect_structure,iterations=2)
grid_2d = grid_2d-eroded_2d
idxs = np.where(grid_2d!=0)
if max_l>max(l):
for i in range(min(5,add_num)):
self.grid[idxs[0],idxs[1],max(l)+i+1] = 0
if remove_below:
l = range(0,min(l)+1)+l
max_z = max(l)
for i in range(extra_layers):
l.append(max_z+i+1)
l_edge = l+range(max(l),max_l+1)
plane_and_below_pts = self.grid[:,:,l_edge]
self.grid[:,:,l] = 0 # set occupancy to zero.
return plane_and_below_pts,l_edge
def segment_objects(self, twod=False):
''' segments out objects after removing the plane.
call after calling to_binary.
returns labelled_array,n_labels
labelled_array - same dimen as occupancy grid, each object has a different label.
'''
plane_and_below_pts,l = self.remove_horizontal_plane(extra_layers=0)
if l == []:
print 'occupancy_grid_3d.segment_objects: There is no plane.'
return None,None
if twod == False:
labelled_arr,n_labels = self.find_objects()
else:
labelled_arr,n_labels = self.find_objects_2d()
self.grid[:,:,l] = plane_and_below_pts
return labelled_arr,n_labels
def find_objects_2d(self):
''' projects all points into the xy plane and then performs
segmentation by region growing.
'''
connect_structure = np.empty((3,3),dtype='int')
connect_structure[:,:] = 1
grid_2d = np.max(self.grid[:,:,:],2)
# grid_2d = ni.binary_erosion(grid_2d)
# grid_2d = ni.binary_erosion(grid_2d,connect_structure)
labeled_arr,n_labels = ni.label(grid_2d,connect_structure)
print 'found %d objects'%(n_labels)
labeled_arr_3d = self.grid.swapaxes(2,0)
labeled_arr_3d = labeled_arr_3d.swapaxes(1,2)
print 'labeled_arr.shape:',labeled_arr.shape
print 'labeled_arr_3d.shape:',labeled_arr_3d.shape
labeled_arr_3d = labeled_arr_3d*labeled_arr
labeled_arr_3d = labeled_arr_3d.swapaxes(2,0)
labeled_arr_3d = labeled_arr_3d.swapaxes(1,0)
labeled_arr = labeled_arr_3d
# I still want to count cells in 3d (thin but tall objects.)
if n_labels > 0:
labels_list = range(1,n_labels+1)
#count_objects = ni.sum(grid_2d,labeled_arr,labels_list)
count_objects = ni.sum(self.grid,labeled_arr,labels_list)
if n_labels == 1:
count_objects = [count_objects]
t0 = time.time()
new_labels_list = []
for c,l in zip(count_objects,labels_list):
if c > 3:
new_labels_list.append(l)
else:
labeled_arr[np.where(labeled_arr == l)] = 0
# relabel stuff
for nl,l in enumerate(new_labels_list):
labeled_arr[np.where(labeled_arr == l)] = nl+1
n_labels = len(new_labels_list)
t1 = time.time()
print 'time:', t1-t0
print 'found %d objects'%(n_labels)
# return labeled_arr,n_labels
return labeled_arr_3d,n_labels
def find_objects(self):
''' region growing kind of thing for segmentation. Useful if plane has been removed.
'''
connect_structure = np.empty((3,3,3),dtype='int')
grid = copy.copy(self.grid)
connect_structure[:,:,:] = 0
connect_structure[1,1,:] = 1
iterations = int(round(0.005/self.resolution[2,0]))
# iterations=5
#grid = ni.binary_closing(grid,connect_structure,iterations=iterations)
connect_structure[:,:,:] = 1
labeled_arr,n_labels = ni.label(grid,connect_structure)
print 'ho!'
print 'found %d objects'%(n_labels)
if n_labels == 0:
return labeled_arr,n_labels
labels_list = range(1,n_labels+1)
count_objects = ni.sum(grid,labeled_arr,labels_list)
if n_labels == 1:
count_objects = [count_objects]
# t0 = time.time()
# remove_labels = np.where(np.matrix(count_objects) <= 5)[1].A1.tolist()
# for r in remove_labels:
# labeled_arr[np.where(labeled_arr == r)] = 0
# t1 = time.time()
# labeled_arr,n_labels = ni.label(labeled_arr,connect_structure)
# print 'time:', t1-t0
t0 = time.time()
new_labels_list = []
for c,l in zip(count_objects,labels_list):
if c > 3:
new_labels_list.append(l)
else:
labeled_arr[np.where(labeled_arr == l)] = 0
# relabel stuff
for nl,l in enumerate(new_labels_list):
labeled_arr[np.where(labeled_arr == l)] = nl+1
n_labels = len(new_labels_list)
t1 = time.time()
print 'time:', t1-t0
print 'found %d objects'%(n_labels)
return labeled_arr,n_labels
if __name__ == '__main__':
import pygame_opengl_3d_display as po3d
import hokuyo.pygame_utils as pu
import processing_3d as p3d
p = optparse.OptionParser()
p.add_option('-f', action='store', type='string', dest='pkl_file_name',
help='file.pkl File with the scan,pos dict.',default=None)
p.add_option('-c', action='store', type='string', dest='pts_pkl',
help='pkl file with 3D points',default=None)
opt, args = p.parse_args()
pts_pkl = opt.pts_pkl
pkl_file_name = opt.pkl_file_name
#-------------- simple test ---------------
# gr = occupancy_grid_3d(np.matrix([0.,0.,0]).T, np.matrix([1.,1.,1]).T,
# np.matrix([1,1,1]).T)
# pts = np.matrix([[1.1,0,-0.2],[0,0,0],[0.7,0.7,0.3],[0.6,0.8,-0.2]]).T
# gr.fill_grid(pts)
## print gr.grid
resolution = np.matrix([0.01,0.01,0.01]).T
gr = occupancy_grid_3d(np.matrix([0.45,-0.5,-1.0]).T, np.matrix([0.65,0.05,-0.2]).T,
resolution)
if pts_pkl != None:
pts = ut.load_pickle(pts_pkl)
elif pkl_file_name != None:
dict = ut.load_pickle(pkl_file_name)
pos_list = dict['pos_list']
scan_list = dict['scan_list']
min_angle = math.radians(-40)
max_angle = math.radians(40)
l1 = dict['l1']
l2 = dict['l2']
pts = p3d.generate_pointcloud(pos_list, scan_list, min_angle, max_angle, l1, l2)
else:
print 'specify a pkl file -c or -f'
print 'Exiting...'
sys.exit()
print 'started filling the grid'
t0 = time.time()
gr.fill_grid(pts)
t1 = time.time()
print 'time to fill the grid:', t1-t0
#grid_pts = gr.grid_to_points()
grid_pts = gr.grid_to_centroids()
## print grid_pts
cloud = pu.CubeCloud(grid_pts,(0,0,0),(resolution/2).A1.tolist())
pc = pu.PointCloud(pts,(100,100,100))
lc = pu.LineCloud(gr.grid_lines(),(100,100,0))
po3d.run([cloud,pc,lc])
| [
[
1,
0,
0.0489,
0.0016,
0,
0.66,
0,
509,
0,
3,
0,
0,
509,
0,
0
],
[
1,
0,
0.0506,
0.0016,
0,
0.66,
0.125,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.0538,
0.0016,
0,
0... | [
"import sys, optparse, os",
"import time",
"import math, numpy as np",
"import scipy.ndimage as ni",
"import copy",
"import hrl_lib.util as ut, hrl_lib.transforms as tr",
"def subtract(og1,og2):\n\n if np.all(og1.resolution==og2.resolution) == False:\n print('occupancy_grid_3d.subtract: The re... |
import roslib; roslib.load_manifest('point_cloud_ros')
from sensor_msgs.msg import PointCloud
from geometry_msgs.msg import Point32
from sensor_msgs.msg import ChannelFloat32
import numpy as np
import time
## PointCloud -> 3xN np matrix
# @param ros_pointcloud - robot_msgs/PointCloud
# @return 3xN np matrix
def ros_pointcloud_to_np(ros_pointcloud):
''' ros PointCloud.pts -> 3xN numpy matrix
'''
return ros_pts_to_np(ros_pointcloud.points)
## list of Point32 points -> 3xN np matrix
# @param ros_points - Point32[ ] (for e.g. from robot_msgs/PointCloud or Polygon3D)
# @return 3xN np matrix
def ros_pts_to_np(ros_pts):
pts_list = []
for p in ros_pts:
pts_list.append([p.x,p.y,p.z])
return np.matrix(pts_list).T
## 3xN np matrix -> ros PointCloud
# @param pts - 3xN np matrix
# @return PointCloud as defined in robot_msgs/msg/PointCloud.msg
def np_points_to_ros(pts):
p_list = []
chlist = []
# p_list = [Point32(p[0,0], p[0,1], p[0,2]) for p in pts.T]
# chlist = np.zeros(pts.shape[1]).tolist()
for p in pts.T:
p_list.append(Point32(p[0,0],p[0,1],p[0,2]))
chlist.append(0.)
ch = ChannelFloat32('t',chlist)
pc = PointCloud()
pc.points = p_list
pc.channels = [ch]
return pc
| [
[
1,
0,
0.0222,
0.0222,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0222,
0.0222,
0,
0.66,
0.1111,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0444,
0.0222,
0,
0.... | [
"import roslib; roslib.load_manifest('point_cloud_ros')",
"import roslib; roslib.load_manifest('point_cloud_ros')",
"from sensor_msgs.msg import PointCloud",
"from geometry_msgs.msg import Point32",
"from sensor_msgs.msg import ChannelFloat32",
"import numpy as np",
"import time",
"def ros_pointcloud_... |
#!/usr/bin/python
import numpy as np, math
import scipy.ndimage as ni
import roslib; roslib.load_manifest('point_cloud_ros')
import rospy
import hrl_lib.util as ut
import point_cloud_ros.occupancy_grid as pog
import point_cloud_ros.ros_occupancy_grid as rog
from point_cloud_ros.msg import OccupancyGrid
def og_cb(og_msg, param_list):
global occupancy_difference_threshold, connected_comonents_size_threshold
rospy.loginfo('og_cb called')
diff_og = param_list[0]
curr_og = rog.og_msg_to_og3d(og_msg, to_binary = False)
if diff_og == None:
param_list[0] = curr_og
return
pog.subtract(diff_og, curr_og)
param_list[0] = curr_og
diff_og.to_binary(occupancy_difference_threshold)
# filter the noise
connect_structure = np.zeros((3,3,3), dtype=int)
connect_structure[1,1,:] = 1
# connect_structure[1,1,0] = 0
diff_og.grid = ni.binary_opening(diff_og.grid, connect_structure,
iterations = 1)
# diff_og.grid, n_labels = diff_og.connected_comonents(connected_comonents_size_threshold)
print 'np.all(diff_og == 0)', np.all(diff_og.grid == 0)
diff_og_msg = rog.og3d_to_og_msg(diff_og)
diff_og_msg.header.frame_id = og_msg.header.frame_id
diff_og_msg.header.stamp = og_msg.header.stamp
param_list[1].publish(diff_og_msg)
#------ arbitrarily set paramters -------
occupancy_difference_threshold = 5
connected_comonents_size_threshold = 10
if __name__ == '__main__':
rospy.init_node('pc_difference_node')
pub = rospy.Publisher('difference_occupancy_grid', OccupancyGrid)
param_list = [None, pub]
rospy.Subscriber('occupancy_grid', OccupancyGrid, og_cb, param_list)
rospy.logout('Ready')
rospy.spin()
| [
[
1,
0,
0.0508,
0.0169,
0,
0.66,
0,
954,
0,
2,
0,
0,
954,
0,
0
],
[
1,
0,
0.0678,
0.0169,
0,
0.66,
0.0833,
348,
0,
1,
0,
0,
348,
0,
0
],
[
1,
0,
0.1017,
0.0169,
0,
... | [
"import numpy as np, math",
"import scipy.ndimage as ni",
"import roslib; roslib.load_manifest('point_cloud_ros')",
"import roslib; roslib.load_manifest('point_cloud_ros')",
"import rospy",
"import hrl_lib.util as ut",
"import point_cloud_ros.occupancy_grid as pog",
"import point_cloud_ros.ros_occupan... |
import time
import sys, os, copy
import numpy as np, math
import scipy.ndimage as ni
class occupancy_grid_3d():
##
# @param resolution - 3x1 matrix. size of each cell (in meters) along
# the different directions.
def __init__(self, center, size, resolution, data,
occupancy_threshold, to_binary = True):
self.grid_shape = size/resolution
tlb = center + size/2
brf = center + size/2
self.size = size
self.grid = np.reshape(data, self.grid_shape)
self.grid_shape = np.matrix(self.grid.shape).T
self.resolution = resolution
self.center = center
if to_binary:
self.to_binary(occupancy_threshold)
## binarize the grid
# @param occupancy_threshold - voxels with occupancy less than this are set to zero.
def to_binary(self, occupancy_threshold):
filled = (self.grid >= occupancy_threshold)
self.grid[np.where(filled==True)] = 1
self.grid[np.where(filled==False)] = 0
##
# @param array - if not None then this will be used instead of self.grid
# @return 3xN matrix of 3d coord of the cells which have occupancy = 1
def grid_to_points(self, array=None):
if array == None:
array = self.grid
idxs = np.where(array == 1)
x_idx = idxs[0]
y_idx = idxs[1]
z_idx = idxs[2]
x = x_idx * self.resolution[0,0] + self.center[0,0] - self.size[0,0]/2
y = y_idx * self.resolution[1,0] + self.center[1,0] - self.size[1,0]/2
z = z_idx * self.resolution[2,0] + self.center[2,0] - self.size[2,0]/2
return np.matrix(np.row_stack([x,y,z]))
## 27-connected components.
# @param threshold - min allowed size of connected component
def connected_comonents(self, threshold):
connect_structure = np.ones((3,3,3), dtype='int')
grid = self.grid
labeled_arr, n_labels = ni.label(grid, connect_structure)
if n_labels == 0:
return labeled_arr, n_labels
labels_list = range(1,n_labels+1)
count_objects = ni.sum(grid, labeled_arr, labels_list)
if n_labels == 1:
count_objects = [count_objects]
t0 = time.time()
new_labels_list = []
for c,l in zip(count_objects, labels_list):
if c > threshold:
new_labels_list.append(l)
else:
labeled_arr[np.where(labeled_arr == l)] = 0
# relabel stuff
for nl,l in enumerate(new_labels_list):
labeled_arr[np.where(labeled_arr == l)] = nl+1
n_labels = len(new_labels_list)
t1 = time.time()
print 'time:', t1-t0
return labeled_arr, n_labels
## subtract occupancy grids. og1 = abs(og1-og2)
# @param og1 - occupancy_grid_3d object.
# @param og2 - occupancy_grid_3d object.
#
# will position og2 at an appropriate location within og1 (hopefully)
# will copy points in og2 but not in og1 into og1
#
#UNTESTED:
# * subtracting grids of different sizes.
def subtract(og1, og2):
if np.all(og1.resolution == og2.resolution) == False:
print 'occupancy_grid_3d.subtract: The resolution of the two grids is not the same.'
print 'res1, res2:', og1.resolution.A1.tolist(), og2.resolution.A1.tolist()
return
if np.any(og1.grid_shape!=og2.grid_shape):
print 'Grid Sizes:', og1.grid_shape.A1, og2.grid_shape.A1
raise RuntimeError('grids are of different sizes')
og1.grid = np.abs(og1.grid - og2.grid)
if __name__ == '__main__':
print 'Hello World'
| [
[
1,
0,
0.0183,
0.0092,
0,
0.66,
0,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.0275,
0.0092,
0,
0.66,
0.1667,
509,
0,
3,
0,
0,
509,
0,
0
],
[
1,
0,
0.0367,
0.0092,
0,
... | [
"import time",
"import sys, os, copy",
"import numpy as np, math",
"import scipy.ndimage as ni",
"class occupancy_grid_3d():\n\n ##\n # @param resolution - 3x1 matrix. size of each cell (in meters) along\n # the different directions.\n def __init__(self, center, size, resolut... |
#!/usr/bin/python
import numpy as np, math
import time
import roslib; roslib.load_manifest('point_cloud_ros')
import rospy
from point_cloud_ros.msg import OccupancyGrid
import hrl_tilting_hokuyo.display_3d_mayavi as d3m
import point_cloud_ros.ros_occupancy_grid as rog
def mayavi_cb(og, param_list):
og3d = rog.og_msg_to_og3d(og)
param_list[0] = og3d
param_list[1] = True
def relay_cb(og, og_pub):
rospy.logout('relay_cb called')
og3d = rog.og_msg_to_og3d(og)
og_new = rog.og3d_to_og_msg(og3d)
og_pub.publish(og_new)
def vis_occupancy_cb(og, param_list):
og3d = rog.og_msg_to_og3d(og, to_binary = False)
param_list[0] = og3d
param_list[1] = True
if __name__ == '__main__':
og_pub = rospy.Publisher('relay_og_out', OccupancyGrid)
rospy.Subscriber('relay_og_in', OccupancyGrid, relay_cb, og_pub)
param_list = [None, False]
rospy.init_node('og_sample_python')
rospy.logout('Ready')
#mode = rospy.get_param('~mode')
#mode = 'mayavi'
mode = 'vis_occupancy'
if mode == 'mayavi':
rospy.Subscriber('occupancy_grid', OccupancyGrid, mayavi_cb, param_list)
while not rospy.is_shutdown():
if param_list[1] == True:
og3d = param_list[0]
print 'grid_shape:', og3d.grid.shape
pts = og3d.grid_to_points()
print pts.shape
# param_list[1] = False
break
rospy.sleep(0.1)
d3m.plot_points(pts)
d3m.show()
if mode == 'vis_occupancy':
rospy.Subscriber('occupancy_grid', OccupancyGrid, vis_occupancy_cb, param_list)
import matplotlib_util.util as mpu
while not rospy.is_shutdown():
if param_list[1] == True:
og3d = param_list[0]
break
rospy.sleep(0.1)
occ_array = og3d.grid.flatten()
mpu.pl.hist(occ_array, 100)
# mpu.plot_yx(occ_array)
mpu.show()
elif mode == 'relay':
rospy.spin()
| [
[
1,
0,
0.0375,
0.0125,
0,
0.66,
0,
954,
0,
2,
0,
0,
954,
0,
0
],
[
1,
0,
0.05,
0.0125,
0,
0.66,
0.0909,
654,
0,
1,
0,
0,
654,
0,
0
],
[
1,
0,
0.075,
0.0125,
0,
0.6... | [
"import numpy as np, math",
"import time",
"import roslib; roslib.load_manifest('point_cloud_ros')",
"import roslib; roslib.load_manifest('point_cloud_ros')",
"import rospy",
"from point_cloud_ros.msg import OccupancyGrid",
"import hrl_tilting_hokuyo.display_3d_mayavi as d3m",
"import point_cloud_ros.... |
#!/usr/bin/python
import numpy as np, math
import roslib; roslib.load_manifest('point_cloud_ros')
import rospy
import point_cloud_ros.ros_occupancy_grid as rog
from point_cloud_ros.msg import OccupancyGrid
from visualization_msgs.msg import Marker
## return a Marker message object
# @param loc - (x,y,z)
# @param scale - (x,y,z)
# @param color - (r,g,b,a)
# @param shape - 'sphere'
# @param frame_id - string.
def simple_viz_marker(loc, scale, color, shape, frame_id):
marker = Marker()
marker.header.frame_id = frame_id
marker.header.stamp = rospy.rostime.get_rostime()
marker.ns = 'basic_shapes'
marker.id = 0
if shape == 'sphere':
marker.type = Marker.SPHERE
marker.action = Marker.ADD
marker.pose.position.x = loc[0]
marker.pose.position.y = loc[1]
marker.pose.position.z = loc[2]
marker.pose.orientation.x = 0.0
marker.pose.orientation.y = 0.0
marker.pose.orientation.z = 0.0
marker.pose.orientation.w = 1.0
marker.scale.x = scale[0]
marker.scale.y = scale[1]
marker.scale.z = scale[2]
marker.color.r = color[0]
marker.color.g = color[1]
marker.color.b = color[2]
marker.color.a = color[3]
marker.lifetime = rospy.Duration()
return marker
if __name__ == '__main__':
rospy.init_node('set_og_param_node')
og_param_pub = rospy.Publisher('/og_params', OccupancyGrid)
marker_pub = rospy.Publisher('/occupancy_grid_viz_marker', Marker)
rospy.logout('Ready')
center = np.matrix([0.8, 0., 0.8]).T # for single object bag file
#center = np.matrix([0.6, 0., 0.75]).T
size = np.matrix([0.4, 0.4, 0.4]).T
#resolution = np.matrix([0.01, 0.01, 0.01]).T
resolution = np.matrix([0.005, 0.005, 0.005]).T
occupancy_threshold = 5
frame_id = 'base_link'
scale = (0.02, 0.02, 0.02)
color = (0., 1., 0., 1.)
shape = 'sphere'
marker = simple_viz_marker(center.A1, scale, color, shape, frame_id)
og_param = rog.og_param_msg(center, size, resolution,
occupancy_threshold, frame_id)
r = rospy.Rate(2)
while not rospy.is_shutdown():
marker_pub.publish(marker)
og_param_pub.publish(og_param)
r.sleep()
rospy.spin()
| [
[
1,
0,
0.04,
0.0133,
0,
0.66,
0,
954,
0,
2,
0,
0,
954,
0,
0
],
[
1,
0,
0.0667,
0.0133,
0,
0.66,
0.125,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0667,
0.0133,
0,
0.6... | [
"import numpy as np, math",
"import roslib; roslib.load_manifest('point_cloud_ros')",
"import roslib; roslib.load_manifest('point_cloud_ros')",
"import rospy",
"import point_cloud_ros.ros_occupancy_grid as rog",
"from point_cloud_ros.msg import OccupancyGrid",
"from visualization_msgs.msg import Marker"... |
#
# Copyright (c) 2010, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
# Author: Advait Jain (advait@cc.gatech.edu), Healthcare Robotics Lab, Georgia Tech
import roslib; roslib.load_manifest('move_arm_tutorials')
import rospy
import actionlib
import geometric_shapes_msgs
from move_arm_msgs.msg import MoveArmAction
from move_arm_msgs.msg import MoveArmGoal
from motion_planning_msgs.msg import SimplePoseConstraint
from motion_planning_msgs.msg import PositionConstraint
from motion_planning_msgs.msg import OrientationConstraint
from actionlib_msgs.msg import GoalStatus
def pose_constraint_to_position_orientation_constraints(pose_constraint):
position_constraint = PositionConstraint()
orientation_constraint = OrientationConstraint()
position_constraint.header = pose_constraint.header
position_constraint.link_name = pose_constraint.link_name
position_constraint.position = pose_constraint.pose.position
position_constraint.constraint_region_shape.type = geometric_shapes_msgs.msg.Shape.BOX
position_constraint.constraint_region_shape.dimensions.append(2*pose_constraint.absolute_position_tolerance.x)
position_constraint.constraint_region_shape.dimensions.append(2*pose_constraint.absolute_position_tolerance.y)
position_constraint.constraint_region_shape.dimensions.append(2*pose_constraint.absolute_position_tolerance.z)
position_constraint.constraint_region_orientation.x = 0.0
position_constraint.constraint_region_orientation.y = 0.0
position_constraint.constraint_region_orientation.z = 0.0
position_constraint.constraint_region_orientation.w = 1.0
position_constraint.weight = 1.0
orientation_constraint.header = pose_constraint.header
orientation_constraint.link_name = pose_constraint.link_name
orientation_constraint.orientation = pose_constraint.pose.orientation
orientation_constraint.type = pose_constraint.orientation_constraint_type
orientation_constraint.absolute_roll_tolerance = pose_constraint.absolute_roll_tolerance
orientation_constraint.absolute_pitch_tolerance = pose_constraint.absolute_pitch_tolerance
orientation_constraint.absolute_yaw_tolerance = pose_constraint.absolute_yaw_tolerance
orientation_constraint.weight = 1.0
return position_constraint, orientation_constraint
def add_goal_constraint_to_move_arm_goal(pose_constraint, move_arm_goal):
position_constraint, orientation_constraint = pose_constraint_to_position_orientation_constraints(pose_constraint)
move_arm_goal.motion_plan_request.goal_constraints.position_constraints.append(position_constraint)
move_arm_goal.motion_plan_request.goal_constraints.orientation_constraints.append(orientation_constraint)
if __name__ == '__main__':
rospy.init_node('move_arm_pose_goal_test')
move_arm = actionlib.SimpleActionClient('move_right_arm', MoveArmAction)
move_arm.wait_for_server()
rospy.loginfo('Connected to server')
goalA = MoveArmGoal()
goalA.motion_plan_request.group_name = 'right_arm'
goalA.motion_plan_request.num_planning_attempts = 1
goalA.motion_plan_request.planner_id = ''
goalA.planner_service_name = 'ompl_planning/plan_kinematic_path'
goalA.motion_plan_request.allowed_planning_time = rospy.Duration(5.0)
desired_pose = SimplePoseConstraint()
desired_pose.header.frame_id = 'torso_lift_link'
desired_pose.link_name = 'r_gripper_l_fingertip_link'
desired_pose.pose.position.x = 0.75
desired_pose.pose.position.y = -0.188
desired_pose.pose.position.z = 0
desired_pose.pose.orientation.x = 0.0
desired_pose.pose.orientation.y = 0.0
desired_pose.pose.orientation.z = 0.0
desired_pose.pose.orientation.w = 1.0
desired_pose.absolute_position_tolerance.x = 0.02
desired_pose.absolute_position_tolerance.y = 0.02
desired_pose.absolute_position_tolerance.z = 0.02
desired_pose.absolute_roll_tolerance = 0.04
desired_pose.absolute_pitch_tolerance = 0.04
desired_pose.absolute_yaw_tolerance = 0.04
add_goal_constraint_to_move_arm_goal(desired_pose, goalA)
move_arm.send_goal(goalA)
finished_within_time = move_arm.wait_for_result(rospy.Duration(200.0))
if not finished_within_time:
move_arm.cancel_goal()
rospy.loginfo("Timed out achieving goal A")
else:
state = move_arm.get_state()
if state == GoalStatus.SUCCEEDED:
rospy.loginfo('Action finished and was successful.')
else:
rospy.loginfo('Action failed: %d'%(state))
| [
[
1,
0,
0.2353,
0.0074,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.2353,
0.0074,
0,
0.66,
0.0769,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.25,
0.0074,
0,
0.66... | [
"import roslib; roslib.load_manifest('move_arm_tutorials')",
"import roslib; roslib.load_manifest('move_arm_tutorials')",
"import rospy",
"import actionlib",
"import geometric_shapes_msgs",
"from move_arm_msgs.msg import MoveArmAction",
"from move_arm_msgs.msg import MoveArmGoal",
"from motion_plannin... |
#
# Copyright (c) 2010, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
# Author: Advait Jain (advait@cc.gatech.edu), Healthcare Robotics Lab, Georgia Tech
import roslib; roslib.load_manifest('move_arm_tutorials')
import rospy
import actionlib
import geometric_shapes_msgs
from move_arm_msgs.msg import MoveArmAction
from move_arm_msgs.msg import MoveArmGoal
from motion_planning_msgs.msg import JointConstraint
from actionlib_msgs.msg import GoalStatus
if __name__ == '__main__':
import hrl_lib.transforms as tr
rospy.init_node('move_arm_joint_goal_test')
move_arm = actionlib.SimpleActionClient('move_right_arm', MoveArmAction)
move_arm.wait_for_server()
rospy.loginfo('Connected to server')
goalB = MoveArmGoal()
names = ['r_shoulder_pan_joint', 'r_shoulder_lift_joint',
'r_upper_arm_roll_joint', 'r_elbow_flex_joint',
'r_forearm_roll_joint', 'r_wrist_flex_joint',
'r_wrist_roll_joint']
goalB.motion_plan_request.group_name = 'right_arm'
goalB.motion_plan_request.num_planning_attempts = 1
goalB.motion_plan_request.allowed_planning_time = rospy.Duration(5.0)
goalB.motion_plan_request.planner_id = ''
goalB.planner_service_name = 'ompl_planning/plan_kinematic_path'
import roslib; roslib.load_manifest('darpa_m3')
import sandbox_advait.pr2_arms as pa
pr2_arms = pa.PR2Arms()
raw_input('Move arm to goal location and hit ENTER')
q = pr2_arms.get_joint_angles(0)
raw_input('Move arm to start location and hit ENTER')
q[6] = tr.angle_within_mod180(q[6])
q[4] = tr.angle_within_mod180(q[4])
for i in range(7):
jc = JointConstraint()
jc.joint_name = names[i]
jc.position = q[i]
jc.tolerance_below = 0.1
jc.tolerance_above = 0.1
goalB.motion_plan_request.goal_constraints.joint_constraints.append(jc)
move_arm.send_goal(goalB)
finished_within_time = move_arm.wait_for_result(rospy.Duration(200.0))
if not finished_within_time:
move_arm.cancel_goal()
rospy.loginfo("Timed out achieving goal A")
else:
state = move_arm.get_state()
if state == GoalStatus.SUCCEEDED:
rospy.loginfo('Action finished and was successful.')
else:
rospy.loginfo('Action failed: %d'%(state))
| [
[
1,
0,
0.3137,
0.0098,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.3137,
0.0098,
0,
0.66,
0.1111,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.3333,
0.0098,
0,
0.... | [
"import roslib; roslib.load_manifest('move_arm_tutorials')",
"import roslib; roslib.load_manifest('move_arm_tutorials')",
"import rospy",
"import actionlib",
"import geometric_shapes_msgs",
"from move_arm_msgs.msg import MoveArmAction",
"from move_arm_msgs.msg import MoveArmGoal",
"from motion_plannin... |
import roslib; roslib.load_manifest('hrl_pr2_kinematics_tutorials')
import rospy
import numpy as np, math
## Class defining the core EPC function and a few simple examples.
# More complex behaviors that use EPC should have their own ROS
# packages.
class EPC():
def __init__(self, robot):
self.robot = robot
##
# @param equi_pt_generator: function that returns stop, ea where ea: equilibrium angles and stop: string which is '' for epc motion to continue
# @param rapid_call_func: called in the time between calls to the equi_pt_generator can be used for logging, safety etc. returns string which is '' for epc motion to continue
# @param time_step: time between successive calls to equi_pt_generator
# @param arg_list - list of arguments to be passed to the equi_pt_generator
# @return stop (the string which has the reason why the epc
# motion stopped.), ea (last commanded equilibrium angles)
def epc_motion(self, equi_pt_generator, time_step, arm, arg_list,
rapid_call_func=None, control_function=None):
stop, ea = equi_pt_generator(*arg_list)
t_end = rospy.get_time()
while stop == '':
t_end += time_step
#self.robot.set_jointangles(arm, ea)
#import pdb; pdb.set_trace()
control_function(arm, *ea)
# self.robot.step() this should be within the rapid_call_func for the meka arms.
t1 = rospy.get_time()
while t1<t_end:
if rapid_call_func != None:
stop = rapid_call_func(arm)
if stop != '':
break
# self.robot.step() this should be within the rapid_call_func for the meka arms.
t1 = rospy.get_time()
stop, ea = equi_pt_generator(*arg_list)
if stop == 'reset timing':
stop = ''
t_end = rospy.get_time()
return stop, ea
## Pull back along a straight line (-ve x direction)
# @param arm - 'right_arm' or 'left_arm'
# @param ea - starting equilibrium angle.
# @param rot_mat - rotation matrix defining end effector pose
# @param distance - how far back to pull.
def pull_back(self, arm, ea, rot_mat, distance):
self.cep = self.robot.FK(arm, ea)
self.dist_left = distance
self.ea = ea
def eq_gen_pull_back(robot, arm, rot_mat):
if self.dist_left <= 0.:
return 'done', None
step_size = 0.01
self.cep[0,0] -= step_size
self.dist_left -= step_size
ea = robot.IK(arm, self.cep, rot_mat, self.ea)
self.ea = ea
if ea == None:
return 'IK fail', ea
return '', [ea,]
arg_list = [self.robot, arm, rot_mat]
stop, ea = self.epc_motion(eq_gen_pull_back, 0.1, arm, arg_list,
control_function = self.robot.set_jointangles)
print stop, ea
## Pull back along a straight line (-ve x direction)
# @param arm - 'right_arm' or 'left_arm'
# @param ea - starting cep.
# @param rot_mat - rotation matrix defining end effector pose
# @param distance - how far back to pull.
def pull_back_cartesian_control(self, arm, cep, rot_mat, distance):
self.cep = cep
self.dist_left = distance
def eq_gen_pull_back(robot, arm, rot_mat):
if self.dist_left <= 0.:
return 'done', None
step_size = 0.01
self.cep[0,0] -= step_size
self.dist_left -= step_size
if self.cep[0,0] < 0.4:
return 'very close to the body: %.3f'%self.cep[0,0], None
return '', (self.cep, rot_mat)
arg_list = [self.robot, arm, rot_mat]
stop, ea = self.epc_motion(eq_gen_pull_back, 0.1, arm, arg_list,
control_function = self.robot.set_cartesian)
print stop, ea
if __name__ == '__main__':
import hrl_pr2
import hrl_lib.transforms as tr
rospy.init_node('epc_pr2', anonymous = True)
rospy.logout('epc_pr2: ready')
pr2 = hrl_pr2.HRL_PR2()
epc = EPC(pr2)
arm = 'right_arm'
if False:
ea = [0, 0, 0, 0, 0, 0, 0]
ea = epc.robot.get_joint_angles(arm)
rospy.logout('Going to starting position')
epc.robot.set_jointangles(arm, ea, duration=4.0)
raw_input('Hit ENTER to pull')
epc.pull_back(arm, ea, tr.Rx(0), 0.2)
if True:
p = np.matrix([0.9, -0.3, -0.15]).T
rot = tr.Rx(0.)
rot = tr.Rx(math.radians(90.))
rospy.logout('Going to starting position')
# epc.robot.open_gripper(arm)
epc.robot.set_cartesian(arm, p, rot)
# raw_input('Hit ENTER to close the gripper')
# epc.robot.close_gripper(arm)
raw_input('Hit ENTER to pull')
epc.pull_back_cartesian_control(arm, p, rot, 0.4)
| [
[
1,
0,
0.0145,
0.0072,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0145,
0.0072,
0,
0.66,
0.2,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0217,
0.0072,
0,
0.66,... | [
"import roslib; roslib.load_manifest('hrl_pr2_kinematics_tutorials')",
"import roslib; roslib.load_manifest('hrl_pr2_kinematics_tutorials')",
"import rospy",
"import numpy as np, math",
"class EPC():\n def __init__(self, robot):\n self.robot = robot\n\n ##\n # @param equi_pt_generator: funct... |
import numpy as np, math
from threading import RLock
import roslib; roslib.load_manifest('hrl_pr2_kinematics_tutorials')
import rospy
import actionlib
from kinematics_msgs.srv import GetPositionFK, GetPositionFKRequest, GetPositionFKResponse
from kinematics_msgs.srv import GetPositionIK, GetPositionIKRequest, GetPositionIKResponse
from pr2_controllers_msgs.msg import JointTrajectoryAction, JointTrajectoryGoal, JointTrajectoryControllerState
from pr2_controllers_msgs.msg import Pr2GripperCommandGoal, Pr2GripperCommandAction, Pr2GripperCommand
from trajectory_msgs.msg import JointTrajectoryPoint
from geometry_msgs.msg import PoseStamped
from std_msgs.msg import Float64
from sensor_msgs.msg import JointState
import hrl_lib.transforms as tr
import time
class HRL_PR2():
def __init__(self):
self.joint_names_list = ['r_shoulder_pan_joint',
'r_shoulder_lift_joint', 'r_upper_arm_roll_joint',
'r_elbow_flex_joint', 'r_forearm_roll_joint',
'r_wrist_flex_joint', 'r_wrist_roll_joint']
rospy.wait_for_service('pr2_right_arm_kinematics/get_fk');
rospy.wait_for_service('pr2_right_arm_kinematics/get_ik');
self.fk_srv = rospy.ServiceProxy('pr2_right_arm_kinematics/get_fk', GetPositionFK)
self.ik_srv = rospy.ServiceProxy('pr2_right_arm_kinematics/get_ik', GetPositionIK)
self.joint_action_client = actionlib.SimpleActionClient('r_arm_controller/joint_trajectory_action', JointTrajectoryAction)
self.gripper_action_client = actionlib.SimpleActionClient('r_gripper_controller/gripper_action', Pr2GripperCommandAction)
self.joint_action_client.wait_for_server()
self.gripper_action_client.wait_for_server()
self.arm_state_lock = RLock()
#rospy.Subscriber('/r_arm_controller/state', JointTrajectoryControllerState, self.r_arm_state_cb)
rospy.Subscriber('/joint_states', JointState, self.joint_states_cb)
self.r_arm_cart_pub = rospy.Publisher('/r_cart/command_pose', PoseStamped)
self.r_arm_pub_l = []
self.joint_nm_list = ['shoulder_pan', 'shoulder_lift', 'upper_arm_roll',
'elbow_flex', 'forearm_roll', 'wrist_flex',
'wrist_roll']
self.r_arm_angles = None
self.r_arm_efforts = None
for nm in self.joint_nm_list:
self.r_arm_pub_l.append(rospy.Publisher('r_'+nm+'_controller/command', Float64))
rospy.sleep(1.)
def joint_states_cb(self, data):
r_arm_angles = []
r_arm_efforts = []
r_jt_idx_list = [17, 18, 16, 20, 19, 21, 22]
for i,nm in enumerate(self.joint_nm_list):
idx = r_jt_idx_list[i]
if data.name[idx] != 'r_'+nm+'_joint':
raise RuntimeError('joint angle name does not match. Expected: %s, Actual: %s i: %d'%('r_'+nm+'_joint', data.name[idx], i))
r_arm_angles.append(data.position[idx])
r_arm_efforts.append(data.effort[idx])
self.arm_state_lock.acquire()
self.r_arm_angles = r_arm_angles
self.r_arm_efforts = r_arm_efforts
self.arm_state_lock.release()
## go to a joint configuration.
# @param q - list of 7 joint angles in RADIANS.
# @param duration - how long (SECONDS) before reaching the joint angles.
def set_jointangles(self, arm, q, duration=0.15):
rospy.logwarn('Currently ignoring the arm parameter.')
# for i,p in enumerate(self.r_arm_pub_l):
# p.publish(q[i])
jtg = JointTrajectoryGoal()
jtg.trajectory.joint_names = self.joint_names_list
jtp = JointTrajectoryPoint()
jtp.positions = q
jtp.velocities = [0 for i in range(len(q))]
jtp.accelerations = [0 for i in range(len(q))]
jtp.time_from_start = rospy.Duration(duration)
jtg.trajectory.points.append(jtp)
self.joint_action_client.send_goal(jtg)
def FK(self, arm, q):
rospy.logwarn('Currently ignoring the arm parameter.')
fk_req = GetPositionFKRequest()
fk_req.header.frame_id = 'torso_lift_link'
fk_req.fk_link_names.append('r_wrist_roll_link')
fk_req.robot_state.joint_state.name = self.joint_names_list
fk_req.robot_state.joint_state.position = q
fk_resp = GetPositionFKResponse()
fk_resp = self.fk_srv.call(fk_req)
if fk_resp.error_code.val == fk_resp.error_code.SUCCESS:
x = fk_resp.pose_stamped[0].pose.position.x
y = fk_resp.pose_stamped[0].pose.position.y
z = fk_resp.pose_stamped[0].pose.position.z
ret = np.matrix([x,y,z]).T
else:
rospy.logerr('Forward kinematics failed')
ret = None
return ret
def IK(self, arm, p, rot, q_guess):
rospy.logwarn('Currently ignoring the arm parameter.')
ik_req = GetPositionIKRequest()
ik_req.timeout = rospy.Duration(5.)
ik_req.ik_request.ik_link_name = 'r_wrist_roll_link'
ik_req.ik_request.pose_stamped.header.frame_id = 'torso_lift_link'
ik_req.ik_request.pose_stamped.pose.position.x = p[0,0]
ik_req.ik_request.pose_stamped.pose.position.y = p[1,0]
ik_req.ik_request.pose_stamped.pose.position.z = p[2,0]
quat = tr.matrix_to_quaternion(rot)
ik_req.ik_request.pose_stamped.pose.orientation.x = quat[0]
ik_req.ik_request.pose_stamped.pose.orientation.y = quat[1]
ik_req.ik_request.pose_stamped.pose.orientation.z = quat[2]
ik_req.ik_request.pose_stamped.pose.orientation.w = quat[3]
ik_req.ik_request.ik_seed_state.joint_state.position = q_guess
ik_req.ik_request.ik_seed_state.joint_state.name = self.joint_names_list
ik_resp = self.ik_srv.call(ik_req)
if ik_resp.error_code.val == ik_resp.error_code.SUCCESS:
ret = ik_resp.solution.joint_state.position
else:
rospy.logerr('Inverse kinematics failed')
ret = None
return ret
# for compatibility with Meka arms on Cody. Need to figure out a
# good way to have a common interface to different arms.
def step(self):
return
def end_effector_pos(self, arm):
q = self.get_joint_angles(arm)
return self.FK(arm, q)
def get_joint_angles(self, arm):
rospy.logwarn('Currently ignoring the arm parameter.')
self.arm_state_lock.acquire()
q = self.r_arm_angles
self.arm_state_lock.release()
return q
# need for search and hook
def go_cartesian(self, arm):
rospy.logerr('Need to implement this function.')
raise RuntimeError('Unimplemented function')
def get_wrist_force(self, arm, bias = True, base_frame = False):
rospy.logerr('Need to implement this function.')
raise RuntimeError('Unimplemented function')
def set_cartesian(self, arm, p, rot):
rospy.logwarn('Currently ignoring the arm parameter.')
ps = PoseStamped()
ps.header.stamp = rospy.rostime.get_rostime()
ps.header.frame_id = 'torso_lift_link'
ps.pose.position.x = p[0,0]
ps.pose.position.y = p[1,0]
ps.pose.position.z = p[2,0]
quat = tr.matrix_to_quaternion(rot)
ps.pose.orientation.x = quat[0]
ps.pose.orientation.y = quat[1]
ps.pose.orientation.z = quat[2]
ps.pose.orientation.w = quat[3]
self.r_arm_cart_pub.publish(ps)
def open_gripper(self, arm):
self.gripper_action_client.send_goal(Pr2GripperCommandGoal(Pr2GripperCommand(position=0.08, max_effort = -1)))
## close the gripper
# @param effort - supposed to be in Newtons. (-ve number => max effort)
def close_gripper(self, arm, effort = 15):
self.gripper_action_client.send_goal(Pr2GripperCommandGoal(Pr2GripperCommand(position=0.0, max_effort = effort)))
def get_wrist_force(self, arm):
pass
if __name__ == '__main__':
rospy.init_node('hrl_pr2', anonymous = True)
rospy.logout('hrl_pr2: ready')
hrl_pr2 = HRL_PR2()
if False:
q = [0, 0, 0, 0, 0, 0, 0]
hrl_pr2.set_jointangles('right_arm', q)
ee_pos = hrl_pr2.FK('right_arm', q)
print 'FK result:', ee_pos.A1
ee_pos[0,0] -= 0.1
q_ik = hrl_pr2.IK('right_arm', ee_pos, tr.Rx(0.), q)
print 'q_ik:', [math.degrees(a) for a in q_ik]
rospy.spin()
if False:
p = np.matrix([0.9, -0.3, -0.15]).T
#rot = tr.Rx(0.)
rot = tr.Rx(math.radians(90.))
hrl_pr2.set_cartesian('right_arm', p, rot)
hrl_pr2.open_gripper('right_arm')
raw_input('Hit ENTER to close')
hrl_pr2.close_gripper('right_arm', effort = 15)
| [
[
1,
0,
0.0089,
0.0044,
0,
0.66,
0,
954,
0,
2,
0,
0,
954,
0,
0
],
[
1,
0,
0.0133,
0.0044,
0,
0.66,
0.0588,
83,
0,
1,
0,
0,
83,
0,
0
],
[
1,
0,
0.0222,
0.0044,
0,
0.... | [
"import numpy as np, math",
"from threading import RLock",
"import roslib; roslib.load_manifest('hrl_pr2_kinematics_tutorials')",
"import roslib; roslib.load_manifest('hrl_pr2_kinematics_tutorials')",
"import rospy",
"import actionlib",
"from kinematics_msgs.srv import GetPositionFK, GetPositionFKReques... |
import roslib; roslib.load_manifest('pr2_doors_epc')
import rospy
import hrl_lib.transforms as tr
import force_torque.FTClient as ftc
import math, numpy as np
from rviz_marker_test import *
from hrl_msgs.msg import FloatArray
if __name__ == '__main__':
ft_client = ftc.FTClient('force_torque_ft2')
ft_client.bias()
marker_pub = rospy.Publisher('/test_marker', Marker)
ati_pub = rospy.Publisher('/ati_ft', FloatArray)
p_st = np.matrix([0.,0.,0.]).T
force_frame_id = 'r_wrist_roll_link'
while not rospy.is_shutdown():
ft = ft_client.read(fresh = True)
rmat = tr.Rx(math.radians(180.)) * tr.Ry(math.radians(-90.)) * tr.Rz(math.radians(30.))
force = rmat * ft[0:3,:]
print 'Force:', force.A1
# force is now in the 'robot' coordinate frame.
force_scale = 0.1
p_end = p_st + force * force_scale
marker = get_marker_arrow(p_st, p_end, force_frame_id)
marker_pub.publish(marker)
farr = FloatArray()
farr.header.stamp = rospy.rostime.get_rostime()
farr.header.frame_id = force_frame_id
farr.data = (-force).A1.tolist()
ati_pub.publish(farr)
# rospy.sleep(0.1)
| [
[
1,
0,
0.0526,
0.0263,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0526,
0.0263,
0,
0.66,
0.125,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0789,
0.0263,
0,
0.6... | [
"import roslib; roslib.load_manifest('pr2_doors_epc')",
"import roslib; roslib.load_manifest('pr2_doors_epc')",
"import rospy",
"import hrl_lib.transforms as tr",
"import force_torque.FTClient as ftc",
"import math, numpy as np",
"from rviz_marker_test import *",
"from hrl_msgs.msg import FloatArray",... |
import roslib; roslib.load_manifest('hrl_pr2_kinematics')
import rospy
from equilibrium_point_control.msg import MechanismKinematicsRot
from equilibrium_point_control.msg import MechanismKinematicsJac
import epc
from threading import RLock
##
# compute the end effector rotation matrix.
# @param hook - hook angle. RADIANS(0, -90, 90) (hor, up, down)
# @param angle - angle between robot and surface normal.
# Angle about the Z axis through which the robot must turn to face
# the surface.
def rot_mat_from_angles(hook, surface):
rot_mat = tr.Rz(hook) * tr.Rx(surface)
return rot_mat
class Door_EPC(epc.EPC):
def __init__(self, robot):
epc.EPC.__init__(self, robot)
self.mech_kinematics_lock = RLock()
self.fit_circle_lock = RLock()
rospy.Subscriber('mechanism_kinematics_rot',
MechanismKinematicsRot,
self.mechanism_kinematics_rot_cb)
rospy.Subscriber('mechanism_kinematics_jac',
MechanismKinematicsJac,
self.mechanism_kinematics_jac_cb)
self.mech_traj_pub = rospy.Publisher('mechanism_trajectory', Point32)
self.eq_pt_not_moving_counter = 0
## log the joint angles, equi pt joint angles and forces.
def log_state(self, arm):
t_now = rospy.get_time()
q_now = self.robot.get_joint_angles(arm)
self.pull_trajectory.q_list.append(q_now)
self.pull_trajectory.time_list.append(t_now)
self.eq_pt_trajectory.q_list.append(self.q_guess) # see equi_pt_generator - q_guess is the config for the eq point.
self.eq_pt_trajectory.time_list.append(t_now)
wrist_force = self.robot.get_wrist_force(arm, base_frame=True)
self.force_trajectory.f_list.append(wrist_force.A1.tolist())
self.force_trajectory.time_list.append(t_now)
return '' # log_state also used as a rapid_call_func
##
# @param arm - 'right_arm' or 'left_arm'
# @param motion vec is in tl frame.
# @param step_size - distance (meters) through which CEP should move
# @param rot_mat - rotation matrix for IK
# @return JEP
def update_eq_point(self, arm, motion_vec, step_size, rot_mat):
self.eq_pt_cartesian = self.eq_pt_cartesian_ts
next_pt = self.eq_pt_cartesian + step_size * motion_vec
q_eq = self.robot.IK(arm, next_pt, rot_mat, self.q_guess)
self.eq_pt_cartesian = next_pt
self.eq_pt_cartesian_ts = self.eq_pt_cartesian
self.q_guess = q_eq
return q_eq
def common_stopping_conditions(self):
stop = ''
if self.q_guess == None:
stop = 'IK fail'
wrist_force = self.robot.get_wrist_force('right_arm',base_frame=True)
mag = np.linalg.norm(wrist_force)
print 'force magnitude:', mag
if mag > self.eq_force_threshold:
stop = 'force exceed'
if mag < 1.2 and self.hooked_location_moved:
if (self.prev_force_mag - mag) > 30.:
stop = 'slip: force step decrease and below thresold.'
#stop = ''
else:
self.slip_count += 1
else:
self.slip_count = 0
if self.slip_count == 10:
stop = 'slip: force below threshold for too long.'
return stop
## constantly update the estimate of the kinematics and move the
# equilibrium point along the tangent of the estimated arc, and
# try to keep the radial force constant.
# @param h_force_possible - True (hook side) or False (hook up).
# @param v_force_possible - False (hook side) or True (hook up).
# Is maintaining a radial force possible or not (based on hook
# geometry and orientation)
# @param cep_vel - tangential velocity of the cep in m/s
def eqpt_gen_control_radial_force(self, arm, rot_mat,
h_force_possible, v_force_possible, cep_vel):
self.log_state(arm)
step_size = 0.1 * cep_vel # 0.1 is the time interval between calls to the equi_generator function (see pull)
q_eq = self.update_eq_point(arm, self.eq_motion_vec, step_size,
rot_mat)
stop = self.common_stopping_conditions()
wrist_force = self.robot.get_wrist_force(arm, base_frame=True)
mag = np.linalg.norm(wrist_force)
curr_pos = self.robot.FK(arm,self.pull_trajectory.q_list[-1])
if len(self.pull_trajectory.q_list)>1:
start_pos = np.matrix(self.cartesian_pts_list[0]).T
else:
start_pos = curr_pos
#mechanism kinematics.
self.mech_traj_pub.publish(Point32(curr_pos[0,0],
curr_pos[1,0], curr_pos[2,0]))
if self.use_jacobian:
self.mech_kinematics_lock.acquire()
self.cartesian_pts_list.append(curr_pos.A1.tolist())
tangential_vec_ts = self.tangential_vec_ts
force_vec_ts = self.constraint_vec_1_ts + self.constraint_vec_2_ts
# this is specifically for the right arm, and lots of
# other assumptions about the hook etc. (Advait, Feb 28, 2010)
if h_force_possible:
force_vec_ts[2,0] = 0.
if v_force_possible:
force_vec_ts[1,0] = 0.
force_vec_ts = force_vec_ts / np.linalg.norm(force_vec_ts)
if force_vec_ts[2,0] < 0.: # only allowing upward force.
force_vec_ts = -force_vec_ts
if force_vec_ts[1,0] < 0.: # only allowing force to the left
force_vec_ts = -force_vec_ts
self.mech_kinematics_lock.release()
force_vec = force_vec_ts
tangential_vec = tangential_vec_ts
if self.use_rotation_center:
self.fit_circle_lock.acquire()
self.cartesian_pts_list.append(curr_pos.A1.tolist())
rad = self.rad
cx_start, cy_start = self.cx_start, self.cy_start
cz_start = self.cz_start
self.fit_circle_lock.release()
cx, cy = cx_start, cy_start
cz = cz_start
radial_vec = curr_pos_tl-np.matrix([cx,cy,cz]).T
radial_vec = radial_vec/np.linalg.norm(radial_vec)
if cy_start<start_pos[1,0]:
tan_x,tan_y = -radial_vec[1,0],radial_vec[0,0]
else:
tan_x,tan_y = radial_vec[1,0],-radial_vec[0,0]
if tan_x > 0. and (start_pos[0,0]-curr_pos[0,0]) < 0.09:
tan_x = -tan_x
tan_y = -tan_y
if cy_start > start_pos[1,0]:
radial_vec = -radial_vec # axis to the left, want force in
# anti-radial direction.
rv = radial_vec
force_vec = np.matrix([rv[0,0], rv[1,0], 0.]).T
tangential_vec = np.matrix([tan_x, tan_y, 0.]).T
tangential_vec_ts = tangential_vec
radial_vec_ts = radial_vec
force_vec_ts = force_vec
f_vec = -1*np.array([wrist_force[0,0], wrist_force[1,0],
wrist_force[2,0]])
f_rad_mag = np.dot(f_vec, force_vec.A1)
err = f_rad_mag-5.
if err>0.:
kp = -0.1
else:
kp = -0.2
radial_motion_mag = kp * err # radial_motion_mag in cm (depends on eq_motion step size)
if self.use_rotation_center:
if h_force_possible == False and parallel_to_floor:
radial_motion_mag = 0.
if v_force_possible == False and parallel_to_floor == False:
radial_motion_mag = 0.
radial_motion_vec = force_vec * radial_motion_mag
self.eq_motion_vec = copy.copy(tangential_vec)
self.eq_motion_vec += radial_motion_vec
self.prev_force_mag = mag
if self.init_tangent_vector == None:
self.init_tangent_vector = copy.copy(tangential_vec_ts)
c = np.dot(tangential_vec_ts.A1, self.init_tangent_vector.A1)
ang = np.arccos(c)
dist_moved = np.dot((curr_pos - start_pos).A1, self.tangential_vec_ts.A1)
ftan = abs(np.dot(wrist_force.A1, tangential_vec.A1))
if abs(dist_moved) > 0.09 and self.hooked_location_moved == False:
# change the force threshold once the hook has started pulling.
self.hooked_location_moved = True
self.eq_force_threshold = ut.bound(mag+30.,20.,80.)
self.ftan_threshold = self.ftan_threshold + max(10., 1.5*ftan)
if self.hooked_location_moved:
if abs(tangential_vec_ts[2,0]) < 0.2 and ftan > self.ftan_threshold:
stop = 'ftan threshold exceed: %f'%ftan
else:
self.ftan_threshold = max(self.ftan_threshold, ftan)
if self.hooked_location_moved and ang > math.radians(90.):
print 'Angle:', math.degrees(ang)
self.open_ang_exceed_count += 1
if self.open_ang_exceed_count > 2:
stop = 'opened mechanism through large angle: %.1f'%(math.degrees(ang))
else:
self.open_ang_exceed_count = 0
self.mech_time_list.append(time.time())
self.mech_x_list.append(ang)
self.f_rad_list.append(f_rad_mag)
self.f_tan_list.append(np.dot(f_vec, tangential_vec.A1))
self.tan_vec_list.append(tangential_vec_ts.A1.tolist())
self.rad_vec_list.append(force_vec_ts.A1.tolist())
return stop, q_eq
def pull(self, arm, hook_angle, force_threshold, ea,
kinematics_estimation = 'rotation_center', pull_left = False):
self.init_tangent_vector = None
self.open_ang_exceed_count = 0.
if kinematics_estimation == 'rotation_center':
self.use_rotation_center = True
else:
self.use_rotation_center = False
if kinematics_estimation == 'jacobian':
self.use_jacobian = True
else:
self.use_jacobian = False
#rot_mat = tr.Rz(hook_angle)*tr.Ry(math.radians(-90))
rot_mat = rot_mat_from_angles(hook_angle, surface_angle)
time_dict = {}
time_dict['before_pull'] = time.time()
self.pull_trajectory = at.JointTrajectory()
self.eq_pt_trajectory = at.JointTrajectory()
self.force_trajectory = at.ForceTrajectory()
self.robot.step()
start_config = self.robot.get_joint_angles(arm)
self.eq_force_threshold = force_threshold
self.ftan_threshold = 2.
self.hooked_location_moved = False # flag to indicate when the hooking location started moving.
self.prev_force_mag = np.linalg.norm(self.robot.get_wrist_force(arm))
self.eq_motion_vec = np.matrix([-1.,0.,0.]).T # might want to change this to account for the surface_angle.
self.slip_count = 0
self.eq_pt_cartesian = self.robot.FK(arm, ea)
self.eq_pt_cartesian_ts = self.robot.FK(arm, ea)
self.start_pos = copy.copy(self.eq_pt_cartesian)
self.q_guess = ea
if not pull_left:
self.tangential_vec_ts = np.matrix([-1.,0.,0.]).T
self.constraint_vec_2_ts = np.matrix([0.,0.,1.]).T
self.constraint_vec_1_ts = np.matrix([0.,1.,0.]).T
else:
self.tangential_vec_ts = np.matrix([0.,1.,0.]).T
self.constraint_vec_2_ts = np.matrix([0.,0.,1.]).T
self.constraint_vec_1_ts = np.matrix([1.,0.,0.]).T
self.mech_time_list = []
self.mech_x_list = []
self.f_rad_list = []
self.f_tan_list = []
self.tan_vec_list = []
self.rad_vec_list = []
self.cartesian_pts_list = []
ee_pos = self.robot.end_effector_pos(arm)
if self.use_rotation_center:
# this might have to change depending on left and right
# arm? or maybe not since the right arm can open both
# doors.
self.cx_start = ee_pos[0,0]
self.cy_start = ee_pos[1,0]-1.0
self.cz_start = ee_pos[2,0]
self.rad = 5.0
h_force_possible = abs(hook_angle) < math.radians(30.)
v_force_possible = abs(hook_angle) > math.radians(60.)
arg_list = [arm, rot_mat, h_force_possible, v_force_possible, cep_vel]
result, jep = self.epc_motion(self.eqpt_gen_control_radial_force,
0.1, arm, arg_list, self.log_state)
print 'EPC motion result:', result
print 'Original force threshold:', force_threshold
print 'Adapted force threshold:', self.eq_force_threshold
print 'Adapted ftan threshold:', self.ftan_threshold
time_dict['after_pull'] = time.time()
d = {'actual': self.pull_trajectory, 'eq_pt': self.eq_pt_trajectory,
'force': self.force_trajectory, 'torque': self.jt_torque_trajectory,
'info': info_string, 'force_threshold': force_threshold,
'eq_force_threshold': self.eq_force_threshold, 'hook_angle':hook_angle,
'result':result, 'time_dict':time_dict,
'cep_vel': cep_vel,
'ftan_threshold': self.ftan_threshold}
self.robot.step()
ut.save_pickle(d,'pull_trajectories_'+d['info']+'_'+ut.formatted_time()+'.pkl')
dd = {'mechanism_x': self.mech_x_list,
'mechanism_time': self.mech_time_list,
'force_rad_list': self.f_rad_list,
'force_tan_list': self.f_tan_list,
'tan_vec_list': self.tan_vec_list,
'rad_vec_list': self.rad_vec_list
}
ut.save_pickle(dd,'mechanism_trajectories_robot_'+d['info']+'_'+ut.formatted_time()+'.pkl')
## behavior to search around the hook_loc to try and get a good
# hooking grasp
# @param arm - 'right_arm' or 'left_arm'
# @param hook_angle - radians(0,-90,90) side,up,down
# @param hook_loc - 3x1 np matrix
# @param angle - angle between torso x axis and surface normal.
# @return s, jep (stopping string and last commanded JEP)
def search_and_hook(self, arm, hook_angle, hook_loc, angle,
hooking_force_threshold = 5.):
rot_mat = rot_mat_from_angles(hook_angle, angle)
if arm == 'right_arm':
hook_dir = np.matrix([0.,1.,0.]).T # hook direc in home position
elif arm == 'left_arm':
hook_dir = np.matrix([0.,-1.,0.]).T # hook direc in home position
else:
raise RuntimeError('Unknown arm: %s', arm)
start_loc = hook_loc + rot_mat.T * hook_dir * -0.03 # 3cm direc opposite to hook.
# vector normal to surface and pointing into the surface.
normal_tl = tr.Rz(-angle) * np.matrix([1.0,0.,0.]).T
pt1 = start_loc - normal_tl * 0.1
pt1[2,0] -= 0.02 # funny error in meka control code? or is it gravity comp?
self.robot.go_cartesian(arm, pt1, rot_mat, speed=0.2)
vec = normal_tl * 0.2
s, jep = self.firenze.move_till_hit(arm, vec=vec, force_threshold=2.0,
rot=rot_mat, speed=0.07)
self.eq_pt_cartesian = self.firenze.FK(arm, jep)
self.eq_pt_cartesian_ts = self.firenze.FK(arm, jep)
self.start_pos = copy.copy(self.eq_pt_cartesian)
self.q_guess = jep
move_dir = rot_mat.T * hook_dir
arg_list = [arm, move_dir, rot_mat, hooking_force_threshold]
s, jep = self.compliant_motion(self.equi_generator_surface_follow, 0.05,
arm, arg_list)
return s, jep
if __name__ == '__main__':
print 'Hello World'
| [
[
1,
0,
0.0052,
0.0026,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0052,
0.0026,
0,
0.66,
0.1111,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0078,
0.0026,
0,
0.... | [
"import roslib; roslib.load_manifest('hrl_pr2_kinematics')",
"import roslib; roslib.load_manifest('hrl_pr2_kinematics')",
"import rospy",
"from equilibrium_point_control.msg import MechanismKinematicsRot",
"from equilibrium_point_control.msg import MechanismKinematicsJac",
"import epc",
"from threading ... |
__all__ = [
'door_epc',
'epc',
'hrl_pr2',
]
| [
[
14,
0,
0.625,
0.625,
0,
0.66,
0,
272,
0,
0,
0,
0,
0,
5,
0
]
] | [
"__all__ = [\n'door_epc',\n'epc',\n'hrl_pr2',\n]"
] |
import roslib; roslib.load_manifest('hrl_pr2_kinematics_tutorials')
import rospy
from visualization_msgs.msg import Marker
from geometry_msgs.msg import Point
import hrl_lib.transforms as tr
import math, numpy as np
def get_marker_arrow(p_st, p_end, frame_id):
m = Marker()
m.header.stamp = rospy.rostime.get_rostime()
m.header.frame_id = frame_id
m.ns = 'basic_shapes'
m.id = 0
m.type = Marker.ARROW
m.action = Marker.ADD
pt1 = Point(p_st[0,0], p_st[1,0], p_st[2,0])
pt2 = Point(p_end[0,0], p_end[1,0], p_end[2,0])
m.points.append(pt1)
m.points.append(pt2)
m.scale.x = 0.02;
m.scale.y = 0.05;
m.scale.z = 0.1;
m.color.r = 1.0;
m.color.g = 0.0;
m.color.b = 0.0;
m.color.a = 1.0;
m.lifetime = rospy.Duration();
return m
if __name__ == '__main__':
rospy.init_node('marker_test', anonymous = True)
marker_pub = rospy.Publisher('/test_marker', Marker)
p1 = np.matrix([0.,0.,0.]).T
p2 = np.matrix([0.,1.,0.]).T
while not rospy.is_shutdown():
marker = get_marker_arrow(p1, p2, 'base_link')
marker_pub.publish(marker)
rospy.sleep(0.1)
| [
[
1,
0,
0.0408,
0.0204,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0408,
0.0204,
0,
0.66,
0.125,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0612,
0.0204,
0,
0.6... | [
"import roslib; roslib.load_manifest('hrl_pr2_kinematics_tutorials')",
"import roslib; roslib.load_manifest('hrl_pr2_kinematics_tutorials')",
"import rospy",
"from visualization_msgs.msg import Marker",
"from geometry_msgs.msg import Point",
"import hrl_lib.transforms as tr",
"import math, numpy as np",... |
#
#
# Copyright (c) 2010, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
import roslib
roslib.load_manifest('hrl_simple_arm_goals')
import rospy
import actionlib
from move_arm_msgs.msg import MoveArmGoal
from move_arm_msgs.msg import MoveArmAction
from motion_planning_msgs.msg import PositionConstraint
from motion_planning_msgs.msg import OrientationConstraint
from geometric_shapes_msgs.msg import Shape
from actionlib_msgs.msg import GoalStatus
if __name__ == '__main__':
rospy.init_node('arm_cartesian_goal_sender')
move_arm = actionlib.SimpleActionClient('move_right_arm', MoveArmAction)
move_arm.wait_for_server()
rospy.logout('Connected to server')
goalA = MoveArmGoal()
goalA.motion_plan_request.group_name = 'right_arm'
goalA.motion_plan_request.num_planning_attempts = 1
goalA.motion_plan_request.planner_id = ''
goalA.planner_service_name = 'ompl_planning/plan_kinematic_path'
goalA.motion_plan_request.allowed_planning_time = rospy.Duration(5.)
pc = PositionConstraint()
pc.header.stamp = rospy.Time.now()
pc.header.frame_id = 'torso_lift_link'
pc.link_name = 'r_wrist_roll_link'
pc.position.x = 0.75
pc.position.y = -0.188
pc.position.z = 0
pc.constraint_region_shape.type = Shape.BOX
pc.constraint_region_shape.dimensions = [0.02, 0.02, 0.02]
pc.constraint_region_orientation.w = 1.0
goalA.motion_plan_request.goal_constraints.position_constraints.append(pc)
oc = OrientationConstraint()
oc.header.stamp = rospy.Time.now()
oc.header.frame_id = 'torso_lift_link'
oc.link_name = 'r_wrist_roll_link'
oc.orientation.x = 0.
oc.orientation.y = 0.
oc.orientation.z = 0.
oc.orientation.w = 1.
oc.absolute_roll_tolerance = 0.04
oc.absolute_pitch_tolerance = 0.04
oc.absolute_yaw_tolerance = 0.04
oc.weight = 1.
goalA.motion_plan_request.goal_constraints.orientation_constraints.append(oc)
move_arm.send_goal(goalA)
finished_within_time = move_arm.wait_for_result()
if not finished_within_time:
move_arm.cancel_goal()
rospy.logout('Timed out achieving goal A')
else:
state = move_arm.get_state()
if state == GoalStatus.SUCCEEDED:
rospy.logout('Action finished with SUCCESS')
else:
rospy.logout('Action failed')
| [
[
1,
0,
0.3048,
0.0095,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.3143,
0.0095,
0,
0.66,
0.1,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.3333,
0.0095,
0,
0.66,... | [
"import roslib",
"roslib.load_manifest('hrl_simple_arm_goals')",
"import rospy",
"import actionlib",
"from move_arm_msgs.msg import MoveArmGoal",
"from move_arm_msgs.msg import MoveArmAction",
"from motion_planning_msgs.msg import PositionConstraint",
"from motion_planning_msgs.msg import OrientationC... |
import matplotlib.pyplot as pp
import numpy as np
import roslib; roslib.load_manifest('hrl_pr2_door_opening')
roslib.load_manifest('equilibrium_point_control')
import hrl_lib.util as ut
import equilibrium_point_control.arm_trajectories_ram as atr
d = ut.load_pickle('pkls/ikea_cabinet_log.pkl')
#d = ut.load_pickle('pkls/ikea_cabinet_2.pkl')
#d = ut.load_pickle('pkls/lab_cabinet_log.pkl')
typ = 'rotary'
pr2_log = True
d['f_list'] = d['f_list_estimate']
h_config, h_ftan_estimate = atr.force_trajectory_in_hindsight(d, typ, pr2_log)
pp.plot(np.degrees(h_config), h_ftan_estimate, 'ro-', mew=0, ms=0,
label='estimate')
if 'f_list_torques' in d:
d['f_list'] = d['f_list_torques']
h_config, h_ftan_torques = atr.force_trajectory_in_hindsight(d, typ,
pr2_log)
pp.plot(np.degrees(h_config), h_ftan_torques, 'go-', mew=0, ms=0,
label='torques')
d['f_list'] = d['f_list_ati']
h_config, h_ftan_ati = atr.force_trajectory_in_hindsight(d, typ, pr2_log)
pp.plot(np.degrees(h_config), h_ftan_ati, 'bo-', mew=0, ms=0,
label='ATI')
pp.legend()
pp.show()
| [
[
1,
0,
0.0513,
0.0256,
0,
0.66,
0,
596,
0,
1,
0,
0,
596,
0,
0
],
[
1,
0,
0.0769,
0.0256,
0,
0.66,
0.0556,
954,
0,
1,
0,
0,
954,
0,
0
],
[
1,
0,
0.1282,
0.0256,
0,
... | [
"import matplotlib.pyplot as pp",
"import numpy as np",
"import roslib; roslib.load_manifest('hrl_pr2_door_opening')",
"import roslib; roslib.load_manifest('hrl_pr2_door_opening')",
"roslib.load_manifest('equilibrium_point_control')",
"import hrl_lib.util as ut",
"import equilibrium_point_control.arm_tr... |
import numpy as np, math
from threading import RLock, Timer
import sys, copy
import roslib; roslib.load_manifest('hrl_pr2_lib')
roslib.load_manifest('force_torque') # hack by Advait
import force_torque.FTClient as ftc
import tf
import hrl_lib.transforms as tr
import hrl_lib.viz as hv
import rospy
import PyKDL as kdl
import actionlib
from actionlib_msgs.msg import GoalStatus
from kinematics_msgs.srv import GetPositionIK, GetPositionIKRequest, GetPositionIKResponse
from pr2_controllers_msgs.msg import JointTrajectoryAction, JointTrajectoryGoal, JointTrajectoryControllerState
from pr2_controllers_msgs.msg import Pr2GripperCommandGoal, Pr2GripperCommandAction, Pr2GripperCommand
from trajectory_msgs.msg import JointTrajectoryPoint
from geometry_msgs.msg import PoseStamped
from teleop_controllers.msg import JTTeleopControllerState
from std_msgs.msg import Float64
from sensor_msgs.msg import JointState
import hrl_lib.transforms as tr
import hrl_lib.kdl_utils as ku
import time
from visualization_msgs.msg import Marker
node_name = "pr2_arms"
def log(str):
rospy.loginfo(node_name + ": " + str)
##
# Convert arrays, lists, matricies to column format.
#
# @param x the unknown format
# @return a column matrix
def make_column(x):
if (type(x) == type([])
or (type(x) == np.ndarray and x.ndim == 1)
or type(x) == type(())):
return np.matrix(x).T
if type(x) == np.ndarray:
x = np.matrix(x)
if x.shape[0] == 1:
return x.T
return x
class PR2Arms(object):
def __init__(self, primary_ft_sensor):
log("Loading PR2Arms")
self.arms = PR2Arms_kdl() # KDL chain.
self.joint_names_list = [['r_shoulder_pan_joint',
'r_shoulder_lift_joint', 'r_upper_arm_roll_joint',
'r_elbow_flex_joint', 'r_forearm_roll_joint',
'r_wrist_flex_joint', 'r_wrist_roll_joint'],
['l_shoulder_pan_joint',
'l_shoulder_lift_joint', 'l_upper_arm_roll_joint',
'l_elbow_flex_joint', 'l_forearm_roll_joint',
'l_wrist_flex_joint', 'l_wrist_roll_joint']]
self.arm_state_lock = [RLock(), RLock()]
self.jep = [None, None]
self.arm_angles = [None, None]
self.torso_position = None
self.arm_efforts = [None, None]
self.r_arm_cart_pub = rospy.Publisher('/r_cart/command_pose', PoseStamped)
self.l_arm_cart_pub = rospy.Publisher('/l_cart/command_pose', PoseStamped)
rospy.Subscriber('/r_cart/state', JTTeleopControllerState, self.r_cart_state_cb)
rospy.Subscriber('/l_cart/state', JTTeleopControllerState, self.l_cart_state_cb)
rospy.Subscriber('/joint_states', JointState,
self.joint_states_cb, queue_size=2)
self.marker_pub = rospy.Publisher('/pr2_arms/viz_markers', Marker)
self.cep_marker_id = 1
self.r_arm_ftc = ftc.FTClient('force_torque_ft2')
self.r_arm_ftc_estimate = ftc.FTClient('force_torque_ft2_estimate')
self.tf_lstnr = tf.TransformListener()
if primary_ft_sensor == 'ati':
self.get_wrist_force = self.get_wrist_force_ati
if primary_ft_sensor == 'estimate':
self.get_wrist_force = self.get_wrist_force_estimate
r_action_client = actionlib.SimpleActionClient('r_arm_controller/joint_trajectory_action',
JointTrajectoryAction)
l_action_client = actionlib.SimpleActionClient('l_arm_controller/joint_trajectory_action',
JointTrajectoryAction)
self.joint_action_client = [r_action_client, l_action_client]
r_gripper_client = actionlib.SimpleActionClient('r_gripper_controller/gripper_action',
Pr2GripperCommandAction)
l_gripper_client = actionlib.SimpleActionClient('l_gripper_controller/gripper_action',
Pr2GripperCommandAction)
self.gripper_action_client = [r_gripper_client, l_gripper_client]
rospy.sleep(2.)
# self.joint_action_client[0].wait_for_server()
# self.joint_action_client[1].wait_for_server()
self.gripper_action_client[0].wait_for_server()
self.gripper_action_client[1].wait_for_server()
log("Finished loading SimpleArmManger")
##
# Callback for /joint_states topic. Updates current joint
# angles and efforts for the arms constantly
# @param data JointState message recieved from the /joint_states topic
def joint_states_cb(self, data):
arm_angles = [[], []]
arm_efforts = [[], []]
r_jt_idx_list = [0]*7
l_jt_idx_list = [0]*7
for i, jt_nm in enumerate(self.joint_names_list[0]):
r_jt_idx_list[i] = data.name.index(jt_nm)
for i, jt_nm in enumerate(self.joint_names_list[1]):
l_jt_idx_list[i] = data.name.index(jt_nm)
for i in range(7):
idx = r_jt_idx_list[i]
if data.name[idx] != self.joint_names_list[0][i]:
raise RuntimeError('joint angle name does not match. Expected: %s, Actual: %s i: %d'%('r_'+nm+'_joint', data.name[idx], i))
arm_angles[0].append(data.position[idx])
arm_efforts[0].append(data.effort[idx])
idx = l_jt_idx_list[i]
if data.name[idx] != self.joint_names_list[1][i]:
raise RuntimeError('joint angle name does not match. Expected: %s, Actual: %s i: %d'%('r_'+nm+'_joint', data.name[idx], i))
#ang = tr.angle_within_mod180(data.position[idx])
ang = data.position[idx]
arm_angles[1] += [ang]
arm_efforts[1] += [data.effort[idx]]
self.arm_state_lock[0].acquire()
self.arm_angles[0] = arm_angles[0]
self.arm_efforts[0] = arm_efforts[0]
torso_idx = data.name.index('torso_lift_joint')
self.torso_position = data.position[torso_idx]
self.arm_state_lock[0].release()
self.arm_state_lock[1].acquire()
self.arm_angles[1] = arm_angles[1]
self.arm_efforts[1] = arm_efforts[1]
self.arm_state_lock[1].release()
def r_cart_state_cb(self, msg):
trans, quat = self.tf_lstnr.lookupTransform('/torso_lift_link',
'r_gripper_tool_frame', rospy.Time(0))
rot = tr.quaternion_to_matrix(quat)
tip = np.matrix([0.12, 0., 0.]).T
self.r_ee_pos = rot*tip + np.matrix(trans).T
self.r_ee_rot = rot
marker = Marker()
marker.header.frame_id = 'torso_lift_link'
time_stamp = rospy.Time.now()
marker.header.stamp = time_stamp
marker.ns = 'aloha land'
marker.type = Marker.SPHERE
marker.action = Marker.ADD
marker.pose.position.x = self.r_ee_pos[0,0]
marker.pose.position.y = self.r_ee_pos[1,0]
marker.pose.position.z = self.r_ee_pos[2,0]
size = 0.02
marker.scale.x = size
marker.scale.y = size
marker.scale.z = size
marker.lifetime = rospy.Duration()
marker.id = 71
marker.pose.orientation.x = 0
marker.pose.orientation.y = 0
marker.pose.orientation.z = 0
marker.pose.orientation.w = 1
color = (0.5, 0., 0.0)
marker.color.r = color[0]
marker.color.g = color[1]
marker.color.b = color[2]
marker.color.a = 1.
self.marker_pub.publish(marker)
ros_pt = msg.x_desi_filtered.pose.position
x, y, z = ros_pt.x, ros_pt.y, ros_pt.z
self.r_cep_pos = np.matrix([x, y, z]).T
pt = rot.T * (np.matrix([x,y,z]).T - np.matrix(trans).T)
pt = pt + tip
self.r_cep_pos_hooktip = rot*pt + np.matrix(trans).T
ros_quat = msg.x_desi_filtered.pose.orientation
quat = (ros_quat.x, ros_quat.y, ros_quat.z, ros_quat.w)
self.r_cep_rot = tr.quaternion_to_matrix(quat)
def l_cart_state_cb(self, msg):
ros_pt = msg.x_desi_filtered.pose.position
self.l_cep_pos = np.matrix([ros_pt.x, ros_pt.y, ros_pt.z]).T
ros_quat = msg.x_desi_filtered.pose.orientation
quat = (ros_quat.x, ros_quat.y, ros_quat.z, ros_quat.w)
self.l_cep_rot = tr.quaternion_to_matrix(quat)
## Returns the current position, rotation of the arm.
# @param arm 0 for right, 1 for left
# @return rotation, position
def end_effector_pos(self, arm):
q = self.get_joint_angles(arm)
return self.arms.FK_all(arm, q)
## Returns the list of 7 joint angles
# @param arm 0 for right, 1 for left
# @return list of 7 joint angles
def get_joint_angles(self, arm):
if arm != 1:
arm = 0
self.arm_state_lock[arm].acquire()
q = self.arm_angles[arm]
self.arm_state_lock[arm].release()
return q
def set_jep(self, arm, q, duration=0.15):
self.arm_state_lock[arm].acquire()
jtg = JointTrajectoryGoal()
jtg.trajectory.joint_names = self.joint_names_list[arm]
jtp = JointTrajectoryPoint()
jtp.positions = q
#jtp.velocities = [0 for i in range(len(q))]
#jtp.accelerations = [0 for i in range(len(q))]
jtp.time_from_start = rospy.Duration(duration)
jtg.trajectory.points.append(jtp)
self.joint_action_client[arm].send_goal(jtg)
self.jep[arm] = q
cep, r = self.arms.FK_all(arm, q)
self.arm_state_lock[arm].release()
o = np.matrix([0.,0.,0.,1.]).T
cep_marker = hv.single_marker(cep, o, 'sphere',
'/torso_lift_link', color=(0., 0., 1., 1.),
scale = (0.02, 0.02, 0.02),
m_id = self.cep_marker_id)
cep_marker.header.stamp = rospy.Time.now()
self.marker_pub.publish(cep_marker)
def get_jep(self, arm):
self.arm_state_lock[arm].acquire()
jep = copy.copy(self.jep[arm])
self.arm_state_lock[arm].release()
return jep
def get_ee_jtt(self, arm):
if arm == 0:
return self.r_ee_pos, self.r_ee_rot
else:
return self.l_ee_pos, self.l_ee_rot
def get_cep_jtt(self, arm, hook_tip = False):
if arm == 0:
if hook_tip:
return self.r_cep_pos_hooktip, self.r_cep_rot
else:
return self.r_cep_pos, self.r_cep_rot
else:
return self.l_cep_pos, self.l_cep_rot
# set a cep using the Jacobian Transpose controller.
def set_cep_jtt(self, arm, p, rot=None):
if arm != 1:
arm = 0
ps = PoseStamped()
ps.header.stamp = rospy.rostime.get_rostime()
ps.header.frame_id = 'torso_lift_link'
ps.pose.position.x = p[0,0]
ps.pose.position.y = p[1,0]
ps.pose.position.z = p[2,0]
if rot == None:
if arm == 0:
rot = self.r_cep_rot
else:
rot = self.l_cep_rot
quat = tr.matrix_to_quaternion(rot)
ps.pose.orientation.x = quat[0]
ps.pose.orientation.y = quat[1]
ps.pose.orientation.z = quat[2]
ps.pose.orientation.w = quat[3]
if arm == 0:
self.r_arm_cart_pub.publish(ps)
else:
self.l_arm_cart_pub.publish(ps)
# rotational interpolation unimplemented.
def go_cep_jtt(self, arm, p):
step_size = 0.01
sleep_time = 0.1
cep_p, cep_rot = self.get_cep_jtt(arm)
unit_vec = (p-cep_p)
unit_vec = unit_vec / np.linalg.norm(unit_vec)
while np.linalg.norm(p-cep_p) > step_size:
cep_p += unit_vec * step_size
self.set_cep_jtt(arm, cep_p)
rospy.sleep(sleep_time)
self.set_cep_jtt(arm, p)
rospy.sleep(sleep_time)
#----------- forces ------------
# force that is being applied on the wrist. (estimate as returned
# by the cartesian controller)
def get_wrist_force_estimate(self, arm, bias = True, base_frame = False):
if arm != 0:
rospy.logerr('Unsupported arm: %d'%arm)
raise RuntimeError('Unimplemented function')
f = self.r_arm_ftc_estimate.read(without_bias = not bias)
f = f[0:3, :]
if base_frame:
trans, quat = self.tf_lstnr.lookupTransform('/torso_lift_link',
'/ft2_estimate', rospy.Time(0))
rot = tr.quaternion_to_matrix(quat)
f = rot * f
return -f # the negative is intentional (Advait, Nov 24. 2010.)
# force that is being applied on the wrist.
def get_wrist_force_ati(self, arm, bias = True, base_frame = False):
if arm != 0:
rospy.logerr('Unsupported arm: %d'%arm)
raise RuntimeError('Unimplemented function')
f = self.r_arm_ftc.read(without_bias = not bias)
f = f[0:3, :]
if base_frame:
trans, quat = self.tf_lstnr.lookupTransform('/torso_lift_link',
'/ft2', rospy.Time(0))
rot = tr.quaternion_to_matrix(quat)
f = rot * f
return -f # the negative is intentional (Advait, Nov 24. 2010.)
## Returns the list of 7 joint angles
# @param arm 0 for right, 1 for left
# @return list of 7 joint angles
def get_force_from_torques(self, arm):
if arm != 1:
arm = 0
self.arm_state_lock[arm].acquire()
q = self.arm_angles[arm]
tau = self.arm_efforts[arm]
self.arm_state_lock[arm].release()
p, _ = self.arms.FK_all(arm, q)
J = self.arms.Jacobian(arm, q, p)
f = np.linalg.pinv(J.T) * np.matrix(tau).T
f = f[0:3,:]
return -f
def bias_wrist_ft(self, arm):
if arm != 0:
rospy.logerr('Unsupported arm: %d'%arm)
raise RuntimeError('Unimplemented function')
self.r_arm_ftc.bias()
self.r_arm_ftc_estimate.bias()
#-------- gripper functions ------------
def move_gripper(self, arm, amount=0.08, effort = 15):
self.gripper_action_client[arm].send_goal(Pr2GripperCommandGoal(Pr2GripperCommand(position=amount,
max_effort = effort)))
## Open the gripper
# @param arm 0 for right, 1 for left
def open_gripper(self, arm):
self.move_gripper(arm, 0.08, -1)
## Close the gripper
# @param arm 0 for right, 1 for left
def close_gripper(self, arm, effort = 15):
self.move_gripper(arm, 0.0, effort)
##
# using KDL for pr2 arm kinematics.
class PR2Arms_kdl():
def __init__(self):
self.right_chain = self.create_right_chain()
fk, ik_v, ik_p, jac = self.create_solvers(self.right_chain)
self.right_fk = fk
self.right_ik_v = ik_v
self.right_ik_p = ik_p
self.right_jac = jac
self.right_tooltip = np.matrix([0.,0.,0.]).T
def create_right_chain(self):
ch = kdl.Chain()
self.right_arm_base_offset_from_torso_lift_link = np.matrix([0., -0.188, 0.]).T
# shoulder pan
ch.addSegment(kdl.Segment(kdl.Joint(kdl.Joint.RotZ),kdl.Frame(kdl.Vector(0.1,0.,0.))))
# shoulder lift
ch.addSegment(kdl.Segment(kdl.Joint(kdl.Joint.RotY),kdl.Frame(kdl.Vector(0.,0.,0.))))
# upper arm roll
ch.addSegment(kdl.Segment(kdl.Joint(kdl.Joint.RotX),kdl.Frame(kdl.Vector(0.4,0.,0.))))
# elbox flex
ch.addSegment(kdl.Segment(kdl.Joint(kdl.Joint.RotY),kdl.Frame(kdl.Vector(0.0,0.,0.))))
# forearm roll
ch.addSegment(kdl.Segment(kdl.Joint(kdl.Joint.RotX),kdl.Frame(kdl.Vector(0.321,0.,0.))))
# wrist flex
ch.addSegment(kdl.Segment(kdl.Joint(kdl.Joint.RotY),kdl.Frame(kdl.Vector(0.,0.,0.))))
# wrist roll
ch.addSegment(kdl.Segment(kdl.Joint(kdl.Joint.RotX),kdl.Frame(kdl.Vector(0.,0.,0.))))
return ch
def create_solvers(self, ch):
fk = kdl.ChainFkSolverPos_recursive(ch)
ik_v = kdl.ChainIkSolverVel_pinv(ch)
ik_p = kdl.ChainIkSolverPos_NR(ch, fk, ik_v)
jac = kdl.ChainJntToJacSolver(ch)
return fk, ik_v, ik_p, jac
## define tooltip as a 3x1 np matrix in the wrist coord frame.
def set_tooltip(self, arm, p):
if arm == 0:
self.right_tooltip = p
else:
rospy.logerr('Arm %d is not supported.'%(arm))
def FK_kdl(self, arm, q, link_number):
if arm == 0:
fk = self.right_fk
endeffec_frame = kdl.Frame()
kinematics_status = fk.JntToCart(q, endeffec_frame,
link_number)
if kinematics_status >= 0:
return endeffec_frame
else:
rospy.loginfo('Could not compute forward kinematics.')
return None
else:
msg = '%s arm not supported.'%(arm)
rospy.logerr(msg)
raise RuntimeError(msg)
## returns point in torso lift link.
def FK_all(self, arm, q, link_number = 7):
q = self.pr2_to_kdl(q)
frame = self.FK_kdl(arm, q, link_number)
pos = frame.p
pos = ku.kdl_vec_to_np(pos)
pos = pos + self.right_arm_base_offset_from_torso_lift_link
m = frame.M
rot = ku.kdl_rot_to_np(m)
if arm == 0:
tooltip_baseframe = rot * self.right_tooltip
pos += tooltip_baseframe
else:
rospy.logerr('Arm %d is not supported.'%(arm))
return None
return pos, rot
def kdl_to_pr2(self, q):
if q == None:
return None
q_pr2 = [0] * 7
q_pr2[0] = q[0]
q_pr2[1] = q[1]
q_pr2[2] = q[2]
q_pr2[3] = q[3]
q_pr2[4] = q[4]
q_pr2[5] = q[5]
q_pr2[6] = q[6]
return q_pr2
def pr2_to_kdl(self, q):
if q == None:
return None
n = len(q)
q_kdl = kdl.JntArray(n)
for i in range(n):
q_kdl[i] = q[i]
return q_kdl
def Jac_kdl(self, arm, q):
J_kdl = kdl.Jacobian(7)
if arm != 0:
rospy.logerr('Unsupported arm: '+ str(arm))
return None
self.right_jac.JntToJac(q,J_kdl)
kdl_jac = np.matrix([
[J_kdl[0,0],J_kdl[0,1],J_kdl[0,2],J_kdl[0,3],J_kdl[0,4],J_kdl[0,5],J_kdl[0,6]],
[J_kdl[1,0],J_kdl[1,1],J_kdl[1,2],J_kdl[1,3],J_kdl[1,4],J_kdl[1,5],J_kdl[1,6]],
[J_kdl[2,0],J_kdl[2,1],J_kdl[2,2],J_kdl[2,3],J_kdl[2,4],J_kdl[2,5],J_kdl[2,6]],
[J_kdl[3,0],J_kdl[3,1],J_kdl[3,2],J_kdl[3,3],J_kdl[3,4],J_kdl[3,5],J_kdl[3,6]],
[J_kdl[4,0],J_kdl[4,1],J_kdl[4,2],J_kdl[4,3],J_kdl[4,4],J_kdl[4,5],J_kdl[4,6]],
[J_kdl[5,0],J_kdl[5,1],J_kdl[5,2],J_kdl[5,3],J_kdl[5,4],J_kdl[5,5],J_kdl[5,6]],
])
return kdl_jac
# ## compute Jacobian (at wrist).
# # @param arm - 0 or 1
# # @param q - list of 7 joint angles.
# # @return 6x7 np matrix
# def Jac(self, arm, q):
# rospy.logerr('Jac only works for getting the Jacobian at the wrist. Use Jacobian to get the Jacobian at a general location.')
# jntarr = self.pr2_to_kdl(q)
# kdl_jac = self.Jac_kdl(arm, jntarr)
# pr2_jac = kdl_jac
# return pr2_jac
## compute Jacobian at point pos.
# p is in the torso_lift_link coord frame.
def Jacobian(self, arm, q, pos):
if arm != 0:
rospy.logerr('Arm %d is not supported.'%(arm))
return None
tooltip = self.right_tooltip
self.right_tooltip = np.matrix([0.,0.,0.]).T
v_list = []
w_list = []
for i in range(7):
p, rot = self.FK_all(arm, q, i)
r = pos - p
z_idx = self.right_chain.getSegment(i).getJoint().getType() - 1
z = rot[:, z_idx]
v_list.append(np.matrix(np.cross(z.A1, r.A1)).T)
w_list.append(z)
J = np.row_stack((np.column_stack(v_list), np.column_stack(w_list)))
self.right_tooltip = tooltip
return J
def close_to_singularity(self, arm, q):
pass
def within_joint_limits(self, arm, q, delta_list=[0., 0., 0., 0., 0., 0., 0.]):
if arm == 0: # right arm
min_arr = np.radians(np.array([-109., -24, -220, -132, -np.inf, -120, -np.inf]))
#max_arr = np.radians(np.array([26., 68, 41, 0, np.inf, 0, np.inf]))
max_arr = np.radians(np.array([26., 68, 41, 5, np.inf, 5, np.inf])) # 5 to prevent singularity. Need to come up with a better solution.
else:
raise RuntimeError('within_joint_limits unimplemented for left arm')
q_arr = np.array(q)
d_arr = np.array(delta_list)
return np.all((q_arr <= max_arr+d_arr, q_arr >= min_arr+d_arr))
if __name__ == '__main__':
from visualization_msgs.msg import Marker
import hrl_lib.viz as hv
rospy.init_node('pr2_arms_test')
pr2_arms = PR2Arms()
pr2_kdl = PR2Arms_kdl()
r_arm, l_arm = 0, 1
arm = r_arm
if True:
np.set_printoptions(precision=2, suppress=True)
while not rospy.is_shutdown():
q = pr2_arms.get_joint_angles(arm)
print 'q in degrees:', np.degrees(q)
rospy.sleep(0.1)
if False:
jep = [0.] * 7
rospy.loginfo('Going to home location.')
raw_input('Hit ENTER to go')
pr2_arms.set_jep(arm, jep, duration=2.)
if False:
# testing FK by publishing a frame marker.
marker_pub = rospy.Publisher('/pr2_kdl/ee_marker', Marker)
pr2_kdl.set_tooltip(arm, np.matrix([0.15, 0., 0.]).T)
rt = rospy.Rate(100)
rospy.loginfo('Starting the maker publishing loop.')
while not rospy.is_shutdown():
q = pr2_arms.get_joint_angles(arm)
p, rot = pr2_kdl.FK_all(arm, q)
m = hv.create_frame_marker(p, rot, 0.15, '/torso_lift_link')
m.header.stamp = rospy.Time.now()
marker_pub.publish(m)
rt.sleep()
if False:
# testing Jacobian by printing KDL and my own Jacobian at the
# current configuration.
while not rospy.is_shutdown():
q = pr2_arms.get_joint_angles(arm)
J_kdl = pr2_kdl.Jac(arm , q)
p, rot = pr2_kdl.FK_all(arm, q)
J_adv = pr2_kdl.Jacobian(arm, q, p)
print J_adv.shape
diff_J = J_kdl - J_adv
print 'difference between KDL and adv is:'
print diff_J
print 'Norm of difference matrix:', np.linalg.norm(diff_J)
raw_input('Move arm into some configuration and hit enter to get the Jacobian.')
# ## Performs Inverse Kinematics on the given position and rotation
# # @param arm 0 for right, 1 for left
# # @param p cartesian position in torso_lift_link frame
# # @param rot quaternion rotation column or rotation matrix
# # of wrist in torso_lift_link frame
# # @param q_guess initial joint angles to use for finding IK
# def IK(self, arm, p, rot, q_guess):
# if arm != 1:
# arm = 0
#
# p = make_column(p)
#
# if rot.shape == (3, 3):
# quat = np.matrix(tr.matrix_to_quaternion(rot)).T
# elif rot.shape == (4, 1):
# quat = make_column(rot)
# else:
# rospy.logerr('Inverse kinematics failed (bad rotation)')
# return None
#
# ik_req = GetPositionIKRequest()
# ik_req.timeout = rospy.Duration(5.)
# if arm == 0:
# ik_req.ik_request.ik_link_name = 'r_wrist_roll_link'
# else:
# ik_req.ik_request.ik_link_name = 'l_wrist_roll_link'
# ik_req.ik_request.pose_stamped.header.frame_id = 'torso_lift_link'
#
# ik_req.ik_request.pose_stamped.pose.position.x = p[0,0]
# ik_req.ik_request.pose_stamped.pose.position.y = p[1,0]
# ik_req.ik_request.pose_stamped.pose.position.z = p[2,0]
#
# ik_req.ik_request.pose_stamped.pose.orientation.x = quat[0]
# ik_req.ik_request.pose_stamped.pose.orientation.y = quat[1]
# ik_req.ik_request.pose_stamped.pose.orientation.z = quat[2]
# ik_req.ik_request.pose_stamped.pose.orientation.w = quat[3]
#
# ik_req.ik_request.ik_seed_state.joint_state.position = q_guess
# ik_req.ik_request.ik_seed_state.joint_state.name = self.joint_names_list[arm]
#
# ik_resp = self.ik_srv[arm].call(ik_req)
# if ik_resp.error_code.val == ik_resp.error_code.SUCCESS:
# ret = list(ik_resp.solution.joint_state.position)
# else:
# rospy.logerr('Inverse kinematics failed')
# ret = None
#
# return ret
#
| [
[
1,
0,
0.0043,
0.0014,
0,
0.66,
0,
954,
0,
2,
0,
0,
954,
0,
0
],
[
1,
0,
0.0058,
0.0014,
0,
0.66,
0.0323,
83,
0,
2,
0,
0,
83,
0,
0
],
[
1,
0,
0.0072,
0.0014,
0,
0.... | [
"import numpy as np, math",
"from threading import RLock, Timer",
"import sys, copy",
"import roslib; roslib.load_manifest('hrl_pr2_lib')",
"import roslib; roslib.load_manifest('hrl_pr2_lib')",
"roslib.load_manifest('force_torque') # hack by Advait",
"import force_torque.FTClient as ftc",
"import tf",... |
#
# Temoprarily in this package. Advait needs to move it to a better
# location.
#
import numpy as np, math
import copy
import roslib; roslib.load_manifest('hrl_pr2_door_opening')
import rospy
import hrl_lib.util as ut
## Class defining the core EPC function and a few simple examples.
# More complex behaviors that use EPC should have their own ROS
# packages.
class EPC():
def __init__(self, robot):
self.robot = robot
self.f_list = []
self.ee_list = []
self.cep_list = []
##
# @param equi_pt_generator: function that returns stop, ea where ea: equilibrium angles and stop: string which is '' for epc motion to continue
# @param rapid_call_func: called in the time between calls to the equi_pt_generator can be used for logging, safety etc. returns string which is '' for epc motion to continue
# @param time_step: time between successive calls to equi_pt_generator
# @param arg_list - list of arguments to be passed to the equi_pt_generator
# @return stop (the string which has the reason why the epc
# motion stopped.), ea (last commanded equilibrium angles)
def epc_motion(self, equi_pt_generator, time_step, arm, arg_list,
rapid_call_func=None, control_function=None):
stop, ea = equi_pt_generator(*arg_list)
t_end = rospy.get_time()
while stop == '':
if rospy.is_shutdown():
stop = 'rospy shutdown'
continue
t_end += time_step
#self.robot.set_jointangles(arm, ea)
#import pdb; pdb.set_trace()
control_function(arm, *ea)
# self.robot.step() this should be within the rapid_call_func for the meka arms.
t1 = rospy.get_time()
while t1<t_end:
if rapid_call_func != None:
stop = rapid_call_func(arm)
if stop != '':
break
#self.robot.step() this should be within the rapid_call_func for the meka arms
rospy.sleep(0.01)
t1 = rospy.get_time()
if stop == '':
stop, ea = equi_pt_generator(*arg_list)
if stop == 'reset timing':
stop = ''
t_end = rospy.get_time()
return stop, ea
## Pull back along a straight line (-ve x direction)
# @param arm - 'right_arm' or 'left_arm'
# @param distance - how far back to pull.
def pull_back_cartesian_control(self, arm, distance, logging_fn):
cep, _ = self.robot.get_cep_jtt(arm)
cep_end = cep + distance * np.matrix([-1., 0., 0.]).T
self.dist_left = distance
def eq_gen_pull_back(cep):
logging_fn(arm)
if self.dist_left <= 0.:
return 'done', None
step_size = 0.01
cep[0,0] -= step_size
self.dist_left -= step_size
if cep[0,0] < 0.4:
return 'very close to the body: %.3f'%cep[0,0], None
return '', (cep, None)
arg_list = [cep]
s = self.epc_motion(eq_gen_pull_back, 0.1, arm, arg_list,
control_function = self.robot.set_cep_jtt)
print s
def move_till_hit(self, arm, vec=np.matrix([0.3,0.,0.]).T, force_threshold=3.0,
speed=0.1, bias_FT=True):
unit_vec = vec/np.linalg.norm(vec)
time_step = 0.1
dist = np.linalg.norm(vec)
step_size = speed * time_step
cep_start, _ = self.robot.get_cep_jtt(arm)
cep = copy.copy(cep_start)
def eq_gen(cep):
force = self.robot.get_wrist_force(arm, base_frame = True)
force_projection = force.T*unit_vec *-1 # projection in direction opposite to motion.
print 'force_projection:', force_projection
if force_projection>force_threshold:
return 'done', None
elif np.linalg.norm(force)>45.:
return 'large force', None
elif np.linalg.norm(cep_start-cep) >= dist:
return 'reached without contact', None
else:
cep_t = cep + unit_vec * step_size
cep[0,0] = cep_t[0,0]
cep[1,0] = cep_t[1,0]
cep[2,0] = cep_t[2,0]
return '', (cep, None)
if bias_FT:
self.robot.bias_wrist_ft(arm)
rospy.sleep(0.5)
return self.epc_motion(eq_gen, time_step, arm, [cep],
control_function = self.robot.set_cep_jtt)
def cep_gen_surface_follow(self, arm, move_dir, force_threshold,
cep, cep_start):
wrist_force = self.robot.get_wrist_force(arm, base_frame=True)
if wrist_force[0,0] < -3.:
cep[0,0] -= 0.002
if wrist_force[0,0] > -1.:
cep[0,0] += 0.003
if cep[0,0] > (cep_start[0,0]+0.05):
cep[0,0] = cep_start[0,0]+0.05
step_size = 0.002
cep_t = cep + move_dir * step_size
cep[0,0] = cep_t[0,0]
cep[1,0] = cep_t[1,0]
cep[2,0] = cep_t[2,0]
print 'wrist_force:', wrist_force.A1
v = cep - cep_start
if (wrist_force.T * move_dir)[0,0] < -force_threshold:
stop = 'got a hook'
elif np.linalg.norm(wrist_force) > 50.:
stop = 'force is large %f'%(np.linalg.norm(wrist_force))
elif (v.T * move_dir)[0,0] > 0.20:
stop = 'moved a lot without a hook'
else:
stop = ''
return stop, (cep, None)
if __name__ == '__main__':
import pr2_arms as pa
rospy.init_node('epc_pr2', anonymous = True)
rospy.logout('epc_pr2: ready')
pr2_arms = pa.PR2Arms()
epc = EPC(pr2_arms)
r_arm, l_arm = 0, 1
arm = r_arm
# #----- testing move_till_hit ------
# p1 = np.matrix([0.6, -0.22, -0.05]).T
# epc.robot.go_cep_jtt(arm, p1)
# epc.move_till_hit(arm)
raw_input('Hit ENTER to close')
pr2_arms.close_gripper(arm)
raw_input('Hit ENTER to search_and_hook')
p1 = np.matrix([0.8, -0.22, -0.05]).T
epc.search_and_hook(arm, p1)
epc.pull_back_cartesian_control(arm, 0.3)
d = {
'f_list': epc.f_list, 'ee_list': epc.ee_list,
'cep_list': epc.cep_list
}
ut.save_pickle(d, 'pr2_pull_'+ut.formatted_time()+'.pkl')
# if False:
# ea = [0, 0, 0, 0, 0, 0, 0]
# ea = epc.robot.get_joint_angles(arm)
# rospy.logout('Going to starting position')
# epc.robot.set_jointangles(arm, ea, duration=4.0)
# raw_input('Hit ENTER to pull')
# epc.pull_back(arm, ea, tr.Rx(0), 0.2)
#
# if False:
# p = np.matrix([0.9, -0.3, -0.15]).T
# rot = tr.Rx(0.)
# rot = tr.Rx(math.radians(90.))
#
# rospy.logout('Going to starting position')
# # epc.robot.open_gripper(arm)
# epc.robot.set_cartesian(arm, p, rot)
# # raw_input('Hit ENTER to close the gripper')
# # epc.robot.close_gripper(arm)
# raw_input('Hit ENTER to pull')
# epc.pull_back_cartesian_control(arm, p, rot, 0.4)
| [
[
1,
0,
0.0341,
0.0049,
0,
0.66,
0,
954,
0,
2,
0,
0,
954,
0,
0
],
[
1,
0,
0.039,
0.0049,
0,
0.66,
0.1429,
739,
0,
1,
0,
0,
739,
0,
0
],
[
1,
0,
0.0488,
0.0049,
0,
0... | [
"import numpy as np, math",
"import copy",
"import roslib; roslib.load_manifest('hrl_pr2_door_opening')",
"import roslib; roslib.load_manifest('hrl_pr2_door_opening')",
"import rospy",
"import hrl_lib.util as ut",
"class EPC():\n def __init__(self, robot):\n self.robot = robot\n self.f_... |
import numpy as np, math
import copy
from threading import RLock
import roslib; roslib.load_manifest('hrl_pr2_door_opening')
roslib.load_manifest('equilibrium_point_control')
import rospy
from equilibrium_point_control.msg import MechanismKinematicsRot
from equilibrium_point_control.msg import MechanismKinematicsJac
from equilibrium_point_control.msg import ForceTrajectory
from geometry_msgs.msg import Point32
from std_msgs.msg import Empty
import epc
import hrl_lib.util as ut
class Door_EPC(epc.EPC):
def __init__(self, robot):
epc.EPC.__init__(self, robot)
self.mech_kinematics_lock = RLock()
self.fit_circle_lock = RLock()
rospy.Subscriber('mechanism_kinematics_rot',
MechanismKinematicsRot,
self.mechanism_kinematics_rot_cb)
rospy.Subscriber('epc/stop', Empty, self.stop_cb)
# used in the ROS stop_cb and equi_pt_generator_control_radial_force
self.force_traj_pub = rospy.Publisher('epc/force_test', ForceTrajectory)
self.mech_traj_pub = rospy.Publisher('mechanism_trajectory', Point32)
def init_log(self):
self.f_list = []
self.f_list_ati = []
self.f_list_estimate = []
self.f_list_torques = []
self.cep_list = []
self.ee_list = []
self.ft = ForceTrajectory()
if self.mechanism_type != '':
self.ft.type = self.mechanism_type
else:
self.ft.type = 'rotary'
def log_state(self, arm):
# only logging the right arm.
f = self.robot.get_wrist_force_ati(arm, base_frame=True)
self.f_list_ati.append(f.A1.tolist())
f = self.robot.get_wrist_force_estimate(arm, base_frame=True)
self.f_list_estimate.append(f.A1.tolist())
f = self.robot.get_force_from_torques(arm)
self.f_list_torques.append(f.A1.tolist())
f = self.robot.get_wrist_force(arm, base_frame=True)
self.f_list.append(f.A1.tolist())
cep, _ = self.robot.get_cep_jtt(arm, hook_tip=True)
self.cep_list.append(cep.A1.tolist())
# ee, _ = self.robot.get_ee_jtt(arm)
ee, _ = self.robot.end_effector_pos(arm)
self.ee_list.append(ee.A1.tolist())
if self.started_pulling_on_handle == False:
if f[0,0] > 10.:
self.started_pulling_on_handle_count += 1
else:
self.started_pulling_on_handle_count = 0
self.init_log() # reset logs until started pulling on the handle.
self.init_tangent_vector = None
if self.started_pulling_on_handle_count > 1:
self.started_pulling_on_handle = True
return ''
## ROS callback. Stop and maintain position.
def stop_cb(self, cmd):
self.stopping_string = 'stop_cb called.'
def common_stopping_conditions(self):
stop = ''
# right arm only.
wrist_force = self.robot.get_wrist_force(0, base_frame=True)
mag = np.linalg.norm(wrist_force)
if mag > self.eq_force_threshold:
stop = 'force exceed'
if mag < 1.2 and self.hooked_location_moved:
if (self.prev_force_mag - mag) > 30.:
stop = 'slip: force step decrease and below thresold.'
else:
self.slip_count += 1
else:
self.slip_count = 0
if self.slip_count == 10:
stop = 'slip: force below threshold for too long.'
return stop
def mechanism_kinematics_rot_cb(self, mk):
self.fit_circle_lock.acquire()
self.cx_start = mk.cx
self.cy_start = mk.cy
self.cz_start = mk.cz
self.rad = mk.rad
self.fit_circle_lock.release()
## constantly update the estimate of the kinematics and move the
# equilibrium point along the tangent of the estimated arc, and
# try to keep the radial force constant.
# @param h_force_possible - True (hook side) or False (hook up).
# @param v_force_possible - False (hook side) or True (hook up).
# Is maintaining a radial force possible or not (based on hook
# geometry and orientation)
# @param cep_vel - tangential velocity of the cep in m/s
def cep_gen_control_radial_force(self, arm, cep, cep_vel):
self.log_state(arm)
if self.started_pulling_on_handle == False:
cep_vel = 0.02
#step_size = 0.01 * cep_vel
step_size = 0.1 * cep_vel # 0.1 is the time interval between calls to the equi_generator function (see pull)
stop = self.common_stopping_conditions()
wrist_force = self.robot.get_wrist_force(arm, base_frame=True)
mag = np.linalg.norm(wrist_force)
curr_pos, _ = self.robot.get_ee_jtt(arm)
if len(self.ee_list)>1:
start_pos = np.matrix(self.ee_list[0]).T
else:
start_pos = curr_pos
#mechanism kinematics.
if self.started_pulling_on_handle:
self.mech_traj_pub.publish(Point32(curr_pos[0,0],
curr_pos[1,0], curr_pos[2,0]))
self.fit_circle_lock.acquire()
rad = self.rad
cx_start, cy_start = self.cx_start, self.cy_start
cz_start = self.cz_start
self.fit_circle_lock.release()
cx, cy = cx_start, cy_start
cz = cz_start
print 'cx, cy, r:', cx, cy, rad
radial_vec = curr_pos - np.matrix([cx,cy,cz]).T
radial_vec = radial_vec/np.linalg.norm(radial_vec)
if cy_start < start_pos[1,0]:
tan_x,tan_y = -radial_vec[1,0],radial_vec[0,0]
else:
tan_x,tan_y = radial_vec[1,0],-radial_vec[0,0]
if tan_x > 0. and (start_pos[0,0]-curr_pos[0,0]) < 0.09:
tan_x = -tan_x
tan_y = -tan_y
if cy_start > start_pos[1,0]:
radial_vec = -radial_vec # axis to the left, want force in
# anti-radial direction.
rv = radial_vec
force_vec = np.matrix([rv[0,0], rv[1,0], 0.]).T
tangential_vec = np.matrix([tan_x, tan_y, 0.]).T
tangential_vec_ts = tangential_vec
radial_vec_ts = radial_vec
force_vec_ts = force_vec
if arm == 'right_arm' or arm == 0:
if force_vec_ts[1,0] < 0.: # only allowing force to the left
force_vec_ts = -force_vec_ts
else:
if force_vec_ts[1,0] > 0.: # only allowing force to the right
force_vec_ts = -force_vec_ts
f_vec = -1*np.array([wrist_force[0,0], wrist_force[1,0],
wrist_force[2,0]])
f_rad_mag = np.dot(f_vec, force_vec.A1)
err = f_rad_mag-4.
if err>0.:
kp = -0.1
else:
kp = -0.2
radial_motion_mag = kp * err # radial_motion_mag in cm (depends on eq_motion step size)
radial_motion_vec = force_vec * radial_motion_mag
print 'tangential_vec:', tangential_vec.A1
eq_motion_vec = copy.copy(tangential_vec)
eq_motion_vec += radial_motion_vec
self.prev_force_mag = mag
if self.init_tangent_vector == None or self.started_pulling_on_handle == False:
self.init_tangent_vector = copy.copy(tangential_vec_ts)
c = np.dot(tangential_vec_ts.A1, self.init_tangent_vector.A1)
ang = np.arccos(c)
if np.isnan(ang):
ang = 0.
tangential_vec = tangential_vec / np.linalg.norm(tangential_vec) # paranoia abot vectors not being unit vectors.
dist_moved = np.dot((curr_pos - start_pos).A1, tangential_vec_ts.A1)
ftan = abs(np.dot(wrist_force.A1, tangential_vec.A1))
self.ft.tangential_force.append(ftan)
self.ft.radial_force.append(f_rad_mag)
if self.ft.type == 'rotary':
self.ft.configuration.append(ang)
else: # drawer
print 'dist_moved:', dist_moved
self.ft.configuration.append(dist_moved)
if self.started_pulling_on_handle:
self.force_traj_pub.publish(self.ft)
# if self.started_pulling_on_handle == False:
# ftan_pull_test = -np.dot(wrist_force.A1, tangential_vec.A1)
# print 'ftan_pull_test:', ftan_pull_test
# if ftan_pull_test > 5.:
# self.started_pulling_on_handle_count += 1
# else:
# self.started_pulling_on_handle_count = 0
# self.init_log() # reset logs until started pulling on the handle.
# self.init_tangent_vector = None
#
# if self.started_pulling_on_handle_count > 1:
# self.started_pulling_on_handle = True
if abs(dist_moved) > 0.09 and self.hooked_location_moved == False:
# change the force threshold once the hook has started pulling.
self.hooked_location_moved = True
self.eq_force_threshold = ut.bound(mag+30.,20.,80.)
self.ftan_threshold = 1.2 * self.ftan_threshold + 20.
if self.hooked_location_moved:
if abs(tangential_vec_ts[2,0]) < 0.2 and ftan > self.ftan_threshold:
stop = 'ftan threshold exceed: %f'%ftan
else:
self.ftan_threshold = max(self.ftan_threshold, ftan)
if self.hooked_location_moved and ang > math.radians(90.):
print 'Angle:', math.degrees(ang)
self.open_ang_exceed_count += 1
if self.open_ang_exceed_count > 2:
stop = 'opened mechanism through large angle: %.1f'%(math.degrees(ang))
else:
self.open_ang_exceed_count = 0
cep_t = cep + eq_motion_vec * step_size
cep[0,0] = cep_t[0,0]
cep[1,0] = cep_t[1,0]
cep[2,0] = cep_t[2,0]
print 'CEP:', cep.A1
stop = stop + self.stopping_string
return stop, (cep, None)
def pull(self, arm, force_threshold, cep_vel, mechanism_type=''):
self.mechanism_type = mechanism_type
self.stopping_string = ''
self.eq_pt_not_moving_counter = 0
self.init_log()
self.init_tangent_vector = None
self.open_ang_exceed_count = 0.
self.eq_force_threshold = force_threshold
self.ftan_threshold = 2.
self.hooked_location_moved = False # flag to indicate when the hooking location started moving.
self.prev_force_mag = np.linalg.norm(self.robot.get_wrist_force(arm))
self.slip_count = 0
self.started_pulling_on_handle = False
self.started_pulling_on_handle_count = 0
ee_pos, _ = self.robot.get_ee_jtt(arm)
self.cx_start = ee_pos[0,0]
self.rad = 10.0
self.cy_start = ee_pos[1,0]-self.rad
self.cz_start = ee_pos[2,0]
cep, _ = self.robot.get_cep_jtt(arm)
arg_list = [arm, cep, cep_vel]
result, _ = self.epc_motion(self.cep_gen_control_radial_force,
0.1, arm, arg_list, self.log_state,
#0.01, arm, arg_list,
control_function = self.robot.set_cep_jtt)
print 'EPC motion result:', result
print 'Original force threshold:', force_threshold
print 'Adapted force threshold:', self.eq_force_threshold
print 'Adapted ftan threshold:', self.ftan_threshold
d = {
'f_list': self.f_list, 'ee_list': self.ee_list,
'cep_list': self.cep_list, 'ftan_list': self.ft.tangential_force,
'config_list': self.ft.configuration, 'frad_list': self.ft.radial_force,
'f_list_ati': self.f_list_ati,
'f_list_estimate': self.f_list_estimate,
'f_list_torques': self.f_list_torques
}
ut.save_pickle(d,'pr2_pull_'+ut.formatted_time()+'.pkl')
def search_and_hook(self, arm, hook_loc, hooking_force_threshold = 5.,
hit_threshold=15., hit_motions = 1,
hook_direction = 'left'):
# this needs to be debugged. Hardcoded for now.
#if arm == 'right_arm' or arm == 0:
# hook_dir = np.matrix([0., 1., 0.]).T # hook direc in home position
# offset = -0.03
#elif arm == 'left_arm' or arm == 1:
# hook_dir = np.matrix([0., -1., 0.]).T # hook direc in home position
# offset = -0.03
#else:
# raise RuntimeError('Unknown arm: %s', arm)
#start_loc = hook_loc + rot_mat.T * hook_dir * offset
if hook_direction == 'left':
offset = np.matrix([0., -0.03, 0.]).T
move_dir = np.matrix([0., 1., 0.]).T
elif hook_direction == 'up':
offset = np.matrix([0., 0., -0.03]).T
move_dir = np.matrix([0., 0., 1.]).T
start_loc = hook_loc + offset
# vector normal to surface and pointing into the surface.
normal_tl = np.matrix([1.0, 0., 0.]).T
pt1 = start_loc - normal_tl * 0.1
self.robot.go_cep_jtt(arm, pt1)
raw_input('Hit ENTER to go')
vec = normal_tl * 0.2
rospy.sleep(1.)
for i in range(hit_motions):
s = self.move_till_hit(arm, vec=vec, force_threshold=hit_threshold, speed=0.07)
cep_start, _ = self.robot.get_cep_jtt(arm)
cep = copy.copy(cep_start)
arg_list = [arm, move_dir, hooking_force_threshold, cep, cep_start]
print 'Hi there.'
s = self.epc_motion(self.cep_gen_surface_follow, 0.1, arm,
arg_list, control_function = self.robot.set_cep_jtt)
print 'result:', s
return s
if __name__ == '__main__':
import pr2_arms as pa
rospy.init_node('epc_pr2', anonymous = True)
rospy.logout('epc_pr2: ready')
#pr2_arms = pa.PR2Arms(primary_ft_sensor='ati')
pr2_arms = pa.PR2Arms(primary_ft_sensor='estimate')
door_epc = Door_EPC(pr2_arms)
r_arm, l_arm = 0, 1
arm = r_arm
tip = np.matrix([0.35, 0., 0.]).T
pr2_arms.arms.set_tooltip(arm, tip)
raw_input('Hit ENTER to close')
pr2_arms.close_gripper(arm, effort=80)
raw_input('Hit ENTER to start Door Opening')
# for cabinets.
#p1 = np.matrix([0.8, -0.40, -0.04]).T # pos 3
#p1 = np.matrix([0.8, -0.10, -0.04]).T # pos 2
p1 = np.matrix([0.8, -0.35, 0.1]).T # pos 1
door_epc.search_and_hook(arm, p1, hook_direction='left')
door_epc.pull(arm, force_threshold=40., cep_vel=0.05)
# # hrl toolchest drawer.
# p1 = np.matrix([0.8, -0.2, -0.17]).T
# door_epc.search_and_hook(arm, p1, hook_direction='up')
# door_epc.pull(arm, force_threshold=40., cep_vel=0.05)
| [
[
1,
0,
0.0052,
0.0026,
0,
0.66,
0,
954,
0,
2,
0,
0,
954,
0,
0
],
[
1,
0,
0.0078,
0.0026,
0,
0.66,
0.0667,
739,
0,
1,
0,
0,
739,
0,
0
],
[
1,
0,
0.0104,
0.0026,
0,
... | [
"import numpy as np, math",
"import copy",
"from threading import RLock",
"import roslib; roslib.load_manifest('hrl_pr2_door_opening')",
"import roslib; roslib.load_manifest('hrl_pr2_door_opening')",
"roslib.load_manifest('equilibrium_point_control')",
"import rospy",
"from equilibrium_point_control.m... |
#!/usr/bin/python
import numpy as np, math
import copy
from threading import RLock
import roslib; roslib.load_manifest('hrl_pr2_door_opening')
import rospy
from hrl_msgs.msg import FloatArray
from geometry_msgs.msg import Twist
def ft_cb(data):
lock.acquire()
ft_val[0] = data.linear.x
ft_val[1] = data.linear.y
ft_val[2] = data.linear.z
ft_val[3] = data.angular.x
ft_val[4] = data.angular.y
ft_val[5] = data.angular.z
lock.release()
if __name__ == '__main__':
lock = RLock()
ft_val = [0.] * 6
pub = rospy.Subscriber('/r_cart/state/wrench', Twist, ft_cb)
pub = rospy.Publisher('/force_torque_ft2_estimate', FloatArray)
rospy.init_node('ati_ft_emulator')
rospy.loginfo('Started the ATI FT emulator.')
rt = rospy.Rate(100)
while not rospy.is_shutdown():
lock.acquire()
send_ft_val = copy.copy(ft_val)
lock.release()
fa = FloatArray(rospy.Header(stamp=rospy.Time.now()), send_ft_val)
pub.publish(fa)
rt.sleep()
| [
[
1,
0,
0.0769,
0.0256,
0,
0.66,
0,
954,
0,
2,
0,
0,
954,
0,
0
],
[
1,
0,
0.1026,
0.0256,
0,
0.66,
0.1111,
739,
0,
1,
0,
0,
739,
0,
0
],
[
1,
0,
0.1282,
0.0256,
0,
... | [
"import numpy as np, math",
"import copy",
"from threading import RLock",
"import roslib; roslib.load_manifest('hrl_pr2_door_opening')",
"import roslib; roslib.load_manifest('hrl_pr2_door_opening')",
"import rospy",
"from hrl_msgs.msg import FloatArray",
"from geometry_msgs.msg import Twist",
"def f... |
import roslib
roslib.load_manifest('rospy')
roslib.load_manifest('visualization_msgs')
import rospy
from visualization_msgs.msg import Marker
import numpy as np
class SceneDraw:
def __init__(self, topic='contact_visualization', node='contact_sim', frame='/world_frame'):
self.pub = rospy.Publisher(topic+'_marker', Marker)
self.frame = frame
self.Marker = Marker
def pub_body(self, pos, quat, scale, color, num, shape, text = ''):
marker = Marker()
marker.header.frame_id = self.frame
marker.header.stamp = rospy.Time.now()
marker.ns = "basic_shapes"
marker.id = num
marker.type = shape
marker.action = Marker.ADD
marker.pose.position.x = pos[0]
marker.pose.position.y = pos[1]
marker.pose.position.z = pos[2]
marker.pose.orientation.x = quat[0]
marker.pose.orientation.y = quat[1]
marker.pose.orientation.z = quat[2]
marker.pose.orientation.w = quat[3]
marker.scale.x = scale[0]
marker.scale.y = scale[1]
marker.scale.z = scale[2]
marker.color.r = color[0]
marker.color.g = color[1]
marker.color.b = color[2]
marker.color.a = color[3]
marker.lifetime = rospy.Duration()
marker.text = text
self.pub.publish(marker)
def get_rot_mat(self, rot):
# rot_mat = np.matrix([[rot[0], rot[3], rot[6]],[rot[1], rot[4], rot[7]], [rot[2], rot[5], rot[8]]])
rot_mat = np.matrix([[rot[0], rot[4], rot[8]],[rot[1], rot[5], rot[9]], [rot[2], rot[6], rot[10]]])
return rot_mat
| [
[
1,
0,
0.02,
0.02,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.04,
0.02,
0,
0.66,
0.1667,
630,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.06,
0.02,
0,
0.66,
0.33... | [
"import roslib",
"roslib.load_manifest('rospy')",
"roslib.load_manifest('visualization_msgs')",
"import rospy",
"from visualization_msgs.msg import Marker",
"import numpy as np",
"class SceneDraw:\n def __init__(self, topic='contact_visualization', node='contact_sim', frame='/world_frame'):\n ... |
#!/usr/bin/env python
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#Author: Marc Killpack
import roslib; roslib.load_manifest('pr2_playpen')
import rospy
from pr2_playpen.srv import *
from robotis.lib_robotis import *
class Play:
def __init__(self):
dyn = USB2Dynamixel_Device('/dev/ttyUSB0')
self.playpen = Robotis_Servo(dyn, 31)
self.conveyor = Robotis_Servo(dyn,32)
self.conveyor.init_cont_turn()
rospy.init_node('playpen_server')
s_play = rospy.Service('playpen', Playpen, self.move_playpen)
s_conv = rospy.Service('conveyor', Conveyor, self.move_conveyor)
rospy.spin()
def move_conveyor(self, data):
delt_time = abs(data.distance)/2.39/0.685/0.0483*2/0.75
if data.distance > 0:
self.conveyor.set_angvel(-5)
else:
self.conveyor.set_angvel(5)
rospy.sleep(delt_time)
self.conveyor.set_angvel(0)
print "move conveyor"
return ConveyorResponse(1)
def move_playpen(self, data):
if data.command == 0:
self.playpen.move_angle(0.28)
print "closing playpen"
elif data.command == 1:
self.playpen.move_angle(1.90)
print "opening playpen...releasing object"
return PlaypenResponse(1)
if __name__== "__main__":
go = Play()
| [
[
1,
0,
0.4444,
0.0139,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.4444,
0.0139,
0,
0.66,
0.1667,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.4583,
0.0139,
0,
0.... | [
"import roslib; roslib.load_manifest('pr2_playpen')",
"import roslib; roslib.load_manifest('pr2_playpen')",
"import rospy",
"from pr2_playpen.srv import *",
"from robotis.lib_robotis import *",
"class Play:\n\n def __init__(self):\n dyn = USB2Dynamixel_Device('/dev/ttyUSB0')\n self.plaype... |
#!/usr/bin/env python
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#Author: Marc Killpack
import os
import roslib
roslib.load_manifest('pr2_playpen')
roslib.load_manifest('tf_conversions')
import rospy
import math
import tf
import sys
import tf_conversions.posemath as pm
import numpy as np
from geometry_msgs.msg import Pose
if __name__ == '__main__':
rospy.init_node('playpen_calibration')
listener = tf.TransformListener()
trans_list = []
rot_list = []
rate = rospy.Rate(10.0)
while not rospy.is_shutdown():
try:
(trans, rot) = listener.lookupTransform(sys.argv[1], sys.argv[2], rospy.Time(0))
(trans2, rot2) = listener.lookupTransform(sys.argv[3], sys.argv[4], rospy.Time(0))
msg1 = Pose()
msg2 = Pose()
msg1.position.x, msg1.position.y, msg1.position.z = trans[0], trans[1], trans[2]
msg2.position.x, msg2.position.y, msg2.position.z = trans2[0], trans2[1], trans2[2]
msg1.orientation.x, msg1.orientation.y, msg1.orientation.z, msg1.orientation.w = rot[0], rot[1], rot[2], rot[3]
msg2.orientation.x, msg2.orientation.y, msg2.orientation.z, msg2.orientation.w = rot2[0], rot2[1], rot2[2], rot2[3]
(trans_tot, rot_tot) = pm.toTf(pm.fromMsg(msg1)*pm.fromMsg(msg2))
print "translation: ", trans_tot, ", rotation :", rot_tot
trans_list.append(trans_tot)
rot_list.append(rot_tot)
except (tf.LookupException, tf.ConnectivityException):
continue
rate.sleep()
trans_str = str(np.median(np.array(trans_list), axis = 0))
rot_str = str(np.median(np.array(rot_list), axis = 0))
print "median of translation :", trans_str
print "median of rotation :", rot_str
try:
os.remove('../../launch/kinect_playpen_to_torso_lift_link.launch')
except:
print 'no file to be removed, creating new file'
f = open('../../launch/kinect_playpen_to_torso_lift_link.launch', 'w')
f.write('<launch>\n')
############################################ I really need to verify the order of sys.arg[4] and sys.arg[1], this could be wrong!!! best way to check
############################################ is to transform something from argv[4] frame to argv[1] frame and check
f.write('<node pkg="tf" type="static_transform_publisher" name="kinect_playpen_to_pr2_lift_link" args=" '+trans_str[1:-1]+' '+rot_str[1:-1]+' '+sys.argv[1]+' '+sys.argv[4]+' 30" />\n')
f.write('</launch>')
f.close()
#run this to calibrate playpen, I should include it in a launch file with arguments and launching pr2_launch/ar_kinect and launch/ar_kinect
#./calibrate.py /torso_lift_link /calibration_pattern /calibration_pattern2 /openni_camera2
| [
[
1,
0,
0.3563,
0.0115,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.3678,
0.0115,
0,
0.66,
0.0909,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.3793,
0.0115,
0,
... | [
"import os",
"import roslib",
"roslib.load_manifest('pr2_playpen')",
"roslib.load_manifest('tf_conversions')",
"import rospy",
"import math",
"import tf",
"import sys",
"import tf_conversions.posemath as pm",
"import numpy as np",
"from geometry_msgs.msg import Pose",
"if __name__ == '__main__... |
#!/usr/bin/env python
import roslib
roslib.load_manifest('pr2_playpen')
import rospy
import hrl_pr2_lib.pressure_listener as pl
import cPickle
class PressureWriter:
def __init__(self):
rospy.init_node('pressure_writer')
self.r_grip_press = pl.PressureListener(topic='/pressure/r_gripper_motor')
self.l_grip_press = pl.PressureListener(topic='/pressure/l_gripper_motor')
self.r_grip_data = []
self.l_grip_data = []
self.status = None
def zero(self):
self.r_grip_press.rezero()
self.l_grip_press.rezero()
def record_pressures(self, file_name, arm, time = 10:)
file_handle = open(file_name, 'w')
self.zero()
start = rospy.get_time()
#might be better to do some condition, like gripper not moving or when arm is moved to side
#while rospy.get_time()-start < time:
while not self.status == 'moving somewhere again':
print "saving data now ..."
self.r_grip_data.append(self.r_grip_press.get_pressure_readings())
self.l_grip_data.append(self.l_grip_press.get_pressure_readings())
rospy.sleep(0.05)
cPickle.dump(data, file_handle)
file_handle.close()
def print_pressures(self):
self.r_grip_press.rezero()
right_tuple = self.r_grip_press.get_pressure_readings()
# print "here's the right gripper :\n", right_tuple
# print "here's the raw values : \n", self.r_grip_press.rmat_raw
def status_callback(self, data):
print "here is the status :", data
# self.status = data.feedback.state
self.status = data
if __name__ == '__main__':
pw = PressureWriter()
rospy.Subscriber('OverheadServer/actionlib/feedback/feedback/state', String, pw.status_callback)
while not rospy.is_shutdown():
if pw.status == 'closing gripper':
pw.record_pressures('test_file', 0)
rospy.sleep(0.02)
| [
[
1,
0,
0.037,
0.0185,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0556,
0.0185,
0,
0.66,
0.1667,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0741,
0.0185,
0,
0.6... | [
"import roslib",
"roslib.load_manifest('pr2_playpen')",
"import rospy",
"import hrl_pr2_lib.pressure_listener as pl",
"import cPickle",
"class PressureWriter:\n\n def __init__(self):\n rospy.init_node('pressure_writer')\n self.r_grip_press = pl.PressureListener(topic='/pressure/r_gripper_... |
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#Based on some code by Kaijen, modified heavily by Marc Killpack
import roslib
roslib.load_manifest('pr2_playpen')
import rospy
from pr2_playpen.pick_and_place_manager import *
from object_manipulator.convert_functions import *
from pr2_playpen.srv import Playpen
from pr2_playpen.srv import Conveyor
from pr2_playpen.srv import Check
from pr2_playpen.srv import Train
from UI_segment_object.srv import Save
import os
import datetime
import cPickle
import math
import numpy as np
class SimplePickAndPlaceExample():
def __init__(self):
rospy.loginfo("initializing pick and place manager")
self.papm = PickAndPlaceManager()
rospy.loginfo("finished initializing pick and place manager")
rospy.wait_for_service('playpen')
rospy.wait_for_service('conveyor')
self.playpen = rospy.ServiceProxy('playpen', Playpen)
self.conveyor = rospy.ServiceProxy('conveyor', Conveyor)
self.objects_dist = [.135, .26-.135, .405-.26, .545-.405,
.70-.545, .865-.70, .995-.865, 1.24-.995]
self.tries = 0
self.successes = 0
#pick up the nearest object to PointStamped target_point with whicharm
#(0=right, 1=left)
def pick_up_object_near_point(self, target_point, whicharm):
rospy.loginfo("moving the arms to the side")
self.papm.move_arm_out_of_way(0)
self.papm.move_arm_out_of_way(1)
#############once is it positioned, we don't want to move the head at all !!!#############
# rospy.loginfo("pointing the head at the target point")
# self.papm.point_head(get_xyz(target_point.point),
# target_point.header.frame_id)
#########################################################################################
rospy.loginfo("detecting the table and objects")
self.papm.call_tabletop_detection(take_static_collision_map = 1,
update_table = 1, clear_attached_objects = 1)
rospy.loginfo("picking up the nearest object to the target point")
success = self.papm.pick_up_object_near_point(target_point,
whicharm)
if success:
rospy.loginfo("pick-up was successful! Moving arm to side")
#self.papm.move_arm_to_side(whicharm)
self.papm.move_arm_out_of_way(whicharm)
else:
rospy.loginfo("pick-up failed.")
return success
#place the object held in whicharm (0=right, 1=left) down in the
#place rectangle defined by place_rect_dims (x,y)
#and place_rect_center (PoseStamped)
def place_object(self, whicharm, place_rect_dims, place_rect_center):
self.papm.set_place_area(place_rect_center, place_rect_dims)
rospy.loginfo("putting down the object in the %s gripper"\
%self.papm.arm_dict[whicharm])
success = self.papm.put_down_object(whicharm,
max_place_tries = 5,
use_place_override = 1)
if success:
rospy.loginfo("place returned success")
else:
rospy.loginfo("place returned failure")
self.papm.open_gripper(whicharm)
return success
if __name__ == "__main__":
rospy.init_node('simple_pick_and_place_example')
sppe = SimplePickAndPlaceExample()
#adjust for your table
table_height = 0.529
date = datetime.datetime.now()
f_name = date.strftime("%Y-%m-%d_%H-%M-%S")
save_dir = os.getcwd()+'/../../data/'+f_name
playpen_dir = '/home/mkillpack/svn/gt-ros-pkg/hrl/pr2_playpen/data/' #should add way to sync
os.mkdir(save_dir)
print "CHECING FOR DIRECTORY : ", os.getcwd()+'/../../data/'+f_name
#.5 m in front of robot, centered
target_point_xyz = [.625, 0, table_height] #this is currently an approximation/hack should use ar tag
target_point = create_point_stamped(target_point_xyz, 'base_link')
arm = 0
rospy.wait_for_service('playpen_train_success')
rospy.wait_for_service('playpen_check_success')
rospy.wait_for_service('playpen_save_pt_cloud')
rospy.wait_for_service('playpen_save_image')
# rospy.wait_for_service('pr2_save_pt_cloud')
try:
train_success = rospy.ServiceProxy('playpen_train_success', Train)
check_success = rospy.ServiceProxy('playpen_check_success', Check)
# save_pr2_cloud = rospy.ServiceProxy('pr2_save_pt_cloud', Save)
save_playpen_cloud = rospy.ServiceProxy('playpen_save_pt_cloud', Save)
save_playpen_image = rospy.ServiceProxy('playpen_save_image', Save)
except rospy.ServiceException, e:
print "Service call failed: %s"%e
num_samples = train_success()
for i in xrange(len(sppe.objects_dist)):
file_handle = open(save_dir+'/object'+str(i).zfill(3)+'.pkl', 'wb')
data = {}
sppe.playpen(0)
sppe.conveyor(sppe.objects_dist[i])
# data['object'+str(i).zfill(3)] = {}
# data['object'+str(i).zfill(3)]['success'] = []
# data['object'+str(i).zfill(3)]['frames'] = []
data['success'] = []
data['frames'] = []
while sppe.tries<6:
print "arm is ", arm
# print "target _point is ", target_point.x
# save_pr2_cloud(save_dir+'/object'+str(i).zfill(3)+'_try'+str(sppe.tries).zfill(3)+'_before_pr2.pcd')
save_playpen_cloud(playpen_dir+'object'+str(i).zfill(3)+'_try'+str(sppe.tries).zfill(3)+'_before_playpen.pcd')
save_playpen_image(playpen_dir+'object'+str(i).zfill(3)+'_try'+str(sppe.tries).zfill(3)+'_before_playpen.png')
success = sppe.pick_up_object_near_point(target_point, arm)
result = []
rospy.sleep(5)
for j in xrange(5):
result.append(check_success('').result)
rospy.sleep(5)
result.sort()
if result[2] == 'table':
success = True
elif result[2] == 'object':
success = False
# else:
# success = False
# sppe.tries = sppe.tries-1 # this is to compensate for failures in perception hopefully
print "SUCCESS IS :", success, ' ', result
data['success'].append(success)
# save_pr2_cloud(save_dir+'/object'+str(i).zfill(3)+'try'+str(sppe.tries).zfill(3)+'_after_pr2.pcd')
save_playpen_cloud(playpen_dir+'object'+str(i).zfill(3)+'_try'+str(sppe.tries).zfill(3)+'_after_playpen.pcd')
save_playpen_image(playpen_dir+'object'+str(i).zfill(3)+'_try'+str(sppe.tries).zfill(3)+'_after_playpen.png')
# save_playpen_cloud(save_dir+'/object'+str(i).zfill(3)+'try'+str(sppe.tries).zfill(3)+'_after_playpen.pcd')
if success:
sppe.successes=sppe.successes + 1
#square of size 30 cm by 30 cm
place_rect_dims = [.1, .1]
x = np.random.uniform(-0.18, 0.18, 1)[0]
y = np.random.uniform(-0.18, 0.18, 1)[0]
center_xyz = [.625+x, y, table_height+.10]
#aligned with axes of frame_id
center_quat = [0,0,0,1]
place_rect_center = create_pose_stamped(center_xyz+center_quat,
'base_link')
sppe.place_object(arm, place_rect_dims, place_rect_center)
arm = arm.__xor__(1)
sppe.tries = sppe.tries+1
sppe.playpen(1)
sppe.successes = 0
sppe.tries = 0
cPickle.dump(data, file_handle)
file_handle.close()
# sppe.playpen(0)
| [
[
1,
0,
0.0175,
0.0175,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
1,
0,
0.0351,
0.0175,
0,
0.66,
0.0714,
164,
0,
1,
0,
0,
164,
0,
0
],
[
1,
0,
0.0526,
0.0175,
0,
... | [
"import roslib",
"import rospy",
"from pr2_playpen.pick_and_place_manager import *",
"from object_manipulator.convert_functions import *",
"from pr2_playpen.srv import Playpen",
"from pr2_playpen.srv import Conveyor",
"from pr2_playpen.srv import Check",
"from pr2_playpen.srv import Train",
"from UI... |
#! /usr/bin/python
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#Based on some code by Kaijen, modified heavily by Marc Killpack
import roslib
roslib.load_manifest('pr2_playpen')
roslib.load_manifest('pr2_grasp_behaviors')
import rospy
import actionlib
import hrl_pr2_lib.pressure_listener as pl
from object_manipulator.convert_functions import *
from pr2_playpen.srv import Playpen
from pr2_playpen.srv import Conveyor
from pr2_playpen.srv import Check
from pr2_playpen.srv import Train
from UI_segment_object.srv import Save
#from pr2_overhead_grasping.msg import *
from pr2_grasp_behaviors.msg import *
import os
import datetime
import cPickle
import math
import numpy as np
class HRLControllerPlaypen():
def __init__(self):
print "waiting for conveyor"
rospy.wait_for_service('playpen')
rospy.wait_for_service('conveyor')
print "started conveyor and playpen"
self.playpen = rospy.ServiceProxy('playpen', Playpen)
self.conveyor = rospy.ServiceProxy('conveyor', Conveyor)
self.objects_dist = [0.13, 0.13, 0.13, 0.13, 0.13, 0.13, 0.13,
0.13, 0.13, 0.13]
self.tries = 0
self.successes = 0
self.r_grip_press = pl.PressureListener(topic='/pressure/r_gripper_motor')
self.l_grip_press = pl.PressureListener(topic='/pressure/l_gripper_motor')
self.grasp_client = [None, None]
self.grasp_setup_client = [None, None]
self.grasp_client[0] = actionlib.SimpleActionClient('r_overhead_grasp', OverheadGraspAction)
self.grasp_client[0].wait_for_server()
self.grasp_setup_client[0] = actionlib.SimpleActionClient('r_overhead_grasp_setup', OverheadGraspSetupAction)
self.grasp_setup_client[0].wait_for_server()
self.grasp_client[1] = actionlib.SimpleActionClient('l_overhead_grasp', OverheadGraspAction)
self.grasp_client[1].wait_for_server()
self.grasp_setup_client[1] = actionlib.SimpleActionClient('l_overhead_grasp_setup', OverheadGraspSetupAction)
self.grasp_setup_client[1].wait_for_server()
def move_to_side(self, whicharm, open_gripper=False):
rospy.loginfo("moving the arms to the side")
setup_goal = OverheadGraspSetupGoal()
setup_goal.disable_head = True
setup_goal.open_gripper = open_gripper
self.grasp_setup_client[whicharm].send_goal(setup_goal)
self.grasp_setup_client[whicharm].wait_for_result()
#pick up the nearest object to PointStamped target_point with whicharm
#(0=right, 1=left)
def pick_up_object_near_point(self, target_point, whicharm):
self.move_to_side(whicharm, False)
#############once is it positioned, we don't want to move the head at all !!!#############
# rospy.loginfo("pointing the head at the target point")
# self.papm.point_head(get_xyz(target_point.point),
# target_point.header.frame_id)
#########################################################################################
rospy.loginfo("picking up the nearest object to the target point")
############################################################
# Creating grasp grasp_goal
grasp_goal = OverheadGraspGoal()
grasp_goal.is_grasp = True
grasp_goal.disable_head = True
grasp_goal.disable_coll = False
grasp_goal.grasp_type=OverheadGraspGoal.VISION_GRASP
grasp_goal.grasp_params = [0] * 3
grasp_goal.grasp_params[0] = target_point.point.x
grasp_goal.grasp_params[1] = target_point.point.y
grasp_goal.behavior_name = "overhead_grasp"
grasp_goal.sig_level = 0.999
############################################################
self.grasp_client[whicharm].send_goal(grasp_goal)
self.grasp_client[whicharm].wait_for_result()
result = self.grasp_client[whicharm].get_result()
success = (result.grasp_result == "Object grasped")
if success:
rospy.loginfo("pick-up was successful! Moving arm to side")
resetup_goal = OverheadGraspSetupGoal()
resetup_goal.disable_head = True
self.grasp_setup_client[whicharm].send_goal(resetup_goal)
self.grasp_setup_client[whicharm].wait_for_result()
else:
rospy.loginfo("pick-up failed.")
return success
#place the object held in whicharm (0=right, 1=left) down in the
#place rectangle defined by place_rect_dims (x,y)
#and place_rect_center (PoseStamped)
def place_object(self, whicharm, place_rect_dims, place_rect_center):
rospy.loginfo("putting down the object in the r gripper")
############################################################
# Creating place goal
grasp_goal = OverheadGraspGoal()
grasp_goal.is_grasp = False
grasp_goal.disable_head = True
grasp_goal.disable_coll = False
grasp_goal.grasp_type=OverheadGraspGoal.MANUAL_GRASP
grasp_goal.grasp_params = [0] * 3
grasp_goal.grasp_params[0] = place_rect_center.pose.position.x
grasp_goal.grasp_params[1] = place_rect_center.pose.position.y
grasp_goal.behavior_name = "overhead_grasp"
grasp_goal.sig_level = 0.999
############################################################
self.grasp_client[whicharm].send_goal(grasp_goal)
self.grasp_client[whicharm].wait_for_result()
result = self.grasp_client[whicharm].get_result()
success = (result.grasp_result == "Object placed")
if success:
rospy.loginfo("place returned success")
else:
rospy.loginfo("place returned failure")
return success
if __name__ == "__main__":
import optparse
p = optparse.OptionParser()
p.add_option('--path', action='store', dest='path_save',type='string',
default=None, help='this is path to directory for saving files')
opt, args = p.parse_args()
rospy.init_node('simple_pick_and_place_example')
hcp = HRLControllerPlaypen()
#adjust for your table
table_height = 0.529
date = datetime.datetime.now()
f_name = date.strftime("%Y-%m-%d_%H-%M-%S")
if opt.path_save == None:
print "Not logging or saving data from playpen"
SAVE = False
else:
save_dir = opt.path_save+f_name
print "Logging and saving playpen data in :", save_dir
SAVE = True
if SAVE == True:
os.mkdir(save_dir)
#print "CHECING FOR DIRECTORY : ", os.getcwd()+'/../../data/'+f_name
#.5 m in front of robot, centered
target_point_xyz = [.625, 0, table_height] #this is currently an approximation/hack should use ar tag
target_point = create_point_stamped(target_point_xyz, 'base_link')
arm = 0
rospy.wait_for_service('playpen_train')
rospy.wait_for_service('playpen_check_success')
if SAVE == True:
# rospy.wait_for_service('playpen_save_pt_cloud')
# rospy.wait_for_service('playpen_save_image')
rospy.wait_for_service('pr2_save_pt_cloud')
rospy.wait_for_service('pr2_save_image')
try:
train = rospy.ServiceProxy('playpen_train', Train)
check_success = rospy.ServiceProxy('playpen_check_success', Check)
if SAVE == True:
save_pr2_cloud = rospy.ServiceProxy('pr2_save_pt_cloud', Save)
save_pr2_image = rospy.ServiceProxy('pr2_save_image', Save)
# save_playpen_cloud = rospy.ServiceProxy('playpen_save_pt_cloud', Save)
# save_playpen_image = rospy.ServiceProxy('playpen_save_image', Save)
except rospy.ServiceException, e:
print "Service call failed: %s"%e
print "moving arms to side"
hcp.move_to_side(0, False)
hcp.move_to_side(1, False)
print "done moving arms, sleeping ..."
rospy.sleep(15)
print "done sleeping, now training for table top"
num_samples = train('table')
for i in xrange(len(hcp.objects_dist)):
try:
if SAVE==True:
file_handle = open(save_dir+'/object'+str(i).zfill(3)+'.pkl', 'w')
data = {}
hcp.playpen(0)
hcp.conveyor(hcp.objects_dist[i])
data['success'] = []
data['frames'] = []
data['pressure'] = {}
data['pressure']['which_arm'] = []
data['pressure']['data'] = []
start_time = rospy.get_time()
# while hcp.tries<3:
while rospy.get_time()-start_time < 100.0:
print "arm is ", arm
hcp.move_to_side(arm, True)
rospy.sleep(7)
if SAVE == True:
save_pr2_cloud(save_dir+'/object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_before_pr2.pcd')
save_pr2_image(save_dir+'/object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_before_pr2.png')
# save_playpen_cloud(playpen_dir+'object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_before_playpen.pcd')
# save_playpen_image(playpen_dir+'object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_before_playpen.png')
num_samples = train('object')
print "attempting to pick up the object"
success = hcp.pick_up_object_near_point(target_point, arm)
print "starting to move arm to side at :", rospy.get_time()
hcp.move_to_side(arm, False)
print "moved past move to side arm command at :", rospy.get_time()
results = []
print "sleeping for 10 seconds, is this necessary ..."
rospy.sleep(10)
num_samples = 7
for j in xrange(num_samples):
results.append(check_success('').result)
results.sort()
print "results are :", results
print "index into result is :", int(num_samples/2)
if results[int(num_samples/2)] == 'table':
success = True
data['success'].append(success)
elif results[int(num_samples/2)] == 'object':
success = False
data['success'].append(success)
else:
success = None
#hcp.tries = hcp.tries-1 # this is to compensate for failures in perception hopefully
print "SUCCESS IS :", success
if SAVE == True:
save_pr2_cloud(save_dir+'/object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_after_pr2.pcd')
save_pr2_image(save_dir+'/object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_after_pr2.png')
# save_playpen_cloud(playpen_dir+'object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_after_playpen.pcd')
# save_playpen_image(playpen_dir+'object'+str(i).zfill(3)+'_try'+str(hcp.tries).zfill(3)+'_after_playpen.png')
if success:
hcp.successes=hcp.successes + 1
#square of size 30 cm by 30 cm
place_rect_dims = [.1, .1]
inside = False
while inside == False:
x = np.random.uniform(-0.18, 0.18, 1)[0]
y = np.random.uniform(-0.18, 0.18, 1)[0]
if math.sqrt(x*x+y*y) <= 0.18:
inside = True
center_xyz = [.625+x, y, table_height+.10]
#aligned with axes of frame_id
center_quat = [0,0,0,1]
place_rect_center = create_pose_stamped(center_xyz+center_quat,
'base_link')
hcp.place_object(arm, place_rect_dims, place_rect_center)
hcp.move_to_side(arm, True)
arm = arm.__xor__(1)
hcp.tries = hcp.tries+1
hcp.playpen(1)
hcp.successes = 0
hcp.tries = 0
cPickle.dump(data, file_handle)
file_handle.close()
hcp.playpen(0)
except:
print "failed for object"
| [
[
1,
0,
0.0083,
0.0083,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
1,
0,
0.0167,
0.0083,
0,
0.66,
0.0625,
164,
0,
1,
0,
0,
164,
0,
0
],
[
1,
0,
0.025,
0.0083,
0,
0... | [
"import roslib",
"import rospy",
"import actionlib",
"import hrl_pr2_lib.pressure_listener as pl",
"from object_manipulator.convert_functions import *",
"from pr2_playpen.srv import Playpen",
"from pr2_playpen.srv import Conveyor",
"from pr2_playpen.srv import Check",
"from pr2_playpen.srv import Tr... |
#!/usr/bin/env python
# Calculating and displaying 2D Hue-Saturation histogram of a color image
import roslib
roslib.load_manifest('opencv2')
import sys
import cv
cv.NamedWindow("back_projection", cv.CV_WINDOW_AUTOSIZE)
cv.NamedWindow("back_modified", cv.CV_WINDOW_AUTOSIZE)
cv.NamedWindow("back_modified2", cv.CV_WINDOW_AUTOSIZE)
def hs_histogram(src, patch):
# Convert to HSV
hsv = cv.CreateImage(cv.GetSize(src), 8, 3)
cv.CvtColor(src, hsv, cv.CV_BGR2HSV)
hsv_patch= cv.CreateImage(cv.GetSize(patch), 8, 3)
# Extract the H and S planes
h_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1)
h_plane_img = cv.CreateImage(cv.GetSize(src), 8, 1)
h_plane_patch = cv.CreateMat(patch.rows, patch.cols, cv.CV_8UC1)
s_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1)
s_plane_img = cv.CreateImage(cv.GetSize(src), 8, 1)
s_plane_patch = cv.CreateMat(patch.rows, patch.cols, cv.CV_8UC1)
v_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1)
cv.Split(hsv, h_plane, s_plane, v_plane, None)
cv.Split(hsv, h_plane_img, s_plane_img, None, None)
cv.Split(hsv_patch, h_plane_patch, s_plane_patch, None, None)
#cv.Split(src, h_plane, s_plane, v_plane, None)
planes = [h_plane_patch, s_plane_patch]#, s_plane, v_plane]
h_bins = 30
s_bins = 32
v_bins = 30
hist_size = [h_bins, s_bins]
# hue varies from 0 (~0 deg red) to 180 (~360 deg red again */
h_ranges = [0, 180]
# saturation varies from 0 (black-gray-white) to
# 255 (pure spectrum color)
s_ranges = [0, 255]
v_ranges = [0, 255]
ranges = [h_ranges, s_ranges]#, s_ranges, v_ranges]
scale = 10
hist = cv.CreateHist([h_bins, s_bins], cv.CV_HIST_ARRAY, ranges, 1)
cv.CalcHist([cv.GetImage(i) for i in planes], hist)
(_, max_value, _, _) = cv.GetMinMaxHistValue(hist)
hist_img = cv.CreateImage((h_bins*scale, s_bins*scale), 8, 3)
back_proj_img = cv.CreateImage(cv.GetSize(src), 8, 1)
cv.CalcBackProject([h_plane_img, s_plane_img], back_proj_img, hist)
# for h in range(h_bins):
# for s in range(s_bins):
# bin_val = cv.QueryHistValue_2D(hist, h, s)
# intensity = cv.Round(bin_val * 255 / max_value)
# cv.Rectangle(hist_img,
# (h*scale, s*scale),
# ((h+1)*scale - 1, (s+1)*scale - 1),
# cv.RGB(intensity, intensity, intensity),
# cv.CV_FILLED)
return back_proj_img, hist
def back_project_hs(src, patch):
# Convert to HSV
hsv = cv.CreateImage(cv.GetSize(src), 8, 3)
cv.CvtColor(src, hsv, cv.CV_BGR2HSV)
hsv_patch= cv.CreateImage(cv.GetSize(patch), 8, 3)
cv.CvtColor(patch, hsv_patch, cv.CV_BGR2HSV)
# Extract the H and S planes
h_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1)
h_plane_img = cv.CreateImage(cv.GetSize(src), 8, 1)
h_plane_patch = cv.CreateMat(patch.rows, patch.cols, cv.CV_8UC1)
s_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1)
s_plane_img = cv.CreateImage(cv.GetSize(src), 8, 1)
s_plane_patch = cv.CreateMat(patch.rows, patch.cols, cv.CV_8UC1)
v_plane = cv.CreateMat(src.rows, src.cols, cv.CV_8UC1)
cv.Split(hsv, h_plane, s_plane, v_plane, None)
cv.Split(hsv, h_plane_img, s_plane_img, None, None)
cv.Split(hsv_patch, h_plane_patch, s_plane_patch, None, None)
#cv.Split(src, h_plane, s_plane, v_plane, None)
planes = [h_plane_patch, s_plane_patch]#, s_plane, v_plane]
# planes = [s_plane_patch]#, s_plane, v_plane]
h_bins = 30
s_bins = 32
hist_size = [h_bins, s_bins]
# hue varies from 0 (~0 deg red) to 180 (~360 deg red again */
h_ranges = [0, 180]
s_ranges = [0, 255]
# saturation varies from 0 (black-gray-white) to
# 255 (pure spectrum color)
ranges = [h_ranges, s_ranges]#, s_ranges, v_ranges]
#ranges = [s_ranges]#, s_ranges, v_ranges]
scale = 1
hist = cv.CreateHist([h_bins, s_bins], cv.CV_HIST_ARRAY, ranges, 1)
#hist = cv.CreateHist([s_bins], cv.CV_HIST_ARRAY, ranges, 1)
cv.CalcHist([cv.GetImage(i) for i in planes], hist)
(min_value, max_value, _, _) = cv.GetMinMaxHistValue(hist)
#cv.NormalizeHist(hist, 20*250.0)
print "min hist value is :", min_value
print "max hist value is :", max_value
back_proj_img = cv.CreateImage(cv.GetSize(src), 8, 1)
#cv.NormalizeHist(hist, 2000)
cv.CalcBackProject([h_plane_img, s_plane_img], back_proj_img, hist)
back_modified = cv.CreateImage(cv.GetSize(src), 8, 1)
back_modified2 = cv.CreateImage(cv.GetSize(src), 8, 1)
# cv.Dilate(back_proj_img, back_proj_img)
# cv.Erode(back_proj_img, back_proj_img)
#cv.Smooth(back_proj_img, back_modified)
#cv.AdaptiveThreshold(back_proj_img, back_modified, 255, adaptive_method=cv.CV_ADAPTIVE_THRESH_GAUSSIAN_C)
#cv.Threshold(back_proj_img, back_modified, 250, 255, cv.CV_THRESH_BINARY)
#cv.MorphologyEx(back_modified,back_modified2, None, None, cv.CV_MOP_CLOSE, 3)
#cv.MorphologyEx(back_modified,back_modified2, None, None, cv.CV_MOP_CLOSE, 1)
# cv.MorphologyEx(back_proj_img,back_modified2, None, None, cv.CV_MOP_CLOSE, 1)
#cv.MorphologyEx(back_modified2,back_modified2, None, None, cv.CV_MOP_OPEN, 2)
cv.MorphologyEx(back_proj_img,back_modified, None, None, cv.CV_MOP_OPEN, 1)
cv.MorphologyEx(back_modified,back_modified, None, None, cv.CV_MOP_CLOSE, 2)
cv.Threshold(back_modified, back_modified, 250, 255, cv.CV_THRESH_BINARY)
# cv.MorphologyEx(back_proj_img,back_modified2, None, None, cv.CV_MOP_CLOSE, 1)
# cv.MorphologyEx(back_modified2,back_modified2, None, None, cv.CV_MOP_OPEN, 2)
#cv.FloodFill(back_modified, (320, 240), cv.Scalar(255), cv.Scalar(30), cv.Scalar(30), flags=8)
# for i in xrange (10):
# cv.MorphologyEx(back_modified,back_modified, None, None, cv.CV_MOP_OPEN, 3)
# cv.MorphologyEx(back_modified,back_modified, None, None, cv.CV_MOP_CLOSE, 1)
#cv.SubRS(back_modified, 255, back_modified)
# cv.CalcBackProject([s_plane_img], back_proj_img, hist)
# cv.Scale(back_proj_img, back_proj_img, 30000)
cv.ShowImage("back_projection", back_proj_img)
cv.ShowImage("back_modified", back_modified)
cv.ShowImage("back_modified2", back_modified2)
cv.WaitKey(0)
#return back_proj_img, hist
return back_modified, hist
#return , hist
if __name__ == '__main__':
folder = sys.argv[1]
cv.NamedWindow("Source", cv.CV_WINDOW_AUTOSIZE)
cv.NamedWindow("final", cv.CV_WINDOW_AUTOSIZE)
src2 = cv.LoadImageM(folder+'object'+str(0).zfill(3)+'_try'+str(0).zfill(3)+'_after_pr2.png')
patch_images = []
avg_noise = cv.CreateImage(cv.GetSize(src2), 8, 1)
cv.Zero(avg_noise)
for k in xrange(1):
patch_images.append(cv.LoadImageM('/home/mkillpack/Desktop/patch2.png'))
#for i in [4]:
for i in xrange(9):
for j in xrange(100):
print folder+'object'+str(i).zfill(3)+'_try'+str(j).zfill(3)+'_after_pr2.png'
src = cv.LoadImageM(folder+'object'+str(i).zfill(3)+'_try'+str(j).zfill(3)+'_after_pr2.png')
cv.ShowImage("Source", src)
back_proj_img, hist1 = back_project_hs(src, patch_images[0])
back_proj_img2, hist2 = back_project_hs(src2, patch_images[0])
scratch = cv.CreateImage(cv.GetSize(back_proj_img2), 8, 1)
scratch2 = cv.CreateImage(cv.GetSize(back_proj_img2), 8, 1)
# do something clever with ands ors and diffs
cv.Zero(scratch)
cv.Zero(scratch2)
#idea is to have a background model from back_proj_img2, or at least an emtpy single shot
###cv.Sub(back_proj_img, back_proj_img2, scratch)
#cv.SubRS(back_proj_img, 255, scratch)
###cv.SubRS(back_proj_img2, 255, scratch2)
#cv.Sub(back_proj_img, back_proj_img2, scratch2) #opposite noise, but excludes object
cv.Sub(back_proj_img2, back_proj_img, scratch2) #noise, but includes object if failed,
#would need to learn before then update selectively
#Maybe want both added in the end.
cv.Sub(scratch2, avg_noise, scratch)
cv.Or(avg_noise, scratch2, avg_noise)
##adding this part fills in wherever the object has been too, heatmaps?
#cv.Sub(back_proj_img2, back_proj_img, scratch)
#cv.Or(avg_noise, scratch, avg_noise)
#
#cv.Sub(back_proj_img2, avg_noise, back_proj_img2)
#cv.Sub(scratch,, back_proj_img2)
cv.ShowImage("final", scratch)
#cv.Sub(scratch, avg_noise, scratch2)
#cv.And(scratch, back_proj_img2, scratch2)
#cv.SubRS(scratch2, 255, scratch)
#cv.ShowImage("final", back_proj_img)
print cv.CompareHist(hist1, hist2, cv.CV_COMP_BHATTACHARYYA)
#making a mask
#mask = cv.CreateImage(cv.GetSize(back_proj_img2), 8, 1)
#cv.SubRS(back_proj_img2, 255, back_proj_img2)
#cv.SubRS(back_proj_img, 255, back_proj_img, mask=back_proj_img2)
#cv.SubRS(back_proj_img, 255, back_proj_img)
#cv.MorphologyEx(back_proj_img,back_proj_img, None, None, cv.CV_MOP_OPEN, 8)
#cv.MorphologyEx(back_proj_img,back_proj_img, None, None, cv.CV_MOP_CLOSE, 8)
#cv.ShowImage("back_projection", back_proj_img2)
#cv.WaitKey(0)
cv.Scale(back_proj_img, back_proj_img, 1/255.0)
print "here's the sum :", cv.Sum(scratch2)
| [
[
1,
0,
0.0126,
0.0042,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0167,
0.0042,
0,
0.66,
0.1111,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0209,
0.0042,
0,
0.... | [
"import roslib",
"roslib.load_manifest('opencv2')",
"import sys",
"import cv",
"cv.NamedWindow(\"back_projection\", cv.CV_WINDOW_AUTOSIZE)",
"cv.NamedWindow(\"back_modified\", cv.CV_WINDOW_AUTOSIZE)",
"cv.NamedWindow(\"back_modified2\", cv.CV_WINDOW_AUTOSIZE)",
"def hs_histogram(src, patch):\n # Co... |
#!/usr/bin/env python
# Calculating and displaying 2D Hue-Saturation histogram of a color image
import roslib
roslib.load_manifest('opencv2')
import sys
import cv
import numpy as np
from collections import deque
cv.NamedWindow("avg_noise", cv.CV_WINDOW_AUTOSIZE)
cv.NamedWindow("back_modified", cv.CV_WINDOW_AUTOSIZE)
cv.NamedWindow("back_modified2", cv.CV_WINDOW_AUTOSIZE)
class HistAnalyzer:
def __init__(self, background_noise, mask):
self.background_noise = background_noise
self.h_bins = 30
self.s_bins = 32
self.h_ranges = [0, 180]
self.s_ranges = [0, 255]
self.ranges = [self.h_ranges, self.s_ranges]
self.hist = None
self.mask = mask
self.avg_noise = None
def calc_hist(self):
self.hist = cv.CreateHist([self.h_bins, self.s_bins], cv.CV_HIST_ARRAY, self.ranges, 1)
hsv = cv.CreateImage(cv.GetSize(self.background_noise[0]), 8, 3)
h_plane = cv.CreateMat(self.background_noise[0].height, self.background_noise[0].width, cv.CV_8UC1)
s_plane = cv.CreateMat(self.background_noise[0].height, self.background_noise[0].width, cv.CV_8UC1)
for i in xrange(len(self.background_noise)):
cv.CvtColor(self.background_noise[i], hsv, cv.CV_BGR2HSV)
cv.Split(hsv, h_plane, s_plane, None, None)
planes = [h_plane, s_plane]#, s_plane, v_plane]
cv.CalcHist([cv.GetImage(i) for i in planes], self.hist, True, self.mask)
#cv.NormalizeHist(self.hist, 1.0)
def check_for_hist(self):
if self.hist == None:
print "YOU CAN'T CALCULATE NOISE WITH HIST MODEL OF TABLETOP"
exit
def calc_noise(self):
self.check_for_hist()
self.avg_noise = cv.CreateImage(cv.GetSize(self.background_noise[0]), 8, 1)
cv.Zero(self.avg_noise)
for i in xrange(len(self.background_noise)-1):
back_proj_img1, hist1 = self.back_project_hs(self.background_noise[i])
back_proj_img2, hist2 = self.back_project_hs(self.background_noise[i+1])
scratch = cv.CreateImage(cv.GetSize(back_proj_img2), 8, 1)
scratch2 = cv.CreateImage(cv.GetSize(back_proj_img2), 8, 1)
# do something clever with ands ors and diffs
cv.Zero(scratch)
cv.Zero(scratch2)
cv.Sub(back_proj_img2, back_proj_img1, scratch2) #noise, but includes object if failed,
cv.Sub(scratch2, self.avg_noise, scratch)
cv.Or(self.avg_noise, scratch2, self.avg_noise)
cv.WaitKey(100)
def compare_imgs(self, img1, img2):
back_proj_img, hist1 = self.back_project_hs(img1)
back_proj_img2, hist2 = self.back_project_hs(img2)
scratch = cv.CreateImage(cv.GetSize(back_proj_img2), 8, 1)
scratch2 = cv.CreateImage(cv.GetSize(back_proj_img2), 8, 1)
cv.Zero(scratch)
cv.Zero(scratch2)
#cv.Sub(back_proj_img, back_proj_img2, scratch2) #opposite noise, but excludes object
cv.Sub(back_proj_img2, back_proj_img, scratch2) #noise, but includes object if failed,
cv.Sub(scratch2, ha.avg_noise, scratch)
return scratch
def back_project_hs(self, img):
self.check_for_hist()
hsv = cv.CreateImage(cv.GetSize(img), 8, 3)
scratch = cv.CreateImage(cv.GetSize(img), 8, 1)
back_proj_img = cv.CreateImage(cv.GetSize(img), 8, 1)
cv.CvtColor(img, hsv, cv.CV_BGR2HSV)
h_plane_img = cv.CreateImage(cv.GetSize(img), 8, 1)
s_plane_img = cv.CreateImage(cv.GetSize(img), 8, 1)
cv.Split(hsv, h_plane_img, s_plane_img, None, None)
cv.CalcBackProject([h_plane_img, s_plane_img], back_proj_img, self.hist)
cv.MorphologyEx(back_proj_img, back_proj_img, None, None, cv.CV_MOP_OPEN, 1)
cv.MorphologyEx(back_proj_img, back_proj_img, None, None, cv.CV_MOP_CLOSE, 2)
cv.Threshold(back_proj_img, back_proj_img, 250, 255, cv.CV_THRESH_BINARY)
return back_proj_img, self.hist
if __name__ == '__main__':
folder = sys.argv[1]+'/background_noise/'
background_noise = deque() #[]
cv.NamedWindow("Source", cv.CV_WINDOW_AUTOSIZE)
cv.NamedWindow("final", cv.CV_WINDOW_AUTOSIZE)
for i in xrange(130):
background_noise.append(cv.LoadImage(folder+'file'+str(i).zfill(3)+'.png'))
mask = cv.LoadImage(sys.argv[2], 0)
ha = HistAnalyzer(background_noise, mask)
ha.calc_hist()
ha.calc_noise()
back_sum_ls = deque() #[]
for i in xrange(130):
img = cv.LoadImage(folder+'file'+str(i).zfill(3)+'.png')
result = ha.compare_imgs(img, ha.background_noise[0])
back_sum_ls.append(float(cv.Sum(result)[0]))
avg = np.mean(back_sum_ls)
std = np.std(back_sum_ls)
print "avg and std are :", avg, std
n = 0
sum_val = 0
#test_sum_ls = []
for i in xrange(9):
for j in xrange(100):
#print sys.argv[1]+'/object'+str(i).zfill(3)+'_try'+str(j).zfill(3)
try:
img = cv.LoadImageM(sys.argv[1]+'/object'+str(i).zfill(3)+'_try'+str(j).zfill(3)+'_after_pr2.png')
#img = cv.LoadImageM(sys.argv[1]+'/object'+str(i).zfill(3)+'_try'+str(j).zfill(3)+'_before_pr2.png')
result = ha.compare_imgs(img, ha.background_noise[-1])
n = n+1
sum_val = sum_val + float(cv.Sum(result)[0])
#print "here's the sum :", cv.Sum(result)[0]
cv.ShowImage("Source", img)
cv.ShowImage("final", result)
cv.WaitKey(-1)
loc_sum = float(cv.Sum(result)[0])
#if loc_sum > avg-5*std and loc_sum < avg+5*std:
if loc_sum < avg+5*std:
print "success ! \t:", loc_sum, "\t compared to \t", avg, 5*std
#ha.background_noise.popleft()
#ha.background_noise.append(img)
else:
print "epic fail ! \t:", loc_sum, "\t compared to \t", avg, 5*std
except:
print "no file like that, probably outside of index range"
print "recalculating hist and noise..."
#ha.calc_hist()
#ha.calc_noise()
print "done!"
print "average error for objects present :", sum_val/n
| [
[
1,
0,
0.0186,
0.0062,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0248,
0.0062,
0,
0.66,
0.1,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0311,
0.0062,
0,
0.66,... | [
"import roslib",
"roslib.load_manifest('opencv2')",
"import sys",
"import cv",
"import numpy as np",
"from collections import deque",
"cv.NamedWindow(\"avg_noise\", cv.CV_WINDOW_AUTOSIZE)",
"cv.NamedWindow(\"back_modified\", cv.CV_WINDOW_AUTOSIZE)",
"cv.NamedWindow(\"back_modified2\", cv.CV_WINDOW_A... |
#!/usr/bin/env python
import roslib
roslib.load_manifest('pr2_playpen')
import rospy
import math
import tf
import numpy as np
import os
import sys
import cPickle as pkl
def is_topic_pub(topic):
flag = False
for item in rospy.get_published_topics():
for thing in item:
if topic in thing:
flag = True
else:
pass
return flag
def get_data(listener, rate):
right = False
left = False
dist_ls = []
time_ls = []
while is_topic_pub('/r_overhead_grasp/feedback') == False and is_topic_pub('/l_overhead_grasp/feedback') == False:
print "waiting for bag file"
rate.sleep()
if is_topic_pub('/r_overhead_grasp/feedback'):
right = True
elif is_topic_pub('/l_overhead_grasp/feedback'):
left = True
if left == True:
prefix = 'l_'
elif right == True:
prefix = 'r_'
frame1 = prefix+'gripper_l_finger_tip_link'
frame2 = prefix+'gripper_r_finger_tip_link'
#run = True
while is_topic_pub('/clock') == True: #run == True:#not rospy.is_shutdown():
try:
(trans,rot) = listener.lookupTransform(frame1, frame2, rospy.Time(0))
dist = math.sqrt((np.matrix(trans)*np.matrix(trans).T)[0,0])
time = rospy.get_time()
dist_ls.append(dist)
time_ls.append(time)
except (tf.LookupException, tf.ConnectivityException):
#run = False
continue
rate.sleep()
return dist_ls, time_ls
if __name__ == '__main__':
rospy.init_node('get_gripper_position')
listener = tf.TransformListener()
rate = rospy.Rate(100.0)
path = sys.argv[1]
print "path is :", path
for i in xrange(9):
j = 0
dist_dict = {}
f_hand = open(path+'/object'+str(i).zfill(3)+'_gripper_dist.pkl', 'w')
while os.path.isfile(path + '/object'+str(i).zfill(3)+'_try'+str(j).zfill(3)+'.bag') == True: #j < 999:
f_path = path + '/object'+str(i).zfill(3)+'_try'+str(j).zfill(3)+'.bag'
os.system('rosbag play -r 2 '+ f_path + ' &')
dist_ls, time_ls = get_data(listener, rate)
dist_dict['try'+str(j).zfill(3)] = {'dist':dist_ls, 'time':time_ls}
j = j+1
pkl.dump(dist_dict, f_hand)
f_hand.close()
| [
[
1,
0,
0.0241,
0.012,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0361,
0.012,
0,
0.66,
0.0909,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0482,
0.012,
0,
0.66,... | [
"import roslib",
"roslib.load_manifest('pr2_playpen')",
"import rospy",
"import math",
"import tf",
"import numpy as np",
"import os",
"import sys",
"import cPickle as pkl",
"def is_topic_pub(topic):\n flag = False\n for item in rospy.get_published_topics():\n for thing in item:\n ... |
#!/usr/bin/env python
import roslib
roslib.load_manifest('pr2_playpen')
import rospy
from sensor_msgs.msg import PointCloud2
import point_cloud_python as pc2py
import numpy as np
from matplotlib import pylab as pl
import draw_scene as ds
import math
from pr2_playpen.srv import * #this is for Train and Check
import threading
class ResultsAnalyzer:
def __init__(self):
rospy.init_node('playpen_results')
self.draw = ds.SceneDraw()
self.cloud = None
rospy.Subscriber("pr2_segment_region", PointCloud2, self.callback)
# rospy.Subscriber("playpen_segment_object", PointCloud2, self.callback)
self.check = rospy.Service("playpen_check_success", Check, self.serv_success)
self.train_empty = rospy.Service("playpen_train", Train, self.serv_train)
self.table_mean = None
self.table_cov = None
self.object_mean = None
self.object_cov = None
self.mean_ls =[]
self.cov_ls = []
self.start_time = rospy.get_time()
self.lock = threading.RLock()
self.new_cloud = False
self.start = 0
def callback(self, data):
self.lock.acquire()
self.cloud = list(pc2py.points(data, ['x', 'y', 'z']))
self.new_cloud = True
print rospy.get_time()-self.start, "time in between call backs"
self.start = rospy.get_time()
self.lock.release()
# self.get_cloud_stats()
def serv_success(self, req):
result = "none"
while self.new_cloud == False:
rospy.sleep(0.01)
self.new_cloud = False
self.lock.acquire()
if self.table_mean == None or self.object_mean == None:
print "you haven't initialized yet!!"
return CheckResponse(result)
np_array_cloud = np.array(self.cloud)
f_ind = np.array(~np.isnan(np_array_cloud).any(1)).flatten()
f_np_array_cloud = np_array_cloud[f_ind, :]
if np.max(f_np_array_cloud.shape)>200:
mean_3d = np.mean(f_np_array_cloud, axis = 0)
cov_3d = np.cov(f_np_array_cloud.T)
v, d = np.linalg.eig(cov_3d)
max_var = d[:, v == np.max(v)]
mean_dist_table = (np.matrix(mean_3d).reshape(3,1)-self.table_mean)
mean_dist_object = (np.matrix(mean_3d).reshape(3,1)-self.object_mean)
mahal_dist_table = mean_dist_table.T*0.5*np.matrix(np.linalg.inv(cov_3d)+np.linalg.inv(self.table_cov))*mean_dist_table
mahal_dist_object = mean_dist_object.T*0.5*np.matrix(np.linalg.inv(cov_3d)+np.linalg.inv(self.object_cov))*mean_dist_object
print "table distance = ", mahal_dist_table
print "object distance = ", mahal_dist_object
# print "d = ", d
# print "v = ", v
#made a simple change so that I only look if table is empty or not
#comparison is made from the user selected region with a base model
#of mean covariance of the empty tabletop
if np.max(f_np_array_cloud.shape)<200:
result = "no_cloud"
elif mahal_dist_table<mahal_dist_object:
result = "table"
else:
result = "object"
# if req.exp_state == 'empty':
# if np.max(f_np_array_cloud.shape)<200:
# result = "success"
# elif mahal_dist<5*self.nom_dist:
# result = "success"
# else:
# result = "fail"
# elif req.exp_state == 'object':
# if np.max(f_np_array_cloud.shape)<200:
# result = "fail"
# elif mahal_dist<5*self.nom_dist:
# result = "success"
# else:
# result = "fail"
# elif req.exp_state == 'objects':
# print "multiple objects is not yet supported"
self.lock.release()
return CheckResponse(result)
def serv_train(self, req):
num_samples = 0
if req.expected == 'table':
self.table_mean = None
self.table_cov = None
print "training for empty table top"
elif req.expected == 'object':
self.object_mean = None
self.object_cov = None
print "training for object on table top"
self.mean_ls = []
self.cov_ls = []
while num_samples < 11:
start_time = rospy.get_time()
while self.new_cloud == False:
rospy.sleep(0.01)
self.lock.acquire()
np_array_cloud = np.array(self.cloud)
f_ind = np.array(~np.isnan(np_array_cloud).any(1)).flatten()
f_np_array_cloud = np_array_cloud[f_ind, :]
if np.max(f_np_array_cloud.shape)>200:
mean_3d = np.mean(f_np_array_cloud, axis = 0)
cov_3d = np.cov(f_np_array_cloud.T)
v, d = np.linalg.eig(cov_3d)
max_var = d[:, v == np.max(v)]
self.mean_ls.append(np.matrix(mean_3d).reshape(3,1))
self.cov_ls.append(np.matrix(cov_3d))
num_samples = num_samples + 1
self.new_cloud = False
print "still initializing"
self.lock.release()
buf_mean = np.matrix(np.zeros((3,1)))
buf_cov = np.matrix(np.zeros((3,3)))
print "here is the mean list :", self.mean_ls
mean_arr = np.array(self.mean_ls)
mean_arr.sort(axis=0)
print "here is th sorted mean array :", mean_arr
print "here is the mean cov :\n", self.cov_ls
cov_arr = np.array(self.cov_ls)
cov_arr.sort(axis=0)
print "here is the sorted cov :\n", cov_arr
# for i in xrange(10):
# buf_mean = buf_mean + self.mean_ls[i]
# buf_cov = buf_cov + self.cov_ls[i] #this is not exactly correct if populations
#have different # of points, but it should be approximately right
if req.expected == 'table':
self.table_mean = mean_arr[5]
self.table_cov = cov_arr[5]
# self.table_mean = buf_mean*1/10.0
# self.table_cov = buf_cov*1/10.0
elif req.expected == 'object':
self.object_mean = mean_arr[5]
self.object_cov = cov_arr[5]
# self.object_mean = buf_mean*1/10.0
# self.object_cov = buf_cov*1/10.0
return TrainResponse(num_samples)
def run(self):
print 'Ready to calculate results'
rospy.spin()
def get_cloud_stats(self):
np_array_cloud = np.array(self.cloud)
f_ind = np.array(~np.isnan(np_array_cloud).any(1)).flatten()
f_np_array_cloud = np_array_cloud[f_ind, :]
print 'size of remaining point cloud :', np.max(f_np_array_cloud.shape)
if np.max(f_np_array_cloud.shape)>200:
mean_3d = np.mean(f_np_array_cloud, axis = 0)
cov_3d = np.cov(f_np_array_cloud.T)
v, d = np.linalg.eig(cov_3d)
max_var = d[:, v == np.max(v)]
mean_dist = (np.matrix(mean_3d).reshape(3,1)-self.nom_mean)
mahal_dist = mean_dist.T*0.5*np.matrix(np.linalg.inv(cov_3d)+np.linalg.inv(self.nom_cov))*mean_dist
print "distance = ", mahal_dist
if rospy.get_time()-self.start_time < 10:
self.nom_mean = np.matrix(mean_3d).reshape(3,1)
self.nom_cov = np.matrix(cov_3d)
print "still initializing"
else:
print "real distance now"
else:
print "not doing anything since point cloud is too small"
# print "mean :\n", mean_3d
# print "cov matrix :\n", cov_3d
# print "eig of cov :\n", v
# print d
# print "max direction of var :\n", max_var
# hs.draw.pub_body((0, 0, 0), (0, 0, 0, 1),
# (0.2, 0.2, 0.2), (1, 0,0,1), 1000000, hs.draw.Marker.SPHERE)
# self.draw.pub_body((mean_3d[2], -1*mean_3d[0], -1*mean_3d[1]), (0, 0, 0, 1),
# (0.2, 0.2, 0.2), (0, 1,0,1), 1000001, self.draw.Marker.SPHERE)
if __name__ == '__main__':
ra = ResultsAnalyzer()
ra.run()
# import roslib
# roslib.load_manifest('my_package')
# import sys
# import rospy
# import cv
# from std_msgs.msg import String
# from sensor_msgs.msg import Image
# from cv_bridge import CvBridge, CvBridgeError
# class image_converter:
# def __init__(self):
# self.image_pub = rospy.Publisher("image_topic_2",Image)
# cv.NamedWindow("Image window", 1)
# self.bridge = CvBridge()
# self.image_sub = rospy.Subscriber("image_topic",Image,self.callback)
# def callback(self,data):
# try:
# cv_image = self.bridge.imgmsg_to_cv(data, "bgr8")
# except CvBridgeError, e:
# print e
# (cols,rows) = cv.GetSize(cv_image)
# if cols > 60 and rows > 60 :
# cv.Circle(cv_image, (50,50), 10, 255)
# cv.ShowImage("Image window", cv_image)
# cv.WaitKey(3)
# try:
# self.image_pub.publish(self.bridge.cv_to_imgmsg(cv_image, "bgr8"))
# except CvBridgeError, e:
# print e
# def main(args):
# ic = image_converter()
# rospy.init_node('image_converter', anonymous=True)
# try:
# rospy.spin()
# except KeyboardInterrupt:
# print "Shutting down"
# cv.DestroyAllWindows()
# if __name__ == '__main__':
# main(sys.argv)
| [
[
1,
0,
0.0076,
0.0038,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0115,
0.0038,
0,
0.66,
0.0833,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0153,
0.0038,
0,
0.... | [
"import roslib",
"roslib.load_manifest('pr2_playpen')",
"import rospy",
"from sensor_msgs.msg import PointCloud2",
"import point_cloud_python as pc2py",
"import numpy as np",
"from matplotlib import pylab as pl",
"import draw_scene as ds",
"import math",
"from pr2_playpen.srv import * #this is for... |
import roslib
roslib.load_manifest('opencv2')
import cv
a = cv.LoadImage('/home/mkillpack/hrl_file_server/playpen_data_sets/2011-06-30_19-01-02/object000_try011_before_pr2.png', 0)
b = cv.LoadImage('/home/mkillpack/hrl_file_server/playpen_data_sets/2011-06-30_19-01-02/object000_try011_after_pr2.png', 0)
foreground = cv.CreateImage((640,480), 8, 1)
size = cv.GetSize(a)
IavgF = cv.CreateImage(size, cv.IPL_DEPTH_32F, 3)
IdiffF = cv.CreateImage(size, cv.IPL_DEPTH_32F, 3)
IprevF = cv.CreateImage(size, cv.IPL_DEPTH_32F, 3)
IhiF = cv.CreateImage(size, cv.IPL_DEPTH_32F, 3)
IlowF = cv.CreateImage(size, cv.IPL_DEPTH_32F, 3)
Ilow1 = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
Ilow2 = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
Ilow3 = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
Ihi1 = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
Ihi2 = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
Ihi3 = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
cv.Zero(IavgF)
cv.Zero(IdiffF)
cv.Zero(IprevF)
cv.Zero(IhiF)
cv.Zero(IlowF)
Icount = 0.00001
Iscratch = cv.CreateImage(size, cv.IPL_DEPTH_32F, 3)
Iscratch2 = cv.CreateImage(size, cv.IPL_DEPTH_32F, 3)
Igray1 = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
Igray2 = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
Igray3 = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
Imaskt = cv.CreateImage(size, cv.IPL_DEPTH_8U, 1)
cv.Zero(Iscratch)
cv.Zero(Iscratch2)
first = 1
def accumulateBackground(img):
global first, Icount
cv.CvtScale(img, Iscratch, 1, 0)
if (not first):
cv.Acc(Iscratch, IavgF)
cv.AbsDiff(Iscratch, IprevF, Iscratch2)
cv.Acc(Iscratch2, IdiffF)
Icount += 1.0
first = 0
cv.Copy(Iscratch, IprevF)
def setHighThresh(thresh):
cv.ConvertScale(IdiffF, Iscratch, thresh)
cv.Add(Iscratch, IavgF, IhiF)
cv.Split(IhiF, Ihi1, Ihi2, Ihi3, None)
def setLowThresh(thresh):
cv.ConvertScale(IdiffF, Iscratch, thresh)
cv.Sub(IavgF, Iscratch, IlowF)
cv.Split(IlowF, Ilow1, Ilow2, Ilow3, None)
def createModelsfromStats():
cv.ConvertScale(IavgF, IavgF, float(1.0/Icount))
cv.ConvertScale(IdiffF, IdiffF, float(1.0/Icount))
cv.AddS(IdiffF, cv.Scalar(1.0, 1.0, 1.0), IdiffF)
setHighThresh(10.0)
setLowThresh(10.0)
def backgroundDiff(img, Imask):
cv.CvtScale(img, Iscratch, 1, 0)
cv.Split(Iscratch, Igray1, Igray2, Igray3, None)
cv.InRange(Igray1, Ilow1, Ihi1, Imask)
cv.InRange(Igray2, Ilow2, Ihi2, Imaskt)
cv.Or(Imask, Imaskt, Imask)
cv.InRange(Igray3, Ilow3, Ihi3, Imaskt)
cv.Or(Imask, Imaskt, Imask)
cv.SubRS(Imask, 255, Imask)
cv.SaveImage('/home/mkillpack/Desktop/mask.png', Imask)
#cv.Erode(Imask, Imask)
print "here is the sum of the non-zero pixels", cv.Sum(Imask)
return Imask
if __name__ == '__main__':
folder = '/home/mkillpack/hrl_file_server/playpen_data_sets/2011-06-30_19-01-02/'
for j in [3]: #[0, 3, 4, 5, 6]
for i in xrange(200):
try:
file_name = folder+'object'+str(j).zfill(3)+'_try'+str(i).zfill(3)+'_after_pr2.png'
img = cv.LoadImage(file_name, 1)
print "reading ", file_name, '...'
except:
print file_name, " doesn't exist"
if not img == None:
accumulateBackground(img)
#c = cv.LoadImage('/home/mkillpack/hrl_file_server/playpen_data_sets/2011-06-30_19-01-02/object000_try012_after_pr2.png', 1)
createModelsfromStats()
file_name = folder+'object006_try'+str(0).zfill(3)+'_before_pr2.png'
img = cv.LoadImage(file_name, 3)
Imask = cv.CreateImage(size, cv.IPL_DEPTH_8U, 1)
cv.Zero(Imask)
cv.Zero(Imaskt)
Imask = backgroundDiff(img, Imask)
| [
[
1,
0,
0.0093,
0.0093,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.0185,
0.0093,
0,
0.66,
0.0263,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.0278,
0.0093,
0,
0.... | [
"import roslib",
"roslib.load_manifest('opencv2')",
"import cv",
"a = cv.LoadImage('/home/mkillpack/hrl_file_server/playpen_data_sets/2011-06-30_19-01-02/object000_try011_before_pr2.png', 0)",
"b = cv.LoadImage('/home/mkillpack/hrl_file_server/playpen_data_sets/2011-06-30_19-01-02/object000_try011_after_pr2... |
#######################################################################
#
# USE pr2_object_manipulation/pr2_gripper_reactive_approach/controller_manager.py
# That code has much of the ideas at the bottom, with more.
#
#######################################################################
# TODO Update code to throw points one at a time. Sections are labled: "Hack"
import numpy as np, math
from threading import RLock, Timer
import sys
import roslib; roslib.load_manifest('hrl_pr2_lib')
import tf
import rospy
import actionlib
from actionlib_msgs.msg import GoalStatus
from pr2_controllers_msgs.msg import Pr2GripperCommandGoal, Pr2GripperCommandAction, Pr2GripperCommand
from geometry_msgs.msg import PoseStamped
from teleop_controllers.msg import JTTeleopControllerState
from std_msgs.msg import Float64
from sensor_msgs.msg import JointState
import hrl_lib.transforms as tr
import time
import tf.transformations as tftrans
import types
node_name = "pr2_arms"
def log(str):
rospy.loginfo(node_name + ": " + str)
##
# Class for simple management of the arms and grippers.
# Provides functionality for moving the arms, opening and closing
# the grippers, performing IK, and other functionality as it is
# developed.
class PR2Arms(object):
##
# Initializes all of the servers, clients, and variables
#
# @param send_delay send trajectory points send_delay nanoseconds into the future
# @param gripper_point given the frame of the wrist_roll_link, this point offsets
# the location used in FK and IK, preferably to the tip of the
# gripper
def __init__(self, send_delay=50000000, gripper_point=(0.23,0.0,0.0),
force_torque = False):
log("Loading PR2Arms")
self.send_delay = send_delay
self.off_point = gripper_point
self.gripper_action_client = [actionlib.SimpleActionClient('r_gripper_controller/gripper_action', Pr2GripperCommandAction),actionlib.SimpleActionClient('l_gripper_controller/gripper_action', Pr2GripperCommandAction)]
self.gripper_action_client[0].wait_for_server()
self.gripper_action_client[1].wait_for_server()
self.arm_state_lock = [RLock(), RLock()]
self.r_arm_cart_pub = rospy.Publisher('/r_cart/command_pose', PoseStamped)
self.l_arm_cart_pub = rospy.Publisher('/l_cart/command_pose', PoseStamped)
rospy.Subscriber('/r_cart/state', JTTeleopControllerState, self.r_cart_state_cb)
rospy.Subscriber('/l_cart/state', JTTeleopControllerState, self.l_cart_state_cb)
self.tf_lstnr = tf.TransformListener()
rospy.sleep(1.)
log("Finished loading SimpleArmManger")
def r_cart_state_cb(self, msg):
trans, quat = self.tf_lstnr.lookupTransform('/torso_lift_link',
'r_gripper_tool_frame', rospy.Time(0))
rot = tr.quaternion_to_matrix(quat)
tip = np.matrix([0.12, 0., 0.]).T
self.r_ee_pos = rot*tip + np.matrix(trans).T
self.r_ee_rot = rot
ros_pt = msg.x_desi_filtered.pose.position
x, y, z = ros_pt.x, ros_pt.y, ros_pt.z
self.r_cep_pos = np.matrix([x, y, z]).T
pt = rot.T * (np.matrix([x,y,z]).T - np.matrix(trans).T)
pt = pt + tip
self.r_cep_pos_hooktip = rot*pt + np.matrix(trans).T
ros_quat = msg.x_desi_filtered.pose.orientation
quat = (ros_quat.x, ros_quat.y, ros_quat.z, ros_quat.w)
self.r_cep_rot = tr.quaternion_to_matrix(quat)
def l_cart_state_cb(self, msg):
ros_pt = msg.x_desi_filtered.pose.position
self.l_cep_pos = np.matrix([ros_pt.x, ros_pt.y, ros_pt.z]).T
ros_quat = msg.x_desi_filtered.pose.orientation
quat = (ros_quat.x, ros_quat.y, ros_quat.z, ros_quat.w)
self.l_cep_rot = tr.quaternion_to_matrix(quat)
def get_ee_jtt(self, arm):
if arm == 0:
return self.r_ee_pos, self.r_ee_rot
else:
return self.l_ee_pos, self.l_ee_rot
def get_cep_jtt(self, arm, hook_tip = False):
if arm == 0:
if hook_tip:
return self.r_cep_pos_hooktip, self.r_cep_rot
else:
return self.r_cep_pos, self.r_cep_rot
else:
return self.l_cep_pos, self.l_cep_rot
# set a cep using the Jacobian Transpose controller.
def set_cep_jtt(self, arm, p, rot=None):
if arm != 1:
arm = 0
ps = PoseStamped()
ps.header.stamp = rospy.rostime.get_rostime()
ps.header.frame_id = 'torso_lift_link'
ps.pose.position.x = p[0,0]
ps.pose.position.y = p[1,0]
ps.pose.position.z = p[2,0]
if rot == None:
if arm == 0:
rot = self.r_cep_rot
else:
rot = self.l_cep_rot
quat = tr.matrix_to_quaternion(rot)
ps.pose.orientation.x = quat[0]
ps.pose.orientation.y = quat[1]
ps.pose.orientation.z = quat[2]
ps.pose.orientation.w = quat[3]
if arm == 0:
self.r_arm_cart_pub.publish(ps)
else:
self.l_arm_cart_pub.publish(ps)
# rotational interpolation unimplemented.
def go_cep_jtt(self, arm, p):
step_size = 0.01
sleep_time = 0.1
cep_p, cep_rot = self.get_cep_jtt(arm)
unit_vec = (p-cep_p)
unit_vec = unit_vec / np.linalg.norm(unit_vec)
while np.linalg.norm(p-cep_p) > step_size:
cep_p += unit_vec * step_size
self.set_cep_jtt(arm, cep_p)
rospy.sleep(sleep_time)
self.set_cep_jtt(arm, p)
rospy.sleep(sleep_time)
# TODO Evaluate gripper functions and parameters
##
# Move the gripper the given amount with given amount of effort
#
# @param arm 0 for right, 1 for left
# @param amount the amount the gripper should be opened
# @param effort - supposed to be in Newtons. (-ve number => max effort)
def move_gripper(self, arm, amount=0.08, effort = 15):
self.gripper_action_client[arm].send_goal(Pr2GripperCommandGoal(Pr2GripperCommand(position=amount, max_effort = effort)))
##
# Open the gripper
#
# @param arm 0 for right, 1 for left
def open_gripper(self, arm):
self.move_gripper(arm, 0.08, -1)
##
# Close the gripper
#
# @param arm 0 for right, 1 for left
def close_gripper(self, arm, effort = 15):
self.move_gripper(arm, 0.0, effort)
# def get_wrist_force(self, arm):
# pass
######################################################
# More specific functionality
######################################################
if __name__ == '__main__':
rospy.init_node(node_name, anonymous = True)
log("Node initialized")
pr2_arm = PR2Arms()
# #------- testing set JEP ---------------
# raw_input('Hit ENTER to begin')
r_arm, l_arm = 0, 1
# cep_p, cep_rot = pr2_arm.get_cep_jtt(r_arm)
# print 'cep_p:', cep_p.A1
#
# for i in range(5):
# cep_p[0,0] += 0.01
# raw_input('Hit ENTER to move')
# pr2_arm.set_cep_jtt(r_arm, cep_p)
raw_input('Hit ENTER to move')
p1 = np.matrix([0.62, 0.0, 0.16]).T
pr2_arm.go_cep_jtt(r_arm, p1)
#rospy.sleep(10)
#pr2_arm.close_gripper(r_arm, effort = -1)
raw_input('Hit ENTER to move')
p2 = np.matrix([0.600+0.06, 0.106, -0.32]).T
pr2_arm.go_cep_jtt(r_arm, p2)
raw_input('Hit ENTER to move')
pr2_arm.go_cep_jtt(r_arm, p1)
raw_input('Hit ENTER to go home')
home = np.matrix([0.23, -0.6, -0.05]).T
pr2_arm.go_cep_jtt(r_arm, home)
| [
[
1,
0,
0.0636,
0.0042,
0,
0.66,
0,
954,
0,
2,
0,
0,
954,
0,
0
],
[
1,
0,
0.0678,
0.0042,
0,
0.66,
0.0476,
83,
0,
2,
0,
0,
83,
0,
0
],
[
1,
0,
0.072,
0.0042,
0,
0.6... | [
"import numpy as np, math",
"from threading import RLock, Timer",
"import sys",
"import roslib; roslib.load_manifest('hrl_pr2_lib')",
"import roslib; roslib.load_manifest('hrl_pr2_lib')",
"import tf",
"import rospy",
"import actionlib",
"from actionlib_msgs.msg import GoalStatus",
"from pr2_contro... |
#!/usr/bin/env python
#
# Copyright (c) 2009, Georgia Tech Research Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the Georgia Tech Research Corporation nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#Author: Marc Killpack
import roslib
roslib.load_manifest('pr2_playpen')
from UI_segment_object.srv import GetObject
import rospy
import sys
import optparse
p = optparse.OptionParser()
p.add_option('--node', action='store', type='string', dest='node')
p.add_option('--serv', action='store', type='string', dest='service')
opt, args = p.parse_args()
rospy.init_node(opt.node)
rospy.wait_for_service(opt.service)
pub_filtered_cloud = rospy.ServiceProxy(opt.service, GetObject)
r = rospy.Rate(30)
while not rospy.is_shutdown():
pub_filtered_cloud()
r.sleep()
| [
[
1,
0,
0.5882,
0.0196,
0,
0.66,
0,
796,
0,
1,
0,
0,
796,
0,
0
],
[
8,
0,
0.6078,
0.0196,
0,
0.66,
0.0714,
630,
3,
1,
0,
0,
0,
0,
1
],
[
1,
0,
0.6275,
0.0196,
0,
0.... | [
"import roslib",
"roslib.load_manifest('pr2_playpen')",
"from UI_segment_object.srv import GetObject",
"import rospy",
"import sys",
"import optparse",
"p = optparse.OptionParser()",
"p.add_option('--node', action='store', type='string', dest='node')",
"p.add_option('--serv', action='store', type='s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.