Python numpy 模块,arctan() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.arctan()。
def get_polar_t(self):
mag = self.get_magnitude()
sizeimg = np.real(self.imgfft).shape
pol = np.zeros(sizeimg)
for x in range(sizeimg[0]):
for y in range(sizeimg[1]):
my = y - sizeimg[1] / 2
mx = x - sizeimg[0] / 2
if mx != 0:
phi = np.arctan(my / float(mx))
else:
phi = 0
r = np.sqrt(mx**2 + my **2)
ix = map_range(phi, -np.pi, np.pi, sizeimg[0], 0)
iy = map_range(r, 0, sizeimg[0], 0, sizeimg[1])
if ix >= 0 and ix < sizeimg[0] and iy >= 0 and iy < sizeimg[1]:
pol[x][y] = mag.data[int(ix)][int(iy)]
pol = MyImage(pol)
pol.limit(1)
return pol
def calc_IndCurrent_cos_range(self,f,t):
"""Induced current over a range of times"""
Bpx = self.Bpx
Bpz = self.Bpz
a2 = self.a2
azm = np.pi*self.azm/180.
R = self.R
L = self.L
w = 2*np.pi*f
Ax = np.pi*a2**2*np.sin(azm)
Az = np.pi*a2**2*np.cos(azm)
Phi = (Ax*Bpx + Az*Bpz)
phi = np.arctan(R/(w*L))-np.pi # This is the phase and not phase lag
Is = -(w*Phi/(R*np.sin(phi) + w*L*np.cos(phi)))*np.cos(w*t + phi)
Ire = -(w*Phi/(R*np.sin(phi) + w*L*np.cos(phi)))*np.cos(w*t)*np.cos(phi)
Iim = (w*Phi/(R*np.sin(phi) + w*L*np.cos(phi)))*np.sin(w*t)*np.sin(phi)
return Ire,Iim,Is,phi
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 effect(self, point):
res = []
# print(self.centers)
for center in self.centers:
center_x, center_y = center
src_x, src_y = point.pos
# Check angle
angle = np.arctan((center_x - src_x) / (center_y - src_y))
if np.abs(angle) > self.angle / 2:
continue
angle = np.deg2rad(90) + angle
u_len = np.sqrt((center_x - src_x) ** 2 + (center_y - src_y) ** 2)
reverse_v = (self.r_index - 1) / self.radius - self.r_index / u_len
v_len = 1 / reverse_v
if v_len > 0:
p_type = 'real'
else:
p_type = 'fake'
target = line_end(point.pos, angle, u_len + v_len)
p = Point(target, p_type, 1)
# point.passed.append(self)
res.append(p)
return tuple(res)
def _radian_direction(dy,dx):
'''
function:
- based on given dy and dx it calculates direction in radian.
- used in feature_eng_pt3
input:
dy = change in y
dx = change in x
output:
returns radian value (0 to 6.28)
'''
if dy < 0.0 and dx > 0.0:
return (2*np.pi + np.arctan(dy/dx))
elif dy >=0.0 and dx > 0.0:
return (np.arctan(dy/dx))
else:
return np.pi + np.arctan(dy/dx)
def flow(self, Kc, Ks, Kz, Ka, numexpr):
zeros = np.zeros
where = np.where
min = np.minimum
max = np.maximum
abs = np.absolute
arctan = np.arctan
sin = np.sin
center = (slice( 1, -1,None),slice( 1, -1,None))
rock = self.center
ds = self.scour[center]
rcc = rock[center]
rock[center] = rcc - ds * Kz
# there isn't really a bottom to the rock but negative values look ugly
rock[center] = where(rcc<0,0,rcc)
def fixOffset(self, offset, img):
size = img.shape
finalImg = np.ndarray(size)
indices = np.indices((self.videoSize[0],self.videoSize[1])).swapaxes(0,2).swapaxes(0,1)
indices = np.around(indices, decimals=1)
indices.shape = (self.videoSize[1] * self.videoSize[0], 2)
phi = 2 * np.arctan(np.exp(indices[:, 1] / self.videoSize[1])) - 1/2 * np.pi - offset[0]
lamb = indices[:, 0] - offset[1]
x = lamb
y = np.log(np.tan(np.pi / 4 + 1/2 * phi)) * self.videoSize[1]
finalIdx = np.ndarray((self.videoSize[1] * self.videoSize[0], 2))
finalIdx = np.around(finalIdx, decimals=1).astype(int)
finalIdx[:, 1] = y % self.videoSize[1]
finalIdx[:, 0] = x % self.videoSize[0]
finalImg[indices[:,1], indices[:,0]] = img[finalIdx[:,1], finalIdx[:,0]]
return finalImg
def _dip_slip_y(self, y1, y2, ang_dip, q):
"""
Based on Okada's paper (1985)
y = down-dip direction
"""
sn = numpy.sin(ang_dip)
cs = numpy.cos(ang_dip)
d_bar = y2*sn - q*cs;
r = numpy.sqrt(y1**2 + y2**2 + q**2)
xx = numpy.sqrt(y1**2 + q**2)
y_bar = y2*cs + q*sn
a5 = 4.*poisson/cs*numpy.arctan((y2*(xx+q*cs)+xx*(r+xx)*sn)/y1/(r+xx)/cs)
a1 = 2.0*poisson*(-y1/(cs*(r+d_bar))) - sn/cs * a5
f = -(y_bar*q/r/(r+y1) + cs*numpy.arctan(y1*y2/q/r) - a1*sn*cs)/(2.0*3.14159)
return f
def _dip_slip_x(self, y1, y2, ang_dip, q):
"""
Based on Okada's paper (1985)
Added by Xiaoming Wang
"""
sn = numpy.sin(ang_dip)
cs = numpy.cos(ang_dip)
d_bar = y2*sn - q*cs;
r = numpy.sqrt(y1**2 + y2**2 + q**2)
xx = numpy.sqrt(y1**2 + q**2)
#a5 = 4.*poisson/cs*numpy.arctan((y2*(xx+q*cs)+xx*(r+xx)*sn)/y1/(r+xx)/cs)
a4 = 2.0*poisson/cs*(numpy.log(r+d_bar) - sn*numpy.log(r+y2))
ytilde = y2*cs + q*sn
a3 = 2.0*poisson*(ytilde/(cs*(r+d_bar)) - numpy.log(r+y2)) + a4*sn/cs
f = -(q/r - a3*sn*cs)/(2.0*3.14159)
return f
def _dip_slip_x(self, y1, y2, ang_dip, q):
"""
Based on Okada's paper (1985)
Added by Xiaoming Wang
"""
sn = numpy.sin(ang_dip)
cs = numpy.cos(ang_dip)
d_bar = y2*sn - q*cs;
r = numpy.sqrt(y1**2 + y2**2 + q**2)
xx = numpy.sqrt(y1**2 + q**2)
#a5 = 4.*poisson/cs*numpy.arctan((y2*(xx+q*cs)+xx*(r+xx)*sn)/y1/(r+xx)/cs)
a4 = 2.0*poisson/cs*(numpy.log(r+d_bar) - sn*numpy.log(r+y2))
ytilde = y2*cs + q*sn
a3 = 2.0*poisson*(ytilde/(cs*(r+d_bar)) - numpy.log(r+y2)) + a4*sn/cs
f = -(q/r - a3*sn*cs)/(2.0*3.14159)
return f
def get_q_per_pixel(self):
'''Gets the delta-q associated with a single pixel. This is computed in
the small-angle limit, so it should only be considered approximate.
For instance, wide-angle detectors will have different delta-q across
the detector face.'''
if self.q_per_pixel is not None:
return self.q_per_pixel
c = (self.pixel_size_um/1e6)/self.distance_m
twotheta = np.arctan(c) # radians
self.q_per_pixel = 2.0*self.get_k()*np.sin(twotheta/2.0)
return self.q_per_pixel
# Maps
########################################
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 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 angularpixelarea(self):
# get the first instrument element
instruments = self.tree.xpath("//instruments/*[1]")
if len(instruments) != 1: raise ValueError("No instruments in ski file")
instrument = instruments[0]
# get the distance in m
d = self.units().convert(instrument.get("distance"), to_unit='m', quantity='distance')
# get the field of view in m
fovx = self.units().convert(instrument.get("fieldOfViewX"), to_unit='m', quantity='length')
fovy = self.units().convert(instrument.get("fieldOfViewY"), to_unit='m', quantity='length')
# get the number of pixels
nx = int(instrument.get("pixelsX"))
ny = int(instrument.get("pixelsY"))
# calculate the angular pixel area
sx = 2 * arctan(fovx / nx / d / 2)
sy = 2 * arctan(fovy / ny / d / 2)
return sx * sy
## This function returns a list of instrument names, in order of occurrence in the ski file.
def orientation_angle(self):
"""
This function ...
:return:
"""
diag_a = self.pixel_scale_matrix[0,1]
diag_b = self.pixel_scale_matrix[1,0]
if not np.isclose(diag_a, diag_b, rtol=0.05):
warnings.warn("The diagonal elements of the pixel scale matrix are not equal: " + repr(diag_a) + " and " + repr(diag_b))
first = self.pixel_scale_matrix[0,0]
radians = np.arctan(diag_a / first)
degrees = radians / math.pi * 180.
return Angle(degrees, "deg")
# -----------------------------------------------------------------
def angularpixelarea(self):
# get the first instrument element
instruments = self.tree.xpath("//instruments/*[1]")
if len(instruments) != 1: raise ValueError("No instruments in ski file")
instrument = instruments[0]
# get the distance in m
d = self.units().convert(instrument.get("distance"), to_unit='m', quantity='distance')
# get the field of view in m
fovx = self.units().convert(instrument.get("fieldOfViewX"), to_unit='m', quantity='length')
fovy = self.units().convert(instrument.get("fieldOfViewY"), to_unit='m', quantity='length')
# get the number of pixels
nx = int(instrument.get("pixelsX"))
ny = int(instrument.get("pixelsY"))
# calculate the angular pixel area
sx = 2 * arctan(fovx / nx / d / 2)
sy = 2 * arctan(fovy / ny / d / 2)
return sx * sy
## This function returns a list of instrument names, in order of occurrence in the ski file.
def orientation_angle(self):
"""
This function ...
:return:
"""
diag_a = self.pixel_scale_matrix[0,1]
diag_b = self.pixel_scale_matrix[1,0]
if not np.isclose(diag_a, diag_b, rtol=0.05):
warnings.warn("The diagonal elements of the pixel scale matrix are not equal: " + repr(diag_a) + " and " + repr(diag_b))
first = self.pixel_scale_matrix[0,0]
radians = np.arctan(diag_a / first)
degrees = radians / math.pi * 180.
return Angle(degrees, "deg")
# -----------------------------------------------------------------
def conferenceWakeOverlap(X, Y, R):
n = np.size(X)
# theta = np.zeros((n, n), dtype=np.float) # angle of wake from fulcrum
f_theta = np.zeros((n, n), dtype=np.float) # smoothing values for smoothing
for i in range(0, n):
for j in range(0, n):
if X[i] < X[j]:
z = R/np.tan(0.34906585)
# print z
theta = np.arctan((Y[j] - Y[i]) / (X[j] - X[i] + z))
# print 'theta =', theta
if -0.34906585 < theta < 0.34906585:
f_theta[i][j] = (1 + np.cos(9*theta))/2
# print f_theta
# print z
# print f_theta
return f_theta
def conferenceWakeOverlap_tune(X, Y, R, boundAngle):
n = np.size(X)
boundAngle = boundAngle*np.pi/180.0
# theta = np.zeros((n, n), dtype=np.float) # angle of wake from fulcrum
f_theta = np.zeros((n, n), dtype=np.float) # smoothing values for smoothing
q = np.pi/boundAngle # factor inside the cos term of the smooth Jensen (see Jensen1983 eq.(3))
# print 'boundAngle = %s' %boundAngle, 'q = %s' %q
for i in range(0, n):
for j in range(0, n):
if X[i] < X[j]:
# z = R/tan(0.34906585)
z = R/np.tan(boundAngle) # distance from fulcrum to wake producing turbine
# print z
theta = np.arctan((Y[j] - Y[i]) / (X[j] - X[i] + z))
# print 'theta =', theta
if -boundAngle < theta < boundAngle:
f_theta[i][j] = (1. + np.cos(q*theta))/2.
# print f_theta
# print z
# print f_theta
return f_theta
def get_cosine_factor_original(X, Y, R0, bound_angle=20.0):
n = np.size(X)
bound_angle = bound_angle*np.pi/180.0
# theta = np.zeros((n, n), dtype=np.float) # angle of wake from fulcrum
f_theta = np.zeros((n, n), dtype=np.float) # smoothing values for smoothing
q = np.pi/bound_angle # factor inside the cos term of the smooth Jensen (see Jensen1983 eq.(3))
for i in range(0, n):
for j in range(0, n):
if X[i] < X[j]:
z = R0/np.tan(bound_angle) # distance from fulcrum to wake producing turbine
theta = np.arctan((Y[j] - Y[i]) / (X[j] - X[i] + z))
if -bound_angle < theta < bound_angle:
f_theta[i][j] = (1. + np.cos(q*theta))/2.
return f_theta
def rotate(self,rotation_method='RTZ'):
####################################################################################
#rotate-------------------------------------------------------------------------
for i in range(0,len(self.rf_st)):
self.rf_st[i].stats.back_azimuth = self.tr_e.stats.sac['baz']
self.rf_st.rotate(method='NE->RT')
if rotation_method == 'LQT':
r_amp = np.amax(np.amax(self.rf_st[1].data))
z_amp = np.amax(np.amax(self.rf_st[2].data))
incidence_angle = np.arctan(r_amp/z_amp) * (180.0/np.pi)
for i in range(0,len(self.rf_st)):
self.rf_st[i].stats.inclination = incidence_angle
self.rf_st.rotate(method='RT->NE')
self.rf_st.rotate(method='ZNE->LQT')
####################################################################################
def test_branch_cuts(self):
# check branch cuts and continuity on them
yield _check_branch_cut, np.log, -0.5, 1j, 1, -1, True
yield _check_branch_cut, np.log2, -0.5, 1j, 1, -1, True
yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1, True
yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1, True
yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1, True
yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, 1j], 1, -1, True
yield _check_branch_cut, np.arccos, [ -2, 2], [1j, 1j], 1, -1, True
yield _check_branch_cut, np.arctan, [0-2j, 2j], [1, 1], -1, 1, True
yield _check_branch_cut, np.arcsinh, [0-2j, 2j], [1, 1], -1, 1, True
yield _check_branch_cut, np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True
yield _check_branch_cut, np.arctanh, [ -2, 2], [1j, 1j], 1, -1, True
# check against bogus branch cuts: assert continuity between quadrants
yield _check_branch_cut, np.arcsin, [0-2j, 2j], [ 1, 1], 1, 1
yield _check_branch_cut, np.arccos, [0-2j, 2j], [ 1, 1], 1, 1
yield _check_branch_cut, np.arctan, [ -2, 2], [1j, 1j], 1, 1
yield _check_branch_cut, np.arcsinh, [ -2, 2, 0], [1j, 1j, 1], 1, 1
yield _check_branch_cut, np.arccosh, [0-2j, 2j, 2], [1, 1, 1j], 1, 1
yield _check_branch_cut, np.arctanh, [0-2j, 2j, 0], [1, 1, 1j], 1, 1
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 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 arrow(img,p1,p2):
cv2.line(s1,p1,p2,(100,255,100),thickness=2)
cv2.line(s2,p1,p2,(100,255,100),thickness=2)
dy,dx= np.array(p2)-np.array(p1)
theta= np.arctan(dy/dx) + (0 if dx>0 else np.pi) if dx!=0 else (1 if dy>0 else -1) * np.pi/2
phy1=theta+ np.pi*7/6
phy2=theta+ np.pi*5/6
R=0.4*np.linalg.norm([dx,dy])
dx1,dx2= (R*np.cos([phy1,phy2])).astype(np.int)
dy1,dy2= (R*np.sin([phy1,phy2])).astype(np.int)
if R<=2:return
Y1,X1=p1
Y2,X2=p2
cv2.line(s1,(dy1+Y2,dx1+X2),p2,(100,255,100),thickness=1)
cv2.line(s1,(dy2+Y2,dx2+X2),p2,(100,255,100),thickness=1)
cv2.line(s2,(dy1+Y2,dx1+X2),p2,(100,255,100),thickness=1)
cv2.line(s2,(dy2+Y2,dx2+X2),p2,(100,255,100),thickness=1)
#????????????????
def convertToOpenGLCameraMatrix(K, framebufferSize, near, far):
""" Convert a camera calibration matrix into OpenGL format. """
width, height = framebufferSize
# print 'framebufferSize:', framebufferSize
fx = K[0,0]
fy = K[1,1]
fovy = 2*np.arctan(0.5*height/fy)#*180/np.pi
aspect = (width*fy)/(height*fx)
# define the near and far clipping planes
# near = 0.1
# far = 100.0
# fx = 10.0
# fy = 10.0
# fovy = 90*(np.pi/180.0)
# aspect = (width*fy)/(height*fx)
proj = openGLPerspectiveMatrix(fovy,aspect,near,far)
return proj
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
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