def test_auto_size_bits_list():
pytest.skip()
a = [0.5, 1.2, 3.2]
b = Sfix.auto_size(a, 18)
for x, y in zip(a, b):
np.isclose(y.val, x)
assert y.left == 2
assert y.right == -15
a = [np.arctan(2 ** -i) for i in range(8)]
b = Sfix.auto_size(a, 18)
for x, y in zip(a, b):
np.isclose(y.val, x)
assert y.left == 0
assert y.right == -17
a = [np.arctan(2 ** -i) for i in range(8, 12)]
b = Sfix.auto_size(a, 18)
for x, y in zip(a, b):
np.isclose(y.val, x)
assert y.left == -8
assert y.right == -25
python类arctan()的实例源码
def load(self, ips):
if ips.imgtype in ('8-bit', 'rgb'):
self.para = {'bright':0, 'contrast':45}
self.view = [('slide', (-100,100), 'Brightness', 'bright', ''),
('slide', (1,89), 'Contrast', 'contrast', '')]
if 'not_slice' in self.note:
self.note.remove('not_slice')
else :
self.arange = minv, maxv = ips.img.min(), ips.img.max()
self.para = {'bright':np.mean(ips.range) - np.mean(self.arange),
'contrast':round(np.arctan((maxv-minv)/(ips.range[1]-ips.range[0]))/np.pi*180)}
self.view = [('slide', (-(maxv-minv)/2, (maxv-minv)/2), 'Brightness', 'bright', ''),
('slide', (1,89), 'Contrast', 'contrast', '')]
if not 'not_slice' in self.note:
self.note.append('not_slice')
return True
def reset_model(self):
self._min_strike_dist = np.inf
self._striked = False
self._strike_pos = None
qpos = self.init_qpos
self.ball = np.array([0.5, -0.175])
while True:
self.goal = np.concatenate([
self.np_random.uniform(low=0.15, high=0.7, size=1),
self.np_random.uniform(low=0.1, high=1.0, size=1)])
if np.linalg.norm(self.ball - self.goal) > 0.17:
break
qpos[-9:-7] = [self.ball[1], self.ball[0]]
qpos[-7:-5] = self.goal
diff = self.ball - self.goal
angle = -np.arctan(diff[0] / (diff[1] + 1e-8))
qpos[-1] = angle / 3.14
qvel = self.init_qvel + self.np_random.uniform(low=-.1, high=.1,
size=self.model.nv)
qvel[7:] = 0
self.set_state(qpos, qvel)
return self._get_obs()
def FitPCA(self, hPCA_Proj):
'''
Determine the timing of the inflation event.
Uses the first component of the pca projection and
fits A * arctan( (t - t0) / c ) + B to the first pca projection.
@param hPCA_Proj: The sklearn PCA projection
@return [t0, c]
'''
fitfunc = lambda p,t: p[0]*np.arctan((t-p[1])/p[2])+p[3]
errfunc = lambda p,x,y: fitfunc(p,x) - y
dLen = len(hPCA_Proj[:,0])
pA, success = optimize.leastsq(errfunc,[1.,dLen/2.,1.,0.],args=(np.arange(dLen),hPCA_Proj[:,0]))
ct = pA[1:3]
return ct, pA[0]
def FitPCA(self, hPCA_Proj):
'''
Determine the timing of the inflation event from the first component of the pca projection
fits A * arctan( (t - t0) / c ) + B to the first pca projection, in order to estimate
source amplitude parameters
@param hPCA_Proj: The sklearn PCA
@return ct: the t0, c, and B parameters from the fit
@return pA[0]: the fitted amplitude parameter
'''
fitfunc = lambda p,t: p[0]*np.arctan((t-p[1])/p[2])+p[3]
errfunc = lambda p,x,y: fitfunc(p,x) - y
dLen = len(hPCA_Proj[:,0])
pA, success = optimize.leastsq(errfunc,[1.,dLen/2.,1.,0.],args=(np.arange(dLen),hPCA_Proj[:,0]))
ct = pA[1:3]
return ct, pA[0]
def test_branch_cuts_complex64(self):
# check branch cuts and continuity on them
yield _check_branch_cut, np.log, -0.5, 1j, 1, -1, True, np.complex64
yield _check_branch_cut, np.log2, -0.5, 1j, 1, -1, True, np.complex64
yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1, True, np.complex64
yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1, True, np.complex64
yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1, True, np.complex64
yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64
yield _check_branch_cut, np.arccos, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64
yield _check_branch_cut, np.arctan, [0-2j, 2j], [1, 1], -1, 1, True, np.complex64
yield _check_branch_cut, np.arcsinh, [0-2j, 2j], [1, 1], -1, 1, True, np.complex64
yield _check_branch_cut, np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True, np.complex64
yield _check_branch_cut, np.arctanh, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64
# check against bogus branch cuts: assert continuity between quadrants
yield _check_branch_cut, np.arcsin, [0-2j, 2j], [ 1, 1], 1, 1, False, np.complex64
yield _check_branch_cut, np.arccos, [0-2j, 2j], [ 1, 1], 1, 1, False, np.complex64
yield _check_branch_cut, np.arctan, [ -2, 2], [1j, 1j], 1, 1, False, np.complex64
yield _check_branch_cut, np.arcsinh, [ -2, 2, 0], [1j, 1j, 1], 1, 1, False, np.complex64
yield _check_branch_cut, np.arccosh, [0-2j, 2j, 2], [1, 1, 1j], 1, 1, False, np.complex64
yield _check_branch_cut, np.arctanh, [0-2j, 2j, 0], [1, 1, 1j], 1, 1, False, np.complex64
def test_against_cmath(self):
import cmath
points = [-1-1j, -1+1j, +1-1j, +1+1j]
name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan',
'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'}
atol = 4*np.finfo(np.complex).eps
for func in self.funcs:
fname = func.__name__.split('.')[-1]
cname = name_map.get(fname, fname)
try:
cfunc = getattr(cmath, cname)
except AttributeError:
continue
for p in points:
a = complex(func(np.complex_(p)))
b = cfunc(p)
assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s" % (fname, p, a, b))
def compute_pd_control(self):
if self.received_data:
# given the computed wall slope, compute theta, avoid divide by zero error
if np.abs(self.m) < EPSILON:
theta = np.pi / 2.0
x_intercept = 0
else:
theta = np.arctan(1.0/self.m)
# solve for y=0 in y=mx+c
x_intercept = self.c / self.m
# x axis is perp. to robot but not perpindicular to wall
# cosine term solves for minimum distance to wall
wall_dist = np.abs(np.cos(theta)*x_intercept)
# control proportional to angular error and distance from wall
distance_term = self.direction_muliplier * KP * (wall_dist - TARGET_DISTANCE)
angle_term = KD * theta
control = angle_term + distance_term
# avoid turning too sharply
self.control = (np.clip(control, -0.3, 0.3), SPEED)
def rotate_image(img_src, angle,scale ,crop=True):
img_src,size_dest= pad_image(img_src,scale)
size = tuple(np.array([img_src.shape[1], img_src.shape[0]]))
org_h=size[1]
org_w=size[0]
src_r = np.sqrt((size[0]/2.0)**2+(size[1]/2.0)**2)
org_angle =np.arctan(float(org_h)/org_w)
dest_h = size_dest[0]
dest_w = size_dest[1]
center = tuple(np.array([img_src.shape[1] * 0.5, img_src.shape[0] * 0.5]))
dsize= (dest_w,dest_h)
rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale)
img_rot = cv2.warpAffine(img_src, rotation_matrix, size, flags=cv2.INTER_CUBIC)
if crop:
x,y,w,h = cv2.boundingRect(img_rot[:,:,3])
return img_rot[y:y+h, x:x+w,:]
else:
return img_rot
def rotate_image(img_src, angle,scale ):
img_src,size_dest= pad_image(img_src,scale)
size = tuple(np.array([img_src.shape[1], img_src.shape[0]]))
org_h=size[1]
org_w=size[0]
src_r = np.sqrt((size[0]/2.0)**2+(size[1]/2.0)**2)
org_angle =np.arctan(float(org_h)/org_w)
dest_h = size_dest[0]
dest_w = size_dest[1]
center = tuple(np.array([img_src.shape[1] * 0.5, img_src.shape[0] * 0.5]))
dsize= (dest_w,dest_h)
rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale)
img_rot = cv2.warpAffine(img_src, rotation_matrix, size, flags=cv2.INTER_CUBIC)
x,y,w,h = cv2.boundingRect(img_rot[:,:,3])
return img_rot[y:y+h, x:x+w,:]
def test_branch_cuts_complex64(self):
# check branch cuts and continuity on them
yield _check_branch_cut, np.log, -0.5, 1j, 1, -1, True, np.complex64
yield _check_branch_cut, np.log2, -0.5, 1j, 1, -1, True, np.complex64
yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1, True, np.complex64
yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1, True, np.complex64
yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1, True, np.complex64
yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64
yield _check_branch_cut, np.arccos, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64
yield _check_branch_cut, np.arctan, [0-2j, 2j], [1, 1], -1, 1, True, np.complex64
yield _check_branch_cut, np.arcsinh, [0-2j, 2j], [1, 1], -1, 1, True, np.complex64
yield _check_branch_cut, np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True, np.complex64
yield _check_branch_cut, np.arctanh, [ -2, 2], [1j, 1j], 1, -1, True, np.complex64
# check against bogus branch cuts: assert continuity between quadrants
yield _check_branch_cut, np.arcsin, [0-2j, 2j], [ 1, 1], 1, 1, False, np.complex64
yield _check_branch_cut, np.arccos, [0-2j, 2j], [ 1, 1], 1, 1, False, np.complex64
yield _check_branch_cut, np.arctan, [ -2, 2], [1j, 1j], 1, 1, False, np.complex64
yield _check_branch_cut, np.arcsinh, [ -2, 2, 0], [1j, 1j, 1], 1, 1, False, np.complex64
yield _check_branch_cut, np.arccosh, [0-2j, 2j, 2], [1, 1, 1j], 1, 1, False, np.complex64
yield _check_branch_cut, np.arctanh, [0-2j, 2j, 0], [1, 1, 1j], 1, 1, False, np.complex64
def test_against_cmath(self):
import cmath
points = [-1-1j, -1+1j, +1-1j, +1+1j]
name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan',
'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'}
atol = 4*np.finfo(np.complex).eps
for func in self.funcs:
fname = func.__name__.split('.')[-1]
cname = name_map.get(fname, fname)
try:
cfunc = getattr(cmath, cname)
except AttributeError:
continue
for p in points:
a = complex(func(np.complex_(p)))
b = cfunc(p)
assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s" % (fname, p, a, b))
def arctan_func(xvals, a, b, c):
'''
--------------------------------------------------------------------
This function generates predicted ability levels given data (xvals)
and parameters a, b, and c, from the following arctan function:
y = (-a / pi) * arctan(b * x + c) + (a / 2)
--------------------------------------------------------------------
INPUTS:
xvals = (N,) vector, data inputs to arctan function
a = scalar, scale parameter for arctan function
b = scalar, curvature parameter for arctan function
c = scalar, shift parameter for arctan function
OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None
OBJECTS CREATED WITHIN FUNCTION:
yvals = (N,) vector, predicted values (output) of arctan function
RETURNS: yvals
--------------------------------------------------------------------
'''
yvals = (-a / np.pi) * np.arctan(b * xvals + c) + (a / 2)
return yvals
def arctan_func(xvals, a, b, c):
'''
--------------------------------------------------------------------
This function generates predicted ability levels given data (xvals)
and parameters a, b, and c, from the following arctan function:
y = (-a / pi) * arctan(b * x + c) + (a / 2)
--------------------------------------------------------------------
INPUTS:
xvals = (N,) vector, data inputs to arctan function
a = scalar, scale parameter for arctan function
b = scalar, curvature parameter for arctan function
c = scalar, shift parameter for arctan function
OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None
OBJECTS CREATED WITHIN FUNCTION:
yvals = (N,) vector, predicted values (output) of arctan function
RETURNS: yvals
--------------------------------------------------------------------
'''
yvals = (-a / np.pi) * np.arctan(b * xvals + c) + (a / 2)
return yvals
def fov(self):
"""
Returns the field of view for each axis
"""
return np.float32([np.arctan(self.shape[1] * 0.5 / self.fx),
np.arctan(self.shape[0] * 0.5 / self.fy)]) * 2.0
def dynamics(q, u, p):
"""
Returns state derivative qdot.
Takes current state q, motor input torque u, and disturbance torque p.
See <http://renaissance.ucsd.edu/courses/mae143c/MIPdynamics.pdf> (rederived with incline).
"""
# Angle of pendulum in incline frame
ang = q[2] - incline
# Mass matrix
M = np.array([
[(mass_wheel + mass_pend)*radius**2 + inertia_wheel, mass_pend*radius*cw_to_cm[1]*np.cos(ang)],
[mass_pend*radius*cw_to_cm[1]*np.cos(ang), inertia_pend + mass_pend*cw_to_cm[1]**2]
])
# Gravity effect
g = np.array([
-mass_pend*radius*cw_to_cm[1]*q[3]**2*np.sin(ang) + mass_wheel*radius*gravity[1]*np.sin(incline),
mass_pend*gravity[1]*cw_to_cm[1]*np.sin(q[2])
])
# Friction force
d = np.array([
-friction_wheel * (q[1] + np.arctan(q[1])),
friction_pend * q[3]
])
# Dynamics
accel_wheel_neg, accel_pend = npl.inv(M).dot(np.array([-u, p+u]) - g - d)
return np.array([q[1], -accel_wheel_neg*radius, q[3], accel_pend])
################################################# SIMULATION
# Define time domain
def cart2sph(x, y, z):
""" Convert cartesian to spherical coordinates.
Attributes
----------
x : float
x-coordinate
y : float
y-coordinate
z : float
z-coordinate
Returns
-------
float
radius
float
aziumth
float
elevation
"""
r = np.sqrt(x**2 + y**2 + z**2)
if x > 0 and y > 0:
az = np.arctan(y / x)
elif x > 0 and y < 0:
az = 2*np.pi - np.arctan(-y / x)
elif x < 0 and y > 0:
az = np.pi - np.arctan(-y / x)
elif x < 0 and y < 0:
az = np.pi + np.arctan(y / x)
elif x == 0 and y > 0:
az = np.pi / 2
elif x == 0 and y < 0:
az = 3 * np.pi / 2
elif y == 0 and x > 0:
az = 0
elif y == 0 and x < 0:
az = np.pi
elev = np.arccos(z / r)
return r, az, elev
def ellipse_angle_of_rotation( a ):
b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0]
return 0.5*NP.arctan(2*b/(a-c))
def ellipse_angle_of_rotation2( a ):
b,c,d,f,g,a = a[1]/2, a[2], a[3]/2, a[4]/2, a[5], a[0]
if b == 0:
if a > c:
return 0
else:
return NP.pi/2
else:
if a > c:
return NP.arctan(2*b/(a-c))/2
else:
return NP.pi/2 + NP.arctan(2*b/(a-c))/2
def radial_filter(order, freq, array_configuration, amp_maxdB=40):
"""Generate modal radial filter of specified order and frequency
Parameters
----------
order : array_like
order of filter
freq : array_like
Frequency of modal filter
array_configuration : ArrayConfiguration
List/Tuple/ArrayConfiguration, see io.ArrayConfiguration
amp_maxdB : int, optional
Maximum modal amplification limit in dB [Default: 40]
Returns
-------
dn : array_like
Vector of modal frequency domain filter of shape [nOrders x nFreq]
"""
array_configuration = ArrayConfiguration(*array_configuration)
extrapolation_coeffs = array_extrapolation(order, freq, array_configuration)
extrapolation_coeffs[extrapolation_coeffs == 0] = 1e-12
a_max = 10 ** (amp_maxdB / 20)
limiting_factor = 2 * a_max / _np.pi * _np.abs(extrapolation_coeffs) * _np.arctan(_np.pi / (2 * a_max * _np.abs(extrapolation_coeffs)))
return limiting_factor / extrapolation_coeffs