00001
00002 import os, sys, tty
00003 import numpy as np
00004 import cPickle as pk
00005 import time
00006 import threading
00007 import math
00008
00009 from hrl_lib.msg import NumpyArray
00010
00011
00012
00013 def getTime():
00014 return '['+time.strftime("%H:%M:%S", time.localtime())+']'
00015
00016
00017
00018 def quat_angle(quat1, quat2):
00019 dot = sum([x*y for (x,y) in zip(quat1, quat2)])
00020 if dot > 1.:
00021 dot = 1.
00022 if dot < -1.:
00023 dot = -1.
00024 angle = 2*math.acos(math.fabs(dot))
00025 return angle
00026
00027 def standard_rad(t):
00028 if t > 0:
00029 return ((t + np.pi) % (np.pi * 2)) - np.pi
00030 else:
00031 return ((t - np.pi) % (np.pi * -2)) + np.pi
00032
00033
00034
00035
00036
00037
00038 def list_mat_to_mat(list_mat, axis=0):
00039 return np.concatenate(tuple(list_mat), axis=axis)
00040
00041
00042
00043
00044 def formatted_time():
00045 date_name = time.strftime('%Y%h%d_%H%M%S', time.localtime())
00046
00047
00048 return date_name
00049
00050
00051
00052
00053 def load_pickle(filename):
00054 try:
00055 p = open(filename, 'r')
00056 except IOError:
00057 print "hrl_lib.util: Pickle file cannot be opened."
00058 return None
00059 try:
00060 picklelicious = pk.load(p)
00061 except ValueError:
00062 print 'util.load_pickle failed once, trying again'
00063 p.close()
00064 p = open(filename, 'r')
00065 picklelicious = pk.load(p)
00066
00067 p.close()
00068 return picklelicious
00069
00070
00071
00072
00073 def save_pickle(object, filename):
00074 pickle_file = open(filename, 'w')
00075 pk.dump(object, pickle_file)
00076 pickle_file.close()
00077
00078
00079
00080 def norm(mat):
00081 return np.power(np.sum(np.power(mat,2), axis=0), 0.5)
00082
00083 def approx_equal(a, b, epsilon=.001):
00084 return (b < (a+epsilon)) and ((a-epsilon) < b)
00085
00086 def unipolar_limit( x, upper ):
00087 """ limit the value of x such that
00088 0 <= x <= upper
00089 """
00090
00091 if x > upper:
00092 x=upper
00093 if x < 0:
00094 x=0
00095
00096 return x
00097
00098 def cart_of_pol(p):
00099 """ Finds cartesian coordinates of polar points [r, t]' """
00100 r = p[0,:]
00101 t = p[1,:]
00102 x = numpy.multiply(numpy.cos(t), r)
00103 y = numpy.multiply(numpy.sin(t), r)
00104 return numpy.vstack((x,y))
00105
00106 def pol_of_cart(p):
00107 """ Find polar coordinates of cartesian points [x, y]' """
00108 norm = numpy.linalg.norm(p)
00109 ang = math.atan2(p[1,0], p[0,0])
00110 return numpy.matrix([norm, ang]).T
00111
00112
00113
00114
00115 def bound(value, lower, upper):
00116 import rospy
00117 rospy.loginfo('hrl_lib.util.bound is DEPRECATED. Please use numpy.clip instead')
00118 if lower >= upper:
00119 t = lower
00120 lower = upper
00121 upper = t
00122
00123
00124 ret_val = min(max(value, lower), upper)
00125
00126
00127 return ret_val
00128
00129
00130
00131
00132
00133
00134
00135 def wrap_np_array(nparr):
00136 shp = nparr.shape
00137 npstr = nparr.tostring()
00138 npdtype = str(nparr.dtype)
00139 nparr_ros = NumpyArray(None,npstr,shp,npdtype)
00140 return nparr_ros
00141
00142
00143
00144
00145 def unwrap_np_array(nparr_ros):
00146 npstr,shp,npdtype = nparr_ros.data,nparr_ros.shape,nparr_ros.dtype
00147 nparr = np.fromstring(npstr,dtype=npdtype)
00148 nparr = nparr.reshape(shp)
00149 return nparr
00150
00151
00152
00153
00154
00155
00156
00157
00158 def cartesian_product(lists, previous_elements = []):
00159 if len(lists) == 1:
00160 for elem in lists[0]:
00161 yield previous_elements + [elem, ]
00162 else:
00163 for elem in lists[0]:
00164 for x in cartesian_product(lists[1:], previous_elements + [elem, ]):
00165 yield x
00166
00167
00168
00169
00170 def choose_without_replacement(list, n):
00171 lists = [list for i in range(n)]
00172 return _choose_without_replacement(lists)
00173
00174 def _choose_without_replacement(lists,previous_elements=[],ignore_count=0):
00175 if len(lists) == 1:
00176 for elem in lists[0][ignore_count:]:
00177 yield previous_elements + [elem, ]
00178 else:
00179 for i,elem in enumerate(lists[0][ignore_count:]):
00180 for x in _choose_without_replacement(lists[1:],previous_elements + [elem, ],ignore_count+i+1):
00181 yield x
00182
00183
00184
00185
00186 def say(text):
00187 os.system( 'echo "' + text + '" | festival --tts' )
00188
00189
00190
00191
00192
00193 def matrixrank(A,tol=1e-8):
00194 s = np.linalg.svd(A,compute_uv=0)
00195 return sum( np.where( s>tol, 1, 0 ) )
00196
00197
00198
00199
00200 def get_keystroke(msg):
00201 print msg
00202
00203 tty.setraw(sys.stdin, tty.TCSAFLUSH)
00204
00205 os.system('stty raw')
00206 r = sys.stdin.read(1)
00207 os.system('stty sane')
00208 return r
00209
00210
00211
00212 def get_bash_command_output(cmd):
00213 p = os.popen(cmd)
00214 output_l = [s.rstrip('\n') for s in p.readlines()]
00215 p.close()
00216 return output_l
00217
00218
00219
00220
00221
00222
00223
00224 def weighted_avg_and_std(values, weights, unbiased):
00225 average = np.average(values, axis=0, weights=weights)
00226 variance = np.dot(weights, (values-average).A**2)/weights.sum()
00227 if unbiased:
00228 n = len(weights) * 1.
00229 variance = n / (n-1) * variance
00230 return average.A1, np.sqrt(variance)
00231
00232
00233
00234
00235
00236
00237